python - 具有多维(或非标量)输出的 Scipy 过滤器

标签 python image-processing numpy scipy ndimage

有没有类似ndimagegeneric_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/

相关文章:

Python PANDAS - 符号前的子字符串第一个 INT 或 FLOAT

python - 是否可以将 Django 的 SafeExceptionReporterFilter 与 AdminEmailHandler 以外的其他东西一起使用?

opencv - 如果图像已经不失真,如何仅从两个 CameraParams 获得 P(投影矩阵)?

image-processing - OpenCV 在同一窗口中相邻显示 2 个图像

python - 有没有一种快速的方法可以在 Python 中返回相同值的 Sin 和 Cos?

python - 如何在列表的一部分上找到 numpy.argmax() 并保存索引?

python - sqlalchemy 批量插入比构建原始 SQL 慢

python - 什么是 alpha 修剪均值滤波器?

python - 如何选择正确的颜色来使用 OpenCV 对图像进行阈值处理?

python - 如果 X 和 Y 匹配 NumPy 数组中的元素