yolov8改进-添加Wise-IoU,yolov8损失改进

1.在ultralytics/utils/metrics.py文件里找到 bbox_iou函数

注释整个函数
在这里插入图片描述

2.将注释的函数后面,去添加以下代码(替换上面注释的函数)

class WIoU_Scale:
    ''' monotonous: {
            None: origin v1
            True: monotonic FM v2
            False: non-monotonic FM v3
        }
        momentum: The momentum of running mean'''

    iou_mean = 1.
    monotonous = False
    _momentum = 1 - 0.5 ** (1 / 7000)
    _is_train = True

    def __init__(self, iou):
        self.iou = iou
        self._update(self)

    @classmethod
    def _update(cls, self):
        if cls._is_train: cls.iou_mean = (1 - cls._momentum) * cls.iou_mean + \
                                         cls._momentum * self.iou.detach().mean().item()

    @classmethod
    def _scaled_loss(cls, self, gamma=1.9, delta=3):
        if isinstance(self.monotonous, bool):
            if self.monotonous:
                return (self.iou.detach() / self.iou_mean).sqrt()
            else:
                beta = self.iou.detach() / self.iou_mean
                alpha = delta * torch.pow(gamma, beta - delta)
                return beta / alpha
        return 1


def bbox_iou(box1, box2, xywh=True, GIoU=False, DIoU=False, CIoU=False, SIoU=False, EIoU=False, WIoU=False, Focal=False,
             alpha=1, gamma=0.5, scale=False, eps=1e-7):
    # Returns Intersection over Union (IoU) of box1(1,4) to box2(n,4)

    # Get the coordinates of bounding boxes
    if xywh:  # transform from xywh to xyxy
        (x1, y1, w1, h1), (x2, y2, w2, h2) = box1.chunk(4, -1), box2.chunk(4, -1)
        w1_, h1_, w2_, h2_ = w1 / 2, h1 / 2, w2 / 2, h2 / 2
        b1_x1, b1_x2, b1_y1, b1_y2 = x1 - w1_, x1 + w1_, y1 - h1_, y1 + h1_
        b2_x1, b2_x2, b2_y1, b2_y2 = x2 - w2_, x2 + w2_, y2 - h2_, y2 + h2_
    else:  # x1, y1, x2, y2 = box1
        b1_x1, b1_y1, b1_x2, b1_y2 = box1.chunk(4, -1)
        b2_x1, b2_y1, b2_x2, b2_y2 = box2.chunk(4, -1)
        w1, h1 = b1_x2 - b1_x1, (b1_y2 - b1_y1).clamp(eps)
        w2, h2 = b2_x2 - b2_x1, (b2_y2 - b2_y1).clamp(eps)

    # Intersection area
    inter = (b1_x2.minimum(b2_x2) - b1_x1.maximum(b2_x1)).clamp(0) * \
            (b1_y2.minimum(b2_y2) - b1_y1.maximum(b2_y1)).clamp(0)

    # Union Area
    union = w1 * h1 + w2 * h2 - inter + eps
    if scale:
        self = WIoU_Scale(1 - (inter / union))

    # IoU
    # iou = inter / union # ori iou
    iou = torch.pow(inter / (union + eps), alpha)  # alpha iou
    if CIoU or DIoU or GIoU or EIoU or SIoU or WIoU:
        cw = b1_x2.maximum(b2_x2) - b1_x1.minimum(b2_x1)  # convex (smallest enclosing box) width
        ch = b1_y2.maximum(b2_y2) - b1_y1.minimum(b2_y1)  # convex height
        if CIoU or DIoU or EIoU or SIoU or WIoU:  # Distance or Complete IoU https://arxiv.org/abs/1911.08287v1
            c2 = (cw ** 2 + ch ** 2) ** alpha + eps  # convex diagonal squared
            rho2 = (((b2_x1 + b2_x2 - b1_x1 - b1_x2) ** 2 + (
                        b2_y1 + b2_y2 - b1_y1 - b1_y2) ** 2) / 4) ** alpha  # center dist ** 2
            if CIoU:  # https://github.com/Zzh-tju/DIoU-SSD-pytorch/blob/master/utils/box/box_utils.py#L47
                v = (4 / math.pi ** 2) * (torch.atan(w2 / h2) - torch.atan(w1 / h1)).pow(2)
                with torch.no_grad():
                    alpha_ciou = v / (v - iou + (1 + eps))
                if Focal:
                    return iou - (rho2 / c2 + torch.pow(v * alpha_ciou + eps, alpha)), torch.pow(inter / (union + eps),
                                                                                                 gamma)  # Focal_CIoU
                else:
                    return iou - (rho2 / c2 + torch.pow(v * alpha_ciou + eps, alpha))  # CIoU
            elif EIoU:
                rho_w2 = ((b2_x2 - b2_x1) - (b1_x2 - b1_x1)) ** 2
                rho_h2 = ((b2_y2 - b2_y1) - (b1_y2 - b1_y1)) ** 2
                cw2 = torch.pow(cw ** 2 + eps, alpha)
                ch2 = torch.pow(ch ** 2 + eps, alpha)
                if Focal:
                    return iou - (rho2 / c2 + rho_w2 / cw2 + rho_h2 / ch2), torch.pow(inter / (union + eps),
                                                                                      gamma)  # Focal_EIou
                else:
                    return iou - (rho2 / c2 + rho_w2 / cw2 + rho_h2 / ch2)  # EIou
            elif SIoU:
                # SIoU Loss https://arxiv.org/pdf/2205.12740.pdf
                s_cw = (b2_x1 + b2_x2 - b1_x1 - b1_x2) * 0.5 + eps
                s_ch = (b2_y1 + b2_y2 - b1_y1 - b1_y2) * 0.5 + eps
                sigma = torch.pow(s_cw ** 2 + s_ch ** 2, 0.5)
                sin_alpha_1 = torch.abs(s_cw) / sigma
                sin_alpha_2 = torch.abs(s_ch) / sigma
                threshold = pow(2, 0.5) / 2
                sin_alpha = torch.where(sin_alpha_1 > threshold, sin_alpha_2, sin_alpha_1)
                angle_cost = torch.cos(torch.arcsin(sin_alpha) * 2 - math.pi / 2)
                rho_x = (s_cw / cw) ** 2
                rho_y = (s_ch / ch) ** 2
                gamma = angle_cost - 2
                distance_cost = 2 - torch.exp(gamma * rho_x) - torch.exp(gamma * rho_y)
                omiga_w = torch.abs(w1 - w2) / torch.max(w1, w2)
                omiga_h = torch.abs(h1 - h2) / torch.max(h1, h2)
                shape_cost = torch.pow(1 - torch.exp(-1 * omiga_w), 4) + torch.pow(1 - torch.exp(-1 * omiga_h), 4)
                if Focal:
                    return iou - torch.pow(0.5 * (distance_cost + shape_cost) + eps, alpha), torch.pow(
                        inter / (union + eps), gamma)  # Focal_SIou
                else:
                    return iou - torch.pow(0.5 * (distance_cost + shape_cost) + eps, alpha)  # SIou
            elif WIoU:
                if Focal:
                    raise RuntimeError("WIoU do not support Focal.")
                elif scale:
                    return getattr(WIoU_Scale, '_scaled_loss')(self), (1 - iou) * torch.exp(
                        (rho2 / c2)), iou  # WIoU https://arxiv.org/abs/2301.10051
                else:
                    return iou, torch.exp((rho2 / c2))  # WIoU v1
            if Focal:
                return iou - rho2 / c2, torch.pow(inter / (union + eps), gamma)  # Focal_DIoU
            else:
                return iou - rho2 / c2  # DIoU
        c_area = cw * ch + eps  # convex area
        if Focal:
            return iou - torch.pow((c_area - union) / c_area + eps, alpha), torch.pow(inter / (union + eps),
                                                                                      gamma)  # Focal_GIoU https://arxiv.org/pdf/1902.09630.pdf
        else:
            return iou - torch.pow((c_area - union) / c_area + eps, alpha)  # GIoU https://arxiv.org/pdf/1902.09630.pdf
    if Focal:
        return iou, torch.pow(inter / (union + eps), gamma)  # Focal_IoU
    else:
        return iou  # IoU

