Merge branch 'mo_new'

This commit is contained in:
2026-06-11 14:55:45 +08:00
119 changed files with 10270 additions and 194 deletions

13
.gitignore vendored
View File

@@ -1,5 +1,12 @@
log
# Build artifacts
build
install
src/ground_slam
# Install artifacts
install
# Log artifacts
log
# VSCode database
.vscode/browse.vc.db*

View File

@@ -11,12 +11,8 @@
"/home/sunrise/yiliao_ws/install/lslidar_msgs/include/**",
"/opt/ros/humble/include/**",
"/home/sunrise/yiliao_ws/src/LSLIDAR_X_ROS2-20240228/src/lslidar_driver/include/**",
"/home/sunrise/yiliao_ws/src/cyy_navigation2/include/**",
"/home/sunrise/yiliao_ws/src/cyy_slamtoolbox/include/**",
"/home/sunrise/yiliao_ws/src/gc_navigation_fish/include/**",
"/home/sunrise/yiliao_ws/src/gc_slam_toolbox_fish/include/**",
"/home/sunrise/yiliao_ws/src/ground_slam/include/**",
"/home/sunrise/yiliao_ws/src/origincar_base/include/**",
"/home/sunrise/yiliao_ws/src/zbw_slamtoolbox/include/**",
"/usr/include/**"
],
"name": "ros2",

View File

