TExcelTAD
Home › Computer Vision: Images to Detection, Segmentation & Tracking › Masks, Polygons and Run-Length Encoding

Masks, Polygons and Run-Length Encoding

A box says where an object is; a mask says which pixels it is made of. Segmentation datasets store that information in three interchangeable forms: a binary mask (an H×WH \times W array of 0 and 1), a polygon (the outline as a list of vertices), and run-length encoding (RLE, the mask written as lengths of runs of 0s and 1s). Annotation tools produce polygons, training code wants masks, and COCO files store crowds and model outputs as RLE. This lesson converts between all three from scratch, checks every conversion with a round trip, and ends with the two file layouts you will meet most: PNG label maps and YOLO segmentation text files.

Three representations of one shape

mask, 4 rows x 5 columns RLE reads columns,top to bottom polygon: 6 vertices outline only,any resolution RLE counts[4, 3, 1, 2, 10] 4 zeros: all of column 0,then 3 ones in column 1 ... area = 3 + 2 = 5 pixels (sum of every second count)
Form Size Good at Weak at
binary mask H⋅WH \cdot W values per object training, IoU, any pixel operation storage: one 1920 x 1080 mask is 2 million values
polygon 2 numbers per vertex annotation (click the outline), resolution-free, small holes need extra rings; crowds and hair are hard to outline
RLE 1 number per run storage of large or complex masks, crowds, model output must be decoded before use; order rules (column-major)

All three can describe the same object, but they are not always equivalent: a polygon drawn with sub-pixel vertices rasterises to a mask that depends on the rasteriser's rule for edge pixels, and a mask traced back to a polygon gives a staircase outline. So conversions are checked with mask IoU, the IoU of two pixel sets (segmentation metrics uses the same quantity):

IoU(M1,M2)=∣M1∩M2∣∣M1∪M2∣\text{IoU}(M_1, M_2) = \frac{\lvert M_1 \cap M_2 \rvert}{\lvert M_1 \cup M_2 \rvert}

Polygon to mask and back

cv2.fillPoly rasterises a polygon (vertices as an int32 array of (x, y) points, x first). The area of a polygon with vertices (xi,yi)(x_i, y_i) is given by the shoelace formula, and it is not the same as the number of pixels the rasteriser fills:

A=12∣∑i=0n−1(xi yi+1−xi+1 yi)∣(indices modulo n)A = \frac{1}{2} \left\lvert \sum_{i=0}^{n-1} \left( x_i\, y_{i+1} - x_{i+1}\, y_i \right) \right\rvert \qquad (\text{indices modulo } n)

The other direction, mask to polygon, is cv2.findContours: it traces the boundary pixels of each connected region. With CHAIN_APPROX_SIMPLE it keeps only the end points of straight runs, and cv2.approxPolyDP simplifies further, dropping vertices closer than epsilon pixels to the simplified outline (the Douglas-Peucker algorithm).

python · try it yourself
import numpy as np, cv2

def mask_iou(a, b):
    return (a & b).sum() / (a | b).sum()

def shoelace(p):
    x, y = p[:, 0].astype(float), p[:, 1].astype(float)
    return 0.5 * abs(np.dot(x, np.roll(y, -1)) - np.dot(np.roll(x, -1), y))

H, W = 48, 64
tri = np.array([[32, 4], [6, 42], [58, 42]], np.int32)                 # (x, y) vertices
mask = np.zeros((H, W), np.uint8)
cv2.fillPoly(mask, [tri], 1)
print("triangle: shoelace area", shoelace(tri), "| pixels filled", int(mask.sum()))

disc = np.zeros((H, W), np.uint8); cv2.circle(disc, (30, 24), 16, 1, -1)
for name, m in [("triangle", mask), ("disc", disc)]:
    for approx, eps in [("NONE", None), ("SIMPLE", None), ("SIMPLE + approxPolyDP 1.0", 1.0)]:
        mode = cv2.CHAIN_APPROX_NONE if approx == "NONE" else cv2.CHAIN_APPROX_SIMPLE
        contours, _ = cv2.findContours(m, cv2.RETR_EXTERNAL, mode)
        c = contours[0]
        if eps:
            c = cv2.approxPolyDP(c, eps, True)
        back = np.zeros_like(m); cv2.fillPoly(back, [c], 1)
        print(f"{name:8s} {approx:26s} vertices {len(c):3d} | mask IoU after round trip {mask_iou(m > 0, back > 0):.3f}")
