loi_heads.py 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353
  1. from typing import Dict, List, Optional, Tuple
  2. import matplotlib.pyplot as plt
  3. import torch
  4. import torch.nn.functional as F
  5. import torchvision
  6. from scipy.optimize import linear_sum_assignment
  7. from torch import nn, Tensor
  8. from libs.vision_libs.ops import boxes as box_ops, roi_align
  9. import libs.vision_libs.models.detection._utils as det_utils
  10. from collections import OrderedDict
  11. def fastrcnn_loss(class_logits, box_regression, labels, regression_targets):
  12. # type: (Tensor, Tensor, List[Tensor], List[Tensor]) -> Tuple[Tensor, Tensor]
  13. """
  14. Computes the loss for Faster R-CNN.
  15. Args:
  16. class_logits (Tensor)
  17. box_regression (Tensor)
  18. labels (list[BoxList])
  19. regression_targets (Tensor)
  20. Returns:
  21. classification_loss (Tensor)
  22. box_loss (Tensor)
  23. """
  24. # print(f'compute fastrcnn_loss:{labels}')
  25. labels = torch.cat(labels, dim=0)
  26. regression_targets = torch.cat(regression_targets, dim=0)
  27. classification_loss = F.cross_entropy(class_logits, labels)
  28. # get indices that correspond to the regression targets for
  29. # the corresponding ground truth labels, to be used with
  30. # advanced indexing
  31. sampled_pos_inds_subset = torch.where(labels > 0)[0]
  32. labels_pos = labels[sampled_pos_inds_subset]
  33. N, num_classes = class_logits.shape
  34. box_regression = box_regression.reshape(N, box_regression.size(-1) // 4, 4)
  35. box_loss = F.smooth_l1_loss(
  36. box_regression[sampled_pos_inds_subset, labels_pos],
  37. regression_targets[sampled_pos_inds_subset],
  38. beta=1 / 9,
  39. reduction="sum",
  40. )
  41. box_loss = box_loss / labels.numel()
  42. return classification_loss, box_loss
  43. def maskrcnn_inference(x, labels):
  44. # type: (Tensor, List[Tensor]) -> List[Tensor]
  45. """
  46. From the results of the CNN, post process the masks
  47. by taking the mask corresponding to the class with max
  48. probability (which are of fixed size and directly output
  49. by the CNN) and return the masks in the mask field of the BoxList.
  50. Args:
  51. x (Tensor): the mask logits
  52. labels (list[BoxList]): bounding boxes that are used as
  53. reference, one for ech image
  54. Returns:
  55. results (list[BoxList]): one BoxList for each image, containing
  56. the extra field mask
  57. """
  58. mask_prob = x.sigmoid()
  59. # select masks corresponding to the predicted classes
  60. num_masks = x.shape[0]
  61. boxes_per_image = [label.shape[0] for label in labels]
  62. labels = torch.cat(labels)
  63. index = torch.arange(num_masks, device=labels.device)
  64. mask_prob = mask_prob[index, labels][:, None]
  65. mask_prob = mask_prob.split(boxes_per_image, dim=0)
  66. return mask_prob
  67. def project_masks_on_boxes(gt_masks, boxes, matched_idxs, M):
  68. # type: (Tensor, Tensor, Tensor, int) -> Tensor
  69. """
  70. Given segmentation masks and the bounding boxes corresponding
  71. to the location of the masks in the image, this function
  72. crops and resizes the masks in the position defined by the
  73. boxes. This prepares the masks for them to be fed to the
  74. loss computation as the targets.
  75. """
  76. matched_idxs = matched_idxs.to(boxes)
  77. rois = torch.cat([matched_idxs[:, None], boxes], dim=1)
  78. gt_masks = gt_masks[:, None].to(rois)
  79. return roi_align(gt_masks, rois, (M, M), 1.0)[:, 0]
  80. def maskrcnn_loss(mask_logits, proposals, gt_masks, gt_labels, mask_matched_idxs):
  81. # type: (Tensor, List[Tensor], List[Tensor], List[Tensor], List[Tensor]) -> Tensor
  82. """
  83. Args:
  84. proposals (list[BoxList])
  85. mask_logits (Tensor)
  86. targets (list[BoxList])
  87. Return:
  88. mask_loss (Tensor): scalar tensor containing the loss
  89. """
  90. discretization_size = mask_logits.shape[-1]
  91. labels = [gt_label[idxs] for gt_label, idxs in zip(gt_labels, mask_matched_idxs)]
  92. mask_targets = [
  93. project_masks_on_boxes(m, p, i, discretization_size) for m, p, i in zip(gt_masks, proposals, mask_matched_idxs)
  94. ]
  95. labels = torch.cat(labels, dim=0)
  96. mask_targets = torch.cat(mask_targets, dim=0)
  97. # torch.mean (in binary_cross_entropy_with_logits) doesn't
  98. # accept empty tensors, so handle it separately
  99. if mask_targets.numel() == 0:
  100. return mask_logits.sum() * 0
  101. mask_loss = F.binary_cross_entropy_with_logits(
  102. mask_logits[torch.arange(labels.shape[0], device=labels.device), labels], mask_targets
  103. )
  104. return mask_loss
  105. def line_points_to_heatmap(keypoints, rois, heatmap_size):
  106. # type: (Tensor, Tensor, int) -> Tuple[Tensor, Tensor]
  107. print(f'rois:{rois.shape}')
  108. print(f'heatmap_size:{heatmap_size}')
  109. offset_x = rois[:, 0]
  110. offset_y = rois[:, 1]
  111. scale_x = heatmap_size / (rois[:, 2] - rois[:, 0])
  112. scale_y = heatmap_size / (rois[:, 3] - rois[:, 1])
  113. offset_x = offset_x[:, None]
  114. offset_y = offset_y[:, None]
  115. scale_x = scale_x[:, None]
  116. scale_y = scale_y[:, None]
  117. print(f'keypoints.shape:{keypoints.shape}')
  118. # batch_size, num_keypoints, _ = keypoints.shape
  119. x = keypoints[..., 0]
  120. y = keypoints[..., 1]
  121. # gs=generate_gaussian_heatmaps(x,y,512,1.0)
  122. # print(f'gs_heatmap shape:{gs.shape}')
  123. #
  124. # show_heatmap(gs,'target')
  125. x_boundary_inds = x == rois[:, 2][:, None]
  126. y_boundary_inds = y == rois[:, 3][:, None]
  127. x = (x - offset_x) * scale_x
  128. x = x.floor().long()
  129. y = (y - offset_y) * scale_y
  130. y = y.floor().long()
  131. x[x_boundary_inds] = heatmap_size - 1
  132. y[y_boundary_inds] = heatmap_size - 1
  133. # print(f'heatmaps x:{x}')
  134. # print(f'heatmaps y:{y}')
  135. valid_loc = (x >= 0) & (y >= 0) & (x < heatmap_size) & (y < heatmap_size)
  136. vis = keypoints[..., 2] > 0
  137. valid = (valid_loc & vis).long()
  138. gs_heatmap=generate_gaussian_heatmaps(x,y,heatmap_size,1.0)
  139. # show_heatmap(gs_heatmap[0],'feature')
  140. print(f'gs_heatmap:{gs_heatmap.shape}')
  141. #
  142. # lin_ind = y * heatmap_size + x
  143. # print(f'lin_ind:{lin_ind.shape}')
  144. # heatmaps = lin_ind * valid
  145. return gs_heatmap
  146. def generate_gaussian_heatmaps(xs, ys, heatmap_size, sigma=2.0, device='cuda'):
  147. """
  148. 为一组点生成并合并高斯热图。
  149. Args:
  150. xs (Tensor): 形状为 (N, 2) 的所有点的 x 坐标
  151. ys (Tensor): 形状为 (N, 2) 的所有点的 y 坐标
  152. heatmap_size (int): 热图大小 H=W
  153. sigma (float): 高斯核标准差
  154. device (str): 设备类型 ('cpu' or 'cuda')
  155. Returns:
  156. Tensor: 形状为 (H, W) 的合并后的热图
  157. """
  158. assert xs.shape == ys.shape, "x and y must have the same shape"
  159. N = xs.shape[0]
  160. print(f'N:{N}')
  161. # 创建网格
  162. grid_y, grid_x = torch.meshgrid(
  163. torch.arange(heatmap_size, device=device),
  164. torch.arange(heatmap_size, device=device),
  165. indexing='ij'
  166. )
  167. # print(f'heatmap_size:{heatmap_size}')
  168. # 初始化输出热图
  169. combined_heatmap = torch.zeros((N,heatmap_size, heatmap_size), device=device)
  170. for i in range(N):
  171. mu_x1 = xs[i, 0].clamp(0, heatmap_size - 1).item()
  172. mu_y1 = ys[i, 0].clamp(0, heatmap_size - 1).item()
  173. # 计算距离平方
  174. dist1 = (grid_x - mu_x1) ** 2 + (grid_y - mu_y1) ** 2
  175. # 计算高斯分布
  176. heatmap1 = torch.exp(-dist1 / (2 * sigma ** 2))
  177. mu_x2 = xs[i, 1].clamp(0, heatmap_size - 1).item()
  178. mu_y2 = ys[i, 1].clamp(0, heatmap_size - 1).item()
  179. # 计算距离平方
  180. dist2 = (grid_x - mu_x2) ** 2 + (grid_y - mu_y2) ** 2
  181. # 计算高斯分布
  182. heatmap2 = torch.exp(-dist2 / (2 * sigma ** 2))
  183. heatmap=heatmap1+heatmap2
  184. # 将当前热图累加到结果中
  185. combined_heatmap[i]= heatmap
  186. return combined_heatmap
  187. # 显示热图的函数
  188. def show_heatmap(heatmap, title="Heatmap"):
  189. """
  190. 使用 matplotlib 显示热图。
  191. Args:
  192. heatmap (Tensor): 要显示的热图张量
  193. title (str): 图表标题
  194. """
  195. # 如果在 GPU 上,首先将其移动到 CPU 并转换为 numpy 数组
  196. if heatmap.is_cuda:
  197. heatmap = heatmap.cpu().numpy()
  198. else:
  199. heatmap = heatmap.numpy()
  200. plt.imshow(heatmap, cmap='hot', interpolation='nearest')
  201. plt.colorbar()
  202. plt.title(title)
  203. plt.show()
  204. def keypoints_to_heatmap(keypoints, rois, heatmap_size):
  205. # type: (Tensor, Tensor, int) -> Tuple[Tensor, Tensor]
  206. offset_x = rois[:, 0]
  207. offset_y = rois[:, 1]
  208. scale_x = heatmap_size / (rois[:, 2] - rois[:, 0])
  209. scale_y = heatmap_size / (rois[:, 3] - rois[:, 1])
  210. offset_x = offset_x[:, None]
  211. offset_y = offset_y[:, None]
  212. scale_x = scale_x[:, None]
  213. scale_y = scale_y[:, None]
  214. x = keypoints[..., 0]
  215. y = keypoints[..., 1]
  216. x_boundary_inds = x == rois[:, 2][:, None]
  217. y_boundary_inds = y == rois[:, 3][:, None]
  218. x = (x - offset_x) * scale_x
  219. x = x.floor().long()
  220. y = (y - offset_y) * scale_y
  221. y = y.floor().long()
  222. x[x_boundary_inds] = heatmap_size - 1
  223. y[y_boundary_inds] = heatmap_size - 1
  224. valid_loc = (x >= 0) & (y >= 0) & (x < heatmap_size) & (y < heatmap_size)
  225. vis = keypoints[..., 2] > 0
  226. valid = (valid_loc & vis).long()
  227. lin_ind = y * heatmap_size + x
  228. heatmaps = lin_ind * valid
  229. return heatmaps, valid
  230. def _onnx_heatmaps_to_keypoints(
  231. maps, maps_i, roi_map_width, roi_map_height, widths_i, heights_i, offset_x_i, offset_y_i
  232. ):
  233. num_keypoints = torch.scalar_tensor(maps.size(1), dtype=torch.int64)
  234. width_correction = widths_i / roi_map_width
  235. height_correction = heights_i / roi_map_height
  236. roi_map = F.interpolate(
  237. maps_i[:, None], size=(int(roi_map_height), int(roi_map_width)), mode="bicubic", align_corners=False
  238. )[:, 0]
  239. w = torch.scalar_tensor(roi_map.size(2), dtype=torch.int64)
  240. pos = roi_map.reshape(num_keypoints, -1).argmax(dim=1)
  241. x_int = pos % w
  242. y_int = (pos - x_int) // w
  243. x = (torch.tensor(0.5, dtype=torch.float32) + x_int.to(dtype=torch.float32)) * width_correction.to(
  244. dtype=torch.float32
  245. )
  246. y = (torch.tensor(0.5, dtype=torch.float32) + y_int.to(dtype=torch.float32)) * height_correction.to(
  247. dtype=torch.float32
  248. )
  249. xy_preds_i_0 = x + offset_x_i.to(dtype=torch.float32)
  250. xy_preds_i_1 = y + offset_y_i.to(dtype=torch.float32)
  251. xy_preds_i_2 = torch.ones(xy_preds_i_1.shape, dtype=torch.float32)
  252. xy_preds_i = torch.stack(
  253. [
  254. xy_preds_i_0.to(dtype=torch.float32),
  255. xy_preds_i_1.to(dtype=torch.float32),
  256. xy_preds_i_2.to(dtype=torch.float32),
  257. ],
  258. 0,
  259. )
  260. # TODO: simplify when indexing without rank will be supported by ONNX
  261. base = num_keypoints * num_keypoints + num_keypoints + 1
  262. ind = torch.arange(num_keypoints)
  263. ind = ind.to(dtype=torch.int64) * base
  264. end_scores_i = (
  265. roi_map.index_select(1, y_int.to(dtype=torch.int64))
  266. .index_select(2, x_int.to(dtype=torch.int64))
  267. .view(-1)
  268. .index_select(0, ind.to(dtype=torch.int64))
  269. )
  270. return xy_preds_i, end_scores_i
  271. @torch.jit._script_if_tracing
  272. def _onnx_heatmaps_to_keypoints_loop(
  273. maps, rois, widths_ceil, heights_ceil, widths, heights, offset_x, offset_y, num_keypoints
  274. ):
  275. xy_preds = torch.zeros((0, 3, int(num_keypoints)), dtype=torch.float32, device=maps.device)
  276. end_scores = torch.zeros((0, int(num_keypoints)), dtype=torch.float32, device=maps.device)
  277. for i in range(int(rois.size(0))):
  278. xy_preds_i, end_scores_i = _onnx_heatmaps_to_keypoints(
  279. maps, maps[i], widths_ceil[i], heights_ceil[i], widths[i], heights[i], offset_x[i], offset_y[i]
  280. )
  281. xy_preds = torch.cat((xy_preds.to(dtype=torch.float32), xy_preds_i.unsqueeze(0).to(dtype=torch.float32)), 0)
  282. end_scores = torch.cat(
  283. (end_scores.to(dtype=torch.float32), end_scores_i.to(dtype=torch.float32).unsqueeze(0)), 0
  284. )
  285. return xy_preds, end_scores
  286. def heatmaps_to_keypoints(maps, rois):
  287. """Extract predicted keypoint locations from heatmaps. Output has shape
  288. (#rois, 4, #keypoints) with the 4 rows corresponding to (x, y, logit, prob)
  289. for each keypoint.
  290. """
  291. # This function converts a discrete image coordinate in a HEATMAP_SIZE x
  292. # HEATMAP_SIZE image to a continuous keypoint coordinate. We maintain
  293. # consistency with keypoints_to_heatmap_labels by using the conversion from
  294. # Heckbert 1990: c = d + 0.5, where d is a discrete coordinate and c is a
  295. # continuous coordinate.
  296. offset_x = rois[:, 0]
  297. offset_y = rois[:, 1]
  298. widths = rois[:, 2] - rois[:, 0]
  299. heights = rois[:, 3] - rois[:, 1]
  300. widths = widths.clamp(min=1)
  301. heights = heights.clamp(min=1)
  302. widths_ceil = widths.ceil()
  303. heights_ceil = heights.ceil()
  304. num_keypoints = maps.shape[1]
  305. if torchvision._is_tracing():
  306. xy_preds, end_scores = _onnx_heatmaps_to_keypoints_loop(
  307. maps,
  308. rois,
  309. widths_ceil,
  310. heights_ceil,
  311. widths,
  312. heights,
  313. offset_x,
  314. offset_y,
  315. torch.scalar_tensor(num_keypoints, dtype=torch.int64),
  316. )
  317. return xy_preds.permute(0, 2, 1), end_scores
  318. xy_preds = torch.zeros((len(rois), 3, num_keypoints), dtype=torch.float32, device=maps.device)
  319. end_scores = torch.zeros((len(rois), num_keypoints), dtype=torch.float32, device=maps.device)
  320. for i in range(len(rois)):
  321. roi_map_width = int(widths_ceil[i].item())
  322. roi_map_height = int(heights_ceil[i].item())
  323. width_correction = widths[i] / roi_map_width
  324. height_correction = heights[i] / roi_map_height
  325. roi_map = F.interpolate(
  326. maps[i][:, None], size=(roi_map_height, roi_map_width), mode="bicubic", align_corners=False
  327. )[:, 0]
  328. # roi_map_probs = scores_to_probs(roi_map.copy())
  329. w = roi_map.shape[2]
  330. pos = roi_map.reshape(num_keypoints, -1).argmax(dim=1)
  331. x_int = pos % w
  332. y_int = torch.div(pos - x_int, w, rounding_mode="floor")
  333. # assert (roi_map_probs[k, y_int, x_int] ==
  334. # roi_map_probs[k, :, :].max())
  335. x = (x_int.float() + 0.5) * width_correction
  336. y = (y_int.float() + 0.5) * height_correction
  337. xy_preds[i, 0, :] = x + offset_x[i]
  338. xy_preds[i, 1, :] = y + offset_y[i]
  339. xy_preds[i, 2, :] = 1
  340. end_scores[i, :] = roi_map[torch.arange(num_keypoints, device=roi_map.device), y_int, x_int]
  341. return xy_preds.permute(0, 2, 1), end_scores
  342. def non_maximum_suppression(a):
  343. ap = F.max_pool2d(a, 3, stride=1, padding=1)
  344. mask = (a == ap).float().clamp(min=0.0)
  345. return a * mask
  346. def heatmaps_to_lines(maps, rois):
  347. """Extract predicted keypoint locations from heatmaps. Output has shape
  348. (#rois, 4, #keypoints) with the 4 rows corresponding to (x, y, logit, prob)
  349. for each keypoint.
  350. """
  351. # This function converts a discrete image coordinate in a HEATMAP_SIZE x
  352. # HEATMAP_SIZE image to a continuous keypoint coordinate. We maintain
  353. # consistency with keypoints_to_heatmap_labels by using the conversion from
  354. # Heckbert 1990: c = d + 0.5, where d is a discrete coordinate and c is a
  355. # continuous coordinate.
  356. offset_x = rois[:, 0]
  357. offset_y = rois[:, 1]
  358. widths = rois[:, 2] - rois[:, 0]
  359. heights = rois[:, 3] - rois[:, 1]
  360. widths = widths.clamp(min=1)
  361. heights = heights.clamp(min=1)
  362. widths_ceil = widths.ceil()
  363. heights_ceil = heights.ceil()
  364. num_keypoints = maps.shape[1]
  365. xy_preds = torch.zeros((len(rois), 3, 2), dtype=torch.float32, device=maps.device)
  366. end_scores = torch.zeros((len(rois), 2), dtype=torch.float32, device=maps.device)
  367. for i in range(len(rois)):
  368. roi_map_width = int(widths_ceil[i].item())
  369. roi_map_height = int(heights_ceil[i].item())
  370. width_correction = widths[i] / roi_map_width
  371. height_correction = heights[i] / roi_map_height
  372. roi_map = F.interpolate(
  373. maps[i][:, None], size=(roi_map_height, roi_map_width), mode="bicubic", align_corners=False
  374. )[:, 0]
  375. print(f'roi_map:{roi_map.shape}')
  376. # roi_map_probs = scores_to_probs(roi_map.copy())
  377. w = roi_map.shape[2]
  378. flatten_map=non_maximum_suppression(roi_map).reshape(1, -1)
  379. score, index = torch.topk(flatten_map, k=2)
  380. print(f'index:{index}')
  381. # pos = roi_map.reshape(num_keypoints, -1).argmax(dim=1)
  382. pos=index
  383. x_int = pos % w
  384. y_int = torch.div(pos - x_int, w, rounding_mode="floor")
  385. # assert (roi_map_probs[k, y_int, x_int] ==
  386. # roi_map_probs[k, :, :].max())
  387. x = (x_int.float() + 0.5) * width_correction
  388. y = (y_int.float() + 0.5) * height_correction
  389. xy_preds[i, 0, :] = x + offset_x[i]
  390. xy_preds[i, 1, :] = y + offset_y[i]
  391. xy_preds[i, 2, :] = 1
  392. end_scores[i, :] = roi_map[torch.arange(1, device=roi_map.device), y_int, x_int]
  393. return xy_preds.permute(0, 2, 1), end_scores
  394. def lines_point_pair_loss(line_logits, proposals, gt_lines, line_matched_idxs):
  395. # type: (Tensor, List[Tensor], List[Tensor], List[Tensor]) -> Tensor
  396. N, K, H, W = line_logits.shape
  397. len_proposals=len(proposals)
  398. print(f'lines_point_pair_loss line_logits.shape:{line_logits.shape},len_proposals:{len_proposals}')
  399. if H != W:
  400. raise ValueError(
  401. f"line_logits height and width (last two elements of shape) should be equal. Instead got H = {H} and W = {W}"
  402. )
  403. discretization_size = H
  404. heatmaps = []
  405. gs_heatmaps=[]
  406. valid = []
  407. for proposals_per_image, gt_kp_in_image, midx in zip(proposals, gt_lines, line_matched_idxs):
  408. print(f'proposals_per_image:{proposals_per_image.shape}')
  409. kp = gt_kp_in_image[midx]
  410. gs_heatmaps_per_img = line_points_to_heatmap(kp, proposals_per_image, discretization_size)
  411. gs_heatmaps.append(gs_heatmaps_per_img)
  412. # print(f'heatmaps_per_image:{heatmaps_per_image.shape}')
  413. # heatmaps.append(heatmaps_per_image.view(-1))
  414. # valid.append(valid_per_image.view(-1))
  415. # line_targets = torch.cat(heatmaps, dim=0)
  416. gs_heatmaps=torch.cat(gs_heatmaps,dim=0)
  417. print(f'gs_heatmaps:{gs_heatmaps.shape}, line_logits.shape:{line_logits.squeeze(1).shape}')
  418. # print(f'line_targets:{line_targets.shape},{line_targets}')
  419. # valid = torch.cat(valid, dim=0).to(dtype=torch.uint8)
  420. # valid = torch.where(valid)[0]
  421. # print(f' line_targets[valid]:{line_targets[valid]}')
  422. # torch.mean (in binary_cross_entropy_with_logits) doesn't
  423. # accept empty tensors, so handle it sepaartely
  424. # if line_targets.numel() == 0 or len(valid) == 0:
  425. # return line_logits.sum() * 0
  426. # line_logits = line_logits.view(N * K, H * W)
  427. # print(f'line_logits[valid]:{line_logits[valid].shape}')
  428. line_logits=line_logits.squeeze(1)
  429. # line_loss = F.cross_entropy(line_logits[valid], line_targets[valid])
  430. line_loss=F.cross_entropy(line_logits,gs_heatmaps)
  431. return line_loss
  432. def lines_to_boxes(lines, img_size=511):
  433. """
  434. 输入:
  435. lines: Tensor of shape (N, 2, 2),表示 N 条线段,每个线段有两个端点 (x, y)
  436. img_size: int,图像尺寸,用于 clamp 边界
  437. 输出:
  438. boxes: Tensor of shape (N, 4),表示 N 个包围盒 [x_min, y_min, x_max, y_max]
  439. """
  440. # 提取所有线段的两个端点
  441. p1 = lines[:, 0] # (N, 2)
  442. p2 = lines[:, 1] # (N, 2)
  443. # 每条线段的 x 和 y 坐标
  444. x_coords = torch.stack([p1[:, 0], p2[:, 0]], dim=1) # (N, 2)
  445. y_coords = torch.stack([p1[:, 1], p2[:, 1]], dim=1) # (N, 2)
  446. # 计算包围盒边界
  447. x_min = x_coords.min(dim=1).values
  448. y_min = y_coords.min(dim=1).values
  449. x_max = x_coords.max(dim=1).values
  450. y_max = y_coords.max(dim=1).values
  451. # 扩展边界并限制在图像范围内
  452. x_min = (x_min - 1).clamp(min=0, max=img_size)
  453. y_min = (y_min - 1).clamp(min=0, max=img_size)
  454. x_max = (x_max + 1).clamp(min=0, max=img_size)
  455. y_max = (y_max + 1).clamp(min=0, max=img_size)
  456. # 合成包围盒
  457. boxes = torch.stack([x_min, y_min, x_max, y_max], dim=1) # (N, 4)
  458. return boxes
  459. def box_iou_pairwise(box1, box2):
  460. """
  461. 输入:
  462. box1: shape (N, 4)
  463. box2: shape (M, 4)
  464. 输出:
  465. ious: shape (min(N, M), ), 只计算 i = j 的配对
  466. """
  467. N = min(len(box1), len(box2))
  468. lt = torch.max(box1[:N, :2], box2[:N, :2]) # 左上角
  469. rb = torch.min(box1[:N, 2:], box2[:N, 2:]) # 右下角
  470. wh = (rb - lt).clamp(min=0) # 宽高
  471. inter_area = wh[:, 0] * wh[:, 1] # 交集面积
  472. area1 = (box1[:N, 2] - box1[:N, 0]) * (box1[:N, 3] - box1[:N, 1])
  473. area2 = (box2[:N, 2] - box2[:N, 0]) * (box2[:N, 3] - box2[:N, 1])
  474. union_area = area1 + area2 - inter_area
  475. ious = inter_area / (union_area + 1e-6)
  476. return ious
  477. def line_iou_loss(x, boxes, gt_lines, matched_idx, img_size=511):
  478. losses = []
  479. boxes_per_image = [box.size(0) for box in boxes]
  480. x2 = x.split(boxes_per_image, dim=0)
  481. for xx, bb, gt_line, mid in zip(x2, boxes, gt_lines, matched_idx):
  482. p_prob, scores = heatmaps_to_lines(xx, bb)
  483. pred_lines = p_prob
  484. gt_line_points = gt_line[mid]
  485. if len(pred_lines) == 0 or len(gt_line_points) == 0:
  486. continue
  487. # ==== 使用新的批量版 lines_to_boxes ====
  488. pred_boxes = lines_to_boxes(pred_lines, img_size)
  489. gt_boxes = lines_to_boxes(gt_line_points, img_size)
  490. # ==== 成对 IoU 计算 ====
  491. ious = box_iou_pairwise(pred_boxes, gt_boxes)
  492. loss = 1.0 - ious
  493. losses.append(loss)
  494. if not losses:
  495. return None
  496. total_loss = torch.mean(torch.cat(losses))
  497. return total_loss
  498. def line_inference(x, boxes):
  499. # type: (Tensor, List[Tensor]) -> Tuple[List[Tensor], List[Tensor]]
  500. points_probs = []
  501. points_scores = []
  502. boxes_per_image = [box.size(0) for box in boxes]
  503. x2 = x.split(boxes_per_image, dim=0)
  504. for xx, bb in zip(x2, boxes):
  505. p_prob, scores = heatmaps_to_lines(xx, bb)
  506. points_probs.append(p_prob)
  507. points_scores.append(scores)
  508. return points_probs, points_scores
  509. def keypointrcnn_loss(keypoint_logits, proposals, gt_keypoints, keypoint_matched_idxs):
  510. # type: (Tensor, List[Tensor], List[Tensor], List[Tensor]) -> Tensor
  511. N, K, H, W = keypoint_logits.shape
  512. if H != W:
  513. raise ValueError(
  514. f"keypoint_logits height and width (last two elements of shape) should be equal. Instead got H = {H} and W = {W}"
  515. )
  516. discretization_size = H
  517. heatmaps = []
  518. valid = []
  519. for proposals_per_image, gt_kp_in_image, midx in zip(proposals, gt_keypoints, keypoint_matched_idxs):
  520. kp = gt_kp_in_image[midx]
  521. heatmaps_per_image, valid_per_image = keypoints_to_heatmap(kp, proposals_per_image, discretization_size)
  522. heatmaps.append(heatmaps_per_image.view(-1))
  523. valid.append(valid_per_image.view(-1))
  524. keypoint_targets = torch.cat(heatmaps, dim=0)
  525. valid = torch.cat(valid, dim=0).to(dtype=torch.uint8)
  526. valid = torch.where(valid)[0]
  527. # torch.mean (in binary_cross_entropy_with_logits) doesn't
  528. # accept empty tensors, so handle it sepaartely
  529. if keypoint_targets.numel() == 0 or len(valid) == 0:
  530. return keypoint_logits.sum() * 0
  531. keypoint_logits = keypoint_logits.view(N * K, H * W)
  532. keypoint_loss = F.cross_entropy(keypoint_logits[valid], keypoint_targets[valid])
  533. return keypoint_loss
  534. def keypointrcnn_inference(x, boxes):
  535. # type: (Tensor, List[Tensor]) -> Tuple[List[Tensor], List[Tensor]]
  536. kp_probs = []
  537. kp_scores = []
  538. boxes_per_image = [box.size(0) for box in boxes]
  539. x2 = x.split(boxes_per_image, dim=0)
  540. for xx, bb in zip(x2, boxes):
  541. kp_prob, scores = heatmaps_to_keypoints(xx, bb)
  542. kp_probs.append(kp_prob)
  543. kp_scores.append(scores)
  544. return kp_probs, kp_scores
  545. def _onnx_expand_boxes(boxes, scale):
  546. # type: (Tensor, float) -> Tensor
  547. w_half = (boxes[:, 2] - boxes[:, 0]) * 0.5
  548. h_half = (boxes[:, 3] - boxes[:, 1]) * 0.5
  549. x_c = (boxes[:, 2] + boxes[:, 0]) * 0.5
  550. y_c = (boxes[:, 3] + boxes[:, 1]) * 0.5
  551. w_half = w_half.to(dtype=torch.float32) * scale
  552. h_half = h_half.to(dtype=torch.float32) * scale
  553. boxes_exp0 = x_c - w_half
  554. boxes_exp1 = y_c - h_half
  555. boxes_exp2 = x_c + w_half
  556. boxes_exp3 = y_c + h_half
  557. boxes_exp = torch.stack((boxes_exp0, boxes_exp1, boxes_exp2, boxes_exp3), 1)
  558. return boxes_exp
  559. # the next two functions should be merged inside Masker
  560. # but are kept here for the moment while we need them
  561. # temporarily for paste_mask_in_image
  562. def expand_boxes(boxes, scale):
  563. # type: (Tensor, float) -> Tensor
  564. if torchvision._is_tracing():
  565. return _onnx_expand_boxes(boxes, scale)
  566. w_half = (boxes[:, 2] - boxes[:, 0]) * 0.5
  567. h_half = (boxes[:, 3] - boxes[:, 1]) * 0.5
  568. x_c = (boxes[:, 2] + boxes[:, 0]) * 0.5
  569. y_c = (boxes[:, 3] + boxes[:, 1]) * 0.5
  570. w_half *= scale
  571. h_half *= scale
  572. boxes_exp = torch.zeros_like(boxes)
  573. boxes_exp[:, 0] = x_c - w_half
  574. boxes_exp[:, 2] = x_c + w_half
  575. boxes_exp[:, 1] = y_c - h_half
  576. boxes_exp[:, 3] = y_c + h_half
  577. return boxes_exp
  578. @torch.jit.unused
  579. def expand_masks_tracing_scale(M, padding):
  580. # type: (int, int) -> float
  581. return torch.tensor(M + 2 * padding).to(torch.float32) / torch.tensor(M).to(torch.float32)
  582. def expand_masks(mask, padding):
  583. # type: (Tensor, int) -> Tuple[Tensor, float]
  584. M = mask.shape[-1]
  585. if torch._C._get_tracing_state(): # could not import is_tracing(), not sure why
  586. scale = expand_masks_tracing_scale(M, padding)
  587. else:
  588. scale = float(M + 2 * padding) / M
  589. padded_mask = F.pad(mask, (padding,) * 4)
  590. return padded_mask, scale
  591. def paste_mask_in_image(mask, box, im_h, im_w):
  592. # type: (Tensor, Tensor, int, int) -> Tensor
  593. TO_REMOVE = 1
  594. w = int(box[2] - box[0] + TO_REMOVE)
  595. h = int(box[3] - box[1] + TO_REMOVE)
  596. w = max(w, 1)
  597. h = max(h, 1)
  598. # Set shape to [batchxCxHxW]
  599. mask = mask.expand((1, 1, -1, -1))
  600. # Resize mask
  601. mask = F.interpolate(mask, size=(h, w), mode="bilinear", align_corners=False)
  602. mask = mask[0][0]
  603. im_mask = torch.zeros((im_h, im_w), dtype=mask.dtype, device=mask.device)
  604. x_0 = max(box[0], 0)
  605. x_1 = min(box[2] + 1, im_w)
  606. y_0 = max(box[1], 0)
  607. y_1 = min(box[3] + 1, im_h)
  608. im_mask[y_0:y_1, x_0:x_1] = mask[(y_0 - box[1]) : (y_1 - box[1]), (x_0 - box[0]) : (x_1 - box[0])]
  609. return im_mask
  610. def _onnx_paste_mask_in_image(mask, box, im_h, im_w):
  611. one = torch.ones(1, dtype=torch.int64)
  612. zero = torch.zeros(1, dtype=torch.int64)
  613. w = box[2] - box[0] + one
  614. h = box[3] - box[1] + one
  615. w = torch.max(torch.cat((w, one)))
  616. h = torch.max(torch.cat((h, one)))
  617. # Set shape to [batchxCxHxW]
  618. mask = mask.expand((1, 1, mask.size(0), mask.size(1)))
  619. # Resize mask
  620. mask = F.interpolate(mask, size=(int(h), int(w)), mode="bilinear", align_corners=False)
  621. mask = mask[0][0]
  622. x_0 = torch.max(torch.cat((box[0].unsqueeze(0), zero)))
  623. x_1 = torch.min(torch.cat((box[2].unsqueeze(0) + one, im_w.unsqueeze(0))))
  624. y_0 = torch.max(torch.cat((box[1].unsqueeze(0), zero)))
  625. y_1 = torch.min(torch.cat((box[3].unsqueeze(0) + one, im_h.unsqueeze(0))))
  626. unpaded_im_mask = mask[(y_0 - box[1]) : (y_1 - box[1]), (x_0 - box[0]) : (x_1 - box[0])]
  627. # TODO : replace below with a dynamic padding when support is added in ONNX
  628. # pad y
  629. zeros_y0 = torch.zeros(y_0, unpaded_im_mask.size(1))
  630. zeros_y1 = torch.zeros(im_h - y_1, unpaded_im_mask.size(1))
  631. concat_0 = torch.cat((zeros_y0, unpaded_im_mask.to(dtype=torch.float32), zeros_y1), 0)[0:im_h, :]
  632. # pad x
  633. zeros_x0 = torch.zeros(concat_0.size(0), x_0)
  634. zeros_x1 = torch.zeros(concat_0.size(0), im_w - x_1)
  635. im_mask = torch.cat((zeros_x0, concat_0, zeros_x1), 1)[:, :im_w]
  636. return im_mask
  637. @torch.jit._script_if_tracing
  638. def _onnx_paste_masks_in_image_loop(masks, boxes, im_h, im_w):
  639. res_append = torch.zeros(0, im_h, im_w)
  640. for i in range(masks.size(0)):
  641. mask_res = _onnx_paste_mask_in_image(masks[i][0], boxes[i], im_h, im_w)
  642. mask_res = mask_res.unsqueeze(0)
  643. res_append = torch.cat((res_append, mask_res))
  644. return res_append
  645. def paste_masks_in_image(masks, boxes, img_shape, padding=1):
  646. # type: (Tensor, Tensor, Tuple[int, int], int) -> Tensor
  647. masks, scale = expand_masks(masks, padding=padding)
  648. boxes = expand_boxes(boxes, scale).to(dtype=torch.int64)
  649. im_h, im_w = img_shape
  650. if torchvision._is_tracing():
  651. return _onnx_paste_masks_in_image_loop(
  652. masks, boxes, torch.scalar_tensor(im_h, dtype=torch.int64), torch.scalar_tensor(im_w, dtype=torch.int64)
  653. )[:, None]
  654. res = [paste_mask_in_image(m[0], b, im_h, im_w) for m, b in zip(masks, boxes)]
  655. if len(res) > 0:
  656. ret = torch.stack(res, dim=0)[:, None]
  657. else:
  658. ret = masks.new_empty((0, 1, im_h, im_w))
  659. return ret
  660. class RoIHeads(nn.Module):
  661. __annotations__ = {
  662. "box_coder": det_utils.BoxCoder,
  663. "proposal_matcher": det_utils.Matcher,
  664. "fg_bg_sampler": det_utils.BalancedPositiveNegativeSampler,
  665. }
  666. def __init__(
  667. self,
  668. box_roi_pool,
  669. box_head,
  670. box_predictor,
  671. # Faster R-CNN training
  672. fg_iou_thresh,
  673. bg_iou_thresh,
  674. batch_size_per_image,
  675. positive_fraction,
  676. bbox_reg_weights,
  677. # Faster R-CNN inference
  678. score_thresh,
  679. nms_thresh,
  680. detections_per_img,
  681. # Line
  682. line_roi_pool=None,
  683. line_head=None,
  684. line_predictor=None,
  685. # Mask
  686. mask_roi_pool=None,
  687. mask_head=None,
  688. mask_predictor=None,
  689. keypoint_roi_pool=None,
  690. keypoint_head=None,
  691. keypoint_predictor=None,
  692. ):
  693. super().__init__()
  694. self.box_similarity = box_ops.box_iou
  695. # assign ground-truth boxes for each proposal
  696. self.proposal_matcher = det_utils.Matcher(fg_iou_thresh, bg_iou_thresh, allow_low_quality_matches=False)
  697. self.fg_bg_sampler = det_utils.BalancedPositiveNegativeSampler(batch_size_per_image, positive_fraction)
  698. if bbox_reg_weights is None:
  699. bbox_reg_weights = (10.0, 10.0, 5.0, 5.0)
  700. self.box_coder = det_utils.BoxCoder(bbox_reg_weights)
  701. self.box_roi_pool = box_roi_pool
  702. self.box_head = box_head
  703. self.box_predictor = box_predictor
  704. self.score_thresh = score_thresh
  705. self.nms_thresh = nms_thresh
  706. self.detections_per_img = detections_per_img
  707. self.line_roi_pool = line_roi_pool
  708. self.line_head = line_head
  709. self.line_predictor = line_predictor
  710. self.mask_roi_pool = mask_roi_pool
  711. self.mask_head = mask_head
  712. self.mask_predictor = mask_predictor
  713. self.keypoint_roi_pool = keypoint_roi_pool
  714. self.keypoint_head = keypoint_head
  715. self.keypoint_predictor = keypoint_predictor
  716. def has_mask(self):
  717. if self.mask_roi_pool is None:
  718. return False
  719. if self.mask_head is None:
  720. return False
  721. if self.mask_predictor is None:
  722. return False
  723. return True
  724. def has_keypoint(self):
  725. if self.keypoint_roi_pool is None:
  726. return False
  727. if self.keypoint_head is None:
  728. return False
  729. if self.keypoint_predictor is None:
  730. return False
  731. return True
  732. def has_line(self):
  733. if self.line_roi_pool is None:
  734. return False
  735. if self.line_head is None:
  736. return False
  737. if self.line_predictor is None:
  738. return False
  739. return True
  740. def assign_targets_to_proposals(self, proposals, gt_boxes, gt_labels):
  741. # type: (List[Tensor], List[Tensor], List[Tensor]) -> Tuple[List[Tensor], List[Tensor]]
  742. matched_idxs = []
  743. labels = []
  744. for proposals_in_image, gt_boxes_in_image, gt_labels_in_image in zip(proposals, gt_boxes, gt_labels):
  745. if gt_boxes_in_image.numel() == 0:
  746. # Background image
  747. device = proposals_in_image.device
  748. clamped_matched_idxs_in_image = torch.zeros(
  749. (proposals_in_image.shape[0],), dtype=torch.int64, device=device
  750. )
  751. labels_in_image = torch.zeros((proposals_in_image.shape[0],), dtype=torch.int64, device=device)
  752. else:
  753. # set to self.box_similarity when https://github.com/pytorch/pytorch/issues/27495 lands
  754. match_quality_matrix = box_ops.box_iou(gt_boxes_in_image, proposals_in_image)
  755. matched_idxs_in_image = self.proposal_matcher(match_quality_matrix)
  756. clamped_matched_idxs_in_image = matched_idxs_in_image.clamp(min=0)
  757. labels_in_image = gt_labels_in_image[clamped_matched_idxs_in_image]
  758. labels_in_image = labels_in_image.to(dtype=torch.int64)
  759. # Label background (below the low threshold)
  760. bg_inds = matched_idxs_in_image == self.proposal_matcher.BELOW_LOW_THRESHOLD
  761. labels_in_image[bg_inds] = 0
  762. # Label ignore proposals (between low and high thresholds)
  763. ignore_inds = matched_idxs_in_image == self.proposal_matcher.BETWEEN_THRESHOLDS
  764. labels_in_image[ignore_inds] = -1 # -1 is ignored by sampler
  765. matched_idxs.append(clamped_matched_idxs_in_image)
  766. labels.append(labels_in_image)
  767. return matched_idxs, labels
  768. def subsample(self, labels):
  769. # type: (List[Tensor]) -> List[Tensor]
  770. sampled_pos_inds, sampled_neg_inds = self.fg_bg_sampler(labels)
  771. sampled_inds = []
  772. for img_idx, (pos_inds_img, neg_inds_img) in enumerate(zip(sampled_pos_inds, sampled_neg_inds)):
  773. img_sampled_inds = torch.where(pos_inds_img | neg_inds_img)[0]
  774. sampled_inds.append(img_sampled_inds)
  775. return sampled_inds
  776. def add_gt_proposals(self, proposals, gt_boxes):
  777. # type: (List[Tensor], List[Tensor]) -> List[Tensor]
  778. proposals = [torch.cat((proposal, gt_box)) for proposal, gt_box in zip(proposals, gt_boxes)]
  779. return proposals
  780. def check_targets(self, targets):
  781. # type: (Optional[List[Dict[str, Tensor]]]) -> None
  782. if targets is None:
  783. raise ValueError("targets should not be None")
  784. if not all(["boxes" in t for t in targets]):
  785. raise ValueError("Every element of targets should have a boxes key")
  786. if not all(["labels" in t for t in targets]):
  787. raise ValueError("Every element of targets should have a labels key")
  788. if self.has_mask():
  789. if not all(["masks" in t for t in targets]):
  790. raise ValueError("Every element of targets should have a masks key")
  791. def select_training_samples(
  792. self,
  793. proposals, # type: List[Tensor]
  794. targets, # type: Optional[List[Dict[str, Tensor]]]
  795. ):
  796. # type: (...) -> Tuple[List[Tensor], List[Tensor], List[Tensor], List[Tensor]]
  797. self.check_targets(targets)
  798. if targets is None:
  799. raise ValueError("targets should not be None")
  800. dtype = proposals[0].dtype
  801. device = proposals[0].device
  802. gt_boxes = [t["boxes"].to(dtype) for t in targets]
  803. gt_labels = [t["labels"] for t in targets]
  804. # append ground-truth bboxes to propos
  805. proposals = self.add_gt_proposals(proposals, gt_boxes)
  806. # get matching gt indices for each proposal
  807. matched_idxs, labels = self.assign_targets_to_proposals(proposals, gt_boxes, gt_labels)
  808. # sample a fixed proportion of positive-negative proposals
  809. sampled_inds = self.subsample(labels)
  810. matched_gt_boxes = []
  811. num_images = len(proposals)
  812. for img_id in range(num_images):
  813. img_sampled_inds = sampled_inds[img_id]
  814. proposals[img_id] = proposals[img_id][img_sampled_inds]
  815. labels[img_id] = labels[img_id][img_sampled_inds]
  816. matched_idxs[img_id] = matched_idxs[img_id][img_sampled_inds]
  817. gt_boxes_in_image = gt_boxes[img_id]
  818. if gt_boxes_in_image.numel() == 0:
  819. gt_boxes_in_image = torch.zeros((1, 4), dtype=dtype, device=device)
  820. matched_gt_boxes.append(gt_boxes_in_image[matched_idxs[img_id]])
  821. regression_targets = self.box_coder.encode(matched_gt_boxes, proposals)
  822. return proposals, matched_idxs, labels, regression_targets
  823. def postprocess_detections(
  824. self,
  825. class_logits, # type: Tensor
  826. box_regression, # type: Tensor
  827. proposals, # type: List[Tensor]
  828. image_shapes, # type: List[Tuple[int, int]]
  829. ):
  830. # type: (...) -> Tuple[List[Tensor], List[Tensor], List[Tensor]]
  831. device = class_logits.device
  832. num_classes = class_logits.shape[-1]
  833. boxes_per_image = [boxes_in_image.shape[0] for boxes_in_image in proposals]
  834. pred_boxes = self.box_coder.decode(box_regression, proposals)
  835. pred_scores = F.softmax(class_logits, -1)
  836. pred_boxes_list = pred_boxes.split(boxes_per_image, 0)
  837. pred_scores_list = pred_scores.split(boxes_per_image, 0)
  838. all_boxes = []
  839. all_scores = []
  840. all_labels = []
  841. for boxes, scores, image_shape in zip(pred_boxes_list, pred_scores_list, image_shapes):
  842. boxes = box_ops.clip_boxes_to_image(boxes, image_shape)
  843. # create labels for each prediction
  844. labels = torch.arange(num_classes, device=device)
  845. labels = labels.view(1, -1).expand_as(scores)
  846. # remove predictions with the background label
  847. boxes = boxes[:, 1:]
  848. scores = scores[:, 1:]
  849. labels = labels[:, 1:]
  850. # batch everything, by making every class prediction be a separate instance
  851. boxes = boxes.reshape(-1, 4)
  852. scores = scores.reshape(-1)
  853. labels = labels.reshape(-1)
  854. # remove low scoring boxes
  855. inds = torch.where(scores > self.score_thresh)[0]
  856. boxes, scores, labels = boxes[inds], scores[inds], labels[inds]
  857. # remove empty boxes
  858. keep = box_ops.remove_small_boxes(boxes, min_size=1e-2)
  859. boxes, scores, labels = boxes[keep], scores[keep], labels[keep]
  860. # non-maximum suppression, independently done per class
  861. keep = box_ops.batched_nms(boxes, scores, labels, self.nms_thresh)
  862. # keep only topk scoring predictions
  863. keep = keep[: self.detections_per_img]
  864. boxes, scores, labels = boxes[keep], scores[keep], labels[keep]
  865. all_boxes.append(boxes)
  866. all_scores.append(scores)
  867. all_labels.append(labels)
  868. return all_boxes, all_scores, all_labels
  869. def forward(
  870. self,
  871. features, # type: Dict[str, Tensor]
  872. proposals, # type: List[Tensor]
  873. image_shapes, # type: List[Tuple[int, int]]
  874. targets=None, # type: Optional[List[Dict[str, Tensor]]]
  875. ):
  876. # type: (...) -> Tuple[List[Dict[str, Tensor]], Dict[str, Tensor]]
  877. """
  878. Args:
  879. features (List[Tensor])
  880. proposals (List[Tensor[N, 4]])
  881. image_shapes (List[Tuple[H, W]])
  882. targets (List[Dict])
  883. """
  884. print(f'roihead forward!!!')
  885. if targets is not None:
  886. for t in targets:
  887. # TODO: https://github.com/pytorch/pytorch/issues/26731
  888. floating_point_types = (torch.float, torch.double, torch.half)
  889. if not t["boxes"].dtype in floating_point_types:
  890. raise TypeError(f"target boxes must of float type, instead got {t['boxes'].dtype}")
  891. if not t["labels"].dtype == torch.int64:
  892. raise TypeError(f"target labels must of int64 type, instead got {t['labels'].dtype}")
  893. if self.has_keypoint():
  894. if not t["keypoints"].dtype == torch.float32:
  895. raise TypeError(f"target keypoints must of float type, instead got {t['keypoints'].dtype}")
  896. if self.training:
  897. proposals, matched_idxs, labels, regression_targets = self.select_training_samples(proposals, targets)
  898. else:
  899. if targets is not None:
  900. proposals, matched_idxs, labels, regression_targets = self.select_training_samples(proposals, targets)
  901. else:
  902. labels = None
  903. regression_targets = None
  904. matched_idxs = None
  905. box_features = self.box_roi_pool(features, proposals, image_shapes)
  906. box_features = self.box_head(box_features)
  907. class_logits, box_regression = self.box_predictor(box_features)
  908. result: List[Dict[str, torch.Tensor]] = []
  909. losses = {}
  910. # _, C, H, W = features['0'].shape # 忽略 batch_size,因为我们只关心 C, H, W
  911. if self.training:
  912. if labels is None:
  913. raise ValueError("labels cannot be None")
  914. if regression_targets is None:
  915. raise ValueError("regression_targets cannot be None")
  916. print(f'boxes compute losses')
  917. loss_classifier, loss_box_reg = fastrcnn_loss(class_logits, box_regression, labels, regression_targets)
  918. losses = {"loss_classifier": loss_classifier, "loss_box_reg": loss_box_reg}
  919. else:
  920. if targets is not None:
  921. loss_classifier, loss_box_reg = fastrcnn_loss(class_logits, box_regression, labels, regression_targets)
  922. losses = {"loss_classifier": loss_classifier, "loss_box_reg": loss_box_reg}
  923. boxes, scores, labels = self.postprocess_detections(class_logits, box_regression, proposals,
  924. image_shapes)
  925. num_images = len(boxes)
  926. for i in range(num_images):
  927. result.append(
  928. {
  929. "boxes": boxes[i],
  930. "labels": labels[i],
  931. "scores": scores[i],
  932. }
  933. )
  934. if self.has_line():
  935. print(f'roi_heads forward has_line()!!!!')
  936. line_proposals = [p["boxes"] for p in result]
  937. print(f'boxes_proposals:{len(line_proposals)}')
  938. # if line_proposals is None or len(line_proposals) == 0:
  939. # # 返回空特征或者跳过该部分计算
  940. # return torch.empty(0, C, H, W).to(features['0'].device)
  941. if self.training:
  942. # during training, only focus on positive boxes
  943. num_images = len(proposals)
  944. print(f'num_images:{num_images}')
  945. line_proposals = []
  946. pos_matched_idxs = []
  947. if matched_idxs is None:
  948. raise ValueError("if in trainning, matched_idxs should not be None")
  949. for img_id in range(num_images):
  950. pos = torch.where(labels[img_id] > 0)[0]
  951. line_proposals.append(proposals[img_id][pos])
  952. pos_matched_idxs.append(matched_idxs[img_id][pos])
  953. else:
  954. if targets is not None:
  955. pos_matched_idxs = []
  956. num_images = len(proposals)
  957. line_proposals = []
  958. print(f'val num_images:{num_images}')
  959. if matched_idxs is None:
  960. raise ValueError("if in trainning, matched_idxs should not be None")
  961. for img_id in range(num_images):
  962. pos = torch.where(labels[img_id] > 0)[0]
  963. line_proposals.append(proposals[img_id][pos])
  964. pos_matched_idxs.append(matched_idxs[img_id][pos])
  965. else:
  966. pos_matched_idxs = None
  967. print(f'line_proposals:{len(line_proposals)}')
  968. line_features = self.line_roi_pool(features, line_proposals, image_shapes)
  969. print(f'line_features from line_roi_pool:{line_features.shape}')
  970. line_features = self.line_head(line_features)
  971. print(f'line_features from line_head:{line_features.shape}')
  972. line_logits = self.line_predictor(line_features)
  973. print(f'line_logits:{line_logits.shape}')
  974. loss_line = {}
  975. loss_line_iou={}
  976. img_size=512
  977. if self.training:
  978. if targets is None or pos_matched_idxs is None:
  979. raise ValueError("both targets and pos_matched_idxs should not be None when in training mode")
  980. gt_lines = [t["lines"] for t in targets]
  981. rcnn_loss_line = lines_point_pair_loss(
  982. line_logits, line_proposals, gt_lines, pos_matched_idxs
  983. )
  984. iou_loss = line_iou_loss(line_logits, line_proposals, gt_lines, pos_matched_idxs,img_size)
  985. loss_line = {"loss_line": rcnn_loss_line}
  986. loss_line_iou = {'loss_line_iou': iou_loss}
  987. else:
  988. if targets is not None:
  989. gt_lines = [t["lines"] for t in targets]
  990. rcnn_loss_lines = lines_point_pair_loss(
  991. line_logits, line_proposals, gt_lines, pos_matched_idxs
  992. )
  993. loss_line = {"loss_line": rcnn_loss_lines}
  994. iou_loss =line_iou_loss(line_logits, line_proposals,gt_lines,pos_matched_idxs,img_size)
  995. loss_line_iou={'loss_line_iou':iou_loss}
  996. else:
  997. if line_logits is None or line_proposals is None:
  998. raise ValueError(
  999. "both keypoint_logits and keypoint_proposals should not be None when not in training mode"
  1000. )
  1001. lines_probs, kp_scores = line_inference(line_logits, line_proposals)
  1002. for keypoint_prob, kps, r in zip(lines_probs, kp_scores, result):
  1003. r["lines"] = keypoint_prob
  1004. r["liness_scores"] = kps
  1005. losses.update(loss_line)
  1006. losses.update(loss_line_iou)
  1007. if self.has_mask():
  1008. mask_proposals = [p["boxes"] for p in result]
  1009. if self.training:
  1010. if matched_idxs is None:
  1011. raise ValueError("if in training, matched_idxs should not be None")
  1012. # during training, only focus on positive boxes
  1013. num_images = len(proposals)
  1014. mask_proposals = []
  1015. pos_matched_idxs = []
  1016. for img_id in range(num_images):
  1017. pos = torch.where(labels[img_id] > 0)[0]
  1018. mask_proposals.append(proposals[img_id][pos])
  1019. pos_matched_idxs.append(matched_idxs[img_id][pos])
  1020. else:
  1021. pos_matched_idxs = None
  1022. if self.mask_roi_pool is not None:
  1023. mask_features = self.mask_roi_pool(features, mask_proposals, image_shapes)
  1024. mask_features = self.mask_head(mask_features)
  1025. mask_logits = self.mask_predictor(mask_features)
  1026. else:
  1027. raise Exception("Expected mask_roi_pool to be not None")
  1028. loss_mask = {}
  1029. if self.training:
  1030. if targets is None or pos_matched_idxs is None or mask_logits is None:
  1031. raise ValueError("targets, pos_matched_idxs, mask_logits cannot be None when training")
  1032. gt_masks = [t["masks"] for t in targets]
  1033. gt_labels = [t["labels"] for t in targets]
  1034. rcnn_loss_mask = maskrcnn_loss(mask_logits, mask_proposals, gt_masks, gt_labels, pos_matched_idxs)
  1035. loss_mask = {"loss_mask": rcnn_loss_mask}
  1036. else:
  1037. labels = [r["labels"] for r in result]
  1038. masks_probs = maskrcnn_inference(mask_logits, labels)
  1039. for mask_prob, r in zip(masks_probs, result):
  1040. r["masks"] = mask_prob
  1041. losses.update(loss_mask)
  1042. # keep none checks in if conditional so torchscript will conditionally
  1043. # compile each branch
  1044. if self.has_keypoint():
  1045. keypoint_proposals = [p["boxes"] for p in result]
  1046. if self.training:
  1047. # during training, only focus on positive boxes
  1048. num_images = len(proposals)
  1049. keypoint_proposals = []
  1050. pos_matched_idxs = []
  1051. if matched_idxs is None:
  1052. raise ValueError("if in trainning, matched_idxs should not be None")
  1053. for img_id in range(num_images):
  1054. pos = torch.where(labels[img_id] > 0)[0]
  1055. keypoint_proposals.append(proposals[img_id][pos])
  1056. pos_matched_idxs.append(matched_idxs[img_id][pos])
  1057. else:
  1058. pos_matched_idxs = None
  1059. keypoint_features = self.line_roi_pool(features, keypoint_proposals, image_shapes)
  1060. keypoint_features = self.line_head(keypoint_features)
  1061. keypoint_logits = self.line_predictor(keypoint_features)
  1062. loss_keypoint = {}
  1063. if self.training:
  1064. if targets is None or pos_matched_idxs is None:
  1065. raise ValueError("both targets and pos_matched_idxs should not be None when in training mode")
  1066. gt_keypoints = [t["keypoints"] for t in targets]
  1067. rcnn_loss_keypoint = keypointrcnn_loss(
  1068. keypoint_logits, keypoint_proposals, gt_keypoints, pos_matched_idxs
  1069. )
  1070. loss_keypoint = {"loss_keypoint": rcnn_loss_keypoint}
  1071. else:
  1072. if keypoint_logits is None or keypoint_proposals is None:
  1073. raise ValueError(
  1074. "both keypoint_logits and keypoint_proposals should not be None when not in training mode"
  1075. )
  1076. keypoints_probs, kp_scores = keypointrcnn_inference(keypoint_logits, keypoint_proposals)
  1077. for keypoint_prob, kps, r in zip(keypoints_probs, kp_scores, result):
  1078. r["keypoints"] = keypoint_prob
  1079. r["keypoints_scores"] = kps
  1080. losses.update(loss_keypoint)
  1081. return result, losses