@@ -1,5 +1,7 @@
{
"cmake.ignoreCMakeListsMissing": true,
"yaml.schemas": {
"https://www.schemastore.org/package.json": "file:///home/guoch/test_ws/src/gc_navigation2_slamtoolbox/config/mapper_params_localization.yaml"
},
"ROS2.distro": "humble",
"python.autoComplete.extraPaths": [
"/home/sunrise/yiliao_ws/install/origincar_base/local/lib/python3.10/dist-packages",

165
CLAUDE.md Normal file
View File

@@ -0,0 +1,165 @@
# CLAUDE.md
## 项目概述
这是一个 ROS 2 Humble 工作空间,用于 Ackermann 转向小车的 Gazebo 仿真、SLAM 建图和 Nav2 导航。同时支持实车部署(无 Gazebo
## 工作空间结构
```
test_ws/
├── src/
│ ├── gc_navigation2_slamtoolbox/ # 仿真版:导航+SLAM 启动文件和配置
│ │ ├── launch/ # Python launch 文件
│ │ ├── config/ # slam_toolbox 参数
│ │ ├── params/ # Nav2 参数
│ │ ├── maps/ # 地图文件 (.pgm, .yaml, .posegraph)
│ │ └── world/ # Gazebo 模型 (zhihui/)
│ ├── gc_navigation2_real/ # 实车版:导航+SLAM 启动文件和配置(无 Gazebo
│ │ ├── launch/ # Python launch 文件
│ │ ├── config/ # slam_toolbox 参数(实车调优)
│ │ ├── params/ # Nav2 参数use_sim_time=false
│ │ ├── maps/ # 实车地图存放目录
│ │ └── behavior_tree/ # 阿克曼自定义行为树
│ ├── origincar_description/ # 机器人 URDF 和 Gazebo world
│ │ ├── urdf/ # origincar.urdf
│ │ ├── world/ # .world 文件
│ │ ├── meshes/ # 3D 模型
│ │ ├── launch/ # display.launch.py
│ │ └── rviz/ # RViz 配置
│ ├── origincar_base/ # 实车底盘驱动(串口通信+EKF+IMU融合
│ │ ├── src/ # C++ 源码origincar_base.cpp
│ │ ├── scripts/ # cmd_vel_to_ackermann_drive.py
│ │ ├── launch/ # origincar_bringup / base_serial / ekf
│ │ └── config/ # ekf.yaml / imu.yaml
│ ├── origincar_msg/ # 自定义 ROS 2 消息
│ │ └── msg/ # Data.msg / Sign.msg
│ └── LSLIDAR_X_ROS2-20240228/ # 镭神激光雷达 ROS 2 驱动
│ └── src/
│ ├── lslidar_driver/ # 雷达驱动核心
│ └── lslidar_msgs/ # 雷达消息定义
├── build/ # colcon build 输出
├── install/ # colcon install 输出 (含符号链接)
└── log/ # 构建日志
```
## 构建命令
```bash
cd /home/guoch/test_ws
source /opt/ros/humble/setup.bash
colcon build --symlink-install
source install/setup.bash
```
## 常用 Launch 文件
### 仿真版 (gc_navigation2_slamtoolbox)
| 文件 | 功能 |
|------|------|
| `gc_slam_mapping.launch.py` | Gazebo + SLAM 建图模式 |
| `gc_nav2_with_slam_online.launch.py` | 已知地图 + SLAM 在线更新 + Nav2 导航 |
| `gc_nav2_with_slam.launch.py` | 已知地图 + SLAM 定位 + Nav2 导航 |
| `gc_nav2_with_amcl.launch.py` | AMCL 定位 + Nav2 导航 |
### 实车版 (gc_navigation2_real)
| 文件 | 功能 |
|------|------|
| `real_bringup.launch.py` | 基础 bringup底盘驱动+雷达+TF无导航 |
| `real_slam_mapping.launch.py` | 实车 SLAM 建图模式 |
| `real_nav2_slam.launch.py` | 已知地图 + SLAM 定位 + Nav2 导航 |
| `real_nav2_slam_online.launch.py` | 已知地图 + SLAM 在线更新 + Nav2 导航 |
## 机器人参数 (origincar)
- **类型**: Ackermann 转向小车
- **尺寸**: 0.276 × 0.214 × 0.211 m (长×宽×高)
- **轴距**: 0.143 mURDF 中前轮 x=0.0715,后轮 x=-0.0715**轮距**: 0.189 m
- **轮子**: 半径 0.03 m厚 0.025 m
- **激光雷达**: 360°, 0.12~3.5 m, 5 Hz仿真; 镭神 N10 0.15~12m实车
- **IMU**: 100 Hz, 含高斯噪声
- **Gazebo 插件**: `gazebo_ros_ackermann_drive`, `gazebo_ros_ray_sensor`, `gazebo_ros_imu_sensor`
## 实车 TF 树
```
map ──→ odom_combined ──→ base_footprint ──→ base_link ──→ laser
↑ ↑ ↑ ↑
slam_toolbox EKF static TF URDF/static
(定位) (融合odom+IMU) (origincar_bringup)
```
- slam_toolbox 发布 `map → odom_combined`
- EKF 发布 `odom_combined → base_footprint`
- origincar_bringup 发布 `base_footprint → base_link`z=0`base_link → laser`
- robot_state_publisher 发布 URDF 各连杆 TF
### 仿真 vs 实车关键差异
| 方面 | 仿真版 | 实车版 |
|------|--------|--------|
| use_sim_time | `true` | `false` |
| odom_frame | `odom` | `odom_combined`EKF 融合后) |
| 底盘驱动 | Gazebo plugin | origincar_base 串口驱动 |
| 激光雷达 | Gazebo ray plugin | lslidar_driver镭神 N10 |
| robot_state_publisher | launch 文件内启动 | origincar_bringup 已包含,勿重复启动 |
| joint_state_publisher | launch 文件内启动 | origincar_bringup 已包含,勿重复启动 |
## 阿克曼底盘模式
通过 `akmcar` 参数控制,链路如下:
```
origincar_bringup.launch.py
└─ akmcar=LaunchConfiguration('akmcar', default='true')
└─ 传入 base_serial.launch.py
├─ IfCondition(true) → origincar_base_node (akm_cmd_vel='ackermann_cmd')
│ + cmd_vel_to_ackermann_drive.py (Twist→Ackermann)
└─ UnlessCondition(false) → 差速模式(跳过)
```
数据流:`MPPI cmd_vel(Twist) → cmd_vel_to_ackermann_drive.py → ackermann_cmd(AckermannDriveStamped) → STM32`
关键参数:
- `cmd_vel_to_ackermann_drive.py`: `wheelbase = 0.143`(与 URDF 一致)
- `akmcar=true` 时 STM32 接收 `speed + steering_angle`
- `akmcar=false` 时 STM32 接收 `vx + vy + wz`(固件自行转换)
## 关键设计
1. **map_server** 提供全量静态底图(`/map`
2. **slam_toolbox** 负责定位和增量建图,重映射 `/map``/slam_map` 避免冲突
3. **Nav2** 使用 `global_costmap/static_layer ← /map` + `local_costmap/obstacle_layer ← /scan`
4. 保存地图: `ros2 service call /slam_toolbox/serialize_map ...`
5. 实车版 launch 文件**不应**自行启动 `robot_state_publisher``joint_state_publisher``origincar_bringup` 已包含
## 地图文件
地图放在 `src/gc_navigation2_slamtoolbox/maps/`(仿真)和 `src/gc_navigation2_real/maps/`(实车),包含:
- `xxx.pgm` — 地图图像
- `xxx.yaml` — 地图元数据 (resolution, origin, thresholds)
- `xxx.posegraph` — 序列化的位姿图
## Gazebo World
World 文件在 `src/origincar_description/world/`:
- `zhihui.world` — 智慧楼墙体环境(内联模型)
- `test.world` — 测试环境
- `fishbot.world` / `gc_world.world` — 其他场景
## 实车底盘驱动包 (origincar_base)
- `origincar_base_node`C++: 串口读写(/dev/ttyACM0, 115200bps、航迹推算、四元数姿态解算Mahony AHRS
- `cmd_vel_to_ackermann_drive.py`Python: Twist → AckermannDriveStamped 转换wheelbase=0.143
- 帧协议: 24 字节收帧头0x7B/帧尾0x7D/ 11 字节发
- EKF 融合: `/odom` + IMU → `/odom_combined``two_d_mode=true`
## 注意事项
- 使用 `--symlink-install` 构建Python launch 文件修改后无需重新编译
- `.world` 文件不应使用 `model://` 外部引用,应将模型内联定义
- `robot_base_frame` 在 ackermann plugin 中应设为 `base_footprint`
- 实车 `gc_navigation2_real` 的 launch 文件调用 `origincar_bringup.launch.py` 时,不再重复启动 `robot_state_publisher``joint_state_publisher`
- 轴距参数在三处需保持一致URDF0.143m)、`cmd_vel_to_ackermann_drive.py`0.143m、Nav2 planner `minimum_turning_radius`0.40m

View File

@@ -82,7 +82,21 @@
---
<br></br>
<<<<<<< HEAD
# 三、其它说明
=======
# 三、指令
启动雷达:
`ros2 launch lslidar_driver lsn10_launch.py `
open new terminal
```bash
ros2 topic pub -1 /lslidar_order std_msgs/msg/Int8 data:\ 1\ # (open radar)
ros2 topic pub -1 /lslidar_order std_msgs/msg/Int8 data:\ 0\ # (close radar)
```
# 四、其它说明
>>>>>>> mo_new
我设置了一些自定义指令,方便终端调试:
```bash
rosbuild <package_name> # 编译指定包
@@ -90,3 +104,7 @@ build_debug <package_name> # 以调试模式编译指定包
foxglove # 启动foxbridge
```
<<<<<<< HEAD
=======
# 五、日志
>>>>>>> mo_new

View File

@@ -0,0 +1,23 @@
cmake_minimum_required(VERSION 3.8)
project(gc_navigation2_real)
if(CMAKE_COMPILER_IS_GNUCXX OR CMAKE_CXX_COMPILER_ID MATCHES "Clang")
add_compile_options(-Wall -Wextra -Wpedantic)
endif()
# find dependencies
find_package(ament_cmake REQUIRED)
install(
DIRECTORY launch config params maps behavior_tree
DESTINATION share/${PROJECT_NAME}
)
if(BUILD_TESTING)
find_package(ament_lint_auto REQUIRED)
set(ament_cmake_copyright_FOUND TRUE)
set(ament_cmake_cpplint_FOUND TRUE)
ament_lint_auto_find_test_dependencies()
endif()
ament_package()

View File

@@ -0,0 +1,37 @@
<!--
阿克曼底盘自定义行为树:移除了 Spin原地旋转
恢复行为改为:清除代价地图 → 后退 → 等待
实车版本 — 与仿真版相同逻辑
-->
<root main_tree_to_execute="MainTree">
<BehaviorTree ID="MainTree">
<RecoveryNode number_of_retries="6" name="NavigateRecovery">
<PipelineSequence name="NavigateWithReplanning">
<RateController hz="1.0">
<RecoveryNode number_of_retries="1" name="ComputePathToPose">
<ComputePathToPose goal="{goal}" path="{path}" planner_id="GridBased"/>
<ClearEntireCostmap name="ClearGlobalCostmap-Context" service_name="global_costmap/clear_entirely_global_costmap"/>
</RecoveryNode>
</RateController>
<RecoveryNode number_of_retries="1" name="FollowPath">
<FollowPath path="{path}" controller_id="FollowPath"/>
<ClearEntireCostmap name="ClearLocalCostmap-Context" service_name="local_costmap/clear_entirely_local_costmap"/>
</RecoveryNode>
</PipelineSequence>
<ReactiveFallback name="RecoveryFallback">
<GoalUpdated/>
<RoundRobin name="RecoveryActions">
<!-- 1. 清除代价地图,去掉短暂障碍 -->
<Sequence name="ClearingActions">
<ClearEntireCostmap name="ClearLocalCostmap-Subtree" service_name="local_costmap/clear_entirely_local_costmap"/>
<ClearEntireCostmap name="ClearGlobalCostmap-Subtree" service_name="global_costmap/clear_entirely_global_costmap"/>
</Sequence>
<!-- 2. 快速后退 0.8m,给重新规划留空间(阿克曼无法原地旋转) -->
<BackUp backup_dist="0.80" backup_speed="0.18"/>
<!-- 3. 短暂等待 0.3s,让新路径规划完成 -->
<Wait wait_duration="0.3"/>
</RoundRobin>
</ReactiveFallback>
</RecoveryNode>
</BehaviorTree>
</root>

View File

@@ -0,0 +1,78 @@
slam_toolbox:
ros__parameters:
# ============================ Solver 插件参数 ======================================
solver_plugin: solver_plugins::CeresSolver
ceres_linear_solver: SPARSE_NORMAL_CHOLESKY
ceres_preconditioner: SCHUR_JACOBI
ceres_trust_strategy: LEVENBERG_MARQUARDT
ceres_dogleg_type: TRADITIONAL_DOGLEG
ceres_loss_function: None
# ============================ ROS 基础参数(实车)===================================
odom_frame: odom_combined # 实车EKF 融合后的里程计坐标系
map_frame: map # 地图坐标系
base_frame: base_footprint # 机器人基座坐标系(与 URDF 根帧一致)
scan_topic: /scan # 激光雷达话题(实车镭神雷达)
use_map_saver: true # 启用地图保存功能
mode: mapping # mapping = 定位 + 实时建图
# ============================ 已有地图加载 ==========================================
# map_file_name: "" # 从零开始建图,留空
map_start_pose: [0.0, 0.0, 0.0] # 初始位姿 [x, y, yaw]
# ============================ 调试与性能 ===========================================
debug_logging: false
throttle_scans: 1 # 每 N 帧处理一次实车每秒10帧左右
transform_publish_period: 0.02 # TF 发布周期(秒)
map_update_interval: 3.0 # /map 话题更新间隔(秒)
resolution: 0.05 # 地图分辨率(米/像素)
restamp_tf: false
min_laser_range: 0.15 # 实车雷达盲区约 0.12m,设 0.15 过滤近处噪点
max_laser_range: 12.0 # 实车雷达最大有效距离(镭神 N10 ≈ 10-15m
minimum_time_interval: 0.3 # 最小处理时间间隔(实车可适当放宽)
transform_timeout: 0.2 # TF 查找超时
tf_buffer_duration: 30.0 # TF 缓冲区时长
stack_size_to_use: 40000000 # 栈大小(序列化大地图需要)
enable_interactive_mode: true # 交互模式:允许外部工具编辑地图
# ============================ 通用建图参数 =========================================
use_scan_matching: true
use_scan_barycenter: true
minimum_travel_distance: 0.3 # 实车最小移动距离(米),小于仿真以更频繁更新
minimum_travel_heading: 0.3 # 最小转向角度(弧度)
check_min_dist_and_heading_precisely: false
scan_buffer_size: 10 # 扫描缓冲区大小
scan_buffer_maximum_scan_distance: 10.0
link_match_minimum_response_fine: 0.1
link_scan_maximum_distance: 1.5
# ============================ 回环检测参数 =========================================
do_loop_closing: true # 启用回环检测
loop_match_minimum_chain_size: 10
loop_match_maximum_variance_coarse: 3.0
loop_match_minimum_response_coarse: 0.35
loop_match_minimum_response_fine: 0.45
loop_search_maximum_distance: 3.0
# ============================ 相关性匹配参数 =======================================
correlation_search_space_dimension: 0.5
correlation_search_space_resolution: 0.01
correlation_search_space_smear_deviation: 0.1
loop_search_space_dimension: 8.0
loop_search_space_resolution: 0.05
loop_search_space_smear_deviation: 0.03
# ============================ 扫描匹配器参数 ========================================
distance_variance_penalty: 0.5
angle_variance_penalty: 1.0
fine_search_angle_offset: 0.00349
coarse_search_angle_offset: 0.349
coarse_angle_resolution: 0.0349
minimum_angle_penalty: 0.9
minimum_distance_penalty: 0.5
use_response_expansion: true
min_pass_through: 2
occupancy_threshold: 0.1

View File

@@ -0,0 +1,77 @@
slam_toolbox:
ros__parameters:
# ============================ Solver 插件参数 ======================================
solver_plugin: solver_plugins::CeresSolver
ceres_linear_solver: SPARSE_NORMAL_CHOLESKY
ceres_preconditioner: SCHUR_JACOBI
ceres_trust_strategy: LEVENBERG_MARQUARDT
ceres_dogleg_type: TRADITIONAL_DOGLEG
ceres_loss_function: None
# ============================ ROS 基础参数(实车定位模式)============================
odom_frame: odom_combined # 实车EKF 融合后的里程计坐标系
map_frame: map
base_frame: base_footprint
scan_topic: /scan
mode: localization # 纯定位模式,不更新地图
# ============================ 已有地图加载 ==========================================
# 由 launch 文件通过 map_file_name 参数传入 .posegraph 路径
# map_file_name: ""
map_start_pose: [0.0, 0.0, 0.0]
# ============================ 调试与性能 ===========================================
debug_logging: false
throttle_scans: 2 # 每2帧处理一次实车激光较慢时使用
transform_publish_period: 0.02
map_update_interval: 5.0
resolution: 0.05
restamp_tf: false
min_laser_range: 0.15 # 过滤雷达盲区噪点
max_laser_range: 12.0 # 实车雷达最大有效距离
minimum_time_interval: 0.3
transform_timeout: 0.2
tf_buffer_duration: 30.0
stack_size_to_use: 40000000
# ============================ 通用参数 =============================================
use_scan_matching: true
use_scan_barycenter: true
minimum_travel_distance: 0.3
minimum_travel_heading: 0.3
check_min_dist_and_heading_precisely: false
scan_buffer_size: 10
scan_buffer_maximum_scan_distance: 10.0
link_match_minimum_response_fine: 0.1
link_scan_maximum_distance: 1.5
# 定位模式关闭回环检测
do_loop_closing: false
loop_match_minimum_chain_size: 10
loop_match_maximum_variance_coarse: 3.0
loop_match_minimum_response_coarse: 0.35
loop_match_minimum_response_fine: 0.45
loop_search_maximum_distance: 3.0
# ============================ 相关性匹配参数 =======================================
correlation_search_space_dimension: 0.5
correlation_search_space_resolution: 0.01
correlation_search_space_smear_deviation: 0.1
loop_search_space_dimension: 8.0
loop_search_space_resolution: 0.05
loop_search_space_smear_deviation: 0.03
# ============================ 扫描匹配器参数 ========================================
distance_variance_penalty: 0.5
angle_variance_penalty: 1.0
fine_search_angle_offset: 0.00349
coarse_search_angle_offset: 0.349
coarse_angle_resolution: 0.0349
minimum_angle_penalty: 0.9
minimum_distance_penalty: 0.5
use_response_expansion: true
min_pass_through: 2
occupancy_threshold: 0.1

View File

@@ -0,0 +1,54 @@
#!/usr/bin/env python3
# ============================================================================
# real_bringup.launch.py
# 功能:实车基础 bringup — 底盘驱动 + 激光雷达 + TF 树
#
# 适用场景:
# - 单独调试底盘通信和传感器数据
# - 遥控测试(无导航)
# - 作为其他 launch 文件的基础模块
#
# 启动内容:
# origincar_base bringup — 串口驱动 + EKF + IMU 滤波 + TF + robot_state_publisher
# lslidar_driver — 镭神激光雷达 → /scan
#
# 使用方式:
# ros2 launch gc_navigation2_real real_bringup.launch.py
# ============================================================================
from ament_index_python.packages import get_package_share_directory
from launch import LaunchDescription
from launch.actions import IncludeLaunchDescription, DeclareLaunchArgument
from launch.launch_description_sources import PythonLaunchDescriptionSource
def generate_launch_description():
"""生成 LaunchDescription启动实车底盘 + 雷达 + TF无导航"""
# ============================ 1. 包路径 =========================================
origincar_base_dir = get_package_share_directory('origincar_base')
# ============================ 2. 实车底盘 bringup ===============================
# 注origincar_bringup 已包含 robot_state_publisher + joint_state_publisher + 静态 TF
origincar_bringup = IncludeLaunchDescription(
PythonLaunchDescriptionSource(
[origincar_base_dir, '/launch', '/origincar_bringup.launch.py']),
)
# ============================ 3. 镭神激光雷达驱动 ===============================
lslidar_launch = IncludeLaunchDescription(
PythonLaunchDescriptionSource(
[get_package_share_directory('lslidar_driver'),
'/launch', '/lsn10_launch.py']),
)
# ============================ 4. 组装 LaunchDescription =========================
return LaunchDescription([
DeclareLaunchArgument(
'use_sim_time',
default_value='false',
description='使用仿真时间(实车必须为 false'),
origincar_bringup,
lslidar_launch,
])

View File

@@ -0,0 +1,110 @@
#!/usr/bin/env python3
# ============================================================================
# real_nav2_slam.launch.py
# 功能:实车导航 — 已知静态地图 + SLAM 定位 + Nav2 导航
#
# 架构:
# origincar_base (bringup) — 底盘串口驱动 + EKF 里程计 + IMU 滤波 + TF
# lslidar_driver — 镭神激光雷达驱动 → /scan
# map_server — 加载 yaml+pgm 全量静态地图 → /map
# slam_toolbox (localization) — 加载 .posegraph激光扫描匹配定位
# 发布 map→odom_combined TF替代 AMCL
# ⚠️ /map 话题重映射为 /slam_map避免冲突
# navigation_launch — Nav2 导航栈
# global_costmap 从 /map 获取全量静态地图
#
# 使用方式:
# ros2 launch gc_navigation2_real real_nav2_slam.launch.py
# ============================================================================
import os
from ament_index_python.packages import get_package_share_directory
from launch import LaunchDescription
from launch.actions import IncludeLaunchDescription, DeclareLaunchArgument
from launch.launch_description_sources import PythonLaunchDescriptionSource
from launch.substitutions import LaunchConfiguration
from launch_ros.actions import Node
def generate_launch_description():
"""生成 LaunchDescription启动实车底盘 + 雷达 + SLAM定位 + Nav2 导航"""
ld = LaunchDescription()
# =============================1. 包路径===========================================
pkg_dir = get_package_share_directory('gc_navigation2_real')
nav2_bringup_dir = get_package_share_directory('nav2_bringup')
origincar_base_dir = get_package_share_directory('origincar_base')
# =============================2. 参数=============================================
use_sim_time = LaunchConfiguration('use_sim_time', default='false')
map_yaml_path = LaunchConfiguration('map', default=os.path.join(
pkg_dir, 'maps', 'my_map.yaml'))
nav2_param_path = LaunchConfiguration('params_file', default=os.path.join(
pkg_dir, 'params', 'gc_navigation_slam_real.yaml'))
slam_params_file = os.path.join(
pkg_dir, 'config', 'slam_toolbox_localization_real.yaml')
posegraph_path = os.path.join(
pkg_dir, 'maps', 'my_map.posegraph')
# =============================3. 实车底盘 bringup ================================
origincar_bringup = IncludeLaunchDescription(
PythonLaunchDescriptionSource(
[origincar_base_dir, '/launch', '/origincar_bringup.launch.py']),
)
# =============================4. 镭神激光雷达驱动 ================================
lslidar_launch = IncludeLaunchDescription(
PythonLaunchDescriptionSource(
[get_package_share_directory('lslidar_driver'),
'/launch', '/lsn10_launch.py']),
)
# =============================5. map_server全量静态地图 ==========================
map_server_node = Node(
package='nav2_map_server',
executable='map_server',
name='map_server',
output='screen',
parameters=[{'yaml_filename': map_yaml_path, 'use_sim_time': False}],
)
map_server_lifecycle = Node(
package='nav2_lifecycle_manager',
executable='lifecycle_manager',
name='lifecycle_manager_map',
output='screen',
parameters=[{'use_sim_time': False, 'autostart': True,
'node_names': ['map_server']}],
)
# =============================6. slam_toolbox 定位模式(替代 AMCL==================
# ⚠️ /map 重映射到 /slam_map避免覆盖 map_server 的全量地图
slam_toolbox_node = Node(
package='slam_toolbox',
executable='localization_slam_toolbox_node',
name='slam_toolbox',
output='screen',
parameters=[slam_params_file,
{'use_sim_time': False,
'map_file_name': posegraph_path}],
remappings=[('/map', '/slam_map')],
)
# =============================7. Nav2 导航栈 =====================================
navigation_launch = IncludeLaunchDescription(
PythonLaunchDescriptionSource(
[nav2_bringup_dir, '/launch', '/navigation_launch.py']),
launch_arguments={
'use_sim_time': use_sim_time,
'params_file': nav2_param_path,
}.items(),
)
# =============================8. 组装=============================================
ld.add_action(origincar_bringup)
ld.add_action(lslidar_launch)
ld.add_action(map_server_node)
ld.add_action(map_server_lifecycle)
ld.add_action(slam_toolbox_node)
ld.add_action(navigation_launch)
return ld

View File

@@ -0,0 +1,135 @@
#!/usr/bin/env python3
# ============================================================================
# real_nav2_slam_online.launch.py
# 功能:实车导航 — 已知全局地图 + SLAM 在线更新 + Nav2 导航
#
# 架构:
# ┌─ /map全量静态地图
# map_server ──────────┤
# └─ 来自 my_map.yaml + my_map.pgm
#
# ┌─ map→odom_combined TF激光扫描匹配定位
# slam_toolbox ────────┤
# (async mapping) └─ /slam_map实时建图结果重映射避免冲突
#
# navigation ┌─ global_costmap/static_layer ← /map全量地图
# ├─ local_costmap/obstacle_layer ← /scan实时避障
# └─ planner + controller + behavior
#
# 关键设计:
# 1. map_server 提供全量静态底图 → Foxglove 中看到完整房间布局
# 2. slam_toolbox 定位 + 实时建图,/slam_map 可单独查看更新效果
# 3. 实时避障通过 costmap 的 obstacle_layer 实现(不依赖地图更新)
# 4. 定期调用 /slam_toolbox/serialize_map 保存更新后的地图
#
# 与仿真版的区别:
# - 无 Gazebo无 spawn_entity
# - 使用 origincar_base bringup串口驱动 + EKF + IMU
# - 使用 lslidar_driver镭神实车雷达
# - use_sim_time: False
# - TF 帧适配实车odom_combined, base_footprint
#
# 使用方式:
# ros2 launch gc_navigation2_real real_nav2_slam_online.launch.py
# ============================================================================
import os
from ament_index_python.packages import get_package_share_directory
from launch import LaunchDescription
from launch.actions import IncludeLaunchDescription, DeclareLaunchArgument
from launch.launch_description_sources import PythonLaunchDescriptionSource
from launch.substitutions import LaunchConfiguration
from launch_ros.actions import Node
from launch.actions import ExecuteProcess
def generate_launch_description():
"""启动实车底盘 + 雷达 + 静态地图 + SLAM 在线定位建图 + Nav2 导航"""
ld = LaunchDescription()
# =============================1. 包路径===========================================
pkg_dir = get_package_share_directory('gc_navigation2_real')
nav2_bringup_dir = get_package_share_directory('nav2_bringup')
origincar_base_dir = get_package_share_directory('origincar_base')
# =============================2. 参数=============================================
use_sim_time = LaunchConfiguration('use_sim_time', default='false')
map_yaml_path = os.path.join(pkg_dir, 'maps', 'my_map.yaml')
nav2_param_path = LaunchConfiguration('params_file', default=os.path.join(
pkg_dir, 'params', 'gc_navigation_slam_real.yaml'))
slam_params_file = os.path.join(pkg_dir, 'config', 'slam_toolbox_async_real.yaml')
posegraph_path = os.path.join(pkg_dir, 'maps', 'my_map.posegraph')
# =============================3. 实车底盘 bringup ================================
origincar_bringup = IncludeLaunchDescription(
PythonLaunchDescriptionSource(
[origincar_base_dir, '/launch', '/origincar_bringup.launch.py']),
)
# =============================4. 镭神激光雷达驱动 ================================
lslidar_launch = IncludeLaunchDescription(
PythonLaunchDescriptionSource(
[get_package_share_directory('lslidar_driver'),
'/launch', '/lsn10_launch.py']),
)
# =============================5. map_server全量静态地图 ==========================
map_server_node = Node(
package='nav2_map_server',
executable='map_server',
name='map_server',
output='screen',
parameters=[{'yaml_filename': map_yaml_path, 'use_sim_time': False}],
)
map_server_lifecycle = Node(
package='nav2_lifecycle_manager',
executable='lifecycle_manager',
name='lifecycle_manager_map',
output='screen',
parameters=[{'use_sim_time': False, 'autostart': True,
'node_names': ['map_server']}],
)
# =============================6. slam_toolbox定位 + 实时建图========================
# ⚠️ /map 重映射到 /slam_map避免覆盖 map_server 的全量地图
slam_toolbox_node = Node(
package='slam_toolbox',
executable='async_slam_toolbox_node',
name='slam_toolbox',
output='screen',
parameters=[slam_params_file, {'use_sim_time': False}],
remappings=[('/map', '/slam_map')],
)
# =============================7. 加载已有序列化地图 =================================
load_map_cmd = ExecuteProcess(
cmd=[
'bash', '-c',
'sleep 8 && '
'ros2 service call /slam_toolbox/deserialize_map '
'slam_toolbox/srv/DeserializePoseGraph '
"'{filename: \"%s\", match_type: 1}'" % posegraph_path,
],
output='screen',
)
# =============================8. Nav2 导航栈 =====================================
navigation_launch = IncludeLaunchDescription(
PythonLaunchDescriptionSource(
[nav2_bringup_dir, '/launch', '/navigation_launch.py']),
launch_arguments={
'use_sim_time': use_sim_time,
'params_file': nav2_param_path,
}.items(),
)
# =============================9. 组装============================================
ld.add_action(origincar_bringup)
ld.add_action(lslidar_launch)
ld.add_action(map_server_node)
ld.add_action(map_server_lifecycle)
ld.add_action(slam_toolbox_node)
ld.add_action(load_map_cmd)
ld.add_action(navigation_launch)
return ld

View File

@@ -0,0 +1,103 @@
#!/usr/bin/env python3
# ============================================================================
# real_slam_mapping.launch.py
# 功能:实车 SLAM 建图启动文件(无 Gazebo 仿真)
#
# 适用场景:
# - 在实际场地遥控机器人建立环境地图
# - 在已有地图基础上增量更新
# - 单独调试 slam_toolbox 建图参数
#
# 架构:
# origincar_base (bringup) — 底盘串口驱动 + EKF 里程计 + IMU 滤波 + TF
# lslidar_driver — 镭神激光雷达驱动 → /scan
# async_slam_toolbox_node — 激光 SLAM 建图mapping 模式)
# 发布 map→odom_combined TF
# 发布 /map 话题(实时地图)
#
# 使用方式:
# ros2 launch gc_navigation2_real real_slam_mapping.launch.py
#
# 保存地图:
# ros2 service call /slam_toolbox/serialize_map slam_toolbox/srv/SerializePoseGraph \
# "{filename: '/home/guoch/test_ws/src/gc_navigation2_real/maps/my_map'}"
# ros2 run nav2_map_server map_saver_cli -f <map_name>
# ============================================================================
import os
from ament_index_python.packages import get_package_share_directory
from launch import LaunchDescription
from launch.actions import DeclareLaunchArgument, IncludeLaunchDescription
from launch.substitutions import LaunchConfiguration
from launch_ros.actions import Node
from launch.launch_description_sources import PythonLaunchDescriptionSource
def generate_launch_description():
"""生成 LaunchDescription启动实车底盘 + 雷达 + slam_toolbox 建图"""
# ============================ 1. 包路径 =========================================
pkg_dir = get_package_share_directory('gc_navigation2_real')
origincar_base_dir = get_package_share_directory('origincar_base')
# ============================ 2. 声明启动参数 ====================================
use_sim_time = LaunchConfiguration('use_sim_time', default='false')
# slam_params_file: slam_toolbox 配置文件
slam_params_file = LaunchConfiguration(
'slam_params_file',
default=os.path.join(pkg_dir, 'config', 'slam_toolbox_async_real.yaml'))
# map_file_name: 可选,加载已有序列化地图继续建图
map_file_name = LaunchConfiguration('map_file_name', default='')
# ============================ 3. 实车底盘 bringup ===============================
# 启动 origincar_base串口驱动 + EKF + IMU 滤波 + TF 发布
# 注origincar_bringup 已包含 robot_state_publisher + joint_state_publisher + 静态 TF
origincar_bringup = IncludeLaunchDescription(
PythonLaunchDescriptionSource(
[origincar_base_dir, '/launch', '/origincar_bringup.launch.py']),
)
# ============================ 4. 镭神激光雷达驱动 ===============================
# 启动 lslidar_driver → /scan 话题
lslidar_launch = IncludeLaunchDescription(
PythonLaunchDescriptionSource(
[get_package_share_directory('lslidar_driver'),
'/launch', '/lsn10_launch.py']),
)
# ============================ 5. slam_toolbox 建图节点 ============================
slam_toolbox_node = Node(
package='slam_toolbox',
executable='async_slam_toolbox_node',
name='slam_toolbox',
output='screen',
parameters=[
slam_params_file,
{
'use_sim_time': False,
'map_file_name': map_file_name,
},
],
)
# ============================ 6. 组装 LaunchDescription =========================
return LaunchDescription([
DeclareLaunchArgument(
'use_sim_time',
default_value='false',
description='使用仿真时间(实车必须为 false'),
DeclareLaunchArgument(
'slam_params_file',
default_value=os.path.join(pkg_dir, 'config', 'slam_toolbox_async_real.yaml'),
description='slam_toolbox 参数配置文件路径'),
DeclareLaunchArgument(
'map_file_name',
default_value='',
description='已有序列化地图路径(.posegraph留空则从零开始建图'),
origincar_bringup,
lslidar_launch,
slam_toolbox_node,
])

View File

@@ -0,0 +1,3 @@
# 实车地图存放目录
# 使用 map_saver_cli 保存地图到此目录:
# ros2 run nav2_map_server map_saver_cli -f ~/test_ws/src/gc_navigation2_real/maps/your_map_name

View File

@@ -0,0 +1,31 @@
<?xml version="1.0"?>
<?xml-model href="http://download.ros.org/schema/package_format3.xsd" schematypens="http://www.w3.org/2001/XMLSchema"?>
<package format="3">
<name>gc_navigation2_real</name>
<version>0.0.0</version>
<description>Real-world navigation package: SLAM + Nav2 for OriginCar on physical robot (no Gazebo)</description>
<maintainer email="guoch@todo.todo">guoch</maintainer>
<license>TODO: License declaration</license>
<buildtool_depend>ament_cmake</buildtool_depend>
<exec_depend>rclcpp</exec_depend>
<exec_depend>slam_toolbox</exec_depend>
<exec_depend>nav2_bringup</exec_depend>
<exec_depend>origincar_base</exec_depend>
<exec_depend>origincar_description</exec_depend>
<exec_depend>origincar_msg</exec_depend>
<exec_depend>robot_state_publisher</exec_depend>
<exec_depend>joint_state_publisher</exec_depend>
<exec_depend>robot_localization</exec_depend>
<exec_depend>imu_filter_madgwick</exec_depend>
<exec_depend>tf2_ros</exec_depend>
<exec_depend>lslidar_driver</exec_depend>
<test_depend>ament_lint_auto</test_depend>
<test_depend>ament_lint_common</test_depend>
<export>
<build_type>ament_cmake</build_type>
</export>
</package>

View File

@@ -0,0 +1,353 @@
# ============================================================================
# gc_navigation_slam_real.yaml
# 实车 Nav2 导航参数SLAM 定位方案,无 AMCL
#
# 与仿真版的区别:
# - use_sim_time: False使用系统时钟
# - TF 帧适配实车odom_combined, base_footprint
# - 速度/加速度参数适当降低以保证实车安全
# - 激光雷达参数匹配镭神 N10 实车性能
# ============================================================================
slam_toolbox:
ros__parameters:
use_sim_time: False
bt_navigator:
ros__parameters:
use_sim_time: False
global_frame: map
robot_base_frame: base_footprint
odom_topic: /odom_combined
bt_loop_duration: 50
default_server_timeout: 20
# 阿克曼底盘专用 BT移除 Spin恢复行为 = 清代价地图 → 后退 → 等待
default_nav_to_pose_bt_xml: /home/guoch/test_ws/install/gc_navigation2_real/share/gc_navigation2_real/behavior_tree/nav_to_pose_ackermann.xml
plugin_lib_names:
- nav2_compute_path_to_pose_action_bt_node
- nav2_compute_path_through_poses_action_bt_node
- nav2_smooth_path_action_bt_node
- nav2_follow_path_action_bt_node
- nav2_spin_action_bt_node
- nav2_wait_action_bt_node
- nav2_back_up_action_bt_node
- nav2_drive_on_heading_bt_node
- nav2_clear_costmap_service_bt_node
- nav2_is_stuck_condition_bt_node
- nav2_goal_reached_condition_bt_node
- nav2_goal_updated_condition_bt_node
- nav2_globally_updated_goal_condition_bt_node
- nav2_is_path_valid_condition_bt_node
- nav2_initial_pose_received_condition_bt_node
- nav2_reinitialize_global_localization_service_bt_node
- nav2_rate_controller_bt_node
- nav2_distance_controller_bt_node
- nav2_speed_controller_bt_node
- nav2_truncate_path_action_bt_node
- nav2_truncate_path_local_action_bt_node
- nav2_goal_updater_node_bt_node
- nav2_recovery_node_bt_node
- nav2_pipeline_sequence_bt_node
- nav2_round_robin_node_bt_node
- nav2_transform_available_condition_bt_node
- nav2_time_expired_condition_bt_node
- nav2_path_expiring_timer_condition
- nav2_distance_traveled_condition_bt_node
- nav2_single_trigger_bt_node
- nav2_is_battery_low_condition_bt_node
- nav2_navigate_through_poses_action_bt_node
- nav2_navigate_to_pose_action_bt_node
- nav2_remove_passed_goals_action_bt_node
- nav2_planner_selector_bt_node
- nav2_controller_selector_bt_node
- nav2_goal_checker_selector_bt_node
- nav2_controller_cancel_bt_node
- nav2_path_longer_on_approach_bt_node
- nav2_wait_cancel_bt_node
- nav2_spin_cancel_bt_node
- nav2_back_up_cancel_bt_node
- nav2_drive_on_heading_cancel_bt_node
bt_navigator_rclcpp_node:
ros__parameters:
use_sim_time: False
controller_server:
ros__parameters:
use_sim_time: False
controller_frequency: 20.0
FollowPath:
plugin: "nav2_mppi_controller::MPPIController"
time_steps: 36
model_dt: 0.05
batch_size: 1000
vx_std: 0.2
vy_std: 0.0
wz_std: 0.4
vx_max: 0.5 # 第一阶段提速0.4→0.5(仿真已验证安全)
vx_min: -0.30 # 第一阶段提速:-0.25→-0.30
vy_max: 0.0
wz_max: 1.5 # 实车最大角速度降低
iteration_count: 1
temperature: 0.3
gamma: 0.015
motion_model: "Ackermann"
visualize: false
TrajectoryVisualizer:
trajectory_step: 5
time_step: 3
AckermannConstraints:
min_turning_r: 0.4
critics: ["ConstraintCritic", "CostCritic", "GoalCritic", "GoalAngleCritic", "PathAlignCritic", "PathFollowCritic", "PathAngleCritic", "PreferForwardCritic"]
ConstraintCritic:
enabled: true
cost_power: 1
cost_weight: 4.0
GoalCritic:
enabled: true
cost_power: 1
cost_weight: 5.0
threshold_to_consider: 1.4
GoalAngleCritic:
enabled: true
cost_power: 1
cost_weight: 3.0
threshold_to_consider: 0.5
PreferForwardCritic:
enabled: true
cost_power: 1
cost_weight: 5.0
threshold_to_consider: 0.5
CostCritic:
enabled: true
cost_power: 1
cost_weight: 3.81
critical_cost: 300.0
consider_footprint: true
collision_cost: 1000000.0
near_goal_distance: 1.0
trajectory_point_step: 2
PathAlignCritic:
enabled: true
cost_power: 1
cost_weight: 14.0
max_path_occupancy_ratio: 0.05
trajectory_point_step: 4
threshold_to_consider: 0.5
offset_from_furthest: 20
use_path_orientations: false
PathFollowCritic:
enabled: true
cost_power: 1
cost_weight: 5.0
offset_from_furthest: 5
threshold_to_consider: 1.4
PathAngleCritic:
enabled: true
cost_power: 1
cost_weight: 2.0
offset_from_furthest: 4
threshold_to_consider: 0.5
max_angle_to_furthest: 1.0
forward_preference: true
controller_server_rclcpp_node:
ros__parameters:
use_sim_time: False
local_costmap:
local_costmap:
ros__parameters:
update_frequency: 5.0
publish_frequency: 2.0
transform_tolerance: 0.5
global_frame: odom_combined # 实车EKF 融合后的里程计坐标系
robot_base_frame: base_footprint # 实车URDF 根帧
use_sim_time: False
rolling_window: true
width: 3
height: 3
resolution: 0.05
footprint: "[[0.14, 0.085],
[0.14, -0.085],
[-0.14, -0.085],
[-0.14, 0.085]]"
footprint_padding: 0.02
plugins: ["voxel_layer", "inflation_layer"]
inflation_layer:
plugin: "nav2_costmap_2d::InflationLayer"
cost_scaling_factor: 3.0
inflation_radius: 0.55
voxel_layer:
plugin: "nav2_costmap_2d::VoxelLayer"
enabled: True
publish_voxel_map: True
origin_z: 0.0
z_resolution: 0.05
z_voxels: 16
max_obstacle_height: 2.0
mark_threshold: 0
observation_sources: scan
scan:
topic: /scan
max_obstacle_height: 2.0
clearing: True
marking: True
data_type: "LaserScan"
raytrace_max_range: 3.0
raytrace_min_range: 0.0
obstacle_max_range: 2.5
obstacle_min_range: 0.0
static_layer:
map_subscribe_transient_local: True
always_send_full_costmap: True
local_costmap_client:
ros__parameters:
use_sim_time: False
local_costmap_rclcpp_node:
ros__parameters:
use_sim_time: False
global_costmap:
global_costmap:
ros__parameters:
use_sim_time: False
transform_tolerance: 0.5
update_frequency: 1.0
publish_frequency: 1.0
global_frame: map
robot_base_frame: base_footprint # 实车:与 URDF 根帧一致
footprint: "[[0.14, 0.085],
[0.14, -0.085],
[-0.14, -0.085],
[-0.14, 0.085]]"
footprint_padding: 0.02
resolution: 0.05
track_unknown_space: true
plugins: ["static_layer", "obstacle_layer", "inflation_layer"]
obstacle_layer:
plugin: "nav2_costmap_2d::ObstacleLayer"
enabled: True
observation_sources: scan
scan:
topic: /scan
max_obstacle_height: 2.0
clearing: True
marking: True
data_type: "LaserScan"
raytrace_max_range: 3.0
raytrace_min_range: 0.0
obstacle_max_range: 2.5
obstacle_min_range: 0.0
static_layer:
plugin: "nav2_costmap_2d::StaticLayer"
map_subscribe_transient_local: True
inflation_layer:
plugin: "nav2_costmap_2d::InflationLayer"
cost_scaling_factor: 3.0
inflation_radius: 0.55
always_send_full_costmap: True
global_costmap_client:
ros__parameters:
use_sim_time: False
global_costmap_rclcpp_node:
ros__parameters:
use_sim_time: False
map_saver:
ros__parameters:
use_sim_time: False
save_map_timeout: 5.0
free_thresh_default: 0.25
occupied_thresh_default: 0.65
map_subscribe_transient_local: True
planner_server:
ros__parameters:
planner_plugins: ["GridBased"]
use_sim_time: False
GridBased:
plugin: "nav2_smac_planner/SmacPlannerHybrid"
downsample_costmap: false
downsampling_factor: 1
tolerance: 0.25
allow_unknown: true
max_iterations: 1000000
max_on_approach_iterations: 1000
max_planning_time: 5.0
motion_model_for_search: "REEDS_SHEPP"
angle_quantization_bins: 72
analytic_expansion_ratio: 3.5
analytic_expansion_max_length: 3.0
minimum_turning_radius: 0.40
reverse_penalty: 1.3
change_penalty: 0.0
non_straight_penalty: 1.2
cost_penalty: 2.0
retrospective_penalty: 0.015
lookup_table_size: 20.0
cache_obstacle_heuristic: false
viz_expansions: false
smooth_path: True
smoother:
max_iterations: 1000
w_smooth: 0.3
w_data: 0.2
tolerance: 1.0e-10
do_refinement: true
refinement_num: 2
planner_server_rclcpp_node:
ros__parameters:
use_sim_time: False
smoother_server:
ros__parameters:
use_sim_time: False
smoother_plugins: ["simple_smoother"]
simple_smoother:
plugin: "nav2_smoother::SimpleSmoother"
tolerance: 1.0e-10
max_its: 1000
do_refinement: True
behavior_server:
ros__parameters:
costmap_topic: local_costmap/costmap_raw
footprint_topic: local_costmap/published_footprint
cycle_frequency: 10.0
behavior_plugins: ["spin", "backup", "wait"]
spin:
plugin: "nav2_behaviors/Spin"
backup:
plugin: "nav2_behaviors/BackUp"
backup_dist: 0.8
backup_speed: 0.18
wait:
plugin: "nav2_behaviors/Wait"
wait_duration: 0.5
global_frame: odom_combined # 实车EKF 融合后的里程计坐标系
robot_base_frame: base_footprint # 实车URDF 根帧
transform_tolerance: 0.5
use_sim_time: False
simulate_ahead_time: 2.0
max_rotational_vel: 1.0
min_rotational_vel: 0.4
rotational_acc_lim: 3.2
robot_state_publisher:
ros__parameters:
use_sim_time: False
waypoint_follower:
ros__parameters:
loop_rate: 20
use_sim_time: False
stop_on_failure: false
waypoint_task_executor_plugin: "wait_at_waypoint"
wait_at_waypoint:
plugin: "nav2_waypoint_follower::WaitAtWaypoint"
enabled: True
waypoint_pause_duration: 200

View File

@@ -0,0 +1,31 @@
cmake_minimum_required(VERSION 3.8)
project(gc_navigation2_slamtoolbox)
if(CMAKE_COMPILER_IS_GNUCXX OR CMAKE_CXX_COMPILER_ID MATCHES "Clang")
add_compile_options(-Wall -Wextra -Wpedantic)
endif()
# find dependencies
find_package(ament_cmake REQUIRED)
# uncomment the following section in order to fill in
# further dependencies manually.
# find_package(<dependency> REQUIRED)
# 查找slam_toolbox包
find_package(slam_toolbox REQUIRED)
install(
DIRECTORY launch config params maps world
DESTINATION share/${PROJECT_NAME}
)
if(BUILD_TESTING)
find_package(ament_lint_auto REQUIRED)
# the following line skips the linter which checks for copyrights
# comment the line when a copyright and license is added to all source files
set(ament_cmake_copyright_FOUND TRUE)
# the following line skips cpplint (only works in a git repo)
# comment the line when this package is in a git repo and when
# a copyright and license is added to all source files
set(ament_cmake_cpplint_FOUND TRUE)
ament_lint_auto_find_test_dependencies()
endif()
ament_package()

View File

@@ -0,0 +1,89 @@
slam_toolbox:
ros__parameters:
# Plugin params
solver_plugin: solver_plugins::CeresSolver
ceres_linear_solver: SPARSE_NORMAL_CHOLESKY
ceres_preconditioner: SCHUR_JACOBI
ceres_trust_strategy: LEVENBERG_MARQUARDT
ceres_dogleg_type: TRADITIONAL_DOGLEG
ceres_loss_function: None
# ROS Parameters
odom_frame: odom
map_frame: map
base_frame: base_link
scan_topic: /scan
use_map_saver: true
mode: mapping
# lifelong params
lifelong_search_use_tree: false
lifelong_minimum_score: 0.1
lifelong_iou_match: 0.85
lifelong_node_removal_score: 0.04
lifelong_overlap_score_scale: 0.06
lifelong_constraint_multiplier: 0.08
lifelong_nearby_penalty: 0.001
lifelong_candidates_scale: 0.03
# if you'd like to immediately start continuing a map at a given pose
# or at the dock, but they are mutually exclusive, if pose is given
# will use pose
#map_file_name: test_steve
#map_start_pose: [0.0, 0.0, 0.0]
#map_start_at_dock: true
debug_logging: false
throttle_scans: 1
transform_publish_period: 0.02 #if 0 never publishes odometry
map_update_interval: 5.0
resolution: 0.05
restamp_tf: false
min_laser_range: 0.0 #for rastering images
max_laser_range: 20.0 #for rastering images
minimum_time_interval: 0.5
transform_timeout: 0.2
tf_buffer_duration: 10.
stack_size_to_use: 40000000 #// program needs a larger stack size to serialize large maps
# General Parameters
use_scan_matching: true
use_scan_barycenter: true
minimum_travel_distance: 0.5
minimum_travel_heading: 0.5
check_min_dist_and_heading_precisely: false
scan_buffer_size: 10
scan_buffer_maximum_scan_distance: 10.0
link_match_minimum_response_fine: 0.1
link_scan_maximum_distance: 1.5
loop_search_maximum_distance: 3.0
do_loop_closing: true
loop_match_minimum_chain_size: 10
loop_match_maximum_variance_coarse: 3.0
loop_match_minimum_response_coarse: 0.35
loop_match_minimum_response_fine: 0.45
# Correlation Parameters - Correlation Parameters
correlation_search_space_dimension: 0.5
correlation_search_space_resolution: 0.01
correlation_search_space_smear_deviation: 0.1
# Correlation Parameters - Loop Closure Parameters
loop_search_space_dimension: 8.0
loop_search_space_resolution: 0.05
loop_search_space_smear_deviation: 0.03
# Scan Matcher Parameters
distance_variance_penalty: 0.5
angle_variance_penalty: 1.0
fine_search_angle_offset: 0.00349
coarse_search_angle_offset: 0.349
coarse_angle_resolution: 0.0349
minimum_angle_penalty: 0.9
minimum_distance_penalty: 0.5
use_response_expansion: true
min_pass_through: 2
occupancy_threshold: 0.1

View File

@@ -0,0 +1,72 @@
slam_toolbox:
ros__parameters:
solver_plugin: solver_plugins::CeresSolver
ceres_linear_solver: SPARSE_NORMAL_CHOLESKY
ceres_preconditioner: SCHUR_JACOBI
ceres_trust_strategy: LEVENBERG_MARQUARDT
ceres_dogleg_type: TRADITIONAL_DOGLEG
ceres_loss_function: None
# ROS Parameters
odom_frame: odom
map_frame: map
base_frame: base_link
scan_topic: /scan
mode: localization #localization
# if you'd like to start localizing on bringup in a map and pose
map_file_name: /home/guoch/test_ws/src/gc_navigation2_slamtoolbox/maps/my_map.posegraph
map_start_pose: [0.0, 0.0, 0.0]
debug_logging: false
throttle_scans: 1
transform_publish_period: 0.02 #if 0 never publishes odometry
map_update_interval: 5.0
resolution: 0.05
restamp_tf: false
min_laser_range: 0.0 #for rastering images
max_laser_range: 20.0 #for rastering images
minimum_time_interval: 0.5
transform_timeout: 0.2
tf_buffer_duration: 30.
stack_size_to_use: 40000000 #// program needs a larger stack size to serialize large maps
# General Parameters
use_scan_matching: true
use_scan_barycenter: true
minimum_travel_distance: 0.5
minimum_travel_heading: 0.5
check_min_dist_and_heading_precisely: false
scan_buffer_size: 3
scan_buffer_maximum_scan_distance: 10.0
link_match_minimum_response_fine: 0.1
link_scan_maximum_distance: 1.5
do_loop_closing: true
loop_match_minimum_chain_size: 3
loop_match_maximum_variance_coarse: 3.0
loop_match_minimum_response_coarse: 0.35
loop_match_minimum_response_fine: 0.45
# Correlation Parameters - Correlation Parameters
correlation_search_space_dimension: 0.5
correlation_search_space_resolution: 0.01
correlation_search_space_smear_deviation: 0.1
# Correlation Parameters - Loop Closure Parameters
loop_search_space_dimension: 8.0
loop_search_space_resolution: 0.05
loop_search_space_smear_deviation: 0.03
loop_search_maximum_distance: 3.0
# Scan Matcher Parameters
distance_variance_penalty: 0.5
angle_variance_penalty: 1.0
fine_search_angle_offset: 0.00349
coarse_search_angle_offset: 0.349
coarse_angle_resolution: 0.0349
minimum_angle_penalty: 0.9
minimum_distance_penalty: 0.5
use_response_expansion: true
min_pass_through: 2
occupancy_threshold: 0.1

View File

@@ -0,0 +1,71 @@
slam_toolbox:
ros__parameters:
# Plugin params
solver_plugin: solver_plugins::CeresSolver
ceres_linear_solver: SPARSE_NORMAL_CHOLESKY
ceres_preconditioner: SCHUR_JACOBI
ceres_trust_strategy: LEVENBERG_MARQUARDT
ceres_dogleg_type: TRADITIONAL_DOGLEG
ceres_loss_function: None
# ROS Parameters
odom_frame: odom
map_frame: map
base_frame: base_footprint
scan_topic: /scan
use_map_saver: true
mode: mapping #localization
debug_logging: false
throttle_scans: 1
transform_publish_period: 0.02 #if 0 never publishes odometry
map_update_interval: 10.0
resolution: 0.05
restamp_tf: false
min_laser_range: 0.0 #for rastering images
max_laser_range: 20.0 #for rastering images
minimum_time_interval: 0.5
transform_timeout: 0.2
tf_buffer_duration: 14400.
stack_size_to_use: 40000000 #// program needs a larger stack size to serialize large maps
enable_interactive_mode: true
# General Parameters
use_scan_matching: true
use_scan_barycenter: true
minimum_travel_distance: 0.5
minimum_travel_heading: 0.5
check_min_dist_and_heading_precisely: false
scan_buffer_size: 10
scan_buffer_maximum_scan_distance: 10.0
link_match_minimum_response_fine: 0.1
link_scan_maximum_distance: 1.5
loop_search_maximum_distance: 3.0
do_loop_closing: true
loop_match_minimum_chain_size: 10
loop_match_maximum_variance_coarse: 3.0
loop_match_minimum_response_coarse: 0.35
loop_match_minimum_response_fine: 0.45
# Correlation Parameters - Correlation Parameters
correlation_search_space_dimension: 0.5
correlation_search_space_resolution: 0.01
correlation_search_space_smear_deviation: 0.1
# Correlation Parameters - Loop Closure Parameters
loop_search_space_dimension: 8.0
loop_search_space_resolution: 0.05
loop_search_space_smear_deviation: 0.03
# Scan Matcher Parameters
distance_variance_penalty: 0.5
angle_variance_penalty: 1.0
fine_search_angle_offset: 0.00349
coarse_search_angle_offset: 0.349
coarse_angle_resolution: 0.0349
minimum_angle_penalty: 0.9
minimum_distance_penalty: 0.5
use_response_expansion: true
min_pass_through: 2
occupancy_threshold: 0.1

View File

@@ -0,0 +1,74 @@
$(var namespace)/slam_toolbox:
ros__parameters:
# Plugin params
solver_plugin: solver_plugins::CeresSolver
ceres_linear_solver: SPARSE_NORMAL_CHOLESKY
ceres_preconditioner: SCHUR_JACOBI
ceres_trust_strategy: LEVENBERG_MARQUARDT
ceres_dogleg_type: TRADITIONAL_DOGLEG
ceres_loss_function: None
# ROS Parameters
odom_frame: global_odom
map_frame: map
base_frame: base_footprint
scan_topic: scan
mode: mapping #localization
# if you'd like to immediately start continuing a map at a given pose
# or at the dock, but they are mutually exclusive, if pose is given
# will use pose
#map_file_name: test_steve
# map_start_pose: [0.0, 0.0, 0.0]
#map_start_at_dock: true
debug_logging: false
throttle_scans: 1
transform_publish_period: 0.02 #if 0 never publishes odometry
map_update_interval: 5.0
resolution: 0.05
max_laser_range: 20.0 #for rastering images
minimum_time_interval: 0.5
transform_timeout: 0.2
tf_buffer_duration: 30.0
stack_size_to_use: 40000000 #// program needs a larger stack size to serialize large maps
enable_interactive_mode: true
# General Parameters
use_scan_matching: true
use_scan_barycenter: true
minimum_travel_distance: 0.5
minimum_travel_heading: 0.5
check_min_dist_and_heading_precisely: false
scan_buffer_size: 10
scan_buffer_maximum_scan_distance: 10.0
link_match_minimum_response_fine: 0.1
link_scan_maximum_distance: 1.5
loop_search_maximum_distance: 3.0
do_loop_closing: true
loop_match_minimum_chain_size: 10
loop_match_maximum_variance_coarse: 3.0
loop_match_minimum_response_coarse: 0.35
loop_match_minimum_response_fine: 0.45
# Correlation Parameters - Correlation Parameters
correlation_search_space_dimension: 0.5
correlation_search_space_resolution: 0.01
correlation_search_space_smear_deviation: 0.1
# Correlation Parameters - Loop Closure Parameters
loop_search_space_dimension: 8.0
loop_search_space_resolution: 0.05
loop_search_space_smear_deviation: 0.03
# Scan Matcher Parameters
distance_variance_penalty: 0.5
angle_variance_penalty: 1.0
fine_search_angle_offset: 0.00349
coarse_search_angle_offset: 0.349
coarse_angle_resolution: 0.0349
minimum_angle_penalty: 0.9
minimum_distance_penalty: 0.5
use_response_expansion: true

View File

@@ -0,0 +1,79 @@
slam_toolbox:
ros__parameters:
# Plugin params
solver_plugin: solver_plugins::CeresSolver
ceres_linear_solver: SPARSE_NORMAL_CHOLESKY
ceres_preconditioner: SCHUR_JACOBI
ceres_trust_strategy: LEVENBERG_MARQUARDT
ceres_dogleg_type: TRADITIONAL_DOGLEG
ceres_loss_function: None
# ROS Parameters
odom_frame: odom
map_frame: map
base_frame: base_footprint
scan_topic: /scan
use_map_saver: true
mode: mapping #localization
# if you'd like to immediately start continuing a map at a given pose
# or at the dock, but they are mutually exclusive, if pose is given
# will use pose
#map_file_name: test_steve
#map_start_pose: [0.0, 0.0, 0.0]
#map_start_at_dock: true
debug_logging: false
throttle_scans: 1
transform_publish_period: 0.02 #if 0 never publishes odometry
map_update_interval: 5.0
resolution: 0.05
restamp_tf: false
min_laser_range: 0.0 #for rastering images
max_laser_range: 20.0 #for rastering images
minimum_time_interval: 0.5
transform_timeout: 0.2
tf_buffer_duration: 30.
stack_size_to_use: 40000000 #// program needs a larger stack size to serialize large maps
enable_interactive_mode: true
# General Parameters
use_scan_matching: true
use_scan_barycenter: true
minimum_travel_distance: 0.5
minimum_travel_heading: 0.5
check_min_dist_and_heading_precisely: false
scan_buffer_size: 10
scan_buffer_maximum_scan_distance: 10.0
link_match_minimum_response_fine: 0.1
link_scan_maximum_distance: 1.5
loop_search_maximum_distance: 3.0
do_loop_closing: true
loop_match_minimum_chain_size: 10
loop_match_maximum_variance_coarse: 3.0
loop_match_minimum_response_coarse: 0.35
loop_match_minimum_response_fine: 0.45
# Correlation Parameters - Correlation Parameters
correlation_search_space_dimension: 0.5
correlation_search_space_resolution: 0.01
correlation_search_space_smear_deviation: 0.1
# Correlation Parameters - Loop Closure Parameters
loop_search_space_dimension: 8.0
loop_search_space_resolution: 0.05
loop_search_space_smear_deviation: 0.03
# Scan Matcher Parameters
distance_variance_penalty: 0.5
angle_variance_penalty: 1.0
fine_search_angle_offset: 0.00349
coarse_search_angle_offset: 0.349
coarse_angle_resolution: 0.0349
minimum_angle_penalty: 0.9
minimum_distance_penalty: 0.5
use_response_expansion: true
min_pass_through: 2
occupancy_threshold: 0.1

View File

@@ -0,0 +1,36 @@
<!--
阿克曼底盘自定义行为树:移除了 Spin原地旋转
恢复行为改为:清除代价地图 → 后退 → 等待
-->
<root main_tree_to_execute="MainTree">
<BehaviorTree ID="MainTree">
<RecoveryNode number_of_retries="6" name="NavigateRecovery">
<PipelineSequence name="NavigateWithReplanning">
<RateController hz="1.0">
<RecoveryNode number_of_retries="1" name="ComputePathToPose">
<ComputePathToPose goal="{goal}" path="{path}" planner_id="GridBased"/>
<ClearEntireCostmap name="ClearGlobalCostmap-Context" service_name="global_costmap/clear_entirely_global_costmap"/>
</RecoveryNode>
</RateController>
<RecoveryNode number_of_retries="1" name="FollowPath">
<FollowPath path="{path}" controller_id="FollowPath"/>
<ClearEntireCostmap name="ClearLocalCostmap-Context" service_name="local_costmap/clear_entirely_local_costmap"/>
</RecoveryNode>
</PipelineSequence>
<ReactiveFallback name="RecoveryFallback">
<GoalUpdated/>
<RoundRobin name="RecoveryActions">
<!-- 1. 清除代价地图,去掉短暂障碍 -->
<Sequence name="ClearingActions">
<ClearEntireCostmap name="ClearLocalCostmap-Subtree" service_name="local_costmap/clear_entirely_local_costmap"/>
<ClearEntireCostmap name="ClearGlobalCostmap-Subtree" service_name="global_costmap/clear_entirely_global_costmap"/>
</Sequence>
<!-- 2. 快速后退 0.8m,给重新规划留空间(阿克曼无法原地旋转) -->
<BackUp backup_dist="0.80" backup_speed="0.18"/>
<!-- 3. 短暂等待 0.3s,让新路径规划完成 -->
<Wait wait_duration="0.3"/>
</RoundRobin>
</ReactiveFallback>
</RecoveryNode>
</BehaviorTree>
</root>

View File

@@ -0,0 +1,82 @@
slam_toolbox:
ros__parameters:
# ============================ Solver 插件参数 ======================================
solver_plugin: solver_plugins::CeresSolver
ceres_linear_solver: SPARSE_NORMAL_CHOLESKY
ceres_preconditioner: SCHUR_JACOBI
ceres_trust_strategy: LEVENBERG_MARQUARDT
ceres_dogleg_type: TRADITIONAL_DOGLEG
ceres_loss_function: None
# ============================ ROS 基础参数 =========================================
odom_frame: odom # 里程计坐标系
map_frame: map # 地图坐标系
base_frame: base_link # 机器人基座坐标系(与 URDF 根帧一致)
scan_topic: /scan # 激光雷达话题
use_map_saver: true # 启用地图保存功能
mode: mapping # mapping = 定位 + 实时建图(地图可更新)
# ============================ 已有地图加载(在其基础上继续更新)==========================
# 启动时暂不加载(注释掉),通过服务在启动后手动加载:
# ros2 service call /slam_toolbox/deserialize_map slam_toolbox/srv/DeserializePoseGraph "{filename: '/home/guoch/test_ws/src/gc_navigation2_slamtoolbox/maps/my_map.posegraph', match_type: 1}"
# map_file_name: /home/guoch/test_ws/src/gc_navigation2_slamtoolbox/maps/my_map.posegraph
map_start_pose: [-2.0, -2.0, 0.0] # 初始位姿 [x, y, yaw]map 坐标系下)
# map_start_at_dock: true # 或从 docking 位姿启动(与 pose 互斥)
# ============================ 调试与性能 ===========================================
debug_logging: false # 调试日志(生产环境关闭)
throttle_scans: 10 # 每 N 帧激光处理一次1=全部处理)
transform_publish_period: 0.02 # TF 发布周期0=不发布里程计
map_update_interval: 3.0 # /map 话题更新间隔(秒),越小越实时
resolution: 0.05 # 地图分辨率(米/像素)
restamp_tf: false # 是否重新打时间戳
min_laser_range: 0.0 # 激光最小有效距离(米)
max_laser_range: 20.0 # 激光最大有效距离(米)
minimum_time_interval: 0.5 # 最小处理时间间隔(秒)
transform_timeout: 0.2 # TF 查找超时(秒)
tf_buffer_duration: 30.0 # TF 缓冲区时长(秒)
stack_size_to_use: 40000000 # 栈大小(序列化大地图需要)
enable_interactive_mode: true # 交互模式:允许外部工具编辑地图
# ============================ 通用建图参数 =========================================
use_scan_matching: true # 启用扫描匹配
use_scan_barycenter: true # 使用扫描重心
minimum_travel_distance: 0.1 # 最小移动距离触发处理(米)
minimum_travel_heading: 0.1 # 最小转向角度触发处理(弧度)
check_min_dist_and_heading_precisely: false
scan_buffer_size: 5 # 扫描缓冲区大小(越大匹配越稳定)
scan_buffer_maximum_scan_distance: 5.0 # 缓冲区最大扫描距离
link_match_minimum_response_fine: 0.1 # 精细匹配最小响应
link_scan_maximum_distance: 1.5 # 链接扫描最大距离
# ============================ 回环检测参数 =========================================
do_loop_closing: true # 启用回环检测(消除累积误差)
loop_match_minimum_chain_size: 10 # 最小回环链大小
loop_match_maximum_variance_coarse: 3.0 # 粗匹配最大方差
loop_match_minimum_response_coarse: 0.35 # 粗匹配最小响应
loop_match_minimum_response_fine: 0.45 # 精细匹配最小响应
loop_search_maximum_distance: 3.0 # 回环搜索最大距离
# ============================ 相关性匹配 - 扫描匹配参数 ==============================
correlation_search_space_dimension: 0.5 # 搜索空间维度
correlation_search_space_resolution: 0.01 # 搜索空间分辨率
correlation_search_space_smear_deviation: 0.1 # 搜索空间平滑偏差
# ============================ 相关性匹配 - 回环检测参数 ==============================
loop_search_space_dimension: 8.0 # 回环搜索空间维度
loop_search_space_resolution: 0.05 # 回环搜索分辨率
loop_search_space_smear_deviation: 0.03 # 回环搜索平滑偏差
# ============================ 扫描匹配器参数 ========================================
distance_variance_penalty: 0.5 # 距离方差惩罚
angle_variance_penalty: 1.0 # 角度方差惩罚
fine_search_angle_offset: 0.00349 # 精细搜索角度偏移
coarse_search_angle_offset: 0.349 # 粗搜索角度偏移
coarse_angle_resolution: 0.0349 # 粗搜索角度分辨率
minimum_angle_penalty: 0.9 # 最小角度惩罚
minimum_distance_penalty: 0.5 # 最小距离惩罚
use_response_expansion: true # 使用响应扩展
min_pass_through: 2 # 最小通过次数
occupancy_threshold: 0.1 # 占据阈值

View File

@@ -0,0 +1,55 @@
slam_toolbox:
ros__parameters:
# 核心模式设置
use_sim_time: true
mode: "localization" # 重要:设置为定位模式
map_file_name: "" # 由启动参数传入
map_start_pose: [0.0,0.0,0.0]
# ROS框架设置
odom_frame: "odom"
map_frame: "map"
base_frame: "base_footprint"
scan_topic: "/scan"
# 求解器设置
solver_plugin: "solver_plugins::CeresSolver"
ceres_linear_solver: "SPARSE_NORMAL_CHOLESKY"
ceres_preconditioner: "SCHUR_JACOBI"
ceres_trust_strategy: "LEVENBERG_MARQUARDT"
ceres_dogleg_type: "TRADITIONAL_DOGLEG"
ceres_loss_function: "None"
# 定位优化参数
use_scan_matching: true
use_scan_barycenter: true
minimum_travel_distance: 0.05
minimum_travel_heading: 0.087
# 扫描处理
scan_buffer_size: 50
throttle_scans: 2
# 回环检测(定位模式可关闭)
do_loop_closing: false
# 搜索参数
link_match_minimum_response_fine: 0.2
link_scan_maximum_distance: 2.0
loop_search_maximum_distance: 5.0
# 性能参数
minimum_time_interval: 0.1
transform_publish_period: 0.02
map_update_interval: 0.5
# 地图参数
resolution: 0.05
max_laser_range: 15.0
min_laser_range: 0.2
# 初始位姿可选可以通过RViz设置
# map_start_pose: [0.0, 0.0, 0.0]
# 调试
debug_logging: false
enable_interactive_mode: true

View File

@@ -0,0 +1,73 @@
slam_toolbox:
ros__parameters:
# === Solver ===
solver_plugin: solver_plugins::CeresSolver
ceres_linear_solver: SPARSE_NORMAL_CHOLESKY
ceres_preconditioner: SCHUR_JACOBI
ceres_trust_strategy: LEVENBERG_MARQUARDT
ceres_dogleg_type: TRADITIONAL_DOGLEG
ceres_loss_function: None
# === ROS 基础 ===
odom_frame: odom
map_frame: map
base_frame: base_link
scan_topic: /scan
mode: mapping
use_map_saver: true
# === 调试与性能 ===
debug_logging: false
throttle_scans: 1
transform_publish_period: 0.02
map_update_interval: 3.0
resolution: 0.05
min_laser_range: 0.15
max_laser_range: 20.0
minimum_time_interval: 0.5
transform_timeout: 0.2
tf_buffer_duration: 30.0
stack_size_to_use: 40000000
enable_interactive_mode: true
# === 建图参数 ===
use_scan_matching: true
use_scan_barycenter: true
minimum_travel_distance: 0.5
minimum_travel_heading: 0.1
scan_buffer_size: 10
scan_buffer_maximum_scan_distance: 10.0
link_match_minimum_response_fine: 0.1
link_scan_maximum_distance: 1.5
# === 回环检测 ===
do_loop_closing: true
loop_match_minimum_chain_size: 10
loop_match_maximum_variance_coarse: 3.0
loop_match_minimum_response_coarse: 0.35
loop_match_minimum_response_fine: 0.45
loop_search_maximum_distance: 3.0
# === 扫描匹配 ===
correlation_search_space_dimension: 0.5
correlation_search_space_resolution: 0.01
correlation_search_space_smear_deviation: 0.1
loop_search_space_dimension: 8.0
loop_search_space_resolution: 0.05
loop_search_space_smear_deviation: 0.03
# === 匹配器参数 ===
distance_variance_penalty: 0.5
angle_variance_penalty: 1.0
fine_search_angle_offset: 0.00349
coarse_search_angle_offset: 0.349
coarse_angle_resolution: 0.0349
minimum_angle_penalty: 0.9
minimum_distance_penalty: 0.5
use_response_expansion: true
min_pass_through: 2
occupancy_threshold: 0.1
# MessageFilter queue size (default 1, too small for high-rate lidar)
scan_queue_size: 20

View File

@@ -0,0 +1,156 @@
# ============================================================================
# gc_nav2_with_amcl.launch.py
# 功能:基于 AMCL自适应蒙特卡洛定位的导航启动文件
#
# 架构:
# Gazebo 仿真环境
# ├── robot_state_publisher — 发布机器人 TF 树URDF 模型)
# └── nav2_bringup_launch — Nav2 一体化启动(包含以下子模块):
# ├── map_server — 加载 my_map.yaml,发布全量静态地图到 /map
# ├── AMCL — 粒子滤波定位,发布 map→odom TF
# │ 需要手动设置 /initialpose 初始位姿
# ├── planner_server — 全局/局部路径规划器SmacHybrid
# ├── controller_server — 路径跟踪控制器MPPI Ackermann
# ├── behavior_server — 恢复行为服务器spin/backup/wait
# └── bt_navigator — 行为树导航编排器
#
# 与 SLAM 定位方案的区别:
# AMCL 粒子滤波定位,需要手动设置初始位姿,地图固定不更新
# SLAM定位 激光扫描匹配定位,自动定位,可加载 .posegraph 序列化地图
# ============================================================================
import os
from ament_index_python.packages import get_package_share_directory
from launch import LaunchDescription
from launch.actions import IncludeLaunchDescription, DeclareLaunchArgument, TimerAction
from launch.launch_description_sources import PythonLaunchDescriptionSource
from launch.substitutions import LaunchConfiguration
from launch_ros.actions import Node
from launch_ros.parameter_descriptions import ParameterValue
from launch.substitutions import Command
from launch.actions import ExecuteProcess
def generate_launch_description():
"""生成 LaunchDescription,启动 Gazebo + AMCL定位 + Nav2 导航"""
ld = LaunchDescription()
# =============================1.定位到包的地址=============================================================
# 通过 ament_index 获取各功能包的安装路径
gc_navigation_fish_dir = get_package_share_directory(
'gc_navigation2_slamtoolbox')
nav2_bringup_dir = get_package_share_directory('nav2_bringup')
origincar_urdf_dir = get_package_share_directory(
'origincar_description')
# =============================2.声明参数,获取配置文件路径===================================================
# use_sim_time: 仿真时间开关。Gazebo 下必须为 True,
# 因为仿真环境通过 /clock 话题提供时间,而非系统时间
use_sim_time = LaunchConfiguration('use_sim_time', default='true')
# map_yaml_path: 全量静态地图 yaml 文件路径
# 传给 bringup_launch → map_server 加载并发布到 /map
map_yaml_path = LaunchConfiguration('map', default=os.path.join(
gc_navigation_fish_dir, 'maps', 'my_map.yaml'))
# nav2_param_path: Nav2 导航栈参数文件(含 AMCL 粒子滤波配置)
# 注意:此处用 gc_navigation_amcl.yaml,包含 AMCL 参数(粒子数、运动模型等)
# SLAM 方案则用 gc_navigation_slam.yaml不含 AMCL
nav2_param_path = LaunchConfiguration('params_file', default=os.path.join(
gc_navigation_fish_dir, 'params', 'gc_navigation_amcl.yaml'))
# =============================3.声明启动launch文件==========================================================
# bringup_launch.py 是 Nav2 的一体化启动入口,内部自动处理:
# 1. 声明所有 launch 参数map, slam, use_sim_time, params_file 等)
# 2. 根据 slam 参数决定启动模式:
# slam=False默认→ localization_launchmap_server + AMCL
# slam=True → slam_launchslam_toolbox 在线建图)
# 3. 启动 navigation_launchplanner + controller + behavior + bt_navigator
# 4. 通过 RewrittenYaml 实现参数文件中的变量替换
#
# 传入参数:
# map: 地图 yaml 文件路径map_server 加载,AMCL 定位)
# use_sim_time: 仿真时间模式Gazebo 下必须为 true
# params_file: Nav2 全部节点的参数配置
nav2_bringup_launch = IncludeLaunchDescription(
PythonLaunchDescriptionSource(
[nav2_bringup_dir, '/launch', '/bringup_launch.py']),
launch_arguments={
'map': map_yaml_path,
'use_sim_time': use_sim_time,
'params_file': nav2_param_path}.items(),
)
# =============================4.Gazebo仿真设置==========================================================
# robot_name_in_model: Gazebo 中机器人的模型名称,需与 URDF 中一致
robot_name_in_model = 'mycar'
# default_model_path: 机器人 URDF 模型文件路径
# 使用 xacro 宏展开生成最终的 URDF
default_model_path = os.path.join(
origincar_urdf_dir, "urdf", "origincar.urdf")
# 声明 model 启动参数,支持命令行覆盖ros2 launch ... model:=/path/to/custom.urdf
model = DeclareLaunchArgument(
name="model", default_value=default_model_path)
# Gazebo 仿真世界文件路径
gazebo_world_path = os.path.join(origincar_urdf_dir, 'world/test.world')
# 启动 Gazebo 仿真器进程
# --verbose: 输出详细日志
# -s libgazebo_ros_init.so: 加载 ROS ↔ Gazebo 通信初始化插件
# -s libgazebo_ros_factory.so: 加载模型生成spawn_entity插件
start_gazebo_cmd = ExecuteProcess(
cmd=['gazebo', '--verbose', '-s', 'libgazebo_ros_init.so',
'-s', 'libgazebo_ros_factory.so', gazebo_world_path],
output='screen')
# 在 Gazebo 世界中生成机器人模型
# -entity: 模型在 Gazebo 中的实例名mycar
# -file: 要加载的 URDF 模型文件
# 生成后 Gazebo 会为模型创建对应的关节状态话题等
spawn_entity_cmd = Node(
package='gazebo_ros',
executable='spawn_entity.py',
arguments=['-entity', robot_name_in_model,
'-file', default_model_path],
output='screen'
)
# robot_description: 将 XACRO/URDF 模型字符串设为 ROS 参数
# robot_state_publisher 读取此参数发布各连杆的 TF 坐标变换
robot_description = ParameterValue(
Command(["xacro ", LaunchConfiguration("model")]), value_type=str)
# robot_state_publisher: 发布机器人各关节、连杆的 TF 变换
# - 订阅 joint_states 话题获取关节角度
# - 根据 URDF 模型计算 base_link → laser_link, wheel_link 等变换
# - publish_frequency=30Hz 确保 TF 更新平滑
# - use_sim_time=True 使用 /clock 仿真时间
robot_state_publisher = Node(
package="robot_state_publisher",
executable="robot_state_publisher",
parameters=[{"robot_description": robot_description,
'use_sim_time': True, 'publish_frequency': 30.0}]
)
# joint_state_publisher: 发布非固定关节的默认状态
# 如果 Gazebo 已经发布 joint_states,此节点可以注释掉避免冲突
# joint_state_publisher = Node(
# package="joint_state_publisher",
# executable="joint_state_publisher"
# )
# =============================5.将所有 Action 添加到 LaunchDescription ==================================
# 注意nav2_bringup_launch 必须在 Gazebo 启动之后,
# 否则会出现 /clock 话题未就绪的问题
# 可通过 TimerAction 添加延迟,或依赖 launch 系统的自动排序
ld.add_action(model) # 1. 声明模型路径参数
ld.add_action(nav2_bringup_launch) # 2. 启动 Nav2 一体化map_server + AMCL + 导航)
ld.add_action(start_gazebo_cmd) # 3. 启动 Gazebo 仿真器
ld.add_action(spawn_entity_cmd) # 4. 在 Gazebo 中生成机器人
ld.add_action(robot_state_publisher) # 5. 发布机器人 TF 树
# ld.add_action(joint_state_publisher) # 6. (可选) 默认关节状态发布
return ld

View File

@@ -0,0 +1,196 @@
# ============================================================================
# gc_nav2_with_slam.launch.py
# 功能:基于 slam_toolbox 定位的导航启动文件
#
# 架构:
# Gazebo 仿真环境
# ├── robot_state_publisher — 发布机器人 TF 树URDF 模型)
# ├── map_server — 加载 my_map.yaml发布全量静态地图到 /map
# ├── slam_toolbox — 加载 my_map.posegraph激光扫描匹配定位
# │ 发布 map→odom TF替代 AMCL 的粒子滤波
# │ ⚠️ /map 话题重映射为 /slam_map避免冲突
# └── navigation_launch — Nav2 导航栈(路径规划 + 运动控制)
# global_costmap 从 /map 获取全量静态地图
#
# 与 AMCL 方案的区别:
# AMCL 粒子滤波定位,需要手动设置初始位姿
# SLAM定位 激光扫描匹配定位,自动根据地图特征定位
# ============================================================================
import os
from ament_index_python.packages import get_package_share_directory
from launch import LaunchDescription
from launch.actions import IncludeLaunchDescription, DeclareLaunchArgument
from launch.launch_description_sources import PythonLaunchDescriptionSource
from launch.substitutions import LaunchConfiguration
from launch_ros.actions import Node
from launch_ros.parameter_descriptions import ParameterValue
from launch.substitutions import Command
from launch.actions import ExecuteProcess
def generate_launch_description():
"""生成 LaunchDescription启动 Gazebo + SLAM定位 + Nav2 导航"""
ld = LaunchDescription()
# =============================1.定位到包的地址=============================================================
# 通过 ament_index 获取各功能包的安装路径
pkg_dir = get_package_share_directory('gc_navigation2_slamtoolbox')
nav2_bringup_dir = get_package_share_directory('nav2_bringup')
origincar_urdf_dir = get_package_share_directory('origincar_description')
# =============================2.声明参数===============================================================
# use_sim_time: 仿真时间开关。Gazebo 下必须为 True
# 因为仿真环境通过 /clock 话题提供时间,而非系统时间
use_sim_time = LaunchConfiguration('use_sim_time', default='true')
# map_yaml_path: 全量静态地图 yaml 文件路径
# 由 map_server 加载,发布到 /map 供 global_costmap 使用
map_yaml_path = LaunchConfiguration('map', default=os.path.join(
pkg_dir, 'maps', 'my_map.yaml'))
# nav2_param_path: Nav2 导航栈参数文件(不含 AMCL含 slam_toolbox
nav2_param_path = LaunchConfiguration('params_file', default=os.path.join(
pkg_dir, 'params', 'gc_navigation_slam.yaml'))
# slam_params_file: slam_toolbox 定位模式的参数文件
# mode: localization — 只定位不建图
# 包含 solver 配置、激光匹配参数、TF 帧定义等
slam_params_file = os.path.join(
pkg_dir, 'config', 'mapper_params_localization.yaml')
# posegraph_path: slam_toolbox 定位所需的序列化地图文件
# .posegraph 文件保存了 slam_toolbox 建图时的位姿图
# 配合 .data 文件slam_toolbox 可以还原完整地图用于激光匹配
posegraph_path = os.path.join(
pkg_dir, 'maps', 'my_map.posegraph')
# =============================3.slam_toolbox 定位模式(替代 AMCL=========================================
# localization_slam_toolbox_node:
# - 加载 .posegraph 序列化地图用于激光扫描匹配
# - 发布 map→odom 坐标变换(替代 AMCL 的粒子滤波定位)
# - 发布 /pose 话题(当前定位位姿)
#
# ⚠️ 关键:将 slam_toolbox 的 /map 重映射为 /slam_map
# 避免覆盖 map_server 发布到 /map 的全量静态地图
# 确保 global_costmap 的 static_layer 能获取完整地图边界
slam_toolbox_node = Node(
package='slam_toolbox',
executable='localization_slam_toolbox_node',
name='slam_toolbox',
output='screen',
parameters=[slam_params_file,
{'use_sim_time': True,
'map_file_name': posegraph_path}],
remappings=[('/map', '/slam_map')],
)
# =============================4.map_server 提供全量静态地图给 global_costmap =============================
# map_server:
# - 加载 my_map.yaml + my_map.pgm 格式的传统静态地图
# - 发布完整地图到 /map 话题199×266 像素,分辨率 0.05 m
# - 这是 global_costmap 静态层的唯一数据来源
# - 是 lifecycle 节点,需要 lifecycle_manager 激活
map_server_node = Node(
package='nav2_map_server',
executable='map_server',
name='map_server',
output='screen',
parameters=[{'yaml_filename': map_yaml_path,
'use_sim_time': True}],
)
# lifecycle_manager: 管理 map_server 的生命周期configure → activate
# autostart=True 表示启动后自动激活 map_server
map_server_lifecycle = Node(
package='nav2_lifecycle_manager',
executable='lifecycle_manager',
name='lifecycle_manager_map',
output='screen',
parameters=[{'use_sim_time': True,
'autostart': True,
'node_names': ['map_server']}],
)
# =============================5.仅启动 nav2 navigation不含 localization=================================
# 为什么用 navigation_launch 而不是 bringup_launch
# bringup_launch 包含 localization_launchAMCL + map_server
# 由于 slam_toolbox 已经替代了 AMCL只需 navigation_launch 的:
# - planner_server — 全局/局部路径规划
# - controller_server — 路径跟踪控制MPPI
# - behavior_server — 行为树spin/backup/wait 恢复)
# - bt_navigator — 行为树导航编排
# - costmap 层 — global_costmap + local_costmap
navigation_launch = IncludeLaunchDescription(
PythonLaunchDescriptionSource(
[nav2_bringup_dir, '/launch', '/navigation_launch.py']),
launch_arguments={
'use_sim_time': use_sim_time,
'params_file': nav2_param_path}.items(),
)
# =============================6.Gazebo仿真设置==========================================================
# robot_name_in_model: Gazebo 中机器人的模型名称,需与 URDF 中一致
robot_name_in_model = 'mycar'
# default_model_path: 机器人 URDF 模型文件路径
# 使用 xacro 预处理生成最终的 URDF
default_model_path = os.path.join(
origincar_urdf_dir, "urdf", "origincar.urdf")
# 声明 model 启动参数,支持命令行覆盖 URDF 路径
model = DeclareLaunchArgument(
name="model", default_value=default_model_path)
# Gazebo 世界文件路径
gazebo_world_path = os.path.join(origincar_urdf_dir, 'world/test.world')
# 启动 Gazebo 仿真器
# --verbose: 详细日志输出
# -s libgazebo_ros_init.so: 加载 ROS-Gazebo 初始化插件
# -s libgazebo_ros_factory.so: 加载模型生成插件
start_gazebo_cmd = ExecuteProcess(
cmd=['gazebo', '--verbose', '-s', 'libgazebo_ros_init.so',
'-s', 'libgazebo_ros_factory.so', gazebo_world_path],
output='screen')
# 在 Gazebo 中生成机器人模型
# -entity: 模型实例名称
# -file: URDF 模型文件
spawn_entity_cmd = Node(
package='gazebo_ros',
executable='spawn_entity.py',
arguments=['-entity', robot_name_in_model,
'-file', default_model_path],
output='screen'
)
# robot_description: 将 URDF/XACRO 模型转换为 ROS 参数
# robot_state_publisher 订阅此参数发布 TF 树
robot_description = ParameterValue(
Command(["xacro ", LaunchConfiguration("model")]), value_type=str)
# robot_state_publisher: 发布机器人各连杆的 TF 变换
# base_link → laser_link, wheel_link 等关节状态
# publish_frequency=30Hz 保证平滑的 TF 更新
robot_state_publisher = Node(
package="robot_state_publisher",
executable="robot_state_publisher",
parameters=[{"robot_description": robot_description,
'use_sim_time': True, 'publish_frequency': 30.0}]
)
# =============================7.将所有 Action 添加到 LaunchDescription ==================================
# 启动顺序由 Launch 系统自动管理依赖
ld.add_action(model) # 1. 声明模型参数
ld.add_action(start_gazebo_cmd) # 2. 启动 Gazebo 仿真器
ld.add_action(spawn_entity_cmd) # 3. 生成机器人模型
ld.add_action(robot_state_publisher) # 4. 发布 TF 树
ld.add_action(map_server_node) # 5. 加载全量静态地图 → /map
ld.add_action(map_server_lifecycle) # 6. 激活 map_server
ld.add_action(slam_toolbox_node) # 7. 启动 SLAM 定位 → map→odom TF
ld.add_action(navigation_launch) # 8. 启动 Nav2 导航栈
return ld

View File

@@ -0,0 +1,181 @@
# ============================================================================
# gc_nav2_with_slam_online.launch.py
# 功能:已知全局地图 + SLAM 在线更新 + 导航
#
# 架构:
# ┌─ /map全量静态地图199×266
# map_server ──────────┤
# └─ 来自 my_map.yaml + my_map.pgm
#
# ┌─ map→odom TF激光扫描匹配定位
# slam_toolbox ────────┤
# (async mapping) └─ /slam_map实时建图结果重映射避免冲突
#
# navigation ┌─ global_costmap/static_layer ← /map全量地图
# ├─ local_costmap/obstacle_layer ← /scan实时避障
# └─ planner + controller + behavior
#
# 关键设计:
# 1. map_server 提供全量静态底图 → Foxglove 中看到完整房间布局
# 2. slam_toolbox 定位 + 实时建图,/slam_map 可单独查看更新效果
# 3. 实时避障通过 costmap 的 obstacle_layer 实现(不依赖地图更新)
# 4. 定期调用 /slam_toolbox/serialize_map 保存更新后的地图
# ============================================================================
import os
from ament_index_python.packages import get_package_share_directory
from launch import LaunchDescription
from launch.actions import IncludeLaunchDescription, DeclareLaunchArgument, SetEnvironmentVariable
from launch.launch_description_sources import PythonLaunchDescriptionSource
from launch.substitutions import LaunchConfiguration
from launch_ros.actions import Node
from launch_ros.parameter_descriptions import ParameterValue
from launch.substitutions import Command
from launch.actions import ExecuteProcess
def generate_launch_description():
"""启动 Gazebo + 已知全局地图 + SLAM 在线定位建图 + Nav2 导航"""
ld = LaunchDescription()
# =============================1.包路径================================================================
pkg_dir = get_package_share_directory('gc_navigation2_slamtoolbox')
nav2_bringup_dir = get_package_share_directory('nav2_bringup')
origincar_urdf_dir = get_package_share_directory('origincar_description')
# =============================2.参数==================================================================
use_sim_time = LaunchConfiguration('use_sim_time', default='true')
map_yaml_path = os.path.join(pkg_dir, 'maps', 'zhihui.yaml')
nav2_param_path = LaunchConfiguration('params_file', default=os.path.join(
pkg_dir, 'params', 'gc_navigation_slam.yaml'))
slam_params_file = os.path.join(pkg_dir, 'config', 'slam_toolbox_async.yaml')
posegraph_path = os.path.join(pkg_dir, 'maps', 'zhihui.posegraph')
# =============================3.map_server全量静态地图Foxglove 看到的全局地图)========================
map_server_node = Node(
package='nav2_map_server',
executable='map_server',
name='map_server',
output='screen',
parameters=[{'yaml_filename': map_yaml_path, 'use_sim_time': True}],
)
map_server_lifecycle = Node(
package='nav2_lifecycle_manager',
executable='lifecycle_manager',
name='lifecycle_manager_map',
output='screen',
parameters=[{'use_sim_time': True, 'autostart': True,
'node_names': ['map_server']}],
)
# =============================4.slam_toolbox定位 + 实时建图=============================================
# ⚠️ /map 重映射到 /slam_map避免覆盖 map_server 的全量地图
slam_toolbox_node = Node(
package='slam_toolbox',
executable='async_slam_toolbox_node',
name='slam_toolbox',
output='screen',
parameters=[slam_params_file, {'use_sim_time': True}],
remappings=[('/map', '/slam_map')],
)
# =============================5.加载已有序列化地图=======================================================
# 通过 ros2 service call 在 slam_toolbox 启动后加载
import launch
load_map_cmd = ExecuteProcess(
cmd=[
'bash', '-c',
# 等待 slam_toolbox 服务就绪后加载地图
'sleep 8 && '
'ros2 service call /slam_toolbox/deserialize_map '
'slam_toolbox/srv/DeserializePoseGraph '
"'{filename: \"%s\", match_type: 1}'" % posegraph_path,
],
output='screen',
)
# =============================6.Nav2 导航栈============================================================
navigation_launch = IncludeLaunchDescription(
PythonLaunchDescriptionSource(
[nav2_bringup_dir, '/launch', '/navigation_launch.py']),
launch_arguments={
'use_sim_time': use_sim_time,
'params_file': nav2_param_path,
}.items(),
)
# =============================7.Gazebo 仿真============================================================
robot_name_in_model = 'mycar'
default_model_path = os.path.join(origincar_urdf_dir, 'urdf', 'origincar.urdf')
model = DeclareLaunchArgument(name='model', default_value=default_model_path)
gazebo_world_path = os.path.join(origincar_urdf_dir, 'world', 'zhihui.world')
start_gazebo_cmd = ExecuteProcess(
cmd=['gazebo', '--verbose',
'-s', 'libgazebo_ros_init.so',
'-s', 'libgazebo_ros_factory.so',
gazebo_world_path],
output='screen',
)
# =============================7a.机器人初始位姿参数=====================================================
# 通过命令行参数覆盖,例如:
# ros2 launch ... spawn_x:=1.0 spawn_y:=-2.0 spawn_yaw:=1.57
spawn_x = LaunchConfiguration('spawn_x', default='-4.311092')
spawn_y = LaunchConfiguration('spawn_y', default='-4.299756')
spawn_z = LaunchConfiguration('spawn_z', default='0.0')
spawn_yaw = LaunchConfiguration('spawn_yaw', default='0.0')
set_spawn_x = SetEnvironmentVariable('SPAWN_X', spawn_x)
set_spawn_y = SetEnvironmentVariable('SPAWN_Y', spawn_y)
set_spawn_z = SetEnvironmentVariable('SPAWN_Z', spawn_z)
set_spawn_yaw = SetEnvironmentVariable('SPAWN_YAW', spawn_yaw)
# =============================7b.在 Gazebo 中生成机器人=================================================
# 通过 bash 读取环境变量,确保位姿参数正确传递
spawn_entity_cmd = ExecuteProcess(
cmd=['bash', '-c',
'ros2 run gazebo_ros spawn_entity.py '
'-entity mycar '
f'-file {default_model_path} '
'-x $SPAWN_X -y $SPAWN_Y -z $SPAWN_Z -Y $SPAWN_YAW'],
output='screen',
)
robot_description = ParameterValue(
Command(['xacro ', LaunchConfiguration('model')]), value_type=str,
)
robot_state_publisher = Node(
package='robot_state_publisher',
executable='robot_state_publisher',
parameters=[{'robot_description': robot_description,
'use_sim_time': True, 'publish_frequency': 30.0}],
)
# =============================8.组装==================================================================
ld.add_action(model)
ld.add_action(DeclareLaunchArgument(
'spawn_x', default_value='-4.311092',
description='机器人初始 x 坐标m'))
ld.add_action(DeclareLaunchArgument(
'spawn_y', default_value='-4.299756',
description='机器人初始 y 坐标m'))
ld.add_action(DeclareLaunchArgument(
'spawn_z', default_value='0.0',
description='机器人初始 z 坐标m'))
ld.add_action(DeclareLaunchArgument(
'spawn_yaw', default_value='0.0',
description='机器人初始偏航角rad'))
ld.add_action(start_gazebo_cmd)
ld.add_action(set_spawn_x)
ld.add_action(set_spawn_y)
ld.add_action(set_spawn_z)
ld.add_action(set_spawn_yaw)
ld.add_action(spawn_entity_cmd)
ld.add_action(robot_state_publisher)
ld.add_action(map_server_node)
ld.add_action(map_server_lifecycle)
ld.add_action(slam_toolbox_node)
ld.add_action(load_map_cmd)
ld.add_action(navigation_launch)
return ld

View File

@@ -0,0 +1,80 @@
# ============================================================================
# gc_nav2_with_slam_online_real.launch.py
# 功能:真机实时建图 — slam_toolbox 从零建图 + Nav2 导航
# ============================================================================
import os
from ament_index_python.packages import get_package_share_directory
from launch import LaunchDescription
from launch.actions import IncludeLaunchDescription, DeclareLaunchArgument
from launch.launch_description_sources import PythonLaunchDescriptionSource
from launch.substitutions import LaunchConfiguration
from launch_ros.actions import Node
from launch_ros.parameter_descriptions import ParameterValue
from launch.substitutions import Command
def generate_launch_description():
"""真机实时建图slam_toolbox 从零建图 + Nav2 导航"""
ld = LaunchDescription()
# === 1. 包路径 ===
pkg_dir = get_package_share_directory('gc_navigation2_slamtoolbox')
nav2_bringup_dir = get_package_share_directory('nav2_bringup')
origincar_urdf_dir = get_package_share_directory('origincar_description')
# === 2. 参数 ===
use_sim_time = LaunchConfiguration('use_sim_time', default='false')
nav2_param_path = LaunchConfiguration('params_file', default=os.path.join(
pkg_dir, 'params', 'gc_navigation_slam.yaml'))
slam_params_file = os.path.join(pkg_dir, 'config', 'slam_toolbox_mapping.yaml')
# === 3. slam_toolbox实时建图 → 直接发布到 /map ===
slam_toolbox_node = Node(
package='slam_toolbox',
executable='async_slam_toolbox_node',
name='slam_toolbox',
output='screen',
parameters=[slam_params_file,
{'use_sim_time': use_sim_time}],
)
# === 4. Nav2 导航栈 ===
navigation_launch = IncludeLaunchDescription(
PythonLaunchDescriptionSource(
[nav2_bringup_dir, '/launch', '/navigation_launch.py']),
launch_arguments={
'use_sim_time': use_sim_time,
'params_file': nav2_param_path,
}.items(),
)
# === 5. 机器人模型 + TF ===
model = DeclareLaunchArgument(
name='model',
default_value=os.path.join(origincar_urdf_dir, 'urdf', 'origincar.urdf'))
robot_description = ParameterValue(
Command(['xacro ', LaunchConfiguration('model')]), value_type=str)
robot_state_publisher = Node(
package='robot_state_publisher',
executable='robot_state_publisher',
parameters=[{'robot_description': robot_description,
'use_sim_time': use_sim_time, 'publish_frequency': 30.0}],
)
base_footprint_tf = Node(
package='tf2_ros',
executable='static_transform_publisher',
name='base_footprint_to_base_link',
arguments=['0', '0', '0', '0', '0', '0', 'base_footprint', 'base_link'],
)
# === 6. 组装 ===
ld.add_action(model)
ld.add_action(robot_state_publisher)
ld.add_action(base_footprint_tf)
ld.add_action(slam_toolbox_node)
ld.add_action(navigation_launch)
return ld

View File

@@ -0,0 +1,25 @@
#!/usr/bin/env python3
from launch import LaunchDescription
from launch_ros.actions import Node
from ament_index_python.packages import get_package_share_directory
import os
def generate_launch_description():
# 获取参数文件路径
pkg_share = get_package_share_directory('gc_navigation2_slamtoolbox')
params_file = os.path.join(
pkg_share, 'config', 'mapper_params_lifelong.yaml')
# 创建SLAM Toolbox节点
slam_toolbox_node = Node(
package='slam_toolbox',
executable='async_slam_toolbox_node', # 或 sync_slam_toolbox_node
name='slam_toolbox',
output='screen',
parameters=[params_file]
)
return LaunchDescription([
slam_toolbox_node
])

View File

@@ -0,0 +1,25 @@
#!/usr/bin/env python3
from launch import LaunchDescription
from launch_ros.actions import Node
from ament_index_python.packages import get_package_share_directory
import os
def generate_launch_description():
# 获取参数文件路径
pkg_share = get_package_share_directory('gc_navigation2_slamtoolbox')
params_file = os.path.join(
pkg_share, 'config', 'mapper_params_localization.yaml')
# 创建SLAM Toolbox节点
slam_toolbox_node = Node(
package='slam_toolbox',
executable='localization_slam_toolbox_node', # 或 sync_slam_toolbox_node
name='slam_toolbox',
output='screen',
parameters=[params_file]
)
return LaunchDescription([
slam_toolbox_node
])

View File

@@ -0,0 +1,25 @@
#!/usr/bin/env python3
from launch import LaunchDescription
from launch_ros.actions import Node
from ament_index_python.packages import get_package_share_directory
import os
def generate_launch_description():
# 获取参数文件路径
pkg_share = get_package_share_directory('gc_navigation2_slamtoolbox')
params_file = os.path.join(
pkg_share, 'config', 'mapper_params_online_async.yaml')
# 创建SLAM Toolbox节点
slam_toolbox_node = Node(
package='slam_toolbox',
executable='async_slam_toolbox_node', # 或 sync_slam_toolbox_node
name='slam_toolbox',
output='screen',
parameters=[params_file]
)
return LaunchDescription([
slam_toolbox_node
])

View File

@@ -0,0 +1,196 @@
#!/usr/bin/env python3
# ============================================================================
# gc_slam_mapping.launch.py
# 功能Gazebo 仿真环境 + SLAM 建图启动文件
#
# 适用场景:
# - 在 Gazebo 仿真中遥控机器人建立环境地图
# - 在已有地图基础上增量更新
# - 单独调试 slam_toolbox 建图参数
#
# 架构:
# Gazebo 仿真器 — 加载 zhihui.world智慧楼墙体环境
# spawn_entity — 在 Gazebo 中生成机器人模型
# robot_state_publisher — 发布机器人 TF 树URDF 模型)
# joint_state_publisher — 发布关节状态
# async_slam_toolbox_node — 激光 SLAM 建图mapping 模式)
# 发布 map→odom TF
# 发布 /map 话题(实时地图)
#
# 使用方式:
# ros2 launch gc_navigation2_slamtoolbox gc_slam_mapping.launch.py
#
# 保存地图:
# ros2 service call /slam_toolbox/serialize_map slam_toolbox/srv/SerializePoseGraph \
# "{filename: '/home/guoch/test_ws/src/gc_navigation2_slamtoolbox/maps/my_map'}"
# ros2 run nav2_map_server map_saver_cli -f <map_name>
# ============================================================================
import os
from ament_index_python.packages import get_package_share_directory
from launch import LaunchDescription
from launch.actions import DeclareLaunchArgument, ExecuteProcess, SetEnvironmentVariable
from launch.substitutions import LaunchConfiguration
from launch_ros.actions import Node
from launch_ros.parameter_descriptions import ParameterValue
from launch.substitutions import Command
def generate_launch_description():
"""生成 LaunchDescription启动 Gazebo + slam_toolbox 建图"""
# ============================ 1. 包路径 =========================================
pkg_dir = get_package_share_directory('gc_navigation2_slamtoolbox')
origincar_urdf_dir = get_package_share_directory('origincar_description')
# ============================ 2. 声明启动参数 ====================================
use_sim_time = LaunchConfiguration('use_sim_time', default='true')
# slam_params_file: slam_toolbox 配置文件
slam_params_file = LaunchConfiguration(
'slam_params_file',
default=os.path.join(pkg_dir, 'config', 'slam_toolbox_async.yaml'))
# map_file_name: 可选,加载已有序列化地图继续建图
map_file_name = LaunchConfiguration('map_file_name', default='')
# model: 机器人 URDF 模型路径(用于 xacro 处理)
# origincar.urdf 是纯 URDF不含 xacro 宏xacro 会原样透传
default_model_path = os.path.join(
origincar_urdf_dir, 'urdf', 'origincar.urdf')
model = DeclareLaunchArgument(
name='model', default_value=default_model_path)
# spawn_model: Gazebo 中生成机器人用的 URDF不含 xacro 宏)
spawn_model_path = os.path.join(
origincar_urdf_dir, 'urdf', 'origincar.urdf')
# ============================ 3. 设置 GAZEBO_MODEL_PATH ==========================
# 让 Gazebo 能找到 zhihui 模型,同时保留标准模型路径
gazebo_model_path = os.path.join(pkg_dir, 'world')
existing_gazebo_path = os.environ.get('GAZEBO_MODEL_PATH', '')
if existing_gazebo_path:
full_gazebo_path = f'{gazebo_model_path}:{existing_gazebo_path}'
else:
full_gazebo_path = gazebo_model_path
set_gazebo_model_path = SetEnvironmentVariable(
name='GAZEBO_MODEL_PATH',
value=full_gazebo_path
)
# ============================ 4. 启动 Gazebo 仿真器 ==============================
gazebo_world_path = os.path.join(pkg_dir, 'world', 'zhihui.world')
start_gazebo_cmd = ExecuteProcess(
cmd=['gazebo', '--verbose',
'-s', 'libgazebo_ros_init.so',
'-s', 'libgazebo_ros_factory.so',
gazebo_world_path],
output='screen'
)
# ============================ 5. 机器人初始位姿参数 ==============================
# 通过命令行参数覆盖,例如:
# ros2 launch ... spawn_x:=1.0 spawn_y:=-2.0 spawn_yaw:=1.57
spawn_x = LaunchConfiguration('spawn_x', default='-4.311092')
spawn_y = LaunchConfiguration('spawn_y', default='-4.299756')
spawn_z = LaunchConfiguration('spawn_z', default='0.0')
spawn_yaw = LaunchConfiguration('spawn_yaw', default='0.0')
# 将位姿参数设为环境变量,供 spawn 命令使用
set_spawn_x = SetEnvironmentVariable('SPAWN_X', spawn_x)
set_spawn_y = SetEnvironmentVariable('SPAWN_Y', spawn_y)
set_spawn_z = SetEnvironmentVariable('SPAWN_Z', spawn_z)
set_spawn_yaw = SetEnvironmentVariable('SPAWN_YAW', spawn_yaw)
# ============================ 6. 在 Gazebo 中生成机器人 ==========================
# 通过 bash 读取环境变量,确保位姿参数正确传递
robot_name_in_model = 'mycar'
spawn_entity_cmd = ExecuteProcess(
cmd=['bash', '-c',
'ros2 run gazebo_ros spawn_entity.py '
'-entity mycar '
f'-file {spawn_model_path} '
'-x $SPAWN_X -y $SPAWN_Y -z $SPAWN_Z -Y $SPAWN_YAW'],
output='screen'
)
# ============================ 7. robot_state_publisher ===========================
robot_description = ParameterValue(
Command(['xacro ', LaunchConfiguration('model')]),
value_type=str
)
robot_state_publisher_node = Node(
package='robot_state_publisher',
executable='robot_state_publisher',
name='robot_state_publisher',
output='screen',
parameters=[{
'robot_description': robot_description,
'use_sim_time': True,
'publish_frequency': 30.0,
}],
)
# ============================ 8. joint_state_publisher ===========================
joint_state_publisher_node = Node(
package='joint_state_publisher',
executable='joint_state_publisher',
name='joint_state_publisher',
output='screen',
parameters=[{'use_sim_time': use_sim_time}],
)
# ============================ 9. slam_toolbox 建图节点 ============================
slam_toolbox_node = Node(
package='slam_toolbox',
executable='async_slam_toolbox_node',
name='slam_toolbox',
output='screen',
parameters=[
slam_params_file,
{
'use_sim_time': use_sim_time,
'map_file_name': map_file_name,
},
],
)
# ============================ 10. 组装 LaunchDescription =========================
return LaunchDescription([
DeclareLaunchArgument(
'use_sim_time',
default_value='true',
description='使用仿真时间Gazebo=true, 实车=false)'),
DeclareLaunchArgument(
'slam_params_file',
default_value=os.path.join(pkg_dir, 'config', 'slam_toolbox_async.yaml'),
description='slam_toolbox 参数配置文件路径'),
DeclareLaunchArgument(
'map_file_name',
default_value='',
description='已有序列化地图路径(.posegraph留空则从零开始建图'),
DeclareLaunchArgument(
'spawn_x', default_value='-4.311092',
description='机器人初始 x 坐标m'),
DeclareLaunchArgument(
'spawn_y', default_value='-4.299756',
description='机器人初始 y 坐标m'),
DeclareLaunchArgument(
'spawn_z', default_value='0.0',
description='机器人初始 z 坐标m'),
DeclareLaunchArgument(
'spawn_yaw', default_value='0.0',
description='机器人初始偏航角rad'),
model,
set_gazebo_model_path,
set_spawn_x,
set_spawn_y,
set_spawn_z,
set_spawn_yaw,
start_gazebo_cmd,
spawn_entity_cmd,
robot_state_publisher_node,
joint_state_publisher_node,
slam_toolbox_node,
])

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@@ -0,0 +1,7 @@
image: my_map.pgm
mode: trinary
resolution: 0.05
origin: [-2.15, -5.81, 0]
negate: 0
occupied_thresh: 0.65
free_thresh: 0.25

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@@ -0,0 +1,7 @@
image: zhihui.pgm
mode: trinary
resolution: 0.05
origin: [-4.98, -4.71, 0]
negate: 0
occupied_thresh: 0.65
free_thresh: 0.25

View File

@@ -0,0 +1,18 @@
<?xml version="1.0"?>
<?xml-model href="http://download.ros.org/schema/package_format3.xsd" schematypens="http://www.w3.org/2001/XMLSchema"?>
<package format="3">
<name>gc_navigation2_slamtoolbox</name>
<version>0.0.0</version>
<description>TODO: Package description</description>
<maintainer email="guoch@todo.todo">guoch</maintainer>
<license>TODO: License declaration</license>
<buildtool_depend>ament_cmake</buildtool_depend>
<test_depend>ament_lint_auto</test_depend>
<test_depend>ament_lint_common</test_depend>
<export>
<build_type>ament_cmake</build_type>
</export>
</package>

View File

@@ -0,0 +1,413 @@
amcl:
ros__parameters:
use_sim_time: True
alpha1: 0.2
alpha2: 0.2
alpha3: 0.2
alpha4: 0.2
alpha5: 0.2
base_frame_id: "base_link"
beam_skip_distance: 0.5
beam_skip_error_threshold: 0.9
beam_skip_threshold: 0.3
do_beamskip: false
global_frame_id: "map"
lambda_short: 0.1
laser_likelihood_max_dist: 2.0
laser_max_range: 100.0
laser_min_range: -1.0
laser_model_type: "likelihood_field"
max_beams: 60
max_particles: 2000
min_particles: 500
odom_frame_id: "odom"
pf_err: 0.05
pf_z: 0.99
recovery_alpha_fast: 0.0
recovery_alpha_slow: 0.0
resample_interval: 1
robot_model_type: "nav2_amcl::DifferentialMotionModel"
save_pose_rate: 0.5
sigma_hit: 0.2
tf_broadcast: true
transform_tolerance: 10.0
update_min_a: 0.2
update_min_d: 0.25
z_hit: 0.5
z_max: 0.05
z_rand: 0.5
z_short: 0.05
scan_topic: scan
amcl_map_client:
ros__parameters:
use_sim_time: True
amcl_rclcpp_node:
ros__parameters:
use_sim_time: True
bt_navigator:
ros__parameters:
use_sim_time: True
global_frame: map
robot_base_frame: base_link
odom_topic: /odom
bt_loop_duration: 20
default_server_timeout: 20
# 'default_nav_through_poses_bt_xml' and 'default_nav_to_pose_bt_xml' are use defaults:
# nav2_bt_navigator/navigate_to_pose_w_replanning_and_recovery.xml
# nav2_bt_navigator/navigate_through_poses_w_replanning_and_recovery.xml
# They can be set here or via a RewrittenYaml remap from a parent launch file to Nav2.
plugin_lib_names:
- nav2_compute_path_to_pose_action_bt_node
- nav2_compute_path_through_poses_action_bt_node
- nav2_smooth_path_action_bt_node
- nav2_follow_path_action_bt_node
- nav2_spin_action_bt_node
- nav2_wait_action_bt_node
- nav2_back_up_action_bt_node
- nav2_drive_on_heading_bt_node
- nav2_clear_costmap_service_bt_node
- nav2_is_stuck_condition_bt_node
- nav2_goal_reached_condition_bt_node
- nav2_goal_updated_condition_bt_node
- nav2_globally_updated_goal_condition_bt_node
- nav2_is_path_valid_condition_bt_node
- nav2_initial_pose_received_condition_bt_node
- nav2_reinitialize_global_localization_service_bt_node
- nav2_rate_controller_bt_node
- nav2_distance_controller_bt_node
- nav2_speed_controller_bt_node
- nav2_truncate_path_action_bt_node
- nav2_truncate_path_local_action_bt_node
- nav2_goal_updater_node_bt_node
- nav2_recovery_node_bt_node
- nav2_pipeline_sequence_bt_node
- nav2_round_robin_node_bt_node
- nav2_transform_available_condition_bt_node
- nav2_time_expired_condition_bt_node
- nav2_path_expiring_timer_condition
- nav2_distance_traveled_condition_bt_node
- nav2_single_trigger_bt_node
- nav2_is_battery_low_condition_bt_node
- nav2_navigate_through_poses_action_bt_node
- nav2_navigate_to_pose_action_bt_node
- nav2_remove_passed_goals_action_bt_node
- nav2_planner_selector_bt_node
- nav2_controller_selector_bt_node
- nav2_goal_checker_selector_bt_node
- nav2_controller_cancel_bt_node
- nav2_path_longer_on_approach_bt_node
- nav2_wait_cancel_bt_node
- nav2_spin_cancel_bt_node
- nav2_back_up_cancel_bt_node
- nav2_drive_on_heading_cancel_bt_node
bt_navigator_rclcpp_node:
ros__parameters:
use_sim_time: True
controller_server:
ros__parameters:
use_sim_time: True
controller_frequency: 30.0
FollowPath:
plugin: "nav2_mppi_controller::MPPIController"
time_steps: 56
model_dt: 0.05
batch_size: 2000
vx_std: 0.2
vy_std: 0.0
wz_std: 0.4
vx_max: 0.5
vx_min: -0.35
vy_max: 0.0
wz_max: 1.9
iteration_count: 1
temperature: 0.3
gamma: 0.015
motion_model: "Ackermann"
visualize: false
TrajectoryVisualizer:
trajectory_step: 5
time_step: 3
AckermannConstraints:
min_turning_r: 0.4
critics: ["ConstraintCritic", "CostCritic", "GoalCritic", "GoalAngleCritic", "PathAlignCritic", "PathFollowCritic", "PathAngleCritic", "PreferForwardCritic"]
ConstraintCritic:
enabled: true
cost_power: 1
cost_weight: 4.0
GoalCritic:
enabled: true
cost_power: 1
cost_weight: 5.0
threshold_to_consider: 1.4
GoalAngleCritic:
enabled: true
cost_power: 1
cost_weight: 3.0
threshold_to_consider: 0.5
PreferForwardCritic:
enabled: true
cost_power: 1
cost_weight: 5.0
threshold_to_consider: 0.5
# Option to replace Cost and use Obstacles instead
# ObstaclesCritic:
# enabled: true
# cost_power: 1
# repulsion_weight: 1.5
# critical_weight: 20.0
# consider_footprint: false
# collision_cost: 10000.0
# collision_margin_distance: 0.1
# near_goal_distance: 0.5
CostCritic:
enabled: true
cost_power: 1
cost_weight: 3.81
critical_cost: 300.0
consider_footprint: true
collision_cost: 1000000.0
near_goal_distance: 1.0
trajectory_point_step: 2
PathAlignCritic:
enabled: true
cost_power: 1
cost_weight: 14.0
max_path_occupancy_ratio: 0.05
trajectory_point_step: 4
threshold_to_consider: 0.5
offset_from_furthest: 20
use_path_orientations: false
PathFollowCritic:
enabled: true
cost_power: 1
cost_weight: 5.0
offset_from_furthest: 5
threshold_to_consider: 1.4
PathAngleCritic:
enabled: true
cost_power: 1
cost_weight: 2.0
offset_from_furthest: 4
threshold_to_consider: 0.5
max_angle_to_furthest: 1.0
forward_preference: true
# VelocityDeadbandCritic:
# enabled: true
# cost_power: 1
# cost_weight: 35.0
# deadband_velocities: [0.05, 0.05, 0.05]
# TwirlingCritic:
# enabled: true
# twirling_cost_power: 1
# twirling_cost_weight: 10.0
controller_server_rclcpp_node:
ros__parameters:
use_sim_time: True
local_costmap:
local_costmap:
ros__parameters:
update_frequency: 5.0
publish_frequency: 2.0
transform_tolerance: 0.5
global_frame: odom
robot_base_frame: base_link
use_sim_time: True
rolling_window: true
width: 3
height: 3
resolution: 0.05
footprint: "[[0.14, 0.085],
[0.14, -0.085],
[-0.14, -0.085],
[-0.14, 0.085]]"
footprint_padding: 0.02
plugins: ["voxel_layer", "inflation_layer"]
inflation_layer:
plugin: "nav2_costmap_2d::InflationLayer"
cost_scaling_factor: 3.0
inflation_radius: 0.55
voxel_layer:
plugin: "nav2_costmap_2d::VoxelLayer"
enabled: True
publish_voxel_map: True
origin_z: 0.0
z_resolution: 0.05
z_voxels: 16
max_obstacle_height: 2.0
mark_threshold: 0
observation_sources: scan
scan:
topic: /scan
max_obstacle_height: 2.0
clearing: True
marking: True
data_type: "LaserScan"
raytrace_max_range: 3.0
raytrace_min_range: 0.0
obstacle_max_range: 2.5
obstacle_min_range: 0.0
static_layer:
map_subscribe_transient_local: True
always_send_full_costmap: True
local_costmap_client:
ros__parameters:
use_sim_time: True
local_costmap_rclcpp_node:
ros__parameters:
use_sim_time: True
global_costmap:
global_costmap:
ros__parameters:
use_sim_time: True
transform_tolerance: 0.5
update_frequency: 1.0
publish_frequency: 1.0
global_frame: map
robot_base_frame: base_link
use_sim_time: True
footprint: "[[0.14, 0.085],
[0.14, -0.085],
[-0.14, -0.085],
[-0.14, 0.085]]"
footprint_padding: 0.02
resolution: 0.05
track_unknown_space: true
plugins: ["static_layer", "obstacle_layer", "inflation_layer"]
obstacle_layer:
plugin: "nav2_costmap_2d::ObstacleLayer"
enabled: True
observation_sources: scan
scan:
topic: /scan
max_obstacle_height: 2.0
clearing: True
marking: True
data_type: "LaserScan"
raytrace_max_range: 3.0
raytrace_min_range: 0.0
obstacle_max_range: 2.5
obstacle_min_range: 0.0
static_layer:
plugin: "nav2_costmap_2d::StaticLayer"
map_subscribe_transient_local: True
inflation_layer:
plugin: "nav2_costmap_2d::InflationLayer"
cost_scaling_factor: 3.0
inflation_radius: 0.55
always_send_full_costmap: True
global_costmap_client:
ros__parameters:
use_sim_time: True
global_costmap_rclcpp_node:
ros__parameters:
use_sim_time: True
map_server:
ros__parameters:
use_sim_time: True
yaml_filename: "turtlebot3_world.yaml"
map_saver:
ros__parameters:
use_sim_time: True
save_map_timeout: 5.0
free_thresh_default: 0.25
occupied_thresh_default: 0.65
map_subscribe_transient_local: True
planner_server:
ros__parameters:
planner_plugins: ["GridBased"]
use_sim_time: True
GridBased:
plugin: "nav2_smac_planner/SmacPlannerHybrid"
downsample_costmap: false # whether or not to downsample the map
downsampling_factor: 1 # multiplier for the resolution of the costmap layer (e.g. 2 on a 5cm costmap would be 10cm)
tolerance: 0.25 # dist-to-goal heuristic cost (distance) for valid tolerance endpoints if exact goal cannot be found.
allow_unknown: true # allow traveling in unknown space
max_iterations: 1000000 # maximum total iterations to search for before failing (in case unreachable), set to -1 to disable
max_on_approach_iterations: 1000 # Maximum number of iterations after within tolerances to continue to try to find exact solution
max_planning_time: 5.0 # max time in s for planner to plan, smooth
motion_model_for_search: "REEDS_SHEPP" # or REEDS_SHEPP 可以倒车
angle_quantization_bins: 72 # Number of angle bins for search
analytic_expansion_ratio: 3.5 # The ratio to attempt analytic expansions during search for final approach.
analytic_expansion_max_length: 3.0 # For Hybrid/Lattice nodes: The maximum length of the analytic expansion to be considered valid to prevent unsafe shortcutting
minimum_turning_radius: 0.40 # minimum turning radius in m of path / vehicle
reverse_penalty: 2.0 # Penalty to apply if motion is reversing, must be => 1
change_penalty: 0.0 # Penalty to apply if motion is changing directions (L to R), must be >= 0
non_straight_penalty: 1.2 # Penalty to apply if motion is non-straight, must be => 1
cost_penalty: 2.0 # Penalty to apply to higher cost areas when adding into the obstacle map dynamic programming distance expansion heuristic. This drives the robot more towards the center of passages. A value between 1.3 - 3.5 is reasonable.
retrospective_penalty: 0.015
lookup_table_size: 20.0 # Size of the dubin/reeds-sheep distance window to cache, in meters.
cache_obstacle_heuristic: false # Cache the obstacle map dynamic programming distance expansion heuristic between subsiquent replannings of the same goal location. Dramatically speeds up replanning performance (40x) if costmap is largely static.
viz_expansions: false # For Hybrid nodes: Whether to publish expansions on the /expansions topic as an array of poses (the orientation has no meaning). WARNING: heavy to compute and to display, for debug only as it degrades the performance.
smooth_path: True # If true, does a simple and quick smoothing post-processing to the path
smoother:
max_iterations: 1000
w_smooth: 0.3
w_data: 0.2
tolerance: 1.0e-10
do_refinement: true
refinement_num: 2
planner_server_rclcpp_node:
ros__parameters:
use_sim_time: True
smoother_server:
ros__parameters:
use_sim_time: True
smoother_plugins: ["simple_smoother"]
simple_smoother:
plugin: "nav2_smoother::SimpleSmoother"
tolerance: 1.0e-10
max_its: 1000
do_refinement: True
behavior_server:
ros__parameters:
costmap_topic: local_costmap/costmap_raw
footprint_topic: local_costmap/published_footprint
cycle_frequency: 10.0
behavior_plugins: ["spin", "backup", "wait"]
spin:
plugin: "nav2_behaviors/Spin"
backup:
plugin: "nav2_behaviors/BackUp"
# drive_on_heading:
# plugin: "nav2_behaviors/DriveOnHeading"
wait:
plugin: "nav2_behaviors/Wait"
global_frame: odom
robot_base_frame: base_link
transform_tolerance: 0.5
use_sim_time: True
simulate_ahead_time: 2.0
max_rotational_vel: 1.0
min_rotational_vel: 0.4
rotational_acc_lim: 3.2
robot_state_publisher:
ros__parameters:
use_sim_time: True
waypoint_follower:
ros__parameters:
loop_rate: 20
use_sim_time: True
stop_on_failure: false
waypoint_task_executor_plugin: "wait_at_waypoint"
wait_at_waypoint:
plugin: "nav2_waypoint_follower::WaitAtWaypoint"
enabled: True
waypoint_pause_duration: 200

