id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
14,231 | from math import sqrt
from functools import partial, lru_cache
import numpy as np
import torch
from torch import nn
from torch.nn import functional as F
def wn_linear(in_dim, out_dim):
return nn.utils.weight_norm(nn.Linear(in_dim, out_dim)) | null |
14,232 | from math import sqrt
from functools import partial, lru_cache
import numpy as np
import torch
from torch import nn
from torch.nn import functional as F
def shift_down(input, size=1):
return F.pad(input, [0, 0, size, 0])[:, :, : input.shape[2], :] | null |
14,233 | from math import sqrt
from functools import partial, lru_cache
import numpy as np
import torch
from torch import nn
from torch.nn import functional as F
def shift_right(input, size=1):
return F.pad(input, [size, 0, 0, 0])[:, :, :, : input.shape[3]] | null |
14,234 | from math import sqrt
from functools import partial, lru_cache
import numpy as np
import torch
from torch import nn
from torch.nn import functional as F
def causal_mask(size):
shape = [size, size]
mask = np.triu(np.ones(shape), k=1).astype(np.uint8).T
start_mask = np.ones(size).astype(np.float32)
start... | null |
14,235 | from math import cos, pi, floor, sin
from torch.optim import lr_scheduler
def anneal_linear(start, end, proportion):
return start + proportion * (end - start) | null |
14,236 | from math import cos, pi, floor, sin
from torch.optim import lr_scheduler
def anneal_cos(start, end, proportion):
cos_val = cos(pi * proportion) + 1
return end + (start - end) / 2 * cos_val | null |
14,237 | import math
import pickle
import torch
from torch import distributed as dist
from torch.utils import data
def get_rank():
if not dist.is_available():
return 0
if not dist.is_initialized():
return 0
return dist.get_rank()
def is_primary():
return get_rank() == 0 | null |
14,238 | import math
import pickle
import torch
from torch import distributed as dist
from torch.utils import data
LOCAL_PROCESS_GROUP = None
def get_rank():
if not dist.is_available():
return 0
if not dist.is_initialized():
return 0
return dist.get_rank()
def get_local_rank():
if not dist.is_av... | null |
14,239 | import math
import pickle
import torch
from torch import distributed as dist
from torch.utils import data
def get_world_size():
if not dist.is_available():
return 1
if not dist.is_initialized():
return 1
return dist.get_world_size()
def all_reduce(tensor, op=dist.ReduceOp.SUM):
world_si... | null |
14,240 | import math
import pickle
import torch
from torch import distributed as dist
from torch.utils import data
def get_world_size():
if not dist.is_available():
return 1
if not dist.is_initialized():
return 1
return dist.get_world_size()
def all_gather(data):
world_size = get_world_size()
... | null |
14,241 | import math
import pickle
import torch
from torch import distributed as dist
from torch.utils import data
def get_rank():
if not dist.is_available():
return 0
if not dist.is_initialized():
return 0
return dist.get_rank()
def get_world_size():
if not dist.is_available():
return 1
... | null |
14,242 | import math
import pickle
import torch
from torch import distributed as dist
from torch.utils import data
def data_sampler(dataset, shuffle, distributed):
if distributed:
return data.distributed.DistributedSampler(dataset, shuffle=shuffle)
if shuffle:
return data.RandomSampler(dataset)
el... | null |
14,243 | import os
import torch
from torch import distributed as dist
from torch import multiprocessing as mp
import distributed as dist_fn
def find_free_port():
def distributed_worker(
local_rank, fn, world_size, n_gpu_per_machine, machine_rank, dist_url, args
):
def launch(fn, n_gpu_per_machine, n_machine=1, machine_rank... | null |
14,244 | import argparse
import numpy as np
import torch
from torch import nn, optim
from torch.utils.data import DataLoader
from tqdm import tqdm
from dataset import LMDBDataset
from pixelsnail import PixelSNAIL
from scheduler import CycleScheduler
def train(args, epoch, loader, model, optimizer, scheduler, device):
loade... | null |
14,245 | from setuptools import find_packages, setup
def readme():
with open('README.md', encoding='utf-8') as f:
content = f.read()
return content | null |
14,246 | from setuptools import find_packages, setup
def get_version():
version_file = 'mmhuman3d/version.py'
with open(version_file, 'r', encoding='utf-8') as f:
exec(compile(f.read(), version_file, 'exec'))
return locals()['__version__'] | null |
14,247 | from setuptools import find_packages, setup
try:
import torch
from torch.utils.cpp_extension import BuildExtension, CUDAExtension
cmd_class = {'build_ext': BuildExtension}
except ModuleNotFoundError:
cmd_class = {}
print('Skip building ext ops due to the absence of torch.')
def get_extensions():
... | null |
14,248 | from setuptools import find_packages, setup
The provided code snippet includes necessary dependencies for implementing the `parse_requirements` function. Write a Python function `def parse_requirements(fname='requirements.txt', with_version=True)` to solve the following problem:
Parse the package dependencies listed i... | Parse the package dependencies listed in a requirements file but strips specific versioning information. Args: fname (str): path to requirements file with_version (bool, default=False): if True include version specs Returns: List[str]: list of requirements items CommandLine: python -c "import setup; print(setup.parse_r... |
14,249 | import os
import sys
import pytorch_sphinx_theme
version_file = '../mmhuman3d/version.py'
def get_version():
with open(version_file, 'r') as f:
exec(compile(f.read(), version_file, 'exec'))
return locals()['__version__'] | null |
14,250 | import argparse
import time
from collections import deque
from queue import Queue
from threading import Event, Lock, Thread
import cv2
import mmcv
import numpy as np
import torch
from mmhuman3d.apis import inference_image_based_model, init_model
from mmhuman3d.core.renderer.mpr_renderer.smpl_realrender import \
Vis... | null |
14,251 | import argparse
import time
from collections import deque
from queue import Queue
from threading import Event, Lock, Thread
import cv2
import mmcv
import numpy as np
import torch
from mmhuman3d.apis import inference_image_based_model, init_model
from mmhuman3d.core.renderer.mpr_renderer.smpl_realrender import \
Vis... | null |
14,252 | import argparse
import time
from collections import deque
from queue import Queue
from threading import Event, Lock, Thread
import cv2
import mmcv
import numpy as np
import torch
from mmhuman3d.apis import inference_image_based_model, init_model
from mmhuman3d.core.renderer.mpr_renderer.smpl_realrender import \
Vis... | null |
14,253 | import argparse
import time
from collections import deque
from queue import Queue
from threading import Event, Lock, Thread
import cv2
import mmcv
import numpy as np
import torch
from mmhuman3d.apis import inference_image_based_model, init_model
from mmhuman3d.core.renderer.mpr_renderer.smpl_realrender import \
Vis... | null |
14,254 | import argparse
import time
from collections import deque
from queue import Queue
from threading import Event, Lock, Thread
import cv2
import mmcv
import numpy as np
import torch
from mmhuman3d.apis import inference_image_based_model, init_model
from mmhuman3d.core.renderer.mpr_renderer.smpl_realrender import \
Vis... | null |
14,255 | import argparse
import copy
import os
import os.path as osp
import shutil
from pathlib import Path
import cv2
import mmcv
import numpy as np
import torch
from torch.utils.data import DataLoader
from tqdm import tqdm
from mmhuman3d.apis import init_model
from mmhuman3d.core.visualization.visualize_smpl import visualize_... | null |
14,256 | import argparse
import copy
import os
import os.path as osp
import shutil
from pathlib import Path
import cv2
import mmcv
import numpy as np
import torch
from torch.utils.data import DataLoader
from tqdm import tqdm
from mmhuman3d.apis import init_model
from mmhuman3d.core.visualization.visualize_smpl import visualize_... | null |
14,257 | import argparse
import copy
import os
import os.path as osp
import shutil
from pathlib import Path
import cv2
import mmcv
import numpy as np
import torch
from torch.utils.data import DataLoader
from tqdm import tqdm
from mmhuman3d.apis import init_model
from mmhuman3d.core.visualization.visualize_smpl import visualize_... | null |
14,258 | import os
import os.path as osp
import shutil
from argparse import ArgumentParser
import mmcv
import numpy as np
import torch
from mmhuman3d.apis import (
feature_extract,
inference_image_based_model,
init_model,
)
from mmhuman3d.core.visualization.visualize_smpl import visualize_smpl_hmr
from mmhuman3d.dat... | Estimate smplx parameters from single-person images with mmdetection Args: args (object): object of argparse.Namespace. frames_iter (np.ndarray,): prepared frames |
14,259 | import os
import os.path as osp
import shutil
from argparse import ArgumentParser
import mmcv
import numpy as np
import torch
from mmhuman3d.apis import (
feature_extract,
inference_image_based_model,
init_model,
)
from mmhuman3d.core.visualization.visualize_smpl import visualize_smpl_hmr
from mmhuman3d.dat... | Estimate smplx parameters from multi-person images with mmtracking Args: args (object): object of argparse.Namespace. frames_iter (np.ndarray,): prepared frames |
14,260 | import os
import os.path as osp
import shutil
import warnings
from argparse import ArgumentParser
from pathlib import Path
import mmcv
import numpy as np
import torch
from mmhuman3d.apis import (
feature_extract,
inference_image_based_model,
inference_video_based_model,
init_model,
)
from mmhuman3d.core... | null |
14,261 | import os
import os.path as osp
import shutil
import warnings
from argparse import ArgumentParser
from pathlib import Path
import mmcv
import numpy as np
import torch
from mmhuman3d.apis import (
feature_extract,
inference_image_based_model,
inference_video_based_model,
init_model,
)
from mmhuman3d.core... | Estimate smpl parameters from single-person images with mmdetection Args: args (object): object of argparse.Namespace. frames_iter (np.ndarray,): prepared frames |
14,262 | import os
import os.path as osp
import shutil
import warnings
from argparse import ArgumentParser
from pathlib import Path
import mmcv
import numpy as np
import torch
from mmhuman3d.apis import (
feature_extract,
inference_image_based_model,
inference_video_based_model,
init_model,
)
from mmhuman3d.core... | Estimate smpl parameters from single-person images with mmdetection Args: args (object): object of argparse.Namespace. frames_iter (np.ndarray,): prepared frames |
14,263 | import os
import os.path as osp
import shutil
import warnings
from argparse import ArgumentParser
from pathlib import Path
import mmcv
import numpy as np
import torch
from mmhuman3d.apis import (
feature_extract,
inference_image_based_model,
inference_video_based_model,
init_model,
)
from mmhuman3d.core... | Estimate smpl parameters from multi-person images with mmtracking Args: args (object): object of argparse.Namespace. frames_iter (np.ndarray,): prepared frames |
14,264 | version_info = parse_version_info(__version__)
The provided code snippet includes necessary dependencies for implementing the `parse_version_info` function. Write a Python function `def parse_version_info(version_str)` to solve the following problem:
Parse a version string into a tuple. Args: version_str (str): The ve... | Parse a version string into a tuple. Args: version_str (str): The version string. Returns: tuple[int | str]: The version info, e.g., "1.3.0" is parsed into (1, 3, 0), and "2.0.0rc1" is parsed into (2, 0, 0, 'rc1'). |
14,265 | import random
import warnings
import numpy as np
import torch
from mmcv.parallel import MMDataParallel, MMDistributedDataParallel
from mmcv.runner import (
DistSamplerSeedHook,
Fp16OptimizerHook,
OptimizerHook,
build_runner,
)
from mmhuman3d.core.distributed_wrapper import DistributedDataParallelWrapper... | Set random seed. Args: seed (int): Seed to be used. deterministic (bool): Whether to set the deterministic option for CUDNN backend, i.e., set `torch.backends.cudnn.deterministic` to True and `torch.backends.cudnn.benchmark` to False. Default: False. |
14,266 | import random
import warnings
import numpy as np
import torch
from mmcv.parallel import MMDataParallel, MMDistributedDataParallel
from mmcv.runner import (
DistSamplerSeedHook,
Fp16OptimizerHook,
OptimizerHook,
build_runner,
)
from mmhuman3d.core.distributed_wrapper import DistributedDataParallelWrapper... | Main api for training model. |
14,267 | from typing import Dict, Tuple, Union
import cv2
import mmcv
import numpy as np
import torch
from mmcv.parallel import collate
from mmcv.runner import load_checkpoint
from mmcv.utils import print_log
from mmhuman3d.data.datasets.pipelines import Compose
from mmhuman3d.models.architectures.builder import build_architect... | Initialize a model from config file. Args: config (str or :obj:`mmcv.Config`): Config file path or the config object. checkpoint (str, optional): Checkpoint path. If left as None, the model will not load any weights. Returns: nn.Module: The constructed model. (nn.Module, None): The constructed extractor model |
14,268 | from typing import Dict, Tuple, Union
import cv2
import mmcv
import numpy as np
import torch
from mmcv.parallel import collate
from mmcv.runner import load_checkpoint
from mmcv.utils import print_log
from mmhuman3d.data.datasets.pipelines import Compose
from mmhuman3d.models.architectures.builder import build_architect... | Inference a single image with a list of person bounding boxes. Args: model (nn.Module): The loaded pose model. img_or_path (Union[str, np.ndarray]): Image filename or loaded image. det_results (List(dict)): the item in the dict may contain 'bbox' and/or 'track_id'. 'bbox' (4, ) or (5, ): The person bounding box, which ... |
14,269 | from typing import Dict, Tuple, Union
import cv2
import mmcv
import numpy as np
import torch
from mmcv.parallel import collate
from mmcv.runner import load_checkpoint
from mmcv.utils import print_log
from mmhuman3d.data.datasets.pipelines import Compose
from mmhuman3d.models.architectures.builder import build_architect... | Inference SMPL parameters from extracted featutres using a video-based model. Args: model (nn.Module): The loaded mesh estimation model. extracted_results (List[List[Dict]]): Multi-frame feature extraction results stored in a nested list. Each element of the outer list is the feature extraction results of a single fram... |
14,270 | from typing import Dict, Tuple, Union
import cv2
import mmcv
import numpy as np
import torch
from mmcv.parallel import collate
from mmcv.runner import load_checkpoint
from mmcv.utils import print_log
from mmhuman3d.data.datasets.pipelines import Compose
from mmhuman3d.models.architectures.builder import build_architect... | Extract image features with a list of person bounding boxes. Args: model (nn.Module): The loaded feature extraction model. img_or_path (Union[str, np.ndarray]): Image filename or loaded image. det_results (List(dict)): the item in the dict may contain 'bbox' and/or 'track_id'. 'bbox' (4, ) or (5, ): The person bounding... |
14,271 | import json
import os
import numpy as np
from tqdm import tqdm
from mmhuman3d.core.conventions.keypoints_mapping import convert_kps
from mmhuman3d.data.data_structures.human_data import HumanData
from mmhuman3d.data.data_structures.multi_human_data import MultiHumanData
from .base_converter import BaseConverter
from .b... | null |
14,272 | import json
import os
import os.path as osp
import pickle as pk
import numpy as np
from mmhuman3d.core.conventions.keypoints_mapping import convert_kps
from mmhuman3d.data.data_converters.builder import DATA_CONVERTERS
from mmhuman3d.data.data_structures.human_data import HumanData
from .base_converter import BaseModeC... | Project keypoints 3D to keypoints 2D on images. Using intrinsics K. |
14,273 | from mmcv.utils import Registry
DATA_CONVERTERS = Registry('data_converters')
The provided code snippet includes necessary dependencies for implementing the `build_data_converter` function. Write a Python function `def build_data_converter(cfg)` to solve the following problem:
Build data converter.
Here is the functi... | Build data converter. |
14,274 | import copy
from typing import Optional, Union
import numpy as np
import torch
from mmcv.parallel import DataContainer as DC
from skimage.util.shape import view_as_windows
from .builder import DATASETS
from .human_image_dataset import HumanImageDataset
def get_vid_name(image_path: str):
"""Get base_dir of the given... | Split annotations into chunks. Adapted from https://github.com/mkocabas/VIBE Args: data_infos (list): parsed annotations. seq_len (int): the length of each chunk. stride (int): the interval between chunks. test_mode (bool): if test_mode is true, then an additional chunk will be added to cover all frames. Otherwise, las... |
14,275 | import math
import random
import cv2
import mmcv
import numpy as np
from mmhuman3d.core.conventions.keypoints_mapping import get_flip_pairs
from ..builder import PIPELINES
from .compose import Compose
The provided code snippet includes necessary dependencies for implementing the `get_warp_matrix` function. Write a Pyt... | Calculate the transformation matrix under the constraint of unbiased. Paper ref: Huang et al. The Devil is in the Details: Delving into Unbiased Data Processing for Human Pose Estimation (CVPR 2020). Args: theta (float): Rotation angle in degrees. size_input (np.ndarray): Size of input image [w, h]. size_dst (np.ndarra... |
14,276 | import math
import random
import cv2
import mmcv
import numpy as np
from mmhuman3d.core.conventions.keypoints_mapping import get_flip_pairs
from ..builder import PIPELINES
from .compose import Compose
The provided code snippet includes necessary dependencies for implementing the `warp_affine_joints` function. Write a ... | Apply affine transformation defined by the transform matrix on the joints. Args: joints (np.ndarray[..., 2]): Origin coordinate of joints. mat (np.ndarray[3, 2]): The affine matrix. Returns: matrix (np.ndarray[..., 2]): Result coordinate of joints. |
14,277 | import math
import random
import cv2
import mmcv
import numpy as np
from mmhuman3d.core.conventions.keypoints_mapping import get_flip_pairs
from ..builder import PIPELINES
from .compose import Compose
The provided code snippet includes necessary dependencies for implementing the `_flip_smpl_pose` function. Write a Pyt... | Flip SMPL pose parameters horizontally. Args: pose (np.ndarray([72])): SMPL pose parameters Returns: pose_flipped |
14,278 | import math
import random
import cv2
import mmcv
import numpy as np
from mmhuman3d.core.conventions.keypoints_mapping import get_flip_pairs
from ..builder import PIPELINES
from .compose import Compose
The provided code snippet includes necessary dependencies for implementing the `_flip_smplx_pose` function. Write a Py... | Flip SMPLX pose parameters horizontally. Args: pose (np.ndarray([63])): SMPLX pose parameters Returns: pose_flipped (np.ndarray([21,3])) |
14,279 | import math
import random
import cv2
import mmcv
import numpy as np
from mmhuman3d.core.conventions.keypoints_mapping import get_flip_pairs
from ..builder import PIPELINES
from .compose import Compose
The provided code snippet includes necessary dependencies for implementing the `_flip_axis_angle` function. Write a Py... | Flip axis_angle horizontally. Args: r (np.ndarray([3])) Returns: f_flipped |
14,280 | import math
import random
import cv2
import mmcv
import numpy as np
from mmhuman3d.core.conventions.keypoints_mapping import get_flip_pairs
from ..builder import PIPELINES
from .compose import Compose
def _flip_hand_pose(r_pose, l_pose):
dim_flip = np.array([1, -1, -1], dtype=r_pose.dtype)
ret_l_pose = r_pose ... | null |
14,281 | import math
import random
import cv2
import mmcv
import numpy as np
from mmhuman3d.core.conventions.keypoints_mapping import get_flip_pairs
from ..builder import PIPELINES
from .compose import Compose
The provided code snippet includes necessary dependencies for implementing the `_flip_keypoints` function. Write a Pyt... | Flip human joints horizontally. Note: num_keypoints: K num_dimension: D Args: keypoints (np.ndarray([K, D])): Coordinates of keypoints. flip_pairs (list[tuple()]): Pairs of keypoints which are mirrored (for example, left ear -- right ear). img_width (int | None, optional): The width of the original image. To flip 2D ke... |
14,282 | import math
import random
import cv2
import mmcv
import numpy as np
from mmhuman3d.core.conventions.keypoints_mapping import get_flip_pairs
from ..builder import PIPELINES
from .compose import Compose
def _construct_rotation_matrix(rot, size=3):
"""Construct the in-plane rotation matrix.
Args:
rot (floa... | Rotate the 3D joints in the local coordinates. Notes: Joints number: K Args: joints_3d (np.ndarray([K, 3])): Coordinates of keypoints. rot (float): Rotation angle (degree). Returns: joints_3d_rotated |
14,283 | import math
import random
import cv2
import mmcv
import numpy as np
from mmhuman3d.core.conventions.keypoints_mapping import get_flip_pairs
from ..builder import PIPELINES
from .compose import Compose
def _construct_rotation_matrix(rot, size=3):
"""Construct the in-plane rotation matrix.
Args:
rot (floa... | Rotate SMPL pose parameters. SMPL (https://smpl.is.tue.mpg.de/) is a 3D human model. Args: pose (np.ndarray([72])): SMPL pose parameters rot (float): Rotation angle (degree). Returns: pose_rotated |
14,284 | import numpy as np
from PIL import Image
def transform(pt, center, scale, res, invert=0):
"""Transform pixel location to different reference."""
t = get_transform(center, scale, res)
if invert:
t = np.linalg.inv(t)
new_pt = np.array([pt[0] - 1, pt[1] - 1, 1.]).T
new_pt = np.dot(t, new_pt)
... | Crop image according to the supplied bounding box. |
14,285 | from collections.abc import Sequence
import mmcv
import numpy as np
import torch
from mmcv.parallel import DataContainer as DC
from PIL import Image
from ..builder import PIPELINES
The provided code snippet includes necessary dependencies for implementing the `to_tensor` function. Write a Python function `def to_tenso... | Convert objects of various python types to :obj:`torch.Tensor`. Supported types are: :class:`numpy.ndarray`, :class:`torch.Tensor`, :class:`Sequence`, :class:`int` and :class:`float`. |
14,286 | import os.path
import random
import cv2
import numpy as np
from ..builder import PIPELINES
The provided code snippet includes necessary dependencies for implementing the `load_pascal_occluders` function. Write a Python function `def load_pascal_occluders(occluders_file)` to solve the following problem:
load pascal occ... | load pascal occluders from the occluder file. |
14,287 | import os.path
import random
import cv2
import numpy as np
from ..builder import PIPELINES
def paste_over(im_src, im_dst, center):
"""Pastes `im_src` onto `im_dst` at a specified position, with alpha
blending, in place.
Locations outside the bounds of `im_dst`
are handled as expected (only a part or non... | Returns an augmented version of `im`, containing some occluders from the Pascal VOC dataset. |
14,288 | import os.path
import random
import cv2
import numpy as np
from ..builder import PIPELINES
The provided code snippet includes necessary dependencies for implementing the `list_filepaths` function. Write a Python function `def list_filepaths(dirpath)` to solve the following problem:
list the file paths.
Here is the fu... | list the file paths. |
14,289 | import math
import random
import cv2
import mmcv
import numpy as np
from mmhuman3d.core.conventions.keypoints_mapping import get_flip_pairs
from mmhuman3d.utils.demo_utils import box2cs, xyxy2xywh
from ..builder import PIPELINES
from .transforms import (
_rotate_smpl_pose,
affine_transform,
get_affine_trans... | Obtain bbox in xyxy format given bbox in xywh format and applying clipping to ensure bbox is within image bounds. Args: xywh (list): bbox in format (x, y, w, h). w (int): image width h (int): image height Returns: xyxy (numpy.ndarray): Converted bboxes in format (xmin, ymin, xmax, ymax). |
14,290 | import math
import random
import cv2
import mmcv
import numpy as np
from mmhuman3d.core.conventions.keypoints_mapping import get_flip_pairs
from mmhuman3d.utils.demo_utils import box2cs, xyxy2xywh
from ..builder import PIPELINES
from .transforms import (
_rotate_smpl_pose,
affine_transform,
get_affine_trans... | Retrieve predicted keypoints and scores from heatmap. |
14,291 | import math
import random
import cv2
import mmcv
import numpy as np
from mmhuman3d.core.conventions.keypoints_mapping import get_flip_pairs
from mmhuman3d.utils.demo_utils import box2cs, xyxy2xywh
from ..builder import PIPELINES
from .transforms import (
_rotate_smpl_pose,
affine_transform,
get_affine_trans... | Convert coordinates from camera to image frame given f and c Args: cam_coord (np.ndarray): Coordinates in camera frame f (list): focal length, fx, fy c (list): principal point offset, x0, y0 Returns: img_coord (np.ndarray): Coordinates in image frame |
14,292 | import math
import random
import cv2
import mmcv
import numpy as np
from mmhuman3d.core.conventions.keypoints_mapping import get_flip_pairs
from mmhuman3d.utils.demo_utils import box2cs, xyxy2xywh
from ..builder import PIPELINES
from .transforms import (
_rotate_smpl_pose,
affine_transform,
get_affine_trans... | Get intrisic matrix (or its inverse) given f and c. Args: f (list): focal length, fx, fy c (list): principal point offset, x0, y0 inv (bool): Store True to get inverse. Default: False. Returns: intrinsic matrix (np.ndarray): 3x3 intrinsic matrix or its inverse |
14,293 | import math
import random
import cv2
import mmcv
import numpy as np
from mmhuman3d.core.conventions.keypoints_mapping import get_flip_pairs
from mmhuman3d.utils.demo_utils import box2cs, xyxy2xywh
from ..builder import PIPELINES
from .transforms import (
_rotate_smpl_pose,
affine_transform,
get_affine_trans... | Convert rotations given as axis/angle to quaternions. Args: axis_angle: Rotations given as a vector in axis angle form, as a np.ndarray of shape (..., 3), where the magnitude is the angle turned anticlockwise in radians around the vector's direction. Returns: quaternions with real part first, as np.ndarray of shape (..... |
14,294 | import math
import random
import cv2
import mmcv
import numpy as np
from mmhuman3d.core.conventions.keypoints_mapping import get_flip_pairs
from mmhuman3d.utils.demo_utils import box2cs, xyxy2xywh
from ..builder import PIPELINES
from .transforms import (
_rotate_smpl_pose,
affine_transform,
get_affine_trans... | Flip thetas. Args: thetas (np.ndarray): joints in shape (num_thetas, 3) theta_pairs (list): flip pairs for thetas Returns: thetas_flip (np.ndarray): flipped thetas with shape (num_thetas, 3) |
14,295 | import math
import random
import cv2
import mmcv
import numpy as np
from mmhuman3d.core.conventions.keypoints_mapping import get_flip_pairs
from mmhuman3d.utils.demo_utils import box2cs, xyxy2xywh
from ..builder import PIPELINES
from .transforms import (
_rotate_smpl_pose,
affine_transform,
get_affine_trans... | Flip 3d joints. Args: joints_3d (np.ndarray): joints in shape (N, 3, 2) width (int): Image width joint_pairs (list): flip pairs for joints Returns: joints_3d_flipped (np.ndarray): flipped joints with shape (N, 3, 2) joints_3d_visible_flipped (np.ndarray): visibility of (N, 3, 2) |
14,296 | import math
import random
import cv2
import mmcv
import numpy as np
from mmhuman3d.core.conventions.keypoints_mapping import get_flip_pairs
from mmhuman3d.utils.demo_utils import box2cs, xyxy2xywh
from ..builder import PIPELINES
from .transforms import (
_rotate_smpl_pose,
affine_transform,
get_affine_trans... | Flip 3d xyz joints. Args: joints_3d (np.ndarray): Joints in shape (N, 3) joint_pairs (list): flip pairs for joints Returns: joints_3d_flipped (np.ndarray): flipped joints with shape (N, 3) |
14,297 | import math
import random
import cv2
import mmcv
import numpy as np
from mmhuman3d.core.conventions.keypoints_mapping import get_flip_pairs
from mmhuman3d.utils.demo_utils import box2cs, xyxy2xywh
from ..builder import PIPELINES
from .transforms import (
_rotate_smpl_pose,
affine_transform,
get_affine_trans... | Flip twist and weight. Args: twist_phi (np.ndarray): twist in shape (num_twist, 2) twist_weight (np.ndarray): weight in shape (num_twist, 2) twist_pairs (list): flip pairs for twist Returns: twist_flip (np.ndarray): flipped twist with shape (num_twist, 2) weight_flip (np.ndarray): flipped weights with shape (num_twist,... |
14,298 | import math
import random
import cv2
import mmcv
import numpy as np
from mmhuman3d.core.conventions.keypoints_mapping import get_flip_pairs
from mmhuman3d.utils.demo_utils import box2cs, xyxy2xywh
from ..builder import PIPELINES
from .transforms import (
_rotate_smpl_pose,
affine_transform,
get_affine_trans... | Flip twist and weight. Args: joints_3d (np.ndarray): Joints in shape (N, 3) joint_pairs (list): flip pairs for joints Returns: joints_3d_flipped (np.ndarray): flipped joints with shape (N, 3) |
14,299 | import platform
import random
from functools import partial
from typing import Optional, Union
import numpy as np
from mmcv.parallel import collate
from mmcv.runner import get_dist_info
from mmcv.utils import Registry, build_from_cfg
from torch.utils.data import DataLoader
from torch.utils.data.dataset import Dataset
f... | Build dataset by the given config. |
14,300 | import platform
import random
from functools import partial
from typing import Optional, Union
import numpy as np
from mmcv.parallel import collate
from mmcv.runner import get_dist_info
from mmcv.utils import Registry, build_from_cfg
from torch.utils.data import DataLoader
from torch.utils.data.dataset import Dataset
f... | Build PyTorch DataLoader. In distributed training, each GPU/process has a dataloader. In non-distributed training, there is only one dataloader for all GPUs. Args: dataset (:obj:`Dataset`): A PyTorch dataset. samples_per_gpu (int): Number of training samples on each GPU, i.e., batch size of each GPU. workers_per_gpu (i... |
14,301 | import math
from typing import Iterable, List, Optional, Tuple, Union
import numpy as np
import torch
from pytorch3d.renderer import cameras
from pytorch3d.structures import Meshes
from pytorch3d.transforms import Transform3d
from mmhuman3d.core.conventions.cameras.convert_convention import (
convert_camera_matrix,... | Concat a list of cameras of the same type. Args: cameras_list (List[cameras.CamerasBase]): a list of cameras. Returns: MMCamerasBase: the returned cameras concated following the batch dim. |
14,302 | import math
from typing import Iterable, List, Optional, Tuple, Union
import numpy as np
import torch
from pytorch3d.renderer import cameras
from pytorch3d.structures import Meshes
from pytorch3d.transforms import Transform3d
from mmhuman3d.core.conventions.cameras.convert_convention import (
convert_camera_matrix,... | Generate a sequence of moving cameras following an orbit. Args: K (Union[torch.Tensor, np.ndarray, None], optional): Intrinsic matrix. Will generate a default K if None. Defaults to None. elev (float, optional): This is the angle between the vector from the object to the camera, and the horizontal plane y = 0 (xz-plane... |
14,303 | import math
from typing import Iterable, List, Optional, Tuple, Union
import numpy as np
import torch
from pytorch3d.renderer import cameras
from pytorch3d.structures import Meshes
from pytorch3d.transforms import Transform3d
from mmhuman3d.core.conventions.cameras.convert_convention import (
convert_camera_matrix,... | Generate a sequence of moving cameras along a direction. We need a `z_vec`, `y_vec` to generate `x_vec` so as to get the `R` matrix. And we need `eye` as `T` matrix. `K` matrix could be set or use default. We recommend `y_vec` as default (0, 1, 0), and it will be orthogonal decomposed. The `x_vec` will be generated by ... |
14,304 | import json
import warnings
from enum import Enum
from typing import Any, List, Tuple, Union
import numpy as np
import torch
from mmhuman3d.core.cameras.cameras import PerspectiveCameras
from mmhuman3d.core.conventions.cameras.convert_convention import (
convert_camera_matrix,
convert_K_3x3_to_4x4,
convert_... | Parse a dict loaded from chessboard file into another dict needed by CameraParameter. Args: chessboard_camera_param (dict): A dict loaded from json.load(chessboard_file). name (str): Name of this camera. inverse (bool, optional): Whether to inverse rotation and translation mat. Defaults to True. Returns: dict: A dict o... |
14,305 | import json
import warnings
from enum import Enum
from typing import Any, List, Tuple, Union
import numpy as np
import torch
from mmhuman3d.core.cameras.cameras import PerspectiveCameras
from mmhuman3d.core.conventions.cameras.convert_convention import (
convert_camera_matrix,
convert_K_3x3_to_4x4,
convert_... | Return a zero mat in list format. Args: n (int, optional): Length of the edge. Defaults to 3. Returns: list: List[List[int]] |
14,306 | from mmcv.runner import build_optimizer
from mmcv.utils import Registry
The provided code snippet includes necessary dependencies for implementing the `build_optimizers` function. Write a Python function `def build_optimizers(model, cfgs)` to solve the following problem:
Build multiple optimizers from configs. If `cfg... | Build multiple optimizers from configs. If `cfgs` contains several dicts for optimizers, then a dict for each constructed optimizers will be returned. If `cfgs` only contains one optimizer config, the constructed optimizer itself will be returned. For example, 1) Multiple optimizer configs: .. code-block:: python optim... |
14,307 | import warnings
from typing import Iterable, List, Optional, Tuple, Union
import numpy as np
import mmhuman3d.core.conventions.keypoints_mapping as keypoints_mapping
from mmhuman3d.core.renderer.matplotlib3d_renderer import Axes3dJointsRenderer
from mmhuman3d.utils.demo_utils import get_different_colors
from mmhuman3d.... | Visualize 3d keypoints to a video with matplotlib. Support multi person and specified limb connections. Args: kp3d (np.ndarray): shape could be (f * J * 4/3/2) or (f * num_person * J * 4/3/2) output_path (str): output video path image folder. limbs (Optional[Union[np.ndarray, List[int]]], optional): if not specified, t... |
14,308 | import copy
import glob
import os
import os.path as osp
import shutil
import warnings
from functools import partial
from pathlib import Path
from typing import List, Optional, Tuple, Union
import mmcv
import numpy as np
import torch
import torch.nn as nn
from colormap import Color
from mmhuman3d.core.cameras import (
... | Visualize a smpl mesh which has opencv calibration matrix defined in screen. |
14,309 | import copy
import glob
import os
import os.path as osp
import shutil
import warnings
from functools import partial
from pathlib import Path
from typing import List, Optional, Tuple, Union
import mmcv
import numpy as np
import torch
import torch.nn as nn
from colormap import Color
from mmhuman3d.core.cameras import (
... | Simplest way to visualize pred smpl with origin frames and predicted cameras. |
14,310 | import copy
import glob
import os
import os.path as osp
import shutil
import warnings
from functools import partial
from pathlib import Path
from typing import List, Optional, Tuple, Union
import mmcv
import numpy as np
import torch
import torch.nn as nn
from colormap import Color
from mmhuman3d.core.cameras import (
... | Simplest way to visualize a sequence of T pose. |
14,311 | import copy
import glob
import os
import os.path as osp
import shutil
import warnings
from functools import partial
from pathlib import Path
from typing import List, Optional, Tuple, Union
import mmcv
import numpy as np
import torch
import torch.nn as nn
from colormap import Color
from mmhuman3d.core.cameras import (
... | Simplest way to visualize a sequence of smpl pose. Cameras will focus on the center of smpl mesh. `orbit speed` is recommended. |
14,312 | import json
import os
from mmhuman3d.core.cameras.camera_parameters import CameraParameter
from mmhuman3d.core.renderer.vedo_render import VedoRenderer
from mmhuman3d.utils.path_utils import check_path_suffix
class CameraParameter:
logger = None
SUPPORTED_KEYS = _CAMERA_PARAMETER_SUPPORTED_KEYS_
def __ini... | Visualize all the RGB cameras in a chessboard file. Args: chessboard_path (str): Path to the chessboard file. interactive (bool, optional): Pause and interact with window (True) or continue execution (False). Defaults to True. show (bool, optional): Whether to show in a window. Defaults to True. |
14,313 | import json
import os
from mmhuman3d.core.cameras.camera_parameters import CameraParameter
from mmhuman3d.core.renderer.vedo_render import VedoRenderer
from mmhuman3d.utils.path_utils import check_path_suffix
class CameraParameter:
logger = None
SUPPORTED_KEYS = _CAMERA_PARAMETER_SUPPORTED_KEYS_
def __ini... | Visualize all cameras dumped in a directory. Args: dumped_dir (str): Path to the directory. interactive (bool, optional): Pause and interact with window (True) or continue execution (False). Defaults to True. show (bool, optional): Whether to show in a window. Defaults to True. |
14,314 | import glob
import os
import os.path as osp
import shutil
import warnings
from pathlib import Path
from typing import Iterable, List, Optional, Tuple, Union
import cv2
import numpy as np
from tqdm import tqdm
from mmhuman3d.core.conventions.keypoints_mapping import KEYPOINTS_FACTORY
from mmhuman3d.core.conventions.keyp... | Check frame path. |
14,315 | import glob
import os
import os.path as osp
import shutil
import warnings
from pathlib import Path
from typing import Iterable, List, Optional, Tuple, Union
import cv2
import numpy as np
from tqdm import tqdm
from mmhuman3d.core.conventions.keypoints_mapping import KEYPOINTS_FACTORY
from mmhuman3d.core.conventions.keyp... | Visualize 2d keypoints to a video or into a folder of frames. Args: kp2d (np.ndarray): should be array of shape (f * J * 2) or (f * n * J * 2)] output_path (str): output video path or image folder. frame_list (Optional[List[str]], optional): list of origin background frame paths, element in list each should be a image ... |
14,316 | from mmcv.utils import Registry
from pytorch3d.renderer import TexturesAtlas, TexturesUV, TexturesVertex
from .textures import TexturesNearest
TEXTURES = Registry('textures')
TEXTURES.register_module(
name=['TexturesAtlas', 'textures_atlas', 'atlas', 'Atlas'],
module=TexturesAtlas)
TEXTURES.register_module(
... | Build textures. |
14,317 | from typing import List, Union
import numpy as np
import torch
from pytorch3d.structures import list_to_padded
def normalize(value,
origin_value_range=None,
out_value_range=(0, 1),
dtype=None,
clip=False) -> Union[torch.Tensor, np.ndarray]:
"""Normalize the te... | Convert image tensor to array. |
14,318 | from typing import List, Union
import numpy as np
import torch
from pytorch3d.structures import list_to_padded
def normalize(value,
origin_value_range=None,
out_value_range=(0, 1),
dtype=None,
clip=False) -> Union[torch.Tensor, np.ndarray]:
"""Normalize the te... | Convert image array to tensor. |
14,319 | from typing import List, Union
import numpy as np
import torch
from pytorch3d.structures import list_to_padded
The provided code snippet includes necessary dependencies for implementing the `rgb2bgr` function. Write a Python function `def rgb2bgr(rgbs) -> Union[torch.Tensor, np.ndarray]` to solve the following problem... | Convert color channels. |
14,320 | from mmcv.utils import Registry
from .lights import AmbientLights, DirectionalLights, PointLights
LIGHTS = Registry('lights')
LIGHTS.register_module(
name=['directional', 'directional_lights', 'DirectionalLights'],
module=DirectionalLights)
LIGHTS.register_module(
name=['point', 'point_lights', 'PointLight... | Build lights. |
14,321 | from mmcv.utils import Registry
from pytorch3d.renderer import (
HardFlatShader,
HardGouraudShader,
HardPhongShader,
SoftGouraudShader,
SoftPhongShader,
)
from .shader import (
DepthShader,
NoLightShader,
NormalShader,
SegmentationShader,
SilhouetteShader,
)
SHADER = Registry('sh... | Build shader. |
14,322 | from typing import Iterable, List, Union
import numpy as np
import torch
import torch.nn as nn
from pytorch3d.renderer import TexturesUV, TexturesVertex
from pytorch3d.renderer.mesh.textures import TexturesBase
from pytorch3d.structures import Meshes, list_to_padded, padded_to_list
from mmhuman3d.models.body_models.bui... | Join `meshes` as a scene each batch. For ParametricMeshes. The Meshes must share the same batch size, and topology could be different. They must all be on the same device. If `include_textures` is true, the textures should be the same type, all be None is not accepted. If `include_textures` is False, textures are ignor... |
14,323 | import io
import os
import shutil
from pathlib import Path
from typing import Iterable, List, Optional, Union
import cv2
import mmcv
import numpy as np
from matplotlib import pyplot as plt
from matplotlib.lines import Line2D
from mpl_toolkits.mplot3d import Axes3D
from mmhuman3d.core.conventions.cameras.convert_convent... | set new pose with axis convention. |
14,324 | import io
import os
import shutil
from pathlib import Path
from typing import Iterable, List, Optional, Union
import cv2
import mmcv
import numpy as np
from matplotlib import pyplot as plt
from matplotlib.lines import Line2D
from mpl_toolkits.mplot3d import Axes3D
from mmhuman3d.core.conventions.cameras.convert_convent... | Draw line on fig with matplotlib. |
14,325 | import io
import os
import shutil
from pathlib import Path
from typing import Iterable, List, Optional, Union
import cv2
import mmcv
import numpy as np
from matplotlib import pyplot as plt
from matplotlib.lines import Line2D
from mpl_toolkits.mplot3d import Axes3D
from mmhuman3d.core.conventions.cameras.convert_convent... | Get numpy image from IO. |
14,326 | import torch
def vis_z_buffer(z, percentile=1, vis_pad=0.2):
z = z[:, :, 0]
mask = z > 1e-5
if torch.sum(mask) == 0:
z[...] = 0
else:
vmin = torch.quantile(z[mask], percentile / 100)
vmax = torch.quantile(z[mask], 1 - percentile / 100)
pad = (vmax - vmin) * vis_pad
... | null |
14,327 | import torch
def vis_normals(coords, normals, vis_pad=0.2):
mask = coords[:, :, 2] > 0
coords_masked = -coords[mask]
normals_masked = normals[mask]
coords_len = torch.sqrt(torch.sum(coords_masked**2, dim=1))
dot = torch.sum(coords_masked * normals_masked, dim=1) / coords_len
h, w = normals.s... | null |
14,328 | import torch
The provided code snippet includes necessary dependencies for implementing the `estimate_normals` function. Write a Python function `def estimate_normals(vertices, faces, pinhole, vertices_filter=None)` to solve the following problem:
Estimate the vertices normals with the specified faces and camera. Args... | Estimate the vertices normals with the specified faces and camera. Args: vertices (torch.tensor): Shape should be (num_verts, 3). faces (torch.tensor): The faces of the vertices. pinhole (object): The object of the camera. Returns: coords (torch.tensor): The estimated coordinates. normals (torch.tensor): The estimated ... |
14,329 | import torch
The provided code snippet includes necessary dependencies for implementing the `project_mesh` function. Write a Python function `def project_mesh(vertices, faces, vertice_values, pinhole, vertices_filter=None)` to solve the following prob... | Project mesh to the image plane with the specified faces and camera. Args: vertices (torch.tensor): Shape should be (num_verts, 3). faces (torch.tensor): The faces of the vertices. vertice_values (torch.tensor): The depth of the each vertex. pinhole (object): The object of the camera. Returns: torch.tensor: The project... |
14,330 | import numpy as np
import trimesh
from trimesh.proximity import closest_point
from .mesh_eval import compute_similarity_transform
def compute_similarity_transform(source_points,
target_points,
return_tform=False):
"""Computes a similarity transform ... | Calculate the mean per-joint position error (MPJPE) and the error after rigid alignment with the ground truth (PA-MPJPE). batch_size: N num_keypoints: K keypoint_dims: C Args: pred (np.ndarray[N, K, C]): Predicted keypoint location. gt (np.ndarray[N, K, C]): Groundtruth keypoint location. mask (np.ndarray[N, K]): Visib... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.