Topic: segmentation

Which pixels belong to which object? Every approach in the course, side by side

Thresholds, watersheds, graphs, energies, moving curves and learned models compared: what each assumes, what it costs, and when it fails.

Segmentation is taught on many days of this course, each time from a different angle. This page puts the approaches next to each other. It does not teach any of them; follow the links to the units for that. Read it after you have met a few methods, or use it to choose where to go next.

The question

Segmentation answers two questions about an image:

  • Which pixels are object? One label per pixel: object or background, or one of a few classes. This is semantic segmentation.
  • Which object does each pixel belong to? Touching nuclei must become two objects, not one blob. This is instance segmentation, and it is what you need for counting and measuring.

Three panels. Left: a grey noisy image with ten oval bright nuclei on a background that gets brighter from left to right; one nucleus in the middle is dim; two pairs of nuclei touch. Middle: the ground-truth mask, white nuclei on black. Right: the ground-truth instances, each nucleus in its own colour.

A synthetic field of ten nuclei (160 × 160 pixels). The light falls off from right to left, one nucleus is dim, and two pairs touch. Middle: the true object pixels. Right: the true objects, one colour each. The same image is used in the comparison below.

What makes it hard is never the easy pixels in the middle of an object. It is the pixels where the image does not decide: noise, a weak or missing piece of edge, uneven light, two objects that touch, an object that looks like the background. Every method below is a different answer to “what do we do where the image does not decide?”. Each one adds an assumption: a grey level model, a smooth boundary, a seed, a shape, or examples.

Five families

Across the course, the methods fall into five families.

  1. Each pixel alone. Decide from the grey level (or colour, or a vector of filter responses) of one pixel: a global threshold, Otsu and minimum error, local thresholds, k-means and Gaussian mixtures, colour clusters.
  2. Regions grown on a graph. Pixels are nodes, neighbours are joined by edges, and regions grow from seeds or minima: the watershed (on a real image, on the distance transform, as a spanning forest), the random walker, spanning trees and Felzenszwalb–Huttenlocher, merge trees, superpixels.
  3. Energy with neighbours. Write down a cost for a whole labelling (misfit to a grey level model plus a price for every pair of neighbours with different labels) and find its minimum: segmentation as energy minimisation, graph cuts, the Ising prior, normalized cuts.
  4. A moving boundary. Start with a curve and move it until it fits: snakes, active shape models, geodesic active contours, Chan–Vese; or find the best boundary in one global search with dynamic programming in polar coordinates and live-wire.
  5. Learned from examples. Let labelled pixels or images define what “object” means: pixel classification with a forest or an SVM, the U-Net, routes from masks to objects, StarDist, Cellpose, promptable segmentation (SAM).

Two further steps belong to almost every pipeline: cleaning a mask with morphology and turning a mask into objects by labelling.

A scatter of method names. x axis, what you must supply: nothing, a few parameters, seeds or a start curve, painted pixels or shapes, many labelled images. y axis, what one decision looks at: one pixel, a neighbourhood, a region or a boundary, the whole object or image. Global threshold and Otsu sit bottom left; k-means and local thresholds a little higher; graph cut and MRF at a neighbourhood with a few parameters; FH, superpixels and merge trees at regions with few parameters; normalized cuts top left; watershed, snakes, Chan–Vese and random walker in the middle column; live-wire and polar DP between seeds and shapes; the active shape model top, at shapes; forests and SVMs at painted pixels and a neighbourhood; U-Net, SAM, StarDist and Cellpose at the right, high up. Colours mark the five families.

A qualitative map. Horizontal: what you must supply before the method can run. Vertical: how much of the image one decision depends on. Moving right costs effort (seeds, painting, annotation); moving up makes the method robust to noise and gaps, but adds assumptions that can be wrong.

Side by side

