From 2378d8bdca83aa3877f8967aaba6a17bff016a03 Mon Sep 17 00:00:00 2001 From: Ashp116 Date: Sat, 12 Jul 2025 14:50:43 -0400 Subject: [PATCH] UPDATE: Code review fix and docs updated --- docs/detection/utils.md | 6 ++++++ supervision/detection/utils.py | 31 ++++++++++++++++++++----------- 2 files changed, 26 insertions(+), 11 deletions(-) diff --git a/docs/detection/utils.md b/docs/detection/utils.md index 323b2954..95b3d5b7 100644 --- a/docs/detection/utils.md +++ b/docs/detection/utils.md @@ -5,6 +5,12 @@ status: new # Detection Utils +
+

box_iou

+
+ +:::supervision.detection.utils.box_iou +

box_iou_batch

diff --git a/supervision/detection/utils.py b/supervision/detection/utils.py index a9ee8225..09e4a87a 100644 --- a/supervision/detection/utils.py +++ b/supervision/detection/utils.py @@ -48,32 +48,41 @@ def polygon_to_mask(polygon: np.ndarray, resolution_wh: Tuple[int, int]) -> np.n return mask -def box_iou(box1: np.ndarray, box2: np.ndarray) -> float: +def box_iou(box_true: Union[List[float], np.ndarray], box_detection: Union[List[float], np.ndarray]) -> float: """ Compute the Intersection over Union (IoU) between two bounding boxes. + Both `box_true` and `box_detection` should be in (x_min, y_min, x_max, y_max) format. + + Note: + Use `box_iou` when computing IoU between two individual boxes. + For comparing multiple boxes (arrays of boxes), use `box_iou_batch` for better performance. + 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]. + box_true (Union[List[float], np.ndarray]): A single bounding box represented as [x_min, y_min, x_max, y_max]. + box_detection (Union[List[float], np.ndarray]): A single bounding box represented as [x_min, y_min, x_max, y_max]. Returns: - float: The IoU value between box1 and box2. + float: The IoU value between the two boxes. 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]) + box_true = np.array(box_true) + box_detection = np.array(box_detection) + + inter_x1 = max(box_true[0], box_detection[0]) + inter_y1 = max(box_true[1], box_detection[1]) + inter_x2 = min(box_true[2], box_detection[2]) + inter_y2 = min(box_true[3], box_detection[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]) + area_true = (box_true[2] - box_true[0]) * (box_true[3] - box_true[1]) + area_detection = (box_detection[2] - box_detection[0]) * (box_detection[3] - box_detection[1]) - union_area = area1 + area2 - inter_area + union_area = area_true + area_detection - inter_area return inter_area / union_area + 1e-6