Sub topic 8
Measuring contours: area, perimeter and centroid
This chapter assumes you can already produce a clean binary image and call cv2.findContours in OpenCV 4, as covered in the earlier chapters. You should also be comfortable with NumPy array shapes. Here you will turn each contour into numbers: area, perimeter, centroid and a bounding box. These numbers drive the filtering and shape classification in later chapters.
What a contour is as data
In OpenCV 4, cv2.findContours returns a tuple (contours, hierarchy). contours is a Python tuple of NumPy arrays. Each array has shape (N, 1, 2), dtype int32, and holds N boundary points as (x, y) pairs. The odd middle axis of size 1 is a legacy of OpenCV's C++ point-vector layout. Many OpenCV functions expect it, so keep it unless you have a reason to reshape.
import cv2
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, hierarchy = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
print("contours found:", len(contours))
print("shape of first contour:", contours[0].shape, contours[0].dtype)The inverted Otsu threshold makes dark shapes on a light background white, which is the polarity findContours expects (white objects on black).
Area with cv2.contourArea
cv2.contourArea(contour) returns the area enclosed by the contour as a float. It uses the polygon area formula (Green's theorem) on the contour points. It does not count pixels.
This has three consequences:
- The result can differ from
cv2.countNonZeroon the filled mask. WithCHAIN_APPROX_SIMPLE, straight segments are compressed to their endpoints, which does not change the area. The contour passes through pixel centers, though, so the boundary pixels are only half counted. For a filled rectangle that is 10 pixels wide, the area is about 9 pixels wide. - Area is always non-negative by default.
cv2.contourArea(c, oriented=True)returns a signed value whose sign tells you the point order (clockwise or counter-clockwise). - For a self-intersecting contour the result is not meaningful. Contours from
findContoursdo not self-intersect, but contours you build by hand might.
Perimeter with cv2.arcLength
cv2.arcLength(contour, closed) sums the distances between consecutive points. Pass True for closed when the contour is a closed boundary, which is the case for anything returned by findContours. If you pass False, the segment from the last point back to the first is left out, and the perimeter comes out short.
Perimeter depends on the approximation method. With CHAIN_APPROX_NONE, a diagonal boundary is a staircase of one-pixel steps. Diagonal steps count as about 1.41 and straight steps as 1. With CHAIN_APPROX_SIMPLE, diagonal runs are kept as a single segment between endpoints. Perimeters of the same shape can therefore differ a little between the two methods. Compare perimeters only when you used the same method.
Centroid from image moments
A moment is a weighted sum over the shape. cv2.moments(contour) returns a dictionary of spatial moments (m00, m10, m01, m20, and so on), central moments (mu20, ...) and normalized central moments (nu20, ...).
The key values are:
m00is the area of the contour (the same value ascontourArea).m10is the sum of x weighted over the shape.m01is the sum of y weighted over the shape.
The centroid is the mean position of the shape:
cx = m10 / m00
cy = m01 / m00m00 is zero for degenerate contours, such as a single point or a line of collinear points. Dividing by it raises ZeroDivisionError, because the values in the dictionary are Python floats, not NumPy scalars. Always guard the division.
def centroid(contour):
m = cv2.moments(contour)
if m["m00"] == 0:
return None
return int(m["m10"] / m["m00"]), int(m["m01"] / m["m00"])The centroid is the center of mass, not the center of the bounding box. For an L-shaped object, or for a crescent, the centroid can even lie outside the object. Use it as a position estimate, not as a guaranteed point on the shape.
Putting the measurements together
This loop skips tiny contours, then prints all four measurements for each remaining one.
for c in contours:
area = cv2.contourArea(c)
if area < 100:
continue
perimeter = cv2.arcLength(c, True)
m = cv2.moments(c)
cx = int(m["m10"] / m["m00"])
cy = int(m["m01"] / m["m00"])
x, y, w, h = cv2.boundingRect(c)
print(f"area={area:.0f} perimeter={perimeter:.1f} centroid=({cx},{cy}) box=({x},{y},{w},{h})")The area < 100 test serves two purposes. It removes noise specks, and it guarantees m00 is not zero, so the division is safe here. The threshold of 100 square pixels is arbitrary. Scale it with the image resolution. The next chapter covers filtering in more detail.
cv2.boundingRect returns the upright rectangle as (x, y, w, h), where (x, y) is the top-left corner. It is cheap and useful for cropping a region of interest with img[y:y+h, x:x+w].
How the pieces relate
The last node, derived ratios, matters for later chapters. Area and perimeter on their own depend on image scale. A ratio such as circularity, 4 * pi * area / perimeter**2, does not change when the shape is scaled, so it describes the shape and not its size. A perfect circle gives 1.0, and elongated or ragged shapes give smaller values.
Units and scale
All measurements are in pixels. Area is in square pixels, and perimeter is in pixels. If your camera is calibrated and you know the pixel size in millimeters, multiply perimeter by that factor and area by its square. A common mistake is to scale area by the linear factor. If the image is resized before processing, measurements change with it. Measure on the resolution you care about, or normalize with ratios.
Edge cases
| Situation | What happens | What to do |
|---|---|---|
| Single-pixel contour | `m00` is 0, area is 0 | Filter by area before using moments |
| Thin line, 1 pixel wide | Area is near 0, perimeter is about twice the length | Use perimeter or `boundingRect` for lines |
| Contour touching the image border | The shape is cut off, so area is smaller than the real object | Pad the image with a border, or discard border contours |
| Holes inside a shape | With `RETR_EXTERNAL`, area includes the hole | Use `RETR_TREE` and subtract child areas |
| Float result compared to an integer | `contourArea` returns a float | Compare with a tolerance, not `==` |
The hole case is easy to miss. contourArea on an outer contour gives the full enclosed region, as if the hole were filled. To get the real material area of a washer-like shape, subtract the areas of its child contours, which you can find through the hierarchy array.
contours, hierarchy = cv2.findContours(binary, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE)
for i, c in enumerate(contours):
if hierarchy[0][i][3] != -1:
continue # skip holes, handle only outer contours
material = cv2.contourArea(c)
child = hierarchy[0][i][2]
while child != -1:
material -= cv2.contourArea(contours[child])
child = hierarchy[0][child][0]
print(i, "material area:", material)RETR_CCOMP organizes contours in two levels, outer boundaries and holes. For each outer contour, hierarchy[0][i][2] is its first hole, and hierarchy[0][child][0] moves to the next hole at the same level.
Visualizing the measurements
Draw the centroid and label each contour to check your numbers against the picture.
out = img.copy()
for c in contours:
if cv2.contourArea(c) < 100:
continue
m = cv2.moments(c)
cx, cy = int(m["m10"] / m["m00"]), int(m["m01"] / m["m00"])
cv2.drawContours(out, [c], -1, (0, 255, 0), 2)
cv2.circle(out, (cx, cy), 4, (0, 0, 255), -1)
cv2.putText(out, f"{cv2.contourArea(c):.0f}", (cx + 6, cy),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 0), 1)
cv2.imwrite("measured.png", out)Note that drawContours takes a list of contours, so a single contour is wrapped in [c]. With index -1 it draws every contour in the list.
Common errors
ZeroDivisionErrorwhen computing the centroid. The contour hasm00 == 0. Filter by area or guard the division.- Perimeter is too small. You passed
closed=False. - Area is zero for an obviously large shape. The binary image has the wrong polarity, so the contour traces the image border or the background. Check that objects are white.
- Unpacking error on
findContours. OpenCV 3 returned three values, and OpenCV 4 returns two. This tutorial uses OpenCV 4. - Centroid looks shifted. Truncating with
int()loses up to one pixel. Useround()if you need a better estimate, or keep floats.
Exercise
A contour for a ring (a washer) is found with RETR_EXTERNAL. Its outer diameter is 100 pixels and the hole has a diameter of 40 pixels. Roughly what does cv2.contourArea return, and how would you get the area of the metal itself?
Show answer
With RETREXTERNAL only the outer boundary is returned, so contourArea gives about pi * 50^2, roughly 7850 square pixels, which counts the hole as filled. To get the metal area, retrieve contours with RETRCCOMP or RETR_TREE, find the hole contour through the hierarchy, and subtract its area (about pi * 20^2, roughly 1257) from the outer area, giving about 6600 square pixels.
Exercise
Why can dividing m10 by m00 fail, and how do you make the centroid code safe?
Show answer
m00 is the contour area, and it is 0 for a single point or a set of collinear points. The division then raises ZeroDivisionError. Check that m["m00"] is not 0 before dividing, or skip contours whose cv2.contourArea is below a minimum.