我如何使用scipy.ndimage.filters.gereric_filter?

时间:2014-06-25 16:18:10

标签: python-2.7 numpy scipy filtering ndimage

我试图使用scipy.ndimage.filters.generic_filter来计算邻域的加权和。这个社区在某些时候会变化,但现在3x3是我正在努力的方向。 到目前为止,这就是我所在的地方:

    def Func(a):
         a = np.reshape((3,3))
         weights = np.array([[0.5,.05,0.5],[0.5,1,0.5],[0.5,0.5,0.5]])
         a = np.multiply(a,weights)
         a = np.sum(a)
         return a

ndimage.filters.generic_filter(Array,Func,footprint=np.ones((3,3)),mode='constant',cval=0.0,origin=0.0)

我从ndimage那里得到一个错误,说' TypeError:需要浮点数'但我不知道它所指的是什么论点,它看起来与我见过的其他例子基本相同。

1 个答案:

答案 0 :(得分:4)

这对我有用。代码有几个小问题:

import scipy.ndimage.filters
import numpy as np

Array = rand( 100,100 )

def Func(a):
    a = a.reshape((3,3))
    weights = np.array([[0.5,.05,0.5],[0.5,1,0.5],[0.5,0.5,0.5]])
    a = np.multiply(a,weights)
    a = np.sum(a)
    return a

out = scipy.ndimage.filters.generic_filter(Array,Func,footprint=np.ones((3,3)),mode='constant',cval=0.0,origin=0.0)

你有a = np.reshape( (3,3) )这是不正确的。这就是你想要的吗?

[更新]

根据我们的讨论稍微清理一下:

import scipy.ndimage.filters
import numpy as np

Array = rand( 100,100 )

def Func(a):
    return np.sum( a * r_[0.5,.05,0.5, 0.5,1,0.5, 0.5,0.5,0.5] )

out = scipy.ndimage.filters.generic_filter(Array,Func,footprint=np.ones((3,3)),mode='constant',cval=0.0,origin=0.0)