Is there a Python equivalent of MATLAB's conv2 function?
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)
Looks like scipy.signal.convolve2d is what you're looking for.