IOU计算代码

    技术2025-01-18  15

    import numpy as np def compute_iou(box1, box2, standard_coordinates=True): ''' :param box1: [Xmin, Ymin, Xmax, Ymax] or [Xcenter, Ycenter, W, H] :param box2: :param standard_coordinates: True [Xmin, Ymin, Xmax, Ymax] Fasle [Xcenter, Ycenter, W, H] :return: ''' # 传进来的是标准坐标 if standard_coordinates is True: Xmin1, Ymin1, Xmax1, Ymax1 = box1 Xmin2, Ymin2, Xmax2, Ymax2 = box2 # 传进来的是中心坐标 else: Xcenter1, Ycenter1, W1, H1 = box1 Xcenter2, Ycenter2, W2, H2 = box2 Xmin1, Ymin1 = int(Xcenter1 - W1 / 2), int(Ycenter1 - H1 / 2) Xmax1, Ymax1 = int(Xcenter1 + W1 / 2), int(Ycenter1 + H1 / 2) Xmin2, Ymin2 = int(Xcenter2 - W2 / 2), int(Ycenter2 - H2 / 2) Xmax2, Ymax2 = int(Xcenter2 + W2 / 2), int(Ycenter2 + H2 / 2) # 获得相交区域的左上角坐标和右下角坐标 min = max(min) max = min(max) inter_Xmin = max(Xmin1, Xmin2) inter_Ymin = max(Ymin1, Ymin2) inter_Xmax = min(Xmax1, Xmax2) inter_Ymax = min(Ymax1, Ymax2) # 以免不相交 W = max(0, inter_Xmax - inter_Xmin) H = max(0, inter_Ymax - inter_Ymin) # 计算相交区域面积 inter_area = W * H # 计算并集面积 merge_area = (Xmax1 - Xmin1) * (Ymax1 - Ymin1) + (Xmax2 - Xmin2) * (Ymax2 - Ymin2) # 计算IOU IOU = inter_area / (merge_area - inter_area + 1e-6) return IOU iou = compute_iou([0, 0, 2, 2], [1, 1, 3, 3]) print(iou)

     

    Processed: 0.009, SQL: 9