法一:
def compute_iou(rec1, rec2):
"""
computing IoU
:param rec1: (y0, x0, y1, x1), which reflects (bottom,left,top,right)
:param rec2: (y0, x0, y1, x1)
:return: value of IoU
"""
# computing area of each rectangles
S_rec1 = (rec1[2] - rec1[0]) * (rec1[3] - rec1[1])
S_rec2 = (rec2[2] - rec2[0]) * (rec2[3] - rec2[1])
# computing the sum_area
sum_area = S_rec1 + S_rec2
print(sum_area)
# find the each edge of intersect rectangle
left_line = max(rec1[1], rec2[1])
right_line = min(rec1[3], rec2[3])
bottom_line = max(rec1[0], rec2[0])
top_line = min(rec1[2], rec2[2])
print(left_line)
print(right_line)
print(bottom_line)
print(top_line)
# judge if there is an intersect
if left_line >= right_line or bottom_line >= top_line:
return 0
else:
intersect = (right_line - left_line) * (top_line - bottom_line)
print(intersect)
return ( intersect / (sum_area - intersect))
rect1 = [661, 23, 679, 57]
rect2 = [662, 27, 682, 47]
print(compute_iou(rect1, rect2))
法二:看两个矩形框的左上角和右下角坐标值,其实也异曲同工
IOU_W = min(x1, x2, x3, x4) + w1 + w2 - max(x1, x2, x3, x4)
IOU_H = min(y1, y2, y3, y4) + h1 + h2 - max(y1, y2, y3, y4)