Exercise: finding objects as boxes
Before this unit: From masks to objects (previous unit); Day 36: Neural networks; Day 38: Evaluation and statistics; Day 39: Variational autoencoders.
See also: Day 15: Watershed; Day 5: Deconvolution; Day 35: Gaussian mixtures.
Goal
By the end of this exercise you should be able to:
- compute the IoU of two boxes, and say how sensitive it is for small objects,
- run greedy non-maximum suppression by hand and predict the effect of its threshold,
- explain why boxes and NMS fail in crowded images of elongated cells,
- say which level of a feature pyramid suits an object of a given size, and what the top-down path adds,
- say where candidate boxes come from (a grid of guesses), knowing that anchors and centre heat maps are taught on the next day (single-shot detection).
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 |
|---|---|
| Box | [x_0, x_1] \times [y_0, y_1], a score, a class |
| IoU | intersection area / union area; for boxes the intersection is a box |
| Candidates | a coarse grid of guesses, each a box and a score (anchors and centre heat maps: next day) |
| Greedy NMS | keep the best box, delete all boxes with IoU > t with it, repeat |
| Scoring | the evaluation day: matching at IoU \ge 0.5, TP/FP/FN, F1, matching accuracy, AP |

By hand
B1. IoU of boxes. (a) A = [0, 4] \times [0, 4] and B = [2, 6] \times [2, 6]. (b) A and the same box shifted by one pixel to the right; and shifted by one pixel right and one down. (c) Two 2 \times 2 boxes shifted by one pixel. What does (b)–(c) tell you about IoU thresholds for small objects?
B2. Greedy NMS. Five candidate boxes with scores:
| box | [x_0, x_1] \times [y_0, y_1] | score |
|---|---|---|
| b_1 | [0, 10] \times [0, 10] | 0.9 |
| b_2 | [1, 11] \times [0, 10] | 0.8 |
| b_3 | [8, 18] \times [0, 10] | 0.7 |
| b_4 | [9, 19] \times [1, 11] | 0.6 |
| b_5 | [20, 26] \times [20, 26] | 0.3 |
The true cells lie under b_1 and under b_3; b_5 is a false detection. (a) Compute the IoUs b_1b_2, b_1b_3, b_1b_4, b_2b_3, b_3b_4. (b) Run greedy NMS with t = 0.3 and with t = 0.7. Which boxes are kept? Count TP, FP and FN at IoU \ge 0.5 for both. (c) Run it with t = 0.1. What goes wrong? Which box represents the second cell now, and is it a good one? (d) Would a score threshold of 0.5 change any of the results?
B3. A colony of rod-shaped bacteria lying side by side, all tilted by 45°. (a) Why do the boxes of neighbouring bacteria overlap a lot, and how much of each box is background? (b) Explain why no NMS threshold both removes duplicates and keeps all bacteria. (c) Which instance route of the previous unit would you use instead?
B4. Objects of every size. A 512 \times 512 image holds spots of 3 px, nuclei of 16 px and cell clusters of 160 px. A detector with a feature pyramid predicts boxes at strides 4, 8, 16 and 32. (a) How many cells across does each kind of object cover at stride 4 and at stride 32? Which level suits which object, if an object should cover a few cells? (b) Instead, the whole network is run on an image pyramid: the image at ×2, ×1 and ×½. How many times the cost of one pass is that? (c) A network without the top-down path predicts the spots directly from its stride-4 backbone map. What goes wrong, and what does the top-down path add to that map? (d) U-Net also has a top-down path with lateral inputs. What does a feature pyramid do differently, and why does a detector need it?
B1. (a) Intersection [2, 4]^2: 4; union 16 + 16 - 4 = 28; IoU = 0.143. (b) Right by one: intersection 3 \times 4 = 12, union 20, IoU 0.6. Right and down: 3 \times 3 = 9, union 23, IoU 0.39. (c) Intersection 1 \times 2 = 2, union 6, IoU 0.33. A shift of one pixel already fails the matching threshold 0.5 for a 2 \times 2 object, while a 40 \times 40 object hardly notices it. For small objects (spots, small cells) IoU thresholds are too strict; a distance between centres is a better matching rule.
B2. (a) b_1b_2: 9 \times 10 = 90, union 110, 0.818. b_1b_3: 2 \times 10 = 20, union 180, 0.111. b_1b_4: 1 \times 9 = 9, union 191, 0.047. b_2b_3: 3 \times 10 = 30, union 170, 0.176. b_3b_4: 9 \times 9 = 81, union 119, 0.681. (b) t = 0.3: keep b_1, delete b_2 (0.818); keep b_3 (0.111 with b_1), delete b_4 (0.681); keep b_5. Kept b_1, b_3, b_5: TP 2, FP 1 (b_5), FN 0. t = 0.7: keep b_1, delete b_2; keep b_3; b_4 survives (0.681 < 0.7); keep b_5. Kept b_1, b_3, b_4, b_5: TP 2, FP 2 (b_4 is a duplicate: it cannot be matched a second time), FN 0. (c) t = 0.1: keep b_1, delete b_2 and b_3 (0.111 > 0.1); b_4 survives (0.047 with b_1); keep b_5. The second cell is represented by b_4, a shifted duplicate; its IoU with the true cell (the box of b_3) is 0.68, so here it still counts as a TP, but the best box of the cell was deleted because it touched the first cell. (d) It removes b_5 before NMS: one FP fewer in every case; the duplicates and the lost box are unchanged.
B3. (a) A rod at 45° fills only a small part of its box (two triangles of background), and the boxes of rods lying side by side overlap almost entirely even though the rods themselves do not touch much. (b) Duplicate boxes of one rod overlap by, say, 0.6–0.9; boxes of neighbouring rods overlap by a similar amount. Any t that deletes the duplicates also deletes the neighbours, and any t that keeps the neighbours keeps duplicates. (c) Flows (long, touching, possibly bent cells) or, for straight rods, a distance map; the evaluation then uses masks, not boxes.
B4. (a) Stride 4: spot 0.75 cells, nucleus 4, cluster 40. Stride 32: spot 0.09 (about 1/100 of a cell’s area), nucleus 0.5, cluster 5. Spots belong on stride 4, nuclei on stride 4 or 8 (4 or 2 cells), clusters on stride 16 or 32 (10 or 5 cells). Twice the size, one level coarser: the object then covers about the same number of cells. (b) The ×2 image has 4 times the pixels, the ×½ image a quarter: 4 + 1 + \tfrac14 = 5.25 passes, against one pass plus a few cheap layers for the feature pyramid. (c) The stride-4 backbone map comes after a few layers: each cell sees a small region and responds to any small bright thing (a spot, a speck of debris, noise, the edge of a nucleus); without context it cannot tell them apart, so false positives. The top-down path adds the upsampled coarse maps, which have seen a large region and know what is there; the sum is sharp and knows what it sees. (d) U-Net concatenates the copied maps and predicts one mask on the finest level only. A feature pyramid adds the lateral maps (after a 1×1 convolution) and predicts boxes on every level: a large cluster gets a few cells on a coarse level instead of hundreds of cells on the finest, each of which would have to guess the box of something much larger than its view.
Math questions
B5. (math) Derive the closed form of the IoU of two axis-aligned boxes and show that it is invariant to scaling both boxes by the same factor and to translating both.
B6. (math) Consider L = 1 - \mathrm{IoU}(A, B) as a function of the position of box B. Show that its gradient is zero whenever the boxes do not overlap. What does that mean for training with this loss alone?
B7. (math) Show that greedy NMS gives the same result if all scores are replaced by g(\text{score}) for any strictly increasing g, and that its cost is O(n^2) IoU evaluations for n candidates.
B5. The intersection of [a_0, a_1] \times [b_0, b_1] and [c_0, c_1] \times [d_0, d_1] is [\max(a_0, c_0), \min(a_1, c_1)] \times [\max(b_0, d_0), \min(b_1, d_1)] when both intervals are non-empty; its area is wh with w = \max(0, \min(a_1, c_1) - \max(a_0, c_0)) and h likewise. Union = |A| + |B| - wh (inclusion–exclusion). Translating both boxes adds the same constant to all coordinates: w, h and the areas are unchanged. Scaling all coordinates by s > 0 multiplies w and h by s, every area by s^2; the ratio is unchanged.
B6. If the boxes do not overlap, then w = 0 or h = 0, and this remains so for every small shift of B (the max with 0 is in its flat part), so the intersection is 0 in a neighbourhood and L = 1 there: the gradient is zero. A network trained with this loss alone gets no signal from boxes that miss the object, however close or far they are; hence regression losses on the coordinates (or IoU variants with a distance term).
B7. NMS only uses the order of the scores (which box is “the best remaining”), and a strictly increasing g keeps the order (ties included). Each round keeps one box and compares it with the remaining ones: at most n - 1 + n - 2 + \dots = O(n^2) IoUs (fewer when many boxes are deleted early).
Explore
The demo has four modes on a 128 \times 128 synthetic cell image; the questions below use the first two. IoU: two boxes on a grid; drag a box to move it, its white corner to resize it. NMS: the candidate boxes of a simulated detector (5 jittered boxes per cell, scored by their overlap with the cell, plus 3 false boxes); step runs one round of greedy NMS (green: kept; grey dashed: removed, with its IoU; yellow: not yet decided), run all rounds; click a box and change its score with score ±. The readout uses the evaluation day’s matching at IoU \ge 0.5. Anchors and Heat map: where candidates come from; see the next day (single-shot detection).
E1. Preset IoU of two boxes. Check B1: drag B to reproduce (a), (b) and the shift by one pixel right and down. Where must B be for IoU = 1/7?
E2. Preset duplicates removed (sparse image, t = 0.5). How many candidates and how many boxes after NMS? Use step: how many duplicates does the first kept box remove? Compare F1 and matching accuracy with AP. Which number is hurt by the 3 false boxes, and how can the score threshold fix it?
E3. Still on the sparse image, set t to 0.3, 0.7 and 0.9. Write down the number of boxes and F1 each time. Why does AP hardly change?
E4. Preset touching cells: NMS deletes the neighbour (t = 0.2, true boxes shown). How many cells have no box after NMS? Step through the first round: what is deleted? Find the t with the best F1.
E5. Preset threshold too high: duplicates survive (t = 0.75). Number of boxes, FP, F1, AP? Explain why AP is high although F1 is low.
E6. Preset diagonal rod: a box is a poor shape. What fraction of the rod’s box is rod? What would a second box-based step (e.g. measuring the intensity inside the box) measure?
E1. A = [0, 4]^2, B = [2, 6]^2: intersection 4, union 28, IoU 0.143 (= 1/7). One right: 0.600; one right and one down: 0.391. IoU = 1/7 needs intersection 4 with two 4 \times 4 boxes, e.g. B at [2, 6]^2 (a 2 \times 2 overlap) or [0, 4] \times [3, 7] (4 \times 1).
E2. 48 candidates, 12 boxes after NMS (all 12 rounds). The first kept box removes 4 duplicates. TP 9, FP 3, FN 0: F1 0.86, matching accuracy 0.75; AP 1.00 (0.97 without NMS). The three false boxes have low scores: they come last in the ranking, so AP (which only asks whether the good boxes rank first) is not hurt, but F1 counts them. Setting the score threshold to 0.6 removes them: 10 boxes, F1 0.95.
E3. t = 0.3: 10 boxes, F1 0.95. t = 0.7: 34 boxes, F1 0.42. t = 0.9: 46 boxes, F1 0.33. The duplicates that survive have lower scores than the box kept for the same cell; in the ranking they come after all true detections, so AP stays 1.00 (0.97 at t = 0.9), while F1, which counts every box above the threshold, collapses.
E4. 10 boxes for 12 cells; 4 cells have no box (TP 8, FP 2, FN 4, F1 0.73). The first kept box deletes 9 boxes: its own duplicates and the boxes of its neighbours, whose IoU with it is about 0.3. F1 by t: 0.1: 0.76; 0.2: 0.73; 0.3: 0.75; 0.4: 0.89 (15 boxes, all 12 cells found, 3 FP); 0.5: 0.83; 0.75: 0.41.
E5. 46 boxes, TP 12, FP 34, F1 0.41, AP 0.98. Every cell’s best box is found (high scores first), and the 34 duplicates are ranked below them, so the precision–recall curve reaches recall 1 before the duplicates appear. AP measures ranking; F1 at a fixed operating point measures what a user would actually get.
E6. The rod fills 16 % of its box. A measurement inside the box (mean intensity, texture) would be dominated by background. A box says where an object is, not which pixels belong to it.
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 moderndl/src/detection/exercise.rs. A box is [x_0, x_1] \times [y_0, y_1] with a score.
C1. iou(a, b): the IoU of two boxes in closed form:
w = max(0, min(a.x1, b.x1) − max(a.x0, b.x0)) # width of the intersection
h = max(0, min(a.y1, b.y1) − max(a.y0, b.y0)) # height of the intersection
IoU = w·h / (area a + area b − w·h)
The checks are your answers to B1 and B2 (a).
C2. nms(boxes, t): greedy non-maximum suppression; returns the indices of the kept boxes:
remaining = all boxes, sorted by score, highest first
while boxes remain:
best = the first remaining box; keep it and take it out
take out every remaining box with IoU(best, box) > t
The checks are your answers to B2 (b) and (c).
C3. boxes_from_labels(labels): the true box of every object of a label image: the smallest box holding all its pixels (pixel (x, y) covers [x, x + 1] \times [y, y + 1]).
C4. count_matches(detections, truth, t): score the kept boxes. Walk through them from the highest score down; a box is a true positive if its best IoU with a true box not yet matched is at least t (that true box is then matched), else a false positive; true boxes left over are false negatives. The check counts TP, FP and FN of B2 (b).
Then cargo run -p moderndl -- detection and open the pictures in out/detection/. A simulated detector gives every true nucleus 5 jittered boxes (each side moved by about a pixel, the score higher the better the box fits) and adds 3 false boxes with low scores. The program runs NMS for t from 0.1 to 0.9 on a sparse image (12 nuclei) and a crowded one (45 nuclei, many touching or overlapping), and prints the boxes, TP, FP, FN and F1. The pictures show the candidates (yellow) and the boxes kept with t = 0.5 (green).
C5. On the sparse image, which t give the best F1, and what goes wrong above t = 0.6? What are the false positives at t = 0.5?
C6. On the crowded image, compare t = 0.1, 0.2 and 0.5. Why is the best t smaller than on the sparse image, and why is no t perfect? Use the printed largest IoU between two true boxes. Count the cost: how many IoUs does NMS compute at most for the 223 candidates?
The model solution is moderndl/src/detection/solution.rs in the download.
C5. The 11 visible nuclei (one of the 12 is hidden under another) get 58 candidates. t = 0.1: 13 boxes, F1 0.92; t = 0.2 to 0.5: 14 boxes, TP 11, FP 3, FN 0, F1 0.88: every nucleus keeps one box, and the false positives are the three false boxes (at t = 0.1 one of them is deleted because it overlaps a better box a little). Above 0.6 the duplicates survive: t = 0.7 keeps 27 boxes (16 FP, F1 0.58), t = 0.9 keeps 57 of the 58 (F1 0.32). A score threshold below the real boxes’ scores would remove the three false boxes (they score at most 0.4).
C6. Crowded image (44 visible nuclei, 223 candidates):
| t | boxes | TP | FP | FN | F1 |
|---|---|---|---|---|---|
| 0.1 | 34 | 33 | 1 | 11 | 0.85 |
| 0.2 | 44 | 41 | 3 | 3 | 0.93 |
| 0.5 | 57 | 42 | 15 | 2 | 0.83 |
With t = 0.1 the box of a nucleus deletes the boxes of its touching neighbours: 11 nuclei lose their box. With t = 0.5 duplicates survive next to each other (15 FP). The best here is t = 0.2, lower than on the sparse image because the neighbours’ boxes overlap. No t is perfect: some nuclei overlap each other so much (the largest IoU between two true boxes is 0.75) that their boxes overlap more than the duplicates of one nucleus do. Cost: at most 222 + 221 + \dots + 1 = 223 \cdot 222 / 2 = 24{,}753 IoUs, fewer because many boxes are deleted early.
Where this leads
Boxes are the outputs of detection networks; how a real network produces them on a grid (anchors, centre heat maps, distances to the box sides) comes on the next day (single-shot detection). The next unit asks how a network can relate a pixel to the whole image (attention and transformers) and where networks come from that nobody trained on your images (pretraining). The scoring of detections is the evaluation day’s.