Search code examples
python-2.7numpyscipyfilteringndimage

How do I use scipy.ndimage.filters.generic_filter?


I'm trying to use scipy.ndimage.filters.generic_filter to calculate a weighted sum from a neighborhood. The neighborhood will be variable at some point but for now 3x3 is what I'm working towards. So far this is where I am:

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)

I get an error from ndimage saying 'TypeError: a float is required' but I don't know what argument it's referring to and it looks basically the same as other examples I've seen.


Solution

  • This worked for me. There were a couple little problems with the code:

    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)
    

    You had a = np.reshape( (3,3) ) which isn't correct. Is that what you want?

    [update]

    To clean this up a little based on our discussion:

    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)