Exercise: the flooding algorithm on a grid

Goal

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

  • run priority-queue flooding (Meyer’s algorithm) by hand: keep the queue as a list of (height, arrival number, pixel), pop, decide, push,
  • say where the watershed line goes with 4 and with 8 neighbours,
  • explain why ties on plateaus are broken first in, first out,
  • estimate the cost with a heap and with a bucket queue,
  • (math) show that the regions are connected and that the flooding is a shortest-path search with “highest point” as the path cost.

Do the pen-and-paper part first, then the demo.

Background

Step What happens
Start every unlabelled neighbour of a marker enters the queue with its height; markers in reading order, neighbours in reading order (up, left, right, down; with 8 neighbours: up-left, up, up-right, left, right, down-left, down, down-right)
Arrival number #0, #1, #2, … in the order pixels enter the queue
Pop the pixel with the smallest height; among equal heights the smallest arrival number (first in, first out)
Decide all labelled neighbours have the same label → that label; two different labels → watershed line
Push the unlabelled neighbours of the popped pixel that are not yet in the queue (a line pixel pushes nothing)
Water level the largest height popped so far

Pixels are written (row, column), both counted from 0 at the top left.

By hand

The 5 \times 5 grid, with marker A at (1, 1) and marker B at (4, 4), 4 neighbours, with a watershed line: f = \begin{bmatrix} 3&2&3&5&6 \\ 2&\mathbf{1}&2&4&5 \\ 3&2&4&3&2 \\ 5&4&3&2&1 \\ 6&5&3&1&\mathbf{0} \end{bmatrix}

