Exercise: non-rigid registration

Goal

By the end of this exercise you should be able to:

  • compute the displacement of a B-spline free-form deformation from its control points,
  • decide from the Jacobian determinant whether a deformation folds,
  • compute entropies and the mutual information of a small joint histogram by hand,
  • choose a similarity measure (SSD, NCC, MI) for a pair of images,
  • recognise when a registration explains away real change,
  • (math) verify the B-spline properties and the properties of mutual information.

Background

Idea What it means
Deformation field \mathbf d(\mathbf x) the moving image is sampled at \mathbf x + \mathbf d(\mathbf x) to match the fixed image at \mathbf x
Free-form deformation (FFD) \mathbf d(\mathbf x) = \sum_{k,l}\mathbf c_{kl}\,\beta^3(x/\Delta - k)\,\beta^3(y/\Delta - l): control points every Δ px
Cubic B-spline \beta^3 \tfrac23 - t^2 + \tfrac12|t|^3 for |t| < 1; \tfrac16(2 - |t|)^3 for 1 \le |t| < 2; 0 beyond. Knot values \tfrac16, \tfrac46, \tfrac16
Jacobian determinant local area change of \mathbf x \mapsto \mathbf x + \mathbf d: > 1 larger in the moving image, < 1 smaller, \le 0 folding
SSD, NCC, MI same contrast; straight-line relation (gain, offset); any consistent relation
Entropy H = -\sum p\log_2 p bits: average number of yes/no questions to guess a value
Mutual information \mathrm{MI} = H(A) + H(B) - H(A, B)

By hand

B1. A 1D FFD. Control points every 10 px at x = 0, 10, 20, 30, 40 with displacements (0, 0, 6, 0, 0). (a) Compute d(20), d(10), d(30) and d(15). (You need \beta^3(0) = \tfrac46, \beta^3(1) = \tfrac16, \beta^3(0.5) = \tfrac{23}{48}.) (b) Sketch d(x). How far does the influence of the moved control point reach? (c) All five coefficients are 6. What is d(x) between 10 and 30?

B2. Folding in 1D. The map x \mapsto x + d(x) folds where d'(x) < -1. For the bump of B1 the steepest slope of d is 0.4 (it occurs at x \approx 13.3 and 26.7; on a grid of spacing Δ the slope of a single bump with coefficient c is at most \tfrac23\,c/\Delta). (a) Does the bump of B1 fold? From which coefficient on would it fold? (b) With control points every 5 px instead of 10, from which coefficient on does a single bump fold? What does that say about fine grids?

B3. Jacobian determinants. Compute the Jacobian determinant of \mathbf x \mapsto \mathbf x + \mathbf d(\mathbf x) for (a) \mathbf d = (0.1x, 0); (b) \mathbf d = (0.1x, 0.1y); (c) \mathbf d = (0.5y, 0); (d) \mathbf d = (-1.2x, 0). Interpret each.

B4. Mutual information by hand. Eight pixels, two grey levels each. (a) A = (0,0,0,0,1,1,1,1), B = 1 - A. Write the joint histogram (rows A, columns B), and compute H(A), H(B), H(A, B) and MI. What is the NCC? (b) B = (0,0,1,1,0,0,1,1): the joint counts are all 2. Compute H(A, B) and MI. (c) B = (1,1,1,0,0,0,0,0): one pixel is “wrong”. Joint counts? Compute MI.

B5. Entropy. Compute H for a histogram with (a) one value only; (b) two equally likely values; (c) four equally likely values; (d) probabilities \tfrac12, \tfrac14, \tfrac14.

B6. Choose the measure: (a) two frames of a time-lapse; (b) a DAPI image to a brightfield image; (c) H&E to an immunofluorescence section; (d) a fluorescence image whose laser power changed between acquisitions (all values scaled by 0.7).

B7. One control point in 2D. Control points every 16 px. One control point is moved by (9, 0). How far do (a) the pixel at that control point, (b) the pixel at the next control point to the right, (c) the pixel at the next control point diagonally, move?

B1. (a) d(20) = 6 \cdot \tfrac46 = 4; d(10) = 6 \cdot \beta^3(-1) = 6 \cdot \tfrac16 = 1; d(30) = 1; d(15) = 6\,\beta^3(-0.5) = 6 \cdot \tfrac{23}{48} = 2.875. (b) A smooth bump, 4 at x = 20, 1 at 10 and 30, 0 at 0 and 40 and beyond: it reaches two control spacings (20 px) either side. (c) 6 everywhere (partition of unity: \sum_k\beta^3(t - k) = 1): a translation. (Near the ends of the grid the sum would need the control points outside the range too.)

