line_vectorizer.py 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. import random
  2. import itertools
  3. from collections import defaultdict
  4. import numpy as np
  5. import torch
  6. import torch.nn as nn
  7. import torch.nn.parallel
  8. import torch.nn.functional as F
  9. from lcnn.config import M
  10. FEATURE_DIM = 8
  11. class LineVectorizer(nn.Module):
  12. def __init__(self, backbone):
  13. super().__init__()
  14. self.backbone = backbone
  15. lambda_ = torch.linspace(0, 1, M.n_pts0)[:, None]
  16. self.register_buffer("lambda_", lambda_)
  17. self.do_static_sampling = M.n_stc_posl + M.n_stc_negl > 0
  18. self.fc1 = nn.Conv2d(256, M.dim_loi, 1)
  19. scale_factor = M.n_pts0 // M.n_pts1
  20. if M.use_conv:
  21. self.pooling = nn.Sequential(
  22. nn.MaxPool1d(scale_factor, scale_factor),
  23. Bottleneck1D(M.dim_loi, M.dim_loi),
  24. )
  25. self.fc2 = nn.Sequential(
  26. nn.ReLU(inplace=True), nn.Linear(M.dim_loi * M.n_pts1 + FEATURE_DIM, 1)
  27. )
  28. else:
  29. self.pooling = nn.MaxPool1d(scale_factor, scale_factor)
  30. self.fc2 = nn.Sequential(
  31. nn.Linear(M.dim_loi * M.n_pts1 + FEATURE_DIM, M.dim_fc),
  32. nn.ReLU(inplace=True),
  33. nn.Linear(M.dim_fc, M.dim_fc),
  34. nn.ReLU(inplace=True),
  35. nn.Linear(M.dim_fc, 1),
  36. )
  37. self.loss = nn.BCEWithLogitsLoss(reduction="none")
  38. def forward(self, input_dict):
  39. result = self.backbone(input_dict)
  40. h = result["heatmaps"]
  41. x = self.fc1(result["feature"])
  42. n_batch, n_channel, row, col = x.shape
  43. xs, ys, fs, ps, idx, jcs = [], [], [], [], [0], []
  44. for i, meta in enumerate(input_dict["meta"]):
  45. p, label, feat, jc = self.sample_lines(
  46. meta, h["jmap"][i], h["joff"][i], input_dict["do_evaluation"]
  47. )
  48. # print("p.shape:", p.shape)
  49. ys.append(label)
  50. if not input_dict["do_evaluation"] and self.do_static_sampling:
  51. p = torch.cat([p, meta["lpre"]])
  52. feat = torch.cat([feat, meta["lpre_feat"]])
  53. ys.append(meta["lpre_label"])
  54. del jc
  55. else:
  56. jcs.append(jc)
  57. ps.append(p)
  58. fs.append(feat)
  59. p = p[:, 0:1, :] * self.lambda_ + p[:, 1:2, :] * (1 - self.lambda_) - 0.5
  60. p = p.reshape(-1, 2) # [N_LINE x N_POINT, 2_XY]
  61. px, py = p[:, 0].contiguous(), p[:, 1].contiguous()
  62. px0 = px.floor().clamp(min=0, max=127)
  63. py0 = py.floor().clamp(min=0, max=127)
  64. px1 = (px0 + 1).clamp(min=0, max=127)
  65. py1 = (py0 + 1).clamp(min=0, max=127)
  66. px0l, py0l, px1l, py1l = px0.long(), py0.long(), px1.long(), py1.long()
  67. # xp: [N_LINE, N_CHANNEL, N_POINT]
  68. xp = (
  69. (
  70. x[i, :, px0l, py0l] * (px1 - px) * (py1 - py)
  71. + x[i, :, px1l, py0l] * (px - px0) * (py1 - py)
  72. + x[i, :, px0l, py1l] * (px1 - px) * (py - py0)
  73. + x[i, :, px1l, py1l] * (px - px0) * (py - py0)
  74. )
  75. .reshape(n_channel, -1, M.n_pts0)
  76. .permute(1, 0, 2)
  77. )
  78. xp = self.pooling(xp)
  79. xs.append(xp)
  80. idx.append(idx[-1] + xp.shape[0])
  81. x, y = torch.cat(xs), torch.cat(ys)
  82. f = torch.cat(fs)
  83. x = x.reshape(-1, M.n_pts1 * M.dim_loi)
  84. x = torch.cat([x, f], 1)
  85. x = self.fc2(x).flatten()
  86. def sum_batch(x):
  87. xs = [x[idx[i] : idx[i + 1]].sum()[None] for i in range(n_batch)]
  88. return torch.cat(xs)
  89. loss = self.loss(x, y)
  90. lpos_mask, lneg_mask = y, 1 - y
  91. loss_lpos, loss_lneg = loss * lpos_mask, loss * lneg_mask
  92. lpos = sum_batch(loss_lpos) / sum_batch(lpos_mask).clamp(min=1)
  93. lneg = sum_batch(loss_lneg) / sum_batch(lneg_mask).clamp(min=1)
  94. result["losses"][0]["lpos"] = lpos * M.loss_weight["lpos"]
  95. result["losses"][0]["lneg"] = lneg * M.loss_weight["lneg"]
  96. if input_dict["do_evaluation"]:
  97. p = torch.cat(ps)
  98. s = torch.sigmoid(x)
  99. b = s > 0.5
  100. lines = []
  101. score = []
  102. for i in range(n_batch):
  103. p0 = p[idx[i] : idx[i + 1]]
  104. s0 = s[idx[i] : idx[i + 1]]
  105. mask = b[idx[i] : idx[i + 1]]
  106. p0 = p0[mask]
  107. s0 = s0[mask]
  108. if len(p0) == 0:
  109. lines.append(torch.zeros([1, M.n_out_line, 2, 2], device=p.device))
  110. score.append(torch.zeros([1, M.n_out_line], device=p.device))
  111. else:
  112. arg = torch.argsort(s0, descending=True)
  113. p0, s0 = p0[arg], s0[arg]
  114. lines.append(p0[None, torch.arange(M.n_out_line) % len(p0)])
  115. score.append(s0[None, torch.arange(M.n_out_line) % len(s0)])
  116. for j in range(len(jcs[i])):
  117. if len(jcs[i][j]) == 0:
  118. jcs[i][j] = torch.zeros([M.n_out_junc, 2], device=p.device)
  119. jcs[i][j] = jcs[i][j][
  120. None, torch.arange(M.n_out_junc) % len(jcs[i][j])
  121. ]
  122. result["heatmaps"]["lines"] = torch.cat(lines)
  123. result["heatmaps"]["score"] = torch.cat(score)
  124. result["heatmaps"]["juncs"] = torch.cat([jcs[i][0] for i in range(n_batch)])
  125. if len(jcs[i]) > 1:
  126. result["heatmaps"]["junts"] = torch.cat(
  127. [jcs[i][1] for i in range(n_batch)]
  128. )
  129. else:
  130. if "heatmaps" in result:
  131. del result["heatmaps"]
  132. return result
  133. def sample_lines(self, meta, jmap, joff, do_evaluation):
  134. with torch.no_grad():
  135. junc = meta["junc"] # [N, 2]
  136. jtyp = meta["jtyp"] # [N]
  137. Lpos = meta["Lpos"]
  138. Lneg = meta["Lneg"]
  139. n_type = jmap.shape[0]
  140. jmap = non_maximum_suppression(jmap).reshape(n_type, -1)
  141. joff = joff.reshape(n_type, 2, -1)
  142. max_K = M.n_dyn_junc // n_type
  143. N = len(junc)
  144. if do_evaluation:
  145. K = min(int((jmap > M.eval_junc_thres).float().sum().item()), max_K)
  146. else:
  147. K = min(int(N * 2 + 2), max_K)
  148. device = jmap.device
  149. # index: [N_TYPE, K]
  150. score, index = torch.topk(jmap, k=K)
  151. y = (index / 128).float() + torch.gather(joff[:, 0], 1, index) + 0.5
  152. x = (index % 128).float() + torch.gather(joff[:, 1], 1, index) + 0.5
  153. # xy: [N_TYPE, K, 2]
  154. xy = torch.cat([y[..., None], x[..., None]], dim=-1)
  155. xy_ = xy[..., None, :]
  156. del x, y, index
  157. # dist: [N_TYPE, K, N]
  158. dist = torch.sum((xy_ - junc) ** 2, -1)
  159. cost, match = torch.min(dist, -1)
  160. # xy: [N_TYPE * K, 2]
  161. # match: [N_TYPE, K]
  162. for t in range(n_type):
  163. match[t, jtyp[match[t]] != t] = N
  164. match[cost > 1.5 * 1.5] = N
  165. match = match.flatten()
  166. _ = torch.arange(n_type * K, device=device)
  167. u, v = torch.meshgrid(_, _)
  168. u, v = u.flatten(), v.flatten()
  169. up, vp = match[u], match[v]
  170. label = Lpos[up, vp]
  171. if do_evaluation:
  172. c = (u < v).flatten()
  173. else:
  174. c = torch.zeros_like(label)
  175. # sample positive lines
  176. cdx = label.nonzero().flatten()
  177. if len(cdx) > M.n_dyn_posl:
  178. # print("too many positive lines")
  179. perm = torch.randperm(len(cdx), device=device)[: M.n_dyn_posl]
  180. cdx = cdx[perm]
  181. c[cdx] = 1
  182. # sample negative lines
  183. cdx = Lneg[up, vp].nonzero().flatten()
  184. if len(cdx) > M.n_dyn_negl:
  185. # print("too many negative lines")
  186. perm = torch.randperm(len(cdx), device=device)[: M.n_dyn_negl]
  187. cdx = cdx[perm]
  188. c[cdx] = 1
  189. # sample other (unmatched) lines
  190. cdx = torch.randint(len(c), (M.n_dyn_othr,), device=device)
  191. c[cdx] = 1
  192. # sample lines
  193. u, v, label = u[c], v[c], label[c]
  194. xy = xy.reshape(n_type * K, 2)
  195. xyu, xyv = xy[u], xy[v]
  196. u2v = xyu - xyv
  197. u2v /= torch.sqrt((u2v ** 2).sum(-1, keepdim=True)).clamp(min=1e-6)
  198. feat = torch.cat(
  199. [
  200. xyu / 128 * M.use_cood,
  201. xyv / 128 * M.use_cood,
  202. u2v * M.use_slop,
  203. (u[:, None] > K).float(),
  204. (v[:, None] > K).float(),
  205. ],
  206. 1,
  207. )
  208. line = torch.cat([xyu[:, None], xyv[:, None]], 1)
  209. xy = xy.reshape(n_type, K, 2)
  210. jcs = [xy[i, score[i] > 0.03] for i in range(n_type)]
  211. return line, label.float(), feat, jcs
  212. def non_maximum_suppression(a):
  213. ap = F.max_pool2d(a, 3, stride=1, padding=1)
  214. mask = (a == ap).float().clamp(min=0.0)
  215. return a * mask
  216. class Bottleneck1D(nn.Module):
  217. def __init__(self, inplanes, outplanes):
  218. super(Bottleneck1D, self).__init__()
  219. planes = outplanes // 2
  220. self.op = nn.Sequential(
  221. nn.BatchNorm1d(inplanes),
  222. nn.ReLU(inplace=True),
  223. nn.Conv1d(inplanes, planes, kernel_size=1),
  224. nn.BatchNorm1d(planes),
  225. nn.ReLU(inplace=True),
  226. nn.Conv1d(planes, planes, kernel_size=3, padding=1),
  227. nn.BatchNorm1d(planes),
  228. nn.ReLU(inplace=True),
  229. nn.Conv1d(planes, outplanes, kernel_size=1),
  230. )
  231. def forward(self, x):
  232. return x + self.op(x)