I = 3 * sin(.3*[1:500]')*ones(1,500) + 3 * cos(.2*[1:500]')*ones(1,500) + 0.5*ones([500 500]); % Generate random sine wave image
I_noisy = imnoise(I,'salt & pepper',.02); % Add noise to the image
I_clean = medfilt2(I_noisy,[3 3],'symmetric');
I_clean2 = medfilt2(I_noisy,[9 9],'symmetric');
figure(1),imshow(I_noisy),title('Salt and Pepper Image')
figure(2),imshow(I_clean),title('Cleaned image using [3 3] filter window')
figure(3),imshow(I_clean2),title('Clean image using [9 9] filter window')
The median filter replaces the pixel at the center of an [m n] window with the median value of all of the other pixels in the window. It specializes in removing salt and pepper noise.