-
Notifications
You must be signed in to change notification settings - Fork 1
/
calibration.py
executable file
·3576 lines (2765 loc) · 172 KB
/
calibration.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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from person_msgs.msg import Person2DOcclusionList as Person2DList # New bagfiles
#from person_msgs.msg import Person2DList as Person2DList # Old bagfiles
import rospy
import rospkg
import tf2_ros
import message_filters
from std_msgs.msg import ColorRGBA
from sensor_msgs.msg import CameraInfo
from sensor_msgs.msg import Image as ROS_Image
from visualization_msgs.msg import MarkerArray,Marker
from geometry_msgs.msg import TransformStamped,Pose,Point
from keypoint_camera_calibration.msg import Person2DWithID
import gtsam
import quaternion
import numpy as np
import cv2
from cv_bridge import CvBridge
from scipy.spatial.distance import pdist
from scipy.optimize import minimize_scalar
from scipy.spatial.transform import Rotation as R
import matplotlib.pyplot as plt
from matplotlib import colors
from matplotlib import cm as cmx
import os
import sys
import copy
import time
import yaml
import shutil
import datetime
import threading
class calibration:
def __init__(self):
# -- Method Parameters -- #
# Synchronizer
self.sync_min_gap = 0.0 # time in seconds in which incomming frame-sets are discarded after the last accepted frame-set
self.sync_queue = 10 # parametrizes the ROS approximate time synchronizer
self.sync_slop = 10 # parametrizes the ROS approximate time synchronizer
# Filter
self.filter_stamps_skip = False # ignores all _stamps_ constraints
self.filter_stamps_span_max = 0.05 # frame-sets with larger span between the earliest and last detection in seconds are removed entirely
self.filter_stamps_std_max = 0.025 # frame-sets with larger std. of all timestamps in seconds are removed entirely
self.filter_scores_skip = False
self.filter_scores_min = 0.6 # removes joint detections with lower scores/confidence values
self.filter_bbox_minimum_distance = 100 # removes person detections within one camera, where the shortest distance in pixels between their bounding boxes is shorter
# Depth Estimation
self.person_size_min = 1.70 # minimum person height to be expeced during calibration
self.person_size_max = 2.00 # maximum person height to be expeced during calibration
self.person_size_ratio_hips = 0.1526136692 # assumed ratio: hip distance / person height
self.person_size_ratio_shoulders = 0.1752612993 # assumed ratio: shoulder distance / person height
self.person_size_ratio_torso = 0.2924273380 # assumed ratio: torso distance / person height
# Data Association
self.data_association_views_min = 2 # specifies the number of required perspectives on each joint within a person hypothesis
self.data_association_threshold = 1.0 # required distance in meters for assigning a person detection to a person hypothesis
# Hypothesis Selection
self.hyp_sel_random = False # disables the selection algorithm (parameters below) and selects at random instead
self.hyp_sel_spacing = 0.2 # minimum distance that is enforced between all selected hypohese (if possible)
self.hyp_sel_timing = 0.05 # weight for prefering the selection of newer over older hypotheses: 0-> uniform selection ... 1-> linear decay
# Optimization
self.optimization_flag = True # enables/disables optimization
self.optimization_interval = 0.50 # optimization interval in seconds
self.optimization_scope_size = 50 # number of person hypotheses included in one optimization
self.optimization_wait_mult = 2.0 # blocks optimization until the queue contains at least _wait_mult*_scope_size hypotheses
self.optimization_delta = 10.0 # parametrizes the GTSAM dogleg optimizer
# Temporal Smoothing
self.kal_init_translation = 0.025 # initial covariance for all prior factors (std. in meters)
self.kal_init_rotation = 1.0 # initial covariance for all prior factors (std. in degrees)
self.kal_process_translation = self.kal_init_translation * 0.05 # process noise added to the measured covariance (std. in meters)
self.kal_process_rotation = self.kal_init_rotation * 0.05 # process noise added to the measured covariance (std. in degrees)
# Scaling
self.smoothing_enforce_scale = True # enforces the scale of the initial estimate by applying Umeyama's method
# -- Inputs -- #
self.cam_ID_range = np.arange(0,100) # scan all input .yaml input-files for the scpecified range of IDs in the form "cam_ID"
# Intrinsics
self.intrinsics_file = "examples/camera_intrinsics.yaml"
# Initial estimate extrinsics
self.extrinsics_estimate_readfromfile = False
self.extrinsics_estimate_file = "examples/camera_extrinsics_estimate.yaml"
# Reference extrinsics
self.extrinsics_reference_readfromfile = True
self.extrinsics_reference_file = "examples/camera_extrinsics_reference.yaml"
# Generate new initial estimate extrinsics by retracting the reference calibration, which will be written to self.extrinsics_estimate_file
self.extrinsics_estimate_generate = True
self.extrinsics_estimate_generate_noise_translation = 0.25 # std. in meters
self.extrinsics_estimate_generate_noise_translation_matchnoise = True # True-> retraction will match- False-> normal distribution around -self.extrinsics_estimate_generate_noise_translation
self.extrinsics_estimate_generate_noise_rotation = 10.0 # std. in degrees
self.extrinsics_estimate_generate_noise_rotation_matchnoise = True # True-> retraction will match- False-> normal distribution around -self.extrinsics_estimate_generate_noise_rotation
# Properties of the recieved person.msg
self.person_msg_keys_num = 17 # number of included keypoints, specifying the available keypoint IDs in [0 .. person_msg_keys_num-1]
self.person_msg_keys_ids = [] # leave empty to include all contained keypoints, otherwise list the IDs from 0 to person_msg_keys_num - 1 to be used
self.person_msg_keys_hips_shoulders = (5,6,11,12) # IDs for shoulders and hips, which are required during data association
self.person_msg_coords_undistort = True # undistorts keypoint coordinates w.r.t. the distortion coefficients provided in the intrinsics file
self.person_msg_scores_normalize = True # scores between scores_min and scores_max will be normalized to [0,1]. Otheriwse scores will be clipped between 0 and 1
self.person_msg_scores_min = 0.0 # scores are expected to be larger or equal before normalization. This adaptively changes when finding smaller scores
self.person_msg_scores_max = 1.0 # scores are expected to be smaller or equal before normalization. This adaptively changes when finding larger scores
self.person_msg_persons_max = 10 # all detections within a camera with more person detections are rejected
# -- Outputs -- #
# Topics #
self.publish_3D_flag = True # master control for all other publish_3D flags
self.publish_3D_interval = 0.1 # refresh interval in seconds
self.publish_3D_landmarks_triangulation = True # publishes MarkerArrays for the skeletons of all person hypotheses included in the latest optimization before optimization
self.publish_3D_landmarks_optimization = True # publishes MarkerArrays for the skeletons of all person hypotheses included in the latest optimization after optimization
self.publish_3D_depth_estimation = True # publishes MarkerArrays for the line-segments computed during depth estimation
self.publish_3D_marker_topic = '/keypoint_projections'
self.publish_3D_camera_poses_result = True # publishes the resulting/current set of camera poses
self.publish_3D_camera_poses_reference = True # publishes the reference set of camera poses
self.publish_3D_camera_poses_initialization = True # publishes the initial set of camera poses before calibration
self.publish_3D_camera_poses_result_label = ""
self.publish_3D_camera_poses_initialization_label = "_ini"
self.publish_3D_camera_poses_reference = "_ref"
self.publish_3D_camera_poses_base_to_cam0 = [-3.44546785, 0.73389514, 2.61657272, 0.79924155, 0.37410778, 0.19631249, 0.42745495] # transformation from some base to cam_0
self.publish_3D_base_to_map = [13.57584285736084, 13.884191513061523, 0.0, 0.0, 0.0, 0.999999972294683, -0.0002353946332988968] # transformation from some base to the map
self.publish_3D_base_name = "base" # name of the base frame
self.publish_3D_map_name = "/map" # name of the map frame
self.publish_2D = False # visualizes the received frame-sets and filtering constraints (only use for debugging, this drastically reduces throughput)
self.publish_2D_interval = 1.0 # refresh interval in seconds
self.publish_2D_topic = '/filter_and_data_association'
# Files #
self.log_dir = "logs/"+str(datetime.datetime.now())[2:-7] # location relative to the package path for storing files specified below
self.log_extrinsics_result_flag = True # saves the resulting calibration
self.log_extrinsics_result_file = "extrinsics_result.yaml"
self.log_history_flag = True # logs all intermediate camera poses into a file
self.log_history_file = "extrinsics_history.yaml"
self.log_extrinsics_reference_file = True # copies reference file into the log folder
self.log_extrinsics_estimate_file = True # copies estimate file into the log folder
self.log_intrinsics_file = True # copies intirnsics file into the log folder
self.log_terminal_flag = True # writes the entire terminal output into a file
self.log_terminal_file = "log.txt"
# -- Program Behavior -- #
# Terminal #
self.print_calibration = False # prints all intrinsic and extrinsic camera parameters before and after optimization
self.print_error = True # prints errors towards reference calibration before and after optimization
self.print_error_delta = True # prints the difference in error after optimization
self.print_verbose = False # various notifications and warnings
self.print_status = True # prints real-time status in the last row
self.print_status_interval = 0.1 # update interval in seconds
# Exit #
self.autoexit_duration = 250.0 # automatically ends calibration after the specified time in seconds. Set 0.0 to deactive
##############
self.startup()
def startup(self):
print()
self.check_parameters()
np.random.seed(2)
np.set_printoptions(suppress=True)
# Data structures / Variables
self.path = rospkg.RosPack().get_path('keypoint_camera_calibration')
self.first_msg_received = False # blocks optimization, termination, status_prints, etc, until first frame is recieved
self.processing = False # blocks shutdown while inside joints_callback or graph_callback
self.shutdown = False # blocks all callbacks once shutdown is initiated
# Read files
ids = []
if self.extrinsics_reference_readfromfile:
self.file_reader_extrinsics_reference()
ids.append(self.found_IDs_reference)
if self.extrinsics_estimate_readfromfile:
self.file_reader_extrinsics_estimate()
ids.append(self.found_IDs_estimate)
else:
self.file_writer_extrinsics_estimate(self.extrinsics_estimate_generate_noise_translation, self.extrinsics_estimate_generate_noise_rotation)
self.file_reader_intrinsics()
ids.append(self.found_IDs_intrinsics)
for i in range(len(ids)-1):
if ids[i] != ids[i+1]:
print("Files do not match!")
os._exit(1)
self.cams = ids[0]
self.cams_num = len(self.cams)
assert self.cams_num > 1 , "A minimum of 2 cameras is required for calibration!"
# Publisher
if self.publish_3D_depth_estimation:
self.publisher_3D_depth_estimation_prepare()
if self.publish_3D_landmarks_triangulation or self.publish_3D_landmarks_optimization or self.publish_3D_depth_estimation:
if self.publish_3D_landmarks_triangulation or self.publish_3D_landmarks_optimization:
self.publisher_3D_landmarks_prepare()
self.marker_array_pub = rospy.Publisher(self.publish_3D_marker_topic,MarkerArray,queue_size=10)
if self.publish_3D_flag and (self.publish_3D_camera_poses_result or self.publish_3D_camera_poses_reference or self.publish_3D_camera_poses_initialization):
self.tf_broadcaster = tf2_ros.TransformBroadcaster()
self.publisher_3D_update = None
rospy.Timer(rospy.Duration(self.publish_3D_interval), self.publisher_3D_callback)
if self.publish_2D:
self.publisher_2D_prepare()
self.img_pub = rospy.Publisher(self.publish_2D_topic, ROS_Image, queue_size=1)
# Subscriber
self.subs_joints = []
for i in range(self.cams_num):
self.subs_joints.append(message_filters.Subscriber(self.extrinsics_estimate[i]["topic"], Person2DList, queue_size=1))
self.ts = message_filters.ApproximateTimeSynchronizer(self.subs_joints, queue_size=self.sync_queue, slop=self.sync_slop)
self.ts.registerCallback(self.joints_callback)
# Prepare and start optimization
self.graph_initialize()
if self.print_status:
self.status_length_max = 0
rospy.Timer(rospy.Duration(self.print_status_interval), self.printer_status)
self.print("\nWaiting for incoming detections...",stamp=True,flush=True)
if self.optimization_flag:
rospy.Timer(rospy.Duration(self.optimization_interval), self.graph_callback)
def check_parameters(self):
assert self.sync_min_gap >= 0.0
assert self.filter_stamps_skip or (not self.filter_stamps_skip and self.filter_stamps_span_max >= 0.0)
assert self.filter_stamps_skip or (not self.filter_stamps_skip and self.filter_stamps_std_max >= 0.0)
assert self.filter_stamps_skip or (not self.filter_stamps_skip and self.filter_scores_min >= 0.0)
assert self.filter_stamps_skip or (not self.filter_stamps_skip and self.filter_bbox_minimum_distance >= 0)
assert self.person_size_min > 0.0
assert self.person_size_max >= self.person_size_min
assert self.person_size_ratio_hips >= 0.0
assert self.person_size_ratio_shoulders >= 0.0
assert self.person_size_ratio_torso >= 0.0
assert self.data_association_views_min >= 2 , "Cannot triangulate from less than 2 perspectives on a single joint!"
assert self.data_association_threshold >= 0.0
assert self.hyp_sel_random or (not self.hyp_sel_random and self.hyp_sel_spacing >= 0.0)
assert self.hyp_sel_random or (not self.hyp_sel_random and self.hyp_sel_timing >= 0.0 and self.hyp_sel_timing <= 1.0)
assert self.optimization_interval >= 0.0
assert self.optimization_scope_size > 0
assert self.optimization_wait_mult >= 1.0
assert self.optimization_delta > 0.0
assert self.kal_init_translation >= 0.0
assert self.kal_init_rotation >= 0.0
assert self.kal_process_translation >= 0.0
assert self.kal_process_rotation >= 0.0
assert self.person_msg_keys_num > 0
assert len(self.person_msg_keys_hips_shoulders) == 4
if len(self.person_msg_keys_ids) == 0:
self.person_msg_keys_ids = np.arange(self.person_msg_keys_num,dtype=np.uint8)
self.person_msg_keys_ids = np.sort(np.unique(np.append(self.person_msg_keys_ids,self.person_msg_keys_hips_shoulders).astype(np.uint8)))
assert np.min(self.person_msg_keys_ids) >= 0 and np.max(self.person_msg_keys_ids) < self.person_msg_keys_num , "Specified keypoint IDs must be in [0.."+str(self.person_msg_keys_num)+"]"
assert self.person_msg_scores_min <= self.person_msg_scores_max
assert self.person_msg_persons_max > 0
assert len(self.person_msg_keys_hips_shoulders) == 4
assert self.intrinsics_file != ""
assert not self.extrinsics_estimate_readfromfile or (self.extrinsics_estimate_readfromfile and self.extrinsics_estimate_file != "")
assert not self.extrinsics_reference_readfromfile or (self.extrinsics_reference_readfromfile and self.extrinsics_reference_file != "")
assert self.extrinsics_estimate_readfromfile or self.extrinsics_reference_readfromfile , "Choose at least one!"
assert (not self.extrinsics_estimate_readfromfile and self.extrinsics_estimate_generate) or (self.extrinsics_estimate_readfromfile and not self.extrinsics_estimate_generate)
assert not self.extrinsics_estimate_generate or (self.extrinsics_estimate_generate and self.extrinsics_reference_readfromfile)
assert not self.extrinsics_estimate_generate or (self.extrinsics_estimate_generate and self.extrinsics_estimate_generate_noise_translation >= 0.0)
assert not self.extrinsics_estimate_generate or (self.extrinsics_estimate_generate and self.extrinsics_estimate_generate_noise_rotation >= 0.0)
assert len(self.publish_3D_camera_poses_base_to_cam0) == 7
assert np.isclose(np.linalg.norm(self.publish_3D_camera_poses_base_to_cam0[3:]), 1.0) , "Rotation component should be a unit quternion"
assert len(self.publish_3D_base_to_map) == 7
assert np.isclose(np.linalg.norm(self.publish_3D_base_to_map[3:]),1.0) , "Rotation component should be a unit quternion"
assert not self.publish_2D or (self.publish_2D and self.publish_2D_interval >= 0.0)
assert not self.log_extrinsics_result_flag or (self.log_extrinsics_result_flag and self.log_extrinsics_result_file != "")
assert not self.log_history_flag or (self.log_history_flag and self.log_history_file != "")
assert not self.log_terminal_flag or (self.log_terminal_flag and self.log_terminal_file != "")
assert not self.log_extrinsics_reference_file or (self.log_extrinsics_reference_file and self.extrinsics_reference_readfromfile)
assert not self.print_status or (self.print_status and self.print_status_interval >= 0.0)
assert self.autoexit_duration >= 0.0
# Graph
def graph_initialize(self):
self.print("Initializing graph...",stamp=True,flush=True)
# Data structures & variables
self.extrinsics_history = []
self.next_landmark_id = 0
self.frame_success = []
self.cams_constrained = []
self.covariance_measurements = []
self.covariance_predictions = []
prediction_row = []
for c in range(self.cams_num):
prediction_row.append(np.eye(6))
self.covariance_predictions.append(prediction_row)
self.means_measurements = []
self.means_predictions = []
prediction_row = []
for c in range(self.cams_num):
prediction_row.append(np.concatenate((R.from_quat(self.extrinsics_estimate[c]["rotation"]).as_euler("xyz",degrees=False),self.extrinsics_estimate[c]["translation"])))
self.means_predictions.append(prediction_row)
self.noise = []
# initialize noise
noise_row = []
noise_zero = np.zeros(shape=(6,6))
noise_row.append(noise_zero)
noise_default = np.zeros(shape=(6,6))
noise_default[range(0,3), range(0,3)] = np.deg2rad(self.kal_init_rotation) ** 2
noise_default[range(3,6), range(3,6)] = self.kal_init_translation ** 2
for i in range(1,self.cams_num):
noise_row.append(noise_default)
self.noise.append(noise_row)
self.uncertainty_process = np.zeros((6,6)) # process noise
self.uncertainty_process[range(0,3), range(0,3)] = np.deg2rad(self.kal_process_rotation) ** 2
self.uncertainty_process[range(3,6), range(3,6)] = self.kal_process_translation ** 2
self.frame_detections = []
self.projections = []
self.landmarks_projected = []
self.landmark_history = []
self.times_optimization = []
self.analyzed_frames = []
self.cam_counters = np.zeros(self.cams_num,dtype=int)
self.cam_counters_history = []
self.graph_compute_initposes()
self.L = gtsam.symbol_shorthand.L
self.X = gtsam.symbol_shorthand.X
self.graph = gtsam.NonlinearFactorGraph()
self.estimate = gtsam.Values()
self.graph_estimate_cameras()
self.extrinsics_update(self.estimate)
self.print("done!")
if self.print_calibration:
self.printer_extrinsics_raw()
if self.print_error and self.extrinsics_reference_readfromfile:
self.printer_extrinsics_error()
def graph_compute_initposes(self):
self.graph_init_poses = [gtsam.Pose3()]
for i in range(1,self.cams_num):
rotation = gtsam.Rot3(R.from_quat(self.extrinsics_estimate[i]["rotation"]).as_matrix())
pose = gtsam.Pose3(rotation,self.extrinsics_estimate[i]["translation"])
self.graph_init_poses.append(pose)
def graph_add_factors_cameras(self):
#Fix cam_0 to zero-pose
factor = gtsam.NonlinearEqualityPose3(self.X(0), gtsam.Pose3())
self.graph.push_back(factor)
# Add prior factors to graph
for i in range(1,self.cams_num):
noise = gtsam.noiseModel.Gaussian.Covariance(self.noise[-1][i])
rotation = gtsam.Rot3(R.from_euler("xyz",self.means_predictions[-1][i][0:3],degrees=False).as_matrix())
pose = gtsam.Pose3(rotation,self.means_predictions[-1][i][3:6])
factor = gtsam.PriorFactorPose3(self.X(i), pose, noise)
self.graph.push_back(factor)
def graph_add_factors_projections(self):
cams_constrained = []
cam_counters = np.zeros(self.cams_num,dtype=int)
start = 0
if len(self.projections) > self.optimization_scope_size:
start = len(self.projections) - self.optimization_scope_size
for n in range(start,len(self.projections)):
for i in range(0,len(self.projections[n])):
if self.projections[n][i][3] in self.landmarks_projected[n-start]["landmark_ids"]:
factor = gtsam.GenericProjectionFactorCal3_S2(
self.projections[n][i][0], self.projections[n][i][1], self.X(self.projections[n][i][2]), self.L(self.projections[n][i][3]), self.intrinsics_cal3s2[self.projections[n][i][2]])
self.graph.push_back(factor)
cam_counters[self.projections[n][i][2]] += 1
cams_constrained.append(self.projections[n][i][2])
cams_constrained = np.unique(np.asarray(cams_constrained))
self.cams_constrained.append(cams_constrained)
self.cam_counters_history.append(cam_counters)
self.cam_counters += cam_counters
def graph_add_factors_landmarks(self):
return
def graph_estimate_cameras(self):
for i in range(self.cams_num):
if len(self.frame_success) == 0:
pose = self.graph_init_poses[i]
else:
rotation = gtsam.Rot3(R.from_euler("xyz",self.means_predictions[-1][i][0:3],degrees=False).as_matrix())
pose = gtsam.Pose3(rotation,self.means_predictions[-1][i][3:6])
self.estimate.insert(self.X(i), pose)
def graph_estimate_landmarks(self):
landmarks = self.landmarks_projected
start = 0
if len(self.projections) > self.optimization_scope_size:
start = len(self.projections)-self.optimization_scope_size
for n in range(start,len(self.projections)):
for p in range(0,len(self.frame_detections[n])):
for k in range(0,len(self.frame_detections[n][p])):
if self.frame_detections[n][p][k][1] in landmarks[n-start]["landmark_ids"]:
self.estimate.insert(self.L(self.frame_detections[n][p][k][1]),
gtsam.Point3(landmarks[n-start]["points"][self.frame_detections[n][p][k][0]][0],
landmarks[n-start]["points"][self.frame_detections[n][p][k][0]][1],
landmarks[n-start]["points"][self.frame_detections[n][p][k][0]][2]))
def graph_optimize(self):
params = gtsam.DoglegParams()
params.setDeltaInitial(self.optimization_delta)
#params.setVerbosityDL("VERBOSE")
optimizer = gtsam.DoglegOptimizer(self.graph, self.estimate, params)
timestamp = rospy.get_time()
try:
result = optimizer.optimize()
success = True
except Exception as e:
result = self.estimate
success = False
self.times_optimization.append(rospy.get_time() - timestamp)
self.frame_success.append(success)
if self.frame_success[-1]:
means_row = []
covariance_row = []
try:
i = -1
marginals = gtsam.Marginals(self.graph,result)
for i in range(self.cams_num):
pose = gtsam.Pose3(result.atPose3(self.X(i)).rotation(),result.atPose3(self.X(i)).translation())
position = pose.translation()
orientation = R.from_matrix(pose.rotation().matrix()).as_euler('xyz',degrees=False)
means_row.append(np.concatenate((orientation,position)))
covariance_row.append(marginals.marginalCovariance(self.X(i)))
except Exception as e:
if self.print_verbose:
self.print("\tError during marginalization! - i="+str(i)+" - "+str(e))
self.frame_success[-1] = False
if self.frame_success[-1]:
self.means_measurements.append(means_row)
self.covariance_measurements.append(covariance_row)
return result
def graph_noise_update_kalman(self,result):
if self.frame_success[-1] and np.sum(self.frame_success)>1:
prediction_covariance_row = []
prediction_covariance_row.append(np.eye(6))
prediction_means_row = []
prediction_means_row.append(np.zeros(6))
for c in range(1,self.cams_num):
if c in self.cams_constrained[-1]:
P = self.covariance_predictions[-1][c] + self.uncertainty_process
K = P @ np.linalg.inv( P + self.covariance_measurements[-1][c] )
means_prev = self.means_predictions[-1][c]
diff = self.means_measurements[-1][c] - means_prev
diff[0:3] = np.mod(diff[0:3]+np.pi,2*np.pi)-np.pi
means = means_prev + K @ (diff)
means[0:3] = np.mod(means[0:3]+np.pi,2*np.pi)-np.pi
cov = (np.eye(6) - K) @ P
pose = gtsam.Pose3(gtsam.Rot3(R.from_euler('xyz',means[0:3],degrees=False).as_matrix()),means[3:])
result.update(self.X(c),pose)
else:
cov = self.covariance_predictions[-1][c]
means = self.means_predictions[-1][c]
prediction_covariance_row.append(cov)
prediction_means_row.append(means)
else:
prediction_covariance_row = self.covariance_predictions[-1]
prediction_means_row = self.means_predictions[-1]
self.covariance_predictions.append(prediction_covariance_row)
self.means_predictions.append(prediction_means_row)
return result
def graph_triangulate(self,proj_matricies,points,confidences=None):
n_views = len(proj_matricies)
if confidences is None:
confidences = np.ones(n_views, dtype=float)
A = np.zeros((2 * n_views, 4))
for j in range(len(proj_matricies)):
A[j * 2 + 0] = points[j][0] * proj_matricies[j][2, :] - proj_matricies[j][0, :]
A[j * 2 + 0] = A[j * 2 + 0] / np.linalg.norm(A[j * 2 + 0]) # for numerical stability
A[j * 2 + 0] = A[j * 2 + 0] * confidences[j]
A[j * 2 + 1] = points[j][1] * proj_matricies[j][2, :] - proj_matricies[j][1, :]
A[j * 2 + 1] = A[j * 2 + 1] / np.linalg.norm(A[j * 2 + 1]) # for numerical stability
A[j * 2 + 1] = A[j * 2 + 1] * confidences[j]
u, s, vh = np.linalg.svd(A, full_matrices=False)
point_3d_homo = vh[3, :]
point_3d = (point_3d_homo.T[:-1] / point_3d_homo.T[-1]).T
return point_3d
def graph_compute_landmarks(self):
if len(self.frame_detections) >= self.optimization_scope_size:
l = self.optimization_scope_size
else:
l = len(self.frame_detections)
landmarks_projected = []
projection_matricies = [None] * self.cams_num
for n in range(0,l):
# find corresponding detections that are observed from at least n different cameras
persons = 0
shared_detections = []
for p in range(0,len(self.frame_detections[-l+n])):
for d in range(0,len(self.frame_detections[-l+n][p])):
if len(self.frame_detections[-l+n][p][d][2]) >= self.data_association_views_min:
shared_detections.append((self.frame_detections[-l+n][p][d][2],p,self.frame_detections[-l+n][p][d][0],self.frame_detections[-l+n][p][d][1],self.frame_detections[-l+n][p][d][3]))
if persons <= p: persons += 1
else:
print("This should not happen")
if not len(shared_detections) > 0:
print("No shared detections, shouldnt happen")
# find all cameras that have at least one shared detections
involved_cams = []
for i in range(len(shared_detections)):
for j in range(len(shared_detections[i][0])):
if shared_detections[i][0][j] not in involved_cams:
involved_cams.append(shared_detections[i][0][j])
if len(involved_cams) == self.cams_num:
break
if len(involved_cams) == self.cams_num:
break
# compute necessary 3x4 projection matricies w.r.t. current extrinsics
for i in range(0,len(involved_cams)):
if projection_matricies[involved_cams[i]] is None:
if len(self.extrinsics_history) > 0:
RT_inv = np.column_stack((R.from_euler("xyz",self.means_predictions[-1][involved_cams[i]][0:3],degrees=False).as_matrix(),self.means_predictions[-1][involved_cams[i]][3:6]))
RT_inv = np.row_stack((RT_inv,np.array((0.0,0.0,0.0,1.0))))
RT_inv = np.linalg.inv(RT_inv)
RT_inv = np.delete(RT_inv,3,0)
else:
RT_inv = np.delete(np.linalg.inv(self.graph_init_poses[involved_cams[i]].matrix()),3,0)
P = self.intrinsics_cal3s2[involved_cams[i]].K() @ RT_inv
projection_matricies[involved_cams[i]] = P
# pack all shared_detection projections/points and triangulate corresponding 3D points
point3s = []
for i in range(0,len(shared_detections)):
keypoint = shared_detections[i][2]
proj_matricies = []
point2s = []
confidences = []
for c in range(0,len(shared_detections[i][0])):
# find corresponding projection
projection = None
for j in range(0,len(self.projections[-l+n])):
if self.projections[-l+n][j][2] == shared_detections[i][0][c] and self.projections[-l+n][j][5] == shared_detections[i][1] and self.projections[-l+n][j][4] == shared_detections[i][2]: #cam, person, keypoint
projection = self.projections[-l+n][j]
break
assert projection != None
proj_matricies.append(projection_matricies[shared_detections[i][0][c]])
point2s.append(projection[0])
confidences.append(shared_detections[i][4][c])
proj_matricies = np.array(proj_matricies)
point2s = np.array(point2s)
point3 = self.graph_triangulate(proj_matricies,point2s,confidences)
point3s.append((shared_detections[i][1],shared_detections[i][2],point3,shared_detections[i][3])) # person, keypoint_id, 3D-point, landmark_id
# format for output
stamps = [None] * len(self.person_msg_keys_ids) * persons
points = np.full((len(self.person_msg_keys_ids) * persons,3),np.inf)
landmarks_ids = [None] * len(self.person_msg_keys_ids) * persons
for i in range(len(point3s)):
stamps[point3s[i][1]*(point3s[i][0]+1)] = rospy.Time.now()
points[point3s[i][1]*(point3s[i][0]+1)] = point3s[i][2]
landmarks_ids[point3s[i][1]*(point3s[i][0]+1)] = point3s[i][3]
result = {"timestamps":stamps, "persons":persons, "points":points, "landmark_ids":landmarks_ids}
landmarks_projected.append(result)
self.landmarks_projected = landmarks_projected
def graph_select_hypotheses(self):
# Select a set of frames
if self.hyp_sel_random:
return np.random.choice(len(self.queue_hyps), self.optimization_scope_size, replace = False)
else:
filter_queue_len = len(self.queue_hyps)
p_linear = np.arange(1,filter_queue_len+1,1)
p_linear = p_linear / np.sum(p_linear)
p_uniform = np.full(filter_queue_len,1.0/filter_queue_len)
p = self.hyp_sel_timing * p_linear + (1-self.hyp_sel_timing) * p_uniform
rng = np.random.default_rng()
ranking = rng.choice(filter_queue_len, filter_queue_len, replace = False, p=p)
props = np.asarray(self.queue_props)
d0 = props[:,0] # valid detec
d1 = props[:,1] # center of mass x
d2 = props[:,2] # center of mass y
d3 = props[:,3] # center of mass z
d4 = props[:,4] # mean distance between center of mass and camera poses
zeta = np.stack((d1,d2,d3),axis=1)
selection = [ranking[0]]
i = 1
while len(selection) < self.optimization_scope_size and i < filter_queue_len:
tooclose = False
for j in range(len(selection)):
if np.linalg.norm(zeta[ranking[i]]-zeta[selection[j]]) < self.hyp_sel_spacing:
tooclose = True
break
if not tooclose:
selection.append(ranking[i])
i += 1
i = 1
while len(selection) < self.optimization_scope_size:
if i == 1 and self.print_verbose:
self.print("\tSpacing constraint violated during hypothesis selection after having selected "+str(len(selection))+"/"+str(self.optimization_scope_size)+" hypotheses.")
if not ranking[i] in selection:
selection.append(ranking[i])
i += 1
selection = np.asarray(selection)
return selection
def graph_update_hypotheses_properties(self,selection):
self.lock.acquire()
for i in range(len(selection)):
self.queue_props[selection[i]][12] += 1
if not self.frame_success[-1]:
self.queue_props[selection[i]][13] += 1
self.lock.release()
def graph_analyze_hypotheses(self,selection):
# frame_detections: k l_id [c] [scores]
# projections: point noise c landmark_id k_index person_id_pos
# hyp 0 1 2 3 4 5 6 7 8 9
# c k score x y cov cov cov stamp depth
for h in selection:
frame_detections = []
projections = []
frame_detections.append([])
appended_k = []
for i in range(len(self.queue_hyps[h])):
c = int(self.queue_hyps[h][i][0])
k = int(self.queue_hyps[h][i][1])
s = self.queue_hyps[h][i][2]
if k in appended_k:
landmark_id = -1
for m in range(0,len(frame_detections[0])):
if frame_detections[0][m][0] == k:
landmark_id = frame_detections[0][m][1]
else:
all_k = np.where(self.queue_hyps[h][:,1]==self.queue_hyps[h][i][1])[0].astype(int)
cams = self.queue_hyps[h][all_k,0].astype(int)
scores = self.queue_hyps[h][all_k,2]
landmark_id = self.next_landmark_id
frame_detections[0].append([k, landmark_id, cams, scores])
appended_k.append(k)
self.next_landmark_id += 1
noise = gtsam.noiseModel.Gaussian.Covariance([
[self.queue_hyps[h][i][5], self.queue_hyps[h][i][6]],
[self.queue_hyps[h][i][6], self.queue_hyps[h][i][7]]])
point = (self.queue_hyps[h][i][3],self.queue_hyps[h][i][4])
projections.append((point,noise,c,landmark_id,k,0))
assert len(self.frame_detections) == len(self.projections)
self.analyzed_frames.append((h,len(self.frame_detections)))
self.frame_detections.append(frame_detections)
self.projections.append(projections)
# Joints
def joints_check_reference(self):
# Check if intrinsics exist
if len(self.intrinsics_cal3s2) < len(self.msg):
if self.print_verbose:
self.print("\tSkipping image frame! - Waiting for camera intrinsics...")
self.joints_finisher(reason="Waiting for intrinsics")
return False
# Check if reference extrinsics exists
if self.extrinsics_reference_readfromfile and len(self.extrinsics_reference) < len(self.msg):
if self.print_verbose:
self.print("\tSkipping image frame! - Waiting for reference extrinsics...")
self.joints_finisher(reason="Waiting for reference extrinsics")
return False
return True
def joints_filter_detections(self):
# remove cams without- or more than expected detections
self.filterstage = 0
detections = np.zeros(self.cams_num,dtype=np.uint8)
for c in self.cams_used:
detections[c] = len(self.msg[c].persons)
if np.sum(detections) == 0:
self.joints_finisher(reason = "No detections")
return False
cams_no_detections = np.where(detections == 0)[0]
if self.remove_cams(cams_no_detections, reason = "No detections") == -1:
return False
cams_too_many_detections = np.where(np.delete(detections,cams_no_detections) > self.person_msg_persons_max)[0]
if cams_too_many_detections.shape[0] > 0:
if self.print_verbose:
self.print("\tWarning! - Exceeding 'max_number_of_persons_per_cam' in cam "+str(np.take(self.cams,np.take(self.cams_used,cams_too_many_detections)))
+". Should be <="+str(self.person_msg_persons_max)+" but is "+str(np.take(detections,np.take(self.cams_used,cams_too_many_detections)))+". Cam was removed from frame.")
if self.remove_cams(cams_too_many_detections, reason = "Too many detections (>"+str(self.person_msg_persons_max)+")") == -1:
return False
return True
def joints_filter_bbox(self):
self.filterstage = 4
for c in copy.deepcopy(self.cams_used):
removal = True
while removal == True:
removal = False
persons = len(self.msg[c].persons)
i = 0
j = 1
while j < persons:
r1 = self.msg[c].persons[i].bbox
r2 = self.msg[c].persons[j].bbox
d, a1, a2 = self.distance_rec2rec(r1,r2)
if d <= self.filter_bbox_minimum_distance:
if self.remove_person(c,j) == -1:
return False
if self.remove_person(c,i) == -1:
return False
removal = True
j = persons
else:
if j+1 < persons:
j = j+1
else:
i = i+1
j = i+1
return True
def joints_filter_timing(self):
# remove cams with insufficient timing
if self.filter_stamps_skip == False:
self.filterstage = 1
stamps_secs = []
stamps_nsecs = []
for c in self.cams_used:
stamps_secs.append(self.msg[c].header.stamp.secs)
stamps_nsecs.append(self.msg[c].header.stamp.nsecs)
stamps = np.asarray(stamps_secs) * 1000000000 + np.asarray(stamps_nsecs)
if np.amax(stamps) - np.amin(stamps) > self.filter_stamps_span_max:
self.joints_finisher(reason = "filter_stamps_span_max")
return False
stamps_std = np.std(stamps)
if stamps_std > self.filter_stamps_std_max:
self.joints_finisher(reason = "filter_stamps_std_max")
return False
return True
def joints_filter(self):
# remove individual keypoints
self.filterstage = 2
for c in copy.deepcopy(self.cams_used):
p_offset = 0
for p in range(0,len(self.msg[c].persons)):
p = p + p_offset # compensate indexing after persons were removed from list
# remove unused keypoints
for k in self.person_msg_keys_ids_unused:
self.msg[c].persons[p].keypoints[k].score = 0
self.msg[c].persons[p].keypoints[k].x = 0.0
self.msg[c].persons[p].keypoints[k].y = 0.0
self.msg[c].persons[p].keypoints[k].cov = (0.0,0.0,0.0)
# read data
data = np.asarray([np.array([self.msg[c].persons[p].keypoints[k].x, self.msg[c].persons[p].keypoints[k].y, self.msg[c].persons[p].keypoints[k].score]) for k in self.person_msg_keys_ids])
scores = data[:,2]
xs = data[:,0]
ys = data[:,1]
# remove keypoints outside of the image
xs_out_of_image = np.where(np.logical_or(xs < 0, xs >= self.extrinsics_estimate[c]["resolution"][0]))[0]
if xs_out_of_image.shape[0] > 0 and self.print_verbose:
self.print("\tEncoutered detection"+("s" if xs_out_of_image.shape[0] > 1 else " ")
+" with x-coordinate"+("s" if xs_out_of_image.shape[0] > 1 else " ")+" exceeding the image width of "
+str(self.extrinsics_estimate[c]["resolution"][0])+": "+np.array2string(np.take(xs,xs_out_of_image)).replace('\n', '')
+ " ; Detection"+("s are" if xs_out_of_image.shape[0] > 1 else " is")+" rejected!", stamp=True)
ys_out_of_image = np.where(np.logical_or(ys < 0, ys >= self.extrinsics_estimate[c]["resolution"][1]))[0]
if ys_out_of_image.shape[0] > 0 and self.print_verbose:
self.print("\tEncoutered detection"+("s" if ys_out_of_image.shape[0] > 1 else " ")
+" with y-coordinate"+("s" if ys_out_of_image.shape[0] > 1 else " ")+" exceeding the image height of "
+str(self.extrinsics_estimate[c]["resolution"][1])+": "+np.array2string(np.take(ys,ys_out_of_image)).replace('\n', '')
+ " ; Detection"+("s are" if ys_out_of_image.shape[0] > 1 else " is")+" rejected!", stamp=True)
outliers = np.unique(np.concatenate((xs_out_of_image,ys_out_of_image)))
if np.any(np.isin(outliers,self.filter_scores_musthahaveids_relative,assume_unique=True)):
if self.remove_person(c,p) == -1: # will report in 2D pub as "rejecting while checking scores"
return False
p_offset -= 1
continue
# normalize or clip scores
normalized = False
if self.person_msg_scores_normalize:
value = np.max(scores)
if value > self.person_msg_scores_max:
if self.print_verbose:
self.print("\tEncoutered higher score than expected: "
+self.format_num(value,1,3)+" > "+self.format_num(self.person_msg_scores_max,1,3)
+" ; Scores are normalized accordingly from now on!", stamp=True)
self.person_msg_scores_max = value # old frames will be ranked too high in frame selection
value = np.min(scores)
if value < self.person_msg_scores_min:
if self.print_verbose:
self.print("\tEncoutered smaller score than expected: "
+self.format_num(value,1,3)+" < "+self.format_num(self.person_msg_scores_min,1,3)
+" ; Scores are normalized accordingly from now on!", stamp=True)
self.person_msg_scores_min = value # old frames will be ranked too low in frame selection
if self.person_msg_scores_min != 0.0 or self.person_msg_scores_max != 1.0:
normalized = True
scores = self.person_msg_scores_min + scores / (self.person_msg_scores_max-self.person_msg_scores_min)
for k in range(len(self.msg[c].persons[p].keypoints)):
self.msg[c].persons[p].keypoints[k].score = self.person_msg_scores_min + self.msg[c].persons[p].keypoints[k].score / (self.person_msg_scores_max-self.person_msg_scores_min)
else:
clip = False
value = np.max(scores)
if value > 1.0:
if self.print_verbose:
self.print("\tEncoutered higher score than expected, "
+self.format_num(value,1,3)+" > 1.0"
+" : Scores are clipped at 1.0!", stamp=True)
clip = True
value = np.min(scores)
if value < 0.0:
if self.print_verbose:
self.print("\tEncoutered smaller score than expected, "
+self.format_num(value,1,3)+" < 0.0"
+" : Scores are clipped at 0.0!", stamp=True)
clip = True
if clip:
normalized = True
scores = np.clip(scores,0.0,1.0)
for k in range(len(self.msg[c].persons[p].keypoints)):
self.msg[c].persons[p].keypoints[k].score = np.clip(self.msg[c].persons[p].keypoints[k].score,0.0,1.0)
# remove keypoints with low scores
scores_to_low = np.where(scores < self.filter_scores_min)[0]
outliers = np.unique(np.concatenate((outliers,scores_to_low)))
if np.any(np.isin(outliers,self.filter_scores_musthahaveids_relative,assume_unique=True)):
if self.remove_person(c,p) == -1:
return False
p_offset -= 1
continue
# remove person with high standard deviation
scores_filter_scope = np.delete(scores,outliers)
scores_std = np.std(scores_filter_scope)
# remove all outliers from msg
for k in outliers:
self.msg[c].persons[p].keypoints[k].score = 0
self.msg[c].persons[p].keypoints[k].x = 0.0
self.msg[c].persons[p].keypoints[k].y = 0.0
self.msg[c].persons[p].keypoints[k].cov = (0.0,0.0,0.0)
# update person info in msg
if normalized or outliers.shape[0] > 0 or self.person_msg_keys_ids_unused.shape[0] > 0:
# average score
scores_mean = np.mean(scores_filter_scope)
self.msg[c].persons[p].score = scores_mean