Sub topic 6
Polygons and Masks for Segmentation
This chapter assumes you know Python lists and dictionaries, JSON, image width and height, and the basic idea of supervised model training. You will learn how to represent the exact shape of an object instead of only its enclosing rectangle.
Polygons, masks, and segmentation tasks
A polygon is a sequence of points connected by straight line segments. In image annotation, each point usually stores an x coordinate and a y coordinate in pixels. The polygon boundary follows the visible object as closely as the annotation rules require.
A mask is an image-sized grid of labels. A binary mask contains zero for background pixels and one for pixels belonging to the object. A mask can preserve curved boundaries and holes more directly than a bounding box.
| Representation | Stores | Common use |
|---|---|---|
| Bounding box | One rectangle per object | Object detection |
| Polygon | Boundary points | Compact instance or semantic labels |
| Binary mask | One value per pixel | Training and evaluating segmentation |
Instance segmentation uses a separate mask for each object. If two cars touch, their masks remain separate. Semantic segmentation assigns a class to every pixel, so touching cars may share the same car label. Panoptic segmentation combines semantic labels with separate object identities.
Drawing a polygon consistently
Start with the visible boundary defined by the project guidelines. Use enough points to capture important bends, but do not add many points to an almost straight edge. Excess points make files larger and can create small, accidental jagged edges.
Use a consistent rule for uncertain pixels. For example, a guideline might say to include visible object pixels, exclude shadows, and follow the estimated boundary behind an occluding object only when the object’s shape is clear. A partially hidden object can therefore have a polygon that represents only the visible region, or an estimated full shape. The dataset must choose one rule and apply it everywhere.
The order of points matters. Points should normally follow the boundary clockwise or counterclockwise and return to the starting region. Self-crossing polygons are invalid or ambiguous. Coordinates outside the image should be rejected unless the annotation format explicitly supports them.
Rasterising a polygon
Rasterisation converts vector-like boundary points into a pixel grid. The result has the same height and width as the source image. The exact boundary rule depends on the library. A pixel whose centre lies on an edge may be included or excluded, so use the same rasterisation method during preparation and evaluation.
The following example creates a binary mask. PIL uses image coordinates with the origin at the top-left. x increases to the right, and y increases downward.
import numpy as np
from PIL import Image, ImageDraw
def polygon_to_mask(points, width, height):
"""Return a uint8 mask with 1 inside the polygon."""
image = Image.new("L", (width, height), 0)
draw = ImageDraw.Draw(image)
draw.polygon([tuple(point) for point in points], outline=1, fill=1)
return np.array(image, dtype=np.uint8)
polygon = [(50, 40), (150, 40), (150, 90), (50, 90)]
mask = polygon_to_mask(polygon, width=640, height=480)
print("shape:", mask.shape)
print("object pixels:", int(mask.sum()))For the example, the mask shape is 480 rows by 640 columns. The sum counts pixels marked as object pixels. It may differ slightly from the geometric area because a continuous polygon is being represented on a discrete pixel grid.
Multiple objects and holes
Store instance masks separately when object identity matters. Two masks may overlap in annotations only if the project explicitly allows it. Otherwise, resolve overlaps according to a visible-depth rule.
A polygon with a hole requires a format that supports multiple rings or a separate hole definition. Do not assume that reversing the point order automatically creates a hole. Check the format and the reader used by the training pipeline.
Checking mask quality
Review masks at the original image resolution. Zooming too far out hides small gaps and boundary errors. Pay special attention to thin objects, object boundaries touching the image edge, holes, heavy occlusion, and objects smaller than a few pixels.
Useful checks include:
- Every polygon has at least three distinct points.
- Every point is finite and lies within the expected coordinate range.
- The rasterised mask contains at least one foreground pixel.
- The mask dimensions equal the image dimensions.
- Each instance has exactly one intended class.
- Tiny isolated components are either valid objects or annotation mistakes.
When two annotators label the same object, compare their masks with intersection over union. IoU is the intersection area divided by the union area. A low value signals disagreement, but the threshold should depend on object size and the project’s boundary tolerance.
Exercise
Why should two touching cars receive separate masks for instance segmentation?
Show answer
Instance segmentation must preserve object identity, so each car needs its own mask even when their pixels touch.