6

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.

user3684221
  • 73
  • 1
  • 4

1 Answers1

6

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)
brechmos
  • 1,278
  • 1
  • 11
  • 22
  • I see what you mean. I think what I wanted is np.reshape(a,(3,3)). Does that make more sense? I think the filter sends a 1D array to the function so I wanted to convert it back to 2D. I guess it might not be important because np.sum will return the same value regardless...? – user3684221 Jun 26 '14 at 11:29
  • reshape does not work "in place" meaning you have to assign to change a variable. If you do `np.reshape(a, (3,3))` then it returns a 3x3 matrix but `a` is not changed. If you do `a = np.reshape(a, (3,3))` then the matrix `a` is changed to be a 3x3 matrix. But you are correct, I don't think it matters much to do all the reshaping. You should be able to just do `return sum( a*weights )`. – brechmos Jun 26 '14 at 13:53
  • Where does the r_ come from? – user3684221 Jun 30 '14 at 20:13