Practical 8: Spatial Filtering — Smoothing & Sharpening

Open In Colab Run this practical in Google Colab

1. Aim

Aim

To implement and analyze the four canonical spatial-domain filters of digital image processing: the box (averaging) filter and median filter for noise smoothing, and the Laplacian and Sobel operators for sharpening and edge detection.

2. Description / Theory
Theory:
  • Box (mean): \( \hat f(x,y) = \frac{1}{mn} \sum_{(s,t)\in S_{xy}} f(s,t) \) — linear smoothing.
  • Median: \( \hat f(x,y) = \mathrm{median}\{ f(s,t) : (s,t)\in S_{xy} \} \) — non-linear, preserves edges, ideal for impulse noise.
  • Laplacian: \( \nabla^2 f \approx f_{N}+f_{S}+f_{E}+f_{W} - 4f(x,y) \) — second derivative for sharpening: \( g = f - \nabla^2 f \).
  • Sobel: first-derivative gradient via \(G_x, G_y\); magnitude \(|G| \approx |G_x|+|G_y|\); direction \(\theta = \arctan(G_y/G_x)\).
3. Code

Part 1: Box Filter (Smoothing)

Apply the box filter at multiple kernel sizes (3, 5, 9, 15, 35) on the standard test pattern. Larger kernels produce stronger blur because they low-pass at lower cut-off frequencies.

Part 2: Median Filter on Salt-and-Pepper Noise

Apply the median filter at multiple kernel sizes to the circuit-board image corrupted with 5% salt-and-pepper noise.

Part 3: Box vs Median — Edge Preservation

Apply both filters at the same kernel size to the same noisy input. The box filter blurs noise and edges together; the median filter removes noise while preserving edges.

Part 4: Laplacian Sharpening

Compute \(\nabla^2 f\) with the 4-neighbour and 8-neighbour kernels and form the sharpened image \(g = f - \nabla^2 f\). Demonstrated on the blurry-moon image.

Part 5: Sobel Edge Detection

Compute \(G_x\), \(G_y\), gradient magnitude \(|G|\) and direction \(\theta\) on the contact-lens image, then threshold the magnitude to obtain a clean edge map.

4. Output 5. Analysis / Conclusion

Analysis Questions

  1. As the box-filter kernel grows from 3×3 to 35×35, what happens to the image, and why does this happen at \(O(1/k)\) in the spatial-frequency sense?
  2. Why does the median filter remove salt-and-pepper noise without blurring edges, while the box filter blurs both?
  3. The Laplacian is a second-derivative operator. Why does subtracting its response sharpen the image rather than darken it? How does the 8-neighbour kernel differ from the 4-neighbour version?
  4. Sobel uses two separate kernels and combines their magnitudes. Why is it preferred over the Laplacian for edge detection, even though both involve derivatives?