gpt-3.5-turbo-0301· openai
Suzhen/CodeChat
Having two bounding boxes compute in python intersection over union
- User
Having two bounding boxes compute in python intersection over union
- Assistant
To compute the intersection over union (IoU) of two bounding boxes in Python, you can use the following code:
def compute_iou(box1, box2): """ Computes the Intersection over Union (IoU) of two bounding boxes. Arguments: box1 -- tuple/list of 4 elements (x1, y1, x2, y2) representing the coordinates of the top-left and bottom-right corners of the first bounding box. box2 -- tuple/list of 4 elements (x1, y1, x2, y2) representing the coordinates of the top-left and bottom-right corners of the second bounding box. Returns: iou -- float value representing the IoU of the two bounding boxes. """ # Compute the area of the two bounding boxes. box1_area = (box1[2] - box1[0] + 1) * (box1[3] - box1[1] + 1) box2_area = (box2[2] - box2[0] + 1) * (box2[3] - box2[1] + 1) # Compute the coordinates of the intersection rectangle. x1 = max(box1[0], box2[0]) y1 = max(box1[1], box2[1]) x2 = min(box1[2], box2[2]) y2 = min(box1[3], box2[3]) # Compute the area of the intersection rectangle. if x2 < x1 or y2 < y1: intersection_area = 0 else: intersection_area = (x2 - x1 + 1) * (y2 - y1 + 1) # Compute the IoU value. iou = intersection_area / float(box1_area + box2_area - intersection_area) return iou