Sub topic 12
Anchor-free detection: FCOS and CenterNet
This chapter assumes you know how anchors are matched to ground truth, how focal loss works, and how non-maximum suppression (NMS) removes duplicates. You should also be comfortable with feature pyramids and NumPy.
Why drop anchors
Anchor-based detectors carry design choices that depend on the dataset:
- You must pick anchor scales, aspect ratios and IoU thresholds for positives and negatives.
- Most anchors are negatives, which is why focal loss was needed.
- Every anchor adds regression outputs and matching cost.
Anchor-free detectors remove the reference boxes. Each location on a feature map predicts a box directly, or predicts that it is the center of one. This chapter covers two designs: FCOS, which predicts distances from a location to the box sides, and CenterNet, which predicts object centers as heatmap peaks.
FCOS: per-pixel box regression
FCOS (Fully Convolutional One-Stage detection) treats every feature-map location as a training sample. A location at image coordinates (x, y) is a positive if it falls inside a ground-truth box. It then regresses four distances to the box sides, (l, t, r, b), instead of offsets from an anchor.
- l = x − x1
- t = y − y1
- r = x2 − x
- b = y2 − y
Because the targets are plain distances, there is no anchor to encode against. The network applies a non-negative function such as exp to its raw outputs, so the predicted distances are positive.
Centerness
Locations near the edge of a box tend to produce poor boxes. FCOS adds a third branch that predicts centerness, a score between 0 and 1 that measures how close a location is to the box center:
centerness = sqrt( min(l, r) / max(l, r) × min(t, b) / max(t, b) )
At inference, the final score is the classification score multiplied by the predicted centerness. Off-center, low-quality boxes get low scores and lose to better ones during NMS.
import math
def fcos_targets(x, y, box):
"""Return ((l, t, r, b), centerness) for a location, or None if outside."""
x1, y1, x2, y2 = box
l, t, r, b = x - x1, y - y1, x2 - x, y2 - y
if min(l, t, r, b) <= 0:
return None
centerness = math.sqrt(min(l, r) / max(l, r) * min(t, b) / max(t, b))
return (l, t, r, b), centerness
box = (10, 20, 50, 60)
print(fcos_targets(30, 40, box)) # ((20, 20, 20, 20), 1.0)
print(fcos_targets(15, 40, box)) # ((5, 20, 35, 20), 0.3779644730092272)
print(fcos_targets(5, 40, box)) # NoneAmbiguity and scale ranges
Two problems follow from using every interior location as a positive.
- Overlapping boxes. A location inside two ground-truth boxes has two possible targets. FCOS picks the box with the smallest area.
- Scale. A large object produces many positives at fine resolution, and some of them are far from the center. FCOS assigns each pyramid level a range for max(l, t, r, b). A location is positive at a level only if its largest distance falls in that level's range. In the original paper, levels P3 to P7 use the ranges 0–64, 64–128, 128–256, 256–512 and 512 and above. This replaces the anchor-size role that FPN levels had in RetinaNet.
The training loss has three parts: focal loss for classification, an IoU-based loss (IoU or GIoU) for the box distances, and binary cross-entropy for centerness. Inference still needs NMS, because neighboring locations on the same object each produce a box.
CenterNet: objects as points
CenterNet ("Objects as Points") changes the problem more. Each object is a single point, its box center. The network outputs, at stride 4 relative to the input:
- A heatmap with one channel per class. A peak means "an object center is here."
- A width and height map. The size is read at the peak.
- A local offset map. This recovers the sub-pixel precision lost by the stride.
Training targets
For each ground-truth center, scaled to the output resolution and rounded to an integer cell, the target heatmap gets a 2D Gaussian. The heatmap value is exactly 1 at the center and decays outward. If Gaussians from several objects of one class overlap, the element-wise maximum is taken. The Gaussian radius depends on the box size, so large boxes tolerate larger center error.
The heatmap loss is a penalty-reduced variant of focal loss. Only the exact center cell counts as positive. Cells near the center are negatives, but their penalty is scaled down by (1 − Gaussian value) raised to a power. Size and offset use L1 losses, computed only at center cells.
Decoding without NMS
At inference, CenterNet keeps a heatmap cell only if its value is at least that of its eight neighbors. Implementations do this with a 3×3 max-pooling and an equality test. The top-K surviving peaks become detections. This max-pool step plays the role of NMS, so no IoU computation is needed.
import numpy as np
def gaussian_heatmap(shape, center, sigma):
h, w = shape
ys, xs = np.mgrid[0:h, 0:w]
cx, cy = center
return np.exp(-((xs - cx) ** 2 + (ys - cy) ** 2) / (2 * sigma ** 2))
def find_peaks(heat, k=5):
"""Cells that equal the max of their 3x3 neighborhood, best first."""
h, w = heat.shape
padded = np.pad(heat, 1, constant_values=-np.inf)
shifts = [padded[1 + dy:1 + dy + h, 1 + dx:1 + dx + w]
for dy in (-1, 0, 1) for dx in (-1, 0, 1)]
local_max = np.max(shifts, axis=0)
ys, xs = np.nonzero(heat == local_max)
scores = heat[ys, xs]
order = np.argsort(-scores)[:k]
return [(int(xs[i]), int(ys[i]), float(scores[i])) for i in order]
heat = np.maximum(
gaussian_heatmap((8, 8), (2, 3), 1.5),
0.8 * gaussian_heatmap((8, 8), (6, 5), 1.0),
)
print(find_peaks(heat)) # [(2, 3, 1.0), (6, 5, 0.8)]Comparing the two designs
| Aspect | FCOS | CenterNet |
|---|---|---|
| Positive samples | All locations inside a box (within a scale range) | One center cell per object |
| Box output | Distances l, t, r, b | Width and height plus offset |
| Multi-scale | Feature pyramid with per-level ranges | Single high-resolution map |
| Duplicate removal | NMS | Max-pool peak picking |
| Classification loss | Focal loss | Penalty-reduced focal loss |
Edge cases and failure modes
- Centers can collide. Two same-class objects whose centers land in the same output cell produce one peak. CenterNet detects only one of them. This is rare at stride 4 but happens in crowds.
- Center outside the object. For some shapes, such as a crescent or a person with outstretched arms, the box center lies on background. A center-based method must learn to fire on pixels that are not on the object.
- Max-pool is not full NMS. The 3×3 window suppresses only adjacent cells. Two peaks four cells apart that describe the same object both survive. Some pipelines still add NMS for this reason.
- FCOS low-quality boxes. Without centerness or center sampling, boundary locations create many poor, high-scoring boxes.
- Resolution cost. A stride-4 heatmap is memory-heavy at large input sizes. FCOS spreads the cost across pyramid levels.
Exercise
A location at (30, 25) lies inside the box (10, 20, 50, 60). Compute its FCOS targets (l, t, r, b) and its centerness. Is this location better or worse than the box center at (30, 40)?
Show answer
l = 30 − 10 = 20, t = 25 − 20 = 5, r = 50 − 30 = 20, b = 60 − 25 = 35. Centerness = sqrt(min(20, 20)/max(20, 20) × min(5, 35)/max(5, 35)) = sqrt(1 × 5/35) = sqrt(0.1429) ≈ 0.378. The center at (30, 40) has l = r = 20 and t = b = 20, so its centerness is 1.0. The location at (30, 25) is worse, and its final score is cut to about 38% of the classification score.
Exercise
Why can CenterNet skip NMS, and in what situation might you still want it?
Show answer
Each object is trained to produce one heatmap peak. Keeping only cells that equal the maximum of their 3x3 neighborhood removes adjacent duplicates. This works like NMS but needs no IoU computation. You may still want NMS when the model produces distant duplicate peaks for one large object, because the 3x3 window does not suppress peaks that are several cells apart.