最近看了网上很多博主写的iou实现方法,但Giou的代码似乎比较少,于是便自己写了一个,新手上路,如有错误请指正,话不多说,上代码:
def Iou(rec1,rec2):
x1,x2,y1,y2 = rec1 #分别是第一个矩形左右上下的坐标
x3,x4,y3,y4 = rec2 #分别是第二个矩形左右上下的坐标
area_1 = (x2-x1)*(y1-y2)
area_2 = (x4-x3)*(y3-y4)
sum_area = area_1 + area_2
w1 = x2 - x1#第一个矩形的宽
w2 = x4 - x3#第二个矩形的宽
h1 = y1 - y2
h2 = y3 - y4
W = min(x1,x2,x3,x4)+w1+w2-max(x1,x2,x3,x4)#交叉部分的宽
H = min(y1,y2,y3,y4)+h1+h2-max(y1,y2,y3,y4)#交叉部分的高
Area = W*H#交叉的面积
Iou = Area/(sum_area-Area)
return Iou
def Giou(rec1,rec2):
x1,x2,y1,y2 = rec1 #分别是第一个矩形左右上下的坐标
x3,x4,y3,y4 = rec2
iou = Iou(rec1,rec2)
area_C = (max(x1,x2,x3,x4)-min(x1,x2,x3,x4))*(max(y1,y2,y3,y4)-min(y1,y2,y3,y4))
area_1 = (x2-x1)*(y1-y2)
area_2 = (x4-x3)*(y3-y4)
sum_area = area_1 + area_2
w1 = x2 - x1#第一个矩形的宽
w2 = x4 - x3#第二个矩形的宽
h1 = y1 - y2
h2 = y3 - y4
W = min(x1,x2,x3,x4)+w1+w2-max(x1,x2,x3,x4)#交叉部分的宽
H = min(y1,y2,y3,y4)+h1+h2-max(y1,y2,y3,y4)#交叉部分的高
Area = W*H#交叉的面积
add_area = sum_area - Area #两矩形并集的面积
end_area = (area_C - add_area)/area_C #(c/(AUB))/c的面积
giou = iou - end_area
return giou
rec1 = (27,47,130,90)
rec2 = (30,68,150,110)
iou = Iou(rec1,rec2)
giou = Giou(rec1,rec2)
print("Iou = {},Giou = {}".format(iou,giou))
关于giou的具体内容可以参考论文及网上一些大神的博客。