Sub topic 12
Detecting triangles, rectangles and circles
This chapter assumes you can load images with cv2, index NumPy arrays, and already produce a clean binary mask and extract contours with cv2.findContours. Here you turn contours into shape names by counting vertices and measuring circularity.
The working model
A contour is a list of boundary points. A perfect triangle drawn on screen still produces a contour with dozens of points once pixel noise, anti-aliasing and blur are included. To name the shape, you:
- Filter out contours that are too small to matter.
- Simplify each contour with
cv2.approxPolyDPso only the corners remain. - Count the remaining vertices.
- Use extra measurements to separate shapes that share a vertex count.
How approxPolyDP works
cv2.approxPolyDP(curve, epsilon, closed) implements the Douglas-Peucker algorithm. It draws a line between the two farthest-apart points of the curve, then finds the point farthest from that line. If that point is more than epsilon away, it becomes a vertex and the process repeats on each side. Points closer than epsilon to the simplified line are dropped.
epsilon is a distance in pixels. Expressing it as a fraction of the contour's perimeter makes it scale with shape size:
peri = cv2.arcLength(contour, True)
approx = cv2.approxPolyDP(contour, 0.04 * peri, True)The second argument of arcLength, True, says the contour is closed. Pass True for both calls when working with contours from findContours.
The result is an array of shape (n, 1, 2). Its length, len(approx), is the vertex count.
Choosing epsilon
| Epsilon (fraction of perimeter) | Effect |
|---|---|
| 0.01 | Keeps slight bends. Noisy edges may add extra vertices. |
| 0.02 | Common default for clean, high-contrast shapes. |
| 0.04 | Tolerant. Good for blurry or hand-drawn shapes, but may merge real corners. |
| 0.10 or more | Over-simplifies. A square can collapse to a triangle. |
There is no universal value. Tune it on a few real images and print the vertex counts.
Classifying by vertex count
The classifier from the topic's examples is the core of this chapter. It is repeated here as a complete script, so it can run on its own:
import math
import cv2
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:
continue
label = classify(c)
x, y, w, h = cv2.boundingRect(c)
cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)
cv2.putText(img, label, (x, max(y - 6, 12)),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 1)
cv2.imwrite("labeled.png", img)The area filter comes first because tiny contours produce meaningless vertex counts and a division by a near-zero height in the aspect-ratio test.
Why four vertices need an aspect ratio
Vertex count alone cannot tell a square from a rectangle. The code takes the upright bounding box of the approximated polygon and compares width to height. A ratio within 5 percent of 1 is called a square.
This has a limit. boundingRect is axis-aligned. A square rotated 45 degrees has a bounding box that is still square, so it passes. A long thin rectangle rotated 45 degrees has a bounding box that is nearly square, so it is wrongly labeled a square. To handle rotation, use cv2.minAreaRect, which returns the rotated box:
(_, _), (w, h), _ = cv2.minAreaRect(approx)
ratio = w / h if h else 0Because minAreaRect may report width and height in either order, compare ratio against both 1 and its reciprocal, or use max(w, h) / min(w, h).
Circularity
Circles have no corners, so approxPolyDP returns many vertices, often 8 or more at a 4 percent tolerance. Circularity separates them from true polygons:
circularity = 4 pi area / perimeter^2
For a perfect circle the value is 1. A square gives about 0.785, an equilateral triangle about 0.60. A regular hexagon gives about 0.91 and an octagon about 0.95. This is the main gotcha: a threshold of 0.8 will label regular hexagons and octagons as circles.
The simple classifier therefore works best when you know the expected shapes. If hexagons are possible, check the vertex count first and treat circularity as a tiebreaker only when n is large:
def classify_strict(contour):
peri = cv2.arcLength(contour, True)
if peri == 0:
return "unknown"
approx = cv2.approxPolyDP(contour, 0.02 * peri, True)
n = len(approx)
circularity = 4 * 3.141592653589793 * cv2.contourArea(contour) / (peri * peri)
if n == 3:
return "triangle"
if n == 4:
return "quadrilateral"
if n > 8 and circularity > 0.85:
return "circle"
return f"polygon with {n} vertices"A second option for circles is cv2.minEnclosingCircle. Compare the contour area with the area of the enclosing circle, pi * r * r. A ratio near 1 means the shape fills its circle. cv2.HoughCircles is a different approach that works directly on a grayscale image and tolerates partial arcs, but it has its own parameters to tune.
Edge cases and failure modes
- Wrong polarity. If the shapes are dark on a light background,
THRESH_BINARY_INVmakes them white. With the wrong choice, the largest contour is the whole image border and everything is classified as a rectangle. - Touching shapes. Two touching shapes merge into one contour, so the vertex count is wrong. Apply erosion or an opening first, as covered in the morphology chapter.
- Perspective and skew. A rectangle photographed at an angle is still four vertices, but its aspect ratio no longer reflects the real object.
- Rounded corners. A rounded rectangle may approximate to 8 or more vertices at small epsilon, or to 4 at large epsilon. The label depends on the tolerance.
- Concave shapes. A star or arrow gives a vertex count that does not match any basic name. Use the convex hull and solidity tools from the later chapter on concavity.
- Degenerate contours. A one-pixel-wide line has near-zero area. A zero perimeter would divide by zero, so guard against it as the code above does.
- Low resolution. Shapes smaller than about 20 pixels across have too few boundary points for stable corners.
Visual debugging
Drawing the simplified polygon next to the original contour shows quickly whether epsilon is right:
vis = img.copy()
for c in contours:
if cv2.contourArea(c) < 100:
continue
peri = cv2.arcLength(c, True)
approx = cv2.approxPolyDP(c, 0.04 * peri, True)
cv2.polylines(vis, [approx], True, (255, 0, 0), 2)
for p in approx[:, 0]:
cv2.circle(vis, tuple(int(v) for v in p), 4, (0, 0, 255), -1)
cv2.imwrite("approx.png", vis)Red dots mark each kept vertex. If a straight edge carries an extra dot, lower the noise or raise epsilon. If a real corner has no dot, lower epsilon.
Summary of decisions
| Situation | Choice |
|---|---|
| Clean synthetic shapes | Epsilon 0.02 to 0.04 of the perimeter |
| Blurry or hand-drawn shapes | Epsilon 0.04 or more, plus a blur before thresholding |
| Rotated rectangles | Use `minAreaRect` for the aspect ratio |
| Hexagons or octagons possible | Count vertices before testing circularity |
| Shapes with arcs only partly visible | Consider `HoughCircles` |
Exercise
A regular octagon is passed to the classify function from this chapter, which uses epsilon of 0.04 times the perimeter and a circularity threshold of 0.8. It is labeled "circle". Why does this happen, and what is one change that fixes it?
Show answer
At 4 percent tolerance the octagon may keep 8 or fewer vertices, which is not 3 or 4, so the code reaches the circularity test. A regular octagon has circularity about 0.95, which is above 0.8, so it is labeled a circle. Fixes: raise the circularity threshold to about 0.97 or higher, require a large vertex count (for example, n > 8) at a smaller epsilon such as 0.02, or add an explicit branch for n == 8 before the circularity test.
Exercise
A thin rectangle, 200 by 20 pixels, is rotated 45 degrees. Using boundingRect on its approximated polygon, the code labels it "square". Which function gives a correct aspect ratio, and how do you compute the ratio?
Show answer
Use cv2.minAreaRect(approx). It returns ((cx, cy), (w, h), angle) for the rotated box. Compute max(w, h) / min(w, h), which is about 10 here, and call the shape a square only if that ratio is near 1.