问题描述
我正在尝试学习 ndimage,但我不知道如何generic_filter() 函数有效.文档提到用户功能将应用于用户定义的足迹,但不知何故我无法做到.示例如下:
>>>将 numpy 导入为 np>>>从 scipy 导入 ndimage>>>im = np.ones((20, 20)) * np.arange(20)>>>足迹 = np.array([[0,0,1],... [0,0,0],... [1,0,0]])...>>>定义测试(x):...返回 x * 0.5...>>>res = ndimage.generic_filter(im, test,footprint=footprint)回溯(最近一次调用最后一次):文件<Engine input>",第 1 行,在 <module> 中文件C:\Python27\lib\site-packages\scipy\ndimage\filters.py",第 1142 行,在 generic_filter 中cval、起源、extra_arguments、extra_keywords)类型错误:只有长度为 1 的数组可以转换为 Python 标量我期望传递给 test()
函数的 x
值是每个数组样本的真实足迹相邻元素,因此在此示例中,数组的形状为 (2,),但出现上述错误.
我做错了什么?
如何告诉通用过滤器在指定的相邻点上应用简单的值计算?
传递给 ndimage.generic_filter
的函数必须将数组映射到标量.该数组将是一维的,并包含 im
中已被 footprint
选择"的值.
对于res
中的每个位置,函数返回的值是分配给该位置的值.这就是函数自然需要返回标量的原因.
例如,
def test(x):返回 (x*0.5).sum()
会起作用.
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?
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.
这篇关于如何应用 ndimage.generic_filter()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!