DIP+CV · Programming Exercise

EP08_09 — 🟠 Illumination Gradient and Adaptive Thresholding

8.14.9 EP08_09 🟠 Illumination Gradient and Adaptive Thresholding

In this variation, the objects are immersed in a background with non-uniform illumination (smooth illumination gradient). Simple single-value thresholding fails, requiring more robust preprocessing.

8.14.9.1 📋 Implementation Guidelines

  1. Input: grayscale image \(H \times W\) with background variation from \(20\) to \(180\).
  2. Preprocessing:
  • Apply Adaptive Thresholding (e.g., cv2.adaptiveThreshold with a Gaussian window of \(15 \times 15\) and constant \(C = 3\)) to isolate the objects regardless of background variation.

    cv2.adaptiveThreshold(img_gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, ksize, C) // 255

    ksize and C are read after the image.

  • Morphological Closing operation (\(3 \times 3\)) to seal any gaps in the contours.

  1. Measurement and Classification: extract the measurements.

  2. Sorting and Output: sort by (bbox[0], bbox[1]) and print the table including the class column.

    • To sort, use medidas.sort(key=lambda m: (m['bbox'][1], m['bbox'][0])), with medidas = mm.measure(img, precision=0.02).

8.14.9.2 📌 Examples

Input Output
16 32
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
…
k 20
id area perimeter cx cy x y w h circularity solidity vertices
1 9.0 12.0 10.0 5.0 8 3 5 5 0.79 1.000 4
2 28.3 18.8 25.0 12.0 22 9 7 7 1.00 1.000 3
🧮 Simulator EP08_09: Illumination Gradient and Adaptive Threshold & OpenCV Measurement Adaptive vs Global → Measurement
PROCESSING STAGE
PIXEL MATRIX VIEW
OBJECT MEASUREMENT TABLE (COMPUTED AT ADAPTIVE THRESHOLD OK)
id area perimeter cx cy x y w h circularity solidity vertices
Figure 8.23: Simulator EP08_09: Illumination Gradient, Adaptive Threshold and OpenCV Measurement
%%writefile EP08_09.py
# Python code
Overwriting EP08_09.py
TestSuite("EP08_09.py").run()
✔️ EP08_09.cases already exists in casos/
📋 3 case(s) loaded from casos/EP08_09.cases

🔍 Testing Python: EP08_09.py
⚠️ EP08_09.py: Empty file (fewer than 3 lines). Tests skipped.