具有多维(或非标量)输出的Scipy滤波器 [英] Scipy filter with multi-dimensional (or non-scalar) output

查看:303
本文介绍了具有多维(或非标量)输出的Scipy滤波器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有类似 ndimage 的过滤器 generic_filter ?我没有设法使 scipy.ndimage.filters.generic_filter 返回超过标量。取消注释下面代码中的行以获取错误: TypeError:只有length-1数组可以转换为Python标量

Is there a filter similar to ndimage's generic_filter that supports vector output? I did not manage to make scipy.ndimage.filters.generic_filter return more than a scalar. Uncomment the line in the code below to get the error: TypeError: only length-1 arrays can be converted to Python scalars.

我正在寻找一个处理2D或3D数组的通用过滤器,并在每个点返回一个向量。因此,输出将具有一个附加维度。对于下面的示例,我希望这样的事情:

I'm looking for a generic filter that process 2D or 3D arrays and returns a vector at each point. Thus the output would have one added dimension. For the example below I'd expect something like this:

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 作为额外参数。

The generic_filter expects myfunc to return a scalar, never a vector. However, there is nothing that precludes myfunc from also adding information to, say, a list which is passed to myfunc as an extra argument.

而不是使用 generic_filter返回的数组,我们可以通过重新整理这个列表来生成矢量值数组。

Instead of using the array returned by generic_filter, we can generate our vector-valued array by reshaping this list.

例如,

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,))

这篇关于具有多维(或非标量)输出的Scipy滤波器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