Spaces:
Running
Running
File size: 7,206 Bytes
517683d |
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 |
# From TEMOS: temos/render/anim.py
# Inspired by
# - https://github.com/anindita127/Complextext2animation/blob/main/src/utils/visualization.py
# - https://github.com/facebookresearch/QuaterNet/blob/main/common/visualization.py
import os
import logging
from dataclasses import dataclass
from typing import List, Tuple, Optional
import numpy as np
from src.tools.rifke import canonicalize_rotation
logger = logging.getLogger("matplotlib.animation")
logger.setLevel(logging.ERROR)
colors = ("black", "magenta", "red", "green", "blue")
KINEMATIC_TREES = {
"smpljoints": [
[0, 3, 6, 9, 12, 15],
[9, 13, 16, 18, 20],
[9, 14, 17, 19, 21],
[0, 1, 4, 7, 10],
[0, 2, 5, 8, 11],
],
"guoh3djoints": [ # no hands
[0, 3, 6, 9, 12, 15],
[9, 13, 16, 18, 20],
[9, 14, 17, 19, 21],
[0, 1, 4, 7, 10],
[0, 2, 5, 8, 11],
],
}
@dataclass
class MatplotlibRender:
jointstype: str = "smpljoints"
fps: float = 20.0
colors: List[str] = colors
figsize: int = 4
fontsize: int = 15
canonicalize: bool = False
def __call__(
self,
joints,
output,
fps=None,
highlights=None,
title: str = "",
canonicalize=None,
):
canonicalize = canonicalize if canonicalize is not None else self.canonicalize
fps = fps if fps is not None else self.fps
if joints.shape[1] == 24:
# remove the hands
joints = joints[:, :22]
render_animation(
joints,
title=title,
highlights=highlights,
output=output,
jointstype=self.jointstype,
fps=self.fps,
colors=self.colors,
figsize=(self.figsize, self.figsize),
fontsize=self.fontsize,
canonicalize=canonicalize,
)
def init_axis(fig, title, radius=1.5):
ax = fig.add_subplot(1, 1, 1, projection="3d")
ax.view_init(elev=20.0, azim=-60)
fact = 2
ax.set_xlim3d([-radius / fact, radius / fact])
ax.set_ylim3d([-radius / fact, radius / fact])
ax.set_zlim3d([0, radius])
ax.set_aspect("auto")
ax.set_xticklabels([])
ax.set_yticklabels([])
ax.set_zticklabels([])
ax.set_axis_off()
ax.grid(b=False)
ax.set_title(title, loc="center", wrap=True)
return ax
def plot_floor(ax, minx, maxx, miny, maxy, minz):
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
# Plot a plane XZ
verts = [
[minx, miny, minz],
[minx, maxy, minz],
[maxx, maxy, minz],
[maxx, miny, minz],
]
xz_plane = Poly3DCollection([verts], zorder=1)
xz_plane.set_facecolor((0.5, 0.5, 0.5, 1))
ax.add_collection3d(xz_plane)
# Plot a bigger square plane XZ
radius = max((maxx - minx), (maxy - miny))
# center +- radius
minx_all = (maxx + minx) / 2 - radius
maxx_all = (maxx + minx) / 2 + radius
miny_all = (maxy + miny) / 2 - radius
maxy_all = (maxy + miny) / 2 + radius
verts = [
[minx_all, miny_all, minz],
[minx_all, maxy_all, minz],
[maxx_all, maxy_all, minz],
[maxx_all, miny_all, minz],
]
xz_plane = Poly3DCollection([verts], zorder=1)
xz_plane.set_facecolor((0.5, 0.5, 0.5, 0.5))
ax.add_collection3d(xz_plane)
return ax
def update_camera(ax, root, radius=1.5):
fact = 2
ax.set_xlim3d([-radius / fact + root[0], radius / fact + root[0]])
ax.set_ylim3d([-radius / fact + root[1], radius / fact + root[1]])
def render_animation(
joints: np.ndarray,
output: str = "notebook",
highlights: Optional[np.ndarray] = None,
jointstype: str = "smpljoints",
title: str = "",
fps: float = 20.0,
colors: List[str] = colors,
figsize: Tuple[int] = (4, 4),
fontsize: int = 15,
canonicalize: bool = False,
agg=True,
):
if agg:
import matplotlib
matplotlib.use("Agg")
if highlights is not None:
assert len(highlights) == len(joints)
assert jointstype in KINEMATIC_TREES
kinematic_tree = KINEMATIC_TREES[jointstype]
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import matplotlib.patheffects as pe
mean_fontsize = fontsize
# heuristic to change fontsize
fontsize = mean_fontsize - (len(title) - 30) / 20
plt.rcParams.update({"font.size": fontsize})
# Z is gravity here
x, y, z = 0, 1, 2
joints = joints.copy()
if canonicalize:
joints = canonicalize_rotation(joints, jointstype=jointstype)
# Create a figure and initialize 3d plot
fig = plt.figure(figsize=figsize)
ax = init_axis(fig, title)
# Create spline line
trajectory = joints[:, 0, [x, y]]
avg_segment_length = (
np.mean(np.linalg.norm(np.diff(trajectory, axis=0), axis=1)) + 1e-3
)
draw_offset = int(25 / avg_segment_length)
(spline_line,) = ax.plot(*trajectory.T, zorder=10, color="white")
# Create a floor
minx, miny, _ = joints.min(axis=(0, 1))
maxx, maxy, _ = joints.max(axis=(0, 1))
plot_floor(ax, minx, maxx, miny, maxy, 0)
# Put the character on the floor
height_offset = np.min(joints[:, :, z]) # Min height
joints = joints.copy()
joints[:, :, z] -= height_offset
# Initialization for redrawing
lines = []
initialized = False
def update(frame):
nonlocal initialized
skeleton = joints[frame]
root = skeleton[0]
update_camera(ax, root)
hcolors = colors
if highlights is not None and highlights[frame]:
hcolors = ("red", "red", "red", "red", "red")
for index, (chain, color) in enumerate(
zip(reversed(kinematic_tree), reversed(hcolors))
):
if not initialized:
lines.append(
ax.plot(
skeleton[chain, x],
skeleton[chain, y],
skeleton[chain, z],
linewidth=6.0,
color=color,
zorder=20,
path_effects=[pe.SimpleLineShadow(), pe.Normal()],
)
)
else:
lines[index][0].set_xdata(skeleton[chain, x])
lines[index][0].set_ydata(skeleton[chain, y])
lines[index][0].set_3d_properties(skeleton[chain, z])
lines[index][0].set_color(color)
left = max(frame - draw_offset, 0)
right = min(frame + draw_offset, trajectory.shape[0])
spline_line.set_xdata(trajectory[left:right, 0])
spline_line.set_ydata(trajectory[left:right, 1])
spline_line.set_3d_properties(np.zeros_like(trajectory[left:right, 0]))
initialized = True
fig.tight_layout()
frames = joints.shape[0]
anim = FuncAnimation(fig, update, frames=frames, interval=1000 / fps, repeat=False)
if output == "notebook":
from IPython.display import HTML
HTML(anim.to_jshtml())
else:
# anim.save(output, writer='ffmpeg', fps=fps)
anim.save(output, fps=fps)
plt.close() |