TExcelTAD

Anchors and Box Encoding

A detector network ends in a convolution, so its output is a grid of numbers: for every position of the feature map, a fixed number of channels. To turn that into boxes, every output position needs a reference box to predict relative to, and a rule that turns four network outputs into four box coordinates. Faster R-CNN, SSD, RetinaNet and YOLOv2 to v5 use anchors: a fixed set of boxes of several sizes and shapes at every position. YOLOv8, YOLO11 and FCOS use anchor points and predict distances to the four sides. This lesson builds both from scratch, matches anchors to objects with the rules Faster R-CNN uses, encodes and decodes boxes, and checks the result against torchvision.

anchor-based (Faster R-CNN, SSD) red: anchors, green: object 3 sizes x 3 ratios = 9 anchors per position anchor-free (FCOS, YOLOv8) lrtb one point, 4 distances to the box sides

Generating anchors

An anchor set is defined by a feature-map stride dd (pixels per feature-map cell), a list of sizes ss and a list of aspect ratios r=h/wr = h / w. Each (size, ratio) pair gives a box of the same area s2s^2:

w=sr,h=srw = \frac{s}{\sqrt{r}}, \qquad h = s \sqrt{r}

and every box is repeated at every feature-map position. torchvision centres them at (jd,id)(j d, i d) for column jj and row ii and rounds the half-widths to whole pixels; other libraries add half a stride to the centre. A feature pyramid (FPN) puts small anchors on the fine, high-resolution levels and large ones on the coarse levels, one size per level. Anchors at the image border may stick out; most implementations keep them.

python · try it yourself
import numpy as np

def make_anchors(grid_h, grid_w, stride, sizes, ratios):
    """torchvision's convention: centres at (j * stride, i * stride), half-sizes rounded; ratio = h / w."""
    r = np.sqrt(np.asarray(ratios, float))
    ws = (np.asarray(sizes, float)[None, :] / r[:, None]).ravel()      # ratio-major, then size
    hs = (np.asarray(sizes, float)[None, :] * r[:, None]).ravel()
    base = np.round(np.stack([-ws, -hs, ws, hs], 1) / 2)
    ys, xs = np.mgrid[0:grid_h, 0:grid_w] * stride
    shifts = np.stack([xs.ravel(), ys.ravel(), xs.ravel(), ys.ravel()], 1)
    return (shifts[:, None, :] + base[None, :, :]).reshape(-1, 4)

A = make_anchors(16, 16, 4, sizes=[12, 18, 24], ratios=[0.5, 1.0, 2.0])
print("64 x 64 image, stride 4, 3 sizes x 3 ratios:", A.shape[0], "anchors")
print("the 9 anchors at column 8, row 8 (centre (32, 32)):")
for a in A[(8 * 16 + 8) * 9:(8 * 16 + 8) * 9 + 9]:
    w, h = a[2] - a[0], a[3] - a[1]
    print(f"  {a.astype(int).tolist()}  w {w:.0f} h {h:.0f}")

