當前位置: 首頁>>代碼示例>>Python>>正文


Python mmcv.Config方法代碼示例

本文整理匯總了Python中mmcv.Config方法的典型用法代碼示例。如果您正苦於以下問題:Python mmcv.Config方法的具體用法?Python mmcv.Config怎麽用?Python mmcv.Config使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在mmcv的用法示例。


在下文中一共展示了mmcv.Config方法的14個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: init_model

# 需要導入模塊: import mmcv [as 別名]
# 或者: from mmcv import Config [as 別名]
def init_model(config, checkpoint=None, device='cuda:0'):
    """
    Initialize a stereo model from config file.
    Args:
        config (str or :obj:`mmcv.Config`): Config file path or the config
            object.
        checkpoint (str, optional): Checkpoint path. If left as None, the model
            will not load any weights.
    Returns:
        nn.Module: The constructed stereo model.
    """
    if isinstance(config, str):
        config = mmcv.Config.fromfile(config)
    elif not isinstance(config, mmcv.Config):
        raise TypeError('config must be a filename or Config object, '
                        'but got {}'.format(type(config)))

    model = build_model(config)
    if checkpoint is not None:
        checkpoint = load_checkpoint(model, checkpoint)
    model.cfg = config  # save the config in the model for convenience
    model.to(device)
    model.eval()
    return model 
開發者ID:DeepMotionAIResearch,項目名稱:DenseMatchingBenchmark,代碼行數:26,代碼來源:inference.py

示例2: setUp

# 需要導入模塊: import mmcv [as 別名]
# 或者: from mmcv import Config [as 別名]
def setUp(self):
        config = dict(
            data=dict(
                test=dict(
                    type='KITTI-2015',
                    data_root='datasets/KITTI-2015/',
                    annfile='datasets/KITTI-2015/annotations/full_eval.json',
                    input_shape=[384, 1248],
                    mean=[0.485, 0.456, 0.406],
                    std=[0.229, 0.224, 0.225],
                    toRAM=False,
                )
            )
        )
        cfg = Config(config)
        self.dataset = build_dataset(cfg, 'test')

        import pdb
        pdb.set_trace() 
開發者ID:DeepMotionAIResearch,項目名稱:DenseMatchingBenchmark,代碼行數:21,代碼來源:test_kitti.py

示例3: init_detector

# 需要導入模塊: import mmcv [as 別名]
# 或者: from mmcv import Config [as 別名]
def init_detector(config, checkpoint=None, device='cuda:0'):
    """Initialize a detector from config file.

    Args:
        config (str or :obj:`mmcv.Config`): Config file path or the config
            object.
        checkpoint (str, optional): Checkpoint path. If left as None, the model
            will not load any weights.

    Returns:
        nn.Module: The constructed detector.
    """
    if isinstance(config, str):
        config = mmcv.Config.fromfile(config)
    elif not isinstance(config, mmcv.Config):
        raise TypeError('config must be a filename or Config object, '
                        f'but got {type(config)}')
    config.model.pretrained = None
    model = build_detector(config.model, test_cfg=config.test_cfg)
    if checkpoint is not None:
        checkpoint = load_checkpoint(model, checkpoint)
        if 'CLASSES' in checkpoint['meta']:
            model.CLASSES = checkpoint['meta']['CLASSES']
        else:
            warnings.simplefilter('once')
            warnings.warn('Class names are not saved in the checkpoint\'s '
                          'meta data, use COCO classes by default.')
            model.CLASSES = get_classes('coco')
    model.cfg = config  # save the config in the model for convenience
    model.to(device)
    model.eval()
    return model 
開發者ID:open-mmlab,項目名稱:mmdetection,代碼行數:34,代碼來源:inference.py

示例4: _get_config_module

# 需要導入模塊: import mmcv [as 別名]
# 或者: from mmcv import Config [as 別名]
def _get_config_module(fname):
    """Load a configuration as a python module."""
    from mmcv import Config
    config_dpath = _get_config_directory()
    config_fpath = join(config_dpath, fname)
    config_mod = Config.fromfile(config_fpath)
    return config_mod 
