Search

Search papers and lessons

Image Segmentation

Level 3 · 9 min read

Image segmentation labels every pixel of an image with a class, so a model answers where each object is, not just what is in the picture.

On this page

  • Colour = topic mix
  • Calculus
  • Linear algebra
  • Architectures
  • Neural network basics
  • Discrete math
  • Probability
  • Sign in to see your progress

TL;DR

Image segmentation gives every pixel in an image a label, such as road, person, sky or tumour. A plain image classifier answers "what is in this picture?" with one label for the whole image. A segmentation model answers "which pixels belong to what?", which is the question a robot, a medical scanner or a photo editor actually needs answered.

The standard approach is a fully convolutional network. It produces one score per class for every pixel, turns those scores into probabilities with a softmax at each pixel, and trains with cross-entropy averaged over all pixels.

Where you'll see it: in the background blur of a video call, in self-driving cars that must know where the drivable road ends, and in medical tools that outline organs or lesions on a scan.

Intuition

Labelling every pixel

Think of a colouring book in reverse. You are handed a photo and asked to paint over it with flat colours, one colour per kind of thing: green for grass, grey for road, blue for car. The result is a map with the same width and height as the photo, where each cell says what it is. That map is the output of segmentation.

The difference from classification matters. A classifier throws away position. It can tell you a cat is present, but not whether the cat is in the left corner or fills the frame. Segmentation keeps position, so its output has to be a full-resolution grid of labels.

Why does this need a new kind of network? A classifier ends in a few numbers that summarise the whole image. Segmentation needs a grid of numbers, one stack of class scores per pixel, so the network must keep spatial detail all the way to the output. The usual solution is an encoder-decoder: the encoder shrinks the image down to a compact description of what is there, and the decoder grows that description back into a map at the original size.

0.20.40.60.81012345probability given to the true classloss
  • loss = -ln p
The per-pixel loss rises steeply as the model gives the correct class less probability. The two marked points are worked through below.

The shape of the network

flowchart LR
  A["Input image"] --> B["Convolution blocks"]
  B --> C["Downsample"]
  C --> D["Bottleneck"]
  D --> E["Upsample"]
  B -.skip connection.-> E
  E --> F["1 by 1 convolution: K scores per pixel"]
  F --> G["Softmax per pixel"]

The dashed arrow is a skip connection, used in U-Net-style models. Downsampling throws away fine detail such as the exact edge of an object. Copying features from the encoder straight across to the decoder gives the decoder that detail back, so object boundaries come out sharp.

The math

Setup

Let the image have H×WH \times W pixels and let there be KK classes. For each pixel (i,j)(i, j) the network produces a vector of raw scores zij∈RK\mathbf{z}_{ij} \in \mathbb{R}^K, one score per class. The label of that pixel is yij∈{1,…,K}y_{ij} \in \{1, \dots, K\}, taken from the ground-truth mask.

Per-pixel probabilities

The Softmax turns each pixel's scores into probabilities that are positive and sum to 1:

p^ij,k=exp⁡(zij,k)∑m=1Kexp⁡(zij,m).\hat{p}_{ij,k} = \frac{\exp(z_{ij,k})}{\sum_{m=1}^{K} \exp(z_{ij,m})}.

Here p^ij,k\hat{p}_{ij,k} is the probability the model gives class kk at pixel (i,j)(i, j). The network is the same function applied everywhere, so it has one output head that is evaluated at every position.

The loss

Apply the cross-entropy loss to each pixel and average over all of them:

L=−1HW∑i=1H∑j=1Wln⁡p^ij, yij.L = -\frac{1}{HW} \sum_{i=1}^{H} \sum_{j=1}^{W} \ln \hat{p}_{ij,\,y_{ij}}.

The inner term is the loss for one pixel: the negative log of the probability given to that pixel's true class. The outer sum runs over pixels, and dividing by HWHW gives the average, so images of different sizes are on the same scale. Everything else is the same as classification, applied independently at each pixel.

Measuring quality

Accuracy, the fraction of pixels labelled correctly, is easy to compute but misleading when one class is rare. The standard overlap score is the intersection over union, or IoU. For one class, with PP the set of predicted pixels and GG the set of true pixels:

IoU=∣P∩G∣∣P∪G∣.\mathrm{IoU} = \frac{|P \cap G|}{|P \cup G|}.

It is 1 for a perfect match and 0 for no overlap. The mean IoU averages this over the classes. A related score, the Dice coefficient, is 2 ∣P∩G∣∣P∣+∣G∣\frac{2\,|P \cap G|}{|P| + |G|}. Both reward getting the object's pixels right and penalise both missed pixels and false ones.

Worked examples

Example
A four-pixel image with two classes

