id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
16,701 | from typing import Literal, Union, Optional, Tuple, List
import torch
from transformers import CLIPTextModel, CLIPTokenizer, CLIPTextModelWithProjection
from diffusers import (
UNet2DConditionModel,
SchedulerMixin,
StableDiffusionPipeline,
StableDiffusionXLPipeline,
AutoencoderKL,
)
from diffusers.p... | null |
16,702 | from typing import Literal, Union, Optional, Tuple, List
import torch
from transformers import CLIPTextModel, CLIPTokenizer, CLIPTextModelWithProjection
from diffusers import (
UNet2DConditionModel,
SchedulerMixin,
StableDiffusionPipeline,
StableDiffusionXLPipeline,
AutoencoderKL,
)
from diffusers.p... | null |
16,703 | from typing import Literal, Union, Optional, Tuple, List
import torch
from transformers import CLIPTextModel, CLIPTokenizer, CLIPTextModelWithProjection
from diffusers import (
UNet2DConditionModel,
SchedulerMixin,
StableDiffusionPipeline,
StableDiffusionXLPipeline,
AutoencoderKL,
)
from diffusers.p... | null |
16,704 | from typing import Literal, Union, Optional, Tuple, List
import torch
from transformers import CLIPTextModel, CLIPTokenizer, CLIPTextModelWithProjection
from diffusers import (
UNet2DConditionModel,
SchedulerMixin,
StableDiffusionPipeline,
StableDiffusionXLPipeline,
AutoencoderKL,
)
from diffusers.p... | null |
16,705 | import os
import sys
import time
import subprocess
from cog import BasePredictor, Input, Path
import cv2
import torch
import numpy as np
from PIL import Image
from diffusers.utils import load_image
from diffusers.models import ControlNetModel
from insightface.app import FaceAnalysis
from pipeline_stable_diffusion_xl_in... | null |
16,706 | import os
import sys
import time
import subprocess
from cog import BasePredictor, Input, Path
import cv2
import torch
import numpy as np
from PIL import Image
from diffusers.utils import load_image
from diffusers.models import ControlNetModel
from insightface.app import FaceAnalysis
from pipeline_stable_diffusion_xl_in... | null |
16,707 | from typing import Any, Callable, Dict, List, Optional, Tuple, Union
import cv2
import math
import numpy as np
import PIL.Image
import torch
import torch.nn.functional as F
from diffusers.image_processor import PipelineImageInput
from diffusers.models import ControlNetModel
from diffusers.utils import (
deprecate,
... | null |
16,708 | from typing import Any, Callable, Dict, List, Optional, Tuple, Union
import cv2
import math
import numpy as np
import PIL.Image
import torch
import torch.nn.functional as F
from diffusers.image_processor import PipelineImageInput
from diffusers.models import ControlNetModel
from diffusers.utils import (
deprecate,
... | null |
16,709 | import torch.nn.functional as F
def is_torch2_available():
return hasattr(F, "scaled_dot_product_attention") | null |
16,710 | import math
import torch
import torch.nn as nn
def FeedForward(dim, mult=4):
inner_dim = int(dim * mult)
return nn.Sequential(
nn.LayerNorm(dim),
nn.Linear(dim, inner_dim, bias=False),
nn.GELU(),
nn.Linear(inner_dim, dim, bias=False),
) | null |
16,711 | import math
import torch
import torch.nn as nn
def reshape_tensor(x, heads):
bs, length, width = x.shape
#(bs, length, width) --> (bs, length, n_heads, dim_per_head)
x = x.view(bs, length, heads, -1)
# (bs, length, n_heads, dim_per_head) --> (bs, n_heads, length, dim_per_head)
x = x.transpose(1, 2)... | null |
16,712 | import cv2
import torch
import numpy as np
from PIL import Image
from diffusers.utils import load_image
from diffusers.models import ControlNetModel
from diffusers.pipelines.controlnet.multicontrolnet import MultiControlNetModel
from insightface.app import FaceAnalysis
from pipeline_stable_diffusion_xl_instantid_full i... | null |
16,713 | import cv2
import torch
import numpy as np
from PIL import Image
from diffusers.utils import load_image
from diffusers.models import ControlNetModel
from diffusers.pipelines.controlnet.multicontrolnet import MultiControlNetModel
from insightface.app import FaceAnalysis
from pipeline_stable_diffusion_xl_instantid_full i... | null |
16,714 | import cv2
import torch
import numpy as np
from PIL import Image
from diffusers.utils import load_image
from diffusers.models import ControlNetModel
from insightface.app import FaceAnalysis
from pipeline_stable_diffusion_xl_instantid import StableDiffusionXLInstantIDPipeline, draw_kps
def resize_img(input_image, max_s... | null |
16,715 | import torch
import torch.nn as nn
def fixed_pos_embedding(x):
seq_len, dim = x.shape
inv_freq = 1.0 / (10000 ** (torch.arange(0, dim) / dim))
sinusoid_inp = (
torch.einsum("i , j -> i j", torch.arange(0, seq_len, dtype=torch.float), inv_freq).to(x)
)
return torch.sin(sinusoid_inp), torch.c... | null |
16,716 | import torch
import torch.nn as nn
def rotate_every_two(x):
x1 = x[:, :, ::2]
x2 = x[:, :, 1::2]
x = torch.stack((-x2, x1), dim=-1)
if x.shape[-1]%2 == 1:
# fill last dim with zero if hidden_size is odd
x2 = torch.concat((x2, torch.zeros_like(x2[:, :, :1])), dim=-1)
return x.flatten(... | null |
16,717 | import os
import ffmpeg
import whisper
import argparse
import warnings
import tempfile
from .utils import filename, str2bool, write_srt
def filename(path):
def get_audio(paths):
temp_dir = tempfile.gettempdir()
audio_paths = {}
for path in paths:
print(f"Extracting audio from {filename(path)}...... | null |
16,718 | import os
import ffmpeg
import whisper
import argparse
import warnings
import tempfile
from .utils import filename, str2bool, write_srt
def write_srt(transcript: Iterator[dict], file: TextIO):
for i, segment in enumerate(transcript, start=1):
print(
f"{i}\n"
f"{format_timestamp(segm... | null |
16,719 | import os
from typing import Iterator, TextIO
def str2bool(string):
string = string.lower()
str2val = {"true": True, "false": False}
if string in str2val:
return str2val[string]
else:
raise ValueError(
f"Expected one of {set(str2val.keys())}, got {string}") | null |
16,720 | import cv2
import numpy as np
import tensorflow as tf
from tensorflow.contrib.framework.python.ops import add_arg_scope
def gate_conv(x_in, cnum, ksize, stride=1, rate=1, name='conv',
padding='SAME', activation='leaky_relu', use_lrn=True,training=True):
assert padding in ['SYMMETRIC', 'SAME', 'REFELEC... | null |
16,721 | import cv2
import numpy as np
import tensorflow as tf
from tensorflow.contrib.framework.python.ops import add_arg_scope
def gate_deconv(input_, output_shape, k_h=5, k_w=5, d_h=2, d_w=2, stddev=0.02,
name="deconv", training=True):
with tf.variable_scope(name):
# filter : [height, width, output_channe... | null |
16,722 | import os
import torch
from setuptools import find_packages, setup
from torch.utils.cpp_extension import BuildExtension, CppExtension, CUDAExtension
def make_cuda_ext(
name, module, sources, sources_cuda=[], extra_args=[], extra_include_path=[]
):
define_macros = []
extra_compile_args = {"cxx": [] + extra... | null |
16,723 | import torch
from mmcv.parallel import MMDistributedDataParallel
from mmcv.runner import (
DistSamplerSeedHook,
EpochBasedRunner,
GradientCumulativeFp16OptimizerHook,
Fp16OptimizerHook,
OptimizerHook,
build_optimizer,
build_runner,
)
from mmdet3d.runner import CustomEpochBasedRunner
from mmd... | null |
16,724 | import numba
import numpy as np
def camera_to_lidar(points, r_rect, velo2cam):
"""Convert points in camera coordinate to lidar coordinate.
Args:
points (np.ndarray, shape=[N, 3]): Points in camera coordinate.
r_rect (np.ndarray, shape=[4, 4]): Matrix to project points in
specific cam... | Covert boxes in camera coordinate to lidar coordinate. Args: data (np.ndarray, shape=[N, 7]): Boxes in camera coordinate. r_rect (np.ndarray, shape=[4, 4]): Matrix to project points in specific camera coordinate (e.g. CAM2) to CAM0. velo2cam (np.ndarray, shape=[4, 4]): Matrix to project points in camera coordinate to l... |
16,725 | import numba
import numpy as np
def camera_to_lidar(points, r_rect, velo2cam):
"""Convert points in camera coordinate to lidar coordinate.
Args:
points (np.ndarray, shape=[N, 3]): Points in camera coordinate.
r_rect (np.ndarray, shape=[4, 4]): Matrix to project points in
specific cam... | Convert depth map to points in lidar coordinate. Args: depth (np.array, shape=[H, W]): Depth map which the row of [0~`trunc_pixel`] are truncated. trunc_pixel (int): The number of truncated row. P2 (p.array, shape=[4, 4]): Intrinsics of Camera2. r_rect (np.ndarray, shape=[4, 4]): Matrix to project points in specific ca... |
16,726 | import numba
import numpy as np
The provided code snippet includes necessary dependencies for implementing the `rotation_points_single_angle` function. Write a Python function `def rotation_points_single_angle(points, angle, axis=0)` to solve the following problem:
Rotate points with a single angle. Args: points (np.n... | Rotate points with a single angle. Args: points (np.ndarray, shape=[N, 3]]): angle (np.ndarray, shape=[1]]): axis (int, optional): Axis to rotate at. Defaults to 0. Returns: np.ndarray: Rotated points. |
16,727 | import numba
import numpy as np
def center_to_corner_box3d(centers, dims, angles=None, origin=(0.5, 1.0, 0.5), axis=1):
"""Convert kitti locations, dimensions and angles to corners.
Args:
centers (np.ndarray): Locations in kitti label file with shape (N, 3).
dims (np.ndarray): Dimensions in kitt... | Convert box3d in camera coordinates to bbox in image coordinates. Args: box3d (np.ndarray, shape=[N, 7]): Boxes in camera coordinate. P2 (np.array, shape=[4, 4]): Intrinsics of Camera2. Returns: np.ndarray, shape=[N, 4]: Boxes 2d in image coordinates. |
16,728 | import numba
import numpy as np
def center_to_corner_box2d(centers, dims, angles=None, origin=0.5):
"""Convert kitti locations, dimensions and angles to corners.
format: center(xy), dims(xy), angles(clockwise when positive)
Args:
centers (np.ndarray): Locations in kitti label file with shape (N, 2).... | Convert minmax box to corners2d. Args: minmax_box (np.ndarray, shape=[N, dims]): minmax boxes. Returns: np.ndarray: 2d corners of boxes |
16,729 | import numba
import numpy as np
The provided code snippet includes necessary dependencies for implementing the `create_anchors_3d_range` function. Write a Python function `def create_anchors_3d_range( feature_size, anchor_range, sizes=((1.6, 3.9, 1.56),), rotations=(0, np.pi / 2), dtype=np.float32,... | Create anchors 3d by range. Args: feature_size (list[float] | tuple[float]): Feature map size. It is either a list of a tuple of [D, H, W](in order of z, y, and x). anchor_range (torch.Tensor | list[float]): Range of anchors with shape [6]. The order is consistent with that of anchors, i.e., (x_min, y_min, z_min, x_max... |
16,730 | import numba
import numpy as np
def limit_period(val, offset=0.5, period=np.pi):
"""Limit the value into a period for periodic function.
Args:
val (np.ndarray): The value to be converted.
offset (float, optional): Offset to set the value range. \
Defaults to 0.5.
period (floa... | convert rotated bbox to nearest 'standing' or 'lying' bbox. Args: rbboxes (np.ndarray): Rotated bboxes with shape of \ (N, 5(x, y, xdim, ydim, rad)). Returns: np.ndarray: Bounding boxes with the shpae of (N, 4(xmin, ymin, xmax, ymax)). |
16,731 | import numba
import numpy as np
The provided code snippet includes necessary dependencies for implementing the `iou_jit` function. Write a Python function `def iou_jit(boxes, query_boxes, mode="iou", eps=0.0)` to solve the following problem:
Calculate box iou. Note that jit version runs ~10x faster than the box_overla... | Calculate box iou. Note that jit version runs ~10x faster than the box_overlaps function in mmdet3d.core.evaluation. Args: boxes (np.ndarray): Input bounding boxes with shape of (N, 4). query_boxes (np.ndarray): Query boxes with shape of (K, 4). mode (str, optional): IoU mode. Defaults to 'iou'. eps (float, optional): ... |
16,732 | import numba
import numpy as np
def camera_to_lidar(points, r_rect, velo2cam):
"""Convert points in camera coordinate to lidar coordinate.
Args:
points (np.ndarray, shape=[N, 3]): Points in camera coordinate.
r_rect (np.ndarray, shape=[4, 4]): Matrix to project points in
specific cam... | Remove points which are outside of image. Args: points (np.ndarray, shape=[N, 3+dims]): Total points. rect (np.ndarray, shape=[4, 4]): Matrix to project points in specific camera coordinate (e.g. CAM2) to CAM0. Trv2c (np.ndarray, shape=[4, 4]): Matrix to project points in camera coordinate to lidar coordinate. P2 (p.ar... |
16,733 | import numba
import numpy as np
The provided code snippet includes necessary dependencies for implementing the `points_in_convex_polygon_jit` function. Write a Python function `def points_in_convex_polygon_jit(points, polygon, clockwise=True)` to solve the following problem:
Check points is in 2d convex polygons. True... | Check points is in 2d convex polygons. True when point in polygon. Args: points (np.ndarray): Input points with the shape of [num_points, 2]. polygon (np.ndarray): Input polygon with the shape of [num_polygon, num_points_of_polygon, 2]. clockwise (bool, optional): Indicate polygon is clockwise. Defaults to True. Return... |
16,734 | import numba
import numpy as np
The provided code snippet includes necessary dependencies for implementing the `boxes3d_to_corners3d_lidar` function. Write a Python function `def boxes3d_to_corners3d_lidar(boxes3d, bottom_center=True)` to solve the following problem:
Convert kitti center boxes to corners. 7 -------- 4... | Convert kitti center boxes to corners. 7 -------- 4 /| /| 6 -------- 5 . | | | | . 3 -------- 0 |/ |/ 2 -------- 1 Args: boxes3d (np.ndarray): Boxes with shape of (N, 7) [x, y, z, w, l, h, ry] in LiDAR coords, see the definition of ry in KITTI dataset. bottom_center (bool, optional): Whether z is on the bottom center o... |
16,735 | import numpy as np
import torch
from logging import warning
The provided code snippet includes necessary dependencies for implementing the `limit_period` function. Write a Python function `def limit_period(val, offset=0.5, period=np.pi)` to solve the following problem:
Limit the value into a period for periodic functi... | Limit the value into a period for periodic function. Args: val (torch.Tensor): The value to be converted. offset (float, optional): Offset to set the value range. \ Defaults to 0.5. period ([type], optional): Period of the value. Defaults to np.pi. Returns: torch.Tensor: Value in the range of \ [-offset * period, (1-of... |
16,736 | import numpy as np
import torch
from logging import warning
The provided code snippet includes necessary dependencies for implementing the `rotation_3d_in_axis` function. Write a Python function `def rotation_3d_in_axis(points, angles, axis=0)` to solve the following problem:
Rotate points by angles according to axis.... | Rotate points by angles according to axis. Args: points (torch.Tensor): Points of shape (N, M, 3). angles (torch.Tensor): Vector of angles in shape (N,) axis (int, optional): The axis to be rotated. Defaults to 0. Raises: ValueError: when the axis is not in range [0, 1, 2], it will \ raise value error. Returns: torch.T... |
16,737 | import numpy as np
import torch
from logging import warning
The provided code snippet includes necessary dependencies for implementing the `xywhr2xyxyr` function. Write a Python function `def xywhr2xyxyr(boxes_xywhr)` to solve the following problem:
Convert a rotated boxes in XYWHR format to XYXYR format. Args: boxes_... | Convert a rotated boxes in XYWHR format to XYXYR format. Args: boxes_xywhr (torch.Tensor): Rotated boxes in XYWHR format. Returns: torch.Tensor: Converted boxes in XYXYR format. |
16,738 | import numpy as np
import torch
from logging import warning
class Box3DMode(IntEnum):
r"""Enum of different ways to represent a box.
Coordinates in LiDAR:
.. code-block:: none
up z
^ x front
| /
| /
left ... | Get the type and mode of box structure. Args: box_type (str): The type of box structure. The valid value are "LiDAR", "Camera", or "Depth". Returns: tuple: Box type and box mode. |
16,739 | import numpy as np
import torch
from logging import warning
The provided code snippet includes necessary dependencies for implementing the `points_cam2img` function. Write a Python function `def points_cam2img(points_3d, proj_mat, with_depth=False)` to solve the following problem:
Project points from camera coordicate... | Project points from camera coordicates to image coordinates. Args: points_3d (torch.Tensor): Points in shape (N, 3). proj_mat (torch.Tensor): Transformation matrix between coordinates. with_depth (bool, optional): Whether to keep depth in the output. Defaults to False. Returns: torch.Tensor: Points in image coordinates... |
16,740 | import numpy as np
import torch
from logging import warning
The provided code snippet includes necessary dependencies for implementing the `mono_cam_box2vis` function. Write a Python function `def mono_cam_box2vis(cam_box)` to solve the following problem:
This is a post-processing function on the bboxes from Mono-3D t... | This is a post-processing function on the bboxes from Mono-3D task. If we want to perform projection visualization, we need to: 1. rotate the box along x-axis for np.pi / 2 (roll) 2. change orientation from local yaw to global yaw 3. convert yaw by (np.pi / 2 - yaw) After applying this function, we can project and draw... |
16,741 | import numpy as np
import torch
from logging import warning
The provided code snippet includes necessary dependencies for implementing the `get_proj_mat_by_coord_type` function. Write a Python function `def get_proj_mat_by_coord_type(img_meta, coord_type)` to solve the following problem:
Obtain image features using po... | Obtain image features using points. Args: img_meta (dict): Meta info. coord_type (str): 'DEPTH' or 'CAMERA' or 'LIDAR'. Can be case-insensitive. Returns: torch.Tensor: transformation matrix. |
16,742 | import torch
def normalize_bbox(bboxes, pc_range):
cx = bboxes[..., 0:1]
cy = bboxes[..., 1:2]
cz = bboxes[..., 2:3]
w = bboxes[..., 3:4].log()
l = bboxes[..., 4:5].log()
h = bboxes[..., 5:6].log()
rot = bboxes[..., 6:7]
if bboxes.size(-1) > 7:
vx = bboxes[..., 7:8]
vy... | null |
16,743 | import torch
def denormalize_bbox(normalized_bboxes, pc_range):
# rotation
rot_sine = normalized_bboxes[..., 6:7]
rot_cosine = normalized_bboxes[..., 7:8]
rot = torch.atan2(rot_sine, rot_cosine)
# center in the bev
cx = normalized_bboxes[..., 0:1]
cy = normalized_bboxes[..., 1:2]
cz =... | null |
16,744 | import torch
from mmdet.core.bbox import bbox_overlaps
from mmdet.core.bbox.iou_calculators.builder import IOU_CALCULATORS
from ..structures import get_box_type
The provided code snippet includes necessary dependencies for implementing the `bbox_overlaps_nearest_3d` function. Write a Python function `def bbox_overlaps... | Calculate nearest 3D IoU. Note: This function first finds the nearest 2D boxes in bird eye view (BEV), and then calculates the 2D IoU using :meth:`bbox_overlaps`. Ths IoU calculator :class:`BboxOverlapsNearest3D` uses this function to calculate IoUs of boxes. If ``is_aligned`` is ``False``, then it calculates the ious ... |
16,745 | import torch
from mmdet.core.bbox import bbox_overlaps
from mmdet.core.bbox.iou_calculators.builder import IOU_CALCULATORS
from ..structures import get_box_type
The provided code snippet includes necessary dependencies for implementing the `bbox_overlaps_3d` function. Write a Python function `def bbox_overlaps_3d(bbox... | Calculate 3D IoU using cuda implementation. Note: This function calculates the IoU of 3D boxes based on their volumes. IoU calculator :class:`BboxOverlaps3D` uses this function to calculate the actual IoUs of boxes. Args: bboxes1 (torch.Tensor): shape (N, 7+C) [x, y, z, h, w, l, ry]. bboxes2 (torch.Tensor): shape (M, 7... |
16,746 | import torch
from mmdet.core.bbox import bbox_overlaps
from mmdet.core.bbox.iou_calculators.builder import IOU_CALCULATORS
from ..structures import get_box_type
The provided code snippet includes necessary dependencies for implementing the `axis_aligned_bbox_overlaps_3d` function. Write a Python function `def axis_ali... | Calculate overlap between two set of axis aligned 3D bboxes. If ``is_aligned`` is ``False``, then calculate the overlaps between each bbox of bboxes1 and bboxes2, otherwise the overlaps between each aligned pair of bboxes1 and bboxes2. Args: bboxes1 (Tensor): shape (B, m, 6) in <x1, y1, z1, x2, y2, z2> format or empty.... |
16,747 | import numba
import numpy as np
def _points_to_voxel_reverse_kernel(
points,
voxel_size,
coors_range,
num_points_per_voxel,
coor_to_voxelidx,
voxels,
coors,
max_points=35,
max_voxels=20000,
):
"""convert kitti points(N, >=3) to voxels.
Args:
points (np.ndarray): [N, n... | convert kitti points(N, >=3) to voxels. Args: points (np.ndarray): [N, ndim]. points[:, :3] contain xyz points and \ points[:, 3:] contain other information such as reflectivity. voxel_size (list, tuple, np.ndarray): [3] xyz, indicate voxel size coors_range (list[float | tuple[float] | ndarray]): Voxel range. \ format:... |
16,748 | import mmcv
from . import voxel_generator
The provided code snippet includes necessary dependencies for implementing the `build_voxel_generator` function. Write a Python function `def build_voxel_generator(cfg, **kwargs)` to solve the following problem:
Builder of voxel generator.
Here is the function:
def build_vox... | Builder of voxel generator. |
16,749 | import numba
import numpy as np
import torch
from mmdet3d.ops.iou3d.iou3d_utils import nms_gpu, nms_normal_gpu
def nms_gpu(boxes, scores, thresh, pre_maxsize=None, post_max_size=None):
"""Nms function with gpu implementation.
Args:
boxes (torch.Tensor): Input boxes with the shape of [N, 5]
... | Multi-class nms for 3D boxes. Args: mlvl_bboxes (torch.Tensor): Multi-level boxes with shape (N, M). M is the dimensions of boxes. mlvl_bboxes_for_nms (torch.Tensor): Multi-level boxes with shape (N, 5) ([x1, y1, x2, y2, ry]). N is the number of boxes. mlvl_scores (torch.Tensor): Multi-level boxes with shape (N, C + 1)... |
16,750 | import numba
import numpy as np
import torch
from mmdet3d.ops.iou3d.iou3d_utils import nms_gpu, nms_normal_gpu
The provided code snippet includes necessary dependencies for implementing the `aligned_3d_nms` function. Write a Python function `def aligned_3d_nms(boxes, scores, classes, thresh)` to solve the following pr... | 3d nms for aligned boxes. Args: boxes (torch.Tensor): Aligned box with shape [n, 6]. scores (torch.Tensor): Scores of each box. classes (torch.Tensor): Class of each box. thresh (float): Iou threshold for nms. Returns: torch.Tensor: Indices of selected boxes. |
16,751 | import numba
import numpy as np
import torch
from mmdet3d.ops.iou3d.iou3d_utils import nms_gpu, nms_normal_gpu
The provided code snippet includes necessary dependencies for implementing the `circle_nms` function. Write a Python function `def circle_nms(dets, thresh, post_max_size=83)` to solve the following problem:
C... | Circular NMS. An object is only counted as positive if no other center with a higher confidence exists within a radius r using a bird-eye view distance metric. Args: dets (torch.Tensor): Detection results with the shape of [N, 3]. thresh (float): Value of threshold. post_max_size (int): Max number of prediction to be k... |
16,752 | import copy
import os
from typing import List, Optional, Tuple
import cv2
import mmcv
import numpy as np
from matplotlib import pyplot as plt
from ..bbox import LiDARInstance3DBoxes
OBJECT_PALETTE = {
"car": (255, 158, 0),
"truck": (255, 99, 71),
"construction_vehicle": (233, 150, 70),
"bus": (255, 69, ... | null |
16,753 | import copy
import os
from typing import List, Optional, Tuple
import cv2
import mmcv
import numpy as np
from matplotlib import pyplot as plt
from ..bbox import LiDARInstance3DBoxes
OBJECT_PALETTE = {
"car": (255, 158, 0),
"truck": (255, 99, 71),
"construction_vehicle": (233, 150, 70),
"bus": (255, 69, ... | null |
16,754 | import copy
import os
from typing import List, Optional, Tuple
import cv2
import mmcv
import numpy as np
from matplotlib import pyplot as plt
from ..bbox import LiDARInstance3DBoxes
MAP_PALETTE = {
"drivable_area": (166, 206, 227),
"road_segment": (31, 120, 180),
"road_block": (178, 223, 138),
"lane": (... | null |
16,755 | import numpy as np
import torch
def gaussian_2d(shape, sigma=1):
"""Generate gaussian map.
Args:
shape (list[int]): Shape of the map.
sigma (float): Sigma to generate gaussian map.
Defaults to 1.
Returns:
np.ndarray: Generated gaussian map.
"""
m, n = [(ss - 1.0) ... | Get gaussian masked heatmap. Args: heatmap (torch.Tensor): Heatmap to be masked. center (torch.Tensor): Center coord of the heatmap. radius (int): Radius of gausian. K (int): Multiple of masked_gaussian. Defaults to 1. Returns: torch.Tensor: Masked heatmap. |
16,756 | import numpy as np
import torch
The provided code snippet includes necessary dependencies for implementing the `gaussian_radius` function. Write a Python function `def gaussian_radius(det_size, min_overlap=0.5)` to solve the following problem:
Get radius of gaussian. Args: det_size (tuple[torch.Tensor]): Size of the d... | Get radius of gaussian. Args: det_size (tuple[torch.Tensor]): Size of the detection result. min_overlap (float): Gaussian_overlap. Defaults to 0.5. Returns: torch.Tensor: Computed radius. |
16,757 | from mmcv.cnn import build_conv_layer, build_norm_layer
from torch import nn
from mmdet3d.ops import spconv
from mmdet.models.backbones.resnet import BasicBlock, Bottleneck
The provided code snippet includes necessary dependencies for implementing the `make_sparse_convmodule` function. Write a Python function `def mak... | Make sparse convolution module. Args: in_channels (int): the number of input channels out_channels (int): the number of out channels kernel_size (int|tuple(int)): kernel size of convolution indice_key (str): the indice key used for sparse tensor stride (int|tuple(int)): the stride of convolution padding (int or list[in... |
16,758 | import torch
from . import bev_pool_ext
class QuickCumsumCuda(torch.autograd.Function):
def forward(ctx, x, geom_feats, ranks, B, D, H, W):
kept = torch.ones(x.shape[0], device=x.device, dtype=torch.bool)
kept[1:] = ranks[1:] != ranks[:-1]
interval_starts = torch.where(kept)[0].int()
... | null |
16,759 | import torch
The provided code snippet includes necessary dependencies for implementing the `calc_square_dist` function. Write a Python function `def calc_square_dist(point_feat_a, point_feat_b, norm=True)` to solve the following problem:
Calculating square distance between a and b. Args: point_feat_a (Tensor): (B, N,... | 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): Whether to normalize the distance. Default: True. Returns: Tensor: (B, N, M) Distance between each pair points. |
16,760 | import torch
from mmcv.runner import force_fp32
from torch import nn as nn
from typing import List
from .furthest_point_sample import furthest_point_sample, furthest_point_sample_with_dist
from .utils import calc_square_dist
class DFPS_Sampler(nn.Module):
"""DFPS_Sampling.
Using Euclidean distances of points fo... | 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. |
16,761 | import torch
The provided code snippet includes necessary dependencies for implementing the `calc_euclidian_dist` function. Write a Python function `def calc_euclidian_dist(xyz1, xyz2)` to solve the following problem:
Calculate the Euclidian distance between two sets of points. Args: xyz1 (torch.Tensor): (N, 3), the f... | Calculate the Euclidian distance between two sets of points. Args: xyz1 (torch.Tensor): (N, 3), the first set of points. xyz2 (torch.Tensor): (N, 3), the second set of points. Returns: torch.Tensor: (N, ), the Euclidian distance between each point pair. |
16,762 | import torch
The provided code snippet includes necessary dependencies for implementing the `assign_score` function. Write a Python function `def assign_score(scores, point_features)` to solve the following problem:
Perform weighted sum to aggregate output features according to scores. This function is used in non-CUD... | Perform weighted sum to aggregate output features according to scores. This function is used in non-CUDA version of PAConv. Compared to the cuda op assigh_score_withk, this pytorch implementation pre-computes output features for the neighbors of all centers, and then performs aggregation. It consumes more GPU memories.... |
16,763 | import torch
The provided code snippet includes necessary dependencies for implementing the `assign_kernel_withoutk` function. Write a Python function `def assign_kernel_withoutk(features, kernels, M)` to solve the following problem:
Pre-compute features with weight matrices in weight bank. This function is used befor... | Pre-compute features with weight matrices in weight bank. This function is used before cuda op assign_score_withk in CUDA version PAConv. Args: features (torch.Tensor): (B, in_dim, N), input features of all points. `N` is the number of points in current point cloud. kernels (torch.Tensor): (2 * in_dim, M * out_dim), we... |
16,764 | import numpy as np
import torch
The provided code snippet includes necessary dependencies for implementing the `scatter_nd` function. Write a Python function `def scatter_nd(indices, updates, shape)` to solve the following problem:
pytorch edition of tensorflow scatter_nd. this function don't contain except handle cod... | pytorch edition of tensorflow scatter_nd. this function don't contain except handle code. so use this carefully when indice repeats, don't support repeat add which is supported in tensorflow. |
16,765 | import math
import numpy as np
import torch
from mmcv.cnn import CONV_LAYERS
from torch.nn import init
from torch.nn.parameter import Parameter
from . import functional as Fsp
from . import ops
from .modules import SparseModule
from .structure import SparseConvTensor
def _calculate_fan_in_and_fan_out_hwio(tensor):
... | null |
16,766 | import sys
import torch
from collections import OrderedDict
from torch import nn
from .structure import SparseConvTensor
class SparseModule(nn.Module):
"""place holder, All module subclass from this will take sptensor in
SparseSequential."""
pass
def is_spconv_module(module):
spconv_modules = (SparseMo... | null |
16,767 | import sys
import torch
from collections import OrderedDict
from torch import nn
from .structure import SparseConvTensor
class SparseConvolution(SparseModule):
def __init__(
self,
ndim,
in_channels,
out_channels,
kernel_size=3,
stride=1,
padding=0,
di... | null |
16,768 | import sys
import torch
from collections import OrderedDict
from torch import nn
from .structure import SparseConvTensor
def _mean_update(vals, m_vals, t):
outputs = []
if not isinstance(vals, list):
vals = [vals]
if not isinstance(m_vals, list):
m_vals = [m_vals]
for val, m_val in zip(... | null |
16,769 | import torch
from . import sparse_conv_ext
def get_conv_output_size(input_size, kernel_size, stride, padding, dilation):
ndim = len(input_size)
output_size = []
for i in range(ndim):
size = (input_size[i] + 2 * padding[i] - dilation[i] * (kernel_size[i] - 1) - 1) // stride[
i
] +... | null |
16,770 | import torch
from . import sparse_conv_ext
def indice_conv(
features, filters, indice_pairs, indice_pair_num, num_activate_out, inverse=False, subm=False
):
if filters.dtype == torch.float32:
return sparse_conv_ext.indice_conv_fp32(
features,
filters,
indice_pairs,
... | null |
16,771 | import torch
from . import sparse_conv_ext
def fused_indice_conv(
features, filters, bias, indice_pairs, indice_pair_num, num_activate_out, inverse, subm
):
if features.dtype == torch.half:
func = sparse_conv_ext.fused_indice_conv_half
elif filters.dtype == torch.float32:
func = sparse_conv... | null |
16,772 | import torch
from . import sparse_conv_ext
def indice_conv_backward(
features, filters, out_bp, indice_pairs, indice_pair_num, inverse=False, subm=False
):
if filters.dtype == torch.float32:
return sparse_conv_ext.indice_conv_backward_fp32(
features, filters, out_bp, indice_pairs, indice_pa... | null |
16,773 | import torch
from . import sparse_conv_ext
def indice_maxpool(features, indice_pairs, indice_pair_num, num_activate_out):
if features.dtype == torch.float32:
return sparse_conv_ext.indice_maxpool_fp32(
features, indice_pairs, indice_pair_num, num_activate_out
)
elif features.dtype =... | null |
16,774 | import torch
from . import sparse_conv_ext
def indice_maxpool_backward(features, out_features, out_bp, indice_pairs, indice_pair_num):
if features.dtype == torch.float32:
return sparse_conv_ext.indice_maxpool_backward_fp32(
features, out_features, out_bp, indice_pairs, indice_pair_num
)... | null |
16,775 | import torch
from . import roiaware_pool3d_ext
The provided code snippet includes necessary dependencies for implementing the `points_in_boxes_gpu` function. Write a Python function `def points_in_boxes_gpu(points, boxes)` to solve the following problem:
Find points that are in boxes (CUDA) Args: points (torch.Tensor)... | Find points that are in boxes (CUDA) Args: points (torch.Tensor): [B, M, 3], [x, y, z] in LiDAR coordinate boxes (torch.Tensor): [B, T, 7], num_valid_boxes <= T, [x, y, z, w, l, h, ry] in LiDAR coordinate, (x, y, z) is the bottom center Returns: box_idxs_of_pts (torch.Tensor): (B, M), default background = -1 |
16,776 | import torch
from . import roiaware_pool3d_ext
The provided code snippet includes necessary dependencies for implementing the `points_in_boxes_cpu` function. Write a Python function `def points_in_boxes_cpu(points, boxes)` to solve the following problem:
Find points that are in boxes (CPU) Note: Currently, the output ... | Find points that are in boxes (CPU) Note: Currently, the output of this function is different from that of points_in_boxes_gpu. Args: points (torch.Tensor): [npoints, 3] boxes (torch.Tensor): [N, 7], in LiDAR coordinate, (x, y, z) is the bottom center Returns: point_indices (torch.Tensor): (N, npoints) |
16,777 | import torch
from . import roiaware_pool3d_ext
The provided code snippet includes necessary dependencies for implementing the `points_in_boxes_batch` function. Write a Python function `def points_in_boxes_batch(points, boxes)` to solve the following problem:
Find points that are in boxes (CUDA) Args: points (torch.Ten... | Find points that are in boxes (CUDA) Args: points (torch.Tensor): [B, M, 3], [x, y, z] in LiDAR coordinate boxes (torch.Tensor): [B, T, 7], num_valid_boxes <= T, [x, y, z, w, l, h, ry] in LiDAR coordinate, (x, y, z) is the bottom center. Returns: box_idxs_of_pts (torch.Tensor): (B, M, T), default background = 0 |
16,778 | import torch
from . import feature_decorator_ext
def feature_decorator(features, num_voxels, coords, vx, vy, x_offset, y_offset, normalize_coords, use_cluster, use_center):
result = torch.ops.feature_decorator_ext.feature_decorator_forward(features, coords, num_voxels, vx, vy, x_offset, y_offset, normalize_coords,... | null |
16,779 | import torch
from . import iou3d_cuda
The provided code snippet includes necessary dependencies for implementing the `boxes_iou_bev` function. Write a Python function `def boxes_iou_bev(boxes_a, boxes_b)` to solve the following problem:
Calculate boxes IoU in the bird view. Args: boxes_a (torch.Tensor): Input boxes a ... | Calculate boxes IoU in the bird 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). |
16,780 | from mmcv.utils import Registry
SA_MODULES = Registry("point_sa_module")
The provided code snippet includes necessary dependencies for implementing the `build_sa_module` function. Write a Python function `def build_sa_module(cfg, *args, **kwargs)` to solve the following problem:
Build PointNet2 set abstraction (SA) mo... | Build PointNet2 set abstraction (SA) module. Args: cfg (None or dict): The SA module config, which should contain: - type (str): Module type. - module args: Args needed to instantiate an SA module. args (argument list): Arguments passed to the `__init__` method of the corresponding module. kwargs (keyword arguments): K... |
16,781 | import mmcv
The provided code snippet includes necessary dependencies for implementing the `extract_result_dict` function. Write a Python function `def extract_result_dict(results, key)` to solve the following problem:
Extract and return the data corresponding to key in result dict. ``results`` is a dict output from `... | Extract and return the data corresponding to key in result dict. ``results`` is a dict output from `pipeline(input_dict)`, which is the loaded data from ``Dataset`` class. The data terms inside may be wrapped in list, tuple and DataContainer, so this function essentially extracts data from these wrappers. Args: results... |
16,782 | import warnings
import numba
import numpy as np
from numba import errors
from mmdet3d.core.bbox import box_np_ops
def noise_per_box(boxes, valid_mask, loc_noises, rot_noises):
"""Add noise to every box (only on the horizontal plane).
Args:
boxes (np.ndarray): Input boxes with shape (N, 5).
valid... | Random rotate or remove each groundtruth independently. use kitti viewer to test this function points_transform_ Args: gt_boxes (np.ndarray): Ground truth boxes with shape (N, 7). points (np.ndarray | None): Input point cloud with shape (M, 4). Default: None. valid_mask (np.ndarray | None): Mask to indicate which boxes... |
16,783 | import os
import numpy as np
import torch
def load_augmented_point_cloud(path, virtual=False, reduce_beams=32):
# NOTE: following Tianwei's implementation, it is hard coded for nuScenes
points = np.fromfile(path, dtype=np.float32).reshape(-1, 5)
# NOTE: path definition different from Tianwei's implementati... | null |
16,784 | import os
import numpy as np
import torch
def reduce_LiDAR_beams(pts, reduce_beams_to=32):
# print(pts.size())
if isinstance(pts, np.ndarray):
pts = torch.from_numpy(pts)
radius = torch.sqrt(pts[:, 0].pow(2) + pts[:, 1].pow(2) + pts[:, 2].pow(2))
sine_theta = pts[:, 2] / radius
# [-pi/2, pi... | null |
16,785 | import tempfile
from os import path as osp
from typing import Any, Dict
import mmcv
import numpy as np
import pyquaternion
import torch
from nuscenes.utils.data_classes import Box as NuScenesBox
from pyquaternion import Quaternion
from mmdet.datasets import DATASETS
from ..core.bbox import LiDARInstance3DBoxes
from .cu... | Convert the output to the box class in the nuScenes. Args: detection (dict): Detection results. - boxes_3d (:obj:`BaseInstance3DBoxes`): Detection bbox. - scores_3d (torch.Tensor): Detection scores. - labels_3d (torch.Tensor): Predicted box labels. Returns: list[:obj:`NuScenesBox`]: List of standard NuScenesBoxes. |
16,786 | import tempfile
from os import path as osp
from typing import Any, Dict
import mmcv
import numpy as np
import pyquaternion
import torch
from nuscenes.utils.data_classes import Box as NuScenesBox
from pyquaternion import Quaternion
from mmdet.datasets import DATASETS
from ..core.bbox import LiDARInstance3DBoxes
from .cu... | Convert the box from ego to global coordinate. Args: info (dict): Info for a specific sample data, including the calibration information. boxes (list[:obj:`NuScenesBox`]): List of predicted NuScenesBoxes. classes (list[str]): Mapped classes in the evaluation. eval_configs : Evaluation configuration object. eval_version... |
16,787 | import platform
from mmcv.utils import Registry, build_from_cfg
from mmdet.datasets import DATASETS
from mmdet.datasets.builder import _concat_dataset
class CBGSDataset:
"""A wrapper of class sampled dataset with ann_file path. Implementation of
paper `Class-balanced Grouping and Sampling for Point Cloud 3D Ob... | null |
16,788 | from collections import OrderedDict
from mmcv.runner import BaseModule, force_fp32
from mmdet.models.builder import BACKBONES
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.modules.batchnorm import _BatchNorm
The provided code snippet includes necessary dependencies for implementing t... | 3x3 convolution with padding |
16,789 | from collections import OrderedDict
from mmcv.runner import BaseModule, force_fp32
from mmdet.models.builder import BACKBONES
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.modules.batchnorm import _BatchNorm
The provided code snippet includes necessary dependencies for implementing t... | 3x3 convolution with padding |
16,790 | from collections import OrderedDict
from mmcv.runner import BaseModule, force_fp32
from mmdet.models.builder import BACKBONES
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.modules.batchnorm import _BatchNorm
The provided code snippet includes necessary dependencies for implementing t... | 1x1 convolution with padding |
16,791 | from torch import nn
from typing import Any, Dict
from functools import cached_property
import torch
from mmcv.cnn import build_conv_layer, build_norm_layer
from mmcv.cnn.resnet import make_res_layer, BasicBlock
from torch import nn
from torch.nn import functional as F
from mmdet3d.models.builder import build_backbone
... | Create boolean mask by actually number of a padded tensor. Args: actual_num ([type]): [description] max_num ([type]): [description] Returns: [type]: [description] |
16,792 | from typing import Any, Dict
import torch
from mmcv.cnn import build_norm_layer
from torch import nn
from torch.nn import functional as F
from mmdet3d.models.builder import build_backbone
from mmdet.models import BACKBONES
The provided code snippet includes necessary dependencies for implementing the `get_paddings_ind... | Create boolean mask by actually number of a padded tensor. Args: actual_num ([type]): [description] max_num ([type]): [description] Returns: [type]: [description] |
16,793 | from typing import Tuple
import torch
from mmcv.runner import force_fp32
from torch import nn
from mmdet3d.ops import bev_pool
def boolmask2idx(mask):
# A utility function, workaround for ONNX not supporting 'nonzero'
return torch.nonzero(mask).squeeze(1).tolist() | null |
16,794 | from typing import Tuple
import torch
from mmcv.runner import force_fp32
from torch import nn
from mmdet3d.ops import bev_pool
def gen_dx_bx(xbound, ybound, zbound):
dx = torch.Tensor([row[2] for row in [xbound, ybound, zbound]])
bx = torch.Tensor([row[0] + row[2] / 2.0 for row in [xbound, ybound, zbound]])
... | null |
16,795 | from mmcv.utils import Registry
from mmdet.models.builder import BACKBONES, HEADS, LOSSES, NECKS
def build_backbone(cfg):
return BACKBONES.build(cfg) | null |
16,796 | from mmcv.utils import Registry
from mmdet.models.builder import BACKBONES, HEADS, LOSSES, NECKS
def build_neck(cfg):
return NECKS.build(cfg) | null |
16,797 | from mmcv.utils import Registry
from mmdet.models.builder import BACKBONES, HEADS, LOSSES, NECKS
VTRANSFORMS = Registry("vtransforms")
def build_vtransform(cfg):
return VTRANSFORMS.build(cfg) | null |
16,798 | from mmcv.utils import Registry
from mmdet.models.builder import BACKBONES, HEADS, LOSSES, NECKS
FUSERS = Registry("fusers")
def build_fuser(cfg):
return FUSERS.build(cfg) | null |
16,799 | from mmcv.utils import Registry
from mmdet.models.builder import BACKBONES, HEADS, LOSSES, NECKS
def build_head(cfg):
return HEADS.build(cfg) | null |
16,800 | from mmcv.utils import Registry
from mmdet.models.builder import BACKBONES, HEADS, LOSSES, NECKS
def build_loss(cfg):
return LOSSES.build(cfg) | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.