Algorithm Search⌘K

Algorithmadvanced

Soft-NMS

Also called soft non-maximum suppression.

Non-maximum suppression that lowers the scores of overlapping boxes by a function of their IoU instead of removing them, which helps with crowded objects.

Time
Θ(n^2) worstO(n^2) averageΘ(n) best
Space
Θ(n) extra
Where
n = the number of input boxes
Properties
deterministicexactofflineiterative
Origin
Navaneeth Bodla, Bharat Singh, Rama Chellappa, Larry S. Davis, 2017

Soft-NMS is a change to greedy non-maximum suppression for detections. Greedy NMS removes every box whose intersection over union with a kept box is above a threshold; Soft-NMS keeps the box and multiplies its score by a decay that gets smaller as the overlap grows. A second object that stands close behind the first one then stays in the output with a lower score instead of being lost. Bodla, Singh, Chellappa and Davis (2017) describe it as a change of one line in the NMS loop, and it needs no retraining of the detector.

In plain words

A detector gives many scored boxes, several around each object. Greedy NMS keeps the best box and throws away every box that overlaps it a lot. When two people stand close together, the box of the second person overlaps the box of the first, and greedy NMS throws it away too.

Soft-NMS does not throw boxes away. It keeps the best box, then lowers the score of every other box: a little for a small overlap, a lot for a large overlap. Then it takes the box with the highest new score, and so on. A duplicate of the first person sits almost on top of the first box, so its score drops close to zero. The second person overlaps less, so its box keeps a useful score. The output is all boxes with new scores, and a final score threshold removes the ones that are left with almost nothing.

The problem

The input is nn boxes B1,…,BnB_1, \ldots, B_n with scores s1,…,sn≥0s_1, \ldots, s_n \ge 0, a decay function ff with values in [0,1][0, 1], and a pruning threshold smin⁡≥0s_{\min} \ge 0. The output is a list of pairs (index, new score) in the order in which the loop selects them. Detection uses this list to compute detection mean average precision, which only looks at the order of the boxes by score and at their positions. Bodla et al. give three rules for ff, with oo the IoU of a box and the box just selected:

  • hard: f(o)=1f(o) = 1 for o<Nto < N_t and 00 for o≥Nto \ge N_t, which is greedy NMS;
  • linear: f(o)=1f(o) = 1 for o<Nto < N_t and 1−o1 - o for o≥Nto \ge N_t;
  • Gaussian: f(o)=e−o2/σf(o) = e^{-o^2 / \sigma}.

The linear rule jumps at NtN_t from 1 to 1−Nt1 - N_t; the Gaussian rule is smooth and decays every overlapping box, even one with a small overlap.

The algorithm

  1. SOFT-NMS(B, s, f, s_min) ▷ n = |B|
  2. 1D ← empty list, S ← copy of s, R ← {1, ..., n}
  3. 2while R is not empty do
  4. 3m ← the index in R with the largest S_m, ties by the smaller index
  5. 4remove m from R and append (m, S_m) to D
  6. 5for each i in R do
  7. 6o ← IoU(B_m, B_i)
  8. 7S_i ← S_i · f(o)
  9. 8if S_i < s_min then remove i from R
  10. 9return D

Line L7 is the one line that differs from greedy NMS. With the hard rule, a box with o≥Nto \ge N_t gets the score 0 and line L8 removes it, which is the removal step of greedy NMS. A small smin⁡s_{\min} makes sure that boxes with almost no score do not stay in the loop.

Example

Take the five boxes of the box NMS page, with the linear rule and Nt=0.3N_t = 0.3:

box corners score
1 (0,0,10,10)(0, 0, 10, 10) 0.90
2 (1,1,11,11)(1, 1, 11, 11) 0.80
3 (6,0,16,10)(6, 0, 16, 10) 0.75
4 (20,20,30,30)(20, 20, 30, 30) 0.60
5 (7,1,17,11)(7, 1, 17, 11) 0.50

