how do i automatically select the kernel size like 5*5, 7*7... instead of the 3*3 in the code below
4 views (last 30 days)
Show older comments
clc;
clear all;
close all;
es=imread('cameraman.Tif');
es=imnoise(es,'salt & pepper',0.5);
b=es;
[r,c]=size(es);
for i=2:r-1
for j=2:c-1
mat=[es(i-1,j-1),es(i-1,j),es(i-1,j+1),es(i,j-1),es(i,j),es(i,j+1),es(i+1,j-1),es(i+1,j),es(i+1,j+1)];
mat=sort(mat);
b(i,j)=mat(5);
end
end
figure;
imshow(es);
title('Image corrupted with Salt & Pepper Noise');
figure;
imshow(b);
title('Image after filtering');
1 Comment
Walter Roberson
on 11 Jan 2022
What should the criteria be for deciding whether a 5*5 or 7*7 is better or more justified than a 3*3 ? What should the code be looking for in order to decide which size to use ?
Answers (2)
Rik
on 6 Jan 2022
This is a terrible way to write a median filter. Since the use of imnoise indicates that you already have the Image Processing toolbox, why not use medfilt2?
2 Comments
Rik
on 11 Jan 2022
Your code is applying a median filter with a 3*3 kernel. That makes it equivalent to this:
es=imread('cameraman.tif');
es=imnoise(es,'salt & pepper',0.5);
es = padarray(es,[1 1],0,'both');%add padding since your code doesn't filter the edges
isequal( b , medfilt2(es,[3 3]) )
As you can see, this way it is trivial to change the kernel size to 5*5 or 7*7.
Why do you want to use your double loop?
Walter Roberson
on 11 Jan 2022
window_size = randi([2 6]) * 2 - 1
hws = (window_size - 1)/2;
es = imread('cameraman.tif');
assert(ndims(es) == 2, 'Grayscale images only!');
es = imnoise(es,'salt & pepper',0.5);
b = es;
[r,c]=size(es);
for i=1+hws:r-hws
for j=1+hws:c-hws
mat = es(i-hws:i+hws, j-hws:j+hws);
mat = sort(mat(:));
b(i,j)= mat((end-1)/2);
end
end
figure;
imshow(es);
title('Image corrupted with Salt & Pepper Noise');
figure;
imshow(b);
title( sprintf('Image after filtering window size %d', window_size) );
0 Comments
See Also
Categories
Find more on Image Processing Toolbox in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!