IOU,Intersection over Union,并交比,是目标检测中常见的评价标准。
主要是衡量模型生成的预测检测框(Predicted Bounding Box)和标注框(Ground Truth Box)之间的重叠程度。
假设预测检测框为A,标注框为B,则IOU计算公式为:
一维IOU计算示例:
两个线段之间的IOU
import numpy as np
def iou(set_a, set_b):
'''
一维 iou 的计算
:param set_a: 第一段的起始和终点坐标
:param set_b: 第二段的起始和终点坐标
:return:
'''
'''
'''
x1, x2 = set_a # (left, right)
y1, y2 = set_b # (left, right)
low = max(x1, y1)
high = min(x2, y2)
# intersection
if high - low < 0:
inter = 0
else:
inter = high - low
# union
union = (x2 - x1) + (y2 - y1) - inter
# iou
iou = inter / union
return iou
if __name__ == "__main__":
r = iou((1, 3), (2, 4))
print(r)
二维IOU计算示例:
两个图形之间的IOU
import numpy as np
def IOU(box1, box2, wh=False):
if wh == False:
xmin1, ymin1, xmax1, ymax1 = box1
xmin2, ymin2, xmax2, ymax2 = box2
else:
xmin1, ymin1 = int(box1[0] - box1[2] / 2.0), int(box1[1] - box1[3] / 2.0)
xmax1, ymax1 = int(box1[0] + box1[2] / 2.0), int(box1[1] + box1[3] / 2.0)
xmin2, ymin2 = int(box2[0] - box2[2] / 2.0), int(box2[1] - box2[3] / 2.0)
xmax2, ymax2 = int(box2[0] + box2[2] / 2.0), int(box2[1] + box2[3] / 2.0)
# 获取矩形框交集对应的左上角和右下角的坐标(intersection)
xx1 = np.max([xmin1, xmin2])
yy1 = np.max([ymin1, ymin2])
xx2 = np.min([xmax1, xmax2])
yy2 = np.min([ymax1, ymax2])
# 计算两个矩形框面积
area1 = (xmax1 - xmin1) * (ymax1 - ymin1)
area2 = (xmax2 - xmin2) * (ymax2 - ymin2)
inter_area = (np.max([0, xx2 - xx1])) * (np.max([0, yy2 - yy1])) # 计算交集面积
iou = inter_area / (area1 + area2 - inter_area + 1e-6) # 计算交并比
return iou
if __name__ == "__main__":
r = IOU([1, 1, 3, 3], [2, 2, 4, 4])
print(r)
参考:
-
IoU、GIoU、DIoU、CIoU损失函数的那点事儿 - Error的文章 - 知乎
https://zhuanlan.zhihu.com/p/94799295