RTAB-Map 0.23.10
Real-Time Appearance-Based Mapping
Loading...
Searching...
No Matches
rtabmap::Rtabmap Class Reference

Top-level RTAB-Map SLAM pipeline (mapping, localization and loop closure). More...

#include <Rtabmap.h>

Public Types

enum  VhStrategy { kVhNone , kVhEpipolar , kVhUndef }
 Loop-closure verification strategy. More...
 

Public Member Functions

bool process (const SensorData &data, Transform odomPose, const cv::Mat &odomCovariance=cv::Mat::eye(6, 6, CV_64FC1), const std::vector< float > &odomVelocity=std::vector< float >(), const std::map< std::string, float > &externalStats=std::map< std::string, float >())
 Main RTAB-Map iteration: ingests one sensor frame and updates the map.
 
bool process (const SensorData &data, Transform odomPose, float odomLinearVariance, float odomAngularVariance, const std::vector< float > &odomVelocity=std::vector< float >(), const std::map< std::string, float > &externalStats=std::map< std::string, float >())
 Convenience overload: builds a diagonal covariance from scalar variances.
 
bool process (const cv::Mat &image, int id=0, const std::map< std::string, float > &externalStats=std::map< std::string, float >())
 Appearance-only convenience overload (loop-closure detection without odometry).
 
void init (const ParametersMap &parameters, const std::string &databasePath="", bool loadDatabaseParameters=false)
 Initializes Rtabmap with parameters and a database.
 
void init (const std::string &configFile="", const std::string &databasePath="", bool loadDatabaseParameters=false)
 Initializes Rtabmap from a configuration file and a database.
 
void close (bool databaseSaved=true, const std::string &ouputDatabasePath="")
 Closes Rtabmap and releases the underlying Memory.
 
const std::string & getWorkingDir () const
 
bool isRGBDMode () const
 
int getLoopClosureId () const
 
float getLoopClosureValue () const
 
int getHighestHypothesisId () const
 
float getHighestHypothesisValue () const
 
int getLastLocationId () const
 
std::list< int > getWM () const
 
std::set< int > getSTM () const
 
int getWMSize () const
 
int getSTMSize () const
 
std::map< int, int > getWeights () const
 
int getTotalMemSize () const
 
double getLastProcessTime () const
 
bool isInSTM (int locationId) const
 
bool isIDsGenerated () const
 
const StatisticsgetStatistics () const
 
const std::map< int, Transform > & getLocalOptimizedPoses () const
 
const std::multimap< int, Link > & getLocalConstraints () const
 
Transform getPose (int locationId) const
 
Transform getMapCorrection () const
 
const MemorygetMemory () const
 
float getGoalReachedRadius () const
 
float getLocalRadius () const
 
const TransformgetLastLocalizationPose () const
 
float getTimeThreshold () const
 
void setTimeThreshold (float maxTimeAllowed)
 Sets the per-iteration time budget (ms).
 
int getMemoryThreshold () const
 
void setMemoryThreshold (int maxMemoryAllowed)
 Sets the maximum number of signatures kept in WM (0 = unbounded).
 
void setInitialPose (const Transform &initialPose)
 Sets the localization prior pose used to seed the next process() call (localization mode only).
 
int triggerNewMap ()
 Starts a new map session (next process() will create a fresh map id).
 
bool labelLocation (int id, const std::string &label)
 Assigns or clears a label on signature id.
 
bool setUserData (int id, const cv::Mat &data)
 Attaches user data to signature id, compressing it on the fly if needed.
 
void generateDOTGraph (const std::string &path, int id=0, int margin=5)
 Writes a Graphviz DOT file of the pose graph.
 
void exportPoses (const std::string &path, bool optimized, bool global, int format)
 Exports the current pose graph to a text file.
 
void resetMemory ()
 Clears all in-memory state and resets the database.
 
void dumpPrediction () const
 Dumps the Bayes-filter prediction matrix to a file in the working directory.
 
void dumpData () const
 Dumps the Memory state (signatures, words, dictionary) to the working directory.
 
void parseParameters (const ParametersMap &parameters)
 Re-parses parameters and propagates them to owned sub-objects (Memory, BayesFilter, Optimizer, ...).
 
const ParametersMapgetParameters () const
 
void setWorkingDirectory (std::string path)
 Sets the working directory used for dumps, logs and temporary files.
 
void rejectLastLoopClosure ()
 Removes the loop-closure link added at the last process() iteration.
 
void deleteLastLocation ()
 Deletes the most recent (non-intermediate) location from the map.
 
void setOptimizedPoses (const std::map< int, Transform > &poses, const std::multimap< int, Link > &constraints)
 Replaces the current optimized poses and constraints with externally provided ones.
 
Signature getSignatureCopy (int id, bool images, bool scan, bool userData, bool occupancyGrid, bool withWords, bool withGlobalDescriptors) const
 Returns a copy of signature id with optional payloads attached.
 
RTABMAP_DEPRECATED void get3DMap (std::map< int, Signature > &signatures, std::map< int, Transform > &poses, std::multimap< int, Link > &constraints, bool optimized, bool global) const
 Deprecated: use getGraph() instead with withImages=true, withScan=true, withUserData=true and withGrid=true.
 
void getGraph (std::map< int, Transform > &poses, std::multimap< int, Link > &constraints, bool optimized, bool global, std::map< int, Signature > *signatures=0, bool withImages=false, bool withScan=false, bool withUserData=false, bool withGrid=false, bool withWords=true, bool withGlobalDescriptors=true) const
 Extracts a full snapshot of the current pose graph.
 
std::map< int, TransformgetNodesInRadius (const Transform &pose, float radius, int k=0, std::map< int, float > *distsSqr=0)
 Returns optimized poses within a metric radius of pose.
 
std::map< int, TransformgetNodesInRadius (int nodeId, float radius, int k=0, std::map< int, float > *distsSqr=0)
 Returns optimized poses within a metric radius of node nodeId.
 
