Sub topic 1
How Object Detectors Work: What an Object Detector Must Output
Prerequisites
This chapter assumes you know basic Python and NumPy, what a convolutional neural network (CNN) does, and the difference between classification and regression. Familiarity with feature maps is helpful.
What an object detector must output
An object detector takes an image and returns a list of detections. Each detection holds a class label, a confidence score, and a bounding box. A box is a rectangle given as (x1, y1, x2, y2): the top-left and bottom-right corners in pixels.
The number of detections changes from image to image, so the output is a variable-length set.
Measuring box overlap with IoU
Intersection over Union (IoU) is the intersection area of two boxes divided by their union area. Identical boxes score 1.0, and disjoint boxes score 0.0.
def iou(a, b):
"""IoU of two boxes given as (x1, y1, x2, y2)."""
ix1, iy1 = max(a[0], b[0]), max(a[1], b[1])
ix2, iy2 = min(a[2], b[2]), min(a[3], b[3])
inter = max(0.0, ix2 - ix1) * max(0.0, iy2 - iy1)
area_a = (a[2] - a[0]) * (a[3] - a[1])
area_b = (b[2] - b[0]) * (b[3] - b[1])
union = area_a + area_b - inter
return inter / union if union > 0 else 0.0
print(round(iou((0, 0, 10, 10), (5, 5, 15, 15)), 4)) # 0.1429Backbones turn pixels into feature maps
A backbone is a CNN that converts an image into a grid of feature vectors, called a feature map. Each cell summarizes a patch of the input. The stride is the number of input pixels between neighboring cells.
| Input size | Stride | Feature map size |
|---|---|---|
| 512 x 512 | 32 | 16 x 16 |
| 512 x 512 | 8 | 64 x 64 |
Anchors: reference boxes at every location
An anchor is a fixed reference box centered on each feature map cell. Detectors usually place several anchors per cell, with different sizes and aspect ratios. A 16 x 16 map with 9 anchors per cell gives 2,304 anchors. The network scores each anchor and adjusts its box.
Predicting offsets instead of raw coordinates
The network predicts offsets (tx, ty, tw, th) relative to an anchor (cx, cy, w, h). The center shifts in units of anchor size. Width and height scale by an exponential, which keeps them positive.
import math
def decode(anchor, deltas):
"""Apply (tx, ty, tw, th) to an anchor given as (cx, cy, w, h)."""
cx_a, cy_a, w_a, h_a = anchor
tx, ty, tw, th = deltas
cx = cx_a + tx * w_a
cy = cy_a + ty * h_a
w = w_a * math.exp(tw)
h = h_a * math.exp(th)
return (cx, cy, w, h)
print(tuple(round(v, 2) for v in decode((50, 50, 20, 40), (0.1, -0.05, 0.0, math.log(2)))))
# (52.0, 48.0, 20.0, 80.0)Exercise
An anchor is (50, 50, 20, 40) and the predicted offsets are (0, 0, 0, 0). What box does decoding return?
Show answer
It returns (50.0, 50.0, 20.0, 40.0). Zero offsets leave the anchor unchanged, so the network only needs to learn corrections to a sensible default.