%{
-------------------------------
2D Median Filter
-------------------------------
1.find the greyscale of an image
2.add noise to it using imnoise()
3.use median filter to see the effect
%}
%%reading the image and getting the grayscale image
image=imread(\'x.jpg\');
gray=rgb2gray(image);
figure,imshow(image),title(\'Original\');
figure,imshow(gray),title(\'Gray\');
%%adding noise to the image
noisy=imnoise(gray,\'salt & pepper\',0.02);
figure,imshow(noisy),title(\'Noise Added\');
noisy1=noisy ; %%copy of the noisy image
noisy2=noisy; %%for testing with medfilt()
%%implementing the median blur on the noisy image
[row,col] = size(noisy);
%%these are created for the padding
arr_up=noisy1(1,:); %top padding
arr_lt=noisy1(:,1); %left left padding
arr_rt=noisy1(:,col); %right padding
arr_dn=noisy1(row,:); %down padding
%%corner values
top_lt=noisy1(1,1);
top_rt=noisy1(1,col);
bot_lt=noisy1(row,1);
bot_rt=noisy1(row,col);
lt_pad=[top_lt;arr_lt;bot_lt];
rt_pad=[top_rt;arr_rt;bot_rt];
%%adding the pads
pad1=[arr_up;noisy1;arr_dn];
final=[lt_pad,pad1,rt_pad];
%%now final consists of the padded noisy image
final1=final;
[r,c]=size(final1);
for i=2:r-1
for j=2:c-1
array1=[ final1(i-1,j-1) final1(i-1,j) final1(i,j+1) final1(i,j-1) final1(i,j) final1(i,j+1) final1(i+1,j-1) final1(i+1,j) final1(i+1,j+1) ];
final1(i,j)=median(array1);
end
end
figure,imshow(final1),title(\'After Applying Median Blur\');
mim=medfilt2(noisy2);
figure,imshow(mim),title(\'Medfilt()\');