View File

@@ -0,0 +1,343 @@
slam_toolbox:
ros__parameters:
use_sim_time: False
bt_navigator:
ros__parameters:
use_sim_time: False
global_frame: map
robot_base_frame: base_footprint
odom_topic: /odom
bt_loop_duration: 50
default_server_timeout: 20
# 阿克曼底盘专用 BT移除 Spin恢复行为 = 清代价地图 → 后退 → 等待
default_nav_to_pose_bt_xml: /home/sunrise/yiliao_ws/install/gc_navigation2_slamtoolbox/share/gc_navigation2_slamtoolbox/config/nav_to_pose_ackermann.xml
plugin_lib_names:
- nav2_compute_path_to_pose_action_bt_node
- nav2_compute_path_through_poses_action_bt_node
- nav2_smooth_path_action_bt_node
- nav2_follow_path_action_bt_node
- nav2_spin_action_bt_node
- nav2_wait_action_bt_node
- nav2_back_up_action_bt_node
- nav2_drive_on_heading_bt_node
- nav2_clear_costmap_service_bt_node
- nav2_is_stuck_condition_bt_node
- nav2_goal_reached_condition_bt_node
- nav2_goal_updated_condition_bt_node
- nav2_globally_updated_goal_condition_bt_node
- nav2_is_path_valid_condition_bt_node
- nav2_initial_pose_received_condition_bt_node
- nav2_reinitialize_global_localization_service_bt_node
- nav2_rate_controller_bt_node
- nav2_distance_controller_bt_node
- nav2_speed_controller_bt_node
- nav2_truncate_path_action_bt_node
- nav2_truncate_path_local_action_bt_node
- nav2_goal_updater_node_bt_node
- nav2_recovery_node_bt_node
- nav2_pipeline_sequence_bt_node
- nav2_round_robin_node_bt_node
- nav2_transform_available_condition_bt_node
- nav2_time_expired_condition_bt_node
- nav2_path_expiring_timer_condition
- nav2_distance_traveled_condition_bt_node
- nav2_single_trigger_bt_node
- nav2_is_battery_low_condition_bt_node
- nav2_navigate_through_poses_action_bt_node
- nav2_navigate_to_pose_action_bt_node
- nav2_remove_passed_goals_action_bt_node
- nav2_planner_selector_bt_node
- nav2_controller_selector_bt_node
- nav2_goal_checker_selector_bt_node
- nav2_controller_cancel_bt_node
- nav2_path_longer_on_approach_bt_node
- nav2_wait_cancel_bt_node
- nav2_spin_cancel_bt_node
- nav2_back_up_cancel_bt_node
- nav2_drive_on_heading_cancel_bt_node
bt_navigator_rclcpp_node:
ros__parameters:
use_sim_time: False
controller_server:
ros__parameters:
use_sim_time: False
controller_frequency: 20.0
FollowPath:
plugin: "nav2_mppi_controller::MPPIController"
time_steps: 36
model_dt: 0.05
batch_size: 1000
vx_std: 0.2
vy_std: 0.0
wz_std: 0.4
vx_max: 0.5
vx_min: -0.35
vy_max: 0.0
wz_max: 1.9
iteration_count: 1
temperature: 0.3
gamma: 0.015
motion_model: "Ackermann"
visualize: false
TrajectoryVisualizer:
trajectory_step: 5
time_step: 3
AckermannConstraints:
min_turning_r: 0.4
critics: ["ConstraintCritic", "CostCritic", "GoalCritic", "GoalAngleCritic", "PathAlignCritic", "PathFollowCritic", "PathAngleCritic", "PreferForwardCritic"]
ConstraintCritic:
enabled: true
cost_power: 1
cost_weight: 4.0
GoalCritic:
enabled: true
cost_power: 1
cost_weight: 5.0
threshold_to_consider: 1.4
GoalAngleCritic:
enabled: true
cost_power: 1
cost_weight: 3.0
threshold_to_consider: 0.5
PreferForwardCritic:
enabled: true
cost_power: 1
cost_weight: 5.0
threshold_to_consider: 0.5
CostCritic:
enabled: true
cost_power: 1
cost_weight: 3.81
critical_cost: 300.0
consider_footprint: true
collision_cost: 1000000.0
near_goal_distance: 1.0
trajectory_point_step: 2
PathAlignCritic:
enabled: true
cost_power: 1
cost_weight: 14.0
max_path_occupancy_ratio: 0.05
trajectory_point_step: 4
threshold_to_consider: 0.5
offset_from_furthest: 20
use_path_orientations: false
PathFollowCritic:
enabled: true
cost_power: 1
cost_weight: 5.0
offset_from_furthest: 5
threshold_to_consider: 1.4
PathAngleCritic:
enabled: true
cost_power: 1
cost_weight: 2.0
offset_from_furthest: 4
threshold_to_consider: 0.5
max_angle_to_furthest: 1.0
forward_preference: true
controller_server_rclcpp_node:
ros__parameters:
use_sim_time: False
local_costmap:
local_costmap:
ros__parameters:
update_frequency: 5.0
publish_frequency: 2.0
transform_tolerance: 0.5
global_frame: odom
robot_base_frame: base_link
use_sim_time: False
rolling_window: true
width: 3
height: 3
resolution: 0.05
footprint: "[[0.14, 0.085],
[0.14, -0.085],
[-0.14, -0.085],
[-0.14, 0.085]]"
footprint_padding: 0.02
plugins: ["voxel_layer", "inflation_layer"]
inflation_layer:
plugin: "nav2_costmap_2d::InflationLayer"
cost_scaling_factor: 3.0
inflation_radius: 0.55
voxel_layer:
plugin: "nav2_costmap_2d::VoxelLayer"
enabled: True
publish_voxel_map: True
origin_z: 0.0
z_resolution: 0.05
z_voxels: 16
max_obstacle_height: 2.0
mark_threshold: 0
observation_sources: scan
scan:
topic: /scan
max_obstacle_height: 2.0
clearing: True
marking: True
data_type: "LaserScan"
raytrace_max_range: 3.0
raytrace_min_range: 0.0
obstacle_max_range: 2.5
obstacle_min_range: 0.0
static_layer:
map_subscribe_transient_local: True
always_send_full_costmap: True
local_costmap_client:
ros__parameters:
use_sim_time: False
local_costmap_rclcpp_node:
ros__parameters:
use_sim_time: False
global_costmap:
global_costmap:
ros__parameters:
use_sim_time: False
transform_tolerance: 0.5
update_frequency: 1.0
publish_frequency: 1.0
global_frame: map
robot_base_frame: base_link
use_sim_time: False
footprint: "[[0.14, 0.085],
[0.14, -0.085],
[-0.14, -0.085],
[-0.14, 0.085]]"
footprint_padding: 0.02
resolution: 0.05
track_unknown_space: true
plugins: ["static_layer", "obstacle_layer", "inflation_layer"]
obstacle_layer:
plugin: "nav2_costmap_2d::ObstacleLayer"
enabled: True
observation_sources: scan
scan:
topic: /scan
max_obstacle_height: 2.0
clearing: True
marking: True
data_type: "LaserScan"
raytrace_max_range: 3.0
raytrace_min_range: 0.0
obstacle_max_range: 2.5
obstacle_min_range: 0.0
static_layer:
plugin: "nav2_costmap_2d::StaticLayer"
map_subscribe_transient_local: True
inflation_layer:
plugin: "nav2_costmap_2d::InflationLayer"
cost_scaling_factor: 3.0
inflation_radius: 0.55
always_send_full_costmap: True
global_costmap_client:
ros__parameters:
use_sim_time: False
global_costmap_rclcpp_node:
ros__parameters:
use_sim_time: False
map_saver:
ros__parameters:
use_sim_time: False
save_map_timeout: 5.0
free_thresh_default: 0.25
occupied_thresh_default: 0.65
map_subscribe_transient_local: True
planner_server:
ros__parameters:
planner_plugins: ["GridBased"]
use_sim_time: False
GridBased:
plugin: "nav2_smac_planner/SmacPlannerHybrid"
downsample_costmap: false
downsampling_factor: 1
tolerance: 0.25
allow_unknown: true
max_iterations: 1000000
max_on_approach_iterations: 1000
max_planning_time: 5.0
motion_model_for_search: "REEDS_SHEPP"
angle_quantization_bins: 72
analytic_expansion_ratio: 3.5
analytic_expansion_max_length: 3.0
minimum_turning_radius: 0.40
reverse_penalty: 1.3 # 后退惩罚,越小越愿意后退(默认 2.0,设为 1.3 允许灵活倒车)
change_penalty: 0.0
non_straight_penalty: 1.2
cost_penalty: 2.0
retrospective_penalty: 0.015
lookup_table_size: 20.0
cache_obstacle_heuristic: false
viz_expansions: false
smooth_path: True
smoother:
max_iterations: 1000
w_smooth: 0.3
w_data: 0.2
tolerance: 1.0e-10
do_refinement: true
refinement_num: 2
planner_server_rclcpp_node:
ros__parameters:
use_sim_time: False
smoother_server:
ros__parameters:
use_sim_time: False
smoother_plugins: ["simple_smoother"]
simple_smoother:
plugin: "nav2_smoother::SimpleSmoother"
tolerance: 1.0e-10
max_its: 1000
do_refinement: True
behavior_server:
ros__parameters:
costmap_topic: local_costmap/costmap_raw
footprint_topic: local_costmap/published_footprint
cycle_frequency: 10.0
behavior_plugins: ["spin", "backup", "wait"]
spin:
plugin: "nav2_behaviors/Spin" # 需保留以匹配默认 BT XML
backup:
plugin: "nav2_behaviors/BackUp"
backup_dist: 0.8
backup_speed: 0.18
wait:
plugin: "nav2_behaviors/Wait"
wait_duration: 0.5
global_frame: odom
robot_base_frame: base_link
transform_tolerance: 0.5
use_sim_time: False
simulate_ahead_time: 2.0
max_rotational_vel: 1.0
min_rotational_vel: 0.4
rotational_acc_lim: 3.2
robot_state_publisher:
ros__parameters:
use_sim_time: False
waypoint_follower:
ros__parameters:
loop_rate: 20
use_sim_time: False
stop_on_failure: false
waypoint_task_executor_plugin: "wait_at_waypoint"
wait_at_waypoint:
plugin: "nav2_waypoint_follower::WaitAtWaypoint"
enabled: True
waypoint_pause_duration: 200

