Algorithm Search⌘K

Techniqueadvanced

Bounding box regression

Also called box regression, box offset encoding.

Predict a box as offsets from a reference box: the center shift divided by the reference size, and the log of the width and height ratios.

Bounding box regression is the step of a detector that turns a rough box into a tight one. It does not predict the corners of a box directly. It predicts four offsets from a reference box, which is a proposal in R-CNN and Fast R-CNN and an anchor box in Faster R-CNN and the single shot multibox detector: the shift of the center divided by the reference width or height, and the logarithm of the ratio of the sizes. A network or a linear model learns these offsets from features; the cost of that model is not part of this page. The encoding and its inverse are exact maps, and they do not change when the image is shifted or scaled, which is the reason for the form.

In plain words

A detector first finds a box that is roughly in the right place. The box may be a little too far left, or too narrow. The regression step corrects it. It does not say "the right edge is at pixel 140". It says "move the box by a tenth of its own width to the right, and make it 20 percent wider". Because the correction is measured in units of the box itself, a small box and a large box with the same kind of error get the same numbers. A learned model can then use one rule for objects of every size and at every place in the image. To get the final box, the detector applies the correction to the rough box.

When it applies

The technique needs a reference box aa for each prediction and a target box gg for training. A box is (x1,y1,x2,y2)(x_1, y_1, x_2, y_2) in continuous image coordinates with x1<x2x_1 < x_2 and y1<y2y_1 < y_2, with xx to the right and yy down. Its center form is (x,y,w,h)(x, y, w, h) with w=x2−x1w = x_2 - x_1, h=y2−y1h = y_2 - y_1, x=x1+w/2x = x_1 + w/2 and y=y1+h/2y = y_1 + h/2. Old PASCAL VOC code uses inclusive pixel boxes with w=x2−x1+1w = x_2 - x_1 + 1; this page uses the continuous form unless it says otherwise.

The targets are

tx=x−xawa,ty=y−yaha,tw=log⁡wwa,th=log⁡hha.t_x = \frac{x - x_a}{w_a}, \qquad t_y = \frac{y - y_a}{h_a}, \qquad t_w = \log \frac{w}{w_a}, \qquad t_h = \log \frac{h}{h_a}.

The map from gg to tt is a bijection from the boxes with w,h>0w, h > 0 onto R4\mathbb{R}^4. A model predicts t^\hat t from the features of the reference box, and the decoded box is the inverse map applied to t^\hat t.

The technique applies when the reference box is already close to the object. R-CNN trains its regressor only on pairs with an intersection over union above 0.6, and the anchor rules of anchor assignment play the same role. For a reference box far from the object, the targets are large and the relation between features and targets is far from linear, so the prediction is poor. This is a design limit, not a theorem.

The template

  1. ENCODE(a, g) ▷ reference box a, target box g
  2. 1(x_a, y_a, w_a, h_a) ← the center form of a
  3. 2(x, y, w, h) ← the center form of g
  4. 3return ((x - x_a) / w_a, (y - y_a) / h_a, log(w / w_a), log(h / h_a))
  5. DECODE(a, t)
  6. 4(x_a, y_a, w_a, h_a) ← the center form of a
  7. 5x ← x_a + t_x w_a, y ← y_a + t_y h_a
  8. 6w ← w_a exp(t_w), h ← h_a exp(t_h)
  9. 7return (x - w/2, y - h/2, x + w/2, y + h/2)
  10. FIT(Φ, T, λ) ▷ R-CNN: one ridge regressor per coordinate
  11. 8W ← (Φ^T Φ + λ I)^-1 Φ^T T

DECODE inverts ENCODE, and ENCODE inverts DECODE. Both maps do not change when the same map p↦(sxpx+bx,sypy+by)p \mapsto (s_x p_x + b_x, s_y p_y + b_y) with sx,sy>0s_x, s_y > 0 is applied to aa and gg. A center error of ee widths, with the rest exact, gives an IoU of (1−∣e∣)/(1+∣e∣)(1 - |e|)/(1 + |e|) with the target for ∣e∣≤1|e| \le 1, and a log width error of ee gives an IoU of e−∣e∣e^{-|e|}. So an error of +e+e and an error of −e-e cost the same IoU, which a plain ratio w/waw/w_a does not give. The proofs are in the proof page.

