AI Wiki中文/EN

Non-maximum suppression: deciding which boxes to keep

非极大值抑制

Trace hard and Soft-NMS, calculate score decay, and test why a confident box can suppress two useful neighbors.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

The same object keeps getting reported

A detector may return several plausible boxes around one object. Keeping every box would turn a correct discovery into a list of duplicates. In the object detection example, the duplicate was a false positive even though its coordinates matched a real object exactly.

Non-maximum suppression (NMS) filters candidate boxes using their scores and overlaps. It starts with the highest-scoring remaining box and asks which nearby answers should lose their place. The decision is local: a high score does not prove that this box has the best localization, or that all overlapping boxes describe the same object.

The difficult case is a crowded scene. Two adjacent people may need overlapping boxes. Deleting a neighbor can remove a duplicate or erase a different person. Hard NMS makes a binary decision; Soft-NMS reduces scores so some neighbors can still be selected later. The original Soft-NMS paper motivates this distinction and describes two decay functions. Soft-NMS, Figure 2 and §4

This chapter concerns bounding-box suppression in object detection. It does not cover every operation called NMS, such as thinning edge responses. It also does not train a detector, move its boxes or invent missing proposals.

Three rules for an overlapping neighbor

Hard NMS: keep the current winner

For one image, let each candidate have a box bib_i, a score sis_i and a class cic_i. Use the continuous, half-open xyxy convention from the detection chapter. IoU is intersection area divided by union area. Choose the maximum-scoring remaining candidate m, append it to the output and remove it from consideration. Our hard rule removes a remaining candidate i when:

ci=cmandIoU⁡(bm,bi)>τ.c_i=c_m\quad\text{and}\quad\operatorname{IoU}(b_m,b_i)>\tau.

Repeat until no candidates remain. In this version, different classes do not suppress one another. Setting every class label to zero gives class-agnostic filtering, but that changes the decision being made. With multiple images, invoke the procedure separately per image; class labels alone do not isolate images.

This strict greater-than rule follows the pinned Torchvision documentation. Its batched_nms interface separates categories; its documentation also warns that tied scores need not select the same box on CPU and GPU. Our example resolves ties by input index to make teaching runs reproducible. We do not claim identical backend behavior. Torchvision nms and batched_nms

After hard NMS, every pair of retained boxes in the same class has IoU at most τ. To see why, consider whichever box was selected first: the other could only remain if it passed that comparison. This pairwise property does not prove the retained boxes are correct objects or form the best possible subset.

Linear Soft-NMS: change a score instead of deleting a box

The paper’s displayed linear rule uses a different boundary convention. With uiu_i equal to the overlap with the selected box, it updates remaining same-class scores as follows:

