Exercise: active contours (snakes)

Goal

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

  • compute the internal force on a bead of a snake by hand, and one step of the update,
  • say where the image force points and how far it reaches,
  • predict what changing \alpha, \beta, \sigma and \tau does to the contour,
  • (math) derive the force from the discrete energy, and the Euler–Lagrange equation for the elastic term.

Do the pen-and-paper part first, then the demo. Questions marked (math) are for those who want the derivations; the concept questions do not depend on them.

Background

Idea What it means
Snake a closed polygon \mathbf x_0, \dots, \mathbf x_{n-1}; after \mathbf x_{n-1} comes \mathbf x_0
Elastic force (weight \alpha) \alpha(\mathbf x_{i-1} - 2\mathbf x_i + \mathbf x_{i+1}): towards the midpoint of the two neighbours
Rigid force (weight \beta) -\beta(\mathbf x_{i-2} - 4\mathbf x_{i-1} + 6\mathbf x_i - 4\mathbf x_{i+1} + \mathbf x_{i+2}): straightens the chain
Edge map f = \lvert\nabla(G_\sigma * I)\rvert^2: large on edges
Image force w\,\nabla f: uphill on the edge map, towards the nearest edge
One step new position = position + \tau\,\times (elastic + rigid + image force)

By hand

B1. Four beads at (1, 1), (-1, 1), (-1, -1), (1, -1) (in this order), no image, \alpha = 1, \beta = 0. (a) Compute the elastic force on each bead. Where does it point? (b) Take one step with \tau = 0.1. Where are the beads now? Is it still a square? (c) The elastic energy is \tfrac12\alpha\sum_i|\mathbf x_{i+1} - \mathbf x_i|^2. Compute it before and after the step. (d) What happens after many steps?

B2. Same square, now with \beta = 1. (a) For the corner (1, 1), which bead is \mathbf x_{i-2} and which is \mathbf x_{i+2}? Compute the rigid force there. (b) With \alpha = \beta = 1: total force and the position after one step with \tau = 0.1.

B3. A regular octagon: 8 beads on the unit circle, at angles 0°, 45°, \dots, 315°; \alpha = 1, \beta = 0. (a) Compute the elastic force on the bead at (1, 0). (Its neighbours are at (\cos 45°, \pm\sin 45°).) (b) After one step with \tau = 0.1, what is the radius of the octagon? Compare with the square of B1. (c) With more and more beads on the same circle, does the elastic force per bead grow or shrink? What does that mean for a snake with many points?

B4. The edge map along a line across an edge at x = 10 is f(x) = e^{-(x - 10)^2/8}. (a) Compute the slope f'(x) at x = 8, 9, 10, 11, 14 and 20. In which direction does the image force w f'(x) push a bead at each position? (b) A bead starts at x = 20. What happens to it if there are no internal forces? (c) How would you make the image force reach further? What is the price?

B5. Force balance. A snake of n = 40 beads lies on a circle of radius r around a bright disk. (a) The beads of a regular polygon satisfy \mathbf x_{i-1} + \mathbf x_{i+1} = 2\cos(2\pi/n)\,\mathbf x_i (centre at the origin). Show that the elastic force has size \alpha r (2 - 2\cos(2\pi/n)) and points to the centre. Compute it for r = 28.5. (b) In the demo’s disk image (\sigma = 2, w = 2) the edge can push a bead outwards with at most about 0.67 (at radius 28.5). Above which \alpha can the edge no longer hold the snake?

B6. Predict, in one sentence each, what the snake on a noisy disk does when (a) \alpha is ten times too large, (b) \beta is very large and the object is a square, (c) \sigma is very small, (d) the start circle lies far outside the disk and \alpha is tiny, (e) the step \tau is too large.

B1. (a) Bead (1, 1): neighbours (-1, 1) and (1, -1), force (-1, 1) + (1, -1) - 2(1, 1) = (-2, -2). By symmetry every bead gets -2 times its own position: (2, -2) at (-1, 1), (2, 2) at (-1, -1), (-2, 2) at (1, -1). All point to the centre (the midpoint of each bead’s neighbours is (0, 0)). (b) (1, 1) + 0.1(-2, -2) = (0.8, 0.8), and likewise: the square (\pm0.8, \pm0.8). Still a square, 0.8 times the size. (c) Each side has length 2: \tfrac12 \cdot 4 \cdot 2^2 = 8. After the step the sides are 1.6: \tfrac12 \cdot 4 \cdot 1.6^2 = 5.12. (d) It shrinks by 0.8 every step, towards its centre: springs alone contract the snake to a point.