B1. The queue. (a) Write the starting queue: every entry as (height, #arrival, pixel), in pop order. (b) Do the first eight pops. For each: the popped pixel, its labelled neighbours, the decision, and the pixels it pushes (with their arrival numbers). (c) Write the queue after the eighth pop. (d) Finish the flooding (you do not need to write every queue). Which pixels end on the watershed line? At which water level does the first line pixel appear?

B2. The same grid and markers with 8 neighbours. Without a full trace: which pixels must now be line pixels, and why does the line get thicker? (Then check with the demo.)

B3. A plateau in 1D: f = 0\,5\,5\,5\,5\,5\,0 (samples 0–6), markers A on sample 0 and B on sample 6, with a watershed line. (a) Trace the flooding with first in, first out among equal heights. Where is the line? (b) Trace it again with last in, first out among equal heights. Where is the line now? (c) Which result would you call correct, and why?

B4. A marker that is not a minimum: f = 5\,3\,1\,2\,4\,6\,4\,2\,0\,2 (samples 0–9), markers A on sample 0 (height 5) and B on sample 8 (height 0), with a watershed line. (a) How many regional minima does f have, and which one has no marker? (b) Trace the pops (pixel, height, water level, decision). What happens to the minimum at sample 2? (c) Write the result.

B5. Cost. A 1024 \times 1024 image with 8-bit heights. (a) Estimate the number of elementary steps for the flooding with a binary heap (\approx n \log_2 n) and with a bucket queue (\approx n + 256). How much faster is the bucket queue? (b) Would you use a bucket queue for a 16-bit image? For the gradient magnitude stored as floating-point numbers?

B6. Why must a line pixel not push its neighbours? Describe what would go wrong on the grid of B1 if (1, 3) pushed (0, 3) and (1, 4) after becoming a line pixel.

B1. (a) A (processed first, in reading order) queues its neighbours up, left, right, down: (0,1) #0, (1,0) #1, (1,2) #2, (2,1) #3, all height 2. B queues (3,4) #4 and (4,3) #5, height 1. In pop order: (1, #4, (3,4)), (1, #5, (4,3)), (2, #0, (0,1)), (2, #1, (1,0)), (2, #2, (1,2)), (2, #3, (2,1)). (b)

pop pixel height, # labelled neighbours → pushes
1 (3,4) 1, #4 B B (2,4) #6, (3,3) #7
2 (4,3) 1, #5 B B (4,2) #8
3 (0,1) 2, #0 A A (0,0) #9, (0,2) #10
4 (1,0) 2, #1 A A (2,0) #11
5 (1,2) 2, #2 A A (1,3) #12, (2,2) #13
6 (2,1) 2, #3 A A (3,1) #14
7 (2,4) 2, #6 B B (1,4) #15, (2,3) #16
8 (3,3) 2, #7 B B (3,2) #17
  1. In pop order: (3, #8, (4,2)), (3, #9, (0,0)), (3, #10, (0,2)), (3, #11, (2,0)), (3, #16, (2,3)), (3, #17, (3,2)), (4, #12, (1,3)), (4, #13, (2,2)), (4, #14, (3,1)), (5, #15, (1,4)).
  2. Pops 9–14 at level 3 label (4,2) B, (0,0) A, (0,2) A, (2,0) A, (2,3) B, (3,2) B. Pop 15, (1,3) at height 4: its neighbours (0,3) and (1,4) are not yet labelled, (1,2) is A and (2,3) is B: line. Then (2,2) and (3,1) (height 4) are lines too (A and B on both sides). Level 5: (1,4) → B, (4,1) → B, (0,3) → A, (3,0) → A. Level 6: (0,4) and (4,0) are lines. Result (| = line): \begin{matrix} A&A&A&A&| \\ A&A&A&|&B \\ A&A&|&B&B \\ A&|&B&B&B \\ |&B&B&B&B \end{matrix} Five line pixels on the anti-diagonal; the first appears at water level 4 (pop 15). 23 pops in total.

B2. With 8 neighbours, A and B pixels must not even touch diagonally. On the anti-diagonal line of B1, the A pixel (1,2) and the B pixel (2,3) are diagonal neighbours, so a one-pixel diagonal line no longer separates them: the line has to be 4-connected, a staircase. The flooding gives 7 line pixels: (1,3), (1,4), (2,2), (2,3), (3,1), (3,2), (4,1); the corners (0,4) and (4,0) become A. In general the regions and the line use complementary connectivities: 4-connected regions need only an 8-connected line, 8-connected regions need a 4-connected line.

B3. (a) Start: sample 1 #0 (A), sample 5 #1 (B). Pops: 1 → A (pushes 2 #2), 5 → B (pushes 4 #3), 2 → A (pushes 3 #4), 4 → B (3 already queued), 3: neighbours A and B → line. A\,A\,A\,|\,B\,B\,B: the line in the middle. (b) LIFO: 5 (#1) → B, pushes 4 #2; 4 → B, pushes 3 #3; 3: only B labelled → B, pushes 2 #4; 2 → B (its other neighbour, 1, is queued but unlabelled); 1 (#0): neighbours A and B → line. A\,|\,B\,B\,B\,B\,B. (c) FIFO: both lakes reach the plateau at the same level and should spread at the same speed, so the dam belongs in the middle. LIFO lets one lake run across first; where the line ends up depends only on the order of the queue.

B4. (a) Two: samples 2 (height 1) and 8 (height 0). The one at sample 2 has no marker. (b) Start: A queues sample 1 (3) #0; B queues 7 (2) #1 and 9 (2) #2. Pops: 7 (2, level 2) → B, pushes 6; 9 (2, level 2) → B; 1 (3, level 3) → A, pushes 2; 2 (height 1, level 3) → A: lower than the water level, popped at once: the minimum is drowned by A’s water; 3 (2, level 3) → A, pushes 4; 6 (4, level 4) → B, pushes 5; 4 (4, level 4) → A; 5 (6, level 6): neighbours A and B → line. (c) A\,A\,A\,A\,A\,|\,B\,B\,B\,B. A marker does not have to sit at a minimum: its water runs downhill into the nearest basin and claims it.

B5. (a) n = 2^{20} = 1\,048\,576, \log_2 n = 20: heap \approx 2.1 \cdot 10^7, bucket queue \approx 1.05 \cdot 10^6: about 20 times fewer steps. (b) 16-bit: 65 536 buckets is still small compared with the number of pixels, so yes. Floating-point heights: there is no small set of levels; use the heap, or quantise the heights to, say, 256 or 4096 levels first (which merges heights that differ less than one level and changes tie-breaking slightly).

B6. A line pixel has two different labels around it; if it pushed its neighbours, water would cross the dam. (0, 3) would be pushed by a pixel with no label: when it pops, its labelled neighbours might be only A, or (with the “first to reach it” rule) it would get no sensible label at all. The dam must stop the water; only labelled pixels spread.

Math questions

B7 (math). Show by induction over the pops that every region of the result is connected and contains exactly one marker (use 4 or 8 neighbours consistently).

B8 (math). A 1D plateau of k samples (positions 1, \ldots, k, all of the same height) lies between marker A (position 0) and marker B (position k + 1), both lower. Show that with FIFO the fronts advance one sample per round, alternately from the left and the right, and that the line pixel is at position \lfloor k/2 \rfloor + 1. Where is it for k = 5 and k = 4?

B9 (math). Let d(p) = \min_{\text{paths } \pi: \text{marker} \to p} \max_{q \in \pi,\ q \ne \text{marker}} f(q) (the minimax or bottleneck distance). Show that the water level never decreases and that d(p) equals the water level at the moment p is popped. Conclude that pixels are flooded in order of d.

B10 (math). Show that the binary heap version costs O(n \log n) and the bucket queue version O(n + L) for integer heights 0, \ldots, L - 1 (with 4 or 8 neighbours).

B7. Invariant after every pop: each label \ell occupies a connected set containing its marker and no other marker. At the start each label is its marker (assume each marker is connected; otherwise each connected piece is its own region). A pop either makes p a line pixel (nothing changes) or gives p a label \ell that a neighbour already carries: the set of \ell grows by a pixel adjacent to it, so it stays connected; p is not a marker (markers are never queued). Other labels are unchanged.

B8. Start: position 1 #0 (pushed by A), position k #1 (by B). Round j (j = 1, 2, \dots) pops position j (A side, pushing j + 1) and then position k + 1 - j (B side, pushing k - j), because entries are popped in arrival order and the arrivals alternate A, B, A, B. This continues while j < k + 1 - j. If k = 2m + 1: after m rounds positions 1..m are A and k - m + 1..k are B; the middle position m + 1 was pushed by A and pops next with neighbours A and B: line at m + 1 = \lfloor k/2 \rfloor + 1. If k = 2m: in round m, A labels position m (position m + 1 is already queued by B), then position m + 1 pops with neighbours m (A) and m + 2 (B): line at m + 1 = \lfloor k/2 \rfloor + 1. For k = 5: position 3 (the exact middle). For k = 4: position 3 (the right one of the two middle samples).

B9. Let \ell be the water level. A pixel q enters the queue when a labelled neighbour r pops; at that moment its best known path cost is \max(d(r), f(q)). If f(q) < \ell, its key is below the current level, so it pops before any pixel of height \ge \ell, while the level is still \ell; its level is \ell = d(r) = \max(d(r), f(q)) (by induction, d(r) = \ell for the pixel r that just popped). If f(q) \ge \ell, it pops when the level reaches f(q), so its level is f(q) = \max(d(r), f(q)). The level never decreases, because it is defined as a running maximum. Optimality: suppose p pops at level \ell but some path \pi from a marker has highest point < \ell. Take the first pixel q on \pi not yet popped; its predecessor on \pi is popped (or a marker), so q is in the queue with f(q) < \ell: it would have been popped before p. Contradiction. So d(p) = \ell, and since \ell never decreases, pixels are flooded in order of d, exactly as in Dijkstra’s algorithm with \max in place of +.

B10. Each pixel is pushed at most once (the “queued” flag) and popped at most once; each pop inspects at most 8 neighbours. Heap: push and pop cost O(\log(\text{queue size})) \le O(\log n), total O(n \log n). Bucket queue: push O(1); pop O(1) plus the pointer moves to the next non-empty bucket. The pointer only moves down when a pixel below it is pushed (at most once per push) and moves up at most L steps plus the total of the downward moves, so all pointer moves together are O(n + L). Total O(n + L).

Explore: step through the queue

Cells show their height (darker = higher). Click a cell to raise (upper half) or lower (lower half) it, or choose marker A–D / no marker and click to place or remove markers. step pops one pixel: it gets a red frame, its labelled neighbours a dashed blue frame, and the box above the options writes out the decision. The table is the queue in pop order (height, arrival number, cell); the next pixel to pop is red, the ones just pushed are highlighted; queued cells show their #arrival in the grid. Options: 8 neighbours, watershed line, LIFO ties. next level jumps to the next water level.

P1. Example 5 × 5 (exercise). Check your queue from B1(a), then step through pops 1–8 and compare with B1(b) and (c). Run to the end: how many pops and line pixels? Tick 8 neighbours and compare with B2.

P2. Example plateau between two markers. Run to the end. Where is the line, and how many line pixels? Tick LIFO ties and run again. Then untick watershed line: what happens to the line pixels?

P3. Example two basins. Use next level: how many water levels are there? How many line pixels at the end? Untick watershed line: which basin gets the former line pixels?

P4. Example a marker that is not a minimum. Step through the first six pops. Where does B’s water go, and at which water level does it reach the right-hand minimum? Compare the final result with two basins.

P5. Example every minimum is a marker. How many markers, pops and line pixels? Untick 8 neighbours and press all regional minima as markers: how many markers now, and why more?

P6. On the 5 × 5 grid, lower the height of (2, 2) from 4 to 1 (click its lower half three times). What changes, and why? (Then press reset.)

P1. The starting queue is the six entries of B1(a); pops 1–8 and the queue after pop 8 match the tables. 23 pops, 5 line pixels (the anti-diagonal). With 8 neighbours: 7 line pixels, as in B2.

P2. With FIFO the line is the middle column (column 4), 5 line pixels: the two fronts meet in the middle. With LIFO, B’s water snakes across the plateau first; A keeps only its marker, and 3 line pixels sit around it: (1,0), (2,1) and (3,0). Without the line, the middle column goes to whichever lake queued it first (A, with FIFO).

P3. 8 water levels (2 to 9). 8 line pixels, a staircase along the ridge: (0,5), rows 1–4 of column 4, rows 5–7 of column 3. Without the line, each former line pixel takes the label of the neighbour that queued it first: (0,5), (3,4) and (4,4) go to B, the other five to A. The boundary follows the same ridge.

P4. B sits at height 6 on the slope. Pop 3 is (2,6) at height 4 (B), pops 4–6 run downhill: (2,5) height 3, (3,5) height 2, (4,5) height 1, all at water level 4: B’s water reaches the right-hand minimum at level 4 and drowns it. The final result is the same as with the marker in the minimum (two basins).

P5. 5 markers (A–E), 59 pops, 20 line pixels: the grid is just noise, and every minimum makes a region. With 4 neighbours there are 7 regional minima: two pixels that were not minima with 8 neighbours (they had a lower or equal diagonal neighbour) now are.

P6. (2, 2) becomes a regional minimum without a marker: a puddle in the middle of the dam. A reaches it first (it is queued by (1,2) at pop 5) and drowns it at pop 6, at water level 2. A’s region grows by the puddle and the line moves one diagonal towards B: 4 line pixels, (1,4), (2,3), (3,2), (4,1), and the corners (0,4) and (4,0) now go to A.

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 watershed/src/ws_flooding/exercise.rs. The priority queue is given (HeapQueue: a binary heap with arrival numbers; HeapQueue::lifo() breaks ties last in, first out). Markers A, B, … are labels 1, 2, …; a line pixel is 0.

C1. regional_minima(f, eight): the plateaus with no lower neighbour, labelled 1, 2, 3, …:

for every pixel s not yet seen:
    collect the plateau of s: flood fill over neighbours of the same height
    on the way, note whether any neighbour of the plateau is lower
    if none is lower: give the whole plateau the next label

C2. watershed(f, markers, eight, line, queue), Meyer’s flooding:

for every marker pixel, in raster order:
    queue its unlabelled neighbours (in reading order), with priority f
while the queue is not empty:
    p = the lowest pixel (first in, first out among equal heights)
    if line and p's labelled neighbours carry two different labels:
        p is a line pixel; it queues nothing
    else:
        label(p) = the label of the pixel that queued p
        queue p's unlabelled neighbours that are not yet queued

Keep, for every pixel, whether it is queued and by which label. The checks are B1 (the first eight pops, 23 pops in all, the line, the first line pixel at pop 15), B2 (7 line pixels with 8 neighbours), B3 (FIFO and LIFO) and B4.

C3. BucketQueue: one first-in-first-out list per height 0, 1, \dots, 255 and a pointer to the lowest list that may be non-empty (the math slide “why a bucket queue is linear”). push appends to the list of its height and moves the pointer down if needed; pop moves the pointer up past empty lists and takes the front. The checks compare it with the heap: the same pixels in the same order, and the same watershed.

Then cargo run -p watershed -- ws-flooding. It prints the result of the exercise grid with 4 and 8 neighbours, and floods a 1024 \times 1024 landscape in 256 grey levels (the inverted synthetic nuclei image) from all its regional minima, once with the heap and once with the bucket queue. Open out/ws-flooding/all-minima-crop.png (the top-left quarter, line pixels white).

C4. How many regional minima does the large landscape have, and how many line pixels does the watershed make? What does all-minima-crop.png look like, and why?

C5. Compare the two run times. B5 predicts about 20 times fewer steps for the bucket queue. Why is the measured gain smaller?

The model solution is watershed/src/ws_flooding/solution.rs in the download.

C4. 92 951 regional minima (with 8 neighbours) in about a million pixels, and 561 342 line pixels, more than half of the image. The picture is confetti: thousands of tiny regions, a few pixels each, separated by white lines, in the background as well as inside the nuclei. Every speck of camera noise is a regional minimum, and every minimum gets its own region: oversegmentation in its purest form. When the regions are this small, most pixels touch two of them, so most pixels become line pixels. The next unit is about the cures.

C5. On our computer the heap took about 0.7–1.0 s and the bucket queue about 0.26–0.44 s: two to three times faster, not twenty (the times differ from run to run and between computers; the labels are always the same). The estimate counts only the queue operations. Every pop also reads 8 neighbours, compares labels and pushes, and that work is the same for both queues. Also, the heap holds only the shoreline, not all n pixels, so a heap operation costs less than \log_2 n = 20 steps.

Where this leads

The algorithm is fast, exact and simple; the hard part is the input: which landscape and which markers. The next unit floods the gradient of a real image and compares smoothing, h-minima and markers as cures for oversegmentation. The graph-cut day (day 27) puts the same pixel graph and the same seeds to a different use (minimum cuts instead of minimax paths), and the graph-based segmentation day (day 29) shows that this flooding is a minimum spanning forest grown from the markers.