计算交并比代码
时间: 2023-08-04 17:06:36 浏览: 49
以下是计算交并比(IoU)的 Python 代码:
```python
def iou(box1, box2):
"""
Calculate Intersection over Union (IoU) between two bounding boxes.
Args:
box1: tuple or list, (x1, y1, x2, y2)
box2: tuple or list, (x1, y1, x2, y2)
Returns:
iou: float, between 0.0 and 1.0
"""
x1 = max(box1[0], box2[0])
y1 = max(box1[1], box2[1])
x2 = min(box1[2], box2[2])
y2 = min(box1[3], box2[3])
if x1 >= x2 or y1 >= y2:
return 0.0
intersection_area = (x2 - x1) * (y2 - y1)
box1_area = (box1[2] - box1[0]) * (box1[3] - box1[1])
box2_area = (box2[2] - box2[0]) * (box2[3] - box2[1])
union_area = box1_area + box2_area - intersection_area
iou = intersection_area / union_area
return iou
```
使用方法:
```python
box1 = (30, 20, 80, 70)
box2 = (50, 40, 100, 90)
iou_score = iou(box1, box2)
print("IoU score:", iou_score)
```
输出结果:
```
IoU score: 0.14285714285714285
```