Is there a Python equivalent of conv2 MATLAB?

Does Python or any of its modules have an equivalent MATLAB conv2 function ? In particular, I'm interested in what does the same calculation as conv2(A, B, 'same')in MATLAB.

+5
source share
4 answers

Looks like scipy.signal.convolve2d is what you are looking for.

+4
source

While other answers are already mentioned scipy.signal.convolve2das equivalent, I found that the results are different when used mode='same'.

Matlab conv2 , scipy.signal.convolve2d .

. , ( ):

, , , , 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
scipy.ndimage.convolve

n .

+1

, singleton, 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
+1

All Articles