Repository navigation
Expand file tree
/
Copy pathrender_final.py
More file actions
410 lines (300 loc) · 13.1 KB
/
Copy pathrender_final.py
File metadata and controls
410 lines (300 loc) · 13.1 KB
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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
from models.rotation2xyz import Rotation2xyz
import numpy as np
from trimesh import Trimesh
import os
from Motion.InverseKinematics import animation_from_positions
from Motion import BVH
os.environ['PYOPENGL_PLATFORM'] = "osmesa"
import torch
from visualize.simplify_loc2rot import joints2smpl
import pyrender
import matplotlib.pyplot as plt
import io
import imageio
from shapely import geometry
import trimesh
from pyrender.constants import RenderFlags
import math
# import ffmpeg
from PIL import Image
class WeakPerspectiveCamera(pyrender.Camera):
def __init__(self,
scale,
translation,
znear=pyrender.camera.DEFAULT_Z_NEAR,
zfar=None,
name=None):
super(WeakPerspectiveCamera, self).__init__(
znear=znear,
zfar=zfar,
name=name,
)
self.scale = scale
self.translation = translation
def get_projection_matrix(self, width=None, height=None):
P = np.eye(4)
P[0, 0] = self.scale[0]
P[1, 1] = self.scale[1]
P[0, 3] = self.translation[0] * self.scale[0]
P[1, 3] = -self.translation[1] * self.scale[1]
P[2, 2] = -1
return P
def motion2smpl(motions, outdir='test_vis', device_id=0, name=None, pred=True):
frames, njoints, nfeats = motions.shape
MINS = motions.min(axis=0).min(axis=0)
MAXS = motions.max(axis=0).max(axis=0)
height_offset = MINS[1]
motions[:, :, 1] -= height_offset
trajec = motions[:, 0, [0, 2]]
j2s = joints2smpl(num_frames=frames, device_id=0, cuda=True)
motion_tensor, opt_dict = j2s.joint2smpl(motions) # [nframes, njoints, 3]
np.save(outdir + name+'_smpl.npy', motion_tensor.cpu().numpy())
def motion2bvh_ik(motions, bvh_path):
frames, njoints, nfeats = motions.shape
MINS = motions.min(axis=0).min(axis=0)
MAXS = motions.max(axis=0).max(axis=0)
height_offset = MINS[1]
motions[:, :, 1] -= height_offset
parents = [-1, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 9, 12, 13, 14, 16, 17, 18, 19]
SMPL_JOINT_NAMES = [
"Pelvis",
"Left_hip",
"Right_hip",
"Spine1",
"Left_knee",
"Right_knee",
"Spine2",
"Left_ankle",
"Right_ankle",
"Spine3",
"Left_foot",
"Right_foot",
"Neck",
"Left_collar",
"Right_collar",
"Head",
"Left_shoulder",
"Right_shoulder",
"Left_elbow",
"Right_elbow",
"Left_wrist",
"Right_wrist",
]
anim, sorted_order, _ = animation_from_positions(motions, parents)
BVH.save(bvh_path, anim, names=np.array(SMPL_JOINT_NAMES)[sorted_order], frametime= 1/20)
# rescale bvh according to scaling_factor
def rescale_bvh(input_file_path, output_file_path, scaling_factor):
# Open the input BVH file
with open(input_file_path, 'r') as input_file:
lines = input_file.readlines()
# Open the output BVH file
with open(output_file_path, 'w') as output_file:
# Iterate through each line in the input file
index = 0
for line in lines:
if line.strip() == "MOTION":
print(line)
break
# Check if the line starts with "OFFSET"
if line.strip().startswith('OFFSET'):
# Split the line into individual values
values = line.strip().split()
# Extract the "OFFSET" values as a list
offset = [float(v) for v in values[1:]]
# Multiply the "OFFSET" values by the scale factor
offset = [v * scaling_factor for v in offset]
offset_index = line.find('OFFSET')
before_offset = line[:offset_index]
after_offset = line[offset_index:]
# Write the modified "OFFSET" values to the output file, preserving any leading tabs
output_file.write(before_offset + 'OFFSET {:.6f} {:.6f} {:.6f}\n'.format(*offset))
else:
# Write all other lines to the output file unchanged
output_file.write(line)
index += 1
print(index)
# Handle motion part
output_file.write(lines[index]) # Append "MOTION"
index += 1
output_file.write(lines[index]) # Append "Frames: ..."
index += 1
output_file.write(lines[index]) # Append "Frame Time: ..."
index += 1
# Apply scaling factor to root translation in each frame
for line in lines[index:]:
values = line.strip().split()
values[0] = str(float(values[0]) * scaling_factor)
values[1] = str(float(values[1]) * scaling_factor)
values[2] = str(float(values[2]) * scaling_factor)
output_file.write(" ".join(values) + "\n")
def render_smpl(motion_tensor, file):
rot2xyz = Rotation2xyz(device=torch.device("cuda:0"))
faces = rot2xyz.smpl_model.faces
vertices = rot2xyz(torch.tensor(motion_tensor).clone(), mask=None,
pose_rep='rot6d', translation=True, glob=True,
jointstype='vertices',
vertstrans=True)
frames = vertices.shape[3] # shape: 1, nb_frames, 3, nb_joints
print (vertices.shape)
MINS = torch.min(torch.min(vertices[0], axis=0)[0], axis=1)[0]
MAXS = torch.max(torch.max(vertices[0], axis=0)[0], axis=1)[0]
# vertices[:,:,1,:] -= MINS[1] + 1e-5
out_list = []
minx = MINS[0] - 0.5
maxx = MAXS[0] + 0.5
minz = MINS[2] - 0.5
maxz = MAXS[2] + 0.5
polygon = geometry.Polygon([[minx, minz], [minx, maxz], [maxx, maxz], [maxx, minz]])
polygon_mesh = trimesh.creation.extrude_polygon(polygon, 1e-5)
vid = []
for i in range(frames):
if i % 10 == 0:
print(i)
mesh = Trimesh(vertices=vertices[0, :, :, i].squeeze().tolist(), faces=faces)
base_color = (0.11, 0.53, 0.8, 0.5)
## OPAQUE rendering without alpha
## BLEND rendering consider alpha
material = pyrender.MetallicRoughnessMaterial(
metallicFactor=0.7,
alphaMode='OPAQUE',
baseColorFactor=base_color
)
mesh = pyrender.Mesh.from_trimesh(mesh, material=material)
polygon_mesh.visual.face_colors = [0, 0, 0, 0.21]
polygon_render = pyrender.Mesh.from_trimesh(polygon_mesh, smooth=False)
bg_color = [1, 1, 1, 0.8]
scene = pyrender.Scene(bg_color=bg_color, ambient_light=(0.4, 0.4, 0.4))
sx, sy, tx, ty = [0.75, 0.75, 0, 0.10]
camera = pyrender.PerspectiveCamera(yfov=(np.pi / 3.0))
light = pyrender.DirectionalLight(color=[1,1,1], intensity=300)
scene.add(mesh)
c = np.pi / 2
scene.add(polygon_render, pose=np.array([[ 1, 0, 0, 0],
[ 0, np.cos(c), -np.sin(c), MINS[1].cpu().numpy()],
[ 0, np.sin(c), np.cos(c), 0],
[ 0, 0, 0, 1]]))
light_pose = np.eye(4)
light_pose[:3, 3] = [0, -1, 1]
scene.add(light, pose=light_pose.copy())
light_pose[:3, 3] = [0, 1, 1]
scene.add(light, pose=light_pose.copy())
light_pose[:3, 3] = [1, 1, 2]
scene.add(light, pose=light_pose.copy())
c = -np.pi / 6
scene.add(camera, pose=[[ 1, 0, 0, (minx+maxx).cpu().numpy()/2],
[ 0, np.cos(c), -np.sin(c), 1.5],
[ 0, np.sin(c), np.cos(c), max(4, minz.cpu().numpy()+(1.5-MINS[1].cpu().numpy())*2, (maxx-minx).cpu().numpy())],
[ 0, 0, 0, 1]
])
# render scene
r = pyrender.OffscreenRenderer(960, 960)
color, _ = r.render(scene, flags=RenderFlags.RGBA)
# Image.fromarray(color).save(outdir+name+'_'+str(i)+'.png')
vid.append(color)
r.delete()
out = np.stack(vid, axis=0)
imageio.mimsave(file, out, fps=20)
def render(motions, outdir='test_vis', device_id=0, name=None, pred=True):
frames, njoints, nfeats = motions.shape
MINS = motions.min(axis=0).min(axis=0)
MAXS = motions.max(axis=0).max(axis=0)
height_offset = MINS[1]
motions[:, :, 1] -= height_offset
trajec = motions[:, 0, [0, 2]]
j2s = joints2smpl(num_frames=frames, device_id=0, cuda=True)
rot2xyz = Rotation2xyz(device=torch.device("cuda:0"))
faces = rot2xyz.smpl_model.faces
if (not os.path.exists(outdir + name+'_pred.pt') and pred) or (not os.path.exists(outdir + name+'_gt.pt') and not pred):
print(f'Running SMPLify, it may take a few minutes.')
motion_tensor, opt_dict = j2s.joint2smpl(motions) # [nframes, njoints, 3]
vertices = rot2xyz(torch.tensor(motion_tensor).clone(), mask=None,
pose_rep='rot6d', translation=True, glob=True,
jointstype='vertices',
vertstrans=True)
if pred:
torch.save(vertices, outdir + name+'_pred.pt')
else:
torch.save(vertices, outdir + name+'_gt.pt')
else:
if pred:
vertices = torch.load(outdir + name+'_pred.pt')
else:
vertices = torch.load(outdir + name+'_gt.pt')
frames = vertices.shape[3] # shape: 1, nb_frames, 3, nb_joints
print (vertices.shape)
MINS = torch.min(torch.min(vertices[0], axis=0)[0], axis=1)[0]
MAXS = torch.max(torch.max(vertices[0], axis=0)[0], axis=1)[0]
# vertices[:,:,1,:] -= MINS[1] + 1e-5
out_list = []
minx = MINS[0] - 0.5
maxx = MAXS[0] + 0.5
minz = MINS[2] - 0.5
maxz = MAXS[2] + 0.5
polygon = geometry.Polygon([[minx, minz], [minx, maxz], [maxx, maxz], [maxx, minz]])
polygon_mesh = trimesh.creation.extrude_polygon(polygon, 1e-5)
vid = []
for i in range(frames):
if i % 10 == 0:
print(i)
mesh = Trimesh(vertices=vertices[0, :, :, i].squeeze().tolist(), faces=faces)
base_color = (0.11, 0.53, 0.8, 0.5)
## OPAQUE rendering without alpha
## BLEND rendering consider alpha
material = pyrender.MetallicRoughnessMaterial(
metallicFactor=0.7,
alphaMode='OPAQUE',
baseColorFactor=base_color
)
mesh = pyrender.Mesh.from_trimesh(mesh, material=material)
polygon_mesh.visual.face_colors = [0, 0, 0, 0.21]
polygon_render = pyrender.Mesh.from_trimesh(polygon_mesh, smooth=False)
bg_color = [1, 1, 1, 0.8]
scene = pyrender.Scene(bg_color=bg_color, ambient_light=(0.4, 0.4, 0.4))
sx, sy, tx, ty = [0.75, 0.75, 0, 0.10]
camera = pyrender.PerspectiveCamera(yfov=(np.pi / 3.0))
light = pyrender.DirectionalLight(color=[1,1,1], intensity=300)
scene.add(mesh)
c = np.pi / 2
scene.add(polygon_render, pose=np.array([[ 1, 0, 0, 0],
[ 0, np.cos(c), -np.sin(c), MINS[1].cpu().numpy()],
[ 0, np.sin(c), np.cos(c), 0],
[ 0, 0, 0, 1]]))
light_pose = np.eye(4)
light_pose[:3, 3] = [0, -1, 1]
scene.add(light, pose=light_pose.copy())
light_pose[:3, 3] = [0, 1, 1]
scene.add(light, pose=light_pose.copy())
light_pose[:3, 3] = [1, 1, 2]
scene.add(light, pose=light_pose.copy())
c = -np.pi / 6
scene.add(camera, pose=[[ 1, 0, 0, (minx+maxx).cpu().numpy()/2],
[ 0, np.cos(c), -np.sin(c), 1.5],
[ 0, np.sin(c), np.cos(c), max(4, minz.cpu().numpy()+(1.5-MINS[1].cpu().numpy())*2, (maxx-minx).cpu().numpy())],
[ 0, 0, 0, 1]
])
# render scene
r = pyrender.OffscreenRenderer(960, 960)
color, _ = r.render(scene, flags=RenderFlags.RGBA)
# Image.fromarray(color).save(outdir+name+'_'+str(i)+'.png')
vid.append(color)
r.delete()
out = np.stack(vid, axis=0)
if pred:
imageio.mimsave(outdir + name+'_pred.gif', out, fps=20)
else:
imageio.mimsave(outdir + name+'_gt.gif', out, fps=20)
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--filedir", type=str, default=None, help='motion npy file dir')
parser.add_argument('--motion-list', default=None, nargs="+", type=str, help="motion name list")
args = parser.parse_args()
filename_list = args.motion_list
filedir = args.filedir
for filename in filename_list:
motions = np.load(filedir + filename+'_pred.npy')
print('pred', motions.shape, filename)
render(motions[0], outdir=filedir, device_id=0, name=filename, pred=True)
motions = np.load(filedir + filename+'_gt.npy')
print('gt', motions.shape, filename)
render(motions[0], outdir=filedir, device_id=0, name=filename, pred=False)