Sub topic 10
Bounding rectangles, circles and ellipses
A contour is a list of boundary points. Often you need a simpler description of it: a box to crop, a circle to place a marker, or an ellipse that gives an orientation. This chapter covers the four fitting functions OpenCV provides and the measurements you can derive from them. It assumes you can already produce a clean binary image and call cv2.findContours, and that you know how to compute a contour's area.
Four ways to bound a contour
Each function takes one contour (an array of shape (N, 1, 2)) and returns a different description.
| Function | Returns | Rotated? | Minimum points |
|---|---|---|---|
| `cv2.boundingRect(c)` | `(x, y, w, h)` | No, axis-aligned | 1 |
| `cv2.minAreaRect(c)` | `((cx, cy), (w, h), angle)` | Yes | 1 |
| `cv2.minEnclosingCircle(c)` | `((cx, cy), radius)` | Not applicable | 1 |
| `cv2.fitEllipse(c)` | `((cx, cy), (d1, d2), angle)` | Yes | 5 |
The first three are enclosing shapes: the contour lies inside them. fitEllipse is different. It is a least-squares fit, so the ellipse passes near the points, and parts of the contour can fall outside it.
A runnable example
The script below builds its own test image, so it needs no input file. It draws an upright rectangle, a rotated rectangle, a circle and a tilted ellipse, then draws all four bounds on each contour.
import cv2
import numpy as np
# Synthetic test image: black shapes on a white background
img = np.full((300, 520, 3), 255, np.uint8)
cv2.rectangle(img, (30, 40), (130, 90), (0, 0, 0), -1)
corners = cv2.boxPoints(((250, 80), (120, 40), 30))
cv2.fillPoly(img, [corners.astype(np.int32)], (0, 0, 0))
cv2.circle(img, (420, 80), 40, (0, 0, 0), -1)
cv2.ellipse(img, ((150, 220), (160, 70), 25), (0, 0, 0), -1)
gray = cv2.cvtColor(img, 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)
out = img.copy()
for c in contours:
if cv2.contourArea(c) < 100:
continue
# Upright rectangle (blue)
x, y, w, h = cv2.boundingRect(c)
cv2.rectangle(out, (x, y), (x + w - 1, y + h - 1), (255, 0, 0), 1)
# Rotated rectangle (red)
rect = cv2.minAreaRect(c)
box = cv2.boxPoints(rect).astype(np.int32)
cv2.polylines(out, [box], True, (0, 0, 255), 1)
# Enclosing circle (green): the circle drawing functions need integers
(cx, cy), r = cv2.minEnclosingCircle(c)
cv2.circle(out, (int(cx), int(cy)), int(r), (0, 160, 0), 1)
# Fitted ellipse (magenta): needs at least 5 points
if len(c) >= 5:
ellipse = cv2.fitEllipse(c)
cv2.ellipse(out, ellipse, (255, 0, 255), 1)
cv2.imwrite("bounds.png", out)
print("saved bounds.png")Three details in this code matter in practice:
boundingRectcounts pixels inclusively. A shape covering columns 30 to 130 getsw = 101, so the last pixel is atx + w - 1. Drawing tox + wputs the edge one pixel outside the shape.boxPointsreturns float32 corners.polylinesandfillPolyneedint32, henceastype(np.int32).cv2.ellipseaccepts the tuple fromfitEllipsedirectly as itsboxargument, so you do not unpack it.
Cropping with the upright rectangle
boundingRect is the usual tool for extracting a region of interest. NumPy indexes rows first, so the slice order is the reverse of the tuple order.
x, y, w, h = cv2.boundingRect(c)
roi = img[y:y + h, x:x + w]Mixing up [y, x] and (x, y) is the most common error here. It either crops the wrong area or returns an empty array without raising an error.
The rotated rectangle
minAreaRect finds the smallest-area rectangle at any angle that contains the contour. Its width and height are the shape's real dimensions, whereas the upright box inflates a tilted shape. A 120 by 40 rectangle tilted 30 degrees has an upright box of roughly 124 by 91, and its true size is lost.
Two behaviors surprise people:
- Which side OpenCV calls
wand which it callshis not stable. For a rotation-independent aspect ratio, take the larger value over the smaller. - The angle convention changed in OpenCV 4.5.1. Older versions returned angles in
[-90, 0). Newer versions return(0, 90]. Code that readsangledirectly can give different answers across versions. If you only need the corners, useboxPointsand ignore the angle.
The enclosing circle
minEnclosingCircle returns the smallest circle containing every contour point. The circle is determined by the extreme points, so one stray pixel stretches it. It is useful when you want a size that does not depend on orientation, such as the radius of a round object or a "reach" distance around a centroid.
The center is not the same as the centroid from image moments. A long thin shape with a heavy end has its centroid pulled toward the heavy end, while the enclosing-circle center sits near the middle of its extent.
The fitted ellipse
fitEllipse returns ((cx, cy), (d1, d2), angle), where d1 and d2 are the full axis lengths, not radii. Halve them if a formula expects semi-axes. The angle is in degrees and describes the rotation of the first axis.
Two failure modes to know:
- With fewer than 5 points, OpenCV raises an error. The
len(c) >= 5guard in the example prevents it. A contour of a tiny speck can have fewer than 5 points even afterCHAIN_APPROX_SIMPLE. - The fit is a least-squares estimate, so a contour with a notch or a protrusion gets an ellipse that cuts through the shape. Do not treat it as an enclosing shape.
Measurements derived from bounds
The bounds are most useful as ratios. Each one below gives a number that helps tell shapes apart.
import math
def bound_metrics(c):
area = cv2.contourArea(c)
x, y, w, h = cv2.boundingRect(c)
(rcx, rcy), (rw, rh), angle = cv2.minAreaRect(c)
(ccx, ccy), r = cv2.minEnclosingCircle(c)
aspect_upright = w / float(h)
aspect_rotated = max(rw, rh) / min(rw, rh) if min(rw, rh) > 0 else 0
extent = area / float(w * h)
rect_fill = area / (rw * rh) if rw * rh > 0 else 0
circle_fill = area / (math.pi * r * r) if r > 0 else 0
return aspect_upright, aspect_rotated, extent, rect_fill, circle_fill| Metric | Meaning | Typical values |
|---|---|---|
| `aspect_upright` | Width over height of the upright box | Changes as the shape rotates |
| `aspect_rotated` | Long side over short side of the rotated box | Stable under rotation, always 1 or more |
| `extent` | Contour area over upright box area | Near 1 for an upright rectangle, about 0.785 for a circle |
| `rect_fill` | Contour area over rotated box area | Near 1 for any rectangle at any angle |
| `circle_fill` | Contour area over enclosing circle area | Near 1 for a circle, about 0.64 for a square |
extent falls when a rectangle rotates, because the upright box grows while the area stays fixed. rect_fill stays near 1, which makes it the better test for "is this a rectangle?" when orientation is unknown. For a quick check on whether a shape is round, circle_fill close to 1 and aspect_rotated close to 1 together are a stronger signal than either alone.
Edge cases and debugging
- Noise inflates every bound. One stray white pixel connected to a shape enlarges all four fits. Clean the mask with morphological opening, or filter by area first, before measuring.
- Touching shapes become one contour. Two objects joined by a thin bridge produce one huge box. Erode the mask or separate the objects before finding contours.
- Holes are ignored. The bounds of an outer contour enclose the hole too. With
RETR_TREE, process each contour on its own to get bounds for inner shapes. - Shapes touching the image border. A contour cut off by the border yields a box that does not represent the whole object. Check whether
x == 0,y == 0,x + w == img.shape[1]ory + h == img.shape[0], and skip or flag those. - Float to integer conversion.
int(r)truncates. Useint(round(r))if the half-pixel matters, for example when overlaying a circle on a small object.
Exercise
A 200 by 50 rectangle is rotated 45 degrees in an image. You compute extent (contour area over the upright bounding rectangle area) and rect_fill (contour area over the minAreaRect area). Which of the two stays near 1, and why?
Show answer
rect_fill stays near 1. The minimum-area rectangle rotates with the shape, so it hugs the contour at any angle. The upright box cannot rotate, so at 45 degrees it grows to about 177 by 177 while the area stays 10,000, which gives an extent of about 0.32.
Exercise
Write a short guard that calls cv2.fitEllipse on a contour c only when it is valid, and then returns the semi-axis lengths. Why are the returned values halved?
Show answer
Use if len(c) < 5: return None, then (cx, cy), (d1, d2), angle = cv2.fitEllipse(c) and return d1 / 2.0, d2 / 2.0. OpenCV returns the full axis lengths (diameters), so halving them gives the semi-axes (radii) that most ellipse formulas expect.
Exercise
You use boundingRect to crop an object with img[x:x + w, y:y + h] and get an array with the wrong shape. What is the fix?
Show answer
NumPy indexes rows (y) first, so the correct slice is img[y:y + h, x:x + w].