DEV Community

Taskmonk Team
Taskmonk Team

Posted on

Converting YOLO Labels to COCO JSON in Python (and the Traps That Corrupt Boxes)

Sooner or later every computer vision team ends up with labels in the wrong format. A vendor delivers YOLO text files, but your training code expects COCO JSON. Or a model zoo wants COCO and your old dataset is YOLO. The conversion looks trivial, and it mostly is, but there are a few traps that silently corrupt boxes. This post walks through a small, tested converter and the checks worth running afterward.

The two formats in one minute

YOLO stores one .txt file per image. Each line is one object:

class_id x_center y_center width height
Enter fullscreen mode Exit fullscreen mode

All four coordinates are normalized to the 0 to 1 range, relative to image width and height.

COCO stores everything in one JSON file with images, annotations and categories lists. Boxes are [x_min, y_min, width, height] in absolute pixels, with the origin at the top-left.

So the conversion needs three things: image sizes, a class mapping, and a coordinate transform.

The coordinate transform

def yolo_to_coco_bbox(xc, yc, w, h, img_w, img_h):
    bw = w * img_w
    bh = h * img_h
    x_min = xc * img_w - bw / 2
    y_min = yc * img_h - bh / 2
    return [round(x_min, 2), round(y_min, 2), round(bw, 2), round(bh, 2)]

print(yolo_to_coco_bbox(0.5, 0.5, 0.2, 0.4, 640, 480))
# [256.0, 144.0, 128.0, 192.0]
Enter fullscreen mode Exit fullscreen mode

The full converter

import json
from pathlib import Path
from PIL import Image

def convert(images_dir, labels_dir, class_names, out_path):
    images, annotations = [], []
    ann_id = 1
    paths = sorted(p for p in Path(images_dir).iterdir()
                   if p.suffix.lower() in {".jpg", ".jpeg", ".png"})
    for img_id, img_path in enumerate(paths, start=1):
        with Image.open(img_path) as im:
            w, h = im.size
        images.append({"id": img_id, "file_name": img_path.name,
                       "width": w, "height": h})
        label_file = Path(labels_dir) / (img_path.stem + ".txt")
        if not label_file.exists():
            continue  # image with no objects
        for line in label_file.read_text().splitlines():
            if not line.strip():
                continue
            cls, xc, yc, bw, bh = line.split()[:5]
            box = yolo_to_coco_bbox(float(xc), float(yc), float(bw), float(bh), w, h)
            annotations.append({
                "id": ann_id, "image_id": img_id,
                "category_id": int(cls) + 1,  # COCO ids usually start at 1
                "bbox": box, "area": round(box[2] * box[3], 2),
                "iscrowd": 0,
            })
            ann_id += 1
    categories = [{"id": i + 1, "name": n} for i, n in enumerate(class_names)]
    Path(out_path).write_text(json.dumps(
        {"images": images, "annotations": annotations, "categories": categories}))
    return len(images), len(annotations)
Enter fullscreen mode Exit fullscreen mode

Traps to watch for

Reading the image size from the wrong place. Never assume all images share one size. Read each one. Datasets that mix phone photos, cropped images and screenshots are common.

EXIF rotation. Phone photos often store pixels in one orientation and an EXIF tag that says to rotate them. If the YOLO labels were made on the rotated view but you read the raw size, width and height are swapped and every box lands in the wrong place. If your labeling tool respected EXIF, apply ImageOps.exif_transpose before reading the size.

Class index offset. YOLO class ids start at 0. Many COCO tools reserve 0 for background and expect categories to start at 1. Decide on one convention and make the mapping explicit, as in the + 1 above.

Segmentation lines. YOLO segmentation files have more than five values per line. The converter above only reads the first five, which would treat polygon points as a box. Detect long lines and handle them separately.

Empty label files versus missing ones. An empty file usually means "no objects". A missing file might mean "not labeled yet". Keep both cases in mind before training on negatives.

Checks after conversion

def sanity_check(coco):
    sizes = {im["id"]: (im["width"], im["height"]) for im in coco["images"]}
    problems = []
    for a in coco["annotations"]:
        x, y, w, h = a["bbox"]
        W, H = sizes[a["image_id"]]
        if w <= 1 or h <= 1:
            problems.append((a["id"], "tiny box"))
        if x < -1 or y < -1 or x + w > W + 1 or y + h > H + 1:
            problems.append((a["id"], "outside image"))
    return problems
Enter fullscreen mode Exit fullscreen mode

Then draw 20 random images with their converted boxes and look at them. Visual spot checks catch rotation and offset bugs faster than any metric.

Avoiding the problem upstream

The cleanest fix is to agree on an export format before labeling starts. Most annotation platforms can export more than one format, so put the target format in the project spec and you rarely need to convert by hand. If you work with a managed provider such as Taskmonk for image annotation, settle the export format and class mapping during project setup, along with the guideline.

Top comments (0)