int detectMoreLoopClosures (float clusterRadiusMax=0.5f, float clusterAngle=M_PI/6.0f, int iterations=1, bool intraSession=true, bool interSession=true, const ProgressState *state=0, float clusterRadiusMin=0.0f, int toFromMapId=-1)
 Post-processing: searches for additional loop closures over the existing graph.
 
bool globalBundleAdjustment (int optimizerType=1, bool rematchFeatures=true, int iterations=0, float pixelVariance=0.0f)
 Runs a global bundle adjustment over the optimized graph.
 
int cleanupLocalGrids (const std::map< int, Transform > &mapPoses, const cv::Mat &map, float xMin, float yMin, float cellSize, int cropRadius=1, bool filterScans=false)
 Filters spurious obstacles from every node's local grid using a reference 2D map.
 
int refineLinks ()
 Re-runs registration on every link of the current graph and updates the ones that converge.
 
bool addLink (const Link &link)
 Adds an external link to the map.
 
cv::Mat getInformation (const cv::Mat &covariance) const
 Converts an odometry covariance into an information matrix, clipping by Memory::getOdomMaxInf() when Parameters::kRGBDLoopCovLimited() is enabled.
 
void addNodesToRepublish (const std::vector< int > &ids)
 Marks node ids whose data should be re-emitted on the next process().
 
void setDummyDictionary (bool enabled=true)
 Loads the visual word dictionary as ids only, without descriptors.
 
int getPathStatus () const
 
void clearPath (int status)
 Clears the current path and sets its terminal status.
 
bool computePath (int targetNode, bool global)
 Plans a path from the current location to node targetNode.
 
bool computePath (const Transform &targetPose, float tolerance=-1.0f)
 Plans a path in the current optimized map toward a metric goal pose.
 
const std::vector< std::pair< int, Transform > > & getPath () const
 
std::vector< std::pair< int, Transform > > getPathNextPoses () const
 
std::vector< int > getPathNextNodes () const
 
int getPathCurrentGoalId () const
 
unsigned int getPathCurrentIndex () const
 
unsigned int getPathCurrentGoalIndex () const
 
const TransformgetPathTransformToGoal () const
 
std::map< int, TransformgetForwardWMPoses (int fromId, int maxNearestNeighbors, float radius, int maxDiffID) const
 Returns optimized poses of WM nodes located in front of fromId.
 
std::map< int, std::map< int, Transform > > getPaths (const std::map< int, Transform > &poses, const Transform &target, int maxGraphDepth=0) const
 Segments a set of optimized poses into paths connected by neighbor links.
 
void adjustLikelihood (std::map< int, float > &likelihood) const
 Applies the standard RTAB-Map likelihood adjustment.
 

Detailed Description

Top-level RTAB-Map SLAM pipeline (mapping, localization and loop closure).

Rtabmap orchestrates the full SLAM iteration. Each new sensor observation passed to process() goes through the steps described below.

1. Memory update

Done via Memory::update(): a new Signature is added to STM, the oldest STM entry is promoted to WM if STM is full, and rehearsal compares the new signature to the previous STM signature.

When the robot barely moved since the previous frame (odometry displacement below Parameters::kRGBDLinearUpdate() and Parameters::kRGBDAngularUpdate()), the iteration is flagged as a "small displacement":

  • If a loop closure or localization was already accepted on a recent iteration, appearance-based global loop-closure detection and proximity detection by space are both skipped to avoid wasting work while the robot is stationary at an already-known location (only retrieval runs).
  • Otherwise (no recent loop closure / localization), both still run normally so a first-time loop closure can still be detected from a standstill.

In either case, at the end of the iteration, if no loop closure, proximity detection or landmark observation latched onto the new node, it is deleted from Memory so the map does not grow while the robot is idle.

Rehearsal still runs first, so visually similar consecutive idle frames may also be merged into the previous STM signature (its weight is incremented and the new signature is discarded) when the similarity exceeds Parameters::kMemRehearsalSimilarity().

2. Loop-closure hypothesis

Scored via Memory::computeLikelihood() and the recursive BayesFilter (prior + observation update).

3. Hypothesis selection

The highest posterior is compared against the loop-closure threshold (Parameters::kRtabmapLoopThr()); if accepted, the loop-closure link is added and the pose graph is re-optimized by Optimizer.

In RGB-D mode, two extra checks must pass before the link is committed:

The optimization used by the consistency check depends on the operating mode:

  • In mapping mode, the local map is re-optimized around the current signature including the new link, then graph::computeMaxGraphErrors() measures the worst per-link residual / its standard deviation. If the ratio exceeds Parameters::kRGBDOptimizeMaxError(), the loop closure(s) added this iteration are removed from Memory.
  • In localization mode, optimization is run on a sub-graph composed of the odometry cache (Parameters::kRGBDMaxOdomCacheSize()), the newly added localization link and pose priors fixing the map nodes (with the variance set from Parameters::kRGBDLocalizationPriorError()). The same error-ratio check is applied; on failure the localization is rejected for this iteration but the persisted map and its links are left untouched.

In both modes, if the same link is rejected twice in a row, a graph repair may also be attempted (within Parameters::kRGBDOptimizeMaxErrorRepairRadius()) to drop the offending link instead of the new candidate.

If either RGB-D check fails, the candidate is discarded and no link is added.

4. Retrieval

Once a loop-closure hypothesis is selected, neighbors of the matched node are brought back from LTM into WM via Memory::reactivateSignatures(), so the next iteration can compare against them too. Up to Parameters::kRtabmapMaxRetrieved() nodes are pulled per iteration; nodes around the current path or local pose may also be retrieved (capped by Parameters::kRGBDMaxLocalRetrieved()).

Retrieval (and the related node immunization) is only active when memory management is enabled, i.e. when Parameters::kRtabmapTimeThr() or Parameters::kRtabmapMemoryThr() is non-zero.

