如何使用SciPy图像应用统一的过滤器,而不计算边界外的数据? [英] How to apply a uniform filter using SciPy Image where the data outside the boundary is not tallied?

查看:61
本文介绍了如何使用SciPy图像应用统一的过滤器,而不计算边界外的数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经花了很多时间,而且我知道如何通过对边界行/列进行切片和索引来手动进行此操作,但是SciPy必须有一种更简单的方法.

I have spent lots of time on this, and I know how to manually do it by slicing and indexing the boundary rows/cols, but there has to be a simpler way with SciPy.

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

I need to set the CVAL (values to fill past the edges when mode=constant) to NaN, however, this will return NaN.

我将用代码和数字对其进行解释:

I will explain it with code and figures:

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

使用SciPy ndimage均匀滤波器,使用3x3内核计算均值:

Use SciPy ndimage uniform filter to calculate the mean using a 3x3 kernel:

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

如您所见,第一个值显示为11,这与预期的一样,但是,对于边界上的任何单元格,它将用零填充值(我也尝试了所有其他模式).

As you can see, the first value comes out as 11, which is as expected, however, for any cell along the border, it will fill the values with zero (I have also tried all the other modes).

这是我需要实现的(左)与 mode = constant CVAL = 0 (默认为0)

Here is what I need to achieve (left) vs mode=constant and CVAL=0 (default 0)

推荐答案

一种简单的方法是使用

One simple approach is to use Normalized Convolution:

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! :)

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

We computed the result of the filter if all data points were 1 (weights). This shows how many data elements there are in each filter window, and returns a value of 1 everywhere except near the boundary, where this value decreases proportionally. By dividing the filtering result with these weights, we correct for the averaging taking zeros into account that were outside the data domain.

这篇关于如何使用SciPy图像应用统一的过滤器,而不计算边界外的数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