Sub topic 6
Polygons and masks for segmentation
A bounding box says where an object is. A polygon or mask says which pixels belong to it. This chapter covers how the two representations relate, how to store and convert them, and how to catch errors before training.
This chapter assumes you can read Python and NumPy, know the COCO box layout from the previous chapter, and understand that an image is a height-by-width array of pixels. The OpenCV example needs opencv-python. The other examples need numpy and pillow.
Two representations of one shape
A polygon is an ordered list of vertices (x, y) joined by straight edges, with the last vertex joined back to the first. It is a vector description, so its size depends on the number of vertices, not on the image size.
A mask is a raster array with the same height and width as the image. A binary mask holds 1 for pixels inside the object and 0 elsewhere. Its size depends on image resolution.
| Property | Polygon | Binary mask |
|---|---|---|
| Storage | A few dozen numbers | height × width values (or compressed RLE) |
| Edge precision | Sub-pixel coordinates possible | Whole pixels only |
| Holes | Need extra conventions | Natural |
| Typical source | Click-by-click tools | Brush tools, model output, SAM-style tools |
| Typical use | Annotation files, review | Training targets, metrics |
Annotators usually draw polygons, and training code usually consumes masks. Most of your work is converting between them without shifting, dropping, or merging objects.
Which task needs which mask
The task types from the first chapter map to mask structures as follows.
- Semantic segmentation needs one label map. Each pixel holds one class ID. Two touching cars become one blob of "car".
- Instance segmentation needs one mask per object. Two touching cars get two masks, and the masks may overlap.
- Panoptic segmentation combines both. "Thing" classes such as cars get instance IDs, and "stuff" classes such as road and sky get a single region each. Every pixel gets exactly one label, so overlaps must be resolved at labelling time.
Decide the target before choosing a tool, because converting instance masks to a label map is easy, but going back is not. Once instances touch and are merged, you cannot recover where one ends and the next begins.
Polygons in COCO
COCO stores a polygon in segmentation as a list of flat coordinate lists, [x1, y1, x2, y2, ...], in absolute pixels. The outer list exists because one object can have several parts. A car split in two by a lamp post is one object with two polygons.
{
"id": 7,
"image_id": 1,
"category_id": 1,
"bbox": [50, 40, 100, 50],
"segmentation": [
[50, 40, 150, 40, 150, 90, 50, 90]
],
"area": 5000,
"iscrowd": 0
}Three details matter here.
- Each flat list needs an even number of values and at least three points (six numbers). Shorter lists are a common export bug.
- The
bboxis stored separately and is not derived automatically. If you edit a polygon, you must also recomputebboxandarea. - With
iscrowd: 1, COCO storessegmentationas run-length encoding (RLE), not polygons. Crowd regions mark groups you chose not to separate, such as a dense flock of birds. Loaders must handle both forms.
COCO polygons have no standard way to describe holes. An object like a doughnut or a chair with gaps in the back gets a polygon around the outside, and the hole is either filled or approximated with a thin bridge. If holes matter for your task, use masks with RLE instead.
Rasterising polygons
Drawing the polygon into a blank image gives the mask. Pillow can do this.
import numpy as np
from PIL import Image, ImageDraw
def polygon_to_mask(points, width, height):
"""points: list of (x, y) pixel coordinates."""
img = Image.new("L", (width, height), 0)
ImageDraw.Draw(img).polygon([tuple(p) for p in points], outline=1, fill=1)
return np.array(img, dtype=np.uint8)
mask = polygon_to_mask([(50, 40), (150, 40), (150, 90), (50, 90)], 640, 480)
print(mask.shape, int(mask.sum()))The array has shape (480, 640): rows first, then columns. Passing (width, height) where (height, width) is expected is a frequent source of transposed masks.
The pixel sum is a little above the 5000 you get from the box area (5151, because Pillow includes the boundary pixels). That small excess is normal. It also shows why the area field in COCO should be defined consistently. Pick one rule, polygon area or pixel count, and apply it to every annotation.
For COCO entries with several parts, draw each part onto the same image. Overlapping parts are unioned.
import numpy as np
from PIL import Image, ImageDraw
def flat_to_points(flat):
if len(flat) % 2 != 0 or len(flat) < 6:
raise ValueError("need an even count and at least 3 points")
return list(zip(flat[0::2], flat[1::2]))
def segmentation_to_mask(segmentation, width, height):
img = Image.new("L", (width, height), 0)
draw = ImageDraw.Draw(img)
for part in segmentation:
draw.polygon(flat_to_points(part), outline=1, fill=1)
return np.array(img, dtype=np.uint8)
seg = [[50, 40, 150, 40, 150, 90, 50, 90],
[200, 40, 260, 40, 230, 100]]
mask = segmentation_to_mask(seg, 640, 480)
print(mask.shape, int(mask.sum()))Pixel-centre conventions
Do you treat coordinate (50, 40) as the corner of a pixel or its centre? Tools and libraries disagree. Rasterisers can therefore differ by up to a pixel at the edges. On a 1000-pixel-wide object this is noise. On a 12-pixel-wide object it changes the area by more than 20%. Use one rasteriser for both training and evaluation, and do not compare masks produced by different libraries without allowing for a small boundary tolerance.
Converting masks back to polygons
Brush tools and model-assisted tools produce masks, but COCO polygons are often the delivery format. OpenCV can trace mask outlines.
import cv2
import numpy as np
def mask_to_polygons(mask, epsilon=1.0, min_points=3):
"""Return a list of flat [x1, y1, x2, y2, ...] polygons."""
contours, _ = cv2.findContours(
mask.astype(np.uint8), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE
)
polygons = []
for c in contours:
c = cv2.approxPolyDP(c, epsilon, True)
if len(c) >= min_points:
polygons.append(c.reshape(-1).tolist())
return polygons
demo = np.zeros((480, 640), dtype=np.uint8)
demo[40:91, 50:151] = 1
print(mask_to_polygons(demo))The parameter epsilon is the maximum distance in pixels between the simplified outline and the original. A value of 0 keeps every boundary pixel, and larger values give fewer vertices. Choose it against the smallest object you care about. RETR_EXTERNAL returns only outer boundaries, so holes are discarded. That matches the COCO polygon limitation, but it silently changes the shape.
Building semantic label maps from instances
To make a single label map from instance masks, paint each object into an array of class IDs. Painting order decides who wins where masks overlap, so it is worth detecting overlaps instead of ignoring them.
import numpy as np
def instances_to_label_map(masks, class_ids, width, height):
"""masks: list of (height, width) arrays. 0 is reserved for background."""
label_map = np.zeros((height, width), dtype=np.uint8)
overlap = np.zeros((height, width), dtype=bool)
for m, cid in zip(masks, class_ids):
m = m.astype(bool)
overlap |= m & (label_map > 0)
label_map[m] = cid
return label_map, overlap
a = np.zeros((480, 640), dtype=np.uint8); a[40:91, 50:151] = 1
b = np.zeros((480, 640), dtype=np.uint8); b[60:121, 100:201] = 1
label_map, overlap = instances_to_label_map([a, b], [1, 2], 640, 480)
print(np.unique(label_map), int(overlap.sum()))Class ID 0 is background, so your taxonomy IDs must start at 1. The uint8 type limits you to 255 classes. If overlap pixels are many, either your annotators are not following the boundary rules, or a guideline for who is "in front" is missing.
Measuring polygon and mask quality
Box IoU from the earlier chapter extends directly to masks. Count intersecting pixels instead of rectangle overlap.
import numpy as np
def mask_iou(a, b):
a = a.astype(bool)
b = b.astype(bool)
union = np.logical_or(a, b).sum()
if union == 0:
return 0.0
return float(np.logical_and(a, b).sum() / union)Mask IoU is stricter than box IoU on thin or concave objects, such as a person with outstretched arms or a bicycle. Two annotators can produce boxes with IoU 0.9 and masks with IoU 0.7. Use mask IoU when comparing annotators for segmentation tasks, and set the acceptance threshold from a pilot batch, not from a number borrowed from detection.
You can also check a polygon directly. The shoelace formula gives its area, which should match the stored area field to within your rounding rule.
def polygon_area(points):
n = len(points)
s = 0.0
for i in range(n):
x1, y1 = points[i]
x2, y2 = points[(i + 1) % n]
s += x1 * y2 - x2 * y1
return abs(s) / 2
print(polygon_area([(50, 40), (150, 40), (150, 90), (50, 90)]))This prints 5000.0. The shoelace formula assumes the polygon does not cross itself. For a self-intersecting "bow-tie" shape it returns a signed sum that is not the visible area, which is why self-intersection is worth flagging separately.
Common errors
| Symptom | Likely cause | Check |
|---|---|---|
| Mask looks rotated or stretched | Width and height swapped when allocating the array | Assert `mask.shape == (height, width)` |
| Polygon drawn in the wrong place | Normalised coordinates used as pixels (or the reverse) | All values should be below image width and height |
| Object has an empty mask | Fewer than three points, or all points collinear | Reject polygons with area 0 |
| Fill covers an unexpected region | Self-intersecting polygon | Test for crossing edges before export |
| Hole is filled in | Holes not representable in the polygon format | Use RLE or document the limitation |
| Neighbouring instances merge | Instances combined into a semantic map too early | Keep instance masks as the master copy |
| Bounding box does not match mask | Mask edited, `bbox` not recomputed | Recompute from the mask extent on export |
| Tiny stray objects | Brush strokes leave isolated pixels | Drop connected components below a size threshold |
Practical guidelines for annotators
- Trace the visible boundary, not the imagined one. Occluded parts are excluded unless your guideline says to annotate amodally.
- Put vertices on corners and curvature changes. Many vertices on straight edges waste time and add no precision.
- Decide how tight to be: inside the edge, on the edge, or outside. State it and show examples, because systematic offsets of one pixel on every object bias every model trained on the data.
- For shared boundaries, say whether adjacent objects may overlap. Panoptic work generally forbids overlap.
- Store the master annotations in the richest form you have (masks or high-vertex polygons) and derive simplified exports from them. Never edit exports by hand.
Exercise
A COCO annotation has segmentation: [[10, 10, 50, 10, 50, 50, 10, 50]] on a 100 × 80 image (width × height). What shape should its mask array have, what is the polygon area, and why might mask.sum() differ from that area?
Show answer
The mask shape is (80, 100), height first. The polygon is a 40 × 40 square, so its area is 1600. A rasteriser such as Pillow includes the boundary pixels, so the mask would hold 41 × 41 = 1681 pixels. The difference comes from the pixel-boundary convention, not from an error, and the dataset should use one area definition consistently.
Exercise
You convert instance masks to a single semantic label map and find that 3% of object pixels are flagged as overlapping. Name two possible causes and one fix for each.
Show answer
First, annotators drew shared boundaries sloppily so neighbouring masks overlap. Fix this by adding a boundary rule to the guideline and having reviewers check shared edges. Second, objects genuinely overlap in the image, such as a person in front of a car. Fix this by defining which class wins (for example the nearer object) and annotating the visible region only.