【IOU系列】分析+代码

文章目录

1 IOU

所需要的数据:
并集:两个矩形面积和—交集
交集:

两个矩形可能出现的情况
在这里插入图片描述

代码:

x_a=max(x1,x1_)
                y_a=max(y1,y1_)
                x_b=min(x2,x2_)
                y_b=min(y2,y2_)
                if x_b-x_a<=0 or y_b-y_a<=0:
                    iou_ratio=0 #即不交的情况
                else:
                    iou_area = (x_b - x_a) * (y_b - y_a)
                    area = w * h
                    area_=w_*h_
                    iou_ratio=iou_area/(area+area_-iou_area)

2 DIOU

根据参数列表中的diou=False确定返回的值为iou还是diou

def bbox_iou(box1, box2, x1y1x2y2=True, diou=False):
    """
    Returns the IoU of two bounding boxes
    """
    if not x1y1x2y2:
        # Transform from center and width to exact coordinates
        b1_x1, b1_x2 = box1[:, 0] - box1[:, 2] / 2, box1[:, 0] + box1[:, 2] / 2
        b1_y1, b1_y2 = box1[:, 1] - box1[:, 3] / 2, box1[:, 1] + box1[:, 3] / 2
        b2_x1, b2_x2 = box2[:, 0] - box2[:, 2] / 2, box2[:, 0] + box2[:, 2] / 2
        b2_y1, b2_y2 = box2[:, 1] - box2[:, 3] / 2, box2[:, 1] + box2[:, 3] / 2
    else:
        # Get the coordinates of bounding boxes
        b1_x1, b1_y1, b1_x2, b1_y2 = box1[:, 0], box1[:, 1], box1[:, 2], box1[:, 3]
        b2_x1, b2_y1, b2_x2, b2_y2 = box2[:, 0], box2[:, 1], box2[:, 2], box2[:, 3]

    # get the corrdinates of the intersection rectangle
    inter_rect_x1 = torch.max(b1_x1, b2_x1)
    inter_rect_y1 = torch.max(b1_y1, b2_y1)
    inter_rect_x2 = torch.min(b1_x2, b2_x2)
    inter_rect_y2 = torch.min(b1_y2, b2_y2)
    # Intersection area
    inter_area = torch.clamp(inter_rect_x2 - inter_rect_x1 + 1, min=0) * torch.clamp(
        inter_rect_y2 - inter_rect_y1 + 1, min=0
    )
    # Union Area
    b1_area = (b1_x2 - b1_x1 + 1) * (b1_y2 - b1_y1 + 1)
    b2_area = (b2_x2 - b2_x1 + 1) * (b2_y2 - b2_y1 + 1)
    if diou:
        union = b1_area + b2_area - inter_area

        # compute enclose area
        enclose_l = torch.min(b1_x1, b2_x1)
        enclose_t = torch.min(b1_y1, b2_y1)
        enclose_r = torch.max(b1_x2, b2_x2)
        enclose_b = torch.max(b1_y2, b2_y2)
        enclose_w = enclose_r - enclose_l
        enclose_h = enclose_b - enclose_t
        enclose_diag = torch.pow(enclose_w, 2) + torch.pow(enclose_h, 2)

        # compute center diag
        center_b1_cx = (b1_x1 + b1_x2) / 2
        center_b1_cy = (b1_y1 + b1_y2) / 2
        center_b2_cx = (b2_x1 + b2_x2) / 2
        center_b2_cy = (b2_y1 + b2_y2) / 2
        center_diag = torch.pow(center_b1_cx - center_b2_cx, 2) + torch.pow(center_b1_cy - center_b2_cy, 2)

        diou = torch.clamp(inter_area / union - center_diag / enclose_diag, min=-1., max=1.)
        return diou

    else:
        iou = inter_area / (b1_area + b2_area - inter_area + 1e-16)
        return iou

猜你喜欢

转载自blog.csdn.net/qq_43586192/article/details/111867324
IOU
今日推荐