Exercise: connectivity and labelling

Before this unit: Day 13: Morphology.

Goal

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

  • count the components of a small mask with 4- and with 8-connectivity, and the holes with the complementary connectivity,
  • explain the digital topology paradox and choose a consistent pair of connectivities (2D and 3D),
  • label a small image by flood fill and by the two-pass algorithm, with its equivalence table,
  • run a sequence of union–find operations by hand, with and without union by rank and path compression.

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

Background

Idea What it means
N_4(p), N_8(p) neighbours sharing an edge; edge or corner
path, connected each pixel a neighbour of the previous; any two pixels joined by a path in the set
component maximal connected set; one label per component
consistent pair objects 8 / background 4 (course convention) or 4 / 8; in 3D (26, 6), (6, 26), (18, 6)
hole background component that does not touch the image border
flood fill grow from a seed with a queue (rings) or a stack (arms)
two-pass raster scan with the visited neighbours (8: up-left, up, up-right, left), provisional labels, equivalences, second pass
union–find parent array; find = follow parents to the root; union = hang one root under the other

Coordinates are (row, column), starting at 0. In union–find, union(a, b) hangs the root of a under the root of b; with union by rank, the root of lower rank goes under the other, and on a tie the root of a goes under the root of b.

By hand

B1. The 8 \times 8 mask (1 = object):

1 1 0 0 0 0 1 0
1 1 0 0 0 1 0 0
0 0 1 0 1 0 1 0
0 0 0 1 0 0 0 1
0 1 1 1 0 0 0 0
0 1 0 1 0 0 1 1
0 1 1 1 0 0 1 1
0 0 0 0 0 0 0 0
  1. How many objects are there with 8-connectivity? Mark them.
  2. How many with 4-connectivity?
  3. With objects 8 and background 4: how many background components are there, and how many of them are holes? What changes with objects 4 and background 8?

B2. Label this 6 \times 6 mask with the two-pass algorithm and 8-connectivity.

1 0 0 0 1 0
1 0 0 1 0 0
1 0 0 1 0 1
1 1 1 1 0 1
0 0 0 0 0 1
1 1 0 1 1 1
  1. Write the provisional labels after the first pass, and at which pixels equivalences are recorded.
  2. Give the equivalence classes and the final labels (classes numbered in order of their smallest provisional label).
  3. How many objects are there with 4-connectivity?

B3. Union–find on the labels 1, \dots, 7, each starting as its own set: union(1,2), union(3,4), union(2,4), union(5,6), union(6,7), union(4,7). (a) Draw the forest without heuristics. What is the depth of node 1, and how many parent pointers does find(1) follow? (b) Draw the forest of find(1) with full path compression. What is the largest depth now? (c) Redo (a) with union by rank: the forest, the ranks, the largest depth, and the cost of find(1).

B4. The diamond-shaped closed curve of the lecture has 16 pixels, each touching its two curve neighbours only at corners, around an inside of 25 pixels. For the pairs (objects/background) 8/8, 4/4, 8/4 and 4/8, give the number of object components and of background components. Which pairs are contradictory, and why?

B5. 3D. Three voxels lie on a body diagonal of a cube: (1,1,1), (2,2,2), (3,3,3). How many objects are there with 6-, 18- and 26-connectivity? And three voxels on a face diagonal, (1,1,2), (2,2,2), (3,3,2)?

B6. Cost. A 1000 \times 1000 image is entirely foreground. (a) A recursive flood fill calls itself for each new neighbour. How deep can the recursion become? (b) The two-pass algorithm on the same image: how many provisional labels, and how many equivalences? (c) The worst case for the number of provisional labels with 8-connectivity is a pattern of isolated pixels. Which pattern, and how many labels does it give on a w \times h image?

