Sub topic 6
Retrieval Modes and Reading the Hierarchy
This chapter assumes that you can load images with OpenCV, work with basic NumPy arrays, and understand grayscale and binary images. A contour is a curve around a connected foreground region. The retrieval mode controls which contours OpenCV returns and how it records their relationships.
Choosing a retrieval mode
cv2.findContours can return only outer boundaries, every boundary, or a complete tree of nested boundaries. The binary image should contain white foreground objects on a black background. OpenCV treats nonzero pixels as foreground.
| Mode | What it returns | Typical use |
|---|---|---|
| `RETR_EXTERNAL` | Only outermost contours | Counting separate objects |
| `RETR_LIST` | All contours without relationships | Measuring every boundary independently |
| `RETR_CCOMP` | Two hierarchy levels | Separating objects and their holes |
| `RETR_TREE` | Full parent-child tree | Nested shapes and multiple holes |
RETR_EXTERNAL ignores holes. For example, a ring produces one contour for its outside boundary, but not the boundary of its inside hole. RETR_TREE returns both boundaries and records that one is inside the other.
The hierarchy array
With RETR_TREE, findContours returns:
contours, hierarchy = cv2.findContours(
binary,
cv2.RETR_TREE,
cv2.CHAIN_APPROX_SIMPLE
)For OpenCV 4, the return value contains two items: the contour list and the hierarchy. Older OpenCV versions returned the modified image as an additional first item.
The hierarchy has shape (1, number_of_contours, 4). For contour index i, the four values are:
next: the next contour at the same level.previous: the previous contour at the same level.first_child: the first contour contained by this contour.parent: the contour that contains this contour.
A value of -1 means that the relationship does not exist.
import cv2
binary = cv2.imread("mask.png", cv2.IMREAD_GRAYSCALE)
if binary is None:
raise FileNotFoundError("Could not read mask.png")
contours, hierarchy = cv2.findContours(
binary,
cv2.RETR_TREE,
cv2.CHAIN_APPROX_SIMPLE
)
if hierarchy is None:
print("No contours found")
else:
tree = hierarchy[0]
for i, contour in enumerate(contours):
next_i, previous_i, child_i, parent_i = tree[i]
level = 0
current = parent_i
while current != -1:
level += 1
current = tree[current][3]
kind = "outer" if parent_i == -1 else f"inside contour {parent_i}"
print(
f"{i}: {kind}, level={level}, "
f"next={next_i}, previous={previous_i}, child={child_i}"
)The level calculation follows parent links until it reaches -1. Level zero contours have no parent and are outer contours. A level-one contour is directly inside an outer contour. Deeper levels occur when shapes contain nested holes or objects.
Inspecting and using relationships
Use RETR_EXTERNAL when holes are irrelevant and you want one contour per visible object. Use RETR_LIST when each boundary should be measured independently but nesting does not matter. Use RETR_CCOMP when you need objects and holes but only need two levels. Use RETR_TREE when nesting itself carries meaning.
A frequent mistake is assuming contour indices represent spatial order. They represent the order chosen by OpenCV's traversal. Use hierarchy links, not index comparisons, to determine containment.
Exercise
Which retrieval mode should you choose to find the outer boundary and every nested hole of each object?
Show answer
Use cv2.RETR_TREE, then inspect each contour's parent and first_child fields.