Object Detection — YOLO and Feature Pyramids
Anchor boxes, IoU, non-maximum suppression, and why YOLO became the production standard for real-time detection. Built from concepts to code.
Classification asks: what is in this image? Object detection asks: what is in this image, where exactly is it, and how many of them are there? That extra "where" changes everything about the architecture.
Shopify's quality control system needs to detect defective stitching in product photos — not just classify "defective" vs "good" but locate exactly where the defect is. DoorDash's delivery verification system detects and reads the order number on the packaging. A traffic camera system counts vehicles and detects lane violations. All require object detection — bounding boxes around every object of interest in the image.
The output of a detection model is a list of bounding boxes. Each box has four coordinates (x_center, y_center, width, height), a confidence score (how sure is the model an object is here), and a class label (what kind of object). One image can produce dozens of boxes — one per detected object instance.
Classification is multiple choice: "Is this a cat, dog, or bird?" Object detection is open-ended search: "Find every animal in this photo, draw a box around each one, and tell me what kind it is." The search problem is fundamentally harder — the model must check every possible location and scale simultaneously.
YOLO's insight: instead of searching sequentially, divide the image into a grid and have every grid cell predict boxes simultaneously. One forward pass, all detections at once. Fast enough for real-time video at 30+ frames per second.
Bounding boxes and IoU — how detection accuracy is measured
A bounding box is defined by four numbers. Two formats are common: corner format (x_min, y_min, x_max, y_max) and centre format (x_center, y_center, width, height). YOLO uses centre format. COCO annotations use corner format. Always know which format your data and model expect.
Intersection over Union (IoU) measures how well a predicted box matches the ground truth box. It is the area of overlap divided by the area of the union. IoU = 1.0 is a perfect match. IoU = 0.0 means no overlap. The standard threshold is IoU ≥ 0.5 for a detection to count as correct (True Positive).
Non-Maximum Suppression — keep the best box, discard the rest
A detection model produces hundreds of candidate boxes. Multiple boxes often overlap on the same object — the model detected the same car 15 times at slightly different positions. Non-Maximum Suppression (NMS) removes duplicates: keep the box with the highest confidence score, remove all other boxes that overlap it significantly (IoU > threshold). Repeat for the remaining boxes.
High IoU threshold (0.7): permissive — more boxes, may include duplicates
YOLO — You Only Look Once — grid-based detection in a single pass
YOLO divides the input image into an S×S grid. Each grid cell predicts B bounding boxes and their confidence scores, plus C class probabilities. All predictions are made simultaneously in one forward pass — hence "You Only Look Once." This makes YOLO dramatically faster than two-stage detectors (like Faster R-CNN) which first propose regions then classify them.
YOLO version history — what each version improved
YOLOv8 with Ultralytics — inference, fine-tuning, and deployment
mAP — mean Average Precision — the standard detection metric
Accuracy does not apply to detection. The standard metric is mAP (mean Average Precision). For each class, you compute Average Precision (AP) — the area under the precision-recall curve across all confidence thresholds. mAP is the mean AP across all classes. mAP@0.5 uses IoU ≥ 0.5 as the threshold for a True Positive. mAP@0.5:0.95 averages mAP across IoU thresholds from 0.5 to 0.95 — the COCO standard, much harder.
Every common object detection mistake — explained and fixed
Real detection deployments — and the tradeoff every one of them makes
Every production object detection system is solving the same underlying tradeoff: bigger models detect more accurately but run slower and cost more to deploy, and where the system runs decides how much of that cost you can actually afford to pay. A cloud GPU serving batch requests can absorb a slower, larger model. A camera bolted to a warehouse ceiling running on embedded hardware cannot.
Five things people get wrong about object detection
Classification always outputs exactly one label for a fixed-size input. Detection has to solve a problem classification never faces: the number of objects in an image is unknown and variable — zero, one, or forty — and each one sits at an unknown location and scale. That is why detection needed its own architectural ideas (a grid of simultaneous predictors, anchor boxes, NMS to clean up duplicates) rather than just classification with extra output neurons. Sliding a classifier over every possible window and scale would technically work, but it is combinatorially too slow — YOLO's single-pass grid exists specifically to avoid that search.
The IoU threshold is an evaluation choice, not a property of the model — it decides how strictly a predicted box must overlap the ground truth to count as correct. Raising it from 0.5 to 0.9 does not make a model better; it makes the bar for "correct" harder to clear, so the same model reports a lower mAP. This is exactly why COCO's mAP@0.5:0.95 exists — it is deliberately more demanding than Pascal VOC's mAP@0.5 — and why comparing two models' mAP numbers is meaningless unless they were evaluated at the same threshold(s).
"Faster" was never the only axis. Two-stage detectors first propose candidate regions then classify each one — more compute, but historically better localisation on small or densely packed objects because the region proposal step gets a second dedicated look at each candidate. One-stage detectors predict everything in a single forward pass, trading some of that per-region refinement for speed. Modern one-stage models (YOLOv8 and later) have closed most of the accuracy gap through multi-scale detection and better training tricks, but the underlying tradeoff — a dedicated proposal-refinement stage versus a single unified pass — is still real and still shows up on small-object-heavy datasets.
A lower threshold suppresses more aggressively, but "more aggressive" is not free — NMS cannot tell the difference between two boxes on the same object and two boxes on two different objects that happen to be standing close together. Push the threshold too low (say, 0.2) in a crowd scene or a shelf of tightly packed products, and legitimate neighbouring objects get merged into one detection. The right threshold is a tuned tradeoff against your specific data's object density, not a knob to minimise.
Anchor boxes are starting references, not a fixed catalog the model must pick from verbatim. At each grid location the model predicts *offsets* — how much to shift and resize a given anchor to match the actual object — so a tall anchor can still stretch to cover a wide object if the regression pushes it there. Anchors exist to give the regression a sane starting point (matched to typical object shapes in the training data via clustering) so training converges faster, not to hard-constrain what shapes are detectable. Anchor-free detectors like YOLOv8 drop this mechanism entirely and predict box dimensions directly, which is a separate design choice, not proof that anchors were ever a hard constraint.
Object detection — 5 questions interviewers actually ask
The image is divided into an S×S grid and passed through the backbone in one forward pass. Each grid cell predicts a fixed number of bounding boxes (as offsets from anchor boxes or, in anchor-free versions, directly), a confidence score for each box, and class probabilities. The cell "responsible" for an object is the one containing that object's centre. This produces hundreds of raw candidate boxes, most low-confidence or duplicates. Boxes below a confidence threshold (e.g. 0.25) are discarded, then Non-Maximum Suppression removes duplicate boxes on the same object, keeping only the highest-confidence box per cluster. What remains is the final detection list — boxes, classes, and scores.
IoU is intersection area divided by union area between a predicted box and the ground truth box — it quantifies how well two boxes overlap, from 0 (no overlap) to 1 (perfect match). It matters for evaluation because it is the criterion that decides whether a prediction counts as a True Positive: IoU ≥ threshold means correct, below it means the prediction is a False Positive even if the class label was right. The threshold you pick changes the reported score without changing the model — Pascal VOC's mAP@0.5 is lenient, COCO's mAP@0.5:0.95 averages across ten thresholds from 0.5 to 0.95 and is much harder to score well on, which is why COCO numbers are always lower than VOC-style numbers for the same model.
A detector typically produces many overlapping candidate boxes around the same real object — without cleanup you would report the same car ten times. NMS removes the duplicates: sort all boxes by confidence score, take the highest-scoring box and add it to the final output, then remove every remaining box whose IoU with that box exceeds a threshold (commonly 0.45). Repeat with whatever boxes are left until none remain. The IoU threshold controls aggressiveness — too low and it merges genuinely distinct nearby objects, too high and duplicate boxes survive.
Two-stage detectors (Faster R-CNN) first generate candidate regions likely to contain an object, then run a second network to classify and refine each region — more compute per image but historically stronger localisation, especially on small or crowded objects, because each candidate gets dedicated attention. One-stage detectors (YOLO, SSD) skip the proposal step and predict boxes and classes directly from the full image in one pass — much faster, which is why YOLO is the standard choice for real-time video at 30+ fps. I'd pick two-stage when accuracy on small/dense objects matters more than latency (offline batch analysis of satellite imagery, for example) and one-stage for anything real-time (live camera feeds, robotics, mobile deployment).
First suspect a distribution mismatch between validation and production data — training images are often cleaner (studio lighting, no motion blur) than what the camera actually captures in the field, so I'd pull real production frames and manually inspect detections on them. Second, check whether the confidence threshold used to compute mAP (often very low, like 0.001, to build the full precision-recall curve) matches the threshold actually used at inference time (often 0.5) — a high mAP built at a permissive threshold does not guarantee good precision at the stricter threshold you deploy with. Third, verify the NMS and confidence settings are identical between evaluation and the production inference code — a silent mismatch there is a common and easy-to-miss bug.
You can detect objects. Next: label every pixel in the image.
Object detection draws bounding boxes — rectangular approximations of object locations. Semantic segmentation goes further: it assigns a class label to every single pixel in the image. Instead of "there is a person at coordinates (100, 200)–(180, 400)" it produces "every pixel that belongs to a person, exactly." Module 58 covers U-Net — the architecture that powers medical image segmentation — and how skip connections preserve fine spatial detail lost during downsampling.
U-Net architecture, skip connections, and how segmentation powers medical imaging and autonomous vehicles.
🎯 Key Takeaways
- ✓Object detection predicts bounding boxes (location + size), confidence scores, and class labels for every object in an image — not just one label for the whole image. Output format: [x_center, y_center, width, height, confidence, class_probs] per predicted box.
- ✓IoU (Intersection over Union) measures overlap between predicted and ground truth boxes. IoU = intersection_area / union_area. IoU ≥ 0.5 is the standard threshold for a True Positive. IoU is used for both NMS (removing duplicates) and mAP evaluation (judging correctness).
- ✓Non-Maximum Suppression (NMS) removes duplicate detections. Sort by confidence → keep highest box → remove all overlapping boxes with IoU above threshold → repeat. Use iou_threshold=0.45 as default. Too high: duplicates survive. Too low: legitimate nearby objects suppressed.
- ✓YOLO divides the image into an S×S grid. Each cell predicts B bounding boxes simultaneously in one forward pass. Multi-scale detection (YOLOv3+) uses three grid sizes to detect small, medium, and large objects. YOLOv8 (anchor-free) is the current production standard — use Ultralytics library.
- ✓mAP (mean Average Precision) is the standard detection metric. mAP@0.5 uses IoU≥0.5 as TP threshold. mAP@0.5:0.95 averages across IoU thresholds 0.5 to 0.95 — the harder COCO standard. Typical production targets: mAP@0.5 > 0.7 for good detection, > 0.85 for excellent.
- ✓Fine-tuning YOLOv8: prepare YOLO-format labels (normalised coordinates 0–1), create dataset.yaml, call model.train(data=yaml, epochs=50). All box coordinates must be normalised by image dimensions. Labels folder must mirror images folder structure with identical filenames but .txt extension.
Discussion
0Have a better approach? Found something outdated? Share it — your knowledge helps everyone learning here.