B1. (a) 2 objects: the large one (the 2 × 2 block at the top left, the diagonal chain through (2,2), (3,3), (2,4), (1,5), (0,6), the branch (2,6), (3,7) and the ring at rows 4–6), 19 pixels; and the 2 × 2 block at the bottom right, 4 pixels. (b) 9: the top-left block, (0,6), (1,5), (2,2), (2,4), (2,6), (3,7) as single pixels, the ring together with (3,3) (which touches (4,3) by an edge), and the bottom-right block. (c) With background 4: 4 background components. The diagonal chains cut off the region above them (rows 0–2, columns 2–5) and a small pocket at the top right ((0,7), (1,6), (1,7), (2,7)); both touch the border, so they are not holes. The rest of the background touches the border too. One component, the pixel (5,2) inside the ring, is a hole. With objects 4 / background 8 there are 2 background components: everything outside, and the same hole (the ring is 4-connected, so it still encloses it).

B2. (a) First pass:

1 . . . 2 .
1 . . 2 . .
1 . . 2 . 3
1 1 1 1 . 3
. . . . . 3
4 4 . 5 3 3

At (3,2) the visited neighbours carry 1 (left) and 2 (up-right): record 1 \equiv 2. At (3,3) they carry 1 and 2 again: already equivalent. At (5,4): 3 (up-right) and 5 (left): record 3 \equiv 5. (b) Classes \{1, 2\}, \{3, 5\}, \{4\}, numbered 1 \to 1, 2 \to 1, 3 \to 2, 4 \to 3, 5 \to 2:

1 . . . 1 .
1 . . 1 . .
1 . . 1 . 2
1 1 1 1 . 2
. . . . . 2
3 3 . 2 2 2

3 objects. (c) 4: the pixel (0,4) touches (1,3) only at a corner and becomes its own object.

B3. (a) union(1,2): 1 → 2. union(3,4): 3 → 4. union(2,4): 2 → 4. union(5,6): 5 → 6. union(6,7): 6 → 7. union(4,7): 4 → 7. Parents of 1, \dots, 7: 2, 4, 4, 7, 6, 7, 7. Node 1 has depth 3; find(1) follows 1 \to 2 \to 4 \to 7, 3 pointers. (b) Nodes 1, 2 and 4 now point to 7. Remaining depths: 3 → 4 → 7 and 5 → 6 → 7, so the largest depth is 2. (c) union(1,2): tie, 1 → 2, rank(2) = 1. union(3,4): 3 → 4, rank(4) = 1. union(2,4): tie of ranks 1, 2 → 4, rank(4) = 2. union(5,6): 5 → 6, rank(6) = 1. union(6,7): root 6 has rank 1, root 7 rank 0, so 7 → 6. union(4,7): roots 4 (rank 2) and 6 (rank 1): 6 → 4. Parents: 2, 4, 4, 4, 6, 4, 6; largest depth 2 (nodes 1, 5, 7); find(1) follows 2 pointers.

B4.

pair objects background
8/8 1 1 closed curve that does not separate
4/4 16 2 no closed curve, yet inside and outside are separated
8/4 1 2 consistent
4/8 16 1 consistent: no curve, no inside

8/8 and 4/4 contradict the Jordan curve theorem; only complementary pairs are consistent.

B5. Body diagonal: the voxels share only corners: 1 object with 26, 3 with 18 and with 6. Face diagonal: they share edges: 1 with 18 and 26, 3 with 6.

B6. (a) Up to about 10^6 nested calls: every new pixel can be reached through the previous one (a long snake through the image), far beyond a typical call stack. (b) 1 provisional label (every pixel after the first copies it) and 0 equivalences. (c) Isolated pixels on every second row and every second column: no two are 8-neighbours. That gives \lceil w/2\rceil \lceil h/2 \rceil labels, about n/4. (With 4-connectivity a checkerboard gives \lceil n/2 \rceil.)

Math questions

B7. (math) Show that if p and q are 8-neighbours and q comes after p in raster order, then p is among the four visited neighbours of q. Conclude that the two-pass algorithm gives all pixels of a component the same final label, and pixels of different components different labels.

B8. (math) Breadth-first flood fill with 4-connectivity from a seed s takes pixels in order of their 4-path distance to s inside the object. Prove it, and relate the set of pixels at distance \le k to k steps of geodesic dilation of \{s\} inside the mask with the 3 × 3 cross (morphology day).

