Object Detection: Boxes, Scores and IoU
A classifier answers "what is in this picture?" with one label. Most real questions need more: how many cars are at the junction, where is the pedestrian, is the forklift inside the safety zone. Object detection answers them by returning, for every object it finds, a class, a box and a score. This lesson pins down that output, shows why the obvious way to produce it (slide a classifier over every window) is expensive, recaps the overlap measure everything in detection is built on, and builds a small detector without any learning so that every later lesson has a baseline to beat.
What a detector returns
For one image a detector returns a list of detections, and is not fixed: zero for an empty road, forty for a crowd.
is a class id, a box in pixels (this course writes boxes as top-left and bottom-right corner, with exclusive, so the width is ; box formats converts to COCO and YOLO), and the confidence. Three related tasks are easy to confuse:
| Task | Output | Example |
|---|---|---|
| Classification | one class per image | "cat" |
| Classification + localisation | one class and one box | "cat, at [2, 0, 431, 295]" |
| Detection | any number of (class, box, score) | "cat 0.89 at ..., dog 0.75 at ..., dog 0.41 at ..." |
Localisation can be solved by a classifier with four extra regression outputs. Detection cannot, because a network has a fixed number of outputs and the image has a variable number of objects. Every detector solves that the same way: it predicts a fixed, large set of candidates (windows, anchors, grid cells), scores each one, and throws most of them away.
The rest of this section of the course fills in the boxes: non-maximum suppression, anchors and box encoding, the two-stage Faster R-CNN and the one-stage YOLO and SSD.
Sliding windows and what they cost
The oldest detector design takes a classifier ("is this window a person?") and runs it on every window of every size and shape. The count grows fast. For a window of width and height moved with stride over a image there are
positions, and that is for one size and one shape.
def n_windows(W, H, w, h, stride):
return ((W - w) // stride + 1) * ((H - h) // stride + 1)
W, H, stride = 640, 480, 8
total = 0
for s in [32, 64, 128, 256]:
shapes = {"square": (s, s), "tall 1:2": (s, 2 * s), "wide 2:1": (2 * s, s)}
counts = {k: n_windows(W, H, w, h, stride) for k, (w, h) in shapes.items() if w <= W and h <= H}
total += sum(counts.values())
print(f"size {s:3d}: {counts}")
print("windows per image:", total)
print(f"at 5 ms per classifier call: {total * 5 / 1000:.0f} s per image")
print("our 64 x 64 shape scenes, squares 12..24 px, stride 2:", sum(n_windows(64, 64, s, s, 2) for s in range(12, 25, 2)))size 32: {'square': 4389, 'tall 1:2': 4081, 'wide 2:1': 4161}
size 64: {'square': 3869, 'tall 1:2': 3285, 'wide 2:1': 3445}
size 128: {'square': 2925, 'tall 1:2': 1885, 'wide 2:1': 2205}
size 256: {'square': 1421, 'wide 2:1': 493}
windows per image: 32159
at 5 ms per classifier call: 161 s per image
our 64 x 64 shape scenes, squares 12..24 px, stride 2: 4060
About 32,000 windows for a single 640 x 480 image with only four sizes and three shapes, which at 5 milliseconds per call (an assumed, optimistic cost for a small CNN on a CPU) is 161 seconds per image, for a scene that may hold three objects. Even the tiny 64 x 64 scenes of this course need 4,060 square windows. Classical detectors made it affordable with a very cheap classifier per window (Haar features in face detection, HOG + linear SVM for pedestrians). Deep detectors make it affordable by computing the convolutional features once for the whole image and reading every window's answer off the same feature map: Faster R-CNN and YOLO are two ways of doing exactly that.
IoU, vectorised
Whether a box is "right" is measured with intersection over union, taught in detection metrics:
A detector compares thousands of candidates with a handful of objects, so IoU is always computed as a matrix with NumPy broadcasting, never in a Python double loop. Here are the ground-truth boxes of a generated scene (the course's make_scene: 64 x 64 images with up to three squares, circles and triangles, with exact boxes) against a few hand-made predictions:
import numpy as np
import numpy as np, cv2
CLASSES = ["square", "circle", "triangle"]
def make_scene(rng, size=64, max_objects=3):
"""Noisy grey background with 1..max_objects shapes that do not touch.
Returns RGB uint8 image, boxes (n, 4) as [x1, y1, x2, y2] with x2, y2 exclusive,
labels (n,) indices into CLASSES, masks (n, size, size) bool."""
img = rng.normal(110, 12, (size, size, 3)).clip(0, 255).astype(np.uint8)
n = int(rng.integers(1, max_objects + 1))
boxes, labels, masks = [], [], []
for _ in range(100):
if len(boxes) == n:
break
s = int(rng.integers(12, 25)); x = int(rng.integers(0, size - s)); y = int(rng.integers(0, size - s))
if any(x < b[2] + 2 and b[0] < x + s + 2 and y < b[3] + 2 and b[1] < y + s + 2 for b in boxes):
continue
c = int(rng.integers(0, 3)); m = np.zeros((size, size), np.uint8)
if c == 0:
cv2.rectangle(m, (x, y), (x + s - 1, y + s - 1), 1, -1)
elif c == 1:
cv2.circle(m, (x + s // 2, y + s // 2), s // 2, 1, -1)
else:
cv2.fillPoly(m, [np.array([[x + s // 2, y], [x, y + s - 1], [x + s - 1, y + s - 1]], np.int32)], 1)
img[m > 0] = rng.integers(0, 256, 3)
ys, xs = np.nonzero(m)
boxes.append([int(xs.min()), int(ys.min()), int(xs.max()) + 1, int(ys.max()) + 1])
labels.append(c); masks.append(m > 0)
return img, np.array(boxes).reshape(-1, 4), np.array(labels), np.array(masks)
def iou_matrix(a, b):
"""(n, 4) x (m, 4) boxes [x1, y1, x2, y2] -> (n, m) IoU."""
a, b = np.asarray(a, float)[:, None], np.asarray(b, float)[None]
iw = (np.minimum(a[..., 2], b[..., 2]) - np.maximum(a[..., 0], b[..., 0])).clip(0)
ih = (np.minimum(a[..., 3], b[..., 3]) - np.maximum(a[..., 1], b[..., 1])).clip(0)
inter = iw * ih
area = lambda z: (z[..., 2] - z[..., 0]) * (z[..., 3] - z[..., 1])
return inter / (area(a) + area(b) - inter)
rng = np.random.default_rng(0)
for _ in range(2):
img, gt, labels, _ = make_scene(rng)
print("ground truth:", gt.tolist(), [CLASSES[l] for l in labels])
pred = np.array([[28, 1, 41, 14], # exact copy of the circle
[30, 3, 43, 16], # circle shifted by 2 px
[26, 0, 45, 18], # circle, box too large
[49, 8, 63, 22], # the square, exact
[56, 8, 63, 22], # only the right half of the square
[5, 40, 20, 55]]) # empty background
M = iou_matrix(pred, gt)
print(M.round(3).tolist())
print("best object per prediction:", M.argmax(1).tolist(), "best IoU:", M.max(1).round(3).tolist())ground truth: [[28, 1, 41, 14], [49, 8, 63, 22]] ['circle', 'square']
[[1.0, 0.0], [0.558, 0.0], [0.494, 0.0], [0.0, 1.0], [0.0, 0.5], [0.0, 0.0]]
best object per prediction: [0, 0, 0, 1, 1, 0] best IoU: [1.0, 0.558, 0.494, 1.0, 0.5, 0.0]
The 2-pixel shift costs the 13-pixel circle a lot: IoU 0.558, not far above the usual 0.5 hit threshold, and a box 3 to 5 pixels too large on each side (0.494) already fails it. The same errors on a 300-pixel object would be invisible. That is why small objects are hard and why COCO reports AP for small, medium and large objects separately. Half of the square gives IoU 0.5 exactly, so "IoU at least 0.5" accepts a box that covers only half the object.
Two jobs per candidate: classify and regress
Every detector, from the oldest to the newest, gives each candidate two outputs:
- Classification: a score per class, plus "background" (or an objectness score). Trained with cross-entropy or its focal-loss variant, because almost all candidates are background.
- Box regression: four numbers that move and resize the candidate box onto the object. Trained with an L1 or smooth-L1 loss on encoded offsets (anchors and box encoding) or directly with an IoU-based loss.
The split matters because the candidate set is coarse (windows every few pixels, a few sizes), so without regression a detector can only be as precise as its grid. The next example shows that numerically.
A detector with no learning
The generated scenes have a grey background with noise, so "is this pixel part of an object?" can be answered with a threshold. A candidate window then gets a contrast score: the share of object pixels inside the window minus twice the share in a 2-pixel ring around it. A window that hugs an object scores high; a window that cuts an object (object pixels in the ring) or contains only background scores low. Steps:
- Candidates: square windows of sizes 12 to 24 pixels with stride 2 (4,060 per image, counted above); sums over windows come from an integral image (four lookups per window).
- Score each window, keep those above 0.3, and remove overlapping duplicates greedily (best first, drop any window with IoU above 0.3 with a kept one; the next lesson studies this step).
- Classify each kept window by its fill ratio (object pixels / box area): about 1 for a square, for a circle, for a triangle.
- Box regression, the hand-made version: replace the window by the tight box around the object pixels near it.
The thresholds (45 grey levels for object pixels, 0.3 for scores) were chosen by looking at a few scenes from seed 0; the evaluation runs on 200 different scenes from seed 1.
import numpy as np
import numpy as np, cv2
CLASSES = ["square", "circle", "triangle"]
def make_scene(rng, size=64, max_objects=3):
"""Noisy grey background with 1..max_objects shapes that do not touch.
Returns RGB uint8 image, boxes (n, 4) as [x1, y1, x2, y2] with x2, y2 exclusive,
labels (n,) indices into CLASSES, masks (n, size, size) bool."""
img = rng.normal(110, 12, (size, size, 3)).clip(0, 255).astype(np.uint8)
n = int(rng.integers(1, max_objects + 1))
boxes, labels, masks = [], [], []
for _ in range(100):
if len(boxes) == n:
break
s = int(rng.integers(12, 25)); x = int(rng.integers(0, size - s)); y = int(rng.integers(0, size - s))
if any(x < b[2] + 2 and b[0] < x + s + 2 and y < b[3] + 2 and b[1] < y + s + 2 for b in boxes):
continue
c = int(rng.integers(0, 3)); m = np.zeros((size, size), np.uint8)
if c == 0:
cv2.rectangle(m, (x, y), (x + s - 1, y + s - 1), 1, -1)
elif c == 1:
cv2.circle(m, (x + s // 2, y + s // 2), s // 2, 1, -1)
else:
cv2.fillPoly(m, [np.array([[x + s // 2, y], [x, y + s - 1], [x + s - 1, y + s - 1]], np.int32)], 1)
img[m > 0] = rng.integers(0, 256, 3)
ys, xs = np.nonzero(m)
boxes.append([int(xs.min()), int(ys.min()), int(xs.max()) + 1, int(ys.max()) + 1])
labels.append(c); masks.append(m > 0)
return img, np.array(boxes).reshape(-1, 4), np.array(labels), np.array(masks)
def iou_matrix(a, b):
a, b = np.asarray(a, float)[:, None], np.asarray(b, float)[None]
iw = (np.minimum(a[..., 2], b[..., 2]) - np.maximum(a[..., 0], b[..., 0])).clip(0)
ih = (np.minimum(a[..., 3], b[..., 3]) - np.maximum(a[..., 1], b[..., 1])).clip(0)
area = lambda z: (z[..., 2] - z[..., 0]) * (z[..., 3] - z[..., 1])
return iw * ih / (area(a) + area(b) - iw * ih)
def detect(img, refine):
fg = (np.abs(img.astype(int) - 110).max(axis=2) > 45).astype(np.int64) # object pixels
ii = np.pad(fg.cumsum(0).cumsum(1), ((1, 0), (1, 0))) # integral image
S = lambda x1, y1, x2, y2: ii[y2, x2] - ii[y1, x2] - ii[y2, x1] + ii[y1, x1] # sum over a box
cands = []
for s in range(12, 25, 2):
y1, x1 = [v.ravel() for v in np.mgrid[0:65 - s:2, 0:65 - s:2]]
x2, y2 = x1 + s, y1 + s
ox1, oy1, ox2, oy2 = (x1 - 2).clip(0), (y1 - 2).clip(0), (x2 + 2).clip(max=64), (y2 + 2).clip(max=64)
inside, outer = S(x1, y1, x2, y2), S(ox1, oy1, ox2, oy2)
ring = (ox2 - ox1) * (oy2 - oy1) - s * s
score = inside / (s * s) - 2 * (outer - inside) / ring # ring pixels count double
cands.append(np.c_[x1, y1, x2, y2, score])
c = np.concatenate(cands)
c = c[c[:, 4] > 0.3]
c = c[np.argsort(-c[:, 4], kind="stable")]
kept = []
for row in c: # greedy duplicate removal
if all(iou_matrix(row[None, :4], k[None, :4])[0, 0] <= 0.3 for k in kept):
kept.append(row)
dets = []
for x1, y1, x2, y2, score in kept:
x1, y1, x2, y2 = int(x1), int(y1), int(x2), int(y2)
a1, b1 = max(x1 - 3, 0), max(y1 - 3, 0)
ys, xs = np.nonzero(fg[b1:y2 + 3, a1:x2 + 3])
tight = [int(a1 + xs.min()), int(b1 + ys.min()), int(a1 + xs.max()) + 1, int(b1 + ys.max()) + 1]
fill = fg[tight[1]:tight[3], tight[0]:tight[2]].mean()
cls = 0 if fill > 0.9 else 1 if fill > 0.65 else 2
dets.append((cls, float(score), tight if refine else [x1, y1, x2, y2]))
return dets
def ap(dets, gts, cls, thr):
"""VOC all-point AP for one class. dets: (image, class, score, box), gts: (image, class, box)."""
g = [(i, b) for i, c, b in gts if c == cls]
used, tp = set(), []
for i, _, s, b in sorted([d for d in dets if d[1] == cls], key=lambda d: -d[2]):
cand = [(iou_matrix([b], [gb])[0, 0], j) for j, (gi, gb) in enumerate(g) if gi == i]
best, j = max(cand, default=(0.0, -1))
tp.append(best >= thr and j not in used)
if tp[-1]:
used.add(j)
tp = np.array(tp, float)
prec, rec = np.cumsum(tp) / np.arange(1, len(tp) + 1), np.cumsum(tp) / len(g)
env = np.maximum.accumulate(prec[::-1])[::-1]
return float(np.sum(np.diff(np.r_[0, rec]) * env))
rng = np.random.default_rng(0)
img, gt, labels, _ = make_scene(rng)
print("scene 0 truth:", gt.tolist(), [CLASSES[l] for l in labels])
for cls, score, box in detect(img, refine=True):
print(f" detected {CLASSES[cls]:8s} score {score:.2f} box {box}")
rng = np.random.default_rng(1)
scenes = [make_scene(rng) for _ in range(200)]
gts = [(i, int(l), b.tolist()) for i, (_, bx, lb, _) in enumerate(scenes) for b, l in zip(bx, lb)]
print("test scenes:", len(scenes), "objects:", len(gts))
for refine in [False, True]:
per_image = [detect(sc[0], refine) for sc in scenes]
dets = [(i, c, s, b) for i, d in enumerate(per_image) for c, s, b in d]
for thr in [0.5, 0.75]:
aps = [ap(dets, gts, c, thr) for c in range(3)]
print(f"{'refined' if refine else 'window '} boxes, AP@{thr}: " + " ".join(f"{CLASSES[c]} {a:.3f}" for c, a in enumerate(aps)) + f" | mAP {np.mean(aps):.3f}")
print("detections:", len(dets))
missed = faint = wrong = 0
confusions = {}
for (im, bx, lb, mk), d in zip(scenes, per_image):
for b, l, m in zip(bx, lb, mk):
M = iou_matrix([b], [x[2] for x in d]) if d else np.zeros((1, 1))
if M.max() < 0.5:
missed += 1
faint += int(np.abs(im[m].astype(int) - 110).max(axis=1).mean() <= 45)
elif d[M.argmax()][0] != l:
wrong += 1
key = f"{CLASSES[l]}->{CLASSES[d[M.argmax()][0]]}"
confusions[key] = confusions.get(key, 0) + 1
print(f"objects missed at IoU 0.5: {missed}, of which {faint} have a colour within 45 grey levels of the background")
print(f"found but wrong class: {wrong}", dict(sorted(confusions.items())))scene 0 truth: [[32, 9, 56, 33]] ['square']
detected square score 0.73 box [32, 9, 56, 33]
test scenes: 200 objects: 404
window boxes, AP@0.5: square 0.761 circle 0.704 triangle 0.837 | mAP 0.767
window boxes, AP@0.75: square 0.705 circle 0.704 triangle 0.502 | mAP 0.637
refined boxes, AP@0.5: square 0.761 circle 0.704 triangle 0.837 | mAP 0.767
refined boxes, AP@0.75: square 0.761 circle 0.704 triangle 0.780 | mAP 0.748
detections: 385
objects missed at IoU 0.5: 19, of which 19 have a colour within 45 grey levels of the background
found but wrong class: 40 {'circle->triangle': 17, 'square->circle': 20, 'square->triangle': 3}
Scene 0 holds one 24-pixel square, and the detector returns exactly its box with score 0.73: the best window was one pixel off (windows start at even coordinates), and the refinement step snapped it onto the object. Of the 4,060 candidate windows, everything else was either below the score threshold or a duplicate.
On the 200 test scenes (404 objects, all shapes 12 to 24 pixels) the results read like a real detector's, measured as in detection metrics (VOC all-point AP per class, mAP the mean over the three classes; the ap helper above is the one from that lesson, written compactly):
- Box regression matters at strict IoU. At IoU 0.5 the raw windows and the refined boxes score the same mAP, 0.767: a window within a pixel or two is good enough. At IoU 0.75 the raw windows drop to 0.637 and the refined boxes keep 0.748. Triangles gain most (0.502 to 0.780), because a square window fits a triangle's box badly. Learned detectors do the same refinement with a regression head.
- Misses come from the input, not the search. Only 19 objects are missed at IoU 0.5, and all 19 have a colour within 45 grey levels of the background, so the pixel threshold never sees them.
- Most lost AP is classification. 40 found objects get the wrong class, mostly squares called circles (20) and circles called triangles (17): the fill-ratio rule breaks when some object pixels fall under the threshold. A hand-made rule cannot fix that; a learned classifier on the same candidates can, which is what the tiny detector does.
The detector is not useless, and on these toy scenes it is a fair baseline. But every number in it (45 grey levels, ring weight 2, score 0.3, fill ratios 0.9 and 0.65) was set by hand for one kind of image, and none would survive a real photo. Learned detectors keep the same structure (candidates, a score, a class, a box refinement, duplicate removal) and learn the numbers from labelled data.
Evaluating a detector
Never judge a detector by looking at a few images, and never by accuracy. The protocol, taught in detection metrics, is: run it with a low score threshold, match detections to ground truth per class with IoU (each object at most once), build the precision-recall curve, take AP per class and average to mAP; report at IoU 0.5 and, COCO style, averaged over IoU 0.5 to 0.95. Say which protocol you used: the same detector above has mAP 0.767 at IoU 0.5 and 0.748 at 0.75, and a COCO-style average would be lower still. For a deployed system also report precision and recall at the operating threshold you will actually use, and errors split by object size, as above, so that you know what to fix (error analysis).
Pitfalls
- Mixing box formats.
[x1, y1, x2, y2],[x, y, w, h]and normalised centre boxes all look like four numbers. An IoU between two formats is silently wrong; convert at the data boundary (box formats). - Rows and columns. Arrays are indexed
img[y, x], boxes are written first. Slicing a box out of an image isimg[y1:y2, x1:x2]. - Thresholding before evaluating. AP needs the low-score detections; filter at 0.5 first and recall, and AP, are cut short. Pick the operating threshold after evaluation, on validation data.
- Judging small objects with the same IoU. A 2-pixel error is a disaster for a 12-pixel object and nothing for a 300-pixel one; report results per size.
- Duplicates. Without duplicate removal every extra box on an object is a false positive, which looks like a precision problem but is a post-processing bug (NMS).
- Classification versus localisation errors. A box in the right place with the wrong class costs as much AP as a missed object. Count both separately, as in the last example, before deciding what to improve.
Practice
- How many square 64 x 64 windows with stride 16 fit in a 640 x 480 image?
Answer
windows. Doubling the stride divides the count by about four, at the price of coarser box positions.
- A ground-truth box is 20 x 20 pixels. A predicted box of the same size is shifted by pixels to the right. For which is IoU still at least 0.5?
Answer
Intersection , union . IoU means , so , , : up to 6 pixels, a third of the width.
- In the last example, change the object-pixel threshold from 45 to 30 grey levels. What do you expect to happen to the 19 missed objects and to false detections? Try it.
Answer
Fainter objects become visible, so fewer misses, but background noise ( per channel, the maximum of three channels) crosses 30 grey levels much more often than 45, so speckle pixels appear: they lower the contrast score of good windows and can create small false detections. The threshold trades recall against precision, the same trade a learned detector makes with its score threshold.
Test yourself
Why can a plain classifier with four extra regression outputs not do object detection?
- It cannot output boxes
- It has a fixed number of outputs, but the number of objects per image varies
- Regression outputs cannot be trained
- Classifiers only work on grey images
In the hand-made detector, the refinement step raised mAP at IoU 0.75 from 0.637 to 0.748 but left mAP at IoU 0.5 unchanged. What does that show?
- Refinement fixes classification errors
- The windows were already close enough for IoU 0.5; box regression matters for tight boxes
- IoU 0.75 is easier than 0.5
- The test set was too small
A predicted box covers exactly the left half of a ground-truth box and nothing else. What is the IoU?
- 0.25
- 0.333
- 0.5
- 0.667
Why do deep detectors not run a CNN on every sliding window?
- Windows cannot be square
- They compute the feature map once for the whole image and read every candidate's prediction from it
- Sliding windows give lower AP by definition
- They only look at the image centre