I have a 2d Numpy array like:
array([[0.87, 0.13, 0.18, 0.04, 0.79],
[0.07, 0.58, 0.84, 0.82, 0.76],
[0.12, 0.77, 0.68, 0.58, 0.8 ],
[0.43, 0.2 , 0.57, 0.91, 0.01],
[0.43, 0.74, 0.56, 0.11, 0.58]])
I'd like to test each number to evaluate if it is the local minima within a window of x*y, for example, a 3x3 window would return this
array([[False, False, False, True, False],
[ True, False, False, False, False],
[False, False, False, False, False],
[False, False, False, False, True],
[False, False, False, False, False]])
I want to avoid using a native python loop, since my array is quite large
CodePudding user response:
You can use scipy.ndimage.minimum_filter
to compute the 2D minima, then perform a comparison to the original:
from scipy.ndimage import minimum_filter
mins = minimum_filter(a, mode='constant', size=(3,3), cval=np.inf)
a==mins # or np.isclose(a, mins)
output:
array([[False, False, False, True, False],
[ True, False, False, False, False],
[False, False, False, False, False],
[False, False, False, False, True],
[False, False, False, False, False]])
intermediate mins
:
array([[0.07, 0.07, 0.04, 0.04, 0.04],
[0.07, 0.07, 0.04, 0.04, 0.04],
[0.07, 0.07, 0.2 , 0.01, 0.01],
[0.12, 0.12, 0.11, 0.01, 0.01],
[0.2 , 0.2 , 0.11, 0.01, 0.01]])