B9. (math) With union by rank (and no compression), show that find costs at most \lfloor \log_2 n \rfloor pointer steps. Give a sequence of unions on n = 2^k elements that reaches this bound.

B7. If q comes after p and they are 8-neighbours, q is either on the same row (then p is its left neighbour) or on the next row (then p is up-left, up or up-right of q). Those are exactly the four visited neighbours. So when q is processed, p already has a label, q copies a label and records an equivalence with every other label it sees; in particular \mathrm{label}(q) \equiv \mathrm{label}(p). By transitivity along a path, all pixels of a component end up in one class; and labels of different components are never declared equivalent, because only neighbours are compared.

B8. Induction on the distance: the queue holds pixels in non-decreasing order of distance (it starts with s at distance 0; a pixel at distance d adds its new neighbours at distance d + 1 to the back). A pixel at distance d + 1 has a neighbour at distance d, which is taken from the queue before any pixel at distance d + 1, and adds it then if it is still unlabelled. The set \{p : d(s, p) \le k\} is exactly \delta^{(k)}_A(\{s\}), k geodesic dilations with the cross inside the mask A: each dilation adds the 4-neighbours inside A.

B9. The depth of a node is at most the rank of its root (the rank grows by one exactly when a tree of equal rank, hence height, is hung under it), and a root of rank r has \ge 2^r nodes (quiz Q9), so r \le \log_2 n. To reach it: unite pairs (1,2), (3,4), …, then pairs of pairs, and so on: a binomial-tree pattern. After k rounds the single tree has rank k and a node at depth k = \log_2 n.

Explore: connectivity pairs

A 12 × 12 grid (click to edit) and a 5 × 5 × 5 voxel set (tab 3D voxels; edit the slices, drag the view to rotate). Choose the connectivity of the objects and of the background. Objects are coloured and numbered by component; enclosed background regions are tinted (2D) or shown as small red cubes (3D). The verdict says whether the pair is consistent.

P1. Check B4 with the four diamond presets. Then switch the background between 4 and 8 on 8/4 works: what happens to the tinted inside?

P2. Preset a diagonal line: two halves? How many background regions are there with background 8 and with background 4? Which answer matches what you see?

P3. Preset a square frame: the frame has edge-connected sides. Does the pair matter here? Now remove one corner pixel of the frame and compare 8/4 with 4/8.

P4. 3D: presets corner-touching voxels and edge-touching voxels. Check B5 by switching the object connectivity between 6, 18 and 26.

P5. 3D: a closed shell, then shell with a corner missing. With which pairs does the cavity survive? Which pairs are contradictory?

P1. As in B4: 8/8: 1 object, 1 region, 0 enclosed; 4/4: 16, 2, 1; 8/4: 1, 2, 1; 4/8: 16, 1, 0. On 8/4 works, switching the background to 8 removes the tint: the inside leaks out through the diagonal gaps.

P2. Background 8: 1 region (paths step diagonally through the line); background 4: 2 regions, the two halves. A line of diagonal steps looks like a wall, so 8/4 matches what we see; 8/8 says the halves are connected.

P3. With the intact frame every pair gives 1 object and 2 background regions (1 enclosed): there are no diagonal gaps, so the pair does not matter. With a corner removed, the frame’s two ends touch only diagonally: with 8/4 the frame is still one closed curve and the inside stays enclosed; with 4/8 the frame is one open curve (still 1 object, since the remaining pixels form one 4-connected path) and the inside connects to the outside through the diagonal gap.

P4. Corner-touching: 1 object with 26, 3 with 18 and with 6. Edge-touching: 1 with 18 and with 26, 3 with 6.

P5. Closed shell: the cavity survives with every pair (the shell has no gaps at all). Shell with a corner missing: the centre voxel touches the outside only through the missing corner. The cavity survives with background 6 or 18 and leaks with background 26. Contradictory: 26/26 (a closed shell that does not enclose) and 6/6 or 18/18 (the shell has a corner gap for the objects, yet the cavity is sealed). Consistent: 26/6, 6/26, 18/6.

Explore: the union–find forest

