SLProject  4.2.000
A platform independent 3D computer graphics framework for desktop OS, Android, iOS and online in web browsers
WAIModeOrbSlam2.h
Go to the documentation of this file.
1 #ifndef WAI_MODE_ORB_SLAM_2
2 #define WAI_MODE_ORB_SLAM_2
3 
4 #include <thread>
5 
6 #include <opencv2/core.hpp>
7 
8 #include <WAIHelper.h>
9 #include <WAIKeyFrameDB.h>
10 #include <WAIMap.h>
11 
12 #include <orb_slam/SURFextractor.h>
13 #include <orb_slam/LocalMapping.h>
14 #include <orb_slam/LoopClosing.h>
15 #include <orb_slam/Initializer.h>
16 #include <orb_slam/ORBmatcher.h>
17 #include <orb_slam/Optimizer.h>
18 #include <orb_slam/PnPsolver.h>
19 
20 #define OPTFLOW_GRID_COLS 7
21 #define OPTFLOW_GRID_ROWS 4
22 
23 namespace WAI
24 {
25 
27 {
33 };
34 
36 {
37 public:
38  struct Params
39  {
40  //run local mapper and loopclosing serial to tracking
41  bool serial = false;
42  //retain the images in the keyframes, so we can store them later
43  bool retainImg = false;
44  //in onlyTracking mode we do not use local mapping and loop closing
45  bool onlyTracking = false;
46  //If true, keyframes loaded from a map will not be culled and the pose will not be changed. Local bundle adjustment is applied only on newly added kfs.
47  //Also, the loop closing will be disabled so that there will be no optimization of the essential graph and no global bundle adjustment.
48  bool fixOldKfs = false;
49  //use lucas canade optical flow tracking
50  bool trackOptFlow = false;
51 
52  //keyframe culling strategy params:
53  // A keyframe is considered redundant if _cullRedundantPerc of the MapPoints it sees, are seen
54  // in at least other 3 keyframes (in the same or finer scale)
55  float cullRedundantPerc = 0.95f; //originally it was 0.9
56  };
57 
58  ModeOrbSlam2(ORB_SLAM2::KPextractor* kpExtractor,
59  ORB_SLAM2::KPextractor* kpIniExtractor,
60  cv::Mat cameraMat,
61  cv::Mat distortionMat,
62  const Params& params,
63  std::string orbVocFile,
64  bool applyMinAccScoreFilter = false);
65 
66  ModeOrbSlam2(ORB_SLAM2::KPextractor* kpExtractor,
67  ORB_SLAM2::KPextractor* kpIniExtractor,
68  ORB_SLAM2::KPextractor* kpMarkerExtractor,
69  std::string markerFile,
70  cv::Mat cameraMat,
71  cv::Mat distortionMat,
72  const Params& params,
73  std::string orbVocFile,
74  bool applyMinAccScoreFilter = false);
75 
76  ~ModeOrbSlam2();
77  bool getPose(cv::Mat* pose);
78  bool update(cv::Mat& imageGray, cv::Mat& imageRGB);
79 
80  static bool relocalization(WAIFrame& currentFrame,
81  WAIKeyFrameDB* keyFrameDB,
82  unsigned int* lastRelocFrameId,
83  WAIMap& waiMap,
84  bool applyMinAccScoreFilter = true,
85  bool relocWithAllKFs = false);
86 
87  void reset();
88  bool isInitialized();
89 
90  void disableMapping();
91  void enableMapping();
92 
93  WAIMap* getMap() { return _map; }
94  WAIKeyFrameDB* getKfDB() { return mpKeyFrameDatabase; }
95 
96  // New KeyFrame rules (according to fps)
97  // Max/Min Frames to insert keyframes and to check relocalisation
98  int mMinFrames = 0;
99  int mMaxFrames = 30; //= fps (max number of frames between keyframes)
100 
101  // Debug functions
102  std::string getPrintableState();
103  TrackingState getTrackingState() { return _state; }
104  std::string getPrintableType();
105  int getKeyPointCount();
106  int getMapPointCount();
107  int getMapPointMatchesCount();
108  int getKeyFrameCount();
109  int getNMapMatches();
110  int getNumKeyFrames();
111  float poseDifference();
112  float getMeanReprojectionError();
113  void findMatches(std::vector<cv::Point2f>& vP2D, std::vector<cv::Point3f>& vP3Dw);
114 
115  std::string getLoopCloseStatus();
116  int getLoopCloseCount();
117  int getKeyFramesInLoopCloseQueueCount();
118 
119  std::vector<WAIMapPoint*> getMapPoints();
120  std::vector<WAIMapPoint*> getMatchedMapPoints();
121  std::vector<WAIMapPoint*> getLocalMapPoints();
122  std::vector<WAIMapPoint*> getMarkerCornerMapPoints();
123  std::vector<WAIKeyFrame*> getKeyFrames();
124  std::pair<std::vector<cv::Vec3f>, std::vector<cv::Vec2f>> getMatchedCorrespondances();
125  std::pair<std::vector<cv::Vec3f>, std::vector<cv::Vec2f>> getCorrespondances();
126 
127  KPextractor* getKPextractor()
128  {
129  return mpExtractor;
130  }
131 
132  bool getTrackOptFlow();
133  void setTrackOptFlow(bool flag);
134 
135  // state machine
136  void pause();
137  void resume();
138  void requestStateIdle();
139  bool hasStateIdle();
140  bool retainImage() { return _params.retainImg; }
141  void setInitialized(bool initialized) { _initialized = initialized; }
142 
143  void setVocabulary(std::string orbVocFile);
144 
145  WAIFrame getCurrentFrame();
146 
147  bool doMarkerMapPreprocessing(std::string markerFile, cv::Mat& nodeTransform, float markerWidthInM);
148  void decorateVideoWithKeyPoints(cv::Mat& image);
149  void decorateVideoWithKeyPointMatches(cv::Mat& image);
150 
151  // marker correction stuff
152  WAIFrame createMarkerFrame(std::string markerFile,
153  KPextractor* markerExtractor);
154 
155 private:
157  {
161  TrackingType_OptFlow
162  };
163 
164  void initialize(cv::Mat& imageGray, cv::Mat& imageRGB);
165  bool createInitialMapMonocular(int mapPointsNeeded);
166  void track3DPts(cv::Mat& imageGray, cv::Mat& imageRGB);
167 
168  //bool relocalization();
169  bool trackReferenceKeyFrame();
170  bool trackWithMotionModel();
171  bool trackLocalMap();
172  bool trackWithOptFlow();
173 
174  bool needNewKeyFrame();
175  void createNewKeyFrame();
176 
177  bool posInGrid(const cv::KeyPoint& kp, int& posX, int& posY, int minX, int minY);
178  void checkReplacedInLastFrame();
179  void updateLocalMap();
180  void updateLocalKeyFrames();
181  void updateLocalPoints();
182  void searchLocalPoints();
183  void updateLastFrame();
184  //void globalBundleAdjustment();
185 
186  WAIKeyFrame* currentKeyFrame();
187 
188  cv::Mat _pose;
189 
191  bool _poseSet = false;
194 
195  cv::Mat _cameraMat;
196  cv::Mat _distortionMat;
197 
199  TrackingType _trackingType = TrackingType_None;
200  WAIKeyFrameDB* mpKeyFrameDatabase = nullptr;
201  WAIMap* _map = nullptr;
202 
203  ORB_SLAM2::ORBVocabulary* mpVocabulary = nullptr;
204  ORB_SLAM2::KPextractor* mpExtractor = nullptr;
205  ORB_SLAM2::KPextractor* mpIniExtractor = nullptr;
206 
207  ORB_SLAM2::LocalMapping* mpLocalMapper = nullptr;
208  ORB_SLAM2::LoopClosing* mpLoopCloser = nullptr;
209  ORB_SLAM2::Initializer* mpInitializer = nullptr;
210 
211  std::thread* mptLocalMapping = nullptr;
212  std::thread* mptLoopClosing = nullptr;
213 
214  std::mutex _meanProjErrorLock;
215  std::mutex _poseDiffLock;
216  std::mutex _mapLock;
217  std::mutex _nMapMatchesLock;
218  std::mutex _optFlowLock;
219 
223  std::vector<int> mvIniMatches;
224  std::vector<cv::Point2f> mvbPrevMatched;
225  std::vector<cv::Point3f> mvIniP3D;
226  bool _bOK = false;
227  bool _mapHasChanged = false;
228 
229  // In case of performing only localization, this flag is true when there are no matches to
230  // points in the map. Still tracking will continue if there are enough matches with temporal points.
231  // In that case we are doing visual odometry. The system will try to do relocalization to recover
232  // "zero-drift" localization to the map.
233  bool mbVO = false;
234 
235  // Lists used to recover the full camera trajectory at the end of the execution.
236  // Basically we store the reference keyframe for each frame and its relative transformation
237  list<cv::Mat> mlRelativeFramePoses;
238  list<WAIKeyFrame*> mlpReferences;
239  list<double> mlFrameTimes;
240  list<bool> mlbLost;
241 
242  //C urrent matches in frame
243  int mnMatchesInliers = 0;
244 
245  //Last Frame, KeyFrame and Relocalisation Info
246  WAIKeyFrame* mpLastKeyFrame = nullptr;
247  unsigned int mnLastRelocFrameId = 0;
248  unsigned int mnLastKeyFrameId;
249 
250  // Local Map
251  // (maybe always the last inserted keyframe?)
252  WAIKeyFrame* mpReferenceKF = nullptr;
253  std::vector<WAIMapPoint*> mvpLocalMapPoints;
254  std::vector<WAIKeyFrame*> mvpLocalKeyFrames;
255 
256  // Motion Model
257  cv::Mat mVelocity;
258 
259  // optical flow
260  bool _optFlowOK = false;
261  cv::Mat _optFlowTcw;
262  vector<WAIMapPoint*> _optFlowMapPtsLastFrame;
263  vector<cv::KeyPoint> _optFlowKeyPtsLastFrame;
266 
267  // state machine
268  void stateTransition();
269  void resetRequests();
270  void requestResume();
271 
272  bool _idleRequested = false;
273  bool _resumeRequested = false;
274  std::mutex _mutexStates;
275 
276  // debug visualization
277  void decorate(cv::Mat& image);
278  void calculateMeanReprojectionError();
279  void calculatePoseDifference();
280 
281  double _meanReprojectionError = -1.0;
282  double _poseDifference = -1.0;
283  bool _showMapPC = true;
284  bool _showMatchesPC = true;
285  bool _showLocalMapPC = false;
286  bool _showKeyFrames = true;
287  bool _showCovisibilityGraph = false;
288  bool _showSpanningTree = true;
289  bool _showLoopEdges = true;
290  bool _renderKfBackground = false;
291  bool _allowKfsAsActiveCam = false;
292 
293  // marker correction stuff
294  bool findMarkerHomography(WAIFrame& markerFrame,
295  WAIKeyFrame* kfCand,
296  cv::Mat& homography,
297  int minMatches);
298 
299  //bool _createMarkerMap;
300  //std::string _markerFile;
301 
302  //std::string _markerFile;
304  ORB_SLAM2::KPextractor* _markerExtractor = nullptr;
305 
306  WAIMapPoint* _mpUL = nullptr;
307  WAIMapPoint* _mpUR = nullptr;
308  WAIMapPoint* _mpLL = nullptr;
309  WAIMapPoint* _mpLR = nullptr;
310 };
311 }
312 
313 #endif
#define WAI_API
Definition: WAIHelper.h:36
std::vector< cv::Point3f > mvIniP3D
unsigned int mnLastKeyFrameId
std::mutex _mutexStates
TrackingState getTrackingState()
float _optFlowGridElementHeightInv
void setInitialized(bool initialized)
std::vector< cv::Point2f > mvbPrevMatched
std::vector< int > mvIniMatches
vector< cv::KeyPoint > _optFlowKeyPtsLastFrame
std::mutex _meanProjErrorLock
list< WAIKeyFrame * > mlpReferences
float _optFlowGridElementWidthInv
std::vector< WAIMapPoint * > mvpLocalMapPoints
list< bool > mlbLost
std::mutex _optFlowLock
std::vector< WAIKeyFrame * > mvpLocalKeyFrames
std::mutex _nMapMatchesLock
KPextractor * getKPextractor()
list< double > mlFrameTimes
vector< WAIMapPoint * > _optFlowMapPtsLastFrame
list< cv::Mat > mlRelativeFramePoses
std::mutex _poseDiffLock
WAIKeyFrameDB * getKfDB()
AR Keyframe database class.
Definition: WAIKeyFrameDB.h:46
AR Keyframe node class.
Definition: WAIKeyFrame.h:60
Definition: WAIMap.h:52
WAI : Where Am I: Collection of duplicate structs for vectors.
Definition: WAIMath.h:8
@ TrackingState_Initializing
@ TrackingState_Idle
@ TrackingState_TrackingOK
@ TrackingState_None
@ TrackingState_TrackingLost