Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 54 ยท Edges, Contours and Shapes

Contour Features: Area, Perimeter and Bounding Boxes

Measure contours with contourArea, arcLength, boundingRect, minAreaRect, minEnclosingCircle, convexHull and moments, and rebuild each measurement in Python.

A contour by itself is just a list of points. To do anything useful with it you measure it: How big is it? How long is its outline? Where is its center? Is it a box, a blob, a thin streak? OpenCV has a small family of functions for this, and together they answer most "which object is the one I want?" questions: the biggest coin, the most circular blob, the tilted card, the object near the center.

In this lesson you will meet each function, learn the small traps in their results (for example, why the area of a contour is not the number of pixels inside it), and rebuild the measurements in plain Python so you can see exactly what they compute. If you have not yet found contours, read Finding and Drawing Contours first.

The cv2 calls are shown read-only because opencv-python does not run in the browser. The runnable Python stand-ins work on a contour written as a list of (x, y) points, which is exactly the data a contour holds. The formulas are the same ones OpenCV uses, but OpenCV's code is optimized C++, so treat the stand-ins as explanations, not replacements.

One contour, many measurements

Python
import cv2

contours, _ = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnt = max(contours, key=cv2.contourArea)          # pick the biggest object

area = cv2.contourArea(cnt)
perimeter = cv2.arcLength(cnt, True)              # True = closed contour
x, y, w, h = cv2.boundingRect(cnt)                # upright rectangle
(cx, cy), (rw, rh), angle = cv2.minAreaRect(cnt)  # rotated rectangle
(ex, ey), radius = cv2.minEnclosingCircle(cnt)
hull = cv2.convexHull(cnt)
M = cv2.moments(cnt)

Measure a contour

Size Area and perimeter.
Boxes Upright and rotated.
Circle Smallest that fits.
Center From the moments.
1 / 2

Area and perimeter

cv2.contourArea(cnt) treats the contour as a polygon through its points and applies the shoelace formula: walk around the polygon, add up x1*y2 - x2*y1 for each edge, and halve the absolute value. cv2.arcLength(cnt, True) adds the lengths of all edges; with False it treats the contour as an open path and skips the closing edge.

There is a trap here. A contour lists boundary pixel centers, so the polygon runs through the middle of the outer pixels. A filled 10 by 10 pixel square has corners at 0 and 9, so contourArea returns 81, not 100. For big objects the difference is tiny, but for small objects, or when you compare with a pixel count such as cv2.countNonZero(mask), it matters. Also, with CHAIN_APPROX_SIMPLE the perimeter of a stair-stepped diagonal line is measured along the shortcut between the stored points, which is shorter than the staircase.

Python Area, perimeter, box and centroid

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The square prints area 81 and perimeter 36 while the filled square holds 100 pixels, and boundingRect reports a width and height of 10 because rectangles count whole pixels. The L-shape (a 6 by 6 square with a 4 by 4 corner cut out) has area 36 - 16 = 20 and perimeter 24. Dropping the closing edge shortens the path from 24 to 18, which is what closed=False means. If you ever need the sign (orientation), cv2.contourArea(cnt, oriented=True) gives a signed area.

Bounding shapes

Three bounding shapes cover different needs:

  • cv2.boundingRect(cnt) returns (x, y, w, h) of the smallest upright rectangle. It is perfect for cropping (img[y:y+h, x:x+w]) and drawing with cv2.rectangle.
  • cv2.minAreaRect(cnt) returns ((cx, cy), (w, h), angle): the smallest rectangle of any rotation. Convert it to four corner points with cv2.boxPoints(rect) and draw them with cv2.drawContours. Its angle convention changed between OpenCV versions (in 4.5.1 and later it lies in the range 0 to 90 degrees), so avoid depending on the exact angle and w/h order across versions.
  • cv2.minEnclosingCircle(cnt) returns ((x, y), radius). There is also cv2.fitEllipse(cnt), which needs at least five points.

Convex hull and shape ratios