ui=IoU⁡(bm,bi),si′={si,ui<τ,si(1−ui),ui≥τ.\begin{aligned}u_i&=\operatorname{IoU}(b_m,b_i),\\s_i'&=\begin{cases}s_i,&u_i<\tau,\\s_i(1-u_i),&u_i\ge\tau.\end{cases}\end{aligned}

Our implementation preserves that greater-than-or-equal boundary rather than silently changing the paper to match the hard rule above. At IoU exactly 0.5 and τ=0.5, hard NMS keeps the neighbor unchanged, whereas linear Soft-NMS halves its score. At IoU 1, the linear score becomes zero. At a positive threshold, crossing the threshold creates a jump in the linear decay factor. Soft-NMS, §4 displayed rules

Scores have changed, so the next candidate must be selected using the updated scores. Advancing through the original ordering would implement a different algorithm. Once a box is selected, our implementation records its current score; later selections do not revise it.

Gaussian Soft-NMS: decay at every positive overlap

The paper also proposes:

si′=siexp⁡ ⁣(−ui2σ),σ>0.s_i'=s_i\exp\!\left(-\frac{u_i^2}{\sigma}\right),\qquad\sigma>0.

Apply this to every remaining same-class box, without an IoU cutoff. The denominator is σ, not 2σ². For ui=0u_i=0 the multiplier is 1. For fixed positive overlap, a smaller σ produces stronger decay. Across multiple selected boxes, the multipliers accumulate. This rule is continuous as a function of overlap, but the overall procedure still uses discrete maximum selection and score filtering. A smooth multiplier does not make the entire detector differentiable. Soft-NMS, §4 Gaussian rule

Work through one ranking

All three candidates below have the same class and height 2:

Indexxyxy boxInitial score
0(0, 0, 2, 2)0.9
1(0.1, 0, 2.1, 2)0.85
2(4, 0, 6, 2)0.8

Candidates 0 and 1 have intersection 3.8 and union 4.2, so their IoU is 19/21. Candidate 2 overlaps neither. With τ=0.5, selecting 0 removes 1 under hard NMS, leaving output [0, 2]. Linear Soft-NMS instead changes score 1 to 0.85×(2/21), about 0.080952. Candidate 2 now outranks it. With σ=0.5, Gaussian decay gives about 0.165347, also below 0.8. Both soft variants therefore select [0, 2, 1] if their score floor is zero.

The score floor and IoU threshold have different roles. Raising the floor to 0.1 removes the final candidate under linear decay, but not under this Gaussian decay. Neither parameter is the overlap threshold used by a benchmark evaluator to decide true positives.

Run the selection, not just a picture of it

This standalone Python program uses only the standard library. It returns original indices for hard NMS and index/current-score pairs for Soft-NMS. The input scores are copied. Hard NMS accepts any finite scores; Soft-NMS requires nonnegative scores, because multiplying a negative score by a factor below one would increase it rather than penalize it.

Boxes must have finite, strictly positive dimensions. Our continuous geometry allows negative coordinates and does not clip them to an image, while the pinned Torchvision documentation specifies nonnegative coordinates. The local tie policy is deterministic. A score at or below min_score is excluded; with the default zero floor, a zeroed linear candidate is not returned. Gaussian mode ignores the IoU threshold for decay, although the shared argument is still validated.

"""Original NMS teaching program; continuous xyxy, one image, class-aware filtering."""
import math


def box(value):
    b = tuple(float(x) for x in value)
    if len(b) != 4 or not all(math.isfinite(x) for x in b):
        raise ValueError('box needs four finite coordinates')
    if not (0 < b[2] - b[0] < math.inf and 0 < b[3] - b[1] < math.inf):
        raise ValueError('box must have finite positive width and height')
    return b


def iou(first, second):
    a, b = box(first), box(second)
    lengths = (a[2]-a[0], a[3]-a[1], b[2]-b[0], b[3]-b[1])
    scale = max(lengths)
    aw, ah, bw, bh = (v / scale for v in lengths)
    iw = max(0.0, min(a[2], b[2]) - max(a[0], b[0])) / scale
    ih = max(0.0, min(a[3], b[3]) - max(a[1], b[1])) / scale
    intersection = iw * ih
    union = aw * ah + bw * bh - intersection
    if union <= 0 or not math.isfinite(union):
        raise ValueError('box areas exceed supported numerical range')
    return intersection / union


def prepare(boxes, scores, classes, threshold):
    if not math.isfinite(threshold) or not 0 <= threshold <= 1:
        raise ValueError('IoU threshold must be in [0,1]')
    boxes = [box(b) for b in boxes]
    scores = [float(s) for s in scores]
    classes = [0]*len(boxes) if classes is None else list(classes)
    if len(boxes) != len(scores) or len(classes) != len(boxes):
        raise ValueError('boxes, scores and classes must have equal lengths')
    if any(not math.isfinite(s) for s in scores):
        raise ValueError('scores must be finite')
    if any(type(c) is not int for c in classes):
        raise ValueError('class labels must be integers')
    return boxes, scores, classes


def hard_nms(boxes, scores, threshold=0.5, classes=None):
    """One image; same-class suppression iff IoU > threshold; input-index ties."""
    boxes, scores, classes = prepare(boxes, scores, classes, threshold)
    remaining = sorted(range(len(boxes)), key=lambda i: (-scores[i], i))
    kept = []
    while remaining:
        best = remaining[0]
        kept.append(best)
        remaining = [i for i in remaining[1:]
                     if classes[i] != classes[best] or iou(boxes[best], boxes[i]) <= threshold]
    return kept


def soft_nms(boxes, scores, threshold=0.5, classes=None,
             method='linear', sigma=0.5, min_score=0.0):
    """Re-select after each decay; linear uses >= threshold, Gaussian decays all overlaps."""
    boxes, scores, classes = prepare(boxes, scores, classes, threshold)
    if method not in ('linear', 'gaussian'):
        raise ValueError('unknown score decay method')
    if any(s < 0 for s in scores):
        raise ValueError('soft decay requires nonnegative scores')
    if not math.isfinite(sigma) or sigma <= 0:
        raise ValueError('sigma must be finite and positive')
    if not math.isfinite(min_score) or min_score < 0:
        raise ValueError('minimum score must be finite and nonnegative')
    remaining, selected = list(range(len(boxes))), []
    while remaining:
        best = max(remaining, key=lambda i: (scores[i], -i))
        if scores[best] <= min_score:
            break
        remaining.remove(best)
        selected.append((best, scores[best]))
        for i in remaining:
            if classes[i] != classes[best]:
                continue
            overlap = iou(boxes[best], boxes[i])
            if method == 'gaussian':
                scores[i] *= math.exp(-(overlap*overlap)/sigma)
            elif overlap >= threshold:
                scores[i] *= 1-overlap
    return selected


if __name__ == '__main__':
    boxes = [(0,0,2,2), (.1,0,2.1,2), (4,0,6,2)]
    scores = [.9,.85,.8]
    print('hard:', hard_nms(boxes,scores))
    for method in ['linear','gaussian']:
        print(method+':', [(i,round(s,6)) for i,s in soft_nms(boxes,scores,method=method)])
    crowd = [(1,0,3,2), (0,0,2,2), (2,0,4,2)]
    selected = hard_nms(crowd,[.9,.8,.8],.3)
    print('greedy counterexample:',selected,'weight',sum([.9,.8,.8][i] for i in selected))

Expected output:

hard: [0, 2]
linear: [(0, 0.9), (2, 0.8), (1, 0.080952)]
gaussian: [(0, 0.9), (2, 0.8), (1, 0.165347)]
greedy counterexample: [0] weight 0.9

For N candidates, hard NMS sorts once in O(N log N) time and can perform O(N²) comparisons. Soft-NMS uses a linear scan to choose each updated maximum and another scan to decay scores, giving O(N²) worst-case time. Re-sorting on every round is unnecessary. These implementations store O(N) additional candidate/score state and do not build a full pairwise IoU matrix. Candidate counts, data movement and backend kernels still affect real latency; this program does not reproduce a CPU/GPU speed benchmark.

A local winner can block a better pair

Consider three same-class boxes, all spanning y from 0 to 2. The middle box spans x from 1 to 3 and scores 0.9. The left box spans 0 to 2 and the right box 2 to 4; each scores 0.8. Each side overlaps the middle with IoU 1/3, but the side boxes only touch each other, giving IoU 0.

At τ=0.3, hard NMS picks the middle box and deletes both sides. Its retained score sum is 0.9. The two side boxes are compatible with the overlap constraint and sum to 1.6. Enumerating all subsets in the tests confirms the difference. This disproves a guarantee of maximum compatible score sum; it does not show that the side pair must achieve better AP, or that score-sum optimization was NMS’s stated objective.

Soft-NMS remains greedy too. It may preserve a useful neighbor at a lower rank, but it can also retain duplicates or push a real object below the score floor. It neither refines coordinates nor resolves a wrong class. Class-aware filtering can keep two conflicting class labels for the same extent; class-agnostic filtering can delete legitimate overlapping objects of different classes. Choose that policy for the actual task, then inspect failures on held-out data.

A score is not automatically a calibrated probability, and multiplying it by an overlap penalty does not provide a probabilistic derivation. Tune thresholds and σ using validation data and evaluate the complete detection pipeline under a fixed protocol. The region-based detection family supplies a next step for studying where candidate boxes come from. A filtering result alone cannot establish detector quality.

Make the next selection yourself

1. Which box comes next?

After selecting candidate 0 in the three-box table, linear decay leaves scores 0.080952 and 0.8. Which index must be selected next, and what mistake would original-order traversal make?

Answer: Select index 2. Visiting index 1 next would ignore the changed ranking. Soft-NMS must find the current maximum after every update; it need not fully sort the list each time.

2. Stand exactly on the boundary

Use boxes (0, 0, 2, 2) and (0, 0, 1, 2), scores 1 and 0.8, and τ=0.5. What happens to the second box under our hard and linear rules?

Answer: IoU is exactly 1/2. The strict hard rule keeps it with score 0.8. The paper-based linear rule applies at equality and changes its score to 0.4. Reproducing a specific implementation requires preserving its comparison operator.

3. Two rounds of Gaussian decay

A remaining candidate scores 0.8 and overlaps each of two successively selected boxes by 1/3. With σ=0.5, what is its score after both updates?

Answer: Each multiplier is exp(-2/9), so the final score is 0.8 exp(-4/9). Using only the latest overlap would discard the first penalty. The tests use two non-overlapping selected boxes so their order is not changed by mutual decay.

4. What did the counterexample prove?

In the middle/left/right example, can we conclude that selecting both side boxes gives a better object detector? What additional evidence is needed?

Answer: We only proved a larger compatible score sum. We still need ground-truth objects, class labels, the evaluation protocol and results across relevant data. If both side boxes are false detections, their larger score sum is not a benefit.

Specify the variant before comparing results

  • Torchvision boxes.py, commit bd94a05: nms/batched_nms documentation and wrappers, including strict comparison, class separation and the tied-score warning. The commit date is 2026-05-26; its BSD-3-Clause license was read. The compiled operators were not executed.
  • Bodla, Singh, Chellappa and Davis, ICCV2017 Soft-NMS: Figure 2 and §4 define iterative reselection and the linear/Gaussian rules. The formulas on physical page 4 were visually checked. No reported accuracy or timing improvement is claimed as our reproduction.

The program and numerical examples are original teaching material. Keep the variant, boundary rule, class policy, tie policy and score floor alongside each experiment; the name “NMS” alone leaves those decisions unspecified.

Make a prediction, then check

After Soft-NMS updates the remaining scores, how is the next box chosen?

Choose one answer

Learning objectives

  • Trace hard suppression and prove the retained same-class boxes are pairwise compatible.
  • Calculate linear/Gaussian decay and reselect using the updated scores.
  • Distinguish threshold conventions and test what a greedy counterexample does and does not prove.

Prerequisites & connections

Explore related knowledge →

References

  1. Torchvision box suppression — fixed commit bd94a05 (2026-05-26)
    Torchvision contributors · 2026
  2. Soft-NMS — Improving Object Detection With One Line of Code, ICCV2017 method
    Navaneeth Bodla; Bharat Singh; Rama Chellappa; Larry S. Davis · 2017

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-07 · Codex single-AI-author technical check: bounded original Soft-NMS method and pinned official documentation, analytic decay, exhaustive subset counterexample, boundary cases and bilingual reasoning. Not independent human review or detector benchmark reproduction.

  • Verified analytic 19/21 overlap and both decays, updated ranking, equality boundaries, class/tie rules, cumulative Gaussian penalties, exhaustive compatible-subset counterexample, hard suppression witnesses, monotone score transforms, floors and invalid inputs. Eight computational tests plus bilingual structure test.
  • Read both languages section by section for algorithm contracts, pairwise-compatibility proof, formula denominators, sample outputs, complexity, limits and four explained exercises. No accuracy or speed improvement claimed as reproduced.
  • Final screenshot review prompted math markup for inline box/score/class/overlap subscripts in both languages. Frozen drafts retained; program, displayed equations, numeric values and answers unchanged.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.