Python Master Course V2 — 167. Object Localization, Bounding Boxes and Detection Metrics
Purpose and learning outcomes
Object detection asks both what is present and where it is. You will locate synthetic red rectangles with a deterministic color-and-component baseline, then evaluate predicted boxes using intersection over union and one-to-one matching. Controlled duplicate and missed detections reveal why a good-looking overlay is not enough. This is not a learned production detector.
- Represent and validate bounding boxes consistently
- Compute intersection over union and match predictions to objects
- Distinguish classification, localization and detection errors
Prerequisites
- 162: coordinate transforms
- 164: segmentation
- 134: precision and recall
Environment and execution
Use a project-specific virtual environment with a currently supported Python 3 release compatible with the packages below. Python 3.11 or 3.12 is a practical starting point. Run shell commands in a terminal, then run the Python blocks in order in one script or notebook kernel. They use only included data and local CPU computation. No account, API key, camera, or external dataset is required. Record the installed package versions with python -m pip freeze when you save your results; a random seed does not guarantee identical numerical behavior across library versions.
python -m venv .venv
# macOS/Linux: source .venv/bin/activate
# Windows PowerShell: .venv\Scripts\Activate.ps1
python -m pip install numpy scipyUnderstand the model and its assumptions
A classification error assigns the wrong category. A localization error places a box poorly around the right object. A detection system can additionally miss an object or produce extra boxes for one object. These failures need different explanations, even when they contribute to the same aggregate precision or recall.
We use half-open boxes x1, y1, x2, y2 in image-edge coordinates. Intersection width is the overlap between horizontal intervals, clipped at zero; height is analogous. IoU divides intersection area by union area. Two boxes that merely touch at an edge have zero intersection area. Invalid or zero-area boxes are rejected instead of being repaired silently.
Detection evaluation matches predictions to ground-truth objects under both a category rule and an IoU threshold. Each ground-truth object can be matched at most once. A duplicate prediction cannot become a second true positive for the same object; it is a false positive. A ground-truth object left unmatched is a false negative. The example processes predictions in descending score order, then chooses the best available overlap.
Precision and recall at one score cutoff and IoU threshold are not average precision or mean average precision. Those metrics require a specified ranking protocol, integration convention, and often several categories or IoU thresholds. Our fixed-threshold report is deliberately simpler. The baseline's constant scores are bookkeeping values rather than calibrated confidence; changing their order can affect greedy matches in crowded scenes.
Worked example: build it in stages
Create two separated red rectangles in an RGB float array. The color rule makes a binary mask, connected components yield slices, and slice bounds become boxes. Evaluate three scenarios: the detector's ordinary output, one added duplicate, and one removed detection. The matcher validates boxes, enforces class agreement, and keeps an explicit set of used ground-truth indices.
import numpy as np
from scipy import ndimage
def area(box):
x1, y1, x2, y2 = box
if not np.isfinite(box).all() or x2 <= x1 or y2 <= y1:
raise ValueError("box must have finite positive area")
return (x2-x1)*(y2-y1)
def box_iou(a, b):
aa, bb = area(a), area(b)
width = max(0, min(a[2], b[2])-max(a[0], b[0]))
height = max(0, min(a[3], b[3])-max(a[1], b[1]))
intersection = width*height
return intersection/(aa+bb-intersection)
image = np.zeros((40, 50, 3), dtype=float)
truth = [{"box": (5, 8, 15, 18), "label": "red"},
{"box": (30, 20, 42, 30), "label": "red"}]
for item in truth:
x1, y1, x2, y2 = item["box"]
image[y1:y2, x1:x2] = [1, 0, 0]
def detect(image):
mask = (image[:, :, 0] > 0.7) & (image[:, :, 1] < 0.2) & (image[:, :, 2] < 0.2)
components, _ = ndimage.label(mask)
result = []
for region in ndimage.find_objects(components):
if region is None:
continue
rows, columns = region
result.append({"box": (columns.start, rows.start, columns.stop, rows.stop),
"label": "red", "score": 0.9})
return result
def evaluate(predictions, targets, iou_threshold=0.5, score_threshold=0.0):
if not 0 <= iou_threshold <= 1:
raise ValueError("IoU threshold must lie in [0, 1]")
for item in predictions + targets:
area(item["box"])
chosen = [p for p in predictions if p["score"] >= score_threshold]
chosen = sorted(chosen, key=lambda p: -p["score"])
used, tp, fp = set(), 0, 0
for prediction in chosen:
candidates = [(box_iou(prediction["box"], target["box"]), i)
for i, target in enumerate(targets)
if i not in used and target["label"] == prediction["label"]]
best = max(candidates, default=(-1.0, -1))
if best[0] >= iou_threshold:
used.add(best[1])
tp += 1
else:
fp += 1
fn = len(targets)-len(used)
return {"tp": tp, "fp": fp, "fn": fn,
"precision": tp/(tp+fp) if tp+fp else None,
"recall": tp/(tp+fn) if tp+fn else None}
predictions = detect(image)
print("ordinary:", evaluate(predictions, truth))
print("duplicate:", evaluate(predictions + [dict(predictions[0], score=0.8)], truth))
print("missed:", evaluate(predictions[:1], truth))
assert box_iou((0, 0, 2, 2), (2, 0, 4, 2)) == 0.0What the output means
The ordinary case yields two true positives, no false positives, and no misses. Adding one duplicate yields two true positives and one false positive, so precision is two-thirds and recall remains one. Keeping one detection yields one true positive and one false negative, so precision is one and recall is one-half. These are reasoned expectations for the exact synthetic geometry, not measured production performance.
Guided lab and acceptance checks
Move one predicted box gradually away from its target and compute IoU at each displacement. Repeat evaluation at thresholds 0.3, 0.5, and 0.75 without changing the ground truth. Add a predicted box with the wrong label but perfect coordinates and explain why it cannot match under the category-aware contract.
Acceptance requires a coordinate convention, validated boxes, one-to-one matching, and separate counts for duplicates and misses. Add touching red rectangles to demonstrate that connected components can merge distinct objects. That failure belongs to the detector, not to the evaluator; do not rewrite the truth as one object merely to improve the score.
Common mistakes and repairs
Do not count every high-overlap prediction as a true positive. Do not compare inclusive boxes from one source with half-open boxes from another. Avoid treating a component's bounding box as a perfect segmentation: it may include background. Finally, do not label a fixed-threshold precision value as mAP; the metric definition is part of the result.
Questions and answers
Why does a duplicate count as a false positive?
The task asks for one detection per object under this evaluation protocol. Once an object has a match, another box for it is extra output. Allowing repeated matches would let a detector inflate true positives by copying one correct prediction.
Why require category agreement as well as overlap?
A box can localize the right region while naming the wrong object type. Category-aware detection evaluates both claims together. If you want class-agnostic localization, define and report that as a different metric.
Can two boxes have high IoU but different practical quality?
Yes. IoU summarizes area overlap, while an application may care more about a particular edge, small defect, or physical dimension. It is a useful standard geometry metric, not a complete description of downstream usefulness.
Why does matching order matter?
In crowded scenes multiple predictions can overlap several targets. A greedy algorithm consumes available matches in score order. Standard benchmarks specify their matching rules precisely; reproduce that protocol rather than assuming all reasonable matchers give identical results.
Is the color threshold a learned detector?
No. It is a deterministic rule designed for synthetic red shapes. It can be a useful baseline under controlled conditions, but changes in illumination, color, contact, or background can break it. A learned detector is a separate model requiring training and evaluation.
Exercises
1. Check identical-box and disjoint-box IoU. 2. Shift a two-by-two box one pixel horizontally and derive its IoU. 3. Add a wrong-label prediction with the same coordinates as a target and verify it remains unmatched.
Worked solutions and reasoning
The shifted boxes overlap in area two and have union area six, giving one-third IoU. A wrong-label prediction consumes no target match, leaving both original targets missed in this isolated scenario.
assert box_iou((0, 0, 2, 2), (0, 0, 2, 2)) == 1.0
assert np.isclose(box_iou((0, 0, 2, 2), (1, 0, 3, 2)), 1/3)
wrong = [{"box": truth[0]["box"], "label": "blue", "score": 1.0}]
result = evaluate(wrong, truth)
assert (result["tp"], result["fp"], result["fn"]) == (0, 1, 2)Recap
Detection evaluation must separate geometry, class identity, duplicates, and missed objects. A transparent matcher and synthetic fixtures make those contracts testable. Report the exact score cutoff and IoU threshold, and reserve broader benchmark names for the full protocols they require.
Official references
Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.