5. Proximity detection (RGB-D mode)

Visual and scan-based local matches to nearby nodes, used in addition to the appearance-based loop closure.

Candidate proximity links go through the same two RGB-D gates as loop closures above: a valid geometric transform must be computed by the registration pipeline, and the transform must not be rejected by the graph-optimization consistency check.

6. Transfer (WM to LTM)

At the end of the iteration, if the iteration exceeded the configured time budget (Parameters::kRtabmapTimeThr()) or WM exceeded its size budget (Parameters::kRtabmapMemoryThr()), Memory::forget() moves the oldest low-frequency signatures from WM to LTM (immunized nodes – retrieved neighbors, the last localization node, etc. – are kept in WM).

Transfer is skipped when both thresholds are 0 (memory management disabled).

7. Map / localization output

Optimized poses, current map correction and statistics are made available to callers via the getters below.

Operating modes

Selected by Parameters::kMemIncrementalMemory() (see Memory::isIncremental()):

  • Mapping: STM and WM grow; loop closures update the optimized graph.
  • Localization: STM/WM are frozen; the current node is matched against the persisted map and only getLastLocalizationPose() is updated.
Path planning

Rtabmap also exposes basic graph-based path planning in RGB-D mode (computePath(), getPath(), getPathStatus()), used by the GUI to navigate between mapped locations.

When memory management is enabled (see step 4 Retrieval and step 6 Transfer), the retrieval step also pulls nodes along the currently planned path back from LTM into WM (capped by Parameters::kRGBDMaxLocalRetrieved()) so the robot is able to re-localize against upcoming waypoints as it follows the path, even when those nodes had been transferred out of WM earlier.

See also
Memory
BayesFilter
Optimizer
Parameters

Definition at line 193 of file Rtabmap.h.

Member Enumeration Documentation

◆ VhStrategy

Loop-closure verification strategy.

Enumerator
kVhNone 

No verification: the highest hypothesis above threshold is accepted.

kVhEpipolar 

Epipolar geometry verification (mostly historical, RGB-only mode).

kVhUndef 

Sentinel – undefined.

Definition at line 197 of file Rtabmap.h.

Member Function Documentation

◆ process() [1/3]

bool rtabmap::Rtabmap::process ( const SensorData data,
Transform  odomPose,
const cv::Mat &  odomCovariance = cv::Mat::eye(6, 6, CV_64FC1),
const std::vector< float > &  odomVelocity = std::vector< float >(),
const std::map< std::string, float > &  externalStats = std::map< std::string, float >() 
)

Main RTAB-Map iteration: ingests one sensor frame and updates the map.

Adds data to Memory, runs the Bayes filter on the current likelihood, selects a loop-closure hypothesis if any, performs proximity detection, re-optimizes the graph as needed, and refreshes getStatistics() and getLastLocalizationPose().

Parameters
dataSensor data for this frame (images, scan, user data, ...).
odomPoseOdometry pose; must be non-null in RGB-D SLAM mode. Pass a null Transform to fall back to appearance-only mode.
odomCovariance6x6 odometry covariance (default: identity).
odomVelocityOptional 6-vector (vx, vy, vz, vroll, vpitch, vyaw).
externalStatsExtra named statistics to record in the database for this iteration.
Returns
True if data was added to the map (i.e. the memory update succeeded).

◆ process() [2/3]

bool rtabmap::Rtabmap::process ( const SensorData data,
Transform  odomPose,
float  odomLinearVariance,
float  odomAngularVariance,
const std::vector< float > &  odomVelocity = std::vector< float >(),
const std::map< std::string, float > &  externalStats = std::map< std::string, float >() 
)

Convenience overload: builds a diagonal covariance from scalar variances.

The 6x6 odometry covariance is constructed as diag(odomLinearVariance, odomLinearVariance, odomLinearVariance, odomAngularVariance, odomAngularVariance, odomAngularVariance).

◆ process() [3/3]

bool rtabmap::Rtabmap::process ( const cv::Mat &  image,
int  id = 0,
const std::map< std::string, float > &  externalStats = std::map< std::string, float >() 
)

Appearance-only convenience overload (loop-closure detection without odometry).

Equivalent to processing image alone, with no odometry pose. Useful for offline loop-closure benchmarking on image sequences.

Parameters
imageRGB or grayscale frame.
idOptional frame id (0 = auto-generated).
externalStatsExtra named statistics to record in the database for this iteration.

◆ init() [1/2]

void rtabmap::Rtabmap::init ( const ParametersMap parameters,
const std::string &  databasePath = "",
bool  loadDatabaseParameters = false 
)

Initializes Rtabmap with parameters and a database.

Parameters
parametersParameters overriding default parameters and database parameters (see loadDatabaseParameters).
databasePathDatabase input/output path. If empty, an in-memory database is used. If set and the file does not exist, it is created empty; if it exists, nodes and the visual word vocabulary are loaded into working memory.
loadDatabaseParametersIf true and an existing database is opened, the parameters stored inside the database are loaded and applied to this Rtabmap instance (then overridden by parameters).

◆ init() [2/2]

void rtabmap::Rtabmap::init ( const std::string &  configFile = "",
const std::string &  databasePath = "",
bool  loadDatabaseParameters = false 
)

Initializes Rtabmap from a configuration file and a database.

Parameters
configFileConfiguration file (*.ini) overriding default parameters and database parameters (see loadDatabaseParameters).
databasePathDatabase input/output path; same semantics as the other init().
loadDatabaseParametersIf true and an existing database is opened, the parameters stored inside the database are loaded and applied first, then overridden by values from configFile.

◆ close()

void rtabmap::Rtabmap::close ( bool  databaseSaved = true,
const std::string &  ouputDatabasePath = "" 
)

Closes Rtabmap and releases the underlying Memory.

