Sub topic 1
What object detection asks of a model
Prerequisites
This chapter assumes you know the following:
- Basic Python: functions, lists, and importing packages.
- Images as arrays of pixels, for example an array of shape height × width × 3.
- A basic idea of a neural network and of training with a loss function.
- What a convolutional neural network (CNN) is, and what image classification means.
You do not need any detection-specific knowledge. This chapter sets up the vocabulary that the rest of the tutorial uses.
From classification to detection
An image classifier answers one question about a whole image: "What is this a picture of?" Its output is a fixed-size vector of class scores, one per class. A photo of a street gets a single label, or a ranked list of labels.
An object detector answers a harder question: "What objects are in this image, and where is each one?" For every object it finds, it must return three things:
- A bounding box, a rectangle that encloses the object.
- A class label, such as
personorbus. - A confidence score, a number between 0 and 1 that says how sure the model is that the box contains an object of that class.
The number of objects varies from image to image. A photo of an empty road has zero detections. A crowd photo may have hundreds. This is the main difference from classification. The output is a variable-length list, not a fixed-size vector, and a network has to be designed so that it can produce such a list.
| Task | Question answered | Output | Output size |
|---|---|---|---|
| Classification | What is in the image? | Class scores | Fixed, one per class |
| Localization | What is it and where is it? (one object) | One class and one box | Fixed |
| Detection | What objects are there and where? | List of (box, class, score) | Variable |
| Instance segmentation | Which pixels belong to each object? | List of (mask, class, score) | Variable |
Detection sits between classification and segmentation. It gives location, but only as a rectangle. A rectangle is a coarse description. A diagonal pole or a person with outstretched arms leaves a lot of background inside the box. For many applications, such as counting, tracking, or triggering an alert, that is enough, and boxes are far cheaper to label than pixel masks.
What a detection looks like in code
A detection result is just structured data. Here is a minimal representation in plain Python, with no model involved. It shows the shape of the information a detector must produce.
from dataclasses import dataclass
@dataclass
class Detection:
x1: float # left edge, in pixels
y1: float # top edge, in pixels
x2: float # right edge, in pixels
y2: float # bottom edge, in pixels
label: str
score: float
detections = [
Detection(34, 20, 210, 400, "person", 0.91),
Detection(220, 50, 640, 380, "bus", 0.87),
Detection(10, 300, 60, 380, "dog", 0.31),
]
for d in detections:
print(f"{d.label:7s} score={d.score:.2f} box=({d.x1}, {d.y1}, {d.x2}, {d.y2})")Every later chapter works with this triple of box, label, and score. Chapter by chapter, you will learn how a model produces it, how to filter it, and how to measure whether it is correct.
What the model is really being asked
Detection looks like one task, but it combines several sub-problems. Knowing them helps you diagnose failures later.
- Localization. Regress four numbers per object so the box fits tightly. This is a continuous-valued prediction, and small errors in pixels matter more for small objects than for large ones.
- Classification. Decide which class the object belongs to. This must work for each box, not for the image as a whole.
- Objectness or confidence. Decide whether a box contains a real object at all, as opposed to background. Most of an image is background, so this decision is where most predictions are rejected.
- Counting and separation. Report each instance once. If two people stand side by side, the model must produce two boxes, not one large box and not four overlapping ones.
The model must also do all of this at many scales. A bus filling the frame and a bus far down the road are the same class, but they differ in size by a factor of 50 or more. Detectors handle this with features computed at several resolutions, which a later chapter on backbone, neck and head explains.
Why the output is hard to produce
A CNN naturally produces fixed-shape tensors. To produce a variable-length list, detectors use a common trick: they predict a very large, fixed number of candidate boxes, score each one, and then discard the weak or redundant ones. The fixed-size grid of predictions is the raw output. The final list is what remains after filtering.
This has two consequences you will see repeatedly.
- Raw output contains many duplicates. Several nearby candidates often describe the same object. Removing them needs a separate step, called non-maximum suppression, which a later chapter covers.
- The confidence threshold you apply changes the result. A low threshold keeps more candidates, so you find more real objects and also more false ones.
Ground truth and what counts as correct
To train or evaluate a detector, you need ground truth: a human-labeled list of boxes and classes for each image. A prediction is not simply right or wrong. It has to be compared with the ground truth on two axes at once.
- Is the class correct?
- Does the predicted box overlap the true box enough?
The second check needs a numeric measure of overlap. That measure is intersection over union (IoU), which has its own chapter. For now, it is enough to know that a prediction counts as a true positive only when its class matches and its overlap with a ground-truth box passes a chosen threshold. Otherwise it is a false positive. A ground-truth object that no prediction matches is a false negative, also called a miss.
These three outcomes drive all detection metrics.
| Outcome | Meaning |
|---|---|
| True positive (TP) | A predicted box matches a real object in class and location |
| False positive (FP) | A predicted box has no matching real object (wrong class, poor overlap, a duplicate, or background) |
| False negative (FN) | A real object has no matching predicted box |
Notice that a duplicate box on an already matched object counts as a false positive. A detector can find every object and still score badly if it also emits many duplicates.
def count_outcomes(n_pred_matched, n_pred_total, n_truth_total):
# n_pred_matched: predictions that matched a distinct ground-truth box
tp = n_pred_matched
fp = n_pred_total - n_pred_matched
fn = n_truth_total - n_pred_matched
return tp, fp, fn
# 10 predictions, 6 of which matched distinct real objects; 8 real objects exist.
print(count_outcomes(6, 10, 8)) # (6, 4, 2)Common pitfalls at this stage
- Treating detection as classification plus a box. Running a classifier on the whole image and then guessing a box does not scale to multiple objects. The model must reason about each location.
- Forgetting the background. Most candidate boxes contain nothing. A detector that is never penalized for false alarms will fire everywhere.
- Ignoring object size. A model that works on large objects can fail on small ones. Check results by size, not only overall.
- Confusing the image with the label. Boxes are stored in a specific coordinate format. Mixing formats, such as pixel corners and normalized centers, silently produces wrong boxes. The next chapter covers this.
Where YOLO fits
YOLO, short for "You Only Look Once", is a family of detectors that predict boxes, objectness, and class scores for the whole image in a single forward pass of one network. That is why it is fast enough for video and edge devices. The rest of this tutorial builds up the pieces in order: box formats, IoU, the single-pass idea, output decoding, non-maximum suppression, then running, training, evaluating, and exporting a model.
Exercise
A detector is run on an image with 5 real objects. It outputs 8 boxes. Of these, 4 each match a different real object correctly, 2 are duplicates of objects that were already matched, and 2 sit on background. How many true positives, false positives, and false negatives are there, and what is the one-step reason a classifier could not give you this result?
Show answer
True positives = 4. False positives = 4 (2 duplicates plus 2 background boxes). False negatives = 1 (5 real objects minus 4 matched). A classifier outputs one fixed-size set of class scores for the whole image, so it cannot report how many objects there are or where each one is. A detector outputs a variable-length list of (box, class, score) entries.
Exercise
Name the three pieces of information a detector returns for each object, and explain why the output length is not fixed.
Show answer
Each detection has a bounding box, a class label, and a confidence score. The length varies because the number of objects differs between images, from none to many. The network produces a fixed number of candidate boxes, and filtering by confidence and duplicate removal leaves a variable-length list.