head_losses.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868
  1. import torch
  2. from matplotlib import pyplot as plt
  3. import torch.nn.functional as F
  4. def features_align(features, proposals, img_size):
  5. print(f'lines_features_align features:{features.shape},proposals:{len(proposals)}')
  6. align_feat_list = []
  7. for feat, proposals_per_img in zip(features, proposals):
  8. print(f'lines_features_align feat:{feat.shape}, proposals_per_img:{proposals_per_img.shape}')
  9. if proposals_per_img.shape[0]>0:
  10. feat = feat.unsqueeze(0)
  11. for proposal in proposals_per_img:
  12. align_feat = torch.zeros_like(feat)
  13. # print(f'align_feat:{align_feat.shape}')
  14. x1, y1, x2, y2 = map(lambda v: int(v.item()), proposal)
  15. # 将每个proposal框内的部分赋值到align_feats对应位置
  16. align_feat[:, :, y1:y2 + 1, x1:x2 + 1] = feat[:, :, y1:y2 + 1, x1:x2 + 1]
  17. align_feat_list.append(align_feat)
  18. # print(f'align_feat_list:{align_feat_list}')
  19. if len(align_feat_list) > 0:
  20. feats_tensor = torch.cat(align_feat_list)
  21. print(f'align features :{feats_tensor.shape}')
  22. else:
  23. feats_tensor = None
  24. return feats_tensor
  25. def normalize_tensor(t):
  26. return (t - t.min()) / (t.max() - t.min() + 1e-6)
  27. def line_length(lines):
  28. """
  29. 计算每条线段的长度
  30. lines: [N, 2, 2] 表示 N 条线段,每条线段由两个点组成
  31. 返回: [N]
  32. """
  33. return torch.norm(lines[:, 1] - lines[:, 0], dim=-1)
  34. def line_direction(lines):
  35. """
  36. 计算每条线段的单位方向向量
  37. lines: [N, 2, 2]
  38. 返回: [N, 2] 单位方向向量
  39. """
  40. vec = lines[:, 1] - lines[:, 0]
  41. return F.normalize(vec, dim=-1)
  42. def angle_loss_cosine(pred_dir, gt_dir):
  43. """
  44. 使用 cosine similarity 计算方向差异
  45. pred_dir: [N, 2]
  46. gt_dir: [N, 2]
  47. 返回: [N]
  48. """
  49. cos_sim = torch.sum(pred_dir * gt_dir, dim=-1).clamp(-1.0, 1.0)
  50. return 1.0 - cos_sim # 或者 torch.acos(cos_sim) / pi 也可
  51. def line_length(lines):
  52. """
  53. 计算每条线段的长度
  54. lines: [N, 2, 2] 表示 N 条线段,每条线段由两个点组成
  55. 返回: [N]
  56. """
  57. return torch.norm(lines[:, 1] - lines[:, 0], dim=-1)
  58. def line_direction(lines):
  59. """
  60. 计算每条线段的单位方向向量
  61. lines: [N, 2, 2]
  62. 返回: [N, 2] 单位方向向量
  63. """
  64. vec = lines[:, 1] - lines[:, 0]
  65. return F.normalize(vec, dim=-1)
  66. def angle_loss_cosine(pred_dir, gt_dir):
  67. """
  68. 使用 cosine similarity 计算方向差异
  69. pred_dir: [N, 2]
  70. gt_dir: [N, 2]
  71. 返回: [N]
  72. """
  73. cos_sim = torch.sum(pred_dir * gt_dir, dim=-1).clamp(-1.0, 1.0)
  74. return 1.0 - cos_sim # 或者 torch.acos(cos_sim) / pi 也可
  75. def single_point_to_heatmap(keypoints, rois, heatmap_size):
  76. # type: (Tensor, Tensor, int) -> Tensor
  77. print(f'rois:{rois.shape}')
  78. print(f'heatmap_size:{heatmap_size}')
  79. print(f'keypoints.shape:{keypoints.shape}')
  80. # batch_size, num_keypoints, _ = keypoints.shape
  81. x = keypoints[..., 0].unsqueeze(1)
  82. y = keypoints[..., 1].unsqueeze(1)
  83. gs = generate_gaussian_heatmaps(x, y,num_points=1, heatmap_size=heatmap_size, sigma=1.0)
  84. # show_heatmap(gs[0],'target')
  85. all_roi_heatmap = []
  86. for roi, heatmap in zip(rois, gs):
  87. # show_heatmap(heatmap, 'target')
  88. # print(f'heatmap:{heatmap.shape}')
  89. heatmap = heatmap.unsqueeze(0)
  90. x1, y1, x2, y2 = map(int, roi)
  91. roi_heatmap = torch.zeros_like(heatmap)
  92. roi_heatmap[..., y1:y2 + 1, x1:x2 + 1] = heatmap[..., y1:y2 + 1, x1:x2 + 1]
  93. # show_heatmap(roi_heatmap[0],'roi_heatmap')
  94. all_roi_heatmap.append(roi_heatmap)
  95. all_roi_heatmap = torch.cat(all_roi_heatmap)
  96. print(f'all_roi_heatmap:{all_roi_heatmap.shape}')
  97. return all_roi_heatmap
  98. def line_points_to_heatmap(keypoints, rois, heatmap_size):
  99. # type: (Tensor, Tensor, int) -> Tensor
  100. print(f'rois:{rois.shape}')
  101. print(f'heatmap_size:{heatmap_size}')
  102. print(f'keypoints.shape:{keypoints.shape}')
  103. # batch_size, num_keypoints, _ = keypoints.shape
  104. x = keypoints[..., 0]
  105. y = keypoints[..., 1]
  106. gs = generate_gaussian_heatmaps(x, y, heatmap_size,num_points=2, sigma=1.0)
  107. # show_heatmap(gs[0],'target')
  108. all_roi_heatmap = []
  109. for roi, heatmap in zip(rois, gs):
  110. # print(f'heatmap:{heatmap.shape}')
  111. # show_heatmap(heatmap,'target')
  112. heatmap = heatmap.unsqueeze(0)
  113. x1, y1, x2, y2 = map(int, roi)
  114. roi_heatmap = torch.zeros_like(heatmap)
  115. roi_heatmap[..., y1:y2 + 1, x1:x2 + 1] = heatmap[..., y1:y2 + 1, x1:x2 + 1]
  116. # show_heatmap(roi_heatmap[0],'roi_heatmap')
  117. all_roi_heatmap.append(roi_heatmap)
  118. if len(all_roi_heatmap) > 0:
  119. all_roi_heatmap = torch.cat(all_roi_heatmap)
  120. print(f'all_roi_heatmap:{all_roi_heatmap.shape}')
  121. else:
  122. all_roi_heatmap = None
  123. return all_roi_heatmap
  124. """
  125. 修改适配的原结构的点 转热图,适用于带roi_pool版本的
  126. """
  127. def line_points_to_heatmap_(keypoints, rois, heatmap_size):
  128. # type: (Tensor, Tensor, int) -> Tuple[Tensor, Tensor]
  129. print(f'rois:{rois.shape}')
  130. print(f'heatmap_size:{heatmap_size}')
  131. offset_x = rois[:, 0]
  132. offset_y = rois[:, 1]
  133. scale_x = heatmap_size / (rois[:, 2] - rois[:, 0])
  134. scale_y = heatmap_size / (rois[:, 3] - rois[:, 1])
  135. offset_x = offset_x[:, None]
  136. offset_y = offset_y[:, None]
  137. scale_x = scale_x[:, None]
  138. scale_y = scale_y[:, None]
  139. print(f'keypoints.shape:{keypoints.shape}')
  140. # batch_size, num_keypoints, _ = keypoints.shape
  141. x = keypoints[..., 0]
  142. y = keypoints[..., 1]
  143. # gs=generate_gaussian_heatmaps(x,y,512,1.0)
  144. # print(f'gs_heatmap shape:{gs.shape}')
  145. #
  146. # show_heatmap(gs[0],'target')
  147. x_boundary_inds = x == rois[:, 2][:, None]
  148. y_boundary_inds = y == rois[:, 3][:, None]
  149. x = (x - offset_x) * scale_x
  150. x = x.floor().long()
  151. y = (y - offset_y) * scale_y
  152. y = y.floor().long()
  153. x[x_boundary_inds] = heatmap_size - 1
  154. y[y_boundary_inds] = heatmap_size - 1
  155. # print(f'heatmaps x:{x}')
  156. # print(f'heatmaps y:{y}')
  157. valid_loc = (x >= 0) & (y >= 0) & (x < heatmap_size) & (y < heatmap_size)
  158. vis = keypoints[..., 2] > 0
  159. valid = (valid_loc & vis).long()
  160. gs_heatmap = generate_gaussian_heatmaps(x, y, heatmap_size, 1.0)
  161. # show_heatmap(gs_heatmap[0], 'feature')
  162. # print(f'gs_heatmap:{gs_heatmap.shape}')
  163. #
  164. # lin_ind = y * heatmap_size + x
  165. # print(f'lin_ind:{lin_ind.shape}')
  166. # heatmaps = lin_ind * valid
  167. return gs_heatmap
  168. def generate_gaussian_heatmaps(xs, ys, heatmap_size,num_points=2, sigma=2.0, device='cuda'):
  169. """
  170. 为一组点生成并合并高斯热图。
  171. Args:
  172. xs (Tensor): 形状为 (N, 2) 的所有点的 x 坐标
  173. ys (Tensor): 形状为 (N, 2) 的所有点的 y 坐标
  174. heatmap_size (int): 热图大小 H=W
  175. sigma (float): 高斯核标准差
  176. device (str): 设备类型 ('cpu' or 'cuda')
  177. Returns:
  178. Tensor: 形状为 (H, W) 的合并后的热图
  179. """
  180. assert xs.shape == ys.shape, "x and y must have the same shape"
  181. print(f'xs:{xs.shape}')
  182. # xs=xs.squeeze(1)
  183. # ys = ys.squeeze(1)
  184. print(f'xs1:{xs.shape}')
  185. N = xs.shape[0]
  186. print(f'N:{N},num_points:{num_points}')
  187. # 创建网格
  188. grid_y, grid_x = torch.meshgrid(
  189. torch.arange(heatmap_size, device=device),
  190. torch.arange(heatmap_size, device=device),
  191. indexing='ij'
  192. )
  193. # print(f'heatmap_size:{heatmap_size}')
  194. # 初始化输出热图
  195. combined_heatmap = torch.zeros((N, heatmap_size, heatmap_size), device=device)
  196. for i in range(N):
  197. heatmap= torch.zeros((heatmap_size, heatmap_size), device=device)
  198. for j in range(num_points):
  199. mu_x1 = xs[i, j].clamp(0, heatmap_size - 1).item()
  200. mu_y1 = ys[i, j].clamp(0, heatmap_size - 1).item()
  201. # print(f'mu_x1,mu_y1:{mu_x1},{mu_y1}')
  202. # 计算距离平方
  203. dist1 = (grid_x - mu_x1) ** 2 + (grid_y - mu_y1) ** 2
  204. # 计算高斯分布
  205. heatmap1 = torch.exp(-dist1 / (2 * sigma ** 2))
  206. heatmap+=heatmap1
  207. # mu_x2 = xs[i, 1].clamp(0, heatmap_size - 1).item()
  208. # mu_y2 = ys[i, 1].clamp(0, heatmap_size - 1).item()
  209. #
  210. # # 计算距离平方
  211. # dist2 = (grid_x - mu_x2) ** 2 + (grid_y - mu_y2) ** 2
  212. #
  213. # # 计算高斯分布
  214. # heatmap2 = torch.exp(-dist2 / (2 * sigma ** 2))
  215. #
  216. # heatmap = heatmap1 + heatmap2
  217. # 将当前热图累加到结果中
  218. combined_heatmap[i] = heatmap
  219. return combined_heatmap
  220. def generate_mask_gaussian_heatmaps(xs, ys, heatmap_size,num_points=2, sigma=2.0, device='cuda'):
  221. """
  222. 为一组点生成并合并高斯热图。
  223. Args:
  224. xs (Tensor): 形状为 (N, 2) 的所有点的 x 坐标
  225. ys (Tensor): 形状为 (N, 2) 的所有点的 y 坐标
  226. heatmap_size (int): 热图大小 H=W
  227. sigma (float): 高斯核标准差
  228. device (str): 设备类型 ('cpu' or 'cuda')
  229. Returns:
  230. Tensor: 形状为 (H, W) 的合并后的热图
  231. """
  232. assert xs.shape == ys.shape, "x and y must have the same shape"
  233. print(f'xs:{xs.shape}')
  234. xs=xs.squeeze(1)
  235. ys = ys.squeeze(1)
  236. print(f'xs1:{xs.shape}')
  237. N = xs.shape[0]
  238. print(f'N:{N},num_points:{num_points}')
  239. # 创建网格
  240. grid_y, grid_x = torch.meshgrid(
  241. torch.arange(heatmap_size, device=device),
  242. torch.arange(heatmap_size, device=device),
  243. indexing='ij'
  244. )
  245. # print(f'heatmap_size:{heatmap_size}')
  246. # 初始化输出热图
  247. combined_heatmap = torch.zeros((N, heatmap_size, heatmap_size), device=device)
  248. for i in range(N):
  249. heatmap= torch.zeros((heatmap_size, heatmap_size), device=device)
  250. for j in range(num_points):
  251. mu_x1 = xs[i, j].clamp(0, heatmap_size - 1).item()
  252. mu_y1 = ys[i, j].clamp(0, heatmap_size - 1).item()
  253. # print(f'mu_x1,mu_y1:{mu_x1},{mu_y1}')
  254. # 计算距离平方
  255. dist1 = (grid_x - mu_x1) ** 2 + (grid_y - mu_y1) ** 2
  256. # 计算高斯分布
  257. heatmap1 = torch.exp(-dist1 / (2 * sigma ** 2))
  258. heatmap+=heatmap1
  259. # mu_x2 = xs[i, 1].clamp(0, heatmap_size - 1).item()
  260. # mu_y2 = ys[i, 1].clamp(0, heatmap_size - 1).item()
  261. #
  262. # # 计算距离平方
  263. # dist2 = (grid_x - mu_x2) ** 2 + (grid_y - mu_y2) ** 2
  264. #
  265. # # 计算高斯分布
  266. # heatmap2 = torch.exp(-dist2 / (2 * sigma ** 2))
  267. #
  268. # heatmap = heatmap1 + heatmap2
  269. # 将当前热图累加到结果中
  270. combined_heatmap[i] = heatmap
  271. return combined_heatmap
  272. def non_maximum_suppression(a):
  273. ap = F.max_pool2d(a, 3, stride=1, padding=1)
  274. mask = (a == ap).float().clamp(min=0.0)
  275. return a * mask
  276. def heatmaps_to_points(maps, rois):
  277. point_preds = torch.zeros((len(rois), 2), dtype=torch.float32, device=maps.device)
  278. point_end_scores = torch.zeros((len(rois), 1), dtype=torch.float32, device=maps.device)
  279. print(f'heatmaps_to_lines:{maps.shape}')
  280. point_maps=maps[:,0]
  281. print(f'point_map:{point_maps.shape}')
  282. for i in range(len(rois)):
  283. point_roi_map = point_maps[i].unsqueeze(0)
  284. print(f'point_roi_map:{point_roi_map.shape}')
  285. # roi_map_probs = scores_to_probs(roi_map.copy())
  286. w = point_roi_map.shape[2]
  287. flatten_point_roi_map = non_maximum_suppression(point_roi_map).reshape(1, -1)
  288. point_score, point_index = torch.topk(flatten_point_roi_map, k=1)
  289. print(f'point index:{point_index}')
  290. # pos = roi_map.reshape(num_keypoints, -1).argmax(dim=1)
  291. point_x =point_index % w
  292. point_y = torch.div(point_index - point_x, w, rounding_mode="floor")
  293. point_preds[i, 0,] = point_x
  294. point_preds[i, 1,] = point_y
  295. point_end_scores[i, :] = point_roi_map[torch.arange(1, device=point_roi_map.device), point_y, point_x]
  296. return point_preds,point_end_scores
  297. def heatmaps_to_lines(maps, rois):
  298. line_preds = torch.zeros((len(rois), 3, 2), dtype=torch.float32, device=maps.device)
  299. line_end_scores = torch.zeros((len(rois), 2), dtype=torch.float32, device=maps.device)
  300. line_maps=maps[:,1]
  301. for i in range(len(rois)):
  302. line_roi_map = line_maps[i].unsqueeze(0)
  303. print(f'line_roi_map:{line_roi_map.shape}')
  304. # roi_map_probs = scores_to_probs(roi_map.copy())
  305. w = line_roi_map.shape[1]
  306. flatten_line_roi_map = non_maximum_suppression(line_roi_map).reshape(1, -1)
  307. line_score, line_index = torch.topk(flatten_line_roi_map, k=2)
  308. print(f'line index:{line_index}')
  309. # pos = roi_map.reshape(num_keypoints, -1).argmax(dim=1)
  310. pos = line_index
  311. line_x = pos % w
  312. line_y = torch.div(pos - line_x, w, rounding_mode="floor")
  313. line_preds[i, 0, :] = line_x
  314. line_preds[i, 1, :] = line_y
  315. line_preds[i, 2, :] = 1
  316. line_end_scores[i, :] = line_roi_map[torch.arange(1, device=line_roi_map.device), line_y, line_x]
  317. return line_preds.permute(0, 2, 1), line_end_scores
  318. # 显示热图的函数
  319. def show_heatmap(heatmap, title="Heatmap"):
  320. """
  321. 使用 matplotlib 显示热图。
  322. Args:
  323. heatmap (Tensor): 要显示的热图张量
  324. title (str): 图表标题
  325. """
  326. # 如果在 GPU 上,首先将其移动到 CPU 并转换为 numpy 数组
  327. if heatmap.is_cuda:
  328. heatmap = heatmap.cpu().numpy()
  329. else:
  330. heatmap = heatmap.numpy()
  331. plt.imshow(heatmap, cmap='hot', interpolation='nearest')
  332. plt.colorbar()
  333. plt.title(title)
  334. plt.show()
  335. def lines_point_pair_loss(line_logits, proposals, gt_lines, line_matched_idxs):
  336. # type: (Tensor, List[Tensor], List[Tensor], List[Tensor]) -> Tensor
  337. N, K, H, W = line_logits.shape
  338. len_proposals = len(proposals)
  339. print(f'lines_point_pair_loss line_logits.shape:{line_logits.shape},len_proposals:{len_proposals},line_matched_idxs:{line_matched_idxs}')
  340. if H != W:
  341. raise ValueError(
  342. f"line_logits height and width (last two elements of shape) should be equal. Instead got H = {H} and W = {W}"
  343. )
  344. discretization_size = H
  345. heatmaps = []
  346. gs_heatmaps = []
  347. valid = []
  348. for proposals_per_image, gt_kp_in_image, midx in zip(proposals, gt_lines, line_matched_idxs):
  349. print(f'line_proposals_per_image:{proposals_per_image.shape}')
  350. print(f'gt_lines:{gt_lines}')
  351. if proposals_per_image.shape[0] > 0 and gt_kp_in_image.shape[0] > 0:
  352. kp = gt_kp_in_image[midx]
  353. gs_heatmaps_per_img = line_points_to_heatmap(kp, proposals_per_image, discretization_size)
  354. gs_heatmaps.append(gs_heatmaps_per_img)
  355. # print(f'heatmaps_per_image:{heatmaps_per_image.shape}')
  356. # heatmaps.append(heatmaps_per_image.view(-1))
  357. # valid.append(valid_per_image.view(-1))
  358. # line_targets = torch.cat(heatmaps, dim=0)
  359. gs_heatmaps = torch.cat(gs_heatmaps, dim=0)
  360. print(f'gs_heatmaps:{gs_heatmaps.shape}, line_logits.shape:{line_logits.squeeze(1).shape}')
  361. # print(f'line_targets:{line_targets.shape},{line_targets}')
  362. # valid = torch.cat(valid, dim=0).to(dtype=torch.uint8)
  363. # valid = torch.where(valid)[0]
  364. # print(f' line_targets[valid]:{line_targets[valid]}')
  365. # torch.mean (in binary_cross_entropy_with_logits) doesn't
  366. # accept empty tensors, so handle it sepaartely
  367. # if line_targets.numel() == 0 or len(valid) == 0:
  368. # return line_logits.sum() * 0
  369. # line_logits = line_logits.view(N * K, H * W)
  370. # print(f'line_logits[valid]:{line_logits[valid].shape}')
  371. print(f'loss1 line_logits:{line_logits.shape}')
  372. line_logits = line_logits[:,1,:,:]
  373. print(f'loss2 line_logits:{line_logits.shape}')
  374. # line_loss = F.cross_entropy(line_logits[valid], line_targets[valid])
  375. line_loss = F.cross_entropy(line_logits, gs_heatmaps)
  376. return line_loss
  377. def compute_arc_loss(feature_logits, proposals, gt_, pos_matched_idxs):
  378. print(f'compute_arc_loss:{feature_logits.shape}')
  379. N, K, H, W = feature_logits.shape
  380. len_proposals = len(proposals)
  381. empty_count = 0
  382. non_empty_count = 0
  383. for prop in proposals:
  384. if prop.shape[0] == 0:
  385. empty_count += 1
  386. else:
  387. non_empty_count += 1
  388. print(f"Empty proposals count: {empty_count}")
  389. print(f"Non-empty proposals count: {non_empty_count}")
  390. print(f'starte to compute_point_loss')
  391. print(f'compute_point_loss line_logits.shape:{feature_logits.shape},len_proposals:{len_proposals}')
  392. if H != W:
  393. raise ValueError(
  394. f"line_logits height and width (last two elements of shape) should be equal. Instead got H = {H} and W = {W}"
  395. )
  396. discretization_size = H
  397. gs_heatmaps = []
  398. # print(f'point_matched_idxs:{point_matched_idxs}')
  399. for proposals_per_image, gt_kp_in_image, midx in zip(proposals, gt_, pos_matched_idxs):
  400. # [
  401. # (Tensor(38, 4), Tensor(1, 57, 2), Tensor(38, 1)),
  402. # (Tensor(65, 4), Tensor(1, 74, 2), Tensor(65, 1))
  403. # ]
  404. print(f'proposals_per_image:{proposals_per_image.shape}')
  405. kp = gt_kp_in_image[midx]
  406. # print(f'gt_kp_in_image:{gt_kp_in_image}')
  407. if proposals_per_image.shape[0] > 0 and gt_kp_in_image.shape[0] > 0:
  408. gs_heatmaps_per_img = arc_points_to_heatmap(kp, proposals_per_image, discretization_size)
  409. gs_heatmaps.append(gs_heatmaps_per_img)
  410. if len(gs_heatmaps)>0:
  411. gs_heatmaps = torch.cat(gs_heatmaps, dim=0)
  412. print(f'gs_heatmaps:{gs_heatmaps.shape}, line_logits.shape:{feature_logits.squeeze(1).shape}')
  413. line_logits = feature_logits[:, 0]
  414. print(f'single_point_logits:{line_logits.shape}')
  415. line_loss = F.binary_cross_entropy_with_logits(line_logits, gs_heatmaps)
  416. # line_loss = F.cross_entropy(line_logits, gs_heatmaps)
  417. else:
  418. line_loss=100
  419. print("d")
  420. return line_loss
  421. def arc_points_to_heatmap(keypoints, rois, heatmap_size):
  422. print(f'rois:{rois.shape}')
  423. print(f'heatmap_size:{heatmap_size}')
  424. print(f'keypoints.shape:{keypoints.shape}')
  425. # batch_size, num_keypoints, _ = keypoints.shape
  426. x = keypoints[..., 0].unsqueeze(1)
  427. y = keypoints[..., 1].unsqueeze(1)
  428. num_points=x.shape[2]
  429. print(f'num_points:{num_points}')
  430. gs = generate_mask_gaussian_heatmaps(x, y, num_points=num_points, heatmap_size=heatmap_size, sigma=1.0)
  431. # show_heatmap(gs[0],'target')
  432. all_roi_heatmap = []
  433. for roi, heatmap in zip(rois, gs):
  434. # show_heatmap(heatmap, 'target')
  435. print(f'heatmap:{heatmap.shape}')
  436. heatmap = heatmap.unsqueeze(0)
  437. x1, y1, x2, y2 = map(int, roi)
  438. roi_heatmap = torch.zeros_like(heatmap)
  439. roi_heatmap[..., y1:y2 + 1, x1:x2 + 1] = heatmap[..., y1:y2 + 1, x1:x2 + 1]
  440. # show_heatmap(roi_heatmap[0],'roi_heatmap')
  441. all_roi_heatmap.append(roi_heatmap)
  442. all_roi_heatmap = torch.cat(all_roi_heatmap)
  443. print(f'all_roi_heatmap:{all_roi_heatmap.shape}')
  444. return all_roi_heatmap
  445. def compute_point_loss(line_logits, proposals, gt_points, point_matched_idxs):
  446. # type: (Tensor, List[Tensor], List[Tensor], List[Tensor]) -> Tensor
  447. N, K, H, W = line_logits.shape
  448. len_proposals = len(proposals)
  449. empty_count = 0
  450. non_empty_count = 0
  451. for prop in proposals:
  452. if prop.shape[0] == 0:
  453. empty_count += 1
  454. else:
  455. non_empty_count += 1
  456. print(f"Empty proposals count: {empty_count}")
  457. print(f"Non-empty proposals count: {non_empty_count}")
  458. print(f'starte to compute_point_loss')
  459. print(f'compute_point_loss line_logits.shape:{line_logits.shape},len_proposals:{len_proposals}')
  460. if H != W:
  461. raise ValueError(
  462. f"line_logits height and width (last two elements of shape) should be equal. Instead got H = {H} and W = {W}"
  463. )
  464. discretization_size = H
  465. gs_heatmaps = []
  466. # print(f'point_matched_idxs:{point_matched_idxs}')
  467. for proposals_per_image, gt_kp_in_image, midx in zip(proposals, gt_points, point_matched_idxs):
  468. print(f'proposals_per_image:{proposals_per_image.shape}')
  469. kp = gt_kp_in_image[midx]
  470. # print(f'gt_kp_in_image:{gt_kp_in_image}')
  471. gs_heatmaps_per_img = single_point_to_heatmap(kp, proposals_per_image, discretization_size)
  472. gs_heatmaps.append(gs_heatmaps_per_img)
  473. gs_heatmaps = torch.cat(gs_heatmaps, dim=0)
  474. print(f'gs_heatmaps:{gs_heatmaps.shape}, line_logits.shape:{line_logits.squeeze(1).shape}')
  475. line_logits = line_logits[:,0]
  476. print(f'single_point_logits:{line_logits.shape}')
  477. line_loss = F.cross_entropy(line_logits, gs_heatmaps)
  478. return line_loss
  479. def lines_to_boxes(lines, img_size=511):
  480. """
  481. 输入:
  482. lines: Tensor of shape (N, 2, 2),表示 N 条线段,每个线段有两个端点 (x, y)
  483. img_size: int,图像尺寸,用于 clamp 边界
  484. 输出:
  485. boxes: Tensor of shape (N, 4),表示 N 个包围盒 [x_min, y_min, x_max, y_max]
  486. """
  487. # 提取所有线段的两个端点
  488. p1 = lines[:, 0] # (N, 2)
  489. p2 = lines[:, 1] # (N, 2)
  490. # 每条线段的 x 和 y 坐标
  491. x_coords = torch.stack([p1[:, 0], p2[:, 0]], dim=1) # (N, 2)
  492. y_coords = torch.stack([p1[:, 1], p2[:, 1]], dim=1) # (N, 2)
  493. # 计算包围盒边界
  494. x_min = x_coords.min(dim=1).values
  495. y_min = y_coords.min(dim=1).values
  496. x_max = x_coords.max(dim=1).values
  497. y_max = y_coords.max(dim=1).values
  498. # 扩展边界并限制在图像范围内
  499. x_min = (x_min - 1).clamp(min=0, max=img_size)
  500. y_min = (y_min - 1).clamp(min=0, max=img_size)
  501. x_max = (x_max + 1).clamp(min=0, max=img_size)
  502. y_max = (y_max + 1).clamp(min=0, max=img_size)
  503. # 合成包围盒
  504. boxes = torch.stack([x_min, y_min, x_max, y_max], dim=1) # (N, 4)
  505. return boxes
  506. def box_iou_pairwise(box1, box2):
  507. """
  508. 输入:
  509. box1: shape (N, 4)
  510. box2: shape (M, 4)
  511. 输出:
  512. ious: shape (min(N, M), ), 只计算 i = j 的配对
  513. """
  514. N = min(len(box1), len(box2))
  515. lt = torch.max(box1[:N, :2], box2[:N, :2]) # 左上角
  516. rb = torch.min(box1[:N, 2:], box2[:N, 2:]) # 右下角
  517. wh = (rb - lt).clamp(min=0) # 宽高
  518. inter_area = wh[:, 0] * wh[:, 1] # 交集面积
  519. area1 = (box1[:N, 2] - box1[:N, 0]) * (box1[:N, 3] - box1[:N, 1])
  520. area2 = (box2[:N, 2] - box2[:N, 0]) * (box2[:N, 3] - box2[:N, 1])
  521. union_area = area1 + area2 - inter_area
  522. ious = inter_area / (union_area + 1e-6)
  523. return ious
  524. def line_iou_loss(x, boxes, gt_lines, matched_idx, img_size=511, alpha=1.0, beta=1.0, gamma=1.0):
  525. """
  526. Args:
  527. x: [N,1,H,W] 热力图
  528. boxes: [N,4] 框坐标
  529. gt_lines: [N,2,3] GT线段(含可见性)
  530. matched_idx: 匹配 index
  531. img_size: 图像尺寸
  532. alpha: IoU 损失权重
  533. beta: 长度损失权重
  534. gamma: 方向角度损失权重
  535. """
  536. losses = []
  537. boxes_per_image = [box.size(0) for box in boxes]
  538. x2 = x.split(boxes_per_image, dim=0)
  539. for xx, bb, gt_line, mid in zip(x2, boxes, gt_lines, matched_idx):
  540. p_prob, _ = heatmaps_to_lines(xx, bb)
  541. pred_lines = p_prob
  542. gt_line_points = gt_line[mid]
  543. if len(pred_lines) == 0 or len(gt_line_points) == 0:
  544. continue
  545. # IoU 损失
  546. pred_boxes = lines_to_boxes(pred_lines, img_size)
  547. gt_boxes = lines_to_boxes(gt_line_points, img_size)
  548. ious = box_iou_pairwise(pred_boxes, gt_boxes)
  549. iou_loss = 1.0 - ious # [N]
  550. # 长度损失
  551. pred_len = line_length(pred_lines)
  552. gt_len = line_length(gt_line_points)
  553. length_diff = F.l1_loss(pred_len, gt_len, reduction='none') # [N]
  554. # 方向角度损失
  555. pred_dir = line_direction(pred_lines)
  556. gt_dir = line_direction(gt_line_points)
  557. ang_loss = angle_loss_cosine(pred_dir, gt_dir) # [N]
  558. # 归一化每一项损失
  559. norm_iou = normalize_tensor(iou_loss)
  560. norm_len = normalize_tensor(length_diff)
  561. norm_ang = normalize_tensor(ang_loss)
  562. total = alpha * norm_iou + beta * norm_len + gamma * norm_ang
  563. losses.append(total)
  564. if not losses:
  565. return None
  566. return torch.mean(torch.cat(losses))
  567. def point_inference(x, point_boxes):
  568. # type: (Tensor, List[Tensor]) -> Tuple[List[Tensor], List[Tensor]]
  569. points_probs = []
  570. points_scores = []
  571. boxes_per_image = [box.size(0) for box in point_boxes]
  572. x2 = x.split(boxes_per_image, dim=0)
  573. for xx, bb in zip(x2, point_boxes):
  574. point_prob,point_scores = heatmaps_to_points(xx, bb)
  575. points_probs.append(point_prob.unsqueeze(1))
  576. points_scores.append(point_scores)
  577. return points_probs,points_scores
  578. def line_inference(x, line_boxes):
  579. # type: (Tensor, List[Tensor]) -> Tuple[List[Tensor], List[Tensor]]
  580. lines_probs = []
  581. lines_scores = []
  582. boxes_per_image = [box.size(0) for box in line_boxes]
  583. x2 = x.split(boxes_per_image, dim=0)
  584. # x2:tuple 2 x2[0]:[1,3,1024,1024]
  585. # line_box: list:2 [1,4] [1.4] fasterrcnn kuang
  586. for xx, bb in zip(x2, line_boxes):
  587. line_prob, line_scores, = heatmaps_to_lines(xx, bb)
  588. lines_probs.append(line_prob)
  589. lines_scores.append(line_scores)
  590. return lines_probs, lines_scores
  591. def arc_inference(x, arc_boxes):
  592. # type: (Tensor, List[Tensor]) -> Tuple[List[Tensor], List[Tensor]]
  593. points_probs = []
  594. points_scores = []
  595. print(f'arc_boxes:{len(arc_boxes)}')
  596. boxes_per_image = [box.size(0) for box in arc_boxes]
  597. print(f'arc boxes_per_image:{boxes_per_image}')
  598. x2 = x.split(boxes_per_image, dim=0)
  599. for xx, bb in zip(x2, arc_boxes):
  600. point_prob,point_scores = heatmaps_to_arc(xx, bb)
  601. points_probs.append(point_prob.unsqueeze(1))
  602. points_scores.append(point_scores)
  603. points_probs_tensor=torch.cat(points_probs)
  604. print(f'points_probs shape:{points_probs_tensor.shape}')
  605. return points_probs,points_scores
  606. import torch.nn.functional as F
  607. def heatmaps_to_arc(maps, rois, threshold=0.1, output_size=(128, 128)):
  608. """
  609. Args:
  610. maps: [N, 3, H, W] - full heatmaps
  611. rois: [N, 4] - bounding boxes
  612. threshold: float - binarization threshold
  613. output_size: resized size for uniform NMS
  614. Returns:
  615. masks: [N, 1, H, W] - binary mask aligned with input map
  616. scores: [N, 1] - count of non-zero pixels in each mask
  617. """
  618. N, _, H, W = maps.shape
  619. masks = torch.zeros((N, 1, H, W), dtype=torch.float32, device=maps.device)
  620. scores = torch.zeros((N, 1), dtype=torch.float32, device=maps.device)
  621. point_maps = maps[:, 0] # È¡µÚÒ»¸öͨµÀ [N, H, W]
  622. print(f"==> heatmaps_to_arc: maps.shape = {maps.shape}, rois.shape = {rois.shape}")
  623. for i in range(N):
  624. x1, y1, x2, y2 = rois[i].long()
  625. x1 = x1.clamp(0, W - 1)
  626. x2 = x2.clamp(0, W - 1)
  627. y1 = y1.clamp(0, H - 1)
  628. y2 = y2.clamp(0, H - 1)
  629. print(f"[{i}] roi: ({x1.item()}, {y1.item()}, {x2.item()}, {y2.item()})")
  630. if x2 <= x1 or y2 <= y1:
  631. print(f" Skipped invalid ROI at index {i}")
  632. continue
  633. roi_map = point_maps[i, y1:y2, x1:x2] # [h, w]
  634. print(f" roi_map.shape: {roi_map.shape}")
  635. if roi_map.numel() == 0:
  636. print(f" Skipped empty ROI at index {i}")
  637. continue
  638. # resize to uniform size
  639. roi_map_resized = F.interpolate(
  640. roi_map.unsqueeze(0).unsqueeze(0),
  641. size=output_size,
  642. mode='bilinear',
  643. align_corners=False
  644. ) # [1, 1, H, W]
  645. print(f" roi_map_resized.shape: {roi_map_resized.shape}")
  646. # NMS + threshold
  647. nms_roi = non_maximum_suppression(roi_map_resized) # shape: [1, H, W]
  648. bin_mask = (nms_roi > threshold).float() # shape: [1, H, W]
  649. print(f" bin_mask.sum(): {bin_mask.sum().item()}")
  650. # resize back to original roi size
  651. h = int((y2 - y1).item())
  652. w = int((x2 - x1).item())
  653. # È·±£ bin_mask ÊÇ [1, 128, 128]
  654. assert bin_mask.dim() == 4, f"Expected 3D tensor [1, H, W], got {bin_mask.shape}"
  655. # ÉϲÉÑù»Ø ROI ԭʼ´óС
  656. bin_mask_original_size = F.interpolate(
  657. # bin_mask.unsqueeze(0), # ? [1, 1, 128, 128]
  658. bin_mask, # ? [1, 1, 128, 128]
  659. size=(h, w),
  660. mode='bilinear',
  661. align_corners=False
  662. )[0] # ? [1, h, w]
  663. masks[i, 0, y1:y2, x1:x2] = bin_mask_original_size.squeeze()
  664. scores[i] = bin_mask_original_size.sum()
  665. print(f" bin_mask_original_size.shape: {bin_mask_original_size.shape}, sum: {scores[i].item()}")
  666. print(f"==> Done. Total valid masks: {(scores > 0).sum().item()} / {N}")
  667. return masks, scores