繁体   English   中英

从存储在NumPy ndarrays中的图像中查找特定(R,G,B)颜色值的(x,y)索引

[英]Finding the (x,y) indexes of specific (R,G,B) color values from images stored in NumPy ndarrays

我有一个图像存储在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)

我想有效地找到具有特定颜色值的像素的(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

...在这种情况下,我知道(200,200)处的像素具有RGB值(32,32,109)-我可以对此进行测试。

我想做的是查询ndarray的像素值并获取坐标。 在上述情况下,假定函数find_pixel(c)将返回(200,200)。

理想情况下,此find_pixel()函数将返回坐标元组的列表,而不仅仅是返回其找到的第一个值。

我看过numpy的“ fancy indexing”,这使我感到非常困惑。我为弄清楚这一点所做的大多数尝试都是过度紧张和不必要的巴洛克式。

我确信这里有一个非常简单的方法可以忽略。 做到这一点的最佳方法是什么?是否有一种完全比我概述的更好的机制来获得这些价值?

对于某些数组颜色数组a和颜色元组c

indices = numpy.where(numpy.all(a == c, axis=-1))

indices现在应该是一个2元组的数组,其中的第一个包含第一个维度的索引,而第二个包含第二个维度的索引,对应于c像素值。

如果需要将其作为坐标元组列表,请使用zip:

coords = zip(indices[0], indices[1])

例如:

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])

将输出:

1 3
2 2
3 1
(array([1, 2, 3]), array([3, 2, 1]))
[(1, 3), (2, 2), (3, 1)]

对应于所有值(4、4、4)的像素。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM