id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
13,106
import torch from torch.nn import functional as F import numpy as np def quaternion_to_axis_angle(quaternion): """ Convert quaternion to axis angle. based on: https://github.com/facebookresearch/QuaterNet/blob/master/common/quaternion.py#L138 Args: quaternion: torch tensor of shape (batch_size, ...
@q1: torch tensor of shape (frame, joints, 4) quaternion @q2: same as q1 @output: torch tensor of shape (frame, joints)
13,107
import torch from torch.nn import functional as F import numpy as np def get_extrinsic(translation, rotation): batch_size = translation.shape[0] pose = torch.zeros((batch_size, 4, 4)) pose[:,:3, :3] = rotation pose[:,:3, 3] = translation pose[:,3, 3] = 1 extrinsic = torch.inverse(pose) retu...
null
13,108
import torch from torch.nn import functional as F import numpy as np def euler_fix_old(euler): frame_num = euler.shape[0] joint_num = euler.shape[1] for l in range(3): for j in range(joint_num): overall_add = 0. for i in range(1,frame_num): add1 = overall_add...
null
13,109
from ..annotator.file_utils import read_json from ..mytools import Timer from .lossbase import print_table from ..config.baseconfig import load_object from ..bodymodel.base import Params from torch.utils.data import DataLoader from tqdm import tqdm def dict_of_tensor_to_numpy(body_params): body_params = {key:val.d...
null
13,110
from ..annotator.file_utils import read_json from ..mytools import Timer from .lossbase import print_table from ..config.baseconfig import load_object from ..bodymodel.base import Params from torch.utils.data import DataLoader from tqdm import tqdm def grad_require(params, flag=False): if isinstance(params, list):...
null
13,111
from ..annotator.file_utils import read_json from ..mytools import Timer from .lossbase import print_table from ..config.baseconfig import load_object from ..bodymodel.base import Params from torch.utils.data import DataLoader from tqdm import tqdm def rel_change(prev_val, curr_val): return (prev_val - curr_val) /...
null
13,112
from ..annotator.file_utils import read_json from ..mytools import Timer from .lossbase import print_table from ..config.baseconfig import load_object from ..bodymodel.base import Params from torch.utils.data import DataLoader from tqdm import tqdm class LBFGS(Optimizer): def __init__(self, p...
null
13,113
from ..annotator.file_utils import read_json from ..mytools import Timer from .lossbase import print_table from ..config.baseconfig import load_object from ..bodymodel.base import Params from torch.utils.data import DataLoader from tqdm import tqdm def load_object(module_name, module_args, **extra_args): module_pa...
null
13,114
from ..annotator.file_utils import read_json from ..mytools import Timer from .lossbase import print_table from ..config.baseconfig import load_object from ..bodymodel.base import Params from torch.utils.data import DataLoader from tqdm import tqdm def load_object(module_name, module_args, **extra_args): module_pa...
null
13,115
from ..annotator.file_utils import read_json from ..mytools import Timer from .lossbase import print_table from ..config.baseconfig import load_object from ..bodymodel.base import Params from torch.utils.data import DataLoader from tqdm import tqdm def dict_of_numpy_to_tensor(body_model, body_params, *args, **kwargs): ...
null
13,116
from ..annotator.file_utils import read_json from ..mytools import Timer from .lossbase import print_table from ..config.baseconfig import load_object from ..bodymodel.base import Params from torch.utils.data import DataLoader from tqdm import tqdm def plot_meshes(img, meshes, K, R, T): import cv2 mesh_camera ...
null
13,117
import torch from ..bodymodel.lbs import batch_rodrigues from .torchgeometry import rotation_matrix_to_axis_angle, rotation_matrix_to_quaternion, quaternion_to_rotation_matrix, quaternion_to_axis_angle import numpy as np from .base_ops import BeforeAfterBase def quaternion_to_rotation_matrix(quaternion): """ C...
Compute the twist component of given rotation and twist axis https://stackoverflow.com/questions/3684269/component-of-a-quaternion-rotation-around-an-axis Parameters ---------- rotation_matrix : Tensor (B, 3, 3,) The rotation to convert twist_axis : Tensor (B, 3,) The twist axis Returns ------- Tensor (B, 3, 3) The twi...
13,118
import numpy as np from os.path import join import os import cv2 def flipPoint2D(point): def mirrorPoint3D(point, M): point_homo = np.hstack([point, np.ones([point.shape[0], 1])]) point_m = (M @ point_homo.T).T[..., :3] return flipPoint2D(point_m)
null
13,119
import numpy as np from os.path import join import os import cv2 def get_rotation_from_two_directions(direc0, direc1): direc0 = direc0/np.linalg.norm(direc0) direc1 = direc1/np.linalg.norm(direc1) rotdir = np.cross(direc0, direc1) if np.linalg.norm(rotdir) < 1e-2: return np.eye(3) rotdir = ...
null
13,120
import numpy as np class ComposedFilter: def __init__(self, filters, min_conf) -> None: self.filters = filters self.min_conf = min_conf def __call__(self, keypoints, **kwargs) -> bool: conf = keypoints[:, 2] conf[conf<self.min_conf] = 0 valid = conf>self.min_conf ...
null
13,121
import numpy as np CONFIG = { 'points': { 'nJoints': 1, 'kintree': [] } } CONFIG['smpl'] = {'nJoints': 24, 'kintree': [ [ 0, 1 ], [ 0, 2 ], [ 0, 3 ], [ 1, 4 ], [ 2, 5 ], [ 3, 6 ], [ 4, 7 ], [ 5, 8 ], [ 6, 9 ], [...
null
13,122
import numpy as np CONFIG = { 'points': { 'nJoints': 1, 'kintree': [] } } CONFIG['smpl'] = {'nJoints': 24, 'kintree': [ [ 0, 1 ], [ 0, 2 ], [ 0, 3 ], [ 1, 4 ], [ 2, 5 ], [ 3, 6 ], [ 4, 7 ], [ 5, 8 ], [ 6, 9 ], [...
null
13,123
import numpy as np COCO17_IN_BODY25 = [0,16,15,18,17,5,2,6,3,7,4,12,9,13,10,14,11] def coco17tobody25(points2d): dim = 3 if len(points2d.shape) == 2: points2d = points2d[None, :, :] dim = 2 kpts = np.zeros((points2d.shape[0], 25, 3)) kpts[:, COCO17_IN_BODY25, :2] = points2d[:, :, :2] ...
null
13,124
import os from os.path import join from glob import glob import cv2 import os, sys import numpy as np from ..mytools.camera_utils import read_camera, get_fundamental_matrix, Undistort from ..mytools import FileWriter, read_annot, getFileList, save_json from ..mytools.reader import read_keypoints3d, read_json, read_smpl...
null
13,125
import os from os.path import join from glob import glob import cv2 import os, sys import numpy as np from ..mytools.camera_utils import read_camera, get_fundamental_matrix, Undistort from ..mytools import FileWriter, read_annot, getFileList, save_json from ..mytools.reader import read_keypoints3d, read_json, read_smpl...
null
13,126
import os from os.path import join from glob import glob import cv2 import os, sys import numpy as np from ..mytools.camera_utils import read_camera, get_fundamental_matrix, Undistort from ..mytools import FileWriter, read_annot, getFileList, save_json from ..mytools.reader import read_keypoints3d, read_json, read_smpl...
null
13,127
def load_weight_pose2d(model, opts): if model == 'smpl': weight = { 'k2d': 2e-4, 'init_poses': 1e-3, 'init_shapes': 1e-2, 'smooth_body': 5e-1, 'smooth_poses': 1e-1, } elif model == 'smplh': raise NotImplementedError elif model == 'smplx': ...
null
13,128
from ..pyfitting import optimizeShape, optimizePose2D, optimizePose3D from ..mytools import Timer from ..dataset import CONFIG from .weight import load_weight_pose, load_weight_shape from .config import Config class Config: OPT_R = False OPT_T = False OPT_POSE = False OPT_SHAPE = False OPT_HAND = F...
null
13,129
from ..pyfitting import optimizeShape, optimizePose2D, optimizePose3D from ..mytools import Timer from ..dataset import CONFIG from .weight import load_weight_pose, load_weight_shape from .config import Config def multi_stage_optimize(body_model, params, kp3ds, kp2ds=None, bboxes=None, Pall=None, weight={}, cfg=None): ...
null
13,130
from ..pyfitting import optimizeShape, optimizePose2D, optimizePose3D from ..mytools import Timer from ..dataset import CONFIG from .weight import load_weight_pose, load_weight_shape from .config import Config def multi_stage_optimize(body_model, params, kp3ds, kp2ds=None, bboxes=None, Pall=None, weight={}, cfg=None): ...
null
13,131
from .yacs import CfgNode as CN import importlib def load_object(module_name, module_args, **extra_args): def load_renderer(cfg, network): if cfg.split == 'mesh': return load_object(cfg.renderer_mesh_module, cfg.renderer_mesh_args, net=network) else: return load_object(cfg.renderer_module, cfg....
null
13,132
from .yacs import CfgNode as CN import importlib def load_object(module_name, module_args, **extra_args): module_path = '.'.join(module_name.split('.')[:-1]) module = importlib.import_module(module_path) name = module_name.split('.')[-1] obj = getattr(module, name)(**extra_args, **module_args) retur...
null
13,133
from .yacs import CfgNode as CN import importlib def load_object(module_name, module_args, **extra_args): module_path = '.'.join(module_name.split('.')[:-1]) module = importlib.import_module(module_path) name = module_name.split('.')[-1] obj = getattr(module, name)(**extra_args, **module_args) retur...
null
13,134
from .yacs import CfgNode as CN class Config: def load_from_args(cls, default_cfg='config/vis/base.yml'): import argparse parser = argparse.ArgumentParser() parser.add_argument('--cfg', type=str, default=default_cfg) parser.add_argument('--local_rank', type=int, default=0) pa...
null
13,135
import copy import io import logging import os from ast import literal_eval import yaml try: _FILE_TYPES = (file, io.IOBase) _PY2 = True except NameError: _FILE_TYPES = (io.IOBase,) def _load_cfg_from_file(file_obj): """Load a config from a YAML file or a Python source file.""" _, file_extension = o...
Load a cfg. Supports loading from: - A file object backed by a YAML file - A file object backed by a Python source file that exports an attribute "cfg" that is either a dict or a CfgNode - A string that can be parsed as valid YAML
13,136
import copy import io import logging import os from ast import literal_eval import yaml _VALID_TYPES = {tuple, list, str, int, float, bool} class CfgNode(dict): """ CfgNode represents an internal node in the configuration tree. It's a simple dict-like container that allows for attribute-based access to keys...
Recursively convert all CfgNode objects to dict objects.
13,137
import copy import io import logging import os from ast import literal_eval import yaml class CfgNode(dict): """ CfgNode represents an internal node in the configuration tree. It's a simple dict-like container that allows for attribute-based access to keys. """ IMMUTABLE = "__immutable__" DEPREC...
Merge config dictionary a into config dictionary b, clobbering the options in b whenever they are also specified in a.
13,138
from .optimize_simple import _optimizeSMPL, deepcopy_tensor, get_prepare_smplx, dict_of_tensor_to_numpy from .lossfactory import LossRepro, LossInit, LossSmoothBody, LossSmoothPoses, LossSmoothBodyMulti, LossSmoothPosesMulti from ..dataset.mirror import flipSMPLPoses, flipPoint2D, flipSMPLParams import torch import num...
From mirror vector to mirror matrix Args: m (bn, 4): (a, b, c, d) Returns: M: (bn, 3, 4)
13,139
from .optimize_simple import _optimizeSMPL, deepcopy_tensor, get_prepare_smplx, dict_of_tensor_to_numpy from .lossfactory import LossRepro, LossInit, LossSmoothBody, LossSmoothPoses, LossSmoothBodyMulti, LossSmoothPosesMulti from ..dataset.mirror import flipSMPLPoses, flipPoint2D, flipSMPLParams import torch import num...
simple function for optimizing mirror # 先写图片的 Args: body_model (SMPL model) params (DictParam): poses(2, 72), shapes(1, 10), Rh(2, 3), Th(2, 3) bboxes (nFrames, nViews, nJoints, 4): 2D bbox of each view,输入的时候是按照时序叠起来的 keypoints2d (nFrames, nViews, nJoints, 4): 2D keypoints of each view,输入的时候是按照时序叠起来的 weight (Dict): str...
13,140
from .optimize_simple import _optimizeSMPL, deepcopy_tensor, get_prepare_smplx, dict_of_tensor_to_numpy from .lossfactory import LossRepro, LossInit, LossSmoothBody, LossSmoothPoses, LossSmoothBodyMulti, LossSmoothPosesMulti from ..dataset.mirror import flipSMPLPoses, flipPoint2D, flipSMPLParams import torch import num...
simple function for optimizing mirror Args: body_model (SMPL model) params (DictParam): poses(2, 72), shapes(1, 10), Rh(2, 3), Th(2, 3) bboxes (nViews, nFrames, 5): 2D bbox of each view,输入的时候是按照时序叠起来的 keypoints2d (nViews, nFrames, nJoints, 3): 2D keypoints of each view,输入的时候是按照时序叠起来的 weight (Dict): string:float cfg (Co...
13,141
import torch from functools import reduce from torch.optim.optimizer import Optimizer def _cubic_interpolate(x1, f1, g1, x2, f2, g2, bounds=None): # ported from https://github.com/torch/optim/blob/master/polyinterp.lua # Compute bounds of interpolation area if bounds is not None: xmin_bound, xmax_bo...
null
13,142
import numpy as np import torch from .lbfgs import LBFGS from .optimize import FittingMonitor, grad_require, FittingLog from .lossfactory import LossSmoothBodyMean, LossRegPoses from .lossfactory import LossKeypoints3D, LossKeypointsMV2D, LossSmoothBody, LossRegPosesZero, LossInit, LossSmoothPoses class LBFGS(Optimiz...
simple function for optimizing model shape given 3d keypoints Args: body_model (SMPL model) params_init (DictParam): poses(1, 72), shapes(1, 10), Rh(1, 3), Th(1, 3) keypoints (nFrames, nJoints, 3): 3D keypoints weight (Dict): string:float kintree ([[src, dst]]): list of list:int cfg (Config): Config Node controling run...
13,143
import numpy as np import torch from .lbfgs import LBFGS from .optimize import FittingMonitor, grad_require, FittingLog from .lossfactory import LossSmoothBodyMean, LossRegPoses from .lossfactory import LossKeypoints3D, LossKeypointsMV2D, LossSmoothBody, LossRegPosesZero, LossInit, LossSmoothPoses def interp(left_valu...
null
13,144
import numpy as np import torch from .lbfgs import LBFGS from .optimize import FittingMonitor, grad_require, FittingLog from .lossfactory import LossSmoothBodyMean, LossRegPoses from .lossfactory import LossKeypoints3D, LossKeypointsMV2D, LossSmoothBody, LossRegPosesZero, LossInit, LossSmoothPoses def get_interp_by_ke...
simple function for optimizing model pose given 3d keypoints Args: body_model (SMPL model) params (DictParam): poses(1, 72), shapes(1, 10), Rh(1, 3), Th(1, 3) keypoints3d (nFrames, nJoints, 4): 3D keypoints weight (Dict): string:float cfg (Config): Config Node controling running mode
13,145
import numpy as np import torch from .lbfgs import LBFGS from .optimize import FittingMonitor, grad_require, FittingLog from .lossfactory import LossSmoothBodyMean, LossRegPoses from .lossfactory import LossKeypoints3D, LossKeypointsMV2D, LossSmoothBody, LossRegPosesZero, LossInit, LossSmoothPoses def get_interp_by_ke...
simple function for optimizing model pose given 3d keypoints Args: body_model (SMPL model) params (DictParam): poses(1, 72), shapes(1, 10), Rh(1, 3), Th(1, 3) keypoints2d (nFrames, nViews, nJoints, 4): 2D keypoints of each view bboxes: (nFrames, nViews, 5) weight (Dict): string:float cfg (Config): Config Node controlin...
13,146
import numpy as np import torch from .operation import projection, batch_rodrigues The provided code snippet includes necessary dependencies for implementing the `gmof` function. Write a Python function `def gmof(squared_res, sigma_squared)` to solve the following problem: Geman-McClure error function Here is the fun...
Geman-McClure error function
13,147
import numpy as np import torch from .operation import projection, batch_rodrigues def projection(points3d, camera_intri, R=None, T=None, distance=None): """ project the 3d points to camera coordinate Arguments: points3d {Tensor} -- (bn, N, 3) camera_intri {Tensor} -- (bn, 3, 3) distan...
null
13,148
import numpy as np import torch from .operation import projection, batch_rodrigues def batch_rodrigues(rot_vecs, epsilon=1e-8, dtype=torch.float32): ''' Calculates the rotation matrices for a batch of rotation vectors Parameters ---------- rot_vecs: torch.tensor Nx3 array of N a...
null
13,149
import numpy as np import torch from .operation import projection, batch_rodrigues def RegularizationLoss(body_params, body_params_init, weight_loss): loss_dict = {} for key in ['poses', 'shapes', 'Th', 'hands', 'head', 'expression']: if 'init_'+key in weight_loss.keys() and weight_loss['init_'+key] > ...
null
13,150
import numpy as np import os from tqdm import tqdm import torch import json def rel_change(prev_val, curr_val): return (prev_val - curr_val) / max([np.abs(prev_val), np.abs(curr_val), 1])
null
13,151
import os import numpy as np import cv2 import pyrender import trimesh import copy7, 1.), colors_table = { # colorblind/print/copy safe: '_blue': [0.65098039, 0.74117647, 0.85882353], '_pink': [.9, .7, .7], '_mint': [ 166/255., 229/255., 204/255.], '_mint2': [ 202/255., 229/255., 223/255.], ...
null
13,152
import os import numpy as np import cv2 import pyrender import trimesh import copy7, 1.), from pyrender import RenderFlags class Renderer(object): def __init__(self, focal_length=1000, height=512, width=512, faces=None, bg_color=[1.0, 1.0, 1.0, 0.0], down_scale=1, # render 配置 extra_mesh=...
null
13,153
import numpy as np import cv2 from os.path import join import os from ..dataset.config import CONFIG The provided code snippet includes necessary dependencies for implementing the `calTransformation` function. Write a Python function `def calTransformation(v_i, v_j, r, adaptr=False, ratio=10)` to solve the following p...
from to vertices to T Arguments: v_i {} -- [description] v_j {[type]} -- [description]
13,154
import numpy as np import cv2 import numpy as np from tqdm import tqdm from os.path import join def load_sphere(): cur_dir = os.path.dirname(__file__) faces = np.loadtxt(join(cur_dir, 'sphere_faces_20.txt'), dtype=int) vertices = np.loadtxt(join(cur_dir, 'sphere_vertices_20.txt')) return vertices, faces...
create sphere Args: points (array): (N, 3)/(N, 4) r (float, optional): radius. Defaults to 0.01.
13,155
import numpy as np import cv2 import numpy as np from tqdm import tqdm from os.path import join import os def create_ground( center=[0, 0, 0], xdir=[1, 0, 0], ydir=[0, 1, 0], # 位置 step=1, xrange=10, yrange=10, # 尺寸 white=[1., 1., 1.], black=[0.,0.,0.], # 颜色 two_sides=True ): if isinstance(cente...
null
13,156
import numpy as np import cv2 import numpy as np from tqdm import tqdm from os.path import join def get_rotation_from_two_directions(direc0, direc1): direc0 = direc0/np.linalg.norm(direc0) direc1 = direc1/np.linalg.norm(direc1) rotdir = np.cross(direc0, direc1) if np.linalg.norm(rotdir) < 1e-2: ...
null
13,157
import numpy as np import cv2 import numpy as np from tqdm import tqdm from os.path import join import os current_dir = os.path.dirname(os.path.realpath(__file__)) def create_cameras_texture(cameras, imgnames, scale=5e-3): import trimesh import pyrender from PIL import Image from os.path import join ...
null
13,158
import numpy as np import cv2 import numpy as np from tqdm import tqdm from os.path import join import os def create_mesh_pyrender(vert, faces, col): import trimesh import pyrender mesh = trimesh.Trimesh(vert, faces, process=False) material = pyrender.MetallicRoughnessMaterial( metallicFactor=0...
null
13,159
import pyrender import numpy as np import trimesh import cv2 from .pyrender_flags import get_flags from ..mytools.vis_base import get_rgb def offscree_render(renderer, scene, img, flags): rend_rgba, rend_depth = renderer.render(scene, flags=flags) assert rend_depth.max() < 65, 'depth should less than 65.536: {...
null
13,160
import pyrender import numpy as np import trimesh import cv2 from .pyrender_flags import get_flags from ..mytools.vis_base import get_rgb class Renderer: def __init__(self, bg_color=[1.0, 1.0, 1.0, 0.0], ambient_light=[0.5, 0.5, 0.5], flags={}) -> None: self.bg_color = bg_color self.ambient_light = ...
null
13,161
import pyrender import numpy as np import trimesh import cv2 from .pyrender_flags import get_flags from ..mytools.vis_base import get_rgb colors_table = { # colorblind/print/copy safe: '_blue': [0.65098039, 0.74117647, 0.85882353], '_pink': [.9, .7, .7], '_mint': [ 166/255., 229/255., 204/255.], '...
null
13,162
from glob import glob from os.path import join import numpy as np from ..mytools.file_utils import read_json from ..mytools.debug_utils import log from ..mytools.reader import read_keypoints3d, read_smpl import os from ..mytools.camera_utils import read_cameras, Undistort import cv2 from ..mytools.vis_base import merge...
null
13,163
from glob import glob from os.path import join import numpy as np from ..mytools.file_utils import read_json from ..mytools.debug_utils import log from ..mytools.reader import read_keypoints3d, read_smpl import os from ..mytools.camera_utils import read_cameras, Undistort import cv2 from ..mytools.vis_base import merge...
null
13,164
from pyrender import RenderFlags render_flags_default = { 'flip_wireframe': False, 'all_wireframe': False, 'all_solid': True, 'shadows': False, # TODO:bug exists in shadow mode 'vertex_normals': False, 'face_normals': False, 'cull_faces': True, # set to False 'point_size': 1.0, 'rgb...
null
13,165
import open3d as o3d import numpy as np from .geometry import create_ground as create_ground_ from .geometry import create_point as create_point_ from .geometry import create_line as create_line_ from os.path import join def _create_cylinder(): # create_cylinder(radius=1.0, height=2.0, resolution=20, split=4, crea...
null
13,166
import open3d as o3d import numpy as np from .geometry import create_ground as create_ground_ from .geometry import create_point as create_point_ from .geometry import create_line as create_line_ from os.path import join load_mesh = o3d.io.read_triangle_mesh def read_mesh(filename): mesh = load_mesh(filename) ...
null
13,167
import open3d as o3d import numpy as np from .geometry import create_ground as create_ground_ from .geometry import create_point as create_point_ from .geometry import create_line as create_line_ from os.path import join Vector3dVector = o3d.utility.Vector3dVector def create_pcd(xyz, color=None, colors=None): pcd ...
null
13,168
import open3d as o3d import numpy as np from .geometry import create_ground as create_ground_ from .geometry import create_point as create_point_ from .geometry import create_line as create_line_ from os.path import join def create_mesh(vertices, faces, colors=None, normal=True, **kwargs): mesh = TriangleMesh() ...
null
13,169
import open3d as o3d import numpy as np from .geometry import create_ground as create_ground_ from .geometry import create_point as create_point_ from .geometry import create_line as create_line_ from os.path import join def create_mesh(vertices, faces, colors=None, normal=True, **kwargs): mesh = TriangleMesh() ...
null
13,170
import open3d as o3d import numpy as np from .geometry import create_ground as create_ground_ from .geometry import create_point as create_point_ from .geometry import create_line as create_line_ from os.path import join TriangleMesh = o3d.geometry.TriangleMesh def create_coord(camera = [0,0,0], radius=1, scale=1): ...
null
13,171
import open3d as o3d import numpy as np from .geometry import create_ground as create_ground_ from .geometry import create_point as create_point_ from .geometry import create_line as create_line_ from os.path import join def create_bbox(min_bound=(-3., -3., 0), max_bound=(3., 3., 2), flip=False): if flip: ...
null
13,172
import open3d as o3d import numpy as np from .geometry import create_ground as create_ground_ from .geometry import create_point as create_point_ from .geometry import create_line as create_line_ from os.path import join def create_line(**kwargs): return create_mesh(**create_line_(**kwargs)) def get_bound_corners(b...
null
13,173
import open3d as o3d import numpy as np from .geometry import create_ground as create_ground_ from .geometry import create_point as create_point_ from .geometry import create_line as create_line_ from os.path import join def create_my_bbox(min_bound=(-3., -3., 0), max_bound=(3., 3., 2)): # 使用圆柱去创建一个mesh bbox =...
null
13,174
import open3d as o3d import numpy as np from .geometry import create_ground as create_ground_ from .geometry import create_point as create_point_ from .geometry import create_line as create_line_ from os.path import join def create_mesh(vertices, faces, colors=None, normal=True, **kwargs): mesh = TriangleMesh() ...
null
13,175
import open3d as o3d import numpy as np from .geometry import create_ground as create_ground_ from .geometry import create_point as create_point_ from .geometry import create_line as create_line_ from os.path import join load_mesh = o3d.io.read_triangle_mesh vis = o3d.visualization.draw_geometries def read_and_vis(fil...
null
13,176
def get_ext(mode): ext = {'image': '.jpg', 'color':'.jpg', 'blend': '.jpg', 'depth':'.png', 'mask':'.png', 'instance':'.png', 'instance-mask': '.png', 'instance-depth': '.png', 'instance-depth-twoside': '.png', 'side': '.jpg' }.get(mode, '.jpg') return ext def ge...
null
13,177
None: self.render = render self.position = {} def factory(self, mode): if mode == 'image': return self.render_image elif mode == 'color': return self.render_color elif mode == 'depth': return self.render_depth elif mode == 'corner':...
null
13,178
from easymocap.config.baseconfig import load_object import torch def make_data_sampler(cfg, dataset, shuffle, is_distributed, is_train): if not is_train and cfg.test.sampler == 'FrameSampler': from .samplers import FrameSampler sampler = FrameSampler(dataset) return sampler if is_distrib...
null
13,179
import torch from collections import Counter from bisect import bisect_right class MultiStepLR(torch.optim.lr_scheduler._LRScheduler): def __init__(self, optimizer, milestones, gamma=0.1, last_epoch=-1): self.milestones = Counter(milestones) self.gamma = gamma super(MultiStepLR, self).__init...
null
13,180
import torch from collections import Counter from bisect import bisect_right def set_lr_scheduler(cfg_scheduler, scheduler): if cfg_scheduler.type == 'multi_step': scheduler.milestones = Counter(cfg_scheduler.milestones) elif cfg_scheduler.type == 'exponential': scheduler.decay_epochs = cfg_sch...
null
13,181
import torch _optimizer_factory = { 'adam': torch.optim.Adam, 'sgd': torch.optim.SGD } def Optimizer(net, cfg): params = [] lr = cfg.lr weight_decay = cfg.weight_decay for key, value in net.named_parameters(): if not value.requires_grad: continue params += [{"params...
null
13,182
import os from termcolor import colored import torch def load_model(net, optim, scheduler, recorder, model_dir, resume=True, epoch=-1): if not resume: os.system('rm -rf {}'.format(model_dir)) if not os.path.exist...
null
13,183
import os from termcolor import colored import torch def save_model(net, optim, scheduler, recorder, model_dir, epoch, last=False): os.system('mkdir -p {}'.format(model_dir)) model = { 'net': net.state_dict(), 'optim': optim.state_dict(), 'scheduler': scheduler.state_dict(), 're...
null
13,184
import os from termcolor import colored import torch def load_network(net, model_dir, resume=True, epoch=-1, strict=True): if not resume: return 0 if not os.path.exists(model_dir): print(colored('pretrained model does not exist', 'red')) return 0 if os.path.isdir(model_dir): ...
null
13,185
import numpy as np import cv2 from termcolor import colored import os from os.path import join from ..dataset.utils_reader import palette colors_rgb = [ (1, 1, 1), (94/255, 124/255, 226/255), # 青色 (255/255, 200/255, 87/255), # yellow (74/255., 189/255., 172/255.), # green (8/255, 76/255, 97/255), ...
null
13,186
import cv2 import numpy as np from ...mytools.file_utils import read_json def img_to_numpy(img): if len(img.shape) == 3: img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) img = img.astype(np.float32)/255. return img
null
13,187
import cv2 import numpy as np from ...mytools.file_utils import read_json def numpy_to_img(img): img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR) img = (img*255).astype(np.uint8) return img
null
13,188
import cv2 import numpy as np from ...mytools.file_utils import read_json def read_json(path): assert os.path.exists(path), path with open(path) as f: try: data = json.load(f) except: print('Reading error {}'.format(path)) data = [] return data def read...
null
13,189
import cv2 import numpy as np from ...mytools.file_utils import read_json palette = get_schp_palette(semantic_dim) The provided code snippet includes necessary dependencies for implementing the `get_schp_palette` function. Write a Python function `def get_schp_palette(num_cls=256)` to solve the following problem: Ret...
Returns the color map for visualizing the segmentation mask. Inputs: num_cls: Number of classes. Returns: The color map.
13,190
import cv2 import numpy as np from ...mytools.file_utils import read_json semantic_dict = { 'background': 0, 'hat': 1, 'hair': 1, 'glove': 1, 'sunglasses': 1, 'upper_cloth': 2, 'dress': 1, #x 'coat': 1, 'sock': 1, 'pant': 3, 'jumpsuit': 1, 'scarf': 1, 'skirt': 1, ...
null
13,191
from os.path import join import numpy as np import cv2 from tqdm import trange import copy from .mvbase import BaseDataset, read_json, get_bounds from ...multistage.mirror import calc_mirror_transform import torch from .utils_sample import AABBwMask def calc_mirror_transform(m_): """ From mirror vector to mirror m...
null
13,192
import numpy as np import cv2 import math from collections import namedtuple def get_rays(H, W, K, R, T): # calculate the camera origin rays_o = -np.dot(R.T, T).ravel() # calculate the world coodinates of pixels i, j = np.meshgrid(np.arange(W, dtype=np.float32), np.arange(H, dtyp...
null
13,193
import numpy as np import cv2 import math from collections import namedtuple The provided code snippet includes necessary dependencies for implementing the `project` function. Write a Python function `def project(xyz, K, R, T)` to solve the following problem: xyz: [N, 3] K: [3, 3] RT: [3, 4] Here is the function: de...
xyz: [N, 3] K: [3, 3] RT: [3, 4]
13,194
import numpy as np import cv2 import math from collections import namedtuple def get_bound_corners(bounds): min_x, min_y, min_z = bounds[0] max_x, max_y, max_z = bounds[1] corners_3d = np.array([ [min_x, min_y, min_z], [min_x, min_y, max_z], [min_x, max_y, min_z], [min_x, ma...
null
13,195
import numpy as np import cv2 import math from collections import namedtuple def get_bounds(xyz, delta=0.05): min_xyz = np.min(xyz, axis=0) max_xyz = np.max(xyz, axis=0) if isinstance(delta, list): delta = np.array(delta, dtype=np.float32).reshape(1, 3) min_xyz -= delta max_xyz += delta ...
null
13,196
import numpy as np import cv2 import math from collections import namedtuple def sample_rays(bound_sum, mask_back, split, nrays=1024, **kwargs): coord_body = np.argwhere(bound_sum*mask_back > 0) if split == 'train': coord_body = coord_body[np.random.randint(0, len(coord_body), nrays)] return coord_...
null
13,197
import numpy as np import cv2 import math from collections import namedtuple def generate_weight_coords(bounds, rates, back_mask): coords = [] for key in bounds.keys(): coord_ = np.argwhere(bounds[key]*back_mask > 0) if rates[key] == 1.: coords.append(coord_) elif rates[key] ...
null
13,198
import numpy as np import cv2 import math from collections import namedtuple def create_cameras_mean(cameras, camera_args): Told = np.stack([d['T'] for d in cameras]) Rold = np.stack([d['R'] for d in cameras]) Kold = np.stack([d['K'] for d in cameras]) Cold = - np.einsum('bmn,bnp->bmp', Rold.transpose(...
null
13,199
import numpy as np import cv2 import math from collections import namedtuple def create_center_radius(center, radius=5., up='y', ranges=[0, 360, 36], angle_x=0, **kwargs): center = np.array(center).reshape(1, 3) thetas = np.deg2rad(np.linspace(*ranges)) st = np.sin(thetas) ct = np.cos(thetas) zero ...
null
13,200
import numpy as np import cv2 import torch.nn as nn import torch import time import json from ..model.base import augment_z_vals, concat _time_ = 0 def tic(): global _time_ _time_ = time.time()
null
13,201
import numpy as np import cv2 import torch.nn as nn import torch import time import json from ..model.base import augment_z_vals, concat _time_ = 0 def toc(name): global _time_ print('{:15s}: {:.1f}'.format(name, 1000*(time.time() - _time_))) _time_ = time.time()
null
13,202
import numpy as np import cv2 import torch.nn as nn import torch import time import json from ..model.base import augment_z_vals, concat def raw2acc(raw): alpha = raw[..., -1] weights = alpha * torch.cumprod( torch.cat( [torch.ones((alpha.shape[0], 1)).to(alpha), 1. - alpha + 1e-10], ...
null
13,203
import numpy as np import cv2 import torch.nn as nn import torch import time import json from ..model.base import augment_z_vals, concat The provided code snippet includes necessary dependencies for implementing the `raw2outputs` function. Write a Python function `def raw2outputs(outputs, z_vals, rays_d, bkgd=None)` t...
Transforms model's predictions to semantically meaningful values. Args: acc: [num_rays, num_samples along ray, 1]. Prediction from model. feature: [num_rays, num_samples along ray, N]. Prediction from model. z_vals: [num_rays, num_samples along ray]. Integration time. rays_d: [num_rays, 3]. Direction of each ray. Retur...
13,204
import torch class Embedder: def __init__(self, **kwargs): self.kwargs = kwargs self.create_embedding_fn() def create_embedding_fn(self): embed_fns = [] d = self.kwargs['input_dims'] out_dim = 0 if self.kwargs['include_input']: embed_fns.append(lambda ...
null
13,205
import torch import torch.nn as nn from torch import searchsorted def augment_z_vals(z_vals, perturb=1): # get intervals between samples mids = .5 * (z_vals[..., 1:] + z_vals[..., :-1]) upper = torch.cat([mids, z_vals[..., -1:]], -1) lower = torch.cat([z_vals[..., :1], mids], -1) # stratified sampl...
null