2

I want to know what will be the equivalent of Matlab's filter2(filter, image, 'valid') function in python OpenCV or scikit-image library. I am mainly concerned with the valid argument which allows to calculate the convolution of filter and image without zero padding the image. I am aware of the fact that similar question is posted on this forum but the equivalent of filter2 function with valid argument has not been described properly.

Community
  • 1
  • 1
sv_jan5
  • 1,543
  • 16
  • 42

2 Answers2

4

The documentation for filter2 says that filter2(H, X, shape) is equivalent to conv2(X,rot90(H,2),shape);

A python equivalent to conv2 is signal.convolve2d. So the equivalent you're looking for is:

signal.convolve2d(X, np.rot90(H), mode='valid')
Community
  • 1
  • 1
Matthew Pope
  • 7,212
  • 1
  • 28
  • 49
3

In matlab

a=[[1, 2, 0, 0];[5, 3, 0, 4];[0, 0, 0, 7]; [9, 3, 0, 0]];
k=[[1,1,1];[1,1,0];[1,0,0]];
a_k=filter2(k, a, 'valid')
ak=conv2(a,rot90(k,2), 'valid')

a_k =

11     5
17    10

ak =

11     5
17    10

In python

a = np.array([[1, 2, 0, 0],[5, 3, 0, 4],[0, 0, 0, 7], [9, 3, 0, 0]])
k = np.array([[1,1,1],[1,1,0],[1,0,0]])
from scipy import signal
print(signal.convolve2d(a, np.rot90(k,2), mode='valid'))

[[11 5] [17 10]]