您现在的位置是:首页 > 技术教程 正文

YOLOV8改进-添加EIOU,SIOU,AlphaIOU,FocalEIOU,WIOU.

admin 阅读: 2024-03-19
后台-插件-广告管理-内容页头部广告(手机)

目录

1替换计算框iou的代码

1.1原代码

1.2替换代码

2修改调用函数

2.1原代码

2.2替换代码

3参数修改


本文介绍的是在yolov8模型上修改成其他的IOU,各种IOU需要自己测试才知道效果。

1替换计算框iou的代码

        将ultralytics/yolo/utils/metrics.py路径下的def bbox_iou替换为其他代码

1.1原代码

  1. def bbox_iou(box1, box2, xywh=True, GIoU=False, DIoU=False, CIoU=False, eps=1e-7):
  2. """
  3. Calculate Intersection over Union (IoU) of box1(1, 4) to box2(n, 4).
  4. Args:
  5. box1 (torch.Tensor): A tensor representing a single bounding box with shape (1, 4).
  6. box2 (torch.Tensor): A tensor representing n bounding boxes with shape (n, 4).
  7. xywh (bool, optional): If True, input boxes are in (x, y, w, h) format. If False, input boxes are in
  8. (x1, y1, x2, y2) format. Defaults to True.
  9. GIoU (bool, optional): If True, calculate Generalized IoU. Defaults to False.
  10. DIoU (bool, optional): If True, calculate Distance IoU. Defaults to False.
  11. CIoU (bool, optional): If True, calculate Complete IoU. Defaults to False.
  12. eps (float, optional): A small value to avoid division by zero. Defaults to 1e-7.
  13. Returns:
  14. (torch.Tensor): IoU, GIoU, DIoU, or CIoU values depending on the specified flags.
  15. """
  16. # Get the coordinates of bounding boxes
  17. if xywh: # transform from xywh to xyxy
  18. (x1, y1, w1, h1), (x2, y2, w2, h2) = box1.chunk(4, -1), box2.chunk(4, -1)
  19. w1_, h1_, w2_, h2_ = w1 / 2, h1 / 2, w2 / 2, h2 / 2
  20. b1_x1, b1_x2, b1_y1, b1_y2 = x1 - w1_, x1 + w1_, y1 - h1_, y1 + h1_
  21. b2_x1, b2_x2, b2_y1, b2_y2 = x2 - w2_, x2 + w2_, y2 - h2_, y2 + h2_
  22. else: # x1, y1, x2, y2 = box1
  23. b1_x1, b1_y1, b1_x2, b1_y2 = box1.chunk(4, -1)
  24. b2_x1, b2_y1, b2_x2, b2_y2 = box2.chunk(4, -1)
  25. w1, h1 = b1_x2 - b1_x1, b1_y2 - b1_y1 + eps
  26. w2, h2 = b2_x2 - b2_x1, b2_y2 - b2_y1 + eps
  27. # Intersection area
  28. inter = (b1_x2.minimum(b2_x2) - b1_x1.maximum(b2_x1)).clamp(0) * \
  29. (b1_y2.minimum(b2_y2) - b1_y1.maximum(b2_y1)).clamp(0)
  30. # Union Area
  31. union = w1 * h1 + w2 * h2 - inter + eps
  32. # IoU
  33. iou = inter / union
  34. if CIoU or DIoU or GIoU:
  35. cw = b1_x2.maximum(b2_x2) - b1_x1.minimum(b2_x1) # convex (smallest enclosing box) width
  36. ch = b1_y2.maximum(b2_y2) - b1_y1.minimum(b2_y1) # convex height
  37. if CIoU or DIoU: # Distance or Complete IoU https://arxiv.org/abs/1911.08287v1
  38. c2 = cw ** 2 + ch ** 2 + eps # convex diagonal squared
  39. rho2 = ((b2_x1 + b2_x2 - b1_x1 - b1_x2) ** 2 + (b2_y1 + b2_y2 - b1_y1 - b1_y2) ** 2) / 4 # center dist ** 2
  40. if CIoU: # https://github.com/Zzh-tju/DIoU-SSD-pytorch/blob/master/utils/box/box_utils.py#L47
  41. v = (4 / math.pi ** 2) * (torch.atan(w2 / h2) - torch.atan(w1 / h1)).pow(2)
  42. with torch.no_grad():
  43. alpha = v / (v - iou + (1 + eps))
  44. return iou - (rho2 / c2 + v * alpha) # CIoU
  45. return iou - rho2 / c2 # DIoU
  46. c_area = cw * ch + eps # convex area
  47. return iou - (c_area - union) / c_area # GIoU https://arxiv.org/pdf/1902.09630.pdf
  48. return iou # IoU

