Skip to content
Search

Jaccard index

lastmod 2023-08-10created 2017-03-1422 edits

Intersection over Union

Iou_stop_sign.png

An example of detecting a stop sign in an image. The predicted bounding box is drawn in red and the ground-truth bounding box is drawn in green. Our goal is to compute the Intersection over Union between these bounding boxes.

Iou_equation.png

Computing Intersection over Union is as simple as dividing the area of overlap between the bounding boxes by the area of their union.

Iou_examples.png

Examples of computing Intersection over Union for various bounding boxes.

Mean Intersection over Union

Think of the "m" in mIoU as Mean. Compute the IoU of every class and then take the average.

Weighted Intersection over Union

See the corresponding page.

Python example

def bb_intersection_over_union(boxA, boxB):
    # determine the (x, y)-coordinates of the intersection rectangle
    xA = max(boxA[0], boxB[0])
    yA = max(boxA[1], boxB[1])
    xB = min(boxA[2], boxB[2])
    yB = min(boxA[3], boxB[3])

    # compute the area of intersection rectangle
    interArea = max(0, xB - xA + 1) * max(0, yB - yA + 1)

    # compute the area of both the prediction and ground-truth
    # rectangles
    boxAArea = (boxA[2] - boxA[0] + 1) * (boxA[3] - boxA[1] + 1)
    boxBArea = (boxB[2] - boxB[0] + 1) * (boxB[3] - boxB[1] + 1)

    # compute the intersection over union by taking the intersection
    # area and dividing it by the sum of prediction + ground-truth
    # areas - the interesection area
    iou = interArea / float(boxAArea + boxBArea - interArea)

    # return the intersection over union value
    return iou

Latest (2023-08-10) version

# -*- coding: utf-8 -*-

from typing import Tuple, Union

NumberType = Union[int, float]
RectType = Tuple[NumberType, NumberType, NumberType, NumberType]


def calculate_iou(rect1: RectType, rect2: RectType) -> float:
    lx1, ly1, lx2, ly2 = rect1
    rx1, ry1, rx2, ry2 = rect2

    # Calculate the coordinates of the intersection rectangle
    left = max(lx1, rx1)
    top = max(ly1, ry1)
    right = min(lx2, rx2)
    bottom = min(ly2, ry2)

    # If the rectangles do not intersect, return 0
    if right <= left or bottom <= top:
        return 0.0

    # Calculate the area of intersection
    intersection_area = (right - left) * (bottom - top)

    # Calculate the area of each rectangle
    area1 = (lx2 - lx1) * (ly2 - ly1)
    area2 = (rx2 - rx1) * (ry2 - ry1)

    # Calculate the union area
    union_area = area1 + area2 - intersection_area

    # Calculate IoU
    return intersection_area / union_area

See also

Favorite site

References


  1. Vision-segmentation-miou_-_gaussian37.pdf ↩

author Zer0 sitemap