0

I am trying to get the x and y coordinates of a given value in a numpy image array.

I can do it by running through the rows and columns manually with a for statement, but this seems rather slow and I am possitive there is a better way to do this.

I was trying to modify a solution I found in this post. Finding the (x,y) indexes of specific (R,G,B) color values from images stored in NumPy ndarrays

a = image
c = intensity_value

y_locs = np.where(np.all(a == c, axis=0))
x_locs = np.where(np.all(a == c, axis=1))

return np.int64(x_locs), np.int64(y_locs)

I have the np.int64 to convert the values back to int64.

I was also looking at numpy.where documentation

Community
  • 1
  • 1
Tim R
  • 514
  • 1
  • 8
  • 24

1 Answers1

1

I don't quite understand the problem. The axis parameter in all() runs over the colour channels (axis 2 or -1) rather than the x and y indices. Then where() will give you the coordinates of the matching values in the image:

>>> # set up data
>>> image = np.zeros((5, 4, 3), dtype=np.int)
>>> image[2, 1, :] = [7, 6, 5]
>>> # find indices
>>> np.where(np.all(image == [7, 6, 5], axis=-1))
(array([2]), array([1]))
>>>

This is really just repeating the answer you linked to. But is a bit too long for a comment. Maybe you could explain a bit more why you need to modify the previous answer? It doesn't seem like you do need to.

YXD
  • 31,741
  • 15
  • 75
  • 115
  • So I am trying to understand np.where. What I need to do is look in the rows and put all hits in an array for the rows, and then look in the columns and put in an array for the columns. – Tim R Apr 06 '15 at 13:34
  • `where` returns both the rows and the columns in one go. Have a read of the documentation http://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html – YXD Apr 06 '15 at 13:44