1.2替换代码

  1. class WIoU_Scale:
  2. ''' monotonous: {
  3. None: origin v1
  4. True: monotonic FM v2
  5. False: non-monotonic FM v3
  6. }
  7. momentum: The momentum of running mean'''
  8. iou_mean = 1.
  9. monotonous = False
  10. _momentum = 1 - 0.5 ** (1 / 7000)
  11. _is_train = True
  12. def __init__(self, iou):
  13. self.iou = iou
  14. self._update(self)
  15. @classmethod
  16. def _update(cls, self):
  17. if cls._is_train: cls.iou_mean = (1 - cls._momentum) * cls.iou_mean + \
  18. cls._momentum * self.iou.detach().mean().item()
  19. @classmethod
  20. def _scaled_loss(cls, self, gamma=1.9, delta=3):
  21. if isinstance(self.monotonous, bool):
  22. if self.monotonous:
  23. return (self.iou.detach() / self.iou_mean).sqrt()
  24. else:
  25. beta = self.iou.detach() / self.iou_mean
  26. alpha = delta * torch.pow(gamma, beta - delta)
  27. return beta / alpha
  28. return 1
  29. def bbox_iou(box1, box2, xywh=True, GIoU=False, DIoU=False, CIoU=False, SIoU=False, EIoU=False, WIoU=False, Focal=False,
  30. alpha=1, gamma=0.5, scale=False, eps=1e-7):
  31. # Returns Intersection over Union (IoU) of box1(1,4) to box2(n,4)
  32. # Get the coordinates of bounding boxes
  33. if xywh: # transform from xywh to xyxy
  34. (x1, y1, w1, h1), (x2, y2, w2, h2) = box1.chunk(4, -1), box2.chunk(4, -1)
  35. w1_, h1_, w2_, h2_ = w1 / 2, h1 / 2, w2 / 2, h2 / 2
  36. b1_x1, b1_x2, b1_y1, b1_y2 = x1 - w1_, x1 + w1_, y1 - h1_, y1 + h1_
  37. b2_x1, b2_x2, b2_y1, b2_y2 = x2 - w2_, x2 + w2_, y2 - h2_, y2 + h2_
  38. else: # x1, y1, x2, y2 = box1
  39. b1_x1, b1_y1, b1_x2, b1_y2 = box1.chunk(4, -1)
  40. b2_x1, b2_y1, b2_x2, b2_y2 = box2.chunk(4, -1)
  41. w1, h1 = b1_x2 - b1_x1, (b1_y2 - b1_y1).clamp(eps)
  42. w2, h2 = b2_x2 - b2_x1, (b2_y2 - b2_y1).clamp(eps)
  43. # Intersection area
  44. inter = (b1_x2.minimum(b2_x2) - b1_x1.maximum(b2_x1)).clamp(0) * \
  45. (b1_y2.minimum(b2_y2) - b1_y1.maximum(b2_y1)).clamp(0)
  46. # Union Area
  47. union = w1 * h1 + w2 * h2 - inter + eps
  48. if scale:
  49. self = WIoU_Scale(1 - (inter / union))
  50. # IoU
  51. # iou = inter / union # ori iou
  52. iou = torch.pow(inter / (union + eps), alpha) # alpha iou
  53. if CIoU or DIoU or GIoU or EIoU or SIoU or WIoU:
  54. cw = b1_x2.maximum(b2_x2) - b1_x1.minimum(b2_x1) # convex (smallest enclosing box) width
  55. ch = b1_y2.maximum(b2_y2) - b1_y1.minimum(b2_y1) # convex height
  56. if CIoU or DIoU or EIoU or SIoU or WIoU: # Distance or Complete IoU https://arxiv.org/abs/1911.08287v1
  57. c2 = (cw ** 2 + ch ** 2) ** alpha + eps # convex diagonal squared
  58. rho2 = (((b2_x1 + b2_x2 - b1_x1 - b1_x2) ** 2 + (
  59. b2_y1 + b2_y2 - b1_y1 - b1_y2) ** 2) / 4) ** alpha # center dist ** 2
  60. if CIoU: # https://github.com/Zzh-tju/DIoU-SSD-pytorch/blob/master/utils/box/box_utils.py#L47
  61. v = (4 / math.pi ** 2) * (torch.atan(w2 / h2) - torch.atan(w1 / h1)).pow(2)
  62. with torch.no_grad():
  63. alpha_ciou = v / (v - iou + (1 + eps))
  64. if Focal:
  65. return iou - (rho2 / c2 + torch.pow(v * alpha_ciou + eps, alpha)), torch.pow(inter / (union + eps),
  66. gamma) # Focal_CIoU
  67. else:
  68. return iou - (rho2 / c2 + torch.pow(v * alpha_ciou + eps, alpha)) # CIoU
  69. elif EIoU:
  70. rho_w2 = ((b2_x2 - b2_x1) - (b1_x2 - b1_x1)) ** 2
  71. rho_h2 = ((b2_y2 - b2_y1) - (b1_y2 - b1_y1)) ** 2
  72. cw2 = torch.pow(cw ** 2 + eps, alpha)
  73. ch2 = torch.pow(ch ** 2 + eps, alpha)
  74. if Focal:
  75. return iou - (rho2 / c2 + rho_w2 / cw2 + rho_h2 / ch2), torch.pow(inter / (union + eps),
  76. gamma) # Focal_EIou
  77. else:
  78. return iou - (rho2 / c2 + rho_w2 / cw2 + rho_h2 / ch2) # EIou
  79. elif SIoU:
  80. # SIoU Loss https://arxiv.org/pdf/2205.12740.pdf
  81. s_cw = (b2_x1 + b2_x2 - b1_x1 - b1_x2) * 0.5 + eps
  82. s_ch = (b2_y1 + b2_y2 - b1_y1 - b1_y2) * 0.5 + eps
  83. sigma = torch.pow(s_cw ** 2 + s_ch ** 2, 0.5)
  84. sin_alpha_1 = torch.abs(s_cw) / sigma
  85. sin_alpha_2 = torch.abs(s_ch) / sigma
  86. threshold = pow(2, 0.5) / 2
  87. sin_alpha = torch.where(sin_alpha_1 > threshold, sin_alpha_2, sin_alpha_1)
  88. angle_cost = torch.cos(torch.arcsin(sin_alpha) * 2 - math.pi / 2)
  89. rho_x = (s_cw / cw) ** 2
  90. rho_y = (s_ch / ch) ** 2
  91. gamma = angle_cost - 2
  92. distance_cost = 2 - torch.exp(gamma * rho_x) - torch.exp(gamma * rho_y)
  93. omiga_w = torch.abs(w1 - w2) / torch.max(w1, w2)
  94. omiga_h = torch.abs(h1 - h2) / torch.max(h1, h2)
  95. shape_cost = torch.pow(1 - torch.exp(-1 * omiga_w), 4) + torch.pow(1 - torch.exp(-1 * omiga_h), 4)
  96. if Focal:
  97. return iou - torch.pow(0.5 * (distance_cost + shape_cost) + eps, alpha), torch.pow(
  98. inter / (union + eps), gamma) # Focal_SIou
  99. else:
  100. return iou - torch.pow(0.5 * (distance_cost + shape_cost) + eps, alpha) # SIou
  101. elif WIoU:
  102. if Focal:
  103. raise RuntimeError("WIoU do not support Focal.")
  104. elif scale:
  105. return getattr(WIoU_Scale, '_scaled_loss')(self), (1 - iou) * torch.exp(
  106. (rho2 / c2)), iou # WIoU https://arxiv.org/abs/2301.10051
  107. else:
  108. return iou, torch.exp((rho2 / c2)) # WIoU v1
  109. if Focal:
  110. return iou - rho2 / c2, torch.pow(inter / (union + eps), gamma) # Focal_DIoU
  111. else:
  112. return iou - rho2 / c2 # DIoU
  113. c_area = cw * ch + eps # convex area
  114. if Focal:
  115. return iou - torch.pow((c_area - union) / c_area + eps, alpha), torch.pow(inter / (union + eps),
  116. gamma) # Focal_GIoU https://arxiv.org/pdf/1902.09630.pdf
  117. else:
  118. return iou - torch.pow((c_area - union) / c_area + eps, alpha) # GIoU https://arxiv.org/pdf/1902.09630.pdf
  119. if Focal:
  120. return iou, torch.pow(inter / (union + eps), gamma) # Focal_IoU
  121. else:
  122. return iou # IoU

