0

Let's say I have a 2D array with a size of m x n elements. Now, I want to get the indices of all maximums. So the result should be something like: [(m1, n1), (m2, n2)] where m and n indicate the x and y coordinates of my maximums.

With only one maximum its quite easy, but with more, I'm getting stuck.

import numpy as np

pixel = np.array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                  [0, 189, 12, 0, 0, 1, 0, 0, 0, 0],
                  [0, 6, 0, 0, 0, 0, 0, 0, 0, 0],
                  [0, 0, 0, 1, 0, 0, 0, 203, 9, 0],
                  [0, 0, 0, 0, 0, 0, 0, 12, 0, 0],
                  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                  [0, 0, 5, 245, 0, 0, 0, 7, 4, 0],
                  [0, 0, 0, 0, 0, 0, 0, 250, 8, 0],
                  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]])
result = np.where(pixel == pixel.max())

print("cross detection at y:", result[0][0], "x:", result[1][0])

print(pixel)

Does somebody have an idea? It would be great, thanks!

4
  • can you please define what are those maximums ?. Commented Jan 19, 2020 at 11:02
  • 1
    Does this answer your question? How to make numpy.argmax return all occurrences of the maximum? Commented Jan 19, 2020 at 11:03
  • 1
    Your question is not clear. Commented Jan 19, 2020 at 12:23
  • 2nd try: basically I have an image which contains some blurred spots and I want to detect the pixel, where these spots are. For example, I have 4 spots, than I expect a list with 4 x,y coordinates. Because of the imaging structure, I know that two points cannot be closer than 20 pixels. Maybe now it gets clearer.. Commented Jan 19, 2020 at 20:54

2 Answers 2

2

Try this:

x,y = np.where(pixel == np.max(pixel))

this will return x axis and y axis of all the elements with maximum values Now,for your question you can do

np.array((x,y)).T 

for this last code I look up to this question

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

3 Comments

Can you add an explanation to explain what this does?
@squareskittles this will return an array of the all the x-axis and an array of all the y-axis of the element having maximum values.
Please edit your answer to include this explanation.
-1

Try numpy.argmax, it returns the indices of the maximum values along an axis.

1 Comment

...and as written in the link you provide "In case of multiple occurrences of the maximum values, the indices corresponding to the first occurrence are returned.". So, a unique maximum per axis

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.