Bounding boxes and IoU
Quick answer
Object detection predicts both object categories and locations. An axis-aligned bounding box stores two corners; intersection over union (IoU) measures overlap between two regions on a scale from zero to one. Examples are static Python snippets tested locally on CPU; Torchvision is required for selected examples. ByteMind execution is unverified.
Overlap with native box_iou
import torchfrom torchvision.ops import box_ioua=torch.tensor([[0.,0.,4.,4.]])b=torch.tensor([[2.,0.,6.,4.],[4.,0.,8.,4.]])print([round(v,6) for v in box_iou(a,b)[0].tolist()])Expected output (locally tested): [0.333333, 0.0]. Intersection eight, union 24; edge-touching boxes have zero intersection.
How it works
Use continuous or half-open pixel coordinates (x1,y1,x2,y2), with x2>x1 and y2>y1. Width is x2-x1, not x2-x1+1. Intersection width is max(0,min(x2)-max(x1)); height is analogous. IoU = intersection area / (area A + area B - intersection area). Touching edges have zero overlap. A box encloses an object but does not describe its exact silhouette. Convert (x,y,w,h) to (x,y,x+w,y+h); clip to image bounds and remove empty boxes. For a horizontal flip of width W, the x interval becomes [W-x2,W-x1). Apply the same geometric transform to pixels, boxes and masks. Scores are model outputs, not necessarily calibrated probabilities.
Horizontal annotation flip
W=10box=[1,2,4,5]def flip(b): x1,y1,x2,y2=b return [W-x2,y1,W-x1,y2]print(flip(box),flip(flip(box)))Expected output (locally tested): [6, 2, 9, 5] [1, 2, 4, 5]. Coordinates follow half-open convention and the operation is reversible.
Common mistakes
Mixing inclusive and half-open coordinates changes areas and IoU. Do not silently swap x and y. Reject invalid boxes before calling evaluation; a zero union has no ordinary IoU.
Practice and next steps
Calculate the overlap of two 4x4 squares offset by two pixels horizontally. Flip a box twice and verify its coordinates return unchanged.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Bounding boxes and IoU — knowledge check
Apply bounding boxes and iou to small examples and debugging scenarios.
What does a detection box add to a class label?
Two boxes touch at an edge. IoU?
Two identical positive-area boxes have IoU?
Horizontal flip of [2,5) in width 8?
What should happen to boxes during a crop?