loi_heads.py 54 KB

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