The convex hull is the outline you get by stretching a rubber band around the shape. cv2.convexHull(cnt) returns its points (and returnPoints=False returns indices into the contour, which cv2.convexityDefects needs to find the dents, for example the valleys between fingers). Comparing the area of a shape with its hull measures how "dented" it is:

  • Solidity = contour area / hull area. A convex shape gives 1.0, a star or a hand clearly less.
  • Extent = contour area / bounding box area. A filled axis-aligned rectangle gives 1.0.
  • Aspect ratio = w / h of the bounding rectangle.
  • Circularity = 4 * pi * area / perimeter**2, which is 1.0 for a perfect circle and smaller for other shapes.

Ratios like these are scale-invariant, which makes them better classifiers than raw sizes.

Python Hull, rotated box, circle and solidity

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The tilted 8 by 3 rectangle fits in an upright box of area 55.61, but the minimum-area rectangle recovers its true size: 24 (8 by 3) at an angle of 30 degrees. That gap is why minAreaRect is the right tool for tilted cards and documents, while boundingRect over-measures them. For the L-shape the hull adds the triangle that bridges the notch, so the hull area is 28 against a shape area of 20, giving a solidity of 0.714; its extent (area over bounding box) is 0.556. The smallest enclosing circle is centered at (3, 3) with a radius of 4.243, which is half the diagonal of the 6 by 6 box.

Moments and the centroid

cv2.moments(cnt) returns a dictionary of weighted sums over the shape. The three you need most are m00 (the area, in pixels for a contour), and m10 and m01 (area-weighted sums of x and y). The centroid, the shape's balance point, is:

Python
M = cv2.moments(cnt)
if M["m00"] != 0:
    cx = int(M["m10"] / M["m00"])
    cy = int(M["m01"] / M["m00"])

Always guard against m00 == 0, which happens for degenerate contours such as single points or lines, otherwise you get a ZeroDivisionError. The first stand-in computed the centroid of the L-shape as (2.2, 2.2), a point that lies on the diagonal and pulled toward the thick corner, as you would expect. The same moments feed higher-order measures: central moments (mu20, ...) describe the spread, and cv2.HuMoments gives seven values that stay (nearly) the same when the shape is moved, scaled or rotated, which is used in simple shape matching with cv2.matchShapes.

Filtering contours in practice

Real masks contain noise, so measurement usually comes with filtering:

Python
keep = []
for cnt in contours:
    area = cv2.contourArea(cnt)
    if area < 200:                       # drop specks
        continue
    perimeter = cv2.arcLength(cnt, True)
    circularity = 4 * 3.14159 * area / (perimeter ** 2)
    x, y, w, h = cv2.boundingRect(cnt)
    keep.append((area, circularity, (x, y, w, h)))
keep.sort(reverse=True)                  # biggest first

Use a threshold that makes sense for your image size, ideally a fraction of the image area rather than a fixed number of pixels, so the same code works at other resolutions.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A filled 10 by 10 pixel square is found as a contour. What does cv2.contourArea return?

    The contour runs through the centers of the outer pixels, so the polygon spans 9 units on each side and has area 81. The pixel count is 100.
  2. 2. Which function gives the smallest rectangle that may be rotated?

    boundingRect always returns an upright rectangle. minAreaRect searches over rotations and returns the center, the size and the angle of the tightest rectangle.
  3. 3. How do you compute the centroid from cv2.moments?

    m10 and m01 are the area-weighted sums of x and y, and m00 is the area, so dividing gives the average position. Check that m00 is not zero first.
  4. 4. A shape has solidity close to 1.0. What does that tell you?

    Solidity is contour area divided by convex hull area. It is 1.0 for convex shapes and drops as the shape gets concave, like a star or a hand.
  5. 5. Why do ratios such as aspect ratio and solidity make good filters across images of different sizes?

    A ratio of two measurements of the same shape does not change when the shape is scaled, while raw area and perimeter do.

Summary

  • contourArea uses the shoelace formula on the boundary points, so it is smaller than the filled pixel count; arcLength(cnt, True) is the closed perimeter.
  • boundingRect is upright, minAreaRect can rotate, minEnclosingCircle gives a center and radius.
  • convexHull wraps the shape; solidity (area / hull area) and extent (area / box area) describe how dented or filled it is.
  • The centroid is m10 / m00, m01 / m00 from cv2.moments; guard against m00 == 0.
  • Filter by area (and by ratios) to remove noise and select the object you want.

Next lesson: Detecting Lines, Circles and Shapes.