How to use convolution on a 2d matrix with a kernel?

79 views (last 30 days)
Thomas Nell
Thomas Nell on 28 Oct 2020
Answered: Rishabh Mishra on 6 Nov 2020
Dear Mathworks community,
I have the following function which i plan on using for a 2d matrix with a 2d kernel. The code is as follows:
function [filtered] = basic_convolution(image,kernel)
dimensions = size(image);
dimensions2 = size(kernel);
image2 = zeros(dimensions(1),dimensions(2));
for i = 1:dimensions(1)
for j = 1:dimensions(2)
accumulator = 0;
for k = 1:dimensions2(1)
for l = 1:dimensions2(2)
if [i j] == [k l]
result = image(i,j) * kernel(k,l);
accumulator = accumulator + result;
else
end
end
end
image2(i,j) = accumulator;
end
end
filtered = image2;
end
What I cant figure out is how to apply this to the whole matrix and not a portion. Also, when the resulting image comes out I find that the pixel in the new image isnt the sum of the area multiplied by the matrix, but the individual components which have been multiplied by the kernel. I am aware of the command conv, but in the specification for this code I am not allowed to use it. Also, border handling isnt required at this stage of the code - ill add that in later. If you guys could point out the error in my code I would be super grateful.
Thanks!!

Answers (1)

Rishabh Mishra
Rishabh Mishra on 6 Nov 2020
Hi,
I have made some changes to the code provided by you, the remaining code remains same. The edited code will perform convolution of 2 matrices (kernel on image) and provide you with required filtered matrix. I have also added some comments for reference.
function [filtered] = basic_convolution(image,kernel)
dimensions = size(image);
dimensions2 = size(kernel);
% define kernel center indices
kernelCenter_x = dimensions2(1)/2;
kernelCenter_y = dimensions2(2)/2;
image2 = zeros(dimensions(1),dimensions(2));
for i = 1:dimensions(1)
for j = 1:dimensions(2)
for k = 1:dimensions2(1)
for l = 1:dimensions2(2)
% New changes are added below
ii = i+(k-kernelCenter_x);
jj = j+(l-kernelCenter_y);
if (ii >= 1 && ii <= dimensions(1) && jj >= 1 && jj <= dimensions(2))
image2(i,j) = image2(i,j) + image(ii,jj)* kernel(k,l);
end
end
end
end
filtered = image2;
end
end
Feel free to reach out for any further queries regarding the above code.
Hope this helps.

Tags

Products


Release

R2019b

Community Treasure Hunt

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

Start Hunting!