line_net.py 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038
  1. import os
  2. from typing import Any, Callable, List, Optional, Tuple, Union
  3. import torch
  4. from torch import nn
  5. from torchvision.ops import MultiScaleRoIAlign
  6. from libs.vision_libs import ops
  7. from libs.vision_libs.models import MobileNet_V3_Large_Weights, mobilenet_v3_large, EfficientNet_V2_S_Weights, \
  8. efficientnet_v2_s, detection, EfficientNet_V2_L_Weights, efficientnet_v2_l, EfficientNet_V2_M_Weights, \
  9. efficientnet_v2_m
  10. from libs.vision_libs.models.detection.anchor_utils import AnchorGenerator
  11. from libs.vision_libs.models.detection.rpn import RPNHead, RegionProposalNetwork
  12. from libs.vision_libs.models.detection.ssdlite import _mobilenet_extractor
  13. from libs.vision_libs.models.detection.transform import GeneralizedRCNNTransform
  14. from libs.vision_libs.ops import misc as misc_nn_ops
  15. from libs.vision_libs.transforms._presets import ObjectDetection
  16. from .line_head import LineRCNNHeads
  17. from .line_predictor import LineRCNNPredictor
  18. from libs.vision_libs.models._api import register_model, Weights, WeightsEnum
  19. from libs.vision_libs.models._meta import _COCO_PERSON_CATEGORIES, _COCO_PERSON_KEYPOINT_NAMES, _COCO_CATEGORIES
  20. from libs.vision_libs.models._utils import _ovewrite_value_param, handle_legacy_interface
  21. from libs.vision_libs.models.resnet import resnet50, ResNet50_Weights, ResNet18_Weights, resnet18, resnet101
  22. from libs.vision_libs.models.detection._utils import overwrite_eps
  23. from libs.vision_libs.models.detection.backbone_utils import _resnet_fpn_extractor, _validate_trainable_layers, \
  24. BackboneWithFPN
  25. from libs.vision_libs.models.detection.faster_rcnn import FasterRCNN, TwoMLPHead, FastRCNNPredictor
  26. from .roi_heads import RoIHeads
  27. from .trainer import Trainer
  28. from ..base import backbone_factory
  29. from ..base.backbone_factory import get_convnext_fpn, get_anchor_generator
  30. # from ..base.backbone_factory import get_convnext_fpn, get_anchor_generator
  31. from ..base.base_detection_net import BaseDetectionNet
  32. import torch.nn.functional as F
  33. from .predict import Predict1, Predict
  34. from ..config.config_tool import read_yaml
  35. FEATURE_DIM = 8
  36. device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
  37. __all__ = [
  38. "LineNet",
  39. "LineNet_ResNet50_FPN_Weights",
  40. "LineNet_ResNet50_FPN_V2_Weights",
  41. "LineNet_MobileNet_V3_Large_FPN_Weights",
  42. "LineNet_MobileNet_V3_Large_320_FPN_Weights",
  43. "linenet_resnet50_fpn",
  44. "linenet_resnet50_fpn_v2",
  45. "linenet_mobilenet_v3_large_fpn",
  46. "linenet_mobilenet_v3_large_320_fpn",
  47. ]
  48. def _default_anchorgen():
  49. anchor_sizes = ((32,), (64,), (128,), (256,), (512,))
  50. aspect_ratios = ((0.5, 1.0, 2.0),) * len(anchor_sizes)
  51. return AnchorGenerator(anchor_sizes, aspect_ratios)
  52. class LineNet(BaseDetectionNet):
  53. # def __init__(self, cfg, **kwargs):
  54. # cfg = read_yaml(cfg)
  55. # self.cfg=cfg
  56. # backbone = cfg['backbone']
  57. # print(f'LineNet Backbone:{backbone}')
  58. # num_classes = cfg['num_classes']
  59. #
  60. # if backbone == 'resnet50_fpn':
  61. # backbone=backbone_factory.get_resnet50_fpn()
  62. # print(f'out_chanenels:{backbone.out_channels}')
  63. # elif backbone== 'mobilenet_v3_large_fpn':
  64. # backbone=backbone_factory.get_mobilenet_v3_large_fpn()
  65. # elif backbone=='resnet18_fpn':
  66. # backbone=backbone_factory.get_resnet18_fpn()
  67. #
  68. # self.__construct__(backbone=backbone, num_classes=num_classes, **kwargs)
  69. def __init__(
  70. self,
  71. backbone,
  72. num_classes=None,
  73. # transform parameters
  74. min_size=512,
  75. max_size=1333,
  76. image_mean=None,
  77. image_std=None,
  78. # RPN parameters
  79. rpn_anchor_generator=None,
  80. rpn_head=None,
  81. rpn_pre_nms_top_n_train=2000,
  82. rpn_pre_nms_top_n_test=1000,
  83. rpn_post_nms_top_n_train=2000,
  84. rpn_post_nms_top_n_test=1000,
  85. rpn_nms_thresh=0.7,
  86. rpn_fg_iou_thresh=0.7,
  87. rpn_bg_iou_thresh=0.3,
  88. rpn_batch_size_per_image=256,
  89. rpn_positive_fraction=0.5,
  90. rpn_score_thresh=0.0,
  91. # Box parameters
  92. box_roi_pool=None,
  93. box_head=None,
  94. box_predictor=None,
  95. box_score_thresh=0.05,
  96. box_nms_thresh=0.5,
  97. box_detections_per_img=100,
  98. box_fg_iou_thresh=0.5,
  99. box_bg_iou_thresh=0.5,
  100. box_batch_size_per_image=512,
  101. box_positive_fraction=0.25,
  102. bbox_reg_weights=None,
  103. # line parameters
  104. line_head=None,
  105. line_predictor=None,
  106. **kwargs,
  107. ):
  108. if not hasattr(backbone, "out_channels"):
  109. raise ValueError(
  110. "backbone should contain an attribute out_channels "
  111. "specifying the number of output channels (assumed to be the "
  112. "same for all the levels)"
  113. )
  114. if not isinstance(rpn_anchor_generator, (AnchorGenerator, type(None))):
  115. raise TypeError(
  116. f"rpn_anchor_generator should be of type AnchorGenerator or None instead of {type(rpn_anchor_generator)}"
  117. )
  118. if not isinstance(box_roi_pool, (MultiScaleRoIAlign, type(None))):
  119. raise TypeError(
  120. f"box_roi_pool should be of type MultiScaleRoIAlign or None instead of {type(box_roi_pool)}"
  121. )
  122. # 修改第一个卷积层,将 in_channels 从 3 改为 4
  123. backbone.body.conv1 = nn.Conv2d(
  124. in_channels=4,
  125. out_channels=64,
  126. kernel_size=7,
  127. stride=2,
  128. padding=3,
  129. bias=False
  130. )
  131. if num_classes is not None:
  132. if box_predictor is not None:
  133. raise ValueError("num_classes should be None when box_predictor is specified")
  134. else:
  135. if box_predictor is None:
  136. raise ValueError("num_classes should not be None when box_predictor is not specified")
  137. out_channels = backbone.out_channels
  138. # cfg = read_yaml(cfg)
  139. # self.cfg=cfg
  140. if line_head is None:
  141. num_class = 5
  142. line_head = LineRCNNHeads(out_channels, num_class)
  143. if line_predictor is None:
  144. line_predictor = LineRCNNPredictor()
  145. if rpn_anchor_generator is None:
  146. rpn_anchor_generator = _default_anchorgen()
  147. if rpn_head is None:
  148. rpn_head = RPNHead(out_channels, rpn_anchor_generator.num_anchors_per_location()[0])
  149. rpn_pre_nms_top_n = dict(training=rpn_pre_nms_top_n_train, testing=rpn_pre_nms_top_n_test)
  150. rpn_post_nms_top_n = dict(training=rpn_post_nms_top_n_train, testing=rpn_post_nms_top_n_test)
  151. rpn = RegionProposalNetwork(
  152. rpn_anchor_generator,
  153. rpn_head,
  154. rpn_fg_iou_thresh,
  155. rpn_bg_iou_thresh,
  156. rpn_batch_size_per_image,
  157. rpn_positive_fraction,
  158. rpn_pre_nms_top_n,
  159. rpn_post_nms_top_n,
  160. rpn_nms_thresh,
  161. score_thresh=rpn_score_thresh,
  162. )
  163. if box_roi_pool is None:
  164. box_roi_pool = MultiScaleRoIAlign(featmap_names=["0", "1", "2", "3"], output_size=7, sampling_ratio=2)
  165. if box_head is None:
  166. resolution = box_roi_pool.output_size[0]
  167. representation_size = 1024
  168. box_head = TwoMLPHead(out_channels * resolution ** 2, representation_size)
  169. if box_predictor is None:
  170. representation_size = 1024
  171. box_predictor = BoxPredictor(representation_size, num_classes)
  172. roi_heads = RoIHeads(
  173. # Box
  174. box_roi_pool,
  175. box_head,
  176. box_predictor,
  177. line_head,
  178. line_predictor,
  179. box_fg_iou_thresh,
  180. box_bg_iou_thresh,
  181. box_batch_size_per_image,
  182. box_positive_fraction,
  183. bbox_reg_weights,
  184. box_score_thresh,
  185. box_nms_thresh,
  186. box_detections_per_img,
  187. )
  188. if image_mean is None:
  189. # image_mean = [0.485, 0.456, 0.406]
  190. image_mean = [0.485, 0.456, 0.406, 0.2549] # 假设你新加的通道均值为0.5
  191. if image_std is None:
  192. # image_std = [0.229, 0.224, 0.225]
  193. image_std = [0.229, 0.224, 0.225, 0.4093] # 标准差也补一个值
  194. transform = GeneralizedRCNNTransform(min_size, max_size, image_mean, image_std, **kwargs)
  195. super().__init__(backbone, rpn, roi_heads, transform)
  196. self.roi_heads = roi_heads
  197. # self.roi_heads.line_head = line_head
  198. # self.roi_heads.line_predictor = line_predictor
  199. def start_train(self, cfg):
  200. # cfg = read_yaml(cfg)
  201. self.trainer = Trainer()
  202. self.trainer.train_from_cfg(model=self, cfg=cfg)
  203. def load_best_model(self,save_path, device='cuda'):
  204. if os.path.exists(save_path):
  205. checkpoint = torch.load(save_path, map_location=device)
  206. self.load_state_dict(checkpoint['model_state_dict'])
  207. # if optimizer is not None:
  208. # optimizer.load_state_dict(checkpoint['optimizer_state_dict'])
  209. # epoch = checkpoint['epoch']
  210. # loss = checkpoint['loss']
  211. # print(f"Loaded best model from {save_path} at epoch {epoch} with loss {loss:.4f}")
  212. print(f"Loaded model from {save_path}")
  213. else:
  214. print(f"No saved model found at {save_path}")
  215. return self
  216. # 加载权重和推理一起
  217. def predict(self,img_path, type=0, threshold=0.5, save_path=None, show=False):
  218. # self.predict = Predict(pt_path, model, img_path, type, threshold, save_path, show)
  219. self.eval()
  220. self.to(device)
  221. self.predict = Predict(self, img_path, type, threshold, save_path, show)
  222. self.predict.run()
  223. # 不加载权重
  224. def predict1(self, model, img_path, type=0, threshold=0.5, save_path=None, show=False):
  225. self.predict = Predict1(model, img_path, type, threshold, save_path, show)
  226. self.predict.run()
  227. class TwoMLPHead(nn.Module):
  228. """
  229. Standard heads for FPN-based models
  230. Args:
  231. in_channels (int): number of input channels
  232. representation_size (int): size of the intermediate representation
  233. """
  234. def __init__(self, in_channels, representation_size):
  235. super().__init__()
  236. self.fc6 = nn.Linear(in_channels, representation_size)
  237. self.fc7 = nn.Linear(representation_size, representation_size)
  238. def forward(self, x):
  239. x = x.flatten(start_dim=1)
  240. x = F.relu(self.fc6(x))
  241. x = F.relu(self.fc7(x))
  242. return x
  243. class LineNetConvFCHead(nn.Sequential):
  244. def __init__(
  245. self,
  246. input_size: Tuple[int, int, int],
  247. conv_layers: List[int],
  248. fc_layers: List[int],
  249. norm_layer: Optional[Callable[..., nn.Module]] = None,
  250. ):
  251. """
  252. Args:
  253. input_size (Tuple[int, int, int]): the input size in CHW format.
  254. conv_layers (list): feature dimensions of each Convolution layer
  255. fc_layers (list): feature dimensions of each FCN layer
  256. norm_layer (callable, optional): Module specifying the normalization layer to use. Default: None
  257. """
  258. in_channels, in_height, in_width = input_size
  259. blocks = []
  260. previous_channels = in_channels
  261. for current_channels in conv_layers:
  262. blocks.append(misc_nn_ops.Conv2dNormActivation(previous_channels, current_channels, norm_layer=norm_layer))
  263. previous_channels = current_channels
  264. blocks.append(nn.Flatten())
  265. previous_channels = previous_channels * in_height * in_width
  266. for current_channels in fc_layers:
  267. blocks.append(nn.Linear(previous_channels, current_channels))
  268. blocks.append(nn.ReLU(inplace=True))
  269. previous_channels = current_channels
  270. super().__init__(*blocks)
  271. for layer in self.modules():
  272. if isinstance(layer, nn.Conv2d):
  273. nn.init.kaiming_normal_(layer.weight, mode="fan_out", nonlinearity="relu")
  274. if layer.bias is not None:
  275. nn.init.zeros_(layer.bias)
  276. class BoxPredictor(nn.Module):
  277. """
  278. Standard classification + bounding box regression layers
  279. for Fast R-CNN.
  280. Args:
  281. in_channels (int): number of input channels
  282. num_classes (int): number of output classes (including background)
  283. """
  284. def __init__(self, in_channels, num_classes):
  285. super().__init__()
  286. self.cls_score = nn.Linear(in_channels, num_classes)
  287. self.bbox_pred = nn.Linear(in_channels, num_classes * 4)
  288. def forward(self, x):
  289. if x.dim() == 4:
  290. torch._assert(
  291. list(x.shape[2:]) == [1, 1],
  292. f"x has the wrong shape, expecting the last two dimensions to be [1,1] instead of {list(x.shape[2:])}",
  293. )
  294. x = x.flatten(start_dim=1)
  295. scores = self.cls_score(x)
  296. bbox_deltas = self.bbox_pred(x)
  297. return scores, bbox_deltas
  298. _COMMON_META = {
  299. "categories": _COCO_CATEGORIES,
  300. "min_size": (1, 1),
  301. }
  302. def create_efficientnetv2_backbone(name='efficientnet_v2_m', pretrained=True):
  303. # 加载EfficientNetV2模型
  304. if name == 'efficientnet_v2_s':
  305. weights = EfficientNet_V2_S_Weights.IMAGENET1K_V1 if pretrained else None
  306. backbone = efficientnet_v2_s(weights=weights).features
  307. if name == 'efficientnet_v2_m':
  308. weights = EfficientNet_V2_M_Weights.IMAGENET1K_V1 if pretrained else None
  309. backbone = efficientnet_v2_m(weights=weights).features
  310. if name == 'efficientnet_v2_l':
  311. weights = EfficientNet_V2_L_Weights.IMAGENET1K_V1 if pretrained else None
  312. backbone = efficientnet_v2_l(weights=weights).features
  313. # 定义返回的层索引和名称
  314. return_layers = {"2": "0", "3": "1", "4": "2", "5": "3"}
  315. # 获取每个层输出通道数
  316. in_channels_list = []
  317. for layer_idx in [2, 3, 4, 5]:
  318. module = backbone[layer_idx]
  319. if hasattr(module, 'out_channels'):
  320. in_channels_list.append(module.out_channels)
  321. elif hasattr(module[-1], 'out_channels'):
  322. # 如果module本身没有out_channels,检查最后一个子模块
  323. in_channels_list.append(module[-1].out_channels)
  324. else:
  325. raise ValueError(f"Cannot determine out_channels for layer {layer_idx}")
  326. # 使用BackboneWithFPN包装backbone
  327. backbone_with_fpn = BackboneWithFPN(
  328. backbone=backbone,
  329. return_layers=return_layers,
  330. in_channels_list=in_channels_list,
  331. out_channels=256
  332. )
  333. return backbone_with_fpn
  334. def get_line_net_efficientnetv2(num_classes, pretrained_backbone=True):
  335. # 创建EfficientNetV2 backbone
  336. backbone = create_efficientnetv2_backbone(pretrained=pretrained_backbone)
  337. # 确认 backbone 输出特征图数量
  338. with torch.no_grad():
  339. images = torch.rand(1,3, 600, 800)
  340. features = backbone(images)
  341. featmap_names = list(features.keys())
  342. print("Feature map names:", featmap_names) # 例如 ['0', '1', '2', '3']
  343. # 根据实际特征层数量设置 anchors
  344. # num_levels = len(featmap_names)
  345. num_levels=5
  346. featmap_names= ['0', '1', '2', '3', 'pool']
  347. anchor_sizes = tuple((int(16 * 2 ** i),) for i in range(num_levels)) # 自动生成不同大小
  348. print(f'anchor_sizes:{anchor_sizes}')
  349. aspect_ratios = ((0.5, 1.0, 2.0),) * num_levels # 所有层共享相同比例
  350. print(f'aspect_ratios:{aspect_ratios}')
  351. anchor_generator = AnchorGenerator(
  352. sizes=anchor_sizes,
  353. aspect_ratios=aspect_ratios
  354. )
  355. # ROI Pooling
  356. roi_pooler = MultiScaleRoIAlign(
  357. featmap_names=featmap_names,
  358. output_size=7,
  359. sampling_ratio=2
  360. )
  361. # 构建模型
  362. model = LineNet(
  363. backbone=backbone,
  364. num_classes=num_classes,
  365. rpn_anchor_generator=anchor_generator,
  366. box_roi_pool=roi_pooler
  367. )
  368. return model
  369. def get_line_net_convnext_fpn(num_classes=91):
  370. backbone=get_convnext_fpn()
  371. featmap_names = ['0', '1', '2', '3', 'pool']
  372. roi_pooler = MultiScaleRoIAlign(
  373. featmap_names=featmap_names,
  374. output_size=7,
  375. sampling_ratio=2
  376. )
  377. test_input = torch.rand(1, 3, 224, 224)
  378. anchor_generator = get_anchor_generator(backbone, test_input)
  379. model = LineNet(
  380. backbone=backbone,
  381. num_classes=num_classes, # COCO 数据集有 91 类
  382. rpn_anchor_generator=anchor_generator,
  383. box_roi_pool=roi_pooler
  384. )
  385. return model
  386. class LineNet_ResNet50_FPN_Weights(WeightsEnum):
  387. COCO_V1 = Weights(
  388. url="https://download.pytorch.org/models/fasterrcnn_resnet50_fpn_coco-258fb6c6.pth",
  389. transforms=ObjectDetection,
  390. meta={
  391. **_COMMON_META,
  392. "num_params": 41755286,
  393. "recipe": "https://github.com/pytorch/vision/tree/main/references/detection#faster-r-cnn-resnet-50-fpn",
  394. "_metrics": {
  395. "COCO-val2017": {
  396. "box_map": 37.0,
  397. }
  398. },
  399. "_ops": 134.38,
  400. "_file_size": 159.743,
  401. "_docs": """These weights were produced by following a similar training recipe as on the paper.""",
  402. },
  403. )
  404. DEFAULT = COCO_V1
  405. class LineNet_ResNet50_FPN_V2_Weights(WeightsEnum):
  406. COCO_V1 = Weights(
  407. url="https://download.pytorch.org/models/fasterrcnn_resnet50_fpn_v2_coco-dd69338a.pth",
  408. transforms=ObjectDetection,
  409. meta={
  410. **_COMMON_META,
  411. "num_params": 43712278,
  412. "recipe": "https://github.com/pytorch/vision/pull/5763",
  413. "_metrics": {
  414. "COCO-val2017": {
  415. "box_map": 46.7,
  416. }
  417. },
  418. "_ops": 280.371,
  419. "_file_size": 167.104,
  420. "_docs": """These weights were produced using an enhanced training recipe to boost the model accuracy.""",
  421. },
  422. )
  423. DEFAULT = COCO_V1
  424. class LineNet_MobileNet_V3_Large_FPN_Weights(WeightsEnum):
  425. COCO_V1 = Weights(
  426. url="https://download.pytorch.org/models/fasterrcnn_mobilenet_v3_large_fpn-fb6a3cc7.pth",
  427. transforms=ObjectDetection,
  428. meta={
  429. **_COMMON_META,
  430. "num_params": 19386354,
  431. "recipe": "https://github.com/pytorch/vision/tree/main/references/detection#faster-r-cnn-mobilenetv3-large-fpn",
  432. "_metrics": {
  433. "COCO-val2017": {
  434. "box_map": 32.8,
  435. }
  436. },
  437. "_ops": 4.494,
  438. "_file_size": 74.239,
  439. "_docs": """These weights were produced by following a similar training recipe as on the paper.""",
  440. },
  441. )
  442. DEFAULT = COCO_V1
  443. class LineNet_MobileNet_V3_Large_320_FPN_Weights(WeightsEnum):
  444. COCO_V1 = Weights(
  445. url="https://download.pytorch.org/models/fasterrcnn_mobilenet_v3_large_320_fpn-907ea3f9.pth",
  446. transforms=ObjectDetection,
  447. meta={
  448. **_COMMON_META,
  449. "num_params": 19386354,
  450. "recipe": "https://github.com/pytorch/vision/tree/main/references/detection#faster-r-cnn-mobilenetv3-large-320-fpn",
  451. "_metrics": {
  452. "COCO-val2017": {
  453. "box_map": 22.8,
  454. }
  455. },
  456. "_ops": 0.719,
  457. "_file_size": 74.239,
  458. "_docs": """These weights were produced by following a similar training recipe as on the paper.""",
  459. },
  460. )
  461. DEFAULT = COCO_V1
  462. # @register_model()
  463. # @handle_legacy_interface(
  464. # weights=("pretrained", LineNet_ResNet50_FPN_Weights.COCO_V1),
  465. # weights_backbone=("pretrained_backbone", ResNet50_Weights.IMAGENET1K_V1),
  466. # )
  467. def linenet_resnet18_fpn(
  468. *,
  469. weights: Optional[LineNet_ResNet50_FPN_Weights] = None,
  470. progress: bool = True,
  471. num_classes: Optional[int] = None,
  472. weights_backbone: Optional[ResNet18_Weights] = ResNet18_Weights.IMAGENET1K_V1,
  473. trainable_backbone_layers: Optional[int] = None,
  474. **kwargs: Any,
  475. ) -> LineNet:
  476. # weights = LineNet_ResNet50_FPN_Weights.verify(weights)
  477. # weights_backbone = ResNet50_Weights.verify(weights_backbone)
  478. if weights is not None:
  479. weights_backbone = None
  480. num_classes = _ovewrite_value_param("num_classes", num_classes, len(weights.meta["categories"]))
  481. elif num_classes is None:
  482. num_classes = 91
  483. if weights_backbone is not None:
  484. print(f'resnet50 weights is not None')
  485. is_trained = weights is not None or weights_backbone is not None
  486. trainable_backbone_layers = _validate_trainable_layers(is_trained, trainable_backbone_layers, 5, 3)
  487. norm_layer = misc_nn_ops.FrozenBatchNorm2d if is_trained else nn.BatchNorm2d
  488. backbone = resnet18(weights=weights_backbone, progress=progress, norm_layer=norm_layer)
  489. backbone = _resnet_fpn_extractor(backbone, trainable_backbone_layers)
  490. model = LineNet(backbone, num_classes=num_classes, **kwargs)
  491. if weights is not None:
  492. model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True))
  493. if weights == LineNet_ResNet50_FPN_Weights.COCO_V1:
  494. overwrite_eps(model, 0.0)
  495. return model
  496. def linenet_resnet50_fpn(
  497. *,
  498. weights: Optional[LineNet_ResNet50_FPN_Weights] = None,
  499. progress: bool = True,
  500. num_classes: Optional[int] = None,
  501. weights_backbone: Optional[ResNet50_Weights] = ResNet50_Weights.IMAGENET1K_V1,
  502. trainable_backbone_layers: Optional[int] = None,
  503. **kwargs: Any,
  504. ) -> LineNet:
  505. """
  506. Faster R-CNN model with a ResNet-50-FPN backbone from the `Faster R-CNN: Towards Real-Time Object
  507. Detection with Region Proposal Networks <https://arxiv.org/abs/1506.01497>`__
  508. paper.
  509. .. betastatus:: detection module
  510. The input to the model is expected to be a list of tensors, each of shape ``[C, H, W]``, one for each
  511. image, and should be in ``0-1`` range. Different images can have different sizes.
  512. The behavior of the model changes depending on if it is in training or evaluation mode.
  513. During training, the model expects both the input tensors and a targets (list of dictionary),
  514. containing:
  515. - boxes (``FloatTensor[N, 4]``): the ground-truth boxes in ``[x1, y1, x2, y2]`` format, with
  516. ``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``.
  517. - labels (``Int64Tensor[N]``): the class label for each ground-truth box
  518. The model returns a ``Dict[Tensor]`` during training, containing the classification and regression
  519. losses for both the RPN and the R-CNN.
  520. During inference, the model requires only the input tensors, and returns the post-processed
  521. predictions as a ``List[Dict[Tensor]]``, one for each input image. The fields of the ``Dict`` are as
  522. follows, where ``N`` is the number of detections:
  523. - boxes (``FloatTensor[N, 4]``): the predicted boxes in ``[x1, y1, x2, y2]`` format, with
  524. ``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``.
  525. - labels (``Int64Tensor[N]``): the predicted labels for each detection
  526. - scores (``Tensor[N]``): the scores of each detection
  527. For more details on the output, you may refer to :ref:`instance_seg_output`.
  528. Faster R-CNN is exportable to ONNX for a fixed batch size with inputs images of fixed size.
  529. Example::
  530. >>> model = torchvision.models.detection.fasterrcnn_resnet50_fpn(weights=FasterRCNN_ResNet50_FPN_Weights.DEFAULT)
  531. >>> # For training
  532. >>> images, boxes = torch.rand(4, 3, 600, 1200), torch.rand(4, 11, 4)
  533. >>> boxes[:, :, 2:4] = boxes[:, :, 0:2] + boxes[:, :, 2:4]
  534. >>> labels = torch.randint(1, 91, (4, 11))
  535. >>> images = list(image for image in images)
  536. >>> targets = []
  537. >>> for i in range(len(images)):
  538. >>> d = {}
  539. >>> d['boxes'] = boxes[i]
  540. >>> d['labels'] = labels[i]
  541. >>> targets.append(d)
  542. >>> output = model(images, targets)
  543. >>> # For inference
  544. >>> model.eval()
  545. >>> x = [torch.rand(3, 300, 400), torch.rand(3, 500, 400)]
  546. >>> predictions = model(x)
  547. >>>
  548. >>> # optionally, if you want to export the model to ONNX:
  549. >>> torch.onnx.export(model, x, "faster_rcnn.onnx", opset_version = 11)
  550. Args:
  551. weights (:class:`~torchvision.models.detection.FasterRCNN_ResNet50_FPN_Weights`, optional): The
  552. pretrained weights to use. See
  553. :class:`~torchvision.models.detection.FasterRCNN_ResNet50_FPN_Weights` below for
  554. more details, and possible values. By default, no pre-trained
  555. weights are used.
  556. progress (bool, optional): If True, displays a progress bar of the
  557. download to stderr. Default is True.
  558. num_classes (int, optional): number of output classes of the model (including the background)
  559. weights_backbone (:class:`~torchvision.models.ResNet50_Weights`, optional): The
  560. pretrained weights for the backbone.
  561. trainable_backbone_layers (int, optional): number of trainable (not frozen) layers starting from
  562. final block. Valid values are between 0 and 5, with 5 meaning all backbone layers are
  563. trainable. If ``None`` is passed (the default) this value is set to 3.
  564. **kwargs: parameters passed to the ``torchvision.models.detection.faster_rcnn.FasterRCNN``
  565. base class. Please refer to the `source code
  566. <https://github.com/pytorch/vision/blob/main/torchvision/models/detection/faster_rcnn.py>`_
  567. for more details about this class.
  568. .. autoclass:: torchvision.models.detection.FasterRCNN_ResNet50_FPN_Weights
  569. :members:
  570. """
  571. weights = LineNet_ResNet50_FPN_Weights.verify(weights)
  572. weights_backbone = ResNet50_Weights.verify(weights_backbone)
  573. if weights is not None:
  574. weights_backbone = None
  575. num_classes = _ovewrite_value_param("num_classes", num_classes, len(weights.meta["categories"]))
  576. elif num_classes is None:
  577. num_classes = 91
  578. if weights_backbone is not None:
  579. print(f'resnet50 weights is not None')
  580. is_trained = weights is not None or weights_backbone is not None
  581. trainable_backbone_layers = _validate_trainable_layers(is_trained, trainable_backbone_layers, 5, 3)
  582. norm_layer = misc_nn_ops.FrozenBatchNorm2d if is_trained else nn.BatchNorm2d
  583. backbone = resnet50(weights=weights_backbone, progress=progress, norm_layer=norm_layer)
  584. backbone = _resnet_fpn_extractor(backbone, trainable_backbone_layers)
  585. model = LineNet(backbone, num_classes=num_classes, **kwargs)
  586. if weights is not None:
  587. model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True))
  588. if weights == LineNet_ResNet50_FPN_Weights.COCO_V1:
  589. overwrite_eps(model, 0.0)
  590. return model
  591. # @register_model()
  592. # @handle_legacy_interface(
  593. # weights=("pretrained", LineNet_ResNet50_FPN_V2_Weights.COCO_V1),
  594. # weights_backbone=("pretrained_backbone", ResNet50_Weights.IMAGENET1K_V1),
  595. # )
  596. def linenet_resnet50_fpn_v2(
  597. *,
  598. weights: Optional[LineNet_ResNet50_FPN_V2_Weights] = None,
  599. progress: bool = True,
  600. num_classes: Optional[int] = None,
  601. weights_backbone: Optional[ResNet50_Weights] = None,
  602. trainable_backbone_layers: Optional[int] = None,
  603. **kwargs: Any,
  604. ) -> LineNet:
  605. """
  606. Constructs an improved Faster R-CNN model with a ResNet-50-FPN backbone from `Benchmarking Detection
  607. Transfer Learning with Vision Transformers <https://arxiv.org/abs/2111.11429>`__ paper.
  608. .. betastatus:: detection module
  609. It works similarly to Faster R-CNN with ResNet-50 FPN backbone. See
  610. :func:`~torchvision.models.detection.fasterrcnn_resnet50_fpn` for more
  611. details.
  612. Args:
  613. weights (:class:`~torchvision.models.detection.FasterRCNN_ResNet50_FPN_V2_Weights`, optional): The
  614. pretrained weights to use. See
  615. :class:`~torchvision.models.detection.FasterRCNN_ResNet50_FPN_V2_Weights` below for
  616. more details, and possible values. By default, no pre-trained
  617. weights are used.
  618. progress (bool, optional): If True, displays a progress bar of the
  619. download to stderr. Default is True.
  620. num_classes (int, optional): number of output classes of the model (including the background)
  621. weights_backbone (:class:`~torchvision.models.ResNet50_Weights`, optional): The
  622. pretrained weights for the backbone.
  623. trainable_backbone_layers (int, optional): number of trainable (not frozen) layers starting from
  624. final block. Valid values are between 0 and 5, with 5 meaning all backbone layers are
  625. trainable. If ``None`` is passed (the default) this value is set to 3.
  626. **kwargs: parameters passed to the ``torchvision.models.detection.faster_rcnn.FasterRCNN``
  627. base class. Please refer to the `source code
  628. <https://github.com/pytorch/vision/blob/main/torchvision/models/detection/faster_rcnn.py>`_
  629. for more details about this class.
  630. .. autoclass:: torchvision.models.detection.FasterRCNN_ResNet50_FPN_V2_Weights
  631. :members:
  632. """
  633. weights = LineNet_ResNet50_FPN_V2_Weights.verify(weights)
  634. weights_backbone = ResNet50_Weights.verify(weights_backbone)
  635. if weights is not None:
  636. weights_backbone = None
  637. num_classes = _ovewrite_value_param("num_classes", num_classes, len(weights.meta["categories"]))
  638. elif num_classes is None:
  639. num_classes = 91
  640. is_trained = weights is not None or weights_backbone is not None
  641. trainable_backbone_layers = _validate_trainable_layers(is_trained, trainable_backbone_layers, 5, 3)
  642. backbone = resnet50(weights=weights_backbone, progress=progress)
  643. backbone = _resnet_fpn_extractor(backbone, trainable_backbone_layers, norm_layer=nn.BatchNorm2d)
  644. rpn_anchor_generator = _default_anchorgen()
  645. rpn_head = RPNHead(backbone.out_channels, rpn_anchor_generator.num_anchors_per_location()[0], conv_depth=2)
  646. box_head = LineNetConvFCHead(
  647. (backbone.out_channels, 7, 7), [256, 256, 256, 256], [1024], norm_layer=nn.BatchNorm2d
  648. )
  649. model = LineNet(
  650. backbone,
  651. num_classes=num_classes,
  652. rpn_anchor_generator=rpn_anchor_generator,
  653. rpn_head=rpn_head,
  654. box_head=box_head,
  655. **kwargs,
  656. )
  657. if weights is not None:
  658. model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True))
  659. return model
  660. def linenet_resnet101_fpn_v2(
  661. *,
  662. weights: Optional[LineNet_ResNet50_FPN_V2_Weights] = None,
  663. progress: bool = True,
  664. num_classes: Optional[int] = None,
  665. weights_backbone: Optional[ResNet50_Weights] = None,
  666. trainable_backbone_layers: Optional[int] = None,
  667. **kwargs: Any,
  668. ) -> LineNet:
  669. """
  670. Constructs an improved Faster R-CNN model with a ResNet-50-FPN backbone from `Benchmarking Detection
  671. Transfer Learning with Vision Transformers <https://arxiv.org/abs/2111.11429>`__ paper.
  672. .. betastatus:: detection module
  673. It works similarly to Faster R-CNN with ResNet-50 FPN backbone. See
  674. :func:`~torchvision.models.detection.fasterrcnn_resnet50_fpn` for more
  675. details.
  676. Args:
  677. weights (:class:`~torchvision.models.detection.FasterRCNN_ResNet50_FPN_V2_Weights`, optional): The
  678. pretrained weights to use. See
  679. :class:`~torchvision.models.detection.FasterRCNN_ResNet50_FPN_V2_Weights` below for
  680. more details, and possible values. By default, no pre-trained
  681. weights are used.
  682. progress (bool, optional): If True, displays a progress bar of the
  683. download to stderr. Default is True.
  684. num_classes (int, optional): number of output classes of the model (including the background)
  685. weights_backbone (:class:`~torchvision.models.ResNet50_Weights`, optional): The
  686. pretrained weights for the backbone.
  687. trainable_backbone_layers (int, optional): number of trainable (not frozen) layers starting from
  688. final block. Valid values are between 0 and 5, with 5 meaning all backbone layers are
  689. trainable. If ``None`` is passed (the default) this value is set to 3.
  690. **kwargs: parameters passed to the ``torchvision.models.detection.faster_rcnn.FasterRCNN``
  691. base class. Please refer to the `source code
  692. <https://github.com/pytorch/vision/blob/main/torchvision/models/detection/faster_rcnn.py>`_
  693. for more details about this class.
  694. .. autoclass:: torchvision.models.detection.FasterRCNN_ResNet50_FPN_V2_Weights
  695. :members:
  696. """
  697. weights = LineNet_ResNet50_FPN_V2_Weights.verify(weights)
  698. weights_backbone = ResNet50_Weights.verify(weights_backbone)
  699. if weights is not None:
  700. weights_backbone = None
  701. num_classes = _ovewrite_value_param("num_classes", num_classes, len(weights.meta["categories"]))
  702. elif num_classes is None:
  703. num_classes = 91
  704. is_trained = weights is not None or weights_backbone is not None
  705. trainable_backbone_layers = _validate_trainable_layers(is_trained, trainable_backbone_layers, 5, 3)
  706. backbone = resnet101(weights=weights_backbone, progress=progress)
  707. backbone = _resnet_fpn_extractor(backbone, trainable_backbone_layers, norm_layer=nn.BatchNorm2d)
  708. rpn_anchor_generator = _default_anchorgen()
  709. rpn_head = RPNHead(backbone.out_channels, rpn_anchor_generator.num_anchors_per_location()[0], conv_depth=2)
  710. box_head = LineNetConvFCHead(
  711. (backbone.out_channels, 7, 7), [256, 256, 256, 256], [1024], norm_layer=nn.BatchNorm2d
  712. )
  713. model = LineNet(
  714. backbone,
  715. num_classes=num_classes,
  716. rpn_anchor_generator=rpn_anchor_generator,
  717. rpn_head=rpn_head,
  718. box_head=box_head,
  719. **kwargs,
  720. )
  721. if weights is not None:
  722. model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True))
  723. return model
  724. def _linenet_mobilenet_v3_large_fpn(
  725. *,
  726. weights: Optional[Union[LineNet_MobileNet_V3_Large_FPN_Weights, LineNet_MobileNet_V3_Large_320_FPN_Weights]],
  727. progress: bool,
  728. num_classes: Optional[int],
  729. weights_backbone: Optional[MobileNet_V3_Large_Weights],
  730. trainable_backbone_layers: Optional[int],
  731. **kwargs: Any,
  732. ) -> LineNet:
  733. if weights is not None:
  734. weights_backbone = None
  735. num_classes = _ovewrite_value_param("num_classes", num_classes, len(weights.meta["categories"]))
  736. elif num_classes is None:
  737. num_classes = 91
  738. is_trained = weights is not None or weights_backbone is not None
  739. trainable_backbone_layers = _validate_trainable_layers(is_trained, trainable_backbone_layers, 6, 3)
  740. norm_layer = misc_nn_ops.FrozenBatchNorm2d if is_trained else nn.BatchNorm2d
  741. backbone = mobilenet_v3_large(weights=weights_backbone, progress=progress, norm_layer=norm_layer)
  742. backbone = _mobilenet_extractor(backbone, True, trainable_backbone_layers)
  743. anchor_sizes = (
  744. (
  745. 32,
  746. 64,
  747. 128,
  748. 256,
  749. 512,
  750. ),
  751. ) * 3
  752. aspect_ratios = ((0.5, 1.0, 2.0),) * len(anchor_sizes)
  753. model = LineNet(
  754. backbone, num_classes, rpn_anchor_generator=AnchorGenerator(anchor_sizes, aspect_ratios), **kwargs
  755. )
  756. if weights is not None:
  757. model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True))
  758. return model
  759. # @register_model()
  760. # @handle_legacy_interface(
  761. # weights=("pretrained", LineNet_MobileNet_V3_Large_320_FPN_Weights.COCO_V1),
  762. # weights_backbone=("pretrained_backbone", MobileNet_V3_Large_Weights.IMAGENET1K_V1),
  763. # )
  764. def linenet_mobilenet_v3_large_320_fpn(
  765. *,
  766. weights: Optional[LineNet_MobileNet_V3_Large_320_FPN_Weights] = None,
  767. progress: bool = True,
  768. num_classes: Optional[int] = None,
  769. weights_backbone: Optional[MobileNet_V3_Large_Weights] = MobileNet_V3_Large_Weights.IMAGENET1K_V1,
  770. trainable_backbone_layers: Optional[int] = None,
  771. **kwargs: Any,
  772. ) -> LineNet:
  773. """
  774. Low resolution Faster R-CNN model with a MobileNetV3-Large backbone tuned for mobile use cases.
  775. .. betastatus:: detection module
  776. It works similarly to Faster R-CNN with ResNet-50 FPN backbone. See
  777. :func:`~torchvision.models.detection.fasterrcnn_resnet50_fpn` for more
  778. details.
  779. Example::
  780. >>> model = torchvision.models.detection.fasterrcnn_mobilenet_v3_large_320_fpn(weights=FasterRCNN_MobileNet_V3_Large_320_FPN_Weights.DEFAULT)
  781. >>> model.eval()
  782. >>> x = [torch.rand(3, 300, 400), torch.rand(3, 500, 400)]
  783. >>> predictions = model(x)
  784. Args:
  785. weights (:class:`~torchvision.models.detection.FasterRCNN_MobileNet_V3_Large_320_FPN_Weights`, optional): The
  786. pretrained weights to use. See
  787. :class:`~torchvision.models.detection.FasterRCNN_MobileNet_V3_Large_320_FPN_Weights` below for
  788. more details, and possible values. By default, no pre-trained
  789. weights are used.
  790. progress (bool, optional): If True, displays a progress bar of the
  791. download to stderr. Default is True.
  792. num_classes (int, optional): number of output classes of the model (including the background)
  793. weights_backbone (:class:`~torchvision.models.MobileNet_V3_Large_Weights`, optional): The
  794. pretrained weights for the backbone.
  795. trainable_backbone_layers (int, optional): number of trainable (not frozen) layers starting from
  796. final block. Valid values are between 0 and 6, with 6 meaning all backbone layers are
  797. trainable. If ``None`` is passed (the default) this value is set to 3.
  798. **kwargs: parameters passed to the ``torchvision.models.detection.faster_rcnn.FasterRCNN``
  799. base class. Please refer to the `source code
  800. <https://github.com/pytorch/vision/blob/main/torchvision/models/detection/faster_rcnn.py>`_
  801. for more details about this class.
  802. .. autoclass:: torchvision.models.detection.FasterRCNN_MobileNet_V3_Large_320_FPN_Weights
  803. :members:
  804. """
  805. weights = LineNet_MobileNet_V3_Large_320_FPN_Weights.verify(weights)
  806. weights_backbone = MobileNet_V3_Large_Weights.verify(weights_backbone)
  807. defaults = {
  808. "min_size": 320,
  809. "max_size": 640,
  810. "rpn_pre_nms_top_n_test": 150,
  811. "rpn_post_nms_top_n_test": 150,
  812. "rpn_score_thresh": 0.05,
  813. }
  814. kwargs = {**defaults, **kwargs}
  815. return _linenet_mobilenet_v3_large_fpn(
  816. weights=weights,
  817. progress=progress,
  818. num_classes=num_classes,
  819. weights_backbone=weights_backbone,
  820. trainable_backbone_layers=trainable_backbone_layers,
  821. **kwargs,
  822. )
  823. # @register_model()
  824. # @handle_legacy_interface(
  825. # weights=("pretrained", LineNet_MobileNet_V3_Large_FPN_Weights.COCO_V1),
  826. # weights_backbone=("pretrained_backbone", MobileNet_V3_Large_Weights.IMAGENET1K_V1),
  827. # )
  828. def linenet_mobilenet_v3_large_fpn(
  829. *,
  830. weights: Optional[LineNet_MobileNet_V3_Large_FPN_Weights] = None,
  831. progress: bool = True,
  832. num_classes: Optional[int] = None,
  833. weights_backbone: Optional[MobileNet_V3_Large_Weights] = MobileNet_V3_Large_Weights.IMAGENET1K_V1,
  834. trainable_backbone_layers: Optional[int] = None,
  835. **kwargs: Any,
  836. ) -> LineNet:
  837. """
  838. Constructs a high resolution Faster R-CNN model with a MobileNetV3-Large FPN backbone.
  839. .. betastatus:: detection module
  840. It works similarly to Faster R-CNN with ResNet-50 FPN backbone. See
  841. :func:`~torchvision.models.detection.fasterrcnn_resnet50_fpn` for more
  842. details.
  843. Example::
  844. >>> model = torchvision.models.detection.fasterrcnn_mobilenet_v3_large_fpn(weights=FasterRCNN_MobileNet_V3_Large_FPN_Weights.DEFAULT)
  845. >>> model.eval()
  846. >>> x = [torch.rand(3, 300, 400), torch.rand(3, 500, 400)]
  847. >>> predictions = model(x)
  848. Args:
  849. weights (:class:`~torchvision.models.detection.FasterRCNN_MobileNet_V3_Large_FPN_Weights`, optional): The
  850. pretrained weights to use. See
  851. :class:`~torchvision.models.detection.FasterRCNN_MobileNet_V3_Large_FPN_Weights` below for
  852. more details, and possible values. By default, no pre-trained
  853. weights are used.
  854. progress (bool, optional): If True, displays a progress bar of the
  855. download to stderr. Default is True.
  856. num_classes (int, optional): number of output classes of the model (including the background)
  857. weights_backbone (:class:`~torchvision.models.MobileNet_V3_Large_Weights`, optional): The
  858. pretrained weights for the backbone.
  859. trainable_backbone_layers (int, optional): number of trainable (not frozen) layers starting from
  860. final block. Valid values are between 0 and 6, with 6 meaning all backbone layers are
  861. trainable. If ``None`` is passed (the default) this value is set to 3.
  862. **kwargs: parameters passed to the ``torchvision.models.detection.faster_rcnn.FasterRCNN``
  863. base class. Please refer to the `source code
  864. <https://github.com/pytorch/vision/blob/main/torchvision/models/detection/faster_rcnn.py>`_
  865. for more details about this class.
  866. .. autoclass:: torchvision.models.detection.FasterRCNN_MobileNet_V3_Large_FPN_Weights
  867. :members:
  868. """
  869. weights = LineNet_MobileNet_V3_Large_FPN_Weights.verify(weights)
  870. weights_backbone = MobileNet_V3_Large_Weights.verify(weights_backbone)
  871. defaults = {
  872. "rpn_score_thresh": 0.05,
  873. }
  874. kwargs = {**defaults, **kwargs}
  875. return _linenet_mobilenet_v3_large_fpn(
  876. weights=weights,
  877. progress=progress,
  878. num_classes=num_classes,
  879. weights_backbone=weights_backbone,
  880. trainable_backbone_layers=trainable_backbone_layers,
  881. **kwargs,
  882. )