Esempio n. 1
0
def keypointrcnn_resnet50_fpn(pretrained=False, progress=True,
                              num_classes=2, num_keypoints=17,
                              pretrained_backbone=True, **kwargs):
    """
    Constructs a Keypoint R-CNN model with a ResNet-50-FPN backbone.

    The input to the model is expected to be a list of tensors, each of shape ``[C, H, W]``, one for each
    image, and should be in ``0-1`` range. Different images can have different sizes.

    The behavior of the model changes depending if it is in training or evaluation mode.

    During training, the model expects both the input tensors, as well as a targets (list of dictionary),
    containing:
        - boxes (``FloatTensor[N, 4]``): the ground-truth boxes in ``[x1, y1, x2, y2]`` format, with values of ``x``
          between ``0`` and ``W`` and values of ``y`` between ``0`` and ``H``
        - labels (``Int64Tensor[N]``): the class label for each ground-truth box
        - keypoints (``FloatTensor[N, K, 3]``): the ``K`` keypoints location for each of the ``N`` instances, in the
          format ``[x, y, visibility]``, where ``visibility=0`` means that the keypoint is not visible.

    The model returns a ``Dict[Tensor]`` during training, containing the classification and regression
    losses for both the RPN and the R-CNN, and the keypoint loss.

    During inference, the model requires only the input tensors, and returns the post-processed
    predictions as a ``List[Dict[Tensor]]``, one for each input image. The fields of the ``Dict`` are as
    follows:
        - boxes (``FloatTensor[N, 4]``): the predicted boxes in ``[x1, y1, x2, y2]`` format,  with values of ``x``
          between ``0`` and ``W`` and values of ``y`` between ``0`` and ``H``
        - labels (``Int64Tensor[N]``): the predicted labels for each image
        - scores (``Tensor[N]``): the scores or each prediction
        - keypoints (``FloatTensor[N, K, 3]``): the locations of the predicted keypoints, in ``[x, y, v]`` format.

    Keypoint R-CNN is exportable to ONNX for a fixed batch size with inputs images of fixed size.

    Example::

        >>> model = torchvision.models.detection.keypointrcnn_resnet50_fpn(pretrained=True)
        >>> model.eval()
        >>> x = [torch.rand(3, 300, 400), torch.rand(3, 500, 400)]
        >>> predictions = model(x)
        >>>
        >>> # optionally, if you want to export the model to ONNX:
        >>> torch.onnx.export(model, x, "keypoint_rcnn.onnx", opset_version = 11)

    Arguments:
        pretrained (bool): If True, returns a model pre-trained on COCO train2017
        progress (bool): If True, displays a progress bar of the download to stderr
    """
    if pretrained:
        # no need to download the backbone if pretrained is set
        pretrained_backbone = False
    backbone = resnet_fpn_backbone('resnet50', pretrained_backbone)
    model = KeypointRCNN(backbone, num_classes, num_keypoints=num_keypoints, **kwargs)
    if pretrained:
        key = 'keypointrcnn_resnet50_fpn_coco'
        if pretrained == 'legacy':
            key += '_legacy'
        state_dict = load_state_dict_from_url(model_urls[key],
                                              progress=progress)
        model.load_state_dict(state_dict)
    return model
Esempio n. 2
0
def fasterrcnn_resnet8_fpn(num_classes=91,
                           pretrained_backbone=True,
                           weight_loss=False,
                           detection_score_thres=0.05,
                           use_soft_nms=False,
                           nms_thres=0.4,
                           anchor_sizes=[32, 64, 128, 256, 512],
                           n_channel_backbone=5,
                           use_context=False,
                           use_track_branch=False,
                           **kwargs):

    backbone = resnet_fpn_backbone('resnet8',
                                   pretrained_backbone,
                                   n_channel_backbone,
                                   first_layer_out='layer1')

    model = FasterRCNN(backbone,
                       num_classes=num_classes,
                       use_soft_nms=use_soft_nms,
                       n_channel_backbone=n_channel_backbone,
                       weight_loss=weight_loss,
                       box_score_thresh=detection_score_thres,
                       use_context=use_context,
                       use_track_branch=use_track_branch,
                       **kwargs)
    return model
Esempio n. 3
0
def get_model(num_classes, device="cuda:0"):

    # 加载backbone时不需要加载官方模型
    backbone = resnet_fpn_backbone('resnet50',
                                   pretrained=False,
                                   trainable_layers=3)
    model = FasterRCNN(backbone, num_classes=91)  # 加载官方模型,这里num_classes不能修改

    # 加载fasterrcnn_resnet50_fpn官方模型
    # https://download.pytorch.org/models/fasterrcnn_resnet50_fpn_coco-258fb6c6.pth
    weights_dict = torch.load(
        "C:/Users/lixiao/.cache/torch/hub/checkpoints/fasterrcnn_resnet50_fpn_coco-258fb6c6.pth",
        map_location=device)
    missing_keys, unexpected_keys = model.load_state_dict(weights_dict,
                                                          strict=False)
    overwrite_eps(model, 0.0)

    if len(missing_keys) != 0 or len(unexpected_keys) != 0:
        print("missing_keys: ", missing_keys)
        print("unexpected_keys: ", unexpected_keys)

    # get number of input features for the classifier
    in_features = model.roi_heads.box_predictor.cls_score.in_features
    # replace the pre-trained head with a new one
    model.roi_heads.box_predictor = FastRCNNPredictor(
        in_features, num_classes)  # 修改predictor

    return model
Esempio n. 4
0
def get_model(num_classes, device="cuda:0"):

    # # https://download.pytorch.org/models/vgg16-397923af.pth
    # # 如果使用mobilenetv2的话就下载对应预训练权重并注释下面三行,接着把mobilenetv2模型对应的两行代码注释取消掉
    # vgg_feature = vgg(model_name="vgg16", weights_path="./backbone/vgg16.pth").features
    # backbone = torch.nn.Sequential(*list(vgg_feature._modules.values())[:-1])  # 删除feature中最后的maxpool层
    # backbone.out_channels = 512

    # # https://download.pytorch.org/models/mobilenet_v2-b0353104.pth
    # # backbone = MobileNetV2(weights_path="./backbone/mobilenet_v2.pth").features
    # # backbone.out_channels = 1280  # 设置对应backbone输出特征矩阵的channels

    # anchor_generator = AnchorGenerator(sizes=((32, 64, 128, 256, 512),),
    #                                     aspect_ratios=((0.5, 1.0, 2.0),))

    # roi_pooler = torchvision.ops.MultiScaleRoIAlign(featmap_names=['0'],  # 在哪些特征层上进行roi pooling
    #                                                 output_size=[7, 7],   # roi_pooling输出特征矩阵尺寸
    #                                                 sampling_ratio=2)  # 采样率

    # model = FasterRCNN(backbone=backbone,
    #                    num_classes=num_classes,
    #                    rpn_anchor_generator=anchor_generator,
    #                    box_roi_pool=roi_pooler)

    # 加载backbone时不需要加载官方模型
    backbone = resnet_fpn_backbone('resnet50',
                                   pretrained=False,
                                   trainable_layers=3)
    model = FasterRCNN(backbone, num_classes=91)  # 加载官方模型,这里num_classes不能修改

    # 加载fasterrcnn_resnet50_fpn官方模型
    # https://download.pytorch.org/models/fasterrcnn_resnet50_fpn_coco-258fb6c6.pth
    weights_dict = torch.load(
        "C:/Users/lixiao/.cache/torch/hub/checkpoints/fasterrcnn_resnet50_fpn_coco-258fb6c6.pth",
        map_location=device)
    missing_keys, unexpected_keys = model.load_state_dict(weights_dict,
                                                          strict=False)
    overwrite_eps(model, 0.0)

    if len(missing_keys) != 0 or len(unexpected_keys) != 0:
        print("missing_keys: ", missing_keys)
        print("unexpected_keys: ", unexpected_keys)

    # get number of input features for the classifier
    in_features = model.roi_heads.box_predictor.cls_score.in_features
    # replace the pre-trained head with a new one
    model.roi_heads.box_predictor = FastRCNNPredictor(
        in_features, num_classes)  # 修改predictor

    return model
