import torch


def compute_IoU(boxes1, boxes2):
    """
    计算IOU
    参数：
        boxes1: gt (n,4)
        boxes2: pred (n,4)
    返回：
        （n,）
    """
    xA = torch.max(boxes1[:, 0], boxes2[:, 0]) #(N,)
    yA = torch.max(boxes1[:, 1], boxes2[:, 1]) #(N,)
    xB = torch.min(boxes1[:, 2], boxes2[:, 2]) #(N,)
    yB = torch.min(boxes1[:, 3], boxes2[:, 3]) #(N,)
    interArea = (xB - xA + 1) * (yB - yA + 1)
    # 无交集，设为0
    interArea[xA > xB] = 0 

    boxAArea = (boxes1[:,2] - boxes1[:,0] + 1) * (boxes1[:,3] - boxes1[:,1] + 1)
    boxBArea = (boxes2[:,2] - boxes2[:,0] + 1) * (boxes2[:,3] - boxes2[:,1] + 1)
    iou = interArea / (boxAArea + boxBArea - interArea)
    # print(boxes1, boxes2,iou)
    return iou