我确定这个问题可以在Google上查询,但我不知道要使用哪些关键字。我对一个特定的案例很好奇,但是对于一般情况下该怎么做呢。可以说我有一个RGB图像作为形状数组,(width, height, 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.any
in的更快np.einsum
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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句