### 源码修改(还原则删除)- loss2 - end

参考链接:

原文链接:https: // blog.csdn.net / darkredrock / article / details / 130292080
原文链接:https: // blog.csdn.net / weixin_45303602 / article / details / 133748724
在这里插入图片描述

3.ultralytics/utils/loss.py文件里,找到BboxLoss类中的forward

找到下面两行代码

iou = bbox_iou(pred_bboxes[fg_mask], target_bboxes[fg_mask], xywh=False, CIoU=True)
loss_iou = ((1.0 - iou) * weight).sum() / target_scores_sum

替换为以下代码:

        # todo 源码修改(还原则删除)- loss6_
        # # WIoU
        iou = bbox_iou_for_nms(pred_bboxes[fg_mask], target_bboxes[fg_mask], xywh=False, WIoU=True, scale=True)
        if type(iou) is tuple:
            if len(iou) == 2:
                loss_iou = ((1.0 - iou[0]) * iou[1].detach() * weight).sum() / target_scores_sum
            else:
                loss_iou = (iou[0] * iou[1] * weight).sum() / target_scores_sum
        else:
            loss_iou = ((1.0 - iou) * weight).sum() / target_scores_sum
        # 源码修改(还原则删除)- loss6 - end

在这里插入图片描述

4.还是loss文件中,添加以下bbox_iou_for_nms代码

