有没有类似ndimage
的generic_filter的滤镜支持矢量输出?我没能使 scipy.ndimage.filters.generic_filter
返回的不仅仅是一个标量。取消注释下面代码中的行以获取错误:TypeError: only length-1 arrays can be converted to Python scalars
。
我正在寻找一个处理 2D 或 3D 数组并在每个点返回一个向量的通用过滤器。因此,输出将增加一个维度。对于下面的示例,我希望是这样的:
m.shape # (10,10)
res.shape # (10,10,2)
示例代码
import numpy as np
from scipy import ndimage
a = np.ones((10, 10)) * np.arange(10)
footprint = np.array([[1,1,1],
[1,0,1],
[1,1,1]])
def myfunc(x):
r = sum(x)
#r = np.array([1,1]) # uncomment this
return r
res = ndimage.generic_filter(a, myfunc, footprint=footprint)
最佳答案
generic_filter
期望 myfunc
返回标量,而不是向量。
但是,没有什么可以阻止myfunc
也添加信息
比如说,作为额外参数传递给 myfunc
的列表。
我们可以通过 reshape 此列表来生成向量值数组,而不是使用 generic_filter
返回的数组。
例如,
import numpy as np
from scipy import ndimage
a = np.ones((10, 10)) * np.arange(10)
footprint = np.array([[1,1,1],
[1,0,1],
[1,1,1]])
ndim = 2
def myfunc(x, out):
r = np.arange(ndim, dtype='float64')
out.extend(r)
return 0
result = []
ndimage.generic_filter(
a, myfunc, footprint=footprint, extra_arguments=(result,))
result = np.array(result).reshape(a.shape+(ndim,))
关于python - 具有多维(或非标量)输出的 Scipy 过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28774642/