loi_heads.py 63 KB

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