Median filter

[3] Such noise reduction is a typical pre-processing step to improve the results of later processing (for example, edge detection on an image).

For one-dimensional signals, the most obvious window is just the first few preceding and following entries, whereas for two-dimensional (or higher-dimensional) data, the window must include all entries within a given radius or ellipsoidal or rectangular region (i.e., the median filter is not a separable filter).

When implementing a median filter, the boundaries of the signal must be handled with special care, as there are not enough entries to fill an entire window.

There are several schemes that have different properties that might be preferred in particular circumstances: Code for a simple two-dimensional median filter algorithm might look like this: This algorithm: Typically, by far the majority of the computational effort and time is spent on calculating the median of each window.

The naïve implementation described above sorts every entry in the window to find the median; however, since only the middle value in a list of numbers is required, selection algorithms can be much more efficient.

[4] The median filter operates by considering a local window (also known as a kernel) around each pixel in the image.

This filtered image effectively removes noisy pixels while preserving important features.

For small to moderate levels of Gaussian noise, the median filter is demonstrably better than Gaussian blur at removing noise whilst preserving edges for a given, fixed window size.

Example of 3 median filters of varying radiuses applied to the same noisy photograph.
Use of a median filter to improve an image severely corrupted by defective pixels