wirepoint_rcnn.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738
  1. import os
  2. from typing import Optional, Any
  3. import cv2
  4. import numpy as np
  5. import torch
  6. from tensorboardX import SummaryWriter
  7. from torch import nn
  8. import torch.nn.functional as F
  9. # from torchinfo import summary
  10. from torchvision.io import read_image
  11. from torchvision.models import resnet50, ResNet50_Weights
  12. from torchvision.models.detection import FasterRCNN, MaskRCNN_ResNet50_FPN_V2_Weights
  13. from torchvision.models.detection._utils import overwrite_eps
  14. from torchvision.models.detection.backbone_utils import _resnet_fpn_extractor, _validate_trainable_layers
  15. from torchvision.models.detection.faster_rcnn import TwoMLPHead, FastRCNNPredictor
  16. from torchvision.models.detection.keypoint_rcnn import KeypointRCNNHeads, KeypointRCNNPredictor, \
  17. KeypointRCNN_ResNet50_FPN_Weights
  18. from torchvision.ops import MultiScaleRoIAlign
  19. from torchvision.ops import misc as misc_nn_ops
  20. # from visdom import Visdom
  21. from models.config import config_tool
  22. from models.config.config_tool import read_yaml
  23. from models.ins.trainer import get_transform
  24. from models.wirenet.head import RoIHeads
  25. from models.wirenet.wirepoint_dataset import WirePointDataset
  26. from tools import utils
  27. from torch.utils.tensorboard import SummaryWriter
  28. import matplotlib.pyplot as plt
  29. import matplotlib as mpl
  30. from skimage import io
  31. import os.path as osp
  32. FEATURE_DIM = 8
  33. device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
  34. print(f"Using device: {device}")
  35. def non_maximum_suppression(a):
  36. ap = F.max_pool2d(a, 3, stride=1, padding=1)
  37. mask = (a == ap).float().clamp(min=0.0)
  38. return a * mask
  39. class Bottleneck1D(nn.Module):
  40. def __init__(self, inplanes, outplanes):
  41. super(Bottleneck1D, self).__init__()
  42. planes = outplanes // 2
  43. self.op = nn.Sequential(
  44. nn.BatchNorm1d(inplanes),
  45. nn.ReLU(inplace=True),
  46. nn.Conv1d(inplanes, planes, kernel_size=1),
  47. nn.BatchNorm1d(planes),
  48. nn.ReLU(inplace=True),
  49. nn.Conv1d(planes, planes, kernel_size=3, padding=1),
  50. nn.BatchNorm1d(planes),
  51. nn.ReLU(inplace=True),
  52. nn.Conv1d(planes, outplanes, kernel_size=1),
  53. )
  54. def forward(self, x):
  55. return x + self.op(x)
  56. class WirepointRCNN(FasterRCNN):
  57. def __init__(
  58. self,
  59. backbone,
  60. num_classes=None,
  61. # transform parameters
  62. min_size=None,
  63. max_size=1333,
  64. image_mean=None,
  65. image_std=None,
  66. # RPN parameters
  67. rpn_anchor_generator=None,
  68. rpn_head=None,
  69. rpn_pre_nms_top_n_train=2000,
  70. rpn_pre_nms_top_n_test=1000,
  71. rpn_post_nms_top_n_train=2000,
  72. rpn_post_nms_top_n_test=1000,
  73. rpn_nms_thresh=0.7,
  74. rpn_fg_iou_thresh=0.7,
  75. rpn_bg_iou_thresh=0.3,
  76. rpn_batch_size_per_image=256,
  77. rpn_positive_fraction=0.5,
  78. rpn_score_thresh=0.0,
  79. # Box parameters
  80. box_roi_pool=None,
  81. box_head=None,
  82. box_predictor=None,
  83. box_score_thresh=0.05,
  84. box_nms_thresh=0.5,
  85. box_detections_per_img=100,
  86. box_fg_iou_thresh=0.5,
  87. box_bg_iou_thresh=0.5,
  88. box_batch_size_per_image=512,
  89. box_positive_fraction=0.25,
  90. bbox_reg_weights=None,
  91. # keypoint parameters
  92. keypoint_roi_pool=None,
  93. keypoint_head=None,
  94. keypoint_predictor=None,
  95. num_keypoints=None,
  96. wirepoint_roi_pool=None,
  97. wirepoint_head=None,
  98. wirepoint_predictor=None,
  99. **kwargs,
  100. ):
  101. if not isinstance(keypoint_roi_pool, (MultiScaleRoIAlign, type(None))):
  102. raise TypeError(
  103. "keypoint_roi_pool should be of type MultiScaleRoIAlign or None instead of {type(keypoint_roi_pool)}"
  104. )
  105. if min_size is None:
  106. min_size = (640, 672, 704, 736, 768, 800)
  107. if num_keypoints is not None:
  108. if keypoint_predictor is not None:
  109. raise ValueError("num_keypoints should be None when keypoint_predictor is specified")
  110. else:
  111. num_keypoints = 17
  112. out_channels = backbone.out_channels
  113. if wirepoint_roi_pool is None:
  114. wirepoint_roi_pool = MultiScaleRoIAlign(featmap_names=["0", "1", "2", "3"], output_size=128,
  115. sampling_ratio=2, )
  116. if wirepoint_head is None:
  117. keypoint_layers = tuple(512 for _ in range(8))
  118. # print(f'keypoinyrcnnHeads inchannels:{out_channels},layers{keypoint_layers}')
  119. wirepoint_head = WirepointHead(out_channels, keypoint_layers)
  120. if wirepoint_predictor is None:
  121. keypoint_dim_reduced = 512 # == keypoint_layers[-1]
  122. wirepoint_predictor = WirepointPredictor()
  123. super().__init__(
  124. backbone,
  125. num_classes,
  126. # transform parameters
  127. min_size,
  128. max_size,
  129. image_mean,
  130. image_std,
  131. # RPN-specific parameters
  132. rpn_anchor_generator,
  133. rpn_head,
  134. rpn_pre_nms_top_n_train,
  135. rpn_pre_nms_top_n_test,
  136. rpn_post_nms_top_n_train,
  137. rpn_post_nms_top_n_test,
  138. rpn_nms_thresh,
  139. rpn_fg_iou_thresh,
  140. rpn_bg_iou_thresh,
  141. rpn_batch_size_per_image,
  142. rpn_positive_fraction,
  143. rpn_score_thresh,
  144. # Box parameters
  145. box_roi_pool,
  146. box_head,
  147. box_predictor,
  148. box_score_thresh,
  149. box_nms_thresh,
  150. box_detections_per_img,
  151. box_fg_iou_thresh,
  152. box_bg_iou_thresh,
  153. box_batch_size_per_image,
  154. box_positive_fraction,
  155. bbox_reg_weights,
  156. **kwargs,
  157. )
  158. if box_roi_pool is None:
  159. box_roi_pool = MultiScaleRoIAlign(featmap_names=["0", "1", "2", "3"], output_size=14, sampling_ratio=2)
  160. if box_head is None:
  161. resolution = box_roi_pool.output_size[0]
  162. representation_size = 1024
  163. box_head = TwoMLPHead(out_channels * resolution ** 2, representation_size)
  164. if box_predictor is None:
  165. representation_size = 1024
  166. box_predictor = FastRCNNPredictor(representation_size, num_classes)
  167. roi_heads = RoIHeads(
  168. # Box
  169. box_roi_pool,
  170. box_head,
  171. box_predictor,
  172. box_fg_iou_thresh,
  173. box_bg_iou_thresh,
  174. box_batch_size_per_image,
  175. box_positive_fraction,
  176. bbox_reg_weights,
  177. box_score_thresh,
  178. box_nms_thresh,
  179. box_detections_per_img,
  180. # wirepoint_roi_pool=wirepoint_roi_pool,
  181. # wirepoint_head=wirepoint_head,
  182. # wirepoint_predictor=wirepoint_predictor,
  183. )
  184. self.roi_heads = roi_heads
  185. self.roi_heads.wirepoint_roi_pool = wirepoint_roi_pool
  186. self.roi_heads.wirepoint_head = wirepoint_head
  187. self.roi_heads.wirepoint_predictor = wirepoint_predictor
  188. class WirepointHead(nn.Module):
  189. def __init__(self, input_channels, num_class):
  190. super(WirepointHead, self).__init__()
  191. self.head_size = [[2], [1], [2]]
  192. m = int(input_channels / 4)
  193. heads = []
  194. # print(f'M.head_size:{M.head_size}')
  195. # for output_channels in sum(M.head_size, []):
  196. for output_channels in sum(self.head_size, []):
  197. heads.append(
  198. nn.Sequential(
  199. nn.Conv2d(input_channels, m, kernel_size=3, padding=1),
  200. nn.ReLU(inplace=True),
  201. nn.Conv2d(m, output_channels, kernel_size=1),
  202. )
  203. )
  204. self.heads = nn.ModuleList(heads)
  205. def forward(self, x):
  206. # for idx, head in enumerate(self.heads):
  207. # print(f'{idx},multitask head:{head(x).shape},input x:{x.shape}')
  208. outputs = torch.cat([head(x) for head in self.heads], dim=1)
  209. features = x
  210. return outputs, features
  211. class WirepointPredictor(nn.Module):
  212. def __init__(self):
  213. super().__init__()
  214. # self.backbone = backbone
  215. # self.cfg = read_yaml(cfg)
  216. self.cfg = read_yaml('wirenet.yaml')
  217. self.n_pts0 = self.cfg['model']['n_pts0']
  218. self.n_pts1 = self.cfg['model']['n_pts1']
  219. self.n_stc_posl = self.cfg['model']['n_stc_posl']
  220. self.dim_loi = self.cfg['model']['dim_loi']
  221. self.use_conv = self.cfg['model']['use_conv']
  222. self.dim_fc = self.cfg['model']['dim_fc']
  223. self.n_out_line = self.cfg['model']['n_out_line']
  224. self.n_out_junc = self.cfg['model']['n_out_junc']
  225. self.loss_weight = self.cfg['model']['loss_weight']
  226. self.n_dyn_junc = self.cfg['model']['n_dyn_junc']
  227. self.eval_junc_thres = self.cfg['model']['eval_junc_thres']
  228. self.n_dyn_posl = self.cfg['model']['n_dyn_posl']
  229. self.n_dyn_negl = self.cfg['model']['n_dyn_negl']
  230. self.n_dyn_othr = self.cfg['model']['n_dyn_othr']
  231. self.use_cood = self.cfg['model']['use_cood']
  232. self.use_slop = self.cfg['model']['use_slop']
  233. self.n_stc_negl = self.cfg['model']['n_stc_negl']
  234. self.head_size = self.cfg['model']['head_size']
  235. self.num_class = sum(sum(self.head_size, []))
  236. self.head_off = np.cumsum([sum(h) for h in self.head_size])
  237. lambda_ = torch.linspace(0, 1, self.n_pts0)[:, None]
  238. self.register_buffer("lambda_", lambda_)
  239. self.do_static_sampling = self.n_stc_posl + self.n_stc_negl > 0
  240. self.fc1 = nn.Conv2d(256, self.dim_loi, 1)
  241. scale_factor = self.n_pts0 // self.n_pts1
  242. if self.use_conv:
  243. self.pooling = nn.Sequential(
  244. nn.MaxPool1d(scale_factor, scale_factor),
  245. Bottleneck1D(self.dim_loi, self.dim_loi),
  246. )
  247. self.fc2 = nn.Sequential(
  248. nn.ReLU(inplace=True), nn.Linear(self.dim_loi * self.n_pts1 + FEATURE_DIM, 1)
  249. )
  250. else:
  251. self.pooling = nn.MaxPool1d(scale_factor, scale_factor)
  252. self.fc2 = nn.Sequential(
  253. nn.Linear(self.dim_loi * self.n_pts1 + FEATURE_DIM, self.dim_fc),
  254. nn.ReLU(inplace=True),
  255. nn.Linear(self.dim_fc, self.dim_fc),
  256. nn.ReLU(inplace=True),
  257. nn.Linear(self.dim_fc, 1),
  258. )
  259. self.loss = nn.BCEWithLogitsLoss(reduction="none")
  260. def forward(self, inputs, features, targets=None):
  261. # outputs, features = input
  262. # for out in outputs:
  263. # print(f'out:{out.shape}')
  264. # outputs=merge_features(outputs,100)
  265. batch, channel, row, col = inputs.shape
  266. # print(f'outputs:{inputs.shape}')
  267. # print(f'batch:{batch}, channel:{channel}, row:{row}, col:{col}')
  268. if targets is not None:
  269. self.training = True
  270. # print(f'target:{targets}')
  271. wires_targets = [t["wires"] for t in targets]
  272. # print(f'wires_target:{wires_targets}')
  273. # 提取所有 'junc_map', 'junc_offset', 'line_map' 的张量
  274. junc_maps = [d["junc_map"] for d in wires_targets]
  275. junc_offsets = [d["junc_offset"] for d in wires_targets]
  276. line_maps = [d["line_map"] for d in wires_targets]
  277. junc_map_tensor = torch.stack(junc_maps, dim=0)
  278. junc_offset_tensor = torch.stack(junc_offsets, dim=0)
  279. line_map_tensor = torch.stack(line_maps, dim=0)
  280. wires_meta = {
  281. "junc_map": junc_map_tensor,
  282. "junc_offset": junc_offset_tensor,
  283. # "line_map": line_map_tensor,
  284. }
  285. else:
  286. self.training = False
  287. t = {
  288. "junc_coords": torch.zeros(1, 2).to(device),
  289. "jtyp": torch.zeros(1, dtype=torch.uint8).to(device),
  290. "line_pos_idx": torch.zeros(2, 2, dtype=torch.uint8).to(device),
  291. "line_neg_idx": torch.zeros(2, 2, dtype=torch.uint8).to(device),
  292. "junc_map": torch.zeros([1, 1, 128, 128]).to(device),
  293. "junc_offset": torch.zeros([1, 1, 2, 128, 128]).to(device),
  294. }
  295. wires_targets = [t for b in range(inputs.size(0))]
  296. wires_meta = {
  297. "junc_map": torch.zeros([1, 1, 128, 128]).to(device),
  298. "junc_offset": torch.zeros([1, 1, 2, 128, 128]).to(device),
  299. }
  300. T = wires_meta.copy()
  301. n_jtyp = T["junc_map"].shape[1]
  302. offset = self.head_off
  303. result = {}
  304. for stack, output in enumerate([inputs]):
  305. output = output.transpose(0, 1).reshape([-1, batch, row, col]).contiguous()
  306. # print(f"Stack {stack} output shape: {output.shape}") # 打印每层的输出形状
  307. jmap = output[0: offset[0]].reshape(n_jtyp, 2, batch, row, col)
  308. lmap = output[offset[0]: offset[1]].squeeze(0)
  309. joff = output[offset[1]: offset[2]].reshape(n_jtyp, 2, batch, row, col)
  310. if stack == 0:
  311. result["preds"] = {
  312. "jmap": jmap.permute(2, 0, 1, 3, 4).softmax(2)[:, :, 1],
  313. "lmap": lmap.sigmoid(),
  314. "joff": joff.permute(2, 0, 1, 3, 4).sigmoid() - 0.5,
  315. }
  316. h = result["preds"]
  317. # print(f'features shape:{features.shape}')
  318. x = self.fc1(features)
  319. n_batch, n_channel, row, col = x.shape
  320. xs, ys, fs, ps, idx, jcs = [], [], [], [], [0], []
  321. for i, meta in enumerate(wires_targets):
  322. p, label, feat, jc = self.sample_lines(
  323. meta, h["jmap"][i], h["joff"][i],
  324. )
  325. # print(f"p.shape:{p.shape},label:{label.shape},feat:{feat.shape},jc:{len(jc)}")
  326. ys.append(label)
  327. if self.training and self.do_static_sampling:
  328. p = torch.cat([p, meta["lpre"]])
  329. feat = torch.cat([feat, meta["lpre_feat"]])
  330. ys.append(meta["lpre_label"])
  331. del jc
  332. else:
  333. jcs.append(jc)
  334. ps.append(p)
  335. fs.append(feat)
  336. p = p[:, 0:1, :] * self.lambda_ + p[:, 1:2, :] * (1 - self.lambda_) - 0.5
  337. p = p.reshape(-1, 2) # [N_LINE x N_POINT, 2_XY]
  338. px, py = p[:, 0].contiguous(), p[:, 1].contiguous()
  339. px0 = px.floor().clamp(min=0, max=127)
  340. py0 = py.floor().clamp(min=0, max=127)
  341. px1 = (px0 + 1).clamp(min=0, max=127)
  342. py1 = (py0 + 1).clamp(min=0, max=127)
  343. px0l, py0l, px1l, py1l = px0.long(), py0.long(), px1.long(), py1.long()
  344. # xp: [N_LINE, N_CHANNEL, N_POINT]
  345. xp = (
  346. (
  347. x[i, :, px0l, py0l] * (px1 - px) * (py1 - py)
  348. + x[i, :, px1l, py0l] * (px - px0) * (py1 - py)
  349. + x[i, :, px0l, py1l] * (px1 - px) * (py - py0)
  350. + x[i, :, px1l, py1l] * (px - px0) * (py - py0)
  351. )
  352. .reshape(n_channel, -1, self.n_pts0)
  353. .permute(1, 0, 2)
  354. )
  355. xp = self.pooling(xp)
  356. # print(f'xp.shape:{xp.shape}')
  357. xs.append(xp)
  358. idx.append(idx[-1] + xp.shape[0])
  359. # print(f'idx__:{idx}')
  360. x, y = torch.cat(xs), torch.cat(ys)
  361. f = torch.cat(fs)
  362. x = x.reshape(-1, self.n_pts1 * self.dim_loi)
  363. x = torch.cat([x, f], 1)
  364. x = x.to(dtype=torch.float32)
  365. x = self.fc2(x).flatten()
  366. # return x,idx,jcs,n_batch,ps,self.n_out_line,self.n_out_junc
  367. return x, y, idx, jcs, n_batch, ps, self.n_out_line, self.n_out_junc
  368. # if mode != "training":
  369. # self.inference(x, idx, jcs, n_batch, ps)
  370. # return result
  371. def sample_lines(self, meta, jmap, joff):
  372. with torch.no_grad():
  373. junc = meta["junc_coords"] # [N, 2]
  374. jtyp = meta["jtyp"] # [N]
  375. Lpos = meta["line_pos_idx"]
  376. Lneg = meta["line_neg_idx"]
  377. n_type = jmap.shape[0]
  378. jmap = non_maximum_suppression(jmap).reshape(n_type, -1)
  379. joff = joff.reshape(n_type, 2, -1)
  380. max_K = self.n_dyn_junc // n_type
  381. N = len(junc)
  382. # if mode != "training":
  383. if not self.training:
  384. K = min(int((jmap > self.eval_junc_thres).float().sum().item()), max_K)
  385. else:
  386. K = min(int(N * 2 + 2), max_K)
  387. if K < 2:
  388. K = 2
  389. device = jmap.device
  390. # index: [N_TYPE, K]
  391. score, index = torch.topk(jmap, k=K)
  392. y = (index // 128).float() + torch.gather(joff[:, 0], 1, index) + 0.5
  393. x = (index % 128).float() + torch.gather(joff[:, 1], 1, index) + 0.5
  394. # xy: [N_TYPE, K, 2]
  395. xy = torch.cat([y[..., None], x[..., None]], dim=-1)
  396. xy_ = xy[..., None, :]
  397. del x, y, index
  398. # print(f"xy_.is_cuda: {xy_.is_cuda}")
  399. # print(f"junc.is_cuda: {junc.is_cuda}")
  400. # dist: [N_TYPE, K, N]
  401. dist = torch.sum((xy_ - junc) ** 2, -1)
  402. cost, match = torch.min(dist, -1)
  403. # xy: [N_TYPE * K, 2]
  404. # match: [N_TYPE, K]
  405. for t in range(n_type):
  406. match[t, jtyp[match[t]] != t] = N
  407. match[cost > 1.5 * 1.5] = N
  408. match = match.flatten()
  409. _ = torch.arange(n_type * K, device=device)
  410. u, v = torch.meshgrid(_, _)
  411. u, v = u.flatten(), v.flatten()
  412. up, vp = match[u], match[v]
  413. label = Lpos[up, vp]
  414. # if mode == "training":
  415. if self.training:
  416. c = torch.zeros_like(label, dtype=torch.bool)
  417. # sample positive lines
  418. cdx = label.nonzero().flatten()
  419. if len(cdx) > self.n_dyn_posl:
  420. # print("too many positive lines")
  421. perm = torch.randperm(len(cdx), device=device)[: self.n_dyn_posl]
  422. cdx = cdx[perm]
  423. c[cdx] = 1
  424. # sample negative lines
  425. cdx = Lneg[up, vp].nonzero().flatten()
  426. if len(cdx) > self.n_dyn_negl:
  427. # print("too many negative lines")
  428. perm = torch.randperm(len(cdx), device=device)[: self.n_dyn_negl]
  429. cdx = cdx[perm]
  430. c[cdx] = 1
  431. # sample other (unmatched) lines
  432. cdx = torch.randint(len(c), (self.n_dyn_othr,), device=device)
  433. c[cdx] = 1
  434. else:
  435. c = (u < v).flatten()
  436. # sample lines
  437. u, v, label = u[c], v[c], label[c]
  438. xy = xy.reshape(n_type * K, 2)
  439. xyu, xyv = xy[u], xy[v]
  440. u2v = xyu - xyv
  441. u2v /= torch.sqrt((u2v ** 2).sum(-1, keepdim=True)).clamp(min=1e-6)
  442. feat = torch.cat(
  443. [
  444. xyu / 128 * self.use_cood,
  445. xyv / 128 * self.use_cood,
  446. u2v * self.use_slop,
  447. (u[:, None] > K).float(),
  448. (v[:, None] > K).float(),
  449. ],
  450. 1,
  451. )
  452. line = torch.cat([xyu[:, None], xyv[:, None]], 1)
  453. xy = xy.reshape(n_type, K, 2)
  454. jcs = [xy[i, score[i] > 0.03] for i in range(n_type)]
  455. return line, label.float(), feat, jcs
  456. def wirepointrcnn_resnet50_fpn(
  457. *,
  458. weights: Optional[KeypointRCNN_ResNet50_FPN_Weights] = None,
  459. progress: bool = True,
  460. num_classes: Optional[int] = None,
  461. num_keypoints: Optional[int] = None,
  462. weights_backbone: Optional[ResNet50_Weights] = ResNet50_Weights.IMAGENET1K_V1,
  463. trainable_backbone_layers: Optional[int] = None,
  464. **kwargs: Any,
  465. ) -> WirepointRCNN:
  466. weights = KeypointRCNN_ResNet50_FPN_Weights.verify(weights)
  467. weights_backbone = ResNet50_Weights.verify(weights_backbone)
  468. is_trained = weights is not None or weights_backbone is not None
  469. trainable_backbone_layers = _validate_trainable_layers(is_trained, trainable_backbone_layers, 5, 3)
  470. norm_layer = misc_nn_ops.FrozenBatchNorm2d if is_trained else nn.BatchNorm2d
  471. backbone = resnet50(weights=weights_backbone, progress=progress, norm_layer=norm_layer)
  472. backbone = _resnet_fpn_extractor(backbone, trainable_backbone_layers)
  473. model = WirepointRCNN(backbone, num_classes=5, **kwargs)
  474. if weights is not None:
  475. model.load_state_dict(weights.get_state_dict(progress=progress))
  476. if weights == KeypointRCNN_ResNet50_FPN_Weights.COCO_V1:
  477. overwrite_eps(model, 0.0)
  478. return model
  479. def _loss(losses):
  480. total_loss = 0
  481. for i in losses.keys():
  482. if i != "loss_wirepoint":
  483. total_loss += losses[i]
  484. else:
  485. loss_labels = losses[i]["losses"]
  486. loss_labels_k = list(loss_labels[0].keys())
  487. for j, name in enumerate(loss_labels_k):
  488. loss = loss_labels[0][name].mean()
  489. total_loss += loss
  490. return total_loss
  491. cmap = plt.get_cmap("jet")
  492. norm = mpl.colors.Normalize(vmin=0.4, vmax=1.0)
  493. sm = plt.cm.ScalarMappable(cmap=cmap, norm=norm)
  494. sm.set_array([])
  495. def c(x):
  496. return sm.to_rgba(x)
  497. def imshow(im):
  498. plt.close()
  499. plt.tight_layout()
  500. plt.imshow(im)
  501. plt.colorbar(sm, fraction=0.046)
  502. plt.xlim([0, im.shape[0]])
  503. plt.ylim([im.shape[0], 0])
  504. def _plot_samples(self, i, index, result, targets, prefix):
  505. fn = self.val_loader.dataset.filelist[index][:-10].replace("_a0", "") + ".png"
  506. img = io.imread(fn)
  507. imshow(img), plt.savefig(f"{prefix}_img.jpg"), plt.close()
  508. def draw_vecl(lines, sline, juncs, junts, fn):
  509. imshow(img)
  510. if len(lines) > 0 and not (lines[0] == 0).all():
  511. for i, ((a, b), s) in enumerate(zip(lines, sline)):
  512. if i > 0 and (lines[i] == lines[0]).all():
  513. break
  514. plt.plot([a[1], b[1]], [a[0], b[0]], c=c(s), linewidth=4)
  515. if not (juncs[0] == 0).all():
  516. for i, j in enumerate(juncs):
  517. if i > 0 and (i == juncs[0]).all():
  518. break
  519. plt.scatter(j[1], j[0], c="red", s=64, zorder=100)
  520. if junts is not None and len(junts) > 0 and not (junts[0] == 0).all():
  521. for i, j in enumerate(junts):
  522. if i > 0 and (i == junts[0]).all():
  523. break
  524. plt.scatter(j[1], j[0], c="blue", s=64, zorder=100)
  525. plt.savefig(fn), plt.close()
  526. junc = targets[i]["junc"].cpu().numpy() * 4
  527. jtyp = targets[i]["jtyp"].cpu().numpy()
  528. juncs = junc[jtyp == 0]
  529. junts = junc[jtyp == 1]
  530. rjuncs = result["juncs"][i].cpu().numpy() * 4
  531. rjunts = None
  532. if "junts" in result:
  533. rjunts = result["junts"][i].cpu().numpy() * 4
  534. lpre = targets[i]["lpre"].cpu().numpy() * 4
  535. vecl_target = targets[i]["lpre_label"].cpu().numpy()
  536. vecl_result = result["lines"][i].cpu().numpy() * 4
  537. score = result["score"][i].cpu().numpy()
  538. lpre = lpre[vecl_target == 1]
  539. draw_vecl(lpre, np.ones(lpre.shape[0]), juncs, junts, f"{prefix}_vecl_a.jpg")
  540. draw_vecl(vecl_result, score, rjuncs, rjunts, f"{prefix}_vecl_b.jpg")
  541. img = cv2.imread(f"{prefix}_vecl_a.jpg")
  542. img1 = cv2.imread(f"{prefix}_vecl_b.jpg")
  543. self.writer.add_images(f"{self.epoch}", torch.tensor([img, img1]), dataformats='NHWC')
  544. if __name__ == '__main__':
  545. cfg = 'wirenet.yaml'
  546. cfg = read_yaml(cfg)
  547. print(f'cfg:{cfg}')
  548. print(cfg['model']['n_dyn_negl'])
  549. # net = WirepointPredictor()
  550. # if torch.cuda.is_available():
  551. # device_name = "cuda"
  552. # torch.backends.cudnn.deterministic = True
  553. # torch.cuda.manual_seed(0)
  554. # print("Let's use", torch.cuda.device_count(), "GPU(s)!")
  555. # else:
  556. # print("CUDA is not available")
  557. #
  558. # device = torch.device(device_name)
  559. dataset_train = WirePointDataset(dataset_path=cfg['io']['datadir'], dataset_type='train')
  560. train_sampler = torch.utils.data.RandomSampler(dataset_train)
  561. # test_sampler = torch.utils.data.SequentialSampler(dataset_test)
  562. train_batch_sampler = torch.utils.data.BatchSampler(train_sampler, batch_size=1, drop_last=True)
  563. train_collate_fn = utils.collate_fn_wirepoint
  564. data_loader_train = torch.utils.data.DataLoader(
  565. dataset_train, batch_sampler=train_batch_sampler, num_workers=0, collate_fn=train_collate_fn
  566. )
  567. dataset_val = WirePointDataset(dataset_path=cfg['io']['datadir'], dataset_type='val')
  568. val_sampler = torch.utils.data.RandomSampler(dataset_val)
  569. # test_sampler = torch.utils.data.SequentialSampler(dataset_test)
  570. val_batch_sampler = torch.utils.data.BatchSampler(val_sampler, batch_size=1, drop_last=True)
  571. val_collate_fn = utils.collate_fn_wirepoint
  572. data_loader_val = torch.utils.data.DataLoader(
  573. dataset_val, batch_sampler=val_batch_sampler, num_workers=0, collate_fn=val_collate_fn
  574. )
  575. model = wirepointrcnn_resnet50_fpn().to(device)
  576. optimizer = torch.optim.Adam(model.parameters(), lr=cfg['optim']['lr'])
  577. writer = SummaryWriter(cfg['io']['logdir'])
  578. def move_to_device(data, device):
  579. if isinstance(data, (list, tuple)):
  580. return type(data)(move_to_device(item, device) for item in data)
  581. elif isinstance(data, dict):
  582. return {key: move_to_device(value, device) for key, value in data.items()}
  583. elif isinstance(data, torch.Tensor):
  584. return data.to(device)
  585. else:
  586. return data # 对于非张量类型的数据不做任何改变
  587. def writer_loss(writer, losses, epoch):
  588. # ??????
  589. try:
  590. for key, value in losses.items():
  591. if key == 'loss_wirepoint':
  592. # ?? wirepoint ??????
  593. for subdict in losses['loss_wirepoint']['losses']:
  594. for subkey, subvalue in subdict.items():
  595. # ?? .item() ?????
  596. writer.add_scalar(f'loss_wirepoint/{subkey}',
  597. subvalue.item() if hasattr(subvalue, 'item') else subvalue,
  598. epoch)
  599. elif isinstance(value, torch.Tensor):
  600. # ????????
  601. writer.add_scalar(key, value.item(), epoch)
  602. except Exception as e:
  603. print(f"TensorBoard logging error: {e}")
  604. for epoch in range(cfg['optim']['max_epoch']):
  605. print(f"epoch:{epoch}")
  606. model.train()
  607. for imgs, targets in data_loader_train:
  608. losses = model(move_to_device(imgs, device), move_to_device(targets, device))
  609. loss = _loss(losses)
  610. print(loss)
  611. optimizer.zero_grad()
  612. loss.backward()
  613. optimizer.step()
  614. writer_loss(writer, losses, epoch)
  615. model.eval()
  616. with torch.no_grad():
  617. for batch_idx, (imgs, targets) in enumerate(data_loader_val):
  618. pred = model(move_to_device(imgs, device))
  619. print(f"perd:{pred}")
  620. # if batch_idx == 0:
  621. # viz = osp.join(cfg['io']['logdir'], "viz", f"{epoch}")
  622. # H = pred["wires"]
  623. # _plot_samples(0, 0, H, targets["wires"], f"{viz}/{epoch}")
  624. # imgs, targets = next(iter(data_loader))
  625. #
  626. # model.train()
  627. # pred = model(imgs, targets)
  628. # print(f'pred:{pred}')
  629. # result, losses = model(imgs, targets)
  630. # print(f'result:{result}')
  631. # print(f'pred:{losses}')