Exercise: watershed as a minimum spanning forest

Goal

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

  • run Prim’s algorithm from markers by hand and read off the watershed (the cut edges),
  • compute minimax distances and predict which marker a pixel goes to,
  • predict where the graph cut, the random walker and the watershed put the boundary for the same seeds and weights, and explain the differences,
  • (math) prove that Prim from a virtual root gives a seeded minimum spanning forest, the minimax assignment, and that only the order of the weights matters.

Background

Idea What it means
Edge altitude d_{pq} = \max(f_p, f_q) for a landscape f, or a dissimilarity such as \lvert I_p - I_q\rvert
Prim from markers queue the edges leaving the labelled pixels; take the cheapest (ties: first in, first out); a new pixel gets the label of its labelled end; an edge between two different labels is a cut edge
Seeded MSF the cheapest forest in which every pixel hangs from exactly one marker; = Kruskal with a virtual root
Minimax distance \pi(p, m) = the lowest possible highest edge on a path from p to m
Watershed rule each pixel goes to the marker with the smallest \pi
Three ways graph cut: sum of cut affinities; random walker: sum of squares; watershed: maximum along a path

By hand

B1. A chain of 7 pixels a–g with markers A at a and B at g; edge weights (dissimilarities) a–b 2, b–c 5, c–d 1, d–e 3, e–f 6, f–g 2. (a) Run Prim from both markers: list the edges in the order they are popped, with “grow” or “cut”. (b) Which pixels belong to A? (c) Compute the minimax distance from d to A and to B.

B2. The same chain read as a random walker and as a graph cut with affinities w = 1/d (so the resistances are the weights d), object seed at a, background seed at g. (a) Where does the graph cut cut? (b) Compute the walker’s voltages at d and e. Where does it cross 0.5? (c) Which two of the three methods agree, and why do they?

B3. A 4 \times 4 landscape (rows top to bottom), markers A at the top-left and B at the bottom-right cell, 4-neighbours, edge altitude \max(f_p, f_q): \begin{bmatrix} 1 & 3 & 9 & 4 \\ 2 & 5 & 8 & 6 \\ 3 & 7 & 2 & 7 \\ 4 & 9 & 6 & 0 \end{bmatrix} (a) Before computing: the low cell 2 in the middle of row 3 lies between high values. Which marker do you expect it to join? (b) Run Prim (or compute minimax distances) and write the label of every cell. (c) At which altitudes are the cut edges?

B4. Fill in the table for the three seeded methods: what is minimised or computed, soft or hard labels, does it shrink, does it leak through a narrow gap, does it need seeds, what does it cost.

B5. Predict. (a) A thin bright filament (1 pixel wide, high rim) starts at an object seed and runs 50 pixels into the background. Which methods keep it? (b) A single tiny background seed sits in a large flat region next to a large object stroke. What does each method do? (c) Two markers lie on a perfectly flat plateau. What decides the watershed boundary?

B1. (a) The queue starts with a–b (2, from A) and f–g (2, from B). Pops: a–b 2 grow (b → A); f–g 2 grow (f → B); b–c 5 grow (c → A; the queue now holds b–c 5 and e–f 6, and 5 is lower); c–d 1 grow (d → A); d–e 3 grow (e → A); e–f 6: both ends labelled, A and B: cut. (b) a, b, c, d, e belong to A; f, g to B. (c) d to A: path d–c–b–a with edges 1, 5, 2: highest 5. d to B: d–e–f–g with 3, 6, 2: highest 6. 5 < 6: d goes to A, as Prim found.

B2. (a) The cheapest cut separates the seeds at the smallest affinity w = 1/6, the e–f edge: object = a–e, the same as the watershed. (b) Total resistance 2 + 5 + 1 + 3 + 6 + 2 = 19. d is at 1 - (2 + 5 + 1)/19 = 11/19 \approx 0.579, e at 8/19 \approx 0.421: the walker crosses 0.5 on the d–e edge (resistance 3), not on the weakest link. (c) The graph cut and the watershed agree: on a chain with one seed at each end, both pick the single weakest link (the cut pays only for that edge; the watershed’s minimax rule meets at the highest edge). The walker spreads the drop over all resistances and crosses 0.5 where half the total resistance is reached.

