-
Notifications
You must be signed in to change notification settings - Fork 59
/
Copy pathwebui.py
1570 lines (1366 loc) · 59.9 KB
/
webui.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
import time
import numpy as np
import torch
import torchvision
import rembg
from gaussiansplatting.scene.colmap_loader import qvec2rotmat
from gaussiansplatting.scene.cameras import Simple_Camera
from threestudio.utils.dpt import DPT
from torchvision.ops import masks_to_boxes
from gaussiansplatting.utils.graphics_utils import fov2focal
import viser
import viser.transforms as tf
from dataclasses import dataclass, field
from viser.theme import TitlebarButton, TitlebarConfig, TitlebarImage
from PIL import Image
from tqdm import tqdm
import cv2
import numpy as np
import sys
import shutil
import torch
from torchvision.transforms.functional import to_pil_image, to_tensor
from kornia.geometry.quaternion import Quaternion
# import threestudio
# import os
# from threestudio.systems.base import BaseLift3DSystem
# from pathlib import Path
# import subprocess
# import rembg
# from threestudio.utils.clip_metrics import ClipSimilarity
# from threestudio.utils.lama import InpaintModel
# from threestudio.utils.ops import binary_cross_entropy
from threestudio.utils.typing import *
from threestudio.utils.transform import rotate_gaussians
from gaussiansplatting.gaussian_renderer import render, point_cloud_render
from gaussiansplatting.scene import GaussianModel
from gaussiansplatting.scene.vanilla_gaussian_model import (
GaussianModel as VanillaGaussianModel,
)
# from gaussiansplatting.utils.graphics_utils import fov2focal
from gaussiansplatting.arguments import (
PipelineParams,
OptimizationParams,
)
from omegaconf import OmegaConf
# from gaussiansplatting.utils.general_utils import inverse_sigmoid
# from gaussiansplatting.gaussian_renderer import camera2rasterizer
from argparse import ArgumentParser
from threestudio.utils.misc import (
get_device,
step_check,
dilate_mask,
erode_mask,
fill_closed_areas,
)
from threestudio.utils.sam import LangSAMTextSegmentor
from threestudio.utils.camera import camera_ray_sample_points, project, unproject
# from threestudio.utils.dpt import DPT
# from threestudio.utils.config import parse_structured
from gaussiansplatting.scene.camera_scene import CamScene
import math
from GUI.EditGuidance import EditGuidance
from GUI.DelGuidance import DelGuidance
# from GUI.AddGuidance import AddGuidance
import os
import random
import ui_utils
import datetime
import subprocess
from pathlib import Path
from threestudio.utils.transform import (
rotate_gaussians,
translate_gaussians,
scale_gaussians,
default_model_mtx,
)
class WebUI:
def __init__(self, cfg) -> None:
self.gs_source = cfg.gs_source
self.colmap_dir = cfg.colmap_dir
self.port = 8084
# training cfg
self.use_sam = False
self.guidance = None
self.stop_training = False
self.inpaint_end_flag = False
self.scale_depth = True
self.depth_end_flag = False
self.seg_scale = True
self.seg_scale_end = False
# from original system
self.points3d = []
self.gaussian = GaussianModel(
sh_degree=0,
anchor_weight_init_g0=1.0,
anchor_weight_init=0.1,
anchor_weight_multiplier=2,
)
# load
self.gaussian.load_ply(self.gs_source)
self.gaussian.max_radii2D = torch.zeros(
(self.gaussian.get_xyz.shape[0]), device="cuda"
)
# front end related
self.colmap_cameras = None
self.render_cameras = None
# diffusion model
self.ip2p = None
self.ctn_ip2p = None
self.ctn_inpaint = None
self.ctn_ip2p = None
self.training = False
if self.colmap_dir is not None:
scene = CamScene(self.colmap_dir, h=512, w=512)
self.cameras_extent = scene.cameras_extent
self.colmap_cameras = scene.cameras
self.background_tensor = torch.tensor(
[0, 0, 0], dtype=torch.float32, device="cuda"
)
self.edit_frames = {}
self.origin_frames = {}
self.masks_2D = {}
self.text_segmentor = LangSAMTextSegmentor().to(get_device())
self.sam_predictor = self.text_segmentor.model.sam
self.sam_predictor.is_image_set = True
self.sam_features = {}
self.semantic_gauassian_masks = {}
self.semantic_gauassian_masks["ALL"] = torch.ones_like(self.gaussian._opacity)
self.parser = ArgumentParser(description="Training script parameters")
self.pipe = PipelineParams(self.parser)
# status
self.display_semantic_mask = False
self.display_point_prompt = False
self.viewer_need_update = False
self.system_need_update = False
self.inpaint_again = True
self.scale_depth = True
self.server = viser.ViserServer(port=self.port)
self.add_theme()
self.draw_flag = True
with self.server.add_gui_folder("Render Setting"):
self.resolution_slider = self.server.add_gui_slider(
"Resolution", min=384, max=4096, step=2, initial_value=2048
)
self.FoV_slider = self.server.add_gui_slider(
"FoV Scaler", min=0.2, max=2, step=0.1, initial_value=1
)
self.fps = self.server.add_gui_text(
"FPS", initial_value="-1", disabled=True
)
self.renderer_output = self.server.add_gui_dropdown(
"Renderer Output",
[
"comp_rgb",
],
)
self.save_button = self.server.add_gui_button("Save Gaussian")
self.frame_show = self.server.add_gui_checkbox(
"Show Frame", initial_value=False
)
with self.server.add_gui_folder("Semantic Tracing"):
self.sam_enabled = self.server.add_gui_checkbox(
"Enable SAM",
initial_value=False,
)
self.add_sam_points = self.server.add_gui_checkbox(
"Add SAM Points", initial_value=False
)
self.sam_group_name = self.server.add_gui_text(
"SAM Group Name", initial_value="table"
)
self.clear_sam_pins = self.server.add_gui_button(
"Clear SAM Pins",
)
self.text_seg_prompt = self.server.add_gui_text(
"Text Seg Prompt", initial_value="a bike"
)
self.semantic_groups = self.server.add_gui_dropdown(
"Semantic Group",
options=["ALL"],
)
self.seg_cam_num = self.server.add_gui_slider(
"Seg Camera Nums", min=6, max=200, step=1, initial_value=24
)
self.mask_thres = self.server.add_gui_slider(
"Seg Threshold", min=0.2, max=0.99999, step=0.00001, initial_value=0.7, visible=False
)
self.show_semantic_mask = self.server.add_gui_checkbox(
"Show Semantic Mask", initial_value=False
)
self.seg_scale_end_button = self.server.add_gui_button(
"End Seg Scale!",
visible=False,
)
self.submit_seg_prompt = self.server.add_gui_button("Tracing Begin!")
with self.server.add_gui_folder("Edit Setting"):
self.edit_type = self.server.add_gui_dropdown(
"Edit Type", ("Edit", "Delete", "Add")
)
self.guidance_type = self.server.add_gui_dropdown(
"Guidance Type", ("InstructPix2Pix", "ControlNet-Pix2Pix")
)
self.edit_frame_show = self.server.add_gui_checkbox(
"Show Edit Frame", initial_value=True, visible=False
)
self.edit_text = self.server.add_gui_text(
"Text",
initial_value="",
visible=True,
)
self.draw_bbox = self.server.add_gui_checkbox(
"Draw Bounding Box", initial_value=False, visible=False
)
self.left_up = self.server.add_gui_vector2(
"Left UP",
initial_value=(0, 0),
step=1,
visible=False,
)
self.right_down = self.server.add_gui_vector2(
"Right Down",
initial_value=(0, 0),
step=1,
visible=False,
)
self.inpaint_seed = self.server.add_gui_slider(
"Inpaint Seed", min=0, max=1000, step=1, initial_value=0, visible=False
)
self.refine_text = self.server.add_gui_text(
"Refine Text",
initial_value="",
visible=False,
)
self.inpaint_end = self.server.add_gui_button(
"End 2D Inpainting!",
visible=False,
)
self.depth_scaler = self.server.add_gui_slider(
"Depth Scale", min=0.0, max=5.0, step=0.01, initial_value=1.0, visible=False
)
self.depth_end = self.server.add_gui_button(
"End Depth Scale!",
visible=False,
)
self.edit_begin_button = self.server.add_gui_button("Edit Begin!")
self.edit_end_button = self.server.add_gui_button(
"End Editing!", visible=False
)
with self.server.add_gui_folder("Advanced Options"):
self.edit_cam_num = self.server.add_gui_slider(
"Camera Num", min=12, max=200, step=1, initial_value=48
)
self.edit_train_steps = self.server.add_gui_slider(
"Total Step", min=0, max=5000, step=100, initial_value=1500
)
self.densify_until_step = self.server.add_gui_slider(
"Densify Until Step",
min=0,
max=5000,
step=50,
initial_value=1300,
)
self.densification_interval = self.server.add_gui_slider(
"Densify Interval",
min=25,
max=1000,
step=25,
initial_value=100,
)
self.max_densify_percent = self.server.add_gui_slider(
"Max Densify Percent",
min=0.0,
max=1.0,
step=0.001,
initial_value=0.01,
)
self.min_opacity = self.server.add_gui_slider(
"Min Opacity",
min=0.0,
max=0.1,
step=0.0001,
initial_value=0.005,
)
self.per_editing_step = self.server.add_gui_slider(
"Edit Interval", min=4, max=48, step=1, initial_value=10
)
self.edit_begin_step = self.server.add_gui_slider(
"Edit Begin Step", min=0, max=5000, step=100, initial_value=0
)
self.edit_until_step = self.server.add_gui_slider(
"Edit Until Step", min=0, max=5000, step=100, initial_value=1000
)
self.inpaint_scale = self.server.add_gui_slider(
"Inpaint Scale", min=0.1, max=10, step=0.1, initial_value=1, visible=False
)
self.mask_dilate = self.server.add_gui_slider(
"Mask Dilate", min=1, max=30, step=1, initial_value=15, visible=False
)
self.fix_holes = self.server.add_gui_checkbox(
"Fix Holes", initial_value=True, visible=False
)
with self.server.add_gui_folder("Learning Rate Scaler"):
self.gs_lr_scaler = self.server.add_gui_slider(
"XYZ LR Init", min=0.0, max=10.0, step=0.1, initial_value=3.0
)
self.gs_lr_end_scaler = self.server.add_gui_slider(
"XYZ LR End", min=0.0, max=10.0, step=0.1, initial_value=2.0
)
self.color_lr_scaler = self.server.add_gui_slider(
"Color LR", min=0.0, max=10.0, step=0.1, initial_value=3.0
)
self.opacity_lr_scaler = self.server.add_gui_slider(
"Opacity LR", min=0.0, max=10.0, step=0.1, initial_value=2.0
)
self.scaling_lr_scaler = self.server.add_gui_slider(
"Scale LR", min=0.0, max=10.0, step=0.1, initial_value=2.0
)
self.rotation_lr_scaler = self.server.add_gui_slider(
"Rotation LR", min=0.0, max=10.0, step=0.1, initial_value=2.0
)
with self.server.add_gui_folder("Loss Options"):
self.lambda_l1 = self.server.add_gui_slider(
"Lambda L1", min=0, max=100, step=1, initial_value=10
)
self.lambda_p = self.server.add_gui_slider(
"Lambda Perceptual", min=0, max=100, step=1, initial_value=10
)
self.anchor_weight_init_g0 = self.server.add_gui_slider(
"Anchor Init G0", min=0., max=10., step=0.05, initial_value=0.05
)
self.anchor_weight_init = self.server.add_gui_slider(
"Anchor Init", min=0., max=10., step=0.05, initial_value=0.1
)
self.anchor_weight_multiplier = self.server.add_gui_slider(
"Anchor Multiplier", min=1., max=10., step=0.1, initial_value=1.3
)
self.lambda_anchor_color = self.server.add_gui_slider(
"Lambda Anchor Color", min=0, max=500, step=1, initial_value=0
)
self.lambda_anchor_geo = self.server.add_gui_slider(
"Lambda Anchor Geo", min=0, max=500, step=1, initial_value=50
)
self.lambda_anchor_scale = self.server.add_gui_slider(
"Lambda Anchor Scale", min=0, max=500, step=1, initial_value=50
)
self.lambda_anchor_opacity = self.server.add_gui_slider(
"Lambda Anchor Opacity", min=0, max=500, step=1, initial_value=50
)
self.anchor_term = [self.anchor_weight_init_g0, self.anchor_weight_init,
self.anchor_weight_multiplier,
self.lambda_anchor_color, self.lambda_anchor_geo,
self.lambda_anchor_scale, self.lambda_anchor_opacity, ]
@self.inpaint_seed.on_update
def _(_):
self.inpaint_again = True
@self.depth_scaler.on_update
def _(_):
self.scale_depth = True
@self.mask_thres.on_update
def _(_):
self.seg_scale = True
@self.edit_type.on_update
def _(_):
if self.edit_type.value == "Edit":
self.edit_text.visible = True
self.refine_text.visible = False
for term in self.anchor_term:
term.visible = True
self.inpaint_scale.visible = False
self.mask_dilate.visible = False
self.fix_holes.visible = False
self.per_editing_step.visible = True
self.edit_begin_step.visible = True
self.edit_until_step.visible = True
self.draw_bbox.visible = False
self.left_up.visible = False
self.right_down.visible = False
self.inpaint_seed.visible = False
self.inpaint_end.visible = False
self.depth_scaler.visible = False
self.depth_end.visible = False
self.edit_frame_show.visible = True
self.guidance_type.visible = True
elif self.edit_type.value == "Delete":
self.edit_text.visible = True
self.refine_text.visible = False
for term in self.anchor_term:
term.visible = True
self.inpaint_scale.visible = True
self.mask_dilate.visible = True
self.fix_holes.visible = True
self.edit_cam_num.value = 24
self.densification_interval.value = 50
self.per_editing_step.visible = False
self.edit_begin_step.visible = False
self.edit_until_step.visible = False
self.draw_bbox.visible = False
self.left_up.visible = False
self.right_down.visible = False
self.inpaint_seed.visible = False
self.inpaint_end.visible = False
self.depth_scaler.visible = False
self.depth_end.visible = False
self.edit_frame_show.visible = True
self.guidance_type.visible = False
elif self.edit_type.value == "Add":
self.edit_text.visible = True
self.refine_text.visible = False
for term in self.anchor_term:
term.visible = False
self.inpaint_scale.visible = False
self.mask_dilate.visible = False
self.fix_holes.visible = False
self.per_editing_step.visible = True
self.edit_begin_step.visible = True
self.edit_until_step.visible = True
self.draw_bbox.visible = True
self.left_up.visible = True
self.right_down.visible = True
self.inpaint_seed.visible = False
self.inpaint_end.visible = False
self.depth_scaler.visible = False
self.depth_end.visible = False
self.edit_frame_show.visible = False
self.guidance_type.visible = False
@self.save_button.on_click
def _(_):
current_time = datetime.datetime.now()
formatted_time = current_time.strftime("%Y-%m-%d-%H:%M")
self.gaussian.save_ply(os.path.join("ui_result", "{}.ply".format(formatted_time)))
@self.inpaint_end.on_click
def _(_):
self.inpaint_end_flag = True
@self.seg_scale_end_button.on_click
def _(_):
self.seg_scale_end = True
@self.depth_end.on_click
def _(_):
self.depth_end_flag = True
@self.edit_end_button.on_click
def _(event: viser.GuiEvent):
self.stop_training = True
@self.edit_begin_button.on_click
def _(event: viser.GuiEvent):
self.edit_begin_button.visible = False
self.edit_end_button.visible = True
if self.training:
return
self.training = True
self.configure_optimizers()
self.gaussian.update_anchor_term(
anchor_weight_init_g0=self.anchor_weight_init_g0.value,
anchor_weight_init=self.anchor_weight_init.value,
anchor_weight_multiplier=self.anchor_weight_multiplier.value,
)
if self.edit_type.value == "Add":
# self.add(self.camera)
self.add(self.camera)
else:
self.edit_frame_show.visible = True
edit_cameras, train_frames, train_frustums = ui_utils.sample_train_camera(self.colmap_cameras,
self.edit_cam_num.value,
self.server)
if self.edit_type.value == "Edit":
self.edit(edit_cameras, train_frames, train_frustums)
elif self.edit_type.value == "Delete":
self.delete(edit_cameras, train_frames, train_frustums)
ui_utils.remove_all(train_frames)
ui_utils.remove_all(train_frustums)
self.edit_frame_show.visible = False
self.guidance = None
self.training = False
self.gaussian.anchor_postfix()
self.edit_begin_button.visible = True
self.edit_end_button.visible = False
@self.submit_seg_prompt.on_click
def _(_):
if not self.sam_enabled.value:
text_prompt = self.text_seg_prompt.value
print("[Segmentation Prompt]", text_prompt)
_, semantic_gaussian_mask = self.update_mask(text_prompt)
else:
text_prompt = self.sam_group_name.value
# buggy here, if self.sam_enabled == True, will raise strange errors. (Maybe caused by multi-threading access to the same SAM model)
self.sam_enabled.value = False
self.add_sam_points.value = False
# breakpoint()
_, semantic_gaussian_mask = self.update_sam_mask_with_point_prompt(
save_mask=True
)
self.semantic_gauassian_masks[text_prompt] = semantic_gaussian_mask
if text_prompt not in self.semantic_groups.options:
self.semantic_groups.options += (text_prompt,)
self.semantic_groups.value = text_prompt
@self.semantic_groups.on_update
def _(_):
semantic_mask = self.semantic_gauassian_masks[self.semantic_groups.value]
self.gaussian.set_mask(semantic_mask)
self.gaussian.apply_grad_mask(semantic_mask)
@self.edit_frame_show.on_update
def _(_):
if self.guidance is not None:
for _ in self.guidance.train_frames:
_.visible = self.edit_frame_show.value
for _ in self.guidance.train_frustums:
_.visible = self.edit_frame_show.value
self.guidance.visible = self.edit_frame_show.value
with torch.no_grad():
self.frames = []
random.seed(0)
frame_index = random.sample(
range(0, len(self.colmap_cameras)),
min(len(self.colmap_cameras), 20),
)
for i in frame_index:
self.make_one_camera_pose_frame(i)
@self.frame_show.on_update
def _(_):
for frame in self.frames:
frame.visible = self.frame_show.value
self.server.world_axes.visible = self.frame_show.value
@self.server.on_scene_click
def _(pointer):
self.click_cb(pointer)
@self.clear_sam_pins.on_click
def _(_):
self.clear_points3d()
def make_one_camera_pose_frame(self, idx):
cam = self.colmap_cameras[idx]
# wxyz = tf.SO3.from_matrix(cam.R.T).wxyz
# position = -cam.R.T @ cam.T
T_world_camera = tf.SE3.from_rotation_and_translation(
tf.SO3(cam.qvec), cam.T
).inverse()
wxyz = T_world_camera.rotation().wxyz
position = T_world_camera.translation()
# breakpoint()
frame = self.server.add_frame(
f"/colmap/frame_{idx}",
wxyz=wxyz,
position=position,
axes_length=0.2,
axes_radius=0.01,
visible=False,
)
self.frames.append(frame)
@frame.on_click
def _(event: viser.GuiEvent):
client = event.client
assert client is not None
T_world_current = tf.SE3.from_rotation_and_translation(
tf.SO3(client.camera.wxyz), client.camera.position
)
T_world_target = tf.SE3.from_rotation_and_translation(
tf.SO3(frame.wxyz), frame.position
) @ tf.SE3.from_translation(np.array([0.0, 0.0, -0.5]))
T_current_target = T_world_current.inverse() @ T_world_target
for j in range(5):
T_world_set = T_world_current @ tf.SE3.exp(
T_current_target.log() * j / 4.0
)
with client.atomic():
client.camera.wxyz = T_world_set.rotation().wxyz
client.camera.position = T_world_set.translation()
time.sleep(1.0 / 15.0)
client.camera.look_at = frame.position
if not hasattr(self, "begin_call"):
def begin_trans(client):
assert client is not None
T_world_current = tf.SE3.from_rotation_and_translation(
tf.SO3(client.camera.wxyz), client.camera.position
)
T_world_target = tf.SE3.from_rotation_and_translation(
tf.SO3(frame.wxyz), frame.position
) @ tf.SE3.from_translation(np.array([0.0, 0.0, -0.5]))
T_current_target = T_world_current.inverse() @ T_world_target
for j in range(5):
T_world_set = T_world_current @ tf.SE3.exp(
T_current_target.log() * j / 4.0
)
with client.atomic():
client.camera.wxyz = T_world_set.rotation().wxyz
client.camera.position = T_world_set.translation()
client.camera.look_at = frame.position
self.begin_call = begin_trans
def configure_optimizers(self):
opt = OptimizationParams(
parser = ArgumentParser(description="Training script parameters"),
max_steps= self.edit_train_steps.value,
lr_scaler = self.gs_lr_scaler.value,
lr_final_scaler = self.gs_lr_end_scaler.value,
color_lr_scaler = self.color_lr_scaler.value,
opacity_lr_scaler = self.opacity_lr_scaler.value,
scaling_lr_scaler = self.scaling_lr_scaler.value,
rotation_lr_scaler = self.rotation_lr_scaler.value,
)
opt = OmegaConf.create(vars(opt))
# opt.update(self.training_args)
self.gaussian.spatial_lr_scale = self.cameras_extent
self.gaussian.training_setup(opt)
def render(
self,
cam,
local=False,
sam=False,
train=False,
) -> Dict[str, Any]:
self.gaussian.localize = local
render_pkg = render(cam, self.gaussian, self.pipe, self.background_tensor)
image, viewspace_point_tensor, _, radii = (
render_pkg["render"],
render_pkg["viewspace_points"],
render_pkg["visibility_filter"],
render_pkg["radii"],
)
if train:
self.viewspace_point_tensor = viewspace_point_tensor
self.radii = radii
self.visibility_filter = self.radii > 0.0
semantic_map = render(
cam,
self.gaussian,
self.pipe,
self.background_tensor,
override_color=self.gaussian.mask[..., None].float().repeat(1, 3),
)["render"]
semantic_map = torch.norm(semantic_map, dim=0)
semantic_map = semantic_map > 0.0 # 1, H, W
semantic_map_viz = image.detach().clone() # C, H, W
semantic_map_viz = semantic_map_viz.permute(1, 2, 0) # 3 512 512 to 512 512 3
semantic_map_viz[semantic_map] = 0.50 * semantic_map_viz[
semantic_map
] + 0.50 * torch.tensor([1.0, 0.0, 0.0], device="cuda")
semantic_map_viz = semantic_map_viz.permute(2, 0, 1) # 512 512 3 to 3 512 512
render_pkg["sam_masks"] = []
render_pkg["point2ds"] = []
if sam:
if hasattr(self, "points3d") and len(self.points3d) > 0:
sam_output = self.sam_predict(image, cam)
if sam_output is not None:
render_pkg["sam_masks"].append(sam_output[0])
render_pkg["point2ds"].append(sam_output[1])
self.gaussian.localize = False # reverse
render_pkg["semantic"] = semantic_map_viz[None]
render_pkg["masks"] = semantic_map[None] # 1, 1, H, W
image = image.permute(1, 2, 0)[None] # C H W to 1 H W C
render_pkg["comp_rgb"] = image # 1 H W C
depth = render_pkg["depth_3dgs"]
depth = depth.permute(1, 2, 0)[None]
render_pkg["depth"] = depth
render_pkg["opacity"] = depth / (depth.max() + 1e-5)
return {
**render_pkg,
}
@torch.no_grad()
def update_mask(self, text_prompt) -> None:
masks = []
weights = torch.zeros_like(self.gaussian._opacity)
weights_cnt = torch.zeros_like(self.gaussian._opacity, dtype=torch.int32)
total_view_num = len(self.colmap_cameras)
random.seed(0) # make sure same views
view_index = random.sample(
range(0, total_view_num),
min(total_view_num, self.seg_cam_num.value),
)
for idx in tqdm(view_index):
cur_cam = self.colmap_cameras[idx]
this_frame = render(
cur_cam, self.gaussian, self.pipe, self.background_tensor
)["render"]
# breakpoint()
# this_frame [c h w]
this_frame = this_frame.moveaxis(0, -1)[None, ...]
mask = self.text_segmentor(this_frame, text_prompt)[0].to(get_device())
if self.use_sam:
print("Using SAM")
self.sam_features[idx] = self.sam_predictor.features
masks.append(mask)
self.gaussian.apply_weights(cur_cam, weights, weights_cnt, mask)
weights /= weights_cnt + 1e-7
self.seg_scale_end_button.visible = True
self.mask_thres.visible = True
self.show_semantic_mask.value = True
while True:
if self.seg_scale:
selected_mask = weights > self.mask_thres.value
selected_mask = selected_mask[:, 0]
self.gaussian.set_mask(selected_mask)
self.gaussian.apply_grad_mask(selected_mask)
self.seg_scale = False
if self.seg_scale_end:
self.seg_scale_end = False
break
time.sleep(0.01)
self.seg_scale_end_button.visible = False
self.mask_thres.visible = False
return masks, selected_mask
@property
def camera(self):
if len(list(self.server.get_clients().values())) == 0:
return None
if self.render_cameras is None and self.colmap_dir is not None:
self.aspect = list(self.server.get_clients().values())[0].camera.aspect
self.render_cameras = CamScene(
self.colmap_dir, h=-1, w=-1, aspect=self.aspect
).cameras
self.begin_call(list(self.server.get_clients().values())[0])
viser_cam = list(self.server.get_clients().values())[0].camera
# viser_cam.up_direction = tf.SO3(viser_cam.wxyz) @ np.array([0.0, -1.0, 0.0])
# viser_cam.look_at = viser_cam.position
R = tf.SO3(viser_cam.wxyz).as_matrix()
T = -R.T @ viser_cam.position
# T = viser_cam.position
if self.render_cameras is None:
fovy = viser_cam.fov * self.FoV_slider.value
else:
fovy = self.render_cameras[0].FoVy * self.FoV_slider.value
fovx = 2 * math.atan(math.tan(fovy / 2) * self.aspect)
# fovy = self.render_cameras[0].FoVy
# fovx = self.render_cameras[0].FoVx
# math.tan(self.render_cameras[0].FoVx / 2) / math.tan(self.render_cameras[0].FoVy / 2)
# math.tan(fovx/2) / math.tan(fovy/2)
# aspect = viser_cam.aspect
width = int(self.resolution_slider.value)
height = int(width / self.aspect)
return Simple_Camera(0, R, T, fovx, fovy, height, width, "", 0)
def click_cb(self, pointer):
if self.sam_enabled.value and self.add_sam_points.value:
assert hasattr(pointer, "click_pos"), "please install our forked viser"
click_pos = pointer.click_pos # tuple (float, float) W, H from 0 to 1
click_pos = torch.tensor(click_pos)
self.add_points3d(self.camera, click_pos)
self.viwer_need_update = True
elif self.draw_bbox.value:
assert hasattr(pointer, "click_pos"), "please install our forked viser"
click_pos = pointer.click_pos
click_pos = torch.tensor(click_pos)
cur_cam = self.camera
if self.draw_flag:
self.left_up.value = [
int(cur_cam.image_width * click_pos[0]),
int(cur_cam.image_height * click_pos[1]),
]
self.draw_flag = False
else:
new_value = [
int(cur_cam.image_width * click_pos[0]),
int(cur_cam.image_height * click_pos[1]),
]
if (self.left_up.value[0] < new_value[0]) and (
self.left_up.value[1] < new_value[1]
):
self.right_down.value = new_value
self.draw_flag = True
else:
self.left_up.value = new_value
def set_system(self, system):
self.system = system
def clear_points3d(self):
self.points3d = []
def add_points3d(self, camera, points2d, update_mask=False):
depth = render(camera, self.gaussian, self.pipe, self.background_tensor)[
"depth_3dgs"
]
unprojected_points3d = unproject(camera, points2d, depth)
self.points3d += unprojected_points3d.unbind(0)
if update_mask:
self.update_sam_mask_with_point_prompt(self.points3d)
# no longer needed since can be extracted from langsam
# def sam_encode_all_view(self):
# assert hasattr(self, "sam_predictor")
# self.sam_features = {}
# # NOTE: assuming all views have the same size
# for id, frame in self.origin_frames.items():
# # TODO: check frame dtype (float32 or uint8) and device
# self.sam_predictor.set_image(frame)
# self.sam_features[id] = self.sam_predictor.features
@torch.no_grad()
def update_sam_mask_with_point_prompt(
self, points3d=None, save_mask=False, save_name="point_prompt_mask"
):
points3d = points3d if points3d is not None else self.points3d
masks = []
weights = torch.zeros_like(self.gaussian._opacity)
weights_cnt = torch.zeros_like(self.gaussian._opacity, dtype=torch.int32)
total_view_num = len(self.colmap_cameras)
random.seed(0) # make sure same views
view_index = random.sample(
range(0, total_view_num),
min(total_view_num, self.seg_cam_num.value),
)
for idx in tqdm(view_index):
cur_cam = self.colmap_cameras[idx]
assert len(points3d) > 0
points2ds = project(cur_cam, points3d)
img = render(cur_cam, self.gaussian, self.pipe, self.background_tensor)[
"render"
]
self.sam_predictor.set_image(
np.asarray(to_pil_image(img.cpu())),
)
self.sam_features[idx] = self.sam_predictor.features
# print(points2ds)
mask, _, _ = self.sam_predictor.predict(
point_coords=points2ds.cpu().numpy(),
point_labels=np.array([1] * points2ds.shape[0], dtype=np.int64),
box=None,
multimask_output=False,
)
mask = torch.from_numpy(mask).to(torch.bool).to(get_device())
self.gaussian.apply_weights(
cur_cam, weights, weights_cnt, mask.to(torch.float32)
)
masks.append(mask)
weights /= weights_cnt + 1e-7
self.seg_scale_end_button.visible = True
self.mask_thres.visible = True
self.show_semantic_mask.value = True
while True:
if self.seg_scale:
selected_mask = weights > self.mask_thres.value
selected_mask = selected_mask[:, 0]
self.gaussian.set_mask(selected_mask)
self.gaussian.apply_grad_mask(selected_mask)
self.seg_scale = False
if self.seg_scale_end:
self.seg_scale_end = False
break
time.sleep(0.01)
self.seg_scale_end_button.visible = False
self.mask_thres.visible = False
if save_mask:
for id, mask in enumerate(masks):
mask = mask.cpu().numpy()[0, 0]
img = Image.fromarray(mask)
os.makedirs("tmp",exist_ok=True)
img.save(f"./tmp/{save_name}-{id}.jpg")
return masks, selected_mask
@torch.no_grad()
def sam_predict(self, image, cam):
img = np.asarray(to_pil_image(image.cpu()))
self.sam_predictor.set_image(img)
if len(self.points3d) == 0:
return
_points2ds = project(cam, self.points3d)
_mask, _, _ = self.sam_predictor.predict(
point_coords=_points2ds.cpu().numpy(),
point_labels=np.array([1] * _points2ds.shape[0], dtype=np.int64),
box=None,
multimask_output=False,
)
_mask = torch.from_numpy(_mask).to(torch.bool).to(get_device())
return _mask.squeeze(), _points2ds
@torch.no_grad()
def prepare_output_image(self, output):
out_key = self.renderer_output.value
out_img = output[out_key][0] # H W C
if out_key == "comp_rgb":
if self.show_semantic_mask.value:
out_img = output["semantic"][0].moveaxis(0, -1)
elif out_key == "masks":
out_img = output["masks"][0].to(torch.float32)[..., None].repeat(1, 1, 3)
if out_img.dtype == torch.float32:
out_img = out_img.clamp(0, 1)
out_img = (out_img * 255).to(torch.uint8).cpu().to(torch.uint8)
out_img = out_img.moveaxis(-1, 0) # C H W
if self.sam_enabled.value:
if "sam_masks" in output and len(output["sam_masks"]) > 0:
try:
out_img = torchvision.utils.draw_segmentation_masks(
out_img, output["sam_masks"][0]
)
out_img = torchvision.utils.draw_keypoints(
out_img,
output["point2ds"][0][None, ...],