The labels are nodes, arrows point to parents, roots have a blue ring (with union by rank, their rank is written next to them). Step through the operations, or click two nodes to unite them (click: find to find a node’s root). The readout counts the parent pointers followed by all finds so far.

U1. Preset 6 unions (exercise): step through and check B3 (a). Then tick union by rank and check (c); choose compression full and check (b).

U2. Preset naive unions build a chain: 7 unions, then find(1) twice. What does each find cost? Repeat with union by rank, with compression full, and with halving.

U3. Preset random: 16 nodes (union by rank, full compression). Read the total pointer steps and the deepest node at the end. Switch both heuristics off: what are they now?

U4. Preset two-pass equivalences of the comb: the 4 equivalences of the comb (morphgrid below). Why is the forest flat even without heuristics?

U1. Naive: parents 2, 4, 4, 7, 6, 7, 7, find(1) costs 3. Union by rank: parents 2, 4, 4, 4, 6, 4, 6, ranks 1 (node 2), 2 (node 4), 1 (node 6); find(1) costs 2. Full compression (no rank): after find(1) nodes 1, 2, 4 point to 7, deepest node at depth 2.

U2. Naive: 7 and 7 (the chain stays). Union by rank: every union hangs the new node under 2: depth 1, each find costs 1 (total 7 steps, from the finds inside the unions). Full compression: 7, then 1. Halving: 7, then 4 (node 1 now points to 3, 3 to 5, 5 to 7, 7 to 8).

U3. With both heuristics: 12 pointer steps in total, deepest node at depth 2. Without: 23 steps, deepest node at depth 5. The trees are deeper and every later union pays for it.

U4. Every union is union(k, 1) with k a fresh root, which hangs k directly under the root 1: the comb’s teeth all meet the same label 1 along the bottom row. Chains appear only when an old root is hung under a new node again and again.

Explore: labelling step by step

The morphology day’s grid, in its label mode. Left: the mask (click to edit); right: the labels. Choose an algorithm (flood fill with a queue or a stack, two-pass with union–find, runs) and step through it; next stage jumps to the next object, row or pass. Orange numbers on the mask are the queue or stack (1 = next out); a red ≡ marks a pixel where an equivalence is recorded. The connectivity buttons choose the pair.

E1. Preset 6 × 6 (exercise): step through the two-pass labelling and check B2 (provisional labels, the two equivalences, final labels). Switch to objects 4: how many provisional labels, equivalences and objects now?

E2. Preset queue rings vs stack arms (objects 4). Step with the queue, then with the stack. What is the largest queue, and the largest stack? Repeat with objects 8.

E3. Preset a comb: many. How many provisional labels and equivalences does the two-pass algorithm need? Switch to runs: how many runs, and how many equivalences?

E4. Preset count with 4 and with 8: check B1 (a) and (b) with the result line, and count the provisional labels and equivalences with each connectivity.

E5. Preset a spiral: runs. Why does the spiral need no equivalence at all with objects 8? Draw your own shape that makes the two-pass algorithm record as many equivalences as possible in a 12 × 12 grid.

E1. With objects 8: 5 provisional labels, equivalences 1 \equiv 2 at (3, 2) and 3 \equiv 5 at (5, 4), 3 objects, as in B2. With objects 4: 6 provisional labels (the pixel (0,4) keeps its own), 2 equivalences, 4 objects.

E2. Objects 4: largest queue 7, largest stack 19. Objects 8: largest queue 13, largest stack 24. The queue holds one ring (the front), the stack holds everything that was seen but not yet taken, which grows along the arm.

E3. Two-pass: 5 provisional labels (one per tooth), 4 equivalences, all recorded on the bottom row. Runs: 16 runs (3 per tooth plus the bottom row) and the same 4 equivalences, recorded when the bottom run is compared with the 5 teeth runs above it.

E4. Objects 8: 2 objects, 4 provisional labels, 2 equivalences. Objects 4: 9 objects, 10 provisional labels, 1 equivalence (in the ring).

