Sub topic 1
What Object Detection Asks of a Model
Prerequisites
This chapter assumes you know:
- Basic Python: functions, tuples, and loops
- Images as grids of pixels, with a width and a height
- The idea that a neural network learns by minimizing a loss function
What object detection asks of a model
Image classification answers one question: what is in this image? Object detection asks three: what objects are present, where each one is, and how confident the model is about each one.
A detector therefore returns a list of detections. Each detection holds a class label, a confidence score between 0 and 1, and a bounding box, which is a rectangle that encloses the object.
Bounding boxes: xyxy, xywh and normalized YOLO coordinates
Libraries describe the same rectangle in different ways:
| Format | Values | Meaning |
|---|---|---|
| xyxy | x1, y1, x2, y2 | Top-left and bottom-right corners, in pixels |
| xywh | x_center, y_center, w, h | Center point and size, in pixels |
| YOLO | x_center, y_center, w, h | Same as xywh, divided by image width and height so every value is from 0 to 1 |
Converting from xywh to xyxy uses x1 = xcenter - w / 2 and x2 = xcenter + w / 2, with the same rule for y. Dividing by the image size gives normalized YOLO coordinates. Always check which format a function expects. Mixing them is a common source of boxes that appear in the wrong place.
Measuring overlap with intersection over union
Intersection over union (IoU) is the overlap area of two boxes divided by the area they cover together. It ranges from 0 (no overlap) to 1 (identical boxes).
def iou(a, b):
# Boxes are (x1, y1, x2, y2) in the same coordinate system.
ax1, ay1, ax2, ay2 = a
bx1, by1, bx2, by2 = b
ix1, iy1 = max(ax1, bx1), max(ay1, by1)
ix2, iy2 = min(ax2, bx2), min(ay2, by2)
inter = max(0, ix2 - ix1) * max(0, iy2 - iy1)
union = (ax2 - ax1) * (ay2 - ay1) + (bx2 - bx1) * (by2 - by1) - inter
return inter / union if union > 0 else 0.0
print(iou((0, 0, 10, 10), (5, 5, 15, 15))) # 25 / 175 = 0.142857...IoU is the standard way to decide whether a predicted box matches a labeled box. A common threshold is 0.5.
The YOLO idea: detection in a single pass
YOLO (You Only Look Once) is a single-stage detector. One forward pass through the network predicts boxes, objectness, and class scores for the whole image at once. Earlier two-stage detectors first proposed candidate regions and then classified each one, which is slower.
Because the network produces many candidate boxes per image, overlapping duplicates are common. Removing them is the job of non-maximum suppression, which the next chapter covers.
Exercise
A box has xyxy coordinates (10, 20, 50, 60). What are its width and height in pixels?
Show answer
Width is 50 - 10 = 40 and height is 60 - 20 = 40.