Python有没有类似于MATLAB conv2函数的等效函数?

11

Python或其任何模块是否有类似于MATLAB的conv2函数的等效函数?更具体地说,我对能够执行与MATLAB中conv2(A, B, 'same')相同计算的内容感兴趣。


@aaa carp - 没问题!无论如何还是谢谢。 - Ryan
此问题已有重复带答案的提问,请参见:https://dev59.com/GXE95IYBdhLWcg3wHqQV Guillaume Mougeot的回答是最快速的实现方法:https://dev59.com/GXE95IYBdhLWcg3wHqQV#64776128 - Mark Lakata
4个回答

11

虽然其他答案已经提到了scipy.signal.convolve2d作为等效方法,但我发现当使用mode='same'时结果确实不同。

虽然Matlab的conv2在图像底部和右侧会产生伪影,scipy.signal.convolve2d在图像顶部和左侧也会产生相同的伪影。

请参见这些链接以查看行为的细节(没有足够的声望直接发布图片):

Barbara的卷积上左角

Barbara的卷积下右角

以下包装器可能效率不是很高,但通过将输入数组和输出数组都旋转180度来解决我的问题:

import numpy as np
from scipy.signal import convolve2d

def conv2(x, y, mode='same'):
    return np.rot90(convolve2d(np.rot90(x, 2), np.rot90(y, 2), mode=mode), 2)

6

4
当使用“same”模式时,我认为它们实际上并不相同。SciPy与Matlab的中心方式不同。Matlab说:“如果行数或列数是奇数,则‘中心’在开头比结尾多留下一个。”而SciPy似乎则相反。 - endolith

1

为了重现Matlab的conv2结果,您必须为每个非单例维度提供一个偏移量。可以像这样制作仅支持“same”选项的简单实现:

import numpy as np
from scipy.ndimage.filters import convolve

def conv2(x,y,mode='same'):
    """
    Emulate the function conv2 from Mathworks.

    Usage:

    z = conv2(x,y,mode='same')

    TODO: 
     - Support other modes than 'same' (see conv2.m)
    """

    if not(mode == 'same'):
        raise Exception("Mode not supported")

    # Add singleton dimensions
    if (len(x.shape) < len(y.shape)):
        dim = x.shape
        for i in range(len(x.shape),len(y.shape)):
            dim = (1,) + dim
        x = x.reshape(dim)
    elif (len(y.shape) < len(x.shape)):
        dim = y.shape
        for i in range(len(y.shape),len(x.shape)):
            dim = (1,) + dim
        y = y.reshape(dim)

    origin = ()

    # Apparently, the origin must be set in a special way to reproduce
    # the results of scipy.signal.convolve and Matlab
    for i in range(len(x.shape)):
        if ( (x.shape[i] - y.shape[i]) % 2 == 0 and
             x.shape[i] > 1 and
             y.shape[i] > 1):
            origin = origin + (-1,)
        else:
            origin = origin + (0,)

    z = convolve(x,y, mode='constant', origin=origin)

    return z

1
scipy.ndimage.convolve

它是否在n维度中实现。


scipy.signal.convolve也是这样吗? - endolith

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接