◆ AI All-in-One

Level 3 In-Depth AI · Vision, Audio and Multimodal

Image Segmentation

Label every pixel. Semantic segmentation says which class each pixel belongs to, instance segmentation separates the individual objects, and panoptic segmentation does both. U-Net, Mask R-CNN and Segment Anything are the models to know.

Level
●●●●● Intermediate
Reading
12 min
To learn it well
1 hour to read, an afternoon to practise
↗ Plan a path here

Read first

Object Detection

This leads to

—
The full path from zero — 19 concepts before this one
  1. What Is AI?
  2. Vectors
  3. Derivatives and Slopes
  4. Probability Basics
  5. How Machines Learn
  6. Partial Derivatives and Gradients
  7. Matrices and Matrix Multiplication
  8. Supervised, Unsupervised and Reinforcement Learning
  9. Gradient Descent
  10. Tensors and Shapes
  11. Supervised Learning
  12. Images as Data
  13. Linear Regression
  14. The Perceptron
  15. Logistic Regression
  16. Neural Networks
  17. Convolutional Neural Networks
  18. Image Classification
  19. Object Detection
  20. Image Segmentation

Read them roughly in this order. See it on the concept map →

Why it matters

A bounding box from Object Detection is a crude outline. It tells you roughly where a tumour is, but not its exact size or shape. It tells a self-driving car there's a road ahead, but not which pixels are drivable. Image segmentation goes all the way down to single pixels: for every pixel it answers "what is this?" and, if wanted, "which object does it belong to?"

That precision matters in medicine (measuring a tumour's volume from a scan, or outlining organs for radiotherapy planning), in autonomous driving (road, lane, pavement, pedestrian), in satellite imagery (buildings, fields, floods), in photo and video editing (cutting out a person, blurring the background in video calls) and in robotics (where exactly to grip). Promptable models such as Meta's Segment Anything have made "click on something to cut it out" a standard feature of image tools.

The intuition

Think of a colouring book in reverse. You get a finished picture and must colour each region according to what it is: blue for sky, green for grass, orange for cats. That is segmentation. The result is a segmentation mask: an image the same size as the input in which each pixel holds a label instead of a colour.

There are three flavours, depending on what counts as "the same":

Classificationone label per image Detectiona box per object Semantica class per pixel Instancea mask per object Panopticboth: every pixel, each object separate sky grass cat (both the same) cat #1 cat #2 ignored background sky, grass: “stuff” cat #1: “thing” cat #2: “thing” boxes include background“cat”
Fig. 1 The same scene under different tasks. Classification gives one label; detection gives boxes; semantic segmentation colours every pixel by class (both cats the same colour); instance segmentation separates the two cats but ignores the background; panoptic segmentation does both.
  • Semantic segmentation: every pixel gets a class (sky, grass, cat). Two touching cats merge into one "cat" region.
  • Instance segmentation: each countable object gets its own mask (cat #1, cat #2). Background is usually ignored.
  • Panoptic segmentation: both at once. Countable "things" (cats, cars, people) get separate instances, and uncountable "stuff" (sky, road, grass) gets a class.

How does a network produce a label for every pixel? It has to know two things that pull in opposite directions: what an area is, which needs a wide view of context, and exactly where its edges are, which needs fine detail. Classification CNNs throw away detail as they shrink the image. Segmentation networks add a path back up to full resolution that brings the detail back.

Key idea Segmentation is classification of every pixel. The standard design is an encoder that shrinks the image to understand it, a decoder that enlarges it back to full size, and skip connections that carry fine detail from encoder to decoder so edges come out sharp.

How it works

Per-pixel classification

For semantic segmentation with KK classes, the network outputs a tensor of shape (K,H,W)(K, H, W): one score per class at every pixel. A softmax over the KK scores at each pixel gives probabilities, and the prediction is the highest one. Training uses the ordinary cross-entropy loss, averaged over all pixels. A 512 × 512 image therefore provides 262,144 labelled examples at once, which is one reason segmentation can be trained on surprisingly few images.

Fully convolutional networks

The first deep approach, the fully convolutional network (FCN, 2014), took a classification CNN and replaced its final fully connected layers with convolutions. The network then outputs a coarse grid of class scores (say 1/32 of the input size) instead of one vector, and the grid is upsampled to full size. The masks were blobby, because the detail had been pooled away.

U-Net: encoder, decoder and skips

U-Net (2015), designed for microscope images of cells, fixed this with a symmetric encoder–decoder architecture:

64 channels256 × 256 64 channels256 × 256 128 channels128 × 128 128 channels128 × 128 256 channels64 × 64 256 channels64 × 64 512 channels32 × 32 512 channels32 × 32 1024 channels16 × 16 image3 × 256× 256maskK × 256× 2561×1Encodershrink: what is it?Decodergrow back: where exactly?skip connections: copyfine detail across, thenconcatenatemax pool ↓2up-conv ↑2bottleneck
Fig. 2 U-Net. The encoder halves the resolution and doubles the channels at each step. The decoder reverses this. Skip connections copy each encoder level's detailed feature maps across to the matching decoder level, where they are concatenated.
  • The encoder (left) is a normal CNN: convolutions and max-pooling. At each level the resolution halves and the number of channels doubles. Deep levels know what is in the image but have lost where, precisely.
  • The decoder (right) climbs back up. Each step doubles the resolution with a transposed convolution (an "up-convolution"), a learned upsampling that spreads each input value over a larger output patch.
  • The skip connections copy each encoder level's feature map across to the decoder level of the same size and concatenate them. Now the decoder has both deep semantic features and shallow, sharp edge features at every scale.

The U-Net paper trained on just 30 annotated images, with heavy elastic-distortion augmentation. U-Net and its descendants are still the default in medical imaging. One self-configuring version, nnU-Net, has won many medical segmentation challenges. U-Nets are also the denoising networks inside diffusion image generators.

The DeepLab family took another route to wide context without losing resolution: atrous (dilated) convolutions, which space a filter's taps apart so a 3 × 3 filter covers a wider area, plus pooling at several scales in parallel.

Instance segmentation: Mask R-CNN

Mask R-CNN (2017) extends the two-stage Faster R-CNN detector. For each detected box, a small extra branch predicts a 28 × 28 binary mask of which pixels inside the box belong to the object. The mask is then resized to the box. One improvement mattered a lot. RoIAlign samples features at exact (fractional) positions instead of rounding box coordinates to the feature grid, and that rounding had misaligned masks by several pixels. Separating instances comes for free, because each detection gets its own mask.

Later, query-based models such as Mask2Former (2021) handled semantic, instance and panoptic segmentation with one Transformer architecture, much like DETR does for boxes.

Segment Anything: promptable segmentation

Meta's Segment Anything Model (SAM, 2023) changed the task itself. Instead of fixed classes, SAM does promptable segmentation: you give it a prompt, such as a click on a point, a rough box, or a few clicks marking inside and outside, and it returns a mask of the thing you indicated, whatever it is. It never names the object. It just outlines it.

SAM has three parts. A large vision Transformer encodes the image once. A light prompt encoder embeds the clicks or box. A small mask decoder combines the two in a few milliseconds, so you can click interactively. Because one click is ambiguous (a click on a shirt could mean the shirt or the whole person), it returns three candidate masks with a predicted quality score for each. It was trained on SA-1B: 11 million images with 1.1 billion masks, most of them produced by the model itself in a loop with human annotators. SAM 2 (2024) extended this to video, tracking the selected object from frame to frame. SAM 3 (November 2025) added concept prompts: give it a short noun phrase such as "yellow school bus" (or an example box) and it finds, segments and tracks every matching object, not just one.

SAM is often combined with an open-vocabulary detector: the detector finds "all the dogs" as boxes, and SAM turns each box into a precise mask.

Measuring a mask

Two overlap scores are standard. Both compare a predicted mask PP with the true mask GG as sets of pixels:

IoU=∣P∩G∣∣P∪G∣,Dice=2 ∣P∩G∣∣P∣+∣G∣\text{IoU} = \frac{|P \cap G|}{|P \cup G|}, \qquad \text{Dice} = \frac{2\,|P \cap G|}{|P| + |G|}

Here ∣P∣|P| means the number of pixels in PP. IoU is exactly the box measure from Object Detection, applied to pixels. The Dice coefficient is closely related: Dice=2 IoU/(1+IoU)\text{Dice} = 2\,\text{IoU} / (1 + \text{IoU}), so it is always at least as large. For semantic segmentation you average IoU over classes to get mean IoU (mIoU), the headline number on benchmarks such as Cityscapes (street scenes) and ADE20K (150 classes).

Worked example. A true tumour mask has 400 pixels. The prediction has 500 pixels, of which 300 overlap the truth. IoU = 300/(400+500−300)=300/600=0.50300 / (400 + 500 - 300) = 300/600 = 0.50. Dice = 2×300/(400+500)=600/900≈0.672 \times 300 / (400 + 500) = 600/900 \approx 0.67. The same prediction looks better under Dice, so always say which one you report.

In medical imaging the object is often tiny compared with the background (a 400-pixel tumour in a 262,144-pixel slice). Plain cross-entropy is then dominated by easy background pixels. Training with a Dice loss (1−Dice1 - \text{Dice}, computed from probabilities), or a mix of Dice and cross-entropy, focuses on the overlap that actually matters.

In code

A tiny U-Net trained from scratch to find a faint disc in very noisy synthetic images. It runs on a CPU in under a minute.

import torch
import torch.nn as nn
import torch.nn.functional as F

def make_batch(n, size=32):
    """Noisy images, each with one bright disc; the mask marks the disc's pixels."""
    yy, xx = torch.meshgrid(torch.arange(size), torch.arange(size), indexing="ij")
    cx, cy = torch.randint(8, size - 8, (2, n, 1, 1))
    r = torch.randint(4, 8, (n, 1, 1))
    mask = ((xx - cx) ** 2 + (yy - cy) ** 2 <= r ** 2).float()
    img = 0.5 * mask + 0.3 * torch.randn(n, size, size)       # faint disc, lots of noise
    return img.unsqueeze(1), mask.unsqueeze(1)

def block(c_in, c_out):
    return nn.Sequential(nn.Conv2d(c_in, c_out, 3, padding=1), nn.ReLU(),
                         nn.Conv2d(c_out, c_out, 3, padding=1), nn.ReLU())

class TinyUNet(nn.Module):
    def __init__(self):
        super().__init__()
        self.down1, self.down2 = block(1, 16), block(16, 32)        # encoder
        self.up = nn.ConvTranspose2d(32, 16, 2, stride=2)            # upsample x2
        self.dec = block(32, 16)                                     # 16 skip + 16 up
        self.out = nn.Conv2d(16, 1, 1)                               # one logit per pixel
    def forward(self, x):
        s1 = self.down1(x)                       # (N, 16, 32, 32)  fine details
        s2 = self.down2(F.max_pool2d(s1, 2))     # (N, 32, 16, 16)  wider context
        u = self.up(s2)                          # (N, 16, 32, 32)
        return self.out(self.dec(torch.cat([u, s1], dim=1)))   # skip connection

def iou(pred, mask):
    inter = (pred * mask).sum()
    return (inter / (pred.sum() + mask.sum() - inter)).item()

torch.manual_seed(0)
model = TinyUNet()
opt = torch.optim.Adam(model.parameters(), lr=1e-3)
for step in range(301):
    x, m = make_batch(32)
    loss = F.binary_cross_entropy_with_logits(model(x), m)   # per-pixel classification
    opt.zero_grad(); loss.backward(); opt.step()
    if step % 100 == 0:
        x, m = make_batch(256)
        with torch.no_grad():
            pred = (model(x) > 0).float()
        print(f"step {step:3d}  loss {loss.item():.3f}  mask IoU {iou(pred, m):.3f}")

# step   0  loss 0.666  mask IoU 0.000
# step 100  loss 0.047  mask IoU 0.854
# step 200  loss 0.029  mask IoU 0.888
# step 300  loss 0.024  mask IoU 0.894

For comparison, the best possible single brightness threshold on these images (marking every pixel above 0.5) reaches an IoU of only about 0.34. The noise is too strong to judge pixels one at a time. The network wins by looking at each pixel's neighbourhood.

A pretrained semantic segmentation model from torchvision (21 PASCAL VOC classes, street.jpg is any photo):

import torch
from torchvision.io import read_image
from torchvision.models.segmentation import deeplabv3_resnet50, DeepLabV3_ResNet50_Weights

weights = DeepLabV3_ResNet50_Weights.DEFAULT
model = deeplabv3_resnet50(weights=weights).eval()
img = read_image("street.jpg")
with torch.no_grad():
    scores = model(weights.transforms()(img).unsqueeze(0))["out"]   # (1, 21, H, W)
mask = scores.argmax(dim=1)[0]                                       # class id per pixel
print({weights.meta["categories"][c]: int((mask == c).sum()) for c in mask.unique()})

And Segment Anything through Hugging Face Transformers: click a point, get masks.

import torch
from PIL import Image
from transformers import SamModel, SamProcessor

processor = SamProcessor.from_pretrained("facebook/sam-vit-base")
model = SamModel.from_pretrained("facebook/sam-vit-base")

image = Image.open("dog.jpg").convert("RGB")
inputs = processor(image, input_points=[[[450, 600]]], return_tensors="pt")   # one click (x, y)
with torch.no_grad():
    outputs = model(**inputs)
masks = processor.image_processor.post_process_masks(
    outputs.pred_masks, inputs["original_sizes"], inputs["reshaped_input_sizes"])
print(masks[0].shape, outputs.iou_scores)     # 3 candidate masks and their predicted quality

Common pitfalls

  • Resizing masks with the wrong interpolation. Resize label masks with nearest-neighbour interpolation. Bilinear interpolation invents in-between class ids: halfway between class 2 and class 4 is class 3, which is a real class.
  • Class imbalance. Small structures (thin vessels, small lesions, distant pedestrians) are a tiny fraction of pixels. Watch per-class IoU, and use Dice or focal losses or class weights.
  • Misaligned augmentation. Every geometric transform applied to the image must be applied identically to the mask. Colour changes must not be applied to the mask.
  • Fuzzy labels at edges. Different annotators draw boundaries differently, so a few pixels of disagreement at every edge are normal. It limits how high IoU can go, especially for small objects. Some datasets mark boundary pixels as "ignore".
  • The "ignore" label. Many datasets use a special value, such as 255 in PASCAL VOC, for unlabelled pixels. Pass it as ignore_index=255 to nn.CrossEntropyLoss, or the model learns it as a class.
  • Memory. Full-resolution outputs of shape (K,H,W)(K, H, W) for big images and many classes use a lot of GPU memory. Train on crops or tiles, and stitch predictions back together with overlap.

Watch out In medical segmentation, a good average Dice can hide clinically serious failures: a small missed metastasis barely moves the average. Report per-case results, look at the worst cases, and check that the patients in your test set were not also in training.

Where it leads

  • Vision Transformers are the encoders of SAM and of most modern segmentation models.
  • Video Understanding extends segmentation through time (video object segmentation, SAM 2).
  • Diffusion models use U-Nets as their denoisers, and image editors use segmentation masks for inpainting.
  • Multimodal LLMs are starting to output masks directly from text instructions.
  • Document AI segments pages into text blocks, tables and figures.

A bit of history

Before deep learning, segmentation meant grouping pixels by colour and texture: thresholds, watershed algorithms, graph cuts (around 2001) and conditional random fields that encouraged neighbouring pixels to share labels. Datasets such as PASCAL VOC (from 2005) and later COCO (2014) and Cityscapes (2016) provided pixel-level labels at scale.

Long, Shelhamer and Darrell's FCN (published 2014, presented 2015) made segmentation end to end with CNNs. Ronneberger, Fischer and Brox's U-Net appeared the same year for biomedical images. It became one of the most cited papers in the field and later the backbone of image generators. DeepLab (2015–2018) introduced atrous convolution, and Mask R-CNN (2017) made instance segmentation routine. Kirillov and colleagues defined panoptic segmentation in 2018. Meta's Segment Anything (2023), SAM 2 (2024) and SAM 3 (2025) shifted the field from fixed class lists to promptable, general-purpose segmentation.

Try it

  1. Compute IoU and Dice by hand for a true mask of 100 pixels and a prediction of 80 pixels that lies entirely inside it. Check that Dice=2 IoU/(1+IoU)\text{Dice} = 2\,\text{IoU}/(1+\text{IoU}).
  2. Remove the skip connection from TinyUNet (decode from u alone, and change block(32, 16) to block(16, 16)). Train again. How does the mask IoU change, and why?
  3. Harder: replace the loss with a soft Dice loss, 1 - (2 * (p * m).sum() + 1) / (p.sum() + m.sum() + 1) where p = torch.sigmoid(model(x)), and compare the IoU after 300 steps.

Hint for 1: the overlap is 80 and the union is 100, so IoU = 0.8 and Dice = 160/180 ≈ 0.89.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. A self-driving team needs every road, sky and pavement pixel labelled, and also each car and pedestrian as a separate object. Which task is this?

  2. A true tumour mask has 400 pixels. The prediction has 500 pixels, 300 of which overlap the truth. What are IoU and Dice?

  3. In a U-Net, what do the skip connections from encoder to decoder add?

  4. You resize your label masks with bilinear interpolation. What goes wrong?

  5. You click once on a person's shirt in Segment Anything. Why does it return three masks?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Paper

Fully Convolutional Networks for Semantic Segmentation

Long, Shelhamer & Darrell · 2014 · Advanced · Free

Turned classification CNNs into pixel-wise predictors by replacing fully connected layers with convolutions and upsampling, founding deep semantic segmentation.

Paper

Mask R-CNN

He, Gkioxari, Dollár & Girshick · 2017 · Advanced · Free

Adds a small mask-predicting branch to Faster R-CNN, giving instance segmentation with a clean, widely copied design.

Paper

Segment Anything

Kirillov et al. · 2023 · Advanced · Free

A promptable segmentation model and a dataset of over 1 billion masks.

Paper

SAM 2: Segment Anything in Images and Videos

Ravi et al. (Meta AI) · 2024 · Intermediate · Free

Extends Segment Anything to video with a memory of earlier frames, so a click on one frame segments and tracks the object through the clip.

Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/vision/segmentation.md