LocalMapping.cc 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488
  1. /**
  2. * This file is part of ORB-SLAM3
  3. *
  4. * Copyright (C) 2017-2020 Carlos Campos, Richard Elvira, Juan J. Gómez 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 "LocalMapping.h"
  19. #include "LoopClosing.h"
  20. #include "ORBmatcher.h"
  21. #include "Optimizer.h"
  22. #include "Converter.h"
  23. #include<mutex>
  24. #include<chrono>
  25. namespace ORB_SLAM3
  26. {
  27. LocalMapping::LocalMapping(System* pSys, Atlas *pAtlas, const float bMonocular, bool bInertial, const string &_strSeqName):
  28. mpSystem(pSys), mbMonocular(bMonocular), mbInertial(bInertial), mbResetRequested(false), mbResetRequestedActiveMap(false), mbFinishRequested(false), mbFinished(true), mpAtlas(pAtlas), bInitializing(false),
  29. mbAbortBA(false), mbStopped(false), mbStopRequested(false), mbNotStop(false), mbAcceptKeyFrames(true),
  30. mbNewInit(false), mIdxInit(0), mScale(1.0), mInitSect(0), mbNotBA1(true), mbNotBA2(true), mIdxIteration(0), infoInertial(Eigen::MatrixXd::Zero(9,9))
  31. {
  32. mnMatchesInliers = 0;
  33. mbBadImu = false;
  34. mTinit = 0.f;
  35. mNumLM = 0;
  36. mNumKFCulling=0;
  37. //DEBUG: times and data from LocalMapping in each frame
  38. strSequence = "";//_strSeqName;
  39. //f_lm.open("localMapping_times" + strSequence + ".txt");
  40. /*f_lm.open("localMapping_times.txt");
  41. f_lm << "# Timestamp KF, Num CovKFs, Num KFs, Num RecentMPs, Num MPs, processKF, MPCulling, CreateMP, SearchNeigh, BA, KFCulling, [numFixKF_LBA]" << endl;
  42. f_lm << fixed;*/
  43. }
  44. void LocalMapping::SetLoopCloser(LoopClosing* pLoopCloser)
  45. {
  46. mpLoopCloser = pLoopCloser;
  47. }
  48. void LocalMapping::SetTracker(Tracking *pTracker)
  49. {
  50. mpTracker=pTracker;
  51. }
  52. void LocalMapping::Run()
  53. {
  54. mbFinished = false;
  55. while(1)
  56. {
  57. // Tracking will see that Local Mapping is busy
  58. SetAcceptKeyFrames(false);
  59. // Check if there are keyframes in the queue
  60. if(CheckNewKeyFrames() && !mbBadImu)
  61. {
  62. // std::cout << "LM" << std::endl;
  63. std::chrono::steady_clock::time_point t0 = std::chrono::steady_clock::now();
  64. // BoW conversion and insertion in Map
  65. ProcessNewKeyFrame();
  66. std::chrono::steady_clock::time_point t1 = std::chrono::steady_clock::now();
  67. // Check recent MapPoints
  68. MapPointCulling();
  69. std::chrono::steady_clock::time_point t2 = std::chrono::steady_clock::now();
  70. // Triangulate new MapPoints
  71. CreateNewMapPoints();
  72. std::chrono::steady_clock::time_point t3 = std::chrono::steady_clock::now();
  73. // Save here:
  74. // # Cov KFs
  75. // # tot Kfs
  76. // # recent added MPs
  77. // # tot MPs
  78. // # localMPs in LBA
  79. // # fixedKFs in LBA
  80. mbAbortBA = false;
  81. if(!CheckNewKeyFrames())
  82. {
  83. // Find more matches in neighbor keyframes and fuse point duplications
  84. SearchInNeighbors();
  85. }
  86. std::chrono::steady_clock::time_point t4 = std::chrono::steady_clock::now();
  87. std::chrono::steady_clock::time_point t5 = t4, t6 = t4;
  88. // mbAbortBA = false;
  89. //DEBUG--
  90. /*f_lm << setprecision(0);
  91. f_lm << mpCurrentKeyFrame->mTimeStamp*1e9 << ",";
  92. f_lm << mpCurrentKeyFrame->GetVectorCovisibleKeyFrames().size() << ",";
  93. f_lm << mpCurrentKeyFrame->GetMap()->GetAllKeyFrames().size() << ",";
  94. f_lm << mlpRecentAddedMapPoints.size() << ",";
  95. f_lm << mpCurrentKeyFrame->GetMap()->GetAllMapPoints().size() << ",";*/
  96. //--
  97. int num_FixedKF_BA = 0;
  98. if(!CheckNewKeyFrames() && !stopRequested())
  99. {
  100. if(mpAtlas->KeyFramesInMap()>2)
  101. {
  102. if(mbInertial && mpCurrentKeyFrame->GetMap()->isImuInitialized())
  103. {
  104. float dist = cv::norm(mpCurrentKeyFrame->mPrevKF->GetCameraCenter() - mpCurrentKeyFrame->GetCameraCenter()) +
  105. cv::norm(mpCurrentKeyFrame->mPrevKF->mPrevKF->GetCameraCenter() - mpCurrentKeyFrame->mPrevKF->GetCameraCenter());
  106. if(dist>0.05)
  107. mTinit += mpCurrentKeyFrame->mTimeStamp - mpCurrentKeyFrame->mPrevKF->mTimeStamp;
  108. if(!mpCurrentKeyFrame->GetMap()->GetIniertialBA2())
  109. {
  110. if((mTinit<10.f) && (dist<0.02))
  111. {
  112. cout << "Not enough motion for initializing. Reseting..." << endl;
  113. unique_lock<mutex> lock(mMutexReset);
  114. mbResetRequestedActiveMap = true;
  115. mpMapToReset = mpCurrentKeyFrame->GetMap();
  116. mbBadImu = true;
  117. }
  118. }
  119. bool bLarge = ((mpTracker->GetMatchesInliers()>75)&&mbMonocular)||((mpTracker->GetMatchesInliers()>100)&&!mbMonocular);
  120. Optimizer::LocalInertialBA(mpCurrentKeyFrame, &mbAbortBA, mpCurrentKeyFrame->GetMap(), bLarge, !mpCurrentKeyFrame->GetMap()->GetIniertialBA2());
  121. }
  122. else
  123. {
  124. std::chrono::steady_clock::time_point begin = std::chrono::steady_clock::now();
  125. Optimizer::LocalBundleAdjustment(mpCurrentKeyFrame,&mbAbortBA, mpCurrentKeyFrame->GetMap(),num_FixedKF_BA);
  126. std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now();
  127. }
  128. }
  129. t5 = std::chrono::steady_clock::now();
  130. // Initialize IMU here
  131. if(!mpCurrentKeyFrame->GetMap()->isImuInitialized() && mbInertial)
  132. {
  133. if (mbMonocular)
  134. InitializeIMU(1e2, 1e10, true);
  135. else
  136. InitializeIMU(1e2, 1e5, true);
  137. }
  138. // Check redundant local Keyframes
  139. KeyFrameCulling();
  140. t6 = std::chrono::steady_clock::now();
  141. if ((mTinit<100.0f) && mbInertial)
  142. {
  143. if(mpCurrentKeyFrame->GetMap()->isImuInitialized() && mpTracker->mState==Tracking::OK) // Enter here everytime local-mapping is called
  144. {
  145. if(!mpCurrentKeyFrame->GetMap()->GetIniertialBA1()){
  146. if (mTinit>5.0f)
  147. {
  148. cout << "start VIBA 1" << endl;
  149. mpCurrentKeyFrame->GetMap()->SetIniertialBA1();
  150. if (mbMonocular)
  151. InitializeIMU(1.f, 1e5, true); // 1.f, 1e5
  152. else
  153. InitializeIMU(1.f, 1e5, true); // 1.f, 1e5
  154. cout << "end VIBA 1" << endl;
  155. }
  156. }
  157. //else if (mbNotBA2){
  158. else if(!mpCurrentKeyFrame->GetMap()->GetIniertialBA2()){
  159. if (mTinit>15.0f){ // 15.0f
  160. cout << "start VIBA 2" << endl;
  161. mpCurrentKeyFrame->GetMap()->SetIniertialBA2();
  162. if (mbMonocular)
  163. InitializeIMU(0.f, 0.f, true); // 0.f, 0.f
  164. else
  165. InitializeIMU(0.f, 0.f, true);
  166. cout << "end VIBA 2" << endl;
  167. }
  168. }
  169. // scale refinement
  170. if (((mpAtlas->KeyFramesInMap())<=100) &&
  171. ((mTinit>25.0f && mTinit<25.5f)||
  172. (mTinit>35.0f && mTinit<35.5f)||
  173. (mTinit>45.0f && mTinit<45.5f)||
  174. (mTinit>55.0f && mTinit<55.5f)||
  175. (mTinit>65.0f && mTinit<65.5f)||
  176. (mTinit>75.0f && mTinit<75.5f))){
  177. cout << "start scale ref" << endl;
  178. if (mbMonocular)
  179. ScaleRefinement();
  180. cout << "end scale ref" << endl;
  181. }
  182. }
  183. }
  184. }
  185. std::chrono::steady_clock::time_point t7 = std::chrono::steady_clock::now();
  186. mpLoopCloser->InsertKeyFrame(mpCurrentKeyFrame);
  187. std::chrono::steady_clock::time_point t8 = std::chrono::steady_clock::now();
  188. double t_procKF = std::chrono::duration_cast<std::chrono::duration<double,std::milli> >(t1 - t0).count();
  189. double t_MPcull = std::chrono::duration_cast<std::chrono::duration<double,std::milli> >(t2 - t1).count();
  190. double t_CheckMP = std::chrono::duration_cast<std::chrono::duration<double,std::milli> >(t3 - t2).count();
  191. double t_searchNeigh = std::chrono::duration_cast<std::chrono::duration<double,std::milli> >(t4 - t3).count();
  192. double t_Opt = std::chrono::duration_cast<std::chrono::duration<double,std::milli> >(t5 - t4).count();
  193. double t_KF_cull = std::chrono::duration_cast<std::chrono::duration<double,std::milli> >(t6 - t5).count();
  194. double t_Insert = std::chrono::duration_cast<std::chrono::duration<double,std::milli> >(t8 - t7).count();
  195. //DEBUG--
  196. /*f_lm << setprecision(6);
  197. f_lm << t_procKF << ",";
  198. f_lm << t_MPcull << ",";
  199. f_lm << t_CheckMP << ",";
  200. f_lm << t_searchNeigh << ",";
  201. f_lm << t_Opt << ",";
  202. f_lm << t_KF_cull << ",";
  203. f_lm << setprecision(0) << num_FixedKF_BA << "\n";*/
  204. //--
  205. }
  206. else if(Stop() && !mbBadImu)
  207. {
  208. // Safe area to stop
  209. while(isStopped() && !CheckFinish())
  210. {
  211. // cout << "LM: usleep if is stopped" << endl;
  212. usleep(3000);
  213. }
  214. if(CheckFinish())
  215. break;
  216. }
  217. ResetIfRequested();
  218. // Tracking will see that Local Mapping is busy
  219. SetAcceptKeyFrames(true);
  220. if(CheckFinish())
  221. break;
  222. // cout << "LM: normal usleep" << endl;
  223. usleep(3000);
  224. }
  225. //f_lm.close();
  226. SetFinish();
  227. }
  228. void LocalMapping::InsertKeyFrame(KeyFrame *pKF)
  229. {
  230. unique_lock<mutex> lock(mMutexNewKFs);
  231. mlNewKeyFrames.push_back(pKF);
  232. mbAbortBA=true;
  233. }
  234. bool LocalMapping::CheckNewKeyFrames()
  235. {
  236. unique_lock<mutex> lock(mMutexNewKFs);
  237. return(!mlNewKeyFrames.empty());
  238. }
  239. void LocalMapping::ProcessNewKeyFrame()
  240. {
  241. //cout << "ProcessNewKeyFrame: " << mlNewKeyFrames.size() << endl;
  242. {
  243. unique_lock<mutex> lock(mMutexNewKFs);
  244. mpCurrentKeyFrame = mlNewKeyFrames.front();
  245. mlNewKeyFrames.pop_front();
  246. }
  247. // Compute Bags of Words structures
  248. mpCurrentKeyFrame->ComputeBoW();
  249. // Associate MapPoints to the new keyframe and update normal and descriptor
  250. const vector<MapPoint*> vpMapPointMatches = mpCurrentKeyFrame->GetMapPointMatches();
  251. for(size_t i=0; i<vpMapPointMatches.size(); i++)
  252. {
  253. MapPoint* pMP = vpMapPointMatches[i];
  254. if(pMP)
  255. {
  256. if(!pMP->isBad())
  257. {
  258. if(!pMP->IsInKeyFrame(mpCurrentKeyFrame))
  259. {
  260. pMP->AddObservation(mpCurrentKeyFrame, i);
  261. pMP->UpdateNormalAndDepth();
  262. pMP->ComputeDistinctiveDescriptors();
  263. }
  264. else // this can only happen for new stereo points inserted by the Tracking
  265. {
  266. mlpRecentAddedMapPoints.push_back(pMP);
  267. }
  268. }
  269. }
  270. }
  271. // Update links in the Covisibility Graph
  272. mpCurrentKeyFrame->UpdateConnections();
  273. // Insert Keyframe in Map
  274. mpAtlas->AddKeyFrame(mpCurrentKeyFrame);
  275. }
  276. void LocalMapping::EmptyQueue()
  277. {
  278. while(CheckNewKeyFrames())
  279. ProcessNewKeyFrame();
  280. }
  281. void LocalMapping::MapPointCulling()
  282. {
  283. // Check Recent Added MapPoints
  284. list<MapPoint*>::iterator lit = mlpRecentAddedMapPoints.begin();
  285. const unsigned long int nCurrentKFid = mpCurrentKeyFrame->mnId;
  286. int nThObs;
  287. if(mbMonocular)
  288. nThObs = 2;
  289. else
  290. nThObs = 3; // MODIFICATION_STEREO_IMU here 3
  291. const int cnThObs = nThObs;
  292. int borrar = mlpRecentAddedMapPoints.size();
  293. while(lit!=mlpRecentAddedMapPoints.end())
  294. {
  295. MapPoint* pMP = *lit;
  296. if(pMP->isBad())
  297. lit = mlpRecentAddedMapPoints.erase(lit);
  298. else if(pMP->GetFoundRatio()<0.25f)
  299. {
  300. pMP->SetBadFlag();
  301. lit = mlpRecentAddedMapPoints.erase(lit);
  302. }
  303. else if(((int)nCurrentKFid-(int)pMP->mnFirstKFid)>=2 && pMP->Observations()<=cnThObs)
  304. {
  305. pMP->SetBadFlag();
  306. lit = mlpRecentAddedMapPoints.erase(lit);
  307. }
  308. else if(((int)nCurrentKFid-(int)pMP->mnFirstKFid)>=3)
  309. lit = mlpRecentAddedMapPoints.erase(lit);
  310. else
  311. {
  312. lit++;
  313. borrar--;
  314. }
  315. }
  316. //cout << "erase MP: " << borrar << endl;
  317. }
  318. void LocalMapping::CreateNewMapPoints()
  319. {
  320. // Retrieve neighbor keyframes in covisibility graph
  321. int nn = 10;
  322. // For stereo inertial case
  323. if(mbMonocular)
  324. nn=20;
  325. vector<KeyFrame*> vpNeighKFs = mpCurrentKeyFrame->GetBestCovisibilityKeyFrames(nn);
  326. if (mbInertial)
  327. {
  328. KeyFrame* pKF = mpCurrentKeyFrame;
  329. int count=0;
  330. while((vpNeighKFs.size()<=nn)&&(pKF->mPrevKF)&&(count++<nn))
  331. {
  332. vector<KeyFrame*>::iterator it = std::find(vpNeighKFs.begin(), vpNeighKFs.end(), pKF->mPrevKF);
  333. if(it==vpNeighKFs.end())
  334. vpNeighKFs.push_back(pKF->mPrevKF);
  335. pKF = pKF->mPrevKF;
  336. }
  337. }
  338. float th = 0.6f;
  339. ORBmatcher matcher(th,false);
  340. cv::Mat Rcw1 = mpCurrentKeyFrame->GetRotation();
  341. cv::Mat Rwc1 = Rcw1.t();
  342. cv::Mat tcw1 = mpCurrentKeyFrame->GetTranslation();
  343. cv::Mat Tcw1(3,4,CV_32F);
  344. Rcw1.copyTo(Tcw1.colRange(0,3));
  345. tcw1.copyTo(Tcw1.col(3));
  346. cv::Mat Ow1 = mpCurrentKeyFrame->GetCameraCenter();
  347. const float &fx1 = mpCurrentKeyFrame->fx;
  348. const float &fy1 = mpCurrentKeyFrame->fy;
  349. const float &cx1 = mpCurrentKeyFrame->cx;
  350. const float &cy1 = mpCurrentKeyFrame->cy;
  351. const float &invfx1 = mpCurrentKeyFrame->invfx;
  352. const float &invfy1 = mpCurrentKeyFrame->invfy;
  353. const float ratioFactor = 1.5f*mpCurrentKeyFrame->mfScaleFactor;
  354. // Search matches with epipolar restriction and triangulate
  355. for(size_t i=0; i<vpNeighKFs.size(); i++)
  356. {
  357. if(i>0 && CheckNewKeyFrames())// && (mnMatchesInliers>50))
  358. return;
  359. KeyFrame* pKF2 = vpNeighKFs[i];
  360. GeometricCamera* pCamera1 = mpCurrentKeyFrame->mpCamera, *pCamera2 = pKF2->mpCamera;
  361. // Check first that baseline is not too short
  362. cv::Mat Ow2 = pKF2->GetCameraCenter();
  363. cv::Mat vBaseline = Ow2-Ow1;
  364. const float baseline = cv::norm(vBaseline);
  365. if(!mbMonocular)
  366. {
  367. if(baseline<pKF2->mb)
  368. continue;
  369. }
  370. else
  371. {
  372. const float medianDepthKF2 = pKF2->ComputeSceneMedianDepth(2);
  373. const float ratioBaselineDepth = baseline/medianDepthKF2;
  374. if(ratioBaselineDepth<0.01)
  375. continue;
  376. }
  377. // Compute Fundamental Matrix
  378. cv::Mat F12 = ComputeF12(mpCurrentKeyFrame,pKF2);
  379. // Search matches that fullfil epipolar constraint
  380. vector<pair<size_t,size_t> > vMatchedIndices;
  381. bool bCoarse = mbInertial &&
  382. ((!mpCurrentKeyFrame->GetMap()->GetIniertialBA2() && mpCurrentKeyFrame->GetMap()->GetIniertialBA1())||
  383. mpTracker->mState==Tracking::RECENTLY_LOST);
  384. matcher.SearchForTriangulation(mpCurrentKeyFrame,pKF2,F12,vMatchedIndices,false,bCoarse);
  385. cv::Mat Rcw2 = pKF2->GetRotation();
  386. cv::Mat Rwc2 = Rcw2.t();
  387. cv::Mat tcw2 = pKF2->GetTranslation();
  388. cv::Mat Tcw2(3,4,CV_32F);
  389. Rcw2.copyTo(Tcw2.colRange(0,3));
  390. tcw2.copyTo(Tcw2.col(3));
  391. const float &fx2 = pKF2->fx;
  392. const float &fy2 = pKF2->fy;
  393. const float &cx2 = pKF2->cx;
  394. const float &cy2 = pKF2->cy;
  395. const float &invfx2 = pKF2->invfx;
  396. const float &invfy2 = pKF2->invfy;
  397. // Triangulate each match
  398. const int nmatches = vMatchedIndices.size();
  399. for(int ikp=0; ikp<nmatches; ikp++)
  400. {
  401. const int &idx1 = vMatchedIndices[ikp].first;
  402. const int &idx2 = vMatchedIndices[ikp].second;
  403. const cv::KeyPoint &kp1 = (mpCurrentKeyFrame -> NLeft == -1) ? mpCurrentKeyFrame->mvKeysUn[idx1]
  404. : (idx1 < mpCurrentKeyFrame -> NLeft) ? mpCurrentKeyFrame -> mvKeys[idx1]
  405. : mpCurrentKeyFrame -> mvKeysRight[idx1 - mpCurrentKeyFrame -> NLeft];
  406. const float kp1_ur=mpCurrentKeyFrame->mvuRight[idx1];
  407. bool bStereo1 = (!mpCurrentKeyFrame->mpCamera2 && kp1_ur>=0);
  408. const bool bRight1 = (mpCurrentKeyFrame -> NLeft == -1 || idx1 < mpCurrentKeyFrame -> NLeft) ? false
  409. : true;
  410. const cv::KeyPoint &kp2 = (pKF2 -> NLeft == -1) ? pKF2->mvKeysUn[idx2]
  411. : (idx2 < pKF2 -> NLeft) ? pKF2 -> mvKeys[idx2]
  412. : pKF2 -> mvKeysRight[idx2 - pKF2 -> NLeft];
  413. const float kp2_ur = pKF2->mvuRight[idx2];
  414. bool bStereo2 = (!pKF2->mpCamera2 && kp2_ur>=0);
  415. const bool bRight2 = (pKF2 -> NLeft == -1 || idx2 < pKF2 -> NLeft) ? false
  416. : true;
  417. if(mpCurrentKeyFrame->mpCamera2 && pKF2->mpCamera2){
  418. if(bRight1 && bRight2){
  419. Rcw1 = mpCurrentKeyFrame->GetRightRotation();
  420. Rwc1 = Rcw1.t();
  421. tcw1 = mpCurrentKeyFrame->GetRightTranslation();
  422. Tcw1 = mpCurrentKeyFrame->GetRightPose();
  423. Ow1 = mpCurrentKeyFrame->GetRightCameraCenter();
  424. Rcw2 = pKF2->GetRightRotation();
  425. Rwc2 = Rcw2.t();
  426. tcw2 = pKF2->GetRightTranslation();
  427. Tcw2 = pKF2->GetRightPose();
  428. Ow2 = pKF2->GetRightCameraCenter();
  429. pCamera1 = mpCurrentKeyFrame->mpCamera2;
  430. pCamera2 = pKF2->mpCamera2;
  431. }
  432. else if(bRight1 && !bRight2){
  433. Rcw1 = mpCurrentKeyFrame->GetRightRotation();
  434. Rwc1 = Rcw1.t();
  435. tcw1 = mpCurrentKeyFrame->GetRightTranslation();
  436. Tcw1 = mpCurrentKeyFrame->GetRightPose();
  437. Ow1 = mpCurrentKeyFrame->GetRightCameraCenter();
  438. Rcw2 = pKF2->GetRotation();
  439. Rwc2 = Rcw2.t();
  440. tcw2 = pKF2->GetTranslation();
  441. Tcw2 = pKF2->GetPose();
  442. Ow2 = pKF2->GetCameraCenter();
  443. pCamera1 = mpCurrentKeyFrame->mpCamera2;
  444. pCamera2 = pKF2->mpCamera;
  445. }
  446. else if(!bRight1 && bRight2){
  447. Rcw1 = mpCurrentKeyFrame->GetRotation();
  448. Rwc1 = Rcw1.t();
  449. tcw1 = mpCurrentKeyFrame->GetTranslation();
  450. Tcw1 = mpCurrentKeyFrame->GetPose();
  451. Ow1 = mpCurrentKeyFrame->GetCameraCenter();
  452. Rcw2 = pKF2->GetRightRotation();
  453. Rwc2 = Rcw2.t();
  454. tcw2 = pKF2->GetRightTranslation();
  455. Tcw2 = pKF2->GetRightPose();
  456. Ow2 = pKF2->GetRightCameraCenter();
  457. pCamera1 = mpCurrentKeyFrame->mpCamera;
  458. pCamera2 = pKF2->mpCamera2;
  459. }
  460. else{
  461. Rcw1 = mpCurrentKeyFrame->GetRotation();
  462. Rwc1 = Rcw1.t();
  463. tcw1 = mpCurrentKeyFrame->GetTranslation();
  464. Tcw1 = mpCurrentKeyFrame->GetPose();
  465. Ow1 = mpCurrentKeyFrame->GetCameraCenter();
  466. Rcw2 = pKF2->GetRotation();
  467. Rwc2 = Rcw2.t();
  468. tcw2 = pKF2->GetTranslation();
  469. Tcw2 = pKF2->GetPose();
  470. Ow2 = pKF2->GetCameraCenter();
  471. pCamera1 = mpCurrentKeyFrame->mpCamera;
  472. pCamera2 = pKF2->mpCamera;
  473. }
  474. }
  475. // Check parallax between rays
  476. cv::Mat xn1 = pCamera1->unprojectMat(kp1.pt);
  477. cv::Mat xn2 = pCamera2->unprojectMat(kp2.pt);
  478. cv::Mat ray1 = Rwc1*xn1;
  479. cv::Mat ray2 = Rwc2*xn2;
  480. const float cosParallaxRays = ray1.dot(ray2)/(cv::norm(ray1)*cv::norm(ray2));
  481. float cosParallaxStereo = cosParallaxRays+1;
  482. float cosParallaxStereo1 = cosParallaxStereo;
  483. float cosParallaxStereo2 = cosParallaxStereo;
  484. if(bStereo1)
  485. cosParallaxStereo1 = cos(2*atan2(mpCurrentKeyFrame->mb/2,mpCurrentKeyFrame->mvDepth[idx1]));
  486. else if(bStereo2)
  487. cosParallaxStereo2 = cos(2*atan2(pKF2->mb/2,pKF2->mvDepth[idx2]));
  488. cosParallaxStereo = min(cosParallaxStereo1,cosParallaxStereo2);
  489. cv::Mat x3D;
  490. if(cosParallaxRays<cosParallaxStereo && cosParallaxRays>0 && (bStereo1 || bStereo2 ||
  491. (cosParallaxRays<0.9998 && mbInertial) || (cosParallaxRays<0.9998 && !mbInertial)))
  492. {
  493. // Linear Triangulation Method
  494. cv::Mat A(4,4,CV_32F);
  495. A.row(0) = xn1.at<float>(0)*Tcw1.row(2)-Tcw1.row(0);
  496. A.row(1) = xn1.at<float>(1)*Tcw1.row(2)-Tcw1.row(1);
  497. A.row(2) = xn2.at<float>(0)*Tcw2.row(2)-Tcw2.row(0);
  498. A.row(3) = xn2.at<float>(1)*Tcw2.row(2)-Tcw2.row(1);
  499. cv::Mat w,u,vt;
  500. cv::SVD::compute(A,w,u,vt,cv::SVD::MODIFY_A| cv::SVD::FULL_UV);
  501. x3D = vt.row(3).t();
  502. if(x3D.at<float>(3)==0)
  503. continue;
  504. // Euclidean coordinates
  505. x3D = x3D.rowRange(0,3)/x3D.at<float>(3);
  506. }
  507. else if(bStereo1 && cosParallaxStereo1<cosParallaxStereo2)
  508. {
  509. x3D = mpCurrentKeyFrame->UnprojectStereo(idx1);
  510. }
  511. else if(bStereo2 && cosParallaxStereo2<cosParallaxStereo1)
  512. {
  513. x3D = pKF2->UnprojectStereo(idx2);
  514. }
  515. else
  516. {
  517. continue; //No stereo and very low parallax
  518. }
  519. cv::Mat x3Dt = x3D.t();
  520. if(x3Dt.empty()) continue;
  521. //Check triangulation in front of cameras
  522. float z1 = Rcw1.row(2).dot(x3Dt)+tcw1.at<float>(2);
  523. if(z1<=0)
  524. continue;
  525. float z2 = Rcw2.row(2).dot(x3Dt)+tcw2.at<float>(2);
  526. if(z2<=0)
  527. continue;
  528. //Check reprojection error in first keyframe
  529. const float &sigmaSquare1 = mpCurrentKeyFrame->mvLevelSigma2[kp1.octave];
  530. const float x1 = Rcw1.row(0).dot(x3Dt)+tcw1.at<float>(0);
  531. const float y1 = Rcw1.row(1).dot(x3Dt)+tcw1.at<float>(1);
  532. const float invz1 = 1.0/z1;
  533. if(!bStereo1)
  534. {
  535. cv::Point2f uv1 = pCamera1->project(cv::Point3f(x1,y1,z1));
  536. float errX1 = uv1.x - kp1.pt.x;
  537. float errY1 = uv1.y - kp1.pt.y;
  538. if((errX1*errX1+errY1*errY1)>5.991*sigmaSquare1)
  539. continue;
  540. }
  541. else
  542. {
  543. float u1 = fx1*x1*invz1+cx1;
  544. float u1_r = u1 - mpCurrentKeyFrame->mbf*invz1;
  545. float v1 = fy1*y1*invz1+cy1;
  546. float errX1 = u1 - kp1.pt.x;
  547. float errY1 = v1 - kp1.pt.y;
  548. float errX1_r = u1_r - kp1_ur;
  549. if((errX1*errX1+errY1*errY1+errX1_r*errX1_r)>7.8*sigmaSquare1)
  550. continue;
  551. }
  552. //Check reprojection error in second keyframe
  553. const float sigmaSquare2 = pKF2->mvLevelSigma2[kp2.octave];
  554. const float x2 = Rcw2.row(0).dot(x3Dt)+tcw2.at<float>(0);
  555. const float y2 = Rcw2.row(1).dot(x3Dt)+tcw2.at<float>(1);
  556. const float invz2 = 1.0/z2;
  557. if(!bStereo2)
  558. {
  559. cv::Point2f uv2 = pCamera2->project(cv::Point3f(x2,y2,z2));
  560. float errX2 = uv2.x - kp2.pt.x;
  561. float errY2 = uv2.y - kp2.pt.y;
  562. if((errX2*errX2+errY2*errY2)>5.991*sigmaSquare2)
  563. continue;
  564. }
  565. else
  566. {
  567. float u2 = fx2*x2*invz2+cx2;
  568. float u2_r = u2 - mpCurrentKeyFrame->mbf*invz2;
  569. float v2 = fy2*y2*invz2+cy2;
  570. float errX2 = u2 - kp2.pt.x;
  571. float errY2 = v2 - kp2.pt.y;
  572. float errX2_r = u2_r - kp2_ur;
  573. if((errX2*errX2+errY2*errY2+errX2_r*errX2_r)>7.8*sigmaSquare2)
  574. continue;
  575. }
  576. //Check scale consistency
  577. cv::Mat normal1 = x3D-Ow1;
  578. float dist1 = cv::norm(normal1);
  579. cv::Mat normal2 = x3D-Ow2;
  580. float dist2 = cv::norm(normal2);
  581. if(dist1==0 || dist2==0)
  582. continue;
  583. if(mbFarPoints && (dist1>=mThFarPoints||dist2>=mThFarPoints)) // MODIFICATION
  584. continue;
  585. const float ratioDist = dist2/dist1;
  586. const float ratioOctave = mpCurrentKeyFrame->mvScaleFactors[kp1.octave]/pKF2->mvScaleFactors[kp2.octave];
  587. if(ratioDist*ratioFactor<ratioOctave || ratioDist>ratioOctave*ratioFactor)
  588. continue;
  589. // Triangulation is succesfull
  590. MapPoint* pMP = new MapPoint(x3D,mpCurrentKeyFrame,mpAtlas->GetCurrentMap());
  591. pMP->AddObservation(mpCurrentKeyFrame,idx1);
  592. pMP->AddObservation(pKF2,idx2);
  593. mpCurrentKeyFrame->AddMapPoint(pMP,idx1);
  594. pKF2->AddMapPoint(pMP,idx2);
  595. pMP->ComputeDistinctiveDescriptors();
  596. pMP->UpdateNormalAndDepth();
  597. mpAtlas->AddMapPoint(pMP);
  598. mlpRecentAddedMapPoints.push_back(pMP);
  599. }
  600. }
  601. }
  602. void LocalMapping::SearchInNeighbors()
  603. {
  604. // Retrieve neighbor keyframes
  605. int nn = 10;
  606. if(mbMonocular)
  607. nn=20;
  608. const vector<KeyFrame*> vpNeighKFs = mpCurrentKeyFrame->GetBestCovisibilityKeyFrames(nn);
  609. vector<KeyFrame*> vpTargetKFs;
  610. for(vector<KeyFrame*>::const_iterator vit=vpNeighKFs.begin(), vend=vpNeighKFs.end(); vit!=vend; vit++)
  611. {
  612. KeyFrame* pKFi = *vit;
  613. if(pKFi->isBad() || pKFi->mnFuseTargetForKF == mpCurrentKeyFrame->mnId)
  614. continue;
  615. vpTargetKFs.push_back(pKFi);
  616. pKFi->mnFuseTargetForKF = mpCurrentKeyFrame->mnId;
  617. }
  618. // Add some covisible of covisible
  619. // Extend to some second neighbors if abort is not requested
  620. for(int i=0, imax=vpTargetKFs.size(); i<imax; i++)
  621. {
  622. const vector<KeyFrame*> vpSecondNeighKFs = vpTargetKFs[i]->GetBestCovisibilityKeyFrames(20);
  623. for(vector<KeyFrame*>::const_iterator vit2=vpSecondNeighKFs.begin(), vend2=vpSecondNeighKFs.end(); vit2!=vend2; vit2++)
  624. {
  625. KeyFrame* pKFi2 = *vit2;
  626. if(pKFi2->isBad() || pKFi2->mnFuseTargetForKF==mpCurrentKeyFrame->mnId || pKFi2->mnId==mpCurrentKeyFrame->mnId)
  627. continue;
  628. vpTargetKFs.push_back(pKFi2);
  629. pKFi2->mnFuseTargetForKF=mpCurrentKeyFrame->mnId;
  630. }
  631. if (mbAbortBA)
  632. break;
  633. }
  634. // Extend to temporal neighbors
  635. if(mbInertial)
  636. {
  637. KeyFrame* pKFi = mpCurrentKeyFrame->mPrevKF;
  638. while(vpTargetKFs.size()<20 && pKFi)
  639. {
  640. if(pKFi->isBad() || pKFi->mnFuseTargetForKF==mpCurrentKeyFrame->mnId)
  641. {
  642. pKFi = pKFi->mPrevKF;
  643. continue;
  644. }
  645. vpTargetKFs.push_back(pKFi);
  646. pKFi->mnFuseTargetForKF=mpCurrentKeyFrame->mnId;
  647. pKFi = pKFi->mPrevKF;
  648. }
  649. }
  650. // Search matches by projection from current KF in target KFs
  651. ORBmatcher matcher;
  652. vector<MapPoint*> vpMapPointMatches = mpCurrentKeyFrame->GetMapPointMatches();
  653. for(vector<KeyFrame*>::iterator vit=vpTargetKFs.begin(), vend=vpTargetKFs.end(); vit!=vend; vit++)
  654. {
  655. KeyFrame* pKFi = *vit;
  656. matcher.Fuse(pKFi,vpMapPointMatches);
  657. if(pKFi->NLeft != -1) matcher.Fuse(pKFi,vpMapPointMatches,true);
  658. }
  659. if (mbAbortBA)
  660. return;
  661. // Search matches by projection from target KFs in current KF
  662. vector<MapPoint*> vpFuseCandidates;
  663. vpFuseCandidates.reserve(vpTargetKFs.size()*vpMapPointMatches.size());
  664. for(vector<KeyFrame*>::iterator vitKF=vpTargetKFs.begin(), vendKF=vpTargetKFs.end(); vitKF!=vendKF; vitKF++)
  665. {
  666. KeyFrame* pKFi = *vitKF;
  667. vector<MapPoint*> vpMapPointsKFi = pKFi->GetMapPointMatches();
  668. for(vector<MapPoint*>::iterator vitMP=vpMapPointsKFi.begin(), vendMP=vpMapPointsKFi.end(); vitMP!=vendMP; vitMP++)
  669. {
  670. MapPoint* pMP = *vitMP;
  671. if(!pMP)
  672. continue;
  673. if(pMP->isBad() || pMP->mnFuseCandidateForKF == mpCurrentKeyFrame->mnId)
  674. continue;
  675. pMP->mnFuseCandidateForKF = mpCurrentKeyFrame->mnId;
  676. vpFuseCandidates.push_back(pMP);
  677. }
  678. }
  679. matcher.Fuse(mpCurrentKeyFrame,vpFuseCandidates);
  680. if(mpCurrentKeyFrame->NLeft != -1) matcher.Fuse(mpCurrentKeyFrame,vpFuseCandidates,true);
  681. // Update points
  682. vpMapPointMatches = mpCurrentKeyFrame->GetMapPointMatches();
  683. for(size_t i=0, iend=vpMapPointMatches.size(); i<iend; i++)
  684. {
  685. MapPoint* pMP=vpMapPointMatches[i];
  686. if(pMP)
  687. {
  688. if(!pMP->isBad())
  689. {
  690. pMP->ComputeDistinctiveDescriptors();
  691. pMP->UpdateNormalAndDepth();
  692. }
  693. }
  694. }
  695. // Update connections in covisibility graph
  696. mpCurrentKeyFrame->UpdateConnections();
  697. }
  698. cv::Mat LocalMapping::ComputeF12(KeyFrame *&pKF1, KeyFrame *&pKF2)
  699. {
  700. cv::Mat R1w = pKF1->GetRotation();
  701. cv::Mat t1w = pKF1->GetTranslation();
  702. cv::Mat R2w = pKF2->GetRotation();
  703. cv::Mat t2w = pKF2->GetTranslation();
  704. cv::Mat R12 = R1w*R2w.t();
  705. cv::Mat t12 = -R1w*R2w.t()*t2w+t1w;
  706. cv::Mat t12x = SkewSymmetricMatrix(t12);
  707. const cv::Mat &K1 = pKF1->mpCamera->toK();
  708. const cv::Mat &K2 = pKF2->mpCamera->toK();
  709. return K1.t().inv()*t12x*R12*K2.inv();
  710. }
  711. void LocalMapping::RequestStop()
  712. {
  713. unique_lock<mutex> lock(mMutexStop);
  714. mbStopRequested = true;
  715. unique_lock<mutex> lock2(mMutexNewKFs);
  716. mbAbortBA = true;
  717. }
  718. bool LocalMapping::Stop()
  719. {
  720. unique_lock<mutex> lock(mMutexStop);
  721. if(mbStopRequested && !mbNotStop)
  722. {
  723. mbStopped = true;
  724. cout << "Local Mapping STOP" << endl;
  725. return true;
  726. }
  727. return false;
  728. }
  729. bool LocalMapping::isStopped()
  730. {
  731. unique_lock<mutex> lock(mMutexStop);
  732. return mbStopped;
  733. }
  734. bool LocalMapping::stopRequested()
  735. {
  736. unique_lock<mutex> lock(mMutexStop);
  737. return mbStopRequested;
  738. }
  739. void LocalMapping::Release()
  740. {
  741. unique_lock<mutex> lock(mMutexStop);
  742. unique_lock<mutex> lock2(mMutexFinish);
  743. if(mbFinished)
  744. return;
  745. mbStopped = false;
  746. mbStopRequested = false;
  747. for(list<KeyFrame*>::iterator lit = mlNewKeyFrames.begin(), lend=mlNewKeyFrames.end(); lit!=lend; lit++)
  748. delete *lit;
  749. mlNewKeyFrames.clear();
  750. cout << "Local Mapping RELEASE" << endl;
  751. }
  752. bool LocalMapping::AcceptKeyFrames()
  753. {
  754. unique_lock<mutex> lock(mMutexAccept);
  755. return mbAcceptKeyFrames;
  756. }
  757. void LocalMapping::SetAcceptKeyFrames(bool flag)
  758. {
  759. unique_lock<mutex> lock(mMutexAccept);
  760. mbAcceptKeyFrames=flag;
  761. }
  762. bool LocalMapping::SetNotStop(bool flag)
  763. {
  764. unique_lock<mutex> lock(mMutexStop);
  765. if(flag && mbStopped)
  766. return false;
  767. mbNotStop = flag;
  768. return true;
  769. }
  770. void LocalMapping::InterruptBA()
  771. {
  772. mbAbortBA = true;
  773. }
  774. void LocalMapping::KeyFrameCulling()
  775. {
  776. // Check redundant keyframes (only local keyframes)
  777. // A keyframe is considered redundant if the 90% of the MapPoints it sees, are seen
  778. // in at least other 3 keyframes (in the same or finer scale)
  779. // We only consider close stereo points
  780. const int Nd = 21; // MODIFICATION_STEREO_IMU 20 This should be the same than that one from LIBA
  781. mpCurrentKeyFrame->UpdateBestCovisibles();
  782. vector<KeyFrame*> vpLocalKeyFrames = mpCurrentKeyFrame->GetVectorCovisibleKeyFrames();
  783. float redundant_th;
  784. if(!mbInertial)
  785. redundant_th = 0.9;
  786. else if (mbMonocular)
  787. redundant_th = 0.9;
  788. else
  789. redundant_th = 0.5;
  790. const bool bInitImu = mpAtlas->isImuInitialized();
  791. int count=0;
  792. // Compoute last KF from optimizable window:
  793. unsigned int last_ID;
  794. if (mbInertial)
  795. {
  796. int count = 0;
  797. KeyFrame* aux_KF = mpCurrentKeyFrame;
  798. while(count<Nd && aux_KF->mPrevKF)
  799. {
  800. aux_KF = aux_KF->mPrevKF;
  801. count++;
  802. }
  803. last_ID = aux_KF->mnId;
  804. }
  805. for(vector<KeyFrame*>::iterator vit=vpLocalKeyFrames.begin(), vend=vpLocalKeyFrames.end(); vit!=vend; vit++)
  806. {
  807. count++;
  808. KeyFrame* pKF = *vit;
  809. if((pKF->mnId==pKF->GetMap()->GetInitKFid()) || pKF->isBad())
  810. continue;
  811. const vector<MapPoint*> vpMapPoints = pKF->GetMapPointMatches();
  812. int nObs = 3;
  813. const int thObs=nObs;
  814. int nRedundantObservations=0;
  815. int nMPs=0;
  816. for(size_t i=0, iend=vpMapPoints.size(); i<iend; i++)
  817. {
  818. MapPoint* pMP = vpMapPoints[i];
  819. if(pMP)
  820. {
  821. if(!pMP->isBad())
  822. {
  823. if(!mbMonocular)
  824. {
  825. if(pKF->mvDepth[i]>pKF->mThDepth || pKF->mvDepth[i]<0)
  826. continue;
  827. }
  828. nMPs++;
  829. if(pMP->Observations()>thObs)
  830. {
  831. const int &scaleLevel = (pKF -> NLeft == -1) ? pKF->mvKeysUn[i].octave
  832. : (i < pKF -> NLeft) ? pKF -> mvKeys[i].octave
  833. : pKF -> mvKeysRight[i].octave;
  834. const map<KeyFrame*, tuple<int,int>> observations = pMP->GetObservations();
  835. int nObs=0;
  836. for(map<KeyFrame*, tuple<int,int>>::const_iterator mit=observations.begin(), mend=observations.end(); mit!=mend; mit++)
  837. {
  838. KeyFrame* pKFi = mit->first;
  839. if(pKFi==pKF)
  840. continue;
  841. tuple<int,int> indexes = mit->second;
  842. int leftIndex = get<0>(indexes), rightIndex = get<1>(indexes);
  843. int scaleLeveli = -1;
  844. if(pKFi -> NLeft == -1)
  845. scaleLeveli = pKFi->mvKeysUn[leftIndex].octave;
  846. else {
  847. if (leftIndex != -1) {
  848. scaleLeveli = pKFi->mvKeys[leftIndex].octave;
  849. }
  850. if (rightIndex != -1) {
  851. int rightLevel = pKFi->mvKeysRight[rightIndex - pKFi->NLeft].octave;
  852. scaleLeveli = (scaleLeveli == -1 || scaleLeveli > rightLevel) ? rightLevel
  853. : scaleLeveli;
  854. }
  855. }
  856. if(scaleLeveli<=scaleLevel+1)
  857. {
  858. nObs++;
  859. if(nObs>thObs)
  860. break;
  861. }
  862. }
  863. if(nObs>thObs)
  864. {
  865. nRedundantObservations++;
  866. }
  867. }
  868. }
  869. }
  870. }
  871. if(nRedundantObservations>redundant_th*nMPs)
  872. {
  873. if (mbInertial)
  874. {
  875. if (mpAtlas->KeyFramesInMap()<=Nd)
  876. continue;
  877. if(pKF->mnId>(mpCurrentKeyFrame->mnId-2))
  878. continue;
  879. if(pKF->mPrevKF && pKF->mNextKF)
  880. {
  881. const float t = pKF->mNextKF->mTimeStamp-pKF->mPrevKF->mTimeStamp;
  882. if((bInitImu && (pKF->mnId<last_ID) && t<3.) || (t<0.5))
  883. {
  884. pKF->mNextKF->mpImuPreintegrated->MergePrevious(pKF->mpImuPreintegrated);
  885. pKF->mNextKF->mPrevKF = pKF->mPrevKF;
  886. pKF->mPrevKF->mNextKF = pKF->mNextKF;
  887. pKF->mNextKF = NULL;
  888. pKF->mPrevKF = NULL;
  889. pKF->SetBadFlag();
  890. }
  891. else if(!mpCurrentKeyFrame->GetMap()->GetIniertialBA2() && (cv::norm(pKF->GetImuPosition()-pKF->mPrevKF->GetImuPosition())<0.02) && (t<3))
  892. {
  893. pKF->mNextKF->mpImuPreintegrated->MergePrevious(pKF->mpImuPreintegrated);
  894. pKF->mNextKF->mPrevKF = pKF->mPrevKF;
  895. pKF->mPrevKF->mNextKF = pKF->mNextKF;
  896. pKF->mNextKF = NULL;
  897. pKF->mPrevKF = NULL;
  898. pKF->SetBadFlag();
  899. }
  900. }
  901. }
  902. else
  903. {
  904. pKF->SetBadFlag();
  905. }
  906. }
  907. if((count > 20 && mbAbortBA) || count>100) // MODIFICATION originally 20 for mbabortBA check just 10 keyframes
  908. {
  909. break;
  910. }
  911. }
  912. }
  913. cv::Mat LocalMapping::SkewSymmetricMatrix(const cv::Mat &v)
  914. {
  915. return (cv::Mat_<float>(3,3) << 0, -v.at<float>(2), v.at<float>(1),
  916. v.at<float>(2), 0,-v.at<float>(0),
  917. -v.at<float>(1), v.at<float>(0), 0);
  918. }
  919. void LocalMapping::RequestReset()
  920. {
  921. {
  922. unique_lock<mutex> lock(mMutexReset);
  923. cout << "LM: Map reset recieved" << endl;
  924. mbResetRequested = true;
  925. }
  926. cout << "LM: Map reset, waiting..." << endl;
  927. while(1)
  928. {
  929. {
  930. unique_lock<mutex> lock2(mMutexReset);
  931. if(!mbResetRequested)
  932. break;
  933. }
  934. usleep(3000);
  935. }
  936. cout << "LM: Map reset, Done!!!" << endl;
  937. }
  938. void LocalMapping::RequestResetActiveMap(Map* pMap)
  939. {
  940. {
  941. unique_lock<mutex> lock(mMutexReset);
  942. cout << "LM: Active map reset recieved" << endl;
  943. mbResetRequestedActiveMap = true;
  944. mpMapToReset = pMap;
  945. }
  946. cout << "LM: Active map reset, waiting..." << endl;
  947. while(1)
  948. {
  949. {
  950. unique_lock<mutex> lock2(mMutexReset);
  951. if(!mbResetRequestedActiveMap)
  952. break;
  953. }
  954. usleep(3000);
  955. }
  956. cout << "LM: Active map reset, Done!!!" << endl;
  957. }
  958. void LocalMapping::ResetIfRequested()
  959. {
  960. bool executed_reset = false;
  961. {
  962. unique_lock<mutex> lock(mMutexReset);
  963. if(mbResetRequested)
  964. {
  965. executed_reset = true;
  966. cout << "LM: Reseting Atlas in Local Mapping..." << endl;
  967. mlNewKeyFrames.clear();
  968. mlpRecentAddedMapPoints.clear();
  969. mbResetRequested=false;
  970. mbResetRequestedActiveMap = false;
  971. // Inertial parameters
  972. mTinit = 0.f;
  973. mbNotBA2 = true;
  974. mbNotBA1 = true;
  975. mbBadImu=false;
  976. mIdxInit=0;
  977. cout << "LM: End reseting Local Mapping..." << endl;
  978. }
  979. if(mbResetRequestedActiveMap) {
  980. executed_reset = true;
  981. cout << "LM: Reseting current map in Local Mapping..." << endl;
  982. mlNewKeyFrames.clear();
  983. mlpRecentAddedMapPoints.clear();
  984. // Inertial parameters
  985. mTinit = 0.f;
  986. mbNotBA2 = true;
  987. mbNotBA1 = true;
  988. mbBadImu=false;
  989. mbResetRequestedActiveMap = false;
  990. cout << "LM: End reseting Local Mapping..." << endl;
  991. }
  992. }
  993. if(executed_reset)
  994. cout << "LM: Reset free the mutex" << endl;
  995. }
  996. void LocalMapping::RequestFinish()
  997. {
  998. unique_lock<mutex> lock(mMutexFinish);
  999. mbFinishRequested = true;
  1000. }
  1001. bool LocalMapping::CheckFinish()
  1002. {
  1003. unique_lock<mutex> lock(mMutexFinish);
  1004. return mbFinishRequested;
  1005. }
  1006. void LocalMapping::SetFinish()
  1007. {
  1008. unique_lock<mutex> lock(mMutexFinish);
  1009. mbFinished = true;
  1010. unique_lock<mutex> lock2(mMutexStop);
  1011. mbStopped = true;
  1012. }
  1013. bool LocalMapping::isFinished()
  1014. {
  1015. unique_lock<mutex> lock(mMutexFinish);
  1016. return mbFinished;
  1017. }
  1018. void LocalMapping::InitializeIMU(float priorG, float priorA, bool bFIBA)
  1019. {
  1020. if (mbResetRequested)
  1021. return;
  1022. float minTime;
  1023. int nMinKF;
  1024. if (mbMonocular)
  1025. {
  1026. minTime = 2.0;
  1027. nMinKF = 10;
  1028. }
  1029. else
  1030. {
  1031. minTime = 1.0;
  1032. nMinKF = 10;
  1033. }
  1034. if(mpAtlas->KeyFramesInMap()<nMinKF)
  1035. return;
  1036. // Retrieve all keyframe in temporal order
  1037. list<KeyFrame*> lpKF;
  1038. KeyFrame* pKF = mpCurrentKeyFrame;
  1039. while(pKF->mPrevKF)
  1040. {
  1041. lpKF.push_front(pKF);
  1042. pKF = pKF->mPrevKF;
  1043. }
  1044. lpKF.push_front(pKF);
  1045. vector<KeyFrame*> vpKF(lpKF.begin(),lpKF.end());
  1046. if(vpKF.size()<nMinKF)
  1047. return;
  1048. mFirstTs=vpKF.front()->mTimeStamp;
  1049. if(mpCurrentKeyFrame->mTimeStamp-mFirstTs<minTime)
  1050. return;
  1051. bInitializing = true;
  1052. while(CheckNewKeyFrames())
  1053. {
  1054. ProcessNewKeyFrame();
  1055. vpKF.push_back(mpCurrentKeyFrame);
  1056. lpKF.push_back(mpCurrentKeyFrame);
  1057. }
  1058. const int N = vpKF.size();
  1059. IMU::Bias b(0,0,0,0,0,0);
  1060. // Compute and KF velocities mRwg estimation
  1061. if (!mpCurrentKeyFrame->GetMap()->isImuInitialized())
  1062. {
  1063. cv::Mat cvRwg;
  1064. cv::Mat dirG = cv::Mat::zeros(3,1,CV_32F);
  1065. for(vector<KeyFrame*>::iterator itKF = vpKF.begin(); itKF!=vpKF.end(); itKF++)
  1066. {
  1067. if (!(*itKF)->mpImuPreintegrated)
  1068. continue;
  1069. if (!(*itKF)->mPrevKF)
  1070. continue;
  1071. dirG -= (*itKF)->mPrevKF->GetImuRotation()*(*itKF)->mpImuPreintegrated->GetUpdatedDeltaVelocity();
  1072. cv::Mat _vel = ((*itKF)->GetImuPosition() - (*itKF)->mPrevKF->GetImuPosition())/(*itKF)->mpImuPreintegrated->dT;
  1073. (*itKF)->SetVelocity(_vel);
  1074. (*itKF)->mPrevKF->SetVelocity(_vel);
  1075. }
  1076. dirG = dirG/cv::norm(dirG);
  1077. cv::Mat gI = (cv::Mat_<float>(3,1) << 0.0f, 0.0f, -1.0f);
  1078. cv::Mat v = gI.cross(dirG);
  1079. const float nv = cv::norm(v);
  1080. const float cosg = gI.dot(dirG);
  1081. const float ang = acos(cosg);
  1082. cv::Mat vzg = v*ang/nv;
  1083. cvRwg = IMU::ExpSO3(vzg);
  1084. mRwg = Converter::toMatrix3d(cvRwg);
  1085. mTinit = mpCurrentKeyFrame->mTimeStamp-mFirstTs;
  1086. }
  1087. else
  1088. {
  1089. mRwg = Eigen::Matrix3d::Identity();
  1090. mbg = Converter::toVector3d(mpCurrentKeyFrame->GetGyroBias());
  1091. mba = Converter::toVector3d(mpCurrentKeyFrame->GetAccBias());
  1092. }
  1093. mScale=1.0;
  1094. mInitTime = mpTracker->mLastFrame.mTimeStamp-vpKF.front()->mTimeStamp;
  1095. std::chrono::steady_clock::time_point t0 = std::chrono::steady_clock::now();
  1096. Optimizer::InertialOptimization(mpAtlas->GetCurrentMap(), mRwg, mScale, mbg, mba, mbMonocular, infoInertial, false, false, priorG, priorA);
  1097. std::chrono::steady_clock::time_point t1 = std::chrono::steady_clock::now();
  1098. /*cout << "scale after inertial-only optimization: " << mScale << endl;
  1099. cout << "bg after inertial-only optimization: " << mbg << endl;
  1100. cout << "ba after inertial-only optimization: " << mba << endl;*/
  1101. if (mScale<1e-1)
  1102. {
  1103. cout << "scale too small" << endl;
  1104. bInitializing=false;
  1105. return;
  1106. }
  1107. // Before this line we are not changing the map
  1108. unique_lock<mutex> lock(mpAtlas->GetCurrentMap()->mMutexMapUpdate);
  1109. std::chrono::steady_clock::time_point t2 = std::chrono::steady_clock::now();
  1110. if ((fabs(mScale-1.f)>0.00001)||!mbMonocular)
  1111. {
  1112. mpAtlas->GetCurrentMap()->ApplyScaledRotation(Converter::toCvMat(mRwg).t(),mScale,true);
  1113. mpTracker->UpdateFrameIMU(mScale,vpKF[0]->GetImuBias(),mpCurrentKeyFrame);
  1114. }
  1115. std::chrono::steady_clock::time_point t3 = std::chrono::steady_clock::now();
  1116. // Check if initialization OK
  1117. if (!mpAtlas->isImuInitialized())
  1118. for(int i=0;i<N;i++)
  1119. {
  1120. KeyFrame* pKF2 = vpKF[i];
  1121. pKF2->bImu = true;
  1122. }
  1123. /*cout << "Before GIBA: " << endl;
  1124. cout << "ba: " << mpCurrentKeyFrame->GetAccBias() << endl;
  1125. cout << "bg: " << mpCurrentKeyFrame->GetGyroBias() << endl;*/
  1126. std::chrono::steady_clock::time_point t4 = std::chrono::steady_clock::now();
  1127. if (bFIBA)
  1128. {
  1129. if (priorA!=0.f)
  1130. Optimizer::FullInertialBA(mpAtlas->GetCurrentMap(), 100, false, 0, NULL, true, priorG, priorA);
  1131. else
  1132. Optimizer::FullInertialBA(mpAtlas->GetCurrentMap(), 100, false, 0, NULL, false);
  1133. }
  1134. std::chrono::steady_clock::time_point t5 = std::chrono::steady_clock::now();
  1135. // If initialization is OK
  1136. mpTracker->UpdateFrameIMU(1.0,vpKF[0]->GetImuBias(),mpCurrentKeyFrame);
  1137. if (!mpAtlas->isImuInitialized())
  1138. {
  1139. cout << "IMU in Map " << mpAtlas->GetCurrentMap()->GetId() << " is initialized" << endl;
  1140. mpAtlas->SetImuInitialized();
  1141. mpTracker->t0IMU = mpTracker->mCurrentFrame.mTimeStamp;
  1142. mpCurrentKeyFrame->bImu = true;
  1143. }
  1144. mbNewInit=true;
  1145. mnKFs=vpKF.size();
  1146. mIdxInit++;
  1147. for(list<KeyFrame*>::iterator lit = mlNewKeyFrames.begin(), lend=mlNewKeyFrames.end(); lit!=lend; lit++)
  1148. {
  1149. (*lit)->SetBadFlag();
  1150. delete *lit;
  1151. }
  1152. mlNewKeyFrames.clear();
  1153. mpTracker->mState=Tracking::OK;
  1154. bInitializing = false;
  1155. /*cout << "After GIBA: " << endl;
  1156. cout << "ba: " << mpCurrentKeyFrame->GetAccBias() << endl;
  1157. cout << "bg: " << mpCurrentKeyFrame->GetGyroBias() << endl;
  1158. double t_inertial_only = std::chrono::duration_cast<std::chrono::duration<double> >(t1 - t0).count();
  1159. double t_update = std::chrono::duration_cast<std::chrono::duration<double> >(t3 - t2).count();
  1160. double t_viba = std::chrono::duration_cast<std::chrono::duration<double> >(t5 - t4).count();
  1161. cout << t_inertial_only << ", " << t_update << ", " << t_viba << endl;*/
  1162. mpCurrentKeyFrame->GetMap()->IncreaseChangeIndex();
  1163. return;
  1164. }
  1165. void LocalMapping::ScaleRefinement()
  1166. {
  1167. // Minimum number of keyframes to compute a solution
  1168. // Minimum time (seconds) between first and last keyframe to compute a solution. Make the difference between monocular and stereo
  1169. // unique_lock<mutex> lock0(mMutexImuInit);
  1170. if (mbResetRequested)
  1171. return;
  1172. // Retrieve all keyframes in temporal order
  1173. list<KeyFrame*> lpKF;
  1174. KeyFrame* pKF = mpCurrentKeyFrame;
  1175. while(pKF->mPrevKF)
  1176. {
  1177. lpKF.push_front(pKF);
  1178. pKF = pKF->mPrevKF;
  1179. }
  1180. lpKF.push_front(pKF);
  1181. vector<KeyFrame*> vpKF(lpKF.begin(),lpKF.end());
  1182. while(CheckNewKeyFrames())
  1183. {
  1184. ProcessNewKeyFrame();
  1185. vpKF.push_back(mpCurrentKeyFrame);
  1186. lpKF.push_back(mpCurrentKeyFrame);
  1187. }
  1188. const int N = vpKF.size();
  1189. mRwg = Eigen::Matrix3d::Identity();
  1190. mScale=1.0;
  1191. std::chrono::steady_clock::time_point t0 = std::chrono::steady_clock::now();
  1192. Optimizer::InertialOptimization(mpAtlas->GetCurrentMap(), mRwg, mScale);
  1193. std::chrono::steady_clock::time_point t1 = std::chrono::steady_clock::now();
  1194. if (mScale<1e-1) // 1e-1
  1195. {
  1196. cout << "scale too small" << endl;
  1197. bInitializing=false;
  1198. return;
  1199. }
  1200. // Before this line we are not changing the map
  1201. unique_lock<mutex> lock(mpAtlas->GetCurrentMap()->mMutexMapUpdate);
  1202. std::chrono::steady_clock::time_point t2 = std::chrono::steady_clock::now();
  1203. if ((fabs(mScale-1.f)>0.00001)||!mbMonocular)
  1204. {
  1205. mpAtlas->GetCurrentMap()->ApplyScaledRotation(Converter::toCvMat(mRwg).t(),mScale,true);
  1206. mpTracker->UpdateFrameIMU(mScale,mpCurrentKeyFrame->GetImuBias(),mpCurrentKeyFrame);
  1207. }
  1208. std::chrono::steady_clock::time_point t3 = std::chrono::steady_clock::now();
  1209. for(list<KeyFrame*>::iterator lit = mlNewKeyFrames.begin(), lend=mlNewKeyFrames.end(); lit!=lend; lit++)
  1210. {
  1211. (*lit)->SetBadFlag();
  1212. delete *lit;
  1213. }
  1214. mlNewKeyFrames.clear();
  1215. double t_inertial_only = std::chrono::duration_cast<std::chrono::duration<double> >(t1 - t0).count();
  1216. // To perform pose-inertial opt w.r.t. last keyframe
  1217. mpCurrentKeyFrame->GetMap()->IncreaseChangeIndex();
  1218. return;
  1219. }
  1220. bool LocalMapping::IsInitializing()
  1221. {
  1222. return bInitializing;
  1223. }
  1224. double LocalMapping::GetCurrKFTime()
  1225. {
  1226. if (mpCurrentKeyFrame)
  1227. {
  1228. return mpCurrentKeyFrame->mTimeStamp;
  1229. }
  1230. else
  1231. return 0.0;
  1232. }
  1233. KeyFrame* LocalMapping::GetCurrKF()
  1234. {
  1235. return mpCurrentKeyFrame;
  1236. }
  1237. } //namespace ORB_SLAM