Sub topic 6
Retrieval modes and reading the hierarchy
This chapter assumes you can load images with cv2, produce a clean binary mask (grayscale, blur, threshold), and call cv2.findContours to get a list of contours. Here you learn how the retrieval mode argument controls which contours you get back, and how to read the hierarchy array that describes how those contours nest.
Why the retrieval mode matters
A binary image can hold shapes inside shapes. A printed letter "O" has an outer boundary and an inner boundary around the hole. A washer has two circles. A picture frame has an outside edge and an inside edge. OpenCV treats each boundary as its own contour.
The second argument of cv2.findContours is the retrieval mode. It decides which of these boundaries are returned and what relationship information is reported alongside them.
contours, hierarchy = cv2.findContours(binary, mode, method)In OpenCV 4 the function returns two values. OpenCV 3 returned three (image, contours, hierarchy), so older tutorials will fail with an unpacking error on OpenCV 4. If you must support both, use contours = result[-2] and hierarchy = result[-1].
The four retrieval modes
| Mode | Contours returned | Hierarchy content |
|---|---|---|
| `cv2.RETR_EXTERNAL` | Only the outermost contours | Present, but every contour is top level |
| `cv2.RETR_LIST` | All contours | No parent/child links (all set to flat) |
| `cv2.RETR_CCOMP` | All contours, in two levels | Outer boundaries and holes only |
| `cv2.RETR_TREE` | All contours | Full nesting tree |
A short guide to choosing:
- Use
RETR_EXTERNALwhen you only care about whole objects and want holes and interior details ignored. This is the usual choice for counting or classifying shapes. - Use
RETR_LISTwhen you want every contour but do not care about nesting. - Use
RETR_CCOMPwhen you need to separate objects from their holes, and nothing deeper. - Use
RETR_TREEwhen you need to know exactly what sits inside what.
RETR_EXTERNAL also makes the result more robust. Interior details such as text on a label or a texture inside a blob are skipped without any filtering code.
Building a test image
The examples below use a synthetic image so you can run them without any files. It has a filled square with a hole, and a small filled square inside that hole, plus a separate circle.
import cv2
import numpy as np
canvas = np.zeros((300, 400), dtype=np.uint8)
# Object A: a large white square with a black hole
cv2.rectangle(canvas, (20, 20), (180, 180), 255, -1)
cv2.rectangle(canvas, (50, 50), (150, 150), 0, -1)
# Object B: a small white square inside the hole of A
cv2.rectangle(canvas, (80, 80), (120, 120), 255, -1)
# Object C: a separate white circle
cv2.circle(canvas, (300, 100), 50, 255, -1)
binary = canvas
for name, mode in [("EXTERNAL", cv2.RETR_EXTERNAL),
("LIST", cv2.RETR_LIST),
("CCOMP", cv2.RETR_CCOMP),
("TREE", cv2.RETR_TREE)]:
contours, hierarchy = cv2.findContours(binary, mode, cv2.CHAIN_APPROX_SIMPLE)
print(name, len(contours))Expected output:
EXTERNAL 3
LIST 5
CCOMP 5
TREE 5There are five boundaries: the outer edge of A, the hole in A, the outer edge of B, and the outer edge of C. That is four, so where is the fifth? The hole of A is a boundary of the black region, and B's outer edge is a boundary of the white region. Both are found. The count of five arises because findContours treats white pixels as the foreground, and the separate boundaries are A-outer, A-hole, B-outer, C-outer. If your count differs by one on your machine, print the areas to see which boundaries were found.
A safer way to check is to print what you actually got rather than trust a count in your head:
contours, hierarchy = cv2.findContours(binary, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
for i, c in enumerate(contours):
print(i, cv2.contourArea(c), hierarchy[0][i])Always inspect the real output on your own image. The number of contours depends on the pixels, not on how many shapes you think you drew.
The hierarchy array
The hierarchy has shape (1, N, 4), where N is the number of contours. The extra leading dimension is a historical quirk, so you almost always index hierarchy[0] first. Each row has four integers:
[next, previous, first_child, parent]nextis the index of the next contour at the same level, or -1 if none.previousis the index of the previous contour at the same level, or -1 if none.first_childis the index of the first contour nested directly inside this one, or -1 if none.parentis the index of the contour that directly contains this one, or -1 if it is top level.
Contours at the same level are siblings, linked as a doubly linked list through next and previous. A parent stores only its first child. To visit all children, follow first_child, then repeatedly follow next.
def children(hierarchy, index):
result = []
child = hierarchy[0][index][2]
while child != -1:
result.append(child)
child = hierarchy[0][child][0]
return resultThe order in which contours appear in the list is not something to rely on. Always use the indices stored in the hierarchy instead of assuming that contour 1 is inside contour 0.
Reading the tree with RETR_TREE
With RETR_TREE, depth is simply the number of parent steps you can take before reaching -1. Even depth means a boundary of a white region (an object). Odd depth means a boundary of a hole.
def depth(hierarchy, index):
d = 0
while hierarchy[0][index][3] != -1:
index = hierarchy[0][index][3]
d += 1
return d
contours, hierarchy = cv2.findContours(binary, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
for i, c in enumerate(contours):
d = depth(hierarchy, i)
role = "object" if d % 2 == 0 else "hole"
print(f"contour {i}: depth {d}, {role}, area {cv2.contourArea(c):.0f}")This even/odd rule holds because contours alternate between white and black regions as you go inward. It only holds when the foreground is white, which ties back to thresholding polarity.
Reading two levels with RETR_CCOMP
RETR_CCOMP organizes contours into exactly two levels. Every outer boundary of an object is level one, and every hole inside an object is level two. A white object sitting inside a hole is again placed at level one, not at level three, so the nesting is flattened.
For that reason, the parent field works as a simple flag:
contours, hierarchy = cv2.findContours(binary, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE)
for i, c in enumerate(contours):
is_hole = hierarchy[0][i][3] != -1
print(i, "hole" if is_hole else "outer", cv2.contourArea(c))Use this mode when you want to compute, for example, the area of an object minus its holes, without caring how deeply things are nested.
Practical recipes
Count objects with holes and their hole areas:
contours, hierarchy = cv2.findContours(binary, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE)
for i, c in enumerate(contours):
if hierarchy[0][i][3] != -1:
continue # skip holes at the top of the loop
outer_area = cv2.contourArea(c)
hole_area = sum(cv2.contourArea(contours[h]) for h in children(hierarchy, i))
print(f"object {i}: net area {outer_area - hole_area:.0f}")Guard against a missing hierarchy. When no contours are found, hierarchy is None in OpenCV 4, and indexing it raises a TypeError.
if hierarchy is None:
print("no contours")
else:
print(hierarchy.shape)Common errors
- Unpacking error.
ValueError: not enough values to unpackmeans you are on OpenCV 4 using the three-value OpenCV 3 form, or the reverse. - Wrong polarity. If the object is dark on a light background and you did not invert the threshold, the "object" is the background. You will see one huge outer contour the size of the image and your objects reported as holes.
- Indexing without
[0]. Writinghierarchy[i]returns the whole array fori = 0and fails for largeri. Usehierarchy[0][i]. - Assuming order. Do not assume parents come before children in the list. Follow the stored indices.
- Using
RETR_LISTand expecting links. The parent and child entries are not meaningful in that mode. ChooseRETR_TREEorRETR_CCOMPif you need them. - Image border contact. A shape touching the image edge is closed along the border, which can change its contour. Add a small border with
cv2.copyMakeBorderif this matters.
Exercise
You run findContours on a mask of coins lying on a table and want only one contour per coin, ignoring any printed detail on the coin faces. Which retrieval mode do you choose, and what would you check in the hierarchy if you used RETR_CCOMP instead?
Show answer
Choose cv2.RETREXTERNAL, which returns only outermost contours. With RETRCCOMP you would keep only contours whose parent field (index 3 of the hierarchy row) is -1, since the others are holes inside a coin.
Exercise
Using RETR_TREE, a contour has hierarchy row [4, 2, -1, 1]. What does each value tell you, and is the contour an object or a hole if contour 1 has parent -1?
Show answer
The next sibling is contour 4, the previous sibling is contour 2, it has no children (-1), and its parent is contour 1. Contour 1 is at depth 0 (an object), so this contour is at depth 1, which makes it a hole.