import torch


def iou_multiple_to_one(bboxes1, bbox2, center=False, zero_center=False):
    """Calculate the IOUs between bboxes1 (multiple) and bbox2 (one).

    Args:
        bboxes1: (Tensor) A n-D tensor representing first group of bboxes.
            The dimension is (..., 4).
            The last dimension represent the bbox, with coordinate (x, y, w, h)
            or (cx, cy, w, h).
        bbox2: (Tensor) A 1D tensor representing the second bbox.
            The dimension is (4,).
        center: (bool). Whether the bboxes are in format (cx, cy, w, h).
        zero_center: (bool). Whether to align two bboxes so their center
            is aligned.

    Returns:
        iou_: (Tensor) A (n-1)-D tensor representing the IOUs.
            It has one less dim than bboxes1
    """

    epsilon = 1e-6

    x1 = bboxes1[..., 0]
    y1 = bboxes1[..., 1]
    w1 = bboxes1[..., 2]
    h1 = bboxes1[..., 3]

    x2 = bbox2[0]
    y2 = bbox2[1]
    w2 = bbox2[2]
    h2 = bbox2[3]

    area1 = w1 * h1
    area2 = w2 * h2

    if zero_center:
        w_intersect = torch.min(w1, w2).clamp(min=0)
        h_intersect = torch.min(h1, h2).clamp(min=0)
    else:
        if center:
            x1 = x1 - w1 / 2
            y1 = y1 - h1 / 2
            x2 = x2 - w2 / 2
            y2 = y2 - h2 / 2
        right1 = (x1 + w1)
        right2 = (x2 + w2)
        top1 = (y1 + h1)
        top2 = (y2 + h2)
        left1 = x1
        left2 = x2
        bottom1 = y1
        bottom2 = y2
        w_intersect = (torch.min(right1, right2) -
                       torch.max(left1, left2)).clamp(min=0)
        h_intersect = (torch.min(top1, top2) -
                       torch.max(bottom1, bottom2)).clamp(min=0)
    area_intersect = h_intersect * w_intersect

    iou_ = area_intersect / (area1 + area2 - area_intersect + epsilon)

    return iou_