B3. (a) The 2’s neighbours are 8 (above), 7 (left), 7 (right) and 6 (below). From B the path 0 → 6 → 2 has edges of altitude 6 and 6: highest 6. Every path from A has to enter through the 8 or one of the 7s: highest at least 7. So it joins B. (b) Prim (FIFO) gives \begin{matrix} A & A & A & B \\ A & A & A & B \\ A & A & B & B \\ A & A & B & B \end{matrix} The minimax distances agree, except where there is a tie, which the order of the queue decides. The 4 in the top-right corner reaches B through the cells 6, 7, 0 (highest edge 7), but it also reaches A at 7, through row 3: 4, 6, 7, 2, 7, 3, 2, 1 (edges 6, 7, 7, 7, 7, 3, 2). A tie at 7, which Prim’s first-in-first-out order gives to B. The 9 in the bottom row is a tie too: every edge out of it has altitude 9. (c) The cut edges have altitudes 7, 8, 8, 9, 9.

B4.

graph cut random walker watershed
computes min. sum of cut weights (max-flow) harmonic function (linear system) min. spanning forest (sort + one pass)
labels hard soft (probabilities) hard
shrinks? yes (boundary length costs) mildly (seed position) no
leaks through a narrow gap? rarely (a short cut across the gap is cheap) partly (the boundary bulges) yes (one low pass suffices)
needs seeds? seeds or a data term seeds (or priors) markers (or all minima)
cost highest high (iterative solver) lowest

B5. (a) The watershed keeps it (the filament’s own pixels are reached over low edges from the seed; length plays no role). The random walker keeps it too if the rim is a strong barrier (its conductance to the background is tiny). A graph cut with seeds only cuts it off at its base when cutting there (about 1–3 edges) is cheaper than following its rim (100 weak edges): shrinking. (b) Graph cut: draws a tiny circle around the background seed (cheap boundary) and gives everything else to the object. Walker: the boundary lies where half the resistance between the seeds is, closer to the small seed but not at it. Watershed: decided by noise passes in the flat region; the result is unpredictable. (c) Only the queue order (first in, first out): both floods advance one ring of pixels per round, so the boundary falls in the middle (with ties resolved towards the marker whose edges were queued first).

Math questions

B6. (math) Show that Prim’s algorithm started at a virtual root r, joined to all markers by edges of weight -\infty, produces after deleting r a spanning forest rooted at the markers of minimum total weight.

B7. (math) Prove the minimax assignment: in a seeded MSF, every pixel p lies in the tree of a marker m with \pi(p, m) = \min_{m'}\pi(p, m') (if the minimum is unique).

B8. (math) (a) Show that any strictly increasing transformation g of the weights (g(d) = d^2 for d \ge 0, d + c, …) leaves the seeded MSF unchanged. (b) Find a small graph and seeds where adding the same constant c > 0 to every affinity changes the minimum graph cut.

B6. Prim from r builds a minimum spanning tree T of the extended graph. The root edges have weight -\infty, strictly less than all others, so they are the first K edges taken (and every MST contains them, by the cut property applied to the split \{m\} vs the rest). After that, Prim takes the cheapest edge leaving the current tree, which is exactly flooding from all markers. Deleting r removes the K root edges and leaves K trees, one containing each marker. Conversely, any spanning forest F rooted at the markers plus the K root edges is a spanning tree of the extended graph, with weight w(F) + K\cdot(-\infty); minimising over trees therefore minimises w(F). So the forest is a minimum seeded spanning forest.

B7. In the extended graph, every path from p to r ends with a root edge (m, r); its highest edge is the highest edge of the part from p to m (the root edge is -\infty). So the minimax distance from p to r is \min_m \pi(p, m). The tree path from p to r in the MST is a minimax path (minimax property of MSTs), and it enters r through the marker of p’s tree. Hence that marker achieves \min_m \pi(p, m); if the minimum is unique, it is that marker.

B8. (a) Prim (and Kruskal) only compare weights: “is this edge cheaper than that one?” A strictly increasing g preserves every comparison, so every step makes the same choice and the forest is the same. (The FIFO tie rule is also preserved, since ties stay ties.) (b) A free node x joined to an object seed by affinity 3 and to two background seeds by affinities 1 and 1. Cuts: “x background” costs 3, “x object” costs 1 + 1 = 2: x is object. Add c = 2 to every affinity: 5 against 3 + 3 = 6: now x is background. The cut with more edges gains more from the constant. (The watershed on the same graph, as a maximum spanning forest of the affinities, joins x to its strongest link, the object, for every c.)