2修改调用函数

替换ultralytics/yolo/utils/loss.py路径下class BboxLoss类的def forward函数

2.1原代码

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

2.2替换代码

  1. iou = bbox_iou(pred_bboxes[fg_mask], target_bboxes[fg_mask], xywh=False, WIoU=True,scale=True)
  2. if type(iou) is tuple:
  3. if len(iou) == 2:
  4. loss_iou = ((1.0 - iou[0]) * iou[1].detach() * weight).sum() / target_scores_sum
  5. else:
  6. loss_iou = (iou[0] * iou[1] * weight).sum() / target_scores_sum
  7. else:
  8. loss_iou = ((1.0 - iou) * weight).sum() / target_scores_sum

3参数修改

将其中的想使用的IOU设置为True,如WIoU=True,保留一个使用的即可。

iou = bbox_iou(pred_bboxes[fg_mask], target_bboxes[fg_mask], xywh=False, WIoU=True,scale=True)

如果出现报错可能是因为其他的类也调用IOU计算,发生冲突。找到其他调用,将其他的修改。

在ultralytics/yolo/utils/tal.py路径下class TaskAlignedAssigner,其中def get_box_metrics函数

将代码

overlaps[mask_gt] = bbox_iou(gt_boxes, pd_boxes, xywh=False, CIoU=True).squeeze(-1).clamp(0)

替换为

overlaps[mask_gt] = bbox_iou(gt_boxes, pd_boxes, xywh=False).squeeze(-1).clamp(0)

标签:
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

在线投稿:投稿 站长QQ:1888636

后台-插件-广告管理-内容页尾部广告(手机)
关注我们

扫一扫关注我们,了解最新精彩内容

搜索