Files
vslam_cpp/tools/vslam_vo_bench.cc

454 lines
20 KiB
C++

// vslam_vo_bench -- chay odometry thi giac RTAB-Map (mac dinh F2M) tren anh
// IR + depth cua mot ban ghi .vsr, xuat quy dao TUM de cham diem z tren doc.
//
// vslam_vo_bench --in X.vsr --out TRAJ.txt [--robot robot.yaml]
// [--guess wheel|none] [--param Key=Value]... [--stats S.json]
// [--reset-after N] [--ref-out REF.txt] [--imu-orient]
// [--imu-hz N] [--accel-bias x,y,z] [--gyro-bias x,y,z]
// [--enc-scale K] [--ir-noise SIGMA] [--seed N] [--no-vo]
// [--ga-alpha A] [--pitch-source ga|sensor] [--sensor-hz N]
// [--sensor-bias-deg B] [--sensor-noise-deg S] [--sensor-lag-ms L]
//
// Ra: TRAJ.txt = "giay x y z qx qy qz qw" cua base_footprint trong frame
// odom (goc = tu the robot o khung dau), chi khung odometry TINH DUOC.
// S.json = so khung, so khung mat bam, so lan reset, ms/khung.
// REF.txt = HANG THAM CHIEU, cung dinh dang, tai cung cac khung anh: z tich
// tu encoder va pitch cua GravityAlign (dung class vslam_node dung):
// z += -ds * sin(pitch), xy += ds * cos(pitch). VO phai thang hang nay moi
// dang chi phi.
//
// --imu-orient: dua roll/pitch cua GravityAlign vao moi khung (rtabmap::IMU,
// khong co yaw). RTAB-Map dung no de dat tu the dau theo trong luc va doan
// phep quay -- giu pitch khoi troi, la thu F2M mot minh khong co.
//
// ================== NUM "GIONG THAT" ==================
// Ban ghi sim SACH (IMU 200 Hz khong bias, banh khong truot, anh khong
// nhieu) -- thuan loi qua muc cho moi thu song nho IMU. Lam xau o day:
// --imu-hz N chi giu ~N mau IMU/giay (WT61PC hien 10 Hz)
// --accel-bias x,y,z cong bias co dinh (m/s^2) -- x lam lech pitch
// --gyro-bias x,y,z (rad/s)
// --enc-scale K encoder doc K lan quang duong that (truot banh /
// sai ban kinh) -- ca doan F2M lan tham chieu
// --ir-noise SIGMA nhieu Gauss tren anh IR truoc khi vao VO
// --no-vo chi tinh tham chieu (nhanh)
// --pitch-source sensor pitch cua hang tham chieu lay tu goc DA LOC cua
// chinh cam bien (khung Angle 0x53 cua WT61PC) thay vi
// tu loc gyro/accel tho. Gia lap: pitch THAT (stream
// ground truth) lay mau --sensor-hz, cong bias + nhieu,
// tre --sensor-lag-ms, giu gia tri giua hai mau. LAC
// QUAN: bo loc trong cam bien that co sai rieng (vd khi
// xe tang toc) -- phai do lai tren robot.
// --ga-alpha A alpha bo loc bu cua GravityAlign (mac dinh 0.98 cua
// pipeline.yaml, tinh MOI MAU: 10 Hz -> tau 5 s,
// 200 Hz -> tau 0.25 s)
//
// ================== BO THAM SO RIENG ==================
// KHONG ke thua slam.yaml: SLAM dang chay Reg/Strategy=1 (ICP) va
// Reg/Force3DoF=true -- ke thua la mat z ngay tu dau. O day:
// Odom/Strategy=0 (F2M), Reg/Strategy=0 (thi giac), Reg/Force3DoF=false,
// Vis/MaxDepth=4 (depth stereo xa hon thi sai so binh phuong khoang cach),
// Vis/MinInliers=15, OdomF2M/BundleAdjustment=1.
// Ngoai lai base_link <- camera_depth_optical_frame TINH tu robot.yaml (khong
// TiltLift: odometry tu tinh chuc ngoc cua than).
//
// Doan chuyen dong (--guess wheel, mac dinh): encoder banh -> buoc SE(2) cua
// than giua hai khung. Tren doc buoc nay van dung trong frame THAN (banh lan
// doc mat doc = truc x cua than).
//
// Mat bam: odometry tra pose rong. Sau N khung mat lien tiep (--reset-after,
// mac dinh 5) thi reset odometry TAI pose doan bang encoder -- giong cach
// vslam_node se lam khi VO hong. Moi lan reset la mot lan dem.
#include <algorithm>
#include <array>
#include <deque>
#include <chrono>
#include <random>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <memory>
#include <string>
#include <vector>
#include <opencv2/core.hpp>
#include <rtabmap/core/CameraModel.h>
#include <rtabmap/core/IMU.h>
#include <rtabmap/core/Odometry.h>
#include <rtabmap/core/OdometryInfo.h>
#include <rtabmap/core/Parameters.h>
#include <rtabmap/core/SensorData.h>
#include <rtabmap/utilite/ULogger.h>
#include "vslam/gravity_align.h"
#include "vslam/node_constants.h"
#include "vslam/record_format.h"
#include "vslam/record_io.h"
#include "vslam/robot_model.h"
#include "vslam/sensor_data_builder.h"
namespace {
struct PendingImage {
int64_t t = -1;
cv::Mat mat;
};
cv::Mat ToMat(const vslam::Image& img) {
const int type = img.format == vslam::PixelFormat::kMono16 ? CV_16UC1 : CV_8UC1;
// Ban sao sau: payload cua chunk bi ghi de o lan doc ke tiep.
return cv::Mat(static_cast<int>(img.height), static_cast<int>(img.width), type,
const_cast<uint8_t*>(img.data), img.step)
.clone();
}
bool ParseVec3(const std::string& s, double v[3]) {
return std::sscanf(s.c_str(), "%lf,%lf,%lf", &v[0], &v[1], &v[2]) == 3;
}
void WriteTum(FILE* f, double t, const rtabmap::Transform& T) {
float x, y, z, qx, qy, qz, qw;
T.getTranslation(x, y, z);
const Eigen::Quaternionf q = T.getQuaternionf();
qx = q.x(); qy = q.y(); qz = q.z(); qw = q.w();
std::fprintf(f, "%.9f %.6f %.6f %.6f %.9f %.9f %.9f %.9f\n", t, x, y, z, qx, qy, qz, qw);
}
} // namespace
int main(int argc, char** argv) {
std::string in, out, robot_yaml, stats_path, ref_path, guess_mode = "wheel";
int reset_after = 5;
bool imu_orient = false, no_vo = false;
double imu_hz = 0.0, enc_scale = 1.0, ir_noise = 0.0, ga_alpha = -1.0;
std::string pitch_source = "ga";
double sensor_hz = 10.0, sensor_bias_deg = 0.0, sensor_noise_deg = 0.0, sensor_lag_ms = 0.0;
double accel_bias[3] = {0, 0, 0}, gyro_bias[3] = {0, 0, 0};
uint32_t seed = 1;
rtabmap::ParametersMap params;
params[rtabmap::Parameters::kOdomStrategy()] = "0";
params[rtabmap::Parameters::kRegStrategy()] = "0";
params[rtabmap::Parameters::kRegForce3DoF()] = "false";
params[rtabmap::Parameters::kVisMaxDepth()] = "4.0";
params[rtabmap::Parameters::kVisMinInliers()] = "15";
params[rtabmap::Parameters::kOdomF2MBundleAdjustment()] = "1";
params[rtabmap::Parameters::kOdomResetCountdown()] = "0";
for (int i = 1; i < argc; ++i) {
const std::string a = argv[i];
auto next = [&]() -> std::string { return i + 1 < argc ? argv[++i] : ""; };
if (a == "--in") in = next();
else if (a == "--out") out = next();
else if (a == "--robot") robot_yaml = next();
else if (a == "--stats") stats_path = next();
else if (a == "--guess") guess_mode = next();
else if (a == "--reset-after") reset_after = std::atoi(next().c_str());
else if (a == "--ref-out") ref_path = next();
else if (a == "--imu-orient") imu_orient = true;
else if (a == "--no-vo") no_vo = true;
else if (a == "--imu-hz") imu_hz = std::atof(next().c_str());
else if (a == "--enc-scale") enc_scale = std::atof(next().c_str());
else if (a == "--ga-alpha") ga_alpha = std::atof(next().c_str());
else if (a == "--pitch-source") pitch_source = next();
else if (a == "--sensor-hz") sensor_hz = std::atof(next().c_str());
else if (a == "--sensor-bias-deg") sensor_bias_deg = std::atof(next().c_str());
else if (a == "--sensor-noise-deg") sensor_noise_deg = std::atof(next().c_str());
else if (a == "--sensor-lag-ms") sensor_lag_ms = std::atof(next().c_str());
else if (a == "--ir-noise") ir_noise = std::atof(next().c_str());
else if (a == "--seed") seed = static_cast<uint32_t>(std::atoi(next().c_str()));
else if (a == "--accel-bias" || a == "--gyro-bias") {
if (!ParseVec3(next(), a == "--accel-bias" ? accel_bias : gyro_bias)) {
std::fprintf(stderr, "%s can x,y,z\n", a.c_str());
return 2;
}
}
else if (a == "--param") {
const std::string kv = next();
const size_t eq = kv.find('=');
if (eq == std::string::npos) {
std::fprintf(stderr, "--param can Key=Value: %s\n", kv.c_str());
return 2;
}
params[kv.substr(0, eq)] = kv.substr(eq + 1);
} else {
std::fprintf(stderr, "tham so la: %s (xem dau file)\n", a.c_str());
return 2;
}
}
if (in.empty() || out.empty() || (guess_mode != "wheel" && guess_mode != "none")) {
std::fprintf(stderr, "can --in, --out; --guess wheel|none\n");
return 2;
}
if (robot_yaml.empty()) {
const char* cd = std::getenv("VSLAM_CONFIG_DIR");
robot_yaml = (cd != nullptr && *cd != '\0' ? std::string(cd) : std::string("configuration_files")) +
"/robot.yaml";
}
vslam::RobotModel robot;
const vslam::StatusResponse rs = robot.LoadFile(robot_yaml);
if (!rs.ok()) {
std::fprintf(stderr, "%s: %s\n", robot_yaml.c_str(), rs.message.c_str());
return 1;
}
vslam::Transform T_bl_cam, T_bl_imu;
if (!robot.StaticTransform(vslam::kBaseLinkFrame, vslam::kCameraDepthOpticalFrame, &T_bl_cam) ||
!robot.StaticTransform(vslam::kBaseLinkFrame, vslam::kImuFrame, &T_bl_imu)) {
std::fprintf(stderr, "robot.yaml thieu camera_depth_optical_frame / imu_link\n");
return 1;
}
const rtabmap::Transform imu_local = vslam::ToRtabmap(T_bl_imu);
const rtabmap::Transform local = vslam::ToRtabmap(T_bl_cam);
const double r_wheel = robot.geometry().wheel_radius;
const double sep = robot.geometry().wheel_separation;
// base_link -> base_footprint: chi tinh tien z.
const rtabmap::Transform T_bl_fp(0, 0, static_cast<float>(-r_wheel), 0, 0, 0);
ULogger::setType(ULogger::kTypeConsole);
ULogger::setLevel(ULogger::kError);
std::unique_ptr<rtabmap::Odometry> odom(rtabmap::Odometry::create(params));
vslam::RecordReader reader;
const vslam::StatusResponse st = reader.Open(in);
if (!st.ok()) {
std::fprintf(stderr, "%s: %s\n", in.c_str(), st.message.c_str());
return 1;
}
FILE* fo = std::fopen(out.c_str(), "w");
if (fo == nullptr) {
std::fprintf(stderr, "khong ghi duoc %s\n", out.c_str());
return 1;
}
std::fprintf(fo, "# vslam_vo_bench %s: base_footprint trong frame odom (TUM)\n", in.c_str());
FILE* fr = nullptr;
if (!ref_path.empty()) {
fr = std::fopen(ref_path.c_str(), "w");
if (fr == nullptr) {
std::fprintf(stderr, "khong ghi duoc %s\n", ref_path.c_str());
return 1;
}
std::fprintf(fr, "# tham chieu ds*sin(pitch GravityAlign) %s: base_footprint (TUM)\n",
in.c_str());
}
// Mac dinh cua GravityAlignConfig = pipeline.yaml (alpha 0.98, LPF 0.05,
// cong 1.0, tru gia toc odom).
vslam::GravityAlignConfig gcfg;
gcfg.wheel_radius = r_wheel;
if (ga_alpha >= 0.0) gcfg.alpha = ga_alpha;
vslam::GravityAlign ga(gcfg);
double rx = 0, ry = 0, rz = 0; // tham chieu: xy ngang + z tich luy
int64_t enc_t = -1, imu_kept_t = -1;
// --pitch-source sensor: goc cam bien gia lap tu ground truth (xem dau file).
const bool use_sensor = pitch_source == "sensor";
double s_roll = 0.0, s_pitch = 0.0;
int64_t s_next = -1;
std::deque<std::array<double, 3>> s_pending; // {t_den_ns, roll, pitch}
std::normal_distribution<double> n_ang(0.0, 1.0);
auto ref_pitch = [&]() { return use_sensor ? s_pitch : ga.pitch(); };
auto ref_roll = [&]() { return use_sensor ? s_roll : ga.roll(); };
std::mt19937 rng(seed);
std::normal_distribution<double> n01(0.0, 1.0);
vslam::CameraInfo info;
bool have_info = false;
PendingImage depth, ir;
// Odometry banh: pose SE(2) tich luy cua than, cap nhat moi encoder.
bool enc_init = false;
double enc_l = 0, enc_r = 0, wx = 0, wy = 0, wyaw = 0;
double fx_prev = 0, fy_prev = 0, fyaw_prev = 0; // pose banh luc khung truoc
int frames = 0, lost = 0, lost_run = 0, resets = 0, keyframes = 0;
long inliers_sum = 0;
std::vector<double> ms;
rtabmap::Transform last_pose = rtabmap::Transform::getIdentity();
rtabmap::Transform guess_since_last = rtabmap::Transform::getIdentity();
vslam::VsrChunkHeader h;
std::string payload;
std::vector<uint8_t> storage;
while (reader.Next(&h, &payload)) {
const int64_t t = static_cast<int64_t>(h.stamp_ns);
if (h.stream == vslam::VsrStream::kCameraInfo && !have_info) {
have_info = vslam::DecodeCameraInfoPayload(payload, &info);
continue;
}
if (h.stream == vslam::VsrStream::kEncoder) {
double l, r;
if (!vslam::DecodeEncoderPayload(payload, &l, &r)) continue;
if (enc_init) {
const double dl = (l - enc_l) * r_wheel * enc_scale;
const double dr = (r - enc_r) * r_wheel * enc_scale;
const double ds = 0.5 * (dl + dr), dth = (dr - dl) / sep;
wx += ds * std::cos(wyaw + 0.5 * dth);
wy += ds * std::sin(wyaw + 0.5 * dth);
// Tham chieu: pitch duong = mui chuc xuong, nen len doc pitch am.
const double p = ref_pitch();
rx += ds * std::cos(p) * std::cos(wyaw + 0.5 * dth);
ry += ds * std::cos(p) * std::sin(wyaw + 0.5 * dth);
rz += -ds * std::sin(p);
wyaw += dth;
const double dt = (t - enc_t) * 1e-9;
if (dt > 0.0) ga.FeedOdom(vslam::UnixTime::fromNSec(t), ds / dt, dth / dt);
}
enc_l = l;
enc_r = r;
enc_t = t;
enc_init = true;
continue;
}
if (use_sensor && h.stream == vslam::VsrStream::kGroundTruth) {
double g[6];
if (!vslam::DecodeGroundTruthPayload(payload, g)) continue;
const double d2r = M_PI / 180.0;
if (s_next < 0 || t >= s_next) {
s_pending.push_back({static_cast<double>(t) + sensor_lag_ms * 1e6,
g[3] + sensor_noise_deg * d2r * n_ang(rng),
g[4] + sensor_bias_deg * d2r + sensor_noise_deg * d2r * n_ang(rng)});
s_next = t + static_cast<int64_t>(1e9 / sensor_hz);
}
while (!s_pending.empty() && s_pending.front()[0] <= static_cast<double>(t)) {
s_roll = s_pending.front()[1];
s_pitch = s_pending.front()[2];
s_pending.pop_front();
}
continue;
}
if (h.stream == vslam::VsrStream::kImu) {
vslam::Imu m;
if (!vslam::DecodeImuPayload(payload, &m)) continue;
// Ha tan so: giu mau cach mau giu truoc >= 1/N (dung sai 1 ms).
if (imu_hz > 0.0 && imu_kept_t >= 0 &&
t - imu_kept_t < static_cast<int64_t>(1e9 / imu_hz) - 1000000) {
continue;
}
imu_kept_t = t;
m.linear_acceleration.x += accel_bias[0];
m.linear_acceleration.y += accel_bias[1];
m.linear_acceleration.z += accel_bias[2];
m.angular_velocity.x += gyro_bias[0];
m.angular_velocity.y += gyro_bias[1];
m.angular_velocity.z += gyro_bias[2];
ga.FeedImu(m);
continue;
}
if (h.stream != vslam::VsrStream::kDepth && h.stream != vslam::VsrStream::kInfra1) continue;
vslam::Image img;
if (!vslam::DecodeImagePayload(payload, &img, &storage)) continue;
PendingImage& slot = h.stream == vslam::VsrStream::kDepth ? depth : ir;
slot.t = t;
slot.mat = ToMat(img);
if (depth.t != ir.t || !have_info) continue; // cho du cap cung gio
// Buoc banh tu khung truoc, trong frame than.
const double c = std::cos(fyaw_prev), s = std::sin(fyaw_prev);
const double ddx = c * (wx - fx_prev) + s * (wy - fy_prev);
const double ddy = -s * (wx - fx_prev) + c * (wy - fy_prev);
const double ddyaw = wyaw - fyaw_prev;
fx_prev = wx; fy_prev = wy; fyaw_prev = wyaw;
const rtabmap::Transform wheel_step(static_cast<float>(ddx), static_cast<float>(ddy), 0.0f,
0.0f, 0.0f, static_cast<float>(ddyaw));
rtabmap::Transform guess = guess_mode == "wheel" ? wheel_step : rtabmap::Transform();
if (no_vo) {
frames++;
depth.t = ir.t = -1;
if (fr != nullptr) {
const rtabmap::Transform ref(static_cast<float>(rx), static_cast<float>(ry),
static_cast<float>(rz), static_cast<float>(ref_roll()),
static_cast<float>(ref_pitch()), static_cast<float>(wyaw));
WriteTum(fr, t * 1e-9, ref);
}
continue;
}
if (ir_noise > 0.0) {
for (int yy = 0; yy < ir.mat.rows; ++yy) {
uint8_t* row = ir.mat.ptr<uint8_t>(yy);
for (int xx = 0; xx < ir.mat.cols; ++xx) {
const double v = row[xx] + ir_noise * n01(rng);
row[xx] = static_cast<uint8_t>(std::min(255.0, std::max(0.0, std::round(v))));
}
}
}
rtabmap::CameraModel model(info.fx_binned(), info.fy_binned(), info.cx_binned(),
info.cy_binned(), local, 0.0,
cv::Size(ir.mat.cols, ir.mat.rows));
rtabmap::SensorData data(ir.mat, depth.mat, model, frames + 1, t * 1e-9);
if (imu_orient && ga.valid()) {
// Huong IMU trong the gioi, yaw 0: RTAB-Map chi lay roll/pitch.
const Eigen::Quaterniond q = rtabmap::Transform(0, 0, 0, static_cast<float>(ga.roll()),
static_cast<float>(ga.pitch()), 0)
.getQuaterniond();
data.setIMU(rtabmap::IMU(cv::Vec4d(q.x(), q.y(), q.z(), q.w()),
cv::Mat::eye(3, 3, CV_64FC1) * 1e-4, cv::Vec3d(), cv::Mat(),
cv::Vec3d(), cv::Mat(), imu_local));
}
rtabmap::OdometryInfo oi;
const auto t0 = std::chrono::steady_clock::now();
rtabmap::Transform pose = odom->process(data, guess, &oi);
ms.push_back(std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0)
.count());
frames++;
depth.t = ir.t = -1;
if (fr != nullptr) {
const rtabmap::Transform ref(static_cast<float>(rx), static_cast<float>(ry),
static_cast<float>(rz), static_cast<float>(ref_roll()),
static_cast<float>(ref_pitch()), static_cast<float>(wyaw));
WriteTum(fr, t * 1e-9, ref);
}
if (pose.isNull()) {
lost++;
lost_run++;
guess_since_last = guess_since_last * wheel_step;
if (reset_after > 0 && lost_run >= reset_after) {
// Tiep tuc tu pose doan bang banh -- VO mat bam thi vslam_node cung
// chi con banh + IMU.
last_pose = last_pose * guess_since_last;
guess_since_last = rtabmap::Transform::getIdentity();
odom->reset(last_pose);
resets++;
lost_run = 0;
}
continue;
}
lost_run = 0;
last_pose = pose;
guess_since_last = rtabmap::Transform::getIdentity();
inliers_sum += oi.reg.inliers;
if (oi.keyFrameAdded) keyframes++;
WriteTum(fo, t * 1e-9, pose * T_bl_fp);
}
std::fclose(fo);
if (fr != nullptr) std::fclose(fr);
if (frames == 0) {
std::fprintf(stderr, "khong co cap IR + depth nao (ghi bang vslam_record --gl)\n");
return 1;
}
if (no_vo) {
std::printf("%d khung, chi tham chieu (--no-vo)\n", frames);
return 0;
}
std::vector<double> sorted = ms;
std::sort(sorted.begin(), sorted.end());
double sum = 0;
for (double v : ms) sum += v;
const double mean = sum / ms.size();
const double p95 = sorted[static_cast<size_t>(0.95 * (sorted.size() - 1))];
const int ok = frames - lost;
std::printf("%d khung, mat bam %d (%.1f%%), reset %d, keyframe %d, inlier TB %.0f, "
"%.1f ms/khung (p95 %.1f)\n",
frames, lost, 100.0 * lost / frames, resets, keyframes,
ok > 0 ? static_cast<double>(inliers_sum) / ok : 0.0, mean, p95);
if (!stats_path.empty()) {
FILE* fs = std::fopen(stats_path.c_str(), "w");
if (fs != nullptr) {
std::fprintf(fs,
"{\"in\":\"%s\",\"frames\":%d,\"lost\":%d,\"resets\":%d,\"keyframes\":%d,"
"\"inliers_mean\":%.1f,\"ms_mean\":%.2f,\"ms_p95\":%.2f,\"guess\":\"%s\"}\n",
in.c_str(), frames, lost, resets, keyframes,
ok > 0 ? static_cast<double>(inliers_sum) / ok : 0.0, mean, p95,
guess_mode.c_str());
std::fclose(fs);
}
}
return 0;
}