The IoU values are IoU(B1,B2)=IoU(B3,B5)=81/119≈0.681\mathrm{IoU}(B_1, B_2) = \mathrm{IoU}(B_3, B_5) = 81/119 \approx 0.681, IoU(B1,B3)=IoU(B2,B5)=1/4\mathrm{IoU}(B_1, B_3) = \mathrm{IoU}(B_2, B_5) = 1/4, IoU(B2,B3)=9/31≈0.290\mathrm{IoU}(B_2, B_3) = 9/31 \approx 0.290 and IoU(B1,B5)=27/173≈0.156\mathrm{IoU}(B_1, B_5) = 27/173 \approx 0.156, and box 4 does not touch any other box.

step selected (L3) its score changes in L7
1 box 1 0.90 box 2: 0.681≥0.30.681 \ge 0.3, 0.80⋅(1−81/119)=152/595≈0.25550.80 \cdot (1 - 81/119) = 152/595 \approx 0.2555; boxes 3, 4, 5 are below NtN_t and keep their scores
2 box 3 0.75 box 5: 0.681≥0.30.681 \ge 0.3, 0.50⋅38/119=19/119≈0.15970.50 \cdot 38/119 = 19/119 \approx 0.1597; box 2: 0.290<0.30.290 < 0.3, no change
3 box 4 0.60 no overlaps
4 box 2 0.2555 box 5: 0.25<0.30.25 < 0.3, no change
5 box 5 0.1597

The output order is 1,3,4,2,51, 3, 4, 2, 5 with nonincreasing scores. Greedy NMS with the same threshold, which is the hard rule, keeps only boxes 1, 3 and 4. The Gaussian rule with σ=0.5\sigma = 0.5 gives the same order with the scores 0.900.90, 0.75⋅e−0.125≈0.66190.75 \cdot e^{-0.125} \approx 0.6619, 0.600.60, 0.26760.2676 and 0.16640.1664. Here box 3 loses some score although its overlap with box 1 is only 0.25.

Correctness

Soft-NMS has no optimality claim; it is a rescoring rule, and its value is measured by benchmark. What can be proved is what it outputs. The correctness file shows four facts. The loop stops after at most nn rounds and outputs each box at most once. The score that a box has when it is selected is si∏f(o(Bm,Bi))s_i \prod f(o(B_m, B_i)) over the boxes mm selected before it, so the result does not depend on how the loop stores the scores. The output scores are nonincreasing, because the selected box has the largest current score and the decay never raises a score. With the hard rule and 0<smin⁡≤min⁡isi0 < s_{\min} \le \min_i s_i, the selected boxes are exactly the output of greedy NMS with the test o≥Nto \ge N_t. The tests check the closed form and the equality with greedy NMS on random inputs, and compare the code with a slow version that recomputes every score from the closed form.

Proof: Soft-NMS terminates, outputs nonincreasing scores with a closed form, and its hard rule is greedy NMSfull

We use the notation of the page. The input is nn boxes B1,…,BnB_1, \ldots, B_n with scores s1,…,sn≥0s_1, \ldots, s_n \ge 0, a decay function ff with 0≤f(o)≤10 \le f(o) \le 1 for every overlap oo, and a pruning threshold smin⁡≥0s_{\min} \ge 0. The linear rule, f(o)=1f(o) = 1 for o<Nto < N_t and 1−o1 - o otherwise, and the Gaussian rule f(o)=e−o2/σf(o) = e^{-o^2/\sigma} both take values in [0,1][0, 1] because o=IoU∈[0,1]o = \mathrm{IoU} \in [0, 1]. The loop keeps a current score SiS_i for each index and a set RR of remaining indices. Let m1,m2,…,mrm_1, m_2, \ldots, m_r be the indices that line L3 selects, in order.

Claim.

  1. (termination) The loop runs at most nn times, and each index is output at most once.
  2. (closed form) The score output with mkm_k is smk∏j<kf(o(Bmj,Bmk))s_{m_k} \prod_{j < k} f(o(B_{m_j}, B_{m_k})).
  3. (order) The output scores are nonincreasing: Sm1≥Sm2≥⋯≥SmrS_{m_1} \ge S_{m_2} \ge \cdots \ge S_{m_r}.
  4. (no loss with the Gaussian rule) If smin⁡=0s_{\min} = 0, every index is output.
  5. (hard rule) If f(o)=1f(o) = 1 for o<Nto < N_t and f(o)=0f(o) = 0 otherwise, and 0<smin⁡≤min⁡isi0 < s_{\min} \le \min_i s_i, the selected indices are exactly the output of greedy NMS that removes a box when its overlap with a kept box is at least NtN_t, in the same order.

