Tracking.cc 108 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345
  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 "Tracking.h"
  19. #include<opencv2/core/core.hpp>
  20. #include<opencv2/features2d/features2d.hpp>
  21. #include"ORBmatcher.h"
  22. #include"FrameDrawer.h"
  23. #include"Converter.h"
  24. #include"Initializer.h"
  25. #include"G2oTypes.h"
  26. #include"Optimizer.h"
  27. #include"PnPsolver.h"
  28. #include<iostream>
  29. #include<mutex>
  30. #include<chrono>
  31. #include <include/CameraModels/Pinhole.h>
  32. #include <include/CameraModels/KannalaBrandt8.h>
  33. #include <include/MLPnPsolver.h>
  34. using namespace std;
  35. namespace ORB_SLAM3
  36. {
  37. Tracking::Tracking(System *pSys, ORBVocabulary* pVoc, FrameDrawer *pFrameDrawer, MapDrawer *pMapDrawer, Atlas *pAtlas, KeyFrameDatabase* pKFDB, const string &strSettingPath, const int sensor, const string &_nameSeq):
  38. mState(NO_IMAGES_YET), mSensor(sensor), mTrackedFr(0), mbStep(false),
  39. mbOnlyTracking(false), mbMapUpdated(false), mbVO(false), mpORBVocabulary(pVoc), mpKeyFrameDB(pKFDB),
  40. mpInitializer(static_cast<Initializer*>(NULL)), mpSystem(pSys), mpViewer(NULL),
  41. mpFrameDrawer(pFrameDrawer), mpMapDrawer(pMapDrawer), mpAtlas(pAtlas), mnLastRelocFrameId(0), time_recently_lost(5.0),
  42. mnInitialFrameId(0), mbCreatedMap(false), mnFirstFrameId(0), mpCamera2(nullptr)
  43. {
  44. // Load camera parameters from settings file
  45. cv::FileStorage fSettings(strSettingPath, cv::FileStorage::READ);
  46. cv::Mat DistCoef = cv::Mat::zeros(4,1,CV_32F);
  47. string sCameraName = fSettings["Camera.type"];
  48. if(sCameraName == "PinHole"){
  49. float fx = fSettings["Camera.fx"];
  50. float fy = fSettings["Camera.fy"];
  51. float cx = fSettings["Camera.cx"];
  52. float cy = fSettings["Camera.cy"];
  53. vector<float> vCamCalib{fx,fy,cx,cy};
  54. mpCamera = new Pinhole(vCamCalib);
  55. mpAtlas->AddCamera(mpCamera);
  56. DistCoef.at<float>(0) = fSettings["Camera.k1"];
  57. DistCoef.at<float>(1) = fSettings["Camera.k2"];
  58. DistCoef.at<float>(2) = fSettings["Camera.p1"];
  59. DistCoef.at<float>(3) = fSettings["Camera.p2"];
  60. }
  61. if(sCameraName == "KannalaBrandt8"){
  62. float fx = fSettings["Camera.fx"];
  63. float fy = fSettings["Camera.fy"];
  64. float cx = fSettings["Camera.cx"];
  65. float cy = fSettings["Camera.cy"];
  66. float K1 = fSettings["Camera.k1"];
  67. float K2 = fSettings["Camera.k2"];
  68. float K3 = fSettings["Camera.k3"];
  69. float K4 = fSettings["Camera.k4"];
  70. vector<float> vCamCalib{fx,fy,cx,cy,K1,K2,K3,K4};
  71. mpCamera = new KannalaBrandt8(vCamCalib);
  72. mpAtlas->AddCamera(mpCamera);
  73. if(sensor==System::STEREO || sensor==System::IMU_STEREO){
  74. //Right camera
  75. fx = fSettings["Camera2.fx"];
  76. fy = fSettings["Camera2.fy"];
  77. cx = fSettings["Camera2.cx"];
  78. cy = fSettings["Camera2.cy"];
  79. K1 = fSettings["Camera2.k1"];
  80. K2 = fSettings["Camera2.k2"];
  81. K3 = fSettings["Camera2.k3"];
  82. K4 = fSettings["Camera2.k4"];
  83. cout << endl << "Camera2 Parameters: " << endl;
  84. cout << "- fx: " << fx << endl;
  85. cout << "- fy: " << fy << endl;
  86. cout << "- cx: " << cx << endl;
  87. cout << "- cy: " << cy << endl;
  88. vector<float> vCamCalib2{fx,fy,cx,cy,K1,K2,K3,K4};
  89. mpCamera2 = new KannalaBrandt8(vCamCalib2);
  90. mpAtlas->AddCamera(mpCamera2);
  91. int leftLappingBegin = fSettings["Camera.lappingBegin"];
  92. int leftLappingEnd = fSettings["Camera.lappingEnd"];
  93. int rightLappingBegin = fSettings["Camera2.lappingBegin"];
  94. int rightLappingEnd = fSettings["Camera2.lappingEnd"];
  95. static_cast<KannalaBrandt8*>(mpCamera)->mvLappingArea[0] = leftLappingBegin;
  96. static_cast<KannalaBrandt8*>(mpCamera)->mvLappingArea[1] = leftLappingEnd;
  97. static_cast<KannalaBrandt8*>(mpCamera2)->mvLappingArea[0] = rightLappingBegin;
  98. static_cast<KannalaBrandt8*>(mpCamera2)->mvLappingArea[1] = rightLappingEnd;
  99. fSettings["Tlr"] >> mTlr;
  100. cout << "- mTlr: \n" << mTlr << endl;
  101. mpFrameDrawer->both = true;
  102. }
  103. }
  104. float fx = fSettings["Camera.fx"];
  105. float fy = fSettings["Camera.fy"];
  106. float cx = fSettings["Camera.cx"];
  107. float cy = fSettings["Camera.cy"];
  108. cv::Mat K = cv::Mat::eye(3,3,CV_32F);
  109. K.at<float>(0,0) = fx;
  110. K.at<float>(1,1) = fy;
  111. K.at<float>(0,2) = cx;
  112. K.at<float>(1,2) = cy;
  113. K.copyTo(mK);
  114. const float k3 = fSettings["Camera.k3"];
  115. if(k3!=0)
  116. {
  117. DistCoef.resize(5);
  118. DistCoef.at<float>(4) = k3;
  119. }
  120. DistCoef.copyTo(mDistCoef);
  121. mbf = fSettings["Camera.bf"];
  122. float fps = fSettings["Camera.fps"];
  123. if(fps==0)
  124. fps=30;
  125. // Max/Min Frames to insert keyframes and to check relocalisation
  126. mMinFrames = 0;
  127. mMaxFrames = fps;
  128. cout << endl << "Camera Parameters: " << endl;
  129. cout << "- fx: " << fx << endl;
  130. cout << "- fy: " << fy << endl;
  131. cout << "- cx: " << cx << endl;
  132. cout << "- cy: " << cy << endl;
  133. cout << "- bf: " << mbf << endl;
  134. cout << "- k1: " << DistCoef.at<float>(0) << endl;
  135. cout << "- k2: " << DistCoef.at<float>(1) << endl;
  136. cout << "- p1: " << DistCoef.at<float>(2) << endl;
  137. cout << "- p2: " << DistCoef.at<float>(3) << endl;
  138. if(DistCoef.rows==5)
  139. cout << "- k3: " << DistCoef.at<float>(4) << endl;
  140. cout << "- fps: " << fps << endl;
  141. int nRGB = fSettings["Camera.RGB"];
  142. mbRGB = nRGB;
  143. if(mbRGB)
  144. cout << "- color order: RGB (ignored if grayscale)" << endl;
  145. else
  146. cout << "- color order: BGR (ignored if grayscale)" << endl;
  147. // Load ORB parameters
  148. int nFeatures = fSettings["ORBextractor.nFeatures"];
  149. float fScaleFactor = fSettings["ORBextractor.scaleFactor"];
  150. int nLevels = fSettings["ORBextractor.nLevels"];
  151. int fIniThFAST = fSettings["ORBextractor.iniThFAST"];
  152. int fMinThFAST = fSettings["ORBextractor.minThFAST"];
  153. mpORBextractorLeft = new ORBextractor(nFeatures,fScaleFactor,nLevels,fIniThFAST,fMinThFAST);
  154. if(sensor==System::STEREO || sensor==System::IMU_STEREO)
  155. mpORBextractorRight = new ORBextractor(nFeatures,fScaleFactor,nLevels,fIniThFAST,fMinThFAST);
  156. if(sensor==System::MONOCULAR || sensor==System::IMU_MONOCULAR)
  157. mpIniORBextractor = new ORBextractor(5*nFeatures,fScaleFactor,nLevels,fIniThFAST,fMinThFAST);
  158. initID = 0; lastID = 0;
  159. cout << endl << "ORB Extractor Parameters: " << endl;
  160. cout << "- Number of Features: " << nFeatures << endl;
  161. cout << "- Scale Levels: " << nLevels << endl;
  162. cout << "- Scale Factor: " << fScaleFactor << endl;
  163. cout << "- Initial Fast Threshold: " << fIniThFAST << endl;
  164. cout << "- Minimum Fast Threshold: " << fMinThFAST << endl;
  165. if(sensor==System::STEREO || sensor==System::RGBD || sensor==System::IMU_STEREO)
  166. {
  167. mThDepth = mbf*(float)fSettings["ThDepth"]/fx;
  168. cout << endl << "Depth Threshold (Close/Far Points): " << mThDepth << endl;
  169. }
  170. if(sensor==System::RGBD)
  171. {
  172. mDepthMapFactor = fSettings["DepthMapFactor"];
  173. if(fabs(mDepthMapFactor)<1e-5)
  174. mDepthMapFactor=1;
  175. else
  176. mDepthMapFactor = 1.0f/mDepthMapFactor;
  177. }
  178. if(sensor==System::IMU_MONOCULAR || sensor==System::IMU_STEREO)
  179. {
  180. cv::Mat Tbc;
  181. fSettings["Tbc"] >> Tbc;
  182. cout << endl;
  183. cout << "Left camera to Imu Transform (Tbc): " << endl << Tbc << endl;
  184. float freq, Ng, Na, Ngw, Naw;
  185. fSettings["IMU.Frequency"] >> freq;
  186. fSettings["IMU.NoiseGyro"] >> Ng;
  187. fSettings["IMU.NoiseAcc"] >> Na;
  188. fSettings["IMU.GyroWalk"] >> Ngw;
  189. fSettings["IMU.AccWalk"] >> Naw;
  190. const float sf = sqrt(freq);
  191. cout << endl;
  192. cout << "IMU frequency: " << freq << " Hz" << endl;
  193. cout << "IMU gyro noise: " << Ng << " rad/s/sqrt(Hz)" << endl;
  194. cout << "IMU gyro walk: " << Ngw << " rad/s^2/sqrt(Hz)" << endl;
  195. cout << "IMU accelerometer noise: " << Na << " m/s^2/sqrt(Hz)" << endl;
  196. cout << "IMU accelerometer walk: " << Naw << " m/s^3/sqrt(Hz)" << endl;
  197. mpImuCalib = new IMU::Calib(Tbc,Ng*sf,Na*sf,Ngw/sf,Naw/sf);
  198. mpImuPreintegratedFromLastKF = new IMU::Preintegrated(IMU::Bias(),*mpImuCalib);
  199. mnFramesToResetIMU = mMaxFrames;
  200. }
  201. mbInitWith3KFs = false;
  202. //Test Images
  203. if((mSensor == System::STEREO || mSensor == System::IMU_STEREO) && sCameraName == "PinHole")
  204. {
  205. cv::Mat K_l, K_r, P_l, P_r, R_l, R_r, D_l, D_r;
  206. fSettings["LEFT.K"] >> K_l;
  207. fSettings["RIGHT.K"] >> K_r;
  208. fSettings["LEFT.P"] >> P_l;
  209. fSettings["RIGHT.P"] >> P_r;
  210. fSettings["LEFT.R"] >> R_l;
  211. fSettings["RIGHT.R"] >> R_r;
  212. fSettings["LEFT.D"] >> D_l;
  213. fSettings["RIGHT.D"] >> D_r;
  214. int rows_l = fSettings["LEFT.height"];
  215. int cols_l = fSettings["LEFT.width"];
  216. int rows_r = fSettings["RIGHT.height"];
  217. int cols_r = fSettings["RIGHT.width"];
  218. // M1r y M2r son los outputs (igual para l)
  219. // M1r y M2r son las matrices relativas al mapeo correspondiente a la rectificación de mapa en el eje X e Y respectivamente
  220. cv::initUndistortRectifyMap(K_l,D_l,R_l,P_l.rowRange(0,3).colRange(0,3),cv::Size(cols_l,rows_l),CV_32F,M1l,M2l);
  221. cv::initUndistortRectifyMap(K_r,D_r,R_r,P_r.rowRange(0,3).colRange(0,3),cv::Size(cols_r,rows_r),CV_32F,M1r,M2r);
  222. }
  223. else
  224. {
  225. int cols = 752;
  226. int rows = 480;
  227. cv::Mat R_l = cv::Mat::eye(3, 3, CV_32F);
  228. }
  229. mnNumDataset = 0;
  230. //f_track_stats.open("tracking_stats"+ _nameSeq + ".txt");
  231. /*f_track_stats.open("tracking_stats.txt");
  232. f_track_stats << "# timestamp, Num KF local, Num MP local, time" << endl;
  233. f_track_stats << fixed ;*/
  234. #ifdef SAVE_TIMES
  235. f_track_times.open("tracking_times.txt");
  236. f_track_times << "# ORB_Ext(ms), Stereo matching(ms), Preintegrate_IMU(ms), Pose pred(ms), LocalMap_track(ms), NewKF_dec(ms)" << endl;
  237. f_track_times << fixed ;
  238. #endif
  239. }
  240. Tracking::~Tracking()
  241. {
  242. //f_track_stats.close();
  243. #ifdef SAVE_TIMES
  244. f_track_times.close();
  245. #endif
  246. }
  247. void Tracking::SetLocalMapper(LocalMapping *pLocalMapper)
  248. {
  249. mpLocalMapper=pLocalMapper;
  250. }
  251. void Tracking::SetLoopClosing(LoopClosing *pLoopClosing)
  252. {
  253. mpLoopClosing=pLoopClosing;
  254. }
  255. void Tracking::SetViewer(Viewer *pViewer)
  256. {
  257. mpViewer=pViewer;
  258. }
  259. void Tracking::SetStepByStep(bool bSet)
  260. {
  261. bStepByStep = bSet;
  262. }
  263. cv::Mat Tracking::GrabImageStereo(const cv::Mat &imRectLeft, const cv::Mat &imRectRight, const double &timestamp, string filename)
  264. {
  265. mImGray = imRectLeft;
  266. cv::Mat imGrayRight = imRectRight;
  267. mImRight = imRectRight;
  268. if(mImGray.channels()==3)
  269. {
  270. if(mbRGB)
  271. {
  272. cvtColor(mImGray,mImGray,CV_RGB2GRAY);
  273. cvtColor(imGrayRight,imGrayRight,CV_RGB2GRAY);
  274. }
  275. else
  276. {
  277. cvtColor(mImGray,mImGray,CV_BGR2GRAY);
  278. cvtColor(imGrayRight,imGrayRight,CV_BGR2GRAY);
  279. }
  280. }
  281. else if(mImGray.channels()==4)
  282. {
  283. if(mbRGB)
  284. {
  285. cvtColor(mImGray,mImGray,CV_RGBA2GRAY);
  286. cvtColor(imGrayRight,imGrayRight,CV_RGBA2GRAY);
  287. }
  288. else
  289. {
  290. cvtColor(mImGray,mImGray,CV_BGRA2GRAY);
  291. cvtColor(imGrayRight,imGrayRight,CV_BGRA2GRAY);
  292. }
  293. }
  294. if (mSensor == System::STEREO && !mpCamera2)
  295. mCurrentFrame = Frame(mImGray,imGrayRight,timestamp,mpORBextractorLeft,mpORBextractorRight,mpORBVocabulary,mK,mDistCoef,mbf,mThDepth,mpCamera);
  296. else if(mSensor == System::STEREO && mpCamera2)
  297. mCurrentFrame = Frame(mImGray,imGrayRight,timestamp,mpORBextractorLeft,mpORBextractorRight,mpORBVocabulary,mK,mDistCoef,mbf,mThDepth,mpCamera,mpCamera2,mTlr);
  298. else if(mSensor == System::IMU_STEREO && !mpCamera2)
  299. mCurrentFrame = Frame(mImGray,imGrayRight,timestamp,mpORBextractorLeft,mpORBextractorRight,mpORBVocabulary,mK,mDistCoef,mbf,mThDepth,mpCamera,&mLastFrame,*mpImuCalib);
  300. else if(mSensor == System::IMU_STEREO && mpCamera2)
  301. mCurrentFrame = Frame(mImGray,imGrayRight,timestamp,mpORBextractorLeft,mpORBextractorRight,mpORBVocabulary,mK,mDistCoef,mbf,mThDepth,mpCamera,mpCamera2,mTlr,&mLastFrame,*mpImuCalib);
  302. std::chrono::steady_clock::time_point t0 = std::chrono::steady_clock::now();
  303. mCurrentFrame.mNameFile = filename;
  304. mCurrentFrame.mnDataset = mnNumDataset;
  305. Track();
  306. std::chrono::steady_clock::time_point t1 = std::chrono::steady_clock::now();
  307. double t_track = std::chrono::duration_cast<std::chrono::duration<double,std::milli> >(t1 - t0).count();
  308. /*cout << "trracking time: " << t_track << endl;
  309. f_track_stats << setprecision(0) << mCurrentFrame.mTimeStamp*1e9 << ",";
  310. f_track_stats << mvpLocalKeyFrames.size() << ",";
  311. f_track_stats << mvpLocalMapPoints.size() << ",";
  312. f_track_stats << setprecision(6) << t_track << endl;*/
  313. #ifdef SAVE_TIMES
  314. f_track_times << mCurrentFrame.mTimeORB_Ext << ",";
  315. f_track_times << mCurrentFrame.mTimeStereoMatch << ",";
  316. f_track_times << mTime_PreIntIMU << ",";
  317. f_track_times << mTime_PosePred << ",";
  318. f_track_times << mTime_LocalMapTrack << ",";
  319. f_track_times << mTime_NewKF_Dec << ",";
  320. f_track_times << t_track << endl;
  321. #endif
  322. return mCurrentFrame.mTcw.clone();
  323. }
  324. cv::Mat Tracking::GrabImageRGBD(const cv::Mat &imRGB,const cv::Mat &imD, const double &timestamp, string filename)
  325. {
  326. mImGray = imRGB;
  327. cv::Mat imDepth = imD;
  328. if(mImGray.channels()==3)
  329. {
  330. if(mbRGB)
  331. cvtColor(mImGray,mImGray,CV_RGB2GRAY);
  332. else
  333. cvtColor(mImGray,mImGray,CV_BGR2GRAY);
  334. }
  335. else if(mImGray.channels()==4)
  336. {
  337. if(mbRGB)
  338. cvtColor(mImGray,mImGray,CV_RGBA2GRAY);
  339. else
  340. cvtColor(mImGray,mImGray,CV_BGRA2GRAY);
  341. }
  342. if((fabs(mDepthMapFactor-1.0f)>1e-5) || imDepth.type()!=CV_32F)
  343. imDepth.convertTo(imDepth,CV_32F,mDepthMapFactor);
  344. std::chrono::steady_clock::time_point t0 = std::chrono::steady_clock::now();
  345. mCurrentFrame = Frame(mImGray,imDepth,timestamp,mpORBextractorLeft,mpORBVocabulary,mK,mDistCoef,mbf,mThDepth,mpCamera);
  346. mCurrentFrame.mNameFile = filename;
  347. mCurrentFrame.mnDataset = mnNumDataset;
  348. Track();
  349. std::chrono::steady_clock::time_point t1 = std::chrono::steady_clock::now();
  350. double t_track = std::chrono::duration_cast<std::chrono::duration<double,std::milli> >(t1 - t0).count();
  351. /*f_track_stats << setprecision(0) << mCurrentFrame.mTimeStamp*1e9 << ",";
  352. f_track_stats << mvpLocalKeyFrames.size() << ",";
  353. f_track_stats << mvpLocalMapPoints.size() << ",";
  354. f_track_stats << setprecision(6) << t_track << endl;*/
  355. #ifdef SAVE_TIMES
  356. f_track_times << mCurrentFrame.mTimeORB_Ext << ",";
  357. f_track_times << mCurrentFrame.mTimeStereoMatch << ",";
  358. f_track_times << mTime_PreIntIMU << ",";
  359. f_track_times << mTime_PosePred << ",";
  360. f_track_times << mTime_LocalMapTrack << ",";
  361. f_track_times << mTime_NewKF_Dec << ",";
  362. f_track_times << t_track << endl;
  363. #endif
  364. return mCurrentFrame.mTcw.clone();
  365. }
  366. cv::Mat Tracking::GrabImageMonocular(const cv::Mat &im, const double &timestamp, string filename)
  367. {
  368. mImGray = im;
  369. if(mImGray.channels()==3)
  370. {
  371. if(mbRGB)
  372. cvtColor(mImGray,mImGray,CV_RGB2GRAY);
  373. else
  374. cvtColor(mImGray,mImGray,CV_BGR2GRAY);
  375. }
  376. else if(mImGray.channels()==4)
  377. {
  378. if(mbRGB)
  379. cvtColor(mImGray,mImGray,CV_RGBA2GRAY);
  380. else
  381. cvtColor(mImGray,mImGray,CV_BGRA2GRAY);
  382. }
  383. if (mSensor == System::MONOCULAR)
  384. {
  385. if(mState==NOT_INITIALIZED || mState==NO_IMAGES_YET ||(lastID - initID) < mMaxFrames)
  386. mCurrentFrame = Frame(mImGray,timestamp,mpIniORBextractor,mpORBVocabulary,mpCamera,mDistCoef,mbf,mThDepth);
  387. else
  388. mCurrentFrame = Frame(mImGray,timestamp,mpORBextractorLeft,mpORBVocabulary,mpCamera,mDistCoef,mbf,mThDepth);
  389. }
  390. else if(mSensor == System::IMU_MONOCULAR)
  391. {
  392. if(mState==NOT_INITIALIZED || mState==NO_IMAGES_YET)
  393. {
  394. cout << "init extractor" << endl;
  395. mCurrentFrame = Frame(mImGray,timestamp,mpIniORBextractor,mpORBVocabulary,mpCamera,mDistCoef,mbf,mThDepth,&mLastFrame,*mpImuCalib);
  396. }
  397. else
  398. mCurrentFrame = Frame(mImGray,timestamp,mpORBextractorLeft,mpORBVocabulary,mpCamera,mDistCoef,mbf,mThDepth,&mLastFrame,*mpImuCalib);
  399. }
  400. if (mState==NO_IMAGES_YET)
  401. t0=timestamp;
  402. std::chrono::steady_clock::time_point t0 = std::chrono::steady_clock::now();
  403. mCurrentFrame.mNameFile = filename;
  404. mCurrentFrame.mnDataset = mnNumDataset;
  405. lastID = mCurrentFrame.mnId;
  406. Track();
  407. std::chrono::steady_clock::time_point t1 = std::chrono::steady_clock::now();
  408. double t_track = std::chrono::duration_cast<std::chrono::duration<double,std::milli> >(t1 - t0).count();
  409. /*f_track_stats << setprecision(0) << mCurrentFrame.mTimeStamp*1e9 << ",";
  410. f_track_stats << mvpLocalKeyFrames.size() << ",";
  411. f_track_stats << mvpLocalMapPoints.size() << ",";
  412. f_track_stats << setprecision(6) << t_track << endl;*/
  413. #ifdef SAVE_TIMES
  414. f_track_times << mCurrentFrame.mTimeORB_Ext << ",";
  415. f_track_times << mCurrentFrame.mTimeStereoMatch << ",";
  416. f_track_times << mTime_PreIntIMU << ",";
  417. f_track_times << mTime_PosePred << ",";
  418. f_track_times << mTime_LocalMapTrack << ",";
  419. f_track_times << mTime_NewKF_Dec << ",";
  420. f_track_times << t_track << endl;
  421. #endif
  422. return mCurrentFrame.mTcw.clone();
  423. }
  424. void Tracking::GrabImuData(const IMU::Point &imuMeasurement)
  425. {
  426. unique_lock<mutex> lock(mMutexImuQueue);
  427. mlQueueImuData.push_back(imuMeasurement);
  428. }
  429. void Tracking::PreintegrateIMU()
  430. {
  431. //cout << "start preintegration" << endl;
  432. if(!mCurrentFrame.mpPrevFrame)
  433. {
  434. Verbose::PrintMess("non prev frame ", Verbose::VERBOSITY_NORMAL);
  435. mCurrentFrame.setIntegrated();
  436. return;
  437. }
  438. // cout << "start loop. Total meas:" << mlQueueImuData.size() << endl;
  439. mvImuFromLastFrame.clear();
  440. mvImuFromLastFrame.reserve(mlQueueImuData.size());
  441. if(mlQueueImuData.size() == 0)
  442. {
  443. Verbose::PrintMess("Not IMU data in mlQueueImuData!!", Verbose::VERBOSITY_NORMAL);
  444. mCurrentFrame.setIntegrated();
  445. return;
  446. }
  447. while(true)
  448. {
  449. bool bSleep = false;
  450. {
  451. unique_lock<mutex> lock(mMutexImuQueue);
  452. if(!mlQueueImuData.empty())
  453. {
  454. IMU::Point* m = &mlQueueImuData.front();
  455. cout.precision(17);
  456. if(m->t<mCurrentFrame.mpPrevFrame->mTimeStamp-0.001l)
  457. {
  458. mlQueueImuData.pop_front();
  459. }
  460. else if(m->t<mCurrentFrame.mTimeStamp-0.001l)
  461. {
  462. mvImuFromLastFrame.push_back(*m);
  463. mlQueueImuData.pop_front();
  464. }
  465. else
  466. {
  467. mvImuFromLastFrame.push_back(*m);
  468. break;
  469. }
  470. }
  471. else
  472. {
  473. break;
  474. bSleep = true;
  475. }
  476. }
  477. if(bSleep)
  478. usleep(500);
  479. }
  480. const int n = mvImuFromLastFrame.size()-1;
  481. IMU::Preintegrated* pImuPreintegratedFromLastFrame = new IMU::Preintegrated(mLastFrame.mImuBias,mCurrentFrame.mImuCalib);
  482. for(int i=0; i<n; i++)
  483. {
  484. float tstep;
  485. cv::Point3f acc, angVel;
  486. if((i==0) && (i<(n-1)))
  487. {
  488. float tab = mvImuFromLastFrame[i+1].t-mvImuFromLastFrame[i].t;
  489. float tini = mvImuFromLastFrame[i].t-mCurrentFrame.mpPrevFrame->mTimeStamp;
  490. acc = (mvImuFromLastFrame[i].a+mvImuFromLastFrame[i+1].a-
  491. (mvImuFromLastFrame[i+1].a-mvImuFromLastFrame[i].a)*(tini/tab))*0.5f;
  492. angVel = (mvImuFromLastFrame[i].w+mvImuFromLastFrame[i+1].w-
  493. (mvImuFromLastFrame[i+1].w-mvImuFromLastFrame[i].w)*(tini/tab))*0.5f;
  494. tstep = mvImuFromLastFrame[i+1].t-mCurrentFrame.mpPrevFrame->mTimeStamp;
  495. }
  496. else if(i<(n-1))
  497. {
  498. acc = (mvImuFromLastFrame[i].a+mvImuFromLastFrame[i+1].a)*0.5f;
  499. angVel = (mvImuFromLastFrame[i].w+mvImuFromLastFrame[i+1].w)*0.5f;
  500. tstep = mvImuFromLastFrame[i+1].t-mvImuFromLastFrame[i].t;
  501. }
  502. else if((i>0) && (i==(n-1)))
  503. {
  504. float tab = mvImuFromLastFrame[i+1].t-mvImuFromLastFrame[i].t;
  505. float tend = mvImuFromLastFrame[i+1].t-mCurrentFrame.mTimeStamp;
  506. acc = (mvImuFromLastFrame[i].a+mvImuFromLastFrame[i+1].a-
  507. (mvImuFromLastFrame[i+1].a-mvImuFromLastFrame[i].a)*(tend/tab))*0.5f;
  508. angVel = (mvImuFromLastFrame[i].w+mvImuFromLastFrame[i+1].w-
  509. (mvImuFromLastFrame[i+1].w-mvImuFromLastFrame[i].w)*(tend/tab))*0.5f;
  510. tstep = mCurrentFrame.mTimeStamp-mvImuFromLastFrame[i].t;
  511. }
  512. else if((i==0) && (i==(n-1)))
  513. {
  514. acc = mvImuFromLastFrame[i].a;
  515. angVel = mvImuFromLastFrame[i].w;
  516. tstep = mCurrentFrame.mTimeStamp-mCurrentFrame.mpPrevFrame->mTimeStamp;
  517. }
  518. if (!mpImuPreintegratedFromLastKF)
  519. cout << "mpImuPreintegratedFromLastKF does not exist" << endl;
  520. mpImuPreintegratedFromLastKF->IntegrateNewMeasurement(acc,angVel,tstep);
  521. pImuPreintegratedFromLastFrame->IntegrateNewMeasurement(acc,angVel,tstep);
  522. }
  523. mCurrentFrame.mpImuPreintegratedFrame = pImuPreintegratedFromLastFrame;
  524. mCurrentFrame.mpImuPreintegrated = mpImuPreintegratedFromLastKF;
  525. mCurrentFrame.mpLastKeyFrame = mpLastKeyFrame;
  526. if(!mpLastKeyFrame)
  527. {
  528. cout << "last KF is empty!" << endl;
  529. }
  530. mCurrentFrame.setIntegrated();
  531. Verbose::PrintMess("Preintegration is finished!! ", Verbose::VERBOSITY_DEBUG);
  532. }
  533. bool Tracking::PredictStateIMU()
  534. {
  535. if(!mCurrentFrame.mpPrevFrame)
  536. {
  537. Verbose::PrintMess("No last frame", Verbose::VERBOSITY_NORMAL);
  538. return false;
  539. }
  540. if(mbMapUpdated && mpLastKeyFrame)
  541. {
  542. const cv::Mat twb1 = mpLastKeyFrame->GetImuPosition();
  543. const cv::Mat Rwb1 = mpLastKeyFrame->GetImuRotation();
  544. const cv::Mat Vwb1 = mpLastKeyFrame->GetVelocity();
  545. const cv::Mat Gz = (cv::Mat_<float>(3,1) << 0,0,-IMU::GRAVITY_VALUE);
  546. const float t12 = mpImuPreintegratedFromLastKF->dT;
  547. cv::Mat Rwb2 = IMU::NormalizeRotation(Rwb1*mpImuPreintegratedFromLastKF->GetDeltaRotation(mpLastKeyFrame->GetImuBias()));
  548. cv::Mat twb2 = twb1 + Vwb1*t12 + 0.5f*t12*t12*Gz+ Rwb1*mpImuPreintegratedFromLastKF->GetDeltaPosition(mpLastKeyFrame->GetImuBias());
  549. cv::Mat Vwb2 = Vwb1 + t12*Gz + Rwb1*mpImuPreintegratedFromLastKF->GetDeltaVelocity(mpLastKeyFrame->GetImuBias());
  550. mCurrentFrame.SetImuPoseVelocity(Rwb2,twb2,Vwb2);
  551. mCurrentFrame.mPredRwb = Rwb2.clone();
  552. mCurrentFrame.mPredtwb = twb2.clone();
  553. mCurrentFrame.mPredVwb = Vwb2.clone();
  554. mCurrentFrame.mImuBias = mpLastKeyFrame->GetImuBias();
  555. mCurrentFrame.mPredBias = mCurrentFrame.mImuBias;
  556. return true;
  557. }
  558. else if(!mbMapUpdated)
  559. {
  560. const cv::Mat twb1 = mLastFrame.GetImuPosition();
  561. const cv::Mat Rwb1 = mLastFrame.GetImuRotation();
  562. const cv::Mat Vwb1 = mLastFrame.mVw;
  563. const cv::Mat Gz = (cv::Mat_<float>(3,1) << 0,0,-IMU::GRAVITY_VALUE);
  564. const float t12 = mCurrentFrame.mpImuPreintegratedFrame->dT;
  565. cv::Mat Rwb2 = IMU::NormalizeRotation(Rwb1*mCurrentFrame.mpImuPreintegratedFrame->GetDeltaRotation(mLastFrame.mImuBias));
  566. cv::Mat twb2 = twb1 + Vwb1*t12 + 0.5f*t12*t12*Gz+ Rwb1*mCurrentFrame.mpImuPreintegratedFrame->GetDeltaPosition(mLastFrame.mImuBias);
  567. cv::Mat Vwb2 = Vwb1 + t12*Gz + Rwb1*mCurrentFrame.mpImuPreintegratedFrame->GetDeltaVelocity(mLastFrame.mImuBias);
  568. mCurrentFrame.SetImuPoseVelocity(Rwb2,twb2,Vwb2);
  569. mCurrentFrame.mPredRwb = Rwb2.clone();
  570. mCurrentFrame.mPredtwb = twb2.clone();
  571. mCurrentFrame.mPredVwb = Vwb2.clone();
  572. mCurrentFrame.mImuBias =mLastFrame.mImuBias;
  573. mCurrentFrame.mPredBias = mCurrentFrame.mImuBias;
  574. return true;
  575. }
  576. else
  577. cout << "not IMU prediction!!" << endl;
  578. return false;
  579. }
  580. void Tracking::ComputeGyroBias(const vector<Frame*> &vpFs, float &bwx, float &bwy, float &bwz)
  581. {
  582. const int N = vpFs.size();
  583. vector<float> vbx;
  584. vbx.reserve(N);
  585. vector<float> vby;
  586. vby.reserve(N);
  587. vector<float> vbz;
  588. vbz.reserve(N);
  589. cv::Mat H = cv::Mat::zeros(3,3,CV_32F);
  590. cv::Mat grad = cv::Mat::zeros(3,1,CV_32F);
  591. for(int i=1;i<N;i++)
  592. {
  593. Frame* pF2 = vpFs[i];
  594. Frame* pF1 = vpFs[i-1];
  595. cv::Mat VisionR = pF1->GetImuRotation().t()*pF2->GetImuRotation();
  596. cv::Mat JRg = pF2->mpImuPreintegratedFrame->JRg;
  597. cv::Mat E = pF2->mpImuPreintegratedFrame->GetUpdatedDeltaRotation().t()*VisionR;
  598. cv::Mat e = IMU::LogSO3(E);
  599. assert(fabs(pF2->mTimeStamp-pF1->mTimeStamp-pF2->mpImuPreintegratedFrame->dT)<0.01);
  600. cv::Mat J = -IMU::InverseRightJacobianSO3(e)*E.t()*JRg;
  601. grad += J.t()*e;
  602. H += J.t()*J;
  603. }
  604. cv::Mat bg = -H.inv(cv::DECOMP_SVD)*grad;
  605. bwx = bg.at<float>(0);
  606. bwy = bg.at<float>(1);
  607. bwz = bg.at<float>(2);
  608. for(int i=1;i<N;i++)
  609. {
  610. Frame* pF = vpFs[i];
  611. pF->mImuBias.bwx = bwx;
  612. pF->mImuBias.bwy = bwy;
  613. pF->mImuBias.bwz = bwz;
  614. pF->mpImuPreintegratedFrame->SetNewBias(pF->mImuBias);
  615. pF->mpImuPreintegratedFrame->Reintegrate();
  616. }
  617. }
  618. void Tracking::ComputeVelocitiesAccBias(const vector<Frame*> &vpFs, float &bax, float &bay, float &baz)
  619. {
  620. const int N = vpFs.size();
  621. const int nVar = 3*N +3; // 3 velocities/frame + acc bias
  622. const int nEqs = 6*(N-1);
  623. cv::Mat J(nEqs,nVar,CV_32F,cv::Scalar(0));
  624. cv::Mat e(nEqs,1,CV_32F,cv::Scalar(0));
  625. cv::Mat g = (cv::Mat_<float>(3,1)<<0,0,-IMU::GRAVITY_VALUE);
  626. for(int i=0;i<N-1;i++)
  627. {
  628. Frame* pF2 = vpFs[i+1];
  629. Frame* pF1 = vpFs[i];
  630. cv::Mat twb1 = pF1->GetImuPosition();
  631. cv::Mat twb2 = pF2->GetImuPosition();
  632. cv::Mat Rwb1 = pF1->GetImuRotation();
  633. cv::Mat dP12 = pF2->mpImuPreintegratedFrame->GetUpdatedDeltaPosition();
  634. cv::Mat dV12 = pF2->mpImuPreintegratedFrame->GetUpdatedDeltaVelocity();
  635. cv::Mat JP12 = pF2->mpImuPreintegratedFrame->JPa;
  636. cv::Mat JV12 = pF2->mpImuPreintegratedFrame->JVa;
  637. float t12 = pF2->mpImuPreintegratedFrame->dT;
  638. // Position p2=p1+v1*t+0.5*g*t^2+R1*dP12
  639. J.rowRange(6*i,6*i+3).colRange(3*i,3*i+3) += cv::Mat::eye(3,3,CV_32F)*t12;
  640. J.rowRange(6*i,6*i+3).colRange(3*N,3*N+3) += Rwb1*JP12;
  641. e.rowRange(6*i,6*i+3) = twb2-twb1-0.5f*g*t12*t12-Rwb1*dP12;
  642. // Velocity v2=v1+g*t+R1*dV12
  643. J.rowRange(6*i+3,6*i+6).colRange(3*i,3*i+3) += -cv::Mat::eye(3,3,CV_32F);
  644. J.rowRange(6*i+3,6*i+6).colRange(3*(i+1),3*(i+1)+3) += cv::Mat::eye(3,3,CV_32F);
  645. J.rowRange(6*i+3,6*i+6).colRange(3*N,3*N+3) -= Rwb1*JV12;
  646. e.rowRange(6*i+3,6*i+6) = g*t12+Rwb1*dV12;
  647. }
  648. cv::Mat H = J.t()*J;
  649. cv::Mat B = J.t()*e;
  650. cv::Mat x(nVar,1,CV_32F);
  651. cv::solve(H,B,x);
  652. bax = x.at<float>(3*N);
  653. bay = x.at<float>(3*N+1);
  654. baz = x.at<float>(3*N+2);
  655. for(int i=0;i<N;i++)
  656. {
  657. Frame* pF = vpFs[i];
  658. x.rowRange(3*i,3*i+3).copyTo(pF->mVw);
  659. if(i>0)
  660. {
  661. pF->mImuBias.bax = bax;
  662. pF->mImuBias.bay = bay;
  663. pF->mImuBias.baz = baz;
  664. pF->mpImuPreintegratedFrame->SetNewBias(pF->mImuBias);
  665. }
  666. }
  667. }
  668. void Tracking::ResetFrameIMU()
  669. {
  670. // TODO To implement...
  671. }
  672. void Tracking::Track()
  673. {
  674. #ifdef SAVE_TIMES
  675. mTime_PreIntIMU = 0;
  676. mTime_PosePred = 0;
  677. mTime_LocalMapTrack = 0;
  678. mTime_NewKF_Dec = 0;
  679. #endif
  680. if (bStepByStep)
  681. {
  682. while(!mbStep)
  683. usleep(500);
  684. mbStep = false;
  685. }
  686. if(mpLocalMapper->mbBadImu)
  687. {
  688. cout << "TRACK: Reset map because local mapper set the bad imu flag " << endl;
  689. mpSystem->ResetActiveMap();
  690. return;
  691. }
  692. Map* pCurrentMap = mpAtlas->GetCurrentMap();
  693. if(mState!=NO_IMAGES_YET)
  694. {
  695. if(mLastFrame.mTimeStamp>mCurrentFrame.mTimeStamp)
  696. {
  697. cerr << "ERROR: Frame with a timestamp older than previous frame detected!" << endl;
  698. unique_lock<mutex> lock(mMutexImuQueue);
  699. mlQueueImuData.clear();
  700. CreateMapInAtlas();
  701. return;
  702. }
  703. else if(mCurrentFrame.mTimeStamp>mLastFrame.mTimeStamp+1.0)
  704. {
  705. cout << "id last: " << mLastFrame.mnId << " id curr: " << mCurrentFrame.mnId << endl;
  706. if(mpAtlas->isInertial())
  707. {
  708. if(mpAtlas->isImuInitialized())
  709. {
  710. cout << "Timestamp jump detected. State set to LOST. Reseting IMU integration..." << endl;
  711. if(!pCurrentMap->GetIniertialBA2())
  712. {
  713. mpSystem->ResetActiveMap();
  714. }
  715. else
  716. {
  717. CreateMapInAtlas();
  718. }
  719. }
  720. else
  721. {
  722. cout << "Timestamp jump detected, before IMU initialization. Reseting..." << endl;
  723. mpSystem->ResetActiveMap();
  724. }
  725. }
  726. return;
  727. }
  728. }
  729. if ((mSensor == System::IMU_MONOCULAR || mSensor == System::IMU_STEREO) && mpLastKeyFrame)
  730. mCurrentFrame.SetNewBias(mpLastKeyFrame->GetImuBias());
  731. if(mState==NO_IMAGES_YET)
  732. {
  733. mState = NOT_INITIALIZED;
  734. }
  735. mLastProcessedState=mState;
  736. if ((mSensor == System::IMU_MONOCULAR || mSensor == System::IMU_STEREO) && !mbCreatedMap)
  737. {
  738. #ifdef SAVE_TIMES
  739. std::chrono::steady_clock::time_point t0 = std::chrono::steady_clock::now();
  740. #endif
  741. PreintegrateIMU();
  742. #ifdef SAVE_TIMES
  743. std::chrono::steady_clock::time_point t1 = std::chrono::steady_clock::now();
  744. mTime_PreIntIMU = std::chrono::duration_cast<std::chrono::duration<double,std::milli> >(t1 - t0).count();
  745. #endif
  746. }
  747. mbCreatedMap = false;
  748. // Get Map Mutex -> Map cannot be changed
  749. unique_lock<mutex> lock(pCurrentMap->mMutexMapUpdate);
  750. mbMapUpdated = false;
  751. int nCurMapChangeIndex = pCurrentMap->GetMapChangeIndex();
  752. int nMapChangeIndex = pCurrentMap->GetLastMapChange();
  753. if(nCurMapChangeIndex>nMapChangeIndex)
  754. {
  755. // cout << "Map update detected" << endl;
  756. pCurrentMap->SetLastMapChange(nCurMapChangeIndex);
  757. mbMapUpdated = true;
  758. }
  759. //std::cout << "T2" << std::endl;
  760. if(mState==NOT_INITIALIZED)
  761. {
  762. if(mSensor==System::STEREO || mSensor==System::RGBD || mSensor==System::IMU_STEREO)
  763. StereoInitialization();
  764. else
  765. {
  766. MonocularInitialization();
  767. }
  768. mpFrameDrawer->Update(this);
  769. if(mState!=OK) // If rightly initialized, mState=OK
  770. {
  771. mLastFrame = Frame(mCurrentFrame);
  772. return;
  773. }
  774. if(mpAtlas->GetAllMaps().size() == 1)
  775. {
  776. mnFirstFrameId = mCurrentFrame.mnId;
  777. }
  778. }
  779. else
  780. {
  781. // System is initialized. Track Frame.
  782. bool bOK;
  783. // Initial camera pose estimation using motion model or relocalization (if tracking is lost)
  784. if(!mbOnlyTracking)
  785. {
  786. #ifdef SAVE_TIMES
  787. std::chrono::steady_clock::time_point timeStartPosePredict = std::chrono::steady_clock::now();
  788. #endif
  789. // State OK
  790. // Local Mapping is activated. This is the normal behaviour, unless
  791. // you explicitly activate the "only tracking" mode.
  792. if(mState==OK)
  793. {
  794. // Local Mapping might have changed some MapPoints tracked in last frame
  795. CheckReplacedInLastFrame();
  796. if((mVelocity.empty() && !pCurrentMap->isImuInitialized()) || mCurrentFrame.mnId<mnLastRelocFrameId+2)
  797. {
  798. //Verbose::PrintMess("TRACK: Track with respect to the reference KF ", Verbose::VERBOSITY_DEBUG);
  799. bOK = TrackReferenceKeyFrame();
  800. }
  801. else
  802. {
  803. //Verbose::PrintMess("TRACK: Track with motion model", Verbose::VERBOSITY_DEBUG);
  804. bOK = TrackWithMotionModel();
  805. if(!bOK)
  806. bOK = TrackReferenceKeyFrame();
  807. }
  808. if (!bOK)
  809. {
  810. if ( mCurrentFrame.mnId<=(mnLastRelocFrameId+mnFramesToResetIMU) &&
  811. (mSensor==System::IMU_MONOCULAR || mSensor==System::IMU_STEREO))
  812. {
  813. mState = LOST;
  814. }
  815. else if(pCurrentMap->KeyFramesInMap()>10)
  816. {
  817. cout << "KF in map: " << pCurrentMap->KeyFramesInMap() << endl;
  818. mState = RECENTLY_LOST;
  819. mTimeStampLost = mCurrentFrame.mTimeStamp;
  820. //mCurrentFrame.SetPose(mLastFrame.mTcw);
  821. }
  822. else
  823. {
  824. mState = LOST;
  825. }
  826. }
  827. }
  828. else
  829. {
  830. if (mState == RECENTLY_LOST)
  831. {
  832. Verbose::PrintMess("Lost for a short time", Verbose::VERBOSITY_NORMAL);
  833. bOK = true;
  834. if((mSensor == System::IMU_MONOCULAR || mSensor == System::IMU_STEREO))
  835. {
  836. if(pCurrentMap->isImuInitialized())
  837. PredictStateIMU();
  838. else
  839. bOK = false;
  840. if (mCurrentFrame.mTimeStamp-mTimeStampLost>time_recently_lost)
  841. {
  842. mState = LOST;
  843. Verbose::PrintMess("Track Lost...", Verbose::VERBOSITY_NORMAL);
  844. bOK=false;
  845. }
  846. }
  847. else
  848. {
  849. // TODO fix relocalization
  850. bOK = Relocalization();
  851. if(!bOK)
  852. {
  853. mState = LOST;
  854. Verbose::PrintMess("Track Lost...", Verbose::VERBOSITY_NORMAL);
  855. bOK=false;
  856. }
  857. }
  858. }
  859. else if (mState == LOST)
  860. {
  861. Verbose::PrintMess("A new map is started...", Verbose::VERBOSITY_NORMAL);
  862. if (pCurrentMap->KeyFramesInMap()<10)
  863. {
  864. mpSystem->ResetActiveMap();
  865. cout << "Reseting current map..." << endl;
  866. }else
  867. CreateMapInAtlas();
  868. if(mpLastKeyFrame)
  869. mpLastKeyFrame = static_cast<KeyFrame*>(NULL);
  870. Verbose::PrintMess("done", Verbose::VERBOSITY_NORMAL);
  871. return;
  872. }
  873. }
  874. #ifdef SAVE_TIMES
  875. std::chrono::steady_clock::time_point timeEndPosePredict = std::chrono::steady_clock::now();
  876. mTime_PosePred = std::chrono::duration_cast<std::chrono::duration<double,std::milli> >(timeEndPosePredict - timeStartPosePredict).count();
  877. #endif
  878. }
  879. else
  880. {
  881. // Localization Mode: Local Mapping is deactivated (TODO Not available in inertial mode)
  882. if(mState==LOST)
  883. {
  884. if(mSensor == System::IMU_MONOCULAR || mSensor == System::IMU_STEREO)
  885. Verbose::PrintMess("IMU. State LOST", Verbose::VERBOSITY_NORMAL);
  886. bOK = Relocalization();
  887. }
  888. else
  889. {
  890. if(!mbVO)
  891. {
  892. // In last frame we tracked enough MapPoints in the map
  893. if(!mVelocity.empty())
  894. {
  895. bOK = TrackWithMotionModel();
  896. }
  897. else
  898. {
  899. bOK = TrackReferenceKeyFrame();
  900. }
  901. }
  902. else
  903. {
  904. // In last frame we tracked mainly "visual odometry" points.
  905. // We compute two camera poses, one from motion model and one doing relocalization.
  906. // If relocalization is sucessfull we choose that solution, otherwise we retain
  907. // the "visual odometry" solution.
  908. bool bOKMM = false;
  909. bool bOKReloc = false;
  910. vector<MapPoint*> vpMPsMM;
  911. vector<bool> vbOutMM;
  912. cv::Mat TcwMM;
  913. if(!mVelocity.empty())
  914. {
  915. bOKMM = TrackWithMotionModel();
  916. vpMPsMM = mCurrentFrame.mvpMapPoints;
  917. vbOutMM = mCurrentFrame.mvbOutlier;
  918. TcwMM = mCurrentFrame.mTcw.clone();
  919. }
  920. bOKReloc = Relocalization();
  921. if(bOKMM && !bOKReloc)
  922. {
  923. mCurrentFrame.SetPose(TcwMM);
  924. mCurrentFrame.mvpMapPoints = vpMPsMM;
  925. mCurrentFrame.mvbOutlier = vbOutMM;
  926. if(mbVO)
  927. {
  928. for(int i =0; i<mCurrentFrame.N; i++)
  929. {
  930. if(mCurrentFrame.mvpMapPoints[i] && !mCurrentFrame.mvbOutlier[i])
  931. {
  932. mCurrentFrame.mvpMapPoints[i]->IncreaseFound();
  933. }
  934. }
  935. }
  936. }
  937. else if(bOKReloc)
  938. {
  939. mbVO = false;
  940. }
  941. bOK = bOKReloc || bOKMM;
  942. }
  943. }
  944. }
  945. if(!mCurrentFrame.mpReferenceKF)
  946. mCurrentFrame.mpReferenceKF = mpReferenceKF;
  947. // If we have an initial estimation of the camera pose and matching. Track the local map.
  948. if(!mbOnlyTracking)
  949. {
  950. if(bOK)
  951. {
  952. #ifdef SAVE_TIMES
  953. std::chrono::steady_clock::time_point time_StartTrackLocalMap = std::chrono::steady_clock::now();
  954. #endif
  955. bOK = TrackLocalMap();
  956. #ifdef SAVE_TIMES
  957. std::chrono::steady_clock::time_point time_EndTrackLocalMap = std::chrono::steady_clock::now();
  958. mTime_LocalMapTrack = std::chrono::duration_cast<std::chrono::duration<double,std::milli> >(time_EndTrackLocalMap - time_StartTrackLocalMap).count();
  959. #endif
  960. }
  961. if(!bOK)
  962. cout << "Fail to track local map!" << endl;
  963. }
  964. else
  965. {
  966. // mbVO true means that there are few matches to MapPoints in the map. We cannot retrieve
  967. // a local map and therefore we do not perform TrackLocalMap(). Once the system relocalizes
  968. // the camera we will use the local map again.
  969. if(bOK && !mbVO)
  970. bOK = TrackLocalMap();
  971. }
  972. if(bOK)
  973. mState = OK;
  974. else if (mState == OK)
  975. {
  976. if (mSensor == System::IMU_MONOCULAR || mSensor == System::IMU_STEREO)
  977. {
  978. Verbose::PrintMess("Track lost for less than one second...", Verbose::VERBOSITY_NORMAL);
  979. if(!pCurrentMap->isImuInitialized() || !pCurrentMap->GetIniertialBA2())
  980. {
  981. cout << "IMU is not or recently initialized. Reseting active map..." << endl;
  982. mpSystem->ResetActiveMap();
  983. }
  984. mState=RECENTLY_LOST;
  985. }
  986. else
  987. mState=LOST; // visual to lost
  988. if(mCurrentFrame.mnId>mnLastRelocFrameId+mMaxFrames)
  989. {
  990. mTimeStampLost = mCurrentFrame.mTimeStamp;
  991. }
  992. }
  993. // Save frame if recent relocalization, since they are used for IMU reset (as we are making copy, it shluld be once mCurrFrame is completely modified)
  994. if((mCurrentFrame.mnId<(mnLastRelocFrameId+mnFramesToResetIMU)) && (mCurrentFrame.mnId > mnFramesToResetIMU) && ((mSensor == System::IMU_MONOCULAR) || (mSensor == System::IMU_STEREO)) && pCurrentMap->isImuInitialized())
  995. {
  996. // TODO check this situation
  997. Verbose::PrintMess("Saving pointer to frame. imu needs reset...", Verbose::VERBOSITY_NORMAL);
  998. Frame* pF = new Frame(mCurrentFrame);
  999. pF->mpPrevFrame = new Frame(mLastFrame);
  1000. // Load preintegration
  1001. pF->mpImuPreintegratedFrame = new IMU::Preintegrated(mCurrentFrame.mpImuPreintegratedFrame);
  1002. }
  1003. if(pCurrentMap->isImuInitialized())
  1004. {
  1005. if(bOK)
  1006. {
  1007. if(mCurrentFrame.mnId==(mnLastRelocFrameId+mnFramesToResetIMU))
  1008. {
  1009. cout << "RESETING FRAME!!!" << endl;
  1010. ResetFrameIMU();
  1011. }
  1012. else if(mCurrentFrame.mnId>(mnLastRelocFrameId+30))
  1013. mLastBias = mCurrentFrame.mImuBias;
  1014. }
  1015. }
  1016. // Update drawer
  1017. mpFrameDrawer->Update(this);
  1018. if(!mCurrentFrame.mTcw.empty())
  1019. mpMapDrawer->SetCurrentCameraPose(mCurrentFrame.mTcw);
  1020. if(bOK || mState==RECENTLY_LOST)
  1021. {
  1022. // Update motion model
  1023. if(!mLastFrame.mTcw.empty() && !mCurrentFrame.mTcw.empty())
  1024. {
  1025. cv::Mat LastTwc = cv::Mat::eye(4,4,CV_32F);
  1026. mLastFrame.GetRotationInverse().copyTo(LastTwc.rowRange(0,3).colRange(0,3));
  1027. mLastFrame.GetCameraCenter().copyTo(LastTwc.rowRange(0,3).col(3));
  1028. mVelocity = mCurrentFrame.mTcw*LastTwc;
  1029. }
  1030. else
  1031. mVelocity = cv::Mat();
  1032. if(mSensor == System::IMU_MONOCULAR || mSensor == System::IMU_STEREO)
  1033. mpMapDrawer->SetCurrentCameraPose(mCurrentFrame.mTcw);
  1034. // Clean VO matches
  1035. for(int i=0; i<mCurrentFrame.N; i++)
  1036. {
  1037. MapPoint* pMP = mCurrentFrame.mvpMapPoints[i];
  1038. if(pMP)
  1039. if(pMP->Observations()<1)
  1040. {
  1041. mCurrentFrame.mvbOutlier[i] = false;
  1042. mCurrentFrame.mvpMapPoints[i]=static_cast<MapPoint*>(NULL);
  1043. }
  1044. }
  1045. // Delete temporal MapPoints
  1046. for(list<MapPoint*>::iterator lit = mlpTemporalPoints.begin(), lend = mlpTemporalPoints.end(); lit!=lend; lit++)
  1047. {
  1048. MapPoint* pMP = *lit;
  1049. delete pMP;
  1050. }
  1051. mlpTemporalPoints.clear();
  1052. #ifdef SAVE_TIMES
  1053. std::chrono::steady_clock::time_point timeStartNewKF = std::chrono::steady_clock::now();
  1054. #endif
  1055. bool bNeedKF = NeedNewKeyFrame();
  1056. #ifdef SAVE_TIMES
  1057. std::chrono::steady_clock::time_point timeEndNewKF = std::chrono::steady_clock::now();
  1058. mTime_NewKF_Dec = std::chrono::duration_cast<std::chrono::duration<double,std::milli> >(timeEndNewKF - timeStartNewKF).count();
  1059. #endif
  1060. // Check if we need to insert a new keyframe
  1061. if(bNeedKF && (bOK|| (mState==RECENTLY_LOST && (mSensor == System::IMU_MONOCULAR || mSensor == System::IMU_STEREO))))
  1062. CreateNewKeyFrame();
  1063. // We allow points with high innovation (considererd outliers by the Huber Function)
  1064. // pass to the new keyframe, so that bundle adjustment will finally decide
  1065. // if they are outliers or not. We don't want next frame to estimate its position
  1066. // with those points so we discard them in the frame. Only has effect if lastframe is tracked
  1067. for(int i=0; i<mCurrentFrame.N;i++)
  1068. {
  1069. if(mCurrentFrame.mvpMapPoints[i] && mCurrentFrame.mvbOutlier[i])
  1070. mCurrentFrame.mvpMapPoints[i]=static_cast<MapPoint*>(NULL);
  1071. }
  1072. }
  1073. // Reset if the camera get lost soon after initialization
  1074. if(mState==LOST)
  1075. {
  1076. if(pCurrentMap->KeyFramesInMap()<=5)
  1077. {
  1078. mpSystem->ResetActiveMap();
  1079. return;
  1080. }
  1081. if ((mSensor == System::IMU_MONOCULAR) || (mSensor == System::IMU_STEREO))
  1082. if (!pCurrentMap->isImuInitialized())
  1083. {
  1084. Verbose::PrintMess("Track lost before IMU initialisation, reseting...", Verbose::VERBOSITY_QUIET);
  1085. mpSystem->ResetActiveMap();
  1086. return;
  1087. }
  1088. CreateMapInAtlas();
  1089. }
  1090. if(!mCurrentFrame.mpReferenceKF)
  1091. mCurrentFrame.mpReferenceKF = mpReferenceKF;
  1092. mLastFrame = Frame(mCurrentFrame);
  1093. }
  1094. if(mState==OK || mState==RECENTLY_LOST)
  1095. {
  1096. // Store frame pose information to retrieve the complete camera trajectory afterwards.
  1097. if(!mCurrentFrame.mTcw.empty())
  1098. {
  1099. cv::Mat Tcr = mCurrentFrame.mTcw*mCurrentFrame.mpReferenceKF->GetPoseInverse();
  1100. mlRelativeFramePoses.push_back(Tcr);
  1101. mlpReferences.push_back(mCurrentFrame.mpReferenceKF);
  1102. mlFrameTimes.push_back(mCurrentFrame.mTimeStamp);
  1103. mlbLost.push_back(mState==LOST);
  1104. }
  1105. else
  1106. {
  1107. // This can happen if tracking is lost
  1108. mlRelativeFramePoses.push_back(mlRelativeFramePoses.back());
  1109. mlpReferences.push_back(mlpReferences.back());
  1110. mlFrameTimes.push_back(mlFrameTimes.back());
  1111. mlbLost.push_back(mState==LOST);
  1112. }
  1113. }
  1114. }
  1115. void Tracking::StereoInitialization()
  1116. {
  1117. if(mCurrentFrame.N>500)
  1118. {
  1119. if (mSensor == System::IMU_STEREO)
  1120. {
  1121. if (!mCurrentFrame.mpImuPreintegrated || !mLastFrame.mpImuPreintegrated)
  1122. {
  1123. cout << "not IMU meas" << endl;
  1124. return;
  1125. }
  1126. if (cv::norm(mCurrentFrame.mpImuPreintegratedFrame->avgA-mLastFrame.mpImuPreintegratedFrame->avgA)<0.5)
  1127. {
  1128. cout << cv::norm(mCurrentFrame.mpImuPreintegratedFrame->avgA) << endl;
  1129. cout << "not enough acceleration" << endl;
  1130. return;
  1131. }
  1132. if(mpImuPreintegratedFromLastKF)
  1133. delete mpImuPreintegratedFromLastKF;
  1134. mpImuPreintegratedFromLastKF = new IMU::Preintegrated(IMU::Bias(),*mpImuCalib);
  1135. mCurrentFrame.mpImuPreintegrated = mpImuPreintegratedFromLastKF;
  1136. }
  1137. // Set Frame pose to the origin (In case of inertial SLAM to imu)
  1138. if (mSensor == System::IMU_STEREO)
  1139. {
  1140. cv::Mat Rwb0 = mCurrentFrame.mImuCalib.Tcb.rowRange(0,3).colRange(0,3).clone();
  1141. cv::Mat twb0 = mCurrentFrame.mImuCalib.Tcb.rowRange(0,3).col(3).clone();
  1142. mCurrentFrame.SetImuPoseVelocity(Rwb0, twb0, cv::Mat::zeros(3,1,CV_32F));
  1143. }
  1144. else
  1145. mCurrentFrame.SetPose(cv::Mat::eye(4,4,CV_32F));
  1146. // Create KeyFrame
  1147. KeyFrame* pKFini = new KeyFrame(mCurrentFrame,mpAtlas->GetCurrentMap(),mpKeyFrameDB);
  1148. // Insert KeyFrame in the map
  1149. mpAtlas->AddKeyFrame(pKFini);
  1150. // Create MapPoints and asscoiate to KeyFrame
  1151. if(!mpCamera2){
  1152. for(int i=0; i<mCurrentFrame.N;i++)
  1153. {
  1154. float z = mCurrentFrame.mvDepth[i];
  1155. if(z>0)
  1156. {
  1157. cv::Mat x3D = mCurrentFrame.UnprojectStereo(i);
  1158. MapPoint* pNewMP = new MapPoint(x3D,pKFini,mpAtlas->GetCurrentMap());
  1159. pNewMP->AddObservation(pKFini,i);
  1160. pKFini->AddMapPoint(pNewMP,i);
  1161. pNewMP->ComputeDistinctiveDescriptors();
  1162. pNewMP->UpdateNormalAndDepth();
  1163. mpAtlas->AddMapPoint(pNewMP);
  1164. mCurrentFrame.mvpMapPoints[i]=pNewMP;
  1165. }
  1166. }
  1167. } else{
  1168. for(int i = 0; i < mCurrentFrame.Nleft; i++){
  1169. int rightIndex = mCurrentFrame.mvLeftToRightMatch[i];
  1170. if(rightIndex != -1){
  1171. cv::Mat x3D = mCurrentFrame.mvStereo3Dpoints[i];
  1172. MapPoint* pNewMP = new MapPoint(x3D,pKFini,mpAtlas->GetCurrentMap());
  1173. pNewMP->AddObservation(pKFini,i);
  1174. pNewMP->AddObservation(pKFini,rightIndex + mCurrentFrame.Nleft);
  1175. pKFini->AddMapPoint(pNewMP,i);
  1176. pKFini->AddMapPoint(pNewMP,rightIndex + mCurrentFrame.Nleft);
  1177. pNewMP->ComputeDistinctiveDescriptors();
  1178. pNewMP->UpdateNormalAndDepth();
  1179. mpAtlas->AddMapPoint(pNewMP);
  1180. mCurrentFrame.mvpMapPoints[i]=pNewMP;
  1181. mCurrentFrame.mvpMapPoints[rightIndex + mCurrentFrame.Nleft]=pNewMP;
  1182. }
  1183. }
  1184. }
  1185. Verbose::PrintMess("New Map created with " + to_string(mpAtlas->MapPointsInMap()) + " points", Verbose::VERBOSITY_QUIET);
  1186. mpLocalMapper->InsertKeyFrame(pKFini);
  1187. mLastFrame = Frame(mCurrentFrame);
  1188. mnLastKeyFrameId=mCurrentFrame.mnId;
  1189. mpLastKeyFrame = pKFini;
  1190. mnLastRelocFrameId = mCurrentFrame.mnId;
  1191. mvpLocalKeyFrames.push_back(pKFini);
  1192. mvpLocalMapPoints=mpAtlas->GetAllMapPoints();
  1193. mpReferenceKF = pKFini;
  1194. mCurrentFrame.mpReferenceKF = pKFini;
  1195. mpAtlas->SetReferenceMapPoints(mvpLocalMapPoints);
  1196. mpAtlas->GetCurrentMap()->mvpKeyFrameOrigins.push_back(pKFini);
  1197. mpMapDrawer->SetCurrentCameraPose(mCurrentFrame.mTcw);
  1198. mState=OK;
  1199. }
  1200. }
  1201. void Tracking::MonocularInitialization()
  1202. {
  1203. if(!mpInitializer)
  1204. {
  1205. // Set Reference Frame
  1206. if(mCurrentFrame.mvKeys.size()>100)
  1207. {
  1208. mInitialFrame = Frame(mCurrentFrame);
  1209. mLastFrame = Frame(mCurrentFrame);
  1210. mvbPrevMatched.resize(mCurrentFrame.mvKeysUn.size());
  1211. for(size_t i=0; i<mCurrentFrame.mvKeysUn.size(); i++)
  1212. mvbPrevMatched[i]=mCurrentFrame.mvKeysUn[i].pt;
  1213. if(mpInitializer)
  1214. delete mpInitializer;
  1215. mpInitializer = new Initializer(mCurrentFrame,1.0,200);
  1216. fill(mvIniMatches.begin(),mvIniMatches.end(),-1);
  1217. if (mSensor == System::IMU_MONOCULAR)
  1218. {
  1219. if(mpImuPreintegratedFromLastKF)
  1220. {
  1221. delete mpImuPreintegratedFromLastKF;
  1222. }
  1223. mpImuPreintegratedFromLastKF = new IMU::Preintegrated(IMU::Bias(),*mpImuCalib);
  1224. mCurrentFrame.mpImuPreintegrated = mpImuPreintegratedFromLastKF;
  1225. }
  1226. return;
  1227. }
  1228. }
  1229. else
  1230. {
  1231. if (((int)mCurrentFrame.mvKeys.size()<=100)||((mSensor == System::IMU_MONOCULAR)&&(mLastFrame.mTimeStamp-mInitialFrame.mTimeStamp>1.0)))
  1232. {
  1233. delete mpInitializer;
  1234. mpInitializer = static_cast<Initializer*>(NULL);
  1235. fill(mvIniMatches.begin(),mvIniMatches.end(),-1);
  1236. return;
  1237. }
  1238. // Find correspondences
  1239. ORBmatcher matcher(0.9,true);
  1240. int nmatches = matcher.SearchForInitialization(mInitialFrame,mCurrentFrame,mvbPrevMatched,mvIniMatches,100);
  1241. // Check if there are enough correspondences
  1242. if(nmatches<100)
  1243. {
  1244. delete mpInitializer;
  1245. mpInitializer = static_cast<Initializer*>(NULL);
  1246. fill(mvIniMatches.begin(),mvIniMatches.end(),-1);
  1247. return;
  1248. }
  1249. cv::Mat Rcw; // Current Camera Rotation
  1250. cv::Mat tcw; // Current Camera Translation
  1251. vector<bool> vbTriangulated; // Triangulated Correspondences (mvIniMatches)
  1252. if(mpCamera->ReconstructWithTwoViews(mInitialFrame.mvKeysUn,mCurrentFrame.mvKeysUn,mvIniMatches,Rcw,tcw,mvIniP3D,vbTriangulated))
  1253. {
  1254. for(size_t i=0, iend=mvIniMatches.size(); i<iend;i++)
  1255. {
  1256. if(mvIniMatches[i]>=0 && !vbTriangulated[i])
  1257. {
  1258. mvIniMatches[i]=-1;
  1259. nmatches--;
  1260. }
  1261. }
  1262. // Set Frame Poses
  1263. mInitialFrame.SetPose(cv::Mat::eye(4,4,CV_32F));
  1264. cv::Mat Tcw = cv::Mat::eye(4,4,CV_32F);
  1265. Rcw.copyTo(Tcw.rowRange(0,3).colRange(0,3));
  1266. tcw.copyTo(Tcw.rowRange(0,3).col(3));
  1267. mCurrentFrame.SetPose(Tcw);
  1268. CreateInitialMapMonocular();
  1269. // Just for video
  1270. // bStepByStep = true;
  1271. }
  1272. }
  1273. }
  1274. void Tracking::CreateInitialMapMonocular()
  1275. {
  1276. // Create KeyFrames
  1277. KeyFrame* pKFini = new KeyFrame(mInitialFrame,mpAtlas->GetCurrentMap(),mpKeyFrameDB);
  1278. KeyFrame* pKFcur = new KeyFrame(mCurrentFrame,mpAtlas->GetCurrentMap(),mpKeyFrameDB);
  1279. if(mSensor == System::IMU_MONOCULAR)
  1280. pKFini->mpImuPreintegrated = (IMU::Preintegrated*)(NULL);
  1281. pKFini->ComputeBoW();
  1282. pKFcur->ComputeBoW();
  1283. // Insert KFs in the map
  1284. mpAtlas->AddKeyFrame(pKFini);
  1285. mpAtlas->AddKeyFrame(pKFcur);
  1286. for(size_t i=0; i<mvIniMatches.size();i++)
  1287. {
  1288. if(mvIniMatches[i]<0)
  1289. continue;
  1290. //Create MapPoint.
  1291. cv::Mat worldPos(mvIniP3D[i]);
  1292. MapPoint* pMP = new MapPoint(worldPos,pKFcur,mpAtlas->GetCurrentMap());
  1293. pKFini->AddMapPoint(pMP,i);
  1294. pKFcur->AddMapPoint(pMP,mvIniMatches[i]);
  1295. pMP->AddObservation(pKFini,i);
  1296. pMP->AddObservation(pKFcur,mvIniMatches[i]);
  1297. pMP->ComputeDistinctiveDescriptors();
  1298. pMP->UpdateNormalAndDepth();
  1299. //Fill Current Frame structure
  1300. mCurrentFrame.mvpMapPoints[mvIniMatches[i]] = pMP;
  1301. mCurrentFrame.mvbOutlier[mvIniMatches[i]] = false;
  1302. //Add to Map
  1303. mpAtlas->AddMapPoint(pMP);
  1304. }
  1305. // Update Connections
  1306. pKFini->UpdateConnections();
  1307. pKFcur->UpdateConnections();
  1308. std::set<MapPoint*> sMPs;
  1309. sMPs = pKFini->GetMapPoints();
  1310. // Bundle Adjustment
  1311. Verbose::PrintMess("New Map created with " + to_string(mpAtlas->MapPointsInMap()) + " points", Verbose::VERBOSITY_QUIET);
  1312. Optimizer::GlobalBundleAdjustemnt(mpAtlas->GetCurrentMap(),20);
  1313. pKFcur->PrintPointDistribution();
  1314. float medianDepth = pKFini->ComputeSceneMedianDepth(2);
  1315. float invMedianDepth;
  1316. if(mSensor == System::IMU_MONOCULAR)
  1317. invMedianDepth = 4.0f/medianDepth; // 4.0f
  1318. else
  1319. invMedianDepth = 1.0f/medianDepth;
  1320. if(medianDepth<0 || pKFcur->TrackedMapPoints(1)<50) // TODO Check, originally 100 tracks
  1321. {
  1322. Verbose::PrintMess("Wrong initialization, reseting...", Verbose::VERBOSITY_NORMAL);
  1323. mpSystem->ResetActiveMap();
  1324. return;
  1325. }
  1326. // Scale initial baseline
  1327. cv::Mat Tc2w = pKFcur->GetPose();
  1328. Tc2w.col(3).rowRange(0,3) = Tc2w.col(3).rowRange(0,3)*invMedianDepth;
  1329. pKFcur->SetPose(Tc2w);
  1330. // Scale points
  1331. vector<MapPoint*> vpAllMapPoints = pKFini->GetMapPointMatches();
  1332. for(size_t iMP=0; iMP<vpAllMapPoints.size(); iMP++)
  1333. {
  1334. if(vpAllMapPoints[iMP])
  1335. {
  1336. MapPoint* pMP = vpAllMapPoints[iMP];
  1337. pMP->SetWorldPos(pMP->GetWorldPos()*invMedianDepth);
  1338. pMP->UpdateNormalAndDepth();
  1339. }
  1340. }
  1341. if (mSensor == System::IMU_MONOCULAR)
  1342. {
  1343. pKFcur->mPrevKF = pKFini;
  1344. pKFini->mNextKF = pKFcur;
  1345. pKFcur->mpImuPreintegrated = mpImuPreintegratedFromLastKF;
  1346. mpImuPreintegratedFromLastKF = new IMU::Preintegrated(pKFcur->mpImuPreintegrated->GetUpdatedBias(),pKFcur->mImuCalib);
  1347. }
  1348. mpLocalMapper->InsertKeyFrame(pKFini);
  1349. mpLocalMapper->InsertKeyFrame(pKFcur);
  1350. mpLocalMapper->mFirstTs=pKFcur->mTimeStamp;
  1351. mCurrentFrame.SetPose(pKFcur->GetPose());
  1352. mnLastKeyFrameId=mCurrentFrame.mnId;
  1353. mpLastKeyFrame = pKFcur;
  1354. mnLastRelocFrameId = mInitialFrame.mnId;
  1355. mvpLocalKeyFrames.push_back(pKFcur);
  1356. mvpLocalKeyFrames.push_back(pKFini);
  1357. mvpLocalMapPoints=mpAtlas->GetAllMapPoints();
  1358. mpReferenceKF = pKFcur;
  1359. mCurrentFrame.mpReferenceKF = pKFcur;
  1360. // Compute here initial velocity
  1361. vector<KeyFrame*> vKFs = mpAtlas->GetAllKeyFrames();
  1362. cv::Mat deltaT = vKFs.back()->GetPose()*vKFs.front()->GetPoseInverse();
  1363. mVelocity = cv::Mat();
  1364. Eigen::Vector3d phi = LogSO3(Converter::toMatrix3d(deltaT.rowRange(0,3).colRange(0,3)));
  1365. double aux = (mCurrentFrame.mTimeStamp-mLastFrame.mTimeStamp)/(mCurrentFrame.mTimeStamp-mInitialFrame.mTimeStamp);
  1366. phi *= aux;
  1367. mLastFrame = Frame(mCurrentFrame);
  1368. mpAtlas->SetReferenceMapPoints(mvpLocalMapPoints);
  1369. mpMapDrawer->SetCurrentCameraPose(pKFcur->GetPose());
  1370. mpAtlas->GetCurrentMap()->mvpKeyFrameOrigins.push_back(pKFini);
  1371. mState=OK;
  1372. initID = pKFcur->mnId;
  1373. }
  1374. void Tracking::CreateMapInAtlas()
  1375. {
  1376. mnLastInitFrameId = mCurrentFrame.mnId;
  1377. mpAtlas->CreateNewMap();
  1378. if (mSensor==System::IMU_STEREO || mSensor == System::IMU_MONOCULAR)
  1379. mpAtlas->SetInertialSensor();
  1380. mbSetInit=false;
  1381. mnInitialFrameId = mCurrentFrame.mnId+1;
  1382. mState = NO_IMAGES_YET;
  1383. // Restart the variable with information about the last KF
  1384. mVelocity = cv::Mat();
  1385. mnLastRelocFrameId = mnLastInitFrameId; // The last relocation KF_id is the current id, because it is the new starting point for new map
  1386. Verbose::PrintMess("First frame id in map: " + to_string(mnLastInitFrameId+1), Verbose::VERBOSITY_NORMAL);
  1387. mbVO = false; // Init value for know if there are enough MapPoints in the last KF
  1388. if(mSensor == System::MONOCULAR || mSensor == System::IMU_MONOCULAR)
  1389. {
  1390. if(mpInitializer)
  1391. delete mpInitializer;
  1392. mpInitializer = static_cast<Initializer*>(NULL);
  1393. }
  1394. if((mSensor == System::IMU_MONOCULAR || mSensor == System::IMU_STEREO ) && mpImuPreintegratedFromLastKF)
  1395. {
  1396. delete mpImuPreintegratedFromLastKF;
  1397. mpImuPreintegratedFromLastKF = new IMU::Preintegrated(IMU::Bias(),*mpImuCalib);
  1398. }
  1399. if(mpLastKeyFrame)
  1400. mpLastKeyFrame = static_cast<KeyFrame*>(NULL);
  1401. if(mpReferenceKF)
  1402. mpReferenceKF = static_cast<KeyFrame*>(NULL);
  1403. mLastFrame = Frame();
  1404. mCurrentFrame = Frame();
  1405. mvIniMatches.clear();
  1406. mbCreatedMap = true;
  1407. }
  1408. void Tracking::CheckReplacedInLastFrame()
  1409. {
  1410. for(int i =0; i<mLastFrame.N; i++)
  1411. {
  1412. MapPoint* pMP = mLastFrame.mvpMapPoints[i];
  1413. if(pMP)
  1414. {
  1415. MapPoint* pRep = pMP->GetReplaced();
  1416. if(pRep)
  1417. {
  1418. mLastFrame.mvpMapPoints[i] = pRep;
  1419. }
  1420. }
  1421. }
  1422. }
  1423. bool Tracking::TrackReferenceKeyFrame()
  1424. {
  1425. // Compute Bag of Words vector
  1426. mCurrentFrame.ComputeBoW();
  1427. // We perform first an ORB matching with the reference keyframe
  1428. // If enough matches are found we setup a PnP solver
  1429. ORBmatcher matcher(0.7,true);
  1430. vector<MapPoint*> vpMapPointMatches;
  1431. int nmatches = matcher.SearchByBoW(mpReferenceKF,mCurrentFrame,vpMapPointMatches);
  1432. if(nmatches<15)
  1433. {
  1434. cout << "TRACK_REF_KF: Less than 15 matches!!\n";
  1435. return false;
  1436. }
  1437. mCurrentFrame.mvpMapPoints = vpMapPointMatches;
  1438. mCurrentFrame.SetPose(mLastFrame.mTcw);
  1439. //mCurrentFrame.PrintPointDistribution();
  1440. // cout << " TrackReferenceKeyFrame mLastFrame.mTcw: " << mLastFrame.mTcw << endl;
  1441. Optimizer::PoseOptimization(&mCurrentFrame);
  1442. // Discard outliers
  1443. int nmatchesMap = 0;
  1444. for(int i =0; i<mCurrentFrame.N; i++)
  1445. {
  1446. //if(i >= mCurrentFrame.Nleft) break;
  1447. if(mCurrentFrame.mvpMapPoints[i])
  1448. {
  1449. if(mCurrentFrame.mvbOutlier[i])
  1450. {
  1451. MapPoint* pMP = mCurrentFrame.mvpMapPoints[i];
  1452. mCurrentFrame.mvpMapPoints[i]=static_cast<MapPoint*>(NULL);
  1453. mCurrentFrame.mvbOutlier[i]=false;
  1454. if(i < mCurrentFrame.Nleft){
  1455. pMP->mbTrackInView = false;
  1456. }
  1457. else{
  1458. pMP->mbTrackInViewR = false;
  1459. }
  1460. pMP->mbTrackInView = false;
  1461. pMP->mnLastFrameSeen = mCurrentFrame.mnId;
  1462. nmatches--;
  1463. }
  1464. else if(mCurrentFrame.mvpMapPoints[i]->Observations()>0)
  1465. nmatchesMap++;
  1466. }
  1467. }
  1468. // TODO check these conditions
  1469. if (mSensor == System::IMU_MONOCULAR || mSensor == System::IMU_STEREO)
  1470. return true;
  1471. else
  1472. return nmatchesMap>=10;
  1473. }
  1474. void Tracking::UpdateLastFrame()
  1475. {
  1476. // Update pose according to reference keyframe
  1477. KeyFrame* pRef = mLastFrame.mpReferenceKF;
  1478. cv::Mat Tlr = mlRelativeFramePoses.back();
  1479. mLastFrame.SetPose(Tlr*pRef->GetPose());
  1480. if(mnLastKeyFrameId==mLastFrame.mnId || mSensor==System::MONOCULAR || mSensor==System::IMU_MONOCULAR || !mbOnlyTracking)
  1481. return;
  1482. // Create "visual odometry" MapPoints
  1483. // We sort points according to their measured depth by the stereo/RGB-D sensor
  1484. vector<pair<float,int> > vDepthIdx;
  1485. vDepthIdx.reserve(mLastFrame.N);
  1486. for(int i=0; i<mLastFrame.N;i++)
  1487. {
  1488. float z = mLastFrame.mvDepth[i];
  1489. if(z>0)
  1490. {
  1491. vDepthIdx.push_back(make_pair(z,i));
  1492. }
  1493. }
  1494. if(vDepthIdx.empty())
  1495. return;
  1496. sort(vDepthIdx.begin(),vDepthIdx.end());
  1497. // We insert all close points (depth<mThDepth)
  1498. // If less than 100 close points, we insert the 100 closest ones.
  1499. int nPoints = 0;
  1500. for(size_t j=0; j<vDepthIdx.size();j++)
  1501. {
  1502. int i = vDepthIdx[j].second;
  1503. bool bCreateNew = false;
  1504. MapPoint* pMP = mLastFrame.mvpMapPoints[i];
  1505. if(!pMP)
  1506. bCreateNew = true;
  1507. else if(pMP->Observations()<1)
  1508. {
  1509. bCreateNew = true;
  1510. }
  1511. if(bCreateNew)
  1512. {
  1513. cv::Mat x3D = mLastFrame.UnprojectStereo(i);
  1514. MapPoint* pNewMP = new MapPoint(x3D,mpAtlas->GetCurrentMap(),&mLastFrame,i);
  1515. mLastFrame.mvpMapPoints[i]=pNewMP;
  1516. mlpTemporalPoints.push_back(pNewMP);
  1517. nPoints++;
  1518. }
  1519. else
  1520. {
  1521. nPoints++;
  1522. }
  1523. if(vDepthIdx[j].first>mThDepth && nPoints>100)
  1524. {
  1525. break;
  1526. }
  1527. }
  1528. }
  1529. bool Tracking::TrackWithMotionModel()
  1530. {
  1531. ORBmatcher matcher(0.9,true);
  1532. // Update last frame pose according to its reference keyframe
  1533. // Create "visual odometry" points if in Localization Mode
  1534. UpdateLastFrame();
  1535. if (mpAtlas->isImuInitialized() && (mCurrentFrame.mnId>mnLastRelocFrameId+mnFramesToResetIMU))
  1536. {
  1537. // Predict ste with IMU if it is initialized and it doesnt need reset
  1538. PredictStateIMU();
  1539. return true;
  1540. }
  1541. else
  1542. {
  1543. mCurrentFrame.SetPose(mVelocity*mLastFrame.mTcw);
  1544. }
  1545. fill(mCurrentFrame.mvpMapPoints.begin(),mCurrentFrame.mvpMapPoints.end(),static_cast<MapPoint*>(NULL));
  1546. // Project points seen in previous frame
  1547. int th;
  1548. if(mSensor==System::STEREO)
  1549. th=7;
  1550. else
  1551. th=15;
  1552. int nmatches = matcher.SearchByProjection(mCurrentFrame,mLastFrame,th,mSensor==System::MONOCULAR || mSensor==System::IMU_MONOCULAR);
  1553. // If few matches, uses a wider window search
  1554. if(nmatches<20)
  1555. {
  1556. Verbose::PrintMess("Not enough matches, wider window search!!", Verbose::VERBOSITY_NORMAL);
  1557. fill(mCurrentFrame.mvpMapPoints.begin(),mCurrentFrame.mvpMapPoints.end(),static_cast<MapPoint*>(NULL));
  1558. nmatches = matcher.SearchByProjection(mCurrentFrame,mLastFrame,2*th,mSensor==System::MONOCULAR || mSensor==System::IMU_MONOCULAR);
  1559. Verbose::PrintMess("Matches with wider search: " + to_string(nmatches), Verbose::VERBOSITY_NORMAL);
  1560. }
  1561. if(nmatches<20)
  1562. {
  1563. Verbose::PrintMess("Not enough matches!!", Verbose::VERBOSITY_NORMAL);
  1564. if (mSensor == System::IMU_MONOCULAR || mSensor == System::IMU_STEREO)
  1565. return true;
  1566. else
  1567. return false;
  1568. }
  1569. // Optimize frame pose with all matches
  1570. Optimizer::PoseOptimization(&mCurrentFrame);
  1571. // Discard outliers
  1572. int nmatchesMap = 0;
  1573. for(int i =0; i<mCurrentFrame.N; i++)
  1574. {
  1575. if(mCurrentFrame.mvpMapPoints[i])
  1576. {
  1577. if(mCurrentFrame.mvbOutlier[i])
  1578. {
  1579. MapPoint* pMP = mCurrentFrame.mvpMapPoints[i];
  1580. mCurrentFrame.mvpMapPoints[i]=static_cast<MapPoint*>(NULL);
  1581. mCurrentFrame.mvbOutlier[i]=false;
  1582. if(i < mCurrentFrame.Nleft){
  1583. pMP->mbTrackInView = false;
  1584. }
  1585. else{
  1586. pMP->mbTrackInViewR = false;
  1587. }
  1588. pMP->mnLastFrameSeen = mCurrentFrame.mnId;
  1589. nmatches--;
  1590. }
  1591. else if(mCurrentFrame.mvpMapPoints[i]->Observations()>0)
  1592. nmatchesMap++;
  1593. }
  1594. }
  1595. if(mbOnlyTracking)
  1596. {
  1597. mbVO = nmatchesMap<10;
  1598. return nmatches>20;
  1599. }
  1600. if (mSensor == System::IMU_MONOCULAR || mSensor == System::IMU_STEREO)
  1601. return true;
  1602. else
  1603. return nmatchesMap>=10;
  1604. }
  1605. bool Tracking::TrackLocalMap()
  1606. {
  1607. // We have an estimation of the camera pose and some map points tracked in the frame.
  1608. // We retrieve the local map and try to find matches to points in the local map.
  1609. mTrackedFr++;
  1610. UpdateLocalMap();
  1611. SearchLocalPoints();
  1612. // TOO check outliers before PO
  1613. int aux1 = 0, aux2=0;
  1614. for(int i=0; i<mCurrentFrame.N; i++)
  1615. if( mCurrentFrame.mvpMapPoints[i])
  1616. {
  1617. aux1++;
  1618. if(mCurrentFrame.mvbOutlier[i])
  1619. aux2++;
  1620. }
  1621. int inliers;
  1622. if (!mpAtlas->isImuInitialized())
  1623. Optimizer::PoseOptimization(&mCurrentFrame);
  1624. else
  1625. {
  1626. if(mCurrentFrame.mnId<=mnLastRelocFrameId+mnFramesToResetIMU)
  1627. {
  1628. Verbose::PrintMess("TLM: PoseOptimization ", Verbose::VERBOSITY_DEBUG);
  1629. Optimizer::PoseOptimization(&mCurrentFrame);
  1630. }
  1631. else
  1632. {
  1633. // if(!mbMapUpdated && mState == OK) // && (mnMatchesInliers>30))
  1634. if(!mbMapUpdated) // && (mnMatchesInliers>30))
  1635. {
  1636. Verbose::PrintMess("TLM: PoseInertialOptimizationLastFrame ", Verbose::VERBOSITY_DEBUG);
  1637. inliers = Optimizer::PoseInertialOptimizationLastFrame(&mCurrentFrame); // , !mpLastKeyFrame->GetMap()->GetIniertialBA1());
  1638. }
  1639. else
  1640. {
  1641. Verbose::PrintMess("TLM: PoseInertialOptimizationLastKeyFrame ", Verbose::VERBOSITY_DEBUG);
  1642. inliers = Optimizer::PoseInertialOptimizationLastKeyFrame(&mCurrentFrame); // , !mpLastKeyFrame->GetMap()->GetIniertialBA1());
  1643. }
  1644. }
  1645. }
  1646. aux1 = 0, aux2 = 0;
  1647. for(int i=0; i<mCurrentFrame.N; i++)
  1648. if( mCurrentFrame.mvpMapPoints[i])
  1649. {
  1650. aux1++;
  1651. if(mCurrentFrame.mvbOutlier[i])
  1652. aux2++;
  1653. }
  1654. mnMatchesInliers = 0;
  1655. // Update MapPoints Statistics
  1656. for(int i=0; i<mCurrentFrame.N; i++)
  1657. {
  1658. if(mCurrentFrame.mvpMapPoints[i])
  1659. {
  1660. if(!mCurrentFrame.mvbOutlier[i])
  1661. {
  1662. mCurrentFrame.mvpMapPoints[i]->IncreaseFound();
  1663. if(!mbOnlyTracking)
  1664. {
  1665. if(mCurrentFrame.mvpMapPoints[i]->Observations()>0)
  1666. mnMatchesInliers++;
  1667. }
  1668. else
  1669. mnMatchesInliers++;
  1670. }
  1671. else if(mSensor==System::STEREO)
  1672. mCurrentFrame.mvpMapPoints[i] = static_cast<MapPoint*>(NULL);
  1673. }
  1674. }
  1675. // Decide if the tracking was succesful
  1676. // More restrictive if there was a relocalization recently
  1677. mpLocalMapper->mnMatchesInliers=mnMatchesInliers;
  1678. if(mCurrentFrame.mnId<mnLastRelocFrameId+mMaxFrames && mnMatchesInliers<50)
  1679. return false;
  1680. if((mnMatchesInliers>10)&&(mState==RECENTLY_LOST))
  1681. return true;
  1682. if (mSensor == System::IMU_MONOCULAR)
  1683. {
  1684. if(mnMatchesInliers<15)
  1685. {
  1686. return false;
  1687. }
  1688. else
  1689. return true;
  1690. }
  1691. else if (mSensor == System::IMU_STEREO)
  1692. {
  1693. if(mnMatchesInliers<15)
  1694. {
  1695. return false;
  1696. }
  1697. else
  1698. return true;
  1699. }
  1700. else
  1701. {
  1702. if(mnMatchesInliers<30)
  1703. return false;
  1704. else
  1705. return true;
  1706. }
  1707. }
  1708. bool Tracking::NeedNewKeyFrame()
  1709. {
  1710. if(((mSensor == System::IMU_MONOCULAR) || (mSensor == System::IMU_STEREO)) && !mpAtlas->GetCurrentMap()->isImuInitialized())
  1711. {
  1712. if (mSensor == System::IMU_MONOCULAR && (mCurrentFrame.mTimeStamp-mpLastKeyFrame->mTimeStamp)>=0.25)
  1713. return true;
  1714. else if (mSensor == System::IMU_STEREO && (mCurrentFrame.mTimeStamp-mpLastKeyFrame->mTimeStamp)>=0.25)
  1715. return true;
  1716. else
  1717. return false;
  1718. }
  1719. if(mbOnlyTracking)
  1720. return false;
  1721. // If Local Mapping is freezed by a Loop Closure do not insert keyframes
  1722. if(mpLocalMapper->isStopped() || mpLocalMapper->stopRequested())
  1723. {
  1724. return false;
  1725. }
  1726. // Return false if IMU is initialazing
  1727. if (mpLocalMapper->IsInitializing())
  1728. return false;
  1729. const int nKFs = mpAtlas->KeyFramesInMap();
  1730. // Do not insert keyframes if not enough frames have passed from last relocalisation
  1731. if(mCurrentFrame.mnId<mnLastRelocFrameId+mMaxFrames && nKFs>mMaxFrames)
  1732. {
  1733. return false;
  1734. }
  1735. // Tracked MapPoints in the reference keyframe
  1736. int nMinObs = 3;
  1737. if(nKFs<=2)
  1738. nMinObs=2;
  1739. int nRefMatches = mpReferenceKF->TrackedMapPoints(nMinObs);
  1740. // Local Mapping accept keyframes?
  1741. bool bLocalMappingIdle = mpLocalMapper->AcceptKeyFrames();
  1742. // Check how many "close" points are being tracked and how many could be potentially created.
  1743. int nNonTrackedClose = 0;
  1744. int nTrackedClose= 0;
  1745. if(mSensor!=System::MONOCULAR && mSensor!=System::IMU_MONOCULAR)
  1746. {
  1747. int N = (mCurrentFrame.Nleft == -1) ? mCurrentFrame.N : mCurrentFrame.Nleft;
  1748. for(int i =0; i<N; i++)
  1749. {
  1750. if(mCurrentFrame.mvDepth[i]>0 && mCurrentFrame.mvDepth[i]<mThDepth)
  1751. {
  1752. if(mCurrentFrame.mvpMapPoints[i] && !mCurrentFrame.mvbOutlier[i])
  1753. nTrackedClose++;
  1754. else
  1755. nNonTrackedClose++;
  1756. }
  1757. }
  1758. }
  1759. bool bNeedToInsertClose;
  1760. bNeedToInsertClose = (nTrackedClose<100) && (nNonTrackedClose>70);
  1761. // Thresholds
  1762. float thRefRatio = 0.75f;
  1763. if(nKFs<2)
  1764. thRefRatio = 0.4f;
  1765. if(mSensor==System::MONOCULAR)
  1766. thRefRatio = 0.9f;
  1767. if(mpCamera2) thRefRatio = 0.75f;
  1768. if(mSensor==System::IMU_MONOCULAR)
  1769. {
  1770. if(mnMatchesInliers>350) // Points tracked from the local map
  1771. thRefRatio = 0.75f;
  1772. else
  1773. thRefRatio = 0.90f;
  1774. }
  1775. // Condition 1a: More than "MaxFrames" have passed from last keyframe insertion
  1776. const bool c1a = mCurrentFrame.mnId>=mnLastKeyFrameId+mMaxFrames;
  1777. // Condition 1b: More than "MinFrames" have passed and Local Mapping is idle
  1778. const bool c1b = ((mCurrentFrame.mnId>=mnLastKeyFrameId+mMinFrames) && bLocalMappingIdle);
  1779. //Condition 1c: tracking is weak
  1780. const bool c1c = mSensor!=System::MONOCULAR && mSensor!=System::IMU_MONOCULAR && mSensor!=System::IMU_STEREO && (mnMatchesInliers<nRefMatches*0.25 || bNeedToInsertClose) ;
  1781. // Condition 2: Few tracked points compared to reference keyframe. Lots of visual odometry compared to map matches.
  1782. const bool c2 = (((mnMatchesInliers<nRefMatches*thRefRatio || bNeedToInsertClose)) && mnMatchesInliers>15);
  1783. // Temporal condition for Inertial cases
  1784. bool c3 = false;
  1785. if(mpLastKeyFrame)
  1786. {
  1787. if (mSensor==System::IMU_MONOCULAR)
  1788. {
  1789. if ((mCurrentFrame.mTimeStamp-mpLastKeyFrame->mTimeStamp)>=0.5)
  1790. c3 = true;
  1791. }
  1792. else if (mSensor==System::IMU_STEREO)
  1793. {
  1794. if ((mCurrentFrame.mTimeStamp-mpLastKeyFrame->mTimeStamp)>=0.5)
  1795. c3 = true;
  1796. }
  1797. }
  1798. bool c4 = false;
  1799. if ((((mnMatchesInliers<75) && (mnMatchesInliers>15)) || mState==RECENTLY_LOST) && ((mSensor == System::IMU_MONOCULAR))) // MODIFICATION_2, originally ((((mnMatchesInliers<75) && (mnMatchesInliers>15)) || mState==RECENTLY_LOST) && ((mSensor == System::IMU_MONOCULAR)))
  1800. c4=true;
  1801. else
  1802. c4=false;
  1803. if(((c1a||c1b||c1c) && c2)||c3 ||c4)
  1804. {
  1805. // If the mapping accepts keyframes, insert keyframe.
  1806. // Otherwise send a signal to interrupt BA
  1807. if(bLocalMappingIdle)
  1808. {
  1809. return true;
  1810. }
  1811. else
  1812. {
  1813. mpLocalMapper->InterruptBA();
  1814. if(mSensor!=System::MONOCULAR && mSensor!=System::IMU_MONOCULAR)
  1815. {
  1816. if(mpLocalMapper->KeyframesInQueue()<3)
  1817. return true;
  1818. else
  1819. return false;
  1820. }
  1821. else
  1822. return false;
  1823. }
  1824. }
  1825. else
  1826. return false;
  1827. }
  1828. void Tracking::CreateNewKeyFrame()
  1829. {
  1830. if(mpLocalMapper->IsInitializing())
  1831. return;
  1832. if(!mpLocalMapper->SetNotStop(true))
  1833. return;
  1834. KeyFrame* pKF = new KeyFrame(mCurrentFrame,mpAtlas->GetCurrentMap(),mpKeyFrameDB);
  1835. if(mpAtlas->isImuInitialized())
  1836. pKF->bImu = true;
  1837. pKF->SetNewBias(mCurrentFrame.mImuBias);
  1838. mpReferenceKF = pKF;
  1839. mCurrentFrame.mpReferenceKF = pKF;
  1840. if(mpLastKeyFrame)
  1841. {
  1842. pKF->mPrevKF = mpLastKeyFrame;
  1843. mpLastKeyFrame->mNextKF = pKF;
  1844. }
  1845. else
  1846. Verbose::PrintMess("No last KF in KF creation!!", Verbose::VERBOSITY_NORMAL);
  1847. // Reset preintegration from last KF (Create new object)
  1848. if (mSensor == System::IMU_MONOCULAR || mSensor == System::IMU_STEREO)
  1849. {
  1850. mpImuPreintegratedFromLastKF = new IMU::Preintegrated(pKF->GetImuBias(),pKF->mImuCalib);
  1851. }
  1852. if(mSensor!=System::MONOCULAR && mSensor != System::IMU_MONOCULAR) // TODO check if incluide imu_stereo
  1853. {
  1854. mCurrentFrame.UpdatePoseMatrices();
  1855. // cout << "create new MPs" << endl;
  1856. // We sort points by the measured depth by the stereo/RGBD sensor.
  1857. // We create all those MapPoints whose depth < mThDepth.
  1858. // If there are less than 100 close points we create the 100 closest.
  1859. int maxPoint = 100;
  1860. if(mSensor == System::IMU_STEREO)
  1861. maxPoint = 100;
  1862. vector<pair<float,int> > vDepthIdx;
  1863. int N = (mCurrentFrame.Nleft != -1) ? mCurrentFrame.Nleft : mCurrentFrame.N;
  1864. vDepthIdx.reserve(mCurrentFrame.N);
  1865. for(int i=0; i<N; i++)
  1866. {
  1867. float z = mCurrentFrame.mvDepth[i];
  1868. if(z>0)
  1869. {
  1870. vDepthIdx.push_back(make_pair(z,i));
  1871. }
  1872. }
  1873. if(!vDepthIdx.empty())
  1874. {
  1875. sort(vDepthIdx.begin(),vDepthIdx.end());
  1876. int nPoints = 0;
  1877. for(size_t j=0; j<vDepthIdx.size();j++)
  1878. {
  1879. int i = vDepthIdx[j].second;
  1880. bool bCreateNew = false;
  1881. MapPoint* pMP = mCurrentFrame.mvpMapPoints[i];
  1882. if(!pMP)
  1883. bCreateNew = true;
  1884. else if(pMP->Observations()<1)
  1885. {
  1886. bCreateNew = true;
  1887. mCurrentFrame.mvpMapPoints[i] = static_cast<MapPoint*>(NULL);
  1888. }
  1889. if(bCreateNew)
  1890. {
  1891. cv::Mat x3D;
  1892. if(mCurrentFrame.Nleft == -1){
  1893. x3D = mCurrentFrame.UnprojectStereo(i);
  1894. }
  1895. else{
  1896. x3D = mCurrentFrame.UnprojectStereoFishEye(i);
  1897. }
  1898. MapPoint* pNewMP = new MapPoint(x3D,pKF,mpAtlas->GetCurrentMap());
  1899. pNewMP->AddObservation(pKF,i);
  1900. //Check if it is a stereo observation in order to not
  1901. //duplicate mappoints
  1902. if(mCurrentFrame.Nleft != -1 && mCurrentFrame.mvLeftToRightMatch[i] >= 0){
  1903. mCurrentFrame.mvpMapPoints[mCurrentFrame.Nleft + mCurrentFrame.mvLeftToRightMatch[i]]=pNewMP;
  1904. pNewMP->AddObservation(pKF,mCurrentFrame.Nleft + mCurrentFrame.mvLeftToRightMatch[i]);
  1905. pKF->AddMapPoint(pNewMP,mCurrentFrame.Nleft + mCurrentFrame.mvLeftToRightMatch[i]);
  1906. }
  1907. pKF->AddMapPoint(pNewMP,i);
  1908. pNewMP->ComputeDistinctiveDescriptors();
  1909. pNewMP->UpdateNormalAndDepth();
  1910. mpAtlas->AddMapPoint(pNewMP);
  1911. mCurrentFrame.mvpMapPoints[i]=pNewMP;
  1912. nPoints++;
  1913. }
  1914. else
  1915. {
  1916. nPoints++; // TODO check ???
  1917. }
  1918. if(vDepthIdx[j].first>mThDepth && nPoints>maxPoint)
  1919. {
  1920. break;
  1921. }
  1922. }
  1923. Verbose::PrintMess("new mps for stereo KF: " + to_string(nPoints), Verbose::VERBOSITY_NORMAL);
  1924. }
  1925. }
  1926. mpLocalMapper->InsertKeyFrame(pKF);
  1927. mpLocalMapper->SetNotStop(false);
  1928. mnLastKeyFrameId = mCurrentFrame.mnId;
  1929. mpLastKeyFrame = pKF;
  1930. //cout << "end creating new KF" << endl;
  1931. }
  1932. void Tracking::SearchLocalPoints()
  1933. {
  1934. // Do not search map points already matched
  1935. for(vector<MapPoint*>::iterator vit=mCurrentFrame.mvpMapPoints.begin(), vend=mCurrentFrame.mvpMapPoints.end(); vit!=vend; vit++)
  1936. {
  1937. MapPoint* pMP = *vit;
  1938. if(pMP)
  1939. {
  1940. if(pMP->isBad())
  1941. {
  1942. *vit = static_cast<MapPoint*>(NULL);
  1943. }
  1944. else
  1945. {
  1946. pMP->IncreaseVisible();
  1947. pMP->mnLastFrameSeen = mCurrentFrame.mnId;
  1948. pMP->mbTrackInView = false;
  1949. pMP->mbTrackInViewR = false;
  1950. }
  1951. }
  1952. }
  1953. int nToMatch=0;
  1954. // Project points in frame and check its visibility
  1955. for(vector<MapPoint*>::iterator vit=mvpLocalMapPoints.begin(), vend=mvpLocalMapPoints.end(); vit!=vend; vit++)
  1956. {
  1957. MapPoint* pMP = *vit;
  1958. if(pMP->mnLastFrameSeen == mCurrentFrame.mnId)
  1959. continue;
  1960. if(pMP->isBad())
  1961. continue;
  1962. // Project (this fills MapPoint variables for matching)
  1963. if(mCurrentFrame.isInFrustum(pMP,0.5))
  1964. {
  1965. pMP->IncreaseVisible();
  1966. nToMatch++;
  1967. }
  1968. if(pMP->mbTrackInView)
  1969. {
  1970. mCurrentFrame.mmProjectPoints[pMP->mnId] = cv::Point2f(pMP->mTrackProjX, pMP->mTrackProjY);
  1971. }
  1972. }
  1973. if(nToMatch>0)
  1974. {
  1975. ORBmatcher matcher(0.8);
  1976. int th = 1;
  1977. if(mSensor==System::RGBD)
  1978. th=3;
  1979. if(mpAtlas->isImuInitialized())
  1980. {
  1981. if(mpAtlas->GetCurrentMap()->GetIniertialBA2())
  1982. th=2;
  1983. else
  1984. th=3;
  1985. }
  1986. else if(!mpAtlas->isImuInitialized() && (mSensor==System::IMU_MONOCULAR || mSensor==System::IMU_STEREO))
  1987. {
  1988. th=10;
  1989. }
  1990. // If the camera has been relocalised recently, perform a coarser search
  1991. if(mCurrentFrame.mnId<mnLastRelocFrameId+2)
  1992. th=5;
  1993. if(mState==LOST || mState==RECENTLY_LOST) // Lost for less than 1 second
  1994. th=15; // 15
  1995. int matches = matcher.SearchByProjection(mCurrentFrame, mvpLocalMapPoints, th, mpLocalMapper->mbFarPoints, mpLocalMapper->mThFarPoints);
  1996. }
  1997. }
  1998. void Tracking::UpdateLocalMap()
  1999. {
  2000. // This is for visualization
  2001. mpAtlas->SetReferenceMapPoints(mvpLocalMapPoints);
  2002. // Update
  2003. UpdateLocalKeyFrames();
  2004. UpdateLocalPoints();
  2005. }
  2006. void Tracking::UpdateLocalPoints()
  2007. {
  2008. mvpLocalMapPoints.clear();
  2009. int count_pts = 0;
  2010. for(vector<KeyFrame*>::const_reverse_iterator itKF=mvpLocalKeyFrames.rbegin(), itEndKF=mvpLocalKeyFrames.rend(); itKF!=itEndKF; ++itKF)
  2011. {
  2012. KeyFrame* pKF = *itKF;
  2013. const vector<MapPoint*> vpMPs = pKF->GetMapPointMatches();
  2014. for(vector<MapPoint*>::const_iterator itMP=vpMPs.begin(), itEndMP=vpMPs.end(); itMP!=itEndMP; itMP++)
  2015. {
  2016. MapPoint* pMP = *itMP;
  2017. if(!pMP)
  2018. continue;
  2019. if(pMP->mnTrackReferenceForFrame==mCurrentFrame.mnId)
  2020. continue;
  2021. if(!pMP->isBad())
  2022. {
  2023. count_pts++;
  2024. mvpLocalMapPoints.push_back(pMP);
  2025. pMP->mnTrackReferenceForFrame=mCurrentFrame.mnId;
  2026. }
  2027. }
  2028. }
  2029. }
  2030. void Tracking::UpdateLocalKeyFrames()
  2031. {
  2032. // Each map point vote for the keyframes in which it has been observed
  2033. map<KeyFrame*,int> keyframeCounter;
  2034. if(!mpAtlas->isImuInitialized() || (mCurrentFrame.mnId<mnLastRelocFrameId+2))
  2035. {
  2036. for(int i=0; i<mCurrentFrame.N; i++)
  2037. {
  2038. MapPoint* pMP = mCurrentFrame.mvpMapPoints[i];
  2039. if(pMP)
  2040. {
  2041. if(!pMP->isBad())
  2042. {
  2043. const map<KeyFrame*,tuple<int,int>> observations = pMP->GetObservations();
  2044. for(map<KeyFrame*,tuple<int,int>>::const_iterator it=observations.begin(), itend=observations.end(); it!=itend; it++)
  2045. keyframeCounter[it->first]++;
  2046. }
  2047. else
  2048. {
  2049. mCurrentFrame.mvpMapPoints[i]=NULL;
  2050. }
  2051. }
  2052. }
  2053. }
  2054. else
  2055. {
  2056. for(int i=0; i<mLastFrame.N; i++)
  2057. {
  2058. // Using lastframe since current frame has not matches yet
  2059. if(mLastFrame.mvpMapPoints[i])
  2060. {
  2061. MapPoint* pMP = mLastFrame.mvpMapPoints[i];
  2062. if(!pMP)
  2063. continue;
  2064. if(!pMP->isBad())
  2065. {
  2066. const map<KeyFrame*,tuple<int,int>> observations = pMP->GetObservations();
  2067. for(map<KeyFrame*,tuple<int,int>>::const_iterator it=observations.begin(), itend=observations.end(); it!=itend; it++)
  2068. keyframeCounter[it->first]++;
  2069. }
  2070. else
  2071. {
  2072. // MODIFICATION
  2073. mLastFrame.mvpMapPoints[i]=NULL;
  2074. }
  2075. }
  2076. }
  2077. }
  2078. int max=0;
  2079. KeyFrame* pKFmax= static_cast<KeyFrame*>(NULL);
  2080. mvpLocalKeyFrames.clear();
  2081. mvpLocalKeyFrames.reserve(3*keyframeCounter.size());
  2082. // All keyframes that observe a map point are included in the local map. Also check which keyframe shares most points
  2083. for(map<KeyFrame*,int>::const_iterator it=keyframeCounter.begin(), itEnd=keyframeCounter.end(); it!=itEnd; it++)
  2084. {
  2085. KeyFrame* pKF = it->first;
  2086. if(pKF->isBad())
  2087. continue;
  2088. if(it->second>max)
  2089. {
  2090. max=it->second;
  2091. pKFmax=pKF;
  2092. }
  2093. mvpLocalKeyFrames.push_back(pKF);
  2094. pKF->mnTrackReferenceForFrame = mCurrentFrame.mnId;
  2095. }
  2096. // Include also some not-already-included keyframes that are neighbors to already-included keyframes
  2097. for(vector<KeyFrame*>::const_iterator itKF=mvpLocalKeyFrames.begin(), itEndKF=mvpLocalKeyFrames.end(); itKF!=itEndKF; itKF++)
  2098. {
  2099. // Limit the number of keyframes
  2100. if(mvpLocalKeyFrames.size()>80) // 80
  2101. break;
  2102. KeyFrame* pKF = *itKF;
  2103. const vector<KeyFrame*> vNeighs = pKF->GetBestCovisibilityKeyFrames(10);
  2104. for(vector<KeyFrame*>::const_iterator itNeighKF=vNeighs.begin(), itEndNeighKF=vNeighs.end(); itNeighKF!=itEndNeighKF; itNeighKF++)
  2105. {
  2106. KeyFrame* pNeighKF = *itNeighKF;
  2107. if(!pNeighKF->isBad())
  2108. {
  2109. if(pNeighKF->mnTrackReferenceForFrame!=mCurrentFrame.mnId)
  2110. {
  2111. mvpLocalKeyFrames.push_back(pNeighKF);
  2112. pNeighKF->mnTrackReferenceForFrame=mCurrentFrame.mnId;
  2113. break;
  2114. }
  2115. }
  2116. }
  2117. const set<KeyFrame*> spChilds = pKF->GetChilds();
  2118. for(set<KeyFrame*>::const_iterator sit=spChilds.begin(), send=spChilds.end(); sit!=send; sit++)
  2119. {
  2120. KeyFrame* pChildKF = *sit;
  2121. if(!pChildKF->isBad())
  2122. {
  2123. if(pChildKF->mnTrackReferenceForFrame!=mCurrentFrame.mnId)
  2124. {
  2125. mvpLocalKeyFrames.push_back(pChildKF);
  2126. pChildKF->mnTrackReferenceForFrame=mCurrentFrame.mnId;
  2127. break;
  2128. }
  2129. }
  2130. }
  2131. KeyFrame* pParent = pKF->GetParent();
  2132. if(pParent)
  2133. {
  2134. if(pParent->mnTrackReferenceForFrame!=mCurrentFrame.mnId)
  2135. {
  2136. mvpLocalKeyFrames.push_back(pParent);
  2137. pParent->mnTrackReferenceForFrame=mCurrentFrame.mnId;
  2138. break;
  2139. }
  2140. }
  2141. }
  2142. // Add 10 last temporal KFs (mainly for IMU)
  2143. if((mSensor == System::IMU_MONOCULAR || mSensor == System::IMU_STEREO) &&mvpLocalKeyFrames.size()<80)
  2144. {
  2145. //cout << "CurrentKF: " << mCurrentFrame.mnId << endl;
  2146. KeyFrame* tempKeyFrame = mCurrentFrame.mpLastKeyFrame;
  2147. const int Nd = 20;
  2148. for(int i=0; i<Nd; i++){
  2149. if (!tempKeyFrame)
  2150. break;
  2151. //cout << "tempKF: " << tempKeyFrame << endl;
  2152. if(tempKeyFrame->mnTrackReferenceForFrame!=mCurrentFrame.mnId)
  2153. {
  2154. mvpLocalKeyFrames.push_back(tempKeyFrame);
  2155. tempKeyFrame->mnTrackReferenceForFrame=mCurrentFrame.mnId;
  2156. tempKeyFrame=tempKeyFrame->mPrevKF;
  2157. }
  2158. }
  2159. }
  2160. if(pKFmax)
  2161. {
  2162. mpReferenceKF = pKFmax;
  2163. mCurrentFrame.mpReferenceKF = mpReferenceKF;
  2164. }
  2165. }
  2166. bool Tracking::Relocalization()
  2167. {
  2168. Verbose::PrintMess("Starting relocalization", Verbose::VERBOSITY_NORMAL);
  2169. // Compute Bag of Words Vector
  2170. mCurrentFrame.ComputeBoW();
  2171. // Relocalization is performed when tracking is lost
  2172. // Track Lost: Query KeyFrame Database for keyframe candidates for relocalisation
  2173. vector<KeyFrame*> vpCandidateKFs = mpKeyFrameDB->DetectRelocalizationCandidates(&mCurrentFrame, mpAtlas->GetCurrentMap());
  2174. if(vpCandidateKFs.empty()) {
  2175. Verbose::PrintMess("There are not candidates", Verbose::VERBOSITY_NORMAL);
  2176. return false;
  2177. }
  2178. const int nKFs = vpCandidateKFs.size();
  2179. // We perform first an ORB matching with each candidate
  2180. // If enough matches are found we setup a PnP solver
  2181. ORBmatcher matcher(0.75,true);
  2182. vector<MLPnPsolver*> vpMLPnPsolvers;
  2183. vpMLPnPsolvers.resize(nKFs);
  2184. vector<vector<MapPoint*> > vvpMapPointMatches;
  2185. vvpMapPointMatches.resize(nKFs);
  2186. vector<bool> vbDiscarded;
  2187. vbDiscarded.resize(nKFs);
  2188. int nCandidates=0;
  2189. for(int i=0; i<nKFs; i++)
  2190. {
  2191. KeyFrame* pKF = vpCandidateKFs[i];
  2192. if(pKF->isBad())
  2193. vbDiscarded[i] = true;
  2194. else
  2195. {
  2196. int nmatches = matcher.SearchByBoW(pKF,mCurrentFrame,vvpMapPointMatches[i]);
  2197. if(nmatches<15)
  2198. {
  2199. vbDiscarded[i] = true;
  2200. continue;
  2201. }
  2202. else
  2203. {
  2204. MLPnPsolver* pSolver = new MLPnPsolver(mCurrentFrame,vvpMapPointMatches[i]);
  2205. pSolver->SetRansacParameters(0.99,10,300,6,0.5,5.991); //This solver needs at least 6 points
  2206. vpMLPnPsolvers[i] = pSolver;
  2207. }
  2208. }
  2209. }
  2210. // Alternatively perform some iterations of P4P RANSAC
  2211. // Until we found a camera pose supported by enough inliers
  2212. bool bMatch = false;
  2213. ORBmatcher matcher2(0.9,true);
  2214. while(nCandidates>0 && !bMatch)
  2215. {
  2216. for(int i=0; i<nKFs; i++)
  2217. {
  2218. if(vbDiscarded[i])
  2219. continue;
  2220. // Perform 5 Ransac Iterations
  2221. vector<bool> vbInliers;
  2222. int nInliers;
  2223. bool bNoMore;
  2224. MLPnPsolver* pSolver = vpMLPnPsolvers[i];
  2225. cv::Mat Tcw = pSolver->iterate(5,bNoMore,vbInliers,nInliers);
  2226. // If Ransac reachs max. iterations discard keyframe
  2227. if(bNoMore)
  2228. {
  2229. vbDiscarded[i]=true;
  2230. nCandidates--;
  2231. }
  2232. // If a Camera Pose is computed, optimize
  2233. if(!Tcw.empty())
  2234. {
  2235. Tcw.copyTo(mCurrentFrame.mTcw);
  2236. set<MapPoint*> sFound;
  2237. const int np = vbInliers.size();
  2238. for(int j=0; j<np; j++)
  2239. {
  2240. if(vbInliers[j])
  2241. {
  2242. mCurrentFrame.mvpMapPoints[j]=vvpMapPointMatches[i][j];
  2243. sFound.insert(vvpMapPointMatches[i][j]);
  2244. }
  2245. else
  2246. mCurrentFrame.mvpMapPoints[j]=NULL;
  2247. }
  2248. int nGood = Optimizer::PoseOptimization(&mCurrentFrame);
  2249. if(nGood<10)
  2250. continue;
  2251. for(int io =0; io<mCurrentFrame.N; io++)
  2252. if(mCurrentFrame.mvbOutlier[io])
  2253. mCurrentFrame.mvpMapPoints[io]=static_cast<MapPoint*>(NULL);
  2254. // If few inliers, search by projection in a coarse window and optimize again
  2255. if(nGood<50)
  2256. {
  2257. int nadditional =matcher2.SearchByProjection(mCurrentFrame,vpCandidateKFs[i],sFound,10,100);
  2258. if(nadditional+nGood>=50)
  2259. {
  2260. nGood = Optimizer::PoseOptimization(&mCurrentFrame);
  2261. // If many inliers but still not enough, search by projection again in a narrower window
  2262. // the camera has been already optimized with many points
  2263. if(nGood>30 && nGood<50)
  2264. {
  2265. sFound.clear();
  2266. for(int ip =0; ip<mCurrentFrame.N; ip++)
  2267. if(mCurrentFrame.mvpMapPoints[ip])
  2268. sFound.insert(mCurrentFrame.mvpMapPoints[ip]);
  2269. nadditional =matcher2.SearchByProjection(mCurrentFrame,vpCandidateKFs[i],sFound,3,64);
  2270. // Final optimization
  2271. if(nGood+nadditional>=50)
  2272. {
  2273. nGood = Optimizer::PoseOptimization(&mCurrentFrame);
  2274. for(int io =0; io<mCurrentFrame.N; io++)
  2275. if(mCurrentFrame.mvbOutlier[io])
  2276. mCurrentFrame.mvpMapPoints[io]=NULL;
  2277. }
  2278. }
  2279. }
  2280. }
  2281. // If the pose is supported by enough inliers stop ransacs and continue
  2282. if(nGood>=50)
  2283. {
  2284. bMatch = true;
  2285. break;
  2286. }
  2287. }
  2288. }
  2289. }
  2290. if(!bMatch)
  2291. {
  2292. return false;
  2293. }
  2294. else
  2295. {
  2296. mnLastRelocFrameId = mCurrentFrame.mnId;
  2297. cout << "Relocalized!!" << endl;
  2298. return true;
  2299. }
  2300. }
  2301. void Tracking::Reset(bool bLocMap)
  2302. {
  2303. Verbose::PrintMess("System Reseting", Verbose::VERBOSITY_NORMAL);
  2304. if(mpViewer)
  2305. {
  2306. mpViewer->RequestStop();
  2307. while(!mpViewer->isStopped())
  2308. usleep(3000);
  2309. }
  2310. // Reset Local Mapping
  2311. if (!bLocMap)
  2312. {
  2313. Verbose::PrintMess("Reseting Local Mapper...", Verbose::VERBOSITY_NORMAL);
  2314. mpLocalMapper->RequestReset();
  2315. Verbose::PrintMess("done", Verbose::VERBOSITY_NORMAL);
  2316. }
  2317. // Reset Loop Closing
  2318. Verbose::PrintMess("Reseting Loop Closing...", Verbose::VERBOSITY_NORMAL);
  2319. mpLoopClosing->RequestReset();
  2320. Verbose::PrintMess("done", Verbose::VERBOSITY_NORMAL);
  2321. // Clear BoW Database
  2322. Verbose::PrintMess("Reseting Database...", Verbose::VERBOSITY_NORMAL);
  2323. mpKeyFrameDB->clear();
  2324. Verbose::PrintMess("done", Verbose::VERBOSITY_NORMAL);
  2325. // Clear Map (this erase MapPoints and KeyFrames)
  2326. mpAtlas->clearAtlas();
  2327. mpAtlas->CreateNewMap();
  2328. if (mSensor==System::IMU_STEREO || mSensor == System::IMU_MONOCULAR)
  2329. mpAtlas->SetInertialSensor();
  2330. mnInitialFrameId = 0;
  2331. KeyFrame::nNextId = 0;
  2332. Frame::nNextId = 0;
  2333. mState = NO_IMAGES_YET;
  2334. if(mpInitializer)
  2335. {
  2336. delete mpInitializer;
  2337. mpInitializer = static_cast<Initializer*>(NULL);
  2338. }
  2339. mbSetInit=false;
  2340. mlRelativeFramePoses.clear();
  2341. mlpReferences.clear();
  2342. mlFrameTimes.clear();
  2343. mlbLost.clear();
  2344. mCurrentFrame = Frame();
  2345. mnLastRelocFrameId = 0;
  2346. mLastFrame = Frame();
  2347. mpReferenceKF = static_cast<KeyFrame*>(NULL);
  2348. mpLastKeyFrame = static_cast<KeyFrame*>(NULL);
  2349. mvIniMatches.clear();
  2350. if(mpViewer)
  2351. mpViewer->Release();
  2352. Verbose::PrintMess(" End reseting! ", Verbose::VERBOSITY_NORMAL);
  2353. }
  2354. void Tracking::ResetActiveMap(bool bLocMap)
  2355. {
  2356. Verbose::PrintMess("Active map Reseting", Verbose::VERBOSITY_NORMAL);
  2357. if(mpViewer)
  2358. {
  2359. mpViewer->RequestStop();
  2360. while(!mpViewer->isStopped())
  2361. usleep(3000);
  2362. }
  2363. Map* pMap = mpAtlas->GetCurrentMap();
  2364. if (!bLocMap)
  2365. {
  2366. Verbose::PrintMess("Reseting Local Mapper...", Verbose::VERBOSITY_NORMAL);
  2367. mpLocalMapper->RequestResetActiveMap(pMap);
  2368. Verbose::PrintMess("done", Verbose::VERBOSITY_NORMAL);
  2369. }
  2370. // Reset Loop Closing
  2371. Verbose::PrintMess("Reseting Loop Closing...", Verbose::VERBOSITY_NORMAL);
  2372. mpLoopClosing->RequestResetActiveMap(pMap);
  2373. Verbose::PrintMess("done", Verbose::VERBOSITY_NORMAL);
  2374. // Clear BoW Database
  2375. Verbose::PrintMess("Reseting Database", Verbose::VERBOSITY_NORMAL);
  2376. mpKeyFrameDB->clearMap(pMap); // Only clear the active map references
  2377. Verbose::PrintMess("done", Verbose::VERBOSITY_NORMAL);
  2378. // Clear Map (this erase MapPoints and KeyFrames)
  2379. mpAtlas->clearMap();
  2380. //KeyFrame::nNextId = mpAtlas->GetLastInitKFid();
  2381. //Frame::nNextId = mnLastInitFrameId;
  2382. mnLastInitFrameId = Frame::nNextId;
  2383. mnLastRelocFrameId = mnLastInitFrameId;
  2384. mState = NO_IMAGES_YET; //NOT_INITIALIZED;
  2385. if(mpInitializer)
  2386. {
  2387. delete mpInitializer;
  2388. mpInitializer = static_cast<Initializer*>(NULL);
  2389. }
  2390. list<bool> lbLost;
  2391. // lbLost.reserve(mlbLost.size());
  2392. unsigned int index = mnFirstFrameId;
  2393. cout << "mnFirstFrameId = " << mnFirstFrameId << endl;
  2394. for(Map* pMap : mpAtlas->GetAllMaps())
  2395. {
  2396. if(pMap->GetAllKeyFrames().size() > 0)
  2397. {
  2398. if(index > pMap->GetLowerKFID())
  2399. index = pMap->GetLowerKFID();
  2400. }
  2401. }
  2402. //cout << "First Frame id: " << index << endl;
  2403. int num_lost = 0;
  2404. cout << "mnInitialFrameId = " << mnInitialFrameId << endl;
  2405. for(list<bool>::iterator ilbL = mlbLost.begin(); ilbL != mlbLost.end(); ilbL++)
  2406. {
  2407. if(index < mnInitialFrameId)
  2408. lbLost.push_back(*ilbL);
  2409. else
  2410. {
  2411. lbLost.push_back(true);
  2412. num_lost += 1;
  2413. }
  2414. index++;
  2415. }
  2416. cout << num_lost << " Frames had been set to lost" << endl;
  2417. mlbLost = lbLost;
  2418. mnInitialFrameId = mCurrentFrame.mnId;
  2419. mnLastRelocFrameId = mCurrentFrame.mnId;
  2420. mCurrentFrame = Frame();
  2421. mLastFrame = Frame();
  2422. mpReferenceKF = static_cast<KeyFrame*>(NULL);
  2423. mpLastKeyFrame = static_cast<KeyFrame*>(NULL);
  2424. mvIniMatches.clear();
  2425. if(mpViewer)
  2426. mpViewer->Release();
  2427. Verbose::PrintMess(" End reseting! ", Verbose::VERBOSITY_NORMAL);
  2428. }
  2429. vector<MapPoint*> Tracking::GetLocalMapMPS()
  2430. {
  2431. return mvpLocalMapPoints;
  2432. }
  2433. void Tracking::ChangeCalibration(const string &strSettingPath)
  2434. {
  2435. cv::FileStorage fSettings(strSettingPath, cv::FileStorage::READ);
  2436. float fx = fSettings["Camera.fx"];
  2437. float fy = fSettings["Camera.fy"];
  2438. float cx = fSettings["Camera.cx"];
  2439. float cy = fSettings["Camera.cy"];
  2440. cv::Mat K = cv::Mat::eye(3,3,CV_32F);
  2441. K.at<float>(0,0) = fx;
  2442. K.at<float>(1,1) = fy;
  2443. K.at<float>(0,2) = cx;
  2444. K.at<float>(1,2) = cy;
  2445. K.copyTo(mK);
  2446. cv::Mat DistCoef(4,1,CV_32F);
  2447. DistCoef.at<float>(0) = fSettings["Camera.k1"];
  2448. DistCoef.at<float>(1) = fSettings["Camera.k2"];
  2449. DistCoef.at<float>(2) = fSettings["Camera.p1"];
  2450. DistCoef.at<float>(3) = fSettings["Camera.p2"];
  2451. const float k3 = fSettings["Camera.k3"];
  2452. if(k3!=0)
  2453. {
  2454. DistCoef.resize(5);
  2455. DistCoef.at<float>(4) = k3;
  2456. }
  2457. DistCoef.copyTo(mDistCoef);
  2458. mbf = fSettings["Camera.bf"];
  2459. Frame::mbInitialComputations = true;
  2460. }
  2461. void Tracking::InformOnlyTracking(const bool &flag)
  2462. {
  2463. mbOnlyTracking = flag;
  2464. }
  2465. void Tracking::UpdateFrameIMU(const float s, const IMU::Bias &b, KeyFrame* pCurrentKeyFrame)
  2466. {
  2467. Map * pMap = pCurrentKeyFrame->GetMap();
  2468. unsigned int index = mnFirstFrameId;
  2469. list<ORB_SLAM3::KeyFrame*>::iterator lRit = mlpReferences.begin();
  2470. list<bool>::iterator lbL = mlbLost.begin();
  2471. for(list<cv::Mat>::iterator lit=mlRelativeFramePoses.begin(),lend=mlRelativeFramePoses.end();lit!=lend;lit++, lRit++, lbL++)
  2472. {
  2473. if(*lbL)
  2474. continue;
  2475. KeyFrame* pKF = *lRit;
  2476. while(pKF->isBad())
  2477. {
  2478. pKF = pKF->GetParent();
  2479. }
  2480. if(pKF->GetMap() == pMap)
  2481. {
  2482. (*lit).rowRange(0,3).col(3)=(*lit).rowRange(0,3).col(3)*s;
  2483. }
  2484. }
  2485. mLastBias = b;
  2486. mpLastKeyFrame = pCurrentKeyFrame;
  2487. mLastFrame.SetNewBias(mLastBias);
  2488. mCurrentFrame.SetNewBias(mLastBias);
  2489. cv::Mat Gz = (cv::Mat_<float>(3,1) << 0, 0, -IMU::GRAVITY_VALUE);
  2490. cv::Mat twb1;
  2491. cv::Mat Rwb1;
  2492. cv::Mat Vwb1;
  2493. float t12;
  2494. while(!mCurrentFrame.imuIsPreintegrated())
  2495. {
  2496. usleep(500);
  2497. }
  2498. if(mLastFrame.mnId == mLastFrame.mpLastKeyFrame->mnFrameId)
  2499. {
  2500. mLastFrame.SetImuPoseVelocity(mLastFrame.mpLastKeyFrame->GetImuRotation(),
  2501. mLastFrame.mpLastKeyFrame->GetImuPosition(),
  2502. mLastFrame.mpLastKeyFrame->GetVelocity());
  2503. }
  2504. else
  2505. {
  2506. twb1 = mLastFrame.mpLastKeyFrame->GetImuPosition();
  2507. Rwb1 = mLastFrame.mpLastKeyFrame->GetImuRotation();
  2508. Vwb1 = mLastFrame.mpLastKeyFrame->GetVelocity();
  2509. t12 = mLastFrame.mpImuPreintegrated->dT;
  2510. mLastFrame.SetImuPoseVelocity(Rwb1*mLastFrame.mpImuPreintegrated->GetUpdatedDeltaRotation(),
  2511. twb1 + Vwb1*t12 + 0.5f*t12*t12*Gz+ Rwb1*mLastFrame.mpImuPreintegrated->GetUpdatedDeltaPosition(),
  2512. Vwb1 + Gz*t12 + Rwb1*mLastFrame.mpImuPreintegrated->GetUpdatedDeltaVelocity());
  2513. }
  2514. if (mCurrentFrame.mpImuPreintegrated)
  2515. {
  2516. twb1 = mCurrentFrame.mpLastKeyFrame->GetImuPosition();
  2517. Rwb1 = mCurrentFrame.mpLastKeyFrame->GetImuRotation();
  2518. Vwb1 = mCurrentFrame.mpLastKeyFrame->GetVelocity();
  2519. t12 = mCurrentFrame.mpImuPreintegrated->dT;
  2520. mCurrentFrame.SetImuPoseVelocity(Rwb1*mCurrentFrame.mpImuPreintegrated->GetUpdatedDeltaRotation(),
  2521. twb1 + Vwb1*t12 + 0.5f*t12*t12*Gz+ Rwb1*mCurrentFrame.mpImuPreintegrated->GetUpdatedDeltaPosition(),
  2522. Vwb1 + Gz*t12 + Rwb1*mCurrentFrame.mpImuPreintegrated->GetUpdatedDeltaVelocity());
  2523. }
  2524. mnFirstImuFrameId = mCurrentFrame.mnId;
  2525. }
  2526. cv::Mat Tracking::ComputeF12(KeyFrame *&pKF1, KeyFrame *&pKF2)
  2527. {
  2528. cv::Mat R1w = pKF1->GetRotation();
  2529. cv::Mat t1w = pKF1->GetTranslation();
  2530. cv::Mat R2w = pKF2->GetRotation();
  2531. cv::Mat t2w = pKF2->GetTranslation();
  2532. cv::Mat R12 = R1w*R2w.t();
  2533. cv::Mat t12 = -R1w*R2w.t()*t2w+t1w;
  2534. cv::Mat t12x = Converter::tocvSkewMatrix(t12);
  2535. const cv::Mat &K1 = pKF1->mK;
  2536. const cv::Mat &K2 = pKF2->mK;
  2537. return K1.t().inv()*t12x*R12*K2.inv();
  2538. }
  2539. void Tracking::CreateNewMapPoints()
  2540. {
  2541. // Retrieve neighbor keyframes in covisibility graph
  2542. const vector<KeyFrame*> vpKFs = mpAtlas->GetAllKeyFrames();
  2543. ORBmatcher matcher(0.6,false);
  2544. cv::Mat Rcw1 = mpLastKeyFrame->GetRotation();
  2545. cv::Mat Rwc1 = Rcw1.t();
  2546. cv::Mat tcw1 = mpLastKeyFrame->GetTranslation();
  2547. cv::Mat Tcw1(3,4,CV_32F);
  2548. Rcw1.copyTo(Tcw1.colRange(0,3));
  2549. tcw1.copyTo(Tcw1.col(3));
  2550. cv::Mat Ow1 = mpLastKeyFrame->GetCameraCenter();
  2551. const float &fx1 = mpLastKeyFrame->fx;
  2552. const float &fy1 = mpLastKeyFrame->fy;
  2553. const float &cx1 = mpLastKeyFrame->cx;
  2554. const float &cy1 = mpLastKeyFrame->cy;
  2555. const float &invfx1 = mpLastKeyFrame->invfx;
  2556. const float &invfy1 = mpLastKeyFrame->invfy;
  2557. const float ratioFactor = 1.5f*mpLastKeyFrame->mfScaleFactor;
  2558. int nnew=0;
  2559. // Search matches with epipolar restriction and triangulate
  2560. for(size_t i=0; i<vpKFs.size(); i++)
  2561. {
  2562. KeyFrame* pKF2 = vpKFs[i];
  2563. if(pKF2==mpLastKeyFrame)
  2564. continue;
  2565. // Check first that baseline is not too short
  2566. cv::Mat Ow2 = pKF2->GetCameraCenter();
  2567. cv::Mat vBaseline = Ow2-Ow1;
  2568. const float baseline = cv::norm(vBaseline);
  2569. if((mSensor!=System::MONOCULAR)||(mSensor!=System::IMU_MONOCULAR))
  2570. {
  2571. if(baseline<pKF2->mb)
  2572. continue;
  2573. }
  2574. else
  2575. {
  2576. const float medianDepthKF2 = pKF2->ComputeSceneMedianDepth(2);
  2577. const float ratioBaselineDepth = baseline/medianDepthKF2;
  2578. if(ratioBaselineDepth<0.01)
  2579. continue;
  2580. }
  2581. // Compute Fundamental Matrix
  2582. cv::Mat F12 = ComputeF12(mpLastKeyFrame,pKF2);
  2583. // Search matches that fullfil epipolar constraint
  2584. vector<pair<size_t,size_t> > vMatchedIndices;
  2585. matcher.SearchForTriangulation(mpLastKeyFrame,pKF2,F12,vMatchedIndices,false);
  2586. cv::Mat Rcw2 = pKF2->GetRotation();
  2587. cv::Mat Rwc2 = Rcw2.t();
  2588. cv::Mat tcw2 = pKF2->GetTranslation();
  2589. cv::Mat Tcw2(3,4,CV_32F);
  2590. Rcw2.copyTo(Tcw2.colRange(0,3));
  2591. tcw2.copyTo(Tcw2.col(3));
  2592. const float &fx2 = pKF2->fx;
  2593. const float &fy2 = pKF2->fy;
  2594. const float &cx2 = pKF2->cx;
  2595. const float &cy2 = pKF2->cy;
  2596. const float &invfx2 = pKF2->invfx;
  2597. const float &invfy2 = pKF2->invfy;
  2598. // Triangulate each match
  2599. const int nmatches = vMatchedIndices.size();
  2600. for(int ikp=0; ikp<nmatches; ikp++)
  2601. {
  2602. const int &idx1 = vMatchedIndices[ikp].first;
  2603. const int &idx2 = vMatchedIndices[ikp].second;
  2604. const cv::KeyPoint &kp1 = mpLastKeyFrame->mvKeysUn[idx1];
  2605. const float kp1_ur=mpLastKeyFrame->mvuRight[idx1];
  2606. bool bStereo1 = kp1_ur>=0;
  2607. const cv::KeyPoint &kp2 = pKF2->mvKeysUn[idx2];
  2608. const float kp2_ur = pKF2->mvuRight[idx2];
  2609. bool bStereo2 = kp2_ur>=0;
  2610. // Check parallax between rays
  2611. cv::Mat xn1 = (cv::Mat_<float>(3,1) << (kp1.pt.x-cx1)*invfx1, (kp1.pt.y-cy1)*invfy1, 1.0);
  2612. cv::Mat xn2 = (cv::Mat_<float>(3,1) << (kp2.pt.x-cx2)*invfx2, (kp2.pt.y-cy2)*invfy2, 1.0);
  2613. cv::Mat ray1 = Rwc1*xn1;
  2614. cv::Mat ray2 = Rwc2*xn2;
  2615. const float cosParallaxRays = ray1.dot(ray2)/(cv::norm(ray1)*cv::norm(ray2));
  2616. float cosParallaxStereo = cosParallaxRays+1;
  2617. float cosParallaxStereo1 = cosParallaxStereo;
  2618. float cosParallaxStereo2 = cosParallaxStereo;
  2619. if(bStereo1)
  2620. cosParallaxStereo1 = cos(2*atan2(mpLastKeyFrame->mb/2,mpLastKeyFrame->mvDepth[idx1]));
  2621. else if(bStereo2)
  2622. cosParallaxStereo2 = cos(2*atan2(pKF2->mb/2,pKF2->mvDepth[idx2]));
  2623. cosParallaxStereo = min(cosParallaxStereo1,cosParallaxStereo2);
  2624. cv::Mat x3D;
  2625. if(cosParallaxRays<cosParallaxStereo && cosParallaxRays>0 && (bStereo1 || bStereo2 || cosParallaxRays<0.9998))
  2626. {
  2627. // Linear Triangulation Method
  2628. cv::Mat A(4,4,CV_32F);
  2629. A.row(0) = xn1.at<float>(0)*Tcw1.row(2)-Tcw1.row(0);
  2630. A.row(1) = xn1.at<float>(1)*Tcw1.row(2)-Tcw1.row(1);
  2631. A.row(2) = xn2.at<float>(0)*Tcw2.row(2)-Tcw2.row(0);
  2632. A.row(3) = xn2.at<float>(1)*Tcw2.row(2)-Tcw2.row(1);
  2633. cv::Mat w,u,vt;
  2634. cv::SVD::compute(A,w,u,vt,cv::SVD::MODIFY_A| cv::SVD::FULL_UV);
  2635. x3D = vt.row(3).t();
  2636. if(x3D.at<float>(3)==0)
  2637. continue;
  2638. // Euclidean coordinates
  2639. x3D = x3D.rowRange(0,3)/x3D.at<float>(3);
  2640. }
  2641. else if(bStereo1 && cosParallaxStereo1<cosParallaxStereo2)
  2642. {
  2643. x3D = mpLastKeyFrame->UnprojectStereo(idx1);
  2644. }
  2645. else if(bStereo2 && cosParallaxStereo2<cosParallaxStereo1)
  2646. {
  2647. x3D = pKF2->UnprojectStereo(idx2);
  2648. }
  2649. else
  2650. continue; //No stereo and very low parallax
  2651. cv::Mat x3Dt = x3D.t();
  2652. //Check triangulation in front of cameras
  2653. float z1 = Rcw1.row(2).dot(x3Dt)+tcw1.at<float>(2);
  2654. if(z1<=0)
  2655. continue;
  2656. float z2 = Rcw2.row(2).dot(x3Dt)+tcw2.at<float>(2);
  2657. if(z2<=0)
  2658. continue;
  2659. //Check reprojection error in first keyframe
  2660. const float &sigmaSquare1 = mpLastKeyFrame->mvLevelSigma2[kp1.octave];
  2661. const float x1 = Rcw1.row(0).dot(x3Dt)+tcw1.at<float>(0);
  2662. const float y1 = Rcw1.row(1).dot(x3Dt)+tcw1.at<float>(1);
  2663. const float invz1 = 1.0/z1;
  2664. if(!bStereo1)
  2665. {
  2666. float u1 = fx1*x1*invz1+cx1;
  2667. float v1 = fy1*y1*invz1+cy1;
  2668. float errX1 = u1 - kp1.pt.x;
  2669. float errY1 = v1 - kp1.pt.y;
  2670. if((errX1*errX1+errY1*errY1)>5.991*sigmaSquare1)
  2671. continue;
  2672. }
  2673. else
  2674. {
  2675. float u1 = fx1*x1*invz1+cx1;
  2676. float u1_r = u1 - mpLastKeyFrame->mbf*invz1;
  2677. float v1 = fy1*y1*invz1+cy1;
  2678. float errX1 = u1 - kp1.pt.x;
  2679. float errY1 = v1 - kp1.pt.y;
  2680. float errX1_r = u1_r - kp1_ur;
  2681. if((errX1*errX1+errY1*errY1+errX1_r*errX1_r)>7.8*sigmaSquare1)
  2682. continue;
  2683. }
  2684. //Check reprojection error in second keyframe
  2685. const float sigmaSquare2 = pKF2->mvLevelSigma2[kp2.octave];
  2686. const float x2 = Rcw2.row(0).dot(x3Dt)+tcw2.at<float>(0);
  2687. const float y2 = Rcw2.row(1).dot(x3Dt)+tcw2.at<float>(1);
  2688. const float invz2 = 1.0/z2;
  2689. if(!bStereo2)
  2690. {
  2691. float u2 = fx2*x2*invz2+cx2;
  2692. float v2 = fy2*y2*invz2+cy2;
  2693. float errX2 = u2 - kp2.pt.x;
  2694. float errY2 = v2 - kp2.pt.y;
  2695. if((errX2*errX2+errY2*errY2)>5.991*sigmaSquare2)
  2696. continue;
  2697. }
  2698. else
  2699. {
  2700. float u2 = fx2*x2*invz2+cx2;
  2701. float u2_r = u2 - mpLastKeyFrame->mbf*invz2;
  2702. float v2 = fy2*y2*invz2+cy2;
  2703. float errX2 = u2 - kp2.pt.x;
  2704. float errY2 = v2 - kp2.pt.y;
  2705. float errX2_r = u2_r - kp2_ur;
  2706. if((errX2*errX2+errY2*errY2+errX2_r*errX2_r)>7.8*sigmaSquare2)
  2707. continue;
  2708. }
  2709. //Check scale consistency
  2710. cv::Mat normal1 = x3D-Ow1;
  2711. float dist1 = cv::norm(normal1);
  2712. cv::Mat normal2 = x3D-Ow2;
  2713. float dist2 = cv::norm(normal2);
  2714. if(dist1==0 || dist2==0)
  2715. continue;
  2716. const float ratioDist = dist2/dist1;
  2717. const float ratioOctave = mpLastKeyFrame->mvScaleFactors[kp1.octave]/pKF2->mvScaleFactors[kp2.octave];
  2718. if(ratioDist*ratioFactor<ratioOctave || ratioDist>ratioOctave*ratioFactor)
  2719. continue;
  2720. // Triangulation is succesfull
  2721. MapPoint* pMP = new MapPoint(x3D,mpLastKeyFrame,mpAtlas->GetCurrentMap());
  2722. pMP->AddObservation(mpLastKeyFrame,idx1);
  2723. pMP->AddObservation(pKF2,idx2);
  2724. mpLastKeyFrame->AddMapPoint(pMP,idx1);
  2725. pKF2->AddMapPoint(pMP,idx2);
  2726. pMP->ComputeDistinctiveDescriptors();
  2727. pMP->UpdateNormalAndDepth();
  2728. mpAtlas->AddMapPoint(pMP);
  2729. nnew++;
  2730. }
  2731. }
  2732. TrackReferenceKeyFrame();
  2733. }
  2734. void Tracking::NewDataset()
  2735. {
  2736. mnNumDataset++;
  2737. }
  2738. int Tracking::GetNumberDataset()
  2739. {
  2740. return mnNumDataset;
  2741. }
  2742. int Tracking::GetMatchesInliers()
  2743. {
  2744. return mnMatchesInliers;
  2745. }
  2746. } //namespace ORB_SLAM