Sub topic 3
Simplifying contours with approxPolyDP
This chapter assumes you know basic Python, can load and threshold images with cv2, and have a list of contours from cv2.findContours. The code uses the OpenCV 4 Python API.
Simplifying contours with approxPolyDP
cv2.approxPolyDP replaces a contour with fewer points. It uses the Douglas-Peucker algorithm, which keeps a point only if it lies farther than epsilon from the simplified outline. The tolerance is a fraction of the perimeter, and 0.04 is a common starting value.
Detecting triangles, rectangles and circles
The vertex count from approxPolyDP gives most of the answer. Three vertices is a triangle, and four is a rectangle or square. A circle has many vertices, so it is identified by circularity, which is 4 * pi * area / perimeter**2. The value is 1.0 for a perfect circle.
import cv2
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"
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, _ = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for c in contours:
if cv2.contourArea(c) >= 100:
print(classify(c))Convex hulls and convexity defects
A convex hull is the smallest convex shape that encloses a contour. A convexity defect is a gap between the hull and the contour, such as the notch between two fingers. Solidity is the contour area divided by the hull area. A value of 1.0 means the shape is fully convex.
The example below continues from the previous script, so contours is already defined.
c = max(contours, key=cv2.contourArea)
hull_idx = cv2.convexHull(c, returnPoints=False)
defects = cv2.convexityDefects(c, hull_idx)
if defects is not None:
for s, e, f, d in defects[:, 0]:
print("deepest point:", tuple(c[f][0]), "depth:", d / 256.0)
hull_area = cv2.contourArea(cv2.convexHull(c))
print("solidity:", cv2.contourArea(c) / hull_area)OpenCV stores defect depth as a fixed-point number with 8 fractional bits, so the code divides by 256.0.
Comparing shapes with matchShapes
cv2.matchShapes compares two contours with Hu moments. A score near 0 means the shapes are similar. The score does not change with position, scale, or rotation.
score = cv2.matchShapes(contours[0], contours[1], cv2.CONTOURS_MATCH_I1, 0.0)
print("dissimilarity:", score)Common pitfalls and debugging checklist
| Symptom | Likely cause | Fix |
|---|---|---|
| No contours, or one large contour | Threshold polarity is wrong | Use `THRESH_BINARY_INV` for dark shapes on a light background |
| Many tiny contours | Noise in the mask | Blur more, apply morphological opening, or filter by area |
| Circle reported as a polygon | Epsilon is too small | Raise the epsilon factor or rely on circularity |
| Holes reported as separate shapes | `RETR_EXTERNAL` ignores nested contours | Use `RETR_TREE` and check the parent index |
| Different results on another machine | Different OpenCV version | Check the version before debugging the code |
Exercise
A square in your image is classified as a rectangle. Which value in the code should you check first, and why?
Show answer
Check the aspect ratio tolerance, 0.95 <= w / h <= 1.05. A square drawn slightly off-axis or with a bounding box that is a few pixels off can fall outside this range. Widen the tolerance or measure the box more carefully.