如何使用 SciPy Image 应用统一过滤器,其中边界外的数据不被统计?

dfr*_*h22 5 python image-processing scipy ndimage

我在这方面花了很多时间,并且我知道如何通过对边界行/列进行切片和索引来手动完成此操作,但 SciPy 必须有一种更简单的方法。

我需要将CVAL(当 时填充超出边缘的值mode=constant) 设置为 NaN,但是,这将返回 NaN。

我用代码和图来解释一下:

import numpy as np
from scipy import ndimage
m = np.reshape(np.arange(0,100),(10,10)).astype(np.float)
Run Code Online (Sandbox Code Playgroud)

输入数组的图片 使用 SciPy ndimage 均匀滤波器使用 3x3 内核计算平均值:

filter = ndimage.uniform_filter(m, size=3, mode='constant')
print(filter[1][1]) # equal to 11
print(filter[9][9]) # I need 93.5, however it gets 41.55 due to zeros
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,第一个值显示为 11,这符合预期,但是,对于边界上的任何单元格,它将用零填充值(我还尝试了所有其他模式)。

这是我需要实现的目标(左)与mode=constantCVAL=0(默认 0)

scipy avg 和我需要什么

Cri*_*ngo 4

一种简单的方法是使用归一化卷积

import numpy as np
from scipy import ndimage
m = np.reshape(np.arange(0,100),(10,10)).astype(np.float)

filter = ndimage.uniform_filter(m, size=3, mode='constant')    # normal filter result

weights = ndimage.uniform_filter(np.ones(m.shape), size=3, mode='constant')
filter = filter / weights    # normalized convolution result

print(filter[1][1]) # equal to 11
print(filter[9][9]) # equal to 93.49999999999994 -- rounding error! :)
Run Code Online (Sandbox Code Playgroud)

如果所有数据点均为 1 ( ),我们计算过滤器的结果weights。这显示了每个过滤器窗口中有多少个数据元素,并在除边界附近之外的所有位置返回值 1,在边界附近该值按比例减小。通过将过滤结果除以这些权重,我们将数据域之外的零考虑在内来校正平均值。