loi_heads.py 54 KB

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