File size: 69,607 Bytes
1403119
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
import numpy as np
import cv2
import open3d as o3d
import os
import sys
from scipy.spatial.transform import Rotation as Rot
from scipy.sparse import lil_matrix
from scipy.optimize import least_squares
from sklearn.cluster import KMeans
import argparse
import time
import itertools

parser = argparse.ArgumentParser()
parser.add_argument('--num', help='Cur run', required=True)
args = parser.parse_args()
cur_process_id = int(args.num)


def get_keypoints_from_indices(keypoints1, index_list1, keypoints2, index_list2):
    """Filters a list of keypoints based on the indices given"""
    points1 = np.array([kp.pt for kp in keypoints1])[index_list1]
    points2 = np.array([kp.pt for kp in keypoints2])[index_list2]
    return points1, points2


def get_3D_point(u1, P1, u2, P2):
    """Solves for 3D point using homogeneous 2D points and the respective camera matrices"""
    A = np.array([[u1[0] * P1[2, 0] - P1[0, 0], u1[0] * P1[2, 1] - P1[0, 1], u1[0] * P1[2, 2] - P1[0, 2]],
                  [u1[1] * P1[2, 0] - P1[1, 0], u1[1] * P1[2, 1] - P1[1, 1], u1[1] * P1[2, 2] - P1[1, 2]],
                  [u2[0] * P2[2, 0] - P2[0, 0], u2[0] * P2[2, 1] - P2[0, 1], u2[0] * P2[2, 2] - P2[0, 2]],
                  [u2[1] * P2[2, 0] - P2[1, 0], u2[1] * P2[2, 1] - P2[1, 1], u2[1] * P2[2, 2] - P2[1, 2]]])
    B = np.array([-(u1[0] * P1[2, 3] - P1[0, 3]),
                  -(u1[1] * P1[2, 3] - P1[1, 3]),
                  -(u2[0] * P2[2, 3] - P2[0, 3]),
                  -(u2[1] * P2[2, 3] - P2[1, 3])])
    X = cv2.solve(A, B, flags=cv2.DECOMP_SVD)
    return X[1]


def remove_outliers_using_F(view1, view2, match_object):
    """Removes outlier keypoints using the fundamental matrix"""
    pixel_points1, pixel_points2 = get_keypoints_from_indices(keypoints1=view1.keypoints,
                                                              keypoints2=view2.keypoints,
                                                              index_list1=match_object.indices1,
                                                              index_list2=match_object.indices2)
    if len(pixel_points1) <= 8:  # A minimum of 8 points is required to calculate the fundamental matrix
        return None
    F, mask = cv2.findFundamentalMat(pixel_points1, pixel_points2, method=cv2.FM_RANSAC,
                                     ransacReprojThreshold=0.3, confidence=0.9999)
    mask = mask.astype(bool).flatten()
    match_object.inliers1 = np.array(match_object.indices1)[mask]
    match_object.inliers2 = np.array(match_object.indices2)[mask]
    return F


def calculate_reprojection_error(point_3D, point_2D, k, R, t):
    """Calculates the reprojection error for a 3D point by projecting it back into the image plane"""
    reprojected_point = k.dot(R.dot(point_3D) + t)
    if reprojected_point[-1][0] < 0:
        return 999
    reprojected_point = cv2.convertPointsFromHomogeneous(reprojected_point.T)[:, 0, :].T
    error = np.linalg.norm(point_2D.reshape((2, 1)) - reprojected_point)
    return error


def get_camera_from_E(E):
    """Calculates rotation and translation component from essential matrix"""
    W = np.array([[0, -1, 0], [1, 0, 0], [0, 0, 1]])
    W_t = W.T
    u, w, vt = np.linalg.svd(E)
    R1 = u @ W @ vt
    R2 = u @ W_t @ vt
    t1 = u[:, -1].reshape((3, 1))
    t2 = - t1
    return R1, R2, t1, t2


def check_determinant(R):
    """Validates using the determinant of the rotation matrix"""
    if np.linalg.det(R) + 1.0 < 1e-9:
        return False
    else:
        return True


def check_triangulation(points, P):
    """Checks whether reconstructed points lie in front of the camera"""
    P = np.vstack((P, np.array([0, 0, 0, 1])))
    reprojected_points = cv2.perspectiveTransform(src=points[np.newaxis], m=P)
    z = reprojected_points[0, :, -1]
    if (np.sum(z > 0)/z.shape[0]) < 0.75:
        return False
    else:
        return True


class Match:
    """Represents a feature match between two views"""
    def __init__(self, view1, view2, use_spatial_consistency_check=0):
        self.indices1 = []  # indices of the matched keypoints in the first view
        self.indices2 = []  # indices of the matched keypoints in the second view
        self.distances = []  # distance between the matched keypoints in the first view
        self.image_name1 = view1.name  # name of the first view
        self.image_name2 = view2.name  # name of the second view
        self.root_path = view1.root_path  # root directory containing the image folder
        # list to store the indices of the keypoints from the first view not removed using the fundamental matrix
        self.inliers1 = []
        # list to store the indices of the keypoints from the second view not removed using the fundamental matrix
        self.inliers2 = []
        self.view1 = view1
        self.view2 = view2
        self.use_spatial_consistency_check = use_spatial_consistency_check  # value for spatial consistency check
        if view1.feature_type in ['sift', 'surf']:
            self.matcher = cv2.BFMatcher(cv2.NORM_L2)  # Added for Lowes ratio test
        else:
            self.matcher = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)
        self.get_matches(view1, view2)

    def get_matches(self, view1, view2):
        """ Extracts feature matches between two views """
        matches = self.matcher.knnMatch(view1.descriptors, view2.descriptors, k=2)  # k=2 for Lowes ratio test
        good_matches = []
        for m, n in matches:
            # Only accept matches where the best match is significantly better than the second best
            if m.distance < 0.75 * n.distance:
                good_matches.append(m)
        # sort the found matches according to their feature distance
        matches = sorted(good_matches, key=lambda x: x.distance)
        # store match components in their respective lists
        for i in range(len(matches)):
            self.indices1.append(matches[i].queryIdx)
            self.indices2.append(matches[i].trainIdx)
            self.distances.append(matches[i].distance)
        if self.use_spatial_consistency_check > 0:
            # Apply the Spatial Consistency Check
            # See https://ieeexplore.ieee.org/document/5459459
            nv1 = (np.sqrt(np.sum((np.array([view1.keypoints[ckp].pt for ckp in range(len(view1.keypoints))])[None, :]
                                  - np.array([view1.keypoints[ckp].pt for ckp in range(len(view1.keypoints))])[:,
                                  None]) ** 2, axis=-1)) < self.use_spatial_consistency_check) * \
                  (np.array([view1.keypoints[ckp].size for ckp in range(len(view1.keypoints))])[None, :]
                   / np.array([view1.keypoints[ckp].size for ckp in range(len(view1.keypoints))])[:, None] < 2) * \
                  (np.array([view1.keypoints[ckp].size for ckp in range(len(view1.keypoints))])[None, :]
                   / np.array([view1.keypoints[ckp].size for ckp in range(len(view1.keypoints))])[:, None] > 0.5)
            nv2 = (np.sqrt(np.sum((np.array([view2.keypoints[ckp].pt for ckp in range(len(view2.keypoints))])[None, :]
                                  - np.array([view2.keypoints[ckp].pt for ckp in range(len(view2.keypoints))])[:,
                                  None]) ** 2, axis=-1)) < self.use_spatial_consistency_check) * \
                  (np.array([view2.keypoints[ckp].size for ckp in range(len(view2.keypoints))])[None, :]
                   / np.array([view2.keypoints[ckp].size for ckp in range(len(view2.keypoints))])[:, None] < 2) * \
                  (np.array([view2.keypoints[ckp].size for ckp in range(len(view2.keypoints))])[None, :]
                   / np.array([view2.keypoints[ckp].size for ckp in range(len(view2.keypoints))])[:, None] > 0.5)
            for cc in range(len(matches)):
                nvi1 = np.sum(nv1[self.indices1[cc], self.indices1])
                if nvi1 == 0:
                    continue
                Nc = np.sum(nv1[self.indices1[cc], self.indices1] * nv2[self.indices2[cc], self.indices2])
                if Nc/nvi1 >= 0.55:
                    self.indices1.append(self.indices1[cc])
                    self.indices2.append(self.indices2[cc])
                    self.distances.append(self.distances[cc])
            self.indices1 = self.indices1[len(matches):]
            self.indices2 = self.indices2[len(matches):]
            self.distances = self.distances[len(matches):]


