Sub topic 7
Drawing and inspecting contours
This chapter covers cv2.drawContours and a few habits for checking what cv2.findContours returned. I assume you can run OpenCV 4 in Python, know that findContours returns a list of point arrays plus a hierarchy array, and can read a NumPy array's shape and dtype. The chapter on retrieval modes covers the hierarchy in detail. Here it only appears as an argument to the drawing call.
Why draw before you measure
Most contour bugs are visible at a glance and nearly invisible in numbers. A contour that traces the background instead of the object, a hole that was never separated, or a hundred tiny noise contours all produce plausible-looking areas. Drawing the result on a copy of the original image is the cheapest check you have. Do it after every change to the preprocessing.
A self-contained test image
The examples below build their own image, so you can run them without any files. The image has two filled rectangles, one of them with a square hole, and two filled circles.
import cv2
import numpy as np
dark = (60, 60, 60)
img = np.full((300, 400, 3), 255, np.uint8)
cv2.rectangle(img, (30, 30), (130, 110), dark, -1)
cv2.circle(img, (250, 80), 50, dark, -1)
cv2.rectangle(img, (60, 160), (200, 270), dark, -1)
cv2.rectangle(img, (90, 190), (170, 240), (255, 255, 255), -1) # hole
cv2.circle(img, (320, 220), 40, dark, -1)
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_TREE, cv2.CHAIN_APPROX_SIMPLE)
print("contours:", len(contours))With RETR_TREE the script finds five contours. Four are outer boundaries, and the fifth is the boundary of the hole.
What a contour looks like in memory
Before drawing, look at the data. A contour is a NumPy array of integer pixel coordinates in (x, y) order, not (row, column).
print(type(contours))
for i, c in enumerate(contours):
print(i, c.shape, c.dtype)
print(contours[0][:3])Each array has shape (N, 1, 2) and dtype int32. The middle axis of length 1 is a historical quirk of the C API. To get a plain (N, 2) array of points, use c.reshape(-1, 2) or c[:, 0, :].
Two details matter here:
- In OpenCV 4,
contoursis a tuple. In older 3.x releasesfindContoursreturned three values, with the image first. If you seeValueError: not enough values to unpack, check your version withcv2.__version__. - The point count depends on the approximation method. With
CHAIN_APPROX_SIMPLE, the filled rectangle has 4 points. A circle has many more, because it has no straight runs to collapse.
The drawContours signature
cv2.drawContours(image, contours, contourIdx, color,
thickness=1, lineType=cv2.LINE_8,
hierarchy=None, maxLevel=INT_MAX, offset=(0, 0))The function draws into image in place and also returns it. It does not create a new image.
| Parameter | Meaning |
|---|---|
| `image` | Destination array. Pass a copy if you want to keep the original. |
| `contours` | A list of contours. Always a list, even for one contour. |
| `contourIdx` | Index of the contour to draw, or `-1` for all of them. |
| `color` | BGR tuple for a 3-channel image, or a single value for grayscale. |
| `thickness` | Line width in pixels. A negative value such as `-1` fills the interior. |
| `lineType` | `cv2.LINE_8` (default), `cv2.LINE_4`, or `cv2.LINE_AA` for smooth edges. |
| `hierarchy` | Optional hierarchy array. Needed for `maxLevel` to have any effect. |
| `maxLevel` | How many levels of nested contours to draw. |
| `offset` | Shift added to every point. Useful when contours came from a cropped region. |
Drawing all, one, or filled
out = img.copy()
cv2.drawContours(out, contours, -1, (0, 255, 0), 2)
cv2.imwrite("all_contours.png", out)
one = img.copy()
cv2.drawContours(one, contours, 2, (0, 0, 255), 3)
cv2.imwrite("contour_2.png", one)
filled = np.zeros_like(img)
cv2.drawContours(filled, contours, -1, (255, 0, 0), -1)
cv2.imwrite("filled.png", filled)The filled version has a gotcha. With a negative thickness, each contour is filled on its own. The hole's contour is filled too, in the same color, so the hole disappears. The next sections show how to handle this.
Drawing a single contour by value
If you already have one contour in a variable c, wrap it in a list.
c = contours[0]
cv2.drawContours(out, [c], 0, (255, 0, 255), 2)Passing c directly, or using index 0 on a list that is not a list of contours, usually raises an assertion error. If you pass a bare (N, 1, 2) array with index -1, OpenCV may treat each row as a separate contour, and you get stray dots or nothing.
Drawing on a grayscale image
If the destination has one channel, only the first value of the color tuple is used. Drawing (0, 255, 0) onto a grayscale image paints with intensity 0, which is black. Convert first when you want colored overlays:
overlay = cv2.cvtColor(gray, cv2.COLOR_GRAY2BGR)
cv2.drawContours(overlay, contours, -1, (0, 255, 0), 2)Using the hierarchy while drawing
Passing hierarchy and maxLevel lets OpenCV draw a contour together with the shapes nested inside it. The index you give is the starting point, and maxLevel is the number of levels to follow.
for i, h in enumerate(hierarchy[0]):
if h[3] == -1: # parent index is -1: an outer contour
cv2.drawContours(out, contours, i, (0, 200, 255), 2,
hierarchy=hierarchy, maxLevel=1)With maxLevel=0, only the contour itself is drawn. With maxLevel=1, its direct children are drawn as well. If you leave out hierarchy, maxLevel is ignored, which is a common reason it seems to do nothing.
To fill shapes while keeping their holes, draw the outer contour filled and then draw the children in the background color. Or build a mask with the same rule:
mask = np.zeros(gray.shape, np.uint8)
for i, h in enumerate(hierarchy[0]):
if h[3] == -1:
cv2.drawContours(mask, contours, i, 255, -1)
else:
cv2.drawContours(mask, contours, i, 0, -1)This simple version handles one level of nesting. Deeper nesting needs a loop that alternates between 255 and 0 by depth.
Labeling contours with their index
Printed indices are hard to connect to shapes on screen. Write the index on the image at the centroid.
labeled = img.copy()
cv2.drawContours(labeled, contours, -1, (0, 255, 0), 2)
for i, c in enumerate(contours):
m = cv2.moments(c)
if m["m00"] == 0:
continue
cx, cy = int(m["m10"] / m["m00"]), int(m["m01"] / m["m00"])
cv2.putText(labeled, str(i), (cx - 8, cy + 6),
cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 0, 255), 2, cv2.LINE_AA)
cv2.imwrite("labeled.png", labeled)The check m["m00"] == 0 matters. A contour with zero area, such as a single point or a one-pixel line, would otherwise cause a division by zero.
The label text is red on a dark shape, so use a light shape or a white text color if you cannot read it. The hole's label lands in the middle of the white square, inside its parent.
Plotting the individual points
To see what CHAIN_APPROX_SIMPLE did to a contour, draw each stored point as a dot.
dots = img.copy()
for c in contours:
for (x, y) in c[:, 0, :]:
cv2.circle(dots, (int(x), int(y)), 3, (0, 0, 255), -1)
cv2.imwrite("points.png", dots)Rectangles show only their corners, while circles show many points along the curve. Switch the approximation to CHAIN_APPROX_NONE and rerun to see every boundary pixel.
Reading values from inside a contour
A filled mask lets you ask what is inside a contour. cv2.mean accepts a mask, so you can get the average color of one shape.
i = 2
m_one = np.zeros(gray.shape, np.uint8)
cv2.drawContours(m_one, contours, i, 255, -1)
b, g, r, _ = cv2.mean(img, mask=m_one)
print(f"contour {i} mean BGR: {b:.0f} {g:.0f} {r:.0f}")If contour 2 is the outer rectangle with a hole, the mask also covers the white hole, and the mean is lighter than the shape's true color. Subtract the child contour from the mask, as in the hierarchy example above.
A repeatable inspection loop
Common mistakes
- Drawing on the original.
drawContourswrites into the array you pass. Callimg.copy()once and draw on that, or later steps will see your green lines as part of the image. - Wrong color order. OpenCV uses BGR, so
(0, 0, 255)is red. - Float coordinates.
putTextandcircleneed integer points. Convert values frommomentswithint(). - Showing a window on a server.
cv2.imshowfails on headless machines. Usecv2.imwriteand open the file. - Contours of the wrong polarity. If the image border or the whole background is outlined, the shapes are probably black on white in the binary image. Invert the threshold.
Exercise
You call cv2.drawContours(out, contours, -1, (0, 255, 0), 2) on a grayscale image and the lines appear black. Why, and how do you fix it?
Show answer
A single-channel image uses only the first color value, which is 0 (black). Convert the image to BGR with cv2.cvtColor(gray, cv2.COLOR_GRAY2BGR) and draw on the converted copy.
Exercise
Write the call that fills only contour 3 with value 255 on a blank mask named mask, then compute the mean of a color image img inside it.
Show answer
cv2.drawContours(mask, contours, 3, 255, -1) followed by cv2.mean(img, mask=mask). The first call fills the interior of contour 3 on the mask, and the second averages only the pixels where the mask is nonzero.