import torch


def iou_overlaps(b1, b2):
        """
        Arguments:
            b1: dts, [n, >=4] (x1, y1, x2, y2, ...)
            b1: gts, [n, >=4] (x1, y1, x2, y2, ...)

        Returns:
            intersection-over-union pair-wise, generalized iou.
        """
        area1 = (b1[:, 2] - b1[:, 0] + 1) * (b1[:, 3] - b1[:, 1] + 1)
        area2 = (b2[:, 2] - b2[:, 0] + 1) * (b2[:, 3] - b2[:, 1] + 1)
        # only for giou loss
        lt1 = torch.max(b1[:, :2], b2[:, :2])
        rb1 = torch.max(b1[:, 2:4], b2[:, 2:4])
        lt2 = torch.min(b1[:, :2], b2[:, :2])
        rb2 = torch.min(b1[:, 2:4], b2[:, 2:4])
        wh1 = (rb2 - lt1 + 1).clamp(min=0)
        wh2 = (rb1 - lt2 + 1).clamp(min=0)
        inter_area = wh1[:, 0] * wh1[:, 1]
        union_area = area1 + area2 - inter_area
        iou = inter_area / torch.clamp(union_area, min=1)
        ac_union = wh2[:, 0] * wh2[:, 1] + 1e-7
        giou = iou - (ac_union - union_area) / ac_union
        return iou, giou