In this function, boxA
and boxB
are lists containing four integers representing the four coordinates of the bounding box: [start x, start y, end x, end y].
This function first calculates the intersection area of two bounding boxes, then calculates the area of each bounding box and the union area of the two bounding boxes, and finally divides the intersection area by the union area, and the result is IOU.
def bbox_intersection_over_union(boxA, boxB):
# 确定每个边界框的 (y, x) 的 (开始,结束) 坐标
xA = max(boxA[0], boxB[0])
yA = max(boxA[1], boxB[1])
xB = min(boxA[2], boxB[2])
yB = min(boxA[3], boxB[3])
# 计算交集的面积
interArea = max(0, xB - xA + 1) * max(0, yB - yA + 1)
# 计算每个边界框的面积
boxAArea = (boxA[2] - boxA[0] + 1) * (boxA[3] - boxA[1] + 1)
boxBArea = (boxB[2] - boxB[0] + 1) * (boxB[3] - boxB[1] + 1)
# 计算并集的面积
unionArea = boxAArea + boxBArea - interArea
# 计算交并比
iou = interArea / float(unionArea)
# 返回交并比
return iou
xA
is the larger of the upper-left x-coordinates of the two bounding boxes, representing the upper-left x-coordinate of the intersection.yA
is the larger value of the y-coordinates of the upper-left corners of the two bounding boxes, indicating the y-coordinates of the upper-left corner of the intersection.xB
is the smaller of the lower-right x-coordinates of the two bounding boxes, representing the lower-right x-coordinate of the intersection.yB
is the smaller value of the lower-right y-coordinates of the two bounding boxes, representing the lower-right y-coordinate of the intersection.These calculations are to find the coordinate extent of the intersection of two bounding boxes, which will be used to calculate the area of the intersection. If
xA
greater thanxB
oryA
greater thanyB
, it means that the two bounding boxes do not intersect, and the area of the intersection will be 0 at this time.