Sub topic 2
Retrieval Modes and Reading the Hierarchy
This chapter assumes you can load a binary image with cv2, that you know what a contour is, and that you can read NumPy arrays. You should already have a clean white-on-black mask, as produced in the earlier thresholding chapter.
Choosing a retrieval mode
cv2.findContours takes a retrieval mode that decides which contours it returns and whether it records their nesting:
RETR_EXTERNALreturns only the outermost contours. Holes are ignored.RETR_LISTreturns every contour with no nesting information.RETR_CCOMPreturns every contour organized into two levels: outer boundaries and holes.RETR_TREEreturns every contour with the full nesting tree.
Reading the hierarchy
With RETR_TREE, the hierarchy array has one row per contour. Each row holds four indexes: [next, previous, first_child, parent]. A parent value of -1 means the contour has no parent, so it is an outer shape.
import cv2
img = cv2.imread("shapes.png")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
_, binary = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)
contours, hierarchy = cv2.findContours(binary, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
hierarchy = hierarchy[0]
kept = []
for i, c in enumerate(contours):
area = cv2.contourArea(c)
if area < 100:
continue
peri = cv2.arcLength(c, True)
m = cv2.moments(c)
cx, cy = int(m["m10"] / m["m00"]), int(m["m01"] / m["m00"])
x, y, w, h = cv2.boundingRect(c)
(ex, ey), radius = cv2.minEnclosingCircle(c)
parent = hierarchy[i][3]
print(f"{i}: parent={parent} area={area:.0f} perim={peri:.1f} "
f"centroid=({cx},{cy}) box=({x},{y},{w},{h}) r={radius:.1f}")
kept.append(c)
out = img.copy()
cv2.drawContours(out, kept, -1, (0, 255, 0), 2)
cv2.imwrite("kept.png", out)Filtering by area keeps the original index i, so the parent lookup still points at the correct row.
Measuring and bounding
cv2.contourAreagives the enclosed area in pixels.cv2.arcLength(c, True)gives the perimeter of a closed contour.cv2.momentsgives the centroid fromm10,m01andm00.cv2.boundingRectgives an upright rectangle.cv2.minAreaRectgives a rotated one.cv2.minEnclosingCirclegives the smallest circle that contains the contour.cv2.fitEllipsefits an ellipse and needs at least five points.
> Note: m00 is the contour area. A zero value causes a division by zero, so filter out empty contours before you compute centroids.
Exercise
Exercise
A contour has parent equal to -1. What does that tell you about it, and which retrieval mode would have dropped it from a ring-shaped mask?
Show answer
It is an outer contour with no enclosing shape. RETR_EXTERNAL would keep it, but it would drop any child contour, such as the hole inside a ring.