Invariant. At the start of each iteration of line L2, after kk selections, every i∈Ri \in R has Si=si∏j≤kf(o(Bmj,Bi))S_i = s_i \prod_{j \le k} f(o(B_{m_j}, B_i)), and i∉{m1,…,mk}i \notin \{m_1, \ldots, m_k\}.

Proof. Before the first iteration, line L1 sets S=sS = s and RR to all indices, and the product is empty. In iteration k+1k + 1, lines L3 and L4 take mk+1m_{k+1} out of RR. Lines L5 to L7 multiply SiS_i by f(o(Bmk+1,Bi))f(o(B_{m_{k+1}}, B_i)) for every other i∈Ri \in R, which extends the product by one factor. Line L8 only removes indices from RR. No line changes the score of an index outside RR, and no line puts an index back into RR. □\square

Proof of the claim. Part 1: each iteration removes mkm_k from RR in line L4 and nothing is added to RR, so ∣R∣|R| falls by at least one in each iteration, and the loop of line L2 stops after at most nn iterations. An index leaves RR when it is output, so it is output at most once.

Part 2 is the invariant at the moment line L4 outputs mkm_k, before the iteration changes any score.

Part 3: when mkm_k is selected, line L3 gives Smk≥SiS_{m_k} \ge S_i for every ii in RR. In the same iteration, line L7 multiplies each SiS_i by a factor in [0,1][0, 1], and the scores are nonnegative, so they do not increase. The next selected index mk+1m_{k+1} is in RR at that time, so Smk+1≤SmkS_{m_{k+1}} \le S_{m_k}.

Part 4: with smin⁡=0s_{\min} = 0 the test of line L8 never removes an index, because every score is nonnegative. Each iteration then removes exactly one index from RR, so all nn indices are output.

Part 5: with the hard rule, a factor is 1 or 0. If an index ii gets a factor 0, its score becomes 0, which is below smin⁡s_{\min}, and line L8 removes it at once. If it gets only factors 1, its score stays si≥smin⁡s_i \ge s_{\min}, and it stays in RR. So the indices in RR always have their input scores, and line L3 selects them in the rank order of the input scores with ties by the smaller index. An index ii leaves RR without being output exactly when some selected mm before it has o(Bm,Bi)≥Nto(B_m, B_i) \ge N_t. These are the two properties that characterize greedy NMS with the test "at least NtN_t": no selected index has an earlier selected index that overlaps it that much, and every other index has one. The argument in the correctness file of box non-maximum suppression shows that only one set has both properties, with the comparison "greater than" there; replacing it with "at least" changes nothing in that argument. So the two outputs are the same set, and both are in rank order. □\square

Remark (the floating-point case). Part 2 is an equality of real numbers. In floating point the code multiplies the factors in the order of selection, and the reference implementation in the tests does the same, so the two agree to the last bit; a program that multiplies in another order can differ in the last bits and can then break a tie in the other direction.

Cost. Iteration kk scans RR twice, once in line L3 and once in lines L5 to L8, with ∣R∣≤n−k+1|R| \le n - k + 1. The total is O(n2)O(n^2) overlaps and decays. With smin⁡=0s_{\min} = 0, part 4 gives ∣R∣=n−k+1|R| = n - k + 1 exactly, and lines L5 to L8 evaluate ∑k=1n(n−k)=n(n−1)/2\sum_{k=1}^{n} (n - k) = n(n-1)/2 overlaps, so the bound is tight. The extra space is the copy of the scores and the set RR, Θ(n)\Theta(n).

Complexity

