Why conv2 gives opposite sign
2 次查看(过去 30 天)
显示 更早的评论
Hi, I have a simple matrix I:
I = [1,2,3,4,5;
6,7,8,9,10;
11,12,13,14,15;
16,17,18,19,20;
21,22,23,24,25]
My kernel is:
k = [0,0,0;
1,0,-1;
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 = [~,~,~,~,~;
~,6-8,7-9,8-10,~;
~,11-13,12-14,13-15,~;
~,16-18,17-19,18-20,~;
~,~,~,~,~]
I used this line to achieve this:
dIx = conv2(I,k,'valid');
This gives me the result:
dIx = [0,0,0,0;
0,2,2,2;
0,2,2,2;
0,2,2,2]
which is the opposite sign of what I expected. Why is the case?
Thank you very much.
0 个评论
采纳的回答
Matt J
2020-8-23
编辑:Matt J
2020-8-23
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;
1,0,-1;
0,0,0]
k=fliplr(flipud(k));
dIx = conv2(I,k,'valid');
although for the kernel you've shown this pre-flip happens to be equivalent to k=-k.
更多回答(1 个)
Image Analyst
2020-8-23
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.
3 个评论
Matt J
2020-8-24
filter2 does have that control, however. You could use that to avoid implementing your own kernel flip.
Image Analyst
2020-8-24
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);
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 GPU Computing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!