B2. (a) 0.4 > -1: no folding. The slope scales with the coefficient: 0.4 = \tfrac23 \cdot 6/10, so folding starts when \tfrac23\,c/10 > 1, i.e. c > 15 px. (b) \tfrac23\,c/5 > 1: c > 7.5 px. A finer grid can bend more sharply, so the same displacement folds sooner: fine grids need a bending penalty.

B3. (a) \begin{vmatrix}1.1 & 0\\0 & 1\end{vmatrix} = 1.1: 10 % larger in the moving image (stretched along x). (b) 1.1 \cdot 1.1 = 1.21: 21 % larger. (c) \begin{vmatrix}1 & 0.5\\0 & 1\end{vmatrix} = 1: a shear, the shape changes but the area does not. (d) 1 - 1.2 = -0.2: folding; the map runs backwards along x.

B4. (a) Counts \begin{pmatrix}0 & 4\\4 & 0\end{pmatrix}, p = \begin{pmatrix}0 & \tfrac12\\ \tfrac12 & 0\end{pmatrix}. H(A) = H(B) = 1 bit; H(A, B) = -2 \cdot \tfrac12\log_2\tfrac12 = 1 bit; MI = 1 + 1 − 1 = 1 bit, the maximum (= H(A)): B is determined by A. NCC = −1. (b) All p = \tfrac14: H(A, B) = 2 bits, MI = 1 + 1 − 2 = 0: knowing A says nothing about B. (c) Counts \begin{pmatrix}1 & 3\\4 & 0\end{pmatrix} (rows A = 0, 1; columns B = 0, 1). H(A) = 1; B has 5 zeros and 3 ones: H(B) = 0.954; H(A, B) = -[\tfrac18\log_2\tfrac18 + \tfrac38\log_2\tfrac38 + \tfrac48\log_2\tfrac48] = 1.406; MI = 1 + 0.954 − 1.406 = 0.549 bits. One wrong pixel in eight roughly halves the MI.

B5. (a) 0. (b) 1 bit. (c) 2 bits. (d) \tfrac12 \cdot 1 + 2 \cdot \tfrac14 \cdot 2 = 1.5 bits.

B6. (a) SSD. (b) MI (nuclei bright in one, dark or grey in the other: consistent but not a straight line). (c) MI. (d) NCC (a gain change keeps a straight-line relation; SSD would be biased).

B7. (a) 9 \cdot \tfrac46 \cdot \tfrac46 = 4 px. (b) 9 \cdot \tfrac16 \cdot \tfrac46 = 1 px. (c) 9 \cdot \tfrac16 \cdot \tfrac16 = 0.25 px. All along x.

Math questions

B8. (math) Verify \beta^3(0) = \tfrac23, \beta^3(\pm1) = \tfrac16, \beta^3(\pm2) = 0, that \beta^3 and its first and second derivatives are continuous at |t| = 1, and that \sum_k \beta^3(t - k) = 1 for t \in [0, 1) (four terms).

B9. (math) Show that \mathrm{MI} \ge 0 with equality iff p(a, b) = p(a)p(b) (use \log x \le x - 1), and that \mathrm{MI} \le \min(H(A), H(B)).

B10. (math) Show that MI (with exact, one-bin-per-value histograms) does not change if the grey values of B are relabelled by any one-to-one map f, while NCC does change unless f is linear increasing. Give an example of a non-linear one-to-one f that changes NCC.

B11. (math) The SSD cost is C = \sum_{\mathbf x}\big(M(\mathbf x + \mathbf d(\mathbf x)) - F(\mathbf x)\big)^2 with \mathbf d an FFD. Show that \frac{\partial C}{\partial c^x_{kl}} = \sum_{\mathbf x} 2\big(M(\mathbf x + \mathbf d) - F(\mathbf x)\big)\,M_x(\mathbf x + \mathbf d)\,\beta^3\!\Big(\frac{x}{\Delta} - k\Big)\beta^3\!\Big(\frac{y}{\Delta} - l\Big), and explain why only pixels within two spacings of the control point contribute.

