0
0
Computer Visionml~5 mins

IoU (Intersection over Union) in Computer Vision

Choose your learning style9 modes available
Introduction
IoU helps us measure how much two shapes overlap. It tells us how well a predicted area matches the true area.
When checking how well a model detects objects in images.
When comparing predicted boxes with real boxes in object detection.
When deciding if two areas are similar enough to count as a match.
When evaluating segmentation masks in images.
When filtering overlapping predictions to keep the best one.
Syntax
Computer Vision
def iou(box1, box2):
    # box format: [x1, y1, x2, y2]
    x_left = max(box1[0], box2[0])
    y_top = max(box1[1], box2[1])
    x_right = min(box1[2], box2[2])
    y_bottom = min(box1[3], box2[3])

    if x_right <= x_left or y_bottom <= y_top:
        return 0.0

    intersection_area = (x_right - x_left) * (y_bottom - y_top)

    box1_area = (box1[2] - box1[0]) * (box1[3] - box1[1])
    box2_area = (box2[2] - box2[0]) * (box2[3] - box2[1])

    iou_value = intersection_area / float(box1_area + box2_area - intersection_area)
    return iou_value
Boxes are usually given as [x1, y1, x2, y2], where (x1, y1) is top-left and (x2, y2) is bottom-right corner.
IoU value ranges from 0 (no overlap) to 1 (perfect overlap).
Examples
Calculates IoU for two overlapping boxes.
Computer Vision
boxA = [1, 1, 4, 4]
boxB = [2, 2, 5, 5]
iou_score = iou(boxA, boxB)
print(f"IoU: {iou_score:.2f}")
Calculates IoU for two boxes that do not overlap, result should be 0.
Computer Vision
boxA = [0, 0, 2, 2]
boxB = [3, 3, 5, 5]
iou_score = iou(boxA, boxB)
print(f"IoU: {iou_score:.2f}")
Sample Model
This program defines a function to calculate IoU and tests it on two pairs of boxes: one overlapping and one non-overlapping.
Computer Vision
def iou(box1, box2):
    x_left = max(box1[0], box2[0])
    y_top = max(box1[1], box2[1])
    x_right = min(box1[2], box2[2])
    y_bottom = min(box1[3], box2[3])

    if x_right <= x_left or y_bottom <= y_top:
        return 0.0

    intersection_area = (x_right - x_left) * (y_bottom - y_top)

    box1_area = (box1[2] - box1[0]) * (box1[3] - box1[1])
    box2_area = (box2[2] - box2[0]) * (box2[3] - box2[1])

    iou_value = intersection_area / float(box1_area + box2_area - intersection_area)
    return iou_value

# Example boxes
box1 = [1, 1, 4, 4]
box2 = [2, 2, 5, 5]
box3 = [0, 0, 2, 2]
box4 = [3, 3, 5, 5]

print(f"IoU between box1 and box2: {iou(box1, box2):.2f}")
print(f"IoU between box3 and box4: {iou(box3, box4):.2f}")
OutputSuccess
Important Notes
IoU is a key metric in object detection tasks to check prediction quality.
If boxes do not overlap, IoU is zero, meaning no common area.
Higher IoU means better match between predicted and true boxes.
Summary
IoU measures overlap between two boxes or areas.
It is used to evaluate how well predictions match reality.
IoU values range from 0 (no overlap) to 1 (perfect overlap).