Sub topic 4
Finding Contours with `cv2.findContours`
This chapter assumes basic Python, NumPy indexing, and OpenCV image loading and saving. You should also know that a grayscale image stores one intensity value per pixel, while a binary image uses background and foreground values.
A contour is a curve that follows the boundary of a connected foreground region. OpenCV represents each contour as an array of points. cv2.findContours extracts these curves from a binary image or edge image.
Prepare the input image
Contours work best when the object and background are separated. In this example, dark shapes appear on a light background, so an inverted threshold makes the shapes white:
import cv2
img = cv2.imread("shapes.png")
if img is None:
raise FileNotFoundError("Could not read shapes.png")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (5, 5), 0)
_, binary = cv2.threshold(
blur,
0,
255,
cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU,
)The result must usually be an 8-bit, single-channel image. OpenCV treats every nonzero pixel as foreground. Therefore, the polarity matters: white objects on black backgrounds are the usual input.
Call `findContours`
The basic call is:
contours, hierarchy = cv2.findContours(
binary,
cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE,
)
print("contours found:", len(contours))
output = img.copy()
cv2.drawContours(output, contours, -1, (0, 255, 0), 2)
cv2.imwrite("contours.png", output)The function returns a list of contours and a hierarchy array. Each contour is an array of points with coordinates in (x, y) order. The image itself is modified during contour extraction in some older OpenCV versions, so pass a copy when the input must be preserved.
Choose retrieval and approximation modes
The retrieval mode controls which contours OpenCV returns.
| Mode | Behavior | Typical use |
|---|---|---|
| `RETR_EXTERNAL` | Returns only outermost contours | Count separate objects |
| `RETR_LIST` | Returns all contours without parent-child relationships | Inspect every boundary |
| `RETR_CCOMP` | Groups contours into two hierarchy levels | Objects and their holes |
| `RETR_TREE` | Returns the complete nesting hierarchy | Objects, holes, and nested regions |
The approximation method controls how many boundary points are stored. CHAIN_APPROX_NONE keeps nearly every boundary pixel. CHAIN_APPROX_SIMPLE removes redundant points along straight sections and is usually sufficient.
Read hierarchy information
With RETR_TREE, each hierarchy row has four values:
[next, previous, first_child, parent]
An index of -1 means that the relationship does not exist. For example, a contour with parent == -1 is an outer contour. A contour with a parent index represents a boundary inside another contour, such as a hole.
contours, hierarchy = cv2.findContours(
binary,
cv2.RETR_TREE,
cv2.CHAIN_APPROX_SIMPLE,
)
if hierarchy is not None:
for index, contour in enumerate(contours):
parent = hierarchy[0][index][3]
label = "outer" if parent == -1 else f"inside contour {parent}"
print(index, label, len(contour))Use RETR_EXTERNAL when internal boundaries are irrelevant. Use RETR_TREE when holes or nested shapes affect the result.
Exercise
Which retrieval mode should you use to count objects while ignoring holes inside them?
Show answer
Use cv2.RETR_EXTERNAL, because it returns only the outermost contour for each object.