Sub topic 5
Drawing and storing bounding boxes
A bounding box is the smallest axis-aligned rectangle that contains one object. It is the most common label for object detection, and many segmentation workflows start from boxes. This chapter covers how to draw boxes consistently, how to store them, how to convert between the two main conventions, and how to catch common errors before training.
This chapter assumes you know basic Python, can read JSON, and have read the previous chapter on pixel coordinates and normalisation. In particular, you should know that the origin is the top-left pixel and that y increases downward.
What a box encodes
A box answers two questions about an object: where is it, and how large is it. Four numbers are enough to describe a box. Different tools pick different four-number combinations, and the mix-up between them is the main source of silent bugs.
| Convention | Numbers | Units | Used by |
|---|---|---|---|
| xyxy (corners) | x_min, y_min, x_max, y_max | pixels | Pascal VOC, many model APIs |
| xywh (top-left + size) | x_min, y_min, width, height | pixels | COCO |
| cxcywh (centre + size) | x_center, y_center, width, height | normalised 0 to 1 | YOLO |
Every box also has a class label, so one stored annotation is really five or more values. Datasets often add flags such as iscrowd, occluded or truncated.
The three conventions describe the same rectangle. Converting between them is arithmetic, but a mistake produces plausible-looking boxes that are shifted or mis-sized. The training run does not fail. It just learns worse.
Drawing boxes consistently
Consistency matters more than any single rule. A model learns the average behaviour of your annotators. If one person draws loose boxes and another draws tight ones, the model sees noisy targets and its localisation accuracy suffers.
Agree on these rules before labelling starts, and write them into your guidelines:
- Tight fit. The box edges touch the outermost visible pixels of the object. Leave no deliberate margin.
- Visible extent or full extent. Decide whether to box only the visible part of an occluded object or to estimate its full extent. Visible-only is easier to label consistently. Full-extent is useful when you need to reason about hidden objects. Pick one and apply it to every class.
- Truncated objects. When an object is cut off by the image edge, box the visible part and stop at the image border. Do not place the edge outside the image.
- Thin parts. Decide whether things such as antennas, tails or poles count as part of the object. Parts that are hard to box consistently usually should be excluded.
- Minimum size. Set a smallest box, for example 8 by 8 pixels. Below that size, annotators disagree by more than the object's size, and the labels stop being useful.
- One box per instance. Two adjacent cars get two boxes, even if the boxes overlap. Overlapping boxes are normal and are not an error.
Pixel edges and off-by-one
A box is defined on a pixel grid, so you must decide whether x_max is the last pixel inside the object or the first pixel outside it. COCO and YOLO both treat boxes as continuous regions, so width is x_max - x_min, not x_max - x_min + 1. Pascal VOC historically used inclusive, 1-based pixel indices. The previous chapter explains the origin. For boxes, the practical lesson is to convert once at the boundary of your pipeline and keep one internal convention after that.
Storing boxes: COCO
COCO stores all annotations for a dataset in one JSON file. Each box is an entry in the annotations list, linked to an image and a category by integer IDs.
{
"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
}
]
}The bbox is [x_min, y_min, width, height] in pixels. This box spans x from 50 to 150 and y from 40 to 90. Points to remember:
areais the area of the segmentation mask when there is one, not alwayswidth * height. For a pure box dataset, you can set it to the box area.iscrowd: 1marks a group of objects, such as a crowd of people, that is labelled as one region. Evaluation code treats these regions specially, so do not use the flag as a general "hard example" marker.- Images with no objects have no entries in
annotations. They still belong inimages, and they are valuable as negative examples.
Storing boxes: YOLO
YOLO stores one text file per image, with the same base name as the image. Each line is one box:
class_id x_center y_center width heightAll four coordinates are normalised by the image width and height, so they lie between 0 and 1. The class ID is a zero-based integer defined in a separate class-names file. An image with no objects gets an empty text file, or no file, depending on the tool you train with. Check its documentation.
Normalised coordinates survive resizing. If you scale an image from 640 by 480 to 320 by 240, the same label file still fits. Pixel-based formats need rescaling in that case.
Converting between conventions
This function converts a COCO box to YOLO. The centre is the top-left corner plus half the size, and then every value is divided by the image dimension.
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))For the example box in a 640 by 480 image, the result is about (0.15625, 0.1354, 0.15625, 0.1042). Note that width is divided by the image width and height by the image height. Dividing both by the same value is a classic bug that only shows up on non-square images.
The reverse direction is just as short. Going back to pixel corners lets you draw the box or compute IoU:
def yolo_to_xyxy(box, img_w, img_h):
xc, yc, w, h = box
x_min = (xc - w / 2) * img_w
y_min = (yc - h / 2) * img_h
x_max = (xc + w / 2) * img_w
y_max = (yc + h / 2) * img_h
return x_min, y_min, x_max, y_max
corners = yolo_to_xyxy((0.15625, 0.1354166667, 0.15625, 0.1041666667), 640, 480)
print(tuple(round(v, 2) for v in corners))This prints (50.0, 40.0, 150.0, 90.0), which matches the original box. A round trip that returns the starting values is the cheapest correctness test for any converter you write.
Rounding and precision
YOLO files store floats, usually with five or six decimals. At six decimals, the error on a 4000-pixel-wide image is far below one pixel, so rounding is harmless. Rounding to two decimals is not. On a 1920-pixel image, 0.01 is 19 pixels. Keep at least five decimals.
Validating boxes
Most box errors are mechanical: a swapped coordinate, a box outside the image, or a conversion that used the wrong image size. A short script finds them all before they reach training.
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))The example box ends at x = 700, beyond the 640-pixel width, so the output is ['box extends outside image'].
A box that is only slightly outside the image is usually an annotator dragging past the edge. Clip it rather than discarding it:
def clip_box_xywh(bbox, img_w, img_h):
"""Return a clipped (x, y, w, h) box, or None if nothing is left inside."""
x, y, w, h = bbox
x1, y1 = max(0, x), max(0, y)
x2, y2 = min(img_w, x + w), min(img_h, y + h)
if x2 <= x1 or y2 <= y1:
return None
return x1, y1, x2 - x1, y2 - y1
print(clip_box_xywh([600, 40, 100, 50], 640, 480))This prints (600, 40, 40, 50). A box far outside the image returns None, and you should inspect it by hand, because a large error usually means a wrong image size or a swapped axis.
Other checks worth adding to the same script:
- Every
image_idandcategory_idin an annotation exists in the file. - No two annotations on one image are exact duplicates. Duplicates inflate the object count and confuse training.
- Boxes smaller than your minimum size are flagged for review.
- Box aspect ratios are plausible for the class. A "person" box 200 pixels wide and 5 tall is probably wrong.
Comparing boxes with IoU
Intersection over union (IoU) measures how well two boxes agree. It is the intersection area divided by the union area, and it ranges from 0 (no overlap) to 1 (identical). You can use it to compare two annotators on the same object, or a model prediction against a label.
def box_iou(a, b):
"""Boxes in (x_min, y_min, x_max, y_max) format."""
ix1, iy1 = max(a[0], b[0]), max(a[1], b[1])
ix2, iy2 = min(a[2], b[2]), min(a[3], b[3])
inter = max(0, ix2 - ix1) * max(0, iy2 - iy1)
area_a = (a[2] - a[0]) * (a[3] - a[1])
area_b = (b[2] - b[0]) * (b[3] - b[1])
union = area_a + area_b - inter
return inter / union if union > 0 else 0.0
print(box_iou((50, 40, 150, 90), (60, 45, 160, 95)))Two 100 by 50 boxes shifted by (10, 5) overlap in a 90 by 45 region. That gives an intersection of 4050, a union of 5950 and an IoU of about 0.68. A shift of only 10 pixels already drops IoU well below 1, which shows how sensitive IoU is for small boxes. The chapter on agreement metrics covers how to turn these scores into dataset-level statistics.
Common errors
| Symptom | Likely cause |
|---|---|
| All boxes appear shifted down and right | Treating a centre as a top-left corner, or the reverse |
| Boxes correct on square images, wrong on others | Width and height normalised by the same dimension |
| Boxes look stretched after resizing | Pixel coordinates were not rescaled |
| Model detects the wrong class | Class IDs shifted by one (0-based vs 1-based) |
| Boxes rotated or mirrored | Image orientation from EXIF data was not applied before labelling |
The EXIF row deserves attention. Some phone photos store pixels rotated and record the correct orientation in metadata. A viewer applies the rotation, and a loader that ignores it does not. Boxes drawn in one view then land in the wrong place in the other. Normalise orientation once, before labelling, and record the final width and height in the annotation file.
Exercise
A 1000 by 500 pixel image has a COCO box [200, 100, 300, 150]. Give the YOLO line values (xcenter, ycenter, width, height) for it, and say what goes wrong if you divide every value by 1000.
Show answer
The centre is x = 200 + 300/2 = 350 and y = 100 + 150/2 = 175. Normalising gives xcenter = 350/1000 = 0.35, ycenter = 175/500 = 0.35, width = 300/1000 = 0.30 and height = 150/500 = 0.30. If you divide every value by 1000, y_center becomes 0.175 and height becomes 0.15. The box is then half as tall as it should be and sits too high, because the image height is 500, not 1000.
Exercise
Two annotators box the same object as (100, 100, 200, 200) and (110, 100, 210, 200) in xyxy pixels. Compute the IoU.
Show answer
Each box is 100 by 100, so each area is 10000. The intersection runs from x = 110 to 200 and y = 100 to 200, so it is 90 by 100 = 9000. The union is 10000 + 10000 - 9000 = 11000. IoU = 9000 / 11000, which is about 0.82.