Sub topic 7
Annotation formats: COCO, YOLO and Pascal VOC
An annotation format is the file layout that stores your boxes, polygons and class names. The same box can be written three ways, and mixing them up is a common cause of silently wrong training data. This chapter shows how each format encodes a box, how to convert between them, and which checks catch mistakes.
This chapter assumes you can read Python and JSON. It also assumes you know that image coordinates start at the top-left corner, with x growing rightward and y growing downward. The chapters on pixel coordinates, bounding boxes and polygons cover that background.
One box, three encodings
Take a car in a 640 by 480 image. Its box has its top-left corner at (50, 40) and measures 100 by 50 pixels.
| Format | Container | Box encoding | Units | Class reference |
|---|---|---|---|---|
| COCO | One JSON file per split | `[x_min, y_min, width, height]` | Pixels | `category_id` into a `categories` list |
| YOLO | One `.txt` file per image | `x_center y_center width height` | Fractions of image size, 0 to 1 | Zero-based index, names stored elsewhere |
| Pascal VOC | One `.xml` file per image | `xmin ymin xmax ymax` | Pixels | Name string in each object |
COCO
COCO (Common Objects in Context) stores a whole dataset in one JSON file with three main lists: images, categories and annotations. Each annotation points to an image through image_id and to a class through category_id.
{
"images": [
{"id": 1, "file_name": "street_001.jpg", "width": 640, "height": 480}
],
"categories": [
{"id": 1, "name": "car"}
],
"annotations": [
{
"id": 1,
"image_id": 1,
"category_id": 1,
"bbox": [50, 40, 100, 50],
"segmentation": [[50, 40, 150, 40, 150, 90, 50, 90]],
"area": 5000,
"iscrowd": 0
}
]
}Details that matter in practice:
bboxis top-left corner plus size, in pixels. It is not two corners.segmentationis a list of polygons. Each polygon is a flat list[x1, y1, x2, y2, ...]. One object can have several polygons, for example when occlusion splits it into separate pieces.areais the mask area, not necessarilyw * h. For a polygon object it is smaller than the box area. Evaluation code uses it to sort objects into small, medium and large.iscrowdset to 1 means the entry marks a dense group, such as a crowd of people, instead of one instance. Itssegmentationis then stored as run-length encoding (RLE), a compressed mask, instead of polygons.- Category ids are arbitrary integers, often starting at 1 and sometimes with gaps. Never assume that
category_idequals a position in a list. - Images with no objects still appear in
images. They have no annotations.
YOLO
YOLO format writes one text file per image, with the same base name as the image. Each line is one object:
0 0.15625 0.135417 0.15625 0.104167The fields are class index, centre x, centre y, width and height. All four coordinates are divided by the image width or height, so the values sit between 0 and 1. Because the values are relative, they survive resizing the image. This only holds if you resize the whole image without cropping.
The files hold no class names. Names live in a separate file, such as classes.txt or the names list in a training data.yaml. Class indices start at 0. An image with no objects gets an empty text file, and the trainer reads that as a background image. A missing file may be treated the same way or reported as a warning, depending on the tool.
Segmentation labels in the YOLO convention use a different line: the class index followed by normalised polygon points, class x1 y1 x2 y2 .... There is no box on that line, and the trainer derives it.
The conversion from COCO to YOLO boxes is a shift to the centre and a division by the image size:
def coco_bbox_to_yolo(bbox, img_w, img_h):
x, y, w, h = bbox
x_center = (x + w / 2) / img_w
y_center = (y + h / 2) / img_h
return x_center, y_center, w / img_w, h / img_h
print(coco_bbox_to_yolo([50, 40, 100, 50], 640, 480))This prints (0.15625, 0.13541666666666666, 0.15625, 0.10416666666666667). Note that x is divided by the width and y by the height. Swapping them is easy to do and shows up only on non-square images.
Pascal VOC
Pascal VOC stores one XML file per image. Each object element carries a class name and a pixel box in corner form:
<annotation>
<filename>street_001.jpg</filename>
<size><width>640</width><height>480</height><depth>3</depth></size>
<object>
<name>car</name>
<truncated>0</truncated>
<difficult>0</difficult>
<bndbox>
<xmin>51</xmin><ymin>41</ymin><xmax>150</xmax><ymax>90</ymax>
</bndbox>
</object>
</annotation>The truncated flag marks an object cut by the image edge. The difficult flag marks one that is hard to recognise. VOC evaluation ignores difficult objects by default.
The original VOC convention counts pixels from 1 and treats xmax and ymax as inclusive. That is why the file above shows xmin as 51 for a box that starts at pixel 50 in 0-based coordinates. Many modern exporters write 0-based values instead, so there is no safe default. Open a few files and compare them with the image before you trust either reading.
Here is a parser that handles both cases and produces COCO-style boxes:
import xml.etree.ElementTree as ET
def voc_to_coco_boxes(xml_path, one_based=True):
root = ET.parse(xml_path).getroot()
offset = 1 if one_based else 0
out = []
for obj in root.findall("object"):
bb = obj.find("bndbox")
xmin = float(bb.findtext("xmin")) - offset
ymin = float(bb.findtext("ymin")) - offset
xmax = float(bb.findtext("xmax"))
ymax = float(bb.findtext("ymax"))
out.append((obj.findtext("name"), [xmin, ymin, xmax - xmin, ymax - ymin]))
return outFor the file above with one_based=True, the result is ("car", [50.0, 40.0, 100.0, 50.0]). That matches the COCO box exactly.
Converting a whole dataset
The following script converts a COCO file into YOLO text files. It maps COCO category ids to contiguous zero-based indices, writes empty files for images with no objects, and skips crowd entries because they have no single box in the usual sense.
import json
from collections import defaultdict
from pathlib import Path
def coco_to_yolo(coco_path, out_dir):
coco = json.loads(Path(coco_path).read_text())
images = {im["id"]: im for im in coco["images"]}
cats = sorted(coco["categories"], key=lambda c: c["id"])
cat_index = {c["id"]: i for i, c in enumerate(cats)}
lines = defaultdict(list)
for ann in coco["annotations"]:
if ann.get("iscrowd", 0):
continue
im = images[ann["image_id"]]
x, y, w, h = ann["bbox"]
xc = (x + w / 2) / im["width"]
yc = (y + h / 2) / im["height"]
lines[im["id"]].append(
f"{cat_index[ann['category_id']]} {xc:.6f} {yc:.6f} "
f"{w / im['width']:.6f} {h / im['height']:.6f}"
)
out = Path(out_dir)
out.mkdir(parents=True, exist_ok=True)
for img_id, im in images.items():
name = Path(im["file_name"]).stem + ".txt"
body = "\n".join(lines[img_id])
(out / name).write_text(body + "\n" if body else "")
(out / "classes.txt").write_text("\n".join(c["name"] for c in cats) + "\n")
coco_to_yolo("annotations.json", "labels")Two limits apply. Images in different folders that share a base name would overwrite each other's label file. The script also drops polygons, so it is not a segmentation converter.
Polygons across formats
Segmentation labels move between formats with the same arithmetic as boxes. In COCO, polygon points are pixels. In YOLO segmentation they are fractions. To rasterise a polygon, draw it into a mask:
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 mask has shape (480, 640), which is height first. Because outline=1 is set, edge pixels count as inside, so the sum is slightly larger than the 5000 pixels in the COCO area field. Expect a gap of this kind when you compare rasterised area with a stored area.
Common errors
Most format bugs come from a short list:
- Treating COCO
[x, y, w, h]as[x1, y1, x2, y2]. Boxes then look too large and run off the image. - Passing absolute pixels to a trainer that expects normalised values, or the reverse.
- Using COCO category ids directly as YOLO class indices. If COCO ids start at 1, every class is off by one.
- Reading the image size from the annotation file instead of the image. A rotated photo with an EXIF orientation tag can have swapped width and height in one place and not the other.
- Mishandling VOC's 1-based pixel convention, which shifts every box by one pixel.
- Rounding too coarsely. Six decimal places is enough for YOLO files on large images.
A validation check catches the first two kinds immediately:
def check_box(bbox, img_w, img_h):
x, y, w, h = bbox
problems = []
if w <= 0 or h <= 0:
problems.append("non-positive size")
if x < 0 or y < 0 or x + w > img_w or y + h > img_h:
problems.append("box extends outside image")
return problems
print(check_box([600, 40, 100, 50], 640, 480))This prints ['box extends outside image'], because 600 + 100 is 700, past the 640-pixel width.
Choosing a format
Pick the format your training framework reads natively, and keep one master copy in a richer format. COCO is a good master because it holds boxes, polygons, areas and crowd flags in one file. YOLO text files are easy to generate on the fly from the master. VOC mainly matters when you inherit older datasets or tools.
Exercise
A YOLO line for a 400 by 200 image reads 0 0.5 0.5 0.25 0.5. What is the equivalent COCO bbox, and what would a VOC reader see for xmin, ymin, xmax and ymax, assuming 0-based exporter values?
Show answer
Width is 0.25 × 400 = 100 pixels and height is 0.5 × 200 = 100 pixels. The centre is at (200, 100), so the top-left corner is (200 − 50, 100 − 50) = (150, 50). The COCO bbox is [150, 50, 100, 100]. VOC with 0-based values gives xmin 150, ymin 50, xmax 250, ymax 150.
Exercise
After converting a COCO dataset, every YOLO class index is one higher than your trainer expects, and the last class raises an out-of-range error. What is the most likely cause, and how do you fix it?
Show answer
The converter used COCO category_id values, which start at 1, as YOLO class indices, which must start at 0. Build a mapping from the sorted category ids to positions 0 to N−1, as cat_index does in coco_to_yolo, and write the class names in that same order.