This repository has been archived by the owner on Jul 8, 2023. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 90
/
stabilizer.py
2520 lines (1833 loc) · 97.2 KB
/
stabilizer.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 quaternion import quaternion
import numpy as np
from datetime import date
import cv2
import csv
import os
for k, v in os.environ.items():
if k.startswith("QT_") and "cv2" in v:
print("deleting" + os.environ[k])
del os.environ[k]
import platform
from tqdm import tqdm
from freqAnalysis import FreqAnalysis
from calibrate_video import FisheyeCalibrator, StandardCalibrator
from scipy.spatial.transform import Rotation
from gyro_integrator import GyroIntegrator, FrameRotationIntegrator
from adaptive_zoom import AdaptiveZoom
from blackbox_extract import BlackboxExtractor
from GPMF_gyro import Extractor
from matplotlib import pyplot as plt
from matplotlib import colors
from vidgear.gears import WriteGear
from vidgear.gears import helper as vidgearHelper
import gyrolog
import json
import multiprocessing as mp
from _version import __version__
from scipy import signal, interpolate
import time
import insta360_utility as insta360_util
import smoothing_algos
VIDGEAR_LOGGING = False
BLOCKING_PLOTS = True
if platform.system() == "Darwin":
BLOCKING_PLOTS = False
def impute_gyro_data(input_data):
input_data = np.copy(input_data)
# Check for corrupted/out of order timestamps
time_order_check = input_data[:-1,0] > input_data[1:,0]
if np.any(time_order_check):
print("Truncated bad gyro data")
input_data = input_data[0:np.argmax(time_order_check)+1,:]
frame_durations = input_data[1:,0] - input_data[:-1,0]
min_frame_duration = frame_durations.min()
max_frame_duration = np.percentile(frame_durations, 10) * 1.5
average_frame_duration = frame_durations[(frame_durations >= min_frame_duration) & (frame_durations <= max_frame_duration)].mean()
print(f'average_frame_duration: {average_frame_duration}')
max_allowed_frame_duration = average_frame_duration * 2
missing_runs = []
last_ts = input_data[0,0]
for ix, ts in np.ndenumerate(input_data[1:,0]):
if ts - last_ts > max_allowed_frame_duration:
missing_runs.append((ix[0], round((ts - last_ts) / average_frame_duration) - 1))
last_ts = ts
print(f'missing_runs: {missing_runs}')
last_ix = 0
arrays_to_concat = []
if len(missing_runs) > 0:
for start, length in missing_runs:
print(f'Appending {input_data[last_ix, 0]}..={input_data[start, 0]}')
arrays_to_concat.append(input_data[last_ix:start+1,:])
prev_row = input_data[start]
next_row = input_data[start+1]
filled_data = np.linspace(prev_row, next_row, length + 1, endpoint=False)[1:]
print(f'Appending {filled_data[0, 0]}..={filled_data[-1, 0]} (filled)')
arrays_to_concat.append(filled_data)
last_ix = start + 1
print(f'Appending {input_data[last_ix, 0]}..={input_data[-1, 0]}')
arrays_to_concat.append(input_data[last_ix:,:])
return np.concatenate(arrays_to_concat)
class Stabilizer:
def __init__(self, videopath, calibrationfile=None, gyro_path=None, fov_scale = 1.6, gyro_lpf_cutoff = -1, video_rotation = -1, gyroflow_file=None):
### Define all important variables
self.initial_offset = 0
self.rough_sync_search_interval = 10
self.better_sync_search_interval = 0.2
self.gyro_lpf_cutoff = gyro_lpf_cutoff
self.do_video_rotation = False
self.num_frames_skipped = 1
self.use_gyroflow_data_file = False
# General video stuff
self.cap = 0
self.width = 0
self.height = 0
self.fps = 0
self.num_frames = 0
# Camera undistortion stuff
self.undistort = None #FisheyeCalibrator()
self.map1 = None
self.map2 = None
self.map_func_scale = 0.9
self.integrator = None #GyroIntegrator(self.gyro_data,initial_orientation=initial_orientation)
self.new_integrator = None
self.times = None
self.stab_transform = None
self.smoothing_algo = None
self.initial_orientation = Rotation.from_euler('zxy', [0,0,np.pi/2]).as_quat()
self.initial_orientation[[0,1,2,3]] = self.initial_orientation[[3,0,1,2]]
# self.raw_gyro_data = None
self.gyro_data = None # self.bbe.get_gyro_data(cam_angle_degrees=cam_angle_degrees)
self.acc_data = None
# time lapse features
self.hyperlapse_multiplier = 1
self.hyperlapse_num_blended_frames = 1 # must be equal or less than hyperlapse_multiplier
self.hyperlapse_skipped_frames = 0
## Combined from individual classes
# Save info
self.videopath = videopath
self.calibrationfile = calibrationfile
self.gyro_path = gyro_path
# General video stuff
self.undistort_fov_scale = fov_scale
self.cap = cv2.VideoCapture(videopath)
orig_w = int(self.cap.get(cv2.CAP_PROP_FRAME_WIDTH))
orig_h = int(self.cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
self.fps = self.cap.get(cv2.CAP_PROP_FPS)
self.num_frames = int(self.cap.get(cv2.CAP_PROP_FRAME_COUNT))
self.orig_dimension = (orig_w,orig_h) #Dimension of input file
self.undistort = FisheyeCalibrator()
self.video_rotate_code = video_rotation
if type(gyroflow_file) != type(None):
success = self.import_gyroflow_file(gyroflow_file)
if not success:
raise RuntimeError
else:
self.undistort.load_calibration_json(calibrationfile, True)
self.do_video_rotation = self.video_rotate_code != -1
if self.video_rotate_code == cv2.ROTATE_90_CLOCKWISE or self.video_rotate_code == cv2.ROTATE_90_COUNTERCLOCKWISE:
orig_w, orig_h = orig_w, orig_h
self.map1, self.map2 = self.undistort.get_maps(self.undistort_fov_scale,new_img_dim=(orig_w,orig_h))
self.process_dimension = self.undistort.get_stretched_size_from_dimension(self.orig_dimension) # Dimension after any stretch corrections
self.width, self.height = self.process_dimension
# Sync stuff
# No longer used:
self.d1 = 0
self.d2 = 0
# Syncpoints
self.transform_times = []
self.transforms = []
self.sync_inputs = [] # consists of pairs of (frame_start, slice_length)
self.sync_vtimes = []
self.sync_delays = []
self.sync_costs = []
def set_initial_offset(self, initial_offset):
self.initial_offset = initial_offset
def set_rough_search(self, interval = 10):
self.rough_sync_search_interval = interval
def set_gyro_lpf(self, cutoff_frequency = -1):
self.gyro_lpf_cutoff = cutoff_frequency
def set_num_frames_skipped(self, num=1):
self.num_frames_skipped = num
def filter_gyro(self):
# Replaces self.gyrodata and should only be used once
num_data_points = self.gyro_data.shape[0]
gyro_sample_rate = num_data_points / (self.gyro_data[-1,0] - self.gyro_data[0,0])
# Nyquist frequency
if (gyro_sample_rate / 2) <= self.gyro_lpf_cutoff:
self.gyro_lpf_cutoff = gyro_sample_rate / 2 - 1
# Tweak with filter order
sosgyro = signal.butter(1, self.gyro_lpf_cutoff, "lowpass", fs=gyro_sample_rate, output="sos")
self.gyro_data[:,1:4] = signal.sosfiltfilt(sosgyro, self.gyro_data[:,1:4], 0) # Filter along "vertical" time axis
def filter_acc(self):
# rather aggressive filtering is applied here
if type(self.acc_data) != type(None):
acc_cutoff = 1
num_data_points = self.acc_data.shape[0]
acc_sample_rate = num_data_points / (self.acc_data[-1,0] - self.acc_data[0,0])
# Nyquist frequency
if (acc_sample_rate / 2) <= acc_cutoff:
self.gyro_lpf_cutoff = acc_sample_rate / 2 - 1
# First order filters to avoid overshoot
# Get rid of high freq.
sosgyro = signal.butter(1, 40, "lowpass", fs=acc_sample_rate, output="sos")
self.acc_data[:,1:4] = signal.sosfiltfilt(sosgyro, self.acc_data[:,1:4], 0) # Filter along "vertical" time axis
sosacc = signal.butter(1, acc_cutoff, "lowpass", fs=acc_sample_rate, output="sos")
self.acc_data[:,1:4] = signal.sosfiltfilt(sosacc, self.acc_data[:,1:4], 0) # Filter along "vertical" time axis
sosgyro = signal.butter(1, 0.5, "lowpass", fs=acc_sample_rate, output="sos")
self.acc_data[:,1:4] = signal.sosfiltfilt(sosgyro, self.acc_data[:,1:4], 0) # Filter along "vertical" time axis
def set_hyperlapse(self, hyperlapse_multiplier = 1, hyperlapse_num_blended_frames = 1):
# Orig frames:
# |0|1|2|3|4|5|6|7|8|9|10|11|12|13
# mult=4, num_blend=2
# |0+1|4+5|8+9|12+13|
self.hyperlapse_multiplier = hyperlapse_multiplier
self.hyperlapse_num_blended_frames = min(hyperlapse_multiplier, hyperlapse_num_blended_frames) # Ensure no overlapping frames
self.hyperlapse_skipped_frames = self.hyperlapse_multiplier - self.hyperlapse_num_blended_frames
def set_smoothing_algo(self, algo = None):
if not algo:
algo = smoothing_algos.PlainSlerp() # Default
else:
self.smoothing_algo = algo
def update_smoothing(self):
if type(self.new_integrator) != type(None):
self.new_integrator.integrate_all(use_acc=self.smoothing_algo.require_acceleration)
self.new_integrator.set_smoothing_algo(self.smoothing_algo)
self.times, self.stab_transform = self.new_integrator.get_interpolated_stab_transform(start=0,interval = 1/self.fps)
return True
print("Orientations not calculated yet")
return False
def auto_sync_stab(self, sliceframe1 = 10, sliceframe2 = 1000, slicelength = 50, debug_plots = True):
if debug_plots:
FreqAnalysis(self.integrator).sampleFrequencyAnalysis()
if self.use_gyroflow_data_file:
self.update_smoothing()
return
v1 = (sliceframe1 + slicelength/2) / self.fps
v2 = (sliceframe2 + slicelength/2) / self.fps
d1, cost1, times1, transforms1 = self.optical_flow_comparison(sliceframe1, slicelength, debug_plots = debug_plots)
#self.initial_offset = d1
d2, cost2, times2, transforms2 = self.optical_flow_comparison(sliceframe2, slicelength, debug_plots = debug_plots)
self.transform_times = [times1, times2]
self.transforms = [transforms1, transforms2]
self.v1 = v1
self.v2 = v2
self.d1 = d1
self.d2 = d2
print("v1: {}, v2: {}, d1: {}, d2: {}".format(v1, v2, d1, d2))
err_slope = (d2-d1)/(v2-v1)
correction_slope = err_slope + 1
gyro_start = (d1 - err_slope*v1)
interval = 1/(correction_slope * self.fps)
g1 = v1 - d1
g2 = v2 - d2
slope = (v2 - v1) / (g2 - g1)
corrected_times = slope * (self.integrator.get_raw_data("t") - g1) + v1
#print("Start {}".format(gyro_start))
print("Gyro correction slope {}".format(slope))
self.plot_sync(corrected_times, slicelength, show=True)
oldplot = True
if oldplot and debug_plots:
plt.figure()
xplot = plt.subplot(311)
plt.plot(times1, -transforms1[:,0] * self.fps)
plt.plot(times2, -transforms2[:,0] * self.fps)
plt.plot(corrected_times, self.integrator.get_raw_data("x"))
plt.ylabel("omega x [rad/s]")
plt.subplot(312, sharex=xplot)
plt.plot(times1, transforms1[:,1] * self.fps)
plt.plot(times2, transforms2[:,1] * self.fps)
plt.plot(corrected_times, self.integrator.get_raw_data("y"))
plt.ylabel("omega y [rad/s]")
plt.subplot(313, sharex=xplot)
plt.plot(times1, transforms1[:,2] * self.fps)
plt.plot(times2, transforms2[:,2] * self.fps)
plt.plot(corrected_times, self.integrator.get_raw_data("z"))
#plt.plot(self.integrator.get_raw_data("t") + d2, self.integrator.get_raw_data("z"))
plt.xlabel("time [s]")
plt.ylabel("omega z [rad/s]")
plt.show(block=BLOCKING_PLOTS)
# Temp new integrator with corrected time scale
initial_orientation = Rotation.from_euler('zxy', [0,0,np.pi/2]).as_quat()
initial_orientation[[0,1,2,3]] = initial_orientation[[3,0,1,2]]
new_gyro_data = np.copy(self.gyro_data)
# Correct time scale
new_gyro_data[:,0] = slope * (self.integrator.get_raw_data("t") - g1) + v1 # (new_gyro_data[:,0]+gyro_start) *correction_slope
if type(self.acc_data) != type(None):
new_acc_data = np.copy(self.acc_data)
new_acc_data[:,0] = new_gyro_data[:,0]
else:
new_acc_data = None
if not self.smoothing_algo:
self.smoothing_algo = smoothing_algos.PlainSlerp()
self.new_integrator = GyroIntegrator(new_gyro_data,zero_out_time=False, initial_orientation=initial_orientation, acc_data=new_acc_data)
if self.smoothing_algo.require_acceleration and type(new_acc_data) == type(None):
print("No acceleration data available. Horizon reference doesn't work without it.")
self.new_integrator.integrate_all(use_acc=self.smoothing_algo.require_acceleration)
#self.last_smooth = smooth
self.new_integrator.set_smoothing_algo(self.smoothing_algo)
self.times, self.stab_transform = self.new_integrator.get_interpolated_stab_transform(start=0,interval = 1/self.fps)
#self.times, self.stab_transform = self.integrator.get_interpolated_stab_transform(smooth=smooth,start=-gyro_start,interval = interval)
def multi_sync_init(self):
self.transform_times = []
self.transforms = []
self.sync_inputs = [] # consists of pairs of (frame_start, slice_length)
self.sync_vtimes = []
self.sync_delays = []
self.sync_costs = []
def multi_sync_add_slice(self, slice_frame_start, slicelength = 50, debug_plots = True):
v1 = (slice_frame_start + slicelength/2) / self.fps
d1, cost1, times1, transforms1 = self.optical_flow_comparison(slice_frame_start, slicelength, debug_plots = debug_plots)
N = len(self.sync_inputs)
# Find where to insert
idx = 0
if N == 0:
pass
elif slice_frame_start > self.sync_inputs[-1][0]:
idx = N
else:
for i in range(len(self.sync_inputs)):
if self.sync_inputs[i][0] > slice_frame_start:
idx = i
break
self.sync_inputs.insert(idx, (slice_frame_start, slicelength))
self.transform_times.insert(idx, times1)
self.transforms.insert(idx, transforms1)
self.sync_vtimes.insert(idx, v1)
self.sync_delays.insert(idx, d1)
self.sync_costs.insert(idx, cost1)
return cost1
def multi_sync_delete_slice(self, idx):
if len(self.transform_times) > idx:
del self.transform_times[idx]
del self.transforms[idx]
del self.sync_inputs[idx]
del self.sync_vtimes[idx]
del self.sync_delays[idx]
del self.sync_costs[idx]
return True
return False
def multi_sync_change_offset(self, idx, newoffset=0):
if len(self.transform_times) > idx:
self.sync_delays[idx] = newoffset
return True
return False
def multi_sync_compute(self, max_cost = 5, max_fitting_error = 0.02, piecewise_correction = False, debug_plots = True):
assert len(self.transform_times) == len(self.transforms) == len(self.sync_vtimes) == len(self.sync_delays) == len(self.sync_costs)
if piecewise_correction:
print("Not implemented yet")
N = len(self.transform_times)
if N == 0:
# no change
print("No valid syncpoints")
self.new_integrator = GyroIntegrator(self.gyro_data,zero_out_time=False, initial_orientation=self.initial_orientation, acc_data=self.acc_data)
elif N == 1:
new_gyro_data = np.copy(self.gyro_data)
# Shift the time
new_gyro_data[:,0] = self.integrator.get_raw_data("t") + self.sync_delays[0] # (new_gyro_data[:,0]+gyro_start) *correction_slope
if type(self.acc_data) != type(None):
new_acc_data = np.copy(self.acc_data)
new_acc_data[:,0] = new_gyro_data[:,0]
else:
new_acc_data = None
self.new_integrator = GyroIntegrator(new_gyro_data,zero_out_time=False, initial_orientation=self.initial_orientation, acc_data=new_acc_data)
else:
# N is two or above, use the weird non-random RANSAC fitting
times = np.array(self.sync_vtimes)
delays = np.array(self.sync_delays)
sync_costs = np.array(self.sync_costs)
chosen_indices = {}
num_chosen = 0
rsquared_best = 1000
chosen_coefs = None
#max_sync_cost = 6 # > 6 is nogo.
for i in range(N):
for j in range(i, N):
if i != j:
del_i = delays[i]
del_j = delays[j]
t_i = times[i]
t_j = times[j]
slope = (del_j - del_i) / (t_j - t_i)
intersect = del_i - t_i * slope
within_error = []
est_curve = times * slope + intersect
within_error = np.where(np.abs(est_curve - delays) < max_fitting_error)[0]
if within_error.shape[0] >= num_chosen and set(within_error) != chosen_indices:
#print(times[within_error])
fit = np.polyfit(times[within_error], delays[within_error], 1, full=True)
coefs = fit[0]
close_constant = -0.1 < coefs[0] < 0.1
if within_error.shape[0] > 2 and close_constant:
rsquared = fit[1]
if rsquared < rsquared_best:
rsquared_best = rsquared
chosen_coefs = coefs
num_chosen = within_error.shape[0]
chosen_indices = set(within_error)
elif close_constant: # close to linear
chosen_coefs = coefs
num_chosen = within_error.shape[0]
chosen_indices = set(within_error)
if type(chosen_coefs) == type(None):
return False
print(chosen_coefs)
print(chosen_indices)
new_gyro_data = np.copy(self.gyro_data)
new_gyro_data[:,0] = (self.integrator.get_raw_data("t") + chosen_coefs[1])/(1- chosen_coefs[0])
if debug_plots:
est_curve = times * chosen_coefs[0] + chosen_coefs[1]
self.plot_sync(new_gyro_data[:,0], 60, True)
plt.figure()
plt.scatter(times, delays)
plt.plot(times, est_curve)
plt.show(block=BLOCKING_PLOTS)
if type(self.acc_data) != type(None):
new_acc_data = np.copy(self.acc_data)
new_acc_data[:,0] = new_gyro_data[:,0]
else:
new_acc_data = None
self.new_integrator = GyroIntegrator(new_gyro_data,zero_out_time=False, initial_orientation=self.initial_orientation, acc_data=new_acc_data)
if not self.smoothing_algo:
self.smoothing_algo = smoothing_algos.PlainSlerp()
if self.smoothing_algo.require_acceleration and type(new_acc_data) == type(None):
print("No acceleration data available. Horizon reference doesn't work without it.")
self.new_integrator.integrate_all(use_acc=self.smoothing_algo.require_acceleration)
self.new_integrator.set_smoothing_algo(self.smoothing_algo)
self.times, self.stab_transform = self.new_integrator.get_interpolated_stab_transform(start=0,interval = 1/self.fps)
return True
def get_recommended_syncpoints(self, num_frames_analyze, max_points=9):
syncpoints = []
num_frames_offset = int(num_frames_analyze / 2)
end_delay = 3 # seconds buffer zone
end_frames = end_delay * self.fps # buffer zone
num_frames = self.num_frames
vid_length = num_frames / self.fps
inter_delay = 13 # second between syncs
inter_delay_frames = int(inter_delay * self.fps)
min_slices = 4
max_slices = max_points
if vid_length < 4: # only one sync
syncpoints.append([5, max(60, int(num_frames-5-self.fps)) ])
num_syncs = 1
elif vid_length < 10: # two points
first_index = 30
last_index = num_frames - 30 - num_frames_analyze
syncpoints.append([first_index, num_frames_analyze])
syncpoints.append([last_index, num_frames_analyze])
num_syncs = 2
else:
# Analysis starts at first frame, so take this into account
# Add also motion analysis from logs here
first_index = end_frames - num_frames_offset
last_index = num_frames - end_frames - num_frames_offset
num_syncs = max(min(round((last_index - first_index)/inter_delay_frames), max_slices), min_slices)
inter_frames_actual = (last_index - first_index) / num_syncs
for i in range(num_syncs):
syncpoints.append([round(first_index + i * inter_frames_actual), num_frames_analyze])
return syncpoints
def full_auto_sync(self, max_fitting_error = 0.02, max_points=9, debug_plots=True):
if self.use_gyroflow_data_file:
self.update_smoothing()
return
self.multi_sync_init()
max_sync_cost_tot = 10 # > 10 is nogo.
num_frames_analyze = 30
syncpoints = self.get_recommended_syncpoints(num_frames_analyze, max_points = max_points)
# save where to analyze. list of [frameindex, num_analysis_frames]
max_sync_cost = max_sync_cost_tot / 30 * num_frames_analyze
# Analyze these slices
num_syncs = len(syncpoints)
print(f"Analyzing {num_syncs} slices")
for frame_index, n_frames in syncpoints:
self.multi_sync_add_slice(frame_index, n_frames, False)
if self.sync_costs[-1] > max_sync_cost:
print("Removing slice due to large error")
self.multi_sync_delete_slice(-1)
elif np.sum( (np.abs(self.transforms[-1] * self.fps) < 0.05) ) >= (0.95 * self.transforms[-1].size):
print("Removing slice due to lack of movement")
self.multi_sync_delete_slice(-1) # if more than 95% of the slice doesn't have significant movement (<3 deg/s)
success = self.multi_sync_compute(max_fitting_error = max_fitting_error, debug_plots=debug_plots)
if not success:
success = self.multi_sync_compute(max_fitting_error = max_fitting_error * 2, debug_plots=debug_plots) # larger bound
if success:
print("Auto sync complete")
return True
else:
print("Auto sync failed to converge. Sorry about that")
return False
def full_auto_sync_parallel(self, max_fitting_error = 0.02, debug_plots = True):
# TODO: Figure out why this fails
if self.use_gyroflow_data_file:
self.update_smoothing()
return
self.multi_sync_init()
max_sync_cost_tot = 10 # > 10 is nogo.
num_frames_analyze = 30
syncpoints = self.get_recommended_syncpoints(num_frames_analyze)
# save where to analyze. list of [frameindex, num_analysis_frames]
max_sync_cost = max_sync_cost_tot / 30 * num_frames_analyze
# Analyze these slices
num_syncs = len(syncpoints)
print(f"Analyzing {num_syncs} slices in parallel")
# Analyze in parallel
n_proc = num_syncs # max about 10, should be fine
with mp.Pool(processes=n_proc) as pool:
# starts the sub-processes without blocking
# pass the chunk to each worker process
proc_results = [pool.apply_async(self.optical_flow_comparison_parallel,
args=(spoint[0],spoint[1],))
for spoint in syncpoints]
# blocks until all results are fetched
result_chunks = [r.get() for r in proc_results]
print(result_chunks)
def plot_sync(self, corrected_times, slicelength, show=False):
n = len(self.transform_times)
fig, axes = plt.subplots(3, n, sharey=True)
fig.set_size_inches(4 * n, 6)
for j in range(n):
mask = ((corrected_times > self.transform_times[j][0] - .2 * slicelength / self.fps) & (corrected_times < self.transform_times[j][-1] + .2 * slicelength / self.fps))
axes[0][j].set(title=f"Syncpoint {j + 1}")
for i, r in enumerate(['x', 'y', 'z']):
axes[i][j].plot(corrected_times[mask], self.integrator.get_raw_data(r)[mask], alpha=.8)
if r == 'x':
axes[i][j].plot(self.transform_times[j], -self.transforms[j][:, i] * self.fps, alpha=.8)
else:
axes[i][j].plot(self.transform_times[j], self.transforms[j][:, i] * self.fps, alpha=.8)
axes[0][0].set(ylabel="omega x [rad/s]")
axes[1][0].set(ylabel="omega y [rad/s]")
axes[2][0].set(ylabel="omega z [rad/s]")
for i in range(n):
axes[2][i].set(xlabel="time [s]")
plt.tight_layout()
if show:
plt.show(block=BLOCKING_PLOTS)
return fig, axes
def manual_sync_correction(self, d1, d2):
if self.use_gyroflow_data_file:
self.update_smoothing()
return
v1 = self.v1
v2 = self.v2
print("v1: {}, v2: {}, d1: {}, d2: {}".format(v1, v2, d1, d2))
g1 = v1 - d1
g2 = v2 - d2
if g1==g2:
slope = 1
else:
slope = (v2 - v1) / (g2 - g1)
corrected_times = slope * (self.integrator.get_raw_data("t") - g1) + v1
print("Gyro correction slope {}".format(slope))
self.plot_sync(corrected_times, slicelength=50, show=True)
# Temp new integrator with corrected time scale
initial_orientation = Rotation.from_euler('zxy', [0,0,np.pi/2]).as_quat()
initial_orientation[[0,1,2,3]] = initial_orientation[[3,0,1,2]]
new_gyro_data = np.copy(self.gyro_data)
# Correct time scale
new_gyro_data[:,0] = slope * (self.integrator.get_raw_data("t") - g1) + v1 # (new_gyro_data[:,0]+gyro_start) *correction_slope
if type(self.acc_data) != type(None):
new_acc_data = np.copy(self.acc_data)
new_acc_data[:,0] = new_gyro_data[:,0]
else:
new_acc_data = None
if not self.smoothing_algo:
self.smoothing_algo = smoothing_algos.PlainSlerp()
self.new_integrator = GyroIntegrator(new_gyro_data,zero_out_time=False, initial_orientation=initial_orientation,acc_data=new_acc_data)
self.new_integrator.integrate_all(use_acc=self.smoothing_algo.require_acceleration)
#self.last_smooth = smooth
self.new_integrator.set_smoothing_algo(self.smoothing_algo)
self.times, self.stab_transform = self.new_integrator.get_interpolated_stab_transform(start=0,interval = 1/self.fps)
def optical_flow_comparison(self, start_frame=0, analyze_length = 50, debug_plots = True):
frame_times = []
frame_idx = []
transforms = []
prev_pts_lst = []
curr_pts_lst = []
self.cap.set(cv2.CAP_PROP_POS_FRAMES, start_frame)
time.sleep(0.05)
# Read first frame
_, prev = self.cap.read()
if self.do_video_rotation:
prev = cv2.rotate(prev, self.video_rotate_code)
prev_gray = cv2.cvtColor(prev, cv2.COLOR_BGR2GRAY)
if self.undistort.image_is_stretched():
prev_gray = cv2.resize(prev_gray, self.process_dimension)
for i in tqdm(range(analyze_length), desc="Analyzing frame", colour="blue"):
prev_pts = cv2.goodFeaturesToTrack(prev_gray, maxCorners=200, qualityLevel=0.01, minDistance=30, blockSize=3)
succ, curr = self.cap.read()
if self.do_video_rotation:
curr = cv2.rotate(curr, self.video_rotate_code)
frame_id = (int(self.cap.get(cv2.CAP_PROP_POS_FRAMES)))
frame_time = (self.cap.get(cv2.CAP_PROP_POS_MSEC)/1000)
#if i % 10 == 0:
# print("Analyzing frame: {}/{}".format(i,analyze_length))
if succ and i % self.num_frames_skipped == 0:
# Only add if succeeded
frame_idx.append(frame_id)
frame_times.append(frame_time)
curr_gray = cv2.cvtColor(curr, cv2.COLOR_BGR2GRAY)
if self.undistort.image_is_stretched():
curr_gray = cv2.resize(curr_gray, self.process_dimension)
# Estimate transform using optical flow
curr_pts, status, err = cv2.calcOpticalFlowPyrLK(prev_gray, curr_gray, prev_pts, None)
idx = np.where(status==1)[0]
prev_pts = prev_pts[idx]
curr_pts = curr_pts[idx]
assert prev_pts.shape == curr_pts.shape
prev_pts_lst.append(prev_pts)
curr_pts_lst.append(curr_pts)
# TODO: Try getting undistort + homography working for more accurate rotation estimation
src_pts = self.undistort.undistort_points(prev_pts, new_img_dim=(self.width,self.height))
dst_pts = self.undistort.undistort_points(curr_pts, new_img_dim=(self.width,self.height))
filtered_src = []
filtered_dst = []
for i in range(src_pts.shape[0]):
# if both points are within frame
if (0 < src_pts[i,0,0] < self.width) and (0 < dst_pts[i,0,0] < self.width) and (0 < src_pts[i,0,1] < self.height) and (0 < dst_pts[i,0,1] < self.height):
filtered_src.append(src_pts[i,:])
filtered_dst.append(dst_pts[i,:])
# rots contains for solutions for the rotation. Get one with smallest magnitude.
# https://docs.opencv.org/master/da/de9/tutorial_py_epipolar_geometry.html
# https://en.wikipedia.org/wiki/Essential_matrix#Extracting_rotation_and_translation
roteul = None
smallest_mag = 1000
try:
R1, R2, t = self.undistort.recover_pose(np.array(filtered_src), np.array(filtered_dst), new_img_dim=(self.width,self.height))
rot1 = Rotation.from_matrix(R1)
rot2 = Rotation.from_matrix(R2)
if rot1.magnitude() < rot2.magnitude():
roteul = rot1.as_rotvec() #rot1.as_euler("xyz")
else:
roteul = rot2.as_rotvec() # as_euler("xyz")
except:
print("Couldn't recover motion for this frame")
roteul = np.array([0,0,0])
transforms.append(list(roteul/self.num_frames_skipped))
prev_gray = curr_gray
else:
print("Frame {}".format(i))
transforms = np.array(transforms)
estimated_offset, cost = self.estimate_gyro_offset(frame_times, transforms, prev_pts_lst, curr_pts_lst, debug_plots = debug_plots)
return estimated_offset, cost, frame_times, transforms
def optical_flow_comparison_parallel(self, start_frame=0, analyze_length = 50, debug_plots = False):
frame_times = []
frame_idx = []
transforms = []
prev_pts_lst = []
curr_pts_lst = []
cap = cv2.VideoCapture(self.videofile)
cap.set(cv2.CAP_PROP_POS_FRAMES, start_frame)
time.sleep(0.05)
# Read first frame
_, prev = cap.read()
if self.do_video_rotation:
prev = cv2.rotate(prev, self.video_rotate_code)
prev_gray = cv2.cvtColor(prev, cv2.COLOR_BGR2GRAY)
if self.undistort.image_is_stretched():
prev_gray = cv2.resize(prev_gray, self.process_dimension)
for i in range(analyze_length):
prev_pts = cv2.goodFeaturesToTrack(prev_gray, maxCorners=200, qualityLevel=0.01, minDistance=30, blockSize=3)
succ, curr = cap.read()
if self.do_video_rotation:
curr = cv2.rotate(curr, self.video_rotate_code)
frame_id = (int(cap.get(cv2.CAP_PROP_POS_FRAMES)))
frame_time = (cap.get(cv2.CAP_PROP_POS_MSEC)/1000)
#if i % 10 == 0:
# print("Analyzing frame: {}/{}".format(i,analyze_length))
if succ and i % self.num_frames_skipped == 0:
# Only add if succeeded
frame_idx.append(frame_id)
frame_times.append(frame_time)
curr_gray = cv2.cvtColor(curr, cv2.COLOR_BGR2GRAY)
if self.undistort.image_is_stretched():
curr_gray = cv2.resize(curr_gray, self.process_dimension)
# Estimate transform using optical flow
curr_pts, status, err = cv2.calcOpticalFlowPyrLK(prev_gray, curr_gray, prev_pts, None)
idx = np.where(status==1)[0]
prev_pts = prev_pts[idx]
curr_pts = curr_pts[idx]
assert prev_pts.shape == curr_pts.shape
prev_pts_lst.append(prev_pts)
curr_pts_lst.append(curr_pts)
# TODO: Try getting undistort + homography working for more accurate rotation estimation
src_pts = self.undistort.undistort_points(prev_pts, new_img_dim=(self.width,self.height))
dst_pts = self.undistort.undistort_points(curr_pts, new_img_dim=(self.width,self.height))
filtered_src = []
filtered_dst = []
for i in range(src_pts.shape[0]):
# if both points are within frame
if (0 < src_pts[i,0,0] < self.width) and (0 < dst_pts[i,0,0] < self.width) and (0 < src_pts[i,0,1] < self.height) and (0 < dst_pts[i,0,1] < self.height):
filtered_src.append(src_pts[i,:])
filtered_dst.append(dst_pts[i,:])
# rots contains for solutions for the rotation. Get one with smallest magnitude.
# https://docs.opencv.org/master/da/de9/tutorial_py_epipolar_geometry.html
# https://en.wikipedia.org/wiki/Essential_matrix#Extracting_rotation_and_translation
roteul = None
try:
R1, R2, t = self.undistort.recover_pose(np.array(filtered_src), np.array(filtered_dst), new_img_dim=(self.width,self.height))
rot1 = Rotation.from_matrix(R1)
rot2 = Rotation.from_matrix(R2)
if rot1.magnitude() < rot2.magnitude():
roteul = rot1.as_rotvec() #rot1.as_euler("xyz")
else:
roteul = rot2.as_rotvec() # as_euler("xyz")
except:
print("Couldn't recover motion for this frame")
roteul = np.array([0,0,0])
transforms.append(list(roteul/self.num_frames_skipped))
prev_gray = curr_gray
else:
print("Frame {}".format(i))
cap.release()
transforms = np.array(transforms)
estimated_offset, cost = self.estimate_gyro_offset(frame_times, transforms, prev_pts_lst, curr_pts_lst, debug_plots = debug_plots)
return estimated_offset, cost, frame_times, transforms
def estimate_gyro_offset(self, OF_times, OF_transforms, prev_pts_list, curr_pts_list, debug_plots = True):
#print(prev_pts_list)
# Estimate offset between small optical flow slice and gyro data
gyro_times = self.integrator.get_raw_data("t")
gyro_data = self.integrator.get_raw_data("xyz")
#print(gyro_data)
# quick low pass filter
self.frame_lowpass = False
if self.frame_lowpass:
params = [0.3,0.4,0.3] # weights. last frame, current frame, next frame
new_OF_transforms = np.copy(OF_transforms)
for i in range(1,new_OF_transforms.shape[0]-1):
new_OF_transforms[i,:] = new_OF_transforms[i-1,:] * params[0] + new_OF_transforms[i,:]*params[1] + new_OF_transforms[i+1,:] * params[2]
OF_transforms = new_OF_transforms
costs = []
offsets = []
dt = self.rough_sync_search_interval # Search +/- 3 seconds
N = int(dt * 100) # 1/100 of a second in rough sync
#dt = self.better_sync_search_interval
#N = int(dt * 5000)
for i in range(N):
offset = dt/2 - i * (dt/N) + self.initial_offset
cost = self.fast_gyro_cost_func(OF_times, OF_transforms, gyro_times + offset, gyro_data) #fast_gyro_cost_func(OF_times, OF_transforms, gyro_times + offset, gyro_data)
offsets.append(offset)
costs.append(cost)
slice_length = len(OF_times)
cutting_ratio = 1
new_slice_length = int(slice_length*cutting_ratio)
start_idx = int((slice_length - new_slice_length)/2)
OF_times = OF_times[start_idx:start_idx + new_slice_length]
OF_transforms = OF_transforms[start_idx:start_idx + new_slice_length,:]
rough_offset = offsets[np.argmin(costs)]
print("Estimated offset: {}".format(rough_offset))
if debug_plots:
plt.figure()
plt.plot(offsets, costs)
# plt.show()
costs = []
offsets = []