id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
7,349
import torch from mmcv.ops import convex_iou, points_in_polygons from mmdet.core.bbox.assigners.assign_result import AssignResult from mmdet.core.bbox.assigners.base_assigner import BaseAssigner from ..builder import ROTATED_BBOX_ASSIGNERS The provided code snippet includes necessary dependencies for implementing the ...
Compute overlaps between polygons and points. Args: gt_rbboxes (torch.Tensor): Groundtruth polygons, shape (k, 8). points (torch.Tensor): Points to be assigned, shape(n, 18). Returns: overlaps (torch.Tensor): Overlaps between k gt_bboxes and n bboxes, shape(k, n).
7,350
import torch from mmcv.ops import convex_iou, points_in_polygons from mmdet.core.bbox.assigners.assign_result import AssignResult from mmdet.core.bbox.assigners.base_assigner import BaseAssigner from ..builder import ROTATED_BBOX_ASSIGNERS The provided code snippet includes necessary dependencies for implementing the ...
Get horizontal bboxes from polygons. Args: gt_rbboxes (torch.Tensor): Groundtruth polygons, shape (k, 8). Returns: gt_rect_bboxes (torch.Tensor): The horizontal bboxes, shape (k, 4).
7,351
import torch from mmcv.ops import convex_iou, points_in_polygons from mmdet.core.bbox.assigners.assign_result import AssignResult from mmdet.core.bbox.assigners.base_assigner import BaseAssigner from ..builder import ROTATED_BBOX_ASSIGNERS The provided code snippet includes necessary dependencies for implementing the ...
Compute the aspect ratio of all gts. Args: gt_rbboxes (torch.Tensor): Groundtruth polygons, shape (k, 8). Returns: ratios (torch.Tensor): The aspect ratio of gt_rbboxes, shape (k, 1).
7,352
from mmcv.ops import box_iou_rotated from .builder import ROTATED_IOU_CALCULATORS The provided code snippet includes necessary dependencies for implementing the `rbbox_overlaps` function. Write a Python function `def rbbox_overlaps(bboxes1, bboxes2, mode='iou', is_aligned=False)` to solve the following problem: Calcul...
Calculate overlap between two set of bboxes. Args: bboxes1 (torch.Tensor): shape (B, m, 5) in <cx, cy, w, h, a> format or empty. bboxes2 (torch.Tensor): shape (B, n, 5) in <cx, cy, w, h, a> format or empty. mode (str): "iou" (intersection over union), "iof" (intersection over foreground) or "giou" (generalized intersec...
7,353
from mmcv.utils import build_from_cfg from mmdet.core.bbox.iou_calculators.builder import IOU_CALCULATORS ROTATED_IOU_CALCULATORS = IOU_CALCULATORS The provided code snippet includes necessary dependencies for implementing the `build_iou_calculator` function. Write a Python function `def build_iou_calculator(cfg, defa...
Builder of IoU calculator.
7,354
from mmcv.utils import build_from_cfg from mmdet.core.bbox.builder import BBOX_ASSIGNERS, BBOX_CODERS, BBOX_SAMPLERS ROTATED_BBOX_ASSIGNERS = BBOX_ASSIGNERS The provided code snippet includes necessary dependencies for implementing the `build_assigner` function. Write a Python function `def build_assigner(cfg, **defau...
Builder of box assigner.
7,355
from mmcv.utils import build_from_cfg from mmdet.core.bbox.builder import BBOX_ASSIGNERS, BBOX_CODERS, BBOX_SAMPLERS ROTATED_BBOX_SAMPLERS = BBOX_SAMPLERS The provided code snippet includes necessary dependencies for implementing the `build_sampler` function. Write a Python function `def build_sampler(cfg, **default_a...
Builder of box sampler.
7,356
from mmcv.utils import build_from_cfg from mmdet.core.bbox.builder import BBOX_ASSIGNERS, BBOX_CODERS, BBOX_SAMPLERS ROTATED_BBOX_CODERS = BBOX_CODERS The provided code snippet includes necessary dependencies for implementing the `build_bbox_coder` function. Write a Python function `def build_bbox_coder(cfg, **default...
Builder of box coder.
7,357
The provided code snippet includes necessary dependencies for implementing the `rotated_anchor_inside_flags` function. Write a Python function `def rotated_anchor_inside_flags(flat_anchors, valid_flags, img_shape, allowed_...
Check whether the rotated anchors are inside the border. Args: flat_anchors (torch.Tensor): Flatten anchors, shape (n, 5). valid_flags (torch.Tensor): An existing valid flags of anchors. img_shape (tuple(int)): Shape of current image. allowed_border (int, optional): The border to allow the valid anchor. Defaults to 0. ...
7,358
from mmcv.utils import build_from_cfg from mmdet.core.anchor.builder import ANCHOR_GENERATORS ROTATED_ANCHOR_GENERATORS = ANCHOR_GENERATORS def build_prior_generator(cfg, default_args=None): return build_from_cfg(cfg, ROTATED_ANCHOR_GENERATORS, default_args)
null
7,359
import numpy as np import torch from mmcv.ops import nms, nms_rotated def translate_bboxes(bboxes, offset): """Translate bboxes according to its shape. If the bbox shape is (n, 5), the bboxes are regarded as horizontal bboxes and in (x, y, x, y, score) format. If the bbox shape is (n, 6), the bboxes are...
Merge patch results via nms. Args: results (list[np.ndarray] | list[tuple]): A list of patches results. offsets (np.ndarray): Positions of the left top points of patches. img_shape (tuple): A tuple of the huge image's width and height. iou_thr (float): The IoU threshold of NMS. device (str): The device to call nms. Ret...
7,360
from itertools import product from math import ceil import numpy as np The provided code snippet includes necessary dependencies for implementing the `get_multiscale_patch` function. Write a Python function `def get_multiscale_patch(sizes, steps, ratios)` to solve the following problem: Get multiscale patch sizes and ...
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...
7,361
from itertools import product from math import ceil import numpy as np The provided code snippet includes necessary dependencies for implementing the `slide_window` function. Write a Python function `def slide_window(width, height, sizes, steps, img_rate_thr=0.6)` to solve the following problem: Slide windows in image...
Slide windows in images and get window position. Args: width (int): The width of the image. height (int): The height of the image. sizes (list): List of window's sizes. steps (list): List of window's steps. img_rate_thr (float): Threshold of window area divided by image area. Returns: np.ndarray: Information of valid w...
7,362
import cv2 import matplotlib.pyplot as plt import mmcv import numpy as np from matplotlib.collections import PatchCollection from matplotlib.patches import Polygon from mmdet.core.visualization import palette_val from mmdet.core.visualization.image import draw_labels, draw_masks from mmrotate.core.visualization.palette...
Draw bboxes and class labels (with scores) on an image. Args: img (str | ndarray): The image to be displayed. bboxes (ndarray): Bounding boxes (with scores), shaped (n, 5) or (n, 6). labels (ndarray): Labels of bboxes. segms (ndarray | None): Masks, shaped (n,h,w) or None. class_names (list[str]): Names of each classes...
7,363
from multiprocessing import get_context import numpy as np import torch from mmcv.ops import box_iou_rotated from mmcv.utils import print_log from mmdet.core import average_precision from terminaltables import AsciiTable def tpfp_default(det_bboxes, gt_bboxes, gt_bboxes_ignore=None, ...
Evaluate mAP of a rotated dataset. Args: det_results (list[list]): [[cls1_det, cls2_det, ...], ...]. The outer list indicates images, and the inner list indicates per-class detected bboxes. annotations (list[dict]): Ground truth annotations where each item of the list indicates an image. Keys of annotations are: - `bbo...
7,364
import torch from mmcv.ops import nms_rotated The provided code snippet includes necessary dependencies for implementing the `multiclass_nms_rotated` function. Write a Python function `def multiclass_nms_rotated(multi_bboxes, multi_scores, score_thr, ...
NMS for multi-class bboxes. Args: multi_bboxes (torch.Tensor): shape (n, #class*5) or (n, 5) multi_scores (torch.Tensor): shape (n, #class), where the last column contains scores of the background class, but this will be ignored. score_thr (float): bbox threshold, bboxes with scores lower than it will not be considered...
7,365
import torch from mmcv.ops import nms_rotated The provided code snippet includes necessary dependencies for implementing the `aug_multiclass_nms_rotated` function. Write a Python function `def aug_multiclass_nms_rotated(merged_bboxes, merged_labels, score_thr, nms, max_num, classes)` to ...
NMS for aug multi-class bboxes. Args: multi_bboxes (torch.Tensor): shape (n, #class*5) or (n, 5) multi_scores (torch.Tensor): shape (n, #class), where the last column contains scores of the background class, but this will be ignored. score_thr (float): bbox threshold, bboxes with scores lower than it will not be consid...
7,366
import copy import platform from mmcv.utils import build_from_cfg from mmdet.datasets import DATASETS, PIPELINES from mmdet.datasets.builder import _concat_dataset ROTATED_DATASETS = DATASETS def build_dataset(cfg, default_args=None): from mmdet.datasets.dataset_wrappers import (ClassBalancedDataset, ...
null
7,367
import glob import os import os.path as osp import re import tempfile import time import warnings import zipfile from collections import defaultdict from functools import partial import mmcv import numpy as np import torch from mmcv.ops import nms_rotated from mmdet.datasets.custom import CustomDataset from mmrotate.co...
Merging patch bboxes into full image. Args: CLASSES (list): Label category. iou_thr (float): Threshold of IoU.
7,368
import torch import torch.nn as nn from mmdet.models.losses.utils import weighted_loss from mmrotate.core import GaussianMixture, gt2gaussian from ..builder import ROTATED_LOSSES def kld_single2single(g1, g2): """Compute Kullback-Leibler Divergence. Args: g1 (dict[str, torch.Tensor]): Gaussian distribut...
Kullback-Leibler Divergence loss. Args: pred (torch.Tensor): Convexes with shape (N, 9, 2). target (torch.Tensor): Polygons with shape (N, 4, 2). eps (float): Defaults to 1e-6. Returns: torch.Tensor: Kullback-Leibler Divergence loss.
7,369
from copy import deepcopy import torch from mmdet.models.losses.utils import weighted_loss from torch import nn from ..builder import ROTATED_LOSSES The provided code snippet includes necessary dependencies for implementing the `xy_wh_r_2_xy_sigma` function. Write a Python function `def xy_wh_r_2_xy_sigma(xywhr)` to s...
Convert oriented bounding box to 2-D Gaussian distribution. Args: xywhr (torch.Tensor): rbboxes with shape (N, 5). Returns: xy (torch.Tensor): center point of 2-D Gaussian distribution with shape (N, 2). sigma (torch.Tensor): covariance matrix of 2-D Gaussian distribution with shape (N, 2, 2).
7,370
from copy import deepcopy import torch from mmdet.models.losses.utils import weighted_loss from torch import nn from ..builder import ROTATED_LOSSES The provided code snippet includes necessary dependencies for implementing the `xy_stddev_pearson_2_xy_sigma` function. Write a Python function `def xy_stddev_pearson_2_x...
Convert oriented bounding box from the Pearson coordinate system to 2-D Gaussian distribution. Args: xy_stddev_pearson (torch.Tensor): rbboxes with shape (N, 5). Returns: xy (torch.Tensor): center point of 2-D Gaussian distribution with shape (N, 2). sigma (torch.Tensor): covariance matrix of 2-D Gaussian distribution ...
7,371
from copy import deepcopy import torch from mmdet.models.losses.utils import weighted_loss from torch import nn from ..builder import ROTATED_LOSSES def postprocess(distance, fun='log1p', tau=1.0): """Convert distance to loss. Args: distance (torch.Tensor) fun (str, optional): The function appli...
Gaussian Wasserstein distance loss. Derivation and simplification: Given any positive-definite symmetrical 2*2 matrix Z: :math:`Tr(Z^{1/2}) = λ_1^{1/2} + λ_2^{1/2}` where :math:`λ_1` and :math:`λ_2` are the eigen values of Z Meanwhile we have: :math:`Tr(Z) = λ_1 + λ_2` :math:`det(Z) = λ_1 * λ_2` Combination with follow...
7,372
from copy import deepcopy import torch from mmdet.models.losses.utils import weighted_loss from torch import nn from ..builder import ROTATED_LOSSES def postprocess(distance, fun='log1p', tau=1.0): """Convert distance to loss. Args: distance (torch.Tensor) fun (str, optional): The function appli...
Symmetrical Kullback-Leibler Divergence loss. Args: pred (torch.Tensor): Predicted bboxes. target (torch.Tensor): Corresponding gt bboxes. fun (str): The function applied to distance. Defaults to 'log1p'. tau (float): Defaults to 1.0. alpha (float): Defaults to 1.0. sqrt (bool): Whether to sqrt the distance. Defaults t...
7,373
from copy import deepcopy import torch from mmdet.models.losses.utils import weighted_loss from torch import nn from ..builder import ROTATED_LOSSES def postprocess(distance, fun='log1p', tau=1.0): """Convert distance to loss. Args: distance (torch.Tensor) fun (str, optional): The function appli...
Symmetrical Max Kullback-Leibler Divergence loss. Args: pred (torch.Tensor): Predicted bboxes. target (torch.Tensor): Corresponding gt bboxes. fun (str): The function applied to distance. Defaults to 'log1p'. tau (float): Defaults to 1.0. alpha (float): Defaults to 1.0. sqrt (bool): Whether to sqrt the distance. Defaul...
7,374
from copy import deepcopy import torch from mmdet.models.losses.utils import weighted_loss from torch import nn from ..builder import ROTATED_LOSSES def postprocess(distance, fun='log1p', tau=1.0): """Convert distance to loss. Args: distance (torch.Tensor) fun (str, optional): The function appli...
Symmetrical Min Kullback-Leibler Divergence loss. Args: pred (torch.Tensor): Predicted bboxes. target (torch.Tensor): Corresponding gt bboxes. fun (str): The function applied to distance. Defaults to 'log1p'. tau (float): Defaults to 1.0. alpha (float): Defaults to 1.0. sqrt (bool): Whether to sqrt the distance. Defaul...
7,375
import torch import torch.nn as nn from mmcv.ops import convex_giou from torch.autograd import Function from torch.autograd.function import once_differentiable from ..builder import ROTATED_LOSSES The provided code snippet includes necessary dependencies for implementing the `AspectRatio` function. Write a Python func...
Compute the aspect ratio of all gts. Args: gt_rbboxes (torch.Tensor): Groundtruth polygons, shape (k, 8). Returns: ratios (torch.Tensor): The aspect ratio of gt_rbboxes, shape (k, 1).
7,376
import warnings import torch import torch.nn as nn from mmdet.models.losses.utils import weighted_loss from ..builder import ROTATED_LOSSES The provided code snippet includes necessary dependencies for implementing the `rotated_iou_loss` function. Write a Python function `def rotated_iou_loss(pred, target, linear=Fals...
Rotated IoU loss. Computing the IoU loss between a set of predicted rbboxes and target rbboxes. The loss is calculated as negative log of IoU. Args: pred (torch.Tensor): Predicted bboxes of format (x, y, h, w, angle), shape (n, 5). target (torch.Tensor): Corresponding gt bboxes, shape (n, 5). linear (bool, optional): I...
7,377
import torch import torch.nn as nn from mmcv.ops import points_in_polygons from ..builder import ROTATED_LOSSES def spatial_border_loss(pts, gt_bboxes): """The loss is used to penalize the learning points out of the assigned ground truth boxes (polygon by default). Args: pts (torch.Tensor): point se...
Weghted spatial border loss. Args: pts (torch.Tensor): point sets with shape (N, 9*2). gt_bboxes (torch.Tensor): gt_bboxes with polygon form with shape(N, 8) weight (torch.Tensor): weights for point sets with shape (N) Returns: loss (torch.Tensor)
7,378
import torch from mmdet.models.losses.utils import weighted_loss from torch import nn from ..builder import ROTATED_LOSSES def xy_wh_r_2_xy_sigma(xywhr): """Convert oriented bounding box to 2-D Gaussian distribution. Args: xywhr (torch.Tensor): rbboxes with shape (N, 5). Returns: xy (torch.T...
Kalman filter IoU loss. Args: pred (torch.Tensor): Predicted bboxes. target (torch.Tensor): Corresponding gt bboxes. pred_decode (torch.Tensor): Predicted decode bboxes. targets_decode (torch.Tensor): Corresponding gt decode bboxes. fun (str): The function applied to distance. Defaults to None. beta (float): Defaults t...
7,379
from copy import deepcopy import torch from torch import nn from ..builder import ROTATED_LOSSES The provided code snippet includes necessary dependencies for implementing the `xy_wh_r_2_xy_sigma` function. Write a Python function `def xy_wh_r_2_xy_sigma(xywhr)` to solve the following problem: Convert oriented boundin...
Convert oriented bounding box to 2-D Gaussian distribution. Args: xywhr (torch.Tensor): rbboxes with shape (N, 5). Returns: xy (torch.Tensor): center point of 2-D Gaussian distribution with shape (N, 2). sigma (torch.Tensor): covariance matrix of 2-D Gaussian distribution with shape (N, 2, 2).
7,380
from copy import deepcopy import torch from torch import nn from ..builder import ROTATED_LOSSES The provided code snippet includes necessary dependencies for implementing the `gwd_loss` function. Write a Python function `def gwd_loss(pred, target, fun='sqrt', tau=2.0)` to solve the following problem: Gaussian Wassers...
Gaussian Wasserstein distance loss. Args: pred (torch.Tensor): Predicted bboxes. target (torch.Tensor): Corresponding gt bboxes. fun (str): The function applied to distance. Defaults to 'log1p'. tau (float): Defaults to 1.0. Returns: loss (torch.Tensor)
7,381
from copy import deepcopy import torch from torch import nn from ..builder import ROTATED_LOSSES The provided code snippet includes necessary dependencies for implementing the `bcd_loss` function. Write a Python function `def bcd_loss(pred, target, fun='log1p', tau=1.0)` to solve the following problem: Bhatacharyya di...
Bhatacharyya distance loss. Args: pred (torch.Tensor): Predicted bboxes. target (torch.Tensor): Corresponding gt bboxes. fun (str): The function applied to distance. Defaults to 'log1p'. tau (float): Defaults to 1.0. Returns: loss (torch.Tensor)
7,382
from copy import deepcopy import torch from torch import nn from ..builder import ROTATED_LOSSES The provided code snippet includes necessary dependencies for implementing the `kld_loss` function. Write a Python function `def kld_loss(pred, target, fun='log1p', tau=1.0)` to solve the following problem: Kullback-Leible...
Kullback-Leibler Divergence loss. Args: pred (torch.Tensor): Predicted bboxes. target (torch.Tensor): Corresponding gt bboxes. fun (str): The function applied to distance. Defaults to 'log1p'. tau (float): Defaults to 1.0. Returns: loss (torch.Tensor)
7,383
import torch.nn as nn import torch.nn.functional as F from mmdet.models import weight_reduce_loss from ..builder import ROTATED_LOSSES The provided code snippet includes necessary dependencies for implementing the `smooth_focal_loss` function. Write a Python function `def smooth_focal_loss(pred, ...
Smooth Focal Loss proposed in Circular Smooth Label (CSL). Args: pred (torch.Tensor): The prediction. target (torch.Tensor): The learning label of the prediction. weight (torch.Tensor, optional): The weight of loss for each prediction. Defaults to None. gamma (float, optional): The gamma for calculating the modulating ...
7,384
import math import numpy as np import torch import torch.nn as nn from mmcv.cnn import ConvModule from mmcv.ops import DeformConv2d, chamfer_distance, min_area_polygons from mmcv.runner import force_fp32 from mmdet.core import images_to_levels, multi_apply, unmap from mmdet.core.anchor.point_generator import MlvlPointG...
Compute the Chamfer distance between two point sets. Args: point_set_1 (torch.tensor): point set 1 with shape (N_pointsets, N_points, 2) point_set_2 (torch.tensor): point set 2 with shape (N_pointsets, N_points, 2) Returns: dist (torch.tensor): chamfer distance between two point sets with shape (N_pointsets,)
7,385
import torch from mmcv.ops import convex_iou The provided code snippet includes necessary dependencies for implementing the `points_center_pts` function. Write a Python function `def points_center_pts(RPoints, y_first=True)` to solve the following problem: Compute center point of Pointsets. Args: RPoints (torch.Tensor...
Compute center point of Pointsets. Args: RPoints (torch.Tensor): the lists of Pointsets, shape (k, 18). y_first (bool, optional): if True, the sequence of Pointsets is (y,x). Returns: center_pts (torch.Tensor): the mean_center coordination of Pointsets, shape (k, 18).
7,386
import torch from mmcv.ops import convex_iou The provided code snippet includes necessary dependencies for implementing the `convex_overlaps` function. Write a Python function `def convex_overlaps(gt_bboxes, points)` to solve the following problem: Compute overlaps between polygons and points. Args: gt_rbboxes (torch....
Compute overlaps between polygons and points. Args: gt_rbboxes (torch.Tensor): Groundtruth polygons, shape (k, 8). points (torch.Tensor): Points to be assigned, shape(n, 18). Returns: overlaps (torch.Tensor): Overlaps between k gt_bboxes and n bboxes, shape(k, n).
7,387
import torch from mmcv.ops import convex_iou The provided code snippet includes necessary dependencies for implementing the `levels_to_images` function. Write a Python function `def levels_to_images(mlvl_tensor, flatten=False)` to solve the following problem: Concat multi-level feature maps by image. [feature_level0, ...
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...
7,388
import torch from mmcv.ops import convex_iou The provided code snippet includes necessary dependencies for implementing the `get_num_level_anchors_inside` function. Write a Python function `def get_num_level_anchors_inside(num_level_anchors, inside_flags)` to solve the following problem: Get number of every level anch...
Get number of every level anchors inside. Args: num_level_anchors (List[int]): List of number of every level's anchors. inside_flags (torch.Tensor): Flags of all anchors. Returns: List[int]: List of number of inside anchors.
7,389
import warnings import e2cnn.nn as enn import torch.nn as nn import torch.utils.checkpoint as cp from mmcv.runner import BaseModule from torch.nn.modules.batchnorm import _BatchNorm from ..builder import ROTATED_BACKBONES from ..utils import (build_enn_divide_feature, build_enn_norm_layer, build_en...
Get the expansion of a residual block. The block expansion will be obtained by the following order: 1. If ``expansion`` is given, just return it. 2. If ``block`` has the attribute ``expansion``, then return ``block.expansion``. 3. Return the default value according the the block type: 1 for ``BasicBlock`` and 4 for ``B...
7,390
import warnings from mmdet.models.builder import MODELS ROTATED_BACKBONES = MODELS The provided code snippet includes necessary dependencies for implementing the `build_backbone` function. Write a Python function `def build_backbone(cfg)` to solve the following problem: Build backbone. Here is the function: def buil...
Build backbone.
7,391
import warnings from mmdet.models.builder import MODELS ROTATED_NECKS = MODELS The provided code snippet includes necessary dependencies for implementing the `build_neck` function. Write a Python function `def build_neck(cfg)` to solve the following problem: Build neck. Here is the function: def build_neck(cfg): ...
Build neck.
7,392
import warnings from mmdet.models.builder import MODELS ROTATED_ROI_EXTRACTORS = MODELS The provided code snippet includes necessary dependencies for implementing the `build_roi_extractor` function. Write a Python function `def build_roi_extractor(cfg)` to solve the following problem: Build roi extractor. Here is the...
Build roi extractor.
7,393
import warnings from mmdet.models.builder import MODELS ROTATED_SHARED_HEADS = MODELS The provided code snippet includes necessary dependencies for implementing the `build_shared_head` function. Write a Python function `def build_shared_head(cfg)` to solve the following problem: Build shared head. Here is the functio...
Build shared head.
7,394
import warnings from mmdet.models.builder import MODELS ROTATED_HEADS = MODELS The provided code snippet includes necessary dependencies for implementing the `build_head` function. Write a Python function `def build_head(cfg)` to solve the following problem: Build head. Here is the function: def build_head(cfg): ...
Build head.
7,395
import warnings from mmdet.models.builder import MODELS ROTATED_LOSSES = MODELS The provided code snippet includes necessary dependencies for implementing the `build_loss` function. Write a Python function `def build_loss(cfg)` to solve the following problem: Build loss. Here is the function: def build_loss(cfg): ...
Build loss.
7,396
import warnings from mmdet.models.builder import MODELS ROTATED_DETECTORS = MODELS The provided code snippet includes necessary dependencies for implementing the `build_detector` function. Write a Python function `def build_detector(cfg, train_cfg=None, test_cfg=None)` to solve the following problem: Build detector. ...
Build detector.
7,397
import e2cnn.nn as enn from e2cnn import gspaces gspace = gspaces.Rot2dOnR2(N=N) The provided code snippet includes necessary dependencies for implementing the `build_enn_feature` function. Write a Python function `def build_enn_feature(planes)` to solve the following problem: build a enn regular feature map with the ...
build a enn regular feature map with the specified number of channels.
7,398
import e2cnn.nn as enn from e2cnn import gspaces def build_enn_divide_feature(planes): """build a enn regular feature map with the specified number of channels divided by N.""" assert gspace.fibergroup.order() > 0 N = gspace.fibergroup.order() planes = planes / N planes = int(planes) return ...
build an enn normalizion layer.
7,399
import e2cnn.nn as enn from e2cnn import gspaces def build_enn_divide_feature(planes): """build a enn regular feature map with the specified number of channels divided by N.""" assert gspace.fibergroup.order() > 0 N = gspace.fibergroup.order() planes = planes / N planes = int(planes) return ...
enn convolution. Args: in_channels (List[int]): Number of input channels per scale. out_channels (int): Number of output channels (used at each scale). kernel_size (int, optional): The size of kernel. stride (int, optional): Stride of the convolution. Default: 1. padding (int or tuple): Zero-padding added to both sides...
7,400
import e2cnn.nn as enn from e2cnn import gspaces def build_enn_divide_feature(planes): """build a enn regular feature map with the specified number of channels divided by N.""" assert gspace.fibergroup.order() > 0 N = gspace.fibergroup.order() planes = planes / N planes = int(planes) return ...
enn convolution with trivial input featurn. Args: in_channels (List[int]): Number of input channels per scale. out_channels (int): Number of output channels (used at each scale). kernel_size (int, optional): The size of kernel. stride (int, optional): Stride of the convolution. Default: 1. padding (int or tuple): Zero-...
7,401
import e2cnn.nn as enn from e2cnn import gspaces def build_enn_divide_feature(planes): """build a enn regular feature map with the specified number of channels divided by N.""" assert gspace.fibergroup.order() > 0 N = gspace.fibergroup.order() planes = planes / N planes = int(planes) return ...
enn ReLU.
7,402
import e2cnn.nn as enn from e2cnn import gspaces def build_enn_divide_feature(planes): """build a enn regular feature map with the specified number of channels divided by N.""" assert gspace.fibergroup.order() > 0 N = gspace.fibergroup.order() planes = planes / N planes = int(planes) return ...
enn Average Pooling. Args: inplanes (int): The number of input channel. kernel_size (int, optional): The size of kernel. stride (int, optional): Stride of the convolution. Default: 1. padding (int or tuple): Zero-padding added to both sides of the input. Default: 0. ceil_mode (bool, optional): if True, keep information...
7,403
import e2cnn.nn as enn from e2cnn import gspaces def build_enn_divide_feature(planes): """build a enn regular feature map with the specified number of channels divided by N.""" assert gspace.fibergroup.order() > 0 N = gspace.fibergroup.order() planes = planes / N planes = int(planes) return ...
enn Max Pooling.
7,404
import e2cnn.nn as enn from e2cnn import gspaces def build_enn_divide_feature(planes): """build a enn regular feature map with the specified number of channels divided by N.""" assert gspace.fibergroup.order() > 0 N = gspace.fibergroup.order() planes = planes / N planes = int(planes) return ...
enn Interpolate.
7,405
import os import platform import warnings import cv2 import torch.multiprocessing as mp 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 the following problem: Setup multi-processing enviro...
Setup multi-processing environment variables.
7,406
from mmcv.utils import collect_env as collect_basic_env from mmcv.utils import get_git_hash import mmrotate 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 environment information....
Collect environment information.
7,407
import torch from mmcv.parallel import MMDataParallel, MMDistributedDataParallel dp_factory = {'cuda': MMDataParallel, 'cpu': MMDataParallel} The provided code snippet includes necessary dependencies for implementing the `build_dp` function. Write a Python function `def build_dp(model, device='cuda', dim=0, *args, **k...
build DataParallel module by device type. if device is cuda, return a MMDataParallel model; if device is mlu, return a MLUDataParallel model. Args: model (:class:`nn.Module`): model to be parallelized. device (str): device type, cuda, cpu or mlu. Defaults to cuda. dim (int): Dimension used to scatter the data. Defaults...
7,408
import torch from mmcv.parallel import MMDataParallel, MMDistributedDataParallel ddp_factory = {'cuda': MMDistributedDataParallel} The provided code snippet includes necessary dependencies for implementing the `build_ddp` function. Write a Python function `def build_ddp(model, device='cuda', *args, **kwargs)` to solve...
Build DistributedDataParallel module by device type. If device is cuda, return a MMDistributedDataParallel model; if device is mlu, return a MLUDistributedDataParallel model. Args: model (:class:`nn.Module`): module to be parallelized. device (str): device type, mlu or cuda. Returns: :class:`nn.Module`: the module to b...
7,409
import torch from mmcv.parallel import MMDataParallel, MMDistributedDataParallel def is_npu_available(): """Returns a bool indicating if NPU is currently available.""" return hasattr(torch, 'npu') and torch.npu.is_available() The provided code snippet includes necessary dependencies for implementing the `get_d...
Returns an available device, cpu, cuda.
7,410
import glob import os.path as osp import warnings The provided code snippet includes necessary dependencies for implementing the `find_latest_checkpoint` function. Write a Python function `def find_latest_checkpoint(path, suffix='pth')` to solve the following problem: Find the latest checkpoint from the working direct...
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
7,411
import copy import warnings from mmcv 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 `runner` s...
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.
7,412
import logging from mmcv.utils import get_logger The provided code snippet includes necessary dependencies for implementing the `get_root_logger` function. Write a Python function `def get_root_logger(log_file=None, log_level=logging.INFO)` to solve the following problem: Get root logger. Args: log_file (str, optional...
Get root logger. Args: log_file (str, optional): File path of log. Defaults to None. log_level (int, optional): The level of logger. Defaults to logging.INFO. Returns: :obj:`logging.Logger`: The obtained logger
7,413
from argparse import ArgumentParser from mmdet.apis import inference_detector, init_detector, show_result_pyplot import mmrotate def parse_args(): parser = ArgumentParser() parser.add_argument('img', help='Image file') parser.add_argument('config', help='Config file') parser.add_argument('checkpoint', ...
null
7,414
from argparse import ArgumentParser from mmdet.apis import init_detector, show_result_pyplot from mmrotate.apis import inference_detector_by_patches def parse_args(): parser = ArgumentParser() parser.add_argument('img', help='Image file') parser.add_argument('config', help='Config file') parser.add_arg...
null
7,415
import argparse import copy import os import os.path as osp import time import warnings import mmcv import torch import torch.distributed as dist from mmcv import Config, DictAction from mmcv.runner import get_dist_info, init_dist from mmcv.utils import get_git_hash from mmdet import __version__ from mmdet.apis import ...
null
7,416
import argparse import numpy as np import torch from mmcv import Config, DictAction from mmrotate.models import build_detector def parse_args(): parser = argparse.ArgumentParser(description='Train a detector') parser.add_argument('config', help='train config file path') parser.add_argument( '--shap...
null
7,417
import argparse import os import matplotlib.pyplot as plt import mmcv import numpy as np import torch from matplotlib.ticker import MultipleLocator from mmcv import Config, DictAction from mmcv.ops import nms_rotated from mmdet.datasets import build_dataset from mmrotate.core.bbox import rbbox_overlaps def parse_args(...
null
7,418
import argparse import os import matplotlib.pyplot as plt import mmcv import numpy as np import torch from matplotlib.ticker import MultipleLocator from mmcv import Config, DictAction from mmcv.ops import nms_rotated from mmdet.datasets import build_dataset from mmrotate.core.bbox import rbbox_overlaps def analyze_per_...
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...
7,419
import argparse import os import matplotlib.pyplot as plt import mmcv import numpy as np import torch from matplotlib.ticker import MultipleLocator from mmcv import Config, DictAction from mmcv.ops import nms_rotated from mmdet.datasets import build_dataset from mmrotate.core.bbox import rbbox_overlaps The provided co...
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. ...
7,420
import argparse import json from collections import defaultdict import matplotlib.pyplot as plt import numpy as np The provided code snippet includes necessary dependencies for implementing the `cal_train_time` function. Write a Python function `def cal_train_time(log_dicts, args)` to solve the following problem: calc...
calculate the training time.
7,421
import argparse import json from collections import defaultdict import matplotlib.pyplot as plt import numpy as np The provided code snippet includes necessary dependencies for implementing the `plot_curve` function. Write a Python function `def plot_curve(log_dicts, args)` to solve the following problem: Plot curve. ...
Plot curve.
7,422
import argparse import json from collections import defaultdict import matplotlib.pyplot as plt import numpy as np def add_plot_parser(subparsers): """Add plot parser.""" parser_plt = subparsers.add_parser( 'plot_curve', help='parser for plotting curves') parser_plt.add_argument( 'json_logs'...
Parse parameters.
7,423
import argparse import json from collections import defaultdict import matplotlib.pyplot as plt import numpy as np The provided code snippet includes necessary dependencies for implementing the `load_json_logs` function. Write a Python function `def load_json_logs(json_logs)` to solve the following problem: Load and c...
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 value of sub dict is a list of corresponding values of all iterations. Args: json_logs (str): json file of logs. Returns: dict: dict of logs.
7,424
import argparse import copy import os import time import torch from mmcv import Config, DictAction from mmcv.cnn import fuse_conv_bn from mmcv.parallel import MMDistributedDataParallel from mmcv.runner import init_dist, load_checkpoint, wrap_fp16_model from mmdet.datasets import build_dataloader, replace_ImageToTensor ...
null
7,425
import argparse import copy import os import time import torch from mmcv import Config, DictAction from mmcv.cnn import fuse_conv_bn from mmcv.parallel import MMDistributedDataParallel from mmcv.runner import init_dist, load_checkpoint, wrap_fp16_model from mmdet.datasets import build_dataloader, replace_ImageToTensor ...
Repeat to inference several times and take the average. Args: cfg (object): Test config object. checkpoint (str): Checkpoint file path. max_iter (int): Num of max iter. log_interval (int): Interval of logging. is_fuse_conv_bn (bool): Whether to fuse conv and bn, this will slightly increase the inference speed use_fp16 ...
7,426
import argparse import subprocess import torch The provided code snippet includes necessary dependencies for implementing the `parse_args` function. Write a Python function `def parse_args()` to solve the following problem: Parse parameters. Here is the function: def parse_args(): """Parse parameters.""" par...
Parse parameters.
7,427
import argparse import subprocess import torch The provided code snippet includes necessary dependencies for implementing the `process_checkpoint` function. Write a Python function `def process_checkpoint(in_file, out_file)` to solve the following problem: Only inference related parameters are retained. Args: in_file ...
Only inference related parameters are retained. Args: in_file (str): Filename of input checkpoint. out_file (str): Filename of output checkpoint.
7,428
import argparse import codecs import datetime import itertools import json import logging import os import os.path as osp import time from functools import partial, reduce from math import ceil from multiprocessing import Manager, Pool import cv2 import numpy as np from PIL import Image def add_parser(parser): """A...
Parse arguments.
7,429
import argparse import codecs import datetime import itertools import json import logging import os import os.path as osp import time from functools import partial, reduce from math import ceil from multiprocessing import Manager, Pool import cv2 import numpy as np from PIL import Image def get_sliding_window(info, siz...
Args: arguments (object): Parameters. sizes (list): List of window's sizes. gaps (list): List of window's gaps. img_rate_thr (float): Threshold of window area divided by image area. iof_thr (float): Threshold of overlaps between bbox and window. no_padding (bool): If True, no padding. padding_value (tuple[int|float]): ...
7,430
import argparse import codecs import datetime import itertools import json import logging import os import os.path as osp import time from functools import partial, reduce from math import ceil from multiprocessing import Manager, Pool import cv2 import numpy as np from PIL import Image The provided code snippet inclu...
Setup logger. Args: log_path (str): Path of log. Returns: object: Logger.
7,431
import argparse import codecs import datetime import itertools import json import logging import os import os.path as osp import time from functools import partial, reduce from math import ceil from multiprocessing import Manager, Pool import cv2 import numpy as np from PIL import Image def _load_dota_single(imgfile, i...
Load DOTA dataset. Args: img_dir (str): Path of images. ann_dir (str): Path of annotations. nproc (int): number of processes. Returns: list: Dataset's contents.
7,432
import argparse import os from collections import Sequence from pathlib import Path import mmcv from mmcv import Config, DictAction from mmdet.datasets.builder import build_dataset from mmrotate.core.visualization import imshow_det_rbboxes def parse_args(): parser = argparse.ArgumentParser(description='Browse a da...
null
7,433
import argparse import os from collections import Sequence from pathlib import Path import mmcv from mmcv import Config, DictAction from mmdet.datasets.builder import build_dataset from mmrotate.core.visualization import imshow_det_rbboxes The provided code snippet includes necessary dependencies for implementing the ...
Retrieve the dataset config file. Args: config_path (str): Path of the config file. skip_type (list[str]): List of the useless pipeline to skip. cfg_options (dict): dict of configs to merge from.
7,434
import argparse import warnings from mmcv import Config, DictAction The provided code snippet includes necessary dependencies for implementing the `parse_args` function. Write a Python function `def parse_args()` to solve the following problem: Parse arguments. Here is the function: def parse_args(): """Parse ar...
Parse arguments.
7,435
from argparse import ArgumentParser, Namespace from pathlib import Path from tempfile import TemporaryDirectory import mmcv The provided code snippet includes necessary dependencies for implementing the `mmrotate2torchserve` function. Write a Python function `def mmrotate2torchserve( config_file: str, checkpoi...
Converts MMRotate model (config + checkpoint) to TorchServe `.mar`. Args: config_file: In MMRotate config format. The contents vary for each task repository. checkpoint_file: In MMRotate checkpoint format. The contents vary for each task repository. output_folder: Folder where `{model_name}.mar` will be created. The fi...
7,436
from argparse import ArgumentParser, Namespace from pathlib import Path from tempfile import TemporaryDirectory import mmcv def parse_args(): parser = ArgumentParser( description='Convert MMRotate models to TorchServe `.mar` format.') parser.add_argument('config', type=str, help='config file path') ...
null
7,437
import os import gc import time import base64 from contextlib import asynccontextmanager from typing import List, Literal, Union, Tuple, Optional import torch import uvicorn from fastapi import FastAPI, HTTPException from fastapi.middleware.cors import CORSMiddleware from loguru import logger from pydantic import BaseM...
An asynchronous context manager for managing the lifecycle of the FastAPI app. It ensures that GPU memory is cleared after the app's lifecycle ends, which is essential for efficient resource management in GPU environments.
7,438
import os import gc import time import base64 from contextlib import asynccontextmanager from typing import List, Literal, Union, Tuple, Optional import torch import uvicorn from fastapi import FastAPI, HTTPException from fastapi.middleware.cors import CORSMiddleware from loguru import logger from pydantic import BaseM...
An endpoint to list available models. It returns a list of model cards. This is useful for clients to query and understand what models are available for use.
7,439
import os import gc import time import base64 from contextlib import asynccontextmanager from typing import List, Literal, Union, Tuple, Optional import torch import uvicorn from fastapi import FastAPI, HTTPException from fastapi.middleware.cors import CORSMiddleware from loguru import logger from pydantic import BaseM...
null
7,440
import requests import json import base64 def create_chat_completion(model, messages, temperature=0.8, max_tokens=2048, top_p=0.8, use_stream=False): """ This function sends a request to the chat API to generate a response based on the given messages. Args: model (str): The name of the model to use ...
Facilitates a simple chat interaction involving an image. Args: use_stream (bool): Specifies whether to use streaming for chat responses. img_path (str): Path to the image file to be included in the chat. This function encodes the specified image and constructs a predefined conversation involving the image. It then cal...
7,441
import gradio as gr import os, sys from PIL import Image import torch import time from sat.model.mixins import CachedAutoregressiveMixin from sat.mpu import get_model_parallel_world_size from sat.model import AutoModel from utils.utils import chat, llama2_tokenizer, llama2_text_processor_inference, get_image_processor,...
null
7,442
import gradio as gr import os, sys from PIL import Image import torch import time from sat.model.mixins import CachedAutoregressiveMixin from sat.mpu import get_model_parallel_world_size from sat.model import AutoModel from utils.utils import chat, llama2_tokenizer, llama2_text_processor_inference, get_image_processor,...
null
7,443
import gradio as gr import os, sys from PIL import Image import torch import time from sat.model.mixins import CachedAutoregressiveMixin from sat.mpu import get_model_parallel_world_size from sat.model import AutoModel from utils.utils import chat, llama2_tokenizer, llama2_text_processor_inference, get_image_processor,...
null
7,444
import gradio as gr import os, sys from PIL import Image import torch import time from sat.model.mixins import CachedAutoregressiveMixin from sat.mpu import get_model_parallel_world_size from sat.model import AutoModel from utils.utils import chat, llama2_tokenizer, llama2_text_processor_inference, get_image_processor,...
null
7,445
import base64 from io import BytesIO from PIL import Image The provided code snippet includes necessary dependencies for implementing the `images_are_same` function. Write a Python function `def images_are_same(img1: Image, img2: Image) -> bool` to solve the following problem: Compare two PIL images. Here is the func...
Compare two PIL images.
7,446
import base64 from io import BytesIO from PIL import Image The provided code snippet includes necessary dependencies for implementing the `encode_file_to_base64` function. Write a Python function `def encode_file_to_base64(file)` to solve the following problem: Convert a file to base64. Here is the function: def enc...
Convert a file to base64.
7,447
import requests import re import streamlit as st from dataclasses import dataclass from enum import auto, Enum from PIL.Image import Image from PIL import ImageDraw from streamlit.delta_generator import DeltaGenerator class Role(Enum): """ CogVLM | CogAgent Only have 2 roles: USER, ASSISTANT Represents the ...
Prepares the conversation history for processing by concatenating the content of each turn. Args: history (list[Conversation]): The conversation history, a list of Conversation objects. Returns: str: A single string that concatenates the content of each conversation turn, followed by the ASSISTANT role indicator. This ...
7,448
import requests import re import streamlit as st from dataclasses import dataclass from enum import auto, Enum from PIL.Image import Image from PIL import ImageDraw from streamlit.delta_generator import DeltaGenerator The provided code snippet includes necessary dependencies for implementing the `postprocess_text` fun...
Post-processes the generated text by incorporating it into a given template. Args: template (str): A template string containing a placeholder for the generated text. text (str): The generated text to be incorporated into the template. Returns: str: The template with the generated text replacing the placeholder.