Sub topic 10
Bounding rectangles, circles and ellipses
This chapter assumes that you can load images with OpenCV, work with NumPy arrays, and obtain contours from a binary mask. A contour is an ordered set of boundary points. Bounding shapes summarize that boundary with a simpler geometric object.
Choosing a bounding shape
Different bounding shapes answer different questions:
| Shape | OpenCV function | Useful for |
|---|---|---|
| Upright rectangle | `cv2.boundingRect` | Fast cropping and rough size |
| Rotated rectangle | `cv2.minAreaRect` | Tight fitting around tilted objects |
| Enclosing circle | `cv2.minEnclosingCircle` | Radial distance and quick detection |
| Fitted ellipse | `cv2.fitEllipse` | Elongated or oval objects |
The upright rectangle has sides parallel to the image axes. It is easy to use, but it includes extra background when the object is rotated. The rotated rectangle is tighter, but its angle convention can require testing with your own images.
Computing and drawing the shapes
The following example finds the largest dark object on a light background and draws each available bounding shape. The threshold creates a white object because findContours expects foreground pixels to be nonzero.
import cv2
import numpy as np
image = cv2.imread("shapes.png")
if image is None:
raise FileNotFoundError("Could not read shapes.png")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
_, mask = cv2.threshold(
gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU
)
contours, _ = cv2.findContours(
mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE
)
if not contours:
raise ValueError("No contours found")
contour = max(contours, key=cv2.contourArea)
output = image.copy()
# Upright rectangle: x and y are the top-left corner.
x, y, width, height = cv2.boundingRect(contour)
cv2.rectangle(output, (x, y), (x + width, y + height), (0, 255, 0), 2)
# Rotated minimum-area rectangle.
rotated = cv2.minAreaRect(contour)
corners = cv2.boxPoints(rotated).astype(np.intp)
cv2.polylines(output, [corners], True, (255, 0, 0), 2)
# Smallest circle containing every contour point.
(center_x, center_y), radius = cv2.minEnclosingCircle(contour)
center = (round(center_x), round(center_y))
cv2.circle(output, center, round(radius), (0, 0, 255), 2)
# An ellipse needs at least five contour points.
if len(contour) >= 5:
ellipse = cv2.fitEllipse(contour)
cv2.ellipse(output, ellipse, (255, 255, 0), 2)
cv2.imwrite("bounding_shapes.png", output)
print("upright box:", (x, y, width, height))
print("rotated rectangle:", rotated)
print("enclosing circle:", center, radius)boundingRect returns (x, y, width, height). Image coordinates start at the top-left, so x increases to the right and y increases downward. The rectangle includes its boundary and is commonly used for slicing:
crop = image[y:y + height, x:x + width]minAreaRect returns ((center_x, center_y), (width, height), angle). Its width, height, and angle may swap as the object rotates. Do not treat the angle as a universal “rotation from horizontal” without checking the returned values.
minEnclosingCircle guarantees that all contour points fit inside the circle. It is often larger than a circle that visually matches the object.
fitEllipse estimates an ellipse from the contour points. It requires at least five points and can be pulled toward outliers. Smoothing the mask or filtering small contours can improve the result.
Exercise
Exercise
Which bounding shape should you choose when an object may be tilted and you need a tight crop around it?
Show answer
Use cv2.minAreaRect and cv2.boxPoints. The upright rectangle stays aligned with the image axes and may include more background.