smartyfy.mrindigi.com

Python Master Course V2 — 164. Thresholding, Segmentation and Morphology

Purpose and learning outcomes

Segmentation assigns a label to each pixel. For a binary task, the first question is what True means: here it means a synthetic foreground object. You will threshold an image, clean the mask with morphology, identify connected components, and measure intersection over union against generated ground truth. Every operation has a declared spatial convention and a visible cost.

  • Create binary masks with explicit foreground conventions
  • Apply erosion, dilation and connected-component analysis
  • Measure segmentation overlap and explain threshold limits

Prerequisites

  • 161–163: images and filtering

Environment and execution

Use a project-specific virtual environment with a currently supported Python 3 release compatible with the packages below. Python 3.11 or 3.12 is a practical starting point. Run shell commands in a terminal, then run the Python blocks in order in one script or notebook kernel. They use only included data and local CPU computation. No account, API key, camera, or external dataset is required. Record the installed package versions with python -m pip freeze when you save your results; a random seed does not guarantee identical numerical behavior across library versions.

python -m venv .venv
# macOS/Linux: source .venv/bin/activate
# Windows PowerShell: .venv\Scripts\Activate.ps1
python -m pip install numpy scipy

Understand the model and its assumptions

Thresholding converts intensity into a foreground decision. A global threshold assumes foreground and background are distinguishable on one scale across the whole image. Uneven illumination, shadows, or overlapping intensity distributions can violate that assumption. A threshold that succeeds on a black background may fail on a bright gradient even when the object itself has not changed.

Binary erosion keeps a foreground pixel only when its required neighborhood fits inside foreground. Dilation expands foreground according to the structuring element. Opening applies erosion then dilation and can remove small isolated regions; closing applies dilation then erosion and can fill small gaps. These operations are geometric assumptions, not universal repairs. A structure larger than a legitimate thin object can erase it.

Connectivity determines what counts as one object. Four-connectivity links horizontal and vertical neighbors; eight-connectivity also links diagonals. A pair of diagonal pixels can be one component under one policy and two under another. scipy.ndimage.label treats nonzero input as foreground, so use a Boolean mask intentionally rather than passing a grayscale image whose background is mostly nonzero.

Intersection over union, or IoU, divides the number of pixels in both prediction and truth by the number in either. It penalizes extra and missing foreground. Empty prediction and empty truth produce a zero denominator; this lesson explicitly assigns them IoU one because they agree completely, while also reporting whether either mask is empty. For datasets with many empty images, summarize those cases separately so perfect empty-image scores do not hide poor object segmentation.

Worked example: build it in stages

Generate two circular masks from coordinate grids, blend them into a gradient background, and add seeded noise. Apply a fixed intensity threshold, a three-by-three opening, and a minimum-area component filter. Component zero is background and must never be retained as an object. Compare raw and cleaned IoU and inspect component areas rather than assuming every cleanup step improves the result.

import numpy as np
from scipy import ndimage

rng = np.random.default_rng(11)
y, x = np.mgrid[:48, :64]
truth = ((x-19)**2 + (y-24)**2 <= 9**2) | ((x-45)**2 + (y-22)**2 <= 7**2)
background = 0.12 + 0.18 * x / 63
image = np.where(truth, 0.8, background)
image = np.clip(image + rng.normal(0, 0.09, image.shape), 0, 1)
raw = image > 0.5
structure = ndimage.generate_binary_structure(2, 1)
opened = ndimage.binary_opening(raw, structure=structure)
labels, count = ndimage.label(opened, structure=structure)
areas = np.bincount(labels.ravel())
keep = np.flatnonzero(areas >= 20)
keep = keep[keep != 0]
cleaned = np.isin(labels, keep)

def iou(prediction, target):
    prediction, target = np.asarray(prediction), np.asarray(target)
    if prediction.shape != target.shape or prediction.dtype != bool or target.dtype != bool:
        raise ValueError("matching Boolean masks required")
    intersection = np.count_nonzero(prediction & target)
    union = np.count_nonzero(prediction | target)
    return intersection / union if union else 1.0

