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.
- Solves
- Object detection
- Time
- Θ(n^2) worstO(n^2) averageΘ(n) best
- Space
- Θ(n) extra
- Where
- n = the number of input boxes
- Model
- Real RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- 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 boxes with scores , a decay function with values in , and a pruning threshold . 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 , with the IoU of a box and the box just selected:
- hard: for and for , which is greedy NMS;
- linear: for and for ;
- Gaussian: .
The linear rule jumps at from 1 to ; the Gaussian rule is smooth and decays every overlapping box, even one with a small overlap.
The algorithm
SOFT-NMS(B, s, f, s_min) ▷ n = |B|- 1
D ← empty list, S ← copy of s, R ← {1, ..., n} - 2
while R is not empty do - 3
m ← the index in R with the largest S_m, ties by the smaller index - 4
remove m from R and append (m, S_m) to D - 5
for each i in R do - 6
o ← IoU(B_m, B_i) - 7
S_i ← S_i · f(o) - 8
if S_i < s_min then remove i from R - 9
return D
Line L7 is the one line that differs from greedy NMS. With the hard rule, a box with gets the score 0 and line L8 removes it, which is the removal step of greedy NMS. A small 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 :
| box | corners | score |
|---|---|---|
| 1 | 0.90 | |
| 2 | 0.80 | |
| 3 | 0.75 | |
| 4 | 0.60 | |
| 5 | 0.50 |
The IoU values are , , and , and box 4 does not touch any other box.
| step | selected (L3) | its score | changes in L7 |
|---|---|---|---|
| 1 | box 1 | 0.90 | box 2: , ; boxes 3, 4, 5 are below and keep their scores |
| 2 | box 3 | 0.75 | box 5: , ; box 2: , no change |
| 3 | box 4 | 0.60 | no overlaps |
| 4 | box 2 | 0.2555 | box 5: , no change |
| 5 | box 5 | 0.1597 |
The output order is 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 gives the same order with the scores , , , and . 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 rounds and outputs each box at most once. The score that a box has when it is selected is over the boxes 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 , the selected boxes are exactly the output of greedy NMS with the test . 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 boxes with scores , a decay function with for every overlap , and a pruning threshold . The linear rule, for and otherwise, and the Gaussian rule both take values in because . The loop keeps a current score for each index and a set of remaining indices. Let be the indices that line L3 selects, in order.
Claim.
- (termination) The loop runs at most times, and each index is output at most once.
- (closed form) The score output with is .
- (order) The output scores are nonincreasing: .
- (no loss with the Gaussian rule) If , every index is output.
- (hard rule) If for and otherwise, and , the selected indices are exactly the output of greedy NMS that removes a box when its overlap with a kept box is at least , in the same order.
Invariant. At the start of each iteration of line L2, after selections, every has , and .
Proof. Before the first iteration, line L1 sets and to all indices, and the product is empty. In iteration , lines L3 and L4 take out of . Lines L5 to L7 multiply by for every other , which extends the product by one factor. Line L8 only removes indices from . No line changes the score of an index outside , and no line puts an index back into .
Proof of the claim. Part 1: each iteration removes from in line L4 and nothing is added to , so falls by at least one in each iteration, and the loop of line L2 stops after at most iterations. An index leaves when it is output, so it is output at most once.
Part 2 is the invariant at the moment line L4 outputs , before the iteration changes any score.
Part 3: when is selected, line L3 gives for every in . In the same iteration, line L7 multiplies each by a factor in , and the scores are nonnegative, so they do not increase. The next selected index is in at that time, so .
Part 4: with the test of line L8 never removes an index, because every score is nonnegative. Each iteration then removes exactly one index from , so all indices are output.
Part 5: with the hard rule, a factor is 1 or 0. If an index gets a factor 0, its score becomes 0, which is below , and line L8 removes it at once. If it gets only factors 1, its score stays , and it stays in . So the indices in 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 leaves without being output exactly when some selected before it has . These are the two properties that characterize greedy NMS with the test "at least ": 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.
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 scans twice, once in line L3 and once in lines L5 to L8, with . The total is overlaps and decays. With , part 4 gives exactly, and lines L5 to L8 evaluate overlaps, so the bound is tight. The extra space is the copy of the scores and the set , .
Complexity
Each round scans the remaining set twice, once to find the maximum in line L3 and once in lines L5 to L8. With and the Gaussian rule nothing is pruned, so the rounds visit boxes and evaluate IoU values: in the real RAM, the same order as the worst case of greedy NMS. The paper states the cost as . The best case is the hard rule with one box that removes all others, . 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, .
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 .
- Generalizes greedy NMS. The hard rule gives greedy NMS with the test "at least ".
- 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 and the Gaussian rule the output has all boxes, so a score threshold or a top- cut must follow if the application needs a short list.
Variants and improvements
- Linear or Gaussian. The paper uses for the linear rule and 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 ", 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 throws away boxes that the decay would have kept, and with the hard rule any 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 " 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 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.
# 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
- 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)
- 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
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag CXYXEQ Edit this page History Report an error Markdown