Algorithm Search⌘K

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 AA and BB of the plane with ∣A∪B∣>0|A \cup B| > 0, where ∣⋅∣|\cdot| is the area,

IoU(A,B)=∣A∩B∣∣A∪B∣=∣A∩B∣∣A∣+∣B∣−∣A∩B∣.\mathrm{IoU}(A, B) = \frac{|A \cap B|}{|A \cup B|} = \frac{|A \cap B|}{|A| + |B| - |A \cap B|}.

For two finite sets of pixels, ∣⋅∣|\cdot| is the number of pixels. When both regions are empty the ratio is 0/00/0, and a program must pick a value; this page uses 0, and a mask metric often uses 1.

On this page a box is a=(x1,y1,x2,y2)a = (x_1, y_1, x_2, y_2) with x1≤x2x_1 \le x_2 and y1≤y2y_1 \le y_2 in continuous image coordinates, the set [x1,x2]×[y1,y2][x_1, x_2] \times [y_1, y_2], so its area is (x2−x1)(y2−y1)(x_2 - x_1)(y_2 - y_1). 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:

  1. IOU(a, b)
  2. 1w ← min(a.x2, b.x2) - max(a.x1, b.x1)
  3. 2h ← min(a.y2, b.y2) - max(a.y1, b.y1)
  4. 3if w ≤ 0 or h ≤ 0 then I ← 0 else I ← w · h
  5. 4U ← area(a) + area(b) - I
  6. 5return 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: x1x_1 and x2x_2 are the indices of the first and the last pixel, both inclusive, so a side has x2−x1+1x_2 - x_1 + 1 pixels. This form is the continuous box (x1,y1,x2+1,y2+1)(x_1, y_1, x_2 + 1, y_2 + 1). Code that mixes the two forms gets a wrong value, and the error is large for small boxes.

The quantity d(A,B)=1−IoU(A,B)d(A, B) = 1 - \mathrm{IoU}(A, B) 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. IoU((0,0,2,2),(1,1,3,3))=1/7\mathrm{IoU}((0,0,2,2), (1,1,3,3)) = 1/7: the intersection is the unit square, and the union is 4+4−1=74 + 4 - 1 = 7. IoU((0,0,10,10),(5,0,15,10))=50/150=1/3\mathrm{IoU}((0,0,10,10), (5,0,15,10)) = 50 / 150 = 1/3: a box shifted by half its width.
  • A shift by a third. IoU((0,0,3,3),(1,0,4,3))=6/12=1/2\mathrm{IoU}((0,0,3,3), (1,0,4,3)) = 6 / 12 = 1/2. 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 (0,0,10,10)(0,0,10,10) gives 49/10049/100. 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, (0,0,2,2)(0,0,2,2) and (1,1,3,3)(1,1,3,3) have 9 pixels each and share 4, so the IoU is 4/14=2/74/14 = 2/7, twice the continuous value. (0,0,10,10)(0,0,10,10) and (5,0,15,10)(5,0,15,10) give 66/176=3/866 / 176 = 3/8 instead of 1/31/3.
  • Pixel masks. For two masks of an instance, the IoU counts pixels: 120 shared pixels out of 200 pixels covered by either mask give 0.60.6. 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 ∣A∩B∣/∣A∣|A \cap B| / |A| (the part of AA that BB covers) and ∣A∩B∣/min⁡(∣A∣,∣B∣)|A \cap B| / \min(|A|, |B|) are not IoU. For the box A=(2,2,6,6)A = (2,2,6,6) inside B=(0,0,10,10)B = (0,0,10,10) both are 1, while the IoU is 16/100=4/2516/100 = 4/25. 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 2∣A∩B∣/(∣A∣+∣B∣)2|A \cap B| / (|A| + |B|) is an increasing function of IoU, D=2J/(1+J)D = 2J / (1 + J), so it ranks pairs in the same order but gives other values: IoU 1/31/3 is Dice 1/21/2. A threshold on one is not the same number on the other.
  • Disjoint boxes. (0,0,1,1)(0,0,1,1) and (2,0,3,1)(2,0,3,1) have IoU 0, and so do (0,0,1,1)(0,0,1,1) and (5,0,6,1)(5,0,6,1). IoU does not say how far apart two disjoint boxes are, which is why a loss of 1−IoU1 - \mathrm{IoU} has no gradient for them. The generalized IoU of Rezatofighi et al. subtracts ∣C∖(A∪B)∣/∣C∣|C \setminus (A \cup B)| / |C|, where CC is the smallest box that holds both, and gives −1/3-1/3 and −2/3-2/3 for these two pairs.

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 O(m+n)O(m + n) for polygons of mm and nn vertices instead of O(1)O(1). The generalized IoU (GIoU) has values in (−1,1](-1, 1], is equal to IoU when one box holds the other, and 1−GIoU1 - \mathrm{GIoU} 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 a=(ax1,ay1,ax2,ay2)a = (a_{x1}, a_{y1}, a_{x2}, a_{y2}) with ax1≤ax2a_{x1} \le a_{x2} and ay1≤ay2a_{y1} \le a_{y2}, and it is the closed set [ax1,ax2]×[ay1,ay2][a_{x1}, a_{x2}] \times [a_{y1}, a_{y2}] of the plane. Its area is ∣a∣=(ax2−ax1)(ay2−ay1)|a| = (a_{x2} - a_{x1})(a_{y2} - a_{y1}). The procedure IOU of the page computes ww and hh in lines L1 and L2, II in line L3, UU in line L4 and returns I/UI / U in line L5.

Claim. If ∣a∪b∣>0|a \cup b| > 0, IOU returns ∣a∩b∣/∣a∪b∣|a \cap b| / |a \cup b|, where ∣⋅∣|\cdot| is the area (the Lebesgue measure of the set).

