IOU

Created
TagsMetrics
def calculate_iou(boxA, boxB):
    """
    Calculate the Intersection over Union (IoU) of two bounding boxes.

    Parameters
    ----------
    boxA : list or tuple
        The bounding box in the format (x1, y1, x2, y2), where (x1, y1) is the top-left coordinate,
        and (x2, y2) is the bottom-right coordinate.
    boxB : list or tuple
        The bounding box in the format (x1, y1, x2, y2).

    Returns
    -------
    float
        The IoU of boxA and boxB.
    """
    # Determine the coordinates of the intersection rectangle
    xA = max(boxA[0], boxB[0])
    yA = max(boxA[1], boxB[1])
    xB = min(boxA[2], boxB[2])
    yB = min(boxA[3], boxB[3])

    # Compute the area of intersection
    intersection_area = max(0, xB - xA) * max(0, yB - yA)

    # Compute the area of both the prediction and ground-truth rectangles
    boxA_area = (boxA[2] - boxA[0]) * (boxA[3] - boxA[1])
    boxB_area = (boxB[2] - boxB[0]) * (boxB[3] - boxB[1])

    # Compute the intersection over union by taking the intersection
    # area and dividing it by the sum of prediction + ground-truth
    # areas - the interesection area
    iou = intersection_area / float(boxA_area + boxB_area - intersection_area)

    return iou