Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 46 ยท Segmentation and Shapes

Contours and Shape Measurements

Measure labeled regions: area, perimeter, centroid, bounding box, circularity, image moments and orientation, then collect them in a pandas table.

Labeling tells you that there are four objects. Measuring tells you what kind of objects they are. Is this one round or square? Is that one long and thin? Which way does it point? Where is its centre? A quality-control camera rejecting bent screws, a microscope program separating round cells from rod-shaped bacteria, and a robot picking up a tilted part all depend on a handful of numbers computed from a binary region.

This lesson defines those numbers, computes each one with NumPy, and gathers them into a pandas table in the style of the regionprops function found in image libraries. You need the labeled regions from connected components; the examples use 2D boolean masks and pandas for the final table.

The basic measurements

Take one region as a boolean array. Its pixels are the points (y, x) where the mask is True.

  • Area: the number of pixels, mask.sum(). It depends on image resolution, so areas are comparable only between images at the same scale.
  • Centroid: the mean of the pixel coordinates, (ys.mean(), xs.mean()). It is the centre of mass of the shape.
  • Bounding box: the smallest axis-aligned rectangle containing the region: (min row, min col) to (max row, max col). ndi.find_objects hands you its slices.
  • Extent (fill ratio): area divided by bounding-box area. A filled rectangle gives 1.0 and a disc roughly 0.7 to 0.8.
  • Perimeter: the length of the boundary. Harder than it looks, as the next section shows.
flowchart TB
    M["binary region"] --> A["area, centroid<br/>from pixel coordinates"]
    M --> BB["bounding box, extent"]
    M --> P["perimeter<br/>from boundary pixels"]
    A --> MO["second moments"]
    MO --> O["orientation, elongation"]
    A --> CI["circularity = 4*pi*area / perimeter^2"]
    P --> CI

Most descriptors are built from a few primitives: pixel coordinates and the boundary.

Perimeter on a pixel grid

On a grid, counting the pixel edges that face the background is a trap: a staircase boundary along a diagonal has length 2 per step instead of about 1.41, so diagonal and curved shapes are overestimated by up to 41%. The consequences are nasty. A disc of radius 10 has a true perimeter of about 62.8, but counting exposed pixel edges gives 84, which would make a disc look less round than a square.

A better estimate walks the boundary pixels and weights each by the kind of local boundary it sits on: 1 for straight stretches, sqrt(2) for diagonal ones, and something in between for corners. The function below does this with a small convolution that encodes each boundary pixel's neighbourhood as a number (the weights follow the approach used by image libraries). It is an estimate, not exact geometry, but it is far better than edge counting.

The most common shape descriptor built from area and perimeter is circularity (also called compactness or isoperimetric quotient):

TEXT
circularity = 4 * pi * area / perimeter^2

A perfect circle gives exactly 1. Any other shape gives less, and the more stretched or jagged the shape, the smaller the value. The demo compares the two perimeter estimates on a disc and a square.

Python Two ways to measure a perimeter

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.

