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

1
  • So exactly whats your problem now? Commented Apr 4, 2015 at 21:17

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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.
where returns both the rows and the columns in one go. Have a read of the documentation docs.scipy.org/doc/numpy/reference/generated/numpy.where.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.