class View:
    """Represents an image used in the reconstruction"""
    def __init__(self, image_path, root_path, data_pos, feature_type='sift'):
        self.name = image_path[image_path.rfind('/') + 1:-4]  # image name without extension
        self.image = cv2.imread(root_path + image_path)  # numpy array of the image
        self.keypoints = []  # list of keypoints obtained from feature extraction
        self.descriptors = []  # list of descriptors obtained from feature extraction
        self.feature_type = feature_type  # feature extraction method
        self.root_path = root_path  # root directory containing the image folder
        R = np.array(Rot.from_quat(data_pos[3:]).as_matrix())  # rotation matrix for the view
        self.R = np.array([[1, 0, 0], [0, 0, -1], [0, 1, 0]]) @ R  # rotate the matrix according to the real world
        self.t = np.array(-self.R @ data_pos[:3])[:, None]  # translation vector for the view
        self.extract_features()
        self.Rs = []
        self.ts = []

    def extract_features(self):
        """Extracts features from the image"""
        if self.feature_type == 'sift':
            detector = cv2.xfeatures2d.SIFT_create()
        elif self.feature_type == 'surf':
            detector = cv2.xfeatures2d.SURF_create()
        elif self.feature_type == 'orb':
            detector = cv2.ORB_create(nfeatures=1500)
        else:
            sys.exit(0)
        self.keypoints, self.descriptors = detector.detectAndCompute(self.image, None)


class SFM:
    """Represents the main reconstruction loop.
       See https://github.com/harish-vnkt/structure-from-motion/blob/master/sfm.py"""
    def __init__(self, views, matches, K, save_path=None, allow_all_matches=True, compare_calculated_Rt_to_real_Rt=True,
                 deg_threshold=10, t_threshold=100, run_id=0):
        self.deg_threshold = deg_threshold
        self.t_threshold = t_threshold
        # if true, for every reconstructed R/T values compare them to the recorded values
        # if the difference is > than the above thresholds, don't allow any matches between the corresponding views
        self.compare_calculated_Rt_to_real_Rt = compare_calculated_Rt_to_real_Rt
        # limit the coordinates to be within the relevant area
        self.area_lim = np.array([[-0.1, 45.5], [-0.1, 31.35], [0., 8.]])
        self.allow_all_matches = allow_all_matches  # if false, only good points will be added
        self.views = views  # list of views
        self.matches = matches  # dictionary of matches
        self.names = []  # image names
        self.done = []  # list of views that have been reconstructed
        self.K = K  # intrinsic matrix
        self.points_3D = np.zeros((0, 3))  # reconstructed 3D points
        self.points_3D_colors = np.zeros((0, 3))  # reconstructed 3D points
        self.point_counter = 0  # keeps track of the reconstructed points
        self.point_map = {}  # a dictionary of the 2D points that contributed to a given 3D point
        self.rev_point_map = {}
        self.errors = []  # list of mean reprojection errors taken at the end of every new view being added
        for view in self.views:
            self.names.append(view.name)
        if save_path == None:  # if no path is specified create one to save the point cloud data in
            if not os.path.exists(self.views[0].root_path + '/run' + str(run_id)):
                os.makedirs(self.views[0].root_path + '/run' + str(run_id))
            if not os.path.exists(self.views[0].root_path + '/run' + str(run_id) + '/points'):
                os.makedirs(self.views[0].root_path + '/run' + str(run_id) + '/points')
            # store results in a root_path/points
            self.results_path = os.path.join(self.views[0].root_path + "/run" + str(run_id), 'points')
        else:
            if not os.path.exists(save_path):
                os.makedirs(save_path)
            if not os.path.exists(save_path + '/points'):
                os.makedirs(save_path + '/points')
            # store results in a root_path/points
            self.results_path = os.path.join(save_path, 'points')

    def get_index_of_view(self, view):
        """Extracts the position of a view in the list of views"""
        return self.names.index(view.name)

    def remove_mapped_points(self, match_object, image_idx):
        """Removes points that have already been reconstructed in the completed views"""
        inliers1 = []
        inliers2 = []
        for i in range(len(match_object.inliers1)):
            if (image_idx, match_object.inliers1[i]) not in self.point_map:
                inliers1.append(match_object.inliers1[i])
                inliers2.append(match_object.inliers2[i])
        match_object.inliers1 = inliers1
        match_object.inliers2 = inliers2

    def compute_pose(self, view1, view2=None, is_baseline=False):
        """Computes the pose of the new view"""
        # procedure for baseline pose estimation
        if is_baseline and view2:
            match_object = self.matches[(view1.name, view2.name)]
            _ = remove_outliers_using_F(view1, view2, match_object)
            rpe1, rpe2 = self.triangulate(view1, view2)
            if rpe1 is not None:
                self.errors.append(np.mean(rpe1))
                self.errors.append(np.mean(rpe2))
            self.done.append(view1)
            self.done.append(view2)
        # procedure for estimating the pose of all other views
        else:
            errors = []
            # reconstruct unreconstructed points from all of the previous views
            for i, old_view in enumerate(self.done):
                try:
                    match_object = self.matches[(old_view.name, view1.name)]
                except KeyError:
                    continue
                F = remove_outliers_using_F(old_view, view1, match_object)
                if F is None:
                    continue
                if self.compare_calculated_Rt_to_real_Rt:
                    E = self.K.T @ F @ self.K
                    R1, R2, t1, t2 = get_camera_from_E(E)  # decompose E
                    if not check_determinant(R1):
                        R1, R2, t1, t2 = get_camera_from_E(-E)
                    R1e = R1 @ old_view.R
                    R2e = R2 @ old_view.R
                    t1e = old_view.t + old_view.R @ t1
                    t2e = old_view.t + old_view.R @ t2
                    deg_error1 = np.rad2deg(np.arccos((np.trace(R1e.T @ view1.R) - 1) / 2))
                    deg_error2 = np.rad2deg(np.arccos((np.trace(R2e.T @ view1.R) - 1) / 2))
                    t_error1 = np.max(np.abs(view1.t - t1e))
                    t_error2 = np.max(np.abs(view1.t - t2e))
                    if np.min([deg_error1, deg_error2]) > self.deg_threshold or np.min([t_error1, t_error2]) >\
                            self.t_threshold:
                        match_object.inliers1 = []
                        match_object.inliers2 = []
                        continue
                _, rpe = self.triangulate(old_view, view1)
                if rpe is None:
                    continue
                errors += rpe
            self.done.append(view1)
            if len(errors) != 0:
                self.errors.append(np.mean(errors))

    def triangulate(self, view1, view2):
        """Triangulates 3D points from two views whose poses have been recovered.
           Also updates the point_map dictionary"""
        K_inv = np.linalg.inv(self.K)
        P1 = np.hstack((view1.R, view1.t))
        P2 = np.hstack((view2.R, view2.t))
        match_object = self.matches[(view1.name, view2.name)]
        pixel_points1, pixel_points2 = get_keypoints_from_indices(keypoints1=view1.keypoints,
                                                                  keypoints2=view2.keypoints,
                                                                  index_list1=match_object.inliers1,
                                                                  index_list2=match_object.inliers2)
        if len(pixel_points1) == 0:
            return None, None
        # Also keep track of one descriptor per 3D point - #
        descriptors1 = np.array(view1.descriptors)[match_object.inliers1]
        # - #
        pixel_points1 = np.append(pixel_points1, np.ones((len(pixel_points1), 1)), axis=1)
        pixel_points2 = np.append(pixel_points2, np.ones((len(pixel_points2), 1)), axis=1)
        reprojection_error1 = []
        reprojection_error2 = []
        for i in range(len(pixel_points1)):
            u1 = pixel_points1[i, :]
            u2 = pixel_points2[i, :]
            u1_normalized = K_inv.dot(u1)
            u2_normalized = K_inv.dot(u2)
            point_3D = get_3D_point(u1_normalized, P1, u2_normalized, P2)
            point_3D_color = view1.image[int(u1[1]), int(u1[0])][::-1]
            col3, col2, col1 = view1.image[int(u1[1]), int(u1[0])]
            col6, col5, col4 = view2.image[int(u2[1]), int(u2[0])]
            error1 = calculate_reprojection_error(point_3D, u1[0:2], self.K, view1.R, view1.t)
            error2 = calculate_reprojection_error(point_3D, u2[0:2], self.K, view2.R, view2.t)
            good_point = True
            # if the error is too large or the point is outside the area, consider it as a bad point
            if error1 > 10 or error2 > 10 or point_3D[0] < self.area_lim[0, 0] or point_3D[0] > self.area_lim[0, 1] or \
                    point_3D[1] < self.area_lim[1, 0] or point_3D[1] > self.area_lim[1, 1] or point_3D[2] < \
                    self.area_lim[2, 0] or point_3D[2] > self.area_lim[2, 1]:
                good_point = False
                if not self.allow_all_matches:
                    continue
            # if the point lies behind the view, consider it as a bad point
            if (P1 @ np.append(point_3D, 1.))[2] < 0:
                good_point = False
                if not self.allow_all_matches:
                    continue
            if (self.get_index_of_view(view1), match_object.inliers1[i]) in self.point_map.keys():
                if (self.get_index_of_view(view2), match_object.inliers2[i]) in self.point_map.keys():
                    continue  # if both points already have existing matches continue
                else:
                    # the point from view 1 is already matched
                    cur_remap_point1, p_status1, *_ = self.point_map[(self.get_index_of_view(view1),
                                                                      match_object.inliers1[i])]
                    if good_point == False or p_status1 == True:
                        # if the new point is bad, or the previous point for view 1 is good, simply
                        # match the 2d point from view 2 to the same previous match of view 1
                        pv, ps, *_ = self.point_map[(self.get_index_of_view(view1), match_object.inliers1[i])]
                        self.point_map[(self.get_index_of_view(view2), match_object.inliers2[i])] = [pv, ps, col4, col5,
                                                                                                     col6]
                    else:  # reassign all 2d points for the previous match of view 1 to the new good point
                        for ckey, cval in self.point_map.items():
                            if cval[0] == cur_remap_point1:
                                self.point_map[ckey][:2] = [self.point_counter, True]
                        self.point_map[(self.get_index_of_view(view2), match_object.inliers2[i])] = [self.point_counter,
                                                                                                     True, col4, col5,
                                                                                                     col6]
                        self.rev_point_map[self.point_counter] = [self.get_index_of_view(view1), True, descriptors1[i]]
                        self.point_counter += 1
                        reprojection_error1.append(error1)
                        reprojection_error2.append(error2)
                        self.points_3D = np.concatenate((self.points_3D, point_3D.T), axis=0)
                        self.points_3D_colors = np.concatenate((self.points_3D_colors, [point_3D_color]), axis=0)
                continue
            if (self.get_index_of_view(view2), match_object.inliers2[i]) in self.point_map.keys():
                continue  # if the point on view 2 is already mapped, continue
            reprojection_error1.append(error1)
            reprojection_error2.append(error2)
            # add the new 3d point to the list and update the point maps
            self.points_3D = np.concatenate((self.points_3D, point_3D.T), axis=0)
            self.points_3D_colors = np.concatenate((self.points_3D_colors, [point_3D_color]), axis=0)
            self.rev_point_map[self.point_counter] = [self.get_index_of_view(view1), good_point, descriptors1[i]]
            # updates point_map with the key (index of view, index of point in the view) and value point_counter
            # multiple keys can have the same value because a 3D point is reconstructed using 2 points
            self.point_map[(self.get_index_of_view(view1), match_object.inliers1[i])] = [self.point_counter, good_point,
                                                                                         col1, col2, col3]
            self.point_map[(self.get_index_of_view(view2), match_object.inliers2[i])] = [self.point_counter, good_point,
                                                                                         col4, col5, col6]
            self.point_counter += 1
        return reprojection_error1, reprojection_error2

    def plot_points(self, name_ad=""):
        """Saves the reconstructed 3D points to ply files using Open3D"""
        number = len(self.done)
        filename = os.path.join(self.results_path, str(number) + '_images' + name_ad + '.ply')
        pcd = o3d.geometry.PointCloud()
        # only save points within the area
        good_points = np.where(
            (self.points_3D[:, 0] >= self.area_lim[0, 0]) * (self.points_3D[:, 0] <= self.area_lim[0, 1]) * (
                        self.points_3D[:, 1] >= self.area_lim[1, 0]) * (self.points_3D[:, 1] <= self.area_lim[1, 1]) * (
                        self.points_3D[:, 2] >= self.area_lim[2, 0]) * (self.points_3D[:, 2] <= self.area_lim[2, 1]))[0]
        pcd.points = o3d.utility.Vector3dVector(self.points_3D[good_points])
        pcd.colors = o3d.utility.Vector3dVector(self.points_3D_colors[good_points].astype(np.float) / 255.0)
        o3d.io.write_point_cloud(filename, pcd)

    def remap_mapped_points(self):
        """ Remap all points so they are numbered from 0 to #points - 1. This only changes the point maps, if 3d points
            without a single match exist. Those 3d points are removed """
        all_points = []
        for key, val in self.point_map.items():
            all_points.append(val[0])
        all_points = np.unique(all_points)
        remap = {cpoint: i for i, cpoint in enumerate(all_points)}
        for key, val in self.point_map.items():
            self.point_map[key][:2] = [remap[val[0]], val[1]]
        point_mask = np.zeros(self.point_counter).astype(bool)
        if len(all_points) != 0:
            point_mask[all_points] = True
        self.points_3D = self.points_3D[point_mask]
        self.points_3D_colors = self.points_3D_colors[point_mask]
        self.point_counter = len(all_points)
        # Take colors as an average over all included points - #
        temp_cols = {pi: [] for pi in range(self.point_counter)}
        for pkey, pval in self.point_map.items():
            temp_cols[pval[0]].append(pval[2:])
        for pi in range(self.point_counter):
            self.points_3D_colors[pi] = np.mean(np.array(temp_cols[pi]), axis=0).astype(int)
        # - #
        # Added for rev_mapped_points - #
        new_rev_point_map = {}
        for key, val in remap.items():
            new_rev_point_map[val] = self.rev_point_map[key]
        for key, val in new_rev_point_map.items():
            if val[0] == -1:
                for key2, val2 in self.point_map.items():
                    if val2[0] == key:
                        new_rev_point_map[key][:2] = [key2[0], False]
                        break
        self.rev_point_map = new_rev_point_map
        # - #

    def remove_double_mapped_points(self):
        """ Removes all 2d points that are mapped to more than 1 3d point. """
        vals_rev = {x: {} for x in range(self.point_counter)}
        for key, val in self.point_map.items():
            try:
                vals_rev[val[0]][key[0]].append(key[1])
            except KeyError:
                vals_rev[val[0]][key[0]] = [key[1]]
        for key, val in vals_rev.items():
            for key2, val2 in val.items():
                if len(val2) > 1:
                    for cur_v in val2:
                        if self.rev_point_map[self.point_map[(key2, cur_v)][0]][0] == key2:
                            self.rev_point_map[self.point_map[(key2, cur_v)][0]][:2] = [-1, False]
                        del self.point_map[(key2, cur_v)]

    def remove_3d_points_with_one_match(self, min_k=2):
        """ Removes all 3d points that have less than the min_k of 2d points mapped to it."""
        vals_rev = {x: {} for x in range(self.point_counter)}
        for key, val in self.point_map.items():
            try:
                vals_rev[val[0]][key[0]].append(key[1])
            except KeyError:
                vals_rev[val[0]][key[0]] = [key[1]]
        for key, val in vals_rev.items():
            if len(val) < min_k:
                self.rev_point_map[key][:2] = [-2, False]
                for key2, val2 in val.items():
                    del self.point_map[(key2, val2[0])]

    def reconstruct(self):
        """ Starts the main reconstruction loop for a given set of views and matches """
        # compute baseline pose
        baseline_view1, baseline_view2 = self.views[0], self.views[1]
        self.compute_pose(view1=baseline_view1, view2=baseline_view2, is_baseline=True)
        for i in range(2, len(self.views)):
            if i % 200 == 0:
                print("Reconstructing %d/%d" % (i, len(self.views)))
            self.compute_pose(view1=self.views[i])


