[英]Finding the (x,y) indexes of specific (R,G,B) color values from images stored in NumPy ndarrays
I have an image stored in a numpy array, as yielded by imread()
: 我有一个图像存储在numpy数组中,由
imread()
产生:
>>> ndim
array([[[ 0, 0, 0],
[ 4, 0, 0],
[ 8, 0, 0],
...,
[247, 0, 28],
[251, 0, 28],
[255, 0, 28]],
[[ 0, 255, 227],
[ 4, 255, 227],
[ 8, 255, 227],
...,
[247, 255, 255],
[251, 255, 255],
[255, 255, 255]]], dtype=uint8)
>>> ndim.shape
(512, 512, 3)
I want to efficiently find the (x, y) coordinate (or coordinates) of pixels with a specific color value, eg 我想有效地找到具有特定颜色值的像素的(x,y)坐标,例如
>>> c
array([ 32, 32, 109], dtype=uint8)
>>> ndim[200,200]
array([ 32, 32, 109], dtype=uint8)
>>> ndim.T[0, 200, 200]
32
>>> ndim.T[1, 200, 200]
32
>>> ndim.T[2, 200, 200]
109
... in this case, I know the pixel at (200, 200) has the RGB value (32, 32, 109) -- I can test for this. ...在这种情况下,我知道(200,200)处的像素具有RGB值(32,32,109)-我可以对此进行测试。
What I want to do is query the ndarray for a pixel value and get back the coordinates. 我想做的是查询ndarray的像素值并获取坐标。 In the above case, the putative function
find_pixel(c)
would return (200, 200). 在上述情况下,假定函数
find_pixel(c)
将返回(200,200)。
Ideally this find_pixel()
function would return a list of coordinate tuples and not just the first value it finds. 理想情况下,此
find_pixel()
函数将返回坐标元组的列表,而不仅仅是返回其找到的第一个值。
I've looked at numpy's "fancy indexing", which confused me greatly... Most of my attempts at figuring this out have been overwrought and unnecessarily baroque. 我看过numpy的“ fancy indexing”,这使我感到非常困惑。我为弄清楚这一点所做的大多数尝试都是过度紧张和不必要的巴洛克式。
I am sure there is a very simple method that I am overlooking here. 我确信这里有一个非常简单的方法可以忽略。 What is the best way to do this -- is there an altogether better mechanism to get these values than that which I have outlined?
做到这一点的最佳方法是什么?是否有一种完全比我概述的更好的机制来获得这些价值?
For some array colour array a
and a colour tuple c
: 对于某些数组颜色数组
a
和颜色元组c
:
indices = numpy.where(numpy.all(a == c, axis=-1))
indices
should now be a 2-tuple of arrays, the first of which contains the indices in the first dimensions and the second of which contains the indices in the second dimension corresponding to pixel values of c
. indices
现在应该是一个2元组的数组,其中的第一个包含第一个维度的索引,而第二个包含第二个维度的索引,对应于c
像素值。
If you need this as a list of coordinate tuples, use zip: 如果需要将其作为坐标元组列表,请使用zip:
coords = zip(indices[0], indices[1])
For example: 例如:
import numpy
a = numpy.zeros((4, 4, 3), 'int')
for n in range(4):
for m in range(4):
a[n, m, :] = n + m
if (n + m) == 4:
print n, m
c = (4, 4, 4)
indices = numpy.where(numpy.all(a == c, axis=-1))
print indices
print zip(indices[0], indices[1])
will output: 将输出:
1 3
2 2
3 1
(array([1, 2, 3]), array([3, 2, 1]))
[(1, 3), (2, 2), (3, 1)]
which corresponds to all the pixels of value (4, 4, 4). 对应于所有值(4、4、4)的像素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.