Each round scans the remaining set twice, once to find the maximum in line L3 and once in lines L5 to L8. With smin⁡=0s_{\min} = 0 and the Gaussian rule nothing is pruned, so the rounds visit n−1,n−2,…,0n - 1, n - 2, \ldots, 0 boxes and evaluate n(n−1)/2n(n-1)/2 IoU values: Θ(n2)\Theta(n^2) in the real RAM, the same order as the worst case of greedy NMS. The paper states the cost as O(N2)O(N^2). The best case is the hard rule with one box that removes all others, Θ(n)\Theta(n). A heap would make line L3 cheaper, but the scores of many boxes change in each round and the loop of line L5 is already linear, so it does not change the order of the cost. The extra space is the copy of the scores and the remaining set, Θ(n)\Theta(n).

Properties

  • Deterministic. With the tie rule fixed, the output is a function of the input.
  • Keeps the order of the best box. The first box of the output is the box with the highest input score, with its score unchanged.
  • Nonincreasing output scores, a theorem for any decay with values in [0,1][0, 1].
  • Generalizes greedy NMS. The hard rule gives greedy NMS with the test "at least NtN_t".
  • No retraining. The rule acts on the outputs of a trained detector, so it can be added to an existing system at test time.
  • Changes scores, not boxes. The boxes are not moved or merged. Methods that average coordinates of overlapping boxes are a different family.
  • Every box can stay. With smin⁡=0s_{\min} = 0 and the Gaussian rule the output has all nn boxes, so a score threshold or a top-kk cut must follow if the application needs a short list.

Variants and improvements

  • Linear or Gaussian. The paper uses Nt=0.3N_t = 0.3 for the linear rule and σ=0.5\sigma = 0.5 for the Gaussian rule, and Section 6.2 studies how the results change with these parameters. They are tuned values for the benchmarks of the paper, not values that follow from a theory.
  • Class-aware runs. As with greedy NMS, the loop runs once for each class.
  • Learned suppression. Hosang, Benenson and Schiele (2017) train a network to rescore the boxes, which learns the step that Soft-NMS fixes by hand.
  • NMS-free detectors. DETR and other set-prediction detectors are trained with a one-to-one matching and need neither greedy NMS nor Soft-NMS.

When to use it

Use Soft-NMS in place of greedy NMS when the score that matters is an average precision over many recall levels, such as COCO mAP, and when objects of the same class overlap, as in crowds, traffic or animal herds. The gain is a benchmark result, not a guarantee. Bodla et al. (2017) report on the MS-COCO test-dev set, with the COCO mAP averaged over IoU 0.5 to 0.95, gains of 1.3 points for R-FCN and 1.1 points for Faster R-CNN, and gains of 1.7 points for both on PASCAL VOC 2007 with the same metric. Keep greedy NMS when the next stage needs a short list with no near-duplicates, for example to count objects, because Soft-NMS leaves the duplicates in the output with low scores.

Pitfalls

  • Forgetting the final threshold. Soft-NMS keeps more boxes. A system that drew every output box would show many faint duplicates, so a score cut must follow for display or counting.
  • Comparing with the wrong threshold. The hard rule here uses "at least NtN_t", and many NMS codes use "greater than"; the two differ only at the threshold, but a comparison on integer boxes can hit it.
  • Pruning too early. A large smin⁡s_{\min} throws away boxes that the decay would have kept, and with the hard rule any smin⁡s_{\min} above a box's input score removes that box before it can compete.
  • Using it to fix a poor detector. Soft-NMS reorders the boxes that the detector produced. It cannot add a box that the detector missed, and it does not move a badly placed box.
  • Floating-point ties. Two programs that multiply the same decays in a different order can get scores that differ in the last bits, and then break a tie in the other direction.

Implementations

The Python code gives the loop of the page with the three rules, a decay function as a parameter, and a pruning threshold. It also has a slow reference that recomputes every score from the closed form, and greedy NMS with the test "at least NtN_t" for comparison. The tests check the example of this page with exact fractions, the equality of the hard rule with greedy NMS on random inputs with tied scores, the agreement with the reference for the linear and Gaussian rules, the order of the output scores, a crowd case in which only Soft-NMS keeps the second object, and the count of n(n−1)/2n(n-1)/2 IoU values when nothing is pruned.

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.