def create_views(data_path, base_img_path, limit=100000, every_xth_image=10, start_v=590, text_file="/13.txt",
                 name_skip=22, use_interpolated_path=None, bad_images_path=None):
    """ Loops through the images and creates an array of views """
    info_file = data_path + text_file
    with open(info_file, "r") as f:
        data_info = f.readlines()
    # obtain the image names and position information from the file
    old_image_names = np.array([x.split(" ")[0].split("/")[1][name_skip:] for x in data_info[:limit]])[start_v:]
    old_data_pos = np.array([x.split("\n")[0].split(" ")[1:] for x in data_info[:limit]]).astype(float)[start_v:]
    image_names = old_image_names[::every_xth_image]
    # if provided, replace the position information with the interpolated position information
    if use_interpolated_path != None:
        data_poses = np.load(use_interpolated_path)
        data_pos = data_poses[start_v:limit:every_xth_image]
    else:
        data_pos = old_data_pos[::every_xth_image]
    # if provided, remove all images marked as bad
    if bad_images_path != None:
        good_imgs = np.where(np.load(bad_images_path)[start_v:limit:every_xth_image] == 1)[0]
        image_names = image_names[good_imgs]
        data_pos = data_pos[good_imgs]
    views = []
    for ci, image_name in enumerate(image_names):
        views.append(View(image_name, base_img_path, data_pos[ci]))
    return views


def create_matches(views, use_spatial_consistency_check=0, use_overlap_criterion=0., K=None):
    """ Computes matches between every possible pair of views and stores them in a dictionary. If the overlap
        criterion is used, only match 2 views, if the specified percentage of points can be seen in both views. """
    if use_overlap_criterion > 0:  # if true, create a 3d grid over the area
        test_coords = np.meshgrid(np.arange(0, 42, 2), np.arange(0, 30, 2), np.arange(0, 2, 4.6))
        test_coords = np.array([test_coords[0].flatten(), test_coords[1].flatten(), test_coords[2].flatten()]).T
        test_coords = np.append(test_coords, np.ones(len(test_coords))[:, None], axis=1)
    matches = {}
    for i in range(0, len(views) - 1):
        if i % 200 == 0:
            print("Creating Matches for %d/%d" % (i, len(views)))
        if use_overlap_criterion > 0:
            e_mat = np.append(views[i].R, views[i].t, axis=1)
            xyz = np.array([K @ e_mat @ rR for rR in test_coords])
            xyz_mask1 = (xyz[:, -1] > 0)
            xyz = xyz / xyz[:, -1, None]
            xyz_mask1 *= (xyz[:, 0] > 0) * (xyz[:, 0] < 640) * (xyz[:, 1] > 0) * (xyz[:, 1] < 480)
        for j in range(i+1, len(views)):
            if use_overlap_criterion > 0:
                e_mat = np.append(views[j].R, views[j].t, axis=1)
                xyz = np.array([K @ e_mat @ rR for rR in test_coords])
                xyz_mask2 = (xyz[:, -1] > 0)
                xyz = xyz / xyz[:, -1, None]
                xyz_mask2 *= (xyz[:, 0] > 0) * (xyz[:, 0] < 640) * (xyz[:, 1] > 0) * (xyz[:, 1] < 480)
                if np.sum(xyz_mask1 * xyz_mask2) / np.minimum(np.sum(xyz_mask1), np.sum(xyz_mask2)) < use_overlap_criterion:
                    continue
            matches[(views[i].name, views[j].name)] = Match(views[i], views[j], use_spatial_consistency_check)
    return matches


