1. 概述
交并比(Intersection over Union, IoU)是目标检测、语义分割、追踪等任务最常用的评估指标。交并比,顾名思义是两区域交集与并集的比值,当两区域完全重叠时交并比最大,为1;当两区域完全不重叠时交并比最小,为0。
2. IoU计算公式
要计算候选框(candidate bound) A与真实框(ground truth bound) B的交并比。
B1框与B2框的IoU计算公式为:
I
o
U
=
∣
A
∩
B
∣
∣
A
∪
B
∣
IoU = \frac{\mid A\cap B\mid}{\mid A\cup B\mid}
IoU=∣A∪B∣∣A∩B∣
A、B的坐标如下图:
交集的左上角坐标为:
x
1
=
m
a
x
(
x
a
1
,
x
b
1
)
x_{1} = max\big(x_{a1}, x_{b1})
x1=max(xa1,xb1)
y 1 = m a x ( y a 1 , y b 1 ) y_{1} = max\big(y_{a1}, y_{b1}) y1=max(ya1,yb1)
交集的右下角坐标为:
x
2
=
m
i
n
(
x
a
2
,
x
b
2
)
x_{2} = min\big(x_{a2}, x_{b2})
x2=min(xa2,xb2)
y 2 = m i n ( y a 2 , y b 2 ) y_{2} = min\big(y_{a2}, y_{b2}) y2=min(ya2,yb2)
交集部分的宽、高、面积:
w
i
d
t
h
=
m
a
x
(
x
2
−
x
1
,
0
)
width = max\big(x_{2}-x_{1}, 0)
width=max(x2−x1,0)
h e i g h t = m a x ( y 2 − y 1 , 0 ) height = max\big(y_{2}-y_{1}, 0) height=max(y2−y1,0)
S A ∩ B = w i d t h ∗ h e i g h t S_{A \cap B} = width * height SA∩B=width∗height
A框的面积:
S
A
=
(
x
a
2
−
x
a
1
)
⋅
(
y
a
2
−
y
a
1
)
S_{A} = \big(x_{a2}-x_{a1})\cdot\big(y_{a2}-y_{a1})
SA=(xa2−xa1)⋅(ya2−ya1)
B框的面积:
S
B
=
(
x
b
2
−
x
b
1
)
⋅
(
y
b
2
−
y
b
1
)
S_{B} = \big(x_{b2}-x_{b1})\cdot\big(y_{b2}-y_{b1})
SB=(xb2−xb1)⋅(yb2−yb1)
并集部分:
S
A
∪
B
=
S
A
+
S
B
−
S
A
∩
B
S_{A \cup B} = S_{A} + S_{B} - S_{A \cap B}
SA∪B=SA+SB−SA∩B
交并比为:
I
o
U
=
S
A
∩
B
S
A
∪
B
IoU = \frac{S_{A \cap B}}{S_{A \cup B}}
IoU=SA∪BSA∩B
3. IoU公式的python实现
def IoU(box1, box2) -> float:
"""
IOU, Intersection over Union
:param box1: list, 第一个框的两个坐标点位置 box1[x1, y1, x2, y2]
:param box2: list, 第二个框的两个坐标点位置 box2[x1, y1, x2, y2]
:return: float, 交并比
"""
weight = max(min(box1[2], box2[2]) - max(box1[0], box2[0]), 0)
height = max(min(box1[3], box2[3]) - max(box1[1], box2[1]), 0)
s_inter = weight * height
s_box1 = (box1[2] - box1[0]) * (box1[3] - box1[1])
s_box2 = (box2[2] - box2[0]) * (box2[3] - box2[1])
s_union = s_box1 + s_box2 - s_inter
return s_inter / s_union
if __name__ == '__main__':
box1 = [0, 0, 50, 50]
box2 = [0, 0, 100, 100]
print('IoU is %f' % IoU(box1, box2))