line_detect.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  1. import os
  2. from typing import Any, Callable, List, Optional, Tuple, Union
  3. import torch
  4. from torch import nn
  5. from libs.vision_libs import ops
  6. from libs.vision_libs.models import MobileNet_V3_Large_Weights, mobilenet_v3_large, EfficientNet_V2_S_Weights, \
  7. efficientnet_v2_s, detection, EfficientNet_V2_L_Weights, efficientnet_v2_l, EfficientNet_V2_M_Weights, \
  8. efficientnet_v2_m
  9. from libs.vision_libs.models.detection.anchor_utils import AnchorGenerator
  10. from libs.vision_libs.models.detection.rpn import RPNHead, RegionProposalNetwork
  11. from libs.vision_libs.models.detection.ssdlite import _mobilenet_extractor
  12. from libs.vision_libs.models.detection.transform import GeneralizedRCNNTransform
  13. from libs.vision_libs.ops import misc as misc_nn_ops, MultiScaleRoIAlign
  14. from libs.vision_libs.transforms._presets import ObjectDetection
  15. from .line_head import LineRCNNHeads
  16. from .line_predictor import LineRCNNPredictor
  17. from libs.vision_libs.models._api import register_model, Weights, WeightsEnum
  18. from libs.vision_libs.models._meta import _COCO_PERSON_CATEGORIES, _COCO_PERSON_KEYPOINT_NAMES, _COCO_CATEGORIES
  19. from libs.vision_libs.models._utils import _ovewrite_value_param, handle_legacy_interface
  20. from libs.vision_libs.models.resnet import resnet50, ResNet50_Weights, ResNet18_Weights, resnet18
  21. from libs.vision_libs.models.detection._utils import overwrite_eps
  22. from libs.vision_libs.models.detection.backbone_utils import _resnet_fpn_extractor, _validate_trainable_layers, \
  23. BackboneWithFPN
  24. from libs.vision_libs.models.detection.faster_rcnn import FasterRCNN, TwoMLPHead, FastRCNNPredictor
  25. from .roi_heads import RoIHeads
  26. from .trainer import Trainer
  27. from ..base import backbone_factory
  28. from ..base.backbone_factory import get_convnext_fpn, get_anchor_generator
  29. # from ..base.backbone_factory import get_convnext_fpn, get_anchor_generator
  30. from ..base.base_detection_net import BaseDetectionNet
  31. import torch.nn.functional as F
  32. from .predict import Predict1, Predict
  33. from ..base.high_reso_resnet import resnet50fpn, resnet18fpn
  34. __all__ = [
  35. "LineDetect",
  36. "LineDetect_ResNet50_FPN_Weights",
  37. "linedetect_resnet50_fpn",
  38. ]
  39. def _default_anchorgen():
  40. anchor_sizes = ((32,), (64,), (128,), (256,), (512,))
  41. aspect_ratios = ((0.5, 1.0, 2.0),) * len(anchor_sizes)
  42. return AnchorGenerator(anchor_sizes, aspect_ratios)
  43. class LineDetect(BaseDetectionNet):
  44. def __init__(
  45. self,
  46. backbone,
  47. num_classes=None,
  48. # transform parameters
  49. min_size=512,
  50. max_size=1333,
  51. image_mean=None,
  52. image_std=None,
  53. # RPN parameters
  54. rpn_anchor_generator=None,
  55. rpn_head=None,
  56. rpn_pre_nms_top_n_train=2000,
  57. rpn_pre_nms_top_n_test=1000,
  58. rpn_post_nms_top_n_train=2000,
  59. rpn_post_nms_top_n_test=1000,
  60. rpn_nms_thresh=0.7,
  61. rpn_fg_iou_thresh=0.7,
  62. rpn_bg_iou_thresh=0.3,
  63. rpn_batch_size_per_image=256,
  64. rpn_positive_fraction=0.5,
  65. rpn_score_thresh=0.0,
  66. # Box parameters
  67. box_roi_pool=None,
  68. box_head=None,
  69. box_predictor=None,
  70. box_score_thresh=0.05,
  71. box_nms_thresh=0.5,
  72. box_detections_per_img=100,
  73. box_fg_iou_thresh=0.5,
  74. box_bg_iou_thresh=0.5,
  75. box_batch_size_per_image=512,
  76. box_positive_fraction=0.25,
  77. bbox_reg_weights=None,
  78. # keypoint parameters
  79. line_roi_pool=None,
  80. line_head=None,
  81. line_predictor=None,
  82. num_keypoints=None,
  83. **kwargs,
  84. ):
  85. out_channels = backbone.out_channels
  86. if rpn_anchor_generator is None:
  87. rpn_anchor_generator = _default_anchorgen()
  88. if rpn_head is None:
  89. rpn_head = RPNHead(out_channels, rpn_anchor_generator.num_anchors_per_location()[0])
  90. rpn_pre_nms_top_n = dict(training=rpn_pre_nms_top_n_train, testing=rpn_pre_nms_top_n_test)
  91. rpn_post_nms_top_n = dict(training=rpn_post_nms_top_n_train, testing=rpn_post_nms_top_n_test)
  92. rpn = RegionProposalNetwork(
  93. rpn_anchor_generator,
  94. rpn_head,
  95. rpn_fg_iou_thresh,
  96. rpn_bg_iou_thresh,
  97. rpn_batch_size_per_image,
  98. rpn_positive_fraction,
  99. rpn_pre_nms_top_n,
  100. rpn_post_nms_top_n,
  101. rpn_nms_thresh,
  102. score_thresh=rpn_score_thresh,
  103. )
  104. if box_roi_pool is None:
  105. box_roi_pool = MultiScaleRoIAlign(featmap_names=["0", "1", "2", "3"], output_size=7, sampling_ratio=2)
  106. if box_head is None:
  107. resolution = box_roi_pool.output_size[0]
  108. representation_size = 1024
  109. box_head = TwoMLPHead(out_channels * resolution**2, representation_size)
  110. if box_predictor is None:
  111. representation_size = 1024
  112. box_predictor = ObjectionPredictor(representation_size, num_classes)
  113. roi_heads = RoIHeads(
  114. # Box
  115. box_roi_pool,
  116. box_head,
  117. box_predictor,
  118. box_fg_iou_thresh,
  119. box_bg_iou_thresh,
  120. box_batch_size_per_image,
  121. box_positive_fraction,
  122. bbox_reg_weights,
  123. box_score_thresh,
  124. box_nms_thresh,
  125. box_detections_per_img,
  126. )
  127. if image_mean is None:
  128. image_mean = [0.485, 0.456, 0.406]
  129. if image_std is None:
  130. image_std = [0.229, 0.224, 0.225]
  131. transform = GeneralizedRCNNTransform(min_size, max_size, image_mean, image_std, **kwargs)
  132. super().__init__(backbone, rpn, roi_heads, transform)
  133. if not isinstance(line_roi_pool, (MultiScaleRoIAlign, type(None))):
  134. raise TypeError(
  135. "keypoint_roi_pool should be of type MultiScaleRoIAlign or None instead of {type(keypoint_roi_pool)}"
  136. )
  137. if min_size is None:
  138. min_size = (640, 672, 704, 736, 768, 800)
  139. if num_keypoints is not None:
  140. if line_predictor is not None:
  141. raise ValueError("num_keypoints should be None when keypoint_predictor is specified")
  142. else:
  143. num_keypoints = 2
  144. if line_roi_pool is None:
  145. line_roi_pool = MultiScaleRoIAlign(featmap_names=["0", "1", "2", "3"], output_size=14, sampling_ratio=2)
  146. if line_head is None:
  147. keypoint_layers = tuple(512 for _ in range(8))
  148. line_head = LineHeads(out_channels, keypoint_layers)
  149. if line_predictor is None:
  150. keypoint_dim_reduced = 512 # == keypoint_layers[-1]
  151. line_predictor = LinePredictor(keypoint_dim_reduced, num_keypoints)
  152. self.roi_heads.keypoint_roi_pool = line_roi_pool
  153. self.roi_heads.keypoint_head = line_head
  154. self.roi_heads.keypoint_predictor = line_predictor
  155. class TwoMLPHead(nn.Module):
  156. """
  157. Standard heads for FPN-based models
  158. Args:
  159. in_channels (int): number of input channels
  160. representation_size (int): size of the intermediate representation
  161. """
  162. def __init__(self, in_channels, representation_size):
  163. super().__init__()
  164. self.fc6 = nn.Linear(in_channels, representation_size)
  165. self.fc7 = nn.Linear(representation_size, representation_size)
  166. def forward(self, x):
  167. x = x.flatten(start_dim=1)
  168. x = F.relu(self.fc6(x))
  169. x = F.relu(self.fc7(x))
  170. return x
  171. class ObjectionConvFCHead(nn.Sequential):
  172. def __init__(
  173. self,
  174. input_size: Tuple[int, int, int],
  175. conv_layers: List[int],
  176. fc_layers: List[int],
  177. norm_layer: Optional[Callable[..., nn.Module]] = None,
  178. ):
  179. """
  180. Args:
  181. input_size (Tuple[int, int, int]): the input size in CHW format.
  182. conv_layers (list): feature dimensions of each Convolution layer
  183. fc_layers (list): feature dimensions of each FCN layer
  184. norm_layer (callable, optional): Module specifying the normalization layer to use. Default: None
  185. """
  186. in_channels, in_height, in_width = input_size
  187. blocks = []
  188. previous_channels = in_channels
  189. for current_channels in conv_layers:
  190. blocks.append(misc_nn_ops.Conv2dNormActivation(previous_channels, current_channels, norm_layer=norm_layer))
  191. previous_channels = current_channels
  192. blocks.append(nn.Flatten())
  193. previous_channels = previous_channels * in_height * in_width
  194. for current_channels in fc_layers:
  195. blocks.append(nn.Linear(previous_channels, current_channels))
  196. blocks.append(nn.ReLU(inplace=True))
  197. previous_channels = current_channels
  198. super().__init__(*blocks)
  199. for layer in self.modules():
  200. if isinstance(layer, nn.Conv2d):
  201. nn.init.kaiming_normal_(layer.weight, mode="fan_out", nonlinearity="relu")
  202. if layer.bias is not None:
  203. nn.init.zeros_(layer.bias)
  204. class ObjectionPredictor(nn.Module):
  205. """
  206. Standard classification + bounding box regression layers
  207. for Fast R-CNN.
  208. Args:
  209. in_channels (int): number of input channels
  210. num_classes (int): number of output classes (including background)
  211. """
  212. def __init__(self, in_channels, num_classes):
  213. super().__init__()
  214. self.cls_score = nn.Linear(in_channels, num_classes)
  215. self.bbox_pred = nn.Linear(in_channels, num_classes * 4)
  216. def forward(self, x):
  217. if x.dim() == 4:
  218. torch._assert(
  219. list(x.shape[2:]) == [1, 1],
  220. f"x has the wrong shape, expecting the last two dimensions to be [1,1] instead of {list(x.shape[2:])}",
  221. )
  222. x = x.flatten(start_dim=1)
  223. scores = self.cls_score(x)
  224. bbox_deltas = self.bbox_pred(x)
  225. return scores, bbox_deltas
  226. class LineHeads(nn.Sequential):
  227. def __init__(self, in_channels, layers):
  228. d = []
  229. next_feature = in_channels
  230. for out_channels in layers:
  231. d.append(nn.Conv2d(next_feature, out_channels, 3, stride=1, padding=1))
  232. d.append(nn.ReLU(inplace=True))
  233. next_feature = out_channels
  234. super().__init__(*d)
  235. for m in self.children():
  236. if isinstance(m, nn.Conv2d):
  237. nn.init.kaiming_normal_(m.weight, mode="fan_out", nonlinearity="relu")
  238. nn.init.constant_(m.bias, 0)
  239. class LinePredictor(nn.Module):
  240. def __init__(self, in_channels, num_keypoints):
  241. super().__init__()
  242. input_features = in_channels
  243. deconv_kernel = 4
  244. self.kps_score_lowres = nn.ConvTranspose2d(
  245. input_features,
  246. num_keypoints,
  247. deconv_kernel,
  248. stride=2,
  249. padding=deconv_kernel // 2 - 1,
  250. )
  251. nn.init.kaiming_normal_(self.kps_score_lowres.weight, mode="fan_out", nonlinearity="relu")
  252. nn.init.constant_(self.kps_score_lowres.bias, 0)
  253. self.up_scale = 2
  254. self.out_channels = num_keypoints
  255. def forward(self, x):
  256. x = self.kps_score_lowres(x)
  257. return torch.nn.functional.interpolate(
  258. x, scale_factor=float(self.up_scale), mode="bilinear", align_corners=False, recompute_scale_factor=False
  259. )
  260. _COMMON_META = {
  261. "categories": _COCO_PERSON_CATEGORIES,
  262. "keypoint_names": _COCO_PERSON_KEYPOINT_NAMES,
  263. "min_size": (1, 1),
  264. }
  265. class LineDetect_ResNet50_FPN_Weights(WeightsEnum):
  266. COCO_LEGACY = Weights(
  267. url="https://download.pytorch.org/models/keypointrcnn_resnet50_fpn_coco-9f466800.pth",
  268. transforms=ObjectDetection,
  269. meta={
  270. **_COMMON_META,
  271. "num_params": 59137258,
  272. "recipe": "https://github.com/pytorch/vision/issues/1606",
  273. "_metrics": {
  274. "COCO-val2017": {
  275. "box_map": 50.6,
  276. "kp_map": 61.1,
  277. }
  278. },
  279. "_ops": 133.924,
  280. "_file_size": 226.054,
  281. "_docs": """
  282. These weights were produced by following a similar training recipe as on the paper but use a checkpoint
  283. from an early epoch.
  284. """,
  285. },
  286. )
  287. COCO_V1 = Weights(
  288. url="https://download.pytorch.org/models/keypointrcnn_resnet50_fpn_coco-fc266e95.pth",
  289. transforms=ObjectDetection,
  290. meta={
  291. **_COMMON_META,
  292. "num_params": 59137258,
  293. "recipe": "https://github.com/pytorch/vision/tree/main/references/detection#keypoint-r-cnn",
  294. "_metrics": {
  295. "COCO-val2017": {
  296. "box_map": 54.6,
  297. "kp_map": 65.0,
  298. }
  299. },
  300. "_ops": 137.42,
  301. "_file_size": 226.054,
  302. "_docs": """These weights were produced by following a similar training recipe as on the paper.""",
  303. },
  304. )
  305. DEFAULT = COCO_V1
  306. @register_model()
  307. @handle_legacy_interface(
  308. weights=(
  309. "pretrained",
  310. lambda kwargs: LineDetect_ResNet50_FPN_Weights.COCO_LEGACY
  311. if kwargs["pretrained"] == "legacy"
  312. else LineDetect_ResNet50_FPN_Weights.COCO_V1,
  313. ),
  314. weights_backbone=("pretrained_backbone", ResNet50_Weights.IMAGENET1K_V1),
  315. )
  316. def linedetect_resnet50_fpn(
  317. *,
  318. weights: Optional[LineDetect_ResNet50_FPN_Weights] = None,
  319. progress: bool = True,
  320. num_classes: Optional[int] = None,
  321. num_keypoints: Optional[int] = None,
  322. weights_backbone: Optional[ResNet50_Weights] = ResNet50_Weights.IMAGENET1K_V1,
  323. trainable_backbone_layers: Optional[int] = None,
  324. **kwargs: Any,
  325. ) -> LineDetect:
  326. """
  327. Constructs a Keypoint R-CNN model with a ResNet-50-FPN backbone.
  328. .. betastatus:: detection module
  329. Reference: `Mask R-CNN <https://arxiv.org/abs/1703.06870>`__.
  330. The input to the model is expected to be a list of tensors, each of shape ``[C, H, W]``, one for each
  331. image, and should be in ``0-1`` range. Different images can have different sizes.
  332. The behavior of the model changes depending on if it is in training or evaluation mode.
  333. During training, the model expects both the input tensors and targets (list of dictionary),
  334. containing:
  335. - boxes (``FloatTensor[N, 4]``): the ground-truth boxes in ``[x1, y1, x2, y2]`` format, with
  336. ``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``.
  337. - labels (``Int64Tensor[N]``): the class label for each ground-truth box
  338. - keypoints (``FloatTensor[N, K, 3]``): the ``K`` keypoints location for each of the ``N`` instances, in the
  339. format ``[x, y, visibility]``, where ``visibility=0`` means that the keypoint is not visible.
  340. The model returns a ``Dict[Tensor]`` during training, containing the classification and regression
  341. losses for both the RPN and the R-CNN, and the keypoint loss.
  342. During inference, the model requires only the input tensors, and returns the post-processed
  343. predictions as a ``List[Dict[Tensor]]``, one for each input image. The fields of the ``Dict`` are as
  344. follows, where ``N`` is the number of detected instances:
  345. - boxes (``FloatTensor[N, 4]``): the predicted boxes in ``[x1, y1, x2, y2]`` format, with
  346. ``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``.
  347. - labels (``Int64Tensor[N]``): the predicted labels for each instance
  348. - scores (``Tensor[N]``): the scores or each instance
  349. - keypoints (``FloatTensor[N, K, 3]``): the locations of the predicted keypoints, in ``[x, y, v]`` format.
  350. For more details on the output, you may refer to :ref:`instance_seg_output`.
  351. Keypoint R-CNN is exportable to ONNX for a fixed batch size with inputs images of fixed size.
  352. Example::
  353. >>> model = torchvision.models.detection.linedetect_resnet50_fpn(weights=LineDetect_ResNet50_FPN_Weights.DEFAULT)
  354. >>> model.eval()
  355. >>> x = [torch.rand(3, 300, 400), torch.rand(3, 500, 400)]
  356. >>> predictions = model(x)
  357. >>>
  358. >>> # optionally, if you want to export the model to ONNX:
  359. >>> torch.onnx.export(model, x, "keypoint_rcnn.onnx", opset_version = 11)
  360. Args:
  361. weights (:class:`~torchvision.models.detection.KeypointRCNN_ResNet50_FPN_Weights`, optional): The
  362. pretrained weights to use. See
  363. :class:`~torchvision.models.detection.KeypointRCNN_ResNet50_FPN_Weights`
  364. below for more details, and possible values. By default, no
  365. pre-trained weights are used.
  366. progress (bool): If True, displays a progress bar of the download to stderr
  367. num_classes (int, optional): number of output classes of the model (including the background)
  368. num_keypoints (int, optional): number of keypoints
  369. weights_backbone (:class:`~torchvision.models.ResNet50_Weights`, optional): The
  370. pretrained weights for the backbone.
  371. trainable_backbone_layers (int, optional): number of trainable (not frozen) layers starting from final block.
  372. Valid values are between 0 and 5, with 5 meaning all backbone layers are trainable. If ``None`` is
  373. passed (the default) this value is set to 3.
  374. .. autoclass:: torchvision.models.detection.KeypointRCNN_ResNet50_FPN_Weights
  375. :members:
  376. """
  377. weights = LineDetect_ResNet50_FPN_Weights.verify(weights)
  378. weights_backbone = ResNet50_Weights.verify(weights_backbone)
  379. if weights is not None:
  380. weights_backbone = None
  381. num_classes = _ovewrite_value_param("num_classes", num_classes, len(weights.meta["categories"]))
  382. num_keypoints = _ovewrite_value_param("num_keypoints", num_keypoints, len(weights.meta["keypoint_names"]))
  383. else:
  384. if num_classes is None:
  385. num_classes = 2
  386. if num_keypoints is None:
  387. num_keypoints = 17
  388. is_trained = weights is not None or weights_backbone is not None
  389. trainable_backbone_layers = _validate_trainable_layers(is_trained, trainable_backbone_layers, 5, 3)
  390. norm_layer = misc_nn_ops.FrozenBatchNorm2d if is_trained else nn.BatchNorm2d
  391. backbone = resnet50(weights=weights_backbone, progress=progress, norm_layer=norm_layer)
  392. backbone = _resnet_fpn_extractor(backbone, trainable_backbone_layers)
  393. model = LineDetect(backbone, num_classes, num_keypoints=num_keypoints, **kwargs)
  394. if weights is not None:
  395. model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True))
  396. if weights == LineDetect_ResNet50_FPN_Weights.COCO_V1:
  397. overwrite_eps(model, 0.0)
  398. return model