Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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') in MATLAB.

like image 441
Ryan Avatar asked Sep 16 '10 21:09

Ryan


3 Answers

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

def conv2(x, y, mode='same'):
    return np.rot90(convolve2d(np.rot90(x, 2), np.rot90(y, 2), mode=mode), 2)
like image 171
jowlo Avatar answered Oct 16 '22 15:10

jowlo


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

like image 30
gnovice Avatar answered Oct 16 '22 15:10

gnovice


scipy.ndimage.convolve

does it in n dimensions.

like image 1
static_rtti Avatar answered Oct 16 '22 15:10

static_rtti