计算机视觉:两个旋转检测框bbox的IoU计算
IoU简介
在目标检测中,经常会使用到IoU。IoU 的全称为交并比(Intersection over Union),IoU 计算方法的是 “预测的bbox” 和 “真实的bbox” 的交集和并集的比值。交并比IoU的取值范围为[0,1],IoU的值越大,说明两个bbox的重合度越高,预测的准确性越高;反之,若IoU的值越小,则说明两个bbox的重合度越低,预测的准确性越低。下面用一个图来形象化表示:
其中,area红色区域是两个检测框的交集,area1和area2蓝色区域加上area红色区域是两个检测框的并集。
python代码如下:
def compute_iou(bbox1, bbox2):
'''
bbox1: [x1, y1, x2, y2]
bbox2: [x1, y1, x2, y2]
'''
xx1, yy1 = max(bbox1[0], bbox2[0]), max(bbox1[1], bbox2[1])
xx2, yy2 = min(bbox1[2], bbox2[2]), min(bbox1[3], bbox2[3])
area1 = (bbox1[2] - bbox1[0]) * (bbox1[3] - bbox1[1])
area2 = (bbox2[2] - bbox2[0]) * (bbox2[3] - bbox2[1])
intersec = (xx2 - xx1) * (yy2 - yy1)
union = area1 + area2 - intersec
iou = intersec / union
return iou
两个旋转检测框bbox的IoU计算
当两个bbox带有旋转时,虽然原理相同,但计算要比上述的要复杂很多。
准备工作:安装opencv库
pip install opencv-python
下面直接上python代码:
import numpy as np
import cv2
# 中心点坐标、矩形的宽和高、旋转角(单位是角度,不是弧度)
def iou_rotate_calculate(box1, box2):
area1 = box1[2] * box1[3]
area2 = box2[2] * box2[3]
r1 = ((box1[0], box1[1]), (box1[2], box1[3]), box1[4])
r2 = ((box2[0], box2[1]), (box2[2], box2[3]), box2[4])
int_pts = cv2.rotatedRectangleIntersection(r1, r2)[1]
if int_pts is not None:
order_pts = cv2.convexHull(int_pts, returnPoints=True)
intersec = cv2.contourArea(order_pts)
union = area1 + area2 - intersec
iou = intersec * 1.0 / union
else:
iou = 0.0
return iou
box1 = [30, 40, 40, 80, 0]
box2 = [30, 40, 40, 80, 90]
iou = iou_rotate_calculate(box1,box2)
print(iou)