DEV Community

Taskmonk Team
Taskmonk Team

Posted on

Turning COCO Polygons into Masks and Catching Broken Annotations in Python

Polygon annotations look clean in the labeling tool. Once you rasterize them into masks for training, problems show up: self-intersecting shapes, slivers a few pixels wide, polygons that spill past the image edge, and objects labeled twice. A short validation pass before training catches most of these.

Rasterizing a COCO polygon

COCO stores each polygon as a flat list [x1, y1, x2, y2, ...]. pycocotools handles the conversion:

from pycocotools import mask as mask_utils
import numpy as np

def polygon_to_mask(segmentation, height, width):
    rles = mask_utils.frPyObjects(segmentation, height, width)
    rle = mask_utils.merge(rles)
    return mask_utils.decode(rle).astype(bool)
Enter fullscreen mode Exit fullscreen mode

merge matters when an object is split into several polygons (for example, a car partly hidden behind a pole).

Five checks worth running

from shapely.geometry import Polygon

def check_annotation(ann, img_h, img_w, min_area=16):
    issues = []
    for seg in ann["segmentation"]:
        pts = list(zip(seg[0::2], seg[1::2]))
        if len(pts) < 3:
            issues.append("fewer than 3 points")
            continue
        poly = Polygon(pts)
        if not poly.is_valid:
            issues.append("self-intersecting polygon")
        xs, ys = seg[0::2], seg[1::2]
        if min(xs) < 0 or min(ys) < 0 or max(xs) > img_w or max(ys) > img_h:
            issues.append("outside image bounds")
    mask = polygon_to_mask(ann["segmentation"], img_h, img_w)
    if mask.sum() < min_area:
        issues.append("tiny mask")
    return issues
Enter fullscreen mode Exit fullscreen mode
  1. Too few points. Usually a mis-click that closed the polygon early.
  2. Self-intersection. The fill rule can leave holes in the mask where none were meant.
  3. Out of bounds. Points slightly outside the image are common after resizing or cropping.
  4. Tiny masks. Often stray clicks, sometimes real but distant objects. Review, don't auto-delete.
  5. Duplicates. Two annotations of the same class with very high mask IoU:
def mask_iou(a, b):
    inter = np.logical_and(a, b).sum()
    union = np.logical_or(a, b).sum()
    return inter / union if union else 0.0

# flag pairs of same-class masks in one image with IoU > 0.9
Enter fullscreen mode Exit fullscreen mode

What to do with the flags

Do not silently fix everything in code. Some flags are real data: a tiny mask may be a distant pedestrian that matters for your use case. Send flagged items back to the annotation queue with the reason attached, and track which issue types come from which annotators or guideline sections. If one issue type keeps recurring, the guideline or the tool setup usually needs a change.

Closing the loop

Validation scripts catch structural errors. They cannot tell you whether the boundary hugs the object or whether the class is right; that still needs a trained reviewer. Teams running image annotation at scale usually pair automated checks like these with a Maker-Checker review step so the script filters and the human decides.

Takeaway

Rasterize early, run the five checks, and route flags back to people with the reason attached. It takes an afternoon to set up and saves a lot of confused debugging after training.

Top comments (0)