ViDiHand2 / utils /visualizer.py
WANG-XIXI's picture
ViDiHand2 demo
567da96
Raw History Blame Contribute Delete
11 kB
"""Overlays of predicted hands on video frames: MANO meshes (nvdiffrast on the GPU, or a CPU rasteriser) and joint skeletons."""
import warnings
import cv2
import numpy as np
import torch
from utils.mano import ManoModel
try:
import nvdiffrast.torch as dr
except ImportError:
dr = None
COLOURS = ( # per side (left, right), the colour of each joint in the MANO order
((176, 196, 222), (0, 95, 158), (0, 130, 216), (72, 182, 255), (0, 26, 158), (0, 36, 216), (72, 102, 255),
(105, 0, 158), (144, 0, 216), (194, 72, 255), (37, 0, 158), (50, 0, 216), (115, 72, 255), (0, 158, 158),
(0, 216, 216), (72, 255, 255), (153, 255, 255), (153, 214, 255), (153, 170, 255), (177, 153, 255), (221, 153, 255)),
((255, 255, 255), (158, 79, 0), (216, 108, 0), (255, 164, 72), (158, 158, 0), (216, 216, 0), (255, 255, 72),
(0, 158, 53), (0, 216, 72), (72, 255, 133), (53, 158, 0), (72, 216, 0), (133, 255, 72), (158, 0, 0),
(216, 0, 0), (255, 72, 72), (255, 153, 153), (255, 204, 153), (255, 255, 153), (187, 255, 153), (153, 255, 187)),
)
TINTS = (np.array((0.25, 0.60, 1.00)), np.array((1.00, 0.55, 0.20))) # mesh tint per side (left, right)
GPU_CHUNK_PIXELS = 32_000_000 # pixels rasterised per GPU batch of frames
def _project(points, K):
"""Pixel coordinates of camera-space points."""
uvw = points @ K.T
return uvw[..., :2] / uvw[..., 2:]
def _vertex_colours(mesh, faces, side):
"""Per-vertex colours of a mesh: its normals as colours, tinted by side."""
normals = np.zeros_like(mesh)
face_normals = np.cross(mesh[faces[:, 1]] - mesh[faces[:, 0]], mesh[faces[:, 2]] - mesh[faces[:, 0]])
for corner in range(3):
np.add.at(normals, faces[:, corner], face_normals)
normals /= np.maximum(np.linalg.norm(normals, axis=-1, keepdims=True), 1e-12)
colours = 0.5 + 0.5 * normals
if side == 0:
colours[:, 2] = 1.0 - colours[:, 2]
return np.clip(colours * 0.6 + TINTS[side] * 0.4, 0, 1)
class Visualizer:
"""Renders MANO meshes (`render_mano`) and joints (`render_joints`) of a prediction over its video, returning new frames."""
def __init__(self, backend="gpu"):
if backend not in ("cpu", "gpu"):
raise ValueError("backend must be gpu or cpu")
self._mano = self._context = None
if backend == "gpu":
try: # nvdiffrast builds its CUDA kernels on first use (needs the CUDA toolkit); any failure falls back to the cpu
if dr is None or not torch.cuda.is_available():
raise RuntimeError("nvdiffrast or CUDA missing")
self._device = torch.device("cuda", torch.cuda.current_device())
with warnings.catch_warnings(): # nvdiffrast builds for the visible GPUs on purpose; torch warns about that
warnings.filterwarnings("ignore", message="TORCH_CUDA_ARCH_LIST is not set")
self._context = dr.RasterizeCudaContext(device=self._device)
except Exception as error:
warnings.warn(f"Visualizer: gpu backend unavailable ({error}), rendering on the cpu")
backend = "cpu"
self.backend = backend
def render_mano(self, mano, video, K):
"""Frames with the valid hands' MANO meshes drawn over them."""
if self._mano is None:
self._mano = ManoModel()
vertices = self._mano.mano2mesh(mano)
if self.backend == "gpu":
return self._render_gpu(vertices, np.asarray(mano["valid"], bool), video, K)
output = np.array(video, copy=True)
for t, image in enumerate(output):
meshes = []
for side in (0, 1):
if mano["valid"][t, side]:
faces = self._mano.faces if side else self._mano.faces[:, [0, 2, 1]]
mesh = vertices[t, side].astype(np.float64)
meshes.append((mesh, faces[(mesh[faces, 2] > 1e-7).all(-1)], side))
if meshes:
output[t] = self._draw_cpu(image, meshes, K[t])
return output
@staticmethod
def _draw_cpu(image, meshes, K):
"""Rasterises meshes (vertices, faces, side) into one image with a z-buffer and perspective-correct colours."""
height, width = image.shape[:2]
vertices, triangles, colours, offset = [], [], [], 0
for mesh, faces, side in meshes:
vertices.append(mesh)
triangles.append(faces + offset)
colours.append(_vertex_colours(mesh, faces, side))
offset += len(mesh)
vertices, triangles, colours = np.concatenate(vertices), np.concatenate(triangles), np.concatenate(colours)
corners = _project(vertices, K)[triangles]
(x0, y0), (x1, y1), (x2, y2) = (corners[:, k].T for k in range(3))
area = (y1 - y2) * (x0 - x2) + (x2 - x1) * (y0 - y2)
keep = np.abs(area) > 1e-10
triangles, corners, area = triangles[keep], corners[keep], area[keep]
low = np.clip(np.ceil(corners.min(1) - 0.5), 0, [width, height]).astype(np.int64)
high = np.clip(np.floor(corners.max(1) - 0.5), -1, [width - 1, height - 1]).astype(np.int64)
size = np.maximum(high - low + 1, 0)
count = size[:, 0] * size[:, 1]
face = np.repeat(np.arange(len(triangles)), count)
if not len(face):
return image
local = np.arange(len(face)) - np.repeat(np.cumsum(count) - count, count)
x = low[face, 0] + local % size[face, 0]
y = low[face, 1] + local // size[face, 0]
(x0, y0), (x1, y1), (x2, y2) = (corners[face, k].T for k in range(3))
first = ((y1 - y2) * (x + 0.5 - x2) + (x2 - x1) * (y + 0.5 - y2)) / area[face]
second = ((y2 - y0) * (x + 0.5 - x2) + (x0 - x2) * (y + 0.5 - y2)) / area[face]
barycentric = np.stack((first, second, 1 - first - second), -1)
inside = (barycentric >= 0).all(-1)
face, x, y, barycentric = face[inside], x[inside], y[inside], barycentric[inside]
weighted = barycentric / vertices[triangles[face], 2]
depth = 1.0 / weighted.sum(-1)
pixel = y * width + x
order = np.lexsort((depth, pixel))
keep = order[np.unique(pixel[order], return_index=True)[1]]
colour = np.einsum("nk,nkc->nc", weighted[keep], colours[triangles[face[keep]]]) * depth[keep, None]
image[y[keep], x[keep]] = np.rint(np.clip(colour, 0, 1) * 255).astype(np.uint8)
return image
def _render_gpu(self, vertices, valid, video, K):
"""render_mano with nvdiffrast, in batches of frames."""
device = self._device
faces = torch.as_tensor(self._mano.faces.astype(np.int64), device=device)
sided = (faces[:, [0, 2, 1]], faces)
triangles = torch.cat((sided[0], sided[1] + vertices.shape[2])).int()
tints = torch.as_tensor(np.stack(TINTS), device=device)
output = np.array(video, copy=True)
height, width = output.shape[1:3]
chunk = max(1, GPU_CHUNK_PIXELS // (height * width))
for start in range(0, len(output), chunk):
stop = min(start + chunk, len(output))
keep = torch.as_tensor(valid[start:stop] & np.isfinite(vertices[start:stop]).all((-1, -2)), device=device)
if not keep.any():
continue
mesh = torch.as_tensor(np.nan_to_num(vertices[start:stop].astype(np.float64)), device=device)
colours = []
for side in (0, 1):
corner = mesh[:, side][:, sided[side]]
face_normals = torch.cross(corner[:, :, 1] - corner[:, :, 0], corner[:, :, 2] - corner[:, :, 0], dim=-1)
normals = torch.zeros_like(mesh[:, side])
for k in range(3):
normals.index_add_(1, sided[side][:, k], face_normals)
normals = normals / normals.norm(dim=-1, keepdim=True).clamp_min(1e-12)
colour = 0.5 + 0.5 * normals
if side == 0:
colour[..., 2] = 1.0 - colour[..., 2]
colours.append((colour * 0.6 + tints[side] * 0.4).clamp(0, 1))
z = mesh[..., 2]
seen = torch.where(keep[..., None], z, torch.nan).flatten(1)
near = (seen.nan_to_num(torch.inf).amin(1) * 0.5).clamp_min(1e-7)[:, None, None]
far = (seen.nan_to_num(-torch.inf).amax(1) * 2.0)[:, None, None]
k = torch.as_tensor(K[start:stop], device=device)
uvw = mesh @ k[:, None].transpose(-1, -2)
positions = torch.stack((2 * uvw[..., 0] / width - z, 2 * uvw[..., 1] / height - z,
(far + near) / (far - near) * z - 2 * far * near / (far - near), z), -1)
positions = torch.where(keep[..., None, None], positions, positions.new_tensor((0.0, 0.0, 0.0, -1.0)))
frames = torch.as_tensor(output[start:stop], device=device)
with torch.no_grad():
raster, _ = dr.rasterize(self._context, positions.flatten(1, 2).float().contiguous(), triangles,
resolution=[height, width])
colour, _ = dr.interpolate(torch.cat(colours, 1).float().contiguous(), raster, triangles)
frames = torch.where(raster[..., 3:] > 0, (colour.clamp(0, 1) * 255).round().to(torch.uint8), frames)
output[start:stop] = frames.cpu().numpy()
return output
def render_joints(self, joints, video, K):
"""Frames with the valid hands' joints and bones drawn over them."""
output = np.array(video, copy=True)
for t, image in enumerate(output):
pixels = np.zeros((2, 21, 2), np.int32)
visible = np.zeros((2, 21), bool)
for side in (0, 1):
if not joints["valid"][t, side]:
continue
points = np.asarray(joints["joints3d"][t, side], np.float64)
good = np.isfinite(points).all(-1) & (points[:, 2] > 1e-7)
pixels[side, good] = np.rint(_project(points[good], K[t])).astype(np.int32)
visible[side] = good
for side in (0, 1):
for child, parent in enumerate(ManoModel.parents[1:], 1):
if visible[side, child] and visible[side, parent]:
a, b = tuple(pixels[side, parent]), tuple(pixels[side, child])
colour = tuple((x + y) // 2 for x, y in zip(COLOURS[side][child], COLOURS[side][parent]))
cv2.line(image, a, b, (0, 0, 0), 3, cv2.LINE_AA)
cv2.line(image, a, b, colour, 1, cv2.LINE_AA)
for side in (0, 1):
for joint in np.flatnonzero(visible[side]):
point, radius = tuple(pixels[side, joint]), 3 if joint == 0 else 2
cv2.circle(image, point, radius + 1, (0, 0, 0), -1, cv2.LINE_AA)
cv2.circle(image, point, radius, COLOURS[side][joint], -1, cv2.LINE_AA)
return output