Spaces:
Sleeping
Sleeping
File size: 13,132 Bytes
5ac1897 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 |
import os
if 'PYOPENGL_PLATFORM' not in os.environ:
os.environ['PYOPENGL_PLATFORM'] = 'egl'
import torch
import numpy as np
import trimesh
import pyrender
from typing import List, Optional, Union, Tuple
from pathlib import Path
from lib.utils.vis import ColorPalette
from lib.utils.data import to_numpy
from lib.utils.media import save_img
from .utils import *
def render_mesh_overlay_img(
faces : Union[torch.Tensor, np.ndarray],
verts : torch.Tensor,
K4 : List,
img : np.ndarray,
output_fn : Optional[Union[str, Path]] = None,
device : str = 'cuda',
resize : float = 1.0,
Rt : Optional[Tuple[torch.Tensor]] = None,
mesh_color : Optional[Union[List[float], str]] = 'green',
):
'''
Render the mesh overlay on the input video frames.
### Args
- faces: Union[torch.Tensor, np.ndarray], (V, 3)
- verts: torch.Tensor, (V, 3)
- K4: List
- [fx, fy, cx, cy], the components of intrinsic camera matrix.
- img: np.ndarray, (H, W, 3)
- output_fn: Union[str, Path] or None
- The output file path, if None, return the rendered img.
- fps: int, default 30
- device: str, default 'cuda'
- resize: float, default 1.0
- The resize factor of the output video.
- Rt: Tuple of Tensor, default None
- The extrinsic camera matrix, in the form of (R, t).
'''
frame = render_mesh_overlay_video(
faces = faces,
verts = verts[None],
K4 = K4,
frames = img[None],
device = device,
resize = resize,
Rt = Rt,
mesh_color = mesh_color,
)[0]
if output_fn is None:
return frame
else:
save_img(frame, output_fn)
def render_mesh_overlay_video(
faces : Union[torch.Tensor, np.ndarray],
verts : Union[torch.Tensor, np.ndarray],
K4 : List,
frames : np.ndarray,
output_fn : Optional[Union[str, Path]] = None,
fps : int = 30,
device : str = 'cuda',
resize : float = 1.0,
Rt : Tuple = None,
mesh_color : Optional[Union[List[float], str]] = 'green',
):
'''
Render the mesh overlay on the input video frames.
### Args
- faces: Union[torch.Tensor, np.ndarray], (V, 3)
- verts: Union[torch.Tensor, np.ndarray], (L, V, 3)
- K4: List
- [fx, fy, cx, cy], the components of intrinsic camera matrix.
- frames: np.ndarray, (L, H, W, 3)
- output_fn: useless, only for compatibility.
- fps: useless, only for compatibility.
- device: useless, only for compatibility.
- resize: useless, only for compatibility.
- Rt: Tuple, default None
- The extrinsic camera matrix, in the form of (R, t).
'''
faces, verts = to_numpy(faces), to_numpy(verts)
assert len(K4) == 4, 'K4 must be a list of 4 elements.'
assert frames.shape[0] == verts.shape[0], 'The length of frames and verts must be the same.'
assert frames.shape[-1] == 3, 'The last dimension of frames must be 3.'
if isinstance(mesh_color, str):
mesh_color = ColorPalette.presets_float[mesh_color]
# Prepare the data.
L = len(frames)
frame_w, frame_h = frames.shape[-2], frames.shape[-3]
renderer = pyrender.OffscreenRenderer(
viewport_width = frame_w,
viewport_height = frame_h,
point_size = 1.0
)
# Camera
camera, cam_pose = create_camera(K4, Rt)
# Scene.
material = pyrender.MetallicRoughnessMaterial(
metallicFactor = 0.0,
alphaMode = 'OPAQUE',
baseColorFactor = (*mesh_color, 1.0)
)
# Light.
light_nodes = create_raymond_lights()
results = []
for i in range(L):
mesh = trimesh.Trimesh(verts[i].copy(), faces.copy())
# if side_view:
# rot = trimesh.transformations.rotation_matrix(
# np.radians(rot_angle), [0, 1, 0])
# mesh.apply_transform(rot)
# elif top_view:
# rot = trimesh.transformations.rotation_matrix(
# np.radians(rot_angle), [1, 0, 0])
# mesh.apply_transform(rot)
rot = trimesh.transformations.rotation_matrix(
np.radians(180), [1, 0, 0])
mesh.apply_transform(rot)
mesh = pyrender.Mesh.from_trimesh(mesh, material=material)
scene = pyrender.Scene(
bg_color = [0.0, 0.0, 0.0, 0.0],
ambient_light = (0.3, 0.3, 0.3),
)
scene.add(mesh, 'mesh')
scene.add(camera, pose=cam_pose)
# Light.
for node in light_nodes:
scene.add_node(node)
# Render.
result_rgba, rend_depth = renderer.render(scene, flags=pyrender.RenderFlags.RGBA)
valid_mask = result_rgba.astype(np.float32)[:, :, [-1]] / 255.0 # (H, W, 1)
bg = frames[i] # (H, W, 3)
final = result_rgba[:, :, :3] * valid_mask + bg * (1 - valid_mask)
final = final.astype(np.uint8) # (H, W, 3)
results.append(final)
results = np.stack(results, axis=0) # (L, H, W, 3)
renderer.delete()
return results
def render_meshes_overlay_img(
faces_all : Union[torch.Tensor, np.ndarray],
verts_all : Union[torch.Tensor, np.ndarray],
cam_t_all : Union[torch.Tensor, np.ndarray],
K4 : List,
img : np.ndarray,
output_fn : Optional[Union[str, Path]] = None,
device : str = 'cuda',
resize : float = 1.0,
Rt : Optional[Tuple[torch.Tensor]] = None,
mesh_color : Optional[Union[List[float], str]] = 'green',
view : str = 'front',
ret_rgba : bool = False,
):
'''
Render the mesh overlay on the input video frames.
### Args
- faces_all: Union[torch.Tensor, np.ndarray], ((Nm,) V, 3)
- verts_all: Union[torch.Tensor, np.ndarray], ((Nm,) V, 3)
- cam_t_all: Union[torch.Tensor, np.ndarray], ((Nm,) 3)
- K4: List
- [fx, fy, cx, cy], the components of intrinsic camera matrix.
- img: np.ndarray, (H, W, 3)
- output_fn: Union[str, Path] or None
- The output file path, if None, return the rendered img.
- fps: int, default 30
- device: str, default 'cuda'
- resize: float, default 1.0
- The resize factor of the output video.
- Rt: Tuple of Tensor, default None
- The extrinsic camera matrix, in the form of (R, t).
- view: str, default 'front', {'front', 'side90d', 'side60d', 'top90d'}
- ret_rgba: bool, default False
- If True, return rgba images, otherwise return rgb images.
- For view is not 'front', the background will become transparent.
'''
if len(verts_all.shape) == 2:
verts_all = verts_all[None] # (1, V, 3)
elif len(verts_all.shape) == 3:
verts_all = verts_all[:, None] # ((Nm,) 1, V, 3)
else:
raise ValueError('The shape of verts_all is not correct.')
if len(cam_t_all.shape) == 1:
cam_t_all = cam_t_all[None] # (1, 3)
elif len(cam_t_all.shape) == 2:
cam_t_all = cam_t_all[:, None] # ((Nm,) 1, 3)
else:
raise ValueError('The shape of verts_all is not correct.')
frame = render_meshes_overlay_video(
faces_all = faces_all,
verts_all = verts_all,
cam_t_all = cam_t_all,
K4 = K4,
frames = img[None],
device = device,
resize = resize,
Rt = Rt,
mesh_color = mesh_color,
view = view,
ret_rgba = ret_rgba,
)[0]
if output_fn is None:
return frame
else:
save_img(frame, output_fn)
def render_meshes_overlay_video(
faces_all : Union[torch.Tensor, np.ndarray],
verts_all : Union[torch.Tensor, np.ndarray],
cam_t_all : Union[torch.Tensor, np.ndarray],
K4 : List,
frames : np.ndarray,
output_fn : Optional[Union[str, Path]] = None,
fps : int = 30,
device : str = 'cuda',
resize : float = 1.0,
Rt : Tuple = None,
mesh_color : Optional[Union[List[float], str]] = 'green',
view : str = 'front',
ret_rgba : bool = False,
):
'''
Render the mesh overlay on the input video frames.
### Args
- faces_all: Union[torch.Tensor, np.ndarray], ((Nm,) V, 3)
- verts_all: Union[torch.Tensor, np.ndarray], ((Nm,) L, V, 3)
- cam_t_all: Union[torch.Tensor, np.ndarray], ((Nm,) L, 3)
- K4: List
- [fx, fy, cx, cy], the components of intrinsic camera matrix.
- frames: np.ndarray, (L, H, W, 3)
- output_fn: useless, only for compatibility.
- fps: useless, only for compatibility.
- device: useless, only for compatibility.
- resize: useless, only for compatibility.
- Rt: Tuple, default None
- The extrinsic camera matrix, in the form of (R, t).
- view: str, default 'front', {'front', 'side90d', 'side60d', 'top90d'}
- ret_rgba: bool, default False
- If True, return rgba images, otherwise return rgb images.
- For view is not 'front', the background will become transparent.
'''
faces_all, verts_all = to_numpy(faces_all), to_numpy(verts_all)
if len(verts_all.shape) == 3:
verts_all = verts_all[None] # (1, L, V, 3)
if len(cam_t_all.shape) == 2:
cam_t_all = cam_t_all[None] # (1, L, 3)
Nm, L, _, _ = verts_all.shape
if len(faces_all.shape) == 2:
faces_all = faces_all[None].repeat(Nm, axis=0) # (Nm, V, 3)
assert len(K4) == 4, 'K4 must be a list of 4 elements.'
assert frames.shape[0] == L, 'The length of frames and verts must be the same.'
assert frames.shape[-1] == 3, 'The last dimension of frames must be 3.'
assert len(verts_all.shape) == 4, 'The shape of verts_all must be (Nm, L, V, 3).'
assert len(faces_all.shape) == 3, 'The shape of faces_all must be (Nm, V, 3).'
if isinstance(mesh_color, str):
mesh_color = ColorPalette.presets_float[mesh_color]
# Prepare the data.
frame_w, frame_h = frames.shape[-2], frames.shape[-3]
renderer = pyrender.OffscreenRenderer(
viewport_width = frame_w,
viewport_height = frame_h,
point_size = 1.0
)
# Camera
camera, cam_pose = create_camera(K4, Rt)
# Scene.
material = pyrender.MetallicRoughnessMaterial(
metallicFactor = 0.0,
alphaMode = 'OPAQUE',
baseColorFactor = (*mesh_color, 1.0)
)
# Light.
light_nodes = create_raymond_lights()
results = []
for i in range(L):
scene = pyrender.Scene(
bg_color = [0.0, 0.0, 0.0, 0.0],
ambient_light = (0.3, 0.3, 0.3),
)
for mid in range(Nm):
mesh = trimesh.Trimesh(verts_all[mid][i].copy(), faces_all[mid].copy())
if view == 'front':
pass
elif view == 'side90d':
rot = trimesh.transformations.rotation_matrix(np.radians(-90), [0, 1, 0])
mesh.apply_transform(rot)
elif view == 'side60d':
rot = trimesh.transformations.rotation_matrix(np.radians(-60), [0, 1, 0])
mesh.apply_transform(rot)
elif view == 'top90d':
rot = trimesh.transformations.rotation_matrix(np.radians(90), [1, 0, 0])
mesh.apply_transform(rot)
else:
raise ValueError('The view is not supported.')
trans = trimesh.transformations.translation_matrix(to_numpy(cam_t_all[mid][i]))
mesh.apply_transform(trans)
rot = trimesh.transformations.rotation_matrix(np.radians(180), [1, 0, 0])
mesh.apply_transform(rot)
mesh = pyrender.Mesh.from_trimesh(mesh, material=material)
scene.add(mesh, f'mesh_{mid}')
scene.add(camera, pose=cam_pose)
# Light.
for node in light_nodes:
scene.add_node(node)
# Render.
result_rgba, rend_depth = renderer.render(scene, flags=pyrender.RenderFlags.RGBA)
valid_mask = result_rgba.astype(np.float32)[:, :, [-1]] / 255.0 # (H, W, 1)
if view == 'front':
bg = frames[i] # (H, W, 3)
else:
bg = np.ones_like(frames[i]) * 255 # (H, W, 3)
if ret_rgba:
if view == 'front':
bg_alpha = np.ones_like(bg[..., [0]]) * 255 # (H, W, 1)
else:
bg_alpha = np.zeros_like(bg[..., [0]]) * 255 # (H, W, 1)
bg = np.concatenate([bg, bg_alpha], axis=-1) # (H, W, 4)
final = result_rgba * valid_mask + bg * (1 - valid_mask) # (H, W, 4)
else:
final = result_rgba[:, :, :3] * valid_mask + bg * (1 - valid_mask)
final = final.astype(np.uint8) # (H, W, 3)
results.append(final)
results = np.stack(results, axis=0) # (L, H, W, 3)
renderer.delete()
return results
|