SIOU损失函数公式
时间: 2023-11-17 16:04:47 浏览: 182
SIoU损失函数是一种目标检测中常用的损失函数,用于衡量预测框和真实框之间的相似度。其公式如下:
LossSIoU = 1 - IoU + (Δ + Ω) / 2
其中,IoU表示预测框和真实框的交并比,Δ和Ω是两个超参数,用于平衡IoU和中心点距离的贡献。具体而言,Δ用于控制中心点距离的影响,Ω用于控制IoU的影响。
以下是SIoU损失函数的代码实现:
```python
import torch
def box_iou(box1, box2):
"""
计算两个框的IoU
"""
# 计算交集的左上角和右下角坐标
lt = torch.max(box1[:, :2], box2[:, :2])
rb = torch.min(box1[:, 2:], box2[:, 2:])
# 计算交集的宽和高
wh = (rb - lt).clamp(min=0)
# 计算交集面积和并集面积
inter = wh[:, 0] * wh[:, 1]
area1 = (box1[:, 2] - box1[:, 0]) * (box1[:, 3] - box1[:, 1])
area2 = (box2[:, 2] - box2[:, 0]) * (box2[:, 3] - box2[:, 1])
union = area1 + area2 - inter
# 计算IoU
iou = inter / union.clamp(min=1e-6)
return iou
def box_ciou(box1, box2, eps=1e-7):
"""
计算两个框的CIoU
"""
# 计算交集的左上角和右下角坐标
lt = torch.max(box1[:, :2], box2[:, :2])
rb = torch.min(box1[:,2:], box2[:, 2:])
# 计算交集的宽和高
wh = (rb - lt).clamp(min=0)
# 计算交集面积和并集面积
inter = wh[:, 0] * wh[:, 1]
area1 = (box1[:, 2] - box1[:, 0]) * (box1[:, 3] - box1[:, 1])
area2 = (box2[:, 2] - box2[:, 0]) * (box2[:, 3] - box2[:, 1])
union = area1 + area2 - inter
# 计算IoU
iou = inter / union.clamp(min=1e-6)
# 计算中心点距离
center1 = (box1[:, :2] + box1[:, 2:]) / 2
center2 = (box2[:, :2] + box2[:, 2:]) / 2
dist = ((center1 - center2) ** 2).sum(dim=1)
# 计算最小外接矩形的对角线长度
cwh = (box1[:, 2:] + box1[:, :2] - box2[:, 2:] - box2[:, :2]).clamp(min=0)
c = cwh[:, 0] ** 2 + cwh[:, 1] ** 2
d = dist / c.clamp(min=eps)
# 计算CIoU
v = 4 / (math.pi ** 2) * torch.pow(torch.atan(box1[:, 2] / box1[:, 3]) - torch.atan(box2[:, 2] / box2[:, 3]), 2)
with torch.no_grad():
alpha = v / (1 - iou + v)
ciou = iou - dist / c.clamp(min=eps) - alpha * v
return ciou
def box_siou(box1, box2, delta=0.1, omega=0.5):
"""
计算两个框的SIoU
"""
# 计算IoU
iou = box_iou(box1, box2)
# 计算中心点距离
center1 = (box1[:, :2] + box1[:, 2:]) / 2
center2 = (box2[:, :2] + box2[:, 2:]) / 2
dist = ((center1 - center2) ** 2).sum(dim=1)
# 计算SIoU
siou = 1 - iou + (delta + omega) / 2 * (dist / (1 - iou + delta + omega))
return siou.mean()
```
阅读全文