Loss. R-CNN fits each coordinate by ridge regression on fixed features, with λ=1000\lambda = 1000 chosen on a validation set (line L8). Fast R-CNN trains the network with the smooth L1 loss

smooth⁡L1(z)={0.5z2∣z∣<1,∣z∣−0.5otherwise,\operatorname{smooth}_{L_1}(z) = \begin{cases} 0.5 z^2 & |z| < 1, \\ |z| - 0.5 & \text{otherwise}, \end{cases}

summed over the four coordinates of t^−t\hat t - t. This is the Huber function with threshold 1. It is quadratic near zero and grows linearly for large errors, so a few bad targets have a bounded gradient. Its derivative is zz inside [−1,1][-1, 1] and sign⁡(z)\operatorname{sign}(z) outside, which is continuous.

Cost. ENCODE and DECODE take O(1)O(1) time each, so O(n)O(n) for nn boxes in the real RAM model. FIT with mm training pairs and dd features costs O(md2)O(m d^2) for the normal equations and O(d3)O(d^3) to solve them, for each of the four coordinates.

Example. Take the anchor a=(0,0,10,10)a = (0, 0, 10, 10) and the true box g=(2,1,14,9)g = (2, 1, 14, 9). Then (xa,ya,wa,ha)=(5,5,10,10)(x_a, y_a, w_a, h_a) = (5, 5, 10, 10) and (x,y,w,h)=(8,5,12,8)(x, y, w, h) = (8, 5, 12, 8). The targets are t=(0.3,0,log⁡1.2,log⁡0.8)=(0.3,0,0.18232,−0.22314)t = (0.3, 0, \log 1.2, \log 0.8) = (0.3, 0, 0.18232, -0.22314). Suppose a model predicts t^=(0.25,0.1,0.2,−0.1)\hat t = (0.25, 0.1, 0.2, -0.1). The differences are (−0.05,0.1,0.01768,0.12314)(-0.05, 0.1, 0.01768, 0.12314), all inside [−1,1][-1, 1], so the smooth L1 loss is 0.50.5 times the sum of their squares, 0.0139880.013988. DECODE gives the center (7.5,6)(7.5, 6), the width 10e0.2=12.21410 e^{0.2} = 12.214 and the height 10e−0.1=9.04810 e^{-0.1} = 9.048, so the box is (1.393,1.476,13.607,10.524)(1.393, 1.476, 13.607, 10.524), with IoU 0.73280.7328 with gg.

Implementation. The Python code has ENCODE and DECODE with optional target weights, the inclusive pixel rule and a cap on twt_w and tht_h, the smooth L1 loss and its derivative, IoU and generalized IoU, and the ridge fit. The tests check the example above with exact fractions for txt_x and tyt_y, the two inverse properties on random boxes, the invariance under scaling and shifting, the two IoU formulas, the derivative of the loss against finite differences, and the ridge fit on targets that are linear in the features.

Classic examples

  • R-CNN. One class-specific linear regressor per coordinate on the pool5 features of the proposal, trained by ridge regression on pairs with IoU above 0.6. On PASCAL VOC 2007 test it raised the mean average precision from 54.2 to 58.5 percent (a benchmark result of the 2014 paper).
  • Fast R-CNN. The network outputs 4K4K offsets for KK classes, one set per class, and uses the set of the true class uu in the loss Lcls+λ[u≥1]LlocL_{cls} + \lambda [u \ge 1] L_{loc} with λ=1\lambda = 1. The targets are normalized to zero mean and unit variance over the training set.
  • Faster R-CNN. The region proposal stage uses the same encoding with an anchor as the reference box, and the second stage uses it again with the proposal as the reference.
  • Single shot multibox detector. The same encoding with the default boxes, divided in common code by "variances" 0.1 for the center and 0.2 for the size, which is the weighting of the next section with weights 10 and 5.
  • YOLO. The first YOLO does not use this encoding: it predicts the center as an offset inside a grid cell and the square roots of the width and height as fractions of the image. YOLOv2 returned to a reference box form, w=pwetww = p_w e^{t_w}, with the center kept inside its cell by a sigmoid.

Variations

  • Target weights. Detectron and torchvision multiply the targets of the second stage by (10,10,5,5)(10, 10, 5, 5), which has the effect of the normalization of Fast R-CNN with fixed constants.
  • A cap on the size offsets. Before the exponential, torchvision and Detectron2 cap twt_w and tht_h at log⁡(1000/16)≈4.135\log(1000/16) \approx 4.135, so one bad prediction cannot make a huge box.
  • IoU losses. Losses of the form 1−IoU⁡1 - \operatorname{IoU} or 1−GIoU⁡1 - \operatorname{GIoU} act on the decoded box and not on tt. Generalized IoU subtracts the share of the smallest enclosing box CC that the union does not cover, GIoU⁡=IoU⁡−∣C∖(A∪B)∣/∣C∣\operatorname{GIoU} = \operatorname{IoU} - |C \setminus (A \cup B)| / |C|, so it is still informative for boxes that do not overlap. DETR uses it with an L1 loss on the normalized center and size.
  • Distances to the sides. Anchor-free detectors predict the four distances from a point to the sides of the box, often in log form or divided by the stride.
  • Iterative refinement. Apply the regressor again to its own output, or use a cascade of regressors trained at higher IoU each.

Pitfalls

  • Inclusive and continuous widths. The +1+1 of inclusive pixel boxes must be used in both ENCODE and DECODE, or in neither. Code that mixes the two rules shifts every box by one pixel, which matters for small objects.
  • Corner form and center form. A target computed from corners with the center formulas, or the other way round, gives boxes that are wrong but look plausible. Convert once, at the boundary of the module.
  • The wrong reference box. In Faster R-CNN the second stage encodes relative to the proposal, not to the anchor that made the proposal.
  • Unnormalized targets. Without the weights or the normalization, the size terms and the center terms have different scales, and the loss weight λ\lambda that works for one detector fails for another.
  • Overflow in the exponential. An untrained network can output tw=50t_w = 50, and e50e^{50} is a box larger than any image. Cap the offset, then clip the box to the image.
  • Regressing far boxes. Training on reference boxes with a low IoU adds targets that the model cannot fit and makes the near ones worse.

Code

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

bounding_box_regression.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/bounding-box-regression/. The authors are listed in prov/TRRBN0.jsonl.
"""Bounding box regression: the offset encoding of R-CNN and its inverse.

A box is (x1, y1, x2, y2) in continuous image coordinates with x1 < x2 and
y1 < y2, so its width is x2 - x1. The reference box a (an anchor or a
proposal) and the target box g give the four targets

    t_x = (x - x_a) / w_a,  t_y = (y - y_a) / h_a,
    t_w = log(w / w_a),     t_h = log(h / h_a),

where (x, y) is the center and (w, h) the size. decode is the inverse map.
The optional weights (w_x, w_y, w_w, w_h) multiply the targets, as in
Detectron and torchvision (10, 10, 5, 5 for the second stage). The flag
inclusive=True uses the old PASCAL VOC rule w = x2 - x1 + 1 of the
py-faster-rcnn code. Standard library only.
"""

import math
from fractions import Fraction

# torchvision and Detectron2 clip t_w and t_h at log(1000 / 16) before exp.
DEFAULT_CLIP = math.log(1000.0 / 16)


def center_form(box, inclusive=False):
    """Return (x, y, w, h): the center and the size of a corner box."""
    one = 1 if inclusive else 0
    w = box[2] - box[0] + one
    h = box[3] - box[1] + one
    if isinstance(w, int) and isinstance(h, int):
        return (box[0] + Fraction(w, 2), box[1] + Fraction(h, 2), w, h)
    return (box[0] + w / 2, box[1] + h / 2, w, h)


def encode_shift(a, g, inclusive=False):
    """The two center targets (t_x, t_y), exact on integer boxes."""
    xa, ya, wa, ha = center_form(a, inclusive)
    x, y, _, _ = center_form(g, inclusive)
    return ((x - xa) / wa, (y - ya) / ha)


def encode(a, g, weights=(1.0, 1.0, 1.0, 1.0), inclusive=False):
    """Targets t = (t_x, t_y, t_w, t_h) of the box g with respect to the box a."""
    xa, ya, wa, ha = center_form(a, inclusive)  # @line L1
    x, y, w, h = center_form(g, inclusive)  # @line L2
    if wa <= 0 or ha <= 0 or w <= 0 or h <= 0:
        raise ValueError("boxes need a positive width and height")
    return (weights[0] * float(x - xa) / float(wa),  # @line L3
            weights[1] * float(y - ya) / float(ha),
            weights[2] * math.log(float(w) / float(wa)),
            weights[3] * math.log(float(h) / float(ha)))


def decode(a, t, weights=(1.0, 1.0, 1.0, 1.0), clip=None, inclusive=False):
    """The box that the targets t give from the box a; clip caps t_w and t_h."""
    xa, ya, wa, ha = (float(v) for v in center_form(a, inclusive))  # @line L4
    tx, ty, tw, th = (t[i] / weights[i] for i in range(4))
    if clip is not None:
        tw, th = min(tw, clip), min(th, clip)
    x, y = xa + tx * wa, ya + ty * ha  # @line L5
    w, h = wa * math.exp(tw), ha * math.exp(th)  # @line L6
    one = 1.0 if inclusive else 0.0
    return (x - w / 2, y - h / 2, x + w / 2 - one, y + h / 2 - one)  # @line L7


def smooth_l1(x, beta=1.0):
    """Smooth L1 of Fast R-CNN: 0.5 x^2 / beta for |x| < beta, else |x| - 0.5 beta."""
    ax = abs(x)
    return 0.5 * x * x / beta if ax < beta else ax - 0.5 * beta


def smooth_l1_grad(x, beta=1.0):
    """Derivative of smooth_l1: x / beta inside, sign(x) outside; it is continuous."""
    if abs(x) < beta:
        return x / beta
    return 1.0 if x > 0 else -1.0


def box_loss(t_pred, t_true, beta=1.0):
    """The sum of smooth L1 over the four coordinates."""
    return sum(smooth_l1(p - q, beta) for p, q in zip(t_pred, t_true))


def area(b):
    return (b[2] - b[0]) * (b[3] - b[1])


def iou(a, b):
    """IoU of two boxes; a Fraction on integer boxes."""
    iw = min(a[2], b[2]) - max(a[0], b[0])
    ih = min(a[3], b[3]) - max(a[1], b[1])
    inter = iw * ih if iw > 0 and ih > 0 else 0
    union = area(a) + area(b) - inter
    if isinstance(inter, int) and isinstance(union, int):
        return Fraction(inter, union)
    return inter / union


def giou(a, b):
    """Generalized IoU of Rezatofighi et al.: IoU minus the empty share of the enclosing box."""
    c = (min(a[0], b[0]), min(a[1], b[1]), max(a[2], b[2]), max(a[3], b[3]))
    iw = min(a[2], b[2]) - max(a[0], b[0])
    ih = min(a[3], b[3]) - max(a[1], b[1])
    inter = iw * ih if iw > 0 and ih > 0 else 0
    union = area(a) + area(b) - inter
    ac = area(c)
    if all(isinstance(v, int) for v in (inter, union, ac)):
        return Fraction(inter, union) - Fraction(ac - union, ac)
    return inter / union - (ac - union) / ac


def solve(m, rhs):
    """Solve m x = rhs by Gaussian elimination with partial pivoting."""
    n = len(m)
    a = [list(map(float, row)) + [float(r)] for row, r in zip(m, rhs)]
    for c in range(n):
        p = max(range(c, n), key=lambda r: abs(a[r][c]))
        if abs(a[p][c]) < 1e-300:
            raise ValueError("singular system")
        a[c], a[p] = a[p], a[c]
        for r in range(c + 1, n):
            f = a[r][c] / a[c][c]
            for k in range(c, n + 1):
                a[r][k] -= f * a[c][k]
    x = [0.0] * n
    for r in range(n - 1, -1, -1):
        x[r] = (a[r][n] - sum(a[r][k] * x[k] for k in range(r + 1, n))) / a[r][r]
    return x


def fit_ridge(features, targets, lam):
    """R-CNN regressor for one coordinate: argmin_w sum (t_i - w . phi_i)^2 + lam ||w||^2."""
    d = len(features[0])
    gram = [[sum(f[i] * f[j] for f in features) + (lam if i == j else 0.0) for j in range(d)]
            for i in range(d)]  # @line L8
    rhs = [sum(f[i] * t for f, t in zip(features, targets)) for i in range(d)]
    return solve(gram, rhs)
test_bounding_box_regression.py 129 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/bounding-box-regression/. The authors are listed in prov/TRRBN0.jsonl.

import math
import random
from fractions import Fraction

from bounding_box_regression import (
    DEFAULT_CLIP,
    box_loss,
    decode,
    encode,
    encode_shift,
    fit_ridge,
    giou,
    iou,
    smooth_l1,
    smooth_l1_grad,
)


def rand_box(rng, lo=-50.0, hi=50.0):
    x1, y1 = rng.uniform(lo, hi), rng.uniform(lo, hi)
    return (x1, y1, x1 + rng.uniform(1.0, 60.0), y1 + rng.uniform(1.0, 60.0))


def close(a, b, tol=1e-9):
    return all(abs(p - q) <= tol * max(1.0, abs(p), abs(q)) for p, q in zip(a, b))


def test_page_example():
    a, g = (0, 0, 10, 10), (2, 1, 14, 9)
    assert encode_shift(a, g) == (Fraction(3, 10), Fraction(0))
    t = encode(a, g)
    assert close(t, (0.3, 0.0, math.log(1.2), math.log(0.8)))
    assert close(decode(a, t), g)


def test_decode_inverts_encode():
    rng = random.Random(1)
    for _ in range(300):
        a, g = rand_box(rng), rand_box(rng)
        assert close(decode(a, encode(a, g)), g, 1e-9)
        w = (10.0, 10.0, 5.0, 5.0)
        assert close(decode(a, encode(a, g, w), w), g, 1e-9)


def test_encode_inverts_decode():
    rng = random.Random(2)
    for _ in range(300):
        a = rand_box(rng)
        t = tuple(rng.uniform(-2.0, 2.0) for _ in range(4))
        assert close(encode(a, decode(a, t)), t, 1e-9)


def test_inclusive_round_trip():
    rng = random.Random(3)
    for _ in range(100):
        x1, y1 = rng.randint(0, 50), rng.randint(0, 50)
        a = (x1, y1, x1 + rng.randint(0, 40), y1 + rng.randint(0, 40))
        x1, y1 = rng.randint(0, 50), rng.randint(0, 50)
        g = (x1, y1, x1 + rng.randint(0, 40), y1 + rng.randint(0, 40))
        assert close(decode(a, encode(a, g, inclusive=True), inclusive=True), g, 1e-9)


def test_invariance_under_scaling_and_shift():
    rng = random.Random(4)
    for _ in range(200):
        a, g = rand_box(rng), rand_box(rng)
        sx, sy = rng.uniform(0.1, 10.0), rng.uniform(0.1, 10.0)
        bx, by = rng.uniform(-100, 100), rng.uniform(-100, 100)

        def m(b):
            return (sx * b[0] + bx, sy * b[1] + by, sx * b[2] + bx, sy * b[3] + by)

        assert close(encode(m(a), m(g)), encode(a, g), 1e-9)


def test_iou_after_one_coordinate_error():
    # A center error e (in widths) gives IoU (1 - |e|) / (1 + |e|); a log-width error e gives exp(-|e|).
    rng = random.Random(5)
    for _ in range(100):
        g = rand_box(rng)
        t = encode(g, g)
        e = rng.uniform(-0.9, 0.9)
        shifted = decode(g, (t[0] + e, t[1], t[2], t[3]))
        assert abs(iou(shifted, g) - (1 - abs(e)) / (1 + abs(e))) < 1e-9
        grown = decode(g, (t[0], t[1], t[2] + e, t[3]))
        assert abs(iou(grown, g) - math.exp(-abs(e))) < 1e-9


def test_clip_caps_growth():
    a = (0.0, 0.0, 16.0, 16.0)
    b = decode(a, (0.0, 0.0, 50.0, 50.0), clip=DEFAULT_CLIP)
    assert abs((b[2] - b[0]) - 1000.0) < 1e-6


def test_smooth_l1_values_and_gradient():
    assert smooth_l1(0.5) == 0.125
    assert smooth_l1(-2.0) == 1.5
    assert smooth_l1(1.0) == 0.5
    for x in [-3.0, -1.2, -0.7, -0.1, 0.0, 0.3, 0.99, 1.5, 4.0]:
        h = 1e-6
        num = (smooth_l1(x + h) - smooth_l1(x - h)) / (2 * h)
        assert abs(num - smooth_l1_grad(x)) < 1e-5
    assert box_loss((0.5, -2.0, 0.0, 0.0), (0.0, 0.0, 0.0, 0.0)) == 1.625


def test_iou_and_giou_check_values():
    assert iou((0, 0, 2, 2), (1, 1, 3, 3)) == Fraction(1, 7)
    assert iou((0, 0, 10, 10), (5, 0, 15, 10)) == Fraction(1, 3)
    assert giou((0, 0, 2, 2), (1, 1, 3, 3)) == Fraction(-5, 63)
    assert giou((0, 0, 1, 1), (2, 0, 3, 1)) == Fraction(-1, 3)
    rng = random.Random(6)
    for _ in range(200):
        a, b = rand_box(rng), rand_box(rng)
        assert -1.0 < giou(a, b) <= iou(a, b) + 1e-12


def test_ridge_recovers_linear_targets():
    rng = random.Random(7)
    w_true = [0.5, -1.0, 2.0, 0.25]
    feats = [[rng.uniform(-1, 1) for _ in range(4)] for _ in range(80)]
    ys = [sum(w * f for w, f in zip(w_true, row)) for row in feats]
    w = fit_ridge(feats, ys, 1e-9)
    assert close(w, w_true, 1e-6)
    # A large lambda shrinks the weights toward zero.
    w_big = fit_ridge(feats, ys, 1e6)
    assert max(abs(v) for v in w_big) < 1e-3

Exercises

  1. Show that DECODE(a, ENCODE(a, g)) = g and ENCODE(a, DECODE(a, t)) = t for all boxes with positive sizes and all t∈R4t \in \mathbb{R}^4.
  2. Two boxes have the same height and yy range, the same width ww, and centers dd apart with d≤wd \le w. Show that their IoU is (w−d)/(w+d)(w - d)/(w + d), and find the largest center error in widths that keeps an IoU of 0.5.
  3. Show that if the target width is waeew_a e^{e} and everything else is exact, the IoU is e−∣e∣e^{-|e|}. What IoU does the ratio form w/wa−1=ew/w_a - 1 = e give for e=0.5e = 0.5 and e=−0.5e = -0.5?
  4. Write the inclusive form of DECODE so that it inverts the inclusive ENCODE, and check it on the box (0,0,9,9)(0, 0, 9, 9) and the target (2,1,13,8)(2, 1, 13, 8).
  5. Show that ΦTΦ+λI\Phi^{\mathsf T}\Phi + \lambda I is positive definite for λ>0\lambda > 0, so line L8 has exactly one solution even when two features are equal.
Proof: The box encoding is a bijection with DECODE as its inverse, it does not change under axis scaling and shifting, and it maps one-coordinate errors to IoU in closed formfull

Let B\mathcal{B} be the set of boxes (x1,y1,x2,y2)(x_1, y_1, x_2, y_2) with x1<x2x_1 < x_2 and y1<y2y_1 < y_2. The center form c(b)=(x,y,w,h)c(b) = (x, y, w, h) with w=x2−x1w = x_2 - x_1, h=y2−y1h = y_2 - y_1, x=x1+w/2x = x_1 + w/2, y=y1+h/2y = y_1 + h/2 is a bijection from B\mathcal{B} onto R2×(0,∞)2\mathbb{R}^2 \times (0, \infty)^2, with inverse (x,y,w,h)↦(x−w/2,y−h/2,x+w/2,y+h/2)(x, y, w, h) \mapsto (x - w/2, y - h/2, x + w/2, y + h/2): the inverse gives x1=x−w/2x_1 = x - w/2 and x2−x1=w>0x_2 - x_1 = w > 0, and the center form of that box is (x,y,w,h)(x, y, w, h) again.

Fix a reference box aa with center form (xa,ya,wa,ha)(x_a, y_a, w_a, h_a), wa,ha>0w_a, h_a > 0.

Claim 1 (inverse maps). For every g∈Bg \in \mathcal{B}, DECODE(a, ENCODE(a, g)) = g. For every t∈R4t \in \mathbb{R}^4, DECODE(a, t) is in B\mathcal{B} and ENCODE(a, DECODE(a, t)) = t.

Proof. Let (x,y,w,h)=c(g)(x, y, w, h) = c(g) and let tt be the output of line L3. Line L5 gives xa+txwa=xa+(x−xa)=xx_a + t_x w_a = x_a + (x - x_a) = x, and the same for yy. Line L6 gives waexp⁡(log⁡(w/wa))=ww_a \exp(\log(w / w_a)) = w, since w/wa>0w / w_a > 0, and the same for hh. Line L7 is the inverse of the center form, so the result is gg. For the second part, lines L5 and L6 give w=waetw>0w = w_a e^{t_w} > 0 and h=haeth>0h = h_a e^{t_h} > 0, so the box of line L7 is in B\mathcal{B} with center form (xa+txwa,ya+tyha,waetw,haeth)(x_a + t_x w_a, y_a + t_y h_a, w_a e^{t_w}, h_a e^{t_h}). Line L3 applied to it gives ((txwa)/wa,(tyha)/ha,log⁡etw,log⁡eth)=t((t_x w_a)/w_a, (t_y h_a)/h_a, \log e^{t_w}, \log e^{t_h}) = t. □\square

So ENCODE(a, ·) is a bijection from B\mathcal{B} onto R4\mathbb{R}^4, and the network output needs no constraint to decode to a valid box.

Claim 2 (invariance). Let m(p)=(sxpx+bx,sypy+by)m(p) = (s_x p_x + b_x, s_y p_y + b_y) with sx,sy>0s_x, s_y > 0, applied to the two corners of a box. Then ENCODE(m(a), m(g)) = ENCODE(a, g).

Proof. Since sx>0s_x > 0, mm keeps x1<x2x_1 < x_2, and the image box has width sxws_x w and center sxx+bxs_x x + b_x; the same holds for yy with sys_y. So txt_x becomes (sxx+bx−sxxa−bx)/(sxwa)=(x−xa)/wa(s_x x + b_x - s_x x_a - b_x)/(s_x w_a) = (x - x_a)/w_a, and twt_w becomes log⁡(sxw/(sxwa))=log⁡(w/wa)\log(s_x w / (s_x w_a)) = \log(w / w_a). The yy terms are the same. □\square

Claim 3 (IoU after one error). Let g∈Bg \in \mathcal{B} with center form (x,y,w,h)(x, y, w, h), and decode with gg itself as the reference.

  1. If t=(e,0,0,0)t = (e, 0, 0, 0) with ∣e∣≤1|e| \le 1, the decoded box has IoU (1−∣e∣)/(1+∣e∣)(1 - |e|)/(1 + |e|) with gg.
  2. If t=(0,0,e,0)t = (0, 0, e, 0) for any real ee, the decoded box has IoU e−∣e∣e^{-|e|} with gg.

Proof. (1) The decoded box is gg shifted by d=∣e∣w≤wd = |e| w \le w along xx. The two boxes share the yy range of length hh, and their xx ranges overlap in a length w−d≥0w - d \ge 0. So the intersection is (w−d)h(w - d)h and the union is 2wh−(w−d)h=(w+d)h2wh - (w - d)h = (w + d)h, and the IoU is (w−d)/(w+d)=(1−∣e∣)/(1+∣e∣)(w - d)/(w + d) = (1 - |e|)/(1 + |e|). (2) The decoded box has the same center and height and width weew e^{e}. The two boxes are nested, so the IoU is the smaller area over the larger one, min⁡(1,ee)/max⁡(1,ee)=e−∣e∣\min(1, e^{e}) / \max(1, e^{e}) = e^{-|e|}. □\square

Claim 4 (smooth L1). The function f(z)=0.5z2f(z) = 0.5 z^2 for ∣z∣<1|z| < 1 and ∣z∣−0.5|z| - 0.5 otherwise is continuously differentiable with f′(z)=zf'(z) = z for ∣z∣<1|z| < 1 and f′(z)=sign⁡(z)f'(z) = \operatorname{sign}(z) for ∣z∣≥1|z| \ge 1, and ∣f′(z)∣≤1|f'(z)| \le 1.

Proof. On each open piece ff is a polynomial with the stated derivative. At z=1z = 1 both pieces give f(1)=0.5f(1) = 0.5, and both one-sided derivatives are 11; at z=−1z = -1 both give 0.50.5 and −1-1. So ff is differentiable everywhere, and f′f' is continuous. The bound follows from the formula. □\square

Claim 5 (ridge fit). For λ>0\lambda > 0, line L8 has exactly one solution, and it is the unique minimizer of ∥T−ΦW∥2+λ∥W∥2\|T - \Phi W\|^2 + \lambda \|W\|^2.

Proof. For v≠0v \ne 0, vT(ΦTΦ+λI)v=∥Φv∥2+λ∥v∥2>0v^{\mathsf T}(\Phi^{\mathsf T}\Phi + \lambda I)v = \|\Phi v\|^2 + \lambda \|v\|^2 > 0, so the matrix is positive definite and invertible. The objective is a strictly convex quadratic with gradient 2(ΦTΦ+λI)W−2ΦTT2(\Phi^{\mathsf T}\Phi + \lambda I)W - 2\Phi^{\mathsf T}T, which is zero exactly at the WW of line L8. □\square

The code solves the system of line L8 by Gaussian elimination with partial pivoting, which gives the exact solution in exact arithmetic for a nonsingular matrix.

References

  1. Ross Girshick, Jeff Donahue, Trevor Darrell and Jitendra Malik, Rich feature hierarchies for accurate object detection and semantic segmentation, CVPR 2014, 580-587 (arXiv 1311.2524, version 5 with appendices), Appendix C, Bounding-box regression (the targets t_x, t_y, t_w, t_h, ridge regression on pool5 features with lambda = 1000, training pairs with IoU above 0.6)
  2. Ross Girshick, Fast R-CNN, ICCV 2015, 1440-1448, Section 2.3, Multi-task loss (Eq. 1 to 3: class-specific targets, the smooth L1 loss, lambda = 1, targets normalized to zero mean and unit variance)
  3. Shaoqing Ren, Kaiming He, Ross Girshick and Jian Sun, Faster R-CNN: towards real-time object detection with region proposal networks, IEEE Transactions on Pattern Analysis and Machine Intelligence 39(6), 2017, 1137-1149, Section 3.1.2, Loss function (Eq. 2, the same encoding with anchors as the reference boxes)
  4. Hamid Rezatofighi, Nathan Tsoi, JunYoung Gwak, Amir Sadeghian, Ian Reid and Silvio Savarese, Generalized intersection over union: a metric and a loss for bounding box regression, CVPR 2019, Section 3 (the definition of GIoU and the loss 1 - GIoU)
  5. Richard Szeliski, Computer Vision, Algorithms and Applications, second edition, Springer, 2022, Section 6.3, Object detection

Where this leads

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH2 full proof
  • correctness: no review record reviews/TRRBN0/proof-correctness.yaml
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • five exercises