Sub topic 4
Anchors: Reference Boxes at Every Location
This chapter assumes you know what a feature map is, how IoU is computed (covered earlier), and basic NumPy. You will learn what anchors are, how to generate them, and where the design breaks down.
Why detectors need reference boxes
A detector must output a variable number of boxes, but a convolutional network produces a fixed-size tensor. Anchors bridge this gap. An anchor is a box with a fixed position, size, and aspect ratio, defined before training and independent of the image content. The network does not predict boxes from scratch. For each anchor, it answers two questions:
- Does this anchor contain an object, and of what class?
- How should this anchor be shifted and resized to fit the object?
This turns detection into a dense, fixed-shape prediction problem, which suits convolutions. The number of anchors is constant. The number of detections comes from filtering them.
How anchors are laid out
Each cell of the backbone's feature map corresponds to a location in the image. The distance in pixels between neighboring cells is the stride. A feature map from a backbone with stride 16 has one cell per 16×16 patch of the input image.
At every cell, you place a small set of anchors that share a center, the middle of that cell's patch. The set varies in two ways:
- Scale is the anchor's size, usually given as the square root of its area in pixels.
- Aspect ratio is height divided by width. Ratios of 0.5, 1, and 2 give wide, square, and tall boxes.
With S scales and R ratios, each location has A = S × R anchors. The total is H × W × A for an H×W feature map. Faster R-CNN used 3 scales (128, 256, 512 pixels) and 3 ratios, giving 9 anchors per location. On a 600×800 image at stride 16, that is about 38 × 50 × 9 ≈ 17,000 anchors.
Generating anchors in code
The function below builds a base set of boxes centered at the origin. It then adds each cell center to them. The width and height satisfy w × h = scale², so every anchor at a given scale has the same area, whatever its ratio.
import numpy as np
def make_anchors(feat_h, feat_w, stride, scales, ratios):
"""Anchors as (x1, y1, x2, y2) in image pixels, shape (feat_h*feat_w*A, 4).
ratio = height / width; scale = sqrt(area) in pixels.
"""
base = []
for s in scales:
for r in ratios:
w = s / np.sqrt(r)
h = s * np.sqrt(r)
base.append((-w / 2, -h / 2, w / 2, h / 2))
base = np.array(base) # (A, 4)
xs = (np.arange(feat_w) + 0.5) * stride # cell centers
ys = (np.arange(feat_h) + 0.5) * stride
cx, cy = np.meshgrid(xs, ys) # (H, W)
centers = np.stack([cx, cy, cx, cy], axis=-1).reshape(-1, 1, 4)
return (centers + base[None]).reshape(-1, 4)
anchors = make_anchors(4, 4, 16, scales=[32, 64], ratios=[0.5, 1.0, 2.0])
print(anchors.shape) # (96, 4)
print(np.round(anchors[0], 1)) # [-14.6 -3.3 30.6 19.3]The result has 4 × 4 locations × 6 anchors = 96 rows. The first anchor sits at the first cell center, (8, 8). It is a wide box (ratio 0.5) that extends past the image border. Many detectors clip such boxes or ignore them during training.
The ordering of the output matters. Cells vary slowest and anchors within a cell vary fastest. The prediction head's output tensor must be flattened in the same order, or each prediction will be paired with the wrong anchor. This is a common source of silent bugs.
Choosing scales, ratios, and stride
| Choice | Effect | Risk |
|---|---|---|
| Larger stride | Fewer anchors, faster | Coarse centers, small objects fit poorly |
| More scales | Covers more object sizes | More anchors and more negatives |
| More ratios | Covers more shapes | Diminishing returns past 3 |
| Larger anchors | Suits big objects | Tiny IoU with small objects |
The choice of scales and ratios is a prior about your data. COCO-style detectors use generic values. For a dataset of, say, tall pedestrians or wide license plates, you can fit the anchor shapes to the training boxes, for example by running k-means on box widths and heights with an IoU-based distance. YOLOv2 did this.
Where anchors fall short
Anchors are matched to ground truth by IoU, so the coverage of the anchor set directly limits what the detector can learn. Two edge cases show why.
Scale mismatch. A 32×32 object centered inside a 128×128 anchor has an IoU of at most 1024 / 16384 = 0.0625. No sensible matching threshold will pair them. If your smallest anchor is much bigger than your smallest object, those objects get no positive anchors and are never learned.
Stride mismatch. Anchor centers sit on a grid, so an object's center may lie up to half a stride from the nearest one, in each axis. Take a 32×32 object and a 32×32 anchor at stride 16, with the object's center midway between four anchor centers. The offset is 8 pixels in x and in y. The overlap is 24 × 24 = 576. The union is 1024 + 1024 − 576 = 1472. The IoU is 576 / 1472 ≈ 0.39. That is below the 0.5 threshold commonly used to call an anchor a positive. Multiple scales and ratios raise the chance that some anchor matches better, but the worst case remains real.
Other costs follow from the dense layout:
- Extreme imbalance. Most of the ~17,000 anchors overlap no object. Negatives outnumber positives by orders of magnitude, which motivates sampling schemes and focal loss.
- Duplicate detections. Several neighboring anchors can match the same object and each produce a confident box. This is why non-maximum suppression is needed.
- Hyperparameters. Scales, ratios, strides, and matching thresholds all interact, and they must be tuned per dataset.
These costs explain later developments. Anchor-free detectors drop the reference boxes, and DETR drops both the anchors and the duplicate-removal step.
Exercise
A detector uses stride 8, scales [16, 32, 64], and ratios [0.5, 1, 2]. It runs on a 640×640 image, giving an 80×80 feature map. How many anchors are there in total, and why can a 16×16 object whose center lies midway between four anchor centers fail to match a 16×16 square anchor at an IoU threshold of 0.5?
Show answer
There are 80 × 80 × (3 × 3) = 57,600 anchors. With stride 8, the worst-case center offset is 4 pixels in each axis. The overlap is 12 × 12 = 144. The union is 256 + 256 − 144 = 368. The IoU is 144 / 368 ≈ 0.39, which is below 0.5. Anchors with other ratios or scales may still match, but the square anchor does not.