是否有Python等效的MATLAB的conv2函数?

时间:2010-09-16 21:49:10

标签: python matlab matrix convolution

Python或其任何模块是否具有MATLAB conv2函数的等价物?更具体地说,我对在MATLAB中执行与conv2(A, B, 'same')相同的计算感兴趣。

4 个答案:

答案 0 :(得分:4)

看起来scipy.signal.convolve2d就是你要找的。

答案 1 :(得分:3)

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

虽然Matlab的conv2导致图像底部和右侧出现伪影,但scipy.signal.convolve2d在图像的顶部和左侧具有相同的瑕疵。

请参阅这些链接以查看显示行为的图表(没有足够的声誉直接发布图片):

Upper left corner of convoluted Barbara

Lower right corner of convoluted 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)

答案 2 :(得分:1)

scipy.ndimage.convolve

是否为n维。

答案 3 :(得分:1)

您必须为每个非单一维度提供偏移量,以重现Matlab的conv2的结果。只支持“相同”选项的简单实现可以像这样做

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