MATLAB Based Salt & Pepper Noise Removal by 2D Median Filtering without medfilt2 MATLAB Function

A 2-D Median filter

The 2D median filter is a sliding-window spatial filter, it replaces the central value in the window with the median of all the pixel values lying in the window. An example of median filtering of a single 3x3 window of values is shown below.

 7 3 0 4 33 5 20 4 11

in ascending order they are:
0, 3, 4, 4, 5, 7, 11, 20, 33

 * * * * 5 * * * *
Center value (previously 33) is replaced by the median of all nine values (5).
The median filter is also widely claimed to be 'edge-preserving' since it theoretically preserves step edges without blurring. However, in the presence of noise it does blur edges in images slightly.

How 2d median filter is applied on an Image Matrix, through a sliding window approach. Due to 2nd & 3rd condition we need to pad the edges.
 (Image illustration Courtesy, CUVT Prague)
By the above illustrations, it might be clear till now how the central element of the median filter is calculated & how the sliding window approach helps to decide & replace the original valued pixel.

Also before going to the implementation of MATLAB Based Salt & Pepper Noise Removal by 2D Median Filtering without medfilt2 MATLAB Function, I suggest you to please refer the below two articles, for having a much enhanced insight of the problem.

Original Image:

 Original Image

Grayscale Version of the original image

 Image after adding the Salt & Pepper Noise
Input:
Enter the size of kernel of median filter, (n for nxn matrix):4

Resultant Noise Removed Image:
 Resultant Noise Removed Image, With a kernel size 4x4