# todo 源码修改(还原则删除)- loss7(2)_
def bbox_iou_for_nms(box1, box2, xywh=True, GIoU=False, DIoU=False, CIoU=False, SIoU=False, EIoU=False, WIoU=False,
                     Focal=False, alpha=1, gamma=0.5, scale=False, eps=1e-7):
    # Returns Intersection over Union (IoU) of box1(1,4) to box2(n,4)

    # Get the coordinates of bounding boxes
    if xywh:  # transform from xywh to xyxy
        (x1, y1, w1, h1), (x2, y2, w2, h2) = box1.chunk(4, -1), box2.chunk(4, -1)
        w1_, h1_, w2_, h2_ = w1 / 2, h1 / 2, w2 / 2, h2 / 2
        b1_x1, b1_x2, b1_y1, b1_y2 = x1 - w1_, x1 + w1_, y1 - h1_, y1 + h1_
        b2_x1, b2_x2, b2_y1, b2_y2 = x2 - w2_, x2 + w2_, y2 - h2_, y2 + h2_
    else:  # x1, y1, x2, y2 = box1
        b1_x1, b1_y1, b1_x2, b1_y2 = box1.chunk(4, -1)
        b2_x1, b2_y1, b2_x2, b2_y2 = box2.chunk(4, -1)
        w1, h1 = b1_x2 - b1_x1, (b1_y2 - b1_y1).clamp(eps)
        w2, h2 = b2_x2 - b2_x1, (b2_y2 - b2_y1).clamp(eps)

    # Intersection area
    inter = (b1_x2.minimum(b2_x2) - b1_x1.maximum(b2_x1)).clamp(0) * \
            (b1_y2.minimum(b2_y2) - b1_y1.maximum(b2_y1)).clamp(0)

    # Union Area
    union = w1 * h1 + w2 * h2 - inter + eps
    if scale:
        self = WIoU_Scale(1 - (inter / union))

    # IoU
    # iou = inter / union # ori iou
    iou = torch.pow(inter / (union + eps), alpha)  # alpha iou
    if CIoU or DIoU or GIoU or EIoU or SIoU or WIoU:
        cw = b1_x2.maximum(b2_x2) - b1_x1.minimum(b2_x1)  # convex (smallest enclosing box) width
        ch = b1_y2.maximum(b2_y2) - b1_y1.minimum(b2_y1)  # convex height
        if CIoU or DIoU or EIoU or SIoU or WIoU:  # Distance or Complete IoU https://arxiv.org/abs/1911.08287v1
            c2 = (cw ** 2 + ch ** 2) ** alpha + eps  # convex diagonal squared
            rho2 = (((b2_x1 + b2_x2 - b1_x1 - b1_x2) ** 2 + (
                        b2_y1 + b2_y2 - b1_y1 - b1_y2) ** 2) / 4) ** alpha  # center dist ** 2
            if CIoU:  # https://github.com/Zzh-tju/DIoU-SSD-pytorch/blob/master/utils/box/box_utils.py#L47
                v = (4 / math.pi ** 2) * (torch.atan(w2 / h2) - torch.atan(w1 / h1)).pow(2)
                with torch.no_grad():
                    alpha_ciou = v / (v - iou + (1 + eps))
                if Focal:
                    return iou - (rho2 / c2 + torch.pow(v * alpha_ciou + eps, alpha)), torch.pow(inter / (union + eps),
                                                                                                 gamma)  # Focal_CIoU
                else:
                    return iou - (rho2 / c2 + torch.pow(v * alpha_ciou + eps, alpha))  # CIoU
            elif EIoU:
                rho_w2 = ((b2_x2 - b2_x1) - (b1_x2 - b1_x1)) ** 2
                rho_h2 = ((b2_y2 - b2_y1) - (b1_y2 - b1_y1)) ** 2
                cw2 = torch.pow(cw ** 2 + eps, alpha)
                ch2 = torch.pow(ch ** 2 + eps, alpha)
                if Focal:
                    return iou - (rho2 / c2 + rho_w2 / cw2 + rho_h2 / ch2), torch.pow(inter / (union + eps),
                                                                                      gamma)  # Focal_EIou
                else:
                    return iou - (rho2 / c2 + rho_w2 / cw2 + rho_h2 / ch2)  # EIou
            elif SIoU:
                # SIoU Loss https://arxiv.org/pdf/2205.12740.pdf
                s_cw = (b2_x1 + b2_x2 - b1_x1 - b1_x2) * 0.5 + eps
                s_ch = (b2_y1 + b2_y2 - b1_y1 - b1_y2) * 0.5 + eps
                sigma = torch.pow(s_cw ** 2 + s_ch ** 2, 0.5)
                sin_alpha_1 = torch.abs(s_cw) / sigma
                sin_alpha_2 = torch.abs(s_ch) / sigma
                threshold = pow(2, 0.5) / 2
                sin_alpha = torch.where(sin_alpha_1 > threshold, sin_alpha_2, sin_alpha_1)
                angle_cost = torch.cos(torch.arcsin(sin_alpha) * 2 - math.pi / 2)
                rho_x = (s_cw / cw) ** 2
                rho_y = (s_ch / ch) ** 2
                gamma = angle_cost - 2
                distance_cost = 2 - torch.exp(gamma * rho_x) - torch.exp(gamma * rho_y)
                omiga_w = torch.abs(w1 - w2) / torch.max(w1, w2)
                omiga_h = torch.abs(h1 - h2) / torch.max(h1, h2)
                shape_cost = torch.pow(1 - torch.exp(-1 * omiga_w), 4) + torch.pow(1 - torch.exp(-1 * omiga_h), 4)
                if Focal:
                    return iou - torch.pow(0.5 * (distance_cost + shape_cost) + eps, alpha), torch.pow(
                        inter / (union + eps), gamma)  # Focal_SIou
                else:
                    return iou - torch.pow(0.5 * (distance_cost + shape_cost) + eps, alpha)  # SIou
            elif WIoU:
                if Focal:
                    raise RuntimeError("WIoU do not support Focal.")
                elif scale:
                    return getattr(WIoU_Scale, '_scaled_loss')(self), (1 - iou) * torch.exp(
                        (rho2 / c2)), iou  # WIoU https://arxiv.org/abs/2301.10051
                else:
                    return iou, torch.exp((rho2 / c2))  # WIoU v1
            if Focal:
                return iou - rho2 / c2, torch.pow(inter / (union + eps), gamma)  # Focal_DIoU
            else:
                return iou - rho2 / c2  # DIoU
        c_area = cw * ch + eps  # convex area
        if Focal:
            return iou - torch.pow((c_area - union) / c_area + eps, alpha), torch.pow(inter / (union + eps),
                                                                                      gamma)  # Focal_GIoU https://arxiv.org/pdf/1902.09630.pdf
        else:
            return iou - torch.pow((c_area - union) / c_area + eps, alpha)  # GIoU https://arxiv.org/pdf/1902.09630.pdf
    if Focal:
        return iou, torch.pow(inter / (union + eps), gamma)  # Focal_IoU
    else:
        return iou  # IoU