View File

@@ -0,0 +1,343 @@
slam_toolbox:
ros__parameters:
use_sim_time: True
bt_navigator:
ros__parameters:
use_sim_time: True
global_frame: map
robot_base_frame: base_footprint
odom_topic: /odom
bt_loop_duration: 50
default_server_timeout: 20
# 阿克曼底盘专用 BT移除 Spin恢复行为 = 清代价地图 → 后退 → 等待
default_nav_to_pose_bt_xml: /home/guoch/test_ws/install/gc_navigation2_slamtoolbox/share/gc_navigation2_slamtoolbox/config/nav_to_pose_ackermann.xml
plugin_lib_names:
- nav2_compute_path_to_pose_action_bt_node
- nav2_compute_path_through_poses_action_bt_node
- nav2_smooth_path_action_bt_node
- nav2_follow_path_action_bt_node
- nav2_spin_action_bt_node
- nav2_wait_action_bt_node
- nav2_back_up_action_bt_node
- nav2_drive_on_heading_bt_node
- nav2_clear_costmap_service_bt_node
- nav2_is_stuck_condition_bt_node
- nav2_goal_reached_condition_bt_node
- nav2_goal_updated_condition_bt_node
- nav2_globally_updated_goal_condition_bt_node
- nav2_is_path_valid_condition_bt_node
- nav2_initial_pose_received_condition_bt_node
- nav2_reinitialize_global_localization_service_bt_node
- nav2_rate_controller_bt_node
- nav2_distance_controller_bt_node
- nav2_speed_controller_bt_node
- nav2_truncate_path_action_bt_node
- nav2_truncate_path_local_action_bt_node
- nav2_goal_updater_node_bt_node
- nav2_recovery_node_bt_node
- nav2_pipeline_sequence_bt_node
- nav2_round_robin_node_bt_node
- nav2_transform_available_condition_bt_node
- nav2_time_expired_condition_bt_node
- nav2_path_expiring_timer_condition
- nav2_distance_traveled_condition_bt_node
- nav2_single_trigger_bt_node
- nav2_is_battery_low_condition_bt_node
- nav2_navigate_through_poses_action_bt_node
- nav2_navigate_to_pose_action_bt_node
- nav2_remove_passed_goals_action_bt_node
- nav2_planner_selector_bt_node
- nav2_controller_selector_bt_node
- nav2_goal_checker_selector_bt_node
- nav2_controller_cancel_bt_node
- nav2_path_longer_on_approach_bt_node
- nav2_wait_cancel_bt_node
- nav2_spin_cancel_bt_node
- nav2_back_up_cancel_bt_node
- nav2_drive_on_heading_cancel_bt_node
bt_navigator_rclcpp_node:
ros__parameters:
use_sim_time: True
controller_server:
ros__parameters:
use_sim_time: True
controller_frequency: 20.0
FollowPath:
plugin: "nav2_mppi_controller::MPPIController"
time_steps: 36
model_dt: 0.05
batch_size: 1000
vx_std: 0.2
vy_std: 0.0
wz_std: 0.4
vx_max: 0.5
vx_min: -0.35
vy_max: 0.0
wz_max: 1.9
iteration_count: 1
temperature: 0.3
gamma: 0.015
motion_model: "Ackermann"
visualize: false
TrajectoryVisualizer:
trajectory_step: 5
time_step: 3
AckermannConstraints:
min_turning_r: 0.4
critics: ["ConstraintCritic", "CostCritic", "GoalCritic", "GoalAngleCritic", "PathAlignCritic", "PathFollowCritic", "PathAngleCritic", "PreferForwardCritic"]
ConstraintCritic:
enabled: true
cost_power: 1
cost_weight: 4.0
GoalCritic:
enabled: true
cost_power: 1
cost_weight: 5.0
threshold_to_consider: 1.4
GoalAngleCritic:
enabled: true
cost_power: 1
cost_weight: 3.0
threshold_to_consider: 0.5
PreferForwardCritic:
enabled: true
cost_power: 1
cost_weight: 5.0
threshold_to_consider: 0.5
CostCritic:
enabled: true
cost_power: 1
cost_weight: 3.81
critical_cost: 300.0
consider_footprint: true
collision_cost: 1000000.0
near_goal_distance: 1.0
trajectory_point_step: 2
PathAlignCritic:
enabled: true
cost_power: 1
cost_weight: 14.0
max_path_occupancy_ratio: 0.05
trajectory_point_step: 4
threshold_to_consider: 0.5
offset_from_furthest: 20
use_path_orientations: false
PathFollowCritic:
enabled: true
cost_power: 1
cost_weight: 5.0
offset_from_furthest: 5
threshold_to_consider: 1.4
PathAngleCritic:
enabled: true
cost_power: 1
cost_weight: 2.0
offset_from_furthest: 4
threshold_to_consider: 0.5
max_angle_to_furthest: 1.0
forward_preference: true
controller_server_rclcpp_node:
ros__parameters:
use_sim_time: True
local_costmap:
local_costmap:
ros__parameters:
update_frequency: 5.0
publish_frequency: 2.0
transform_tolerance: 0.5
global_frame: odom
robot_base_frame: base_link
use_sim_time: True
rolling_window: true
width: 3
height: 3
resolution: 0.05
footprint: "[[0.14, 0.085],
[0.14, -0.085],
[-0.14, -0.085],
[-0.14, 0.085]]"
footprint_padding: 0.02
plugins: ["voxel_layer", "inflation_layer"]
inflation_layer:
plugin: "nav2_costmap_2d::InflationLayer"
cost_scaling_factor: 3.0
inflation_radius: 0.55
voxel_layer:
plugin: "nav2_costmap_2d::VoxelLayer"
enabled: True
publish_voxel_map: True
origin_z: 0.0
z_resolution: 0.05
z_voxels: 16
max_obstacle_height: 2.0
mark_threshold: 0
observation_sources: scan
scan:
topic: /scan
max_obstacle_height: 2.0
clearing: True
marking: True
data_type: "LaserScan"
raytrace_max_range: 3.0
raytrace_min_range: 0.0
obstacle_max_range: 2.5
obstacle_min_range: 0.0
static_layer:
map_subscribe_transient_local: True
always_send_full_costmap: True
local_costmap_client:
ros__parameters:
use_sim_time: True
local_costmap_rclcpp_node:
ros__parameters:
use_sim_time: True
global_costmap:
global_costmap:
ros__parameters:
use_sim_time: True
transform_tolerance: 0.5
update_frequency: 1.0
publish_frequency: 1.0
global_frame: map
robot_base_frame: base_link
use_sim_time: True
footprint: "[[0.14, 0.085],
[0.14, -0.085],
[-0.14, -0.085],
[-0.14, 0.085]]"
footprint_padding: 0.02
resolution: 0.05
track_unknown_space: true
plugins: ["static_layer", "obstacle_layer", "inflation_layer"]
obstacle_layer:
plugin: "nav2_costmap_2d::ObstacleLayer"
enabled: True
observation_sources: scan
scan:
topic: /scan
max_obstacle_height: 2.0
clearing: True
marking: True
data_type: "LaserScan"
raytrace_max_range: 3.0
raytrace_min_range: 0.0
obstacle_max_range: 2.5
obstacle_min_range: 0.0
static_layer:
plugin: "nav2_costmap_2d::StaticLayer"
map_subscribe_transient_local: True
inflation_layer:
plugin: "nav2_costmap_2d::InflationLayer"
cost_scaling_factor: 3.0
inflation_radius: 0.55
always_send_full_costmap: True
global_costmap_client:
ros__parameters:
use_sim_time: True
global_costmap_rclcpp_node:
ros__parameters:
use_sim_time: True
map_saver:
ros__parameters:
use_sim_time: True
save_map_timeout: 5.0
free_thresh_default: 0.25
occupied_thresh_default: 0.65
map_subscribe_transient_local: True
planner_server:
ros__parameters:
planner_plugins: ["GridBased"]
use_sim_time: True
GridBased:
plugin: "nav2_smac_planner/SmacPlannerHybrid"
downsample_costmap: false
downsampling_factor: 1
tolerance: 0.25
allow_unknown: true
max_iterations: 1000000
max_on_approach_iterations: 1000
max_planning_time: 5.0
motion_model_for_search: "REEDS_SHEPP"
angle_quantization_bins: 72
analytic_expansion_ratio: 3.5
analytic_expansion_max_length: 3.0
minimum_turning_radius: 0.40
reverse_penalty: 1.3 # 后退惩罚,越小越愿意后退(默认 2.0,设为 1.3 允许灵活倒车)
change_penalty: 0.0
non_straight_penalty: 1.2
cost_penalty: 2.0
retrospective_penalty: 0.015
lookup_table_size: 20.0
cache_obstacle_heuristic: false
viz_expansions: false
smooth_path: True
smoother:
max_iterations: 1000
w_smooth: 0.3
w_data: 0.2
tolerance: 1.0e-10
do_refinement: true
refinement_num: 2
planner_server_rclcpp_node:
ros__parameters:
use_sim_time: True
smoother_server:
ros__parameters:
use_sim_time: True
smoother_plugins: ["simple_smoother"]
simple_smoother:
plugin: "nav2_smoother::SimpleSmoother"
tolerance: 1.0e-10
max_its: 1000
do_refinement: True
behavior_server:
ros__parameters:
costmap_topic: local_costmap/costmap_raw
footprint_topic: local_costmap/published_footprint
cycle_frequency: 10.0
behavior_plugins: ["spin", "backup", "wait"]
spin:
plugin: "nav2_behaviors/Spin" # 需保留以匹配默认 BT XML
backup:
plugin: "nav2_behaviors/BackUp"
backup_dist: 0.8
backup_speed: 0.18
wait:
plugin: "nav2_behaviors/Wait"
wait_duration: 0.5
global_frame: odom
robot_base_frame: base_link
transform_tolerance: 0.5
use_sim_time: True
simulate_ahead_time: 2.0
max_rotational_vel: 1.0
min_rotational_vel: 0.4
rotational_acc_lim: 3.2
robot_state_publisher:
ros__parameters:
use_sim_time: True
waypoint_follower:
ros__parameters:
loop_rate: 20
use_sim_time: True
stop_on_failure: false
waypoint_task_executor_plugin: "wait_at_waypoint"
wait_at_waypoint:
plugin: "nav2_waypoint_follower::WaitAtWaypoint"
enabled: True
waypoint_pause_duration: 200

View File

@@ -0,0 +1,11 @@
<?xml version="1.0" ?>
<model>
<name>zhihui</name>
<version>1.0</version>
<sdf version="1.7">model.sdf</sdf>
<author>
<name></name>
<email></email>
</author>
<description></description>
</model>

View File

