id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
9,476 | import logging
import torch.nn as nn
import torch.utils.checkpoint as cp
from .utils import constant_init, kaiming_init
def make_res_layer(block,
inplanes,
planes,
blocks,
stride=1,
dilation=1,
style='pyto... | null |
9,477 | import logging
import torch.nn as nn
from .utils import constant_init, kaiming_init, normal_init
def conv3x3(in_planes, out_planes, dilation=1):
"""3x3 convolution with padding."""
return nn.Conv2d(
in_planes,
out_planes,
kernel_size=3,
padding=dilation,
dilation=dilation... | null |
9,478 | import torch
import annotator.uniformer.mmcv as mmcv
class _BatchNormXd(torch.nn.modules.batchnorm._BatchNorm):
"""A general BatchNorm layer without input dimension check.
Reproduced from @kapily's work:
(https://github.com/pytorch/pytorch/issues/41081#issuecomment-783961547)
The only difference between... | Helper function to convert all `SyncBatchNorm` (SyncBN) and `mmcv.ops.sync_bn.SyncBatchNorm`(MMSyncBN) layers in the model to `BatchNormXd` layers. Adapted from @kapily's work: (https://github.com/pytorch/pytorch/issues/41081#issuecomment-783961547) Args: module (nn.Module): The module containing `SyncBatchNorm` layers... |
9,479 | import torch
import torch.nn as nn
def _fuse_conv_bn(conv, bn):
"""Fuse conv and bn into one module.
Args:
conv (nn.Module): Conv to be fused.
bn (nn.Module): BN to be fused.
Returns:
nn.Module: Fused module.
"""
conv_w = conv.weight
conv_b = conv.bias if conv.bias is not... | Recursively fuse conv and bn in a module. During inference, the functionary of batch norm layers is turned off but only the mean and var alone channels are used, which exposes the chance to fuse it with the preceding conv layers to save computations and simplify network structures. Args: module (nn.Module): Module to b... |
9,480 | import copy
import math
import warnings
import numpy as np
import torch
import torch.nn as nn
from torch import Tensor
from annotator.uniformer.mmcv.utils import Registry, build_from_cfg, get_logger, print_log
The provided code snippet includes necessary dependencies for implementing the `update_init_info` function. W... | Update the `_params_init_info` in the module if the value of parameters are changed. Args: module (obj:`nn.Module`): The module of PyTorch with a user-defined attribute `_params_init_info` which records the initialization information. init_info (str): The string that describes the initialization. |
9,481 | import copy
import math
import warnings
import numpy as np
import torch
import torch.nn as nn
from torch import Tensor
from annotator.uniformer.mmcv.utils import Registry, build_from_cfg, get_logger, print_log
def constant_init(module, val, bias=0):
if hasattr(module, 'weight') and module.weight is not None:
... | null |
9,482 | import copy
import math
import warnings
import numpy as np
import torch
import torch.nn as nn
from torch import Tensor
from annotator.uniformer.mmcv.utils import Registry, build_from_cfg, get_logger, print_log
def xavier_init(module, gain=1, bias=0, distribution='normal'):
assert distribution in ['uniform', 'norma... | null |
9,483 | import copy
import math
import warnings
import numpy as np
import torch
import torch.nn as nn
from torch import Tensor
from annotator.uniformer.mmcv.utils import Registry, build_from_cfg, get_logger, print_log
def normal_init(module, mean=0, std=1, bias=0):
if hasattr(module, 'weight') and module.weight is not Non... | null |
9,484 | import copy
import math
import warnings
import numpy as np
import torch
import torch.nn as nn
from torch import Tensor
from annotator.uniformer.mmcv.utils import Registry, build_from_cfg, get_logger, print_log
def trunc_normal_(tensor: Tensor,
mean: float = 0.,
std: float = 1.,
... | null |
9,485 | import copy
import math
import warnings
import numpy as np
import torch
import torch.nn as nn
from torch import Tensor
from annotator.uniformer.mmcv.utils import Registry, build_from_cfg, get_logger, print_log
def uniform_init(module, a=0, b=1, bias=0):
if hasattr(module, 'weight') and module.weight is not None:
... | null |
9,486 | import copy
import math
import warnings
import numpy as np
import torch
import torch.nn as nn
from torch import Tensor
from annotator.uniformer.mmcv.utils import Registry, build_from_cfg, get_logger, print_log
def kaiming_init(module,
a=0,
mode='fan_out',
nonlinearity=... | null |
9,487 | import copy
import math
import warnings
import numpy as np
import torch
import torch.nn as nn
from torch import Tensor
from annotator.uniformer.mmcv.utils import Registry, build_from_cfg, get_logger, print_log
The provided code snippet includes necessary dependencies for implementing the `bias_init_with_prob` function... | initialize conv/fc bias value according to a given probability value. |
9,488 | import copy
import math
import warnings
import numpy as np
import torch
import torch.nn as nn
from torch import Tensor
from annotator.uniformer.mmcv.utils import Registry, build_from_cfg, get_logger, print_log
def _get_bases_name(m):
return [b.__name__ for b in m.__class__.__bases__] | null |
9,489 | import copy
import math
import warnings
import numpy as np
import torch
import torch.nn as nn
from torch import Tensor
from annotator.uniformer.mmcv.utils import Registry, build_from_cfg, get_logger, print_log
def _initialize(module, cfg, wholemodule=False):
func = build_from_cfg(cfg, INITIALIZERS)
# wholemodul... | Initialize a module. Args: module (``torch.nn.Module``): the module will be initialized. init_cfg (dict | list[dict]): initialization configuration dict to define initializer. OpenMMLab has implemented 6 initializers including ``Constant``, ``Xavier``, ``Normal``, ``Uniform``, ``Kaiming``, and ``Pretrained``. Example: ... |
9,490 | import sys
from functools import partial
import numpy as np
import torch
import torch.nn as nn
import annotator.uniformer.mmcv as mmcv
def flops_to_string(flops, units='GFLOPs', precision=2):
"""Convert FLOPs number into a string.
Note that Here we take a multiply-add counts as one FLOP.
Args:
flops... | Get complexity information of a model. This method can calculate FLOPs and parameter counts of a model with corresponding input shape. It can also print complexity information for each layer in a model. Supported layers are listed as below: - Convolutions: ``nn.Conv1d``, ``nn.Conv2d``, ``nn.Conv3d``. - Activations: ``n... |
9,491 | import sys
from functools import partial
import numpy as np
import torch
import torch.nn as nn
import annotator.uniformer.mmcv as mmcv
def empty_flops_counter_hook(module, input, output):
module.__flops__ += 0 | null |
9,492 | import json
import numpy as np
from .base import BaseFileHandler
The provided code snippet includes necessary dependencies for implementing the `set_default` function. Write a Python function `def set_default(obj)` to solve the following problem:
Set default json values for non-serializable values. It helps convert ``... | Set default json values for non-serializable values. It helps convert ``set``, ``range`` and ``np.ndarray`` data types to list. It also converts ``np.generic`` (including ``np.int32``, ``np.float32``, etc.) into plain numbers of plain python built-in types. |
9,493 | from io import BytesIO, StringIO
from pathlib import Path
from ..utils import is_list_of, is_str
from .file_client import FileClient
from .handlers import BaseFileHandler, JsonHandler, PickleHandler, YamlHandler
file_handlers = {
'json': JsonHandler(),
'yaml': YamlHandler(),
'yml': YamlHandler(),
'pickl... | Load data from json/yaml/pickle files. This method provides a unified api for loading data from serialized files. Note: In v1.3.16 and later, ``load`` supports loading data from serialized files those can be storaged in different backends. Args: file (str or :obj:`Path` or file-like object): Filename or a file-like obj... |
9,494 | from io import BytesIO, StringIO
from pathlib import Path
from ..utils import is_list_of, is_str
from .file_client import FileClient
from .handlers import BaseFileHandler, JsonHandler, PickleHandler, YamlHandler
file_handlers = {
'json': JsonHandler(),
'yaml': YamlHandler(),
'yml': YamlHandler(),
'pickl... | Dump data to json/yaml/pickle strings or files. This method provides a unified api for dumping data as strings or to files, and also supports custom arguments for each file format. Note: In v1.3.16 and later, ``dump`` supports dumping data as strings or to files which is saved to different backends. Args: obj (any): Th... |
9,495 | from io import BytesIO, StringIO
from pathlib import Path
from ..utils import is_list_of, is_str
from .file_client import FileClient
from .handlers import BaseFileHandler, JsonHandler, PickleHandler, YamlHandler
def _register_handler(handler, file_formats):
"""Register a handler for some file extensions.
Args:
... | null |
9,496 | from io import StringIO
from .file_client import FileClient
class FileClient:
"""A general file client to access files in different backends.
The client loads a file or text in a specified backend from its path
and returns it as a binary or text file. There are two ways to choose a
backend, the name o... | Load a text file and parse the content as a list of strings. Note: In v1.3.16 and later, ``list_from_file`` supports loading a text file which can be storaged in different backends and parsing the content as a list for strings. Args: filename (str): Filename. prefix (str): The prefix to be inserted to the beginning of ... |
9,497 | from io import StringIO
from .file_client import FileClient
class FileClient:
"""A general file client to access files in different backends.
The client loads a file or text in a specified backend from its path
and returns it as a binary or text file. There are two ways to choose a
backend, the name o... | Load a text file and parse the content as a dict. Each line of the text file will be two or more columns split by whitespaces or tabs. The first column will be parsed as dict keys, and the following columns will be parsed as dict values. Note: In v1.3.16 and later, ``dict_from_file`` supports loading a text file which ... |
9,498 | import cv2
import numpy as np
The provided code snippet includes necessary dependencies for implementing the `imconvert` function. Write a Python function `def imconvert(img, src, dst)` to solve the following problem:
Convert an image from the src colorspace to dst colorspace. Args: img (ndarray): The input image. src... | Convert an image from the src colorspace to dst colorspace. Args: img (ndarray): The input image. src (str): The source colorspace, e.g., 'rgb', 'hsv'. dst (str): The destination colorspace, e.g., 'rgb', 'hsv'. Returns: ndarray: The converted image. |
9,499 | import cv2
import numpy as np
The provided code snippet includes necessary dependencies for implementing the `rgb2gray` function. Write a Python function `def rgb2gray(img, keepdim=False)` to solve the following problem:
Convert a RGB image to grayscale image. Args: img (ndarray): The input image. keepdim (bool): If F... | Convert a RGB image to grayscale image. Args: img (ndarray): The input image. keepdim (bool): If False (by default), then return the grayscale image with 2 dims, otherwise 3 dims. Returns: ndarray: The converted grayscale image. |
9,500 | import cv2
import numpy as np
The provided code snippet includes necessary dependencies for implementing the `gray2rgb` function. Write a Python function `def gray2rgb(img)` to solve the following problem:
Convert a grayscale image to RGB image. Args: img (ndarray): The input image. Returns: ndarray: The converted RGB... | Convert a grayscale image to RGB image. Args: img (ndarray): The input image. Returns: ndarray: The converted RGB image. |
9,501 | import cv2
import numpy as np
def _convert_input_type_range(img):
"""Convert the type and range of the input image.
It converts the input image to np.float32 type and range of [0, 1].
It is mainly used for pre-processing the input image in colorspace
conversion functions such as rgb2ycbcr and ycbcr2rgb.... | Convert a RGB image to YCbCr image. This function produces the same results as Matlab's `rgb2ycbcr` function. It implements the ITU-R BT.601 conversion for standard-definition television. See more details in https://en.wikipedia.org/wiki/YCbCr#ITU-R_BT.601_conversion. It differs from a similar function in cv2.cvtColor:... |
9,502 | import cv2
import numpy as np
def _convert_input_type_range(img):
"""Convert the type and range of the input image.
It converts the input image to np.float32 type and range of [0, 1].
It is mainly used for pre-processing the input image in colorspace
conversion functions such as rgb2ycbcr and ycbcr2rgb.... | Convert a BGR image to YCbCr image. The bgr version of rgb2ycbcr. It implements the ITU-R BT.601 conversion for standard-definition television. See more details in https://en.wikipedia.org/wiki/YCbCr#ITU-R_BT.601_conversion. It differs from a similar function in cv2.cvtColor: `BGR <-> YCrCb`. In OpenCV, it implements a... |
9,503 | import cv2
import numpy as np
def _convert_input_type_range(img):
"""Convert the type and range of the input image.
It converts the input image to np.float32 type and range of [0, 1].
It is mainly used for pre-processing the input image in colorspace
conversion functions such as rgb2ycbcr and ycbcr2rgb.... | Convert a YCbCr image to RGB image. This function produces the same results as Matlab's ycbcr2rgb function. It implements the ITU-R BT.601 conversion for standard-definition television. See more details in https://en.wikipedia.org/wiki/YCbCr#ITU-R_BT.601_conversion. It differs from a similar function in cv2.cvtColor: `... |
9,504 | import cv2
import numpy as np
def _convert_input_type_range(img):
"""Convert the type and range of the input image.
It converts the input image to np.float32 type and range of [0, 1].
It is mainly used for pre-processing the input image in colorspace
conversion functions such as rgb2ycbcr and ycbcr2rgb.... | Convert a YCbCr image to BGR image. The bgr version of ycbcr2rgb. It implements the ITU-R BT.601 conversion for standard-definition television. See more details in https://en.wikipedia.org/wiki/YCbCr#ITU-R_BT.601_conversion. It differs from a similar function in cv2.cvtColor: `YCrCb <-> BGR`. In OpenCV, it implements a... |
9,505 | import cv2
import numpy as np
def convert_color_factory(src, dst):
code = getattr(cv2, f'COLOR_{src.upper()}2{dst.upper()}')
def convert_color(img):
out_img = cv2.cvtColor(img, code)
return out_img
convert_color.__doc__ = f"""Convert a {src.upper()} image to {dst.upper()}
image.
... | null |
9,506 | import cv2
import numpy as np
from ..utils import is_tuple_of
from .colorspace import bgr2gray, gray2bgr
def imnormalize_(img, mean, std, to_rgb=True):
"""Inplace normalize an image with mean and std.
Args:
img (ndarray): Image to be normalized.
mean (ndarray): The mean to be used for normalize.... | Normalize an image with mean and std. Args: img (ndarray): Image to be normalized. mean (ndarray): The mean to be used for normalize. std (ndarray): The std to be used for normalize. to_rgb (bool): Whether to convert to rgb. Returns: ndarray: The normalized image. |
9,507 | import cv2
import numpy as np
from ..utils import is_tuple_of
from .colorspace import bgr2gray, gray2bgr
def imdenormalize(img, mean, std, to_bgr=True):
assert img.dtype != np.uint8
mean = mean.reshape(1, -1).astype(np.float64)
std = std.reshape(1, -1).astype(np.float64)
img = cv2.multiply(img, std) #... | null |
9,508 | import cv2
import numpy as np
from ..utils import is_tuple_of
from .colorspace import bgr2gray, gray2bgr
The provided code snippet includes necessary dependencies for implementing the `iminvert` function. Write a Python function `def iminvert(img)` to solve the following problem:
Invert (negate) an image. Args: img (n... | Invert (negate) an image. Args: img (ndarray): Image to be inverted. Returns: ndarray: The inverted image. |
9,509 | import cv2
import numpy as np
from ..utils import is_tuple_of
from .colorspace import bgr2gray, gray2bgr
The provided code snippet includes necessary dependencies for implementing the `solarize` function. Write a Python function `def solarize(img, thr=128)` to solve the following problem:
Solarize an image (invert all... | Solarize an image (invert all pixel values above a threshold) Args: img (ndarray): Image to be solarized. thr (int): Threshold for solarizing (0 - 255). Returns: ndarray: The solarized image. |
9,510 | import cv2
import numpy as np
from ..utils import is_tuple_of
from .colorspace import bgr2gray, gray2bgr
The provided code snippet includes necessary dependencies for implementing the `posterize` function. Write a Python function `def posterize(img, bits)` to solve the following problem:
Posterize an image (reduce the... | Posterize an image (reduce the number of bits for each color channel) Args: img (ndarray): Image to be posterized. bits (int): Number of bits (1 to 8) to use for posterizing. Returns: ndarray: The posterized image. |
9,511 | import cv2
import numpy as np
from ..utils import is_tuple_of
from .colorspace import bgr2gray, gray2bgr
def bgr2gray(img, keepdim=False):
"""Convert a BGR image to grayscale image.
Args:
img (ndarray): The input image.
keepdim (bool): If False (by default), then return the grayscale image
... | r"""It blends the source image and its gray image: .. math:: output = img * alpha + gray\_img * beta + gamma Args: img (ndarray): The input source image. alpha (int | float): Weight for the source image. Default 1. beta (int | float): Weight for the converted gray image. If None, it's assigned the value (1 - `alpha`). ... |
9,512 | import cv2
import numpy as np
from ..utils import is_tuple_of
from .colorspace import bgr2gray, gray2bgr
The provided code snippet includes necessary dependencies for implementing the `imequalize` function. Write a Python function `def imequalize(img)` to solve the following problem:
Equalize the image histogram. This... | Equalize the image histogram. This function applies a non-linear mapping to the input image, in order to create a uniform distribution of grayscale values in the output image. Args: img (ndarray): Image to be equalized. Returns: ndarray: The equalized image. |
9,513 | import cv2
import numpy as np
from ..utils import is_tuple_of
from .colorspace import bgr2gray, gray2bgr
The provided code snippet includes necessary dependencies for implementing the `adjust_brightness` function. Write a Python function `def adjust_brightness(img, factor=1.)` to solve the following problem:
Adjust im... | Adjust image brightness. This function controls the brightness of an image. An enhancement factor of 0.0 gives a black image. A factor of 1.0 gives the original image. This function blends the source image and the degenerated black image: .. math:: output = img * factor + degenerated * (1 - factor) Args: img (ndarray):... |
9,514 | import cv2
import numpy as np
from ..utils import is_tuple_of
from .colorspace import bgr2gray, gray2bgr
def bgr2gray(img, keepdim=False):
"""Convert a BGR image to grayscale image.
Args:
img (ndarray): The input image.
keepdim (bool): If False (by default), then return the grayscale image
... | Adjust image contrast. This function controls the contrast of an image. An enhancement factor of 0.0 gives a solid grey image. A factor of 1.0 gives the original image. It blends the source image and the degenerated mean image: .. math:: output = img * factor + degenerated * (1 - factor) Args: img (ndarray): Image to b... |
9,515 | import cv2
import numpy as np
from ..utils import is_tuple_of
from .colorspace import bgr2gray, gray2bgr
The provided code snippet includes necessary dependencies for implementing the `auto_contrast` function. Write a Python function `def auto_contrast(img, cutoff=0)` to solve the following problem:
Auto adjust image ... | Auto adjust image contrast. This function maximize (normalize) image contrast by first removing cutoff percent of the lightest and darkest pixels from the histogram and remapping the image so that the darkest pixel becomes black (0), and the lightest becomes white (255). Args: img (ndarray): Image to be contrasted. BGR... |
9,516 | import cv2
import numpy as np
from ..utils import is_tuple_of
from .colorspace import bgr2gray, gray2bgr
The provided code snippet includes necessary dependencies for implementing the `adjust_sharpness` function. Write a Python function `def adjust_sharpness(img, factor=1., kernel=None)` to solve the following problem... | Adjust image sharpness. This function controls the sharpness of an image. An enhancement factor of 0.0 gives a blurred image. A factor of 1.0 gives the original image. And a factor of 2.0 gives a sharpened image. It blends the source image and the degenerated mean image: .. math:: output = img * factor + degenerated * ... |
9,517 | import cv2
import numpy as np
from ..utils import is_tuple_of
from .colorspace import bgr2gray, gray2bgr
The provided code snippet includes necessary dependencies for implementing the `adjust_lighting` function. Write a Python function `def adjust_lighting(img, eigval, eigvec, alphastd=0.1, to_rgb=True)` to solve the ... | AlexNet-style PCA jitter. This data augmentation is proposed in `ImageNet Classification with Deep Convolutional Neural Networks <https://dl.acm.org/doi/pdf/10.1145/3065386>`_. Args: img (ndarray): Image to be adjusted lighting. BGR order. eigval (ndarray): the eigenvalue of the convariance matrix of pixel values, resp... |
9,518 | import cv2
import numpy as np
from ..utils import is_tuple_of
from .colorspace import bgr2gray, gray2bgr
The provided code snippet includes necessary dependencies for implementing the `lut_transform` function. Write a Python function `def lut_transform(img, lut_table)` to solve the following problem:
Transform array b... | Transform array by look-up table. The function lut_transform fills the output array with values from the look-up table. Indices of the entries are taken from the input array. Args: img (ndarray): Image to be transformed. lut_table (ndarray): look-up table of 256 elements; in case of multi-channel input array, the table... |
9,519 | import cv2
import numpy as np
from ..utils import is_tuple_of
from .colorspace import bgr2gray, gray2bgr
The provided code snippet includes necessary dependencies for implementing the `clahe` function. Write a Python function `def clahe(img, clip_limit=40.0, tile_grid_size=(8, 8))` to solve the following problem:
Use ... | Use CLAHE method to process the image. See `ZUIDERVELD,K. Contrast Limited Adaptive Histogram Equalization[J]. Graphics Gems, 1994:474-485.` for more information. Args: img (ndarray): Image to be processed. clip_limit (float): Threshold for contrast limiting. Default: 40.0. tile_grid_size (tuple[int]): Size of grid for... |
9,520 | import numbers
import cv2
import numpy as np
from ..utils import to_2tuple
from .io import imread_backend
def _scale_size(size, scale):
"""Rescale a size by a ratio.
Args:
size (tuple[int]): (w, h).
scale (float | tuple(float)): Scaling factor.
Returns:
tuple[int]: scaled size.
"... | Resize image according to a given size or scale factor and then rounds up the the resized or rescaled image size to the nearest value that can be divided by the divisor. Args: img (ndarray): The input image. divisor (int | tuple): Resized image size will be a multiple of divisor. If divisor is a tuple, divisor should b... |
9,521 | import numbers
import cv2
import numpy as np
from ..utils import to_2tuple
from .io import imread_backend
def imresize(img,
size,
return_scale=False,
interpolation='bilinear',
out=None,
backend=None):
"""Resize image to a given size.
Args:
... | Resize image to the same size of a given image. Args: img (ndarray): The input image. dst_img (ndarray): The target image. return_scale (bool): Whether to return `w_scale` and `h_scale`. interpolation (str): Same as :func:`resize`. backend (str | None): Same as :func:`resize`. Returns: tuple or ndarray: (`resized_img`,... |
9,522 | import numbers
import cv2
import numpy as np
from ..utils import to_2tuple
from .io import imread_backend
def imresize(img,
size,
return_scale=False,
interpolation='bilinear',
out=None,
backend=None):
"""Resize image to a given size.
Args:
... | Resize image while keeping the aspect ratio. Args: img (ndarray): The input image. scale (float | tuple[int]): The scaling factor or maximum size. If it is a float number, then the image will be rescaled by this factor, else if it is a tuple of 2 integers, then the image will be rescaled as large as possible within the... |
9,523 | import numbers
import cv2
import numpy as np
from ..utils import to_2tuple
from .io import imread_backend
The provided code snippet includes necessary dependencies for implementing the `imflip` function. Write a Python function `def imflip(img, direction='horizontal')` to solve the following problem:
Flip an image hor... | Flip an image horizontally or vertically. Args: img (ndarray): Image to be flipped. direction (str): The flip direction, either "horizontal" or "vertical" or "diagonal". Returns: ndarray: The flipped image. |
9,524 | import numbers
import cv2
import numpy as np
from ..utils import to_2tuple
from .io import imread_backend
The provided code snippet includes necessary dependencies for implementing the `imflip_` function. Write a Python function `def imflip_(img, direction='horizontal')` to solve the following problem:
Inplace flip an... | Inplace flip an image horizontally or vertically. Args: img (ndarray): Image to be flipped. direction (str): The flip direction, either "horizontal" or "vertical" or "diagonal". Returns: ndarray: The flipped image (inplace). |
9,525 | import numbers
import cv2
import numpy as np
from ..utils import to_2tuple
from .io import imread_backend
cv2_interp_codes = {
'nearest': cv2.INTER_NEAREST,
'bilinear': cv2.INTER_LINEAR,
'bicubic': cv2.INTER_CUBIC,
'area': cv2.INTER_AREA,
'lanczos': cv2.INTER_LANCZOS4
}
The provided code snippet in... | Rotate an image. Args: img (ndarray): Image to be rotated. angle (float): Rotation angle in degrees, positive values mean clockwise rotation. center (tuple[float], optional): Center point (w, h) of the rotation in the source image. If not specified, the center of the image will be used. scale (float): Isotropic scale f... |
9,526 | import numbers
import cv2
import numpy as np
from ..utils import to_2tuple
from .io import imread_backend
def bbox_clip(bboxes, img_shape):
"""Clip bboxes to fit the image shape.
Args:
bboxes (ndarray): Shape (..., 4*k)
img_shape (tuple[int]): (height, width) of the image.
Returns:
n... | Crop image patches. 3 steps: scale the bboxes -> clip bboxes -> crop and pad. Args: img (ndarray): Image to be cropped. bboxes (ndarray): Shape (k, 4) or (4, ), location of cropped bboxes. scale (float, optional): Scale ratio of bboxes, the default value 1.0 means no padding. pad_fill (Number | list[Number]): Value to ... |
9,527 | import numbers
import cv2
import numpy as np
from ..utils import to_2tuple
from .io import imread_backend
def impad(img,
*,
shape=None,
padding=None,
pad_val=0,
padding_mode='constant'):
"""Pad the given image to a certain shape or pad on all sides with
specifie... | Pad an image to ensure each edge to be multiple to some number. Args: img (ndarray): Image to be padded. divisor (int): Padded image edges will be multiple to divisor. pad_val (Number | Sequence[Number]): Same as :func:`impad`. Returns: ndarray: The padded image. |
9,528 | import numbers
import cv2
import numpy as np
from ..utils import to_2tuple
from .io import imread_backend
The provided code snippet includes necessary dependencies for implementing the `cutout` function. Write a Python function `def cutout(img, shape, pad_val=0)` to solve the following problem:
Randomly cut out a rect... | Randomly cut out a rectangle from the original img. Args: img (ndarray): Image to be cutout. shape (int | tuple[int]): Expected cutout shape (h, w). If given as a int, the value will be used for both h and w. pad_val (int | float | tuple[int | float]): Values to be filled in the cut area. Defaults to 0. Returns: ndarra... |
9,529 | import numbers
import cv2
import numpy as np
from ..utils import to_2tuple
from .io import imread_backend
cv2_interp_codes = {
'nearest': cv2.INTER_NEAREST,
'bilinear': cv2.INTER_LINEAR,
'bicubic': cv2.INTER_CUBIC,
'area': cv2.INTER_AREA,
'lanczos': cv2.INTER_LANCZOS4
}
def _get_shear_matrix(magnitu... | Shear an image. Args: img (ndarray): Image to be sheared with format (h, w) or (h, w, c). magnitude (int | float): The magnitude used for shear. direction (str): The flip direction, either "horizontal" or "vertical". border_value (int | tuple[int]): Value used in case of a constant border. interpolation (str): Same as ... |
9,530 | import numbers
import cv2
import numpy as np
from ..utils import to_2tuple
from .io import imread_backend
cv2_interp_codes = {
'nearest': cv2.INTER_NEAREST,
'bilinear': cv2.INTER_LINEAR,
'bicubic': cv2.INTER_CUBIC,
'area': cv2.INTER_AREA,
'lanczos': cv2.INTER_LANCZOS4
}
def _get_translate_matrix(off... | Translate an image. Args: img (ndarray): Image to be translated with format (h, w) or (h, w, c). offset (int | float): The offset used for translate. direction (str): The translate direction, either "horizontal" or "vertical". border_value (int | tuple[int]): Value used in case of a constant border. interpolation (str)... |
9,531 | import numpy as np
import annotator.uniformer.mmcv as mmcv
try:
import torch
except ImportError:
torch = None
The provided code snippet includes necessary dependencies for implementing the `tensor2imgs` function. Write a Python function `def tensor2imgs(tensor, mean=(0, 0, 0), std=(1, 1, 1), to_rgb=True)` to s... | Convert tensor to 3-channel images. Args: tensor (torch.Tensor): Tensor that contains multiple images, shape ( N, C, H, W). mean (tuple[float], optional): Mean of images. Defaults to (0, 0, 0). std (tuple[float], optional): Standard deviation of images. Defaults to (1, 1, 1). to_rgb (bool, optional): Whether the tensor... |
9,532 | import io
import os.path as osp
from pathlib import Path
import cv2
import numpy as np
from cv2 import (IMREAD_COLOR, IMREAD_GRAYSCALE, IMREAD_IGNORE_ORIENTATION,
IMREAD_UNCHANGED)
from annotator.uniformer.mmcv.utils import check_file_exist, is_str, mkdir_or_exist
try:
import tifffile
except Import... | Select a backend for image decoding. Args: backend (str): The image decoding backend type. Options are `cv2`, `pillow`, `turbojpeg` (see https://github.com/lilohuang/PyTurboJPEG) and `tifffile`. `turbojpeg` is faster but it only supports `.jpeg` file format. |
9,533 | import io
import os.path as osp
from pathlib import Path
import cv2
import numpy as np
from cv2 import (IMREAD_COLOR, IMREAD_GRAYSCALE, IMREAD_IGNORE_ORIENTATION,
IMREAD_UNCHANGED)
from annotator.uniformer.mmcv.utils import check_file_exist, is_str, mkdir_or_exist
try:
import tifffile
except Import... | Read an image. Args: img_or_path (ndarray or str or Path): Either a numpy array or str or pathlib.Path. If it is a numpy array (loaded image), then it will be returned as is. flag (str): Flags specifying the color type of a loaded image, candidates are `color`, `grayscale`, `unchanged`, `color_ignore_orientation` and `... |
9,534 | import io
import os.path as osp
from pathlib import Path
import cv2
import numpy as np
from cv2 import (IMREAD_COLOR, IMREAD_GRAYSCALE, IMREAD_IGNORE_ORIENTATION,
IMREAD_UNCHANGED)
from annotator.uniformer.mmcv.utils import check_file_exist, is_str, mkdir_or_exist
jpeg = None
supported_backends = ['cv2... | Read an image from bytes. Args: content (bytes): Image bytes got from files or other streams. flag (str): Same as :func:`imread`. backend (str | None): The image decoding backend type. Options are `cv2`, `pillow`, `turbojpeg`, `None`. If backend is None, the global imread_backend specified by ``mmcv.use_backend()`` wil... |
9,535 | import io
import os.path as osp
from pathlib import Path
import cv2
import numpy as np
from cv2 import (IMREAD_COLOR, IMREAD_GRAYSCALE, IMREAD_IGNORE_ORIENTATION,
IMREAD_UNCHANGED)
from annotator.uniformer.mmcv.utils import check_file_exist, is_str, mkdir_or_exist
The provided code snippet includes ne... | Write image to file. Args: img (ndarray): Image array to be written. file_path (str): Image file path. params (None or list): Same as opencv :func:`imwrite` interface. auto_mkdir (bool): If the parent folder of `file_path` does not exist, whether to create it automatically. Returns: bool: Successful or not. |
9,536 | import cv2
import numpy as np
from annotator.uniformer.mmcv.image import imread, imwrite
from .color import color_val
def imshow(img, win_name='', wait_time=0):
"""Show an image.
Args:
img (str or ndarray): The image to be displayed.
win_name (str): The window name.
wait_time (int): Valu... | Draw bboxes on an image. Args: img (str or ndarray): The image to be displayed. bboxes (list or ndarray): A list of ndarray of shape (k, 4). colors (list[str or tuple or Color]): A list of colors. top_k (int): Plot the first k bboxes only if set positive. thickness (int): Thickness of lines. show (bool): Whether to sho... |
9,537 | import cv2
import numpy as np
from annotator.uniformer.mmcv.image import imread, imwrite
from .color import color_val
def imshow(img, win_name='', wait_time=0):
"""Show an image.
Args:
img (str or ndarray): The image to be displayed.
win_name (str): The window name.
wait_time (int): Valu... | Draw bboxes and class labels (with scores) on an image. Args: img (str or ndarray): The image to be displayed. bboxes (ndarray): Bounding boxes (with scores), shaped (n, 4) or (n, 5). labels (ndarray): Labels of bboxes. class_names (list[str]): Names of each classes. score_thr (float): Minimum score of bboxes to be sho... |
9,538 | from __future__ import division
import numpy as np
from annotator.uniformer.mmcv.image import rgb2bgr
from annotator.uniformer.mmcv.video import flowread
from .image import imshow
def flow2rgb(flow, color_wheel=None, unknown_thr=1e6):
"""Convert flow map to RGB image.
Args:
flow (ndarray): Array of opti... | Show optical flow. Args: flow (ndarray or str): The optical flow to be displayed. win_name (str): The window name. wait_time (int): Value of waitKey param. |
9,539 | from ..utils import ext_loader
ext_module = ext_loader.load_ext('_ext', ['bbox_overlaps'])
The provided code snippet includes necessary dependencies for implementing the `bbox_overlaps` function. Write a Python function `def bbox_overlaps(bboxes1, bboxes2, mode='iou', aligned=False, offset=0)` to solve the following p... | Calculate overlap between two set of bboxes. If ``aligned`` is ``False``, then calculate the ious between each bbox of bboxes1 and bboxes2, otherwise the ious between each aligned pair of bboxes1 and bboxes2. Args: bboxes1 (Tensor): shape (m, 4) in <x1, y1, x2, y2> format or empty. bboxes2 (Tensor): shape (n, 4) in <x1... |
9,540 | import torch
import torch.nn as nn
import torch.nn.functional as F
from annotator.uniformer.mmcv.cnn import PLUGIN_LAYERS, Scale
The provided code snippet includes necessary dependencies for implementing the `NEG_INF_DIAG` function. Write a Python function `def NEG_INF_DIAG(n, device)` to solve the following problem:
... | Returns a diagonal matrix of size [n, n]. The diagonal are all "-inf". This is for avoiding calculating the overlapped element in the Criss-Cross twice. |
9,541 | import torch
import torch.nn.functional as F
from torch import nn
from torch.autograd import Function
from ..utils import ext_loader
class FusedBiasLeakyReLUFunction(Function):
def forward(ctx, input, bias, negative_slope, scale):
empty = input.new_empty(0)
out = ext_module.fused_bias_leakyrelu(
... | Fused bias leaky ReLU function. This function is introduced in the StyleGAN2: http://arxiv.org/abs/1912.04958 The bias term comes from the convolution operation. In addition, to keep the variance of the feature map or gradients unchanged, they also adopt a scale similarly with Kaiming initialization. However, since the... |
9,542 | import torch
from ..utils import ext_loader
ext_module = ext_loader.load_ext('_ext', [
'iou3d_boxes_iou_bev_forward', 'iou3d_nms_forward',
'iou3d_nms_normal_forward'
])
The provided code snippet includes necessary dependencies for implementing the `boxes_iou_bev` function. Write a Python function `def boxes_io... | Calculate boxes IoU in the Bird's Eye View. Args: boxes_a (torch.Tensor): Input boxes a with shape (M, 5). boxes_b (torch.Tensor): Input boxes b with shape (N, 5). Returns: ans_iou (torch.Tensor): IoU result with shape (M, N). |
9,543 | import torch
from ..utils import ext_loader
ext_module = ext_loader.load_ext('_ext', [
'iou3d_boxes_iou_bev_forward', 'iou3d_nms_forward',
'iou3d_nms_normal_forward'
])
The provided code snippet includes necessary dependencies for implementing the `nms_bev` function. Write a Python function `def nms_bev(boxes,... | NMS function GPU implementation (for BEV boxes). The overlap of two boxes for IoU calculation is defined as the exact overlapping area of the two boxes. In this function, one can also set ``pre_max_size`` and ``post_max_size``. Args: boxes (torch.Tensor): Input boxes with the shape of [N, 5] ([x1, y1, x2, y2, ry]). sco... |
9,544 | import torch
from ..utils import ext_loader
ext_module = ext_loader.load_ext('_ext', [
'iou3d_boxes_iou_bev_forward', 'iou3d_nms_forward',
'iou3d_nms_normal_forward'
])
The provided code snippet includes necessary dependencies for implementing the `nms_normal_bev` function. Write a Python function `def nms_nor... | Normal NMS function GPU implementation (for BEV boxes). The overlap of two boxes for IoU calculation is defined as the exact overlapping area of the two boxes WITH their yaw angle set to 0. Args: boxes (torch.Tensor): Input boxes with shape (N, 5). scores (torch.Tensor): Scores of predicted boxes with shape (N). thresh... |
9,545 | from typing import List
import torch
from torch import nn as nn
from annotator.uniformer.mmcv.runner import force_fp32
from .furthest_point_sample import (furthest_point_sample,
furthest_point_sample_with_dist)
The provided code snippet includes necessary dependencies for implementi... | Calculating square distance between a and b. Args: point_feat_a (Tensor): (B, N, C) Feature vector of each point. point_feat_b (Tensor): (B, M, C) Feature vector of each point. norm (Bool, optional): Whether to normalize the distance. Default: True. Returns: Tensor: (B, N, M) Distance between each pair points. |
9,546 | from typing import List
import torch
from torch import nn as nn
from annotator.uniformer.mmcv.runner import force_fp32
from .furthest_point_sample import (furthest_point_sample,
furthest_point_sample_with_dist)
class DFPSSampler(nn.Module):
"""Using Euclidean distances of points ... | Get the type and mode of points sampler. Args: sampler_type (str): The type of points sampler. The valid value are "D-FPS", "F-FPS", or "FS". Returns: class: Points sampler type. |
9,547 | from ..utils import ext_loader
ext_module = ext_loader.load_ext('_ext', ['box_iou_rotated'])
The provided code snippet includes necessary dependencies for implementing the `box_iou_rotated` function. Write a Python function `def box_iou_rotated(bboxes1, bboxes2, mode='iou', aligned=False)` to solve the following probl... | Return intersection-over-union (Jaccard index) of boxes. Both sets of boxes are expected to be in (x_center, y_center, width, height, angle) format. If ``aligned`` is ``False``, then calculate the ious between each bbox of bboxes1 and bboxes2, otherwise the ious between each aligned pair of bboxes1 and bboxes2. Argumen... |
9,548 | import torch
from torch.autograd import Function
from torch.nn import functional as F
from annotator.uniformer.mmcv.utils import to_2tuple
from ..utils import ext_loader
class UpFirDn2d(Function):
def forward(ctx, input, kernel, up, down, pad):
up_x, up_y = up
down_x, down_y = down
pad_x0, p... | UpFRIDn for 2d features. UpFIRDn is short for upsample, apply FIR filter and downsample. More details can be found in: https://www.mathworks.com/help/signal/ref/upfirdn.html Args: input (Tensor): Tensor with shape of (n, c, h, w). kernel (Tensor): Filter kernel. up (int | tuple[int], optional): Upsampling factor. If gi... |
9,549 | import os
import numpy as np
import torch
from annotator.uniformer.mmcv.utils import deprecated_api_warning
from ..utils import ext_loader
ext_module = ext_loader.load_ext(
'_ext', ['nms', 'softnms', 'nms_match', 'nms_rotated'])
class NMSop(torch.autograd.Function):
def forward(ctx, bboxes, scores, iou_threshol... | Dispatch to either CPU or GPU NMS implementations. The input can be either torch tensor or numpy array. GPU NMS will be used if the input is gpu tensor, otherwise CPU NMS will be used. The returned type will always be the same as inputs. Arguments: boxes (torch.Tensor or np.ndarray): boxes in shape (N, 4). scores (torc... |
9,550 | import os
import numpy as np
import torch
from annotator.uniformer.mmcv.utils import deprecated_api_warning
from ..utils import ext_loader
ext_module = ext_loader.load_ext(
'_ext', ['nms', 'softnms', 'nms_match', 'nms_rotated'])
class SoftNMSop(torch.autograd.Function):
def forward(ctx, boxes, scores, iou_thres... | Dispatch to only CPU Soft NMS implementations. The input can be either a torch tensor or numpy array. The returned type will always be the same as inputs. Arguments: boxes (torch.Tensor or np.ndarray): boxes in shape (N, 4). scores (torch.Tensor or np.ndarray): scores in shape (N, ). iou_threshold (float): IoU threshol... |
9,551 | import os
import numpy as np
import torch
from annotator.uniformer.mmcv.utils import deprecated_api_warning
from ..utils import ext_loader
The provided code snippet includes necessary dependencies for implementing the `batched_nms` function. Write a Python function `def batched_nms(boxes, scores, idxs, nms_cfg, class_... | Performs non-maximum suppression in a batched fashion. Modified from https://github.com/pytorch/vision/blob /505cd6957711af790211896d32b40291bea1bc21/torchvision/ops/boxes.py#L39. In order to perform NMS independently per class, we add an offset to all the boxes. The offset is dependent only on the class idx, and is la... |
9,552 | import os
import numpy as np
import torch
from annotator.uniformer.mmcv.utils import deprecated_api_warning
from ..utils import ext_loader
ext_module = ext_loader.load_ext(
'_ext', ['nms', 'softnms', 'nms_match', 'nms_rotated'])
The provided code snippet includes necessary dependencies for implementing the `nms_ma... | Matched dets into different groups by NMS. NMS match is Similar to NMS but when a bbox is suppressed, nms match will record the indice of suppressed bbox and form a group with the indice of kept bbox. In each group, indice is sorted as score order. Arguments: dets (torch.Tensor | np.ndarray): Det boxes with scores, sha... |
9,553 | import os
import numpy as np
import torch
from annotator.uniformer.mmcv.utils import deprecated_api_warning
from ..utils import ext_loader
ext_module = ext_loader.load_ext(
'_ext', ['nms', 'softnms', 'nms_match', 'nms_rotated'])
The provided code snippet includes necessary dependencies for implementing the `nms_ro... | Performs non-maximum suppression (NMS) on the rotated boxes according to their intersection-over-union (IoU). Rotated NMS iteratively removes lower scoring rotated boxes which have an IoU greater than iou_threshold with another (higher scoring) rotated box. Args: boxes (Tensor): Rotated boxes in shape (N, 5). They are ... |
9,554 | import torch
from ..utils import ext_loader
ext_module = ext_loader.load_ext('_ext', [
'points_in_boxes_part_forward', 'points_in_boxes_cpu_forward',
'points_in_boxes_all_forward'
])
The provided code snippet includes necessary dependencies for implementing the `points_in_boxes_part` function. Write a Python f... | Find the box in which each point is (CUDA). Args: points (torch.Tensor): [B, M, 3], [x, y, z] in LiDAR/DEPTH coordinate boxes (torch.Tensor): [B, T, 7], num_valid_boxes <= T, [x, y, z, x_size, y_size, z_size, rz] in LiDAR/DEPTH coordinate, (x, y, z) is the bottom center Returns: box_idxs_of_pts (torch.Tensor): (B, M), ... |
9,555 | import torch
from ..utils import ext_loader
ext_module = ext_loader.load_ext('_ext', [
'points_in_boxes_part_forward', 'points_in_boxes_cpu_forward',
'points_in_boxes_all_forward'
])
The provided code snippet includes necessary dependencies for implementing the `points_in_boxes_cpu` function. Write a Python fu... | Find all boxes in which each point is (CPU). The CPU version of :meth:`points_in_boxes_all`. Args: points (torch.Tensor): [B, M, 3], [x, y, z] in LiDAR/DEPTH coordinate boxes (torch.Tensor): [B, T, 7], num_valid_boxes <= T, [x, y, z, x_size, y_size, z_size, rz], (x, y, z) is the bottom center. Returns: box_idxs_of_pts ... |
9,556 | import torch
from ..utils import ext_loader
ext_module = ext_loader.load_ext('_ext', [
'points_in_boxes_part_forward', 'points_in_boxes_cpu_forward',
'points_in_boxes_all_forward'
])
The provided code snippet includes necessary dependencies for implementing the `points_in_boxes_all` function. Write a Python fu... | Find all boxes in which each point is (CUDA). Args: points (torch.Tensor): [B, M, 3], [x, y, z] in LiDAR/DEPTH coordinate boxes (torch.Tensor): [B, T, 7], num_valid_boxes <= T, [x, y, z, x_size, y_size, z_size, rz], (x, y, z) is the bottom center. Returns: box_idxs_of_pts (torch.Tensor): (B, M, T), default background =... |
9,557 | import numpy as np
import torch
from ..utils import ext_loader
ext_module = ext_loader.load_ext('_ext', ['contour_expand'])
The provided code snippet includes necessary dependencies for implementing the `contour_expand` function. Write a Python function `def contour_expand(kernel_mask, internal_kernel_label, min_kerne... | Expand kernel contours so that foreground pixels are assigned into instances. Arguments: kernel_mask (np.array or Tensor): The instance kernel mask with size hxw. internal_kernel_label (np.array or Tensor): The instance internal kernel label with size hxw. min_kernel_area (int): The minimum kernel area. kernel_num (int... |
9,558 | import math
import warnings
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd.function import Function, once_differentiable
from annotator.uniformer.mmcv import deprecated_api_warning
from annotator.uniformer.mmcv.cnn import constant_init, xavier_init
from annotator.uniformer.mmcv.c... | CPU version of multi-scale deformable attention. Args: value (Tensor): The value has shape (bs, num_keys, mum_heads, embed_dims//num_heads) value_spatial_shapes (Tensor): Spatial shape of each feature map, has shape (num_levels, 2), last dimension 2 represent (h, w) sampling_locations (Tensor): The location of sampling... |
9,559 | from os import path as osp
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.modules.utils import _pair
from torch.onnx.operators import shape_as_tensor
def normalize(grid):
"""Normalize input grid from [-1, 1] to [0, 1]
Args:
grid (Tensor): The grid to be normalize, range... | Generate regular square grid of points in [0, 1] x [0, 1] coordinate space. Args: num_grid (int): The number of grids to sample, one for each region. size (tuple(int, int)): The side size of the regular grid. device (torch.device): Desired device of returned tensor. Returns: (torch.Tensor): A tensor of shape (num_grid,... |
9,560 | from os import path as osp
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.modules.utils import _pair
from torch.onnx.operators import shape_as_tensor
def rel_roi_point_to_abs_img_point(rois, rel_roi_points):
"""Convert roi based relative point coordinates to image based absolute
... | Convert roi based relative point coordinates to image based absolute point coordinates. Args: rois (Tensor): RoIs or BBoxes, shape (N, 4) or (N, 5) rel_roi_points (Tensor): Point coordinates inside RoI, relative to RoI, location, range (0, 1), shape (N, P, 2) img (tuple/Tensor): (height, width) of image or feature map.... |
9,561 | from os import path as osp
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.modules.utils import _pair
from torch.onnx.operators import shape_as_tensor
def bilinear_grid_sample(im, grid, align_corners=False):
"""Given an input and a flow-field grid, computes the output using input
... | A wrapper around :func:`grid_sample` to support 3D point_coords tensors Unlike :func:`torch.nn.functional.grid_sample` it assumes point_coords to lie inside ``[0, 1] x [0, 1]`` square. Args: input (Tensor): Feature map, shape (N, C, H, W). points (Tensor): Image based absolute point coordinates (normalized), range [0, ... |
9,562 | import glob
import os
import torch
def get_compiler_version():
return 'GCC ' + parrots.version.compiler | null |
9,563 | import glob
import os
import torch
def get_compiling_cuda_version():
return parrots.version.cuda | null |
9,564 | import glob
import os
import torch
def get_compiler_version():
return ext_module.get_compiler_version() | null |
9,565 | import glob
import os
import torch
def get_compiling_cuda_version():
return ext_module.get_compiling_cuda_version() | null |
9,566 | import glob
import os
import torch
def get_onnxruntime_op_path():
wildcard = os.path.join(
os.path.abspath(os.path.dirname(os.path.dirname(__file__))),
'_ext_ort.*.so')
paths = glob.glob(wildcard)
if len(paths) > 0:
return paths[0]
else:
return '' | null |
9,567 | import numpy as np
import torch
from ..utils import ext_loader
ext_module = ext_loader.load_ext('_ext', ['pixel_group'])
The provided code snippet includes necessary dependencies for implementing the `pixel_group` function. Write a Python function `def pixel_group(score, mask, embedding, kernel_label, kernel_contour, ... | Group pixels into text instances, which is widely used text detection methods. Arguments: score (np.array or Tensor): The foreground score with size hxw. mask (np.array or Tensor): The foreground mask with size hxw. embedding (np.array or Tensor): The embedding with size hxwxc to distinguish instances. kernel_label (np... |
9,568 | import os
import os.path as osp
import subprocess
import tempfile
from annotator.uniformer.mmcv.utils import requires_executable
def convert_video(in_file,
out_file,
print_cmd=False,
pre_options='',
**kwargs):
"""Convert a video with ffmpeg.
... | Resize a video. Args: in_file (str): Input video filename. out_file (str): Output video filename. size (tuple): Expected size (w, h), eg, (320, 240) or (320, -1). ratio (tuple or float): Expected resize ratio, (2, 0.5) means (w*2, h*0.5). keep_ar (bool): Whether to keep original aspect ratio. log_level (str): Logging l... |
9,569 | import os
import os.path as osp
import subprocess
import tempfile
from annotator.uniformer.mmcv.utils import requires_executable
def convert_video(in_file,
out_file,
print_cmd=False,
pre_options='',
**kwargs):
"""Convert a video with ffmpeg.
... | Cut a clip from a video. Args: in_file (str): Input video filename. out_file (str): Output video filename. start (None or float): Start time (in seconds). end (None or float): End time (in seconds). vcodec (None or str): Output video codec, None for unchanged. acodec (None or str): Output audio codec, None for unchange... |
9,570 | import os
import os.path as osp
import subprocess
import tempfile
from annotator.uniformer.mmcv.utils import requires_executable
def convert_video(in_file,
out_file,
print_cmd=False,
pre_options='',
**kwargs):
"""Convert a video with ffmpeg.
... | Concatenate multiple videos into a single one. Args: video_list (list): A list of video filenames out_file (str): Output video filename vcodec (None or str): Output video codec, None for unchanged acodec (None or str): Output audio codec, None for unchanged log_level (str): Logging level of ffmpeg. print_cmd (bool): Wh... |
9,571 | import os.path as osp
from collections import OrderedDict
import cv2
from cv2 import (CAP_PROP_FOURCC, CAP_PROP_FPS, CAP_PROP_FRAME_COUNT,
CAP_PROP_FRAME_HEIGHT, CAP_PROP_FRAME_WIDTH,
CAP_PROP_POS_FRAMES, VideoWriter_fourcc)
from annotator.uniformer.mmcv.utils import (check_file_exist,... | Read the frame images from a directory and join them as a video. Args: frame_dir (str): The directory containing video frames. video_file (str): Output filename. fps (float): FPS of the output video. fourcc (str): Fourcc of the output video, this should be compatible with the output file type. filename_tmpl (str): File... |
9,572 | import warnings
import cv2
import numpy as np
from annotator.uniformer.mmcv.arraymisc import dequantize, quantize
from annotator.uniformer.mmcv.image import imread, imwrite
from annotator.uniformer.mmcv.utils import is_str
def dequantize_flow(dx, dy, max_val=0.02, denorm=True):
"""Recover from quantized flow.
A... | Read an optical flow map. Args: flow_or_path (ndarray or str): A flow map or filepath. quantize (bool): whether to read quantized pair, if set to True, remaining args will be passed to :func:`dequantize_flow`. concat_axis (int): The axis that dx and dy are concatenated, can be either 0 or 1. Ignored if quantize is Fals... |
9,573 | import warnings
import cv2
import numpy as np
from annotator.uniformer.mmcv.arraymisc import dequantize, quantize
from annotator.uniformer.mmcv.image import imread, imwrite
from annotator.uniformer.mmcv.utils import is_str
def quantize_flow(flow, max_val=0.02, norm=True):
"""Quantize flow to [0, 255].
After thi... | Write optical flow to file. If the flow is not quantized, it will be saved as a .flo file losslessly, otherwise a jpeg image which is lossy but of much smaller size. (dx and dy will be concatenated horizontally into a single image if quantize is True.) Args: flow (ndarray): (h, w, 2) array of optical flow. filename (st... |
9,574 | import warnings
import cv2
import numpy as np
from annotator.uniformer.mmcv.arraymisc import dequantize, quantize
from annotator.uniformer.mmcv.image import imread, imwrite
from annotator.uniformer.mmcv.utils import is_str
The provided code snippet includes necessary dependencies for implementing the `flow_warp` funct... | Use flow to warp img. Args: img (ndarray, float or uint8): Image to be warped. flow (ndarray, float): Optical Flow. filling_value (int): The missing pixels will be set with filling_value. interpolate_mode (str): bilinear -> Bilinear Interpolation; nearest -> Nearest Neighbor. Returns: ndarray: Warped image with the sam... |
9,575 | import warnings
import cv2
import numpy as np
from annotator.uniformer.mmcv.arraymisc import dequantize, quantize
from annotator.uniformer.mmcv.image import imread, imwrite
from annotator.uniformer.mmcv.utils import is_str
The provided code snippet includes necessary dependencies for implementing the `flow_from_bytes`... | Read dense optical flow from bytes. .. note:: This load optical flow function works for FlyingChairs, FlyingThings3D, Sintel, FlyingChairsOcc datasets, but cannot load the data from ChairsSDHom. Args: content (bytes): Optical flow bytes got from files or other streams. Returns: ndarray: Loaded optical flow with the sha... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.