Definitionintro
Intersection over union
Also called IoU, box overlap ratio.
The area of the intersection of two boxes or regions divided by the area of their union, the measure of how well a detection matches an object.
Intersection over union (IoU) is the area of the overlap of two regions divided by the area of the region that they cover together. It is the Jaccard index of two sets of points, applied to boxes or to pixel masks in an image. In object detection it decides whether a predicted box matches a ground-truth box, and it is the overlap test inside box non-maximum suppression and detection mean average precision. The value is 1 for two equal regions, 0 for regions that do not overlap, and it does not change when both regions move or scale together.
Definition
For two measurable regions and of the plane with , where is the area,
For two finite sets of pixels, is the number of pixels. When both regions are empty the ratio is , and a program must pick a value; this page uses 0, and a mask metric often uses 1.
On this page a box is with and in continuous image coordinates, the set , so its area is . An axis-aligned box meets another axis-aligned box in a box or in nothing, so the IoU of two boxes costs a constant number of operations:
IOU(a, b)- 1
w ← min(a.x2, b.x2) - max(a.x1, b.x1) - 2
h ← min(a.y2, b.y2) - max(a.y1, b.y1) - 3
if w ≤ 0 or h ≤ 0 then I ← 0 else I ← w · h - 4
U ← area(a) + area(b) - I - 5
return I / U
Line L3 tests the overlap of the two intervals in each axis, and line L4 is inclusion and exclusion. The proof that the procedure gives the ratio of areas is in the correctness file of this page. On integer boxes the value is a rational number, and an exact check uses fractions.
The PASCAL VOC development kit uses a different box form: and are the indices of the first and the last pixel, both inclusive, so a side has pixels. This form is the continuous box . Code that mixes the two forms gets a wrong value, and the error is large for small boxes.
The quantity is the Jaccard distance. It is a metric: it is symmetric, it is 0 only for equal regions of positive area, and it satisfies the triangle inequality (Kosub 2019 gives two short proofs for finite sets; the box case follows through pixel cells). This is a theorem. The use of a fixed threshold on IoU, such as 0.5, to call a detection correct is a convention.
Examples and non-examples
- The check values. : the intersection is the unit square, and the union is . : a box shifted by half its width.
- A shift by a third. . A box moved sideways by one third of its width is exactly at the threshold 0.5 of PASCAL VOC, and VOC requires a value above 0.5, so this box does not count as a match.
- A box that is too small. A box of side 7 inside the box gives . A detection that is correct in position but has sides at 70 percent of the true sides fails the 0.5 test.
- The same numbers in the inclusive form. As inclusive pixel boxes, and have 9 pixels each and share 4, so the IoU is , twice the continuous value. and give instead of .
- Pixel masks. For two masks of an instance, the IoU counts pixels: 120 shared pixels out of 200 pixels covered by either mask give . The mean IoU of semantic segmentation computes this ratio for each class over all pixels of a data set and averages over classes.
- Not coverage. The coverage ratios (the part of that covers) and are not IoU. For the box inside both are 1, while the IoU is . The deformable part model of Felzenszwalb et al. (2010) suppresses a box when a kept box covers at least half of it, and a reader who takes that rule for an IoU threshold misreads it.
- Not the Dice coefficient. The Dice coefficient is an increasing function of IoU, , so it ranks pairs in the same order but gives other values: IoU is Dice . A threshold on one is not the same number on the other.
- Disjoint boxes. and have IoU 0, and so do and . IoU does not say how far apart two disjoint boxes are, which is why a loss of has no gradient for them. The generalized IoU of Rezatofighi et al. subtracts , where is the smallest box that holds both, and gives and for these two pairs.
Related definitions
The Jaccard similarity is the same ratio for any two finite sets, such as sets of words or shingles; IoU is its name in vision, for regions of the plane. Detection uses IoU in three places. A matching rule calls a predicted box a true positive when its IoU with an unmatched ground-truth box is above a threshold, which detection mean average precision turns into one score per class. Box non-maximum suppression and Soft-NMS remove or down-weight a box by its IoU with a box of higher score. Anchor assignment and bounding box regression pick training targets by IoU. Mean intersection over union is the segmentation metric built from pixel IoU per class.
Boxes that are not axis-aligned, such as rotated boxes, meet in a convex polygon, and their IoU needs a convex polygon intersection, which costs for polygons of and vertices instead of . The generalized IoU (GIoU) has values in , is equal to IoU when one box holds the other, and is also a metric. The Python code of this page computes IoU for boxes in both forms, for pixel sets, the Jaccard distance and GIoU, and its tests compare the box formula with a count of pixel cells.
Proof: The box formula for IoU gives the area of the intersection over the area of the unionfull
We use the notation of the page. A box is with and , and it is the closed set of the plane. Its area is . The procedure IOU of the page computes and in lines L1 and L2, in line L3, in line L4 and returns in line L5.
Claim. If , IOU returns , where is the area (the Lebesgue measure of the set).
Lemma 1 (the intersection of two boxes). , and this set is empty when one of the two intervals is empty.
Proof. A point is in exactly when , , and . The two conditions on together say , and the same holds for . A product of two intervals is empty exactly when one of them is empty.
Lemma 2 (the area of the intersection). After line L3, .
Proof. Lines L1 and L2 compute the lengths and of the two intervals of Lemma 1. If and , the intersection is a box with sides and , so its area is . If or , the interval is empty or a single point, so the intersection is empty or lies on a line segment, and its area is 0. Line L3 returns exactly these two values.
Lemma 3 (the area of the union). After line L4, .
Proof. Area is additive on disjoint measurable sets, and is the disjoint union of and . Also is the disjoint union of and . So , which is the value of line L4 by Lemma 2.
Proof of the claim. By Lemmas 2 and 3, line L5 returns when .
Corollary (range and symmetry). and . If and , then exactly when .
Proof. gives the range, and the formulas of lines L1 to L4 do not change when and swap. If the value is 1, then , so . The intersection is a box inside with the same positive area, and a box inside a box with the same area has the same sides, so . In the same way , so .
Corollary (invariance). For a map with , .
Proof. maps boxes to boxes, keeps the order of coordinates, and maps to . It multiplies every area by , so the ratio does not change.
Corollary (pixel sets). For a box with integer corners, let be the set of unit cells inside . Then , , and the box IoU equals .
Proof. The cells inside are those with and , so there are of them. A cell is inside both boxes exactly when it is inside their intersection, which is a box with integer corners by Lemma 1. Counting with inclusion and exclusion as in Lemma 3 gives the union.
The inclusive pixel form. The PASCAL VOC development kit stores the first and the last pixel of each side, so a side from index to index has pixels. This is the continuous box , and the claim applies to that box. The two forms give different values on the same four numbers, for example and for and .
The metric. The Jaccard distance satisfies the triangle inequality on finite sets (Kosub 2019 gives two short proofs). By the pixel-set corollary, is then a metric on boxes with integer corners and positive area. A box with rational corners becomes a box with integer corners after a scaling, which does not change IoU by the invariance corollary, and continuity extends the inequality to real corners. We do not repeat the proof of the set inequality here; the tests check it on random boxes.
Code
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/intersection-over-union/. The authors are listed in prov/20CWE7.jsonl.
"""Intersection over union (IoU) of axis-aligned boxes and of pixel sets.
A box is (x1, y1, x2, y2) with x1 <= x2 and y1 <= y2 in continuous image
coordinates, so its area is (x2 - x1) (y2 - y1). With inclusive=True the
corners are inclusive pixel indices, as in the PASCAL VOC development kit,
and every side length gets + 1. Integer or Fraction inputs give exact results
when the caller wraps them in Fraction; floats give float results.
Standard library only. Cost: O(1) per pair of boxes, O(|A| + |B|) per pair of
pixel sets.
"""
from fractions import Fraction
def box_area(b, inclusive=False):
"""Area of a box; 0 for a degenerate box."""
e = 1 if inclusive else 0
return max(0, b[2] - b[0] + e) * max(0, b[3] - b[1] + e)
def intersection_area(a, b, inclusive=False):
"""Area of the intersection box [max x1, min x2] x [max y1, min y2]."""
e = 1 if inclusive else 0
iw = min(a[2], b[2]) - max(a[0], b[0]) + e # @line L1
ih = min(a[3], b[3]) - max(a[1], b[1]) + e # @line L2
if iw <= 0 or ih <= 0: # @line L3
return 0
return iw * ih
def iou(a, b, inclusive=False, empty=0):
"""IoU of two boxes. Returns `empty` when the union has area 0."""
inter = intersection_area(a, b, inclusive) # @line L3
union = box_area(a, inclusive) + box_area(b, inclusive) - inter # @line L4
if union == 0:
return empty
if isinstance(inter, int) and isinstance(union, int):
return Fraction(inter, union) # @line L5
return inter / union # @line L5
def iou_matrix(boxes_a, boxes_b, inclusive=False):
"""All pairwise IoU values, as a list of rows (one row per box of boxes_a)."""
return [[iou(a, b, inclusive) for b in boxes_b] for a in boxes_a]
def mask_iou(pa, pb, empty=0):
"""IoU of two finite sets of pixels, |A & B| / |A | B|."""
sa, sb = set(pa), set(pb)
union = len(sa | sb)
if union == 0:
return empty
return Fraction(len(sa & sb), union)
def box_pixels(b):
"""The unit cells [u, u+1) x [v, v+1) inside an integer box, as (u, v) pairs."""
return {(u, v) for v in range(b[1], b[3]) for u in range(b[0], b[2])}
def jaccard_distance(a, b):
"""1 - IoU of two boxes; a metric on boxes of positive area."""
return 1 - iou(a, b)
def enclosing_box(a, b):
return (min(a[0], b[0]), min(a[1], b[1]), max(a[2], b[2]), max(a[3], b[3]))
def giou(a, b):
"""Generalized IoU of Rezatofighi et al. 2019: IoU - |C minus (A u B)| / |C|.
C is the smallest box that holds both boxes. The value lies in (-1, 1].
"""
inter = intersection_area(a, b)
union = box_area(a) + box_area(b) - inter
c = box_area(enclosing_box(a, b))
if isinstance(c, int) and isinstance(union, int):
return Fraction(inter, union) - Fraction(c - union, c)
return inter / union - (c - union) / c
def intersection_over_min(a, b):
"""|A & B| / min(|A|, |B|), the coverage overlap. This is NOT IoU."""
inter = intersection_area(a, b)
m = min(box_area(a), box_area(b))
if isinstance(inter, int) and isinstance(m, int):
return Fraction(inter, m)
return inter / m
test_intersection_over_union.py 106 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/intersection-over-union/. The authors are listed in prov/20CWE7.jsonl.
import random
from fractions import Fraction
from intersection_over_union import (box_area, box_pixels, giou, intersection_area,
intersection_over_min, iou, iou_matrix,
jaccard_distance, mask_iou)
def random_box(rng, size=8):
x1, x2 = sorted(rng.sample(range(size + 1), 2))
y1, y2 = sorted(rng.sample(range(size + 1), 2))
return (x1, y1, x2, y2)
def test_check_values():
assert iou((0, 0, 2, 2), (1, 1, 3, 3)) == Fraction(1, 7)
assert iou((0, 0, 10, 10), (5, 0, 15, 10)) == Fraction(1, 3)
assert iou((0, 0, 3, 3), (1, 0, 4, 3)) == Fraction(1, 2)
assert iou((0, 0, 10, 10), (0, 0, 7, 7)) == Fraction(49, 100)
def test_inclusive_pixel_form():
# VOC devkit form: corners are inclusive pixel indices.
assert iou((0, 0, 2, 2), (1, 1, 3, 3), inclusive=True) == Fraction(2, 7)
assert iou((0, 0, 10, 10), (5, 0, 15, 10), inclusive=True) == Fraction(3, 8)
rng = random.Random(3)
for _ in range(200):
a, b = random_box(rng), random_box(rng)
grow = lambda r: (r[0], r[1], r[2] + 1, r[3] + 1)
assert iou(a, b, inclusive=True) == iou(grow(a), grow(b))
def test_against_pixel_sets():
rng = random.Random(1)
for _ in range(300):
a, b = random_box(rng), random_box(rng)
assert intersection_area(a, b) == len(box_pixels(a) & box_pixels(b))
assert iou(a, b) == mask_iou(box_pixels(a), box_pixels(b))
def test_range_symmetry_and_identity():
rng = random.Random(2)
for _ in range(300):
a, b = random_box(rng), random_box(rng)
v = iou(a, b)
assert 0 <= v <= 1
assert v == iou(b, a)
assert iou(a, a) == 1
if v == 1:
assert a == b
def test_jaccard_distance_triangle_inequality():
rng = random.Random(4)
for _ in range(2000):
a, b, c = random_box(rng, 6), random_box(rng, 6), random_box(rng, 6)
assert jaccard_distance(a, c) <= jaccard_distance(a, b) + jaccard_distance(b, c)
def test_translation_and_scale_invariance():
rng = random.Random(5)
for _ in range(200):
a, b = random_box(rng), random_box(rng)
dx, dy, s = rng.randint(-5, 5), rng.randint(-5, 5), rng.randint(1, 4)
move = lambda r: (s * r[0] + dx, s * r[1] + dy, s * r[2] + dx, s * r[3] + dy)
assert iou(move(a), move(b)) == iou(a, b)
def test_floats():
v = iou((0.0, 0.0, 2.0, 2.0), (1.0, 1.0, 3.0, 3.0))
assert abs(v - 1.0 / 7.0) < 1e-15
def test_empty_union():
assert iou((1, 1, 1, 1), (2, 2, 2, 2)) == 0
assert iou((1, 1, 1, 1), (2, 2, 2, 2), empty=1) == 1
assert box_area((3, 3, 1, 5)) == 0
def test_giou():
assert giou((0, 0, 1, 1), (2, 0, 3, 1)) == Fraction(-1, 3)
assert giou((0, 0, 1, 1), (5, 0, 6, 1)) == Fraction(-2, 3)
assert giou((0, 0, 2, 2), (1, 1, 3, 3)) == Fraction(-5, 63)
rng = random.Random(6)
for _ in range(300):
a, b = random_box(rng), random_box(rng)
g = giou(a, b)
assert -1 < g <= iou(a, b) <= 1
inside = a[0] <= b[0] and a[1] <= b[1] and b[2] <= a[2] and b[3] <= a[3]
if inside:
assert g == iou(a, b)
def test_coverage_is_not_iou():
big, small = (0, 0, 10, 10), (2, 2, 6, 6)
assert intersection_over_min(big, small) == 1
assert iou(big, small) == Fraction(4, 25)
def test_matrix():
m = iou_matrix([(0, 0, 2, 2), (0, 0, 10, 10)], [(1, 1, 3, 3), (5, 0, 15, 10)])
assert m[0][0] == Fraction(1, 7) and m[1][1] == Fraction(1, 3)
assert m[0][1] == 0
References
- Paul Jaccard, The distribution of the flora in the alpine zone, New Phytologist 11(2), 1912, 37-50, The coefficient of community: the number of species common to two areas as a fraction of the number of species in both
- Mark Everingham, Luc Van Gool, Christopher K. I. Williams, John Winn and Andrew Zisserman, The PASCAL Visual Object Classes (VOC) challenge, International Journal of Computer Vision 88(2), 2010, 303-338, Section 4.2, Bounding box evaluation, Eq. (3) (the overlap ratio must exceed 0.5, and why the threshold is low), and Section 4.2.1 (the segmentation measure, the same ratio on pixels)
- Sven Kosub, A note on the triangle inequality for the Jaccard distance, Pattern Recognition Letters 120, 2019, 36-38, The two proofs that 1 minus the Jaccard index is a metric on finite sets
- Hamid Rezatofighi, Nathan Tsoi, JunYoung Gwak, Amir Sadeghian, Ian Reid and Silvio Savarese, Generalized intersection over union: a metric and a loss for bounding box regression, CVPR 2019, 658-666, Section 3 (the definition of GIoU with the smallest enclosing box, its range and its properties)
- Richard Szeliski, Computer Vision, Algorithms and Applications, second edition, Springer, 2022, Section 6.3, Object detection (the overlap of a detection and a ground truth box)
Where this leads
- IoU-based anchor assignment
- Anchor boxes
- Bounding box regression
- Non-maximum suppression for detections
- ByteTrack
- CLEAR MOT metrics
- Mean average precision for detection
- DETR
- Higher order tracking accuracy
- Mean intersection over union
- Object detection
- Object proposal generation
- Panoptic segmentation
- SORT tracker
- Visual object tracking
- YOLO
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H2 full proof |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag 20CWE7 Edit this page History Report an error Markdown