Sub topic 4
Finding contours with cv2.findContours
This chapter assumes you can load and save images with cv2, index NumPy arrays, and know what grayscale and binary images are. It uses the Python API of OpenCV 4. The previous chapter produced a binary image. Here you turn that image into contours.
What a contour is
A contour is a curve that follows the boundary of a connected white region in a binary image. OpenCV stores it as a NumPy array of (x, y) points. cv2.findContours assumes the objects are white (255) on a black (0) background. Any non-zero pixel counts as foreground.
The function does not look at colors or edges. It looks at which pixels are zero and which are not. A bad binary image therefore gives bad contours, whatever you do afterwards.
The call and its return values
import cv2
img = cv2.imread("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)
contours, hierarchy = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
print("contours found:", len(contours))
out = img.copy()
cv2.drawContours(out, contours, -1, (0, 255, 0), 2)
cv2.imwrite("contours.png", out)This example assumes dark shapes on a light background. THRESH_BINARY_INV flips the polarity so the shapes become white. The call takes three arguments:
- image: an 8-bit single-channel image. Use a binary image, not a color one.
- mode: the retrieval mode. It decides which contours you get and whether you get their nesting relationships.
- method: the approximation method. It decides how many points are stored per contour.
It returns two values in OpenCV 4:
- contours: a tuple of arrays. Each array has shape
(N, 1, 2)and dtypeint32, where N is the number of points. - hierarchy: an array of shape
(1, num_contours, 4), orNonewhen no contours are found.
The extra middle dimension in (N, 1, 2) is a leftover of OpenCV's C++ design. To get a plain (N, 2) array of points, use c.reshape(-1, 2) or c[:, 0, :].
Version differences
Older versions return three values. OpenCV 3 returns image, contours, hierarchy, where image is a copy of the input. OpenCV 2 and 4 return two values. If you see ValueError: not enough values to unpack or too many values to unpack, check cv2.__version__ first.
For code that must run on several versions, read the last two items of the returned tuple:
result = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contours, hierarchy = result[-2:]Input requirements and polarity
The input must be single-channel. A three-channel image raises an error. Binary values of 0 and 255 are the normal case, but any non-zero value is treated as foreground.
Polarity is the most common source of wrong results. If your objects are black on a white page, the white page is the foreground. Then findContours returns one large contour around the whole image border, plus holes where your objects are. Fix this in the threshold step, either by choosing THRESH_BINARY_INV or by inverting with cv2.bitwise_not(binary).
A quick check is to count the contours and measure the largest one:
contours, _ = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
h, w = binary.shape
biggest = max(contours, key=cv2.contourArea, default=None)
if biggest is not None and cv2.contourArea(biggest) > 0.9 * h * w:
print("Largest contour covers the whole image: polarity is probably inverted")Retrieval modes
The retrieval mode controls which contours are returned and how the hierarchy is filled. This chapter introduces the choice. A later chapter covers reading the hierarchy in detail.
| Mode | Returns | Hierarchy |
|---|---|---|
| `RETR_EXTERNAL` | Only the outermost contours. Holes and nested shapes are ignored. | Present, but parent and child links are not meaningful. |
| `RETR_LIST` | All contours, with no relationships. | Present, but parent and child links are -1. |
| `RETR_CCOMP` | All contours in two levels: outer boundaries and the holes inside them. | Two-level. |
| `RETR_TREE` | All contours with the full nesting tree. | Full parent and child links. |
Use RETR_EXTERNAL when you only want to count or measure separate objects. Use RETR_TREE when you need to tell a ring from a disc, or detect a shape inside another shape. A ring (like the letter O or a washer) produces two contours with RETR_TREE and RETR_LIST: the outer edge and the inner edge of the hole. It produces one with RETR_EXTERNAL.
Each hierarchy row has four numbers: [next, previous, first_child, parent]. A value of -1 means no such contour.
contours, hierarchy = cv2.findContours(binary, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# hierarchy has shape (1, N, 4): [next, previous, first_child, parent]
for i, c in enumerate(contours):
parent = hierarchy[0][i][3]
kind = "outer" if parent == -1 else f"inside contour {parent}"
print(i, kind, cv2.contourArea(c))Approximation methods
The method controls how many points are kept along each boundary.
CHAIN_APPROX_NONEstores every boundary point. A rectangle of 200 by 100 pixels gives about 600 points.CHAIN_APPROX_SIMPLEremoves points in the middle of straight horizontal, vertical and diagonal segments. The same rectangle gives 4 points.
CHAIN_APPROX_SIMPLE uses less memory and is the usual default. Use CHAIN_APPROX_NONE when you need every boundary pixel, for example to build a mask or to compute a precise curvature. You can see the difference directly:
import cv2
import numpy as np
canvas = np.zeros((200, 300), dtype=np.uint8)
cv2.rectangle(canvas, (50, 50), (250, 150), 255, -1)
for name, method in [("NONE", cv2.CHAIN_APPROX_NONE), ("SIMPLE", cv2.CHAIN_APPROX_SIMPLE)]:
cs, _ = cv2.findContours(canvas, cv2.RETR_EXTERNAL, method)
print(name, len(cs[0]))This prints about 600 points for NONE and 4 for SIMPLE. Curved shapes keep more points under SIMPLE, because their boundaries have no long straight runs.
How the contours are produced
OpenCV uses a border-following algorithm (Suzuki and Abe, 1985). It scans the image row by row. When it meets a foreground pixel next to a background pixel, it walks along that boundary until it returns to the start. It records the points on the way.
Edge cases
- Image border. A shape that touches the border of the image still gets a contour, but it follows the shape only inside the image. Its measurements describe the visible part. A common fix is to pad the binary image with a one-pixel black border using
cv2.copyMakeBorder. - Single-pixel and thin objects. A one-pixel object yields a contour with one point. Its area is 0. A thin line gives a contour that goes out and back along the line, so its area is also near 0.
- Noise. Isolated white pixels each become a tiny contour. Blur before thresholding, clean the mask with morphology, and filter by area afterwards.
- No contours. The hierarchy is
None, andcontoursis an empty tuple. Code such ashierarchy[0]then fails withTypeError. Checkif hierarchy is not Nonefirst. - Input is modified. In OpenCV 3.2 and later, the input image is no longer modified. Older versions overwrote it, so copy the image first if your code must run on very old versions.
- Order. The order of the contours is not a spatial order. Sort them yourself if you need left-to-right or top-to-bottom order.
Sorting by position uses the bounding rectangle:
contours, _ = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contours = sorted(contours, key=lambda c: cv2.boundingRect(c)[0])
for c in contours:
print(cv2.boundingRect(c))Choosing settings
| Goal | Mode | Method |
|---|---|---|
| Count separate objects | `RETR_EXTERNAL` | `CHAIN_APPROX_SIMPLE` |
| Find holes in objects | `RETR_CCOMP` or `RETR_TREE` | `CHAIN_APPROX_SIMPLE` |
| Detect nested shapes | `RETR_TREE` | `CHAIN_APPROX_SIMPLE` |
| Pixel-exact boundary | any | `CHAIN_APPROX_NONE` |
Exercise
You run contours, hierarchy = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) on a photo of black coins on a white table. It returns one contour, and its area is almost the whole image. What is the likely cause, and how do you fix it?
Show answer
The polarity is inverted. The white table is the foreground, so the contour is the image border, and the coins are holes that RETREXTERNAL ignores. Fix the threshold with THRESHBINARYINV, or invert the mask with cv2.bitwisenot, so the coins become white.
Exercise
A filled 200 by 100 rectangle is drawn on a black canvas. How many points does its contour have with CHAINAPPROXSIMPLE, and why is the count different with CHAINAPPROXNONE?
Show answer
It has 4 points, the corners. CHAINAPPROXSIMPLE drops points in the middle of straight segments. CHAINAPPROXNONE keeps every boundary pixel, which gives about 600 points (the perimeter of the rectangle).
Exercise
A white ring (a disc with a hole) is on a black background. How many contours does RETREXTERNAL return, and how many does RETRTREE return? Which contour in the RETR_TREE result has a parent?
Show answer
RETREXTERNAL returns 1 contour, the outer edge. RETRTREE returns 2: the outer edge and the edge of the hole. The hole contour has the outer edge as its parent, so its hierarchy entry has a parent index other than -1.