def rotate(points, rot_vecs):
    """ Rotate points by given rotation vectors. Rodrigues' rotation formula is used. """
    theta = np.linalg.norm(rot_vecs, axis=1)[:, np.newaxis]
    with np.errstate(invalid='ignore'):
        v = rot_vecs / theta
        v = np.nan_to_num(v)
    dot = np.sum(points * v, axis=1)[:, np.newaxis]
    cos_theta = np.cos(theta)
    sin_theta = np.sin(theta)
    return cos_theta * points + sin_theta * np.cross(v, points) + dot * (1 - cos_theta) * v


def project(points, camera_params, intrinsic_k):
    """Convert 3-D points to 2-D by projecting onto images."""
    points_proj = rotate(points, camera_params[:, :3])
    points_proj += camera_params[:, 3:6]
    # Prevent least squares to fit a point behind the views by dislocating them
    additional_cost = np.minimum(1e9 * points_proj[:, 2], 0)  # points behind the view have negative values in z
    points_proj = points_proj[:, :2] / points_proj[:, 2, np.newaxis]
    f1 = intrinsic_k[0]
    f2 = intrinsic_k[1]
    k1 = intrinsic_k[2]
    k2 = intrinsic_k[3]
    # edit for k1, k2 as shift params
    f_s = np.vstack((f1, f2)).T
    k_s = np.vstack((k1, k2)).T
    points_proj = f_s * points_proj + k_s
    return points_proj + additional_cost[:, None]


def fun_no_K_all_E(params, n_cameras, n_points, camera_indices, point_indices, points_2d, intrinsic_k):
    """Compute residuals.

    `params` contains camera parameters and 3-D coordinates.
    """
    camera_params = params[:n_cameras * 6].reshape((n_cameras, 6))
    points_3d = params[n_cameras * 6:].reshape((n_points, 3))
    points_proj = project(points_3d[point_indices], camera_params[camera_indices], intrinsic_k)
    return (points_proj - points_2d).ravel()


def bundle_adjustment_sparsity_no_K_all_E(n_cameras, n_points, camera_indices, point_indices):
    """ Creates and returns a sparsity matrix for the bundle adjustment. """
    m = camera_indices.size * 2
    n = n_cameras * 6 + n_points * 3
    A = lil_matrix((m, n), dtype=int)
    i = np.arange(camera_indices.size)
    for s in range(6):
        A[2 * i, camera_indices * 6 + s] = 1
        A[2 * i + 1, camera_indices * 6 + s] = 1
    for s in range(3):
        A[2 * i, n_cameras * 6 + point_indices * 3 + s] = 1
        A[2 * i + 1, n_cameras * 6 + point_indices * 3 + s] = 1
    return A


def fun_no_E_no_K(params, camera_params, intrinsic_k, n_cameras, n_points, camera_indices, point_indices, points_2d):
    """Compute residuals.

    `params` contains 3-D coordinates.
    """
    camera_params = camera_params.reshape((n_cameras, 6))
    points_3d = params.reshape((n_points, 3))
    points_proj = project(points_3d[point_indices], camera_params[camera_indices], intrinsic_k)
    return (points_proj - points_2d).ravel()


def bundle_adjustment_sparsity_no_E_no_K(n_points, camera_indices, point_indices):
    """ Creates and returns a sparsity matrix for the bundle adjustment. """
    m = camera_indices.size * 2
    n = n_points * 3
    A = lil_matrix((m, n), dtype=int)
    i = np.arange(camera_indices.size)
    for s in range(3):
        A[2 * i, point_indices * 3 + s] = 1
        A[2 * i + 1, point_indices * 3 + s] = 1
    return A


def run_ba_no_E_no_K(sfm1, points_3d, views, use_bounds=False, bounds_xyz=(-1., 43., -1., 32., -1., 8.),
                     pos_3d_adjustment_error_limit=20):
    """ Runs bundle adjustment for 3d points only. """
    points_2d = []
    camera_indices = []
    point_indices = []
    sorted_keys = sorted(sfm1.point_map.items(), key=lambda x: x[1][0])
    camera_params = []
    for key, val in sorted_keys:
        camera_indices.append(key[0])
        point_indices.append(val[0])
        points_2d.append(views[key[0]].keypoints[key[1]].pt)
    for view in views:
        cur_R = Rot.from_matrix(view.R).as_rotvec()
        cur_t = view.t
        camera_params.append(np.hstack((cur_R, cur_t.flatten())))
    points_2d = np.array(points_2d)
    camera_indices = np.array(camera_indices)
    point_indices = np.array(point_indices)
    n_cameras = len(camera_params)
    camera_params = np.array(camera_params).ravel()
    n_points = points_3d.shape[0]
    x0 = points_3d.ravel()
    intrinsic_k = np.array([K[0, 0], K[1, 1], K[0, 2], K[1, 2]])
    A = bundle_adjustment_sparsity_no_E_no_K(n_points, camera_indices, point_indices)
    if use_bounds:
        bounds = np.zeros((len(x0), 2))
        bounds[0::3, 0] = bounds_xyz[0]
        bounds[1::3, 0] = bounds_xyz[2]
        bounds[2::3, 0] = bounds_xyz[4]
        bounds[0::3, 1] = bounds_xyz[1]
        bounds[1::3, 1] = bounds_xyz[3]
        bounds[2::3, 1] = bounds_xyz[5]
        x0[x0 < bounds[:, 0]] = bounds[x0 < bounds[:, 0], 0]
        x0[x0 > bounds[:, 1]] = bounds[x0 > bounds[:, 1], 1]
        res = least_squares(fun_no_E_no_K, x0, bounds=bounds.T, jac_sparsity=A, verbose=1, x_scale='jac', ftol=1e-4,
                            method='trf',
                            args=(
                            camera_params, intrinsic_k, n_cameras, n_points, camera_indices, point_indices, points_2d))
    else:
        res = least_squares(fun_no_E_no_K, x0, jac_sparsity=A, verbose=1, x_scale='jac', ftol=1e-4,
                            method='trf',
                            args=(
                            camera_params, intrinsic_k, n_cameras, n_points, camera_indices, point_indices, points_2d))
    to_remove = np.unique((np.where(np.abs(res.fun) > pos_3d_adjustment_error_limit)[0] / 2.).astype(int))
    remove_dict = {p: np.where(point_indices == p)[0] for p in np.unique(point_indices[to_remove])}
    new_to_remove = []
    for key, val in remove_dict.items():
        max_error = np.argmax(np.sum(np.abs(res.fun[2*val[:, None] + np.array([[0, 1]])]), axis=1))
        new_to_remove.append(val[max_error])
    to_remove = np.array(new_to_remove)
    to_del = []
    for tr in to_remove:
        ci = camera_indices[tr]
        pi = point_indices[tr]
        for key, val in sfm1.point_map.items():
            if key[0] == ci and val[0] == pi:
                to_del.append(key)
    for td in to_del:
        del sfm1.point_map[td]
    return res.x.reshape((n_points, 3)), len(to_remove)


