Sub topic 2
Representing segmentation: label maps and mask stacks
This chapter assumes you know basic Python and NumPy, and that you know what a convolutional network outputs for classification and detection. Every later chapter on models, losses, and metrics depends on how a segmentation result is stored. A model, a metric, or a dataset loader can be correct and still give wrong numbers if it reads one format as another.
Three ways to store a segmentation
A segmentation result is a set of regions, each with a class. There are three common array layouts for it.
| Format | Shape | Typical dtype | Used for |
|---|---|---|---|
| Label map | (H, W) | uint8 or int64 | Semantic segmentation |
| Mask stack | (N, H, W) | bool or float | Instance segmentation |
| Panoptic ID map | (H, W) | int32 | Panoptic segmentation |
Label maps
A label map is a 2D integer array the same size as the image. The value at [y, x] is the class of that pixel. It is the natural output of semantic segmentation. Because each pixel holds exactly one value, classes can never overlap. This is the layout's strength and its limit: two touching people both read as "person" and cannot be told apart.
Datasets usually reserve one value for pixels that should not count. Pascal VOC and Cityscapes training IDs use 255 as the ignore index. Pixels marked 255 mark object boundaries or unlabeled regions. The loss and the metric must both skip them. The confusion-matrix code in the IoU chapter does this by dropping any target outside [0, num_classes).
Models do not output label maps directly. A network outputs a score tensor of shape (C, H, W), one score per class per pixel. You get the label map with argmax over the class axis:
import numpy as np
scores = np.random.rand(3, 4, 5) # (C, H, W) class scores
label_map = scores.argmax(axis=0) # (H, W), values in 0..2
print(label_map.shape, label_map.dtype)Mask stacks
A mask stack holds one binary mask per object. Entry masks[i] is an (H, W) boolean array that is true where object i is. A parallel list classes[i] (and usually scores[i]) gives each object's class and confidence. Mask R-CNN returns this form: one mask per detection. The masks may overlap, since each is independent of the others. Two detections of the same person produce two masks covering the same pixels.
A stack with N objects costs N times the memory of a single map. A 100-instance prediction on a 1024 × 1024 image is 100 MB as booleans, since NumPy stores one byte per bool. This is why annotation files do not store raw stacks. They store polygons or run-length encoding (RLE), which lists alternating run lengths of background and foreground pixels. RLE is compact because masks are mostly large uniform regions.
Converting between layouts
A label map converts to a stack by comparing against each class value. A stack converts back by painting each mask with its class. The round trip is lossless only when masks do not overlap.
import numpy as np
IGNORE = 255
label_map = np.array([
[0, 0, 1, 1],
[0, 2, 2, 1],
[255, 2, 2, 1],
], dtype=np.uint8)
class_ids = [int(c) for c in np.unique(label_map) if c != IGNORE]
stack = np.stack([label_map == c for c in class_ids]) # (3, 3, 4) bool
print(class_ids, stack.shape)
restored = np.full(label_map.shape, IGNORE, dtype=np.uint8)
for c, mask in zip(class_ids, stack):
restored[mask] = c
assert (restored == label_map).all()Pixels not claimed by any mask keep the ignore value. That is how the ignore region survives the round trip.
Panoptic ID maps
Panoptic segmentation needs both a class and an instance identity per pixel, with no overlap. A common encoding stores one integer per pixel: class_id * divisor + instance_number. With a divisor of 1000, the value 1001 means class 1, instance 1. Stuff classes such as road have no instances, so they use instance number 0 and appear as class_id * 1000. Value 0 is void, so this scheme needs class IDs starting at 1.
COCO's panoptic files use a different packing. They store segment IDs in the three channels of a PNG, as R + 256·G + 256²·B, and list each segment's class in a separate JSON file. The idea is the same: one non-overlapping map plus a lookup from ID to class.
The function below converts a stack to an ID map. Where masks overlap, the earlier mask wins.
import numpy as np
def stack_to_panoptic_ids(masks, classes, divisor=1000):
# masks: (N, H, W) bool; classes: length-N list of class ids >= 1
ids = np.zeros(masks.shape[1:], dtype=np.int32) # 0 = void
for k, (mask, c) in enumerate(zip(masks, classes), start=1):
ids[mask & (ids == 0)] = c * divisor + k
return ids
masks = np.zeros((2, 4, 4), dtype=bool)
masks[0, :, :3] = True # object 1 covers columns 0-2
masks[1, :, 2:] = True # object 2 covers columns 2-3, overlapping column 2
classes = [1, 2]
print("overlapping pixels:", int((masks.sum(axis=0) > 1).sum())) # 4
ids = stack_to_panoptic_ids(masks, classes)
print(ids[0]) # [1001 1001 1001 2002]
print("class:", ids[0] // 1000, "instance:", ids[0] % 1000)The masks.sum(axis=0) > 1 check counts pixels claimed more than once. Run it before any conversion that assumes non-overlap. The next chapters return to how a model's overlapping instances are resolved.
Resizing and dtype
Masks need different resizing rules than images. Interpolating a label map with bilinear filtering averages class IDs. Classes 1 and 3 blend into 2, a class that may not be there at all. Use nearest-neighbor interpolation for any integer label map or ID map. For model scores, you can interpolate the (C, H, W) logits bilinearly and then take the argmax. This is the usual way to upsample a network output to the input size.
Also watch the dtype:
uint8holds class IDs up to 255, which collides with the ignore index if you have 256 classes. Keep 255 reserved.- Cross-entropy losses in PyTorch expect targets as
int64(long). Auint8or float target raises an error or silently misbehaves. - Saving a label map as JPEG corrupts the values through lossy compression. Use PNG, which is lossless.
- Panoptic IDs can exceed 255, so they need
int32or a multi-channel PNG, never a singleuint8channel.
Choosing a layout
Use a label map when classes never need to be separated by object and you want the smallest, fastest representation. Use a mask stack when you need individual objects or overlapping predictions, for example to count items or to compute mask AP. Use a panoptic ID map when you need a single consistent scene description with classes and instances together.
Exercise
A model predicts three instance masks of a "car" class (class ID 3) on a 100 × 100 image. Mask A and mask B overlap on 200 pixels. Using stack_to_panoptic_ids with divisor 1000, what ID value do the overlapping pixels receive if A comes before B in the list, and how many pixels of B remain labeled B?
Show answer
The overlapping pixels get A's ID, 3001, because the function only writes where ids == 0 and A is painted first. B keeps its own area minus the 200 overlapping pixels. If B has 500 pixels in total, 300 receive ID 3002. Reordering the list changes the result, which is why instance results are usually sorted by confidence first.