【问题标题】:python: Faster local maximum in 2-d matrixpython:二维矩阵中更快的局部最大值
【发布时间】:2014-10-10 23:56:51
【问题描述】:

给定:R 是一个 mxn 浮点矩阵

输出:O 是一个 mxn 矩阵,其中 O[i,j] = R[i,j] 如果 (i,j) 是局部最大值,否则 O[i,j] = 0。局部最大值定义为以 i,j 为中心的 3x3 块中的最大元素。

使用 numpy 和 scipy 在 python 上执行此操作的更快方法是什么。

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)

【问题讨论】:

    标签: python numpy matrix scipy


    【解决方案1】:

    你可以使用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 窗口上获得最大值:

    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 进行比较;这是一个布尔矩阵:

    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]])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-03-18
      • 2010-12-30
      • 2018-12-17
      • 1970-01-01
      • 2020-09-12
      • 2018-03-21
      • 2015-05-23
      相关资源
      最近更新 更多