Filtering and thresholding

Smoothing, sharpening and differentiating are one operation with different kernels — except the median, which is not linear at all.

What you'll learn
  • Compute a filtered pixel by hand from a 3×3 kernel
  • Explain why a median filter removes salt-and-pepper noise that blurs cannot
  • Pick a threshold type, and a threshold automatically with Otsu's method

A linear filter replaces every pixel by a weighted sum of its neighbourhood. The weights form a kernel, and cv2.filter2D slides it across the image:

\[g(x, y) = \sum_{i=-1}^{1} \sum_{j=-1}^{1} k(i, j)\, f(x + j, y + i)\]

(Strictly this is correlation; convolution flips the kernel first. For the symmetric kernels below there is no difference.) The kernel decides what the filter does:

A 3×3 kernel sliding over an 8×8 patch: a vertical step edge (40 | 200) with one salt pixel (255) and one pepper pixel (0). The readout shows the exact weighted sum for each output pixel. Try the median: the two noise pixels disappear and the edge stays sharp.

08_image_filtering.py uses these kernels:

kernel1 = np.array([[0, 0, 0], [0, 1, 0], [0, 0, 0]])        # identity
kernel2 = np.ones((5, 5), np.float32) / 25                   # box blur
kernel3 = np.array([[0, -1, 0], [-1, 5, -1], [0, -1, 0]])    # sharpen
gauss_blur = cv2.GaussianBlur(src=image, ksize=(5, 5), sigmaX=0, sigmaY=0)
mid_blur = cv2.medianBlur(src=image, ksize=5)
bilateral = cv2.bilateralFilter(src=image, d=9, sigmaColor=75, sigmaSpace=75)
  • Box and Gaussian kernels sum to 1, so flat regions keep their brightness while fine detail and noise are averaged away. The Gaussian weights the centre more and produces fewer ringing artefacts. With sigmaX=0, OpenCV derives σ from the kernel size.
  • Sharpen is the identity plus a negative Laplacian: weights still sum to 1, but each pixel is pushed away from the mean of its neighbours.
  • Median is not a weighted sum. It sorts the neighbourhood and takes the middle value, so a single extreme pixel never reaches the output.
  • Bilateral weights neighbours by distance and by similarity of intensity, so it smooths within regions but not across edges — at a much higher cost.

The script has a display slip worth knowing about: it computes img_blur and mid_blur but shows img (the box-blurred image) in both windows, so the “built-in blur” and “median blur” windows both show the box result.

Measuring the difference

Running the filters on img.png with 8% of its pixels set to pure black or white:

Six panels of the same campus photo: salt-and-pepper noisy input, box 5x5, Gaussian 5x5, median 5, bilateral on the clean input, and sharpened clean input. The median panel is clean; the box and Gaussian panels show grey smudges where the noise was.
Linear blurs smear each noise pixel into a grey blotch; the median removes it.
Peak signal-to-noise ratio against the clean image. The median wins by more than a decibel over the Gaussian, its nearest rival.

Thresholding

09_image_thresholding.py turns a grey image into a mask with cv2.threshold and five rules — THRESH_BINARY (above → max, else 0), BINARY_INV, TRUNC (clip at the threshold), TOZERO and TOZERO_INV. Its first call uses thresh=0, which marks every pixel brighter than 0 as foreground; 127 was presumably meant, as in the other four.

A fixed number rarely suits every image. Otsu’s method chooses the threshold that best separates the histogram into two classes (it maximises the between-class variance), and is requested with a flag:

ret, mask = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)

The 0 is ignored and ret returns the chosen value — 162 for the coins image of lesson 12.

Try it yourself. In the animation, pick the box kernel and compute out[1][1] by hand before stepping to it. Then add noise to an image with noisy[np.random.rand(*noisy.shape[:2]) < 0.05] = 255, and compare cv2.GaussianBlur with cv2.medianBlur for kernel sizes 3, 5 and 7. Which grows blurrier faster as the kernel grows?

View source on GitHub →