B8. \beta^3(0) = \tfrac23; at t = 1: inner formula \tfrac23 - 1 + \tfrac12 = \tfrac16, outer formula \tfrac16(2 - 1)^3 = \tfrac16 (continuous). Derivatives for t > 0: inner -2t + \tfrac32t^2 \to -\tfrac12, outer -\tfrac12(2 - t)^2 \to -\tfrac12; second derivatives: inner -2 + 3t \to 1, outer (2 - t) \to 1. At t = 2 the outer formula and its first two derivatives are 0. For t \in [0, 1) the four nonzero terms are \beta^3(t + 1) + \beta^3(t) + \beta^3(t - 1) + \beta^3(t - 2) = \tfrac16(1 - t)^3 + (\tfrac23 - t^2 + \tfrac12t^3) + (\tfrac23 - (1 - t)^2 + \tfrac12(1 - t)^3) + \tfrac16t^3; expanding, the t^3, t^2 and t terms cancel and the constant is \tfrac16 + \tfrac23 + \tfrac16 = 1.

B9. -\mathrm{MI} = \sum p(a,b)\log_2\frac{p(a)p(b)}{p(a,b)} \le \frac{1}{\ln 2}\sum p(a,b)\Big(\frac{p(a)p(b)}{p(a,b)} - 1\Big) = \frac{1}{\ln 2}\Big(\sum_{a,b:\,p(a,b)>0}p(a)p(b) - 1\Big) \le 0, with equality iff p(a)p(b) = p(a,b) everywhere (equality in \log x \le x - 1 needs x = 1). Upper bound: \mathrm{MI} = H(A) - H(A \mid B) with the conditional entropy H(A \mid B) = H(A, B) - H(B) \ge 0 (an average of entropies), so \mathrm{MI} \le H(A); likewise \le H(B).

B10. A one-to-one relabelling of B permutes the columns of the joint histogram: the set of probabilities p(a, b) and the column sums p(b) are the same numbers in a different order, so H(B), H(A, B) and MI are unchanged. NCC depends on the values themselves: with A = B = (0, 1, 2), NCC = 1; relabel B by f(0) = 0, f(1) = 2, f(2) = 1 (one-to-one, not monotone): f(B) = (0, 2, 1), NCC = 0.5. Even a monotone but non-linear f, e.g. f(v) = v^3 on (0, 1, 2) giving (0, 1, 8), lowers NCC (to 0.96).

B11. Chain rule: \partial C/\partial c^x_{kl} = \sum_{\mathbf x}2(M(\mathbf x + \mathbf d) - F)\,\partial M(\mathbf x + \mathbf d)/\partial c^x_{kl}, and \partial M(\mathbf x + \mathbf d)/\partial c^x_{kl} = M_x(\mathbf x + \mathbf d)\,\partial d_x/\partial c^x_{kl} = M_x(\mathbf x + \mathbf d)\,\beta^3(x/\Delta - k)\beta^3(y/\Delta - l), because \mathbf d is linear in the coefficients. \beta^3 vanishes beyond |t| \ge 2, so only pixels within two spacings in x and in y contribute: each gradient component is a local, B-spline-weighted sum (all of them together: a blur of the per-pixel gradient image, sampled on the grid).

Explore

Explore: joint histogram and similarity

Fixed image: a 96² crop of the micrograph; moving image: the same crop with its contrast mapped (same, gain + offset, inverted, non-monotone) plus noise. Slide the moving image: the overlay (fixed magenta, moving green), the joint histogram of the overlapping pixels (log counts; fixed value across, moving value up), and SSD (negated), NCC and MI against the x shift, each scaled to its own range, with the current shift dashed. The readout gives the values and each measure’s best shift.

J1. Preset aligned: a thin line, then misaligned: a cloud. Read NCC and MI in both. Why does the histogram spread out?

J2. Preset inverted. Read SSD, NCC and MI, and the best shift of each. Which measures “know” that the images are aligned?

J3. Preset non-monotone. Describe the joint histogram. Which measure peaks at the true alignment?

J4. Contrast gain + offset at shift 0: compare SSD and NCC with the aligned case. What does NCC ignore?

J5. Preset too many bins (128 bins). What does the histogram look like? Where is the maximum of the MI curve now? Reduce the bins to 16.

J6. Preset tiny overlap (shift 80, 64 bins). How many pixels overlap? Compare the MI here with the MI at a shift of 40. What goes wrong?

J1. Aligned: NCC 0.986, MI 2.06 bits; misaligned by (6, 3): NCC 0.43, MI 0.20 bits. When the images are shifted, a fixed value no longer predicts the moving value: the pixels pair up with neighbours of different brightness and the joint histogram spreads into a cloud.

J2. SSD 0.127, NCC −0.986, MI 2.04 bits (as high as when aligned). Best shift: SSD −27, NCC −30, MI 0. Only MI picks the true alignment; NCC sees a perfect (negative) relation, but a score that is maximised wants +1, and SSD is worst exactly at the alignment.

J3. A hump: mid-grey in the fixed image maps to bright in the moving one, both dark and bright to dark. At the true alignment MI is 1.83 bits and is the only measure that peaks there; SSD and NCC are best at the far ends of the shift range.

