# how do i automatically select the kernel size like 5*5, 7*7... instead of the 3*3 in the code below

9 views (last 30 days)
Baththama Alhassan on 6 Jan 2022
Answered: Walter Roberson on 11 Jan 2022
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 CommentShowHide None
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 ?

Sign in to comment.

### 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 CommentsShowHide 1 older comment
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]) )
ans = logical
1
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?

Sign in to comment.

Walter Roberson on 11 Jan 2022
window_size = randi([2 6]) * 2 - 1
window_size = 7
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 CommentsShowHide -1 older comments

Sign in to comment.

R2018a

### Community Treasure Hunt

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

Start Hunting!