triangle: shoelace area 988.0 | pixels filled 1053
triangle NONE                       vertices 128 | mask IoU after round trip 1.000
triangle SIMPLE                     vertices  51 | mask IoU after round trip 1.000
triangle SIMPLE + approxPolyDP 1.0  vertices   3 | mask IoU after round trip 1.000
disc     NONE                       vertices  88 | mask IoU after round trip 1.000
disc     SIMPLE                     vertices  52 | mask IoU after round trip 1.000
disc     SIMPLE + approxPolyDP 1.0  vertices  12 | mask IoU after round trip 0.980

findContours puts its vertices on the centres of the boundary pixels, and fillPoly fills those pixels too, so the round trip through all boundary points (NONE: 128 for the triangle, 88 for the disc) or their straight-run end points (SIMPLE: about 50) is exact here. approxPolyDP with epsilon = 1.0 finds the triangle's 3 corners and still rebuilds it exactly, but describes the disc with 12 vertices and loses a little of it (IoU 0.980). Annotation tools store something like the simplified polygon, which is why a mask rebuilt from a COCO polygon rarely matches the annotator's screen pixel for pixel. Note also that the shoelace area of the triangle (988) differs from its pixel count (1,053): polygon area treats vertices as points in the plane, rasterisation counts every pixel the outline touches.

Run-length encoding, COCO style

RLE replaces the mask by the lengths of its runs of equal values. COCO's uncompressed RLE is a dictionary {"size": [H, W], "counts": [...]} with two rules that every from-scratch implementation must get right:

  1. pixels are read in column-major (Fortran) order: down the first column, then down the second, and so on (mask.ravel(order="F")), not row by row as NumPy does by default;
  2. the counts start with a run of zeros, which may have length 0 if the first pixel is 1, and then alternate: zeros, ones, zeros, ...

So the object's area is the sum of the counts at odd positions, with no decoding at all.

python · try it yourself
import numpy as np, cv2

CLASSES = ["square", "circle", "triangle"]

