如何应用ndimage.generic_filter()

the*_*eta 4 python scipy

我正在尝试学习ndimage,我不知道generic_filter()函数的工作方式。文档中提到用户功能将应用于用户定义的占用空间,但是我无法做到。这是示例:

>>> 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
Run Code Online (Sandbox Code Playgroud)

我希望x传递给test()函数的值是每个数组样本的True True相邻元素,因此在本示例中,形状为(2,)的数组,但我得到的错误超过了。

我究竟做错了什么?
如何告诉通用过滤器对指定的相邻点应用简单值计算?

unu*_*tbu 6

传递给的函数ndimage.generic_filter必须将数组映射到标量。该数组将是一维的,并包含im已由进行“选择”的值footprint

对于中的每个位置res,函数返回的值是分配给该位置的值。这就是为什么函数自然需要返回标量的原因。

因此,例如

def test(x):
    return (x*0.5).sum()
Run Code Online (Sandbox Code Playgroud)

会工作。