E5. In the spiral every new row of the shape touches only one earlier label when the scan reaches it, so the labels never meet twice: 2 objects (the spiral and the inner piece), 2 provisional labels, 0 equivalences with objects 8, 17 runs. Many equivalences need many arms that start separately and are joined later, like a comb with many teeth (or several combs).

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 labelling/src/label_connectivity/exercise.rs. Masks are images of true (object) and false; labels are whole numbers, 0 = background.

C1. flood_fill(mask, labels, seed, label, eight): give label to the component of the seed, with a queue, and return the pixels in the order they leave the queue:

label(seed) = label;  put seed in the queue
while the queue is not empty:
    take p from the front of the queue;  write p down
    for every neighbour q of p (4 or 8):
        if q is inside the image, an object pixel and has no label:
            label(q) = label;  put q at the back of the queue

The check fills a 7 \times 7 block and tests that pixels come out ring by ring (B8).

C2. label_flood_fill(mask, eight): scan the image row by row; at every object pixel without a label, start a flood fill with the next label 1, 2, 3, … The checks are B1 (a)–(c) (also the background components) and the final labels of B2.

C3. UnionFind, with find (follow the parents to the root), union(a, b) (the root of a under the root of b) and union_by_rank(a, b) (the root of lower rank under the other; on a tie, a’s root under b’s and b’s root gets rank + 1). The checks are the parents of B3 (a) and (c).

C4. label_two_pass(mask, eight): the two-pass algorithm with your union–find:

for every object pixel p, in raster order:
    L = the labels of its visited neighbours      # 8: up-left, up, up-right, left; 4: up, left
    if L is empty:  label(p) = new provisional label
    else:           label(p) = min(L);  union(l, min(L)) for every l in L
number the classes 1, 2, 3, … in order of their smallest provisional label
for every object pixel p:  label(p) = class number of find(label(p))

The checks are the provisional and the final labels of B2, and the same result as C2 on a piece of the micrograph.

Then cargo run -p labelling -- label-connectivity and open the pictures in out/label-connectivity/. The program labels a synthetic image of 30 nuclei (threshold 0.35) and the dark regions of the micrograph (grey level below 95 of 255), and fills one large nucleus blob from its centre.

C5. How many components does the nuclei mask have, with 8- and with 4-connectivity, and how many nuclei are there? Explain the difference, and why 4 and 8 agree here. Then compare the two counts for the micrograph.

C6. In fill-order.png the pixels are coloured in bands by when they left the queue (left: 4-connectivity, right: 8; red: the seed). What shape do the fronts have in each, and why? Which distance does each one measure?

C7. The program prints the number of provisional labels of the two-pass algorithm. Compare it with the number of objects. What makes a shape need more than one provisional label?

The model solution is labelling/src/label_connectivity/solution.rs in the download.

C5. The mask has 19 components with both connectivities, for 30 nuclei. Touching and overlapping nuclei share pixels above the threshold, so they become one component; see nuclei-labels.png, where several blobs of two or three nuclei have one colour. Splitting them is the job of the watershed day. 4 and 8 agree because the outlines are smooth: no two blobs touch only at a corner. The micrograph is different: 1141 objects with 4-connectivity and 764 with 8. Its dark regions are ragged and full of single noise pixels that touch only diagonally.

C6. With 4-connectivity the fronts are diamonds, with 8-connectivity squares, both centred on the seed and bent where the blob’s outline stops them. A queue takes pixels in order of their path distance from the seed inside the object (B8): the number of 4-steps (city-block distance, a diamond) or of 8-steps (chessboard distance, a square). This is the geodesic dilation of the morphology day, with the cross or the square.

C7. On the micrograph: 1720 provisional labels for 1141 objects (4-connectivity), 1052 for 764 (8). Each extra label is a part of an object that the raster scan reaches before it has seen the connection to the rest: the second arm of a U, the teeth of a comb, any object whose top has several bumps. These are the parts that need an equivalence.

Where this leads

The label image is the input of everything that follows on this day: the next unit measures each object (area, centroid, second moments, perimeter, Euler number). The watershed day (day 15) starts from labelled markers and returns a label image. Union–find returns in Kruskal’s minimum spanning tree on the graph-based segmentation day (day 29), and the connected components of every threshold set nest into the component tree of merge trees.