J4. NCC 0.948 (against 0.986) and SSD 0.0087 (against 0.0009). NCC ignores gain and offset (it compares deviations from the mean, scaled by the spread), so it barely changes (the noise is relatively larger at the lower gain); SSD sees the brightness difference as misalignment. MI is 1.31 bits: with half the contrast, the moving image uses fewer bins.

J5. With 128 bins and about 9000 pixels most bins hold 0 or 1 count: a speckle in which every pattern looks “tight”. The maximum of the MI curve moves to the edge of the range (shift −84), where the overlap is smallest and the histogram emptiest. With 16 bins it is back at 0.

J6. 1536 pixels (16 columns). MI 0.89 bits, three times the 0.29 bits at a shift of 40 (5376 pixels), although neither is aligned: with few pixels spread over 64 × 64 bins the histogram is sparse and MI is biased upwards. A registration that maximises MI can drift towards small overlaps; normalised MI and a minimum overlap guard against that.

Explore: free-form registration

Fixed image: a 128² crop of the micrograph (0 to 1). Moving image: the fixed one deformed by a known smooth random field (mean displacement 2.3 px, at most 4.4 px), with its contrast optionally changed, plus noise. Drag the yellow control points to deform by hand, or press optimise: gradient descent on similarity + λ · bending, coarse to fine if ticked. Tabs: a checkerboard of the fixed and the registered image, their difference, the moving image with the grid it is sampled on, the registered image, the Jacobian determinant (black = folding). The readout gives the error against the true field (2.41 px before registration).

R1. Preset drag one control point: one coefficient of 9 px to the right. Look at the cyan grid in the moving tab and at the Jacobian tab. Drag the point further (the demo allows up to 30 px): does black (folding) appear?

R2. Preset optimise with SSD. Watch the checkerboard while it runs. Read the final error, the number of iterations and the range of the Jacobian determinant.

R3. Preset inverted contrast: SSD fails, MI works. What does SSD do to the grid? Read the error and the folded pixels. Select mutual information and optimise again (press zero grid first). Then try NCC.

R4. Preset fine grid, λ = 0: folding (grid 6 px, noise 0.25). How many pixels fold? Set λ to 1, press zero grid and optimise again. And λ = 100?

R5. Preset too free: it explains away a growing blob: a bright blob that is larger in the moving image, nothing else moves. Look at the Jacobian at the blob after optimising. Repeat with λ = 100, and with grid spacing 32 and λ = 0. Which result tells the truth?

R1. The grid bulges locally around the control point: pixels within two spacings (32 px) sample the moving image further to the right; the Jacobian is 0.75 on one side of the point and 1.25 on the other at 9 px. Dragging along x does not fold within the demo’s 30 px limit (minimum Jacobian 0.17 at 30 px): the steepest slope is c \cdot \tfrac23 \cdot \tfrac46 / 16 (B2, times the factor \tfrac46 of the row), which reaches 1 only at c = 36 px. Moving two neighbouring control points towards each other folds much sooner.

R2. The checkerboard seams disappear as the grid refines from 32 to 16 px. Final error 0.05 px after 96 iterations; Jacobian between 0.86 and 1.13, no folding.

R3. SSD tries to make the inverted image look like the original, which no smooth deformation can: it crumples the grid (error 30 px, 4786 folded pixels). Mutual information: error 0.07 px, no folding. NCC fails too (error 60 px): an inverted image has NCC −1 at the true alignment, and a cost that rewards +1 pushes away from it.

R4. 57 folded pixels (Jacobian down to −0.20; error 1.28 px): the fine grid fits the noise. λ = 1: no folding, Jacobian 0.32 to 1.49, error 0.68 px; λ = 10: 0.64 px. λ = 100: 1.68 px, the deformation is too stiff to follow the true field.

R5. With a 8 px grid and λ = 0 the registration matches the blob perfectly by deforming it: the Jacobian at the blob is about 3.3 (the “deformation” explains the growth). With λ = 100 it is about 1.9 and the residual difference shows the growth, partly; with a 32 px grid and λ = 0, about 1.5. None of them is “right” in an absolute sense: the deformation model cannot tell growth from motion. The honest result keeps the deformation smooth enough for the question and reports the Jacobian; a blob with a large Jacobian is a candidate for real growth, to be checked independently.

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 opticalflow/src/nonrigid_reg/exercise.rs.

C1. bspline3(t): the cubic B-spline of the Background table. The checks are the values of B8 and the partition of unity.

