-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathrun_system.py
1715 lines (1355 loc) · 62.7 KB
/
run_system.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
##########################
#
# This file is part of https://github.com/TRAILab/UncertainShapePose
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>
#
import sys, os
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
# Support headless mode for matplotlib
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
import open3d as o3d
import numpy as np
import torch
from datetime import datetime
import random
import glob, imageio
import cv2
from scipy.spatial.transform import Rotation as R
from reconstruct.utils import color_table, set_view, get_configs, get_decoder
from reconstruct.utils import set_view_mat
from reconstruct.loss_utils import get_time
from reconstruct.optimizer import Optimizer
from uncertainty.optimizer_uncertainty import MeshExtractorUncertain
from utils.visualizer import visualize_mesh_to_image, visualize_meshes_to_image
from utils.io import generate_sample_points
from utils.dataset_loader import Dataset
from utils.evo import evaluate_estimation_results, summarize_results_with_instance_frames_keep_dict
from utils.scannet_subset import ScanNetSubset
from utils.args import config_parser
from utils import SE3
from data_association.association_utils import name_to_coco_id, Observation, Object
from data_association.association_utils import *
# @pts: numpy
def save_to_pcd(pts, filename):
if isinstance(pts, torch.Tensor):
pts = pts.cpu().numpy()
if pts.shape[-1] == 4:
pts = pts[:,:3]
# change array to pcd file
scene_pcd = o3d.geometry.PointCloud()
scene_pcd.points = o3d.utility.Vector3dVector(pts)
o3d.io.write_point_cloud(filename, scene_pcd)
# Update: a mechanism to choose dataset and get data from it;
# save_pts: save poins to files.
def save_pcd_with_inputs_gt(pcd, surface_points, gt_local, save_dir, save_pts=False):
inputs = surface_points
gt = gt_local
comp = np.asarray(pcd.points)
fig_num = 4
fig = plt.figure(figsize=(8*fig_num, 8))
# input vis
pts = inputs
ax = fig.add_subplot(141, projection='3d')
x = pts[:,0]
y = pts[:,1]
z = pts[:,2]
ax.scatter(x, y, z, color='b')
ax.set_title('inputs')
ax.set_box_aspect((1, 1, 1))
pts = gt
ax = fig.add_subplot(142, projection='3d')
x = pts[:,0]
y = pts[:,1]
z = pts[:,2]
ax.scatter(x, y, z, color='r')
ax.set_title('gt')
ax.set_box_aspect((1, 1, 1))
pts = comp
ax = fig.add_subplot(143, projection='3d')
x = pts[:,0]
y = pts[:,1]
z = pts[:,2]
ax.scatter(x, y, z, color='g')
ax.set_title('est')
ax.set_box_aspect((1, 1, 1))
# overlap with comp & gt
pts = comp
ax = fig.add_subplot(144, projection='3d')
ax.scatter(x, y, z, color='g')
pts = gt
x = pts[:,0]
y = pts[:,1]
z = pts[:,2]
ax.scatter(x, y, z, color='r')
ax.set_box_aspect((1, 1, 1))
ax.set_title('est & gt')
fig.savefig(f'{save_dir}/pts-{i}.png')
plt.close()
# add a inputs & gt compare
fig_num = 1
fig = plt.figure(figsize=(8*fig_num, 8))
# input vis
pts = inputs
ax = fig.add_subplot(111, projection='3d')
x = pts[:,0]
y = pts[:,1]
z = pts[:,2]
ax.scatter(x, y, z, color='b')
pts = gt
x = pts[:,0]
y = pts[:,1]
z = pts[:,2]
ax.scatter(x, y, z, color='r')
ax.set_title('inputs & gt')
ax.set_box_aspect((1, 1, 1))
fig.savefig(f'{save_dir}/pts-extra-{i}.png')
plt.close()
if save_pts:
save_to_pcd(inputs, f'{save_dir}/inputs-{i}.ply')
save_to_pcd(gt, f'{save_dir}/gt-{i}.ply')
save_to_pcd(comp, f'{save_dir}/comp-{i}.ply')
def save_output_as_deepsdf(save_dir, est_mesh_filename, gt_mesh_transformed, data_sdf, view_file, prefix):
# if not os.path.exists(os.path.dirname(save_im_name)):
# os.makedirs(os.path.dirname(save_im_name))
if not os.path.exists(save_dir):
os.makedirs(save_dir)
save_im_name = os.path.join(save_dir, prefix + '.png')
visualize_mesh_to_image(est_mesh_filename, view_file, save_im_name)
if gt_mesh_transformed is not None:
gt_save_im_name = save_im_name[:-4] + '_gt.png'
visualize_meshes_to_image([gt_mesh_transformed], view_file, gt_save_im_name)
gt_save_im_name = save_im_name[:-4] + '_compare.png'
visualize_meshes_to_image([est_mesh_filename, gt_mesh_transformed], view_file, gt_save_im_name, color=[None, [1, 0.706, 0]])
# further save point cloud
if isinstance(data_sdf, list):
data_sdf_stack = torch.cat(data_sdf, 0) # stack positive, negative
else:
data_sdf_stack = data_sdf
sdf_pts = generate_sample_points(data_sdf_stack, sample_num = 10000)
# we sample part of the points
# sdf_pts = sdf_pts.
gt_save_im_name = save_im_name[:-4] + '_sdf.png'
visualize_meshes_to_image([sdf_pts], view_file, gt_save_im_name)
gt_save_im_name = save_im_name[:-4] + '_sdf_compare.png'
visualize_meshes_to_image([est_mesh_filename, sdf_pts], view_file, gt_save_im_name, color=[None, [1, 0.706, 0]])
def load_random_seed(seed=1):
print('Set random seed for torch, random, numpy to:', seed)
torch.manual_seed(seed)
random.seed(seed)
np.random.seed(seed)
def load_dataset(dataset_name, args, configs):
if dataset_name == 'scannet':
from utils.scannet import ScanNet
dataset = ScanNet(args.sequence_dir)
return dataset
def visualize_o3d_ins_to_image(o3d_list, view_file, save_im_name, vis, set_view_param=None):
'''
@set_view_param: (dist, theta, yaw)
'''
vis.clear_geometries()
for ins_o3d in o3d_list:
if ins_o3d is None:
continue
vis.add_geometry(ins_o3d)
# load view from file
if view_file is not None:
ctr = vis.get_view_control()
param = o3d.io.read_pinhole_camera_parameters(view_file)
ctr.convert_from_pinhole_camera_parameters(param)
elif set_view_param is not None:
set_view(vis, set_view_param[0], set_view_param[1], set_view_param[2])
'''
Temp DEBUG TO Change Point Size
'''
vis.get_render_option().point_size = 10.0
# update and save to image
vis.poll_events()
vis.update_renderer()
vis.capture_screen_image(save_im_name)
def visualize_and_save_reconstruction_results(mesh_extractor, obj_list, frame_save_dir,
use_uncertainty=True, vis_uncertainty=True, vis=None,
vis_abs_uncer=True, t_cw_vis: np.array=None):
'''
A function to visualize the pose and shape estimation result of current instance.
Save latent code, ply meshes.
Output: a png file by rendering a 3D scene into a 2D view specified by t_cw_vis.
'''
mesh_list_world = []
pts_list_world = []
for obj_id, obj in enumerate(obj_list):
if not obj.is_good:
print('optimization fail for obj:', obj_id)
continue
# 1. generating mesh
if use_uncertainty:
code = obj.code[:,0]
sigma = obj.code[:,1]
if not vis_uncertainty:
sigma = None # sigma is not valid.
else:
code = obj.code[:,0]
try:
if use_uncertainty:
# with uncertainty painted
mesh_o3d = mesh_extractor.generate_mesh_for_vis(code,code_sigma=sigma,N=10,vis_abs_uncer=vis_abs_uncer)
else:
# no uncertainty
mesh = mesh_extractor.extract_mesh_from_code(code)
mesh_o3d = o3d.geometry.TriangleMesh(o3d.utility.Vector3dVector(mesh.vertices), o3d.utility.Vector3iVector(mesh.faces))
mesh_o3d.compute_vertex_normals()
mesh_o3d.paint_uniform_color(color_table[obj_id])
# o3d.io.write_triangle_mesh(f"{save_dir}/mesh-local-{i}.obj", mesh_o3d)
except:
print('Fail to generate mesh for obj', obj_id)
continue
# save local mesh
mesh_save_name = os.path.join(frame_save_dir, f'mesh-ins-{obj_id}.ply')
# save mesh, and local pts to image
if obj.pts_local is not None:
pts = obj.pts_local.cpu().numpy()
# transform to world with t_world_cam = obj.t_world_obj @ inv(obj.t_cam_obj)
t_world_cam = obj.t_world_obj @ np.linalg.inv(obj.t_cam_obj)
pts_world = np.dot(t_world_cam[:3,:3], pts.T).T + t_world_cam[:3,3]
pts_pcd = o3d.geometry.PointCloud()
pts_pcd.points = o3d.utility.Vector3dVector(pts_world)
else:
pts_pcd = None
pts_list_world.append(pts_pcd)
mesh_o3d_world = mesh_o3d.transform(obj.t_world_obj)
mesh_list_world.append(mesh_o3d_world)
# save latent code
code_save_name = os.path.join(frame_save_dir, f'code-ins-{obj_id}.pt')
torch.save(obj.code, code_save_name)
'''
Visualize the whole frame, including lidar points, and reconstructed meshes with GT POSE
'''
# Only valid for KITTI dataset. Add LiDAR point cloud
if vis is None:
vis = o3d.visualization.Visualizer()
vis.clear_geometries()
obj_index = 0
# visualize meshes in 3D
for mesh_o3d in mesh_list_world:
vis.add_geometry(mesh_o3d)
mesh_save_name = os.path.join(frame_save_dir, f'mesh-world-{obj_index}.ply')
o3d.io.write_triangle_mesh(mesh_save_name, mesh_o3d)
obj_index += 1
# set view from t_wc_vis
if t_cw_vis is not None:
set_view_mat(vis, t_cw_vis)
vis.poll_events()
vis.update_renderer()
im_path = os.path.join(frame_save_dir, f'visualization_3d.png')
vis.capture_screen_image(im_path)
obj_index = 0
# visualize observation points in 3D
for pts_pcd_world in pts_list_world:
if pts_pcd_world is None:
continue
vis.add_geometry(pts_pcd_world)
point_save_name = os.path.join(frame_save_dir, f"point-world-{obj_index}.ply")
o3d.io.write_point_cloud(point_save_name, pts_pcd_world)
obj_index += 1
# set view from t_wc_vis
if t_cw_vis is not None:
set_view_mat(vis, t_cw_vis)
vis.poll_events()
vis.update_renderer()
im_path = os.path.join(frame_save_dir, f'visualization_3d_w_pts.png')
vis.capture_screen_image(im_path)
def visualize_intermediate_results(mesh_extractor, reconstruction_results_frame,
frame_save_dir,
vis,
frame_num = 1,
use_uncertainty=True,
vis_uncertainty=False,
vis_abs_uncer=True,
render_depth=False, BACKGROUND_DEPTH=9.0, mask=None, K=None,
duration=5):
'''
This function generates meshes for each iteration, and render 3D mesh into 2D image, and finally
generate a gif image over all the images.
@ duration: the total time of the gif; 5 seconds
'''
for obj_id, obj in enumerate(reconstruction_results_frame):
if not obj.is_good:
continue
intermediate_result = obj.intermediate # it stores sigma, not log(var)
intermediate_code = intermediate_result['code']
# visualize intermediate results
num_steps = len(intermediate_code)
# make a valid list from 0 to num_steps, make sure 0 and last ind is inside,
# and divide center equally with frame_num
consider_indicies_list = np.linspace(0, num_steps - 1, frame_num).astype(int).tolist()
mesh_list_steps = []
T_oc_list_steps = []
for ind in consider_indicies_list:
code_dist = intermediate_code[ind]
code_dist = code_dist.cpu().numpy()
# 1. generating mesh
if use_uncertainty:
code = code_dist[:,0]
sigma = code_dist[:,1]
if not vis_uncertainty:
sigma = None # sigma is not valid.
else:
code = code_dist
try:
if use_uncertainty:
# with uncertainty painted
mesh_o3d = mesh_extractor.generate_mesh_for_vis(code,code_sigma=sigma,
N=10,vis_abs_uncer=vis_abs_uncer)
else:
# Origin codes
mesh = mesh_extractor.extract_mesh_from_code(code)
mesh_o3d = o3d.geometry.TriangleMesh(o3d.utility.Vector3dVector(mesh.vertices),
o3d.utility.Vector3iVector(mesh.faces))
mesh_o3d.compute_vertex_normals()
mesh_o3d.paint_uniform_color(color_table[obj_id])
# o3d.io.write_triangle_mesh(f"{save_dir}/mesh-local-{i}.obj", mesh_o3d)
except:
print('Fail to generate mesh for obj', obj_id)
continue
mesh_list_steps.append(mesh_o3d)
T_oc_list_steps.append(intermediate_result['T_oc'][ind])
if render_depth:
# render depth for each obj code
# note there are randomness, not exactly the same as the optimization process
from reconstruct.loss import render_uncertain_depth
mask = mask
K = K
t_obj_cam = np.linalg.inv(obj.t_cam_obj)
latent_vector_distribution = code_dist
depth, std = render_uncertain_depth(mask, K, t_obj_cam, decoder, latent_vector_distribution,
num_depth_samples=50, BACKGROUND_DEPTH=BACKGROUND_DEPTH,
device='cuda', dtype=torch.float64)
# save to the disk
depth_save_name = os.path.join(frame_save_dir, f'depth-ins-{obj_id}-{t}.png')
std_save_name = os.path.join(frame_save_dir, f'std-ins-{obj_id}-{t}.png')
plt.imsave(depth_save_name, depth)
plt.imsave(std_save_name, std)
if obj.pts_local is not None:
pts = obj.pts_local.cpu().numpy() # points in camera frame
pts_pcd = o3d.geometry.PointCloud()
pts_pcd.points = o3d.utility.Vector3dVector(pts)
# change pts size
# pts_pcd.scale(0.01, center=pts_pcd.get_center())
# specify color
color_pts = np.array([0,255,0]) / 255.0 # r,g,b dark purple
pts_pcd.paint_uniform_color(color_pts)
else:
pts_pcd = None
#########
# visualize shape with pose, into the world frame.
for t, mesh_o3d in enumerate(mesh_list_steps):
T_oc = T_oc_list_steps[t]
T_co = T_oc.inverse()
# transform from object frame to camera frame
mesh_o3d_cam = mesh_o3d.transform(T_co.detach().cpu().numpy()) # camera frame
ind = consider_indicies_list[t]
im_path = os.path.join(frame_save_dir, f'optimization-ins-{obj_id}-{ind}.png')
visualize_o3d_ins_to_image([mesh_o3d_cam], None, im_path, vis, set_view_param=(0,0,0))
# images under dir to gif
im_list = glob.glob(os.path.join(frame_save_dir, f'optimization-ins-{obj_id}-*.png'))
im_list = sorted(im_list, key=lambda x: int(x.split('-')[-1].split('.')[0]))
im_list = [imageio.v2.imread(im) for im in im_list]
gif_path = os.path.join(frame_save_dir, f'optimization-ins-{obj_id}.gif')
imageio.mimsave(gif_path, im_list, duration=duration)
# whether to delete intermediate images
im_list = glob.glob(os.path.join(frame_save_dir, f'optimization-ins-{obj_id}-*.png'))
# for im in im_list:
# os.remove(im)
#########
# visualize all the meshes into gif
for t, mesh_o3d in enumerate(mesh_list_steps):
ind = consider_indicies_list[t]
im_path = os.path.join(frame_save_dir, f'optimization-w-pts-{obj_id}-{ind}.png')
visualize_o3d_ins_to_image([mesh_o3d, pts_pcd], None, im_path, vis, set_view_param=(0,0,0))
# images under dir to gif
im_list = glob.glob(os.path.join(frame_save_dir, f'optimization-w-pts-{obj_id}-*.png'))
im_list = sorted(im_list, key=lambda x: int(x.split('-')[-1].split('.')[0]))
im_list = [imageio.v2.imread(im) for im in im_list]
gif_path = os.path.join(frame_save_dir, f'optimization-w-pts-{obj_id}.gif')
imageio.mimsave(gif_path, im_list, duration=duration)
# delete intermediate images
im_list = glob.glob(os.path.join(frame_save_dir, f'optimization-w-pts-{obj_id}-*.png'))
# for im in im_list:
# os.remove(im)
if render_depth:
# add a gif for std and depth
im_list = glob.glob(os.path.join(frame_save_dir, f'std-ins-{obj_id}-*.png'))
im_list = sorted(im_list, key=lambda x: int(x.split('-')[-1].split('.')[0]))
im_list = [imageio.v2.imread(im) for im in im_list]
gif_path = os.path.join(frame_save_dir, f'std-ins-{obj_id}.gif')
imageio.mimsave(gif_path, im_list, duration=duration)
im_list = glob.glob(os.path.join(frame_save_dir, f'std-ins-{obj_id}-*.png'))
# for im in im_list:
# os.remove(im)
# add for depth
im_list = glob.glob(os.path.join(frame_save_dir, f'depth-ins-{obj_id}-*.png'))
im_list = sorted(im_list, key=lambda x: int(x.split('-')[-1].split('.')[0]))
im_list = [imageio.v2.imread(im) for im in im_list]
gif_path = os.path.join(frame_save_dir, f'depth-ins-{obj_id}.gif')
imageio.mimsave(gif_path, im_list, duration=duration)
im_list = glob.glob(os.path.join(frame_save_dir, f'depth-ins-{obj_id}-*.png'))
# for im in im_list:
# os.remove(im)
def plot_loss_curve(reconstruction_results_frame, frame_save_dir, loss_weights=None):
'''
@ loss_weights: a dict with {loss_name: weight, ...}
'''
loss_names = ['loss_sdf', 'loss_norm', 'loss_2d', 'loss']
# define different curve shapes
curve_shapes = ['--', '-.', ':', '-']
for id, obj in enumerate(reconstruction_results_frame):
if not obj.is_good:
continue
plt.figure()
ax = plt.gca()
ax2 = ax.twinx()
for loss_name in loss_names:
loss_list = getattr(obj, loss_name+'_list')
if loss_weights is not None:
loss_list = [loss_weights[loss_name] * loss for loss in loss_list]
label_name = f'{loss_name} * {loss_weights[loss_name]}'
else:
label_name = loss_name
if loss_name == 'loss':
# plot with another axis
ax2.plot(loss_list, label=label_name, linestyle=curve_shapes[loss_names.index(loss_name)])
else:
# plot with the same axis
ax.plot(loss_list, label=label_name, linestyle=curve_shapes[loss_names.index(loss_name)])
plt.title(f'Loss curve')
plt.xlabel('Iteration')
plt.ylabel('Loss')
ax.legend(loc='upper right')
ax.grid(True)
plt.savefig(os.path.join(frame_save_dir, f'loss-obj-{id}.png'))
plt.close()
'''
Debug mode, plot the losses in one figure for each iterations
'''
make_loss_gif = False
if make_loss_gif:
print('==> Debug mode, plot the losses in one figure for each iterations')
n_all_steps = 200
# No 3d loss
loss_names = ['sdf_loss', 'loss_2d', 'norm_term']
loss_names_vis = ['3D loss', '2D loss', 'Norm term']
# solid dot with different color
curve_shapes = ['-', '-', '-.']
for step in range(n_all_steps):
plt.figure()
ax = plt.gca()
# ax2 = ax.twinx()
for i,loss_name in enumerate(loss_names):
loss_list = getattr(obj, loss_name+'_list')
# only consider part of loss
loss_list = loss_list[:step]
if loss_weights is not None:
loss_list = [loss_weights[loss_name] * loss for loss in loss_list]
loss_name_vis = loss_names_vis[i]
label_name = f'{loss_name_vis}'
else:
label_name = loss_names_vis[i]
if loss_name == 'loss':
# plot with another axis
ax2.plot(loss_list, label=label_name, linestyle=curve_shapes[loss_names.index(loss_name)])
else:
# plot with the same axis
ax.plot(loss_list, label=label_name, linestyle=curve_shapes[loss_names.index(loss_name)])
plt.title(f'Loss curve')
plt.xlabel('Iteration')
plt.ylabel('Loss')
ax.legend(loc='upper right')
# add grid
ax.grid(True)
plt.savefig(os.path.join(frame_save_dir, f'loss-obj-{id}-step-{step}.png'))
plt.close()
'''
Made a gif for all the loss curves
'''
im_list = glob.glob(os.path.join(frame_save_dir, f'loss-obj-{id}-*.png'))
im_list = sorted(im_list, key=lambda x: int(x.split('-')[-1].split('.')[0]))
im_list = [imageio.v2.imread(im) for im in im_list]
gif_path = os.path.join(frame_save_dir, f'loss-obj-{id}.gif')
# frame rate 24
# duration = n_all_steps / 24.0 / 2.0
fps = 24
duration = 1000 * 1 / fps
imageio.mimsave(gif_path, im_list, duration=duration)
def construct_scene(dataset, scene_name, frame_list=None):
scene = Scene()
scene.name = scene_name
#for frame_id in range(0, num_frames, skip):
for frame_id in frame_list:
print("Working on frame:",frame_id)
# load frame information
frame = dataset.load_frame(scene_name, frame_id)
for j in range(frame.n_bboxes):
label = frame.labels[j]
if not coco_id_in_intereted_classes(label) or frame.scores[j] < 0.6:
continue
obs = Observation(frame, j)
frame.add_observation(obs)
print("Number of observations:",frame.n_obs)
if (frame.n_obs == 0):
continue
scene.add_frame(frame)
scene.prune_overlapping_objects()
scene.estimate_poses()
return scene
def associate_obj_to_gt(dataset, scene):
gt_obj_list = dataset.load_objects_from_scene(scene.name)
gt_obj_pos = np.empty((0,3))
for gt_obj in gt_obj_list:
gt_obj_pos = np.vstack((gt_obj_pos, gt_obj['trs']['translation']))
for obj in scene.objects:
est_pos = obj.estimated_pose[0:3,3].T
dist = np.linalg.norm(gt_obj_pos - est_pos, axis=1)
gt_id = np.argmin(dist)
min_dist = np.min(dist)
if min_dist < 0.5:
obj.obj_gt_id = gt_id
print("Associating object",obj.obj_id,"to ground truth object",gt_id)
return
def init_instance_order_list_in_scene(dataset, scene_name, args,
input=None, scene_order=None, vis=None):
'''
This function recoginizes the number of valid objects inside the scene, so that we could iterate over each objects.
There are two options according to the applications:
1) use groundtruth data associations.
This assumes we know data association in advance, and concentrate on shape and pose estimation.
This can reveal the upperbound of the mapping accuracy (all observations are for this object).
2) Automatically solve data association.
This makes the system more complete, without relying on an assumption like 1).
We need to consider all the frames of the scenes, initialize objects for each frame, and associate them
with some data association algorithms.
We give a simple implementation using minimum distance as below.
TODO: We are still organizing the code for the automatic data association module.
@ args.use_gt_association: whether to use gt association or use automatic association.
if True:
@ args.dataset_subset_package:
a dataset subset package containing instances information.
@ args.obj_id
Specify one object to deal with.
Or:
Consider all instances of this scene.
if False:
Automatically solve objects assocaition.
'''
output = {}
if args.use_gt_association:
# If using gt association,
# Use input package
if args.dataset_subset_package is not None:
# if package is in, use it
ins_orders_list = input['ins_orders_list_all_scenes'][scene_order]
else:
# or, manually load
if args.obj_id is None:
ins_orders_list = dataset.load_objects_orders_from_scene_with_category(scene_name, category='chair')
else:
ins_orders_list = [args.obj_id]
else:
'''
Automatically get objects assocaition with observations
'''
# reconstruct a scene by yourself
scene = construct_scene(dataset, args.scene_name)
scene.visualize_objects(vis)
associate_obj_to_gt(dataset, scene)
# whether to use args.obj_id to consider one specific object
if args.obj_id is None:
ins_orders_list = scene.get_object_indices_with_category('chair')
else:
ins_orders_list = [args.obj_id]
output['scene'] = scene
return ins_orders_list, output
def init_scene_list(args, dataset):
output = {}
if args.dataset_subset_package is not None:
# load from the dataset subset package
dataset_subset_data = torch.load(args.dataset_subset_package)
# subset_scannet = {
# 'scene_names': selected_scene_names,
# 'scene_ins_list': selected_chair_indices,
# 'n_scenes': len(selected_scene_names),
# 'n_objects': n_selected_instances,
# 'category': category,
# 'version': 'v1',
# 'description': 'A subset of ScanNet, with only chair instances. Used for debugging.',
# 'time': time.asctime(time.localtime(time.time()))
# }
selected_scene_names = dataset_subset_data['scene_names']
ins_orders_list_all_scenes = dataset_subset_data['scene_ins_list']
scene_ins_frames_single = dataset_subset_data['scene_ins_frames_single']
scene_ins_frames = dataset_subset_data['scene_ins_frames']
print('==> load dataset subset from:', args.dataset_subset_package)
print(' Description:', dataset_subset_data['description'])
if args.continue_from_scene is not None:
# start from this scene_name
if args.continue_from_scene in selected_scene_names:
start_scene_idx = selected_scene_names.index(args.continue_from_scene)
selected_scene_names = selected_scene_names[start_scene_idx:]
ins_orders_list_all_scenes = ins_orders_list_all_scenes[start_scene_idx:]
scene_ins_frames_single = scene_ins_frames_single[start_scene_idx:]
scene_ins_frames = scene_ins_frames[start_scene_idx:]
print('==> continue from scene:', args.continue_from_scene)
else:
raise ValueError('continue from scene not in the dataset subset package')
output['ins_orders_list_all_scenes'] = ins_orders_list_all_scenes
# both single and multi-view frames should be considered
output['scene_ins_frames_single'] = scene_ins_frames_single
output['scene_ins_frames'] = scene_ins_frames
output['selected_scene_names'] = selected_scene_names
output['category_list'] = dataset_subset_data['category_list']
else:
if args.scene_name is None:
# iterating over all the scenes
val_scene_names = dataset.get_scene_name_list()
MAX_SCENE_CONSIDERATION = 20 # debug
SCENE_START_IDX = 0
selected_scene_names = val_scene_names[SCENE_START_IDX:][:MAX_SCENE_CONSIDERATION]
else:
selected_scene_names = [args.scene_name]
return selected_scene_names, output
def init_frame_ids_for_instance(args, LOOP_INS_ID, scene_order,
scene_detail, dataset_subset=None,
sample_method='equal'):
'''
@option_select_frame: when using dataset_subset_package, choose how to sample frames from selected frames.
@sample_method: when NOT using dataset_subset_package, how to sample frames for each instance.
* equal: equally starting from 0 with the same interval to cover all the frames.
* center: sample frames around the center frame to make sure the observation quality is high and in the center.
TODO: Combine the two parameters
'''
# Select the frames for each instances
# dataset frames selection
# get all the observations of this instance
if args.dataset_name != 'scannet':
raise NotImplementedError
view_num = args.view_num
if args.use_gt_association:
# get frames from package
if args.dataset_subset_package is not None:
all_frame_list_ins = scene_detail['scene_ins_frames']
# besides the single view frame, we further sample frames from the multi-view frames
all_frame_list = all_frame_list_ins[scene_order][LOOP_INS_ID]
# option_select_frame = 'interval' # max interval
option_select_frame = args.option_select_frame
if option_select_frame == 'stage_3':
# Only 3 stage: single/sparse/dense, corresponding to 1,3,10 views;
view_groups = {
1: [5],
3: [5,3,7],
10: [5,0,1,2,3,4,6,7,8,9],
}
if not view_num in view_groups:
raise ValueError('Only support 1/3/10 views.')
# Debug, output options:
print(' - Select from', view_groups[view_num])
print(' - all_frame_list:', all_frame_list)
selected_frames = [all_frame_list[i] for i in view_groups[view_num]]
all_frame_list = selected_frames
else:
# consider view num
single_frame_list_ins = scene_detail['scene_ins_frames_single']
single_frame_id = single_frame_list_ins[scene_order][LOOP_INS_ID][0]
if view_num > 1:
'''
We need to make sure the first frame is the same as the single view frame.
For the remaining frames, we sample in a deterministic way so that each run is the same.
'''
# remove the single view frame
all_frame_list_no_single = [frame_id for frame_id in all_frame_list if frame_id != single_frame_id]
N_sample = view_num - 1
if option_select_frame == 'interval':
# sample in a deterministic way
all_frame_list_no_single = sorted(all_frame_list_no_single)
all_frame_list_no_single = all_frame_list_no_single[::len(all_frame_list_no_single)//N_sample]
selected_frames = all_frame_list_no_single[:N_sample]
elif option_select_frame == 'close': # get closest frame!
frame_dist = np.abs(np.array(all_frame_list_no_single) - single_frame_id)
# find top K minimum dis indices
min_dist_indices = np.argsort(frame_dist)[:N_sample]
selected_frames = [all_frame_list_no_single[i] for i in min_dist_indices]
# sort
selected_frames = sorted(selected_frames)
# add the single view frame
all_frame_list = [single_frame_id] + selected_frames
else:
all_frame_list = [single_frame_id]
obs_id_list = all_frame_list
else:
'''
The view is not specified.
'''
if args.frame_id is not None:
obs_id_list = [args.frame_id]
else:
# Sample frames from all valid frames
max_frame_num = view_num
# Get the observed frames list!
# dataset_subset = ScanNetSubset(args.sequence_dir, scene_name, LOOP_INS_ID, load_image = False)
num_total_frames = len(dataset_subset)
if sample_method == 'equal':
# equally sample max_frame_num frames from num_total_frames
obs_id_list = np.round(np.linspace(0, num_total_frames-1, max_frame_num)).astype(int)
elif sample_method == 'center':
# sample frames around the center frame
# if single
if max_frame_num == 1:
obs_id_list = [num_total_frames//2]
else:
# Only when the number of frames is one, the center sample_method is valid.
raise NotImplementedError
else:
# get all the observations of this instance
object_obs_frames = scene.objects[obj_id].observations
num_total_frames = len(object_obs_frames)
print('===> number of observations of the object:', num_total_frames)
if args.frame_id is not None:
obs_id_list = [args.frame_id]
else:
max_frame_num = 3 # for single frame, consider how many frames?
# only randomly consider two frames
# Replace: false to select once each
obs_id_list = np.round(np.linspace(0, num_total_frames-1, max_frame_num)).astype(int)
return obs_id_list
def resize_image(im, s):
# Calculate the new dimensions
new_dimensions = (int(im.shape[1]*s), int(im.shape[0]*s))
# Resize the image
resized_image = cv2.resize(im, new_dimensions, interpolation = cv2.INTER_AREA)
return resized_image
def vis_frame_func(scene, obj_id, obs_id, recon_save_dir_prefix_frame,
dataset_subset=None,
args=None, resize_scale=1.0):
# visualize RGB, Depth, Mask
save_frame_im_dir = os.path.join(recon_save_dir_prefix_frame, 'input')
os.makedirs(save_frame_im_dir, exist_ok=True)
if scene is not None:
rgb = scene.objects[obj_id].observations[obs_id].rgb
depth = scene.objects[obj_id].observations[obs_id].depth
mask = scene.objects[obj_id].observations[obs_id].mask_inflated
else:
frame = dataset_subset.get_one_frame(obs_id, load_image=True) # in default, it loads mask from mask2former
rgb = frame.rgb
depth = frame.depth
mask = dataset_subset._load_mask(dataset_subset.scene_name,
dataset_subset.obj_id, frame) # loading gt mask.
# save to the disk
rgb_save_name = os.path.join(save_frame_im_dir, f'rgb_f{obs_id}.png')
depth_save_name = os.path.join(save_frame_im_dir, f'depth_f{obs_id}.png')
mask_save_name = os.path.join(save_frame_im_dir, f'mask_f{obs_id}.png')
cv2.imwrite(rgb_save_name, resize_image(rgb, resize_scale))
plt.imsave(depth_save_name, resize_image(depth, resize_scale))
if mask is None:
print('Invalid mask for test evo.')
return
plt.imsave(mask_save_name, mask)
'''
Update: Crop RGB with Mask and Save
'''
# Find coordinates of non-zero (valid) pixels in the mask
non_zero_indices = np.nonzero(mask)
min_x, min_y = np.min(non_zero_indices, axis=1)
max_x, max_y = np.max(non_zero_indices, axis=1)
# Crop the area of the minimum bounding box from the RGB image
cropped_rgb = rgb[min_x:max_x+1, min_y:max_y+1]
cropped_rgb_save_name = os.path.join(save_frame_im_dir, f'rgb_cropped_f{obs_id}.png')
cv2.imwrite(cropped_rgb_save_name, resize_image(cropped_rgb, resize_scale))
##
# Crop with no Background
# background = np.zeros_like(rgb) # Update: use white background
background = np.ones_like(rgb) * 255
background[mask != 0] = rgb[mask != 0]
cropped_rgb_mask = background[min_x:max_x+1, min_y:max_y+1]
cropped_rgb_mask_save_name = os.path.join(save_frame_im_dir, f'rgb_cropped_mask_f{obs_id}.png')
cv2.imwrite(cropped_rgb_mask_save_name, resize_image(cropped_rgb_mask, resize_scale))
'''
Utils IO
'''
def construct_object_from_frame(frame, category):
'''
Need attributes: