DIP+CV · Programming Exercise

EP08_08 — 🟡 Grayscale Image and Dynamic Thresholding

8.14.8 EP08_08 🟡 Grayscale Image and Dynamic Thresholding

In this exercise, the input image is no longer strictly binary (0/1) but becomes a grayscale image (\(8\) bits, \(0\dots255\)), where objects have an intermediate average intensity over a dark background (\(0\)), in addition to salt-and-pepper noise scattered throughout the entire image.

8.14.8.1 📋 Implementation Guidelines

  1. Input: read \(H\) and \(W\) on the first line, followed by the \(H\) lines with integer values from \(0\) to \(255\) in an \(H \times W\) matrix.
  2. Preprocessing:
  • Apply a Median filter (\(3 \times 3\)) to remove salt-and-pepper noise while keeping edges sharp.
  • Apply Otsu’s thresholding (or a fixed threshold \(T = 60\)) to binarize the clean image.
  1. Measurement and Output: extract the contour of the objects, compute the geometric metrics (area, perimeter, cx, cy, x, y, w, h, circularity, solidity), and sort the objects by bbox[0] (with bbox[1] as a tiebreaker). Reassign id from \(1\) to \(N\) and print the table.
    • For sorting, use medidas.sort(key=lambda m: (m['bbox'][1], m['bbox'][0])), with medidas = mm.measure(img).

8.14.8.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
…
(binary image containing a square and a circle)
id area perimeter cx cy x y w h circularity solidity vertices
1 16.0 16.0 8.0 8.0 6 6 5 5 0.79 1.000 4
2 28.3 18.8 22.5 8.0 19 5 7 7 1.00 1.000 8
🧮 Simulator EP08_08: Salt and Pepper Noise in Grayscale & OpenCV Measurement Median 3x3 → Binarization → Measurement
PROCESSING STAGE
PIXEL MATRIX VIEW
OBJECT MEASUREMENT TABLE (SORTED BY BBOX_X, BBOX_Y)
id area perimeter cx cy x y w h circularity solidity vertices
Figure 8.22: EP08_08 Simulator: Median Filtering in Grayscale and Object Measurement with OpenCV
%%writefile EP08_08.py
# Python code
Overwriting EP08_08.py
TestSuite("EP08_08.py").run()
✔️ EP08_08.cases already exists in casos/
📋 3 case(s) loaded from casos/EP08_08.cases

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