Parameters
databaseSavedIf true, the in-memory state is flushed to the database; if false, in-memory changes are discarded.
ouputDatabasePathIf non-empty, the database is copied to this path on close. If a database on disk was initially created/loaded on a different path, it will be updated with the latest changes and renamed to the output path.

◆ getWorkingDir()

const std::string & rtabmap::Rtabmap::getWorkingDir ( ) const
inline
Returns
Working directory used for dumps, log files and temporary outputs.

Definition at line 297 of file Rtabmap.h.

◆ isRGBDMode()

bool rtabmap::Rtabmap::isRGBDMode ( ) const
inline
Returns
True if RGB-D SLAM mode is enabled (Parameters::kRGBDEnabled()).

Definition at line 299 of file Rtabmap.h.

◆ getLoopClosureId()

int rtabmap::Rtabmap::getLoopClosureId ( ) const
inline
Returns
Id of the loop-closure hypothesis accepted at the last process() iteration, or 0 if none.

Definition at line 301 of file Rtabmap.h.

◆ getLoopClosureValue()

float rtabmap::Rtabmap::getLoopClosureValue ( ) const
inline
Returns
Posterior probability of the accepted loop-closure hypothesis, or 0 if none.

Definition at line 303 of file Rtabmap.h.

◆ getHighestHypothesisId()

int rtabmap::Rtabmap::getHighestHypothesisId ( ) const
inline
Returns
Id of the highest-posterior hypothesis at the last iteration (whether or not it was accepted).

Definition at line 305 of file Rtabmap.h.

◆ getHighestHypothesisValue()

float rtabmap::Rtabmap::getHighestHypothesisValue ( ) const
inline
Returns
Posterior of the highest-posterior hypothesis at the last iteration.

Definition at line 307 of file Rtabmap.h.

◆ getLastLocationId()

int rtabmap::Rtabmap::getLastLocationId ( ) const
Returns
Id of the last non-intermediate signature added to the map (0 if none).

◆ getWM()

std::list< int > rtabmap::Rtabmap::getWM ( ) const
Returns
Working memory ids ordered as in Memory::getWorkingMem().

◆ getSTM()

std::set< int > rtabmap::Rtabmap::getSTM ( ) const
Returns
Short-term memory ids.

◆ getWMSize()

int rtabmap::Rtabmap::getWMSize ( ) const
Returns
Working memory size (number of WM signatures).

◆ getSTMSize()

int rtabmap::Rtabmap::getSTMSize ( ) const
Returns
Short-term memory size (number of STM signatures).

◆ getWeights()

std::map< int, int > rtabmap::Rtabmap::getWeights ( ) const
Returns
Per-signature weights (rehearsal counts) for WM and STM.

◆ getTotalMemSize()

int rtabmap::Rtabmap::getTotalMemSize ( ) const
Returns
Total number of signatures across WM, STM and LTM.

◆ getLastProcessTime()

double rtabmap::Rtabmap::getLastProcessTime ( ) const
inline
Returns
Wall-clock duration of the last process() call, in seconds.

Definition at line 323 of file Rtabmap.h.

◆ isInSTM()

bool rtabmap::Rtabmap::isInSTM ( int  locationId) const
Returns
True if locationId is currently in short-term memory.

◆ isIDsGenerated()

bool rtabmap::Rtabmap::isIDsGenerated ( ) const
Returns
True if signature ids are auto-generated (vs. taken from SensorData::id()).

◆ getStatistics()

const Statistics & rtabmap::Rtabmap::getStatistics ( ) const
Returns
Statistics produced by the last process() iteration.

◆ getLocalOptimizedPoses()

const std::map< int, Transform > & rtabmap::Rtabmap::getLocalOptimizedPoses ( ) const
inline
Returns
Optimized poses of the current local map (last graph optimization result).

Definition at line 331 of file Rtabmap.h.

◆ getLocalConstraints()

const std::multimap< int, Link > & rtabmap::Rtabmap::getLocalConstraints ( ) const
inline
Returns
Constraints (links) of the current local map.

Definition at line 333 of file Rtabmap.h.

◆ getPose()

Transform rtabmap::Rtabmap::getPose ( int  locationId) const
Returns
Optimized pose of locationId in the current local map (identity if not present).

◆ getMapCorrection()

Transform rtabmap::Rtabmap::getMapCorrection ( ) const
inline
Returns
Transform mapping odometry frame to the optimized map frame.

This is the correction applied to incoming odometry poses so they align with the latest graph optimization output. Updated whenever a loop closure or proximity detection re-optimizes the graph.

In ROS terms, this corresponds to the standard /map -> /odom TF transform published by SLAM systems: composing it with the live odometry pose (/odom -> /base_link) yields the robot pose in the map frame.

Definition at line 349 of file Rtabmap.h.

◆ getMemory()

const Memory * rtabmap::Rtabmap::getMemory ( ) const
inline
Returns
Owned Memory (may be null before init()).

Definition at line 351 of file Rtabmap.h.

◆ getGoalReachedRadius()

float rtabmap::Rtabmap::getGoalReachedRadius ( ) const
inline
Returns
Radius (meters) under which the current path goal is considered reached.

Definition at line 353 of file Rtabmap.h.

◆ getLocalRadius()

float rtabmap::Rtabmap::getLocalRadius ( ) const
inline
Returns
Local radius (meters) used by proximity detection and path planning queries.

Definition at line 355 of file Rtabmap.h.

◆ getLastLocalizationPose()

const Transform & rtabmap::Rtabmap::getLastLocalizationPose ( ) const
inline
Returns
Last localized pose in the map frame.

In localization mode, this is the corrected odometry pose of the last processed frame. In mapping mode, this is the last pose returned by getLocalOptimizedPoses().

Definition at line 363 of file Rtabmap.h.

◆ getTimeThreshold()

float rtabmap::Rtabmap::getTimeThreshold ( ) const
inline
Returns
Maximum allowed processing time per process() call, in milliseconds.
See also
Parameters::kRtabmapTimeThr()

