Sub topic 16
Datasets and annotation formats
This chapter assumes you know what label maps and mask stacks are, and that you have met IoU, mask AP, and PQ. Here you will see how real datasets store those masks on disk, how to decode them, and where the formats cause silent errors.
Why the format matters
A segmentation model trains on tensors, but datasets ship as PNG files, JSON files, or both. Each format makes a different trade-off between file size, editing convenience, and the task it can express. Most segmentation bugs in practice are not model bugs. They come from reading a label file the wrong way: wrong class mapping, an ignored value treated as a class, or masks resized with smoothing.
Common datasets at a glance
| Dataset | Task | Classes | Label storage |
|---|---|---|---|
| Pascal VOC | Semantic, instance | 20 plus background | Palette PNG, 255 marks void |
| Cityscapes | Semantic, instance, panoptic | 19 evaluated | PNGs, plus polygon JSON |
| ADE20K (SceneParsing) | Semantic | 150 | PNG, one class per pixel |
| COCO instance | Instance | 80 things | JSON with polygons or RLE |
| COCO panoptic | Panoptic | 133 (80 things, 53 stuff) | PNG plus JSON segment list |
| LVIS | Instance | About 1,200, long-tailed | COCO-style JSON |
The class counts are the ones normally used for training and evaluation. Many datasets define more raw labels than they evaluate.
Three families of formats
Per-pixel PNG label maps
Semantic datasets such as VOC, ADE20K, and Cityscapes store one PNG per image. Each pixel value is a class index. The PNG must be lossless, so never re-encode labels as JPEG. Compression artifacts would create class ids that do not exist.
Two details matter here:
- VOC uses a palette PNG. The file looks colored in a viewer, but the stored values are small integers. Read it with a library that preserves indices, such as Pillow without converting to RGB.
- Value 255 usually means "ignore". In VOC it marks object boundaries and unlabeled regions. Your loss must skip these pixels, and your confusion matrix must skip them too, as the
confusion_matrixfunction earlier in this tutorial does.
COCO-style JSON
COCO instance annotations are one JSON file with three lists: images, annotations, and categories. Each annotation holds one object instance:
segmentation: either a list of polygons (each a flat list[x1, y1, x2, y2, ...]) or a run-length encoding (RLE).bbox:[x, y, width, height], not corner coordinates.area: the mask area in pixels.iscrowd: 0 for a single object, 1 for a crowd region.
A crowd region is a group of objects too dense to separate, such as a mass of people. It uses RLE instead of polygons. Evaluation tools treat it specially, because predictions that fall inside a crowd region are not counted as false positives.
RLE stores a mask as alternating run lengths of 0s and 1s, always starting with a run of zeros. COCO flattens the mask in column-major order, which surprises people who expect row-major. The compressed form that pycocotools produces is a string, while the uncompressed form is a plain list of integers.
ID maps with a segment list
Panoptic data needs both a class and an instance for every pixel, so it stores a segment id per pixel plus a table that maps ids to classes. Two conventions are common:
- COCO panoptic stores an RGB PNG. The segment id is
R + 256*G + 256*256*B. A separate JSON entry per image listssegments_info, withid,category_id,iscrowd,area, andbboxfor each segment. Pixels with id 0 are void. - Cityscapes
instanceIdsPNGs storeclass_id * 1000 + instance_numberfor thing pixels. Stuff pixels keep the plain class id, which is below 1000.
Decoding the formats
The following runnable NumPy code decodes an uncompressed RLE, converts an RGB panoptic image to ids, and splits Cityscapes-style ids.
import numpy as np
def decode_rle(counts, size):
# size is [height, width]; counts alternate 0-runs and 1-runs, starting with 0.
h, w = size
flat = np.zeros(h * w, dtype=np.uint8)
pos, value = 0, 0
for run in counts:
flat[pos:pos + run] = value
pos += run
value ^= 1
return flat.reshape((h, w), order="F").astype(bool) # column-major, as in COCO
def rgb_to_id(rgb):
rgb = rgb.astype(np.uint32) # avoid uint8 overflow when multiplying
return rgb[..., 0] + 256 * rgb[..., 1] + 256 * 256 * rgb[..., 2]
def split_cityscapes_id(ids):
ids = np.asarray(ids)
is_instance = ids >= 1000
class_id = np.where(is_instance, ids // 1000, ids)
instance_id = np.where(is_instance, ids % 1000, 0)
return class_id, instance_id
mask = decode_rle([1, 2, 3], [2, 3])
print(mask.astype(int))
rgb = np.zeros((1, 3, 3), dtype=np.uint8)
rgb[0, 1] = (5, 0, 0)
rgb[0, 2] = (0, 1, 0)
print(rgb_to_id(rgb))
print(split_cityscapes_id([7, 26000, 26001]))The first print shows a 2 by 3 mask with ones at row 1, column 0 and row 0, column 1. The second prints [[ 0 5 256]]. The third prints class ids [7, 26, 26] and instance ids [0, 0, 1].
The astype(np.uint32) call in rgb_to_id is not optional. If you multiply a uint8 array by 256, the values wrap around and every id above 255 comes out wrong.
Class remapping and ignore labels
Raw dataset ids are often not the ids you train on. Cityscapes defines about 30 raw labels, such as labelIds, but evaluates 19. The official trainIds mapping sends the other raw labels to 255. COCO category ids run from 1 to 90 with gaps, because only 80 are used, so a model with 80 outputs needs a lookup table from COCO id to a contiguous index.
Build the lookup once, apply it as an array index, and keep 255 as the single ignore value. Then check that the set of values in your remapped labels is a subset of {0, ..., C-1, 255}. This one assertion catches many data bugs before training starts.
Practical rules
- Resize labels with nearest-neighbor interpolation. Bilinear resizing creates fractional values between two classes, which become invalid class ids after rounding.
- Apply geometric augmentation to image and label together. Flips, crops, and scales must use the same random parameters. Pad labels with 255, not 0, so padding is not treated as background.
- Treat crowd regions deliberately. Either skip
iscrowd=1annotations when training an instance model, or keep them as ignore regions. - Respect the official splits. Cityscapes test labels are held back for a server, so you evaluate on validation. Frames from the same city or video are highly correlated, so random splits across frames leak information.
- Know what annotators did. Boundaries are imprecise. Polygon annotations are coarser than per-pixel painting. Scores differ between datasets partly because of labeling style, not only model quality.
Summary of decisions
Choose per-pixel PNGs when you only need semantic labels and want simple loading. Choose COCO JSON when you need separate instances and object-level metadata. Choose a panoptic PNG plus segment list when you need a non-overlapping result with both classes and instances. Converting between them is possible, but conversion from semantic to instance labels needs extra information, because a semantic map cannot say where one object ends and the next begins.
Exercise
A COCO panoptic PNG has a pixel with RGB value (10, 2, 0). What is its segment id, and where do you find its class?
Show answer
The id is 10 + 2562 + 655360 = 522. Look up the entry with id 522 in that image's segments_info in the panoptic JSON, and read its category_id.
Exercise
Your semantic model trains without errors but IoU stays near zero for all classes. The label PNGs were resized from 2048x1024 to 1024x512 with bilinear interpolation, and 255 is the ignore value. Name two things that can go wrong and the fix.
Show answer
Bilinear interpolation blends neighboring values, producing class ids that belong to neither neighbor, and it also blends 255 into valid classes near ignored regions, creating wrong ids and invalid targets. Resize labels with nearest-neighbor interpolation, then assert that the unique values are within the valid class range or 255.