Sub topic 1
What Image Segmentation Is and Why It Matters
Image segmentation assigns a label to every pixel in an image. A classifier says "this photo contains a dog." A detector says "there is a dog inside this box." A segmentation model says "these exact pixels are the dog, and these other pixels are grass." This chapter defines the task, separates its three main variants, and gives you the vocabulary the rest of the tutorial builds on.
Prerequisites
This chapter assumes you have:
- Basic Python and NumPy, including array shapes and boolean indexing.
- Convolutional neural networks and image classification, at the level of knowing what a feature map is.
- Object detection basics: bounding boxes and confidence scores.
- Gradient-based training and loss functions.
You do not need to know any segmentation architecture yet. Later chapters cover those.
From classification to pixels
Vision tasks differ in how fine-grained their output is.
| Task | Output | Granularity |
|---|---|---|
| Image classification | One label per image | Whole image |
| Object detection | A box, class, and score per object | Rectangle |
| Semantic segmentation | One class per pixel | Pixel |
| Instance segmentation | One mask per object | Pixel, per object |
| Panoptic segmentation | A class and instance ID per pixel | Pixel, whole scene |
A bounding box is a coarse description. A box around a diagonal pole contains mostly background. A box around a person holding a bicycle overlaps with the bicycle's box. A mask removes this ambiguity because it says which pixels belong to which thing.
Why it matters
Many applications need shape and extent, not only location:
- Autonomous driving. The drivable surface, lane markings, and sidewalks have no useful box. Cars and pedestrians need to be separated individually.
- Medical imaging. Tumor volume, organ boundaries, and cell counts are measured from masks. A few pixels of error can change a clinical measurement.
- Photo and video editing. Background removal and portrait effects need clean object boundaries.
- Remote sensing. Land cover, roads, and building footprints are area quantities.
- Robotics. A gripper needs the shape of the object, not a rectangle around it.
In each case the quantity of interest (area, boundary, count, free space) is computed directly from the mask.
The three variants
The three variants differ in what they label and in whether they separate individual objects.
Semantic segmentation
Every pixel gets exactly one class from a fixed list, such as road, car, person, or sky. Two adjacent cars receive the same label and merge into one region. The output is a single 2D array of class IDs.
Use it when you care about what each region is and not how many objects there are. Land cover mapping and drivable-area detection are typical.
Instance segmentation
Each detected object gets its own mask, class, and confidence score. Two adjacent cars become two separate masks. Pixels that belong to no object, such as sky or road, are usually left unlabeled. Masks from different instances may overlap in the raw output of many models.
Use it when you need to count, track, or measure individual objects. Cell counting and picking items from a bin are typical.
Panoptic segmentation
Panoptic segmentation combines both. Every pixel receives a class, and pixels that belong to countable objects also receive an instance ID. Masks never overlap, and every pixel is covered (or marked void if it is ignored in the annotation).
Use it when you need full scene understanding, such as in a driving stack that must know both the road layout and each separate vehicle.
Things and stuff
The split between the variants follows a split in the kind of content in an image.
- Things are countable objects with a defined shape: people, cars, dogs. Instances make sense for them.
- Stuff is amorphous or uncountable regions: sky, road, grass, water. Asking "which sky is this?" has no meaningful answer.
Semantic segmentation handles both but cannot separate things from each other. Instance segmentation handles only things. Panoptic segmentation handles both and separates the things. A later chapter treats this distinction in more detail.
Seeing the difference in data
Here is a tiny 4x6 image represented as arrays. Class IDs are 0 = road (stuff), 1 = car (thing). The two cars touch in the middle.
import numpy as np
# Semantic output: one class ID per pixel. The two cars merge into one region.
semantic = np.array([
[0, 0, 0, 0, 0, 0],
[0, 1, 1, 1, 1, 0],
[0, 1, 1, 1, 1, 0],
[0, 0, 0, 0, 0, 0],
])
# Instance output: a stack of boolean masks, one per object.
car_a = np.zeros((4, 6), dtype=bool)
car_b = np.zeros((4, 6), dtype=bool)
car_a[1:3, 1:3] = True
car_b[1:3, 3:5] = True
instances = np.stack([car_a, car_b]) # shape (N, H, W)
# Panoptic output: class map plus an instance ID map (0 = no instance).
panoptic_class = semantic.copy()
panoptic_instance = np.zeros_like(semantic)
panoptic_instance[car_a] = 1
panoptic_instance[car_b] = 2
print("semantic cars as one region:", (semantic == 1).sum(), "pixels")
print("instance masks:", instances.shape[0], "objects,", instances.sum(axis=(1, 2)), "pixels each")
print("panoptic instance IDs:\n", panoptic_instance)The semantic array cannot tell you there are two cars. The mask stack can. The panoptic pair of arrays keeps both facts and guarantees that no pixel belongs to two objects.
How models produce pixel outputs
A classification network shrinks spatial resolution until a single vector remains. A segmentation network must recover a prediction at full resolution. The main strategies, each covered in later chapters, are:
- Dense per-pixel prediction. An encoder extracts features, and a decoder upsamples them to a class score map (fully convolutional and encoder-decoder networks).
- Detect, then segment. A detector finds objects, and a small head predicts a mask inside each box (Mask R-CNN).
- Mask classification. The model predicts a set of masks and assigns a class to each mask (MaskFormer and Mask2Former). This one design handles all three variants.
The training signal is usually a per-pixel loss such as cross-entropy or Dice, computed against ground-truth masks.
How results are scored
Boxes are scored by overlap with ground-truth boxes. Masks are scored the same way, but with pixel sets. The core quantity is intersection over union (IoU): the number of pixels in both the prediction and the ground truth, divided by the number of pixels in either. Each variant builds a metric on top of it:
| Variant | Typical metric |
|---|---|
| Semantic | Mean IoU over classes (mIoU) |
| Instance | Mask average precision (mask AP) |
| Panoptic | Panoptic quality (PQ), split into SQ and RQ |
Accuracy per pixel alone is a poor measure. If 95% of an image is background, predicting all background scores 95% pixel accuracy and finds nothing.
Costs and limits
Segmentation is more demanding than detection in several ways.
- Annotation cost. Tracing a polygon around an object takes much longer than drawing a box. Panoptic labels require labeling every pixel in the image.
- Compute and memory. Outputs are full-resolution, so activations and losses scale with the pixel count. High-resolution inputs strain GPU memory.
- Boundary precision. Most error is at object edges, where a one-pixel shift matters little for IoU on large objects but a lot for small ones.
- Class imbalance. Small objects and rare classes cover few pixels, so a plain per-pixel loss can ignore them.
Choosing a variant
Start from the question your application asks.
- Do you need to know what is where, with no counting? Use semantic segmentation.
- Do you need to count, track, or measure individual objects, and can ignore the rest? Use instance segmentation.
- Do you need both the scene layout and individual objects in one consistent output? Use panoptic segmentation.
Panoptic segmentation is not simply "better." It needs more complete annotations and is evaluated by a stricter metric. If your task is only background removal for one object type, a simpler semantic or instance model is often cheaper and easier to train.
What comes next
The next chapters formalize the representations used here (label maps and mask stacks), define things and stuff precisely, and then develop each variant, its models, and its metrics in turn.
Exercise
A warehouse camera must report how many boxes are on a conveyor belt and the pixel area of each one. The belt itself does not matter. Which segmentation variant fits best, and why would semantic segmentation alone fall short?
Show answer
Instance segmentation fits best. It gives one mask per box, so you count the masks and sum the pixels in each. Semantic segmentation would label all box pixels with one class, and touching boxes would merge into one region, so you could neither count them reliably nor measure each box's area.
Exercise
A model predicts "background" for every pixel on an image where 96% of the pixels are background. What is its pixel accuracy, and why is mIoU a better measure here?
Show answer
Pixel accuracy is 96%. The IoU for the background class is also about 0.96, but the IoU for the object class is 0, because the model never predicts any object pixels. Averaging over classes gives an mIoU of about 0.48, which exposes the failure that pixel accuracy hides.