首页 > 其他分享 >IoU

IoU

时间:2023-06-05 19:56:56浏览次数:41  
标签:IoU torch eps b1 b2 alpha iou

  1. IOU(Intersection over Union):

    • 作用:IOU是最常用的边界框重叠度量方法,用于衡量两个边界框之间的重叠程度。
    • 优点:简单直观,易于计算和理解。
    • 缺点:不考虑形状信息,对大小和方向不敏感。
    • 计算公式:IOU = (Intersection Area) / (Union Area)
  2. GIOU(Generalized Intersection over Union):

    • 作用:GIOU是对IOU的改进,它在边界框重叠度量中考虑了形状信息。它通过计算交集面积、并集面积和最小闭合矩形的面积来进行度量。
    • 优点:对形状差异较大的边界框提供了更准确的度量结果。
    • 缺点:对形状变化敏感度不一致,不具备方向信息,对大小不敏感。
    • 计算公式:GIOU = IOU - (C - Union Area) / C, C为最小包闭区面积
  3. DIOU(Distance-IoU):

    • 作用:在GIOU的基础上考虑了边界框中心点之间的距离。
    • 优点:对中心点距离的变化更加敏感,可以更好地处理边界框的位置偏移。
    • 缺点:仍然不具备方向信息,对大小不敏感。
    • 计算公式:DIOU = IOU - (ρ2(b, bgt) / c2), ρ为预测框与gt框中心点距离,c为最小包闭区对角线长度。
  4. CIOU(Complete-IoU):

    • 作用:在DIOU的基础上进一步考虑了宽高的相似性。
    • 优点:综合考虑了位置、形状、尺寸等因素,对边界框的重叠度量更加准确。
    • 缺点:仍然不具备方向信息。
    • 计算公式:
      ν = 4 / pi2 * ( arctan( wgt / hgt ) - arctan(w / h))2
      α = ν / (1 - IoU + ν)   PS:ν不变时,iou越大,α越大,loss越大
      CIOU = DIOU - αv
    • 当iou很小时,v的权重小,更多关心把iou变大;当iou很大时,权重大,更多关心是否相似

  5. α - IOU
    在计算iou损失时,将iou项变为α指数。对小数据集和噪声的鲁棒性更好
    eg. LIOU = 1 - IOU   Lα - IOU = 1 - IOUα
          LGIOU = 1- IOU + (C - U) / C,   Lα-GIOU = 1 - IOUα + (C - U) / C)α

    当iou>0.5时,梯度>1,加速学习

  6. EIOU:

    • 将CIOU的长宽比例拆分为长比例、宽比例,收敛更快
    • EIOU = IOU - (ρ2(b, bgt) / c2) - (ρ2(w, wgt) / cw2) - (ρ2(h, hgt) / ch2) , cw、ch最小包闭区w、h

    • 引入Focal - EIOU缓解样品不平衡问题
    • LFocal-EIOU = IOUλLEIOU
    • 简单的任务框(即iou较大)回归不需要用过大的权重来学习,而复杂的任务框回归需要大权重来学习

 

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 = (torch.min(b1_x2, b2_x2) - torch.max(b1_x1, b2_x1)).clamp(0) * \
            (torch.min(b1_y2, b2_y2) - torch.max(b1_y1, 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 = torch.max(b1_x2, b2_x2) - torch.min(b1_x1, b2_x1)  # convex (smallest enclosing box) width
        ch = torch.max(b1_y2, b2_y2) - torch.min(b1_y1, 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

 

标签:IoU,torch,eps,b1,b2,alpha,iou
From: https://www.cnblogs.com/lbclyc/p/17458788.html

相关文章

  • leetcode 594. Longest Harmonious Subsequence
    Wedefineaharmoniousarrayisanarraywherethedifferencebetweenitsmaximumvalueanditsminimumvalueisexactly1.Now,givenanintegerarray,youneedtofindthelengthofitslongestharmonioussubsequenceamongallitspossiblesubsequences.E......
  • Python计算目标检测中的IoU
    Python计算目标检测中的IoU前言前提条件相关介绍实验环境IoU概念代码实现前言本文是个人使用PythonPython处理文件的电子笔记,由于水平有限,难免出现错漏,敬请批评改正。更多精彩内容,可点击进入我的个人主页查看前提条件熟悉Python相关介绍Python是一种跨平台的计算机程序设计语言。......
  • fatal: detected dubious ownership in repository at 'D:/xxx'
     git的出现这个错误: 执行下面代码即可:gitconfig--global--addsafe.directory"*"; ......
  • 【攻防世界逆向】《re-for-50-plz-50》《srm-50》《Mysterious》《Guess-the-Number》
    题目re-for-50-plz-50解法题目不难,先exeinfo32位elf无壳,但是我在做的时候碰到了一些困难,原本用的是低版本的ida,在f5进行反汇编的时候失败了,然后在吾爱下了一个新版本的ida,就反汇编成功了。以下看起来非常简单明了,关键在于有一个字符串和55进行了异或,点进去看看这样一个,好......
  • PS一键磨皮插件delicious retouch插件(DR5白金版)
    哪里可以获取PS一键磨皮插件deliciousretouch插件中文激活版资源呢?DeliciousRetouch是一款Photoshop扩展插件,旨在帮助用户快速、高效地进行照片修饰和美化。它提供了多种功能和工具,可以帮助用户轻松地修饰肤色、磨皮、润色、增强细节等,使得照片更加美观自然。DeliciousRetouch......
  • Infectious Media Generator成功
    刚才失败了,然后我把BT5虚拟机回退到先前的一个snapshot,然后再次操作,就成功了:root@bt:~#cd/pentest/exploits/set/root@bt:/pentest/exploits/set#./setCopyright2012,TheSocial-EngineerToolkit(SET)byTrustedSec,LLCAllrightsreserved.Redistributionandusei......
  • How do I make a delicious lemon cheesecake?
    Therearemanydifferentwaystoprepareadeliciouslemoncheesecake.Hereisonepopularrecipethatyoucantry:Ingredients:21/4cupsgrahamcrackercrumbs(about150crackers)3tablespoonssugar8ozcreamcheese,softened1cupgranulatedsugar1......
  • 英语四级难点单词之 conscientious
    conscientious是 良心的,尽责的意思单词"conscientious"来自于Latin语"conscius",意思是"知道"、"意识到"。它的后缀"-ous"表示"充满"的意思,因此"conscientious"可以理解为"充满责任心的、认真的、小心谨慎的"。充满意识,说明一个充满了认真和责任感对应的......
  • codeforces 4D D. Mysterious Present(dp)
    题目连接:codeforces4D题目大意:给出n个信封,这n个信封有长和宽,给出卡片的尺寸,求取能够装入卡片的最长的序列,序列满足后一个的长和宽一定大于前一个,求最长的这个序列的长度,并且给出一组可行解。题目分析:一看这种题目就是dp的题目,状态定义dp[i]为以i结尾的序列的最大的长度,并且利用一......
  • 感觉和知觉(Perception and Consciousness)的区分和学习
     感觉和知觉(PerceptionandConsciousness)consciousness是知觉,这个应该是被动对环境的反应和内在的意识Perception对对外的感觉,主动对外界的思考的探索前缀per-表示“完全,贯穿,自始至终,向前”。forth,ford是其同源词。词根cap-,capt-,cept-,ceiv-,cip-,cup-=take,hol......