Sub topic 7
Drawing and Inspecting Contours
Assume you can load images with OpenCV and understand grayscale images, NumPy arrays, and basic Python loops. This chapter shows how to draw detected contours and inspect them before measuring or classifying shapes.
What `drawContours` displays
A contour is a list of boundary points around a connected region in a binary image. OpenCV stores the contour points as arrays of coordinates. The function cv2.drawContours renders those points on an image.
The basic call is:
cv2.drawContours(image, contours, contour_index, color, thickness)imageis the image to modify.contoursis the list returned bycv2.findContours.contour_indexselects a contour. Use-1to draw all contours.coloris a BGR tuple, such as(0, 255, 0)for green.thicknessis the line width. Use-1to fill the contour.
Draw on a copy when you need to preserve the original image for later processing.
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))
outlined = img.copy()
cv2.drawContours(outlined, contours, -1, (0, 255, 0), 2)
cv2.imwrite("contours-outlined.png", outlined)
filled = img.copy()
cv2.drawContours(filled, contours, -1, (255, 0, 0), -1)
cv2.imwrite("contours-filled.png", filled)The first output shows green boundaries. The second paints each detected region blue. Drawing filled contours is useful for checking whether the binary mask represents the intended objects.
Inspecting individual contours
Use an index to inspect one contour at a time. The contour length is the number of stored boundary points. With CHAIN_APPROX_SIMPLE, straight runs are compressed, so this number is usually smaller than with CHAIN_APPROX_NONE.
for i, contour in enumerate(contours):
x, y, w, h = cv2.boundingRect(contour)
area = cv2.contourArea(contour)
print(
f"index={i} points={len(contour)} "
f"area={area:.1f} box=({x}, {y}, {w}, {h})"
)
inspected = img.copy()
cv2.drawContours(inspected, contours, i, (0, 0, 255), 3)
cv2.imwrite(f"contour-{i}.png", inspected)The bounding rectangle gives the contour's left and top position, width, and height. It is an upright rectangle, so it may contain empty space around a rotated object.
A useful debugging image labels each contour index. This connects printed measurements to visible regions.
debug = img.copy()
for i, contour in enumerate(contours):
x, y, w, h = cv2.boundingRect(contour)
cv2.drawContours(debug, contours, i, (0, 255, 0), 2)
cv2.putText(
debug,
str(i),
(x, max(y - 5, 15)),
cv2.FONT_HERSHEY_SIMPLEX,
0.6,
(0, 0, 255),
2,
cv2.LINE_AA,
)
cv2.imwrite("contours-labeled.png", debug)Common inspection problems
If no contours appear, check the mask polarity. findContours treats white regions as foreground. If the objects are black on white, use an inverted threshold or invert the mask.
If there are too many contours, small noise may be present. Blur the image, apply morphological opening, or filter contours by area.
If contours merge, the threshold or morphological closing may have joined nearby objects. Reduce the closing kernel or improve object separation before drawing.
Exercise
Exercise
How would you draw only the third contour with a thick yellow outline?
Show answer
Use cv2.drawContours(image, contours, 2, (0, 255, 255), 4). The index is zero-based, and yellow in BGR is (0, 255, 255).