-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlarge_dataset_loc.py
461 lines (365 loc) · 18.9 KB
/
large_dataset_loc.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
from object_memory import *
import ast, pickle, shutil, time
import psutil, os
import pdb, pickle
@dataclass
class LocalArgs:
"""
Class to hold local configuration arguments.
"""
testname="subvolume_fix"
lora_path: str='models/vit_finegrained_5x40_procthor.pt'
test_folder_path: str='/scratch/aneesh.chavan/8room/8-room-v1/1/'
# rearranged_test_folder_path: str='/scratch/aneesh.chavan/8-room-new' # basically the dataset of the stuff ebing localised
rearranged_test_folder_path: str='/scratch/aneesh.chavan/8room/8-room-v1/1/' # basically the dataset of the stuff ebing localised
device: str='cuda'
sam_checkpoint_path: str = '/scratch/aneesh.chavan/sam_vit_h_4b8939.pth'
ram_pretrained_path: str = '/scratch/aneesh.chavan/ram_swin_large_14m.pth'
downsampling_rate: int = 5 # downsample points every these many frames
save_dir: str = "/scratch/aneesh.chavan/results/8-room-new-icp"
sampling_period: int = 15
start_file_index: int = 200
last_file_index: int = 1500
# rot_correction: float = 30.0 # keep as 30 for 8-room-new
rot_correction: float = 0.0
look_around_range: int = 0 # number of sucessive frames to consider at every frame
save_point_clouds: bool = True # Save ICP results
save_individual_objects: bool = True
save_localised_objects: bool = True
add_pose_noise: bool = True
down_sample_voxel_size: float = 0.01 # best results
create_ext_mesh: bool = False
fpfh_global_dist_factor: float = 1.5
fpfh_local_dist_factor: float = 0.4
fpfh_voxel_size: float = 0.05
localise_times: int = 1
loc_results_start_file_index: int = 210
# loc_results_last_file_index: int = 280
# loc_results_last_file_index: int = 600
# loc_results_start_file_index: int = 1289
# loc_results_last_file_index: int = 938
loc_results_last_file_index: int = 1400
loc_results_sampling_period: int = 13
useLora: bool=True
consider_floor=False
load_mem_from_mem=True
perform_semantic_icp=False
if __name__=="__main__":
start_time = time.time()
largs = tyro.cli(LocalArgs, description=__doc__)
print(largs)
# creating save dir
os.makedirs(largs.save_dir, exist_ok=True)
print(f"Created save directory {largs.save_dir}")
files = os.listdir(os.path.join(largs.test_folder_path, "rgb"))
num_files = len(files)
print(f"We have {num_files} files")
print("\nBegin Memory Initialization")
mem = ObjectMemory(device = largs.device,
ram_pretrained_path=largs.ram_pretrained_path,
sam_checkpoint_path = largs.sam_checkpoint_path,
lora_path=largs.lora_path)
print("Memory Init'ed\n")
if largs.last_file_index == -1:
largs.last_file_index = num_files
if largs.loc_results_last_file_index == -1:
largs.loc_results_last_file_index = num_files
frame_counter = 0
if largs.load_mem_from_mem == False:
for cur_frame in tqdm(range(largs.start_file_index,
largs.last_file_index + 1,
largs.sampling_period),
total=(largs.last_file_index-largs.start_file_index)//largs.sampling_period):
for i in range(cur_frame, min(largs.last_file_index + 1, cur_frame + largs.look_around_range + 1)):
print(f"\n\tSeeing image {i} currently")
image_file_path = os.path.join(largs.test_folder_path,
f"rgb/{i}.png")
depth_file_path = os.path.join(largs.test_folder_path,
f"depth/{i}.npy")
pose_file_path = os.path.join(largs.test_folder_path,
f"pose/{i}.txt")
with open(pose_file_path, 'r') as file:
pose_dict = file.read()
pose_dict = ast.literal_eval(pose_dict)
pose_dict = {
"position": {
"x": pose_dict[0]['x'],
"y": pose_dict[0]['y'],
"z": pose_dict[0]['z']
},
"rotation": {
"x": pose_dict[1]['x'] + largs.rot_correction,
"y": pose_dict[1]['y'],
"z": pose_dict[1]['z']
}
}
q = Rotation.from_euler('xyz', [r for _, r in pose_dict["rotation"].items()], degrees=True).as_quat()
t = np.array([x for _, x in pose_dict["position"].items()])
pose = np.concatenate([t, q])
mem.process_image(testname=f"view%d" % i,
image_path = image_file_path,
depth_image_path = depth_file_path,
pose=pose,
verbose=False, add_noise=largs.add_pose_noise, useLora = largs.useLora,
consider_floor=largs.consider_floor)
pid = psutil.Process()
memory_info = pid.memory_info()
memory_info_GBs = memory_info.rss / (1e3 ** 3)
# print(f"Memory usage: {memory_info_GBs:.3f} GB")
cuda_memory_stats = torch.cuda.memory_stats()
max_cuda_memory_GBs = int(cuda_memory_stats["allocated_bytes.all.peak"]) / (1e3 ** 3)
# print(f"Max GPU memory usage: {max_cuda_memory_GBs:.3f} GB")
print("\t ----------------")
# periodically downsample
if frame_counter % largs.downsampling_rate == 0:
# if largs.down_sample_voxel_size > 0:
# print(f"Downsampling at {frame_counter} frame voxel size as {largs.down_sample_voxel_size}")
mem.downsample_all_objects(voxel_size=largs.down_sample_voxel_size)
""" Commented both out to test dbscanning """
# mem.consolidate_memory()
# mem.remove_object_floors()
# # begin debug
if i > 60:
pcd_list = []
for info in mem.memory:
object_pcd = info.pcd
pcd_list.append(object_pcd)
combined_pcd = o3d.geometry.PointCloud()
for bhencho in range(len(pcd_list)):
pcd_np = pcd_list[bhencho]
pcd_vec = o3d.utility.Vector3dVector(pcd_np.T)
pcd = o3d.geometry.PointCloud()
pcd.points = pcd_vec
pcd.paint_uniform_color(np.random.rand(3))
combined_pcd += pcd
save_path = os.path.join(largs.save_dir,
f"/home2/aneesh.chavan/Change_detection/pcds/{largs.testname}_after_cons.ply")
o3d.io.write_point_cloud(save_path, combined_pcd)
print("Memory's pointcloud saved to", save_path)
# pdb.set_trace()
# end debug
frame_counter += 1
if largs.down_sample_voxel_size > 0:
print(f"Downsampling using voxel size as {largs.down_sample_voxel_size}")
mem.downsample_all_objects(voxel_size=largs.down_sample_voxel_size)
#######
# save memory point cloud
pcd_list = []
for info in mem.memory:
object_pcd = info.pcd
pcd_list.append(object_pcd)
combined_pcd = o3d.geometry.PointCloud()
for bhencho in range(len(pcd_list)):
pcd_np = pcd_list[bhencho]
pcd_vec = o3d.utility.Vector3dVector(pcd_np.T)
pcd = o3d.geometry.PointCloud()
pcd.points = pcd_vec
pcd.paint_uniform_color(np.random.rand(3))
combined_pcd += pcd
save_path = os.path.join(largs.save_dir,
f"/home2/aneesh.chavan/Change_detection/pcds/cached_{largs.testname}_after_cons.ply")
o3d.io.write_point_cloud(save_path, combined_pcd)
#######
# dbscan all objects and cluster them
mem.recluster_via_dbscan(viz=True)
mem.remove_object_floors()
end_time = time.time()
print(f"Traversal completed in {end_time - start_time} seconds")
frame_counter += 1
print(f"{(end_time - start_time)/float(frame_counter)} seconds per image for {frame_counter} images\n")
else:
mem = pickle.load(open('cached_memories/clustered_mem.pkl', 'rb'))
print("Memory loaded")
#####################################################
pcd_list = []
for info in mem.memory:
object_pcd = info.pcd
pcd_list.append(object_pcd)
combined_pcd = o3d.geometry.PointCloud()
if largs.save_localised_objects:
localised_mem_save_dir = os.path.join(largs.save_dir,
f"localised_mems")
os.makedirs(localised_mem_save_dir, exist_ok=True)
if largs.save_individual_objects:
individual_mem_save_dir = os.path.join(largs.save_dir,
f"ind_mems")
os.makedirs(individual_mem_save_dir, exist_ok=True)
for i in range(len(pcd_list)):
pcd_np = pcd_list[i]
pcd_vec = o3d.utility.Vector3dVector(pcd_np.T)
pcd = o3d.geometry.PointCloud()
pcd.points = pcd_vec
if largs.save_individual_objects:
cur_save_path = os.path.join(individual_mem_save_dir,
f"memory_{i}.ply")
o3d.io.write_point_cloud(cur_save_path, pcd)
print(f"{i} pointcloud saved to", cur_save_path)
combined_pcd += pcd
# save memory point cloud
pcd_list = []
for info in mem.memory:
object_pcd = info.pcd
pcd_list.append(object_pcd)
combined_pcd = o3d.geometry.PointCloud()
for bhencho in range(len(pcd_list)):
pcd_np = pcd_list[bhencho]
pcd_vec = o3d.utility.Vector3dVector(pcd_np.T)
pcd = o3d.geometry.PointCloud()
pcd.points = pcd_vec
pcd.paint_uniform_color(np.random.rand(3))
combined_pcd += pcd
save_path = os.path.join(largs.save_dir,
f"/home2/aneesh.chavan/Change_detection/pcds/{largs.testname}_after_cons.ply")
o3d.io.write_point_cloud(save_path, combined_pcd)
print("Memory's pointcloud saved to", save_path)
print("\n\n\t---------------------")
mem.view_memory()
start_time = time.time()
tgt = []
pred = []
trans_errors = []
rot_errors = []
chosen_assignments = []
for n, i in tqdm(enumerate(range(largs.loc_results_start_file_index,
largs.loc_results_last_file_index + 1,
largs.loc_results_sampling_period)), total=(largs.loc_results_start_file_index-largs.loc_results_start_file_index)//largs.loc_results_sampling_period):
print(f"\n\tLocalizing image {i} currently")
image_file_path = os.path.join(largs.rearranged_test_folder_path,
f"rgb/{i}.png")
depth_file_path = os.path.join(largs.rearranged_test_folder_path,
f"depth/{i}.npy")
pose_file_path = os.path.join(largs.rearranged_test_folder_path,
f"pose/{i}.txt")
with open(pose_file_path, 'r') as file:
pose_dict = file.read()
pose_dict = ast.literal_eval(pose_dict)
pose_dict = {
"position": {
"x": pose_dict[0]['x'],
"y": pose_dict[0]['y'],
"z": pose_dict[0]['z']
},
"rotation": {
"x": pose_dict[1]['x'] + largs.rot_correction,
"y": pose_dict[1]['y'],
"z": pose_dict[1]['z']
}
}
q = Rotation.from_euler('xyz', [r for _, r in pose_dict["rotation"].items()], degrees=True).as_quat()
t = np.array([x for _, x in pose_dict["position"].items()])
target_pose = np.concatenate([t, q])
tgt.append(target_pose)
if largs.save_localised_objects:
estimated_pose, chosen_assignment = mem.localise(image_path=image_file_path,
depth_image_path=depth_file_path,
testname=largs.testname,
subtest_name=f"{i}" ,
save_point_clouds=largs.save_point_clouds,
fpfh_global_dist_factor = largs.fpfh_global_dist_factor,
fpfh_local_dist_factor = largs.fpfh_global_dist_factor,
fpfh_voxel_size = largs.fpfh_voxel_size,
save_localised_pcd_path = localised_mem_save_dir, useLora = largs.useLora,
consider_floor=largs.consider_floor,
perform_semantic_icp=largs.perform_semantic_icp)
else:
estimated_pose, chosen_assignment = mem.localise(image_path=image_file_path,
depth_image_path=depth_file_path,
testname=largs.testname,
subtest_name=f"{i}" ,
save_point_clouds=largs.save_point_clouds,
fpfh_global_dist_factor = largs.fpfh_global_dist_factor,
fpfh_local_dist_factor = largs.fpfh_global_dist_factor,
fpfh_voxel_size = largs.fpfh_voxel_size, useLora = largs.useLora,
consider_floor=largs.consider_floor,
perform_semantic_icp=largs.perform_semantic_icp)
# save detected objs
_, _, detected_pcds = mem._get_object_info(image_path=image_file_path, depth_image_path=depth_file_path, useLora=largs.useLora, consider_floor=largs.consider_floor)
if largs.save_individual_objects and detected_pcds is not None:
p = o3d.geometry.PointCloud()
for j, det_pcd in enumerate(detected_pcds):
save_path = os.path.join(individual_mem_save_dir,
f"detected_img_{n}_{j}.ply")
p.points = o3d.utility.Vector3dVector(det_pcd.T)
o3d.io.write_point_cloud(save_path, p)
print(f"Img {i} obj {j} pointcloud saved to", save_path)
print("Target pose: ", target_pose)
print("Estimated pose: ", estimated_pose)
translation_error = np.linalg.norm(target_pose[:3] - estimated_pose[:3])
rotation_error = QuaternionOps.quaternion_error(target_pose[3:], estimated_pose[3:])
print("Translation error: ", translation_error)
print("Rotation_error: ", rotation_error)
# ## DEBUG
# if detected_pcds is not None:
# print("DEBUG BEGINS")
# print(f"Detectec len {len(detected_pcds)}")
# outlier_removal_config = {
# "radius_nb_points": 8,
# "radius": 0.05,
# }
# assn = chosen_assignment[0]
# all_detected_points = []
# all_memory_points = []
# for pcd in detected_pcds:
# all_detected_points.append(pcd)
# for info in mem.memory:
# all_memory_points.append(info.pcd)
# all_detected_points = np.concatenate(all_detected_points, axis=-1).T
# all_memory_points = np.concatenate(all_memory_points, axis=-1).T
# all_detected_pcd = o3d.geometry.PointCloud()
# all_memory_pcd = o3d.geometry.PointCloud()
# all_detected_pcd.points = o3d.utility.Vector3dVector(all_detected_points)
# all_memory_pcd.points = o3d.utility.Vector3dVector(all_memory_points)
# # all_detected_pcd_filtered, _ = all_detected_pcd.remove_radius_outlier(nb_points=outlier_removal_config["radius_nb_points"],
# # radius=outlier_removal_config["radius"])
# all_memory_pcd = all_memory_pcd.voxel_down_sample(0.05)
# all_memory_pcd.paint_uniform_color([0,1,1])
# all_detected_pcd.paint_uniform_color([1,0,0])
# print("points: ", all_detected_points)
# o3d.io.write_point_cloud(f"./temp/{str(assn)}-{i}-ISTHISIT.ply", all_detected_pcd)
# transform = np.eye(4)
# transform[:3,:3] = Rotation.from_quat(estimated_pose[3:]).as_matrix()
# transform[:3, 3] = estimated_pose[:3]
# print(transform)
# o3d.io.write_point_cloud(f"./temp/{str(assn)}-{i}-full_aligned.ply", all_memory_pcd +
# all_detected_pcd.transform(transform))
# o3d.io.write_point_cloud(f"./temp/{str(assn)}-{i}-full_aligned_test.ply", all_detected_pcd.transform(transform))
# # import pdb;
# # if len(detected_pcds) > 0:
# # pdb.set_trace()
# ## END DEBUG
pred.append(estimated_pose.tolist())
trans_errors.append(translation_error)
rot_errors.append(rotation_error)
chosen_assignments.append(chosen_assignment)
# if n % 10 == 0:
# for ii in range(len(trans_errors)):
# print(f"Pose {i + 1}")
# print("Translation error", trans_errors[ii])
# print("Rotation errors", rot_errors[ii])
# print("Assignment: ", chosen_assignments[ii][0])
# print("Moved objects: ", chosen_assignments[ii][1])
for i, n in enumerate(range(largs.loc_results_start_file_index,
largs.loc_results_last_file_index + 1,
largs.loc_results_sampling_period)):
print(f"Pose {i + 1}, image {n}")
print("Translation error", trans_errors[i])
print("Rotation errors", rot_errors[i])
print("Assignment: ", chosen_assignments[i][0])
print("Moved objects: ", chosen_assignments[i][1])
if trans_errors[i] < 0.6 and rot_errors[i] < 0.3:
print("SUCCESS")
else:
print("MISALIGNED")
print()
results = {
"translation_errors": trans_errors,
"rotation_errors": rot_errors,
"assignments": chosen_assignments,
}
save_path = os.path.join(largs.save_dir,
f"results.pkl")
with open(save_path, "wb") as f:
pickle.dump(results, f)
print("Resuts saved to", save_path)
end_time = time.time()
print(f"Localization completed in {end_time - start_time} seconds")