def make_scene(rng, size=64, max_objects=3):
    """Noisy grey background with 1..max_objects shapes that do not touch.
    Returns RGB uint8 image, boxes (n, 4) as [x1, y1, x2, y2] with x2, y2 exclusive,
    labels (n,) indices into CLASSES, masks (n, size, size) bool."""
    img = rng.normal(110, 12, (size, size, 3)).clip(0, 255).astype(np.uint8)
    n = int(rng.integers(1, max_objects + 1))
    boxes, labels, masks = [], [], []
    for _ in range(100):
        if len(boxes) == n:
            break
        s = int(rng.integers(12, 25)); x = int(rng.integers(0, size - s)); y = int(rng.integers(0, size - s))
        if any(x < b[2] + 2 and b[0] < x + s + 2 and y < b[3] + 2 and b[1] < y + s + 2 for b in boxes):
            continue
        c = int(rng.integers(0, 3)); m = np.zeros((size, size), np.uint8)
        if c == 0:
            cv2.rectangle(m, (x, y), (x + s - 1, y + s - 1), 1, -1)
        elif c == 1:
            cv2.circle(m, (x + s // 2, y + s // 2), s // 2, 1, -1)
        else:
            cv2.fillPoly(m, [np.array([[x + s // 2, y], [x, y + s - 1], [x + s - 1, y + s - 1]], np.int32)], 1)
        img[m > 0] = rng.integers(0, 256, 3)
        ys, xs = np.nonzero(m)
        boxes.append([int(xs.min()), int(ys.min()), int(xs.max()) + 1, int(ys.max()) + 1])
        labels.append(c); masks.append(m > 0)
    return img, np.array(boxes).reshape(-1, 4), np.array(labels), np.array(masks)

def rle_encode(mask):
    """COCO uncompressed RLE: column-major, counts start with a run of zeros."""
    flat = np.asarray(mask, np.uint8).ravel(order="F")
    change = np.flatnonzero(np.diff(flat)) + 1                     # positions where the value changes
    bounds = np.concatenate([[0], change, [flat.size]])
    counts = np.diff(bounds).tolist()
    if flat[0] == 1:
        counts = [0] + counts                                      # first run must be zeros
    return {"size": [mask.shape[0], mask.shape[1]], "counts": counts}

def rle_decode(rle):
    H, W = rle["size"]
    values = np.arange(len(rle["counts"])) % 2                     # 0, 1, 0, 1, ...
    flat = np.repeat(values, rle["counts"]).astype(bool)
    return flat.reshape((H, W), order="F")

def rle_area(rle):
    return int(sum(rle["counts"][1::2]))

tiny = np.array([[0, 1, 1, 0, 0],
                 [0, 1, 1, 0, 0],
                 [0, 1, 0, 0, 0],
                 [0, 0, 0, 0, 0]], bool)
print("tiny mask:", rle_encode(tiny))
print("starts with a 1:", rle_encode(np.array([[1, 0], [1, 1]], bool)))

rng = np.random.default_rng(0)
masks = np.concatenate([make_scene(rng)[3] for _ in range(100)])
encoded = [rle_encode(m) for m in masks]
ok = all(np.array_equal(rle_decode(r), m) for r, m in zip(encoded, masks))
areas_ok = all(rle_area(r) == int(m.sum()) for r, m in zip(encoded, masks))
n_counts = sum(len(r["counts"]) for r in encoded)
print(f"{len(masks)} masks of 64 x 64: round trip exact {ok}, area from counts exact {areas_ok}")
print(f"values stored: masks {masks.size}, RLE counts {n_counts} ({n_counts / masks.size:.4f} of the mask)")
def decode_row_major(rle):                                         # the bug: NumPy's default order "C"
    return np.repeat(np.arange(len(rle["counts"])) % 2, rle["counts"]).astype(bool).reshape(rle["size"])
ious = [(decode_row_major(r) & m).sum() / (decode_row_major(r) | m).sum() for r, m in zip(encoded, masks)]
print(f"decoded row-major by mistake: mean IoU with the truth {np.mean(ious):.3f}")
tiny mask: {'size': [4, 5], 'counts': [4, 3, 1, 2, 10]}
starts with a 1: {'size': [2, 2], 'counts': [0, 2, 1, 1]}
200 masks of 64 x 64: round trip exact True, area from counts exact True
values stored: masks 819200, RLE counts 7356 (0.0090 of the mask)
decoded row-major by mistake: mean IoU with the truth 0.112

The tiny mask reads, column by column: 4 zeros (column 0), then 3 ones (column 1, rows 0 to 2), 1 zero, 2 ones (column 2, rows 0 and 1), and 10 zeros to the end. Its area is 3+2=53 + 2 = 5 without decoding. A mask whose first pixel is 1 gets a leading 0. On the 200 generated masks the round trip and the area are exact, and RLE stores 7,356 counts instead of 819,200 pixel values (0.009 of them), because each mask is one convex shape and most columns hold two runs at most. Decoding with NumPy's default row order instead of order="F" turns every shape into its transpose, a classic bug: mean IoU with the truth falls to 0.112, because the transposed shape sits somewhere else in the image.

The official COCO files and pycocotools use a compressed RLE for crowds and results: the same counts, written as a short ASCII string with a variable-length encoding of the differences. pycocotools is a C extension that is not in the browser, so here is how it is used on your own machine:

python
# Not run here: needs pycocotools (pip install pycocotools), a C extension
from pycocotools import mask as mask_utils
import numpy as np

m = np.asfortranarray(binary_mask.astype(np.uint8))   # it requires column-major uint8
rle = mask_utils.encode(m)                           # {"size": [H, W], "counts": b"..."} compressed
area = mask_utils.area(rle); box = mask_utils.toBbox(rle)   # box as [x, y, w, h]
back = mask_utils.decode(rle)                         # (H, W) uint8
ious = mask_utils.iou([rle_pred], [rle_gt], [0])      # mask IoU; the last argument is iscrowd per gt

Semantic label maps and instance masks

So far each object had its own mask. Datasets for the two segmentation tasks (semantic and instance) usually store one map per image instead:

  • a semantic label map is an H×WH \times W array of class ids (0 = background; Pascal VOC also uses 255 for "ignore" pixels at object borders). Two objects of the same class get the same value, so they cannot be told apart;
  • an instance map stores an object id per pixel (0 = background), with a table from object id to class; or one binary mask per object, as COCO does.

Label maps are saved as PNG, which is lossless (JPEG would blur the ids at every border: never store labels as JPEG). Pascal VOC uses a palette ("P" mode) PNG (Cityscapes stores its ids as plain 8-bit greyscale PNGs instead): each pixel holds an index, and the file carries a colour table so that viewers show colours while the stored values stay ids.

python · try it yourself
import io
import numpy as np, cv2
from PIL import Image

CLASSES = ["square", "circle", "triangle"]

def make_scene(rng, size=64, max_objects=3):
    """Noisy grey background with 1..max_objects shapes that do not touch.
    Returns RGB uint8 image, boxes (n, 4) as [x1, y1, x2, y2] with x2, y2 exclusive,
    labels (n,) indices into CLASSES, masks (n, size, size) bool."""
    img = rng.normal(110, 12, (size, size, 3)).clip(0, 255).astype(np.uint8)
    n = int(rng.integers(1, max_objects + 1))
    boxes, labels, masks = [], [], []
    for _ in range(100):
        if len(boxes) == n:
            break
        s = int(rng.integers(12, 25)); x = int(rng.integers(0, size - s)); y = int(rng.integers(0, size - s))
        if any(x < b[2] + 2 and b[0] < x + s + 2 and y < b[3] + 2 and b[1] < y + s + 2 for b in boxes):
            continue
        c = int(rng.integers(0, 3)); m = np.zeros((size, size), np.uint8)
        if c == 0:
            cv2.rectangle(m, (x, y), (x + s - 1, y + s - 1), 1, -1)
        elif c == 1:
            cv2.circle(m, (x + s // 2, y + s // 2), s // 2, 1, -1)
        else:
            cv2.fillPoly(m, [np.array([[x + s // 2, y], [x, y + s - 1], [x + s - 1, y + s - 1]], np.int32)], 1)
        img[m > 0] = rng.integers(0, 256, 3)
        ys, xs = np.nonzero(m)
        boxes.append([int(xs.min()), int(ys.min()), int(xs.max()) + 1, int(ys.max()) + 1])
        labels.append(c); masks.append(m > 0)
    return img, np.array(boxes).reshape(-1, 4), np.array(labels), np.array(masks)

rng = np.random.default_rng(0)
for _ in range(3):
    img, boxes, labels, masks = make_scene(rng)        # the third scene has two squares
semantic = np.zeros((64, 64), np.uint8)                # 0 = background, 1 + class index otherwise
instance = np.zeros((64, 64), np.uint8)                # 0 = background, 1, 2, ... = object id
for k, (l, m) in enumerate(zip(labels, masks), start=1):
    semantic[m] = 1 + l
    instance[m] = k
print("classes:", [CLASSES[l] for l in labels])
print("semantic values:", np.unique(semantic).tolist(), "| instance values:", np.unique(instance).tolist())
print("objects recoverable from the semantic map:", cv2.connectedComponents((semantic == 1).astype(np.uint8))[0] - 1,
      "squares (they do not touch; touching squares would merge into one)")

palette = [0, 0, 0, 230, 25, 75, 60, 180, 75, 0, 130, 200] + [0] * (256 - 4) * 3   # colours for ids 0..3
png = Image.fromarray(semantic); png.putpalette(palette)          # putpalette makes it a "P" image
buf = io.BytesIO(); png.save(buf, format="PNG")
back = Image.open(io.BytesIO(buf.getvalue()))
print("palette PNG:", len(buf.getvalue()), "bytes | mode", back.mode,
      "| ids preserved:", np.array_equal(np.array(back), semantic))
print("shown colour of a square pixel (RGB):", back.convert("RGB").getpixel((20, 35)))
jpg = io.BytesIO(); Image.fromarray(semantic * 60).save(jpg, format="JPEG", quality=90)
dec = np.array(Image.open(io.BytesIO(jpg.getvalue())))
print("same map as JPEG: pixels with a changed value:", int((dec != semantic * 60).sum()), "of", semantic.size)
classes: ['square', 'square']
semantic values: [0, 1] | instance values: [0, 1, 2]
objects recoverable from the semantic map: 2 squares (they do not touch; touching squares would merge into one)
palette PNG: 881 bytes | mode P | ids preserved: True
shown colour of a square pixel (RGB): (230, 25, 75)
same map as JPEG: pixels with a changed value: 317 of 4096

np.array(back) gives back the stored indices, not the colours: that is the whole point of a palette PNG, and the classic bug is to load such a file with a library that converts it to RGB first (OpenCV's cv2.imread does, even with cv2.IMREAD_UNCHANGED: it always expands the palette to BGR colours, and IMREAD_GRAYSCALE gives their brightness; either way the pixel values are no longer class ids, so read palette label maps with Pillow). The JPEG line shows why label maps are never stored lossy: even at quality 90, 317 of the 4,096 values change, all around the borders, creating class ids that do not exist. The lossless PNG with its palette takes 881 bytes and returns every id.

YOLO segmentation text files

Ultralytics' segmentation format extends the YOLO box format: one line per object, the class index, then the polygon vertices x1 y1 x2 y2 ..., all normalised by the image width and height. No box is stored; it is computed from the polygon. Writing it is findContours plus normalisation; reading it is denormalising plus fillPoly.

python · try it yourself
import numpy as np, cv2

W, H = 96, 64                                              # not square, on purpose
mask = np.zeros((H, W), np.uint8)
cv2.ellipse(mask, (60, 30), (25, 14), 20, 0, 360, 1, -1)   # one object, class 1

contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
poly = cv2.approxPolyDP(contours[0], 0.5, True).reshape(-1, 2)
line = "1 " + " ".join(f"{x / W:.6f} {y / H:.6f}" for x, y in poly)
print("vertices:", len(poly), "| line length:", len(line), "characters")
print(line[:60], "...")

vals = line.split()
cls, xy = int(vals[0]), np.array(vals[1:], float).reshape(-1, 2) * [W, H]
back = np.zeros_like(mask); cv2.fillPoly(back, [np.round(xy).astype(np.int32)], 1)
iou = (back & mask).sum() / (back | mask).sum()
x1, y1 = xy.min(0); x2, y2 = xy.max(0) + 1
print(f"class {cls} | mask IoU after the round trip {iou:.3f} | box from the polygon {[int(x1), int(y1), int(x2), int(y2)]}")
ys, xs = np.nonzero(mask)
print("box from the mask:", [int(xs.min()), int(ys.min()), int(xs.max()) + 1, int(ys.max()) + 1])
vertices: 28 | line length: 505 characters
1 0.375000 0.343750 0.375000 0.421875 0.395833 0.484375 0.42 ...
class 1 | mask IoU after the round trip 0.988 | box from the polygon [36, 14, 85, 47]
box from the mask: [36, 14, 85, 47]

The 28 normalised vertices take 505 characters, and the mask rebuilt from them has IoU 0.988 with the original (the simplification with epsilon = 0.5 and the rounding of the rebuilt vertices cost a few edge pixels). The box derived from the polygon, [36, 14, 85, 47], matches the box derived from the mask, because both come from the same boundary pixels. Objects with holes (a ring, a donut) or several parts (a car split by a pole) do not fit one simple polygon: COCO stores several polygons per object (holes are not supported in its polygon form, which is one reason crowds and complex masks use RLE), and Ultralytics' converter joins parts into one polygon with thin connecting segments.

Pitfalls

  • Row-major RLE. COCO counts are column-major; decoding them row by row transposes every mask.
  • Forgetting the leading zero run when a mask starts with a 1: every following run swaps meaning.
  • x/y order. OpenCV point arrays are (x, y); NumPy indexing is [y, x]. A polygon with swapped coordinates is mirrored along the diagonal.
  • Storing label maps as JPEG, or reading palette PNGs as RGB: ids become colours or new, invalid values.
  • Polygon area used as mask area. The shoelace area and the pixel count differ by roughly half the perimeter; use the one your metric uses (COCO uses the mask's pixel count).
  • Resizing label maps with bilinear interpolation: it averages class ids (1 and 3 give 2, a class that is not there). Resize masks and label maps with nearest neighbour (resize and geometry).
  • Overlapping instances written into one instance map: the later object overwrites the earlier one's pixels. Decide an order (for example by depth), or keep one mask per object.

Practice

  1. Decode by hand the COCO RLE {"size": [3, 3], "counts": [2, 4, 3]} and give the mask's area.
  2. A mask's first pixel (top-left) is 1. What is the first count of its COCO RLE?
  3. Why can a semantic label map not be turned into instance masks when two objects of the same class touch?
Answer
  1. Values in column order: 0, 0, 1, 1, 1, 1, 0, 0, 0. Column 0 is (0, 0, 1), column 1 is (1, 1, 1), column 2 is (0, 0, 0). So the mask is rows [0, 1, 0], [0, 1, 0], [1, 1, 0], with area 4 (the second count).
  2. 0: the counts always start with a run of zeros, here of length zero.
  3. Both objects have the same value and their pixels are connected, so a connected-components pass finds one region. The information about where one ends and the other begins was never stored; that is what an instance map (or watershed on the shape, see instance segmentation) adds.

Test yourself

In which order does COCO's uncompressed RLE read the pixels of a mask?

  1. Row by row, left to right
  2. Column by column, top to bottom (Fortran order), starting with a run of zeros
  3. In a spiral
  4. Only the boundary pixels

An RLE has counts [10, 4, 6, 3, 41]. What is the object's area in pixels?

  1. 64
  2. 7
  3. 14
  4. 10

Why are segmentation label maps stored as PNG rather than JPEG?

  1. PNG files are always smaller
  2. JPEG is lossy: it changes pixel values near edges, creating class ids that do not exist; PNG keeps every value exactly
  3. JPEG cannot store grey images
  4. PNG supports more classes

A label map is downscaled for training. Which interpolation must be used?

  1. Bilinear
  2. Bicubic
  3. Nearest neighbour, so every output pixel keeps a class id that exists
  4. Area averaging