python - 带圆形窗口的局部最大值

标签 python numpy filtering

我正在尝试使用圆形内核计算矩阵上的局部最大值滤波器。 输出应该是局部最大值的单元格。对于输入“数据”中的每个像素,我需要通过圆形窗口查看它是否是局部最大值,从而返回值 1,否则返回 0。

我有这段代码,基于这里的答案: How to apply a disc shaped mask to a numpy array?

import numpy as np
import scipy.ndimage as sc

radius = 2
kernel = np.zeros((2*radius+1, 2*radius+1))
y,x = np.ogrid[-radius:radius+1, -radius:radius+1]
mask2 = x**2 + y**2 <= radius**2
kernel[mask2] = 1

def local_maxima(matrix, window_size):
    loc_max = sc.maximum_filter(matrix, window_size, mode='constant')
    return loc_max


data = np.array([(1, 1, 1, 1, 1, 1, 1, 1, 1), (1, 1, 1, 1, 1, 1, 1, 1, 1), (1, 1, 1, 1, 1, 1, 1, 1, 1),
                 (1, 1, 1, 1, 1, 1, 1, 1, 1), (1, 1, 1, 1, 4, 1, 1, 1, 1), (1, 1, 1, 1, 1, 1, 1, 1, 1),
                 (1, 1, 1, 1, 1, 1, 1, 1, 1), (1, 1, 1, 1, 1, 1, 1, 1, 1), (1, 1, 1, 1, 1, 1, 1, 1, 1),
                 (1, 1, 1, 1, 1, 1, 1, 1, 1)])

loc_max = sc.filters.generic_filter(data, local_maxima(data, np.shape(kernel)), footprint=kernel)
max_matrix = np.where(loc_max == data, 1, 0)
np.savetxt('.....\Local\Test_Local_Max.txt', max_matrix, delimiter='\t')

内核具有以下形状:

[[ 0.  0.  1.  0.  0.]
 [ 0.  1.  1.  1.  0.]
 [ 1.  1.  1.  1.  1.]
 [ 0.  1.  1.  1.  0.]
 [ 0.  0.  1.  0.  0.]]

因此,搜索单元格将仅是值为 1 的单元格。值为 0 的单元格应从局部最大值搜索中排除。

但是脚本在第 21 行给出了以下错误:

RuntimeError: function parameter is not callable

感谢您的帮助!

最佳答案

如果访问的单元格是由 kernel 定义的圆形窗口的局部最大值,则可以使用下面的代码返回 1 (我刚刚使用了 %pylab 绘制结果作为插图):

%pylab
import scipy.ndimage as sc
data = np.array([(1, 1, 1, 1, 1, 1, 1, 1, 1), (1, 1, 1, 1, 1, 1, 1, 1, 1), (1, 1, 1, 1, 1, 1, 1, 1, 1),
                 (1, 1, 1, 1, 1, 1, 1, 1, 1), (1, 1, 1, 1, 4, 1, 1, 1, 1), (1, 1, 1, 1, 1, 1, 1, 1, 1),
                 (1, 1, 1, 1, 1, 1, 1, 1, 1), (1, 1, 1, 1, 1, 1, 1, 1, 1), (1, 1, 1, 1, 1, 1, 1, 1, 1),
                 (1, 1, 1, 1, 1, 1, 1, 1, 1)])
matshow(data)
colorbar()

data

radius = 2
kernel = np.zeros((2*radius+1, 2*radius+1))
y,x = np.ogrid[-radius:radius+1, -radius:radius+1]
mask2 = x**2 + y**2 <= radius**2
kernel[mask2] = 1
matshow(kernel)
colorbar()

kernel

def filter_func(a):
    return a[len(a)/2] == a.max()
out = sc.generic_filter(data, filter_func, footprint=kernel)
matshow(out)
colorbar()

output

下面是随机输入数据数组的结果:

data = np.random.random(size=data.shape)
matshow(data)

random array

out = sc.generic_filter(data, filter_func, footprint=kernel)
matshow(out)
colorbar()

output on random array

关于python - 带圆形窗口的局部最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39272267/

相关文章:

python - 在 Apache Spark 上训练逻辑回归模型时出错。 SPARK-5063

python manage.py shell &lt;scripts/myscript.py 当文件包含 if __name__ == '__main__' 时不起作用

python - 如何在 python 中保存来自 selenium 和 opencv 的部分屏幕截图

python - 在python中将一个范围分割成n个大小相等的部分

awk - Grep 来自大文件的多个输入,但每个输入仅第一次出现

python - 通过在 Python 中切片列表来分配值的紧凑方法

python - 防止四舍五入到小数点后两位

python - 使用 atlas 和 openblas 对 numpy 进行基准测试时出现奇怪的结果

python带通滤波器-奇异矩阵误差

javascript - 过滤 Vuex 状态