Sub topic 2
Bounding boxes: xyxy, xywh and normalized YOLO coordinates
This chapter assumes you know basic Python, can treat an image as an array of pixels (rows, then columns), and know that a detector outputs boxes with class labels. A box is a rectangle that encloses an object. Almost every detection bug that is not a model problem is a box-format problem, so this chapter is worth getting exactly right.
Why formats matter
A bounding box is four numbers. The trouble is that different tools give the same four numbers different meanings. A box written as (100, 50, 300, 250) can be a corner pair or a position plus a size. If you read it the wrong way, the code still runs. The boxes are simply drawn in the wrong place, and your metrics drop without any error message.
Three conventions cover most of what you will meet with YOLO:
| Name | Values | Units | Origin of the box |
|---|---|---|---|
| `xyxy` | x1, y1, x2, y2 | pixels | top-left and bottom-right corners |
| `xywh` | x, y, w, h | pixels | top-left corner plus width and height (COCO style) |
| `cxcywh` (YOLO) | xc, yc, w, h | normalized 0 to 1 | center plus width and height |
Some libraries use the name xywh for a center-based box, and others use it for a top-left-based box. Ultralytics, for instance, exposes box.xywh as center-based. COCO JSON files use top-left-based [x, y, w, h]. Always check the documentation of the tool you are using, and never rely on the name alone.
The pixel coordinate system
Image coordinates start at the top-left corner. The x axis runs right and the y axis runs down. This differs from a school graph, where y runs up.
An image array has shape (height, width, channels). The x coordinate indexes columns and the y coordinate indexes rows, so a pixel at (x, y) is read as image[y, x]. Mixing up this order is a classic mistake.
Converting between formats
All conversions are small arithmetic steps. The key relations are:
- Width is
x2 - x1and height isy2 - y1. - The center is
(x1 + x2) / 2and(y1 + y2) / 2. - Normalizing divides x values and widths by the image width, and y values and heights by the image height.
Here is a complete set of converters. They work on single boxes given as tuples.
def xyxy_to_xywh(box):
# Corners -> top-left corner plus size (COCO style), all in pixels.
x1, y1, x2, y2 = box
return x1, y1, x2 - x1, y2 - y1
def xywh_to_xyxy(box):
x, y, w, h = box
return x, y, x + w, y + h
def xyxy_to_yolo(box, img_w, img_h):
# Pixel corners -> normalized center and size.
x1, y1, x2, y2 = box
xc = (x1 + x2) / 2 / img_w
yc = (y1 + y2) / 2 / img_h
w = (x2 - x1) / img_w
h = (y2 - y1) / img_h
return xc, yc, w, h
def yolo_to_xyxy(box, img_w, img_h):
# Normalized center and size -> pixel corners.
xc, yc, w, h = box
x1 = (xc - w / 2) * img_w
y1 = (yc - h / 2) * img_h
x2 = (xc + w / 2) * img_w
y2 = (yc + h / 2) * img_h
return x1, y1, x2, y2
box = (100, 50, 300, 250)
print(xyxy_to_xywh(box)) # (100, 50, 200, 200)
yolo = xyxy_to_yolo(box, 640, 480)
print([round(v, 4) for v in yolo]) # [0.3125, 0.3125, 0.3125, 0.4167]
print(yolo_to_xyxy(yolo, 640, 480)) # (100.0, 50.0, 300.0, 250.0)The last line shows a round trip. Converting to YOLO format and back should return the original box, apart from floating-point rounding. Round-trip checks like this are a cheap test to put in any data pipeline.
Worked example
Take a 640 by 480 image with a box from (100, 50) to (300, 250).
- Width in pixels: 300 - 100 = 200. Height: 250 - 50 = 200.
- Center in pixels: x = 200, y = 150.
- Normalize x values by 640: xc = 200 / 640 = 0.3125, w = 200 / 640 = 0.3125.
- Normalize y values by 480: yc = 150 / 480 = 0.3125, h = 200 / 480 = 0.4167.
The label line for class 0 is 0 0.3125 0.3125 0.3125 0.4167. Notice that a square box in pixels is not square in normalized units, because the image is not square. This is correct, not a bug.
Why YOLO normalizes
Normalized coordinates are independent of image size. The same label file stays valid if you resize the image from 1920 by 1080 to 640 by 640, because the box covers the same fraction of the picture. This matters because training pipelines routinely resize, pad and augment images.
Normalization also keeps the numbers in a small, stable range, which suits a neural network's regression targets. A model predicting values near 0.3 trains more smoothly than one predicting values near 1,000.
The label format stores one object per line:
# class_id x_center y_center width height (all normalized to 0-1)
0 0.512 0.430 0.200 0.350
1 0.150 0.700 0.100 0.220The class id is an integer, and the other four values are floats. A later chapter covers building whole datasets in this format.
Reading boxes from Ultralytics
Ultralytics result objects expose several views of the same boxes, so you rarely need to convert by hand. For a result r, each box in r.boxes offers these attributes.
| Attribute | Meaning |
|---|---|
| `box.xyxy` | pixel corners in the original image |
| `box.xywh` | pixel center and size in the original image |
| `box.xyxyn` | corners normalized to 0 to 1 |
| `box.xywhn` | center and size normalized to 0 to 1 |
The trailing n stands for normalized. Each attribute is a tensor with one row, so you take element [0], as in box.xyxy[0].tolist().
Edge cases and common errors
Swapped width and height
A frequent error is normalizing x by the image height, or the reverse. On square images this goes unnoticed, so the bug appears only when you meet your first non-square image. Divide x and width by the image width, and y and height by the image height.
Letterboxing and padding
Detectors usually take a fixed square input such as 640 by 640. To keep the aspect ratio, the image is scaled to fit and then padded with gray borders. This is called letterboxing. Boxes predicted in the padded input space must be mapped back to the original image by removing the padding offset and dividing by the scale factor. Ultralytics does this for you in r.boxes.xyxy. If you run a raw exported model yourself, you must do it yourself, or the boxes will be shifted and scaled incorrectly.
Boxes outside the image
Predicted or annotated boxes can extend past the image edge. Clip them to the image before use:
def clip_xyxy(box, img_w, img_h):
x1, y1, x2, y2 = box
return (
min(max(x1, 0), img_w),
min(max(y1, 0), img_h),
min(max(x2, 0), img_w),
min(max(y2, 0), img_h),
)
print(clip_xyxy((-10, 20, 700, 500), 640, 480)) # (0, 20, 640, 480)Degenerate boxes
A box with zero or negative width or height has no area. It comes from annotation mistakes or aggressive clipping. Dividing by its area gives errors or nan values later, for example in IoU. Filter these boxes out when you load a dataset.
Integer pixels versus float pixels
Rounding corners to integers is fine for drawing. Keep floats while you compute overlaps or metrics. A one-pixel rounding error on a 10-pixel-wide box changes its area by about 10 percent.
Pixel-center conventions
Some tools treat a pixel's coordinate as its top-left corner, so a box from 0 to 10 covers 10 pixels. Others treat it as the pixel center, so a box from 0 to 10 covers 11 pixels. The difference is usually one pixel. It rarely matters for training but can matter when you compare numbers with another tool.
Checking your boxes visually
When in doubt, draw. Plotting a few boxes on their images catches format mistakes faster than any number. This sketch uses OpenCV and takes a YOLO label line.
import cv2
def draw_yolo_label(image_path, label_line, out_path):
img = cv2.imread(image_path)
img_h, img_w = img.shape[:2] # shape is (height, width, channels)
cls_id, xc, yc, w, h = label_line.split()
xc, yc, w, h = (float(v) for v in (xc, yc, w, h))
x1 = int((xc - w / 2) * img_w)
y1 = int((yc - h / 2) * img_h)
x2 = int((xc + w / 2) * img_w)
y2 = int((yc + h / 2) * img_h)
cv2.rectangle(img, (x1, y1), (x2, y2), (0, 255, 0), 2)
cv2.putText(img, cls_id, (x1, max(y1 - 5, 12)),
cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0), 2)
cv2.imwrite(out_path, img)
draw_yolo_label("bus.jpg", "0 0.512 0.430 0.200 0.350", "check.jpg")If the green box sits on the object, your conversion is right. If it is shifted by half its size, you mixed up center and corner. If it is stretched, you mixed up width and height.
Why this matters for the next chapter
Intersection over union compares two boxes by their overlap, and it needs both boxes in the same format and the same units. The iou function in the next chapter expects xyxy pixels. Converting first, and only then computing overlap, avoids a whole class of silent errors.
Exercise
An image is 800 pixels wide and 600 pixels high. An object has the pixel corner box (200, 150, 600, 450). Write its YOLO label line for class 2, and say how the normalized width and height compare.
Show answer
Width in pixels is 400 and height is 300. The center is x = 400, y = 300. Normalized: xc = 400 / 800 = 0.5, yc = 300 / 600 = 0.5, w = 400 / 800 = 0.5, h = 300 / 600 = 0.5. The label line is "2 0.5 0.5 0.5 0.5". Both normalized sizes are 0.5 because the box covers half of the image in each direction, even though its pixel width and height differ.
Exercise
A COCO annotation gives [x, y, w, h] = [40, 60, 120, 90] on a 400 by 300 image. Convert it to xyxy pixels and to a YOLO line for class 0. Why would treating it as a center-based box be wrong?
Show answer
COCO boxes are top-left based, so xyxy is (40, 60, 160, 150). The center is (100, 105). Normalized: xc = 100 / 400 = 0.25, yc = 105 / 300 = 0.35, w = 120 / 400 = 0.3, h = 90 / 300 = 0.3. The line is "0 0.25 0.35 0.3 0.3". Reading [40, 60, 120, 90] as a center-based box would place the center at (40, 60) and shift the box up and left by half its width and height, so it would no longer cover the object.