wirepoint_rcnn.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703
  1. import os
  2. from typing import Optional, Any
  3. import numpy as np
  4. import torch
  5. from tensorboardX import SummaryWriter
  6. from torch import nn
  7. import torch.nn.functional as F
  8. # from torchinfo import summary
  9. from torchvision.io import read_image
  10. from torchvision.models import resnet50, ResNet50_Weights
  11. from torchvision.models.detection import FasterRCNN, MaskRCNN_ResNet50_FPN_V2_Weights
  12. from torchvision.models.detection._utils import overwrite_eps
  13. from torchvision.models.detection.backbone_utils import _resnet_fpn_extractor, _validate_trainable_layers
  14. from torchvision.models.detection.faster_rcnn import TwoMLPHead, FastRCNNPredictor
  15. from torchvision.models.detection.keypoint_rcnn import KeypointRCNNHeads, KeypointRCNNPredictor, \
  16. KeypointRCNN_ResNet50_FPN_Weights
  17. from torchvision.ops import MultiScaleRoIAlign
  18. from torchvision.ops import misc as misc_nn_ops
  19. # from visdom import Visdom
  20. from models.config import config_tool
  21. from models.config.config_tool import read_yaml
  22. from models.ins.trainer import get_transform
  23. from models.wirenet.head import RoIHeads
  24. from models.wirenet.wirepoint_dataset import WirePointDataset
  25. from tools import utils
  26. FEATURE_DIM = 8
  27. def non_maximum_suppression(a):
  28. ap = F.max_pool2d(a, 3, stride=1, padding=1)
  29. mask = (a == ap).float().clamp(min=0.0)
  30. return a * mask
  31. class Bottleneck1D(nn.Module):
  32. def __init__(self, inplanes, outplanes):
  33. super(Bottleneck1D, self).__init__()
  34. planes = outplanes // 2
  35. self.op = nn.Sequential(
  36. nn.BatchNorm1d(inplanes),
  37. nn.ReLU(inplace=True),
  38. nn.Conv1d(inplanes, planes, kernel_size=1),
  39. nn.BatchNorm1d(planes),
  40. nn.ReLU(inplace=True),
  41. nn.Conv1d(planes, planes, kernel_size=3, padding=1),
  42. nn.BatchNorm1d(planes),
  43. nn.ReLU(inplace=True),
  44. nn.Conv1d(planes, outplanes, kernel_size=1),
  45. )
  46. def forward(self, x):
  47. return x + self.op(x)
  48. class WirepointRCNN(FasterRCNN):
  49. def __init__(
  50. self,
  51. backbone,
  52. num_classes=None,
  53. # transform parameters
  54. min_size=None,
  55. max_size=1333,
  56. image_mean=None,
  57. image_std=None,
  58. # RPN parameters
  59. rpn_anchor_generator=None,
  60. rpn_head=None,
  61. rpn_pre_nms_top_n_train=2000,
  62. rpn_pre_nms_top_n_test=1000,
  63. rpn_post_nms_top_n_train=2000,
  64. rpn_post_nms_top_n_test=1000,
  65. rpn_nms_thresh=0.7,
  66. rpn_fg_iou_thresh=0.7,
  67. rpn_bg_iou_thresh=0.3,
  68. rpn_batch_size_per_image=256,
  69. rpn_positive_fraction=0.5,
  70. rpn_score_thresh=0.0,
  71. # Box parameters
  72. box_roi_pool=None,
  73. box_head=None,
  74. box_predictor=None,
  75. box_score_thresh=0.05,
  76. box_nms_thresh=0.5,
  77. box_detections_per_img=100,
  78. box_fg_iou_thresh=0.5,
  79. box_bg_iou_thresh=0.5,
  80. box_batch_size_per_image=512,
  81. box_positive_fraction=0.25,
  82. bbox_reg_weights=None,
  83. # keypoint parameters
  84. keypoint_roi_pool=None,
  85. keypoint_head=None,
  86. keypoint_predictor=None,
  87. num_keypoints=None,
  88. wirepoint_roi_pool=None,
  89. wirepoint_head=None,
  90. wirepoint_predictor=None,
  91. **kwargs,
  92. ):
  93. if not isinstance(keypoint_roi_pool, (MultiScaleRoIAlign, type(None))):
  94. raise TypeError(
  95. "keypoint_roi_pool should be of type MultiScaleRoIAlign or None instead of {type(keypoint_roi_pool)}"
  96. )
  97. if min_size is None:
  98. min_size = (640, 672, 704, 736, 768, 800)
  99. if num_keypoints is not None:
  100. if keypoint_predictor is not None:
  101. raise ValueError("num_keypoints should be None when keypoint_predictor is specified")
  102. else:
  103. num_keypoints = 17
  104. out_channels = backbone.out_channels
  105. if wirepoint_roi_pool is None:
  106. wirepoint_roi_pool = MultiScaleRoIAlign(featmap_names=["0", "1", "2", "3"], output_size=128,
  107. sampling_ratio=2,)
  108. if wirepoint_head is None:
  109. keypoint_layers = tuple(512 for _ in range(8))
  110. print(f'keypoinyrcnnHeads inchannels:{out_channels},layers{keypoint_layers}')
  111. wirepoint_head = WirepointHead(out_channels, keypoint_layers)
  112. if wirepoint_predictor is None:
  113. keypoint_dim_reduced = 512 # == keypoint_layers[-1]
  114. wirepoint_predictor = WirepointPredictor()
  115. super().__init__(
  116. backbone,
  117. num_classes,
  118. # transform parameters
  119. min_size,
  120. max_size,
  121. image_mean,
  122. image_std,
  123. # RPN-specific parameters
  124. rpn_anchor_generator,
  125. rpn_head,
  126. rpn_pre_nms_top_n_train,
  127. rpn_pre_nms_top_n_test,
  128. rpn_post_nms_top_n_train,
  129. rpn_post_nms_top_n_test,
  130. rpn_nms_thresh,
  131. rpn_fg_iou_thresh,
  132. rpn_bg_iou_thresh,
  133. rpn_batch_size_per_image,
  134. rpn_positive_fraction,
  135. rpn_score_thresh,
  136. # Box parameters
  137. box_roi_pool,
  138. box_head,
  139. box_predictor,
  140. box_score_thresh,
  141. box_nms_thresh,
  142. box_detections_per_img,
  143. box_fg_iou_thresh,
  144. box_bg_iou_thresh,
  145. box_batch_size_per_image,
  146. box_positive_fraction,
  147. bbox_reg_weights,
  148. **kwargs,
  149. )
  150. if box_roi_pool is None:
  151. box_roi_pool = MultiScaleRoIAlign(featmap_names=["0", "1", "2", "3"], output_size=14, sampling_ratio=2)
  152. if box_head is None:
  153. resolution = box_roi_pool.output_size[0]
  154. representation_size = 1024
  155. box_head = TwoMLPHead(out_channels * resolution ** 2, representation_size)
  156. if box_predictor is None:
  157. representation_size = 1024
  158. box_predictor = FastRCNNPredictor(representation_size, num_classes)
  159. roi_heads = RoIHeads(
  160. # Box
  161. box_roi_pool,
  162. box_head,
  163. box_predictor,
  164. box_fg_iou_thresh,
  165. box_bg_iou_thresh,
  166. box_batch_size_per_image,
  167. box_positive_fraction,
  168. bbox_reg_weights,
  169. box_score_thresh,
  170. box_nms_thresh,
  171. box_detections_per_img,
  172. # wirepoint_roi_pool=wirepoint_roi_pool,
  173. # wirepoint_head=wirepoint_head,
  174. # wirepoint_predictor=wirepoint_predictor,
  175. )
  176. self.roi_heads = roi_heads
  177. self.roi_heads.wirepoint_roi_pool = wirepoint_roi_pool
  178. self.roi_heads.wirepoint_head = wirepoint_head
  179. self.roi_heads.wirepoint_predictor = wirepoint_predictor
  180. class WirepointHead(nn.Module):
  181. def __init__(self, input_channels, num_class):
  182. super(WirepointHead, self).__init__()
  183. self.head_size = [[2], [1], [2]]
  184. m = int(input_channels / 4)
  185. heads = []
  186. # print(f'M.head_size:{M.head_size}')
  187. # for output_channels in sum(M.head_size, []):
  188. for output_channels in sum(self.head_size, []):
  189. heads.append(
  190. nn.Sequential(
  191. nn.Conv2d(input_channels, m, kernel_size=3, padding=1),
  192. nn.ReLU(inplace=True),
  193. nn.Conv2d(m, output_channels, kernel_size=1),
  194. )
  195. )
  196. self.heads = nn.ModuleList(heads)
  197. def forward(self, x):
  198. # for idx, head in enumerate(self.heads):
  199. # print(f'{idx},multitask head:{head(x).shape},input x:{x.shape}')
  200. outputs = torch.cat([head(x) for head in self.heads], dim=1)
  201. features = x
  202. return outputs, features
  203. class WirepointPredictor(nn.Module):
  204. def __init__(self):
  205. super().__init__()
  206. # self.backbone = backbone
  207. # self.cfg = read_yaml(cfg)
  208. self.cfg = read_yaml('wirenet.yaml')
  209. self.n_pts0 = self.cfg['model']['n_pts0']
  210. self.n_pts1 = self.cfg['model']['n_pts1']
  211. self.n_stc_posl = self.cfg['model']['n_stc_posl']
  212. self.dim_loi = self.cfg['model']['dim_loi']
  213. self.use_conv = self.cfg['model']['use_conv']
  214. self.dim_fc = self.cfg['model']['dim_fc']
  215. self.n_out_line = self.cfg['model']['n_out_line']
  216. self.n_out_junc = self.cfg['model']['n_out_junc']
  217. self.loss_weight = self.cfg['model']['loss_weight']
  218. self.n_dyn_junc = self.cfg['model']['n_dyn_junc']
  219. self.eval_junc_thres = self.cfg['model']['eval_junc_thres']
  220. self.n_dyn_posl = self.cfg['model']['n_dyn_posl']
  221. self.n_dyn_negl = self.cfg['model']['n_dyn_negl']
  222. self.n_dyn_othr = self.cfg['model']['n_dyn_othr']
  223. self.use_cood = self.cfg['model']['use_cood']
  224. self.use_slop = self.cfg['model']['use_slop']
  225. self.n_stc_negl = self.cfg['model']['n_stc_negl']
  226. self.head_size = self.cfg['model']['head_size']
  227. self.num_class = sum(sum(self.head_size, []))
  228. self.head_off = np.cumsum([sum(h) for h in self.head_size])
  229. lambda_ = torch.linspace(0, 1, self.n_pts0)[:, None]
  230. self.register_buffer("lambda_", lambda_)
  231. self.do_static_sampling = self.n_stc_posl + self.n_stc_negl > 0
  232. self.fc1 = nn.Conv2d(256, self.dim_loi, 1)
  233. scale_factor = self.n_pts0 // self.n_pts1
  234. if self.use_conv:
  235. self.pooling = nn.Sequential(
  236. nn.MaxPool1d(scale_factor, scale_factor),
  237. Bottleneck1D(self.dim_loi, self.dim_loi),
  238. )
  239. self.fc2 = nn.Sequential(
  240. nn.ReLU(inplace=True), nn.Linear(self.dim_loi * self.n_pts1 + FEATURE_DIM, 1)
  241. )
  242. else:
  243. self.pooling = nn.MaxPool1d(scale_factor, scale_factor)
  244. self.fc2 = nn.Sequential(
  245. nn.Linear(self.dim_loi * self.n_pts1 + FEATURE_DIM, self.dim_fc),
  246. nn.ReLU(inplace=True),
  247. nn.Linear(self.dim_fc, self.dim_fc),
  248. nn.ReLU(inplace=True),
  249. nn.Linear(self.dim_fc, 1),
  250. )
  251. self.loss = nn.BCEWithLogitsLoss(reduction="none")
  252. def forward(self, inputs,features, targets=None):
  253. # outputs, features = input
  254. # for out in outputs:
  255. # print(f'out:{out.shape}')
  256. # outputs=merge_features(outputs,100)
  257. batch, channel, row, col = inputs.shape
  258. print(f'outputs:{inputs.shape}')
  259. print(f'batch:{batch}, channel:{channel}, row:{row}, col:{col}')
  260. if targets is not None:
  261. self.training = True
  262. # print(f'target:{targets}')
  263. wires_targets = [t["wires"] for t in targets]
  264. # print(f'wires_target:{wires_targets}')
  265. # 提取所有 'junc_map', 'junc_offset', 'line_map' 的张量
  266. junc_maps = [d["junc_map"] for d in wires_targets]
  267. junc_offsets = [d["junc_offset"] for d in wires_targets]
  268. line_maps = [d["line_map"] for d in wires_targets]
  269. junc_map_tensor = torch.stack(junc_maps, dim=0)
  270. junc_offset_tensor = torch.stack(junc_offsets, dim=0)
  271. line_map_tensor = torch.stack(line_maps, dim=0)
  272. wires_meta = {
  273. "junc_map": junc_map_tensor,
  274. "junc_offset": junc_offset_tensor,
  275. # "line_map": line_map_tensor,
  276. }
  277. else:
  278. self.training = False
  279. t = {
  280. "junc_coords": torch.zeros(1, 2),
  281. "jtyp": torch.zeros(1, dtype=torch.uint8),
  282. "line_pos_idx": torch.zeros(2, 2, dtype=torch.uint8),
  283. "line_neg_idx": torch.zeros(2, 2, dtype=torch.uint8),
  284. "junc_map": torch.zeros([1, 1, 128, 128]),
  285. "junc_offset": torch.zeros([1, 1, 2, 128, 128]),
  286. }
  287. wires_targets=[t for b in range(inputs.size(0))]
  288. wires_meta={
  289. "junc_map": torch.zeros([1, 1, 128, 128]),
  290. "junc_offset": torch.zeros([1, 1, 2, 128, 128]),
  291. }
  292. T = wires_meta.copy()
  293. n_jtyp = T["junc_map"].shape[1]
  294. offset = self.head_off
  295. result={}
  296. for stack, output in enumerate([inputs]):
  297. output = output.transpose(0, 1).reshape([-1, batch, row, col]).contiguous()
  298. print(f"Stack {stack} output shape: {output.shape}") # 打印每层的输出形状
  299. jmap = output[0: offset[0]].reshape(n_jtyp, 2, batch, row, col)
  300. lmap = output[offset[0]: offset[1]].squeeze(0)
  301. joff = output[offset[1]: offset[2]].reshape(n_jtyp, 2, batch, row, col)
  302. if stack == 0:
  303. result["preds"] = {
  304. "jmap": jmap.permute(2, 0, 1, 3, 4).softmax(2)[:, :, 1],
  305. "lmap": lmap.sigmoid(),
  306. "joff": joff.permute(2, 0, 1, 3, 4).sigmoid() - 0.5,
  307. }
  308. # visualize_feature_map(jmap[0, 0], title=f"jmap - Stack {stack}")
  309. # visualize_feature_map(lmap, title=f"lmap - Stack {stack}")
  310. # visualize_feature_map(joff[0, 0], title=f"joff - Stack {stack}")
  311. h = result["preds"]
  312. print(f'features shape:{features.shape}')
  313. x = self.fc1(features)
  314. print(f'x:{x.shape}')
  315. n_batch, n_channel, row, col = x.shape
  316. print(f'n_batch:{n_batch}, n_channel:{n_channel}, row:{row}, col:{col}')
  317. xs, ys, fs, ps, idx, jcs = [], [], [], [], [0], []
  318. for i, meta in enumerate(wires_targets):
  319. p, label, feat, jc = self.sample_lines(
  320. meta, h["jmap"][i], h["joff"][i],
  321. )
  322. print(f"p.shape:{p.shape},label:{label.shape},feat:{feat.shape},jc:{len(jc)}")
  323. ys.append(label)
  324. if self.training and self.do_static_sampling:
  325. p = torch.cat([p, meta["lpre"]])
  326. feat = torch.cat([feat, meta["lpre_feat"]])
  327. ys.append(meta["lpre_label"])
  328. del jc
  329. else:
  330. jcs.append(jc)
  331. ps.append(p)
  332. fs.append(feat)
  333. p = p[:, 0:1, :] * self.lambda_ + p[:, 1:2, :] * (1 - self.lambda_) - 0.5
  334. p = p.reshape(-1, 2) # [N_LINE x N_POINT, 2_XY]
  335. px, py = p[:, 0].contiguous(), p[:, 1].contiguous()
  336. px0 = px.floor().clamp(min=0, max=127)
  337. py0 = py.floor().clamp(min=0, max=127)
  338. px1 = (px0 + 1).clamp(min=0, max=127)
  339. py1 = (py0 + 1).clamp(min=0, max=127)
  340. px0l, py0l, px1l, py1l = px0.long(), py0.long(), px1.long(), py1.long()
  341. # xp: [N_LINE, N_CHANNEL, N_POINT]
  342. xp = (
  343. (
  344. x[i, :, px0l, py0l] * (px1 - px) * (py1 - py)
  345. + x[i, :, px1l, py0l] * (px - px0) * (py1 - py)
  346. + x[i, :, px0l, py1l] * (px1 - px) * (py - py0)
  347. + x[i, :, px1l, py1l] * (px - px0) * (py - py0)
  348. )
  349. .reshape(n_channel, -1, self.n_pts0)
  350. .permute(1, 0, 2)
  351. )
  352. xp = self.pooling(xp)
  353. print(f'xp.shape:{xp.shape}')
  354. xs.append(xp)
  355. idx.append(idx[-1] + xp.shape[0])
  356. print(f'idx__:{idx}')
  357. x, y = torch.cat(xs), torch.cat(ys)
  358. f = torch.cat(fs)
  359. x = x.reshape(-1, self.n_pts1 * self.dim_loi)
  360. # print("Weight dtype:", self.fc2.weight.dtype)
  361. x = torch.cat([x, f], 1)
  362. print("Input dtype:", x.dtype)
  363. x = x.to(dtype=torch.float32)
  364. print("Input dtype1:", x.dtype)
  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. ####deprecated
  372. # def inference(self,input, idx, jcs, n_batch, ps):
  373. # if not self.training:
  374. # p = torch.cat(ps)
  375. # s = torch.sigmoid(input)
  376. # b = s > 0.5
  377. # lines = []
  378. # score = []
  379. # print(f"n_batch:{n_batch}")
  380. # for i in range(n_batch):
  381. # print(f"idx:{idx}")
  382. # p0 = p[idx[i]: idx[i + 1]]
  383. # s0 = s[idx[i]: idx[i + 1]]
  384. # mask = b[idx[i]: idx[i + 1]]
  385. # p0 = p0[mask]
  386. # s0 = s0[mask]
  387. # if len(p0) == 0:
  388. # lines.append(torch.zeros([1, self.n_out_line, 2, 2], device=p.device))
  389. # score.append(torch.zeros([1, self.n_out_line], device=p.device))
  390. # else:
  391. # arg = torch.argsort(s0, descending=True)
  392. # p0, s0 = p0[arg], s0[arg]
  393. # lines.append(p0[None, torch.arange(self.n_out_line) % len(p0)])
  394. # score.append(s0[None, torch.arange(self.n_out_line) % len(s0)])
  395. # for j in range(len(jcs[i])):
  396. # if len(jcs[i][j]) == 0:
  397. # jcs[i][j] = torch.zeros([self.n_out_junc, 2], device=p.device)
  398. # jcs[i][j] = jcs[i][j][
  399. # None, torch.arange(self.n_out_junc) % len(jcs[i][j])
  400. # ]
  401. # result["preds"]["lines"] = torch.cat(lines)
  402. # result["preds"]["score"] = torch.cat(score)
  403. # result["preds"]["juncs"] = torch.cat([jcs[i][0] for i in range(n_batch)])
  404. #
  405. # if len(jcs[i]) > 1:
  406. # result["preds"]["junts"] = torch.cat(
  407. # [jcs[i][1] for i in range(n_batch)]
  408. # )
  409. # if self.training:
  410. # del result["preds"]
  411. def sample_lines(self, meta, jmap, joff):
  412. with torch.no_grad():
  413. junc = meta["junc_coords"] # [N, 2]
  414. jtyp = meta["jtyp"] # [N]
  415. Lpos = meta["line_pos_idx"]
  416. Lneg = meta["line_neg_idx"]
  417. n_type = jmap.shape[0]
  418. jmap = non_maximum_suppression(jmap).reshape(n_type, -1)
  419. joff = joff.reshape(n_type, 2, -1)
  420. max_K = self.n_dyn_junc // n_type
  421. N = len(junc)
  422. # if mode != "training":
  423. if not self.training:
  424. K = min(int((jmap > self.eval_junc_thres).float().sum().item()), max_K)
  425. else:
  426. K = min(int(N * 2 + 2), max_K)
  427. if K < 2:
  428. K = 2
  429. device = jmap.device
  430. # index: [N_TYPE, K]
  431. score, index = torch.topk(jmap, k=K)
  432. y = (index // 128).float() + torch.gather(joff[:, 0], 1, index) + 0.5
  433. x = (index % 128).float() + torch.gather(joff[:, 1], 1, index) + 0.5
  434. # xy: [N_TYPE, K, 2]
  435. xy = torch.cat([y[..., None], x[..., None]], dim=-1)
  436. xy_ = xy[..., None, :]
  437. del x, y, index
  438. # dist: [N_TYPE, K, N]
  439. dist = torch.sum((xy_ - junc) ** 2, -1)
  440. cost, match = torch.min(dist, -1)
  441. # xy: [N_TYPE * K, 2]
  442. # match: [N_TYPE, K]
  443. for t in range(n_type):
  444. match[t, jtyp[match[t]] != t] = N
  445. match[cost > 1.5 * 1.5] = N
  446. match = match.flatten()
  447. _ = torch.arange(n_type * K, device=device)
  448. u, v = torch.meshgrid(_, _)
  449. u, v = u.flatten(), v.flatten()
  450. up, vp = match[u], match[v]
  451. label = Lpos[up, vp]
  452. # if mode == "training":
  453. if self.training:
  454. c = torch.zeros_like(label, dtype=torch.bool)
  455. # sample positive lines
  456. cdx = label.nonzero().flatten()
  457. if len(cdx) > self.n_dyn_posl:
  458. # print("too many positive lines")
  459. perm = torch.randperm(len(cdx), device=device)[: self.n_dyn_posl]
  460. cdx = cdx[perm]
  461. c[cdx] = 1
  462. # sample negative lines
  463. cdx = Lneg[up, vp].nonzero().flatten()
  464. if len(cdx) > self.n_dyn_negl:
  465. # print("too many negative lines")
  466. perm = torch.randperm(len(cdx), device=device)[: self.n_dyn_negl]
  467. cdx = cdx[perm]
  468. c[cdx] = 1
  469. # sample other (unmatched) lines
  470. cdx = torch.randint(len(c), (self.n_dyn_othr,), device=device)
  471. c[cdx] = 1
  472. else:
  473. c = (u < v).flatten()
  474. # sample lines
  475. u, v, label = u[c], v[c], label[c]
  476. xy = xy.reshape(n_type * K, 2)
  477. xyu, xyv = xy[u], xy[v]
  478. u2v = xyu - xyv
  479. u2v /= torch.sqrt((u2v ** 2).sum(-1, keepdim=True)).clamp(min=1e-6)
  480. feat = torch.cat(
  481. [
  482. xyu / 128 * self.use_cood,
  483. xyv / 128 * self.use_cood,
  484. u2v * self.use_slop,
  485. (u[:, None] > K).float(),
  486. (v[:, None] > K).float(),
  487. ],
  488. 1,
  489. )
  490. line = torch.cat([xyu[:, None], xyv[:, None]], 1)
  491. xy = xy.reshape(n_type, K, 2)
  492. jcs = [xy[i, score[i] > 0.03] for i in range(n_type)]
  493. return line, label.float(), feat, jcs
  494. def wirepointrcnn_resnet50_fpn(
  495. *,
  496. weights: Optional[KeypointRCNN_ResNet50_FPN_Weights] = None,
  497. progress: bool = True,
  498. num_classes: Optional[int] = None,
  499. num_keypoints: Optional[int] = None,
  500. weights_backbone: Optional[ResNet50_Weights] = ResNet50_Weights.IMAGENET1K_V1,
  501. trainable_backbone_layers: Optional[int] = None,
  502. **kwargs: Any,
  503. ) -> WirepointRCNN:
  504. weights = KeypointRCNN_ResNet50_FPN_Weights.verify(weights)
  505. weights_backbone = ResNet50_Weights.verify(weights_backbone)
  506. is_trained = weights is not None or weights_backbone is not None
  507. trainable_backbone_layers = _validate_trainable_layers(is_trained, trainable_backbone_layers, 5, 3)
  508. norm_layer = misc_nn_ops.FrozenBatchNorm2d if is_trained else nn.BatchNorm2d
  509. backbone = resnet50(weights=weights_backbone, progress=progress, norm_layer=norm_layer)
  510. backbone = _resnet_fpn_extractor(backbone, trainable_backbone_layers)
  511. model = WirepointRCNN(backbone, num_classes=5, **kwargs)
  512. if weights is not None:
  513. model.load_state_dict(weights.get_state_dict(progress=progress))
  514. if weights == KeypointRCNN_ResNet50_FPN_Weights.COCO_V1:
  515. overwrite_eps(model, 0.0)
  516. return model
  517. if __name__ == '__main__':
  518. cfg = 'wirenet.yaml'
  519. cfg = read_yaml(cfg)
  520. print(f'cfg:{cfg}')
  521. print(cfg['model']['n_dyn_negl'])
  522. # net = WirepointPredictor()
  523. dataset = WirePointDataset(dataset_path=cfg['io']['datadir'], dataset_type='val')
  524. train_sampler = torch.utils.data.RandomSampler(dataset)
  525. # test_sampler = torch.utils.data.SequentialSampler(dataset_test)
  526. train_batch_sampler = torch.utils.data.BatchSampler(train_sampler, batch_size=4, drop_last=True)
  527. train_collate_fn = utils.collate_fn_wirepoint
  528. data_loader = torch.utils.data.DataLoader(
  529. dataset, batch_sampler=train_batch_sampler, num_workers=10, collate_fn=train_collate_fn
  530. )
  531. model = wirepointrcnn_resnet50_fpn()
  532. imgs, targets = next(iter(data_loader))
  533. model.train()
  534. pred = model(imgs, targets)
  535. print(f'pred:{pred}')
  536. # result, losses = model(imgs, targets)
  537. # print(f'result:{result}')
  538. # print(f'pred:{losses}')
  539. '''
  540. ########### predict#############
  541. img_path=r"I:\wirenet_dateset\images\train\00030078_2.png"
  542. transforms = MaskRCNN_ResNet50_FPN_V2_Weights.DEFAULT.transforms()
  543. img = read_image(img_path)
  544. img = transforms(img)
  545. img = torch.ones((2, 3, 512, 512))
  546. # print(f'img shape:{img.shape}')
  547. model.eval()
  548. onnx_file_path = "./wirenet.onnx"
  549. # 导出模型为ONNX格式
  550. # torch.onnx.export(model, img, onnx_file_path, verbose=True, input_names=['input'],
  551. # output_names=['output'])
  552. # torch.save(model,'./wirenet.pt')
  553. # 5. 指定输出的 ONNX 文件名
  554. # onnx_file_path = "./wirepoint_rcnn.onnx"
  555. # 准备一个示例输入:Mask R-CNN 需要一个图像列表作为输入,每个图像张量的形状应为 [C, H, W]
  556. img = [torch.ones((3, 800, 800))] # 示例输入图像大小为 800x800,3个通道
  557. # 指定输出的 ONNX 文件名
  558. # onnx_file_path = "./mask_rcnn.onnx"
  559. # model_scripted = torch.jit.script(model)
  560. # torch.onnx.export(model_scripted, input, "model.onnx", verbose=True, input_names=["input"],
  561. # output_names=["output"])
  562. #
  563. # print(f"Model has been converted to ONNX and saved to {onnx_file_path}")
  564. pred=model(img)
  565. #
  566. print(f'pred:{pred}')
  567. ################################################## end predict
  568. ########## traing ###################################
  569. # imgs, targets = next(iter(data_loader))
  570. # model.train()
  571. # pred = model(imgs, targets)
  572. # class WrapperModule(torch.nn.Module):
  573. # def __init__(self, model):
  574. # super(WrapperModule, self).__init__()
  575. # self.model = model
  576. #
  577. # def forward(self,img, targets):
  578. # # 在这里处理复杂的输入结构,将其转换为适合追踪的形式
  579. # return self.model(img,targets)
  580. # torch.save(model.state_dict(),'./wire.pt')
  581. # 包装原始模型
  582. # wrapped_model = WrapperModule(model)
  583. # # model_scripted = torch.jit.trace(wrapped_model,img)
  584. # writer = SummaryWriter('./')
  585. # writer.add_graph(wrapped_model, (imgs,targets))
  586. # writer.close()
  587. #
  588. # print(f'pred:{pred}')
  589. ########## end traing ###################################
  590. # for imgs,targets in data_loader:
  591. # print(f'imgs:{imgs}')
  592. # print(f'targets:{targets}')
  593. '''