Compare commits

..
Author SHA1 Message Date
matlabbe 85112c2cdf add pull request template 2024-03-16 21:45:05 -07:00
matlabbe 8657e18bda update config 2024-03-16 21:27:50 -07:00
matlabbe 578bf0ed8f Try with pre-commit default usage 2024-03-16 21:06:00 -07:00
matlabbe 9f230f5b28 Adding pre-commit checks 2024-03-16 20:26:56 -07:00
219 changed files with 10269 additions and 17874 deletions
-8
View File
@@ -1,8 +0,0 @@
{
"image": "introlab3it/rtabmap:android-deps",
"customizations": {
"vscode": {
"extensions": ["ms-vscode.cpptools-themes", "ms-vscode.cmake-tools", "vscjava.vscode-java-pack"]
}
}
}
-8
View File
@@ -1,8 +0,0 @@
{
"image": "introlab3it/rtabmap:18.04",
"customizations": {
"vscode": {
"extensions": ["ms-vscode.cpptools-themes", "ms-vscode.cmake-tools"]
}
}
}
@@ -2,7 +2,7 @@
"image": "introlab3it/rtabmap:20.04", "image": "introlab3it/rtabmap:20.04",
"customizations": { "customizations": {
"vscode": { "vscode": {
"extensions": ["ms-vscode.cpptools-themes", "ms-vscode.cmake-tools"] "extensions": ["ms-vscode.cpptools-themes", "ms-vscode.cmake-tools", "vscjava.vscode-java-pack"]
} }
} }
} }
-8
View File
@@ -1,8 +0,0 @@
{
"image": "introlab3it/rtabmap:22.04",
"customizations": {
"vscode": {
"extensions": ["ms-vscode.cpptools-themes", "ms-vscode.cmake-tools"]
}
}
}
-8
View File
@@ -1,8 +0,0 @@
{
"image": "introlab3it/rtabmap:24.04",
"customizations": {
"vscode": {
"extensions": ["ms-vscode.cpptools-themes", "ms-vscode.cmake-tools"]
}
}
}
+7
View File
@@ -0,0 +1,7 @@
## Description
Please include a summary of the change and which issue is fixed (if any).
## Checklist:
- [ ] Did `pre-commit run --all-files` locally to fix any pre-commit failures on CI.
-3
View File
@@ -31,9 +31,6 @@ jobs:
os: ubuntu-22.04 os: ubuntu-22.04
- ros_distribution: 'iron' - ros_distribution: 'iron'
os: ubuntu-22.04 os: ubuntu-22.04
# Currently CI has some errors on setup-ros with this OS, disabling for now
#- ros_distribution: 'jazzy'
# os: ubuntu-24.04
steps: steps:
- uses: ros-tooling/[email protected] - uses: ros-tooling/[email protected]
+1 -1
View File
@@ -18,7 +18,7 @@ jobs:
strategy: strategy:
fail-fast: false fail-fast: false
matrix: matrix:
os: [ubuntu-24.04, ubuntu-22.04, ubuntu-20.04] os: [ubuntu-22.04, ubuntu-20.04]
steps: steps:
- name: Install dependencies - name: Install dependencies
+2 -21
View File
@@ -12,7 +12,7 @@ jobs:
strategy: strategy:
fail-fast: false fail-fast: false
matrix: matrix:
docker_tag: [focal-deps, jammy-deps, jammy-iron-deps, noble-deps] docker_tag: [focal-deps, jammy-deps, jammy-iron-deps]
include: include:
- docker_tag: focal-deps - docker_tag: focal-deps
docker_tags: | docker_tags: |
@@ -20,7 +20,6 @@ jobs:
docker_platforms: | docker_platforms: |
linux/amd64 linux/amd64
linux/arm64 linux/arm64
linux/arm/v7
docker_path: 'focal/deps' docker_path: 'focal/deps'
- docker_tag: jammy-deps - docker_tag: jammy-deps
docker_tags: | docker_tags: |
@@ -35,13 +34,6 @@ jobs:
docker_platforms: | docker_platforms: |
linux/amd64 linux/amd64
docker_path: 'jammy-iron/deps' docker_path: 'jammy-iron/deps'
- docker_tag: noble-deps
docker_tags: |
introlab3it/rtabmap:noble-deps
docker_platforms: |
linux/amd64
linux/arm64
docker_path: 'noble/deps'
steps: steps:
- -
@@ -80,7 +72,7 @@ jobs:
strategy: strategy:
fail-fast: false fail-fast: false
matrix: matrix:
docker_tag: [bionic, focal, jammy, jammy-iron, noble, android23, android24, android26, android30] docker_tag: [bionic, focal, jammy, jammy-iron, android23, android24, android26, android30]
include: include:
- docker_tag: bionic - docker_tag: bionic
docker_tags: | docker_tags: |
@@ -102,7 +94,6 @@ jobs:
docker_platforms: | docker_platforms: |
linux/amd64 linux/amd64
linux/arm64 linux/arm64
linux/arm/v7
docker_path: 'focal' docker_path: 'focal'
- docker_tag: jammy - docker_tag: jammy
docker_tags: | docker_tags: |
@@ -122,16 +113,6 @@ jobs:
docker_platforms: | docker_platforms: |
linux/amd64 linux/amd64
docker_path: 'jammy-iron' docker_path: 'jammy-iron'
- docker_tag: noble
docker_tags: |
introlab3it/rtabmap:noble
introlab3it/rtabmap:24.04
docker_args: |
NOT_USED=0
docker_platforms: |
linux/amd64
linux/arm64
docker_path: 'noble'
- docker_tag: android23 - docker_tag: android23
docker_tags: | docker_tags: |
introlab3it/rtabmap:android23 introlab3it/rtabmap:android23
+16
View File
@@ -0,0 +1,16 @@
name: pre-commit
on:
pull_request:
branches:
- '**'
push:
branches: [master]
jobs:
pre-commit:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-python@v3
- uses: pre-commit/[email protected]
-16
View File
@@ -1,16 +0,0 @@
name: RTAB-Map Scheduled Stats Extraction From GitHub
on:
workflow_dispatch:
schedule:
- cron: '0 5 * * *'
jobs:
get_stats:
runs-on: ubuntu-latest
steps:
- name: Update Stats
uses: introlab/github-stats-action@v1
with:
github-stats-token: ${{ secrets.STATS_TOKEN }}
google-application-credentials: ${{ secrets.GOOGLE_APPLICATION_CREDENTIALS }}
spreadsheet-id: ${{ secrets.SPREADSHEET_ID }}
+31
View File
@@ -0,0 +1,31 @@
# See https://pre-commit.com for more information
# See https://pre-commit.com/hooks.html for more hooks
exclude: '^build/|^data/|^app/|^archive/|^cmake_modules/|^\..*'
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v3.2.0
hooks:
- id: trailing-whitespace
- id: end-of-file-fixer
- id: check-yaml
- id: check-added-large-files
- repo: https://github.com/cheshirekow/cmake-format-precommit
rev: v0.6.10
hooks:
- id: cmake-format
- id: cmake-lint
- repo: https://github.com/pryorda/dockerfilelint-precommit-hooks
rev: v0.1.0
hooks:
- id: dockerfilelint
- repo: https://github.com/pre-commit/mirrors-clang-format
rev: v18.1.1
hooks:
- id: clang-format
args: ["-style=Google", "-i"]
+15 -56
View File
@@ -1,5 +1,5 @@
# Top-Level CmakeLists.txt # Top-Level CmakeLists.txt
cmake_minimum_required(VERSION 3.14) cmake_minimum_required(VERSION 3.10)
PROJECT( RTABMap ) PROJECT( RTABMap )
SET(PROJECT_PREFIX rtabmap) SET(PROJECT_PREFIX rtabmap)
@@ -20,7 +20,7 @@ SET(CMAKE_MODULE_PATH "${PROJECT_SOURCE_DIR}/cmake_modules")
####################### #######################
SET(RTABMAP_MAJOR_VERSION 0) SET(RTABMAP_MAJOR_VERSION 0)
SET(RTABMAP_MINOR_VERSION 21) SET(RTABMAP_MINOR_VERSION 21)
SET(RTABMAP_PATCH_VERSION 5) SET(RTABMAP_PATCH_VERSION 4)
SET(RTABMAP_VERSION SET(RTABMAP_VERSION
${RTABMAP_MAJOR_VERSION}.${RTABMAP_MINOR_VERSION}.${RTABMAP_PATCH_VERSION}) ${RTABMAP_MAJOR_VERSION}.${RTABMAP_MINOR_VERSION}.${RTABMAP_PATCH_VERSION})
@@ -181,7 +181,6 @@ option(WITH_FREENECT "Include Freenect support" ON)
option(WITH_FREENECT2 "Include Freenect2 support" ON) option(WITH_FREENECT2 "Include Freenect2 support" ON)
option(WITH_K4W2 "Include Kinect for Windows v2 support" ON) option(WITH_K4W2 "Include Kinect for Windows v2 support" ON)
option(WITH_K4A "Include Kinect for Azure support" ON) option(WITH_K4A "Include Kinect for Azure support" ON)
option(WITH_OPENNI "Include OpenNI support" ON)
option(WITH_OPENNI2 "Include OpenNI2 support" ON) option(WITH_OPENNI2 "Include OpenNI2 support" ON)
option(WITH_DC1394 "Include dc1394 support" ON) option(WITH_DC1394 "Include dc1394 support" ON)
option(WITH_G2O "Include g2o support" ON) option(WITH_G2O "Include g2o support" ON)
@@ -204,7 +203,6 @@ option(WITH_REALSENSE_SLAM "Include RealSenseSlam support" ON)
option(WITH_REALSENSE2 "Include RealSense support" ON) option(WITH_REALSENSE2 "Include RealSense support" ON)
option(WITH_MYNTEYE "Include mynteye-s support" ON) option(WITH_MYNTEYE "Include mynteye-s support" ON)
option(WITH_DEPTHAI "Include depthai-core support" OFF) option(WITH_DEPTHAI "Include depthai-core support" OFF)
option(WITH_XVSDK "Include XVisio SDK support" OFF)
option(WITH_OCTOMAP "Include OctoMap support" ON) option(WITH_OCTOMAP "Include OctoMap support" ON)
option(WITH_GRIDMAP "Include GridMap support" ON) option(WITH_GRIDMAP "Include GridMap support" ON)
option(WITH_CPUTSDF "Include CPUTSDF support" OFF) option(WITH_CPUTSDF "Include CPUTSDF support" OFF)
@@ -254,10 +252,10 @@ endif()
FIND_PACKAGE(ZLIB REQUIRED QUIET) FIND_PACKAGE(ZLIB REQUIRED QUIET)
FIND_PACKAGE(SQLite3 QUIET) FIND_PACKAGE(Sqlite3 QUIET)
IF(SQLite3_FOUND) IF(Sqlite3_FOUND)
MESSAGE(STATUS "Found SQLite3: ${SQLite3_INCLUDE_DIRS} ${SQLite3_LIBRARIES}") MESSAGE(STATUS "Found Sqlite3: ${Sqlite3_INCLUDE_DIRS} ${Sqlite3_LIBRARIES}")
ENDIF(SQLite3_FOUND) ENDIF(Sqlite3_FOUND)
if(NOT "${PCL_LIBRARIES}" STREQUAL "") if(NOT "${PCL_LIBRARIES}" STREQUAL "")
# fix libproj.so not found on Xenial # fix libproj.so not found on Xenial
@@ -541,11 +539,6 @@ IF(WITH_POINTMATCHER)
message(STATUS "libnabo found, version ${libnabo_VERSION} (Config mode)") message(STATUS "libnabo found, version ${libnabo_VERSION} (Config mode)")
SET(libpointmatcher_LIBRARIES "${libpointmatcher_LIBRARIES};libnabo::nabo") SET(libpointmatcher_LIBRARIES "${libpointmatcher_LIBRARIES};libnabo::nabo")
ENDIF(value EQUAL -1) ENDIF(value EQUAL -1)
string(FIND "${libpointmatcher_LIBRARIES}" "yaml-cpp::yaml-cpp" value)
IF(NOT value EQUAL -1)
# Find yaml-cpp (Issue #1268):
find_package(yaml-cpp QUIET)
ENDIF(NOT value EQUAL -1)
ENDIF(libpointmatcher_FOUND) ENDIF(libpointmatcher_FOUND)
ENDIF(WITH_POINTMATCHER) ENDIF(WITH_POINTMATCHER)
@@ -658,19 +651,12 @@ IF(WITH_MYNTEYE)
ENDIF(WITH_MYNTEYE) ENDIF(WITH_MYNTEYE)
IF(WITH_DEPTHAI) IF(WITH_DEPTHAI)
FIND_PACKAGE(depthai 2.24 QUIET) FIND_PACKAGE(depthai 2 QUIET)
IF(depthai_FOUND) IF(depthai_FOUND)
MESSAGE(STATUS "Found depthai-core (targets)") MESSAGE(STATUS "Found depthai-core (targets)")
ENDIF(depthai_FOUND) ENDIF(depthai_FOUND)
ENDIF(WITH_DEPTHAI) ENDIF(WITH_DEPTHAI)
IF(WITH_XVSDK)
FIND_PACKAGE(xvsdk QUIET)
IF(xvsdk_FOUND)
MESSAGE(STATUS "Found xvsdk (targets)")
ENDIF(xvsdk_FOUND)
ENDIF(WITH_XVSDK)
IF(WITH_OCTOMAP) IF(WITH_OCTOMAP)
FIND_PACKAGE(octomap QUIET) FIND_PACKAGE(octomap QUIET)
IF(octomap_FOUND) IF(octomap_FOUND)
@@ -965,9 +951,6 @@ ELSE()
) )
ENDIF(WIN32) ENDIF(WIN32)
ENDIF() ENDIF()
IF(NOT (OpenNI_FOUND AND WITH_OPENNI))
SET(OPENNI "//")
ENDIF()
IF(NOT OpenNI2_FOUND) IF(NOT OpenNI2_FOUND)
SET(OPENNI2 "//") SET(OPENNI2 "//")
ENDIF() ENDIF()
@@ -1012,12 +995,6 @@ IF(NOT depthai_FOUND)
ELSE() ELSE()
SET(CONF_WITH_DEPTH_AI 1) SET(CONF_WITH_DEPTH_AI 1)
ENDIF() ENDIF()
IF(NOT xvsdk_FOUND)
SET(XVSDK "//")
SET(CONF_WITH_XVSDK 0)
ELSE()
SET(CONF_WITH_XVSDK 1)
ENDIF()
IF(NOT octomap_FOUND) IF(NOT octomap_FOUND)
SET(OCTOMAP "//") SET(OCTOMAP "//")
SET(CONF_WITH_OCTOMAP 0) SET(CONF_WITH_OCTOMAP 0)
@@ -1093,16 +1070,14 @@ IF(ANDROID)
IF(BUILD_APP) IF(BUILD_APP)
ADD_SUBDIRECTORY( app ) ADD_SUBDIRECTORY( app )
ENDIF(BUILD_APP) ENDIF(BUILD_APP)
ELSEIF(WITH_QT) ELSEIF(Qt6_FOUND OR Qt5_FOUND OR (QT4_FOUND AND QT_QTCORE_FOUND AND QT_QTGUI_FOUND))
IF(Qt6_FOUND OR Qt5_FOUND OR (QT4_FOUND AND QT_QTCORE_FOUND AND QT_QTGUI_FOUND))
ADD_SUBDIRECTORY( guilib ) ADD_SUBDIRECTORY( guilib )
IF(BUILD_APP) IF(BUILD_APP)
ADD_SUBDIRECTORY( app ) ADD_SUBDIRECTORY( app )
ENDIF(BUILD_APP) ENDIF(BUILD_APP)
ELSE() ELSEIF(WITH_QT)
MESSAGE(WARNING "Qt not found, the GUI lib and the stand-alone application will not be compiled...") MESSAGE(WARNING "Qt not found, the GUI lib and the stand-alone application will not be compiled...")
ENDIF() ENDIF()
ENDIF()
IF(BUILD_TOOLS) IF(BUILD_TOOLS)
ADD_SUBDIRECTORY( tools ) ADD_SUBDIRECTORY( tools )
@@ -1129,7 +1104,7 @@ ENDIF()
#### ####
add_library(rtabmap INTERFACE) add_library(rtabmap INTERFACE)
add_library(rtabmap::rtabmap ALIAS rtabmap) add_library(rtabmap::rtabmap ALIAS rtabmap)
IF(WITH_QT AND (QT4_FOUND OR Qt5_FOUND OR Qt6_FOUND)) IF(QT4_FOUND OR Qt5_FOUND OR Qt6_FOUND)
set(CONF_WITH_GUI ON) set(CONF_WITH_GUI ON)
IF(QT4_FOUND) IF(QT4_FOUND)
set(CONF_QT_VERSION 4) set(CONF_QT_VERSION 4)
@@ -1341,13 +1316,13 @@ IF(OpenCV_FOUND)
ENDIF() ENDIF()
ENDIF(OpenCV_FOUND) ENDIF(OpenCV_FOUND)
IF(WITH_QT AND QT4_FOUND) IF(QT4_FOUND)
MESSAGE(STATUS " With Qt4 = YES (License: Open Source or Commercial)") MESSAGE(STATUS " With Qt4 = YES (License: Open Source or Commercial)")
MESSAGE(STATUS " With VTK ${VTK_MAJOR_VERSION}.${VTK_MINOR_VERSION} = YES (License: BSD)") MESSAGE(STATUS " With VTK ${VTK_MAJOR_VERSION}.${VTK_MINOR_VERSION} = YES (License: BSD)")
ELSEIF(WITH_QT AND Qt5_FOUND) ELSEIF(Qt5_FOUND)
MESSAGE(STATUS " With Qt ${Qt5_VERSION} = YES (License: Open Source or Commercial)") MESSAGE(STATUS " With Qt ${Qt5_VERSION} = YES (License: Open Source or Commercial)")
MESSAGE(STATUS " With VTK ${VTK_MAJOR_VERSION}.${VTK_MINOR_VERSION} = YES (License: BSD)") MESSAGE(STATUS " With VTK ${VTK_MAJOR_VERSION}.${VTK_MINOR_VERSION} = YES (License: BSD)")
ELSEIF(WITH_QT AND Qt6_FOUND) ELSEIF(Qt6_FOUND)
MESSAGE(STATUS " With Qt ${Qt6_VERSION} = YES (License: Open Source or Commercial)") MESSAGE(STATUS " With Qt ${Qt6_VERSION} = YES (License: Open Source or Commercial)")
MESSAGE(STATUS " With VTK ${VTK_MAJOR_VERSION}.${VTK_MINOR_VERSION} = YES (License: BSD)") MESSAGE(STATUS " With VTK ${VTK_MAJOR_VERSION}.${VTK_MINOR_VERSION} = YES (License: BSD)")
@@ -1357,10 +1332,10 @@ ELSE()
MESSAGE(STATUS " With Qt = NO (Qt not found)") MESSAGE(STATUS " With Qt = NO (Qt not found)")
ENDIF() ENDIF()
IF(SQLite3_FOUND) IF(Sqlite3_FOUND)
MESSAGE(STATUS " With external SQLite3 = YES (License: Public Domain)") MESSAGE(STATUS " With external SQLite3 = YES (License: Public Domain)")
ELSE() ELSE()
MESSAGE(STATUS " With external SQLite3 = NO (SQLite3 not found, internal version is used for convenience)") MESSAGE(STATUS " With external SQLite3 = NO (sqlite3 not found, internal version is used for convenience)")
ENDIF() ENDIF()
IF(WITH_ORB_OCTREE) IF(WITH_ORB_OCTREE)
@@ -1551,14 +1526,6 @@ ELSE()
MESSAGE(STATUS " With Freenect = NO (libfreenect not found)") MESSAGE(STATUS " With Freenect = NO (libfreenect not found)")
ENDIF() ENDIF()
IF(WITH_OPENNI AND OpenNI_FOUND)
MESSAGE(STATUS " With OpenNI = YES (License: Apache v2)")
ELSEIF(NOT WITH_OPENNI)
MESSAGE(STATUS " With OpenNI = NO (WITH_OPENNI=OFF)")
ELSE()
MESSAGE(STATUS " With OpenNI = NO (OpenNI not found)")
ENDIF()
IF(OpenNI2_FOUND) IF(OpenNI2_FOUND)
MESSAGE(STATUS " With OpenNI2 = YES (License: Apache v2)") MESSAGE(STATUS " With OpenNI2 = YES (License: Apache v2)")
ELSEIF(NOT WITH_OPENNI2) ELSEIF(NOT WITH_OPENNI2)
@@ -1666,14 +1633,6 @@ ELSE()
MESSAGE(STATUS " With DepthAI = NO (depthai-core not found)") MESSAGE(STATUS " With DepthAI = NO (depthai-core not found)")
ENDIF() ENDIF()
IF(xvsdk_FOUND)
MESSAGE(STATUS " With XVisio SDK ${xvsdk_VERSION} = YES")
ELSEIF(NOT WITH_XVSDK)
MESSAGE(STATUS " With XVisio SDK = NO (WITH_XVSDK=OFF)")
ELSE()
MESSAGE(STATUS " With XVisio SDK = NO (xvsdk not found)")
ENDIF()
MESSAGE(STATUS "") MESSAGE(STATUS "")
MESSAGE(STATUS " Odometry Approaches:") MESSAGE(STATUS " Odometry Approaches:")
IF(loam_velodyne_FOUND) IF(loam_velodyne_FOUND)
+3 -6
View File
@@ -43,11 +43,7 @@ IF(@CONF_WITH_K4A@)
ENDIF() ENDIF()
IF(@CONF_WITH_DEPTH_AI@) IF(@CONF_WITH_DEPTH_AI@)
find_dependency(depthai 2.24) find_dependency(depthai 2)
ENDIF()
IF(@CONF_WITH_XVSDK@)
find_dependency(xvsdk)
ENDIF() ENDIF()
IF(@CONF_WITH_OCTOMAP@) IF(@CONF_WITH_OCTOMAP@)
@@ -97,7 +93,8 @@ endforeach()
include("${CMAKE_CURRENT_LIST_DIR}/RTABMapTargets.cmake") include("${CMAKE_CURRENT_LIST_DIR}/RTABMapTargets.cmake")
foreach(_comp ${RTABMap_FIND_COMPONENTS}) foreach(_comp ${RTABMap_FIND_COMPONENTS})
if (NOT RTABMap_${_comp}_FOUND) if (NOT ";${_RTABMap_supported_components};" MATCHES ";${_comp};")
set(RTABMap_${_comp}_FOUND False)
if(${RTABMap_FIND_REQUIRED_${_comp}}) if(${RTABMap_FIND_REQUIRED_${_comp}})
set(RTABMap_FOUND False) set(RTABMap_FOUND False)
set(RTABMap_NOT_FOUND_MESSAGE "Unsupported or not found required component: ${_comp}") set(RTABMap_NOT_FOUND_MESSAGE "Unsupported or not found required component: ${_comp}")
-2
View File
@@ -45,7 +45,6 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@CERES@#define RTABMAP_CERES @CERES@#define RTABMAP_CERES
@MRPT@#define RTABMAP_MRPT @MRPT@#define RTABMAP_MRPT
@VERTIGO@#define RTABMAP_VERTIGO @VERTIGO@#define RTABMAP_VERTIGO
@OPENNI@#define RTABMAP_OPENNI
@OPENNI2@#define RTABMAP_OPENNI2 @OPENNI2@#define RTABMAP_OPENNI2
@FREENECT@#define RTABMAP_FREENECT @FREENECT@#define RTABMAP_FREENECT
@FREENECT2@#define RTABMAP_FREENECT2 @FREENECT2@#define RTABMAP_FREENECT2
@@ -69,7 +68,6 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@REALSENSE2@#define RTABMAP_REALSENSE2 @REALSENSE2@#define RTABMAP_REALSENSE2
@MYNTEYE@#define RTABMAP_MYNTEYE @MYNTEYE@#define RTABMAP_MYNTEYE
@DEPTHAI@#define RTABMAP_DEPTHAI @DEPTHAI@#define RTABMAP_DEPTHAI
@XVSDK@#define RTABMAP_XVSDK
@OCTOMAP@#define RTABMAP_OCTOMAP @OCTOMAP@#define RTABMAP_OCTOMAP
@GRIDMAP@#define RTABMAP_GRIDMAP @GRIDMAP@#define RTABMAP_GRIDMAP
@CPUTSDF@#define RTABMAP_CPUTSDF @CPUTSDF@#define RTABMAP_CPUTSDF
+145 -17
View File
@@ -334,12 +334,11 @@ void CameraARCore::setScreenRotationAndSize(ScreenRotation colorCameraToDisplayR
} }
} }
SensorData CameraARCore::updateDataOnRender(Transform & pose) SensorData CameraARCore::captureImage(CameraInfo * info)
{ {
UScopeMutex lock(arSessionMutex_); UScopeMutex lock(arSessionMutex_);
//LOGI("Capturing image..."); //LOGI("Capturing image...");
pose.setNull();
SensorData data; SensorData data;
if(!arSession_) if(!arSession_)
{ {
@@ -371,7 +370,7 @@ SensorData CameraARCore::updateDataOnRender(Transform & pose)
if (geometry_changed != 0 || !uvs_initialized_) { if (geometry_changed != 0 || !uvs_initialized_) {
ArFrame_transformCoordinates2d( ArFrame_transformCoordinates2d(
arSession_, arFrame_, AR_COORDINATES_2D_OPENGL_NORMALIZED_DEVICE_COORDINATES, arSession_, arFrame_, AR_COORDINATES_2D_OPENGL_NORMALIZED_DEVICE_COORDINATES,
BackgroundRenderer::kNumVertices, BackgroundRenderer_kVerticesDevice, AR_COORDINATES_2D_TEXTURE_NORMALIZED, BackgroundRenderer::kNumVertices, BackgroundRenderer_kVertices, AR_COORDINATES_2D_TEXTURE_NORMALIZED,
transformed_uvs_); transformed_uvs_);
UASSERT(transformed_uvs_); UASSERT(transformed_uvs_);
uvs_initialized_ = true; uvs_initialized_ = true;
@@ -394,6 +393,7 @@ SensorData CameraARCore::updateDataOnRender(Transform & pose)
ArTrackingState camera_tracking_state; ArTrackingState camera_tracking_state;
ArCamera_getTrackingState(arSession_, ar_camera, &camera_tracking_state); ArCamera_getTrackingState(arSession_, ar_camera, &camera_tracking_state);
Transform pose;
CameraModel model; CameraModel model;
if(camera_tracking_state == AR_TRACKING_STATE_TRACKING) if(camera_tracking_state == AR_TRACKING_STATE_TRACKING)
{ {
@@ -401,13 +401,24 @@ SensorData CameraARCore::updateDataOnRender(Transform & pose)
float pose_raw[7]; float pose_raw[7];
ArCamera_getPose(arSession_, ar_camera, arPose_); ArCamera_getPose(arSession_, ar_camera, arPose_);
ArPose_getPoseRaw(arSession_, arPose_, pose_raw); ArPose_getPoseRaw(arSession_, arPose_, pose_raw);
Transform poseArCore = Transform(pose_raw[4], pose_raw[5], pose_raw[6], pose_raw[0], pose_raw[1], pose_raw[2], pose_raw[3]); pose = Transform(pose_raw[4], pose_raw[5], pose_raw[6], pose_raw[0], pose_raw[1], pose_raw[2], pose_raw[3]);
poseArCore = rtabmap::rtabmap_world_T_opengl_world * poseArCore * rtabmap::opengl_world_T_rtabmap_world; pose = rtabmap::rtabmap_world_T_opengl_world * pose * rtabmap::opengl_world_T_rtabmap_world;
if(poseArCore.isNull()) Transform poseArCore = pose;
if(pose.isNull())
{ {
LOGE("CameraARCore: Pose is null"); LOGE("CameraARCore: Pose is null");
} }
else
{
this->poseReceived(pose);
// adjust origin
if(!getOriginOffset().isNull())
{
pose = getOriginOffset() * pose;
}
info->odomPose = pose;
}
// Get calibration parameters // Get calibration parameters
float fx,fy, cx, cy; float fx,fy, cx, cy;
@@ -540,17 +551,6 @@ SensorData CameraARCore::updateDataOnRender(Transform & pose)
data = SensorData(scan, rgb, depthFromMotion_?getOcclusionImage():cv::Mat(), model, 0, stamp); data = SensorData(scan, rgb, depthFromMotion_?getOcclusionImage():cv::Mat(), model, 0, stamp);
data.setFeatures(kpts, kpts3, cv::Mat()); data.setFeatures(kpts, kpts3, cv::Mat());
if(!poseArCore.isNull())
{
pose = poseArCore;
this->poseReceived(pose, stamp);
// adjust origin
if(!getOriginOffset().isNull())
{
pose = getOriginOffset() * pose;
}
}
} }
} }
else else
@@ -571,6 +571,134 @@ SensorData CameraARCore::updateDataOnRender(Transform & pose)
ArCamera_release(ar_camera); ArCamera_release(ar_camera);
return data; return data;
}
void CameraARCore::capturePoseOnly()
{
UScopeMutex lock(arSessionMutex_);
//LOGI("Capturing image...");
if(!arSession_)
{
return;
}
if(textureId_ != 0)
{
glBindTexture(GL_TEXTURE_EXTERNAL_OES, textureId_);
glTexParameteri(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
ArSession_setCameraTextureName(arSession_, textureId_);
}
// Update session to get current frame and render camera background.
if (ArSession_update(arSession_, arFrame_) != AR_SUCCESS) {
LOGE("CameraARCore::capturePoseOnly() ArSession_update error");
return;
}
// If display rotation changed (also includes view size change), we need to
// re-query the uv coordinates for the on-screen portion of the camera image.
int32_t geometry_changed = 0;
ArFrame_getDisplayGeometryChanged(arSession_, arFrame_, &geometry_changed);
if (geometry_changed != 0 || !uvs_initialized_) {
ArFrame_transformCoordinates2d(
arSession_, arFrame_, AR_COORDINATES_2D_OPENGL_NORMALIZED_DEVICE_COORDINATES,
BackgroundRenderer::kNumVertices, BackgroundRenderer_kVertices, AR_COORDINATES_2D_TEXTURE_NORMALIZED,
transformed_uvs_);
UASSERT(transformed_uvs_);
uvs_initialized_ = true;
}
ArCamera* ar_camera;
ArFrame_acquireCamera(arSession_, arFrame_, &ar_camera);
ArCamera_getViewMatrix(arSession_, ar_camera, glm::value_ptr(viewMatrix_));
ArCamera_getProjectionMatrix(arSession_, ar_camera,
/*near=*/0.1f, /*far=*/100.f,
glm::value_ptr(projectionMatrix_));
// adjust origin
if(!getOriginOffset().isNull())
{
viewMatrix_ = glm::inverse(rtabmap::glmFromTransform(rtabmap::opengl_world_T_rtabmap_world * getOriginOffset() *rtabmap::rtabmap_world_T_opengl_world)*glm::inverse(viewMatrix_));
}
ArTrackingState camera_tracking_state;
ArCamera_getTrackingState(arSession_, ar_camera, &camera_tracking_state);
Transform pose;
CameraModel model;
if(camera_tracking_state == AR_TRACKING_STATE_TRACKING)
{
// pose in OpenGL coordinates
float pose_raw[7];
ArCamera_getPose(arSession_, ar_camera, arPose_);
ArPose_getPoseRaw(arSession_, arPose_, pose_raw);
pose = Transform(pose_raw[4], pose_raw[5], pose_raw[6], pose_raw[0], pose_raw[1], pose_raw[2], pose_raw[3]);
if(!pose.isNull())
{
pose = rtabmap::rtabmap_world_T_opengl_world * pose * rtabmap::opengl_world_T_rtabmap_world;
this->poseReceived(pose);
if(!getOriginOffset().isNull())
{
pose = getOriginOffset() * pose;
}
}
int32_t is_depth_supported = 0;
ArSession_isDepthModeSupported(arSession_, AR_DEPTH_MODE_AUTOMATIC, &is_depth_supported);
if(is_depth_supported)
{
LOGD("Acquire depth image!");
ArImage * depthImage = nullptr;
ArFrame_acquireDepthImage(arSession_, arFrame_, &depthImage);
ArImageFormat format;
ArImage_getFormat(arSession_, depthImage, &format);
if(format == AR_IMAGE_FORMAT_DEPTH16)
{
LOGD("Depth format detected!");
int planeCount;
ArImage_getNumberOfPlanes(arSession_, depthImage, &planeCount);
LOGD("planeCount=%d", planeCount);
UASSERT_MSG(planeCount == 1, uFormat("Error: getNumberOfPlanes() planceCount = %d", planeCount).c_str());
const uint8_t *data = nullptr;
int len = 0;
int stride;
int width;
int height;
ArImage_getWidth(arSession_, depthImage, &width);
ArImage_getHeight(arSession_, depthImage, &height);
ArImage_getPlaneRowStride(arSession_, depthImage, 0, &stride);
ArImage_getPlaneData(arSession_, depthImage, 0, &data, &len);
LOGD("width=%d, height=%d, bytes=%d stride=%d", width, height, len, stride);
cv::Mat occlusionImage = cv::Mat(height, width, CV_16UC1, (void*)data).clone();
float fx,fy, cx, cy;
int32_t rgb_width, rgb_height;
ArCamera_getImageIntrinsics(arSession_, ar_camera, arCameraIntrinsics_);
ArCameraIntrinsics_getFocalLength(arSession_, arCameraIntrinsics_, &fx, &fy);
ArCameraIntrinsics_getPrincipalPoint(arSession_, arCameraIntrinsics_, &cx, &cy);
ArCameraIntrinsics_getImageDimensions(arSession_, arCameraIntrinsics_, &rgb_width, &rgb_height);
float scaleX = (float)width / (float)rgb_width;
float scaleY = (float)height / (float)rgb_height;
CameraModel occlusionModel(fx*scaleX, fy*scaleY, cx*scaleX, cy*scaleY, pose*deviceTColorCamera_, 0, cv::Size(width, height));
this->setOcclusionImage(occlusionImage, occlusionModel);
}
ArImage_release(depthImage);
}
}
ArCamera_release(ar_camera);
} }
} /* namespace rtabmap */ } /* namespace rtabmap */
+11 -2
View File
@@ -63,14 +63,23 @@ public:
CameraARCore(void* env, void* context, void* activity, bool depthFromMotion = false, bool smoothing = false); CameraARCore(void* env, void* context, void* activity, bool depthFromMotion = false, bool smoothing = false);
virtual ~CameraARCore(); virtual ~CameraARCore();
bool uvsInitialized() const {return uvs_initialized_;}
const float* uvsTransformed() const {return transformed_uvs_;}
void getVPMatrices(glm::mat4 & view, glm::mat4 & projection) const {view=viewMatrix_; projection=projectionMatrix_;}
virtual void setScreenRotationAndSize(ScreenRotation colorCameraToDisplayRotation, int width, int height); virtual void setScreenRotationAndSize(ScreenRotation colorCameraToDisplayRotation, int width, int height);
virtual bool init(const std::string & calibrationFolder = ".", const std::string & cameraName = ""); virtual bool init(const std::string & calibrationFolder = ".", const std::string & cameraName = "");
virtual void close(); // close ARCore connection void setupGL();
virtual void close(); // close Tango connection
virtual std::string getSerial() const; virtual std::string getSerial() const;
GLuint getTextureId() const {return textureId_;}
void imageCallback(AImageReader *reader);
protected: protected:
virtual SensorData updateDataOnRender(Transform & pose); // should be called in opengl thread virtual SensorData captureImage(CameraInfo * info = 0); // should be called in opengl thread
virtual void capturePoseOnly();
private: private:
rtabmap::Transform getPoseAtTimestamp(double timestamp); rtabmap::Transform getPoseAtTimestamp(double timestamp);
+69 -77
View File
@@ -117,6 +117,9 @@ bool CameraAREngine::init(const std::string & calibrationFolder, const std::stri
deviceTColorCamera_ = opticalRotation; deviceTColorCamera_ = opticalRotation;
// Required as ArSession_update does some off-screen OpenGL stuff...
HwArSession_setCameraTextureName(arSession_, textureId_);
if (HwArSession_resume(arSession_) != HWAR_SUCCESS) if (HwArSession_resume(arSession_) != HWAR_SUCCESS)
{ {
UERROR("Cannot resume camera!"); UERROR("Cannot resume camera!");
@@ -166,87 +169,38 @@ void CameraAREngine::close()
CameraMobile::close(); CameraMobile::close();
} }
void CameraAREngine::setScreenRotationAndSize(ScreenRotation colorCameraToDisplayRotation, int width, int height) SensorData CameraAREngine::captureImage(CameraInfo * info)
{
CameraMobile::setScreenRotationAndSize(colorCameraToDisplayRotation, width, height);
if(arSession_)
{
int ret = static_cast<int>(colorCameraToDisplayRotation) + 1; // remove 90deg camera rotation
if (ret > 3) {
ret -= 4;
}
HwArSession_setDisplayGeometry(arSession_, ret, width, height);
}
}
SensorData CameraAREngine::updateDataOnRender(Transform & pose)
{ {
UScopeMutex lock(arSessionMutex_); UScopeMutex lock(arSessionMutex_);
//LOGI("Capturing image..."); //LOGI("Capturing image...");
pose.setNull();
SensorData data; SensorData data;
if(!arSession_) if(!arSession_)
{ {
return data; return data;
} }
if(textureId_ == 0)
{
glGenTextures(1, &textureId_);
glBindTexture(GL_TEXTURE_EXTERNAL_OES, textureId_);
glTexParameteri(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
}
if(textureId_!=0)
HwArSession_setCameraTextureName(arSession_, textureId_);
// Update session to get current frame and render camera background. // Update session to get current frame and render camera background.
if (HwArSession_update(arSession_, arFrame_) != HWAR_SUCCESS) { if (HwArSession_update(arSession_, arFrame_) != HWAR_SUCCESS) {
LOGE("CameraAREngine::captureImage() ArSession_update error"); LOGE("CameraAREngine::captureImage() ArSession_update error");
return data; return data;
} }
// If display rotation changed (also includes view size change), we need to
// re-query the uv coordinates for the on-screen portion of the camera image.
int32_t geometry_changed = 0;
HwArFrame_getDisplayGeometryChanged(arSession_, arFrame_, &geometry_changed);
if (geometry_changed != 0 || !uvs_initialized_) {
HwArFrame_transformDisplayUvCoords(
arSession_, arFrame_,
BackgroundRenderer::kNumVertices*2, BackgroundRenderer_kVerticesView,
transformed_uvs_);
UERROR("uv: (%f,%f) (%f,%f) (%f,%f) (%f,%f)",
transformed_uvs_[0], transformed_uvs_[1],
transformed_uvs_[2], transformed_uvs_[3],
transformed_uvs_[4], transformed_uvs_[5],
transformed_uvs_[6], transformed_uvs_[7]);
UASSERT(transformed_uvs_);
uvs_initialized_ = true;
}
HwArCamera* ar_camera; HwArCamera* ar_camera;
HwArFrame_acquireCamera(arSession_, arFrame_, &ar_camera); HwArFrame_acquireCamera(arSession_, arFrame_, &ar_camera);
HwArCamera_getViewMatrix(arSession_, ar_camera, glm::value_ptr(viewMatrix_));
HwArCamera_getProjectionMatrix(arSession_, ar_camera,
/*near=*/0.1f, /*far=*/100.f,
glm::value_ptr(projectionMatrix_));
// adjust origin
if(!getOriginOffset().isNull())
{
viewMatrix_ = glm::inverse(rtabmap::glmFromTransform(rtabmap::opengl_world_T_rtabmap_world * getOriginOffset() *rtabmap::rtabmap_world_T_opengl_world)*glm::inverse(viewMatrix_));
}
HwArTrackingState camera_tracking_state; HwArTrackingState camera_tracking_state;
HwArCamera_getTrackingState(arSession_, ar_camera, &camera_tracking_state); HwArCamera_getTrackingState(arSession_, ar_camera, &camera_tracking_state);
Transform pose;
if(camera_tracking_state == HWAR_TRACKING_STATE_TRACKING) if(camera_tracking_state == HWAR_TRACKING_STATE_TRACKING)
{ {
// pose in OpenGL coordinates
float pose_raw[7];
HwArCamera_getPose(arSession_, ar_camera, arPose_);
HwArPose_getPoseRaw(arSession_, arPose_, pose_raw);
pose = Transform(pose_raw[4], pose_raw[5], pose_raw[6], pose_raw[0], pose_raw[1], pose_raw[2], pose_raw[3]);
// Get calibration parameters // Get calibration parameters
// FIXME: Hard-coded as getting intrinsics with the api fails // FIXME: Hard-coded as getting intrinsics with the api fails
float fx=492.689667,fy=492.606201, cx=323.594849, cy=234.659744; float fx=492.689667,fy=492.606201, cx=323.594849, cy=234.659744;
@@ -320,26 +274,6 @@ SensorData CameraAREngine::updateDataOnRender(Transform & pose)
double stamp = double(timestamp_ns)/10e8; double stamp = double(timestamp_ns)/10e8;
CameraModel model = CameraModel(fx, fy, cx, cy, deviceTColorCamera_, 0, cv::Size(camWidth, camHeight)); CameraModel model = CameraModel(fx, fy, cx, cy, deviceTColorCamera_, 0, cv::Size(camWidth, camHeight));
data = SensorData(outputRGB, outputDepth, model, 0, stamp); data = SensorData(outputRGB, outputDepth, model, 0, stamp);
// pose in OpenGL coordinates
float pose_raw[7];
HwArCamera_getPose(arSession_, ar_camera, arPose_);
HwArPose_getPoseRaw(arSession_, arPose_, pose_raw);
pose = Transform(pose_raw[4], pose_raw[5], pose_raw[6], pose_raw[0], pose_raw[1], pose_raw[2], pose_raw[3]);
if(pose.isNull())
{
LOGE("CameraAREngine: Pose is null");
}
else
{
pose = rtabmap::rtabmap_world_T_opengl_world * pose * rtabmap::opengl_world_T_rtabmap_world;
this->poseReceived(pose, stamp);
// adjust origin
if(!getOriginOffset().isNull())
{
pose = getOriginOffset() * pose;
}
}
} }
} }
else else
@@ -357,8 +291,66 @@ SensorData CameraAREngine::updateDataOnRender(Transform & pose)
} }
HwArCamera_release(ar_camera); HwArCamera_release(ar_camera);
if(pose.isNull())
{
LOGE("CameraAREngine: Pose is null");
}
else
{
pose = rtabmap::rtabmap_world_T_opengl_world * pose * rtabmap::opengl_world_T_rtabmap_world;
this->poseReceived(pose);
// adjust origin
if(!getOriginOffset().isNull())
{
pose = getOriginOffset() * pose;
}
info->odomPose = pose;
}
return data; return data;
} }
void CameraAREngine::capturePoseOnly()
{
UScopeMutex lock(arSessionMutex_);
//LOGI("Capturing image...");
SensorData data;
if(!arSession_)
{
return;
}
// Update session to get current frame and render camera background.
if (HwArSession_update(arSession_, arFrame_) != HWAR_SUCCESS) {
LOGE("CameraARCore::captureImage() ArSession_update error");
return;
}
HwArCamera* ar_camera;
HwArFrame_acquireCamera(arSession_, arFrame_, &ar_camera);
HwArTrackingState camera_tracking_state;
HwArCamera_getTrackingState(arSession_, ar_camera, &camera_tracking_state);
Transform pose;
CameraModel model;
if(camera_tracking_state == HWAR_TRACKING_STATE_TRACKING)
{
// pose in OpenGL coordinates
float pose_raw[7];
HwArCamera_getPose(arSession_, ar_camera, arPose_);
HwArPose_getPoseRaw(arSession_, arPose_, pose_raw);
pose = Transform(pose_raw[4], pose_raw[5], pose_raw[6], pose_raw[0], pose_raw[1], pose_raw[2], pose_raw[3]);
if(!pose.isNull())
{
pose = rtabmap::rtabmap_world_T_opengl_world * pose * rtabmap::opengl_world_T_rtabmap_world;
this->poseReceived(pose);
}
}
HwArCamera_release(ar_camera);
}
} /* namespace rtabmap */ } /* namespace rtabmap */
+4 -5
View File
@@ -38,7 +38,6 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <rtabmap/utilite/UEvent.h> #include <rtabmap/utilite/UEvent.h>
#include <rtabmap/utilite/UTimer.h> #include <rtabmap/utilite/UTimer.h>
#include <boost/thread/mutex.hpp> #include <boost/thread/mutex.hpp>
#include <background_renderer.h>
#include <huawei_arengine_interface.h> #include <huawei_arengine_interface.h>
@@ -49,14 +48,13 @@ public:
CameraAREngine(void* env, void* context, void* activity, bool smoothing = false); CameraAREngine(void* env, void* context, void* activity, bool smoothing = false);
virtual ~CameraAREngine(); virtual ~CameraAREngine();
virtual void setScreenRotationAndSize(ScreenRotation colorCameraToDisplayRotation, int width, int height);
virtual bool init(const std::string & calibrationFolder = ".", const std::string & cameraName = ""); virtual bool init(const std::string & calibrationFolder = ".", const std::string & cameraName = "");
virtual void close(); // close AREngine connection virtual void close(); // close Tango connection
virtual std::string getSerial() const; virtual std::string getSerial() const;
protected: protected:
virtual SensorData updateDataOnRender(Transform & pose); virtual SensorData captureImage(CameraInfo * info = 0);
virtual void capturePoseOnly();
private: private:
rtabmap::Transform getPoseAtTimestamp(double timestamp); rtabmap::Transform getPoseAtTimestamp(double timestamp);
@@ -71,6 +69,7 @@ private:
HwArCameraIntrinsics *arCameraIntrinsics_ = nullptr; HwArCameraIntrinsics *arCameraIntrinsics_ = nullptr;
HwArPose * arPose_ = nullptr; HwArPose * arPose_ = nullptr;
bool arInstallRequested_; bool arInstallRequested_;
GLuint textureId_;
UMutex arSessionMutex_; UMutex arSessionMutex_;
}; };
+124 -180
View File
@@ -55,8 +55,10 @@ const rtabmap::Transform CameraMobile::opticalRotationInv = Transform(
CameraMobile::CameraMobile(bool smoothing) : CameraMobile::CameraMobile(bool smoothing) :
Camera(10), Camera(10),
deviceTColorCamera_(Transform::getIdentity()), deviceTColorCamera_(Transform::getIdentity()),
spinOncePreviousStamp_(0.0),
textureId_(0), textureId_(0),
uvs_initialized_(false), uvs_initialized_(false),
previousStamp_(0.0),
stampEpochOffset_(0.0), stampEpochOffset_(0.0),
smoothing_(smoothing), smoothing_(smoothing),
colorCameraToDisplayRotation_(ROTATION_0), colorCameraToDisplayRotation_(ROTATION_0),
@@ -77,12 +79,13 @@ bool CameraMobile::init(const std::string &, const std::string &)
void CameraMobile::close() void CameraMobile::close()
{ {
firstFrame_ = true; previousPose_.setNull();
previousStamp_ = 0.0;
lastKnownGPS_ = GPS(); lastKnownGPS_ = GPS();
lastEnvSensors_.clear(); lastEnvSensors_.clear();
originOffset_ = Transform(); originOffset_ = Transform();
originUpdate_ = false; originUpdate_ = false;
dataPose_ = Transform(); pose_ = Transform();
data_ = SensorData(); data_ = SensorData();
if(textureId_ != 0) if(textureId_ != 0)
@@ -94,108 +97,36 @@ void CameraMobile::close()
void CameraMobile::resetOrigin() void CameraMobile::resetOrigin()
{ {
firstFrame_ = true; previousPose_.setNull();
previousStamp_ = 0.0;
lastKnownGPS_ = GPS(); lastKnownGPS_ = GPS();
lastEnvSensors_.clear(); lastEnvSensors_.clear();
dataPose_ = Transform(); pose_ = Transform();
data_ = SensorData(); data_ = SensorData();
originUpdate_ = true; originUpdate_ = true;
} }
bool CameraMobile::getPose(double stamp, Transform & pose, cv::Mat & covariance, double maxWaitTime) void CameraMobile::poseReceived(const Transform & pose)
{
pose.setNull();
int maxWaitTimeMs = maxWaitTime * 1000;
// Interpolate pose
if(!poseBuffer_.empty())
{
poseMutex_.lock();
int waitTry = 0;
while(maxWaitTimeMs>0 && poseBuffer_.rbegin()->first < stamp && waitTry < maxWaitTimeMs)
{
poseMutex_.unlock();
++waitTry;
uSleep(1);
poseMutex_.lock();
}
if(poseBuffer_.rbegin()->first < stamp)
{
if(maxWaitTimeMs > 0)
{
UWARN("Could not find poses to interpolate at time %f after waiting %d ms (latest is %f)...", stamp, maxWaitTimeMs, poseBuffer_.rbegin()->first);
}
else
{
UWARN("Could not find poses to interpolate at time %f (latest is %f)...", stamp, poseBuffer_.rbegin()->first);
}
}
else
{
std::map<double, Transform>::const_iterator iterB = poseBuffer_.lower_bound(stamp);
std::map<double, Transform>::const_iterator iterA = iterB;
if(iterA != poseBuffer_.begin())
{
iterA = --iterA;
}
if(iterB == poseBuffer_.end())
{
iterB = --iterB;
}
if(iterA == iterB && stamp == iterA->first)
{
pose = iterA->second;
}
else if(stamp >= iterA->first && stamp <= iterB->first)
{
pose = iterA->second.interpolate((stamp-iterA->first) / (iterB->first-iterA->first), iterB->second);
}
else // stamp < iterA->first
{
UWARN("Could not find pose data to interpolate at time %f (earliest is %f). Are sensors synchronized?", stamp, iterA->first);
}
}
poseMutex_.unlock();
}
return !pose.isNull();
}
void CameraMobile::poseReceived(const Transform & pose, double deviceStamp)
{ {
if(!pose.isNull()) if(!pose.isNull())
{ {
Transform p = pose; // send pose of the camera (without optical rotation)
Transform p = pose*deviceTColorCamera_;
if(originUpdate_) if(originUpdate_)
{ {
originOffset_ = p.translation().inverse(); originOffset_ = p.translation().inverse();
originUpdate_ = false; originUpdate_ = false;
} }
if(stampEpochOffset_ == 0.0)
{
stampEpochOffset_ = UTimer::now() - deviceStamp;
}
double epochStamp = stampEpochOffset_ + deviceStamp;
if(!originOffset_.isNull()) if(!originOffset_.isNull())
{ {
p = originOffset_*p; this->post(new PoseEvent(originOffset_*p));
} }
else
{ {
UScopeMutex lock(poseMutex_); this->post(new PoseEvent(p));
poseBuffer_.insert(poseBuffer_.end(), std::make_pair(epochStamp, p));
if(poseBuffer_.size() > 1000)
{
poseBuffer_.erase(poseBuffer_.begin());
} }
} }
// send pose of the camera (with optical rotation)
this->post(new PoseEvent(p * deviceTColorCamera_));
}
} }
bool CameraMobile::isCalibrated() const bool CameraMobile::isCalibrated() const
@@ -208,20 +139,11 @@ void CameraMobile::setGPS(const GPS & gps)
lastKnownGPS_ = gps; lastKnownGPS_ = gps;
} }
void CameraMobile::addEnvSensor(int type, float value) void CameraMobile::setData(const SensorData & data, const Transform & pose, const glm::mat4 & viewMatrix, const glm::mat4 & projectionMatrix, const float * texCoord)
{ {
lastEnvSensors_.insert(std::make_pair((EnvSensor::Type)type, EnvSensor((EnvSensor::Type)type, value))); LOGD("CameraMobile::setData pose=%s stamp=%f", pose.prettyPrint().c_str(), data.stamp());
}
void CameraMobile::update(const SensorData & data, const Transform & pose, const glm::mat4 & viewMatrix, const glm::mat4 & projectionMatrix, const float * texCoord)
{
UScopeMutex lock(dataMutex_);
bool notify = !data_.isValid();
LOGD("CameraMobile::update pose=%s stamp=%f", pose.prettyPrint().c_str(), data.stamp());
data_ = data; data_ = data;
dataPose_ = pose; pose_ = pose;
viewMatrix_ = viewMatrix; viewMatrix_ = viewMatrix;
projectionMatrix_ = projectionMatrix; projectionMatrix_ = projectionMatrix;
@@ -229,7 +151,7 @@ void CameraMobile::update(const SensorData & data, const Transform & pose, const
// adjust origin // adjust origin
if(!originOffset_.isNull()) if(!originOffset_.isNull())
{ {
dataPose_ = originOffset_ * dataPose_; pose_ = originOffset_ * pose_;
viewMatrix_ = glm::inverse(rtabmap::glmFromTransform(rtabmap::opengl_world_T_rtabmap_world * originOffset_ *rtabmap::rtabmap_world_T_opengl_world)*glm::inverse(viewMatrix_)); viewMatrix_ = glm::inverse(rtabmap::glmFromTransform(rtabmap::opengl_world_T_rtabmap_world * originOffset_ *rtabmap::rtabmap_world_T_opengl_world)*glm::inverse(viewMatrix_));
} }
@@ -244,7 +166,7 @@ void CameraMobile::update(const SensorData & data, const Transform & pose, const
uvs_initialized_ = true; uvs_initialized_ = true;
} }
LOGD("CameraMobile::update textureId_=%d", (int)textureId_); LOGD("CameraMobile::setData textureId_=%d", (int)textureId_);
if(textureId_ != 0 && texCoord != 0) if(textureId_ != 0 && texCoord != 0)
{ {
@@ -271,63 +193,78 @@ void CameraMobile::update(const SensorData & data, const Transform & pose, const
return; return;
} }
} }
postUpdate();
if(notify)
{
dataReady_.release();
}
} }
void CameraMobile::updateOnRender() void CameraMobile::addEnvSensor(int type, float value)
{ {
UScopeMutex lock(dataMutex_); lastEnvSensors_.insert(std::make_pair((EnvSensor::Type)type, EnvSensor((EnvSensor::Type)type, value)));
bool notify = !data_.isValid(); }
data_ = updateDataOnRender(dataPose_); void CameraMobile::spinOnce()
if(data_.isValid())
{ {
postUpdate(); if(!this->isRunning())
if(notify)
{ {
dataReady_.release(); bool ignoreFrame = false;
//float rate = 10.0f; // maximum 10 FPS for image data
double now = UTimer::now();
/*if(rate>0.0f)
{
if((spinOncePreviousStamp_>=0.0 && now>spinOncePreviousStamp_ && now - spinOncePreviousStamp_ < 1.0f/rate) ||
((spinOncePreviousStamp_<=0.0 || now<=spinOncePreviousStamp_) && spinOnceFrameRateTimer_.getElapsedTime() < 1.0f/rate))
{
ignoreFrame = true;
}
}*/
if(!ignoreFrame)
{
spinOnceFrameRateTimer_.start();
spinOncePreviousStamp_ = now;
mainLoop();
}
else
{
// just send pose
capturePoseOnly();
} }
} }
} }
SensorData CameraMobile::updateDataOnRender(Transform & pose) void CameraMobile::mainLoopBegin()
{ {
LOGE("To use CameraMobile::updateOnRender(), CameraMobile::updateDataOnRender() " double t = cameraStartedTime_.elapsed();
"should be overridden by inherited classes. Returning empty data!\n"); if(t < 5.0)
return SensorData(); {
uSleep((5.0-t)*1000); // just to make sure that the camera is started
}
} }
void CameraMobile::postUpdate() void CameraMobile::mainLoop()
{ {
if(data_.isValid()) CameraInfo info;
SensorData data = this->captureImage(&info);
if(data.isValid() && !info.odomPose.isNull())
{ {
if(lastKnownGPS_.stamp() > 0.0 && data_.stamp()-lastKnownGPS_.stamp()<1.0) if(lastKnownGPS_.stamp() > 0.0 && data.stamp()-lastKnownGPS_.stamp()<1.0)
{ {
data_.setGPS(lastKnownGPS_); data.setGPS(lastKnownGPS_);
} }
else if(lastKnownGPS_.stamp()>0.0) else if(lastKnownGPS_.stamp()>0.0)
{ {
LOGD("GPS too old (current time=%f, gps time = %f)", data_.stamp(), lastKnownGPS_.stamp()); LOGD("GPS too old (current time=%f, gps time = %f)", data.stamp(), lastKnownGPS_.stamp());
} }
if(lastEnvSensors_.size()) if(lastEnvSensors_.size())
{ {
data_.setEnvSensors(lastEnvSensors_); data.setEnvSensors(lastEnvSensors_);
lastEnvSensors_.clear(); lastEnvSensors_.clear();
} }
if(smoothing_ && !data_.depthRaw().empty()) if(smoothing_ && !data.depthRaw().empty())
{ {
//UTimer t; //UTimer t;
data_.setDepthOrRightRaw(rtabmap::util2d::fastBilateralFiltering(data_.depthRaw(), bilateralFilteringSigmaS, bilateralFilteringSigmaR)); data.setDepthOrRightRaw(rtabmap::util2d::fastBilateralFiltering(data.depthRaw(), bilateralFilteringSigmaS, bilateralFilteringSigmaR));
//LOGD("Bilateral filtering, time=%fs", t.ticks()); //LOGD("Bilateral filtering, time=%fs", t.ticks());
} }
@@ -336,15 +273,15 @@ void CameraMobile::postUpdate()
{ {
UDEBUG("ROTATION_90"); UDEBUG("ROTATION_90");
cv::Mat rgb, depth; cv::Mat rgb, depth;
cv::Mat rgbt(data_.imageRaw().cols, data_.imageRaw().rows, data_.imageRaw().type()); cv::Mat rgbt(data.imageRaw().cols, data.imageRaw().rows, data.imageRaw().type());
cv::flip(data_.imageRaw(),rgb,1); cv::flip(data.imageRaw(),rgb,1);
cv::transpose(rgb,rgbt); cv::transpose(rgb,rgbt);
rgb = rgbt; rgb = rgbt;
cv::Mat deptht(data_.depthRaw().cols, data_.depthRaw().rows, data_.depthRaw().type()); cv::Mat deptht(data.depthRaw().cols, data.depthRaw().rows, data.depthRaw().type());
cv::flip(data_.depthRaw(),depth,1); cv::flip(data.depthRaw(),depth,1);
cv::transpose(depth,deptht); cv::transpose(depth,deptht);
depth = deptht; depth = deptht;
CameraModel model = data_.cameraModels()[0]; CameraModel model = data.cameraModels()[0];
cv::Size sizet(model.imageHeight(), model.imageWidth()); cv::Size sizet(model.imageHeight(), model.imageWidth());
model = CameraModel( model = CameraModel(
model.fy(), model.fy(),
@@ -353,25 +290,25 @@ void CameraMobile::postUpdate()
model.cx()>0?model.imageWidth()-model.cx():0, model.cx()>0?model.imageWidth()-model.cx():0,
model.localTransform()*rtabmap::Transform(0,-1,0,0, 1,0,0,0, 0,0,1,0)); model.localTransform()*rtabmap::Transform(0,-1,0,0, 1,0,0,0, 0,0,1,0));
model.setImageSize(sizet); model.setImageSize(sizet);
data_.setRGBDImage(rgb, depth, model); data.setRGBDImage(rgb, depth, model);
std::vector<cv::KeyPoint> keypoints = data_.keypoints(); std::vector<cv::KeyPoint> keypoints = data.keypoints();
for(size_t i=0; i<keypoints.size(); ++i) for(size_t i=0; i<keypoints.size(); ++i)
{ {
keypoints[i].pt.x = data_.keypoints()[i].pt.y; keypoints[i].pt.x = data.keypoints()[i].pt.y;
keypoints[i].pt.y = rgb.rows - data_.keypoints()[i].pt.x; keypoints[i].pt.y = rgb.rows - data.keypoints()[i].pt.x;
} }
data_.setFeatures(keypoints, data_.keypoints3D(), cv::Mat()); data.setFeatures(keypoints, data.keypoints3D(), cv::Mat());
} }
else if(colorCameraToDisplayRotation_ == ROTATION_180) else if(colorCameraToDisplayRotation_ == ROTATION_180)
{ {
UDEBUG("ROTATION_180"); UDEBUG("ROTATION_180");
cv::Mat rgb, depth; cv::Mat rgb, depth;
cv::flip(data_.imageRaw(),rgb,1); cv::flip(data.imageRaw(),rgb,1);
cv::flip(rgb,rgb,0); cv::flip(rgb,rgb,0);
cv::flip(data_.depthOrRightRaw(),depth,1); cv::flip(data.depthOrRightRaw(),depth,1);
cv::flip(depth,depth,0); cv::flip(depth,depth,0);
CameraModel model = data_.cameraModels()[0]; CameraModel model = data.cameraModels()[0];
cv::Size sizet(model.imageWidth(), model.imageHeight()); cv::Size sizet(model.imageWidth(), model.imageHeight());
model = CameraModel( model = CameraModel(
model.fx(), model.fx(),
@@ -380,26 +317,26 @@ void CameraMobile::postUpdate()
model.cy()>0?model.imageHeight()-model.cy():0, model.cy()>0?model.imageHeight()-model.cy():0,
model.localTransform()*rtabmap::Transform(0,0,0,0,0,1,0)); model.localTransform()*rtabmap::Transform(0,0,0,0,0,1,0));
model.setImageSize(sizet); model.setImageSize(sizet);
data_.setRGBDImage(rgb, depth, model); data.setRGBDImage(rgb, depth, model);
std::vector<cv::KeyPoint> keypoints = data_.keypoints(); std::vector<cv::KeyPoint> keypoints = data.keypoints();
for(size_t i=0; i<keypoints.size(); ++i) for(size_t i=0; i<keypoints.size(); ++i)
{ {
keypoints[i].pt.x = rgb.cols - data_.keypoints()[i].pt.x; keypoints[i].pt.x = rgb.cols - data.keypoints()[i].pt.x;
keypoints[i].pt.y = rgb.rows - data_.keypoints()[i].pt.y; keypoints[i].pt.y = rgb.rows - data.keypoints()[i].pt.y;
} }
data_.setFeatures(keypoints, data_.keypoints3D(), cv::Mat()); data.setFeatures(keypoints, data.keypoints3D(), cv::Mat());
} }
else if(colorCameraToDisplayRotation_ == ROTATION_270) else if(colorCameraToDisplayRotation_ == ROTATION_270)
{ {
UDEBUG("ROTATION_270"); UDEBUG("ROTATION_270");
cv::Mat rgb(data_.imageRaw().cols, data_.imageRaw().rows, data_.imageRaw().type()); cv::Mat rgb(data.imageRaw().cols, data.imageRaw().rows, data.imageRaw().type());
cv::transpose(data_.imageRaw(),rgb); cv::transpose(data.imageRaw(),rgb);
cv::flip(rgb,rgb,1); cv::flip(rgb,rgb,1);
cv::Mat depth(data_.depthOrRightRaw().cols, data_.depthOrRightRaw().rows, data_.depthOrRightRaw().type()); cv::Mat depth(data.depthOrRightRaw().cols, data.depthOrRightRaw().rows, data.depthOrRightRaw().type());
cv::transpose(data_.depthOrRightRaw(),depth); cv::transpose(data.depthOrRightRaw(),depth);
cv::flip(depth,depth,1); cv::flip(depth,depth,1);
CameraModel model = data_.cameraModels()[0]; CameraModel model = data.cameraModels()[0];
cv::Size sizet(model.imageHeight(), model.imageWidth()); cv::Size sizet(model.imageHeight(), model.imageWidth());
model = CameraModel( model = CameraModel(
model.fy(), model.fy(),
@@ -408,54 +345,61 @@ void CameraMobile::postUpdate()
model.cx(), model.cx(),
model.localTransform()*rtabmap::Transform(0,1,0,0, -1,0,0,0, 0,0,1,0)); model.localTransform()*rtabmap::Transform(0,1,0,0, -1,0,0,0, 0,0,1,0));
model.setImageSize(sizet); model.setImageSize(sizet);
data_.setRGBDImage(rgb, depth, model); data.setRGBDImage(rgb, depth, model);
std::vector<cv::KeyPoint> keypoints = data_.keypoints(); std::vector<cv::KeyPoint> keypoints = data.keypoints();
for(size_t i=0; i<keypoints.size(); ++i) for(size_t i=0; i<keypoints.size(); ++i)
{ {
keypoints[i].pt.x = rgb.cols - data_.keypoints()[i].pt.y; keypoints[i].pt.x = rgb.cols - data.keypoints()[i].pt.y;
keypoints[i].pt.y = data_.keypoints()[i].pt.x; keypoints[i].pt.y = data.keypoints()[i].pt.x;
}
data_.setFeatures(keypoints, data_.keypoints3D(), cv::Mat());
}
} }
data.setFeatures(keypoints, data.keypoints3D(), cv::Mat());
} }
SensorData CameraMobile::captureImage(SensorCaptureInfo * info) rtabmap::Transform pose = info.odomPose;
{
SensorData data;
if(dataReady_.acquire(1, 5000))
{
UScopeMutex lock(dataMutex_);
data = data_;
data_ = SensorData();
}
if(data.isValid())
{
data.setGroundTruth(Transform()); data.setGroundTruth(Transform());
data.setStamp(stampEpochOffset_ + data.stamp());
if(info) // convert stamp to epoch
bool firstFrame = previousPose_.isNull();
if(firstFrame)
{ {
stampEpochOffset_ = UTimer::now()-data.stamp();
}
data.setStamp(stampEpochOffset_ + data.stamp());
OdometryInfo info;
if(!firstFrame)
{
info.interval = data.stamp()-previousStamp_;
info.transform = previousPose_.inverse() * pose;
}
// linear cov = 0.0001 // linear cov = 0.0001
info->odomCovariance = cv::Mat::eye(6,6,CV_64FC1) * (firstFrame_?9999.0:0.0001); info.reg.covariance = cv::Mat::eye(6,6,CV_64FC1) * (firstFrame?9999.0:0.0001);
if(!firstFrame_) if(!firstFrame)
{ {
// angular cov = 0.000001 // angular cov = 0.000001
info->odomCovariance.at<double>(3,3) *= 0.01; info.reg.covariance.at<double>(3,3) *= 0.01;
info->odomCovariance.at<double>(4,4) *= 0.01; info.reg.covariance.at<double>(4,4) *= 0.01;
info->odomCovariance.at<double>(5,5) *= 0.01; info.reg.covariance.at<double>(5,5) *= 0.01;
}
LOGI("Publish odometry message (variance=%f)", firstFrame?9999:0.0001);
this->post(new OdometryEvent(data, pose, info));
previousPose_ = pose;
previousStamp_ = data.stamp();
}
else if(!this->isKilled() && info.odomPose.isNull())
{
LOGW("Odometry lost");
this->post(new OdometryEvent());
} }
info->odomPose = dataPose_;
} }
firstFrame_ = false; SensorData CameraMobile::captureImage(CameraInfo * info)
}
else
{ {
UWARN("CameraMobile::captureImage() invalid data!"); if(info)
{
info->odomPose = pose_;
} }
return data; return data_;
} }
LaserScan CameraMobile::scanFromPointCloudData( LaserScan CameraMobile::scanFromPointCloudData(
+16 -20
View File
@@ -68,7 +68,7 @@ private:
Transform pose_; Transform pose_;
}; };
class CameraMobile : public Camera, public UEventsSender { class CameraMobile : public Camera, public UThread, public UEventsSender {
public: public:
static const float bilateralFilteringSigmaS; static const float bilateralFilteringSigmaS;
static const float bilateralFilteringSigmaR; static const float bilateralFilteringSigmaR;
@@ -93,20 +93,14 @@ public:
// abstract functions // abstract functions
virtual bool init(const std::string & calibrationFolder = ".", const std::string & cameraName = ""); virtual bool init(const std::string & calibrationFolder = ".", const std::string & cameraName = "");
virtual void close(); // inherited classes should call its parent at the end of their close(). virtual void close(); // inherited classes should call its parent in their close().
virtual std::string getSerial() const {return "CameraMobile";} virtual std::string getSerial() const {return "CameraMobile";}
void update(const SensorData & data, const Transform & pose, const glm::mat4 & viewMatrix, const glm::mat4 & projectionMatrix, const float * texCoord);
void updateOnRender();
const Transform & getOriginOffset() const {return originOffset_;} // in rtabmap frame const Transform & getOriginOffset() const {return originOffset_;} // in rtabmap frame
void resetOrigin(); void resetOrigin();
virtual bool isCalibrated() const; virtual bool isCalibrated() const;
virtual bool odomProvided() const { return true; } void poseReceived(const Transform & pose); // in rtabmap frame
virtual bool getPose(double epochStamp, Transform & pose, cv::Mat & covariance, double maxWaitTime = 0.06); // Return pose of device in rtabmap frame (with origin offset), stamp should be epoch time
void poseReceived(const Transform & pose, double deviceStamp); // original pose of device in rtabmap frame (without origin offset), stamp of the device (may be not epoch)
double getStampEpochOffset() const {return stampEpochOffset_;}
const CameraModel & getCameraModel() const {return model_;} const CameraModel & getCameraModel() const {return model_;}
const Transform & getDeviceTColorCamera() const {return deviceTColorCamera_;} const Transform & getDeviceTColorCamera() const {return deviceTColorCamera_;}
@@ -114,6 +108,9 @@ public:
virtual void setScreenRotationAndSize(ScreenRotation colorCameraToDisplayRotation, int width, int height) {colorCameraToDisplayRotation_ = colorCameraToDisplayRotation;} virtual void setScreenRotationAndSize(ScreenRotation colorCameraToDisplayRotation, int width, int height) {colorCameraToDisplayRotation_ = colorCameraToDisplayRotation;}
void setGPS(const GPS & gps); void setGPS(const GPS & gps);
void addEnvSensor(int type, float value); void addEnvSensor(int type, float value);
void setData(const SensorData & data, const Transform & pose, const glm::mat4 & viewMatrix, const glm::mat4 & projectionMatrix, const float * texCoord);
void spinOnce(); // Should only be called if not thread is not running, otherwise it does nothing
GLuint getTextureId() {return textureId_;} GLuint getTextureId() {return textureId_;}
bool uvsInitialized() const {return uvs_initialized_;} bool uvsInitialized() const {return uvs_initialized_;}
@@ -125,15 +122,17 @@ public:
const cv::Mat & getOcclusionImage(CameraModel * model=0) const {if(model)*model=occlusionModel_; return occlusionImage_; } const cv::Mat & getOcclusionImage(CameraModel * model=0) const {if(model)*model=occlusionModel_; return occlusionImage_; }
protected: protected:
virtual SensorData updateDataOnRender(Transform & pose); virtual SensorData captureImage(CameraInfo * info = 0);
virtual void capturePoseOnly() {}
private: virtual void mainLoopBegin();
virtual SensorData captureImage(SensorCaptureInfo * info = 0); virtual void mainLoop();
void postUpdate(); // Should be called while being protected by dataMutex_
protected: protected:
CameraModel model_; // local transform is the device to camera optical rotation in rtabmap frame CameraModel model_; // local transform is the device to camera optical rotation in rtabmap frame
Transform deviceTColorCamera_; // device to camera optical rotation in rtabmap frame Transform deviceTColorCamera_; // device to camera optical rotation in rtabmap frame
UTimer spinOnceFrameRateTimer_;
double spinOncePreviousStamp_;
GLuint textureId_; GLuint textureId_;
glm::mat4 viewMatrix_; glm::mat4 viewMatrix_;
@@ -142,7 +141,9 @@ protected:
bool uvs_initialized_ = false; bool uvs_initialized_ = false;
private: private:
bool firstFrame_; Transform previousPose_;
double previousStamp_;
UTimer cameraStartedTime_;
double stampEpochOffset_; double stampEpochOffset_;
bool smoothing_; bool smoothing_;
ScreenRotation colorCameraToDisplayRotation_; ScreenRotation colorCameraToDisplayRotation_;
@@ -151,13 +152,8 @@ private:
Transform originOffset_; Transform originOffset_;
bool originUpdate_; bool originUpdate_;
USemaphore dataReady_;
UMutex dataMutex_;
SensorData data_; SensorData data_;
Transform dataPose_; Transform pose_;
UMutex poseMutex_;
std::map<double, Transform> poseBuffer_; // <stamp, Pose>
cv::Mat occlusionImage_; cv::Mat occlusionImage_;
CameraModel occlusionModel_; CameraModel occlusionModel_;
+23 -18
View File
@@ -101,7 +101,7 @@ void onPoseAvailableRouter(void* context, const TangoPoseData* pose)
if(pose->status_code == TANGO_POSE_VALID) if(pose->status_code == TANGO_POSE_VALID)
{ {
CameraTango* app = static_cast<CameraTango*>(context); CameraTango* app = static_cast<CameraTango*>(context);
app->poseReceived(rtabmap_world_T_tango_world * app->tangoPoseToTransform(pose) * tango_device_T_rtabmap_world, pose->timestamp); app->poseReceived(rtabmap_world_T_tango_world * app->tangoPoseToTransform(pose) * tango_device_T_rtabmap_world);
} }
} }
@@ -444,7 +444,7 @@ void CameraTango::cloudReceived(const cv::Mat & cloud, double timestamp)
//LOGD("Depth received! %fs (%d points)", timestamp, cloud.cols); //LOGD("Depth received! %fs (%d points)", timestamp, cloud.cols);
UASSERT(cloud.type() == CV_32FC4); UASSERT(cloud.type() == CV_32FC4);
boost::mutex::scoped_lock lock(tangoDataMutex_); boost::mutex::scoped_lock lock(dataMutex_);
// From post: http://stackoverflow.com/questions/29236110/timing-issues-with-tango-image-frames // From post: http://stackoverflow.com/questions/29236110/timing-issues-with-tango-image-frames
// "In the current version of Project Tango Tablet RGB IR camera // "In the current version of Project Tango Tablet RGB IR camera
@@ -463,7 +463,7 @@ void CameraTango::cloudReceived(const cv::Mat & cloud, double timestamp)
if(dt >= 0.0 && dt < 0.5) if(dt >= 0.0 && dt < 0.5)
{ {
bool notify = !tangoData_.isValid(); bool notify = !data_.isValid();
cv::Mat tangoImage = tangoColor_; cv::Mat tangoImage = tangoColor_;
cv::Mat rgb; cv::Mat rgb;
@@ -495,7 +495,7 @@ void CameraTango::cloudReceived(const cv::Mat & cloud, double timestamp)
else else
{ {
LOGE("Not supported color format : %d.", tangoColorType); LOGE("Not supported color format : %d.", tangoColorType);
tangoData_ = SensorData(); data_ = SensorData();
return; return;
} }
@@ -678,24 +678,24 @@ void CameraTango::cloudReceived(const cv::Mat & cloud, double timestamp)
if(rawScanPublished_) if(rawScanPublished_)
{ {
tangoData_ = SensorData(LaserScan::backwardCompatibility(scan, cloud.total()/scanDownsampling, 0, scanLocalTransform), rgb, depth, model, this->getNextSeqID(), rgbStamp); data_ = SensorData(LaserScan::backwardCompatibility(scan, cloud.total()/scanDownsampling, 0, scanLocalTransform), rgb, depth, model, this->getNextSeqID(), rgbStamp);
} }
else else
{ {
tangoData_ = SensorData(rgb, depth, model, this->getNextSeqID(), rgbStamp); data_ = SensorData(rgb, depth, model, this->getNextSeqID(), rgbStamp);
} }
tangoData_.setGroundTruth(odom); data_.setGroundTruth(odom);
} }
else else
{ {
LOGE("Could not get depth and rgb images!?!"); LOGE("Could not get depth and rgb images!?!");
tangoData_ = SensorData(); data_ = SensorData();
return; return;
} }
if(notify) if(notify)
{ {
tangoDataReady_.release(); dataReady_.release();
} }
LOGD("process cloud received %fs", timer.ticks()); LOGD("process cloud received %fs", timer.ticks());
} }
@@ -709,7 +709,7 @@ void CameraTango::rgbReceived(const cv::Mat & tangoImage, int type, double times
{ {
//LOGD("RGB received! %fs", timestamp); //LOGD("RGB received! %fs", timestamp);
boost::mutex::scoped_lock lock(tangoDataMutex_); boost::mutex::scoped_lock lock(dataMutex_);
tangoColor_ = tangoImage.clone(); tangoColor_ = tangoImage.clone();
tangoColorStamp_ = timestamp; tangoColorStamp_ = timestamp;
@@ -775,11 +775,10 @@ rtabmap::Transform CameraTango::getPoseAtTimestamp(double timestamp)
return pose; return pose;
} }
SensorData CameraTango::updateDataOnRender(Transform & pose) SensorData CameraTango::captureImage(CameraInfo * info)
{ {
//LOGI("Capturing image..."); //LOGI("Capturing image...");
pose.setNull();
if(textureId_ == 0) if(textureId_ == 0)
{ {
glGenTextures(1, &textureId_); glGenTextures(1, &textureId_);
@@ -798,7 +797,10 @@ SensorData CameraTango::updateDataOnRender(Transform & pose)
if (status == TANGO_SUCCESS) if (status == TANGO_SUCCESS)
{ {
pose = getPoseAtTimestamp(video_overlay_timestamp); if(info)
{
info->odomPose = getPoseAtTimestamp(video_overlay_timestamp);
}
int rotation = static_cast<int>(getScreenRotation()) + 1; // remove 90deg camera rotation int rotation = static_cast<int>(getScreenRotation()) + 1; // remove 90deg camera rotation
if (rotation > 3) { if (rotation > 3) {
@@ -874,14 +876,17 @@ SensorData CameraTango::updateDataOnRender(Transform & pose)
} }
SensorData data; SensorData data;
if(tangoDataReady_.acquireTry(1)) if(dataReady_.acquireTry(1))
{ {
boost::mutex::scoped_lock lock(tangoDataMutex_); boost::mutex::scoped_lock lock(dataMutex_);
data = tangoData_; data = data_;
tangoData_ = SensorData(); data_ = SensorData();
pose = data.groundTruth(); if(info)
{
info->odomPose = data.groundTruth();
data.setGroundTruth(Transform()); data.setGroundTruth(Transform());
} }
}
return data; return data;
} }
+5 -4
View File
@@ -52,6 +52,7 @@ public:
virtual void close(); // close Tango connection virtual void close(); // close Tango connection
virtual std::string getSerial() const; virtual std::string getSerial() const;
rtabmap::Transform tangoPoseToTransform(const TangoPoseData * tangoPose) const; rtabmap::Transform tangoPoseToTransform(const TangoPoseData * tangoPose) const;
void setColorCamera(bool enabled) {if(!this->isRunning()) colorCamera_ = enabled;}
void setDecimation(int value) {decimation_ = value;} void setDecimation(int value) {decimation_ = value;}
void setRawScanPublished(bool enabled) {rawScanPublished_ = enabled;} void setRawScanPublished(bool enabled) {rawScanPublished_ = enabled;}
@@ -60,7 +61,7 @@ public:
void tangoEventReceived(int type, const char * key, const char * value); void tangoEventReceived(int type, const char * key, const char * value);
protected: protected:
virtual SensorData updateDataOnRender(Transform & pose); virtual SensorData captureImage(CameraInfo * info = 0);
private: private:
rtabmap::Transform getPoseAtTimestamp(double timestamp); rtabmap::Transform getPoseAtTimestamp(double timestamp);
@@ -70,12 +71,12 @@ private:
bool colorCamera_; bool colorCamera_;
int decimation_; int decimation_;
bool rawScanPublished_; bool rawScanPublished_;
SensorData tangoData_; SensorData data_;
cv::Mat tangoColor_; cv::Mat tangoColor_;
int tangoColorType_; int tangoColorType_;
double tangoColorStamp_; double tangoColorStamp_;
boost::mutex tangoDataMutex_; boost::mutex dataMutex_;
USemaphore tangoDataReady_; USemaphore dataReady_;
cv::Mat fisheyeRectifyMapX_; cv::Mat fisheyeRectifyMapX_;
cv::Mat fisheyeRectifyMapY_; cv::Mat fisheyeRectifyMapY_;
}; };
+97 -71
View File
@@ -65,7 +65,6 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <rtabmap/core/GainCompensator.h> #include <rtabmap/core/GainCompensator.h>
#include <rtabmap/core/DBDriver.h> #include <rtabmap/core/DBDriver.h>
#include <rtabmap/core/Recovery.h> #include <rtabmap/core/Recovery.h>
#include <rtabmap/core/lidar/LidarVLP16.h>
#include <pcl/common/common.h> #include <pcl/common/common.h>
#include <pcl/filters/extract_indices.h> #include <pcl/filters/extract_indices.h>
#include <pcl/io/ply_io.h> #include <pcl/io/ply_io.h>
@@ -135,7 +134,6 @@ rtabmap::ParametersMap RTABMapApp::getRtabmapParameters()
parameters.insert(rtabmap::ParametersPair(rtabmap::Parameters::kRtabmapPublishLikelihood(), std::string("false"))); parameters.insert(rtabmap::ParametersPair(rtabmap::Parameters::kRtabmapPublishLikelihood(), std::string("false")));
parameters.insert(rtabmap::ParametersPair(rtabmap::Parameters::kRtabmapPublishPdf(), std::string("false"))); parameters.insert(rtabmap::ParametersPair(rtabmap::Parameters::kRtabmapPublishPdf(), std::string("false")));
parameters.insert(rtabmap::ParametersPair(rtabmap::Parameters::kRtabmapStartNewMapOnLoopClosure(), uBool2Str(!localizationMode_ && appendMode_))); parameters.insert(rtabmap::ParametersPair(rtabmap::Parameters::kRtabmapStartNewMapOnLoopClosure(), uBool2Str(!localizationMode_ && appendMode_)));
parameters.insert(rtabmap::ParametersPair(rtabmap::Parameters::kRGBDAggressiveLoopThr(), "0.0"));
parameters.insert(rtabmap::ParametersPair(rtabmap::Parameters::kMemBinDataKept(), uBool2Str(!trajectoryMode_))); parameters.insert(rtabmap::ParametersPair(rtabmap::Parameters::kMemBinDataKept(), uBool2Str(!trajectoryMode_)));
parameters.insert(rtabmap::ParametersPair(rtabmap::Parameters::kOptimizerIterations(), "10")); parameters.insert(rtabmap::ParametersPair(rtabmap::Parameters::kOptimizerIterations(), "10"));
parameters.insert(rtabmap::ParametersPair(rtabmap::Parameters::kMemIncrementalMemory(), uBool2Str(!localizationMode_))); parameters.insert(rtabmap::ParametersPair(rtabmap::Parameters::kMemIncrementalMemory(), uBool2Str(!localizationMode_)));
@@ -204,7 +202,6 @@ RTABMapApp::RTABMapApp() :
#endif #endif
cameraDriver_(0), cameraDriver_(0),
camera_(0), camera_(0),
sensorCaptureThread_(0),
rtabmapThread_(0), rtabmapThread_(0),
rtabmap_(0), rtabmap_(0),
logHandler_(0), logHandler_(0),
@@ -219,7 +216,6 @@ RTABMapApp::RTABMapApp() :
cameraColor_(true), cameraColor_(true),
fullResolution_(false), fullResolution_(false),
appendMode_(true), appendMode_(true),
useExternalLidar_(false),
maxCloudDepth_(2.5), maxCloudDepth_(2.5),
minCloudDepth_(0.0), minCloudDepth_(0.0),
cloudDensityLevel_(1), cloudDensityLevel_(1),
@@ -541,7 +537,7 @@ int RTABMapApp::openDatabase(const std::string & databasePath, bool databaseInMe
// Voxelize and filter depending on the previous cloud? // Voxelize and filter depending on the previous cloud?
pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud; pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud;
pcl::IndicesPtr indices(new std::vector<int>); pcl::IndicesPtr indices(new std::vector<int>);
if(!data.imageRaw().empty() && !data.depthRaw().empty() && (!useExternalLidar_ || data.laserScanRaw().isEmpty())) if(!data.imageRaw().empty() && !data.depthRaw().empty())
{ {
int meshDecimation = updateMeshDecimation(data.depthRaw().cols, data.depthRaw().rows); int meshDecimation = updateMeshDecimation(data.depthRaw().cols, data.depthRaw().rows);
@@ -941,19 +937,6 @@ bool RTABMapApp::startCamera()
LOGI("Start camera thread"); LOGI("Start camera thread");
cameraJustInitialized_ = true; cameraJustInitialized_ = true;
if(useExternalLidar_)
{
rtabmap::LidarVLP16 * lidar = new rtabmap::LidarVLP16(boost::asio::ip::address_v4::from_string("192.168.1.201"), 2368, true);
lidar->init();
camera_->setImageRate(0); // if lidar, to get close camera synchronization
sensorCaptureThread_ = new rtabmap::SensorCaptureThread(lidar, camera_, camera_, rtabmap::Transform::getIdentity());
sensorCaptureThread_->setScanParameters(false, 1, 0.0f, 0.0f, 0.0f, 0, 0.0f, 0.0f, true);
}
else
{
sensorCaptureThread_ = new rtabmap::SensorCaptureThread(camera_);
}
sensorCaptureThread_->start();
return true; return true;
} }
UERROR("Failed camera initialization!"); UERROR("Failed camera initialization!");
@@ -965,12 +948,13 @@ void RTABMapApp::stopCamera()
LOGI("stopCamera()"); LOGI("stopCamera()");
{ {
boost::mutex::scoped_lock lock(cameraMutex_); boost::mutex::scoped_lock lock(cameraMutex_);
if(sensorCaptureThread_!=0) if(camera_!=0)
{ {
sensorCaptureThread_->join(true); camera_->join(true);
delete sensorCaptureThread_; // camera_ is closed and deleted inside camera_->close();
sensorCaptureThread_ = 0; delete camera_;
camera_ = 0; camera_ = 0;
poseBuffer_.clear();
} }
} }
{ {
@@ -1257,7 +1241,7 @@ int RTABMapApp::Render()
std::list<rtabmap::RtabmapEvent*> rtabmapEvents; std::list<rtabmap::RtabmapEvent*> rtabmapEvents;
try try
{ {
if(sensorCaptureThread_ == 0) if(camera_ == 0)
{ {
// We are not doing continous drawing, just measure single draw // We are not doing continous drawing, just measure single draw
fpsTime_.restart(); fpsTime_.restart();
@@ -1288,15 +1272,18 @@ int RTABMapApp::Render()
{ {
if(cameraDriver_ <= 2) if(cameraDriver_ <= 2)
{ {
camera_->updateOnRender(); camera_->spinOnce();
} }
#ifdef DEBUG_RENDERING_PERFORMANCE #ifdef DEBUG_RENDERING_PERFORMANCE
LOGW("Camera updateOnRender %fs", time.ticks()); LOGW("Camera spinOnce %fs", time.ticks());
#endif #endif
if(cameraDriver_ != 2)
{
if(main_scene_.background_renderer_ == 0 && camera_->getTextureId() != 0) if(main_scene_.background_renderer_ == 0 && camera_->getTextureId() != 0)
{ {
main_scene_.background_renderer_ = new BackgroundRenderer(); main_scene_.background_renderer_ = new BackgroundRenderer();
main_scene_.background_renderer_->InitializeGlContent(((rtabmap::CameraMobile*)camera_)->getTextureId(), cameraDriver_ <= 2); main_scene_.background_renderer_->InitializeGlContent(((rtabmap::CameraMobile*)camera_)->getTextureId(), cameraDriver_ == 0 || cameraDriver_ == 1);
} }
if(camera_->uvsInitialized()) if(camera_->uvsInitialized())
{ {
@@ -1329,6 +1316,7 @@ int RTABMapApp::Render()
UERROR("invalid occlusionModel: %f %f %f %f %dx%d", occlusionModel.fx(), occlusionModel.fy(), occlusionModel.cx(), occlusionModel.cy(), occlusionModel.imageWidth(), occlusionModel.imageHeight()); UERROR("invalid occlusionModel: %f %f %f %f %dx%d", occlusionModel.fx(), occlusionModel.fy(), occlusionModel.cx(), occlusionModel.cy(), occlusionModel.imageWidth(), occlusionModel.imageHeight());
} }
} }
}
#ifdef DEBUG_RENDERING_PERFORMANCE #ifdef DEBUG_RENDERING_PERFORMANCE
LOGW("Update background and occlusion mesh %fs", time.ticks()); LOGW("Update background and occlusion mesh %fs", time.ticks());
#endif #endif
@@ -1346,14 +1334,14 @@ int RTABMapApp::Render()
} }
} }
rtabmap::SensorEvent sensorEvent; rtabmap::OdometryEvent odomEvent;
{ {
boost::mutex::scoped_lock lock(sensorMutex_); boost::mutex::scoped_lock lock(odomMutex_);
if(sensorEvents_.size()) if(odomEvents_.size())
{ {
LOGI("Process sensor events"); LOGI("Process odom events");
sensorEvent = sensorEvents_.back(); odomEvent = odomEvents_.back();
sensorEvents_.clear(); odomEvents_.clear();
if(cameraJustInitialized_) if(cameraJustInitialized_)
{ {
notifyCameraStarted = true; notifyCameraStarted = true;
@@ -1373,7 +1361,7 @@ int RTABMapApp::Render()
{ {
main_scene_.SetCameraPose(rtabmap::opengl_world_T_rtabmap_world*pose*rtabmap::optical_T_opengl); main_scene_.SetCameraPose(rtabmap::opengl_world_T_rtabmap_world*pose*rtabmap::optical_T_opengl);
} }
if(sensorCaptureThread_!=0 && cameraJustInitialized_) if(camera_!=0 && cameraJustInitialized_)
{ {
notifyCameraStarted = true; notifyCameraStarted = true;
cameraJustInitialized_ = false; cameraJustInitialized_ = false;
@@ -1574,9 +1562,9 @@ int RTABMapApp::Render()
if(clearSceneOnNextRender_) if(clearSceneOnNextRender_)
{ {
LOGI("Clearing all rendering data..."); LOGI("Clearing all rendering data...");
sensorMutex_.lock(); odomMutex_.lock();
sensorEvents_.clear(); odomEvents_.clear();
sensorMutex_.unlock(); odomMutex_.unlock();
poseMutex_.lock(); poseMutex_.lock();
poseEvents_.clear(); poseEvents_.clear();
@@ -1812,7 +1800,7 @@ int RTABMapApp::Render()
// Voxelize and filter depending on the previous cloud? // Voxelize and filter depending on the previous cloud?
pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud; pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud;
pcl::IndicesPtr indices(new std::vector<int>); pcl::IndicesPtr indices(new std::vector<int>);
if(!data.imageRaw().empty() && !data.depthRaw().empty() && (!useExternalLidar_ || data.laserScanRaw().isEmpty())) if(!data.imageRaw().empty() && !data.depthRaw().empty())
{ {
int meshDecimation = updateMeshDecimation(data.depthRaw().cols, data.depthRaw().rows); int meshDecimation = updateMeshDecimation(data.depthRaw().cols, data.depthRaw().rows);
cloud = rtabmap::util3d::cloudRGBFromSensorData(data, meshDecimation, maxCloudDepth_, minCloudDepth_, indices.get()); cloud = rtabmap::util3d::cloudRGBFromSensorData(data, meshDecimation, maxCloudDepth_, minCloudDepth_, indices.get());
@@ -2016,26 +2004,26 @@ int RTABMapApp::Render()
} }
else else
{ {
main_scene_.setCloudVisible(-1, odomCloudShown_ && !trajectoryMode_ && sensorCaptureThread_!=0); main_scene_.setCloudVisible(-1, odomCloudShown_ && !trajectoryMode_ && camera_!=0);
//just process the last one //just process the last one
if(!sensorEvent.info().odomPose.isNull()) if(!odomEvent.pose().isNull())
{ {
if(odomCloudShown_ && !trajectoryMode_) if(odomCloudShown_ && !trajectoryMode_)
{ {
if((!sensorEvent.data().imageRaw().empty() && !sensorEvent.data().depthRaw().empty()) || !sensorEvent.data().laserScanRaw().isEmpty()) if((!odomEvent.data().imageRaw().empty() && !odomEvent.data().depthRaw().empty()) || !odomEvent.data().laserScanRaw().isEmpty())
{ {
pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud; pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud;
pcl::IndicesPtr indices(new std::vector<int>); pcl::IndicesPtr indices(new std::vector<int>);
if(!sensorEvent.data().imageRaw().empty() && !sensorEvent.data().depthRaw().empty() && (!useExternalLidar_ || sensorEvent.data().laserScanRaw().isEmpty())) if((!odomEvent.data().imageRaw().empty() && !odomEvent.data().depthRaw().empty()))
{ {
int meshDecimation = updateMeshDecimation(sensorEvent.data().depthRaw().cols, sensorEvent.data().depthRaw().rows); int meshDecimation = updateMeshDecimation(odomEvent.data().depthRaw().cols, odomEvent.data().depthRaw().rows);
cloud = rtabmap::util3d::cloudRGBFromSensorData(sensorEvent.data(), meshDecimation, maxCloudDepth_, minCloudDepth_, indices.get()); cloud = rtabmap::util3d::cloudRGBFromSensorData(odomEvent.data(), meshDecimation, maxCloudDepth_, minCloudDepth_, indices.get());
} }
else else
{ {
//scan //scan
cloud = rtabmap::util3d::laserScanToPointCloudRGB(rtabmap::util3d::commonFiltering(sensorEvent.data().laserScanRaw(), 1, minCloudDepth_, maxCloudDepth_), sensorEvent.data().laserScanRaw().localTransform(), 255, 255, 255); cloud = rtabmap::util3d::laserScanToPointCloudRGB(rtabmap::util3d::commonFiltering(odomEvent.data().laserScanRaw(), 1, minCloudDepth_, maxCloudDepth_), odomEvent.data().laserScanRaw().localTransform(), 255, 255, 255);
indices->resize(cloud->size()); indices->resize(cloud->size());
for(unsigned int i=0; i<cloud->size(); ++i) for(unsigned int i=0; i<cloud->size(); ++i)
{ {
@@ -2046,10 +2034,10 @@ int RTABMapApp::Render()
if(cloud->size() && indices->size()) if(cloud->size() && indices->size())
{ {
LOGI("Created odom cloud (rgb=%dx%d depth=%dx%d cloud=%dx%d)", LOGI("Created odom cloud (rgb=%dx%d depth=%dx%d cloud=%dx%d)",
sensorEvent.data().imageRaw().cols, sensorEvent.data().imageRaw().rows, odomEvent.data().imageRaw().cols, odomEvent.data().imageRaw().rows,
sensorEvent.data().depthRaw().cols, sensorEvent.data().depthRaw().rows, odomEvent.data().depthRaw().cols, odomEvent.data().depthRaw().rows,
(int)cloud->width, (int)cloud->height); (int)cloud->width, (int)cloud->height);
main_scene_.addCloud(-1, cloud, indices, rtabmap::opengl_world_T_rtabmap_world*mapToOdom_*sensorEvent.info().odomPose); main_scene_.addCloud(-1, cloud, indices, rtabmap::opengl_world_T_rtabmap_world*mapToOdom_*odomEvent.pose());
main_scene_.setCloudVisible(-1, true); main_scene_.setCloudVisible(-1, true);
} }
else else
@@ -2139,7 +2127,7 @@ int RTABMapApp::Render()
lastPostRenderEventTime_ = UTimer::now(); lastPostRenderEventTime_ = UTimer::now();
if(sensorCaptureThread_!=0 && lastPoseEventTime_>0.0 && UTimer::now()-lastPoseEventTime_ > 1.0) if(camera_!=0 && lastPoseEventTime_>0.0 && UTimer::now()-lastPoseEventTime_ > 1.0)
{ {
UERROR("TangoPoseEventNotReceived"); UERROR("TangoPoseEventNotReceived");
UEventsManager::post(new rtabmap::CameraInfoEvent(10, "TangoPoseEventNotReceived", uNumber2Str(UTimer::now()-lastPoseEventTime_, 6))); UEventsManager::post(new rtabmap::CameraInfoEvent(10, "TangoPoseEventNotReceived", uNumber2Str(UTimer::now()-lastPoseEventTime_, 6)));
@@ -2331,7 +2319,7 @@ void RTABMapApp::setTrajectoryMode(bool enabled)
void RTABMapApp::setGraphOptimization(bool enabled) void RTABMapApp::setGraphOptimization(bool enabled)
{ {
graphOptimization_ = enabled; graphOptimization_ = enabled;
if((sensorCaptureThread_ == 0) && rtabmap_ && rtabmap_->getMemory()->getLastWorkingSignature()!=0) if((camera_ == 0) && rtabmap_ && rtabmap_->getMemory()->getLastWorkingSignature()!=0)
{ {
std::map<int, rtabmap::Transform> poses; std::map<int, rtabmap::Transform> poses;
std::multimap<int, rtabmap::Link> links; std::multimap<int, rtabmap::Link> links;
@@ -3721,12 +3709,19 @@ void RTABMapApp::postCameraPoseEvent(
if(qx==0 && qy==0 && qz==0 && qw==0) if(qx==0 && qy==0 && qz==0 && qw==0)
{ {
// Lost! clear buffer // Lost! clear buffer
poseBuffer_.clear();
camera_->resetOrigin(); // we are lost, create new session on next valid frame camera_->resetOrigin(); // we are lost, create new session on next valid frame
return; return;
} }
rtabmap::Transform pose(x,y,z,qx,qy,qz,qw); rtabmap::Transform pose(x,y,z,qx,qy,qz,qw);
pose = rtabmap::rtabmap_world_T_opengl_world * pose * rtabmap::opengl_world_T_rtabmap_world; pose = rtabmap::rtabmap_world_T_opengl_world * pose * rtabmap::opengl_world_T_rtabmap_world;
camera_->poseReceived(pose, stamp); camera_->poseReceived(pose);
poseBuffer_.insert(std::make_pair(stamp, pose));
if(poseBuffer_.size() > 1000)
{
poseBuffer_.erase(poseBuffer_.begin());
}
} }
} }
@@ -3838,33 +3833,56 @@ void RTABMapApp::postOdometryEvent(
{ {
pose = rtabmap::rtabmap_world_T_opengl_world * pose * rtabmap::opengl_world_T_rtabmap_world; pose = rtabmap::rtabmap_world_T_opengl_world * pose * rtabmap::opengl_world_T_rtabmap_world;
rtabmap::Transform poseWithOriginOffset = pose;
if(!camera_->getOriginOffset().isNull())
{
poseWithOriginOffset = camera_->getOriginOffset() * pose;
}
// Registration depth to rgb // Registration depth to rgb
if(!outputDepth.empty() && !depthFrame.isNull() && depth_fx!=0 && (rgbFrame != depthFrame || depthStamp!=stamp)) if(!outputDepth.empty() && !depthFrame.isNull() && depth_fx!=0 && (rgbFrame != depthFrame || depthStamp!=stamp))
{ {
UTimer time; UTimer time;
rtabmap::Transform motion = rtabmap::Transform::getIdentity(); rtabmap::Transform motion = rtabmap::Transform::getIdentity();
if(depthStamp != stamp) if(depthStamp != stamp && !poseBuffer_.empty())
{ {
// Interpolate pose // Interpolate pose
rtabmap::Transform poseDepth; if(!poseBuffer_.empty())
cv::Mat cov;
if(!camera_->getPose(camera_->getStampEpochOffset()+depthStamp, poseDepth, cov, 0.0))
{ {
UERROR("Could not find pose at depth stamp %f (epoch=%f rgb=%f)!", depthStamp, camera_->getStampEpochOffset()+depthStamp, stamp); if(poseBuffer_.rbegin()->first < depthStamp)
{
UWARN("Could not find poses to interpolate at time %f (last is %f)...", depthStamp, poseBuffer_.rbegin()->first);
} }
else else
{ {
std::map<double, rtabmap::Transform >::const_iterator iterB = poseBuffer_.lower_bound(depthStamp);
std::map<double, rtabmap::Transform >::const_iterator iterA = iterB;
rtabmap::Transform poseDepth;
if(iterA != poseBuffer_.begin())
{
iterA = --iterA;
}
if(iterB == poseBuffer_.end())
{
iterB = --iterB;
}
if(iterA == iterB && depthStamp == iterA->first)
{
poseDepth = iterA->second;
}
else if(depthStamp >= iterA->first && depthStamp <= iterB->first)
{
poseDepth = iterA->second.interpolate((depthStamp-iterA->first) / (iterB->first-iterA->first), iterB->second);
}
else if(depthStamp < iterA->first)
{
UERROR("Could not find poses to interpolate at image time %f (earliest is %f). Are sensors synchronized?", depthStamp, iterA->first);
}
else
{
UERROR("Could not find poses to interpolate at image time %f (between %f and %f), Are sensors synchronized?", depthStamp, iterA->first, iterB->first);
}
if(!poseDepth.isNull())
{
#ifndef DISABLE_LOG #ifndef DISABLE_LOG
UDEBUG("poseRGB =%s (stamp=%f)", poseWithOriginOffset.prettyPrint().c_str(), stamp); UDEBUG("poseRGB =%s (stamp=%f)", pose.prettyPrint().c_str(), depthStamp);
UDEBUG("poseDepth=%s (stamp=%f)", poseDepth.prettyPrint().c_str(), depthStamp); UDEBUG("poseDepth=%s (stamp=%f)", poseDepth.prettyPrint().c_str(), depthStamp);
#endif #endif
motion = poseWithOriginOffset.inverse()*poseDepth; motion = pose.inverse()*poseDepth;
// transform in camera frame // transform in camera frame
#ifndef DISABLE_LOG #ifndef DISABLE_LOG
UDEBUG("motion=%s", motion.prettyPrint().c_str()); UDEBUG("motion=%s", motion.prettyPrint().c_str());
@@ -3875,6 +3893,8 @@ void RTABMapApp::postOdometryEvent(
#endif #endif
} }
} }
}
}
rtabmap::Transform rgbToDepth = motion*rgbFrame.inverse()*depthFrame; rtabmap::Transform rgbToDepth = motion*rgbFrame.inverse()*depthFrame;
float scale = (float)outputDepth.cols/(float)outputRGB.cols; float scale = (float)outputDepth.cols/(float)outputRGB.cols;
cv::Mat colorK = (cv::Mat_<double>(3,3) << cv::Mat colorK = (cv::Mat_<double>(3,3) <<
@@ -3921,6 +3941,11 @@ void RTABMapApp::postOdometryEvent(
if(!outputDepth.empty()) if(!outputDepth.empty())
{ {
rtabmap::Transform poseWithOriginOffset = pose;
if(!camera_->getOriginOffset().isNull())
{
poseWithOriginOffset = camera_->getOriginOffset() * pose;
}
rtabmap::CameraModel depthModel = model.scaled(float(outputDepth.cols) / float(model.imageWidth())); rtabmap::CameraModel depthModel = model.scaled(float(outputDepth.cols) / float(model.imageWidth()));
depthModel.setLocalTransform(poseWithOriginOffset*model.localTransform()); depthModel.setLocalTransform(poseWithOriginOffset*model.localTransform());
camera_->setOcclusionImage(outputDepth, depthModel); camera_->setOcclusionImage(outputDepth, depthModel);
@@ -3946,7 +3971,8 @@ void RTABMapApp::postOdometryEvent(
texCoords[5] = t5; texCoords[5] = t5;
texCoords[6] = t6; texCoords[6] = t6;
texCoords[7] = t7; texCoords[7] = t7;
camera_->update(data, pose, viewMatrixMat, projectionMatrix, main_scene_.GetCameraType() == tango_gl::GestureCamera::kFirstPerson?texCoords:0); camera_->setData(data, pose, viewMatrixMat, projectionMatrix, main_scene_.GetCameraType() == tango_gl::GestureCamera::kFirstPerson?texCoords:0);
camera_->spinOnce();
} }
} }
} }
@@ -3963,17 +3989,17 @@ void RTABMapApp::postOdometryEvent(
bool RTABMapApp::handleEvent(UEvent * event) bool RTABMapApp::handleEvent(UEvent * event)
{ {
if(sensorCaptureThread_!=0) if(camera_!=0)
{ {
// called from events manager thread, so protect the data // called from events manager thread, so protect the data
if(event->getClassName().compare("SensorEvent") == 0) if(event->getClassName().compare("OdometryEvent") == 0)
{ {
LOGI("Received SensorEvent!"); LOGI("Received OdometryEvent!");
if(sensorMutex_.try_lock()) if(odomMutex_.try_lock())
{ {
sensorEvents_.clear(); odomEvents_.clear();
sensorEvents_.push_back(*((rtabmap::SensorEvent*)(event))); odomEvents_.push_back(*((rtabmap::OdometryEvent*)(event)));
sensorMutex_.unlock(); odomMutex_.unlock();
} }
} }
if(event->getClassName().compare("RtabmapEvent") == 0) if(event->getClassName().compare("RtabmapEvent") == 0)
+3 -6
View File
@@ -40,9 +40,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "util.h" #include "util.h"
#include "ProgressionStatus.h" #include "ProgressionStatus.h"
#include <rtabmap/core/SensorCaptureThread.h>
#include <rtabmap/core/RtabmapThread.h> #include <rtabmap/core/RtabmapThread.h>
#include <rtabmap/core/SensorEvent.h>
#include <rtabmap/utilite/UEventsHandler.h> #include <rtabmap/utilite/UEventsHandler.h>
#include <boost/thread/mutex.hpp> #include <boost/thread/mutex.hpp>
#include <pcl/pcl_base.h> #include <pcl/pcl_base.h>
@@ -211,7 +209,6 @@ class RTABMapApp : public UEventsHandler {
private: private:
int cameraDriver_; int cameraDriver_;
rtabmap::CameraMobile * camera_; rtabmap::CameraMobile * camera_;
rtabmap::SensorCaptureThread * sensorCaptureThread_;
rtabmap::RtabmapThread * rtabmapThread_; rtabmap::RtabmapThread * rtabmapThread_;
rtabmap::Rtabmap * rtabmap_; rtabmap::Rtabmap * rtabmap_;
rtabmap::LogHandler * logHandler_; rtabmap::LogHandler * logHandler_;
@@ -227,7 +224,6 @@ class RTABMapApp : public UEventsHandler {
bool cameraColor_; bool cameraColor_;
bool fullResolution_; bool fullResolution_;
bool appendMode_; bool appendMode_;
bool useExternalLidar_;
float maxCloudDepth_; float maxCloudDepth_;
float minCloudDepth_; float minCloudDepth_;
int cloudDensityLevel_; int cloudDensityLevel_;
@@ -274,15 +270,16 @@ class RTABMapApp : public UEventsHandler {
UTimer fpsTime_; UTimer fpsTime_;
std::list<rtabmap::RtabmapEvent*> rtabmapEvents_; std::list<rtabmap::RtabmapEvent*> rtabmapEvents_;
std::list<rtabmap::SensorEvent> sensorEvents_; std::list<rtabmap::OdometryEvent> odomEvents_;
std::list<rtabmap::Transform> poseEvents_; std::list<rtabmap::Transform> poseEvents_;
std::map<double, rtabmap::Transform> poseBuffer_;
rtabmap::Transform mapToOdom_; rtabmap::Transform mapToOdom_;
boost::mutex cameraMutex_; boost::mutex cameraMutex_;
boost::mutex rtabmapMutex_; boost::mutex rtabmapMutex_;
boost::mutex meshesMutex_; boost::mutex meshesMutex_;
boost::mutex sensorMutex_; boost::mutex odomMutex_;
boost::mutex poseMutex_; boost::mutex poseMutex_;
boost::mutex renderingMutex_; boost::mutex renderingMutex_;
+2 -2
View File
@@ -155,7 +155,7 @@ void BackgroundRenderer::InitializeGlContent(GLuint textureId, bool oes)
} }
void BackgroundRenderer::Draw(const float * transformed_uvs, const GLuint & depthTexture, int screenWidth, int screenHeight, bool redUnknown) { void BackgroundRenderer::Draw(const float * transformed_uvs, const GLuint & depthTexture, int screenWidth, int screenHeight, bool redUnknown) {
static_assert(std::extent<decltype(BackgroundRenderer_kVerticesDevice)>::value == kNumVertices * 2, "Incorrect kVertices length"); static_assert(std::extent<decltype(BackgroundRenderer_kVertices)>::value == kNumVertices * 2, "Incorrect kVertices length");
GLuint program = shaderPrograms_[depthTexture>0?1:0]; GLuint program = shaderPrograms_[depthTexture>0?1:0];
@@ -191,7 +191,7 @@ void BackgroundRenderer::Draw(const float * transformed_uvs, const GLuint & dept
GLuint attributeVertices = glGetAttribLocation(program, "a_Position"); GLuint attributeVertices = glGetAttribLocation(program, "a_Position");
GLuint attributeUvs = glGetAttribLocation(program, "a_TexCoord"); GLuint attributeUvs = glGetAttribLocation(program, "a_TexCoord");
glVertexAttribPointer(attributeVertices, 2, GL_FLOAT, GL_FALSE, 0, BackgroundRenderer_kVerticesDevice); glVertexAttribPointer(attributeVertices, 2, GL_FLOAT, GL_FALSE, 0, BackgroundRenderer_kVertices);
glVertexAttribPointer(attributeUvs, 2, GL_FLOAT, GL_FALSE, 0, transformed_uvs?transformed_uvs:BackgroundRenderer_kTexCoord); glVertexAttribPointer(attributeUvs, 2, GL_FLOAT, GL_FALSE, 0, transformed_uvs?transformed_uvs:BackgroundRenderer_kTexCoord);
glEnableVertexAttribArray(attributeVertices); glEnableVertexAttribArray(attributeVertices);
+1 -7
View File
@@ -28,15 +28,9 @@
#include "util.h" #include "util.h"
static const GLfloat BackgroundRenderer_kVerticesDevice[] = { static const GLfloat BackgroundRenderer_kVertices[] = {
-1.0f, -1.0f, +1.0f, -1.0f, -1.0f, +1.0f, +1.0f, +1.0f, -1.0f, -1.0f, +1.0f, -1.0f, -1.0f, +1.0f, +1.0f, +1.0f,
}; };
//static const GLfloat BackgroundRenderer_kVerticesView[] = {
// 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f,
//};
static const GLfloat BackgroundRenderer_kVerticesView[] = {
0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f,
};
static const GLfloat BackgroundRenderer_kTexCoord[] = { static const GLfloat BackgroundRenderer_kTexCoord[] = {
1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f,
}; };
+1 -4
View File
@@ -1,4 +1 @@
# Ignore everything in this directory *.jar
*
# Except this file
!.gitignore
+1 -1
View File
@@ -84,7 +84,7 @@
<string name="pref_key_depth_from_motion">pref_key_depth_from_motion</string> <string name="pref_key_depth_from_motion">pref_key_depth_from_motion</string>
<string name="pref_default_depth_from_motion">false</string> <string name="pref_default_depth_from_motion">false</string>
<string name="pref_key_arcore_localization_filtering_speed">pref_key_arcore_localization_filtering_speed</string> <string name="pref_key_arcore_localization_filtering_speed">pref_key_arcore_localization_filtering_speed</string>
<string name="pref_default_arcore_localization_filtering_speed">0</string> <string name="pref_default_arcore_localization_filtering_speed">1</string>
<string name="pref_key_update_rate">pref_key_update_rate</string> <string name="pref_key_update_rate">pref_key_update_rate</string>
<string name="pref_default_update_rate">1</string> <string name="pref_default_update_rate">1</string>
<string name="pref_key_max_speed">pref_key_max_speed</string> <string name="pref_key_max_speed">pref_key_max_speed</string>
@@ -116,9 +116,6 @@ public class ARCoreSharedCamera {
public TOF_ImageReader mTOFImageReader = new TOF_ImageReader(); public TOF_ImageReader mTOFImageReader = new TOF_ImageReader();
private boolean mTOFAvailable = false; private boolean mTOFAvailable = false;
ByteBuffer mPreviousDepth = null;
double mPreviousDepthStamp = 0.0;
public boolean isDepthSupported() {return mTOFAvailable;} public boolean isDepthSupported() {return mTOFAvailable;}
public void setToast(Toast toast) public void setToast(Toast toast)
@@ -701,7 +698,6 @@ public class ARCoreSharedCamera {
mToast.setText(msg); mToast.setText(msg);
} }
previousAnchorPose = null; previousAnchorPose = null;
arCoreCorrection = Pose.IDENTITY;
} }
} }
}); });
@@ -722,8 +718,7 @@ public class ARCoreSharedCamera {
final double speed = Math.sqrt(t[0]*t[0]+t[1]*t[1]+t[2]*t[2])/((double)(frame.getTimestamp()-previousAnchorTimeStamp)/10e8); final double speed = Math.sqrt(t[0]*t[0]+t[1]*t[1]+t[2]*t[2])/((double)(frame.getTimestamp()-previousAnchorTimeStamp)/10e8);
if(speed>=mARCoreLocalizationFilteringSpeed) if(speed>=mARCoreLocalizationFilteringSpeed)
{ {
// Only correct the translation to not lose rotation aligned with gravity arCoreCorrection = arCoreCorrection.compose(previousAnchorPose).compose(pose.inverse());
arCoreCorrection = arCoreCorrection.compose(previousAnchorPose.compose(pose.inverse()).extractTranslation());
t = arCoreCorrection.getTranslation(); t = arCoreCorrection.getTranslation();
Log.e(TAG, String.format("POTENTIAL TELEPORTATION!!!!!!!!!!!!!! previous anchor moved (speed=%f), new arcorrection: %f %f %f", speed, t[0], t[1], t[2])); Log.e(TAG, String.format("POTENTIAL TELEPORTATION!!!!!!!!!!!!!! previous anchor moved (speed=%f), new arcorrection: %f %f %f", speed, t[0], t[1], t[2]));
@@ -749,6 +744,7 @@ public class ARCoreSharedCamera {
{ {
mToast.setText(msg); mToast.setText(msg);
} }
previousAnchorPose = null;
} }
} }
}); });
@@ -759,8 +755,9 @@ public class ARCoreSharedCamera {
previousAnchorTimeStamp = frame.getTimestamp(); previousAnchorTimeStamp = frame.getTimestamp();
double stamp = (double)frame.getTimestamp()/10e8; double stamp = (double)frame.getTimestamp()/10e8;
if(!RTABMapActivity.DISABLE_LOG) Log.d(TAG, String.format("pose=%f %f %f arcore %f %f %f cor= %f %f %f stamp=%f", odomPose.tx(), odomPose.ty(), odomPose.tz(), pose.tx(), pose.ty(), pose.tz(), arCoreCorrection.tx(), arCoreCorrection.ty(), arCoreCorrection.tz(), stamp)); if(!RTABMapActivity.DISABLE_LOG) Log.d(TAG, String.format("pose=%f %f %f q=%f %f %f %f stamp=%f", odomPose.tx(), odomPose.ty(), odomPose.tz(), odomPose.qx(), odomPose.qy(), odomPose.qz(), odomPose.qw(), stamp));
RTABMapLib.postCameraPoseEvent(RTABMapActivity.nativeApplication, odomPose.tx(), odomPose.ty(), odomPose.tz(), odomPose.qx(), odomPose.qy(), odomPose.qz(), odomPose.qw(), stamp); RTABMapLib.postCameraPoseEvent(RTABMapActivity.nativeApplication, odomPose.tx(), odomPose.ty(), odomPose.tz(), odomPose.qx(), odomPose.qy(), odomPose.qz(), odomPose.qw(), stamp);
CameraIntrinsics intrinsics = camera.getImageIntrinsics(); CameraIntrinsics intrinsics = camera.getImageIntrinsics();
try{ try{
Image image = frame.acquireCameraImage(); Image image = frame.acquireCameraImage();
@@ -817,12 +814,6 @@ public class ARCoreSharedCamera {
depthStamp = (double)mTOFImageReader.timestamp/10e8; depthStamp = (double)mTOFImageReader.timestamp/10e8;
} }
if(mPreviousDepth == null)
{
mPreviousDepth = depth;
mPreviousDepthStamp = depthStamp;
}
if(!RTABMapActivity.DISABLE_LOG) Log.d(TAG, String.format("Depth %dx%d len=%dbytes format=%d stamp=%f", if(!RTABMapActivity.DISABLE_LOG) Log.d(TAG, String.format("Depth %dx%d len=%dbytes format=%d stamp=%f",
mTOFImageReader.WIDTH, mTOFImageReader.HEIGHT, depth.limit(), ImageFormat.DEPTH16, depthStamp)); mTOFImageReader.WIDTH, mTOFImageReader.HEIGHT, depth.limit(), ImageFormat.DEPTH16, depthStamp));
@@ -834,17 +825,13 @@ public class ARCoreSharedCamera {
rgbExtrinsics.tx(), rgbExtrinsics.ty(), rgbExtrinsics.tz(), rgbExtrinsics.qx(), rgbExtrinsics.qy(), rgbExtrinsics.qz(), rgbExtrinsics.qw(), rgbExtrinsics.tx(), rgbExtrinsics.ty(), rgbExtrinsics.tz(), rgbExtrinsics.qx(), rgbExtrinsics.qy(), rgbExtrinsics.qz(), rgbExtrinsics.qw(),
depthExtrinsics.tx(), depthExtrinsics.ty(), depthExtrinsics.tz(), depthExtrinsics.qx(), depthExtrinsics.qy(), depthExtrinsics.qz(), depthExtrinsics.qw(), depthExtrinsics.tx(), depthExtrinsics.ty(), depthExtrinsics.tz(), depthExtrinsics.qx(), depthExtrinsics.qy(), depthExtrinsics.qz(), depthExtrinsics.qw(),
stamp, stamp,
depthStamp>stamp?mPreviousDepthStamp:depthStamp, depthStamp,
y, u, v, y.limit(), image.getWidth(), image.getHeight(), image.getFormat(), y, u, v, y.limit(), image.getWidth(), image.getHeight(), image.getFormat(),
depthStamp>stamp?mPreviousDepth:depth, depthStamp>stamp?mPreviousDepth.limit():depth.limit(), mTOFImageReader.WIDTH, mTOFImageReader.HEIGHT, ImageFormat.DEPTH16, depth, depth.limit(), mTOFImageReader.WIDTH, mTOFImageReader.HEIGHT, ImageFormat.DEPTH16,
points, points.limit()/4, points, points.limit()/4,
viewMatrix[12], viewMatrix[13], viewMatrix[14], quat[1], quat[2], quat[3], quat[0], viewMatrix[12], viewMatrix[13], viewMatrix[14], quat[1], quat[2], quat[3], quat[0],
p[0], p[5], p[8], p[9], p[10], p[11], p[14], p[0], p[5], p[8], p[9], p[10], p[11], p[14],
texCoord[0],texCoord[1],texCoord[2],texCoord[3],texCoord[4],texCoord[5],texCoord[6],texCoord[7]); texCoord[0],texCoord[1],texCoord[2],texCoord[3],texCoord[4],texCoord[5],texCoord[6],texCoord[7]);
mPreviousDepthStamp = depthStamp;
mPreviousDepth = depth;
} }
else else
{ {
+2 -2
View File
@@ -284,11 +284,11 @@ void setCameraNative(const void *object, int type) {
} }
void postCameraPoseEventNative(const void *object, void postCameraPoseEventNative(const void *object,
float x, float y, float z, float qx, float qy, float qz, float qw, double stamp) float x, float y, float z, float qx, float qy, float qz, float qw)
{ {
if(object) if(object)
{ {
native(object)->postCameraPoseEvent(x,y,z,qx,qy,qz,qw,stamp); native(object)->postCameraPoseEvent(x,y,z,qx,qy,qz,qw,0.0);
} }
else else
{ {
+1 -1
View File
@@ -67,7 +67,7 @@ bool startCameraNative(const void *object);
void stopCameraNative(const void *object); void stopCameraNative(const void *object);
void setCameraNative(const void *object, int type); void setCameraNative(const void *object, int type);
void postCameraPoseEventNative(const void *object, void postCameraPoseEventNative(const void *object,
float x, float y, float z, float qx, float qy, float qz, float qw, double stamp); float x, float y, float z, float qx, float qy, float qz, float qw);
void postOdometryEventNative(const void *object, void postOdometryEventNative(const void *object,
float x, float y, float z, float qx, float qy, float qz, float qw, float x, float y, float z, float qx, float qy, float qz, float qw,
float fx, float fy, float cx, float cy, float fx, float fy, float cx, float cy,
+4 -4
View File
@@ -216,18 +216,18 @@ class RTABMap {
setCameraNative(native_rtabmap, Int32(type)) setCameraNative(native_rtabmap, Int32(type))
} }
func postCameraPoseEvent(pose: simd_float4x4, stamp: TimeInterval) { func postCameraPoseEvent(pose: simd_float4x4) {
let rotation = GLKMatrix3( let rotation = GLKMatrix3(
m: (pose[0,0], pose[0,1], pose[0,2], m: (pose[0,0], pose[0,1], pose[0,2],
pose[1,0], pose[1,1], pose[1,2], pose[1,0], pose[1,1], pose[1,2],
pose[2,0], pose[2,1], pose[2,2])) pose[2,0], pose[2,1], pose[2,2]))
let quat = GLKQuaternionMakeWithMatrix3(rotation) let quat = GLKQuaternionMakeWithMatrix3(rotation)
postCameraPoseEventNative(native_rtabmap, pose[3,0], pose[3,1], pose[3,2], quat.x, quat.y, quat.z, quat.w, stamp) postCameraPoseEventNative(native_rtabmap, pose[3,0], pose[3,1], pose[3,2], quat.x, quat.y, quat.z, quat.w)
} }
func notifyLost() { func notifyLost() {
// a null transform will make rtabmap creating a new session // a null transform will make rtabmap creating a new session
postCameraPoseEventNative(native_rtabmap, 0,0,0,0,0,0,0,0) postCameraPoseEventNative(native_rtabmap, 0,0,0,0,0,0,0)
} }
func postOdometryEvent(frame: ARFrame, orientation: UIInterfaceOrientation, viewport: CGSize) { func postOdometryEvent(frame: ARFrame, orientation: UIInterfaceOrientation, viewport: CGSize) {
@@ -239,7 +239,7 @@ class RTABMap {
let quat = GLKQuaternionMakeWithMatrix3(rotation) let quat = GLKQuaternionMakeWithMatrix3(rotation)
postCameraPoseEventNative(native_rtabmap, pose[3,0], pose[3,1], pose[3,2], quat.x, quat.y, quat.z, quat.w, frame.timestamp) postCameraPoseEventNative(native_rtabmap, pose[3,0], pose[3,1], pose[3,2], quat.x, quat.y, quat.z, quat.w)
let confMap = frame.sceneDepth?.confidenceMap let confMap = frame.sceneDepth?.confidenceMap
let depthMap = frame.sceneDepth?.depthMap let depthMap = frame.sceneDepth?.depthMap
-25
View File
@@ -1,25 +0,0 @@
To reproduce results (based on parameters of this [paper](https://introlab.3it.usherbrooke.ca/mediawiki-introlab/images/b/bc/TRO2013.pdf)):
```
rtabmap-console \
--Rtabmap/StatisticLogged true\
--Rtabmap/StatisticLoggedHeaders false\
--Kp/DetectorStrategy 0\
--Rtabmap/MemoryThr 300\
--Rtabmap/LoopRatio 0.9\
--SURF/HessianThreshold 150\
--Mem/STMSize 30\
--Vis/MaxFeatures 400\
--Kp/TfIdfLikelihoodUsed false\
--Kp/MaxFeatures 400\
--Kp/BadSignRatio 0.25\
--Mem/BadSignaturesIgnored true\
--Mem/RehearsalSimilarity 0.20\
--Mem/RecentWmRatio 0.2\
-gt "~/Downloads/UdeS_1Hz.png"\
~/Downloads/UdeS_1Hz
```
Adding the ground truth file here is optional to show recall at 100% precision at the end of the process directly without using the octave/MATLAB script below. For NewCollege and CityCentre datasets, `rtabmap-imagesJoiner` can be used to assemble the left and right images together.
To analyze with Octave/MATLAB, drop `LogF.txt` and `LogI.txt` generated files from command above in ShowLogs directly, then execute `showLogs.m`.
+4
View File
@@ -0,0 +1,4 @@
This directory contains some basic concepts on Bayes filtering.
Main scripts :
RecursivesBayes.m
RecursivesBayesAvpd.m
@@ -33,6 +33,7 @@ if ~isempty(GroundTruth)
error(['The ground truth size doesn''t match the log files (LogI=' num2str(length(LogI(:,1))) ', LogF=' num2str(length(LogF(:,1))) ', GT=' num2str(size(GroundTruth, 1)) ')']) error(['The ground truth size doesn''t match the log files (LogI=' num2str(length(LogI(:,1))) ', LogF=' num2str(length(LogF(:,1))) ', GT=' num2str(size(GroundTruth, 1)) ')'])
end end
%[highestHypot, CorrespondingID, GT, Accepted, Good, Index, UnderLoopRatio] descending order %[highestHypot, CorrespondingID, GT, Accepted, Good, Index, UnderLoopRatio] descending order
if(sum(LogI(:,8) == 10) > 0) if(sum(LogI(:,8) == 10) > 0)
%OLD %OLD
@@ -110,14 +111,14 @@ if ~isempty(GroundTruth)
index = find(PR(:,1) == 1); index = find(PR(:,1) == 1);
if ~isempty(index) if ~isempty(index)
maxRecall = PR(index(end),2) * 100; maxRecall = PR(index(end),2) * 100;
display(['Recall max (Precision=100%) = ' num2str(maxRecall) '% (p=' num2str(lc(index(end),1)) '), accepted=' num2str(sum(lc(1:index(end),5) & ~lc(1:index(end),7) & lc(1:index(end),2))) '/' num2str(GT_total_positives)]) display(['Recall max (Precision=100%) = ' num2str(maxRecall) '% (p=' num2str(lc(index(end),1)) '), accepted=' num2str(sum(lc(1:index(end),5) & ~lc(1:index(end),7) & lc(1:index(end),2)))])
else else
display('Recall max (Precision=100%) = 0') display('Recall max (Precision=100%) = 0')
end end
indexAccepted = find(PR(:,3) == 1); indexAccepted = find(PR(:,3) == 1);
if ~isempty(indexAccepted) if ~isempty(indexAccepted)
maxRecall = PR(indexAccepted(end),2) * 100; maxRecall = PR(indexAccepted(end),2) * 100;
display(['Recall max accepted (Precision=100%) = ' num2str(maxRecall) '% (p=' num2str(lc(indexAccepted(end),1)) '), accepted=' num2str(sum(lc(1:indexAccepted(end),5) & ~lc(1:indexAccepted(end),7) & lc(1:indexAccepted(end),2))) '/' num2str(GT_total_positives)]) display(['Recall max accepted (Precision=100%) = ' num2str(maxRecall) '% (p=' num2str(lc(indexAccepted(end),1)) '), accepted=' num2str(sum(lc(1:indexAccepted(end),5) & ~lc(1:indexAccepted(end),7) & lc(1:indexAccepted(end),2)))])
else else
display('Recall max accepted (Precision=100%) = 0') display('Recall max accepted (Precision=100%) = 0')
end end
+1 -3
View File
@@ -22,8 +22,6 @@ function [LogF LogI] = showlogs(PathPrefix, GT_file)
set(0,'defaultAxesFontName', 'Times') set(0,'defaultAxesFontName', 'Times')
set(0,'defaultTextFontName', 'Times') set(0,'defaultTextFontName', 'Times')
close all
if nargin < 2, GT_file = ''; end if nargin < 2, GT_file = ''; end
if nargin < 1, PathPrefix = '.'; end if nargin < 1, PathPrefix = '.'; end
@@ -327,7 +325,7 @@ y(LogI(:, 1) == 0) = [];
x(LogI(:, 1) == 0) = []; x(LogI(:, 1) == 0) = [];
plot(x,y, 'g.') plot(x,y, 'g.')
%set(datacursormode,'UpdateFcn',@(Y,X){sprintf('X: %0.2f',X.Position(1)),sprintf('Y: %0.2f',X.Position(2))}) set(datacursormode,'UpdateFcn',@(Y,X){sprintf('X: %0.2f',X.Position(1)),sprintf('Y: %0.2f',X.Position(2))})
% %matched sign words % %matched sign words
% y = LogI(:,2); % y = LogI(:,2);
% x = 1:length(y); % x = 1:length(y);
-8
View File
@@ -1,8 +0,0 @@
#!/bin/bash
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"
$SCRIPT_DIR/run_bow.sh ~/loop_closure_detection_datasets/NewCollege ~/loop_closure_detection_datasets/NewCollege.png
$SCRIPT_DIR/run_bow.sh ~/loop_closure_detection_datasets/CityCentre ~/loop_closure_detection_datasets/CityCentre.png
$SCRIPT_DIR/run_bow.sh ~/loop_closure_detection_datasets/UdeS_1Hz ~/loop_closure_detection_datasets/UdeS_1Hz.png
-32
View File
@@ -1,32 +0,0 @@
#!/bin/bash
DATASET_FOLDER=""
GT_FILE=""
if [ $# -eq 2 ]
then
DATASET_FOLDER=$1
GT_FILE=$2
else
echo "Usage: run_bow.sh \"dataset folder\" \"ground truth file\""
exit
fi
rtabmap-console \
-quiet \
--Rtabmap/StatisticLogged true\
--Rtabmap/StatisticLoggedHeaders false\
--Kp/DetectorStrategy 0\
--SURF/HessianThreshold 150\
--Rtabmap/MemoryThr 300\
--Rtabmap/LoopRatio 0.9\
--Mem/STMSize 30\
--Vis/MaxFeatures 400\
--Kp/TfIdfLikelihoodUsed false\
--Kp/MaxFeatures 400\
--Kp/BadSignRatio 0.25\
--Mem/BadSignaturesIgnored true\
--Mem/RehearsalSimilarity 0.20\
--Mem/RecentWmRatio 0.20\
-gt "$GT_FILE"\
"$DATASET_FOLDER"
+1 -1
View File
@@ -32,7 +32,7 @@ We provide two formats: the first one is more general and the second one is used
* `device_poses.txt`: VIO poses of each image in `device` frame * `device_poses.txt`: VIO poses of each image in `device` frame
* `camera_poses.txt`: VIO poses of each image in `camera` frame * `camera_poses.txt`: VIO poses of each image in `camera` frame
* [RTAB-Map Databases](https://drive.google.com/file/d/1TklUcTKFSrcg8b0t0U80G_IpFRMVRlY5/view?usp=drive_link) * [RTAB-Map Databases](https://drive.google.com/file/d/1TklUcTKFSrcg8b0t0U80G_IpFRMVRlY5/view?usp=drive_link)
* Dataset now also available on [Federated Research Data Repository (FRDR)](https://doi.org/10.20383/103.0931) (if links above don't work)
## How reproduce results shown in the paper ## How reproduce results shown in the paper
+30
View File
@@ -0,0 +1,30 @@
# - Find Sqlite3
# This module finds an installed Sqlite3 package.
#
# It sets the following variables:
# Sqlite3_FOUND - Set to false, or undefined, if Sqlite3 isn't found.
# Sqlite3_INCLUDE_DIR - The Sqlite3 include directory.
# Sqlite3_LIBRARY - The Sqlite3 library to link against.
FIND_PATH(Sqlite3_INCLUDE_DIR sqlite3.h PATHS $ENV{Sqlite3_ROOT_DIR}/include $ENV{Sqlite3_ROOT_DIR})
FIND_LIBRARY(Sqlite3_LIBRARY NAMES sqlite3 PATHS $ENV{Sqlite3_ROOT_DIR}/lib $ENV{Sqlite3_ROOT_DIR})
IF (Sqlite3_INCLUDE_DIR AND Sqlite3_LIBRARY)
SET(Sqlite3_FOUND TRUE)
SET(Sqlite3_INCLUDE_DIRS ${Sqlite3_INCLUDE_DIR})
SET(Sqlite3_LIBRARIES ${Sqlite3_LIBRARY})
ENDIF (Sqlite3_INCLUDE_DIR AND Sqlite3_LIBRARY)
IF (Sqlite3_FOUND)
# show which Sqlite3 was found only if not quiet
IF (NOT Sqlite3_FIND_QUIETLY)
MESSAGE(STATUS "Found Sqlite3: ${Sqlite3_INCLUDE_DIRS} ${Sqlite3_LIBRARIES}")
ENDIF (NOT Sqlite3_FIND_QUIETLY)
ELSE (Sqlite3_FOUND)
# fatal error if Sqlite3 is required but not found
IF (Sqlite3_FIND_REQUIRED)
MESSAGE(FATAL_ERROR "Could not find Sqlite3")
ENDIF (Sqlite3_FIND_REQUIRED)
ENDIF (Sqlite3_FOUND)
+37 -19
View File
@@ -1,5 +1,5 @@
/* /*
Copyright (c) 2010-2022, Mathieu Labbe - IntRoLab - Universite de Sherbrooke Copyright (c) 2010-2016, Mathieu Labbe - IntRoLab - Universite de Sherbrooke
All rights reserved. All rights reserved.
Redistribution and use in source and binary forms, with or without Redistribution and use in source and binary forms, with or without
@@ -28,32 +28,47 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#pragma once #pragma once
#include "rtabmap/core/rtabmap_core_export.h" // DLL export/import defines #include "rtabmap/core/rtabmap_core_export.h" // DLL export/import defines
#include <rtabmap/core/SensorCapture.h>
#include <rtabmap/core/IMU.h> #include <opencv2/highgui/highgui.hpp>
#include "rtabmap/core/SensorData.h"
#include "rtabmap/core/CameraInfo.h"
#include <set>
#include <stack>
#include <list>
#include <vector>
class UDirectory;
class UTimer;
namespace rtabmap namespace rtabmap
{ {
class IMUFilter;
/** /**
* Class Camera * Class Camera
* *
*/ */
class RTABMAP_CORE_EXPORT Camera : public SensorCapture class RTABMAP_CORE_EXPORT Camera
{ {
public: public:
virtual ~Camera(); virtual ~Camera();
SensorData takeImage(CameraInfo * info = 0);
SensorData takeImage(SensorCaptureInfo * info = 0) {return takeData(info);}
float getImageRate() const {return getFrameRate();}
void setImageRate(float imageRate) {setFrameRate(imageRate);}
void setInterIMUPublishing(bool enabled, IMUFilter * filter = 0); // Take ownership of filter
bool isInterIMUPublishing() const {return publishInterIMU_;}
bool initFromFile(const std::string & calibrationPath); bool initFromFile(const std::string & calibrationPath);
virtual bool init(const std::string & calibrationFolder = ".", const std::string & cameraName = "") = 0;
virtual bool isCalibrated() const = 0; virtual bool isCalibrated() const = 0;
virtual std::string getSerial() const = 0;
virtual bool odomProvided() const { return false; }
virtual bool getPose(double stamp, Transform & pose, cv::Mat & covariance) { return false; }
//getters
float getImageRate() const {return _imageRate;}
const Transform & getLocalTransform() const {return _localTransform;}
//setters
void setImageRate(float imageRate) {_imageRate = imageRate;}
void setLocalTransform(const Transform & localTransform) {_localTransform= localTransform;}
void resetTimer();
protected: protected:
/** /**
* Constructor * Constructor
@@ -63,16 +78,19 @@ protected:
*/ */
Camera(float imageRate = 0, const Transform & localTransform = Transform::getIdentity()); Camera(float imageRate = 0, const Transform & localTransform = Transform::getIdentity());
virtual SensorData captureImage(SensorCaptureInfo * info = 0) = 0; /**
* returned rgb and depth images should be already rectified if calibration was loaded
*/
virtual SensorData captureImage(CameraInfo * info = 0) = 0;
void postInterIMU(const IMU & imu, double stamp); int getNextSeqID() {return ++_seq;}
private: private:
virtual SensorData captureData(SensorCaptureInfo * info = 0) {return captureImage(info);} float _imageRate;
Transform _localTransform;
private: cv::Size _targetImageSize;
IMUFilter * imuFilter_; UTimer * _frameRateTimer;
bool publishInterIMU_; int _seq;
}; };
+62 -1
View File
@@ -27,4 +27,65 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#pragma once #pragma once
#include "rtabmap/core/SensorEvent.h" #include <rtabmap/utilite/UEvent.h>
#include "rtabmap/core/SensorData.h"
#include "rtabmap/core/CameraInfo.h"
namespace rtabmap
{
class CameraEvent :
public UEvent
{
public:
enum Code {
kCodeData,
kCodeNoMoreImages
};
public:
CameraEvent(const cv::Mat & image, int seq=0, double stamp = 0.0, const std::string & cameraName = std::string()) :
UEvent(kCodeData),
data_(image, seq, stamp)
{
cameraInfo_.cameraName = cameraName;
}
CameraEvent() :
UEvent(kCodeNoMoreImages)
{
}
CameraEvent(const SensorData & data) :
UEvent(kCodeData),
data_(data)
{
}
CameraEvent(const SensorData & data, const std::string & cameraName) :
UEvent(kCodeData),
data_(data)
{
cameraInfo_.cameraName = cameraName;
}
CameraEvent(const SensorData & data, const CameraInfo & cameraInfo) :
UEvent(kCodeData),
data_(data),
cameraInfo_(cameraInfo)
{
}
// Image or descriptors
const SensorData & data() const {return data_;}
const std::string & cameraName() const {return cameraInfo_.cameraName;}
const CameraInfo & info() const {return cameraInfo_;}
virtual ~CameraEvent() {}
virtual std::string getClassName() const {return std::string("CameraEvent");}
private:
SensorData data_;
CameraInfo cameraInfo_;
};
} // namespace rtabmap
+47 -1
View File
@@ -27,4 +27,50 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#pragma once #pragma once
#include "rtabmap/core/SensorCaptureInfo.h" #include <string>
namespace rtabmap
{
class CameraInfo
{
public:
CameraInfo() :
cameraName(""),
id(0),
stamp(0.0),
timeCapture(0.0f),
timeDisparity(0.0f),
timeMirroring(0.0f),
timeStereoExposureCompensation(0.0f),
timeImageDecimation(0.0f),
timeHistogramEqualization(0.0f),
timeScanFromDepth(0.0f),
timeUndistortDepth(0.0f),
timeBilateralFiltering(0.0f),
timeTotal(0.0f),
odomCovariance(cv::Mat::eye(6,6,CV_64FC1))
{
}
virtual ~CameraInfo() {}
std::string cameraName;
int id;
double stamp;
float timeCapture;
float timeDisparity;
float timeMirroring;
float timeStereoExposureCompensation;
float timeImageDecimation;
float timeHistogramEqualization;
float timeScanFromDepth;
float timeUndistortDepth;
float timeBilateralFiltering;
float timeTotal;
Transform odomPose;
cv::Mat odomCovariance;
std::vector<float> odomVelocity;
};
} // namespace rtabmap
+1 -1
View File
@@ -37,4 +37,4 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <rtabmap/core/camera/CameraRealSense2.h> #include <rtabmap/core/camera/CameraRealSense2.h>
#include <rtabmap/core/camera/CameraRGBDImages.h> #include <rtabmap/core/camera/CameraRGBDImages.h>
#include <rtabmap/core/camera/CameraK4A.h> #include <rtabmap/core/camera/CameraK4A.h>
#include <rtabmap/core/camera/CameraSeerSense.h>
+133 -1
View File
@@ -27,4 +27,136 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#pragma once #pragma once
#include "rtabmap/core/SensorCaptureThread.h" #include "rtabmap/core/rtabmap_core_export.h" // DLL export/import defines
#include <rtabmap/core/Parameters.h>
#include <rtabmap/core/Transform.h>
#include <rtabmap/utilite/UThread.h>
#include <rtabmap/utilite/UEventsSender.h>
namespace clams
{
class DiscreteDepthDistortionModel;
}
namespace rtabmap
{
class Camera;
class CameraInfo;
class SensorData;
class StereoDense;
class IMUFilter;
class Feature2D;
/**
* Class CameraThread
*
*/
class RTABMAP_CORE_EXPORT CameraThread :
public UThread,
public UEventsSender
{
public:
// ownership transferred
CameraThread(Camera * camera, const ParametersMap & parameters = ParametersMap());
/**
* @param camera the camera to take images from
* @param odomSensor an odometry sensor to get a pose
* @param extrinsics the static transform between odometry sensor's left lens frame to camera's left lens frame
*/
CameraThread(Camera * camera,
Camera * odomSensor,
const Transform & extrinsics,
double poseTimeOffset = 0.0,
float poseScaleFactor = 1.0f,
bool odomAsGt = false,
const ParametersMap & parameters = ParametersMap());
CameraThread(Camera * camera,
bool odomAsGt,
const ParametersMap & parameters = ParametersMap());
virtual ~CameraThread();
void setMirroringEnabled(bool enabled) {_mirroring = enabled;}
void setStereoExposureCompensation(bool enabled) {_stereoExposureCompensation = enabled;}
void setColorOnly(bool colorOnly) {_colorOnly = colorOnly;}
void setImageDecimation(int decimation) {_imageDecimation = decimation;}
void setHistogramMethod(int histogramMethod) {_histogramMethod = histogramMethod;}
void setStereoToDepth(bool enabled) {_stereoToDepth = enabled;}
void setImageRate(float imageRate);
void setDistortionModel(const std::string & path);
void enableBilateralFiltering(float sigmaS, float sigmaR);
void disableBilateralFiltering() {_bilateralFiltering = false;}
void enableIMUFiltering(int filteringStrategy=1, const ParametersMap & parameters = ParametersMap(), bool baseFrameConversion = false);
void disableIMUFiltering();
void enableFeatureDetection(const ParametersMap & parameters = ParametersMap());
void disableFeatureDetection();
// Use new version of this function with groundNormalsUp=0.8 for forceGroundNormalsUp=True and groundNormalsUp=0.0 for forceGroundNormalsUp=False.
RTABMAP_DEPRECATED void setScanParameters(
bool fromDepth,
int downsampleStep, // decimation of the depth image in case the scan is from depth image
float rangeMin,
float rangeMax,
float voxelSize,
int normalsK,
int normalsRadius,
bool forceGroundNormalsUp);
void setScanParameters(
bool fromDepth,
int downsampleStep=1, // decimation of the depth image in case the scan is from depth image
float rangeMin=0.0f,
float rangeMax=0.0f,
float voxelSize = 0.0f,
int normalsK = 0,
int normalsRadius = 0.0f,
float groundNormalsUp = 0.0f);
void postUpdate(SensorData * data, CameraInfo * info = 0) const;
//getters
bool isPaused() const {return !this->isRunning();}
bool isCapturing() const {return this->isRunning();}
bool odomProvided() const;
Camera * camera() {return _camera;} // return null if not set, valid until CameraThread is deleted
Camera * odomSensor() {return _odomSensor;} // return null if not set, valid until CameraThread is deleted
private:
virtual void mainLoopBegin();
virtual void mainLoop();
virtual void mainLoopKill();
private:
Camera * _camera;
Camera * _odomSensor;
Transform _extrinsicsOdomToCamera;
bool _odomAsGt;
double _poseTimeOffset;
float _poseScaleFactor;
bool _mirroring;
bool _stereoExposureCompensation;
bool _colorOnly;
int _imageDecimation;
int _histogramMethod;
bool _stereoToDepth;
bool _scanFromDepth;
int _scanDownsampleStep;
float _scanRangeMin;
float _scanRangeMax;
float _scanVoxelSize;
int _scanNormalsK;
float _scanNormalsRadius;
float _scanForceGroundNormalsUp;
StereoDense * _stereoDense;
clams::DiscreteDepthDistortionModel * _distortionModel;
bool _bilateralFiltering;
float _bilateralSigmaS;
float _bilateralSigmaR;
IMUFilter * _imuFilter;
bool _imuBaseFrameConversion;
Feature2D * _featureDetector;
bool _depthAsMask;
};
} // namespace rtabmap
+2 -3
View File
@@ -82,15 +82,14 @@ public:
virtual bool isCalibrated() const; virtual bool isCalibrated() const;
virtual std::string getSerial() const; virtual std::string getSerial() const;
virtual bool odomProvided() const {return !_odometryIgnored;} virtual bool odomProvided() const {return !_odometryIgnored;}
virtual bool getPose(double stamp, Transform & pose, cv::Mat & covariance, double maxWaitTime = 0.06);
const DBDriver * driver() const {return _dbDriver;} const DBDriver * driver() const {return _dbDriver;}
protected: protected:
virtual SensorData captureImage(SensorCaptureInfo * info = 0); virtual SensorData captureImage(CameraInfo * info = 0);
private: private:
SensorData getNextData(SensorCaptureInfo * info = 0); SensorData getNextData(CameraInfo * info = 0);
private: private:
std::list<std::string> _paths; std::list<std::string> _paths;
+5 -7
View File
@@ -192,17 +192,16 @@ public:
const cv::Mat & disparity, const cv::Mat & disparity,
float minDisparity); float minDisparity);
static void limitKeypoints(std::vector<cv::KeyPoint> & keypoints, int maxKeypoints, const cv::Size & imageSize = cv::Size(), bool ssc = false); static void limitKeypoints(std::vector<cv::KeyPoint> & keypoints, int maxKeypoints);
static void limitKeypoints(std::vector<cv::KeyPoint> & keypoints, cv::Mat & descriptors, int maxKeypoints, const cv::Size & imageSize = cv::Size(), bool ssc = false); static void limitKeypoints(std::vector<cv::KeyPoint> & keypoints, cv::Mat & descriptors, int maxKeypoints);
static void limitKeypoints(std::vector<cv::KeyPoint> & keypoints, std::vector<cv::Point3f> & keypoints3D, cv::Mat & descriptors, int maxKeypoints, const cv::Size & imageSize = cv::Size(), bool ssc = false); static void limitKeypoints(std::vector<cv::KeyPoint> & keypoints, std::vector<cv::Point3f> & keypoints3D, cv::Mat & descriptors, int maxKeypoints);
static void limitKeypoints(const std::vector<cv::KeyPoint> & keypoints, std::vector<bool> & inliers, int maxKeypoints, const cv::Size & imageSize = cv::Size(), bool ssc = false); static void limitKeypoints(const std::vector<cv::KeyPoint> & keypoints, std::vector<bool> & inliers, int maxKeypoints);
static void limitKeypoints(const std::vector<cv::KeyPoint> & keypoints, std::vector<bool> & inliers, int maxKeypoints, const cv::Size & imageSize, int gridRows, int gridCols, bool ssc = false); static void limitKeypoints(const std::vector<cv::KeyPoint> & keypoints, std::vector<bool> & inliers, int maxKeypoints, const cv::Size & imageSize, int gridRows, int gridCols);
static cv::Rect computeRoi(const cv::Mat & image, const std::string & roiRatios); static cv::Rect computeRoi(const cv::Mat & image, const std::string & roiRatios);
static cv::Rect computeRoi(const cv::Mat & image, const std::vector<float> & roiRatios); static cv::Rect computeRoi(const cv::Mat & image, const std::vector<float> & roiRatios);
int getMaxFeatures() const {return maxFeatures_;} int getMaxFeatures() const {return maxFeatures_;}
bool getSSC() const {return SSC_;}
float getMinDepth() const {return _minDepth;} float getMinDepth() const {return _minDepth;}
float getMaxDepth() const {return _maxDepth;} float getMaxDepth() const {return _maxDepth;}
int getGridRows() const {return gridRows_;} int getGridRows() const {return gridRows_;}
@@ -235,7 +234,6 @@ private:
private: private:
ParametersMap parameters_; ParametersMap parameters_;
int maxFeatures_; int maxFeatures_;
bool SSC_;
float _maxDepth; // 0=inf float _maxDepth; // 0=inf
float _minDepth; float _minDepth;
std::vector<float> _roiRatios; // size 4 std::vector<float> _roiRatios; // size 4
@@ -1,5 +1,5 @@
/* /*
Copyright (c) 2010-2024, Mathieu Labbe - IntRoLab - Universite de Sherbrooke Copyright (c) 2010-2020, Mathieu Labbe - IntRoLab - Universite de Sherbrooke
All rights reserved. All rights reserved.
Redistribution and use in source and binary forms, with or without Redistribution and use in source and binary forms, with or without
@@ -1,73 +0,0 @@
/*
Copyright (c) 2010-2024, Mathieu Labbe - IntRoLab - Universite de Sherbrooke
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Universite de Sherbrooke nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef GLOBAL_DESCRIPTOR_EXTRACTOR_H_
#define GLOBAL_DESCRIPTOR_EXTRACTOR_H_
#include "rtabmap/core/rtabmap_core_export.h" // DLL export/import defines
#include "rtabmap/core/Parameters.h"
#include "rtabmap/core/SensorData.h"
namespace rtabmap {
// Feature2D
class RTABMAP_CORE_EXPORT GlobalDescriptorExtractor {
public:
enum Type {
kUndef=0,
kPyDescriptor=1};
static std::string typeName(Type type)
{
switch(type){
case kPyDescriptor:
return "PyDescriptor";
default:
return "Unknown";
}
}
static GlobalDescriptorExtractor * create(const ParametersMap & parameters = ParametersMap());
static GlobalDescriptorExtractor * create(GlobalDescriptorExtractor::Type type, const ParametersMap & parameters = ParametersMap()); // for convenience
public:
virtual ~GlobalDescriptorExtractor();
virtual GlobalDescriptor extract(const SensorData & data) const = 0;
virtual void parseParameters(const ParametersMap & parameters) {}
virtual GlobalDescriptorExtractor::Type getType() const = 0;
protected:
GlobalDescriptorExtractor(const ParametersMap & parameters = ParametersMap());
};
}
#endif /* GLOBAL_DESCRIPTOR_EXTRACTOR_H_ */
+1 -2
View File
@@ -28,13 +28,12 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef CORELIB_INCLUDE_RTABMAP_CORE_IMUFILTER_H_ #ifndef CORELIB_INCLUDE_RTABMAP_CORE_IMUFILTER_H_
#define CORELIB_INCLUDE_RTABMAP_CORE_IMUFILTER_H_ #define CORELIB_INCLUDE_RTABMAP_CORE_IMUFILTER_H_
#include "rtabmap/core/rtabmap_core_export.h" // DLL export/import defines
#include <rtabmap/core/Parameters.h> #include <rtabmap/core/Parameters.h>
#include <Eigen/Geometry> #include <Eigen/Geometry>
namespace rtabmap { namespace rtabmap {
class RTABMAP_CORE_EXPORT IMUFilter class IMUFilter
{ {
public: public:
enum Type { enum Type {
+2 -9
View File
@@ -47,8 +47,7 @@ public:
kXYZRGB=7, kXYZRGB=7,
kXYZNormal=8, kXYZNormal=8,
kXYZINormal=9, kXYZINormal=9,
kXYZRGBNormal=10, kXYZRGBNormal=10};
kXYZIT=11};
static std::string formatName(const Format & format); static std::string formatName(const Format & format);
static int channels(const Format & format); static int channels(const Format & format);
@@ -56,7 +55,6 @@ public:
static bool isScanHasNormals(const Format & format); static bool isScanHasNormals(const Format & format);
static bool isScanHasRGB(const Format & format); static bool isScanHasRGB(const Format & format);
static bool isScanHasIntensity(const Format & format); static bool isScanHasIntensity(const Format & format);
static bool isScanHasTime(const Format & format);
static LaserScan backwardCompatibility( static LaserScan backwardCompatibility(
const cv::Mat & oldScanFormat, const cv::Mat & oldScanFormat,
int maxPoints = 0, int maxPoints = 0,
@@ -123,27 +121,22 @@ public:
float angleMin() const {return angleMin_;} float angleMin() const {return angleMin_;}
float angleMax() const {return angleMax_;} float angleMax() const {return angleMax_;}
float angleIncrement() const {return angleIncrement_;} float angleIncrement() const {return angleIncrement_;}
void setLocalTransform(const Transform & t) {localTransform_ = t;}
Transform localTransform() const {return localTransform_;} Transform localTransform() const {return localTransform_;}
bool empty() const {return data_.empty();} bool empty() const {return data_.empty();}
bool isEmpty() const {return data_.empty();} bool isEmpty() const {return data_.empty();}
int size() const {return data_.total();} int size() const {return data_.cols;}
int dataType() const {return data_.type();} int dataType() const {return data_.type();}
bool is2d() const {return isScan2d(format_);} bool is2d() const {return isScan2d(format_);}
bool hasNormals() const {return isScanHasNormals(format_);} bool hasNormals() const {return isScanHasNormals(format_);}
bool hasRGB() const {return isScanHasRGB(format_);} bool hasRGB() const {return isScanHasRGB(format_);}
bool hasIntensity() const {return isScanHasIntensity(format_);} bool hasIntensity() const {return isScanHasIntensity(format_);}
bool hasTime() const {return isScanHasTime(format_);}
bool isCompressed() const {return !data_.empty() && data_.type()==CV_8UC1;} bool isCompressed() const {return !data_.empty() && data_.type()==CV_8UC1;}
bool isOrganized() const {return data_.rows > 1;}
LaserScan clone() const; LaserScan clone() const;
LaserScan densify() const;
int getIntensityOffset() const {return hasIntensity()?(is2d()?2:3):-1;} int getIntensityOffset() const {return hasIntensity()?(is2d()?2:3):-1;}
int getRGBOffset() const {return hasRGB()?(is2d()?2:3):-1;} int getRGBOffset() const {return hasRGB()?(is2d()?2:3):-1;}
int getNormalsOffset() const {return hasNormals()?(2 + (is2d()?0:1) + ((hasRGB() || hasIntensity())?1:0)):-1;} int getNormalsOffset() const {return hasNormals()?(2 + (is2d()?0:1) + ((hasRGB() || hasIntensity())?1:0)):-1;}
int getTimeOffset() const {return hasTime()?4:-1;}
float & field(unsigned int pointIndex, unsigned int channelOffset); float & field(unsigned int pointIndex, unsigned int channelOffset);
-57
View File
@@ -1,57 +0,0 @@
/*
Copyright (c) 2010-2022, Mathieu Labbe - IntRoLab - Universite de Sherbrooke
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Universite de Sherbrooke nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#pragma once
#include "rtabmap/core/rtabmap_core_export.h" // DLL export/import defines
#include <rtabmap/core/SensorCapture.h>
namespace rtabmap
{
/**
* Class Lidar
*
*/
class RTABMAP_CORE_EXPORT Lidar : public SensorCapture
{
public:
virtual ~Lidar() {}
protected:
/**
* Constructor
*
* @param lidarRate the frame rate (Hz), 0 for fast as the lidar can
* @param localTransform the transform from base frame to lidar frame
*/
Lidar(float lidarRate = 0, const Transform & localTransform = Transform::getIdentity()) :
SensorCapture(lidarRate, localTransform) {}
};
} // namespace rtabmap
-4
View File
@@ -59,7 +59,6 @@ class RegistrationVis;
class Stereo; class Stereo;
class LocalGridMaker; class LocalGridMaker;
class MarkerDetector; class MarkerDetector;
class GlobalDescriptorExtractor;
class RTABMAP_CORE_EXPORT Memory class RTABMAP_CORE_EXPORT Memory
{ {
@@ -334,7 +333,6 @@ private:
bool _rotateImagesUpsideUp; bool _rotateImagesUpsideUp;
bool _createOccupancyGrid; bool _createOccupancyGrid;
int _visMaxFeatures; int _visMaxFeatures;
bool _visSSC;
bool _imagesAlreadyRectified; bool _imagesAlreadyRectified;
bool _rectifyOnlyFeatures; bool _rectifyOnlyFeatures;
bool _covOffDiagonalIgnored; bool _covOffDiagonalIgnored;
@@ -377,8 +375,6 @@ private:
LocalGridMaker * _localMapMaker; LocalGridMaker * _localMapMaker;
MarkerDetector * _markerDetector; MarkerDetector * _markerDetector;
GlobalDescriptorExtractor * _globalDescriptorExtractor;
}; };
} // namespace rtabmap } // namespace rtabmap
-1
View File
@@ -111,7 +111,6 @@ private:
bool _alignWithGround; bool _alignWithGround;
bool _publishRAMUsage; bool _publishRAMUsage;
bool _imagesAlreadyRectified; bool _imagesAlreadyRectified;
bool _deskewing;
Transform _pose; Transform _pose;
int _resetCurrentCount; int _resetCurrentCount;
double previousStamp_; double previousStamp_;
@@ -50,7 +50,6 @@ public:
localBundleConstraints(0), localBundleConstraints(0),
localBundleTime(0), localBundleTime(0),
keyFrameAdded(false), keyFrameAdded(false),
timeDeskewing(0.0f),
timeEstimation(0.0f), timeEstimation(0.0f),
timeParticleFiltering(0.0f), timeParticleFiltering(0.0f),
stamp(0), stamp(0),
@@ -77,7 +76,6 @@ public:
output.localBundlePoses = localBundlePoses; output.localBundlePoses = localBundlePoses;
output.localBundleModels = localBundleModels; output.localBundleModels = localBundleModels;
output.keyFrameAdded = keyFrameAdded; output.keyFrameAdded = keyFrameAdded;
output.timeDeskewing = timeDeskewing;
output.timeEstimation = timeEstimation; output.timeEstimation = timeEstimation;
output.timeParticleFiltering = timeParticleFiltering; output.timeParticleFiltering = timeParticleFiltering;
output.stamp = stamp; output.stamp = stamp;
@@ -107,7 +105,6 @@ public:
std::map<int, Transform> localBundlePoses; std::map<int, Transform> localBundlePoses;
std::map<int, std::vector<CameraModel> > localBundleModels; std::map<int, std::vector<CameraModel> > localBundleModels;
bool keyFrameAdded; bool keyFrameAdded;
float timeDeskewing;
float timeEstimation; float timeEstimation;
float timeParticleFiltering; float timeParticleFiltering;
double stamp; double stamp;
-16
View File
@@ -197,7 +197,6 @@ class RTABMAP_CORE_EXPORT Parameters
RTABMAP_PARAM(Rtabmap, LoopThr, float, 0.11, "Loop closing threshold."); RTABMAP_PARAM(Rtabmap, LoopThr, float, 0.11, "Loop closing threshold.");
RTABMAP_PARAM(Rtabmap, LoopRatio, float, 0, "The loop closure hypothesis must be over LoopRatio x lastHypothesisValue."); RTABMAP_PARAM(Rtabmap, LoopRatio, float, 0, "The loop closure hypothesis must be over LoopRatio x lastHypothesisValue.");
RTABMAP_PARAM(Rtabmap, LoopGPS, bool, true, uFormat("Use GPS to filter likelihood (if GPS is recorded). Only locations inside the local radius \"%s\" of the current GPS location are considered for loop closure detection.", kRGBDLocalRadius().c_str())); RTABMAP_PARAM(Rtabmap, LoopGPS, bool, true, uFormat("Use GPS to filter likelihood (if GPS is recorded). Only locations inside the local radius \"%s\" of the current GPS location are considered for loop closure detection.", kRGBDLocalRadius().c_str()));
RTABMAP_PARAM(Rtabmap, VirtualPlaceLikelihoodRatio, int, 0, "Likelihood ratio for virtual place (for no loop closure hypothesis): 0=Mean / StdDev, 1=StdDev / (Max-Mean)");
// Memory // Memory
RTABMAP_PARAM(Mem, RehearsalSimilarity, float, 0.6, "Rehearsal similarity."); RTABMAP_PARAM(Mem, RehearsalSimilarity, float, 0.6, "Rehearsal similarity.");
@@ -232,7 +231,6 @@ class RTABMAP_CORE_EXPORT Parameters
RTABMAP_PARAM(Mem, UseOdomFeatures, bool, true, "Use odometry features instead of regenerating them."); RTABMAP_PARAM(Mem, UseOdomFeatures, bool, true, "Use odometry features instead of regenerating them.");
RTABMAP_PARAM(Mem, UseOdomGravity, bool, false, uFormat("Use odometry instead of IMU orientation to add gravity links to new nodes created. We assume that odometry is already aligned with gravity (e.g., we are using a VIO approach). Gravity constraints are used by graph optimization only if \"%s\" is not zero.", kOptimizerGravitySigma().c_str())); RTABMAP_PARAM(Mem, UseOdomGravity, bool, false, uFormat("Use odometry instead of IMU orientation to add gravity links to new nodes created. We assume that odometry is already aligned with gravity (e.g., we are using a VIO approach). Gravity constraints are used by graph optimization only if \"%s\" is not zero.", kOptimizerGravitySigma().c_str()));
RTABMAP_PARAM(Mem, CovOffDiagIgnored, bool, true, "Ignore off diagonal values of the covariance matrix."); RTABMAP_PARAM(Mem, CovOffDiagIgnored, bool, true, "Ignore off diagonal values of the covariance matrix.");
RTABMAP_PARAM(Mem, GlobalDescriptorStrategy, int, 0, "Extract global descriptor from sensor data. 0=disabled, 1=PyDescriptor");
RTABMAP_PARAM(Mem, RotateImagesUpsideUp, bool, false, "Rotate images so that upside is up if they are not already. This can be useful in case the robots don't have all same camera orientation but are using the same map, so that not rotation-invariant visual features can still be used across the fleet."); RTABMAP_PARAM(Mem, RotateImagesUpsideUp, bool, false, "Rotate images so that upside is up if they are not already. This can be useful in case the robots don't have all same camera orientation but are using the same map, so that not rotation-invariant visual features can still be used across the fleet.");
// KeypointMemory (Keypoint-based) // KeypointMemory (Keypoint-based)
@@ -244,7 +242,6 @@ class RTABMAP_CORE_EXPORT Parameters
RTABMAP_PARAM(Kp, MaxDepth, float, 0, "Filter extracted keypoints by depth (0=inf)."); RTABMAP_PARAM(Kp, MaxDepth, float, 0, "Filter extracted keypoints by depth (0=inf).");
RTABMAP_PARAM(Kp, MinDepth, float, 0, "Filter extracted keypoints by depth."); RTABMAP_PARAM(Kp, MinDepth, float, 0, "Filter extracted keypoints by depth.");
RTABMAP_PARAM(Kp, MaxFeatures, int, 500, "Maximum features extracted from the images (0 means not bounded, <0 means no extraction)."); RTABMAP_PARAM(Kp, MaxFeatures, int, 500, "Maximum features extracted from the images (0 means not bounded, <0 means no extraction).");
RTABMAP_PARAM(Kp, SSC, bool, false, "If true, SSC (Suppression via Square Covering) is applied to limit keypoints.");
RTABMAP_PARAM(Kp, BadSignRatio, float, 0.5, "Bad signature ratio (less than Ratio x AverageWordsPerImage = bad)."); RTABMAP_PARAM(Kp, BadSignRatio, float, 0.5, "Bad signature ratio (less than Ratio x AverageWordsPerImage = bad).");
RTABMAP_PARAM(Kp, NndrRatio, float, 0.8, "NNDR ratio (A matching pair is detected, if its distance is closer than X times the distance of the second nearest neighbor.)"); RTABMAP_PARAM(Kp, NndrRatio, float, 0.8, "NNDR ratio (A matching pair is detected, if its distance is closer than X times the distance of the second nearest neighbor.)");
#if CV_MAJOR_VERSION > 2 && !defined(HAVE_OPENCV_XFEATURES2D) #if CV_MAJOR_VERSION > 2 && !defined(HAVE_OPENCV_XFEATURES2D)
@@ -357,12 +354,10 @@ class RTABMAP_CORE_EXPORT Parameters
RTABMAP_PARAM(RGBD, AngularUpdate, float, 0.1, "Minimum angular displacement (rad) to update the map. Rehearsal is done prior to this, so weights are still updated."); RTABMAP_PARAM(RGBD, AngularUpdate, float, 0.1, "Minimum angular displacement (rad) to update the map. Rehearsal is done prior to this, so weights are still updated.");
RTABMAP_PARAM(RGBD, LinearSpeedUpdate, float, 0.0, "Maximum linear speed (m/s) to update the map (0 means not limit)."); RTABMAP_PARAM(RGBD, LinearSpeedUpdate, float, 0.0, "Maximum linear speed (m/s) to update the map (0 means not limit).");
RTABMAP_PARAM(RGBD, AngularSpeedUpdate, float, 0.0, "Maximum angular speed (rad/s) to update the map (0 means not limit)."); RTABMAP_PARAM(RGBD, AngularSpeedUpdate, float, 0.0, "Maximum angular speed (rad/s) to update the map (0 means not limit).");
RTABMAP_PARAM(RGBD, AggressiveLoopThr, float, 0.05, uFormat("Loop closure threshold used (overriding %s) when a new mapping session is not yet linked to a map of the highest loop closure hypothesis. In localization mode, this threshold is used when there are no loop closure constraints with any map in the cache (%s). In all cases, the goal is to aggressively loop on a previous map in the database. Only used when %s is enabled. Set 1 to disable.", kRtabmapLoopThr().c_str(), kRGBDMaxOdomCacheSize().c_str(), kRGBDEnabled().c_str()));
RTABMAP_PARAM(RGBD, NewMapOdomChangeDistance, float, 0, "A new map is created if a change of odometry translation greater than X m is detected (0 m = disabled)."); RTABMAP_PARAM(RGBD, NewMapOdomChangeDistance, float, 0, "A new map is created if a change of odometry translation greater than X m is detected (0 m = disabled).");
RTABMAP_PARAM(RGBD, OptimizeFromGraphEnd, bool, false, "Optimize graph from the newest node. If false, the graph is optimized from the oldest node of the current graph (this adds an overhead computation to detect to oldest node of the current graph, but it can be useful to preserve the map referential from the oldest node). Warning when set to false: when some nodes are transferred, the first referential of the local map may change, resulting in momentary changes in robot/map position (which are annoying in teleoperation)."); RTABMAP_PARAM(RGBD, OptimizeFromGraphEnd, bool, false, "Optimize graph from the newest node. If false, the graph is optimized from the oldest node of the current graph (this adds an overhead computation to detect to oldest node of the current graph, but it can be useful to preserve the map referential from the oldest node). Warning when set to false: when some nodes are transferred, the first referential of the local map may change, resulting in momentary changes in robot/map position (which are annoying in teleoperation).");
RTABMAP_PARAM(RGBD, OptimizeMaxError, float, 3.0, uFormat("Reject loop closures if optimization error ratio is greater than this value (0=disabled). Ratio is computed as absolute error over standard deviation of each link. This will help to detect when a wrong loop closure is added to the graph. Not compatible with \"%s\" if enabled.", kOptimizerRobust().c_str())); RTABMAP_PARAM(RGBD, OptimizeMaxError, float, 3.0, uFormat("Reject loop closures if optimization error ratio is greater than this value (0=disabled). Ratio is computed as absolute error over standard deviation of each link. This will help to detect when a wrong loop closure is added to the graph. Not compatible with \"%s\" if enabled.", kOptimizerRobust().c_str()));
RTABMAP_PARAM(RGBD, MaxLoopClosureDistance, float, 0.0, "Reject loop closures/localizations if the distance from the map is over this distance (0=disabled)."); RTABMAP_PARAM(RGBD, MaxLoopClosureDistance, float, 0.0, "Reject loop closures/localizations if the distance from the map is over this distance (0=disabled).");
RTABMAP_PARAM(RGBD, ForceOdom3DoF, bool, true, uFormat("Force odometry pose to be 3DoF if %s=true.", kRegForce3DoF().c_str()));
RTABMAP_PARAM(RGBD, StartAtOrigin, bool, false, uFormat("If true, rtabmap will assume the robot is starting from origin of the map. If false, rtabmap will assume the robot is restarting from the last saved localization pose from previous session (the place where it shut down previously). Used only in localization mode (%s=false).", kMemIncrementalMemory().c_str())); RTABMAP_PARAM(RGBD, StartAtOrigin, bool, false, uFormat("If true, rtabmap will assume the robot is starting from origin of the map. If false, rtabmap will assume the robot is restarting from the last saved localization pose from previous session (the place where it shut down previously). Used only in localization mode (%s=false).", kMemIncrementalMemory().c_str()));
RTABMAP_PARAM(RGBD, GoalReachedRadius, float, 0.5, "Goal reached radius (m)."); RTABMAP_PARAM(RGBD, GoalReachedRadius, float, 0.5, "Goal reached radius (m).");
RTABMAP_PARAM(RGBD, PlanStuckIterations, int, 0, "Mark the current goal node on the path as unreachable if it is not updated after X iterations (0=disabled). If all upcoming nodes on the path are unreachabled, the plan fails."); RTABMAP_PARAM(RGBD, PlanStuckIterations, int, 0, "Mark the current goal node on the path as unreachable if it is not updated after X iterations (0=disabled). If all upcoming nodes on the path are unreachabled, the plan fails.");
@@ -441,9 +436,6 @@ class RTABMAP_CORE_EXPORT Parameters
RTABMAP_PARAM(g2o, Baseline, double, 0.075, "When doing bundle adjustment with RGB-D data, we can set a fake baseline (m) to do stereo bundle adjustment (if 0, mono bundle adjustment is done). For stereo data, the baseline in the calibration is used directly."); RTABMAP_PARAM(g2o, Baseline, double, 0.075, "When doing bundle adjustment with RGB-D data, we can set a fake baseline (m) to do stereo bundle adjustment (if 0, mono bundle adjustment is done). For stereo data, the baseline in the calibration is used directly.");
RTABMAP_PARAM(GTSAM, Optimizer, int, 1, "0=Levenberg 1=GaussNewton 2=Dogleg"); RTABMAP_PARAM(GTSAM, Optimizer, int, 1, "0=Levenberg 1=GaussNewton 2=Dogleg");
RTABMAP_PARAM(GTSAM, Incremental, bool, false, uFormat("Do graph optimization incrementally (iSAM2) to increase optimization speed on loop closures. Note that only GaussNewton and Dogleg optimization algorithms are supported (%s) in this mode.", kGTSAMOptimizer().c_str()));
RTABMAP_PARAM(GTSAM, IncRelinearizeThreshold, double, 0.01, "Only relinearize variables whose linear delta magnitude is greater than this threshold. See GTSAM::ISAM2 doc for more info.");
RTABMAP_PARAM(GTSAM, IncRelinearizeSkip, int, 1, "Only relinearize any variables every X calls to ISAM2::update(). See GTSAM::ISAM2 doc for more info.");
// Odometry // Odometry
RTABMAP_PARAM(Odom, Strategy, int, 0, "0=Frame-to-Map (F2M) 1=Frame-to-Frame (F2F) 2=Fovis 3=viso2 4=DVO-SLAM 5=ORB_SLAM2 6=OKVIS 7=LOAM 8=MSCKF_VIO 9=VINS-Fusion 10=OpenVINS 11=FLOAM 12=Open3D"); RTABMAP_PARAM(Odom, Strategy, int, 0, "0=Frame-to-Map (F2M) 1=Frame-to-Frame (F2F) 2=Fovis 3=viso2 4=DVO-SLAM 5=ORB_SLAM2 6=OKVIS 7=LOAM 8=MSCKF_VIO 9=VINS-Fusion 10=OpenVINS 11=FLOAM 12=Open3D");
@@ -466,7 +458,6 @@ class RTABMAP_CORE_EXPORT Parameters
RTABMAP_PARAM(Odom, ScanKeyFrameThr, float, 0.9, "[Geometry] Create a new keyframe when the number of ICP inliers drops under this ratio of points in last frame's scan. Setting the value to 0 means that a keyframe is created for each processed frame."); RTABMAP_PARAM(Odom, ScanKeyFrameThr, float, 0.9, "[Geometry] Create a new keyframe when the number of ICP inliers drops under this ratio of points in last frame's scan. Setting the value to 0 means that a keyframe is created for each processed frame.");
RTABMAP_PARAM(Odom, ImageDecimation, unsigned int, 1, uFormat("Decimation of the RGB image before registration. If depth size is larger than decimated RGB size, depth is decimated to be always at most equal to RGB size. If %s is true and if depth is smaller than decimated RGB, depth may be interpolated to match RGB size for feature detection.", kVisDepthAsMask().c_str())); RTABMAP_PARAM(Odom, ImageDecimation, unsigned int, 1, uFormat("Decimation of the RGB image before registration. If depth size is larger than decimated RGB size, depth is decimated to be always at most equal to RGB size. If %s is true and if depth is smaller than decimated RGB, depth may be interpolated to match RGB size for feature detection.", kVisDepthAsMask().c_str()));
RTABMAP_PARAM(Odom, AlignWithGround, bool, false, "Align odometry with the ground on initialization."); RTABMAP_PARAM(Odom, AlignWithGround, bool, false, "Align odometry with the ground on initialization.");
RTABMAP_PARAM(Odom, Deskewing, bool, true, "Lidar deskewing. If input lidar has time channel, it will be deskewed with a constant motion model (with IMU orientation and/or guess if provided).");
// Odometry Frame-to-Map // Odometry Frame-to-Map
RTABMAP_PARAM(OdomF2M, MaxSize, int, 2000, "[Visual] Local map size: If > 0 (example 5000), the odometry will maintain a local map of X maximum words."); RTABMAP_PARAM(OdomF2M, MaxSize, int, 2000, "[Visual] Local map size: If > 0 (example 5000), the odometry will maintain a local map of X maximum words.");
@@ -695,7 +686,6 @@ class RTABMAP_CORE_EXPORT Parameters
RTABMAP_PARAM(Vis, FeatureType, int, 6, "0=SURF 1=SIFT 2=ORB 3=FAST/FREAK 4=FAST/BRIEF 5=GFTT/FREAK 6=GFTT/BRIEF 7=BRISK 8=GFTT/ORB 9=KAZE 10=ORB-OCTREE 11=SuperPoint 12=SURF/FREAK 13=GFTT/DAISY 14=SURF/DAISY 15=PyDetector"); RTABMAP_PARAM(Vis, FeatureType, int, 6, "0=SURF 1=SIFT 2=ORB 3=FAST/FREAK 4=FAST/BRIEF 5=GFTT/FREAK 6=GFTT/BRIEF 7=BRISK 8=GFTT/ORB 9=KAZE 10=ORB-OCTREE 11=SuperPoint 12=SURF/FREAK 13=GFTT/DAISY 14=SURF/DAISY 15=PyDetector");
#endif #endif
RTABMAP_PARAM(Vis, MaxFeatures, int, 1000, "0 no limits."); RTABMAP_PARAM(Vis, MaxFeatures, int, 1000, "0 no limits.");
RTABMAP_PARAM(Vis, SSC, bool, false, "If true, SSC (Suppression via Square Covering) is applied to limit keypoints.");
RTABMAP_PARAM(Vis, MaxDepth, float, 0, "Max depth of the features (0 means no limit)."); RTABMAP_PARAM(Vis, MaxDepth, float, 0, "Max depth of the features (0 means no limit).");
RTABMAP_PARAM(Vis, MinDepth, float, 0, "Min depth of the features (0 means no limit)."); RTABMAP_PARAM(Vis, MinDepth, float, 0, "Min depth of the features (0 means no limit).");
RTABMAP_PARAM(Vis, DepthAsMask, bool, true, "Use depth image as mask when extracting features."); RTABMAP_PARAM(Vis, DepthAsMask, bool, true, "Use depth image as mask when extracting features.");
@@ -731,10 +721,6 @@ class RTABMAP_CORE_EXPORT Parameters
RTABMAP_PARAM(GMS, WithScale, bool, false, "Take scale transformation into account."); RTABMAP_PARAM(GMS, WithScale, bool, false, "Take scale transformation into account.");
RTABMAP_PARAM(GMS, ThresholdFactor, double, 6.0, "The higher, the less matches."); RTABMAP_PARAM(GMS, ThresholdFactor, double, 6.0, "The higher, the less matches.");
// Global descriptor approaches
RTABMAP_PARAM_STR(PyDescriptor, Path, "", "Path to python script file (see available ones in rtabmap/corelib/src/pydescriptor/*). See the header to see where the script should be used.");
RTABMAP_PARAM(PyDescriptor, Dim, int, 4096, "Descriptor dimension.");
// ICP registration parameters // ICP registration parameters
#ifdef RTABMAP_POINTMATCHER #ifdef RTABMAP_POINTMATCHER
RTABMAP_PARAM(Icp, Strategy, int, 1, "ICP implementation: 0=Point Cloud Library, 1=libpointmatcher, 2=CCCoreLib (CloudCompare)."); RTABMAP_PARAM(Icp, Strategy, int, 1, "ICP implementation: 0=Point Cloud Library, 1=libpointmatcher, 2=CCCoreLib (CloudCompare).");
@@ -757,7 +743,6 @@ class RTABMAP_CORE_EXPORT Parameters
RTABMAP_PARAM(Icp, Epsilon, float, 0, "Set the transformation epsilon (maximum allowable difference between two consecutive transformations) in order for an optimization to be considered as having converged to the final solution."); RTABMAP_PARAM(Icp, Epsilon, float, 0, "Set the transformation epsilon (maximum allowable difference between two consecutive transformations) in order for an optimization to be considered as having converged to the final solution.");
RTABMAP_PARAM(Icp, CorrespondenceRatio, float, 0.1, "Ratio of matching correspondences to accept the transform."); RTABMAP_PARAM(Icp, CorrespondenceRatio, float, 0.1, "Ratio of matching correspondences to accept the transform.");
RTABMAP_PARAM(Icp, Force4DoF, bool, false, uFormat("Limit ICP to x, y, z and yaw DoF. Available if %s > 0.", kIcpStrategy().c_str())); RTABMAP_PARAM(Icp, Force4DoF, bool, false, uFormat("Limit ICP to x, y, z and yaw DoF. Available if %s > 0.", kIcpStrategy().c_str()));
RTABMAP_PARAM(Icp, FiltersEnabled, int, 3, "Flag to enable filters: 1=\"from\" cloud only, 2=\"to\" cloud only, 3=both.");
#ifdef RTABMAP_POINTMATCHER #ifdef RTABMAP_POINTMATCHER
RTABMAP_PARAM(Icp, PointToPlane, bool, true, "Use point to plane ICP."); RTABMAP_PARAM(Icp, PointToPlane, bool, true, "Use point to plane ICP.");
#else #else
@@ -937,7 +922,6 @@ public:
static ParametersMap filterParameters(const ParametersMap & parameters, const std::string & group, bool remove = false); static ParametersMap filterParameters(const ParametersMap & parameters, const std::string & group, bool remove = false);
static void readINI(const std::string & configFile, ParametersMap & parameters, bool modifiedOnly = false); static void readINI(const std::string & configFile, ParametersMap & parameters, bool modifiedOnly = false);
static void readINIStr(const std::string & configContent, ParametersMap & parameters, bool modifiedOnly = false);
static void writeINI(const std::string & configFile, const ParametersMap & parameters); static void writeINI(const std::string & configFile, const ParametersMap & parameters);
/** /**
@@ -69,7 +69,6 @@ private:
float _epsilon; float _epsilon;
float _correspondenceRatio; float _correspondenceRatio;
bool _force4DoF; bool _force4DoF;
int _filtersEnabled;
bool _pointToPlane; bool _pointToPlane;
int _pointToPlaneK; int _pointToPlaneK;
float _pointToPlaneRadius; float _pointToPlaneRadius;
-5
View File
@@ -151,8 +151,6 @@ public:
float getTimeThreshold() const {return _maxTimeAllowed;} // in ms float getTimeThreshold() const {return _maxTimeAllowed;} // in ms
void setTimeThreshold(float maxTimeAllowed); // in ms void setTimeThreshold(float maxTimeAllowed); // in ms
int getMemoryThreshold() const {return _maxMemoryAllowed;} // in nodes
void setMemoryThreshold(int maxMemoryAllowed); // in nodes
void setInitialPose(const Transform & initialPose); void setInitialPose(const Transform & initialPose);
int triggerNewMap(); int triggerNewMap();
@@ -284,8 +282,6 @@ private:
unsigned int _maxMemoryAllowed; // signatures count in WM unsigned int _maxMemoryAllowed; // signatures count in WM
float _loopThr; float _loopThr;
float _loopRatio; float _loopRatio;
float _aggressiveLoopThr;
int _virtualPlaceLikelihoodRatio;
float _maxLoopClosureDistance; float _maxLoopClosureDistance;
bool _verifyLoopClosureHypothesis; bool _verifyLoopClosureHypothesis;
unsigned int _maxRetrieved; unsigned int _maxRetrieved;
@@ -326,7 +322,6 @@ private:
int _pathStuckIterations; int _pathStuckIterations;
float _pathLinearVelocity; float _pathLinearVelocity;
float _pathAngularVelocity; float _pathAngularVelocity;
bool _forceOdom3doF;
bool _restartAtOrigin; bool _restartAtOrigin;
bool _loopCovLimited; bool _loopCovLimited;
bool _loopGPS; bool _loopGPS;
@@ -1,93 +0,0 @@
/*
Copyright (c) 2010-2022, Mathieu Labbe
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#pragma once
#include "rtabmap/core/rtabmap_core_export.h" // DLL export/import defines
#include <opencv2/highgui/highgui.hpp>
#include <rtabmap/core/SensorCaptureInfo.h>
#include "rtabmap/core/SensorData.h"
#include <set>
#include <stack>
#include <list>
#include <vector>
class UDirectory;
class UTimer;
namespace rtabmap
{
/**
* Class Camera
*
*/
class RTABMAP_CORE_EXPORT SensorCapture
{
public:
virtual ~SensorCapture();
SensorData takeData(SensorCaptureInfo * info = 0);
virtual bool init(const std::string & calibrationFolder = ".", const std::string & cameraName = "") = 0;
virtual std::string getSerial() const = 0;
virtual bool odomProvided() const { return false; }
virtual bool getPose(double stamp, Transform & pose, cv::Mat & covariance, double maxWaitTime = 0.06) { return false; }
//getters
float getFrameRate() const {return _frameRate;}
const Transform & getLocalTransform() const {return _localTransform;}
//setters
void setFrameRate(float frameRate) {_frameRate = frameRate;}
void setLocalTransform(const Transform & localTransform) {_localTransform= localTransform;}
void resetTimer();
protected:
/**
* Constructor
*
* @param frameRate the frame rate (Hz), 0 for fast as the sensor can
* @param localTransform the transform from base frame to sensor frame
*/
SensorCapture(float frameRate = 0, const Transform & localTransform = Transform::getIdentity());
/**
* returned rgb and depth images should be already rectified if calibration was loaded
*/
virtual SensorData captureData(SensorCaptureInfo * info = 0) = 0;
int getNextSeqID() {return ++_seq;}
private:
float _frameRate;
Transform _localTransform;
UTimer * _frameRateTimer;
int _seq;
};
} // namespace rtabmap
@@ -1,82 +0,0 @@
/*
Copyright (c) 2010-2016, Mathieu Labbe - IntRoLab - Universite de Sherbrooke
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Universite de Sherbrooke nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#pragma once
#include "rtabmap/core/Transform.h"
#include <string>
namespace rtabmap
{
class SensorCaptureInfo
{
public:
SensorCaptureInfo() :
cameraName(""),
id(0),
stamp(0.0),
timeCapture(0.0f),
timeDeskewing(0.0f),
timeDisparity(0.0f),
timeMirroring(0.0f),
timeStereoExposureCompensation(0.0f),
timeImageDecimation(0.0f),
timeHistogramEqualization(0.0f),
timeScanFromDepth(0.0f),
timeUndistortDepth(0.0f),
timeBilateralFiltering(0.0f),
timeTotal(0.0f),
odomCovariance(cv::Mat::eye(6,6,CV_64FC1))
{
}
virtual ~SensorCaptureInfo() {}
std::string cameraName;
int id;
double stamp;
float timeCapture;
float timeDeskewing;
float timeDisparity;
float timeMirroring;
float timeStereoExposureCompensation;
float timeImageDecimation;
float timeHistogramEqualization;
float timeScanFromDepth;
float timeUndistortDepth;
float timeBilateralFiltering;
float timeTotal;
Transform odomPose;
cv::Mat odomCovariance;
std::vector<float> odomVelocity;
};
//backward compatibility
RTABMAP_DEPRECATED typedef SensorCaptureInfo CameraInfo;
} // namespace rtabmap
@@ -1,216 +0,0 @@
/*
Copyright (c) 2010-2016, Mathieu Labbe - IntRoLab - Universite de Sherbrooke
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Universite de Sherbrooke nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#pragma once
#include "rtabmap/core/rtabmap_core_export.h" // DLL export/import defines
#include <rtabmap/core/Parameters.h>
#include <rtabmap/core/Transform.h>
#include <rtabmap/utilite/UThread.h>
#include <rtabmap/utilite/UEventsSender.h>
namespace clams
{
class DiscreteDepthDistortionModel;
}
namespace rtabmap
{
class Camera;
class Lidar;
class SensorCapture;
class SensorCaptureInfo;
class SensorData;
class StereoDense;
class IMUFilter;
class Feature2D;
/**
* Class CameraThread
*
*/
class RTABMAP_CORE_EXPORT SensorCaptureThread :
public UThread,
public UEventsSender
{
public:
// ownership transferred
SensorCaptureThread(
Camera * camera,
const ParametersMap & parameters = ParametersMap());
/**
* @param camera the camera to take images from
* @param odomSensor an odometry sensor to get a pose (can be again the camera)
* @param odomAsGt set odometry sensor pose as ground truth instead of odometry
* @param extrinsics the static transform between odometry sensor's left lens frame to camera's left lens frame (without optical rotation)
*/
SensorCaptureThread(
Camera * camera,
SensorCapture * odomSensor,
const Transform & extrinsics,
double poseTimeOffset = 0.0,
float poseScaleFactor = 1.0f,
double poseWaitTime = 0.1,
const ParametersMap & parameters = ParametersMap());
/**
* @param lidar the lidar to take scans from
*/
SensorCaptureThread(
Lidar * lidar,
const ParametersMap & parameters = ParametersMap());
/**
* @param lidar the lidar to take scans from
* @param camera the camera to take images from. If the camera is providing a pose, it can be used for deskewing
*/
SensorCaptureThread(
Lidar * lidar,
Camera * camera,
const ParametersMap & parameters = ParametersMap());
/**
* @param lidar the lidar to take scans from
* @param odomSensor an odometry sensor to get a pose and used for deskewing (can be again the lidar)
*/
SensorCaptureThread(
Lidar * lidar,
SensorCapture * odomSensor,
double poseTimeOffset = 0.0,
float poseScaleFactor = 1.0f,
double poseWaitTime = 0.1,
const ParametersMap & parameters = ParametersMap());
/**
* @param lidar the lidar to take scans from
* @param camera the camera to take images from
* @param odomSensor an odometry sensor to get a pose and used for deskewing (can be again the camera or lidar)
* @param extrinsics the static transform between odometry frame to camera frame (without optical rotation)
*/
SensorCaptureThread(
Lidar * lidar,
Camera * camera,
SensorCapture * odomSensor,
const Transform & extrinsics,
double poseTimeOffset = 0.0,
float poseScaleFactor = 1.0f,
double poseWaitTime = 0.1,
const ParametersMap & parameters = ParametersMap());
virtual ~SensorCaptureThread();
void setMirroringEnabled(bool enabled) {_mirroring = enabled;}
void setStereoExposureCompensation(bool enabled) {_stereoExposureCompensation = enabled;}
void setColorOnly(bool colorOnly) {_colorOnly = colorOnly;}
void setImageDecimation(int decimation) {_imageDecimation = decimation;}
void setHistogramMethod(int histogramMethod) {_histogramMethod = histogramMethod;}
void setStereoToDepth(bool enabled) {_stereoToDepth = enabled;}
void setFrameRate(float frameRate);
RTABMAP_DEPRECATED void setImageRate(float frameRate) {setFrameRate(frameRate);}
void setDistortionModel(const std::string & path);
void setOdomAsGroundTruth(bool enabled) {_odomAsGt = enabled;}
void enableBilateralFiltering(float sigmaS, float sigmaR);
void disableBilateralFiltering() {_bilateralFiltering = false;}
void enableIMUFiltering(int filteringStrategy=1, const ParametersMap & parameters = ParametersMap(), bool baseFrameConversion = false);
void disableIMUFiltering();
void enableFeatureDetection(const ParametersMap & parameters = ParametersMap());
void disableFeatureDetection();
// Use new version of this function with groundNormalsUp=0.8 for forceGroundNormalsUp=True and groundNormalsUp=0.0 for forceGroundNormalsUp=False.
RTABMAP_DEPRECATED void setScanParameters(
bool fromDepth,
int downsampleStep, // decimation of the depth image in case the scan is from depth image
float rangeMin,
float rangeMax,
float voxelSize,
int normalsK,
float normalsRadius,
bool forceGroundNormalsUp,
bool deskewing);
void setScanParameters(
bool fromDepth,
int downsampleStep=1, // decimation of the depth image in case the scan is from depth image
float rangeMin=0.0f,
float rangeMax=0.0f,
float voxelSize = 0.0f,
int normalsK = 0,
float normalsRadius = 0.0f,
float groundNormalsUp = 0.0f,
bool deskewing = false);
void postUpdate(SensorData * data, SensorCaptureInfo * info = 0) const;
//getters
bool isPaused() const {return !this->isRunning();}
bool isCapturing() const {return this->isRunning();}
bool odomProvided() const;
Camera * camera() {return _camera;} // return null if not set, valid until CameraThread is deleted
SensorCapture * odomSensor() {return _odomSensor;} // return null if not set, valid until CameraThread is deleted
Lidar * lidar() {return _lidar;} // return null if not set, valid until CameraThread is deleted
private:
virtual void mainLoopBegin();
virtual void mainLoop();
virtual void mainLoopKill();
private:
Camera * _camera;
SensorCapture * _odomSensor;
Lidar * _lidar;
Transform _extrinsicsOdomToCamera;
bool _odomAsGt;
double _poseTimeOffset;
float _poseScaleFactor;
double _poseWaitTime;
bool _mirroring;
bool _stereoExposureCompensation;
bool _colorOnly;
int _imageDecimation;
int _histogramMethod;
bool _stereoToDepth;
bool _scanDeskewing;
bool _scanFromDepth;
int _scanDownsampleStep;
float _scanRangeMin;
float _scanRangeMax;
float _scanVoxelSize;
int _scanNormalsK;
float _scanNormalsRadius;
float _scanForceGroundNormalsUp;
StereoDense * _stereoDense;
clams::DiscreteDepthDistortionModel * _distortionModel;
bool _bilateralFiltering;
float _bilateralSigmaS;
float _bilateralSigmaR;
IMUFilter * _imuFilter;
bool _imuBaseFrameConversion;
Feature2D * _featureDetector;
bool _depthAsMask;
};
//backward compatibility
RTABMAP_DEPRECATED typedef SensorCaptureThread CameraThread;
} // namespace rtabmap
@@ -1,94 +0,0 @@
/*
Copyright (c) 2010-2016, Mathieu Labbe - IntRoLab - Universite de Sherbrooke
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Universite de Sherbrooke nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#pragma once
#include <rtabmap/core/SensorCaptureInfo.h>
#include <rtabmap/utilite/UEvent.h>
#include "rtabmap/core/SensorData.h"
namespace rtabmap
{
class SensorEvent :
public UEvent
{
public:
enum Code {
kCodeData,
kCodeNoMoreImages
};
public:
SensorEvent(const cv::Mat & image, int seq=0, double stamp = 0.0, const std::string & cameraName = std::string()) :
UEvent(kCodeData),
data_(image, seq, stamp)
{
sensorCaptureInfo_.cameraName = cameraName;
}
SensorEvent() :
UEvent(kCodeNoMoreImages)
{
}
SensorEvent(const SensorData & data) :
UEvent(kCodeData),
data_(data)
{
}
SensorEvent(const SensorData & data, const std::string & cameraName) :
UEvent(kCodeData),
data_(data)
{
sensorCaptureInfo_.cameraName = cameraName;
}
SensorEvent(const SensorData & data, const SensorCaptureInfo & sensorCaptureInfo) :
UEvent(kCodeData),
data_(data),
sensorCaptureInfo_(sensorCaptureInfo)
{
}
// Image or descriptors
const SensorData & data() const {return data_;}
const std::string & cameraName() const {return sensorCaptureInfo_.cameraName;}
const SensorCaptureInfo & info() const {return sensorCaptureInfo_;}
virtual ~SensorEvent() {}
virtual std::string getClassName() const {return std::string("SensorEvent");}
private:
SensorData data_;
SensorCaptureInfo sensorCaptureInfo_;
};
//backward compatibility
RTABMAP_DEPRECATED typedef SensorEvent CameraEvent;
} // namespace rtabmap
+2 -3
View File
@@ -90,10 +90,9 @@ public:
void removeLink(int idTo); void removeLink(int idTo);
void removeVirtualLinks(); void removeVirtualLinks();
void addLandmark(const Link & landmark); void addLandmark(const Link & landmark) {_landmarks.insert(std::make_pair(landmark.to(), landmark));}
const std::map<int, Link> & getLandmarks() const {return _landmarks;} const std::map<int, Link> & getLandmarks() const {return _landmarks;}
void removeLandmarks(); void removeLandmarks() {_landmarks.clear();}
void removeLandmark(int landmarkId);
void setSaved(bool saved) {_saved = saved;} void setSaved(bool saved) {_saved = saved;}
void setModified(bool modified) {_modified = modified; _linksModified = modified;} void setModified(bool modified) {_modified = modified; _linksModified = modified;}
@@ -157,7 +157,6 @@ class RTABMAP_CORE_EXPORT Statistics
RTABMAP_STATS(Timing, Memory_update, ms); RTABMAP_STATS(Timing, Memory_update, ms);
RTABMAP_STATS(Timing, Neighbor_link_refining, ms); RTABMAP_STATS(Timing, Neighbor_link_refining, ms);
RTABMAP_STATS(Timing, Proximity_by_time, ms); RTABMAP_STATS(Timing, Proximity_by_time, ms);
RTABMAP_STATS(Timing, Proximity_by_space_search, ms);
RTABMAP_STATS(Timing, Proximity_by_space_visual, ms); RTABMAP_STATS(Timing, Proximity_by_space_visual, ms);
RTABMAP_STATS(Timing, Proximity_by_space, ms); RTABMAP_STATS(Timing, Proximity_by_space, ms);
RTABMAP_STATS(Timing, Cleaning_neighbors, ms); RTABMAP_STATS(Timing, Cleaning_neighbors, ms);
@@ -57,12 +57,9 @@ public:
void setOutputMode(int outputMode = 0); void setOutputMode(int outputMode = 0);
void setDepthProfile(int confThreshold = 200, int lrcThreshold = 5); void setDepthProfile(int confThreshold = 200, int lrcThreshold = 5);
void setExtendedDisparity(bool extendedDisparity); void setRectification(bool useSpecTranslation, float alphaScaling = 0.0f);
void setSubpixelMode(bool enabled, int fractionalBits = 3);
void setCompanding(bool enabled, int width=96);
void setRectification(bool useSpecTranslation, float alphaScaling = 0.0f, bool enabled=true);
void setIMU(bool imuPublished, bool publishInterIMU); void setIMU(bool imuPublished, bool publishInterIMU);
void setIrIntensity(float dotIntensity = 0.0f, float floodIntensity = 0.0f); void setIrBrightness(float dotProjectormA = 0.0f, float floodLightmA = 200.0f);
void setDetectFeatures(int detectFeatures = 0); void setDetectFeatures(int detectFeatures = 0);
void setBlobPath(const std::string & blobPath); void setBlobPath(const std::string & blobPath);
void setGFTTDetector(bool useHarrisDetector = false, float minDistance = 7.0f, int numTargetFeatures = 1000); void setGFTTDetector(bool useHarrisDetector = false, float minDistance = 7.0f, int numTargetFeatures = 1000);
@@ -73,7 +70,7 @@ public:
virtual std::string getSerial() const; virtual std::string getSerial() const;
protected: protected:
virtual SensorData captureImage(SensorCaptureInfo * info = 0); virtual SensorData captureImage(CameraInfo * info = 0);
private: private:
#ifdef RTABMAP_DEPTHAI #ifdef RTABMAP_DEPTHAI
@@ -85,16 +82,12 @@ private:
int confThreshold_; int confThreshold_;
int lrcThreshold_; int lrcThreshold_;
int resolution_; int resolution_;
bool extendedDisparity_;
int subpixelFractionalBits_;
int compandingWidth_;
bool useSpecTranslation_; bool useSpecTranslation_;
float alphaScaling_; float alphaScaling_;
bool imagesRectified_;
bool imuPublished_; bool imuPublished_;
bool publishInterIMU_; bool publishInterIMU_;
float dotIntensity_; float dotProjectormA_;
float floodIntensity_; float floodLightmA_;
int detectFeatures_; int detectFeatures_;
bool useHarrisDetector_; bool useHarrisDetector_;
float minDistance_; float minDistance_;
@@ -104,7 +97,9 @@ private:
int nmsRadius_; int nmsRadius_;
std::string blobPath_; std::string blobPath_;
std::shared_ptr<dai::Device> device_; std::shared_ptr<dai::Device> device_;
std::shared_ptr<dai::DataOutputQueue> cameraQueue_; std::shared_ptr<dai::DataOutputQueue> leftOrColorQueue_;
std::shared_ptr<dai::DataOutputQueue> rightOrDepthQueue_;
std::shared_ptr<dai::DataOutputQueue> featuresQueue_;
std::map<double, cv::Vec3f> accBuffer_; std::map<double, cv::Vec3f> accBuffer_;
std::map<double, cv::Vec3f> gyroBuffer_; std::map<double, cv::Vec3f> gyroBuffer_;
UMutex imuMutex_; UMutex imuMutex_;
@@ -61,7 +61,7 @@ public:
virtual std::string getSerial() const; virtual std::string getSerial() const;
protected: protected:
virtual SensorData captureImage(SensorCaptureInfo * info = 0); virtual SensorData captureImage(CameraInfo * info = 0);
private: private:
#ifdef RTABMAP_FREENECT #ifdef RTABMAP_FREENECT
@@ -77,7 +77,7 @@ public:
virtual std::string getSerial() const; virtual std::string getSerial() const;
protected: protected:
virtual SensorData captureImage(SensorCaptureInfo * info = 0); virtual SensorData captureImage(CameraInfo * info = 0);
private: private:
#ifdef RTABMAP_FREENECT2 #ifdef RTABMAP_FREENECT2
@@ -118,7 +118,7 @@ public:
} }
protected: protected:
virtual SensorData captureImage(SensorCaptureInfo * info = 0); virtual SensorData captureImage(CameraInfo * info = 0);
private: private:
bool readPoses( bool readPoses(
@@ -63,7 +63,7 @@ public:
void setPreferences(int rgb_resolution, int framerate, int depth_resolution); void setPreferences(int rgb_resolution, int framerate, int depth_resolution);
protected: protected:
virtual SensorData captureImage(SensorCaptureInfo * info = 0); virtual SensorData captureImage(CameraInfo * info = 0);
private: private:
void close(); void close();
@@ -72,7 +72,7 @@ public:
virtual std::string getSerial() const; virtual std::string getSerial() const;
protected: protected:
virtual SensorData captureImage(SensorCaptureInfo * info = 0); virtual SensorData captureImage(CameraInfo * info = 0);
private: private:
void close(); void close();
@@ -67,7 +67,7 @@ protected:
/** /**
* returned rgb and depth images should be already rectified if calibration was loaded * returned rgb and depth images should be already rectified if calibration was loaded
*/ */
virtual SensorData captureImage(SensorCaptureInfo * info = 0); virtual SensorData captureImage(CameraInfo * info = 0);
private: private:
#ifdef RTABMAP_MYNTEYE #ifdef RTABMAP_MYNTEYE
@@ -69,7 +69,7 @@ public:
void setDepthDecimation(int decimation); void setDepthDecimation(int decimation);
protected: protected:
virtual SensorData captureImage(SensorCaptureInfo * info = 0); virtual SensorData captureImage(CameraInfo * info = 0);
private: private:
#ifdef RTABMAP_OPENNI2 #ifdef RTABMAP_OPENNI2
@@ -51,7 +51,7 @@ public:
virtual std::string getSerial() const {return "";} // unknown with OpenCV virtual std::string getSerial() const {return "";} // unknown with OpenCV
protected: protected:
virtual SensorData captureImage(SensorCaptureInfo * info = 0); virtual SensorData captureImage(CameraInfo * info = 0);
private: private:
bool _asus; bool _asus;
@@ -34,13 +34,15 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <pcl/pcl_config.h> #include <pcl/pcl_config.h>
#ifdef RTABMAP_OPENNI #ifdef HAVE_OPENNI
#if __linux__ && __i386__ && __cplusplus >= 201103L #if __linux__ && __i386__ && __cplusplus >= 201103L
#warning "Openni driver is not available on i386 when building with c++11 support" #warning "Openni driver is not available on i386 when building with c++11 support"
#endif #else
#define RTABMAP_OPENNI
#include <pcl/io/openni_camera/openni_depth_image.h> #include <pcl/io/openni_camera/openni_depth_image.h>
#include <pcl/io/openni_camera/openni_image.h> #include <pcl/io/openni_camera/openni_image.h>
#endif #endif
#endif
#include <boost/signals2/connection.hpp> #include <boost/signals2/connection.hpp>
@@ -83,7 +85,7 @@ public:
virtual std::string getSerial() const; virtual std::string getSerial() const;
protected: protected:
virtual SensorData captureImage(SensorCaptureInfo * info = 0); virtual SensorData captureImage(CameraInfo * info = 0);
private: private:
pcl::Grabber* interface_; pcl::Grabber* interface_;
@@ -53,7 +53,7 @@ public:
virtual void setMaxFrames(int value) {CameraImages::setMaxFrames(value);cameraDepth_.setMaxFrames(value);} virtual void setMaxFrames(int value) {CameraImages::setMaxFrames(value);cameraDepth_.setMaxFrames(value);}
protected: protected:
virtual SensorData captureImage(SensorCaptureInfo * info = 0); virtual SensorData captureImage(CameraInfo * info = 0);
private: private:
CameraImages cameraDepth_; CameraImages cameraDepth_;
@@ -72,7 +72,7 @@ public:
virtual bool odomProvided() const; virtual bool odomProvided() const;
protected: protected:
virtual SensorData captureImage(SensorCaptureInfo * info = 0); virtual SensorData captureImage(CameraInfo * info = 0);
private: private:
#ifdef RTABMAP_REALSENSE #ifdef RTABMAP_REALSENSE
@@ -68,7 +68,7 @@ public:
virtual bool isCalibrated() const; virtual bool isCalibrated() const;
virtual std::string getSerial() const; virtual std::string getSerial() const;
virtual bool odomProvided() const; virtual bool odomProvided() const;
virtual bool getPose(double stamp, Transform & pose, cv::Mat & covariance, double maxWaitTime = 0.06); virtual bool getPose(double stamp, Transform & pose, cv::Mat & covariance);
// parameters are set during initialization // parameters are set during initialization
// D400 series // D400 series
@@ -77,7 +77,7 @@ public:
void setResolution(int width, int height, int fps = 30); void setResolution(int width, int height, int fps = 30);
void setDepthResolution(int width, int height, int fps = 30); void setDepthResolution(int width, int height, int fps = 30);
void setGlobalTimeSync(bool enabled); void setGlobalTimeSync(bool enabled);
void publishInterIMU(bool enabled);
/** /**
* Dual mode (D400+T265 or L500+T265) * Dual mode (D400+T265 or L500+T265)
* @param enabled enable dual mode * @param enabled enable dual mode
@@ -105,7 +105,7 @@ private:
#endif #endif
protected: protected:
virtual SensorData captureImage(SensorCaptureInfo * info = 0); virtual SensorData captureImage(CameraInfo * info = 0);
private: private:
#ifdef RTABMAP_REALSENSE2 #ifdef RTABMAP_REALSENSE2
@@ -142,6 +142,7 @@ private:
int cameraDepthHeight_; int cameraDepthHeight_;
int cameraDepthFps_; int cameraDepthFps_;
bool globalTimeSync_; bool globalTimeSync_;
bool publishInterIMU_;
bool dualMode_; bool dualMode_;
Transform dualExtrinsics_; Transform dualExtrinsics_;
std::string jsonConfig_; std::string jsonConfig_;
@@ -1,52 +0,0 @@
#pragma once
#include "rtabmap/core/Camera.h"
#include "rtabmap/core/Version.h"
#include "rtabmap/utilite/USemaphore.h"
#ifdef RTABMAP_XVSDK
#include <xv-sdk.h>
#endif
namespace rtabmap
{
class RTABMAP_CORE_EXPORT CameraSeerSense :
public Camera
{
public:
static bool available();
public:
CameraSeerSense(
bool computeOdometry = false,
float imageRate = 0.0f,
const Transform & localTransform = Transform::getIdentity()
);
virtual ~CameraSeerSense();
virtual bool init(const std::string & calibrationFolder = ".", const std::string & cameraName = "");
virtual bool isCalibrated() const;
virtual std::string getSerial() const;
virtual bool odomProvided() const;
virtual bool getPose(double stamp, Transform & pose, cv::Mat & covariance, double maxWaitTime = 0.0);
protected:
virtual SensorData captureImage(SensorCaptureInfo * info = 0);
private:
#ifdef RTABMAP_XVSDK
CameraModel cameraModel_;
bool computeOdometry_;
int imuId_;
int tofId_;
std::shared_ptr<xv::Device> device_;
std::map<double, std::pair<cv::Vec3d, cv::Vec3d>> imuBuffer_;
std::pair<double, std::pair<cv::Mat, cv::Mat>> lastData_;
UMutex imuMutex_;
UMutex dataMutex_;
USemaphore dataReady_;
#endif
};
} // namespace rtabmap
@@ -51,7 +51,7 @@ public:
virtual std::string getSerial() const; virtual std::string getSerial() const;
protected: protected:
virtual SensorData captureImage(SensorCaptureInfo * info = 0); virtual SensorData captureImage(CameraInfo * info = 0);
private: private:
#ifdef RTABMAP_DC1394 #ifdef RTABMAP_DC1394
@@ -53,7 +53,7 @@ public:
virtual std::string getSerial() const; virtual std::string getSerial() const;
protected: protected:
virtual SensorData captureImage(SensorCaptureInfo * info = 0); virtual SensorData captureImage(CameraInfo * info = 0);
private: private:
#ifdef RTABMAP_FLYCAPTURE2 #ifdef RTABMAP_FLYCAPTURE2
@@ -64,7 +64,7 @@ public:
virtual void setMaxFrames(int value) {CameraImages::setMaxFrames(value);camera2_->setMaxFrames(value);} virtual void setMaxFrames(int value) {CameraImages::setMaxFrames(value);camera2_->setMaxFrames(value);}
protected: protected:
virtual SensorData captureImage(SensorCaptureInfo * info = 0); virtual SensorData captureImage(CameraInfo * info = 0);
private: private:
CameraImages * camera2_; CameraImages * camera2_;
@@ -60,7 +60,7 @@ public:
virtual std::string getSerial() const; virtual std::string getSerial() const;
protected: protected:
virtual SensorData captureImage(SensorCaptureInfo * info = 0); virtual SensorData captureImage(CameraInfo * info = 0);
private: private:
cv::VideoCapture capture_; cv::VideoCapture capture_;
@@ -71,7 +71,7 @@ public:
void setResolution(int width, int height) {_width=width, _height=height;} void setResolution(int width, int height) {_width=width, _height=height;}
protected: protected:
virtual SensorData captureImage(SensorCaptureInfo * info = 0); virtual SensorData captureImage(CameraInfo * info = 0);
private: private:
cv::VideoCapture capture_; cv::VideoCapture capture_;
@@ -76,12 +76,12 @@ public:
virtual bool isCalibrated() const; virtual bool isCalibrated() const;
virtual std::string getSerial() const; virtual std::string getSerial() const;
virtual bool odomProvided() const; virtual bool odomProvided() const;
virtual bool getPose(double stamp, Transform & pose, cv::Mat & covariance, double maxWaitTime = 0.0); virtual bool getPose(double stamp, Transform & pose, cv::Mat & covariance);
void postInterIMUPublic(const IMU & imu, double stamp); void publishInterIMU(bool enabled);
protected: protected:
virtual SensorData captureImage(SensorCaptureInfo * info = 0); virtual SensorData captureImage(CameraInfo * info = 0);
private: private:
#ifdef RTABMAP_ZED #ifdef RTABMAP_ZED
@@ -100,6 +100,7 @@ private:
bool computeOdometry_; bool computeOdometry_;
bool lost_; bool lost_;
bool force3DoF_; bool force3DoF_;
bool publishInterIMU_;
ZedIMUThread * imuPublishingThread_; ZedIMUThread * imuPublishingThread_;
#endif #endif
}; };
@@ -63,7 +63,7 @@ public:
virtual std::string getSerial() const; virtual std::string getSerial() const;
protected: protected:
virtual SensorData captureImage(SensorCaptureInfo * info = 0); virtual SensorData captureImage(CameraInfo * info = 0);
private: private:
#ifdef RTABMAP_ZEDOC #ifdef RTABMAP_ZEDOC
@@ -64,7 +64,7 @@ public:
void setResolution(int width, int height) {_width=width, _height=height;} void setResolution(int width, int height) {_width=width, _height=height;}
protected: protected:
virtual SensorData captureImage(SensorCaptureInfo * info = 0); virtual SensorData captureImage(CameraInfo * info = 0);
private: private:
// File type // File type
@@ -1,94 +0,0 @@
/*
Copyright (c) 2010-2022, Mathieu Labbe
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef CORELIB_INCLUDE_RTABMAP_CORE_LIDAR_LIDARVLP16_H_
#define CORELIB_INCLUDE_RTABMAP_CORE_LIDAR_LIDARVLP16_H_
// Should be first on windows to avoid "WinSock.h has already been included" error
#include <pcl/io/vlp_grabber.h>
#include <rtabmap/core/Lidar.h>
#include <rtabmap/utilite/USemaphore.h>
namespace rtabmap {
struct PointXYZIT {
float x;
float y;
float z;
float i;
float t;
};
class RTABMAP_CORE_EXPORT LidarVLP16 :public Lidar, public pcl::VLPGrabber {
public:
LidarVLP16(
const std::string& pcapFile,
bool organized = false,
bool stampLast = true,
float frameRate = 0.0f,
Transform localTransform = Transform::getIdentity());
LidarVLP16(
const boost::asio::ip::address& ipAddress,
const std::uint16_t port = 2368,
bool organized = false,
bool useHostTime = true,
bool stampLast = true,
float frameRate = 0.0f,
Transform localTransform = Transform::getIdentity());
virtual ~LidarVLP16();
SensorData takeScan(SensorCaptureInfo * info = 0) {return takeData(info);}
virtual bool init(const std::string & calibrationFolder = ".", const std::string & cameraName = "") override;
virtual std::string getSerial() const override {return getName();}
void setOrganized(bool enable);
private:
void buildTimings(bool dualMode);
virtual void toPointClouds (HDLDataPacket *dataPacket) override;
protected:
virtual SensorData captureData(SensorCaptureInfo * info = 0) override;
private:
// timing offset lookup table
std::vector< std::vector<float> > timingOffsets_;
bool timingOffsetsDualMode_;
double startSweepTime_;
double startSweepTimeHost_;
bool organized_;
bool useHostTime_;
bool stampLast_;
SensorData lastScan_;
std::vector<std::vector<PointXYZIT> > accumulatedScans_;
USemaphore scanReady_;
UMutex lastScanMutex_;
};
} /* namespace rtabmap */
#endif /* CORELIB_INCLUDE_RTABMAP_CORE_LIDAR_LIDARVLP16_H_ */
@@ -30,10 +30,6 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <rtabmap/core/Optimizer.h> #include <rtabmap/core/Optimizer.h>
namespace gtsam {
class ISAM2;
}
namespace rtabmap { namespace rtabmap {
class RTABMAP_CORE_EXPORT OptimizerGTSAM : public Optimizer class RTABMAP_CORE_EXPORT OptimizerGTSAM : public Optimizer
@@ -42,8 +38,13 @@ public:
static bool available(); static bool available();
public: public:
OptimizerGTSAM(const ParametersMap & parameters = ParametersMap()); OptimizerGTSAM(const ParametersMap & parameters = ParametersMap()) :
virtual ~OptimizerGTSAM(); Optimizer(parameters),
optimizer_(Parameters::defaultGTSAMOptimizer())
{
parseParameters(parameters);
}
virtual ~OptimizerGTSAM() {}
virtual Type type() const {return kTypeGTSAM;} virtual Type type() const {return kTypeGTSAM;}
@@ -59,25 +60,7 @@ public:
int * iterationsDone = 0); int * iterationsDone = 0);
private: private:
int internalOptimizerType_; int optimizer_;
gtsam::ISAM2 * isam2_;
struct ConstraintToFactor {
ConstraintToFactor(int _from, int _to, std::uint64_t _factorIndice)
{
from = _from;
to = _to;
factorIndice = _factorIndice;
}
int from;
int to;
std::uint64_t factorIndice;
};
std::vector<ConstraintToFactor> lastAddedConstraints_;
int lastSwitchId_;
std::set<int> addedPoses_;
std::pair<int, std::uint64_t> lastRootFactorIndex_;
}; };
} /* namespace rtabmap */ } /* namespace rtabmap */
-3
View File
@@ -164,9 +164,6 @@ void RTABMAP_CORE_EXPORT NMS(
cv::Mat & descriptorsOut, cv::Mat & descriptorsOut,
int border, int dist_thresh, int img_width, int img_height); int border, int dist_thresh, int img_width, int img_height);
std::vector<int> RTABMAP_CORE_EXPORT SSC(
const std::vector<cv::KeyPoint> & keypoints, int maxKeypoints, float tolerance, int cols, int rows);
/** /**
* @brief Rotate images and camera model so that the top of the image is up. * @brief Rotate images and camera model so that the top of the image is up.
* *
-13
View File
@@ -455,19 +455,6 @@ RTABMAP_DEPRECATED pcl::PointCloud<pcl::PointXYZ>::Ptr RTABMAP_CORE_EXPORT loadC
int downsampleStep = 1, int downsampleStep = 1,
float voxelSize = 0.0f); float voxelSize = 0.0f);
/**
* @brief Lidar deskewing
* @param input lidar, format should have time channel
* @param input stamp of the lidar
* @param velocity in base frame
* @param velocity stamp at which it has been computed
* @return lidar deskewed
*/
LaserScan RTABMAP_CORE_EXPORT deskew(
const LaserScan & input,
double inputStamp,
const rtabmap::Transform & velocity);
} // namespace util3d } // namespace util3d
} // namespace rtabmap } // namespace rtabmap
+4 -24
View File
@@ -13,10 +13,8 @@ SET(SRC_FILES
Recovery.cpp Recovery.cpp
SensorCapture.cpp
SensorCaptureThread.cpp
Camera.cpp Camera.cpp
CameraThread.cpp
CameraModel.cpp CameraModel.cpp
camera/CameraFreenect.cpp camera/CameraFreenect.cpp
@@ -40,7 +38,6 @@ SET(SRC_FILES
camera/CameraVideo.cpp camera/CameraVideo.cpp
camera/CameraMyntEye.cpp camera/CameraMyntEye.cpp
camera/CameraDepthAI.cpp camera/CameraDepthAI.cpp
camera/CameraSeerSense.cpp
EpipolarGeometry.cpp EpipolarGeometry.cpp
VisualWord.cpp VisualWord.cpp
@@ -118,8 +115,6 @@ SET(SRC_FILES
MarkerDetector.cpp MarkerDetector.cpp
GlobalDescriptorExtractor.cpp
GainCompensator.cpp GainCompensator.cpp
rtflann/ext/lz4.c rtflann/ext/lz4.c
@@ -137,13 +132,6 @@ SET(SRC_FILES
opencv/five-point.cpp opencv/five-point.cpp
) )
IF(PCL_VERSION VERSION_GREATER_EQUAL "1.8")
SET(SRC_FILES
${SRC_FILES}
lidar/LidarVLP16.cpp
)
ENDIF(PCL_VERSION VERSION_GREATER_EQUAL "1.8")
IF(OpenCV_VERSION_MAJOR EQUAL 2) IF(OpenCV_VERSION_MAJOR EQUAL 2)
SET(SRC_FILES SET(SRC_FILES
${SRC_FILES} ${SRC_FILES}
@@ -185,14 +173,14 @@ SET(PUBLIC_LIBRARIES
${PCL_LIBRARIES} ${PCL_LIBRARIES}
) )
IF(SQLite3_FOUND) IF(Sqlite3_FOUND)
SET(INCLUDE_DIRS SET(INCLUDE_DIRS
${INCLUDE_DIRS} ${INCLUDE_DIRS}
${SQLite3_INCLUDE_DIRS} ${Sqlite3_INCLUDE_DIRS}
) )
SET(LIBRARIES SET(LIBRARIES
${LIBRARIES} ${LIBRARIES}
${SQLite3_LIBRARIES} ${Sqlite3_LIBRARIES}
) )
ELSE() ELSE()
SET(SRC_FILES SET(SRC_FILES
@@ -236,7 +224,6 @@ IF(WITH_PYTHON AND Python3_FOUND)
python/PythonInterface.cpp python/PythonInterface.cpp
python/PyMatcher.cpp python/PyMatcher.cpp
python/PyDetector.cpp python/PyDetector.cpp
python/PyDescriptor.cpp
) )
SET(INCLUDE_DIRS SET(INCLUDE_DIRS
${TORCH_INCLUDE_DIRS} ${TORCH_INCLUDE_DIRS}
@@ -384,13 +371,6 @@ IF(depthai_FOUND)
) )
ENDIF(depthai_FOUND) ENDIF(depthai_FOUND)
IF(xvsdk_FOUND)
SET(PUBLIC_LIBRARIES
${PUBLIC_LIBRARIES}
${xvsdk_LIBRARIES}
)
ENDIF(xvsdk_FOUND)
IF(TARGET OpenMP::OpenMP_CXX) IF(TARGET OpenMP::OpenMP_CXX)
SET(LIBRARIES SET(LIBRARIES
${LIBRARIES} ${LIBRARIES}
+67 -28
View File
@@ -26,25 +26,42 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/ */
#include "rtabmap/core/Camera.h" #include "rtabmap/core/Camera.h"
#include "rtabmap/core/IMUFilter.h"
#include <rtabmap/utilite/UEventsManager.h>
#include <rtabmap/utilite/UConversion.h>
#include <rtabmap/utilite/UStl.h> #include <rtabmap/utilite/UStl.h>
#include <rtabmap/utilite/UConversion.h>
#include <rtabmap/utilite/UFile.h> #include <rtabmap/utilite/UFile.h>
#include <rtabmap/utilite/UDirectory.h> #include <rtabmap/utilite/UDirectory.h>
#include <rtabmap/utilite/UEventsManager.h> #include <rtabmap/utilite/UTimer.h>
#include <opencv2/imgproc/imgproc.hpp>
#include <iostream>
#include <cmath>
namespace rtabmap namespace rtabmap
{ {
Camera::Camera(float imageRate, const Transform & localTransform) : Camera::Camera(float imageRate, const Transform & localTransform) :
SensorCapture(imageRate, localTransform*CameraModel::opticalRotation()), _imageRate(imageRate),
imuFilter_(0), _localTransform(localTransform*CameraModel::opticalRotation()),
publishInterIMU_(false) _targetImageSize(0,0),
{} _frameRateTimer(new UTimer()),
_seq(0)
{
}
Camera::~Camera() Camera::~Camera()
{ {
delete imuFilter_; UDEBUG("");
delete _frameRateTimer;
UDEBUG("");
}
void Camera::resetTimer()
{
_frameRateTimer->start();
} }
bool Camera::initFromFile(const std::string & calibrationPath) bool Camera::initFromFile(const std::string & calibrationPath)
@@ -52,32 +69,54 @@ bool Camera::initFromFile(const std::string & calibrationPath)
return init(UDirectory::getDir(calibrationPath), uSplit(UFile::getName(calibrationPath), '.').front()); return init(UDirectory::getDir(calibrationPath), uSplit(UFile::getName(calibrationPath), '.').front());
} }
void Camera::setInterIMUPublishing(bool enabled, IMUFilter * filter) SensorData Camera::takeImage(CameraInfo * info)
{ {
publishInterIMU_ = enabled; bool warnFrameRateTooHigh = false;
delete imuFilter_; float actualFrameRate = 0;
imuFilter_ = filter; float imageRate = _imageRate;
if(imageRate>0)
{
int sleepTime = (1000.0f/imageRate - 1000.0f*_frameRateTimer->getElapsedTime());
if(sleepTime > 2)
{
uSleep(sleepTime-2);
}
else if(sleepTime < 0)
{
warnFrameRateTooHigh = true;
actualFrameRate = 1.0/(_frameRateTimer->getElapsedTime());
} }
void Camera::postInterIMU(const IMU & imu, double stamp) // Add precision at the cost of a small overhead
while(_frameRateTimer->getElapsedTime() < 1.0/double(imageRate)-0.000001)
{ {
if(imuFilter_) //
{
imuFilter_->update(
imu.angularVelocity()[0], imu.angularVelocity()[1], imu.angularVelocity()[2],
imu.linearAcceleration()[0], imu.linearAcceleration()[1], imu.linearAcceleration()[2],
stamp);
cv::Vec4d q;
imuFilter_->getOrientation(q[0],q[1],q[2],q[3]);
UEventsManager::post(new IMUEvent(IMU(
q, cv::Mat(),
imu.angularVelocity(), imu.angularVelocityCovariance(),
imu.linearAcceleration(), imu.linearAccelerationCovariance(),
imu.localTransform()),
stamp));
return;
} }
UEventsManager::post(new IMUEvent(imu, stamp));
double slept = _frameRateTimer->getElapsedTime();
_frameRateTimer->start();
UDEBUG("slept=%fs vs target=%fs", slept, 1.0/double(imageRate));
}
UTimer timer;
SensorData data = this->captureImage(info);
double captureTime = timer.ticks();
if(warnFrameRateTooHigh)
{
UWARN("Camera: Cannot reach target image rate %f Hz, current rate is %f Hz and capture time = %f s.",
imageRate, actualFrameRate, captureTime);
}
else
{
UDEBUG("Time capturing image = %fs", captureTime);
}
if(info)
{
info->id = data.id();
info->stamp = data.stamp();
info->timeCapture = captureTime;
}
return data;
} }
} // namespace rtabmap } // namespace rtabmap
+3 -3
View File
@@ -60,7 +60,7 @@ CameraModel::CameraModel(
localTransform_(localTransform) localTransform_(localTransform)
{ {
UASSERT(K_.empty() || (K_.rows == 3 && K_.cols == 3 && K_.type() == CV_64FC1)); UASSERT(K_.empty() || (K_.rows == 3 && K_.cols == 3 && K_.type() == CV_64FC1));
UASSERT(D_.empty() || (D_.rows == 1 && (D_.cols == 4 || D_.cols == 5 || D_.cols == 6 || D_.cols == 8 || D_.cols == 12 || D_.cols == 14) && D_.type() == CV_64FC1)); UASSERT(D_.empty() || (D_.rows == 1 && (D_.cols == 4 || D_.cols == 5 || D_.cols == 6 || D_.cols == 8) && D_.type() == CV_64FC1));
UASSERT(R_.empty() || (R_.rows == 3 && R_.cols == 3 && R_.type() == CV_64FC1)); UASSERT(R_.empty() || (R_.rows == 3 && R_.cols == 3 && R_.type() == CV_64FC1));
UASSERT(P_.empty() || (P_.rows == 3 && P_.cols == 4 && P_.type() == CV_64FC1)); UASSERT(P_.empty() || (P_.rows == 3 && P_.cols == 4 && P_.type() == CV_64FC1));
} }
@@ -156,7 +156,7 @@ CameraModel::CameraModel(
bool CameraModel::initRectificationMap() bool CameraModel::initRectificationMap()
{ {
UASSERT(imageSize_.height > 0 && imageSize_.width > 0); UASSERT(imageSize_.height > 0 && imageSize_.width > 0);
UASSERT(D_.rows == 1 && (D_.cols == 4 || D_.cols == 5 || D_.cols == 6 || D_.cols == 8 || D_.cols == 12 || D_.cols == 14)); UASSERT(D_.rows == 1 && (D_.cols == 4 || D_.cols == 5 || D_.cols == 6 || D_.cols == 8));
UASSERT(R_.rows == 3 && R_.cols == 3); UASSERT(R_.rows == 3 && R_.cols == 3);
UASSERT(P_.rows == 3 && P_.cols == 4); UASSERT(P_.rows == 3 && P_.cols == 4);
// init rectification map // init rectification map
@@ -279,7 +279,7 @@ bool CameraModel::load(const std::string & filePath)
std::vector<double> data; std::vector<double> data;
n["data"] >> data; n["data"] >> data;
UASSERT(rows*cols == (int)data.size()); UASSERT(rows*cols == (int)data.size());
UASSERT(rows == 1 && (cols == 4 || cols == 5 || cols == 8 || cols == 12 || cols == 14)); UASSERT(rows == 1 && (cols == 4 || cols == 5 || cols == 8));
D_ = cv::Mat(rows, cols, CV_64FC1, data.data()).clone(); D_ = cv::Mat(rows, cols, CV_64FC1, data.data()).clone();
} }
else else
@@ -25,10 +25,9 @@ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/ */
#include "rtabmap/core/SensorCaptureThread.h" #include "rtabmap/core/CameraThread.h"
#include "rtabmap/core/Camera.h" #include "rtabmap/core/Camera.h"
#include "rtabmap/core/Lidar.h" #include "rtabmap/core/CameraEvent.h"
#include "rtabmap/core/SensorEvent.h"
#include "rtabmap/core/CameraRGBD.h" #include "rtabmap/core/CameraRGBD.h"
#include "rtabmap/core/util2d.h" #include "rtabmap/core/util2d.h"
#include "rtabmap/core/util3d.h" #include "rtabmap/core/util3d.h"
@@ -51,81 +50,18 @@ namespace rtabmap
{ {
// ownership transferred // ownership transferred
SensorCaptureThread::SensorCaptureThread( CameraThread::CameraThread(Camera * camera, const ParametersMap & parameters) :
Camera * camera,
const ParametersMap & parameters) :
SensorCaptureThread(0, camera, 0, Transform(), 0.0, 1.0f, 0.1, parameters)
{
UASSERT(camera != 0);
}
// ownership transferred
SensorCaptureThread::SensorCaptureThread(
Camera * camera,
SensorCapture * odomSensor,
const Transform & extrinsics,
double poseTimeOffset,
float poseScaleFactor,
double poseWaitTime,
const ParametersMap & parameters) :
SensorCaptureThread(0, camera, odomSensor, extrinsics, poseTimeOffset, poseScaleFactor, poseWaitTime, parameters)
{
UASSERT(camera != 0 && odomSensor != 0 && !extrinsics.isNull());
}
SensorCaptureThread::SensorCaptureThread(
Lidar * lidar,
const ParametersMap & parameters) :
SensorCaptureThread(lidar, 0, 0, Transform(), 0.0, 1.0f, 0.1, parameters)
{
UASSERT(lidar != 0);
}
SensorCaptureThread::SensorCaptureThread(
Lidar * lidar,
Camera * camera,
const ParametersMap & parameters) :
SensorCaptureThread(lidar, camera, 0, Transform(), 0.0, 1.0f, 0.1, parameters)
{
UASSERT(lidar != 0 && camera != 0);
}
SensorCaptureThread::SensorCaptureThread(
Lidar * lidar,
SensorCapture * odomSensor,
double poseTimeOffset,
float poseScaleFactor,
double poseWaitTime,
const ParametersMap & parameters) :
SensorCaptureThread(lidar, 0, odomSensor, Transform(), poseTimeOffset, poseScaleFactor, poseWaitTime, parameters)
{
UASSERT(lidar != 0 && odomSensor != 0);
}
SensorCaptureThread::SensorCaptureThread(
Lidar * lidar,
Camera * camera,
SensorCapture * odomSensor,
const Transform & extrinsics,
double poseTimeOffset,
float poseScaleFactor,
double poseWaitTime,
const ParametersMap & parameters) :
_camera(camera), _camera(camera),
_odomSensor(odomSensor), _odomSensor(0),
_lidar(lidar),
_extrinsicsOdomToCamera(extrinsics * CameraModel::opticalRotation()),
_odomAsGt(false), _odomAsGt(false),
_poseTimeOffset(poseTimeOffset), _poseTimeOffset(0.0),
_poseScaleFactor(poseScaleFactor), _poseScaleFactor(1.0f),
_poseWaitTime(poseWaitTime),
_mirroring(false), _mirroring(false),
_stereoExposureCompensation(false), _stereoExposureCompensation(false),
_colorOnly(false), _colorOnly(false),
_imageDecimation(1), _imageDecimation(1),
_histogramMethod(0), _histogramMethod(0),
_stereoToDepth(false), _stereoToDepth(false),
_scanDeskewing(false),
_scanFromDepth(false), _scanFromDepth(false),
_scanDownsampleStep(1), _scanDownsampleStep(1),
_scanRangeMin(0.0f), _scanRangeMin(0.0f),
@@ -144,56 +80,113 @@ SensorCaptureThread::SensorCaptureThread(
_featureDetector(0), _featureDetector(0),
_depthAsMask(Parameters::defaultVisDepthAsMask()) _depthAsMask(Parameters::defaultVisDepthAsMask())
{ {
UASSERT(_camera != 0 || _lidar != 0); UASSERT(_camera != 0);
if(_lidar && _camera)
{
_camera->setFrameRate(0);
}
if(_odomSensor)
{
if(_camera)
{
if(_odomSensor == _camera && _extrinsicsOdomToCamera.isNull())
{
_extrinsicsOdomToCamera.setIdentity();
}
UASSERT(!_extrinsicsOdomToCamera.isNull());
UDEBUG("_extrinsicsOdomToCamera=%s", _extrinsicsOdomToCamera.prettyPrint().c_str());
}
UDEBUG("_poseTimeOffset =%f", _poseTimeOffset);
UDEBUG("_poseScaleFactor =%f", _poseScaleFactor);
UDEBUG("_poseWaitTime =%f", _poseWaitTime);
}
} }
SensorCaptureThread::~SensorCaptureThread() // ownership transferred
CameraThread::CameraThread(
Camera * camera,
Camera * odomSensor,
const Transform & extrinsics,
double poseTimeOffset,
float poseScaleFactor,
bool odomAsGt,
const ParametersMap & parameters) :
_camera(camera),
_odomSensor(odomSensor),
_extrinsicsOdomToCamera(extrinsics * CameraModel::opticalRotation()),
_odomAsGt(odomAsGt),
_poseTimeOffset(poseTimeOffset),
_poseScaleFactor(poseScaleFactor),
_mirroring(false),
_stereoExposureCompensation(false),
_colorOnly(false),
_imageDecimation(1),
_histogramMethod(0),
_stereoToDepth(false),
_scanFromDepth(false),
_scanDownsampleStep(1),
_scanRangeMin(0.0f),
_scanRangeMax(0.0f),
_scanVoxelSize(0.0f),
_scanNormalsK(0),
_scanNormalsRadius(0.0f),
_scanForceGroundNormalsUp(false),
_stereoDense(StereoDense::create(parameters)),
_distortionModel(0),
_bilateralFiltering(false),
_bilateralSigmaS(10),
_bilateralSigmaR(0.1),
_imuFilter(0),
_imuBaseFrameConversion(false),
_featureDetector(0),
_depthAsMask(Parameters::defaultVisDepthAsMask())
{
UASSERT(_camera != 0 && _odomSensor != 0 && !_extrinsicsOdomToCamera.isNull());
UDEBUG("_extrinsicsOdomToCamera=%s", _extrinsicsOdomToCamera.prettyPrint().c_str());
UDEBUG("_poseTimeOffset =%f", _poseTimeOffset);
UDEBUG("_poseScaleFactor =%f", _poseScaleFactor);
UDEBUG("_odomAsGt =%s", _odomAsGt?"true":"false");
}
// ownership transferred
CameraThread::CameraThread(
Camera * camera,
bool odomAsGt,
const ParametersMap & parameters) :
_camera(camera),
_odomSensor(0),
_odomAsGt(odomAsGt),
_poseTimeOffset(0.0),
_poseScaleFactor(1.0f),
_mirroring(false),
_stereoExposureCompensation(false),
_colorOnly(false),
_imageDecimation(1),
_histogramMethod(0),
_stereoToDepth(false),
_scanFromDepth(false),
_scanDownsampleStep(1),
_scanRangeMin(0.0f),
_scanRangeMax(0.0f),
_scanVoxelSize(0.0f),
_scanNormalsK(0),
_scanNormalsRadius(0.0f),
_scanForceGroundNormalsUp(false),
_stereoDense(StereoDense::create(parameters)),
_distortionModel(0),
_bilateralFiltering(false),
_bilateralSigmaS(10),
_bilateralSigmaR(0.1),
_imuFilter(0),
_imuBaseFrameConversion(false),
_featureDetector(0),
_depthAsMask(Parameters::defaultVisDepthAsMask())
{
UASSERT(_camera != 0);
UDEBUG("_odomAsGt =%s", _odomAsGt?"true":"false");
}
CameraThread::~CameraThread()
{ {
join(true); join(true);
if(_odomSensor != _camera && _odomSensor != _lidar)
{
delete _odomSensor;
}
delete _camera; delete _camera;
delete _lidar; delete _odomSensor;
delete _distortionModel; delete _distortionModel;
delete _stereoDense; delete _stereoDense;
delete _imuFilter; delete _imuFilter;
delete _featureDetector; delete _featureDetector;
} }
void SensorCaptureThread::setFrameRate(float frameRate) void CameraThread::setImageRate(float imageRate)
{ {
if(_lidar) if(_camera)
{ {
_lidar->setFrameRate(frameRate); _camera->setImageRate(imageRate);
}
else if(_camera)
{
_camera->setFrameRate(frameRate);
} }
} }
void SensorCaptureThread::setDistortionModel(const std::string & path) void CameraThread::setDistortionModel(const std::string & path)
{ {
if(_distortionModel) if(_distortionModel)
{ {
@@ -213,7 +206,7 @@ void SensorCaptureThread::setDistortionModel(const std::string & path)
} }
} }
void SensorCaptureThread::enableBilateralFiltering(float sigmaS, float sigmaR) void CameraThread::enableBilateralFiltering(float sigmaS, float sigmaR)
{ {
UASSERT(sigmaS > 0.0f && sigmaR > 0.0f); UASSERT(sigmaS > 0.0f && sigmaR > 0.0f);
_bilateralFiltering = true; _bilateralFiltering = true;
@@ -221,27 +214,26 @@ void SensorCaptureThread::enableBilateralFiltering(float sigmaS, float sigmaR)
_bilateralSigmaR = sigmaR; _bilateralSigmaR = sigmaR;
} }
void SensorCaptureThread::enableIMUFiltering(int filteringStrategy, const ParametersMap & parameters, bool baseFrameConversion) void CameraThread::enableIMUFiltering(int filteringStrategy, const ParametersMap & parameters, bool baseFrameConversion)
{ {
delete _imuFilter; delete _imuFilter;
_imuFilter = IMUFilter::create((IMUFilter::Type)filteringStrategy, parameters); _imuFilter = IMUFilter::create((IMUFilter::Type)filteringStrategy, parameters);
_imuBaseFrameConversion = baseFrameConversion; _imuBaseFrameConversion = baseFrameConversion;
} }
void SensorCaptureThread::disableIMUFiltering() void CameraThread::disableIMUFiltering()
{ {
delete _imuFilter; delete _imuFilter;
_imuFilter = 0; _imuFilter = 0;
} }
void SensorCaptureThread::enableFeatureDetection(const ParametersMap & parameters) void CameraThread::enableFeatureDetection(const ParametersMap & parameters)
{ {
delete _featureDetector; delete _featureDetector;
ParametersMap params = parameters; ParametersMap params = parameters;
ParametersMap defaultParams = Parameters::getDefaultParameters("Vis"); ParametersMap defaultParams = Parameters::getDefaultParameters("Vis");
uInsert(params, ParametersPair(Parameters::kKpDetectorStrategy(), uValue(params, Parameters::kVisFeatureType(), defaultParams.at(Parameters::kVisFeatureType())))); uInsert(params, ParametersPair(Parameters::kKpDetectorStrategy(), uValue(params, Parameters::kVisFeatureType(), defaultParams.at(Parameters::kVisFeatureType()))));
uInsert(params, ParametersPair(Parameters::kKpMaxFeatures(), uValue(params, Parameters::kVisMaxFeatures(), defaultParams.at(Parameters::kVisMaxFeatures())))); uInsert(params, ParametersPair(Parameters::kKpMaxFeatures(), uValue(params, Parameters::kVisMaxFeatures(), defaultParams.at(Parameters::kVisMaxFeatures()))));
uInsert(params, ParametersPair(Parameters::kKpSSC(), uValue(params, Parameters::kVisSSC(), defaultParams.at(Parameters::kVisSSC()))));
uInsert(params, ParametersPair(Parameters::kKpMaxDepth(), uValue(params, Parameters::kVisMaxDepth(), defaultParams.at(Parameters::kVisMaxDepth())))); uInsert(params, ParametersPair(Parameters::kKpMaxDepth(), uValue(params, Parameters::kVisMaxDepth(), defaultParams.at(Parameters::kVisMaxDepth()))));
uInsert(params, ParametersPair(Parameters::kKpMinDepth(), uValue(params, Parameters::kVisMinDepth(), defaultParams.at(Parameters::kVisMinDepth())))); uInsert(params, ParametersPair(Parameters::kKpMinDepth(), uValue(params, Parameters::kVisMinDepth(), defaultParams.at(Parameters::kVisMinDepth()))));
uInsert(params, ParametersPair(Parameters::kKpRoiRatios(), uValue(params, Parameters::kVisRoiRatios(), defaultParams.at(Parameters::kVisRoiRatios())))); uInsert(params, ParametersPair(Parameters::kKpRoiRatios(), uValue(params, Parameters::kVisRoiRatios(), defaultParams.at(Parameters::kVisRoiRatios()))));
@@ -253,38 +245,35 @@ void SensorCaptureThread::enableFeatureDetection(const ParametersMap & parameter
_featureDetector = Feature2D::create(params); _featureDetector = Feature2D::create(params);
_depthAsMask = Parameters::parse(params, Parameters::kVisDepthAsMask(), _depthAsMask); _depthAsMask = Parameters::parse(params, Parameters::kVisDepthAsMask(), _depthAsMask);
} }
void SensorCaptureThread::disableFeatureDetection() void CameraThread::disableFeatureDetection()
{ {
delete _featureDetector; delete _featureDetector;
_featureDetector = 0; _featureDetector = 0;
} }
void SensorCaptureThread::setScanParameters( void CameraThread::setScanParameters(
bool fromDepth, bool fromDepth,
int downsampleStep, int downsampleStep,
float rangeMin, float rangeMin,
float rangeMax, float rangeMax,
float voxelSize, float voxelSize,
int normalsK, int normalsK,
float normalsRadius, int normalsRadius,
bool forceGroundNormalsUp, bool forceGroundNormalsUp)
bool deskewing)
{ {
setScanParameters(fromDepth, downsampleStep, rangeMin, rangeMax, voxelSize, normalsK, normalsRadius, forceGroundNormalsUp?0.8f:0.0f, deskewing); setScanParameters(fromDepth, downsampleStep, rangeMin, rangeMax, voxelSize, normalsK, normalsRadius, forceGroundNormalsUp?0.8f:0.0f);
} }
void SensorCaptureThread::setScanParameters( void CameraThread::setScanParameters(
bool fromDepth, bool fromDepth,
int downsampleStep, // decimation of the depth image in case the scan is from depth image int downsampleStep, // decimation of the depth image in case the scan is from depth image
float rangeMin, float rangeMin,
float rangeMax, float rangeMax,
float voxelSize, float voxelSize,
int normalsK, int normalsK,
float normalsRadius, int normalsRadius,
float groundNormalsUp, float groundNormalsUp)
bool deskewing)
{ {
_scanDeskewing = deskewing;
_scanFromDepth = fromDepth; _scanFromDepth = fromDepth;
_scanDownsampleStep=downsampleStep; _scanDownsampleStep=downsampleStep;
_scanRangeMin = rangeMin; _scanRangeMin = rangeMin;
@@ -295,178 +284,29 @@ void SensorCaptureThread::setScanParameters(
_scanForceGroundNormalsUp = groundNormalsUp; _scanForceGroundNormalsUp = groundNormalsUp;
} }
bool SensorCaptureThread::odomProvided() const bool CameraThread::odomProvided() const
{ {
if(_odomAsGt) return _camera && (_camera->odomProvided() || (_odomSensor && _odomSensor->odomProvided()));
{
return false;
}
return _odomSensor != 0;
} }
void SensorCaptureThread::mainLoopBegin() void CameraThread::mainLoopBegin()
{ {
ULogger::registerCurrentThread("Camera"); ULogger::registerCurrentThread("Camera");
if(_lidar)
{
_lidar->resetTimer();
}
else if(_camera)
{
_camera->resetTimer(); _camera->resetTimer();
} }
if(_imuFilter)
{
// In case we paused the camera and moved somewhere else, restart filtering.
_imuFilter->reset();
}
}
void SensorCaptureThread::mainLoop() void CameraThread::mainLoop()
{ {
UASSERT(_lidar || _camera);
UTimer totalTime; UTimer totalTime;
SensorCaptureInfo info; CameraInfo info;
SensorData data; SensorData data = _camera->takeImage(&info);
SensorData cameraData;
double lidarStamp = 0.0;
double cameraStamp = 0.0;
if(_lidar)
{
data = _lidar->takeData(&info);
if(data.stamp() == 0.0)
{
UWARN("Could not capture scan!");
}
else
{
lidarStamp = data.stamp();
if(_camera)
{
cameraData = _camera->takeData();
if(cameraData.stamp() == 0.0)
{
UWARN("Could not capture image!");
}
else
{
double stampStart = UTimer::now();
while(cameraData.stamp() < data.stamp() &&
!isKilled() &&
UTimer::now() - stampStart < _poseWaitTime &&
!cameraData.imageRaw().empty())
{
// Make sure the camera frame is newer than lidar frame so
// that if there are imus published by the cameras, we can get
// them all in odometry before deskewing.
cameraData = _camera->takeData();
}
cameraStamp = cameraData.stamp(); if(_odomSensor)
if(cameraData.stamp() < data.stamp())
{ {
UWARN("Could not get camera frame (%f) with stamp more recent than lidar frame (%f) after waiting for %f seconds.",
cameraData.stamp(),
data.stamp(),
_poseWaitTime);
}
if(!cameraData.stereoCameraModels().empty())
{
data.setStereoImage(cameraData.imageRaw(), cameraData.depthOrRightRaw(), cameraData.stereoCameraModels(), true);
}
else
{
data.setRGBDImage(cameraData.imageRaw(), cameraData.depthOrRightRaw(), cameraData.cameraModels(), true);
}
}
}
}
}
else if(_camera)
{
data = _camera->takeData(&info);
if(data.stamp() == 0.0)
{
UWARN("Could not capture image!");
}
else
{
cameraStamp = cameraData.stamp();
}
}
if(_odomSensor && data.stamp() != 0.0)
{
if(lidarStamp!=0.0 && _scanDeskewing)
{
UDEBUG("Deskewing begin");
if(!data.laserScanRaw().empty() && data.laserScanRaw().hasTime())
{
float scanTime =
data.laserScanRaw().data().ptr<float>(0, data.laserScanRaw().size()-1)[data.laserScanRaw().getTimeOffset()] -
data.laserScanRaw().data().ptr<float>(0, 0)[data.laserScanRaw().getTimeOffset()];
Transform poseFirstScan;
Transform poseLastScan;
cv::Mat cov;
double firstStamp = data.stamp() + data.laserScanRaw().data().ptr<float>(0, 0)[data.laserScanRaw().getTimeOffset()];
double lastStamp = data.stamp() + data.laserScanRaw().data().ptr<float>(0, data.laserScanRaw().size()-1)[data.laserScanRaw().getTimeOffset()];
if(_odomSensor->getPose(firstStamp+_poseTimeOffset, poseFirstScan, cov, _poseWaitTime>0?_poseWaitTime:0) &&
_odomSensor->getPose(lastStamp+_poseTimeOffset, poseLastScan, cov, _poseWaitTime>0?_poseWaitTime:0))
{
if(_poseScaleFactor>0 && _poseScaleFactor!=1.0f)
{
poseFirstScan.x() *= _poseScaleFactor;
poseFirstScan.y() *= _poseScaleFactor;
poseFirstScan.z() *= _poseScaleFactor;
poseLastScan.x() *= _poseScaleFactor;
poseLastScan.y() *= _poseScaleFactor;
poseLastScan.z() *= _poseScaleFactor;
}
UASSERT(!poseFirstScan.isNull() && !poseLastScan.isNull());
Transform transform = poseFirstScan.inverse() * poseLastScan;
// convert to velocity
float x,y,z,roll,pitch,yaw;
transform.getTranslationAndEulerAngles(x, y, z, roll, pitch, yaw);
x/=scanTime;
y/=scanTime;
z/=scanTime;
roll /= scanTime;
pitch /= scanTime;
yaw /= scanTime;
Transform velocity(x,y,z,roll,pitch,yaw);
UTimer timeDeskewing;
LaserScan scanDeskewed = util3d::deskew(data.laserScanRaw(), data.stamp(), velocity);
info.timeDeskewing = timeDeskewing.ticks();
if(!scanDeskewed.isEmpty())
{
data.setLaserScan(scanDeskewed);
}
}
else if(!data.laserScanRaw().empty())
{
UWARN("Failed to get poses for stamps %f and %f! Lidar won't be deskewed!", firstStamp+_poseTimeOffset, lastStamp+_poseTimeOffset);
}
}
else if(!data.laserScanRaw().empty())
{
UWARN("The input scan doesn't have time channel (scan format received=%s)!. Lidar won't be deskewed!", data.laserScanRaw().formatName().c_str());
}
UDEBUG("Deskewing end");
}
Transform pose; Transform pose;
Transform poseToLeftCam;
cv::Mat covariance; cv::Mat covariance;
if(!info.odomPose.isNull() && _lidar == 0 && _odomSensor == _camera) if(_odomSensor->getPose(data.stamp()+_poseTimeOffset, pose, covariance))
{
// Do nothing, we have already the pose
}
else if(_odomSensor->getPose(data.stamp()+_poseTimeOffset, pose, covariance, _poseWaitTime>0?_poseWaitTime:0))
{ {
info.odomPose = pose; info.odomPose = pose;
info.odomCovariance = covariance; info.odomCovariance = covariance;
@@ -476,48 +316,22 @@ void SensorCaptureThread::mainLoop()
info.odomPose.y() *= _poseScaleFactor; info.odomPose.y() *= _poseScaleFactor;
info.odomPose.z() *= _poseScaleFactor; info.odomPose.z() *= _poseScaleFactor;
} }
if(cameraStamp != 0.0)
{
Transform cameraCorrection = Transform::getIdentity();
if(lidarStamp > 0.0 && lidarStamp != cameraStamp)
{
if(_odomSensor->getPose(cameraStamp+_poseTimeOffset, pose, covariance, _poseWaitTime>0?_poseWaitTime:0))
{
cameraCorrection = info.odomPose.inverse() * pose;
}
else
{
UWARN("Could not get pose at stamp %f, the camera local motion against lidar won't be adjusted.", cameraStamp);
}
}
// Adjust local transform of the camera based on the pose frame // Adjust local transform of the camera based on the pose frame
if(!data.cameraModels().empty()) if(!data.cameraModels().empty())
{ {
UASSERT(data.cameraModels().size()==1); UASSERT(data.cameraModels().size()==1);
CameraModel model = data.cameraModels()[0]; CameraModel model = data.cameraModels()[0];
model.setLocalTransform(cameraCorrection*_extrinsicsOdomToCamera); model.setLocalTransform(_extrinsicsOdomToCamera);
data.setCameraModel(model); data.setCameraModel(model);
} }
else if(!data.stereoCameraModels().empty()) else if(!data.stereoCameraModels().empty())
{ {
UASSERT(data.stereoCameraModels().size()==1); UASSERT(data.stereoCameraModels().size()==1);
StereoCameraModel model = data.stereoCameraModels()[0]; StereoCameraModel model = data.stereoCameraModels()[0];
model.setLocalTransform(cameraCorrection*_extrinsicsOdomToCamera); model.setLocalTransform(_extrinsicsOdomToCamera);
data.setStereoCameraModel(model); data.setStereoCameraModel(model);
} }
} }
// Fake IMU to intialize gravity (assuming pose is aligned with gravity!)
Eigen::Quaterniond q = info.odomPose.getQuaterniond();
data.setIMU(IMU(
cv::Vec4d(q.x(), q.y(), q.z(), q.w()), cv::Mat(),
cv::Vec3d(), cv::Mat(),
cv::Vec3d(), cv::Mat(),
Transform::getIdentity()));
this->disableIMUFiltering();
}
else else
{ {
UWARN("Could not get pose at stamp %f", data.stamp()); UWARN("Could not get pose at stamp %f", data.stamp());
@@ -533,19 +347,19 @@ void SensorCaptureThread::mainLoop()
if(!data.imageRaw().empty() || !data.laserScanRaw().empty() || (dynamic_cast<DBReader*>(_camera) != 0 && data.id()>0)) // intermediate nodes could not have image set if(!data.imageRaw().empty() || !data.laserScanRaw().empty() || (dynamic_cast<DBReader*>(_camera) != 0 && data.id()>0)) // intermediate nodes could not have image set
{ {
postUpdate(&data, &info); postUpdate(&data, &info);
info.cameraName = _lidar?_lidar->getSerial():_camera->getSerial(); info.cameraName = _camera->getSerial();
info.timeTotal = totalTime.ticks(); info.timeTotal = totalTime.ticks();
this->post(new SensorEvent(data, info)); this->post(new CameraEvent(data, info));
} }
else if(!this->isKilled()) else if(!this->isKilled())
{ {
UWARN("no more data..."); UWARN("no more images...");
this->kill(); this->kill();
this->post(new SensorEvent()); this->post(new CameraEvent());
} }
} }
void SensorCaptureThread::mainLoopKill() void CameraThread::mainLoopKill()
{ {
if(dynamic_cast<CameraFreenect2*>(_camera) != 0) if(dynamic_cast<CameraFreenect2*>(_camera) != 0)
{ {
@@ -570,7 +384,7 @@ void SensorCaptureThread::mainLoopKill()
} }
} }
void SensorCaptureThread::postUpdate(SensorData * dataPtr, SensorCaptureInfo * info) const void CameraThread::postUpdate(SensorData * dataPtr, CameraInfo * info) const
{ {
UASSERT(dataPtr!=0); UASSERT(dataPtr!=0);
SensorData & data = *dataPtr; SensorData & data = *dataPtr;
+1 -1
View File
@@ -6728,7 +6728,7 @@ void DBDriverSqlite3::stepGlobalDescriptor(sqlite3_stmt * ppStmt,
//data //data
std::vector<unsigned char> dataBytes = rtabmap::compressData(descriptor.data()); std::vector<unsigned char> dataBytes = rtabmap::compressData(descriptor.data());
if(dataBytes.empty()) if(infoBytes.empty())
{ {
rc = sqlite3_bind_null(ppStmt, index++); rc = sqlite3_bind_null(ppStmt, index++);
} }
+3 -9
View File
@@ -25,7 +25,6 @@ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/ */
#include <rtabmap/core/SensorEvent.h>
#include "rtabmap/core/DBReader.h" #include "rtabmap/core/DBReader.h"
#include "rtabmap/core/DBDriver.h" #include "rtabmap/core/DBDriver.h"
@@ -35,6 +34,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <rtabmap/utilite/UConversion.h> #include <rtabmap/utilite/UConversion.h>
#include <rtabmap/utilite/UEventsManager.h> #include <rtabmap/utilite/UEventsManager.h>
#include "rtabmap/core/CameraEvent.h"
#include "rtabmap/core/RtabmapEvent.h" #include "rtabmap/core/RtabmapEvent.h"
#include "rtabmap/core/OdometryEvent.h" #include "rtabmap/core/OdometryEvent.h"
#include "rtabmap/core/util3d.h" #include "rtabmap/core/util3d.h"
@@ -268,13 +268,7 @@ std::string DBReader::getSerial() const
return "DBReader"; return "DBReader";
} }
bool DBReader::getPose(double stamp, Transform & pose, cv::Mat & covariance, double maxWaitTime) SensorData DBReader::captureImage(CameraInfo * info)
{
UERROR("DBReader only provides pose when capturing data, it cannot provide asynchronous pose.");
return false;
}
SensorData DBReader::captureImage(SensorCaptureInfo * info)
{ {
SensorData data = this->getNextData(info); SensorData data = this->getNextData(info);
if(data.id()>0 && _stopId>0 && data.id() > _stopId) if(data.id()>0 && _stopId>0 && data.id() > _stopId)
@@ -376,7 +370,7 @@ SensorData DBReader::captureImage(SensorCaptureInfo * info)
return data; return data;
} }
SensorData DBReader::getNextData(SensorCaptureInfo * info) SensorData DBReader::getNextData(CameraInfo * info)
{ {
SensorData data; SensorData data;
if(_dbDriver) if(_dbDriver)
+19 -77
View File
@@ -268,67 +268,25 @@ void Feature2D::filterKeypointsByDisparity(
} }
} }
void Feature2D::limitKeypoints(std::vector<cv::KeyPoint> & keypoints, int maxKeypoints, const cv::Size & imageSize, bool ssc) void Feature2D::limitKeypoints(std::vector<cv::KeyPoint> & keypoints, int maxKeypoints)
{ {
cv::Mat descriptors; cv::Mat descriptors;
limitKeypoints(keypoints, descriptors, maxKeypoints, imageSize, ssc); limitKeypoints(keypoints, descriptors, maxKeypoints);
} }
void Feature2D::limitKeypoints(std::vector<cv::KeyPoint> & keypoints, cv::Mat & descriptors, int maxKeypoints, const cv::Size & imageSize, bool ssc) void Feature2D::limitKeypoints(std::vector<cv::KeyPoint> & keypoints, cv::Mat & descriptors, int maxKeypoints)
{ {
std::vector<cv::Point3f> keypoints3D; std::vector<cv::Point3f> keypoints3D;
limitKeypoints(keypoints, keypoints3D, descriptors, maxKeypoints, imageSize, ssc); limitKeypoints(keypoints, keypoints3D, descriptors, maxKeypoints);
} }
void Feature2D::limitKeypoints(std::vector<cv::KeyPoint> & keypoints, std::vector<cv::Point3f> & keypoints3D, cv::Mat & descriptors, int maxKeypoints, const cv::Size & imageSize, bool ssc) void Feature2D::limitKeypoints(std::vector<cv::KeyPoint> & keypoints, std::vector<cv::Point3f> & keypoints3D, cv::Mat & descriptors, int maxKeypoints)
{ {
UASSERT_MSG((int)keypoints.size() == descriptors.rows || descriptors.rows == 0, uFormat("keypoints=%d descriptors=%d", (int)keypoints.size(), descriptors.rows).c_str()); UASSERT_MSG((int)keypoints.size() == descriptors.rows || descriptors.rows == 0, uFormat("keypoints=%d descriptors=%d", (int)keypoints.size(), descriptors.rows).c_str());
UASSERT_MSG(keypoints.size() == keypoints3D.size() || keypoints3D.size() == 0, uFormat("keypoints=%d keypoints3D=%d", (int)keypoints.size(), (int)keypoints3D.size()).c_str()); UASSERT_MSG(keypoints.size() == keypoints3D.size() || keypoints3D.size() == 0, uFormat("keypoints=%d keypoints3D=%d", (int)keypoints.size(), (int)keypoints3D.size()).c_str());
if(maxKeypoints > 0 && (int)keypoints.size() > maxKeypoints) if(maxKeypoints > 0 && (int)keypoints.size() > maxKeypoints)
{ {
UTimer timer; UTimer timer;
int removed;
std::vector<cv::KeyPoint> kptsTmp;
std::vector<cv::Point3f> kpts3DTmp;
cv::Mat descriptorsTmp;
if(ssc)
{
ULOGGER_DEBUG("too much words (%d), removing words with SSC", keypoints.size());
static constexpr float tolerance = 0.1;
auto ResultVec = util2d::SSC(keypoints, maxKeypoints, tolerance, imageSize.width, imageSize.height);
removed = keypoints.size()-ResultVec.size();
// retrieve final keypoints
kptsTmp.resize(ResultVec.size());
if(!keypoints3D.empty())
{
kpts3DTmp.resize(ResultVec.size());
}
if(descriptors.rows)
{
descriptorsTmp = cv::Mat(ResultVec.size(), descriptors.cols, descriptors.type());
}
for(unsigned int k=0; k<ResultVec.size(); ++k)
{
kptsTmp[k] = keypoints[ResultVec[k]];
if(keypoints3D.size())
{
kpts3DTmp[k] = keypoints3D[ResultVec[k]];
}
if(descriptors.rows)
{
if(descriptors.type() == CV_32FC1)
{
memcpy(descriptorsTmp.ptr<float>(k), descriptors.ptr<float>(ResultVec[k]), descriptors.cols*sizeof(float));
}
else
{
memcpy(descriptorsTmp.ptr<char>(k), descriptors.ptr<char>(ResultVec[k]), descriptors.cols*sizeof(char));
}
}
}
}
else
{
ULOGGER_DEBUG("too much words (%d), removing words with the hessian threshold", keypoints.size()); ULOGGER_DEBUG("too much words (%d), removing words with the hessian threshold", keypoints.size());
// Remove words under the new hessian threshold // Remove words under the new hessian threshold
@@ -341,13 +299,15 @@ void Feature2D::limitKeypoints(std::vector<cv::KeyPoint> & keypoints, std::vecto
} }
// Remove them from the signature // Remove them from the signature
removed = (int)hessianMap.size()-maxKeypoints; int removed = (int)hessianMap.size()-maxKeypoints;
std::multimap<float, int>::reverse_iterator iter = hessianMap.rbegin(); std::multimap<float, int>::reverse_iterator iter = hessianMap.rbegin();
kptsTmp.resize(maxKeypoints); std::vector<cv::KeyPoint> kptsTmp(maxKeypoints);
std::vector<cv::Point3f> kpts3DTmp;
if(!keypoints3D.empty()) if(!keypoints3D.empty())
{ {
kpts3DTmp.resize(maxKeypoints); kpts3DTmp.resize(maxKeypoints);
} }
cv::Mat descriptorsTmp;
if(descriptors.rows) if(descriptors.rows)
{ {
descriptorsTmp = cv::Mat(maxKeypoints, descriptors.cols, descriptors.type()); descriptorsTmp = cv::Mat(maxKeypoints, descriptors.cols, descriptors.type());
@@ -371,8 +331,7 @@ void Feature2D::limitKeypoints(std::vector<cv::KeyPoint> & keypoints, std::vecto
} }
} }
} }
} ULOGGER_DEBUG("%d keypoints removed, (kept %d), minimum response=%f", removed, (int)kptsTmp.size(), kptsTmp.size()?kptsTmp.back().response:0.0f);
ULOGGER_DEBUG("%d keypoints removed, (kept %d), minimum response=%f", removed, (int)kptsTmp.size(), !ssc&&kptsTmp.size()?kptsTmp.back().response:0.0f);
ULOGGER_DEBUG("removing words time = %f s", timer.ticks()); ULOGGER_DEBUG("removing words time = %f s", timer.ticks());
keypoints = kptsTmp; keypoints = kptsTmp;
keypoints3D = kpts3DTmp; keypoints3D = kpts3DTmp;
@@ -383,28 +342,12 @@ void Feature2D::limitKeypoints(std::vector<cv::KeyPoint> & keypoints, std::vecto
} }
} }
void Feature2D::limitKeypoints(const std::vector<cv::KeyPoint> & keypoints, std::vector<bool> & inliers, int maxKeypoints, const cv::Size & imageSize, bool ssc) void Feature2D::limitKeypoints(const std::vector<cv::KeyPoint> & keypoints, std::vector<bool> & inliers, int maxKeypoints)
{ {
if(maxKeypoints > 0 && (int)keypoints.size() > maxKeypoints) if(maxKeypoints > 0 && (int)keypoints.size() > maxKeypoints)
{ {
UTimer timer; UTimer timer;
float minimumHessian = 0.0f; ULOGGER_DEBUG("too much words (%d), removing words with the hessian threshold", (int)keypoints.size());
int removed;
inliers.resize(keypoints.size(), false);
if(ssc)
{
ULOGGER_DEBUG("too much words (%d), removing words with SSC", keypoints.size());
static constexpr float tolerance = 0.1;
auto ResultVec = util2d::SSC(keypoints, maxKeypoints, tolerance, imageSize.width, imageSize.height);
removed = keypoints.size()-ResultVec.size();
for(unsigned int k=0; k<ResultVec.size(); ++k)
{
inliers[ResultVec[k]] = true;
}
}
else
{
ULOGGER_DEBUG("too much words (%d), removing words with the hessian threshold", keypoints.size());
// Remove words under the new hessian threshold // Remove words under the new hessian threshold
// Sort words by hessian // Sort words by hessian
@@ -416,14 +359,15 @@ void Feature2D::limitKeypoints(const std::vector<cv::KeyPoint> & keypoints, std:
} }
// Keep keypoints with highest response // Keep keypoints with highest response
removed = (int)hessianMap.size()-maxKeypoints; int removed = (int)hessianMap.size()-maxKeypoints;
std::multimap<float, int>::reverse_iterator iter = hessianMap.rbegin(); std::multimap<float, int>::reverse_iterator iter = hessianMap.rbegin();
inliers.resize(keypoints.size(), false);
float minimumHessian = 0.0f;
for(int k=0; k < maxKeypoints && iter!=hessianMap.rend(); ++k, ++iter) for(int k=0; k < maxKeypoints && iter!=hessianMap.rend(); ++k, ++iter)
{ {
inliers[iter->second] = true; inliers[iter->second] = true;
minimumHessian = iter->first; minimumHessian = iter->first;
} }
}
ULOGGER_DEBUG("%d keypoints removed, (kept %d), minimum response=%f", removed, maxKeypoints, minimumHessian); ULOGGER_DEBUG("%d keypoints removed, (kept %d), minimum response=%f", removed, maxKeypoints, minimumHessian);
ULOGGER_DEBUG("filter keypoints time = %f s", timer.ticks()); ULOGGER_DEBUG("filter keypoints time = %f s", timer.ticks());
} }
@@ -434,7 +378,7 @@ void Feature2D::limitKeypoints(const std::vector<cv::KeyPoint> & keypoints, std:
} }
} }
void Feature2D::limitKeypoints(const std::vector<cv::KeyPoint> & keypoints, std::vector<bool> & inliers, int maxKeypoints, const cv::Size & imageSize, int gridRows, int gridCols, bool ssc) void Feature2D::limitKeypoints(const std::vector<cv::KeyPoint> & keypoints, std::vector<bool> & inliers, int maxKeypoints, const cv::Size & imageSize, int gridRows, int gridCols)
{ {
if(maxKeypoints <= 0 || (int)keypoints.size() <= maxKeypoints) if(maxKeypoints <= 0 || (int)keypoints.size() <= maxKeypoints)
{ {
@@ -462,7 +406,7 @@ void Feature2D::limitKeypoints(const std::vector<cv::KeyPoint> & keypoints, std:
for(size_t i=0; i<keypointsPerCell.size(); ++i) for(size_t i=0; i<keypointsPerCell.size(); ++i)
{ {
std::vector<bool> inliersCell; std::vector<bool> inliersCell;
limitKeypoints(keypointsPerCell[i], inliersCell, maxKeypointsPerCell, cv::Size(colSize, rowSize), ssc); limitKeypoints(keypointsPerCell[i], inliersCell, maxKeypointsPerCell);
for(size_t j=0; j<inliersCell.size(); ++j) for(size_t j=0; j<inliersCell.size(); ++j)
{ {
if(inliersCell[j]) if(inliersCell[j])
@@ -488,7 +432,6 @@ cv::Rect Feature2D::computeRoi(const cv::Mat & image, const std::vector<float> &
///////////////////// /////////////////////
Feature2D::Feature2D(const ParametersMap & parameters) : Feature2D::Feature2D(const ParametersMap & parameters) :
maxFeatures_(Parameters::defaultKpMaxFeatures()), maxFeatures_(Parameters::defaultKpMaxFeatures()),
SSC_(Parameters::defaultKpSSC()),
_maxDepth(Parameters::defaultKpMaxDepth()), _maxDepth(Parameters::defaultKpMaxDepth()),
_minDepth(Parameters::defaultKpMinDepth()), _minDepth(Parameters::defaultKpMinDepth()),
_roiRatios(std::vector<float>(4, 0.0f)), _roiRatios(std::vector<float>(4, 0.0f)),
@@ -510,7 +453,6 @@ void Feature2D::parseParameters(const ParametersMap & parameters)
uInsert(parameters_, parameters); uInsert(parameters_, parameters);
Parameters::parse(parameters, Parameters::kKpMaxFeatures(), maxFeatures_); Parameters::parse(parameters, Parameters::kKpMaxFeatures(), maxFeatures_);
Parameters::parse(parameters, Parameters::kKpSSC(), SSC_);
Parameters::parse(parameters, Parameters::kKpMaxDepth(), _maxDepth); Parameters::parse(parameters, Parameters::kKpMaxDepth(), _maxDepth);
Parameters::parse(parameters, Parameters::kKpMinDepth(), _minDepth); Parameters::parse(parameters, Parameters::kKpMinDepth(), _minDepth);
Parameters::parse(parameters, Parameters::kKpSubPixWinSize(), _subPixWinSize); Parameters::parse(parameters, Parameters::kKpSubPixWinSize(), _subPixWinSize);
@@ -794,7 +736,7 @@ std::vector<cv::KeyPoint> Feature2D::generateKeypoints(const cv::Mat & image, co
subKeypoints = this->generateKeypointsImpl(image, roi, mask); subKeypoints = this->generateKeypointsImpl(image, roi, mask);
if (this->getType() != Feature2D::Type::kFeaturePyDetector) if (this->getType() != Feature2D::Type::kFeaturePyDetector)
{ {
limitKeypoints(subKeypoints, maxFeatures, roi.size(), this->getSSC()); limitKeypoints(subKeypoints, maxFeatures);
} }
if(roi.x || roi.y) if(roi.x || roi.y)
{ {
@@ -2200,7 +2142,7 @@ std::vector<cv::KeyPoint> ORBOctree::generateKeypointsImpl(const cv::Mat & image
if((int)keypoints.size() > this->getMaxFeatures()) if((int)keypoints.size() > this->getMaxFeatures())
{ {
limitKeypoints(keypoints, descriptors_, this->getMaxFeatures(), roi.size(), this->getSSC()); limitKeypoints(keypoints, descriptors_, this->getMaxFeatures());
} }
#else #else
UWARN("RTAB-Map is not built with ORB OcTree option enabled so ORB OcTree feature cannot be used!"); UWARN("RTAB-Map is not built with ORB OcTree option enabled so ORB OcTree feature cannot be used!");
-76
View File
@@ -1,76 +0,0 @@
/*
Copyright (c) 2010-2024, Mathieu Labbe - IntRoLab - Universite de Sherbrooke
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Universite de Sherbrooke nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "rtabmap/core/GlobalDescriptorExtractor.h"
#ifdef RTABMAP_PYTHON
#include "python/PyDescriptor.h"
#endif
namespace rtabmap {
GlobalDescriptorExtractor::GlobalDescriptorExtractor(const ParametersMap & parameters)
{
}
GlobalDescriptorExtractor::~GlobalDescriptorExtractor()
{
}
GlobalDescriptorExtractor * GlobalDescriptorExtractor::create(const ParametersMap & parameters)
{
int type = Parameters::defaultMemGlobalDescriptorStrategy();
Parameters::parse(parameters, Parameters::kMemGlobalDescriptorStrategy(), type);
return create((GlobalDescriptorExtractor::Type)type, parameters);
}
GlobalDescriptorExtractor * GlobalDescriptorExtractor::create(GlobalDescriptorExtractor::Type type, const ParametersMap & parameters)
{
UDEBUG("Creating global descriptor of type %d", (int)type);
#ifndef RTABMAP_PYTHON
if(type == GlobalDescriptorExtractor::kPyDescriptor)
{
UWARN("PyDescriptor cannot be used as rtabmap is not built with Python3 support.");
type = GlobalDescriptorExtractor::kUndef;
}
#endif
GlobalDescriptorExtractor * GlobalDescriptorExtractor = 0;
switch(type)
{
#ifdef RTABMAP_PYTHON
case GlobalDescriptorExtractor::kPyDescriptor:
GlobalDescriptorExtractor = new PyDescriptor(parameters);
break;
#endif
default:
type = GlobalDescriptorExtractor::kUndef;
break;
}
return GlobalDescriptorExtractor;
}
}
+1 -1
View File
@@ -121,7 +121,7 @@ bool GlobalMap::update(const std::map<int, Transform> & poses)
} }
else else
{ {
UDEBUG("Updated pose for node %d is not found, some points may not be copied. Use negative ids to just update cell values without adding new ones.", iter->first); UDEBUG("Updated pose for node %d is not found, some points may not be copied. Use negative ids to just update cell values without adding new ones.", jter->first);
} }
} }

Some files were not shown because too many files have changed in this diff Show More