A median filter changes the value of one given pixel by the median value (or a weighted version) of a patch of pixels (most often around the given pixel). Generally, the patch contains an odd number of pixels: $\pm K$ above and below, left and right, with a total of $(2K+1)^2$.
I will details three basic scenariiscenarios:
- clean edge (1D vision): suppose that the image is all black on the left ($0$ value), white on the right ($255$ value), a clear vertical edge. If you take a line, across the edge, the values will be $(\ldots,0,0,0,255,255,255\ldots)$. A 3-point median does a perfect job: the patch $(0,0,255)$ yields $0$, the patch $(0,255,255)$ yields $255$. Now look across columns: they are constant, so the output of a A 3-point median yelds the same constant. This also works with any $2m+1\times 2n+1$ patch. So the clean edge is fully preserved, while a linear filter (non-trivial) would average values, and yields non integer pixels, introducing additional rounding errors
- pure flat+gaussian noise: the median is a robust estimator of the flat value, and can reduce the variance of the noise (I can add references if needed)
- pure flat (or pure noise)+ isolated outliers: depending on the number of outliers and the size of patch, the outliers are strongly shrunk toward the flat or a noise value.
It is non-linear, since the median of $(0,1,2)$ is $1$, the median of $(3,1,1)$ is $1$, but the median of $(0,1,2)+(3,1,1)$ is $3$, and not $1+1$.
So it can be better than linear filters, but this depends on the nature of edges, noise properties and patch size. Others sources on SE.DSP: