wirenet_rcnn.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617
  1. import os
  2. from typing import Optional, Any
  3. import cv2
  4. import numpy as np
  5. import torch
  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, WeightsEnum, Weights, resnet18, ResNet18_Weights
  11. from torchvision.models._api import register_model
  12. from torchvision.models._utils import handle_legacy_interface, _ovewrite_value_param
  13. from torchvision.models.detection import FasterRCNN, MaskRCNN_ResNet50_FPN_V2_Weights
  14. from torchvision.models.detection._utils import overwrite_eps
  15. from torchvision.models.detection.backbone_utils import _resnet_fpn_extractor, _validate_trainable_layers
  16. from torchvision.models._meta import _COCO_PERSON_CATEGORIES, _COCO_PERSON_KEYPOINT_NAMES
  17. from torchvision.ops import MultiScaleRoIAlign
  18. from torchvision.ops import misc as misc_nn_ops
  19. __all__ = [
  20. "WirenetRCNN",
  21. "WirenetRCNN_ResNet50_FPN_Weights",
  22. "wirenetrcnn_resnet50_fpn",
  23. ]
  24. from torchvision.transforms._presets import ObjectDetection
  25. class WirenetRCNN(FasterRCNN):
  26. """
  27. Implements Keypoint R-CNN.
  28. The input to the model is expected to be a list of tensors, each of shape [C, H, W], one for each
  29. image, and should be in 0-1 range. Different images can have different sizes.
  30. The behavior of the model changes depending on if it is in training or evaluation mode.
  31. During training, the model expects both the input tensors and targets (list of dictionary),
  32. containing:
  33. - boxes (``FloatTensor[N, 4]``): the ground-truth boxes in ``[x1, y1, x2, y2]`` format, with
  34. ``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``.
  35. - labels (Int64Tensor[N]): the class label for each ground-truth box
  36. - keypoints (FloatTensor[N, K, 3]): the K keypoints location for each of the N instances, in the
  37. format [x, y, visibility], where visibility=0 means that the keypoint is not visible.
  38. The model returns a Dict[Tensor] during training, containing the classification and regression
  39. losses for both the RPN and the R-CNN, and the keypoint loss.
  40. During inference, the model requires only the input tensors, and returns the post-processed
  41. predictions as a List[Dict[Tensor]], one for each input image. The fields of the Dict are as
  42. follows:
  43. - boxes (``FloatTensor[N, 4]``): the predicted boxes in ``[x1, y1, x2, y2]`` format, with
  44. ``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``.
  45. - labels (Int64Tensor[N]): the predicted labels for each image
  46. - scores (Tensor[N]): the scores or each prediction
  47. - keypoints (FloatTensor[N, K, 3]): the locations of the predicted keypoints, in [x, y, v] format.
  48. Args:
  49. backbone (nn.Module): the network used to compute the features for the model.
  50. It should contain an out_channels attribute, which indicates the number of output
  51. channels that each feature map has (and it should be the same for all feature maps).
  52. The backbone should return a single Tensor or and OrderedDict[Tensor].
  53. num_classes (int): number of output classes of the model (including the background).
  54. If box_predictor is specified, num_classes should be None.
  55. min_size (int): minimum size of the image to be rescaled before feeding it to the backbone
  56. max_size (int): maximum size of the image to be rescaled before feeding it to the backbone
  57. image_mean (Tuple[float, float, float]): mean values used for input normalization.
  58. They are generally the mean values of the dataset on which the backbone has been trained
  59. on
  60. image_std (Tuple[float, float, float]): std values used for input normalization.
  61. They are generally the std values of the dataset on which the backbone has been trained on
  62. rpn_anchor_generator (AnchorGenerator): module that generates the anchors for a set of feature
  63. maps.
  64. rpn_head (nn.Module): module that computes the objectness and regression deltas from the RPN
  65. rpn_pre_nms_top_n_train (int): number of proposals to keep before applying NMS during training
  66. rpn_pre_nms_top_n_test (int): number of proposals to keep before applying NMS during testing
  67. rpn_post_nms_top_n_train (int): number of proposals to keep after applying NMS during training
  68. rpn_post_nms_top_n_test (int): number of proposals to keep after applying NMS during testing
  69. rpn_nms_thresh (float): NMS threshold used for postprocessing the RPN proposals
  70. rpn_fg_iou_thresh (float): minimum IoU between the anchor and the GT box so that they can be
  71. considered as positive during training of the RPN.
  72. rpn_bg_iou_thresh (float): maximum IoU between the anchor and the GT box so that they can be
  73. considered as negative during training of the RPN.
  74. rpn_batch_size_per_image (int): number of anchors that are sampled during training of the RPN
  75. for computing the loss
  76. rpn_positive_fraction (float): proportion of positive anchors in a mini-batch during training
  77. of the RPN
  78. rpn_score_thresh (float): during inference, only return proposals with a classification score
  79. greater than rpn_score_thresh
  80. box_roi_pool (MultiScaleRoIAlign): the module which crops and resizes the feature maps in
  81. the locations indicated by the bounding boxes
  82. box_head (nn.Module): module that takes the cropped feature maps as input
  83. box_predictor (nn.Module): module that takes the output of box_head and returns the
  84. classification logits and box regression deltas.
  85. box_score_thresh (float): during inference, only return proposals with a classification score
  86. greater than box_score_thresh
  87. box_nms_thresh (float): NMS threshold for the prediction head. Used during inference
  88. box_detections_per_img (int): maximum number of detections per image, for all classes.
  89. box_fg_iou_thresh (float): minimum IoU between the proposals and the GT box so that they can be
  90. considered as positive during training of the classification head
  91. box_bg_iou_thresh (float): maximum IoU between the proposals and the GT box so that they can be
  92. considered as negative during training of the classification head
  93. box_batch_size_per_image (int): number of proposals that are sampled during training of the
  94. classification head
  95. box_positive_fraction (float): proportion of positive proposals in a mini-batch during training
  96. of the classification head
  97. bbox_reg_weights (Tuple[float, float, float, float]): weights for the encoding/decoding of the
  98. bounding boxes
  99. wirenet_roi_pool (MultiScaleRoIAlign): the module which crops and resizes the feature maps in
  100. the locations indicated by the bounding boxes, which will be used for the keypoint head.
  101. wirenet_head (nn.Module): module that takes the cropped feature maps as input
  102. wirenet_predictor (nn.Module): module that takes the output of the keypoint_head and returns the
  103. heatmap logits
  104. Example::
  105. >>> import torch
  106. >>> import torchvision
  107. >>> from torchvision.models.detection import KeypointRCNN
  108. >>> from torchvision.models.detection.anchor_utils import AnchorGenerator
  109. >>>
  110. >>> # load a pre-trained model for classification and return
  111. >>> # only the features
  112. >>> backbone = torchvision.models.mobilenet_v2(weights=MobileNet_V2_Weights.DEFAULT).features
  113. >>> # KeypointRCNN needs to know the number of
  114. >>> # output channels in a backbone. For mobilenet_v2, it's 1280,
  115. >>> # so we need to add it here
  116. >>> backbone.out_channels = 1280
  117. >>>
  118. >>> # let's make the RPN generate 5 x 3 anchors per spatial
  119. >>> # location, with 5 different sizes and 3 different aspect
  120. >>> # ratios. We have a Tuple[Tuple[int]] because each feature
  121. >>> # map could potentially have different sizes and
  122. >>> # aspect ratios
  123. >>> anchor_generator = AnchorGenerator(sizes=((32, 64, 128, 256, 512),),
  124. >>> aspect_ratios=((0.5, 1.0, 2.0),))
  125. >>>
  126. >>> # let's define what are the feature maps that we will
  127. >>> # use to perform the region of interest cropping, as well as
  128. >>> # the size of the crop after rescaling.
  129. >>> # if your backbone returns a Tensor, featmap_names is expected to
  130. >>> # be ['0']. More generally, the backbone should return an
  131. >>> # OrderedDict[Tensor], and in featmap_names you can choose which
  132. >>> # feature maps to use.
  133. >>> roi_pooler = torchvision.ops.MultiScaleRoIAlign(featmap_names=['0'],
  134. >>> output_size=7,
  135. >>> sampling_ratio=2)
  136. >>>
  137. >>> keypoint_roi_pooler = torchvision.ops.MultiScaleRoIAlign(featmap_names=['0'],
  138. >>> output_size=14,
  139. >>> sampling_ratio=2)
  140. >>> # put the pieces together inside a KeypointRCNN model
  141. >>> model = KeypointRCNN(backbone,
  142. >>> num_classes=2,
  143. >>> rpn_anchor_generator=anchor_generator,
  144. >>> box_roi_pool=roi_pooler,
  145. >>> keypoint_roi_pool=keypoint_roi_pooler)
  146. >>> model.eval()
  147. >>> model.eval()
  148. >>> x = [torch.rand(3, 300, 400), torch.rand(3, 500, 400)]
  149. >>> predictions = model(x)
  150. """
  151. def __init__(
  152. self,
  153. backbone,
  154. num_classes=None,
  155. # transform parameters
  156. min_size=512,
  157. max_size=1333,
  158. image_mean=None,
  159. image_std=None,
  160. # RPN parameters
  161. rpn_anchor_generator=None,
  162. rpn_head=None,
  163. rpn_pre_nms_top_n_train=2000,
  164. rpn_pre_nms_top_n_test=1000,
  165. rpn_post_nms_top_n_train=2000,
  166. rpn_post_nms_top_n_test=1000,
  167. rpn_nms_thresh=0.7,
  168. rpn_fg_iou_thresh=0.7,
  169. rpn_bg_iou_thresh=0.3,
  170. rpn_batch_size_per_image=256,
  171. rpn_positive_fraction=0.5,
  172. rpn_score_thresh=0.0,
  173. # Box parameters
  174. box_roi_pool=None,
  175. box_head=None,
  176. box_predictor=None,
  177. box_score_thresh=0.05,
  178. box_nms_thresh=0.5,
  179. box_detections_per_img=100,
  180. box_fg_iou_thresh=0.5,
  181. box_bg_iou_thresh=0.5,
  182. box_batch_size_per_image=512,
  183. box_positive_fraction=0.25,
  184. bbox_reg_weights=None,
  185. # keypoint parameters
  186. wirenet_roi_pool=None,
  187. wirenet_head=None,
  188. wirenet_predictor=None,
  189. num_keypoints=None,
  190. **kwargs,
  191. ):
  192. if not isinstance(wirenet_roi_pool, (MultiScaleRoIAlign, type(None))):
  193. raise TypeError(
  194. "keypoint_roi_pool should be of type MultiScaleRoIAlign or None instead of {type(keypoint_roi_pool)}"
  195. )
  196. if min_size is None:
  197. min_size = (640, 672, 704, 736, 768, 800)
  198. if num_keypoints is not None:
  199. if wirenet_predictor is not None:
  200. raise ValueError("num_keypoints should be None when keypoint_predictor is specified")
  201. else:
  202. num_keypoints = 2
  203. out_channels = backbone.out_channels
  204. if wirenet_roi_pool is None:
  205. wirenet_roi_pool = MultiScaleRoIAlign(featmap_names=["0", "1", "2", "3"], output_size=14, sampling_ratio=2)
  206. if wirenet_head is None:
  207. keypoint_layers = tuple(512 for _ in range(8))
  208. wirenet_head = WirenetRCNNHeads(out_channels, keypoint_layers)
  209. if wirenet_predictor is None:
  210. keypoint_dim_reduced = 512 # == keypoint_layers[-1]
  211. wirenet_predictor = WirenetRCNNPredictor(keypoint_dim_reduced, num_keypoints)
  212. super().__init__(
  213. backbone,
  214. num_classes,
  215. # transform parameters
  216. min_size,
  217. max_size,
  218. image_mean,
  219. image_std,
  220. # RPN-specific parameters
  221. rpn_anchor_generator,
  222. rpn_head,
  223. rpn_pre_nms_top_n_train,
  224. rpn_pre_nms_top_n_test,
  225. rpn_post_nms_top_n_train,
  226. rpn_post_nms_top_n_test,
  227. rpn_nms_thresh,
  228. rpn_fg_iou_thresh,
  229. rpn_bg_iou_thresh,
  230. rpn_batch_size_per_image,
  231. rpn_positive_fraction,
  232. rpn_score_thresh,
  233. # Box parameters
  234. box_roi_pool,
  235. box_head,
  236. box_predictor,
  237. box_score_thresh,
  238. box_nms_thresh,
  239. box_detections_per_img,
  240. box_fg_iou_thresh,
  241. box_bg_iou_thresh,
  242. box_batch_size_per_image,
  243. box_positive_fraction,
  244. bbox_reg_weights,
  245. **kwargs,
  246. )
  247. self.roi_heads.keypoint_roi_pool = wirenet_roi_pool
  248. self.roi_heads.keypoint_head = wirenet_head
  249. self.roi_heads.keypoint_predictor = wirenet_predictor
  250. class WirenetRCNNHeads(nn.Module):
  251. def __init__(self, in_channels, layers, num_keypoints=3):
  252. super().__init__()
  253. d = []
  254. next_feature = in_channels
  255. for out_channels in layers:
  256. d.append(nn.Conv2d(next_feature, out_channels, 3, stride=1, padding=1))
  257. d.append(nn.ReLU(inplace=True))
  258. next_feature = out_channels
  259. # super().__init__(*d)
  260. self.feature_layers = nn.Sequential(*d)
  261. for m in self.feature_layers.children():
  262. if isinstance(m, nn.Conv2d):
  263. nn.init.kaiming_normal_(m.weight, mode="fan_out", nonlinearity="relu")
  264. nn.init.constant_(m.bias, 0)
  265. input_features = next_feature
  266. deconv_kernel = 4
  267. self.kps_score_lowres = nn.ConvTranspose2d(
  268. input_features,
  269. num_keypoints,
  270. deconv_kernel,
  271. stride=2,
  272. padding=deconv_kernel // 2 - 1,
  273. )
  274. nn.init.kaiming_normal_(self.kps_score_lowres.weight, mode="fan_out", nonlinearity="relu")
  275. nn.init.constant_(self.kps_score_lowres.bias, 0)
  276. self.up_scale = 2
  277. self.out_channels = num_keypoints
  278. def forward(self, x):
  279. x = self.feature_layers(x)
  280. x = self.kps_score_lowres(x)
  281. return torch.nn.functional.interpolate(
  282. x, scale_factor=float(self.up_scale), mode="bilinear", align_corners=False, recompute_scale_factor=False
  283. )
  284. class WirenetRCNNPredictor(nn.Module):
  285. def __init__(self, in_channels, num_keypoints):
  286. super().__init__()
  287. input_features = in_channels
  288. deconv_kernel = 4
  289. self.kps_score_lowres = nn.ConvTranspose2d(
  290. input_features,
  291. num_keypoints,
  292. deconv_kernel,
  293. stride=2,
  294. padding=deconv_kernel // 2 - 1,
  295. )
  296. nn.init.kaiming_normal_(self.kps_score_lowres.weight, mode="fan_out", nonlinearity="relu")
  297. nn.init.constant_(self.kps_score_lowres.bias, 0)
  298. self.up_scale = 2
  299. self.out_channels = num_keypoints
  300. def forward(self, x):
  301. x = self.kps_score_lowres(x)
  302. x=torch.nn.functional.interpolate(
  303. x, scale_factor=float(self.up_scale), mode="bilinear", align_corners=False, recompute_scale_factor=False
  304. )
  305. print(f'x.shape:{x.shape}')
  306. return x
  307. _COMMON_META = {
  308. "categories": _COCO_PERSON_CATEGORIES,
  309. "keypoint_names": _COCO_PERSON_KEYPOINT_NAMES,
  310. "min_size": (1, 1),
  311. }
  312. class WirenetRCNN_ResNet50_FPN_Weights(WeightsEnum):
  313. COCO_LEGACY = Weights(
  314. url="https://download.pytorch.org/models/keypointrcnn_resnet50_fpn_coco-9f466800.pth",
  315. transforms=ObjectDetection,
  316. meta={
  317. **_COMMON_META,
  318. "num_params": 59137258,
  319. "recipe": "https://github.com/pytorch/vision/issues/1606",
  320. "_metrics": {
  321. "COCO-val2017": {
  322. "box_map": 50.6,
  323. "kp_map": 61.1,
  324. }
  325. },
  326. "_ops": 133.924,
  327. "_file_size": 226.054,
  328. "_docs": """
  329. These weights were produced by following a similar training recipe as on the paper but use a checkpoint
  330. from an early epoch.
  331. """,
  332. },
  333. )
  334. COCO_V1 = Weights(
  335. url="https://download.pytorch.org/models/keypointrcnn_resnet50_fpn_coco-fc266e95.pth",
  336. transforms=ObjectDetection,
  337. meta={
  338. **_COMMON_META,
  339. "num_params": 59137258,
  340. "recipe": "https://github.com/pytorch/vision/tree/main/references/detection#keypoint-r-cnn",
  341. "_metrics": {
  342. "COCO-val2017": {
  343. "box_map": 54.6,
  344. "kp_map": 65.0,
  345. }
  346. },
  347. "_ops": 137.42,
  348. "_file_size": 226.054,
  349. "_docs": """These weights were produced by following a similar training recipe as on the paper.""",
  350. },
  351. )
  352. DEFAULT = COCO_V1
  353. @register_model()
  354. @handle_legacy_interface(
  355. weights=(
  356. "pretrained",
  357. lambda kwargs: WirenetRCNN_ResNet50_FPN_Weights.COCO_LEGACY
  358. if kwargs["pretrained"] == "legacy"
  359. else WirenetRCNN_ResNet50_FPN_Weights.COCO_V1,
  360. ),
  361. weights_backbone=("pretrained_backbone", ResNet50_Weights.IMAGENET1K_V1),
  362. )
  363. def wirenetrcnn_resnet50_fpn(
  364. *,
  365. weights: Optional[WirenetRCNN_ResNet50_FPN_Weights] = None,
  366. progress: bool = True,
  367. num_classes: Optional[int] = None,
  368. num_keypoints: Optional[int] = None,
  369. weights_backbone: Optional[ResNet50_Weights] = ResNet50_Weights.IMAGENET1K_V1,
  370. trainable_backbone_layers: Optional[int] = None,
  371. **kwargs: Any,
  372. ) -> WirenetRCNN:
  373. """
  374. Constructs a Keypoint R-CNN model with a ResNet-50-FPN backbone.
  375. .. betastatus:: detection module
  376. Reference: `Mask R-CNN <https://arxiv.org/abs/1703.06870>`__.
  377. The input to the model is expected to be a list of tensors, each of shape ``[C, H, W]``, one for each
  378. image, and should be in ``0-1`` range. Different images can have different sizes.
  379. The behavior of the model changes depending on if it is in training or evaluation mode.
  380. During training, the model expects both the input tensors and targets (list of dictionary),
  381. containing:
  382. - boxes (``FloatTensor[N, 4]``): the ground-truth boxes in ``[x1, y1, x2, y2]`` format, with
  383. ``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``.
  384. - labels (``Int64Tensor[N]``): the class label for each ground-truth box
  385. - keypoints (``FloatTensor[N, K, 3]``): the ``K`` keypoints location for each of the ``N`` instances, in the
  386. format ``[x, y, visibility]``, where ``visibility=0`` means that the keypoint is not visible.
  387. The model returns a ``Dict[Tensor]`` during training, containing the classification and regression
  388. losses for both the RPN and the R-CNN, and the keypoint loss.
  389. During inference, the model requires only the input tensors, and returns the post-processed
  390. predictions as a ``List[Dict[Tensor]]``, one for each input image. The fields of the ``Dict`` are as
  391. follows, where ``N`` is the number of detected instances:
  392. - boxes (``FloatTensor[N, 4]``): the predicted boxes in ``[x1, y1, x2, y2]`` format, with
  393. ``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``.
  394. - labels (``Int64Tensor[N]``): the predicted labels for each instance
  395. - scores (``Tensor[N]``): the scores or each instance
  396. - keypoints (``FloatTensor[N, K, 3]``): the locations of the predicted keypoints, in ``[x, y, v]`` format.
  397. For more details on the output, you may refer to :ref:`instance_seg_output`.
  398. Keypoint R-CNN is exportable to ONNX for a fixed batch size with inputs images of fixed size.
  399. Example::
  400. >>> model = torchvision.models.detection.keypointrcnn_resnet50_fpn(weights=WirenetRCNN_ResNet50_FPN_Weights.DEFAULT)
  401. >>> model.eval()
  402. >>> x = [torch.rand(3, 300, 400), torch.rand(3, 500, 400)]
  403. >>> predictions = model(x)
  404. >>>
  405. >>> # optionally, if you want to export the model to ONNX:
  406. >>> torch.onnx.export(model, x, "keypoint_rcnn.onnx", opset_version = 11)
  407. Args:
  408. weights (:class:`~torchvision.models.detection.KeypointRCNN_ResNet50_FPN_Weights`, optional): The
  409. pretrained weights to use. See
  410. :class:`~torchvision.models.detection.KeypointRCNN_ResNet50_FPN_Weights`
  411. below for more details, and possible values. By default, no
  412. pre-trained weights are used.
  413. progress (bool): If True, displays a progress bar of the download to stderr
  414. num_classes (int, optional): number of output classes of the model (including the background)
  415. num_keypoints (int, optional): number of keypoints
  416. weights_backbone (:class:`~torchvision.models.ResNet50_Weights`, optional): The
  417. pretrained weights for the backbone.
  418. trainable_backbone_layers (int, optional): number of trainable (not frozen) layers starting from final block.
  419. Valid values are between 0 and 5, with 5 meaning all backbone layers are trainable. If ``None`` is
  420. passed (the default) this value is set to 3.
  421. .. autoclass:: torchvision.models.detection.KeypointRCNN_ResNet50_FPN_Weights
  422. :members:
  423. """
  424. weights = WirenetRCNN_ResNet50_FPN_Weights.verify(weights)
  425. weights_backbone = ResNet50_Weights.verify(weights_backbone)
  426. if weights is not None:
  427. weights_backbone = None
  428. num_classes = _ovewrite_value_param("num_classes", num_classes, len(weights.meta["categories"]))
  429. num_keypoints = _ovewrite_value_param("num_keypoints", num_keypoints, len(weights.meta["keypoint_names"]))
  430. else:
  431. if num_classes is None:
  432. num_classes = 2
  433. if num_keypoints is None:
  434. num_keypoints = 17
  435. is_trained = weights is not None or weights_backbone is not None
  436. trainable_backbone_layers = _validate_trainable_layers(is_trained, trainable_backbone_layers, 5, 3)
  437. norm_layer = misc_nn_ops.FrozenBatchNorm2d if is_trained else nn.BatchNorm2d
  438. backbone = resnet50(weights=weights_backbone, progress=progress, norm_layer=norm_layer)
  439. backbone = _resnet_fpn_extractor(backbone, trainable_backbone_layers)
  440. model = WirenetRCNN(backbone, num_classes, num_keypoints=num_keypoints, **kwargs)
  441. if weights is not None:
  442. model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True))
  443. if weights == WirenetRCNN_ResNet50_FPN_Weights.COCO_V1:
  444. overwrite_eps(model, 0.0)
  445. return model
  446. def wirenetrcnn_resnet18_fpn(
  447. *,
  448. weights: Optional[WirenetRCNN_ResNet50_FPN_Weights] = None,
  449. progress: bool = True,
  450. num_classes: Optional[int] = None,
  451. num_keypoints: Optional[int] = None,
  452. weights_backbone: Optional[ResNet50_Weights] = ResNet50_Weights.IMAGENET1K_V1,
  453. trainable_backbone_layers: Optional[int] = None,
  454. **kwargs: Any,
  455. ) -> WirenetRCNN:
  456. """
  457. Constructs a Keypoint R-CNN model with a ResNet-50-FPN backbone.
  458. .. betastatus:: detection module
  459. Reference: `Mask R-CNN <https://arxiv.org/abs/1703.06870>`__.
  460. The input to the model is expected to be a list of tensors, each of shape ``[C, H, W]``, one for each
  461. image, and should be in ``0-1`` range. Different images can have different sizes.
  462. The behavior of the model changes depending on if it is in training or evaluation mode.
  463. During training, the model expects both the input tensors and targets (list of dictionary),
  464. containing:
  465. - boxes (``FloatTensor[N, 4]``): the ground-truth boxes in ``[x1, y1, x2, y2]`` format, with
  466. ``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``.
  467. - labels (``Int64Tensor[N]``): the class label for each ground-truth box
  468. - keypoints (``FloatTensor[N, K, 3]``): the ``K`` keypoints location for each of the ``N`` instances, in the
  469. format ``[x, y, visibility]``, where ``visibility=0`` means that the keypoint is not visible.
  470. The model returns a ``Dict[Tensor]`` during training, containing the classification and regression
  471. losses for both the RPN and the R-CNN, and the keypoint loss.
  472. During inference, the model requires only the input tensors, and returns the post-processed
  473. predictions as a ``List[Dict[Tensor]]``, one for each input image. The fields of the ``Dict`` are as
  474. follows, where ``N`` is the number of detected instances:
  475. - boxes (``FloatTensor[N, 4]``): the predicted boxes in ``[x1, y1, x2, y2]`` format, with
  476. ``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``.
  477. - labels (``Int64Tensor[N]``): the predicted labels for each instance
  478. - scores (``Tensor[N]``): the scores or each instance
  479. - keypoints (``FloatTensor[N, K, 3]``): the locations of the predicted keypoints, in ``[x, y, v]`` format.
  480. For more details on the output, you may refer to :ref:`instance_seg_output`.
  481. Keypoint R-CNN is exportable to ONNX for a fixed batch size with inputs images of fixed size.
  482. Example::
  483. >>> model = torchvision.models.detection.keypointrcnn_resnet50_fpn(weights=WirenetRCNN_ResNet50_FPN_Weights.DEFAULT)
  484. >>> model.eval()
  485. >>> x = [torch.rand(3, 300, 400), torch.rand(3, 500, 400)]
  486. >>> predictions = model(x)
  487. >>>
  488. >>> # optionally, if you want to export the model to ONNX:
  489. >>> torch.onnx.export(model, x, "keypoint_rcnn.onnx", opset_version = 11)
  490. Args:
  491. weights (:class:`~torchvision.models.detection.KeypointRCNN_ResNet50_FPN_Weights`, optional): The
  492. pretrained weights to use. See
  493. :class:`~torchvision.models.detection.KeypointRCNN_ResNet50_FPN_Weights`
  494. below for more details, and possible values. By default, no
  495. pre-trained weights are used.
  496. progress (bool): If True, displays a progress bar of the download to stderr
  497. num_classes (int, optional): number of output classes of the model (including the background)
  498. num_keypoints (int, optional): number of keypoints
  499. weights_backbone (:class:`~torchvision.models.ResNet50_Weights`, optional): The
  500. pretrained weights for the backbone.
  501. trainable_backbone_layers (int, optional): number of trainable (not frozen) layers starting from final block.
  502. Valid values are between 0 and 5, with 5 meaning all backbone layers are trainable. If ``None`` is
  503. passed (the default) this value is set to 3.
  504. .. autoclass:: torchvision.models.detection.KeypointRCNN_ResNet50_FPN_Weights
  505. :members:
  506. """
  507. weights = WirenetRCNN_ResNet50_FPN_Weights.verify(weights)
  508. weights_backbone = ResNet50_Weights.verify(weights_backbone)
  509. # if weights_backbone is None:
  510. weights_backbone = ResNet18_Weights.IMAGENET1K_V1
  511. if weights is not None:
  512. # weights_backbone = None
  513. num_classes = _ovewrite_value_param("num_classes", num_classes, len(weights.meta["categories"]))
  514. num_keypoints = _ovewrite_value_param("num_keypoints", num_keypoints, len(weights.meta["keypoint_names"]))
  515. else:
  516. if num_classes is None:
  517. num_classes = 3
  518. if num_keypoints is None:
  519. num_keypoints = 17
  520. is_trained = weights is not None or weights_backbone is not None
  521. trainable_backbone_layers = _validate_trainable_layers(is_trained, trainable_backbone_layers, 5, 3)
  522. norm_layer = misc_nn_ops.FrozenBatchNorm2d if is_trained else nn.BatchNorm2d
  523. backbone = resnet18(weights=weights_backbone, progress=progress, norm_layer=norm_layer)
  524. backbone = _resnet_fpn_extractor(backbone, trainable_backbone_layers)
  525. model = WirenetRCNN(backbone, num_classes, num_keypoints=num_keypoints, **kwargs)
  526. if weights is not None:
  527. model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True))
  528. if weights == WirenetRCNN_ResNet50_FPN_Weights.COCO_V1:
  529. overwrite_eps(model, 0.0)
  530. return model
  531. if __name__ == '__main__':
  532. model=wirenetrcnn_resnet18_fpn(num_keypoints=3)
  533. img = torch.ones((3, 3, 512, 512))
  534. model.eval()
  535. model(img)
  536. # model.train(cfg='train.yaml')