-
Notifications
You must be signed in to change notification settings - Fork 1
/
camera_calibrate_input_rms_ext.py
4157 lines (3581 loc) · 198 KB
/
camera_calibrate_input_rms_ext.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
# made by yeolip.yoon ([email protected])
# camera_calibrate_input_depth ./square151
# camera_calibrate_input_depth ./cx_cy/ stereo_config_init.json ./input_csv/
# camera_calibrate_input_depth ./\input_lgit_964/ ./\input_lgit_964/stereo_config_result.json ./\input_lgit_964/
# camera_calibrate_input_depth ./\input_lgit/ ./\input_lgit/stereo_config_result_lge.json ./\input_lgit/
# camera_calibrate_input_depth ./\input_lgit/ ./\input_lgit/stereo_config_33_2_1.json ./\input_lgit/
# camera_calibrate_input_depth ./\input_sm/ ./\input_sm/stereo_config2.json ./\input_sm/
# camera_calibrate_input_depth ./\input_sm/ ./\input_sm/stereo_config_result_lge.json ./\input_sm/
# camera_calibrate_input_depth ./dump_pattern ./dump_pattern/stereo_config.json
# camera_calibrate_input_depth ./dump_pattern ./dump_pattern/stereo_config.json
# camera_calibrate_input_depth ./\input_sm_idiada/ ./input_sm_idiada/stereo_config2.json ./input_sm_idiada/
# camera_calibrate_input_depth ./\input_sm_idiada/ ./input_sm_idiada/stereo_config_result_lge.json ./input_sm_idiada/
# camera_calibrate_input_depth ./\input_sm_lip/ ./input_sm_lip/stereo_config.json ./input_sm_lip/
#./data/rmsecal_input/ ./data/rmsecal_input/stereo_config_result_lge.json ./data/rmsecal_input/
# to do
# 1. load, save k3, k4, k5 on left,right - ok
# 2. disparity distance from pattern - ok
# 3. save Essensial and Fundamantal - ok
# 4. distinguish minus focal on intrinsic - ok
# 4. distinguish left to right and right to left on extrinsic - ok
# 5. disparity distance from point - ok
# 6. calc stereo rms - ok
# 7. auto parameter such as one, repeat using point, circle, square
# 8. retification json data with Q
# ../python_rmse/small_cal/3_cover/1/learn/1/ ../python_rmse/small_cal/3_taltail/stereo_config1.json ../python_rmse/small_cal/3_cover/1/learn/1/
# ../python_rmse/small_cal/3_cover/1/learn/3/ ../python_rmse/small_cal/3_taltail/stereo_config1.json ../python_rmse/small_cal/3_cover/1/learn/3/
# ../python_rmse/small_cal/3_cover/1/learn/5/ ../python_rmse/small_cal/3_taltail/stereo_config1.json ../python_rmse/small_cal/3_cover/1/learn/5/
#
# ../python_rmse/small_cal/3_cover/2/learn/1/ ../python_rmse/small_cal/3_taltail/stereo_config2.json ../python_rmse/small_cal/3_cover/2/learn/1/
# ../python_rmse/small_cal/3_cover/2/learn/3/ ../python_rmse/small_cal/3_taltail/stereo_config2.json ../python_rmse/small_cal/3_cover/2/learn/3/
# ../python_rmse/small_cal/3_cover/2/learn/5/ ../python_rmse/small_cal/3_taltail/stereo_config2.json ../python_rmse/small_cal/3_cover/2/learn/5/
#
#
# ../python_rmse/small_cal/3_cover/3/learn/1/ ../python_rmse/small_cal/3_taltail/stereo_config3.json ../python_rmse/small_cal/3_cover/3/learn/1/
# ../python_rmse/small_cal/3_cover/3/learn/3/ ../python_rmse/small_cal/3_taltail/stereo_config3.json ../python_rmse/small_cal/3_cover/3/learn/3/
# ../python_rmse/small_cal/3_cover/3/learn/5/ ../python_rmse/small_cal/3_taltail/stereo_config3.json ../python_rmse/small_cal/3_cover/3/learn/5/
#
#
# ../python_rmse/small_cal/15_cover/1/learn/1/ ../python_rmse/small_cal/15_taltail/stereo_config1.json ../python_rmse/small_cal/15_cover/1/learn/1/
# ../python_rmse/small_cal/15_cover/1/learn/3/ ../python_rmse/small_cal/15_taltail/stereo_config1.json ../python_rmse/small_cal/15_cover/1/learn/3/
# ../python_rmse/small_cal/15_cover/1/learn/5/ ../python_rmse/small_cal/15_taltail/stereo_config1.json ../python_rmse/small_cal/15_cover/1/learn/5/
#
# ../python_rmse/small_cal/15_cover/2/learn/1/ ../python_rmse/small_cal/15_taltail/stereo_config2.json ../python_rmse/small_cal/15_cover/2/learn/1/
# ../python_rmse/small_cal/15_cover/2/learn/3/ ../python_rmse/small_cal/15_taltail/stereo_config2.json ../python_rmse/small_cal/15_cover/2/learn/3/
# ../python_rmse/small_cal/15_cover/2/learn/5/ ../python_rmse/small_cal/15_taltail/stereo_config2.json ../python_rmse/small_cal/15_cover/2/learn/5/
#
# ../python_rmse/small_cal/15_cover/3/learn/1/ ../python_rmse/small_cal/15_taltail/stereo_config3.json ../python_rmse/small_cal/15_cover/3/learn/1/
# ../python_rmse/small_cal/15_cover/3/learn/3/ ../python_rmse/small_cal/15_taltail/stereo_config3.json ../python_rmse/small_cal/15_cover/3/learn/3/
# ../python_rmse/small_cal/15_cover/3/learn/5/ ../python_rmse/small_cal/15_taltail/stereo_config3.json ../python_rmse/small_cal/15_cover/3/learn/5/
#
#example
#D:\HET\calib\data\example\image\cal\circle\raw
#change option
# select_png_or_raw = 1 #png: 0, raw: 1
#D:\HET\calib\data\example\image\cal\circle\png
#change option
# select_png_or_raw = 0 #png: 0, raw: 1
#D:\HET\calib\data\example\image\cal\square\png_8_5
# marker_point_x = 8 #pattern's width point
# marker_point_y = 5 #pattern's height point
# marker_length = 60 #pattern's gap (unit is mm)
# select_detect_pattern = 1 #circle: 0, square: 1
# select_png_or_raw = 0 #png: 0, raw: 1
#D:\HET\calib\data\example\image\cal\square\raw_6_4
# marker_point_x = 6 #pattern's width point
# marker_point_y = 4 #pattern's height point
# marker_length = 60 #pattern's gap (unit is mm)
# select_detect_pattern = 1 #circle: 0, square: 1
# select_png_or_raw = 1 #png: 0, raw: 1
#D:\HET\calib\data\example\image\cal\circle\raw D:\HET\calib\data\example\image\cal\circle\raw\stereo_config_result_r_to_l.json
# select_png_or_raw = 1 #png: 0, raw: 1
#D:\HET\calib\data\example\image\cal\square\raw_6_4 D:\HET\calib\data\example\image\cal\square\raw_6_4\stereo_config_result_r_to_l.json
# select_png_or_raw = 1 #png: 0, raw: 1
# marker_point_x = 6 #pattern's width point
# marker_point_y = 4 #pattern's height point
# marker_length = 60 #pattern's gap (unit is mm)
# select_detect_pattern = 1 #circle: 0, square: 1
# select_png_or_raw = 1 #png: 0, raw: 1
#D:\HET\calibration\luritech_parse\test\9JPM0747-806361 ./stereo_config_init_964.json D:\HET\calibration\luritech_parse\test\9JPM0747-806361
import numpy as np
import cv2
import glob
import argparse
import math
import pandas as pd
#lip #
import matplotlib.pyplot as plt
import json
import os
import sys #, getopt
import csv
import datetime as dt
import scipy.optimize
####select user option for debugging ###########################################
enable_debug_detect_pattern_from_image = 0 #true: 1, false: 0
enable_debug_display_image_point_and_reproject_point = 0 #true(from img): 1, false: 0, true(from white background): 2
enable_debug_pose_estimation_display = 0 #false: 0, all_enable: 1, left:2, right:3
enable_debug_loop_moving_of_rot_and_trans = 1 #false: 0, left: 1, right:2
enable_debug_dispatiry_estimation_display = 0 #true: 1, false: 0, debug: 2
select_png_or_raw = 0 #png: 0, raw: 1
select_point_or_arrow_based_on_reproject_point = 1 #point: 0, arrow: 1
enable_intrinsic_plus_focal = 0 #plus: 1, minus: 0
enable_extrinsic_left_to_right = 0 # left to right: 1, right to left: 0
###default setting option#########################################
select_detect_pattern = 0 #circle: 0, square: 1
marker_point_x = 10 #pattern's width point
marker_point_y = 10 #pattern's height point
marker_length = 30 #pattern's gap (unit is mm)
degreeToRadian = math.pi/180
radianToDegree = 180/math.pi
#if you want to get good quality result, please set image's width and height.
image_width = 1280 #4912
image_height = 964 #3264
default_camera_param_f = 1470 #3854
default_camera_param_cx = image_width/2
default_camera_param_cy = image_height/2
default_camera_param_k1 = -0.1
default_camera_param_k2 = -0.2
default_camera_param_p1 = 0
default_camera_param_p2 = 0
default_camera_param_k3 = 0
default_camera_param_k4 = 0
default_camera_param_k5 = 0
default_camera_param_k6 = 0
###########################################################
def check_version_of_opencv():
(major, minor, mdummy) = cv2.__version__.split(".")
return (int(major), int(minor), int(mdummy) )
###load point on csv file
def load_point_from_csv(filename):
ref_point = []
img_point_l = []
img_point_r = []
fp = open(filename, 'r', encoding='utf-8')
for row in csv.reader(fp):
# print(row)
# print(row[0], row[1], row[2])
if (float(row[3]) <= 0 or float(row[4]) <= 0 or float(row[5]) <= 0 or float(row[6]) <= 0):
print('skip', row, float(row[3]), float(row[4]), float(row[5]), float(row[6]))
else:
ref_point.append([float(row[0]), float(row[1]), float(row[2])])
img_point_l.append([float(row[3]), float(row[4])])
img_point_r.append([float(row[5]), float(row[6])])
fp.close()
# print(type(ref_point))
ret_ref_point = np.array(ref_point, np.float32)
ret_img_point_l = np.array(img_point_l, np.float32)
ret_img_point_r = np.array(img_point_r, np.float32)
# print(type(ret_ref_point))
return ret_ref_point, ret_img_point_l, ret_img_point_r
###load and get about stereo_config.json
### return value is plus focal length, and position of rot and trans from left to right
def load_value_from_json(filename):
# fpd = pd.read_json(filename)
print(filename)
fp = open(filename)
# print(fp)
fjs = json.load(fp)
# print(fjs)
m_fx, m_fy = fjs["master"]["lens_params"]['focal_len']
m_cx, m_cy = fjs["master"]["lens_params"]['principal_point']
m_k1 = fjs["master"]["lens_params"]['k1']
m_k2 = fjs["master"]["lens_params"]['k2']
m_k3 = fjs["master"]["lens_params"]['p1']
m_k4 = fjs["master"]["lens_params"]['p2']
m_k5 = fjs["master"]["lens_params"]['k3']
m_k6 = fjs["master"]["lens_params"]['k4']
m_k7 = fjs["master"]["lens_params"]['k5']
m_k8 = fjs["master"]["lens_params"]['k6']
s_fx, s_fy = fjs["slave"]["lens_params"]['focal_len']
s_cx, s_cy = fjs["slave"]["lens_params"]['principal_point']
s_k1 = fjs["slave"]["lens_params"]['k1']
s_k2 = fjs["slave"]["lens_params"]['k2']
s_k3 = fjs["slave"]["lens_params"]['p1']
s_k4 = fjs["slave"]["lens_params"]['p2']
s_k5 = fjs["slave"]["lens_params"]['k3']
s_k6 = fjs["slave"]["lens_params"]['k4']
s_k7 = fjs["slave"]["lens_params"]['k5']
s_k8 = fjs["slave"]["lens_params"]['k6']
print("*" * 50)
m_ttrans = np.zeros((3, 1))
m_trot = np.zeros((3, 1))
s_ttrans = np.zeros((3, 1))
s_trot = np.zeros((3, 1))
#################################################################
tranx = trany = tranz = 0
rotx = roty = rotz = 0
if (fjs['master'].get('camera_pose') is not None):
m_ttrans = fjs['master']['camera_pose']['trans']
m_trot = fjs['master']['camera_pose']['rot']
elif (fjs["master"].get('w_Rt_c') is not None):
m_ttrans = fjs["master"]["w_Rt_c"]['w_t_c']
m_trot[1], m_trot[0], m_trot[2] = fjs["master"]["w_Rt_c"]['w_euleryxzdeg_c']
# print('m_ttrans',m_ttrans, m_trot)
if (fjs['slave'].get('camera_pose') is not None):
s_ttrans = fjs['slave']['camera_pose']['trans']
s_trot = fjs['slave']['camera_pose']['rot']
elif (fjs["slave"].get('w_Rt_c') is not None):
s_ttrans = fjs["slave"]["w_Rt_c"]['w_t_c']
s_trot[1], s_trot[0], s_trot[2] = fjs["slave"]["w_Rt_c"]['w_euleryxzdeg_c']
# print('s_ttrans',s_ttrans, s_trot)
if (s_ttrans[0] == 0 and s_ttrans[1] == 0 and s_ttrans[2] == 0 and s_trot[0] == 0 and s_trot[1] == 0 and s_trot[2] == 0):
print("slave trans(0,0,0), rot(0,0,0)")
tranx, trany, tranz = m_ttrans # fjs["master"]["camera_pose"]['trans']
rotx, roty, rotz = m_trot # fjs["master"]["camera_pose"]['rot']
if (m_fx < 0 and m_fy < 0):
m_fx = - m_fx
m_fy = - m_fy
s_fx = - s_fx
s_fy = - s_fy
tranx = - tranx
trany = - trany
rotx = - rotx
roty = - roty
m_k3 = -m_k3
m_k4 = -m_k4
s_k3 = -s_k3
s_k4 = -s_k4
elif (m_ttrans[0] == 0 and m_ttrans[1] == 0 and m_ttrans[2] == 0 and m_trot[0] == 0 and m_trot[1] == 0 and m_trot[2] == 0):
print("master trans(0,0,0), rot(0,0,0)")
# print(s_trot, s_ttrans)
t_matrix = np.eye(4)
s_trot[0] = degreeToRadian * s_trot[0]
s_trot[1] = degreeToRadian * s_trot[1]
s_trot[2] = degreeToRadian * s_trot[2]
t_matrix[0:3, 0:3] = eulerAnglesToRotationMatrix(s_trot)
t_matrix[0:3, 3] = s_ttrans
# print('t_matrix',t_matrix)
t_matrix_inv = np.linalg.inv(t_matrix)
# print('t_matrix_inv', t_matrix_inv)
euler = rotationMatrixToEulerAngles(t_matrix_inv[0:3, 0:3]) * radianToDegree
tranx = t_matrix_inv[0][3]
trany = t_matrix_inv[1][3]
tranz = t_matrix_inv[2][3]
rotx, roty, rotz = euler
if (m_fx < 0 and m_fy < 0):
m_fx = - m_fx
m_fy = - m_fy
s_fx = - s_fx
s_fy = - s_fy
tranx = - tranx
trany = - trany
rotx = - rotx
roty = - roty
m_k3 = -m_k3
m_k4 = -m_k4
s_k3 = -s_k3
s_k4 = -s_k4
#################################################################3
print('|master [ %.8f, %.8f, %.8f, %.8f, %.8f, %.8f, %.8f, %.8f, %.8f, %.8f, %.8f, %.8f]'%(m_fx, m_fy, m_cx, m_cy, m_k1, m_k2, m_k3, m_k4, m_k5, m_k6, m_k7, m_k8))
print('|slave [ %.8f, %.8f, %.8f, %.8f, %.8f, %.8f, %.8f, %.8f, %.8f, %.8f, %.8f, %.8f]'%(s_fx, s_fy, s_cx, s_cy, s_k1, s_k2, s_k3, s_k4, s_k5, s_k6, s_k7, s_k8))
print('|trans [ %.8f, %.8f, %.8f]'%(tranx, trany, tranz))
print('|rot_radian[ %.8f, %.8f, %.8f]'%(rotx * degreeToRadian, roty * degreeToRadian, rotz * degreeToRadian))
print('|rot_degree[ %.8f, %.8f, %.8f]'%(rotx, roty, rotz) , '\n///////////////')
calib_res = fjs["master"]["lens_params"]['calib_res']
fp.close()
# return value is plus focal length, and position of rot and trans from left to right
return m_fx, m_fy, m_cx, m_cy, m_k1, m_k2, m_k3, m_k4, m_k5, m_k6, m_k7, m_k8, s_fx, s_fy, s_cx, s_cy, s_k1, s_k2, s_k3, s_k4, s_k5, s_k6, s_k7, s_k8, tranx, trany, tranz, \
rotx * degreeToRadian, roty * degreeToRadian, rotz * degreeToRadian, calib_res
###save with result to stereo_config.json
def convert(o):
if isinstance(o, np.float64):
return int(o)
print(o, type(o))
raise TypeError
def modify_value_from_json(path, filename, M1, d1, M2, d2, R, T, imgsize, ret_rp, E, F):
# fpd = pd.read_json(filename)
# print("modify_value_from_json")
# fp = open(filename + '_sample.json')
init_json = {'type': 'Ext Calibration Parameter for Stereo Camera', 'version': 2.0, 'master': {'serial': 0, 'camera_pose': {'trans': [0.0, 0.0, 0.0], 'rot': [0.0, 0.0, 0.0]}, 'lens_params': {'focal_len': [0, 0], 'principal_point': [0, 0], 'skew': 0, 'k1': 0, 'k2': 0, 'p1': 0, 'p2': 0, 'k3': 0, 'k4': 0,'k5': 0,'k6': 0,'calib_res': [0, 0]}}, 'slave': {'serial': 1, 'camera_pose': {'trans': [0.0, 0.0, 0.0], 'rot': [0.0, 0.0, 0.0]}, 'lens_params': {'focal_len': [0, 0], 'principal_point': [0, 0], 'skew': 0, 'k1': 0, 'k2': 0, 'p1': 0, 'p2': 0, 'k3': 0, 'k4': 0,'k5': 0,'k6': 0,'calib_res': [0, 0]}}}
fjson = json.dumps(init_json)
# print(filename + '_sample.json')
# fp = open("D:\HET\calibration\python_stereo/" + filename + '_sample.json')
# print("#########D:\HET\calibration\python_stereo/" + filename + '_sample.json')
fjs = json.loads(fjson)
print(fjs)
# print(type(fjs))
# tR = np.eye(3)
# tT = np.array([0,0,0])
# tM1 = np.eye(3)
# tM2 = np.eye(3)
tR = R.copy()
tT = T.copy()
tM1 = M1.copy()
tM2 = M2.copy()
td1 = d1.copy()
td2 = d2.copy()
if (enable_intrinsic_plus_focal == 1):
print("flag enable_intrinsic_plus_focal")
if(M1[0][0] > 0):
print("input +focal") #ok
else:
print("input -focal")
tR[0][2] = -(R[0][2])
tR[1][2] = -(R[1][2])
tR[2][0] = -(R[2][0])
tR[2][1] = -(R[2][1])
tT[0] = -T[0]
tT[1] = -T[1]
tT[2] = T[2]
tM1[0][0] = - (M1[0][0])
tM1[1][1] = - (M1[1][1])
tM2[0][0] = - (M2[0][0])
tM2[1][1] = - (M2[1][1])
td1[0][2] = - (td1[0][2])
td1[0][3] = - (td1[0][3])
td2[0][2] = - (td2[0][2])
td2[0][3] = - (td2[0][3])
else:
print("flag enable_intrinsic_minus_focal")
if(M1[0][0] > 0):
print("input +focal")
tR[0][2] = -(R[0][2])
tR[1][2] = -(R[1][2])
tR[2][0] = -(R[2][0])
tR[2][1] = -(R[2][1])
tT[0] = -T[0]
tT[1] = -T[1]
tT[2] = T[2]
tM1[0][0] = - (M1[0][0])
tM1[1][1] = - (M1[1][1])
tM2[0][0] = - (M2[0][0])
tM2[1][1] = - (M2[1][1])
td1[0][2] = - (td1[0][2])
td1[0][3] = - (td1[0][3])
td2[0][2] = - (td2[0][2])
td2[0][3] = - (td2[0][3])
else:
print("input -focal") #ok
if (enable_extrinsic_left_to_right == 1): # left to right: 0
euler = rotationMatrixToEulerAngles(tR) * radianToDegree
print('T', tT)
# fjs["master"]["camera_pose"]['trans'] = tT[0], tT[1], tT[2]
fjs["master"]["camera_pose"]['trans'] = *tT[0], *tT[1], *tT[2]
fjs["master"]["camera_pose"]['rot'] = euler[0], euler[1], euler[2]
else: #right to left: 1
t_matrix = np.eye(4)
t_matrix[0:3, 0:3] = tR
t_matrix[0:3, 3] = tT.T
# print('t_matrix',t_matrix)
t_matrix_inv = np.linalg.inv(t_matrix)
# print('t_matrix_inv', t_matrix_inv)
euler = rotationMatrixToEulerAngles(t_matrix_inv[0:3, 0:3]) * radianToDegree
fjs["slave"]["camera_pose"]['trans'] = t_matrix_inv[0][3], t_matrix_inv[1][3], t_matrix_inv[2][3]
fjs["slave"]["camera_pose"]['rot'] = euler[0], euler[1], euler[2]
# print('euler', euler)
fjs["master"]["lens_params"]['focal_len'] = tM1[0][0], tM1[1][1]
fjs["master"]["lens_params"]['principal_point'] = tM1[0][2], tM1[1][2]
fjs["master"]["lens_params"]['k1'] = td1[0][0]
fjs["master"]["lens_params"]['k2'] = td1[0][1]
fjs["master"]["lens_params"]['p1'] = td1[0][2]
fjs["master"]["lens_params"]['p2'] = td1[0][3]
fjs["master"]["lens_params"]['k3'] = td1[0][4]
fjs["master"]["lens_params"]['k4'] = td1[0][5]
fjs["master"]["lens_params"]['k5'] = td1[0][6]
fjs["master"]["lens_params"]['k6'] = td1[0][7]
fjs["slave"]["lens_params"]['focal_len'] = tM2[0][0], tM2[1][1]
fjs["slave"]["lens_params"]['principal_point'] = tM2[0][2], tM2[1][2]
fjs["slave"]["lens_params"]['k1'] = td2[0][0]
fjs["slave"]["lens_params"]['k2'] = td2[0][1]
fjs["slave"]["lens_params"]['p1'] = td2[0][2]
fjs["slave"]["lens_params"]['p2'] = td2[0][3]
fjs["slave"]["lens_params"]['k3'] = td2[0][4]
fjs["slave"]["lens_params"]['k4'] = td2[0][5]
fjs["slave"]["lens_params"]['k5'] = td2[0][6]
fjs["slave"]["lens_params"]['k6'] = td2[0][7]
print("*" * 50)
fjs["master"]["lens_params"]['calib_res'] = imgsize
fjs["slave"]["lens_params"]['calib_res'] = imgsize
fjs["reprojection_error"] = np.round(ret_rp,8)
tE = np.round(E, 8)
tF = np.round(F, 8)
fjs["essensial_matrix"] = tE[0][0],tE[0][1],tE[0][2],tE[1][0],tE[1][1],tE[1][2],tE[2][0],tE[2][1],tE[2][2]
fjs["fundamental_matrix"] = tF[0][0],tF[0][1],tF[0][2],tF[1][0],tF[1][1],tF[1][2],tF[2][0],tF[2][1],tF[2][2]
# wfp = open(path + '/' +filename + '_result_l_to_r' + '.json', 'w', encoding='utf-8')
# print( path + '/' +filename+ '_result_l_to_r' + '.json')
# json.dump(fjs, wfp, indent=4)
# wfp.close()
# enable_intrinsic_plus_focal = 1 # plus: 1, minus: 0
# enable_extrinsic_left_to_right = 1 # left to right: 1, right to left: 0
if (enable_extrinsic_left_to_right == 1):
tsubname = '_l_to_r'
else:
tsubname = '_r_to_l'
if (enable_intrinsic_plus_focal == 1):
tsubname = tsubname + '_plus_f'
else:
tsubname = tsubname + '_minus_f'
for i in range(0, 1000, 1):
fnum = '_%03d' % (i)
# print(filename + tsubname + fnum + '.json')
if not os.path.isfile(path + '/'+ filename + tsubname + fnum + '.json'):
# print('break')
break
print('save....... ' + filename + tsubname + fnum + '.json')
wfp2 = open(path + '/' +filename + tsubname + fnum + '.json', 'w', encoding='utf-8')
json.dump(fjs, wfp2, indent=4, default=convert)
wfp2.close()
# fp.close()
def modify_value_from_json_from_plus_to_minus_focal(path, filename, M1, d1, M2, d2, R, T, imgsize, ret_rp, E, F):
# fpd = pd.read_json(filename)
# print("modify_value_from_json_from_plus_to_minus_focal")
fp = open(filename + '_sample.json')
fjs = json.load(fp)
# print(fjs)
# print(type(fjs))
# fjs["master"]["lens_params"]['focal_len'] = M1[0][0], M1[1][1]
fjs["master"]["lens_params"]['focal_len'] = M1[0][0], M1[1][1]
fjs["master"]["lens_params"]['principal_point'] = M1[0][2], M1[1][2]
fjs["master"]["lens_params"]['k1'] = d1[0][0]
fjs["master"]["lens_params"]['k2'] = d1[0][1]
fjs["master"]["lens_params"]['p1'] = d1[0][2]
fjs["master"]["lens_params"]['p2'] = d1[0][3]
fjs["master"]["lens_params"]['k3'] = d1[0][4]
fjs["master"]["lens_params"]['k4'] = d1[0][5]
fjs["master"]["lens_params"]['k5'] = d1[0][6]
fjs["master"]["lens_params"]['k6'] = d1[0][7]
# fjs["slave"]["lens_params"]['focal_len'] = M2[0][0], M2[1][1]
fjs["slave"]["lens_params"]['focal_len'] = M2[0][0], M2[1][1]
fjs["slave"]["lens_params"]['principal_point'] = M2[0][2], M2[1][2]
fjs["slave"]["lens_params"]['k1'] = d2[0][0]
fjs["slave"]["lens_params"]['k2'] = d2[0][1]
fjs["slave"]["lens_params"]['p1'] = d2[0][2]
fjs["slave"]["lens_params"]['p2'] = d2[0][3]
fjs["slave"]["lens_params"]['k3'] = d2[0][4]
fjs["slave"]["lens_params"]['k4'] = d2[0][5]
fjs["slave"]["lens_params"]['k5'] = d2[0][6]
fjs["slave"]["lens_params"]['k6'] = d2[0][7]
print("*" * 50)
# fjs["slave"]["camera_pose"]['trans'] = *T[0], *T[1], *T[2]
fjs["slave"]["camera_pose"]['trans'] = T[0], T[1], T[2]
euler = rotationMatrixToEulerAngles(R) * radianToDegree
print('slave_T', T)
print('slave_R', euler)
fjs["slave"]["camera_pose"]['rot'] = euler[0], euler[1], euler[2]
fjs["master"]["lens_params"]['calib_res'] = imgsize
fjs["slave"]["lens_params"]['calib_res'] = imgsize
fjs["reprojection_error"] = np.round(ret_rp,8)
tE = np.round(E, 8)
tF = np.round(F, 8)
fjs["essensial_matrix"] = tE[0][0],tE[0][1],tE[0][2],tE[1][0],tE[1][1],tE[1][2],tE[2][0],tE[2][1],tE[2][2]
fjs["fundamental_matrix"] = tF[0][0],tF[0][1],tF[0][2],tF[1][0],tF[1][1],tF[1][2],tF[2][0],tF[2][1],tF[2][2]
wfp = open(path + '/' +filename + '_result_r_to_l' + '.json', 'w', encoding='utf-8')
json.dump(fjs, wfp, indent=4)
fp.close()
wfp.close()
###extarct and save coordinate point to csv file
def save_coordinate_both_stereo_obj_img(path, objpoints, imgpoints_l, imgpoints_r, count_ok_dual):
table = []
refpointx = []
refpointy = []
refpointz = []
lpointx = []
lpointy = []
rpointx = []
rpointy = []
print('3D ref count', len(objpoints))
print('Left img count', len(imgpoints_l))
print('Right img count', len(imgpoints_r))
# print(len(objpoints) / count_ok_dual)
# print(type(imgpoints_l))
for i in objpoints:
for refpoint in i:
# print(refpoint[0],refpoint[1],refpoint[2])
refpointx.append(refpoint[0])
refpointy.append(refpoint[1])
refpointz.append(refpoint[2])
for i in imgpoints_l:
for j in i:
for leftpoint in j:
# print(leftpoint[0], leftpoint[1])
lpointx.append(leftpoint[0])
lpointy.append(leftpoint[1])
# print(i.shape)
# print("&" * 50)
for i in imgpoints_r:
for j in i:
for rightpoint in j:
# print(rightpoint[0], rightpoint[1])
rpointx.append(rightpoint[0])
rpointy.append(rightpoint[1])
# ret_table = np.zeros((count_ok_dual, len(refpointx)/count_ok_dual), np.float32)
group_of_value = int(len(refpointx) / count_ok_dual)
# ret_table = np.zeros((count_ok_dual, group_of_value), np.float32)
# ret_table = [[0 for cols in range(group_of_value)] for rows in range(count_ok_dual)]
ret_tables = []
# print(ret_table)
for i in range(0, len(refpointx), 1):
table.append([refpointx[i], refpointy[i], refpointz[i], lpointx[i], lpointy[i], rpointx[i], rpointy[i]])
col = ['refpX', 'refpY', 'refpZ', 'M_imgX', 'M_imgY', 'S_imgX', 'S_imgY']
for j in range(0, count_ok_dual, 1):
temp = []
for i in range(0, group_of_value, 1):
temp.append([refpointx[i + group_of_value * j], refpointy[i + group_of_value * j],refpointz[i + group_of_value * j],
lpointx[i + group_of_value * j], lpointy[i + group_of_value * j],
rpointx[i + group_of_value * j], rpointy[i + group_of_value * j]])
temp = np.round(temp, 6)
output2 = pd.DataFrame(temp, columns=col)
tfilename = "p_from_img%03d.csv"%(j)
output2.to_csv(path + '/' +tfilename, index=False, header=False)
table = np.round(table, 6)
output = pd.DataFrame(table, columns=col)
output.to_csv(path + '/' + "total_p_from_img.txt", index=False, header=False)
def save_coordinate_using_rectify(path, objpoints, imgpoints_l, imgpoints_r, count_ok_dual):
table = []
refpointx = []
refpointy = []
refpointz = []
lpointx = []
lpointy = []
rpointx = []
rpointy = []
for i in objpoints:
for refpoint in i:
refpointx.append(refpoint[0])
refpointy.append(refpoint[1])
refpointz.append(refpoint[2])
for i in imgpoints_l:
for j in i:
for leftpoint in j:
lpointx.append(leftpoint[0])
lpointy.append(leftpoint[1])
for i in imgpoints_r:
for j in i:
for rightpoint in j:
rpointx.append(rightpoint[0])
rpointy.append(rightpoint[1])
for i in range(0, len(refpointx), 1):
table.append([refpointx[i], refpointy[i], refpointz[i], lpointx[i], lpointy[i], rpointx[i], rpointy[i]])
group_of_value = int(len(refpointx) / count_ok_dual)
col = ['refpX', 'refpY', 'refpZ', 'M_imgX', 'M_imgY', 'S_imgX', 'S_imgY']
for j in range(0, count_ok_dual, 1):
temp = []
for i in range(0, group_of_value, 1):
temp.append([refpointx[i + group_of_value * j], refpointy[i + group_of_value * j],refpointz[i + group_of_value * j],
lpointx[i + group_of_value * j], lpointy[i + group_of_value * j],
rpointx[i + group_of_value * j], rpointy[i + group_of_value * j]])
temp = np.round(temp, 6)
output2 = pd.DataFrame(temp, columns=col)
tfilename = "rectify_from_img%03d.csv"%(j)
output2.to_csv(path + '/' + tfilename, index=False, header=False)
table = np.round(table, 6)
output = pd.DataFrame(table, columns=col)
output.to_csv(path + '/' + "totalRectify_p_from_img.txt", index=False, header=False)
def save_coordinate_using_rectify_with_distance(path, objpoints, imgpoints_l, imgpoints_r, baseline, focal):
table = []
refpointx = []
refpointy = []
refpointz = []
lpointx = []
lpointy = []
rpointx = []
rpointy = []
for i in objpoints:
for refpoint in i:
refpointx.append(refpoint[0])
refpointy.append(refpoint[1])
refpointz.append(refpoint[2])
for i in imgpoints_l:
for j in i:
for leftpoint in j:
lpointx.append(leftpoint[0])
lpointy.append(leftpoint[1])
for i in imgpoints_r:
for j in i:
for rightpoint in j:
rpointx.append(rightpoint[0])
rpointy.append(rightpoint[1])
for i in range(0, len(refpointx), 1):
distance = (focal * baseline) / (lpointx[i] - rpointx[i])
table.append([refpointx[i], refpointy[i], refpointz[i], lpointx[i], lpointy[i], rpointx[i], rpointy[i], distance])
group_of_value = int(len(refpointx) / len(objpoints))
col = ['refpX', 'refpY', 'refpZ', 'M_imgX', 'M_imgY', 'S_imgX', 'S_imgY', 'Distance']
for j in range(0, len(objpoints), 1):
temp = []
for i in range(0, group_of_value, 1):
distance = (focal * baseline) / (lpointx[i + group_of_value * j] - rpointx[i + group_of_value * j])
temp.append([refpointx[i + group_of_value * j], refpointy[i + group_of_value * j],refpointz[i + group_of_value * j],
lpointx[i + group_of_value * j], lpointy[i + group_of_value * j],
rpointx[i + group_of_value * j], rpointy[i + group_of_value * j], distance])
temp = np.round(temp, 6)
output2 = pd.DataFrame(temp, columns=col)
tfilename = "distance_from_img%03d.csv"%(j)
output2.to_csv(path + '/' + tfilename, index=False, header=False)
table = np.round(table, 6)
output = pd.DataFrame(table, columns=col)
output.to_csv(path + '/' + "totalDist_p_from_img.txt", index=False, header=False)
def print_current_time(path, name):
print(path)
if(path == None):
return
flog = open(path + name, 'a')
tnow = dt.datetime.now()
flog.write('\n/////////////// %s-%2s-%2s %2s:%2s:%2s //////////////\n' % (
tnow.year, tnow.month, tnow.day, tnow.hour, tnow.minute, tnow.second))
flog.close()
print('%s-%2s-%2s %2s:%2s:%2s' % (tnow.year, tnow.month, tnow.day, tnow.hour, tnow.minute, tnow.second))
ply_header = '''ply
format ascii 1.0
element vertex %(vert_num)d
property float x
property float y
property float z
property uchar red
property uchar green
property uchar blue
end_header
'''
def write_ply(fn, verts, colors):
verts = verts.reshape(-1, 3)
colors = colors.reshape(-1, 3)
verts = np.hstack([verts, colors])
with open(fn, 'wb') as f:
f.write((ply_header % dict(vert_num=len(verts))).encode('utf-8'))
np.savetxt(f, verts, fmt='%f %f %f %d %d %d ')
def least_squares_stereo_rmse(x, tobj_point, timgpoint_l, timgpoint_r, A1, D1, A2, D2, R, T):
tot_error = 0
total_points = 0
# rvec_l = np.zeros(1,3)
# tvec_l = np.zeros(1,3)
rvec_l = x[0:3]
tvec_l = x[3:6]
# print(rvec_l, tvec_l)
rp_l, _ = cv2.projectPoints(tobj_point, rvec_l, tvec_l, A1, D1)
# print( 'rp_l' , rp_l )tobj_point
# tot_error += np.sum(np.square(np.float64(imgpoints_l[i] - rp_l)))
tot_error += np.sum(np.square(np.float64(rp_l - timgpoint_l)))
total_points += len(tobj_point)
# calculate world <-> cam2 transformation
rvec_r, tvec_r = cv2.composeRT(rvec_l, tvec_l, cv2.Rodrigues(R)[0], T)[:2]
# print('rvec_r', 'tvec_r', rvec_r, tvec_r)
# compute reprojection error for cam2
rp_r, _ = cv2.projectPoints(tobj_point, rvec_r, tvec_r, A2, D2)
# print( 'rp_r' , rp_r )
# tot_error += np.square(rp_r - t_imgpoints_r).sum()
tot_error += np.sum(np.square(np.float64(rp_r - timgpoint_r)))
total_points += len(tobj_point)
# temp_error = np.square(rp_r - t_imgpoints_r).sum() + np.square(rp_l - t_imgpoints_l).sum()
temp_error = np.sum(np.square(np.float64(rp_l - timgpoint_l))) + np.sum(np.square(np.float64(rp_r - timgpoint_r)))
temp_points = 2 * len(tobj_point)
# temp_error = np.sum(np.square(np.float64(rp_l - timgpoint_l)))
# temp_points = len(tobj_point)
temp_mean_error = np.sqrt(temp_error / temp_points)
return temp_mean_error
def least_squares_stereo_rmse2(x, tobj_point, timgpoint_l, timgpoint_r, A1, D1, A2, D2, R, T):
tot_error = 0
total_points = 0
res = scipy.optimize.least_squares(fun=least_squares_stereo_rmse3, x0=x,
args=(R, T))
print(res)
if res['success'] == False:
print('Failed minimization')
return np.nan
print('res', res['x'])
print(x)
rvec_l = res['x'][0:3]
tvec_l = res['x'][3:6]
rp_l, _ = cv2.projectPoints(tobj_point, rvec_l, tvec_l, A1, D1)
# print( 'rp_l' , rp_l )tobj_point
# tot_error += np.sum(np.square(np.float64(imgpoints_l[i] - rp_l)))
tot_error += np.sum(np.square(np.float64(rp_l - timgpoint_l)))
total_points += len(tobj_point)
# calculate world <-> cam2 transformation
rvec_r2, tvec_r2 = cv2.composeRT(rvec_l, tvec_l, cv2.Rodrigues(R)[0], T)[:2]
# print('rvec_r', 'tvec_r', rvec_r, tvec_r)
# compute reprojection error for cam2
rp_r, _ = cv2.projectPoints(tobj_point, rvec_r2, tvec_r2, A2, D2)
# print( 'rp_r' , rp_r )
# tot_error += np.square(rp_r - t_imgpoints_r).sum()
tot_error += np.sum(np.square(np.float64(rp_r - timgpoint_r)))
total_points += len(tobj_point)
# temp_error = np.square(rp_r - t_imgpoints_r).sum() + np.square(rp_l - t_imgpoints_l).sum()
temp_error = np.sum(np.square(np.float64(rp_l - timgpoint_l))) + np.sum(np.square(np.float64(rp_r - timgpoint_r)))
temp_points = 2 * len(tobj_point)
# temp_error = np.sum(np.square(np.float64(rp_l - timgpoint_l)))
# temp_points = len(tobj_point)
temp_mean_error = np.sqrt(temp_error / temp_points)
print('rmse %.8f' % temp_mean_error)
return temp_mean_error
def least_squares_stereo_rmse3(x, R, T):
tot_error = 0
total_points = 0
# rvec_l = np.zeros(1,3)
# tvec_l = np.zeros(1,3)
rvec_l = x[0:3]
tvec_l = x[3:6]
rvec_r = x[6:9]
tvec_r = x[9:12]
# print(rvec_l, tvec_l)
x[0:3] = rvec_l.reshape(3)
x[3:6] = tvec_l.reshape(3)
x[6:9] = rvec_r.reshape(3)
x[9:12] = tvec_r.reshape(3)
rvec_r2, tvec_r2 = cv2.composeRT(rvec_l, tvec_l, cv2.Rodrigues(R)[0], T)[:2]
# print('rvec_r', 'tvec_r', rvec_r, tvec_r)
# residuals = np.sum(np.square(rvec_r-rvec_r2) + np.square(tvec_r-tvec_r2))
rvec_r3, tvec_r3 = cv2.composeRT(rvec_r2, tvec_r2, -rvec_r, -tvec_r)[:2]
# residuals = np.sum(np.square(tvec_r3))
residuals = np.sum(np.square(tvec_r3)+np.square(rvec_r3))
print('result\n', residuals)
return residuals
def least_squares_stereo_rmse4(x, tobj_point, timgpoint_l, timgpoint_r, A1, D1, A2, D2, R, T):
rvec_l = x[0:3]
tvec_l = x[3:6]
rp_l, _ = cv2.projectPoints(tobj_point, rvec_l, tvec_l, A1, D1)
rvec_r, tvec_r = cv2.composeRT(rvec_l, tvec_l, cv2.Rodrigues(R)[0], T)[:2]
rp_r, _ = cv2.projectPoints(tobj_point, rvec_r, tvec_r, A2, D2)
residuals = np.vstack([np.float64(rp_l - timgpoint_l), np.float64(rp_r - timgpoint_r)]).ravel()
return residuals
#################################################################################################
# https://www.learnopencv.com/rotation-matrix-to-euler-angles/
# Checks if a matrix is a valid rotation matrix.
def isRotationMatrix(R):
Rt = np.transpose(R)
shouldBeIdentity = np.dot(Rt, R)
I = np.identity(3, dtype=R.dtype)
n = np.linalg.norm(I - shouldBeIdentity)
return n < 1e-6
# Calculates rotation matrix to euler angles
# The result is the same as MATLAB except the order
# of the euler angles ( x and z are swapped ).
def rotationMatrixToEulerAngles(R):
assert (isRotationMatrix(R))
# sy = math.sqrt(R[0, 0] * R[0, 0] + R[1, 0] * R[1, 0])
sy = math.sqrt(R[2, 1] * R[2, 1] + R[2, 2] * R[2, 2])
# print(sy)
singular = sy < 1e-6
if not singular:
x = math.atan2(R[2, 1], R[2, 2])
y = math.atan2(-R[2, 0], sy)
z = math.atan2(R[1, 0], R[0, 0])
# print(x, y, z)
else:
x = math.atan2(-R[1, 2], R[1, 1])
y = math.atan2(-R[2, 0], sy)
z = 0
return np.array([x, y, z]) #(X)Pitch / (Y)Yaw / (Z)Roll.
# Calculates Rotation Matrix given euler angles.
def eulerAnglesToRotationMatrix(theta):
R_x = np.array([[1, 0, 0],
[0, math.cos(theta[0]), -math.sin(theta[0])],
[0, math.sin(theta[0]), math.cos(theta[0])]
])
R_y = np.array([[math.cos(theta[1]), 0, math.sin(theta[1])],
[0, 1, 0],
[-math.sin(theta[1]), 0, math.cos(theta[1])]
])
R_z = np.array([[math.cos(theta[2]), -math.sin(theta[2]), 0],
[math.sin(theta[2]), math.cos(theta[2]), 0],
[0, 0, 1]
])
R = np.dot(R_z, np.dot(R_y, R_x))
return R
#############################################################################################
class StereoCalibration(object):
def getName(self):
return "extend"
def __init__(self, argv):
# termination criteria
self.criteria = (cv2.TERM_CRITERIA_EPS +
cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)
self.criteria_cal = (cv2.TERM_CRITERIA_EPS +
cv2.TERM_CRITERIA_MAX_ITER, 100, 1e-5)
# prepare object points, like (0,0,0), (1,0,0), (2,0,0) ....,(6,5,0)
#self.objp = np.zeros((9 * 6, 3), np.float32)
#self.objp[:, :2] = np.mgrid[0:9, 0:6].T.reshape(-1, 2)
self.objp = np.zeros((marker_point_x * marker_point_y, 3), np.float32)
self.objp[:, :2] = np.mgrid[0: marker_point_x, 0: marker_point_y].T.reshape(-1, 2) * marker_length * 0.001
# self.objp[:, :2] = self.objp[:, :2] - [((0 + (marker_point_x - 1) * marker_length * 0.001) / 2), ((0 + (marker_point_y - 1) * marker_length * 0.001) / 2)]
# patternsize = (10,10)
# self.objs_test = np.zeros((np.prod(patternsize),3), np.float32)
# self.objs_test[:,:2] = np.indices(patternsize).T.reshape(-1,2)
# self.objs_test *= 30
# sum = np.sum(self.objs_test)
# # print(np.bincount(self.objs_test))
# print(self.objs_test.shape)
tobj_center = np.mean(self.objp, axis=0)
self.objp_center = self.objp - tobj_center
# print(type(self.objp))
# print(self.objp)
# pose estimation
#self.axis = np.float32([[3, 0, 0], [0, 3, 0], [0, 0, -3]]).reshape(-1, 3)
self.axis = np.float32([[marker_length * 0.001 *3, 0, 0], [0, marker_length * 0.001 *3, 0], [0, 0, marker_length * 0.001 * -3]]).reshape(-1, 3)
if(argv == 'Manual'):
print("initialize done")
return
# self.cal_path = filepath
if len(argv) >= 2:
self.initialize(argv[1])
print('argv[1]= ', argv[1], ', argc=', len(argv), '\n\n')
else:
print("argument is wrong. please check it, again\n")
return
if len(argv) >= 4:
cal_loadjson = argv[2]
cal_loadpoint = argv[3]
print('argv[2]= ', argv[2], ', len= ', len(argv), '\n\n')
self.calc_rms_about_stereo(self.cal_path, cal_loadjson, cal_loadpoint)
# self.read_points_with_stereo(self.cal_path, cal_loadjson, cal_loadpoint)
# self.repeat_calibration(3, 3, self.cal_path, cal_loadjson, cal_loadpoint)
# self.read_points_with_mono_stereo(self.cal_path, cal_loadjson, cal_loadpoint)
elif len(argv) >= 3:
cal_loadjson = argv[2]
print('argv[2]=', argv[2], ', len= ', len(argv), '\n\n')
self.read_param_and_images_with_stereo(self.cal_path, cal_loadjson)
else:
# self.repeat_calibration(1,1,self.cal_path, 0, 0)
self.read_images_with_mono_stereo(self.cal_path)
pass
def initialize(self, basepath):
# Arrays to store object points and image points from all the images.
self.objpoints = [] # 3d point in real world space
self.objpoints_center = [] # 3d point in real world space for center of chart
self.imgpoints_l = [] # 2d points in image plane.
self.imgpoints_r = [] # 2d points in image plane.
print('BasePath', basepath)
self.cal_path = basepath
def repeat_calibration(self, action, idx, cal_path, cal_loadjson, cal_loadpoint):
CURRENT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__)))
if(action==1 and idx==1):
try:
os.chdir(cal_path)
print("change path2", cal_path)
files_to_replace = []
for dirpath, dirnames, filenames in os.walk("."):
if(os.path.exists(dirpath+'/LEFT') and os.path.exists(dirpath+'/RIGHT')):
print(dirpath)
files_to_replace.append(os.path.join(dirpath)+'\\')
elif(os.path.exists(dirpath + '/L') and os.path.exists(dirpath + '/R')):
print(dirpath)
files_to_replace.append(os.path.join(dirpath)+'\\')
except OSError:
print("Can't change the Current Working Directory")
print(files_to_replace)
for tpath in files_to_replace:
self.objpoints = [] # 3d point in real world space
self.objpoints_center = [] # 3d point in real world space for center of chart
self.imgpoints_l = [] # 2d points in image plane.
self.imgpoints_r = [] # 2d points in image plane.
print('tpath', tpath)
# self.read_points_with_stereo(tpath, cal_loadjson, tpath)
# self.read_points_with_mono_stereo(tpath, cal_loadjson, tpath)
self.read_images_with_mono_stereo(tpath)
else:
try:
os.chdir(cal_path)
print("change path", cal_path)
files_to_replace = []
for dirpath, dirnames, filenames in os.walk("."):
for filename in [f for f in filenames if f.endswith(".csv")]:
# files_to_replace.append(os.path.join(dirpath))
if("distance_from_img" in filename):
# print('skip file: ',filename)
continue
if("rectify_from_img" in filename):
# print('skip file: ', filename)
continue
files_to_replace.append(os.path.abspath(dirpath))
# print(filename)
break
# print("ok")
# for filename in [f for f in filenames if f.endswith(".json")]:
# print(os.path.join(dirpath))