def run_ba_final_no_k(sfm1, points_3d, camera_params, views, intrinsic_k, use_bounds=False,
                      bounds_xyz=(-1., 43., -1., 32., -1., 8.), std_lim=10, bounds_trans=0., bounds_rots=0.,
                      start_x0=None):
    """ Runs bundle adjustment for 3d points and extrinsic camera params. """
    points_2d = []
    camera_indices = []
    point_indices = []
    sorted_keys = sorted(sfm1.point_map.items(), key=lambda x: x[1][0])
    for key, val in sorted_keys:
        camera_indices.append(key[0])
        point_indices.append(val[0])
        points_2d.append(views[key[0]].keypoints[key[1]].pt)
    points_2d = np.array(points_2d)
    camera_indices = np.array(camera_indices)
    point_indices = np.array(point_indices)
    n_cameras = len(camera_params)
    n_points = points_3d.shape[0]
    x0 = np.hstack((camera_params.ravel(), points_3d.ravel()))
    A = bundle_adjustment_sparsity_no_K_all_E(n_cameras, n_points, camera_indices, point_indices)
    if use_bounds:
        bounds = np.zeros((len(x0), 2))
        if bounds_trans != 0:
            bounds[:n_cameras * 6:6, 0] = start_x0[:n_cameras * 6:6] - bounds_trans * np.abs(start_x0[:n_cameras * 6:6])
            bounds[:n_cameras * 6:6, 1] = start_x0[:n_cameras * 6:6] + bounds_trans * np.abs(start_x0[:n_cameras * 6:6])
            bounds[1:n_cameras * 6:6, 0] = start_x0[1:n_cameras * 6:6] - bounds_trans * np.abs(start_x0[1:n_cameras * 6:6])
            bounds[1:n_cameras * 6:6, 1] = start_x0[1:n_cameras * 6:6] + bounds_trans * np.abs(start_x0[1:n_cameras * 6:6])
            bounds[2:n_cameras * 6:6, 0] = start_x0[2:n_cameras * 6:6] - bounds_trans * np.abs(start_x0[2:n_cameras * 6:6])
            bounds[2:n_cameras * 6:6, 1] = start_x0[2:n_cameras * 6:6] + bounds_trans * np.abs(start_x0[2:n_cameras * 6:6])
        else:
            bounds[:n_cameras * 6:6, 0] = -np.inf
            bounds[:n_cameras * 6:6, 1] = np.inf
            bounds[1:n_cameras * 6:6, 0] = -np.inf
            bounds[1:n_cameras * 6:6, 1] = np.inf
            bounds[2:n_cameras * 6:6, 0] = -np.inf
            bounds[2:n_cameras * 6:6, 1] = np.inf
        if bounds_rots != 0:
            bounds[3:n_cameras * 6:6, 0] = start_x0[3:n_cameras * 6:6] - bounds_rots * np.abs(start_x0[3:n_cameras * 6:6])
            bounds[3:n_cameras * 6:6, 1] = start_x0[3:n_cameras * 6:6] + bounds_rots * np.abs(start_x0[3:n_cameras * 6:6])
            bounds[4:n_cameras * 6:6, 0] = start_x0[4:n_cameras * 6:6] - bounds_rots * np.abs(start_x0[4:n_cameras * 6:6])
            bounds[4:n_cameras * 6:6, 1] = start_x0[4:n_cameras * 6:6] + bounds_rots * np.abs(start_x0[4:n_cameras * 6:6])
            bounds[5:n_cameras * 6:6, 0] = start_x0[5:n_cameras * 6:6] - bounds_rots * np.abs(start_x0[5:n_cameras * 6:6])
            bounds[5:n_cameras * 6:6, 1] = start_x0[5:n_cameras * 6:6] + bounds_rots * np.abs(start_x0[5:n_cameras * 6:6])
        else:
            bounds[3:n_cameras * 6:6, 0] = -np.inf
            bounds[3:n_cameras * 6:6, 1] = np.inf
            bounds[4:n_cameras * 6:6, 0] = -np.inf
            bounds[4:n_cameras * 6:6, 1] = np.inf
            bounds[5:n_cameras * 6:6, 0] = -np.inf
            bounds[5:n_cameras * 6:6, 1] = np.inf
        bounds[n_cameras * 6::3, 0] = bounds_xyz[0]
        bounds[n_cameras * 6 + 1::3, 0] = bounds_xyz[2]
        bounds[n_cameras * 6 + 2::3, 0] = bounds_xyz[4]
        bounds[n_cameras * 6::3, 1] = bounds_xyz[1]
        bounds[n_cameras * 6 + 1::3, 1] = bounds_xyz[3]
        bounds[n_cameras * 6 + 2::3, 1] = bounds_xyz[5]
        x0[x0 < bounds[:, 0]] = bounds[x0 < bounds[:, 0], 0]
        x0[x0 > bounds[:, 1]] = bounds[x0 > bounds[:, 1], 1]
        res = least_squares(fun_no_K_all_E, x0, bounds=bounds.T, jac_sparsity=A, verbose=1, x_scale='jac', ftol=1e-4, method='trf',
                            args=(n_cameras, n_points, camera_indices, point_indices, points_2d, intrinsic_k))
    else:
        res = least_squares(fun_no_K_all_E, x0, jac_sparsity=A, verbose=1, x_scale='jac', ftol=1e-4, method='trf',
                            args=(n_cameras, n_points, camera_indices, point_indices, points_2d, intrinsic_k))
    if np.quantile(np.abs(res.fun), 0.99) < 1:
        to_remove = np.unique((np.where(np.abs(res.fun) > 2)[0] / 2.).astype(int))
    else:
        to_remove = np.unique((np.where(np.abs(res.fun) > std_lim * np.std(res.fun))[0]/2.).astype(int))
    remove_dict = {p: to_remove[point_indices[to_remove] == p] for p in np.unique(point_indices[to_remove])}
    new_to_remove = []
    for key, val in remove_dict.items():
        max_error = np.argmax(np.sum(np.abs(res.fun[2*val[:, None] + np.array([[0, 1]])]), axis=1))
        new_to_remove.append(val[max_error])
    to_remove = np.array(new_to_remove)
    to_del = []
    for tr in to_remove:
        ci = camera_indices[tr]
        pi = point_indices[tr]
        for key, val in sfm1.point_map.items():
            if key[0] == ci and val[0] == pi:
                to_del.append(key)
    for td in to_del:
        del sfm1.point_map[td]
    return res.x[:n_cameras * 6].reshape((n_cameras, 6)), res.x[n_cameras * 6:].reshape((n_points, 3)), len(to_remove)


def gibbs_separate(sfm1, points_3d, views, use_bounds=True, bounds_xyz=np.array([-0.1, 45.5, -0.1, 31.35, 0., 8.]),
                   gibbs_separation_limit=10, gibbs_improvement_factor=2.):
    """ Uses the described "gibbs separate method" to remove bad matches. """
    points_2d = []
    camera_indices = []
    point_indices = []
    sorted_keys = sorted(sfm1.point_map.items(), key=lambda x: x[1][0])
    camera_params = []
    for key, val in sorted_keys:
        camera_indices.append(key[0])
        point_indices.append(val[0])
        points_2d.append(views[key[0]].keypoints[key[1]].pt)
    for view in views:
        cur_R = Rot.from_matrix(view.R).as_rotvec()
        cur_t = view.t
        camera_params.append(np.hstack((cur_R, cur_t.flatten())))
    points_2d = np.array(points_2d)
    camera_indices = np.array(camera_indices)
    point_indices = np.array(point_indices)
    n_cameras = len(camera_params)
    camera_params = np.array(camera_params).ravel()
    n_points = points_3d.shape[0]
    x0 = points_3d.ravel()
    intrinsic_k = np.array([K[0, 0], K[1, 1], K[0, 2], K[1, 2]])
    A = bundle_adjustment_sparsity_no_E_no_K(n_points, camera_indices, point_indices)
    if use_bounds:
        bounds = np.zeros((len(x0), 2))
        bounds[0::3, 0] = bounds_xyz[0]
        bounds[1::3, 0] = bounds_xyz[2]
        bounds[2::3, 0] = bounds_xyz[4]
        bounds[0::3, 1] = bounds_xyz[1]
        bounds[1::3, 1] = bounds_xyz[3]
        bounds[2::3, 1] = bounds_xyz[5]
        x0[x0 < bounds[:, 0]] = bounds[x0 < bounds[:, 0], 0]
        x0[x0 > bounds[:, 1]] = bounds[x0 > bounds[:, 1], 1]
        res = least_squares(fun_no_E_no_K, x0, bounds=bounds.T, jac_sparsity=A, verbose=0, x_scale='jac', ftol=1e-4,
                            method='trf',
                            args=(
                            camera_params, intrinsic_k, n_cameras, n_points, camera_indices, point_indices, points_2d))
    else:
        res = least_squares(fun_no_E_no_K, x0, jac_sparsity=A, verbose=0, x_scale='jac', ftol=1e-4,
                            method='trf',
                            args=(
                            camera_params, intrinsic_k, n_cameras, n_points, camera_indices, point_indices, points_2d))
    to_remove = np.unique((np.where(np.abs(res.fun) > gibbs_separation_limit)[0] / 2.).astype(int))
    cor_3d_points = point_indices[to_remove]
    un_cor = np.unique(cor_3d_points)
    bounds1 = np.zeros((3, 2))
    bounds1[0, 0] = bounds_xyz[0]
    bounds1[1, 0] = bounds_xyz[2]
    bounds1[2, 0] = bounds_xyz[4]
    bounds1[0, 1] = bounds_xyz[1]
    bounds1[1, 1] = bounds_xyz[3]
    bounds1[2, 1] = bounds_xyz[5]
    to_remove = []
    for cucc, ucc in enumerate(un_cor):
        if cucc % 500 == 0:
            print("%d/%d" % (cucc, len(un_cor)))
        x1 = points_3d[ucc]
        points_2d1 = points_2d[np.where(point_indices == ucc)[0]]
        n_points1 = 1
        camera_indices1 = camera_indices[np.where(point_indices == ucc)[0]]
        point_indices1 = np.zeros(len(camera_indices1) - 1).astype(int)
        rev_pi = (np.where(point_indices == ucc)[0]*2).astype(int)
        start_errors = res.fun[np.insert(rev_pi + 1,  np.arange(len(rev_pi)), rev_pi)]
        p_mask = np.ones(len(points_2d1)).astype(bool)
        error_mask = np.ones(len(start_errors)).astype(bool)
        error_improvements = []
        for pi in range(len(p_mask)):
            p_mask[pi - 1] = True
            p_mask[pi] = False
            error_mask[(pi-1) * 2] = True
            error_mask[(pi-1) * 2 + 1] = True
            error_mask[pi * 2] = False
            error_mask[pi * 2 + 1] = False
            rev_errors = start_errors[error_mask]
            A1 = bundle_adjustment_sparsity_no_E_no_K(n_points1, camera_indices1[p_mask], point_indices1)
            res1 = least_squares(fun_no_E_no_K, x1, bounds=bounds1.T, jac_sparsity=A1, verbose=0, x_scale='jac', ftol=1e-4,
                                 method='trf',
                                 args=(
                                    camera_params, intrinsic_k, n_cameras, n_points1, camera_indices1[p_mask], point_indices1,
                                    points_2d1[p_mask]))
            error_improvements.append(np.sum(np.abs(rev_errors - res1.fun)))
        best_improve_ind = np.argmax(error_improvements)
        if error_improvements[best_improve_ind] > gibbs_improvement_factor * np.sort(error_improvements)[-2]:
            to_remove.append(np.where(point_indices == ucc)[0][best_improve_ind])
    to_remove = np.array(to_remove)
    print("Removing: %d" % len(to_remove))
    to_del = []
    for tr in to_remove:
        ci = camera_indices[tr]
        pi = point_indices[tr]
        for key, val in sfm1.point_map.items():
            if key[0] == ci and val[0] == pi:
                to_del.append(key)
    for td in to_del:
        del sfm1.point_map[td]