Explore: Prim from markers

The grid of B3 with edge altitudes \max(f_p, f_q). Step through Prim’s algorithm: the list on the right is the queue (edges leaving the labelled cells, cheapest first). Click cells (mode click: markers) to add or remove markers.

P1. Preset Prim from two markers: step to the end and check B3 (labels and cut edges). How many steps are there, and how many are cuts?

P2. Add a third marker on the middle cell 2 (row 3, column 3). Which cells does it take?

P3. Switch the edge weights to \lvert f_p - f_q\rvert (two markers again: press reset). What happens, and why is this a bad choice of edge weight for a landscape?

P4. Preset a plateau: ties: two markers at the ends of the middle row, a plateau of 5s between them. Where is the boundary? What decides it?

P1. 24 steps (one per edge of the grid); 5 of them are cuts, at altitudes 7, 8, 8, 9, 9. The labels are those of B3: A owns the left two columns, the top two rows up to the 9, and the cell 9 in the bottom row; B the bottom-right block and the right column.

P2. The labels become A A A C / A A C C / A C C C / A A C B: the third marker C takes the middle 2 and almost all of B’s former region (the 7s, 8, 6s and the top-right 4); B keeps only its own cell, because every neighbour of B is reached from C over passes no higher than from B, and C’s edges are queued first.

P3. Everything except B’s own cell goes to A (labels 1111 1111 1111 1112). With \lvert\Delta f\rvert the weight measures change, not height: water can flow over the high ridge cheaply as long as it rises in small steps. A landscape needs altitudes; differences belong to images where similar neighbours should group (as in the FH unit and the three-method comparison).

P4. Between columns 4 and 5: A gets columns 1–4, B columns 5–7. All plateau edges have altitude 5, so the queue order decides: both floods spread one ring per round, and A’s edges entered the queue first, so A also takes the middle column.

Explore: three methods on the same seeds

The same seeds and contrast weights w = \exp(-\Delta I^2/2\sigma^2) segmented three ways: the random walker in the large panel (paint seeds there), the graph cut with seeds only (no data term) and the seeded watershed (minimum spanning forest on |\Delta I|) on the right. The readout gives the object pixels of each method and their run times.

C1. Preset all three agree on a clean edge: compare the object pixel counts. Why do the methods agree here?

C2. Preset a gap in a wall, strong noise (noise 16). Compare the three boundaries at the gap and the pixel counts. Lower the noise to 8: what changes for the watershed?

C3. Preset no edge, a small seed. Which method cuts off the background seed? Paint a long background stroke down the right border: what happens to the graph cut?

C4. Preset two discs, a weak boundary. Do the three methods agree? Move the background seed in the lower disc close to the waist between the discs: which method follows?

C5. Compare the run times in the readout. Which is fastest, and does it match the timing slide?

C1. 3378 object pixels for all three. Every edge of the objects is very strong compared with the noise (contrast 120, σ = 20), and the object seed is enclosed by them: the cheapest cut, the walker’s 0.5 crossing and the minimax boundary all run along the same edges.

C2. Graph cut 8257 pixels: the boundary crosses the gap in a straight 3-pixel cut. Walker 8466: it bulges a little into the right half through the gap. Watershed 8443: a ragged bulge, because in the noisy flat field the highest pass on every path is set by noise. At noise 8 the counts are 8448 (walker), 8259 (cut), 8258 (watershed): with weaker noise the watershed closes the gap as well.

C3. The graph cut: it draws a small circle around the background seed (16 342 object pixels, almost the whole image), because a short boundary is cheap and the ramp offers no edge. The watershed is similar (16 222), the walker puts the boundary roughly halfway between the seeds in resistance (11 938). A long background stroke makes a short cut around it impossible: the graph cut’s boundary moves out into the ramp.

C4. Yes: 1899 (walker), 1908 (cut) and 1911 (watershed) object pixels; the weak boundary at the waist (20 grey levels) is still the cheapest place for all three, and the seeds are well placed. Moving the background seed close to the waist mainly changes the walker (seed position); the cut and the watershed stay at the waist, where the image has its weakest link.

