-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreconstruction.cc
More file actions
executable file
·2062 lines (1677 loc) · 66.7 KB
/
reconstruction.cc
File metadata and controls
executable file
·2062 lines (1677 loc) · 66.7 KB
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
// Copyright (c) 2018, ETH Zurich and UNC Chapel Hill.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of ETH Zurich and UNC Chapel Hill nor the names of
// its contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
// Author: Johannes L. Schoenberger (jsch-at-demuc-dot-de)
// Modified by Javier Morlana (jmorlana-at-unizar-dot-es) for the Endomapper Dataset.
// Addition of WriteImagesModelText to WriteText and WriteBinary functions, generating
// a file with all the covisible images for each image.
#include "base/reconstruction.h"
#include <fstream>
#include "base/database_cache.h"
#include "base/pose.h"
#include "base/projection.h"
#include "base/similarity_transform.h"
#include "base/triangulation.h"
#include "estimators/similarity_transform.h"
#include "optim/loransac.h"
#include "util/bitmap.h"
#include "util/misc.h"
#include "util/ply.h"
namespace colmap {
Reconstruction::Reconstruction()
: correspondence_graph_(nullptr), num_added_points3D_(0) {}
std::unordered_set<point3D_t> Reconstruction::Point3DIds() const {
std::unordered_set<point3D_t> point3D_ids;
point3D_ids.reserve(points3D_.size());
for (const auto& point3D : points3D_) {
point3D_ids.insert(point3D.first);
}
return point3D_ids;
}
void Reconstruction::Load(const DatabaseCache& database_cache) {
correspondence_graph_ = nullptr;
// Add cameras.
cameras_.reserve(database_cache.NumCameras());
for (const auto& camera : database_cache.Cameras()) {
if (!ExistsCamera(camera.first)) {
AddCamera(camera.second);
}
// Else: camera was added before, e.g. with `ReadAllCameras`.
}
// Add images.
images_.reserve(database_cache.NumImages());
for (const auto& image : database_cache.Images()) {
if (ExistsImage(image.second.ImageId())) {
class Image& existing_image = Image(image.second.ImageId());
CHECK_EQ(existing_image.Name(), image.second.Name());
if (existing_image.NumPoints2D() == 0) {
existing_image.SetPoints2D(image.second.Points2D());
} else {
CHECK_EQ(image.second.NumPoints2D(), existing_image.NumPoints2D());
}
existing_image.SetNumObservations(image.second.NumObservations());
existing_image.SetNumCorrespondences(image.second.NumCorrespondences());
} else {
AddImage(image.second);
}
}
// Add image pairs.
for (const auto& image_pair :
database_cache.CorrespondenceGraph().NumCorrespondencesBetweenImages()) {
ImagePairStat image_pair_stat;
image_pair_stat.num_total_corrs = image_pair.second;
image_pair_stats_.emplace(image_pair.first, image_pair_stat);
}
}
void Reconstruction::SetUp(const CorrespondenceGraph* correspondence_graph) {
CHECK_NOTNULL(correspondence_graph);
for (auto& image : images_) {
image.second.SetUp(Camera(image.second.CameraId()));
}
correspondence_graph_ = correspondence_graph;
// If an existing model was loaded from disk and there were already images
// registered previously, we need to set observations as triangulated.
for (const auto image_id : reg_image_ids_) {
const class Image& image = Image(image_id);
for (point2D_t point2D_idx = 0; point2D_idx < image.NumPoints2D();
++point2D_idx) {
if (image.Point2D(point2D_idx).HasPoint3D()) {
const bool kIsContinuedPoint3D = false;
SetObservationAsTriangulated(image_id, point2D_idx,
kIsContinuedPoint3D);
}
}
}
}
void Reconstruction::TearDown() {
correspondence_graph_ = nullptr;
// Remove all not yet registered images.
std::unordered_set<camera_t> keep_camera_ids;
for (auto it = images_.begin(); it != images_.end();) {
if (it->second.IsRegistered()) {
keep_camera_ids.insert(it->second.CameraId());
it->second.TearDown();
++it;
} else {
it = images_.erase(it);
}
}
// Remove all unused cameras.
for (auto it = cameras_.begin(); it != cameras_.end();) {
if (keep_camera_ids.count(it->first) == 0) {
it = cameras_.erase(it);
} else {
++it;
}
}
// Compress tracks.
for (auto& point3D : points3D_) {
point3D.second.Track().Compress();
}
}
void Reconstruction::AddCamera(const class Camera& camera) {
CHECK(!ExistsCamera(camera.CameraId()));
CHECK(camera.VerifyParams());
cameras_.emplace(camera.CameraId(), camera);
}
void Reconstruction::AddImage(const class Image& image) {
CHECK(!ExistsImage(image.ImageId()));
images_[image.ImageId()] = image;
}
point3D_t Reconstruction::AddPoint3D(const Eigen::Vector3d& xyz,
const Track& track,
const Eigen::Vector3ub& color) {
const point3D_t point3D_id = ++num_added_points3D_;
CHECK(!ExistsPoint3D(point3D_id));
class Point3D& point3D = points3D_[point3D_id];
point3D.SetXYZ(xyz);
point3D.SetTrack(track);
point3D.SetColor(color);
for (const auto& track_el : track.Elements()) {
class Image& image = Image(track_el.image_id);
CHECK(!image.Point2D(track_el.point2D_idx).HasPoint3D());
image.SetPoint3DForPoint2D(track_el.point2D_idx, point3D_id);
CHECK_LE(image.NumPoints3D(), image.NumPoints2D());
}
const bool kIsContinuedPoint3D = false;
for (const auto& track_el : track.Elements()) {
SetObservationAsTriangulated(track_el.image_id, track_el.point2D_idx,
kIsContinuedPoint3D);
}
return point3D_id;
}
void Reconstruction::AddObservation(const point3D_t point3D_id,
const TrackElement& track_el) {
class Image& image = Image(track_el.image_id);
CHECK(!image.Point2D(track_el.point2D_idx).HasPoint3D());
image.SetPoint3DForPoint2D(track_el.point2D_idx, point3D_id);
CHECK_LE(image.NumPoints3D(), image.NumPoints2D());
class Point3D& point3D = Point3D(point3D_id);
point3D.Track().AddElement(track_el);
const bool kIsContinuedPoint3D = true;
SetObservationAsTriangulated(track_el.image_id, track_el.point2D_idx,
kIsContinuedPoint3D);
}
point3D_t Reconstruction::MergePoints3D(const point3D_t point3D_id1,
const point3D_t point3D_id2) {
const class Point3D& point3D1 = Point3D(point3D_id1);
const class Point3D& point3D2 = Point3D(point3D_id2);
const Eigen::Vector3d merged_xyz =
(point3D1.Track().Length() * point3D1.XYZ() +
point3D2.Track().Length() * point3D2.XYZ()) /
(point3D1.Track().Length() + point3D2.Track().Length());
const Eigen::Vector3d merged_rgb =
(point3D1.Track().Length() * point3D1.Color().cast<double>() +
point3D2.Track().Length() * point3D2.Color().cast<double>()) /
(point3D1.Track().Length() + point3D2.Track().Length());
Track merged_track;
merged_track.Reserve(point3D1.Track().Length() + point3D2.Track().Length());
merged_track.AddElements(point3D1.Track().Elements());
merged_track.AddElements(point3D2.Track().Elements());
DeletePoint3D(point3D_id1);
DeletePoint3D(point3D_id2);
const point3D_t merged_point3D_id =
AddPoint3D(merged_xyz, merged_track, merged_rgb.cast<uint8_t>());
return merged_point3D_id;
}
void Reconstruction::DeletePoint3D(const point3D_t point3D_id) {
// Note: Do not change order of these instructions, especially with respect to
// `Reconstruction::ResetTriObservations`
const class Track& track = Point3D(point3D_id).Track();
const bool kIsDeletedPoint3D = true;
for (const auto& track_el : track.Elements()) {
ResetTriObservations(track_el.image_id, track_el.point2D_idx,
kIsDeletedPoint3D);
}
for (const auto& track_el : track.Elements()) {
class Image& image = Image(track_el.image_id);
image.ResetPoint3DForPoint2D(track_el.point2D_idx);
}
points3D_.erase(point3D_id);
}
void Reconstruction::DeleteObservation(const image_t image_id,
const point2D_t point2D_idx) {
// Note: Do not change order of these instructions, especially with respect to
// `Reconstruction::ResetTriObservations`
class Image& image = Image(image_id);
const point3D_t point3D_id = image.Point2D(point2D_idx).Point3DId();
class Point3D& point3D = Point3D(point3D_id);
if (point3D.Track().Length() <= 2) {
DeletePoint3D(point3D_id);
return;
}
point3D.Track().DeleteElement(image_id, point2D_idx);
const bool kIsDeletedPoint3D = false;
ResetTriObservations(image_id, point2D_idx, kIsDeletedPoint3D);
image.ResetPoint3DForPoint2D(point2D_idx);
}
void Reconstruction::DeleteAllPoints2DAndPoints3D() {
points3D_.clear();
for (auto& image : images_) {
class Image new_image;
new_image.SetImageId(image.second.ImageId());
new_image.SetName(image.second.Name());
new_image.SetCameraId(image.second.CameraId());
new_image.SetRegistered(image.second.IsRegistered());
new_image.SetNumCorrespondences(image.second.NumCorrespondences());
new_image.SetQvec(image.second.Qvec());
new_image.SetQvecPrior(image.second.QvecPrior());
new_image.SetTvec(image.second.Tvec());
new_image.SetTvecPrior(image.second.TvecPrior());
image.second = new_image;
}
}
void Reconstruction::RegisterImage(const image_t image_id) {
class Image& image = Image(image_id);
if (!image.IsRegistered()) {
image.SetRegistered(true);
reg_image_ids_.push_back(image_id);
}
}
void Reconstruction::DeRegisterImage(const image_t image_id) {
class Image& image = Image(image_id);
for (point2D_t point2D_idx = 0; point2D_idx < image.NumPoints2D();
++point2D_idx) {
if (image.Point2D(point2D_idx).HasPoint3D()) {
DeleteObservation(image_id, point2D_idx);
}
}
image.SetRegistered(false);
reg_image_ids_.erase(
std::remove(reg_image_ids_.begin(), reg_image_ids_.end(), image_id),
reg_image_ids_.end());
}
void Reconstruction::Normalize(const double extent, const double p0,
const double p1, const bool use_images) {
CHECK_GT(extent, 0);
CHECK_GE(p0, 0);
CHECK_LE(p0, 1);
CHECK_GE(p1, 0);
CHECK_LE(p1, 1);
CHECK_LE(p0, p1);
if ((use_images && reg_image_ids_.size() < 2) ||
(!use_images && points3D_.size() < 2)) {
return;
}
EIGEN_STL_UMAP(class Image*, Eigen::Vector3d) proj_centers;
for (size_t i = 0; i < reg_image_ids_.size(); ++i) {
class Image& image = Image(reg_image_ids_[i]);
const Eigen::Vector3d proj_center = image.ProjectionCenter();
proj_centers[&image] = proj_center;
}
// Coordinates of image centers or point locations.
std::vector<float> coords_x;
std::vector<float> coords_y;
std::vector<float> coords_z;
if (use_images) {
coords_x.reserve(proj_centers.size());
coords_y.reserve(proj_centers.size());
coords_z.reserve(proj_centers.size());
for (const auto& proj_center : proj_centers) {
coords_x.push_back(static_cast<float>(proj_center.second(0)));
coords_y.push_back(static_cast<float>(proj_center.second(1)));
coords_z.push_back(static_cast<float>(proj_center.second(2)));
}
} else {
coords_x.reserve(points3D_.size());
coords_y.reserve(points3D_.size());
coords_z.reserve(points3D_.size());
for (const auto& point3D : points3D_) {
coords_x.push_back(static_cast<float>(point3D.second.X()));
coords_y.push_back(static_cast<float>(point3D.second.Y()));
coords_z.push_back(static_cast<float>(point3D.second.Z()));
}
}
// Determine robust bounding box and mean.
std::sort(coords_x.begin(), coords_x.end());
std::sort(coords_y.begin(), coords_y.end());
std::sort(coords_z.begin(), coords_z.end());
const size_t P0 = static_cast<size_t>(
(coords_x.size() > 3) ? p0 * (coords_x.size() - 1) : 0);
const size_t P1 = static_cast<size_t>(
(coords_x.size() > 3) ? p1 * (coords_x.size() - 1) : coords_x.size() - 1);
const Eigen::Vector3d bbox_min(coords_x[P0], coords_y[P0], coords_z[P0]);
const Eigen::Vector3d bbox_max(coords_x[P1], coords_y[P1], coords_z[P1]);
Eigen::Vector3d mean_coord(0, 0, 0);
for (size_t i = P0; i <= P1; ++i) {
mean_coord(0) += coords_x[i];
mean_coord(1) += coords_y[i];
mean_coord(2) += coords_z[i];
}
mean_coord /= P1 - P0 + 1;
// Calculate scale and translation, such that
// translation is applied before scaling.
const double old_extent = (bbox_max - bbox_min).norm();
double scale;
if (old_extent < std::numeric_limits<double>::epsilon()) {
scale = 1;
} else {
scale = extent / old_extent;
}
const Eigen::Vector3d translation = mean_coord;
// Transform images.
for (auto& image_proj_center : proj_centers) {
image_proj_center.second -= translation;
image_proj_center.second *= scale;
const Eigen::Quaterniond quat(
image_proj_center.first->Qvec(0), image_proj_center.first->Qvec(1),
image_proj_center.first->Qvec(2), image_proj_center.first->Qvec(3));
image_proj_center.first->SetTvec(quat * -image_proj_center.second);
}
// Transform points.
for (auto& point3D : points3D_) {
point3D.second.XYZ() -= translation;
point3D.second.XYZ() *= scale;
}
}
void Reconstruction::Transform(const SimilarityTransform3& tform) {
for (auto& image : images_) {
tform.TransformPose(&image.second.Qvec(), &image.second.Tvec());
}
for (auto& point3D : points3D_) {
tform.TransformPoint(&point3D.second.XYZ());
}
}
bool Reconstruction::Merge(const Reconstruction& reconstruction,
const double max_reproj_error) {
const double kMinInlierObservations = 0.3;
Eigen::Matrix3x4d alignment;
if (!ComputeAlignmentBetweenReconstructions(reconstruction, *this,
kMinInlierObservations,
max_reproj_error, &alignment)) {
return false;
}
const SimilarityTransform3 tform(alignment);
// Find common and missing images in the two reconstructions.
std::unordered_set<image_t> common_image_ids;
common_image_ids.reserve(reconstruction.NumRegImages());
std::unordered_set<image_t> missing_image_ids;
missing_image_ids.reserve(reconstruction.NumRegImages());
for (const auto& image_id : reconstruction.RegImageIds()) {
if (ExistsImage(image_id)) {
common_image_ids.insert(image_id);
} else {
missing_image_ids.insert(image_id);
}
}
// Register the missing images in this reconstruction.
for (const auto image_id : missing_image_ids) {
auto reg_image = reconstruction.Image(image_id);
reg_image.SetRegistered(false);
AddImage(reg_image);
RegisterImage(image_id);
if (!ExistsCamera(reg_image.CameraId())) {
AddCamera(reconstruction.Camera(reg_image.CameraId()));
}
auto& image = Image(image_id);
tform.TransformPose(&image.Qvec(), &image.Tvec());
}
// Merge the two point clouds using the following two rules:
// - copy points to this reconstruction with non-conflicting tracks,
// i.e. points that do not have an already triangulated observation
// in this reconstruction.
// - merge tracks that are unambiguous, i.e. only merge points in the two
// reconstructions if they have a one-to-one mapping.
// Note that in both cases no cheirality or reprojection test is performed.
for (const auto& point3D : reconstruction.Points3D()) {
Track new_track;
Track old_track;
std::set<point3D_t> old_point3D_ids;
for (const auto& track_el : point3D.second.Track().Elements()) {
if (common_image_ids.count(track_el.image_id) > 0) {
const auto& point2D =
Image(track_el.image_id).Point2D(track_el.point2D_idx);
if (point2D.HasPoint3D()) {
old_track.AddElement(track_el);
old_point3D_ids.insert(point2D.Point3DId());
} else {
new_track.AddElement(track_el);
}
} else if (missing_image_ids.count(track_el.image_id) > 0) {
Image(track_el.image_id).ResetPoint3DForPoint2D(track_el.point2D_idx);
new_track.AddElement(track_el);
}
}
const bool create_new_point = new_track.Length() >= 2;
const bool merge_new_and_old_point =
(new_track.Length() + old_track.Length()) >= 2 &&
old_point3D_ids.size() == 1;
if (create_new_point || merge_new_and_old_point) {
Eigen::Vector3d xyz = point3D.second.XYZ();
tform.TransformPoint(&xyz);
const auto point3D_id =
AddPoint3D(xyz, new_track, point3D.second.Color());
if (old_point3D_ids.size() == 1) {
MergePoints3D(point3D_id, *old_point3D_ids.begin());
}
}
}
FilterPoints3DWithLargeReprojectionError(max_reproj_error, Point3DIds());
return true;
}
bool Reconstruction::Align(const std::vector<std::string>& image_names,
const std::vector<Eigen::Vector3d>& locations,
const int min_common_images) {
CHECK_GE(min_common_images, 3);
CHECK_EQ(image_names.size(), locations.size());
// Find out which images are contained in the reconstruction and get the
// positions of their camera centers.
std::set<image_t> common_image_ids;
std::vector<Eigen::Vector3d> src;
std::vector<Eigen::Vector3d> dst;
for (size_t i = 0; i < image_names.size(); ++i) {
const class Image* image = FindImageWithName(image_names[i]);
if (image == nullptr) {
continue;
}
if (!IsImageRegistered(image->ImageId())) {
continue;
}
// Ignore duplicate images.
if (common_image_ids.count(image->ImageId()) > 0) {
continue;
}
common_image_ids.insert(image->ImageId());
src.push_back(image->ProjectionCenter());
dst.push_back(locations[i]);
}
// Only compute the alignment if there are enough correspondences.
if (common_image_ids.size() < static_cast<size_t>(min_common_images)) {
return false;
}
SimilarityTransform3 tform;
if (!tform.Estimate(src, dst)) {
return false;
}
Transform(tform);
return true;
}
bool Reconstruction::AlignRobust(const std::vector<std::string>& image_names,
const std::vector<Eigen::Vector3d>& locations,
const int min_common_images,
const RANSACOptions& ransac_options) {
CHECK_GE(min_common_images, 3);
CHECK_EQ(image_names.size(), locations.size());
// Find out which images are contained in the reconstruction and get the
// positions of their camera centers.
std::set<image_t> common_image_ids;
std::vector<Eigen::Vector3d> src;
std::vector<Eigen::Vector3d> dst;
for (size_t i = 0; i < image_names.size(); ++i) {
const class Image* image = FindImageWithName(image_names[i]);
if (image == nullptr) {
continue;
}
if (!IsImageRegistered(image->ImageId())) {
continue;
}
// Ignore duplicate images.
if (common_image_ids.count(image->ImageId()) > 0) {
continue;
}
common_image_ids.insert(image->ImageId());
src.push_back(image->ProjectionCenter());
dst.push_back(locations[i]);
}
// Only compute the alignment if there are enough correspondences.
if (common_image_ids.size() < static_cast<size_t>(min_common_images)) {
return false;
}
LORANSAC<SimilarityTransformEstimator<3>, SimilarityTransformEstimator<3>>
ransac(ransac_options);
const auto report = ransac.Estimate(src, dst);
if (report.support.num_inliers < static_cast<size_t>(min_common_images)) {
return false;
}
Transform(SimilarityTransform3(report.model));
return true;
}
const class Image* Reconstruction::FindImageWithName(
const std::string& name) const {
for (const auto& image : images_) {
if (image.second.Name() == name) {
return &image.second;
}
}
return nullptr;
}
std::vector<image_t> Reconstruction::FindCommonRegImageIds(
const Reconstruction& reconstruction) const {
std::vector<image_t> common_reg_image_ids;
for (const auto image_id : reg_image_ids_) {
if (reconstruction.ExistsImage(image_id) &&
reconstruction.IsImageRegistered(image_id)) {
CHECK_EQ(Image(image_id).Name(), reconstruction.Image(image_id).Name());
common_reg_image_ids.push_back(image_id);
}
}
return common_reg_image_ids;
}
void Reconstruction::TranscribeImageIdsToDatabase(const Database& database) {
std::unordered_map<image_t, image_t> old_to_new_image_ids;
old_to_new_image_ids.reserve(NumImages());
EIGEN_STL_UMAP(image_t, class Image) new_images;
new_images.reserve(NumImages());
for (auto& image : images_) {
if (!database.ExistsImageWithName(image.second.Name())) {
LOG(FATAL) << "Image with name " << image.second.Name()
<< " does not exist in database";
}
const auto database_image = database.ReadImageWithName(image.second.Name());
old_to_new_image_ids.emplace(image.second.ImageId(),
database_image.ImageId());
image.second.SetImageId(database_image.ImageId());
new_images.emplace(database_image.ImageId(), image.second);
}
images_ = std::move(new_images);
for (auto& image_id : reg_image_ids_) {
image_id = old_to_new_image_ids.at(image_id);
}
for (auto& point3D : points3D_) {
for (auto& track_el : point3D.second.Track().Elements()) {
track_el.image_id = old_to_new_image_ids.at(track_el.image_id);
}
}
}
size_t Reconstruction::FilterPoints3D(
const double max_reproj_error, const double min_tri_angle,
const std::unordered_set<point3D_t>& point3D_ids) {
size_t num_filtered = 0;
num_filtered +=
FilterPoints3DWithLargeReprojectionError(max_reproj_error, point3D_ids);
num_filtered +=
FilterPoints3DWithSmallTriangulationAngle(min_tri_angle, point3D_ids);
return num_filtered;
}
size_t Reconstruction::FilterPoints3DInImages(
const double max_reproj_error, const double min_tri_angle,
const std::unordered_set<image_t>& image_ids) {
std::unordered_set<point3D_t> point3D_ids;
for (const image_t image_id : image_ids) {
const class Image& image = Image(image_id);
for (const Point2D& point2D : image.Points2D()) {
if (point2D.HasPoint3D()) {
point3D_ids.insert(point2D.Point3DId());
}
}
}
return FilterPoints3D(max_reproj_error, min_tri_angle, point3D_ids);
}
size_t Reconstruction::FilterAllPoints3D(const double max_reproj_error,
const double min_tri_angle) {
// Important: First filter observations and points with large reprojection
// error, so that observations with large reprojection error do not make
// a point stable through a large triangulation angle.
const std::unordered_set<point3D_t>& point3D_ids = Point3DIds();
size_t num_filtered = 0;
num_filtered +=
FilterPoints3DWithLargeReprojectionError(max_reproj_error, point3D_ids);
num_filtered +=
FilterPoints3DWithSmallTriangulationAngle(min_tri_angle, point3D_ids);
return num_filtered;
}
size_t Reconstruction::FilterObservationsWithNegativeDepth() {
size_t num_filtered = 0;
for (const auto image_id : reg_image_ids_) {
const class Image& image = Image(image_id);
const Eigen::Matrix3x4d proj_matrix = image.ProjectionMatrix();
for (point2D_t point2D_idx = 0; point2D_idx < image.NumPoints2D();
++point2D_idx) {
const Point2D& point2D = image.Point2D(point2D_idx);
if (point2D.HasPoint3D()) {
const class Point3D& point3D = Point3D(point2D.Point3DId());
if (!HasPointPositiveDepth(proj_matrix, point3D.XYZ())) {
DeleteObservation(image_id, point2D_idx);
num_filtered += 1;
}
}
}
}
return num_filtered;
}
std::vector<image_t> Reconstruction::FilterImages(
const double min_focal_length_ratio, const double max_focal_length_ratio,
const double max_extra_param) {
std::vector<image_t> filtered_image_ids;
for (const image_t image_id : RegImageIds()) {
const class Image& image = Image(image_id);
const class Camera& camera = Camera(image.CameraId());
if (image.NumPoints3D() == 0) {
filtered_image_ids.push_back(image_id);
} else if (camera.HasBogusParams(min_focal_length_ratio,
max_focal_length_ratio, max_extra_param)) {
filtered_image_ids.push_back(image_id);
}
}
// Only de-register after iterating over reg_image_ids_ to avoid
// simultaneous iteration and modification of the vector.
for (const image_t image_id : filtered_image_ids) {
DeRegisterImage(image_id);
}
return filtered_image_ids;
}
size_t Reconstruction::ComputeNumObservations() const {
size_t num_obs = 0;
for (const image_t image_id : reg_image_ids_) {
num_obs += Image(image_id).NumPoints3D();
}
return num_obs;
}
double Reconstruction::ComputeMeanTrackLength() const {
if (points3D_.empty()) {
return 0.0;
} else {
return ComputeNumObservations() / static_cast<double>(points3D_.size());
}
}
double Reconstruction::ComputeMeanObservationsPerRegImage() const {
if (reg_image_ids_.empty()) {
return 0.0;
} else {
return ComputeNumObservations() /
static_cast<double>(reg_image_ids_.size());
}
}
double Reconstruction::ComputeMeanReprojectionError() const {
double error_sum = 0.0;
size_t num_valid_errors = 0;
for (const auto& point3D : points3D_) {
if (point3D.second.HasError()) {
error_sum += point3D.second.Error();
num_valid_errors += 1;
}
}
if (num_valid_errors == 0) {
return 0.0;
} else {
return error_sum / num_valid_errors;
}
}
void Reconstruction::Read(const std::string& path) {
if (ExistsFile(JoinPaths(path, "cameras.bin")) &&
ExistsFile(JoinPaths(path, "images.bin")) &&
ExistsFile(JoinPaths(path, "points3D.bin"))) {
ReadBinary(path);
} else if (ExistsFile(JoinPaths(path, "cameras.txt")) &&
ExistsFile(JoinPaths(path, "images.txt")) &&
ExistsFile(JoinPaths(path, "points3D.txt"))) {
ReadText(path);
} else {
LOG(FATAL) << "cameras, images, points3D files do not exist at " << path;
}
}
void Reconstruction::Write(const std::string& path) const { WriteBinary(path); }
void Reconstruction::ReadText(const std::string& path) {
ReadCamerasText(JoinPaths(path, "cameras.txt"));
ReadImagesText(JoinPaths(path, "images.txt"));
ReadPoints3DText(JoinPaths(path, "points3D.txt"));
}
void Reconstruction::ReadBinary(const std::string& path) {
ReadCamerasBinary(JoinPaths(path, "cameras.bin"));
ReadImagesBinary(JoinPaths(path, "images.bin"));
ReadPoints3DBinary(JoinPaths(path, "points3D.bin"));
}
// Modified by Javier Morlana
void Reconstruction::WriteText(const std::string& path) const {
WriteCamerasText(JoinPaths(path, "cameras.txt"));
WriteImagesText(JoinPaths(path, "images.txt"));
WritePoints3DText(JoinPaths(path, "points3D.txt"));
WriteImagesModelText(JoinPaths(path, "camerasModel.txt"));
}
// Modified by Javier Morlana
void Reconstruction::WriteBinary(const std::string& path) const {
WriteCamerasBinary(JoinPaths(path, "cameras.bin"));
WriteImagesBinary(JoinPaths(path, "images.bin"));
WritePoints3DBinary(JoinPaths(path, "points3D.bin"));
WriteImagesModelText(JoinPaths(path, "camerasModel.txt"));
}
std::vector<PlyPoint> Reconstruction::ConvertToPLY() const {
std::vector<PlyPoint> ply_points;
ply_points.reserve(points3D_.size());
for (const auto& point3D : points3D_) {
PlyPoint ply_point;
ply_point.x = point3D.second.X();
ply_point.y = point3D.second.Y();
ply_point.z = point3D.second.Z();
ply_point.r = point3D.second.Color(0);
ply_point.g = point3D.second.Color(1);
ply_point.b = point3D.second.Color(2);
ply_points.push_back(ply_point);
}
return ply_points;
}
void Reconstruction::ImportPLY(const std::string& path) {
points3D_.clear();
const auto ply_points = ReadPly(path);
points3D_.reserve(ply_points.size());
for (const auto& ply_point : ply_points) {
AddPoint3D(Eigen::Vector3d(ply_point.x, ply_point.y, ply_point.z), Track(),
Eigen::Vector3ub(ply_point.r, ply_point.g, ply_point.b));
}
}
void Reconstruction::ImportPLY(const std::vector<PlyPoint> &ply_points)
{
points3D_.clear();
points3D_.reserve(ply_points.size());
for (const auto& ply_point : ply_points) {
AddPoint3D(Eigen::Vector3d(ply_point.x, ply_point.y, ply_point.z), Track(),
Eigen::Vector3ub(ply_point.r, ply_point.g, ply_point.b));
}
}
bool Reconstruction::ExportNVM(const std::string& path) const {
std::ofstream file(path, std::ios::trunc);
CHECK(file.is_open()) << path;
// White space added for compatibility with Meshlab.
file << "NVM_V3 " << std::endl << " " << std::endl;
file << reg_image_ids_.size() << " " << std::endl;
std::unordered_map<image_t, size_t> image_id_to_idx_;
size_t image_idx = 0;
for (const auto image_id : reg_image_ids_) {
const class Image& image = Image(image_id);
const class Camera& camera = Camera(image.CameraId());
if (camera.ModelId() != SimpleRadialCameraModel::model_id) {
std::cout << "WARNING: NVM only supports `SIMPLE_RADIAL` camera model."
<< std::endl;
return false;
}
const double f =
camera.Params(SimpleRadialCameraModel::focal_length_idxs[0]);
const double k =
-1 * camera.Params(SimpleRadialCameraModel::extra_params_idxs[0]);
const Eigen::Vector3d proj_center = image.ProjectionCenter();
file << image.Name() << " ";
file << f << " ";
file << image.Qvec(0) << " ";
file << image.Qvec(1) << " ";
file << image.Qvec(2) << " ";
file << image.Qvec(3) << " ";
file << proj_center(0) << " ";
file << proj_center(1) << " ";
file << proj_center(2) << " ";
file << k << " ";
file << 0 << std::endl;
image_id_to_idx_[image_id] = image_idx;
image_idx += 1;
}
file << std::endl << points3D_.size() << std::endl;
for (const auto& point3D : points3D_) {
file << point3D.second.XYZ()(0) << " ";
file << point3D.second.XYZ()(1) << " ";
file << point3D.second.XYZ()(2) << " ";
file << static_cast<int>(point3D.second.Color(0)) << " ";
file << static_cast<int>(point3D.second.Color(1)) << " ";
file << static_cast<int>(point3D.second.Color(2)) << " ";
std::ostringstream line;
std::unordered_set<image_t> image_ids;
for (const auto& track_el : point3D.second.Track().Elements()) {
// Make sure that each point only has a single observation per image,
// since VisualSfM does not support with multiple observations.
if (image_ids.count(track_el.image_id) == 0) {
const class Image& image = Image(track_el.image_id);
const Point2D& point2D = image.Point2D(track_el.point2D_idx);
line << image_id_to_idx_[track_el.image_id] << " ";
line << track_el.point2D_idx << " ";
line << point2D.X() << " ";
line << point2D.Y() << " ";
image_ids.insert(track_el.image_id);
}
}
std::string line_string = line.str();
line_string = line_string.substr(0, line_string.size() - 1);
file << image_ids.size() << " ";
file << line_string << std::endl;
}
return true;
}
bool Reconstruction::ExportBundler(const std::string& path,
const std::string& list_path) const {
std::ofstream file(path, std::ios::trunc);
CHECK(file.is_open()) << path;
std::ofstream list_file(list_path, std::ios::trunc);
CHECK(list_file.is_open()) << list_path;
file << "# Bundle file v0.3" << std::endl;
file << reg_image_ids_.size() << " " << points3D_.size() << std::endl;
std::unordered_map<image_t, size_t> image_id_to_idx_;
size_t image_idx = 0;
for (const image_t image_id : reg_image_ids_) {
const class Image& image = Image(image_id);
const class Camera& camera = Camera(image.CameraId());
double f;
double k1;
double k2;
if (camera.ModelId() == SimplePinholeCameraModel::model_id ||
camera.ModelId() == PinholeCameraModel::model_id) {
f = camera.MeanFocalLength();
k1 = 0.0;
k2 = 0.0;
} else if (camera.ModelId() == SimpleRadialCameraModel::model_id) {
f = camera.Params(SimpleRadialCameraModel::focal_length_idxs[0]);
k1 = camera.Params(SimpleRadialCameraModel::extra_params_idxs[0]);
k2 = 0.0;
} else if (camera.ModelId() == RadialCameraModel::model_id) {
f = camera.Params(RadialCameraModel::focal_length_idxs[0]);