Sub topic 12
Detecting Triangles, Rectangles and Circles
Assume you know basic Python, NumPy indexing, and how to load and save images with OpenCV. This chapter uses OpenCV 4 and works with a clean binary mask containing dark shapes on a light background.
Shape classification usually follows this path:
- Create a binary image.
- Find the external contours.
- Simplify each contour into a polygon.
- Use the number of vertices and measurements to choose a label.
Simplifying a contour
A contour contains many boundary points. Even a nearly straight edge can contain small pixel-level changes. cv2.approxPolyDP reduces these points while keeping the general shape.
Its second argument is the approximation tolerance, called epsilon. A value such as 0.04 * perimeter means that the allowed error grows with the size of the contour.
- A triangle usually becomes three vertices.
- A rectangle usually becomes four vertices.
- A circle becomes a polygon with many vertices.
A tolerance that is too small keeps noise. A tolerance that is too large removes important corners.
import math
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)
blur = cv2.GaussianBlur(gray, (5, 5), 0)
# Dark shapes become white foreground regions.
_, binary = cv2.threshold(
blur, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU
)
contours, _ = cv2.findContours(
binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE
)
def classify(contour):
area = cv2.contourArea(contour)
perimeter = cv2.arcLength(contour, True)
if area < 100 or perimeter == 0:
return "noise"
polygon = cv2.approxPolyDP(contour, 0.04 * perimeter, True)
vertices = len(polygon)
if vertices == 3:
return "triangle"
if vertices == 4:
x, y, width, height = cv2.boundingRect(polygon)
ratio = width / float(height)
return "square" if 0.95 <= ratio <= 1.05 else "rectangle"
circularity = 4 * math.pi * area / (perimeter * perimeter)
if circularity > 0.80:
return "circle"
return f"polygon ({vertices} vertices)"
result = image.copy()
for contour in contours:
label = classify(contour)
if label == "noise":
continue
x, y, width, height = cv2.boundingRect(contour)
cv2.drawContours(result, [contour], -1, (0, 255, 0), 2)
cv2.putText(
result, label, (x, max(20, y - 8)),
cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 0, 255), 2
)
cv2.imwrite("classified_shapes.png", result)Why circularity helps
Circularity compares the contour area with the square of its perimeter:
C = \frac{4\pi A}{P^2}A perfect circle has a value close to 1. Jagged, elongated, or concave shapes have lower values. The threshold 0.80 is a starting point, not a universal rule. Change it after testing images from the real camera or dataset.
The rectangle test above uses an upright bounding rectangle. It works for simple, mostly upright shapes. A rotated square can have a wide bounding box and be incorrectly labeled as a rectangle. For rotated objects, use cv2.minAreaRect or compare the polygon's side lengths and angles.
Common errors
- If every shape becomes one contour, inspect the binary mask. Touching white regions cannot be separated by contour classification.
- If dark shapes disappear, reverse the threshold polarity with
THRESH_BINARYinstead ofTHRESH_BINARY_INV. - If circles become polygons, increase the approximation tolerance slightly or classify them with circularity.
- If small dots are labeled as shapes, filter by area before approximation.
Exercise
Why can a rotated square be labeled as a rectangle by the example?
Show answer
The example compares the width and height of an upright bounding rectangle. Rotation changes that ratio, even though the polygon still has four sides.