B2. (a) For bead i at (1, 1) with neighbours \mathbf x_{i-1} = (1, -1) and \mathbf x_{i+1} = (-1, 1), both \mathbf x_{i-2} and \mathbf x_{i+2} are the opposite corner (-1, -1) (with 4 beads, two steps back is two steps forward). Rigid force: -\big[(-1,-1) - 4(1,-1) + 6(1,1) - 4(-1,1) + (-1,-1)\big] = -(4, 4) = (-4, -4). (b) (-2, -2) + (-4, -4) = (-6, -6); after one step (1, 1) + 0.1(-6, -6) = (0.4, 0.4). On a square the straightening force also points inwards: a 4-bead “square” is as bent as a closed polygon can be.

B3. (a) (\cos 45°, \sin 45°) + (\cos 45°, -\sin 45°) - 2(1, 0) = (2\cos 45° - 2, 0) = (-0.586, 0): size 0.586, towards the centre. (b) Radius 1 - 0.1 \cdot 0.586 = 0.941, against 0.8 for the 4-bead square (whose corners are at radius \sqrt2, but the factor is what counts: 1 - 0.1\cdot 2 = 0.8). (c) It shrinks: the force is (2 - 2\cos(2\pi/n))\,r \approx (2\pi/n)^2 r, so doubling n makes it four times weaker. A snake with many points shrinks slowly in flat regions, and \alpha must be read together with n.

B4. (a) f'(x) = -\tfrac{x - 10}{4}e^{-(x-10)^2/8}: f'(8) = 0.303, f'(9) = 0.221, f'(10) = 0, f'(11) = -0.221, f'(14) = -0.135, f'(20) = -0.0000093. Left of the edge the force pushes right, right of it left: always towards the edge, zero on it. (b) Practically nothing: the force at x = 20 is 10^{-5} times the force at x = 8. The bead is outside the capture range and stays where it is. (c) Smooth more (larger \sigma): the edge map becomes wider and the pull reaches further. The price: neighbouring edges merge, corners round off, and the ridge of f can move away from the true edge.

B5. (a) \alpha(\mathbf x_{i-1} + \mathbf x_{i+1} - 2\mathbf x_i) = \alpha(2\cos(2\pi/n) - 2)\mathbf x_i: a negative multiple of \mathbf x_i, so towards the centre, with size \alpha r(2 - 2\cos 9°) = 0.0246\,\alpha r. For r = 28.5: 0.702\,\alpha. (b) The edge holds while 0.702\,\alpha < 0.67, i.e. up to \alpha \approx 0.95. Above that the springs pull the snake through the edge and it shrinks to a point.

B6. (a) It shrinks off the edge towards a point. (b) It cuts the corners: a rounded square inside the true one. (c) It stops on the first speckles of noise it meets: a ragged outline away from the edge. (d) It hardly moves: no image force reaches it, and the springs are too weak to bring it in. (e) The beads overshoot, a zig-zag grows, and the snake explodes.

Math questions

B7. (math) For the discrete energy E_\text{int} = \sum_j \tfrac12\alpha|\mathbf x_{j+1} - \mathbf x_j|^2 + \tfrac12\beta|\mathbf x_{j-1} - 2\mathbf x_j + \mathbf x_{j+1}|^2, compute \partial E_\text{int}/\partial\mathbf x_i and show that minus it is the elastic plus rigid force of the table above.

B8. (math) Show that the internal forces on all beads add up to zero, and explain why that had to be so. Show that [1, -4, 6, -4, 1] is the convolution of [1, -2, 1] with itself.

