Sub topic 5
Predicting Offsets Instead of Raw Coordinates
Why detectors predict offsets
Assume you know basic Python, NumPy, convolutional feature maps, and regression losses. You should also know that an object detector predicts both a class and a bounding box.
A bounding box can be represented by its center (cx, cy), width w, and height h. A simple approach would ask the model to predict these four values directly. This is difficult because image sizes vary. A box center might be near 10 in one image and near 900 in another. Widths and heights also have very different scales.
Anchor-based detectors solve this by predicting offsets from an anchor box. An anchor is a reference box with a known position and size. The model learns how to move and resize the anchor until it fits the object.
The offset encoding
Let an anchor have center (cx_a, cy_a), width w_a, and height h_a. Let the ground-truth box have corresponding values (cx, cy, w, h). The training targets are:
t_x = \frac{cx - cx_a}{w_a}t_y = \frac{cy - cy_a}{h_a}t_w = \log\left(\frac{w}{w_a}\right)t_h = \log\left(\frac{h}{h_a}\right)The center offsets are normalized by the anchor dimensions. The width and height use logarithms because object sizes can vary multiplicatively. For example, doubling a width and halving a width become symmetric changes: log(2) and log(0.5).
| Target | Meaning | Decoding formula |
|---|---|---|
| `tx` | horizontal center shift | `cx = cx_a + tx * w_a` |
| `ty` | vertical center shift | `cy = cy_a + ty * h_a` |
| `tw` | width scale change | `w = w_a * exp(tw)` |
| `th` | height scale change | `h = h_a * exp(th)` |
Encoding and decoding in Python
import math
def decode(anchor, deltas):
"""Decode (tx, ty, tw, th) for an anchor (cx, cy, w, h)."""
cx_a, cy_a, w_a, h_a = anchor
tx, ty, tw, th = deltas
cx = cx_a + tx * w_a
cy = cy_a + ty * h_a
w = w_a * math.exp(tw)
h = h_a * math.exp(th)
return cx, cy, w, h
anchor = (50, 50, 20, 40)
deltas = (0.1, -0.05, 0.0, math.log(2))
print(decode(anchor, deltas))
# (52.0, 48.0, 20.0, 80.0)The predicted tx of 0.1 moves the center right by 10% of the anchor width: 2 pixels. The predicted ty moves the center up by 2 pixels. A tw of zero keeps the width unchanged. A th of log(2) doubles the height.
Common errors
- Applying
expto center offsets. Only width and height use exponentials. - Using pixel shifts directly when the training target expects normalized shifts.
- Mixing coordinate conventions, such as
(x1, y1, x2, y2)and(cx, cy, w, h). - Forgetting that the same encoding must be used during training and decoding.
- Allowing invalid anchors with zero or negative width and height.
Exercise
An anchor is (cx=40, cy=30, w=20, h=10), and the predicted deltas are (0.5, -1.0, log(2), 0). What decoded box is produced?
Show answer
The center is (50, 20), the width is 40, and the height is 10.