TwoViewReconstruction.cc 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935
  1. /**
  2. * This file is part of ORB-SLAM3
  3. *
  4. * Copyright (C) 2017-2020 Carlos Campos, Richard Elvira, Juan J. Gómez Rodríguez, José M.M. Montiel and Juan D. Tardós, University of Zaragoza.
  5. * Copyright (C) 2014-2016 Raúl Mur-Artal, José M.M. Montiel and Juan D. Tardós, University of Zaragoza.
  6. *
  7. * ORB-SLAM3 is free software: you can redistribute it and/or modify it under the terms of the GNU General Public
  8. * License as published by the Free Software Foundation, either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * ORB-SLAM3 is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
  12. * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License along with ORB-SLAM3.
  16. * If not, see <http://www.gnu.org/licenses/>.
  17. */
  18. #include "TwoViewReconstruction.h"
  19. #include "Thirdparty/DBoW2/DUtils/Random.h"
  20. #include<thread>
  21. using namespace std;
  22. namespace ORB_SLAM3
  23. {
  24. TwoViewReconstruction::TwoViewReconstruction(cv::Mat& K, float sigma, int iterations)
  25. {
  26. mK = K.clone();
  27. mSigma = sigma;
  28. mSigma2 = sigma*sigma;
  29. mMaxIterations = iterations;
  30. }
  31. bool TwoViewReconstruction::Reconstruct(const std::vector<cv::KeyPoint>& vKeys1, const std::vector<cv::KeyPoint>& vKeys2, const vector<int> &vMatches12,
  32. cv::Mat &R21, cv::Mat &t21, vector<cv::Point3f> &vP3D, vector<bool> &vbTriangulated)
  33. {
  34. mvKeys1.clear();
  35. mvKeys2.clear();
  36. mvKeys1 = vKeys1;
  37. mvKeys2 = vKeys2;
  38. // Fill structures with current keypoints and matches with reference frame
  39. // Reference Frame: 1, Current Frame: 2
  40. mvMatches12.clear();
  41. mvMatches12.reserve(mvKeys2.size());
  42. mvbMatched1.resize(mvKeys1.size());
  43. for(size_t i=0, iend=vMatches12.size();i<iend; i++)
  44. {
  45. if(vMatches12[i]>=0)
  46. {
  47. mvMatches12.push_back(make_pair(i,vMatches12[i]));
  48. mvbMatched1[i]=true;
  49. }
  50. else
  51. mvbMatched1[i]=false;
  52. }
  53. const int N = mvMatches12.size();
  54. // Indices for minimum set selection
  55. vector<size_t> vAllIndices;
  56. vAllIndices.reserve(N);
  57. vector<size_t> vAvailableIndices;
  58. for(int i=0; i<N; i++)
  59. {
  60. vAllIndices.push_back(i);
  61. }
  62. // Generate sets of 8 points for each RANSAC iteration
  63. mvSets = vector< vector<size_t> >(mMaxIterations,vector<size_t>(8,0));
  64. DUtils::Random::SeedRandOnce(0);
  65. for(int it=0; it<mMaxIterations; it++)
  66. {
  67. vAvailableIndices = vAllIndices;
  68. // Select a minimum set
  69. for(size_t j=0; j<8; j++)
  70. {
  71. int randi = DUtils::Random::RandomInt(0,vAvailableIndices.size()-1);
  72. int idx = vAvailableIndices[randi];
  73. mvSets[it][j] = idx;
  74. vAvailableIndices[randi] = vAvailableIndices.back();
  75. vAvailableIndices.pop_back();
  76. }
  77. }
  78. // Launch threads to compute in parallel a fundamental matrix and a homography
  79. vector<bool> vbMatchesInliersH, vbMatchesInliersF;
  80. float SH, SF;
  81. cv::Mat H, F;
  82. thread threadH(&TwoViewReconstruction::FindHomography,this,ref(vbMatchesInliersH), ref(SH), ref(H));
  83. thread threadF(&TwoViewReconstruction::FindFundamental,this,ref(vbMatchesInliersF), ref(SF), ref(F));
  84. // Wait until both threads have finished
  85. threadH.join();
  86. threadF.join();
  87. // Compute ratio of scores
  88. if(SH+SF == 0.f) return false;
  89. float RH = SH/(SH+SF);
  90. float minParallax = 1.0;
  91. // Try to reconstruct from homography or fundamental depending on the ratio (0.40-0.45)
  92. if(RH>0.50) // if(RH>0.40)
  93. {
  94. //cout << "Initialization from Homography" << endl;
  95. return ReconstructH(vbMatchesInliersH,H, mK,R21,t21,vP3D,vbTriangulated,minParallax,50);
  96. }
  97. else //if(pF_HF>0.6)
  98. {
  99. //cout << "Initialization from Fundamental" << endl;
  100. return ReconstructF(vbMatchesInliersF,F,mK,R21,t21,vP3D,vbTriangulated,minParallax,50);
  101. }
  102. }
  103. void TwoViewReconstruction::FindHomography(vector<bool> &vbMatchesInliers, float &score, cv::Mat &H21)
  104. {
  105. // Number of putative matches
  106. const int N = mvMatches12.size();
  107. // Normalize coordinates
  108. vector<cv::Point2f> vPn1, vPn2;
  109. cv::Mat T1, T2;
  110. Normalize(mvKeys1,vPn1, T1);
  111. Normalize(mvKeys2,vPn2, T2);
  112. cv::Mat T2inv = T2.inv();
  113. // Best Results variables
  114. score = 0.0;
  115. vbMatchesInliers = vector<bool>(N,false);
  116. // Iteration variables
  117. vector<cv::Point2f> vPn1i(8);
  118. vector<cv::Point2f> vPn2i(8);
  119. cv::Mat H21i, H12i;
  120. vector<bool> vbCurrentInliers(N,false);
  121. float currentScore;
  122. // Perform all RANSAC iterations and save the solution with highest score
  123. for(int it=0; it<mMaxIterations; it++)
  124. {
  125. // Select a minimum set
  126. for(size_t j=0; j<8; j++)
  127. {
  128. int idx = mvSets[it][j];
  129. vPn1i[j] = vPn1[mvMatches12[idx].first];
  130. vPn2i[j] = vPn2[mvMatches12[idx].second];
  131. }
  132. cv::Mat Hn = ComputeH21(vPn1i,vPn2i);
  133. H21i = T2inv*Hn*T1;
  134. H12i = H21i.inv();
  135. currentScore = CheckHomography(H21i, H12i, vbCurrentInliers, mSigma);
  136. if(currentScore>score)
  137. {
  138. H21 = H21i.clone();
  139. vbMatchesInliers = vbCurrentInliers;
  140. score = currentScore;
  141. }
  142. }
  143. }
  144. void TwoViewReconstruction::FindFundamental(vector<bool> &vbMatchesInliers, float &score, cv::Mat &F21)
  145. {
  146. // Number of putative matches
  147. const int N = vbMatchesInliers.size();
  148. // Normalize coordinates
  149. vector<cv::Point2f> vPn1, vPn2;
  150. cv::Mat T1, T2;
  151. Normalize(mvKeys1,vPn1, T1);
  152. Normalize(mvKeys2,vPn2, T2);
  153. cv::Mat T2t = T2.t();
  154. // Best Results variables
  155. score = 0.0;
  156. vbMatchesInliers = vector<bool>(N,false);
  157. // Iteration variables
  158. vector<cv::Point2f> vPn1i(8);
  159. vector<cv::Point2f> vPn2i(8);
  160. cv::Mat F21i;
  161. vector<bool> vbCurrentInliers(N,false);
  162. float currentScore;
  163. // Perform all RANSAC iterations and save the solution with highest score
  164. for(int it=0; it<mMaxIterations; it++)
  165. {
  166. // Select a minimum set
  167. for(int j=0; j<8; j++)
  168. {
  169. int idx = mvSets[it][j];
  170. vPn1i[j] = vPn1[mvMatches12[idx].first];
  171. vPn2i[j] = vPn2[mvMatches12[idx].second];
  172. }
  173. cv::Mat Fn = ComputeF21(vPn1i,vPn2i);
  174. F21i = T2t*Fn*T1;
  175. currentScore = CheckFundamental(F21i, vbCurrentInliers, mSigma);
  176. if(currentScore>score)
  177. {
  178. F21 = F21i.clone();
  179. vbMatchesInliers = vbCurrentInliers;
  180. score = currentScore;
  181. }
  182. }
  183. }
  184. cv::Mat TwoViewReconstruction::ComputeH21(const vector<cv::Point2f> &vP1, const vector<cv::Point2f> &vP2)
  185. {
  186. const int N = vP1.size();
  187. cv::Mat A(2*N,9,CV_32F);
  188. for(int i=0; i<N; i++)
  189. {
  190. const float u1 = vP1[i].x;
  191. const float v1 = vP1[i].y;
  192. const float u2 = vP2[i].x;
  193. const float v2 = vP2[i].y;
  194. A.at<float>(2*i,0) = 0.0;
  195. A.at<float>(2*i,1) = 0.0;
  196. A.at<float>(2*i,2) = 0.0;
  197. A.at<float>(2*i,3) = -u1;
  198. A.at<float>(2*i,4) = -v1;
  199. A.at<float>(2*i,5) = -1;
  200. A.at<float>(2*i,6) = v2*u1;
  201. A.at<float>(2*i,7) = v2*v1;
  202. A.at<float>(2*i,8) = v2;
  203. A.at<float>(2*i+1,0) = u1;
  204. A.at<float>(2*i+1,1) = v1;
  205. A.at<float>(2*i+1,2) = 1;
  206. A.at<float>(2*i+1,3) = 0.0;
  207. A.at<float>(2*i+1,4) = 0.0;
  208. A.at<float>(2*i+1,5) = 0.0;
  209. A.at<float>(2*i+1,6) = -u2*u1;
  210. A.at<float>(2*i+1,7) = -u2*v1;
  211. A.at<float>(2*i+1,8) = -u2;
  212. }
  213. cv::Mat u,w,vt;
  214. cv::SVDecomp(A,w,u,vt,cv::SVD::MODIFY_A | cv::SVD::FULL_UV);
  215. return vt.row(8).reshape(0, 3);
  216. }
  217. cv::Mat TwoViewReconstruction::ComputeF21(const vector<cv::Point2f> &vP1,const vector<cv::Point2f> &vP2)
  218. {
  219. const int N = vP1.size();
  220. cv::Mat A(N,9,CV_32F);
  221. for(int i=0; i<N; i++)
  222. {
  223. const float u1 = vP1[i].x;
  224. const float v1 = vP1[i].y;
  225. const float u2 = vP2[i].x;
  226. const float v2 = vP2[i].y;
  227. A.at<float>(i,0) = u2*u1;
  228. A.at<float>(i,1) = u2*v1;
  229. A.at<float>(i,2) = u2;
  230. A.at<float>(i,3) = v2*u1;
  231. A.at<float>(i,4) = v2*v1;
  232. A.at<float>(i,5) = v2;
  233. A.at<float>(i,6) = u1;
  234. A.at<float>(i,7) = v1;
  235. A.at<float>(i,8) = 1;
  236. }
  237. cv::Mat u,w,vt;
  238. cv::SVDecomp(A,w,u,vt,cv::SVD::MODIFY_A | cv::SVD::FULL_UV);
  239. cv::Mat Fpre = vt.row(8).reshape(0, 3);
  240. cv::SVDecomp(Fpre,w,u,vt,cv::SVD::MODIFY_A | cv::SVD::FULL_UV);
  241. w.at<float>(2)=0;
  242. return u*cv::Mat::diag(w)*vt;
  243. }
  244. float TwoViewReconstruction::CheckHomography(const cv::Mat &H21, const cv::Mat &H12, vector<bool> &vbMatchesInliers, float sigma)
  245. {
  246. const int N = mvMatches12.size();
  247. const float h11 = H21.at<float>(0,0);
  248. const float h12 = H21.at<float>(0,1);
  249. const float h13 = H21.at<float>(0,2);
  250. const float h21 = H21.at<float>(1,0);
  251. const float h22 = H21.at<float>(1,1);
  252. const float h23 = H21.at<float>(1,2);
  253. const float h31 = H21.at<float>(2,0);
  254. const float h32 = H21.at<float>(2,1);
  255. const float h33 = H21.at<float>(2,2);
  256. const float h11inv = H12.at<float>(0,0);
  257. const float h12inv = H12.at<float>(0,1);
  258. const float h13inv = H12.at<float>(0,2);
  259. const float h21inv = H12.at<float>(1,0);
  260. const float h22inv = H12.at<float>(1,1);
  261. const float h23inv = H12.at<float>(1,2);
  262. const float h31inv = H12.at<float>(2,0);
  263. const float h32inv = H12.at<float>(2,1);
  264. const float h33inv = H12.at<float>(2,2);
  265. vbMatchesInliers.resize(N);
  266. float score = 0;
  267. const float th = 5.991;
  268. const float invSigmaSquare = 1.0/(sigma*sigma);
  269. for(int i=0; i<N; i++)
  270. {
  271. bool bIn = true;
  272. const cv::KeyPoint &kp1 = mvKeys1[mvMatches12[i].first];
  273. const cv::KeyPoint &kp2 = mvKeys2[mvMatches12[i].second];
  274. const float u1 = kp1.pt.x;
  275. const float v1 = kp1.pt.y;
  276. const float u2 = kp2.pt.x;
  277. const float v2 = kp2.pt.y;
  278. // Reprojection error in first image
  279. // x2in1 = H12*x2
  280. const float w2in1inv = 1.0/(h31inv*u2+h32inv*v2+h33inv);
  281. const float u2in1 = (h11inv*u2+h12inv*v2+h13inv)*w2in1inv;
  282. const float v2in1 = (h21inv*u2+h22inv*v2+h23inv)*w2in1inv;
  283. const float squareDist1 = (u1-u2in1)*(u1-u2in1)+(v1-v2in1)*(v1-v2in1);
  284. const float chiSquare1 = squareDist1*invSigmaSquare;
  285. if(chiSquare1>th)
  286. bIn = false;
  287. else
  288. score += th - chiSquare1;
  289. // Reprojection error in second image
  290. // x1in2 = H21*x1
  291. const float w1in2inv = 1.0/(h31*u1+h32*v1+h33);
  292. const float u1in2 = (h11*u1+h12*v1+h13)*w1in2inv;
  293. const float v1in2 = (h21*u1+h22*v1+h23)*w1in2inv;
  294. const float squareDist2 = (u2-u1in2)*(u2-u1in2)+(v2-v1in2)*(v2-v1in2);
  295. const float chiSquare2 = squareDist2*invSigmaSquare;
  296. if(chiSquare2>th)
  297. bIn = false;
  298. else
  299. score += th - chiSquare2;
  300. if(bIn)
  301. vbMatchesInliers[i]=true;
  302. else
  303. vbMatchesInliers[i]=false;
  304. }
  305. return score;
  306. }
  307. float TwoViewReconstruction::CheckFundamental(const cv::Mat &F21, vector<bool> &vbMatchesInliers, float sigma)
  308. {
  309. const int N = mvMatches12.size();
  310. const float f11 = F21.at<float>(0,0);
  311. const float f12 = F21.at<float>(0,1);
  312. const float f13 = F21.at<float>(0,2);
  313. const float f21 = F21.at<float>(1,0);
  314. const float f22 = F21.at<float>(1,1);
  315. const float f23 = F21.at<float>(1,2);
  316. const float f31 = F21.at<float>(2,0);
  317. const float f32 = F21.at<float>(2,1);
  318. const float f33 = F21.at<float>(2,2);
  319. vbMatchesInliers.resize(N);
  320. float score = 0;
  321. const float th = 3.841;
  322. const float thScore = 5.991;
  323. const float invSigmaSquare = 1.0/(sigma*sigma);
  324. for(int i=0; i<N; i++)
  325. {
  326. bool bIn = true;
  327. const cv::KeyPoint &kp1 = mvKeys1[mvMatches12[i].first];
  328. const cv::KeyPoint &kp2 = mvKeys2[mvMatches12[i].second];
  329. const float u1 = kp1.pt.x;
  330. const float v1 = kp1.pt.y;
  331. const float u2 = kp2.pt.x;
  332. const float v2 = kp2.pt.y;
  333. // Reprojection error in second image
  334. // l2=F21x1=(a2,b2,c2)
  335. const float a2 = f11*u1+f12*v1+f13;
  336. const float b2 = f21*u1+f22*v1+f23;
  337. const float c2 = f31*u1+f32*v1+f33;
  338. const float num2 = a2*u2+b2*v2+c2;
  339. const float squareDist1 = num2*num2/(a2*a2+b2*b2);
  340. const float chiSquare1 = squareDist1*invSigmaSquare;
  341. if(chiSquare1>th)
  342. bIn = false;
  343. else
  344. score += thScore - chiSquare1;
  345. // Reprojection error in second image
  346. // l1 =x2tF21=(a1,b1,c1)
  347. const float a1 = f11*u2+f21*v2+f31;
  348. const float b1 = f12*u2+f22*v2+f32;
  349. const float c1 = f13*u2+f23*v2+f33;
  350. const float num1 = a1*u1+b1*v1+c1;
  351. const float squareDist2 = num1*num1/(a1*a1+b1*b1);
  352. const float chiSquare2 = squareDist2*invSigmaSquare;
  353. if(chiSquare2>th)
  354. bIn = false;
  355. else
  356. score += thScore - chiSquare2;
  357. if(bIn)
  358. vbMatchesInliers[i]=true;
  359. else
  360. vbMatchesInliers[i]=false;
  361. }
  362. return score;
  363. }
  364. bool TwoViewReconstruction::ReconstructF(vector<bool> &vbMatchesInliers, cv::Mat &F21, cv::Mat &K,
  365. cv::Mat &R21, cv::Mat &t21, vector<cv::Point3f> &vP3D, vector<bool> &vbTriangulated, float minParallax, int minTriangulated)
  366. {
  367. int N=0;
  368. for(size_t i=0, iend = vbMatchesInliers.size() ; i<iend; i++)
  369. if(vbMatchesInliers[i])
  370. N++;
  371. // Compute Essential Matrix from Fundamental Matrix
  372. cv::Mat E21 = K.t()*F21*K;
  373. cv::Mat R1, R2, t;
  374. // Recover the 4 motion hypotheses
  375. DecomposeE(E21,R1,R2,t);
  376. cv::Mat t1=t;
  377. cv::Mat t2=-t;
  378. // Reconstruct with the 4 hyphoteses and check
  379. vector<cv::Point3f> vP3D1, vP3D2, vP3D3, vP3D4;
  380. vector<bool> vbTriangulated1,vbTriangulated2,vbTriangulated3, vbTriangulated4;
  381. float parallax1,parallax2, parallax3, parallax4;
  382. int nGood1 = CheckRT(R1,t1,mvKeys1,mvKeys2,mvMatches12,vbMatchesInliers,K, vP3D1, 4.0*mSigma2, vbTriangulated1, parallax1);
  383. int nGood2 = CheckRT(R2,t1,mvKeys1,mvKeys2,mvMatches12,vbMatchesInliers,K, vP3D2, 4.0*mSigma2, vbTriangulated2, parallax2);
  384. int nGood3 = CheckRT(R1,t2,mvKeys1,mvKeys2,mvMatches12,vbMatchesInliers,K, vP3D3, 4.0*mSigma2, vbTriangulated3, parallax3);
  385. int nGood4 = CheckRT(R2,t2,mvKeys1,mvKeys2,mvMatches12,vbMatchesInliers,K, vP3D4, 4.0*mSigma2, vbTriangulated4, parallax4);
  386. int maxGood = max(nGood1,max(nGood2,max(nGood3,nGood4)));
  387. R21 = cv::Mat();
  388. t21 = cv::Mat();
  389. int nMinGood = max(static_cast<int>(0.9*N),minTriangulated);
  390. int nsimilar = 0;
  391. if(nGood1>0.7*maxGood)
  392. nsimilar++;
  393. if(nGood2>0.7*maxGood)
  394. nsimilar++;
  395. if(nGood3>0.7*maxGood)
  396. nsimilar++;
  397. if(nGood4>0.7*maxGood)
  398. nsimilar++;
  399. // If there is not a clear winner or not enough triangulated points reject initialization
  400. if(maxGood<nMinGood || nsimilar>1)
  401. {
  402. return false;
  403. }
  404. // If best reconstruction has enough parallax initialize
  405. if(maxGood==nGood1)
  406. {
  407. if(parallax1>minParallax)
  408. {
  409. vP3D = vP3D1;
  410. vbTriangulated = vbTriangulated1;
  411. R1.copyTo(R21);
  412. t1.copyTo(t21);
  413. return true;
  414. }
  415. }else if(maxGood==nGood2)
  416. {
  417. if(parallax2>minParallax)
  418. {
  419. vP3D = vP3D2;
  420. vbTriangulated = vbTriangulated2;
  421. R2.copyTo(R21);
  422. t1.copyTo(t21);
  423. return true;
  424. }
  425. }else if(maxGood==nGood3)
  426. {
  427. if(parallax3>minParallax)
  428. {
  429. vP3D = vP3D3;
  430. vbTriangulated = vbTriangulated3;
  431. R1.copyTo(R21);
  432. t2.copyTo(t21);
  433. return true;
  434. }
  435. }else if(maxGood==nGood4)
  436. {
  437. if(parallax4>minParallax)
  438. {
  439. vP3D = vP3D4;
  440. vbTriangulated = vbTriangulated4;
  441. R2.copyTo(R21);
  442. t2.copyTo(t21);
  443. return true;
  444. }
  445. }
  446. return false;
  447. }
  448. bool TwoViewReconstruction::ReconstructH(vector<bool> &vbMatchesInliers, cv::Mat &H21, cv::Mat &K,
  449. cv::Mat &R21, cv::Mat &t21, vector<cv::Point3f> &vP3D, vector<bool> &vbTriangulated, float minParallax, int minTriangulated)
  450. {
  451. int N=0;
  452. for(size_t i=0, iend = vbMatchesInliers.size() ; i<iend; i++)
  453. if(vbMatchesInliers[i])
  454. N++;
  455. // We recover 8 motion hypotheses using the method of Faugeras et al.
  456. // Motion and structure from motion in a piecewise planar environment.
  457. // International Journal of Pattern Recognition and Artificial Intelligence, 1988
  458. cv::Mat invK = K.inv();
  459. cv::Mat A = invK*H21*K;
  460. cv::Mat U,w,Vt,V;
  461. cv::SVD::compute(A,w,U,Vt,cv::SVD::FULL_UV);
  462. V=Vt.t();
  463. float s = cv::determinant(U)*cv::determinant(Vt);
  464. float d1 = w.at<float>(0);
  465. float d2 = w.at<float>(1);
  466. float d3 = w.at<float>(2);
  467. if(d1/d2<1.00001 || d2/d3<1.00001)
  468. {
  469. return false;
  470. }
  471. vector<cv::Mat> vR, vt, vn;
  472. vR.reserve(8);
  473. vt.reserve(8);
  474. vn.reserve(8);
  475. //n'=[x1 0 x3] 4 posibilities e1=e3=1, e1=1 e3=-1, e1=-1 e3=1, e1=e3=-1
  476. float aux1 = sqrt((d1*d1-d2*d2)/(d1*d1-d3*d3));
  477. float aux3 = sqrt((d2*d2-d3*d3)/(d1*d1-d3*d3));
  478. float x1[] = {aux1,aux1,-aux1,-aux1};
  479. float x3[] = {aux3,-aux3,aux3,-aux3};
  480. //case d'=d2
  481. float aux_stheta = sqrt((d1*d1-d2*d2)*(d2*d2-d3*d3))/((d1+d3)*d2);
  482. float ctheta = (d2*d2+d1*d3)/((d1+d3)*d2);
  483. float stheta[] = {aux_stheta, -aux_stheta, -aux_stheta, aux_stheta};
  484. for(int i=0; i<4; i++)
  485. {
  486. cv::Mat Rp=cv::Mat::eye(3,3,CV_32F);
  487. Rp.at<float>(0,0)=ctheta;
  488. Rp.at<float>(0,2)=-stheta[i];
  489. Rp.at<float>(2,0)=stheta[i];
  490. Rp.at<float>(2,2)=ctheta;
  491. cv::Mat R = s*U*Rp*Vt;
  492. vR.push_back(R);
  493. cv::Mat tp(3,1,CV_32F);
  494. tp.at<float>(0)=x1[i];
  495. tp.at<float>(1)=0;
  496. tp.at<float>(2)=-x3[i];
  497. tp*=d1-d3;
  498. cv::Mat t = U*tp;
  499. vt.push_back(t/cv::norm(t));
  500. cv::Mat np(3,1,CV_32F);
  501. np.at<float>(0)=x1[i];
  502. np.at<float>(1)=0;
  503. np.at<float>(2)=x3[i];
  504. cv::Mat n = V*np;
  505. if(n.at<float>(2)<0)
  506. n=-n;
  507. vn.push_back(n);
  508. }
  509. //case d'=-d2
  510. float aux_sphi = sqrt((d1*d1-d2*d2)*(d2*d2-d3*d3))/((d1-d3)*d2);
  511. float cphi = (d1*d3-d2*d2)/((d1-d3)*d2);
  512. float sphi[] = {aux_sphi, -aux_sphi, -aux_sphi, aux_sphi};
  513. for(int i=0; i<4; i++)
  514. {
  515. cv::Mat Rp=cv::Mat::eye(3,3,CV_32F);
  516. Rp.at<float>(0,0)=cphi;
  517. Rp.at<float>(0,2)=sphi[i];
  518. Rp.at<float>(1,1)=-1;
  519. Rp.at<float>(2,0)=sphi[i];
  520. Rp.at<float>(2,2)=-cphi;
  521. cv::Mat R = s*U*Rp*Vt;
  522. vR.push_back(R);
  523. cv::Mat tp(3,1,CV_32F);
  524. tp.at<float>(0)=x1[i];
  525. tp.at<float>(1)=0;
  526. tp.at<float>(2)=x3[i];
  527. tp*=d1+d3;
  528. cv::Mat t = U*tp;
  529. vt.push_back(t/cv::norm(t));
  530. cv::Mat np(3,1,CV_32F);
  531. np.at<float>(0)=x1[i];
  532. np.at<float>(1)=0;
  533. np.at<float>(2)=x3[i];
  534. cv::Mat n = V*np;
  535. if(n.at<float>(2)<0)
  536. n=-n;
  537. vn.push_back(n);
  538. }
  539. int bestGood = 0;
  540. int secondBestGood = 0;
  541. int bestSolutionIdx = -1;
  542. float bestParallax = -1;
  543. vector<cv::Point3f> bestP3D;
  544. vector<bool> bestTriangulated;
  545. // Instead of applying the visibility constraints proposed in the Faugeras' paper (which could fail for points seen with low parallax)
  546. // We reconstruct all hypotheses and check in terms of triangulated points and parallax
  547. for(size_t i=0; i<8; i++)
  548. {
  549. float parallaxi;
  550. vector<cv::Point3f> vP3Di;
  551. vector<bool> vbTriangulatedi;
  552. int nGood = CheckRT(vR[i],vt[i],mvKeys1,mvKeys2,mvMatches12,vbMatchesInliers,K,vP3Di, 4.0*mSigma2, vbTriangulatedi, parallaxi);
  553. if(nGood>bestGood)
  554. {
  555. secondBestGood = bestGood;
  556. bestGood = nGood;
  557. bestSolutionIdx = i;
  558. bestParallax = parallaxi;
  559. bestP3D = vP3Di;
  560. bestTriangulated = vbTriangulatedi;
  561. }
  562. else if(nGood>secondBestGood)
  563. {
  564. secondBestGood = nGood;
  565. }
  566. }
  567. if(secondBestGood<0.75*bestGood && bestParallax>=minParallax && bestGood>minTriangulated && bestGood>0.9*N)
  568. {
  569. vR[bestSolutionIdx].copyTo(R21);
  570. vt[bestSolutionIdx].copyTo(t21);
  571. vP3D = bestP3D;
  572. vbTriangulated = bestTriangulated;
  573. return true;
  574. }
  575. return false;
  576. }
  577. void TwoViewReconstruction::Triangulate(const cv::KeyPoint &kp1, const cv::KeyPoint &kp2, const cv::Mat &P1, const cv::Mat &P2, cv::Mat &x3D)
  578. {
  579. cv::Mat A(4,4,CV_32F);
  580. A.row(0) = kp1.pt.x*P1.row(2)-P1.row(0);
  581. A.row(1) = kp1.pt.y*P1.row(2)-P1.row(1);
  582. A.row(2) = kp2.pt.x*P2.row(2)-P2.row(0);
  583. A.row(3) = kp2.pt.y*P2.row(2)-P2.row(1);
  584. cv::Mat u,w,vt;
  585. cv::SVD::compute(A,w,u,vt,cv::SVD::MODIFY_A| cv::SVD::FULL_UV);
  586. x3D = vt.row(3).t();
  587. x3D = x3D.rowRange(0,3)/x3D.at<float>(3);
  588. }
  589. void TwoViewReconstruction::Normalize(const vector<cv::KeyPoint> &vKeys, vector<cv::Point2f> &vNormalizedPoints, cv::Mat &T)
  590. {
  591. float meanX = 0;
  592. float meanY = 0;
  593. const int N = vKeys.size();
  594. vNormalizedPoints.resize(N);
  595. for(int i=0; i<N; i++)
  596. {
  597. meanX += vKeys[i].pt.x;
  598. meanY += vKeys[i].pt.y;
  599. }
  600. meanX = meanX/N;
  601. meanY = meanY/N;
  602. float meanDevX = 0;
  603. float meanDevY = 0;
  604. for(int i=0; i<N; i++)
  605. {
  606. vNormalizedPoints[i].x = vKeys[i].pt.x - meanX;
  607. vNormalizedPoints[i].y = vKeys[i].pt.y - meanY;
  608. meanDevX += fabs(vNormalizedPoints[i].x);
  609. meanDevY += fabs(vNormalizedPoints[i].y);
  610. }
  611. meanDevX = meanDevX/N;
  612. meanDevY = meanDevY/N;
  613. float sX = 1.0/meanDevX;
  614. float sY = 1.0/meanDevY;
  615. for(int i=0; i<N; i++)
  616. {
  617. vNormalizedPoints[i].x = vNormalizedPoints[i].x * sX;
  618. vNormalizedPoints[i].y = vNormalizedPoints[i].y * sY;
  619. }
  620. T = cv::Mat::eye(3,3,CV_32F);
  621. T.at<float>(0,0) = sX;
  622. T.at<float>(1,1) = sY;
  623. T.at<float>(0,2) = -meanX*sX;
  624. T.at<float>(1,2) = -meanY*sY;
  625. }
  626. int TwoViewReconstruction::CheckRT(const cv::Mat &R, const cv::Mat &t, const vector<cv::KeyPoint> &vKeys1, const vector<cv::KeyPoint> &vKeys2,
  627. const vector<Match> &vMatches12, vector<bool> &vbMatchesInliers,
  628. const cv::Mat &K, vector<cv::Point3f> &vP3D, float th2, vector<bool> &vbGood, float &parallax)
  629. {
  630. // Calibration parameters
  631. const float fx = K.at<float>(0,0);
  632. const float fy = K.at<float>(1,1);
  633. const float cx = K.at<float>(0,2);
  634. const float cy = K.at<float>(1,2);
  635. vbGood = vector<bool>(vKeys1.size(),false);
  636. vP3D.resize(vKeys1.size());
  637. vector<float> vCosParallax;
  638. vCosParallax.reserve(vKeys1.size());
  639. // Camera 1 Projection Matrix K[I|0]
  640. cv::Mat P1(3,4,CV_32F,cv::Scalar(0));
  641. K.copyTo(P1.rowRange(0,3).colRange(0,3));
  642. cv::Mat O1 = cv::Mat::zeros(3,1,CV_32F);
  643. // Camera 2 Projection Matrix K[R|t]
  644. cv::Mat P2(3,4,CV_32F);
  645. R.copyTo(P2.rowRange(0,3).colRange(0,3));
  646. t.copyTo(P2.rowRange(0,3).col(3));
  647. P2 = K*P2;
  648. cv::Mat O2 = -R.t()*t;
  649. int nGood=0;
  650. for(size_t i=0, iend=vMatches12.size();i<iend;i++)
  651. {
  652. if(!vbMatchesInliers[i])
  653. continue;
  654. const cv::KeyPoint &kp1 = vKeys1[vMatches12[i].first];
  655. const cv::KeyPoint &kp2 = vKeys2[vMatches12[i].second];
  656. cv::Mat p3dC1;
  657. Triangulate(kp1,kp2,P1,P2,p3dC1);
  658. if(!isfinite(p3dC1.at<float>(0)) || !isfinite(p3dC1.at<float>(1)) || !isfinite(p3dC1.at<float>(2)))
  659. {
  660. vbGood[vMatches12[i].first]=false;
  661. continue;
  662. }
  663. // Check parallax
  664. cv::Mat normal1 = p3dC1 - O1;
  665. float dist1 = cv::norm(normal1);
  666. cv::Mat normal2 = p3dC1 - O2;
  667. float dist2 = cv::norm(normal2);
  668. float cosParallax = normal1.dot(normal2)/(dist1*dist2);
  669. // Check depth in front of first camera (only if enough parallax, as "infinite" points can easily go to negative depth)
  670. if(p3dC1.at<float>(2)<=0 && cosParallax<0.99998)
  671. continue;
  672. // Check depth in front of second camera (only if enough parallax, as "infinite" points can easily go to negative depth)
  673. cv::Mat p3dC2 = R*p3dC1+t;
  674. if(p3dC2.at<float>(2)<=0 && cosParallax<0.99998)
  675. continue;
  676. // Check reprojection error in first image
  677. float im1x, im1y;
  678. float invZ1 = 1.0/p3dC1.at<float>(2);
  679. im1x = fx*p3dC1.at<float>(0)*invZ1+cx;
  680. im1y = fy*p3dC1.at<float>(1)*invZ1+cy;
  681. float squareError1 = (im1x-kp1.pt.x)*(im1x-kp1.pt.x)+(im1y-kp1.pt.y)*(im1y-kp1.pt.y);
  682. if(squareError1>th2)
  683. continue;
  684. // Check reprojection error in second image
  685. float im2x, im2y;
  686. float invZ2 = 1.0/p3dC2.at<float>(2);
  687. im2x = fx*p3dC2.at<float>(0)*invZ2+cx;
  688. im2y = fy*p3dC2.at<float>(1)*invZ2+cy;
  689. float squareError2 = (im2x-kp2.pt.x)*(im2x-kp2.pt.x)+(im2y-kp2.pt.y)*(im2y-kp2.pt.y);
  690. if(squareError2>th2)
  691. continue;
  692. vCosParallax.push_back(cosParallax);
  693. vP3D[vMatches12[i].first] = cv::Point3f(p3dC1.at<float>(0),p3dC1.at<float>(1),p3dC1.at<float>(2));
  694. nGood++;
  695. if(cosParallax<0.99998)
  696. vbGood[vMatches12[i].first]=true;
  697. }
  698. if(nGood>0)
  699. {
  700. sort(vCosParallax.begin(),vCosParallax.end());
  701. size_t idx = min(50,int(vCosParallax.size()-1));
  702. parallax = acos(vCosParallax[idx])*180/CV_PI;
  703. }
  704. else
  705. parallax=0;
  706. return nGood;
  707. }
  708. void TwoViewReconstruction::DecomposeE(const cv::Mat &E, cv::Mat &R1, cv::Mat &R2, cv::Mat &t)
  709. {
  710. cv::Mat u,w,vt;
  711. cv::SVD::compute(E,w,u,vt);
  712. u.col(2).copyTo(t);
  713. t=t/cv::norm(t);
  714. cv::Mat W(3,3,CV_32F,cv::Scalar(0));
  715. W.at<float>(0,1)=-1;
  716. W.at<float>(1,0)=1;
  717. W.at<float>(2,2)=1;
  718. R1 = u*W*vt;
  719. if(cv::determinant(R1)<0)
  720. R1=-R1;
  721. R2 = u*W.t()*vt;
  722. if(cv::determinant(R2)<0)
  723. R2=-R2;
  724. }
  725. } //namespace ORB_SLAM