1. def bbox_iou(box1, box2, x1y1x2y2=True):
    2. # Returns the IoU of box1 to box2. box1 is 4, box2 is nx4
    3. # Get the coordinates of bounding boxes
    4. if x1y1x2y2: # x1, y1, x2, y2 = box1
    5. b1_x1, b1_y1, b1_x2, b1_y2 = box1[0], box1[1], box1[2], box1[3]
    6. b2_x1, b2_y1, b2_x2, b2_y2 = box2[0], box2[1], box2[2], box2[3]
    7. else: # x, y, w, h = box1
    8. b1_x1, b1_x2 = box1[0] - box1[2] / 2, box1[0] + box1[2] / 2
    9. b1_y1, b1_y2 = box1[1] - box1[3] / 2, box1[1] + box1[3] / 2
    10. b2_x1, b2_x2 = box2[0] - box2[2] / 2, box2[0] + box2[2] / 2
    11. b2_y1, b2_y2 = box2[1] - box2[3] / 2, box2[1] + box2[3] / 2
    12. # Intersection area
    13. inter = (min(b1_x2, b2_x2) - max(b1_x1, b2_x1)) * \
    14. (min(b1_y2, b2_y2) - max(b1_y1, b2_y1))
    15. # Union Area
    16. w1, h1 = b1_x2 - b1_x1, b1_y2 - b1_y1
    17. w2, h2 = b2_x2 - b2_x1, b2_y2 - b2_y1
    18. union = (w1 * h1 + 1e-16) + w2 * h2 - inter
    19. iou = inter / union # iou
    20. return iou