-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathinb.py
More file actions
4162 lines (3563 loc) · 131 KB
/
Copy pathinb.py
File metadata and controls
4162 lines (3563 loc) · 131 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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
os.environ["HSA_OVERRIDE_GFX_VERSION"] = "9.0.0" # for AMD GPU
os.environ["MKL_NUM_THREADS"] = "1"
os.environ["NUMEXPR_NUM_THREADS"] = "1"
os.environ["OMP_NUM_THREADS"] = "1"
os.environ["PYOPENGL_PLATFORM"] = "egl" # "osmesa"
import argparse
import itertools
import math
import random
import shlex
import subprocess
import textwrap
import time
from distutils.spawn import find_executable
from pathlib import Path
import cv2
cv2.setNumThreads(0)
cv2.ocl.setUseOpenCL(False)
import PIL.Image as Image
import igl
import matplotlib.pyplot as plt
import networkx as nx
import numpy as np
import optuna
import pyrender
import torch
import triangle as tr
import trimesh
from pyrender import Sampler
from pyrender.constants import GLTF
from pyrender.shader_program import ShaderProgramCache
from shapely.geometry import (
Point,
LineString,
Polygon,
)
from scipy.spatial.distance import cdist
from scipy.spatial.transform import (
Rotation,
Slerp,
)
from skimage.measure import (
label,
regionprops,
)
from torch.nn import functional as F
from simple_lama_inpainting import SimpleLama
import deform.kvf
import dino_inference
import draw
import losses
import mesh_utils
import pose_estimation
import segment
import utils
import write_utils
from skeleton import (
get_fk,
Skeleton2d,
Skeleton3d,
)
try:
from animated_drawings.model.bvh import BVH
except ModuleNotFoundError as e:
print(textwrap.dedent(
f"""
{e}.
To read bvh animation, create a symbolic link to
`animated_drawings`. directory from
`https://github.com/facebookresearch/AnimatedDrawings` in `src`
directory:
`ln -s ABS_PATH_TO_ANIMATED_DRAWINGS/animated_drawings ./src`
"""
)
)
import biskin
import fastSymDir
try:
from train_log.RIFE_HDv3 import Model
except ModuleNotFoundError as e:
print(textwrap.dedent(
f"""
{e}.
Required with the `--interactive NUM` key. For interactive
manipulations, create a symbolic link to the `model` and `trian_log`
directories from `https://github.com/hzwer/ECCV2022-RIFE` in `src`
directory:
`ln -s ABS_PATH_TO_RIFE/train_log ./src`
`ln -s ABS_PATH_TO_RIFE/model ./src`
"""
)
)
GIMP = "gimp"
GIMP_EXE = find_executable(GIMP)
if not GIMP_EXE:
print(textwrap.dedent(
f"""
`{GIMP}` not found. Install `{GIMP}` or other program for manual
annotation or provide masks with $IMG_mask.$EXT and
$IMG_occlusion_mask_pred.$EXT file names.
"""
)
)
def parse_args(args=None):
parser = argparse.ArgumentParser()
parser.add_argument(
"--img-paths",
nargs="+",
type=str,
required=True,
help="path to images",
)
parser.add_argument(
"--guidance-paths",
nargs="+",
type=str,
required=False,
help="path to guidance images",
)
parser.add_argument(
"--animation-paths",
nargs="+",
type=str,
required=False,
default=None,
help="path to bvh animations",
)
parser.add_argument(
"--frame-interpolation-model-path",
type=str,
default="./src/train_log",
help="frame interpolation model path",
)
parser.add_argument(
"--character-topology-path",
type=str,
default="./characters_topology/human_topology.json",
help="path to charachter topology",
)
parser.add_argument(
"--out-dir",
type=str,
required=True,
help="path to save results",
)
parser.add_argument(
"--pose-estimation-model-path",
type=str,
default=f"{Path('./models').resolve()}/hrn_w48_384x288.onnx",
help="pose estimation model",
)
parser.add_argument(
"--segmentation-model-path",
type=str,
default=f"{Path('./models').resolve()}/model_14_2.pth",
help="pose estimation model",
)
parser.add_argument(
"--n-steps",
type=int,
default=24,
required=False,
help="number of inbetweens",
)
parser.add_argument(
"--n-pts",
type=int,
default=1,
required=False,
help="number of sampled points along the bone",
)
parser.add_argument(
"--use-o-mask-gt",
required=False,
action="store_true",
help="use gt occlusion mask",
)
parser.add_argument(
"--inpaint-method",
type=str,
default="copy",
required=False,
choices=["copy", "cv2", "lama"],
help="inpaint method",
)
parser.add_argument(
"--deform-method",
type=str,
default="dirichlet",
required=False,
choices=["arap", "dirichlet", "kvf"],
help="defomation method",
)
parser.add_argument(
"--to-show",
required=False,
action="store_true",
help="debug",
)
parser.add_argument(
"--no-optuna",
required=False,
action="store_true",
help="optuna optimization",
)
parser.add_argument(
"--use-nearest",
required=False,
action="store_true",
help="use nearest sampler instead of linear in gl",
)
parser.add_argument(
"--interactive",
required=False,
type=int,
default=0,
help="intercative",
)
parser.add_argument(
"--epsilon",
type=float,
default=2,
required=False,
help="simplify contours",
)
parser.add_argument(
"--touch-pixels",
type=int,
default=2,
required=False,
help="touching pixels",
)
parser.add_argument(
"--seed",
required=False,
type=int,
default=31459,
help="random seed",
)
args = parser.parse_args(args)
return args
def normalize_keypoints(kpts, wh, root=0):
kpts = kpts - root
kpts = 2 * kpts / wh
return kpts
def denormalize_keypoints(kpts, wh, root=0):
kpts = wh * kpts / 2
kpts = kpts + root
return kpts
def get_uv_param(verts_normalized, root, wh, uv_wh):
uv_param = denormalize_keypoints(verts_normalized, wh, root)
uv_param = np.stack(
[
uv_param[:, 0] / uv_wh,
1 - uv_param[:, 1] / uv_wh,
]
).T
return uv_param
def get_trimesh(v, t, uv, img):
h, w = img.shape[:2]
assert h == w
visual = trimesh.visual.texture.TextureVisuals(
uv=uv,
image=Image.fromarray(img),
)
mesh = trimesh.Trimesh(
np.pad(v, ((0, 0), (0, 1))),
t,
visual=visual,
process=False,
validate=False,
)
return mesh
def get_pad_center(t, wh):
d = (2 * t - wh).round().astype("int")
x, y = t
w, h = wh
if x >= w // 2: # x
if y >= h // 2: # y
assert (d >= 0).all()
pad = (
[0, d[1]],
[0, d[0]],
)
else:
assert d[1] <= 0, d[1]
assert d[0] >= 0
pad = (
[abs(d[1]), 0],
[0, d[0]],
)
else:
if y >= h // 2: # y
assert d[1] >= 0
assert d[0] <= 0
pad = (
[0, d[1]],
[abs(d[0]), 0],
)
else:
assert (d <= 0).all()
pad = (
[abs(d[1]), 0],
[abs(d[0]), 0],
)
return pad
def center_image(img, root, mod=4, mode="symmetric"):
#print(f"Original {img.shape=}")
wh_img = np.array(img.shape[:2][::-1])
root = root.round()
pad = get_pad_center(root, wh_img)
pad_ch = ((0, 0), ) * (img.ndim == 3)
img = np.pad(
img,
pad + pad_ch,
#mode="edge",
mode=mode,
)
#print(f"After center {img.shape=}")
h, w = img.shape[:2]
a = abs(h - w) // 2
b = abs(h - w) % 2
if h > w:
img = np.pad(
img,
((0, 0), (a, a + b)) + pad_ch,
#mode="edge",
mode=mode,
)
elif h < w:
img = np.pad(
img,
((a, a + b), (0, 0)) + pad_ch,
#mode="edge",
mode=mode,
)
#print(f"After square {img.shape=}")
h, w = img.shape[:2]
assert h == w
wh = h
wh_img = max(wh_img)
assert wh >= wh_img, f"Centered image must not be less then original. {wh=} {wh_img}"
#print(f"{wh=} {wh_img=}")
# https://www.google.com/search?q=texture+is+divisible+by+4&newwindow=1&sca_esv=596270913&sxsrf=AM9HkKlax1j7kSewy-M18MD8ntHc-XlwtA%3A1704585258319&ei=KuiZZdjzEs6f5NoPw4WIiA8&ved=0ahUKEwjYsL72-smDAxXOD1kFHcMCAvEQ4dUDCBA&uact=5&oq=texture+is+divisible+by+4&gs_lp=Egxnd3Mtd2l6LXNlcnAiGXRleHR1cmUgaXMgZGl2aXNpYmxlIGJ5IDRI2ylQoQRYjSdwAXgBkAEAmAFjoAGXCKoBAjEyuAEDyAEA-AEBwgIEECMYJ8ICBxAjGLACGCfiAwQYACBBiAYB&sclient=gws-wiz-serp
# https://stackoverflow.com/questions/57346317/opengl-greyscale-texture-data-layout-doesnt-match-when-the-dimensions-arent-d
# https://support.lumion.com/hc/en-us/articles/7764034284188-What-do-the-properties-of-the-Standard-Material-mean-in-Lumion-2023-
# https://www.khronos.org/opengl/wiki/Texture
if wh_img % mod != 0:
wh_img = (wh_img // mod + 1) * mod
d = wh - wh_img
if d > 0:
__wh = (wh % mod)
_wh = __wh // 2
img = np.pad(
img,
((_wh, _wh + (__wh % 2)), (_wh, _wh + (__wh % 2))) + pad_ch,
mode=mode,
#mode="edge",
)
#a = d // 2 # 8 (20), 4(25)
#b = d % 2 # 8 (20), 4(25)
#img = img[a:-a - b, a:-a - b].copy()
#print(f"After crop to {mod} {img.shape=}")
elif d < 0:
new_h = (wh // mod + 1) * mod
d = new_h - wh
a = d // 2 # 8(20), 4(25)
b = d % 2 # 8(20), 4(25)
img = np.pad(
img,
((a, a + b), (a, a + b)) + pad_ch,
mode=mode,
#mode="edge",
)
#print(f"After pad to {mod} {img.shape=}")
#assert img.shape[0] == img.shape[1] == wh_img, (img.shape, wh_img)
#print(f"Final {img.shape=}")
_wh = 16
img = np.pad(
img,
((_wh, _wh), (_wh, _wh)) + pad_ch,
mode=mode,
#mode="edge",
)
return img, wh_img
def copy_overlapping_mesh_hidden(V, T, T_ov_inds, unvis):
#unvis = sorted(set(unvis))
mesh_utils.check_unique(np.array(unvis))
unvis = list(unvis)
assert sorted(set(unvis)) == sorted(unvis)
mapping = dict(zip(unvis, len(V) + np.arange(len(unvis))))
T = T.copy()
for t in T_ov_inds:
T[t, 0] = mapping.get(T[t, 0], T[t, 0])
T[t, 1] = mapping.get(T[t, 1], T[t, 1])
T[t, 2] = mapping.get(T[t, 2], T[t, 2])
return unvis, T, mapping
def bones_to_verts_hierarchy(bones, skeleton_data):
if skeleton_data.kps_to_hier is None:
return
vinds = []
for i in bones:
a, b = skeleton_data.skeleton[i]
vinds.extend(
[
skeleton_data.joints.index(i)
for i in skeleton_data.kps_to_hier[skeleton_data.joints[a]]
]
)
vinds.extend(
[
skeleton_data.joints.index(i)
for i in skeleton_data.kps_to_hier[skeleton_data.joints[b]]
]
)
vinds = sorted(set(vinds))
return vinds
def cut_mesh(vertices, triangles, T_ov_inds, path, n_verts, bnd, to_show=False):
# cut mesh from boundary (path[0] must lie on the boundary)
if len(path) < 2:
return vertices, triangles, [], {}
assert len(path) > 1, "cut mesh requires more than 1 edges"
path_orig = path
# if last on boundary, then don't remove, if not remove?
#bnd = igl.boundary_loop(triangles)
is_removed = False
if path[-1] not in bnd:
is_removed = True
path = path[:-1]
T_adj_inds = [] # list of adjacent triangles' indices from `T_ov_inds` to path `path`
for t in T_ov_inds:
for i in triangles[t]:
if i in path:
T_adj_inds.append(t)
if to_show:
plt.title("cut mesh")
plt.triplot(vertices[:, 0], -vertices[:, 1], triangles)
plt.triplot(vertices[:, 0], -vertices[:, 1], triangles[T_ov_inds])
plt.scatter(
vertices[path_orig, 0],
-vertices[path_orig, 1],
color="red",
s=100,
label="path to cut",
)
if len(T_adj_inds) > 0:
plt.scatter(
vertices[triangles[np.unique(T_adj_inds)], 0],
-vertices[triangles[np.unique(T_adj_inds)], 1],
color="cyan",
s=50,
label="adjacent vertices to cut",
)
# create new vertices along path `path` and change indices in triangles
v_ov_inds, triangles, mapping = copy_overlapping_mesh_hidden(
vertices, triangles, T_adj_inds, path,
)
if to_show:
plt.scatter(
vertices[v_ov_inds, 0],
-vertices[v_ov_inds, 1],
color="blue",
s=25,
label="cut",
)
#plt.show()
#plt.close()
vertices = np.concatenate(
[
vertices,
vertices[v_ov_inds],
],
axis=0,
)
# TODO: fix new veritex indices update mapping!!!
_max_v = len(vertices)
V, T, v_ov_inds_d = mesh_utils.disentangle_single_vertices(
vertices,
triangles,
n_verts=n_verts,
#v_ov_inds=v_ov_inds,
)
if not is_removed:
assert len(v_ov_inds_d) == 0, (len(v_ov_inds_d), v_ov_inds_d)
max_v = max(mapping.values()) + 1
assert _max_v == max_v
# if type is "f" and "b" and the origin is in one point, then it is not the case!!!
assert len(set(v_ov_inds_d) & set(mapping)) == 0, (set(v_ov_inds_d) & set(mapping), v_ov_inds_d)
for i, nv in enumerate(v_ov_inds_d):
mapping[nv] = max_v + i
v_ov_inds.extend(v_ov_inds_d)
vertices = V
triangles = T
ok, d = mesh_utils.check_VT(vertices, triangles)
if not ok:
_, _, d = d
d = list(d)
if not to_show:
plt.triplot(vertices[:, 0], -vertices[:, 1], triangles)
plt.triplot(vertices[:, 0], -vertices[:, 1], triangles[T_ov_inds])
plt.scatter(vertices[path_orig, 0], -vertices[path_orig, 1], color="red", s=100)
if len(T_adj_inds) > 0:
plt.scatter(
vertices[triangles[np.unique(T_adj_inds)], 0],
-vertices[triangles[np.unique(T_adj_inds)], 1],
color="cyan",
s=50,
)
plt.scatter(vertices[d, 0], -vertices[d, 1], color="black", s=50)
plt.show()
plt.close()
raise
if to_show:
plt.gca().set_aspect("equal")
plt.legend()
plt.show()
plt.close()
return vertices, triangles, v_ov_inds, mapping
def plot_skel_cv(img, joints=None, skeleton=None, t_jun=None, joint_names=None):
blue_rgb = (85, 153, 255)
red_rgb = (255, 85, 85)
blue = blue_rgb[::-1]
red = red_rgb[::-1]
#h, w = img.shape[:2]
pt_size = int(0.005 * max(img.shape[:2]))
if joints is not None:
for x, y in joints:
x = int(x)
y = int(y)
#y = h - int(y)
cv2.circle(img, (x, y), pt_size, blue, lineType=cv2.LINE_AA, thickness=cv2.FILLED)
if skeleton is not None:
for a, b in skeleton:
if joint_names is not None and "right" in joint_names[a].lower():
color = blue#red
else:
color = blue
a = joints[a]
#a = [a[0], h - a[1]]
b = joints[b]
#b = [b[0], h - b[1]]
cv2.line(img, a, b, color, lineType=cv2.LINE_AA)
if t_jun is not None and len(t_jun) > 0:
for x, y in t_jun:
#y = h - y
cv2.circle(img, (x, y), pt_size, red, lineType=cv2.LINE_AA, thickness=cv2.FILLED)
class SkeletonData:
def __init__(self, joints, root, skeleton, parents2d, parents2d_to_kps, names, zero_inds, dj, type, kps_to_hier=None):
self.joints = joints
self.root_name = root
self.root = self.joints.index(self.root_name)
self.skeleton = skeleton
self.right_inds = [
i
for i, (a, _) in enumerate(self.skeleton)
if "right" in self.joints[a].lower()
]
self.parents2d = parents2d
self.parents2d_to_kps = parents2d_to_kps
self.names = names
assert len(self.parents2d) == len(self.parents2d_to_kps) == len(self.names)
self.zero_inds = [self.names.index(i) for i in zero_inds]
self.dj = dj
self.type = type
self.kps_to_hier = kps_to_hier
self.kps_to_skeleton = [
[
j
for j, (a, b) in enumerate(self.skeleton)
if self.joints[a] == kp or self.joints[b] == kp
]
for kp in self.joints
]
self.g = nx.Graph()
self.g.add_edges_from(self.skeleton)
self.end_effectors_inds = [n for n in self.g.nodes if self.g.degree[n] == 1]
print(f"{self.end_effectors_inds=}")
self.adjacent = [n for n in self.g.nodes if self.g.degree[n] > 2]
print(f"{self.adjacent=}")
self.end_effector2par = {}
if len(self.adjacent) > 0:
self.end_effector2par = {
v: min(
(
nx.shortest_path(self.g, v, t)
for t in self.adjacent
),
key=len,
)[1:]
for v in self.end_effectors_inds
}
self.manifold_joints = [
nx.shortest_path(self.g, v, ee)[1]
for v in self.adjacent
for ee in self.end_effectors_inds
]
self.manifold_joints = set(
p
for p in self.manifold_joints
if self.is_symmetric_joint(p)
)
self.manifold_bones = set(
self.get_bone(v, u)
for v in self.manifold_joints
for u in self.g.neighbors(v)
)
def is_symmetric_joint(self, joint_ind):
joint = self.joints[joint_ind].lower()
return "left" in joint or "right" in joint
def get_symmetric_joint(self, joint_ind):
if not self.is_symmetric_joint(joint_ind):
return joint_ind
joint = self.joints[joint_ind].lower()
if "left" in joint:
joint_sym = self.joints[joint_ind].lower().replace("left", "right")
else:
joint_sym = self.joints[joint_ind].lower().replace("right", "left")
joint_sym_ind, = [i for i, joint in enumerate(self.joints) if joint.lower == joint_sym]
return joint_sym_ind
def get_bone(self, a, b):
try:
b = self.skeleton.index([a, b])
except ValueError:
b = self.skeleton.index([b, a])
return b
def is_symmetric_bone(self, a, b):
return self.is_symmetric_joint(a) or self.is_symmetric_joint(b)
@classmethod
def from_json(cls, path):
meta = write_utils.load_json(path)
c = cls(
joints=meta["joints"],
root=meta["root"],
skeleton=meta["skeleton"],
parents2d=meta["parents2d"],
parents2d_to_kps=meta["parents2d_to_kps"],
names=meta["names"],
zero_inds=meta["zero_inds"],
dj=meta["dj"],
type=meta["type"],
kps_to_hier=meta.get("kps_to_hier", None),
)
return c
def inpaint_lama(texture, mask):
if not mask.any():
return texture
uv_wh = texture.shape[0]
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
simple_lama = SimpleLama(device)
image = Image.fromarray(texture)
mask = Image.fromarray(mask).convert("L")
result = simple_lama(image, mask)
texture = np.array(result)
if texture.shape[0] != uv_wh: # w
texture = texture[:uv_wh, :uv_wh].copy()
return texture
class Inbetweener:
def __init__(
self,
skeleton_data,
img,
mask,
o_mask,
keypoints_2d,
z_order,
bone_to_top,
t_jun,
inpaint_method="copy",
epsilon=2,
n_pts=1,
to_show=False,
device="cpu",
nearest=False,
):
self.skeleton_data = skeleton_data
self.nearest = nearest
self.inpaint_method = inpaint_method
self.img = img
self.mask = mask
self.root = keypoints_2d[self.skeleton_data.root].copy()
self.wh = max(self.img.shape[:2])
# todo enlarge texture due to croping some body parts
self.texture, self.wh_skeleton = center_image(self.img, self.root)
assert self.texture.shape[0] == self.texture.shape[1], f"Texture must be squared. {self.texture.shape=}"
assert self.texture.shape[0] % 4 == 0, f"Texture must be divisible by 4. {self.texture.shape=}"
self.o_mask_texture, _ = center_image(o_mask, self.root)
self.uv_wh = max(self.texture.shape[:2])
self.z_order = z_order
self.epsilon = epsilon
self.omeshes = []
self.omesh_ind = 0
for _t_jun in [[]]:
if len(_t_jun) == 0:
_o_mask = o_mask
else:
raise
self.omeshes.append(
mesh_utils.get_overlapping_mesh(
mask,
_o_mask,
keypoints_2d,
bone_to_top,
t_jun,
skeleton_data=self.skeleton_data,
n_pts=n_pts,
epsilon=self.epsilon,
to_show=to_show,
)
)
self._set_vt()
self.device = device
self._path = {"visible": [], "hidden": []}
self.saved_mesh: list = []
#self.render(
# out_path=Path("./TEST/c"),
#)
#raise
def _set_vt(self):
self.n_verts = len(self.omesh.vertices)
self.vertices = normalize_keypoints(
self.omesh.vertices,
self.wh,
root=self.root,
)
self.triangles = self.omesh.triangles.copy()
self.mapping = self.omesh.mapping.copy()
self.set_trimesh(self.vertices)
self._recalculate_skinning(force_rewrite=True)
@property
def omesh(self):
return self.omeshes[self.omesh_ind]
@property
def skeleton(self):
return self.vertices[self.omesh.vert_to_skel].copy()
@skeleton.setter
def skeleton(self, skeleton):
self.vertices[self.omesh.vert_to_skel] = skeleton.copy()
def set_trimesh(self, vertices):
self.vertices = vertices.copy()
self.uv = get_uv_param(
self.vertices,
#root=[self.root[0] - self.uv_wh // 2, self.root[1] - self.uv_wh // 2],
#root=self.root,
root=[self.uv_wh // 2 + 0.5, self.uv_wh // 2 + 0.5],
wh=self.wh,
uv_wh=self.uv_wh,
)
self.mesh = get_trimesh(
self.vertices,
self.triangles,
self.uv,
self.texture,
)
def prepare_mesh_for_render(self, deforms=None, out_path=None, interactive=False, rotpi=False):
mesh = self.mesh.copy()
if deforms is None:
deforms = np.zeros_like(mesh.vertices)
if deforms.shape[-1] != 3:
#deforms = np.pad(deforms, ((0, 0), (0, 1)))
deforms = self._add_z(deforms, 1, np.zeros(len(deforms)))
vert_o = mesh.vertices.copy()
mesh.vertices = mesh.vertices + deforms
if not interactive:
tr = trimesh.transformations.translation_matrix(-mesh.vertices[self.omesh.vert_to_skel[self.skeleton_data.root]])
mesh.apply_transform(tr)
rot = trimesh.transformations.rotation_matrix(np.pi, [1, 0, 0])
if rotpi:
mesh.apply_transform(trimesh.transformations.rotation_matrix(np.pi, [0, 1, 0]))
mesh.invert()
if out_path is not None:
m = trimesh.Trimesh(
mesh.vertices,
mesh.faces,
process=False,
validate=False,
)
color = np.array(m.visual.vertex_colors)
color[:] = [233, 233, 233, 255]
red = [255, 0, 0, 255]
#color[self.omesh.vert_to_skel] = red
if hasattr(self, "_path"):
green = [0, 255, 0, 255]
blue = [0, 0, 255, 255]
for ci, _path in self._path.items():
if len(_path) > 0:
if ci == "visible":
color[_path] = green
elif ci == "hidden":
color[_path] = blue
face_colors = np.full(
(len(self.triangles), 4),
fill_value=233,
dtype="uint8",
)
face_colors[:, 3] = 255
red = np.full(
(len(self.triangles), 3),
fill_value=0,
dtype="uint8",
)
red[:, 0] = 255
energy = self._verts_inds_bad_quality(
mesh.vertices,
mesh.faces,
V_old=vert_o,
)
np.savetxt(out_path.with_name(f"{out_path.stem}_path_deformation"), energy)
x = np.clip((energy - 4.0) / 0.5, 0, 1)
x = x[:, None] # [N, 1]
face_colors[:, :3] = (
(1 - x) * face_colors[:, :3] + x * red
).astype("uint8")
m.visual.face_colors = face_colors
m.apply_transform(rot)
m.export(out_path.with_suffix(".ply"))
#m.visual.face_colors = None
m.visual.vertex_colors = color
m.export(out_path.with_name(f"{out_path.stem}_path.ply"))
mesh.apply_transform(rot)
if out_path is not None:
mesh.export(out_path.with_suffix(".glb"))
return mesh
def render(
self,
deforms=None,
out_path=None,
bg_color=None,
viewport_width=512,
viewport_height=512,
uv=None,
texture=None,
layer=None,
smooth=False,
interactive=False,
rotpi=False,
):
if out_path is not None:
if isinstance(out_path, str):
out_path = Path(out_path)
mesh = self.prepare_mesh_for_render(
deforms=deforms,
out_path=out_path,
interactive=interactive,
rotpi=rotpi,
)
#vertices = mesh.vertices
#assert np.allclose(
# vertices[self.omesh.vert_to_skel[9]][:2],
# [0, 0],
#), (vertices[self.omesh.vert_to_skel[9]][:2], "hips must be centered")
mesh = pyrender.Mesh.from_trimesh(
mesh,
smooth=smooth,
)