# def soft_nms(bboxes, scores, iou_thresh=0.5, sigma=0.5, score_threshold=0.25):
#     order = torch.arange(0, scores.size(0)).to(bboxes.device)
#     keep = []
#
#     while order.numel() > 1:
#         if order.numel() == 1:
#             keep.append(order[0])
#             break
#         else:
#             i = order[0]
#             keep.append(i)
#         # todo 源码修改(还原则取消注释)- loss10_
#         iou = bbox_iou_for_nms(bboxes[i], bboxes[order[1:]]).squeeze()
#         # todo 源码修改(还原则删除)- loss11_
#         # iou = bbox_iou_for_nms(bboxes[i], bboxes[order[1:]],WIoU=True).squeeze()
#         # iou = bbox_iou_for_nms(bboxes[i], bboxes[order[1:]],WIoU=True)
#
#         idx = (iou > iou_thresh).nonzero().squeeze()
#         if idx.numel() > 0:
#             iou = iou[idx]
#             newScores = torch.exp(-torch.pow(iou, 2) / sigma)
#             scores[order[idx + 1]] *= newScores
#
#         newOrder = (scores[order[1:]] > score_threshold).nonzero().squeeze()
#         if newOrder.numel() == 0:
#             break
#         else:
#             maxScoreIndex = torch.argmax(scores[order[newOrder + 1]])
#             if maxScoreIndex != 0:
#                 newOrder[[0, maxScoreIndex],] = newOrder[[maxScoreIndex, 0],]
#             order = order[newOrder + 1]
#
#     return torch.LongTensor(keep)
# 源码修改(还原则删除)- loss7(2) - end