def cluster_remove(rep_errors, remove_dict):
    """ Separates corresponding matches for 3d points into 2 groups each. """
    to_remove = []
    for key, val in remove_dict.items():
        cor_2d = np.array([rep_errors[2 * x:2 * x + 2] for x in val])
        kmeans = KMeans(n_clusters=2, random_state=0).fit(cor_2d)
        l_to_remove = (len(cor_2d)/2 - np.sum(kmeans.labels_ == 0) < 0) + 0.
        to_remove.extend(val[kmeans.labels_ == l_to_remove])
    return np.array(to_remove)


def cluster_separate(sfm1, points_3d, views, use_bounds=True, bounds_xyz=np.array([-0.1, 45.5, -0.1, 31.35, 0., 8.]),
                     cluster_separation_limit=30):
    """ Uses the described "cluster separate method" to remove bad matches. """
    points_2d = []
    camera_indices = []
    point_indices = []
    sorted_keys = sorted(sfm1.point_map.items(), key=lambda x: x[1][0])
    camera_params = []
    for key, val in sorted_keys:
        camera_indices.append(key[0])
        point_indices.append(val[0])
        points_2d.append(views[key[0]].keypoints[key[1]].pt)
    for view in views:
        cur_R = Rot.from_matrix(view.R).as_rotvec()
        cur_t = view.t
        camera_params.append(np.hstack((cur_R, cur_t.flatten())))
    points_2d = np.array(points_2d)
    camera_indices = np.array(camera_indices)
    point_indices = np.array(point_indices)
    n_cameras = len(camera_params)
    camera_params = np.array(camera_params).ravel()
    n_points = points_3d.shape[0]
    x0 = points_3d.ravel()
    intrinsic_k = np.array([K[0, 0], K[1, 1], K[0, 2], K[1, 2]])
    A = bundle_adjustment_sparsity_no_E_no_K(n_points, camera_indices, point_indices)
    if use_bounds:
        bounds = np.zeros((len(x0), 2))
        bounds[0::3, 0] = bounds_xyz[0]
        bounds[1::3, 0] = bounds_xyz[2]
        bounds[2::3, 0] = bounds_xyz[4]
        bounds[0::3, 1] = bounds_xyz[1]
        bounds[1::3, 1] = bounds_xyz[3]
        bounds[2::3, 1] = bounds_xyz[5]
        x0[x0 < bounds[:, 0]] = bounds[x0 < bounds[:, 0], 0]
        x0[x0 > bounds[:, 1]] = bounds[x0 > bounds[:, 1], 1]
        res = least_squares(fun_no_E_no_K, x0, bounds=bounds.T, jac_sparsity=A, verbose=0, x_scale='jac', ftol=1e-4,
                            method='trf',
                            args=(
                            camera_params, intrinsic_k, n_cameras, n_points, camera_indices, point_indices, points_2d))
    else:
        res = least_squares(fun_no_E_no_K, x0, jac_sparsity=A, verbose=0, x_scale='jac', ftol=1e-4,
                            method='trf',
                            args=(
                            camera_params, intrinsic_k, n_cameras, n_points, camera_indices, point_indices, points_2d))
    # New remove method - #
    to_remove = np.unique((np.where(np.abs(res.fun) > cluster_separation_limit)[0] / 2.).astype(int))
    remove_dict = {p: np.where(point_indices == p)[0] for p in np.unique(point_indices[to_remove])}
    cluster_2d_points = cluster_remove(res.fun, remove_dict)
    if len(cluster_2d_points) == 0:
        return points_3d, 0
    cluster_3d_points = point_indices[cluster_2d_points]
    cur_num_points = sfm1.point_counter
    for cb, b3d in enumerate(np.unique(cluster_3d_points)):
        to_remap = cluster_2d_points[np.where(cluster_3d_points == b3d)[0]]
        cur_view = sorted_keys[to_remap[0]][0]
        cur_desc = views[cur_view[0]].descriptors[cur_view[1]]
        cur_col = views[cur_view[0]].image[int(views[cur_view[0]].keypoints[cur_view[1]].pt[1]),
                                           int(views[cur_view[0]].keypoints[cur_view[1]].pt[0])][::-1]
        sfm1.rev_point_map[cur_num_points + cb] = [cur_view[0], True, np.copy(cur_desc)]
        for tr in to_remap:
            sfm1.point_map[sorted_keys[tr][0]][0] = cur_num_points + cb
        sfm1.points_3D = np.vstack([sfm1.points_3D, np.zeros((1, 3))])
        sfm1.points_3D_colors = np.vstack([sfm1.points_3D_colors, np.copy(cur_col).reshape((1, 3))])
    sfm1.point_counter += len(np.unique(cluster_3d_points))
    for val in range(cur_num_points, cur_num_points + len(np.unique(cluster_3d_points))):
        cE = np.hstack((views[sfm1.rev_point_map[val][0]].R, views[sfm1.rev_point_map[val][0]].t))
        relevant_bounds = np.array([0, 2, 4]) + (cE[2, :3] > 0).astype(int)
        relevant_bounds = bounds_xyz[relevant_bounds]
        relevant_bounds[cE[2, :3] > 0] -= 1
        relevant_bounds[cE[2, :3] <= 0] += bounds_xyz[-2]
        cur_fac = np.min(((relevant_bounds - (np.linalg.inv(-cE[:, :3]) @ cE[:, 3])) / cE[2, :3])[:2])
        sfm1.points_3D[val] = (np.linalg.inv(-cE[:, :3]) @ cE[:, 3]) + cur_fac * cE[2, :3]
        if sfm1.points_3D[val][2] < 0:
            sfm1.points_3D[val][2] = 0.
    points_3d = np.vstack([points_3d, sfm1.points_3D[-len(np.unique(cluster_3d_points)):]])
    return points_3d, len(cluster_2d_points)


