Sub topic 1
What an Object Detector Must Output
Prerequisites
This chapter assumes you know the following:
- Basic Python and NumPy.
- How convolutional neural networks produce feature maps.
- Training with gradient descent and loss functions.
- The difference between classification and regression.
Familiarity with Transformers is helpful for the last chapters of the tutorial but is not needed here.
The task in one sentence
An object detector takes one image and returns a variable-length set of detections. Each detection contains:
- A box that locates the object, usually as corner coordinates
(x1, y1, x2, y2)in pixels. - A class label, such as
personorcar. - A confidence score between 0 and 1.
Image classification returns one label for the whole image. Semantic segmentation returns a label for every pixel. Detection sits between them. It names each object instance and gives its position, so two cars in one image produce two separate detections.
detections = [
{"box": (48, 30, 210, 190), "label": "dog", "score": 0.97},
{"box": (220, 80, 300, 200), "label": "cat", "score": 0.88},
]
for d in detections:
x1, y1, x2, y2 = d["box"]
print(d["label"], d["score"], "area =", (x2 - x1) * (y2 - y1))Why this output is hard for a neural network
A standard network produces a fixed-size output. A detector must produce a list whose length depends on the image. The same model has to return zero detections for an empty street and fifty for a crowd.
Three properties make this difficult:
- Variable count. The number of objects is unknown before the model runs.
- No natural order. The detections form a set. Listing the cat before the dog means the same thing as listing the dog before the cat.
- Mixed outputs. Each detection combines a discrete choice (the class) with continuous numbers (the box).
Every detector in this tutorial answers the same question: how can a fixed-size network produce a variable-size, unordered set of boxes? The answers differ, and the differences organize the rest of the tutorial.
| Family | How it handles the variable count | Typical filtering step |
|---|---|---|
| Two-stage (R-CNN family) | Proposes candidate regions, then classifies each | Non-maximum suppression (NMS) |
| Single-stage with anchors (SSD, RetinaNet, YOLO) | Predicts for a dense grid of reference boxes | NMS |
| Anchor-free (FCOS, CenterNet) | Predicts per location, with no reference boxes | NMS or peak picking |
| DETR | Predicts a fixed number of slots, some meaning "no object" | None |
The common recipe: predict too much, then filter
The earliest practical approach, and the one most detectors still follow, is to predict many candidates and discard most of them. The model emits thousands of candidate boxes, each with class scores. Most candidates describe background. Many of the rest describe the same object as their neighbors.
This pipeline has two consequences you will meet repeatedly:
- During training, the model needs a rule that says which candidates are responsible for which ground-truth objects. This is label assignment.
- During inference, the model needs a rule that removes duplicates. This is usually NMS.
DETR removes both rules by changing what the network predicts. That is why this tutorial ends there.
Box formats and coordinate conventions
Detection code is full of silent bugs caused by mixed-up box formats. You will see at least three conventions.
| Format | Fields | Used by |
|---|---|---|
| Corner | `(x1, y1, x2, y2)` | Most evaluation code, IoU, NMS |
| Center-size | `(cx, cy, w, h)` | Anchor decoding, DETR |
| Corner plus size | `(x, y, w, h)` | COCO annotation files |
Coordinates can also be absolute pixels or normalized to the range 0 to 1 by dividing by image width and height. DETR predicts normalized center-size boxes. COCO stores absolute top-left plus size.
A pair of small conversion functions prevents many mistakes.
def corner_to_center(box):
x1, y1, x2, y2 = box
return ((x1 + x2) / 2, (y1 + y2) / 2, x2 - x1, y2 - y1)
def center_to_corner(box):
cx, cy, w, h = box
return (cx - w / 2, cy - h / 2, cx + w / 2, cy + h / 2)
def coco_to_corner(box):
x, y, w, h = box
return (x, y, x + w, y + h)
box = (10, 20, 50, 100)
print(corner_to_center(box)) # (30.0, 60.0, 40, 80)
print(center_to_corner(corner_to_center(box))) # (10.0, 20.0, 50.0, 100.0)
print(coco_to_corner((10, 20, 40, 80))) # (10, 20, 50, 100)The class output includes "background"
A detector usually predicts a class distribution over the object classes plus one extra class, background (also called "no object"). A candidate that covers nothing of interest should be classified as background.
This extra class matters because most candidates are background. With thousands of candidates per image and a handful of objects, background examples vastly outnumber object examples. Later chapters show how this imbalance shapes the loss, and why focal loss was introduced to handle it.
Some detectors, such as RetinaNet, use one sigmoid per class and treat background as "all sigmoids are low". Others, such as Faster R-CNN and DETR, use a softmax over classes plus an explicit background entry. The idea is the same: the model needs a way to say "nothing here".
From raw outputs to a final list
The raw output of a detector is not yet the final answer. Consider what happens at inference time:
- The head produces box and class predictions for every candidate.
- Candidates with a score below a threshold, such as 0.05 or 0.5, are dropped.
- Duplicate boxes are removed.
- The surviving detections are returned, often capped at a maximum count such as 100.
The score threshold is a deployment choice. A low threshold keeps more true objects and more false positives. A high threshold does the reverse. Evaluation with average precision sweeps over this threshold, so it does not depend on one choice. A later chapter covers this.
def filter_by_score(boxes, scores, labels, threshold=0.5, max_det=100):
"""Keep detections above a score threshold, highest score first."""
order = sorted(range(len(boxes)), key=lambda i: scores[i], reverse=True)
kept = [i for i in order if scores[i] >= threshold][:max_det]
return [(boxes[i], labels[i], scores[i]) for i in kept]
boxes = [(0, 0, 10, 10), (1, 1, 11, 11), (50, 50, 60, 60)]
scores = [0.9, 0.3, 0.7]
labels = ["car", "car", "person"]
print(filter_by_score(boxes, scores, labels))
# [((0, 0, 10, 10), 'car', 0.9), ((50, 50, 60, 60), 'person', 0.7)]Here the score filter alone removes the weak duplicate. In practice duplicates often have high scores too, which is why a dedicated duplicate-removal step is needed.
What training data looks like
The ground truth for one image is a set of boxes and labels written by human annotators. A typical record has a list of (box, label) pairs and no scores. Images with no objects have an empty list.
import numpy as np
target = {
"boxes": np.array([[48, 30, 210, 190], [220, 80, 300, 200]], dtype=np.float32),
"labels": np.array([1, 2]), # integer class ids; 0 is reserved for background
}
print(target["boxes"].shape) # (2, 4)
print(target["labels"].shape) # (2,)The key point is the size mismatch. The model produces thousands of candidates, while the target has two objects. Every training algorithm in this tutorial is, at its core, a way to compare a large prediction set with a small ground-truth set. Anchor-based methods compare by overlap. DETR compares by optimal one-to-one matching.
Common errors at this stage
- Mixing box formats, as described above.
- Forgetting image resizing. If you resize an image, the boxes must be scaled by the same factors.
- Treating the output as ordered. Do not rely on detection order. Sort by score yourself if you need an order.
- Judging a detector by classification accuracy. A correct label with a badly placed box is a failure. Detection quality needs both.
- Ignoring the empty case. Code that indexes
detections[0]will crash on images with no detections.
Where this leads
The next chapter defines Intersection over Union, the measure of box overlap that underlies label assignment, duplicate removal, and evaluation. After that, the tutorial builds the machinery of anchor-based detectors step by step, then shows how anchor-free methods and DETR remove parts of it.
Exercise
A detector returns 300 candidate boxes for an image that contains 4 annotated objects. Name the two problems this size mismatch creates, one at training time and one at inference time, and state which step addresses each in a typical anchor-based detector.
Show answer
At training time, the model must decide which of the 300 candidates should be trained to match each of the 4 ground-truth objects and which should be trained as background. Label assignment, which matches candidates to ground truth by overlap, addresses this. At inference time, several candidates may describe the same object, so the output contains duplicates. Non-maximum suppression addresses this by keeping the highest-scoring box and removing overlapping ones.
Exercise
A COCO annotation gives the box [100, 50, 40, 60] as (x, y, w, h). Convert it to corner format and to center-size format.
Show answer
Corner format is (100, 50, 140, 110), since x2 = 100 + 40 and y2 = 50 + 60. Center-size format is (120, 80, 40, 60), since cx = (100 + 140) / 2 and cy = (50 + 110) / 2.