-
Notifications
You must be signed in to change notification settings - Fork 19
/
dataloader_SGFN.py
1473 lines (1269 loc) · 62.4 KB
/
dataloader_SGFN.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
from collections import defaultdict
import torch.utils.data as data
import os
import random
import torch
import json
import trimesh
import h5py
import copy
from tqdm import tqdm
import numpy as np
import multiprocessing as mp
# from utils import util_ply, util_data, util, define
from codeLib.common import random_drop
from codeLib import transformation
from ssg.utils import util_ply, util_data
from codeLib.utils.util import read_txt_to_list, check_file_exist
from ssg import define
# from codeLib.torch.visualization import show_tensor_images
from codeLib.common import normalize_imagenet
from torchvision import transforms
import codeLib.torchvision.transforms as cltransform
import ssg.utils.compute_weight as compute_weight
from ssg.utils.util_data import raw_to_data, data_to_raw, cvt_all_to_dict_from_h5
import codeLib.utils.string_numpy as snp
import logging
from PIL import Image
from codeLib.common import run
from pytictoc import TicToc
from torch_geometric.data import HeteroData
logger_py = logging.getLogger(__name__)
DRAW_BBOX_IMAGE = True
DRAW_BBOX_IMAGE = False
class SGFNDataset (data.Dataset):
def __init__(self, config, mode, **args):
super().__init__()
assert mode in ['train', 'validation', 'test']
self._device = config.DEVICE
path = config.data['path']
self.config = config
self.cfg = self.config
self.mconfig = config.data
self.path = config.data.path
self.label_file = config.data.label_file
self.use_data_augmentation = self.mconfig.data_augmentation
self.root_3rscan = config.data.path_3rscan_data
self.path_h5 = os.path.join(self.path, define.NAME_RELATIONSHIPS)
self.path_mv = os.path.join(self.path, define.NAME_VIS_GRAPH)
self.path_roi_img = os.path.join(
self.mconfig.roi_img_path, define.NAME_ROI_IMAGE)
self.pth_filtered = os.path.join(
self.path, 'filtered_scans_detection.h5')
self.pth_node_weights = os.path.join(self.path, 'node_weights.txt')
self.pth_edge_weights = os.path.join(self.path, 'edge_weights.txt')
self.pth_node_occ = os.path.join(self.path, 'node_occ.txt')
self.pth_edge_occ = os.path.join(self.path, 'edge_occ.txt')
try:
self.root_scannet = config.data.path_scannet
except:
self.root_scannet = None
# SEGMENT_TYPE='GT'
with open(os.path.join(self.cfg.data.path, 'args.json')) as f:
tmp = json.load(f)
label_type = tmp['label_type']
segment_type = tmp['segment_type']
image_feature_folder_name = define.NAME_IMAGE_FEAUTRE_FORMAT.format(
segment_type, label_type)
self.path_img_feature = os.path.join(
self.cfg.data.path_image_feature, image_feature_folder_name+'.h5')
self.w_cls_obj = self.w_cls_rel = None
self.multi_rel_outputs = multi_rel_outputs = config.model.multi_rel
self.shuffle_objs = False
self.use_rgb = config.model.use_rgb
self.use_normal = config.model.use_normal
self.sample_in_runtime = config.data.sample_in_runtime
self.load_cache = False
self.for_eval = mode != 'train'
self.max_edges = config.data.max_num_edge
self.full_edge = self.multi_rel_outputs # self.config.data.full_edge
# self.output_node = args.get('output_node', True)
# self.output_edge = args.get('output_edge', True)
''' read classes '''
pth_classes = os.path.join(path, 'classes.txt')
pth_relationships = os.path.join(path, 'relationships.txt')
selected_scans = read_txt_to_list(os.path.join(
self.cfg.data.path_split, '%s_scans.txt' % (mode)))
names_classes = read_txt_to_list(pth_classes)
names_relationships = read_txt_to_list(pth_relationships)
if not multi_rel_outputs:
if define.NAME_NONE not in names_relationships:
names_relationships.append(define.NAME_NONE)
elif define.NAME_NONE in names_relationships:
names_relationships.remove(define.NAME_NONE)
self.relationNames = sorted(names_relationships)
self.classNames = sorted(names_classes)
self.none_idx = self.relationNames.index(
define.NAME_NONE) if not multi_rel_outputs else None
'''set transform'''
if self.mconfig.load_images:
if self.mconfig.is_roi_img:
if not self.for_eval:
self.transform = transforms.Compose([
transforms.Resize(config.data.roi_img_size),
cltransform.TrivialAugmentWide(),
# RandAugment(),
])
else:
self.transform = transforms.Compose([
transforms.Resize(config.data.roi_img_size),
])
else:
if not self.for_eval:
if config.data.img_size > 0:
self.transform = transforms.Compose([
transforms.Resize(config.data.img_size),
cltransform.TrivialAugmentWide(),
])
else:
self.transform = transforms.Compose([
cltransform.TrivialAugmentWide(),
])
else:
self.transform = transforms.Compose([
])
# Generate filtered data and compute weights
self.__preprocessing()
'''compute channel dims'''
self.dim_pts = 3
if self.use_rgb:
self.dim_pts += 3
if self.use_normal:
self.dim_pts += 3
'''pack with snp'''
self.open_filtered()
scan_ids = set(self.filtered_data.keys()
).intersection(set(selected_scans))
self.scans = snp.pack(list(scan_ids))
self.size = len(scan_ids)
'''check if pre-computed global image featur exist'''
if not self.mconfig.is_roi_img and self.mconfig.load_images and self.cfg.data.use_precompute_img_feature: # loading and memory issue. try to use precomputed
# self.open_filtered()
should_compute_image_feature = False
if not os.path.exists(self.path_img_feature):
should_compute_image_feature = True
else:
feature_type = self.cfg.model.image_encoder.backend
self.open_image_feature()
image_feature = self.image_feature[feature_type]
for scan_id in scan_ids:
# Check scan exist
if scan_id not in image_feature:
should_compute_image_feature = True
else:
# check image exist
filtered_data = raw_to_data(self.filtered_data[scan_id])[
define.NAME_FILTERED_KF_INDICES]
# try to open it
try:
for kfId in filtered_data:
if str(kfId) not in image_feature[scan_id]:
should_compute_image_feature = True
break
except:
should_compute_image_feature = True
if should_compute_image_feature:
break
if should_compute_image_feature:
# Try to generate
os.environ['MKL_THREADING_LAYER'] = 'GNU'
# os.environ['PYTHONPATH'] = config.PYTHONPATH
# subprocess.call(["export PYTHONPATH={}".format(PYTHONPATH)], shell=True)
# mode_ = 'eval' if mode == 'test' else mode
bashCommand = [
'python', 'ssg/utils/compute_image_feature.py',
"--config", config.config_path,
'-n', image_feature_folder_name,
"-o", self.cfg.data.path_image_feature,
# "--mode",mode_,
]
run(bashCommand)
if not os.path.exists(self.path_img_feature):
raise RuntimeError(
'use precompute image feature is true but file not found.')
if not self.for_eval:
w_node_cls = np.loadtxt(self.pth_node_weights)
w_edge_cls = np.loadtxt(self.pth_edge_weights)
self.w_node_cls = torch.from_numpy(w_node_cls).float()
self.w_edge_cls = torch.from_numpy(w_edge_cls).float()
# return
'''cache'''
self.cache_data = dict()
if self.config.data.load_cache and self.mconfig.load_points:
print('load data to cache')
pool = mp.Pool(8)
pool.daemon = True
for scan_id in scan_ids:
scan_id_no_split = scan_id.rsplit('_', 1)[0]
if 'scene' in scan_id:
path = os.path.join(self.root_scannet, scan_id_no_split)
else:
path = os.path.join(self.root_3rscan, scan_id_no_split)
if scan_id_no_split not in self.cache_data:
self.cache_data[scan_id_no_split] = pool.apply_async(load_mesh,
(path, self.label_file, self.use_rgb, self.use_normal))
pool.close()
pool.join()
for key, item in self.cache_data.items():
self.cache_data[key] = item.get()
self.reset_data()
def open_filtered(self):
self.filtered_data = h5py.File(self.pth_filtered, 'r')
def open_mv_graph(self):
if not hasattr(self, 'mv_data'):
self.mv_data = h5py.File(self.path_mv, 'r')
def open_data(self):
if not hasattr(self, 'sg_data'):
self.sg_data = h5py.File(self.path_h5, 'r')
def open_img(self):
if not hasattr(self, 'roi_imgs'):
self.roi_imgs = h5py.File(self.path_roi_img, 'r')
def open_image_feature(self):
if not hasattr(self, 'image_feature'):
self.image_feature = h5py.File(self.path_img_feature, 'r')
def __getitem__(self, index):
timers = dict()
timer = TicToc()
scan_id = snp.unpack(self.scans, index) # self.scans[idx]
'''open data'''
timer.tic()
# open
self.open_filtered()
self.open_data()
# get SG data
scan_data_raw = self.sg_data[scan_id]
scan_data = raw_to_data(scan_data_raw)
# shortcut
object_data = scan_data['nodes']
relationships_data = scan_data['relationships']
filtered_data = raw_to_data(self.filtered_data[scan_id])
filtered_node_indices = filtered_data[define.NAME_FILTERED_OBJ_INDICES]
filtered_kf_indices = filtered_data[define.NAME_FILTERED_KF_INDICES]
mv_data = None
if self.mconfig.load_images:
self.open_mv_graph()
mv_data = self.mv_data[scan_id]
mv_nodes = mv_data['nodes'] # contain kf ids of a given node
if self.mconfig.is_roi_img:
self.open_img()
roi_imgs = self.roi_imgs[scan_id]
'''filter node data'''
object_data = {nid: object_data[nid] for nid in filtered_node_indices}
timers['open_data'] = timer.tocvalue()
''' build nn dict '''
timer.tic()
nns = dict()
seg2inst = dict()
for oid, odata in object_data.items():
nns[str(oid)] = [int(s) for s in odata['neighbors']]
'''build instance dict'''
if 'instance_id' in odata:
seg2inst[oid] = odata['instance_id']
else:
seg2inst[oid]
timers['build_nn_dict'] = timer.tocvalue()
''' load point cloud data '''
timer.tic()
if self.mconfig.load_points:
if 'scene' in scan_id:
path = os.path.join(self.root_scannet, scan_id)
else:
path = os.path.join(self.root_3rscan, scan_id)
if self.config.data.load_cache:
data = self.cache_data[scan_id]
else:
data = load_mesh(path, self.label_file,
self.use_rgb, self.use_normal)
points = copy.deepcopy(data['points'])
instances = copy.deepcopy(data['instances'])
if self.use_data_augmentation and not self.for_eval:
points = self.data_augmentation(points)
timers['load_pc'] = timer.tocvalue()
'''extract 3D node classes and instances'''
timer.tic()
cat, oid2idx, idx2oid, filtered_instances = self.__sample_3D_nodes(object_data,
mv_data,
nns)
timers['sample_3D_nodes'] = timer.tocvalue()
'''sample 3D node connections'''
timer.tic()
edge_indices_3D = self.__sample_3D_node_edges(
cat, oid2idx, filtered_instances, nns)
timers['sample_3D_node_edges'] = timer.tocvalue()
'''extract relationships data'''
timer.tic()
relationships_3D = self.__extract_relationship_data(
relationships_data, oid2idx)
timers['extract_relationship_data'] = timer.tocvalue()
# relationships_3D_mask = [] # change obj idx to obj mask idx
'''
Generate mapping from selected entity buffer to the ground truth entity buffer (for evaluation)
Save the mapping in edge_index format to allow PYG to rearrange them.
'''
instance2labelName = {int(key): node['label']
for key, node in object_data.items()}
# Collect GT entity list
gt_entities = set()
gtIdx_entities_cls = []
gtIdx2ebIdx = []
for key, value in relationships_3D.items():
sub_o = key[0]
tgt_o = key[1]
gt_entities.add(sub_o)
gt_entities.add(tgt_o)
gt_entities = [k for k in gt_entities]
# assert len(gt_entities) > 0
for gtIdx, k in enumerate(gt_entities):
if k in oid2idx:
idx = oid2idx[k]
gtIdx2ebIdx.append([gtIdx, idx])
label = instance2labelName[k]
gtIdx_entities_cls.append(self.classNames.index(label))
else:
# Add negative index to indicate missing
gtIdx2ebIdx.append([gtIdx, -1])
gtIdx_edge_index = []
gtIdx_edge_cls = []
for key, value in relationships_3D.items():
sub_o = key[0]
tgt_o = key[1]
# sub_cls = instance2labelName[sub_o]
# tgt_cls = instance2labelName[tgt_o]
# sub_cls_id = self.classNames.index(sub_cls)
# tgt_cls_id = self.classNames.index(tgt_cls)
# relationships_3D_mask.append([sub_o,tgt_o,sub_cls_id,tgt_cls_id,value])
sub_ebIdx = oid2idx[sub_o]
tgt_ebIdx = oid2idx[tgt_o]
sub_gtIdx = gt_entities.index(sub_o)
tgt_gtIdx = gt_entities.index(tgt_o)
gtIdx_edge_index.append([sub_gtIdx, tgt_gtIdx])
gtIdx_edge_cls.append(value)
# gtIdx_entities_cls = torch.from_numpy(np.array(gtIdx_entities_cls))
gtIdx2ebIdx = torch.tensor(
gtIdx2ebIdx, dtype=torch.long).t().contiguous()
# gtIdx_edge_cls = torch.from_numpy(np.array(gtIdx_edge_cls))
gtIdx_edge_index = torch.tensor(
gtIdx_edge_index, dtype=torch.long).t().contiguous()
'''sample 3D edges'''
timer.tic()
gt_rels_3D, edge_index_has_gt_3D = self.__sample_relationships(
relationships_3D, idx2oid, edge_indices_3D)
timers['sample_relationships'] = timer.tocvalue()
'''drop edges''' # to fit memory
gt_rels_3D, edge_indices_3D = self.__drop_edge(
gt_rels_3D, edge_indices_3D, edge_index_has_gt_3D)
''' random sample points '''
if self.mconfig.load_points:
timer.tic()
obj_points, descriptor, bboxes = self.__sample_points(
scan_id, points, instances, cat, filtered_instances)
timers['sample_points'] = timer.tocvalue()
'''build rel points'''
timer.tic()
if self.mconfig.rel_data_type == 'points':
rel_points = self.__sample_rel_points(
points, instances, idx2oid, bboxes, edge_indices_3D)
timers['sample_rel_points'] = timer.tocvalue()
'''load images'''
if self.mconfig.load_images:
timer.tic()
if self.mconfig.is_roi_img:
roi_images, node_descriptor_for_image, edge_indices_img_to_obj = \
self.__load_roi_images(cat, idx2oid, mv_nodes, roi_imgs,
object_data, filtered_instances)
else:
images, img_bounding_boxes, bbox_cat, node_descriptor_for_image, \
image_edge_indices, img_idx2oid, temporal_node_graph, temporal_edge_graph = self.__load_full_images(
scan_id, idx2oid, cat, scan_data, mv_data, filtered_kf_indices)
relationships_img = self.__extract_relationship_data(
relationships_data, oid2idx)
gt_rels_2D, edge_index_has_gt_2D = self.__sample_relationships(
relationships_img, img_idx2oid, image_edge_indices)
# img_oid_indices = [oid for oid in img_idx2oid.values()]
img_oid_indices = [seg2inst[oid]
for oid in img_idx2oid.values()]
img_oid_indices = torch.from_numpy(np.array(img_oid_indices))
# gt_rels_2D, image_edge_indices, final_edge_indices_2D = self.__drop_edge(
# gt_rels_2D, image_edge_indices,edge_index_has_gt_2D)
# # filter temporal edge graph
# to_delete=[]
# all_indices = range(len(temporal_edge_graph))
# for idx in all_indices:
# idx_0,idx_1 = temporal_edge_graph[idx][0],temporal_edge_graph[idx][1]
# if idx_0 not in final_edge_indices_2D or idx_1 not in final_edge_indices_2D:
# to_delete.append(idx)
# to_keep = set(all_indices).difference(to_delete)
# temporal_edge_graph = [temporal_edge_graph[idx] for idx in to_keep]
'''to tensor'''
assert len(img_bounding_boxes) > 0
images = torch.stack(images, dim=0)
assert len(bbox_cat) == len(img_bounding_boxes)
img_bounding_boxes = torch.from_numpy(
np.array(img_bounding_boxes)).float()
gt_class_image = torch.from_numpy(np.array(bbox_cat))
image_edge_indices = torch.tensor(
image_edge_indices, dtype=torch.long)
temporal_node_graph = torch.tensor(
temporal_node_graph, dtype=torch.long)
temporal_edge_graph = torch.tensor(
temporal_edge_graph, dtype=torch.long)
if len(node_descriptor_for_image) > 0:
node_descriptor_for_image = torch.stack(
node_descriptor_for_image)
else:
node_descriptor_for_image = torch.tensor(
[], dtype=torch.long)
timers['load_images'] = timer.tocvalue()
'''collect attribute for nodes'''
# for inseg the segment instance should be converted back to the GT instances
inst_indices = [seg2inst[k] for k in idx2oid.values()]
''' to tensor '''
gt_class_3D = torch.from_numpy(np.array(cat))
tensor_oid = torch.from_numpy(np.array(inst_indices))
edge_indices_3D = torch.tensor(edge_indices_3D, dtype=torch.long)
# new_edge_index_has_gt = torch.tensor(new_edge_index_has_gt,dtype=torch.long)
# idx2iid = seg2inst
# idx2iid = torch.LongTensor([seg2inst[oid] if oid in seg2inst else oid for oid in idx2oid.values() ]) # mask idx to instance idx
# idx2oid = torch.LongTensor([oid for oid in idx2oid.values()]) # mask idx to seg idx (instance idx)
'''Gather output in HeteroData'''
output = HeteroData()
output['scan_id'] = scan_id # str
output['node'].x = torch.zeros([gt_class_3D.shape[0], 1]) # dummy
output['node'].y = gt_class_3D
output['node'].oid = tensor_oid
# if len(gtIdx_entities_cls) == 0:
# print('scan_id',scan_id)
# print('len(gtIdx_entities_cls)',len(gtIdx_entities_cls))
# print('gtIdx2ebIdx.shape',gtIdx2ebIdx.shape)
# print('gtIdx_edge_cls',len(gtIdx_edge_cls))
# print('gtIdx_edge_index.shape',gtIdx_edge_index.shape)
# print('hallo')
# gtIdx_entities_cls =None
# gtIdx_edge_cls = None
output['node_gt'].x = torch.zeros(
[len(gtIdx_entities_cls), 1]) # dummy
output['node_gt'].clsIdx = gtIdx_entities_cls if len(
gtIdx_entities_cls) > 0 else torch.zeros([len(gtIdx_entities_cls), 1]) # dummy
output['node_gt', 'to', 'node'].edge_index = gtIdx2ebIdx
output['node_gt', 'to', 'node_gt'].clsIdx = gtIdx_edge_cls if len(
gtIdx_edge_cls) > 0 else torch.zeros([len(gtIdx_entities_cls), 1]) # dummy
output['node_gt', 'to', 'node_gt'].edge_index = gtIdx_edge_index
# edges for computing features
output['node', 'to', 'node'].edge_index = edge_indices_3D.t().contiguous()
output['node', 'to', 'node'].y = gt_rels_3D
if self.mconfig.load_points:
output['node'].pts = obj_points
if 'edge_desc' not in self.mconfig or self.mconfig['edge_desc'] == 'pts':
output['node'].desp = descriptor
if self.mconfig.rel_data_type == 'points':
output['edge'].pts = rel_points
if self.mconfig.load_images:
if self.mconfig.is_roi_img:
output['roi'].x = torch.zeros([roi_images.size(0), 1])
output['roi'].img = roi_images
output['roi', 'sees', 'node'].edge_index = edge_indices_img_to_obj
if 'edge_desc' not in self.mconfig or self.mconfig['edge_desc'] == 'roi':
output['node'].desp = node_descriptor_for_image
# if not self.mconfig.load_points:
# output['node'].desp = node_descriptor_for_image
else:
output['roi'].x = torch.zeros([len(img_bounding_boxes), 1])
output['roi'].y = gt_class_image
output['roi'].box = img_bounding_boxes
output['roi'].img = images
output['roi'].desp = node_descriptor_for_image
output['roi'].oid = img_oid_indices
# need this for temporal edge graph
output['edge2D'].x = torch.zeros([len(temporal_node_graph), 1])
output['roi', 'to',
'roi'].edge_index = image_edge_indices.t().contiguous()
output['roi', 'to', 'roi'].y = gt_rels_2D
output['roi', 'temporal',
'roi'].edge_index = temporal_node_graph.t().contiguous()
output['edge2D', 'temporal',
'edge2D'].edge_index = temporal_edge_graph.t().contiguous()
# print('image_edge_indices',image_edge_indices)
# print('gt_rels_2D',gt_rels_2D)
# print(image_edge_indices)
# print(image_edge_indices)
# tmp1 = torch.sort(torch.unique(tensor_oid))[0]
# tmp2 = torch.sort(torch.unique(img_oid_indices))[0]
# tmp3 = torch.sort(torch.unique(torch.from_numpy(np.array([seg2inst[k] for k in tmp2.tolist()]))))[0]
# assert torch.equal(tmp1,tmp3)
# assert torch.equal(tmp1,tmp2)
'''release'''
self.reset_data()
return output
def __len__(self):
return self.size
def reset_data(self):
to_delete = ['sg_data', 'roi_imgs', 'filtered_data', 'image_featre']
for key in to_delete:
if hasattr(self, key):
del self.__dict__[key]
def norm_tensor(self, points):
assert points.ndim == 2
assert points.shape[1] == 3
centroid = torch.mean(points, dim=0) # N, 3
points -= centroid # n, 3, npts
# find maximum distance for each n -> [n]
furthest_distance = points.pow(2).sum(1).sqrt().max()
points /= furthest_distance
return points
def data_augmentation(self, points):
# random rotate
matrix = np.eye(3)
matrix[0:3, 0:3] = transformation.rotation_matrix(
[0, 0, 1], np.random.uniform(0, 2*np.pi, 1))
centroid = points[:, :3].mean(0)
points[:, :3] -= centroid
points[:, :3] = np.dot(points[:, :3], matrix.T)
if self.use_normal:
ofset = 3
if self.use_rgb:
ofset += 3
points[:, ofset:3 +
ofset] = np.dot(points[:, ofset:3+ofset], matrix.T)
# Add noise
# ## points
# noise = np.random.normal(0,1e-3,[points.shape[0],3]) # 1 mm std
# points[:,:3] += noise
# ## colors
# if self.use_rgb:
# noise = np.random.normal(0,0.078,[points.shape[0],3])
# colors = points[:,3:6]
# colors += noise
# colors[np.where(colors>1)] = 1
# colors[np.where(colors<-1)] = -1
# ## normals
# if self.use_normal:
# ofset=3
# if self.use_rgb:
# ofset+=3
# normals = points[:,ofset:3+ofset]
# normals = np.dot(normals, matrix.T)
# noise = np.random.normal(0,1e-4,[points.shape[0],3])
# normals += noise
# normals = normals/ np.linalg.norm(normals)
return points
def __preprocessing(self):
pth_node_weights = self.pth_node_weights
pth_edge_weights = self.pth_edge_weights
pth_filtered = self.pth_filtered
config = self.cfg
should_process = not os.path.isfile(pth_filtered)
if not self.for_eval:
should_process |= not os.path.isfile(
pth_node_weights) or not os.path.isfile(pth_edge_weights)
if should_process:
'''
This is to make sure the 2D and 3D methdos have the same amount of data for training
'''
# print('generating filtered data...')
''' load data '''
self.open_mv_graph()
self.open_data()
c_sg_data = cvt_all_to_dict_from_h5(self.sg_data)
'''check scan_ids'''
# filter input scans with splits
# inter = set(c_sg_data.keys()).intersection(set(self.selected_scans))
# filter with mv_data
inter = sorted(
list(set(c_sg_data.keys()).intersection(self.mv_data.keys())))
'''check if filtered scan is generated'''
try:
h5f = h5py.File(pth_filtered, 'a')
except:
os.remove(pth_filtered)
h5f = h5py.File(pth_filtered, 'a')
self.open_data()
self.open_mv_graph()
# filtered_data = defaultdict(dict)
for scan_id in tqdm(inter, desc='generating filtered data...'):
if scan_id in h5f:
continue
scan_data = c_sg_data[scan_id]
object_data = scan_data['nodes']
# relationships_data = scan_data['relationships']
''' build mapping '''
instance2labelName = {
int(key): node['label'] for key, node in object_data.items()}
mv_data = self.mv_data[scan_id]
mv_nodes = mv_data['nodes']
kfs = mv_data['kfs']
'''filter'''
# get the intersection between point and multi-view data
mv_node_ids = [int(x) for x in mv_nodes.keys()]
sg_node_ids = object_data.keys()
inter_node_ids = set(sg_node_ids).intersection(mv_node_ids)
# object_data = {nid: object_data[nid] for nid in inter_node_ids}
filtered_object_indices = [nid for nid in inter_node_ids]
if len(filtered_object_indices) == 0:
continue # skip if no intersection
dict_objId_kfId = dict() # make sure each object has at least a keyframe
kf_indices = []
'''select frames with at least 1 objects'''
for k in kfs.keys():
kf = kfs[k]
oids = [v[0] for v in kf.attrs['seg2idx']]
# filter object bbox with the intersection of the object_data
oids = set(object_data.keys()).intersection(oids)
if len(oids) == 0:
continue # skip if no object available
# filter keyframe by checking there is at least one object exist
obj_count = 0
for oid in oids:
oid = int(oid)
if oid in instance2labelName:
if instance2labelName[oid] in self.classNames:
dict_objId_kfId[oid] = k
obj_count += 1
if obj_count > 0:
kf_indices.append(int(k))
if len(kf_indices) == 0:
continue # skip if no keyframe available
filtered_object_indices = [k for k in dict_objId_kfId.keys()]
tmp = {
define.NAME_FILTERED_KF_INDICES: kf_indices,
define.NAME_FILTERED_OBJ_INDICES: filtered_object_indices
}
# filtered_data[scan_id] = tmp
buffer = data_to_raw(tmp)
h5f.create_dataset(scan_id, data=buffer, compression='gzip')
h5f.close()
# with h5py.File(pth_filtered, 'w') as h5f:
# for scan_id in filtered_data:
# buffer = data_to_raw(filtered_data[scan_id])
# h5f.create_dataset(scan_id,data=buffer,compression='gzip')
if not self.for_eval:
'''compute weights'''
if not os.path.isfile(pth_node_weights) or not os.path.isfile(pth_edge_weights):
training_scans = read_txt_to_list(os.path.join(
self.cfg.data.path_split, 'train_scans.txt'))
filtered_sg_data = dict()
self.open_filtered()
for scan_id in self.filtered_data.keys():
if scan_id not in training_scans:
continue # only compute over training scans
filtered_data = raw_to_data(self.filtered_data[scan_id])
node_indices = filtered_data[define.NAME_FILTERED_OBJ_INDICES]
# mv_node_ids = [int(x) for x in self.mv_data[scan_id]['nodes'].keys()]
# sg_node_ids = c_sg_data[scan_id]['nodes'].keys()
# inter_node_ids = set(sg_node_ids).intersection(mv_node_ids)
filtered_sg_data[scan_id] = dict()
filtered_sg_data[scan_id]['nodes'] = {
nid: c_sg_data[scan_id]['nodes'][nid] for nid in node_indices}
filtered_sg_data[scan_id]['relationships'] = c_sg_data[scan_id]['relationships']
c_sg_data = filtered_sg_data
if self.full_edge:
edge_mode = 'fully_connected'
else:
edge_mode = 'nn'
# edge_mode='gt'
# print('edge_mode:',edge_mode)
wobjs, wrels, o_obj_cls, o_rel_cls = compute_weight.compute_sgfn(self.classNames, self.relationNames, c_sg_data, training_scans,
normalize=config.data.normalize_weight,
for_BCE=self.multi_rel_outputs == True,
edge_mode=edge_mode,
none_index=self.none_idx,
verbose=config.VERBOSE)
for idx, obj_cls_name in enumerate(self.classNames):
if obj_cls_name in config.data.obj_ignore_list:
if config.VERBOSE:
print('ignore object ', obj_cls_name)
wobjs[idx] = 0
with open(self.pth_node_occ, 'w') as f:
for idx, obj_cls_name in enumerate(self.classNames):
f.write('{}\t{}\n'.format(
obj_cls_name, o_obj_cls[idx]))
with open(self.pth_edge_occ, 'w') as f:
for idx, rel_cls_name in enumerate(self.relationNames):
f.write('{}\t{}\n'.format(
rel_cls_name, o_rel_cls[idx]))
wobjs = np.array(wobjs)
wrels = np.array(wrels)
np.savetxt(pth_node_weights, wobjs)
np.savetxt(pth_edge_weights, wrels)
# test
_ = np.loadtxt(pth_node_weights)
_ = np.loadtxt(pth_edge_weights)
def __sample_points(self, scan_id, points, instances, cat: list, filtered_instances: list):
bboxes = list()
use_obj_context = False # TODO: not here
obj_points = torch.zeros(
[len(cat), self.mconfig.node_feature_dim, self.dim_pts])
descriptor = torch.zeros([len(cat), 11])
for i in range(len(filtered_instances)):
instance_id = filtered_instances[i]
obj_pointset = points[np.where(instances == instance_id)[0], :]
min_box = np.min(obj_pointset[:, :3], 0)
max_box = np.max(obj_pointset[:, :3], 0)
if use_obj_context:
min_box -= 0.02
max_box += 0.02
filter_mask = (points[:, 0] > min_box[0]) * (points[:, 0] < max_box[0]) \
* (points[:, 1] > min_box[1]) * (points[:, 1] < max_box[1]) \
* (points[:, 2] > min_box[2]) * (points[:, 2] < max_box[2])
obj_pointset = points[np.where(filter_mask > 0)[0], :]
bboxes.append([min_box, max_box])
if len(obj_pointset) == 0:
print('scan_id:', scan_id)
# print('selected_instances:',len(selected_instances))
print('filtered_instances:', len(filtered_instances))
print('instance_id:', instance_id)
choice = np.random.choice(len(obj_pointset), self.mconfig.node_feature_dim, replace=len(
obj_pointset) < self.mconfig.node_feature_dim)
obj_pointset = obj_pointset[choice, :]
descriptor[i] = util_data.gen_descriptor_pts(
torch.from_numpy(obj_pointset)[:, :3])
obj_pointset = torch.from_numpy(obj_pointset.astype(np.float32))
# util_data.save_to_ply(obj_pointset[:,:3],'./tmp_{}.ply'.format(i))
obj_pointset[:, :3] = self.norm_tensor(obj_pointset[:, :3])
obj_points[i] = obj_pointset
obj_points = obj_points.permute(0, 2, 1)
return obj_points, descriptor, bboxes
def __sample_rel_points(self, points, instances, idx2oid, bboxes, edge_indices):
rel_points = list()
for e in range(len(edge_indices)):
edge = edge_indices[e]
index1 = edge[0]
index2 = edge[1]
mask1 = (instances == idx2oid[index1]).astype(np.int32) * 1
mask2 = (instances == idx2oid[index2]).astype(np.int32) * 2
mask_ = np.expand_dims(mask1 + mask2, 1)
bbox1 = bboxes[index1]
bbox2 = bboxes[index2]
min_box = np.minimum(bbox1[0], bbox2[0])
max_box = np.maximum(bbox1[1], bbox2[1])
filter_mask = (points[:, 0] > min_box[0]) * (points[:, 0] < max_box[0]) \
* (points[:, 1] > min_box[1]) * (points[:, 1] < max_box[1]) \
* (points[:, 2] > min_box[2]) * (points[:, 2] < max_box[2])
points4d = np.concatenate([points, mask_], 1)
pointset = points4d[np.where(filter_mask > 0)[0], :]
choice = np.random.choice(
len(pointset), self.mconfig.num_points_union, replace=True)
pointset = pointset[choice, :]
pointset = torch.from_numpy(pointset.astype(np.float32))
# save_to_ply(pointset[:,:3],'./tmp_rel_{}.ply'.format(e))
pointset[:, :3] = zero_mean(pointset[:, :3], False)
rel_points.append(pointset)
if not self.for_eval:
try:
rel_points = torch.stack(rel_points, 0)
except:
rel_points = torch.zeros([0, self.mconfig.num_points_union, 4])
else:
if len(rel_points) == 0:
# print('len(edge_indices)',len(edge_indices))
# sometimes tere will have no edge because of only 1 ndoe exist.
# this is due to the label mapping/filtering process in the data generation
rel_points = torch.zeros([0, self.mconfig.num_points_union, 4])
else:
rel_points = torch.stack(rel_points, 0)
rel_points = rel_points.permute(0, 2, 1)
return rel_points
def __sample_3D_nodes(self, object_data: dict, mv_data: dict, nns: dict):
instance2labelName = {int(key): node['label']
for key, node in object_data.items()}
'''sample training set'''
instances_ids = list(instance2labelName.keys())
if 0 in instances_ids:
instances_ids.remove(0)
if self.sample_in_runtime and not self.for_eval:
selected_nodes = list(object_data.keys())
if self.mconfig.load_images:
mv_node_ids = [int(x) for x in mv_data['nodes'].keys()]
selected_nodes = list(
set(selected_nodes).intersection(mv_node_ids))
# selected_nodes = list(set(selected_nodes).intersection(filtered_data))
# if len(selected_nodes)==0:
# print('object_data.keys():',sorted(list(object_data.keys())))
# if self.mconfig.load_images:
# print('mv_node_ids',sorted(mv_node_ids))
# print('filtered_data:',sorted(np.asarray(filtered_data)))
# raise RuntimeError('no node available!')
use_all = False
# 1 if "sample_num_nn" not in self.config else self.config.sample_num_nn
sample_num_nn = self.mconfig.sample_num_nn
# 1 if "sample_num_seed" not in self.config else self.config.sample_num_seed
sample_num_seed = self.mconfig.sample_num_seed
if sample_num_nn == 0 or sample_num_seed == 0:
use_all = True
if not use_all:
# select 1 node and include their neighbor nodes n times.
filtered_nodes = util_data.build_neighbor_sgfn(
nns, selected_nodes, sample_num_nn, sample_num_seed)
else:
filtered_nodes = selected_nodes # use all nodes
instances_ids = list(filtered_nodes)
if 0 in instances_ids:
instances_ids.remove(0)
if 'max_num_node' in self.mconfig and self.mconfig.max_num_node > 0 and len(instances_ids) > self.mconfig.max_num_node:
instances_ids = random_drop(
instances_ids, self.mconfig.max_num_node)
if self.shuffle_objs:
random.shuffle(instances_ids)
'''
Find instances we care about. Build oid2idx and cat list
oid2idx maps instances to a mask id. to randomize the order of instance in training.
'''
oid2idx = {} # map instance_id to idx
idx2oid = {} # map idx to instance_id
cat = []
counter = 0
filtered_instances = list()
for instance_id in instances_ids:
class_id = -1
instance_labelName = instance2labelName[instance_id]
if instance_labelName in self.classNames:
class_id = self.classNames.index(instance_labelName)
# mask to cat:
# insstance 0 is unlabeled.
if (class_id >= 0) and (instance_id > 0):
oid2idx[int(instance_id)] = counter
idx2oid[counter] = int(instance_id)
counter += 1
filtered_instances.append(instance_id)
# idx2oid.append(int(instance_id))
cat.append(class_id)
return cat, oid2idx, idx2oid, filtered_instances
# return cat,idx2oid,filtered_instances
def __extract_relationship_data(self, relationships_data, oid2idx: dict):
'''build relaitonship data'''
relatinoships_gt = defaultdict(list)
for r in relationships_data:
r_src = int(r[0])
r_tgt = int(r[1])
r_lid = int(r[2])
r_cls = r[3]
if r_cls not in self.relationNames:
continue # only keep the relationships we want
# remap the index of relationships in case of custom relationNames
r_lid = self.relationNames.index(r_cls)
if r_src not in oid2idx or r_tgt not in oid2idx:
continue # only keep the relevant objects
key = (r_src, r_tgt)
# if r_src not in oid2idx or r_tgt not in oid2idx: continue
# index1 = oid2idx[r_src]
# index2 = oid2idx[r_tgt]
# key = (index1,index2)
# assert index1>=0
# assert index2>=0
# if self.sample_in_runtime:
# print('index1,index2',index1,index2, type(edge_indices),edge_indices)
# if key not in edge_indices: continue
relatinoships_gt[key].append(r_lid)
return relatinoships_gt
def __sample_relationships(self, relatinoships_gt: dict, idx2oid: dict, edge_indices: list):
if self.multi_rel_outputs:
gt_rels = torch.zeros(len(edge_indices), len(
self.relationNames), dtype=torch.float)
else:
gt_rels = torch.ones(