AI Wiki中文/EN

Object detection: finding objects, then judging the boxes

目标检测

Build a small detector from pixels, trace duplicate predictions through matching, and derive why three AP conventions produce different results.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Two objects, three confident answers

Imagine a dark image containing two bright rectangles. A detector returns three boxes: one on the first rectangle, another on that same rectangle, and a third on the second. Every box overlaps a real object. Has the detector made three correct predictions?

Counting all three would reward a system for repeating itself. Object detection needs both localization and accounting: which object does each prediction refer to, and has that object already received credit? This is why evaluating a detector requires more than checking whether each crop looks plausible.

An image classifier produces an image-level answer. A detector produces a variable-length collection of class labels, locations and scores. Zero detections is a valid output for an empty scene. A box describes extent; it does not describe every foreground pixel, as a segmentation mask would. These distinctions are explicit in the VOC task definitions.

We will build a deliberately simple detector using brightness and connected components. It gives us a complete path from pixels to boxes, without making training a neural network a prerequisite. Then we will add one duplicate and follow its effect through the evaluation. The scene, labels and scores are teaching examples, not benchmark results.

Geometry, matching and a ranked list

A coordinate convention is part of the algorithm

Use continuous corner coordinates in the order (left, top, right, bottom), abbreviated xyxy. The image origin is at the upper left, x increases rightward and y downward. A box covers a half-open rectangle: its right and bottom boundaries are excluded. Thus (1, 1, 3, 3) covers four unit pixels, with width and height both 2. We require strictly positive width and height.

Other systems use a center and size, or left/top/width/height. Converting the latter requires adding width to left and height to top. Adding 1 to every width would change our geometry; do that only when a different discrete, inclusive-coordinate convention explicitly requires it. VOC’s file format places the top-left pixel at (1, 1), so our zero-based scene is not a drop-in submission file. VOC §4.3

For boxes A and B, intersect their horizontal and vertical intervals. A negative intersection length means there is no overlap, so clamp it to zero. Subtracting the intersection once avoids double-counting shared area in the union:

x−=max⁡(xA1,xB1),x+=min⁡(xA2,xB2),y−=max⁡(yA1,yB1),y+=min⁡(yA2,yB2),wI=max⁡(0,x+−x−),hI=max⁡(0,y+−y−),I=wIhI,IoU⁡(A,B)=I∣A∣+∣B∣−I.\begin{aligned}x_-&=\max(x_A^1,x_B^1),\\x_+&=\min(x_A^2,x_B^2),\\y_-&=\max(y_A^1,y_B^1),\\y_+&=\min(y_A^2,y_B^2),\\w_I&=\max(0,x_+-x_-),\\h_I&=\max(0,y_+-y_-),\\I&=w_Ih_I,\\\operatorname{IoU}(A,B)&=\frac{I}{|A|+|B|-I}.\end{aligned}

Intersection over union (IoU) lies between 0 and 1 for valid finite-area boxes. Identical boxes give 1; touching along an edge gives 0. Two 2-by-2 boxes displaced horizontally by 1 have intersection 2 and union 6, hence IoU 1/3. IoU measures geometric overlap, not the probability that a class prediction is correct.

Assign credit before drawing the curve

Our evaluator handles one category across any number of images. It sorts predictions by decreasing score, breaking ties by their input order. For each prediction, it finds the highest-IoU ground-truth box in that image. A prediction is a true positive (TP) only if that overlap is strictly greater than the chosen threshold and that ground-truth box has not already been matched. Otherwise it is a false positive (FP). Equal-IoU ground truths use annotation order. A duplicate is not reassigned to the second-best ground truth.

This is an explicit teaching contract, not a universal matching procedure. VOC’s documentation specifies overlap above 50%, penalizes repeated detections and ignores difficult objects; our reduced evaluator omits difficult-object handling. The pinned COCO implementation searches while excluding previously matched ordinary ground truths and has separate crowd/ignore rules. Its threshold comparison also accepts equality. These distinctions can change assignments in crowded scenes. VOC §4.4, COCO matching code

The toy ranking has scores 0.9, 0.8 and 0.7. Its TP flags are 1, 0 and 1. With G=2 ground-truth objects, calculate cumulative precision and recall at each rank k:

