Median Filter for Salt Pepper Noise
A median filter swaps each pixel for the middle value of its window. Lone specks get outvoted while true edges stand untouched.
Why Does This Exist?
Salt-and-pepper noise slams random pixels to pure black or white: dead sensor cells, transmission glitches, dust on a scan. Averaging filters like the box and Gaussian smear each speck into a grey smudge, spreading the damage. The median instead takes a vote, and one loud outlier always loses an election of nine.
It is the nonlinear member of the smoothing family. It erases impulses while leaving step edges exactly where they were, something no weighted mean can do.
Think of It Like This
Nine judges, one bribed
Nine judges score a dive and the median score stands, so one bribed 10 cannot rescue a flop. Averaging would let that bribe drag the result up. The window is your judging panel and the speck is the bribed judge. The catch matches too: if five judges are bribed, the median falls, which is why the filter fails once corruption fills half the window.
How It Actually Works
Slide a window, usually , over the image. Collect the covered values, sort them, and write the middle one to the output center. No weights, no sums, no new values invented: the output is always one of the input pixels, so edges keep their exact heights and positions.
Worked example
A window holds calm values plus one salt speck:
Sorted: . The middle (5th) value is 14, so the output is 14 and the 255 vanishes. The mean of the same window is , which would paint a visible smudge. Vote beats average whenever corruption is rare but loud.
Watch Out For
Fails past half-window corruption
The median survives only while clean pixels hold the majority of the window. The symptom under heavy noise is blotchy patches where specks survive in clusters. Grow the window to , or stack passes, when more than a third of pixels are corrupted.
Eats thin lines and corners
A line thinner than half the window looks like noise to the voter and gets erased along with the specks. The symptom is vanishing wires, cracks, and sharp corners after filtering. Shrink the window to fit the thinnest structure you must keep, or mask those regions out first.
The Quick Version
- The median filter outputs the middle sorted value of each window.
- Single black or white specks get outvoted and vanish entirely.
- Outputs are always real input values, so edges keep exact positions.
- It fails when corruption fills half the window or more.
- Keep windows smaller than the thinnest line you must preserve.