Exercise: the snake as a linear system
Before this unit: Active contours (snakes) (previous unit); Day 27: Graph cuts; Day 2: Edges, blobs and ridges.
See also: Day 6: Splines and NURBS.
Goal
By the end of this exercise you should be able to:
- write the snake matrix A for a small n and read its properties,
- give the eigenvalues of A and say which shapes of the curve each one belongs to,
- find the largest stable step of the explicit update, and the factor per step of the semi-implicit one,
- explain the capture range and choose between a larger \sigma, a balloon force and GVF,
- (math) derive the eigenvalues of a circulant matrix and the semi-implicit step.
Do the pen-and-paper part first, then the two demos. Questions marked (math) are for those who want the derivations.
Background
| Idea | What it means |
|---|---|
| Snake matrix A | n \times n, row i: \beta,\ -\alpha-4\beta,\ 2\alpha+6\beta,\ -\alpha-4\beta,\ \beta at columns i-2, \dots, i+2 (mod n); internal force = -A\mathbf x |
| Modes | the sampled waves \cos(2\pi kj/n), \sin(2\pi kj/n): eigenvectors of A |
| Eigenvalues | \lambda_k = 4\alpha\sin^2(\pi k/n) + 16\beta\sin^4(\pi k/n); \lambda_\text{max} = 4\alpha + 16\beta (n even) |
| Explicit step | \mathbf x \leftarrow \mathbf x + \tau(-A\mathbf x + \mathbf f): mode k times 1 - \tau\lambda_k |
| Semi-implicit step | (A + \gamma I)\mathbf x_\text{new} = \gamma\mathbf x + \mathbf f, \gamma = 1/\tau: mode k times 1/(1 + \tau\lambda_k) |
| Balloon | \kappa\,\mathbf n_i along the outward normal of each bead |
| GVF | \mathbf v \leftarrow \mathbf v + \Delta t\,[\mu\nabla^2\mathbf v - \lvert\nabla f\rvert^2(\mathbf v - \nabla f)], starting from \mathbf v = \nabla f |
By hand
B1. n = 6, \alpha = 1, \beta = 0. (a) Write A. Which entries come from the curve being closed? (b) Check that A\mathbf 1 = 0. What does that mean for the snake? (c) Check that (1, -1, 1, -1, 1, -1) is an eigenvector. Eigenvalue? Draw what this pattern does to the x coordinates of a hexagon.
B2. Still n = 6. (a) Give all six eigenvalues \lambda_0, \dots, \lambda_5 for \alpha = 1, \beta = 0. Which are equal, and why? (b) The same for \alpha = 1, \beta = 1. Which modes does \beta make most expensive?
B3. Explicit step, n = 6. (a) With \alpha = 1, \beta = 0: what is the largest \tau for which no mode grows? Give the factor per step of modes k = 1, 2, 3 for \tau = 0.1, 0.5 and 1. (b) With \alpha = \beta = 1: largest stable \tau?
B4. Semi-implicit step, n = 6, \alpha = 1, \beta = 0. (a) Factor per step of modes k = 1, 2, 3 for \tau = 1 (\gamma = 1). Compare with the explicit step at the same \tau. (b) What happens to the factors when \tau becomes huge? What does the snake look like after one such step?
B5. Unit 1’s snake: n = 40, \alpha = 0.1, \beta = 0.05, semi-implicit \tau = 1. (a) \lambda_\text{max}, and the largest stable \tau for the explicit step. (b) Mode k = 1 (the overall size of a circle): its eigenvalue and factor per step. About how many steps does it take, without an image, for the circle to shrink to half its radius?
B6. 1D GVF. Seven samples of the edge force g = \nabla f along a line: g = (0, 0, 1, 0, -1, 0, 0) (the edge is at sample 3, counting from 0). Take \mu = 0.25, \Delta t = 1, \mathbf v = g at the start, and at the two ends repeat the end value (so v''_0 = v_1 - v_0). (a) Do one update v_i \leftarrow v_i + \mu(v_{i-1} - 2v_i + v_{i+1}) - g_i^2(v_i - g_i). (b) Do a second update. Where is the force now non-zero that was zero before? Does it point towards the edge? (c) What would the plain edge force do to a bead at sample 0?
B7. Predict, for a balloon started inside a bright disk: (a) \kappa very small; (b) \kappa moderate; (c) \kappa large; (d) moderate \kappa, but the edge of the disk is faint on one side.
B1. (a) Rows (2, -1, 0, 0, 0, -1), (-1, 2, -1, 0, 0, 0), …, (-1, 0, 0, 0, -1, 2): the -1 in the top-right and bottom-left corners link bead 0 and bead 5, which are neighbours only because the curve is closed. (b) Every row sums to 2 - 1 - 1 = 0. Moving all beads by the same amount creates no internal force: the snake can be anywhere. (c) Row 0: 2\cdot1 - (-1) - (-1) = 4; row 1: -1 \cdot 1 + 2\cdot(-1) - 1\cdot1 = -4, and so on: A\mathbf v = (4, -4, 4, -4, 4, -4) = 4\mathbf v. Eigenvalue 4. Added to the x coordinates of a hexagon it pushes alternate corners left and right: a zig-zag, the most bent pattern.
B2. (a) \lambda_k = 4\sin^2(\pi k/6): 0, 1, 3, 4, 3, 1. \lambda_k = \lambda_{6-k}: the waves \cos and \sin of the same frequency have the same cost (a wave and its shifted copy). (b) Add 16\sin^4(\pi k/6): 0, 2, 12, 20, 12, 2. Mode 1 goes from 1 to 2, mode 3 from 4 to 20: \beta makes the wiggly modes far more expensive.
B3. (a) \lambda_\text{max} = 4: stable for \tau \le 2/4 = 0.5. Factors 1 - \tau\lambda_k for k = 1, 2, 3: \tau = 0.1: 0.9, 0.7, 0.6. \tau = 0.5: 0.5, -0.5, -1 (the zig-zag flips sign forever, neither growing nor shrinking). \tau = 1: 0, -2, -3: modes 2 and 3 explode. (b) \lambda_\text{max} = 20: \tau \le 0.1.
B4. (a) 1/(1 + \lambda_k): 0.5, 0.25, 0.2, against 0, -2, -3 for the explicit step at \tau = 1. All between 0 and 1: stable, the wiggles shrink fastest. (b) All factors go to 0 except k = 0 (factor 1): after one huge step only the mean position is left, the snake collapses to its centroid. Stable, but the image force must then do all the work in each step.
B5. (a) \lambda_\text{max} = 0.4 + 0.8 = 1.2; explicit stable for \tau < 1.67. (b) \lambda_1 = 0.4\sin^2(\pi/40) + 0.8\sin^4(\pi/40) = 0.00249; factor 1/1.00249 = 0.99751. Half the radius after \ln 2/(-\ln 0.99751) = 278 steps. That is why the snake of unit 1 needed about a hundred steps to shrink from radius 45 to the edge.
B6. (a) v = (0, 0.25, 0.5, 0, -0.5, -0.25, 0). (At sample 2: 1 + 0.25(0 - 2 + 0) - 1\cdot(1 - 1) = 0.5; at sample 1: 0 + 0.25(0 - 0 + 1) - 0 = 0.25.) (b) v = (0.0625, 0.25, 0.8125, 0, -0.8125, -0.25, -0.0625). Samples 0, 1, 5, 6, where g = 0, now have a force, positive on the left (pointing right, towards the edge) and negative on the right: towards the edge. Next to the edge the data term pulls v back towards g (sample 2: from 0.5 up to 0.81). (c) Nothing: g_0 = 0. The bead is outside the capture range of the plain edge force.
B7. (a) It hardly grows: the elastic force (and noise) hold it. (b) It inflates until it reaches the edge, where the edge force balances the balloon. (c) It pushes through the edge and keeps growing. (d) It stops on the strong side but leaks through the faint side: the balloon is the same everywhere, the edge force is not.
Math questions
B8. (math) Show that \mathbf v with v_j = e^{2\pi ikj/n} is an eigenvector of any circulant matrix (row j = row 0 shifted by j), with eigenvalue \sum_m a_m e^{2\pi ikm/n} where a_m is the entry of row 0 in column m. Use it to derive \lambda_k = 4\alpha\sin^2(\pi k/n) + 16\beta\sin^4(\pi k/n).
B9. (math) Show that A is positive semidefinite by writing \tfrac12\mathbf x^\top A\mathbf x as the internal energy (for one coordinate). When is \mathbf x^\top A\mathbf x = 0?
B10. (math) Derive the semi-implicit step from \mathbf x_{t+1} = \mathbf x_t - \tau(A\mathbf x_{t+1} - \mathbf f_t). Show that A + \gamma I is invertible for every \gamma > 0 and that the internal part of the step never increases the internal energy.
B11. (math) Show that the GVF update is gradient descent (up to a factor 2) on \mathcal E(\mathbf v) = \sum_\text{pixels}\mu|\nabla \mathbf v|^2 + |\nabla f|^2|\mathbf v - \nabla f|^2 (finite differences for \nabla\mathbf v). Why is \Delta t \le 1/(4\mu) needed for stability in flat regions?
B8. Row j has entry a_{m} in column j + m (mod n). (A\mathbf v)_j = \sum_m a_m v_{j+m} = \sum_m a_m e^{2\pi ik(j+m)/n} = \big(\sum_m a_m e^{2\pi ikm/n}\big) v_j. For the snake, a_0 = 2\alpha + 6\beta, a_{\pm1} = -\alpha - 4\beta, a_{\pm2} = \beta; with c = \cos(2\pi k/n): \lambda_k = 2\alpha + 6\beta - 2(\alpha + 4\beta)c + 2\beta\cos(4\pi k/n). With \cos(4\pi k/n) = 2c^2 - 1 this is 2\alpha(1 - c) + 4\beta(1 - c)^2, and 1 - c = 2\sin^2(\pi k/n) gives 4\alpha\sin^2 + 16\beta\sin^4.
B9. For one coordinate, \tfrac12\mathbf x^\top A\mathbf x = \sum_j\tfrac12\alpha(x_{j+1} - x_j)^2 + \tfrac12\beta(x_{j-1} - 2x_j + x_{j+1})^2 \ge 0 (the gradient of this quadratic is A\mathbf x, and a quadratic form equals half its gradient dotted with \mathbf x). With \alpha > 0 it is zero only when all x_j are equal: the null space is the translations, \lambda_0 = 0.
B10. Moving \tau A\mathbf x_{t+1} to the left: (I + \tau A)\mathbf x_{t+1} = \mathbf x_t + \tau\mathbf f_t; divide by \tau. A is symmetric with eigenvalues \lambda_k \ge 0, so A + \gamma I has eigenvalues \lambda_k + \gamma > 0. Internal part: in the eigenbasis each coefficient c_k becomes c_k/(1 + \tau\lambda_k), with |{\cdot}| \le |c_k|, and the internal energy is \tfrac12\sum_k\lambda_k c_k^2: it cannot increase.
B11. \partial\mathcal E/\partial\mathbf v_p: the smoothness term \mu\sum|\mathbf v_q - \mathbf v_p|^2 over neighbour pairs gives -2\mu(\sum_{q \sim p}\mathbf v_q - 4\mathbf v_p) = -2\mu\nabla^2\mathbf v_p, the data term 2|\nabla f|^2(\mathbf v_p - \nabla f). So -\tfrac12\partial\mathcal E/\partial\mathbf v_p = \mu\nabla^2\mathbf v_p - |\nabla f|^2(\mathbf v_p - \nabla f), the update direction. In flat regions only the diffusion acts: \mathbf v \leftarrow (1 + \Delta t\mu\nabla^2)\mathbf v; the most negative eigenvalue of the 5-point Laplacian is -8 (checkerboard), so the checkerboard is multiplied by 1 - 8\mu\Delta t, which stays \ge -1 only for \Delta t \le 1/(4\mu): the same stability argument as for the explicit snake step.
Explore: the modes of a snake
No image here: a closed polygon of n beads moves under its internal forces only. Drag the beads to make your own shape. The plots show, for each mode k (number of waves around the curve): the eigenvalue \lambda_k (with the explicit limit 2/\tau dashed), the factor per step (green inside \pm1, red outside), and the size of the mode in the current contour (grey bars: at the start; dots: now). show matrix A replaces the contour by A.
S1. Preset n = 6: the matrix by hand. Compare the matrix with B1, the eigenvalues with B2(a), the factors with B3(a) for \tau = 0.2. Add \beta = 1: which entries change?
S2. Preset α only: shrinks to a point (noisy circle, n = 16, \alpha = 0.2, semi-implicit \tau = 1). Step 10 times. Which modes disappear first? Read the factor of mode 1 and estimate after how many steps the circle has half its radius. Check with the demo.
S3. Preset β only. Compare the factors of mode 1 and mode 8 with S2. Which snake keeps its size longer, and which smooths its wiggles faster?
S4. Presets explicit at the limit and explicit just beyond: explodes. Read \tau\lambda_\text{max} and the factor of mode 8. Step and watch the contour and the bottom plot. Then switch the second one to semi-implicit.
S5. Preset semi-implicit, huge τ: still stable (\tau = 50). What does one step do to the noisy circle? Why is that not a useful way to run a snake on an image?
S6. Choose star with n = 32, \alpha = 0.1, \beta = 0, semi-implicit \tau = 1. Which modes carry the star’s points (look at the grey bars)? Play: in which order does the star turn into a circle and the circle into a point?
S1. The matrix is B1’s (rows 2, -1, 0, 0, 0, -1 shifted, with the corner entries). The demo’s eigenvalue bars show 0, 1, 3, 4 for k = 0, \dots, 3 (each of 1 and 3 belongs to two waves). With \tau = 0.2 (explicit) the factors are 1, 0.8, 0.4, 0.2. With \beta = 1 the diagonal becomes 2 + 6 = 8, the neighbours -1 - 4 = -5, the second neighbours (two places from the diagonal, including the corners) 1; \lambda_\text{max} = 20 and \tau\lambda_\text{max} = 4: unstable.
S2. The high modes go first (factors 0.71 for k = 4 down to 0.56 for k = 8): after 10 steps the wiggles are gone and a smooth, slightly smaller circle is left. Mode 1 has factor 0.970: half the radius after \ln 2/(-\ln 0.970) \approx 23 steps.
S3. \beta = 0.2: mode 1 has factor 0.995 (half-life 150 steps), mode 8 factor 0.24. Against \alpha = 0.2: 0.970 and 0.56. The \beta-snake keeps its size about six times longer and removes wiggles faster: \beta’s cost grows like k^4, \alpha’s like k^2.
S4. At the limit: \tau\lambda_\text{max} = 1.95, factor of mode 8 is -0.95: the zig-zag flips sign every step and fades slowly. Just beyond: 2.1, factor -1.1: the zig-zag grows by 10 % per step, flipping sign, and after some tens of steps the contour leaves the view and explodes. Semi-implicit with the same \tau = 2.1: mode 8 has factor 1/(1 + 2.1) = 0.32, stable.
S5. All factors except mode 0 are small (mode 1: 0.34, mode 8: 0.02): one step removes the noise and shrinks the circle to a third of its size; a few steps collapse it. With an image, such a step trusts the image force read at the old position for a very long move: the snake can jump over edges. \tau (or \gamma) still sets how far the snake may move per step, it just cannot make it explode.
S6. After mode 1 (the circle itself, size 1.10) the largest grey bars are at modes 4 (0.28) and 6 (0.13): the 5 points ride on the once-around circle, which puts them at 5 - 1 and 5 + 1 waves per turn in the x and y coordinates. Under the internal forces these die within some tens of steps (mode 4: \lambda_4 = 0.4\sin^2(4\pi/32) = 0.059, factor 0.945, half-life about 12 steps; mode 6: factor 0.89), long before mode 1 (\lambda_1 = 0.0038, factor 0.996, half-life about 180 steps): first a smooth roundish shape, then a slowly shrinking circle.
Explore: balloon, GVF and the matrix
The snake demo of the previous unit, now with GVF next to the plain edge force, a balloon force \kappa, and the matrix A (explicit) or A + \gamma I (semi-implicit) on the right, with the wrap-around entries framed in orange. Tick field to see the force field the snake uses.
G1. Preset concavity: cannot enter the U, tick field, play. Then preset U: GVF enters the concavity. Compare the two fields inside the slot and the two results. Set resample every to off in the GVF preset and reset: what changes, and why?
G2. Preset balloon from inside (\kappa = 0.3). Play. Then try \kappa = 0.1, 0.6 and 1. Where does each one end?
G3. Preset balloon leaks through the weak edge (\kappa = 0.6). Where does it leak? Lower \kappa until it stops at the edge everywhere. Is there a \kappa that both reaches the edge on the strong side and stops on the weak side?
G4. Preset far start: GVF captures it. Compare with edge force (same start, same \alpha = 0.01). Use field to explain.
G5. Set n = 8 and look at the matrix panel for the explicit and the semi-implicit update (\alpha = 0.1, \beta = 0.05, \tau = 1). Which entries change between the two? Then raise \beta to 1: how does the band change?
G6. Preset two blobs with GVF, and with a balloon from inside one blob. Can any of the new forces separate the two blobs with one snake?
G1. The edge force inside the slot points sideways to the walls; with it the snake closes over the mouth (deepest point in the slot y = 15.6 after 800 iterations). The GVF field points down into the slot as well; the GVF snake reaches the bottom of the slot (y = 77.5) after about 800 iterations (40.7 after 100, 53.4 after 400). Without resampling it stops at y = 38: the beads that enter the slot are pulled far apart, and the few beads there cannot follow the long walls; resampling keeps enough beads along the curve.
G2. \kappa = 0.3: it inflates to radius 30.3 and stops on the edge. \kappa = 0.1: 30.0, \kappa = 0.6: 31.1, pushed slightly outward against the edge force. \kappa = 1: it breaks through and keeps growing (radius 256 after 400 iterations).
G3. It leaks through the right-hand side, where the disk fades into the background, and grows on (beads beyond x = 200 after 400 iterations). \kappa = 0.1 stops on the edge everywhere (mean radius 29.8). At \kappa = 0.2 it already bulges out on the weak side (beads up to x = 104); at 0.3 it leaks. No single \kappa fits both sides well: the balloon is the same everywhere, the edge force is not. A weak edge needs a weak balloon, or knowledge of the shape.
G4. With the edge force the snake barely moves (radius 56.4 after 100 iterations): no force reaches it. With GVF it is pulled in at once (radius 39.5 after 50 iterations, 29.85 after 100). The field shows arrows everywhere around the disk pointing towards it: the edge force diffused into the flat background.
G5. The semi-implicit matrix adds \gamma = 1/\tau = 1 to the diagonal (0.5 + 1 = 1.5; off-diagonals -0.3 and 0.05, the same in both); the corner entries are the wrap-around of the closed curve. With \beta = 1 the diagonal becomes 6.2 (explicit) or 7.2, the first off-diagonals -4.1 and the second 1: the band is dominated by \beta, and the explicit step would need \tau < 2/16.4 = 0.12.
G6. No. GVF lets the snake follow the gap between the blobs more deeply, and a balloon in one blob finds that blob only, but one snake is always one closed curve: it either bridges the two blobs or covers one of them. Two objects need two snakes (or a representation that can split: level sets).
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 snakes/src/snake_matrix/exercise.rs.
C1. snake_matrix(n, alpha, beta): the n \times n matrix A, row by row:
A = n × n zeros
for every row i:
for (d, weight) in (−2, β), (−1, −α−4β), (0, 2α+6β), (1, −α−4β), (2, β):
A[i][(i + d) mod n] += weight
The checks are B1: the matrix for n = 6, rows summing to 0, and the alternating eigenvector.
C2. explicit_step(a, x, f, tau): one coordinate of all beads, \mathbf x_\text{new} = \mathbf x - \tau(A\mathbf x - \mathbf f), with \mathbf f the image force on every bead. The check applies it to the waves of B3 and compares the factors per step.
C3. semi_implicit_inverse(a, tau): the matrix (A + \gamma I)^{-1}, \gamma = 1/\tau, computed once:
M = A with γ added to every diagonal entry
for every column j:
e = (0, …, 0, 1, 0, …, 0) # 1 at position j
column j of the inverse = the solution c of M c = e
C4. semi_implicit_step(inv, x, f, tau): \mathbf x_\text{new} = (A + \gamma I)^{-1}(\gamma\mathbf x + \mathbf f), a matrix times a vector. The checks are B4: the factors 0.5, 0.25, 0.2, and the collapse to the mean for a huge \tau.
C5. gvf(gx, gy, mu, dt, iterations): gradient vector flow, both components:
v = g; m = |g|² at every pixel
repeat iterations times:
for every pixel p:
lap = (sum of the 4 neighbours of v) − 4 v(p) # outside: copy the edge
new(p) = v(p) + Δt · (μ · lap − m(p) · (v(p) − g(p)))
v = new
The check is B6, after one and after two updates.
Then cargo run -p snakes -- snake-matrix and open the pictures in out/snake-matrix/. The program moves snakes with your matrix and steps: first a circle of radius 40 without any image, then unit 1’s disk with \tau = 2, then a far start and a U shape with the edge force (left) and with GVF (right). It scales the GVF arrows to length 1 before using them as the image force.
C6. The circle without an image (n = 40, \alpha = 0.1, \beta = 0.05, semi-implicit \tau = 1) runs for 278 steps. Predict its radius from B5, then compare with the printed value. Then compare the explicit and the semi-implicit step with \tau = 2 on the disk.
C7. Look at far-start.png and u-shape.png (white: start, yellow: after 100 or 800 steps; green: the force field). Where does each snake end, and why? Why does the program scale the GVF arrows to length 1?
The model solution is snakes/src/snake_matrix/solution.rs in the download.
C6. B5: mode 1 is multiplied by 0.99751 per step, so the radius halves in about 278 steps. The program prints radius 20.02, from 40: half, as predicted (the circle stays a circle, it is mode 1 alone). With \tau = 2 the explicit step explodes after 54 steps; the semi-implicit step ends at mean radius 29.73, the same as the explicit step with \tau = 1 in unit 1 (29.74).
C7. Far start: with the edge force the snake has hardly moved after 100 steps (mean radius 56.41): the arrows are zero except in a thin ring around the disk, and the springs at \alpha = 0.01 are weak. With GVF every arrow points towards the disk, and the snake reaches it (mean radius 30.30), a little lumpy because the scaled force is equally strong everywhere. U shape: with the edge force the snake bridges the slot (its deepest point in the slot is at y = 16.7; the slot goes down to y = 77.5), because inside the slot the edge force points sideways and is zero in the middle. With GVF the arrows in the slot point down into it, and the snake reaches the bottom (y = 77.9). GVF is a diffusion, so far from the edges the arrows are very short: they point the right way but are too weak to move the snake in a reasonable number of steps. Without the scaling the far snake only gets to about radius 49 in 100 steps.
Where this leads
The snake knows only “smooth”: a missing piece of edge is bridged by a straight line, and an outline in clutter can wander off. When the object class is known (hands, leaves, vertebrae, nuclei) we can learn from examples which shapes are plausible: the next unit builds such a shape model, and the one after uses it to search the image.