With edge counting, the square (0.785, its exact value) scores higher than the disc (0.565), which is the wrong way round. With the weighted estimate the disc scores 0.92 and the square 0.87, so the ranking is right. The weighted values are still not exact (the square's circularity should be 0.785), so treat circularity as a relative score: use it to separate round from non-round with a threshold chosen on your own data, not as a precise geometric constant.

Image moments, orientation and elongation

Area and centroid are the first two statistics of the pixel coordinates. The next ones tell you how the pixels are spread. The central second moments (variances and covariance of the coordinates) are:

TEXT
mu20 = mean((x - cx)^2)       mu02 = mean((y - cy)^2)       mu11 = mean((x - cx) * (y - cy))

They form a 2 by 2 covariance matrix of the shape. Its eigenvectors point along the shape's major and minor axes, and its eigenvalues measure the spread along them. From this you get:

  • Orientation: the angle of the major axis, 0.5 * arctan2(2*mu11, mu20 - mu02). With image coordinates (y grows downward) a positive angle means the long axis tilts toward the lower right.
  • Elongation: the ratio of the major to the minor spread, sqrt(lambda_max / lambda_min). A disc or square gives 1, a thin bar gives a large number.
  • Axis lengths: for a filled ellipse, the full axis lengths equal 4 * sqrt(eigenvalue).

This is the same idea as principal component analysis, applied to the pixel coordinates. The next demo makes a disc, a square, a thin bar and an ellipse tilted by 40 degrees, and then measures a region from scratch.

Python Moments, orientation and axis lengths of an ellipse

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.

All three recovered numbers match the shape we drew, within a pixel or two, even though we never told the code about the ellipse: only the pixel coordinates entered the formulas. Orientation has one subtlety. It is only defined modulo 180 degrees (an axis has no arrow), and it is meaningless for round shapes, where mu20 - mu02 and mu11 are both near zero. Check elongation before you trust an angle.

A regionprops-style table

Real projects need these measurements for every region, in a form you can sort and filter. A function that loops over ndi.find_objects, computes one dictionary of measurements per region, and returns a pandas.DataFrame is the usual approach. Cropping to the bounding box before computing keeps each region cheap, and adding the box's top-left corner converts coordinates back to the full image.

Python Measuring every region into a table

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.

Read the table row by row. The disc is the only object above 0.9 circularity. The square has the same elongation (1.00) but a lower circularity, so the two numbers separate "round" from "compact but angular". The tilted ellipse reports an orientation near 40 degrees and an elongation above 2, and the thin bar has the highest elongation of all and an orientation of 0 (horizontal). With a table like this, filtering becomes ordinary pandas: table[(table.area > 100) & (table.circularity > 0.8)].

Libraries such as scikit-image provide regionprops with dozens of such properties (including solidity, Euler number and Hu moments) and OpenCV provides contour-based functions like findContours, contourArea, arcLength and minAreaRect. They work on the same principles; writing them once by hand shows what the numbers mean.

Contours

A contour is the ordered list of boundary points around a region, which is more than the unordered set of boundary pixels used above. With a contour you can compute perimeter as the length of a polyline, simplify the shape to a few corners (a polygon approximation tells you whether an object is a triangle, rectangle or circle), compute a convex hull and a solidity (area divided by hull area, low for shapes with dents), or fit a rotated rectangle. Extracting contours needs a border-following algorithm, which is beyond what we run here, but the measurements in this lesson are the ones you would compute from them, and the results are comparable.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A disc and a square have the same area. Which statement about circularity 4piarea/perimeter^2 is correct?

    For a given area the circle has the smallest perimeter, so it maximizes the quotient, with value 1 in the ideal case.
  2. 2. Why is counting exposed pixel edges a poor perimeter estimate for a disc?

    A diagonal run of pixels is longer when measured along pixel sides than along the true diagonal, so round shapes look too long.
  3. 3. Which quantity is computed from the second central moments of the pixel coordinates?

    Variances and the covariance of the coordinates form a matrix whose eigenvectors give the axes and whose eigenvalues give the spread; area and centroid are lower-order statistics.
  4. 4. When is the orientation of a region unreliable?

    A round shape has no preferred axis, so the angle formula is dominated by noise. Check elongation first.
  5. 5. The slices from ndi.find_objects start at (row 10, col 60). To convert a pixel found inside the cropped region back to full-image coordinates you should:

    Cropped arrays start at (0, 0), so adding the top-left corner of the bounding box gives the position in the whole image.

Summary

  • Basic region measurements: area (mask.sum()), centroid (mean coordinates), bounding box (find_objects), and extent (area over box area).
  • Perimeter on a grid needs care; edge counting overestimates diagonals, while a weighted boundary-pixel estimate is much closer.
  • Circularity 4*pi*area/perimeter^2 is 1 for a perfect circle and smaller otherwise; use it as a relative score with a threshold tuned on your data.
  • Second central moments give orientation (0.5 * arctan2(2*mu11, mu20 - mu02)), axis lengths and elongation; orientation is undefined for round shapes.
  • Loop over find_objects, collect one dictionary per region, and build a pandas DataFrame to sort and filter objects.

Next, separate objects that touch by clustering and flooding in Segmentation by Clustering and Watershed.