Object detection I: boxes, IoU, NMS and mean average precision
Build box representations, IoU-based losses and suppression, then evaluate detections with matching and COCO-style average precision.
After this lesson you can
- Convert and encode bounding boxes under explicit coordinate conventions.
- Calculate IoU, GIoU, DIoU and CIoU and discuss their gradients.
- Implement class-aware NMS and compare Soft-NMS.
- Construct precision-recall curves and interpret COCO AP.
- Diagnose detection errors under a declared matching protocol.
Before you start
What is there and where
A robot that must grasp a cup needs to locate it, not merely know it appears in the image. Object detection returns a set of predictions : box, class and score. Object count changes across images and set order is not a property of the world. A score ranks candidates but is not necessarily a calibrated probability.
Annotations are also a modeling choice. PASCAL VOC provides classes, boxes and flags such as difficult; COCO adds crowd and area annotations, among others. A box bounds a rectangle, not the exact silhouette. A partially occluded object can lead to different annotation decisions; evaluate under the dataset protocol and check conventions before comparing models.
Coordinates and encoding
Box representation must state units and boundaries. In continuous coordinates, xyxy is with and ; its area is . xywh uses top-left corner, width and height; cxcywh uses center, width and height. In a image, normalization divides horizontal coordinates by and vertical by . Clipping corners to the image rectangle can produce a degenerate box that must be handled explicitly.
For a reference and target in center format with positive widths and heights, a common encoding is
The inverse recovers and , analogously vertically. Some implementations scale these four components: do not mix their weights with an unscaled formula. Integer pixel indices and continuous boxes are not interchangeable without conversion: the lab converts VOC XML from inclusive one-based coordinates to continuous zero-based edges, subtracting one from minima and retaining maxima.
A geometric measure and its losses
Intersection over union is for positive-area boxes. Intersection uses minima of upper corners and maxima of lower corners, clipping each length at zero. Between predictions and targets, broadcasting computes the matrix; cost and memory grow with . IoU does not distinguish shift direction when boxes are disjoint: in a noncontact neighborhood it is zero and its coordinate gradient is zero.
Let be the smallest enclosing box, the squared center distance and the squared diagonal of . GIoU and DIoU define
A possible loss is or . GIoU can provide signal for separate boxes but does not guarantee nonzero gradient in every geometry: for example, certain infinitesimal movements of a centered contained box preserve areas and enclosure. For CIoU, with positive widths and heights, define and . Then . For identical boxes the fraction is ; its continuous contribution is defined as zero. Some implementations stop the gradient of , so state that convention when comparing derivatives. Contacts, ties between endpoints or degenerate areas may introduce nondifferentiable points.
Suppressing redundant candidates
A detector often proposes several boxes for one object. Non-maximum suppression applies a greedy rule: sort by score, retain the first and remove remaining boxes whose IoU with it exceeds a threshold; repeat with the best remaining box. Here we use , not , and break ties by original index. Sorting costs and a direct implementation may compare pairs. The result depends on threshold, scores and tie rule.
Hard NMS can sort once and traverse candidates in that order. This lesson’s teaching implementations re-sort remaining candidates at each iteration, so their cumulative sorting cost can reach ; for Soft-NMS, linearly finding the maximum after score updates keeps a direct implementation at operations.
In per-class NMS only candidates of the same category compete. Class-agnostic NMS also exists, useful in other designs but capable of removing boxes of different categories. The trick of shifting coordinates by class requires separation greater than the full coordinate range, including negatives, and sufficient numerical precision; using it without those conditions can mix groups.
Soft-NMS reduces neighbor scores instead of immediately eliminating them. In the linear variant, if IoU exceeds threshold, multiply the score by ; the Gaussian uses parameterized continuous decay. After each reduction the highest score must be chosen again: keeping original order changes the algorithm. Neither variant rescues a box discarded before candidates arrive.
From matching to the curve
For one class and IoU threshold, sort each image’s detections by score and greedily match to an eligible unassigned target. A second detection of the same object is a false positive if it does not reach threshold with another eligible free target, even if its box has good IoU with the first. Then combine sorted detections across images and accumulate true and false positives. For and , precision is and recall is , with valid targets. The precision-recall curve may have jumps and precision can fall as false positives are added.
Detection average precision summarizes the curve. For each recall level , use the envelope , or zero if no point reaches . VOC 2007 averaged 11 levels; COCO averages 101 levels from 0 to 1. AP is per class and IoU; mAP averages eligible classes and, for the main COCO metric, ten IoU thresholds from 0.50 to 0.95 in steps of 0.05. AP50 and AP75 fix one threshold. Do not compare VOC AP with COCO AP as though they were the same quantity.
The official COCOeval evaluator limits detections by default to 100 per image and category for AP, and also reports recall with limits 1, 10 and 100. Small, medium and large AP filters by annotation area; numerical boundaries are and square pixels and official code includes both endpoints of each range. Categories without valid targets for a combination are marked absent and excluded from the mean, not replaced by zero.
iscrowd crowds require special treatment: one annotation can absorb multiple detections, which are ignored rather than counted as false positives, and overlap uses intersection divided by detection area. Annotations outside an area range are ignored in that breakdown; unmatched detections outside the range are also ignored. Official box code sets the ignore flag from iscrowd, overwriting a standalone ignore. These details affect denominator and matching; averaging ten simple APs does not reproduce all of COCO.
Diagnose before changing the model
A false positive can be a duplicate of a correct detection, a poorly localized box, a wrong class or background. An object without a corresponding detection is a false negative. These categories depend on assignment rules and thresholds: state priorities and do not add their counts as though they were directly lost AP points. Hoiem and colleagues propose analyzing error types to guide improvements, not only looking at an aggregate number.
If boxes around the correct object predominate but do not reach required IoU, study regression and resolution; if boxes align but confuse classes, inspect labels and classification. In crowds, aggressive NMS may remove distinct overlapping objects; permissive NMS may leave duplicates. Change one component, measure with the same protocol and reserve test for final evaluation.
Labs
First build conversions, encoding and IoU by broadcasting. Boxes are continuous with strictly positive area; empty matrices are accepted. Losses and finite differences check both a separated case and a contained one where slopes can vanish.
"""Cajas continuas xyxy, conversión, codificación e IoU por pares.
Se exigen coordenadas finitas y área estrictamente positiva. Las coordenadas
pueden ser negativas; no se añade +1 porque no contamos píxeles discretos.
"""
import numpy as np
def boxes_xyxy(boxes):
boxes = np.asarray(boxes, dtype=np.float64)
if boxes.ndim != 2 or boxes.shape[1] != 4 or not np.isfinite(boxes).all():
raise ValueError('Se espera una matriz finita de forma (N, 4)')
if np.any(boxes[:, 2:] <= boxes[:, :2]):
raise ValueError('Cada caja debe tener anchura y altura positivas')
return boxes
def xyxy_to_xywh(boxes):
b = boxes_xyxy(boxes)
return np.concatenate((b[:, :2], b[:, 2:] - b[:, :2]), axis=1)
def xywh_to_xyxy(boxes):
b = np.asarray(boxes, dtype=np.float64)
if b.ndim != 2 or b.shape[1] != 4 or not np.isfinite(b).all() or np.any(b[:, 2:] <= 0):
raise ValueError('Se espera (N, 4) finito con tamaño positivo')
return np.concatenate((b[:, :2], b[:, :2] + b[:, 2:]), axis=1)
def xyxy_to_cxcywh(boxes):
b = boxes_xyxy(boxes)
return np.concatenate(((b[:, :2] + b[:, 2:]) / 2, b[:, 2:] - b[:, :2]), axis=1)
def cxcywh_to_xyxy(boxes):
b = np.asarray(boxes, dtype=np.float64)
if b.ndim != 2 or b.shape[1] != 4 or not np.isfinite(b).all() or np.any(b[:, 2:] <= 0):
raise ValueError('Se espera (N, 4) finito con tamaño positivo')
return np.concatenate((b[:, :2] - b[:, 2:] / 2, b[:, :2] + b[:, 2:] / 2), axis=1)
def encode(reference, target):
r, t = xyxy_to_cxcywh(reference), xyxy_to_cxcywh(target)
if r.shape != t.shape:
raise ValueError('Cada caja de referencia necesita un objetivo')
return np.concatenate(((t[:, :2] - r[:, :2]) / r[:, 2:], np.log(t[:, 2:] / r[:, 2:])), axis=1)
def decode(reference, deltas):
r = xyxy_to_cxcywh(reference)
d = np.asarray(deltas, dtype=np.float64)
if d.shape != r.shape or not np.isfinite(d).all():
raise ValueError('Desplazamientos finitos de forma (N, 4)')
with np.errstate(over='raise', under='raise', invalid='raise'):
try:
b = np.concatenate((r[:, :2] + d[:, :2] * r[:, 2:], r[:, 2:] * np.exp(d[:, 2:])), axis=1)
except FloatingPointError as exc:
raise ValueError('Escala fuera del rango numérico') from exc
return cxcywh_to_xyxy(b)
def overlap_metrics(a, b):
"""Tres matrices N×M: IoU, GIoU y DIoU entre cajas válidas."""
a, b = boxes_xyxy(a), boxes_xyxy(b)
lo = np.maximum(a[:, None, :2], b[None, :, :2])
hi = np.minimum(a[:, None, 2:], b[None, :, 2:])
inter = np.prod(np.maximum(hi - lo, 0), axis=-1)
area_a = np.prod(a[:, 2:] - a[:, :2], axis=-1)[:, None]
area_b = np.prod(b[:, 2:] - b[:, :2], axis=-1)[None, :]
union = area_a + area_b - inter
iou = inter / union
enclosing = np.maximum(a[:, None, 2:], b[None, :, 2:]) - np.minimum(a[:, None, :2], b[None, :, :2])
enclosing_area = np.prod(enclosing, axis=-1)
giou = iou - (enclosing_area - union) / enclosing_area
center_a = (a[:, :2] + a[:, 2:]) / 2
center_b = (b[:, :2] + b[:, 2:]) / 2
center_distance2 = np.sum((center_a[:, None, :] - center_b[None, :, :]) ** 2, axis=-1)
diou = iou - center_distance2 / np.sum(enclosing ** 2, axis=-1)
return iou, giou, diou
reference = np.array([[0., 0., 2., 2.], [1., 1., 3., 3.]])
target = np.array([[1., 0., 5., 4.], [0., 0., 1., 1.]])
np.testing.assert_allclose(xywh_to_xyxy(xyxy_to_xywh(reference)), reference)
np.testing.assert_allclose(cxcywh_to_xyxy(xyxy_to_cxcywh(reference)), reference)
deltas = encode(reference, target)
np.testing.assert_allclose(decode(reference, deltas), target, atol=1e-14)
np.testing.assert_allclose(deltas[0], [1., .5, np.log(2.), np.log(2.)])
iou, giou, diou = overlap_metrics(reference, target)
np.testing.assert_allclose(iou, [[2/18, 1/4], [4/16, 0]], atol=1e-15)
np.testing.assert_allclose(overlap_metrics(reference[:0], target)[0].shape, (0, 2))
assert overlap_metrics(reference[:1], reference[:1])[0][0, 0] == 1
def translation_derivative(fixed, moving, eps=1e-5):
delta = np.array([[eps, 0., eps, 0.]])
plus = np.array([x[0, 0] for x in overlap_metrics(fixed, moving + delta)])
minus = np.array([x[0, 0] for x in overlap_metrics(fixed, moving - delta)])
return (plus - minus) / (2 * eps)
disjoint_grad = translation_derivative(np.array([[0., 0., 2., 2.]]), np.array([[3., 0., 5., 2.]]))
centered_grad = translation_derivative(np.array([[0., 0., 4., 4.]]), np.array([[1., 1., 3., 3.]]))
assert disjoint_grad[0] == 0 and disjoint_grad[1] < 0 and disjoint_grad[2] < 0
np.testing.assert_allclose(centered_grad, 0, atol=1e-10)
for invalid in (np.array([[0, 0, 0, 1]]), np.array([[0, 0, 1, np.nan]])):
try:
boxes_xyxy(invalid)
raise AssertionError('Se aceptó una caja inválida')
except ValueError:
pass
print('Desplazamientos:\n', np.round(deltas, 6))
print('IoU:\n', np.round(iou, 6))
print('GIoU:\n', np.round(giou, 6))
print('DIoU:\n', np.round(diou, 6))
print('Derivada numérica al desplazar la segunda caja a la derecha:')
print(' cajas separadas, IoU/GIoU/DIoU:', np.round(disjoint_grad, 6))
print(' caja centrada contenida, IoU/GIoU/DIoU:', np.round(centered_grad, 6))
print('Ida y vuelta, matriz vacía y cajas inválidas: correctas')Then implement per-class NMS and Gaussian Soft-NMS, re-sorting after each step with stable tie-breaking. This example’s output comes from boxes and scores defined in the cell.
"""NMS por clase y Soft-NMS gaussiana con reordenación tras cada paso.
Formato continuo xyxy. Umbral NMS estricto: se descarta si IoU > umbral.
Ante empate se elige el índice original menor. Las puntuaciones de Soft-NMS
deben ser no negativas; se conservan solo si score >= score_min.
"""
import numpy as np
def checked_inputs(boxes, scores, labels):
b = np.asarray(boxes, dtype=np.float64)
s = np.asarray(scores, dtype=np.float64)
c = np.asarray(labels)
if b.ndim != 2 or b.shape[1] != 4 or not np.isfinite(b).all():
raise ValueError('Cajas de forma (N, 4) y coordenadas finitas')
if np.any(b[:, 2:] <= b[:, :2]):
raise ValueError('Cajas con anchura y altura positivas')
if s.shape != (len(b),) or not np.isfinite(s).all() or c.shape != (len(b),):
raise ValueError('Puntuaciones y clases incompatibles')
if c.dtype.kind not in 'iu':
raise ValueError('Las clases deben ser índices enteros')
return b, s.copy(), c
def iou_one_to_many(box, boxes):
lo = np.maximum(box[:2], boxes[:, :2])
hi = np.minimum(box[2:], boxes[:, 2:])
intersection = np.prod(np.maximum(hi-lo, 0), axis=1)
area1 = np.prod(box[2:]-box[:2])
area2 = np.prod(boxes[:, 2:]-boxes[:, :2], axis=1)
return intersection / (area1 + area2 - intersection)
def nms_by_class(boxes, scores, labels, threshold):
b, s, c = checked_inputs(boxes, scores, labels)
if not np.isfinite(threshold) or not 0 <= threshold <= 1:
raise ValueError('Umbral de IoU entre 0 y 1')
remaining = np.arange(len(b))
keep = []
while len(remaining):
order = np.lexsort((remaining, -s[remaining]))
remaining = remaining[order]
chosen, rest = remaining[0], remaining[1:]
keep.append(chosen)
overlaps = iou_one_to_many(b[chosen], b[rest])
remaining = rest[~((c[rest] == c[chosen]) & (overlaps > threshold))]
return np.asarray(keep, dtype=np.int64)
def soft_nms_gaussian(boxes, scores, labels, sigma=.5, score_min=.001):
"""Devuelve índices y puntuaciones finales en el orden de selección."""
b, s, c = checked_inputs(boxes, scores, labels)
if np.any(s < 0) or not np.isfinite(sigma) or sigma <= 0 or not np.isfinite(score_min) or score_min < 0:
raise ValueError('Se exigen scores no negativos, sigma > 0 y score_min >= 0')
remaining = np.flatnonzero(s >= score_min)
keep, selected_scores = [], []
while len(remaining):
# La puntuación de los candidatos cambia: hay que volver a ordenar.
remaining = remaining[np.lexsort((remaining, -s[remaining]))]
chosen, rest = remaining[0], remaining[1:]
keep.append(chosen)
selected_scores.append(s[chosen])
same = c[rest] == c[chosen]
overlap = iou_one_to_many(b[chosen], b[rest])
s[rest[same]] *= np.exp(-(overlap[same] ** 2) / sigma)
remaining = rest[s[rest] >= score_min]
return np.asarray(keep, dtype=np.int64), np.asarray(selected_scores, dtype=np.float64)
boxes = np.array([[0., 0., 2., 2.], [.2, .2, 2.2, 2.2],
[4., 4., 6., 6.], [.2, .2, 2.2, 2.2]])
scores = np.array([.9, .85, .7, .8])
classes = np.array([0, 0, 0, 1])
hard = nms_by_class(boxes, scores, classes, .5)
soft, softened_scores = soft_nms_gaussian(boxes, scores, classes, .5, .001)
np.testing.assert_array_equal(hard, [0, 3, 2])
np.testing.assert_array_equal(soft, [0, 3, 2, 1])
expected_last = .85 * np.exp(-(1.8*1.8 / (8-1.8*1.8)) ** 2 / .5)
np.testing.assert_allclose(softened_scores, [.9, .8, .7, expected_last], atol=1e-15)
# IoU exactamente igual al umbral se conserva; empate por índice original.
equal_boxes = np.array([[0., 0., 2., 2.], [0., 0., 1., 2.]])
np.testing.assert_array_equal(nms_by_class(equal_boxes, [.5, .5], [0, 0], .5), [0, 1])
np.testing.assert_array_equal(nms_by_class(equal_boxes, [.5, .5], [0, 0], .49), [0])
np.testing.assert_array_equal(nms_by_class(np.empty((0, 4)), [], np.array([], dtype=int), .5), [])
np.testing.assert_array_equal(soft_nms_gaussian(boxes, scores, classes, .5, .71)[0], [0, 3])
print('NMS por clase, índices:', hard.tolist())
print('Soft-NMS gaussiana, índices:', soft.tolist())
print('Puntuaciones finales:', np.round(softened_scores, 6).tolist())
print('Reordenación, clases, empate, umbral exacto y conjunto vacío: correctos')The next cell implements COCO evaluation for boxes by category, including ranges, crowds and maxDets. Its complete precision and recall tensors were checked against pycocotools on the example, edge cases and reproducible sets. It does not cover masks, keypoints or category-free proposals; boxes must have positive area.
"""Evaluación COCO de cajas: IoU, AP/AR, multitudes y rangos de área.
Entradas: imágenes y categorías como listas de identificadores enteros;
anotaciones con image_id, category_id, bbox=[x,y,w,h], area e iscrowd;
detecciones con image_id, category_id, bbox y score. Cada lista conserva
su orden original en empates. En bbox, COCOeval oficial sobrescribe el campo
"ignore" de GT con iscrowd; se reproduce ese detalle, no un ignore general.
El área de GT se toma de su anotación, que puede proceder de una máscara.
No evalúa segmentación, keypoints, propuestas sin categoría ni COCO captions.
"""
import numpy as np
IOU_LEVELS = np.linspace(.50, .95, 10)
RECALL_LEVELS = np.linspace(0, 1, 101)
AREA_RANGES = ((0., 1e10), (0., 32.**2), (32.**2, 96.**2), (96.**2, 1e10))
MAX_DETS = (1, 10, 100)
def validate_records(images, categories, ground_truth, detections):
images, categories = sorted(set(images)), sorted(set(categories))
image_set, category_set = set(images), set(categories)
for r in list(ground_truth) + list(detections):
if r['image_id'] not in image_set or r['category_id'] not in category_set:
raise ValueError('Imagen o categoría fuera de las listas de evaluación')
box = np.asarray(r['bbox'], dtype=float)
if box.shape != (4,) or not np.isfinite(box).all() or np.any(box[2:] <= 0):
raise ValueError('bbox xywh debe ser finita, con anchura y altura positivas')
for r in ground_truth:
if not np.isfinite(r['area']) or r['area'] < 0 or r.get('iscrowd', 0) not in (0, 1):
raise ValueError('area o iscrowd inválido')
for r in detections:
if not np.isfinite(r['score']):
raise ValueError('La puntuación debe ser finita')
return images, categories
def bbox_overlaps(detections, ground_truth):
"""IoU normal, o intersección/área detección para cada GT iscrowd."""
result = np.zeros((len(detections), len(ground_truth)))
for d, dt in enumerate(detections):
x, y, w, h = dt['bbox']
for g, gt in enumerate(ground_truth):
u, v, p, q = gt['bbox']
intersection = max(0., min(x+w, u+p)-max(x, u)) * max(0., min(y+h, v+q)-max(y, v))
denominator = w*h if gt.get('iscrowd', 0) else w*h+p*q-intersection
result[d, g] = intersection / denominator
return result
def match_image(gt, dt, area_range, max_det):
"""Emparejamiento voraz por imagen, categoría y rango de área."""
lo, hi = area_range
ignored = np.array([bool(g.get('iscrowd', 0)) or g['area'] < lo or g['area'] > hi for g in gt], dtype=bool)
gt_order = np.argsort(ignored, kind='stable')
gt = [gt[i] for i in gt_order]
ignored = ignored[gt_order]
# Orden estable y truncado por imagen, no sobre el conjunto completo.
dt = sorted(dt, key=lambda d: -d['score'])[:max_det]
overlaps = bbox_overlaps(dt, gt)
matched = np.zeros((len(IOU_LEVELS), len(dt)), dtype=bool)
dt_ignore = np.zeros_like(matched)
for t, threshold in enumerate(IOU_LEVELS):
gt_taken = np.zeros(len(gt), dtype=bool)
for d in range(len(dt)):
best, best_overlap = -1, min(float(threshold), 1 - 1e-10)
for g in range(len(gt)):
if gt_taken[g] and not gt[g].get('iscrowd', 0):
continue
if best >= 0 and not ignored[best] and ignored[g]:
break
if overlaps[d, g] < best_overlap:
continue
best, best_overlap = g, overlaps[d, g]
if best >= 0:
matched[t, d] = True
dt_ignore[t, d] = ignored[best]
gt_taken[best] = True
elif dt[d]['bbox'][2] * dt[d]['bbox'][3] < lo or dt[d]['bbox'][2] * dt[d]['bbox'][3] > hi:
dt_ignore[t, d] = True
return np.array([d['score'] for d in dt]), matched, dt_ignore, int(np.count_nonzero(~ignored))
def coco_bbox_eval(images, categories, ground_truth, detections):
"""Tensor precisión (10,101,K,4,3), recall (10,K,4,3); -1 si sin GT válido."""
images, categories = validate_records(images, categories, ground_truth, detections)
shape = (len(IOU_LEVELS), len(categories), len(AREA_RANGES), len(MAX_DETS))
precision = np.full((shape[0], len(RECALL_LEVELS), *shape[1:]), -1., dtype=float)
recall = np.full(shape, -1., dtype=float)
for k, category in enumerate(categories):
for a, area_range in enumerate(AREA_RANGES):
# Solo hay que emparejar una vez a maxDets=100: los prefijos no cambian.
per_image = []
for image in images:
gt = [r for r in ground_truth if r['image_id'] == image and r['category_id'] == category]
dt = [r for r in detections if r['image_id'] == image and r['category_id'] == category]
if gt or dt:
per_image.append(match_image(gt, dt, area_range, MAX_DETS[-1]))
if not per_image:
continue
positives = sum(entry[3] for entry in per_image)
if positives == 0:
continue
for m, limit in enumerate(MAX_DETS):
scores = np.concatenate([entry[0][:limit] for entry in per_image])
matched = np.concatenate([entry[1][:, :limit] for entry in per_image], axis=1)
ignored = np.concatenate([entry[2][:, :limit] for entry in per_image], axis=1)
order = np.argsort(-scores, kind='stable')
matched, ignored = matched[:, order], ignored[:, order]
tp = np.cumsum(matched & ~ignored, axis=1)
fp = np.cumsum(~matched & ~ignored, axis=1)
for t in range(len(IOU_LEVELS)):
r = tp[t] / positives
p = tp[t] / (tp[t] + fp[t] + np.spacing(1))
recall[t, k, a, m] = r[-1] if len(r) else 0.
if len(p):
envelope = np.maximum.accumulate(p[::-1])[::-1]
inds = np.searchsorted(r, RECALL_LEVELS, side='left')
valid = inds < len(envelope)
precision[t, :, k, a, m] = 0.
precision[t, valid, k, a, m] = envelope[inds[valid]]
else:
precision[t, :, k, a, m] = 0.
return {'precision': precision, 'recall': recall, 'images': images, 'categories': categories}
def valid_mean(values):
"""Excluye combinaciones con -1; devuelve -1 si ninguna es válida."""
values = np.asarray(values)
values = values[values >= 0]
return float(values.mean()) if len(values) else -1.
# Dos clases evaluables, otra solo con falsos positivos y otra solo crowd.
# La primera predicción es un FP empatado con una verdadera de otra imagen.
images, categories = [1, 2, 3], [1, 2, 3, 4]
ground_truth = [
{'image_id': 1, 'category_id': 1, 'bbox': [0., 0., 20., 20.], 'area': 400., 'iscrowd': 0},
{'image_id': 1, 'category_id': 1, 'bbox': [40., 0., 80., 80.], 'area': 6400., 'iscrowd': 1},
{'image_id': 2, 'category_id': 1, 'bbox': [10., 10., 32., 32.], 'area': 1024., 'iscrowd': 0},
{'image_id': 2, 'category_id': 2, 'bbox': [0., 0., 100., 100.], 'area': 10000., 'iscrowd': 0, 'ignore': 1},
{'image_id': 3, 'category_id': 4, 'bbox': [0., 0., 20., 20.], 'area': 400., 'iscrowd': 1},
]
detections = [
{'image_id': 1, 'category_id': 1, 'bbox': [150., 150., 10., 10.], 'score': .99},
{'image_id': 2, 'category_id': 1, 'bbox': [10., 10., 32., 32.], 'score': .99},
{'image_id': 1, 'category_id': 1, 'bbox': [0., 0., 20., 20.], 'score': .95},
{'image_id': 1, 'category_id': 1, 'bbox': [0., 0., 20., 20.], 'score': .90},
{'image_id': 1, 'category_id': 1, 'bbox': [50., 10., 10., 10.], 'score': .89},
{'image_id': 1, 'category_id': 1, 'bbox': [60., 20., 10., 10.], 'score': .88},
{'image_id': 2, 'category_id': 2, 'bbox': [0., 0., 100., 100.], 'score': .75},
{'image_id': 3, 'category_id': 3, 'bbox': [0., 0., 5., 5.], 'score': .80},
{'image_id': 3, 'category_id': 4, 'bbox': [0., 0., 5., 5.], 'score': .75},
]
result = coco_bbox_eval(images, categories, ground_truth, detections)
precision, recall = result['precision'], result['recall']
assert precision.shape == (10, 101, 4, 4, 3) and recall.shape == (10, 4, 4, 3)
assert np.all(precision[:, :, 2:, :, :] == -1)
assert np.all(precision[:, :, 1, 0, 2] >= 0) # ignore aislado no anula GT de bbox
assert valid_mean(precision[:, :, :, 0, 2]) >= 0
# Referencia: COCOeval bbox de pycocotools 2.0.11, para los datos anteriores.
# Se contrastaron además los tensores completos fuera de esta celda.
assert np.isclose(valid_mean(precision[:, :, :, 0, 2]), 5/6, atol=1e-12)
assert np.isclose(valid_mean(precision[0, :, :, 0, 2]), 5/6, atol=1e-12)
assert np.allclose([valid_mean(recall[:, :, 0, m]) for m in range(3)], [0.75, 1., 1.], atol=1e-12)
assert np.allclose([valid_mean(precision[:, :, :, a, 2]) for a in (1, 2, 3)], [2/3, 1., 1.], atol=1e-12)
print('AP COCO, área all, maxDets 100:', round(valid_mean(precision[:, :, :, 0, 2]), 6))
print('AP50, área all, maxDets 100:', round(valid_mean(precision[0, :, :, 0, 2]), 6))
print('AR, área all, maxDets 1/10/100:', [round(valid_mean(recall[:, :, 0, m]), 6) for m in range(3)])
print('AP small/medium/large:', [round(valid_mean(precision[:, :, :, a, 2]), 6) for a in (1, 2, 3)])
print('Clases sin GT válido: precisión y recall = -1, excluidas de la media')A real detector on VOC
The local cell downloads official COCO Faster R-CNN weights and a pinned VOC2007 mirror. It reads the compressed file without extracting it, verifies its hash, maps the 20 categories by name and excludes images containing difficult objects; this sample is therefore not the official VOC protocol. This cell’s own AP covers full area without crowds and is compared with TorchMetrics; the preceding evaluator covers the more general box protocol. By default valid validation images are processed; ORYON_VERIFY_SHORT=1 limits this to eight. If the sample contains image 000009, the cell also exports JSON with its PNG and detections in the structure used by the NMS interactive.
In a short test of eight images and seven present classes, own AP was 0.6169731259 and TorchMetrics gave 0.6169731021; AP50 was 0.8333333333 and 0.8333333135 respectively. At score at least 0.5, the diagnostic rule recorded 16 true positives, 0 duplicates, 1 class error, 4 localization errors, 1 background error and 1 missed object. These figures are from that filtered sample, not a VOC benchmark or estimate of causal gain from correcting each error.
"""Detector COCO en VOC2007 val; AP propia frente a TorchMetrics.
Requiere torch, torchvision, torchmetrics, pycocotools, numpy, Pillow y
huggingface_hub. El lector necesita instalar los paquetes ausentes, por
ejemplo torchmetrics[detection]. Descarga el tar a la caché de Hugging Face
y los pesos oficiales a la caché de Torch. No extrae el tar. El protocolo
excluye imágenes con algún objeto marcado difficult: no es la evaluación
VOC oficial, y no trata difficult como iscrowd. Las clases comunes se mapean
por nombre entre VOC y los índices COCO de los pesos.
El cálculo propio cubre área all y maxDet 100 sin crowd, y se contrasta con
TorchMetrics/pycocotools para AP@[.50:.95], AP50 y AP75. Los parámetros de
área y crowd requieren el evaluador completo de la otra celda. ORYON_VERIFY_SHORT=1
usa 8 imágenes: sirve para verificar el circuito, no para publicar mAP VOC.
"""
import base64
import hashlib
import io
import json
import os
import tarfile
import xml.etree.ElementTree as ET
from pathlib import Path
import numpy as np
from PIL import Image
from huggingface_hub import hf_hub_download
import torch
from torchmetrics.detection.mean_ap import MeanAveragePrecision
from torchvision.models.detection import fasterrcnn_resnet50_fpn, FasterRCNN_ResNet50_FPN_Weights
torch.set_num_threads(1)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
short = os.environ.get('ORYON_VERIFY_SHORT') == '1'
repo, revision = 'davin11/VOC2007', 'fa6fc00e5e617859ce9b7aa7abd581c7bd8ffa15'
filename = 'VOCtrainval_06-Nov-2007.tar'
expected_sha256 = '7d8cd951101b0957ddfd7a530bdc8a94f06121cfc1e511bb5937e973020c7508'
weights = FasterRCNN_ResNet50_FPN_Weights.COCO_V1
names = weights.meta['categories']
voc_classes = ['aeroplane','bicycle','bird','boat','bottle','bus','car','cat','chair','cow',
'diningtable','dog','horse','motorbike','person','pottedplant','sheep','sofa','train','tvmonitor']
aliases = {'aeroplane':'airplane', 'diningtable':'dining table', 'motorbike':'motorcycle',
'pottedplant':'potted plant', 'sofa':'couch', 'tvmonitor':'tv'}
mapping = {name: names.index(aliases.get(name, name)) for name in voc_classes}
allowed = set(mapping.values())
def sha256_file(path):
digest = hashlib.sha256()
with open(path, 'rb') as stream:
for part in iter(lambda: stream.read(1024*1024), b''):
digest.update(part)
return digest.hexdigest()
def iou_matrix(box, boxes):
if not len(boxes):
return np.empty(0, dtype=np.float64)
lo = np.maximum(box[:2], boxes[:, :2])
hi = np.minimum(box[2:], boxes[:, 2:])
intersection = np.maximum(hi-lo, 0).prod(axis=1)
area_a = np.maximum(box[2:]-box[:2], 0).prod()
area_b = np.maximum(boxes[:, 2:]-boxes[:, :2], 0).prod(axis=1)
return np.divide(intersection, area_a+area_b-intersection,
out=np.zeros_like(intersection), where=(area_a+area_b-intersection)>0)
def own_ap(predictions, targets, thresholds=np.linspace(.5,.95,10), max_det=100):
"""Área all, sin ignore/crowd: matching por imagen y clase; 101 recalls."""
classes = sorted({int(c) for target in targets for c in target['labels'].tolist()})
table = []
for threshold in thresholds:
scores_by_class = []
for category in classes:
events, num_gt = [], 0
for prediction, target in zip(predictions, targets):
gt = target['boxes'][target['labels']==category].numpy().astype(np.float64)
num_gt += len(gt)
mask = prediction['labels']==category
boxes = prediction['boxes'][mask].numpy().astype(np.float64)
scores = prediction['scores'][mask].numpy().astype(np.float64)
order = np.argsort(-scores, kind='stable')[:max_det]
used = np.zeros(len(gt), dtype=bool)
for idx in order:
overlaps = iou_matrix(boxes[idx], gt)
best, current = -1, min(float(threshold), 1-1e-10)
for j, overlap in enumerate(overlaps):
if used[j] or overlap < current:
continue
best, current = j, overlap
if best >= 0:
used[best] = True
events.append((float(scores[idx]), int(best >= 0)))
events.sort(key=lambda event: -event[0]) # estable entre imágenes y empates
if not events:
scores_by_class.append(0.)
continue
tp = np.cumsum([event[1] for event in events])
fp = np.cumsum([1-event[1] for event in events])
recall = tp/num_gt
precision = tp/np.maximum(tp+fp, 1)
precision = np.maximum.accumulate(precision[::-1])[::-1]
ix = np.searchsorted(recall, np.linspace(0,1,101), side='left')
interpolated = np.zeros(101)
valid = ix < len(precision)
interpolated[valid] = precision[ix[valid]]
scores_by_class.append(float(interpolated.mean()))
table.append(float(np.mean(scores_by_class)) if scores_by_class else None)
return {'map': float(np.mean(table)), 'map_50': table[0], 'map_75': table[5],
'per_iou': table, 'classes_with_ground_truth': classes}
def diagnose(predictions, targets, score_threshold=.5):
"""Conteos de diagnóstico local, no descomposición causal de AP."""
totals = {'true_positive':0, 'duplicate':0, 'classification':0, 'localization':0, 'background':0, 'missed':0}
for pred, target in zip(predictions, targets):
boxes, labels = target['boxes'].numpy(), target['labels'].numpy()
used = set()
ordered = np.argsort(-pred['scores'].numpy(), kind='stable')
for i in ordered:
if float(pred['scores'][i]) < score_threshold:
continue
overlaps = iou_matrix(pred['boxes'][i].numpy(), boxes)
label = int(pred['labels'][i])
same = [j for j in range(len(boxes)) if labels[j] == label and overlaps[j] >= .5]
available = [j for j in same if j not in used]
if available:
chosen = max(available, key=lambda j: (overlaps[j], -j))
used.add(chosen)
totals['true_positive'] += 1
elif same:
totals['duplicate'] += 1
elif any(labels[j] != label and overlaps[j] >= .5 for j in range(len(boxes))):
totals['classification'] += 1
elif any(labels[j] == label and .1 <= overlaps[j] < .5 for j in range(len(boxes))):
totals['localization'] += 1
else:
totals['background'] += 1
totals['missed'] += len(boxes)-len(used)
return totals
def main():
if device.type != 'cuda':
raise RuntimeError('Para esta comprobación se requiere CUDA')
path = hf_hub_download(repo_id=repo, repo_type='dataset', revision=revision, filename=filename)
checksum = sha256_file(path)
if checksum != expected_sha256:
raise ValueError('El hash del tar no coincide con el espejo fijado')
model = fasterrcnn_resnet50_fpn(weights=weights, box_score_thresh=0., box_detections_per_img=100).to(device).eval()
transform = weights.transforms()
predictions, targets, ids, skipped = [], [], [], []
prefix = 'VOCdevkit/VOC2007/'
with tarfile.open(path, 'r:') as archive:
val_ids = archive.extractfile(prefix+'ImageSets/Main/val.txt').read().decode('ascii').split()
for image_id in val_ids:
xml = ET.fromstring(archive.extractfile(prefix+'Annotations/'+image_id+'.xml').read())
objects = xml.findall('object')
if any(int(o.findtext('difficult', default='0')) for o in objects):
skipped.append(image_id)
continue
bboxes, labels = [], []
for obj in objects:
box = obj.find('bndbox')
# VOC: 1-based inclusivo; xyxy medio abierto de píxeles.
coords = [int(box.findtext('xmin'))-1, int(box.findtext('ymin'))-1,
int(box.findtext('xmax')), int(box.findtext('ymax'))]
if coords[2] <= coords[0] or coords[3] <= coords[1]:
raise ValueError('Caja VOC degenerada: '+image_id)
bboxes.append(coords)
labels.append(mapping[obj.findtext('name')])
target = {'boxes': torch.tensor(bboxes, dtype=torch.float32).reshape(-1,4),
'labels': torch.tensor(labels, dtype=torch.int64)}
with Image.open(io.BytesIO(archive.extractfile(prefix+'JPEGImages/'+image_id+'.jpg').read())) as image:
x = transform(image.convert('RGB')).to(device)
with torch.no_grad():
prediction = model([x])[0]
mask = torch.tensor([int(label) in allowed for label in prediction['labels']], device=device)
pred = {k: prediction[k][mask].cpu() for k in ('boxes','scores','labels')}
predictions.append(pred)
targets.append(target)
ids.append(image_id)
print('procesada', image_id, 'objetos', len(labels), 'predicciones VOC', len(pred['labels']), flush=True)
if short and len(ids) >= 8:
break
if not ids:
raise RuntimeError('No se encontró ninguna imagen válida')
own = own_ap(predictions, targets)
metric = MeanAveragePrecision(box_format='xyxy', iou_type='bbox', backend='pycocotools')
metric.update(predictions, targets)
reference_raw = metric.compute()
reference = {key: float(reference_raw[key]) for key in ('map','map_50','map_75')}
for key, value in reference.items():
if not np.isclose(own[key], value, rtol=0, atol=1e-6):
raise AssertionError(f'{key}: propio={own[key]} TorchMetrics={value}')
def serialize(row):
return {key: value.tolist() for key,value in row.items()}
output = {'protocol': {'repo': repo, 'revision': revision, 'tar_sha256': checksum,
'dataset': 'VOC2007 val del tar trainval', 'short': short, 'ids': ids,
'skipped_difficult_ids': skipped, 'weights': 'FasterRCNN_ResNet50_FPN_Weights.COCO_V1',
'class_mapping': mapping, 'boxes': 'VOC 1-based inclusivo a xyxy 0-based con extremos superiores abiertos',
'metric': 'área all, maxDet 100, IoU .50:.95, 101 recalls, sin crowd ni imágenes difficult',
'score_filter': 'el detector limita a 100 detecciones totales por imagen y se conservan después las 20 clases VOC',
'warning': 'muestra y filtrado no corresponden a evaluación VOC oficial; modelo preentrenado en COCO',
'gpu': torch.cuda.get_device_name(device), 'torch': str(torch.__version__), 'cuda': str(torch.version.cuda)},
'own': own, 'torchmetrics': reference, 'diagnostic_score_threshold': .5,
'diagnostic': diagnose(predictions, targets),
'predictions': [serialize(p) for p in predictions], 'targets': [serialize(t) for t in targets]}
out = Path(os.environ.get('ORYON_VOC_OUTPUT', 'voc-detection-results.json'))
out.write_text(json.dumps(output, ensure_ascii=False, indent=2, allow_nan=False), encoding='utf-8')
image_id = '000009'
if image_id in ids:
# Imagen y predicciones de la figura NMS. Se leen del mismo tar fijado
# y de la ejecución actual, no de archivos auxiliares de la lección.
index = ids.index(image_id)
with tarfile.open(path, 'r:') as archive:
raw = archive.extractfile(prefix+'JPEGImages/'+image_id+'.jpg').read()
with Image.open(io.BytesIO(raw)) as image:
image = image.convert('RGB')
width, height = image.size
image.thumbnail((500, 500))
buffer = io.BytesIO()
image.save(buffer, format='PNG')
pred = output['predictions'][index]
example = {'protocol': {'source': 'VOC2007 val, predicciones reales de Faster R-CNN COCO_V1',
'note': 'Estas salidas ya pasaron NMS interna; la figura aplica una segunda supresión.',
'repo': repo, 'revision': revision, 'id': image_id},
'image': 'data:image/png;base64,'+base64.b64encode(buffer.getvalue()).decode('ascii'),
'width': width, 'height': height,
'classes': {str(value): key for key, value in mapping.items()},
'predictions': [{'id': i, 'box': box, 'score': score, 'label': label}
for i, (box, score, label) in enumerate(zip(pred['boxes'], pred['scores'], pred['labels']))]}
example_out = out.with_name(out.stem + '-nms-ejemplo.json')
example_out.write_text(json.dumps(example, ensure_ascii=False, separators=(',', ':'), allow_nan=False), encoding='utf-8')
print('Ejemplo NMS:', example_out, 'candidatas:', len(example['predictions']), flush=True)
else:
print('La muestra no incluye la imagen 000009 para el ejemplo NMS.', flush=True)
print('propio:', own, 'TorchMetrics:', reference, 'diagnóstico:', output['diagnostic'], 'archivo:', out, flush=True)
del model
torch.cuda.empty_cache()
if __name__ == '__main__':
main()npm run lab and open the connection link.Exercises
import numpy as np
def iou_pairwise(a, b):
passimport numpy as np
def class_nms(boxes, scores, classes, threshold):
pass