Why conv2 gives opposite sign

2 views (last 30 days)
xiaojuezi on 23 Aug 2020
Commented: Image Analyst on 24 Aug 2020
Hi, I have a simple matrix I:
I = [1,2,3,4,5;
My kernel is:
k = [0,0,0;
I would like to compute for the non-boundary elements. For each element, I want to compute its left neighbour - its right neighbour,i.e.:
dIx = [~,~,~,~,~;
I used this line to achieve this:
dIx = conv2(I,k,'valid');
This gives me the result:
dIx = [0,0,0,0;
which is the opposite sign of what I expected. Why is the case?
Thank you very much.

Accepted Answer

Matt J
Matt J on 23 Aug 2020
Edited: Matt J on 23 Aug 2020
Remember that a convolution does not slide k over I, but rather a pre-flipped version of k. You can compensate for this by doing,
k = [0,0,0;
dIx = conv2(I,k,'valid');
although for the kernel you've shown this pre-flip happens to be equivalent to k=-k.
  1 Comment
xiaojuezi on 24 Aug 2020
Thank you very much!

Sign in to comment.

More Answers (1)

Image Analyst
Image Analyst on 23 Aug 2020
Convolution flips the kernel - that's just how it works, and there are theoretical/mathematical reasons for it. Perhaps you can use imfilter() instead if you don't want to flip the kernel to be flipped.
Image Analyst
Image Analyst on 24 Aug 2020
Here are the boundary options for conv2:
Here are the options for imfilter():
It looks to me like imfilter() has more options than conv2(). What control did you want to have over the boundary that conv2() has but imfilter() does not? 'Valid'? You could always just use indexing to crop out that part yet still avoid the flipping of the kernel, which you don't want to do.
outputImage = outputImage(2:end-1, 2:end-1);

Sign in to comment.


Find more on Images in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by