id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
14,655
import math import numpy as np import requests import torch import torch.nn as nn from PIL import Image, ImageDraw from utils.datasets import letterbox from utils.general import non_max_suppression, make_divisible, scale_coords, xyxy2xywh from utils.plots import color_list def channel_shuffle(x, groups): batchsize...
null
14,656
import glob import logging import math import os import random import shutil import time from itertools import repeat from multiprocessing.pool import ThreadPool from pathlib import Path from threading import Thread import cv2 import numpy as np import torch from PIL import Image, ExifTags from torch.utils.data import ...
null
14,657
import glob import logging import math import os import random import shutil import time from itertools import repeat from multiprocessing.pool import ThreadPool from pathlib import Path from threading import Thread import cv2 import numpy as np import torch from PIL import Image, ExifTags from torch.utils.data import ...
null
14,658
import glob import logging import math import os import random import shutil import time from itertools import repeat from multiprocessing.pool import ThreadPool from pathlib import Path from threading import Thread import cv2 import numpy as np import torch from PIL import Image, ExifTags from torch.utils.data import ...
null
14,659
import glob import logging import math import os import random import shutil import time from itertools import repeat from multiprocessing.pool import ThreadPool from pathlib import Path from threading import Thread import cv2 import numpy as np import torch from PIL import Image, ExifTags from torch.utils.data import ...
null
14,660
import glob import logging import math import os import random import shutil import time from itertools import repeat from multiprocessing.pool import ThreadPool from pathlib import Path from threading import Thread import cv2 import numpy as np import torch from PIL import Image, ExifTags from torch.utils.data import ...
null
14,661
import glob import logging import math import os import random import shutil import time from itertools import repeat from multiprocessing.pool import ThreadPool from pathlib import Path from threading import Thread import cv2 import numpy as np import torch from PIL import Image, ExifTags from torch.utils.data import ...
null
14,662
import glob import logging import math import os import random import shutil import time from itertools import repeat from multiprocessing.pool import ThreadPool from pathlib import Path from threading import Thread import cv2 import numpy as np import torch from PIL import Image, ExifTags from torch.utils.data import ...
null
14,663
import glob import logging import math import os import random import shutil import time from itertools import repeat from multiprocessing.pool import ThreadPool from pathlib import Path from threading import Thread import cv2 import numpy as np import torch from PIL import Image, ExifTags from torch.utils.data import ...
null
14,664
import glob import logging import math import os import random import shutil import time from itertools import repeat from multiprocessing.pool import ThreadPool from pathlib import Path from threading import Thread import cv2 import numpy as np import torch from PIL import Image, ExifTags from torch.utils.data import ...
null
14,665
import glob import logging import math import os import random import shutil import time from itertools import repeat from multiprocessing.pool import ThreadPool from pathlib import Path from threading import Thread import cv2 import numpy as np import torch from PIL import Image, ExifTags from torch.utils.data import ...
null
14,666
import glob import logging import math import os import random import shutil import time from itertools import repeat from multiprocessing.pool import ThreadPool from pathlib import Path from threading import Thread import cv2 import numpy as np import torch from PIL import Image, ExifTags from torch.utils.data import ...
Autosplit a dataset into train/val/test splits and save path/autosplit_*.txt files # Arguments path: Path to images directory weights: Train, val, test weights (list)
14,667
import json import sys from pathlib import Path import torch import yaml from tqdm import tqdm from utils.datasets import LoadImagesAndLabels from utils.datasets import img2label_paths from utils.general import colorstr, xywh2xyxy, check_dataset def check_wandb_config_file(data_config_file): wandb_config = '_wandb...
null
14,668
import json import sys from pathlib import Path import torch import yaml from tqdm import tqdm from utils.datasets import LoadImagesAndLabels from utils.datasets import img2label_paths from utils.general import colorstr, xywh2xyxy, check_dataset try: import wandb from wandb import init, finish except ImportErro...
null
14,669
import argparse import yaml from wandb_utils import WandbLogger class WandbLogger(): def __init__(self, opt, name, run_id, data_dict, job_type='Training'): # Pre-training routine -- self.job_type = job_type self.wandb, self.wandb_run, self.data_dict = wandb, None if not wandb else wandb.run...
null
14,670
import logging import math import os import subprocess import time from contextlib import contextmanager from copy import deepcopy from pathlib import Path import torch import torch.backends.cudnn as cudnn import torch.nn as nn import torch.nn.functional as F import torchvision logger = logging.getLogger(__name__) def ...
null
14,671
import logging import math import os import subprocess import time from contextlib import contextmanager from copy import deepcopy from pathlib import Path import torch import torch.backends.cudnn as cudnn import torch.nn as nn import torch.nn.functional as F import torchvision def initialize_weights(model): for m...
null
14,672
import logging import math import os import subprocess import time from contextlib import contextmanager from copy import deepcopy from pathlib import Path import torch import torch.backends.cudnn as cudnn import torch.nn as nn import torch.nn.functional as F import torchvision def find_modules(model, mclass=nn.Conv2d...
null
14,673
import logging import math import os import subprocess import time from contextlib import contextmanager from copy import deepcopy from pathlib import Path import torch import torch.backends.cudnn as cudnn import torch.nn as nn import torch.nn.functional as F import torchvision def sparsity(model): # Return global ...
null
14,674
import logging import math import os import subprocess import time from contextlib import contextmanager from copy import deepcopy from pathlib import Path import torch import torch.backends.cudnn as cudnn import torch.nn as nn import torch.nn.functional as F import torchvision def fuse_conv_and_bn(conv, bn): # Fu...
null
14,675
import logging import math import os import subprocess import time from contextlib import contextmanager from copy import deepcopy from pathlib import Path import torch import torch.backends.cudnn as cudnn import torch.nn as nn import torch.nn.functional as F import torchvision try: import thop # for FLOPS computa...
null
14,676
import logging import math import os import subprocess import time from contextlib import contextmanager from copy import deepcopy from pathlib import Path import torch import torch.backends.cudnn as cudnn import torch.nn as nn import torch.nn.functional as F import torchvision def load_classifier(name='resnet101', n=...
null
14,677
import logging import math import os import subprocess import time from contextlib import contextmanager from copy import deepcopy from pathlib import Path import torch import torch.backends.cudnn as cudnn import torch.nn as nn import torch.nn.functional as F import torchvision def scale_img(img, ratio=1.0, same_shape...
null
14,678
import logging import math import os import subprocess import time from contextlib import contextmanager from copy import deepcopy from pathlib import Path import torch import torch.backends.cudnn as cudnn import torch.nn as nn import torch.nn.functional as F import torchvision def copy_attr(a, b, include=(), exclude=...
null
14,679
import glob import logging import math import os import random import shutil import time from itertools import repeat from multiprocessing.pool import ThreadPool from pathlib import Path from threading import Thread import cv2 import numpy as np import torch import torch.nn.functional as F from PIL import Image, ExifTa...
null
14,680
import glob import logging import math import os import random import shutil import time from itertools import repeat from multiprocessing.pool import ThreadPool from pathlib import Path from threading import Thread import cv2 import numpy as np import torch import torch.nn.functional as F from PIL import Image, ExifTa...
null
14,681
import glob import logging import math import os import random import shutil import time from itertools import repeat from multiprocessing.pool import ThreadPool from pathlib import Path from threading import Thread import cv2 import numpy as np import torch import torch.nn.functional as F from PIL import Image, ExifTa...
null
14,682
import glob import logging import math import os import random import shutil import time from itertools import repeat from multiprocessing.pool import ThreadPool from pathlib import Path from threading import Thread import cv2 import numpy as np import torch import torch.nn.functional as F from PIL import Image, ExifTa...
null
14,683
import glob import logging import math import os import random import shutil import time from itertools import repeat from multiprocessing.pool import ThreadPool from pathlib import Path from threading import Thread import cv2 import numpy as np import torch import torch.nn.functional as F from PIL import Image, ExifTa...
null
14,684
import glob import logging import math import os import random import shutil import time from itertools import repeat from multiprocessing.pool import ThreadPool from pathlib import Path from threading import Thread import cv2 import numpy as np import torch import torch.nn.functional as F from PIL import Image, ExifTa...
null
14,685
import glob import logging import math import os import random import shutil import time from itertools import repeat from multiprocessing.pool import ThreadPool from pathlib import Path from threading import Thread import cv2 import numpy as np import torch import torch.nn.functional as F from PIL import Image, ExifTa...
null
14,686
import glob import logging import math import os import random import shutil import time from itertools import repeat from multiprocessing.pool import ThreadPool from pathlib import Path from threading import Thread import cv2 import numpy as np import torch import torch.nn.functional as F from PIL import Image, ExifTa...
null
14,687
import glob import logging import math import os import random import shutil import time from itertools import repeat from multiprocessing.pool import ThreadPool from pathlib import Path from threading import Thread import cv2 import numpy as np import torch import torch.nn.functional as F from PIL import Image, ExifTa...
null
14,688
import glob import logging import math import os import random import shutil import time from itertools import repeat from multiprocessing.pool import ThreadPool from pathlib import Path from threading import Thread import cv2 import numpy as np import torch import torch.nn.functional as F from PIL import Image, ExifTa...
null
14,689
import glob import logging import math import os import random import shutil import time from itertools import repeat from multiprocessing.pool import ThreadPool from pathlib import Path from threading import Thread import cv2 import numpy as np import torch import torch.nn.functional as F from PIL import Image, ExifTa...
Autosplit a dataset into train/val/test splits and save path/autosplit_*.txt files # Arguments path: Path to images directory weights: Train, val, test weights (list)
14,690
import os import platform import subprocess import time from pathlib import Path import requests import torch def get_token(cookie="./cookie"): with open(cookie) as f: for line in f: if "download" in line: return line.split()[-1] return "" def gdrive_download(id='16TiPfZj7ht...
null
14,691
import glob import math import os import random from copy import copy from pathlib import Path import cv2 import matplotlib import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns import torch import yaml from PIL import Image, ImageDraw from scipy.signal import butter, filtfilt fro...
null
14,692
import glob import math import os import random from copy import copy from pathlib import Path import cv2 import matplotlib import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns import torch import yaml from PIL import Image, ImageDraw from scipy.signal import butter, filtfilt fro...
null
14,693
import glob import math import os import random from copy import copy from pathlib import Path import cv2 import matplotlib import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns import torch import yaml from PIL import Image, ImageDraw from scipy.signal import butter, filtfilt fro...
null
14,694
import glob import math import os import random from copy import copy from pathlib import Path import cv2 import matplotlib import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns import torch import yaml from PIL import Image, ImageDraw from scipy.signal import butter, filtfilt fro...
null
14,695
import glob import math import os import random from copy import copy from pathlib import Path import cv2 import matplotlib import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns import torch import yaml from PIL import Image, ImageDraw from scipy.signal import butter, filtfilt fro...
null
14,696
import glob import math import os import random from copy import copy from pathlib import Path import cv2 import matplotlib import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns import torch import yaml from PIL import Image, ImageDraw from scipy.signal import butter, filtfilt fro...
null
14,697
import glob import math import os import random from copy import copy from pathlib import Path import cv2 import matplotlib import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns import torch import yaml from PIL import Image, ImageDraw from scipy.signal import butter, filtfilt fro...
null
14,698
import glob import math import os import random from copy import copy from pathlib import Path import cv2 import matplotlib import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns import torch import yaml from PIL import Image, ImageDraw from scipy.signal import butter, filtfilt fro...
null
14,699
import glob import math import os import random from copy import copy from pathlib import Path import cv2 import matplotlib import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns import torch import yaml from PIL import Image, ImageDraw from scipy.signal import butter, filtfilt fro...
null
14,700
import glob import math import os import random from copy import copy from pathlib import Path import cv2 import matplotlib import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns import torch import yaml from PIL import Image, ImageDraw from scipy.signal import butter, filtfilt fro...
null
14,701
import torch def decode_infer(output, stride): # logging.info(torch.tensor(output.shape[0])) # logging.info(output.shape) # # bz is batch-size # bz = tuple(torch.tensor(output.shape[0])) # gridsize = tuple(torch.tensor(output.shape[-1])) # logging.info(gridsize) sh = torch.tensor(output.sha...
null
14,702
import glob import logging import math import os import random import re import subprocess import time from pathlib import Path import cv2 import numpy as np import torch import torchvision import yaml from utils.google_utils import gsutil_getsize from utils.metrics import fitness from utils.torch_utils import init_tor...
null
14,703
import glob import logging import math import os import random import re import subprocess import time from pathlib import Path import cv2 import numpy as np import torch import torchvision import yaml from utils.google_utils import gsutil_getsize from utils.metrics import fitness from utils.torch_utils import init_tor...
null
14,704
import glob import logging import math import os import random import re import subprocess import time from pathlib import Path import cv2 import numpy as np import torch import torchvision import yaml from utils.google_utils import gsutil_getsize from utils.metrics import fitness from utils.torch_utils import init_tor...
null
14,705
import glob import logging import math import os import random import re import subprocess import time from pathlib import Path import cv2 import numpy as np import torch import torchvision import yaml from utils.google_utils import gsutil_getsize from utils.metrics import fitness from utils.torch_utils import init_tor...
null
14,706
import glob import logging import math import os import random import re import subprocess import time from pathlib import Path import cv2 import numpy as np import torch import torchvision import yaml from utils.google_utils import gsutil_getsize from utils.metrics import fitness from utils.torch_utils import init_tor...
null
14,707
import glob import logging import math import os import random import re import subprocess import time from pathlib import Path import cv2 import numpy as np import torch import torchvision import yaml from utils.google_utils import gsutil_getsize from utils.metrics import fitness from utils.torch_utils import init_tor...
null
14,708
import glob import logging import math import os import random import re import subprocess import time from pathlib import Path import cv2 import numpy as np import torch import torchvision import yaml from utils.google_utils import gsutil_getsize from utils.metrics import fitness from utils.torch_utils import init_tor...
null
14,709
import glob import logging import math import os import random import re import subprocess import time from pathlib import Path import cv2 import numpy as np import torch import torchvision import yaml from utils.google_utils import gsutil_getsize from utils.metrics import fitness from utils.torch_utils import init_tor...
null
14,710
import glob import logging import math import os import random import re import subprocess import time from pathlib import Path import cv2 import numpy as np import torch import torchvision import yaml from utils.google_utils import gsutil_getsize from utils.metrics import fitness from utils.torch_utils import init_tor...
null
14,711
import glob import logging import math import os import random import re import subprocess import time from pathlib import Path import cv2 import numpy as np import torch import torchvision import yaml from utils.google_utils import gsutil_getsize from utils.metrics import fitness from utils.torch_utils import init_tor...
null
14,712
import glob import logging import math import os import random import re import subprocess import time from pathlib import Path import cv2 import numpy as np import torch import torchvision import yaml from utils.google_utils import gsutil_getsize from utils.metrics import fitness from utils.torch_utils import init_tor...
Performs Non-Maximum Suppression (NMS) on inference results Returns: detections with shape: nx6 (x1, y1, x2, y2, conf, cls)
14,713
import glob import logging import math import os import random import re import subprocess import time from pathlib import Path import cv2 import numpy as np import torch import torchvision import yaml from utils.google_utils import gsutil_getsize from utils.metrics import fitness from utils.torch_utils import init_tor...
null
14,714
import glob import logging import math import os import random import re import subprocess import time from pathlib import Path import cv2 import numpy as np import torch import torchvision import yaml from utils.google_utils import gsutil_getsize from utils.metrics import fitness from utils.torch_utils import init_tor...
null
14,715
from pathlib import Path import matplotlib.pyplot as plt import numpy as np import torch from . import general def compute_ap(recall, precision): """ Compute the average precision, given the recall and precision curves # Arguments recall: The recall curve (list) precision: The precision curve...
Compute the average precision, given the recall and precision curves. Source: https://github.com/rafaelpadilla/Object-Detection-Metrics. # Arguments tp: True positives (nparray, nx1 or nx10). conf: Objectness value from 0-1 (nparray). pred_cls: Predicted object classes (nparray). target_cls: True object classes (nparra...
14,717
from typing import List, Optional, Sequence, Tuple, Union import numpy as np import torch from torch import Tensor from mmdet.structures.bbox import BaseBoxes The provided code snippet includes necessary dependencies for implementing the `find_inside_bboxes` function. Write a Python function `def find_inside_bboxes(bb...
Find bboxes as long as a part of bboxes is inside the image. Args: bboxes (Tensor): Shape (N, 4). img_h (int): Image height. img_w (int): Image width. Returns: Tensor: Index of the remaining bboxes.
14,718
from typing import List, Optional, Sequence, Tuple, Union import numpy as np import torch from torch import Tensor from mmdet.structures.bbox import BaseBoxes def bbox_flip(bboxes: Tensor, img_shape: Tuple[int], direction: str = 'horizontal') -> Tensor: """Flip bboxes horizontally or ver...
Map bboxes from the original image scale to testing scale.
14,719
from typing import List, Optional, Sequence, Tuple, Union import numpy as np import torch from torch import Tensor from mmdet.structures.bbox import BaseBoxes def bbox_flip(bboxes: Tensor, img_shape: Tuple[int], direction: str = 'horizontal') -> Tensor: """Flip bboxes horizontally or ver...
Map bboxes from testing scale to original image scale.
14,720
from typing import List, Optional, Sequence, Tuple, Union import numpy as np import torch from torch import Tensor from mmdet.structures.bbox import BaseBoxes def get_box_tensor(boxes: Union[Tensor, BaseBoxes]) -> Tensor: """Get tensor data from box type boxes. Args: boxes (Tensor or BaseBoxes): boxes w...
Convert a list of bboxes to roi format. Args: bbox_list (List[Union[Tensor, :obj:`BaseBoxes`]): a list of bboxes corresponding to a batch of images. Returns: Tensor: shape (n, box_dim + 1), where ``box_dim`` depends on the different box types. For example, If the box type in ``bbox_list`` is HorizontalBoxes, the output...
14,721
from typing import List, Optional, Sequence, Tuple, Union import numpy as np import torch from torch import Tensor from mmdet.structures.bbox import BaseBoxes The provided code snippet includes necessary dependencies for implementing the `roi2bbox` function. Write a Python function `def roi2bbox(rois: Tensor) -> List[...
Convert rois to bounding box format. Args: rois (Tensor): RoIs with the shape (n, 5) where the first column indicates batch id of each RoI. Returns: List[Tensor]: Converted boxes of corresponding rois.
14,722
from typing import List, Optional, Sequence, Tuple, Union import numpy as np import torch from torch import Tensor from mmdet.structures.bbox import BaseBoxes The provided code snippet includes necessary dependencies for implementing the `bbox2result` function. Write a Python function `def bbox2result(bboxes: Union[Te...
Convert detection results to a list of numpy arrays. Args: bboxes (Tensor | np.ndarray): shape (n, 5) labels (Tensor | np.ndarray): shape (n, ) num_classes (int): class number, including background class Returns: List(np.ndarray]): bbox results of each class
14,723
from typing import List, Optional, Sequence, Tuple, Union import numpy as np import torch from torch import Tensor from mmdet.structures.bbox import BaseBoxes The provided code snippet includes necessary dependencies for implementing the `distance2bbox` function. Write a Python function `def distance2bbox( points:...
Decode distance prediction to bounding box. Args: points (Tensor): Shape (B, N, 2) or (N, 2). distance (Tensor): Distance from the given point to 4 boundaries (left, top, right, bottom). Shape (B, N, 4) or (N, 4) max_shape (Union[Sequence[int], Tensor, Sequence[Sequence[int]]], optional): Maximum bounds for boxes, spec...
14,724
from typing import List, Optional, Sequence, Tuple, Union import numpy as np import torch from torch import Tensor from mmdet.structures.bbox import BaseBoxes The provided code snippet includes necessary dependencies for implementing the `bbox2distance` function. Write a Python function `def bbox2distance(points: Tens...
Decode bounding box based on distances. Args: points (Tensor): Shape (n, 2) or (b, n, 2), [x, y]. bbox (Tensor): Shape (n, 4) or (b, n, 4), "xyxy" format max_dis (float, optional): Upper bound of the distance. eps (float): a small value to ensure target < max_dis, instead <= Returns: Tensor: Decoded distances.
14,725
from typing import List, Optional, Sequence, Tuple, Union import numpy as np import torch from torch import Tensor from mmdet.structures.bbox import BaseBoxes The provided code snippet includes necessary dependencies for implementing the `bbox_rescale` function. Write a Python function `def bbox_rescale(bboxes: Tensor...
Rescale bounding box w.r.t. scale_factor. Args: bboxes (Tensor): Shape (n, 4) for bboxes or (n, 5) for rois scale_factor (float): rescale factor Returns: Tensor: Rescaled bboxes.
14,726
from typing import List, Optional, Sequence, Tuple, Union import numpy as np import torch from torch import Tensor from mmdet.structures.bbox import BaseBoxes The provided code snippet includes necessary dependencies for implementing the `bbox_cxcywh_to_xyxy` function. Write a Python function `def bbox_cxcywh_to_xyxy(...
Convert bbox coordinates from (cx, cy, w, h) to (x1, y1, x2, y2). Args: bbox (Tensor): Shape (n, 4) for bboxes. Returns: Tensor: Converted bboxes.
14,727
from typing import List, Optional, Sequence, Tuple, Union import numpy as np import torch from torch import Tensor from mmdet.structures.bbox import BaseBoxes The provided code snippet includes necessary dependencies for implementing the `bbox_xyxy_to_cxcywh` function. Write a Python function `def bbox_xyxy_to_cxcywh(...
Convert bbox coordinates from (x1, y1, x2, y2) to (cx, cy, w, h). Args: bbox (Tensor): Shape (n, 4) for bboxes. Returns: Tensor: Converted bboxes.
14,728
from typing import List, Optional, Sequence, Tuple, Union import numpy as np import torch from torch import Tensor from mmdet.structures.bbox import BaseBoxes def bbox2corner(bboxes: torch.Tensor) -> torch.Tensor: """Convert bbox coordinates from (x1, y1, x2, y2) to corners ((x1, y1), (x2, y1), (x1, y2), (x2, y...
Geometric transformation for bbox. Args: bboxes (Union[torch.Tensor, np.ndarray]): Shape (n, 4) for bboxes. homography_matrix (Union[torch.Tensor, np.ndarray]): Shape (3, 3) for geometric transformation. img_shape (Tuple[int, int], optional): Image shape. Defaults to None. Returns: Union[torch.Tensor, np.ndarray]: Conv...
14,729
from typing import List, Optional, Sequence, Tuple, Union import numpy as np import torch from torch import Tensor from mmdet.structures.bbox import BaseBoxes The provided code snippet includes necessary dependencies for implementing the `cat_boxes` function. Write a Python function `def cat_boxes(data_list: List[Unio...
Concatenate boxes with type of tensor or box type. Args: data_list (List[Union[Tensor, :obj:`BaseBoxes`]]): A list of tensors or box types need to be concatenated. dim (int): The dimension over which the box are concatenated. Defaults to 0. Returns: Union[Tensor, :obj`BaseBoxes`]: Concatenated results.
14,730
from typing import List, Optional, Sequence, Tuple, Union import numpy as np import torch from torch import Tensor from mmdet.structures.bbox import BaseBoxes The provided code snippet includes necessary dependencies for implementing the `stack_boxes` function. Write a Python function `def stack_boxes(data_list: List[...
Stack boxes with type of tensor or box type. Args: data_list (List[Union[Tensor, :obj:`BaseBoxes`]]): A list of tensors or box types need to be stacked. dim (int): The dimension over which the box are stacked. Defaults to 0. Returns: Union[Tensor, :obj`BaseBoxes`]: Stacked results.
14,731
from typing import List, Optional, Sequence, Tuple, Union import numpy as np import torch from torch import Tensor from mmdet.structures.bbox import BaseBoxes The provided code snippet includes necessary dependencies for implementing the `scale_boxes` function. Write a Python function `def scale_boxes(boxes: Union[Ten...
Scale boxes with type of tensor or box type. Args: boxes (Tensor or :obj:`BaseBoxes`): boxes need to be scaled. Its type can be a tensor or a box type. scale_factor (Tuple[float, float]): factors for scaling boxes. The length should be 2. Returns: Union[Tensor, :obj:`BaseBoxes`]: Scaled boxes.
14,732
from typing import List, Optional, Sequence, Tuple, Union import numpy as np import torch from torch import Tensor from mmdet.structures.bbox import BaseBoxes The provided code snippet includes necessary dependencies for implementing the `get_box_wh` function. Write a Python function `def get_box_wh(boxes: Union[Tenso...
Get the width and height of boxes with type of tensor or box type. Args: boxes (Tensor or :obj:`BaseBoxes`): boxes with type of tensor or box type. Returns: Tuple[Tensor, Tensor]: the width and height of boxes.
14,733
from typing import List, Optional, Sequence, Tuple, Union import numpy as np import torch from torch import Tensor from mmdet.structures.bbox import BaseBoxes The provided code snippet includes necessary dependencies for implementing the `empty_box_as` function. Write a Python function `def empty_box_as(boxes: Union[T...
Generate empty box according to input ``boxes` type and device. Args: boxes (Tensor or :obj:`BaseBoxes`): boxes with type of tensor or box type. Returns: Union[Tensor, BaseBoxes]: Generated empty box.
14,734
from typing import Callable, Optional, Tuple, Type, Union import numpy as np import torch from torch import Tensor from .base_boxes import BaseBoxes def _register_box(name: str, box_type: Type, force: bool = False) -> None: """Register a box type. Args: name (str): The name of box type. box_type...
Register a box type. A record will be added to ``bbox_types``, whose key is the box type name and value is the box type itself. Simultaneously, a reverse dictionary ``_box_type_to_name`` will be updated. It can be used as a decorator or a normal function. Args: name (str): The name of box type. bbox_type (type, Optiona...
14,735
from typing import Callable, Optional, Tuple, Type, Union import numpy as np import torch from torch import Tensor from .base_boxes import BaseBoxes def _register_box_converter(src_type: Union[str, type], dst_type: Union[str, type], converter: Callable, ...
Register a box converter. A record will be added to ``box_converter``, whose key is '{src_type_name}2{dst_type_name}' and value is the convert function. It can be used as a decorator or a normal function. Args: src_type (str or type): source box type name or class. dst_type (str or type): destination box type name or c...
14,736
from typing import Callable, Optional, Tuple, Type, Union import numpy as np import torch from torch import Tensor from .base_boxes import BaseBoxes BoxType = Union[np.ndarray, Tensor, BaseBoxes] box_converters: dict = {} def get_box_type(box_type: Union[str, type]) -> Tuple[str, type]: """get both box type name an...
Convert boxes from source type to destination type. If ``boxes`` is a instance of BaseBoxes, the ``src_type`` will be set as the type of ``boxes``. Args: boxes (np.ndarray or Tensor or :obj:`BaseBoxes`): boxes need to convert. src_type (str or type, Optional): source box type. Defaults to None. dst_type (str or type, O...
14,737
from typing import Callable, Optional, Tuple, Type, Union import numpy as np import torch from torch import Tensor from .base_boxes import BaseBoxes def get_box_type(box_type: Union[str, type]) -> Tuple[str, type]: """get both box type name and class. Args: box_type (str or type): Single box type name o...
A decorator which automatically casts results['gt_bboxes'] to the destination box type. It commenly used in mmdet.datasets.transforms to make the transforms up- compatible with the np.ndarray type of results['gt_bboxes']. The speed of processing of np.ndarray and BaseBoxes data are the same: - np.ndarray: 0.0509 img/s ...
14,738
import torch def fp16_clamp(x, min=None, max=None): if not x.is_cuda and x.dtype == torch.float16: # clamp for cpu float16, tensor fp16 has no clamp implementation return x.float().clamp(min, max).half() return x.clamp(min, max) The provided code snippet includes necessary dependencies for impl...
Calculate overlap between two set of bboxes. FP16 Contributed by https://github.com/open-mmlab/mmdetection/pull/4889 Note: Assume bboxes1 is M x 4, bboxes2 is N x 4, when mode is 'iou', there are some new generated variable when calculating IOU using bbox_overlaps function: 1) is_aligned is False area1: M x 1 area2: N ...
14,739
import numpy as np import pycocotools.mask as mask_util import torch from mmengine.utils import slice_list The provided code snippet includes necessary dependencies for implementing the `split_combined_polys` function. Write a Python function `def split_combined_polys(polys, poly_lens, polys_per_mask)` to solve the fo...
Split the combined 1-D polys into masks. A mask is represented as a list of polys, and a poly is represented as a 1-D array. In dataset, all masks are concatenated into a single 1-D tensor. Here we need to split the tensor into original representations. Args: polys (list): a list (length = image num) of 1-D tensors pol...
14,740
import numpy as np import pycocotools.mask as mask_util import torch from mmengine.utils import slice_list The provided code snippet includes necessary dependencies for implementing the `encode_mask_results` function. Write a Python function `def encode_mask_results(mask_results)` to solve the following problem: Encod...
Encode bitmap mask to RLE code. Args: mask_results (list): bitmap mask results. Returns: list | tuple: RLE encoded mask.
14,741
import numpy as np import pycocotools.mask as mask_util import torch from mmengine.utils import slice_list The provided code snippet includes necessary dependencies for implementing the `mask2bbox` function. Write a Python function `def mask2bbox(masks)` to solve the following problem: Obtain tight bounding boxes of b...
Obtain tight bounding boxes of binary masks. Args: masks (Tensor): Binary mask of shape (n, h, w). Returns: Tensor: Bboxe with shape (n, 4) of \ positive region in binary mask.
14,742
import itertools from abc import ABCMeta, abstractmethod from typing import Sequence, Type, TypeVar import cv2 import mmcv import numpy as np import pycocotools.mask as maskUtils import torch from mmcv.ops.roi_align import roi_align The provided code snippet includes necessary dependencies for implementing the `polygo...
Convert masks from the form of polygons to bitmaps. Args: polygons (list[ndarray]): masks in polygon representation height (int): mask height width (int): mask width Return: ndarray: the converted masks in bitmap representation
14,743
import itertools from abc import ABCMeta, abstractmethod from typing import Sequence, Type, TypeVar import cv2 import mmcv import numpy as np import pycocotools.mask as maskUtils import torch from mmcv.ops.roi_align import roi_align The provided code snippet includes necessary dependencies for implementing the `bitmap...
Convert masks from the form of bitmaps to polygons. Args: bitmap (ndarray): masks in bitmap representation. Return: list[ndarray]: the converted mask in polygon representation. bool: whether the mask has holes.
14,744
import numpy as np import torch from torch.nn.modules.utils import _pair def mask_target_single(pos_proposals, pos_assigned_gt_inds, gt_masks, cfg): """Compute mask target for each positive proposal in the image. Args: pos_proposals (Tensor): Positive proposals. pos_assigned_gt_inds (Tensor): As...
Compute mask target for positive proposals in multiple images. Args: pos_proposals_list (list[Tensor]): Positive proposals in multiple images, each has shape (num_pos, 4). pos_assigned_gt_inds_list (list[Tensor]): Assigned GT indices for each positive proposals, each has shape (num_pos,). gt_masks_list (list[:obj:`Base...
14,745
import copy import warnings from pathlib import Path from typing import Optional, Sequence, Union import numpy as np import torch import torch.nn as nn from mmcv.ops import RoIPool from mmcv.transforms import Compose from mmengine.config import Config from mmengine.runner import load_checkpoint from mmdet.registry impo...
Initialize a detector from config file. Args: config (str, :obj:`Path`, or :obj:`mmengine.Config`): Config file path, :obj:`Path`, or the config object. checkpoint (str, optional): Checkpoint path. If left as None, the model will not load any weights. palette (str): Color palette used for visualization. If palette is s...
14,746
import copy import warnings from pathlib import Path from typing import Optional, Sequence, Union import numpy as np import torch import torch.nn as nn from mmcv.ops import RoIPool from mmcv.transforms import Compose from mmengine.config import Config from mmengine.runner import load_checkpoint from mmdet.registry impo...
Inference image(s) with the detector. Args: model (nn.Module): The loaded detector. imgs (str, ndarray, Sequence[str/ndarray]): Either image files or loaded images. test_pipeline (:obj:`Compose`): Test pipeline. Returns: :obj:`DetDataSample` or list[:obj:`DetDataSample`]: If imgs is a list or tuple, the same length lis...
14,747
import copy import warnings from pathlib import Path from typing import Optional, Sequence, Union import numpy as np import torch import torch.nn as nn from mmcv.ops import RoIPool from mmcv.transforms import Compose from mmengine.config import Config from mmengine.runner import load_checkpoint from mmdet.registry impo...
Async inference image(s) with the detector. Args: model (nn.Module): The loaded detector. img (str | ndarray): Either image files or loaded images. Returns: Awaitable detection results.
14,748
from typing import List, Tuple, Union import mmcv import numpy as np from mmengine.utils import is_str The provided code snippet includes necessary dependencies for implementing the `palette_val` function. Write a Python function `def palette_val(palette: List[tuple]) -> List[tuple]` to solve the following problem: Co...
Convert palette to matplotlib palette. Args: palette (List[tuple]): A list of color tuples. Returns: List[tuple[float]]: A list of RGB matplotlib color tuples.
14,749
from typing import List, Tuple, Union import mmcv import numpy as np from mmengine.utils import is_str The provided code snippet includes necessary dependencies for implementing the `get_palette` function. Write a Python function `def get_palette(palette: Union[List[tuple], str, tuple], num_classes: in...
Get palette from various inputs. Args: palette (list[tuple] | str | tuple): palette inputs. num_classes (int): the number of classes. Returns: list[tuple[int]]: A list of color tuples.
14,750
from typing import List, Tuple, Union import mmcv import numpy as np from mmengine.utils import is_str The provided code snippet includes necessary dependencies for implementing the `_get_adaptive_scales` function. Write a Python function `def _get_adaptive_scales(areas: np.ndarray, min_area: ...
Get adaptive scales according to areas. The scale range is [0.5, 1.0]. When the area is less than ``min_area``, the scale is 0.5 while the area is larger than ``max_area``, the scale is 1.0. Args: areas (ndarray): The areas of bboxes or masks with the shape of (n, ). min_area (int): Lower bound areas for adaptive scale...
14,751
from typing import List, Tuple, Union import mmcv import numpy as np from mmengine.utils import is_str The provided code snippet includes necessary dependencies for implementing the `jitter_color` function. Write a Python function `def jitter_color(color: tuple) -> tuple` to solve the following problem: Randomly jitte...
Randomly jitter the given color in order to better distinguish instances with the same class. Args: color (tuple): The RGB color tuple. Each value is between [0, 255]. Returns: tuple: The jittered color tuple.
14,752
import datetime import itertools import os.path as osp import tempfile from typing import Dict, Optional, Sequence, Tuple, Union import mmcv import numpy as np from mmengine.evaluator import BaseMetric from mmengine.fileio import FileClient, dump, load from mmengine.logging import MMLogger, print_log from terminaltable...
Parse the Panoptic Quality results. Args: pq_results (dict): Panoptic Quality results. Returns: dict: Panoptic Quality results parsed.
14,753
import datetime import itertools import os.path as osp import tempfile from typing import Dict, Optional, Sequence, Tuple, Union import mmcv import numpy as np from mmengine.evaluator import BaseMetric from mmengine.fileio import FileClient, dump, load from mmengine.logging import MMLogger, print_log from terminaltable...
Print the panoptic evaluation results table. Args: pq_results(dict): The Panoptic Quality results. classwise_results(dict, optional): The classwise Panoptic Quality. results. The keys are class names and the values are metrics. Defaults to None. logger (:obj:`MMLogger` | str, optional): Logger used for printing related...
14,754
from mmengine.utils import is_str The provided code snippet includes necessary dependencies for implementing the `wider_face_classes` function. Write a Python function `def wider_face_classes() -> list` to solve the following problem: Class names of WIDERFace. Here is the function: def wider_face_classes() -> list: ...
Class names of WIDERFace.
14,755
from mmengine.utils import is_str The provided code snippet includes necessary dependencies for implementing the `voc_classes` function. Write a Python function `def voc_classes() -> list` to solve the following problem: Class names of PASCAL VOC. Here is the function: def voc_classes() -> list: """Class names o...
Class names of PASCAL VOC.