Sub topic 11
Simplifying Contours with `approxPolyDP`
Prerequisites and working model
This chapter assumes that you know basic Python and NumPy indexing, can load and save images with OpenCV, and understand grayscale and binary images. It also assumes you have already created a clean binary mask and extracted contours with cv2.findContours.
A contour is a sequence of points around the boundary of an object. A detailed contour may contain hundreds of points, including small changes caused by pixels or image noise. cv2.approxPolyDP replaces that sequence with fewer points while keeping the simplified boundary close to the original.
The method is based on the Douglas–Peucker algorithm. It keeps the endpoints of a boundary segment, finds the contour point farthest from that segment, and keeps that point only when its distance is large enough. It repeats this process on the remaining segments.
Choosing the approximation tolerance
The main argument is epsilon, the maximum allowed distance between the original contour and its approximation. Use a value relative to the contour perimeter:
epsilon = 0.04 * cv2.arcLength(contour, True)
approx = cv2.approxPolyDP(contour, epsilon, True)The second argument to arcLength is True because an object contour is normally closed. The final True tells approxPolyDP to connect the last approximated point back to the first.
A small epsilon preserves more detail. A large epsilon produces fewer points and a simpler polygon. There is no universal best value. The correct value depends on image resolution, object size, and how much boundary detail matters.
| Epsilon | Result | Typical use |
|---|---|---|
| Small | Many vertices, close to the source | Measuring detailed boundaries |
| Medium | Fewer stable vertices | Basic shape recognition |
| Large | Very simple polygon | Rough object outlines |
A complete approximation example
The following example loads an image, creates a mask for dark objects, finds external contours, and draws both the original contour and its approximation.
import cv2
image = cv2.imread("shapes.png")
if image is None:
raise FileNotFoundError("Could not read shapes.png")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
_, binary = cv2.threshold(
gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU
)
contours, _ = cv2.findContours(
binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE
)
output = image.copy()
for contour in contours:
if cv2.contourArea(contour) < 100:
continue
perimeter = cv2.arcLength(contour, True)
epsilon = 0.04 * perimeter
approximation = cv2.approxPolyDP(contour, epsilon, True)
cv2.drawContours(output, [contour], -1, (0, 255, 0), 1)
cv2.polylines(
output, [approximation], True, (0, 0, 255), 2
)
print("approximated vertices:", len(approximation))
cv2.imwrite("approximated_contours.png", output)The green line shows the original contour. The red line shows the simplified polygon. Each approximated point has the NumPy shape (1, 2), so its coordinates can be read as point[0].
Common errors
Do not compare epsilon values without considering object size. An epsilon of 5 pixels may be tiny for a large object but excessive for a small one. A perimeter-based value scales better.
Approximation does not repair a poor mask. Noise, broken edges, or merged objects are problems for thresholding and morphology first. Clean the binary image before simplifying its contours.
Also, do not assume that four approximated vertices always mean a perfect rectangle. Perspective, rotation, shadows, and an unsuitable epsilon can change the result. Inspect the approximation visually and validate its area or aspect ratio before classifying the object.
Exercise
A contour has a perimeter of 500 pixels. What epsilon does 0.02 * cv2.arcLength(contour, True) produce, and what happens if you increase the factor to 0.08?
Show answer
It produces an epsilon of 10 pixels. Increasing the factor produces 40 pixels, allowing more deviation and usually yielding fewer approximated vertices.