loi_heads.py 59 KB

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