use*_*719 6 python numpy image-processing scipy ndimage
是否有类似于支持向量输出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)
Run Code Online (Sandbox Code Playgroud)
示例代码
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)
Run Code Online (Sandbox Code Playgroud)
在generic_filter预计myfunc到会返回一个标,从来没有一个载体.然而,没有什么可以阻止myfunc从还添加信息,比方说,这是传递给一个列表myfunc作为一个额外的参数.
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,))
Run Code Online (Sandbox Code Playgroud)