Definition at line 369 of file Rtabmap.h.

◆ setTimeThreshold()

void rtabmap::Rtabmap::setTimeThreshold ( float  maxTimeAllowed)

Sets the per-iteration time budget (ms).

Drives how aggressively WM is transferred to LTM to keep iterations under the threshold. 0 disables the time bound.

Note
This setting and setMemoryThreshold() are the only two switches that enable RTAB-Map's memory management (WM-to-LTM transfer, retrieval and node immunization). When both are 0, memory management is disabled and all signatures stay in working memory.
See also
Parameters::kRtabmapTimeThr()

◆ getMemoryThreshold()

int rtabmap::Rtabmap::getMemoryThreshold ( ) const
inline
Returns
Maximum allowed WM size (number of signatures).
See also
Parameters::kRtabmapMemoryThr()

Definition at line 388 of file Rtabmap.h.

◆ setMemoryThreshold()

void rtabmap::Rtabmap::setMemoryThreshold ( int  maxMemoryAllowed)

Sets the maximum number of signatures kept in WM (0 = unbounded).

Note
This setting and setTimeThreshold() are the only two switches that enable RTAB-Map's memory management (WM-to-LTM transfer, retrieval and node immunization). When both are 0, memory management is disabled and all signatures stay in working memory.
See also
Parameters::kRtabmapMemoryThr()

◆ setInitialPose()

void rtabmap::Rtabmap::setInitialPose ( const Transform initialPose)

Sets the localization prior pose used to seed the next process() call (localization mode only).

Tells RTAB-Map where the robot is currently located in the map frame, so that the very next call to process() can align incoming odometry with the persisted map without waiting for a loop closure. Typical use cases: restoring localization after a session restart, applying an external pose estimate (e.g. from a GPS or a known starting point), or recovering from "kidnapped robot" situations.

This call only stages state; it does not itself produce a non-identity getMapCorrection(). The alignment between the odometry frame and the map frame is performed on the next process() call, which consumes initialPose together with the incoming odometry pose. Two branches are taken depending on Parameters::kRGBDOptimizeFromGraphEnd():

  • false (default): getMapCorrection() is set so that the live odometry pose is shifted to land on initialPose in the map frame (the optimized map is left untouched).
  • true: every optimized node pose is rigidly transformed so that the map itself moves to align with initialPose (the map correction stays close to identity).

The transform applied is restricted by SLAM dimensionality: 3-DoF (x, y, yaw) for 2D SLAM, 4-DoF (x, y, z, yaw) when gravity is available (IMU orientation or Memory::isOdomGravityUsed()) and Parameters::kOptimizerGravitySigma() is non-zero, full 6-DoF otherwise.

Side effects on the staged state:

  • getLastLocalizationPose() is replaced by initialPose; the localization covariance, the last localization node id and the odometry cache used for loop-closure rejection are all cleared.
  • getMapCorrection() is reset to identity and any backup is cleared.
  • If the current map has not been optimized yet (no entries in getLocalOptimizedPoses()) and a last working signature exists, the map is optimized around that signature so the next process() has something to localize against.

After the next process() consumes the prior, the nearest optimized node to initialPose is recorded as the last localization node.

Parameters
initialPoseRobot pose in the map frame.
Note
No-op (with warning) in mapping mode.
See also
Parameters::kMemIncrementalMemory()
Parameters::kRGBDOptimizeFromGraphEnd()

◆ triggerNewMap()

int rtabmap::Rtabmap::triggerNewMap ( )

Starts a new map session (next process() will create a fresh map id).

In mapping mode, this increments the map id, clears the local optimized graph and resets the Bayes filter. In localization mode, it resets the map correction, the localization node and the odometry cache; if Parameters::kRGBDStartAtOrigin() is enabled, the last localization pose is reset to identity.

Returns
The new map id (mapping mode), or -1 (localization mode).

◆ labelLocation()

bool rtabmap::Rtabmap::labelLocation ( int  id,
const std::string &  label 
)

Assigns or clears a label on signature id.

Returns
True if the label was applied.

◆ setUserData()

bool rtabmap::Rtabmap::setUserData ( int  id,
const cv::Mat &  data 
)

Attaches user data to signature id, compressing it on the fly if needed.

The format is detected automatically: a single-row CV_8UC1 matrix is treated as already-compressed data and stored as-is; anything else is considered raw and compressed before being stored.

Note
If you pass one-dimensional unsigned 8-bit raw data, transpose it so it has multiple rows (not multiple columns), otherwise it will be misdetected as already compressed.
Parameters
idTarget signature id (must be in WM/STM or LTM).
dataRaw or pre-compressed user data.
Returns
True if the data was attached.

◆ generateDOTGraph()

void rtabmap::Rtabmap::generateDOTGraph ( const std::string &  path,
int  id = 0,
int  margin = 5 
)

Writes a Graphviz DOT file of the pose graph.

Parameters
pathOutput file path.
idIf non-zero, root the graph at id; otherwise use the last signature.
marginMaximum graph depth around id to include.

◆ exportPoses()

void rtabmap::Rtabmap::exportPoses ( const std::string &  path,
bool  optimized,
bool  global,
int  format 
)

Exports the current pose graph to a text file.

Forwards to graph::exportPoses() after collecting either the optimized or the raw odometry poses (and the matching constraints when needed).

Parameters
pathOutput file path.
optimizedIf true, export optimized poses; otherwise raw odometry poses.
globalIf true, include nodes from LTM as well; otherwise only WM/STM.
formatOutput format code; see graph::exportPoses() for the full list of supported values (raw, RGBD-SLAM/TUM, KITTI, TORO, g2o, ...).
See also
graph::exportPoses()

◆ resetMemory()

void rtabmap::Rtabmap::resetMemory ( )

Clears all in-memory state and resets the database.

In incremental mode, also clears the persisted map. In read-only memory mode, resets the in-memory state but leaves the database untouched.

