Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 54 ยท Edges, Contours and Shapes

Finding and Drawing Contours

Learn cv2.findContours: retrieval modes, approximation methods, the hierarchy array, drawContours, and how contours relate to connected components.

A contour is the outline of an object: an ordered list of boundary points that you can walk around. Once you have contours you can count objects, measure their size, find the biggest one, crop it out or classify its shape. That is why cv2.findContours sits behind so many OpenCV projects: document scanners, coin counters, color trackers and shape detectors all start by finding contours.

This lesson shows how to call findContours correctly, what its modes and hierarchy mean, and how to draw the result. The real calls are read-only code here. To see how the idea works inside, the runnable stand-ins label connected regions and rebuild the nesting tree (outer shapes, holes, shapes inside holes) with plain NumPy.

opencv-python cannot run in the browser, so cv2.findContours and cv2.drawContours appear in read-only blocks. The stand-ins use connected-component labeling, a close relative that answers "which pixels belong together?". OpenCV actually follows borders (the Suzuki-Abe algorithm) and returns ordered boundary points, which labeling does not, so the stand-ins show the idea and the structure, not the exact algorithm.

The standard recipe

Contours are found on a binary image: white (non-zero) objects on a black background. The usual pipeline converts to gray, thresholds or runs Canny (see Thresholding and Canny Edge Detection), and then calls findContours:

Python
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_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
print(len(contours), "objects")

out = img.copy()
cv2.drawContours(out, contours, -1, (0, 255, 0), 2)   # -1 = all contours

Two points trip people up. First, the objects must be white. If your shapes are dark on a light page, invert the threshold (as above with THRESH_BINARY_INV), or you will get the outline of the page background instead. Second, the return values depend on the OpenCV version: OpenCV 4 returns (contours, hierarchy), while OpenCV 3 returned (image, contours, hierarchy). If you ever see ValueError: too many values to unpack, you are mixing versions. Check with cv2.version and write for 4.x.

Each contour is a NumPy array of shape (N, 1, 2) and dtype int32: N points, each stored as [[x, y]]. Remember the coordinate order from Images Are NumPy Arrays: contour points are (x, y), but image indexing is [row, col], i.e. [y, x].

A contour in one picture

White shape Object on black.
Boundary points Ordered around the edge.
A list One array per object.
1 / 2

Retrieval modes

The second argument decides which contours you get and how much hierarchy information comes with them:

  • cv2.RETR_EXTERNAL: only the outermost outline of each object. Holes and shapes inside holes are ignored. Best when you just want to count or measure objects.
  • cv2.RETR_LIST: every contour (outer outlines and hole outlines), as a flat list with no parent-child relationships.
  • cv2.RETR_CCOMP: every contour, organized in two levels: outer boundaries at level 1, holes at level 2.
  • cv2.RETR_TREE: every contour with the complete tree of nesting (object contains hole, hole contains object, and so on).

Approximation methods

The third argument controls how many points are stored. cv2.CHAIN_APPROX_NONE keeps every boundary pixel, so a 100 by 100 square needs about 400 points. cv2.CHAIN_APPROX_SIMPLE drops redundant points on straight horizontal, vertical and diagonal runs, so the same square needs only its 4 corners. Use SIMPLE unless you need every pixel; it saves memory and speeds up later steps. There are also the Teh-Chin variants (CHAIN_APPROX_TC89_L1, CHAIN_APPROX_TC89_KCOS), which are rarely needed.

Hierarchy

When you use RETR_CCOMP or RETR_TREE, hierarchy has shape (1, N, 4): for each contour four indices [next, previous, first_child, parent]. Each index points into the contours list, and -1 means "none". So a contour with parent -1 is at the top level, and a contour with first child -1 has no holes or inner shapes. A typical loop that keeps only the holes of an object looks like this:

Python
contours, hierarchy = cv2.findContours(binary, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE)
for i, cnt in enumerate(contours):
    is_hole = hierarchy[0][i][3] != -1       # has a parent -> it is a hole
    color = (0, 0, 255) if is_hole else (0, 255, 0)
    cv2.drawContours(out, contours, i, color, 2)

Think of the hierarchy as the nesting of a letter "B": the letter's outline contains two holes, and each hole is a child of that outline.

Connected components: the stand-in

Before looking at borders, there is an easier question: which foreground pixels form one object? Pixels that touch form a connected component, and labeling them is a flood fill. The two common definitions of "touch" are 4-connectivity (up, down, left, right) and 8-connectivity (also the diagonals). The choice changes the number of objects, as the first stand-in shows:

Python Labeling connected regions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

With 4-connectivity the staircase of pixels leading away from the 3x3 block falls apart into separate pieces (5 regions); with 8-connectivity the diagonal steps link up and the same picture contains 3 objects. OpenCV's findContours treats the foreground as 8-connected, and cv2.connectedComponents lets you choose with its connectivity argument. Note how the printed bounding box lists x first and y second, the same order contours use. The label map also shows the downside of labeling compared with contours: it gives you every pixel of an object, but not an ordered outline.

Nesting: objects, holes, and shapes inside holes

The interesting part of findContours is the hierarchy. You can rebuild it with the trick that foreground and background are mirror images: label objects with 8-connectivity and background pieces with 4-connectivity (this pairing avoids paradoxes where an object and the background would both pass through the same diagonal gap). The background piece that touches the image border is the root. Whatever touches it is a top-level object, whatever touches that object from the inside is a hole, and so on:

Python Rebuilding the contour hierarchy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The tree reads like RETR_TREE: the outside background has three children, the frame (object 1, area 56) and two blobs. The frame contains one hole (background 6), and inside that hole sits the single dot, object 3. RETR_EXTERNAL would report only the three top-level objects; RETR_CCOMP would add the hole as a level-2 contour, and the dot would again appear at level 1. The last lines count boundary pixels, those object pixels that touch the background; a contour is essentially that boundary, listed in walking order. For the frame, 52 of its 56 pixels are on the boundary (outer edge 32, hole edge 20).

Drawing contours

cv2.drawContours(image, contours, contourIdx, color, thickness) draws on the image in place. A contourIdx of -1 draws all contours; a positive number draws one. A thickness of -1 (or cv2.FILLED) fills the inside, which is a handy way to create a mask of an object for the operations in Arithmetic, Bitwise Ops and Masking:

Python
mask = np.zeros(gray.shape, dtype=np.uint8)
cv2.drawContours(mask, [largest], -1, 255, thickness=cv2.FILLED)
cutout = cv2.bitwise_and(img, img, mask=mask)

Note that the contours argument must be a list of contours, so a single contour is passed as [cnt]. Choosing the biggest object is a one-liner: largest = max(contours, key=cv2.contourArea), which the next lesson explains.

Common pitfalls

  • Objects dark on light: invert the threshold, or findContours outlines the background.
  • Noise: tiny specks become tiny contours. Clean the mask with morphology and drop contours whose area is below a limit.
  • Canny edges: an edge map can leave gaps, so objects do not close. Dilate the edges slightly before findContours.
  • contours is a tuple in OpenCV 4.x, not a list; convert with list(contours) if you need to sort or modify it.
  • Coordinates are (x, y); image indexing is img[y, x].

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which retrieval mode returns only the outermost outline of each object?

    RETR_EXTERNAL ignores holes and inner shapes and returns only the outer boundaries. The other modes also return inner contours.
  2. 2. In OpenCV 4, what does cv2.findContours return?

    OpenCV 4 returns two values, contours and hierarchy. OpenCV 3 returned three, which is why mixed-up code fails with an unpacking error.
  3. 3. A hierarchy entry is [3, 1, -1, 0]. What does the -1 in third position say?

    The four values are [next, previous, first_child, parent]. A -1 in the first-child position means the contour has no holes or inner shapes; here its parent is contour 0.
  4. 4. Your shapes are black on a white sheet and findContours returns one huge contour. What is the likely fix?

    findContours looks for non-zero objects on a zero background. With dark shapes on a light page, the white page is treated as the object. THRESH_BINARY_INV swaps the roles.
  5. 5. How is a single contour cnt passed to cv2.drawContours?

    drawContours expects a sequence of contours, so a single contour must be wrapped in a list. (cnt) is just cnt in Python.

Summary

  • Contours are outlines of white objects on black; get a binary image first and invert if needed.
  • OpenCV 4: contours, hierarchy = cv2.findContours(binary, mode, method); each contour has shape (N, 1, 2) in (x, y) order.
  • RETR_EXTERNAL, LIST, CCOMP and TREE choose how much nesting is reported; CHAIN_APPROX_SIMPLE stores only the corner points.
  • hierarchy[0][i] is [next, previous, first_child, parent], with -1 for "none".
  • cv2.drawContours takes a list of contours; thickness -1 fills and makes masks.
  • Connected-component labeling shows the same structure with 4- or 8-connectivity.

Next lesson: Contour Features: Area, Perimeter and Bounding Boxes.