-
Notifications
You must be signed in to change notification settings - Fork 28
/
train_gui.py
executable file
·1889 lines (1669 loc) · 101 KB
/
train_gui.py
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
#
# Copyright (C) 2023, Inria
# GRAPHDECO research group, https://team.inria.fr/graphdeco
# All rights reserved.
#
# This software is free for non-commercial, research and evaluation use
# under the terms of the LICENSE.md file.
#
# For inquiries contact [email protected]
#
import os
# os.environ['PYOPENGL_PLATFORM'] = 'osmesa'
import time
import torch
from random import randint
from utils.loss_utils import l1_loss, ssim
from gaussian_renderer import render, network_gui, render_flow
import sys
from scene import Scene, GaussianModel, DeformModel
from utils.general_utils import safe_state, get_linear_noise_func
import uuid
import tqdm
from argparse import ArgumentParser, Namespace
from arguments import ModelParams, PipelineParams, OptimizationParams
from train import training_report
import math
from cam_utils import OrbitCamera
import numpy as np
import dearpygui.dearpygui as dpg
import imageio
import datetime
from PIL import Image
from train_gui_utils import DeformKeypoints
from scipy.spatial.transform import Rotation as R
try:
from torch.utils.tensorboard import SummaryWriter
TENSORBOARD_FOUND = True
except ImportError:
TENSORBOARD_FOUND = False
def getProjectionMatrix(znear, zfar, fovX, fovY):
tanHalfFovY = math.tan((fovY / 2))
tanHalfFovX = math.tan((fovX / 2))
P = torch.zeros(4, 4)
z_sign = 1.0
P[0, 0] = 1 / tanHalfFovX
P[1, 1] = 1 / tanHalfFovY
P[3, 2] = z_sign
P[2, 2] = z_sign * zfar / (zfar - znear)
P[2, 3] = -(zfar * znear) / (zfar - znear)
return P
def landmark_interpolate(landmarks, steps, step, interpolation='log'):
stage = (step >= np.array(steps)).sum()
if stage == len(steps):
return max(0, landmarks[-1])
elif stage == 0:
return 0
else:
ldm1, ldm2 = landmarks[stage-1], landmarks[stage]
if ldm2 <= 0:
return 0
step1, step2 = steps[stage-1], steps[stage]
ratio = (step - step1) / (step2 - step1)
if interpolation == 'log':
return np.exp(np.log(ldm1) * (1 - ratio) + np.log(ldm2) * ratio)
elif interpolation == 'linear':
return ldm1 * (1 - ratio) + ldm2 * ratio
else:
print(f'Unknown interpolation type: {interpolation}')
raise NotImplementedError
def getWorld2View2(R, t, translate=np.array([.0, .0, .0]), scale=1.0):
Rt = np.zeros((4, 4))
Rt[:3, :3] = R.transpose()
Rt[:3, 3] = t
Rt[3, 3] = 1.0
C2W = np.linalg.inv(Rt)
cam_center = C2W[:3, 3]
cam_center = (cam_center + translate) * scale
C2W[:3, 3] = cam_center
Rt = np.linalg.inv(C2W)
return np.float32(Rt)
class MiniCam:
def __init__(self, c2w, width, height, fovy, fovx, znear, zfar, fid):
# c2w (pose) should be in NeRF convention.
self.image_width = width
self.image_height = height
self.FoVy = fovy
self.FoVx = fovx
self.znear = znear
self.zfar = zfar
self.fid = fid
self.c2w = c2w
w2c = np.linalg.inv(c2w)
# rectify...
w2c[1:3, :3] *= -1
w2c[:3, 3] *= -1
self.world_view_transform = torch.tensor(w2c).transpose(0, 1).cuda().float()
self.projection_matrix = (
getProjectionMatrix(
znear=self.znear, zfar=self.zfar, fovX=self.FoVx, fovY=self.FoVy
)
.transpose(0, 1)
.cuda().float()
)
self.full_proj_transform = self.world_view_transform @ self.projection_matrix
self.camera_center = -torch.tensor(c2w[:3, 3]).cuda()
def reset_extrinsic(self, R, T):
self.world_view_transform = torch.tensor(getWorld2View2(R, T)).transpose(0, 1).cuda()
self.full_proj_transform = (
self.world_view_transform.unsqueeze(0).bmm(self.projection_matrix.unsqueeze(0))).squeeze(0)
self.camera_center = self.world_view_transform.inverse()[3, :3]
class GUI:
def __init__(self, args, dataset, opt, pipe, testing_iterations, saving_iterations) -> None:
self.dataset = dataset
self.args = args
self.opt = opt
self.pipe = pipe
self.testing_iterations = testing_iterations
self.saving_iterations = saving_iterations
if self.opt.progressive_train:
self.opt.iterations_node_sampling = max(self.opt.iterations_node_sampling, int(self.opt.progressive_stage_steps / self.opt.progressive_stage_ratio))
self.opt.iterations_node_rendering = max(self.opt.iterations_node_rendering, self.opt.iterations_node_sampling + 2000)
print(f'Progressive trian is on. Adjusting the iterations node sampling to {self.opt.iterations_node_sampling} and iterations node rendering {self.opt.iterations_node_rendering}')
self.tb_writer = prepare_output_and_logger(dataset)
self.deform = DeformModel(K=self.dataset.K, deform_type=self.dataset.deform_type, is_blender=self.dataset.is_blender, skinning=self.args.skinning, hyper_dim=self.dataset.hyper_dim, node_num=self.dataset.node_num, pred_opacity=self.dataset.pred_opacity, pred_color=self.dataset.pred_color, use_hash=self.dataset.use_hash, hash_time=self.dataset.hash_time, d_rot_as_res=self.dataset.d_rot_as_res and not self.dataset.d_rot_as_rotmat, local_frame=self.dataset.local_frame, progressive_brand_time=self.dataset.progressive_brand_time, with_arap_loss=not self.opt.no_arap_loss, max_d_scale=self.dataset.max_d_scale, enable_densify_prune=self.opt.node_enable_densify_prune, is_scene_static=dataset.is_scene_static)
deform_loaded = self.deform.load_weights(dataset.model_path, iteration=-1)
self.deform.train_setting(opt)
gs_fea_dim = self.deform.deform.node_num if args.skinning and self.deform.name == 'node' else self.dataset.hyper_dim
self.gaussians = GaussianModel(dataset.sh_degree, fea_dim=gs_fea_dim, with_motion_mask=self.dataset.gs_with_motion_mask)
self.scene = Scene(dataset, self.gaussians, load_iteration=-1)
self.gaussians.training_setup(opt)
if self.deform.name == 'node' and not deform_loaded:
if not self.dataset.is_blender:
if self.opt.random_init_deform_gs:
num_pts = 100_000
print(f"Generating random point cloud ({num_pts})...")
xyz = torch.rand((num_pts, 3)).float().cuda() * 2 - 1
mean, scale = self.gaussians.get_xyz.mean(dim=0), self.gaussians.get_xyz.std(dim=0).mean() * 3
xyz = xyz * scale + mean
self.deform.deform.init(init_pcl=xyz, force_init=True, opt=self.opt, as_gs_force_with_motion_mask=self.dataset.as_gs_force_with_motion_mask, force_gs_keep_all=True)
else:
print('Initialize nodes with COLMAP point cloud.')
self.deform.deform.init(init_pcl=self.gaussians.get_xyz, force_init=True, opt=self.opt, as_gs_force_with_motion_mask=self.dataset.as_gs_force_with_motion_mask, force_gs_keep_all=self.dataset.init_isotropic_gs_with_all_colmap_pcl)
else:
print('Initialize nodes with Random point cloud.')
self.deform.deform.init(init_pcl=self.gaussians.get_xyz, force_init=True, opt=self.opt, as_gs_force_with_motion_mask=False, force_gs_keep_all=args.skinning)
bg_color = [1, 1, 1] if dataset.white_background else [0, 0, 0]
self.background = torch.tensor(bg_color, dtype=torch.float32, device="cuda")
self.iter_start = torch.cuda.Event(enable_timing=True)
self.iter_end = torch.cuda.Event(enable_timing=True)
self.iteration = 1 if self.scene.loaded_iter is None else self.scene.loaded_iter
self.iteration_node_rendering = 1 if self.scene.loaded_iter is None else self.opt.iterations_node_rendering
self.viewpoint_stack = None
self.ema_loss_for_log = 0.0
self.best_psnr = 0.0
self.best_ssim = 0.0
self.best_ms_ssim = 0.0
self.best_lpips = np.inf
self.best_alex_lpips = np.inf
self.best_iteration = 0
self.progress_bar = tqdm.tqdm(range(opt.iterations), desc="Training progress")
self.smooth_term = get_linear_noise_func(lr_init=0.1, lr_final=1e-15, lr_delay_mult=0.01, max_steps=20000)
# For UI
self.visualization_mode = 'RGB'
self.gui = args.gui # enable gui
self.W = args.W
self.H = args.H
self.cam = OrbitCamera(args.W, args.H, r=args.radius, fovy=args.fovy)
self.vis_scale_const = None
self.mode = "render"
self.seed = "random"
self.buffer_image = np.ones((self.W, self.H, 3), dtype=np.float32)
self.training = False
self.video_speed = 1.
# For Animation
self.animation_time = 0.
self.is_animation = False
self.need_update_overlay = False
self.buffer_overlay = None
self.animation_trans_bias = None
self.animation_rot_bias = None
self.animation_scaling_bias = None
self.animate_tool = None
self.is_training_animation_weight = False
self.is_training_motion_analysis = False
self.motion_genmodel = None
self.motion_animation_d_values = None
self.showing_overlay = True
self.should_save_screenshot = False
self.should_vis_trajectory = False
self.screenshot_id = 0
self.screenshot_sv_path = f'./screenshot/' + datetime.datetime.now().strftime('%Y-%m-%d')
self.traj_overlay = None
self.vis_traj_realtime = False
self.last_traj_overlay_type = None
self.view_animation = True
self.n_rings_N = 2
# Use ARAP or Generative Model to Deform
self.deform_mode = "arap_iterative"
self.should_render_customized_trajectory = False
self.should_render_customized_trajectory_spiral = False
if self.gui:
dpg.create_context()
self.register_dpg()
self.test_step()
def animation_initialize(self, use_traj=True):
from lap_deform import LapDeform
gaussians = self.deform.deform.as_gaussians
fid = torch.tensor(self.animation_time).cuda().float()
time_input = fid.unsqueeze(0).expand(gaussians.get_xyz.shape[0], -1)
values = self.deform.deform.node_deform(t=time_input)
trans = values['d_xyz']
pcl = gaussians.get_xyz + trans
if use_traj:
print('Trajectory analysis!')
t_samp_num = 16
t_samp = torch.linspace(0, 1, t_samp_num).cuda().float()
time_input = t_samp[None, :, None].expand(gaussians.get_xyz.shape[0], -1, 1)
trajectory = self.deform.deform.node_deform(t=time_input)['d_xyz'] + gaussians.get_xyz[:, None]
else:
trajectory = None
self.animate_init_values = values
self.animate_tool = LapDeform(init_pcl=pcl, K=4, trajectory=trajectory, node_radius=self.deform.deform.node_radius.detach())
self.keypoint_idxs = []
self.keypoint_3ds = []
self.keypoint_labels = []
self.keypoint_3ds_delta = []
self.keypoint_idxs_to_drag = []
self.deform_keypoints = DeformKeypoints()
self.animation_trans_bias = None
self.animation_rot_bias = None
self.buffer_overlay = None
print('Initialize Animation Model with %d control nodes' % len(pcl))
def animation_reset(self):
self.animate_tool.reset()
self.keypoint_idxs = []
self.keypoint_3ds = []
self.keypoint_labels = []
self.keypoint_3ds_delta = []
self.keypoint_idxs_to_drag = []
self.deform_keypoints = DeformKeypoints()
self.animation_trans_bias = None
self.animation_rot_bias = None
self.buffer_overlay = None
self.motion_animation_d_values = None
print('Reset Animation Model ...')
def __del__(self):
if self.gui:
dpg.destroy_context()
def register_dpg(self):
### register texture
with dpg.texture_registry(show=False):
dpg.add_raw_texture(
self.W,
self.H,
self.buffer_image,
format=dpg.mvFormat_Float_rgb,
tag="_texture",
)
### register window
# the rendered image, as the primary window
with dpg.window(
tag="_primary_window",
width=self.W,
height=self.H,
pos=[0, 0],
no_move=True,
no_title_bar=True,
no_scrollbar=True,
):
# add the texture
dpg.add_image("_texture")
# dpg.set_primary_window("_primary_window", True)
# control window
with dpg.window(
label="Control",
tag="_control_window",
width=600,
height=self.H,
pos=[self.W, 0],
no_move=True,
no_title_bar=True,
):
# button theme
with dpg.theme() as theme_button:
with dpg.theme_component(dpg.mvButton):
dpg.add_theme_color(dpg.mvThemeCol_Button, (23, 3, 18))
dpg.add_theme_color(dpg.mvThemeCol_ButtonHovered, (51, 3, 47))
dpg.add_theme_color(dpg.mvThemeCol_ButtonActive, (83, 18, 83))
dpg.add_theme_style(dpg.mvStyleVar_FrameRounding, 5)
dpg.add_theme_style(dpg.mvStyleVar_FramePadding, 3, 3)
# timer stuff
with dpg.group(horizontal=True):
dpg.add_text("Infer time: ")
dpg.add_text("no data", tag="_log_infer_time")
def callback_setattr(sender, app_data, user_data):
setattr(self, user_data, app_data)
# init stuff
with dpg.collapsing_header(label="Initialize", default_open=True):
# seed stuff
def callback_set_seed(sender, app_data):
self.seed = app_data
self.seed_everything()
dpg.add_input_text(
label="seed",
default_value=self.seed,
on_enter=True,
callback=callback_set_seed,
)
# input stuff
def callback_select_input(sender, app_data):
# only one item
for k, v in app_data["selections"].items():
dpg.set_value("_log_input", k)
self.load_input(v)
self.need_update = True
with dpg.file_dialog(
directory_selector=False,
show=False,
callback=callback_select_input,
file_count=1,
tag="file_dialog_tag",
width=700,
height=400,
):
dpg.add_file_extension("Images{.jpg,.jpeg,.png}")
with dpg.group(horizontal=True):
dpg.add_button(
label="input",
callback=lambda: dpg.show_item("file_dialog_tag"),
)
dpg.add_text("", tag="_log_input")
# save current model
with dpg.group(horizontal=True):
dpg.add_text("Visualization: ")
def callback_vismode(sender, app_data, user_data):
self.visualization_mode = user_data
dpg.add_button(
label="RGB",
tag="_button_vis_rgb",
callback=callback_vismode,
user_data='RGB',
)
dpg.bind_item_theme("_button_vis_rgb", theme_button)
def callback_vis_traj_realtime():
self.vis_traj_realtime = not self.vis_traj_realtime
if not self.vis_traj_realtime:
self.traj_coor = None
print('Visualize trajectory: ', self.vis_traj_realtime)
dpg.add_button(
label="Traj",
tag="_button_vis_traj",
callback=callback_vis_traj_realtime,
)
dpg.bind_item_theme("_button_vis_traj", theme_button)
dpg.add_button(
label="MotionMask",
tag="_button_vis_motion_mask",
callback=callback_vismode,
user_data='MotionMask',
)
dpg.bind_item_theme("_button_vis_motion_mask", theme_button)
dpg.add_button(
label="NodeMotion",
tag="_button_vis_node_motion",
callback=callback_vismode,
user_data='MotionMask_Node',
)
dpg.bind_item_theme("_button_vis_node_motion", theme_button)
dpg.add_button(
label="Node",
tag="_button_vis_node",
callback=callback_vismode,
user_data='Node',
)
dpg.bind_item_theme("_button_vis_node", theme_button)
dpg.add_button(
label="Dynamic",
tag="_button_vis_Dynamic",
callback=callback_vismode,
user_data='Dynamic',
)
dpg.bind_item_theme("_button_vis_Dynamic", theme_button)
dpg.add_button(
label="Static",
tag="_button_vis_Static",
callback=callback_vismode,
user_data='Static',
)
dpg.bind_item_theme("_button_vis_Static", theme_button)
with dpg.group(horizontal=True):
dpg.add_text("Scale Const: ")
def callback_vis_scale_const(sender):
self.vis_scale_const = 10 ** dpg.get_value(sender)
self.need_update = True
dpg.add_slider_float(
label="Log vis_scale_const (For debugging)",
default_value=-3,
max_value=-.5,
min_value=-5,
callback=callback_vis_scale_const,
)
# save current model
with dpg.group(horizontal=True):
dpg.add_text("Temporal Speed: ")
self.video_speed = 1.
def callback_speed_control(sender):
self.video_speed = 10 ** dpg.get_value(sender)
self.need_update = True
dpg.add_slider_float(
label="Play speed",
default_value=0.,
max_value=3.,
min_value=-3.,
callback=callback_speed_control,
)
# save current model
with dpg.group(horizontal=True):
dpg.add_text("Save: ")
def callback_save(sender, app_data, user_data):
print("\n[ITER {}] Saving Gaussians".format(self.iteration))
self.scene.save(self.iteration)
self.deform.save_weights(self.args.model_path, self.iteration)
dpg.add_button(
label="model",
tag="_button_save_model",
callback=callback_save,
user_data='model',
)
dpg.bind_item_theme("_button_save_model", theme_button)
def callback_screenshot(sender, app_data):
self.should_save_screenshot = True
dpg.add_button(
label="screenshot", tag="_button_screenshot", callback=callback_screenshot
)
dpg.bind_item_theme("_button_screenshot", theme_button)
def callback_render_traj(sender, app_data):
self.should_render_customized_trajectory = True
dpg.add_button(
label="render_traj", tag="_button_render_traj", callback=callback_render_traj
)
dpg.bind_item_theme("_button_render_traj", theme_button)
def callback_render_traj(sender, app_data):
self.should_render_customized_trajectory_spiral = not self.should_render_customized_trajectory_spiral
if self.should_render_customized_trajectory_spiral:
dpg.configure_item("_button_render_traj_spiral", label="camera")
else:
dpg.configure_item("_button_render_traj_spiral", label="spiral")
dpg.add_button(
label="spiral", tag="_button_render_traj_spiral", callback=callback_render_traj
)
dpg.bind_item_theme("_button_render_traj_spiral", theme_button)
def callback_cache_nn(sender, app_data):
self.deform.deform.cached_nn_weight = not self.deform.deform.cached_nn_weight
print(f'Cached nn weight for higher rendering speed: {self.deform.deform.cached_nn_weight}')
dpg.add_button(
label="cache_nn", tag="_button_cache_nn", callback=callback_cache_nn
)
dpg.bind_item_theme("_button_cache_nn", theme_button)
# training stuff
with dpg.collapsing_header(label="Train", default_open=True):
# lr and train button
with dpg.group(horizontal=True):
dpg.add_text("Train: ")
def callback_train(sender, app_data):
if self.training:
self.training = False
dpg.configure_item("_button_train", label="start")
else:
# self.prepare_train()
self.training = True
dpg.configure_item("_button_train", label="stop")
dpg.add_button(
label="start", tag="_button_train", callback=callback_train
)
dpg.bind_item_theme("_button_train", theme_button)
def callback_save_deform_kpt(sender, app_data):
from utils.pickle_utils import save_obj
self.deform_keypoints.t = self.animation_time
save_obj(path=self.args.model_path+'/deform_kpt.pickle', obj=self.deform_keypoints)
print('Save kpt done!')
dpg.add_button(
label="save_deform_kpt", tag="_button_save_deform_kpt", callback=callback_save_deform_kpt
)
dpg.bind_item_theme("_button_save_deform_kpt", theme_button)
def callback_load_deform_kpt(sender, app_data):
from utils.pickle_utils import load_obj
self.deform_keypoints = load_obj(path=self.args.model_path+'/deform_kpt.pickle')
self.animation_time = self.deform_keypoints.t
with torch.no_grad():
animated_pcl, quat, ani_d_scaling = self.animate_tool.deform_arap(handle_idx=self.deform_keypoints.get_kpt_idx(), handle_pos=self.deform_keypoints.get_deformed_kpt_np(), return_R=True)
self.animation_trans_bias = animated_pcl - self.animate_tool.init_pcl
self.animation_rot_bias = quat
self.animation_scaling_bias = ani_d_scaling
self.need_update_overlay = True
print('Load kpt done!')
dpg.add_button(
label="load_deform_kpt", tag="_button_load_deform_kpt", callback=callback_load_deform_kpt
)
dpg.bind_item_theme("_button_load_deform_kpt", theme_button)
with dpg.group(horizontal=True):
dpg.add_text("", tag="_log_train_psnr")
with dpg.group(horizontal=True):
dpg.add_text("", tag="_log_train_log")
# rendering options
with dpg.collapsing_header(label="Rendering", default_open=True):
# mode combo
def callback_change_mode(sender, app_data):
self.mode = app_data
self.need_update = True
dpg.add_combo(
("render", "depth", "alpha", "normal_dep"),
label="mode",
default_value=self.mode,
callback=callback_change_mode,
)
# fov slider
def callback_set_fovy(sender, app_data):
self.cam.fovy = np.deg2rad(app_data)
self.need_update = True
dpg.add_slider_int(
label="FoV (vertical)",
min_value=1,
max_value=120,
format="%d deg",
default_value=np.rad2deg(self.cam.fovy),
callback=callback_set_fovy,
)
# animation options
with dpg.collapsing_header(label="Motion Editing", default_open=True):
# save current model
with dpg.group(horizontal=True):
dpg.add_text("Freeze Time: ")
def callback_animation_time(sender):
self.animation_time = dpg.get_value(sender)
self.is_animation = True
self.need_update = True
# self.animation_initialize()
dpg.add_slider_float(
label="",
default_value=0.,
max_value=1.,
min_value=0.,
callback=callback_animation_time,
)
with dpg.group(horizontal=True):
def callback_animation_mode(sender, app_data):
with torch.no_grad():
self.is_animation = not self.is_animation
if self.is_animation:
if not hasattr(self, 'animate_tool') or self.animate_tool is None:
self.animation_initialize()
dpg.add_button(
label="Play",
tag="_button_vis_animation",
callback=callback_animation_mode,
user_data='Animation',
)
dpg.bind_item_theme("_button_vis_animation", theme_button)
def callback_animation_initialize(sender, app_data):
with torch.no_grad():
self.is_animation = True
self.animation_initialize()
dpg.add_button(
label="Init Graph",
tag="_button_init_graph",
callback=callback_animation_initialize,
)
dpg.bind_item_theme("_button_init_graph", theme_button)
def callback_clear_animation(sender, app_data):
with torch.no_grad():
self.is_animation = True
self.animation_reset()
dpg.add_button(
label="Clear Graph",
tag="_button_clc_animation",
callback=callback_clear_animation,
)
dpg.bind_item_theme("_button_clc_animation", theme_button)
def callback_overlay(sender, app_data):
if self.showing_overlay:
self.showing_overlay = False
dpg.configure_item("_button_train_motion_gen", label="show overlay")
else:
self.showing_overlay = True
dpg.configure_item("_button_train_motion_gen", label="close overlay")
dpg.add_button(
label="close overlay", tag="_button_overlay", callback=callback_overlay
)
dpg.bind_item_theme("_button_overlay", theme_button)
def callback_save_ckpt(sender, app_data):
from utils.pickle_utils import save_obj
if not self.is_animation:
print('Please switch to animation mode!')
deform_keypoint_files = sorted([file for file in os.listdir(os.path.join(self.args.model_path)) if file.startswith('deform_keypoints') and file.endswith('.pickle')])
if len(deform_keypoint_files) > 0:
newest_id = int(deform_keypoint_files[-1].split('.')[0].split('_')[-1])
else:
newest_id = -1
save_obj(os.path.join(self.args.model_path, f'deform_keypoints_{newest_id+1}.pickle'), [self.deform_keypoints, self.animation_time])
dpg.add_button(
label="sv_kpt", tag="_button_save_kpt", callback=callback_save_ckpt
)
dpg.bind_item_theme("_button_save_kpt", theme_button)
with dpg.group(horizontal=True):
def callback_change_deform_mode(sender, app_data):
self.deform_mode = app_data
self.need_update = True
dpg.add_combo(
("arap_iterative", "arap_from_init"),
label="Editing Mode",
default_value=self.deform_mode,
callback=callback_change_deform_mode,
)
with dpg.group(horizontal=True):
def callback_change_n_rings_N(sender, app_data):
self.n_rings_N = int(app_data)
dpg.add_combo(
("0", "1", "2", "3", "4"),
label="n_rings",
default_value="2",
callback=callback_change_n_rings_N,
)
def callback_set_mouse_loc(sender, app_data):
if not dpg.is_item_focused("_primary_window"):
return
self.mouse_loc = np.array(app_data)
def callback_keypoint_drag(sender, app_data):
if not self.is_animation:
print("Please switch to animation mode!")
return
if not dpg.is_item_focused("_primary_window"):
return
if len(self.deform_keypoints.get_kpt()) == 0:
return
if self.animate_tool is None:
self.animation_initialize()
# 2D to 3D delta
dx = app_data[1]
dy = app_data[2]
if dpg.is_key_down(dpg.mvKey_R):
side = self.cam.rot.as_matrix()[:3, 0]
up = self.cam.rot.as_matrix()[:3, 1]
forward = self.cam.rot.as_matrix()[:3, 2]
rotvec_z = forward * np.radians(-0.05 * dx)
rot_mat = (R.from_rotvec(rotvec_z)).as_matrix()
self.deform_keypoints.set_rotation_delta(rot_mat)
else:
delta = 0.00010 * self.cam.rot.as_matrix()[:3, :3] @ np.array([dx, -dy, 0])
self.deform_keypoints.update_delta(delta)
self.need_update_overlay = True
if self.deform_mode.startswith("arap"):
with torch.no_grad():
if self.deform_mode == "arap_from_init" or self.animation_trans_bias is None:
init_verts = None
else:
init_verts = self.animation_trans_bias + self.animate_tool.init_pcl
animated_pcl, quat, ani_d_scaling = self.animate_tool.deform_arap(handle_idx=self.deform_keypoints.get_kpt_idx(), handle_pos=self.deform_keypoints.get_deformed_kpt_np(), init_verts=init_verts, return_R=True)
self.animation_trans_bias = animated_pcl - self.animate_tool.init_pcl
self.animation_rot_bias = quat
self.animation_scaling_bias = ani_d_scaling
def callback_keypoint_add(sender, app_data):
if not dpg.is_item_focused("_primary_window"):
return
##### select keypoints by shift + click
if dpg.is_key_down(dpg.mvKey_S) or dpg.is_key_down(dpg.mvKey_D) or dpg.is_key_down(dpg.mvKey_F) or dpg.is_key_down(dpg.mvKey_A) or dpg.is_key_down(dpg.mvKey_Q):
if not self.is_animation:
print("Please switch to animation mode!")
return
# Rendering the image with node gaussians to select nodes as keypoints
fid = torch.tensor(self.animation_time).cuda().float()
cur_cam = MiniCam(
self.cam.pose,
self.W,
self.H,
self.cam.fovy,
self.cam.fovx,
self.cam.near,
self.cam.far,
fid = fid
)
with torch.no_grad():
time_input = self.deform.deform.expand_time(fid)
d_values = self.deform.step(self.gaussians.get_xyz.detach(), time_input, feature=self.gaussians.feature, is_training=False, motion_mask=self.gaussians.motion_mask, camera_center=cur_cam.camera_center, node_trans_bias=self.animation_trans_bias, node_rot_bias=self.animation_rot_bias, node_scaling_bias=self.animation_scaling_bias)
gaussians = self.gaussians
d_xyz, d_rotation, d_scaling, d_opacity, d_color = d_values['d_xyz'], d_values['d_rotation'], d_values['d_scaling'], d_values['d_opacity'], d_values['d_color']
out = render(viewpoint_camera=cur_cam, pc=gaussians, pipe=self.pipe, bg_color=self.background, d_xyz=d_xyz, d_rotation=d_rotation, d_scaling=d_scaling, d_opacity=d_opacity, d_color=d_color, d_rot_as_res=self.deform.d_rot_as_res)
# Project mouse_loc to points_3d
pw, ph = int(self.mouse_loc[0]), int(self.mouse_loc[1])
d = out['depth'][0][ph, pw]
z = cur_cam.zfar / (cur_cam.zfar - cur_cam.znear) * d - cur_cam.zfar * cur_cam.znear / (cur_cam.zfar - cur_cam.znear)
uvz = torch.tensor([((pw-.5)/self.W * 2 - 1) * d, ((ph-.5)/self.H*2-1) * d, z, d]).cuda().float().view(1, 4)
p3d = (uvz @ torch.inverse(cur_cam.full_proj_transform))[0, :3]
# Pick the closest node as the keypoint
node_trans = self.deform.deform.node_deform(time_input)['d_xyz']
if self.animation_trans_bias is not None:
node_trans = node_trans + self.animation_trans_bias
nodes = self.deform.deform.nodes[..., :3] + node_trans
keypoint_idxs = torch.tensor([(p3d - nodes).norm(dim=-1).argmin()]).cuda()
if dpg.is_key_down(dpg.mvKey_A):
if True:
keypoint_idxs = self.animate_tool.add_n_ring_nbs(keypoint_idxs, n=self.n_rings_N)
keypoint_3ds = nodes[keypoint_idxs]
self.deform_keypoints.add_kpts(keypoint_3ds, keypoint_idxs)
print(f'Add kpt: {self.deform_keypoints.selective_keypoints_idx_list}')
elif dpg.is_key_down(dpg.mvKey_S):
self.deform_keypoints.select_kpt(keypoint_idxs.item())
elif dpg.is_key_down(dpg.mvKey_D):
if True:
keypoint_idxs = self.animate_tool.add_n_ring_nbs(keypoint_idxs, n=self.n_rings_N)
keypoint_3ds = nodes[keypoint_idxs]
self.deform_keypoints.add_kpts(keypoint_3ds, keypoint_idxs, expand=True)
print(f'Expand kpt: {self.deform_keypoints.selective_keypoints_idx_list}')
elif dpg.is_key_down(dpg.mvKey_F):
keypoint_idxs = torch.arange(nodes.shape[0]).cuda()
keypoint_3ds = nodes[keypoint_idxs]
self.deform_keypoints.add_kpts(keypoint_3ds, keypoint_idxs, expand=True)
print(f'Add all the control points as kpt: {self.deform_keypoints.selective_keypoints_idx_list}')
elif dpg.is_key_down(dpg.mvKey_Q):
self.deform_keypoints.select_rotation_kpt(keypoint_idxs.item())
print(f"select rotation control points: {keypoint_idxs.item()}")
self.need_update_overlay = True
self.callback_keypoint_add = callback_keypoint_add
self.callback_keypoint_drag = callback_keypoint_drag
### register camera handler
def callback_camera_drag_rotate_or_draw_mask(sender, app_data):
if not dpg.is_item_focused("_primary_window"):
return
dx = app_data[1]
dy = app_data[2]
self.cam.orbit(dx, dy)
self.need_update = True
def callback_camera_wheel_scale(sender, app_data):
if not dpg.is_item_focused("_primary_window"):
return
delta = app_data
self.cam.scale(delta)
self.need_update = True
def callback_camera_drag_pan(sender, app_data):
if not dpg.is_item_focused("_primary_window"):
return
dx = app_data[1]
dy = app_data[2]
self.cam.pan(dx, dy)
self.need_update = True
with dpg.handler_registry():
# for camera moving
dpg.add_mouse_drag_handler(
button=dpg.mvMouseButton_Left,
callback=callback_camera_drag_rotate_or_draw_mask,
)
dpg.add_mouse_wheel_handler(callback=callback_camera_wheel_scale)
dpg.add_mouse_drag_handler(
button=dpg.mvMouseButton_Middle, callback=callback_camera_drag_pan
)
dpg.add_mouse_move_handler(callback=callback_set_mouse_loc)
dpg.add_mouse_drag_handler(button=dpg.mvMouseButton_Right, callback=callback_keypoint_drag)
dpg.add_mouse_click_handler(button=dpg.mvMouseButton_Left, callback=callback_keypoint_add)
dpg.create_viewport(
title="Gaussian3D",
width=self.W + 600,
height=self.H + (45 if os.name == "nt" else 0),
resizable=False,
)
### global theme
with dpg.theme() as theme_no_padding:
with dpg.theme_component(dpg.mvAll):
# set all padding to 0 to avoid scroll bar
dpg.add_theme_style(
dpg.mvStyleVar_WindowPadding, 0, 0, category=dpg.mvThemeCat_Core
)
dpg.add_theme_style(
dpg.mvStyleVar_FramePadding, 0, 0, category=dpg.mvThemeCat_Core
)
dpg.add_theme_style(
dpg.mvStyleVar_CellPadding, 0, 0, category=dpg.mvThemeCat_Core
)
dpg.bind_item_theme("_primary_window", theme_no_padding)
dpg.setup_dearpygui()
if os.path.exists("LXGWWenKai-Regular.ttf"):
with dpg.font_registry():
with dpg.font("LXGWWenKai-Regular.ttf", 18) as default_font:
dpg.bind_font(default_font)
dpg.show_viewport()
@torch.no_grad()
def draw_gs_trajectory(self, time_gap=0.3, samp_num=512, gs_num=512, thickness=1):
fid = torch.tensor(self.animation_time).cuda().float() if self.is_animation else torch.remainder(torch.tensor((time.time()-self.t0) * self.fps_of_fid).float().cuda() / len(self.scene.getTrainCameras()) * self.video_speed, 1.)
from utils.pickle_utils import load_obj, save_obj
if os.path.exists(os.path.join(self.args.model_path, 'trajectory_camera.pickle')):
print('Use fixed camera for screenshot: ', os.path.join(self.args.model_path, 'trajectory_camera.pickle'))
cur_cam = load_obj(os.path.join(self.args.model_path, 'trajectory_camera.pickle'))
else:
cur_cam = MiniCam(
self.cam.pose,
self.W,
self.H,
self.cam.fovy,
self.cam.fovx,
self.cam.near,
self.cam.far,
fid = fid
)
save_obj(os.path.join(self.args.model_path, 'trajectory_camera.pickle'), cur_cam)
fid = cur_cam.fid
# Calculate the gs position at t0
t = fid
time_input = t.unsqueeze(0).expand(self.gaussians.get_xyz.shape[0], -1) if self.deform.name == 'mlp' else self.deform.deform.expand_time(t)
d_values = self.deform.step(self.gaussians.get_xyz.detach(), time_input, feature=self.gaussians.feature, is_training=False, motion_mask=self.gaussians.motion_mask)
cur_pts = self.gaussians.get_xyz + d_values['d_xyz']
if not os.path.exists(os.path.join(self.args.model_path, 'trajectory_keypoints.pickle')):
from utils.time_utils import farthest_point_sample
pts_idx = farthest_point_sample(cur_pts[None], gs_num)[0]
save_obj(os.path.join(self.args.model_path, 'trajectory_keypoints.pickle'), cur_pts[pts_idx].detach().cpu().numpy())
else:
print('Load keypoints from ', os.path.join(self.args.model_path, 'trajectory_keypoints.pickle'))
kpts = torch.from_numpy(load_obj(os.path.join(self.args.model_path, 'trajectory_keypoints.pickle'))).cuda()
import pytorch3d.ops
_, idxs, _ = pytorch3d.ops.knn_points(kpts[None], cur_pts[None], None, None, K=1)
pts_idx = idxs[0,:,0]
delta_ts = torch.linspace(0, time_gap, samp_num)
traj_pts = []
for i in range(samp_num):
t = fid + delta_ts[i]
time_input = t.unsqueeze(0).expand(gs_num, -1) if self.deform.name == 'mlp' else self.deform.deform.expand_time(t)
d_values = self.deform.step(self.gaussians.get_xyz[pts_idx].detach(), time_input, feature=self.gaussians.feature[pts_idx], is_training=False, motion_mask=self.gaussians.motion_mask[pts_idx])
cur_pts = self.gaussians.get_xyz[pts_idx] + d_values['d_xyz']
cur_pts = torch.cat([cur_pts, torch.ones_like(cur_pts[..., :1])], dim=-1)
cur_pts2d = cur_pts @ cur_cam.full_proj_transform
cur_pts2d = cur_pts2d[..., :2] / cur_pts2d[..., -1:]
cur_pts2d = (cur_pts2d + 1) / 2 * torch.tensor([cur_cam.image_height, cur_cam.image_width]).cuda()
traj_pts.append(cur_pts2d)
traj_pts = torch.stack(traj_pts, dim=1).detach().cpu().numpy() # N, T, 2
import cv2
from matplotlib import cm
color_map = cm.get_cmap("jet")
colors = np.array([np.array(color_map(i/max(1, float(gs_num - 1)))[:3]) * 255 for i in range(gs_num)], dtype=np.int32)
alpha_img = np.zeros([cur_cam.image_height, cur_cam.image_width, 3])
traj_img = np.zeros([cur_cam.image_height, cur_cam.image_width, 3])
for i in range(gs_num):
alpha_img = cv2.polylines(img=alpha_img, pts=[traj_pts[i].astype(np.int32)], isClosed=False, color=[1, 1, 1], thickness=thickness)
color = colors[i] / 255
traj_img = cv2.polylines(img=traj_img, pts=[traj_pts[i].astype(np.int32)], isClosed=False, color=[float(color[0]), float(color[1]), float(color[2])], thickness=thickness)
traj_img = np.concatenate([traj_img, alpha_img[..., :1]], axis=-1) * 255
Image.fromarray(traj_img.astype('uint8')).save(os.path.join(self.args.model_path, 'trajectory.png'))
from utils.vis_utils import render_cur_cam
img_begin = render_cur_cam(self=self, cur_cam=cur_cam)
cur_cam.fid = cur_cam.fid + delta_ts[-1]
img_end = render_cur_cam(self=self, cur_cam=cur_cam)
img_begin = (img_begin.permute(1,2,0).clamp(0, 1).detach().cpu().numpy() * 255).astype('uint8')
img_end = (img_end.permute(1,2,0).clamp(0, 1).detach().cpu().numpy() * 255).astype('uint8')
Image.fromarray(img_begin).save(os.path.join(self.args.model_path, 'traj_start.png'))
Image.fromarray(img_end).save(os.path.join(self.args.model_path, 'traj_end.png'))
# gui mode
def render(self):
assert self.gui
while dpg.is_dearpygui_running():
# update texture every frame
if self.training:
if self.deform.name == 'node' and self.iteration_node_rendering < self.opt.iterations_node_rendering:
self.train_node_rendering_step()
else:
self.train_step()
if self.should_vis_trajectory:
self.draw_gs_trajectory()
self.should_vis_trajectory = False
if self.should_render_customized_trajectory:
self.render_customized_trajectory(use_spiral=self.should_render_customized_trajectory_spiral)
self.test_step()
dpg.render_dearpygui_frame()
# no gui mode
def train(self, iters=5000):
if iters > 0:
for i in tqdm.trange(iters):
if self.deform.name == 'node' and self.iteration_node_rendering < self.opt.iterations_node_rendering:
self.train_node_rendering_step()