Home > Software engineering >  How to get matrix position of the max element in sliding window view of an array?
How to get matrix position of the max element in sliding window view of an array?

Time:06-24

I have successfully found the maximum of the array in each sliding window view using amax and sliding_window_view functions from NumPy as follows:

import numpy as np


a = np.random.randint(0, 100, (5, 6))  # 2D array

array([[51, 92, 14, 71, 60, 20],
       [82, 86, 74, 74, 87, 99],
       [23,  2, 21, 52,  1, 87],
       [29, 37,  1, 63, 59, 20],
       [32, 75, 57, 21, 88, 48]])

windows = np.lib.stride_tricks.sliding_window_view(a, (3, 3))
np.amax(windows, axis=(2, 3))

array([[92, 92, 87, 99],
       [86, 86, 87, 99],
       [75, 75, 88, 88]])

Now, I'm trying to find the position of the max values in the original array considering the windows.

Expected Output

The first element i.e. `92` should give position `(1, 0)`.
The second element i.e. `92` should give position `(1, 0)`.
The third element i.e. `87` should give position `(4, 1)`.
.
.
so on

NOTE: Only one position per value is needed. Hence, if there are multiple positions inside a window, return only the first.

CodePudding user response:

An easy solution could be:

maxvals = np.amax(windows, axis=(2, 3))

np.isin(a, maxvals).nonzero()

which gives you back one array for each axis. You'll need to slightly massage the output to get the indices in tuple form. Something like this:

[f'{a[ind]} at {ind}' for ind in zip(*indx)]

If a value occurs multiple times, all the positions are returned. You can choose to keep only the first if you want.

CodePudding user response:

Without loops, it could be achieved with use of another SO post:

unique_values, index = np.unique(a, return_index=True)
result = index[np.searchsorted(unique_values, np.amax(windows, axis=(2, 3)))]
ind = np.dstack((result // a.shape[1], result % a.shape[1]))
  • Related