Object Detection with Bounding Boxes
Detection is two problems stapled together: what is it, and where exactly is it. This is the "where" half — a regression problem with IoU sitting at the center of both its loss and its grading.
Predicted Box Offset
offsets from ground truth — all sliders to 0 means a perfect prediction
Predicted vs Ground Truth
—Loss as IoU Improves
Metrics
Overview
What a detector outputs and how it is trained
An object detector's output head does two jobs per candidate region: classify what is there. And regress four counts describing where it is precisely. Often a box centre, width and height. Or the offsets needed to nudge a fixed anchor box onto the real object. The sorting half is an ordinary softmax problem. The localisation half is what this module is about. And IoU sits at the centre of it twice: once inside the training loss. And again in how the net gets graded afterward.
This page covers the two box forms (corner and centre forms), how anchor boxes work, what the regression target really is. And the IoU-based loss that replaced smooth-L1 in most modern designs. The visualisation above lets you drag predicted and ground-truth boxes and watch IoU, the sorting label. And the loss value update in real time.
Anchor boxes are the starting point: a grid of fixed rectangles at multiple scales and aspect ratios, each one a hypothesis the net refines. The regression head predicts small offsets (dx, dy, dw, dh) relative to each anchor rather than absolute coordinates. It keeps the counts small and training stable. At test time, non-max suppression collapses overlapping predictions into one box per object, with IoU to decide which boxes are duplicates.
Detection is two problems stapled together: what is it, and where exactly is it.
In this guide
- What a detector outputs and how it is trained
- IoU as loss, IoU as grade
- Sorting says what. Detection says what and where
- The hard parts
- Two families of detector
- Four counts, and all that depends on them
- Things to try
- Summing up
- How detections are scored
- Annotation, and where projects really fail
- Questions people ask
- Recap in one screen
Object Detection with Bounding Boxes: A Practical Guide
Classification tells you what. A regression head tells you where.
What a detector outputs and how it is trained
An object detector's output head does two jobs per candidate region: classify what is there. And regress four counts describing where it is precisely. Often a box centre, width and height. Or the offsets needed to nudge a fixed anchor box onto the real object. The sorting half is an ordinary softmax problem. The localisation half is what this module is about. And IoU sits at the centre of it twice: once inside the training loss. And again in how the net gets graded afterward.
This page covers the two box forms (corner and centre forms), how anchor boxes work, what the regression target really is. And the IoU-based loss that replaced smooth-L1 in most modern designs. The visualisation above lets you drag predicted and ground-truth boxes and watch IoU, the sorting label. And the loss value update in real time.
Anchor boxes are the starting point: a grid of fixed rectangles at multiple scales and aspect ratios, each one a hypothesis the net refines. The regression head predicts small offsets (dx, dy, dw, dh) relative to each anchor rather than absolute coordinates. It keeps the counts small and training stable. At test time, non-max suppression collapses overlapping predictions into one box per object, with IoU to decide which boxes are duplicates.
IoU as loss, IoU as grade
A natural localization loss is simply 1 − IoU between the predicted box and the ground truth box: 0 when they coincide just, approaching 1 as they stop overlapping at all. At test time, the same IoU count gets a other job. A detection is often scored as a true positive just if its IoU with the matching ground truth box clears a threshold, conventionally 0.5 under the PASCAL VOC convention. A box can be visibly "close" and still count as a complete miss if it doesn't clear that bar.
Sorting says what. Detection says what and where
A sorter answers one question about a whole pic. A detector answers two questions about each object in it: what is it. And where is it — expressed as a rectangle.
A bounding box is four counts. And there are three common conventions:
| Format | Numbers | Used by |
|---|---|---|
(x_min, y_min, x_max, y_max) | Two corners | Pascal VOC, most libraries |
(x, y, width, height) | Top-left corner and size | COCO |
(cx, cy, w, h) normalised | Centre and size, 0–1 | YOLO |
Mixing them up is the single most common bug in detection code. And it fails quietly: boxes appear in roughly plausible places and the metrics are mysteriously poor. Always check which convention a dataset and a net each expect.
Each box also carries a class label and a confidence score. So one detection is: a rectangle, a name. And a count between 0 and 1.
The hard parts
Detection is much harder than sorting for reasons that are structural rather than incidental.
The count of outputs varies. A network gives a fixed-size output. An pic may hold zero objects or fifty. Each detector design is, at heart, a way of handling that mismatch.
Objects vary enormously in scale. A pedestrian may be 20 pixels tall or 500. A single feature map has one effective scale. It is why detectors predict from a few feature maps at once.
Localisation and sorting are other tasks with other losses, trained jointly. Often a cross-entropy for the class and a regression loss (smooth L1, or a direct IoU loss) for the coordinates.
The background dominates. Most candidate positions hold nothing at all, often by a thousand to one. That extreme imbalance is why focal loss. Which down-weights easy, well-classified cases — was invented for detection namely.
Two families of detector
Two-stage detectors (R-CNN, Fast R-CNN, Faster R-CNN) first propose regions that might hold something, then classify and refine each proposal. More exact, historically slower. And still preferred where precision matters more than latency.
One-stage detectors (YOLO, SSD, RetinaNet) predict boxes and classes right from the feature maps in a single pass. Much faster, and the score gap has largely closed. Which is why most production systems now use them.
Anchor-based versus anchor-free is the other axis. Anchor-based ways place a set of predefined box shapes at each position and learn offsets from them. Anchor-free ways (FCOS, CenterNet, recent YOLO versions) predict boxes right, removing the anchor hyperparameters that were always awkward to tune.
DETR and its successors take a third route fully, treating detection as set prediction with a transformer and removing the need for non-max suppression — conceptually cleaner. And slower to train.
Four counts, and all that depends on them
A bounding box is four counts. And almost each detection bug comes from a disagreement about which four. This works through the formats, the conversions, IoU, non-max suppression and the loss -- all of it arithmetic you can check line by line.
Another subtle disagreement is whether coordinates refer to pixel indices or pixel edges.
IoU measures how well a predicted box overlaps the ground truth. And the max/min pattern makes it straightforward to compute.
NMS removes near-duplicate detections by keeping the most confident box and suppressing overlapping ones.
Lowering the threshold suppresses more boxes. Check the two settings side by side.
The threshold trades duplicate removal against the risk of merging genuinely distinct objects.
Detection also needs a regression loss on the box coordinates. And the standard choices each have a weakness.
Things to try
- Read the starting position. The predicted box is offset and undersized relative to the ground truth. Overlap is low, loss is close to 1. And it does not count as a match.
- Drag dx and dy toward 0. IoU climbs as the boxes line up spatially. And the loss falls in lockstep. This is the gradient signal a real localization head would be trained on.
- Now close dw and dh too. Position alone isn't enough. A box in the right place but the wrong size still loses IoU on both sides.
- Watch the Match readout as IoU crosses 0.5. It flips from a miss to a match at just that edge, still though the loss was now improving smoothly well before the flip.
Summing up
1 − IoU is a smooth, differentiable signal that a network can really be trained against. Whether a detection counts as correct at test time is not smooth at all. It's a hard threshold on that same IoU count. A net can make genuine, loss-reducing progress on a box for a long stretch before that progress ever shows up as a correct detection in your metrics.
How detections are scored
IoU (Intersection over Union) measures how well a predicted box overlaps a true one:
IoU = area of overlap / area of union
It runs from 0 (no overlap) to 1 (perfect). A prediction often counts as correct if its IoU with a ground-truth box of the same class exceeds a threshold. 0.5 is the classic choice.
Non-max suppression is the cleanup step. A detector often fires a few times on the same object. So NMS keeps the highest-scoring box and discards any box overlapping it by more than a threshold. Without it, each object is reported three or four times.
mAP (mean Average Precision) is the standard headline metric. For each class, sweep the confidence threshold, build a precision-recall curve, take its area. Then average across classes. COCO's version averages more over IoU thresholds from 0.5 to 0.95. It rewards precise localisation rather than approximate boxes.
The real reading: mAP@0.5 tells you whether objects are found. MAP@0.5:0.95 tells you whether the boxes are tight.
Annotation, and where projects really fail
Detection datasets are costly. And the quality of the boxes sets the ceiling on the net.
- Be consistent about tightness. Does the box include the shadow? The handle? The occluded part? Write the rule down before annotating, since a net trained on inconsistent boxes learns the inconsistency.
- Label each instance. A missed object is trained as background. It actively teaches the net not to detect it.
- Decide on occlusion and truncation rules for objects half out of frame.
- Watch class imbalance. Rare classes need either more cases or a weighted loss.
- Match augmentation to the boxes. Flipping, rotating or cropping an pic must transform the coordinates too. Libraries such as Albumentations do this correctly. And hand-rolled pipelines often do not.
A few hundred well-annotated pics plus a pretrained backbone will often beat thousands of sloppy ones.
Questions people ask
Which detector should I start with? A recent YOLO or a torchvision Faster R-CNN, fine-tuned from pretrained weights. Training a detector from scratch needs far more data than most projects have.
How much data do I need? With transfer learning, a few hundred annotated pics per class gets a usable net. Thousands for production reliability.
What IoU threshold should I use for NMS? 0.5 is typical. Less it if duplicates persist, raise it if genuinely overlapping objects are being suppressed.
Why are small objects missed? Since they occupy few pixels in the feature maps used for prediction. Feature pyramids, more-resolution input and tiled test time are the standard replies.
What is the gap from segmentation? Detection gives boxes. Semantic segmentation labels each pixel. Instance segmentation gives per-object masks. Boxes are cheaper to annotate and often enough.
How do I detect objects in video? Detect per frame, then associate detections across frames with a tracker (SORT, ByteTrack) to give each object a persistent identity.
Recap in one screen
- Detection outputs a box, a class and a confidence for each object present.
- Box formats differ between datasets — corners, corner-plus-size. And scaled centre-plus-size.
- Two-stage detectors propose then classify. One-stage detectors predict right and are now the real default.
- IoU measures overlap, NMS removes duplicates. And mAP is the headline metric.
- Annotation consistency sets the ceiling. Augmentation must transform the boxes as well as the pic.