B9. (math) Continuous snake \mathbf x(s), s \in [0, 2\pi), closed. (a) Show by integration by parts that the first variation of \int\tfrac12\alpha|\mathbf x'|^2 ds in the direction \mathbf h is -\int\alpha\,\mathbf x''\cdot\mathbf h\,ds. (b) For the circle \mathbf x(s) = r(\cos s, \sin s), compute the internal force \alpha\mathbf x'' - \beta\mathbf x''''. In which direction does it point, and how large is it? Compare with B3 and B5.

B10. (math) For a one-dimensional quadratic energy E(x) = \tfrac12\lambda x^2 (\lambda > 0), write the gradient-descent step x_{t+1} = x_t - \tau E'(x_t). For which \tau does x_t go to 0? What happens for \tau\lambda slightly above 2?

B7. \mathbf x_i appears in the elastic terms j = i - 1 and j = i: \partial/\partial\mathbf x_i gives \alpha(\mathbf x_i - \mathbf x_{i-1}) - \alpha(\mathbf x_{i+1} - \mathbf x_i) = -\alpha(\mathbf x_{i-1} - 2\mathbf x_i + \mathbf x_{i+1}). Write \mathbf d_j = \mathbf x_{j-1} - 2\mathbf x_j + \mathbf x_{j+1}; \mathbf x_i appears in \mathbf d_{i-1} (coefficient 1), \mathbf d_i (-2) and \mathbf d_{i+1} (1), so the derivative of \tfrac12\beta\sum|\mathbf d_j|^2 is \beta(\mathbf d_{i-1} - 2\mathbf d_i + \mathbf d_{i+1}) = \beta(\mathbf x_{i-2} - 4\mathbf x_{i-1} + 6\mathbf x_i - 4\mathbf x_{i+1} + \mathbf x_{i+2}). Minus these are the two forces.

B8. Summed over i (indices mod n), each \mathbf x_j appears with total coefficient 1 - 2 + 1 = 0 in the elastic sum and 1 - 4 + 6 - 4 + 1 = 0 in the rigid one. It had to be so: the internal energy depends only on differences of positions, so translating the whole snake by \mathbf c leaves it unchanged, and the derivative in that direction, \sum_i \partial E/\partial\mathbf x_i\cdot\mathbf c, is zero for every \mathbf c. Convolution: [1, -2, 1] * [1, -2, 1] = [1, -2-2, 1+4+1, -2-2, 1] = [1, -4, 6, -4, 1].

B9. (a) \frac{d}{d\varepsilon}\int\tfrac12\alpha|\mathbf x' + \varepsilon\mathbf h'|^2 = \int\alpha\,\mathbf x'\cdot\mathbf h' at \varepsilon = 0; integrating by parts, = [\alpha\,\mathbf x'\cdot\mathbf h]_0^{2\pi} - \int\alpha\,\mathbf x''\cdot\mathbf h, and the bracket vanishes because \mathbf x and \mathbf h are periodic. (b) \mathbf x'' = -r(\cos s, \sin s) = -\mathbf x and \mathbf x'''' = \mathbf x, so the internal force is -\alpha\mathbf x - \beta\mathbf x = -(\alpha + \beta)\mathbf x: towards the centre, size (\alpha + \beta)r. With n beads the parameter step is 2\pi/n instead of 1, which gives the factor (2\pi/n)^2 of B3: 2 - 2\cos(2\pi/n) \approx (2\pi/n)^2.

B10. x_{t+1} = x_t - \tau\lambda x_t = (1 - \tau\lambda)x_t, so x_t = (1 - \tau\lambda)^t x_0. It goes to 0 when |1 - \tau\lambda| < 1, i.e. 0 < \tau < 2/\lambda. For \tau\lambda slightly above 2 the factor is slightly below -1: x changes sign every step and grows, an oscillation that explodes. The snake’s zig-zag is this, for the stiffest pattern of the polygon (next unit).

Explore

The demo shows a 128 \times 128 image with a snake (yellow, orange beads). Drag on the image to place a new start circle (or choose drag: draw and draw a closed curve). Play, step and +10 move the snake; reset goes back to the start. Blue arrows: the internal force on each bead, red: the image force (both \times 10). field shows the image force on a grid; edge map shows f instead of the image. The plot gives the internal, image and total energy per iteration; the readout gives \lambda_\text{max} = 4\alpha + 16\beta and, for the explicit step, \tau\lambda_\text{max}. n points changes the number of beads, resample every re-spaces them evenly. Leave the update on semi-implicit unless a question says otherwise (the explicit step is plain gradient descent; the next unit explains the difference).

E1. Preset fits the disk. Play for about 300 iterations. How do the internal and the image energy change, and when? Why does the internal energy not fall to zero? Look at the arrows at the end: what balances what?

E2. Preset α too large: shrinks away (\alpha = 1). Lower \alpha with the slider (press reset after each change) and find, roughly, the largest \alpha at which the snake stays on the edge. Compare with B5.

E3. Preset β too large: rounds the square (\beta = 2). Describe the result. Then set \beta = 0, reset and play. What changes at the corners? Why does \beta affect the corners and hardly the straight sides?

E4. Preset σ too small: stuck on noise (noise 0.25, \sigma = 0.5). Switch to the edge map view: what does the snake see? Raise \sigma to 1, 1.5, 2 and 4 (reset each time). From which \sigma does the snake find the edge? What happens to the result at \sigma = 4?

E5. Preset too far: does not move (\alpha = 0.01). Tick field: why does the snake hardly move? Now set \alpha = 0.1 and reset: what happens, and why? Would that help if the start circle were inside the disk, or beside it?