原参考链接是在metrics.py下添加上述bbox_iou_for_nms代码,可参考,不过我这边报错,已注释

# todo 源码修改(还原则删除)- loss7_
# def bbox_iou_for_nms(box1, box2, xywh=True, GIoU=False, DIoU=False, CIoU=False, SIoU=False, EIoU=False, WIoU=False,
#                      Focal=False, alpha=1, gamma=0.5, scale=False, eps=1e-7):
#     # Returns Intersection over Union (IoU) of box1(1,4) to box2(n,4)
#
#     # Get the coordinates of bounding boxes
#     if xywh:  # transform from xywh to xyxy
#         (x1, y1, w1, h1), (x2, y2, w2, h2) = box1.chunk(4, -1), box2.chunk(4, -1)
#         w1_, h1_, w2_, h2_ = w1 / 2, h1 / 2, w2 / 2, h2 / 2
#         b1_x1, b1_x2, b1_y1, b1_y2 = x1 - w1_, x1 + w1_, y1 - h1_, y1 + h1_
#         b2_x1, b2_x2, b2_y1, b2_y2 = x2 - w2_, x2 + w2_, y2 - h2_, y2 + h2_
#     else:  # x1, y1, x2, y2 = box1
#         b1_x1, b1_y1, b1_x2, b1_y2 = box1.chunk(4, -1)
#         b2_x1, b2_y1, b2_x2, b2_y2 = box2.chunk(4, -1)
#         w1, h1 = b1_x2 - b1_x1, (b1_y2 - b1_y1).clamp(eps)
#         w2, h2 = b2_x2 - b2_x1, (b2_y2 - b2_y1).clamp(eps)
#
#     # Intersection area
#     inter = (b1_x2.minimum(b2_x2) - b1_x1.maximum(b2_x1)).clamp(0) * \
#             (b1_y2.minimum(b2_y2) - b1_y1.maximum(b2_y1)).clamp(0)
#
#     # Union Area
#     union = w1 * h1 + w2 * h2 - inter + eps
#     if scale:
#         self = WIoU_Scale(1 - (inter / union))
#
#     # IoU
#     # iou = inter / union # ori iou
#     iou = torch.pow(inter / (union + eps), alpha)  # alpha iou
#     if CIoU or DIoU or GIoU or EIoU or SIoU or WIoU:
#         cw = b1_x2.maximum(b2_x2) - b1_x1.minimum(b2_x1)  # convex (smallest enclosing box) width
#         ch = b1_y2.maximum(b2_y2) - b1_y1.minimum(b2_y1)  # convex height
#         if CIoU or DIoU or EIoU or SIoU or WIoU:  # Distance or Complete IoU https://arxiv.org/abs/1911.08287v1
#             c2 = (cw ** 2 + ch ** 2) ** alpha + eps  # convex diagonal squared
#             rho2 = (((b2_x1 + b2_x2 - b1_x1 - b1_x2) ** 2 + (
#                         b2_y1 + b2_y2 - b1_y1 - b1_y2) ** 2) / 4) ** alpha  # center dist ** 2
#             if CIoU:  # https://github.com/Zzh-tju/DIoU-SSD-pytorch/blob/master/utils/box/box_utils.py#L47
#                 v = (4 / math.pi ** 2) * (torch.atan(w2 / h2) - torch.atan(w1 / h1)).pow(2)
#                 with torch.no_grad():
#                     alpha_ciou = v / (v - iou + (1 + eps))
#                 if Focal:
#                     return iou - (rho2 / c2 + torch.pow(v * alpha_ciou + eps, alpha)), torch.pow(inter / (union + eps),
#                                                                                                  gamma)  # Focal_CIoU
#                 else:
#                     return iou - (rho2 / c2 + torch.pow(v * alpha_ciou + eps, alpha))  # CIoU
#             elif EIoU:
#                 rho_w2 = ((b2_x2 - b2_x1) - (b1_x2 - b1_x1)) ** 2
#                 rho_h2 = ((b2_y2 - b2_y1) - (b1_y2 - b1_y1)) ** 2
#                 cw2 = torch.pow(cw ** 2 + eps, alpha)
#                 ch2 = torch.pow(ch ** 2 + eps, alpha)
#                 if Focal:
#                     return iou - (rho2 / c2 + rho_w2 / cw2 + rho_h2 / ch2), torch.pow(inter / (union + eps),
#                                                                                       gamma)  # Focal_EIou
#                 else:
#                     return iou - (rho2 / c2 + rho_w2 / cw2 + rho_h2 / ch2)  # EIou
#             elif SIoU:
#                 # SIoU Loss https://arxiv.org/pdf/2205.12740.pdf
#                 s_cw = (b2_x1 + b2_x2 - b1_x1 - b1_x2) * 0.5 + eps
#                 s_ch = (b2_y1 + b2_y2 - b1_y1 - b1_y2) * 0.5 + eps
#                 sigma = torch.pow(s_cw ** 2 + s_ch ** 2, 0.5)
#                 sin_alpha_1 = torch.abs(s_cw) / sigma
#                 sin_alpha_2 = torch.abs(s_ch) / sigma
#                 threshold = pow(2, 0.5) / 2
#                 sin_alpha = torch.where(sin_alpha_1 > threshold, sin_alpha_2, sin_alpha_1)
#                 angle_cost = torch.cos(torch.arcsin(sin_alpha) * 2 - math.pi / 2)
#                 rho_x = (s_cw / cw) ** 2
#                 rho_y = (s_ch / ch) ** 2
#                 gamma = angle_cost - 2
#                 distance_cost = 2 - torch.exp(gamma * rho_x) - torch.exp(gamma * rho_y)
#                 omiga_w = torch.abs(w1 - w2) / torch.max(w1, w2)
#                 omiga_h = torch.abs(h1 - h2) / torch.max(h1, h2)
#                 shape_cost = torch.pow(1 - torch.exp(-1 * omiga_w), 4) + torch.pow(1 - torch.exp(-1 * omiga_h), 4)
#                 if Focal:
#                     return iou - torch.pow(0.5 * (distance_cost + shape_cost) + eps, alpha), torch.pow(
#                         inter / (union + eps), gamma)  # Focal_SIou
#                 else:
#                     return iou - torch.pow(0.5 * (distance_cost + shape_cost) + eps, alpha)  # SIou
#             elif WIoU:
#                 if Focal:
#                     raise RuntimeError("WIoU do not support Focal.")
#                 elif scale:
#                     return getattr(WIoU_Scale, '_scaled_loss')(self), (1 - iou) * torch.exp(
#                         (rho2 / c2)), iou  # WIoU https://arxiv.org/abs/2301.10051
#                 else:
#                     return iou, torch.exp((rho2 / c2))  # WIoU v1
#             if Focal:
#                 return iou - rho2 / c2, torch.pow(inter / (union + eps), gamma)  # Focal_DIoU
#             else:
#                 return iou - rho2 / c2  # DIoU
#         c_area = cw * ch + eps  # convex area
#         if Focal:
#             return iou - torch.pow((c_area - union) / c_area + eps, alpha), torch.pow(inter / (union + eps),
#                                                                                       gamma)  # Focal_GIoU https://arxiv.org/pdf/1902.09630.pdf
#         else:
#             return iou - torch.pow((c_area - union) / c_area + eps, alpha)  # GIoU https://arxiv.org/pdf/1902.09630.pdf
#     if Focal:
#         return iou, torch.pow(inter / (union + eps), gamma)  # Focal_IoU
#     else:
#         return iou  # IoU
#
#
# def soft_nms(bboxes, scores, iou_thresh=0.5, sigma=0.5, score_threshold=0.25):
#     order = torch.arange(0, scores.size(0)).to(bboxes.device)
#     keep = []
#
#     while order.numel() > 1:
#         if order.numel() == 1:
#             keep.append(order[0])
#             break
#         else:
#             i = order[0]
#             keep.append(i)
#         # todo 源码修改(还原则取消注释)- loss10_
#         # iou = bbox_iou_for_nms(bboxes[i], bboxes[order[1:]]).squeeze()
#         # todo 源码修改(还原则删除)- loss11_
#         # iou = bbox_iou_for_nms(bboxes[i], bboxes[order[1:]],WIoU=True).squeeze()
#         """
#         # 如果,iou等于下面这个-1
#         iou = bbox_iou_for_nms(bboxes[i], bboxes[order[1:]],WIoU=True)
#         print(f"--------为解决bug,打印iou--------:{iou}")
#         print(f"--------为解决bug,打印iou的类型--------:{type(iou)}") #<class 'tuple'>
#         print(f"--------为解决bug,打印iou[0]的形状--------:{iou[0].shape}") # torch.Size([503, 1]) # torch.Size([6693, 1]) # torch.Size([4298, 1])
#         print(f"--------为解决bug,打印iou[1]的形状--------:{iou[1].shape}") # torch.Size([503, 1]) # torch.Size([6693, 1]) # torch.Size([4298, 1])
#         print(f"--------为解决bug,打印iou的len--------:{len(iou)}") # 2
#         # 那么,iou是元组类型,元组里装了两个tensor,每个tensor的shape [x,1] # 即 (tensor(x,1),tensor(x,1))
#         """
#         """
#         # 如果,iou等于下面这个-2
#         iou = bbox_iou_for_nms(bboxes[i], bboxes[order[1:]],WIoU=True)[0]
#         print(f"--------为解决bug,打印iou--------:{iou}")
#         print(f"--------为解决bug,打印iou的类型--------:{type(iou)}") # <class 'torch.Tensor'>
#         print(f"--------为解决bug,打印iou[0]的形状--------:{iou[0].shape}") # torch.Size([1])
#         print(f"--------为解决bug,打印iou[1]的形状--------:{iou[1].shape}") # torch.Size([1])
#         print(f"--------为解决bug,打印iou的len--------:{len(iou)}") # 29
#         # scores[order[idx + 1]] *= newScores --报错--> # RuntimeError:  The size of tensor a (16) must match the size of tensor b (2) at non-singleton dimension 1
#         """
#
#         """
#         # 如果,iou等于下面这个-3
#         iou_temp = bbox_iou_for_nms(bboxes[i], bboxes[order[1:]], WIoU=True)
#         iou = (iou_temp[0].squeeze(),iou_temp[1].squeeze())
#         print(f"--------为解决bug,打印iou--------:{iou}")
#         print(f"--------为解决bug,打印iou的类型--------:{type(iou)}")
#         print(f"--------为解决bug,打印iou[0]的形状--------:{iou[0].shape}")
#         print(f"--------为解决bug,打印iou[1]的形状--------:{iou[1].shape}")
#         print(f"--------为解决bug,打印iou的len--------:{len(iou)}")
#         """
#         pass
#         idx = (iou > iou_thresh).nonzero().squeeze()
#         if idx.numel() > 0:
#             iou = iou[idx]
#             newScores = torch.exp(-torch.pow(iou, 2) / sigma)
#             scores[order[idx + 1]] *= newScores
#
#         newOrder = (scores[order[1:]] > score_threshold).nonzero().squeeze()
#         if newOrder.numel() == 0:
#             break
#         else:
#             maxScoreIndex = torch.argmax(scores[order[newOrder + 1]])
#             if maxScoreIndex != 0:
#                 newOrder[[0, maxScoreIndex],] = newOrder[[maxScoreIndex, 0],]
#             order = order[newOrder + 1]
#
#     return torch.LongTensor(keep)
# 源码修改(还原则删除)- loss7 - end
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值