Sub topic 1
Representing boxes: corners, width-height, and normalization
Every detection metric starts with a box. Before you can compute Intersection over Union (IoU), match detections to ground truth, or build a precision-recall curve, you need to know exactly what four numbers describe a box and in what units. Most wrong mAP numbers in practice do not come from the metric. They come from a box in one format being compared against a box in another.
This chapter covers the common box formats, how to convert between them, what normalization changes, and the edge cases that cause silent errors.
Prerequisites
This chapter assumes you have:
- Basic Python, including tuples, lists, and functions.
- A working idea of what an object detector outputs: a box, a class label, and a confidence score for each detection.
- A rough idea of precision and recall from classification. You do not need them yet in this chapter.
You do not need any library. All code here uses plain Python.
What a box is
An axis-aligned bounding box is a rectangle whose sides are parallel to the image axes. Four numbers describe it. The rectangle is not rotated, so there is no angle.
Image coordinates follow a convention that differs from school mathematics:
- The origin (0, 0) is the top-left corner of the image.
- x grows to the right.
- y grows downward.
So "top" means a smaller y value, and "bottom" means a larger y value. The corner with the smallest x and y is the top-left corner. The corner with the largest x and y is the bottom-right corner.
Common box formats
Three formats cover almost every dataset and framework you will meet.
| Format | Four numbers | Used by (typical) |
|---|---|---|
| Corners (xyxy) | x_min, y_min, x_max, y_max | Pascal VOC annotations, many PyTorch detection models |
| Top-left plus size (xywh) | x_min, y_min, width, height | COCO annotation files |
| Center plus size (cxcywh) | x_center, y_center, width, height | YOLO label files (normalized), DETR-style models |
The names are conventions, not standards. A library can use "xywh" to mean center-based boxes. Always read the documentation for the exact order and meaning of the four numbers, and test it on one known box.
The IoU code in this tutorial uses the corner format (x1, y1, x2, y2) with x1 < x2 and y1 < y2. Convert everything to this format before you compare boxes.
Using xyxy as the hub means you write two pairs of converters instead of three. It also means the metric code only needs to understand one format.
Converting between formats
The conversions are short, but each one has a place where an off-by-one or a mixed-up order can hide.
def xywh_to_xyxy(box):
x, y, w, h = box
return (x, y, x + w, y + h)
def xyxy_to_xywh(box):
x1, y1, x2, y2 = box
return (x1, y1, x2 - x1, y2 - y1)
def cxcywh_to_xyxy(box):
cx, cy, w, h = box
return (cx - w / 2, cy - h / 2, cx + w / 2, cy + h / 2)
def xyxy_to_cxcywh(box):
x1, y1, x2, y2 = box
return ((x1 + x2) / 2, (y1 + y2) / 2, x2 - x1, y2 - y1)
box = (10, 20, 50, 100) # xyxy: 40 wide, 80 tall
print(xyxy_to_xywh(box)) # (10, 20, 40, 80)
print(xyxy_to_cxcywh(box)) # (30.0, 60.0, 40, 80)
print(cxcywh_to_xyxy(xyxy_to_cxcywh(box))) # (10.0, 20.0, 50.0, 100.0)
print(xywh_to_xyxy(xyxy_to_xywh(box))) # (10, 20, 50, 100)A round trip, as in the last two lines, is a cheap test. If converting forward and back does not return the original box, one of your functions is wrong.
Normalization
A coordinate can be in pixels or in a fraction of the image size. Normalized coordinates divide x values by the image width and y values by the image height, so they fall between 0 and 1.
YOLO label files are the usual example. A box is stored as class cx cy w h, each divided by the image dimensions. A normalized box in a 640 by 480 image converts back like this:
def denormalize(box, img_w, img_h):
"""Scale a normalized (a, b, c, d) box to pixels.
Works for any format, because x-like values use the width
and y-like values use the height. The order must be x, y, x, y
(xyxy) or x, y, w, h (xywh and cxcywh).
"""
a, b, c, d = box
return (a * img_w, b * img_h, c * img_w, d * img_h)
def normalize(box, img_w, img_h):
a, b, c, d = box
return (a / img_w, b / img_h, c / img_w, d / img_h)
norm = (0.5, 0.5, 0.25, 0.5) # cxcywh, normalized
pixels = denormalize(norm, 640, 480)
print(pixels) # (320.0, 240.0, 160.0, 240.0)
print(cxcywh_to_xyxy(pixels)) # (240.0, 120.0, 400.0, 360.0)
print(normalize(pixels, 640, 480)) # (0.5, 0.5, 0.25, 0.5)The denormalize function works for all three formats because in each of them the first and third numbers are horizontal quantities and the second and fourth are vertical ones. That holds for xyxy (x, y, x, y) and for xywh and cxcywh (x, y, w, h), where w is horizontal and h is vertical.
Does normalization change IoU?
IoU is a ratio of areas, so a uniform scale cancels out. But normalization divides x by the width and y by the height, and those can differ. If the image is not square, this is a non-uniform scale. Area scales by 1 / (W * H) for every region, so intersection and union both scale by the same factor and the ratio is unchanged.
So IoU is the same in pixels and in normalized coordinates, as long as both boxes use the same image size. You can check it:
def iou(a, b):
"""IoU of two boxes given as (x1, y1, x2, y2) with x1 < x2 and y1 < y2."""
ix1 = max(a[0], b[0])
iy1 = max(a[1], b[1])
ix2 = min(a[2], b[2])
iy2 = min(a[3], b[3])
inter = max(0.0, ix2 - ix1) * max(0.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
a = (100, 50, 300, 250)
b = (150, 100, 350, 300)
W, H = 640, 480
print(iou(a, b)) # 0.39130434782608703
print(iou(normalize(a, W, H), normalize(b, W, H))) # same value, up to roundingNormalization still matters for other reasons. The two boxes must be in the same units. A pixel-space ground truth compared with a normalized prediction gives an IoU of 0 or a meaningless value, with no error raised.
Some size-based metrics also depend on pixels. COCO splits objects into small, medium, and large by area in pixels (below 32 squared, between 32 squared and 96 squared, above 96 squared). If you evaluate on normalized boxes, those buckets are wrong.
Resizing and letterboxing
Detectors usually run on a resized copy of the image. A model might take 640 by 640 input, so the image is scaled and often padded (letterboxed) to keep its aspect ratio. The model's output is in the coordinates of that resized, padded input.
To compare against ground truth, which is in original image coordinates, you must undo the transform:
- Subtract the padding offset from x and y.
- Divide by the scale factor.
- Clip to the original image bounds.
def undo_letterbox(box, scale, pad_x, pad_y, img_w, img_h):
"""Map an xyxy box from letterboxed input space to original pixels."""
x1, y1, x2, y2 = box
x1 = (x1 - pad_x) / scale
x2 = (x2 - pad_x) / scale
y1 = (y1 - pad_y) / scale
y2 = (y2 - pad_y) / scale
x1 = min(max(x1, 0.0), img_w)
x2 = min(max(x2, 0.0), img_w)
y1 = min(max(y1, 0.0), img_h)
y2 = min(max(y2, 0.0), img_h)
return (x1, y1, x2, y2)
# Original image 800x600, resized by 0.8 to 640x480, padded 80 px top and bottom.
print(undo_letterbox((100, 180, 300, 380), 0.8, 0, 80, 800, 600))
# (125.0, 125.0, 375.0, 375.0)Forgetting this step shifts every prediction. IoU then drops for all boxes, and the mAP is lower than the model deserves. Because the error is systematic, it looks like a weak model rather than a bug.
Edge cases and silent errors
Several mistakes produce plausible numbers instead of crashes.
- Wrong format. Treating an xywh box as xyxy makes the "x2, y2" values smaller than they should be, often smaller than x1 and y1. The overlap code then returns 0 or a wrong area.
- Swapped coordinates. A box with
x1 > x2has a negative width. In the IoU code, a negative area for one box can shrink the union and push IoU above its true value, or even above 1. Normalize inputs withminandmax, or reject them. - Degenerate boxes. A box with zero width or height has zero area. The
union > 0guard iniouavoids a division by zero when both boxes are degenerate. Decide up front whether to drop such boxes from ground truth. - Out-of-bounds boxes. Model outputs can extend past the image. Clip them to the image before evaluation. A ground truth box and a prediction clipped differently will disagree at the borders.
- Integer pixel conventions. Some annotation tools treat coordinates as pixel indices, so a box from pixel 10 to pixel 19 includes both ends and is 10 pixels wide. Others treat coordinates as edges, so the same extent is 9 wide. The older Pascal VOC convention adds 1 to widths. Keep one convention across predictions and ground truth.
- Integer division. In Python 3,
/returns a float, socx - w / 2is safe. If you port code that uses//or arrays of integer type, you lose half pixels.
A small validation function catches most of these before they reach the metric:
def validate_xyxy(box, img_w=None, img_h=None):
x1, y1, x2, y2 = box
if x2 <= x1 or y2 <= y1:
raise ValueError(f"empty or inverted box: {box}")
if img_w is not None and (x1 < 0 or x2 > img_w):
raise ValueError(f"box exceeds image width: {box}")
if img_h is not None and (y1 < 0 or y2 > img_h):
raise ValueError(f"box exceeds image height: {box}")
return box
validate_xyxy((10, 20, 50, 100), 640, 480)
try:
validate_xyxy((50, 20, 10, 100))
except ValueError as e:
print(e) # empty or inverted box: (50, 20, 10, 100)Why this matters for mAP
The later chapters build on boxes in one consistent format. IoU compares two boxes. Matching uses IoU against a threshold such as 0.5. Precision and recall come from the matches. Average precision comes from those. A box format error at the start changes every IoU, so every later number is wrong, and no later step reveals it.
Exercise
A ground truth box in a COCO annotation file is [100, 40, 60, 80], in xywh format. A detector returns the box (110, 50, 150, 110) in xyxy format. What are the ground truth box in xyxy format, and the IoU of the two boxes?
Show answer
The ground truth in xyxy is (100, 40, 160, 120), since x2 = 100 + 60 and y2 = 40 + 80. The intersection runs from x = 110 to 150 and y = 50 to 110, so it is 40 wide and 60 tall, an area of 2400. The ground truth area is 60 80 = 4800. The detection area is 40 60 = 2400. The union is 4800 + 2400 - 2400 = 4800. The IoU is 2400 / 4800 = 0.5. The detection lies entirely inside the ground truth.
Exercise
A model works on a 640 by 640 letterboxed input of an image that is 1280 wide and 720 tall. The image is scaled by 0.5, giving 640 by 360, and padded by 140 pixels at the top and bottom. The model predicts the box (200, 240, 400, 400) in input coordinates. What is this box in original image pixels?
Show answer
Subtract the padding from y, then divide all values by the scale 0.5. For x: 200 / 0.5 = 400 and 400 / 0.5 = 800. For y: (240 - 140) / 0.5 = 200 and (400 - 140) / 0.5 = 520. The box is (400, 200, 800, 520). It is within the 1280 by 720 image, so clipping changes nothing.
Exercise
Why is IoU unchanged when you normalize two boxes by the image width and height, but the COCO small, medium, and large buckets would be wrong on normalized boxes?
Show answer
IoU is a ratio. Normalization multiplies every area by the same factor 1 / (W * H), so the factor cancels between intersection and union. The size buckets compare an absolute area in pixels to fixed thresholds (32 squared and 96 squared). A normalized area is a fraction between 0 and 1, so it would fall below the small threshold for every object.