Sub topic 16
Datasets and Annotation Formats
Assume you know basic Python and NumPy, convolutional neural networks, object-detection boxes, and gradient-based training. This chapter focuses on how segmentation labels are stored and how those storage choices affect training and evaluation.
Match the annotation to the task
A segmentation dataset usually stores an image plus one or more target representations:
| Task | Typical target | Meaning |
|---|---|---|
| Semantic | Integer label map of shape `(H, W)` | Every pixel has a class ID |
| Instance | One record and mask per object | Each object has its own identity |
| Panoptic | ID map plus segment metadata | Every pixel belongs to one segment or void |
A semantic label map might use 0 for background, 1 for road, and 2 for car. Pixels with value 255 often mean “ignore.” The map must have the same height and width as the image after all preprocessing.
Instance annotations commonly use COCO-style JSON. Each object record contains a category ID, bounding box, area, and a segmentation. The segmentation can be a polygon, which lists boundary coordinates, or run-length encoding (RLE), which stores mask runs compactly. Polygons are convenient for simple shapes but may lose detail along complex boundaries.
Panoptic datasets usually separate the pixel map from its metadata. The map stores a segment ID at each pixel. A JSON record then maps each segment ID to a category, area, and iscrowd flag. A segment ID is not necessarily the same as a category ID. Confusing these IDs silently corrupts training.
Validate geometry and IDs
Images, masks, and augmentations must stay aligned. If you rotate or crop an image, apply the same geometric operation to every mask. Use nearest-neighbor interpolation for discrete label maps. Bilinear interpolation can create invalid class IDs such as 1.4.
import numpy as np
num_classes = 3
label_map = np.array([[0, 1, 2], [2, 255, 1]], dtype=np.int64)
valid = (label_map == 255) | ((label_map >= 0) & (label_map < num_classes))
if not valid.all():
raise ValueError("Found an invalid class ID")
valid_pixels = label_map[label_map != 255]
print("shape:", label_map.shape)
print("classes present:", np.unique(valid_pixels).tolist())Keep training, validation, and test images separated by scene, video, patient, or object when those sources are related. Splitting neighboring frames randomly can leak nearly identical content into validation and produce an inflated score.
Exercise
Why should a semantic label map use nearest-neighbor resizing instead of bilinear resizing?
Show answer
Class IDs are discrete values. Bilinear resizing mixes neighboring IDs and can create values that do not represent any valid class.