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.
Asked
Active
Viewed 3,609 times
2
2 Answers
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
-
1Also see `scipy.ndimage.convolve`. – Stefan van der Walt Apr 07 '17 at 16:33
-
1Correct me if I'm wrong, but I thought `ndimage.convolve` always did the equivalent of matlab's `filter2` with the option `'same'`, and the OP has asked specifically about the `'valid'` option. – Matthew Pope Apr 09 '17 at 23:11
-
I guess my thinking was that the OP could then do padding of various sorts easily, but you're right. – Stefan van der Walt Apr 24 '17 at 20:14
-
1I think it should be signal.convolve2d(X, np.rot90(H, k=2), mode='valid') otherwise the default is k=1 and you are rotating the array 90 degrees – Robyc Jun 25 '19 at 13:59
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]]

H.biyuechuji
- 31
- 2