⽬标检测基本概念理解之IoU (交并⽐)以及Python 代码实现
⽬标检测基本概念理解之IoU (交并⽐)
交并⽐理解
在检测任务中,使⽤交并⽐(Interction of Union,IoU)作为衡量指标。这⼀概念来源于数学中的集合,⽤来描述两个集合A和B之间的关系,它等于两个集合的交集⾥⾯所包含的元素个数,除以它们的并集⾥⾯所包含的元素个数,具体计算公式如下:
我们将⽤这个概念来描述两个框之间的重合度。两个框可以看成是两个像素的集合,它们的交并⽐等于两个框重合部分的⾯积除以它们合并起来的⾯积。下图“交集”中青⾊区域是两个框的重合⾯积,图“并集”中蓝⾊区域是两个框的相并⾯积。⽤这两个⾯积相除即可得到它们
之间的交并⽐,如图所⽰。
the top
假设两个矩形框A和B的位置分别为:
假如位置关系如 图 所⽰:
rock you是什么意思
如果⼆者有相交部分,则相交部分左上⾓坐标为:
相交部分右下⾓坐标为:
计算先交部分⾯积:
矩形框A和B的⾯积分别是:
计算相并部分⾯积:
IoU =A ∪B
最好的英语培训机构A ∩B
A :[x ,y ,x ,y ]
a 1a 1a 2a 2A :[x ,y ,x ,y ]
b 1b 1b 2b 2x =1max (x ,x ),y 1=a 1b 1max (y ,y )
伟大辩手
a 1
b 1x =2min (x ,x ),y 2=a 2b 2min (y ,y )
a 2
b 2intertion =max (x −2x +1 1.0)∗(y −2y +1 1.0)
S =A (x −a 2x +a 1 1.0)∗(y −a 2y +a 1 1.0)
S =B (x −b 2x +b 1 1.0)∗(y −b 2y +b 1 1.0)
union =S +A S −B intertion
计算交并⽐:
intertion
IoU=union
为了直观的展⽰交并⽐的⼤⼩跟重合程度之间的关系,⽰意了不同交并⽐下两个框之间的相对位置关系,从 IoU = 0.95 到 IoU = 0.
Python代码实现
计算IoU,矩形框的坐标形式为xyxy
# 计算IoU,矩形框的坐标形式为xyxy
# (x1,y1)是矩形框左上⾓的坐标,(x2,y2)是矩形框右下⾓的坐标
def box_iou_xyxy(box1, box2):
# 获取box1左上⾓和右下⾓的坐标
x1min, y1min, x1max, y1max = box1[0], box1[1], box1[2], box1[3]
# 计算box1的⾯积
s1 =(y1max - y1min +1.)*(x1max - x1min +1.)
# 获取box2左上⾓和右下⾓的坐标
x2min, y2min, x2max, y2max = box2[0], box2[1], box2[2], box2[3]
# 计算box2的⾯积
s2 =(y2max - y2min +1.)*(x2max - x2min +1.)
# 计算相交矩形框的坐标
初级日语xmin = np.maximum(x1min, x2min)# 左上⾓的横坐标
prtsymin = np.maximum(y1min, y2min)# 左上⾓的纵坐标
xmax = np.minimum(x1max, x2max)# 右下⾓的横坐标
ymax = np.minimum(y1max, y2max)# 右下⾓的纵坐标
# 计算相交矩形的⾼度、宽度、⾯积
inter_h = np.maximum(ymax - ymin +1.,0.)
inter_w = np.maximum(xmax - xmin +1.,0.)
interction = inter_h * inter_w
# 计算相并⾯积
myqqunion = s1 + s2 - interction
# 计算交并⽐
iou = interction / union
return iou
bbox1 =[100.,100.,200.,200.]
bbox2 =[120.,120.,220.,220.]
iou = box_iou_xyxy(bbox1, bbox2)
print('IoU is {}'.format(iou))
IoU is 0.47402644317607107
计算IoU,矩形框的坐标形式为xywh
# 计算IoU,矩形框的坐标形式为xywh
# (x,y)(x, y)(x,y)是矩形框中⼼点的坐标,www是矩形框的宽度,hhh是矩形框的⾼度。def box_iou_xywh(box1, box2):
# 获取box1左上⾓的坐标
x1min, y1min = box1[0]- box1[2]/2.0, box1[1]- box1[3]/2.0
# 获取box1右下⾓的坐标
x1max, y1max = box1[0]+ box1[2]/2.0, box1[1]+ box1[3]/2.0
# 获取box1的⾯积
s1 = box1[2]* box1[3]
# 获取box2左上⾓的坐标
x2min, y2min = box2[0]- box2[2]/2.0, box2[0]- box2[2]/2.0
# 获取box2右下⾓的坐标
x2max, y2max = box2[0]+ box2[2]/2.0, box2[0]+ box2[2]/2.0
# 获取box2的⾯积
s2 = box2[2]* box2[3]
# 计算相交矩形框的坐标
xmin = np.maximum(x1min, x2min)# 左上⾓的横坐标
ymin = np.maximum(y1min, y2min)# 左上⾓的纵坐标
xmax = np.minimum(x1max, x2max)# 右下⾓的横坐标
bill kaulitzymax = np.minimum(y1max, y2max)# 右下⾓的纵坐标
inter_h = np.maximum(ymax - ymin,0.)
inter_w = np.maximum(xmax - xmin,0.)
obama speechinterction = inter_h * inter_w
union = s1 + s2 - interction
iou = interction / union
damage
return iou
bbox1 =[100.,100.,200.,200.]
bbox2 =[120.,120.,220.,220.]
iou = box_iou_xywh(bbox1, bbox2)
print('IoU is {}'.format(iou))
IoU is 0.6902485659655831