gpt4 book ai didi

python - 如何应用 ndimage.generic_filter()

转载 作者:太空狗 更新时间:2023-10-30 02:48:07 27 4
gpt4 key购买 nike

我正在尝试学习 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

我预计传递给 test() 函数的 x 值是每个数组样本的那些 True footprint 相邻元素,因此在此示例中,形状为 (2, ), 但我遇到了上述错误。

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

最佳答案

传递给 ndimage.generic_filter 的函数必须将数组映射到标量。该数组将是一维的,并且包含来自 im 的值,这些值已被 footprint“选择”。

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

例如,

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

会起作用。

关于python - 如何应用 ndimage.generic_filter(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14059529/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com