code stringlengths 17 6.64M |
|---|
def init_random_seed(seed=None, device='cuda'):
"Initialize random seed.\n\n If the seed is not set, the seed will be automatically randomized,\n and then broadcast to all processes to prevent some potential bugs.\n\n Args:\n seed (int, Optional): The seed. Default to None.\n device (str): ... |
def set_random_seed(seed, deterministic=False):
'Set random seed.\n\n Args:\n seed (int): Seed to be used.\n deterministic (bool): Whether to set the deterministic option for\n CUDNN backend, i.e., set `torch.backends.cudnn.deterministic`\n to True and `torch.backends.cudnn.... |
def train_detector(model, dataset, cfg, distributed=False, validate=False, timestamp=None, meta=None):
logger = get_root_logger(log_level=cfg.log_level)
dataset = (dataset if isinstance(dataset, (list, tuple)) else [dataset])
if ('imgs_per_gpu' in cfg.data):
logger.warning('"imgs_per_gpu" is depre... |
def build_prior_generator(cfg, default_args=None):
return build_from_cfg(cfg, PRIOR_GENERATORS, default_args)
|
def build_anchor_generator(cfg, default_args=None):
warnings.warn('``build_anchor_generator`` would be deprecated soon, please use ``build_prior_generator`` ')
return build_prior_generator(cfg, default_args=default_args)
|
@PRIOR_GENERATORS.register_module()
class PointGenerator():
def _meshgrid(self, x, y, row_major=True):
xx = x.repeat(len(y))
yy = y.view((- 1), 1).repeat(1, len(x)).view((- 1))
if row_major:
return (xx, yy)
else:
return (yy, xx)
def grid_points(self, f... |
@PRIOR_GENERATORS.register_module()
class MlvlPointGenerator():
'Standard points generator for multi-level (Mlvl) feature maps in 2D\n points-based detectors.\n\n Args:\n strides (list[int] | list[tuple[int, int]]): Strides of anchors\n in multiple feature levels in order (w, h).\n ... |
class AssignResult(util_mixins.NiceRepr):
'Stores assignments between predicted and truth boxes.\n\n Attributes:\n num_gts (int): the number of truth boxes considered when computing this\n assignment\n\n gt_inds (LongTensor): for each predicted box indicates the 1-based\n in... |
class BaseAssigner(metaclass=ABCMeta):
'Base assigner that assigns boxes to ground truth boxes.'
@abstractmethod
def assign(self, bboxes, gt_bboxes, gt_bboxes_ignore=None, gt_labels=None):
'Assign boxes to either a ground truth boxes or a negative boxes.'
|
@BBOX_ASSIGNERS.register_module()
class HungarianAssigner(BaseAssigner):
'Computes one-to-one matching between predictions and ground truth.\n\n This class computes an assignment between the targets and the predictions\n based on the costs. The costs are weighted sum of three components:\n classification... |
@BBOX_ASSIGNERS.register_module()
class MaskHungarianAssigner(BaseAssigner):
"Computes one-to-one matching between predictions and ground truth for\n mask.\n\n This class computes an assignment between the targets and the predictions\n based on the costs. The costs are weighted sum of three components:\n... |
@BBOX_ASSIGNERS.register_module()
class UniformAssigner(BaseAssigner):
'Uniform Matching between the anchors and gt boxes, which can achieve\n balance in positive anchors, and gt_bboxes_ignore was not considered for\n now.\n\n Args:\n pos_ignore_thr (float): the threshold to ignore positive anchor... |
def build_assigner(cfg, **default_args):
'Builder of box assigner.'
return build_from_cfg(cfg, BBOX_ASSIGNERS, default_args)
|
def build_sampler(cfg, **default_args):
'Builder of box sampler.'
return build_from_cfg(cfg, BBOX_SAMPLERS, default_args)
|
def build_bbox_coder(cfg, **default_args):
'Builder of box coder.'
return build_from_cfg(cfg, BBOX_CODERS, default_args)
|
class BaseBBoxCoder(metaclass=ABCMeta):
'Base bounding box coder.'
def __init__(self, **kwargs):
pass
@abstractmethod
def encode(self, bboxes, gt_bboxes):
'Encode deltas between bboxes and ground truth boxes.'
@abstractmethod
def decode(self, bboxes, bboxes_pred):
'D... |
@BBOX_CODERS.register_module()
class DistancePointBBoxCoder(BaseBBoxCoder):
'Distance Point BBox coder.\n\n This coder encodes gt bboxes (x1, y1, x2, y2) into (top, bottom, left,\n right) and decode it back to the original.\n\n Args:\n clip_border (bool, optional): Whether clip the objects outside... |
@BBOX_CODERS.register_module()
class PseudoBBoxCoder(BaseBBoxCoder):
'Pseudo bounding box coder.'
def __init__(self, **kwargs):
super(BaseBBoxCoder, self).__init__(**kwargs)
def encode(self, bboxes, gt_bboxes):
'torch.Tensor: return the given ``bboxes``'
return gt_bboxes
def... |
def build_iou_calculator(cfg, default_args=None):
'Builder of IoU calculator.'
return build_from_cfg(cfg, IOU_CALCULATORS, default_args)
|
def build_match_cost(cfg, default_args=None):
'Builder of IoU calculator.'
return build_from_cfg(cfg, MATCH_COST, default_args)
|
@BBOX_SAMPLERS.register_module()
class CombinedSampler(BaseSampler):
'A sampler that combines positive sampler and negative sampler.'
def __init__(self, pos_sampler, neg_sampler, **kwargs):
super(CombinedSampler, self).__init__(**kwargs)
self.pos_sampler = build_sampler(pos_sampler, **kwargs)... |
@BBOX_SAMPLERS.register_module()
class InstanceBalancedPosSampler(RandomSampler):
'Instance balanced sampler that samples equal number of positive samples\n for each instance.'
def _sample_pos(self, assign_result, num_expected, **kwargs):
'Sample positive boxes.\n\n Args:\n assig... |
@BBOX_SAMPLERS.register_module()
class IoUBalancedNegSampler(RandomSampler):
'IoU Balanced Sampling.\n\n arXiv: https://arxiv.org/pdf/1904.02701.pdf (CVPR 2019)\n\n Sampling proposals according to their IoU. `floor_fraction` of needed RoIs\n are sampled from proposals whose IoU are lower than `floor_thr`... |
@BBOX_SAMPLERS.register_module()
class MaskPseudoSampler(BaseSampler):
'A pseudo sampler that does not do sampling actually.'
def __init__(self, **kwargs):
pass
def _sample_pos(self, **kwargs):
'Sample positive samples.'
raise NotImplementedError
def _sample_neg(self, **kwar... |
@BBOX_SAMPLERS.register_module()
class OHEMSampler(BaseSampler):
'Online Hard Example Mining Sampler described in `Training Region-based\n Object Detectors with Online Hard Example Mining\n <https://arxiv.org/abs/1604.03540>`_.\n '
def __init__(self, num, pos_fraction, context, neg_pos_ub=(- 1), add... |
@BBOX_SAMPLERS.register_module()
class PseudoSampler(BaseSampler):
'A pseudo sampler that does not do sampling actually.'
def __init__(self, **kwargs):
pass
def _sample_pos(self, **kwargs):
'Sample positive samples.'
raise NotImplementedError
def _sample_neg(self, **kwargs):... |
@BBOX_SAMPLERS.register_module()
class RandomSampler(BaseSampler):
'Random sampler.\n\n Args:\n num (int): Number of samples\n pos_fraction (float): Fraction of positive samples\n neg_pos_up (int, optional): Upper bound number of negative and\n positive samples. Defaults to -1.\... |
class GeneralData(NiceRepr):
'A general data structure of OpenMMlab.\n\n A data structure that stores the meta information,\n the annotations of the images or the model predictions,\n which can be used in communication between components.\n\n The attributes in `GeneralData` are divided into two parts,... |
class InstanceData(GeneralData):
'Data structure for instance-level annnotations or predictions.\n\n Subclass of :class:`GeneralData`. All value in `data_fields`\n should have the same length. This design refer to\n https://github.com/facebookresearch/detectron2/blob/master/detectron2/structures/instance... |
def wider_face_classes():
return ['face']
|
def voc_classes():
return ['aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'car', 'cat', 'chair', 'cow', 'diningtable', 'dog', 'horse', 'motorbike', 'person', 'pottedplant', 'sheep', 'sofa', 'train', 'tvmonitor']
|
def imagenet_det_classes():
return ['accordion', 'airplane', 'ant', 'antelope', 'apple', 'armadillo', 'artichoke', 'axe', 'baby_bed', 'backpack', 'bagel', 'balance_beam', 'banana', 'band_aid', 'banjo', 'baseball', 'basketball', 'bathing_cap', 'beaker', 'bear', 'bee', 'bell_pepper', 'bench', 'bicycle', 'binder', '... |
def imagenet_vid_classes():
return ['airplane', 'antelope', 'bear', 'bicycle', 'bird', 'bus', 'car', 'cattle', 'dog', 'domestic_cat', 'elephant', 'fox', 'giant_panda', 'hamster', 'horse', 'lion', 'lizard', 'monkey', 'motorcycle', 'rabbit', 'red_panda', 'sheep', 'snake', 'squirrel', 'tiger', 'train', 'turtle', 'wa... |
def coco_classes():
return ['person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', 'boat', 'traffic_light', 'fire_hydrant', 'stop_sign', 'parking_meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow', 'elephant', 'bear', 'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie'... |
def cityscapes_classes():
return ['person', 'rider', 'car', 'truck', 'bus', 'train', 'motorcycle', 'bicycle']
|
def oid_challenge_classes():
return ['Footwear', 'Jeans', 'House', 'Tree', 'Woman', 'Man', 'Land vehicle', 'Person', 'Wheel', 'Bus', 'Human face', 'Bird', 'Dress', 'Girl', 'Vehicle', 'Building', 'Cat', 'Car', 'Belt', 'Elephant', 'Dessert', 'Butterfly', 'Train', 'Guitar', 'Poster', 'Book', 'Boy', 'Bee', 'Flower', ... |
def oid_v6_classes():
return ['Tortoise', 'Container', 'Magpie', 'Sea turtle', 'Football', 'Ambulance', 'Ladder', 'Toothbrush', 'Syringe', 'Sink', 'Toy', 'Organ (Musical Instrument)', 'Cassette deck', 'Apple', 'Human eye', 'Cosmetics', 'Paddle', 'Snowman', 'Beer', 'Chopsticks', 'Human beard', 'Bird', 'Parking met... |
def get_classes(dataset):
'Get class names of a dataset.'
alias2name = {}
for (name, aliases) in dataset_aliases.items():
for alias in aliases:
alias2name[alias] = name
if mmcv.is_str(dataset):
if (dataset in alias2name):
labels = eval((alias2name[dataset] + '_c... |
def _calc_dynamic_intervals(start_interval, dynamic_interval_list):
assert mmcv.is_list_of(dynamic_interval_list, tuple)
dynamic_milestones = [0]
dynamic_milestones.extend([dynamic_interval[0] for dynamic_interval in dynamic_interval_list])
dynamic_intervals = [start_interval]
dynamic_intervals.ex... |
class EvalHook(BaseEvalHook):
def __init__(self, *args, dynamic_intervals=None, **kwargs):
super(EvalHook, self).__init__(*args, **kwargs)
self.use_dynamic_intervals = (dynamic_intervals is not None)
if self.use_dynamic_intervals:
(self.dynamic_milestones, self.dynamic_interva... |
class DistEvalHook(BaseDistEvalHook):
def __init__(self, *args, dynamic_intervals=None, **kwargs):
super(DistEvalHook, self).__init__(*args, **kwargs)
self.use_dynamic_intervals = (dynamic_intervals is not None)
if self.use_dynamic_intervals:
(self.dynamic_milestones, self.dyn... |
def generate_inputs_and_wrap_model(config_path, checkpoint_path, input_config, cfg_options=None):
"Prepare sample input and wrap model for ONNX export.\n\n The ONNX export API only accept args, and all inputs should be\n torch.Tensor or corresponding types (such as tuple of tensor).\n So we should call t... |
def build_model_from_cfg(config_path, checkpoint_path, cfg_options=None):
'Build a model from config and load the given checkpoint.\n\n Args:\n config_path (str): the OpenMMLab config for the model we want to\n export to ONNX\n checkpoint_path (str): Path to the corresponding checkpoin... |
def preprocess_example_input(input_config):
"Prepare an example input image for ``generate_inputs_and_wrap_model``.\n\n Args:\n input_config (dict): customized config describing the example input.\n\n Returns:\n tuple: (one_img, one_meta), tensor of the example input image and meta... |
@HOOKS.register_module()
class CheckInvalidLossHook(Hook):
'Check invalid loss hook.\n\n This hook will regularly check whether the loss is valid\n during training.\n\n Args:\n interval (int): Checking interval (every k iterations).\n Default: 50.\n '
def __init__(self, interval... |
class BaseEMAHook(Hook):
"Exponential Moving Average Hook.\n\n Use Exponential Moving Average on all parameters of model in training\n process. All parameters have a ema backup, which update by the formula\n as below. EMAHook takes priority over EvalHook and CheckpointHook. Note,\n the original model ... |
@HOOKS.register_module()
class ExpMomentumEMAHook(BaseEMAHook):
'EMAHook using exponential momentum strategy.\n\n Args:\n total_iter (int): The total number of iterations of EMA momentum.\n Defaults to 2000.\n '
def __init__(self, total_iter=2000, **kwargs):
super(ExpMomentumEM... |
@HOOKS.register_module()
class LinearMomentumEMAHook(BaseEMAHook):
'EMAHook using linear momentum strategy.\n\n Args:\n warm_up (int): During first warm_up steps, we may use smaller decay\n to update ema parameters more slowly. Defaults to 100.\n '
def __init__(self, warm_up=100, **kw... |
@HOOKS.register_module()
class SetEpochInfoHook(Hook):
"Set runner's epoch information to the model."
def before_train_epoch(self, runner):
epoch = runner.epoch
model = runner.model
if is_module_wrapper(model):
model = model.module
model.set_epoch(epoch)
|
def get_norm_states(module):
async_norm_states = OrderedDict()
for (name, child) in module.named_modules():
if isinstance(child, nn.modules.batchnorm._NormBase):
for (k, v) in child.state_dict().items():
async_norm_states['.'.join([name, k])] = v
return async_norm_state... |
@HOOKS.register_module()
class SyncNormHook(Hook):
'Synchronize Norm states after training epoch, currently used in YOLOX.\n\n Args:\n num_last_epochs (int): The number of latter epochs in the end of the\n training to switch to synchronizing norm interval. Default: 15.\n interval (int)... |
@HOOKS.register_module()
class SyncRandomSizeHook(Hook):
"Change and synchronize the random image size across ranks.\n SyncRandomSizeHook is deprecated, please use Resize pipeline to achieve\n similar functions. Such as `dict(type='Resize', img_scale=[(448, 448),\n (832, 832)], multiscale_mode='range', k... |
@HOOKS.register_module()
class YOLOXLrUpdaterHook(CosineAnnealingLrUpdaterHook):
'YOLOX learning rate scheme.\n\n There are two main differences between YOLOXLrUpdaterHook\n and CosineAnnealingLrUpdaterHook.\n\n 1. When the current running epoch is greater than\n `max_epoch-last_epoch`, a fi... |
@HOOKS.register_module()
class YOLOXModeSwitchHook(Hook):
"Switch the mode of YOLOX during training.\n\n This hook turns off the mosaic and mixup data augmentation and switches\n to use L1 loss in bbox_head.\n\n Args:\n num_last_epochs (int): The number of latter epochs in the end of the\n ... |
def mask_matrix_nms(masks, labels, scores, filter_thr=(- 1), nms_pre=(- 1), max_num=(- 1), kernel='gaussian', sigma=2.0, mask_area=None):
"Matrix NMS for multi-class masks.\n\n Args:\n masks (Tensor): Has shape (num_instances, h, w)\n labels (Tensor): Labels of corresponding masks,\n h... |
def _allreduce_coalesced(tensors, world_size, bucket_size_mb=(- 1)):
if (bucket_size_mb > 0):
bucket_size_bytes = ((bucket_size_mb * 1024) * 1024)
buckets = _take_tensors(tensors, bucket_size_bytes)
else:
buckets = OrderedDict()
for tensor in tensors:
tp = tensor.ty... |
def allreduce_grads(params, coalesce=True, bucket_size_mb=(- 1)):
'Allreduce gradients.\n\n Args:\n params (list[torch.Parameters]): List of parameters of a model\n coalesce (bool, optional): Whether allreduce parameters as a whole.\n Defaults to True.\n bucket_size_mb (int, opt... |
class DistOptimizerHook(OptimizerHook):
'Deprecated optimizer hook for distributed training.'
def __init__(self, *args, **kwargs):
warnings.warn('"DistOptimizerHook" is deprecated, please switch to"mmcv.runner.OptimizerHook".')
super().__init__(*args, **kwargs)
|
def reduce_mean(tensor):
'"Obtain the mean of tensor on different GPUs.'
if (not (dist.is_available() and dist.is_initialized())):
return tensor
tensor = tensor.clone()
dist.all_reduce(tensor.div_(dist.get_world_size()), op=dist.ReduceOp.SUM)
return tensor
|
def obj2tensor(pyobj, device='cuda'):
'Serialize picklable python object to tensor.'
storage = torch.ByteStorage.from_buffer(pickle.dumps(pyobj))
return torch.ByteTensor(storage).to(device=device)
|
def tensor2obj(tensor):
'Deserialize tensor to picklable python object.'
return pickle.loads(tensor.cpu().numpy().tobytes())
|
@functools.lru_cache()
def _get_global_gloo_group():
'Return a process group based on gloo backend, containing all the ranks\n The result is cached.'
if (dist.get_backend() == 'nccl'):
return dist.new_group(backend='gloo')
else:
return dist.group.WORLD
|
def all_reduce_dict(py_dict, op='sum', group=None, to_float=True):
"Apply all reduce function for python dict object.\n\n The code is modified from https://github.com/Megvii-\n BaseDetection/YOLOX/blob/main/yolox/utils/allreduce_norm.py.\n\n NOTE: make sure that py_dict in different ranks has the same ke... |
def palette_val(palette):
'Convert palette to matplotlib palette.\n\n Args:\n palette List[tuple]: A list of color tuples.\n\n Returns:\n List[tuple[float]]: A list of RGB matplotlib color tuples.\n '
new_palette = []
for color in palette:
color = [(c / 255) for c in color]
... |
def get_palette(palette, num_classes):
'Get palette from various inputs.\n\n Args:\n palette (list[tuple] | str | tuple | :obj:`Color`): palette inputs.\n num_classes (int): the number of classes.\n\n Returns:\n list[tuple[int]]: A list of color tuples.\n '
assert isinstance(num_... |
class COCO(_COCO):
'This class is almost the same as official pycocotools package.\n\n It implements some snake case function aliases. So that the COCO class has\n the same interface as LVIS class.\n '
def __init__(self, annotation_file=None):
if (getattr(pycocotools, '__version__', '0') >= ... |
def pq_compute_single_core(proc_id, annotation_set, gt_folder, pred_folder, categories, file_client=None):
'The single core function to evaluate the metric of Panoptic\n Segmentation.\n\n Same as the function with the same name in `panopticapi`. Only the function\n to load the images is changed to use th... |
def pq_compute_multi_core(matched_annotations_list, gt_folder, pred_folder, categories, file_client=None):
'Evaluate the metrics of Panoptic Segmentation with multithreading.\n\n Same as the function with the same name in `panopticapi`.\n\n Args:\n matched_annotations_list (list): The matched annotat... |
def _concat_dataset(cfg, default_args=None):
from .dataset_wrappers import ConcatDataset
ann_files = cfg['ann_file']
img_prefixes = cfg.get('img_prefix', None)
seg_prefixes = cfg.get('seg_prefix', None)
proposal_files = cfg.get('proposal_file', None)
separate_eval = cfg.get('separate_eval', Tr... |
def build_dataset(cfg, default_args=None):
from .dataset_wrappers import ClassBalancedDataset, ConcatDataset, MultiImageMixDataset, RepeatDataset
if isinstance(cfg, (list, tuple)):
dataset = ConcatDataset([build_dataset(c, default_args) for c in cfg])
elif (cfg['type'] == 'ConcatDataset'):
... |
def build_dataloader(dataset, samples_per_gpu, workers_per_gpu, num_gpus=1, dist=True, shuffle=True, seed=None, runner_type='EpochBasedRunner', persistent_workers=False, **kwargs):
'Build PyTorch DataLoader.\n\n In distributed training, each GPU/process has a dataloader.\n In non-distributed training, there... |
def worker_init_fn(worker_id, num_workers, rank, seed):
worker_seed = (((num_workers * rank) + worker_id) + seed)
np.random.seed(worker_seed)
random.seed(worker_seed)
|
@DATASETS.register_module()
class CityscapesDataset(CocoDataset):
CLASSES = ('person', 'rider', 'car', 'truck', 'bus', 'train', 'motorcycle', 'bicycle')
PALETTE = [(220, 20, 60), (255, 0, 0), (0, 0, 142), (0, 0, 70), (0, 60, 100), (0, 80, 100), (0, 0, 230), (119, 11, 32)]
def _filter_imgs(self, min_size=... |
@DATASETS.register_module()
class CustomDataset(Dataset):
"Custom dataset for detection.\n\n The annotation format is shown as follows. The `ann` field is optional for\n testing.\n\n .. code-block:: none\n\n [\n {\n 'filename': 'a.jpg',\n 'width': 1280,\n ... |
@DATASETS.register_module()
class ConcatDataset(_ConcatDataset):
'A wrapper of concatenated dataset.\n\n Same as :obj:`torch.utils.data.dataset.ConcatDataset`, but\n concat the group flag for image aspect ratio.\n\n Args:\n datasets (list[:obj:`Dataset`]): A list of datasets.\n separate_eva... |
@DATASETS.register_module()
class RepeatDataset():
'A wrapper of repeated dataset.\n\n The length of repeated dataset will be `times` larger than the original\n dataset. This is useful when the data loading time is long but the dataset\n is small. Using RepeatDataset can reduce the data loading time betw... |
@DATASETS.register_module()
class ClassBalancedDataset():
'A wrapper of repeated dataset with repeat factor.\n\n Suitable for training on class imbalanced datasets like LVIS. Following\n the sampling strategy in the `paper <https://arxiv.org/abs/1908.03195>`_,\n in each epoch, an image may appear multipl... |
@DATASETS.register_module()
class MultiImageMixDataset():
'A wrapper of multiple images mixed dataset.\n\n Suitable for training on multiple images mixed data augmentation like\n mosaic and mixup. For the augmentation pipeline of mixed image data,\n the `get_indexes` method needs to be provided to obtain... |
@DATASETS.register_module()
class DeepFashionDataset(CocoDataset):
CLASSES = ('top', 'skirt', 'leggings', 'dress', 'outer', 'pants', 'bag', 'neckwear', 'headwear', 'eyeglass', 'belt', 'footwear', 'hair', 'skin', 'face')
PALETTE = [(0, 192, 64), (0, 64, 96), (128, 192, 192), (0, 64, 64), (0, 192, 224), (0, 192... |
@PIPELINES.register_module()
class Compose():
'Compose multiple transforms sequentially.\n\n Args:\n transforms (Sequence[dict | callable]): Sequence of transform object or\n config dict to be composed.\n '
def __init__(self, transforms):
assert isinstance(transforms, collecti... |
def to_tensor(data):
'Convert objects of various python types to :obj:`torch.Tensor`.\n\n Supported types are: :class:`numpy.ndarray`, :class:`torch.Tensor`,\n :class:`Sequence`, :class:`int` and :class:`float`.\n\n Args:\n data (torch.Tensor | numpy.ndarray | Sequence | int | float): Data to\n ... |
@PIPELINES.register_module()
class ToTensor():
'Convert some results to :obj:`torch.Tensor` by given keys.\n\n Args:\n keys (Sequence[str]): Keys that need to be converted to Tensor.\n '
def __init__(self, keys):
self.keys = keys
def __call__(self, results):
'Call function t... |
@PIPELINES.register_module()
class ImageToTensor():
'Convert image to :obj:`torch.Tensor` by given keys.\n\n The dimension order of input image is (H, W, C). The pipeline will convert\n it to (C, H, W). If only 2 dimension (H, W) is given, the output would be\n (1, H, W).\n\n Args:\n keys (Sequ... |
@PIPELINES.register_module()
class Transpose():
'Transpose some results by given keys.\n\n Args:\n keys (Sequence[str]): Keys of results to be transposed.\n order (Sequence[int]): Order of transpose.\n '
def __init__(self, keys, order):
self.keys = keys
self.order = order
... |
@PIPELINES.register_module()
class ToDataContainer():
"Convert results to :obj:`mmcv.DataContainer` by given fields.\n\n Args:\n fields (Sequence[dict]): Each field is a dict like\n ``dict(key='xxx', **kwargs)``. The ``key`` in result will\n be converted to :obj:`mmcv.DataContainer... |
@PIPELINES.register_module()
class DefaultFormatBundle():
'Default formatting bundle.\n\n It simplifies the pipeline of formatting common fields, including "img",\n "proposals", "gt_bboxes", "gt_labels", "gt_masks" and "gt_semantic_seg".\n These fields are formatted as follows.\n\n - img: (1)transpose... |
@PIPELINES.register_module()
class Collect():
'Collect data from the loader relevant to the specific task.\n\n This is usually the last stage of the data loader pipeline. Typically keys\n is set to some subset of "img", "proposals", "gt_bboxes",\n "gt_bboxes_ignore", "gt_labels", and/or "gt_masks".\n\n ... |
@PIPELINES.register_module()
class WrapFieldsToLists():
"Wrap fields of the data dictionary into lists for evaluation.\n\n This class can be used as a last step of a test or validation\n pipeline for single image evaluation or inference.\n\n Example:\n >>> test_pipeline = [\n >>> dict(ty... |
@PIPELINES.register_module()
class InstaBoost():
'Data augmentation method in `InstaBoost: Boosting Instance\n Segmentation Via Probability Map Guided Copy-Pasting\n <https://arxiv.org/abs/1908.07801>`_.\n\n Refer to https://github.com/GothicAi/Instaboost for implementation details.\n\n Args:\n ... |
@PIPELINES.register_module()
class MultiScaleFlipAug():
'Test-time augmentation with multiple scales and flipping.\n\n An example configuration is as followed:\n\n .. code-block::\n\n img_scale=[(1333, 400), (1333, 800)],\n flip=True,\n transforms=[\n dict(type=\'Resize\', ke... |
class DistributedSampler(_DistributedSampler):
def __init__(self, dataset, num_replicas=None, rank=None, shuffle=True, seed=0):
super().__init__(dataset, num_replicas=num_replicas, rank=rank, shuffle=shuffle)
self.seed = (seed if (seed is not None) else 0)
def __iter__(self):
if self... |
class GroupSampler(Sampler):
def __init__(self, dataset, samples_per_gpu=1):
assert hasattr(dataset, 'flag')
self.dataset = dataset
self.samples_per_gpu = samples_per_gpu
self.flag = dataset.flag.astype(np.int64)
self.group_sizes = np.bincount(self.flag)
self.num_s... |
class DistributedGroupSampler(Sampler):
'Sampler that restricts data loading to a subset of the dataset.\n\n It is especially useful in conjunction with\n :class:`torch.nn.parallel.DistributedDataParallel`. In such case, each\n process can pass a DistributedSampler instance as a DataLoader sampler,\n ... |
class InfiniteGroupBatchSampler(Sampler):
'Similar to `BatchSampler` warping a `GroupSampler. It is designed for\n iteration-based runners like `IterBasedRunner` and yields a mini-batch\n indices each time, all indices in a batch should be in the same group.\n\n The implementation logic is referred to\n ... |
class InfiniteBatchSampler(Sampler):
'Similar to `BatchSampler` warping a `DistributedSampler. It is designed\n iteration-based runners like `IterBasedRunner` and yields a mini-batch\n indices each time.\n\n The implementation logic is referred to\n https://github.com/facebookresearch/detectron2/blob/... |
def replace_ImageToTensor(pipelines):
"Replace the ImageToTensor transform in a data pipeline to\n DefaultFormatBundle, which is normally useful in batch inference.\n\n Args:\n pipelines (list[dict]): Data pipeline configs.\n\n Returns:\n list: The new pipeline list with all ImageToTensor r... |
def get_loading_pipeline(pipeline):
"Only keep loading image and annotations related configuration.\n\n Args:\n pipeline (list[dict]): Data pipeline configs.\n\n Returns:\n list[dict]: The new pipeline list with only keep\n loading image and annotations related configuration.\n\n ... |
@HOOKS.register_module()
class NumClassCheckHook(Hook):
def _check_head(self, runner):
'Check whether the `num_classes` in head matches the length of\n `CLASSES` in `dataset`.\n\n Args:\n runner (obj:`EpochBasedRunner`): Epoch based Runner.\n '
model = runner.model... |
@DATASETS.register_module()
class VOCDataset(XMLDataset):
CLASSES = ('aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'car', 'cat', 'chair', 'cow', 'diningtable', 'dog', 'horse', 'motorbike', 'person', 'pottedplant', 'sheep', 'sofa', 'train', 'tvmonitor')
PALETTE = [(106, 0, 228), (119, 11, 32), (165,... |
@DATASETS.register_module()
class WIDERFaceDataset(XMLDataset):
'Reader for the WIDER Face dataset in PASCAL VOC format.\n\n Conversion scripts can be found in\n https://github.com/sovrasov/wider-face-pascal-voc-annotations\n '
CLASSES = ('face',)
PALETTE = [(0, 255, 0)]
def __init__(self, *... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.