Back to Tutorials
Deep Learning
Advanced

Image Segmentation: Labelling Every Pixel

Make masks for a microscope picture with thresholds, see why pixel accuracy flatters them, then split touching cells apart and count them.

10 minInteractive: drag, click and try things as you read


A detector draws a box around each object. Some jobs need more than a box: a surgeon planning around a tumour, a car deciding where the road ends, a phone blurring the background behind your head. Image segmentation labels every pixel, so you get the exact shape. A segmentation is a label for every pixel, and you judge it by how well the shapes overlap. Here you’ll make masks for a picture of cells, see why the obvious score lies, and find out what it takes to count cells that touch.

Three ways to label a picture#

Classification gives the whole picture one label: “cells”. Detection draws a box around each object. Segmentation gives every pixel a label, and the set of pixels with one label is called a mask. It comes in flavours:

  • Semantic segmentation labels each pixel with a class (road, car, sky; cell or background) but doesn’t separate objects: two cars side by side are one blob of “car”.
  • Instance segmentation gives each object its own mask: car 1, car 2.
  • Panoptic segmentation does both: every pixel gets a class, and countable things also get an instance.

Scoring a mask#

To check a mask you need the true outline, usually drawn by a person, and a score for how well the two agree. The obvious one is pixel accuracy, the share of pixels labelled correctly.

Predict first

About 81% of the picture below is background. A lazy model labels every single pixel background and finds no cells at all. What’s its pixel accuracy?

Try it
A made-up microscope picture, 160 × 120 pixels, drawn with known cell outlines so every score is exact. The masks are made live by thresholds, not a neural network. The histogram counts pixels at each brightness (on a square-root scale, so the cells show up); yellow bars are labelled cell.

Two scores ignore the easy background and look only at the thing you care about. IoU (intersection over union, the same score detectors use for boxes) is the overlap between the predicted and true cell pixels divided by all the pixels either one covers. Dice is twice the overlap divided by the two masks’ sizes added together; it’s always a bit kinder than IoU and moves with it. Both are 0 for the lazy mask. They can also disagree with accuracy about which mask is better: at a threshold of 180 the pixel accuracy is slightly higher than with Otsu’s threshold (93.7% against 93.4%), but IoU is clearly lower (0.67 against 0.73), because the stricter cut loses cell pixels, and there are far fewer of those to lose. When the thing you’re segmenting is small, judge the mask by IoU or Dice, not pixel accuracy.

One threshold isn’t enough#

Cells here are brighter than their background, so the simplest segmenter is a threshold: anything brighter than a cut-off is cell. Otsu’s method (1979) picks the cut-off automatically, choosing the one that best splits the brightness histogram into two groups. It picks 141 and scores an IoU of 0.73.

Switch to vs truth and look at the edges of the picture. The light is uneven, dim on the left and bright on the right, as under a real microscope, so the bright right-hand background gets called cell. The faint cell on the left is missed completely. Tuning by hand helps a little (the best single threshold, 156, reaches 0.80) but never fixes the faint cell: to find even half of it you’d have to go down to 102, where over 6,500 background pixels are called cell.

The adaptive threshold compares each pixel with the average of the square around it instead of with one number for the whole picture. Uneven light stops mattering, IoU rises to 0.90, and the faint cell is mostly found. That’s the general lesson: a rule that looks only at one pixel’s value is fragile, and context is what fixes it.

How neural networks segment#

A neural network takes that idea all the way. Instead of a hand-written rule, it learns what a cell (or a road, or a tumour) looks like from examples where people have painted the true masks, and it judges every pixel by a wide neighbourhood around it. The classic design is U-Net, published in 2015 for medical images: an encoder shrinks the picture step by step into features that describe larger and larger areas, a decoder grows it back to full size, and skip connections pass fine detail straight across so edges stay sharp. The output is a class score for every pixel, and training pushes those scores towards the painted masks, often with a loss built from Dice itself.

The catch is the painting. Outlining every pixel by hand is slow, which is why Meta’s Segment Anything Model (SAM, 2023) mattered: trained on over a billion masks, it segments almost anything you point at with a click or a box, with no training on your images. SAM 2 (2024) follows objects through video, and SAM 3 (November 2025) also takes short text prompts like “yellow school bus” and finds every match. A common workflow today is to let SAM draft the masks and have people correct them.

From pixels to separate objects#

A cell-or-not mask tells you how much of the picture is cell. Often the question is how many cells there are, and how big each one is. That needs instance segmentation.

Predict first

The adaptive mask finds all 15 cells, but three pairs of them touch. You count the connected blobs of cell pixels. How many cells do you get?

Try it
The adaptive mask from above (offset 15), split into cells live in your browser. Each colour is one cell. A found cell is matched to a true one when their IoU is at least 0.5, as in detection.

Connected pieces gets 12 cells. The watershed, a classic fix, works out how far each cell pixel is from the background, plants a seed at the deepest point of each blob, and grows all the seeds outwards together until they meet. Two touching cells have two deep centres and a shallow neck between them, so they split along the neck. With seeds at least 8 pixels apart it finds all 15 cells.

Slide the spacing both ways and you hit the method’s weakness. Allow seeds 2 pixels apart and bumps on a cell’s outline get their own seeds, cutting 6 cells into pieces. Insist on 22 and close neighbours share a seed, so the 3 touching pairs merge again. Separating touching objects is the hard part of instance segmentation, and every method trades splits against merges. Neural instance methods learn that trade-off from examples instead of a hand-set spacing: Mask R-CNN (2017) predicts a box and then a mask inside each box, and tools built for cells, such as StarDist and Cellpose, learn shapes that keep crowded cells apart.

In code#

Instance segmentation with a pretrained network, free and local, with pip install ultralytics. This runs YOLO26’s smallest segmentation model on the bus photo from Ultralytics’ documentation:

from ultralytics import YOLO

model = YOLO("yolo26n-seg.pt")  # the smallest segmentation model; downloads the first time
result = model("https://ultralytics.com/images/bus.jpg", verbose=False)[0]

h, w = result.masks.data.shape[1:]
for box, mask in zip(result.boxes, result.masks.data):
    name = model.names[int(box.cls)]
    share = mask.sum().item() / (h * w)
    print(f"{name:7} {float(box.conf):.2f}  covers {share:.1%} of the picture")
# person  0.88  covers 5.6% of the picture
# person  0.86  covers 2.4% of the picture
# bus     0.86  covers 29.2% of the picture
# person  0.81  covers 3.8% of the picture
# person  0.65  covers 1.2% of the picture

Each detection now comes with a mask, a grid of 0s and 1s the size of the picture, so you can measure areas, cut objects out or score them with IoU against masks you’ve drawn yourself.

What to remember

  • Segmentation labels every pixel: semantic segmentation gives classes, instance segmentation also separates objects.
  • Pixel accuracy flatters masks of small things; IoU and Dice look only at the object and are the scores to use.
  • Context beats single-pixel rules, and separating touching objects is the hard part: methods trade splitting against merging.

Keep going

Sign in to save your place and keep a learning streak. Free, with Google.