loi_heads.py 52 KB

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