5

I'm trying to learn ndimage and I can't figure how generic_filter() function works. Documentation mentions that user function is to be applied to user defined footprint, but somehow I can't make it. Here is example:

>>> import numpy as np
>>> from scipy import ndimage
>>> im = np.ones((20, 20)) * np.arange(20)
>>> footprint = np.array([[0,0,1],
...                       [0,0,0],
...                       [1,0,0]])
... 
>>> def test(x):
...     return x * 0.5
... 
>>> res = ndimage.generic_filter(im, test, footprint=footprint)
Traceback (most recent call last):
  File "<Engine input>", line 1, in <module>
  File "C:\Python27\lib\site-packages\scipy\ndimage\filters.py", line 1142, in generic_filter
    cval, origins, extra_arguments, extra_keywords)
TypeError: only length-1 arrays can be converted to Python scalars

I expected that x value passed to test() function, are those True footprint neighboring elements for each array sample, so in this example arrays with shape (2,), but I get above error.

What am I doing wrong?
How can I tell generic filter to apply simple value calculation on specified neighboring points?

theta
  • 24,593
  • 37
  • 119
  • 159

1 Answers1

8

The function passed to ndimage.generic_filter must map an array to a scalar. The array will be 1-dimensional, and contain the values from im which have been "selected" by the footprint.

For each location in res, the value returned by the function is the value assigned to that location. That's why, naturally, the function needs to return a scalar.

So, for example,

def test(x):
    return (x*0.5).sum()

would work.

unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677