IoU(交并比)的理解及python实现

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=ABAB

A、B的坐标如下图:

img

交集的左上角坐标为:
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(x2x1,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(y2y1,0)

S A ∩ B = w i d t h ∗ h e i g h t S_{A \cap B} = width * height SAB=widthheight

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=(xa2xa1)(ya2ya1)
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=(xb2xb1)(yb2yb1)
并集部分:
S A ∪ B = S A + S B − S A ∩ B S_{A \cup B} = S_{A} + S_{B} - S_{A \cap B} SAB=SA+SBSAB
交并比为:

I o U = S A ∩ B S A ∪ B IoU = \frac{S_{A \cap B}}{S_{A \cup B}} IoU=SABSAB
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))
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值