Esempio n. 5
0
def fasterrcnn_resnet50_fpn(pretrained=False, progress=True,
                            num_classes=91, pretrained_backbone=True, **kwargs):
    """
    Constructs a Faster R-CNN model with a ResNet-50-FPN backbone.

    The input to the model is expected to be a list of tensors, each of shape ``[C, H, W]``, one for each
    image, and should be in ``0-1`` range. Different images can have different sizes.

    The behavior of the model changes depending if it is in training or evaluation mode.

    During training, the model expects both the input tensors, as well as a targets (list of dictionary),
    containing:
        - boxes (``FloatTensor[N, 4]``): the ground-truth boxes in ``[x1, y1, x2, y2]`` format, with values
          between ``0`` and ``H`` and ``0`` and ``W``
        - labels (``Int64Tensor[N]``): the class label for each ground-truth box

    The model returns a ``Dict[Tensor]`` during training, containing the classification and regression
    losses for both the RPN and the R-CNN.

    During inference, the model requires only the input tensors, and returns the post-processed
    predictions as a ``List[Dict[Tensor]]``, one for each input image. The fields of the ``Dict`` are as
    follows:
        - boxes (``FloatTensor[N, 4]``): the predicted boxes in ``[x1, y1, x2, y2]`` format, with values between
          ``0`` and ``H`` and ``0`` and ``W``
        - labels (``Int64Tensor[N]``): the predicted labels for each image
        - scores (``Tensor[N]``): the scores or each prediction

    Example::

        >>> model = torchvision.models.detection.fasterrcnn_resnet50_fpn(pretrained=True)
        >>> model.eval()
        >>> x = [torch.rand(3, 300, 400), torch.rand(3, 500, 400)]
        >>> predictions = model(x)

    Arguments:
        pretrained (bool): If True, returns a model pre-trained on COCO train2017
        progress (bool): If True, displays a progress bar of the download to stderr
    """
    if pretrained:
        # no need to download the backbone if pretrained is set
        pretrained_backbone = False
    backbone = resnet_fpn_backbone('resnet50', pretrained_backbone)
    model = FasterRCNN(backbone, num_classes, **kwargs)
    if pretrained:
        state_dict = load_state_dict_from_url(model_urls['fasterrcnn_resnet50_fpn_coco'],
                                              progress=progress)
        model.load_state_dict(state_dict)
    return model
Esempio n. 6
0
def newrcnn_resnet50_fpn(pretrained=False,
                         progress=True,
                         weights=None,
                         num_classes=2,
                         num_keypoints=17,
                         pretrained_backbone=True,
                         **kwargs):
    if pretrained:
        # no need to download the backbone if pretrained is set
        pretrained_backbone = False
    backbone = resnet_fpn_backbone('resnet50', pretrained_backbone)
    model = NewRCNN(backbone, num_classes, **kwargs)
    if pretrained:
        # state_dict = load_state_dict_from_url(model_urls['maskrcnn_resnet50_fpn_coco'],
        #                                              progress=progress)
        #weight_path = "new_rcnn_resnet50_fpn.pth"
        weight_path = "weight/newrcnn.pth"
        if weights is not None:
            weight_path = "../weight/" + weights
        state_dict = torch.load(weight_path)
        model.load_state_dict(state_dict)
    return model
Esempio n. 7
0
def fasterrcnn_resnet50_fpn(pretrained=False,
                            num_classes=91,
                            pretrained_backbone=True,
                            weight_loss=False,
                            detection_score_thres=0.05,
                            use_soft_nms=False,
                            nms_thres=0.4,
                            anchor_sizes=[32, 64, 128, 256, 512],
                            n_channel_backbone=5,
                            use_context=False,
                            use_track_branch=False,
                            **kwargs):

    backbone = resnet_fpn_backbone('resnet50',
                                   pretrained_backbone,
                                   n_channel_backbone,
                                   first_layer_out='layer1')
    if pretrained:
        model = FasterRCNN(backbone,
                           num_classes=91,
                           weight_loss=weight_loss,
                           box_score_thresh=detection_score_thres,
                           use_soft_nms=use_soft_nms,
                           box_nms_thresh=nms_thres,
                           **kwargs)
        state_dict = load_state_dict_from_url(
            model_urls['fasterrcnn_resnet50_fpn_coco'], progress=True)
        model.load_state_dict(state_dict)
    else:
        model = FasterRCNN(backbone,
                           num_classes=num_classes,
                           box_score_thresh=detection_score_thres,
                           anchor_sizes=anchor_sizes,
                           weight_loss=weight_loss,
                           use_soft_nms=use_soft_nms,
                           use_context=use_context,
                           use_track_branch=use_track_branch,
                           **kwargs)
    return model