Lemma 1 (the intersection of two boxes). a∩b=[max⁡(ax1,bx1),min⁡(ax2,bx2)]×[max⁡(ay1,by1),min⁡(ay2,by2)]a \cap b = [\max(a_{x1}, b_{x1}), \min(a_{x2}, b_{x2})] \times [\max(a_{y1}, b_{y1}), \min(a_{y2}, b_{y2})], and this set is empty when one of the two intervals is empty.

Proof. A point (x,y)(x, y) is in a∩ba \cap b exactly when ax1≤x≤ax2a_{x1} \le x \le a_{x2}, bx1≤x≤bx2b_{x1} \le x \le b_{x2}, ay1≤y≤ay2a_{y1} \le y \le a_{y2} and by1≤y≤by2b_{y1} \le y \le b_{y2}. The two conditions on xx together say max⁡(ax1,bx1)≤x≤min⁡(ax2,bx2)\max(a_{x1}, b_{x1}) \le x \le \min(a_{x2}, b_{x2}), and the same holds for yy. A product of two intervals is empty exactly when one of them is empty. □\square

Lemma 2 (the area of the intersection). After line L3, I=∣a∩b∣I = |a \cap b|.

Proof. Lines L1 and L2 compute the lengths ww and hh of the two intervals of Lemma 1. If w>0w > 0 and h>0h > 0, the intersection is a box with sides ww and hh, so its area is whw h. If w≤0w \le 0 or h≤0h \le 0, 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. □\square

Lemma 3 (the area of the union). After line L4, U=∣a∪b∣U = |a \cup b|.

Proof. Area is additive on disjoint measurable sets, and a∪ba \cup b is the disjoint union of aa and b∖ab \setminus a. Also bb is the disjoint union of b∖ab \setminus a and a∩ba \cap b. So ∣a∪b∣=∣a∣+∣b∣−∣a∩b∣|a \cup b| = |a| + |b| - |a \cap b|, which is the value of line L4 by Lemma 2. □\square

Proof of the claim. By Lemmas 2 and 3, line L5 returns ∣a∩b∣/∣a∪b∣|a \cap b| / |a \cup b| when U>0U > 0. □\square

Corollary (range and symmetry). 0≤IoU(a,b)≤10 \le \mathrm{IoU}(a, b) \le 1 and IoU(a,b)=IoU(b,a)\mathrm{IoU}(a, b) = \mathrm{IoU}(b, a). If ∣a∣>0|a| > 0 and ∣b∣>0|b| > 0, then IoU(a,b)=1\mathrm{IoU}(a, b) = 1 exactly when a=ba = b.

Proof. a∩b⊆a∪ba \cap b \subseteq a \cup b gives the range, and the formulas of lines L1 to L4 do not change when aa and bb swap. If the value is 1, then ∣a∩b∣=∣a∪b∣|a \cap b| = |a \cup b|, so ∣a∣=∣a∩b∣=∣b∣|a| = |a \cap b| = |b|. The intersection is a box inside aa with the same positive area, and a box inside a box with the same area has the same sides, so a∩b=aa \cap b = a. In the same way a∩b=ba \cap b = b, so a=ba = b. □\square

Corollary (invariance). For a map ϕ(x,y)=(sx+tx,sy+ty)\phi(x, y) = (s x + t_x, s y + t_y) with s>0s > 0, IoU(ϕ(a),ϕ(b))=IoU(a,b)\mathrm{IoU}(\phi(a), \phi(b)) = \mathrm{IoU}(a, b).

Proof. ϕ\phi maps boxes to boxes, keeps the order of coordinates, and maps a∩ba \cap b to ϕ(a)∩ϕ(b)\phi(a) \cap \phi(b). It multiplies every area by s2s^2, so the ratio does not change. □\square

Corollary (pixel sets). For a box with integer corners, let P(a)P(a) be the set of unit cells [u,u+1)×[v,v+1)[u, u + 1) \times [v, v + 1) inside aa. Then ∣P(a)∣=∣a∣|P(a)| = |a|, P(a∩b)=P(a)∩P(b)P(a \cap b) = P(a) \cap P(b), and the box IoU equals ∣P(a)∩P(b)∣/∣P(a)∪P(b)∣|P(a) \cap P(b)| / |P(a) \cup P(b)|.

Proof. The cells inside aa are those with ax1≤u<ax2a_{x1} \le u < a_{x2} and ay1≤v<ay2a_{y1} \le v < a_{y2}, so there are (ax2−ax1)(ay2−ay1)(a_{x2} - a_{x1})(a_{y2} - a_{y1}) 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. □\square

The inclusive pixel form. The PASCAL VOC development kit stores the first and the last pixel of each side, so a side from index x1x_1 to index x2x_2 has x2−x1+1x_2 - x_1 + 1 pixels. This is the continuous box (x1,y1,x2+1,y2+1)(x_1, y_1, x_2 + 1, y_2 + 1), and the claim applies to that box. The two forms give different values on the same four numbers, for example 1/71/7 and 2/72/7 for (0,0,2,2)(0, 0, 2, 2) and (1,1,3,3)(1, 1, 3, 3).

The metric. The Jaccard distance 1−∣A∩B∣/∣A∪B∣1 - |A \cap B| / |A \cup B| satisfies the triangle inequality on finite sets (Kosub 2019 gives two short proofs). By the pixel-set corollary, 1−IoU1 - \mathrm{IoU} 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.

intersection_over_union.pyI0RawGitHub
# 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

  1. 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
  2. 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)
  3. 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
  4. 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)
  5. 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

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.

LadderLevelWhat the next level needs
Human proofH2 full proof
  • correctness: no review record reviews/20CWE7/proof-correctness.yaml
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/20CWE7/text.yaml