Using Vectorization to Calculate New Values Based on Surrounding Values

조회 수: 7 (최근 30일)
Sam Ajami
Sam Ajami 2018년 3월 24일
댓글: Image Analyst 2018년 3월 24일
Pardon any mistakes, I'm going through a massive panic attack at the moment with the stress of trying to solve this the last 4+ hours.
I have a project for my programming class that wants me to write a bunch of functions to assist an edge finding function. It has to all be vectorized, ie no iteration or selection. And I'm failing to vectorize the very first function.
The task in question:
The idea is that all the values in a matrix are given a weighted average based on given matrix W. I've already successfully implemented this code with iteration here:
W = [10/222 27/222 10/222;
27/222 74/222 27/222;
10/222 27/222 10/222];
for i=2:size(bw_im,1)-1
for j=2:size(bw_im,2)-1
A=bw_im(i-1:i+1, j-1:j+1);
bw_im(i,j)=sum(sum(A.*W));
end
end
bw_smooth=bw_im;
This successfully outputs the values the full instructions ask for. However, I've been unable to properly vectorize it. The best I've gotten is cutting out the iteration with this
bw_im(2:size(bw_im,1)-1,2:size(bw_im,2)-1)=
Which means it'll only overwrite the non-edge values. Other than that, I'm completely stumped. Please help, I'm panicking at the moment as there is still so much more to do.

답변 (1개)

Image Analyst
Image Analyst 2018년 3월 24일
Just use conv2() with the valid option and then paste it onto a copy of the original. It's 3 lines of code. Hint:
conv2Image = conv2(A, w, 'valid');
result = A; % Initialize
result(2:............) = conv2Image; % Paste
I'll let you figure out the indexes in the third line to complete it. Should take you less than a minute, not 4 hours, once you realize what they are describing is convolution (actually correlation but with a symmetrical kernel correlation is the same as convolution).
If you can't use conv2() and need to do it yourself, I attach a very inefficient manual way of doing the scanning with a 4-nested for loop, though it's not recommended. I recommend using conv2 because it's highly efficient and optimized.
  댓글 수: 9
Sam Ajami
Sam Ajami 2018년 3월 24일
Welp I figured it out, it's the stupidest piece of code ever but it works
bw_im(2:end-1,2:end-1)=bw_im(1:end-2,1:end-2)*10/222+bw_im(1:end-2,2:end-1)*27/222+bw_im(1:end-2,3:end)*10/222+bw_im(2:end-1,1:end-2)*27/222+bw_im(2:end-1,2:end-1)*74/222+bw_im(2:end-1,3:end)*27/222+bw_im(3:end,1:end-2)*10/222+bw_im(3:end,2:end-1)*27/222+bw_im(3:end,3:end)*10/222;
Image Analyst
Image Analyst 2018년 3월 24일
There are differences between your method and the one I suggested. See attached code.

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

카테고리

Help CenterFile Exchange에서 Numerical Integration and Differentiation에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by