Approach Assumes You supply Cost Fails when Units
Global threshold, Otsu, mixtures object and background differ in grey level, everywhere the same nothing (or the number of classes) one histogram pass uneven light; overlapping grey levels; noise specks histogram, Otsu, mixtures
Local threshold, hysteresis the background varies slowly; objects are smaller than the window window size, offset a few box filters objects larger than the window; low contrast local thresholds
k-means, colour clusters classes are compact clouds in feature space k, the feature space a few passes over the pixels elongated or unequal clouds; spatial context ignored k-means, colour
Watershed objects are basins of a landscape (gradient, inverted distance) the landscape; markers or h sort + one flooding pass over-segmentation without markers; leaks through gaps landscape, real image, distance
Random walker boundaries lie where neighbours differ; seeds are representative seeds for every label one sparse linear system far from all seeds; no edge; small seeds near big ones random walker
Spanning trees, FH, merge trees, superpixels regions are internally similar; borders are weak links a scale k or a cut of the tree nearly linear (sort edges) chaining through one weak link; texture MST and FH, merge trees, superpixels
Graph cut, MRF a grey level model per label + short boundaries the model or seeds, the weight λ one max-flow (exact for two labels) thin structures (shrinking bias); wrong model; blocky boundaries energy, graph cut, Ising
Normalized cuts groups are strongly linked inside, weakly between, and balanced the affinities, the number of groups eigenvectors of a large matrix unbalanced groups; only approximate normalized cuts
Snakes, geodesic contours the boundary is a smooth curve on strong edges a start curve near the object many small steps (local minimum) gaps in the edge (leaks); bad start; concavities snakes, geodesic
Chan–Vese inside and outside have different mean grey levels a start (any), λ many steps (local minimum) uneven light; objects of several grey levels Chan–Vese
Dynamic programming, live-wire the boundary is a path of low cost (star-shaped, or between clicks) a centre, or clicks along the boundary one global search on a grid non-star shapes (polar); many clicks on weak edges polar DP, live-wire
Active shape model the object looks like the training shapes landmarked training shapes, a start a few search iterations shapes outside the training set shape models, ASM
Forest or SVM on feature stacks the painted pixels represent all cases; filters capture the difference painted strokes; the filter bank training: seconds; prediction: per pixel anything not painted (dim cells, new stains); merges forest, SVM
U-Net and instance networks the test images look like the training images many annotated images, a GPU training: hours; prediction: fast domain shift; confident errors; merged contacts U-Net, instances, StarDist, Cellpose
Promptable models (SAM) the object is “a thing” in natural-image terms a click or box per object; a very large pretrained model heavy encoder once, light decoder per click microscopy unlike its training data; ambiguous parts SAM, networks vs classical

Edges or regions?

Many pairs in the table differ in one way: do they look at edges (local differences between neighbours) or at regions (what the inside and outside look like as a whole)?

  • Edge-based: the gradient watershed, snakes, geodesic contours, live-wire, the contrast-sensitive weights of graph cuts and the random walker. They cope with uneven light, because an edge is local. They suffer where the edge is weak or broken: there the boundary leaks.
  • Region-based: thresholds, mixtures, Chan–Vese, the data term of graph cuts. Noise averages out over a region, and blurred edges are fine. They fail when the region model is wrong: uneven light, an object with two grey levels.

Most good methods use both: graph cuts and the random walker put the region model in the data term and the edges in the neighbour weights. The Chan–Vese unit has the full comparison table, and the three seeded methods (watershed, random walker, graph cut) differ in exactly how they add up the edges between the seeds. Try them on the same seeds:

Try the presets: on a clean edge the three agree; at a gap in a wall, or where there is no edge at all, they disagree, each in its own way. Questions on this demo: exercise of the watershed as a spanning forest.

From a mask to objects

A semantic mask is not yet a list of objects. Labelling the connected components gives one object per blob, so two nuclei that touch come out as one. The classical cure is the watershed of the distance transform: every object has a peak of “distance to the background” in its middle, and the watershed cuts at the narrow neck between two peaks.

Four panels. A noisy image of two overlapping bright discs; the thresholded mask outlined as one object; the distance transform, bright at the two disc centres and darker at the neck; the watershed result with two objects in two colours split along a straight line at the neck.

Two touching discs. Threshold and labelling give one object; the distance to the background has two peaks (14 pixels at the centre); its watershed splits the blob at the neck into two objects.

Networks face the same problem and solve it in the same spirit: they predict a map from which objects can be separated (a boundary class, a distance map, star-convex rays, or a flow field), and a decoding step turns it into objects. See from masks to objects, then StarDist and Cellpose. The cure fails in the same way for both: a neck that is too wide (two nuclei squashed together) gives only one peak; an elongated or bent object gives several peaks and is split.

How each family fails

Each assumption has a typical failure. Recognising it in a result tells you which method to try next.

Four panels. (a) A mosaic of 1004 small coloured regions. (b) A noisy disc with a thin horizontal arm; the graph-cut outline follows the disc and ignores the arm. (c) A light image with a dark ring that has a gap on the right; the contour has escaped through the gap and runs along the image border. (d) The ten-nucleus image with outlines; the dim nucleus in the middle, marked by a dashed red circle, has no outline.

One typical failure per family, all computed. (a) Watershed of the gradient without markers: every noise minimum floods its own basin: 1004 regions for 2 true ones. (b) Graph cut with a large smoothness weight (λ = 12): the thin arm costs more boundary than its pixels gain, so 0 % of it is kept (99 % at λ = 0.5). (c) An edge-based contour pushed outwards by a balloon force escapes through a gap in the wall and fills 6524 pixels outside the object (of 8100 in the image; 0 with the wall closed). (d) A forest trained on bright nuclei finds 0 % of the dim one (dashed circle): its mean object probability there is 0.26.
What you see Likely cause What helps
Hundreds of tiny regions one region per minimum (watershed) or per noise blob markers, h-minima, smoothing first, region merging
Thin parts and corners cut off boundary length is penalised (graph cut, snakes, Chan–Vese) smaller λ; edge-sensitive weights; seeds on the thin part
A region floods into the background an edge with a gap (watershed, geodesic contours) a region term; markers on both sides; smaller balloon
One side of the image is all object one grey level model for uneven light background correction, local threshold, an edge-based method
Touching objects merged a mask was labelled directly distance-transform watershed; an instance network
A class of objects missing not in the training examples (forest, network) paint or annotate those cases; check per subgroup

