Sub topic 2
Representing Segmentation: Label Maps and Mask Stacks
Assume you know basic Python, NumPy, convolutional neural networks, and object detection. In this chapter, you will represent segmentation annotations and predictions in three useful forms: label maps, instance ID maps, and binary mask stacks.
Label maps
A label map is a two-dimensional integer array with one value per pixel. The array has height and width, but no color channels:
L \in \mathbb{Z}^{H \times W}Each integer refers to a class. For example, 0 might mean background, 1 road, and 2 car. A semantic segmentation result uses this form because every pixel receives one class label.
An ignored or unknown pixel needs a reserved value, such as 255 or -1. Evaluation code must exclude that value instead of treating it as a real class.
An instance ID map has the same shape, but its values identify individual objects. An ID of 3 means “object 3,” regardless of its class. You normally store the object class separately:
| Representation | Shape | Meaning |
|---|---|---|
| Semantic label map | `(H, W)` | Class at each pixel |
| Instance ID map | `(H, W)` | Object identity at each pixel |
| Binary mask stack | `(N, H, W)` | One mask for each object |
Binary mask stacks
A binary mask is a two-dimensional Boolean array. True marks pixels belonging to an object, and False marks all other pixels. A stack of N masks has shape (N, H, W).
The corresponding arrays usually include:
masks: Boolean masks with shape(N, H, W)labels: class IDs with shape(N,)scores: confidence values with shape(N,)
Unlike a label map, a mask stack can contain overlapping objects. This is useful for instance segmentation because two predicted objects can claim the same pixel before post-processing resolves the overlap.
import numpy as np
semantic = np.array([
[0, 1, 1, 0],
[0, 2, 2, 0],
[0, 2, 2, 0],
])
instance_ids = np.array([
[0, 1, 1, 0],
[0, 2, 2, 0],
[0, 2, 2, 0],
])
masks = np.stack([
instance_ids == 1,
instance_ids == 2,
])
labels = np.array([1, 2]) # class for each mask
scores = np.array([0.96, 0.88])
print("semantic shape:", semantic.shape)
print("mask shape:", masks.shape)
print("object classes:", labels)
print("foreground pixels in object 2:", masks[1].sum())The mask index connects the arrays: masks[1], labels[1], and scores[1] describe the same detected object. Keep this alignment when filtering or sorting detections.
Practical checks
Before training or evaluation, verify that:
- Every map has the expected height and width.
- Class IDs fit the configured number of classes.
- Ignore values are handled consistently.
- Mask, label, and score arrays have the same first dimension.
- Boolean masks contain only
TrueandFalse.
Exercise
If an image contains two cars, what should a semantic label map and an instance ID map store for those pixels?
Show answer
The semantic map stores the same car class ID for both cars. The instance map stores different IDs, such as 4 for the first car and 5 for the second.