Implement average filter without using built-in functions
15 views (last 30 days)
Show older comments
I am trying to blur the image, but I did not succeed. I am keep getting almost black image? What am I missing here?
clc;
clear all;
img = imread("Q3_Input", "tif");
imshow(img);
[M, N] = size(img);
filter = averageFilter(img, M, N);
%blurredImage = conv2(single(img), filter, 'full');
figure;
imshow(filter, []);
%{
since the filter 3x3
i == 1 & j == 1 or
i == 1 & (N - j) == 0 or
(M - i) & j == 1 or
(M - i) & (N - j) == 0
covers the corner areas
x = covered areas
__________
|_x_|__|_x_|
|__|__|__|
|_x_|__|_x_|
the other coverts the middle of the area
|__|_x_|__|
|_x_|_x_|_x_|
|__|_x_|__|
%}
function img = averageFilter(image, M, N)
newImg = zeros(M, N);
for i = 1: M
for j = 1: N
if i == 1
if j == 1
summation = 0;
for k = i: i + 1
for l = j: j + 1
summation = summation + image(k,l);
end
end
newImg(i, j) = ceil(summation / 4.0);
elseif (N - j) == 0
for k = i: i + 1
for l = j - 1: j
summation = summation + image(k,l);
end
end
newImg(i, j) = ceil(summation / 4.0);
else
for k = i: i + 1
for l = j - 1: j + 1
summation = summation + image(k,l);
end
end
newImg(i, j) = ceil(summation / 6.0);
end
elseif (M - i) == 0
if j == 1
for k = i - 1: i
for l = j: j + 1
summation = summation + image(k,l);
end
end
newImg(i, j) = ceil(summation / 4.0);
elseif (N - j) == 0
for k = i -1: i
for l = j -1: j
summation = summation + image(k,l);
end
end
newImg(i, j) = ceil(summation / 4.0);
else
for k = i - 1: i
for l = j - 1: j + 1
summation = summation + image(k,l);
end
end
newImg(i, j) = ceil(summation / 6.0);
end
else
if j == 1
for k = i - 1: i + 1
for l = j: j + 1
summation = summation + image(k,l);
end
end
newImg(i, j) = ceil(summation / 6.0);
elseif (N - j) == 0
for k = i - 1: i + 1
for l = j - 1: j
summation = summation + image(k,l);
end
end
newImg(i, j) = ceil(summation / 6.0);
else
for k = i - 1: i + 1
for l = j - 1: j + 1
summation = summation + image(k,l);
end
end
newImg(i, j) = ceil(summation / 9.0);
end
end
end
end
img = newImg;
end
original image
0 Comments
Accepted Answer
Matt J
on 21 Oct 2019
Edited: Matt J
on 21 Oct 2019
In all likelihood, you have not converted your image to floating point
img = im2double( imread("Q3_Input", "tif") );
2 Comments
Image Analyst
on 21 Oct 2019
No. Computing the mean in a window inherently gives you a floating point number. However, if you want, you can cast the final floating point image into uint8 after the whole window scanning process has finished.
More Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!