E6. Preset τ too large: explodes (explicit update, \tau = 2). Step through the first 40 iterations: what pattern grows? Find the largest \tau for which the explicit snake still settles, and compare with the readout \tau\lambda_\text{max}. Then switch to semi-implicit with \tau = 2.

E7. Presets concavity: cannot enter the U and two blobs: one snake bridges them. Describe each result and explain it with the image force (tick field). Which of the two problems could a better image force fix, and which not?

E8. Preset micrograph: nucleus. Where does the snake follow the nuclear envelope, and where not? Try \sigma = 1, and draw your own start curve close to the envelope.

E1. The internal energy falls steadily from 101.0 while the circle shrinks (78.7 at iteration 50, 60.6 at 100); the image energy stays near 0 until the snake reaches the edge region, then drops quickly, between iterations 100 (−0.8) and 200 (−70.9). At the end the snake sits at radius 29.8 with internal energy 44.3 and image energy −70.9 (total −26.6). The internal energy cannot reach zero while the snake keeps its size: a circle of radius 30 has stretched springs. At the end the blue arrows (inward, elastic) and the red ones (image force, outward on the inner flank of the edge ridge) cancel at every bead.

E2. On the demo’s image the snake holds up to about \alpha = 0.80 and shrinks away from \alpha = 0.85 (after 500 iterations: radius 28.5 at 0.80, 7.5 at 0.85, and 0.2 at 1). B5 predicted 0.95 for a clean edge; the noise weakens the image force at some beads (along one ray of the noisy image the largest outward force is only 0.56, which gives 0.80), and the snake gives way at its weakest bead.

E3. With \beta = 2 the corners are cut off: the snake is a rounded square whose corner lies about 10.4 pixels from the true corner, and it sits up to 9 pixels inside the square near the corners. With \beta = 0 (only \alpha = 0.1) it follows the square much more closely; the corners are still slightly rounded (5.8 pixels from the true corner) because the edge map itself is blurred there (\sigma = 2). The rigid force is proportional to the change of the second difference: zero on a straight side, large where the direction changes, so only the corners pay.

E4. In the edge map at \sigma = 0.5 the noise makes bright speckles everywhere: the snake stops on the first ones (radius between 37 and 44 after 500 iterations). At \sigma = 1 it gets through most of the speckles but is still caught in places (radius 28.6 to 36). From \sigma = 1.5 it finds the edge (mean radius 29.9). At \sigma = 4 it is smooth but slightly too small (mean radius 29.6): strong blurring moves the ridge of the edge map of a curved edge inwards.

E5. All beads are more than 20 pixels from the edge, where the image force is practically zero (the field shows dots, not arrows), and the springs at \alpha = 0.01 shrink the circle very slowly: radius 56.4 after 100 iterations, 53.4 after 300. With \alpha = 0.1 the springs bring the snake in (radius 45.2 after 100 iterations) until the edge catches it: radius 29.8 after 300. This only works because the start encloses the object, so shrinking happens to move towards it. A circle inside the disk would shrink away from the edge, and one beside the disk would shrink to a point next to it.

E6. A zig-zag: alternate beads move in and out, more every step (radius between 40.5 and 40.9 at iteration 20, between 10.9 and 137 at iteration 40), and at iteration 55 the snake has exploded. \lambda_\text{max} = 4 \cdot 0.1 + 16 \cdot 0.05 = 1.2: the explicit step is stable for \tau\lambda_\text{max} < 2, i.e. \tau < 1.67. In the demo \tau = 1.65 (\tau\lambda_\text{max} = 1.98) does not explode, but the beads keep wobbling (after 400 iterations they still lie between radius 22.9 and 31.6); \tau = 1.7 (2.04) explodes after 284 iterations. The semi-implicit update with \tau = 2 settles at radius 29.8 like \tau = 1.

E7. The U: the snake closes over the mouth of the slot and never enters it (after 800 iterations its deepest point in the slot is at y = 15.6, the slot goes down to y = 77.5). The field shows why: inside the slot the image force points sideways, to the two walls, and nowhere down into it; a bead at the mouth sees no reason to go in, and the springs pull it straight. Two blobs: one snake wraps both blobs and bridges the gap between them. A better image force (gradient vector flow, next unit) fixes the concavity. The two blobs it cannot fix: one snake is one closed curve, and it cannot split into two.