TP⁡k=∑i=1kzi,Pk=TP⁡kk,Rk=TP⁡kG.\begin{aligned}\operatorname{TP}_k&=\sum_{i=1}^{k}z_i,\\P_k&=\frac{\operatorname{TP}_k}{k},\\R_k&=\frac{\operatorname{TP}_k}{G}.\end{aligned}
RankWhat happenedPrecisionRecall
1First object found11/2
2First object repeated1/21/2
3Second object found2/31

The duplicate increases the denominator of precision without finding another object. Lowering a score threshold includes more predictions, but recall rises only when one of them matches a new object. The score threshold selects predictions; the IoU threshold judges overlap. They are different controls.

Why “AP” needs a definition

Interpolated precision at a recall level r is the best measured precision at that or any higher recall, or zero if the detector never reaches r. Integrating this envelope over recall gives all-point average precision:

p∗(r)=max⁡({Pk:Rk≥r}∪{0}),AP⁡all=∑k(Rk−Rk−1)p∗(Rk),R0=0.\begin{aligned}p_*(r)&=\max\bigl(\{P_k:R_k\ge r\}\cup\{0\}\bigr),\\\operatorname{AP}_{\mathrm{all}}&=\sum_k(R_k-R_{k-1})p_*(R_k),\\R_0&=0.\end{aligned}

For our ranking, the envelope is 1 over the first half of recall and 2/3 over the second half. Its area is 1/2 + (1/2)(2/3) = 5/6. This is not the arithmetic mean of the three raw precision values. VOC2010 changed from fixed 11-point sampling to this all-point integral. VOC §3.4.1

Sampling instead at recall 0, 0.1, …, 1 gives six samples of 1 and five of 2/3: 28/33. Sampling at 101 evenly spaced recall values gives 51 samples of 1 and 50 of 2/3: 253/303. The function below supports all three calculations so their difference is visible.

The pinned COCO code uses 101 recall samples, ten IoU thresholds from 0.50 through 0.95, category handling, area ranges and detection limits. Its standard detection defaults include limits of 1, 10 and 100 per image for different summaries. Merely selecting 101 samples in our function does not implement COCO AP. “mAP” also needs an averaging definition: over which categories, thresholds and valid cases? COCO accumulation and detection parameters

Run a complete small baseline

The following standalone Python program needs only the standard library. The detector visits bright pixels, groups four-neighbor connections, and takes each group’s minimum and maximum coordinates. Its score is mean component brightness. That score is useful for this constructed image but is not a calibrated object probability.

The labels are literal coordinates from the scene design, independent of detector output. Generating ground truth from predicted boxes would make the test circular. The extra prediction is deliberately inserted after detection; the baseline itself returns two boxes.

"""Original teaching detector/evaluator; continuous xyxy, one category, no ignored GT."""
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 components(image, threshold=0.5, min_area=1):
    """Four-neighbor bright components; score is mean brightness, not probability."""
    if not math.isfinite(threshold) or not 0 <= threshold <= 1:
        raise ValueError('threshold must be in [0,1]')
    if type(min_area) is not int or min_area < 1:
        raise ValueError('min_area must be a positive integer')
    height = len(image)
    width = len(image[0]) if height else 0
    if any(len(row) != width for row in image):
        raise ValueError('image must be rectangular')
    if any(not math.isfinite(v) or not 0 <= v <= 1 for row in image for v in row):
        raise ValueError('pixels must be finite values in [0,1]')
    seen, detections = set(), []
    for y in range(height):
        for x in range(width):
            if image[y][x] <= threshold or (y, x) in seen:
                continue
            stack, pixels = [(y, x)], []
            seen.add((y, x))
            while stack:
                py, px = stack.pop()
                pixels.append((py, px))
                for ny, nx in ((py-1, px), (py+1, px), (py, px-1), (py, px+1)):
                    if (0 <= ny < height and 0 <= nx < width and
                            image[ny][nx] > threshold and (ny, nx) not in seen):
                        seen.add((ny, nx))
                        stack.append((ny, nx))
            if len(pixels) >= min_area:
                ys, xs = zip(*pixels)
                bounds = (min(xs), min(ys), max(xs)+1, max(ys)+1)
                score = math.fsum(image[py][px] for py, px in pixels) / len(pixels)
                detections.append((bounds, score))
    return detections


