clc, clear, close all;

tic

a=imread(‘lena_gray.tif’); imshow(a);

nf=.5;

ws=3;

b=imnoise(a,’salt & pepper’,nf);

figure,imshow(b);

[m1 n1]=size(a);

ll=floor(ws/2);

y=zeros(m1+ws-1); % b1 is zero matrix of 514*514

y=uint8(y); % b1 is a unsign 8 bit

[m n]=size(y); % Size of b1 matrix is 514*514

y(ll+1:m-ll,ll+1:n-ll)=b; % b1(2:513,2:513)

for i = 2:m1-1

for j = 2:n1-1

flg = 0;

n = size(b);

for l = 2:n;

key = y(l);

k = l-1;

while(k>0 && y(k)>key)

y(k+1) = y(k);

k = k-1;

y(k+1)=key;

end

end

if y(i,j) == 0 || y(i,j) == 255

flg = 1;

end

if flg == 0

if S(1) < y(i,j) && y(i,j) < S(5) && 0 < S(1) && S(9) < 255

y(i,j) = y(i,j);

end

else

if S(1) < S(5) && S(5) < S(9) && 0 < S(5) && S(5) < 255

y(i,j) = S(5);

end

if S(1) >= S(5) || S(5) >= S(9) || S(5) == 255 && S(5) == 0

y(i,j) = y(i,j-1);

end

end

end

end

y(1,:) = y(2,:);

y(R,:) = y(R-1,:);

y(:,1) = y(:,2);

y(:,C) = y(:,C-1);

b2=b1(ll+1:m-ll,ll+1:n-ll);

figure,imshow(b2);

toc