◆ getParameters()

const ParametersMap & rtabmap::Rtabmap::getParameters ( ) const
inline
Returns
Current effective parameter map.

Definition at line 526 of file Rtabmap.h.

◆ setWorkingDirectory()

void rtabmap::Rtabmap::setWorkingDirectory ( std::string  path)

Sets the working directory used for dumps, logs and temporary files.

Can also be configured through Parameters::kRtabmapWorkingDirectory() in the parameter map passed to init() or parseParameters().

See also
Parameters::kRtabmapWorkingDirectory()

◆ rejectLastLoopClosure()

void rtabmap::Rtabmap::rejectLastLoopClosure ( )

Removes the loop-closure link added at the last process() iteration.

Looks at the last non-intermediate signature in STM and erases any Link::kGlobalClosure, Link::kLocalSpaceClosure, Link::kLocalTimeClosure or Link::kUserClosure attached to it. The current optimized map is updated accordingly.

◆ deleteLastLocation()

void rtabmap::Rtabmap::deleteLastLocation ( )

Deletes the most recent (non-intermediate) location from the map.

Used by tools to undo the very last process() iteration. In mapping mode, the optimized graph is recomputed without the deleted node.

Note
Locations whose neighbors include intermediate nodes are not supported.

◆ setOptimizedPoses()

void rtabmap::Rtabmap::setOptimizedPoses ( const std::map< int, Transform > &  poses,
const std::multimap< int, Link > &  constraints 
)

Replaces the current optimized poses and constraints with externally provided ones.

Useful when graph optimization is performed outside of Rtabmap.

Warning
No consistency check is performed against the current Memory state: poses and constraints overwrite the internal containers verbatim. The caller is responsible for ensuring that every id in poses (and every endpoint of every link in constraints) belongs to a signature currently in STM or WM (see Memory::isInSTM() / Memory::isInWM()). Passing poses for ids that are no longer loaded will leave dangling entries that may confuse subsequent process() calls.

◆ getSignatureCopy()

Signature rtabmap::Rtabmap::getSignatureCopy ( int  id,
bool  images,
bool  scan,
bool  userData,
bool  occupancyGrid,
bool  withWords,
bool  withGlobalDescriptors 
) const

Returns a copy of signature id with optional payloads attached.

Loads from WM/STM if present, otherwise from LTM. Selectively populates the returned Signature with images, scan, user data, occupancy grid, visual words and global descriptors.

◆ getGraph()

void rtabmap::Rtabmap::getGraph ( std::map< int, Transform > &  poses,
std::multimap< int, Link > &  constraints,
bool  optimized,
bool  global,
std::map< int, Signature > *  signatures = 0,
bool  withImages = false,
bool  withScan = false,
bool  withUserData = false,
bool  withGrid = false,
bool  withWords = true,
bool  withGlobalDescriptors = true 
) const

Extracts a full snapshot of the current pose graph.

Parameters
posesOutput: pose for every selected node.
constraintsOutput: links between selected nodes.
optimizedIf true, return optimized poses; otherwise raw odometry poses.
globalIf true, include nodes from LTM as well; otherwise only WM/STM.
signaturesOptional output: a copy of each node's Signature (with the payloads requested by the with* flags).
withImagesAttach compressed RGB/depth images to signatures.
withScanAttach laser scan blob.
withUserDataAttach user data blob.
withGridAttach occupancy grid cells.
withWordsAttach visual words (id, keypoints, 3D points, descriptors).
withGlobalDescriptorsAttach global descriptors.

◆ getNodesInRadius() [1/2]

std::map< int, Transform > rtabmap::Rtabmap::getNodesInRadius ( const Transform pose,
float  radius,
int  k = 0,
std::map< int, float > *  distsSqr = 0 
)

Returns optimized poses within a metric radius of pose.

Parameters
poseQuery pose in the map frame.
radiusSearch radius in meters (0 falls back to Parameters::kRGBDLocalRadius()).
kIf non-zero, also cap the result to the k nearest neighbors.
distsSqrOptional output: per-id squared distance to pose.
Returns
Nodes (and possibly landmarks) within the radius, mapped to their pose. Landmarks have a negative id.

◆ getNodesInRadius() [2/2]

std::map< int, Transform > rtabmap::Rtabmap::getNodesInRadius ( int  nodeId,
float  radius,
int  k = 0,
std::map< int, float > *  distsSqr = 0 
)

Returns optimized poses within a metric radius of node nodeId.

Parameters
nodeIdQuery node id. Pass 0 to query around the latest node. A negative id requests neighbors of the corresponding landmark.
radiusSearch radius in meters (0 falls back to Parameters::kRGBDLocalRadius()).
kIf non-zero, cap the result to the k nearest neighbors.
distsSqrOptional output: per-id squared distance to nodeId.
Returns
Nodes (and possibly landmarks) within the radius.

◆ detectMoreLoopClosures()

int rtabmap::Rtabmap::detectMoreLoopClosures ( float  clusterRadiusMax = 0.5f,
float  clusterAngle = M_PI/6.0f,
int  iterations = 1,
bool  intraSession = true,
bool  interSession = true,
const ProgressState state = 0,
float  clusterRadiusMin = 0.0f,
int  toFromMapId = -1 
)

Post-processing: searches for additional loop closures over the existing graph.

Clusters nearby optimized poses and runs registration between candidates that are not yet linked. New links are added to Memory and the graph is re-optimized.

