-
Notifications
You must be signed in to change notification settings - Fork 858
/
reconstruction.py
1701 lines (1425 loc) · 57.6 KB
/
reconstruction.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
# pyre-unsafe
"""Incremental reconstruction pipeline"""
import datetime
import enum
import logging
import math
from abc import ABC, abstractmethod
from collections import defaultdict
from itertools import combinations
from timeit import default_timer as timer
from typing import Any, Dict, List, Optional, Set, Tuple, Union
import cv2
import numpy as np
from opensfm import (
log,
matching,
multiview,
pybundle,
pygeometry,
pymap,
pysfm,
reconstruction_helpers as helpers,
rig,
tracking,
types,
)
from opensfm.align import align_reconstruction, apply_similarity
from opensfm.context import current_memory_usage, parallel_map
from opensfm.dataset_base import DataSetBase
logger: logging.Logger = logging.getLogger(__name__)
class ReconstructionAlgorithm(str, enum.Enum):
INCREMENTAL = "incremental"
TRIANGULATION = "triangulation"
def _get_camera_from_bundle(
ba: pybundle.BundleAdjuster, camera: pygeometry.Camera
) -> None:
"""Read camera parameters from a bundle adjustment problem."""
c = ba.get_camera(camera.id)
for k, v in c.get_parameters_map().items():
camera.set_parameter_value(k, v)
def log_bundle_stats(bundle_type: str, bundle_report: Dict[str, Any]) -> None:
times = bundle_report["wall_times"]
time_secs = times["run"] + times["setup"] + times["teardown"]
num_images, num_points, num_reprojections = bundle_report["num_images"], bundle_report["num_points"], bundle_report["num_reprojections"]
msg = f"Ran {bundle_type} bundle in {time_secs:.2f} secs."
if num_points > 0 :
msg += f"with {num_images}/{num_points}/{num_reprojections} ({num_reprojections/num_points:.2f}) "
msg += "shots/points/proj. (avg. length)"
logger.info(msg)
def bundle(
reconstruction: types.Reconstruction,
camera_priors: Dict[str, pygeometry.Camera],
rig_camera_priors: Dict[str, pymap.RigCamera],
gcp: Optional[List[pymap.GroundControlPoint]],
config: Dict[str, Any],
) -> Dict[str, Any]:
"""Bundle adjust a reconstruction."""
report = pysfm.BAHelpers.bundle(
reconstruction.map,
dict(camera_priors),
dict(rig_camera_priors),
gcp if gcp is not None else [],
config,
)
log_bundle_stats("GLOBAL", report)
logger.debug(report["brief_report"])
return report
def bundle_shot_poses(
reconstruction: types.Reconstruction,
shot_ids: Set[str],
camera_priors: Dict[str, pygeometry.Camera],
rig_camera_priors: Dict[str, pymap.RigCamera],
config: Dict[str, Any],
) -> Dict[str, Any]:
"""Bundle adjust a set of shots poses."""
report = pysfm.BAHelpers.bundle_shot_poses(
reconstruction.map,
shot_ids,
dict(camera_priors),
dict(rig_camera_priors),
config,
)
return report
def bundle_local(
reconstruction: types.Reconstruction,
camera_priors: Dict[str, pygeometry.Camera],
rig_camera_priors: Dict[str, pymap.RigCamera],
gcp: Optional[List[pymap.GroundControlPoint]],
central_shot_id: str,
config: Dict[str, Any],
) -> Tuple[Dict[str, Any], List[int]]:
"""Bundle adjust the local neighborhood of a shot."""
pt_ids, report = pysfm.BAHelpers.bundle_local(
reconstruction.map,
dict(camera_priors),
dict(rig_camera_priors),
gcp if gcp is not None else [],
central_shot_id,
config,
)
log_bundle_stats("LOCAL", report)
logger.debug(report["brief_report"])
return pt_ids, report
def shot_neighborhood(
reconstruction: types.Reconstruction,
central_shot_id: str,
radius: int,
min_common_points: int,
max_interior_size: int,
) -> Tuple[Set[str], Set[str]]:
"""Reconstructed shots near a given shot.
Returns:
a tuple with interior and boundary:
- interior: the list of shots at distance smaller than radius
- boundary: shots sharing at least on point with the interior
Central shot is at distance 0. Shots at distance n + 1 share at least
min_common_points points with shots at distance n.
"""
max_boundary_size = 1000000
interior = {central_shot_id}
for _distance in range(1, radius):
remaining = max_interior_size - len(interior)
if remaining <= 0:
break
neighbors = direct_shot_neighbors(
reconstruction, interior, min_common_points, remaining
)
interior.update(neighbors)
boundary = direct_shot_neighbors(reconstruction, interior, 1, max_boundary_size)
return interior, boundary
def direct_shot_neighbors(
reconstruction: types.Reconstruction,
shot_ids: Set[str],
min_common_points: int,
max_neighbors: int,
) -> Set[str]:
"""Reconstructed shots sharing reconstructed points with a shot set."""
points = set()
for shot_id in shot_ids:
shot = reconstruction.shots[shot_id]
valid_landmarks = shot.get_valid_landmarks()
for track in valid_landmarks:
if track.id in reconstruction.points:
points.add(track)
candidate_shots = set(reconstruction.shots) - set(shot_ids)
common_points = defaultdict(int)
for track in points:
neighbors = track.get_observations()
for neighbor in neighbors:
if neighbor.id in candidate_shots:
common_points[neighbor] += 1
pairs = sorted(common_points.items(), key=lambda x: -x[1])
neighbors = set()
for neighbor, num_points in pairs[:max_neighbors]:
if num_points >= min_common_points:
neighbors.add(neighbor.id)
else:
break
return neighbors
def pairwise_reconstructability(common_tracks: int, rotation_inliers: int) -> float:
"""Likeliness of an image pair giving a good initial reconstruction."""
outliers = common_tracks - rotation_inliers
outlier_ratio = float(outliers) / common_tracks
if outlier_ratio >= 0.3:
return outliers
else:
return 0
TPairArguments = Tuple[
str, str, np.ndarray, np.ndarray, pygeometry.Camera, pygeometry.Camera, float
]
def compute_image_pairs(
track_dict: Dict[Tuple[str, str], tracking.TPairTracks], data: DataSetBase
) -> List[Tuple[str, str]]:
"""All matched image pairs sorted by reconstructability."""
cameras = data.load_camera_models()
args = _pair_reconstructability_arguments(track_dict, cameras, data)
processes = data.config["processes"]
result = parallel_map(_compute_pair_reconstructability, args, processes)
result = list(result)
pairs = [(im1, im2) for im1, im2, r in result if r > 0]
score = [r for im1, im2, r in result if r > 0]
order = np.argsort(-np.array(score))
return [pairs[o] for o in order]
def _pair_reconstructability_arguments(
track_dict: Dict[Tuple[str, str], tracking.TPairTracks],
cameras: Dict[str, pygeometry.Camera],
data: DataSetBase,
) -> List[TPairArguments]:
threshold = 4 * data.config["five_point_algo_threshold"]
args = []
for (im1, im2), (_, p1, p2) in track_dict.items():
camera1 = cameras[data.load_exif(im1)["camera"]]
camera2 = cameras[data.load_exif(im2)["camera"]]
args.append((im1, im2, p1, p2, camera1, camera2, threshold))
return args
def _compute_pair_reconstructability(args: TPairArguments) -> Tuple[str, str, float]:
log.setup()
im1, im2, p1, p2, camera1, camera2, threshold = args
R, inliers = two_view_reconstruction_rotation_only(
p1, p2, camera1, camera2, threshold
)
r = pairwise_reconstructability(len(p1), len(inliers))
return (im1, im2, r)
def add_shot(
data: DataSetBase,
reconstruction: types.Reconstruction,
rig_assignments: Dict[str, Tuple[str, str, List[str]]],
shot_id: str,
pose: pygeometry.Pose,
) -> Set[str]:
"""Add a shot to the reconstruction.
In case of a shot belonging to a rig instance, the pose of
shot will drive the initial pose setup of the rig instance.
All necessary shots and rig models will be created.
"""
added_shots = set()
if shot_id not in rig_assignments:
camera_id = data.load_exif(shot_id)["camera"]
shot = reconstruction.create_shot(shot_id, camera_id, pose)
shot.metadata = helpers.get_image_metadata(data, shot_id)
added_shots = {shot_id}
else:
instance_id, _, instance_shots = rig_assignments[shot_id]
rig_instance = reconstruction.add_rig_instance(pymap.RigInstance(instance_id))
for shot in instance_shots:
_, rig_camera_id, _ = rig_assignments[shot]
camera_id = data.load_exif(shot)["camera"]
created_shot = reconstruction.create_shot(
shot,
camera_id,
pygeometry.Pose(),
rig_camera_id,
instance_id,
)
created_shot.metadata = helpers.get_image_metadata(data, shot)
rig_instance.update_instance_pose_with_shot(shot_id, pose)
added_shots = set(instance_shots)
return added_shots
def _two_view_reconstruction_inliers(
b1: np.ndarray, b2: np.ndarray, R: np.ndarray, t: np.ndarray, threshold: float
) -> List[int]:
"""Returns indices of matches that can be triangulated."""
ok = matching.compute_inliers_bearings(b1, b2, R, t, threshold)
# pyre-fixme[7]: Expected `List[int]` but got `ndarray[typing.Any,
# dtype[typing.Any]]`.
return np.nonzero(ok)[0]
def two_view_reconstruction_plane_based(
b1: np.ndarray,
b2: np.ndarray,
threshold: float,
) -> Tuple[Optional[np.ndarray], Optional[np.ndarray], List[int]]:
"""Reconstruct two views from point correspondences lying on a plane.
Args:
b1, b2: lists bearings in the images
threshold: reprojection error threshold
Returns:
rotation, translation and inlier list
"""
x1 = multiview.euclidean(b1)
x2 = multiview.euclidean(b2)
H, inliers = cv2.findHomography(x1, x2, cv2.RANSAC, threshold)
motions = multiview.motion_from_plane_homography(H)
if not motions:
return None, None, []
if len(motions) == 0:
return None, None, []
motion_inliers = []
for R, t, _, _ in motions:
inliers = _two_view_reconstruction_inliers(b1, b2, R.T, -R.T.dot(t), threshold)
motion_inliers.append(inliers)
# pyre-fixme[6]: For 1st argument expected `Union[_SupportsArray[dtype[typing.Any...
best = np.argmax(map(len, motion_inliers))
R, t, n, d = motions[best]
inliers = motion_inliers[best]
return cv2.Rodrigues(R)[0].ravel(), t, inliers
def two_view_reconstruction_and_refinement(
b1: np.ndarray,
b2: np.ndarray,
R: np.ndarray,
t: np.ndarray,
threshold: float,
iterations: int,
transposed: bool,
) -> Tuple[np.ndarray, np.ndarray, List[int]]:
"""Reconstruct two views using provided rotation and translation.
Args:
b1, b2: lists bearings in the images
R, t: rotation & translation
threshold: reprojection error threshold
iterations: number of iteration for refinement
transposed: use transposed R, t instead
Returns:
rotation, translation and inlier list
"""
if transposed:
t_curr = -R.T.dot(t)
R_curr = R.T
else:
t_curr = t.copy()
R_curr = R.copy()
inliers = _two_view_reconstruction_inliers(b1, b2, R_curr, t_curr, threshold)
if len(inliers) > 5:
T = multiview.relative_pose_optimize_nonlinear(
b1[inliers], b2[inliers], t_curr, R_curr, iterations
)
R_curr = T[:, :3]
t_curr = T[:, 3]
inliers = _two_view_reconstruction_inliers(b1, b2, R_curr, t_curr, threshold)
return cv2.Rodrigues(R_curr.T)[0].ravel(), -R_curr.T.dot(t_curr), inliers
def _two_view_rotation_inliers(
b1: np.ndarray, b2: np.ndarray, R: np.ndarray, threshold: float
) -> List[int]:
br2 = R.dot(b2.T).T
ok = np.linalg.norm(br2 - b1, axis=1) < threshold
# pyre-fixme[7]: Expected `List[int]` but got `ndarray[typing.Any,
# dtype[typing.Any]]`.
return np.nonzero(ok)[0]
def two_view_reconstruction_rotation_only(
p1: np.ndarray,
p2: np.ndarray,
camera1: pygeometry.Camera,
camera2: pygeometry.Camera,
threshold: float,
) -> Tuple[np.ndarray, List[int]]:
"""Find rotation between two views from point correspondences.
Args:
p1, p2: lists points in the images
camera1, camera2: Camera models
threshold: reprojection error threshold
Returns:
rotation and inlier list
"""
b1 = camera1.pixel_bearing_many(p1)
b2 = camera2.pixel_bearing_many(p2)
R = multiview.relative_pose_ransac_rotation_only(b1, b2, threshold, 1000, 0.999)
inliers = _two_view_rotation_inliers(b1, b2, R, threshold)
return cv2.Rodrigues(R.T)[0].ravel(), inliers
def two_view_reconstruction_5pt(
b1: np.ndarray,
b2: np.ndarray,
R: np.ndarray,
t: np.ndarray,
threshold: float,
iterations: int,
check_reversal: bool = False,
reversal_ratio: float = 1.0,
) -> Tuple[Optional[np.ndarray], Optional[np.ndarray], List[int]]:
"""Run 5-point reconstruction and refinement, given computed relative rotation and translation.
Optionally, the method will perform reconstruction and refinement for both given and transposed
rotation and translation.
Args:
p1, p2: lists points in the images
camera1, camera2: Camera models
threshold: reprojection error threshold
iterations: number of step for the non-linear refinement of the relative pose
check_reversal: whether to check for Necker reversal ambiguity
reversal_ratio: ratio of triangulated point between normal and reversed
configuration to consider a pair as being ambiguous
Returns:
rotation, translation and inlier list
"""
configurations = [False, True] if check_reversal else [False]
# Refine both normal and transposed relative motion
results_5pt = []
for transposed in configurations:
R_5p, t_5p, inliers_5p = two_view_reconstruction_and_refinement(
b1,
b2,
R,
t,
threshold,
iterations,
transposed,
)
valid_curr_5pt = R_5p is not None and t_5p is not None
if len(inliers_5p) <= 5 or not valid_curr_5pt:
continue
logger.info(
f"Two-view 5-points reconstruction inliers (transposed={transposed}): {len(inliers_5p)} / {len(b1)}"
)
results_5pt.append((R_5p, t_5p, inliers_5p))
# Use relative motion if one version stands out
if len(results_5pt) == 1:
R_5p, t_5p, inliers_5p = results_5pt[0]
elif len(results_5pt) == 2:
inliers1, inliers2 = results_5pt[0][2], results_5pt[1][2]
len1, len2 = len(inliers1), len(inliers2)
ratio = min(len1, len2) / max(len1, len2)
if ratio > reversal_ratio:
logger.warning(
f"Un-decidable Necker configuration (ratio={ratio}), skipping."
)
R_5p, t_5p, inliers_5p = None, None, []
else:
index = 0 if len1 > len2 else 1
R_5p, t_5p, inliers_5p = results_5pt[index]
else:
R_5p, t_5p, inliers_5p = None, None, []
return R_5p, t_5p, inliers_5p
def two_view_reconstruction_general(
p1: np.ndarray,
p2: np.ndarray,
camera1: pygeometry.Camera,
camera2: pygeometry.Camera,
threshold: float,
iterations: int,
check_reversal: bool = False,
reversal_ratio: float = 1.0,
) -> Tuple[Optional[np.ndarray], Optional[np.ndarray], List[int], Dict[str, Any]]:
"""Reconstruct two views from point correspondences.
These will try different reconstruction methods and return the
results of the one with most inliers.
Args:
p1, p2: lists points in the images
camera1, camera2: Camera models
threshold: reprojection error threshold
iterations: number of step for the non-linear refinement of the relative pose
check_reversal: whether to check for Necker reversal ambiguity
reversal_ratio: ratio of triangulated point between normal and reversed
configuration to consider a pair as being ambiguous
Returns:
rotation, translation and inlier list
"""
b1 = camera1.pixel_bearing_many(p1)
b2 = camera2.pixel_bearing_many(p2)
# Get 5-point relative motion
T_robust = multiview.relative_pose_ransac(b1, b2, threshold, 1000, 0.999)
R_robust = T_robust[:, :3]
t_robust = T_robust[:, 3]
R_5p, t_5p, inliers_5p = two_view_reconstruction_5pt(
b1,
b2,
R_robust,
t_robust,
threshold,
iterations,
check_reversal,
reversal_ratio,
)
valid_5pt = R_5p is not None and t_5p is not None
# Compute plane-based relative-motion
R_plane, t_plane, inliers_plane = two_view_reconstruction_plane_based(
b1,
b2,
threshold,
)
valid_plane = R_plane is not None and t_plane is not None
report: Dict[str, Any] = {
"5_point_inliers": len(inliers_5p),
"plane_based_inliers": len(inliers_plane),
}
if valid_5pt and len(inliers_5p) > len(inliers_plane):
report["method"] = "5_point"
R, t, inliers = R_5p, t_5p, inliers_5p
elif valid_plane:
report["method"] = "plane_based"
R, t, inliers = R_plane, t_plane, inliers_plane
else:
report["decision"] = "Could not find initial motion"
logger.info(report["decision"])
R, t, inliers = None, None, []
return R, t, inliers, report
def reconstruction_from_relative_pose(
data: DataSetBase,
tracks_manager: pymap.TracksManager,
im1: str,
im2: str,
R: np.ndarray,
t: np.ndarray,
) -> Tuple[Optional[types.Reconstruction], Dict[str, Any]]:
"""Create a reconstruction from 'im1' and 'im2' using the provided rotation 'R' and translation 't'."""
report = {}
min_inliers = data.config["five_point_algo_min_inliers"]
camera_priors = data.load_camera_models()
rig_camera_priors = data.load_rig_cameras()
rig_assignments = rig.rig_assignments_per_image(data.load_rig_assignments())
reconstruction = types.Reconstruction()
reconstruction.reference = data.load_reference()
reconstruction.cameras = camera_priors
reconstruction.rig_cameras = rig_camera_priors
new_shots = add_shot(data, reconstruction, rig_assignments, im1, pygeometry.Pose())
if im2 not in new_shots:
new_shots |= add_shot(
data, reconstruction, rig_assignments, im2, pygeometry.Pose(R, t)
)
align_reconstruction(reconstruction, [], data.config)
triangulate_shot_features(tracks_manager, reconstruction, new_shots, data.config)
logger.info("Triangulated: {}".format(len(reconstruction.points)))
report["triangulated_points"] = len(reconstruction.points)
if len(reconstruction.points) < min_inliers:
report["decision"] = "Initial motion did not generate enough points"
logger.info(report["decision"])
return None, report
to_adjust = {s for s in new_shots if s != im1}
bundle_shot_poses(
reconstruction, to_adjust, camera_priors, rig_camera_priors, data.config
)
retriangulate(tracks_manager, reconstruction, data.config)
if len(reconstruction.points) < min_inliers:
report[
"decision"
] = "Re-triangulation after initial motion did not generate enough points"
logger.info(report["decision"])
return None, report
bundle_shot_poses(
reconstruction, to_adjust, camera_priors, rig_camera_priors, data.config
)
report["decision"] = "Success"
report["memory_usage"] = current_memory_usage()
return reconstruction, report
def bootstrap_reconstruction(
data: DataSetBase,
tracks_manager: pymap.TracksManager,
im1: str,
im2: str,
p1: np.ndarray,
p2: np.ndarray,
) -> Tuple[Optional[types.Reconstruction], Dict[str, Any]]:
"""Start a reconstruction using two shots."""
logger.info("Starting reconstruction with {} and {}".format(im1, im2))
report: Dict[str, Any] = {
"image_pair": (im1, im2),
"common_tracks": len(p1),
}
camera_priors = data.load_camera_models()
camera1 = camera_priors[data.load_exif(im1)["camera"]]
camera2 = camera_priors[data.load_exif(im2)["camera"]]
threshold = data.config["five_point_algo_threshold"]
iterations = data.config["five_point_refine_rec_iterations"]
check_reversal = data.config["five_point_reversal_check"]
reversal_ratio = data.config["five_point_reversal_ratio"]
(
R,
t,
inliers,
report["two_view_reconstruction"],
) = two_view_reconstruction_general(
p1, p2, camera1, camera2, threshold, iterations, check_reversal, reversal_ratio
)
if R is None or t is None:
return None, report
rec, rec_report = reconstruction_from_relative_pose(
data, tracks_manager, im1, im2, R, t
)
report.update(rec_report)
return rec, report
def reconstructed_points_for_images(
tracks_manager: pymap.TracksManager,
reconstruction: types.Reconstruction,
images: Set[str],
) -> List[Tuple[str, int]]:
"""Number of reconstructed points visible on each image.
Returns:
A list of (image, num_point) pairs sorted by decreasing number
of points.
"""
non_reconstructed = [im for im in images if im not in reconstruction.shots]
res = pysfm.count_tracks_per_shot(
tracks_manager, non_reconstructed, list(reconstruction.points.keys())
)
return sorted(res.items(), key=lambda x: -x[1])
def resect(
data: DataSetBase,
tracks_manager: pymap.TracksManager,
reconstruction: types.Reconstruction,
shot_id: str,
threshold: float,
min_inliers: int,
) -> Tuple[bool, Set[str], Dict[str, Any]]:
"""Try resecting and adding a shot to the reconstruction.
Return:
True on success.
"""
rig_assignments = rig.rig_assignments_per_image(data.load_rig_assignments())
camera = reconstruction.cameras[data.load_exif(shot_id)["camera"]]
bs, Xs, ids = [], [], []
for track, obs in tracks_manager.get_shot_observations(shot_id).items():
if track in reconstruction.points:
b = camera.pixel_bearing(obs.point)
bs.append(b)
Xs.append(reconstruction.points[track].coordinates)
ids.append(track)
bs = np.array(bs)
Xs = np.array(Xs)
if len(bs) < 5:
return False, set(), {"num_common_points": len(bs)}
T = multiview.absolute_pose_ransac(bs, Xs, threshold, 1000, 0.999)
R = T[:, :3]
t = T[:, 3]
reprojected_bs = R.T.dot((Xs - t).T).T
reprojected_bs /= np.linalg.norm(reprojected_bs, axis=1)[:, np.newaxis]
inliers = np.linalg.norm(reprojected_bs - bs, axis=1) < threshold
ninliers = int(sum(inliers))
logger.info("{} resection inliers: {} / {}".format(shot_id, ninliers, len(bs)))
report: Dict[str, Any] = {
"num_common_points": len(bs),
"num_inliers": ninliers,
}
if ninliers >= min_inliers:
R = T[:, :3].T
t = -R.dot(T[:, 3])
assert shot_id not in reconstruction.shots
new_shots = add_shot(
data, reconstruction, rig_assignments, shot_id, pygeometry.Pose(R, t)
)
if shot_id in rig_assignments:
triangulate_shot_features(
tracks_manager, reconstruction, new_shots, data.config
)
for i, succeed in enumerate(inliers):
if succeed:
add_observation_to_reconstruction(
tracks_manager, reconstruction, shot_id, ids[i]
)
report["shots"] = list(new_shots)
return True, new_shots, report
else:
return False, set(), report
def corresponding_tracks(
tracks1: Dict[str, pymap.Observation], tracks2: Dict[str, pymap.Observation]
) -> List[Tuple[str, str]]:
features1 = {obs.id: t1 for t1, obs in tracks1.items()}
corresponding_tracks = []
for t2, obs in tracks2.items():
feature_id = obs.id
if feature_id in features1:
corresponding_tracks.append((features1[feature_id], t2))
return corresponding_tracks
def compute_common_tracks(
reconstruction1: types.Reconstruction,
reconstruction2: types.Reconstruction,
tracks_manager1: pymap.TracksManager,
tracks_manager2: pymap.TracksManager,
) -> List[Tuple[str, str]]:
common_tracks = set()
common_images = set(reconstruction1.shots.keys()).intersection(
reconstruction2.shots.keys()
)
all_shot_ids1 = set(tracks_manager1.get_shot_ids())
all_shot_ids2 = set(tracks_manager2.get_shot_ids())
for image in common_images:
if image not in all_shot_ids1 or image not in all_shot_ids2:
continue
at_shot1 = tracks_manager1.get_shot_observations(image)
at_shot2 = tracks_manager2.get_shot_observations(image)
for t1, t2 in corresponding_tracks(at_shot1, at_shot2):
if t1 in reconstruction1.points and t2 in reconstruction2.points:
common_tracks.add((t1, t2))
return list(common_tracks)
def resect_reconstruction(
reconstruction1: types.Reconstruction,
reconstruction2: types.Reconstruction,
tracks_manager1: pymap.TracksManager,
tracks_manager2: pymap.TracksManager,
threshold: float,
min_inliers: int,
) -> Tuple[bool, np.ndarray, List[Tuple[str, str]]]:
"""Compute a similarity transform `similarity` such as :
reconstruction2 = T . reconstruction1
between two reconstruction 'reconstruction1' and 'reconstruction2'.
Their respective tracks managers are used to find common tracks that
are further used to compute the 3D similarity transform T using RANSAC.
"""
common_tracks = compute_common_tracks(
reconstruction1, reconstruction2, tracks_manager1, tracks_manager2
)
worked, similarity, inliers = align_two_reconstruction(
reconstruction1, reconstruction2, common_tracks, threshold
)
if not worked or similarity is None:
return False, np.ones((4, 4)), []
inliers = [common_tracks[inliers[i]] for i in range(len(inliers))]
return True, similarity, inliers
def add_observation_to_reconstruction(
tracks_manager: pymap.TracksManager,
reconstruction: types.Reconstruction,
shot_id: str,
track_id: str,
) -> None:
observation = tracks_manager.get_observation(shot_id, track_id)
reconstruction.add_observation(shot_id, track_id, observation)
class TrackHandlerBase(ABC):
"""Interface for providing/retrieving tracks from/to 'TrackTriangulator'."""
@abstractmethod
def get_observations(self, track_id: str) -> Dict[str, pymap.Observation]:
"""Returns the observations of 'track_id'"""
pass
@abstractmethod
def store_track_coordinates(self, track_id: str, coordinates: np.ndarray) -> None:
"""Stores coordinates of triangulated track."""
pass
@abstractmethod
def store_inliers_observation(self, track_id: str, shot_id: str) -> None:
"""Called by the 'TrackTriangulator' for each track inlier found."""
pass
class TrackHandlerTrackManager(TrackHandlerBase):
"""Provider that reads tracks from a 'TrackManager' object."""
tracks_manager: pymap.TracksManager
reconstruction: types.Reconstruction
def __init__(
self,
tracks_manager: pymap.TracksManager,
reconstruction: types.Reconstruction,
) -> None:
self.tracks_manager = tracks_manager
self.reconstruction = reconstruction
def get_observations(self, track_id: str) -> Dict[str, pymap.Observation]:
"""Return the observations of 'track_id', for all
shots that appears in 'self.reconstruction.shots'
"""
return {
k: v
for k, v in self.tracks_manager.get_track_observations(track_id).items()
if k in self.reconstruction.shots
}
def store_track_coordinates(self, track_id: str, coordinates: np.ndarray) -> None:
"""Stores coordinates of triangulated track."""
self.reconstruction.create_point(track_id, coordinates)
def store_inliers_observation(self, track_id: str, shot_id: str) -> None:
"""Stores triangulation inliers in the tracks manager."""
observation = self.tracks_manager.get_observation(shot_id, track_id)
self.reconstruction.add_observation(shot_id, track_id, observation)
class TrackTriangulator:
"""Triangulate tracks in a reconstruction.
Caches shot origin and rotation matrix
"""
# for getting shots
reconstruction: types.Reconstruction
# for storing tracks inliers
tracks_handler: TrackHandlerBase
# caches
origins: Dict[str, np.ndarray] = {}
rotation_inverses: Dict[str, np.ndarray] = {}
Rts: Dict[str, np.ndarray] = {}
def __init__(
self, reconstruction: types.Reconstruction, tracks_handler: TrackHandlerBase
) -> None:
"""Build a triangulator for a specific reconstruction."""
self.reconstruction = reconstruction
self.tracks_handler = tracks_handler
self.origins = {}
self.rotation_inverses = {}
self.Rts = {}
def triangulate_robust(
self,
track: str,
reproj_threshold: float,
min_ray_angle_degrees: float,
iterations: int,
) -> None:
"""Triangulate track in a RANSAC way and add point to reconstruction."""
os, bs, ids = [], [], []
for shot_id, obs in self.tracks_handler.get_observations(track).items():
shot = self.reconstruction.shots[shot_id]
os.append(self._shot_origin(shot))
b = shot.camera.pixel_bearing(np.array(obs.point))
r = self._shot_rotation_inverse(shot)
bs.append(r.dot(b))
ids.append(shot_id)
if len(ids) < 2:
return
os = np.array(os)
bs = np.array(bs)
best_inliers = []
best_point = None
combinatiom_tried = set()
ransac_tries = 11 # 0.99 proba, 60% inliers
all_combinations = list(combinations(range(len(ids)), 2))
thresholds = len(os) * [reproj_threshold]
min_ray_angle_radians = np.radians(min_ray_angle_degrees)
max_ray_angle_radians = np.pi - min_ray_angle_radians
for i in range(ransac_tries):
random_id = int(np.random.rand() * (len(all_combinations) - 1))
if random_id in combinatiom_tried:
continue
i, j = all_combinations[random_id]
combinatiom_tried.add(random_id)
os_t = np.array([os[i], os[j]])
bs_t = np.array([bs[i], bs[j]])
valid_triangulation, X = pygeometry.triangulate_bearings_midpoint(
os_t,
bs_t,
thresholds,
min_ray_angle_radians,
max_ray_angle_radians,
)
X = pygeometry.point_refinement(os_t, bs_t, X, iterations)
if valid_triangulation:
reprojected_bs = X - os
reprojected_bs /= np.linalg.norm(reprojected_bs, axis=1)[:, np.newaxis]
inliers = np.nonzero(
np.linalg.norm(reprojected_bs - bs, axis=1) < reproj_threshold
)[0].tolist()
if len(inliers) > len(best_inliers):
_, new_X = pygeometry.triangulate_bearings_midpoint(
os[inliers],
bs[inliers],
len(inliers) * [reproj_threshold],
min_ray_angle_radians,
max_ray_angle_radians,
)
new_X = pygeometry.point_refinement(
os[inliers], bs[inliers], X, iterations
)
reprojected_bs = new_X - os
reprojected_bs /= np.linalg.norm(reprojected_bs, axis=1)[
:, np.newaxis
]
ls_inliers = np.nonzero(
np.linalg.norm(reprojected_bs - bs, axis=1) < reproj_threshold
)[0]
if len(ls_inliers) > len(inliers):
best_inliers = ls_inliers
best_point = new_X.tolist()
else:
best_inliers = inliers
best_point = X.tolist()
pout = 0.99
inliers_ratio = float(len(best_inliers)) / len(ids)
if inliers_ratio == 1.0:
break
optimal_iter = math.log(1.0 - pout) / math.log(
1.0 - inliers_ratio * inliers_ratio
)
if optimal_iter <= i:
break
if len(best_inliers) > 1:
self.tracks_handler.store_track_coordinates(track, best_point)
for i in best_inliers:
self.tracks_handler.store_inliers_observation(track, ids[i])