Sub topic 11
Simplifying contours with approxPolyDP
This chapter assumes you can load images with cv2, index NumPy arrays, and have already produced a binary mask and extracted contours with cv2.findContours. Here you learn how cv2.approxPolyDP reduces a contour with hundreds of points to a polygon with a handful of vertices, how to choose its tolerance, and what goes wrong in practice.
Why simplify a contour
A contour from findContours follows every pixel step along a boundary. A hand-drawn square may have 400 points, and most of them describe pixel noise, not the shape. Counting corners, measuring angles or comparing outlines is hard on that data.
cv2.approxPolyDP replaces the contour with a polygon that has far fewer vertices. Every vertex of the result is a point taken from the original contour. The polygon stays within a chosen distance of the original curve.
The Douglas-Peucker algorithm
The function name stands for "approximate polygonal curve using Douglas-Peucker". The algorithm works recursively:
- Draw a straight line between the first and last point of the curve.
- Find the contour point farthest from that line.
- If that distance is no larger than the tolerance
epsilon, discard all points between the endpoints. The line is the approximation. - If the distance is larger, keep that point and repeat steps 1 to 3 on each of the two sub-curves.
For a closed contour, OpenCV starts from two points on the curve and treats each half as an open curve. Points that survive are the ones that stick out more than epsilon pixels from a straight segment.
Calling the function
The signature in Python is:
approx = cv2.approxPolyDP(curve, epsilon, closed)curveis a contour array of shape(N, 1, 2)with integer or float32 coordinates.epsilonis the maximum allowed distance, in pixels, between the original curve and its approximation.closedisTrueif the last point connects back to the first. UseTruefor contours fromfindContours. UseFalsefor an open polyline.
The return value has the same (M, 1, 2) layout, where M is the new vertex count.
Choosing epsilon
An absolute epsilon in pixels breaks when the same shape appears at different sizes. A tolerance of 5 pixels is generous for a 40-pixel square and negligible for a 2000-pixel one. The standard fix is to express epsilon as a fraction of the contour perimeter:
peri = cv2.arcLength(contour, True)
approx = cv2.approxPolyDP(contour, 0.02 * peri, True)The table shows how the fraction affects the result.
| Epsilon as fraction of perimeter | Effect |
|---|---|
| 0.001 to 0.005 | Almost no simplification. Keeps most detail and many vertices. |
| 0.01 to 0.03 | Good starting range for clean polygons such as rectangles and triangles. |
| 0.04 to 0.06 | Strong simplification. Suits noisy outlines, but can merge real corners. |
| Above 0.1 | Collapses most shapes to a triangle or a line. |
Start at 0.02 and adjust by looking at the result, not by guessing.
A runnable experiment
The program below draws a rectangle with a noisy edge and a circle, then prints the vertex count at several epsilon values. It needs only NumPy and OpenCV.
import cv2
import numpy as np
canvas = np.zeros((300, 400), dtype=np.uint8)
cv2.rectangle(canvas, (40, 60), (180, 220), 255, -1)
cv2.circle(canvas, (290, 140), 70, 255, -1)
# Add jagged noise along the rectangle's top edge.
rng = np.random.default_rng(0)
for x in range(40, 181, 3):
canvas[60 - int(rng.integers(0, 3)), x] = 255
contours, _ = cv2.findContours(canvas, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
for c in contours:
peri = cv2.arcLength(c, True)
counts = []
for frac in (0.001, 0.01, 0.02, 0.04, 0.1):
approx = cv2.approxPolyDP(c, frac * peri, True)
counts.append((frac, len(approx)))
print(f"original points={len(c)} perimeter={peri:.0f}", counts)For the rectangle, the count falls from dozens of points to 4 once the fraction reaches about 0.02. The circle never settles on a small number, because every vertex of a circle's polygon is a legitimate deviation from a straight line. That difference is what the classification step uses.
Classifying shapes from the vertex count
Once a contour is a short polygon, the vertex count gives a first guess at the shape. The function below extends this with the aspect ratio for four-sided shapes and circularity for rounded ones.
import math
def classify(contour):
peri = cv2.arcLength(contour, True)
approx = cv2.approxPolyDP(contour, 0.04 * peri, True)
n = len(approx)
if n == 3:
return "triangle"
if n == 4:
_, _, w, h = cv2.boundingRect(approx)
return "square" if 0.95 <= w / float(h) <= 1.05 else "rectangle"
area = cv2.contourArea(contour)
circularity = 4 * math.pi * area / (peri * peri) if peri > 0 else 0
if circularity > 0.8:
return "circle"
return f"polygon with {n} vertices"Circularity is 4*pi*area / perimeter^2. It equals 1.0 for a perfect circle and drops for other shapes. A square scores about 0.785, which is why the threshold of 0.8 separates circles from squares, but only narrowly. Pixel noise can push a real circle slightly below 0.8, so test your threshold on your own images.
Gotchas and failure modes
The output depends on the starting point and the data type
The function accepts int32 and float32 contours. A contour of another dtype, such as int64 from a manual conversion, raises an assertion error. Convert with contour.astype(np.int32).
Convexity is not checked
A four-vertex result can be a concave quadrilateral, such as an arrowhead. Call cv2.isContourConvex(approx) before calling it a rectangle:
if len(approx) == 4 and cv2.isContourConvex(approx):
print("convex quadrilateral")A square is rarely exactly square
Perspective, rotation and rounding make w / h drift from 1.0. The upright boundingRect also overstates the size of a rotated square. For rotated shapes, use cv2.minAreaRect and compare its width and height instead.
Rounded corners add vertices
A rectangle with rounded corners may produce 6 to 8 vertices at small epsilon values. Raising epsilon removes them, but the same increase can destroy a small triangle's third corner. No single fraction fits all shapes. If your input varies, filter by area first, then classify, and keep epsilon scaled to the perimeter.
Noise and holes change the count
A noisy mask gives jagged outlines that survive a small epsilon. Clean the mask with blur and morphological opening or closing before you extract contours. With RETR_TREE, inner contours (holes) are separate entries, and approximating a hole gives its own vertex count. Use the hierarchy to skip them if you only want outer shapes.
Approximation is not smoothing
The result is a polygon with straight edges. It cannot represent a circle or ellipse well, and it should not be used to measure curved shapes. Use cv2.fitEllipse or cv2.minEnclosingCircle for those.
Tiny contours produce meaningless counts
A contour of 10 pixels in area has a perimeter near 12 pixels, so epsilon is below 1 pixel and the result is nearly unchanged. Skip contours below a minimum area before classifying.
Verifying your approximation visually
Draw the approximated polygon over the original image and check that it hugs the shape:
img = cv2.cvtColor(canvas, cv2.COLOR_GRAY2BGR)
for c in contours:
peri = cv2.arcLength(c, True)
approx = cv2.approxPolyDP(c, 0.02 * peri, True)
cv2.polylines(img, [approx], True, (0, 255, 0), 2)
for p in approx[:, 0]:
cv2.circle(img, tuple(int(v) for v in p), 4, (0, 0, 255), -1)
cv2.imwrite("approx.png", img)Green lines show the polygon and red dots show each retained vertex. If a corner is missing or a flat edge has extra dots, change epsilon.
Exercise
A contour has a perimeter of 600 pixels. You call cv2.approxPolyDP with epsilon = 0.02 * perimeter and get 4 vertices. What is the epsilon in pixels, and what extra check should you run before calling the shape a rectangle?
Show answer
Epsilon is 0.02 * 600 = 12 pixels, so no point of the original contour is more than 12 pixels from the polygon edges. Before calling it a rectangle, check that the quadrilateral is convex with cv2.isContourConvex(approx), and compare the width and height ratio (or use minAreaRect for rotated shapes), because a 4-vertex polygon can also be a concave arrowhead or a skewed parallelogram.
Exercise
The same square shape appears at 50 pixels wide in one image and 500 pixels wide in another. Why does a fixed epsilon of 8 pixels give inconsistent vertex counts, and how do you fix it?
Show answer
Eight pixels is a large fraction of the small square's perimeter (200 pixels, so 4 percent) but a small fraction of the large one's (2000 pixels, so 0.4 percent). The small square may lose corners while the large one keeps extra vertices from edge noise. Compute epsilon as a fraction of the contour's perimeter, for example 0.02 * cv2.arcLength(contour, True), so the tolerance scales with the shape.