Note
The registration approach used here is the one configured in Memory via Parameters::kRegStrategy() (0=Vis, 1=Icp, 2=VisIcp), so the quality and sensor requirements of this pass mirror the live loop-closure pipeline.
Candidate cluster pairs whose ids differ by less than Parameters::kMemSTMSize(), or that are already reachable from each other within that many graph hops, are filtered out. This prevents trivial "loop closures" between temporally or topologically adjacent nodes.
Parameters
clusterRadiusMaxMaximum metric distance (m) between two candidate nodes.
clusterAngleMaximum angular distance (rad) between two candidate nodes.
iterationsNumber of refinement passes.
intraSessionInclude loop closures within the same map session.
interSessionInclude loop closures between different map sessions.
stateOptional progress sink; cancellation requests are honored.
clusterRadiusMinMinimum metric distance (m); pairs closer than this are considered already linked through neighbor links.
toFromMapIdIf >=0, restrict candidate pairs to nodes belonging to this map id.
Returns
Number of loop closures added, or -1 on error (e.g. not in RGB-D mode, no optimizer iterations).

◆ globalBundleAdjustment()

bool rtabmap::Rtabmap::globalBundleAdjustment ( int  optimizerType = 1,
bool  rematchFeatures = true,
int  iterations = 0,
float  pixelVariance = 0.0f 
)

Runs a global bundle adjustment over the optimized graph.

Parameters
optimizerTypeBackend optimizer (e.g. 1=g2o); availability depends on what RTAB-Map was built with.
rematchFeaturesIf true, re-match visual features between connected nodes before BA (otherwise reuse existing word-id correspondences).
iterationsSolver iterations (0 falls back to Parameters::kOptimizerIterations()).
pixelVariancePixel reprojection variance used by the cost (0 falls back to Parameters::kOptimizerPixelVariance()).
Returns
True if BA was run and improved poses were stored.

◆ cleanupLocalGrids()

int rtabmap::Rtabmap::cleanupLocalGrids ( const std::map< int, Transform > &  mapPoses,
const cv::Mat &  map,
float  xMin,
float  yMin,
float  cellSize,
int  cropRadius = 1,
bool  filterScans = false 
)

Filters spurious obstacles from every node's local grid using a reference 2D map.

Thin wrapper around Memory::cleanupLocalGrids(); see that method for the exact filtering rule and the meaning of cropRadius and filterScans.

Returns
Number of (node, grid or scan) modifications, or -1 on error.

◆ refineLinks()

int rtabmap::Rtabmap::refineLinks ( )

Re-runs registration on every link of the current graph and updates the ones that converge.

Useful after parameter changes to refresh stored transforms.

Note
The registration approach is the one configured in Memory via Parameters::kRegStrategy() (0=Vis, 1=Icp, 2=VisIcp). For each link, the link's existing relative transform (the constraint produced by the current optimized local graph) is passed as the initial guess to Memory::computeTransform(), so links already close to convergence are refined locally rather than re-estimated from scratch.
Returns
Number of links refined, or -1 if not in RGB-D mode.

◆ addLink()

bool rtabmap::Rtabmap::addLink ( const Link link)

Adds an external link to the map.

The link's "from" and "to" endpoints must exist in memory (incremental mode) or in the optimized poses (localization mode). RGB-D mode only.

Returns
True if the link was added.

◆ addNodesToRepublish()

void rtabmap::Rtabmap::addNodesToRepublish ( const std::vector< int > &  ids)

Marks node ids whose data should be re-emitted on the next process().

The requested signatures are attached to the Statistics object produced by the next process() call (via the same mechanism as the regular "last signature data"), so consumers reading getStatistics() pick them up alongside the normal output. Up to Parameters::kRtabmapMaxRepublished() ids are emitted per iteration; any leftover ids stay queued for subsequent iterations until they are republished or fall out of the current graph.

Pass an empty vector to clear the request set. Requires Parameters::kRtabmapMaxRepublished() > 0 and Parameters::kRtabmapPublishLastSignature() = true.

◆ setDummyDictionary()

void rtabmap::Rtabmap::setDummyDictionary ( bool  enabled = true)

Loads the visual word dictionary as ids only, without descriptors.

With a dummy dictionary, init() populates VWDictionary with placeholder VisualWord objects carrying an empty descriptor, and the dictionary update (FLANN index construction) is skipped. This makes opening a large database much faster and lighter in RAM when the word descriptors are not needed, e.g. to inspect or post-process an existing map rather than to localize in it.

The dummy dictionary is silently disabled if the database has no words, or if the dictionary has to be rebuilt from the nodes because it was not saved properly.

Parameters
enabledTrue to load ids only, false to load the full dictionary (default).
Note
Must be called before init(); an error is logged and the call ignored once the memory exists.
Warning
Incompatible with mapping: adding new nodes asserts in Memory::createSignature(). Loop closure detection also cannot match new observations against a descriptor-less dictionary.
See also
Memory::setDummyDictionary()

◆ getPathStatus()

int rtabmap::Rtabmap::getPathStatus ( ) const
inline
Returns
Current path status: -1 = failed, 0 = idle / executing, 1 = success.

Definition at line 776 of file Rtabmap.h.

◆ clearPath()

void rtabmap::Rtabmap::clearPath ( int  status)

Clears the current path and sets its terminal status.

Parameters
status-1 = failed, 0 = idle / executing, 1 = success.

◆ computePath() [1/2]

bool rtabmap::Rtabmap::computePath ( int  targetNode,
bool  global 
)

Plans a path from the current location to node targetNode.

RGB-D mode only (requires Parameters::kRGBDEnabled() = true).

Parameters
targetNodeDestination node id (positive) or landmark id (negative).
globalIf true, also search nodes in LTM; otherwise only the current optimized map.
Returns
True if a path was computed; the result is available via getPath().
See also
Parameters::kRGBDEnabled()

◆ computePath() [2/2]

bool rtabmap::Rtabmap::computePath ( const Transform targetPose,
float  tolerance = -1.0f 
)

Plans a path in the current optimized map toward a metric goal pose.

Parameters
targetPoseGoal pose in the map frame.
toleranceGoal-acceptance tolerance (meters). A negative value falls back to Parameters::kRGBDLocalRadius(); 0 means infinite tolerance.
Returns
True if a path was computed.

◆ getPath()