def separate_behind_points(sfm1, points_3d, views, bounds_xyz=np.array([-0.1, 45.5, -0.1, 31.35, 0., 8.])):
    """ Sets any points, that are behind a view, in front of it. """
    points_2d = []
    camera_indices = []
    point_indices = []
    sorted_keys = sorted(sfm1.point_map.items(), key=lambda x: x[1][0])
    camera_params = []
    for key, val in sorted_keys:
        camera_indices.append(key[0])
        point_indices.append(val[0])
        points_2d.append(views[key[0]].keypoints[key[1]].pt)
    for view in views:
        cur_R = Rot.from_matrix(view.R).as_rotvec()
        cur_t = view.t
        camera_params.append(np.hstack((cur_R, cur_t.flatten())))
    points_2d = np.array(points_2d)
    camera_indices = np.array(camera_indices)
    point_indices = np.array(point_indices)
    n_cameras = len(camera_params)
    camera_params = np.array(camera_params).ravel()
    n_points = points_3d.shape[0]
    x0 = points_3d.ravel()
    intrinsic_k = np.array([K[0, 0], K[1, 1], K[0, 2], K[1, 2]])
    f0 = fun_no_E_no_K(x0, camera_params, intrinsic_k, n_cameras, n_points, camera_indices, point_indices, points_2d)
    behind_2d_points = (np.where(np.abs(f0) > 1e6)[0]/2.).astype(int)
    if len(behind_2d_points) == 0:
        return points_3d, 0
    behind_3d_points = point_indices[behind_2d_points]
    cur_num_points = sfm1.point_counter
    for cb, b3d in enumerate(np.unique(behind_3d_points)):
        to_remap = behind_2d_points[np.where(behind_3d_points == b3d)[0]]
        cur_view = sorted_keys[to_remap[0]][0]
        cur_desc = views[cur_view[0]].descriptors[cur_view[1]]
        cur_col = views[cur_view[0]].image[int(views[cur_view[0]].keypoints[cur_view[1]].pt[1]),
                                           int(views[cur_view[0]].keypoints[cur_view[1]].pt[0])][::-1]
        sfm1.rev_point_map[cur_num_points + cb] = [cur_view[0], True, np.copy(cur_desc)]
        for tr in to_remap:
            sfm1.point_map[sorted_keys[tr][0]][0] = cur_num_points + cb
        sfm1.points_3D = np.vstack([sfm1.points_3D, np.zeros((1, 3))])
        sfm1.points_3D_colors = np.vstack([sfm1.points_3D_colors, np.copy(cur_col).reshape((1, 3))])
    sfm1.point_counter += len(np.unique(behind_3d_points))
    for val in range(cur_num_points, cur_num_points + len(np.unique(behind_3d_points))):
        cE = np.hstack((views[sfm1.rev_point_map[val][0]].R, views[sfm1.rev_point_map[val][0]].t))
        relevant_bounds = np.array([0, 2, 4]) + (cE[2, :3] > 0).astype(int)
        relevant_bounds = bounds_xyz[relevant_bounds]
        relevant_bounds[cE[2, :3] > 0] -= 1
        relevant_bounds[cE[2, :3] <= 0] += bounds_xyz[-2]
        cur_fac = np.min(((relevant_bounds - (np.linalg.inv(-cE[:, :3]) @ cE[:, 3])) / cE[2, :3])[:2])
        sfm1.points_3D[val] = (np.linalg.inv(-cE[:, :3]) @ cE[:, 3]) + cur_fac * cE[2, :3]
        if sfm1.points_3D[val][2] < 0:
            sfm1.points_3D[val][2] = 0.
    points_3d = np.vstack([points_3d, sfm1.points_3D[-len(np.unique(behind_3d_points)):]])
    return points_3d, len(behind_2d_points)


# !! The following numbers and paths need to be adjusted to your setup !! --------------------------------- #
name_skip = 3  # length of the string (in the text file) before the actual image name
text_file = "/11_12.txt"  # text file with the frame names/ translation values / quaternions
data_path = "..."  # path with all relevant files
use_interpolated_path = data_path + "/11_12_interp_0.0010_1.0000_4deg_cor.npy"  # None for not using interpolated gt
bad_images_path = data_path + "/frames_to_use_up_to_41500_visual_check_every_50th_image.npy"  # None for not excluding any frames
run_id = 8  # use any id (if it already exists the content will be replaced)
save_path_base = ".../sfm_results/run" + str(run_id) + "/p%d"  # path to save the created files
base_img_path = data_path + "/11_12_uwb_040321_abs4_images_50/"  # base path for the corresponding images
# --------------------------------------------------------------------------------------------------------- #


time_save_file_path_base = save_path_base + "/time_info_"  # file to save timing information
params_save_file_path_base = save_path_base + "/params_info.txt"  # file to write the parameters in
# lists the names of the parameters
param_names = ["start_view", "end_view", "step_size", "std_lim", "min_matches_per_point",
               "reset_points_for_final_adjustment", "spatial_consistency_check", "overlap_criterion",
               "separation_limits", "gibbs_improvement_factor"]
start_views = [0]  # 590
end_views = [41550] # 6840
step_sizes = [50]  # 5
std_lim_globs = [(3, 4), (4, 4), (5, 4)]  # (4, 4)
K = np.array([[548.44934818, 0., 317.73762648],
              [0., 549.17600512, 249.00614224],
              [0., 0., 1.]])
use_camera_pos_shift = False  # False # Should have a rather minor effect
# if True, place all 3d points in the middle of their corresponding first view (projected onto the next wall)
reset_all_points = True
save_all_descriptors = True  # if True, save the descriptors of all corresponding 2d points for every 3d point
min_matches_per_point_singles = [3, 4, 5]  # minimal number of matches necessary to keep a 3d point
# if True, the below bounds will be used for sfm/bundle adjustment. Only 3d points within the bounds
# will be saved in the point cloud
use_bounds = True
bounds_xyz = np.array([-0.1, 45.5, -0.1, 31.35, 0., 8.])
bounds_trans = 0.01  # allowed deviation from the original recorded positions # Set to 0 to not use them
bounds_rots = 0.01  # allowed deviation from the original recorded rotations # Set to 0 to not use them
# if True, reset 3d point values before the final adjustment (same reset method as reset_all_points)
reset_points_for_final_adjustments = [True, False]
use_spatial_consistency_checks = [0, 5, 7]  # value for spatial consistency check. if 0 no check is used
use_overlap_criterions = [0.2, 0.3, 0.4]  # value for overlap criterion. if 0 no no overlap criterion is used
# values for the different separation methods
separation_limits = [(40, 30, 30), (40, 30, 20), (40, 30, 10),
                     (40, 20, 30), (40, 20, 20), (40, 20, 10), (40, 10, 30), (40, 10, 20), (40, 10, 10),
                     (30, 30, 30), (30, 30, 20), (30, 30, 10),
                     (30, 20, 30), (30, 20, 20), (30, 20, 10), (30, 10, 30), (30, 10, 20), (30, 10, 10),
                     (20, 20, 20), (20, 20, 10), (20, 10, 20), (20, 10, 10)]
gibbs_improvement_factors = [2.]  # factor
all_params = list(itertools.product(start_views, end_views, step_sizes, std_lim_globs, min_matches_per_point_singles,
                                    reset_points_for_final_adjustments, use_spatial_consistency_checks,
                                    use_overlap_criterions, separation_limits, gibbs_improvement_factors))