E8. The snake runs along the dark envelope on the right and the top, but cuts across at the lower left and the left, where the cytoplasm next to the nucleus is just as dark and the envelope gives a weaker edge. With \sigma = 1 the texture of the cytoplasm catches it (from the same start it ends far outside, from x = 33 to 119). A start drawn close to the envelope does much better: the snake refines a good guess, it does not find the object on its own.

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/snakes/exercise.rs.

C1. internal_force(points, i, alpha, beta): the elastic plus rigid force on bead i of a closed snake, with the indices taken around the curve:

n = number of beads
for c in x, y:
    a, b, p, q, r = coordinate c of beads i−2, i−1, i, i+1, i+2   (indices mod n)
    force[c] = α (b − 2p + q) − β (a − 4b + 6p − 4q + r)

The checks are your answers to B1(a), B2(a) and B3(a).

C2. edge_map(img, sigma): blur the image with a Gaussian of width \sigma (the blur is given), then at every pixel f = g_x^2 + g_y^2 with central differences g_x = \tfrac12(I(x+1, y) - I(x-1, y)), and divide by the largest value of f, so that f runs from 0 to 1 whatever the contrast of the image.

C3. snake_step(points, f, alpha, beta, w, tau): one explicit step of the whole snake:

for every bead i at (x, y):
    fx = (f(x+1, y) − f(x−1, y)) / 2          # f read between pixels: bilinear
    fy = (f(x, y+1) − f(x, y−1)) / 2
    new[i] = old[i] + τ · (internal_force(old, i) + w · (fx, fy))

All forces are computed from the old positions. The checks are B1(b), B2(b) and B4: a bead at x = 8 moves about 0.3 towards the edge at x = 10, one at x = 20 does not move.

Then cargo run -p snakes -- snakes and open the pictures in out/snakes/. The program runs the snake of the demo’s disk preset (\alpha = 0.1, \beta = 0.05, \sigma = 2, w = 2, 40 beads, start radius 45) with \tau = 1 and with \tau = 2, once with \alpha = 1, and once on the nucleus of the micrograph.

C4. disk.png shows the start (dashed), the snake after 100 steps and after 300. Compare the printed mean radius after 100, 200 and 300 steps with the demo (question E1). Why does the snake end slightly inside the disk’s edge (radius 30), and not exactly on it?

C5. explode.png shows the \tau = 2 snake after 30 steps (blue) and 40 steps (red). What pattern grows, and after how many steps does the program report an explosion? Predict it from \tau\lambda_\text{max}, with \lambda_\text{max} = 4\alpha + 16\beta.

C6. The run with \alpha = 1 uses \tau = 0.3, not \tau = 1. Where does the snake end? Why would \tau = 1 go wrong here? Then look at nucleus.png: where does the snake follow the nuclear envelope, and where not?

The model solution is snakes/src/snakes/solution.rs in the download.

C4. Mean radius 34.98 after 100 steps, 29.74 after 200 and still 29.74 after 300 (the beads lie between 29.45 and 29.89): the circle shrinks slowly while no edge reaches it, then the edge catches it and it stays. The demo gives about the same numbers (34.9 after 100 steps, 29.78 at the end). The snake stops where the inward elastic force equals the outward image force. The image force is zero on the ridge of the edge map and grows only on its flanks, so the balance is reached a little inside the ridge, on the inner flank. Blurring a curved edge also moves the ridge itself slightly inwards.

C5. A zig-zag: alternate beads move in and out, more every step. After 20 steps the beads still lie between radius 40.60 and 40.84, after 30 between 35.49 and 42.06, after 40 between 26.7 and 150; after 47 steps the program stops because a bead is more than 1000 pixels away. \lambda_\text{max} = 4 \cdot 0.1 + 16 \cdot 0.05 = 1.2, so \tau\lambda_\text{max} = 2.4 > 2: the zig-zag mode is multiplied by 1 - 2.4 = -1.4 every step and grows (the next unit).

C6. The snake shrinks off the edge to a point: mean radius 1.63 after 500 steps. With \alpha = 1, \lambda_\text{max} = 4 + 0.8 = 4.8: the explicit step is stable only for \tau < 2/4.8 = 0.42, so \tau = 1 would explode instead of shrinking. On the micrograph the snake runs along the dark nuclear envelope at the top and on the right, but cuts straight across at the lower left, where the cytoplasm beside the nucleus is as dark as the envelope and the edge is weak.

Where this leads

The explicit step explodes when \tau is too large, and the image force reaches only a few pixels. The next unit writes the internal forces as a matrix, shows which patterns of the curve explode and why, introduces the semi-implicit step that never does, and extends the capture range with balloon forces and gradient vector flow.