Take a strip of four pixels, with classes background (0) and object (1). For each pixel the network gives two logits, and the true label is known.

  1. Pixel 1: logits (2.0,0.0)(2.0, 0.0), true label background.
    • Softmax: e2=7.389e^{2} = 7.389 and e0=1e^{0} = 1, so p^bg=7.389/8.389=0.8808\hat{p}_{\text{bg}} = 7.389 / 8.389 = 0.8808.
    • Loss: −ln⁡0.8808=0.1269-\ln 0.8808 = 0.1269.
  2. Pixel 2: logits (0.0,1.0)(0.0, 1.0), true label object.
    • Softmax: p^obj=e/(1+e)=2.718/3.718=0.7311\hat{p}_{\text{obj}} = e / (1 + e) = 2.718 / 3.718 = 0.7311.
    • Loss: −ln⁡0.7311=0.3133-\ln 0.7311 = 0.3133.
  3. Pixel 3: logits (0.5,0.5)(0.5, 0.5), true label object.
    • Softmax: both probabilities are 0.50.5.
    • Loss: −ln⁡0.5=0.6931-\ln 0.5 = 0.6931.
  4. Pixel 4: logits (1.0,3.0)(1.0, 3.0), true label background.
    • Softmax: p^bg=e1/(e1+e3)=2.718/22.804=0.1192\hat{p}_{\text{bg}} = e^{1} / (e^{1} + e^{3}) = 2.718 / 22.804 = 0.1192.
    • Loss: −ln⁡0.1192=2.1269-\ln 0.1192 = 2.1269.
  5. Average over the four pixels: (0.1269+0.3133+0.6931+2.1269)/4=3.2603/4=0.8151(0.1269 + 0.3133 + 0.6931 + 2.1269) / 4 = 3.2603 / 4 = 0.8151.

Interpretation: pixels 1 and 2 are confident and right, so they cost little. Pixel 4 is confidently wrong, and it contributes more than the other three together. The loss is dominated by the pixels the model gets most wrong, which is what drives the training.

Example
Why accuracy lies on a medical scan

A 256 by 256 scan has 65,53665{,}536 pixels. A tumour covers 1,2001{,}200 of them, so it is 1,200/65,536=1.83%1{,}200 / 65{,}536 = 1.83\% of the image.

  1. A model that labels every pixel as healthy tissue gets 65,536−1,200=64,33665{,}536 - 1{,}200 = 64{,}336 pixels right.
  2. Its accuracy is 64,336/65,536=98.17%64{,}336 / 65{,}536 = 98.17\%.
  3. Its IoU for the tumour class is ∣P∩G∣/∣P∪G∣=0/1,200=0|P \cap G| / |P \cup G| = 0 / 1{,}200 = 0, because it predicts no tumour pixels at all.

Interpretation: 98 percent accuracy sounds excellent and the model is useless. This is why segmentation is judged by IoU or Dice per class, and why the loss is sometimes weighted so rare classes count for more.

Tradeoffs and failure modes

Segmentation needs a label for every pixel, and that is expensive. A mask for one image can take minutes of careful drawing, so datasets are small compared to classification datasets. Data augmentation helps, but only if the flips, crops and rotations are applied to the image and its mask together.

Downsampling buys context at the cost of detail. A deep encoder sees the whole scene but blurs small objects. Skip connections and high-resolution branches recover detail, at the cost of memory, since full-resolution feature maps are large.

SituationLikely problemBetter choice
Thin objects such as wires or blood vesselsDownsampling erases themSkip connections, or a high-resolution branch
Rare class covers a few percent of pixelsModel ignores it, accuracy stays highReport IoU or Dice, weight the loss for the rare class
Output edges are blockyUpsampling is too coarseLearned upsampling via Transposed Convolution, or a skip connection
Two touching objects of the same classMerged into one blobInstance segmentation, which labels each object separately
Little labelled dataOverfitting, poor generalisationPretrained encoder and heavy augmentation

Segmentation labels are classes, not objects. A semantic model that marks all people as "person" cannot tell two people apart. Instance segmentation solves that, at additional cost.

History

Before deep learning, segmentation was done with hand-built features, graph cuts and conditional random fields. Those methods worked on textures and colours but struggled with the variety of real scenes.

In 2014 Jonathan Long, Evan Shelhamer and Trevor Darrell showed that a classifier trained on whole images could be converted into a fully convolutional network that produces a dense map directly. Their paper made per-pixel prediction with deep networks the standard approach.

In 2015 Olaf Ronneberger, Philipp Fischer and Thomas Brox published U-Net for biomedical images. It used a symmetric encoder-decoder with skip connections and trained well on very few annotated scans, which made it popular in medicine and beyond. Later models such as DeepLab added dilated convolutions and refinements, but the encoder-decoder idea remained central.

Check yourself

QuestionWhat is the difference between image classification and image segmentation in terms of the network's output?Show answer

A classifier outputs one vector of class scores for the whole image. Segmentation outputs a grid of class scores, one vector per pixel, with the same height and width as the input, so the output keeps spatial position.

QuestionA pixel has logits (0.0, 2.0) and its true class is 0. What is its cross-entropy loss, to two decimals?Show answer

The softmax probabilities are e0/(e0+e2)=1/8.389=0.1192e^{0} / (e^{0} + e^{2}) = 1 / 8.389 = 0.1192 for class 0. The loss is −ln⁡0.1192=2.13-\ln 0.1192 = 2.13, to two decimals.

QuestionWhy is the loss averaged over pixels instead of summed?Show answer

Averaging divides by HWHW, so the loss does not depend on the image size. Without it, a large image would produce a much larger loss and gradient than a small one, and the learning rate would have to be retuned for every input size.

QuestionA model segments tumours and reports 97 percent pixel accuracy. Why might that still be a bad model?Show answer

If tumours cover only a few percent of pixels, a model that predicts no tumour at all already scores around 97 percent. Per-class IoU or Dice would show the tumour class scoring near zero.

QuestionWhy do U-Net-style models copy encoder features across to the decoder?Show answer

Downsampling discards fine spatial detail, such as exact edges. Skip connections pass high-resolution features from the encoder to the decoder, so the decoder can place object boundaries precisely when it upsamples.

Sources