@@ -0,0 +1,471 @@
<?xml version='1.0'?>
<sdf version='1.7'>
<model name='zhihui'>
<pose>-2.11635 -1.73906 0 0 -0 0</pose>
<link name='Wall_12'>
<collision name='Wall_12_Collision'>
<geometry>
<box>
<size>1.75 0.15 2.5</size>
</box>
</geometry>
<pose>0 0 1.25 0 -0 0</pose>
</collision>
<visual name='Wall_12_Visual'>
<pose>0 0 1.25 0 -0 0</pose>
<geometry>
<box>
<size>1.75 0.15 2.5</size>
</box>
</geometry>
<material>
<script>
<uri>file://media/materials/scripts/gazebo.material</uri>
<name>Gazebo/Grey</name>
</script>
<ambient>1 1 1 1</ambient>
</material>
<meta>
<layer>0</layer>
</meta>
</visual>
<pose>-1.61999 -0.744014 0 0 -0 0</pose>
</link>
<link name='Wall_15'>
<collision name='Wall_15_Collision'>
<geometry>
<box>
<size>2.75 0.15 2.5</size>
</box>
</geometry>
<pose>0 0 1.25 0 -0 0</pose>
</collision>
<visual name='Wall_15_Visual'>
<pose>0 0 1.25 0 -0 0</pose>
<geometry>
<box>
<size>2.75 0.15 2.5</size>
</box>
</geometry>
<material>
<script>
<uri>file://media/materials/scripts/gazebo.material</uri>
<name>Gazebo/Grey</name>
</script>
<ambient>1 1 1 1</ambient>
</material>
<meta>
<layer>0</layer>
</meta>
</visual>
<pose>1.62754 -0.744014 0 0 -0 0</pose>
</link>
<link name='Wall_17'>
<collision name='Wall_17_Collision'>
<geometry>
<box>
<size>1 0.15 2.5</size>
</box>
</geometry>
<pose>0 0 1.25 0 -0 0</pose>
</collision>
<visual name='Wall_17_Visual'>
<pose>0 0 1.25 0 -0 0</pose>
<geometry>
<box>
<size>1 0.15 2.5</size>
</box>
</geometry>
<material>
<script>
<uri>file://media/materials/scripts/gazebo.material</uri>
<name>Gazebo/Grey</name>
</script>
<ambient>1 1 1 1</ambient>
</material>
<meta>
<layer>0</layer>
</meta>
</visual>
<pose>-0.827543 -0.3078 0 0 -0 1.5708</pose>
</link>
<link name='Wall_19'>
<collision name='Wall_19_Collision'>
<geometry>
<box>
<size>1 0.15 2.5</size>
</box>
</geometry>
<pose>0 0 1.25 0 -0 0</pose>
</collision>
<visual name='Wall_19_Visual'>
<pose>0 0 1.25 0 -0 0</pose>
<geometry>
<box>
<size>1 0.15 2.5</size>
</box>
</geometry>
<material>
<script>
<uri>file://media/materials/scripts/gazebo.material</uri>
<name>Gazebo/Grey</name>
</script>
<ambient>1 1 1 1</ambient>
</material>
<meta>
<layer>0</layer>
</meta>
</visual>
<pose>0.327543 -0.319014 0 0 -0 1.5708</pose>
</link>
<link name='Wall_2'>
<collision name='Wall_2_Collision'>
<geometry>
<box>
<size>5 0.15 2.5</size>
</box>
</geometry>
<pose>0 0 1.25 0 -0 0</pose>
</collision>
<visual name='Wall_2_Visual'>
<pose>0 0 1.25 0 -0 0</pose>
<geometry>
<box>
<size>5 0.15 2.5</size>
</box>
</geometry>
<material>
<script>
<uri>file://media/materials/scripts/gazebo.material</uri>
<name>Gazebo/Grey</name>
</script>
<ambient>1 1 1 1</ambient>
</material>
<meta>
<layer>0</layer>
</meta>
</visual>
<pose>0.062177 -2.89677 0 0 -0 0</pose>
</link>
<link name='Wall_29'>
<collision name='Wall_29_Collision'>
<geometry>
<box>
<size>3.75 0.15 2.5</size>
</box>
</geometry>
<pose>0 0 1.25 0 -0 0</pose>
</collision>
<visual name='Wall_29_Visual'>
<pose>0 0 1.25 0 -0 0</pose>
<geometry>
<box>
<size>3.75 0.15 2.5</size>
</box>
</geometry>
<material>
<script>
<uri>file://media/materials/scripts/gazebo.material</uri>
<name>Gazebo/Grey</name>
</script>
<ambient>1 1 1 1</ambient>
</material>
<meta>
<layer>0</layer>
</meta>
</visual>
<pose>-0.305988 0.758719 0 0 -0 0</pose>
</link>
<link name='Wall_31'>
<collision name='Wall_31_Collision'>
<geometry>
<box>
<size>3.75 0.15 2.5</size>
</box>
</geometry>
<pose>0 0 1.25 0 -0 0</pose>
</collision>
<visual name='Wall_31_Visual'>
<pose>0 0 1.25 0 -0 0</pose>
<geometry>
<box>
<size>3.75 0.15 2.5</size>
</box>
</geometry>
<material>
<script>
<uri>file://media/materials/scripts/gazebo.material</uri>
<name>Gazebo/Grey</name>
</script>
<ambient>1 1 1 1</ambient>
</material>
<meta>
<layer>0</layer>
</meta>
</visual>
<pose>-0.300519 2.09188 0 0 -0 0</pose>
</link>
<link name='Wall_33'>
<collision name='Wall_33_Collision'>
<geometry>
<box>
<size>1.5 0.15 2.5</size>
</box>
</geometry>
<pose>0 0 1.25 0 -0 0</pose>
</collision>
<visual name='Wall_33_Visual'>
<pose>0 0 1.25 0 -0 0</pose>
<geometry>
<box>
<size>1.5 0.15 2.5</size>
</box>
</geometry>
<material>
<script>
<uri>file://media/materials/scripts/gazebo.material</uri>
<name>Gazebo/Grey</name>
</script>
<ambient>1 1 1 1</ambient>
</material>
<meta>
<layer>0</layer>
</meta>
</visual>
<pose>1.65085 1.41824 0 0 -0 -1.5708</pose>
</link>
<link name='Wall_36'>
<collision name='Wall_36_Collision'>
<geometry>
<box>
<size>2.75 0.15 2.5</size>
</box>
</geometry>
<pose>0 0 1.25 0 -0 0</pose>
</collision>
<visual name='Wall_36_Visual'>
<pose>0 0 1.25 0 -0 0</pose>
<geometry>
<box>
<size>2.75 0.15 2.5</size>
</box>
</geometry>
<material>
<script>
<uri>file://media/materials/scripts/gazebo.material</uri>
<name>Gazebo/Grey</name>
</script>
<ambient>1 1 1 1</ambient>
</material>
<meta>
<layer>0</layer>
</meta>
</visual>
<pose>2.3125 1.40828 0 0 -0 1.5708</pose>
</link>
<link name='Wall_38'>
<collision name='Wall_38_Collision'>
<geometry>
<box>
<size>5.25 0.15 2.5</size>
</box>
</geometry>
<pose>0 0 1.25 0 -0 0</pose>
</collision>
<visual name='Wall_38_Visual'>
<pose>0 0 1.25 0 -0 0</pose>
<geometry>
<box>
<size>5.25 0.15 2.5</size>
</box>
</geometry>
<material>
<script>
<uri>file://media/materials/scripts/gazebo.material</uri>
<name>Gazebo/Grey</name>
</script>
<ambient>1 1 1 1</ambient>
</material>
<meta>
<layer>0</layer>
</meta>
</visual>
<pose>-0.19189 2.74413 0 0 -0 3.14159</pose>
</link>
<link name='Wall_4'>
<collision name='Wall_4_Collision'>
<geometry>
<box>
<size>2 0.15 2.5</size>
</box>
</geometry>
<pose>0 0 1.25 0 -0 0</pose>
</collision>
<visual name='Wall_4_Visual'>
<pose>0 0 1.25 0 -0 0</pose>
<geometry>
<box>
<size>2 0.15 2.5</size>
</box>
</geometry>
<material>
<script>
<uri>file://media/materials/scripts/gazebo.material</uri>
<name>Gazebo/Grey</name>
</script>
<ambient>1 1 1 1</ambient>
</material>
<meta>
<layer>0</layer>
</meta>
</visual>
<pose>2.6265 -1.8264 0 0 -0 1.5708</pose>
</link>
<link name='Wall_40'>
<collision name='Wall_40_Collision'>
<geometry>
<box>
<size>1.5 0.15 2.5</size>
</box>
</geometry>
<pose>0 0 1.25 0 -0 0</pose>
</collision>
<visual name='Wall_40_Visual'>
<pose>0 0 1.25 0 -0 0</pose>
<geometry>
<box>
<size>1.5 0.15 2.5</size>
</box>
</geometry>
<material>
<script>
<uri>file://media/materials/scripts/gazebo.material</uri>
<name>Gazebo/Grey</name>
</script>
<ambient>1 1 1 1</ambient>
</material>
<meta>
<layer>0</layer>
</meta>
</visual>
<pose>-2.25486 1.43754 0 0 -0 -1.5708</pose>
</link>
<link name='Wall_44'>
<collision name='Wall_44_Collision'>
<geometry>
<box>
<size>3 0.15 2.5</size>
</box>
</geometry>
<pose>0 0 1.25 0 -0 0</pose>
</collision>
<visual name='Wall_44_Visual'>
<pose>0 0 1.25 0 -0 0</pose>
<geometry>
<box>
<size>3 0.15 2.5</size>
</box>
</geometry>
<material>
<script>
<uri>file://media/materials/scripts/gazebo.material</uri>
<name>Gazebo/Grey</name>
</script>
<ambient>1 1 1 1</ambient>
</material>
<meta>
<layer>0</layer>
</meta>
</visual>
<pose>-2.89932 1.47176 0 0 -0 -1.5708</pose>
</link>
<link name='Wall_46'>
<collision name='Wall_46_Collision'>
<geometry>
<box>
<size>2.25 0.15 2.5</size>
</box>
</geometry>
<pose>0 0 1.25 0 -0 0</pose>
</collision>
<visual name='Wall_46_Visual'>
<pose>0 0 1.25 0 -0 0</pose>
<geometry>
<box>
<size>2.25 0.15 2.5</size>
</box>
</geometry>
<material>
<script>
<uri>file://media/materials/scripts/gazebo.material</uri>
<name>Gazebo/Grey</name>
</script>
<ambient>1 1 1 1</ambient>
</material>
<meta>
<layer>0</layer>
</meta>
</visual>
<pose>-1.87754 0.1172 0 0 -0 3.14159</pose>
</link>
<link name='Wall_48'>
<collision name='Wall_48_Collision'>
<geometry>
<box>
<size>2.13496 0.15 2.5</size>
</box>
</geometry>
<pose>0 0 1.25 0 -0 0</pose>
</collision>
<visual name='Wall_48_Visual'>
<pose>0 0 1.25 0 -0 0</pose>
<geometry>
<box>
<size>2.13496 0.15 2.5</size>
</box>
</geometry>
<material>
<script>
<uri>file://media/materials/scripts/gazebo.material</uri>
<name>Gazebo/Grey</name>
</script>
<ambient>1 1 1 1</ambient>
</material>
<meta>
<layer>0</layer>
</meta>
</visual>
<pose>1.32002 0.107134 0 0 -0 0.001157</pose>
</link>
<link name='Wall_6'>
<collision name='Wall_6_Collision'>
<geometry>
<box>
<size>2 0.15 2.5</size>
</box>
</geometry>
<pose>0 0 1.25 0 -0 0</pose>
</collision>
<visual name='Wall_6_Visual'>
<pose>0 0 1.25 0 -0 0</pose>
<geometry>
<box>
<size>2 0.15 2.5</size>
</box>
</geometry>
<material>
<script>
<uri>file://media/materials/scripts/gazebo.material</uri>
<name>Gazebo/Grey</name>
</script>
<ambient>1 1 1 1</ambient>
</material>
<meta>
<layer>0</layer>
</meta>
</visual>
<pose>-2.50971 -1.81518 0 0 -0 1.5708</pose>
</link>
<static>1</static>
</model>
</sdf>

Submodule src/ground_slam deleted from 287e3077d7

51
src/ground_slam/.gitignore vendored Executable file
View File

@@ -0,0 +1,51 @@
build/
bin/
lib/
debug/
msg_gen/
srv_gen/
msg/*Action.msg
msg/*ActionFeedback.msg
msg/*ActionGoal.msg
msg/*ActionResult.msg
msg/*Feedback.msg
msg/*Goal.msg
msg/*Result.msg
msg/_*.py
# Generated by dynamic reconfigure
*.cfgc
/cfg/cpp/
/cfg/*.py
# Ignore generated docs
*.dox
*.wikidoc
# eclipse stuff
.project
.cproject
# qcreator stuff
CMakeLists.txt.user
srv/_*.py
*.pcd
*.pyc
qtcreator-*
*.user
*~
# Emacs
.#*
# Catkin custom files
CATKIN_IGNORE
bag
.vscode/*
log/*
saving/*
debug/*
test/*

118
src/ground_slam/CMakeLists.txt Executable file
View File

@@ -0,0 +1,118 @@
cmake_minimum_required(VERSION 3.8)
project(ground_slam)
# Default to C++17 (ROS2 Humble standard)
if(NOT CMAKE_CXX_STANDARD)
set(CMAKE_CXX_STANDARD 17)
endif()
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_BUILD_TYPE Release)
set(CMAKE_MODULE_PATH ${PROJECT_SOURCE_DIR}/cmake)
# ── ROS2 packages ──────────────────────────────────────
find_package(ament_cmake REQUIRED)
find_package(rclcpp REQUIRED)
find_package(geometry_msgs REQUIRED)
find_package(nav_msgs REQUIRED)
find_package(std_msgs REQUIRED)
find_package(sensor_msgs REQUIRED)
find_package(cv_bridge REQUIRED)
find_package(tf2 REQUIRED)
find_package(tf2_geometry_msgs REQUIRED)
find_package(tf2_ros REQUIRED)
find_package(visualization_msgs REQUIRED)
# ── System dependencies ────────────────────────────────
find_package(OpenCV 4.2 REQUIRED)
find_package(OpenMP REQUIRED)
find_package(Eigen3 REQUIRED)
find_package(FFTW3 REQUIRED)
find_package(Ceres REQUIRED)
find_package(yaml-cpp REQUIRED)
find_package(Boost REQUIRED)
find_package(VTK REQUIRED)
# ── Compiler flags ─────────────────────────────────────
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall -O3 -march=native")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -O3 -march=native -Wno-reorder")
if(OPENMP_FOUND)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${OpenMP_C_FLAGS}")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${OpenMP_CXX_FLAGS}")
endif()
# ── Include directories ────────────────────────────────
include_directories(
${PROJECT_SOURCE_DIR}/include
${OpenCV_INCLUDE_DIRS}
${EIGEN3_INCLUDE_DIR}
${FFTW3_INCLUDE_DIRS}
${YAML_CPP_INCLUDE_DIR}
${CERES_INCLUDE_DIRS}
${Boost_INCLUDE_DIRS}
${VTK_INCLUDE_DIRS}
)
# ── Core library ───────────────────────────────────────
add_library(${PROJECT_NAME}_lib SHARED
src/optimization_2d/pose_graph_2d.cc
src/utils.cc
src/dataset.cc
src/camera.cc
src/frame.cc
src/edge.cc
src/correlation_flow.cc
src/loop_closure.cc
src/map.cc
src/map_builder.cc
src/thread_publisher.cc
src/map_stitcher.cc
src/visualization.cc
src/timer.cc
)
target_link_libraries(${PROJECT_NAME}_lib
-lfftw3
-lfftw3f
${OpenCV_LIBS}
${EIGEN3_LIBS}
${CERES_LIBRARIES}
yaml-cpp
${Boost_LIBRARIES}
${VTK_LIBRARIES}
)
# ROS2 deps (header-only via include_directories above, link where needed)
ament_target_dependencies(${PROJECT_NAME}_lib
rclcpp
geometry_msgs
nav_msgs
std_msgs
sensor_msgs
cv_bridge
tf2
tf2_geometry_msgs
tf2_ros
visualization_msgs
)
# ── Executable ─────────────────────────────────────────
add_executable(${PROJECT_NAME} main.cpp)
target_link_libraries(${PROJECT_NAME} ${PROJECT_NAME}_lib)
ament_target_dependencies(${PROJECT_NAME}
rclcpp
)
# ── Install ────────────────────────────────────────────
install(TARGETS ${PROJECT_NAME} ${PROJECT_NAME}_lib
ARCHIVE DESTINATION lib
LIBRARY DESTINATION lib
RUNTIME DESTINATION lib/${PROJECT_NAME}
)
install(DIRECTORY configs/
DESTINATION share/${PROJECT_NAME}/configs
)
ament_package()

674
src/ground_slam/LICENSE.md Normal file
View File

@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
{one line to give the program's name and a brief idea of what it does.}
Copyright (C) {year} {name of author}
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
{project} Copyright (C) {year} {fullname}
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.

138
src/ground_slam/README.md Normal file
View File

@@ -0,0 +1,138 @@
<h1 align="center">GroundSLAM: A Robust Visual SLAM System for Warehouse Robots Using Ground Textures</h1><p align="center"><strong>
<a href = "https://scholar.google.com/citations?user=-p7HvCMAAAAJ&hl=zh-CN">Kuan Xu</a><sup>1</sup>,
<a href = "https://github.com/yangzheng-yz">Zheng Yang</a><sup>1</sup>,
<a href = "https://scholar.google.com.sg/citations?user=Fmrv3J8AAAAJ&hl=en">Lihua Xie</a><sup>1</sup>,
<a href = "https://sairlab.org/team/chenw/">Chen Wang</a><sup>2</sup>
</strong></p>
<p align="center"><strong>
<a href = "https://www.ntu.edu.sg/cartin">1: Centre for Advanced Robotics Technology Innovation (CARTIN), Nanyang Technological University</a><br>
<a href = "https://sairlab.org/">2: Spatial AI & Robotics (SAIR) Lab, Computer Science and Engineering, University at Buffalo</a><br>
</strong></p>
<p align="center"><strong>
<!-- <a href = "https://arxiv.org/pdf/2408.03520">&#128196; [PDF]</a> |
<a href = "https://xukuanhit.github.io/airslam/">&#128190; [Project Site]</a> | -->
<a href = "https://youtu.be/2sI76SDptDA">&#127909; [Youtube]</a> |
<a href = "https://www.bilibili.com/video/BV1vWh8zTE77">&#127909; [Bilibili]</a>
<a href = "supplementary/GroundSLAM_Supplement_Materia.pdf">&#128202; [Supplementary]</a>
<!-- &#128214; [OpenAccess] -->
</strong></p>
<img src="figures/pipeline.png" width = "800" alt="pipeline" />
GroundSLAM is a novel **feature-free** and **ground-texture-based** SLAM system for **the warehouse robot**. Our system can provide robust pose estimation and localization in environments with many **dynamic** objects or **open spaces**, such as warehouses, which is very challenging for localization systems with a forward-facing camera or LiDAR. GroundSLAM consists of three components: feature-free visual odometry, ground-texture-based loop detection and map optimization, and map reuse. Specifically, we introduce a kernel cross-correlator for **image-level pose tracking**, loop detection, and map reuse to improve localization accuracy and robustness, and incorporate adaptive pruning strategies to enhance efficiency. Due to these specific designs, GroundSLAM more **robust** and **accurate** when dealing with ground images with **few textures** or with many **repetitive patterns** than the feature-based methods.
**Video:**
<p align="middle">
<a href="https://youtu.be/2sI76SDptDA" target="_blank"><img src="figures/video.png" width="600" border="10"/></a>
</p>
## Test Environment
### Dependencies
* OpenCV 4.2
* Eigen 3
* Ceres 2.0.0
* FFTW3
* ROS noetic
* Boost
* yaml-cpp
* VTK
## Build
```
cd ~/catkin_ws/src
git clone https://github.com/sair-lab/GroundSLAM.git
cd ../
catkin_make
source ~/catkin_ws/devel/setup.bash
```
## Run
Modify the configuration file in [configs](configs) and then run
```
rosrun ground_slam ground_slam src/GroundSLAM/configs/your_config.yaml
```
## Data
### PathTex Dataset
<img src="figures/sample_images.jpg" width = "600" alt="pathtex_dataset" />
Our data collection platform is a modified Weston SCOUT Robot. The robot is equipped with an IDS uEye monocular camera, which is positioned at the bottom and facing downward, placed at a height of 0.1m above the ground. To ensure constant illumination, a set of LED lights are arranged around the camera. For ground truth, a prism is installed on the top of the robot, and its position is tracked by a Leica Nova MS60 MultiStation laser tracker.
We collect the data of 10 common ground textures, including 6 $\color{lightblue}{outdoor}$ textures and 4 $\color{red}{indoor}$ textures. The table below provides detailed information and download links for each sequence. The **camera parameters** can be found [here](https://entuedu-my.sharepoint.com/:u:/g/personal/kuan_xu_staff_main_ntu_edu_sg/EQqXW2eDcXNAkBWlSGgq6bgBe2yYdjdcuSJ8HEFey3haGg?e=nOg2ym).
<!-- <div align=center> -->
Sequence Name|Total Size|Total Images|Download Link
:--:|:--:|:--:|:--:
Brick_seq1|1.0g|3119|[Link](https://entuedu-my.sharepoint.com/:u:/g/personal/kuan_xu_staff_main_ntu_edu_sg/EUMENxrPbQBFmzAQmfhMw4YB4df6_uq6ua7H1fo9A7NC7g?e=5Mzy9Q)
Brick_seq2|0.9g|5328|[Link](https://entuedu-my.sharepoint.com/:u:/g/personal/kuan_xu_staff_main_ntu_edu_sg/EY1-hFr2taZJqjxE4k6-W6oB-XenzRAk_RW8DME6VvqUmg?e=PSQEi6)
Carpet1_seq1|1.7g|8458|[Link](https://entuedu-my.sharepoint.com/:u:/g/personal/kuan_xu_staff_main_ntu_edu_sg/ETuQX1ePORdKmQJ_wFXT1mUBS6MqJ3LoZ-eeUsDhhXouug?e=AmMgBX)
Carpet1_seq2|1.7g|8499|[Link](https://entuedu-my.sharepoint.com/:u:/g/personal/kuan_xu_staff_main_ntu_edu_sg/EQwzCVxFMT1Hh9BMMNljwSgBM27RXd7v8gdM3KMNWm5mDQ?e=aSoH1v)
Carpet2_seq1|3.0g|15481|[Link](https://entuedu-my.sharepoint.com/:u:/g/personal/kuan_xu_staff_main_ntu_edu_sg/EZ6Y6xsmk6xBjkkU7JNrVQIB_zTovWY8-AOPdW7AN7XJLw?e=GvlK03)
Carpet3_seq1|0.7g|4500|[Link](https://entuedu-my.sharepoint.com/:u:/g/personal/kuan_xu_staff_main_ntu_edu_sg/EXxxHyPOvsFBh8judFQqhtEB-kI6uBzFmKcCiNDZZBzBIw?e=917b5c)
Carpet3_seq2|0.7g|4385|[Link](https://entuedu-my.sharepoint.com/:u:/g/personal/kuan_xu_staff_main_ntu_edu_sg/EQHoNL0xtpdKj6e6mhBBLyEBl-7s5N0cJ6U47jzT1tJheg?e=ot4hSH)
Carpet3_seq3|1.0g|6428|[Link](https://entuedu-my.sharepoint.com/:u:/g/personal/kuan_xu_staff_main_ntu_edu_sg/EcE3o-HN0UJEpc57_EJM3kcBSVSIQ8M7oCjkWsZlUQRKLw?e=qG8MUM)
Coarse_asphalt_seq1|1.2g|5897|[Link](https://entuedu-my.sharepoint.com/:u:/g/personal/kuan_xu_staff_main_ntu_edu_sg/EQbDBVemPH9Cp7bqV2ZwfFIBD_gsHQ-d3atPfSY8__6DKQ?e=ASludI)
Concrete_seq1|1.0g|5850|[Link](https://entuedu-my.sharepoint.com/:u:/g/personal/kuan_xu_staff_main_ntu_edu_sg/EcIYh8RIhClKs7ogwgFmS_QBlflxcx-eR33BwRVerNXFgg?e=8McLDA)
Concrete_seq2|0.9g|5975|[Link](https://entuedu-my.sharepoint.com/:u:/g/personal/kuan_xu_staff_main_ntu_edu_sg/EbNJ5FdpQSJMqK-2zyoEPNoBNCO4ZzhuzjzTL2m1AYZQKQ?e=feQNUX)
Fine_asphalt_seq1|1.1g|5119|[Link](https://entuedu-my.sharepoint.com/:u:/g/personal/kuan_xu_staff_main_ntu_edu_sg/EY22RWOcM89ApAYEr0E5I5EB6QhINnL5iGsbgli8INjuXg?e=HArfqb)
Fine_asphalt_seq2|1.3g|11897|[Link](https://entuedu-my.sharepoint.com/:u:/g/personal/kuan_xu_staff_main_ntu_edu_sg/ERBTClOvkpBHgNeAEc5co4sBI5E-ubQ2MqNFwlfys07mbQ?e=WDd0uP)
Granite_tiles_seq1|1.2g|7194|[Link](https://entuedu-my.sharepoint.com/:u:/g/personal/kuan_xu_staff_main_ntu_edu_sg/ERNkKMy_nvFFmORT7LU_MxEB7TDzhAsNKEEfBf_cNG4Zbg?e=sjDkYW)
Granite_tiles_seq2|1.6g|10633|[Link](https://entuedu-my.sharepoint.com/:u:/g/personal/kuan_xu_staff_main_ntu_edu_sg/EU-8ocb82WZDpErJuOGfR6oBbQwXEpAzR-nykA6wXk9zeg?e=Vx4P1t)
Gravel_road1_seq1|0.8g|4883|[Link](https://entuedu-my.sharepoint.com/:u:/g/personal/kuan_xu_staff_main_ntu_edu_sg/ERRQQR0VTCVEqSdo9pM85zwBNMQFRBcgev4VVIZtjg68Vg?e=KFxJST)
Gravel_road2_seq1|2.1g|11776|[Link](https://entuedu-my.sharepoint.com/:u:/g/personal/kuan_xu_staff_main_ntu_edu_sg/EZS9BNL-ct1Nu3_Ag1Z0YuIBt6ah02i8vojro4eHexs4ww?e=hQOLIF)
<!-- </div> -->
### Run with Your Data
The data should be organized in the following format:
```
dataroot
├── image_names.txt
├── rgb
│   ├── 00001.png
│   ├── 00002.png
│   ├── 00003.png
│   └── ......
└── times.txt
```
where `image_names.txt` contains the image names in `/dataroot/rgb` and `times.txt` contains the corresponding double type timestamps.
## Experiments
### Data Association
<img src="figures/features_small.jpg" width = "700" alt="data_association" />
We compare the data association of our system with ORB and SIFT on the HD Ground dataset. The numbers of features and matching inliers are given. For our method, the correction results are projected to three coordinate axes and represent the estimation of the 3-DOF movement. The vertical axis is the confidence of estimated movement on the horizontal axis. The higher the value of the peak relative to other positions, the greater the confidence of motion estimation. The results show that the data association of our system is more stable for various ground texture images.
### Visual Odometry
<div style="display:flex; justify-content:flex-start;">
<img src="figures/trajectory.jpg" height="200" style="margin-right: 20px;" />
<img src="figures/rmse_curve.jpg" height="200" />
</div>
This experiment is conducted on our PathTex dataset. The left figure shows the trajectories produced by our system and GT-SLAM on 4 sequences. The right figure provides the comparison of error distributions of different systems on the Gravel_road2_seq1 sequence, where the vertical axis is the proportion of pose errors that are less than the given error threshold on the horizontal axis.
### Loop Closure
<div style="display:flex; justify-content:flex-start;">
<img src="figures/loop_trajectory.jpg" height="135" style="margin-right: 20px;" />
<img src="figures/loop_error.jpg" height="135" />
</div>
These two figures show the performance difference of GroundSLAM with and without loop correction on the Fine_asphalt_seq2 sequence. It is seen that the pose errors are significantly decreased after the loop correction.

View File

@@ -0,0 +1,94 @@
# - Try to find Eigen3 lib
#
# This module supports requiring a minimum version, e.g. you can do
# find_package(Eigen3 3.1.2)
# to require version 3.1.2 or newer of Eigen3.
#
# Once done this will define
#
# EIGEN3_FOUND - system has eigen lib with correct version
# EIGEN3_INCLUDE_DIR - the eigen include directory
# EIGEN3_VERSION - eigen version
# Copyright (c) 2006, 2007 Montel Laurent, <montel@kde.org>
# Copyright (c) 2008, 2009 Gael Guennebaud, <g.gael@free.fr>
# Copyright (c) 2009 Benoit Jacob <jacob.benoit.1@gmail.com>
# Redistribution and use is allowed according to the terms of the 2-clause BSD license.
if(NOT Eigen3_FIND_VERSION)
if(NOT Eigen3_FIND_VERSION_MAJOR)
set(Eigen3_FIND_VERSION_MAJOR 2)
endif(NOT Eigen3_FIND_VERSION_MAJOR)
if(NOT Eigen3_FIND_VERSION_MINOR)
set(Eigen3_FIND_VERSION_MINOR 91)
endif(NOT Eigen3_FIND_VERSION_MINOR)
if(NOT Eigen3_FIND_VERSION_PATCH)
set(Eigen3_FIND_VERSION_PATCH 0)
endif(NOT Eigen3_FIND_VERSION_PATCH)
set(Eigen3_FIND_VERSION "${Eigen3_FIND_VERSION_MAJOR}.${Eigen3_FIND_VERSION_MINOR}.${Eigen3_FIND_VERSION_PATCH}")
endif(NOT Eigen3_FIND_VERSION)
macro(_eigen3_check_version)
file(READ "${EIGEN3_INCLUDE_DIR}/Eigen/src/Core/util/Macros.h" _eigen3_version_header)
string(REGEX MATCH "define[ \t]+EIGEN_WORLD_VERSION[ \t]+([0-9]+)" _eigen3_world_version_match "${_eigen3_version_header}")
set(EIGEN3_WORLD_VERSION "${CMAKE_MATCH_1}")
string(REGEX MATCH "define[ \t]+EIGEN_MAJOR_VERSION[ \t]+([0-9]+)" _eigen3_major_version_match "${_eigen3_version_header}")
set(EIGEN3_MAJOR_VERSION "${CMAKE_MATCH_1}")
string(REGEX MATCH "define[ \t]+EIGEN_MINOR_VERSION[ \t]+([0-9]+)" _eigen3_minor_version_match "${_eigen3_version_header}")
set(EIGEN3_MINOR_VERSION "${CMAKE_MATCH_1}")
set(EIGEN3_VERSION ${EIGEN3_WORLD_VERSION}.${EIGEN3_MAJOR_VERSION}.${EIGEN3_MINOR_VERSION})
if(${EIGEN3_VERSION} VERSION_LESS ${Eigen3_FIND_VERSION})
set(EIGEN3_VERSION_OK FALSE)
else(${EIGEN3_VERSION} VERSION_LESS ${Eigen3_FIND_VERSION})
set(EIGEN3_VERSION_OK TRUE)
endif(${EIGEN3_VERSION} VERSION_LESS ${Eigen3_FIND_VERSION})
if(NOT EIGEN3_VERSION_OK)
message(STATUS "Eigen3 version ${EIGEN3_VERSION} found in ${EIGEN3_INCLUDE_DIR}, "
"but at least version ${Eigen3_FIND_VERSION} is required")
endif(NOT EIGEN3_VERSION_OK)
endmacro(_eigen3_check_version)
if (EIGEN3_INCLUDE_DIR)
# in cache already
_eigen3_check_version()
set(EIGEN3_FOUND ${EIGEN3_VERSION_OK})
else (EIGEN3_INCLUDE_DIR)
# specific additional paths for some OS
if (WIN32)
set(EIGEN_ADDITIONAL_SEARCH_PATHS ${EIGEN_ADDITIONAL_SEARCH_PATHS} "C:/Program Files/Eigen/include" "C:/Program Files (x86)/Eigen/include")
endif(WIN32)
find_path(EIGEN3_INCLUDE_DIR NAMES signature_of_eigen3_matrix_library
PATHS
${CMAKE_INSTALL_PREFIX}/include
${EIGEN_ADDITIONAL_SEARCH_PATHS}
${KDE4_INCLUDE_DIR}
PATH_SUFFIXES eigen3 eigen
)
if(EIGEN3_INCLUDE_DIR)
_eigen3_check_version()
endif(EIGEN3_INCLUDE_DIR)
include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(Eigen3 DEFAULT_MSG EIGEN3_INCLUDE_DIR EIGEN3_VERSION_OK)
mark_as_advanced(EIGEN3_INCLUDE_DIR)
endif(EIGEN3_INCLUDE_DIR)
if(EIGEN3_FOUND)
include_directories(${EIGEN3_INCLUDE_DIR})
link_directories(${EIGEN3_LIBRARIES})
else(EIGEN3_FOUND)
MESSAGE(FATAL_ERROR "Eigen3 library not found")
endif(EIGEN3_FOUND)

View File

@@ -0,0 +1,18 @@
# - Find FFTW3
# Find the native FFTW3 includes and library
#
# FFTW3_INCLUDE_DIRS - where to find fftw3.h
# FFTW3_LIBRARIES - List of libraries when using FFTW3.
# FFTW3_FOUND - True if FFTW3 found.
if (FFTW3_INCLUDE_DIRS)
set(FFTW3_FIND_QUIETLY TRUE)
endif()
find_path(FFTW3_INCLUDE_DIRS fftw3.h)
find_library(FFTW3_LIBRARIES NAMES fftw3)
include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(FFTW3 DEFAULT_MSG FFTW3_LIBRARIES FFTW3_INCLUDE_DIRS)
mark_as_advanced(FFTW3_LIBRARIES FFTW3_INCLUDE_DIRS)

View File

@@ -0,0 +1,49 @@
dataset:
camera_config: /media/zheng/xukuanssd/NTU/ground_texture/HD_ground/camera.yaml
dataroot: /media/zheng/xukuanssd/NTU/ground_texture/HD_ground/ramp_rubber/database/seq0033
image_dir_name: rgb
correlation_flow:
gaussian:
sigma: 0.2
height: 1200
kernel: 0 # {0: "polynomial", 1: "gaussian"}
lambda: 0.1
polynomial:
offset: 0.1
power: 3
rotation_channel: 480
rotation_divisor: 720
width: 1600
keyframe_selection:
lower_response_thr: 30
max_angle: 6.3
max_distance: 0.01
upper_response_thr: 90
map:
grid_scale: 0.1 # the true size of one grid
loop_closure:
to_find_loop: true
angle_response_thr: 60
distance_thr: 5
frame_gap_thr: 100
position_response_thr: 60
map_sticther:
cell_size: 1000
stitch_map: true
visualization:
frame_id: map
topic:
image: /kcc_slam/image
frame_pose: /kcc_slam/frame_pose
kcc_pose: /kcc_slam/kcc_pose
map: /kcc_slam/occupancy_map
saving:
save_pose: true
saving_root: /home/xukuan/debug/kcc

View File

@@ -0,0 +1,50 @@
dataset:
dataroot: "/home/zheng/datasets/loopclosure/"
camera_config: "/home/zheng/datasets/loopclosure/camera.yaml"
image_dir_name: ""
correlation_flow:
width: 448
height: 448
rotation_divisor: 720 #720 # Higher means higher resolution, but slower
rotation_channel: 480 #480 # Lower means faster. Too lower, e.g., less than 10, may produce error about 1/rotation_divisor*360 degrees. 64 may work well.
lambda: 0.1 # For regularization
kernel: 0 #1 # {0: "polynomial", 1: "gaussian"}
polynomial: # (X^T Y + offset).pow(power)
offset: 0.1
power: 3
gaussian: # exp(-(|X-Y|^2/(2*sigma^2)))
sigma: 0.2 # For Gaussian Kernel
keyframe_selection:
to_find_loop: true
max_distance: 0.2 # in normalized plane, real size equal max_distance*camera_height
max_angle: 0.5 # rad
lower_response_thr: 30
upper_response_thr: 60
map:
grid_scale: 0.1 # the true size of one grid
loop_closure:
to_find_loop: true
position_response_thr: 60 # this should be tuned together with width and height: higher width*height -> higher threshold
angle_response_thr: 60 # this should be tuned together with rotation_divisor and rotation_channel: higher divisor*channel -> higher threshold
frame_gap_thr: 100
distance_thr: 5 # in normalized plane, real size equal distance_thr*camera_height
map_sticther:
stitch_map: true # whether to stitch map
cell_size: 1000
visualization:
frame_id: "map"
topic:
image: /kcc_slam/undistort_image
kcc_pose: "/kcc_slam/kcc_pose"
frame_pose: "/kcc_slam/frame_pose"
map: "/kcc_slam/occupancy_map"
saving:
save_pose: true
saving_root: "/home/zheng/projects/ros_ws/src/kcc_slam/saving/experiments"

View File

@@ -0,0 +1,49 @@
dataset:
camera_config: /media/data/datasets/ntu/NTU_Ground_Texture_Dataset/camera.yaml
dataroot: /media/data/datasets/ntu/NTU_Ground_Texture_Dataset/brick-V3
image_dir_name: rgb
correlation_flow:
gaussian:
sigma: 0.2
height: 480
kernel: 0 # {0: "polynomial", 1: "gaussian"}
lambda: 0.1
polynomial:
offset: 0.1
power: 3
rotation_channel: 480
rotation_divisor: 720
width: 640
keyframe_selection:
lower_response_thr: 30
max_angle: 0.052359877
max_distance: 0.4
upper_response_thr: 90
map:
grid_scale: 0.1 # the true size of one grid
loop_closure:
to_find_loop: true
angle_response_thr: 60
distance_thr: 5
frame_gap_thr: 100
position_response_thr: 60
map_sticther:
cell_size: 1000
stitch_map: true
visualization:
frame_id: map
topic:
image: /kcc_slam/image
frame_pose: /kcc_slam/frame_pose
kcc_pose: /kcc_slam/kcc_pose
map: /kcc_slam/occupancy_map
saving:
save_pose: true
saving_root: /home/xukuan/debug/kcc

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.7 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 883 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 297 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 775 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 381 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 115 KiB

View File

@@ -0,0 +1,59 @@
#ifndef CAMERA_H_
#define CAMERA_H_
#include <iostream>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/opencv.hpp>
#include <Eigen/Core>
#include <Eigen/Dense>
#include <Eigen/SparseCore>
class Camera{
public:
Camera();
Camera(const std::string& camera_file);
Camera& operator=(const Camera& camera);
void UndistortImage(cv::Mat& image, cv::Mat& undistort_image);
void GetNewCameraMatrix(cv::Mat& camera_matrix);
double GetImageHeight();
double GetImageWidth();
double GetHeight();
bool HeightIsAccurate();
void GetExtrinsics(Eigen::Matrix3d& extrinsics);
double GetLengthOfPixel();
Eigen::Vector3d ConvertPrincipalToCenter(const Eigen::Vector3d& image_plane_pose);
Eigen::Vector3d ConvertCenterToPrincipal(const Eigen::Vector3d& image_center_pose);
// Image plane: pixel plane, principal point on the image is the origin
// Camera: normalized plane,
// Robot: robot body coordinate system.
bool ConvertImagePlanePoseToCamera(Eigen::Vector3d& image_plane_pose, Eigen::Vector3d& camera_pose);
bool ConvertCameraPoseToImagePlane(Eigen::Vector3d& image_plane_pose, Eigen::Vector3d& camera_pose);
bool ConvertCameraPoseToRobot(Eigen::Vector3d& camera_pose, Eigen::Vector3d& robot_pose);
bool ConvertRobotPoseToCamera(Eigen::Vector3d& camera_pose, Eigen::Vector3d& robot_pose);
bool ConvertImagePlanePoseToRobot(Eigen::Vector3d& image_plane_pose, Eigen::Vector3d& robot_pose);
bool ConvertRobotPoseToImagePlane(Eigen::Vector3d& image_plane_pose, Eigen::Vector3d& robot_pose);
private:
int _image_height;
int _image_width;
double _scale;
double _new_scale;
int _new_width;
int _new_height;
double _height;
bool _accurate_height;
cv::Mat _K;
cv::Mat _new_K;
cv::Mat _D;
cv::Mat _map1;
cv::Mat _map2;
Eigen::Matrix3d _extrinsics;
};
typedef std::shared_ptr<Camera> CameraPtr;
#endif // CAMERA_H_

View File

@@ -0,0 +1,252 @@
// circ_shift.h
// https://stackoverflow.com/questions/46077242/eigen-modifyable-custom-expression/46301503#46301503
// this file implements circShift, fftshift, and ifftshift for Eigen vectors/matrices.
//
#pragma once
#include <Eigen/Core>
template <bool B> using bool_constant = std::integral_constant<bool, B>;
namespace helper
{
namespace detail
{
template <typename T>
constexpr std::true_type is_matrix(Eigen::MatrixBase<T>);
std::false_type constexpr is_matrix(...);
template <typename T>
constexpr std::true_type is_array(Eigen::ArrayBase<T>);
std::false_type constexpr is_array(...);
}
template <typename T>
struct is_matrix : decltype(detail::is_matrix(std::declval<std::remove_cv_t<T>>()))
{
};
template <typename T>
struct is_array : decltype(detail::is_array(std::declval<std::remove_cv_t<T>>()))
{
};
template <typename T>
using is_matrix_or_array = bool_constant<is_array<T>::value || is_matrix<T>::value>;
/*
* Index something if it's not an scalar
*/
template <typename T, typename std::enable_if<is_matrix_or_array<T>::value, int>::type = 0>
auto index_if_necessary(T&& thing, Eigen::Index idx)
{
return thing(idx);
}
/*
* Overload for scalar.
*/
template <typename T, typename std::enable_if<std::is_scalar<std::decay_t<T>>::value, int>::type = 0>
auto index_if_necessary(T&& thing, Eigen::Index)
{
return thing;
}
}
namespace Eigen
{
template <typename XprType, typename RowIndices, typename ColIndices>
class CircShiftedView;
namespace internal
{
template <typename XprType, typename RowIndices, typename ColIndices>
struct traits<CircShiftedView<XprType, RowIndices, ColIndices>>
: traits<XprType>
{
enum
{
RowsAtCompileTime = traits<XprType>::RowsAtCompileTime,
ColsAtCompileTime = traits<XprType>::ColsAtCompileTime,
MaxRowsAtCompileTime = (RowsAtCompileTime != Dynamic
? int(RowsAtCompileTime)
: int(traits<XprType>::MaxRowsAtCompileTime)),
MaxColsAtCompileTime = (ColsAtCompileTime != Dynamic
? int(ColsAtCompileTime)
: int(traits<XprType>::MaxColsAtCompileTime)),
XprTypeIsRowMajor = (int(traits<XprType>::Flags) & RowMajorBit) != 0,
IsRowMajor = ((MaxRowsAtCompileTime == 1 && MaxColsAtCompileTime != 1) ? 1
: (MaxColsAtCompileTime == 1 && MaxRowsAtCompileTime != 1) ? 0
: XprTypeIsRowMajor),
FlagsRowMajorBit = IsRowMajor ? RowMajorBit : 0,
FlagsLvalueBit = is_lvalue<XprType>::value ? LvalueBit : 0,
Flags = (traits<XprType>::Flags & HereditaryBits) | FlagsLvalueBit | FlagsRowMajorBit
};
};
}
template <typename XprType, typename RowShift, typename ColShift, typename StorageKind>
class CircShiftedViewImpl;
template <typename XprType, typename RowShift, typename ColShift>
class CircShiftedView : public CircShiftedViewImpl<XprType, RowShift, ColShift,
typename internal::traits<XprType>::StorageKind>
{
public:
typedef typename CircShiftedViewImpl<XprType, RowShift, ColShift,
typename internal::traits<XprType>::StorageKind>::Base Base;
EIGEN_GENERIC_PUBLIC_INTERFACE(CircShiftedView)
EIGEN_INHERIT_ASSIGNMENT_OPERATORS(CircShiftedView)
typedef typename internal::ref_selector<XprType>::non_const_type MatrixTypeNested;
typedef typename internal::remove_all<XprType>::type NestedExpression;
template <typename T0, typename T1>
CircShiftedView(XprType& xpr, const T0& rowShift, const T1& colShift)
: m_xpr(xpr), m_rowShift(rowShift), m_colShift(colShift)
{
for (auto c = 0; c < xpr.cols(); ++c)
assert(std::abs(helper::index_if_necessary(m_rowShift, c)) < m_xpr.rows()); // row shift must be within +- rows()-1
for (auto r = 0; r < xpr.rows(); ++r)
assert(std::abs(helper::index_if_necessary(m_colShift, r)) < m_xpr.cols()); // col shift must be within +- cols()-1
}
/** \returns number of rows */
Index rows() const { return m_xpr.rows(); }
/** \returns number of columns */
Index cols() const { return m_xpr.cols(); }
/** \returns the nested expression */
const typename internal::remove_all<XprType>::type&
nestedExpression() const { return m_xpr; }
/** \returns the nested expression */
typename internal::remove_reference<XprType>::type&
nestedExpression() { return m_xpr.const_cast_derived(); }
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
Index getRowIdx(Index row, Index col) const
{
Index R = m_xpr.rows();
assert(row >= 0 && row < R && col >= 0 && col < m_xpr.cols());
Index r = row - helper::index_if_necessary(m_rowShift, col);
if (r >= R)
return r - R;
if (r < 0)
return r + R;
return r;
}
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
Index getColIdx(Index row, Index col) const
{
Index C = m_xpr.cols();
assert(row >= 0 && row < m_xpr.rows() && col >= 0 && col < C);
Index c = col - helper::index_if_necessary(m_colShift, row);
if (c >= C)
return c - C;
if (c < 0)
return c + C;
return c;
}
protected:
MatrixTypeNested m_xpr;
RowShift m_rowShift;
ColShift m_colShift;
};
// Generic API dispatcher
template <typename XprType, typename RowIndices, typename ColIndices, typename StorageKind>
class CircShiftedViewImpl
: public internal::generic_xpr_base<CircShiftedView<XprType, RowIndices, ColIndices>>::type
{
public:
typedef typename internal::generic_xpr_base<CircShiftedView<XprType, RowIndices, ColIndices>>::type Base;
};
namespace internal
{
template <typename ArgType, typename RowIndices, typename ColIndices>
struct unary_evaluator<CircShiftedView<ArgType, RowIndices, ColIndices>, IndexBased>
: evaluator_base<CircShiftedView<ArgType, RowIndices, ColIndices>>
{
typedef CircShiftedView<ArgType, RowIndices, ColIndices> XprType;
enum
{
CoeffReadCost = (evaluator<ArgType>::CoeffReadCost
+ NumTraits<Index>::AddCost /* for comparison */
+ NumTraits<Index>::AddCost) /* for addition */,
Flags = (evaluator<ArgType>::Flags & HereditaryBits),
Alignment = 0
};
EIGEN_DEVICE_FUNC explicit unary_evaluator(const XprType& xpr) : m_argImpl(xpr.nestedExpression()), m_xpr(xpr)
{
EIGEN_INTERNAL_CHECK_COST_VALUE(CoeffReadCost);
}
typedef typename XprType::Scalar Scalar;
typedef typename XprType::CoeffReturnType CoeffReturnType;
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
CoeffReturnType coeff(Index row, Index col) const
{
return m_argImpl.coeff(m_xpr.getRowIdx(row, col), m_xpr.getColIdx(row, col));
}
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
CoeffReturnType coeff(Index idx) const
{
if (m_xpr.cols() == 1)
return m_argImpl.coeff(m_xpr.getRowIdx(idx, 1), 1);
if (m_xpr.rows() == 1)
return m_argImpl.coeff(1, m_xpr.getColIdx(1, idx));
assert(m_xpr.cols() == 1 || m_xpr.rows() == 1);
// default no-assert case - assume col vector
return m_argImpl.coeff(m_xpr.getRowIdx(idx, 1), 1);
}
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
Scalar& coeffRef(Index row, Index col)
{
assert(row >= 0 && row < m_xpr.rows() && col >= 0 && col < m_xpr.cols());
return m_argImpl.coeffRef(m_xpr.getRowIdx(row, col), m_xpr.getColIdx(row, col));
}
protected:
evaluator<ArgType> m_argImpl;
const XprType& m_xpr;
};
} // end namespace internal
} // end namespace Eigen
template <typename XprType, typename RowShift, typename ColShift>
auto circShift(Eigen::DenseBase<XprType>& x, RowShift r, ColShift c)
{
return Eigen::CircShiftedView<XprType, RowShift, ColShift>(x.derived(), r, c);
}
template <typename XprType>
auto fftshift(Eigen::DenseBase<XprType>& x)
{
Eigen::Index rs = x.rows() / 2;
Eigen::Index cs = x.cols() / 2;
return Eigen::CircShiftedView<XprType, Eigen::Index, Eigen::Index>(x.derived(), rs, cs);
}
template <typename XprType>
auto ifftshift(Eigen::DenseBase<XprType>& x)
{
Eigen::Index rs = (x.rows() + 1) / 2;
Eigen::Index cs = (x.cols() + 1) / 2;
return Eigen::CircShiftedView<XprType, Eigen::Index, Eigen::Index>(x.derived(), rs, cs);
}