開發者ID:open-mmlab,項目名稱:mmdetection,代碼行數:9,代碼來源:test_forward.py

示例5: _get_detector_cfg

# 需要導入模塊: import mmcv [as 別名]
# 或者: from mmcv import Config [as 別名]
def _get_detector_cfg(fname):
    """Grab configs necessary to create a detector.

    These are deep copied to allow for safe modification of parameters without
    influencing other tests.
    """
    import mmcv
    config = _get_config_module(fname)
    model = copy.deepcopy(config.model)
    train_cfg = mmcv.Config(copy.deepcopy(config.train_cfg))
    test_cfg = mmcv.Config(copy.deepcopy(config.test_cfg))
    return model, train_cfg, test_cfg 
開發者ID:open-mmlab,項目名稱:mmdetection,代碼行數:14,代碼來源:test_forward.py

示例6: init_detector

# 需要導入模塊: import mmcv [as 別名]
# 或者: from mmcv import Config [as 別名]
def init_detector(config, checkpoint=None, device='cuda:0'):
    """Initialize a detector from config file.

    Args:
        config (str or :obj:`mmcv.Config`): Config file path or the config
            object.
        checkpoint (str, optional): Checkpoint path. If left as None, the model
            will not load any weights.

    Returns:
        nn.Module: The constructed detector.
    """
    if isinstance(config, str):
        config = mmcv.Config.fromfile(config)
    elif not isinstance(config, mmcv.Config):
        raise TypeError('config must be a filename or Config object, '
                        'but got {}'.format(type(config)))
    config.model.pretrained = None
    model = build_detector(config.model, test_cfg=config.test_cfg)
    if checkpoint is not None:
        checkpoint = load_checkpoint(model, checkpoint)
        if 'CLASSES' in checkpoint['meta']:
            model.CLASSES = checkpoint['meta']['CLASSES']
        else:
            warnings.warn('Class names are not saved in the checkpoint\'s '
                          'meta data, use COCO classes by default.')
            model.CLASSES = get_classes('coco')
    model.cfg = config  # save the config in the model for convenience
    model.to(device)
    model.eval()
    return model 
開發者ID:dingjiansw101,項目名稱:AerialDetection,代碼行數:33,代碼來源:inference.py

示例7: setUp

# 需要導入模塊: import mmcv [as 別名]
# 或者: from mmcv import Config [as 別名]
def setUp(self):
        config = dict(
            data=dict(
                train=dict(
                    type='FlyingChairs',
                    data_root='/home/youmin/data/OpticalFlow/FlyingChairs/',
                    annfile='/home/youmin/data/annotations/FlyingChairs/test.json',
                    input_shape=[256, 448],
                    mean=[0.485, 0.456, 0.406],
                    std=[0.229, 0.224, 0.225],
                )
            )
        )
        cfg = Config(config)
        self.dataset = build_dataset(cfg, 'train') 
開發者ID:DeepMotionAIResearch,項目名稱:DenseMatchingBenchmark,代碼行數:17,代碼來源:test_flying_chairs.py

示例8: setUp

# 需要導入模塊: import mmcv [as 別名]
# 或者: from mmcv import Config [as 別名]
def setUp(self):
        config = dict(
            data=dict(
                train=dict(
                    type='SceneFlow',
                    data_root='/home/youmin/data/StereoMatching/SceneFlow/',
                    annfile='/home/youmin/data/annotations/SceneFlow/cleanpass_train.json',
                    input_shape=[256, 512],
                    mean=[0.485, 0.456, 0.406],
                    std=[0.229, 0.224, 0.225],
                )
            )
        )
        cfg = Config(config)
        self.dataset = build_dataset(cfg, 'train') 
開發者ID:DeepMotionAIResearch,項目名稱:DenseMatchingBenchmark,代碼行數:17,代碼來源:test_scene_flow.py

示例9: init_detector

# 需要導入模塊: import mmcv [as 別名]
# 或者: from mmcv import Config [as 別名]
def init_detector(config, checkpoint=None, device='cuda:0'):
    """Initialize a detector from config file.

    Args:
        config (str or :obj:`mmcv.Config`): Config file path or the config
            object.
        checkpoint (str, optional): Checkpoint path. If left as None, the model
            will not load any weights.

    Returns:
        nn.Module: The constructed detector.
    """
    if isinstance(config, str):
        config = mmcv.Config.fromfile(config)
    elif not isinstance(config, mmcv.Config):
        raise TypeError('config must be a filename or Config object, '
                        'but got {}'.format(type(config)))
    config.model.pretrained = None
    model = build_detector(config.model, test_cfg=config.test_cfg)
    if checkpoint is not None:
        checkpoint = load_checkpoint(model, checkpoint)
        if 'CLASSES' in checkpoint['meta']:
            model.CLASSES = checkpoint['meta']['classes']
        else:
            warnings.warn('Class names are not saved in the checkpoint\'s '
                          'meta data, use COCO classes by default.')
            model.CLASSES = get_classes('coco')
    model.cfg = config  # save the config in the model for convenience
    model.to(device)
    model.eval()
    return model 
開發者ID:STVIR,項目名稱:Grid-R-CNN,代碼行數:33,代碼來源:inference.py

示例10: _get_detector_cfg

# 需要導入模塊: import mmcv [as 別名]
# 或者: from mmcv import Config [as 別名]
def _get_detector_cfg(fname):
    """
    Grab configs necessary to create a detector. These are deep copied to allow
    for safe modification of parameters without influencing other tests.
    """
    import mmcv
    config = _get_config_module(fname)
    model = copy.deepcopy(config.model)
    train_cfg = mmcv.Config(copy.deepcopy(config.train_cfg))
    test_cfg = mmcv.Config(copy.deepcopy(config.test_cfg))
    return model, train_cfg, test_cfg 
開發者ID:zl1994,項目名稱:IoU-Uniform-R-CNN,代碼行數:13,代碼來源:test_forward.py

示例11: test_fcos_head_loss

