carsten12 commited on
Commit
90216c1
·
verified ·
1 Parent(s): 6c5a7a3

Delete visualize.py

Browse files
Files changed (1) hide show
  1. visualize.py +0 -896
visualize.py DELETED
@@ -1,896 +0,0 @@
1
-
2
- import numpy as np
3
- from typing import List
4
- import plotly
5
- import plotly.graph_objects as go
6
- import plotly.express as px
7
- import trimesh
8
- import argparse
9
- import smplx
10
- import json
11
- import torch
12
- #import ipywidgets as widgets
13
- from plotly.subplots import make_subplots
14
-
15
-
16
-
17
- from measurement_definitions import MeasurementType
18
- from utils import convex_hull_from_3D_points, filter_body_part_slices
19
- from joint_definitions import SMPL_IND2JOINT, SMPLX_IND2JOINT
20
- from landmark_definitions import SMPL_LANDMARK_INDICES, SMPLX_LANDMARK_INDICES
21
-
22
- class Visualizer():
23
- '''
24
- Visualize the body model with measurements, landmarks and joints.
25
- All the measurements are expressed in cm.
26
- '''
27
-
28
- def __init__(self,
29
- verts: np.ndarray,
30
- faces: np.ndarray,
31
- joints: np.ndarray,
32
- landmarks: dict,
33
- measurements: dict,
34
- measurement_types: dict,
35
- length_definitions: dict,
36
- circumf_definitions: dict,
37
- joint2ind: dict,
38
- circumf_2_bodypart: dict,
39
- face_segmentation: dict,
40
- visualize_body: bool = True,
41
- visualize_landmarks: bool = True,
42
- visualize_joints: bool = True,
43
- visualize_measurements: bool=True,
44
- title: str = "Measurement visualization"
45
- ):
46
-
47
-
48
- self.verts = verts
49
- self.faces = faces
50
- self.joints = joints
51
- self.landmarks = landmarks
52
- self.measurements = measurements
53
- self.measurement_types = measurement_types
54
- self.length_definitions = length_definitions
55
- self.circumf_definitions = circumf_definitions
56
- self.joint2ind = joint2ind
57
- self.circumf_2_bodypart = circumf_2_bodypart
58
- self.face_segmentation = face_segmentation
59
-
60
- self.visualize_body = visualize_body
61
- self.visualize_landmarks = visualize_landmarks
62
- self.visualize_joints = visualize_joints
63
- self.visualize_measurements = visualize_measurements
64
-
65
- self.title = title
66
-
67
-
68
-
69
- @staticmethod
70
- def create_mesh_plot(verts: np.ndarray, faces: np.ndarray):
71
- '''
72
- Visualize smpl body mesh.
73
- :param verts: np.array (N,3) of vertices
74
- :param faces: np.array (F,3) of faces connecting the vertices
75
-
76
- Return:
77
- plotly Mesh3d object for plotting
78
- '''
79
- mesh_plot = go.Mesh3d(
80
- x=verts[:,0],
81
- y=verts[:,1],
82
- z=verts[:,2],
83
- color="gray",
84
- hovertemplate ='<i>Index</i>: %{text}',
85
- text = [i for i in range(verts.shape[0])],
86
- # i, j and k give the vertices of triangles
87
- i=faces[:,0],
88
- j=faces[:,1],
89
- k=faces[:,2],
90
- opacity=0.6,
91
- name='body',
92
- )
93
- return mesh_plot
94
-
95
- @staticmethod
96
- def create_joint_plot(joints: np.ndarray):
97
-
98
- return go.Scatter3d(x = joints[:,0],
99
- y = joints[:,1],
100
- z = joints[:,2],
101
- mode='markers',
102
- marker=dict(size=8,
103
- color="black",
104
- opacity=1,
105
- symbol="cross"
106
- ),
107
- name="joints"
108
- )
109
-
110
- @staticmethod
111
- def create_wireframe_plot(verts: np.ndarray,faces: np.ndarray):
112
- '''
113
- Given vertices and faces, creates a wireframe of plotly segments.
114
- Used for visualizing the wireframe.
115
-
116
- :param verts: np.array (N,3) of vertices
117
- :param faces: np.array (F,3) of faces connecting the verts
118
- '''
119
- i=faces[:,0]
120
- j=faces[:,1]
121
- k=faces[:,2]
122
-
123
- triangles = np.vstack((i,j,k)).T
124
-
125
- x=verts[:,0]
126
- y=verts[:,1]
127
- z=verts[:,2]
128
-
129
- vertices = np.vstack((x,y,z)).T
130
- tri_points = vertices[triangles]
131
-
132
- #extract the lists of x, y, z coordinates of the triangle
133
- # vertices and connect them by a "line" by adding None
134
- # this is a plotly convention for plotting segments
135
- Xe = []
136
- Ye = []
137
- Ze = []
138
- for T in tri_points:
139
- Xe.extend([T[k%3][0] for k in range(4)]+[ None])
140
- Ye.extend([T[k%3][1] for k in range(4)]+[ None])
141
- Ze.extend([T[k%3][2] for k in range(4)]+[ None])
142
-
143
- # return Xe, Ye, Ze
144
- wireframe = go.Scatter3d(
145
- x=Xe,
146
- y=Ye,
147
- z=Ze,
148
- mode='lines',
149
- name='wireframe',
150
- line=dict(color= 'rgb(70,70,70)', width=1)
151
- )
152
- return wireframe
153
-
154
- def create_landmarks_plot(self,
155
- landmark_names: List[str],
156
- verts: np.ndarray
157
- ) -> List[plotly.graph_objs.Scatter3d]:
158
- '''
159
- Visualize landmarks from landmark_names list
160
- :param landmark_names: List[str] of landmark names to visualize
161
-
162
- Return
163
- :param plots: list of plotly objects to plot
164
- '''
165
-
166
- plots = []
167
-
168
- landmark_colors = dict(zip(self.landmarks.keys(),
169
- px.colors.qualitative.Alphabet))
170
-
171
- for lm_name in landmark_names:
172
- if lm_name not in self.landmarks.keys():
173
- print(f"Landmark {lm_name} is not defined.")
174
- pass
175
-
176
- lm_index = self.landmarks[lm_name]
177
- if isinstance(lm_index,tuple):
178
- lm = (verts[lm_index[0]] + verts[lm_index[1]]) / 2
179
- else:
180
- lm = verts[lm_index]
181
-
182
- plot = go.Scatter3d(x = [lm[0]],
183
- y = [lm[1]],
184
- z = [lm[2]],
185
- mode='markers',
186
- marker=dict(size=8,
187
- color=landmark_colors[lm_name],
188
- opacity=1,
189
- ),
190
- name=lm_name
191
- )
192
-
193
- plots.append(plot)
194
-
195
- return plots
196
-
197
- def create_measurement_length_plot(self,
198
- measurement_name: str,
199
- verts: np.ndarray,
200
- color: str
201
- ):
202
- '''
203
- Create length measurement plot.
204
- :param measurement_name: str, measurement name to plot
205
- :param verts: np.array (N,3) of vertices
206
- :param color: str of color to color the measurement
207
-
208
- Return
209
- plotly object to plot
210
- '''
211
-
212
- measurement_landmarks_inds = self.length_definitions[measurement_name]
213
-
214
- segments = {"x":[],"y":[],"z":[]}
215
- for i in range(2):
216
- if isinstance(measurement_landmarks_inds[i],tuple):
217
- lm_tnp = (verts[measurement_landmarks_inds[i][0]] +
218
- verts[measurement_landmarks_inds[i][1]]) / 2
219
- else:
220
- lm_tnp = verts[measurement_landmarks_inds[i]]
221
- segments["x"].append(lm_tnp[0])
222
- segments["y"].append(lm_tnp[1])
223
- segments["z"].append(lm_tnp[2])
224
- for ax in ["x","y","z"]:
225
- segments[ax].append(None)
226
-
227
- if measurement_name in self.measurements:
228
- m_viz_name = f"{measurement_name}: {self.measurements[measurement_name]:.2f}cm"
229
- else:
230
- m_viz_name = measurement_name
231
-
232
- return go.Scatter3d(x=segments["x"],
233
- y=segments["y"],
234
- z=segments["z"],
235
- marker=dict(
236
- size=4,
237
- color="rgba(0,0,0,0)",
238
- ),
239
- line=dict(
240
- color=color,
241
- width=10),
242
- name=m_viz_name
243
- )
244
-
245
- def create_measurement_circumference_plot(self,
246
- measurement_name: str,
247
- verts: np.ndarray,
248
- faces: np.ndarray,
249
- color: str):
250
- '''
251
- Create circumference measurement plot
252
- :param measurement_name: str, measurement name to plot
253
- :param verts: np.array (N,3) of vertices
254
- :param faces: np.array (F,3) of faces connecting the vertices
255
- :param color: str of color to color the measurement
256
-
257
- Return
258
- plotly object to plot
259
- '''
260
-
261
- circumf_landmarks = self.circumf_definitions[measurement_name]["LANDMARKS"]
262
- circumf_landmark_indices = [self.landmarks[l_name] for l_name in circumf_landmarks]
263
- circumf_n1, circumf_n2 = self.circumf_definitions[measurement_name]["JOINTS"]
264
- circumf_n1, circumf_n2 = self.joint2ind[circumf_n1], self.joint2ind[circumf_n2]
265
-
266
- plane_origin = np.mean(verts[circumf_landmark_indices,:],axis=0)
267
- plane_normal = self.joints[circumf_n1,:] - self.joints[circumf_n2,:]
268
-
269
- mesh = trimesh.Trimesh(vertices=verts, faces=faces)
270
-
271
- slice_segments, sliced_faces = trimesh.intersections.mesh_plane(mesh,
272
- plane_normal=plane_normal,
273
- plane_origin=plane_origin,
274
- return_faces=True) # (N, 2, 3), (N,)
275
-
276
- slice_segments = filter_body_part_slices(slice_segments,
277
- sliced_faces,
278
- measurement_name,
279
- self.circumf_2_bodypart,
280
- self.face_segmentation)
281
-
282
- slice_segments_hull = convex_hull_from_3D_points(slice_segments)
283
-
284
-
285
- draw_segments = {"x":[],"y":[],"z":[]}
286
- map_ax = {0:"x",1:"y",2:"z"}
287
-
288
- for i in range(slice_segments_hull.shape[0]):
289
- for j in range(3):
290
- draw_segments[map_ax[j]].append(slice_segments_hull[i,0,j])
291
- draw_segments[map_ax[j]].append(slice_segments_hull[i,1,j])
292
- draw_segments[map_ax[j]].append(None)
293
-
294
- if measurement_name in self.measurements:
295
- m_viz_name = f"{measurement_name}: {self.measurements[measurement_name]:.2f}cm"
296
- else:
297
- m_viz_name = measurement_name
298
-
299
- return go.Scatter3d(
300
- x=draw_segments["x"],
301
- y=draw_segments["y"],
302
- z=draw_segments["z"],
303
- mode="lines",
304
- line=dict(
305
- color=color,
306
- width=10),
307
- name=m_viz_name
308
- )
309
-
310
- def visualize(self,
311
- measurement_names: List[str] = [],
312
- landmark_names: List[str] = [],
313
- title="Measurement visualization"
314
- ):
315
- '''
316
- Visualize the body model with measurements, landmarks and joints.
317
-
318
- :param measurement_names: List[str], list of strings with measurement names
319
- :param landmark_names: List[str], list of strings with landmark names
320
- :param title: str, title of plot
321
- '''
322
-
323
-
324
- fig = go.Figure()
325
-
326
- if self.visualize_body:
327
- # visualize model mesh
328
- mesh_plot = self.create_mesh_plot(self.verts, self.faces)
329
- fig.add_trace(mesh_plot)
330
- # visualize wireframe
331
- wireframe_plot = self.create_wireframe_plot(self.verts, self.faces)
332
- fig.add_trace(wireframe_plot)
333
-
334
- # visualize joints
335
- if self.visualize_joints:
336
- joint_plot = self.create_joint_plot(self.joints)
337
- fig.add_trace(joint_plot)
338
-
339
-
340
- # visualize landmarks
341
- if self.visualize_landmarks:
342
- landmarks_plot = self.create_landmarks_plot(landmark_names, self.verts)
343
- fig.add_traces(landmarks_plot)
344
-
345
-
346
- # visualize measurements
347
- measurement_colors = dict(zip(self.measurement_types.keys(),
348
- px.colors.qualitative.Alphabet))
349
-
350
- if self.visualize_measurements:
351
- for m_name in measurement_names:
352
- if m_name not in self.measurement_types.keys():
353
- print(f"Measurement {m_name} not defined.")
354
- pass
355
-
356
- if self.measurement_types[m_name] == MeasurementType().LENGTH:
357
- measurement_plot = self.create_measurement_length_plot(measurement_name=m_name,
358
- verts=self.verts,
359
- color=measurement_colors[m_name])
360
- elif self.measurement_types[m_name] == MeasurementType().CIRCUMFERENCE:
361
- measurement_plot = self.create_measurement_circumference_plot(measurement_name=m_name,
362
- verts=self.verts,
363
- faces=self.faces,
364
- color=measurement_colors[m_name])
365
-
366
- fig.add_trace(measurement_plot)
367
-
368
-
369
- fig.update_layout(scene_aspectmode='data',
370
- width=1000, height=700,
371
- title=title,
372
- )
373
-
374
- fig.show()
375
-
376
-
377
- def viz_smplx_joints(visualize_body=True,fig=None,show=True,title="SMPLX joints"):
378
- """
379
- Visualize smpl joints on the same plot.
380
- :param visualize_body: bool, whether to visualize the body or not.
381
- :param fig: plotly Figure object, if None, create new figure.
382
- """
383
-
384
- betas = torch.zeros((1, 10), dtype=torch.float32)
385
-
386
- smplx_model = smplx.create(model_path="data",
387
- model_type="smplx",
388
- gender="NEUTRAL",
389
- use_face_contour=False,
390
- num_betas=10,
391
- #body_pose=torch.zeros((1, (55-1) * 3)),
392
- ext='pkl')
393
-
394
- smplx_model = smplx_model(betas=betas, return_verts=True)
395
- smplx_joints = smplx_model.joints.detach().numpy()[0]
396
- smplx_joint_pelvis = smplx_joints[0,:]
397
- smplx_joints = smplx_joints - smplx_joint_pelvis
398
- smplx_vertices = smplx_model.vertices.detach().numpy()[0]
399
- smplx_vertices = smplx_vertices - smplx_joint_pelvis
400
- smplx_faces = smplx.SMPLX("data/smplx",ext="pkl").faces
401
-
402
- joint_colors = px.colors.qualitative.Alphabet + \
403
- px.colors.qualitative.Dark24 + \
404
- px.colors.qualitative.Alphabet + \
405
- px.colors.qualitative.Dark24 + \
406
- px.colors.qualitative.Alphabet + \
407
- ["#000000"]
408
-
409
- if isinstance(fig,type(None)):
410
- fig = go.Figure()
411
-
412
- for i in range(smplx_joints.shape[0]):
413
-
414
- if i in SMPLX_IND2JOINT.keys():
415
- joint_name = SMPLX_IND2JOINT[i]
416
- else:
417
- joint_name = f"noname-{i}"
418
-
419
- joint_plot = go.Scatter3d(x = [smplx_joints[i,0]],
420
- y = [smplx_joints[i,1]],
421
- z = [smplx_joints[i,2]],
422
- mode='markers',
423
- marker=dict(size=10,
424
- color=joint_colors[i],
425
- opacity=1,
426
- symbol="circle"
427
- ),
428
- name="smplx-"+joint_name
429
- )
430
-
431
-
432
- fig.add_trace(joint_plot)
433
-
434
-
435
- if visualize_body:
436
- plot_body = go.Mesh3d(
437
- x=smplx_vertices[:,0],
438
- y=smplx_vertices[:,1],
439
- z=smplx_vertices[:,2],
440
- color = "red",
441
- i=smplx_faces[:,0],
442
- j=smplx_faces[:,1],
443
- k=smplx_faces[:,2],
444
- name='smplx mesh',
445
- showscale=True,
446
- opacity=0.5
447
- )
448
- fig.add_trace(plot_body)
449
-
450
- fig.update_layout(scene_aspectmode='data',
451
- width=1000, height=700,
452
- title=title,
453
- )
454
-
455
-
456
- if show:
457
- fig.show()
458
- else:
459
- return fig
460
-
461
-
462
- def viz_smpl_joints(visualize_body=True,fig=None,show=True,title="SMPL joints"):
463
- """
464
- Visualize smpl joints on the same plot.
465
- :param visualize_body: bool, whether to visualize the body or not.
466
- :param fig: plotly Figure object, if None, create new figure.
467
- """
468
-
469
- betas = torch.zeros((1, 10), dtype=torch.float32)
470
-
471
- smpl_model = smplx.create(model_path="data",
472
- model_type="smpl",
473
- gender="NEUTRAL",
474
- use_face_contour=False,
475
- num_betas=10,
476
- ext='pkl')
477
-
478
- smpl_model = smpl_model(betas=betas, return_verts=True)
479
- smpl_joints = smpl_model.joints.detach().numpy()[0]
480
- smpl_joints_pelvis = smpl_joints[0,:]
481
- smpl_joints = smpl_joints - smpl_joints_pelvis
482
- smpl_vertices = smpl_model.vertices.detach().numpy()[0]
483
- smpl_vertices = smpl_vertices - smpl_joints_pelvis
484
- smpl_faces = smplx.SMPL("data/smpl",ext="pkl").faces
485
-
486
-
487
- joint_colors = px.colors.qualitative.Alphabet + \
488
- px.colors.qualitative.Dark24 + \
489
- px.colors.qualitative.Alphabet + \
490
- px.colors.qualitative.Dark24 + \
491
- px.colors.qualitative.Alphabet + \
492
- ["#000000"]
493
-
494
- if isinstance(fig,type(None)):
495
- fig = go.Figure()
496
-
497
- for i in range(smpl_joints.shape[0]):
498
-
499
- if i in SMPL_IND2JOINT.keys():
500
- joint_name = SMPL_IND2JOINT[i]
501
- else:
502
- joint_name = f"noname-{i}"
503
-
504
- joint_plot = go.Scatter3d(x = [smpl_joints[i,0]],
505
- y = [smpl_joints[i,1]],
506
- z = [smpl_joints[i,2]],
507
- mode='markers',
508
- marker=dict(size=10,
509
- color=joint_colors[i],
510
- opacity=1,
511
- symbol="cross"
512
- ),
513
- name="smpl-"+joint_name
514
- )
515
-
516
-
517
- fig.add_trace(joint_plot)
518
-
519
- if visualize_body:
520
- plot_body = go.Mesh3d(
521
- x=smpl_vertices[:,0],
522
- y=smpl_vertices[:,1],
523
- z=smpl_vertices[:,2],
524
- #facecolor=face_colors,
525
- color = "blue",
526
- i=smpl_faces[:,0],
527
- j=smpl_faces[:,1],
528
- k=smpl_faces[:,2],
529
- name='smpl mesh',
530
- showscale=True,
531
- opacity=0.5
532
- )
533
- fig.add_trace(plot_body)
534
-
535
- fig.update_layout(scene_aspectmode='data',
536
- width=1000, height=700,
537
- title=title,
538
- )
539
- if show:
540
- fig.show()
541
- else:
542
- return fig
543
-
544
-
545
- def viz_face_segmentation(verts,faces,face_colors,
546
- title="Segmented body",name="mesh",show=True):
547
- """
548
- Visualize face segmentation defined in face_colors.
549
- :param verts: np.ndarray - (N,3) representing the vertices
550
- :param faces: np.ndarray - (F,3) representing the indices of the faces
551
- :param face_colors: np.ndarray - (F,3) representing the colors of the faces
552
- """
553
-
554
- import plotly.graph_objects as go
555
-
556
- fig = go.Figure()
557
- mesh_plot = go.Mesh3d(
558
- x=verts[:,0],
559
- y=verts[:,1],
560
- z=verts[:,2],
561
- facecolor=face_colors,
562
- i=faces[:,0],
563
- j=faces[:,1],
564
- k=faces[:,2],
565
- name=name,
566
- showscale=True,
567
- opacity=1
568
- )
569
- fig.add_trace(mesh_plot)
570
- fig.update_layout(scene_aspectmode='data',
571
- width=1000, height=700,
572
- title=title)
573
-
574
- if show:
575
- fig.show()
576
- else:
577
- return fig
578
-
579
-
580
- def viz_smpl_face_segmentation(fig=None, show=True, title="SMPL face segmentation"):
581
- body = smplx.SMPL("data/smpl",ext="pkl")
582
-
583
- with open("data/smpl/smpl_body_parts_2_faces.json","r") as f:
584
- face_segmentation = json.load(f)
585
-
586
- faces = body.faces
587
- verts = body.v_template
588
-
589
- # create colors for each face
590
- colors = px.colors.qualitative.Alphabet + \
591
- px.colors.qualitative.Dark24
592
- mapping_bp2ind = dict(zip(face_segmentation.keys(),
593
- range(len(face_segmentation.keys()))
594
- ))
595
- face_colors = [0]*faces.shape[0]
596
- for bp_name,bp_indices in face_segmentation.items():
597
- bp_label = mapping_bp2ind[bp_name]
598
- for i in bp_indices:
599
- face_colors[i] = colors[bp_label]
600
-
601
- if isinstance(fig,type(None)):
602
- fig = go.Figure()
603
-
604
- fig = viz_face_segmentation(verts,faces,face_colors,title=title,name="smpl",show=False)
605
-
606
- if show:
607
- fig.show()
608
- else:
609
- return fig
610
-
611
-
612
- def viz_smplx_face_segmentation(fig=None,show=True,title="SMPLX face segmentation"):
613
- """
614
- Visualize face segmentations for smplx.
615
- """
616
-
617
- body = smplx.SMPLX("data/smplx",ext="pkl")
618
-
619
- with open("data/smplx/smplx_body_parts_2_faces.json","r") as f:
620
- face_segmentation = json.load(f)
621
-
622
-
623
- faces = body.faces
624
- verts = body.v_template
625
-
626
- # create colors for each face
627
- colors = px.colors.qualitative.Alphabet + \
628
- px.colors.qualitative.Dark24
629
- mapping_bp2ind = dict(zip(face_segmentation.keys(),
630
- range(len(face_segmentation.keys()))
631
- ))
632
- face_colors = [0]*faces.shape[0]
633
- for bp_name,bp_indices in face_segmentation.items():
634
- bp_label = mapping_bp2ind[bp_name]
635
- for i in bp_indices:
636
- face_colors[i] = colors[bp_label]
637
-
638
- if isinstance(fig,type(None)):
639
- fig = go.Figure()
640
-
641
- fig = viz_face_segmentation(verts,faces,face_colors,title=title,name="smpl",show=False)
642
-
643
- if show:
644
- fig.show()
645
- else:
646
- return fig
647
-
648
-
649
- def viz_point_segmentation(verts,point_segm,title="Segmented body",fig=None,show=True):
650
- """
651
- Visualze points and their segmentation defined in dict point_segm.
652
- :param verts: np.ndarray - (N,3) representing the vertices
653
- :param point_segm: dict - dict mapping body part to all points belonging
654
- to it
655
- """
656
- colors = px.colors.qualitative.Alphabet + \
657
- px.colors.qualitative.Dark24
658
-
659
- if isinstance(fig,type(None)):
660
- fig = go.Figure()
661
-
662
- for i, (body_part, body_indices) in enumerate(point_segm.items()):
663
- plot = go.Scatter3d(x = verts[body_indices,0],
664
- y = verts[body_indices,1],
665
- z = verts[body_indices,2],
666
- mode='markers',
667
- marker=dict(size=5,
668
- color=colors[i],
669
- opacity=1,
670
- #symbol="cross"
671
- ),
672
- name=body_part
673
- )
674
- fig.add_trace(plot)
675
- fig.update_layout(scene_aspectmode='data',
676
- width=1000, height=700,
677
- title=title)
678
- if show:
679
- fig.show()
680
- return fig
681
-
682
-
683
- def viz_smplx_point_segmentation(fig=None,show=True,title="SMPLX point segmentation"):
684
- """
685
- Visualize point segmentations for smplx.
686
- """
687
-
688
- model_path = "data/smplx"
689
- smpl_verts = smplx.SMPLX(model_path,ext="pkl").v_template
690
- with open("data/smplx/point_segmentation_meshcapade.json","r") as f:
691
- point_segm = json.load(f)
692
- fig = viz_point_segmentation(smpl_verts,point_segm,title=title,fig=fig,show=show)
693
-
694
- if show:
695
- fig.show()
696
- else:
697
- return fig
698
-
699
-
700
- def viz_smpl_point_segmentation(fig=None,show=True,title="SMPL point segmentation"):
701
- """
702
- Visualize point segmentations for smpl.
703
- """
704
-
705
- model_path = "data/smpl"
706
- smpl_verts = smplx.SMPL(model_path,ext="pkl").v_template
707
- with open("data/smpl/point_segmentation_meshcapade.json","r") as f:
708
- point_segm = json.load(f)
709
- fig = viz_point_segmentation(smpl_verts,point_segm,title=title,fig=fig,show=show)
710
-
711
- if show:
712
- fig.show()
713
- else:
714
- return fig
715
-
716
-
717
- def viz_landmarks(verts,landmark_dict,title="Visualize landmarks",fig=None,show=True,name="points"):
718
-
719
- if isinstance(fig,type(None)):
720
- fig = go.Figure()
721
-
722
- plot = go.Scatter3d(x = verts[:,0],
723
- y = verts[:,1],
724
- z = verts[:,2],
725
- mode='markers',
726
- hovertemplate ='<i>Index</i>: %{text}',
727
- text = [i for i in range(verts.shape[0])],
728
- marker=dict(size=5,
729
- color="black",
730
- opacity=0.2,
731
- # line=dict(color='black',width=1)
732
- ),
733
- name=name
734
- )
735
-
736
- fig.add_trace(plot)
737
-
738
- colors = px.colors.qualitative.Alphabet + \
739
- px.colors.qualitative.Dark24 + \
740
- px.colors.qualitative.Alphabet + \
741
- px.colors.qualitative.Dark24
742
-
743
- for i, (lm_name, lm_ind) in enumerate(landmark_dict.items()):
744
- plot = go.Scatter3d(x = [verts[lm_ind,0]],
745
- y = [verts[lm_ind,1]],
746
- z = [verts[lm_ind,2]],
747
- mode='markers',
748
- marker=dict(size=10,
749
- color=colors[i],
750
- opacity=1,
751
- symbol="cross"
752
- ),
753
- name=name+"-"+lm_name
754
- )
755
- fig.add_trace(plot)
756
-
757
- fig.update_layout(scene_aspectmode='data',
758
- width=1000, height=700,
759
- title=title)
760
-
761
- if show:
762
- fig.show()
763
- else:
764
- return fig
765
-
766
-
767
- def viz_smpl_landmarks(fig=None,show=True,title="SMPL landmarks"):
768
- """
769
- Visualize smpl landmarks.
770
- """
771
-
772
- verts = smplx.SMPL("data/smpl",ext="pkl").v_template
773
- landmark_dict = SMPL_LANDMARK_INDICES
774
-
775
- if isinstance(fig,type(None)):
776
- fig=go.Figure()
777
-
778
- fig = viz_landmarks(verts,
779
- landmark_dict,
780
- title="Visualize landmarks",
781
- fig=fig,
782
- show=show,
783
- name="smpl")
784
-
785
- if show:
786
- fig.show()
787
- else:
788
- return fig
789
-
790
-
791
- def viz_smplx_landmarks(fig=None,show=True,title="SMPLX landmarks"):
792
- """
793
- Visualize smplx landmarks.
794
- """
795
-
796
- verts = smplx.SMPLX("data/smplx",ext="pkl").v_template
797
- landmark_dict = SMPLX_LANDMARK_INDICES
798
-
799
- if isinstance(fig,type(None)):
800
- fig=go.Figure()
801
-
802
- fig = viz_landmarks(verts,
803
- landmark_dict,
804
- title="Visualize landmarks",
805
- fig=fig,
806
- show=show,
807
- name="smplx")
808
-
809
- if show:
810
- fig.show()
811
- else:
812
- return fig
813
-
814
-
815
-
816
- if __name__ == "__main__":
817
-
818
- parser = argparse.ArgumentParser(description='Visualize body models, joints and segmentations..')
819
- parser.add_argument('--visualize_smpl_and_smplx_face_segmentation', action='store_true',
820
- help="Visualize face segmentations for smplx model.")
821
- parser.add_argument('--visualize_smpl_and_smplx_joints', action='store_true',
822
- help="visualize smpl and smplx joints on same plot.")
823
- parser.add_argument('--visualize_smpl_and_smplx_point_segmentation', action='store_true',
824
- help="visualize smpl and smplx point segmentation on two separate plots.")
825
- parser.add_argument('--visualize_smpl_and_smplx_landmarks', action='store_true',
826
- help="visualize smpl and smplx landmarks on two separate plots.")
827
- args = parser.parse_args()
828
-
829
-
830
-
831
- if args.visualize_smpl_and_smplx_face_segmentation:
832
- # mesh is not compatible with subplots so these are plotted
833
- # onto separate plots
834
- viz_smpl_face_segmentation(fig=None, show=True)
835
- viz_smplx_face_segmentation(fig=None,show=True)
836
-
837
-
838
-
839
- if args.visualize_smpl_and_smplx_joints:
840
- title = "SMPL and SMPLX joints"
841
- fig = viz_smpl_joints(visualize_body=True,
842
- fig=None,
843
- show=False,
844
- title=title)
845
- viz_smplx_joints(visualize_body=True,
846
- fig=fig,
847
- show=True,
848
- title=title)
849
-
850
- if args.visualize_smpl_and_smplx_point_segmentation:
851
- fig = make_subplots(rows=1, cols=2,
852
- specs=[[{'type': 'scene'},
853
- {'type': 'scene'}]],
854
- subplot_titles=("SMPL", "SMPLX"))
855
- title="SMPL and SMPLX point segmentation"
856
-
857
-
858
- fig_smpl = viz_smpl_point_segmentation(fig=None,show=False,title=title)
859
- fig_smplx = viz_smplx_point_segmentation(fig=None,show=False,title=title)
860
-
861
-
862
- for i in range(len(fig_smpl.data)):
863
- fig.add_trace(fig_smpl.data[i],row=1,col=1)
864
- for i in range(len(fig_smplx.data)):
865
- fig.add_trace(fig_smplx.data[i],row=1,col=2)
866
-
867
-
868
- fig.update_layout(fig_smpl.layout)
869
- fig.update_layout(scene2_aspectmode="data",
870
- showlegend=False,
871
- width=1200,
872
- height=700)
873
- fig.show()
874
-
875
- if args.visualize_smpl_and_smplx_landmarks:
876
- fig = make_subplots(rows=1, cols=2,
877
- specs=[[{'type': 'scene'},
878
- {'type': 'scene'}]],
879
- subplot_titles=("SMPL", "SMPLX"))
880
- title="SMPL and SMPLX landmarks"
881
-
882
- fig_smpl = viz_smpl_landmarks(fig=None,show=False,title=title)
883
- fig_smplx = viz_smplx_landmarks(fig=None,show=False,title=title)
884
-
885
- for i in range(len(fig_smpl.data)):
886
- fig.add_trace(fig_smpl.data[i],row=1,col=1)
887
- for i in range(len(fig_smplx.data)):
888
- fig.add_trace(fig_smplx.data[i],row=1,col=2)
889
-
890
-
891
- fig.update_layout(fig_smpl.layout)
892
- fig.update_layout(scene2_aspectmode="data",
893
- showlegend=False,
894
- width=1200,
895
- height=700)
896
- fig.show()