필터 지우기
필터 지우기

Discrepancy between convolution and filtering

조회 수: 2 (최근 30일)
AlexRD
AlexRD 2021년 4월 5일
댓글: AlexRD 2021년 4월 5일
I've been trying to optimize the convolution process for my neural network to make it work on a big matrix. I figured out the logic, but the implementation is giving me different results from the conv2 function.
I've written a code to exemplify this:
% The image is a 28x28 picture, and the filter 5x5. The code i've written
% here is not the one i've optimized for matrix multiplication, but it
% shows the same logic where you sweep the image, multiply it by the
% filter and sum it.
image = data(:,:,1);
filter = rand(5, 5);
a = conv2(image, filter, 'valid');
b = zeros(24, 24);
for j=1:24
for i=1:24
b(i, j) = sum(filter .* image(i:i+4, j:j+4), 'all');
end
end
Although a and b are very similar:
They're usually off by a non-trivial amount:
Is there something i'm doing wrong here? Or maybe the conv2 algorithm does something to speed up the process that changes the result in a significant way?
Also, when the filter is all ones (like ones(5,5) instead of rand), a and b are identical.
  댓글 수: 2
Rik
Rik 2021년 4월 5일
I believe filter and conv2 are equivalent except for flipping the second input. That would explain why the result is the same for a symmetrical kernel.
Did you check the documentation?
AlexRD
AlexRD 2021년 4월 5일
Yeah, what was missing was the flipping. Thanks!

댓글을 달려면 로그인하십시오.

채택된 답변

Image Analyst
Image Analyst 2021년 4월 5일
Your manual way is not flipping the kernel like conv2() does. So when the kernel is symmetric, the results will be the same and when the kernel is not symmetric, the results will be different. Try flipping the kernel in your "manual" way and you'll find they are the same.
  댓글 수: 1
AlexRD
AlexRD 2021년 4월 5일
That did it! I tried earlier to flip the results but forgot i had to flip the two dimensions, and not only one.
In case anyone is curious, here is the code:
image = data(:,:,1);
filter = rand(5, 5);
a = conv2(image, filter, 'valid');
b = zeros(24, 24);
for j=1:24
for i=1:24
b(i, j) = sum(flip(flip(filter, 1), 2) .* image(i:i+4, j:j+4), 'all');
end
end
Thank you very much

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by