python矩阵中最大值及位置_Python:二维矩阵中的局部最大值更快

1586010002-jmsa.png

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 in a 3x3 block centered at i,j.

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)

解决方案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 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]])

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值