Every Template Gets a Job

Using Vision ModelsMedium+20 XP+20

Every Template Gets a Job

Many detectors, from some one-stage designs to the proposal step of many two-stage ones, start from a fixed set of template boxes called anchors, laid out across the image at set positions and sizes. For each training photo, before the loss is computed, every anchor is given a job by comparing it with that photo's true object boxes using IoU (the area two boxes share divided by the total area they cover between them).

Step 1: thresholds. For each anchor, find the object it overlaps best: the highest IoU, with the lower object index winning a tie. Then:

  • If that IoU is at least high, the anchor is responsible for that object. Its label is the object's index.
  • If that IoU is below low, the anchor is background. Its label is -1.
  • Otherwise it is too ambiguous to learn from. Its label is -2, which means "ignore".

Step 2: no object left behind. A small or awkwardly placed object might not reach high with any anchor. So go through the objects in order. For each one, find the anchor that overlaps it best (the lowest anchor index wins a tie). If that IoU is greater than 0, set that anchor's label to this object's index, replacing whatever label it already has, even another object's. When two objects pick the same anchor, the later object's label is the one that stays.

Task: write match_anchors(anchors, objects, high, low).

  • Every box is [x_min, y_min, x_max, y_max], with x_min < x_max and y_min < y_max.
  • Two boxes that only touch along an edge share no area.
  • There is at least one anchor and at least one object, and low <= high.
  • Return a list of whole-number labels, one per anchor, in the same order as anchors.

Examples

anchors = [[0, 0, 10, 10], [5, 0, 15, 10], [20, 20, 30, 30], [12, 0, 22, 10]]
objects = [[1, 0, 11, 10], [13, 1, 23, 11]]
high = 0.5
low = 0.4
returns [0, -2, -1, 1]
anchors = [[0, 0, 8, 8], [8, 0, 16, 8], [0, 8, 8, 16], [8, 8, 16, 16]]
objects = [[1, 1, 9, 9], [10, 10, 13, 13]]
high = 0.5
low = 0.3
returns [0, -1, -1, 1]

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run