matcher.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  1. import numpy as np
  2. import torch
  3. class Yolov3Matcher(object):
  4. def __init__(self, num_classes, num_anchors, anchor_size, iou_thresh):
  5. self.num_classes = num_classes
  6. self.num_anchors = num_anchors
  7. self.iou_thresh = iou_thresh
  8. self.anchor_boxes = np.array(
  9. [[0., 0., anchor[0], anchor[1]]
  10. for anchor in anchor_size]
  11. ) # [KA, 4]
  12. def compute_iou(self, anchor_boxes, gt_box):
  13. """
  14. anchor_boxes : ndarray -> [KA, 4] (cx, cy, bw, bh).
  15. gt_box : ndarray -> [1, 4] (cx, cy, bw, bh).
  16. """
  17. # anchors: [KA, 4]
  18. anchors_xyxy = np.zeros_like(anchor_boxes)
  19. anchors_area = anchor_boxes[..., 2] * anchor_boxes[..., 3]
  20. # convert [cx, cy, bw, bh] -> [x1, y1, x2, y2]
  21. anchors_xyxy[..., :2] = anchor_boxes[..., :2] - anchor_boxes[..., 2:] * 0.5 # x1y1
  22. anchors_xyxy[..., 2:] = anchor_boxes[..., :2] + anchor_boxes[..., 2:] * 0.5 # x2y2
  23. # expand gt_box: [1, 4] -> [KA, 4]
  24. gt_box = np.array(gt_box).reshape(-1, 4)
  25. gt_box = np.repeat(gt_box, anchors_xyxy.shape[0], axis=0)
  26. gt_box_area = gt_box[..., 2] * gt_box[..., 3]
  27. # convert [cx, cy, bw, bh] -> [x1, y1, x2, y2]
  28. gt_box_xyxy = np.zeros_like(gt_box)
  29. gt_box_xyxy[..., :2] = gt_box[..., :2] - gt_box[..., 2:] * 0.5 # x1y1
  30. gt_box_xyxy[..., 2:] = gt_box[..., :2] + gt_box[..., 2:] * 0.5 # x2y2
  31. # intersection
  32. inter_w = np.minimum(anchors_xyxy[:, 2], gt_box_xyxy[:, 2]) - \
  33. np.maximum(anchors_xyxy[:, 0], gt_box_xyxy[:, 0])
  34. inter_h = np.minimum(anchors_xyxy[:, 3], gt_box_xyxy[:, 3]) - \
  35. np.maximum(anchors_xyxy[:, 1], gt_box_xyxy[:, 1])
  36. inter_area = inter_w * inter_h
  37. # union
  38. union_area = anchors_area + gt_box_area - inter_area
  39. # iou
  40. iou = inter_area / union_area
  41. iou = np.clip(iou, a_min=1e-10, a_max=1.0)
  42. return iou
  43. @torch.no_grad()
  44. def __call__(self, fmp_sizes, fpn_strides, targets):
  45. """
  46. fmp_size: (List) [fmp_h, fmp_w]
  47. fpn_strides: (List) -> [8, 16, 32, ...] stride of network output.
  48. targets: (Dict) dict{'boxes': [...],
  49. 'labels': [...],
  50. 'orig_size': ...}
  51. """
  52. assert len(fmp_sizes) == len(fpn_strides)
  53. # prepare
  54. bs = len(targets)
  55. gt_objectness = [
  56. torch.zeros([bs, fmp_h, fmp_w, self.num_anchors, 1])
  57. for (fmp_h, fmp_w) in fmp_sizes
  58. ]
  59. gt_classes = [
  60. torch.zeros([bs, fmp_h, fmp_w, self.num_anchors, self.num_classes])
  61. for (fmp_h, fmp_w) in fmp_sizes
  62. ]
  63. gt_bboxes = [
  64. torch.zeros([bs, fmp_h, fmp_w, self.num_anchors, 4])
  65. for (fmp_h, fmp_w) in fmp_sizes
  66. ]
  67. for batch_index in range(bs):
  68. targets_per_image = targets[batch_index]
  69. # [N,]
  70. tgt_cls = targets_per_image["labels"].numpy()
  71. # [N, 4]
  72. tgt_box = targets_per_image['boxes'].numpy()
  73. for gt_box, gt_label in zip(tgt_box, tgt_cls):
  74. # get a bbox coords
  75. x1, y1, x2, y2 = gt_box.tolist()
  76. # xyxy -> cxcywh
  77. xc, yc = (x2 + x1) * 0.5, (y2 + y1) * 0.5
  78. bw, bh = x2 - x1, y2 - y1
  79. gt_box = [0, 0, bw, bh]
  80. # check target
  81. if bw < 1. or bh < 1.:
  82. # invalid target
  83. continue
  84. # compute IoU
  85. iou = self.compute_iou(self.anchor_boxes, gt_box)
  86. iou_mask = (iou > self.iou_thresh)
  87. label_assignment_results = []
  88. if iou_mask.sum() == 0:
  89. # We assign the anchor box with highest IoU score.
  90. iou_ind = np.argmax(iou)
  91. level = iou_ind // self.num_anchors # pyramid level
  92. anchor_idx = iou_ind - level * self.num_anchors # anchor index
  93. # get the corresponding stride
  94. stride = fpn_strides[level]
  95. # compute the grid cell
  96. xc_s = xc / stride
  97. yc_s = yc / stride
  98. grid_x = int(xc_s)
  99. grid_y = int(yc_s)
  100. label_assignment_results.append([grid_x, grid_y, level, anchor_idx])
  101. else:
  102. for iou_ind, iou_m in enumerate(iou_mask):
  103. if iou_m:
  104. level = iou_ind // self.num_anchors # pyramid level
  105. anchor_idx = iou_ind - level * self.num_anchors # anchor index
  106. # get the corresponding stride
  107. stride = fpn_strides[level]
  108. # compute the gride cell
  109. xc_s = xc / stride
  110. yc_s = yc / stride
  111. grid_x = int(xc_s)
  112. grid_y = int(yc_s)
  113. label_assignment_results.append([grid_x, grid_y, level, anchor_idx])
  114. # label assignment
  115. for result in label_assignment_results:
  116. grid_x, grid_y, level, anchor_idx = result
  117. fmp_h, fmp_w = fmp_sizes[level]
  118. if grid_x < fmp_w and grid_y < fmp_h:
  119. # obj
  120. gt_objectness[level][batch_index, grid_y, grid_x, anchor_idx] = 1.0
  121. # cls
  122. cls_ont_hot = torch.zeros(self.num_classes)
  123. cls_ont_hot[int(gt_label)] = 1.0
  124. gt_classes[level][batch_index, grid_y, grid_x, anchor_idx] = cls_ont_hot
  125. # box
  126. gt_bboxes[level][batch_index, grid_y, grid_x, anchor_idx] = torch.as_tensor([x1, y1, x2, y2])
  127. # [B, M, C]
  128. gt_objectness = torch.cat([gt.view(bs, -1, 1) for gt in gt_objectness], dim=1).float()
  129. gt_classes = torch.cat([gt.view(bs, -1, self.num_classes) for gt in gt_classes], dim=1).float()
  130. gt_bboxes = torch.cat([gt.view(bs, -1, 4) for gt in gt_bboxes], dim=1).float()
  131. return gt_objectness, gt_classes, gt_bboxes