View File

@@ -0,0 +1,36 @@
#ifndef CORRELATION_FLOW_H
#define CORRELATION_FLOW_H
#include <fftw3.h>
#include "utils.h"
#include "read_configs.h"
class CorrelationFlow{
public:
CorrelationFlow(CFConfig& cf_config, double &image_height, double &image_width);
void ComputeIntermedium(const Eigen::ArrayXXf&, Eigen::ArrayXXcf&, Eigen::ArrayXXcf&);
Eigen::Vector3d ComputePose(const Eigen::ArrayXXcf&, const Eigen::ArrayXXf&, const Eigen::ArrayXXcf&, const Eigen::ArrayXXcf&, Eigen::Vector3d&, bool);
private:
CFConfig cfg;
Eigen::ArrayXXcf target_fft;
Eigen::ArrayXXcf target_rotation_fft;
Eigen::ArrayXXcf FFT(const Eigen::ArrayXXf&);
Eigen::ArrayXXf IFFT(const Eigen::ArrayXXcf&);
Eigen::ArrayXXcf GetTargetFFT(int, int);
inline Eigen::ArrayXXf RemoveZeroComponent(const Eigen::ArrayXXf&);
inline Eigen::ArrayXXcf gaussian_kernel(const Eigen::ArrayXXcf&, int, int);
inline Eigen::ArrayXXcf gaussian_kernel(const Eigen::ArrayXXcf&, const Eigen::ArrayXXcf&, int, int);
inline Eigen::ArrayXXcf polynomial_kernel(const Eigen::ArrayXXcf&, int, int);
inline Eigen::ArrayXXcf polynomial_kernel(const Eigen::ArrayXXcf&, const Eigen::ArrayXXcf&, int, int);
float EstimateTrans(const Eigen::ArrayXXcf&, const Eigen::ArrayXXcf&, const Eigen::ArrayXXcf&, int, int, Eigen::Vector2d&);
inline Eigen::ArrayXXf polar(const Eigen::ArrayXXf&);
inline float GetInfo(const Eigen::ArrayXXf&, float);
// void PrintArrayToFile (const Eigen::ArrayXXf target);
};
typedef std::shared_ptr<CorrelationFlow> CorrelationFlowPtr;
#endif // CORRELATION_FLOW_H

View File

@@ -0,0 +1,30 @@
#ifndef DATASET_H_
#define DATASET_H_
#include <vector>
#include <Eigen/Dense>
#include <Eigen/SparseCore>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/opencv.hpp>
#include "utils.h"
class Dataset{
public:
Dataset(const std::string& dataroot, const std::string& image_dir_name);
size_t GetDatasetLength();
bool GetImage(cv::Mat& image, size_t idx);
double GetTimestamp(size_t idx);
private:
std::string _dataroot;
std::string _image_dir;
std::string _image_name_file_path;
std::vector<std::string> _image_names;
std::string _time_file_path;
std::vector<double> _timestamps;
};
#endif // DATASET_H_

View File

@@ -0,0 +1,31 @@
#ifndef EDGE_H_
#define EDGE_H_
#include <string>
#include <Eigen/Dense>
#include <Eigen/SparseCore>
#include "utils.h"
struct Edge{
enum Type {
Odom = 0,
KCC = 1,
Loop = 2,
Others = 3,
};
int _edge_id;
Type _type;
int _from;
int _to;
Eigen::Vector3d _T;
Eigen::Matrix3d _information;
Edge();
Edge(int edge_id, Type type, int from, int to, Eigen::Vector3d& T, Eigen::Matrix3d& information);
};
typedef std::shared_ptr<Edge> EdgePtr;
#endif // EDGE_H_

View File

@@ -0,0 +1,45 @@
#ifndef FRAME_H_
#define FRAME_H_
#include <string>
#include <Eigen/Dense>
#include <Eigen/SparseCore>
#include "utils.h"
class Frame{
public:
Frame();
Frame(int frame_id);
Frame(int frame_id, double timestamp, Eigen::ArrayXXf&, Eigen::ArrayXXcf&, Eigen::ArrayXXcf&);
Frame& operator=(const Frame& other);
void SetFrameId(int frame_id);
int GetFrameId();
double GetTimestamp();
Eigen::ArrayXXf GetFrame();
void SetFFTResult(Eigen::ArrayXXcf& fft_result);
void SetFFTResult(Eigen::ArrayXXcf& fft_result, Eigen::ArrayXXcf& depth_fft_result);
void GetFFTResult(Eigen::ArrayXXcf& fft_result);
void GetFFTResult(Eigen::ArrayXXcf& fft_result, Eigen::ArrayXXcf& depth_fft_result);
void SetPose(Eigen::Vector3d& pose);
void GetPose(Eigen::Vector3d& pose);
void AddEdge(int edge_id);
void GetEdgeIds(std::vector<int>& edge_ids);
void SaveToDisk(const std::string root_dir);
private:
int _frame_id;
double _timestamp;
Eigen::ArrayXXf _frame;
Eigen::ArrayXXcf _fft_result;
Eigen::ArrayXXcf _fft_polar;
Eigen::ArrayXXcf _depth_fft_result;
Eigen::Vector3d _pose;
std::vector<int> _edge_ids;
};
typedef std::shared_ptr<Frame> FramePtr;
#endif // FRAME_H_

View File

@@ -0,0 +1,43 @@
#ifndef LOOP_CLOSURE_H_
#define LOOP_CLOSURE_H_
#include "read_configs.h"
#include "correlation_flow.h"
#include "map.h"
struct LoopClosureResult{
bool found;
Eigen::Vector3d response;
FramePtr current_frame;
FramePtr loop_frame;
Eigen::Vector3d relative_pose;
LoopClosureResult(): found(false), response(-1.0, -1.0, -1.0) {}
LoopClosureResult(bool _found, Eigen::Vector3d _resopnse): found(_found), response(_resopnse) {}
LoopClosureResult& operator=(const LoopClosureResult& other){
found = other.found;
response = other.response;
current_frame = other.current_frame;
loop_frame = other.loop_frame;
relative_pose = other.relative_pose;
return *this;
}
};
class LoopClosure{
public:
LoopClosure(LoopClosureConfig& loop_closure_config, CorrelationFlowPtr correlation_flow, MapPtr map);
LoopClosureResult FindLoopClosure(Eigen::ArrayXXf& image, FramePtr& current_frame);
LoopClosureResult FindLoopClosure(Eigen::ArrayXXf& image, FramePtr& current_frame, Eigen::Vector3d& prior_pose);
LoopClosureResult FindLoopClosure(Eigen::ArrayXXf& image, FramePtr& current_frame, std::vector<FramePtr>& frames);
private:
LoopClosureConfig _loop_thr;
CorrelationFlowPtr _correlation_flow;
MapPtr _map;
};
typedef std::shared_ptr<LoopClosure> LoopClosurePtr;
#endif // LOOP_CLOSURE_H_

View File

@@ -0,0 +1,81 @@
#ifndef MAP_H_
#define MAP_H_
#include <vector>
#include <map>
#include <unordered_set>
#include <unordered_map>
#include "read_configs.h"
#include "camera.h"
#include "frame.h"
#include "edge.h"
#include "utils.h"
struct GridLocation{
GridLocation() : x(0), y(0) {}
GridLocation(int x_, int y_) : x(x_), y(y_) {}
GridLocation& operator=(const GridLocation& other){
x = other.x;
y = other.y;
return *this;
}
friend std::ostream & operator<<(std::ostream &out, GridLocation &loc){
out << "(" << loc.x << ", " << loc.y << ")";
return out;
}
int x;
int y;
};
struct GridLocationHash{
std::size_t operator() (const GridLocation& loc) const{
return std::hash<int>()(loc.x) ^ std::hash<int>()(loc.y);
}
};
struct GridLocationEqual{
bool operator()(const GridLocation& l1, const GridLocation& l2) const{
return l1.x == l2.x && l1.y == l2.y;
}
};
typedef std::unordered_set<FramePtr> FrameSet;
typedef std::unordered_map<GridLocation, FrameSet, GridLocationHash, GridLocationEqual> GridMap;
class Map{
public:
Map();
Map(MapConfig& map_config);
void AddFrame(FramePtr& frame);
void SetFrameDistance(FramePtr& frame, double distance);
void AddEdge(EdgePtr& edge);
int GetAllFrames(std::vector<FramePtr>& frames);
double GetFrameDistance(FramePtr& frame);
int GetAllEdges(std::vector<EdgePtr>& edges);
void UpdatePoses(AlignedMap<int, Eigen::Vector3d> frame_poses);
GridLocation ComputeGridLocation(double x, double y);
GridLocation ComputeGridLocation(Eigen::Vector3d pose);
int GetFramesInGrids(std::vector<FramePtr>& frames, std::vector<GridLocation>& grid_locations);
FramePtr GetBaseframe();
private:
CameraPtr _camera;
std::map<int, FramePtr> _frames;
std::map<FramePtr, double> _frame_distanses;
std::map<int, EdgePtr> _edges;
double _grid_scale;
GridMap _grid_map;
FramePtr _baseframe;
};
typedef std::shared_ptr<Map> MapPtr;
#endif // MAP_H_

View File

@@ -0,0 +1,83 @@
#ifndef MAP_BUILDER_H_
#define MAP_BUILDER_H_
#include "read_configs.h"
#include "camera.h"
#include "frame.h"
#include "correlation_flow.h"
#include "map.h"
#include "loop_closure.h"
#include "map_stitcher.h"
class MapBuilder{
public:
MapBuilder(Configs& configs);
bool AddNewInput(cv::Mat& image, double timestamp = -1);
void ComputeFFTResult(cv::Mat& image);
void ConstructFrame(double timestamp);
void SetCurrentFramePose();
bool Initialize();
void UpdateIntermedium();
void UpdateCurrentPose();
bool Tracking(Eigen::Vector3d& response);
void AddCFEdge();
void AddCFEdgeToMap(Eigen::Vector3d& relative_pose, int from, int to,
int edge_id, Edge::Type edge_type, Eigen::Matrix3d& info);
Eigen::Vector2d ComputeRelativeDA();
void SetFrameDistance();
bool FindLoopClosure();
void AddLoopEdges();
bool OptimizeMap();
void CheckAndOptimize();
void UpdateValueAfterLoop();
// for visualization
bool GetCFPose(Eigen::Vector3d& pose);
bool GetFramePoses(Aligned<std::vector, Eigen::Vector3d>& poses, std::vector<double>& timestamps);
bool GetOccupancyMapOrigin(
Eigen::Vector3d& pixel_origin, Eigen::Matrix<double, 7, 1>& real_origin); // [qw, qx, qy, qz, x, y, z]
double GetMapResolution();
OccupancyData& GetMapData();
private:
bool _init;
int _frame_id;
int _edge_id;
bool _last_lost;
// tmp
FramePtr _last_frame;
FramePtr _current_frame;
// image plane pose
Eigen::Vector3d _last_cf_pose;
Eigen::Vector3d _current_cf_pose;
// real scale pose
Eigen::Vector3d _last_cf_real_pose;
Eigen::Vector3d _current_cf_real_pose;
// robot pose
Eigen::Vector3d _last_pose;
Eigen::Vector3d _current_pose;
// distance
double _distance;
// intermedium rsults
Eigen::ArrayXXf _image_array;
Eigen::ArrayXXcf _last_fft_result;
Eigen::ArrayXXcf _last_fft_polar;
Eigen::ArrayXXcf _fft_result;
Eigen::ArrayXXcf _fft_polar;
std::vector<LoopClosureResult> _loop_matches;
Configs _configs;
CameraPtr _camera;
CorrelationFlowPtr _correlation_flow;
KeyframeSelectionConfig _kfs_config;
MapPtr _map;
LoopClosurePtr _loop_closure;
MapStitcherPtr _map_stitcher;
};
#endif // MAP_BUILDER_H

View File

@@ -0,0 +1,42 @@
#ifndef MAP_STITCHER_H_
#define MAP_STITCHER_H_
#include "optimization_2d/pose_graph_2d_error_term.h"
#include "camera.h"
#include "frame.h"
#include "map.h"
#include "read_configs.h"
struct Cell{
int size;
Eigen::ArrayXXi data;
Eigen::ArrayXXi weight;
Cell(): size(0) {}
Cell(int _size): size(_size), data(Eigen::ArrayXXi::Zero(_size, _size)), weight(Eigen::ArrayXXi::Zero(_size, _size)) {}
};
typedef std::unordered_map<GridLocation, Cell, GridLocationHash, GridLocationEqual> OccupancyData;
class MapStitcher{
public:
MapStitcher(MapStitcherConfig config, CameraPtr camera);
void InsertFrame(FramePtr frame, cv::Mat& image);
// input is the posion in one axis, output is the cell and the position in cell
Eigen::Vector2i ComputeCellPosition(int x);
void AddImageToOccupancy(FramePtr frame);
void RecomputeOccupancy();
OccupancyData& GetOccupancyData();
private:
int _cell_size;
bool _to_stitch;
CameraPtr _camera;
std::unordered_map<FramePtr, Eigen::MatrixXi> _raw_images;
OccupancyData _occupancy_data;
};
typedef std::shared_ptr<MapStitcher> MapStitcherPtr;
#endif // MAP_STITCHER_H_

View File

@@ -0,0 +1,66 @@
// Ceres Solver - A fast non-linear least squares minimizer
// Copyright 2016 Google Inc. All rights reserved.
// http://ceres-solver.org/
//
// 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 Google Inc. 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 OWNER 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.
//
// Author: vitus@google.com (Michael Vitus)
#ifndef OPTIMIZATION_2D_ANGLE_LOCAL_PARAMETERIZATION_H_
#define OPTIMIZATION_2D_ANGLE_LOCAL_PARAMETERIZATION_H_
#include <ceres/local_parameterization.h>
#include "normalize_angle.h"
namespace ceres {
namespace optimization_2d {
// Defines a local parameterization for updating the angle to be constrained in
// [-pi to pi).
class AngleLocalParameterization {
public:
template <typename T>
bool operator()(const T* theta_radians,
const T* delta_theta_radians,
T* theta_radians_plus_delta) const {
*theta_radians_plus_delta =
NormalizeAngle(*theta_radians + *delta_theta_radians);
return true;
}
static ceres::LocalParameterization* Create() {
return (new ceres::AutoDiffLocalParameterization<AngleLocalParameterization,
1,
1>);
}
};
} // namespace optimization_2d
} // namespace ceres
#endif // OPTIMIZATION_2D_ANGLE_LOCAL_PARAMETERIZATION_H_

View File

@@ -0,0 +1,52 @@
// Ceres Solver - A fast non-linear least squares minimizer
// Copyright 2016 Google Inc. All rights reserved.
// http://ceres-solver.org/
//
// 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 Google Inc. 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 OWNER 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.
//
// Author: vitus@google.com (Michael Vitus)
#ifndef OPTIMIZATION_2D_NORMALIZE_ANGLE_H_
#define OPTIMIZATION_2D_NORMALIZE_ANGLE_H_
#include <cmath>
#include <ceres/ceres.h>
namespace ceres {
namespace optimization_2d {
// Normalizes the angle in radians between [-pi and pi).
template <typename T>
inline T NormalizeAngle(const T& angle_radians) {
// Use ceres::floor because it is specialized for double and Jet types.
T two_pi(2.0 * M_PI);
return angle_radians -
two_pi * ceres::floor((angle_radians + T(M_PI)) / two_pi);
}
} // namespace optimization_2d
} // namespace ceres
#endif // OPTIMIZATION_2D_NORMALIZE_ANGLE_H_

View File

@@ -0,0 +1,33 @@
#ifndef OPTIMIZATION_2D_POSE_GRAPH_2D_H_
#define OPTIMIZATION_2D_POSE_GRAPH_2D_H_
#include <fstream>
#include <iostream>
#include <map>
#include <string>
#include <vector>
#include <ceres/ceres.h>
#include "angle_local_parameterization.h"
#include "pose_graph_2d_error_term.h"
#include "types.h"
namespace ceres {
namespace optimization_2d {
void BuildOptimizationProblem(const std::vector<Constraint2d>& constraints,
std::map<int, Pose2d>* poses,
ceres::Problem* problem);
void BuildOptimizationProblemWithScale(const std::vector<Constraint2d>& constraints,
std::vector<ScaleData>& scale_data,
const std::vector<int>& scale_data_idx,
std::map<int, Pose2d>* poses,
ceres::Problem* problem);
bool SolveOptimizationProblem(ceres::Problem* problem);
} // namespace optimization_2d
} // namespace ceres
#endif // OPTIMIZATION_2D_POSE_GRAPH_2D_H_

View File

@@ -0,0 +1,183 @@
// Ceres Solver - A fast non-linear least squares minimizer
// Copyright 2016 Google Inc. All rights reserved.
// http://ceres-solver.org/
//
// 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 Google Inc. 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 OWNER 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.
//
// Author: vitus@google.com (Michael Vitus)
//
// Cost function for a 2D pose graph formulation.
#ifndef OPTIMIZATION_2D_POSE_GRAPH_2D_ERROR_TERM_H_
#define OPTIMIZATION_2D_POSE_GRAPH_2D_ERROR_TERM_H_
#include <Eigen/Core>
#include "optimization_2d/normalize_angle.h"
namespace ceres {
namespace optimization_2d {
template <typename T>
Eigen::Matrix<T, 2, 2> RotationMatrix2D(T yaw_radians) {
const T cos_yaw = ceres::cos(yaw_radians);
const T sin_yaw = ceres::sin(yaw_radians);
Eigen::Matrix<T, 2, 2> rotation;
rotation << cos_yaw, -sin_yaw, sin_yaw, cos_yaw;
return rotation;
}
// Computes the error term for two poses that have a relative pose measurement
// between them. Let the hat variables be the measurement.
//
// residual = information^{1/2} * [ r_a^T * (p_b - p_a) - \hat{p_ab} ]
// [ Normalize(yaw_b - yaw_a - \hat{yaw_ab}) ]
//
// where r_a is the rotation matrix that rotates a vector represented in frame A
// into the global frame, and Normalize(*) ensures the angles are in the range
// [-pi, pi).
class PoseGraph2dErrorTerm {
public:
PoseGraph2dErrorTerm(double x_ab,
double y_ab,
double yaw_ab_radians,
const Eigen::Matrix3d& sqrt_information)
: p_ab_(x_ab, y_ab),
yaw_ab_radians_(yaw_ab_radians),
sqrt_information_(sqrt_information) {}
template <typename T>
bool operator()(const T* const x_a,
const T* const y_a,
const T* const yaw_a,
const T* const x_b,
const T* const y_b,
const T* const yaw_b,
T* residuals_ptr) const {
const Eigen::Matrix<T, 2, 1> p_a(*x_a, *y_a);
const Eigen::Matrix<T, 2, 1> p_b(*x_b, *y_b);
Eigen::Map<Eigen::Matrix<T, 3, 1>> residuals_map(residuals_ptr);
residuals_map.template head<2>() =
RotationMatrix2D(*yaw_a).transpose() * (p_b - p_a) - p_ab_.cast<T>();
residuals_map(2) = NormalizeAngle(
(*yaw_b - *yaw_a) - static_cast<T>(yaw_ab_radians_));
// Scale the residuals by the square root information matrix to account for
// the measurement uncertainty.
residuals_map = sqrt_information_.template cast<T>() * residuals_map;
return true;
}
static ceres::CostFunction* Create(double x_ab,
double y_ab,
double yaw_ab_radians,
const Eigen::Matrix3d& sqrt_information) {
return (new ceres::
AutoDiffCostFunction<PoseGraph2dErrorTerm, 3, 1, 1, 1, 1, 1, 1>(
new PoseGraph2dErrorTerm(
x_ab, y_ab, yaw_ab_radians, sqrt_information)));
}
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
private:
// The position of B relative to A in the A frame.
const Eigen::Vector2d p_ab_;
// The orientation of frame B relative to frame A.
const double yaw_ab_radians_;
// The inverse square root of the measurement covariance matrix.
const Eigen::Matrix3d sqrt_information_;
};
class PoseGraph2dErrorTermWithScale {
public:
PoseGraph2dErrorTermWithScale(double x_ab,
double y_ab,
double yaw_ab_radians,
const Eigen::Matrix3d& sqrt_information)
: p_ab_(x_ab, y_ab),
yaw_ab_radians_(yaw_ab_radians),
sqrt_information_(sqrt_information) {}
template <typename T>
bool operator()(const T* const x_a,
const T* const y_a,
const T* const yaw_a,
const T* const x_b,
const T* const y_b,
const T* const yaw_b,
const T* const scale,
T* residuals_ptr) const {
const Eigen::Matrix<T, 2, 1> p_a(*x_a, *y_a);
const Eigen::Matrix<T, 2, 1> p_b(*x_b, *y_b);
Eigen::Map<Eigen::Matrix<T, 3, 1>> residuals_map(residuals_ptr);
Eigen::Matrix<T, 2, 2> scale_matrix = Eigen::Matrix<T, 2, 2>::Identity();
scale_matrix *= (*scale);
residuals_map.template head<2>() =
RotationMatrix2D(*yaw_a).transpose() * (p_b - p_a) - scale_matrix * p_ab_.cast<T>();
residuals_map(2) = NormalizeAngle(
(*yaw_b - *yaw_a) - static_cast<T>(yaw_ab_radians_));
// Scale the residuals by the square root information matrix to account for
// the measurement uncertainty.
residuals_map = sqrt_information_.template cast<T>() * residuals_map;
return true;
}
static ceres::CostFunction* Create(double x_ab,
double y_ab,
double yaw_ab_radians,
const Eigen::Matrix3d& sqrt_information) {
return (new ceres::
AutoDiffCostFunction<PoseGraph2dErrorTermWithScale, 3, 1, 1, 1, 1, 1, 1, 1>(
new PoseGraph2dErrorTermWithScale(
x_ab, y_ab, yaw_ab_radians, sqrt_information)));
}
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
private:
// The position of B relative to A in the A frame.
const Eigen::Vector2d p_ab_;
// The orientation of frame B relative to frame A.
const double yaw_ab_radians_;
// The inverse square root of the measurement covariance matrix.
const Eigen::Matrix3d sqrt_information_;
};
} // namespace optimization_2d
} // namespace ceres
#endif // OPTIMIZATION_2D_POSE_GRAPH_2D_ERROR_TERM_H_

View File

@@ -0,0 +1,116 @@
// Ceres Solver - A fast non-linear least squares minimizer
// Copyright 2016 Google Inc. All rights reserved.
// http://ceres-solver.org/
//
// 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 Google Inc. 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 OWNER 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.
//
// Author: vitus@google.com (Michael Vitus)
//
// Defines the types used in the 2D pose graph SLAM formulation. Each vertex of
// the graph has a unique integer ID with a position and orientation. There are
// delta transformation constraints between two vertices.
#ifndef OPTIMIZATION_2D_TYPES_H_
#define OPTIMIZATION_2D_TYPES_H_
#include <fstream>
#include <Eigen/Core>
#include "optimization_2d/normalize_angle.h"
namespace ceres {
namespace optimization_2d {
struct ScaleData{
double scale;
bool fixed;
ScaleData() {}
ScaleData(double _scale, bool _fixed): scale(_scale), fixed(_fixed) {}
};
inline std::istream& operator>>(std::istream& input, ScaleData& scale_data) {
input >> scale_data.scale >> scale_data.fixed;
// Normalize the angle between -pi to pi.
return input;
}
// The state for each vertex in the pose graph.
struct Pose2d {
double x;
double y;
double yaw_radians;
// The name of the data type in the g2o file format.
static std::string name() { return "VERTEX_SE2"; }
};
inline std::istream& operator>>(std::istream& input, Pose2d& pose) {
input >> pose.x >> pose.y >> pose.yaw_radians;
// Normalize the angle between -pi to pi.
pose.yaw_radians = NormalizeAngle(pose.yaw_radians);
return input;
}
// The constraint between two vertices in the pose graph. The constraint is the
// transformation from vertex id_begin to vertex id_end.
struct Constraint2d {
int id_begin;
int id_end;
double x;
double y;
double yaw_radians;
// The inverse of the covariance matrix for the measurement. The order of the
// entries are x, y, and yaw.
Eigen::Matrix3d information;
// The name of the data type in the g2o file format.
static std::string name() { return "EDGE_SE2"; }
};
inline std::istream& operator>>(std::istream& input, Constraint2d& constraint) {
input >> constraint.id_begin >> constraint.id_end >> constraint.x >>
constraint.y >> constraint.yaw_radians >> constraint.information(0, 0) >>
constraint.information(0, 1) >> constraint.information(0, 2) >>
constraint.information(1, 1) >> constraint.information(1, 2) >>
constraint.information(2, 2);
// Set the lower triangular part of the information matrix.
constraint.information(1, 0) = constraint.information(0, 1);
constraint.information(2, 0) = constraint.information(0, 2);
constraint.information(2, 1) = constraint.information(1, 2);
// Normalize the angle between -pi to pi.
constraint.yaw_radians = NormalizeAngle(constraint.yaw_radians);
return input;
}
} // namespace optimization_2d
} // namespace ceres
#endif // OPTIMIZATION_2D_TYPES_H_

