Sub topic 5
Matching the filter to the noise
This chapter assumes you can read and write basic Python and NumPy, that OpenCV (cv2) is installed, and that you know how cv2.blur, cv2.GaussianBlur, cv2.medianBlur and cv2.bilateralFilter are called. The previous chapter introduced those four filters. Here you learn how to choose among them.
Why the choice matters
Smoothing is not free. Every filter trades noise removal against lost detail, and each filter loses a different kind of detail. A filter that suits one kind of noise can make another kind worse. The noise type should decide which filter you use.
Later steps depend on this choice. Sobel and Canny amplify noise, because a derivative responds strongly to random pixel-to-pixel jumps. A thresholded mask inherits whatever speckle the smoothing step left behind.
Two common noise models
Noise comes in many forms. Two models cover most cases you will meet early on.
- Gaussian noise changes every pixel by a small random amount drawn from a bell curve. It looks like fine grain and typically comes from sensor electronics or low light.
- Salt-and-pepper noise (impulse noise) replaces a few pixels with pure black (0) or pure white (255) and leaves the rest untouched. It comes from dead pixels, transmission errors, or corrupted bytes.
Other kinds exist. JPEG compression produces blocky artifacts, and multiplicative speckle appears in ultrasound and radar images. This chapter focuses on the two models above, because they show most clearly why the filters behave differently.
How each filter reacts
Each filter computes a new value for a pixel from its neighborhood.
- Box (
cv2.blur) takes the plain average. It reduces Gaussian noise but blurs edges equally in all directions. It also smears an impulse outlier into a gray blob the size of the kernel. - Gaussian (
cv2.GaussianBlur) takes a weighted average that favors nearby pixels. It handles Gaussian noise well and blurs edges less harshly than the box filter. It still averages in outliers, so salt-and-pepper pixels become soft dots instead of disappearing. - Median (
cv2.medianBlur) takes the middle value of the sorted neighborhood. A single extreme pixel never becomes the middle value, so impulse noise is removed outright. It also keeps step edges sharp. It rounds corners and erases lines thinner than about half the kernel size. - Bilateral (
cv2.bilateralFilter) averages only pixels that are both near and similar in intensity. Flat areas are smoothed and strong edges are preserved. It is much slower than the others, and its settings need care. It handles impulse noise badly, because an extreme pixel has no similar neighbors and so is mostly left alone.
| Noise or goal | First choice | Why | Watch out for |
|---|---|---|---|
| Gaussian (sensor) noise | `GaussianBlur` | Averaging cuts random variation, and the weighting limits blur | Blurs edges as sigma grows |
| Salt-and-pepper | `medianBlur` | Outliers never become the median | Erases thin lines and rounds corners |
| Gaussian noise, edges must stay sharp | `bilateralFilter` | Mixes only similar intensities | Slow, and can leave a cartoon-like look |
| Quick, rough smoothing | `blur` | Cheapest option | Visible box-shaped artifacts at large sizes |
Measuring the difference
Judging results by eye is unreliable. A quick numeric check is PSNR (peak signal-to-noise ratio), which cv2.PSNR computes against a clean reference. Higher is better. You need a clean image to compute it, so the script builds a synthetic one and adds noise itself. That keeps the example runnable without any input file.
import cv2
import numpy as np
rng = np.random.default_rng(0)
# Synthetic clean image: a gradient, a bright square, and a 1-pixel line.
clean = np.tile(
np.linspace(40, 200, 256, dtype=np.float32), (256, 1)
).astype(np.uint8)
cv2.rectangle(clean, (60, 60), (140, 140), 255, -1)
cv2.line(clean, (20, 200), (230, 200), 0, 1)
def add_gaussian(img, sigma=20.0):
noise = rng.normal(0.0, sigma, img.shape)
return np.clip(img.astype(np.float32) + noise, 0, 255).astype(np.uint8)
def add_salt_pepper(img, amount=0.05):
out = img.copy()
r = rng.random(img.shape)
out[r < amount / 2] = 0
out[r > 1 - amount / 2] = 255
return out
filters = {
"box": lambda x: cv2.blur(x, (5, 5)),
"gaussian": lambda x: cv2.GaussianBlur(x, (5, 5), 0),
"median": lambda x: cv2.medianBlur(x, 5),
"bilateral": lambda x: cv2.bilateralFilter(x, 9, 75, 75),
}
noisy_images = {
"gaussian noise": add_gaussian(clean),
"salt-and-pepper": add_salt_pepper(clean),
}
for noise_name, noisy in noisy_images.items():
print(f"{noise_name}: unfiltered PSNR = {cv2.PSNR(clean, noisy):.1f} dB")
for name, apply_filter in filters.items():
result = apply_filter(noisy)
print(f" {name:10s} {cv2.PSNR(clean, result):.1f} dB")Run it and compare the two blocks of output. Exact numbers depend on the random seed and the image. The pattern to look for is that medianBlur scores best on the salt-and-pepper image. On the Gaussian image, GaussianBlur and bilateralFilter do better than the median.
The 1-pixel line in the test image is deliberate. A 5x5 median erases it, and that loss shows up in the score.
A decision path
Ask what the noise looks like, then ask what you cannot afford to lose.
Parameter notes that affect the result
- Kernel size. Larger kernels remove more noise and blur more detail. Begin with 3x3 or 5x5 and increase only if the noise remains.
- Gaussian sigma. Passing
0as sigma tells OpenCV to derive it from the kernel size. Passingksize=(0, 0)with an explicit sigma derives the kernel size from sigma instead. Use whichever you want to control. - Median ksize. It must be odd and greater than 1. For sizes 3 and 5 it accepts several depths, but larger sizes accept only
uint8. - Bilateral
d. This is the neighborhood diameter. Around 5 suits real-time use, and around 9 suits offline use. SetsigmaColorandsigmaSpaceequal for simplicity. Below about 10 the effect is weak. Above about 150 the image looks cartoon-like. - Repeated filtering. Two passes of a 3x3 median often preserve more detail than one 7x7 pass. Test both on your data.
Common mistakes
- Choosing by habit.
GaussianBlur((5, 5), 0)is a good default for Gaussian noise. It is the wrong tool for impulse noise. - Using a large median kernel on line art. Thin strokes, text and fine edges disappear. Check the output at full size, not as a thumbnail.
- Using bilateral on impulse noise. The filter keeps strong differences by design, so it preserves the outliers you want gone.
- Smoothing too much before edge detection. Heavy blur removes weak but real edges. The pre-blur for Canny or Sobel should be only strong enough to suppress noise-driven responses.
- Judging only visually. Compare with a metric on a reference, or inspect a zoomed crop of an edge and a flat region separately.
Beyond these four filters
When Gaussian noise is strong and you need to keep texture, the four filters here may fall short. cv2.fastNlMeansDenoising (and cv2.fastNlMeansDenoisingColored) compares whole patches instead of single pixels and usually does better on grain, at a high cost in time. It is outside this chapter's scope, but remember it exists before you push a Gaussian kernel to large sizes.
Exercise
A scanned document has scattered isolated black and white specks, and the text strokes are one to two pixels wide. You must remove the specks before thresholding. Which filter and kernel size would you try first, and what risk would you check for?
Show answer
Try cv2.medianBlur with ksize 3. Isolated black and white specks are impulse noise, and the median removes them without averaging them into neighbors. The risk is that a larger median kernel erases or breaks the thin strokes, so inspect the text at full size. If strokes are damaged, keep ksize 3 or apply a single pass only. Do not use GaussianBlur or box, because they smear the specks into gray blobs that survive thresholding.
Exercise
In the PSNR script, you replace the noisy salt-and-pepper image with one that has Gaussian noise of sigma 20 and want to keep the edge of the bright square sharp. Which filter should you expect to score well, and why might its score still trail GaussianBlur on the smooth gradient region?
Show answer
bilateralFilter is the expected choice, because it averages only pixels with similar intensity and so preserves the square's edge. On the smooth gradient, noise of sigma 20 can exceed the sigmaColor tolerance for many neighbors, so fewer pixels are averaged and less noise is removed. GaussianBlur averages all neighbors in the window and can score higher in flat regions, at the cost of blurring the square's edge.