code
stringlengths
17
6.64M
class Demo(data.Dataset): def __init__(self, args, train=False): self.args = args self.name = 'Demo' self.scale = args.scale self.idx_scale = 0 self.train = False self.benchmark = False self.filelist = [] for f in os.listdir(args.dir_demo): ...
class DIV2K(srdata.SRData): def __init__(self, args, train=True): super(DIV2K, self).__init__(args, train) self.repeat = (args.test_every // (args.n_train // args.batch_size)) def _scan(self): list_hr = [] list_lr = [[] for _ in self.scale] if self.train: ...
def _ms_loop(dataset, index_queue, data_queue, collate_fn, scale, seed, init_fn, worker_id): global _use_shared_memory _use_shared_memory = True _set_worker_signal_handlers() torch.set_num_threads(1) torch.manual_seed(seed) while True: r = index_queue.get() if (r is None): ...
class _MSDataLoaderIter(_DataLoaderIter): def __init__(self, loader): self.dataset = loader.dataset self.scale = loader.scale self.collate_fn = loader.collate_fn self.batch_sampler = loader.batch_sampler self.num_workers = loader.num_workers self.pin_memory = (load...
class MSDataLoader(DataLoader): def __init__(self, args, dataset, batch_size=1, shuffle=False, sampler=None, batch_sampler=None, collate_fn=default_collate, pin_memory=False, drop_last=False, timeout=0, worker_init_fn=None): super(MSDataLoader, self).__init__(dataset, batch_size=batch_size, shuffle=shuff...
class Adversarial(nn.Module): def __init__(self, args, gan_type): super(Adversarial, self).__init__() self.gan_type = gan_type self.gan_k = args.gan_k self.discriminator = discriminator.Discriminator(args, gan_type) if (gan_type != 'WGAN_GP'): self.optimizer = ...
class Discriminator(nn.Module): def __init__(self, args, gan_type='GAN'): super(Discriminator, self).__init__() in_channels = 3 out_channels = 64 depth = 7 bn = True act = nn.LeakyReLU(negative_slope=0.2, inplace=True) m_features = [common.BasicBlock(args.n...
class VGG(nn.Module): def __init__(self, conv_index, rgb_range=1): super(VGG, self).__init__() vgg_features = models.vgg19(pretrained=True).features modules = [m for m in vgg_features] if (conv_index == '22'): self.vgg = nn.Sequential(*modules[:8]) elif (conv_i...
def default_conv(in_channels, out_channels, kernel_size, bias=True): return nn.Conv2d(in_channels, out_channels, kernel_size, padding=(kernel_size // 2), bias=bias)
class MeanShift(nn.Conv2d): def __init__(self, rgb_range, rgb_mean, rgb_std, sign=(- 1)): super(MeanShift, self).__init__(3, 3, kernel_size=1) std = torch.Tensor(rgb_std) self.weight.data = torch.eye(3).view(3, 3, 1, 1) self.weight.data.div_(std.view(3, 1, 1, 1)) self.bias...
class BasicBlock(nn.Sequential): def __init__(self, in_channels, out_channels, kernel_size, stride=1, bias=True, bn=False, act=nn.ReLU(True)): m = [nn.Conv2d(in_channels, out_channels, kernel_size, padding=(kernel_size // 2), stride=stride, bias=bias)] if bn: m.append(nn.BatchNorm2d(o...
class ResBlock(nn.Module): def __init__(self, conv, n_feat, kernel_size, bias=True, bn=False, act=nn.ReLU(True), res_scale=1): super(ResBlock, self).__init__() m = [] for i in range(2): m.append(conv(n_feat, n_feat, kernel_size, bias=bias)) if bn: m...
class Upsampler(nn.Sequential): def __init__(self, conv, scale, n_feat, bn=False, act=False, bias=True): m = [] if ((scale & (scale - 1)) == 0): for _ in range(int(math.log(scale, 2))): m.append(conv(n_feat, (4 * n_feat), 3, bias)) m.append(nn.PixelShuf...
def make_model(args, parent=False): return DDBPN(args)
def projection_conv(in_channels, out_channels, scale, up=True): (kernel_size, stride, padding) = {2: (6, 2, 2), 4: (8, 4, 2), 8: (12, 8, 2)}[scale] if up: conv_f = nn.ConvTranspose2d else: conv_f = nn.Conv2d return conv_f(in_channels, out_channels, kernel_size, stride=stride, padding=p...
class DenseProjection(nn.Module): def __init__(self, in_channels, nr, scale, up=True, bottleneck=True): super(DenseProjection, self).__init__() if bottleneck: self.bottleneck = nn.Sequential(*[nn.Conv2d(in_channels, nr, 1), nn.PReLU(nr)]) inter_channels = nr else: ...
class DDBPN(nn.Module): def __init__(self, args): super(DDBPN, self).__init__() scale = args.scale[0] n0 = 128 nr = 32 self.depth = 6 rgb_mean = (0.4488, 0.4371, 0.404) rgb_std = (1.0, 1.0, 1.0) self.sub_mean = common.MeanShift(args.rgb_range, rgb_m...
def make_model(args, parent=False): return EDSR(args)
class EDSR(nn.Module): def __init__(self, args, conv=common.default_conv): super(EDSR, self).__init__() n_resblock = args.n_resblocks n_feats = args.n_feats kernel_size = 3 scale = args.scale[0] act = nn.ReLU(True) rgb_mean = (0.4488, 0.4371, 0.404) ...
def make_model(args, parent=False): return MDSR(args)
class MDSR(nn.Module): def __init__(self, args, conv=common.default_conv): super(MDSR, self).__init__() n_resblocks = args.n_resblocks n_feats = args.n_feats kernel_size = 3 self.scale_idx = 0 act = nn.ReLU(True) rgb_mean = (0.4488, 0.4371, 0.404) r...
def set_template(args): if (args.template.find('jpeg') >= 0): args.data_train = 'DIV2K_jpeg' args.data_test = 'DIV2K_jpeg' args.epochs = 200 args.lr_decay = 100 if (args.template.find('EDSR_paper') >= 0): args.model = 'EDSR' args.n_resblocks = 32 args.n_...
class Trainer(): def __init__(self, args, loader, my_model, my_loss, ckp): self.args = args self.scale = args.scale self.ckp = ckp self.loader_train = loader.loader_train self.loader_test = loader.loader_test self.model = my_model self.loss = my_loss ...
def angular_error(gt_mesh_name, gen_mesh_name, sample_num): '\n This function computes a symmetric chamfer distance, i.e. the sum of both chamfers.\n\n gt_mesh: trimesh.base.Trimesh of output mesh from whichever autoencoding reconstruction\n method (see compute_metrics.py for more)\n\n gen_m...
def print_matching(list_a, list_b): counter = 0 for (a, b) in zip(list_a, list_b): counter += 1 print(f'Matched {a} and {b}') print(f'Matched {counter} of {len(list_a)} and {len(list_b)}')
def res2str(name_a, name_b, res_a2b, res_b2a, ms): '\n this normalizes the results by bounding box diagonal\n and put into a new dict\n ' a2b_error_field = ms.mesh(3).vertex_quality_array() b2a_error_field = ms.mesh(5).vertex_quality_array() a2b_error_field /= res_a2b['diag_mesh_0'] b2a_e...
def compare_meshes(meshfile_a, meshfile_b, sample_num): ms = pymeshlab.MeshSet() ms.load_new_mesh(meshfile_a) ms.load_new_mesh(meshfile_b) res_a2b = ms.hausdorff_distance(sampledmesh=0, targetmesh=1, savesample=True, samplevert=False, sampleedge=False, samplefauxedge=False, sampleface=True, samplenum=...
def broyden(g, x_init, J_inv_init, max_steps=50, cvg_thresh=1e-05, dvg_thresh=1, eps=1e-06): 'Find roots of the given function g(x) = 0.\n This function is impleneted based on https://github.com/locuslab/deq.\n\n Tensor shape abbreviation:\n N: number of points\n D: space dimension\n Args:\...
def calculate_iou(gt, prediction): intersection = torch.logical_and(gt, prediction) union = torch.logical_or(gt, prediction) return (torch.sum(intersection) / torch.sum(union))
class VertexJointSelector(nn.Module): def __init__(self, vertex_ids=None, use_hands=True, use_feet_keypoints=True, **kwargs): super(VertexJointSelector, self).__init__() extra_joints_idxs = [] face_keyp_idxs = np.array([vertex_ids['nose'], vertex_ids['reye'], vertex_ids['leye'], vertex_id...
def chamfer_loss_separate(output, target, weight=10000.0, phase='train', debug=False): from chamferdist.chamferdist import ChamferDistance cdist = ChamferDistance() (model2scan, scan2model, idx1, idx2) = cdist(output, target) if (phase == 'train'): return (model2scan, scan2model, idx1, idx2) ...
def normal_loss(output_normals, target_normals, nearest_idx, weight=1.0, phase='train'): '\n Given the set of nearest neighbors found by chamfer distance, calculate the\n L1 discrepancy between the predicted and GT normals on each nearest neighbor point pairs.\n Note: the input normals are already normal...
def color_loss(output_colors, target_colors, nearest_idx, weight=1.0, phase='train', excl_holes=False): '\n Similar to normal loss, used in training a color prediction model.\n ' nearest_idx = nearest_idx.expand(3, (- 1), (- 1)).permute([1, 2, 0]).long() target_colors_chosen = torch.gather(target_co...
class GaussianSmoothing(nn.Module): '\n Apply gaussian smoothing on a\n 1d, 2d or 3d tensor. Filtering is performed seperately for each channel\n in the input using a depthwise convolution.\n Arguments:\n channels (int, sequence): Number of channels of the input tensors. Output will\n ...
class CBatchNorm2d(nn.Module): ' Conditional batch normalization layer class.\n Borrowed from Occupancy Network repo: https://github.com/autonomousvision/occupancy_networks\n Args:\n c_dim (int): dimension of latent conditioned code c\n f_channels (int): number of channels of the feature m...
class Conv2DBlock(nn.Module): def __init__(self, input_nc, output_nc, kernel_size=4, stride=2, padding=1, use_bias=False, use_bn=True, use_relu=True): super(Conv2DBlock, self).__init__() self.use_bn = use_bn self.use_relu = use_relu self.conv = nn.Conv2d(input_nc, output_nc, kerne...
class UpConv2DBlock(nn.Module): def __init__(self, input_nc, output_nc, kernel_size=4, stride=2, padding=1, use_bias=False, use_bn=True, up_mode='upconv', use_dropout=False): super(UpConv2DBlock, self).__init__() assert (up_mode in ('upconv', 'upsample')) self.use_bn = use_bn self...
class GeomConvLayers(nn.Module): '\n A few convolutional layers to smooth the geometric feature tensor\n ' def __init__(self, input_nc=16, hidden_nc=16, output_nc=16, use_relu=False): super().__init__() self.use_relu = use_relu self.conv1 = nn.Conv2d(input_nc, hidden_nc, kernel_...
class GeomConvBottleneckLayers(nn.Module): '\n A u-net-like small bottleneck network for smoothing the geometric feature tensor\n ' def __init__(self, input_nc=16, hidden_nc=16, output_nc=16, use_relu=False): super().__init__() self.use_relu = use_relu self.conv1 = nn.Conv2d(inp...
class GaussianSmoothingLayers(nn.Module): '\n use a fixed, not-trainable gaussian smoother layers for smoothing the geometric feature tensor\n ' def __init__(self, channels=16, kernel_size=5, sigma=1.0): super().__init__() self.conv1 = GaussianSmoothing(channels, kernel_size=kernel_size...
class UnetNoCond5DS(nn.Module): def __init__(self, input_nc=3, output_nc=3, nf=64, up_mode='upconv', use_dropout=False, return_lowres=False, return_2branches=False): super().__init__() assert (up_mode in ('upconv', 'upsample')) self.return_lowres = return_lowres self.return_2branc...
class UnetNoCond6DS(nn.Module): def __init__(self, input_nc=3, output_nc=3, nf=64, up_mode='upconv', use_dropout=False, return_lowres=False, return_2branches=False): super(UnetNoCond6DS, self).__init__() assert (up_mode in ('upconv', 'upsample')) self.return_lowres = return_lowres ...
class UnetNoCond7DS(nn.Module): def __init__(self, input_nc=3, output_nc=3, nf=64, up_mode='upconv', use_dropout=False, return_lowres=False, return_2branches=False): super(UnetNoCond7DS, self).__init__() assert (up_mode in ('upconv', 'upsample')) self.return_lowres = return_lowres ...
class ShapeDecoder(nn.Module): '\n The "Shape Decoder" in the POP paper Fig. 2. The same as the "shared MLP" in the SCALE paper.\n - with skip connection from the input features to the 4th layer\'s output features (like DeepSDF)\n - branches out at the second-to-last layer, one branch for position pred, ...
class PreDeformer(nn.Module): '\n ' def __init__(self, in_size, out_size=3, hsize=64, actv_fn='softplus'): self.hsize = hsize super(PreDeformer, self).__init__() self.conv1 = torch.nn.Conv1d(in_size, self.hsize, 1) self.conv2 = torch.nn.Conv1d(self.hsize, self.hsize, 1) ...
def loadShader(shaderType, shaderFile): strFilename = findFileOrThrow(shaderFile) shaderData = None print(f'Found shader filename = {strFilename}') with open(strFilename, 'r') as f: shaderData = f.read() shader = glCreateShader(shaderType) glShaderSource(shader, shaderData) glCompi...
def createProgram(shaderList): program = glCreateProgram() for shader in shaderList: glAttachShader(program, shader) glLinkProgram(program) status = glGetProgramiv(program, GL_LINK_STATUS) if (status == GL_FALSE): strInfoLog = glGetProgramInfoLog(program) print(('Linker fai...
def findFileOrThrow(strBasename): if os.path.isfile(strBasename): return strBasename LOCAL_FILE_DIR = ('data' + os.sep) GLOBAL_FILE_DIR = (((os.path.dirname(os.path.abspath(__file__)) + os.sep) + 'data') + os.sep) strFilename = (LOCAL_FILE_DIR + strBasename) if os.path.isfile(strFilename):...
def tensor2numpy(tensor): if isinstance(tensor, torch.Tensor): return tensor.detach().cpu().numpy()
def vertex_normal_2_vertex_color(vertex_normal): import torch if torch.is_tensor(vertex_normal): vertex_normal = vertex_normal.detach().cpu().numpy() normal_length = ((vertex_normal ** 2).sum(1) ** 0.5) normal_length = normal_length.reshape((- 1), 1) vertex_normal /= normal_length colo...
def export_ply_with_vquality(filename, v_array=None, f_array=None, vq_array=None): '\n v_array: vertex array\n vq_array: vertex quality array\n ' Nv = (v_array.shape[0] if (v_array is not None) else 0) Nf = (f_array.shape[0] if (f_array is not None) else 0) with open(filename, 'w') as plyfile...
def customized_export_ply(outfile_name, v, f=None, v_n=None, v_c=None, f_c=None, e=None): "\n Author: Jinlong Yang, jyang@tue.mpg.de\n\n Exports a point cloud / mesh to a .ply file\n supports vertex normal and color export\n such that the saved file will be correctly displayed in MeshLab\n\n # v: V...
def save_result_examples(save_dir, model_name, result_name, points, normals=None, patch_color=None, texture=None, coarse_pts=None, gt=None, epoch=None): from os.path import join import numpy as np if (epoch is None): normal_fn = '{}_{}_pred.ply'.format(model_name, result_name) else: no...
def adjust_loss_weights(init_weight, current_epoch, mode='decay', start=400, every=20): if (mode != 'binary'): if (current_epoch < start): if (mode == 'rise'): weight = (init_weight * 1e-06) else: weight = init_weight elif (every == 0): ...
def generate_previews(): gcoll = avt_preview_collections['thumbnail_previews'] image_location = gcoll.images_location enum_items = [] gallery = ['dress01.jpg', 'dress02.jpg', 'dress03.jpg', 'dress04.jpg', 'dress05.jpg', 'dress06.jpg', 'glasses01.jpg', 'glasses02.jpg', 'hat01.jpg', 'hat02.jpg', 'hat03....
def update_weights(self, context): global mAvt if (mAvt.body is not None): obj = mAvt.body else: reload_avatar() mAvt.val_breast = self.val_breast mAvt.val_torso = self.val_torso mAvt.val_hips = (- self.val_hips) mAvt.val_armslegs = self.val_limbs mAvt.val_weight = (- s...
def load_model_from_blend_file(filename): with bpy.data.libraries.load(filename) as (data_from, data_to): data_to.objects = [name for name in data_from.objects] for obj in data_to.objects: bpy.context.scene.collection.objects.link(obj)
def reload_avatar(): global mAvt mAvt.load_shape_model() mAvt.eyes = bpy.data.objects['Avatar:High-poly'] mAvt.body = bpy.data.objects['Avatar:Body'] mAvt.skel = bpy.data.objects['Avatar'] mAvt.armature = bpy.data.armatures['Avatar'] mAvt.skel_ref = motion_utils.get_rest_pose(mAvt.skel, mA...
class AVATAR_OT_LoadModel(bpy.types.Operator): bl_idname = 'avt.load_model' bl_label = 'Load human model' bl_description = 'Loads a parametric naked human model' def execute(self, context): global mAvt global avt_path scn = context.scene obj = context.active_object ...
class AVATAR_OT_SetBodyShape(bpy.types.Operator): bl_idname = 'avt.set_body_shape' bl_label = 'Set Body Shape' bl_description = 'Set Body Shape' def execute(self, context): global mAvt obj = mAvt.body cp_vals = obj.data.copy() mAvt.np_mesh_prev = mAvt.read_verts(cp_val...
class AVATAR_OT_ResetParams(bpy.types.Operator): bl_idname = 'avt.reset_params' bl_label = 'Reset Parameters' bl_description = 'Reset original parameters of body shape' def execute(self, context): global mAvt obj = bpy.data.objects['Avatar:Body'] cp_vals = obj.data.copy() ...
class AVATAR_PT_LoadPanel(bpy.types.Panel): bl_idname = 'AVATAR_PT_LoadPanel' bl_label = 'Load model' bl_space_type = 'VIEW_3D' bl_region_type = 'UI' bl_category = 'Avatar' bpy.types.Object.val_breast = FloatProperty(name='Breast Size', description='Breasts Size', default=0, min=0.0, max=1.0, ...
class AVATAR_OT_CreateStudio(bpy.types.Operator): bl_idname = 'avt.create_studio' bl_label = 'Create Studio' bl_description = 'Set up a lighting studio for high quality renderings' def execute(self, context): global avt_path dressing.load_studio(avt_path) return {'FINISHED'}
class AVATAR_OT_WearCloth(bpy.types.Operator): bl_idname = 'avt.wear_cloth' bl_label = 'Wear Cloth' bl_description = 'Dress human with selected cloth' def execute(self, context): global avt_path scn = context.scene obj = context.active_object iconname = bpy.context.sce...
class AVATAR_PT_DressingPanel(bpy.types.Panel): bl_idname = 'AVATAR_PT_DressingPanel' bl_label = 'Dress Human' bl_space_type = 'VIEW_3D' bl_region_type = 'UI' bl_category = 'Avatar' def draw(self, context): layout = self.layout obj = context.object scn = context.scene ...
class AVATAR_OT_SetRestPose(bpy.types.Operator): bl_idname = 'avt.set_rest_pose' bl_label = 'Reset Pose' bl_options = {'REGISTER'} def execute(self, context): global mAvt motion_utils.set_rest_pose(mAvt.skel, mAvt.skel_ref, mAvt.list_bones) mAvt.frame = 1 return {'FINI...
class AVATAR_OT_LoadBVH(bpy.types.Operator): bl_idname = 'avt.load_bvh' bl_label = 'Load BVH' bl_description = 'Transfer motion to human model' filepath: bpy.props.StringProperty(subtype='FILE_PATH') act_x: bpy.props.BoolProperty(name='X') act_y: bpy.props.BoolProperty(name='Y') act_z: bpy...
class AVATAR_PT_MotionPanel(bpy.types.Panel): bl_idname = 'AVATAR_PT_MotionPanel' bl_label = 'Motion' bl_space_type = 'VIEW_3D' bl_region_type = 'UI' bl_category = 'Avatar' bpy.types.Object.bvh_offset = IntProperty(name='Offset', description='Start motion offset', default=0, min=0, max=250) ...
def enum_menu_items(): global avt_path rigs_folder = ('%s/motion/rigs' % avt_path) rigs_names = [f for f in os.listdir(rigs_folder) if f.endswith('.txt')] menu_items = [] i = 0 for rig in rigs_names: i = (i + 1) rigsplit = rig.split('.') name = rigsplit[0] menu_...
def register(): gcoll = bpy.utils.previews.new() gcoll.images_location = ('%s/dressing/cloth_previews' % avt_path) avt_preview_collections['thumbnail_previews'] = gcoll bpy.types.Scene.avt_thumbnails = EnumProperty(items=generate_previews()) bpy.types.Scene.skel_rig = bpy.props.EnumProperty(items=...
def unregister(): from bpy.utils import unregister_class for clas in classes: unregister_class(clas) for gcoll in avt_preview_collections.values(): bpy.utils.previews.remove(gcoll) avt_preview_collections.clear() del bpy.types.Scene.avt_thumbnails del bpy.types.Scene.skel_rig
def read_eigenbody(filename): eigenbody = [] f_eigen = open(filename, 'r') for line in f_eigen: eigenbody.append(float(line)) return np.array(eigenbody)
def compose_vertices_eigenmat(eigenmat): eigenvertices = [] for i in range(0, len(eigenmat), 3): eigenvertices.append([eigenmat[i], (- eigenmat[(i + 2)]), eigenmat[(i + 1)]]) return np.array(eigenvertices)
def get_material_id(name_cloth): idx_list = clthlst.index(name_cloth) return cloth_class[idx_list]
def load_cloth(cloth_file, cloth_name): bpy.ops.import_scene.obj(filepath=cloth_file) bpy.context.selected_objects[0].name = cloth_name bpy.context.selected_objects[0].data.name = cloth_name b = bpy.data.objects[cloth_name] b.select_set(True) bpy.context.view_layer.objects.active = b bpy.o...
def read_file_textures(root_path, fold_name): tex_col = tex_norm = tex_spec = None ftex = open(('%s/dressing/textures/%s/default.txt' % (root_path, fold_name)), 'r') lines = [] for line in ftex: lines.append(line.strip()) ftex.close() num_lines = len(lines) if (num_lines == 1): ...
def load_studio(root_path): s_file = ('%s/dressing/models/studio_plane.obj' % root_path) bpy.ops.import_scene.obj(filepath=s_file) bpy.context.selected_objects[0].name = 'studio_plane' bpy.context.selected_objects[0].data.name = 'studio_plane' for o in bpy.context.scene.objects: if (o.type...
def create_material_generic(matname, index, matid): for m in bpy.data.materials: if ('Default' in m.name): bpy.data.materials.remove(m) mat_name = ('%s_mat%02d' % (matname, index)) skinMat = (bpy.data.materials.get(mat_name) or bpy.data.materials.new(mat_name)) skinMat.pass_index =...
def assign_textures_generic_mat(body, cmat, tex_img, tex_norm, tex_spec): body.select_set(True) if (len(body.material_slots) == 0): bpy.context.view_layer.objects.active = body bpy.ops.object.material_slot_add() body.material_slots[0].material = cmat img_tex_img = img_tex_norm = img_te...
def read_text_lines(filename): list_bones = [] text_file = open(filename, 'r') lines = text_file.readlines() for line in lines: line_split = line.split() if (len(line_split) == 2): list_bones.append([line_split[0], line_split[1]]) else: list_bones.append...
def find_bone_match(list_bones, bone_name): bone_match = 'none' for b in list_bones: if (b[0] == bone_name): bone_match = b[1] break return bone_match
def matrix_scale(scale_vec): return Matrix([[scale_vec[0], 0, 0, 0], [0, scale_vec[1], 0, 0], [0, 0, scale_vec[2], 0], [0, 0, 0, 1]])
def matrix_for_bone_from_parent(bone, ao): eb1 = ao.data.bones[bone.name] E = eb1.matrix_local ebp = ao.data.bones[bone.name].parent E_p = ebp.matrix_local return (E_p.inverted() @ E)
def matrix_the_hard_way(pose_bone, ao): if (pose_bone.rotation_mode == 'QUATERNION'): mr = pose_bone.rotation_quaternion.to_matrix().to_4x4() else: mr = pose_bone.rotation_euler.to_matrix().to_4x4() m1 = ((Matrix.Translation(pose_bone.location) @ mr) @ matrix_scale(pose_bone.scale)) E ...
def worldMatrix(ArmatureObject, Bone): _bone = ArmatureObject.pose.bones[Bone] _obj = ArmatureObject return (_obj.matrix_world * _bone.matrix)
def pose_to_match(arm, goal, bc): '\n pose arm so that its bones line up with the REST pose of goal\n ' matrix_os = {} for bone in arm.data.bones: bone_match = find_bone_match(bc, bone.name) if (bone_match is not 'none'): ebp = goal.pose.bones[bone_match] matr...
def set_rest_pose(skeleton): for bone in skeleton.pose.bones: bone.rotation_mode = 'XYZ' bone.rotation_euler = (0, 0, 0)
def set_hips_origin(skeleton, hips_name): hips_bone = skeleton.pose.bones[hips_name] hips_bone.location = (0, 0, 0)
def find_scale_factor(skel, trg_skel, hips_name_skel, hips_name_target): hips_pos_skel = (skel.matrix_world @ Matrix.Translation(skel.pose.bones[hips_name_skel].head)).to_translation() hips_pos_targ = (trg_skel.matrix_world @ Matrix.Translation(trg_skel.pose.bones[hips_name_target].head)).to_translation() ...
def read_text_lines(filename): list_bones = [] text_file = open(filename, 'r') lines = text_file.readlines() for line in lines: line_split = line.split() if (len(line_split) == 2): list_bones.append([line_split[0], line_split[1]]) else: list_bones.append...
def find_bone_match(list_bones, bone_name): bone_match = 'none' for b in list_bones: if (b[0] == bone_name): bone_match = b[1] break return bone_match
def check_installation(): 'Check whether mmcv-full has been installed successfully.' np_boxes1 = np.asarray([[1.0, 1.0, 3.0, 4.0, 0.5], [2.0, 2.0, 3.0, 4.0, 0.6], [7.0, 7.0, 8.0, 8.0, 0.4]], dtype=np.float32) np_boxes2 = np.asarray([[0.0, 2.0, 2.0, 5.0, 0.3], [2.0, 1.0, 3.0, 3.0, 0.5], [5.0, 5.0, 6.0, 7.0...
class Model(nn.Module): def __init__(self): super(Model, self).__init__() self.conv1 = nn.Conv2d(3, 6, 5) self.pool = nn.MaxPool2d(2, 2) self.conv2 = nn.Conv2d(6, 16, 5) self.fc1 = nn.Linear(((16 * 5) * 5), 120) self.fc2 = nn.Linear(120, 84) self.fc3 = nn.L...
def quantize(arr, min_val, max_val, levels, dtype=np.int64): 'Quantize an array of (-inf, inf) to [0, levels-1].\n\n Args:\n arr (ndarray): Input array.\n min_val (scalar): Minimum value to be clipped.\n max_val (scalar): Maximum value to be clipped.\n levels (int): Quantization lev...
def dequantize(arr, min_val, max_val, levels, dtype=np.float64): 'Dequantize an array.\n\n Args:\n arr (ndarray): Input array.\n min_val (scalar): Minimum value to be clipped.\n max_val (scalar): Maximum value to be clipped.\n levels (int): Quantization levels.\n dtype (np.ty...
class AlexNet(nn.Module): 'AlexNet backbone.\n\n Args:\n num_classes (int): number of classes for classification.\n ' def __init__(self, num_classes=(- 1)): super(AlexNet, self).__init__() self.num_classes = num_classes self.features = nn.Sequential(nn.Conv2d(3, 64, kerne...
@ACTIVATION_LAYERS.register_module(name='Clip') @ACTIVATION_LAYERS.register_module() class Clamp(nn.Module): 'Clamp activation layer.\n\n This activation function is to clamp the feature map value within\n :math:`[min, max]`. More details can be found in ``torch.clamp()``.\n\n Args:\n min (Number ...
class GELU(nn.Module): 'Applies the Gaussian Error Linear Units function:\n\n .. math::\n \\text{GELU}(x) = x * \\Phi(x)\n where :math:`\\Phi(x)` is the Cumulative Distribution Function for\n Gaussian Distribution.\n\n Shape:\n - Input: :math:`(N, *)` where `*` means, any number of addit...
def build_activation_layer(cfg): 'Build activation layer.\n\n Args:\n cfg (dict): The activation layer config, which should contain:\n\n - type (str): Layer type.\n - layer args: Args needed to instantiate an activation layer.\n\n Returns:\n nn.Module: Created activation ...
def last_zero_init(m): if isinstance(m, nn.Sequential): constant_init(m[(- 1)], val=0) else: constant_init(m, val=0)