loi_heads.py 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399
  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_features_align(features, proposals, img_size):
  395. print(f'lines_features_align features:{features.shape}')
  396. for feat, proposals_per_img in zip(features,proposals):
  397. # print(f'lines_features_align feat:{feat.shape}, proposals_per_img:{proposals_per_img.shape}')
  398. align_feat_list=[]
  399. feat=feat.unsqueeze(0)
  400. for proposal in proposals_per_img:
  401. align_feat = torch.zeros_like(feat)
  402. # print(f'align_feat:{align_feat.shape}')
  403. x1, y1, x2, y2 = map(lambda v: int(v.item()), proposal)
  404. # 将每个proposal框内的部分赋值到align_feats对应位置
  405. align_feat[:,:, y1:y2 + 1, x1:x2 + 1] = feat[:,:, y1:y2 + 1, x1:x2 + 1]
  406. align_feat_list.append(align_feat)
  407. feats_tensor=torch.cat(align_feat_list)
  408. print(f'align features :{feats_tensor.shape}')
  409. return feats_tensor
  410. def lines_point_pair_loss(line_logits, proposals, gt_lines, line_matched_idxs):
  411. # type: (Tensor, List[Tensor], List[Tensor], List[Tensor]) -> Tensor
  412. N, K, H, W = line_logits.shape
  413. len_proposals=len(proposals)
  414. print(f'lines_point_pair_loss line_logits.shape:{line_logits.shape},len_proposals:{len_proposals}')
  415. if H != W:
  416. raise ValueError(
  417. f"line_logits height and width (last two elements of shape) should be equal. Instead got H = {H} and W = {W}"
  418. )
  419. discretization_size = H
  420. heatmaps = []
  421. gs_heatmaps=[]
  422. valid = []
  423. for proposals_per_image, gt_kp_in_image, midx in zip(proposals, gt_lines, line_matched_idxs):
  424. print(f'proposals_per_image:{proposals_per_image.shape}')
  425. kp = gt_kp_in_image[midx]
  426. gs_heatmaps_per_img = line_points_to_heatmap(kp, proposals_per_image, discretization_size)
  427. gs_heatmaps.append(gs_heatmaps_per_img)
  428. # print(f'heatmaps_per_image:{heatmaps_per_image.shape}')
  429. # heatmaps.append(heatmaps_per_image.view(-1))
  430. # valid.append(valid_per_image.view(-1))
  431. # line_targets = torch.cat(heatmaps, dim=0)
  432. gs_heatmaps=torch.cat(gs_heatmaps,dim=0)
  433. print(f'gs_heatmaps:{gs_heatmaps.shape}, line_logits.shape:{line_logits.squeeze(1).shape}')
  434. # print(f'line_targets:{line_targets.shape},{line_targets}')
  435. # valid = torch.cat(valid, dim=0).to(dtype=torch.uint8)
  436. # valid = torch.where(valid)[0]
  437. # print(f' line_targets[valid]:{line_targets[valid]}')
  438. # torch.mean (in binary_cross_entropy_with_logits) doesn't
  439. # accept empty tensors, so handle it sepaartely
  440. # if line_targets.numel() == 0 or len(valid) == 0:
  441. # return line_logits.sum() * 0
  442. # line_logits = line_logits.view(N * K, H * W)
  443. # print(f'line_logits[valid]:{line_logits[valid].shape}')
  444. line_logits=line_logits.squeeze(1)
  445. # line_loss = F.cross_entropy(line_logits[valid], line_targets[valid])
  446. line_loss=F.cross_entropy(line_logits,gs_heatmaps)
  447. return line_loss
  448. def lines_to_boxes(lines, img_size=511):
  449. """
  450. 输入:
  451. lines: Tensor of shape (N, 2, 2),表示 N 条线段,每个线段有两个端点 (x, y)
  452. img_size: int,图像尺寸,用于 clamp 边界
  453. 输出:
  454. boxes: Tensor of shape (N, 4),表示 N 个包围盒 [x_min, y_min, x_max, y_max]
  455. """
  456. # 提取所有线段的两个端点
  457. p1 = lines[:, 0] # (N, 2)
  458. p2 = lines[:, 1] # (N, 2)
  459. # 每条线段的 x 和 y 坐标
  460. x_coords = torch.stack([p1[:, 0], p2[:, 0]], dim=1) # (N, 2)
  461. y_coords = torch.stack([p1[:, 1], p2[:, 1]], dim=1) # (N, 2)
  462. # 计算包围盒边界
  463. x_min = x_coords.min(dim=1).values
  464. y_min = y_coords.min(dim=1).values
  465. x_max = x_coords.max(dim=1).values
  466. y_max = y_coords.max(dim=1).values
  467. # 扩展边界并限制在图像范围内
  468. x_min = (x_min - 1).clamp(min=0, max=img_size)
  469. y_min = (y_min - 1).clamp(min=0, max=img_size)
  470. x_max = (x_max + 1).clamp(min=0, max=img_size)
  471. y_max = (y_max + 1).clamp(min=0, max=img_size)
  472. # 合成包围盒
  473. boxes = torch.stack([x_min, y_min, x_max, y_max], dim=1) # (N, 4)
  474. return boxes
  475. def box_iou_pairwise(box1, box2):
  476. """
  477. 输入:
  478. box1: shape (N, 4)
  479. box2: shape (M, 4)
  480. 输出:
  481. ious: shape (min(N, M), ), 只计算 i = j 的配对
  482. """
  483. N = min(len(box1), len(box2))
  484. lt = torch.max(box1[:N, :2], box2[:N, :2]) # 左上角
  485. rb = torch.min(box1[:N, 2:], box2[:N, 2:]) # 右下角
  486. wh = (rb - lt).clamp(min=0) # 宽高
  487. inter_area = wh[:, 0] * wh[:, 1] # 交集面积
  488. area1 = (box1[:N, 2] - box1[:N, 0]) * (box1[:N, 3] - box1[:N, 1])
  489. area2 = (box2[:N, 2] - box2[:N, 0]) * (box2[:N, 3] - box2[:N, 1])
  490. union_area = area1 + area2 - inter_area
  491. ious = inter_area / (union_area + 1e-6)
  492. return ious
  493. def line_iou_loss(x, boxes, gt_lines, matched_idx, img_size=511):
  494. losses = []
  495. boxes_per_image = [box.size(0) for box in boxes]
  496. x2 = x.split(boxes_per_image, dim=0)
  497. for xx, bb, gt_line, mid in zip(x2, boxes, gt_lines, matched_idx):
  498. p_prob, scores = heatmaps_to_lines(xx, bb)
  499. pred_lines = p_prob
  500. gt_line_points = gt_line[mid]
  501. if len(pred_lines) == 0 or len(gt_line_points) == 0:
  502. continue
  503. pred_boxes = lines_to_boxes(pred_lines, img_size)
  504. gt_boxes = lines_to_boxes(gt_line_points, img_size)
  505. ious = box_iou_pairwise(pred_boxes, gt_boxes)
  506. loss = 1.0 - ious
  507. losses.append(loss)
  508. if not losses: # 如果损失列表为空,则返回默认值或抛出自定义异常
  509. print("Warning: No valid losses were computed.")
  510. return torch.tensor(1.0, requires_grad=True).to(x.device) # 返回一个标量张量
  511. total_loss = torch.mean(torch.cat(losses))
  512. return total_loss
  513. def line_inference(x, boxes):
  514. # type: (Tensor, List[Tensor]) -> Tuple[List[Tensor], List[Tensor]]
  515. points_probs = []
  516. points_scores = []
  517. boxes_per_image = [box.size(0) for box in boxes]
  518. x2 = x.split(boxes_per_image, dim=0)
  519. for xx, bb in zip(x2, boxes):
  520. p_prob, scores = heatmaps_to_lines(xx, bb)
  521. points_probs.append(p_prob)
  522. points_scores.append(scores)
  523. return points_probs, points_scores
  524. def keypointrcnn_loss(keypoint_logits, proposals, gt_keypoints, keypoint_matched_idxs):
  525. # type: (Tensor, List[Tensor], List[Tensor], List[Tensor]) -> Tensor
  526. N, K, H, W = keypoint_logits.shape
  527. if H != W:
  528. raise ValueError(
  529. f"keypoint_logits height and width (last two elements of shape) should be equal. Instead got H = {H} and W = {W}"
  530. )
  531. discretization_size = H
  532. heatmaps = []
  533. valid = []
  534. for proposals_per_image, gt_kp_in_image, midx in zip(proposals, gt_keypoints, keypoint_matched_idxs):
  535. kp = gt_kp_in_image[midx]
  536. heatmaps_per_image, valid_per_image = keypoints_to_heatmap(kp, proposals_per_image, discretization_size)
  537. heatmaps.append(heatmaps_per_image.view(-1))
  538. valid.append(valid_per_image.view(-1))
  539. keypoint_targets = torch.cat(heatmaps, dim=0)
  540. valid = torch.cat(valid, dim=0).to(dtype=torch.uint8)
  541. valid = torch.where(valid)[0]
  542. # torch.mean (in binary_cross_entropy_with_logits) doesn't
  543. # accept empty tensors, so handle it sepaartely
  544. if keypoint_targets.numel() == 0 or len(valid) == 0:
  545. return keypoint_logits.sum() * 0
  546. keypoint_logits = keypoint_logits.view(N * K, H * W)
  547. keypoint_loss = F.cross_entropy(keypoint_logits[valid], keypoint_targets[valid])
  548. return keypoint_loss
  549. def keypointrcnn_inference(x, boxes):
  550. # type: (Tensor, List[Tensor]) -> Tuple[List[Tensor], List[Tensor]]
  551. kp_probs = []
  552. kp_scores = []
  553. boxes_per_image = [box.size(0) for box in boxes]
  554. x2 = x.split(boxes_per_image, dim=0)
  555. for xx, bb in zip(x2, boxes):
  556. kp_prob, scores = heatmaps_to_keypoints(xx, bb)
  557. kp_probs.append(kp_prob)
  558. kp_scores.append(scores)
  559. return kp_probs, kp_scores
  560. def _onnx_expand_boxes(boxes, scale):
  561. # type: (Tensor, float) -> Tensor
  562. w_half = (boxes[:, 2] - boxes[:, 0]) * 0.5
  563. h_half = (boxes[:, 3] - boxes[:, 1]) * 0.5
  564. x_c = (boxes[:, 2] + boxes[:, 0]) * 0.5
  565. y_c = (boxes[:, 3] + boxes[:, 1]) * 0.5
  566. w_half = w_half.to(dtype=torch.float32) * scale
  567. h_half = h_half.to(dtype=torch.float32) * scale
  568. boxes_exp0 = x_c - w_half
  569. boxes_exp1 = y_c - h_half
  570. boxes_exp2 = x_c + w_half
  571. boxes_exp3 = y_c + h_half
  572. boxes_exp = torch.stack((boxes_exp0, boxes_exp1, boxes_exp2, boxes_exp3), 1)
  573. return boxes_exp
  574. # the next two functions should be merged inside Masker
  575. # but are kept here for the moment while we need them
  576. # temporarily for paste_mask_in_image
  577. def expand_boxes(boxes, scale):
  578. # type: (Tensor, float) -> Tensor
  579. if torchvision._is_tracing():
  580. return _onnx_expand_boxes(boxes, scale)
  581. w_half = (boxes[:, 2] - boxes[:, 0]) * 0.5
  582. h_half = (boxes[:, 3] - boxes[:, 1]) * 0.5
  583. x_c = (boxes[:, 2] + boxes[:, 0]) * 0.5
  584. y_c = (boxes[:, 3] + boxes[:, 1]) * 0.5
  585. w_half *= scale
  586. h_half *= scale
  587. boxes_exp = torch.zeros_like(boxes)
  588. boxes_exp[:, 0] = x_c - w_half
  589. boxes_exp[:, 2] = x_c + w_half
  590. boxes_exp[:, 1] = y_c - h_half
  591. boxes_exp[:, 3] = y_c + h_half
  592. return boxes_exp
  593. @torch.jit.unused
  594. def expand_masks_tracing_scale(M, padding):
  595. # type: (int, int) -> float
  596. return torch.tensor(M + 2 * padding).to(torch.float32) / torch.tensor(M).to(torch.float32)
  597. def expand_masks(mask, padding):
  598. # type: (Tensor, int) -> Tuple[Tensor, float]
  599. M = mask.shape[-1]
  600. if torch._C._get_tracing_state(): # could not import is_tracing(), not sure why
  601. scale = expand_masks_tracing_scale(M, padding)
  602. else:
  603. scale = float(M + 2 * padding) / M
  604. padded_mask = F.pad(mask, (padding,) * 4)
  605. return padded_mask, scale
  606. def paste_mask_in_image(mask, box, im_h, im_w):
  607. # type: (Tensor, Tensor, int, int) -> Tensor
  608. TO_REMOVE = 1
  609. w = int(box[2] - box[0] + TO_REMOVE)
  610. h = int(box[3] - box[1] + TO_REMOVE)
  611. w = max(w, 1)
  612. h = max(h, 1)
  613. # Set shape to [batchxCxHxW]
  614. mask = mask.expand((1, 1, -1, -1))
  615. # Resize mask
  616. mask = F.interpolate(mask, size=(h, w), mode="bilinear", align_corners=False)
  617. mask = mask[0][0]
  618. im_mask = torch.zeros((im_h, im_w), dtype=mask.dtype, device=mask.device)
  619. x_0 = max(box[0], 0)
  620. x_1 = min(box[2] + 1, im_w)
  621. y_0 = max(box[1], 0)
  622. y_1 = min(box[3] + 1, im_h)
  623. 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])]
  624. return im_mask
  625. def _onnx_paste_mask_in_image(mask, box, im_h, im_w):
  626. one = torch.ones(1, dtype=torch.int64)
  627. zero = torch.zeros(1, dtype=torch.int64)
  628. w = box[2] - box[0] + one
  629. h = box[3] - box[1] + one
  630. w = torch.max(torch.cat((w, one)))
  631. h = torch.max(torch.cat((h, one)))
  632. # Set shape to [batchxCxHxW]
  633. mask = mask.expand((1, 1, mask.size(0), mask.size(1)))
  634. # Resize mask
  635. mask = F.interpolate(mask, size=(int(h), int(w)), mode="bilinear", align_corners=False)
  636. mask = mask[0][0]
  637. x_0 = torch.max(torch.cat((box[0].unsqueeze(0), zero)))
  638. x_1 = torch.min(torch.cat((box[2].unsqueeze(0) + one, im_w.unsqueeze(0))))
  639. y_0 = torch.max(torch.cat((box[1].unsqueeze(0), zero)))
  640. y_1 = torch.min(torch.cat((box[3].unsqueeze(0) + one, im_h.unsqueeze(0))))
  641. unpaded_im_mask = mask[(y_0 - box[1]) : (y_1 - box[1]), (x_0 - box[0]) : (x_1 - box[0])]
  642. # TODO : replace below with a dynamic padding when support is added in ONNX
  643. # pad y
  644. zeros_y0 = torch.zeros(y_0, unpaded_im_mask.size(1))
  645. zeros_y1 = torch.zeros(im_h - y_1, unpaded_im_mask.size(1))
  646. concat_0 = torch.cat((zeros_y0, unpaded_im_mask.to(dtype=torch.float32), zeros_y1), 0)[0:im_h, :]
  647. # pad x
  648. zeros_x0 = torch.zeros(concat_0.size(0), x_0)
  649. zeros_x1 = torch.zeros(concat_0.size(0), im_w - x_1)
  650. im_mask = torch.cat((zeros_x0, concat_0, zeros_x1), 1)[:, :im_w]
  651. return im_mask
  652. @torch.jit._script_if_tracing
  653. def _onnx_paste_masks_in_image_loop(masks, boxes, im_h, im_w):
  654. res_append = torch.zeros(0, im_h, im_w)
  655. for i in range(masks.size(0)):
  656. mask_res = _onnx_paste_mask_in_image(masks[i][0], boxes[i], im_h, im_w)
  657. mask_res = mask_res.unsqueeze(0)
  658. res_append = torch.cat((res_append, mask_res))
  659. return res_append
  660. def paste_masks_in_image(masks, boxes, img_shape, padding=1):
  661. # type: (Tensor, Tensor, Tuple[int, int], int) -> Tensor
  662. masks, scale = expand_masks(masks, padding=padding)
  663. boxes = expand_boxes(boxes, scale).to(dtype=torch.int64)
  664. im_h, im_w = img_shape
  665. if torchvision._is_tracing():
  666. return _onnx_paste_masks_in_image_loop(
  667. masks, boxes, torch.scalar_tensor(im_h, dtype=torch.int64), torch.scalar_tensor(im_w, dtype=torch.int64)
  668. )[:, None]
  669. res = [paste_mask_in_image(m[0], b, im_h, im_w) for m, b in zip(masks, boxes)]
  670. if len(res) > 0:
  671. ret = torch.stack(res, dim=0)[:, None]
  672. else:
  673. ret = masks.new_empty((0, 1, im_h, im_w))
  674. return ret
  675. class RoIHeads(nn.Module):
  676. __annotations__ = {
  677. "box_coder": det_utils.BoxCoder,
  678. "proposal_matcher": det_utils.Matcher,
  679. "fg_bg_sampler": det_utils.BalancedPositiveNegativeSampler,
  680. }
  681. def __init__(
  682. self,
  683. box_roi_pool,
  684. box_head,
  685. box_predictor,
  686. # Faster R-CNN training
  687. fg_iou_thresh,
  688. bg_iou_thresh,
  689. batch_size_per_image,
  690. positive_fraction,
  691. bbox_reg_weights,
  692. # Faster R-CNN inference
  693. score_thresh,
  694. nms_thresh,
  695. detections_per_img,
  696. # Line
  697. line_roi_pool=None,
  698. line_head=None,
  699. line_predictor=None,
  700. # Mask
  701. mask_roi_pool=None,
  702. mask_head=None,
  703. mask_predictor=None,
  704. keypoint_roi_pool=None,
  705. keypoint_head=None,
  706. keypoint_predictor=None,
  707. ):
  708. super().__init__()
  709. self.box_similarity = box_ops.box_iou
  710. # assign ground-truth boxes for each proposal
  711. self.proposal_matcher = det_utils.Matcher(fg_iou_thresh, bg_iou_thresh, allow_low_quality_matches=False)
  712. self.fg_bg_sampler = det_utils.BalancedPositiveNegativeSampler(batch_size_per_image, positive_fraction)
  713. if bbox_reg_weights is None:
  714. bbox_reg_weights = (10.0, 10.0, 5.0, 5.0)
  715. self.box_coder = det_utils.BoxCoder(bbox_reg_weights)
  716. self.box_roi_pool = box_roi_pool
  717. self.box_head = box_head
  718. self.box_predictor = box_predictor
  719. self.score_thresh = score_thresh
  720. self.nms_thresh = nms_thresh
  721. self.detections_per_img = detections_per_img
  722. self.line_roi_pool = line_roi_pool
  723. self.line_head = line_head
  724. self.line_predictor = line_predictor
  725. self.mask_roi_pool = mask_roi_pool
  726. self.mask_head = mask_head
  727. self.mask_predictor = mask_predictor
  728. self.keypoint_roi_pool = keypoint_roi_pool
  729. self.keypoint_head = keypoint_head
  730. self.keypoint_predictor = keypoint_predictor
  731. self.channel_compress = nn.Sequential(
  732. nn.Conv2d(256, 16, kernel_size=1),
  733. nn.BatchNorm2d(16),
  734. nn.ReLU(inplace=True)
  735. )
  736. def has_mask(self):
  737. if self.mask_roi_pool is None:
  738. return False
  739. if self.mask_head is None:
  740. return False
  741. if self.mask_predictor is None:
  742. return False
  743. return True
  744. def has_keypoint(self):
  745. if self.keypoint_roi_pool is None:
  746. return False
  747. if self.keypoint_head is None:
  748. return False
  749. if self.keypoint_predictor is None:
  750. return False
  751. return True
  752. def has_line(self):
  753. if self.line_roi_pool is None:
  754. return False
  755. if self.line_head is None:
  756. return False
  757. if self.line_predictor is None:
  758. return False
  759. return True
  760. def assign_targets_to_proposals(self, proposals, gt_boxes, gt_labels):
  761. # type: (List[Tensor], List[Tensor], List[Tensor]) -> Tuple[List[Tensor], List[Tensor]]
  762. matched_idxs = []
  763. labels = []
  764. for proposals_in_image, gt_boxes_in_image, gt_labels_in_image in zip(proposals, gt_boxes, gt_labels):
  765. if gt_boxes_in_image.numel() == 0:
  766. # Background image
  767. device = proposals_in_image.device
  768. clamped_matched_idxs_in_image = torch.zeros(
  769. (proposals_in_image.shape[0],), dtype=torch.int64, device=device
  770. )
  771. labels_in_image = torch.zeros((proposals_in_image.shape[0],), dtype=torch.int64, device=device)
  772. else:
  773. # set to self.box_similarity when https://github.com/pytorch/pytorch/issues/27495 lands
  774. match_quality_matrix = box_ops.box_iou(gt_boxes_in_image, proposals_in_image)
  775. matched_idxs_in_image = self.proposal_matcher(match_quality_matrix)
  776. clamped_matched_idxs_in_image = matched_idxs_in_image.clamp(min=0)
  777. labels_in_image = gt_labels_in_image[clamped_matched_idxs_in_image]
  778. labels_in_image = labels_in_image.to(dtype=torch.int64)
  779. # Label background (below the low threshold)
  780. bg_inds = matched_idxs_in_image == self.proposal_matcher.BELOW_LOW_THRESHOLD
  781. labels_in_image[bg_inds] = 0
  782. # Label ignore proposals (between low and high thresholds)
  783. ignore_inds = matched_idxs_in_image == self.proposal_matcher.BETWEEN_THRESHOLDS
  784. labels_in_image[ignore_inds] = -1 # -1 is ignored by sampler
  785. matched_idxs.append(clamped_matched_idxs_in_image)
  786. labels.append(labels_in_image)
  787. return matched_idxs, labels
  788. def subsample(self, labels):
  789. # type: (List[Tensor]) -> List[Tensor]
  790. sampled_pos_inds, sampled_neg_inds = self.fg_bg_sampler(labels)
  791. sampled_inds = []
  792. for img_idx, (pos_inds_img, neg_inds_img) in enumerate(zip(sampled_pos_inds, sampled_neg_inds)):
  793. img_sampled_inds = torch.where(pos_inds_img | neg_inds_img)[0]
  794. sampled_inds.append(img_sampled_inds)
  795. return sampled_inds
  796. def add_gt_proposals(self, proposals, gt_boxes):
  797. # type: (List[Tensor], List[Tensor]) -> List[Tensor]
  798. proposals = [torch.cat((proposal, gt_box)) for proposal, gt_box in zip(proposals, gt_boxes)]
  799. return proposals
  800. def check_targets(self, targets):
  801. # type: (Optional[List[Dict[str, Tensor]]]) -> None
  802. if targets is None:
  803. raise ValueError("targets should not be None")
  804. if not all(["boxes" in t for t in targets]):
  805. raise ValueError("Every element of targets should have a boxes key")
  806. if not all(["labels" in t for t in targets]):
  807. raise ValueError("Every element of targets should have a labels key")
  808. if self.has_mask():
  809. if not all(["masks" in t for t in targets]):
  810. raise ValueError("Every element of targets should have a masks key")
  811. def select_training_samples(
  812. self,
  813. proposals, # type: List[Tensor]
  814. targets, # type: Optional[List[Dict[str, Tensor]]]
  815. ):
  816. # type: (...) -> Tuple[List[Tensor], List[Tensor], List[Tensor], List[Tensor]]
  817. self.check_targets(targets)
  818. if targets is None:
  819. raise ValueError("targets should not be None")
  820. dtype = proposals[0].dtype
  821. device = proposals[0].device
  822. gt_boxes = [t["boxes"].to(dtype) for t in targets]
  823. gt_labels = [t["labels"] for t in targets]
  824. # append ground-truth bboxes to propos
  825. proposals = self.add_gt_proposals(proposals, gt_boxes)
  826. # get matching gt indices for each proposal
  827. matched_idxs, labels = self.assign_targets_to_proposals(proposals, gt_boxes, gt_labels)
  828. # sample a fixed proportion of positive-negative proposals
  829. sampled_inds = self.subsample(labels)
  830. matched_gt_boxes = []
  831. num_images = len(proposals)
  832. for img_id in range(num_images):
  833. img_sampled_inds = sampled_inds[img_id]
  834. proposals[img_id] = proposals[img_id][img_sampled_inds]
  835. labels[img_id] = labels[img_id][img_sampled_inds]
  836. matched_idxs[img_id] = matched_idxs[img_id][img_sampled_inds]
  837. gt_boxes_in_image = gt_boxes[img_id]
  838. if gt_boxes_in_image.numel() == 0:
  839. gt_boxes_in_image = torch.zeros((1, 4), dtype=dtype, device=device)
  840. matched_gt_boxes.append(gt_boxes_in_image[matched_idxs[img_id]])
  841. regression_targets = self.box_coder.encode(matched_gt_boxes, proposals)
  842. return proposals, matched_idxs, labels, regression_targets
  843. def postprocess_detections(
  844. self,
  845. class_logits, # type: Tensor
  846. box_regression, # type: Tensor
  847. proposals, # type: List[Tensor]
  848. image_shapes, # type: List[Tuple[int, int]]
  849. ):
  850. # type: (...) -> Tuple[List[Tensor], List[Tensor], List[Tensor]]
  851. device = class_logits.device
  852. num_classes = class_logits.shape[-1]
  853. boxes_per_image = [boxes_in_image.shape[0] for boxes_in_image in proposals]
  854. pred_boxes = self.box_coder.decode(box_regression, proposals)
  855. pred_scores = F.softmax(class_logits, -1)
  856. pred_boxes_list = pred_boxes.split(boxes_per_image, 0)
  857. pred_scores_list = pred_scores.split(boxes_per_image, 0)
  858. all_boxes = []
  859. all_scores = []
  860. all_labels = []
  861. for boxes, scores, image_shape in zip(pred_boxes_list, pred_scores_list, image_shapes):
  862. boxes = box_ops.clip_boxes_to_image(boxes, image_shape)
  863. # create labels for each prediction
  864. labels = torch.arange(num_classes, device=device)
  865. labels = labels.view(1, -1).expand_as(scores)
  866. # remove predictions with the background label
  867. boxes = boxes[:, 1:]
  868. scores = scores[:, 1:]
  869. labels = labels[:, 1:]
  870. # batch everything, by making every class prediction be a separate instance
  871. boxes = boxes.reshape(-1, 4)
  872. scores = scores.reshape(-1)
  873. labels = labels.reshape(-1)
  874. # remove low scoring boxes
  875. inds = torch.where(scores > self.score_thresh)[0]
  876. boxes, scores, labels = boxes[inds], scores[inds], labels[inds]
  877. # remove empty boxes
  878. keep = box_ops.remove_small_boxes(boxes, min_size=1e-2)
  879. boxes, scores, labels = boxes[keep], scores[keep], labels[keep]
  880. # non-maximum suppression, independently done per class
  881. keep = box_ops.batched_nms(boxes, scores, labels, self.nms_thresh)
  882. # keep only topk scoring predictions
  883. keep = keep[: self.detections_per_img]
  884. boxes, scores, labels = boxes[keep], scores[keep], labels[keep]
  885. all_boxes.append(boxes)
  886. all_scores.append(scores)
  887. all_labels.append(labels)
  888. return all_boxes, all_scores, all_labels
  889. def forward(
  890. self,
  891. features, # type: Dict[str, Tensor]
  892. proposals, # type: List[Tensor]
  893. image_shapes, # type: List[Tuple[int, int]]
  894. targets=None, # type: Optional[List[Dict[str, Tensor]]]
  895. ):
  896. # type: (...) -> Tuple[List[Dict[str, Tensor]], Dict[str, Tensor]]
  897. """
  898. Args:
  899. features (List[Tensor])
  900. proposals (List[Tensor[N, 4]])
  901. image_shapes (List[Tuple[H, W]])
  902. targets (List[Dict])
  903. """
  904. print(f'roihead forward!!!')
  905. if targets is not None:
  906. for t in targets:
  907. # TODO: https://github.com/pytorch/pytorch/issues/26731
  908. floating_point_types = (torch.float, torch.double, torch.half)
  909. if not t["boxes"].dtype in floating_point_types:
  910. raise TypeError(f"target boxes must of float type, instead got {t['boxes'].dtype}")
  911. if not t["labels"].dtype == torch.int64:
  912. raise TypeError(f"target labels must of int64 type, instead got {t['labels'].dtype}")
  913. if self.has_keypoint():
  914. if not t["keypoints"].dtype == torch.float32:
  915. raise TypeError(f"target keypoints must of float type, instead got {t['keypoints'].dtype}")
  916. if self.training:
  917. proposals, matched_idxs, labels, regression_targets = self.select_training_samples(proposals, targets)
  918. else:
  919. if targets is not None:
  920. proposals, matched_idxs, labels, regression_targets = self.select_training_samples(proposals, targets)
  921. else:
  922. labels = None
  923. regression_targets = None
  924. matched_idxs = None
  925. box_features = self.box_roi_pool(features, proposals, image_shapes)
  926. box_features = self.box_head(box_features)
  927. class_logits, box_regression = self.box_predictor(box_features)
  928. result: List[Dict[str, torch.Tensor]] = []
  929. losses = {}
  930. # _, C, H, W = features['0'].shape # 忽略 batch_size,因为我们只关心 C, H, W
  931. if self.training:
  932. if labels is None:
  933. raise ValueError("labels cannot be None")
  934. if regression_targets is None:
  935. raise ValueError("regression_targets cannot be None")
  936. print(f'boxes compute losses')
  937. loss_classifier, loss_box_reg = fastrcnn_loss(class_logits, box_regression, labels, regression_targets)
  938. losses = {"loss_classifier": loss_classifier, "loss_box_reg": loss_box_reg}
  939. else:
  940. if targets is not None:
  941. loss_classifier, loss_box_reg = fastrcnn_loss(class_logits, box_regression, labels, regression_targets)
  942. losses = {"loss_classifier": loss_classifier, "loss_box_reg": loss_box_reg}
  943. boxes, scores, labels = self.postprocess_detections(class_logits, box_regression, proposals,
  944. image_shapes)
  945. num_images = len(boxes)
  946. for i in range(num_images):
  947. result.append(
  948. {
  949. "boxes": boxes[i],
  950. "labels": labels[i],
  951. "scores": scores[i],
  952. }
  953. )
  954. if self.has_line():
  955. print(f'roi_heads forward has_line()!!!!')
  956. line_proposals = [p["boxes"] for p in result]
  957. print(f'boxes_proposals:{len(line_proposals)}')
  958. # if line_proposals is None or len(line_proposals) == 0:
  959. # # 返回空特征或者跳过该部分计算
  960. # return torch.empty(0, C, H, W).to(features['0'].device)
  961. if self.training:
  962. # during training, only focus on positive boxes
  963. num_images = len(proposals)
  964. print(f'num_images:{num_images}')
  965. line_proposals = []
  966. pos_matched_idxs = []
  967. if matched_idxs is None:
  968. raise ValueError("if in trainning, matched_idxs should not be None")
  969. for img_id in range(num_images):
  970. pos = torch.where(labels[img_id] > 0)[0]
  971. line_proposals.append(proposals[img_id][pos])
  972. pos_matched_idxs.append(matched_idxs[img_id][pos])
  973. else:
  974. if targets is not None:
  975. pos_matched_idxs = []
  976. num_images = len(proposals)
  977. line_proposals = []
  978. print(f'val num_images:{num_images}')
  979. if matched_idxs is None:
  980. raise ValueError("if in trainning, matched_idxs should not be None")
  981. for img_id in range(num_images):
  982. pos = torch.where(labels[img_id] > 0)[0]
  983. line_proposals.append(proposals[img_id][pos])
  984. pos_matched_idxs.append(matched_idxs[img_id][pos])
  985. else:
  986. pos_matched_idxs = None
  987. print(f'line_proposals:{len(line_proposals)}')
  988. # line_features = self.line_roi_pool(features, line_proposals, image_shapes)
  989. # print(f'line_features from line_roi_pool:{line_features.shape}')
  990. line_features=self.channel_compress(features['0'])
  991. line_features=lines_features_align(line_features,line_proposals,image_shapes)
  992. line_features = self.line_head(line_features)
  993. print(f'line_features from line_head:{line_features.shape}')
  994. # line_logits = self.line_predictor(line_features)
  995. line_logits=line_features
  996. print(f'line_logits:{line_logits.shape}')
  997. loss_line = {}
  998. loss_line_iou={}
  999. if self.training:
  1000. if targets is None or pos_matched_idxs is None:
  1001. raise ValueError("both targets and pos_matched_idxs should not be None when in training mode")
  1002. gt_lines = [t["lines"] for t in targets]
  1003. h, w = targets[0]["img_size"]
  1004. img_size = h
  1005. rcnn_loss_line = lines_point_pair_loss(
  1006. line_logits, line_proposals, gt_lines, pos_matched_idxs
  1007. )
  1008. iou_loss = line_iou_loss(line_logits, line_proposals, gt_lines, pos_matched_idxs,img_size)
  1009. loss_line = {"loss_line": rcnn_loss_line}
  1010. loss_line_iou = {'loss_line_iou': iou_loss}
  1011. else:
  1012. if targets is not None:
  1013. h, w = targets[0]["img_size"]
  1014. img_size = h
  1015. gt_lines = [t["lines"] for t in targets]
  1016. rcnn_loss_lines = lines_point_pair_loss(
  1017. line_logits, line_proposals, gt_lines, pos_matched_idxs
  1018. )
  1019. loss_line = {"loss_line": rcnn_loss_lines}
  1020. iou_loss =line_iou_loss(line_logits, line_proposals,gt_lines,pos_matched_idxs,img_size)
  1021. loss_line_iou={'loss_line_iou':iou_loss}
  1022. else:
  1023. if line_logits is None or line_proposals is None:
  1024. raise ValueError(
  1025. "both keypoint_logits and keypoint_proposals should not be None when not in training mode"
  1026. )
  1027. lines_probs, kp_scores = line_inference(line_logits, line_proposals)
  1028. for keypoint_prob, kps, r in zip(lines_probs, kp_scores, result):
  1029. r["lines"] = keypoint_prob
  1030. r["liness_scores"] = kps
  1031. losses.update(loss_line)
  1032. losses.update(loss_line_iou)
  1033. if self.has_mask():
  1034. mask_proposals = [p["boxes"] for p in result]
  1035. if self.training:
  1036. if matched_idxs is None:
  1037. raise ValueError("if in training, matched_idxs should not be None")
  1038. # during training, only focus on positive boxes
  1039. num_images = len(proposals)
  1040. mask_proposals = []
  1041. pos_matched_idxs = []
  1042. for img_id in range(num_images):
  1043. pos = torch.where(labels[img_id] > 0)[0]
  1044. mask_proposals.append(proposals[img_id][pos])
  1045. pos_matched_idxs.append(matched_idxs[img_id][pos])
  1046. else:
  1047. pos_matched_idxs = None
  1048. if self.mask_roi_pool is not None:
  1049. mask_features = self.mask_roi_pool(features, mask_proposals, image_shapes)
  1050. mask_features = self.mask_head(mask_features)
  1051. mask_logits = self.mask_predictor(mask_features)
  1052. else:
  1053. raise Exception("Expected mask_roi_pool to be not None")
  1054. loss_mask = {}
  1055. if self.training:
  1056. if targets is None or pos_matched_idxs is None or mask_logits is None:
  1057. raise ValueError("targets, pos_matched_idxs, mask_logits cannot be None when training")
  1058. gt_masks = [t["masks"] for t in targets]
  1059. gt_labels = [t["labels"] for t in targets]
  1060. rcnn_loss_mask = maskrcnn_loss(mask_logits, mask_proposals, gt_masks, gt_labels, pos_matched_idxs)
  1061. loss_mask = {"loss_mask": rcnn_loss_mask}
  1062. else:
  1063. labels = [r["labels"] for r in result]
  1064. masks_probs = maskrcnn_inference(mask_logits, labels)
  1065. for mask_prob, r in zip(masks_probs, result):
  1066. r["masks"] = mask_prob
  1067. losses.update(loss_mask)
  1068. # keep none checks in if conditional so torchscript will conditionally
  1069. # compile each branch
  1070. if self.has_keypoint():
  1071. keypoint_proposals = [p["boxes"] for p in result]
  1072. if self.training:
  1073. # during training, only focus on positive boxes
  1074. num_images = len(proposals)
  1075. keypoint_proposals = []
  1076. pos_matched_idxs = []
  1077. if matched_idxs is None:
  1078. raise ValueError("if in trainning, matched_idxs should not be None")
  1079. for img_id in range(num_images):
  1080. pos = torch.where(labels[img_id] > 0)[0]
  1081. keypoint_proposals.append(proposals[img_id][pos])
  1082. pos_matched_idxs.append(matched_idxs[img_id][pos])
  1083. else:
  1084. pos_matched_idxs = None
  1085. keypoint_features = self.line_roi_pool(features, keypoint_proposals, image_shapes)
  1086. keypoint_features = self.line_head(keypoint_features)
  1087. keypoint_logits = self.line_predictor(keypoint_features)
  1088. loss_keypoint = {}
  1089. if self.training:
  1090. if targets is None or pos_matched_idxs is None:
  1091. raise ValueError("both targets and pos_matched_idxs should not be None when in training mode")
  1092. gt_keypoints = [t["keypoints"] for t in targets]
  1093. rcnn_loss_keypoint = keypointrcnn_loss(
  1094. keypoint_logits, keypoint_proposals, gt_keypoints, pos_matched_idxs
  1095. )
  1096. loss_keypoint = {"loss_keypoint": rcnn_loss_keypoint}
  1097. else:
  1098. if keypoint_logits is None or keypoint_proposals is None:
  1099. raise ValueError(
  1100. "both keypoint_logits and keypoint_proposals should not be None when not in training mode"
  1101. )
  1102. keypoints_probs, kp_scores = keypointrcnn_inference(keypoint_logits, keypoint_proposals)
  1103. for keypoint_prob, kps, r in zip(keypoints_probs, kp_scores, result):
  1104. r["keypoints"] = keypoint_prob
  1105. r["keypoints_scores"] = kps
  1106. losses.update(loss_keypoint)
  1107. return result, losses