Modules/Computer Vision/ Detection Lab

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.

Overview

Start here

An object detector's output head does two jobs per candidate region: classify what's there, and regress four numbers describing where it is precisely — typically a box center, width and height, or the offsets needed to nudge a fixed anchor box onto the real object. The classification half is an ordinary softmax problem. The localization half is what this module is about, and IoU sits at the center of it twice: once inside the training loss, and again in how the model gets graded afterward.

Predicted Box Offset

40
-30
-20
15

offsets from ground truth — all sliders to 0 means a perfect prediction

Predicted vs Ground Truth

Loss as IoU Improves

Metrics

IoU0.00
Loss (1 − IoU)1.00
Match @ 0.5no

 

Object Detection with Bounding Boxes: A Practical Guide

Classification tells you what. A regression head tells you where.

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 exactly, approaching 1 as they stop overlapping at all. At evaluation time, the same IoU number gets a different job — a detection is usually scored as a true positive only 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.

Classification says what; detection says what and where

A classifier answers one question about a whole image. A detector answers two questions about every object in it: what is it, and where is it — expressed as a rectangle.

A bounding box is four numbers, and there are three common conventions:

FormatNumbersUsed by
(x_min, y_min, x_max, y_max)Two cornersPascal VOC, most libraries
(x, y, width, height)Top-left corner and sizeCOCO
(cx, cy, w, h) normalisedCentre and size, 0–1YOLO

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 model each expect.

Each box also carries a class label and a confidence score, so one detection is: a rectangle, a name, and a number between 0 and 1.

The hard parts

Detection is substantially harder than classification for reasons that are structural rather than incidental.

The number of outputs varies. A network produces a fixed-size output; an image may contain zero objects or fifty. Every detector architecture 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, which is why detectors predict from several feature maps at once.

Localisation and classification are different tasks with different losses, trained jointly — typically 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 contain nothing at all, often by a thousand to one. That extreme imbalance is why focal loss — which down-weights easy, well-classified examples — was invented for detection specifically.

Two families of detector

Two-stage detectors (R-CNN, Fast R-CNN, Faster R-CNN) first propose regions that might contain something, then classify and refine each proposal. More accurate, historically slower, and still preferred where precision matters more than latency.

One-stage detectors (YOLO, SSD, RetinaNet) predict boxes and classes directly from the feature maps in a single pass. Much faster, and the accuracy gap has largely closed — which is why most production systems now use them.

Anchor-based versus anchor-free is the other axis. Anchor-based methods place a set of predefined box shapes at every position and learn offsets from them. Anchor-free methods (FCOS, CenterNet, recent YOLO versions) predict boxes directly, removing the anchor hyperparameters that were always awkward to tune.

DETR and its successors take a third route entirely, treating detection as set prediction with a transformer and removing the need for non-maximum suppression — conceptually cleaner, and slower to train.

Four numbers, and everything that depends on them

A bounding box is four numbers, and almost every 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.

example_01.pyNumPy
Output

Things to try

  1. 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.
  2. 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.
  3. 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.
  4. Watch the Match readout as IoU crosses 0.5. It flips from a miss to a match at exactly that boundary, even though the loss was already improving smoothly well before the flip.

Summing up

1 − IoU is a smooth, differentiable signal that a network can actually be trained against. Whether a detection counts as correct at evaluation time is not smooth at all — it's a hard threshold on that same IoU number. A model 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 usually counts as correct if its IoU with a ground-truth box of the same class exceeds a threshold — 0.5 is the traditional choice.

Non-maximum suppression is the cleanup step. A detector typically fires several 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, every 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 further over IoU thresholds from 0.5 to 0.95, which rewards precise localisation rather than approximate boxes.

The practical 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 actually fail

Detection datasets are expensive, and the quality of the boxes sets the ceiling on the model.

  • Be consistent about tightness. Does the box include the shadow? The handle? The occluded part? Write the rule down before annotating, because a model trained on inconsistent boxes learns the inconsistency.
  • Label every instance. A missed object is trained as background, which actively teaches the model not to detect it.
  • Decide on occlusion and truncation rules for objects half out of frame.
  • Watch class imbalance. Rare classes need either more examples or a weighted loss.
  • Match augmentation to the boxes. Flipping, rotating or cropping an image must transform the coordinates too — libraries such as Albumentations do this correctly, and hand-rolled pipelines frequently do not.

A few hundred well-annotated images plus a pretrained backbone will usually outperform 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 images per class gets a usable model. Thousands for production reliability.

What IoU threshold should I use for NMS? 0.5 is typical. Lower it if duplicates persist, raise it if genuinely overlapping objects are being suppressed.

Why are small objects missed? Because they occupy few pixels in the feature maps used for prediction. Feature pyramids, higher-resolution input and tiled inference are the standard responses.

What is the difference from segmentation? Detection gives boxes; semantic segmentation labels every 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 every object present.
  • Box formats differ between datasets — corners, corner-plus-size, and normalised centre-plus-size.
  • Two-stage detectors propose then classify; one-stage detectors predict directly and are now the practical 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 image.

Recall check

0 of 3

Say the answer out loud before you reveal it — recalling it is what makes it stick, and rereading it is not.

  1. What does this module say about “Start here”?

  2. What does this module say about “IoU as loss, IoU as grade”?

  3. What does this module say about “Classification says what; detection says what and where”?

Cheat sheet

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.

COMPUTER VISION · vizlearn.in/computer_vision/object_detection_with_bounding_boxes.html

About the author

Ashish Jangra builds and maintains VizLearn. Every module here is written and the visualisation behind it hand-built, so the numbers in a readout come from the same code that draws the picture. Corrections are genuinely welcome and get priority over everything else — if a page states something wrong, or an animation misrepresents what the algorithm does, get in touch.