पाठ 6 / 26
Thresholding and Connected Components
Separate foreground from background and count objects.
Otsu, morphology, labelling
Thresholding turns a grayscale image into a binary mask. Otsu's method chooses the threshold automatically by best separating the two intensity groups. Morphological operations clean the mask: closing fills small holes, opening removes specks. Connected-component labelling then assigns an id to each separate blob so you can count objects and measure their area or shape. This works well with controlled lighting (inspection, lab images); touching objects merge, which needs watershed or learned segmentation.
Counting coins with Otsu and labelling, run
I ran this on CPU with Python 3, OpenCV 5.0.0, scikit-image 0.26.0, PyTorch 2.14.1 and torchvision 0.29.1, using scikit-image's bundled sample photos and torchvision's published pretrained weights. Otsu picks a threshold of 107 for the bundled coins photo, and labelling finds 22 objects. Most areas are 1,100 to 3,100 pixels, but one region of 12,849 pixels is several coins merged together: classical methods struggle when objects touch.
from skimage import data, filters, measure, morphology
img = data.coins()
t = filters.threshold_otsu(img)
mask = img > t
mask = morphology.remove_small_objects(morphology.binary_closing(mask, morphology.disk(3)), max_size=149)
labels = measure.label(mask)
regions = [r for r in measure.regionprops(labels)]
print("Otsu threshold:", round(float(t), 1))
print("objects found:", len(regions))
areas = sorted(int(r.area) for r in regions)
print("smallest areas:", areas[:3], "| largest:", areas[-3:])
Output:
Otsu threshold: 107.0 objects found: 22 smallest areas: [1104, 1130, 1135] | largest: [2606, 3113, 12849]
Control the lighting
For inspection systems, consistent lighting and backgrounds make simple thresholding far more reliable than any algorithm tweak.
त्वरित जाँच: Why did one coin region come out much larger than the others?
- Labels were assigned randomly
- Otsu always fails
- The image is in colour
- Several touching coins merged into one connected component
Answer
Several touching coins merged into one connected component — Touching objects need separation methods.