The math: one energy behind many methods

Many of the methods minimise the same kind of energy over a labelling L (one label L_p per pixel p): E(L) \;=\; \sum_{p} D_p(L_p) \;+\; \lambda \sum_{(p,q)\ \text{neighbours}} w_{pq}\,[L_p \ne L_q]. The data term D_p says how well pixel p fits label L_p (for example (I_p - c_{L_p})^2, or -\log of a mixture or classifier probability); the boundary term pays w_{pq} for every neighbouring pair with different labels, a small w_{pq} across a strong edge.

  • \lambda = 0: each pixel decides alone. With D_p = (I_p - c_\ell)^2 and fixed means this is a threshold halfway between the means; alternating with updating the means gives isodata/k-means.
  • Two labels, any \lambda \ge 0: the exact minimum is one minimum cut (graph cuts); with an Ising prior it is the MAP estimate of the Markov random field.
  • A continuous curve C instead of pixel labels, with D = (I - c_{\text{in/out}})^2 and boundary term \lambda\cdot\text{length}(C): the Chan–Vese energy, minimised locally by level sets. With the data term dropped and the length weighted by an edge function g(|\nabla I|): geodesic active contours.
  • Seeds fix some labels; the data term disappears. Replacing [L_p \ne L_q] by |x_p - x_q|^\beta with x_p \in [0,1]: \beta = 1 gives the graph cut, \beta = 2 the random walker (a linear system), and with the weights raised to a large power only their order matters, giving the watershed (a minimum spanning forest; see the power watershed).
  • Dynamic programming minimises a boundary energy (cost along the curve plus a smoothness price per step) exactly, but only over curves of a restricted kind (one radius per angle).
  • A network trained with a per-pixel loss learns D_p from examples, with a receptive field so large that the “neighbour” term is folded into the data term.

What changes between methods is the model (which D, which w, pixels or a curve) and the optimiser (exact cut, linear system, flooding, gradient descent, dynamic programming). The failures above come from the model; the local minima of snakes and level sets come from the optimiser.

Judging a segmentation

A segmentation is only as good as the comparison that checks it. Pixel scores (Dice, Jaccard, ROC and precision–recall) cannot see whether two nuclei were merged: the gallery above has a local threshold and a split version with the same Dice (0.89) but 8 and 9 matched objects. For objects, match predicted to true objects at an IoU threshold and count splits, merges, misses and false objects (object evaluation). Annotators disagree too: boundaries and the uncertain ground truth. And a learned method is only honestly evaluated on images it never saw during training or tuning (leakage).

Choosing

A short guide, not a rule:

  1. Look at the histogram and the image. Two clear peaks and even light: a threshold is enough. Uneven light: correct the background or use a local threshold.
  2. Objects touch? Add the watershed of the distance transform (or an instance network).
  3. Noisy, but the grey level model is right? Add a smoothness term: graph cut or MRF.
  4. Edges are clear but regions are not uniform? Edge-based: seeded watershed, random walker, live-wire, geodesic contours.
  5. A few important objects, and you can click? Seeded methods and live-wire are fast and exact where the image is ambiguous.
  6. Objects differ by texture or context, not by grey level? Paint pixels and train a classifier; for many images of one kind, annotate and train a network.
  7. Always: check the result against a hand-annotated subset, with object-level scores.

All units on this topic

Day Units
12 Thresholding histogram · Otsu (demo) · local thresholds (demo, hysteresis) · evaluation (demo)
13 Morphology opening, closing, distance transform (demo)
14 Labelling connectivity and labelling (demo)
15 Watershed landscape (demo) · real image (demo) · distance transform (demo)
27 Graph cuts energy (demo) · graph cut (demo) · normalized cuts (demo)
28 Ising Bayesian denoising with an Ising prior (demo)
29 Graph-based random walker (demo) · spanning trees, FH (demo) · watershed as MSF (demo) · merge trees (demo) · superpixels (demo)
30 Snakes snakes (demo) · shape models · active shape models (demo)
31 Level sets geodesic contours (demo) · Chan–Vese (demo)
32 Dynamic programming polar boundaries (demo) · live-wire (demo)
33–35 Learning pixel classification (forest) (demo) · SVM pixels (demo) · k-means (demo) · mixtures on images (demo)
36, 39, 40 Networks U-Net (demo) · masks to objects (demo) · StarDist · Cellpose · SAM · compared with classical pipelines
37 Evaluation matching objects (demo) · uncertain ground truth
42 Colour colour segmentation (demo)

Related topic pages: energy minimisation (the energy view in depth), eigenvectors (normalized cuts, shape models), removing noise; all topics.