-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathEstimators.h
1897 lines (1587 loc) · 64 KB
/
Estimators.h
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
#include <Eigen/Dense>
#include <GSLAM/core/Glog.h>
#include <GSLAM/core/SIM3.h>
namespace Eigen {
typedef Eigen::Matrix<double, 3, 4> Matrix3x4d;
typedef Eigen::Matrix<uint8_t, 3, 1> Vector3ub;
typedef Eigen::Matrix<uint8_t, 4, 1> Vector4ub;
typedef Eigen::Matrix<double, 6, 1> Vector6d;
} // namespace Eigen
namespace GSLAM {
// Direct linear transformation algorithm to compute the homography between
// point pairs. This algorithm computes the least squares estimate for
// the homography from at least 4 correspondences.
class HomographyMatrixEstimator {
public:
typedef Eigen::Vector2d X_t;
typedef Eigen::Vector2d Y_t;
typedef Eigen::Matrix3d M_t;
// The minimum number of samples needed to estimate a model.
static const int kMinNumSamples = 4;
// Estimate the projective transformation (homography).
//
// The number of corresponding points must be at least 4.
//
// @param points1 First set of corresponding points.
// @param points2 Second set of corresponding points.
//
// @return 3x3 homogeneous transformation matrix.
static std::vector<M_t> Estimate(const std::vector<X_t>& points1,
const std::vector<Y_t>& points2);
// Calculate the transformation error for each corresponding point pair.
//
// Residuals are defined as the squared transformation error when
// transforming the source to the destination coordinates.
//
// @param points1 First set of corresponding points.
// @param points2 Second set of corresponding points.
// @param H 3x3 projective matrix.
// @param residuals Output vector of residuals.
static void Residuals(const std::vector<X_t>& points1,
const std::vector<Y_t>& points2, const M_t& H,
std::vector<double>* residuals);
};
// Fundamental matrix estimator from corresponding point pairs.
//
// This algorithm solves the 7-Point problem and is based on the following
// paper:
//
// Zhengyou Zhang and T. Kanade, Determining the Epipolar Geometry and its
// Uncertainty: A Review, International Journal of Computer Vision, 1998.
// http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.33.4540
class FundamentalMatrixSevenPointEstimator {
public:
typedef Eigen::Vector2d X_t;
typedef Eigen::Vector2d Y_t;
typedef Eigen::Matrix3d M_t;
// The minimum number of samples needed to estimate a model.
static const int kMinNumSamples = 7;
// Estimate either 1 or 3 possible fundamental matrix solutions from a set of
// corresponding points.
//
// The number of corresponding points must be exactly 7.
//
// @param points1 First set of corresponding points.
// @param points2 Second set of corresponding points
//
// @return Up to 4 solutions as a vector of 3x3 fundamental matrices.
static std::vector<M_t> Estimate(const std::vector<X_t>& points1,
const std::vector<Y_t>& points2);
// Calculate the residuals of a set of corresponding points and a given
// fundamental matrix.
//
// Residuals are defined as the squared Sampson error.
//
// @param points1 First set of corresponding points as Nx2 matrix.
// @param points2 Second set of corresponding points as Nx2 matrix.
// @param F 3x3 fundamental matrix.
// @param residuals Output vector of residuals.
static void Residuals(const std::vector<X_t>& points1,
const std::vector<Y_t>& points2, const M_t& F,
std::vector<double>* residuals);
};
// Fundamental matrix estimator from corresponding point pairs.
//
// This algorithm solves the 8-Point problem based on the following paper:
//
// Hartley and Zisserman, Multiple View Geometry, algorithm 11.1, page 282.
class FundamentalMatrixEightPointEstimator {
public:
typedef Eigen::Vector2d X_t;
typedef Eigen::Vector2d Y_t;
typedef Eigen::Matrix3d M_t;
// The minimum number of samples needed to estimate a model.
static const int kMinNumSamples = 8;
// Estimate fundamental matrix solutions from a set of corresponding points.
//
// The number of corresponding points must be at least 8.
//
// @param points1 First set of corresponding points.
// @param points2 Second set of corresponding points
//
// @return Single solution as a vector of 3x3 fundamental matrices.
static std::vector<M_t> Estimate(const std::vector<X_t>& points1,
const std::vector<Y_t>& points2);
// Calculate the residuals of a set of corresponding points and a given
// fundamental matrix.
//
// Residuals are defined as the squared Sampson error.
//
// @param points1 First set of corresponding points as Nx2 matrix.
// @param points2 Second set of corresponding points as Nx2 matrix.
// @param F 3x3 fundamental matrix.
// @param residuals Output vector of residuals.
static void Residuals(const std::vector<X_t>& points1,
const std::vector<Y_t>& points2, const M_t& F,
std::vector<double>* residuals);
};
class EssentialMatrixFivePointEstimator {
public:
typedef Eigen::Vector2d X_t;
typedef Eigen::Vector2d Y_t;
typedef Eigen::Matrix3d M_t;
// The minimum number of samples needed to estimate a model.
static const int kMinNumSamples = 5;
// Estimate up to 10 possible essential matrix solutions from a set of
// corresponding points.
//
// The number of corresponding points must be at least 5.
//
// @param points1 First set of corresponding points.
// @param points2 Second set of corresponding points.
//
// @return Up to 10 solutions as a vector of 3x3 essential matrices.
static std::vector<M_t> Estimate(const std::vector<X_t>& points1,
const std::vector<Y_t>& points2);
// Calculate the residuals of a set of corresponding points and a given
// essential matrix.
//
// Residuals are defined as the squared Sampson error.
//
// @param points1 First set of corresponding points.
// @param points2 Second set of corresponding points.
// @param E 3x3 essential matrix.
// @param residuals Output vector of residuals.
static void Residuals(const std::vector<X_t>& points1,
const std::vector<Y_t>& points2, const M_t& E,
std::vector<double>* residuals);
};
// Essential matrix estimator from corresponding normalized point pairs.
//
// This algorithm solves the 8-Point problem based on the following paper:
//
// Hartley and Zisserman, Multiple View Geometry, algorithm 11.1, page 282.
class EssentialMatrixEightPointEstimator {
public:
typedef Eigen::Vector2d X_t;
typedef Eigen::Vector2d Y_t;
typedef Eigen::Matrix3d M_t;
// The minimum number of samples needed to estimate a model.
static const int kMinNumSamples = 8;
// Estimate essential matrix solutions from set of corresponding points.
//
// The number of corresponding points must be at least 8.
//
// @param points1 First set of corresponding points.
// @param points2 Second set of corresponding points.
static std::vector<M_t> Estimate(const std::vector<X_t>& points1,
const std::vector<Y_t>& points2);
// Calculate the residuals of a set of corresponding points and a given
// essential matrix.
//
// Residuals are defined as the squared Sampson error.
//
// @param points1 First set of corresponding points.
// @param points2 Second set of corresponding points.
// @param E 3x3 essential matrix.
// @param residuals Output vector of residuals.
static void Residuals(const std::vector<X_t>& points1,
const std::vector<Y_t>& points2, const M_t& E,
std::vector<double>* residuals);
};
// Analytic solver for the P3P (Perspective-Three-Point) problem.
//
// The algorithm is based on the following paper:
//
// X.S. Gao, X.-R. Hou, J. Tang, H.-F. Chang. Complete Solution
// Classification for the Perspective-Three-Point Problem.
// http://www.mmrc.iss.ac.cn/~xgao/paper/ieee.pdf
class P3PEstimator {
public:
// The 2D image feature observations.
typedef Eigen::Vector2d X_t;
// The observed 3D features in the world frame.
typedef Eigen::Vector3d Y_t;
// The transformation from the world to the camera frame.
typedef Eigen::Matrix3x4d M_t;
// The minimum number of samples needed to estimate a model.
static const int kMinNumSamples = 3;
// Estimate the most probable solution of the P3P problem from a set of
// three 2D-3D point correspondences.
//
// @param points2D Normalized 2D image points as 3x2 matrix.
// @param points3D 3D world points as 3x3 matrix.
//
// @return Most probable pose as length-1 vector of a 3x4 matrix.
static std::vector<M_t> Estimate(const std::vector<X_t>& points2D,
const std::vector<Y_t>& points3D);
// Calculate the squared reprojection error given a set of 2D-3D point
// correspondences and a projection matrix.
//
// @param points2D Normalized 2D image points as Nx2 matrix.
// @param points3D 3D world points as Nx3 matrix.
// @param proj_matrix 3x4 projection matrix.
// @param residuals Output vector of residuals.
static void Residuals(const std::vector<X_t>& points2D,
const std::vector<Y_t>& points3D,
const M_t& proj_matrix, std::vector<double>* residuals);
};
// EPNP solver for the PNP (Perspective-N-Point) problem. The solver needs a
// minimum of 4 2D-3D correspondences.
//
// The algorithm is based on the following paper:
//
// Lepetit, Vincent, Francesc Moreno-Noguer, and Pascal Fua.
// "Epnp: An accurate o (n) solution to the pnp problem."
// International journal of computer vision 81.2 (2009): 155-166.
//
// The implementation is based on their original open-source release, but is
// ported to Eigen and contains several improvements over the original code.
class EPNPEstimator {
public:
// The 2D image feature observations.
typedef Eigen::Vector2d X_t;
// The observed 3D features in the world frame.
typedef Eigen::Vector3d Y_t;
// The transformation from the world to the camera frame.
typedef Eigen::Matrix3x4d M_t;
// The minimum number of samples needed to estimate a model.
static const int kMinNumSamples = 4;
// Estimate the most probable solution of the P3P problem from a set of
// three 2D-3D point correspondences.
//
// @param points2D Normalized 2D image points as 3x2 matrix.
// @param points3D 3D world points as 3x3 matrix.
//
// @return Most probable pose as length-1 vector of a 3x4 matrix.
static std::vector<M_t> Estimate(const std::vector<X_t>& points2D,
const std::vector<Y_t>& points3D);
// Calculate the squared reprojection error given a set of 2D-3D point
// correspondences and a projection matrix.
//
// @param points2D Normalized 2D image points as Nx2 matrix.
// @param points3D 3D world points as Nx3 matrix.
// @param proj_matrix 3x4 projection matrix.
// @param residuals Output vector of residuals.
static void Residuals(const std::vector<X_t>& points2D,
const std::vector<Y_t>& points3D,
const M_t& proj_matrix, std::vector<double>* residuals);
private:
bool ComputePose(const std::vector<Eigen::Vector2d>& points2D,
const std::vector<Eigen::Vector3d>& points3D,
Eigen::Matrix3x4d* proj_matrix);
void ChooseControlPoints();
bool ComputeBarycentricCoordinates();
Eigen::Matrix<double, Eigen::Dynamic, 12> ComputeM();
Eigen::Matrix<double, 6, 10> ComputeL6x10(
const Eigen::Matrix<double, 12, 12>& Ut);
Eigen::Matrix<double, 6, 1> ComputeRho();
void FindBetasApprox1(const Eigen::Matrix<double, 6, 10>& L_6x10,
const Eigen::Matrix<double, 6, 1>& rho,
Eigen::Vector4d* betas);
void FindBetasApprox2(const Eigen::Matrix<double, 6, 10>& L_6x10,
const Eigen::Matrix<double, 6, 1>& rho,
Eigen::Vector4d* betas);
void FindBetasApprox3(const Eigen::Matrix<double, 6, 10>& L_6x10,
const Eigen::Matrix<double, 6, 1>& rho,
Eigen::Vector4d* betas);
void RunGaussNewton(const Eigen::Matrix<double, 6, 10>& L_6x10,
const Eigen::Matrix<double, 6, 1>& rho,
Eigen::Vector4d* betas);
double ComputeRT(const Eigen::Matrix<double, 12, 12>& Ut,
const Eigen::Vector4d& betas, Eigen::Matrix3d* R,
Eigen::Vector3d* t);
void ComputeCcs(const Eigen::Vector4d& betas,
const Eigen::Matrix<double, 12, 12>& Ut);
void ComputePcs();
void SolveForSign();
void EstimateRT(Eigen::Matrix3d* R, Eigen::Vector3d* t);
double ComputeTotalReprojectionError(const Eigen::Matrix3d& R,
const Eigen::Vector3d& t);
std::vector<Eigen::Vector2d> points2D_;
std::vector<Eigen::Vector3d> points3D_;
std::vector<Eigen::Vector3d> pcs_;
std::vector<Eigen::Vector4d> alphas_;
std::array<Eigen::Vector3d, 4> cws_;
std::array<Eigen::Vector3d, 4> ccs_;
};
class SE3PlaneEstimator {
public:
typedef pi::Point3d X_t;
typedef pi::Point3d Y_t;
typedef pi::SE3d M_t;
// The minimum number of samples needed to estimate a model.
static const int kMinNumSamples = 3;
// Estimate a plane from set of corresponding points.
//
// The number of corresponding points must be at least 3.
//
// @param points1 First set of corresponding points.
static std::vector<M_t> Estimate(const std::vector<X_t>& vv3Inliers,const std::vector<X_t>& vv3Inliers2)
{
// With these inliers, calculate mean and cov
pi::Point3d v3MeanOfInliers(0,0,0);
for(unsigned int i=0; i<vv3Inliers.size(); i++)
v3MeanOfInliers=v3MeanOfInliers+vv3Inliers[i];
v3MeanOfInliers =v3MeanOfInliers*(1.0 / vv3Inliers.size());
Eigen::Matrix3d A=Eigen::Matrix3d::Zero();
for(unsigned int i=0; i<vv3Inliers.size(); i++)
{
pi::Point3d d = vv3Inliers[i] - v3MeanOfInliers;
A(0,0)+=d.x*d.x; A(0,1)+=d.x*d.y; A(0,2)+=d.x*d.z;
A(1,0)+=d.y*d.x; A(1,1)+=d.y*d.y; A(1,2)+=d.y*d.z;
A(2,0)+=d.z*d.x; A(2,1)+=d.z*d.y; A(2,2)+=d.z*d.z;
};
// Solve for the nullspace of the constraint matrix.
Eigen::JacobiSVD<Eigen::Matrix<double, 3,3> > svd(
A, Eigen::ComputeFullV);
const Eigen::Vector3d nullspace = svd.matrixV().col(2);
auto v3BestNormal=pi::Point3d(nullspace[0],nullspace[1],nullspace[2]);
pi::Point3d vx,vy,vz;
if(v3BestNormal.z<0)
vz=-v3BestNormal;
else vz=v3BestNormal;
vx=(vz^pi::Point3d(0,-1,0)).normalize();
vy=(vz^vx);
double r[9];
r[0]=vx.x;r[1]=vy.x;r[2]=vz.x;
r[3]=vx.y;r[4]=vy.y;r[5]=vz.y;
r[6]=vx.z;r[7]=vy.z;r[8]=vz.z;
pi::SE3d se3Aligner;
se3Aligner.get_translation() = v3MeanOfInliers;
se3Aligner.get_rotation().fromMatrix(r);
return std::vector<M_t>({se3Aligner});
}
// Calculate the residuals of a set of corresponding points and a given
// essential matrix.
//
// Residuals are defined as the squared Sampson error.
//
// @param points1 First set of corresponding points.
// @param points2 Second set of corresponding points.
// @param residuals Output vector of residuals.
static void Residuals(const std::vector<X_t>& points1,
const std::vector<Y_t>& points2, const M_t& plane,
std::vector<double>* residuals)
{
auto pt2plane=plane.inverse();
residuals->resize(points1.size());
for(int i=0;i<points1.size();++i){
double e=(pt2plane*points1[i])[2];
residuals->at(i)=e*e;
}
}
};
//class Sim3Estimator{
//public:
// typedef pi::Point3d X_t;
// typedef pi::Point3d Y_t;
// typedef pi::SIM3d M_t;
// // The minimum number of samples needed to estimate a model.
// static const int kMinNumSamples = 3;
// // Estimate a plane from set of corresponding points.
// //
// // The number of corresponding points must be at least 3.
// //
// // @param points1 First set of corresponding points.
// static std::vector<M_t> Estimate(const std::vector<X_t>& from,const std::vector<Y_t>& to)
// {
// // Custom implementation of:
// // Horn 1987, Closed-form solution of absolute orientataion using unit quaternions
// // Y=M_t*X
// /// 1. Compute the centre of two point set and translate points to centre
// pi::Point3d centre_Track(0,0,0);
// pi::Point3d centre_GPS(0,0,0);
// size_t Num=from.size();
// for(size_t i=0;i<Num;i++)
// {
// centre_Track=centre_Track+from[i];
// centre_GPS =centre_GPS+to[i];
// }
// centre_Track=centre_Track/(double)Num;
// centre_GPS=centre_GPS/(double)Num;
// Eigen::Matrix<double,3,Eigen::Dynamic> X(3,Num);
// Eigen::Matrix<double,3,Eigen::Dynamic> Y(3,Num);
// for(size_t i=0;i<Num;i++)
// {
// pi::Point3d pt1=from[i];
// pi::Point3d pt2=to[i];
// pt1=pt1-centre_Track;
// pt2=pt2-centre_GPS;
// X.block(i,0,1,3)=Eigen::Vector3d(pt1.x,pt1.y,pt1.z);
// Y.block(i,0,1,3)=Eigen::Vector3d(pt2.x,pt2.y,pt2.z);
// }
// /// 2. Compute M ,N matrix
// Eigen::Matrix3d M = Y*X.transpose();
// double N11, N12, N13, N14, N22, N23, N24, N33, N34, N44;
// Eigen::Matrix4d N;
// N11 = M(0,0)+M(1,1)+M(2,2);
// N12 = M(1,2)-M(2,1);
// N13 = M(2,0)-M(0,2);
// N14 = M(0,1)-M(1,0);
// N22 = M(0,0)-M(1,1)-M(2,2);
// N23 = M(0,1)+M(1,0);
// N24 = M(2,0)+M(0,2);
// N33 = -M(0,0)+M(1,1)-M(2,2);
// N34 = M(1,2)+M(2,1);
// N44 = -M(0,0)-M(1,1)+M(2,2);
// N << N11, N12, N13, N14,
// N12, N22, N23, N24,
// N13, N23, N33, N34,
// N14, N24, N34, N44;
// /// 3. Get rotation from eigenvector of the highest eigenvalue
// Eigen::EigenSolver<Eigen::Matrix4d > eigen(N);
// const Eigen::Vector3d highestVec = eigen.pseudoEigenvectors().block(0,0,3,1);
// pi::SO3d Rxy(highestVec[0],highestVec[1],highestVec[2],highestVec[3]);
// /// 4: Rotate set 2 and compute scale
// Eigen::Matrix3d mRxy;
// Rxy.getMatrixUnsafe(mRxy);
// auto Y_=mRxy*Y;
// double XY=X.dot(Y_);
// double YY=Y_.dot(Y_);
// double scale = YY/XY;
//// /// 5. Compute translation and get SIM3
// auto Ryx=Rxy.inv();
// pi::Point3d translation = centre_GPS - (Ryx*centre_Track)*scale;
// return {pi::SIM3d(Ryx,translation,scale)};
// }
// // Calculate the residuals of a set of corresponding points and a given
// // essential matrix.
// //
// // Residuals are defined as the squared Sampson error.
// //
// // @param points1 First set of corresponding points.
// // @param points2 Second set of corresponding points.
// // @param residuals Output vector of residuals.
// static void Residuals(const std::vector<X_t>& points1,
// const std::vector<Y_t>& points2, const M_t& plane,
// std::vector<double>* residuals)
// {
// residuals->resize(points1.size());
// for(int i=0;i<points1.size();++i){
// double e=(plane.inverse()*points1[i])[2];
// residuals->at(i)=e*e;
// }
// }
//};
void CenterAndNormalizeImagePoints(const std::vector<Eigen::Vector2d>& points,
std::vector<Eigen::Vector2d>* normed_points,
Eigen::Matrix3d* matrix) {
// Calculate centroid
Eigen::Vector2d centroid(0, 0);
for (const auto point : points) {
centroid += point;
}
centroid /= points.size();
// Root mean square error to centroid of all points
double rms_mean_dist = 0;
for (const auto point : points) {
rms_mean_dist += (point - centroid).squaredNorm();
}
rms_mean_dist = std::sqrt(rms_mean_dist / points.size());
// Compose normalization matrix
const double norm_factor = std::sqrt(2.0) / rms_mean_dist;
*matrix << norm_factor, 0, -norm_factor * centroid(0), 0, norm_factor,
-norm_factor * centroid(1), 0, 0, 1;
// Apply normalization matrix
normed_points->resize(points.size());
const double M_00 = (*matrix)(0, 0);
const double M_01 = (*matrix)(0, 1);
const double M_02 = (*matrix)(0, 2);
const double M_10 = (*matrix)(1, 0);
const double M_11 = (*matrix)(1, 1);
const double M_12 = (*matrix)(1, 2);
const double M_20 = (*matrix)(2, 0);
const double M_21 = (*matrix)(2, 1);
const double M_22 = (*matrix)(2, 2);
for (size_t i = 0; i < points.size(); ++i) {
const double p_0 = points[i](0);
const double p_1 = points[i](1);
const double np_0 = M_00 * p_0 + M_01 * p_1 + M_02;
const double np_1 = M_10 * p_0 + M_11 * p_1 + M_12;
const double np_2 = M_20 * p_0 + M_21 * p_1 + M_22;
const double inv_np_2 = 1.0 / np_2;
(*normed_points)[i](0) = np_0 * inv_np_2;
(*normed_points)[i](1) = np_1 * inv_np_2;
}
}
// Remove leading zero coefficients.
Eigen::VectorXd RemoveLeadingZeros(const Eigen::VectorXd& coeffs) {
Eigen::VectorXd::Index num_zeros = 0;
for (; num_zeros < coeffs.size(); ++num_zeros) {
if (coeffs(num_zeros) != 0) {
break;
}
}
return coeffs.tail(coeffs.size() - num_zeros);
}
// Remove trailing zero coefficients.
Eigen::VectorXd RemoveTrailingZeros(const Eigen::VectorXd& coeffs) {
Eigen::VectorXd::Index num_zeros = 0;
for (; num_zeros < coeffs.size(); ++num_zeros) {
if (coeffs(coeffs.size() - 1 - num_zeros) != 0) {
break;
}
}
return coeffs.head(coeffs.size() - num_zeros);
}
bool FindLinearPolynomialRoots(const Eigen::VectorXd& coeffs,
Eigen::VectorXd* real, Eigen::VectorXd* imag) {
CHECK_EQ(coeffs.size(), 2);
if (coeffs(0) == 0) {
return false;
}
if (real != nullptr) {
real->resize(1);
(*real)(0) = -coeffs(1) / coeffs(0);
}
if (imag != nullptr) {
imag->resize(1);
(*imag)(0) = 0;
}
return true;
}
bool FindQuadraticPolynomialRoots(const Eigen::VectorXd& coeffs,
Eigen::VectorXd* real,
Eigen::VectorXd* imag) {
CHECK_EQ(coeffs.size(), 3);
const double a = coeffs(0);
if (a == 0) {
return FindLinearPolynomialRoots(coeffs.tail(2), real, imag);
}
const double b = coeffs(1);
const double c = coeffs(2);
if (b == 0 && c == 0) {
if (real != nullptr) {
real->resize(1);
(*real)(0) = 0;
}
if (imag != nullptr) {
imag->resize(1);
(*imag)(0) = 0;
}
return true;
}
const double d = b * b - 4 * a * c;
if (d >= 0) {
const double sqrt_d = std::sqrt(d);
if (real != nullptr) {
real->resize(2);
if (b >= 0) {
(*real)(0) = (-b - sqrt_d) / (2 * a);
(*real)(1) = (2 * c) / (-b - sqrt_d);
} else {
(*real)(0) = (2 * c) / (-b + sqrt_d);
(*real)(1) = (-b + sqrt_d) / (2 * a);
}
}
if (imag != nullptr) {
imag->resize(2);
imag->setZero();
}
} else {
if (real != nullptr) {
real->resize(2);
real->setConstant(-b / (2 * a));
}
if (imag != nullptr) {
imag->resize(2);
(*imag)(0) = std::sqrt(-d) / (2 * a);
(*imag)(1) = -(*imag)(0);
}
}
return true;
}
bool FindPolynomialRootsDurandKerner(const Eigen::VectorXd& coeffs_all,
Eigen::VectorXd* real,
Eigen::VectorXd* imag) {
CHECK_GE(coeffs_all.size(), 2);
const Eigen::VectorXd coeffs = RemoveLeadingZeros(coeffs_all);
const int degree = coeffs.size() - 1;
if (degree <= 0) {
return false;
} else if (degree == 1) {
return FindLinearPolynomialRoots(coeffs, real, imag);
} else if (degree == 2) {
return FindQuadraticPolynomialRoots(coeffs, real, imag);
}
// Initialize roots.
Eigen::VectorXcd roots(degree);
roots(degree - 1) = std::complex<double>(1, 0);
for (int i = degree - 2; i >= 0; --i) {
roots(i) = roots(i + 1) * std::complex<double>(1, 1);
}
// Iterative solver.
const int kMaxNumIterations = 100;
const double kMaxRootChange = 1e-10;
for (int iter = 0; iter < kMaxNumIterations; ++iter) {
double max_root_change = 0.0;
for (int i = 0; i < degree; ++i) {
const std::complex<double> root_i = roots(i);
std::complex<double> numerator = coeffs[0];
std::complex<double> denominator = coeffs[0];
for (int j = 0; j < degree; ++j) {
numerator = numerator * root_i + coeffs[j + 1];
if (i != j) {
denominator = denominator * (root_i - roots(j));
}
}
const std::complex<double> root_i_change = numerator / denominator;
roots(i) = root_i - root_i_change;
max_root_change =
std::max(max_root_change, std::abs(root_i_change.real()));
max_root_change =
std::max(max_root_change, std::abs(root_i_change.imag()));
}
// Break, if roots do not change anymore.
if (max_root_change < kMaxRootChange) {
break;
}
}
if (real != nullptr) {
real->resize(degree);
*real = roots.real();
}
if (imag != nullptr) {
imag->resize(degree);
*imag = roots.imag();
}
return true;
}
bool FindPolynomialRootsCompanionMatrix(const Eigen::VectorXd& coeffs_all,
Eigen::VectorXd* real,
Eigen::VectorXd* imag) {
CHECK_GE(coeffs_all.size(), 2);
Eigen::VectorXd coeffs = RemoveLeadingZeros(coeffs_all);
const int degree = coeffs.size() - 1;
if (degree <= 0) {
return false;
} else if (degree == 1) {
return FindLinearPolynomialRoots(coeffs, real, imag);
} else if (degree == 2) {
return FindQuadraticPolynomialRoots(coeffs, real, imag);
}
// Remove the coefficients where zero is a solution.
coeffs = RemoveTrailingZeros(coeffs);
// Check if only zero is a solution.
if (coeffs.size() == 1) {
if (real != nullptr) {
real->resize(1);
(*real)(0) = 0;
}
if (imag != nullptr) {
imag->resize(1);
(*imag)(0) = 0;
}
return true;
}
// Fill the companion matrix.
Eigen::MatrixXd C(coeffs.size() - 1, coeffs.size() - 1);
C.setZero();
for (Eigen::MatrixXd::Index i = 1; i < C.rows(); ++i) {
C(i, i - 1) = 1;
}
C.row(0) = -coeffs.tail(coeffs.size() - 1) / coeffs(0);
// Solve for the roots of the polynomial.
Eigen::EigenSolver<Eigen::MatrixXd> solver(C, false);
if (solver.info() != Eigen::Success) {
return false;
}
// If there are trailing zeros, we must add zero as a solution.
const int effective_degree =
coeffs.size() - 1 < degree ? coeffs.size() : coeffs.size() - 1;
if (real != nullptr) {
real->resize(effective_degree);
real->head(coeffs.size() - 1) = solver.eigenvalues().real();
if (effective_degree > coeffs.size() - 1) {
(*real)(real->size() - 1) = 0;
}
}
if (imag != nullptr) {
imag->resize(effective_degree);
imag->head(coeffs.size() - 1) = solver.eigenvalues().imag();
if (effective_degree > coeffs.size() - 1) {
(*imag)(imag->size() - 1) = 0;
}
}
return true;
}
void ComputeSquaredSampsonError(const std::vector<Eigen::Vector2d>& points1,
const std::vector<Eigen::Vector2d>& points2,
const Eigen::Matrix3d& E,
std::vector<double>* residuals) {
CHECK_EQ(points1.size(), points2.size());
residuals->resize(points1.size());
// Note that this code might not be as nice as Eigen expressions,
// but it is significantly faster in various tests
const double E_00 = E(0, 0);
const double E_01 = E(0, 1);
const double E_02 = E(0, 2);
const double E_10 = E(1, 0);
const double E_11 = E(1, 1);
const double E_12 = E(1, 2);
const double E_20 = E(2, 0);
const double E_21 = E(2, 1);
const double E_22 = E(2, 2);
for (size_t i = 0; i < points1.size(); ++i) {
const double x1_0 = points1[i](0);
const double x1_1 = points1[i](1);
const double x2_0 = points2[i](0);
const double x2_1 = points2[i](1);
// Ex1 = E * points1[i].homogeneous();
const double Ex1_0 = E_00 * x1_0 + E_01 * x1_1 + E_02;
const double Ex1_1 = E_10 * x1_0 + E_11 * x1_1 + E_12;
const double Ex1_2 = E_20 * x1_0 + E_21 * x1_1 + E_22;
// Etx2 = E.transpose() * points2[i].homogeneous();
const double Etx2_0 = E_00 * x2_0 + E_10 * x2_1 + E_20;
const double Etx2_1 = E_01 * x2_0 + E_11 * x2_1 + E_21;
// x2tEx1 = points2[i].homogeneous().transpose() * Ex1;
const double x2tEx1 = x2_0 * Ex1_0 + x2_1 * Ex1_1 + Ex1_2;
// Sampson distance
(*residuals)[i] =
x2tEx1 * x2tEx1 /
(Ex1_0 * Ex1_0 + Ex1_1 * Ex1_1 + Etx2_0 * Etx2_0 + Etx2_1 * Etx2_1);
}
}
void ComputeSquaredReprojectionError(
const std::vector<Eigen::Vector2d>& points2D,
const std::vector<Eigen::Vector3d>& points3D,
const Eigen::Matrix3x4d& proj_matrix, std::vector<double>* residuals) {
CHECK_EQ(points2D.size(), points3D.size());
residuals->resize(points2D.size());
// Note that this code might not be as nice as Eigen expressions,
// but it is significantly faster in various tests.
const double P_00 = proj_matrix(0, 0);
const double P_01 = proj_matrix(0, 1);
const double P_02 = proj_matrix(0, 2);
const double P_03 = proj_matrix(0, 3);
const double P_10 = proj_matrix(1, 0);
const double P_11 = proj_matrix(1, 1);
const double P_12 = proj_matrix(1, 2);
const double P_13 = proj_matrix(1, 3);
const double P_20 = proj_matrix(2, 0);
const double P_21 = proj_matrix(2, 1);
const double P_22 = proj_matrix(2, 2);
const double P_23 = proj_matrix(2, 3);
for (size_t i = 0; i < points2D.size(); ++i) {
const double X_0 = points3D[i](0);
const double X_1 = points3D[i](1);
const double X_2 = points3D[i](2);
// Project 3D point from world to camera.
const double px_2 = P_20 * X_0 + P_21 * X_1 + P_22 * X_2 + P_23;
// Check if 3D point is in front of camera.
if (px_2 > std::numeric_limits<double>::epsilon()) {
const double px_0 = P_00 * X_0 + P_01 * X_1 + P_02 * X_2 + P_03;
const double px_1 = P_10 * X_0 + P_11 * X_1 + P_12 * X_2 + P_13;
const double x_0 = points2D[i](0);
const double x_1 = points2D[i](1);
const double inv_px_2 = 1.0 / px_2;
const double dx_0 = x_0 - px_0 * inv_px_2;
const double dx_1 = x_1 - px_1 * inv_px_2;
(*residuals)[i] = dx_0 * dx_0 + dx_1 * dx_1;
} else {
(*residuals)[i] = std::numeric_limits<double>::max();
}
}
}
std::vector<HomographyMatrixEstimator::M_t> HomographyMatrixEstimator::Estimate(
const std::vector<X_t>& points1, const std::vector<Y_t>& points2) {
CHECK_EQ(points1.size(), points2.size());
const size_t N = points1.size();
// Center and normalize image points for better numerical stability.
std::vector<X_t> normed_points1;
std::vector<Y_t> normed_points2;
Eigen::Matrix3d points1_norm_matrix;
Eigen::Matrix3d points2_norm_matrix;
CenterAndNormalizeImagePoints(points1, &normed_points1, &points1_norm_matrix);
CenterAndNormalizeImagePoints(points2, &normed_points2, &points2_norm_matrix);
// Setup constraint matrix.
Eigen::Matrix<double, Eigen::Dynamic, 9> A = Eigen::MatrixXd::Zero(2 * N, 9);
for (size_t i = 0, j = N; i < points1.size(); ++i, ++j) {
const double s_0 = normed_points1[i](0);
const double s_1 = normed_points1[i](1);
const double d_0 = normed_points2[i](0);
const double d_1 = normed_points2[i](1);
A(i, 0) = -s_0;
A(i, 1) = -s_1;
A(i, 2) = -1;
A(i, 6) = s_0 * d_0;
A(i, 7) = s_1 * d_0;
A(i, 8) = d_0;
A(j, 3) = -s_0;
A(j, 4) = -s_1;
A(j, 5) = -1;
A(j, 6) = s_0 * d_1;
A(j, 7) = s_1 * d_1;
A(j, 8) = d_1;
}
// Solve for the nullspace of the constraint matrix.
Eigen::JacobiSVD<Eigen::Matrix<double, Eigen::Dynamic, 9>> svd(
A, Eigen::ComputeFullV);
const Eigen::VectorXd nullspace = svd.matrixV().col(8);
Eigen::Map<const Eigen::Matrix3d> H_t(nullspace.data());
const std::vector<M_t> models = {points2_norm_matrix.inverse() *
H_t.transpose() * points1_norm_matrix};
return models;
}
void HomographyMatrixEstimator::Residuals(const std::vector<X_t>& points1,
const std::vector<Y_t>& points2,
const M_t& H,
std::vector<double>* residuals) {
CHECK_EQ(points1.size(), points2.size());
residuals->resize(points1.size());
// Note that this code might not be as nice as Eigen expressions,
// but it is significantly faster in various tests.
const double H_00 = H(0, 0);
const double H_01 = H(0, 1);
const double H_02 = H(0, 2);
const double H_10 = H(1, 0);
const double H_11 = H(1, 1);
const double H_12 = H(1, 2);
const double H_20 = H(2, 0);
const double H_21 = H(2, 1);
const double H_22 = H(2, 2);
for (size_t i = 0; i < points1.size(); ++i) {
const double s_0 = points1[i](0);
const double s_1 = points1[i](1);
const double d_0 = points2[i](0);
const double d_1 = points2[i](1);
const double pd_0 = H_00 * s_0 + H_01 * s_1 + H_02;
const double pd_1 = H_10 * s_0 + H_11 * s_1 + H_12;
const double pd_2 = H_20 * s_0 + H_21 * s_1 + H_22;
const double inv_pd_2 = 1.0 / pd_2;
const double dd_0 = d_0 - pd_0 * inv_pd_2;
const double dd_1 = d_1 - pd_1 * inv_pd_2;