print("raw/cleaned IoU:", iou(raw, truth), iou(cleaned, truth))
print("components before area filtering:", count)
print("retained areas:", areas[keep].tolist())
assert cleaned.dtype == bool
assert not np.any(cleaned & (labels == 0))
assert iou(truth, truth) == 1.0

What the output means

The script reports measured raw and cleaned IoU, component count, and retained areas. No improvement is guaranteed: opening may remove noise but also remove true boundary pixels. Comparing the two scores makes that tradeoff explicit. The self-comparison IoU is exactly one. The background assertion verifies that a large background region cannot accidentally pass the area threshold and become foreground.

Guided lab and acceptance checks

Create development scenes with one thin rectangle, two touching disks, and a brighter background. Keep a copy of every truth mask. Compare opening with closing and explain the geometric change before inspecting the score. Select a threshold and structure from development scenes, then assess fresh noise seeds and a held-out illumination range.

Acceptance requires declared foreground meaning, threshold, connectivity, structuring element, minimum area, and empty-mask convention. Report pixel IoU separately from object count. A mask can achieve high overlap while merging two objects, which may be unacceptable for counting or inspection even when segmentation looks good.

Common mistakes and repairs

Do not apply connected-component labeling directly to noisy floating intensities. Do not assume morphology respects object identity: dilation can join neighbors and erosion can split bridges. Avoid selecting component zero because its background area is large. Never silently cast a multiclass label image to bool if different nonzero classes must remain distinct.

Questions and answers

Why can opening lower IoU while removing visible speckles?

It may remove more true boundary pixels than false foreground pixels. Visual cleanliness and overlap are different criteria. The appropriate choice depends on whether the downstream task values thin features, object area, separation, or simply a less noisy appearance.

When does connectivity change the answer?

Diagonal contacts are the clearest example. Under four-connectivity diagonal pixels are separate; under eight-connectivity they join. Choose the policy based on geometry and resolution, then keep it consistent in truth generation, component analysis, and evaluation.

Is IoU sufficient for object counting?

No. Two adjacent objects can merge into one component with little change in total foreground area. Counting requires instance-level evidence, such as component matching, in addition to a pixel-level overlap score.

Why define empty-mask behavior explicitly?

The ordinary ratio is undefined when both masks are empty. An application may treat that as perfect agreement or exclude it from foreground IoU. Either choice affects averages, especially when most images contain no object, so the convention must be visible.

Can a global threshold solve uneven illumination?

Only when foreground and background remain separable everywhere. Otherwise consider background correction, local thresholds, or a learned model, and evaluate on held-out lighting conditions. A more complicated method still needs a declared failure policy.

Exercises

1. Demonstrate the difference between four- and eight-connectivity. 2. Check empty-mask and completely missed-object IoU. 3. Explain why minimum-area filtering is a resolution-dependent assumption.

Worked solutions and reasoning

A twenty-pixel object at one resolution can occupy eighty pixels when both image dimensions double. Minimum area should therefore be tied to acquisition scale or normalized physical assumptions, rather than copied blindly between datasets.

diagonal = np.eye(2, dtype=bool)
_, four = ndimage.label(diagonal, structure=ndimage.generate_binary_structure(2, 1))
_, eight = ndimage.label(diagonal, structure=ndimage.generate_binary_structure(2, 2))
assert (four, eight) == (2, 1)
empty = np.zeros((3, 3), dtype=bool)
assert iou(empty, empty) == 1.0
assert iou(empty, np.ones((3, 3), dtype=bool)) == 0.0

Recap

Segmentation combines intensity assumptions with geometry. Thresholds create masks, morphology changes their shapes, connectivity defines objects, and metrics reveal only the properties they measure. Keep these choices explicit and evaluate both empty scenes and difficult foreground cases.

Official references

Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.