def run_process(j, views=None):
    save_path = save_path_base % j
    if not os.path.exists(save_path):
        os.makedirs(save_path)
        print("-------------------- Dealing with: %d --------------------" % j)
    else:
        print("-------------------- Skipped: %d Already exists --------------------" % j)
        return
    time_save_file_path = (time_save_file_path_base % j) + str(int(time.time() * 1000)) + ".txt"
    params_save_file_path = params_save_file_path_base % j
    # Read current params -- #
    start_view = all_params[j][0]
    end_view = all_params[j][1]
    step_size = all_params[j][2]
    std_lim = np.copy(all_params[j][3][0])
    reduce_std_lim_to = all_params[j][3][1]
    min_matches_per_point_single = all_params[j][4]
    reset_points_for_final_adjustment = all_params[j][5]
    use_spatial_consistency_check = all_params[j][6]
    use_overlap_criterion = all_params[j][7]
    cluster_separation_limit = all_params[j][8][0]
    gibbs_separation_limit = all_params[j][8][1]
    pos_3d_adjustment_error_limit = all_params[j][8][2]
    gibbs_improvement_factor = all_params[j][9]
    # -- #
    # Save current params -- #
    with open(params_save_file_path, "w") as f:
        for cpi, cpname in enumerate(param_names):
            f.write("%s: \t %s \n" % (cpname, all_params[j][cpi]))
    # -- #
    t1 = time.time()
    print("Creating Views")
    if views == None:
        views = create_views(data_path, base_img_path, limit=end_view, every_xth_image=step_size,
                             start_v=start_view, text_file=text_file, name_skip=name_skip,
                             use_interpolated_path=use_interpolated_path, bad_images_path=bad_images_path)
    print("%d views created" % len(views))
    t2 = time.time()
    with open(time_save_file_path, "w") as f:
        f.write("Views creation:\t %.2f \n" % (t2-t1))
    print("Creating matches")
    if use_overlap_criterion != 0:
        matches = create_matches(views, use_spatial_consistency_check, use_overlap_criterion, K)
    else:
        matches = create_matches(views, use_spatial_consistency_check)
    t3 = time.time()
    with open(time_save_file_path, "a") as f:
        f.write("Matches creation:\t %.2f \n" % (t3-t2))
    sfm = SFM(views, matches, K, run_id=run_id, save_path=save_path)
    print("Starting reconstruction")
    sfm.reconstruct()
    sfm.remove_double_mapped_points()
    sfm.remove_3d_points_with_one_match(min_k=min_matches_per_point_single)
    sfm.remap_mapped_points()
    print("Reconstruction done")
    t4 = time.time()
    with open(time_save_file_path, "a") as f:
        f.write("Reconstruction:\t %.2f \n" % (t4-t3))
    # Adjust camera pos with real data shift
    if use_camera_pos_shift:
        for counter_view, view in enumerate(views):
            add_t = (view.R[2, :] * 0.085 + view.R[0, :] * 0.045)[:, None]
            view.t = view.t + (-view.R @ add_t)
    points_3d = sfm.points_3D
    # Reset points to be in front of their corresponding views
    corrected_points = 0
    for val in range(sfm.point_counter):
        if reset_all_points or not sfm.rev_point_map[val][1]:
            corrected_points += 1
            cE = np.hstack((views[sfm.rev_point_map[val][0]].R, views[sfm.rev_point_map[val][0]].t))
            relevant_bounds = np.array([0, 2, 4]) + (cE[2, :3] > 0).astype(int)
            relevant_bounds = bounds_xyz[relevant_bounds]
            relevant_bounds[cE[2, :3] > 0] -= 1
            relevant_bounds[cE[2, :3] <= 0] += bounds_xyz[-2]
            cur_fac = np.min(((relevant_bounds - (np.linalg.inv(-cE[:, :3]) @ cE[:, 3])) / cE[2, :3])[:2])
            points_3d[val] = (np.linalg.inv(-cE[:, :3]) @ cE[:, 3]) + cur_fac*cE[2, :3]
            if points_3d[val][2] < 0:
                points_3d[val][2] = 0.
    t5 = time.time()
    with open(time_save_file_path, "a") as f:
        f.write("Point preparation :\t %.2f \n" % (t5-t4))
    # Added for separating any points which are still behind their corresponding view --#
    break_cond = 1
    print("Behind separation")
    while break_cond != 0:
        points_3d, break_cond = separate_behind_points(sfm, points_3d, views, bounds_xyz)
        print("Remapped points: %d" % break_cond)
        sfm.remove_3d_points_with_one_match(min_k=min_matches_per_point_single)
    sfm.points_3D = points_3d
    sfm.remap_mapped_points()
    points_3d = sfm.points_3D
    t6 = time.time()
    with open(time_save_file_path, "a") as f:
        f.write("Behind separation:\t %.2f \n" % (t6-t5))
    # -- #
    # Added for separating matches with high error --#
    break_cond = 1
    print("Cluster separation")
    while break_cond != 0:
        points_3d, break_cond = cluster_separate(sfm, points_3d, views, use_bounds=use_bounds,
                                                 bounds_xyz=bounds_xyz,
                                                 cluster_separation_limit=cluster_separation_limit)
        print("Remapped points: %d" % break_cond)
        sfm.remove_3d_points_with_one_match(min_k=min_matches_per_point_single)
    sfm.points_3D = points_3d
    sfm.remap_mapped_points()
    points_3d = sfm.points_3D
    t7 = time.time()
    with open(time_save_file_path, "a") as f:
        f.write("Cluster separation:\t %.2f \n" % (t7-t6))
    # -- #
    # Added for identifying single wrong matches -- #
    print("Gibbs separation")
    gibbs_separate(sfm, points_3d, views, use_bounds=use_bounds, bounds_xyz=bounds_xyz,
                   gibbs_separation_limit=gibbs_separation_limit, gibbs_improvement_factor=gibbs_improvement_factor)
    sfm.remove_3d_points_with_one_match(min_k=min_matches_per_point_single)
    sfm.points_3D = points_3d
    sfm.remap_mapped_points()
    points_3d = sfm.points_3D
    t8 = time.time()
    with open(time_save_file_path, "a") as f:
        f.write("Gibbs separation:\t %.2f \n" % (t8-t7))
    # -- #
    break_cond = 1
    print("3D pos adjustment")
    while break_cond != 0:
        points_3d, break_cond = run_ba_no_E_no_K(sfm, points_3d, views, use_bounds=use_bounds, bounds_xyz=bounds_xyz,
                                                 pos_3d_adjustment_error_limit=pos_3d_adjustment_error_limit)
        print("Removed points: %d" % break_cond)
        sfm.remove_3d_points_with_one_match(min_k=min_matches_per_point_single)
    sfm.points_3D = points_3d
    sfm.remap_mapped_points()
    t9 = time.time()
    with open(time_save_file_path, "a") as f:
        f.write("3D pos adjustment:\t %.2f \n" % (t9-t8))
    camera_params2 = []
    for iv, view in enumerate(views):
        cur_R = Rot.from_matrix(view.R).as_rotvec()
        cur_t = view.t
        camera_params2.append(np.hstack((cur_R, cur_t.flatten())))
    camera_params2 = np.array(camera_params2)
    # Final adjustment
    if reset_points_for_final_adjustment:
        points_3d = sfm.points_3D
        # Reset points, which are behind the corresponding view to the lowest or highest valued corner
        # depending on which of those is in front of the view
        corrected_points = 0
        for val in range(sfm.point_counter):
            corrected_points += 1
            cE = np.hstack((views[sfm.rev_point_map[val][0]].R, views[sfm.rev_point_map[val][0]].t))
            relevant_bounds = np.array([0, 2, 4]) + (cE[2, :3] > 0).astype(int)
            relevant_bounds = bounds_xyz[relevant_bounds]
            relevant_bounds[cE[2, :3] > 0] -= 1
            relevant_bounds[cE[2, :3] <= 0] += bounds_xyz[-2]
            cur_fac = np.min(((relevant_bounds - (np.linalg.inv(-cE[:, :3]) @ cE[:, 3])) / cE[2, :3])[:2])
            points_3d[val] = (np.linalg.inv(-cE[:, :3]) @ cE[:, 3]) + cur_fac * cE[2, :3]
            if points_3d[val][2] < 0:
                points_3d[val][2] = 0.
    else:
        points_3d = sfm.points_3D
    intrinsic_k = np.array([K[0, 0], K[1, 1], K[0, 2], K[1, 2]])
    t10 = time.time()
    with open(time_save_file_path, "a") as f:
        f.write("Adjustment all params preparation:\t %.2f \n" % (t10-t9))
    print("Adjust all params")
    break_cond = 1
    start_x0 = np.hstack((camera_params2.ravel()))
    while break_cond != 0:
        camera_params2, points_3d, break_cond = run_ba_final_no_k(sfm, points_3d, camera_params2, views,
                                                                  intrinsic_k, use_bounds=use_bounds,
                                                                  bounds_xyz=bounds_xyz,
                                                                  std_lim=std_lim, bounds_trans=bounds_trans,
                                                                  bounds_rots=bounds_rots, start_x0=start_x0)
        print("Removed points: %d" % break_cond)
        sfm.remove_3d_points_with_one_match(min_k=min_matches_per_point_single)
        if reduce_std_lim_to != 0:
            if break_cond == 0 and std_lim != reduce_std_lim_to:
                std_lim = reduce_std_lim_to
                break_cond = 1
    sfm.points_3D = points_3d
    sfm.remap_mapped_points()
    sfm.plot_points("_ba_all_run_%02d" % j)
    t11 = time.time()
    with open(time_save_file_path, "a") as f:
        f.write("Adjust all params:\t %.2f \n" % (t11-t10))
    points_2d = []
    camera_indices = []
    point_indices = []
    all_descriptors = []
    sorted_keys = sorted(sfm.point_map.items(), key=lambda x: x[1][0])
    for key, val in sorted_keys:
        camera_indices.append(key[0])
        point_indices.append(val[0])
        points_2d.append(views[key[0]].keypoints[key[1]].pt)
        if save_all_descriptors:
            all_descriptors.append(views[key[0]].descriptors[key[1]])
    all_descriptors = np.array(all_descriptors).astype("int")
    descriptors = np.array([]).reshape(0, 128)
    for cur_d in range(sfm.point_counter):
        descriptors = np.append(descriptors, np.array(sfm.rev_point_map[cur_d][2:]), axis=0)
    np.save(save_path + "/p3D_desc_%d_%d_%d_run_%02d" % (start_view, end_view, step_size, j), descriptors)
    np.save(save_path + "/p3D_%d_%d_%d_run_%02d" % (start_view, end_view, step_size, j), sfm.points_3D)
    np.save(save_path + "/p3Dc_%d_%d_%d_run_%02d" % (start_view, end_view, step_size, j), sfm.points_3D_colors)
    np.save(save_path + "/p2D_%d_%d_%d_run_%02d" % (start_view, end_view, step_size, j), points_2d)
    np.save(save_path + "/pI_%d_%d_%d_run_%02d" % (start_view, end_view, step_size, j), point_indices)
    np.save(save_path + "/cI_%d_%d_%d_run_%02d" % (start_view, end_view, step_size, j), camera_indices)
    np.save(save_path + "/cp_%d_%d_%d_run_%02d" % (start_view, end_view, step_size, j), camera_params2)
    np.save(save_path + "/K_%d_%d_%d_run_%02d" % (start_view, end_view, step_size, j), intrinsic_k)
    if save_all_descriptors:
        np.save(save_path + "/p3D_descALL_%d_%d_%d_run_%02d" % (start_view, end_view, step_size, j), all_descriptors)
    t12 = time.time()
    with open(time_save_file_path, "a") as f:
        f.write("Completion time:\t %.2f \n" % (t12-t1))
    print("----Done----")


if __name__ == "__main__":
    cur_runs = np.arange(len(all_params))
    np.random.shuffle(cur_runs)
    print("Cur Process Id: ", cur_process_id)
    print("Number of Runs: ", len(cur_runs))
    print("Cur Runs: ", cur_runs)
    if len(start_views) == 1 and len(end_views) == 1 and len(step_sizes) == 1:
        views = create_views(data_path, base_img_path, limit=end_views[0], every_xth_image=step_sizes[0],
                             start_v=start_views[0], text_file=text_file, name_skip=name_skip,
                             use_interpolated_path=use_interpolated_path, bad_images_path=bad_images_path)
    else:
        views = None
    for cr in cur_runs:
        run_process(cr, views=views)