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 for each prediction and a target box for training. A box is in continuous image coordinates with and , with to the right and down. Its center form is with , , and . Old PASCAL VOC code uses inclusive pixel boxes with ; this page uses the continuous form unless it says otherwise.
The targets are
The map from to is a bijection from the boxes with onto . A model predicts from the features of the reference box, and the decoded box is the inverse map applied to .
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
ENCODE(a, g) ▷ reference box a, target box g- 1
(x_a, y_a, w_a, h_a) ← the center form of a - 2
(x, y, w, h) ← the center form of g - 3
return ((x - x_a) / w_a, (y - y_a) / h_a, log(w / w_a), log(h / h_a)) DECODE(a, t)- 4
(x_a, y_a, w_a, h_a) ← the center form of a - 5
x ← x_a + t_x w_a, y ← y_a + t_y h_a - 6
w ← w_a exp(t_w), h ← h_a exp(t_h) - 7
return (x - w/2, y - h/2, x + w/2, y + h/2) FIT(Φ, T, λ) ▷ R-CNN: one ridge regressor per coordinate- 8
W ← (Φ^T Φ + λ I)^-1 Φ^T T
DECODE inverts ENCODE, and ENCODE inverts DECODE. Both maps do not change when the same map with is applied to and . A center error of widths, with the rest exact, gives an IoU of with the target for , and a log width error of gives an IoU of . So an error of and an error of cost the same IoU, which a plain ratio does not give. The proofs are in the proof page.
Loss. R-CNN fits each coordinate by ridge regression on fixed features, with chosen on a validation set (line L8). Fast R-CNN trains the network with the smooth L1 loss
summed over the four coordinates of . 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 inside and outside, which is continuous.
Cost. ENCODE and DECODE take time each, so for boxes in the real RAM model. FIT with training pairs and features costs for the normal equations and to solve them, for each of the four coordinates.
Example. Take the anchor and the true box . Then and . The targets are . Suppose a model predicts . The differences are , all inside , so the smooth L1 loss is times the sum of their squares, . DECODE gives the center , the width and the height , so the box is , with IoU with .
Implementation. The Python code has ENCODE and DECODE with optional target weights, the inclusive pixel rule and a cap on and , 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 and , 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 offsets for classes, one set per class, and uses the set of the true class in the loss with . 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, , with the center kept inside its cell by a sigmoid.
Variations
- Target weights. Detectron and torchvision multiply the targets of the second stage by , 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 and at , so one bad prediction cannot make a huge box.
- IoU losses. Losses of the form or act on the decoded box and not on . Generalized IoU subtracts the share of the smallest enclosing box that the union does not cover, , 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 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 that works for one detector fails for another.
- Overflow in the exponential. An untrained network can output , and 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.
# 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
- Show that DECODE(a, ENCODE(a, g)) = g and ENCODE(a, DECODE(a, t)) = t for all boxes with positive sizes and all .
- Two boxes have the same height and range, the same width , and centers apart with . Show that their IoU is , and find the largest center error in widths that keeps an IoU of 0.5.
- Show that if the target width is and everything else is exact, the IoU is . What IoU does the ratio form give for and ?
- Write the inclusive form of DECODE so that it inverts the inclusive ENCODE, and check it on the box and the target .
- Show that is positive definite for , 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 be the set of boxes with and . The center form with , , , is a bijection from onto , with inverse : the inverse gives and , and the center form of that box is again.
Fix a reference box with center form , .
Claim 1 (inverse maps). For every , DECODE(a, ENCODE(a, g)) = g. For every , DECODE(a, t) is in and ENCODE(a, DECODE(a, t)) = t.
Proof. Let and let be the output of line L3. Line L5 gives , and the same for . Line L6 gives , since , and the same for . Line L7 is the inverse of the center form, so the result is . For the second part, lines L5 and L6 give and , so the box of line L7 is in with center form . Line L3 applied to it gives .
So ENCODE(a, ·) is a bijection from onto , and the network output needs no constraint to decode to a valid box.
Claim 2 (invariance). Let with , applied to the two corners of a box. Then ENCODE(m(a), m(g)) = ENCODE(a, g).
Proof. Since , keeps , and the image box has width and center ; the same holds for with . So becomes , and becomes . The terms are the same.
Claim 3 (IoU after one error). Let with center form , and decode with itself as the reference.
- If with , the decoded box has IoU with .
- If for any real , the decoded box has IoU with .
Proof. (1) The decoded box is shifted by along . The two boxes share the range of length , and their ranges overlap in a length . So the intersection is and the union is , and the IoU is . (2) The decoded box has the same center and height and width . The two boxes are nested, so the IoU is the smaller area over the larger one, .
Claim 4 (smooth L1). The function for and otherwise is continuously differentiable with for and for , and .
Proof. On each open piece is a polynomial with the stated derivative. At both pieces give , and both one-sided derivatives are ; at both give and . So is differentiable everywhere, and is continuous. The bound follows from the formula.
Claim 5 (ridge fit). For , line L8 has exactly one solution, and it is the unique minimizer of .
Proof. For , , so the matrix is positive definite and invertible. The objective is a strictly convex quadratic with gradient , which is zero exactly at the of line L8.
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
- 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)
- 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)
- 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)
- 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)
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H2 full proof |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag TRRBN0 Edit this page History Report an error Markdown