Recently read a lot of bloggers on the Internet to write the iou implementation method, but Giou's code seems to be relatively small, so they wrote a new hand, if there is any error, please correct me, words do not say, on the code:
def Iou(rec1,rec2): x1,x2,y1,y2 = rec1 # are the coordinates of the first rectangle's left, right, top, and bottom. x3,x4,y3,y4 = rec2 # are the coordinates of the second rectangle's left, right, top and bottom, respectively area_1 = (x2-x1)*(y1-y2) area_2 = (x4-x3)*(y3-y4) sum_area = area_1 + area_2 w1 = x2 - x1# The width of the first rectangle w2 = x4 - x3# The width of the second rectangle h1 = y1 - y2 h2 = y3 - y4 W = min(x1,x2,x3,x4)+w1+w2-max(x1,x2,x3,x4)# Width of cross section H = min(y1,y2,y3,y4)+h1+h2-max(y1,y2,y3,y4)# Cross section high Area = W*H# Area of intersection Iou = Area/(sum_area-Area) return Iou def Giou(rec1,rec2): x1,x2,y1,y2 = rec1 # are the coordinates of the first rectangle's left, right, top, and bottom. 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# The width of the first rectangle w2 = x4 - x3# The width of the second rectangle h1 = y1 - y2 h2 = y3 - y4 W = min(x1,x2,x3,x4)+w1+w2-max(x1,x2,x3,x4)# Width of cross section H = min(y1,y2,y3,y4)+h1+h2-max(y1,y2,y3,y4)# Cross section high Area = W*H# Area of intersection add_area = sum_area - Area # Area of the concatenation of two rectangles end_area = (area_C - add_area)/area_C # Area of (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))
This python implementation of Iou and Giou code above is all I have shared with you.