wirepoint_rcnn.py 31 KB

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