loi_heads.py 63 KB

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