python:在二维矩阵中更快的局部最大值 [英] python: Faster local maximum in 2-d matrix
本文介绍了python:在二维矩阵中更快的局部最大值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给出:R是一个mxn浮点矩阵
Given: R is an mxn float matrix
输出:O是一个mxn矩阵,如果(i,j)是局部最大值,则O [i,j] = R [i,j],否则O [i,j] = 0.局部最大值定义为以i,j为中心的3x3块中的最大元素.
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 in a 3x3 block centered at i,j.
使用numpy和scipy在python上执行此操作的更快方法是什么.
What's a faster way to do this operation on 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)
推荐答案
You can use scipy.ndimage.maximum_filter
:
In [28]: from scipy.ndimage import maximum_filter
这是示例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]])
在3x3的窗口上获取最大值:
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]])
比较mx
与R
;这是一个布尔矩阵:
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)
使用 np.where
创建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]])
这篇关于python:在二维矩阵中更快的局部最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文