loi_heads.py 62 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679
  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. print(f'starte to compute_point_loss')
  562. print(f'compute_point_loss line_logits.shape:{line_logits.shape},len_proposals:{len_proposals}')
  563. if H != W:
  564. raise ValueError(
  565. f"line_logits height and width (last two elements of shape) should be equal. Instead got H = {H} and W = {W}"
  566. )
  567. discretization_size = H
  568. gs_heatmaps = []
  569. # print(f'point_matched_idxs:{point_matched_idxs}')
  570. for proposals_per_image, gt_kp_in_image, midx in zip(proposals, gt_points, point_matched_idxs):
  571. print(f'proposals_per_image:{proposals_per_image.shape}')
  572. kp = gt_kp_in_image[midx]
  573. # print(f'gt_kp_in_image:{gt_kp_in_image}')
  574. gs_heatmaps_per_img = single_point_to_heatmap(kp, proposals_per_image, discretization_size)
  575. gs_heatmaps.append(gs_heatmaps_per_img)
  576. gs_heatmaps = torch.cat(gs_heatmaps, dim=0)
  577. print(f'gs_heatmaps:{gs_heatmaps.shape}, line_logits.shape:{line_logits.squeeze(1).shape}')
  578. line_logits = line_logits[:,0]
  579. print(f'single_point_logits:{line_logits.shape}')
  580. line_loss = F.cross_entropy(line_logits, gs_heatmaps)
  581. return line_loss
  582. def lines_to_boxes(lines, img_size=511):
  583. """
  584. 输入:
  585. lines: Tensor of shape (N, 2, 2),表示 N 条线段,每个线段有两个端点 (x, y)
  586. img_size: int,图像尺寸,用于 clamp 边界
  587. 输出:
  588. boxes: Tensor of shape (N, 4),表示 N 个包围盒 [x_min, y_min, x_max, y_max]
  589. """
  590. # 提取所有线段的两个端点
  591. p1 = lines[:, 0] # (N, 2)
  592. p2 = lines[:, 1] # (N, 2)
  593. # 每条线段的 x 和 y 坐标
  594. x_coords = torch.stack([p1[:, 0], p2[:, 0]], dim=1) # (N, 2)
  595. y_coords = torch.stack([p1[:, 1], p2[:, 1]], dim=1) # (N, 2)
  596. # 计算包围盒边界
  597. x_min = x_coords.min(dim=1).values
  598. y_min = y_coords.min(dim=1).values
  599. x_max = x_coords.max(dim=1).values
  600. y_max = y_coords.max(dim=1).values
  601. # 扩展边界并限制在图像范围内
  602. x_min = (x_min - 1).clamp(min=0, max=img_size)
  603. y_min = (y_min - 1).clamp(min=0, max=img_size)
  604. x_max = (x_max + 1).clamp(min=0, max=img_size)
  605. y_max = (y_max + 1).clamp(min=0, max=img_size)
  606. # 合成包围盒
  607. boxes = torch.stack([x_min, y_min, x_max, y_max], dim=1) # (N, 4)
  608. return boxes
  609. def box_iou_pairwise(box1, box2):
  610. """
  611. 输入:
  612. box1: shape (N, 4)
  613. box2: shape (M, 4)
  614. 输出:
  615. ious: shape (min(N, M), ), 只计算 i = j 的配对
  616. """
  617. N = min(len(box1), len(box2))
  618. lt = torch.max(box1[:N, :2], box2[:N, :2]) # 左上角
  619. rb = torch.min(box1[:N, 2:], box2[:N, 2:]) # 右下角
  620. wh = (rb - lt).clamp(min=0) # 宽高
  621. inter_area = wh[:, 0] * wh[:, 1] # 交集面积
  622. area1 = (box1[:N, 2] - box1[:N, 0]) * (box1[:N, 3] - box1[:N, 1])
  623. area2 = (box2[:N, 2] - box2[:N, 0]) * (box2[:N, 3] - box2[:N, 1])
  624. union_area = area1 + area2 - inter_area
  625. ious = inter_area / (union_area + 1e-6)
  626. return ious
  627. def line_iou_loss(x, boxes, gt_lines, matched_idx, img_size=511, alpha=1.0, beta=1.0, gamma=1.0):
  628. """
  629. Args:
  630. x: [N,1,H,W] 热力图
  631. boxes: [N,4] 框坐标
  632. gt_lines: [N,2,3] GT线段(含可见性)
  633. matched_idx: 匹配 index
  634. img_size: 图像尺寸
  635. alpha: IoU 损失权重
  636. beta: 长度损失权重
  637. gamma: 方向角度损失权重
  638. """
  639. losses = []
  640. boxes_per_image = [box.size(0) for box in boxes]
  641. x2 = x.split(boxes_per_image, dim=0)
  642. for xx, bb, gt_line, mid in zip(x2, boxes, gt_lines, matched_idx):
  643. p_prob, _ = heatmaps_to_lines(xx, bb)
  644. pred_lines = p_prob
  645. gt_line_points = gt_line[mid]
  646. if len(pred_lines) == 0 or len(gt_line_points) == 0:
  647. continue
  648. # IoU 损失
  649. pred_boxes = lines_to_boxes(pred_lines, img_size)
  650. gt_boxes = lines_to_boxes(gt_line_points, img_size)
  651. ious = box_iou_pairwise(pred_boxes, gt_boxes)
  652. iou_loss = 1.0 - ious # [N]
  653. # 长度损失
  654. pred_len = line_length(pred_lines)
  655. gt_len = line_length(gt_line_points)
  656. length_diff = F.l1_loss(pred_len, gt_len, reduction='none') # [N]
  657. # 方向角度损失
  658. pred_dir = line_direction(pred_lines)
  659. gt_dir = line_direction(gt_line_points)
  660. ang_loss = angle_loss_cosine(pred_dir, gt_dir) # [N]
  661. # 归一化每一项损失
  662. norm_iou = normalize_tensor(iou_loss)
  663. norm_len = normalize_tensor(length_diff)
  664. norm_ang = normalize_tensor(ang_loss)
  665. total = alpha * norm_iou + beta * norm_len + gamma * norm_ang
  666. losses.append(total)
  667. if not losses:
  668. return None
  669. return torch.mean(torch.cat(losses))
  670. def line_inference(x, boxes):
  671. # type: (Tensor, List[Tensor]) -> Tuple[List[Tensor], List[Tensor]]
  672. lines_probs = []
  673. lines_scores = []
  674. points_probs = []
  675. points_scores = []
  676. boxes_per_image = [box.size(0) for box in boxes]
  677. x2 = x.split(boxes_per_image, dim=0)
  678. for xx, bb in zip(x2, boxes):
  679. line_prob, line_scores,point_prob,point_scores = heatmaps_to_lines(xx, bb)
  680. lines_probs.append(line_prob)
  681. lines_scores.append(line_scores)
  682. points_probs.append(point_prob.unsqueeze(1))
  683. points_scores.append(point_scores)
  684. return lines_probs, lines_scores,points_probs,points_scores
  685. def keypointrcnn_loss(keypoint_logits, proposals, gt_keypoints, keypoint_matched_idxs):
  686. # type: (Tensor, List[Tensor], List[Tensor], List[Tensor]) -> Tensor
  687. N, K, H, W = keypoint_logits.shape
  688. if H != W:
  689. raise ValueError(
  690. f"keypoint_logits height and width (last two elements of shape) should be equal. Instead got H = {H} and W = {W}"
  691. )
  692. discretization_size = H
  693. heatmaps = []
  694. valid = []
  695. for proposals_per_image, gt_kp_in_image, midx in zip(proposals, gt_keypoints, keypoint_matched_idxs):
  696. kp = gt_kp_in_image[midx]
  697. heatmaps_per_image, valid_per_image = keypoints_to_heatmap(kp, proposals_per_image, discretization_size)
  698. heatmaps.append(heatmaps_per_image.view(-1))
  699. valid.append(valid_per_image.view(-1))
  700. keypoint_targets = torch.cat(heatmaps, dim=0)
  701. valid = torch.cat(valid, dim=0).to(dtype=torch.uint8)
  702. valid = torch.where(valid)[0]
  703. # torch.mean (in binary_cross_entropy_with_logits) doesn't
  704. # accept empty tensors, so handle it sepaartely
  705. if keypoint_targets.numel() == 0 or len(valid) == 0:
  706. return keypoint_logits.sum() * 0
  707. keypoint_logits = keypoint_logits.view(N * K, H * W)
  708. keypoint_loss = F.cross_entropy(keypoint_logits[valid], keypoint_targets[valid])
  709. return keypoint_loss
  710. def keypointrcnn_inference(x, boxes):
  711. # type: (Tensor, List[Tensor]) -> Tuple[List[Tensor], List[Tensor]]
  712. kp_probs = []
  713. kp_scores = []
  714. boxes_per_image = [box.size(0) for box in boxes]
  715. x2 = x.split(boxes_per_image, dim=0)
  716. for xx, bb in zip(x2, boxes):
  717. kp_prob, scores = heatmaps_to_keypoints(xx, bb)
  718. kp_probs.append(kp_prob)
  719. kp_scores.append(scores)
  720. return kp_probs, kp_scores
  721. def _onnx_expand_boxes(boxes, scale):
  722. # type: (Tensor, float) -> Tensor
  723. w_half = (boxes[:, 2] - boxes[:, 0]) * 0.5
  724. h_half = (boxes[:, 3] - boxes[:, 1]) * 0.5
  725. x_c = (boxes[:, 2] + boxes[:, 0]) * 0.5
  726. y_c = (boxes[:, 3] + boxes[:, 1]) * 0.5
  727. w_half = w_half.to(dtype=torch.float32) * scale
  728. h_half = h_half.to(dtype=torch.float32) * scale
  729. boxes_exp0 = x_c - w_half
  730. boxes_exp1 = y_c - h_half
  731. boxes_exp2 = x_c + w_half
  732. boxes_exp3 = y_c + h_half
  733. boxes_exp = torch.stack((boxes_exp0, boxes_exp1, boxes_exp2, boxes_exp3), 1)
  734. return boxes_exp
  735. # the next two functions should be merged inside Masker
  736. # but are kept here for the moment while we need them
  737. # temporarily for paste_mask_in_image
  738. def expand_boxes(boxes, scale):
  739. # type: (Tensor, float) -> Tensor
  740. if torchvision._is_tracing():
  741. return _onnx_expand_boxes(boxes, scale)
  742. w_half = (boxes[:, 2] - boxes[:, 0]) * 0.5
  743. h_half = (boxes[:, 3] - boxes[:, 1]) * 0.5
  744. x_c = (boxes[:, 2] + boxes[:, 0]) * 0.5
  745. y_c = (boxes[:, 3] + boxes[:, 1]) * 0.5
  746. w_half *= scale
  747. h_half *= scale
  748. boxes_exp = torch.zeros_like(boxes)
  749. boxes_exp[:, 0] = x_c - w_half
  750. boxes_exp[:, 2] = x_c + w_half
  751. boxes_exp[:, 1] = y_c - h_half
  752. boxes_exp[:, 3] = y_c + h_half
  753. return boxes_exp
  754. @torch.jit.unused
  755. def expand_masks_tracing_scale(M, padding):
  756. # type: (int, int) -> float
  757. return torch.tensor(M + 2 * padding).to(torch.float32) / torch.tensor(M).to(torch.float32)
  758. def expand_masks(mask, padding):
  759. # type: (Tensor, int) -> Tuple[Tensor, float]
  760. M = mask.shape[-1]
  761. if torch._C._get_tracing_state(): # could not import is_tracing(), not sure why
  762. scale = expand_masks_tracing_scale(M, padding)
  763. else:
  764. scale = float(M + 2 * padding) / M
  765. padded_mask = F.pad(mask, (padding,) * 4)
  766. return padded_mask, scale
  767. def paste_mask_in_image(mask, box, im_h, im_w):
  768. # type: (Tensor, Tensor, int, int) -> Tensor
  769. TO_REMOVE = 1
  770. w = int(box[2] - box[0] + TO_REMOVE)
  771. h = int(box[3] - box[1] + TO_REMOVE)
  772. w = max(w, 1)
  773. h = max(h, 1)
  774. # Set shape to [batchxCxHxW]
  775. mask = mask.expand((1, 1, -1, -1))
  776. # Resize mask
  777. mask = F.interpolate(mask, size=(h, w), mode="bilinear", align_corners=False)
  778. mask = mask[0][0]
  779. im_mask = torch.zeros((im_h, im_w), dtype=mask.dtype, device=mask.device)
  780. x_0 = max(box[0], 0)
  781. x_1 = min(box[2] + 1, im_w)
  782. y_0 = max(box[1], 0)
  783. y_1 = min(box[3] + 1, im_h)
  784. 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])]
  785. return im_mask
  786. def _onnx_paste_mask_in_image(mask, box, im_h, im_w):
  787. one = torch.ones(1, dtype=torch.int64)
  788. zero = torch.zeros(1, dtype=torch.int64)
  789. w = box[2] - box[0] + one
  790. h = box[3] - box[1] + one
  791. w = torch.max(torch.cat((w, one)))
  792. h = torch.max(torch.cat((h, one)))
  793. # Set shape to [batchxCxHxW]
  794. mask = mask.expand((1, 1, mask.size(0), mask.size(1)))
  795. # Resize mask
  796. mask = F.interpolate(mask, size=(int(h), int(w)), mode="bilinear", align_corners=False)
  797. mask = mask[0][0]
  798. x_0 = torch.max(torch.cat((box[0].unsqueeze(0), zero)))
  799. x_1 = torch.min(torch.cat((box[2].unsqueeze(0) + one, im_w.unsqueeze(0))))
  800. y_0 = torch.max(torch.cat((box[1].unsqueeze(0), zero)))
  801. y_1 = torch.min(torch.cat((box[3].unsqueeze(0) + one, im_h.unsqueeze(0))))
  802. unpaded_im_mask = mask[(y_0 - box[1]): (y_1 - box[1]), (x_0 - box[0]): (x_1 - box[0])]
  803. # TODO : replace below with a dynamic padding when support is added in ONNX
  804. # pad y
  805. zeros_y0 = torch.zeros(y_0, unpaded_im_mask.size(1))
  806. zeros_y1 = torch.zeros(im_h - y_1, unpaded_im_mask.size(1))
  807. concat_0 = torch.cat((zeros_y0, unpaded_im_mask.to(dtype=torch.float32), zeros_y1), 0)[0:im_h, :]
  808. # pad x
  809. zeros_x0 = torch.zeros(concat_0.size(0), x_0)
  810. zeros_x1 = torch.zeros(concat_0.size(0), im_w - x_1)
  811. im_mask = torch.cat((zeros_x0, concat_0, zeros_x1), 1)[:, :im_w]
  812. return im_mask
  813. @torch.jit._script_if_tracing
  814. def _onnx_paste_masks_in_image_loop(masks, boxes, im_h, im_w):
  815. res_append = torch.zeros(0, im_h, im_w)
  816. for i in range(masks.size(0)):
  817. mask_res = _onnx_paste_mask_in_image(masks[i][0], boxes[i], im_h, im_w)
  818. mask_res = mask_res.unsqueeze(0)
  819. res_append = torch.cat((res_append, mask_res))
  820. return res_append
  821. def paste_masks_in_image(masks, boxes, img_shape, padding=1):
  822. # type: (Tensor, Tensor, Tuple[int, int], int) -> Tensor
  823. masks, scale = expand_masks(masks, padding=padding)
  824. boxes = expand_boxes(boxes, scale).to(dtype=torch.int64)
  825. im_h, im_w = img_shape
  826. if torchvision._is_tracing():
  827. return _onnx_paste_masks_in_image_loop(
  828. masks, boxes, torch.scalar_tensor(im_h, dtype=torch.int64), torch.scalar_tensor(im_w, dtype=torch.int64)
  829. )[:, None]
  830. res = [paste_mask_in_image(m[0], b, im_h, im_w) for m, b in zip(masks, boxes)]
  831. if len(res) > 0:
  832. ret = torch.stack(res, dim=0)[:, None]
  833. else:
  834. ret = masks.new_empty((0, 1, im_h, im_w))
  835. return ret
  836. class RoIHeads(nn.Module):
  837. __annotations__ = {
  838. "box_coder": det_utils.BoxCoder,
  839. "proposal_matcher": det_utils.Matcher,
  840. "fg_bg_sampler": det_utils.BalancedPositiveNegativeSampler,
  841. }
  842. def __init__(
  843. self,
  844. box_roi_pool,
  845. box_head,
  846. box_predictor,
  847. # Faster R-CNN training
  848. fg_iou_thresh,
  849. bg_iou_thresh,
  850. batch_size_per_image,
  851. positive_fraction,
  852. bbox_reg_weights,
  853. # Faster R-CNN inference
  854. score_thresh,
  855. nms_thresh,
  856. detections_per_img,
  857. # Line
  858. line_roi_pool=None,
  859. line_head=None,
  860. line_predictor=None,
  861. # Mask
  862. mask_roi_pool=None,
  863. mask_head=None,
  864. mask_predictor=None,
  865. keypoint_roi_pool=None,
  866. keypoint_head=None,
  867. keypoint_predictor=None,
  868. ):
  869. super().__init__()
  870. self.box_similarity = box_ops.box_iou
  871. # assign ground-truth boxes for each proposal
  872. self.proposal_matcher = det_utils.Matcher(fg_iou_thresh, bg_iou_thresh, allow_low_quality_matches=False)
  873. self.fg_bg_sampler = det_utils.BalancedPositiveNegativeSampler(batch_size_per_image, positive_fraction)
  874. if bbox_reg_weights is None:
  875. bbox_reg_weights = (10.0, 10.0, 5.0, 5.0)
  876. self.box_coder = det_utils.BoxCoder(bbox_reg_weights)
  877. self.box_roi_pool = box_roi_pool
  878. self.box_head = box_head
  879. self.box_predictor = box_predictor
  880. self.score_thresh = score_thresh
  881. self.nms_thresh = nms_thresh
  882. self.detections_per_img = detections_per_img
  883. self.line_roi_pool = line_roi_pool
  884. self.line_head = line_head
  885. self.line_predictor = line_predictor
  886. self.mask_roi_pool = mask_roi_pool
  887. self.mask_head = mask_head
  888. self.mask_predictor = mask_predictor
  889. self.keypoint_roi_pool = keypoint_roi_pool
  890. self.keypoint_head = keypoint_head
  891. self.keypoint_predictor = keypoint_predictor
  892. self.channel_compress = nn.Sequential(
  893. nn.Conv2d(256, 8, kernel_size=1),
  894. nn.BatchNorm2d(8),
  895. nn.ReLU(inplace=True)
  896. )
  897. def has_mask(self):
  898. if self.mask_roi_pool is None:
  899. return False
  900. if self.mask_head is None:
  901. return False
  902. if self.mask_predictor is None:
  903. return False
  904. return True
  905. def has_keypoint(self):
  906. if self.keypoint_roi_pool is None:
  907. return False
  908. if self.keypoint_head is None:
  909. return False
  910. if self.keypoint_predictor is None:
  911. return False
  912. return True
  913. def has_line(self):
  914. # if self.line_roi_pool is None:
  915. # return False
  916. if self.line_head is None:
  917. return False
  918. # if self.line_predictor is None:
  919. # return False
  920. return True
  921. def assign_targets_to_proposals(self, proposals, gt_boxes, gt_labels):
  922. # type: (List[Tensor], List[Tensor], List[Tensor]) -> Tuple[List[Tensor], List[Tensor]]
  923. matched_idxs = []
  924. labels = []
  925. for proposals_in_image, gt_boxes_in_image, gt_labels_in_image in zip(proposals, gt_boxes, gt_labels):
  926. if gt_boxes_in_image.numel() == 0:
  927. # Background image
  928. device = proposals_in_image.device
  929. clamped_matched_idxs_in_image = torch.zeros(
  930. (proposals_in_image.shape[0],), dtype=torch.int64, device=device
  931. )
  932. labels_in_image = torch.zeros((proposals_in_image.shape[0],), dtype=torch.int64, device=device)
  933. else:
  934. # set to self.box_similarity when https://github.com/pytorch/pytorch/issues/27495 lands
  935. match_quality_matrix = box_ops.box_iou(gt_boxes_in_image, proposals_in_image)
  936. matched_idxs_in_image = self.proposal_matcher(match_quality_matrix)
  937. clamped_matched_idxs_in_image = matched_idxs_in_image.clamp(min=0)
  938. labels_in_image = gt_labels_in_image[clamped_matched_idxs_in_image]
  939. labels_in_image = labels_in_image.to(dtype=torch.int64)
  940. # Label background (below the low threshold)
  941. bg_inds = matched_idxs_in_image == self.proposal_matcher.BELOW_LOW_THRESHOLD
  942. labels_in_image[bg_inds] = 0
  943. # Label ignore proposals (between low and high thresholds)
  944. ignore_inds = matched_idxs_in_image == self.proposal_matcher.BETWEEN_THRESHOLDS
  945. labels_in_image[ignore_inds] = -1 # -1 is ignored by sampler
  946. matched_idxs.append(clamped_matched_idxs_in_image)
  947. labels.append(labels_in_image)
  948. return matched_idxs, labels
  949. def subsample(self, labels):
  950. # type: (List[Tensor]) -> List[Tensor]
  951. sampled_pos_inds, sampled_neg_inds = self.fg_bg_sampler(labels)
  952. sampled_inds = []
  953. for img_idx, (pos_inds_img, neg_inds_img) in enumerate(zip(sampled_pos_inds, sampled_neg_inds)):
  954. img_sampled_inds = torch.where(pos_inds_img | neg_inds_img)[0]
  955. sampled_inds.append(img_sampled_inds)
  956. return sampled_inds
  957. def add_gt_proposals(self, proposals, gt_boxes):
  958. # type: (List[Tensor], List[Tensor]) -> List[Tensor]
  959. proposals = [torch.cat((proposal, gt_box)) for proposal, gt_box in zip(proposals, gt_boxes)]
  960. return proposals
  961. def check_targets(self, targets):
  962. # type: (Optional[List[Dict[str, Tensor]]]) -> None
  963. if targets is None:
  964. raise ValueError("targets should not be None")
  965. if not all(["boxes" in t for t in targets]):
  966. raise ValueError("Every element of targets should have a boxes key")
  967. if not all(["labels" in t for t in targets]):
  968. raise ValueError("Every element of targets should have a labels key")
  969. if self.has_mask():
  970. if not all(["masks" in t for t in targets]):
  971. raise ValueError("Every element of targets should have a masks key")
  972. def select_training_samples(
  973. self,
  974. proposals, # type: List[Tensor]
  975. targets, # type: Optional[List[Dict[str, Tensor]]]
  976. ):
  977. # type: (...) -> Tuple[List[Tensor], List[Tensor], List[Tensor], List[Tensor]]
  978. self.check_targets(targets)
  979. if targets is None:
  980. raise ValueError("targets should not be None")
  981. dtype = proposals[0].dtype
  982. device = proposals[0].device
  983. gt_boxes = [t["boxes"].to(dtype) for t in targets]
  984. gt_labels = [t["labels"] for t in targets]
  985. # append ground-truth bboxes to propos
  986. proposals = self.add_gt_proposals(proposals, gt_boxes)
  987. # get matching gt indices for each proposal
  988. matched_idxs, labels = self.assign_targets_to_proposals(proposals, gt_boxes, gt_labels)
  989. # sample a fixed proportion of positive-negative proposals
  990. sampled_inds = self.subsample(labels)
  991. matched_gt_boxes = []
  992. num_images = len(proposals)
  993. for img_id in range(num_images):
  994. img_sampled_inds = sampled_inds[img_id]
  995. proposals[img_id] = proposals[img_id][img_sampled_inds]
  996. labels[img_id] = labels[img_id][img_sampled_inds]
  997. matched_idxs[img_id] = matched_idxs[img_id][img_sampled_inds]
  998. gt_boxes_in_image = gt_boxes[img_id]
  999. if gt_boxes_in_image.numel() == 0:
  1000. gt_boxes_in_image = torch.zeros((1, 4), dtype=dtype, device=device)
  1001. matched_gt_boxes.append(gt_boxes_in_image[matched_idxs[img_id]])
  1002. regression_targets = self.box_coder.encode(matched_gt_boxes, proposals)
  1003. return proposals, matched_idxs, labels, regression_targets
  1004. def postprocess_detections(
  1005. self,
  1006. class_logits, # type: Tensor
  1007. box_regression, # type: Tensor
  1008. proposals, # type: List[Tensor]
  1009. image_shapes, # type: List[Tuple[int, int]]
  1010. ):
  1011. # type: (...) -> Tuple[List[Tensor], List[Tensor], List[Tensor]]
  1012. device = class_logits.device
  1013. num_classes = class_logits.shape[-1]
  1014. boxes_per_image = [boxes_in_image.shape[0] for boxes_in_image in proposals]
  1015. pred_boxes = self.box_coder.decode(box_regression, proposals)
  1016. pred_scores = F.softmax(class_logits, -1)
  1017. pred_boxes_list = pred_boxes.split(boxes_per_image, 0)
  1018. pred_scores_list = pred_scores.split(boxes_per_image, 0)
  1019. all_boxes = []
  1020. all_scores = []
  1021. all_labels = []
  1022. for boxes, scores, image_shape in zip(pred_boxes_list, pred_scores_list, image_shapes):
  1023. boxes = box_ops.clip_boxes_to_image(boxes, image_shape)
  1024. # create labels for each prediction
  1025. labels = torch.arange(num_classes, device=device)
  1026. labels = labels.view(1, -1).expand_as(scores)
  1027. # remove predictions with the background label
  1028. boxes = boxes[:, 1:]
  1029. scores = scores[:, 1:]
  1030. labels = labels[:, 1:]
  1031. # batch everything, by making every class prediction be a separate instance
  1032. boxes = boxes.reshape(-1, 4)
  1033. scores = scores.reshape(-1)
  1034. labels = labels.reshape(-1)
  1035. # remove low scoring boxes
  1036. inds = torch.where(scores > self.score_thresh)[0]
  1037. boxes, scores, labels = boxes[inds], scores[inds], labels[inds]
  1038. # remove empty boxes
  1039. keep = box_ops.remove_small_boxes(boxes, min_size=1e-2)
  1040. boxes, scores, labels = boxes[keep], scores[keep], labels[keep]
  1041. # non-maximum suppression, independently done per class
  1042. keep = box_ops.batched_nms(boxes, scores, labels, self.nms_thresh)
  1043. # keep only topk scoring predictions
  1044. keep = keep[: self.detections_per_img]
  1045. boxes, scores, labels = boxes[keep], scores[keep], labels[keep]
  1046. all_boxes.append(boxes)
  1047. all_scores.append(scores)
  1048. all_labels.append(labels)
  1049. return all_boxes, all_scores, all_labels
  1050. def forward(
  1051. self,
  1052. features, # type: Dict[str, Tensor]
  1053. proposals, # type: List[Tensor]
  1054. image_shapes, # type: List[Tuple[int, int]]
  1055. targets=None, # type: Optional[List[Dict[str, Tensor]]]
  1056. ):
  1057. # type: (...) -> Tuple[List[Dict[str, Tensor]], Dict[str, Tensor]]
  1058. """
  1059. Args:
  1060. features (List[Tensor])
  1061. proposals (List[Tensor[N, 4]])
  1062. image_shapes (List[Tuple[H, W]])
  1063. targets (List[Dict])
  1064. """
  1065. print(f'roihead forward!!!')
  1066. if targets is not None:
  1067. for t in targets:
  1068. # TODO: https://github.com/pytorch/pytorch/issues/26731
  1069. floating_point_types = (torch.float, torch.double, torch.half)
  1070. if not t["boxes"].dtype in floating_point_types:
  1071. raise TypeError(f"target boxes must of float type, instead got {t['boxes'].dtype}")
  1072. if not t["labels"].dtype == torch.int64:
  1073. raise TypeError(f"target labels must of int64 type, instead got {t['labels'].dtype}")
  1074. if self.has_keypoint():
  1075. if not t["keypoints"].dtype == torch.float32:
  1076. raise TypeError(f"target keypoints must of float type, instead got {t['keypoints'].dtype}")
  1077. if self.training:
  1078. proposals, matched_idxs, labels, regression_targets = self.select_training_samples(proposals, targets)
  1079. else:
  1080. if targets is not None:
  1081. proposals, matched_idxs, labels, regression_targets = self.select_training_samples(proposals, targets)
  1082. else:
  1083. labels = None
  1084. regression_targets = None
  1085. matched_idxs = None
  1086. box_features = self.box_roi_pool(features, proposals, image_shapes)
  1087. box_features = self.box_head(box_features)
  1088. class_logits, box_regression = self.box_predictor(box_features)
  1089. result: List[Dict[str, torch.Tensor]] = []
  1090. losses = {}
  1091. # _, C, H, W = features['0'].shape # 忽略 batch_size,因为我们只关心 C, H, W
  1092. if self.training:
  1093. if labels is None:
  1094. raise ValueError("labels cannot be None")
  1095. if regression_targets is None:
  1096. raise ValueError("regression_targets cannot be None")
  1097. print(f'boxes compute losses')
  1098. loss_classifier, loss_box_reg = fastrcnn_loss(class_logits, box_regression, labels, regression_targets)
  1099. losses = {"loss_classifier": loss_classifier, "loss_box_reg": loss_box_reg}
  1100. else:
  1101. if targets is not None:
  1102. loss_classifier, loss_box_reg = fastrcnn_loss(class_logits, box_regression, labels, regression_targets)
  1103. losses = {"loss_classifier": loss_classifier, "loss_box_reg": loss_box_reg}
  1104. boxes, scores, labels = self.postprocess_detections(class_logits, box_regression, proposals,
  1105. image_shapes)
  1106. num_images = len(boxes)
  1107. for i in range(num_images):
  1108. result.append(
  1109. {
  1110. "boxes": boxes[i],
  1111. "labels": labels[i],
  1112. "scores": scores[i],
  1113. }
  1114. )
  1115. if self.has_line():
  1116. print(f'roi_heads forward has_line()!!!!')
  1117. # print(f'labels:{labels}')
  1118. line_proposals = [p["boxes"] for p in result]
  1119. point_proposals = [p["boxes"] for p in result]
  1120. print(f'boxes_proposals:{len(line_proposals)}')
  1121. # if line_proposals is None or len(line_proposals) == 0:
  1122. # # 返回空特征或者跳过该部分计算
  1123. # return torch.empty(0, C, H, W).to(features['0'].device)
  1124. if self.training:
  1125. # during training, only focus on positive boxes
  1126. num_images = len(proposals)
  1127. print(f'num_images:{num_images}')
  1128. line_proposals = []
  1129. point_proposals = []
  1130. arc_proposals = []
  1131. pos_matched_idxs = []
  1132. line_pos_matched_idxs = []
  1133. point_pos_matched_idxs = []
  1134. if matched_idxs is None:
  1135. raise ValueError("if in trainning, matched_idxs should not be None")
  1136. for img_id in range(num_images):
  1137. pos = torch.where(labels[img_id] > 0)[0]
  1138. line_pos=torch.where(labels[img_id] ==2)[0]
  1139. point_pos=torch.where(labels[img_id] ==1)[0]
  1140. line_proposals.append(proposals[img_id][line_pos])
  1141. point_proposals.append(proposals[img_id][point_pos])
  1142. line_pos_matched_idxs.append(matched_idxs[img_id][line_pos])
  1143. point_pos_matched_idxs.append(matched_idxs[img_id][point_pos])
  1144. # pos_matched_idxs.append(matched_idxs[img_id][pos])
  1145. else:
  1146. if targets is not None:
  1147. pos_matched_idxs = []
  1148. num_images = len(proposals)
  1149. line_proposals = []
  1150. point_proposals=[]
  1151. arc_proposals=[]
  1152. line_pos_matched_idxs = []
  1153. point_pos_matched_idxs = []
  1154. print(f'val num_images:{num_images}')
  1155. if matched_idxs is None:
  1156. raise ValueError("if in trainning, matched_idxs should not be None")
  1157. for img_id in range(num_images):
  1158. pos = torch.where(labels[img_id] > 0)[0]
  1159. # line_proposals.append(proposals[img_id][pos])
  1160. # pos_matched_idxs.append(matched_idxs[img_id][pos])
  1161. line_pos = torch.where(labels[img_id] == 2)[0]
  1162. point_pos = torch.where(labels[img_id] == 1)[0]
  1163. line_proposals.append(proposals[img_id][line_pos])
  1164. point_proposals.append(proposals[img_id][point_pos])
  1165. line_pos_matched_idxs.append(matched_idxs[img_id][line_pos])
  1166. point_pos_matched_idxs.append(matched_idxs[img_id][point_pos])
  1167. else:
  1168. pos_matched_idxs = None
  1169. print(f'line_proposals:{len(line_proposals)}')
  1170. # line_features = self.line_roi_pool(features, line_proposals, image_shapes)
  1171. # print(f'line_features from line_roi_pool:{line_features.shape}')
  1172. #(b,256,512,512)
  1173. line_features = self.channel_compress(features['0'])
  1174. #(b.8,512,512)
  1175. all_proposals=line_proposals+point_proposals
  1176. # print(f'all_proposals:{all_proposals}')
  1177. filtered_proposals = [proposal for proposal in all_proposals if proposal.shape[0] > 0]
  1178. line_features = lines_features_align(line_features, filtered_proposals, image_shapes)
  1179. print(f'line_features from features_align:{line_features.shape}')
  1180. line_features = self.line_head(line_features)
  1181. #(N,1,512,512)
  1182. print(f'line_features from line_head:{line_features.shape}')
  1183. # line_logits = self.line_predictor(line_features)
  1184. line_logits = line_features
  1185. print(f'line_logits:{line_logits.shape}')
  1186. loss_line = {}
  1187. loss_line_iou = {}
  1188. loss_point = {}
  1189. if self.training:
  1190. if targets is None or pos_matched_idxs is None:
  1191. raise ValueError("both targets and pos_matched_idxs should not be None when in training mode")
  1192. gt_lines = [t["lines"] for t in targets]
  1193. gt_points = [t["points"] for t in targets]
  1194. print(f'gt_lines:{gt_lines[0].shape}')
  1195. h, w = targets[0]["img_size"]
  1196. img_size = h
  1197. # rcnn_loss_line = lines_point_pair_loss(
  1198. # line_logits, line_proposals, gt_lines, pos_matched_idxs
  1199. # )
  1200. # iou_loss = line_iou_loss(line_logits, line_proposals, gt_lines, pos_matched_idxs, img_size)
  1201. gt_lines_tensor=torch.cat(gt_lines)
  1202. gt_points_tensor = torch.cat(gt_points)
  1203. print(f'gt_lines_tensor:{gt_lines_tensor.shape}')
  1204. print(f'gt_points_tensor:{gt_points_tensor.shape}')
  1205. if gt_lines_tensor.shape[0]>0:
  1206. loss_line = lines_point_pair_loss(
  1207. line_logits, line_proposals, gt_lines, line_pos_matched_idxs
  1208. )
  1209. loss_line_iou = line_iou_loss(line_logits, line_proposals, gt_lines, line_pos_matched_idxs, img_size)
  1210. if gt_points_tensor.shape[0]>0:
  1211. loss_point = compute_point_loss(
  1212. line_logits, point_proposals, gt_points, point_pos_matched_idxs
  1213. )
  1214. if not loss_line:
  1215. loss_line = torch.tensor(0.0, device=line_features.device)
  1216. if not loss_line_iou:
  1217. loss_line_iou = torch.tensor(0.0, device=line_features.device)
  1218. loss_line = {"loss_line": loss_line}
  1219. loss_line_iou = {'loss_line_iou': loss_line_iou}
  1220. loss_point = {"loss_point": loss_point}
  1221. else:
  1222. if targets is not None:
  1223. h, w = targets[0]["img_size"]
  1224. img_size = h
  1225. gt_lines = [t["lines"] for t in targets]
  1226. gt_points = [t["points"] for t in targets]
  1227. gt_lines_tensor = torch.cat(gt_lines)
  1228. gt_points_tensor = torch.cat(gt_points)
  1229. if gt_lines_tensor.shape[0] > 0:
  1230. loss_line = lines_point_pair_loss(
  1231. line_logits, line_proposals, gt_lines, line_pos_matched_idxs
  1232. )
  1233. loss_line_iou = line_iou_loss(line_logits, line_proposals, gt_lines, line_pos_matched_idxs,
  1234. img_size)
  1235. if gt_points_tensor.shape[0] > 0:
  1236. loss_point = compute_point_loss(
  1237. line_logits, point_proposals, gt_points, point_pos_matched_idxs
  1238. )
  1239. if not loss_line :
  1240. loss_line=torch.tensor(0.0,device=line_features.device)
  1241. if not loss_line_iou :
  1242. loss_line_iou=torch.tensor(0.0,device=line_features.device)
  1243. loss_line = {"loss_line": loss_line}
  1244. loss_line_iou = {'loss_line_iou': loss_line_iou}
  1245. loss_point={"loss_point":loss_point}
  1246. else:
  1247. if line_logits is None or line_proposals is None:
  1248. raise ValueError(
  1249. "both keypoint_logits and keypoint_proposals should not be None when not in training mode"
  1250. )
  1251. lines_probs, lines_scores,point_probs,points_scores = line_inference(line_logits, line_proposals)
  1252. for keypoint_prob, kps, points,ps,r in zip(lines_probs, lines_scores,point_probs,points_scores, result):
  1253. print(f'points_prob :{points.shape}')
  1254. r["lines"] = keypoint_prob
  1255. r["liness_scores"] = kps
  1256. r["points"] = points
  1257. r["points_scores"] = ps
  1258. losses.update(loss_line)
  1259. losses.update(loss_line_iou)
  1260. losses.update(loss_point)
  1261. print(f'losses:{losses}')
  1262. if self.has_mask():
  1263. mask_proposals = [p["boxes"] for p in result]
  1264. if self.training:
  1265. if matched_idxs is None:
  1266. raise ValueError("if in training, matched_idxs should not be None")
  1267. # during training, only focus on positive boxes
  1268. num_images = len(proposals)
  1269. mask_proposals = []
  1270. pos_matched_idxs = []
  1271. for img_id in range(num_images):
  1272. pos = torch.where(labels[img_id] > 0)[0]
  1273. mask_proposals.append(proposals[img_id][pos])
  1274. pos_matched_idxs.append(matched_idxs[img_id][pos])
  1275. else:
  1276. pos_matched_idxs = None
  1277. if self.mask_roi_pool is not None:
  1278. mask_features = self.mask_roi_pool(features, mask_proposals, image_shapes)
  1279. mask_features = self.mask_head(mask_features)
  1280. mask_logits = self.mask_predictor(mask_features)
  1281. else:
  1282. raise Exception("Expected mask_roi_pool to be not None")
  1283. loss_mask = {}
  1284. if self.training:
  1285. if targets is None or pos_matched_idxs is None or mask_logits is None:
  1286. raise ValueError("targets, pos_matched_idxs, mask_logits cannot be None when training")
  1287. gt_masks = [t["masks"] for t in targets]
  1288. gt_labels = [t["labels"] for t in targets]
  1289. rcnn_loss_mask = maskrcnn_loss(mask_logits, mask_proposals, gt_masks, gt_labels, pos_matched_idxs)
  1290. loss_mask = {"loss_mask": rcnn_loss_mask}
  1291. else:
  1292. labels = [r["labels"] for r in result]
  1293. masks_probs = maskrcnn_inference(mask_logits, labels)
  1294. for mask_prob, r in zip(masks_probs, result):
  1295. r["masks"] = mask_prob
  1296. losses.update(loss_mask)
  1297. # keep none checks in if conditional so torchscript will conditionally
  1298. # compile each branch
  1299. if self.has_keypoint():
  1300. keypoint_proposals = [p["boxes"] for p in result]
  1301. if self.training:
  1302. # during training, only focus on positive boxes
  1303. num_images = len(proposals)
  1304. keypoint_proposals = []
  1305. pos_matched_idxs = []
  1306. if matched_idxs is None:
  1307. raise ValueError("if in trainning, matched_idxs should not be None")
  1308. for img_id in range(num_images):
  1309. pos = torch.where(labels[img_id] > 0)[0]
  1310. keypoint_proposals.append(proposals[img_id][pos])
  1311. pos_matched_idxs.append(matched_idxs[img_id][pos])
  1312. else:
  1313. pos_matched_idxs = None
  1314. keypoint_features = self.line_roi_pool(features, keypoint_proposals, image_shapes)
  1315. keypoint_features = self.line_head(keypoint_features)
  1316. keypoint_logits = self.line_predictor(keypoint_features)
  1317. loss_keypoint = {}
  1318. if self.training:
  1319. if targets is None or pos_matched_idxs is None:
  1320. raise ValueError("both targets and pos_matched_idxs should not be None when in training mode")
  1321. gt_keypoints = [t["keypoints"] for t in targets]
  1322. rcnn_loss_keypoint = keypointrcnn_loss(
  1323. keypoint_logits, keypoint_proposals, gt_keypoints, pos_matched_idxs
  1324. )
  1325. loss_keypoint = {"loss_keypoint": rcnn_loss_keypoint}
  1326. else:
  1327. if keypoint_logits is None or keypoint_proposals is None:
  1328. raise ValueError(
  1329. "both keypoint_logits and keypoint_proposals should not be None when not in training mode"
  1330. )
  1331. keypoints_probs, lines_scores = keypointrcnn_inference(keypoint_logits, keypoint_proposals)
  1332. for keypoint_prob, kps, r in zip(keypoints_probs, lines_scores, result):
  1333. r["keypoints"] = keypoint_prob
  1334. r["keypoints_scores"] = kps
  1335. losses.update(loss_keypoint)
  1336. return result, losses