Skip to content Skip to sidebar Skip to footer

Is There A Python Equivalent Of Matlab's Conv2 Function?

Does Python or any of its modules have an equivalent of MATLAB's conv2 function? More specifically, I'm interested in something that does the same computation as conv2(A, B, 'same'

Solution 1:

While the other answers already mention scipy.signal.convolve2d as an equivalent, i found that the results do differ when using mode='same'.

While Matlab's conv2 results in artifacts on the bottom and right of an image, scipy.signal.convolve2d has the same artifacts on the top and left of an image.

See these links for plots showing the behaviour (not enough reputation to post the images directly):

Upper left corner of convoluted Barbara

Lower right corner of convoluted Barbara

The following wrapper might not be very efficient, but solved the problem in my case by rotating both input arrays and the output array, each by 180 degrees:

import numpy as np
from scipy.signal import convolve2d

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

Solution 2:

Looks like scipy.signal.convolve2d is what you're looking for.

Solution 3:

scipy.ndimage.convolve

does it in n dimensions.

Solution 4:

You must provide an offset for each non-singleton dimension to reproduce the results of Matlab's conv2. A simple implementation supporting the 'same' option, only, could be made like this

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

defconv2(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)
    """ifnot(mode == 'same'):
        raise Exception("Mode not supported")

    # Add singleton dimensionsif (len(x.shape) < len(y.shape)):
        dim = x.shape
        for i inrange(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 inrange(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 Matlabfor i inrange(len(x.shape)):
        if ( (x.shape[i] - y.shape[i]) % 2 == 0and
             x.shape[i] > 1and
             y.shape[i] > 1):
            origin = origin + (-1,)
        else:
            origin = origin + (0,)

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

    return z

Post a Comment for "Is There A Python Equivalent Of Matlab's Conv2 Function?"