Median vs mean filter

Averaging the neighborhood reduces noise, but it also blurs edges, and a single extreme pixel spreads into a blotch. The median takes the middle value instead. Add noise and compare the two filters.

Noisy click to select a pixel and row
Original without noise
Mean filter
Median filter
Intensity along the selected row

Two kinds of noise

Mean filter

The box filter, or mean filter, replaces each pixel by the average of the NN pixel values IiI_i in its window, here N=n×nN = n \times n:

B=1N∑i=1NIiB = \frac{1}{N} \sum_{i=1}^{N} I_i

Averaging NN independent noise values reduces their standard deviation by a factor N=n\sqrt{N} = n, which works well for Gaussian noise. But the mean is sensitive to outliers: a single white pixel on black contributes 1/N1/N to every output pixel of its window and leaves a gray square. The mean also mixes the two sides of every edge, so edges get blurred.

Median filter

The median filter selects the median intensity in the window: it sorts the values and takes the middle one. Because it is based on the ordering of the gray levels, it is a rank filter, like the min, max and range filters.

M=median⁡{I1,…,IN}M = \operatorname{median} \{ I_1, \dots, I_N \}

As long as fewer than half of the values in the window are outliers, they end up at the ends of the sorted list and do not affect the result at all. At a straight edge, more than half of the window lies on one side, so the output takes a value from that side: the edge stays sharp. The price is that thin lines and corners, which cover less than half of the window, are removed, and sorting makes it more expensive than the mean.

The median is not a weighted sum of the inputs, so it is a non-linear filter: it cannot be written as a convolution, and the median of a sum of two images is not the sum of their medians.

Measuring the result. The values panel compares every image with the original using the peak signal-to-noise ratio PSNR=10log⁡10(1/MSE)\mathrm{PSNR} = 10 \log_{10} (1 / \mathrm{MSE}) dB. Higher is better.

Try this