diff --git a/supervision/detection/utils.py b/supervision/detection/utils.py index ec50200d..e10e7489 100644 --- a/supervision/detection/utils.py +++ b/supervision/detection/utils.py @@ -122,3 +122,18 @@ def xywh_to_xyxy(boxes_xywh: np.ndarray) -> np.ndarray: xyxy[:, 2] = boxes_xywh[:, 0] + boxes_xywh[:, 2] xyxy[:, 3] = boxes_xywh[:, 1] + boxes_xywh[:, 3] return xyxy + + +def mask_to_xyxy(masks: np.ndarray) -> np.ndarray: + n = masks.shape[0] + bboxes = np.zeros((n, 4), dtype=int) + + for i, mask in enumerate(masks): + rows, cols = np.where(mask) + + if len(rows) > 0 and len(cols) > 0: + x_min, x_max = np.min(cols), np.max(cols) + y_min, y_max = np.min(rows), np.max(rows) + bboxes[i, :] = [x_min, y_min, x_max, y_max] + + return bboxes