11

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

Samuel
  • 5,977
  • 14
  • 55
  • 77

4 Answers4

8

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.

buzjwa
  • 2,632
  • 2
  • 24
  • 37
KrnTneJa
  • 190
  • 2
  • 9
3

Using the functions scipy.ndimage.filters.correlate and scipy.ndimage.filters.convolve

Samuel
  • 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
1

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

Maxi
  • 421
  • 4
  • 4
0

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)

The original image was: enter image description here

With MATLAB's imfilter: enter image description here

With scipy.ndimage.convolve or scipy.ndimage.correlate: enter image description here

And with cv2.filter2D: enter image description here

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.

Facundo Farall
  • 500
  • 6
  • 18