Tracking.cc 135 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126
  1. /**
  2. * This file is part of ORB-SLAM3
  3. *
  4. * Copyright (C) 2017-2021 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 "ORBmatcher.h"
  20. #include "FrameDrawer.h"
  21. #include "Converter.h"
  22. #include "G2oTypes.h"
  23. #include "Optimizer.h"
  24. #include "Pinhole.h"
  25. #include "KannalaBrandt8.h"
  26. #include "MLPnPsolver.h"
  27. #include "GeometricTools.h"
  28. #include <iostream>
  29. #include <mutex>
  30. #include <chrono>
  31. using namespace std;
  32. namespace ORB_SLAM3
  33. {
  34. Tracking::Tracking(System *pSys, ORBVocabulary* pVoc, FrameDrawer *pFrameDrawer, MapDrawer *pMapDrawer, Atlas *pAtlas, KeyFrameDatabase* pKFDB, const string &strSettingPath, const int sensor, Settings* settings, const string &_nameSeq):
  35. mState(NO_IMAGES_YET), mSensor(sensor), mTrackedFr(0), mbStep(false),
  36. mbOnlyTracking(false), mbMapUpdated(false), mbVO(false), mpORBVocabulary(pVoc), mpKeyFrameDB(pKFDB),
  37. mbReadyToInitializate(false), mpSystem(pSys), mpViewer(NULL), bStepByStep(false),
  38. mpFrameDrawer(pFrameDrawer), mpMapDrawer(pMapDrawer), mpAtlas(pAtlas), mnLastRelocFrameId(0), time_recently_lost(5.0),
  39. mnInitialFrameId(0), mbCreatedMap(false), mnFirstFrameId(0), mpCamera2(nullptr), mpLastKeyFrame(static_cast<KeyFrame*>(NULL))
  40. {
  41. // Load camera parameters from settings file
  42. if(settings){
  43. newParameterLoader(settings);
  44. }
  45. else{
  46. cv::FileStorage fSettings(strSettingPath, cv::FileStorage::READ);
  47. bool b_parse_cam = ParseCamParamFile(fSettings);
  48. if(!b_parse_cam)
  49. {
  50. std::cout << "*Error with the camera parameters in the config file*" << std::endl;
  51. }
  52. // Load ORB parameters
  53. bool b_parse_orb = ParseORBParamFile(fSettings);
  54. if(!b_parse_orb)
  55. {
  56. std::cout << "*Error with the ORB parameters in the config file*" << std::endl;
  57. }
  58. bool b_parse_imu = true;
  59. if(sensor==System::IMU_MONOCULAR || sensor==System::IMU_STEREO || sensor==System::IMU_RGBD)
  60. {
  61. b_parse_imu = ParseIMUParamFile(fSettings);
  62. if(!b_parse_imu)
  63. {
  64. std::cout << "*Error with the IMU parameters in the config file*" << std::endl;
  65. }
  66. mnFramesToResetIMU = mMaxFrames;
  67. }
  68. if(!b_parse_cam || !b_parse_orb || !b_parse_imu)
  69. {
  70. std::cerr << "**ERROR in the config file, the format is not correct**" << std::endl;
  71. try
  72. {
  73. throw -1;
  74. }
  75. catch(exception &e)
  76. {
  77. }
  78. }
  79. }
  80. initID = 0; lastID = 0;
  81. mbInitWith3KFs = false;
  82. mnNumDataset = 0;
  83. vector<GeometricCamera*> vpCams = mpAtlas->GetAllCameras();
  84. std::cout << "There are " << vpCams.size() << " cameras in the atlas" << std::endl;
  85. for(GeometricCamera* pCam : vpCams)
  86. {
  87. std::cout << "Camera " << pCam->GetId();
  88. if(pCam->GetType() == GeometricCamera::CAM_PINHOLE)
  89. {
  90. std::cout << " is pinhole" << std::endl;
  91. }
  92. else if(pCam->GetType() == GeometricCamera::CAM_FISHEYE)
  93. {
  94. std::cout << " is fisheye" << std::endl;
  95. }
  96. else
  97. {
  98. std::cout << " is unknown" << std::endl;
  99. }
  100. }
  101. #ifdef REGISTER_TIMES
  102. vdRectStereo_ms.clear();
  103. vdResizeImage_ms.clear();
  104. vdORBExtract_ms.clear();
  105. vdStereoMatch_ms.clear();
  106. vdIMUInteg_ms.clear();
  107. vdPosePred_ms.clear();
  108. vdLMTrack_ms.clear();
  109. vdNewKF_ms.clear();
  110. vdTrackTotal_ms.clear();
  111. #endif
  112. }
  113. #ifdef REGISTER_TIMES
  114. double calcAverage(vector<double> v_times)
  115. {
  116. double accum = 0;
  117. for(double value : v_times)
  118. {
  119. accum += value;
  120. }
  121. return accum / v_times.size();
  122. }
  123. double calcDeviation(vector<double> v_times, double average)
  124. {
  125. double accum = 0;
  126. for(double value : v_times)
  127. {
  128. accum += pow(value - average, 2);
  129. }
  130. return sqrt(accum / v_times.size());
  131. }
  132. double calcAverage(vector<int> v_values)
  133. {
  134. double accum = 0;
  135. int total = 0;
  136. for(double value : v_values)
  137. {
  138. if(value == 0)
  139. continue;
  140. accum += value;
  141. total++;
  142. }
  143. return accum / total;
  144. }
  145. double calcDeviation(vector<int> v_values, double average)
  146. {
  147. double accum = 0;
  148. int total = 0;
  149. for(double value : v_values)
  150. {
  151. if(value == 0)
  152. continue;
  153. accum += pow(value - average, 2);
  154. total++;
  155. }
  156. return sqrt(accum / total);
  157. }
  158. void Tracking::LocalMapStats2File()
  159. {
  160. ofstream f;
  161. f.open("LocalMapTimeStats.txt");
  162. f << fixed << setprecision(6);
  163. f << "#Stereo rect[ms], MP culling[ms], MP creation[ms], LBA[ms], KF culling[ms], Total[ms]" << endl;
  164. for(int i=0; i<mpLocalMapper->vdLMTotal_ms.size(); ++i)
  165. {
  166. f << mpLocalMapper->vdKFInsert_ms[i] << "," << mpLocalMapper->vdMPCulling_ms[i] << ","
  167. << mpLocalMapper->vdMPCreation_ms[i] << "," << mpLocalMapper->vdLBASync_ms[i] << ","
  168. << mpLocalMapper->vdKFCullingSync_ms[i] << "," << mpLocalMapper->vdLMTotal_ms[i] << endl;
  169. }
  170. f.close();
  171. f.open("LBA_Stats.txt");
  172. f << fixed << setprecision(6);
  173. f << "#LBA time[ms], KF opt[#], KF fixed[#], MP[#], Edges[#]" << endl;
  174. for(int i=0; i<mpLocalMapper->vdLBASync_ms.size(); ++i)
  175. {
  176. f << mpLocalMapper->vdLBASync_ms[i] << "," << mpLocalMapper->vnLBA_KFopt[i] << ","
  177. << mpLocalMapper->vnLBA_KFfixed[i] << "," << mpLocalMapper->vnLBA_MPs[i] << ","
  178. << mpLocalMapper->vnLBA_edges[i] << endl;
  179. }
  180. f.close();
  181. }
  182. void Tracking::TrackStats2File()
  183. {
  184. ofstream f;
  185. f.open("SessionInfo.txt");
  186. f << fixed;
  187. f << "Number of KFs: " << mpAtlas->GetAllKeyFrames().size() << endl;
  188. f << "Number of MPs: " << mpAtlas->GetAllMapPoints().size() << endl;
  189. f << "OpenCV version: " << CV_VERSION << endl;
  190. f.close();
  191. f.open("TrackingTimeStats.txt");
  192. f << fixed << setprecision(6);
  193. f << "#Image Rect[ms], Image Resize[ms], ORB ext[ms], Stereo match[ms], IMU preint[ms], Pose pred[ms], LM track[ms], KF dec[ms], Total[ms]" << endl;
  194. for(int i=0; i<vdTrackTotal_ms.size(); ++i)
  195. {
  196. double stereo_rect = 0.0;
  197. if(!vdRectStereo_ms.empty())
  198. {
  199. stereo_rect = vdRectStereo_ms[i];
  200. }
  201. double resize_image = 0.0;
  202. if(!vdResizeImage_ms.empty())
  203. {
  204. resize_image = vdResizeImage_ms[i];
  205. }
  206. double stereo_match = 0.0;
  207. if(!vdStereoMatch_ms.empty())
  208. {
  209. stereo_match = vdStereoMatch_ms[i];
  210. }
  211. double imu_preint = 0.0;
  212. if(!vdIMUInteg_ms.empty())
  213. {
  214. imu_preint = vdIMUInteg_ms[i];
  215. }
  216. f << stereo_rect << "," << resize_image << "," << vdORBExtract_ms[i] << "," << stereo_match << "," << imu_preint << ","
  217. << vdPosePred_ms[i] << "," << vdLMTrack_ms[i] << "," << vdNewKF_ms[i] << "," << vdTrackTotal_ms[i] << endl;
  218. }
  219. f.close();
  220. }
  221. void Tracking::PrintTimeStats()
  222. {
  223. // Save data in files
  224. TrackStats2File();
  225. LocalMapStats2File();
  226. ofstream f;
  227. f.open("ExecMean.txt");
  228. f << fixed;
  229. //Report the mean and std of each one
  230. std::cout << std::endl << " TIME STATS in ms (mean$\\pm$std)" << std::endl;
  231. f << " TIME STATS in ms (mean$\\pm$std)" << std::endl;
  232. cout << "OpenCV version: " << CV_VERSION << endl;
  233. f << "OpenCV version: " << CV_VERSION << endl;
  234. std::cout << "---------------------------" << std::endl;
  235. std::cout << "Tracking" << std::setprecision(5) << std::endl << std::endl;
  236. f << "---------------------------" << std::endl;
  237. f << "Tracking" << std::setprecision(5) << std::endl << std::endl;
  238. double average, deviation;
  239. if(!vdRectStereo_ms.empty())
  240. {
  241. average = calcAverage(vdRectStereo_ms);
  242. deviation = calcDeviation(vdRectStereo_ms, average);
  243. std::cout << "Stereo Rectification: " << average << "$\\pm$" << deviation << std::endl;
  244. f << "Stereo Rectification: " << average << "$\\pm$" << deviation << std::endl;
  245. }
  246. if(!vdResizeImage_ms.empty())
  247. {
  248. average = calcAverage(vdResizeImage_ms);
  249. deviation = calcDeviation(vdResizeImage_ms, average);
  250. std::cout << "Image Resize: " << average << "$\\pm$" << deviation << std::endl;
  251. f << "Image Resize: " << average << "$\\pm$" << deviation << std::endl;
  252. }
  253. average = calcAverage(vdORBExtract_ms);
  254. deviation = calcDeviation(vdORBExtract_ms, average);
  255. std::cout << "ORB Extraction: " << average << "$\\pm$" << deviation << std::endl;
  256. f << "ORB Extraction: " << average << "$\\pm$" << deviation << std::endl;
  257. if(!vdStereoMatch_ms.empty())
  258. {
  259. average = calcAverage(vdStereoMatch_ms);
  260. deviation = calcDeviation(vdStereoMatch_ms, average);
  261. std::cout << "Stereo Matching: " << average << "$\\pm$" << deviation << std::endl;
  262. f << "Stereo Matching: " << average << "$\\pm$" << deviation << std::endl;
  263. }
  264. if(!vdIMUInteg_ms.empty())
  265. {
  266. average = calcAverage(vdIMUInteg_ms);
  267. deviation = calcDeviation(vdIMUInteg_ms, average);
  268. std::cout << "IMU Preintegration: " << average << "$\\pm$" << deviation << std::endl;
  269. f << "IMU Preintegration: " << average << "$\\pm$" << deviation << std::endl;
  270. }
  271. average = calcAverage(vdPosePred_ms);
  272. deviation = calcDeviation(vdPosePred_ms, average);
  273. std::cout << "Pose Prediction: " << average << "$\\pm$" << deviation << std::endl;
  274. f << "Pose Prediction: " << average << "$\\pm$" << deviation << std::endl;
  275. average = calcAverage(vdLMTrack_ms);
  276. deviation = calcDeviation(vdLMTrack_ms, average);
  277. std::cout << "LM Track: " << average << "$\\pm$" << deviation << std::endl;
  278. f << "LM Track: " << average << "$\\pm$" << deviation << std::endl;
  279. average = calcAverage(vdNewKF_ms);
  280. deviation = calcDeviation(vdNewKF_ms, average);
  281. std::cout << "New KF decision: " << average << "$\\pm$" << deviation << std::endl;
  282. f << "New KF decision: " << average << "$\\pm$" << deviation << std::endl;
  283. average = calcAverage(vdTrackTotal_ms);
  284. deviation = calcDeviation(vdTrackTotal_ms, average);
  285. std::cout << "Total Tracking: " << average << "$\\pm$" << deviation << std::endl;
  286. f << "Total Tracking: " << average << "$\\pm$" << deviation << std::endl;
  287. // Local Mapping time stats
  288. std::cout << std::endl << std::endl << std::endl;
  289. std::cout << "Local Mapping" << std::endl << std::endl;
  290. f << std::endl << "Local Mapping" << std::endl << std::endl;
  291. average = calcAverage(mpLocalMapper->vdKFInsert_ms);
  292. deviation = calcDeviation(mpLocalMapper->vdKFInsert_ms, average);
  293. std::cout << "KF Insertion: " << average << "$\\pm$" << deviation << std::endl;
  294. f << "KF Insertion: " << average << "$\\pm$" << deviation << std::endl;
  295. average = calcAverage(mpLocalMapper->vdMPCulling_ms);
  296. deviation = calcDeviation(mpLocalMapper->vdMPCulling_ms, average);
  297. std::cout << "MP Culling: " << average << "$\\pm$" << deviation << std::endl;
  298. f << "MP Culling: " << average << "$\\pm$" << deviation << std::endl;
  299. average = calcAverage(mpLocalMapper->vdMPCreation_ms);
  300. deviation = calcDeviation(mpLocalMapper->vdMPCreation_ms, average);
  301. std::cout << "MP Creation: " << average << "$\\pm$" << deviation << std::endl;
  302. f << "MP Creation: " << average << "$\\pm$" << deviation << std::endl;
  303. average = calcAverage(mpLocalMapper->vdLBA_ms);
  304. deviation = calcDeviation(mpLocalMapper->vdLBA_ms, average);
  305. std::cout << "LBA: " << average << "$\\pm$" << deviation << std::endl;
  306. f << "LBA: " << average << "$\\pm$" << deviation << std::endl;
  307. average = calcAverage(mpLocalMapper->vdKFCulling_ms);
  308. deviation = calcDeviation(mpLocalMapper->vdKFCulling_ms, average);
  309. std::cout << "KF Culling: " << average << "$\\pm$" << deviation << std::endl;
  310. f << "KF Culling: " << average << "$\\pm$" << deviation << std::endl;
  311. average = calcAverage(mpLocalMapper->vdLMTotal_ms);
  312. deviation = calcDeviation(mpLocalMapper->vdLMTotal_ms, average);
  313. std::cout << "Total Local Mapping: " << average << "$\\pm$" << deviation << std::endl;
  314. f << "Total Local Mapping: " << average << "$\\pm$" << deviation << std::endl;
  315. // Local Mapping LBA complexity
  316. std::cout << "---------------------------" << std::endl;
  317. std::cout << std::endl << "LBA complexity (mean$\\pm$std)" << std::endl;
  318. f << "---------------------------" << std::endl;
  319. f << std::endl << "LBA complexity (mean$\\pm$std)" << std::endl;
  320. average = calcAverage(mpLocalMapper->vnLBA_edges);
  321. deviation = calcDeviation(mpLocalMapper->vnLBA_edges, average);
  322. std::cout << "LBA Edges: " << average << "$\\pm$" << deviation << std::endl;
  323. f << "LBA Edges: " << average << "$\\pm$" << deviation << std::endl;
  324. average = calcAverage(mpLocalMapper->vnLBA_KFopt);
  325. deviation = calcDeviation(mpLocalMapper->vnLBA_KFopt, average);
  326. std::cout << "LBA KF optimized: " << average << "$\\pm$" << deviation << std::endl;
  327. f << "LBA KF optimized: " << average << "$\\pm$" << deviation << std::endl;
  328. average = calcAverage(mpLocalMapper->vnLBA_KFfixed);
  329. deviation = calcDeviation(mpLocalMapper->vnLBA_KFfixed, average);
  330. std::cout << "LBA KF fixed: " << average << "$\\pm$" << deviation << std::endl;
  331. f << "LBA KF fixed: " << average << "$\\pm$" << deviation << std::endl;
  332. average = calcAverage(mpLocalMapper->vnLBA_MPs);
  333. deviation = calcDeviation(mpLocalMapper->vnLBA_MPs, average);
  334. std::cout << "LBA MP: " << average << "$\\pm$" << deviation << std::endl << std::endl;
  335. f << "LBA MP: " << average << "$\\pm$" << deviation << std::endl << std::endl;
  336. std::cout << "LBA executions: " << mpLocalMapper->nLBA_exec << std::endl;
  337. std::cout << "LBA aborts: " << mpLocalMapper->nLBA_abort << std::endl;
  338. f << "LBA executions: " << mpLocalMapper->nLBA_exec << std::endl;
  339. f << "LBA aborts: " << mpLocalMapper->nLBA_abort << std::endl;
  340. // Map complexity
  341. std::cout << "---------------------------" << std::endl;
  342. std::cout << std::endl << "Map complexity" << std::endl;
  343. std::cout << "KFs in map: " << mpAtlas->GetAllKeyFrames().size() << std::endl;
  344. std::cout << "MPs in map: " << mpAtlas->GetAllMapPoints().size() << std::endl;
  345. f << "---------------------------" << std::endl;
  346. f << std::endl << "Map complexity" << std::endl;
  347. vector<Map*> vpMaps = mpAtlas->GetAllMaps();
  348. Map* pBestMap = vpMaps[0];
  349. for(int i=1; i<vpMaps.size(); ++i)
  350. {
  351. if(pBestMap->GetAllKeyFrames().size() < vpMaps[i]->GetAllKeyFrames().size())
  352. {
  353. pBestMap = vpMaps[i];
  354. }
  355. }
  356. f << "KFs in map: " << pBestMap->GetAllKeyFrames().size() << std::endl;
  357. f << "MPs in map: " << pBestMap->GetAllMapPoints().size() << std::endl;
  358. f << "---------------------------" << std::endl;
  359. f << std::endl << "Place Recognition (mean$\\pm$std)" << std::endl;
  360. std::cout << "---------------------------" << std::endl;
  361. std::cout << std::endl << "Place Recognition (mean$\\pm$std)" << std::endl;
  362. average = calcAverage(mpLoopClosing->vdDataQuery_ms);
  363. deviation = calcDeviation(mpLoopClosing->vdDataQuery_ms, average);
  364. f << "Database Query: " << average << "$\\pm$" << deviation << std::endl;
  365. std::cout << "Database Query: " << average << "$\\pm$" << deviation << std::endl;
  366. average = calcAverage(mpLoopClosing->vdEstSim3_ms);
  367. deviation = calcDeviation(mpLoopClosing->vdEstSim3_ms, average);
  368. f << "SE3 estimation: " << average << "$\\pm$" << deviation << std::endl;
  369. std::cout << "SE3 estimation: " << average << "$\\pm$" << deviation << std::endl;
  370. average = calcAverage(mpLoopClosing->vdPRTotal_ms);
  371. deviation = calcDeviation(mpLoopClosing->vdPRTotal_ms, average);
  372. f << "Total Place Recognition: " << average << "$\\pm$" << deviation << std::endl << std::endl;
  373. std::cout << "Total Place Recognition: " << average << "$\\pm$" << deviation << std::endl << std::endl;
  374. f << std::endl << "Loop Closing (mean$\\pm$std)" << std::endl;
  375. std::cout << std::endl << "Loop Closing (mean$\\pm$std)" << std::endl;
  376. average = calcAverage(mpLoopClosing->vdLoopFusion_ms);
  377. deviation = calcDeviation(mpLoopClosing->vdLoopFusion_ms, average);
  378. f << "Loop Fusion: " << average << "$\\pm$" << deviation << std::endl;
  379. std::cout << "Loop Fusion: " << average << "$\\pm$" << deviation << std::endl;
  380. average = calcAverage(mpLoopClosing->vdLoopOptEss_ms);
  381. deviation = calcDeviation(mpLoopClosing->vdLoopOptEss_ms, average);
  382. f << "Essential Graph: " << average << "$\\pm$" << deviation << std::endl;
  383. std::cout << "Essential Graph: " << average << "$\\pm$" << deviation << std::endl;
  384. average = calcAverage(mpLoopClosing->vdLoopTotal_ms);
  385. deviation = calcDeviation(mpLoopClosing->vdLoopTotal_ms, average);
  386. f << "Total Loop Closing: " << average << "$\\pm$" << deviation << std::endl << std::endl;
  387. std::cout << "Total Loop Closing: " << average << "$\\pm$" << deviation << std::endl << std::endl;
  388. f << "Numb exec: " << mpLoopClosing->nLoop << std::endl;
  389. std::cout << "Num exec: " << mpLoopClosing->nLoop << std::endl;
  390. average = calcAverage(mpLoopClosing->vnLoopKFs);
  391. deviation = calcDeviation(mpLoopClosing->vnLoopKFs, average);
  392. f << "Number of KFs: " << average << "$\\pm$" << deviation << std::endl;
  393. std::cout << "Number of KFs: " << average << "$\\pm$" << deviation << std::endl;
  394. f << std::endl << "Map Merging (mean$\\pm$std)" << std::endl;
  395. std::cout << std::endl << "Map Merging (mean$\\pm$std)" << std::endl;
  396. average = calcAverage(mpLoopClosing->vdMergeMaps_ms);
  397. deviation = calcDeviation(mpLoopClosing->vdMergeMaps_ms, average);
  398. f << "Merge Maps: " << average << "$\\pm$" << deviation << std::endl;
  399. std::cout << "Merge Maps: " << average << "$\\pm$" << deviation << std::endl;
  400. average = calcAverage(mpLoopClosing->vdWeldingBA_ms);
  401. deviation = calcDeviation(mpLoopClosing->vdWeldingBA_ms, average);
  402. f << "Welding BA: " << average << "$\\pm$" << deviation << std::endl;
  403. std::cout << "Welding BA: " << average << "$\\pm$" << deviation << std::endl;
  404. average = calcAverage(mpLoopClosing->vdMergeOptEss_ms);
  405. deviation = calcDeviation(mpLoopClosing->vdMergeOptEss_ms, average);
  406. f << "Optimization Ess.: " << average << "$\\pm$" << deviation << std::endl;
  407. std::cout << "Optimization Ess.: " << average << "$\\pm$" << deviation << std::endl;
  408. average = calcAverage(mpLoopClosing->vdMergeTotal_ms);
  409. deviation = calcDeviation(mpLoopClosing->vdMergeTotal_ms, average);
  410. f << "Total Map Merging: " << average << "$\\pm$" << deviation << std::endl << std::endl;
  411. std::cout << "Total Map Merging: " << average << "$\\pm$" << deviation << std::endl << std::endl;
  412. f << "Numb exec: " << mpLoopClosing->nMerges << std::endl;
  413. std::cout << "Num exec: " << mpLoopClosing->nMerges << std::endl;
  414. average = calcAverage(mpLoopClosing->vnMergeKFs);
  415. deviation = calcDeviation(mpLoopClosing->vnMergeKFs, average);
  416. f << "Number of KFs: " << average << "$\\pm$" << deviation << std::endl;
  417. std::cout << "Number of KFs: " << average << "$\\pm$" << deviation << std::endl;
  418. average = calcAverage(mpLoopClosing->vnMergeMPs);
  419. deviation = calcDeviation(mpLoopClosing->vnMergeMPs, average);
  420. f << "Number of MPs: " << average << "$\\pm$" << deviation << std::endl;
  421. std::cout << "Number of MPs: " << average << "$\\pm$" << deviation << std::endl;
  422. f << std::endl << "Full GBA (mean$\\pm$std)" << std::endl;
  423. std::cout << std::endl << "Full GBA (mean$\\pm$std)" << std::endl;
  424. average = calcAverage(mpLoopClosing->vdGBA_ms);
  425. deviation = calcDeviation(mpLoopClosing->vdGBA_ms, average);
  426. f << "GBA: " << average << "$\\pm$" << deviation << std::endl;
  427. std::cout << "GBA: " << average << "$\\pm$" << deviation << std::endl;
  428. average = calcAverage(mpLoopClosing->vdUpdateMap_ms);
  429. deviation = calcDeviation(mpLoopClosing->vdUpdateMap_ms, average);
  430. f << "Map Update: " << average << "$\\pm$" << deviation << std::endl;
  431. std::cout << "Map Update: " << average << "$\\pm$" << deviation << std::endl;
  432. average = calcAverage(mpLoopClosing->vdFGBATotal_ms);
  433. deviation = calcDeviation(mpLoopClosing->vdFGBATotal_ms, average);
  434. f << "Total Full GBA: " << average << "$\\pm$" << deviation << std::endl << std::endl;
  435. std::cout << "Total Full GBA: " << average << "$\\pm$" << deviation << std::endl << std::endl;
  436. f << "Numb exec: " << mpLoopClosing->nFGBA_exec << std::endl;
  437. std::cout << "Num exec: " << mpLoopClosing->nFGBA_exec << std::endl;
  438. f << "Numb abort: " << mpLoopClosing->nFGBA_abort << std::endl;
  439. std::cout << "Num abort: " << mpLoopClosing->nFGBA_abort << std::endl;
  440. average = calcAverage(mpLoopClosing->vnGBAKFs);
  441. deviation = calcDeviation(mpLoopClosing->vnGBAKFs, average);
  442. f << "Number of KFs: " << average << "$\\pm$" << deviation << std::endl;
  443. std::cout << "Number of KFs: " << average << "$\\pm$" << deviation << std::endl;
  444. average = calcAverage(mpLoopClosing->vnGBAMPs);
  445. deviation = calcDeviation(mpLoopClosing->vnGBAMPs, average);
  446. f << "Number of MPs: " << average << "$\\pm$" << deviation << std::endl;
  447. std::cout << "Number of MPs: " << average << "$\\pm$" << deviation << std::endl;
  448. f.close();
  449. }
  450. #endif
  451. Tracking::~Tracking()
  452. {
  453. //f_track_stats.close();
  454. }
  455. void Tracking::newParameterLoader(Settings *settings) {
  456. mpCamera = settings->camera1();
  457. mpCamera = mpAtlas->AddCamera(mpCamera);
  458. if(settings->needToUndistort()){
  459. mDistCoef = settings->camera1DistortionCoef();
  460. }
  461. else{
  462. mDistCoef = cv::Mat::zeros(4,1,CV_32F);
  463. }
  464. //TODO: missing image scaling and rectification
  465. mImageScale = 1.0f;
  466. mK = cv::Mat::eye(3,3,CV_32F);
  467. mK.at<float>(0,0) = mpCamera->getParameter(0);
  468. mK.at<float>(1,1) = mpCamera->getParameter(1);
  469. mK.at<float>(0,2) = mpCamera->getParameter(2);
  470. mK.at<float>(1,2) = mpCamera->getParameter(3);
  471. mK_.setIdentity();
  472. mK_(0,0) = mpCamera->getParameter(0);
  473. mK_(1,1) = mpCamera->getParameter(1);
  474. mK_(0,2) = mpCamera->getParameter(2);
  475. mK_(1,2) = mpCamera->getParameter(3);
  476. if((mSensor==System::STEREO || mSensor==System::IMU_STEREO || mSensor==System::IMU_RGBD) &&
  477. settings->cameraType() == Settings::KannalaBrandt){
  478. mpCamera2 = settings->camera2();
  479. mpCamera2 = mpAtlas->AddCamera(mpCamera2);
  480. mTlr = settings->Tlr();
  481. mpFrameDrawer->both = true;
  482. }
  483. if(mSensor==System::STEREO || mSensor==System::RGBD || mSensor==System::IMU_STEREO || mSensor==System::IMU_RGBD ){
  484. mbf = settings->bf();
  485. mThDepth = settings->b() * settings->thDepth();
  486. }
  487. if(mSensor==System::RGBD || mSensor==System::IMU_RGBD){
  488. mDepthMapFactor = settings->depthMapFactor();
  489. if(fabs(mDepthMapFactor)<1e-5)
  490. mDepthMapFactor=1;
  491. else
  492. mDepthMapFactor = 1.0f/mDepthMapFactor;
  493. }
  494. mMinFrames = 0;
  495. mMaxFrames = settings->fps();
  496. mbRGB = settings->rgb();
  497. //ORB parameters
  498. int nFeatures = settings->nFeatures();
  499. int nLevels = settings->nLevels();
  500. int fIniThFAST = settings->initThFAST();
  501. int fMinThFAST = settings->minThFAST();
  502. float fScaleFactor = settings->scaleFactor();
  503. mpORBextractorLeft = new ORBextractor(nFeatures,fScaleFactor,nLevels,fIniThFAST,fMinThFAST);
  504. if(mSensor==System::STEREO || mSensor==System::IMU_STEREO)
  505. mpORBextractorRight = new ORBextractor(nFeatures,fScaleFactor,nLevels,fIniThFAST,fMinThFAST);
  506. if(mSensor==System::MONOCULAR || mSensor==System::IMU_MONOCULAR)
  507. mpIniORBextractor = new ORBextractor(5*nFeatures,fScaleFactor,nLevels,fIniThFAST,fMinThFAST);
  508. //IMU parameters
  509. Sophus::SE3f Tbc = settings->Tbc();
  510. mInsertKFsLost = settings->insertKFsWhenLost();
  511. mImuFreq = settings->imuFrequency();
  512. mImuPer = 0.001; //1.0 / (double) mImuFreq; //TODO: ESTO ESTA BIEN?
  513. float Ng = settings->noiseGyro();
  514. float Na = settings->noiseAcc();
  515. float Ngw = settings->gyroWalk();
  516. float Naw = settings->accWalk();
  517. const float sf = sqrt(mImuFreq);
  518. mpImuCalib = new IMU::Calib(Tbc,Ng*sf,Na*sf,Ngw/sf,Naw/sf);
  519. mpImuPreintegratedFromLastKF = new IMU::Preintegrated(IMU::Bias(),*mpImuCalib);
  520. }
  521. bool Tracking::ParseCamParamFile(cv::FileStorage &fSettings)
  522. {
  523. mDistCoef = cv::Mat::zeros(4,1,CV_32F);
  524. cout << endl << "Camera Parameters: " << endl;
  525. bool b_miss_params = false;
  526. string sCameraName = fSettings["Camera.type"];
  527. if(sCameraName == "PinHole")
  528. {
  529. float fx, fy, cx, cy;
  530. mImageScale = 1.f;
  531. // Camera calibration parameters
  532. cv::FileNode node = fSettings["Camera.fx"];
  533. if(!node.empty() && node.isReal())
  534. {
  535. fx = node.real();
  536. }
  537. else
  538. {
  539. std::cerr << "*Camera.fx parameter doesn't exist or is not a real number*" << std::endl;
  540. b_miss_params = true;
  541. }
  542. node = fSettings["Camera.fy"];
  543. if(!node.empty() && node.isReal())
  544. {
  545. fy = node.real();
  546. }
  547. else
  548. {
  549. std::cerr << "*Camera.fy parameter doesn't exist or is not a real number*" << std::endl;
  550. b_miss_params = true;
  551. }
  552. node = fSettings["Camera.cx"];
  553. if(!node.empty() && node.isReal())
  554. {
  555. cx = node.real();
  556. }
  557. else
  558. {
  559. std::cerr << "*Camera.cx parameter doesn't exist or is not a real number*" << std::endl;
  560. b_miss_params = true;
  561. }
  562. node = fSettings["Camera.cy"];
  563. if(!node.empty() && node.isReal())
  564. {
  565. cy = node.real();
  566. }
  567. else
  568. {
  569. std::cerr << "*Camera.cy parameter doesn't exist or is not a real number*" << std::endl;
  570. b_miss_params = true;
  571. }
  572. // Distortion parameters
  573. node = fSettings["Camera.k1"];
  574. if(!node.empty() && node.isReal())
  575. {
  576. mDistCoef.at<float>(0) = node.real();
  577. }
  578. else
  579. {
  580. std::cerr << "*Camera.k1 parameter doesn't exist or is not a real number*" << std::endl;
  581. b_miss_params = true;
  582. }
  583. node = fSettings["Camera.k2"];
  584. if(!node.empty() && node.isReal())
  585. {
  586. mDistCoef.at<float>(1) = node.real();
  587. }
  588. else
  589. {
  590. std::cerr << "*Camera.k2 parameter doesn't exist or is not a real number*" << std::endl;
  591. b_miss_params = true;
  592. }
  593. node = fSettings["Camera.p1"];
  594. if(!node.empty() && node.isReal())
  595. {
  596. mDistCoef.at<float>(2) = node.real();
  597. }
  598. else
  599. {
  600. std::cerr << "*Camera.p1 parameter doesn't exist or is not a real number*" << std::endl;
  601. b_miss_params = true;
  602. }
  603. node = fSettings["Camera.p2"];
  604. if(!node.empty() && node.isReal())
  605. {
  606. mDistCoef.at<float>(3) = node.real();
  607. }
  608. else
  609. {
  610. std::cerr << "*Camera.p2 parameter doesn't exist or is not a real number*" << std::endl;
  611. b_miss_params = true;
  612. }
  613. node = fSettings["Camera.k3"];
  614. if(!node.empty() && node.isReal())
  615. {
  616. mDistCoef.resize(5);
  617. mDistCoef.at<float>(4) = node.real();
  618. }
  619. node = fSettings["Camera.imageScale"];
  620. if(!node.empty() && node.isReal())
  621. {
  622. mImageScale = node.real();
  623. }
  624. if(b_miss_params)
  625. {
  626. return false;
  627. }
  628. if(mImageScale != 1.f)
  629. {
  630. // K matrix parameters must be scaled.
  631. fx = fx * mImageScale;
  632. fy = fy * mImageScale;
  633. cx = cx * mImageScale;
  634. cy = cy * mImageScale;
  635. }
  636. vector<float> vCamCalib{fx,fy,cx,cy};
  637. mpCamera = new Pinhole(vCamCalib);
  638. mpCamera = mpAtlas->AddCamera(mpCamera);
  639. std::cout << "- Camera: Pinhole" << std::endl;
  640. std::cout << "- Image scale: " << mImageScale << std::endl;
  641. std::cout << "- fx: " << fx << std::endl;
  642. std::cout << "- fy: " << fy << std::endl;
  643. std::cout << "- cx: " << cx << std::endl;
  644. std::cout << "- cy: " << cy << std::endl;
  645. std::cout << "- k1: " << mDistCoef.at<float>(0) << std::endl;
  646. std::cout << "- k2: " << mDistCoef.at<float>(1) << std::endl;
  647. std::cout << "- p1: " << mDistCoef.at<float>(2) << std::endl;
  648. std::cout << "- p2: " << mDistCoef.at<float>(3) << std::endl;
  649. if(mDistCoef.rows==5)
  650. std::cout << "- k3: " << mDistCoef.at<float>(4) << std::endl;
  651. mK = cv::Mat::eye(3,3,CV_32F);
  652. mK.at<float>(0,0) = fx;
  653. mK.at<float>(1,1) = fy;
  654. mK.at<float>(0,2) = cx;
  655. mK.at<float>(1,2) = cy;
  656. mK_.setIdentity();
  657. mK_(0,0) = fx;
  658. mK_(1,1) = fy;
  659. mK_(0,2) = cx;
  660. mK_(1,2) = cy;
  661. }
  662. else if(sCameraName == "KannalaBrandt8")
  663. {
  664. float fx, fy, cx, cy;
  665. float k1, k2, k3, k4;
  666. mImageScale = 1.f;
  667. // Camera calibration parameters
  668. cv::FileNode node = fSettings["Camera.fx"];
  669. if(!node.empty() && node.isReal())
  670. {
  671. fx = node.real();
  672. }
  673. else
  674. {
  675. std::cerr << "*Camera.fx parameter doesn't exist or is not a real number*" << std::endl;
  676. b_miss_params = true;
  677. }
  678. node = fSettings["Camera.fy"];
  679. if(!node.empty() && node.isReal())
  680. {
  681. fy = node.real();
  682. }
  683. else
  684. {
  685. std::cerr << "*Camera.fy parameter doesn't exist or is not a real number*" << std::endl;
  686. b_miss_params = true;
  687. }
  688. node = fSettings["Camera.cx"];
  689. if(!node.empty() && node.isReal())
  690. {
  691. cx = node.real();
  692. }
  693. else
  694. {
  695. std::cerr << "*Camera.cx parameter doesn't exist or is not a real number*" << std::endl;
  696. b_miss_params = true;
  697. }
  698. node = fSettings["Camera.cy"];
  699. if(!node.empty() && node.isReal())
  700. {
  701. cy = node.real();
  702. }
  703. else
  704. {
  705. std::cerr << "*Camera.cy parameter doesn't exist or is not a real number*" << std::endl;
  706. b_miss_params = true;
  707. }
  708. // Distortion parameters
  709. node = fSettings["Camera.k1"];
  710. if(!node.empty() && node.isReal())
  711. {
  712. k1 = node.real();
  713. }
  714. else
  715. {
  716. std::cerr << "*Camera.k1 parameter doesn't exist or is not a real number*" << std::endl;
  717. b_miss_params = true;
  718. }
  719. node = fSettings["Camera.k2"];
  720. if(!node.empty() && node.isReal())
  721. {
  722. k2 = node.real();
  723. }
  724. else
  725. {
  726. std::cerr << "*Camera.k2 parameter doesn't exist or is not a real number*" << std::endl;
  727. b_miss_params = true;
  728. }
  729. node = fSettings["Camera.k3"];
  730. if(!node.empty() && node.isReal())
  731. {
  732. k3 = node.real();
  733. }
  734. else
  735. {
  736. std::cerr << "*Camera.k3 parameter doesn't exist or is not a real number*" << std::endl;
  737. b_miss_params = true;
  738. }
  739. node = fSettings["Camera.k4"];
  740. if(!node.empty() && node.isReal())
  741. {
  742. k4 = node.real();
  743. }
  744. else
  745. {
  746. std::cerr << "*Camera.k4 parameter doesn't exist or is not a real number*" << std::endl;
  747. b_miss_params = true;
  748. }
  749. node = fSettings["Camera.imageScale"];
  750. if(!node.empty() && node.isReal())
  751. {
  752. mImageScale = node.real();
  753. }
  754. if(!b_miss_params)
  755. {
  756. if(mImageScale != 1.f)
  757. {
  758. // K matrix parameters must be scaled.
  759. fx = fx * mImageScale;
  760. fy = fy * mImageScale;
  761. cx = cx * mImageScale;
  762. cy = cy * mImageScale;
  763. }
  764. vector<float> vCamCalib{fx,fy,cx,cy,k1,k2,k3,k4};
  765. mpCamera = new KannalaBrandt8(vCamCalib);
  766. mpCamera = mpAtlas->AddCamera(mpCamera);
  767. std::cout << "- Camera: Fisheye" << std::endl;
  768. std::cout << "- Image scale: " << mImageScale << std::endl;
  769. std::cout << "- fx: " << fx << std::endl;
  770. std::cout << "- fy: " << fy << std::endl;
  771. std::cout << "- cx: " << cx << std::endl;
  772. std::cout << "- cy: " << cy << std::endl;
  773. std::cout << "- k1: " << k1 << std::endl;
  774. std::cout << "- k2: " << k2 << std::endl;
  775. std::cout << "- k3: " << k3 << std::endl;
  776. std::cout << "- k4: " << k4 << std::endl;
  777. mK = cv::Mat::eye(3,3,CV_32F);
  778. mK.at<float>(0,0) = fx;
  779. mK.at<float>(1,1) = fy;
  780. mK.at<float>(0,2) = cx;
  781. mK.at<float>(1,2) = cy;
  782. mK_.setIdentity();
  783. mK_(0,0) = fx;
  784. mK_(1,1) = fy;
  785. mK_(0,2) = cx;
  786. mK_(1,2) = cy;
  787. }
  788. if(mSensor==System::STEREO || mSensor==System::IMU_STEREO || mSensor==System::IMU_RGBD){
  789. // Right camera
  790. // Camera calibration parameters
  791. cv::FileNode node = fSettings["Camera2.fx"];
  792. if(!node.empty() && node.isReal())
  793. {
  794. fx = node.real();
  795. }
  796. else
  797. {
  798. std::cerr << "*Camera2.fx parameter doesn't exist or is not a real number*" << std::endl;
  799. b_miss_params = true;
  800. }
  801. node = fSettings["Camera2.fy"];
  802. if(!node.empty() && node.isReal())
  803. {
  804. fy = node.real();
  805. }
  806. else
  807. {
  808. std::cerr << "*Camera2.fy parameter doesn't exist or is not a real number*" << std::endl;
  809. b_miss_params = true;
  810. }
  811. node = fSettings["Camera2.cx"];
  812. if(!node.empty() && node.isReal())
  813. {
  814. cx = node.real();
  815. }
  816. else
  817. {
  818. std::cerr << "*Camera2.cx parameter doesn't exist or is not a real number*" << std::endl;
  819. b_miss_params = true;
  820. }
  821. node = fSettings["Camera2.cy"];
  822. if(!node.empty() && node.isReal())
  823. {
  824. cy = node.real();
  825. }
  826. else
  827. {
  828. std::cerr << "*Camera2.cy parameter doesn't exist or is not a real number*" << std::endl;
  829. b_miss_params = true;
  830. }
  831. // Distortion parameters
  832. node = fSettings["Camera2.k1"];
  833. if(!node.empty() && node.isReal())
  834. {
  835. k1 = node.real();
  836. }
  837. else
  838. {
  839. std::cerr << "*Camera2.k1 parameter doesn't exist or is not a real number*" << std::endl;
  840. b_miss_params = true;
  841. }
  842. node = fSettings["Camera2.k2"];
  843. if(!node.empty() && node.isReal())
  844. {
  845. k2 = node.real();
  846. }
  847. else
  848. {
  849. std::cerr << "*Camera2.k2 parameter doesn't exist or is not a real number*" << std::endl;
  850. b_miss_params = true;
  851. }
  852. node = fSettings["Camera2.k3"];
  853. if(!node.empty() && node.isReal())
  854. {
  855. k3 = node.real();
  856. }
  857. else
  858. {
  859. std::cerr << "*Camera2.k3 parameter doesn't exist or is not a real number*" << std::endl;
  860. b_miss_params = true;
  861. }
  862. node = fSettings["Camera2.k4"];
  863. if(!node.empty() && node.isReal())
  864. {
  865. k4 = node.real();
  866. }
  867. else
  868. {
  869. std::cerr << "*Camera2.k4 parameter doesn't exist or is not a real number*" << std::endl;
  870. b_miss_params = true;
  871. }
  872. int leftLappingBegin = -1;
  873. int leftLappingEnd = -1;
  874. int rightLappingBegin = -1;
  875. int rightLappingEnd = -1;
  876. node = fSettings["Camera.lappingBegin"];
  877. if(!node.empty() && node.isInt())
  878. {
  879. leftLappingBegin = node.operator int();
  880. }
  881. else
  882. {
  883. std::cout << "WARNING: Camera.lappingBegin not correctly defined" << std::endl;
  884. }
  885. node = fSettings["Camera.lappingEnd"];
  886. if(!node.empty() && node.isInt())
  887. {
  888. leftLappingEnd = node.operator int();
  889. }
  890. else
  891. {
  892. std::cout << "WARNING: Camera.lappingEnd not correctly defined" << std::endl;
  893. }
  894. node = fSettings["Camera2.lappingBegin"];
  895. if(!node.empty() && node.isInt())
  896. {
  897. rightLappingBegin = node.operator int();
  898. }
  899. else
  900. {
  901. std::cout << "WARNING: Camera2.lappingBegin not correctly defined" << std::endl;
  902. }
  903. node = fSettings["Camera2.lappingEnd"];
  904. if(!node.empty() && node.isInt())
  905. {
  906. rightLappingEnd = node.operator int();
  907. }
  908. else
  909. {
  910. std::cout << "WARNING: Camera2.lappingEnd not correctly defined" << std::endl;
  911. }
  912. node = fSettings["Tlr"];
  913. cv::Mat cvTlr;
  914. if(!node.empty())
  915. {
  916. cvTlr = node.mat();
  917. if(cvTlr.rows != 3 || cvTlr.cols != 4)
  918. {
  919. std::cerr << "*Tlr matrix have to be a 3x4 transformation matrix*" << std::endl;
  920. b_miss_params = true;
  921. }
  922. }
  923. else
  924. {
  925. std::cerr << "*Tlr matrix doesn't exist*" << std::endl;
  926. b_miss_params = true;
  927. }
  928. if(!b_miss_params)
  929. {
  930. if(mImageScale != 1.f)
  931. {
  932. // K matrix parameters must be scaled.
  933. fx = fx * mImageScale;
  934. fy = fy * mImageScale;
  935. cx = cx * mImageScale;
  936. cy = cy * mImageScale;
  937. leftLappingBegin = leftLappingBegin * mImageScale;
  938. leftLappingEnd = leftLappingEnd * mImageScale;
  939. rightLappingBegin = rightLappingBegin * mImageScale;
  940. rightLappingEnd = rightLappingEnd * mImageScale;
  941. }
  942. static_cast<KannalaBrandt8*>(mpCamera)->mvLappingArea[0] = leftLappingBegin;
  943. static_cast<KannalaBrandt8*>(mpCamera)->mvLappingArea[1] = leftLappingEnd;
  944. mpFrameDrawer->both = true;
  945. vector<float> vCamCalib2{fx,fy,cx,cy,k1,k2,k3,k4};
  946. mpCamera2 = new KannalaBrandt8(vCamCalib2);
  947. mpCamera2 = mpAtlas->AddCamera(mpCamera2);
  948. mTlr = Converter::toSophus(cvTlr);
  949. static_cast<KannalaBrandt8*>(mpCamera2)->mvLappingArea[0] = rightLappingBegin;
  950. static_cast<KannalaBrandt8*>(mpCamera2)->mvLappingArea[1] = rightLappingEnd;
  951. std::cout << "- Camera1 Lapping: " << leftLappingBegin << ", " << leftLappingEnd << std::endl;
  952. std::cout << std::endl << "Camera2 Parameters:" << std::endl;
  953. std::cout << "- Camera: Fisheye" << std::endl;
  954. std::cout << "- Image scale: " << mImageScale << std::endl;
  955. std::cout << "- fx: " << fx << std::endl;
  956. std::cout << "- fy: " << fy << std::endl;
  957. std::cout << "- cx: " << cx << std::endl;
  958. std::cout << "- cy: " << cy << std::endl;
  959. std::cout << "- k1: " << k1 << std::endl;
  960. std::cout << "- k2: " << k2 << std::endl;
  961. std::cout << "- k3: " << k3 << std::endl;
  962. std::cout << "- k4: " << k4 << std::endl;
  963. std::cout << "- mTlr: \n" << cvTlr << std::endl;
  964. std::cout << "- Camera2 Lapping: " << rightLappingBegin << ", " << rightLappingEnd << std::endl;
  965. }
  966. }
  967. if(b_miss_params)
  968. {
  969. return false;
  970. }
  971. }
  972. else
  973. {
  974. std::cerr << "*Not Supported Camera Sensor*" << std::endl;
  975. std::cerr << "Check an example configuration file with the desired sensor" << std::endl;
  976. }
  977. if(mSensor==System::STEREO || mSensor==System::RGBD || mSensor==System::IMU_STEREO || mSensor==System::IMU_RGBD )
  978. {
  979. cv::FileNode node = fSettings["Camera.bf"];
  980. if(!node.empty() && node.isReal())
  981. {
  982. mbf = node.real();
  983. if(mImageScale != 1.f)
  984. {
  985. mbf *= mImageScale;
  986. }
  987. }
  988. else
  989. {
  990. std::cerr << "*Camera.bf parameter doesn't exist or is not a real number*" << std::endl;
  991. b_miss_params = true;
  992. }
  993. }
  994. float fps = fSettings["Camera.fps"];
  995. if(fps==0)
  996. fps=30;
  997. // Max/Min Frames to insert keyframes and to check relocalisation
  998. mMinFrames = 0;
  999. mMaxFrames = fps;
  1000. cout << "- fps: " << fps << endl;
  1001. int nRGB = fSettings["Camera.RGB"];
  1002. mbRGB = nRGB;
  1003. if(mbRGB)
  1004. cout << "- color order: RGB (ignored if grayscale)" << endl;
  1005. else
  1006. cout << "- color order: BGR (ignored if grayscale)" << endl;
  1007. if(mSensor==System::STEREO || mSensor==System::RGBD || mSensor==System::IMU_STEREO || mSensor==System::IMU_RGBD)
  1008. {
  1009. float fx = mpCamera->getParameter(0);
  1010. cv::FileNode node = fSettings["ThDepth"];
  1011. if(!node.empty() && node.isReal())
  1012. {
  1013. mThDepth = node.real();
  1014. mThDepth = mbf*mThDepth/fx;
  1015. cout << endl << "Depth Threshold (Close/Far Points): " << mThDepth << endl;
  1016. }
  1017. else
  1018. {
  1019. std::cerr << "*ThDepth parameter doesn't exist or is not a real number*" << std::endl;
  1020. b_miss_params = true;
  1021. }
  1022. }
  1023. if(mSensor==System::RGBD || mSensor==System::IMU_RGBD)
  1024. {
  1025. cv::FileNode node = fSettings["DepthMapFactor"];
  1026. if(!node.empty() && node.isReal())
  1027. {
  1028. mDepthMapFactor = node.real();
  1029. if(fabs(mDepthMapFactor)<1e-5)
  1030. mDepthMapFactor=1;
  1031. else
  1032. mDepthMapFactor = 1.0f/mDepthMapFactor;
  1033. }
  1034. else
  1035. {
  1036. std::cerr << "*DepthMapFactor parameter doesn't exist or is not a real number*" << std::endl;
  1037. b_miss_params = true;
  1038. }
  1039. }
  1040. if(b_miss_params)
  1041. {
  1042. return false;
  1043. }
  1044. return true;
  1045. }
  1046. bool Tracking::ParseORBParamFile(cv::FileStorage &fSettings)
  1047. {
  1048. bool b_miss_params = false;
  1049. int nFeatures, nLevels, fIniThFAST, fMinThFAST;
  1050. float fScaleFactor;
  1051. cv::FileNode node = fSettings["ORBextractor.nFeatures"];
  1052. if(!node.empty() && node.isInt())
  1053. {
  1054. nFeatures = node.operator int();
  1055. }
  1056. else
  1057. {
  1058. std::cerr << "*ORBextractor.nFeatures parameter doesn't exist or is not an integer*" << std::endl;
  1059. b_miss_params = true;
  1060. }
  1061. node = fSettings["ORBextractor.scaleFactor"];
  1062. if(!node.empty() && node.isReal())
  1063. {
  1064. fScaleFactor = node.real();
  1065. }
  1066. else
  1067. {
  1068. std::cerr << "*ORBextractor.scaleFactor parameter doesn't exist or is not a real number*" << std::endl;
  1069. b_miss_params = true;
  1070. }
  1071. node = fSettings["ORBextractor.nLevels"];
  1072. if(!node.empty() && node.isInt())
  1073. {
  1074. nLevels = node.operator int();
  1075. }
  1076. else
  1077. {
  1078. std::cerr << "*ORBextractor.nLevels parameter doesn't exist or is not an integer*" << std::endl;
  1079. b_miss_params = true;
  1080. }
  1081. node = fSettings["ORBextractor.iniThFAST"];
  1082. if(!node.empty() && node.isInt())
  1083. {
  1084. fIniThFAST = node.operator int();
  1085. }
  1086. else
  1087. {
  1088. std::cerr << "*ORBextractor.iniThFAST parameter doesn't exist or is not an integer*" << std::endl;
  1089. b_miss_params = true;
  1090. }
  1091. node = fSettings["ORBextractor.minThFAST"];
  1092. if(!node.empty() && node.isInt())
  1093. {
  1094. fMinThFAST = node.operator int();
  1095. }
  1096. else
  1097. {
  1098. std::cerr << "*ORBextractor.minThFAST parameter doesn't exist or is not an integer*" << std::endl;
  1099. b_miss_params = true;
  1100. }
  1101. if(b_miss_params)
  1102. {
  1103. return false;
  1104. }
  1105. mpORBextractorLeft = new ORBextractor(nFeatures,fScaleFactor,nLevels,fIniThFAST,fMinThFAST);
  1106. if(mSensor==System::STEREO || mSensor==System::IMU_STEREO)
  1107. mpORBextractorRight = new ORBextractor(nFeatures,fScaleFactor,nLevels,fIniThFAST,fMinThFAST);
  1108. if(mSensor==System::MONOCULAR || mSensor==System::IMU_MONOCULAR)
  1109. mpIniORBextractor = new ORBextractor(5*nFeatures,fScaleFactor,nLevels,fIniThFAST,fMinThFAST);
  1110. cout << endl << "ORB Extractor Parameters: " << endl;
  1111. cout << "- Number of Features: " << nFeatures << endl;
  1112. cout << "- Scale Levels: " << nLevels << endl;
  1113. cout << "- Scale Factor: " << fScaleFactor << endl;
  1114. cout << "- Initial Fast Threshold: " << fIniThFAST << endl;
  1115. cout << "- Minimum Fast Threshold: " << fMinThFAST << endl;
  1116. return true;
  1117. }
  1118. bool Tracking::ParseIMUParamFile(cv::FileStorage &fSettings)
  1119. {
  1120. bool b_miss_params = false;
  1121. cv::Mat cvTbc;
  1122. cv::FileNode node = fSettings["Tbc"];
  1123. if(!node.empty())
  1124. {
  1125. cvTbc = node.mat();
  1126. if(cvTbc.rows != 4 || cvTbc.cols != 4)
  1127. {
  1128. std::cerr << "*Tbc matrix have to be a 4x4 transformation matrix*" << std::endl;
  1129. b_miss_params = true;
  1130. }
  1131. }
  1132. else
  1133. {
  1134. std::cerr << "*Tbc matrix doesn't exist*" << std::endl;
  1135. b_miss_params = true;
  1136. }
  1137. cout << endl;
  1138. cout << "Left camera to Imu Transform (Tbc): " << endl << cvTbc << endl;
  1139. Eigen::Matrix<float,4,4,Eigen::RowMajor> eigTbc(cvTbc.ptr<float>(0));
  1140. Sophus::SE3f Tbc(eigTbc);
  1141. node = fSettings["InsertKFsWhenLost"];
  1142. mInsertKFsLost = true;
  1143. if(!node.empty() && node.isInt())
  1144. {
  1145. mInsertKFsLost = (bool) node.operator int();
  1146. }
  1147. if(!mInsertKFsLost)
  1148. cout << "Do not insert keyframes when lost visual tracking " << endl;
  1149. float Ng, Na, Ngw, Naw;
  1150. node = fSettings["IMU.Frequency"];
  1151. if(!node.empty() && node.isInt())
  1152. {
  1153. mImuFreq = node.operator int();
  1154. mImuPer = 0.001; //1.0 / (double) mImuFreq;
  1155. }
  1156. else
  1157. {
  1158. std::cerr << "*IMU.Frequency parameter doesn't exist or is not an integer*" << std::endl;
  1159. b_miss_params = true;
  1160. }
  1161. node = fSettings["IMU.NoiseGyro"];
  1162. if(!node.empty() && node.isReal())
  1163. {
  1164. Ng = node.real();
  1165. }
  1166. else
  1167. {
  1168. std::cerr << "*IMU.NoiseGyro parameter doesn't exist or is not a real number*" << std::endl;
  1169. b_miss_params = true;
  1170. }
  1171. node = fSettings["IMU.NoiseAcc"];
  1172. if(!node.empty() && node.isReal())
  1173. {
  1174. Na = node.real();
  1175. }
  1176. else
  1177. {
  1178. std::cerr << "*IMU.NoiseAcc parameter doesn't exist or is not a real number*" << std::endl;
  1179. b_miss_params = true;
  1180. }
  1181. node = fSettings["IMU.GyroWalk"];
  1182. if(!node.empty() && node.isReal())
  1183. {
  1184. Ngw = node.real();
  1185. }
  1186. else
  1187. {
  1188. std::cerr << "*IMU.GyroWalk parameter doesn't exist or is not a real number*" << std::endl;
  1189. b_miss_params = true;
  1190. }
  1191. node = fSettings["IMU.AccWalk"];
  1192. if(!node.empty() && node.isReal())
  1193. {
  1194. Naw = node.real();
  1195. }
  1196. else
  1197. {
  1198. std::cerr << "*IMU.AccWalk parameter doesn't exist or is not a real number*" << std::endl;
  1199. b_miss_params = true;
  1200. }
  1201. node = fSettings["IMU.fastInit"];
  1202. mFastInit = false;
  1203. if(!node.empty())
  1204. {
  1205. mFastInit = static_cast<int>(fSettings["IMU.fastInit"]) != 0;
  1206. }
  1207. if(mFastInit)
  1208. cout << "Fast IMU initialization. Acceleration is not checked \n";
  1209. if(b_miss_params)
  1210. {
  1211. return false;
  1212. }
  1213. const float sf = sqrt(mImuFreq);
  1214. cout << endl;
  1215. cout << "IMU frequency: " << mImuFreq << " Hz" << endl;
  1216. cout << "IMU gyro noise: " << Ng << " rad/s/sqrt(Hz)" << endl;
  1217. cout << "IMU gyro walk: " << Ngw << " rad/s^2/sqrt(Hz)" << endl;
  1218. cout << "IMU accelerometer noise: " << Na << " m/s^2/sqrt(Hz)" << endl;
  1219. cout << "IMU accelerometer walk: " << Naw << " m/s^3/sqrt(Hz)" << endl;
  1220. mpImuCalib = new IMU::Calib(Tbc,Ng*sf,Na*sf,Ngw/sf,Naw/sf);
  1221. mpImuPreintegratedFromLastKF = new IMU::Preintegrated(IMU::Bias(),*mpImuCalib);
  1222. return true;
  1223. }
  1224. void Tracking::SetLocalMapper(LocalMapping *pLocalMapper)
  1225. {
  1226. mpLocalMapper=pLocalMapper;
  1227. }
  1228. void Tracking::SetLoopClosing(LoopClosing *pLoopClosing)
  1229. {
  1230. mpLoopClosing=pLoopClosing;
  1231. }
  1232. void Tracking::SetViewer(Viewer *pViewer)
  1233. {
  1234. mpViewer=pViewer;
  1235. }
  1236. void Tracking::SetStepByStep(bool bSet)
  1237. {
  1238. bStepByStep = bSet;
  1239. }
  1240. bool Tracking::GetStepByStep()
  1241. {
  1242. return bStepByStep;
  1243. }
  1244. Sophus::SE3f Tracking::GrabImageStereo(const cv::Mat &imRectLeft, const cv::Mat &imRectRight, const double &timestamp, string filename)
  1245. {
  1246. //cout << "GrabImageStereo" << endl;
  1247. mImGray = imRectLeft;
  1248. cv::Mat imGrayRight = imRectRight;
  1249. mImRight = imRectRight;
  1250. if(mImGray.channels()==3)
  1251. {
  1252. //cout << "Image with 3 channels" << endl;
  1253. if(mbRGB)
  1254. {
  1255. cvtColor(mImGray,mImGray,cv::COLOR_RGB2GRAY);
  1256. cvtColor(imGrayRight,imGrayRight,cv::COLOR_RGB2GRAY);
  1257. }
  1258. else
  1259. {
  1260. cvtColor(mImGray,mImGray,cv::COLOR_BGR2GRAY);
  1261. cvtColor(imGrayRight,imGrayRight,cv::COLOR_BGR2GRAY);
  1262. }
  1263. }
  1264. else if(mImGray.channels()==4)
  1265. {
  1266. //cout << "Image with 4 channels" << endl;
  1267. if(mbRGB)
  1268. {
  1269. cvtColor(mImGray,mImGray,cv::COLOR_RGBA2GRAY);
  1270. cvtColor(imGrayRight,imGrayRight,cv::COLOR_RGBA2GRAY);
  1271. }
  1272. else
  1273. {
  1274. cvtColor(mImGray,mImGray,cv::COLOR_BGRA2GRAY);
  1275. cvtColor(imGrayRight,imGrayRight,cv::COLOR_BGRA2GRAY);
  1276. }
  1277. }
  1278. //cout << "Incoming frame creation" << endl;
  1279. if (mSensor == System::STEREO && !mpCamera2)
  1280. mCurrentFrame = Frame(mImGray,imGrayRight,timestamp,mpORBextractorLeft,mpORBextractorRight,mpORBVocabulary,mK,mDistCoef,mbf,mThDepth,mpCamera);
  1281. else if(mSensor == System::STEREO && mpCamera2)
  1282. mCurrentFrame = Frame(mImGray,imGrayRight,timestamp,mpORBextractorLeft,mpORBextractorRight,mpORBVocabulary,mK,mDistCoef,mbf,mThDepth,mpCamera,mpCamera2,mTlr);
  1283. else if(mSensor == System::IMU_STEREO && !mpCamera2)
  1284. mCurrentFrame = Frame(mImGray,imGrayRight,timestamp,mpORBextractorLeft,mpORBextractorRight,mpORBVocabulary,mK,mDistCoef,mbf,mThDepth,mpCamera,&mLastFrame,*mpImuCalib);
  1285. else if(mSensor == System::IMU_STEREO && mpCamera2)
  1286. mCurrentFrame = Frame(mImGray,imGrayRight,timestamp,mpORBextractorLeft,mpORBextractorRight,mpORBVocabulary,mK,mDistCoef,mbf,mThDepth,mpCamera,mpCamera2,mTlr,&mLastFrame,*mpImuCalib);
  1287. //cout << "Incoming frame ended" << endl;
  1288. mCurrentFrame.mNameFile = filename;
  1289. mCurrentFrame.mnDataset = mnNumDataset;
  1290. #ifdef REGISTER_TIMES
  1291. vdORBExtract_ms.push_back(mCurrentFrame.mTimeORB_Ext);
  1292. vdStereoMatch_ms.push_back(mCurrentFrame.mTimeStereoMatch);
  1293. #endif
  1294. //cout << "Tracking start" << endl;
  1295. Track();
  1296. //cout << "Tracking end" << endl;
  1297. return mCurrentFrame.GetPose();
  1298. }
  1299. Sophus::SE3f Tracking::GrabImageRGBD(const cv::Mat &imRGB,const cv::Mat &imD, const double &timestamp, string filename)
  1300. {
  1301. mImGray = imRGB;
  1302. cv::Mat imDepth = imD;
  1303. if(mImGray.channels()==3)
  1304. {
  1305. if(mbRGB)
  1306. cvtColor(mImGray,mImGray,cv::COLOR_RGB2GRAY);
  1307. else
  1308. cvtColor(mImGray,mImGray,cv::COLOR_BGR2GRAY);
  1309. }
  1310. else if(mImGray.channels()==4)
  1311. {
  1312. if(mbRGB)
  1313. cvtColor(mImGray,mImGray,cv::COLOR_RGBA2GRAY);
  1314. else
  1315. cvtColor(mImGray,mImGray,cv::COLOR_BGRA2GRAY);
  1316. }
  1317. if((fabs(mDepthMapFactor-1.0f)>1e-5) || imDepth.type()!=CV_32F)
  1318. imDepth.convertTo(imDepth,CV_32F,mDepthMapFactor);
  1319. if (mSensor == System::RGBD)
  1320. mCurrentFrame = Frame(mImGray,imDepth,timestamp,mpORBextractorLeft,mpORBVocabulary,mK,mDistCoef,mbf,mThDepth,mpCamera);
  1321. else if(mSensor == System::IMU_RGBD)
  1322. mCurrentFrame = Frame(mImGray,imDepth,timestamp,mpORBextractorLeft,mpORBVocabulary,mK,mDistCoef,mbf,mThDepth,mpCamera,&mLastFrame,*mpImuCalib);
  1323. mCurrentFrame.mNameFile = filename;
  1324. mCurrentFrame.mnDataset = mnNumDataset;
  1325. #ifdef REGISTER_TIMES
  1326. vdORBExtract_ms.push_back(mCurrentFrame.mTimeORB_Ext);
  1327. #endif
  1328. Track();
  1329. return mCurrentFrame.GetPose();
  1330. }
  1331. Sophus::SE3f Tracking::GrabImageMonocular(const cv::Mat &im, const double &timestamp, string filename)
  1332. {
  1333. mImGray = im;
  1334. if(mImGray.channels()==3)
  1335. {
  1336. if(mbRGB)
  1337. cvtColor(mImGray,mImGray,cv::COLOR_RGB2GRAY);
  1338. else
  1339. cvtColor(mImGray,mImGray,cv::COLOR_BGR2GRAY);
  1340. }
  1341. else if(mImGray.channels()==4)
  1342. {
  1343. if(mbRGB)
  1344. cvtColor(mImGray,mImGray,cv::COLOR_RGBA2GRAY);
  1345. else
  1346. cvtColor(mImGray,mImGray,cv::COLOR_BGRA2GRAY);
  1347. }
  1348. if (mSensor == System::MONOCULAR)
  1349. {
  1350. if(mState==NOT_INITIALIZED || mState==NO_IMAGES_YET ||(lastID - initID) < mMaxFrames)
  1351. mCurrentFrame = Frame(mImGray,timestamp,mpIniORBextractor,mpORBVocabulary,mpCamera,mDistCoef,mbf,mThDepth);
  1352. else
  1353. mCurrentFrame = Frame(mImGray,timestamp,mpORBextractorLeft,mpORBVocabulary,mpCamera,mDistCoef,mbf,mThDepth);
  1354. }
  1355. else if(mSensor == System::IMU_MONOCULAR)
  1356. {
  1357. if(mState==NOT_INITIALIZED || mState==NO_IMAGES_YET)
  1358. {
  1359. mCurrentFrame = Frame(mImGray,timestamp,mpIniORBextractor,mpORBVocabulary,mpCamera,mDistCoef,mbf,mThDepth,&mLastFrame,*mpImuCalib);
  1360. }
  1361. else
  1362. mCurrentFrame = Frame(mImGray,timestamp,mpORBextractorLeft,mpORBVocabulary,mpCamera,mDistCoef,mbf,mThDepth,&mLastFrame,*mpImuCalib);
  1363. }
  1364. if (mState==NO_IMAGES_YET)
  1365. t0=timestamp;
  1366. mCurrentFrame.mNameFile = filename;
  1367. mCurrentFrame.mnDataset = mnNumDataset;
  1368. #ifdef REGISTER_TIMES
  1369. vdORBExtract_ms.push_back(mCurrentFrame.mTimeORB_Ext);
  1370. #endif
  1371. lastID = mCurrentFrame.mnId;
  1372. Track();
  1373. return mCurrentFrame.GetPose();
  1374. }
  1375. void Tracking::GrabImuData(const IMU::Point &imuMeasurement)
  1376. {
  1377. unique_lock<mutex> lock(mMutexImuQueue);
  1378. mlQueueImuData.push_back(imuMeasurement);
  1379. }
  1380. void Tracking::PreintegrateIMU()
  1381. {
  1382. if(!mCurrentFrame.mpPrevFrame)
  1383. {
  1384. Verbose::PrintMess("non prev frame ", Verbose::VERBOSITY_NORMAL);
  1385. mCurrentFrame.setIntegrated();
  1386. return;
  1387. }
  1388. mvImuFromLastFrame.clear();
  1389. mvImuFromLastFrame.reserve(mlQueueImuData.size());
  1390. if(mlQueueImuData.size() == 0)
  1391. {
  1392. Verbose::PrintMess("Not IMU data in mlQueueImuData!!", Verbose::VERBOSITY_NORMAL);
  1393. mCurrentFrame.setIntegrated();
  1394. return;
  1395. }
  1396. while(true)
  1397. {
  1398. bool bSleep = false;
  1399. {
  1400. unique_lock<mutex> lock(mMutexImuQueue);
  1401. if(!mlQueueImuData.empty())
  1402. {
  1403. IMU::Point* m = &mlQueueImuData.front();
  1404. cout.precision(17);
  1405. if(m->t<mCurrentFrame.mpPrevFrame->mTimeStamp-mImuPer)
  1406. {
  1407. mlQueueImuData.pop_front();
  1408. }
  1409. else if(m->t<mCurrentFrame.mTimeStamp-mImuPer)
  1410. {
  1411. mvImuFromLastFrame.push_back(*m);
  1412. mlQueueImuData.pop_front();
  1413. }
  1414. else
  1415. {
  1416. mvImuFromLastFrame.push_back(*m);
  1417. break;
  1418. }
  1419. }
  1420. else
  1421. {
  1422. break;
  1423. bSleep = true;
  1424. }
  1425. }
  1426. if(bSleep)
  1427. usleep(500);
  1428. }
  1429. const int n = mvImuFromLastFrame.size()-1;
  1430. if(n==0){
  1431. cout << "Empty IMU measurements vector!!!\n";
  1432. return;
  1433. }
  1434. IMU::Preintegrated* pImuPreintegratedFromLastFrame = new IMU::Preintegrated(mLastFrame.mImuBias,mCurrentFrame.mImuCalib);
  1435. for(int i=0; i<n; i++)
  1436. {
  1437. float tstep;
  1438. Eigen::Vector3f acc, angVel;
  1439. if((i==0) && (i<(n-1)))
  1440. {
  1441. float tab = mvImuFromLastFrame[i+1].t-mvImuFromLastFrame[i].t;
  1442. float tini = mvImuFromLastFrame[i].t-mCurrentFrame.mpPrevFrame->mTimeStamp;
  1443. acc = (mvImuFromLastFrame[i].a+mvImuFromLastFrame[i+1].a-
  1444. (mvImuFromLastFrame[i+1].a-mvImuFromLastFrame[i].a)*(tini/tab))*0.5f;
  1445. angVel = (mvImuFromLastFrame[i].w+mvImuFromLastFrame[i+1].w-
  1446. (mvImuFromLastFrame[i+1].w-mvImuFromLastFrame[i].w)*(tini/tab))*0.5f;
  1447. tstep = mvImuFromLastFrame[i+1].t-mCurrentFrame.mpPrevFrame->mTimeStamp;
  1448. }
  1449. else if(i<(n-1))
  1450. {
  1451. acc = (mvImuFromLastFrame[i].a+mvImuFromLastFrame[i+1].a)*0.5f;
  1452. angVel = (mvImuFromLastFrame[i].w+mvImuFromLastFrame[i+1].w)*0.5f;
  1453. tstep = mvImuFromLastFrame[i+1].t-mvImuFromLastFrame[i].t;
  1454. }
  1455. else if((i>0) && (i==(n-1)))
  1456. {
  1457. float tab = mvImuFromLastFrame[i+1].t-mvImuFromLastFrame[i].t;
  1458. float tend = mvImuFromLastFrame[i+1].t-mCurrentFrame.mTimeStamp;
  1459. acc = (mvImuFromLastFrame[i].a+mvImuFromLastFrame[i+1].a-
  1460. (mvImuFromLastFrame[i+1].a-mvImuFromLastFrame[i].a)*(tend/tab))*0.5f;
  1461. angVel = (mvImuFromLastFrame[i].w+mvImuFromLastFrame[i+1].w-
  1462. (mvImuFromLastFrame[i+1].w-mvImuFromLastFrame[i].w)*(tend/tab))*0.5f;
  1463. tstep = mCurrentFrame.mTimeStamp-mvImuFromLastFrame[i].t;
  1464. }
  1465. else if((i==0) && (i==(n-1)))
  1466. {
  1467. acc = mvImuFromLastFrame[i].a;
  1468. angVel = mvImuFromLastFrame[i].w;
  1469. tstep = mCurrentFrame.mTimeStamp-mCurrentFrame.mpPrevFrame->mTimeStamp;
  1470. }
  1471. if (!mpImuPreintegratedFromLastKF)
  1472. cout << "mpImuPreintegratedFromLastKF does not exist" << endl;
  1473. mpImuPreintegratedFromLastKF->IntegrateNewMeasurement(acc,angVel,tstep);
  1474. pImuPreintegratedFromLastFrame->IntegrateNewMeasurement(acc,angVel,tstep);
  1475. }
  1476. mCurrentFrame.mpImuPreintegratedFrame = pImuPreintegratedFromLastFrame;
  1477. mCurrentFrame.mpImuPreintegrated = mpImuPreintegratedFromLastKF;
  1478. mCurrentFrame.mpLastKeyFrame = mpLastKeyFrame;
  1479. mCurrentFrame.setIntegrated();
  1480. //Verbose::PrintMess("Preintegration is finished!! ", Verbose::VERBOSITY_DEBUG);
  1481. }
  1482. bool Tracking::PredictStateIMU()
  1483. {
  1484. if(!mCurrentFrame.mpPrevFrame)
  1485. {
  1486. Verbose::PrintMess("No last frame", Verbose::VERBOSITY_NORMAL);
  1487. return false;
  1488. }
  1489. if(mbMapUpdated && mpLastKeyFrame)
  1490. {
  1491. const Eigen::Vector3f twb1 = mpLastKeyFrame->GetImuPosition();
  1492. const Eigen::Matrix3f Rwb1 = mpLastKeyFrame->GetImuRotation();
  1493. const Eigen::Vector3f Vwb1 = mpLastKeyFrame->GetVelocity();
  1494. const Eigen::Vector3f Gz(0, 0, -IMU::GRAVITY_VALUE);
  1495. const float t12 = mpImuPreintegratedFromLastKF->dT;
  1496. Eigen::Matrix3f Rwb2 = IMU::NormalizeRotation(Rwb1 * mpImuPreintegratedFromLastKF->GetDeltaRotation(mpLastKeyFrame->GetImuBias()));
  1497. Eigen::Vector3f twb2 = twb1 + Vwb1*t12 + 0.5f*t12*t12*Gz+ Rwb1*mpImuPreintegratedFromLastKF->GetDeltaPosition(mpLastKeyFrame->GetImuBias());
  1498. Eigen::Vector3f Vwb2 = Vwb1 + t12*Gz + Rwb1 * mpImuPreintegratedFromLastKF->GetDeltaVelocity(mpLastKeyFrame->GetImuBias());
  1499. mCurrentFrame.SetImuPoseVelocity(Rwb2,twb2,Vwb2);
  1500. mCurrentFrame.mImuBias = mpLastKeyFrame->GetImuBias();
  1501. mCurrentFrame.mPredBias = mCurrentFrame.mImuBias;
  1502. return true;
  1503. }
  1504. else if(!mbMapUpdated)
  1505. {
  1506. const Eigen::Vector3f twb1 = mLastFrame.GetImuPosition();
  1507. const Eigen::Matrix3f Rwb1 = mLastFrame.GetImuRotation();
  1508. const Eigen::Vector3f Vwb1 = mLastFrame.GetVelocity();
  1509. const Eigen::Vector3f Gz(0, 0, -IMU::GRAVITY_VALUE);
  1510. const float t12 = mCurrentFrame.mpImuPreintegratedFrame->dT;
  1511. Eigen::Matrix3f Rwb2 = IMU::NormalizeRotation(Rwb1 * mCurrentFrame.mpImuPreintegratedFrame->GetDeltaRotation(mLastFrame.mImuBias));
  1512. Eigen::Vector3f twb2 = twb1 + Vwb1*t12 + 0.5f*t12*t12*Gz+ Rwb1 * mCurrentFrame.mpImuPreintegratedFrame->GetDeltaPosition(mLastFrame.mImuBias);
  1513. Eigen::Vector3f Vwb2 = Vwb1 + t12*Gz + Rwb1 * mCurrentFrame.mpImuPreintegratedFrame->GetDeltaVelocity(mLastFrame.mImuBias);
  1514. mCurrentFrame.SetImuPoseVelocity(Rwb2,twb2,Vwb2);
  1515. mCurrentFrame.mImuBias = mLastFrame.mImuBias;
  1516. mCurrentFrame.mPredBias = mCurrentFrame.mImuBias;
  1517. return true;
  1518. }
  1519. else
  1520. cout << "not IMU prediction!!" << endl;
  1521. return false;
  1522. }
  1523. void Tracking::ResetFrameIMU()
  1524. {
  1525. // TODO To implement...
  1526. }
  1527. void Tracking::Track()
  1528. {
  1529. if (bStepByStep)
  1530. {
  1531. std::cout << "Tracking: Waiting to the next step" << std::endl;
  1532. while(!mbStep && bStepByStep)
  1533. usleep(500);
  1534. mbStep = false;
  1535. }
  1536. if(mpLocalMapper->mbBadImu)
  1537. {
  1538. cout << "TRACK: Reset map because local mapper set the bad imu flag " << endl;
  1539. mpSystem->ResetActiveMap();
  1540. return;
  1541. }
  1542. Map* pCurrentMap = mpAtlas->GetCurrentMap();
  1543. if(!pCurrentMap)
  1544. {
  1545. cout << "ERROR: There is not an active map in the atlas" << endl;
  1546. }
  1547. if(mState!=NO_IMAGES_YET)
  1548. {
  1549. if(mLastFrame.mTimeStamp>mCurrentFrame.mTimeStamp)
  1550. {
  1551. cerr << "ERROR: Frame with a timestamp older than previous frame detected!" << endl;
  1552. unique_lock<mutex> lock(mMutexImuQueue);
  1553. mlQueueImuData.clear();
  1554. CreateMapInAtlas();
  1555. return;
  1556. }
  1557. else if(mCurrentFrame.mTimeStamp>mLastFrame.mTimeStamp+1.0)
  1558. {
  1559. // cout << mCurrentFrame.mTimeStamp << ", " << mLastFrame.mTimeStamp << endl;
  1560. // cout << "id last: " << mLastFrame.mnId << " id curr: " << mCurrentFrame.mnId << endl;
  1561. if(mpAtlas->isInertial())
  1562. {
  1563. if(mpAtlas->isImuInitialized())
  1564. {
  1565. cout << "Timestamp jump detected. State set to LOST. Reseting IMU integration..." << endl;
  1566. if(!pCurrentMap->GetIniertialBA2())
  1567. {
  1568. mpSystem->ResetActiveMap();
  1569. }
  1570. else
  1571. {
  1572. CreateMapInAtlas();
  1573. }
  1574. }
  1575. else
  1576. {
  1577. cout << "Timestamp jump detected, before IMU initialization. Reseting..." << endl;
  1578. mpSystem->ResetActiveMap();
  1579. }
  1580. return;
  1581. }
  1582. }
  1583. }
  1584. if ((mSensor == System::IMU_MONOCULAR || mSensor == System::IMU_STEREO || mSensor == System::IMU_RGBD) && mpLastKeyFrame)
  1585. mCurrentFrame.SetNewBias(mpLastKeyFrame->GetImuBias());
  1586. if(mState==NO_IMAGES_YET)
  1587. {
  1588. mState = NOT_INITIALIZED;
  1589. }
  1590. mLastProcessedState=mState;
  1591. if ((mSensor == System::IMU_MONOCULAR || mSensor == System::IMU_STEREO || mSensor == System::IMU_RGBD) && !mbCreatedMap)
  1592. {
  1593. #ifdef REGISTER_TIMES
  1594. std::chrono::steady_clock::time_point time_StartPreIMU = std::chrono::steady_clock::now();
  1595. #endif
  1596. PreintegrateIMU();
  1597. #ifdef REGISTER_TIMES
  1598. std::chrono::steady_clock::time_point time_EndPreIMU = std::chrono::steady_clock::now();
  1599. double timePreImu = std::chrono::duration_cast<std::chrono::duration<double,std::milli> >(time_EndPreIMU - time_StartPreIMU).count();
  1600. vdIMUInteg_ms.push_back(timePreImu);
  1601. #endif
  1602. }
  1603. mbCreatedMap = false;
  1604. // Get Map Mutex -> Map cannot be changed
  1605. unique_lock<mutex> lock(pCurrentMap->mMutexMapUpdate);
  1606. mbMapUpdated = false;
  1607. int nCurMapChangeIndex = pCurrentMap->GetMapChangeIndex();
  1608. int nMapChangeIndex = pCurrentMap->GetLastMapChange();
  1609. if(nCurMapChangeIndex>nMapChangeIndex)
  1610. {
  1611. pCurrentMap->SetLastMapChange(nCurMapChangeIndex);
  1612. mbMapUpdated = true;
  1613. }
  1614. if(mState==NOT_INITIALIZED)
  1615. {
  1616. if(mSensor==System::STEREO || mSensor==System::RGBD || mSensor==System::IMU_STEREO || mSensor==System::IMU_RGBD)
  1617. {
  1618. StereoInitialization();
  1619. }
  1620. else
  1621. {
  1622. MonocularInitialization();
  1623. }
  1624. //mpFrameDrawer->Update(this);
  1625. if(mState!=OK) // If rightly initialized, mState=OK
  1626. {
  1627. mLastFrame = Frame(mCurrentFrame);
  1628. return;
  1629. }
  1630. if(mpAtlas->GetAllMaps().size() == 1)
  1631. {
  1632. mnFirstFrameId = mCurrentFrame.mnId;
  1633. }
  1634. }
  1635. else
  1636. {
  1637. // System is initialized. Track Frame.
  1638. bool bOK;
  1639. #ifdef REGISTER_TIMES
  1640. std::chrono::steady_clock::time_point time_StartPosePred = std::chrono::steady_clock::now();
  1641. #endif
  1642. // Initial camera pose estimation using motion model or relocalization (if tracking is lost)
  1643. if(!mbOnlyTracking)
  1644. {
  1645. // State OK
  1646. // Local Mapping is activated. This is the normal behaviour, unless
  1647. // you explicitly activate the "only tracking" mode.
  1648. if(mState==OK)
  1649. {
  1650. // Local Mapping might have changed some MapPoints tracked in last frame
  1651. CheckReplacedInLastFrame();
  1652. if((!mbVelocity && !pCurrentMap->isImuInitialized()) || mCurrentFrame.mnId<mnLastRelocFrameId+2)
  1653. {
  1654. Verbose::PrintMess("TRACK: Track with respect to the reference KF ", Verbose::VERBOSITY_DEBUG);
  1655. bOK = TrackReferenceKeyFrame();
  1656. }
  1657. else
  1658. {
  1659. Verbose::PrintMess("TRACK: Track with motion model", Verbose::VERBOSITY_DEBUG);
  1660. bOK = TrackWithMotionModel();
  1661. if(!bOK)
  1662. bOK = TrackReferenceKeyFrame();
  1663. }
  1664. if (!bOK)
  1665. {
  1666. if ( mCurrentFrame.mnId<=(mnLastRelocFrameId+mnFramesToResetIMU) &&
  1667. (mSensor==System::IMU_MONOCULAR || mSensor==System::IMU_STEREO || mSensor == System::IMU_RGBD))
  1668. {
  1669. mState = LOST;
  1670. }
  1671. else if(pCurrentMap->KeyFramesInMap()>10)
  1672. {
  1673. // cout << "KF in map: " << pCurrentMap->KeyFramesInMap() << endl;
  1674. mState = RECENTLY_LOST;
  1675. mTimeStampLost = mCurrentFrame.mTimeStamp;
  1676. }
  1677. else
  1678. {
  1679. mState = LOST;
  1680. }
  1681. }
  1682. }
  1683. else
  1684. {
  1685. if (mState == RECENTLY_LOST)
  1686. {
  1687. Verbose::PrintMess("Lost for a short time", Verbose::VERBOSITY_NORMAL);
  1688. bOK = true;
  1689. if((mSensor == System::IMU_MONOCULAR || mSensor == System::IMU_STEREO || mSensor == System::IMU_RGBD))
  1690. {
  1691. if(pCurrentMap->isImuInitialized())
  1692. PredictStateIMU();
  1693. else
  1694. bOK = false;
  1695. if (mCurrentFrame.mTimeStamp-mTimeStampLost>time_recently_lost)
  1696. {
  1697. mState = LOST;
  1698. Verbose::PrintMess("Track Lost...", Verbose::VERBOSITY_NORMAL);
  1699. bOK=false;
  1700. }
  1701. }
  1702. else
  1703. {
  1704. // Relocalization
  1705. bOK = Relocalization();
  1706. //std::cout << "mCurrentFrame.mTimeStamp:" << to_string(mCurrentFrame.mTimeStamp) << std::endl;
  1707. //std::cout << "mTimeStampLost:" << to_string(mTimeStampLost) << std::endl;
  1708. if(mCurrentFrame.mTimeStamp-mTimeStampLost>3.0f && !bOK)
  1709. {
  1710. mState = LOST;
  1711. Verbose::PrintMess("Track Lost...", Verbose::VERBOSITY_NORMAL);
  1712. bOK=false;
  1713. }
  1714. }
  1715. }
  1716. else if (mState == LOST)
  1717. {
  1718. Verbose::PrintMess("A new map is started...", Verbose::VERBOSITY_NORMAL);
  1719. if (pCurrentMap->KeyFramesInMap()<10)
  1720. {
  1721. mpSystem->ResetActiveMap();
  1722. Verbose::PrintMess("Reseting current map...", Verbose::VERBOSITY_NORMAL);
  1723. }else
  1724. CreateMapInAtlas();
  1725. if(mpLastKeyFrame)
  1726. mpLastKeyFrame = static_cast<KeyFrame*>(NULL);
  1727. Verbose::PrintMess("done", Verbose::VERBOSITY_NORMAL);
  1728. return;
  1729. }
  1730. }
  1731. }
  1732. else
  1733. {
  1734. // Localization Mode: Local Mapping is deactivated (TODO Not available in inertial mode)
  1735. if(mState==LOST)
  1736. {
  1737. if(mSensor == System::IMU_MONOCULAR || mSensor == System::IMU_STEREO || mSensor == System::IMU_RGBD)
  1738. Verbose::PrintMess("IMU. State LOST", Verbose::VERBOSITY_NORMAL);
  1739. bOK = Relocalization();
  1740. }
  1741. else
  1742. {
  1743. if(!mbVO)
  1744. {
  1745. // In last frame we tracked enough MapPoints in the map
  1746. if(mbVelocity)
  1747. {
  1748. bOK = TrackWithMotionModel();
  1749. }
  1750. else
  1751. {
  1752. bOK = TrackReferenceKeyFrame();
  1753. }
  1754. }
  1755. else
  1756. {
  1757. // In last frame we tracked mainly "visual odometry" points.
  1758. // We compute two camera poses, one from motion model and one doing relocalization.
  1759. // If relocalization is sucessfull we choose that solution, otherwise we retain
  1760. // the "visual odometry" solution.
  1761. bool bOKMM = false;
  1762. bool bOKReloc = false;
  1763. vector<MapPoint*> vpMPsMM;
  1764. vector<bool> vbOutMM;
  1765. Sophus::SE3f TcwMM;
  1766. if(mbVelocity)
  1767. {
  1768. bOKMM = TrackWithMotionModel();
  1769. vpMPsMM = mCurrentFrame.mvpMapPoints;
  1770. vbOutMM = mCurrentFrame.mvbOutlier;
  1771. TcwMM = mCurrentFrame.GetPose();
  1772. }
  1773. bOKReloc = Relocalization();
  1774. if(bOKMM && !bOKReloc)
  1775. {
  1776. mCurrentFrame.SetPose(TcwMM);
  1777. mCurrentFrame.mvpMapPoints = vpMPsMM;
  1778. mCurrentFrame.mvbOutlier = vbOutMM;
  1779. if(mbVO)
  1780. {
  1781. for(int i =0; i<mCurrentFrame.N; i++)
  1782. {
  1783. if(mCurrentFrame.mvpMapPoints[i] && !mCurrentFrame.mvbOutlier[i])
  1784. {
  1785. mCurrentFrame.mvpMapPoints[i]->IncreaseFound();
  1786. }
  1787. }
  1788. }
  1789. }
  1790. else if(bOKReloc)
  1791. {
  1792. mbVO = false;
  1793. }
  1794. bOK = bOKReloc || bOKMM;
  1795. }
  1796. }
  1797. }
  1798. if(!mCurrentFrame.mpReferenceKF)
  1799. mCurrentFrame.mpReferenceKF = mpReferenceKF;
  1800. #ifdef REGISTER_TIMES
  1801. std::chrono::steady_clock::time_point time_EndPosePred = std::chrono::steady_clock::now();
  1802. double timePosePred = std::chrono::duration_cast<std::chrono::duration<double,std::milli> >(time_EndPosePred - time_StartPosePred).count();
  1803. vdPosePred_ms.push_back(timePosePred);
  1804. #endif
  1805. #ifdef REGISTER_TIMES
  1806. std::chrono::steady_clock::time_point time_StartLMTrack = std::chrono::steady_clock::now();
  1807. #endif
  1808. // If we have an initial estimation of the camera pose and matching. Track the local map.
  1809. if(!mbOnlyTracking)
  1810. {
  1811. if(bOK)
  1812. {
  1813. bOK = TrackLocalMap();
  1814. }
  1815. if(!bOK)
  1816. cout << "Fail to track local map!" << endl;
  1817. }
  1818. else
  1819. {
  1820. // mbVO true means that there are few matches to MapPoints in the map. We cannot retrieve
  1821. // a local map and therefore we do not perform TrackLocalMap(). Once the system relocalizes
  1822. // the camera we will use the local map again.
  1823. if(bOK && !mbVO)
  1824. bOK = TrackLocalMap();
  1825. }
  1826. if(bOK)
  1827. mState = OK;
  1828. else if (mState == OK)
  1829. {
  1830. if (mSensor == System::IMU_MONOCULAR || mSensor == System::IMU_STEREO || mSensor == System::IMU_RGBD)
  1831. {
  1832. Verbose::PrintMess("Track lost for less than one second...", Verbose::VERBOSITY_NORMAL);
  1833. if(!pCurrentMap->isImuInitialized() || !pCurrentMap->GetIniertialBA2())
  1834. {
  1835. cout << "IMU is not or recently initialized. Reseting active map..." << endl;
  1836. mpSystem->ResetActiveMap();
  1837. }
  1838. mState=RECENTLY_LOST;
  1839. }
  1840. else
  1841. mState=RECENTLY_LOST; // visual to lost
  1842. /*if(mCurrentFrame.mnId>mnLastRelocFrameId+mMaxFrames)
  1843. {*/
  1844. mTimeStampLost = mCurrentFrame.mTimeStamp;
  1845. //}
  1846. }
  1847. // 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)
  1848. if((mCurrentFrame.mnId<(mnLastRelocFrameId+mnFramesToResetIMU)) && (mCurrentFrame.mnId > mnFramesToResetIMU) &&
  1849. (mSensor == System::IMU_MONOCULAR || mSensor == System::IMU_STEREO || mSensor == System::IMU_RGBD) && pCurrentMap->isImuInitialized())
  1850. {
  1851. // TODO check this situation
  1852. Verbose::PrintMess("Saving pointer to frame. imu needs reset...", Verbose::VERBOSITY_NORMAL);
  1853. Frame* pF = new Frame(mCurrentFrame);
  1854. pF->mpPrevFrame = new Frame(mLastFrame);
  1855. // Load preintegration
  1856. pF->mpImuPreintegratedFrame = new IMU::Preintegrated(mCurrentFrame.mpImuPreintegratedFrame);
  1857. }
  1858. if(pCurrentMap->isImuInitialized())
  1859. {
  1860. if(bOK)
  1861. {
  1862. if(mCurrentFrame.mnId==(mnLastRelocFrameId+mnFramesToResetIMU))
  1863. {
  1864. cout << "RESETING FRAME!!!" << endl;
  1865. ResetFrameIMU();
  1866. }
  1867. else if(mCurrentFrame.mnId>(mnLastRelocFrameId+30))
  1868. mLastBias = mCurrentFrame.mImuBias;
  1869. }
  1870. }
  1871. #ifdef REGISTER_TIMES
  1872. std::chrono::steady_clock::time_point time_EndLMTrack = std::chrono::steady_clock::now();
  1873. double timeLMTrack = std::chrono::duration_cast<std::chrono::duration<double,std::milli> >(time_EndLMTrack - time_StartLMTrack).count();
  1874. vdLMTrack_ms.push_back(timeLMTrack);
  1875. #endif
  1876. // Update drawer
  1877. mpFrameDrawer->Update(this);
  1878. if(mCurrentFrame.isSet())
  1879. mpMapDrawer->SetCurrentCameraPose(mCurrentFrame.GetPose());
  1880. if(bOK || mState==RECENTLY_LOST)
  1881. {
  1882. // Update motion model
  1883. if(mLastFrame.isSet() && mCurrentFrame.isSet())
  1884. {
  1885. Sophus::SE3f LastTwc = mLastFrame.GetPose().inverse();
  1886. mVelocity = mCurrentFrame.GetPose() * LastTwc;
  1887. mbVelocity = true;
  1888. }
  1889. else {
  1890. mbVelocity = false;
  1891. }
  1892. if(mSensor == System::IMU_MONOCULAR || mSensor == System::IMU_STEREO || mSensor == System::IMU_RGBD)
  1893. mpMapDrawer->SetCurrentCameraPose(mCurrentFrame.GetPose());
  1894. // Clean VO matches
  1895. for(int i=0; i<mCurrentFrame.N; i++)
  1896. {
  1897. MapPoint* pMP = mCurrentFrame.mvpMapPoints[i];
  1898. if(pMP)
  1899. if(pMP->Observations()<1)
  1900. {
  1901. mCurrentFrame.mvbOutlier[i] = false;
  1902. mCurrentFrame.mvpMapPoints[i]=static_cast<MapPoint*>(NULL);
  1903. }
  1904. }
  1905. // Delete temporal MapPoints
  1906. for(list<MapPoint*>::iterator lit = mlpTemporalPoints.begin(), lend = mlpTemporalPoints.end(); lit!=lend; lit++)
  1907. {
  1908. MapPoint* pMP = *lit;
  1909. delete pMP;
  1910. }
  1911. mlpTemporalPoints.clear();
  1912. #ifdef REGISTER_TIMES
  1913. std::chrono::steady_clock::time_point time_StartNewKF = std::chrono::steady_clock::now();
  1914. #endif
  1915. bool bNeedKF = NeedNewKeyFrame();
  1916. // Check if we need to insert a new keyframe
  1917. // if(bNeedKF && bOK)
  1918. if(bNeedKF && (bOK || (mInsertKFsLost && mState==RECENTLY_LOST &&
  1919. (mSensor == System::IMU_MONOCULAR || mSensor == System::IMU_STEREO || mSensor == System::IMU_RGBD))))
  1920. CreateNewKeyFrame();
  1921. #ifdef REGISTER_TIMES
  1922. std::chrono::steady_clock::time_point time_EndNewKF = std::chrono::steady_clock::now();
  1923. double timeNewKF = std::chrono::duration_cast<std::chrono::duration<double,std::milli> >(time_EndNewKF - time_StartNewKF).count();
  1924. vdNewKF_ms.push_back(timeNewKF);
  1925. #endif
  1926. // We allow points with high innovation (considererd outliers by the Huber Function)
  1927. // pass to the new keyframe, so that bundle adjustment will finally decide
  1928. // if they are outliers or not. We don't want next frame to estimate its position
  1929. // with those points so we discard them in the frame. Only has effect if lastframe is tracked
  1930. for(int i=0; i<mCurrentFrame.N;i++)
  1931. {
  1932. if(mCurrentFrame.mvpMapPoints[i] && mCurrentFrame.mvbOutlier[i])
  1933. mCurrentFrame.mvpMapPoints[i]=static_cast<MapPoint*>(NULL);
  1934. }
  1935. }
  1936. // Reset if the camera get lost soon after initialization
  1937. if(mState==LOST)
  1938. {
  1939. if(pCurrentMap->KeyFramesInMap()<=10)
  1940. {
  1941. mpSystem->ResetActiveMap();
  1942. return;
  1943. }
  1944. if (mSensor == System::IMU_MONOCULAR || mSensor == System::IMU_STEREO || mSensor == System::IMU_RGBD)
  1945. if (!pCurrentMap->isImuInitialized())
  1946. {
  1947. Verbose::PrintMess("Track lost before IMU initialisation, reseting...", Verbose::VERBOSITY_QUIET);
  1948. mpSystem->ResetActiveMap();
  1949. return;
  1950. }
  1951. CreateMapInAtlas();
  1952. return;
  1953. }
  1954. if(!mCurrentFrame.mpReferenceKF)
  1955. mCurrentFrame.mpReferenceKF = mpReferenceKF;
  1956. mLastFrame = Frame(mCurrentFrame);
  1957. }
  1958. if(mState==OK || mState==RECENTLY_LOST)
  1959. {
  1960. // Store frame pose information to retrieve the complete camera trajectory afterwards.
  1961. if(mCurrentFrame.isSet())
  1962. {
  1963. Sophus::SE3f Tcr_ = mCurrentFrame.GetPose() * mCurrentFrame.mpReferenceKF->GetPoseInverse();
  1964. mlRelativeFramePoses.push_back(Tcr_);
  1965. mlpReferences.push_back(mCurrentFrame.mpReferenceKF);
  1966. mlFrameTimes.push_back(mCurrentFrame.mTimeStamp);
  1967. mlbLost.push_back(mState==LOST);
  1968. }
  1969. else
  1970. {
  1971. // This can happen if tracking is lost
  1972. mlRelativeFramePoses.push_back(mlRelativeFramePoses.back());
  1973. mlpReferences.push_back(mlpReferences.back());
  1974. mlFrameTimes.push_back(mlFrameTimes.back());
  1975. mlbLost.push_back(mState==LOST);
  1976. }
  1977. }
  1978. #ifdef REGISTER_LOOP
  1979. if (Stop()) {
  1980. // Safe area to stop
  1981. while(isStopped())
  1982. {
  1983. usleep(3000);
  1984. }
  1985. }
  1986. #endif
  1987. }
  1988. void Tracking::StereoInitialization()
  1989. {
  1990. if(mCurrentFrame.N>500)
  1991. {
  1992. if (mSensor == System::IMU_STEREO || mSensor == System::IMU_RGBD)
  1993. {
  1994. if (!mCurrentFrame.mpImuPreintegrated || !mLastFrame.mpImuPreintegrated)
  1995. {
  1996. cout << "not IMU meas" << endl;
  1997. return;
  1998. }
  1999. if (!mFastInit && (mCurrentFrame.mpImuPreintegratedFrame->avgA-mLastFrame.mpImuPreintegratedFrame->avgA).norm()<0.5)
  2000. {
  2001. cout << "not enough acceleration" << endl;
  2002. return;
  2003. }
  2004. if(mpImuPreintegratedFromLastKF)
  2005. delete mpImuPreintegratedFromLastKF;
  2006. mpImuPreintegratedFromLastKF = new IMU::Preintegrated(IMU::Bias(),*mpImuCalib);
  2007. mCurrentFrame.mpImuPreintegrated = mpImuPreintegratedFromLastKF;
  2008. }
  2009. // Set Frame pose to the origin (In case of inertial SLAM to imu)
  2010. if (mSensor == System::IMU_STEREO || mSensor == System::IMU_RGBD)
  2011. {
  2012. Eigen::Matrix3f Rwb0 = mCurrentFrame.mImuCalib.mTcb.rotationMatrix();
  2013. Eigen::Vector3f twb0 = mCurrentFrame.mImuCalib.mTcb.translation();
  2014. Eigen::Vector3f Vwb0;
  2015. Vwb0.setZero();
  2016. mCurrentFrame.SetImuPoseVelocity(Rwb0, twb0, Vwb0);
  2017. }
  2018. else
  2019. mCurrentFrame.SetPose(Sophus::SE3f());
  2020. // Create KeyFrame
  2021. KeyFrame* pKFini = new KeyFrame(mCurrentFrame,mpAtlas->GetCurrentMap(),mpKeyFrameDB);
  2022. // Insert KeyFrame in the map
  2023. mpAtlas->AddKeyFrame(pKFini);
  2024. // Create MapPoints and asscoiate to KeyFrame
  2025. if(!mpCamera2){
  2026. for(int i=0; i<mCurrentFrame.N;i++)
  2027. {
  2028. float z = mCurrentFrame.mvDepth[i];
  2029. if(z>0)
  2030. {
  2031. Eigen::Vector3f x3D;
  2032. mCurrentFrame.UnprojectStereo(i, x3D);
  2033. MapPoint* pNewMP = new MapPoint(x3D, pKFini, mpAtlas->GetCurrentMap());
  2034. pNewMP->AddObservation(pKFini,i);
  2035. pKFini->AddMapPoint(pNewMP,i);
  2036. pNewMP->ComputeDistinctiveDescriptors();
  2037. pNewMP->UpdateNormalAndDepth();
  2038. mpAtlas->AddMapPoint(pNewMP);
  2039. mCurrentFrame.mvpMapPoints[i]=pNewMP;
  2040. }
  2041. }
  2042. } else{
  2043. for(int i = 0; i < mCurrentFrame.Nleft; i++){
  2044. int rightIndex = mCurrentFrame.mvLeftToRightMatch[i];
  2045. if(rightIndex != -1){
  2046. Eigen::Vector3f x3D = mCurrentFrame.mvStereo3Dpoints[i];
  2047. MapPoint* pNewMP = new MapPoint(x3D, pKFini, mpAtlas->GetCurrentMap());
  2048. pNewMP->AddObservation(pKFini,i);
  2049. pNewMP->AddObservation(pKFini,rightIndex + mCurrentFrame.Nleft);
  2050. pKFini->AddMapPoint(pNewMP,i);
  2051. pKFini->AddMapPoint(pNewMP,rightIndex + mCurrentFrame.Nleft);
  2052. pNewMP->ComputeDistinctiveDescriptors();
  2053. pNewMP->UpdateNormalAndDepth();
  2054. mpAtlas->AddMapPoint(pNewMP);
  2055. mCurrentFrame.mvpMapPoints[i]=pNewMP;
  2056. mCurrentFrame.mvpMapPoints[rightIndex + mCurrentFrame.Nleft]=pNewMP;
  2057. }
  2058. }
  2059. }
  2060. Verbose::PrintMess("New Map created with " + to_string(mpAtlas->MapPointsInMap()) + " points", Verbose::VERBOSITY_QUIET);
  2061. //cout << "Active map: " << mpAtlas->GetCurrentMap()->GetId() << endl;
  2062. mpLocalMapper->InsertKeyFrame(pKFini);
  2063. mLastFrame = Frame(mCurrentFrame);
  2064. mnLastKeyFrameId = mCurrentFrame.mnId;
  2065. mpLastKeyFrame = pKFini;
  2066. //mnLastRelocFrameId = mCurrentFrame.mnId;
  2067. mvpLocalKeyFrames.push_back(pKFini);
  2068. mvpLocalMapPoints=mpAtlas->GetAllMapPoints();
  2069. mpReferenceKF = pKFini;
  2070. mCurrentFrame.mpReferenceKF = pKFini;
  2071. mpAtlas->SetReferenceMapPoints(mvpLocalMapPoints);
  2072. mpAtlas->GetCurrentMap()->mvpKeyFrameOrigins.push_back(pKFini);
  2073. mpMapDrawer->SetCurrentCameraPose(mCurrentFrame.GetPose());
  2074. mState=OK;
  2075. }
  2076. }
  2077. void Tracking::MonocularInitialization()
  2078. {
  2079. if(!mbReadyToInitializate)
  2080. {
  2081. // Set Reference Frame
  2082. if(mCurrentFrame.mvKeys.size()>100)
  2083. {
  2084. mInitialFrame = Frame(mCurrentFrame);
  2085. mLastFrame = Frame(mCurrentFrame);
  2086. mvbPrevMatched.resize(mCurrentFrame.mvKeysUn.size());
  2087. for(size_t i=0; i<mCurrentFrame.mvKeysUn.size(); i++)
  2088. mvbPrevMatched[i]=mCurrentFrame.mvKeysUn[i].pt;
  2089. fill(mvIniMatches.begin(),mvIniMatches.end(),-1);
  2090. if (mSensor == System::IMU_MONOCULAR)
  2091. {
  2092. if(mpImuPreintegratedFromLastKF)
  2093. {
  2094. delete mpImuPreintegratedFromLastKF;
  2095. }
  2096. mpImuPreintegratedFromLastKF = new IMU::Preintegrated(IMU::Bias(),*mpImuCalib);
  2097. mCurrentFrame.mpImuPreintegrated = mpImuPreintegratedFromLastKF;
  2098. }
  2099. mbReadyToInitializate = true;
  2100. return;
  2101. }
  2102. }
  2103. else
  2104. {
  2105. if (((int)mCurrentFrame.mvKeys.size()<=100)||((mSensor == System::IMU_MONOCULAR)&&(mLastFrame.mTimeStamp-mInitialFrame.mTimeStamp>1.0)))
  2106. {
  2107. mbReadyToInitializate = false;
  2108. return;
  2109. }
  2110. // Find correspondences
  2111. ORBmatcher matcher(0.9,true);
  2112. int nmatches = matcher.SearchForInitialization(mInitialFrame,mCurrentFrame,mvbPrevMatched,mvIniMatches,100);
  2113. // Check if there are enough correspondences
  2114. if(nmatches<100)
  2115. {
  2116. mbReadyToInitializate = false;
  2117. return;
  2118. }
  2119. Sophus::SE3f Tcw;
  2120. vector<bool> vbTriangulated; // Triangulated Correspondences (mvIniMatches)
  2121. if(mpCamera->ReconstructWithTwoViews(mInitialFrame.mvKeysUn,mCurrentFrame.mvKeysUn,mvIniMatches,Tcw,mvIniP3D,vbTriangulated))
  2122. {
  2123. for(size_t i=0, iend=mvIniMatches.size(); i<iend;i++)
  2124. {
  2125. if(mvIniMatches[i]>=0 && !vbTriangulated[i])
  2126. {
  2127. mvIniMatches[i]=-1;
  2128. nmatches--;
  2129. }
  2130. }
  2131. // Set Frame Poses
  2132. mInitialFrame.SetPose(Sophus::SE3f());
  2133. mCurrentFrame.SetPose(Tcw);
  2134. CreateInitialMapMonocular();
  2135. }
  2136. }
  2137. }
  2138. void Tracking::CreateInitialMapMonocular()
  2139. {
  2140. // Create KeyFrames
  2141. KeyFrame* pKFini = new KeyFrame(mInitialFrame,mpAtlas->GetCurrentMap(),mpKeyFrameDB);
  2142. KeyFrame* pKFcur = new KeyFrame(mCurrentFrame,mpAtlas->GetCurrentMap(),mpKeyFrameDB);
  2143. if(mSensor == System::IMU_MONOCULAR)
  2144. pKFini->mpImuPreintegrated = (IMU::Preintegrated*)(NULL);
  2145. pKFini->ComputeBoW();
  2146. pKFcur->ComputeBoW();
  2147. // Insert KFs in the map
  2148. mpAtlas->AddKeyFrame(pKFini);
  2149. mpAtlas->AddKeyFrame(pKFcur);
  2150. for(size_t i=0; i<mvIniMatches.size();i++)
  2151. {
  2152. if(mvIniMatches[i]<0)
  2153. continue;
  2154. //Create MapPoint.
  2155. Eigen::Vector3f worldPos;
  2156. worldPos << mvIniP3D[i].x, mvIniP3D[i].y, mvIniP3D[i].z;
  2157. MapPoint* pMP = new MapPoint(worldPos,pKFcur,mpAtlas->GetCurrentMap());
  2158. pKFini->AddMapPoint(pMP,i);
  2159. pKFcur->AddMapPoint(pMP,mvIniMatches[i]);
  2160. pMP->AddObservation(pKFini,i);
  2161. pMP->AddObservation(pKFcur,mvIniMatches[i]);
  2162. pMP->ComputeDistinctiveDescriptors();
  2163. pMP->UpdateNormalAndDepth();
  2164. //Fill Current Frame structure
  2165. mCurrentFrame.mvpMapPoints[mvIniMatches[i]] = pMP;
  2166. mCurrentFrame.mvbOutlier[mvIniMatches[i]] = false;
  2167. //Add to Map
  2168. mpAtlas->AddMapPoint(pMP);
  2169. }
  2170. // Update Connections
  2171. pKFini->UpdateConnections();
  2172. pKFcur->UpdateConnections();
  2173. std::set<MapPoint*> sMPs;
  2174. sMPs = pKFini->GetMapPoints();
  2175. // Bundle Adjustment
  2176. Verbose::PrintMess("New Map created with " + to_string(mpAtlas->MapPointsInMap()) + " points", Verbose::VERBOSITY_QUIET);
  2177. Optimizer::GlobalBundleAdjustemnt(mpAtlas->GetCurrentMap(),20);
  2178. float medianDepth = pKFini->ComputeSceneMedianDepth(2);
  2179. float invMedianDepth;
  2180. if(mSensor == System::IMU_MONOCULAR)
  2181. invMedianDepth = 4.0f/medianDepth; // 4.0f
  2182. else
  2183. invMedianDepth = 1.0f/medianDepth;
  2184. if(medianDepth<0 || pKFcur->TrackedMapPoints(1)<50) // TODO Check, originally 100 tracks
  2185. {
  2186. Verbose::PrintMess("Wrong initialization, reseting...", Verbose::VERBOSITY_QUIET);
  2187. mpSystem->ResetActiveMap();
  2188. return;
  2189. }
  2190. // Scale initial baseline
  2191. Sophus::SE3f Tc2w = pKFcur->GetPose();
  2192. Tc2w.translation() *= invMedianDepth;
  2193. pKFcur->SetPose(Tc2w);
  2194. // Scale points
  2195. vector<MapPoint*> vpAllMapPoints = pKFini->GetMapPointMatches();
  2196. for(size_t iMP=0; iMP<vpAllMapPoints.size(); iMP++)
  2197. {
  2198. if(vpAllMapPoints[iMP])
  2199. {
  2200. MapPoint* pMP = vpAllMapPoints[iMP];
  2201. pMP->SetWorldPos(pMP->GetWorldPos()*invMedianDepth);
  2202. pMP->UpdateNormalAndDepth();
  2203. }
  2204. }
  2205. if (mSensor == System::IMU_MONOCULAR)
  2206. {
  2207. pKFcur->mPrevKF = pKFini;
  2208. pKFini->mNextKF = pKFcur;
  2209. pKFcur->mpImuPreintegrated = mpImuPreintegratedFromLastKF;
  2210. mpImuPreintegratedFromLastKF = new IMU::Preintegrated(pKFcur->mpImuPreintegrated->GetUpdatedBias(),pKFcur->mImuCalib);
  2211. }
  2212. mpLocalMapper->InsertKeyFrame(pKFini);
  2213. mpLocalMapper->InsertKeyFrame(pKFcur);
  2214. mpLocalMapper->mFirstTs=pKFcur->mTimeStamp;
  2215. mCurrentFrame.SetPose(pKFcur->GetPose());
  2216. mnLastKeyFrameId=mCurrentFrame.mnId;
  2217. mpLastKeyFrame = pKFcur;
  2218. //mnLastRelocFrameId = mInitialFrame.mnId;
  2219. mvpLocalKeyFrames.push_back(pKFcur);
  2220. mvpLocalKeyFrames.push_back(pKFini);
  2221. mvpLocalMapPoints=mpAtlas->GetAllMapPoints();
  2222. mpReferenceKF = pKFcur;
  2223. mCurrentFrame.mpReferenceKF = pKFcur;
  2224. // Compute here initial velocity
  2225. vector<KeyFrame*> vKFs = mpAtlas->GetAllKeyFrames();
  2226. Sophus::SE3f deltaT = vKFs.back()->GetPose() * vKFs.front()->GetPoseInverse();
  2227. mbVelocity = false;
  2228. Eigen::Vector3f phi = deltaT.so3().log();
  2229. double aux = (mCurrentFrame.mTimeStamp-mLastFrame.mTimeStamp)/(mCurrentFrame.mTimeStamp-mInitialFrame.mTimeStamp);
  2230. phi *= aux;
  2231. mLastFrame = Frame(mCurrentFrame);
  2232. mpAtlas->SetReferenceMapPoints(mvpLocalMapPoints);
  2233. mpMapDrawer->SetCurrentCameraPose(pKFcur->GetPose());
  2234. mpAtlas->GetCurrentMap()->mvpKeyFrameOrigins.push_back(pKFini);
  2235. mState=OK;
  2236. initID = pKFcur->mnId;
  2237. }
  2238. void Tracking::CreateMapInAtlas()
  2239. {
  2240. mnLastInitFrameId = mCurrentFrame.mnId;
  2241. mpAtlas->CreateNewMap();
  2242. if (mSensor==System::IMU_STEREO || mSensor == System::IMU_MONOCULAR || mSensor == System::IMU_RGBD)
  2243. mpAtlas->SetInertialSensor();
  2244. mbSetInit=false;
  2245. mnInitialFrameId = mCurrentFrame.mnId+1;
  2246. mState = NO_IMAGES_YET;
  2247. // Restart the variable with information about the last KF
  2248. mbVelocity = false;
  2249. //mnLastRelocFrameId = mnLastInitFrameId; // The last relocation KF_id is the current id, because it is the new starting point for new map
  2250. Verbose::PrintMess("First frame id in map: " + to_string(mnLastInitFrameId+1), Verbose::VERBOSITY_NORMAL);
  2251. mbVO = false; // Init value for know if there are enough MapPoints in the last KF
  2252. if(mSensor == System::MONOCULAR || mSensor == System::IMU_MONOCULAR)
  2253. {
  2254. mbReadyToInitializate = false;
  2255. }
  2256. if((mSensor == System::IMU_MONOCULAR || mSensor == System::IMU_STEREO || mSensor == System::IMU_RGBD) && mpImuPreintegratedFromLastKF)
  2257. {
  2258. delete mpImuPreintegratedFromLastKF;
  2259. mpImuPreintegratedFromLastKF = new IMU::Preintegrated(IMU::Bias(),*mpImuCalib);
  2260. }
  2261. if(mpLastKeyFrame)
  2262. mpLastKeyFrame = static_cast<KeyFrame*>(NULL);
  2263. if(mpReferenceKF)
  2264. mpReferenceKF = static_cast<KeyFrame*>(NULL);
  2265. mLastFrame = Frame();
  2266. mCurrentFrame = Frame();
  2267. mvIniMatches.clear();
  2268. mbCreatedMap = true;
  2269. }
  2270. void Tracking::CheckReplacedInLastFrame()
  2271. {
  2272. for(int i =0; i<mLastFrame.N; i++)
  2273. {
  2274. MapPoint* pMP = mLastFrame.mvpMapPoints[i];
  2275. if(pMP)
  2276. {
  2277. MapPoint* pRep = pMP->GetReplaced();
  2278. if(pRep)
  2279. {
  2280. mLastFrame.mvpMapPoints[i] = pRep;
  2281. }
  2282. }
  2283. }
  2284. }
  2285. bool Tracking::TrackReferenceKeyFrame()
  2286. {
  2287. // Compute Bag of Words vector
  2288. mCurrentFrame.ComputeBoW();
  2289. // We perform first an ORB matching with the reference keyframe
  2290. // If enough matches are found we setup a PnP solver
  2291. ORBmatcher matcher(0.7,true);
  2292. vector<MapPoint*> vpMapPointMatches;
  2293. int nmatches = matcher.SearchByBoW(mpReferenceKF,mCurrentFrame,vpMapPointMatches);
  2294. if(nmatches<15)
  2295. {
  2296. cout << "TRACK_REF_KF: Less than 15 matches!!\n";
  2297. return false;
  2298. }
  2299. mCurrentFrame.mvpMapPoints = vpMapPointMatches;
  2300. mCurrentFrame.SetPose(mLastFrame.GetPose());
  2301. //mCurrentFrame.PrintPointDistribution();
  2302. // cout << " TrackReferenceKeyFrame mLastFrame.mTcw: " << mLastFrame.mTcw << endl;
  2303. Optimizer::PoseOptimization(&mCurrentFrame);
  2304. // Discard outliers
  2305. int nmatchesMap = 0;
  2306. for(int i =0; i<mCurrentFrame.N; i++)
  2307. {
  2308. //if(i >= mCurrentFrame.Nleft) break;
  2309. if(mCurrentFrame.mvpMapPoints[i])
  2310. {
  2311. if(mCurrentFrame.mvbOutlier[i])
  2312. {
  2313. MapPoint* pMP = mCurrentFrame.mvpMapPoints[i];
  2314. mCurrentFrame.mvpMapPoints[i]=static_cast<MapPoint*>(NULL);
  2315. mCurrentFrame.mvbOutlier[i]=false;
  2316. if(i < mCurrentFrame.Nleft){
  2317. pMP->mbTrackInView = false;
  2318. }
  2319. else{
  2320. pMP->mbTrackInViewR = false;
  2321. }
  2322. pMP->mbTrackInView = false;
  2323. pMP->mnLastFrameSeen = mCurrentFrame.mnId;
  2324. nmatches--;
  2325. }
  2326. else if(mCurrentFrame.mvpMapPoints[i]->Observations()>0)
  2327. nmatchesMap++;
  2328. }
  2329. }
  2330. if (mSensor == System::IMU_MONOCULAR || mSensor == System::IMU_STEREO || mSensor == System::IMU_RGBD)
  2331. return true;
  2332. else
  2333. return nmatchesMap>=10;
  2334. }
  2335. void Tracking::UpdateLastFrame()
  2336. {
  2337. // Update pose according to reference keyframe
  2338. KeyFrame* pRef = mLastFrame.mpReferenceKF;
  2339. Sophus::SE3f Tlr = mlRelativeFramePoses.back();
  2340. mLastFrame.SetPose(Tlr * pRef->GetPose());
  2341. if(mnLastKeyFrameId==mLastFrame.mnId || mSensor==System::MONOCULAR || mSensor==System::IMU_MONOCULAR || !mbOnlyTracking)
  2342. return;
  2343. // Create "visual odometry" MapPoints
  2344. // We sort points according to their measured depth by the stereo/RGB-D sensor
  2345. vector<pair<float,int> > vDepthIdx;
  2346. const int Nfeat = mLastFrame.Nleft == -1? mLastFrame.N : mLastFrame.Nleft;
  2347. vDepthIdx.reserve(Nfeat);
  2348. for(int i=0; i<Nfeat;i++)
  2349. {
  2350. float z = mLastFrame.mvDepth[i];
  2351. if(z>0)
  2352. {
  2353. vDepthIdx.push_back(make_pair(z,i));
  2354. }
  2355. }
  2356. if(vDepthIdx.empty())
  2357. return;
  2358. sort(vDepthIdx.begin(),vDepthIdx.end());
  2359. // We insert all close points (depth<mThDepth)
  2360. // If less than 100 close points, we insert the 100 closest ones.
  2361. int nPoints = 0;
  2362. for(size_t j=0; j<vDepthIdx.size();j++)
  2363. {
  2364. int i = vDepthIdx[j].second;
  2365. bool bCreateNew = false;
  2366. MapPoint* pMP = mLastFrame.mvpMapPoints[i];
  2367. if(!pMP)
  2368. bCreateNew = true;
  2369. else if(pMP->Observations()<1)
  2370. bCreateNew = true;
  2371. if(bCreateNew)
  2372. {
  2373. Eigen::Vector3f x3D;
  2374. if(mLastFrame.Nleft == -1){
  2375. mLastFrame.UnprojectStereo(i, x3D);
  2376. }
  2377. else{
  2378. x3D = mLastFrame.UnprojectStereoFishEye(i);
  2379. }
  2380. MapPoint* pNewMP = new MapPoint(x3D,mpAtlas->GetCurrentMap(),&mLastFrame,i);
  2381. mLastFrame.mvpMapPoints[i]=pNewMP;
  2382. mlpTemporalPoints.push_back(pNewMP);
  2383. nPoints++;
  2384. }
  2385. else
  2386. {
  2387. nPoints++;
  2388. }
  2389. if(vDepthIdx[j].first>mThDepth && nPoints>100)
  2390. break;
  2391. }
  2392. }
  2393. bool Tracking::TrackWithMotionModel()
  2394. {
  2395. ORBmatcher matcher(0.9,true);
  2396. // Update last frame pose according to its reference keyframe
  2397. // Create "visual odometry" points if in Localization Mode
  2398. UpdateLastFrame();
  2399. if (mpAtlas->isImuInitialized() && (mCurrentFrame.mnId>mnLastRelocFrameId+mnFramesToResetIMU))
  2400. {
  2401. // Predict state with IMU if it is initialized and it doesnt need reset
  2402. PredictStateIMU();
  2403. return true;
  2404. }
  2405. else
  2406. {
  2407. mCurrentFrame.SetPose(mVelocity * mLastFrame.GetPose());
  2408. }
  2409. fill(mCurrentFrame.mvpMapPoints.begin(),mCurrentFrame.mvpMapPoints.end(),static_cast<MapPoint*>(NULL));
  2410. // Project points seen in previous frame
  2411. int th;
  2412. if(mSensor==System::STEREO)
  2413. th=7;
  2414. else
  2415. th=15;
  2416. int nmatches = matcher.SearchByProjection(mCurrentFrame,mLastFrame,th,mSensor==System::MONOCULAR || mSensor==System::IMU_MONOCULAR);
  2417. // If few matches, uses a wider window search
  2418. if(nmatches<20)
  2419. {
  2420. Verbose::PrintMess("Not enough matches, wider window search!!", Verbose::VERBOSITY_NORMAL);
  2421. fill(mCurrentFrame.mvpMapPoints.begin(),mCurrentFrame.mvpMapPoints.end(),static_cast<MapPoint*>(NULL));
  2422. nmatches = matcher.SearchByProjection(mCurrentFrame,mLastFrame,2*th,mSensor==System::MONOCULAR || mSensor==System::IMU_MONOCULAR);
  2423. Verbose::PrintMess("Matches with wider search: " + to_string(nmatches), Verbose::VERBOSITY_NORMAL);
  2424. }
  2425. if(nmatches<20)
  2426. {
  2427. Verbose::PrintMess("Not enough matches!!", Verbose::VERBOSITY_NORMAL);
  2428. if (mSensor == System::IMU_MONOCULAR || mSensor == System::IMU_STEREO || mSensor == System::IMU_RGBD)
  2429. return true;
  2430. else
  2431. return false;
  2432. }
  2433. // Optimize frame pose with all matches
  2434. Optimizer::PoseOptimization(&mCurrentFrame);
  2435. // Discard outliers
  2436. int nmatchesMap = 0;
  2437. for(int i =0; i<mCurrentFrame.N; i++)
  2438. {
  2439. if(mCurrentFrame.mvpMapPoints[i])
  2440. {
  2441. if(mCurrentFrame.mvbOutlier[i])
  2442. {
  2443. MapPoint* pMP = mCurrentFrame.mvpMapPoints[i];
  2444. mCurrentFrame.mvpMapPoints[i]=static_cast<MapPoint*>(NULL);
  2445. mCurrentFrame.mvbOutlier[i]=false;
  2446. if(i < mCurrentFrame.Nleft){
  2447. pMP->mbTrackInView = false;
  2448. }
  2449. else{
  2450. pMP->mbTrackInViewR = false;
  2451. }
  2452. pMP->mnLastFrameSeen = mCurrentFrame.mnId;
  2453. nmatches--;
  2454. }
  2455. else if(mCurrentFrame.mvpMapPoints[i]->Observations()>0)
  2456. nmatchesMap++;
  2457. }
  2458. }
  2459. if(mbOnlyTracking)
  2460. {
  2461. mbVO = nmatchesMap<10;
  2462. return nmatches>20;
  2463. }
  2464. if (mSensor == System::IMU_MONOCULAR || mSensor == System::IMU_STEREO || mSensor == System::IMU_RGBD)
  2465. return true;
  2466. else
  2467. return nmatchesMap>=10;
  2468. }
  2469. bool Tracking::TrackLocalMap()
  2470. {
  2471. // We have an estimation of the camera pose and some map points tracked in the frame.
  2472. // We retrieve the local map and try to find matches to points in the local map.
  2473. mTrackedFr++;
  2474. UpdateLocalMap();
  2475. SearchLocalPoints();
  2476. // TOO check outliers before PO
  2477. int aux1 = 0, aux2=0;
  2478. for(int i=0; i<mCurrentFrame.N; i++)
  2479. if( mCurrentFrame.mvpMapPoints[i])
  2480. {
  2481. aux1++;
  2482. if(mCurrentFrame.mvbOutlier[i])
  2483. aux2++;
  2484. }
  2485. int inliers;
  2486. if (!mpAtlas->isImuInitialized())
  2487. Optimizer::PoseOptimization(&mCurrentFrame);
  2488. else
  2489. {
  2490. if(mCurrentFrame.mnId<=mnLastRelocFrameId+mnFramesToResetIMU)
  2491. {
  2492. Verbose::PrintMess("TLM: PoseOptimization ", Verbose::VERBOSITY_DEBUG);
  2493. Optimizer::PoseOptimization(&mCurrentFrame);
  2494. }
  2495. else
  2496. {
  2497. // if(!mbMapUpdated && mState == OK) // && (mnMatchesInliers>30))
  2498. if(!mbMapUpdated) // && (mnMatchesInliers>30))
  2499. {
  2500. Verbose::PrintMess("TLM: PoseInertialOptimizationLastFrame ", Verbose::VERBOSITY_DEBUG);
  2501. inliers = Optimizer::PoseInertialOptimizationLastFrame(&mCurrentFrame); // , !mpLastKeyFrame->GetMap()->GetIniertialBA1());
  2502. }
  2503. else
  2504. {
  2505. Verbose::PrintMess("TLM: PoseInertialOptimizationLastKeyFrame ", Verbose::VERBOSITY_DEBUG);
  2506. inliers = Optimizer::PoseInertialOptimizationLastKeyFrame(&mCurrentFrame); // , !mpLastKeyFrame->GetMap()->GetIniertialBA1());
  2507. }
  2508. }
  2509. }
  2510. aux1 = 0, aux2 = 0;
  2511. for(int i=0; i<mCurrentFrame.N; i++)
  2512. if( mCurrentFrame.mvpMapPoints[i])
  2513. {
  2514. aux1++;
  2515. if(mCurrentFrame.mvbOutlier[i])
  2516. aux2++;
  2517. }
  2518. mnMatchesInliers = 0;
  2519. // Update MapPoints Statistics
  2520. for(int i=0; i<mCurrentFrame.N; i++)
  2521. {
  2522. if(mCurrentFrame.mvpMapPoints[i])
  2523. {
  2524. if(!mCurrentFrame.mvbOutlier[i])
  2525. {
  2526. mCurrentFrame.mvpMapPoints[i]->IncreaseFound();
  2527. if(!mbOnlyTracking)
  2528. {
  2529. if(mCurrentFrame.mvpMapPoints[i]->Observations()>0)
  2530. mnMatchesInliers++;
  2531. }
  2532. else
  2533. mnMatchesInliers++;
  2534. }
  2535. else if(mSensor==System::STEREO)
  2536. mCurrentFrame.mvpMapPoints[i] = static_cast<MapPoint*>(NULL);
  2537. }
  2538. }
  2539. // Decide if the tracking was succesful
  2540. // More restrictive if there was a relocalization recently
  2541. mpLocalMapper->mnMatchesInliers=mnMatchesInliers;
  2542. if(mCurrentFrame.mnId<mnLastRelocFrameId+mMaxFrames && mnMatchesInliers<50)
  2543. return false;
  2544. if((mnMatchesInliers>10)&&(mState==RECENTLY_LOST))
  2545. return true;
  2546. if (mSensor == System::IMU_MONOCULAR)
  2547. {
  2548. if((mnMatchesInliers<15 && mpAtlas->isImuInitialized())||(mnMatchesInliers<50 && !mpAtlas->isImuInitialized()))
  2549. {
  2550. return false;
  2551. }
  2552. else
  2553. return true;
  2554. }
  2555. else if (mSensor == System::IMU_STEREO || mSensor == System::IMU_RGBD)
  2556. {
  2557. if(mnMatchesInliers<15)
  2558. {
  2559. return false;
  2560. }
  2561. else
  2562. return true;
  2563. }
  2564. else
  2565. {
  2566. if(mnMatchesInliers<30)
  2567. return false;
  2568. else
  2569. return true;
  2570. }
  2571. }
  2572. bool Tracking::NeedNewKeyFrame()
  2573. {
  2574. if((mSensor == System::IMU_MONOCULAR || mSensor == System::IMU_STEREO || mSensor == System::IMU_RGBD) && !mpAtlas->GetCurrentMap()->isImuInitialized())
  2575. {
  2576. if (mSensor == System::IMU_MONOCULAR && (mCurrentFrame.mTimeStamp-mpLastKeyFrame->mTimeStamp)>=0.25)
  2577. return true;
  2578. else if ((mSensor == System::IMU_STEREO || mSensor == System::IMU_RGBD) && (mCurrentFrame.mTimeStamp-mpLastKeyFrame->mTimeStamp)>=0.25)
  2579. return true;
  2580. else
  2581. return false;
  2582. }
  2583. if(mbOnlyTracking)
  2584. return false;
  2585. // If Local Mapping is freezed by a Loop Closure do not insert keyframes
  2586. if(mpLocalMapper->isStopped() || mpLocalMapper->stopRequested()) {
  2587. /*if(mSensor == System::MONOCULAR)
  2588. {
  2589. std::cout << "NeedNewKeyFrame: localmap stopped" << std::endl;
  2590. }*/
  2591. return false;
  2592. }
  2593. const int nKFs = mpAtlas->KeyFramesInMap();
  2594. // Do not insert keyframes if not enough frames have passed from last relocalisation
  2595. if(mCurrentFrame.mnId<mnLastRelocFrameId+mMaxFrames && nKFs>mMaxFrames)
  2596. {
  2597. return false;
  2598. }
  2599. // Tracked MapPoints in the reference keyframe
  2600. int nMinObs = 3;
  2601. if(nKFs<=2)
  2602. nMinObs=2;
  2603. int nRefMatches = mpReferenceKF->TrackedMapPoints(nMinObs);
  2604. // Local Mapping accept keyframes?
  2605. bool bLocalMappingIdle = mpLocalMapper->AcceptKeyFrames();
  2606. // Check how many "close" points are being tracked and how many could be potentially created.
  2607. int nNonTrackedClose = 0;
  2608. int nTrackedClose= 0;
  2609. if(mSensor!=System::MONOCULAR && mSensor!=System::IMU_MONOCULAR)
  2610. {
  2611. int N = (mCurrentFrame.Nleft == -1) ? mCurrentFrame.N : mCurrentFrame.Nleft;
  2612. for(int i =0; i<N; i++)
  2613. {
  2614. if(mCurrentFrame.mvDepth[i]>0 && mCurrentFrame.mvDepth[i]<mThDepth)
  2615. {
  2616. if(mCurrentFrame.mvpMapPoints[i] && !mCurrentFrame.mvbOutlier[i])
  2617. nTrackedClose++;
  2618. else
  2619. nNonTrackedClose++;
  2620. }
  2621. }
  2622. //Verbose::PrintMess("[NEEDNEWKF]-> closed points: " + to_string(nTrackedClose) + "; non tracked closed points: " + to_string(nNonTrackedClose), Verbose::VERBOSITY_NORMAL);// Verbose::VERBOSITY_DEBUG);
  2623. }
  2624. bool bNeedToInsertClose;
  2625. bNeedToInsertClose = (nTrackedClose<100) && (nNonTrackedClose>70);
  2626. // Thresholds
  2627. float thRefRatio = 0.75f;
  2628. if(nKFs<2)
  2629. thRefRatio = 0.4f;
  2630. /*int nClosedPoints = nTrackedClose + nNonTrackedClose;
  2631. const int thStereoClosedPoints = 15;
  2632. if(nClosedPoints < thStereoClosedPoints && (mSensor==System::STEREO || mSensor==System::IMU_STEREO))
  2633. {
  2634. //Pseudo-monocular, there are not enough close points to be confident about the stereo observations.
  2635. thRefRatio = 0.9f;
  2636. }*/
  2637. if(mSensor==System::MONOCULAR)
  2638. thRefRatio = 0.9f;
  2639. if(mpCamera2) thRefRatio = 0.75f;
  2640. if(mSensor==System::IMU_MONOCULAR)
  2641. {
  2642. if(mnMatchesInliers>350) // Points tracked from the local map
  2643. thRefRatio = 0.75f;
  2644. else
  2645. thRefRatio = 0.90f;
  2646. }
  2647. // Condition 1a: More than "MaxFrames" have passed from last keyframe insertion
  2648. const bool c1a = mCurrentFrame.mnId>=mnLastKeyFrameId+mMaxFrames;
  2649. // Condition 1b: More than "MinFrames" have passed and Local Mapping is idle
  2650. const bool c1b = ((mCurrentFrame.mnId>=mnLastKeyFrameId+mMinFrames) && bLocalMappingIdle); //mpLocalMapper->KeyframesInQueue() < 2);
  2651. //Condition 1c: tracking is weak
  2652. const bool c1c = mSensor!=System::MONOCULAR && mSensor!=System::IMU_MONOCULAR && mSensor!=System::IMU_STEREO && mSensor!=System::IMU_RGBD && (mnMatchesInliers<nRefMatches*0.25 || bNeedToInsertClose) ;
  2653. // Condition 2: Few tracked points compared to reference keyframe. Lots of visual odometry compared to map matches.
  2654. const bool c2 = (((mnMatchesInliers<nRefMatches*thRefRatio || bNeedToInsertClose)) && mnMatchesInliers>15);
  2655. //std::cout << "NeedNewKF: c1a=" << c1a << "; c1b=" << c1b << "; c1c=" << c1c << "; c2=" << c2 << std::endl;
  2656. // Temporal condition for Inertial cases
  2657. bool c3 = false;
  2658. if(mpLastKeyFrame)
  2659. {
  2660. if (mSensor==System::IMU_MONOCULAR)
  2661. {
  2662. if ((mCurrentFrame.mTimeStamp-mpLastKeyFrame->mTimeStamp)>=0.5)
  2663. c3 = true;
  2664. }
  2665. else if (mSensor==System::IMU_STEREO || mSensor == System::IMU_RGBD)
  2666. {
  2667. if ((mCurrentFrame.mTimeStamp-mpLastKeyFrame->mTimeStamp)>=0.5)
  2668. c3 = true;
  2669. }
  2670. }
  2671. bool c4 = false;
  2672. 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)))
  2673. c4=true;
  2674. else
  2675. c4=false;
  2676. if(((c1a||c1b||c1c) && c2)||c3 ||c4)
  2677. {
  2678. // If the mapping accepts keyframes, insert keyframe.
  2679. // Otherwise send a signal to interrupt BA
  2680. if(bLocalMappingIdle || mpLocalMapper->IsInitializing())
  2681. {
  2682. return true;
  2683. }
  2684. else
  2685. {
  2686. mpLocalMapper->InterruptBA();
  2687. if(mSensor!=System::MONOCULAR && mSensor!=System::IMU_MONOCULAR)
  2688. {
  2689. if(mpLocalMapper->KeyframesInQueue()<3)
  2690. return true;
  2691. else
  2692. return false;
  2693. }
  2694. else
  2695. {
  2696. //std::cout << "NeedNewKeyFrame: localmap is busy" << std::endl;
  2697. return false;
  2698. }
  2699. }
  2700. }
  2701. else
  2702. return false;
  2703. }
  2704. void Tracking::CreateNewKeyFrame()
  2705. {
  2706. if(mpLocalMapper->IsInitializing() && !mpAtlas->isImuInitialized())
  2707. return;
  2708. if(!mpLocalMapper->SetNotStop(true))
  2709. return;
  2710. KeyFrame* pKF = new KeyFrame(mCurrentFrame,mpAtlas->GetCurrentMap(),mpKeyFrameDB);
  2711. if(mpAtlas->isImuInitialized()) // || mpLocalMapper->IsInitializing())
  2712. pKF->bImu = true;
  2713. pKF->SetNewBias(mCurrentFrame.mImuBias);
  2714. mpReferenceKF = pKF;
  2715. mCurrentFrame.mpReferenceKF = pKF;
  2716. if(mpLastKeyFrame)
  2717. {
  2718. pKF->mPrevKF = mpLastKeyFrame;
  2719. mpLastKeyFrame->mNextKF = pKF;
  2720. }
  2721. else
  2722. Verbose::PrintMess("No last KF in KF creation!!", Verbose::VERBOSITY_NORMAL);
  2723. // Reset preintegration from last KF (Create new object)
  2724. if (mSensor == System::IMU_MONOCULAR || mSensor == System::IMU_STEREO || mSensor == System::IMU_RGBD)
  2725. {
  2726. mpImuPreintegratedFromLastKF = new IMU::Preintegrated(pKF->GetImuBias(),pKF->mImuCalib);
  2727. }
  2728. if(mSensor!=System::MONOCULAR && mSensor != System::IMU_MONOCULAR) // TODO check if incluide imu_stereo
  2729. {
  2730. mCurrentFrame.UpdatePoseMatrices();
  2731. // cout << "create new MPs" << endl;
  2732. // We sort points by the measured depth by the stereo/RGBD sensor.
  2733. // We create all those MapPoints whose depth < mThDepth.
  2734. // If there are less than 100 close points we create the 100 closest.
  2735. int maxPoint = 100;
  2736. if(mSensor == System::IMU_STEREO || mSensor == System::IMU_RGBD)
  2737. maxPoint = 100;
  2738. vector<pair<float,int> > vDepthIdx;
  2739. int N = (mCurrentFrame.Nleft != -1) ? mCurrentFrame.Nleft : mCurrentFrame.N;
  2740. vDepthIdx.reserve(mCurrentFrame.N);
  2741. for(int i=0; i<N; i++)
  2742. {
  2743. float z = mCurrentFrame.mvDepth[i];
  2744. if(z>0)
  2745. {
  2746. vDepthIdx.push_back(make_pair(z,i));
  2747. }
  2748. }
  2749. if(!vDepthIdx.empty())
  2750. {
  2751. sort(vDepthIdx.begin(),vDepthIdx.end());
  2752. int nPoints = 0;
  2753. for(size_t j=0; j<vDepthIdx.size();j++)
  2754. {
  2755. int i = vDepthIdx[j].second;
  2756. bool bCreateNew = false;
  2757. MapPoint* pMP = mCurrentFrame.mvpMapPoints[i];
  2758. if(!pMP)
  2759. bCreateNew = true;
  2760. else if(pMP->Observations()<1)
  2761. {
  2762. bCreateNew = true;
  2763. mCurrentFrame.mvpMapPoints[i] = static_cast<MapPoint*>(NULL);
  2764. }
  2765. if(bCreateNew)
  2766. {
  2767. Eigen::Vector3f x3D;
  2768. if(mCurrentFrame.Nleft == -1){
  2769. mCurrentFrame.UnprojectStereo(i, x3D);
  2770. }
  2771. else{
  2772. x3D = mCurrentFrame.UnprojectStereoFishEye(i);
  2773. }
  2774. MapPoint* pNewMP = new MapPoint(x3D,pKF,mpAtlas->GetCurrentMap());
  2775. pNewMP->AddObservation(pKF,i);
  2776. //Check if it is a stereo observation in order to not
  2777. //duplicate mappoints
  2778. if(mCurrentFrame.Nleft != -1 && mCurrentFrame.mvLeftToRightMatch[i] >= 0){
  2779. mCurrentFrame.mvpMapPoints[mCurrentFrame.Nleft + mCurrentFrame.mvLeftToRightMatch[i]]=pNewMP;
  2780. pNewMP->AddObservation(pKF,mCurrentFrame.Nleft + mCurrentFrame.mvLeftToRightMatch[i]);
  2781. pKF->AddMapPoint(pNewMP,mCurrentFrame.Nleft + mCurrentFrame.mvLeftToRightMatch[i]);
  2782. }
  2783. pKF->AddMapPoint(pNewMP,i);
  2784. pNewMP->ComputeDistinctiveDescriptors();
  2785. pNewMP->UpdateNormalAndDepth();
  2786. mpAtlas->AddMapPoint(pNewMP);
  2787. mCurrentFrame.mvpMapPoints[i]=pNewMP;
  2788. nPoints++;
  2789. }
  2790. else
  2791. {
  2792. nPoints++;
  2793. }
  2794. if(vDepthIdx[j].first>mThDepth && nPoints>maxPoint)
  2795. {
  2796. break;
  2797. }
  2798. }
  2799. //Verbose::PrintMess("new mps for stereo KF: " + to_string(nPoints), Verbose::VERBOSITY_NORMAL);
  2800. }
  2801. }
  2802. mpLocalMapper->InsertKeyFrame(pKF);
  2803. mpLocalMapper->SetNotStop(false);
  2804. mnLastKeyFrameId = mCurrentFrame.mnId;
  2805. mpLastKeyFrame = pKF;
  2806. }
  2807. void Tracking::SearchLocalPoints()
  2808. {
  2809. // Do not search map points already matched
  2810. for(vector<MapPoint*>::iterator vit=mCurrentFrame.mvpMapPoints.begin(), vend=mCurrentFrame.mvpMapPoints.end(); vit!=vend; vit++)
  2811. {
  2812. MapPoint* pMP = *vit;
  2813. if(pMP)
  2814. {
  2815. if(pMP->isBad())
  2816. {
  2817. *vit = static_cast<MapPoint*>(NULL);
  2818. }
  2819. else
  2820. {
  2821. pMP->IncreaseVisible();
  2822. pMP->mnLastFrameSeen = mCurrentFrame.mnId;
  2823. pMP->mbTrackInView = false;
  2824. pMP->mbTrackInViewR = false;
  2825. }
  2826. }
  2827. }
  2828. int nToMatch=0;
  2829. // Project points in frame and check its visibility
  2830. for(vector<MapPoint*>::iterator vit=mvpLocalMapPoints.begin(), vend=mvpLocalMapPoints.end(); vit!=vend; vit++)
  2831. {
  2832. MapPoint* pMP = *vit;
  2833. if(pMP->mnLastFrameSeen == mCurrentFrame.mnId)
  2834. continue;
  2835. if(pMP->isBad())
  2836. continue;
  2837. // Project (this fills MapPoint variables for matching)
  2838. if(mCurrentFrame.isInFrustum(pMP,0.5))
  2839. {
  2840. pMP->IncreaseVisible();
  2841. nToMatch++;
  2842. }
  2843. if(pMP->mbTrackInView)
  2844. {
  2845. mCurrentFrame.mmProjectPoints[pMP->mnId] = cv::Point2f(pMP->mTrackProjX, pMP->mTrackProjY);
  2846. }
  2847. }
  2848. if(nToMatch>0)
  2849. {
  2850. ORBmatcher matcher(0.8);
  2851. int th = 1;
  2852. if(mSensor==System::RGBD || mSensor==System::IMU_RGBD)
  2853. th=3;
  2854. if(mpAtlas->isImuInitialized())
  2855. {
  2856. if(mpAtlas->GetCurrentMap()->GetIniertialBA2())
  2857. th=2;
  2858. else
  2859. th=6;
  2860. }
  2861. else if(!mpAtlas->isImuInitialized() && (mSensor==System::IMU_MONOCULAR || mSensor==System::IMU_STEREO || mSensor == System::IMU_RGBD))
  2862. {
  2863. th=10;
  2864. }
  2865. // If the camera has been relocalised recently, perform a coarser search
  2866. if(mCurrentFrame.mnId<mnLastRelocFrameId+2)
  2867. th=5;
  2868. if(mState==LOST || mState==RECENTLY_LOST) // Lost for less than 1 second
  2869. th=15; // 15
  2870. int matches = matcher.SearchByProjection(mCurrentFrame, mvpLocalMapPoints, th, mpLocalMapper->mbFarPoints, mpLocalMapper->mThFarPoints);
  2871. }
  2872. }
  2873. void Tracking::UpdateLocalMap()
  2874. {
  2875. // This is for visualization
  2876. mpAtlas->SetReferenceMapPoints(mvpLocalMapPoints);
  2877. // Update
  2878. UpdateLocalKeyFrames();
  2879. UpdateLocalPoints();
  2880. }
  2881. void Tracking::UpdateLocalPoints()
  2882. {
  2883. mvpLocalMapPoints.clear();
  2884. int count_pts = 0;
  2885. for(vector<KeyFrame*>::const_reverse_iterator itKF=mvpLocalKeyFrames.rbegin(), itEndKF=mvpLocalKeyFrames.rend(); itKF!=itEndKF; ++itKF)
  2886. {
  2887. KeyFrame* pKF = *itKF;
  2888. const vector<MapPoint*> vpMPs = pKF->GetMapPointMatches();
  2889. for(vector<MapPoint*>::const_iterator itMP=vpMPs.begin(), itEndMP=vpMPs.end(); itMP!=itEndMP; itMP++)
  2890. {
  2891. MapPoint* pMP = *itMP;
  2892. if(!pMP)
  2893. continue;
  2894. if(pMP->mnTrackReferenceForFrame==mCurrentFrame.mnId)
  2895. continue;
  2896. if(!pMP->isBad())
  2897. {
  2898. count_pts++;
  2899. mvpLocalMapPoints.push_back(pMP);
  2900. pMP->mnTrackReferenceForFrame=mCurrentFrame.mnId;
  2901. }
  2902. }
  2903. }
  2904. }
  2905. void Tracking::UpdateLocalKeyFrames()
  2906. {
  2907. // Each map point vote for the keyframes in which it has been observed
  2908. map<KeyFrame*,int> keyframeCounter;
  2909. if(!mpAtlas->isImuInitialized() || (mCurrentFrame.mnId<mnLastRelocFrameId+2))
  2910. {
  2911. for(int i=0; i<mCurrentFrame.N; i++)
  2912. {
  2913. MapPoint* pMP = mCurrentFrame.mvpMapPoints[i];
  2914. if(pMP)
  2915. {
  2916. if(!pMP->isBad())
  2917. {
  2918. const map<KeyFrame*,tuple<int,int>> observations = pMP->GetObservations();
  2919. for(map<KeyFrame*,tuple<int,int>>::const_iterator it=observations.begin(), itend=observations.end(); it!=itend; it++)
  2920. keyframeCounter[it->first]++;
  2921. }
  2922. else
  2923. {
  2924. mCurrentFrame.mvpMapPoints[i]=NULL;
  2925. }
  2926. }
  2927. }
  2928. }
  2929. else
  2930. {
  2931. for(int i=0; i<mLastFrame.N; i++)
  2932. {
  2933. // Using lastframe since current frame has not matches yet
  2934. if(mLastFrame.mvpMapPoints[i])
  2935. {
  2936. MapPoint* pMP = mLastFrame.mvpMapPoints[i];
  2937. if(!pMP)
  2938. continue;
  2939. if(!pMP->isBad())
  2940. {
  2941. const map<KeyFrame*,tuple<int,int>> observations = pMP->GetObservations();
  2942. for(map<KeyFrame*,tuple<int,int>>::const_iterator it=observations.begin(), itend=observations.end(); it!=itend; it++)
  2943. keyframeCounter[it->first]++;
  2944. }
  2945. else
  2946. {
  2947. // MODIFICATION
  2948. mLastFrame.mvpMapPoints[i]=NULL;
  2949. }
  2950. }
  2951. }
  2952. }
  2953. int max=0;
  2954. KeyFrame* pKFmax= static_cast<KeyFrame*>(NULL);
  2955. mvpLocalKeyFrames.clear();
  2956. mvpLocalKeyFrames.reserve(3*keyframeCounter.size());
  2957. // All keyframes that observe a map point are included in the local map. Also check which keyframe shares most points
  2958. for(map<KeyFrame*,int>::const_iterator it=keyframeCounter.begin(), itEnd=keyframeCounter.end(); it!=itEnd; it++)
  2959. {
  2960. KeyFrame* pKF = it->first;
  2961. if(pKF->isBad())
  2962. continue;
  2963. if(it->second>max)
  2964. {
  2965. max=it->second;
  2966. pKFmax=pKF;
  2967. }
  2968. mvpLocalKeyFrames.push_back(pKF);
  2969. pKF->mnTrackReferenceForFrame = mCurrentFrame.mnId;
  2970. }
  2971. // Include also some not-already-included keyframes that are neighbors to already-included keyframes
  2972. for(vector<KeyFrame*>::const_iterator itKF=mvpLocalKeyFrames.begin(), itEndKF=mvpLocalKeyFrames.end(); itKF!=itEndKF; itKF++)
  2973. {
  2974. // Limit the number of keyframes
  2975. if(mvpLocalKeyFrames.size()>80) // 80
  2976. break;
  2977. KeyFrame* pKF = *itKF;
  2978. const vector<KeyFrame*> vNeighs = pKF->GetBestCovisibilityKeyFrames(10);
  2979. for(vector<KeyFrame*>::const_iterator itNeighKF=vNeighs.begin(), itEndNeighKF=vNeighs.end(); itNeighKF!=itEndNeighKF; itNeighKF++)
  2980. {
  2981. KeyFrame* pNeighKF = *itNeighKF;
  2982. if(!pNeighKF->isBad())
  2983. {
  2984. if(pNeighKF->mnTrackReferenceForFrame!=mCurrentFrame.mnId)
  2985. {
  2986. mvpLocalKeyFrames.push_back(pNeighKF);
  2987. pNeighKF->mnTrackReferenceForFrame=mCurrentFrame.mnId;
  2988. break;
  2989. }
  2990. }
  2991. }
  2992. const set<KeyFrame*> spChilds = pKF->GetChilds();
  2993. for(set<KeyFrame*>::const_iterator sit=spChilds.begin(), send=spChilds.end(); sit!=send; sit++)
  2994. {
  2995. KeyFrame* pChildKF = *sit;
  2996. if(!pChildKF->isBad())
  2997. {
  2998. if(pChildKF->mnTrackReferenceForFrame!=mCurrentFrame.mnId)
  2999. {
  3000. mvpLocalKeyFrames.push_back(pChildKF);
  3001. pChildKF->mnTrackReferenceForFrame=mCurrentFrame.mnId;
  3002. break;
  3003. }
  3004. }
  3005. }
  3006. KeyFrame* pParent = pKF->GetParent();
  3007. if(pParent)
  3008. {
  3009. if(pParent->mnTrackReferenceForFrame!=mCurrentFrame.mnId)
  3010. {
  3011. mvpLocalKeyFrames.push_back(pParent);
  3012. pParent->mnTrackReferenceForFrame=mCurrentFrame.mnId;
  3013. break;
  3014. }
  3015. }
  3016. }
  3017. // Add 10 last temporal KFs (mainly for IMU)
  3018. if((mSensor == System::IMU_MONOCULAR || mSensor == System::IMU_STEREO || mSensor == System::IMU_RGBD) &&mvpLocalKeyFrames.size()<80)
  3019. {
  3020. KeyFrame* tempKeyFrame = mCurrentFrame.mpLastKeyFrame;
  3021. const int Nd = 20;
  3022. for(int i=0; i<Nd; i++){
  3023. if (!tempKeyFrame)
  3024. break;
  3025. if(tempKeyFrame->mnTrackReferenceForFrame!=mCurrentFrame.mnId)
  3026. {
  3027. mvpLocalKeyFrames.push_back(tempKeyFrame);
  3028. tempKeyFrame->mnTrackReferenceForFrame=mCurrentFrame.mnId;
  3029. tempKeyFrame=tempKeyFrame->mPrevKF;
  3030. }
  3031. }
  3032. }
  3033. if(pKFmax)
  3034. {
  3035. mpReferenceKF = pKFmax;
  3036. mCurrentFrame.mpReferenceKF = mpReferenceKF;
  3037. }
  3038. }
  3039. bool Tracking::Relocalization()
  3040. {
  3041. Verbose::PrintMess("Starting relocalization", Verbose::VERBOSITY_NORMAL);
  3042. // Compute Bag of Words Vector
  3043. mCurrentFrame.ComputeBoW();
  3044. // Relocalization is performed when tracking is lost
  3045. // Track Lost: Query KeyFrame Database for keyframe candidates for relocalisation
  3046. vector<KeyFrame*> vpCandidateKFs = mpKeyFrameDB->DetectRelocalizationCandidates(&mCurrentFrame, mpAtlas->GetCurrentMap());
  3047. if(vpCandidateKFs.empty()) {
  3048. Verbose::PrintMess("There are not candidates", Verbose::VERBOSITY_NORMAL);
  3049. return false;
  3050. }
  3051. const int nKFs = vpCandidateKFs.size();
  3052. // We perform first an ORB matching with each candidate
  3053. // If enough matches are found we setup a PnP solver
  3054. ORBmatcher matcher(0.75,true);
  3055. vector<MLPnPsolver*> vpMLPnPsolvers;
  3056. vpMLPnPsolvers.resize(nKFs);
  3057. vector<vector<MapPoint*> > vvpMapPointMatches;
  3058. vvpMapPointMatches.resize(nKFs);
  3059. vector<bool> vbDiscarded;
  3060. vbDiscarded.resize(nKFs);
  3061. int nCandidates=0;
  3062. for(int i=0; i<nKFs; i++)
  3063. {
  3064. KeyFrame* pKF = vpCandidateKFs[i];
  3065. if(pKF->isBad())
  3066. vbDiscarded[i] = true;
  3067. else
  3068. {
  3069. int nmatches = matcher.SearchByBoW(pKF,mCurrentFrame,vvpMapPointMatches[i]);
  3070. if(nmatches<15)
  3071. {
  3072. vbDiscarded[i] = true;
  3073. continue;
  3074. }
  3075. else
  3076. {
  3077. MLPnPsolver* pSolver = new MLPnPsolver(mCurrentFrame,vvpMapPointMatches[i]);
  3078. pSolver->SetRansacParameters(0.99,10,300,6,0.5,5.991); //This solver needs at least 6 points
  3079. vpMLPnPsolvers[i] = pSolver;
  3080. nCandidates++;
  3081. }
  3082. }
  3083. }
  3084. // Alternatively perform some iterations of P4P RANSAC
  3085. // Until we found a camera pose supported by enough inliers
  3086. bool bMatch = false;
  3087. ORBmatcher matcher2(0.9,true);
  3088. while(nCandidates>0 && !bMatch)
  3089. {
  3090. for(int i=0; i<nKFs; i++)
  3091. {
  3092. if(vbDiscarded[i])
  3093. continue;
  3094. // Perform 5 Ransac Iterations
  3095. vector<bool> vbInliers;
  3096. int nInliers;
  3097. bool bNoMore;
  3098. MLPnPsolver* pSolver = vpMLPnPsolvers[i];
  3099. Eigen::Matrix4f eigTcw;
  3100. bool bTcw = pSolver->iterate(5,bNoMore,vbInliers,nInliers, eigTcw);
  3101. // If Ransac reachs max. iterations discard keyframe
  3102. if(bNoMore)
  3103. {
  3104. vbDiscarded[i]=true;
  3105. nCandidates--;
  3106. }
  3107. // If a Camera Pose is computed, optimize
  3108. if(bTcw)
  3109. {
  3110. Sophus::SE3f Tcw(eigTcw);
  3111. mCurrentFrame.SetPose(Tcw);
  3112. // Tcw.copyTo(mCurrentFrame.mTcw);
  3113. set<MapPoint*> sFound;
  3114. const int np = vbInliers.size();
  3115. for(int j=0; j<np; j++)
  3116. {
  3117. if(vbInliers[j])
  3118. {
  3119. mCurrentFrame.mvpMapPoints[j]=vvpMapPointMatches[i][j];
  3120. sFound.insert(vvpMapPointMatches[i][j]);
  3121. }
  3122. else
  3123. mCurrentFrame.mvpMapPoints[j]=NULL;
  3124. }
  3125. int nGood = Optimizer::PoseOptimization(&mCurrentFrame);
  3126. if(nGood<10)
  3127. continue;
  3128. for(int io =0; io<mCurrentFrame.N; io++)
  3129. if(mCurrentFrame.mvbOutlier[io])
  3130. mCurrentFrame.mvpMapPoints[io]=static_cast<MapPoint*>(NULL);
  3131. // If few inliers, search by projection in a coarse window and optimize again
  3132. if(nGood<50)
  3133. {
  3134. int nadditional =matcher2.SearchByProjection(mCurrentFrame,vpCandidateKFs[i],sFound,10,100);
  3135. if(nadditional+nGood>=50)
  3136. {
  3137. nGood = Optimizer::PoseOptimization(&mCurrentFrame);
  3138. // If many inliers but still not enough, search by projection again in a narrower window
  3139. // the camera has been already optimized with many points
  3140. if(nGood>30 && nGood<50)
  3141. {
  3142. sFound.clear();
  3143. for(int ip =0; ip<mCurrentFrame.N; ip++)
  3144. if(mCurrentFrame.mvpMapPoints[ip])
  3145. sFound.insert(mCurrentFrame.mvpMapPoints[ip]);
  3146. nadditional =matcher2.SearchByProjection(mCurrentFrame,vpCandidateKFs[i],sFound,3,64);
  3147. // Final optimization
  3148. if(nGood+nadditional>=50)
  3149. {
  3150. nGood = Optimizer::PoseOptimization(&mCurrentFrame);
  3151. for(int io =0; io<mCurrentFrame.N; io++)
  3152. if(mCurrentFrame.mvbOutlier[io])
  3153. mCurrentFrame.mvpMapPoints[io]=NULL;
  3154. }
  3155. }
  3156. }
  3157. }
  3158. // If the pose is supported by enough inliers stop ransacs and continue
  3159. if(nGood>=50)
  3160. {
  3161. bMatch = true;
  3162. break;
  3163. }
  3164. }
  3165. }
  3166. }
  3167. if(!bMatch)
  3168. {
  3169. return false;
  3170. }
  3171. else
  3172. {
  3173. mnLastRelocFrameId = mCurrentFrame.mnId;
  3174. cout << "Relocalized!!" << endl;
  3175. return true;
  3176. }
  3177. }
  3178. void Tracking::Reset(bool bLocMap)
  3179. {
  3180. Verbose::PrintMess("System Reseting", Verbose::VERBOSITY_NORMAL);
  3181. if(mpViewer)
  3182. {
  3183. mpViewer->RequestStop();
  3184. while(!mpViewer->isStopped())
  3185. usleep(3000);
  3186. }
  3187. // Reset Local Mapping
  3188. if (!bLocMap)
  3189. {
  3190. Verbose::PrintMess("Reseting Local Mapper...", Verbose::VERBOSITY_NORMAL);
  3191. mpLocalMapper->RequestReset();
  3192. Verbose::PrintMess("done", Verbose::VERBOSITY_NORMAL);
  3193. }
  3194. // Reset Loop Closing
  3195. Verbose::PrintMess("Reseting Loop Closing...", Verbose::VERBOSITY_NORMAL);
  3196. mpLoopClosing->RequestReset();
  3197. Verbose::PrintMess("done", Verbose::VERBOSITY_NORMAL);
  3198. // Clear BoW Database
  3199. Verbose::PrintMess("Reseting Database...", Verbose::VERBOSITY_NORMAL);
  3200. mpKeyFrameDB->clear();
  3201. Verbose::PrintMess("done", Verbose::VERBOSITY_NORMAL);
  3202. // Clear Map (this erase MapPoints and KeyFrames)
  3203. mpAtlas->clearAtlas();
  3204. mpAtlas->CreateNewMap();
  3205. if (mSensor==System::IMU_STEREO || mSensor == System::IMU_MONOCULAR || mSensor == System::IMU_RGBD)
  3206. mpAtlas->SetInertialSensor();
  3207. mnInitialFrameId = 0;
  3208. KeyFrame::nNextId = 0;
  3209. Frame::nNextId = 0;
  3210. mState = NO_IMAGES_YET;
  3211. mbReadyToInitializate = false;
  3212. mbSetInit=false;
  3213. mlRelativeFramePoses.clear();
  3214. mlpReferences.clear();
  3215. mlFrameTimes.clear();
  3216. mlbLost.clear();
  3217. mCurrentFrame = Frame();
  3218. mnLastRelocFrameId = 0;
  3219. mLastFrame = Frame();
  3220. mpReferenceKF = static_cast<KeyFrame*>(NULL);
  3221. mpLastKeyFrame = static_cast<KeyFrame*>(NULL);
  3222. mvIniMatches.clear();
  3223. if(mpViewer)
  3224. mpViewer->Release();
  3225. Verbose::PrintMess(" End reseting! ", Verbose::VERBOSITY_NORMAL);
  3226. }
  3227. void Tracking::ResetActiveMap(bool bLocMap)
  3228. {
  3229. Verbose::PrintMess("Active map Reseting", Verbose::VERBOSITY_NORMAL);
  3230. if(mpViewer)
  3231. {
  3232. mpViewer->RequestStop();
  3233. while(!mpViewer->isStopped())
  3234. usleep(3000);
  3235. }
  3236. Map* pMap = mpAtlas->GetCurrentMap();
  3237. if (!bLocMap)
  3238. {
  3239. Verbose::PrintMess("Reseting Local Mapper...", Verbose::VERBOSITY_VERY_VERBOSE);
  3240. mpLocalMapper->RequestResetActiveMap(pMap);
  3241. Verbose::PrintMess("done", Verbose::VERBOSITY_VERY_VERBOSE);
  3242. }
  3243. // Reset Loop Closing
  3244. Verbose::PrintMess("Reseting Loop Closing...", Verbose::VERBOSITY_NORMAL);
  3245. mpLoopClosing->RequestResetActiveMap(pMap);
  3246. Verbose::PrintMess("done", Verbose::VERBOSITY_NORMAL);
  3247. // Clear BoW Database
  3248. Verbose::PrintMess("Reseting Database", Verbose::VERBOSITY_NORMAL);
  3249. mpKeyFrameDB->clearMap(pMap); // Only clear the active map references
  3250. Verbose::PrintMess("done", Verbose::VERBOSITY_NORMAL);
  3251. // Clear Map (this erase MapPoints and KeyFrames)
  3252. mpAtlas->clearMap();
  3253. //KeyFrame::nNextId = mpAtlas->GetLastInitKFid();
  3254. //Frame::nNextId = mnLastInitFrameId;
  3255. mnLastInitFrameId = Frame::nNextId;
  3256. //mnLastRelocFrameId = mnLastInitFrameId;
  3257. mState = NO_IMAGES_YET; //NOT_INITIALIZED;
  3258. mbReadyToInitializate = false;
  3259. list<bool> lbLost;
  3260. // lbLost.reserve(mlbLost.size());
  3261. unsigned int index = mnFirstFrameId;
  3262. cout << "mnFirstFrameId = " << mnFirstFrameId << endl;
  3263. for(Map* pMap : mpAtlas->GetAllMaps())
  3264. {
  3265. if(pMap->GetAllKeyFrames().size() > 0)
  3266. {
  3267. if(index > pMap->GetLowerKFID())
  3268. index = pMap->GetLowerKFID();
  3269. }
  3270. }
  3271. //cout << "First Frame id: " << index << endl;
  3272. int num_lost = 0;
  3273. cout << "mnInitialFrameId = " << mnInitialFrameId << endl;
  3274. for(list<bool>::iterator ilbL = mlbLost.begin(); ilbL != mlbLost.end(); ilbL++)
  3275. {
  3276. if(index < mnInitialFrameId)
  3277. lbLost.push_back(*ilbL);
  3278. else
  3279. {
  3280. lbLost.push_back(true);
  3281. num_lost += 1;
  3282. }
  3283. index++;
  3284. }
  3285. cout << num_lost << " Frames set to lost" << endl;
  3286. mlbLost = lbLost;
  3287. mnInitialFrameId = mCurrentFrame.mnId;
  3288. mnLastRelocFrameId = mCurrentFrame.mnId;
  3289. mCurrentFrame = Frame();
  3290. mLastFrame = Frame();
  3291. mpReferenceKF = static_cast<KeyFrame*>(NULL);
  3292. mpLastKeyFrame = static_cast<KeyFrame*>(NULL);
  3293. mvIniMatches.clear();
  3294. mbVelocity = false;
  3295. if(mpViewer)
  3296. mpViewer->Release();
  3297. Verbose::PrintMess(" End reseting! ", Verbose::VERBOSITY_NORMAL);
  3298. }
  3299. vector<MapPoint*> Tracking::GetLocalMapMPS()
  3300. {
  3301. return mvpLocalMapPoints;
  3302. }
  3303. void Tracking::ChangeCalibration(const string &strSettingPath)
  3304. {
  3305. cv::FileStorage fSettings(strSettingPath, cv::FileStorage::READ);
  3306. float fx = fSettings["Camera.fx"];
  3307. float fy = fSettings["Camera.fy"];
  3308. float cx = fSettings["Camera.cx"];
  3309. float cy = fSettings["Camera.cy"];
  3310. mK_.setIdentity();
  3311. mK_(0,0) = fx;
  3312. mK_(1,1) = fy;
  3313. mK_(0,2) = cx;
  3314. mK_(1,2) = cy;
  3315. cv::Mat K = cv::Mat::eye(3,3,CV_32F);
  3316. K.at<float>(0,0) = fx;
  3317. K.at<float>(1,1) = fy;
  3318. K.at<float>(0,2) = cx;
  3319. K.at<float>(1,2) = cy;
  3320. K.copyTo(mK);
  3321. cv::Mat DistCoef(4,1,CV_32F);
  3322. DistCoef.at<float>(0) = fSettings["Camera.k1"];
  3323. DistCoef.at<float>(1) = fSettings["Camera.k2"];
  3324. DistCoef.at<float>(2) = fSettings["Camera.p1"];
  3325. DistCoef.at<float>(3) = fSettings["Camera.p2"];
  3326. const float k3 = fSettings["Camera.k3"];
  3327. if(k3!=0)
  3328. {
  3329. DistCoef.resize(5);
  3330. DistCoef.at<float>(4) = k3;
  3331. }
  3332. DistCoef.copyTo(mDistCoef);
  3333. mbf = fSettings["Camera.bf"];
  3334. Frame::mbInitialComputations = true;
  3335. }
  3336. void Tracking::InformOnlyTracking(const bool &flag)
  3337. {
  3338. mbOnlyTracking = flag;
  3339. }
  3340. void Tracking::UpdateFrameIMU(const float s, const IMU::Bias &b, KeyFrame* pCurrentKeyFrame)
  3341. {
  3342. Map * pMap = pCurrentKeyFrame->GetMap();
  3343. unsigned int index = mnFirstFrameId;
  3344. list<ORB_SLAM3::KeyFrame*>::iterator lRit = mlpReferences.begin();
  3345. list<bool>::iterator lbL = mlbLost.begin();
  3346. for(auto lit=mlRelativeFramePoses.begin(),lend=mlRelativeFramePoses.end();lit!=lend;lit++, lRit++, lbL++)
  3347. {
  3348. if(*lbL)
  3349. continue;
  3350. KeyFrame* pKF = *lRit;
  3351. while(pKF->isBad())
  3352. {
  3353. pKF = pKF->GetParent();
  3354. }
  3355. if(pKF->GetMap() == pMap)
  3356. {
  3357. (*lit).translation() *= s;
  3358. }
  3359. }
  3360. mLastBias = b;
  3361. mpLastKeyFrame = pCurrentKeyFrame;
  3362. mLastFrame.SetNewBias(mLastBias);
  3363. mCurrentFrame.SetNewBias(mLastBias);
  3364. while(!mCurrentFrame.imuIsPreintegrated())
  3365. {
  3366. usleep(500);
  3367. }
  3368. if(mLastFrame.mnId == mLastFrame.mpLastKeyFrame->mnFrameId)
  3369. {
  3370. mLastFrame.SetImuPoseVelocity(mLastFrame.mpLastKeyFrame->GetImuRotation(),
  3371. mLastFrame.mpLastKeyFrame->GetImuPosition(),
  3372. mLastFrame.mpLastKeyFrame->GetVelocity());
  3373. }
  3374. else
  3375. {
  3376. const Eigen::Vector3f Gz(0, 0, -IMU::GRAVITY_VALUE);
  3377. const Eigen::Vector3f twb1 = mLastFrame.mpLastKeyFrame->GetImuPosition();
  3378. const Eigen::Matrix3f Rwb1 = mLastFrame.mpLastKeyFrame->GetImuRotation();
  3379. const Eigen::Vector3f Vwb1 = mLastFrame.mpLastKeyFrame->GetVelocity();
  3380. float t12 = mLastFrame.mpImuPreintegrated->dT;
  3381. mLastFrame.SetImuPoseVelocity(IMU::NormalizeRotation(Rwb1*mLastFrame.mpImuPreintegrated->GetUpdatedDeltaRotation()),
  3382. twb1 + Vwb1*t12 + 0.5f*t12*t12*Gz+ Rwb1*mLastFrame.mpImuPreintegrated->GetUpdatedDeltaPosition(),
  3383. Vwb1 + Gz*t12 + Rwb1*mLastFrame.mpImuPreintegrated->GetUpdatedDeltaVelocity());
  3384. }
  3385. if (mCurrentFrame.mpImuPreintegrated)
  3386. {
  3387. const Eigen::Vector3f Gz(0, 0, -IMU::GRAVITY_VALUE);
  3388. const Eigen::Vector3f twb1 = mCurrentFrame.mpLastKeyFrame->GetImuPosition();
  3389. const Eigen::Matrix3f Rwb1 = mCurrentFrame.mpLastKeyFrame->GetImuRotation();
  3390. const Eigen::Vector3f Vwb1 = mCurrentFrame.mpLastKeyFrame->GetVelocity();
  3391. float t12 = mCurrentFrame.mpImuPreintegrated->dT;
  3392. mCurrentFrame.SetImuPoseVelocity(IMU::NormalizeRotation(Rwb1*mCurrentFrame.mpImuPreintegrated->GetUpdatedDeltaRotation()),
  3393. twb1 + Vwb1*t12 + 0.5f*t12*t12*Gz+ Rwb1*mCurrentFrame.mpImuPreintegrated->GetUpdatedDeltaPosition(),
  3394. Vwb1 + Gz*t12 + Rwb1*mCurrentFrame.mpImuPreintegrated->GetUpdatedDeltaVelocity());
  3395. }
  3396. mnFirstImuFrameId = mCurrentFrame.mnId;
  3397. }
  3398. void Tracking::NewDataset()
  3399. {
  3400. mnNumDataset++;
  3401. }
  3402. int Tracking::GetNumberDataset()
  3403. {
  3404. return mnNumDataset;
  3405. }
  3406. int Tracking::GetMatchesInliers()
  3407. {
  3408. return mnMatchesInliers;
  3409. }
  3410. void Tracking::SaveSubTrajectory(string strNameFile_frames, string strNameFile_kf, string strFolder)
  3411. {
  3412. mpSystem->SaveTrajectoryEuRoC(strFolder + strNameFile_frames);
  3413. //mpSystem->SaveKeyFrameTrajectoryEuRoC(strFolder + strNameFile_kf);
  3414. }
  3415. void Tracking::SaveSubTrajectory(string strNameFile_frames, string strNameFile_kf, Map* pMap)
  3416. {
  3417. mpSystem->SaveTrajectoryEuRoC(strNameFile_frames, pMap);
  3418. if(!strNameFile_kf.empty())
  3419. mpSystem->SaveKeyFrameTrajectoryEuRoC(strNameFile_kf, pMap);
  3420. }
  3421. float Tracking::GetImageScale()
  3422. {
  3423. return mImageScale;
  3424. }
  3425. #ifdef REGISTER_LOOP
  3426. void Tracking::RequestStop()
  3427. {
  3428. unique_lock<mutex> lock(mMutexStop);
  3429. mbStopRequested = true;
  3430. }
  3431. bool Tracking::Stop()
  3432. {
  3433. unique_lock<mutex> lock(mMutexStop);
  3434. if(mbStopRequested && !mbNotStop)
  3435. {
  3436. mbStopped = true;
  3437. cout << "Tracking STOP" << endl;
  3438. return true;
  3439. }
  3440. return false;
  3441. }
  3442. bool Tracking::stopRequested()
  3443. {
  3444. unique_lock<mutex> lock(mMutexStop);
  3445. return mbStopRequested;
  3446. }
  3447. bool Tracking::isStopped()
  3448. {
  3449. unique_lock<mutex> lock(mMutexStop);
  3450. return mbStopped;
  3451. }
  3452. void Tracking::Release()
  3453. {
  3454. unique_lock<mutex> lock(mMutexStop);
  3455. mbStopped = false;
  3456. mbStopRequested = false;
  3457. }
  3458. #endif
  3459. } //namespace ORB_SLAM