Reputation: 1808
I have the following image that I am convolving with a Sobel filter:
At row 157, the color begins to change and we see that the intensity increases. Note in my MATLAB code, I converted the image to grayscale. This behavior can be seen below:
I then apply the following Sobel Filter:
Gy = [-1 -2 -1; 0 0 0; +1 +2 +1];
A = conv2(im, Gy);
I expect the output to be a matrix with positive numbers since the intensity increases. However, the output shows a matrix with negative numbers. Does anyone know why?
Upvotes: 3
Views: 1252
Reputation: 104503
conv2
rotates the kernel / filter mask by 180 degrees before performing filtering. This is the definition of convolution (a.k.a. you're using conv2
- 2D convolution). The positive changes you're expecting as the result is from the process of performing correlation instead. As such, either use filter2
, or rotate the kernel by 180 degrees by doing Gy = Gy(end:-1:1, end:-1:1);
and then call conv2
after so that inside conv2
it will rotate the kernel again so that you're performing correlation instead.
As such:
Gy = [-1 -2 -1; 0 0 0; +1 +2 +1];
Gy = Gy(end:-1:1, end:-1:1); %// Added
A = conv2(im, Gy);
Similarly, if you have access to the image processing toolbox, you may use imfilter
as already suggested by another answer and the default behaviour is to use correlation instead of convolution. You can override this behaviour by specifying the 'conv'
flag if you expressly want to perform convolution instead.
Upvotes: 3