# 需要導入模塊: import mmcv [as 別名]
# 或者: from mmcv import Config [as 別名]
def test_fcos_head_loss():
    """Tests fcos head loss when truth is empty and non-empty."""
    s = 256
    img_metas = [{
        'img_shape': (s, s, 3),
        'scale_factor': 1,
        'pad_shape': (s, s, 3)
    }]
    train_cfg = mmcv.Config(
        dict(
            assigner=dict(
                type='MaxIoUAssigner',
                pos_iou_thr=0.5,
                neg_iou_thr=0.4,
                min_pos_iou=0,
                ignore_iof_thr=-1),
            allowed_border=-1,
            pos_weight=-1,
            debug=False))
    # since Focal Loss is not supported on CPU
    self = FCOSHead(
        num_classes=4,
        in_channels=1,
        train_cfg=train_cfg,
        loss_cls=dict(
            type='CrossEntropyLoss', use_sigmoid=True, loss_weight=1.0))
    feat = [
        torch.rand(1, 1, s // feat_size, s // feat_size)
        for feat_size in [4, 8, 16, 32, 64]
    ]
    cls_scores, bbox_preds, centerness = self.forward(feat)
    # Test that empty ground truth encourages the network to predict background
    gt_bboxes = [torch.empty((0, 4))]
    gt_labels = [torch.LongTensor([])]
    gt_bboxes_ignore = None
    empty_gt_losses = self.loss(cls_scores, bbox_preds, centerness, gt_bboxes,
                                gt_labels, img_metas, gt_bboxes_ignore)
    # When there is no truth, the cls loss should be nonzero but there should
    # be no box loss.
    empty_cls_loss = empty_gt_losses['loss_cls']
    empty_box_loss = empty_gt_losses['loss_bbox']
    assert empty_cls_loss.item() > 0, 'cls loss should be non-zero'
    assert empty_box_loss.item() == 0, (
        'there should be no box loss when there are no true boxes')

    # When truth is non-empty then both cls and box loss should be nonzero for
    # random inputs
    gt_bboxes = [
        torch.Tensor([[23.6667, 23.8757, 238.6326, 151.8874]]),
    ]
    gt_labels = [torch.LongTensor([2])]
    one_gt_losses = self.loss(cls_scores, bbox_preds, centerness, gt_bboxes,
                              gt_labels, img_metas, gt_bboxes_ignore)
    onegt_cls_loss = one_gt_losses['loss_cls']
    onegt_box_loss = one_gt_losses['loss_bbox']
    assert onegt_cls_loss.item() > 0, 'cls loss should be non-zero'
    assert onegt_box_loss.item() > 0, 'box loss should be non-zero' 
開發者ID:open-mmlab,項目名稱:mmdetection,代碼行數:59,代碼來源:test_heads.py

示例12: test_bbox_head_loss

# 需要導入模塊: import mmcv [as 別名]
# 或者: from mmcv import Config [as 別名]
def test_bbox_head_loss():
    """Tests bbox head loss when truth is empty and non-empty."""
    self = BBoxHead(in_channels=8, roi_feat_size=3)

    # Dummy proposals
    proposal_list = [
        torch.Tensor([[23.6667, 23.8757, 228.6326, 153.8874]]),
    ]

    target_cfg = mmcv.Config(dict(pos_weight=1))

    # Test bbox loss when truth is empty
    gt_bboxes = [torch.empty((0, 4))]
    gt_labels = [torch.LongTensor([])]

    sampling_results = _dummy_bbox_sampling(proposal_list, gt_bboxes,
                                            gt_labels)

    bbox_targets = self.get_targets(sampling_results, gt_bboxes, gt_labels,
                                    target_cfg)
    labels, label_weights, bbox_targets, bbox_weights = bbox_targets

    # Create dummy features "extracted" for each sampled bbox
    num_sampled = sum(len(res.bboxes) for res in sampling_results)
    rois = bbox2roi([res.bboxes for res in sampling_results])
    dummy_feats = torch.rand(num_sampled, 8 * 3 * 3)
    cls_scores, bbox_preds = self.forward(dummy_feats)

    losses = self.loss(cls_scores, bbox_preds, rois, labels, label_weights,
                       bbox_targets, bbox_weights)
    assert losses.get('loss_cls', 0) > 0, 'cls-loss should be non-zero'
    assert losses.get('loss_bbox', 0) == 0, 'empty gt loss should be zero'

    # Test bbox loss when truth is non-empty
    gt_bboxes = [
        torch.Tensor([[23.6667, 23.8757, 238.6326, 151.8874]]),
    ]
    gt_labels = [torch.LongTensor([2])]

    sampling_results = _dummy_bbox_sampling(proposal_list, gt_bboxes,
                                            gt_labels)
    rois = bbox2roi([res.bboxes for res in sampling_results])

    bbox_targets = self.get_targets(sampling_results, gt_bboxes, gt_labels,
                                    target_cfg)
    labels, label_weights, bbox_targets, bbox_weights = bbox_targets

    # Create dummy features "extracted" for each sampled bbox
    num_sampled = sum(len(res.bboxes) for res in sampling_results)
    dummy_feats = torch.rand(num_sampled, 8 * 3 * 3)
    cls_scores, bbox_preds = self.forward(dummy_feats)

    losses = self.loss(cls_scores, bbox_preds, rois, labels, label_weights,
                       bbox_targets, bbox_weights)
    assert losses.get('loss_cls', 0) > 0, 'cls-loss should be non-zero'
    assert losses.get('loss_bbox', 0) > 0, 'box-loss should be non-zero' 
開發者ID:open-mmlab,項目名稱:mmdetection,代碼行數:58,代碼來源:test_heads.py

示例13: testCase1

# 需要導入模塊: import mmcv [as 別名]
# 或者: from mmcv import Config [as 別名]
def testCase1(self):
        start_disp = -4
        dilation = 2
        alpha = 1.0
        normalize = True
        max_disp = 9
        h, w = 2, 2

        d = (max_disp + dilation - 1) // dilation

        cfg = Config(dict(
            model=dict(
                disp_predictor=dict(
                    type=self.pred_type,
                    # the maximum disparity of disparity search range
                    max_disp=max_disp,
                    # disparity sample radius
                    radius=self.radius,
                    # the start disparity of disparity search range
                    start_disp=start_disp,
                    # the step between near disparity sample
                    dilation=dilation,
                    # the step between near disparity sample when local sampling
                    radius_dilation = self.radius_dilation,
                    # the temperature coefficient of soft argmin
                    alpha=alpha,
                    # whether normalize the estimated cost volume
                    normalize=normalize,

                ),
            )
        ))

        cfg.model.update(disp_predictor = kick_out_none_keys(cfg.model.disp_predictor))

        cost = torch.ones(1, d, h, w).to(self.device)
        cost.requires_grad = True
        print('*' * 60)
        print('Cost volume:')
        print(cost)

        disp_predictor = build_disp_predictor(cfg).to(self.device)
        print(disp_predictor)
        disp = disp_predictor(cost)
        print('*' * 60)
        print('Regressed disparity map :')
        print(disp)

        # soft argmin
        if self.pred_type == 'DEFAULT':
            print('*' * 60)
            print('Test directly providing disparity samples')

            end_disp = start_disp + max_disp - 1

            # generate disparity samples
            disp_samples = torch.linspace(start_disp, end_disp, d).repeat(1, h, w, 1).\
                                                permute(0, 3, 1, 2).contiguous().to(cost.device)
            disp = disp_predictor(cost, disp_samples)
            print('Regressed disparity map :')
            print(disp) 
開發者ID:DeepMotionAIResearch,項目名稱:DenseMatchingBenchmark,代碼行數:63,代碼來源:test_disp_predictors.py

示例14: testCase1

# 需要導入模塊: import mmcv [as 別名]
# 或者: from mmcv import Config [as 別名]
def testCase1(self):
        max_disp = 5
        start_disp = -2
        dilation = 2
        h, w = 3, 4
        d = (max_disp + dilation - 1) // dilation
        variance = 2

        gtDisp = torch.rand(1, 1, h, w) * max_disp + start_disp

        gtDisp = gtDisp.to(self.device)

        cfg = Config(dict(
            data = dict(
              sparse = False,
            ),
            model=dict(
                losses=dict(
                    focal_loss=dict(
                        # the maximum disparity of disparity search range
                        max_disp=max_disp,
                        # the start disparity of disparity search range
                        start_disp=start_disp,
                        # the step between near disparity sample
                        dilation=dilation,
                        # weight for stereo focal loss with regard to other loss type
                        weight=1.0,
                        # weights for different scale loss
                        weights=(1.0),
                        # stereo focal loss focal coefficient
                        coefficient=5.0,
                    )
                ),
            )
        ))

        estCost = torch.ones(1, d, h, w).to(self.device)
        estCost.requires_grad = True
        print('\n \n Test Case 1:')
        print('*' * 60)
        print('Estimated Cost volume:')
        print(estCost)

        stereo_focal_loss_evaluator = make_focal_loss_evaluator(cfg)
        print(stereo_focal_loss_evaluator)
        print('*' * 60)
        print(stereo_focal_loss_evaluator(estCost=estCost, gtDisp=gtDisp, variance=variance, disp_sample=None)) 
開發者ID:DeepMotionAIResearch,項目名稱:DenseMatchingBenchmark,代碼行數:49,代碼來源:test_stereo_focal_loss.py


注:本文中的mmcv.Config方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。