Chapter 27 of 42 · ~20 min read & lab+80 XP
Chapter 27 · Deep Learning

Object Detection Explained: Anchors, IoU, Non-Maximum Suppression (NMS) & YOLO vs. DETR

How neural networks locate AND classify multiple objects in one image: Intersection over Union (IoU), greedy Non-Maximum Suppression (NMS), mAP@50:95 evaluation, and real-time YOLO vs. end-to-end Transformer DETR!

Why ML Engineers & Data Scientists Actually Need This

Image classification says 'there is a car somewhere' — Object Detection outputs exact pixel coordinates [x1, y1, x2, y2] and class labels for every pedestrian, cyclist, and traffic light in real time!

ML / AI Engineer

Implementing IoU and NMS cleanly (and knowing when to pick YOLO vs. RT-DETR) is a core computer vision engineering skill.

Data Scientist

Understanding mAP@50:95 prevents shipping a detector that gets high recall by spamming 50 noisy boxes per frame!

Interview & Debug Edge

Classic Computer Vision coding interview: 'Implement IoU and Non-Maximum Suppression (NMS) in NumPy/PyTorch, and explain how DETR eliminates NMS!'

Step 0 · Test Your Gut Before Any Math!

In greedy Non-Maximum Suppression (NMS), after keeping the highest-confidence box B_max, which remaining boxes get deleted?

What You Will Master in This Chapter
  • Compute exact Intersection over Union (IoU) between predicted and ground-truth bounding boxes
  • Implement Non-Maximum Suppression (NMS) to remove duplicate overlapping detections
  • Understand mAP@50 and mAP@50:95 precision-recall evaluation across classes and IoU thresholds
  • Compare real-time one-stage YOLO detectors against end-to-end DETR (Hungarian bipartite matching, zero NMS!)
Plain-English Symbol Decoder · Click Any Symbol Before We Begin
1 / 2
IoU(A,B)=∣A∩B∣∣A∪B∣=∣A∩B∣∣A∣+∣B∣−∣A∩B∣\text{IoU}(A, B) = \frac{|A \cap B|}{|A \cup B|} = \frac{|A \cap B|}{|A| + |B| - |A \cap B|}Say aloud:“IoU equals area of intersection divided by area of union”
Plain-English Meaning
Standard bounding-box overlap metric ranging from 0.0 (disjoint) to 1.0 (exact pixel match).
Everyday Example
COCO mAP@50:95 averages Average Precision across 10 IoU thresholds from 0.50 to 0.95!
Story-First Intuition, Visual Diagrams & Interactive Walkthroughs

Imagine 10 spotters all pointing at the same deer in a photo and drawing slightly shifted rectangles around it. NMS picks the most confident spotter's rectangle and tells everyone else pointing at the same spot (IoU > 0.5) to lower their hands — while letting a spotter pointing at a second deer keep their box!

1. Bounding Boxes & Intersection over Union (IoU)

Intersection over Union (IoU): Measuring Bounding-Box AccuracyGT BoxPred BoxA ∩ BIoU = (A ∩ B) / (A ∪ B)0.0 = No Overlap · 1.0 = Exact Match ✓
Intersection over Union (IoU) measures bounding-box alignment: Area(A ∩ B) / Area(A ∪ B) — standard benchmarks require IoU ≥ 0.50 (mAP@50) or average across 0.50:0.95!

Every detection outputs [x1, y1, x2, y2, confidence, class_id]. To grade whether a predicted box is a True Positive, compute IoU (intersection / union). Modern losses like GIoU / CIoU optimize IoU directly instead of raw L1 box coordinates!

2. Non-Maximum Suppression (NMS)

Non-Maximum Suppression (NMS): Filtering Duplicate Detections1. Raw Grid Boxes0.94, 0.87, 0.72 overlap2. Pick Max (0.94)Suppress IoU > 0.503. Clean Output ✓1 sharp box per object
Non-Maximum Suppression (NMS) sorts overlapping boxes by confidence, keeps the highest-scoring box, and suppresses every neighbor with IoU > threshold (e.g., 0.5)!

Dense grid detectors emit thousands of candidate boxes per image. NMS cleans them up in 3 lines: sort by confidence, pop the best box into keep[], and remove all remaining boxes with IoU > thresh until none remain!

Animated Mini-Lab • Object Detection

NMS IoU Suppression Threshold Simulator

Box A (Max) (IoU=1) ✓
Box B (Dup) (IoU=0.72) ✕
Box C (Edge) (IoU=0.41) ✓
Box D (Other) (IoU=0.08) ✓

3. Real-Time YOLO vs. End-to-End DETR

