Find the numerical coordinates of the array of the neighboring maximum

I used the accepted answer in this question to get local maxima in numpy 2 or more sizes so that I could label them. Now, I would also like to assign these labels to neighboring cells in the array, depending on the gradient - i.e. The cell receives the same label as the neighboring cell with the highest value. That way I can iteratively assign labels to my entire array.

Suppose I have an array Alike

>>> A = np.array([[ 1. ,  2. ,  2.2,  3.5],
                  [ 2.1,  2.4,  3. ,  3.3],
                  [ 1. ,  3. ,  3.2,  3. ],
                  [ 2. ,  4.1,  4. ,  2. ]])

By applying maximum_filter, I get

>>> scipy.ndimage.filters.maximum_filter(A, size=3)
array([[ 2.4,  3. ,  3.5,  3.5],
       [ 3. ,  3.2,  3.5,  3.5],
       [ 4.1,  4.1,  4.1,  4. ],
       [ 4.1,  4.1,  4.1,  4. ]])

Now, for each cell of this array, I would like to have the coordinates of the maximum found by the filter, i.e.

array([[[1,1],[1,2],[0,3],[0,3]],
       [[2,1],[2,2],[0,3],[0,3]],
       [[3,1],[3,1],[3,1],[3,2]],
       [[3,1],[3,1],[3,1],[3,2]]])

Then I used these coordinates to assign my labels iteratively.

,

highest_neighbor_coordinates = np.array([[(argmax2D(A[i-1:i+2, j-1:j+2])+np.array([i-1, j-1])) for j in range(1, A.shape[1]-1)] for i in range(1, A.shape[0]-1)])

scipy.ndimage , ( > 3 ).

+4
1

, scikit-image view_as_windows, argmax, , , -

from skimage.util import view_as_windows as viewW

def window_argmax_global2D(A, size):
    hsize = (size-1)//2 # expects size as odd number
    m,n = A.shape
    A1 = np.pad(A, (hsize,hsize), mode='reflect')
    idx = viewW(A1, (size,size)).reshape(-1,size**2).argmax(-1).reshape(m,n)

    r,c = np.unravel_index(idx, (size,size))
    rows = np.abs(r + np.arange(-hsize,m-hsize)[:,None])
    cols = np.abs(c + np.arange(-hsize,n-hsize))
    return rows, cols    

-

In [201]: A
Out[201]: 
array([[1. , 2. , 2.2, 3.5],
       [2.1, 2.4, 3. , 3.3],
       [1. , 3. , 3.2, 3. ],
       [2. , 4.1, 4. , 2. ]])

In [202]: rows, cols = window_argmax_global2D(A, size=3)

In [203]: rows
Out[203]: 
array([[1, 1, 0, 0],
       [2, 2, 0, 0],
       [3, 3, 3, 3],
       [3, 3, 3, 3]])

In [204]: cols
Out[204]: 
array([[1, 2, 3, 3],
       [1, 2, 3, 3],
       [1, 1, 1, 2],
       [1, 1, 1, 2]])

n-dim

np.ogrid :

def window_argmax_global(A, size):
    hsize = (size-1)//2 # expects size as odd number
    shp = A.shape
    N = A.ndim
    A1 = np.pad(A, (hsize,hsize), mode='reflect')
    idx = viewW(A1, ([size]*N)).reshape(-1,size**N).argmax(-1).reshape(shp)

    offsets = np.ogrid[tuple(map(slice, shp))]
    out = np.unravel_index(idx, ([size]*N))
    return [np.abs(i+j-hsize) for i,j in zip(out,offsets)]
+1

Source: https://habr.com/ru/post/1692386/


All Articles