View File

@@ -0,0 +1,137 @@
#ifndef READ_CONFIGS_H_
#define READ_CONFIGS_H_
#include <iostream>
#include <yaml-cpp/yaml.h>
#include "utils.h"
struct DatasetConfig{
std::string dataroot;
std::string image_dir_name;
std::string camera_file;
};
struct CFConfig{
int width;
int height;
float lambda;
int kernel;
float sigma;
float offset;
int power;
int rotation_divisor;
int rotation_channel;
};
struct KeyframeSelectionConfig{
double max_distance;
double max_angle;
double lower_response_thr;
double upper_response_thr;
};
struct MapConfig{
double grid_scale;
};
struct LoopClosureConfig{
bool to_find_loop;
double position_response_thr;
double angle_response_thr;
int frame_gap_thr;
double distance_thr;
};
struct MapStitcherConfig{
bool stitch_map;
int cell_size;
};
struct VisualizationConfig{
std::string frame_id;
std::string kcc_pose_topic;
std::string frame_pose_topic;
std::string map_topic;
std::string image_topic;
};
struct SavingConfig{
std::string saving_root;
bool save_pose;
};
struct Configs{
DatasetConfig dataset_config;
CFConfig cf_config;
KeyframeSelectionConfig keyframe_selection_config;
MapConfig map_config;
LoopClosureConfig loop_closure_config;
MapStitcherConfig map_stitcher_config;
VisualizationConfig visualization_config;
SavingConfig saving_config;
Configs(const std::string& config_file){
if(!FileExists(config_file)){
std::cout << "config file: " << config_file << " doesn't exist" << std::endl;
return;
}
YAML::Node file_node = YAML::LoadFile(config_file);
YAML::Node dataset_node = file_node["dataset"];
dataset_config.dataroot = dataset_node["dataroot"].as<std::string>();
dataset_config.image_dir_name = dataset_node["image_dir_name"].as<std::string>();
dataset_config.camera_file = dataset_node["camera_config"].as<std::string>();
YAML::Node cf_node = file_node["correlation_flow"];
cf_config.width = cf_node["width"].as<int>();
cf_config.height = cf_node["height"].as<int>();
cf_config.lambda = cf_node["lambda"].as<float>();
cf_config.rotation_divisor = cf_node["rotation_divisor"].as<int>();
cf_config.rotation_channel = cf_node["rotation_channel"].as<int>();
cf_config.kernel = cf_node["kernel"].as<int>();
cf_config.offset = cf_node["polynomial"]["offset"].as<float>();
cf_config.power = cf_node["polynomial"]["power"].as<int>();
cf_config.sigma = cf_node["gaussian"]["sigma"].as<float>();
YAML::Node kfs_node = file_node["keyframe_selection"];
keyframe_selection_config.max_distance = kfs_node["max_distance"].as<double>();
keyframe_selection_config.max_angle = kfs_node["max_angle"].as<double>();
keyframe_selection_config.lower_response_thr = kfs_node["lower_response_thr"].as<double>();
keyframe_selection_config.upper_response_thr = kfs_node["upper_response_thr"].as<double>();
YAML::Node map_node = file_node["map"];
map_config.grid_scale = map_node["grid_scale"].as<double>();
YAML::Node loop_closure_node = file_node["loop_closure"];
loop_closure_config.to_find_loop =
loop_closure_node["to_find_loop"].as<bool>();
loop_closure_config.position_response_thr =
loop_closure_node["position_response_thr"].as<double>();
loop_closure_config.angle_response_thr =
loop_closure_node["angle_response_thr"].as<double>();
loop_closure_config.frame_gap_thr =
loop_closure_node["frame_gap_thr"].as<int>();
loop_closure_config.distance_thr =
loop_closure_node["distance_thr"].as<double>();
YAML::Node map_stitcher_node = file_node["map_sticther"];
map_stitcher_config.stitch_map = map_stitcher_node["stitch_map"].as<bool>();
map_stitcher_config.cell_size = map_stitcher_node["cell_size"].as<int>();
YAML::Node visualization_node = file_node["visualization"];
visualization_config.frame_id = visualization_node["frame_id"].as<std::string>();
visualization_config.kcc_pose_topic = visualization_node["topic"]["kcc_pose"].as<std::string>();
visualization_config.frame_pose_topic = visualization_node["topic"]["frame_pose"].as<std::string>();
visualization_config.map_topic = visualization_node["topic"]["map"].as<std::string>();
visualization_config.image_topic = visualization_node["topic"]["image"].as<std::string>();
YAML::Node saving_node = file_node["saving"];
saving_config.saving_root = saving_node["saving_root"].as<std::string>();
saving_config.save_pose = saving_node["save_pose"].as<bool>();
}
};
#endif // READ_CONFIGS_H_

View File

@@ -0,0 +1,32 @@
#ifndef THREAD_PUBLISHER_H_
#define THREAD_PUBLISHER_H_
#include <string>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <vector>
#include <queue>
#include <functional>
template <typename T>
class ThreadPublisher {
public:
ThreadPublisher();
~ThreadPublisher();
void Register(std::function<void(const std::shared_ptr<const T>&)> cb);
void Start();
void Publish(const std::shared_ptr<const T> msg);
void Process();
void ShutDown();
private:
std::mutex msg_mutex_;
std::condition_variable msg_cond_;
std::queue<std::shared_ptr<const T>> msgs_;
std::thread publish_thread_;
std::vector<std::function<void(const std::shared_ptr<const T>&)>> callbacks_;
bool shutdown_requested_;
};
#endif // THREAD_PUBLISHER_H_

27
src/ground_slam/include/timer.h Executable file
View File

@@ -0,0 +1,27 @@
#ifndef _TIMER_H_
#define _TIMER_H_
#include <sys/time.h>
#include <stdio.h>
typedef struct{
struct timeval start;
struct timeval stop;
}Timer;
void startTimer(Timer *pTimer);
void stopTimer(Timer *pTimer);
double getElapsedTime(Timer *pTimer);
void writeTimeToFile(double arrTime[], int nCount, int nFrameNo, char *filename);
#define INITIALIZE_TIMER Timer stTimer; double arrTime[100]
#define START_TIMER startTimer(&stTimer)
#define STOP_TIMER(text) stopTimer(&stTimer); printf(text); printf(": %.1f\n",getElapsedTime(&stTimer))
#define END_TIMER(nIndex) stopTimer(&stTimer); arrTime[nIndex] = getElapsedTime(&stTimer)
#define ACC_TIMER(nIndex) stopTimer(&stTimer); arrTime[nIndex] += getElapsedTime(&stTimer)
#define WRITE_TIME_FILE(nCount, nFrameNo, filename) writeTimeToFile(arrTime, nCount, nFrameNo, (char *)filename)
#endif//_TIMER_H_

View File

@@ -0,0 +1,82 @@
#ifndef UTILS_H_
#define UTILS_H_
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <sys/types.h>
#include <sys/stat.h>
#include <functional>
#include <map>
#include <limits.h>
#include <memory>
#include <type_traits>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <Eigen/Core>
#include <Eigen/StdVector>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/opencv.hpp>
#include <opencv2/core/eigen.hpp>
// Eigen type
template <template <typename, typename> class Container, typename Type>
using Aligned = Container<Type, Eigen::aligned_allocator<Type>>;
template <typename KeyType, typename ValueType>
using AlignedMap =
std::map<KeyType, ValueType, std::less<KeyType>,
Eigen::aligned_allocator<std::pair<const KeyType, ValueType>>>;
template <typename KeyType, typename ValueType>
using AlignedUnorderedMap = std::unordered_map<
KeyType, ValueType, std::hash<KeyType>, std::equal_to<KeyType>,
Eigen::aligned_allocator<std::pair<const KeyType, ValueType>>>;
template <typename KeyType, typename ValueType>
using AlignedUnorderedMultimap = std::unordered_multimap<
KeyType, ValueType, std::hash<KeyType>, std::equal_to<KeyType>,
Eigen::aligned_allocator<std::pair<const KeyType, ValueType>>>;
template <typename Type>
using AlignedUnorderedSet =
std::unordered_set<Type, std::hash<Type>, std::equal_to<Type>,
Eigen::aligned_allocator<Type>>;
// files
bool FileExists(const std::string& file);
bool PathExists(const std::string& path);
void ConcatenateFolderAndFileName(
const std::string& folder, const std::string& file_name,
std::string* path);
std::string ConcatenateFolderAndFileName(
const std::string& folder, const std::string& file_name);
void MakeDir(const std::string& path);
void ReadTxt(const std::string& file_path,
std::vector<std::vector<std::string> >& lines, std::string seq);
void WriteTxt(const std::string file_path,
std::vector<std::vector<std::string> >& lines, std::string seq);
// correlation flow
void ConvertMatToNormalizedArray(cv::Mat& image, Eigen::ArrayXXf& array);
Eigen::ArrayXXf ConvertMatToArray(const cv::Mat&);
cv::Mat ConvertArrayToMat(const Eigen::ArrayXXf&);
Eigen::ArrayXXf RotateArray(const Eigen::ArrayXXf&, float);
Eigen::ArrayXXf WarpArray(const Eigen::ArrayXXf&, float tx, float ty, float degree);
double NormalizeDegree(double angle_degree);
// Eigen pose
Eigen::Vector3d ComputeRelativePose(Eigen::Vector3d& pose1, Eigen::Vector3d& pose2);
Eigen::Vector3d ComputeAbsolutePose(Eigen::Vector3d& pose1, Eigen::Vector3d& relative_pose);
void ShowArray(const Eigen::ArrayXXf&, std::string window="debug", int waitKey=1);
#endif // UTILS_H_

View File

@@ -0,0 +1,65 @@
#ifndef VISUALIZATION_H_
#define VISUALIZATION_H_
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <functional>
#include <map>
#include <memory>
#include <Eigen/Core>
#include <rclcpp/rclcpp.hpp>
#include <nav_msgs/msg/path.hpp>
#include <geometry_msgs/msg/quaternion.hpp>
#include <geometry_msgs/msg/pose_stamped.hpp>
#include <nav_msgs/msg/occupancy_grid.hpp>
#include <nav_msgs/msg/odometry.hpp>
#include <sensor_msgs/msg/image.hpp>
#include <sensor_msgs/msg/point_cloud2.hpp>
#include <cv_bridge/cv_bridge.h>
#include "read_configs.h"
#include "map_stitcher.h"
#include "map_builder.h"
class Visualizer {
public:
enum class TrajectoryType {
Frame = 0,
KCC = 1,
Odom = 2,
};
Visualizer(rclcpp::Node::SharedPtr node, VisualizationConfig& config);
void AddNewPoseToPath(
Eigen::Vector3d& pose, double time_double,
nav_msgs::msg::Path& path, std::string& frame_id);
void UpdateOdomPose(Eigen::Vector3d& pose, double time_double);
void UpdateKccPose(Eigen::Vector3d& pose, double time_double);
void UpdateFramePose(Aligned<std::vector, Eigen::Vector3d>& frame_poses,
std::vector<double>& timestamps);
void ConvertMapToOccupancyMsgs(OccupancyData& map,
nav_msgs::msg::OccupancyGrid& msgs);
void UpdateMap(MapBuilder& map_builder);
void PublishImage(cv::Mat& image, double time_double);
void GetTrajectoryTxt(std::vector<std::vector<std::string>>& lines,
TrajectoryType trajectory_type);
private:
rclcpp::Node::SharedPtr node_;
std::string frame_id_;
rclcpp::Publisher<nav_msgs::msg::Path>::SharedPtr kcc_pose_pub_;
rclcpp::Publisher<nav_msgs::msg::Path>::SharedPtr frame_pose_pub_;
rclcpp::Publisher<nav_msgs::msg::OccupancyGrid>::SharedPtr map_pub_;
rclcpp::Publisher<sensor_msgs::msg::Image>::SharedPtr image_pub_;
nav_msgs::msg::Path odom_pose_msgs_;
nav_msgs::msg::Path kcc_pose_msgs_;
nav_msgs::msg::Path frame_pose_msgs_;
nav_msgs::msg::OccupancyGrid occupancy_map_msgs_;
};
#endif // VISUALIZATION_H_

110
src/ground_slam/main.cpp Executable file
View File

@@ -0,0 +1,110 @@
#include <iostream>
#include <iomanip>
#include <queue>
#include <string>
#include <unistd.h>
#include <Eigen/Dense>
#include <opencv2/highgui/highgui.hpp>
#include <rclcpp/rclcpp.hpp>
#include <cv_bridge/cv_bridge.h>
#include "read_configs.h"
#include "dataset.h"
#include "camera.h"
#include "frame.h"
#include "map_stitcher.h"
#include "map_builder.h"
#include "thread_publisher.h"
#include "visualization.h"
#include <typeinfo>
#include <time.h>
using namespace std;
class GroundSlamNode : public rclcpp::Node {
public:
GroundSlamNode(const std::string& config_file)
: Node("build_map"), configs_(config_file) {}
void run() {
DatasetConfig dataset_config = configs_.dataset_config;
Dataset dataset(dataset_config.dataroot, dataset_config.image_dir_name);
MapBuilder map_builder(configs_);
Visualizer visualizer(this->shared_from_this(), configs_.visualization_config);
Aligned<std::vector, Eigen::Vector3d> frame_poses;
std::vector<double> timestamps;
Eigen::Vector3d new_kcc_pose;
size_t dataset_length = dataset.GetDatasetLength();
for (size_t i = 0; i < dataset_length; ++i) {
if (!rclcpp::ok()) break;
std::cout << i << std::endl;
cv::Mat image;
if (!dataset.GetImage(image, i)) {
std::cout << "can not get image " << i << std::endl;
break;
}
double time_double = dataset.GetTimestamp(i);
visualizer.PublishImage(image, time_double);
auto t1 = std::chrono::high_resolution_clock::now();
bool insert_keyframe = map_builder.AddNewInput(image, time_double);
auto t2 = std::chrono::high_resolution_clock::now();
auto compute_time = std::chrono::duration_cast<std::chrono::microseconds>(t2 - t1).count() / 1e3;
std::cout << "processing for one frame is " << compute_time << "ms" << std::endl;
if ((i + 1) >= dataset_length) {
map_builder.CheckAndOptimize();
} else if (!insert_keyframe) {
continue;
}
std::cout << "Insert a keyframe !" << std::endl;
if (map_builder.GetCFPose(new_kcc_pose)) {
visualizer.UpdateKccPose(new_kcc_pose, time_double);
}
if (map_builder.GetFramePoses(frame_poses, timestamps)) {
visualizer.UpdateFramePose(frame_poses, timestamps);
}
visualizer.UpdateMap(map_builder);
rclcpp::spin_some(this->shared_from_this());
}
// save trajectories
std::string saving_root = configs_.saving_config.saving_root;
MakeDir(saving_root);
std::string trajectory_KCC = saving_root + "/KCC_Keyframe.txt";
std::string trajectory_frame = saving_root + "/optimized_keyframe.txt";
std::vector<std::vector<std::string>> kcc_keyframe_lines, optimized_keyframe_lines;
visualizer.GetTrajectoryTxt(kcc_keyframe_lines, Visualizer::TrajectoryType::KCC);
visualizer.GetTrajectoryTxt(optimized_keyframe_lines, Visualizer::TrajectoryType::Frame);
WriteTxt(trajectory_KCC, kcc_keyframe_lines, " ");
WriteTxt(trajectory_frame, optimized_keyframe_lines, " ");
}
private:
Configs configs_;
};
int main(int argc, char** argv) {
rclcpp::init(argc, argv);
if (argc < 2) {
std::cerr << "Usage: ground_slam <config_yaml>" << std::endl;
rclcpp::shutdown();
return 1;
}
auto node = std::make_shared<GroundSlamNode>(argv[1]);
node->run();
rclcpp::shutdown();
return 0;
}

View File

@@ -0,0 +1,27 @@
<?xml version="1.0"?>
<?xml-model href="http://download.ros.org/schema/package_format3.xsd" schematypens="http://www.w3.org/2001/XMLSchema"?>
<package format="3">
<name>ground_slam</name>
<version>0.1.0</version>
<description>GroundSLAM: Feature-free ground-texture-based visual SLAM for warehouse robots (ROS2 port)</description>
<maintainer email="sunrise@todo.todo">sunrise</maintainer>
<license>MIT</license>
<buildtool_depend>ament_cmake</buildtool_depend>
<depend>rclcpp</depend>
<depend>geometry_msgs</depend>
<depend>visualization_msgs</depend>
<depend>nav_msgs</depend>
<depend>std_msgs</depend>
<depend>sensor_msgs</depend>
<depend>cv_bridge</depend>
<depend>tf2</depend>
<depend>tf2_geometry_msgs</depend>
<depend>tf2_ros</depend>
<export>
<build_type>ament_cmake</build_type>
</export>
</package>

View File

@@ -0,0 +1,243 @@
#include <yaml-cpp/yaml.h>
#include <math.h>
#include <unistd.h>
#include <iostream>
#include "camera.h"
#include "utils.h"
#include "optimization_2d/pose_graph_2d_error_term.h"
using namespace std;
Camera::Camera(){
}
Camera::Camera(const std::string& camera_file){
if(!FileExists(camera_file)){
std::cout << "camera file: " << camera_file << " doesn't exist" << std::endl;
return;
}
YAML::Node file_node = YAML::LoadFile(camera_file);
_image_width = file_node["image_size"][0].as<int>();
_image_height = file_node["image_size"][1].as<int>();
_height = file_node["height"].as<double>();
_accurate_height = file_node["accurate_height"].as<bool>();
_new_scale = 0;
_new_width = 0;
_new_height = 0;
YAML::Node K_node = file_node["intrinsics"]["data"];
double fx = K_node[0].as<double>();
double cx = K_node[1].as<double>();
double fy = K_node[2].as<double>();
double cy = K_node[3].as<double>();
_K = (cv::Mat_<double>(3, 3) << fx, 0.0, cx, 0.0, fy, cy, 0.0, 0.0, 1.0);
YAML::Node D_node = file_node["distortion"]["data"];
double D_data[5];
for(size_t i = 0; i < 5; i++){
D_data[i] = D_node[i].as<double>();
}
_D = (cv::Mat_<double>(5, 1) << D_data[0], D_data[1], D_data[2], D_data[3], D_data[4]);
cv::Size image_size(_image_width, _image_height);
_new_K = getOptimalNewCameraMatrix(_K, _D, image_size, 0, image_size);
initUndistortRectifyMap(_K, _D, cv::Mat(), _new_K, image_size, CV_16SC2, _map1, _map2);
// // update _new_K
// if(_image_width > _image_height)
// {
// _scale = min(_new_K.at<double>(0,0), _new_K.at<double>(1,1)) / max(_new_K.at<double>(0,0), _new_K.at<double>(1,1));
// _new_width = round(_image_width * _scale);
// _new_scale = double(_new_width) / double(_image_width);
// cout << "_new width: " << _new_width << endl;
// _new_K.at<double>(0,0) = _new_K.at<double>(0,0) / _new_scale;
// _new_K.at<double>(0,2) = _new_K.at<double>(0,2) / _new_scale;
// _image_width = _new_width;
// }
// else{
// _scale = min(_new_K.at<double>(0,0), _new_K.at<double>(1,1)) / max(_new_K.at<double>(0,0), _new_K.at<double>(1,1));
// _new_height = round(_image_height * _scale);
// _new_scale = _new_height / _image_height;
// _new_K.at<double>(1,1) = _new_K.at<double>(1,1) / _new_scale;
// _new_K.at<double>(1,2) = _new_K.at<double>(1,2) / _new_scale;
// _image_height = _new_height;
// }
YAML::Node E_node = file_node["extrinsics"]["data"];
for(size_t i = 0; i < 3; i++){
for(size_t j = 0; j < 3; j++){
size_t idx = 3 * i + j;
_extrinsics(i, j) = E_node[idx].as<double>();
}
}
}
Camera& Camera::operator=(const Camera& camera){
_image_height = camera._image_height;
_image_width = camera._image_width;
_height = camera._height;
_accurate_height = camera._accurate_height;
_K = camera._K.clone();
_new_K = camera._new_K;
_D = camera._D.clone();
_map1 = camera._map1.clone();
_map2 = camera._map2.clone();
_extrinsics = camera._extrinsics;
return *this;
}
void Camera::UndistortImage(cv::Mat& image, cv::Mat& undistort_image){
remap(image, undistort_image, _map1, _map2, cv::INTER_LINEAR);
// cv::Mat _new_undistort_image;
// if(_new_height == 0 && _new_scale != 0){
// resize(undistort_image, _new_undistort_image, cv::Size(), _new_scale, 1.0, cv::INTER_LINEAR);
// }
// else if(_new_width == 0 && _new_scale != 0){
// resize(undistort_image, _new_undistort_image, cv::Size(), 1.0, _new_scale, cv::INTER_LINEAR);
// }
// _new_undistort_image.copyTo(undistort_image);
}
void Camera::GetNewCameraMatrix(cv::Mat& camera_matrix){
camera_matrix = _new_K.clone();
}
double Camera::GetImageHeight(){
return _image_height;
}
bool Camera::HeightIsAccurate(){
return _accurate_height;
}
double Camera::GetImageWidth(){
return _image_width;
}
double Camera::GetHeight(){
return _height;
}
void Camera::GetExtrinsics(Eigen::Matrix3d& extrinsics){
extrinsics = _extrinsics;
}
double Camera::GetLengthOfPixel(){
Eigen::Vector3d pixel(1.0, 1.0, 0.0);
Eigen::Vector3d real;
ConvertImagePlanePoseToRobot(pixel, real);
return (real(0) + real(1)) / 2;
}
Eigen::Vector3d Camera::ConvertPrincipalToCenter(const Eigen::Vector3d& image_plane_pose){
Eigen::Vector3d image_center_pose;
const Eigen::Matrix2d I2 = Eigen::Matrix2d::Identity();
image_center_pose(2) = image_plane_pose(2);
Eigen::Matrix2d R = ceres::optimization_2d::RotationMatrix2D(image_plane_pose(2));
Eigen::Vector2d O_bias;
O_bias << (_image_width * 0.5 - _new_K.at<double>(0, 2)), (_image_height * 0.5 - _new_K.at<double>(1, 2));
image_center_pose.head(2) = image_plane_pose.head(2) - (I2 - R) * O_bias;
return image_center_pose;
}
Eigen::Vector3d Camera::ConvertCenterToPrincipal(const Eigen::Vector3d& image_center_pose){
Eigen::Vector3d image_plane_pose;
const Eigen::Matrix2d I2 = Eigen::Matrix2d::Identity();
image_plane_pose(2) = image_center_pose(2);
Eigen::Matrix2d R = ceres::optimization_2d::RotationMatrix2D(image_center_pose(2));
Eigen::Vector2d O_bias;
O_bias << (_image_width * 0.5 - _new_K.at<double>(0, 2)), (_image_height * 0.5 - _new_K.at<double>(1, 2));
image_plane_pose.head(2) = image_center_pose.head(2) + (I2 - R) * O_bias;
return image_plane_pose;
}
bool Camera::ConvertImagePlanePoseToCamera(
Eigen::Vector3d& image_plane_pose, Eigen::Vector3d& camera_pose){
double u = image_plane_pose(0);
double v = image_plane_pose(1);
double angle = image_plane_pose(2);
double fx = _new_K.at<double>(0, 0);
// double cx = _new_K.at<double>(0, 2);
double fy = _new_K.at<double>(1, 1);
// double cy = _new_K.at<double>(1, 2);
double x = u / fx;
double y = v / fy;
camera_pose << x, y, angle;
return true;
}
bool Camera::ConvertCameraPoseToImagePlane(
Eigen::Vector3d& image_plane_pose, Eigen::Vector3d& camera_pose){
double x = camera_pose(0);
double y = camera_pose(1);
double angle = camera_pose(2);
double fx = _new_K.at<double>(0, 0);
// double cx = _new_K.at<double>(0, 2);
double fy = _new_K.at<double>(1, 1);
// double cy = _new_K.at<double>(1, 2);
double u = fx * x;
double v = fy * y;
image_plane_pose << u, v, angle;
return true;
}
bool Camera::ConvertCameraPoseToRobot(
Eigen::Vector3d& camera_pose, Eigen::Vector3d& robot_pose){
if(_height < 0){
std::cout << "camera height: " << _height << " < 0" << std::endl;
return false;
}
double x = _height * camera_pose(0);
double y = _height * camera_pose(1);
robot_pose << x, y, camera_pose(2);
robot_pose = _extrinsics * robot_pose;
return true;
}
bool Camera::ConvertRobotPoseToCamera(
Eigen::Vector3d& camera_pose, Eigen::Vector3d& robot_pose){
if(_height < 0){
std::cout << "camera height: " << _height << " < 0" << std::endl;
return false;
}
camera_pose = _extrinsics.inverse() * robot_pose;
camera_pose(0) /= _height;
camera_pose(1) /= _height;
return true;
}
bool Camera::ConvertImagePlanePoseToRobot(
Eigen::Vector3d& image_plane_pose, Eigen::Vector3d& robot_pose){
Eigen::Vector3d camera_pose;
bool c1 = ConvertImagePlanePoseToCamera(image_plane_pose, camera_pose);
bool c2 = ConvertCameraPoseToRobot(camera_pose, robot_pose);
return (c1 && c2);
}
bool Camera::ConvertRobotPoseToImagePlane(
Eigen::Vector3d& image_plane_pose, Eigen::Vector3d& robot_pose){
Eigen::Vector3d camera_pose;
bool c1 = ConvertRobotPoseToCamera(camera_pose, robot_pose);
bool c2 = ConvertCameraPoseToImagePlane(image_plane_pose, camera_pose);
return (c1 && c2);
}

View File

@@ -0,0 +1,228 @@
#include <math.h>
#include <opencv2/imgproc.hpp>
#include "correlation_flow.h"
#include "read_configs.h"
#include "circ_shift.h"
#include "optimization_2d/pose_graph_2d_error_term.h"
#include <iostream>
#include <fstream>
using namespace std;
#include "unistd.h"
#include <chrono>
using namespace std::chrono;
// // void PrintArrayToFile (const Eigen::ArrayXXf target, int rows, int cols) {
// void PrintArrayToFile (const auto& target, int rows, int cols) {
// ofstream myfile ("example.txt");
// if (myfile.is_open())
// {
// for(int count_row = 0; count_row < rows; count_row ++){
// for(int count_col = 0; count_col < cols; count_col ++){
// myfile << target(count_row, count_col) << " " ;
// if(count_col == cols - 1){
// myfile << "\n";
// }
// }
// }
// myfile.close();
// }
// else std::cout << "Unable to open file";
// }
CorrelationFlow::CorrelationFlow(CFConfig& cf_config, double &image_height, double &image_width):cfg(cf_config){
cfg.height = int(image_height);
cfg.width = int(image_width);
target_fft = GetTargetFFT(cfg.height, cfg.width);
target_rotation_fft = GetTargetFFT(cfg.rotation_divisor, cfg.rotation_channel);
}
Eigen::ArrayXXcf CorrelationFlow::GetTargetFFT(int rows, int cols){
Eigen::ArrayXXf target = Eigen::ArrayXXf::Zero(rows, cols);
target(rows/2, cols/2) = 1;
return FFT(target);
}
Eigen::ArrayXXcf CorrelationFlow::FFT(const Eigen::ArrayXXf& x){
Eigen::ArrayXXcf xf = Eigen::ArrayXXcf(x.rows()/2+1, x.cols()); // xf [225, 448]
fftwf_plan fft_plan = fftwf_plan_dft_r2c_2d(x.cols(), x.rows(), (float(*))(x.data()),
(float(*)[2])(xf.data()), FFTW_ESTIMATE); // reverse order for column major
fftwf_execute(fft_plan);
fftwf_destroy_plan(fft_plan);
fftw_cleanup();
return xf;
}
Eigen::ArrayXXf CorrelationFlow::IFFT(const Eigen::ArrayXXcf& xf){
Eigen::ArrayXXf x = Eigen::ArrayXXf((xf.rows()-1)*2, xf.cols());
Eigen::ArrayXXcf cxf = xf;
fftwf_plan fft_plan = fftwf_plan_dft_c2r_2d(xf.cols(), (xf.rows()-1)*2, (float(*)[2])(cxf.data()),
(float(*))(x.data()), FFTW_ESTIMATE);
fftwf_execute(fft_plan);
fftwf_destroy_plan(fft_plan);
fftw_cleanup();
return x/x.size();
}
inline Eigen::ArrayXXf CorrelationFlow::RemoveZeroComponent(const Eigen::ArrayXXf& x){
Eigen::ArrayXXf y(x);
unsigned int cols = x.cols();
unsigned int rows = x.rows();
y.block(0, 0, 1, cols) = (x.block(1, 0, 1, cols) + x.block(rows-1, 0, 1, cols))/2.0;
y.block(0, 0, rows, 1) = (x.block(0, 1, rows, 1) + x.block(0, cols-1, rows, 1))/2.0;
return y;
}
void CorrelationFlow::ComputeIntermedium(const Eigen::ArrayXXf& image, Eigen::ArrayXXcf& fft_result, Eigen::ArrayXXcf& fft_polar){
fft_result = FFT(image);
Eigen::ArrayXXf power = IFFT(fft_result.abs());
auto high_power = RemoveZeroComponent(power);
fft_polar = FFT(polar(fftshift(high_power)));
}
Eigen::Vector3d CorrelationFlow::ComputePose(const Eigen::ArrayXXcf& last_fft_result, const Eigen::ArrayXXf& image,
const Eigen::ArrayXXcf& last_fft_polar, const Eigen::ArrayXXcf& fft_polar,
Eigen::Vector3d& pose, bool not_large_rotation){
Eigen::Vector2d trans, trans_orig, trans_veri, rots; Eigen::Vector3d info; float info_trans;
auto info_rots = EstimateTrans(last_fft_polar, fft_polar, target_rotation_fft, cfg.rotation_divisor, cfg.rotation_channel, rots);
float degree = rots[0]*(2.0/cfg.rotation_divisor)*180;
degree = NormalizeDegree(degree);
if(not_large_rotation){
degree = std::abs(degree) > 90 ? degree - 180 : degree;
auto fft_rot_orig = FFT(RotateArray(image, -degree));
float info_trans_orig = EstimateTrans(last_fft_result, fft_rot_orig, target_fft, cfg.height, cfg.width, trans_orig);
info_trans = info_trans_orig;
trans = trans_orig;
degree = degree;
}else{
auto fft_rot_orig = FFT(RotateArray(image, -degree));
auto fft_rot_veri = FFT(RotateArray(image, -degree+180));
float info_trans_orig = EstimateTrans(last_fft_result, fft_rot_orig, target_fft, cfg.height, cfg.width, trans_orig); //error
float info_trans_veri = EstimateTrans(last_fft_result, fft_rot_veri, target_fft, cfg.height, cfg.width, trans_veri);
if (info_trans_orig > info_trans_veri)
{
info_trans = info_trans_orig;
trans = trans_orig;
degree = degree;
}
else{
info_trans = info_trans_veri;
trans = trans_veri;
degree = degree + 180;
}
}
(degree>180)? degree=degree-360 : degree=degree;
float theta = degree/180*M_PI;
info[0] = info_trans; pose[0] = trans[1];
info[1] = info_trans; pose[1] = trans[0];
info[2] = info_rots; pose[2] = theta;
std::cout<<"X, Y, \u0398: "<<pose.transpose()<<" Rad = "<< degree <<"Degree"<<std::endl;
std::cout<<"Info: "<<info.transpose()<<std::endl;
auto rectify = WarpArray(IFFT(last_fft_result),-pose[0],-pose[1], degree);
return info;
}
float CorrelationFlow::EstimateTrans(const Eigen::ArrayXXcf& last_fft_result, const Eigen::ArrayXXcf& fft_result,
const Eigen::ArrayXXcf& output_fft, int height, int width, Eigen::Vector2d& trans){
/// @brief can esrimate translation, rotation, and scale
/// @param last_fft_result fft result of key frame
/// @param fft_result current frame's fft result
/// @param output_fft target_rotation_fft generate from GetTargetFFT(720, 480)
/// @param height cfg.rotation_divisor
/// @param width cfg.rotation_channel
/// @param trans the result, ie. rotation degree, notice that the trans length is two, trans[0] is actually the degree we need
Eigen::ArrayXXcf Kzz, Kxz;
switch(cfg.kernel) {
case 0:
Kzz = polynomial_kernel(last_fft_result, height, width);
Kxz = polynomial_kernel(fft_result, last_fft_result, height, width);
break;
case 1:
Kzz = gaussian_kernel(last_fft_result, height, width);
Kxz = gaussian_kernel(fft_result, last_fft_result, height, width);
break;
default:
throw std::invalid_argument( "Received invalid kernel type" );
}
auto H = output_fft/(Kzz + cfg.lambda);
Eigen::ArrayXXcf G = H*Kxz;
Eigen::ArrayXXf g = IFFT(G);
Eigen::ArrayXXf::Index row, col;
float response = g.maxCoeff(&(row), &(col));
trans[0] = -(row-height/2);
trans[1] = -(col-width/2);
return GetInfo(g, response);
}
inline Eigen::ArrayXXcf CorrelationFlow::gaussian_kernel(const Eigen::ArrayXXcf& xf, const Eigen::ArrayXXcf& zf, int height, int width){
unsigned int N = height * width;
auto xx = xf.square().abs().sum()/N; // Parseval's Theorem
auto zz = zf.square().abs().sum()/N;
auto zfc = zf.conjugate();
Eigen::ArrayXXcf xzf = xf * zfc;
auto xz = IFFT(xzf);
auto xxzz = (xx+zz-2*xz)/N;
Eigen::ArrayXXf kernel = (-1/(cfg.sigma*cfg.sigma)*xxzz).exp();
kernel = kernel/kernel.abs().maxCoeff();
return FFT(kernel);
}
inline Eigen::ArrayXXcf CorrelationFlow::gaussian_kernel(const Eigen::ArrayXXcf& xf, int height, int width){
unsigned int N = height * width;
auto xx = xf.square().abs().sum()/N; // Parseval's Theorem
auto zfc = xf.conjugate();
Eigen::ArrayXXcf xzf = xf * zfc;
auto xz = IFFT(xzf);
auto xxzz = (xx+xx-2*xz)/N;
Eigen::ArrayXXf kernel = (-1/(cfg.sigma*cfg.sigma)*xxzz).exp();
kernel = kernel/kernel.abs().maxCoeff();
return FFT(kernel);
}
inline Eigen::ArrayXXcf CorrelationFlow::polynomial_kernel(const Eigen::ArrayXXcf& xf, const Eigen::ArrayXXcf& zf, int height, int width){
auto zfc = zf.conjugate();
Eigen::ArrayXXcf xzf = xf * zfc;
auto xz = IFFT(xzf);
Eigen::ArrayXXf kernel = (xz+cfg.offset).pow(cfg.power);
kernel = kernel/kernel.abs().maxCoeff();
return FFT(kernel);
}
inline Eigen::ArrayXXcf CorrelationFlow::polynomial_kernel(const Eigen::ArrayXXcf& xf, int height, int width){
auto zfc = xf.conjugate();
Eigen::ArrayXXcf xzf = xf * zfc;
auto xz = IFFT(xzf);
Eigen::ArrayXXf kernel = (xz+cfg.offset).pow(cfg.power);
kernel = kernel/kernel.abs().maxCoeff();
return FFT(kernel);
}
inline Eigen::ArrayXXf CorrelationFlow::polar(const Eigen::ArrayXXf& array){
cv::Mat polar_img, img=ConvertArrayToMat(array);
cv::Point2f center((float)img.cols/2, (float)img.rows/2);
double radius = (double)std::min(img.rows/2, img.cols/2);
cv::Size dsize = cv::Size(cfg.rotation_channel, cfg.rotation_divisor);
cv::warpPolar(img, polar_img, dsize, center, radius, cv::INTER_LINEAR + cv::WARP_FILL_OUTLIERS);
return ConvertMatToArray(polar_img);
}
inline float CorrelationFlow::GetInfo(const Eigen::ArrayXXf& output, float response){
float side_lobe_mean = (output.sum()-response)/(output.size()-1);
float std = sqrt((output-side_lobe_mean).square().mean());
return (response - side_lobe_mean)/(std+1e-7);
}