Esempio n. 8
0
def fasterrcnn_resnet50_fpn(pretrained=False,
                            progress=True,
                            num_classes=91,
                            pretrained_backbone=True,
                            trainable_backbone_layers=None,
                            **kwargs):
    """
    Constructs a Faster R-CNN model with a ResNet-50-FPN backbone.
    The input to the model is expected to be a list of tensors, each of shape ``[C, H, W]``, one for each
    image, and should be in ``0-1`` range. Different images can have different sizes.
    The behavior of the model changes depending if it is in training or evaluation mode.
    During training, the model expects both the input tensors, as well as a targets (list of dictionary),
    containing:
        - boxes (``FloatTensor[N, 4]``): the ground-truth boxes in ``[x1, y1, x2, y2]`` format, with
          ``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``.
        - labels (``Int64Tensor[N]``): the class label for each ground-truth box
    The model returns a ``Dict[Tensor]`` during training, containing the classification and regression
    losses for both the RPN and the R-CNN.
    During inference, the model requires only the input tensors, and returns the post-processed
    predictions as a ``List[Dict[Tensor]]``, one for each input image. The fields of the ``Dict`` are as
    follows:
        - boxes (``FloatTensor[N, 4]``): the predicted boxes in ``[x1, y1, x2, y2]`` format, with
          ``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``.
        - labels (``Int64Tensor[N]``): the predicted labels for each image
        - scores (``Tensor[N]``): the scores or each prediction
    Faster R-CNN is exportable to ONNX for a fixed batch size with inputs images of fixed size.
    Example::
        >>> model = torchvision.models.detection.fasterrcnn_resnet50_fpn(pretrained=True)
        >>> # For training
        >>> images, boxes = torch.rand(4, 3, 600, 1200), torch.rand(4, 11, 4)
        >>> labels = torch.randint(1, 91, (4, 11))
        >>> images = list(image for image in images)
        >>> targets = []
        >>> for i in range(len(images)):
        >>>     d = {}
        >>>     d['boxes'] = boxes[i]
        >>>     d['labels'] = labels[i]
        >>>     targets.append(d)
        >>> output = model(images, targets)
        >>> # For inference
        >>> model.eval()
        >>> x = [torch.rand(3, 300, 400), torch.rand(3, 500, 400)]
        >>> predictions = model(x)
        >>>
        >>> # optionally, if you want to export the model to ONNX:
        >>> torch.onnx.export(model, x, "faster_rcnn.onnx", opset_version = 11)
    Args:
        pretrained (bool): If True, returns a model pre-trained on COCO train2017
        progress (bool): If True, displays a progress bar of the download to stderr
        num_classes (int): number of output classes of the model (including the background)
        pretrained_backbone (bool): If True, returns a model with backbone pre-trained on Imagenet
        trainable_backbone_layers (int): number of trainable (not frozen) resnet layers starting from final block.
            Valid values are between 0 and 5, with 5 meaning all backbone layers are trainable.
    """
    trainable_backbone_layers = _validate_trainable_layers(
        pretrained or pretrained_backbone, trainable_backbone_layers, 5, 3)

    if pretrained:
        # no need to download the backbone if pretrained is set
        pretrained_backbone = False
    backbone = resnet_fpn_backbone('resnet50',
                                   pretrained_backbone,
                                   trainable_layers=trainable_backbone_layers)
    model = FasterRCNN(backbone, num_classes, **kwargs)
    if pretrained:
        state_dict = load_state_dict_from_url(
            model_urls['fasterrcnn_resnet50_fpn_coco'], progress=progress)
        model.load_state_dict(state_dict)
        overwrite_eps(model, 0.0)
    return model