Skip to main content
 首页 » 编程设计

python之查找二维数组中四个邻居的最大值

2024年09月07日25lvdongjie

我想找到 2D numpy 数组中项目的四个邻居的最大值。我想到的第一个解决方案是使用 scipy.ndimage.generic_filter:

import numpy as np 
import scipy.ndimage 
 
a = np.random.uniform(low=10, high=100, size=(6500,6500)).astype(np.float) 
 
def filter2d(footprint_elements): 
    return max(footprint_elements) 
 
footprint = np.array([[0, 1, 0], 
                       [1, 0, 1], 
                       [0, 1, 0]]) 
 
maxs = scipy.ndimage.generic_filter(a,filter2d, footprint=footprint) 

这里使用通用过滤器的问题是它很慢,所以我想出了一个更快的解决方案(请注意边缘并不重要):

maxs = np.maximum.reduce([a[:-2, 1:-1], a[1:-1, 2:], a[2:, 1:-1], a[1:-1,:-2]]) 

我正在寻找任何可能更快的方法。

我不确定考虑这是否会提高速度,但我只对特定项目感兴趣(由另一个数组确定)。例如,找到数组 a 中那些项目的最大邻居,其中数组 b 大于 0:

b = np.random.uniform(low=-10, high=10, size=(6500,6500)).astype(np.float) 
 
# need to find maximum neighbour of array a where b > 0 
 
 maxs[b > 0] 

请您参考如下方法:

代替 scipy.ndimage.generic_filter,您可以使用 scipy.ndimage.maximum_filter .它还接受一个 footprint 参数:

from scipy.ndimage import maximum_filter 
 
maxs = maximum_filter(a, footprint=footprint) 

时间:

In [105]: a = np.random.uniform(low=10, high=100, size=(6500,6500)) 
 
In [106]: %timeit maxs = maximum_filter(a, footprint=footprint) 
858 ms ± 2.13 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) 
 
In [107]: %timeit maxs = np.maximum.reduce([a[:-2, 1:-1], a[1:-1, 2:], a[2:, 1:-1], a[1:-1,:-2]]) 
1.34 s ± 12.7 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) 

所以 maximum_filter 比使用应用于切片的 np.maximum.reduce 快一点。