def ap_from_flags(flags, positives, samples=None):
    """Flags are TP/FP in descending score order. Return None if no positive GT."""
    flags = list(flags)
    if type(positives) is not int or positives < 0:
        raise ValueError('positives must be a nonnegative integer')
    if any(type(f) is not int or f not in (0, 1) for f in flags) or sum(flags) > positives:
        raise ValueError('invalid TP flags')
    if samples is not None and (type(samples) is not int or samples < 2):
        raise ValueError('samples must be at least two, or None')
    if positives == 0:
        return None
    tp, recalls, precision = 0, [], []
    for rank, flag in enumerate(flags, 1):
        tp += flag
        recalls.append(tp / positives)
        precision.append(tp / rank)
    envelope = precision[:]
    for k in range(len(envelope)-2, -1, -1):
        envelope[k] = max(envelope[k], envelope[k+1])
    if samples is not None:
        return math.fsum(max((p for r, p in zip(recalls, envelope)
                             if r >= j/(samples-1)), default=0.0)
                         for j in range(samples)) / samples
    previous, areas = 0.0, []
    for recall, p in zip(recalls, envelope):
        areas.append((recall-previous)*p)
        previous = recall
    return math.fsum(areas)


def evaluate(truth, predictions, threshold=0.5):
    """Single class across images. Best GT first; duplicates never get reassigned."""
    if not math.isfinite(threshold) or not 0 <= threshold <= 1:
        raise ValueError('IoU threshold must be in [0,1]')
    truth = {image: [box(b) for b in boxes] for image, boxes in truth.items()}
    validated = []
    for index, (image, bounds, score) in enumerate(predictions):
        if not math.isfinite(score):
            raise ValueError('scores must be finite')
        validated.append((index, image, box(bounds), score))
    used, flags = set(), []
    for _, image, bounds, _ in sorted(validated, key=lambda p: (-p[3], p[0])):
        overlaps = [iou(bounds, gt) for gt in truth.get(image, [])]
        best = max(range(len(overlaps)), key=overlaps.__getitem__) if overlaps else None
        match = (image, best)
        hit = best is not None and overlaps[best] > threshold and match not in used
        flags.append(int(hit))
        if hit:
            used.add(match)
    positives = sum(map(len, truth.values()))
    return {'flags': flags, 'AP': ap_from_flags(flags, positives)}


if __name__ == '__main__':
    image = [[0.0]*12 for _ in range(8)]
    for y in range(1, 3):
        for x in range(1, 3):
            image[y][x] = 0.9
    for y in range(4, 6):
        for x in range(8, 10):
            image[y][x] = 0.7
    found = components(image)
    # Labels come from the scene design, independently of the detector output.
    truth = {'demo': [(1, 1, 3, 3), (8, 4, 10, 6)]}
    predictions = [('demo', b, s) for b, s in found]
    predictions.append(('demo', (1, 1, 3, 3), 0.8))
    result = evaluate(truth, predictions)
    print('boxes:', [b for b, _ in found])
    print('TP flags:', result['flags'])
    print('all-point AP:', round(result['AP'], 6))
    print('11-point AP:', round(ap_from_flags(result['flags'], 2, 11), 6))
    print('101-point AP:', round(ap_from_flags(result['flags'], 2, 101), 6))

Expected output:

boxes: [(1, 1, 3, 3), (8, 4, 10, 6)]
TP flags: [1, 0, 1]
all-point AP: 0.833333
11-point AP: 0.848485
101-point AP: 0.834983

For H×W pixels, connected-component traversal takes O(HW) time and O(HW) worst-case storage. With D predictions, score sorting takes O(D log D). Direct matching takes up to O(DG) overlap calculations if G bounds the number of ground truths per image. The all-point envelope takes O(D) time after matching. Our intentionally straightforward sampled calculation takes O(SD) for S recall samples; production evaluators can use ordered lookups.

The IoU routine scales lengths before multiplying areas, which handles uniformly large coordinates better than naive area products. It rejects invalid dimensions and some unrepresentable cases; it is not arbitrary-precision geometry. Ordinary image coordinates avoid these extremes.

What breaks outside the constructed scene?

Connect the two bright rectangles with a bright bridge and the baseline may merge them. Make an object darker than the threshold and it disappears. Bright background clutter becomes an object. A perfect result on two rectangles says nothing about recognizing cats, handling occlusion or distinguishing adjacent instances.

A learned detector must also decide how to represent candidates, predict classes and refine coordinates from training data. The next topics examine region-based models, YOLO, SSD and DETR. They answer different modeling questions from the metric lesson here. Non-maximum suppression is a separate candidate-filtering topic; filtering cannot recover an object that was never proposed.

