B-DoPED / scripts /render_utils.py
1Konny's picture
Initial release: B-DoPED dataset (library + scripts + rendered outputs)
40980f7
Raw
History Blame Contribute Delete
16.9 kB
import yaml
import pickle
from subprocess import run
import numpy as np
import torch
import torch.nn.functional as F
# import smplx
import shutil
import os
from pathlib import Path
import trimesh
import pyrender
import math
import matplotlib.pyplot as plt
import cv2
from contextlib import contextmanager
from PIL import Image
from scipy.spatial.transform import Rotation
def project_keypoints_to_2d(keyp_3d, camera_params, img_size=1024):
"""
Project 3D keypoints to 2D image coordinates using weak perspective camera.
Applies the same transformation as the mesh renderer (180 degree rotation around X-axis).
Uses the same projection matrix as WeakPerspectiveCamera.
Args:
keyp_3d: (N, 3) or (1, N, 3) array of 3D keypoints
camera_params: [sx, sy, tx, ty] camera parameters
img_size: image size (assumes square image)
Returns:
keyp_2d: (N, 2) array of 2D keypoints in image coordinates
"""
if keyp_3d.ndim == 3:
keyp_3d = keyp_3d[0] # (N, 3)
# Apply the same 180-degree rotation around X-axis as in the renderer
# This matches the transformation in _create_mesh_from_trimesh:
# transform = trimesh.transformations.rotation_matrix(math.radians(180), [1, 0, 0])
rot_matrix = np.array([
[1, 0, 0],
[0, -1, 0], # cos(180) = -1, sin(180) = 0
[0, 0, -1]
])
keyp_3d_transformed = keyp_3d @ rot_matrix.T # Apply rotation
sx, sy, tx, ty = camera_params
# Apply projection matrix as in WeakPerspectiveCamera.get_projection_matrix()
# P[0, 0] = sx, P[0, 3] = tx * sx
# P[1, 1] = sy, P[1, 3] = -ty * sy <- Note the negative sign!
x_proj = sx * keyp_3d_transformed[:, 0] + tx * sx
y_proj = sy * keyp_3d_transformed[:, 1] - ty * sy # Negative ty!
# Convert from NDC (normalized device coordinates) [-1, 1] to pixel coordinates [0, img_size]
x_pixel = (x_proj + 1) * img_size / 2
y_pixel = (1 - y_proj) * img_size / 2 # Flip Y for image coordinates
keyp_2d = np.stack([x_pixel, y_pixel], axis=1)
return keyp_2d
def draw_keypoints_on_image(image, keyp_2d, radius=5, color=(255, 0, 0), thickness=-1):
"""
Draw keypoints on image.
Args:
image: (H, W, 3) or (H, W, 4) numpy array
keyp_2d: (N, 2) array of 2D keypoint coordinates
radius: circle radius
color: RGB color tuple
thickness: circle thickness (-1 for filled)
Returns:
image with keypoints drawn
"""
img = np.array(image).copy()
for i, (x, y) in enumerate(keyp_2d):
if 0 <= x < img.shape[1] and 0 <= y < img.shape[0]:
cv2.circle(img, (int(x), int(y)), radius, color, thickness)
# Optional: add keypoint index
# cv2.putText(img, str(i), (int(x)+5, int(y)+5),
# cv2.FONT_HERSHEY_SIMPLEX, 0.3, color, 1)
return img
def show_progress_bar(current, total, description="Processing"):
if total == 0:
return
progress = (current + 1) / total
bar_length = 50
filled_length = int(bar_length * progress)
bar = '#' * filled_length + '-' * (bar_length - filled_length)
percentage = progress * 100
print(f"\r{description}: [{bar}] {percentage:.1f}% ({current + 1}/{total})", end="", flush=True)
if current + 1 == total:
print()
def copy_with_progress_bar(source_path, dest_path, description="Copying"):
if not os.path.exists(source_path):
print(f"Warning: {description} source not found at {source_path}")
return False
# Remove destination if it exists
if os.path.exists(dest_path):
shutil.rmtree(dest_path)
# Create destination directory
os.makedirs(dest_path, exist_ok=True)
if os.path.isdir(source_path):
# Copy directory contents
items = list(Path(source_path).rglob("*"))
files = [item for item in items if item.is_file()]
print(f"{description} {len(files)} files from {source_path} to {dest_path}")
for i, file_path in enumerate(files):
rel_path = file_path.relative_to(source_path)
dest_file = Path(dest_path) / rel_path
dest_file.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(file_path, dest_file)
# Update progress bar
show_progress_bar(i, len(files), description)
return True
else:
# Copy single file
print(f"{description} single file from {source_path} to {dest_path}")
shutil.copy2(source_path, dest_path)
return True
def rsync(src, dst):
run(["rsync", "-a", src, dst], check=True)
def load_yaml(path):
with open(path, 'r') as f:
return yaml.safe_load(f)
def load_pkl(path):
with open(path, 'rb') as file:
return pickle.load(file)
def pitch(): # Positive: down
theta = np.deg2rad(np.random.uniform(-10, 100))
rotation_matrix = np.array([
[1, 0, 0],
[0, np.cos(theta), -np.sin(theta)],
[0, np.sin(theta), np.cos(theta)]
], dtype=np.float32)
return rotation_matrix, theta > np.deg2rad(50)
def yaw(): # Positive: clockwise
theta = np.deg2rad(np.random.uniform(-180, 180))
rotation_matrix = np.array([
[np.cos(theta), 0, -np.sin(-theta)],
[0, 1, 0],
[np.sin(-theta), 0, np.cos(theta)]
], dtype=np.float32)
return rotation_matrix
def roll(theta): # Positive: clockwise
return np.array([
[1, 0, 0],
[0, np.cos(theta), -np.sin(theta)],
[0, np.sin(theta), np.cos(theta)]
], dtype=np.float32)
def rot6d_to_rotmat(rot6d):
assert rot6d.ndim == 2
rot6d = rot6d.view(-1, 3, 2)
a1 = rot6d[:, :, 0]
a2 = rot6d[:, :, 1]
b1 = F.normalize(a1)
b2 = F.normalize(a2 - torch.einsum("bi,bi->b", b1, a2).unsqueeze(-1) * b1)
b3 = torch.linalg.cross(b1, b2)
rotmat = torch.stack((b1, b2, b3), dim=-1)
return rotmat
def create_pose_rotmat(pose, orient):
orient = rot6d_to_rotmat(torch.tensor(orient).reshape(-1, 6)).reshape(1, 3, 3).numpy()
pose = rot6d_to_rotmat(torch.tensor(pose).reshape(-1, 6)).reshape(-1, 3, 3).numpy()
return np.concatenate([orient, pose], axis=0)
def get_bbox(proj):
min_x, min_y = np.min(proj, axis=0)
max_x, max_y = np.max(proj, axis=0)
return (min_x, min_y, max_x, max_y)
# class SMALLayer(smplx.SMPLLayer):
# NUM_JOINTS = 34
# NUM_BODY_JOINTS = 34
# SHAPE_SPACE_DIM = 145
# def __init__(self, *args, **kwargs):
# super().__init__(*args, **kwargs)
# self.vertex_joint_selector.extra_joints_idxs = torch.empty(0, dtype=torch.int32)
def weak_perspective_project(verts, scale, tx, ty):
proj = verts[:, :2] * scale
proj[:, 0] += tx
proj[:, 1] += ty
return proj
def convert_to_pixel_coords(scale, tx, ty, resolution=1024):
tx_px = (tx + 0.5) * resolution
ty_px = (ty + 0.5) * resolution
s_wp = scale * resolution
return s_wp, tx_px, ty_px
def save_vertices_obj(vertices, faces, save_path):
with open(save_path, 'w') as f:
for v in vertices:
f.write(f'v {v[0]} {v[1]} {v[2]}\n')
for face in faces + 1:
f.write(f'f {face[0]} {face[1]} {face[2]}\n')
def deduce_weak_perspective_params(verts, img_size=(1024, 1024), random=False):
"""
Compute weak perspective camera parameters to fit mesh in image.
Args:
verts: (N, 3) vertices
img_size: (width, height) image size
random: if True, add randomness to scale and translation; if False, fit exactly
Returns:
scale, tx, ty: camera parameters
"""
min_x, min_y = verts[:, :2].min(axis=0)
max_x, max_y = verts[:, :2].max(axis=0)
scale_x = img_size[0] / (max_x - min_x)
scale_y = img_size[1] / (max_y - min_y)
scale = min(scale_x, scale_y)
scale *= 0.9
if random:
scale *= np.random.uniform(0.9, 1.0)
scaled_width = scale * (max_x - min_x)
scaled_height = scale * (max_y - min_y)
tx_min = 0 - scale * min_x
tx_max = img_size[0] - scale * max_x
ty_min = 0 - scale * min_y
ty_max = img_size[1] - scale * max_y
if random:
tx = np.random.uniform(tx_min, tx_max)
ty_mid = (ty_min + ty_max) / 2
ty = np.random.uniform(ty_mid, ty_max)
else:
# Center the mesh perfectly
tx = (tx_min + tx_max) / 2
ty = (ty_min + ty_max) / 2
return scale, tx, ty
class WeakPerspectiveCamera(pyrender.Camera):
def __init__(self, scale, translation, znear=10.0, zfar=1000.0):
super().__init__(znear=znear, zfar=zfar)
self.scale = np.asarray(scale, dtype=float).ravel()[:2]
self.translation = np.asarray(translation, dtype=float).ravel()[:2]
def get_projection_matrix(self, width=None, height=None):
P = np.eye(4)
sx, sy = self.scale
tx, ty = self.translation
P[0, 0] = sx
P[1, 1] = sy
P[0, 3] = tx * sx
P[1, 3] = -ty * sy
P[2, 2] = -0.1
return P
class MeshRenderer:
def __init__(self, faces=None, resolution=(1024, 1024), randomize_light_orientation=False):
self.faces = faces
self.resolution = resolution
self.randomize_light_orientation = randomize_light_orientation
self.renderer = pyrender.OffscreenRenderer(*resolution)
self.scene = pyrender.Scene(
bg_color=[0, 0, 0, 0],
ambient_light=(0.5, 0.5, 0.5)
)
self.light_nodes = []
self._setup_lights(randomize_orientation=randomize_light_orientation)
def _setup_lights(self, randomize_orientation=False):
# Remove existing lights first
for node in self.light_nodes:
self.scene.remove_node(node)
self.light_nodes = []
# Base directions for directional lights (pointing towards origin)
# DirectionalLight shines along its local -Z axis, so we create rotations
# that point the light from different directions
base_directions = np.array([
[0, -1, 1], # from above-front
[0, 1, 1], # from above-back
[1, 1, 2], # from above-right-back
], dtype=np.float64)
# Normalize to get unit direction vectors
base_directions = base_directions / np.linalg.norm(base_directions, axis=1, keepdims=True)
if randomize_orientation:
# Apply random 3D rotation to all light directions
random_rotation = Rotation.random()
directions = random_rotation.apply(base_directions)
else:
directions = base_directions
light = pyrender.DirectionalLight(color=[1.0, 1.0, 1.0], intensity=0.8)
for direction in directions:
# Create rotation matrix that aligns -Z axis with the light direction
# Light shines along -Z in its local frame, so we want -Z to point along 'direction'
# This means Z should point along '-direction'
z_axis = -direction # The light's Z axis (opposite of light direction)
# Create orthonormal basis
# Pick an arbitrary vector not parallel to z_axis for cross product
up = np.array([0, 1, 0]) if abs(z_axis[1]) < 0.9 else np.array([1, 0, 0])
x_axis = np.cross(up, z_axis)
x_axis = x_axis / np.linalg.norm(x_axis)
y_axis = np.cross(z_axis, x_axis)
# Build rotation matrix (columns are the local axes in world coordinates)
pose = np.eye(4)
pose[:3, 0] = x_axis
pose[:3, 1] = y_axis
pose[:3, 2] = z_axis
node = self.scene.add(light, pose=pose)
self.light_nodes.append(node)
def _calculate_surface_normals(self, vertices, faces):
normals = np.cross(
vertices[faces[:, 1]] - vertices[faces[:, 0]],
vertices[faces[:, 2]] - vertices[faces[:, 1]]
)
normals /= np.linalg.norm(normals, axis=1)[:, None]
return (normals + 1) / 2 * 255
def _create_mesh_from_vertices(self, vertices, color=None):
"""Create mesh from vertices and faces (legacy method)"""
mesh = trimesh.Trimesh(vertices=vertices, faces=self.faces, process=False)
mesh = mesh.subdivide_loop(iterations=2)
transform = trimesh.transformations.rotation_matrix(math.radians(180), [1, 0, 0])
mesh.apply_transform(transform)
if color is not None:
material = pyrender.MetallicRoughnessMaterial(
baseColorFactor=[*color, 1.0],
metallicFactor=0.1,
alphaMode="OPAQUE"
)
return pyrender.Mesh.from_trimesh(mesh, material=material, smooth=True)
else:
normals = self._calculate_surface_normals(mesh.vertices, mesh.faces)
mesh.visual.face_colors = normals.astype(np.uint8)
return pyrender.Mesh.from_trimesh(mesh, material=None, smooth=False)
def _create_mesh_from_trimesh(self, trimesh_obj, color=None):
"""Create mesh from a trimesh object (supports textures)"""
mesh = trimesh_obj.copy()
# Check if mesh has texture - if so, don't subdivide as it breaks UV coordinates
has_texture = hasattr(mesh.visual, 'uv') and mesh.visual.uv is not None
if not has_texture:
mesh = mesh.subdivide_loop(iterations=2)
transform = trimesh.transformations.rotation_matrix(math.radians(180), [1, 0, 0])
mesh.apply_transform(transform)
if color is not None:
# Override with solid color
material = pyrender.MetallicRoughnessMaterial(
baseColorFactor=[*color, 1.0],
metallicFactor=0.1,
alphaMode="OPAQUE"
)
return pyrender.Mesh.from_trimesh(mesh, material=material, smooth=True)
else:
# Use existing visual (texture or vertex colors)
# pyrender automatically handles TextureVisuals from trimesh
return pyrender.Mesh.from_trimesh(mesh, smooth=True)
def render(self, mesh_or_vertices, camera_params, color=None, depth_only=False):
"""
Render a mesh with camera parameters.
Args:
mesh_or_vertices: Either a trimesh.Trimesh object or numpy array of vertices
camera_params: Camera parameters [sx, sy, tx, ty]
color: Optional color override (R, G, B) in [0, 1]
depth_only: If True, only return depth map
"""
# Randomize light orientation on each render call if enabled
if self.randomize_light_orientation:
self._setup_lights(randomize_orientation=True)
# Determine if input is a trimesh object or vertices array
if isinstance(mesh_or_vertices, trimesh.Trimesh):
pyrender_mesh = self._create_mesh_from_trimesh(mesh_or_vertices, color)
else:
# Assume it's a vertices array
pyrender_mesh = self._create_mesh_from_vertices(mesh_or_vertices, color)
mesh_node = self.scene.add(pyrender_mesh)
cam = WeakPerspectiveCamera(scale=camera_params[:2], translation=camera_params[2:])
cam_node = self.scene.add(cam, pose=np.eye(4))
if depth_only:
depth = self.renderer.render(self.scene, flags=pyrender.RenderFlags.DEPTH_ONLY)
self.scene.remove_node(mesh_node); self.scene.remove_node(cam_node)
return depth
img_rgba, depth = self.renderer.render(self.scene, flags=pyrender.RenderFlags.RGBA)
# Make a writable copy since pyrender returns read-only arrays
img_rgba = img_rgba.copy()
alpha = (depth > 0).astype(np.uint8) * 255
img_rgba[..., 3] = alpha
self.scene.remove_node(mesh_node); self.scene.remove_node(cam_node)
return img_rgba
def overlay_rgba_on_rgb(rendered_rgba, background_rgb):
fg = Image.fromarray(rendered_rgba, mode="RGBA")
bg = Image.fromarray(background_rgb, mode="RGB")
if fg.size != bg.size:
bg = bg.resize(fg.size, resample=Image.BILINEAR)
out = Image.alpha_composite(bg.convert("RGBA"), fg)
return np.array(out.convert("RGB"))