Datasets:
Download scripts/smal_utils.py from 1Konny/B-DoPED: direct link, hf CLI and curl.
- Browser
- Download file 13 kB
-
https://huggingface.co/datasets/1Konny/B-DoPED/resolve/main/scripts/smal_utils.py
- Command line
-
hf download hf://datasets/1Konny/B-DoPED/scripts/smal_utils.py
-
curl -L -o smal_utils.py https://huggingface.co/datasets/1Konny/B-DoPED/resolve/main/scripts/smal_utils.py
13 kB
| import torch | |
| import numpy as np | |
| import trimesh | |
| import inspect | |
| import os | |
| import sys | |
| if not hasattr(inspect, 'getargspec'): | |
| inspect.getargspec = inspect.getfullargspec | |
| # chumpy-pickled SMAL models reference removed numpy aliases; restore them. | |
| for name, alias in [('bool', np.bool_), ('int', np.int_), ('float', np.float64), ('complex', np.complex128), ('object', np.object_), ('str', np.str_), ('unicode', str)]: | |
| if not hasattr(np, name): | |
| setattr(np, name, alias) | |
| # Locate the BITE checkout (code + SMAL weights). Override with BITE_ROOT env var | |
| # (render_smal_multiview.py --bite-root sets it); default to ./bite_gradio-hf in cwd | |
| # or alongside this file. | |
| def _resolve_bite_root(): | |
| env = os.environ.get('BITE_ROOT') | |
| if env: | |
| return os.path.abspath(env) | |
| here = os.path.dirname(os.path.abspath(__file__)) | |
| for cand in [os.path.join(os.getcwd(), 'bite_gradio-hf'), | |
| os.path.join(here, 'bite_gradio-hf'), | |
| os.path.join(here, '..', 'bite_gradio-hf')]: | |
| if os.path.isdir(os.path.join(cand, 'src')): | |
| return os.path.abspath(cand) | |
| return os.path.abspath(os.path.join(os.getcwd(), 'bite_gradio-hf')) | |
| BITE_ROOT = _resolve_bite_root() | |
| sys.path.insert(0, os.path.join(BITE_ROOT, 'src')) | |
| from smal_pytorch.smal_model.smal_torch_new import SMAL | |
| from configs.SMAL_configs import SMAL_MODEL_CONFIG | |
| from lifting_to_3d.utils.geometry_utils import rot6d_to_rotmat, rotmat_to_rot6d | |
| def get_optimized_pose_with_glob(orient_6d, pose_6d): | |
| """Convert 6D rotation representation to rotation matrices for SMAL.""" | |
| batch_size = orient_6d.shape[0] | |
| orient_rotmat = rot6d_to_rotmat(orient_6d.reshape(-1, 6)).reshape(batch_size, 1, 3, 3) | |
| pose_rotmat = rot6d_to_rotmat(pose_6d.reshape(-1, 6)).reshape(batch_size, 34, 3, 3) | |
| return torch.cat([orient_rotmat, pose_rotmat], dim=1) | |
| def initialize_smal_model( | |
| keyp_conf='red', | |
| output_obj_path=None, | |
| output_npz_path=None, | |
| output_skeleton_path=None, | |
| beta=None, | |
| betas_limbs=None, | |
| pose_6d=None, | |
| orient_6d=None, | |
| vert_off_compact=None, | |
| trans=None, | |
| logscale_part_list=None, | |
| uvmap_image=None, | |
| xatlas_params=None, | |
| ): | |
| """ | |
| Initialize SMAL model in rest pose and save as OBJ file. | |
| """ | |
| # Set device | |
| device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') | |
| # SMAL model configuration | |
| smal_model_type = '39dogs_norm' # or '39dogs' depending on your needs | |
| logscale_part_list = SMAL_MODEL_CONFIG[smal_model_type]['logscale_part_list'] if logscale_part_list is None else logscale_part_list | |
| # Initialize SMAL model | |
| smal = SMAL( | |
| smal_model_type=smal_model_type, | |
| template_name='neutral', | |
| logscale_part_list=logscale_part_list | |
| ).to(device) | |
| beta_init = torch.zeros(1, 30).to(device) | |
| # betas_limbs_init = torch.zeros(1, 7).to(device) | |
| betas_limbs_init = torch.zeros(1, len(logscale_part_list)).to(device) | |
| identity_3x3 = torch.eye(3, device=device, dtype=torch.float32) | |
| identity_6d = rotmat_to_rot6d(identity_3x3.unsqueeze(0)) | |
| pose_6d_init = identity_6d.unsqueeze(0).repeat(1, 34, 1) | |
| orient_6d_init = identity_6d.unsqueeze(0).repeat(1, 1, 1) | |
| vert_off_compact_init = torch.zeros(1, 2*smal.n_center + 3*smal.n_left).to(device) | |
| trans_init = torch.zeros(1, 3).to(device) | |
| if beta is not None: | |
| beta_init = beta.to(device) | |
| if betas_limbs is not None: | |
| betas_limbs_init = betas_limbs.to(device) | |
| if pose_6d is not None: | |
| pose_6d = pose_6d.to(device) | |
| else: | |
| pose_6d = pose_6d_init | |
| if orient_6d is not None: | |
| orient_6d = orient_6d.to(device) | |
| else: | |
| orient_6d = orient_6d_init | |
| if vert_off_compact is not None: | |
| vert_off_compact_init = vert_off_compact.to(device) | |
| if trans is not None: | |
| trans_init = trans.to(device) | |
| pose_init = get_optimized_pose_with_glob(orient_6d, pose_6d) | |
| with torch.no_grad(): | |
| # Use default parameters for rest pose | |
| smal_verts, keyp_3d, _ = smal( | |
| beta=beta_init, # Shape parameters (neutral) | |
| betas_limbs=betas_limbs_init, # Limb parameters (neutral) | |
| pose=pose_init, # Rest pose (identity rotations) | |
| vert_off_compact=vert_off_compact_init, # No vertex offsets | |
| trans=trans_init, # No translation | |
| keyp_conf=keyp_conf, | |
| get_skin=True | |
| ) | |
| # Convert to numpy and create trimesh | |
| vertices = smal_verts[0].detach().cpu().numpy() | |
| faces = smal.faces.detach().cpu().numpy() | |
| # Save mesh and parameters | |
| mesh = trimesh.Trimesh(vertices=vertices, faces=faces, process=False, maintain_order=True) | |
| if xatlas_params is not None: | |
| mesh.vertices = mesh.vertices[xatlas_params['vmapping']] | |
| mesh.faces = xatlas_params['faces'] | |
| mesh.visual.uv = xatlas_params['uvs'] | |
| if uvmap_image is not None: | |
| # apply texture to mesh | |
| material = trimesh.visual.texture.SimpleMaterial( | |
| image=uvmap_image, diffuse=(255, 255, 255) | |
| ) | |
| texture_visuals = trimesh.visual.TextureVisuals( | |
| uv=mesh.visual.uv, image=uvmap_image, material=material | |
| ) | |
| mesh.visual = texture_visuals | |
| if output_obj_path is not None: | |
| output_obj_path.parent.mkdir(parents=True, exist_ok=True) | |
| mesh.export(file_obj=output_obj_path) | |
| if output_npz_path is not None: | |
| output_npz_path.parent.mkdir(parents=True, exist_ok=True) | |
| np.savez_compressed(output_npz_path, | |
| beta=beta_init.data.cpu().numpy(), | |
| betas_limbs=betas_limbs_init.data.cpu().numpy(), | |
| pose_6d=pose_6d.data.cpu().numpy(), | |
| orient_6d=orient_6d.data.cpu().numpy(), | |
| pose=pose_init.data.cpu().numpy(), | |
| vert_off_compact=vert_off_compact_init.data.cpu().numpy(), | |
| trans=trans_init.data.cpu().numpy(), | |
| keyp_conf=keyp_conf, | |
| ) | |
| skeleton_mesh = None | |
| if output_skeleton_path is not None: | |
| from utils import create_skeleton_visualization # optional; only for skeleton export | |
| skeleton_mesh = create_skeleton_visualization( | |
| keyp_3d.cpu().numpy(), | |
| smal.parents, | |
| sphere_radius=0.02, | |
| line_radius=0.005, | |
| ) | |
| skeleton_mesh.export(file_obj=output_skeleton_path) | |
| output = {} | |
| output['mesh'] = mesh | |
| output['skeleton_mesh'] = skeleton_mesh | |
| output['parents'] = smal.parents | |
| output['vertices'] = vertices | |
| output['faces'] = faces | |
| output['keyp_3d'] = keyp_3d | |
| output['beta'] = beta_init | |
| output['betas_limbs'] = betas_limbs_init | |
| output['pose_6d'] = pose_6d | |
| output['orient_6d'] = orient_6d | |
| output['vert_off_compact'] = vert_off_compact_init | |
| output['trans'] = trans_init | |
| output['keyp_conf'] = keyp_conf | |
| output['logscale_part_list'] = logscale_part_list | |
| output['smal_model_type'] = smal_model_type | |
| output['uvmap_image'] = uvmap_image | |
| output['xatlas_params'] = xatlas_params | |
| return output | |
| def initialize_smal_model_batch( | |
| keyp_conf='red', | |
| beta_batch=None, # (B, 30) | |
| betas_limbs_batch=None, # (B, 7) or (B, num_limbs) | |
| pose_6d_batch=None, # (B, 34, 6) | |
| orient_6d_batch=None, # (B, 1, 6) | |
| vert_off_compact_batch=None, # (B, vert_dim) | |
| trans_batch=None, # (B, 3) | |
| logscale_part_list=None, # shared across batch | |
| uvmap_image_list=None, # list of B PIL images or None | |
| xatlas_params_list=None, # list of B xatlas param dicts or None | |
| ): | |
| """ | |
| Initialize SMAL model in batch mode for faster processing. | |
| All batch inputs should have the same batch size B. | |
| Optionally applies texture to each mesh if uvmap_image_list and xatlas_params_list are provided. | |
| """ | |
| # Set device | |
| device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') | |
| # SMAL model configuration | |
| smal_model_type = '39dogs_norm' | |
| logscale_part_list = SMAL_MODEL_CONFIG[smal_model_type]['logscale_part_list'] if logscale_part_list is None else logscale_part_list | |
| # Initialize SMAL model once | |
| smal = SMAL( | |
| smal_model_type=smal_model_type, | |
| template_name='neutral', | |
| logscale_part_list=logscale_part_list | |
| ).to(device) | |
| # Determine batch size from inputs | |
| batch_size = None | |
| for tensor in [beta_batch, betas_limbs_batch, pose_6d_batch, orient_6d_batch]: | |
| if tensor is not None: | |
| batch_size = tensor.shape[0] | |
| break | |
| if batch_size is None: | |
| batch_size = 1 | |
| # Initialize default values | |
| identity_3x3 = torch.eye(3, device=device, dtype=torch.float32) | |
| identity_6d = rotmat_to_rot6d(identity_3x3.unsqueeze(0)) | |
| # Prepare batch inputs with defaults | |
| if beta_batch is not None: | |
| beta_batch = beta_batch.to(device) | |
| else: | |
| beta_batch = torch.zeros(batch_size, 30).to(device) | |
| if betas_limbs_batch is not None: | |
| betas_limbs_batch = betas_limbs_batch.to(device) | |
| else: | |
| betas_limbs_batch = torch.zeros(batch_size, len(logscale_part_list)).to(device) | |
| if pose_6d_batch is not None: | |
| pose_6d_batch = pose_6d_batch.to(device) | |
| else: | |
| pose_6d_batch = identity_6d.unsqueeze(0).repeat(batch_size, 34, 1) | |
| if orient_6d_batch is not None: | |
| orient_6d_batch = orient_6d_batch.to(device) | |
| else: | |
| orient_6d_batch = identity_6d.unsqueeze(0).repeat(batch_size, 1, 1) | |
| if vert_off_compact_batch is not None: | |
| vert_off_compact_batch = vert_off_compact_batch.to(device) | |
| else: | |
| vert_off_compact_batch = torch.zeros(batch_size, 2*smal.n_center + 3*smal.n_left).to(device) | |
| if trans_batch is not None: | |
| trans_batch = trans_batch.to(device) | |
| else: | |
| trans_batch = torch.zeros(batch_size, 3).to(device) | |
| # Convert 6D rotations to rotation matrices for the entire batch | |
| # orient_6d_batch: (B, 1, 6) -> (B, 1, 3, 3) | |
| # pose_6d_batch: (B, 34, 6) -> (B, 34, 3, 3) | |
| orient_rotmat = rot6d_to_rotmat(orient_6d_batch.reshape(-1, 6)).reshape(batch_size, 1, 3, 3) | |
| pose_rotmat = rot6d_to_rotmat(pose_6d_batch.reshape(-1, 6)).reshape(batch_size, 34, 3, 3) | |
| pose_batch = torch.cat([orient_rotmat, pose_rotmat], dim=1) # (B, 35, 3, 3) | |
| with torch.no_grad(): | |
| # Batch forward pass | |
| smal_verts, keyp_3d, _ = smal( | |
| beta=beta_batch, | |
| betas_limbs=betas_limbs_batch, | |
| pose=pose_batch, | |
| vert_off_compact=vert_off_compact_batch, | |
| trans=trans_batch, | |
| keyp_conf=keyp_conf, | |
| get_skin=True | |
| ) | |
| # Convert to numpy and create trimesh objects for each sample | |
| vertices_batch = smal_verts.detach().cpu().numpy() # (B, V, 3) | |
| faces = smal.faces.detach().cpu().numpy() | |
| keyp_3d_batch = keyp_3d.detach().cpu() # (B, J, 3) | |
| # Create output list | |
| outputs = [] | |
| for i in range(batch_size): | |
| vertices = vertices_batch[i] | |
| mesh = trimesh.Trimesh(vertices=vertices, faces=faces, process=False, maintain_order=True) | |
| # Get texture params for this sample | |
| xatlas_params = xatlas_params_list[i] if xatlas_params_list is not None else None | |
| uvmap_image = uvmap_image_list[i] if uvmap_image_list is not None else None | |
| # Apply xatlas remapping if available | |
| if xatlas_params is not None: | |
| mesh.vertices = mesh.vertices[xatlas_params['vmapping']] | |
| mesh.faces = xatlas_params['faces'] | |
| mesh.visual.uv = xatlas_params['uvs'] | |
| # Apply texture if available | |
| if uvmap_image is not None: | |
| material = trimesh.visual.texture.SimpleMaterial( | |
| image=uvmap_image, diffuse=(255, 255, 255) | |
| ) | |
| texture_visuals = trimesh.visual.TextureVisuals( | |
| uv=mesh.visual.uv, image=uvmap_image, material=material | |
| ) | |
| mesh.visual = texture_visuals | |
| output = {} | |
| output['mesh'] = mesh | |
| output['skeleton_mesh'] = None | |
| output['parents'] = smal.parents | |
| output['vertices'] = vertices | |
| output['faces'] = faces | |
| output['keyp_3d'] = keyp_3d_batch[i:i+1] # Keep as (1, J, 3) for compatibility | |
| output['beta'] = beta_batch[i:i+1] | |
| output['betas_limbs'] = betas_limbs_batch[i:i+1] | |
| output['pose_6d'] = pose_6d_batch[i:i+1] | |
| output['orient_6d'] = orient_6d_batch[i:i+1] | |
| output['vert_off_compact'] = vert_off_compact_batch[i:i+1] | |
| output['trans'] = trans_batch[i:i+1] | |
| output['keyp_conf'] = keyp_conf | |
| output['logscale_part_list'] = logscale_part_list | |
| output['smal_model_type'] = smal_model_type | |
| output['uvmap_image'] = uvmap_image | |
| output['xatlas_params'] = xatlas_params | |
| outputs.append(output) | |
| return outputs |