Assign anchor boxes to ground-truth objects for detector training

Anchor-based detectors place many fixed boxes over the image and must decide, before computing any loss, which anchor is responsible for which object. Small objects often overlap no anchor well, so a second pass guarantees every object gets at least one anchor.

Write match_anchors(anchors, gts, pos_thr, neg_thr). anchors has shape (A, 4), gts has shape (G, 4), boxes are [x1, y1, x2, y2]. Area is (x2 - x1) * (y2 - y1). IoU is intersection over union, and 0 when the union is 0.
1. For each anchor take its best gt by IoU (lowest gt index on ties). Label it with that gt index if best IoU >= pos_thr, -1 (background) if best IoU < neg_thr, else -2 (ignore).
2. Then for each gt j in increasing order, find the anchor with the highest IoU to j (lowest anchor index on ties). If that IoU > 0, set that anchor's label to j, overwriting anything earlier.
If G is 0, every anchor is -1. Return a list of A ints.

Signaturedef match_anchors(anchors, gts, pos_thr, neg_thr)

Example

anchors [[0, 0, 10, 10], [20, 20, 30, 30]], gts [[0, 0, 10, 10]], thresholds 0.5 and 0.4 give [0, -1].

Understand the idea

An anchor-based detector covers the image with fixed boxes and, before any loss, decides which anchor is responsible for which object. The measure is IoU: overlap area divided by the area of the union. Worked example: anchor [0, 0, 10, 10] and object [5, 0, 15, 10]. Intersection is 5 * 10 = 50, union is 100 + 100 - 50 = 150, so IoU = 0.333. With pos_thr 0.5 and neg_thr 0.4, this anchor's best IoU is below 0.4, so pass one labels it -1 (background). Pass one rule: each anchor takes its best object (lowest index on ties); IoU >= pos_thr gives that object index, below neg_thr gives -1, anything in between gives -2 (ignore). Pass two: for each object in order, find its single best anchor (lowest index on ties) and, if that IoU is above 0, force the label to that object, even overwriting earlier choices. In the example, if this is the object's best anchor, its label becomes the object index despite IoU 0.333. Without pass two, small objects can end up with no positive anchor. Used in SSD, RetinaNet and Faster R-CNN style training.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: examplematch_anchors([[0, 0, 10, 10], [20, 20, 30, 30]], [[0, 0, 10, 10]], 0.5, 0.4)
  • Sample 2: small object forced matchmatch_anchors(_anc, _gt, 0.5, 0.3)