C2. ffd_displacement(cx, cy, spacing, x, y): the displacement of a free-form deformation. The coefficients are two small images, one value per control point; control point (k, l) sits at pixel ((k - 1)\Delta, (l - 1)\Delta), so that one ring of control points lies outside the image. The checks are B1 and B7.

k0 = ⌊x / Δ⌋,  l0 = ⌊y / Δ⌋
d = (0, 0)
for l = l0 .. l0 + 3,  k = k0 .. k0 + 3:            # the 4 × 4 control points nearby
    w = β(x/Δ − k + 1) · β(y/Δ − l + 1)
    d = d + w · (cx[k, l], cy[k, l])

C3. jacobian_determinant(dx, dy): at every pixel, by central differences, (1 + \partial_x d_x)(1 + \partial_y d_y) - \partial_y d_x\,\partial_x d_y. The check is B3.

C4. entropy(p) in bits, and mutual_information(a, b, bins) of two images with values in [0, 1]. The checks are B5 and B4.

joint = bins × bins zeros
for every pixel:  joint[bin of a, bin of b] += 1          # bin = min(⌊v · bins⌋, bins − 1)
p = joint / number of pixels;  pa = row sums of p;  pb = column sums of p
MI = H(pa) + H(pb) − H(p),   with H(q) = −Σ q log2 q over the non-empty bins

C5. register_ssd(fixed, moving, spacing, iterations, step): gradient descent on the SSD (B11), from zero coefficients.

∇M = gradient of the moving image (once)
repeat N times:
    G = zeros, one pair per control point
    for every pixel x:
        d = ffd_displacement(c, x);   r = M(x + d) − F(x)
        for each of its 4 × 4 control points (k, l), weight w = β β as in C2:
            G[k, l] += 2 · r · ∇M(x + d) · w
    c = c − step · G

The check: a smooth pattern moved by (1.5, -1) must be registered to a displacement of (1.5, -1).

Then cargo run -p opticalflow -- nonrigid-reg and open the pictures in out/nonrigid-reg/. First the program compares SSD and mutual information (16 bins) on a 96 × 96 crop of the micrograph and a noisy copy, with the same and with inverted contrast, for shifts along x from −30 to 30. Then it deforms a 128 × 128 crop with a smooth random free-form deformation (control points every 32 px), so the true displacement is known, and registers it with your register_ssd (control points every 16 px, 200 iterations), once with the same contrast and once with the moving image inverted. The checkerboards alternate the fixed image and the registered moving image in squares of 16 px; the Jacobian pictures run from black (smallest) to white (largest).

C6. SSD and MI against the shift: which shift does each pick, with the same and with inverted contrast? Compare the MI at shift 0 in the two cases.

C7. The registration with the same contrast: the error against the true displacement before and after, and the range of the Jacobian determinant. Compare checker-before.png with checker-after-same.png.

C8. The registration of the inverted image with SSD: what happens to the error and to the Jacobian? Look at checker-after-inverted.png (the registered image is inverted back for the picture). Which measure should the registration have used, and what would it need that this code does not have?

The model solution is opticalflow/src/nonrigid_reg/solution.rs in the download.

C6. Same contrast: SSD and MI both pick shift 0 (SSD 0.0009, MI 2.16 bits; at a shift of 6 the MI is only 0.12 bits). Inverted: MI still picks 0, with the same 2.16 bits, because inverting only relabels the bins (B10). SSD is 0.40 at shift 0 and picks −30, the end of the tested range: it wants the images to look alike, which an inverted copy never does.

C7. The true displacement has a mean of 1.96 px (at most 3.64 px). After registration the mean error is 0.07 px. The Jacobian determinant lies between 0.85 and 1.12: mild compression and stretching, no folding. In checker-before.png the membranes jump at the square borders; in checker-after-same.png they run straight across.

C8. The error grows from 1.96 to 10.48 px; the Jacobian runs from −0.54 to 5.30, and 1566 pixels fold. SSD rewards moving bright pixels of the inverted image onto bright pixels of the fixed image, which no smooth deformation can do consistently, and checker-after-inverted.png is crumpled and smeared. The registration should have maximised mutual information, which is as high for the inverted pair as for the original (C6). For gradient descent it needs the derivative of MI with respect to the coefficients, which needs a histogram that changes smoothly with the displacement (each value spread over two neighbouring bins, slide “The math: mutual information”).

Where this leads

The tracking day (day 26) follows objects (cells, nuclei) rather than pixels: detection, linking over time, divisions and lineages, with optical flow as one source of motion predictions. The splines day (day 6) treats B-splines, the building block of the free-form deformation, in depth: B-splines and splines on images.