soft_nms.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/soft-nms/. The authors are listed in prov/CXYXEQ.jsonl.
"""Soft-NMS (Bodla et al. 2017): rescore overlapping detections instead of
removing them.

A box is (x1, y1, x2, y2) in continuous image coordinates and scores are
nonnegative. The loop picks the box with the highest current score, puts it
in the output with that score, and multiplies the score of every remaining
box by a decay f(IoU) in [0, 1]. A box whose score falls below s_min is
dropped. The decay rules are those of the paper:

    linear    f(o) = 1 if o < N_t, else 1 - o
    gaussian  f(o) = exp(-o * o / sigma)
    hard      f(o) = 1 if o < N_t, else 0    (greedy NMS with o >= N_t)

Standard library only. Cost: one overlap and one decay per pair (selected
box, remaining box), so O(n^2) time in the worst case and O(n) extra space.
"""

import math
from fractions import Fraction


def iou(a, b):
    """IoU of two boxes; exact (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 = (a[2] - a[0]) * (a[3] - a[1]) + (b[2] - b[0]) * (b[3] - b[1]) - inter
    if union == 0:
        return 0
    if isinstance(inter, int) and isinstance(union, int):
        return Fraction(inter, union)
    return inter / union


def make_decay(method="linear", nt=0.3, sigma=0.5):
    """Return the decay function f(o) of one of the three rules."""
    if method == "linear":
        return lambda o: 1 if o < nt else 1 - o
    if method == "gaussian":
        return lambda o: math.exp(-(o * o) / sigma)
    if method == "hard":
        return lambda o: 1 if o < nt else 0
    raise ValueError("unknown method: %r" % (method,))


def soft_nms(boxes, scores, method="linear", nt=0.3, sigma=0.5, s_min=0.001,
             overlap=iou, decay=None):
    """Return a list of (index, new score) pairs in the order of selection.

    The new scores are nonincreasing along the list. Ties in the current
    score go to the smaller index.
    """
    f = decay if decay is not None else make_decay(method, nt, sigma)
    out, cur, rest = [], list(scores), list(range(len(boxes)))  # @line L1
    while rest:  # @line L2
        m = min(rest, key=lambda i: (-cur[i], i))  # @line L3
        rest.remove(m)  # @line L4
        out.append((m, cur[m]))
        survivors = []
        for i in rest:  # @line L5
            o = overlap(boxes[m], boxes[i])  # @line L6
            cur[i] = cur[i] * f(o)  # @line L7
            if cur[i] >= s_min:  # @line L8
                survivors.append(i)
        rest = survivors
    return out  # @line L9


def soft_nms_reference(boxes, scores, decay, s_min, overlap=iou):
    """A slow reference that keeps no running scores.

    At every step it recomputes the score of each candidate from scratch as
    s_i times the product of f(IoU(B_m, B_i)) over the boxes m selected so
    far, and it drops a candidate when one of these partial products, taken
    in selection order, falls below s_min. It must agree with soft_nms.
    """
    n = len(boxes)
    chosen, dropped = [], set()

    def partial(i, upto):
        v = scores[i]
        for m in chosen[:upto]:
            v = v * decay(overlap(boxes[m], boxes[i]))
        return v

    out = []
    while True:
        cands = []
        for i in range(n):
            if i in chosen or i in dropped:
                continue
            gone = any(partial(i, k) < s_min for k in range(1, len(chosen) + 1))
            if gone:
                dropped.add(i)
            else:
                cands.append(i)
        if not cands:
            return out
        m = min(cands, key=lambda i: (-partial(i, len(chosen)), i))
        out.append((m, partial(m, len(chosen))))
        chosen.append(m)


def greedy_nms_ge(boxes, scores, nt, overlap=iou):
    """Greedy NMS that removes a box when its overlap with a kept box is at
    least nt. This is the classic algorithm that the hard rule reproduces.
    """
    order = sorted(range(len(boxes)), key=lambda i: (-scores[i], i))
    keep, removed = [], [False] * len(boxes)
    for pos, i in enumerate(order):
        if removed[i]:
            continue
        keep.append(i)
        for j in order[pos + 1:]:
            if not removed[j] and overlap(boxes[i], boxes[j]) >= nt:
                removed[j] = True
    return keep
test_soft_nms.py 130 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/soft-nms/. The authors are listed in prov/CXYXEQ.jsonl.

import math
import random
from fractions import Fraction

from soft_nms import greedy_nms_ge, iou, make_decay, soft_nms, soft_nms_reference

EXAMPLE_BOXES = [(0, 0, 10, 10), (1, 1, 11, 11), (6, 0, 16, 10), (20, 20, 30, 30), (7, 1, 17, 11)]
EXAMPLE_SCORES = [Fraction(9, 10), Fraction(8, 10), Fraction(3, 4), Fraction(3, 5), Fraction(1, 2)]


def random_instance(rng, n, size=20):
    boxes = []
    for _ in range(n):
        x, y = rng.randint(0, size), rng.randint(0, size)
        w, h = rng.randint(2, 8), rng.randint(2, 8)
        boxes.append((x, y, x + w, y + h))
    scores = [Fraction(rng.randint(1, 6), 6) for _ in range(n)]  # ties on purpose
    return boxes, scores


def test_page_example_linear():
    out = soft_nms(EXAMPLE_BOXES, EXAMPLE_SCORES, "linear", nt=Fraction(3, 10))
    assert [i for i, _ in out] == [0, 2, 3, 1, 4]
    assert [s for _, s in out] == [Fraction(9, 10), Fraction(3, 4), Fraction(3, 5),
                                   Fraction(152, 595), Fraction(19, 119)]
    assert iou(EXAMPLE_BOXES[1], EXAMPLE_BOXES[2]) == Fraction(9, 31)


def test_page_example_gaussian():
    floats = [float(s) for s in EXAMPLE_SCORES]
    out = soft_nms(EXAMPLE_BOXES, floats, "gaussian", sigma=0.5)
    assert [i for i, _ in out] == [0, 2, 3, 1, 4]
    assert abs(out[1][1] - 0.75 * math.exp(-0.125)) < 1e-12
    assert round(out[3][1], 4) == 0.2676 and round(out[4][1], 4) == 0.1664


def test_page_example_hard_is_greedy_nms():
    out = soft_nms(EXAMPLE_BOXES, EXAMPLE_SCORES, "hard", nt=Fraction(3, 10))
    assert [i for i, _ in out] == [0, 2, 3]
    assert greedy_nms_ge(EXAMPLE_BOXES, EXAMPLE_SCORES, Fraction(3, 10)) == [0, 2, 3]


def test_hard_rule_equals_greedy_nms():
    rng = random.Random(11)
    for trial in range(200):
        boxes, scores = random_instance(rng, rng.randint(0, 15))
        nt = rng.choice([Fraction(1, 10), Fraction(3, 10), Fraction(1, 2), Fraction(7, 10)])
        out = soft_nms(boxes, scores, "hard", nt=nt)
        assert [i for i, _ in out] == greedy_nms_ge(boxes, scores, nt)
        # The hard rule never changes a surviving score.
        assert all(s == scores[i] for i, s in out)


def test_matches_reference_exact():
    rng = random.Random(12)
    for trial in range(120):
        boxes, scores = random_instance(rng, rng.randint(0, 10))
        nt = rng.choice([Fraction(1, 5), Fraction(3, 10), Fraction(1, 2)])
        s_min = rng.choice([0, Fraction(1, 100), Fraction(1, 5)])
        f = make_decay("linear", nt=nt)
        got = soft_nms(boxes, scores, s_min=s_min, decay=f)
        assert got == soft_nms_reference(boxes, scores, f, s_min)


def test_matches_reference_gaussian():
    rng = random.Random(13)
    for trial in range(80):
        boxes, scores = random_instance(rng, rng.randint(0, 10))
        scores = [float(s) for s in scores]
        f = make_decay("gaussian", sigma=0.5)
        got = soft_nms(boxes, scores, s_min=0.05, decay=f)
        assert got == soft_nms_reference(boxes, scores, f, 0.05)


def test_scores_are_nonincreasing_and_closed_form():
    rng = random.Random(14)
    for method in ("linear", "gaussian"):
        for trial in range(60):
            boxes, scores = random_instance(rng, 20, size=25)
            if method == "gaussian":
                scores = [float(s) for s in scores]
            f = make_decay(method, nt=Fraction(3, 10), sigma=0.5)
            out = soft_nms(boxes, scores, s_min=0, decay=f)
            # With s_min = 0 every box is output exactly once.
            assert sorted(i for i, _ in out) == list(range(20))
            vals = [s for _, s in out]
            assert all(vals[k] >= vals[k + 1] for k in range(len(vals) - 1))
            # The output score is the input score times the decays of all
            # boxes selected before it, in the order of selection.
            for pos, (i, s) in enumerate(out):
                v = scores[i]
                for m, _ in out[:pos]:
                    v = v * f(iou(boxes[m], boxes[i]))
                assert v == s


def test_disjoint_boxes_keep_scores_and_rank_order():
    boxes = [(3 * i, 0, 3 * i + 2, 2) for i in range(12)]
    rng = random.Random(15)
    scores = [Fraction(rng.randint(1, 4), 4) for _ in range(12)]
    out = soft_nms(boxes, scores, "linear")
    assert [i for i, _ in out] == sorted(range(12), key=lambda i: (-scores[i], i))
    assert all(s == scores[i] for i, s in out)


def test_crowd_case_keeps_second_object():
    # Two true objects whose boxes overlap with IoU 3/5. Greedy NMS at 0.5
    # removes the second one; the linear rule keeps it with a lower score.
    a, b = (0, 0, 8, 10), (2, 0, 10, 10)
    assert iou(a, b) == Fraction(3, 5)
    out = soft_nms([a, b], [Fraction(9, 10), Fraction(4, 5)], "linear")
    assert out == [(0, Fraction(9, 10)), (1, Fraction(8, 25))]
    assert soft_nms([a, b], [Fraction(9, 10), Fraction(4, 5)], "hard", nt=Fraction(1, 2)) == [(0, Fraction(9, 10))]


def test_quadratic_overlap_count():
    calls = [0]

    def counting_iou(p, q):
        calls[0] += 1
        return iou(p, q)

    n = 25
    rng = random.Random(16)
    boxes, scores = random_instance(rng, n)
    soft_nms(boxes, [float(s) for s in scores], "gaussian", s_min=0, overlap=counting_iou)
    assert calls[0] == n * (n - 1) // 2

History

Greedy NMS with a fixed IoU threshold had been the last step of almost every detector for years, and its loss of recall in crowds was known. Bodla, Singh, Chellappa and Davis (2017) observed that the removal step can be read as a score decay that is a step function of the overlap, and replaced it with a continuous one. The paper, titled "improving object detection with one line of code", appeared at ICCV 2017 with code for the detectors of that time, and the method was added to many detection libraries. The same year, Hosang, Benenson and Schiele proposed to learn the suppression step. Set-prediction detectors such as DETR (2020) later removed the need for a suppression step altogether.

References

  1. Navaneeth Bodla, Bharat Singh, Rama Chellappa and Larry S. Davis, Soft-NMS: improving object detection with one line of code, ICCV 2017, 5562-5570, Figure 2, Algorithm 1 (the loop with the hard and the soft rule), the linear and Gaussian rescoring functions and the O(N^2) cost, Section 6 (results on PASCAL VOC 2007 and MS-COCO), Section 6.2 (sensitivity analysis)
  2. Navaneeth Bodla, Bharat Singh, Rama Chellappa and Larry S. Davis, Soft-NMS: improving object detection with one line of code, arXiv:1704.04503, 2017, The preprint of the ICCV paper, with the same Algorithm 1
  3. Tsung-Yi Lin, Michael Maire, Serge Belongie, James Hays, Pietro Perona, Deva Ramanan, Piotr Dollar and C. Lawrence Zitnick, Microsoft COCO: common objects in context, ECCV 2014, LNCS 8693, 740-755, The COCO data set and its detection task, on which the gains of Soft-NMS are reported
  4. Jan Hosang, Rodrigo Benenson and Bernt Schiele, Learning non-maximum suppression, CVPR 2017, A network that learns the suppression step, an alternative to a fixed rescoring rule

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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.average
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example