print("feature pyramid, 3 ratios per position:")
for H, W in [(640, 640), (800, 1216)]:
    levels = [(stride, size, (H // stride) * (W // stride) * 3) for stride, size in [(4, 32), (8, 64), (16, 128), (32, 256), (64, 512)]]
    print(f"  {H} x {W}:", ", ".join(f"P stride {d} size {s}: {n}" for d, s, n in levels), "| total", sum(n for _, _, n in levels))
64 x 64 image, stride 4, 3 sizes x 3 ratios: 2304 anchors
the 9 anchors at column 8, row 8 (centre (32, 32)):
  [24, 28, 40, 36]  w 16 h 8
  [19, 26, 45, 38]  w 26 h 12
  [15, 24, 49, 40]  w 34 h 16
  [26, 26, 38, 38]  w 12 h 12
  [23, 23, 41, 41]  w 18 h 18
  [20, 20, 44, 44]  w 24 h 24
  [28, 24, 36, 40]  w 8 h 16
  [26, 19, 38, 45]  w 12 h 26
  [24, 15, 40, 49]  w 16 h 34
feature pyramid, 3 ratios per position:
  640 x 640: P stride 4 size 32: 76800, P stride 8 size 64: 19200, P stride 16 size 128: 4800, P stride 32 size 256: 1200, P stride 64 size 512: 300 | total 102300
  800 x 1216: P stride 4 size 32: 182400, P stride 8 size 64: 45600, P stride 16 size 128: 11400, P stride 32 size 256: 2850, P stride 64 size 512: 684 | total 242934

The nine anchors at one position come in three areas (about 12212^2, 18218^2, 24224^2 pixels, slightly changed by rounding) and three shapes: wide (r=0.5r = 0.5), square and tall (r=2r = 2). 256 positions times 9 gives 2,304 anchors for a 64 x 64 image. A Faster R-CNN-style pyramid on a 640 x 640 image has 102,300 anchors, three quarters of them on the finest level, and 242,934 on an 800 x 1216 image (a typical COCO training size). Almost all of them are background in any given image.

Matching anchors to objects

During training every anchor needs a target: which object it should predict, or "background". Faster R-CNN's region proposal network uses three rules on the IoU matrix between anchors and ground-truth boxes:

  1. An anchor whose best IoU with any object is at least 0.7 is positive for that object.
  2. An anchor whose best IoU is below 0.3 is negative (background).
  3. Anchors in between are ignored: they are neither rewarded nor punished, because they are ambiguous.

and a fourth rule repairs a gap: for every object, the anchor(s) with the highest IoU are positive even if that IoU is below 0.7, so no object is left without a positive anchor. RetinaNet uses 0.5 and 0.4 instead of 0.7 and 0.3; the idea is the same.

python · try it yourself
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 make_anchors(grid_h, grid_w, stride, sizes, ratios):
    r = np.sqrt(np.asarray(ratios, float))
    ws = (np.asarray(sizes, float)[None, :] / r[:, None]).ravel()
    hs = (np.asarray(sizes, float)[None, :] * r[:, None]).ravel()
    base = np.round(np.stack([-ws, -hs, ws, hs], 1) / 2)
    ys, xs = np.mgrid[0:grid_h, 0:grid_w] * stride
    shifts = np.stack([xs.ravel(), ys.ravel(), xs.ravel(), ys.ravel()], 1)
    return (shifts[:, None, :] + base[None, :, :]).reshape(-1, 4)

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 match(anchors, gt, pos=0.7, neg=0.3):
    """Returns per anchor: index of its object (>= 0), -1 negative, -2 ignored."""
    M = iou_matrix(anchors, gt)
    best, which = M.max(1), M.argmax(1)
    out = np.where(best >= pos, which, np.where(best < neg, -1, -2))
    for j in range(len(gt)):                       # rule 4: best anchor(s) of every object
        tops = np.flatnonzero(M[:, j] == M[:, j].max())
        out[tops] = j
    return out, M

A = make_anchors(16, 16, 4, [12, 18, 24], [0.5, 1.0, 2.0])
rng = np.random.default_rng(0)
for _ in range(2):
    img, gt, labels, _ = make_scene(rng)
m, M = match(A, gt)
print("objects:", gt.tolist())
print("positive:", int((m >= 0).sum()), "| negative:", int((m == -1).sum()), "| ignored:", int((m == -2).sum()), "of", len(A))
for j in range(len(gt)):
    print(f"  object {j}: best anchor IoU {M[:, j].max():.3f}, positives {int((m == j).sum())}, of which IoU >= 0.7: {int(((m == j) & (M[:, j] >= 0.7)).sum())}")

rng = np.random.default_rng(1)
n_obj = only_rule4 = n_pos = n_neg = 0
for _ in range(200):
    img, gt, labels, _ = make_scene(rng)
    m, M = match(A, gt)
    n_obj += len(gt); only_rule4 += int((M.max(0) < 0.7).sum())
    n_pos += int((m >= 0).sum()); n_neg += int((m == -1).sum())
print(f"200 scenes: {n_obj} objects, {only_rule4} of them ({only_rule4 / n_obj:.0%}) have no anchor with IoU >= 0.7")
print(f"positives per scene {n_pos / 200:.1f}, negatives per scene {n_neg / 200:.1f}, ratio 1 : {n_neg / n_pos:.0f}")
objects: [[28, 1, 41, 14], [49, 8, 63, 22]]
positive: 2 | negative: 2177 | ignored: 125 of 2304
  object 0: best anchor IoU 0.729, positives 1, of which IoU >= 0.7: 1
  object 1: best anchor IoU 0.735, positives 1, of which IoU >= 0.7: 1
200 scenes: 404 objects, 85 of them (21%) have no anchor with IoU >= 0.7
positives per scene 3.5, negatives per scene 2102.2, ratio 1 : 593

In scene 1 each object has exactly one anchor above 0.7 (0.729 and 0.735) and so one positive anchor; 2,177 anchors are background and 125 are ignored. Over 200 scenes, 85 of the 404 objects (21%) have no anchor with IoU 0.7 and get their positive only from rule 4. Without it a fifth of the objects would never be trained on, typically those whose size or shape falls between the anchor sizes. The last line is the reason detection needs special care in the classification loss: about 593 negatives per positive. Faster R-CNN samples a balanced mini-batch of 256 anchors (at most half positive); RetinaNet keeps all of them and uses the focal loss to down-weight the many easy negatives.

Encoding a box relative to an anchor

The network does not output pixel coordinates. For a positive anchor aa (centre xa,yax_a, y_a, size wa,haw_a, h_a) and its object gg the training target is

tx=xg−xawa,ty=yg−yaha,tw=log⁡wgwa,th=log⁡hghat_x = \frac{x_g - x_a}{w_a}, \qquad t_y = \frac{y_g - y_a}{h_a}, \qquad t_w = \log \frac{w_g}{w_a}, \qquad t_h = \log \frac{h_g}{h_a}

and at inference the predicted (tx,ty,tw,th)(t_x, t_y, t_w, t_h) are decoded back:

x=xa+txwa,y=ya+tyha,w=waetw,h=haethx = x_a + t_x w_a, \qquad y = y_a + t_y h_a, \qquad w = w_a e^{t_w}, \qquad h = h_a e^{t_h}

Why this form: dividing the shift by the anchor size makes a 2-pixel error on a small anchor as large a target as a 20-pixel error on a ten times larger one, so one regression head serves all sizes. The logarithm makes "twice as wide" and "half as wide" symmetric (±0.693\pm 0.693) and the decoded width is always positive. Implementations then multiply the targets by fixed weights so that they have roughly unit spread: torchvision's second stage uses (10,10,5,5)(10, 10, 5, 5), and SSD writes the same thing as "variances" (0.1,0.1,0.2,0.2)(0.1, 0.1, 0.2, 0.2) that the targets are divided by. The regression loss (smooth L1 or L1) is computed on positive anchors only.

python · try it yourself
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 make_anchors(grid_h, grid_w, stride, sizes, ratios):
    r = np.sqrt(np.asarray(ratios, float))
    ws = (np.asarray(sizes, float)[None, :] / r[:, None]).ravel()
    hs = (np.asarray(sizes, float)[None, :] * r[:, None]).ravel()
    base = np.round(np.stack([-ws, -hs, ws, hs], 1) / 2)
    ys, xs = np.mgrid[0:grid_h, 0:grid_w] * stride
    shifts = np.stack([xs.ravel(), ys.ravel(), xs.ravel(), ys.ravel()], 1)
    return (shifts[:, None, :] + base[None, :, :]).reshape(-1, 4)

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 to_cxcywh(b):
    b = np.asarray(b, float)
    return (b[:, 0] + b[:, 2]) / 2, (b[:, 1] + b[:, 3]) / 2, b[:, 2] - b[:, 0], b[:, 3] - b[:, 1]

def encode(gt, anchors, weights=(1.0, 1.0, 1.0, 1.0)):
    gx, gy, gw, gh = to_cxcywh(gt); ax, ay, aw, ah = to_cxcywh(anchors)
    t = np.stack([(gx - ax) / aw, (gy - ay) / ah, np.log(gw / aw), np.log(gh / ah)], 1)
    return t * np.asarray(weights)

def decode(t, anchors, weights=(1.0, 1.0, 1.0, 1.0)):
    t = t / np.asarray(weights)
    ax, ay, aw, ah = to_cxcywh(anchors)
    x, y, w, h = ax + t[:, 0] * aw, ay + t[:, 1] * ah, aw * np.exp(t[:, 2]), ah * np.exp(t[:, 3])
    return np.stack([x - w / 2, y - h / 2, x + w / 2, y + h / 2], 1)

A = make_anchors(16, 16, 4, [12, 18, 24], [0.5, 1.0, 2.0])
rng = np.random.default_rng(1)
anc, tgt = [], []
for _ in range(200):
    img, gt, labels, _ = make_scene(rng)
    M = iou_matrix(A, gt)
    pos = M.max(1) >= 0.5                          # positives at IoU 0.5 (RetinaNet-style), for the statistics
    anc.append(A[pos]); tgt.append(gt[M[pos].argmax(1)])
anc, tgt = np.concatenate(anc), np.concatenate(tgt)
t = encode(tgt, anc)
print("positive anchor-object pairs:", len(t))
print("first pair: anchor", anc[0].astype(int).tolist(), "object", tgt[0].tolist(), "-> t", t[0].round(3).tolist())
print("round trip, max error in pixels:", float(np.abs(decode(t, anc) - tgt).max()))
print("std of (tx, ty, tw, th):", t.std(0).round(3).tolist())
print("std with weights (10, 10, 5, 5):", encode(tgt, anc, (10, 10, 5, 5)).std(0).round(3).tolist())
print("twice / half the anchor width: tw =", round(float(np.log(2)), 3), "/", round(float(np.log(0.5)), 3))
positive anchor-object pairs: 7620
first pair: anchor [-5, 10, 21, 22] object [3, 9, 20, 26] -> t [0.135, 0.125, -0.425, 0.348]
round trip, max error in pixels: 8.881784197001252e-16
std of (tx, ty, tw, th): [0.134, 0.135, 0.314, 0.313]
std with weights (10, 10, 5, 5): [1.341, 1.35, 1.569, 1.567]
twice / half the anchor width: tw = 0.693 / -0.693

Over the 7,620 positive (anchor, object) pairs from 200 scenes (positives taken at IoU 0.5 here, to get more pairs), encode followed by decode reproduces every box to within 10−1510^{-15} pixels: the encoding is exact and invertible, so all of the error at inference comes from the network's prediction of tt. The raw targets are small, with a spread of about 0.13 for the centre and 0.31 for the size; multiplied by (10,10,5,5)(10, 10, 5, 5) they have a spread of 1.3 to 1.6, closer to the unit scale that losses and initialisations assume.

Checking against torchvision

torchvision's detectors are built from the same three pieces: AnchorGenerator, Matcher (the 0.7 / 0.3 rule with allow_low_quality_matches=True for rule 4) and BoxCoder. This recorded example (PyTorch, run in Docker) builds them with the settings above and compares them with the NumPy versions:

python · try it yourself
import numpy as np
import torch
from torchvision.models.detection.anchor_utils import AnchorGenerator
from torchvision.models.detection.image_list import ImageList
from torchvision.models.detection._utils import BoxCoder, Matcher
from torchvision.ops import box_iou
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 make_anchors(grid_h, grid_w, stride, sizes, ratios):
    r = np.sqrt(np.asarray(ratios, float))
    ws = (np.asarray(sizes, float)[None, :] / r[:, None]).ravel()
    hs = (np.asarray(sizes, float)[None, :] * r[:, None]).ravel()
    base = np.round(np.stack([-ws, -hs, ws, hs], 1) / 2)
    ys, xs = np.mgrid[0:grid_h, 0:grid_w] * stride
    shifts = np.stack([xs.ravel(), ys.ravel(), xs.ravel(), ys.ravel()], 1)
    return (shifts[:, None, :] + base[None, :, :]).reshape(-1, 4)

ours = make_anchors(16, 16, 4, [12, 18, 24], [0.5, 1.0, 2.0])
gen = AnchorGenerator(sizes=((12, 18, 24),), aspect_ratios=((0.5, 1.0, 2.0),))
images = ImageList(torch.zeros(1, 3, 64, 64), [(64, 64)])
tv = gen(images, [torch.zeros(1, 8, 16, 16)])[0]
print("anchors:", tuple(tv.shape), "| identical to NumPy:", bool(np.array_equal(tv.numpy(), ours)))

rng = np.random.default_rng(0)
for _ in range(2):
    img, gt, labels, _ = make_scene(rng)
gt_t = torch.tensor(gt, dtype=torch.float32)
matched = Matcher(0.7, 0.3, allow_low_quality_matches=True)(box_iou(gt_t, tv))
print("Matcher: positive", int((matched >= 0).sum()), "| negative", int((matched == -1).sum()), "| ignored", int((matched == -2).sum()))

coder = BoxCoder(weights=(1.0, 1.0, 1.0, 1.0))
pos = matched >= 0
t = coder.encode_single(gt_t[matched[pos]], tv[pos])
back = coder.decode_single(t, tv[pos])
ax, ay = (tv[pos][:, 0] + tv[pos][:, 2]) / 2, (tv[pos][:, 1] + tv[pos][:, 3]) / 2
aw, ah = tv[pos][:, 2] - tv[pos][:, 0], tv[pos][:, 3] - tv[pos][:, 1]
g = gt_t[matched[pos]]
ours_t = torch.stack([((g[:, 0] + g[:, 2]) / 2 - ax) / aw, ((g[:, 1] + g[:, 3]) / 2 - ay) / ah,
                      torch.log((g[:, 2] - g[:, 0]) / aw), torch.log((g[:, 3] - g[:, 1]) / ah)], 1)
print("BoxCoder targets equal the formula:", bool(torch.allclose(t, ours_t, atol=1e-6)), "| decode error:", round(float((back - g).abs().max()), 6))
print("decode clamps tw, th at log(1000 / 16) =", round(float(np.log(1000 / 16)), 3))
anchors: (2304, 4) | identical to NumPy: True
Matcher: positive 2 | negative 2177 | ignored 125
BoxCoder targets equal the formula: True | decode error: 0.0
decode clamps tw, th at log(1000 / 16) = 4.135

The anchors are identical, the Matcher makes the same decisions (2 positive, 2,177 negative, 125 ignored), and BoxCoder computes the same formula and decodes it back exactly. The one detail the NumPy version lacks is the clamp: before etwe^{t_w}, torchvision limits twt_w and tht_h to log⁡(1000/16)≈4.135\log(1000/16) \approx 4.135, so a wild prediction early in training cannot make a box e50e^{50} pixels wide and overflow.

Anchor-free: points and distances

Anchors bring hyperparameters (sizes, ratios, two IoU thresholds per level) that have to be tuned to the data: anchors that fit COCO fit long thin text lines or tiny insects badly. Anchor-free detectors drop the boxes and keep only the points. FCOS (2019) and the YOLOv8 / YOLO11 head work like this:

  • Every feature-map cell has one anchor point at its centre, ((j+0.5)d,(i+0.5)d)((j + 0.5) d, (i + 0.5) d).
  • A point inside an object's box can be responsible for it. The target is the four distances from the point to the sides, (l,t,r,b)(l, t, r, b), all positive; decoding is [x−l,y−t,x+r,y+b][x - l, y - t, x + r, y + b].
  • Which points count as positive is decided by an assigner: FCOS takes points inside the box (in its improved version only those near the box centre) on the pyramid level whose size range fits the object; YOLOv8 uses the task-aligned assigner (TAL), which ranks points by a mix of predicted class score and IoU and keeps the top 10 per object.
  • YOLOv8 predicts each distance, in units of the stride, as a distribution over 16 bins 0,1,…,150, 1, \ldots, 15 (distribution focal loss, DFL) and decodes it as the expected value. So one side can be at most 15 strides from its point.
python · try it yourself
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 anchor_points(grid, stride):
    ys, xs = np.mgrid[0:grid, 0:grid]
    return np.stack([(xs.ravel() + 0.5) * stride, (ys.ravel() + 0.5) * stride], 1)

def ltrb(points, box):
    return np.stack([points[:, 0] - box[0], points[:, 1] - box[1], box[2] - points[:, 0], box[3] - points[:, 1]], 1)

rng = np.random.default_rng(0)
for _ in range(2):
    img, gt, labels, _ = make_scene(rng)
P = anchor_points(8, 8)                                     # stride 8 on a 64 x 64 image: 64 points
for box in gt:
    d = ltrb(P, box)
    inside = (d > 0).all(1)
    cx, cy = (box[0] + box[2]) / 2, (box[1] + box[3]) / 2
    best = np.argmin(np.hypot(P[:, 0] - cx, P[:, 1] - cy) + 1e9 * ~inside)   # the point nearest the centre
    p, dist = P[best], d[best]
    decoded = [p[0] - dist[0], p[1] - dist[1], p[0] + dist[2], p[1] + dist[3]]
    print(f"box {box.tolist()}: {int(inside.sum())} points inside, nearest centre {p.tolist()} -> l, t, r, b {dist.tolist()} -> decoded {[int(v) for v in decoded]}")

# YOLOv8 style: one distance in stride units as a distribution over 16 bins
stride, l_pix = 8, 42.4
l = l_pix / stride                                          # 5.3 strides
target = np.zeros(16); target[5], target[6] = 0.7, 0.3      # DFL target: the two neighbouring bins
logits = np.log(target + 1e-9)                              # a perfectly trained head
p = np.exp(logits - logits.max()); p /= p.sum()
print(f"distance {l_pix} px = {l} strides -> bins 5 and 6 with weights 0.7 / 0.3 -> decoded {float((p * np.arange(16)).sum() * stride):.1f} px")
print("largest distance one level can express:", 15 * 8, "px at stride 8,", 15 * 32, "px at stride 32")
box [28, 1, 41, 14]: 2 points inside, nearest centre [36.0, 4.0] -> l, t, r, b [8.0, 3.0, 5.0, 10.0] -> decoded [28, 1, 41, 14]
box [49, 8, 63, 22]: 4 points inside, nearest centre [52.0, 12.0] -> l, t, r, b [3.0, 4.0, 11.0, 10.0] -> decoded [49, 8, 63, 22]
distance 42.4 px = 5.3 strides -> bins 5 and 6 with weights 0.7 / 0.3 -> decoded 42.4 px
largest distance one level can express: 120 px at stride 8, 480 px at stride 32

The first object (a 13 x 13 circle) has only 2 of the 64 stride-8 points inside its box and the second (14 x 14) has 4: on a coarse grid small objects get few candidate points, which is why anchor-free detectors also use finer levels (stride 8 is YOLOv8's finest). Decoding the distances reproduces the box exactly. With DFL, a distance of 5.3 strides becomes weight 0.7 on bin 5 and 0.3 on bin 6, and the expected value returns 42.4 pixels. The 16 bins limit a side to 15 strides from its point, 120 pixels at stride 8 and 480 at stride 32; larger objects must be handled by the coarser levels, which is one reason for the pyramid.

Anchor-based Anchor-free (points)
Reference per position kk boxes (sizes ×\times ratios), e.g. 9 1 point
Regression target (tx,ty,tw,th)(t_x, t_y, t_w, t_h) relative to the anchor distances (l,t,r,b)(l, t, r, b), in strides
Positive if IoU with the object ≥\ge threshold (+ best anchor) point inside the box, chosen by an assigner
Hyperparameters sizes, ratios, IoU thresholds per level assigner settings, size range per level
Examples Faster R-CNN, SSD, RetinaNet, YOLOv2 to v5 FCOS, CenterNet, YOLOX, YOLOv8, YOLO11

Pitfalls

  • Anchors that do not fit the objects. torchvision's default Faster R-CNN anchors start at 32 pixels; on 10-pixel insects or 1:10 text lines no anchor reaches IoU 0.7 and rule 4 alone carries training. Check the best-anchor IoU distribution on your training boxes (as above) before training; YOLOv5 runs a k-means "autoanchor" on the training boxes for this reason.
  • Encoding against the wrong centre. Mixing a corner-centred anchor grid (torchvision) with a cell-centred one (+0.5+0.5 stride) shifts every box by half a stride. Encode and decode with the same anchors.
  • Forgetting the weights at decode time. Targets multiplied by (10,10,5,5)(10, 10, 5, 5) in training must be divided by them at inference, or every box ends up far too large.
  • No clamp on twt_w, tht_h. An exponential of an untrained output overflows; clamp before decoding.
  • Ignoring the imbalance. Hundreds of negatives per positive: a plain cross-entropy loss is dominated by easy background. Sample or use focal loss.
  • Counting ignored anchors as negatives. Anchors between 0.3 and 0.7 are deliberately excluded from the loss; treating them as background punishes the network for nearly-right boxes.

Practice

  1. An anchor is [20, 20, 52, 36] and the object [24, 18, 56, 42]. Compute (tx,ty,tw,th)(t_x, t_y, t_w, t_h).
Answer

Anchor: centre (36, 28), size 32 x 16. Object: centre (40, 30), size 32 x 24. tx=4/32=0.125t_x = 4/32 = 0.125, ty=2/16=0.125t_y = 2/16 = 0.125, tw=log⁡1=0t_w = \log 1 = 0, th=log⁡1.5≈0.405t_h = \log 1.5 \approx 0.405.

  1. How many anchors does a single-level detector with stride 16, 5 sizes and 3 ratios have on a 512 x 512 image? How many anchor points would an anchor-free head on the same level have?
Answer

32⋅32=102432 \cdot 32 = 1024 positions, times 15 anchors =15,360= 15{,}360 anchors. The anchor-free head has one point per position: 1,024.

  1. Why does rule 4 (the best anchor of every object is positive) matter more for small objects?
Answer

IoU punishes small offsets on small boxes. A 12-pixel object between anchor positions 4 pixels apart, or between anchor sizes, often has no anchor with IoU 0.7. In the 200 test scenes 21% of the objects (all 12 to 24 pixels) needed rule 4.

Test yourself

Why is the width target encoded as tw=log⁡(wg/wa)t_w = \log(w_g / w_a)?

  1. To make it an integer
  2. So that doubling and halving are symmetric and the decoded width waetww_a e^{t_w} is always positive
  3. Because the log is faster to compute
  4. To match the IoU

In Faster R-CNN's RPN, an anchor's best IoU with any object is 0.5. What is it during training (unless it is some object's best anchor)?

  1. Positive
  2. Negative
  3. Ignored: it is not used in the loss
  4. It is deleted

On 200 generated scenes, 21% of the objects had no anchor with IoU at least 0.7. What keeps them in training?

  1. NMS
  2. The rule that every object's best-overlapping anchor is positive
  3. The ignore band
  4. Focal loss

What does an anchor-free head such as YOLOv8's predict at each point?

  1. Offsets from nine anchor boxes
  2. Distances from the point to the four sides of the box, plus class scores
  3. A segmentation mask
  4. Only an objectness score