Generate anchor boxes over a feature map grid
Why it matters Faster R-CNN, RetinaNet and SSD all start from an anchor grid built like this.
Anchor-based detectors place a fixed set of boxes of several sizes and shapes at every feature map cell, then learn to adjust them.
Write make_anchors(feat_h, feat_w, stride, scales, ratios). Cells are visited row by row (y outer, x inner). The center of cell (y, x) in image pixels is ((x + 0.5) * stride, (y + 0.5) * stride). At each cell, for each scale (outer) and each ratio r = h / w (inner), the anchor has w = scale / sqrt(r) and h = scale * sqrt(r), so its area is scale^2. Return an (feat_h * feat_w * len(scales) * len(ratios), 4) float array of (x1, y1, x2, y2) = (cx - w/2, cy - h/2, cx + w/2, cy + h/2).
def make_anchors(feat_h, feat_w, stride, scales, ratios)Example
make_anchors(1, 2, 16, [8], [1, 4]) is [[4, 4, 12, 12], [6, 0, 10, 16], [20, 4, 28, 12], [22, 0, 26, 16]].
Understand the idea
A detector does not search for boxes from nothing. It starts from a fixed set of guesses, called anchors, laid out on a grid, a few at every location with different sizes and shapes: square, tall, wide. Training only has to learn small corrections. Like setting out empty picture frames of several shapes on every square of a chessboard and asking which frame fits an object best.
Tiny example: a 1 x 2 grid, stride 16, so cell centers are (8, 8) and (24, 8). Scale 8, ratio 1 gives an 8 x 8 box: (4, 4, 12, 12). Ratio 4 (tall) gives w = 4, h = 16: (6, 0, 10, 16).
Rules: center = ((x + 0.5) * stride, (y + 0.5) * stride); w = scale / sqrt(r), h = scale * sqrt(r).
Region proposal networks and single-shot detectors generate thousands of such anchors per image.
Shapes and data flow
(feat_h * feat_w) cells x (S * R) anchors per cell -> (N, 4)