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

前端 未结 1 1210
慢半拍i
慢半拍i 2020-12-19 04:47

I have an image stored in a numpy array, as yielded by imread():

>>> ndim
array([[[  0,   0,   0],
        [  4,   0,   0],
        [           


        
相关标签:
1条回答
  • 2020-12-19 05:27

    For some array colour array a and a colour tuple 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.

    If you need this as a list of coordinate tuples, use 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).

    0 讨论(0)
提交回复
热议问题