const std::vector< std::pair< int, Transform > > & rtabmap::Rtabmap::getPath ( ) const
inline
Returns
The currently planned path as a sequence of (node id, pose) waypoints.

Definition at line 805 of file Rtabmap.h.

◆ getPathNextPoses()

std::vector< std::pair< int, Transform > > rtabmap::Rtabmap::getPathNextPoses ( ) const
Returns
Upcoming waypoints (from the current path index onward).

◆ getPathNextNodes()

std::vector< int > rtabmap::Rtabmap::getPathNextNodes ( ) const
Returns
Upcoming node ids (from the current path index onward).

◆ getPathCurrentGoalId()

int rtabmap::Rtabmap::getPathCurrentGoalId ( ) const
Returns
Id of the current intermediate path goal (the node currently being chased).

◆ getPathCurrentIndex()

unsigned int rtabmap::Rtabmap::getPathCurrentIndex ( ) const
inline
Returns
Index of the current waypoint in getPath().

Definition at line 813 of file Rtabmap.h.

◆ getPathCurrentGoalIndex()

unsigned int rtabmap::Rtabmap::getPathCurrentGoalIndex ( ) const
inline
Returns
Index of the current intermediate goal in getPath().

Definition at line 815 of file Rtabmap.h.

◆ getPathTransformToGoal()

const Transform & rtabmap::Rtabmap::getPathTransformToGoal ( ) const
inline
Returns
Transform from the final waypoint pose to the requested goal pose.

Definition at line 817 of file Rtabmap.h.

◆ getForwardWMPoses()

std::map< int, Transform > rtabmap::Rtabmap::getForwardWMPoses ( int  fromId,
int  maxNearestNeighbors,
float  radius,
int  maxDiffID 
) const

Returns optimized poses of WM nodes located in front of fromId.

Candidates are first gathered around fromId, then STM nodes are excluded, the survivors are cropped to a forward-facing box of width radius (1 m behind, radius ahead, +/-radius laterally), and a KdTree radius search keeps the maxNearestNeighbors closest poses in that box.

Note
Mapping vs. localization mode differs only in how the initial candidate set is built:
  • In mapping mode (incremental), candidates are produced by a graph-radius walk from fromId: nodes reachable within maxDiffID graph hops AND within radius meters in the optimized poses.
  • In localization mode, the graph-hop restriction is ignored: every optimized pose within radius meters of fromId is considered. The forward-box crop and KdTree radius search that follow are identical in both modes.
Parameters
fromIdReference node (must be in Memory and getLocalOptimizedPoses()).
maxNearestNeighborsCap on the number of nodes returned.
radiusMaximum metric distance from fromId (meters).
maxDiffIDMaximum graph depth from fromId in mapping mode (0 = unlimited). Ignored in localization mode.

◆ getPaths()

std::map< int, std::map< int, Transform > > rtabmap::Rtabmap::getPaths ( const std::map< int, Transform > &  poses,
const Transform target,
int  maxGraphDepth = 0 
) const

Segments a set of optimized poses into paths connected by neighbor links.

Designed to be called on the result of a radius search around target (a set of poses already constrained to be metrically close to the goal). Within that radius, the method partitions the poses into one or more "paths" where each path is a connected component reachable from its starting node using only neighbor (sequential) links – loop-closure links, landmark links and intermediate nodes are not used to traverse between members. Paths are produced one at a time, each starting from the still-unclaimed pose nearest to target; a candidate is added to the current path only if it has at least one neighbor link to a node already in the path.

Used internally by proximity detection by space (see Parameters::kRGBDProximityBySpace()) in two independent stages, each iterating over the segmented paths:

  • One-to-one (visual registration): runs registration between the current node and at most one node per neighbor-connected path, avoiding redundant attempts against nearby members of the same local trajectory.
  • One-to-many (scan matching, enabled when Parameters::kRGBDProximityPathMaxNeighbors() > 0): on each path, neighboring nodes are assembled around the nearest pose on the path (up to the configured count, walked forward and backward) and their laser scans are merged for an ICP registration against the current scan. The neighbor-link-only structure of each path is what makes this assembly geometrically consistent.
Parameters
posesCandidate nodes with their optimized poses (typically pre-filtered to a radius around target).
targetReference pose used to order paths: each path's starting node is the still-unclaimed pose closest to target.
maxGraphDepthMaximum graph depth traversed from the starting node when gathering candidates for a path (0 = unlimited).
Returns
Map from the starting node id of each path to its (node id -> pose) chain.

◆ adjustLikelihood()

void rtabmap::Rtabmap::adjustLikelihood ( std::map< int, float > &  likelihood) const

Applies the standard RTAB-Map likelihood adjustment.

Normalizes raw likelihoods using mean and standard deviation across non-null values. Real-place entries with value <= mean + stdDev are clamped to 1.0; only entries above that threshold are scaled. The virtual place (the first key in likelihood, representing the "new place" hypothesis) is then set so that its likelihood reflects how peaked the real distribution is.

The exact formulas are selected by Parameters::kRtabmapVirtualPlaceLikelihoodRatio() (default 0, Angeli PhD formulation):

  • Ratio = 0 (mean / std-dev formulation):
    • Real place above threshold: (value - (stdDev - epsilon)) / mean
    • Virtual place: mean / stdDev + 1 (when stdDev is non-trivial and a maximum exists; otherwise 2). The virtual place "wins" when the real-place distribution is flat (small stdDev relative to mean).
  • Ratio != 0 (z-score formulation):
    • Real place above threshold: (value - mean) / stdDev (i.e. the z-score).
    • Virtual place: stdDev / (max - mean) + 1 (when max > mean; otherwise 2). The virtual place "wins" when no real candidate stands out far above the mean.

In both formulations a low virtual-place likelihood favors a real-place loop closure on the next Bayes update; a high one favors the "new place" hypothesis.

See also
Parameters::kRtabmapVirtualPlaceLikelihoodRatio()

The documentation for this class was generated from the following file: