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
- Builds on
- 19 concepts →
- Quiz
- 5 questions ↓
Read first
Object DetectionThis leads to
—The full path from zero — 19 concepts before this one
- What Is AI?
- Vectors
- Derivatives and Slopes
- Probability Basics
- How Machines Learn
- Partial Derivatives and Gradients
- Matrices and Matrix Multiplication
- Supervised, Unsupervised and Reinforcement Learning
- Gradient Descent
- Tensors and Shapes
- Supervised Learning
- Images as Data
- Linear Regression
- The Perceptron
- Logistic Regression
- Neural Networks
- Convolutional Neural Networks
- Image Classification
- Object Detection
- 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":
- 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 classes, the network outputs a tensor of shape : one score per class at every pixel. A softmax over the 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:
- 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 with the true mask as sets of pixels:
Here means the number of pixels in . IoU is exactly the box measure from Object Detection, applied to pixels. The Dice coefficient is closely related: , 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 = . Dice = . 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 (, 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=255tonn.CrossEntropyLoss, or the model learns it as a class. - Memory. Full-resolution outputs of shape 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
- 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 .
- Remove the skip connection from
TinyUNet(decode fromualone, and changeblock(32, 16)toblock(16, 16)). Train again. How does the mask IoU change, and why?- Harder: replace the loss with a soft Dice loss,
1 - (2 * (p * m).sum() + 1) / (p.sum() + m.sum() + 1)wherep = 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.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
Stanford CS231n: Deep Learning for Computer Vision
Famous course notes on neural nets, backprop, CNNs and training, written very clearly.
U-Net: Convolutional Networks for Biomedical Image Segmentation
The U-shaped encoder–decoder that became the backbone of segmentation and diffusion models.
Fully Convolutional Networks for Semantic Segmentation
Turned classification CNNs into pixel-wise predictors by replacing fully connected layers with convolutions and upsampling, founding deep semantic segmentation.
Mask R-CNN
Adds a small mask-predicting branch to Faster R-CNN, giving instance segmentation with a clean, widely copied design.
Segment Anything
A promptable segmentation model and a dataset of over 1 billion masks.
SAM 2: Segment Anything in Images and Videos
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.
TorchVision Object Detection Finetuning Tutorial
Fine-tunes a pretrained Mask R-CNN on a small pedestrian dataset, covering the dataset format for boxes and masks, training and evaluation.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/vision/segmentation.md