BodyScan / visualize.py
carsten12's picture
Create visualize.py
50b0701 verified
Raw History Blame Contribute Delete
3.47 kB
import os
import json
import numpy as np
import torch
import trimesh
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from smplx import SMPL
from landmark_definitions import SMPLLandmarks
def load_smpl_mesh(gender, betas=None):
"""
Load an SMPL mesh (vertices and faces) for the given gender.
If betas is provided, shape the model; otherwise use mean (zero) shape.
"""
model = SMPL(model_path='.', gender=gender, ext='pkl')
if betas is None:
betas = torch.zeros((1, 10))
else:
betas = torch.tensor([betas], dtype=torch.float32)
global_orient = torch.zeros((1, 3), dtype=torch.float32)
body_pose = torch.zeros((1, 69), dtype=torch.float32)
transl = torch.zeros((1, 3), dtype=torch.float32)
out = model(betas=betas, global_orient=global_orient, body_pose=body_pose, transl=transl)
verts = out.vertices.detach().cpu().numpy().squeeze()
faces = model.faces
return verts, faces
def visualize_smpl_face_segmentation(gender='female', betas=None):
"""
Visualize SMPL face/body segmentation on the mesh.
"""
verts, faces = load_smpl_mesh(gender, betas)
# Load segmentation JSON (flat path)
seg_file = os.path.join(os.path.dirname(__file__), 'smpl_body_parts_2_faces.json')
with open(seg_file, 'r') as f:
part2faces = json.load(f)
# Prepare face colors
face_colors = np.zeros((faces.shape[0], 3), dtype=np.uint8)
# Assign a random color to each part (just for visualization)
for part_idx, (part_name, face_list) in enumerate(part2faces.items()):
color = np.random.randint(0, 255, size=3, dtype=np.uint8)
face_colors[face_list] = color
# Create mesh and apply face colors
mesh = trimesh.Trimesh(vertices=verts, faces=faces, process=False)
mesh.visual.face_colors = np.concatenate([face_colors, np.full((face_colors.shape[0],1),255,dtype=np.uint8)], axis=1)
# Plot
fig = plt.figure(figsize=(8,6))
ax = fig.add_subplot(111, projection='3d')
# Plot colored mesh
ax.plot_trisurf(mesh.vertices[:, 0], mesh.vertices[:, 1], faces, mesh.vertices[:, 2],
shade=True, facecolors=mesh.visual.face_colors/255.0, linewidth=0.2, antialiased=True)
ax.set_title(f"SMPL {gender.capitalize()} Face Segmentation")
plt.axis('off')
plt.show()
def visualize_smpl_landmarks(gender='female', betas=None):
"""
Visualize SMPL landmarks on the mesh.
"""
verts, faces = load_smpl_mesh(gender, betas)
# Collect landmark points
lm_points = []
lm_names = []
for attr in dir(SMPLLandmarks):
if not attr.startswith("__"):
idx = getattr(SMPLLandmarks, attr)
lm_points.append(verts[idx])
lm_names.append(attr)
lm_points = np.array(lm_points)
# Plot mesh in gray
fig = plt.figure(figsize=(6,6))
ax = fig.add_subplot(111, projection='3d')
mesh = trimesh.Trimesh(vertices=verts, faces=faces, process=False)
ax.plot_trisurf(mesh.vertices[:,0], mesh.vertices[:,1], faces, mesh.vertices[:,2],
color=(0.8,0.8,0.8), alpha=0.5, linewidth=0.1, antialiased=True)
# Plot landmarks
ax.scatter(lm_points[:,0], lm_points[:,1], lm_points[:,2], c='red', s=20)
for i, name in enumerate(lm_names):
ax.text(lm_points[i,0], lm_points[i,1], lm_points[i,2], name, color='black')
ax.set_title(f"SMPL {gender.capitalize()} Landmarks")
plt.axis('off')
plt.show()