%Question No: 5
%Write a MATLAB function for implementing median filtering of an image. Add
%salt and pepper noise to it. Apply the median filtering to the resulting
%image. Compare the results.

function medianfilt(x)
f=imread(x);
f=im2double(f);
MF=filt(f);
figure,imshow(f),title('Original Image');
figure,imshow(MF),title('Median Filtered Image');
SP=noise(f);
figure,imshow(SP),title('Salt & Pepper Noisy Image');
SPMF=filt(SP);
figure,imshow(SPMF),title('Salt & Pepper - Median Filtered  Image');
end
function M=filt(f)
[r,c]=size(f);
for i=1:r
    for j=1:c
        ip=i+1;
        im=i-1;
        jm=j-1;
        jp=j+1;
        if(im<1)
            im=i;
        elseif (ip>r)
            ip=i;
        end
        if(jm<1)
            jm=j;
        elseif (jp>c)
            jp=j;
        end
        W=[f(i,j) f(i,jm) f(i,jp) f(ip,j) f(im,j) f(im,jm) f(ip,jm) f(ip,jp) f(im,jp)];
        m=median(W);
        M(i,j)=m;
    end
end
end
function N=noise(f)
a=0.05;b=0.05;
[r c]=size(f);
h(1:r,1:c)=0.5;
x=rand(r,c);
idx=find(x<=a);
h(idx)=0;
idx=find(x>a & x<=(a+b));
h(idx)=1;
N=f;
for i=1:r
    for j=1:c
        if(h(i,j)==0)
            N(i,j)=0;
        elseif(h(i,j)==1)
                N(i,j)=255;
       end
    end
end
end