Encode ground-truth boxes as regression deltas from anchors
Why it matters Faster R-CNN, RetinaNet and Mask R-CNN all train their box heads on these encoded targets.
Detectors do not predict box corners directly. They predict small, scale-free offsets of a box relative to its anchor.
Write encode_boxes(anchors, gt, weights=(10.0, 10.0, 5.0, 5.0)). Both are (n, 4) arrays of (x1, y1, x2, y2). For each pair: width w = x2 - x1, height h = y2 - y1, center cx = x1 + 0.5 * w, cy = y1 + 0.5 * h. With (wx, wy, ww, wh) = weights, return the (n, 4) float array of dx = wx * (gcx - acx) / aw, dy = wy * (gcy - acy) / ah, dw = ww * log(gw / aw), dh = wh * log(gh / ah).
def encode_boxes(anchors, gt, weights=(10.0, 10.0, 5.0, 5.0))Example
anchors [[0, 0, 10, 10]], gt [[1, 0, 11, 20]] gives [[1.0, 5.0, 0.0, 3.4657]] (rounded).
Understand the idea
An anchor is a starting guess. Instead of asking the network for exact pixel coordinates, we ask for how far to shift the center, measured in anchor widths, and how much to stretch, measured as a log ratio. These numbers look the same for a small car and a large truck, which makes learning easier. Like giving directions as half a block east rather than in absolute map coordinates.
Tiny example: anchor (0, 0, 10, 10) has center (5, 5) and size 10 x 10. Ground truth (1, 0, 11, 20) has center (6, 10), size 10 x 20. dx = 10 * 1 / 10 = 1, dy = 10 * 5 / 10 = 5, dw = 5 * log 1 = 0, dh = 5 * log 2 = 3.47.
Rules: dx = wx (gcx - acx) / aw, dy = wy (gcy - acy) / ah, dw = ww log(gw / aw), dh = wh log(gh / ah).
The decoder at inference inverts these four formulas to turn predictions back into boxes.
Shapes and data flow
anchors, gt (n,4) -> deltas (n,4)