IOU、GIOU、DIOU、CIOU 代码实现

废话不多说,原理看这个:

IOU、GIOU、DIOU、CIOU详解及代码实现

代码如下

为了更好的处理多个bbox的IoU计算,对代码进行了改造

import math
import torch
from torch import Tensor
# author:wuliang
# time: 2022.5.27

def _upcast(t: Tensor) -> Tensor:
    # Protects from numerical overflows in multiplications by upcasting to the equivalent higher type
    if t.is_floating_point():
        return t if t.dtype in (torch.float32, torch.float64) else t.float()
    else:
        return t if t.dtype in (torch.int32, torch.int64) else t.int()

def box_area(boxes: Tensor) -> Tensor:
    """
    Computes the area of a set of bounding boxes, which are specified by their
    (x1, y1, x2, y2) coordinates.

    Args:
        boxes (Tensor[N, 4]): boxes for which the area will be computed. They
            are expected to be in (x1, y1, x2, y2) format with
            ``0 <= x1 < x2`` and ``0 <= y1 < y2``.

    Returns:
        Tensor[N]: the area for each box
    """
    boxes = _upcast(boxes)
    return (boxes[:, 2] - boxes[:, 0]) * (boxes[:, 3] - boxes[:, 1])
    
def box_iou(boxes1, boxes2):
    area1 = box_area(boxes1)
    area2 = box_area(boxes2)

    lt = torch.max(boxes1[:, None, :
### 不同类型的IoU指标定义与区别 #### 1. **交并比 (Intersection over Union, IoU)** IoU 是一种用于衡量两个边界框重叠程度的标准方法。其计算方式为预测框和真实框的交集面积除以它们的并集面积[^1]。 公式如下: \[ IoU = \frac{A_{pred} \cap A_{gt}}{A_{pred} \cup A_{gt}} \] 其中 \(A_{pred}\) 表示预测框区域,\(A_{gt}\) 表示真实框区域。 --- #### 2. **广义交并比 (Generalized Intersection over Union, GIoU)** GIoU 扩展了传统 IoU 的概念,在处理不相交的情况时表现更好。它通过引入最小闭包的概念来改进 IoU 计算。 公式如下: \[ GIoU = IoU - \frac{C - (A_{pred} \cup A_{gt})}{C} \] 这里 \(C\) 是能够覆盖 \(A_{pred}\) 和 \(A_{gt}\) 的最小矩形区域。 --- #### 3. **距离交并比 (Distance-IoU Loss, DIoU)** DIoU 进一步优化了目标检测中的定位精度问题,除了考虑重叠部分外,还加入了中心点之间的欧几里得距离以及包围盒的比例关系。 公式如下: \[ DIoU = IoU - \frac{\rho^2(B,B^{GT})}{c^2} \] 其中 \(\rho^2(B,B^{GT})\) 是预测框和真实框中心点的距离平方,而 \(c\) 则是最小封闭矩形对角线长度。 --- #### 4. **完全交并比 (Complete-IoU Loss, CIoU)** CIoU 继承了 DIoU 的优点,并额外加入了一个比例因子项,用来调整宽高比的影响,从而进一步提升回归性能。 公式如下: \[ CIoU = IoU - \left( \frac{\rho^2(B,B^{GT})}{c^2} + v \cdot \alpha(v)\right) \] 这里的 \(v=\frac{(ar)^2-(ar^{*})^2}{(ar)^2+(ar^{*})^2}\),表示宽高比差异;\(\alpha(v)=\frac{v}{(1-\text{IoU}+\epsilon)}\) 控制权重平衡。 --- #### 5. **扩展交并比 (Enhanced-IoU Loss, EIoU)** EIou 主要针对旋转框设计,不仅关注位置偏差,也注重角度误差带来的影响。 具体实现细节可参考相关论文或开源项目代码。 --- #### 6. **形状交并比 (Shape-IoU, SIoU)** SIoU 更加专注于边界框的方向性和几何特性匹配度评估,适用于复杂场景下的对象检测任务。 --- #### 7. **加权交并比 (Weighted-IoU, WIoU)** WIoU 考虑到不同类别间的重要性可能有所不同,因此引入权重机制使得某些类别的误检代价更高。 --- #### 8. **多视角方向交并比 (Multi-Perspective Directional IoU, MPDIoU)** MPDIoU 结合多个视角的信息综合判断目标的位置及姿态信息,适合于三维空间内的物体检测应用场合。 --- #### 9. **形态学交并比 (Morphological Perceptual Distance IoU, ShapeIoU)** 此版本强调的是两幅图像之间像素级相似性的测度而非单纯基于边界的比较。 --- ```python import torch def iou_loss(pred_boxes, gt_boxes): """Basic IoU loss implementation.""" # Compute areas of pred and ground truth boxes. area_pred = ... area_gt = ... # Calculate intersection areas between preds & gts. inter_area = ... union_area = area_pred + area_gt - inter_area return 1 - (inter_area / union_area) # Example usage with PyTorch tensors. if __name__ == "__main__": pred = torch.tensor([[...]]) # Predictions as tensor. target = torch.tensor([[...]]) # Ground truths as tensor. loss_value = iou_loss(pred, target) print(f"IoU Loss Value: {loss_value.item()}") ``` 上述代码片段展示了如何利用 PyTorch 实现基本形式的 IoU 损失函数[^2]。 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值