Exercise: region properties and moments
Before this unit: Connectivity and labelling (previous unit); Day 13: Morphology.
Goal
By the end of this exercise you should be able to:
- compute the area, centroid, central moments and the second-moment matrix S of a small object by hand,
- find the eigenvalues, eigenvectors and orientation of S, and draw the equivalent ellipse,
- estimate a perimeter by edge count and chain code, and explain the bias of each,
- compute the Euler number by counting objects and holes, and check it with 2 × 2 windows.
Do the pen-and-paper part first, then the demo.
Background
| Quantity | Formula |
|---|---|
| raw moments | m_{pq} = \sum_{(x,y)\in\Omega} x^p y^q; area A = m_{00} |
| centroid | \bar x = m_{10}/A, \bar y = m_{01}/A |
| central moments | \mu_{20} = \sum (x-\bar x)^2, \mu_{11} = \sum (x-\bar x)(y - \bar y), \mu_{02} = \sum (y - \bar y)^2 |
| second-moment matrix | S = \frac1A \begin{pmatrix}\mu_{20} & \mu_{11}\\ \mu_{11} & \mu_{02}\end{pmatrix}, eigenvalues \lambda_1 \ge \lambda_2 |
| equivalent ellipse | semi-axes 2\sqrt{\lambda_1}, 2\sqrt{\lambda_2} along the eigenvectors |
| eccentricity, elongation | \sqrt{1 - \lambda_2/\lambda_1}, \sqrt{\lambda_1/\lambda_2} |
| perimeter | edge count (pixel edges); chain code (steps 1 and \sqrt2 between boundary pixel centres) |
| Euler number | objects − holes = (Q_1 - Q_3 - 2Q_D)/4 for 8-connected objects |
x = column, y = row (pointing down), pixel centres at integer coordinates. An orientation is given counter-clockwise as seen on the screen.
By hand
B1. An object of 12 pixels in a 5 \times 5 box (1 = object; x = column, y = row, both from 0):
1 1 0 0 0
1 1 1 0 0
0 1 1 1 0
0 0 1 1 1
0 0 0 1 0
- Area, bounding box and extent.
- m_{10}, m_{01} and the centroid.
- \mu_{20}, \mu_{11}, \mu_{02} (use the raw moments m_{20}, m_{11}, m_{02}, or sum directly) and S.
- The eigenvalues and eigenvectors of S. (Hint: S has equal diagonal entries.) Sketch the object with \mathbf v_1, \mathbf v_2 and the equivalent ellipse.
- Orientation (counter-clockwise on screen), eccentricity and elongation. Does the orientation match your sketch?
B2. A digital disc of radius 4: the pixels whose centre lies within distance 4 of a pixel centre. (a) Draw it (9 rows) and count its pixels. Compare with \pi r^2. (b) Count the pixel edges between the disc and the background. Compare with 2\pi r and with 8r. (c) The chain code through the boundary pixel centres: how many steps of length 1 and of length \sqrt 2? What length does it give?
B3. A 7 \times 9 image:
. . . . . . . . .
. # # # . . . . .
. # . # . . . . .
. # # # . # # . .
. . . . . . . # .
. . . . . . . # .
. . . . . . . . .
- Number of objects and holes with objects 8 / background 4, and the Euler number. And with objects 4 / background 8?
- Count the 2 × 2 windows (including those that stick out of the image by one pixel, where the outside is background) with exactly one object pixel (Q_1), with three (Q_3), and with two diagonal object pixels (Q_D). Check E_8 = (Q_1 - Q_3 - 2Q_D)/4 and E_4 = (Q_1 - Q_3 + 2Q_D)/4.
B4. Edge count on squares. A large square of side s pixels, (a) aligned with the grid, (b) rotated by 45°. What does the edge count give relative to the true perimeter 4s in each case? How does that fit with the factor 4/\pi for a disc?
B5. Predict, without computing: (a) \lambda_1 and \lambda_2 for a disc, a square and an equilateral triangle; which of them have a defined orientation? (b) A rectangle of 2 \times 10 pixels: compute S, \lambda_1, \lambda_2, the eccentricity and the major axis length 4\sqrt{\lambda_1}. Why is the axis longer than 10?
B1. (a) A = 12; box x \in [0, 4], y \in [0, 4], 5 \times 5; extent 12/25 = 0.48. (b) m_{10} = \sum x = 22, m_{01} = \sum y = 22; centroid (22/12, 22/12) = (1.833, 1.833). (c) m_{20} = m_{02} = 58, m_{11} = 54. \mu_{20} = 58 - 22^2/12 = 53/3 = 17.67, \mu_{02} = 17.67, \mu_{11} = 54 - 22 \cdot 22/12 = 41/3 = 13.67. S = \begin{pmatrix}1.472 & 1.139 \\ 1.139 & 1.472\end{pmatrix} (exactly \frac{1}{36}\begin{pmatrix}53 & 41\\ 41 & 53\end{pmatrix}). (d) With equal diagonal a and off-diagonal b, the eigenvectors are (1, 1)/\sqrt2 and (-1, 1)/\sqrt2 with eigenvalues a \pm b: \lambda_1 = 94/36 = 2.611, \lambda_2 = 12/36 = 0.333. \mathbf v_1 = (1,1)/\sqrt 2 points right and down. Ellipse semi-axes 2\sqrt{2.611} = 3.23 and 2\sqrt{0.333} = 1.15. (e) \theta = \frac12\operatorname{atan2}(2 \cdot 13.67, 0) = 45° from x towards y (down), so the orientation counter-clockwise on screen is -45°: the object runs from the top left to the bottom right, as drawn. Eccentricity \sqrt{1 - 12/94} = 0.934, elongation \sqrt{94/12} = 2.80.
B2. (a) Rows of 1, 5, 7, 7, 9, 7, 7, 5, 1 pixels: 49 pixels; \pi r^2 = 50.3. (b) The disc spans 9 pixels in each direction and every row and column is one run, so the edge count is $2 + 2 = $ 36. 2\pi r = 25.1: the edge count is 1.43 times too long; 8r = 32 is the large-disc value (8(r + \tfrac12) = 36 for this digital disc, which reaches half a pixel further out). (c) 8 steps of length 1 and 12 of length \sqrt2: 8 + 12\sqrt2 = 24.97, within 1 % of 2\pi r here (the polygon through the centres lies inside the true circle, which partly cancels the excess of the diagonal steps).
B3. (a) Objects 8 / background 4: 2 objects (the ring, and the four pixels at the right, joined by the diagonal step from (3,6) to (4,7)), 1 hole: E_8 = 1. Objects 4 / background 8: 3 objects (the diagonal step breaks the right one in two), still 1 hole: E_4 = 2. (b) Q_1 = 10, Q_3 = 4, Q_D = 1 (the window at the diagonal step). E_8 = (10 - 4 - 2)/4 = 1 ✓, E_4 = (10 - 4 + 2)/4 = 2 ✓.
B4. (a) Aligned: the edge count is exactly 4s: ratio 1. (b) At 45°, each side of length s becomes a staircase with legs s/\sqrt2 and s/\sqrt2: \sqrt2 \, s per side, ratio \sqrt2 = 1.41. The ratio |\cos\varphi| + |\sin\varphi| depends on the direction of the boundary, between 1 and \sqrt2; a disc has all directions, and the average is 4/\pi = 1.27.
B5. (a) A disc, a square and an equilateral triangle all have \lambda_1 = \lambda_2 (they have rotational symmetry of order 4 or 3, and S must be unchanged by that rotation, which forces a multiple of the identity). None of them has a defined orientation. (b) x = 0, \dots, 9, y = 0, 1: variances \frac{10^2 - 1}{12} = 8.25 and \frac{2^2 - 1}{12} = 0.25, no covariance: S = \operatorname{diag}(8.25, 0.25), \lambda_1 = 8.25, \lambda_2 = 0.25, eccentricity \sqrt{1 - 0.25/8.25} = 0.985, major axis 4\sqrt{8.25} = 11.5. The equivalent ellipse has the same variance as the rectangle; a rectangle has more of its pixels far from the centre than an ellipse of the same length, so the matching ellipse must be longer.
Math questions
B6. (math) Derive the orientation formula: rotate the coordinates by \theta and require the rotated \mu_{11}' to vanish. Show that this gives \tan 2\theta = 2\mu_{11}/(\mu_{20} - \mu_{02}), and explain why atan2 (rather than arctan) picks the major axis.
B7. (math) Show that a solid ellipse with semi-axes a and b has variance a^2/4 along its major axis (substitute x = a r \cos t, y = b r \sin t). Conclude that the equivalent ellipse has a = 2\sqrt{\lambda_1}, and check that a disc of radius r gives back r.
B8. (math) Show that the edge-count perimeter of a convex digital object equals twice its width plus twice its height (in pixels). Use this to prove that for large digital discs the edge count tends to 8r, i.e. 4/\pi times the true perimeter.
B9. (math) Show that \operatorname{tr} S = \lambda_1 + \lambda_2 is the mean squared distance of the pixels from the centroid, and that it is invariant under rotation. For a disc of radius r, compute it (continuous) and relate it to the second-moment “compactness” 2\pi\,\overline{r^2}/A of the next unit.
B6. With x' = x\cos\theta + y\sin\theta, y' = -x\sin\theta + y\cos\theta (centred coordinates): \mu_{11}' = \sum x'y' = (\mu_{02} - \mu_{20})\sin\theta\cos\theta + \mu_{11}(\cos^2\theta - \sin^2\theta) = -\tfrac12(\mu_{20} - \mu_{02})\sin 2\theta + \mu_{11}\cos 2\theta. Setting it to 0: \tan 2\theta = 2\mu_{11}/(\mu_{20} - \mu_{02}). This has two solutions in [0°, 180°), 90° apart: the major and the minor axis. \operatorname{atan2}(2\mu_{11}, \mu_{20} - \mu_{02}) returns the angle 2\theta of the vector (\mu_{20} - \mu_{02}, 2\mu_{11}); then \mu_{20}' = \tfrac{\mu_{20} + \mu_{02}}{2} + \tfrac12\sqrt{(\mu_{20}-\mu_{02})^2 + 4\mu_{11}^2}, the larger of the two: the major axis.
B7. With x = ar\cos t, y = br\sin t, dx\,dy = ab\,r\,dr\,dt: \iint x^2 = a^3 b \int_0^1 r^3 dr \int_0^{2\pi}\cos^2 t\, dt = a^3 b \cdot \tfrac14 \cdot \pi. Dividing by the area \pi ab: a^2/4. So \lambda_1 = a^2/4 gives a = 2\sqrt{\lambda_1}. A disc: \lambda = r^2/4, 2\sqrt{\lambda} = r.
B8. In a convex digital object every row and every column is one run. Each row contributes exactly 2 vertical boundary edges (its two ends), each column 2 horizontal ones: P_{\text{edges}} = 2 \cdot (\text{number of rows}) + 2\cdot(\text{number of columns}) = 2h + 2w. A large digital disc has w \approx h \approx 2r, so P_{\text{edges}} \approx 8r, and 8r / (2\pi r) = 4/\pi.
B9. \operatorname{tr} S = \frac1A\sum\big((x - \bar x)^2 + (y - \bar y)^2\big) = \overline{\rho^2}, the mean squared distance from the centroid; the trace equals the sum of the eigenvalues, which do not change under rotation. Disc: \overline{\rho^2} = \frac{1}{\pi r^2}\int_0^r \rho^2\, 2\pi\rho\, d\rho = r^2/2, so 2\pi\,\overline{\rho^2}/A = 2\pi (r^2/2)/(\pi r^2) = 1. The disc has the smallest mean squared radius for its area, so this compactness is 1 for a disc and larger for anything else.
Explore
A shape-editing canvas: the outline (a polygon) is digitised on a pixel grid, and the pixel size slider sets how coarse the grid is. Drag a corner or the whole shape, use the buttons to rotate, scale and mirror, or draw new shape. Overlays: centroid (+), bounding box, the equivalent ellipse (orange), \mathbf v_1 (red) and \mathbf v_2 (green) with lengths 2\sqrt{\lambda_i}. The table compares the digitised values with the exact values of the outline; the plot shows the three perimeter estimates divided by the exact perimeter at many pixel sizes (pixels across = equivalent diameter in pixels; dotted line: the current pixel size).
E1. Preset 12 pixels (exercise) is the object of B1 (shifted by one pixel). Check your answers for A, S, \lambda_1, \lambda_2, the orientation and the eccentricity. What are its three perimeter estimates?
E2. Preset rotate the ellipse. Read S, \lambda_1, \lambda_2 and \theta. Rotate with ⟲ 15° once and twice. What changes, what stays? Compare \theta with the exact orientation in the last column.
E3. Preset a square: equal eigenvalues. What are \lambda_1, \lambda_2 and the orientation? Rotate the square: does anything change? Now drag one corner a little outwards: what happens to the orientation?
E4. Preset the L: the ellipse is not the shape. Read the eigenvalues and the orientation. Which part of the L does the ellipse cover badly? Mirror the L (↔︎): how does the orientation change?
E5. Presets a ring: Euler number 0 and two objects, one hole. Check the Euler number both ways. Drag the small object onto the ring so that they overlap: what is the Euler number now?
E6. Preset a digital disc: 8r, not 2πr. At pixel size 2, read the three perimeter ratios. Move the slider from 8 to 0.25 and watch the plot. Which estimator converges to the true perimeter, which do not, and to what?
E1. A = 12, S = (1.47, 1.14, 1.47), \lambda_1 = 2.61, \lambda_2 = 0.33, orientation -45.0°, eccentricity 0.93, as in B1 (the centroid reads (2.83, 2.83) because the demo’s object starts at pixel 1). Perimeters: edge count 20, chain code 11.9 (2 + 7\sqrt2), Crofton 14.0. The exact outline here is the pixel boundary itself, length 20, so the edge count is exact for this object, and the chain code (through the centres) is much shorter.
E2. Start: S = (98.92, -40.66, 47.21), \lambda_1 = 121.25, \lambda_2 = 24.88, \theta = 28.8° (exact 28.6°). After 15°: S = (74.44, -47.56, 71.37), \lambda_1 = 120.49, \lambda_2 = 25.32, \theta = 44.1°. After 30°: \lambda_1 = 118.94, \lambda_2 = 25.19, \theta = 58.7°. S changes completely; the eigenvalues stay within about 2 % (the digitisation changes a little), and \theta follows the rotation.
E3. \lambda_1 = \lambda_2 = 65.91; the table shows the orientation as undefined. Rotating changes nothing (the square rotated by 20° has the same S as the upright one, up to digitisation). Dragging a corner out makes the eigenvalues slightly different, and the orientation suddenly gets a value pointing towards that corner: an arbitrarily small change of the shape decides the reported angle.
E4. \lambda_1 = 147.33, \lambda_2 = 48.44, orientation -58.0° (eccentricity 0.82). The ellipse runs diagonally from the top of the vertical bar to the end of the foot, covering the empty corner of the L and missing the ends. Mirroring left–right changes the orientation to +58°.
E5. Ring: 1 object, 1 hole, E = 0, and bit-quads (76 - 76 - 0)/4 = 0. Two objects, one hole: E = 2 - 1 = 1, bit-quads (74 - 70 - 0)/4 = 1. Dragged onto the ring so that they overlap, the two outlines merge into 1 object (the even–odd fill may also open a new hole where the outlines overlap): the counts and the bit-quad value change together, they always agree.
E6. At pixel size 2: edge count × 1.273, chain code × 1.023, Crofton × 1.013. In the plot the edge count stays at about 1.27 = 4/\pi at every resolution (from about 10 pixels across); the chain code settles a few per cent above 1 (1.04–1.05); Crofton converges to 1 (1.002 at pixel size 0.25). At very coarse pixels (a few pixels across) all three are erratic.
Code
Write the algorithms of this unit yourself, in Rust. Setup, and how to run and check your code: coding exercises: getting started. Your code goes in labelling/src/regionprops/exercise.rs.
C1. measure(labels): one scan over a label image gives a row per object: area, centroid, central moments and bounding box.
for every pixel (x, y) with label k > 0:
m00[k] += 1; m10[k] += x; m01[k] += y
m20[k] += x²; m11[k] += x·y; m02[k] += y²
update the smallest and largest x and y of k
for every label k:
x̄ = m10/m00, ȳ = m01/m00
μ20 = m20 − m10²/m00, μ11 = m11 − m10·m01/m00, μ02 = m02 − m01²/m00
The checks are B1 (a)–(c) and the rectangle of B5 (b), both in one label image.
C2. ellipse(region): the eigenvalues of S (largest first) and the angle \theta = \tfrac12\operatorname{atan2}(2\mu_{11}, \mu_{20} - \mu_{02}) of the major axis. In the code \theta turns from x towards y, i.e. clockwise on screen; the orientation of the exercises (counter-clockwise on screen) is -\theta. The checks are B1 (d)–(e), B5 (b), and a turned copy of the B1 object (same eigenvalues).
C3. perimeter_edges(mask): count the pixel edges between object and background (outside the image is background). The checks are B2 (b) and B4 (a).
C4. perimeter_crofton(mask): count the crossings of the boundary along the rows (n_0), the columns (n_{90}) and both diagonals (n_{45}, n_{135}): pairs of neighbouring pixels in that direction of which exactly one is object. Then P \approx \tfrac{\pi}{8}\big(n_0 + n_{90} + (n_{45} + n_{135})/\sqrt2\big).
C5. bit_quads(mask) and euler_number(mask, eight): count the 2 \times 2 windows (including those that stick out of the image) with one object pixel, with three, and with a diagonal pair; then E_8 = (Q_1 - Q_3 - 2Q_D)/4, E_4 = (Q_1 - Q_3 + 2Q_D)/4. The check is B3.
Then cargo run -p labelling -- regionprops and open the pictures in out/regionprops/. The program prints the table of 12 synthetic nuclei (their true labels) and draws the equivalent ellipses in nuclei-ellipses.png; it measures digital discs of growing radius; and it computes the Euler number of the dark regions of the micrograph (grey level below 95 of 255).
C6. In the disc table, the perimeters are divided by the perimeter of the circle with the same area. To what does each ratio go as the radius grows? Which estimator would you use for the form factor 4\pi A/P^2 of the nuclei, and why do some nuclei in the table have a form factor well below 1?
C7. The Euler number of the micrograph’s dark regions is 528 with objects 8 and 1075 with objects 4. The labelling program of the last unit counts 764 and 1141 objects in the same mask. How many holes are there in each case? Why does the bit-quad count need no labelling at all?
The model solution is labelling/src/regionprops/solution.rs in the download.
C6. The edge count falls from 1.57 (radius 2) through 1.37 (radius 8) to 1.28 (radius 100): towards 4/\pi = 1.273, and never to 1. Crofton is 1.05 to 1.06 for radii 2 to 8 and 1.004 at radius 64: it goes to 1. Use Crofton for the form factor: with the edge count every disc would get about (\pi/4)^2 = 0.62. Most nuclei have form factors from 0.91 to 1.01. Labels 2 and 4 (0.78 and 0.73) are partly covered by a neighbouring nucleus in the true label image (where two overlap, the later one wins): their outline has a dent where the other nucleus cuts in, which makes it longer for its area. In nuclei-ellipses.png they are the smaller partners of touching pairs (at the top and in the middle).
C7. Holes = objects − E. Objects 8, background 4: 764 - 528 = 236 holes. Objects 4, background 8: 1141 - 1075 = 66 holes; with 8-connected background, many small enclosed pockets leak out through diagonal gaps. The Euler number is a sum over 2 \times 2 windows, each of which contributes a fixed amount (the math slide), so a single scan with no labels and no equivalences gives it.
Where this leads
Moments summarise an object by its spread. The next unit, shape features, measures the outline itself: convex hull and solidity, Feret diameters, the form factor (which inherits the perimeter bias of this unit), inscribed circles and Fourier descriptors. The moments day (day 18) continues with higher-order moments and invariants (Hu), recalling the moments of this unit.