I know the equivalent functions of conv2
and corr2
of MATLAB are scipy.signal.correlate
and scipy.signal.convolve
. But the function imfilter
has the property of dealing with the outside the bounds of the array. Like as symmetric
, replicate
and circular
. Can Python do that things

- 5,977
- 14
- 55
- 77
4 Answers
Just to add some solid code, I wanted imfilter(A, B)
equivalent in python for simple 2-D image and filter (kernel). I found that following gives same result as MATLAB:
import scipy.ndimage
import numpy as np
scipy.ndimage.correlate(A, B, mode='constant').transpose()
For given question, this will work:
scipy.ndimage.correlate(A, B, mode='nearest').transpose()
Note that for some reason MATLAB returns transpose of the expected answer.
See documentation here for more options.
Edit 1:
There are more options given by MATLAB as documented here. Specifically, if we wish to use the 'conv'
option, we have MATLAB code (for example):
imfilter(x, f, 'replicate', 'conv')
This has python equivalence with:
scipy.ndimage.convolve(x, f, mode='nearest')
Note the 'replicate'
in MATLAB is same as 'nearest'
in SciPy in python.
Using the functions scipy.ndimage.filters.correlate
and scipy.ndimage.filters.convolve

- 5,977
- 14
- 55
- 77
-
Would it be possible for you to elaborate? I'm trying to replicate `profil2 = imfilter(profil,h,'replicate');` exactly. – Sam Aug 10 '16 at 20:46
I needed to replicate the exact same results for a Gaussian filter from Matlab in Python and came up with the following:
Matlab:
A = imfilter(A, fspecial('gaussian',12,3));
Python:
A = scipy.ndimage.correlate(A, matlab_style_gauss2D((12,12),3), mode='constant', origin=-1)
where matlab_style_gauss2D
can be taken from How to obtain a gaussian filter in python

- 421
- 4
- 4
-
For me I hat to set `origin` to zero to get the same results as Matlab's `imfilter` produces – Standard Dec 16 '22 at 09:56
The previous options didn't work the same way as MATLAB's imfilter
for me, instead I used cv2.filter2D
. The code would be:
import cv2
filtered_image = cv2.filter2D(image, -1, kernel)
With scipy.ndimage.convolve
or scipy.ndimage.correlate
:
Because of the way I saved the image from MATLAB and the one from cv2
, they don't look exactly the same here, but trust me, they are.

- 500
- 6
- 18