View File

@@ -0,0 +1,55 @@
#include "dataset.h"
#include "utils.h"
#include<iostream>
#include <unistd.h>
using namespace std;
Dataset::Dataset(const std::string& dataroot, const std::string& image_dir_name): _dataroot(dataroot){
if(!PathExists(dataroot)){
std::cout << "dataroot : " << dataroot << " doesn't exist" << std::endl;
exit(0);
}
_image_dir = ConcatenateFolderAndFileName(_dataroot, image_dir_name);
_image_name_file_path = ConcatenateFolderAndFileName(_dataroot, "image_names.txt");
_time_file_path = ConcatenateFolderAndFileName(_dataroot, "times.txt");
std::vector<std::vector<std::string> > image_names_data;
ReadTxt(_image_name_file_path, image_names_data, ",");
for(std::vector<std::string>& line : image_names_data){
_image_names.emplace_back(line[0]);
}
std::vector<std::vector<std::string> > timestamps_data;
if(FileExists(_time_file_path)){
ReadTxt(_time_file_path, timestamps_data, ",");
for(std::vector<std::string>& line : timestamps_data){
_timestamps.push_back(atof(line[0].c_str()));
}
}
}
size_t Dataset::GetDatasetLength(){
return _image_names.size();
}
bool Dataset::GetImage(cv::Mat& image, size_t idx){
if(idx >= _image_names.size()){
return false;
}
std::string image_name = _image_names[idx];
std::string image_path = ConcatenateFolderAndFileName(_image_dir, image_name);
image = cv::imread(image_path, cv::ImreadModes::IMREAD_GRAYSCALE);
return true;
}
double Dataset::GetTimestamp(size_t idx){
if(idx < _timestamps.size()){
return _timestamps[idx];
}else{
return -1.0;
}
}

View File

@@ -0,0 +1,9 @@
#include "edge.h"
Edge::Edge(){
}
Edge::Edge(int edge_id, Type type, int from, int to, Eigen::Vector3d& T, Eigen::Matrix3d& information):
_edge_id(edge_id), _type(type), _from(from), _to(to), _T(T), _information(information){
}

View File

@@ -0,0 +1,77 @@
#include "frame.h"
Frame::Frame(){
}
Frame::Frame(int frame_id): _frame_id(frame_id){
}
Frame::Frame(int frame_id, double timestamp, Eigen::ArrayXXf& frame, Eigen::ArrayXXcf& fft_result, Eigen::ArrayXXcf& fft_polar):
_frame_id(frame_id), _timestamp(timestamp), _frame(frame), _fft_result(fft_result), _fft_polar(fft_polar){
}
Frame& Frame::operator=(const Frame& other){
_frame_id = other._frame_id;
_timestamp = other._timestamp;
_fft_result = other._fft_result;
_fft_polar = other._fft_polar;
_pose = other._pose;
_edge_ids = other._edge_ids;
return *this;
}
void Frame::SetFrameId(int frame_id){
_frame_id = frame_id;
}
int Frame::GetFrameId(){
return _frame_id;
}
double Frame::GetTimestamp(){
return _timestamp;
}
Eigen::ArrayXXf Frame::GetFrame(){
return _frame;
}
void Frame::SetFFTResult(Eigen::ArrayXXcf& fft_result){
_fft_result = fft_result;
}
void Frame::SetFFTResult(Eigen::ArrayXXcf& fft_result,
Eigen::ArrayXXcf& fft_polar){
_fft_result = fft_result;
_fft_polar = fft_polar;
}
void Frame::GetFFTResult(Eigen::ArrayXXcf& fft_result){
fft_result = _fft_result;
}
void Frame::GetFFTResult(Eigen::ArrayXXcf& fft_result,
Eigen::ArrayXXcf& fft_polar){
fft_result = _fft_result;
fft_polar = _fft_polar;
}
void Frame::SetPose(Eigen::Vector3d& pose){
_pose = pose;
}
void Frame::GetPose(Eigen::Vector3d& pose){
pose = _pose;
}
void Frame::AddEdge(int edge_id){
_edge_ids.emplace_back(edge_id);
}
void Frame::GetEdgeIds(std::vector<int>& edge_ids){
edge_ids = _edge_ids;
}
void Frame::SaveToDisk(const std::string root_dir){
//TODO
}

View File

@@ -0,0 +1,74 @@
#include "loop_closure.h"
#include <cmath>
LoopClosure::LoopClosure(LoopClosureConfig& loop_closure_config,
CorrelationFlowPtr correlation_flow, MapPtr map):
_loop_thr(loop_closure_config), _correlation_flow(correlation_flow), _map(map){
}
LoopClosureResult LoopClosure::FindLoopClosure(Eigen::ArrayXXf& image, FramePtr& current_frame){
std::vector<FramePtr> frames;
_map->GetAllFrames(frames);
LoopClosureResult result = FindLoopClosure(image, current_frame, frames);
return result;
}
LoopClosureResult LoopClosure::FindLoopClosure(
Eigen::ArrayXXf& image, FramePtr& current_frame, Eigen::Vector3d& prior_pose){
std::vector<GridLocation> grid_locations;
GridLocation grid_location = _map->ComputeGridLocation(prior_pose);
for(int i = -1; i <= 1; i++){
for(int j = -1; j <= 1; j++){
GridLocation gl = grid_location;
gl.x += i;
gl.y += j;
grid_locations.emplace_back(gl);
}
}
std::vector<FramePtr> frames;
_map->GetFramesInGrids(frames, grid_locations);
LoopClosureResult result = FindLoopClosure(image, current_frame, frames);
return result;
}
LoopClosureResult LoopClosure::FindLoopClosure(
Eigen::ArrayXXf& image, FramePtr& current_frame, std::vector<FramePtr>& frames){
Eigen::ArrayXXcf current_fft_result, current_fft_polar;
current_frame->GetFFTResult(current_fft_result, current_fft_polar);
LoopClosureResult result;
result.current_frame = current_frame;
for(FramePtr frame : frames){
if(_loop_thr.frame_gap_thr > 0 &&
std::abs((current_frame->GetFrameId() - frame->GetFrameId())) < _loop_thr.frame_gap_thr){
continue;
}
if(_loop_thr.distance_thr > 0){
double d1 = _map->GetFrameDistance(current_frame); // distance is accumulation distance
double d2 = _map->GetFrameDistance(frame);
if(std::abs((d1 - d2)) < _loop_thr.distance_thr){
continue;
}
}
Eigen::ArrayXXcf fft_result, fft_polar;
frame->GetFFTResult(fft_result, fft_polar);
Eigen::Vector3d relative_pose;
Eigen::Vector3d response =
_correlation_flow->ComputePose(fft_result, image, fft_polar, current_fft_polar, relative_pose, false);
if(response.sum() > result.response.sum()){
result.response = response;
result.loop_frame = frame;
result.relative_pose = relative_pose;
}
}
bool c1 = (result.response(0) > _loop_thr.position_response_thr);
bool c2 = (result.response(2) > _loop_thr.angle_response_thr);
result.found = (c1 && c2);
return result;
}

105
src/ground_slam/src/map.cc Normal file
View File

@@ -0,0 +1,105 @@
#include <iostream>
#include <unistd.h>
#include <map>
#include <vector>
#include "map.h"
using namespace std;
Map::Map(): _grid_scale(1.0){
}
Map::Map(MapConfig& map_config): _grid_scale(map_config.grid_scale){
}
void Map::AddFrame(FramePtr& frame){
if(_frames.size() < 1){
_baseframe = frame;
frame->SetFrameId(0);
}
int frame_id = frame->GetFrameId();
_frames[frame_id] = frame;
Eigen::Vector3d pose;
frame->GetPose(pose);
GridLocation grid_location = ComputeGridLocation(pose);
_grid_map[grid_location].insert(frame);
}
void Map::SetFrameDistance(FramePtr& frame, double distance){
_frame_distanses[frame] = distance;
}
void Map::AddEdge(EdgePtr& edge){
int edge_id = edge->_edge_id;
int from = edge->_from;
int to = edge->_to;
_edges[edge_id] = edge;
if(_frames.count(from) > 0){
_frames[from]->AddEdge(edge_id);
}
if(_frames.count(to) > 0){
_frames[to]->AddEdge(edge_id);
}
}
int Map::GetAllFrames(std::vector<FramePtr>& frames){
for(auto kv : _frames){
frames.emplace_back(kv.second);
}
return frames.size();
}
double Map::GetFrameDistance(FramePtr& frame){
if(_frame_distanses.count(frame) > 0){
return _frame_distanses[frame];
}else{
return -1;
}
}
int Map::GetAllEdges(std::vector<EdgePtr>& edges){
for(auto kv : _edges){
edges.emplace_back(kv.second);
}
return edges.size();
}
void Map::UpdatePoses(AlignedMap<int, Eigen::Vector3d> frame_poses){
for(auto kv : frame_poses){
if(_frames.count(kv.first) > 0){
_frames[kv.first]->SetPose(kv.second);
}
}
}
GridLocation Map::ComputeGridLocation(double x, double y){
int grid_x = static_cast<int>((x / _grid_scale));
int grid_y = static_cast<int>((y / _grid_scale));
return GridLocation(grid_x, grid_y);
}
GridLocation Map::ComputeGridLocation(Eigen::Vector3d pose){
double x = pose(0);
double y = pose(1);
return ComputeGridLocation(x, y);
}
int Map::GetFramesInGrids(
std::vector<FramePtr>& frames, std::vector<GridLocation>& grid_locations){
for(auto grid_location : grid_locations){
if(_grid_map.count(grid_location) > 0){
frames.insert(frames.end(), _grid_map[grid_location].begin(), _grid_map[grid_location].end());
}
}
return frames.size();
}
FramePtr Map::GetBaseframe(){
return _baseframe;
}

View File

@@ -0,0 +1,334 @@
#include "map_builder.h"
#include <set>
#include <string>
#include <cmath>
#include <iostream>
#include <Eigen/Dense>
#include <Eigen/SparseCore>
#include "edge.h"
#include "utils.h"
#include "optimization_2d/types.h"
#include "optimization_2d/pose_graph_2d.h"
using namespace std;
MapBuilder::MapBuilder(Configs& configs):_init(false), _frame_id(0), _edge_id(0),
_configs(configs), _kfs_config(configs.keyframe_selection_config){
_camera = std::shared_ptr<Camera>(new Camera(configs.dataset_config.camera_file));
double _image_height = _camera->GetImageHeight();
double _image_width = _camera->GetImageWidth();
_correlation_flow = std::shared_ptr<CorrelationFlow>(new CorrelationFlow(configs.cf_config, _image_height, _image_width));
_map = std::shared_ptr<Map>(new Map(configs.map_config));
_loop_closure = std::shared_ptr<LoopClosure>(
new LoopClosure(configs.loop_closure_config, _correlation_flow, _map));
_map_stitcher = std::shared_ptr<MapStitcher>(new MapStitcher(configs.map_stitcher_config, _camera));
}
bool MapBuilder::AddNewInput(cv::Mat& image, double timestamp){
cv::Mat undistort_image;
_camera->UndistortImage(image, undistort_image);
ComputeFFTResult(undistort_image);
ConstructFrame(timestamp);
if(!_init){
Initialize();
_map_stitcher->InsertFrame(_current_frame, undistort_image);
UpdateIntermedium();
return true;
}
Eigen::Vector3d response;
bool good_tracking = Tracking(response);
if(good_tracking){
UpdateCurrentPose();
SetCurrentFramePose();
Eigen::Vector2d da = ComputeRelativeDA();
bool c1 = da(0) > _kfs_config.max_distance;
bool c2 = da(1) > _kfs_config.max_angle;
bool c3 = ((response(0) > _kfs_config.lower_response_thr) && (response(0) < _kfs_config.upper_response_thr));
bool c4 = ((response(2) > _kfs_config.lower_response_thr) && (response(2) < _kfs_config.upper_response_thr));
bool to_insert = (c1 || c2 || c3 || c4);
if(!to_insert) return false;
_distance += da(0);
}else{
return false;
}
if(good_tracking) AddCFEdge();
_map->AddFrame(_current_frame);
SetFrameDistance();
_map_stitcher->InsertFrame(_current_frame, undistort_image);
bool loop_found = _configs.loop_closure_config.to_find_loop ? FindLoopClosure() : false;
if(!loop_found){
CheckAndOptimize();
}
UpdateIntermedium();
return true;
}
void MapBuilder::ComputeFFTResult(cv::Mat& image){
ConvertMatToNormalizedArray(image, _image_array);
_correlation_flow->ComputeIntermedium(_image_array, _fft_result, _fft_polar);
}
void MapBuilder::ConstructFrame(double timestamp){
_current_frame = std::shared_ptr<Frame>(
new Frame(_frame_id++, timestamp, _image_array, _fft_result, _fft_polar));
}
void MapBuilder::SetCurrentFramePose(){
_current_frame->SetPose(_current_pose);
}
bool MapBuilder::Initialize(){
_current_cf_pose << 0.0, 0.0, 0.0;
_camera->ConvertImagePlanePoseToCamera(_current_cf_pose, _current_cf_real_pose);
_camera->ConvertCameraPoseToRobot(_current_cf_real_pose, _current_pose);
SetCurrentFramePose();
_map->AddFrame(_current_frame);
_distance = 0;
_map->SetFrameDistance(_current_frame, _distance);
_init = true;
_last_lost = false;
return true;
}
void MapBuilder::UpdateIntermedium(){
_last_frame = _current_frame;
_last_cf_pose = _current_cf_pose;
_last_cf_real_pose = _current_cf_real_pose;
_last_pose = _current_pose;
_last_fft_result = _fft_result;
_last_fft_polar = _fft_polar;
}
void MapBuilder::CheckAndOptimize(){
if(_loop_matches.size() >= 2){
AddLoopEdges();
OptimizeMap();
UpdateValueAfterLoop();
_map_stitcher->RecomputeOccupancy();
}
_loop_matches.clear();
}
void MapBuilder::UpdateCurrentPose(){
Eigen::Vector3d last_robot_pose_from_cf, current_robot_pose_from_cf;
_camera->ConvertImagePlanePoseToRobot(_last_cf_pose, last_robot_pose_from_cf);
_camera->ConvertImagePlanePoseToRobot(_current_cf_pose, current_robot_pose_from_cf);
Eigen::Vector3d relativate_pose_from_cf = ComputeRelativePose(last_robot_pose_from_cf, current_robot_pose_from_cf);
Eigen::Vector3d relative_pose = relativate_pose_from_cf;
_current_pose = ComputeAbsolutePose(_last_pose, relative_pose);
}
bool MapBuilder::Tracking(Eigen::Vector3d& response){
Eigen::Vector3d relative_pose;
response = _correlation_flow->ComputePose(
_last_fft_result, _image_array, _last_fft_polar, _fft_polar, relative_pose, true);
relative_pose = _camera->ConvertCenterToPrincipal(relative_pose);
bool good_tracking = ((response(0) > _kfs_config.lower_response_thr) && ((response(2) > _kfs_config.lower_response_thr)));
if(good_tracking){
_current_cf_pose = ComputeAbsolutePose(_last_cf_pose, relative_pose);
_camera->ConvertImagePlanePoseToCamera(_current_cf_pose, _current_cf_real_pose);
}
return good_tracking;
}
void MapBuilder::AddCFEdge(){
Eigen::Vector3d relative_cf_real_pose = ComputeRelativePose(_last_cf_real_pose, _current_cf_real_pose);
Eigen::Matrix3d info = Eigen::Matrix3d::Identity();
AddCFEdgeToMap(relative_cf_real_pose, _last_frame->GetFrameId(), _current_frame->GetFrameId(), _edge_id++, Edge::Type::KCC, info);
}
void MapBuilder::AddCFEdgeToMap(Eigen::Vector3d& relative_pose, int from, int to,
int edge_id, Edge::Type edge_type, Eigen::Matrix3d& info){
EdgePtr cf_edge = std::make_shared<Edge>();
cf_edge->_edge_id = edge_id;
cf_edge->_type = edge_type;
cf_edge->_from = from;
cf_edge->_to = to;
cf_edge->_T = relative_pose;
cf_edge->_information = info;
_map->AddEdge(cf_edge);
}
Eigen::Vector2d MapBuilder::ComputeRelativeDA(){
Eigen::Vector3d rlt_camera_pose;
Eigen::Vector3d rlt_pose = _current_cf_pose - _last_cf_pose;
_camera->ConvertImagePlanePoseToCamera(rlt_pose, rlt_camera_pose);
double d = sqrt(rlt_camera_pose.head(2).dot(rlt_camera_pose.head(2)));
Eigen::Vector2d result;
result << d, std::abs(rlt_camera_pose(2));
return result;
}
void MapBuilder::SetFrameDistance(){
_map->SetFrameDistance(_current_frame, _distance);
}
bool MapBuilder::FindLoopClosure(){
LoopClosureResult loop_closure_result = _loop_closure->FindLoopClosure(_image_array, _current_frame, _current_pose);
if(loop_closure_result.found){
loop_closure_result.relative_pose = _camera->ConvertCenterToPrincipal(loop_closure_result.relative_pose);
_loop_matches.emplace_back(loop_closure_result);
std::cout << "Find a loop edge, current frame = " << loop_closure_result.current_frame->GetFrameId()
<< ", loop frame = " << loop_closure_result.loop_frame->GetFrameId() << std::endl;
}
return loop_closure_result.found;
}
void MapBuilder::AddLoopEdges(){
for(auto loop_match : _loop_matches){ // greater than two matches
int edge_id = _edge_id++;
int from = loop_match.loop_frame->GetFrameId();
int to = loop_match.current_frame->GetFrameId();
Eigen::Vector3d relative_pose;
_camera->ConvertImagePlanePoseToCamera(loop_match.relative_pose, relative_pose);
Eigen::Matrix3d info = Eigen::Matrix3d::Identity();
AddCFEdgeToMap(relative_pose, from, to, edge_id, Edge::Type::Loop, info);
}
}
bool MapBuilder::OptimizeMap(){
std::map<int, ceres::optimization_2d::Pose2d> poses;
std::vector<ceres::optimization_2d::Constraint2d> constraints;
std::vector<FramePtr> frames;
std::set<int> frame_ids;
std::vector<EdgePtr> edges;
_map->GetAllFrames(frames);
_map->GetAllEdges(edges);
for(FramePtr& frame : frames){
int frame_id = frame->GetFrameId();
Eigen::Vector3d pose_vec;
frame->GetPose(pose_vec);
frame_ids.insert(frame_id);
ceres::optimization_2d::Pose2d pose_2d;
pose_2d.x = pose_vec(0);
pose_2d.y = pose_vec(1);
pose_2d.yaw_radians = pose_vec(2);
poses.insert(std::pair<int, ceres::optimization_2d::Pose2d>(frame_id, pose_2d));
}
std::vector<ceres::optimization_2d::ScaleData> scale_data;
ceres::optimization_2d::ScaleData cf_scale;
cf_scale.scale = _camera->GetImageHeight();
if(!_camera->HeightIsAccurate()){
cf_scale.fixed = false;
}else{
cf_scale.fixed = true;
}
scale_data.emplace_back(cf_scale);
std::vector<int> scale_data_idx;
for(EdgePtr& edge : edges){
int from = edge->_from;
int to = edge->_to;
if((frame_ids.count(from) < 1) || (frame_ids.count(to) < 1)){
continue;
}
Eigen::Vector3d relative_pose;
if(edge->_type == Edge::Type::KCC || edge->_type == Edge::Type::Loop){
scale_data_idx.emplace_back(0);
_camera->ConvertCameraPoseToRobot(edge->_T, relative_pose);
}else{
continue;
}
ceres::optimization_2d::Constraint2d constraint;
constraint.id_begin = from;
constraint.id_end = to;
constraint.x = relative_pose(0);
constraint.y = relative_pose(1);
constraint.yaw_radians = relative_pose(2);
constraint.information = edge->_information;
constraints.emplace_back(constraint);
}
ceres::Problem problem;
ceres::optimization_2d::BuildOptimizationProblem(constraints, &poses, &problem);
// ceres::optimization_2d::BuildOptimizationProblemWithScale(constraints, scale_data, scale_data_idx, &poses, &problem);
CHECK(ceres::optimization_2d::SolveOptimizationProblem(&problem))
<< "The solve was not successful, exiting.";
// copy back frame pose
AlignedMap<int, Eigen::Vector3d> frame_poses;
for(auto kv : poses){
Eigen::Vector3d frame_pose;
frame_pose << kv.second.x, kv.second.y, kv.second.yaw_radians;
frame_poses[kv.first] = frame_pose;
}
_map->UpdatePoses(frame_poses);
std::cout << "Map optimization is done !" << std::endl;
return true;
}
void MapBuilder::UpdateValueAfterLoop(){
_current_frame->GetPose(_current_pose);
_camera->ConvertRobotPoseToCamera(_current_cf_real_pose, _current_pose);
_camera->ConvertCameraPoseToImagePlane(_current_cf_pose, _current_cf_real_pose);
}
// for visualization
bool MapBuilder::GetCFPose(Eigen::Vector3d& pose){
Eigen::Vector3d cf_base_pose(0.0, 0.0, 0.0);
Eigen::Vector3d robot_base_pose;
_camera->ConvertImagePlanePoseToRobot(cf_base_pose, robot_base_pose);
Eigen::Vector3d robot_current_pose;
_camera->ConvertImagePlanePoseToRobot(_current_cf_pose, robot_current_pose);
pose = ComputeRelativePose(robot_base_pose, robot_current_pose);
return true;
}
bool MapBuilder::GetFramePoses(Aligned<std::vector, Eigen::Vector3d>& poses, std::vector<double>& timestamps){
poses.clear();
timestamps.clear();
std::vector<FramePtr> frames;
_map->GetAllFrames(frames);
for(auto frame : frames){
Eigen::Vector3d pose;
frame->GetPose(pose);
poses.emplace_back(pose);
timestamps.emplace_back(frame->GetTimestamp());
}
return true;
}
bool MapBuilder::GetOccupancyMapOrigin(
Eigen::Vector3d& pixel_origin, Eigen::Matrix<double, 7, 1>& real_origin){
Eigen::Matrix3d Rbc;
_camera->GetExtrinsics(Rbc);
Eigen::Quaterniond qbc(Rbc);
real_origin(0, 0) = qbc.w();
real_origin(1, 0) = qbc.x();
real_origin(2, 0) = qbc.y();
real_origin(3, 0) = qbc.z();
Eigen::Vector3d robot_origin;
_camera->ConvertImagePlanePoseToRobot(pixel_origin, robot_origin);
real_origin(4, 0) = robot_origin(0);
real_origin(5, 0) = robot_origin(1);
real_origin(6, 0) = robot_origin(2);
return true;
}
double MapBuilder::GetMapResolution(){
return _camera->GetLengthOfPixel();
}
OccupancyData& MapBuilder::GetMapData(){
return _map_stitcher->GetOccupancyData();
}

View File

@@ -0,0 +1,149 @@
#include "map_stitcher.h"
#include "utils.h"
#include <algorithm>
#include <iostream>
using namespace std;
MapStitcher::MapStitcher(MapStitcherConfig config, CameraPtr camera):
_cell_size(config.cell_size), _to_stitch(config.stitch_map), _camera(camera){
}
void MapStitcher::InsertFrame(FramePtr frame, cv::Mat& image){
if(!_to_stitch) return;
const double scale = 100.0 / 255.0;
cv::Mat norm_image = image * scale;
Eigen::MatrixXi matrix;
cv::cv2eigen(norm_image, matrix);
_raw_images[frame] = matrix;
AddImageToOccupancy(frame);
}
Eigen::Vector2i MapStitcher::ComputeCellPosition(int x){
Eigen::Vector2i result;
if(x >=0 ){
result(0) = x / _cell_size;
}else{
result(0) = (x - _cell_size + 1) / _cell_size;
}
result(1) = x - result(0) * _cell_size;
return result;
}
void MapStitcher::AddImageToOccupancy(FramePtr frame){
Eigen::MatrixXi& data = _raw_images[frame];
Eigen::Vector3d robot_pose, image_pose;
frame->GetPose(robot_pose);
_camera->ConvertRobotPoseToImagePlane(image_pose, robot_pose);
image_pose = _camera->ConvertPrincipalToCenter(image_pose);
int W = data.cols();
int H = data.rows();
Eigen::Matrix2d R = ceres::optimization_2d::RotationMatrix2D(image_pose(2));
Eigen::VectorXd W_idx(W);
Eigen::VectorXd H_idx(H);
Eigen::VectorXd X(W);
Eigen::VectorXd Y(W);
double cx = (double)W / 2;
double cy = (double)H / 2;
for(int i = 0; i < W; i++){
W_idx(i) = i - cx;
X(i) = image_pose(0);
Y(i) = image_pose(1);
}
for(int i = 0; i < H; i++) H_idx(i) = i - cy;
Eigen::VectorXd Wx = R(0, 0) * W_idx + X;
Eigen::VectorXd Wy = R(1, 0) * W_idx + Y;
Eigen::VectorXd Hx = R(0, 1) * H_idx;
Eigen::VectorXd Hy = R(1, 1) * H_idx;
// find which cells may be used
int x00 = static_cast<int>((Wx(0) + Hx(0)));
int y00 = static_cast<int>((Wy(0) + Hy(0)));
int x01 = static_cast<int>((Wx(0) + Hx((H-1))));
int y01 = static_cast<int>((Wy(0) + Hy((H-1))));
int x10 = static_cast<int>((Wx((W-1)) + Hx(0)));
int y10 = static_cast<int>((Wy((W-1)) + Hy(0)));
int x11 = static_cast<int>((Wx((W-1)) + Hx((H-1))));
int y11 = static_cast<int>((Wy((W-1)) + Hy((H-1))));
int min_x = std::min(x00, std::min(x01, std::min(x10, x11)));
int max_x = std::max(x00, std::max(x01, std::max(x10, x11)));
int min_y = std::min(y00, std::min(y01, std::min(y10, y11)));
int max_y = std::max(y00, std::max(y01, std::max(y10, y11)));
Eigen::Vector2i min_cell_x = ComputeCellPosition(min_x);
Eigen::Vector2i max_cell_x = ComputeCellPosition(max_x);
Eigen::Vector2i min_cell_y = ComputeCellPosition(min_y);
Eigen::Vector2i max_cell_y = ComputeCellPosition(max_y);
std::unordered_map<GridLocation, bool, GridLocationHash, GridLocationEqual> locations;
OccupancyData tmp_data;
for(int i = min_cell_x(0); i <= max_cell_x(0); i++){
for(int j = min_cell_y(0); j <= max_cell_y(0); j++){
GridLocation grid_location(i, j);
tmp_data[grid_location] = Cell(_cell_size);
locations[grid_location] = false;
}
}
for(int i = 0; i < W; i++){
for(int j = 0; j < H; j ++){
int x = static_cast<int>((Wx(i) + Hx(j)));
int y = static_cast<int>((Wy(i) + Hy(j)));
Eigen::Vector2i cell_x = ComputeCellPosition(x);
Eigen::Vector2i cell_y = ComputeCellPosition(y);
GridLocation grid_location(cell_x(0), cell_y(0));
// cout << data.size() << endl;
// sleep(1000);
tmp_data[grid_location].data(cell_y(1), cell_x(1)) += data(j, i);
tmp_data[grid_location].weight(cell_y(1), cell_x(1)) += 1;
locations[grid_location] = true;
}
}
for(auto& kv : tmp_data){
GridLocation loc = kv.first;
if(!locations[loc]) continue;
if(_occupancy_data.count(loc) > 0){
_occupancy_data[loc].size = _cell_size;
_occupancy_data[loc].data =
_occupancy_data[loc].data * _occupancy_data[loc].weight + tmp_data[loc].data * tmp_data[loc].weight;
_occupancy_data[loc].weight = _occupancy_data[loc].weight + tmp_data[loc].weight;
for(int i = 0; i < _cell_size; i++){
for(int j = 0; j < _cell_size; j++){
if(_occupancy_data[loc].weight(i, j) < 1) continue;
_occupancy_data[loc].data(i, j) = _occupancy_data[loc].data(i, j) / _occupancy_data[loc].weight(i, j);
}
}
}else{
_occupancy_data[loc].size = _cell_size;
_occupancy_data[loc].data = tmp_data[loc].data;
_occupancy_data[loc].weight = tmp_data[loc].weight;
}
}
}
void MapStitcher::RecomputeOccupancy(){
std::cout << "Recompute occupancy map ........" << std::endl;
_occupancy_data.clear();
for(auto kv : _raw_images){
AddImageToOccupancy(kv.first);
Eigen::Vector3d pose;
kv.first->GetPose(pose);
}
std::cout << "Occupancy map has been updated !" << std::endl;
}
OccupancyData& MapStitcher::GetOccupancyData(){
return _occupancy_data;
}

View File

@@ -0,0 +1,221 @@
// Ceres Solver - A fast non-linear least squares minimizer
// Copyright 2016 Google Inc. All rights reserved.
// http://ceres-solver.org/
//
// 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 Google Inc. 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 OWNER 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.
//
// Author: vitus@google.com (Michael Vitus)
//
// An example of solving a graph-based formulation of Simultaneous Localization
// and Mapping (SLAM). It reads a 2D pose graph problem definition file in the
// g2o format, formulates and solves the Ceres optimization problem, and outputs
// the original and optimized poses to file for plotting.
#include <fstream>
#include <iostream>
#include <map>
#include <string>
#include <vector>
#include <gflags/gflags.h>
#include <glog/logging.h>
#include "optimization_2d/pose_graph_2d.h"
namespace ceres {
namespace optimization_2d {
// Constructs the nonlinear least squares optimization problem from the pose
// graph constraints.
void BuildOptimizationProblem(const std::vector<Constraint2d>& constraints,
std::map<int, Pose2d>* poses,
ceres::Problem* problem) {
CHECK(poses != NULL);
CHECK(problem != NULL);
if (constraints.empty()) {
LOG(INFO) << "No constraints, no problem to optimize.";
return;
}
ceres::LossFunction* loss_function = NULL;
ceres::LocalParameterization* angle_local_parameterization =
AngleLocalParameterization::Create();
for (std::vector<Constraint2d>::const_iterator constraints_iter =
constraints.begin();
constraints_iter != constraints.end();
++constraints_iter) {
const Constraint2d& constraint = *constraints_iter;
std::map<int, Pose2d>::iterator pose_begin_iter =
poses->find(constraint.id_begin);
CHECK(pose_begin_iter != poses->end())
<< "Pose with ID: " << constraint.id_begin << " not found.";
std::map<int, Pose2d>::iterator pose_end_iter =
poses->find(constraint.id_end);
CHECK(pose_end_iter != poses->end())
<< "Pose with ID: " << constraint.id_end << " not found.";
const Eigen::Matrix3d sqrt_information =
constraint.information.llt().matrixL();
// Ceres will take ownership of the pointer.
ceres::CostFunction* cost_function = PoseGraph2dErrorTerm::Create(
constraint.x, constraint.y, constraint.yaw_radians, sqrt_information);
problem->AddResidualBlock(cost_function,
loss_function,
&pose_begin_iter->second.x,
&pose_begin_iter->second.y,
&pose_begin_iter->second.yaw_radians,
&pose_end_iter->second.x,
&pose_end_iter->second.y,
&pose_end_iter->second.yaw_radians);
problem->SetParameterization(&pose_begin_iter->second.yaw_radians,
angle_local_parameterization);
problem->SetParameterization(&pose_end_iter->second.yaw_radians,
angle_local_parameterization);
}
// fix base frame
std::map<int, Pose2d>::iterator baseframe_pose_iter = poses->find(0);
CHECK(baseframe_pose_iter != poses->end());
problem->SetParameterBlockConstant(&baseframe_pose_iter->second.x);
problem->SetParameterBlockConstant(&baseframe_pose_iter->second.y);
problem->SetParameterBlockConstant(&baseframe_pose_iter->second.yaw_radians);
}
void BuildOptimizationProblemWithScale(const std::vector<Constraint2d>& constraints,
std::vector<ScaleData>& scale_data,
const std::vector<int>& scale_data_idx,
std::map<int, Pose2d>* poses,
ceres::Problem* problem) {
CHECK(poses != NULL);
CHECK(problem != NULL);
CHECK_EQ(constraints.size(), scale_data_idx.size());
if (constraints.empty()) {
LOG(INFO) << "No constraints, no problem to optimize.";
return;
}
ceres::LossFunction* loss_function = NULL;
ceres::LocalParameterization* angle_local_parameterization =
AngleLocalParameterization::Create();
size_t i = 0;
for (std::vector<Constraint2d>::const_iterator constraints_iter =
constraints.begin();
constraints_iter != constraints.end();
++constraints_iter) {
const Constraint2d& constraint = *constraints_iter;
std::map<int, Pose2d>::iterator pose_begin_iter =
poses->find(constraint.id_begin);
CHECK(pose_begin_iter != poses->end())
<< "Pose with ID: " << constraint.id_begin << " not found.";
std::map<int, Pose2d>::iterator pose_end_iter =
poses->find(constraint.id_end);
CHECK(pose_end_iter != poses->end())
<< "Pose with ID: " << constraint.id_end << " not found.";
int scale_idx = scale_data_idx[i++];
const Eigen::Matrix3d sqrt_information =
constraint.information.llt().matrixL();
// Ceres will take ownership of the pointer.
ceres::CostFunction* cost_function = PoseGraph2dErrorTermWithScale::Create(
constraint.x, constraint.y, constraint.yaw_radians, sqrt_information);
problem->AddResidualBlock(cost_function,
loss_function,
&pose_begin_iter->second.x,
&pose_begin_iter->second.y,
&pose_begin_iter->second.yaw_radians,
&pose_end_iter->second.x,
&pose_end_iter->second.y,
&pose_end_iter->second.yaw_radians,
&(scale_data[scale_idx].scale));
problem->SetParameterization(&pose_begin_iter->second.yaw_radians,
angle_local_parameterization);
problem->SetParameterization(&pose_end_iter->second.yaw_radians,
angle_local_parameterization);
}
// fix some scales
for(size_t j = 0; j < scale_data.size(); j++){
if(scale_data[j].fixed){
problem->SetParameterBlockConstant(&(scale_data[j].scale));
}
}
// fix base frame
std::map<int, Pose2d>::iterator baseframe_pose_iter = poses->find(0);
CHECK(baseframe_pose_iter != poses->end());
problem->SetParameterBlockConstant(&baseframe_pose_iter->second.x);
problem->SetParameterBlockConstant(&baseframe_pose_iter->second.y);
problem->SetParameterBlockConstant(&baseframe_pose_iter->second.yaw_radians);
}
// Returns true if the solve was successful.
bool SolveOptimizationProblem(ceres::Problem* problem) {
CHECK(problem != NULL);
ceres::Solver::Options options;
options.max_num_iterations = 300;
options.linear_solver_type = ceres::SPARSE_NORMAL_CHOLESKY;
ceres::Solver::Summary summary;
ceres::Solve(options, problem, &summary);
std::cout << summary.FullReport() << '\n';
return summary.IsSolutionUsable();
}
// Output the poses to the file with format: ID x y yaw_radians.
bool OutputPoses(const std::string& filename,
const std::map<int, Pose2d>& poses) {
std::fstream outfile;
outfile.open(filename.c_str(), std::istream::out);
if (!outfile) {
std::cerr << "Error opening the file: " << filename << '\n';
return false;
}
for (std::map<int, Pose2d>::const_iterator poses_iter = poses.begin();
poses_iter != poses.end();
++poses_iter) {
const std::map<int, Pose2d>::value_type& pair = *poses_iter;
outfile << pair.first << " " << pair.second.x << " " << pair.second.y << ' '
<< pair.second.yaw_radians << '\n';
}
return true;
}
} // namespace optimization_2d
} // namespace ceres

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