使用scipy应用矩形阶梯函数

时间:2017-01-19 00:30:09

标签: python scipy

scipy中是否有矩形滤镜?我想复制@Mike T&#39的解决方案https://gis.stackexchange.com/questions/9431/what-raster-smoothing-generalization-tools-are-available/162852,但不管高斯模糊,我想应用矩形滤波器(即基本上是阶梯函数)

1 个答案:

答案 0 :(得分:1)

您只需使用scipy.ndimage.convolve并自行定义weights(过滤器​​)即可。还有一个专门的,优化的矩形滤波器功能:uniform_filter

例如,要应用宽度3均值过滤器(如果需要和过滤器,则乘以ndim*size):

>>> from scipy.ndimage import uniform_filter
>>> uniform_filter([1,4,2,56,2,3,6,1,3,1,3], size=3)
array([ 2,  2, 20, 19, 20,  3,  3,  3,  1,  2,  2])

这也可以应用于多维数组:

>>> uniform_filter(np.random.randint(0, 20, (10, 10)), size=3)  # 3x3 filter
array([[ 6,  7, 10,  9,  9,  7,  5,  7,  9, 12],
       [ 6,  7,  9,  9,  7,  6,  5,  5,  7,  9],
       [ 5,  8,  8,  9,  7,  6,  4,  4,  6,  8],
       [ 9, 10,  9, 10,  8,  6,  4,  4,  8, 11],
       [10, 12,  9, 10,  9, 10,  8,  8,  9, 10],
       [12, 12,  9, 10, 10, 10,  9,  9,  9,  9],
       [12, 11,  9,  8,  7,  8,  7,  8,  6,  5],
       [11, 10,  9,  9,  9,  9,  6,  8,  8,  9],
       [12,  9,  7,  7,  9,  8,  6,  6,  6,  8],
       [12,  9,  8,  9, 12, 10,  7,  5,  6,  9]])
>>> uniform_filter(np.random.randint(0, 20, (10, 10)), size=(5, 3))  # 5x3 filter
array([[ 7,  7,  8, 10, 11, 10, 11, 11, 12, 12],
       [ 7,  7,  7,  9, 10, 11, 11, 10,  9,  9],
       [ 7,  6,  6,  8,  8,  9,  9,  9,  8,  8],
       [ 6,  6,  6,  8,  8,  9,  8,  7,  7,  8],
       [ 8,  8,  7,  9,  8, 11,  8,  8,  6,  6],
       [ 7,  8,  7,  9,  8, 11,  7,  7,  5,  7],
       [ 9,  8,  8,  9,  9,  9,  7,  7,  7,  8],
       [ 8,  8,  8,  9, 10, 10,  8,  7,  6,  6],
       [ 9,  7,  6,  8,  9, 10,  8,  7,  6,  6],
       [ 9,  6,  6,  7, 10,  8,  8,  6,  6,  6]])