-
Notifications
You must be signed in to change notification settings - Fork 2
/
MyhalCollision.py
4141 lines (3349 loc) · 165 KB
/
MyhalCollision.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
#
#
# 0=================================0
# | Kernel Point Convolutions |
# 0=================================0
#
#
# ----------------------------------------------------------------------------------------------------------------------
#
# Class handling SemanticKitti dataset.
# Implements a Dataset, a Sampler, and a collate_fn
#
# ----------------------------------------------------------------------------------------------------------------------
#
# Hugues THOMAS - 11/06/2018
#
# ----------------------------------------------------------------------------------------------------------------------
#
# Imports and global variables
# \**********************************/
#
# Common libs
import sys
import time
import os
os.environ.update(OMP_NUM_THREADS='1',
OPENBLAS_NUM_THREADS='1',
NUMEXPR_NUM_THREADS='1',
MKL_NUM_THREADS='1',)
import numpy as np
import pickle
import yaml
import torch
from multiprocessing import Lock
from datasets.common import PointCloudDataset, batch_neighbors
from torch.utils.data import Sampler
from utils.config import bcolors
from datasets.common import grid_subsampling
import matplotlib.pyplot as plt
from scipy.spatial.transform import Rotation as scipyR
from sklearn.neighbors import KDTree
from slam.PointMapSLAM import PointMap, extract_map_ground, extract_ground
from slam.cpp_slam import update_pointmap, polar_normals, point_to_map_icp, slam_on_sim_sequence, ray_casting_annot, get_lidar_visibility
from slam.dev_slam import frame_H_to_points, interp_pose, rot_trans_diffs, normals_orientation, save_trajectory, RANSAC
from utils.ply import read_ply, write_ply
from utils.mayavi_visu import save_future_anim, fast_save_future_anim
# OS functions
from os import listdir, makedirs
from os.path import exists, join, isdir, getsize
# ----------------------------------------------------------------------------------------------------------------------
#
# Special dataset class for SLAM
# \************************************/
class MyhalCollisionSlam:
def __init__(self,
only_day_1=False,
first_day='',
last_day='',
day_list=None,
map_day=None,
verbose=1):
# Name of the dataset
self.name = 'MyhalCollisionSlam'
# Data path
self.original_path = '../Data/Simulation'
self.data_path = self.original_path
self.days_folder = join(self.original_path, 'simulated_runs')
self.frame_folder_name = 'sim_frames'
self.map_day = map_day
# List of days
if day_list is not None:
# Use explicit day list
self.days = np.array(day_list)
else:
# Use first and last days
self.days = np.sort([d for d in listdir(self.days_folder)])
if len(first_day) == 0:
first_day = self.days[0]
if len(last_day) == 0:
last_day = self.days[-1]
self.days = np.sort(
[d for d in self.days if first_day <= d <= last_day])
# Parameters
self.only_day_1 = only_day_1
self.motion_distortion = False
self.day_f_times = []
self.day_f_names = []
self.map_f_times = None
self.map_f_names = None
self.get_frames_names()
##################
# Load calibration
##################
# Calibration file from simulation
calib_csv = join(self.original_path, 'calibration', 'jackal_calib.csv')
calib = np.loadtxt(calib_csv, delimiter=',', dtype=str)
T_base_A = [float(t) for t in calib[1, 2:5]]
T_A_B = [float(t) for t in calib[4, 2:5]]
T_B_velo = [float(t) for t in calib[7, 2:5]]
Q_base_A = np.array([float(t) for t in calib[1, 5:9]])
Q_A_B = np.array([float(t) for t in calib[4, 5:9]])
Q_B_velo = np.array([float(t) for t in calib[7, 5:9]])
# Transorm quaternions and translation into homogenus 4x4 matrices
H_base_A = np.eye(4, dtype=np.float64)
H_base_A[:3, :3] = scipyR.from_quat(Q_base_A).as_matrix()
H_base_A[:3, 3] = T_base_A
H_A_B = np.eye(4, dtype=np.float64)
H_A_B[:3, :3] = scipyR.from_quat(Q_A_B).as_matrix()
H_A_B[:3, 3] = T_A_B
H_B_velo = np.eye(4, dtype=np.float64)
H_B_velo[:3, :3] = scipyR.from_quat(Q_B_velo).as_matrix()
H_B_velo[:3, 3] = T_B_velo
self.H_velo_base = np.matmul(H_B_velo, np.matmul(H_A_B, H_base_A))
self.H_base_velo = np.linalg.inv(self.H_velo_base)
###############
# Load GT poses
###############
if verbose:
print('\nLoading days groundtruth poses...')
t0 = time.time()
self.gt_t, self.gt_H = self.load_gt_poses()
t2 = time.time()
if verbose:
print('Done in {:.1f}s\n'.format(t2 - t0))
################
# Load loc poses
################
if verbose:
print('\nLoading days localization poses...')
t0 = time.time()
self.loc_t, self.loc_H = self.load_loc_poses()
t2 = time.time()
if verbose:
print('Done in {:.1f}s\n'.format(t2 - t0))
return
def get_frames_names(self, verbose=1):
# Loop on days
self.day_f_times = []
self.day_f_names = []
for d, day in enumerate(self.days):
# Get frame timestamps
frames_folder = join(self.days_folder, day, self.frame_folder_name)
if not exists(frames_folder):
frames_folder = join(self.days_folder, day,
'classified_frames')
f_names = [f for f in listdir(frames_folder) if f[-4:] == '.ply']
f_times = np.array([float(f[:-4]) for f in f_names],
dtype=np.float64)
f_names = np.array([join(frames_folder, f) for f in f_names])
ordering = np.argsort(f_times)
f_names = f_names[ordering]
f_times = f_times[ordering]
self.day_f_times.append(f_times)
self.day_f_names.append(f_names)
if self.only_day_1 and d > -1:
break
# Handle map day
frames_folder = join(self.days_folder, self.map_day,
self.frame_folder_name)
f_names = [f for f in listdir(frames_folder) if f[-4:] == '.ply']
f_times = np.array([float(f[:-4]) for f in f_names], dtype=np.float64)
f_names = np.array([join(frames_folder, f) for f in f_names])
ordering = np.argsort(f_times)
self.map_f_names = f_names[ordering]
self.map_f_times = f_times[ordering]
return
def load_gt_poses_old(self):
#gt_files = np.sort([gt_f for gt_f in listdir(self.days) if gt_f[-4:] == '.csv'])
gt_H = []
gt_t = []
for d, day in enumerate(self.days):
# Out files
gt_folder = join(self.data_path, 'slam_gt', day)
if not exists(gt_folder):
makedirs(gt_folder)
t1 = time.time()
gt_pkl_file = join(gt_folder, 'gt_poses.pkl')
if exists(gt_pkl_file):
# Read pkl
with open(gt_pkl_file, 'rb') as f:
day_gt_t, day_gt_H = pickle.load(f)
else:
# File paths
gt_csv = join(self.days_folder, day, 'gt_poses.csv')
# Load gt
day_gt_t = np.loadtxt(gt_csv,
delimiter=',',
usecols=0,
skiprows=1,
dtype=np.uint64)
gt_T = np.loadtxt(gt_csv,
delimiter=',',
usecols=(5, 6, 7),
skiprows=1,
dtype=np.float32)
gt_Q = np.loadtxt(gt_csv,
delimiter=',',
usecols=(8, 9, 10, 11),
skiprows=1,
dtype=np.float32)
# Convert gt to homogenous rotation/translation matrix
gt_R = scipyR.from_quat(gt_Q)
gt_R = gt_R.as_matrix()
day_gt_H = np.zeros((len(day_gt_t), 4, 4))
day_gt_H[:, :3, :3] = gt_R
day_gt_H[:, :3, 3] = gt_T
day_gt_H[:, 3, 3] = 1
# Save pickle
with open(gt_pkl_file, 'wb') as f:
pickle.dump([day_gt_t, day_gt_H], f)
t2 = time.time()
print('{:s} {:d}/{:d} Done in {:.1f}s'.format(
day, d, len(self.days), t2 - t1))
gt_t += [day_gt_t]
gt_H += [day_gt_H]
if self.only_day_1 and d > -1:
break
return gt_t, gt_H
def load_gt_poses(self):
gt_H = []
gt_t = []
for d, day in enumerate(self.days):
# Out files
gt_folder = join(self.data_path, 'slam_gt', day)
if not exists(gt_folder):
makedirs(gt_folder)
t1 = time.time()
# Load gt from ply files
gt_ply_file = join(self.days_folder, day, 'gt_pose.ply')
if not exists(gt_ply_file):
print('No groundtruth poses found at ' + gt_ply_file)
print('Using localization poses instead')
gt_ply_file = join(self.days_folder, day, 'loc_pose.ply')
if not exists(gt_ply_file):
raise ValueError('No localization poses found at ' + gt_ply_file)
data = read_ply(gt_ply_file)
gt_T = np.vstack([data['pos_x'], data['pos_y'], data['pos_z']]).T
gt_Q = np.vstack([data['rot_x'], data['rot_y'], data['rot_z'], data['rot_w']]).T
# Times
day_gt_t = data['time']
# print(day_gt_t)
# print(self.day_f_times[d])
# plt.plot(day_gt_t, day_gt_t*0, '.')
# plt.plot(self.day_f_times[d], self.day_f_times[d]*0, '.')
# plt.show()
# a = 1/0
# Convert gt to homogenous rotation/translation matrix
gt_R = scipyR.from_quat(gt_Q)
gt_R = gt_R.as_matrix()
day_gt_H = np.zeros((len(day_gt_t), 4, 4))
day_gt_H[:, :3, :3] = gt_R
day_gt_H[:, :3, 3] = gt_T
day_gt_H[:, 3, 3] = 1
t2 = time.time()
print('{:s} {:d}/{:d} Done in {:.1f}s'.format(
day, d, len(self.days), t2 - t1))
gt_t += [day_gt_t]
gt_H += [day_gt_H]
# # Remove frames that are not inside gt timings
# mask = np.logical_and(self.day_f_times[d] > day_gt_t[0], self.day_f_times[d] < day_gt_t[-1])
# self.day_f_names[d] = self.day_f_names[d][mask]
# self.day_f_times[d] = self.day_f_times[d][mask]
if self.only_day_1 and d > -1:
break
return gt_t, gt_H
def load_loc_poses(self):
loc_H = []
loc_t = []
for d, day in enumerate(self.days):
t1 = time.time()
# Load loc from ply files
loc_ply_file = join(self.days_folder, day, 'loc_pose.ply')
if not exists(loc_ply_file):
raise ValueError('No localization poses found at ' + loc_ply_file)
data = read_ply(loc_ply_file)
loc_T = np.vstack([data['pos_x'], data['pos_y'], data['pos_z']]).T
loc_Q = np.vstack([data['rot_x'], data['rot_y'], data['rot_z'], data['rot_w']]).T
# Times
day_loc_t = data['time']
# print(day_loc_t)
# print(self.day_f_times[d])
# plt.plot(day_loc_t, day_loc_t*0, '.')
# plt.plot(self.day_f_times[d], self.day_f_times[d]*0, '.')
# plt.show()
# a = 1/0
# Convert loc to homogenous rotation/translation matrix
loc_R = scipyR.from_quat(loc_Q)
loc_R = loc_R.as_matrix()
day_loc_H = np.zeros((len(day_loc_t), 4, 4))
day_loc_H[:, :3, :3] = loc_R
day_loc_H[:, :3, 3] = loc_T
day_loc_H[:, 3, 3] = 1
t2 = time.time()
print('{:s} {:d}/{:d} Done in {:.1f}s'.format(
day, d, len(self.days), t2 - t1))
loc_t += [day_loc_t]
loc_H += [day_loc_H]
if self.only_day_1 and d > -1:
break
return loc_t, loc_H
def load_map_poses(self, day):
# Load map from ply files
map_ply_file = join(self.days_folder, day, 'logs-' + day,
'map_traj.ply')
data = read_ply(map_ply_file)
map_T = np.vstack([data['pos_x'], data['pos_y'], data['pos_z']]).T
map_Q = np.vstack(
[data['rot_x'], data['rot_y'], data['rot_z'], data['rot_w']]).T
# Times
day_map_t = data['time']
# Convert map to homogenous rotation/translation matrix
map_R = scipyR.from_quat(map_Q)
map_R = map_R.as_matrix()
day_map_H = np.zeros((len(day_map_t), 4, 4))
day_map_H[:, :3, :3] = map_R
day_map_H[:, :3, 3] = map_T
day_map_H[:, 3, 3] = 1
return day_map_t, day_map_H
def load_map_gt_poses(self):
####################################
# Load gt poses from mapping session
####################################
# Load gt from ply files
gt_ply_file = join(self.days_folder, self.map_day, 'gt_pose.ply')
data = read_ply(gt_ply_file)
gt_T = np.vstack([data['pos_x'], data['pos_y'], data['pos_z']]).T
gt_Q = np.vstack(
[data['rot_x'], data['rot_y'], data['rot_z'], data['rot_w']]).T
# Times
day_gt_t = data['time']
# print(day_gt_t)
# print(self.day_f_times[d])
# plt.plot(day_gt_t, day_gt_t*0, '.')
# plt.plot(self.day_f_times[d], self.day_f_times[d]*0, '.')
# plt.show()
# a = 1/0
# Convert gt to homogenous rotation/translation matrix
gt_R = scipyR.from_quat(gt_Q)
gt_R = gt_R.as_matrix()
day_gt_H = np.zeros((len(day_gt_t), 4, 4))
day_gt_H[:, :3, :3] = gt_R
day_gt_H[:, :3, 3] = gt_T
day_gt_H[:, 3, 3] = 1
return day_gt_t, day_gt_H
def load_frame_points(self, frame_path):
data = read_ply(frame_path)
points = np.vstack((data['x'], data['y'], data['z'])).T
# Safe check for points equal to zero
hr = np.sqrt(np.sum(points[:, :2]**2, axis=1))
points = points[hr > 1e-6]
if np.sum((hr < 1e-6).astype(np.int32)) > 0:
print('Warning: lidar frame with invalid points: frame_names[i].')
a = 1 / 0
return points
def load_frame_points_labels(self, frame_path):
data = read_ply(frame_path)
points = np.vstack((data['x'], data['y'], data['z'])).T
if 'category' in data.dtype.names:
labels = data['category']
elif 'cat' in data.dtype.names:
labels = data['cat']
else:
labels = -np.ones(points[:, 0].shape, dtype=np.int32)
# Safe check for points equal to zero
hr = np.sqrt(np.sum(points[:, :2]**2, axis=1))
labels = labels[hr > 1e-6]
points = points[hr > 1e-6]
if np.sum((hr < 1e-6).astype(np.int32)) > 0:
print('Warning: lidar frame with invalid points: frame_names[i].')
a = 1 / 0
return points, labels
def debug_angular_velocity(self):
for d, day in enumerate(self.days):
# List of frames for this day
frame_times = self.day_f_times[d]
# List of groundtruth timestamps and poses
gt_t = self.gt_t[d]
gt_H = self.gt_H[d]
all_frame_H = []
for i, f_t in enumerate(frame_times):
# Find closest gt poses
gt_i1 = np.argmin(np.abs(gt_t - f_t))
if f_t < gt_t[gt_i1]:
gt_i0 = gt_i1 - 1
else:
gt_i0 = gt_i1
gt_i1 = gt_i0 + 1
# Interpolate the ground truth pose at current time
interp_t = (f_t - gt_t[gt_i0]) / (gt_t[gt_i1] - gt_t[gt_i0])
frame_H = interp_pose(interp_t, gt_H[gt_i0], gt_H[gt_i1])
# Transformation of the lidar (gt is in body frame)
all_frame_H.append(np.matmul(frame_H, self.H_velo_base))
all_frame_H = np.stack(all_frame_H, axis=0)
dT, dR = rot_trans_diffs(all_frame_H)
plt.figure('dT')
plt.plot(dT)
plt.figure('dR')
plt.plot(dR * 180 / np.pi)
plt.show()
return
def gt_mapping(self, map_voxel_size=0.08, save_group=50, verbose=1):
#################
# Init parameters
#################
# Out files
out_folder = join(self.data_path, 'slam_gt')
if not exists(out_folder):
makedirs(out_folder)
##########################
# Start first pass of SLAM
##########################
for d, day in enumerate(self.days):
out_day_folder = join(out_folder, day)
if not exists(out_day_folder):
makedirs(out_day_folder)
for folder_name in ['trajectory', 'map', 'frames']:
if not exists(join(out_day_folder, folder_name)):
makedirs(join(out_day_folder, folder_name))
gt_slam_file = join(out_day_folder, 'gt_map_{:s}.pkl'.format(day))
if exists(gt_slam_file):
continue
# List of frames for this day
frame_names = self.day_f_names[d]
frame_times = self.day_f_times[d]
# List of groundtruth timestamps and poses
gt_t = self.gt_t[d]
gt_H = self.gt_H[d]
# Initiate map
transform_list = []
pointmap = PointMap(dl=map_voxel_size)
last_saved_frames = 0
FPS = 0
N = len(frame_names)
# Test mapping
for i, f_t in enumerate(frame_times):
t = [time.time()]
# Load ply format points
points = self.load_frame_points(frame_names[i])
t += [time.time()]
# Get normals (dummy r_scale to avoid removing points as simulation scans are perfect)
normals, planarity, linearity = polar_normals(points,
radius=1.5,
lidar_n_lines=31,
h_scale=0.5,
r_scale=1000.0)
norm_scores = planarity + linearity
# Remove outliers
points = points[norm_scores > 0.1]
normals = normals[norm_scores > 0.1]
norm_scores = norm_scores[norm_scores > 0.1]
# Filter out points according to main normal directions (Not necessary if normals are better computed)
# norm_scores *= normal_filtering(normals)
# Find closest gt poses
gt_i1 = np.argmin(np.abs(gt_t - f_t))
if f_t < gt_t[gt_i1]:
gt_i0 = gt_i1 - 1
else:
gt_i0 = gt_i1
gt_i1 = gt_i0 + 1
if gt_i1 >= len(gt_t):
break
# Interpolate the ground truth pose at current time
interp_t = (f_t - gt_t[gt_i0]) / (gt_t[gt_i1] - gt_t[gt_i0])
frame_H = interp_pose(interp_t, gt_H[gt_i0], gt_H[gt_i1])
# Transformation of the lidar (gt is in body frame)
H_velo_world = np.matmul(frame_H, self.H_velo_base)
transform_list.append(H_velo_world)
# Apply transf
world_points = np.hstack((points, np.ones_like(points[:, :1])))
world_points = np.matmul(world_points, H_velo_world.T).astype(
np.float32)[:, :3]
world_normals = np.matmul(
normals, H_velo_world[:3, :3].T).astype(np.float32)
t += [time.time()]
# Update map
pointmap.update(world_points, world_normals, norm_scores)
if i % save_group == 0:
filename = join(out_day_folder, 'map',
'gt_map_{:03d}.ply'.format(i))
write_ply(filename, [
pointmap.points, pointmap.normals, pointmap.scores,
pointmap.counts
], ['x', 'y', 'z', 'nx', 'ny', 'nz', 'scores', 'counts'])
t += [time.time()]
if verbose == 2:
ti = 0
print('Load ............ {:7.1f}ms'.format(
1000 * (t[ti + 1] - t[ti])))
ti += 1
print('Preprocessing ... {:7.1f}ms'.format(
1000 * (t[ti + 1] - t[ti])))
ti += 1
print('Align ........... {:7.1f}ms'.format(
1000 * (t[ti + 1] - t[ti])))
ti += 1
print('Mapping ......... {:7.1f}ms'.format(
1000 * (t[ti + 1] - t[ti])))
if verbose > 0:
fmt_str = 'GT Mapping {:3d} --- {:5.1f}% or {:02d}:{:02d}:{:02d} remaining at {:.1f}fps'
if i == 0:
FPS = 1 / (t[-1] - t[0])
else:
FPS += (1 / (t[-1] - t[0]) - FPS) / 10
remaining = int((N - (i + 1)) / FPS)
hours = remaining // 3600
remaining = remaining - 3600 * hours
minutes = remaining // 60
seconds = remaining - 60 * minutes
print(
fmt_str.format(i, 100 * (i + 1) / N, hours, minutes,
seconds, FPS))
# Save groups of 100 frames together
if (i > last_saved_frames + save_group + 1):
all_points = []
all_labels = []
all_traj_pts = []
all_traj_clrs = []
all_traj_pts2 = []
all_traj_clrs2 = []
i0 = last_saved_frames
i1 = i0 + save_group
for save_i, save_f_t in enumerate(frame_times[i0:i1]):
# Load points
points, labels = self.load_frame_points_labels(
frame_names[i0 + save_i])
# Find closest gt poses
gt_i1 = np.argmin(np.abs(gt_t - save_f_t))
if save_f_t < gt_t[gt_i1]:
gt_i0 = gt_i1 - 1
else:
gt_i0 = gt_i1
gt_i1 = gt_i0 + 1
# Interpolate the ground truth pose at current time
interp_t = (save_f_t - gt_t[gt_i0]) / (gt_t[gt_i1] - gt_t[gt_i0])
world_H = interp_pose(interp_t, gt_H[gt_i0],
gt_H[gt_i1])
# Transformation of the lidar (gt is in body frame)
H_velo_world = np.matmul(world_H, self.H_velo_base)
# Apply transf
world_pts = np.hstack(
(points, np.ones_like(points[:, :1])))
world_pts = np.matmul(
world_pts, H_velo_world.T).astype(np.float32)
# Save frame
world_pts[:, 3] = i0 + save_i
all_points.append(world_pts)
all_labels.append(labels)
# also save trajectory
traj_pts, traj_clrs = frame_H_to_points(H_velo_world,
size=0.1)
traj_pts = np.hstack(
(traj_pts,
np.ones_like(traj_pts[:, :1]) * (i0 + save_i)))
all_traj_pts.append(traj_pts.astype(np.float32))
all_traj_clrs.append(traj_clrs)
traj_pts, traj_clrs = frame_H_to_points(world_H,
size=1.1)
traj_pts = np.hstack(
(traj_pts,
np.ones_like(traj_pts[:, :1]) * (i0 + save_i)))
all_traj_pts2.append(traj_pts.astype(np.float32))
all_traj_clrs2.append(traj_clrs)
last_saved_frames += save_group
filename = join(out_day_folder, 'frames',
'gt_aligned_{:05d}.ply'.format(i0))
write_ply(filename,
[np.vstack(all_points),
np.hstack(all_labels)],
['x', 'y', 'z', 't', 'category'])
filename = join(out_day_folder, 'trajectory',
'gt_traj_{:05d}.ply'.format(i0))
write_ply(
filename,
[np.vstack(all_traj_pts),
np.vstack(all_traj_clrs)],
['x', 'y', 'z', 't', 'red', 'green', 'blue'])
filename = join(out_day_folder, 'trajectory',
'gt_traj_body_{:05d}.ply'.format(i0))
write_ply(
filename,
[np.vstack(all_traj_pts2),
np.vstack(all_traj_clrs2)],
['x', 'y', 'z', 't', 'red', 'green', 'blue'])
#################
# Post processing
#################
filename = join(out_day_folder, 'gt_map_{:s}.ply'.format(day))
write_ply(filename, [
pointmap.points, pointmap.normals, pointmap.scores,
pointmap.counts
], ['x', 'y', 'z', 'nx', 'ny', 'nz', 'scores', 'counts'])
all_points = []
all_labels = []
all_traj_pts = []
all_traj_clrs = []
i0 = last_saved_frames
for save_i, save_f_t in enumerate(frame_times[i0:]):
# Load points
points, labels = self.load_frame_points_labels(
frame_names[i0 + save_i])
# Find closest gt poses
gt_i1 = np.argmin(np.abs(gt_t - save_f_t))
if save_f_t < gt_t[gt_i1]:
gt_i0 = gt_i1 - 1
else:
gt_i0 = gt_i1
gt_i1 = gt_i0 + 1
if gt_i1 >= len(gt_t):
break
# Interpolate the ground truth pose at current time
interp_t = (save_f_t - gt_t[gt_i0]) / \
(gt_t[gt_i1] - gt_t[gt_i0])
world_H = interp_pose(interp_t, gt_H[gt_i0], gt_H[gt_i1])
# Transformation of the lidar (gt is in body frame)
H_velo_world = np.matmul(world_H, self.H_velo_base)
# Apply transf
world_pts = np.hstack((points, np.ones_like(points[:, :1])))
world_pts = np.matmul(world_pts,
H_velo_world.T).astype(np.float32)
# Save frame
world_pts[:, 3] = i0 + save_i
all_points.append(world_pts)
all_labels.append(labels)
# also save trajectory
traj_pts, traj_clrs = frame_H_to_points(H_velo_world, size=0.1)
traj_pts = np.hstack(
(traj_pts, np.ones_like(traj_pts[:, :1]) * (i0 + save_i)))
all_traj_pts.append(traj_pts.astype(np.float32))
all_traj_clrs.append(traj_clrs)
last_saved_frames += save_group
filename = join(out_day_folder, 'frames',
'gt_aligned_{:05d}.ply'.format(i0))
write_ply(filename, [np.vstack(all_points),
np.hstack(all_labels)],
['x', 'y', 'z', 't', 'category'])
filename = join(out_day_folder, 'trajectory',
'gt_traj_{:05d}.ply'.format(i0))
write_ply(filename,
[np.vstack(all_traj_pts),
np.vstack(all_traj_clrs)],
['x', 'y', 'z', 't', 'red', 'green', 'blue'])
# Save full trajectory
all_traj_pts = []
all_traj_clrs = []
for save_i, save_H in enumerate(transform_list):
# Save trajectory
traj_pts, traj_clrs = frame_H_to_points(save_H, size=0.1)
traj_pts = np.hstack(
(traj_pts, np.ones_like(traj_pts[:, :1]) * save_i))
all_traj_pts.append(traj_pts.astype(np.float32))
all_traj_clrs.append(traj_clrs)
filename = join(out_day_folder, 'gt_traj_{:s}.ply'.format(day))
write_ply(filename,
[np.vstack(all_traj_pts),
np.vstack(all_traj_clrs)],
['x', 'y', 'z', 't', 'red', 'green', 'blue'])
# Save alignments
with open(gt_slam_file, 'wb') as file:
pickle.dump((frame_names[:len(transform_list)], transform_list,
1, pointmap), file)
def loc_mapping(self, map_voxel_size=0.03, save_group=50, verbose=1):
#################
# Init parameters
#################
# Out files
out_folder = join(self.data_path, 'slam_online')
if not exists(out_folder):
makedirs(out_folder)
##########################
# Start first pass of SLAM
##########################
for d, day in enumerate(self.days):
out_day_folder = join(out_folder, day)
if not exists(out_day_folder):
makedirs(out_day_folder)
for folder_name in ['trajectory', 'map', 'frames']:
if not exists(join(out_day_folder, folder_name)):
makedirs(join(out_day_folder, folder_name))
online_slam_file = join(out_day_folder,
'loc_map_{:s}.pkl'.format(day))
if exists(online_slam_file):
continue
# List of frames for this day
frame_names = self.day_f_names[d]
frame_times = self.day_f_times[d]
# List of groundtruth timestamps and poses
loc_t = self.loc_t[d]
loc_H = self.loc_H[d]
# Initiate map
transform_list = []
pointmap = PointMap(dl=map_voxel_size)
last_saved_frames = 0
FPS = 0
N = len(frame_names)
# Test mapping
for i, f_t in enumerate(frame_times):
t = [time.time()]
# Load ply format points
points = self.load_frame_points(frame_names[i])
t += [time.time()]
# Get normals (dummy r_scale to avoid removing points as simulation scans are perfect)
normals, planarity, linearity = polar_normals(points,
radius=1.5,
lidar_n_lines=31,
h_scale=0.5,
r_scale=1000.0)
norm_scores = planarity + linearity
# Remove outliers
points = points[norm_scores > 0.1]
normals = normals[norm_scores > 0.1]
norm_scores = norm_scores[norm_scores > 0.1]
# Filter out points according to main normal directions (Not necessary if normals are better computed)
# norm_scores *= normal_filtering(normals)
# Find closest loc poses
loc_i1 = np.argmin(np.abs(loc_t - f_t))
if f_t < loc_t[loc_i1]:
loc_i0 = loc_i1 - 1
else:
loc_i0 = loc_i1
loc_i1 = loc_i0 + 1
if loc_i1 >= len(loc_t):
break
# Interpolate the ground truth pose at current time
interp_t = (f_t - loc_t[loc_i0]) / \
(loc_t[loc_i1] - loc_t[loc_i0])
frame_H = interp_pose(interp_t, loc_H[loc_i0], loc_H[loc_i1])
# Transformation of the lidar (loc is in body frame)
H_velo_world = np.matmul(frame_H, self.H_velo_base)
transform_list.append(H_velo_world)
# Apply transf
world_points = np.hstack((points, np.ones_like(points[:, :1])))
world_points = np.matmul(world_points, H_velo_world.T).astype(
np.float32)[:, :3]
world_normals = np.matmul(
normals, H_velo_world[:3, :3].T).astype(np.float32)
t += [time.time()]
# Update map
pointmap.update(world_points, world_normals, norm_scores)
if i % save_group == 0:
filename = join(out_day_folder, 'map',
'loc_map_{:03d}.ply'.format(i))
write_ply(filename, [
pointmap.points, pointmap.normals, pointmap.scores,
pointmap.counts
], ['x', 'y', 'z', 'nx', 'ny', 'nz', 'scores', 'counts'])
t += [time.time()]
if verbose == 2:
ti = 0
print('Load ............ {:7.1f}ms'.format(
1000 * (t[ti + 1] - t[ti])))
ti += 1
print('Preprocessing ... {:7.1f}ms'.format(
1000 * (t[ti + 1] - t[ti])))
ti += 1
print('Align ........... {:7.1f}ms'.format(
1000 * (t[ti + 1] - t[ti])))
ti += 1
print('Mapping ......... {:7.1f}ms'.format(
1000 * (t[ti + 1] - t[ti])))
if verbose > 0:
fmt_str = 'GT Mapping {:3d} --- {:5.1f}% or {:02d}:{:02d}:{:02d} remaining at {:.1f}fps'
if i == 0:
FPS = 1 / (t[-1] - t[0])
else:
FPS += (1 / (t[-1] - t[0]) - FPS) / 10
remaining = int((N - (i + 1)) / FPS)
hours = remaining // 3600
remaining = remaining - 3600 * hours
minutes = remaining // 60
seconds = remaining - 60 * minutes
print(
fmt_str.format(i, 100 * (i + 1) / N, hours, minutes,
seconds, FPS))
# Save groups of 100 frames together
if (i > last_saved_frames + save_group + 1):
all_points = []
all_labels = []
all_traj_pts = []
all_traj_clrs = []
all_traj_pts2 = []
all_traj_clrs2 = []
i0 = last_saved_frames
i1 = i0 + save_group
for save_i, save_f_t in enumerate(frame_times[i0:i1]):
# Load points
points, labels = self.load_frame_points_labels(
frame_names[i0 + save_i])
# Find closest loc poses
loc_i1 = np.argmin(np.abs(loc_t - save_f_t))
if save_f_t < loc_t[loc_i1]:
loc_i0 = loc_i1 - 1
else:
loc_i0 = loc_i1
loc_i1 = loc_i0 + 1
# Interpolate the ground truth pose at current time
interp_t = (save_f_t - loc_t[loc_i0]) / (
loc_t[loc_i1] - loc_t[loc_i0])
world_H = interp_pose(interp_t, loc_H[loc_i0],
loc_H[loc_i1])
# Transformation of the lidar (loc is in body frame)
H_velo_world = np.matmul(world_H, self.H_velo_base)
# Apply transf
world_pts = np.hstack(
(points, np.ones_like(points[:, :1])))
world_pts = np.matmul(
world_pts, H_velo_world.T).astype(np.float32)