Modern Detectors: One-Stage YOLO vs. Transformer DETRYOLO (Dense Grid + NMS)• Single CNN pass → 100+ FPS edge speed• Needs NMS post-processing (except v10+)Best for real-time robotics & edge video ✓DETR / RT-DETR (Set Prediction)• Learned Object Queries + Cross-Attention• Hungarian 1-to-1 matching → ZERO NMS!End-to-end differentiable global reasoning ✓
One-stage YOLO predicts boxes on a dense grid + NMS (ultra-fast real-time FPS), whereas DETR uses Transformer object queries + Hungarian bipartite matching (zero NMS needed)!
  • YOLO (v8/v10/v11): Anchor-free dense CNN grid running at 100+ FPS on edge GPUs.
  • DETR / RT-DETR: Uses Transformer Object Queries + Hungarian Bipartite Matching during training so each query claims exactly one ground-truth object — eliminating hand-tuned anchors and NMS completely!
Pause & Check · Quick Intuition Pulse

Why does DETR not need Non-Maximum Suppression (NMS) at inference time?

“Wait, I'm Confused...” · Teacher Office Hours Q&A

The exact honest questions almost every beginner wonders — answered in plain English without hiding behind jargon.

In crowded scenes (e.g., two pedestrians standing right next to each other with IoU = 0.55), hard NMS deletes the second person! Soft-NMS decays the overlapping box's confidence smoothly instead of hard-deleting it.

Interactive Visual Lab
Lab Challenge: Watch the 60 FPS NMS Box-Filter Studio prune overlapping duplicate boxes.
Interactive Animation • Object Detection Deep Lab

Non-Maximum Suppression (NMS) Greedy Box Filtering

Watch NMS keep the highest-confidence box and prune overlapping duplicates.

Step 1 / 3
1. Detector emits 4 overlapping boxes (0.94, 0.87, 0.81, 0.68)
2. Pick top box (0.94) → Suppress duplicate Box B (IoU 0.72 > 0.50)
3. Keep Box D (IoU 0.08 — separate object!) → 2 clean detections ✓
0%
NMS Step 1
Intuition Takeaway: Object Detection combines IoU overlap math, per-class NMS (or DETR's Hungarian 1-to-1 matching), and mAP@50:95 evaluation to localize multiple objects at real-time speed.
Where This Powers Real ML, Deep Learning & Generative AI

Autonomous Driving, Retail Analytics & Medical Detection

YOLO/RT-DETR pipelines power real-time pedestrian detection, warehouse inventory counting, and radiology lesion localization.

Production NumPy & PyTorch Code Patterns
import torch

# Vectorized Box IoU & Greedy Non-Maximum Suppression (NMS) from scratch
def box_iou(box: torch.Tensor, boxes: torch.Tensor) -> torch.Tensor:
    x1 = torch.maximum(box[0], boxes[:, 0])
    y1 = torch.maximum(box[1], boxes[:, 1])
    x2 = torch.minimum(box[2], boxes[:, 2])
    y2 = torch.minimum(box[3], boxes[:, 3])
    inter = (x2 - x1).clamp(min=0) * (y2 - y1).clamp(min=0)
    area_a = (box[2] - box[0]) * (box[3] - box[1])
    area_b = (boxes[:, 2] - boxes[:, 0]) * (boxes[:, 3] - boxes[:, 1])
    return inter / (area_a + area_b - inter + 1e-6)

def greedy_nms(boxes: torch.Tensor, scores: torch.Tensor, iou_thresh: float = 0.5):
    order = scores.argsort(descending=True)
    keep = []
    while order.numel() > 0:
        i = order[0].item()
        keep.append(i)
        if order.numel() == 1:
            break
        ious = box_iou(boxes[i], boxes[order[1:]])
        order = order[1:][ious <= iou_thresh]
    return keep

boxes = torch.tensor([[10., 10., 50., 50.], [12., 12., 48., 48.], [80., 80., 120., 120.]])
scores = torch.tensor([0.95, 0.80, 0.88])
print("Kept box indices after NMS:", greedy_nms(boxes, scores, iou_thresh=0.5))
Common ML Interview Traps & Numerical Pitfalls
Trap #1: Running NMS across ALL classes combined instead of per-class (or class-offset) NMS.
Best Practice: A person riding a bicycle has high IoU between person and bicycle — run NMS per class so you don't delete the rider!
Chapter Mastery Check (+80 XP)
Score: 0 / 1
1Two identical 10×10 boxes overlap completely (intersection = 100). What is their IoU?

Apply What You Learned — Solve Matching Coding Problems