Python: faster local maximum in 2nd matrix
Given: R is an mxn float matrix
Output: O is an mxn matrix, where O [i, j] = R [i, j] if (i, j) is local max and O [i, j] = 0 otherwise. The local maximum is defined as the maximum element in a 3x3 block centered at i, j.
What's a faster way to accomplish this operation in python using numpy and scipy.
m,n = R.shape
for i in range(m):
for j in range(n):
R[i,j] *= (1 if R[min(0,i-1):max(m, i+2), min(0,j-1):max(n,j+2)].max() == R[i,j] else 0)
+3
source to share
1 answer
You can use scipy.ndimage.maximum_filter
:
In [28]: from scipy.ndimage import maximum_filter
Here's a sample R
:
In [29]: R
Out[29]:
array([[3, 3, 0, 0, 3],
[0, 0, 2, 1, 3],
[0, 1, 1, 1, 2],
[3, 2, 1, 2, 0],
[2, 2, 1, 2, 1]])
Get the most out of 3x3 windows:
In [30]: mx = maximum_filter(R, size=3)
In [31]: mx
Out[31]:
array([[3, 3, 3, 3, 3],
[3, 3, 3, 3, 3],
[3, 3, 2, 3, 3],
[3, 3, 2, 2, 2],
[3, 3, 2, 2, 2]])
Compare mx
with R
; this is a boolean matrix:
In [32]: mx == R
Out[32]:
array([[ True, True, False, False, True],
[False, False, False, False, True],
[False, False, False, False, False],
[ True, False, False, True, False],
[False, False, False, True, False]], dtype=bool)
Use np.where
to create O
:
In [33]: O = np.where(mx == R, R, 0)
In [34]: O
Out[34]:
array([[3, 3, 0, 0, 3],
[0, 0, 0, 0, 3],
[0, 0, 0, 0, 0],
[3, 0, 0, 2, 0],
[0, 0, 0, 2, 0]])
+9
source to share