Sub topic 1
Representing boxes: corners, width-height, and normalization
Prerequisites
This chapter assumes you can work with Python lists and tuples. You should know that an object detector outputs a box, a class label, and a confidence score for each object it finds. You should also know what precision and recall mean for classification.
Two ways to store a box
A bounding box is an axis-aligned rectangle around an object. Two formats are common:
- Corners:
(x1, y1, x2, y2), the top-left and bottom-right points. - Width-height:
(x, y, w, h), the top-left point plus the box size.
Convert between them with x2 = x + w and y2 = y + h. Check which format each dataset uses before comparing boxes. COCO stores boxes as (x, y, w, h), while Pascal VOC uses corner coordinates, often with 1-based pixel indices.
Normalization
Normalized coordinates divide each value by the image size, so every value falls between 0 and 1. A pixel x-value from a 640-pixel-wide image becomes x / 640. Compare boxes only within one coordinate system. Mixing normalized and pixel boxes produces wrong IoU values without any error message.
Intersection over Union
Intersection over Union (IoU) is the overlap area divided by the combined area of both boxes. It is 0 for disjoint boxes and 1 for identical boxes.
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
print(iou((0, 0, 10, 10), (5, 5, 15, 15))) # 25 / 175 = 0.142857...Duplicate detections and non-maximum suppression
A detector often outputs several overlapping boxes for one object. Non-maximum suppression (NMS) keeps the highest-scoring box, removes the other boxes of the same class whose IoU with it exceeds a threshold such as 0.5, and then repeats with the next highest-scoring box.
Matching detections to ground truth
Sort detections by score, highest first. For each detection, find the unmatched ground-truth box of the same class with the highest IoU. If that IoU meets the threshold, the detection is a true positive (TP), and that ground-truth box is marked as matched. Otherwise, the detection is a false positive (FP). A ground-truth box that no detection matches is a false negative (FN).
Exercise
Boxes a = (0, 0, 10, 10) and b = (0, 0, 5, 10) are given in corner format. What is their IoU?
Show answer
The intersection is 5 × 10 = 50. The union is 100 + 50 − 50 = 100. The IoU is 50 / 100 = 0.5.