AP is a ranking summary. A strictly increasing transformation of every score preserves ranking and, absent changed filtering or limits, preserves this evaluator’s AP. It does not preserve probability calibration. Nor does one AP value reveal which classes, object sizes or scene conditions fail. Inspect those slices and actual mistakes before choosing a deployment threshold.

No-positive-ground-truth cases return None, because recall has no denominator. Positive ground truth with no predictions yields AP 0. Reporting code must distinguish these cases rather than silently turning every undefined category into a zero. Use the exact official evaluator for a benchmark submission, and keep score thresholds, data splits and matching conventions fixed when comparing runs. Choose parameters using training/validation data, not repeated inspection of test labels.

Predict, calculate, then test

1. A box shifted one pixel

Two boxes are (0, 0, 2, 2) and (1, 0, 3, 2). Compute IoU. Would the second pass an overlap threshold of 0.5 against the first?

Answer: Their intersection has area 2 and union area 6. IoU is 1/3, which fails. A high confidence score would not change the geometry.

2. Move the duplicate to the end

Change only the duplicate’s score from 0.8 to 0.6. What are the TP flags and all-point AP?

Answer: The flags become 1, 1, 0. Both recall increases occur at precision 1, so AP becomes 1. The final duplicate is still an FP, and final precision is 2/3. This shows why AP should be read alongside the operating threshold and false detections, rather than as a complete error inventory.

3. Touching is not the same as connected

Run the detector on [[1, 0], [0, 1]]. How many components appear? What changes if diagonal neighbors are admitted?

Answer: Four-neighbor traversal finds two components, each a one-pixel box. Eight-neighbor traversal would connect the diagonal pixels into one component with box (0, 0, 2, 2). The resulting box would include two dark pixels. Box extent need not equal foreground area.

4. Is 101-point AP a COCO reproduction?

Our output includes 0.834983. Can we label it “COCO AP”? What information would still be missing?

Answer: No. We changed only recall sampling. The toy evaluator uses one category and one IoU threshold, has different matching semantics, and lacks crowd/ignore handling, area ranges and per-image limits. It also uses synthetic data. A reproduction requires the specified dataset, protocol and official implementation or a verified equivalent.

Keep the protocol beside the number

  • VOC2010 development kit documentation, §§3.4.1 and 4.1–4.4 supplies the historical AP change, detection output format and evaluation rules. The mathematical image alt text was read; the complete MATLAB devkit was not run.
  • COCO evaluator at commit 6c3b394 was inspected for matching, accumulation and default detection parameters. This is a fixed 2019 revision, not a claim about every later competition. Its BSD-2-Clause license was checked; no upstream code was copied or executed.

The implementations, scene and arithmetic here are original teaching material. See the precision and recall topic for threshold tradeoffs and model evaluation for experimental design. The habit to carry forward is simple: save the coordinate, matching and averaging rules with every reported detection metric.

Make a prediction, then check

With two ground-truth objects and ranked TP flags [1,0,1], what is all-point interpolated AP?

Choose one answer

Learning objectives

  • Convert box coordinates and derive IoU without mixing pixel conventions.
  • Trace duplicates and score ordering through matching, precision, recall and AP.
  • Run and challenge a complete non-AI detector while distinguishing benchmark protocols.

Prerequisites & connections

Explore related knowledge →

References

  1. PASCAL VOC2010 Development Kit — detection and average precision
    Mark Everingham; John Winn · 2010
  2. COCO API detection evaluator — fixed commit 6c3b394 (2019-12-25)
    Piotr Dollar; Tsung-Yi Lin; COCO API contributors · 2019

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-07 · Codex single-AI-author technical check: bounded primary documentation and pinned official source; original pixel detector, independent geometry/AP references, boundary tests and bilingual reasoning. Not independent human review or a VOC/COCO benchmark reproduction.

  • Checked independently labeled pixel components, exhaustive integer-box IoU via pixel sets, exhaustive short TP sequences against recall-level AP, duplicate matching, exact fractions and invalid/empty cases. Nine numerical checks plus bilingual structural check.
  • Read both languages section by section: coordinate contract, assignment, envelope derivation, examples, complexity, limitations and four answers correspond. Python and displayed formulas are identical.
  • Final links check found precision-recall is catalogued but unwritten: both locale links now lead to its catalogue entry, and it is removed as an assumed prerequisite because this article teaches the required definitions. Mobile inspection prompted an equivalent decomposition of the IoU formula into interval endpoints. Frozen original retained; code, arithmetic and exercise 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.