Skip to content

BUG: box_iou_batch inefficient for 1-to-1 iou calculation #1873

@Ashp116

Description

@Ashp116

Search before asking

  • I have searched the Supervision issues and found no similar bug report.

Bug

The function box_iou_batch is inefficient when computing the IoU between just two individual bounding boxes. In such cases, it takes approximately twice as long as a simple one-to-one IoU function optimized for single-pair comparisons. Please review the link below for a benchmark that shows the performance difference. Although the time to compute a single IoU is minimal, the overhead becomes significant when running many iterations. In my setup, where I was constructing a DAG, using box_iou_batch nearly doubled the total computation time.

Environment

  • Supervision 0.25.0
  • Windows 11
  • Python 3.12.6

Minimal Reproducible Example

To reproduce this issue, run a benchmark between the box_iou_batch and the function below. Refer to this link to see my benchmarking results.

def box_iou(box1: np.ndarray, box2: np.ndarray) -> float:
    """
    Compute the Intersection over Union (IoU) between two bounding boxes.

    Args:
        box1 (np.ndarray): A bounding box represented as [x1, y1, x2, y2].
        box2 (np.ndarray): A bounding box represented as [x1, y1, x2, y2].

    Returns:
        float: The IoU value between box1 and box2.
               Ranges from 0.0 (no overlap) to 1.0 (perfect overlap).
    """
    inter_x1 = max(box1[0], box2[0])
    inter_y1 = max(box1[1], box2[1])
    inter_x2 = min(box1[2], box2[2])
    inter_y2 = min(box1[3], box2[3])

    inter_w = max(0, inter_x2 - inter_x1)
    inter_h = max(0, inter_y2 - inter_y1)

    inter_area = inter_w * inter_h

    area1 = (box1[2] - box1[0]) * (box1[3] - box1[1])
    area2 = (box2[2] - box2[0]) * (box2[3] - box2[1])

    union_area = area1 + area2 - inter_area

    return inter_area / union_area + 1e-6

Additional

I propose to have one function that does a non-vectorized single iou calculation

Are you willing to submit a PR?

  • Yes I'd like to help by submitting a PR!

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions