我确信这个问题可以通过谷歌搜索得到答案,但是我不知道要用什么关键词。我对一个具体的案例很感兴趣,同时也想了解一般情况下如何做。假设我有一张RGB图像,它被表示为一个形状为(宽度,高度,3)
的数组,我想找到所有红色通道大于100的像素。我觉得image > [100, 0, 0]
应该给我一个索引数组(如果我比较一个标量并使用灰度图像,则会给出结果),但是这会将每个元素与列表进行比较。我该如何在前两个维度上进行比较,其中每个“元素”都是最后一个维度?
我确信这个问题可以通过谷歌搜索得到答案,但是我不知道要用什么关键词。我对一个具体的案例很感兴趣,同时也想了解一般情况下如何做。假设我有一张RGB图像,它被表示为一个形状为(宽度,高度,3)
的数组,我想找到所有红色通道大于100的像素。我觉得image > [100, 0, 0]
应该给我一个索引数组(如果我比较一个标量并使用灰度图像,则会给出结果),但是这会将每个元素与列表进行比较。我该如何在前两个维度上进行比较,其中每个“元素”都是最后一个维度?
np.argwhere(image[:,:,0] > threshold)
解释:
red-channel
与threshold
进行比较,得到一个布尔数组,形状与输入图像相同,但没有第三个轴(颜色通道)。np.argwhere
获取成功匹配的索引。如果想要查看任何通道是否高于某个阈值,请使用.any(-1)
(沿着最后一个轴/颜色通道满足条件的任何元素)。
np.argwhere((image > threshold).any(-1))
样例运行
输入图像:
In [76]: image
Out[76]:
array([[[118, 94, 109],
[ 36, 122, 6],
[ 85, 91, 58],
[ 30, 2, 23]],
[[ 32, 47, 50],
[ 1, 105, 141],
[ 91, 120, 58],
[129, 127, 111]]], dtype=uint8)
In [77]: threshold
Out[77]: 100
案例 #1:仅红色通道
In [69]: np.argwhere(image[:,:,0] > threshold)
Out[69]:
array([[0, 0],
[1, 3]])
In [70]: image[0,0]
Out[70]: array([118, 94, 109], dtype=uint8)
In [71]: image[1,3]
Out[71]: array([129, 127, 111], dtype=uint8)
案例 #2:任意通道
In [72]: np.argwhere((image > threshold).any(-1))
Out[72]:
array([[0, 0],
[0, 1],
[1, 1],
[1, 2],
[1, 3]])
In [73]: image[0,1]
Out[73]: array([ 36, 122, 6], dtype=uint8)
In [74]: image[1,1]
Out[74]: array([ 1, 105, 141], dtype=uint8)
In [75]: image[1,2]
Out[75]: array([ 91, 120, 58], dtype=uint8)
np.einsum
提供比np.any
更快的替代方案np.einsum
可以被“欺骗”以执行np.any
的工作,结果稍微快一点。
因此,boolean_arr.any(-1)
等同于np.einsum('ijk->ij',boolean_arr)
。
以下是各种数据大小的相关运行时间 -
In [105]: image = np.random.randint(0,255,(30,30,3)).astype('uint8')
...: %timeit np.argwhere((image > threshold).any(-1))
...: %timeit np.argwhere(np.einsum('ijk->ij',image>threshold))
...: out1 = np.argwhere((image > threshold).any(-1))
...: out2 = np.argwhere(np.einsum('ijk->ij',image>threshold))
...: print np.allclose(out1,out2)
...:
10000 loops, best of 3: 79.2 µs per loop
10000 loops, best of 3: 56.5 µs per loop
True
In [106]: image = np.random.randint(0,255,(300,300,3)).astype('uint8')
...: %timeit np.argwhere((image > threshold).any(-1))
...: %timeit np.argwhere(np.einsum('ijk->ij',image>threshold))
...: out1 = np.argwhere((image > threshold).any(-1))
...: out2 = np.argwhere(np.einsum('ijk->ij',image>threshold))
...: print np.allclose(out1,out2)
...:
100 loops, best of 3: 5.47 ms per loop
100 loops, best of 3: 3.69 ms per loop
True
In [107]: image = np.random.randint(0,255,(3000,3000,3)).astype('uint8')
...: %timeit np.argwhere((image > threshold).any(-1))
...: %timeit np.argwhere(np.einsum('ijk->ij',image>threshold))
...: out1 = np.argwhere((image > threshold).any(-1))
...: out2 = np.argwhere(np.einsum('ijk->ij',image>threshold))
...: print np.allclose(out1,out2)
...:
1 loops, best of 3: 833 ms per loop
1 loops, best of 3: 640 ms per loop
True