Finding coordinates in a picture

Posted on Sun 01 December 2013 in Notes

This is a very handy one liner I found in Programming Computer Vision, that can give you the coordinates of non-black pixels in an image.

In [25]: a = np.random.randint(10, size =(5,5))

In [26]: a[a>6] = 0

In [27]: a
Out[27]: 
array([[8, 0, 0, 0, 6],
       [0, 6, 8, 0, 0],
       [9, 0, 0, 6, 6],
       [0, 0, 0, 8, 0],
       [0, 0, 0, 0, 0]])

In [28]: coord = np.array(a.nonzero()).T

In [29]: coord
Out[29]: 
array([[0, 0],
       [0, 4],
       [1, 1],
       [1, 2],
       [2, 0],
       [2, 3],
       [2, 4],
       [3, 3]])

It's the np.array(a.nonzero()).T where the magic happens.