Day 10: OpenCV III: contours & morphology
From a binary mask to a usable shape
Yesterday's thresholding and edge detection produce binary masks — but a raw mask is noisy: stray white pixels, small gaps, ragged edges. Today's two tools, contours and morphology, turn a noisy mask into a clean, usable shape — exactly what the Catalog Tool needs between 'background removed' and 'clean cutout'.
Contours
A contour is a curve joining the continuous boundary points of a connected white region in a binary mask — practically, 'trace the outline of this blob'. cv2.findContours returns every such boundary in an image, which you can then filter (by area, by shape) to find the one that's actually the garment and discard small noise blobs.
contours, _ = cv2.findContours(binary_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# keep only the largest contour by area — assume it's the garment, discard noise
largest = max(contours, key=cv2.contourArea)
x, y, w, h = cv2.boundingRect(largest) # a tight bounding box around itMorphology: erosion, dilation, opening, closing
Morphological operations reshape a binary mask using a small structuring element (like a kernel, but for shape rather than intensity). Erosion shrinks white regions (eats away boundaries — good for removing tiny noise specks). Dilation grows white regions (fills small gaps and holes). Opening (erode then dilate) removes small noise while roughly preserving the main shape's size. Closing (dilate then erode) fills small holes inside the shape without growing its outer boundary.
kernel = np.ones((5, 5), np.uint8)
# opening: erase small noise specks outside the garment
opened = cv2.morphologyEx(binary_mask, cv2.MORPH_OPEN, kernel)
# closing: fill small holes inside the garment silhouette
cleaned = cv2.morphologyEx(opened, cv2.MORPH_CLOSE, kernel)A mental shortcut
Opening removes things smaller than the kernel that stick OUT (noise specks). Closing fills things smaller than the kernel that dip IN (small holes). Same two primitives — erode and dilate — just run in opposite order.
Key terms
- Contour
- A curve tracing the continuous boundary of a connected region in a binary mask.
- Erosion
- A morphological operation that shrinks white regions in a binary mask, removing small protrusions and noise.
- Dilation
- A morphological operation that grows white regions, filling small gaps and holes.
- Opening / Closing
- Erosion-then-dilation (removes small noise) and dilation-then-erosion (fills small holes), respectively.
A garment mask has a few small holes inside the silhouette (e.g. from a pattern that confused the threshold) but no stray noise outside it. Which single operation fixes it?