yolov1.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. import torch
  2. import torch.nn as nn
  3. import numpy as np
  4. from .yolov1_basic import Conv
  5. from .yolov1_neck import SPP
  6. from .yolov1_backbone import build_resnet
  7. # YOLOv1
  8. class YOLOv1(nn.Module):
  9. def __init__(self,
  10. device,
  11. img_size=None,
  12. num_classes=20,
  13. conf_thresh=0.01,
  14. nms_thresh=0.5,
  15. trainable=False):
  16. super(YOLOv1, self).__init__()
  17. # ------------------- Basic parameters -------------------
  18. self.img_size = img_size # 输入图像大小
  19. self.device = device # cuda或者是cpu
  20. self.num_classes = num_classes # 类别的数量
  21. self.trainable = trainable # 训练的标记
  22. self.conf_thresh = conf_thresh # 得分阈值
  23. self.nms_thresh = nms_thresh # NMS阈值
  24. self.stride = 32 # 网络的最大步长
  25. # ------------------- Network Structure -------------------
  26. ## backbone: resnet18
  27. self.backbone, feat_dim = build_resnet('resnet18', pretrained=trainable)
  28. ## neck: SPP
  29. self.neck = nn.Sequential(
  30. SPP(),
  31. Conv(feat_dim*4, feat_dim, k=1),
  32. )
  33. ## head
  34. self.convsets = nn.Sequential(
  35. Conv(feat_dim, feat_dim//2, k=1),
  36. Conv(feat_dim//2, feat_dim, k=3, p=1),
  37. Conv(feat_dim, feat_dim//2, k=1),
  38. Conv(feat_dim//2, feat_dim, k=3, p=1)
  39. )
  40. ## pred
  41. self.pred = nn.Conv2d(feat_dim, 1 + self.num_classes + 4, 1)
  42. if self.trainable:
  43. self.init_bias()
  44. def init_bias(self):
  45. # init bias
  46. init_prob = 0.01
  47. bias_value = -torch.log(torch.tensor((1. - init_prob) / init_prob))
  48. nn.init.constant_(self.pred.bias[..., :1], bias_value)
  49. nn.init.constant_(self.pred.bias[..., 1:1+self.num_classes], bias_value)
  50. def create_grid(self, fmp_size):
  51. """
  52. 用于生成G矩阵,其中每个元素都是特征图上的像素坐标。
  53. """
  54. # 特征图的宽和高
  55. ws, hs = fmp_size
  56. # 生成网格的x坐标和y坐标
  57. grid_y, grid_x = torch.meshgrid([torch.arange(hs), torch.arange(ws)])
  58. # 将xy两部分的坐标拼起来:[H, W, 2]
  59. grid_xy = torch.stack([grid_x, grid_y], dim=-1).float()
  60. # [H, W, 2] -> [HW, 2] -> [HW, 2]
  61. grid_xy = grid_xy.view(-1, 2).to(self.device)
  62. return grid_xy
  63. def set_grid(self, img_size):
  64. """
  65. 用于重置G矩阵。
  66. """
  67. self.img_size = img_size
  68. self.grid_cell = self.create_grid(img_size)
  69. def decode_boxes(self, pred, fmp_size):
  70. """
  71. 将txtytwth转换为常用的x1y1x2y2形式。
  72. """
  73. # 生成网格坐标矩阵
  74. grid_cell = self.create_grid(fmp_size)
  75. # 计算预测边界框的中心点坐标和宽高
  76. pred[..., :2] = torch.sigmoid(pred[..., :2]) + grid_cell
  77. pred[..., 2:] = torch.exp(pred[..., 2:])
  78. # 将所有bbox的中心带你坐标和宽高换算成x1y1x2y2形式
  79. output = torch.zeros_like(pred)
  80. output[..., :2] = pred[..., :2] * self.stride - pred[..., 2:] * 0.5
  81. output[..., 2:] = pred[..., :2] * self.stride + pred[..., 2:] * 0.5
  82. return output
  83. def nms(self, bboxes, scores):
  84. """"Pure Python NMS baseline."""
  85. x1 = bboxes[:, 0] #xmin
  86. y1 = bboxes[:, 1] #ymin
  87. x2 = bboxes[:, 2] #xmax
  88. y2 = bboxes[:, 3] #ymax
  89. areas = (x2 - x1) * (y2 - y1)
  90. order = scores.argsort()[::-1]
  91. keep = []
  92. while order.size > 0:
  93. i = order[0]
  94. keep.append(i)
  95. # 计算交集的左上角点和右下角点的坐标
  96. xx1 = np.maximum(x1[i], x1[order[1:]])
  97. yy1 = np.maximum(y1[i], y1[order[1:]])
  98. xx2 = np.minimum(x2[i], x2[order[1:]])
  99. yy2 = np.minimum(y2[i], y2[order[1:]])
  100. # 计算交集的宽高
  101. w = np.maximum(1e-10, xx2 - xx1)
  102. h = np.maximum(1e-10, yy2 - yy1)
  103. # 计算交集的面积
  104. inter = w * h
  105. # 计算交并比
  106. iou = inter / (areas[i] + areas[order[1:]] - inter)
  107. # 滤除超过nms阈值的检测框
  108. inds = np.where(iou <= self.nms_thresh)[0]
  109. order = order[inds + 1]
  110. return keep
  111. def postprocess(self, bboxes, scores):
  112. """
  113. Input:
  114. bboxes: [HxW, 4]
  115. scores: [HxW, num_classes]
  116. Output:
  117. bboxes: [N, 4]
  118. score: [N,]
  119. labels: [N,]
  120. """
  121. labels = np.argmax(scores, axis=1)
  122. scores = scores[(np.arange(scores.shape[0]), labels)]
  123. # threshold
  124. keep = np.where(scores >= self.conf_thresh)
  125. bboxes = bboxes[keep]
  126. scores = scores[keep]
  127. labels = labels[keep]
  128. # NMS
  129. keep = np.zeros(len(bboxes), dtype=np.int)
  130. for i in range(self.num_classes):
  131. inds = np.where(labels == i)[0]
  132. if len(inds) == 0:
  133. continue
  134. c_bboxes = bboxes[inds]
  135. c_scores = scores[inds]
  136. c_keep = self.nms(c_bboxes, c_scores)
  137. keep[inds[c_keep]] = 1
  138. keep = np.where(keep > 0)
  139. bboxes = bboxes[keep]
  140. scores = scores[keep]
  141. labels = labels[keep]
  142. return bboxes, scores, labels
  143. @torch.no_grad()
  144. def inference(self, x):
  145. # backbone主干网络
  146. feat = self.backbone(x)
  147. # neck网络
  148. feat = self.neck(feat)
  149. # detection head网络
  150. feat = self.convsets(feat)
  151. # 预测层
  152. pred = self.pred(feat)
  153. fmp_size = pred.shape[-2:]
  154. # 对pred 的size做一些view调整,便于后续的处理
  155. # [B, C, H, W] -> [B, H, W, C] -> [B, H*W, C]
  156. pred = pred.permute(0, 2, 3, 1).contiguous().flatten(1, 2)
  157. # 从pred中分离出objectness预测、类别class预测、bbox的txtytwth预测
  158. # [B, H*W, 1]
  159. conf_pred = pred[..., :1]
  160. # [B, H*W, num_cls]
  161. cls_pred = pred[..., 1:1+self.num_classes]
  162. # [B, H*W, 4]
  163. txtytwth_pred = pred[..., 1+self.num_classes:]
  164. # 测试时,笔者默认batch是1,
  165. # 因此,我们不需要用batch这个维度,用[0]将其取走。
  166. conf_pred = conf_pred[0] #[H*W, 1]
  167. cls_pred = cls_pred[0] #[H*W, NC]
  168. txtytwth_pred = txtytwth_pred[0] #[H*W, 4]
  169. # 每个边界框的得分
  170. scores = torch.sigmoid(conf_pred) * torch.softmax(cls_pred, dim=-1)
  171. # 解算边界框, 并归一化边界框: [H*W, 4]
  172. bboxes = self.decode_boxes(txtytwth_pred, fmp_size)
  173. # 将预测放在cpu处理上,以便进行后处理
  174. scores = scores.to('cpu').numpy()
  175. bboxes = bboxes.to('cpu').numpy()
  176. # 后处理
  177. bboxes, scores, labels = self.postprocess(bboxes, scores)
  178. return bboxes, scores, labels
  179. def forward(self, x):
  180. if not self.trainable:
  181. return self.inference(x)
  182. else:
  183. # backbone主干网络
  184. feat = self.backbone(x)
  185. # neck网络
  186. feat = self.neck(feat)
  187. # detection head网络
  188. feat = self.convsets(feat)
  189. # 预测层
  190. pred = self.pred(feat)
  191. # 对pred 的size做一些view调整,便于后续的处理
  192. # [B, C, H, W] -> [B, H, W, C] -> [B, H*W, C]
  193. pred = pred.permute(0, 2, 3, 1).contiguous().flatten(1, 2)
  194. # 从pred中分离出objectness预测、类别class预测、bbox的txtytwth预测
  195. # [B, H*W, 1]
  196. conf_pred = pred[..., :1]
  197. # [B, H*W, num_cls]
  198. cls_pred = pred[..., 1:1+self.num_classes]
  199. # [B, H*W, 4]
  200. txtytwth_pred = pred[..., 1+self.num_classes:]
  201. # 网络输出
  202. outputs = {"pred_obj": conf_pred, # (Tensor) [B, M, 1]
  203. "pred_cls": cls_pred, # (Tensor) [B, M, C]
  204. "pred_txty": txtytwth_pred[..., :2], # (Tensor) [B, M, 2]
  205. "pred_twth": txtytwth_pred[..., 2:], # (Tensor) [B, M, 2]
  206. "stride": self.stride, # (Int)
  207. "img_size": x.shape[-2:] # (List) [img_h, img_w]
  208. }
  209. return outputs