Python: Faster Local Maximum In 2-d 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 a local max and O[i,j] = 0 otherwise. Local maximum is defined as the maximum element i
Solution 1:
You can use scipy.ndimage.maximum_filter
:
In [28]: from scipy.ndimageimport 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 maximum on 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
to 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]])
Post a Comment for "Python: Faster Local Maximum In 2-d Matrix"