C5. The watershed is the fastest (a few tens of ms in the browser), the graph cut next; the walker is solved iteratively over several frames (hundreds of CG iterations). The order matches the timing slide.

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 graphseg/src/ws_msf/exercise.rs. A graph is a number of nodes and a list of edges (a, b, d); markers are a list with 0 for a free node and the marker’s label (1, 2, …) otherwise. Given: incident_edges (the edges of every node) and EdgeQueue, a priority queue that pops the cheapest edge, first in, first out among equal weights.

C1. altitude_edges(f): the pixel graph of a landscape f, every pixel with an edge to the right and one down, at the altitude of the pass d_{pq} = \max(f_p, f_q).

C2. prim_from_markers(n, edges, markers): Meyer’s flooding as Prim’s algorithm from all markers at once. Returns the labels and the cut edges:

queue every edge from a marker to a free node        (marker nodes in index order)
while the queue is not empty:
    (a, b) = the cheapest edge (first in among equals)
    if both ends have labels:
        if the labels differ: it is a cut edge (watershed)
    else:
        give the free end the label of the other end
        queue its edges to nodes that are still free

The checks are B1, B3 with its cut altitudes 7, 8, 8, 9, 9 (P1), a third marker (P2) and the plateau of P4.

C3. kruskal_from_markers(n, edges, markers): the same forest by Kruskal with a virtual root. Each component carries the label of the marker in it (or none):

for each edge (a, b, d), sorted by d (equal weights in list order):
    A = find(a),  B = find(b)
    if A ≠ B and not both carry a label:
        join them; the new component carries the label of either

Two components that both carry a label are never joined: through the virtual root, the edge would close a cycle. The check compares with C2 on B1 and B3.

C4. minimax_distance(n, edges, source): the lowest possible highest edge on a path from source to every node: Dijkstra’s algorithm (from the live-wire unit) with \max in place of +:

dist = ∞ everywhere, dist[source] = 0;  queue (0, source)
while the queue is not empty:
    take the node p with the smallest dist (skip it if already done); mark p done
    for every edge (p, q, d):
        if max(dist[p], d) < dist[q]:  dist[q] = max(dist[p], d);  queue (dist[q], q)

The checks are B1(c) (5 to A, 6 to B), and on B3, that every pixel went to a marker it reaches over the lowest highest pass.

Then cargo run -p graphseg -- ws-msf and open the pictures in out/ws-msf/. The program floods a synthetic image of 18 nuclei from one marker per nucleus (a 3 \times 3 square at its centre) and one on the image border, first on the gradient landscape, then with |\Delta I| of the image itself as edge weights.

C5. Compare watershed.png with truth.png. How many nuclei are matched (overlap ≥ 0.5), and where are the differences? How long did Prim take for 65 536 pixels?

C6. Prim and Kruskal (C3) disagree at a few hundred pixels, although both build a minimum spanning forest. Why can two minimum spanning forests differ?

C7. Look at watershed-diff.png (weights |\Delta I| instead of altitudes). What went wrong, and why? Compare with demo question P3.

The model solution is graphseg/src/ws_msf/solution.rs in the download.

C5. 15 of 18 nuclei are matched. Every nucleus that has its own marker is outlined along the crest of its gradient ring, and touching nuclei are split between their markers. The differences are where nuclei overlap in the truth: a nucleus partly hidden under a neighbour is only a sliver there, and the split between the two follows the gradient instead. Prim took about 50 ms in our run (including building the 130 560 edges).

C6. Prim agreed with Kruskal at 64 998 of 65 536 pixels. A landscape has many edges of equal altitude (here between neighbouring pixels on a flat part of the gradient), and among equal weights there are several minimum spanning forests. Prim breaks ties by queue order (first in, first out), Kruskal by the order of the sorted edge list: different tie rules, different but equally cheap forests.

C7. On |\Delta I| only 13 of 18 nuclei are matched. Inside a nucleus and in the background the differences between neighbours are small (noise), and so are the steps across a blurred nucleus border: the highest step on a path out of a nucleus is not much higher than one inside. Some floods leak out into the background through a low step and grow ragged blobs there (the nucleus on the left). As in P3, differences measure change, not height: the watershed needs a landscape whose ridges are the boundaries.

Where this leads

Flood without markers and never stop: every time two basins meet, record the level. That record is a tree of all watershed segmentations: hierarchical segmentation.