id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
14,856
from functools import partial from typing import List, Sequence, Tuple, Union import numpy as np import torch from mmengine.structures import InstanceData from mmengine.utils import digit_version from six.moves import map, zip from torch import Tensor from torch.autograd import Function from torch.nn import functional ...
Unpack ``gt_instances``, ``gt_instances_ignore`` and ``img_metas`` based on ``batch_data_samples`` Args: batch_data_samples (List[:obj:`DetDataSample`]): The Data Samples. It usually includes information such as `gt_instance`, `gt_panoptic_seg` and `gt_sem_seg`. Returns: tuple: - batch_gt_instances (list[:obj:`Instance...
14,857
from functools import partial from typing import List, Sequence, Tuple, Union import numpy as np import torch from mmengine.structures import InstanceData from mmengine.utils import digit_version from six.moves import map, zip from torch import Tensor from torch.autograd import Function from torch.nn import functional ...
Handle predicted instances when RoI is empty. Note: If ``instance_results`` is not None, it will be modified in place internally, and then return ``instance_results`` Args: batch_img_metas (list[dict]): List of image information. device (torch.device): Device of tensor. task_type (str): Expected returned task type. it ...
14,858
from functools import partial from typing import List, Sequence, Tuple, Union import numpy as np import torch from mmengine.structures import InstanceData from mmengine.utils import digit_version from six.moves import map, zip from torch import Tensor from torch.autograd import Function from torch.nn import functional ...
Apply function to a list of arguments. Note: This function applies the ``func`` to multiple inputs and map the multiple outputs of the ``func`` into different list. Each list contains the same type of outputs corresponding to different inputs. Args: func (Function): A function that will be applied to a list of argument...
14,859
from functools import partial from typing import List, Sequence, Tuple, Union import numpy as np import torch from mmengine.structures import InstanceData from mmengine.utils import digit_version from six.moves import map, zip from torch import Tensor from torch.autograd import Function from torch.nn import functional ...
Unmap a subset of item (data) back to the original set of items (of size count)
14,860
from functools import partial from typing import List, Sequence, Tuple, Union import numpy as np import torch from mmengine.structures import InstanceData from mmengine.utils import digit_version from six.moves import map, zip from torch import Tensor from torch.autograd import Function from torch.nn import functional ...
Convert Mask to ndarray.. Args: mask (:obj:`BitmapMasks` or :obj:`PolygonMasks` or torch.Tensor or np.ndarray): The mask to be converted. Returns: np.ndarray: Ndarray mask of shape (n, h, w) that has been converted
14,861
from functools import partial from typing import List, Sequence, Tuple, Union import numpy as np import torch from mmengine.structures import InstanceData from mmengine.utils import digit_version from six.moves import map, zip from torch import Tensor from torch.autograd import Function from torch.nn import functional ...
flip tensor base on flip_direction. Args: src_tensor (Tensor): input feature map, shape (B, C, H, W). flip_direction (str): The flipping direction. Options are 'horizontal', 'vertical', 'diagonal'. Returns: out_tensor (Tensor): Flipped tensor.
14,862
from functools import partial from typing import List, Sequence, Tuple, Union import numpy as np import torch from mmengine.structures import InstanceData from mmengine.utils import digit_version from six.moves import map, zip from torch import Tensor from torch.autograd import Function from torch.nn import functional ...
Extract a multi-scale single image tensor from a multi-scale batch tensor based on batch index. Note: The default value of detach is True, because the proposal gradient needs to be detached during the training of the two-stage model. E.g Cascade Mask R-CNN. Args: mlvl_tensors (list[Tensor]): Batch tensor for all scale ...
14,863
from functools import partial from typing import List, Sequence, Tuple, Union import numpy as np import torch from mmengine.structures import InstanceData from mmengine.utils import digit_version from six.moves import map, zip from torch import Tensor from torch.autograd import Function from torch.nn import functional ...
Filter results using score threshold and topk candidates. Args: scores (Tensor): The scores, shape (num_bboxes, K). score_thr (float): The score filter threshold. topk (int): The number of topk candidates. results (dict or list or Tensor, Optional): The results to which the filtering rule is to be applied. The shape of...
14,864
from functools import partial from typing import List, Sequence, Tuple, Union import numpy as np import torch from mmengine.structures import InstanceData from mmengine.utils import digit_version from six.moves import map, zip from torch import Tensor from torch.autograd import Function from torch.nn import functional ...
Calculate the centroid coordinates of the mask. Args: mask (Tensor): The mask to be calculated, shape (h, w). esp (float): Avoid dividing by zero. Default: 1e-6. Returns: tuple[Tensor]: the coordinates of the center point of the mask. - center_h (Tensor): the center point of the height. - center_w (Tensor): the center ...
14,865
from functools import partial from typing import List, Sequence, Tuple, Union import numpy as np import torch from mmengine.structures import InstanceData from mmengine.utils import digit_version from six.moves import map, zip from torch import Tensor from torch.autograd import Function from torch.nn import functional ...
Generate the coordinate. Args: featmap_sizes (tuple): The feature to be calculated, of shape (N, C, W, H). device (str): The device where the feature will be put on. Returns: coord_feat (Tensor): The coordinate feature, of shape (N, 2, W, H).
14,866
from functools import partial from typing import List, Sequence, Tuple, Union import numpy as np import torch from mmengine.structures import InstanceData from mmengine.utils import digit_version from six.moves import map, zip from torch import Tensor from torch.autograd import Function from torch.nn import functional ...
Concat multi-level feature maps by image. [feature_level0, feature_level1...] -> [feature_image0, feature_image1...] Convert the shape of each element in mlvl_tensor from (N, C, H, W) to (N, H*W , C), then split the element to N elements with shape (H*W, C), and concat elements in same image of all level along first di...
14,867
from functools import partial from typing import List, Sequence, Tuple, Union import numpy as np import torch from mmengine.structures import InstanceData from mmengine.utils import digit_version from six.moves import map, zip from torch import Tensor from torch.autograd import Function from torch.nn import functional ...
Convert targets by image to targets by feature level. [target_img0, target_img1] -> [target_level0, target_level1, ...]
14,868
from functools import partial from typing import List, Sequence, Tuple, Union import numpy as np import torch from mmengine.structures import InstanceData from mmengine.utils import digit_version from six.moves import map, zip from torch import Tensor from torch.autograd import Function from torch.nn import functional ...
null
14,869
from functools import partial from typing import List, Sequence, Tuple, Union import numpy as np import torch from mmengine.structures import InstanceData from mmengine.utils import digit_version from six.moves import map, zip from torch import Tensor from torch.autograd import Function from torch.nn import functional ...
null
14,870
from functools import partial from typing import List, Sequence, Tuple, Union import numpy as np import torch from mmengine.structures import InstanceData from mmengine.utils import digit_version from six.moves import map, zip from torch import Tensor from torch.autograd import Function from torch.nn import functional ...
Filter ground truth (GT) instances by score and/or size. Args: batch_data_samples (SampleList): The Data Samples. It usually includes information such as `gt_instance`, `gt_panoptic_seg` and `gt_sem_seg`. score_thr (float): The score filter threshold. wh_thr (tuple): Minimum width and height of bbox. Returns: SampleLis...
14,871
from functools import partial from typing import List, Sequence, Tuple, Union import numpy as np import torch from mmengine.structures import InstanceData from mmengine.utils import digit_version from six.moves import map, zip from torch import Tensor from torch.autograd import Function from torch.nn import functional ...
Rename the key names in loss dict by adding a prefix. Args: prefix (str): The prefix for loss components. losses (dict): A dictionary of loss components. Returns: dict: A dictionary of loss components with prefix.
14,872
from functools import partial from typing import List, Sequence, Tuple, Union import numpy as np import torch from mmengine.structures import InstanceData from mmengine.utils import digit_version from six.moves import map, zip from torch import Tensor from torch.autograd import Function from torch.nn import functional ...
Reweight losses in the dict by weight. Args: losses (dict): A dictionary of loss components. weight (float): Weight for loss components. Returns: dict: A dictionary of weighted loss components.
14,873
from functools import partial from typing import List, Sequence, Tuple, Union import numpy as np import torch from mmengine.structures import InstanceData from mmengine.utils import digit_version from six.moves import map, zip from torch import Tensor from torch.autograd import Function from torch.nn import functional ...
Generate the relative coordinate maps with feat_stride. Args: locations (Tensor): The prior location of mask feature map. It has shape (num_priors, 2). centers (Tensor): The prior points of a object in all feature pyramid. It has shape (num_pos, 2) strides (Tensor): The prior strides of a object in all feature pyramid....
14,874
from functools import partial from typing import List, Sequence, Tuple, Union import numpy as np import torch from mmengine.structures import InstanceData from mmengine.utils import digit_version from six.moves import map, zip from torch import Tensor from torch.autograd import Function from torch.nn import functional ...
aligned bilinear, used in original implement in CondInst: https://github.com/aim-uofa/AdelaiDet/blob/\ c0b2092ce72442b0f40972f7c6dda8bb52c46d16/adet/utils/comm.py#L23
14,875
from functools import partial from typing import List, Sequence, Tuple, Union import numpy as np import torch from mmengine.structures import InstanceData from mmengine.utils import digit_version from six.moves import map, zip from torch import Tensor from torch.autograd import Function from torch.nn import functional ...
unfold_wo_center, used in original implement in BoxInst: https://github.com/aim-uofa/AdelaiDet/blob/\ 4a3a1f7372c35b48ebf5f6adc59f135a0fa28d60/\ adet/modeling/condinst/condinst.py#L53
14,876
from math import sqrt import torch import torch.nn.functional as F def gaussian2D(radius, sigma=1, dtype=torch.float32, device='cpu'): """Generate 2D gaussian kernel. Args: radius (int): Radius of gaussian kernel. sigma (int): Sigma of gaussian function. Default: 1. dtype (torch.dtype): ...
Generate 2D gaussian heatmap. Args: heatmap (Tensor): Input heatmap, the gaussian kernel will cover on it and maintain the max value. center (list[int]): Coord of gaussian kernel's center. radius (int): Radius of gaussian kernel. k (int): Coefficient of gaussian kernel. Default: 1. Returns: out_heatmap (Tensor): Update...
14,877
from math import sqrt import torch import torch.nn.functional as F The provided code snippet includes necessary dependencies for implementing the `gaussian_radius` function. Write a Python function `def gaussian_radius(det_size, min_overlap)` to solve the following problem: r"""Generate 2D gaussian radius. This functi...
r"""Generate 2D gaussian radius. This function is modified from the `official github repo <https://github.com/princeton-vl/CornerNet-Lite/blob/master/core/sample/ utils.py#L65>`_. Given ``min_overlap``, radius could computed by a quadratic equation according to Vieta's formulas. There are 3 cases for computing gaussian...
14,878
from math import sqrt import torch import torch.nn.functional as F The provided code snippet includes necessary dependencies for implementing the `get_local_maximum` function. Write a Python function `def get_local_maximum(heat, kernel=3)` to solve the following problem: Extract local maximum pixel with given kernel. ...
Extract local maximum pixel with given kernel. Args: heat (Tensor): Target heatmap. kernel (int): Kernel size of max pooling. Default: 3. Returns: heat (Tensor): A heatmap where local maximum pixels maintain its own value and other positions are 0.
14,879
from math import sqrt import torch import torch.nn.functional as F The provided code snippet includes necessary dependencies for implementing the `get_topk_from_heatmap` function. Write a Python function `def get_topk_from_heatmap(scores, k=20)` to solve the following problem: Get top k positions from heatmap. Args: s...
Get top k positions from heatmap. Args: scores (Tensor): Target heatmap with shape [batch, num_classes, height, width]. k (int): Target number. Default: 20. Returns: tuple[torch.Tensor]: Scores, indexes, categories and coords of topk keypoint. Containing following Tensors: - topk_scores (Tensor): Max scores of each top...
14,880
from math import sqrt import torch import torch.nn.functional as F def gather_feat(feat, ind, mask=None): """Gather feature according to index. Args: feat (Tensor): Target feature map. ind (Tensor): Target coord index. mask (Tensor | None): Mask of feature map. Default: None. Returns...
Transpose and gather feature according to index. Args: feat (Tensor): Target feature map. ind (Tensor): Target coord index. Returns: feat (Tensor): Transposed and gathered feature.
14,881
import torch from mmcv.ops import point_sample from torch import Tensor def get_uncertainty(mask_preds: Tensor, labels: Tensor) -> Tensor: """Estimate uncertainty based on pred logits. We estimate uncertainty as L1 distance between 0.0 and the logits prediction in 'mask_preds' for the foreground class in `c...
Get ``num_points`` most uncertain points with random points during train. Sample points in [0, 1] x [0, 1] coordinate space based on their uncertainty. The uncertainties are calculated for each point using 'get_uncertainty()' function that takes point's logit prediction as input. Args: mask_preds (Tensor): A tensor of ...
14,882
from typing import Tuple import torch from torch import Tensor The provided code snippet includes necessary dependencies for implementing the `preprocess_panoptic_gt` function. Write a Python function `def preprocess_panoptic_gt(gt_labels: Tensor, gt_masks: Tensor, gt_semantic_seg: Tensor, n...
Preprocess the ground truth for a image. Args: gt_labels (Tensor): Ground truth labels of each bbox, with shape (num_gts, ). gt_masks (BitmapMasks): Ground truth masks of each instances of a image, shape (num_gts, h, w). gt_semantic_seg (Tensor | None): Ground truth of semantic segmentation with the shape (1, h, w). [0...
14,883
import re from mmengine.config import Config The provided code snippet includes necessary dependencies for implementing the `replace_cfg_vals` function. Write a Python function `def replace_cfg_vals(ori_cfg)` to solve the following problem: Replace the string "${key}" with the corresponding value. Replace the "${key}"...
Replace the string "${key}" with the corresponding value. Replace the "${key}" with the value of ori_cfg.key in the config. And support replacing the chained ${key}. Such as, replace "${key0.key1}" with the value of cfg.key0.key1. Code is modified from `vars.py < https://github.com/microsoft/SoftTeacher/blob/main/ssod/...
14,884
import torch The provided code snippet includes necessary dependencies for implementing the `split_batch` function. Write a Python function `def split_batch(img, img_metas, kwargs)` to solve the following problem: Split data_batch by tags. Code is modified from <https://github.com/microsoft/SoftTeacher/blob/main/ssod/...
Split data_batch by tags. Code is modified from <https://github.com/microsoft/SoftTeacher/blob/main/ssod/utils/structure_utils.py> # noqa: E501 Args: img (Tensor): of shape (N, C, H, W) encoding input images. Typically these should be mean centered and std scaled. img_metas (list[dict]): List of image info dict where e...
14,885
import datetime import os import platform import warnings import cv2 import torch.multiprocessing as mp from mmengine import DefaultScope The provided code snippet includes necessary dependencies for implementing the `setup_multi_processes` function. Write a Python function `def setup_multi_processes(cfg)` to solve th...
Setup multi-processing environment variables.
14,886
import datetime import os import platform import warnings import cv2 import torch.multiprocessing as mp from mmengine import DefaultScope The provided code snippet includes necessary dependencies for implementing the `register_all_modules` function. Write a Python function `def register_all_modules(init_default_scope:...
Register all modules in mmdet into the registries. Args: init_default_scope (bool): Whether initialize the mmdet default scope. When `init_default_scope=True`, the global default scope will be set to `mmdet`, and all registries will build modules from mmdet's registry node. To understand more about the registry, please...
14,887
from mmengine.utils import get_git_hash from mmengine.utils.dl_utils import collect_env as collect_base_env import mmdet The provided code snippet includes necessary dependencies for implementing the `collect_env` function. Write a Python function `def collect_env()` to solve the following problem: Collect the informa...
Collect the information of the running environments.
14,888
import functools import pickle import warnings from collections import OrderedDict import numpy as np import torch import torch.distributed as dist from mmengine.dist import get_dist_info from torch._utils import (_flatten_dense_tensors, _take_tensors, _unflatten_dense_tensors) def _allreduce_...
Allreduce gradients. Args: params (list[torch.Parameters]): List of parameters of a model coalesce (bool, optional): Whether allreduce parameters as a whole. Defaults to True. bucket_size_mb (int, optional): Size of bucket, the unit is MB. Defaults to -1.
14,889
import functools import pickle import warnings from collections import OrderedDict import numpy as np import torch import torch.distributed as dist from mmengine.dist import get_dist_info from torch._utils import (_flatten_dense_tensors, _take_tensors, _unflatten_dense_tensors) The provided c...
Obtain the mean of tensor on different GPUs.
14,890
import functools import pickle import warnings from collections import OrderedDict import numpy as np import torch import torch.distributed as dist from mmengine.dist import get_dist_info from torch._utils import (_flatten_dense_tensors, _take_tensors, _unflatten_dense_tensors) The provided c...
Return a process group based on gloo backend, containing all the ranks The result is cached.
14,891
import functools import pickle import warnings from collections import OrderedDict import numpy as np import torch import torch.distributed as dist from mmengine.dist import get_dist_info from torch._utils import (_flatten_dense_tensors, _take_tensors, _unflatten_dense_tensors) def obj2tensor(...
Apply all reduce function for python dict object. The code is modified from https://github.com/Megvii- BaseDetection/YOLOX/blob/main/yolox/utils/allreduce_norm.py. NOTE: make sure that py_dict in different ranks has the same keys and the values should be in the same shape. Currently only supports nccl backend. Args: py...
14,892
import functools import pickle import warnings from collections import OrderedDict import numpy as np import torch import torch.distributed as dist from mmengine.dist import get_dist_info from torch._utils import (_flatten_dense_tensors, _take_tensors, _unflatten_dense_tensors) The provided c...
Make sure different ranks share the same seed. All workers must call this function, otherwise it will deadlock. This method is generally used in `DistributedSampler`, because the seed should be identical across all processes in the distributed group. In distributed sampling, different ranks should sample non-overlapped...
14,893
import asyncio import contextlib import logging import os import time from typing import List import torch logger = logging.getLogger(__name__) DEBUG_COMPLETED_TIME = bool(os.environ.get('DEBUG_COMPLETED_TIME', False)) The provided code snippet includes necessary dependencies for implementing the `completed` function....
Async context manager that waits for work to complete on given CUDA streams.
14,894
import asyncio import contextlib import logging import os import time from typing import List import torch logger = logging.getLogger(__name__) The provided code snippet includes necessary dependencies for implementing the `concurrent` function. Write a Python function `async def concurrent(streamqueue: asyncio.Queue,...
Run code concurrently in different streams. :param streamqueue: asyncio.Queue instance. Queue tasks define the pool of streams used for concurrent execution.
14,895
import glob import os import os.path as osp import warnings from typing import Union from mmengine.config import Config, ConfigDict from mmengine.logging import print_log The provided code snippet includes necessary dependencies for implementing the `find_latest_checkpoint` function. Write a Python function `def find_...
Find the latest checkpoint from the working directory. Args: path(str): The path to find checkpoints. suffix(str): File extension. Defaults to pth. Returns: latest_path(str | None): File path of the latest checkpoint. References: .. [1] https://github.com/microsoft/SoftTeacher /blob/main/ssod/utils/patch.py
14,896
import glob import os import os.path as osp import warnings from typing import Union from mmengine.config import Config, ConfigDict from mmengine.logging import print_log The provided code snippet includes necessary dependencies for implementing the `update_data_root` function. Write a Python function `def update_data...
Update data root according to env MMDET_DATASETS. If set env MMDET_DATASETS, update cfg.data_root according to MMDET_DATASETS. Otherwise, using cfg.data_root as default. Args: cfg (:obj:`Config`): The model config need to modify logger (logging.Logger | str | None): the way to print msg
14,897
import glob import os import os.path as osp import warnings from typing import Union from mmengine.config import Config, ConfigDict from mmengine.logging import print_log The provided code snippet includes necessary dependencies for implementing the `get_test_pipeline_cfg` function. Write a Python function `def get_te...
Get the test dataset pipeline from entire config. Args: cfg (str or :obj:`ConfigDict`): the entire config. Can be a config file or a ``ConfigDict``. Returns: :obj:`ConfigDict`: the config of test dataset.
14,898
import contextlib import sys import time import torch The provided code snippet includes necessary dependencies for implementing the `profile_time` function. Write a Python function `def profile_time(trace_name, name, enabled=True, stream=None, ...
Print time spent by CPU and GPU. Useful as a temporary context manager to find sweet spots of code suitable for async implementation.
14,899
import copy import time from functools import partial from typing import List, Optional, Union import numpy as np import torch import torch.nn as nn from mmcv.cnn import fuse_conv_bn from mmengine import MMLogger from mmengine.config import Config from mmengine.device import get_max_cuda_memory from mmengine.dist impor...
Custom round function.
14,900
import copy import time from functools import partial from typing import List, Optional, Union import numpy as np import torch import torch.nn as nn from mmcv.cnn import fuse_conv_bn from mmengine import MMLogger from mmengine.config import Config from mmengine.device import get_max_cuda_memory from mmengine.dist impor...
print process memory info.
14,901
import numpy as np The provided code snippet includes necessary dependencies for implementing the `ensure_rng` function. Write a Python function `def ensure_rng(rng=None)` to solve the following problem: Coerces input into a random number generator. If the input is None, then a global random state is returned. If the ...
Coerces input into a random number generator. If the input is None, then a global random state is returned. If the input is a numeric value, then that is used as a seed to construct a random state. Otherwise the input is returned as-is. Adapted from [1]_. Args: rng (int | numpy.random.RandomState | None): if None, then...
14,902
import warnings from collections import abc from contextlib import contextmanager from functools import wraps import torch from mmengine.logging import MMLogger The provided code snippet includes necessary dependencies for implementing the `cast_tensor_type` function. Write a Python function `def cast_tensor_type(inpu...
Recursively convert Tensor in inputs from ``src_type`` to ``dst_type``. Args: inputs: Inputs that to be casted. src_type (torch.dtype | torch.device): Source type. src_type (torch.dtype | torch.device): Destination type. Returns: The same type with inputs, but all contained Tensors have been cast.
14,903
import warnings from collections import abc from contextlib import contextmanager from functools import wraps import torch from mmengine.logging import MMLogger The provided code snippet includes necessary dependencies for implementing the `_ignore_torch_cuda_oom` function. Write a Python function `def _ignore_torch_c...
A context which ignores CUDA OOM exception from pytorch. Code is modified from <https://github.com/facebookresearch/detectron2/blob/main/detectron2/utils/memory.py> # noqa: E501
14,904
import copy import warnings from mmengine.config import ConfigDict def compat_runner_args(cfg): if 'runner' not in cfg: cfg.runner = ConfigDict({ 'type': 'EpochBasedRunner', 'max_epochs': cfg.total_epochs }) warnings.warn( 'config is now expected to have a...
This function would modify some filed to keep the compatibility of config. For example, it will move some args which will be deprecated to the correct fields.
14,905
import inspect from mmengine.logging import print_log def get_caller_name(): """Get name of caller method.""" # this_func_frame = inspect.stack()[0][0] # i.e., get_caller_name # callee_frame = inspect.stack()[1][0] # e.g., log_img_scale caller_frame = inspect.stack()[2][0] # e.g., caller of log_img_s...
Log image size. Args: img_scale (tuple): Image size to be logged. shape_order (str, optional): The order of image shape. 'hw' for (height, width) and 'wh' for (width, height). Defaults to 'hw'. skip_square (bool, optional): Whether to skip logging for square img_scale. Defaults to False. Returns: bool: Whether to have ...
14,906
import argparse import logging import os import os.path as osp from mmengine.config import Config, DictAction from mmengine.logging import print_log from mmengine.registry import RUNNERS from mmengine.runner import Runner from mmdet.utils import register_all_modules def parse_args(): parser = argparse.ArgumentPars...
null
14,907
import json import multiprocessing import os import sys from itertools import product from math import ceil import cv2 import numpy as np class PatchGenerator(object): def __init__(self, info, type='normal', data_dir='/home/liwenxi/panda/raw/PANDA/image_train', save_img_path='/home/liwenxi/panda/ra...
null
14,908
import json import multiprocessing import os import sys from itertools import product from math import ceil import cv2 import numpy as np class PatchGenerator(object): def __init__(self, info, type='normal', data_dir='/home/liwenxi/panda/raw/PANDA/image_train', save_img_path='/home/liwenxi/panda/ra...
null
14,909
import argparse import tempfile from functools import partial from pathlib import Path import torch from mmengine.config import Config, DictAction from mmengine.logging import MMLogger from mmengine.model import revert_sync_batchnorm from mmengine.registry import init_default_scope from mmengine.runner import Runner fr...
null
14,910
import argparse import tempfile from functools import partial from pathlib import Path import torch from mmengine.config import Config, DictAction from mmengine.logging import MMLogger from mmengine.model import revert_sync_batchnorm from mmengine.registry import init_default_scope from mmengine.runner import Runner fr...
null
14,911
import argparse import os.path as osp import numpy as np import torch from mmengine.config import Config from mmengine.fileio import dump from mmengine.logging import MMLogger from mmengine.utils import ProgressBar from scipy.optimize import differential_evolution from mmdet.registry import DATASETS from mmdet.structur...
null
14,912
import argparse import os import matplotlib.pyplot as plt import numpy as np from matplotlib.ticker import MultipleLocator from mmcv.ops import nms from mmengine import Config, DictAction from mmengine.fileio import load from mmengine.utils import ProgressBar from mmdet.evaluation import bbox_overlaps from mmdet.regist...
null
14,913
import argparse import os import matplotlib.pyplot as plt import numpy as np from matplotlib.ticker import MultipleLocator from mmcv.ops import nms from mmengine import Config, DictAction from mmengine.fileio import load from mmengine.utils import ProgressBar from mmdet.evaluation import bbox_overlaps from mmdet.regist...
Calculate the confusion matrix. Args: dataset (Dataset): Test or val dataset. results (list[ndarray]): A list of detection results in each image. score_thr (float|optional): Score threshold to filter bboxes. Default: 0. nms_iou_thr (float|optional): nms IoU threshold, the detection results have done nms in the detector...
14,914
import argparse import os import matplotlib.pyplot as plt import numpy as np from matplotlib.ticker import MultipleLocator from mmcv.ops import nms from mmengine import Config, DictAction from mmengine.fileio import load from mmengine.utils import ProgressBar from mmdet.evaluation import bbox_overlaps from mmdet.regist...
Draw confusion matrix with matplotlib. Args: confusion_matrix (ndarray): The confusion matrix. labels (list[str]): List of class names. save_dir (str|optional): If set, save the confusion matrix plot to the given path. Default: None. show (bool): Whether to show the plot. Default: True. title (str): Title of the plot. ...
14,915
import os.path as osp from argparse import ArgumentParser import numpy as np from mmengine.fileio import load def get_coco_style_results(filename, task='bbox', metric=None, prints='mPC', aggregate='benchmark'): ...
null
14,916
import os.path as osp from argparse import ArgumentParser import numpy as np from mmengine.fileio import load def get_distortions_from_results(eval_output): def get_distortions_from_file(filename): eval_output = load(filename) return get_distortions_from_results(eval_output)
null
14,917
import argparse import os.path as osp from mmengine.config import Config, DictAction from mmengine.utils import ProgressBar from mmdet.models.utils import mask2ndarray from mmdet.registry import DATASETS, VISUALIZERS from mmdet.structures.bbox import BaseBoxes from mmdet.utils import register_all_modules def parse_arg...
null
14,918
import argparse import mmengine from mmengine import Config, DictAction from mmengine.evaluator import Evaluator from mmdet.registry import DATASETS from mmdet.utils import register_all_modules def parse_args(): parser = argparse.ArgumentParser(description='Evaluate metric of the ' ...
null
14,919
import copy import os from argparse import ArgumentParser from multiprocessing import Pool import matplotlib.pyplot as plt import numpy as np from pycocotools.coco import COCO from pycocotools.cocoeval import COCOeval def makeplot(rs, ps, outDir, class_name, iou_type): cs = np.vstack([ np.ones((2, 3)), ...
null
14,920
import argparse import json from collections import defaultdict import matplotlib.pyplot as plt import numpy as np import seaborn as sns def cal_train_time(log_dicts, args): for i, log_dict in enumerate(log_dicts): print(f'{"-" * 5}Analyze train time of {args.json_logs[i]}{"-" * 5}') all_times = []...
null
14,921
import argparse import json from collections import defaultdict import matplotlib.pyplot as plt import numpy as np import seaborn as sns def plot_curve(log_dicts, args): if args.backend is not None: plt.switch_backend(args.backend) sns.set_style(args.style) # if legend is None, use {filename}_{key}...
null
14,922
import argparse import json from collections import defaultdict import matplotlib.pyplot as plt import numpy as np import seaborn as sns def add_plot_parser(subparsers): parser_plt = subparsers.add_parser( 'plot_curve', help='parser for plotting curves') parser_plt.add_argument( 'json_logs', ...
null
14,923
import argparse import json from collections import defaultdict import matplotlib.pyplot as plt import numpy as np import seaborn as sns def load_json_logs(json_logs): # load and convert json_logs to log_dict, key is epoch, value is a sub dict # keys of sub dict is different metrics, e.g. memory, bbox_mAP ...
null
14,924
import argparse import os from mmengine import MMLogger from mmengine.config import Config, DictAction from mmengine.dist import init_dist from mmengine.utils import mkdir_or_exist from mmdet.utils import register_all_modules from mmdet.utils.benchmark import (DataLoaderBenchmark, DatasetBenchmark, ...
null
14,925
import argparse import os from mmengine import MMLogger from mmengine.config import Config, DictAction from mmengine.dist import init_dist from mmengine.utils import mkdir_or_exist from mmdet.utils import register_all_modules from mmdet.utils.benchmark import (DataLoaderBenchmark, DatasetBenchmark, ...
null
14,926
import argparse import os from mmengine import MMLogger from mmengine.config import Config, DictAction from mmengine.dist import init_dist from mmengine.utils import mkdir_or_exist from mmdet.utils import register_all_modules from mmdet.utils.benchmark import (DataLoaderBenchmark, DatasetBenchmark, ...
null
14,927
import argparse import os from mmengine import MMLogger from mmengine.config import Config, DictAction from mmengine.dist import init_dist from mmengine.utils import mkdir_or_exist from mmdet.utils import register_all_modules from mmdet.utils.benchmark import (DataLoaderBenchmark, DatasetBenchmark, ...
null
14,928
import argparse import os.path as osp from multiprocessing import Pool import mmcv import numpy as np from mmengine.config import Config, DictAction from mmengine.fileio import load from mmengine.runner import Runner from mmengine.structures import InstanceData, PixelData from mmengine.utils import ProgressBar, check_f...
Evaluate mAP of single image det result. Args: det_result (list[list]): [[cls1_det, cls2_det, ...], ...]. The outer list indicates images, and the inner list indicates per-class detected bboxes. annotation (dict): Ground truth annotations where keys of annotations are: - bboxes: numpy array of shape (n, 4) - labels: nu...
14,929
import argparse import os.path as osp from multiprocessing import Pool import mmcv import numpy as np from mmengine.config import Config, DictAction from mmengine.fileio import load from mmengine.runner import Runner from mmengine.structures import InstanceData, PixelData from mmengine.utils import ProgressBar, check_f...
null
14,930
from itertools import product from math import ceil from pathlib import Path import warnings import glob import os import pickle import tqdm import mmcv import numpy as np import torch from mmcv.ops import RoIPool from mmcv.transforms import Compose from torch.utils.data import Dataset from mmcv.ops import nms from arg...
Get multiscale patch sizes and steps. Args: sizes (list): A list of patch sizes. steps (list): A list of steps to slide patches. ratios (list): Multiscale ratios. devidie to each size and step and generate patches in new scales. Returns: new_sizes (list): A list of multiscale patch sizes. new_steps (list): A list of st...
14,931
from itertools import product from math import ceil from pathlib import Path import warnings import glob import os import pickle import tqdm import mmcv import numpy as np import torch from mmcv.ops import RoIPool from mmcv.transforms import Compose from torch.utils.data import Dataset from mmcv.ops import nms from arg...
inference patches with the detector. Split huge image(s) into patches and inference them with the detector. Finally, merge patch results on one huge image by nms. Args: model (nn.Module): The loaded detector. img (str | ndarray or): Either an image file or loaded image. sizes (list): The sizes of patches. steps (list):...
14,932
from itertools import product from math import ceil from pathlib import Path import warnings import glob import os import pickle import tqdm import mmcv import numpy as np import torch from mmcv.ops import RoIPool from mmcv.transforms import Compose from torch.utils.data import Dataset from mmcv.ops import nms from arg...
null
14,933
import argparse from collections import OrderedDict import torch The provided code snippet includes necessary dependencies for implementing the `moco_convert` function. Write a Python function `def moco_convert(src, dst)` to solve the following problem: Convert keys in pycls pretrained moco models to mmdet style. Her...
Convert keys in pycls pretrained moco models to mmdet style.
14,934
import argparse import tempfile from collections import OrderedDict import torch from mmengine import Config def parse_config(config_strings): temp_file = tempfile.NamedTemporaryFile() config_path = f'{temp_file.name}.py' with open(config_path, 'w') as f: f.write(config_strings) config = Config....
null
14,935
import argparse from collections import OrderedDict import torch from mmengine.fileio import load arch_settings = {50: (3, 4, 6, 3), 101: (3, 4, 23, 3)} def convert_bn(blobs, state_dict, caffe_name, torch_name, converted_names): # detectron replace bn with affine channel layer state_dict[torch_name + '.bias'] =...
Convert keys in detectron pretrained ResNet models to pytorch style.
14,936
import argparse from collections import OrderedDict import torch from mmengine.fileio import load from mmengine.runner import save_checkpoint The provided code snippet includes necessary dependencies for implementing the `convert` function. Write a Python function `def convert(src: str, dst: str, prefix: str = 'd2_mod...
Convert Detectron2 checkpoint to MMDetection style. Args: src (str): The Detectron2 checkpoint path, should endswith `pkl`. dst (str): The MMDetection checkpoint path. prefix (str): The prefix of MMDetection model, defaults to 'd2_model'.
14,937
import argparse from collections import OrderedDict import torch def convert_stem(model_key, model_weight, state_dict, converted_names): new_key = model_key.replace('stem.conv', 'conv1') new_key = new_key.replace('stem.bn', 'bn1') state_dict[new_key] = model_weight converted_names.add(model_key) pri...
Convert keys in pycls pretrained RegNet models to mmdet style.
14,938
import argparse import re import tempfile from collections import OrderedDict import torch from mmengine import Config def is_head(key): valid_head_list = [ 'bbox_head', 'mask_head', 'semantic_head', 'grid_head', 'mask_iou_head' ] return any(key.startswith(h) for h in valid_head_list) def parse_conf...
Convert keys in checkpoints. There can be some breaking changes during the development of mmdetection, and this tool is used for upgrading checkpoints trained with old versions to the latest one.
14,939
import argparse import subprocess import torch from mmengine.logging import print_log def parse_args(): parser = argparse.ArgumentParser( description='Process a checkpoint to be published') parser.add_argument('in_file', help='input checkpoint filename') parser.add_argument('out_file', help='output...
null
14,940
import argparse import subprocess import torch from mmengine.logging import print_log def process_checkpoint(in_file, out_file, save_keys=['meta', 'state_dict']): checkpoint = torch.load(in_file, map_location='cpu') # only keep `meta` and `state_dict` for smaller file size ckpt_keys = list(checkpoint.keys...
null
14,941
import argparse import glob import os.path as osp import cityscapesscripts.helpers.labels as CSLabels import mmcv import numpy as np import pycocotools.mask as maskUtils from mmengine.fileio import dump from mmengine.utils import (Timer, mkdir_or_exist, track_parallel_progress, track_progres...
null
14,942
import argparse import glob import os.path as osp import cityscapesscripts.helpers.labels as CSLabels import mmcv import numpy as np import pycocotools.mask as maskUtils from mmengine.fileio import dump from mmengine.utils import (Timer, mkdir_or_exist, track_parallel_progress, track_progres...
null
14,943
import argparse import glob import os.path as osp import cityscapesscripts.helpers.labels as CSLabels import mmcv import numpy as np import pycocotools.mask as maskUtils from mmengine.fileio import dump from mmengine.utils import (Timer, mkdir_or_exist, track_parallel_progress, track_progres...
null
14,944
import argparse import glob import os.path as osp import cityscapesscripts.helpers.labels as CSLabels import mmcv import numpy as np import pycocotools.mask as maskUtils from mmengine.fileio import dump from mmengine.utils import (Timer, mkdir_or_exist, track_parallel_progress, track_progres...
null
14,945
import argparse import os.path as osp import xml.etree.ElementTree as ET import numpy as np from mmengine.fileio import dump, list_from_file from mmengine.utils import mkdir_or_exist, track_progress from mmdet.evaluation import voc_classes def parse_xml(args): xml_path, img_path = args tree = ET.parse(xml_path)...
null
14,946
import argparse import os.path as osp import xml.etree.ElementTree as ET import numpy as np from mmengine.fileio import dump, list_from_file from mmengine.utils import mkdir_or_exist, track_progress from mmdet.evaluation import voc_classes def parse_args(): parser = argparse.ArgumentParser( description='Co...
null
14,947
import argparse import os from mmengine.fileio import dump, list_from_file from mmengine.utils import mkdir_or_exist, scandir, track_iter_progress from PIL import Image def parse_args(): parser = argparse.ArgumentParser( description='Convert images to coco format without annotations') parser.add_argume...
null
14,948
import argparse import os from mmengine.fileio import dump, list_from_file from mmengine.utils import mkdir_or_exist, scandir, track_iter_progress from PIL import Image def collect_image_infos(path, exclude_extensions=None): img_infos = [] images_generator = scandir(path, recursive=True) for image_path in...
null
14,949
import argparse import os from mmengine.fileio import dump, list_from_file from mmengine.utils import mkdir_or_exist, scandir, track_iter_progress from PIL import Image def cvt_to_coco_json(img_infos, classes): image_id = 0 coco = dict() coco['images'] = [] coco['type'] = 'instance' coco['categorie...
null
14,950
import argparse import json import logging import os.path as osp from multiprocessing import Pool import mmcv from mmengine.config import Config from mmengine.fileio import FileClient, dump from mmengine.logging import print_log def parse_args(): parser = argparse.ArgumentParser(description='Collect image metas') ...
null
14,951
import argparse import json import logging import os.path as osp from multiprocessing import Pool import mmcv from mmengine.config import Config from mmengine.fileio import FileClient, dump from mmengine.logging import print_log def get_image_metas(anno_str, img_prefix): id_hw = {} file_client = FileClient(bac...
null
14,952
import argparse import tarfile from itertools import repeat from multiprocessing.pool import ThreadPool from pathlib import Path from tarfile import TarFile from zipfile import ZipFile import torch from mmengine.utils.path import mkdir_or_exist def parse_args(): parser = argparse.ArgumentParser( descriptio...
null
14,953
import argparse import tarfile from itertools import repeat from multiprocessing.pool import ThreadPool from pathlib import Path from tarfile import TarFile from zipfile import ZipFile import torch from mmengine.utils.path import mkdir_or_exist def download(url, dir, unzip=True, delete=False, threads=1): def down...
null
14,954
import argparse import tarfile from itertools import repeat from multiprocessing.pool import ThreadPool from pathlib import Path from tarfile import TarFile from zipfile import ZipFile import torch from mmengine.utils.path import mkdir_or_exist def download_objects365v2(url, dir, unzip=True, delete=False, threads=1): ...
null
14,955
import argparse import csv import os.path as osp from multiprocessing import Pool import mmcv from mmengine.config import Config from mmengine.fileio import FileClient, dump def parse_args(): parser = argparse.ArgumentParser(description='Collect image metas') parser.add_argument('config', help='Config file pat...
null