// Chay lai mot session da ghi trong DB RTAB-Map qua wrapper cua ta, roi so // pose voi pose da toi uu ma chinh DB do luu. // // ================== VI SAO BAI NAY DUNG DUOC NGAY HOM NAY ================== // `map_house.db` DA LA mot dataset replay duoc, truoc khi phan cung chay lan // nao. Moi node trong DB co scan, odom pose, va pose da toi uu. Doc lai chung // theo dung thu tu la co mot phien chay day du. // // Day cung la cach kiem chung wrapper tu viet cho cung ket qua voi // rtabmap_ros: neu ATE so voi pose toi uu trong DB nho, wrapper dang goi // RTAB-Map dung cach. // // Ba che do: // --db X.db chay lai session trong DB (mapping) // --db X.db --localize chay lai o che do localization tren chinh DB do // --db X.db --kidnap N,M tha robot lech N met / M do, do thoi gian hoi tu #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "vslam/geometry.h" #include "vslam/occupancy_export.h" #include "vslam/occupancy_map_io.h" #include "vslam/rtabmap_slam.h" #include "vslam/sensor_data_builder.h" namespace { struct Frame { int id = 0; double stamp = 0.0; vslam::Pose2D odom; // pose odom goc (chua toi uu) vslam::Pose2D optimized; // pose sau toi uu -- dong vai "su that" bool has_optimized = false; vslam::LaserScan scan; bool has_scan = false; // Anh, chi nap khi --with-images. Giu cv::Mat SONG vi Image POD chi tro // vao du lieu chu khong so huu. cv::Mat rgb, depth; vslam::Image rgb_pod, depth_pod; vslam::CameraInfo info; bool has_image = false; }; // cv::Mat -> Image POD. KHONG copy: `m` phai song qua het loi goi Process(). vslam::Image WrapMat(const cv::Mat& m) { vslam::Image img; img.width = static_cast(m.cols); img.height = static_cast(m.rows); img.step = static_cast(m.step); img.data = m.data; if (m.type() == CV_16UC1) img.format = vslam::PixelFormat::kMono16; else if (m.type() == CV_32FC1) img.format = vslam::PixelFormat::kFloat32; else img.format = vslam::PixelFormat::kMono8; return img; } // rtabmap::LaserScan (kXY hoac kXYZ) -> LaserScan POD. // // DB luu DIEM chu khong luu tia, nen phai dung lai cau truc tia. Dung dung // angle_min/max/increment ma DB nho, roi do tia nao gan diem nao. Tia khong // co diem nao -> inf (khong co phan xa), DUNG ngu nghia ta da dinh nghia. bool ToPodScan(const rtabmap::LaserScan& in, vslam::LaserScan* out) { if (in.isEmpty()) return false; const int n = in.size(); float amin = in.angleMin(), amax = in.angleMax(), ainc = in.angleIncrement(); if (!(ainc > 0.0f)) { // DB cu khong luu thong tin goc -> suy ra tu so diem, gia dinh quet deu // 360 do. Tho, nhung chi anh huong toi cach dung lai tia, khong anh huong // toi toa do diem ma ICP thuc su dung. amin = -static_cast(M_PI); amax = static_cast(M_PI); ainc = (amax - amin) / static_cast(std::max(n, 1)); } const int nbeam = std::max(1, static_cast(std::lround((amax - amin) / ainc)) + 1); out->ranges.assign(static_cast(nbeam), std::numeric_limits::infinity()); out->intensities.clear(); out->angle_min = amin; out->angle_max = amax; out->angle_increment = ainc; out->range_min = in.rangeMin() > 0.0f ? in.rangeMin() : 0.05f; out->range_max = in.rangeMax() > 0.0f ? in.rangeMax() : 40.0f; out->scan_time = 0.04; out->time_increment = out->scan_time / nbeam; const cv::Mat& d = in.data(); for (int i = 0; i < n; ++i) { const float* p = d.ptr(0, i); const float x = p[0], y = p[1]; if (!std::isfinite(x) || !std::isfinite(y)) continue; const float r = std::sqrt(x * x + y * y); if (r < out->range_min || r > out->range_max) continue; const float a = std::atan2(y, x); int k = static_cast(std::lround((a - amin) / ainc)); if (k < 0 || k >= nbeam) continue; // Nhieu diem co the roi vao cung mot tia (scan 3D ep xuong): giu diem // GAN NHAT, giong cach mot LiDAR 2D that hanh xu. if (!std::isfinite(out->ranges[k]) || r < out->ranges[k]) out->ranges[k] = r; } return true; } double Rmse(const std::vector& a, const std::vector& b) { double sum = 0.0; const size_t n = std::min(a.size(), b.size()); if (n == 0) return -1.0; for (size_t i = 0; i < n; ++i) { const double dx = a[i].x - b[i].x, dy = a[i].y - b[i].y; sum += dx * dx + dy * dy; } return std::sqrt(sum / static_cast(n)); } // ATE co CAN CHINH: tim phep quay + tinh tien SE(2) toi uu dua `est` ve `ref` // (Umeyama 2D, khong co ti le) roi moi do sai so. // // Vi sao can: hai quy dao nam trong hai khung map KHAC NHAU. RTAB-Map dat goc // map o node dau tien cua PHIEN DO, nen mot phien chay lai bat dau tu node // khac -- hoac chi thay mot phan session -- se lech ca khung. Do truc tiep se // tra ve khoang cach giua hai GOC TOA DO chu khong phai sai so quy dao. // // Bao cao CA HAI: neu tho lon ma can chinh nho thi loi la lech khung; neu ca // hai cung lon thi la troi that. double AteAligned(const std::vector& est, const std::vector& ref) { const size_t n = std::min(est.size(), ref.size()); if (n < 2) return -1.0; double mex = 0, mey = 0, mrx = 0, mry = 0; for (size_t i = 0; i < n; ++i) { mex += est[i].x; mey += est[i].y; mrx += ref[i].x; mry += ref[i].y; } mex /= n; mey /= n; mrx /= n; mry /= n; double sxy = 0, sxx = 0; for (size_t i = 0; i < n; ++i) { const double ex = est[i].x - mex, ey = est[i].y - mey; const double rx = ref[i].x - mrx, ry = ref[i].y - mry; sxx += ex * rx + ey * ry; // phan doi xung -> cos sxy += ex * ry - ey * rx; // phan phan doi xung -> sin } const double th = std::atan2(sxy, sxx); const double c = std::cos(th), s = std::sin(th); double sum = 0.0; for (size_t i = 0; i < n; ++i) { const double ex = est[i].x - mex, ey = est[i].y - mey; const double ax = c * ex - s * ey + mrx; const double ay = s * ex + c * ey + mry; const double dx = ax - ref[i].x, dy = ay - ref[i].y; sum += dx * dx + dy * dy; } return std::sqrt(sum / static_cast(n)); } } // namespace int main(int argc, char** argv) { std::string db; bool localize = false; double kid_m = 0.0, kid_deg = 0.0; int limit = 0; std::string optimizer = "1"; std::string export_map; bool export_only = false; bool visual_loop = false; bool trace = false; bool with_images = false; std::string ref_db; std::map extra; 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 == "--db") db = next(); else if (a == "--localize") localize = true; else if (a == "--limit") limit = std::atoi(next().c_str()); else if (a == "--optimizer") optimizer = next(); else if (a == "--export-map") export_map = next(); else if (a == "--export-only") export_only = true; else if (a == "--visual-loop") visual_loop = true; else if (a == "--trace") trace = true; else if (a == "--with-images") with_images = true; else if (a == "--ref-db") ref_db = next(); else if (a == "--param") { // --param Key/Name=value. Di thang vao khoi overrides, tuc la CUNG // duong ma slam.yaml di -- ke ca phep kiem ten key. const std::string kv = next(); const size_t e = kv.find('='); if (e != std::string::npos) extra[kv.substr(0, e)] = kv.substr(e + 1); } else if (a == "--kidnap") { const std::string v = next(); const size_t c = v.find(','); kid_m = std::atof(v.substr(0, c).c_str()); if (c != std::string::npos) kid_deg = std::atof(v.substr(c + 1).c_str()); localize = true; } else if (a == "--help") { std::printf( "cach dung: %s --db X.db [--localize] [--kidnap M,DEG]\n" " [--limit N] [--optimizer 0|1|2|3] [--export-map out.pgm]\n", argv[0]); return 0; } } if (db.empty()) { std::fprintf(stderr, "can --db\n"); return 2; } // --- Che do doi chung: so pose toi uu cua HAI DB --- // // Dung de doi chung wrapper voi `rtabmap-reprocess`, cong cu chinh thuc cua // RTAB-Map. Neu reprocess chay cung tham so cung cho ATE ~ bang nhau so voi // DB goc, thi chenh lech do la HE QUA CUA CAU HINH chu khong phai loi cua // wrapper. Do la phep kiem quan trong nhat cua P6: no tach "wrapper goi sai // API" ra khoi "scan-only thi khong dung bang scan+anh". if (!ref_db.empty()) { std::unique_ptr d2(rtabmap::DBDriver::create()); if (d2 == nullptr || !d2->openConnection(ref_db, false)) { std::fprintf(stderr, "khong mo duoc %s\n", ref_db.c_str()); return 1; } const std::map opt2 = d2->loadOptimizedPoses(); d2->closeConnection(false); std::unique_ptr d1(rtabmap::DBDriver::create()); d1->openConnection(db, false); const std::map opt1 = d1->loadOptimizedPoses(); d1->closeConnection(false); std::vector a, b; for (const auto& kv : opt1) { auto it = opt2.find(kv.first); if (it == opt2.end()) continue; a.push_back(vslam::FromRtabmap(kv.second)); b.push_back(vslam::FromRtabmap(it->second)); } std::printf("so hai DB: %zu vs %zu pose, %zu id chung\n", opt1.size(), opt2.size(), a.size()); std::printf(" ATE RMSE (tho) : %.4f m\n", Rmse(a, b)); std::printf(" ATE RMSE (can chinh): %.4f m\n", AteAligned(a, b)); return 0; } // --- Doc session tu DB --- std::unique_ptr driver(rtabmap::DBDriver::create()); if (driver == nullptr || !driver->openConnection(db, false)) { std::fprintf(stderr, "khong mo duoc %s\n", db.c_str()); return 1; } const std::map opt = driver->loadOptimizedPoses(); { const vslam::DbFacts facts = vslam::InspectDatabase(db); std::printf("DB goc: %d node, %d tu vung, Optimizer/Strategy=\"%s\"\n", facts.nodes, facts.words, facts.optimizer_strategy.empty() ? "(khong luu)" : facts.optimizer_strategy.c_str()); } std::set ids; driver->getAllNodeIds(ids); vslam::Transform laser_to_base = vslam::TransformIdentity(); bool have_laser_tf = false; std::vector frames; frames.reserve(ids.size()); for (int id : ids) { if (limit > 0 && static_cast(frames.size()) >= limit) break; Frame f; f.id = id; rtabmap::Transform pose, gt; int map_id = 0, weight = 0; std::string label; std::vector vel; rtabmap::GPS gps; rtabmap::EnvSensors sensors; if (!driver->getNodeInfo(id, pose, map_id, weight, label, f.stamp, gt, vel, gps, sensors)) { continue; } f.odom = vslam::FromRtabmap(pose); // CHI node co trong tap pose toi uu moi dung lam tham chieu. DB co node // nam ngoai do thi da toi uu (bi loai, hoac thuoc phien khac); lay pose // odom cua chung lam "su that" la dang so uoc luong DA TOI UU cua ta voi // odom THO -- do chinh la thu SLAM sinh ra de sua. auto o = opt.find(id); if (o != opt.end()) { f.optimized = vslam::FromRtabmap(o->second); f.has_optimized = true; } rtabmap::SensorData data; driver->getNodeData(id, data, with_images, true, false, false); data.uncompressData(); f.has_scan = ToPodScan(data.laserScanRaw(), &f.scan); if (!f.has_scan) continue; // Frame cuc bo cua laser nam TRONG scan cua DB, khong phai trong node // info. Bo qua no la dat moi scan lech 24 cm so voi pose. if (!data.laserScanRaw().localTransform().isNull()) { laser_to_base = vslam::TransformFromRtabmap(data.laserScanRaw().localTransform()); have_laser_tf = true; } if (with_images && !data.imageRaw().empty() && !data.depthRaw().empty() && !data.cameraModels().empty()) { f.rgb = data.imageRaw().clone(); f.depth = data.depthRaw().clone(); f.rgb_pod = WrapMat(f.rgb); f.depth_pod = WrapMat(f.depth); const rtabmap::CameraModel& cm = data.cameraModels()[0]; f.info.width = static_cast(f.depth.cols); f.info.height = static_cast(f.depth.rows); f.info.k[0] = cm.fx(); f.info.k[2] = cm.cx(); f.info.k[4] = cm.fy(); f.info.k[5] = cm.cy(); f.info.k[8] = 1.0; f.has_image = true; } frames.push_back(std::move(f)); } driver->closeConnection(false); size_t with_img = 0; for (const Frame& f : frames) with_img += f.has_image ? 1 : 0; std::printf("DB %s: %zu node co scan (tong %zu), %zu pose toi uu, %zu co anh\n", db.c_str(), frames.size(), ids.size(), opt.size(), with_img); if (frames.empty()) return 1; // --- Chay qua wrapper --- // Ghi vao BAN SAO trong RAM: khong duoc sua corpus. vslam::RtabmapConfig cfg; cfg.mode = localize ? vslam::SlamMode::kLocalization : vslam::SlamMode::kMapping; // O che do localization phai mo DB THAT. KHONG BAO GIO mo thang corpus: // mot lan `Mem/IncrementalMemory` bi dat nham la ban do goc bi ghi de, va // corpus khong co ban sao. Chep ra cho tam roi mo ban chep. std::string work_db; if (localize) { work_db = db.substr(0, db.size() - 3) + "_bench_tmp.db"; // RTAB-Map doi duoi .db std::ifstream src(db, std::ios::binary); std::ofstream dst(work_db, std::ios::binary); if (!src || !dst) { std::fprintf(stderr, "khong chep duoc DB ra %s\n", work_db.c_str()); return 1; } dst << src.rdbuf(); dst.close(); std::printf("che do localization: dang dung ban chep %s\n", work_db.c_str()); } cfg.database_path = work_db; // rong = DB trong RAM (che do mapping) cfg.optimizer_strategy = optimizer; cfg.visual_loop = visual_loop; cfg.overrides = extra; for (const auto& kv : extra) { std::printf("param: %s = %s\n", kv.first.c_str(), kv.second.c_str()); } vslam::RtabmapSlam slam; slam.SetExtrinsics(laser_to_base, vslam::TransformIdentity()); std::printf("laser_to_base: %s(%.3f, %.3f, %.3f)\n", have_laser_tf ? "" : "MAC DINH ", laser_to_base.translation.x, laser_to_base.translation.y, laser_to_base.translation.z); const vslam::StatusResponse st = slam.Init(cfg); if (!st.ok()) { std::fprintf(stderr, "init: %s\n", st.message.c_str()); return 1; } // --- Pose ban dau --- // // RTAB-Map KHONG dinh vi toan cuc duoc bang scan khong. Vong dong toan cuc // di qua tui tu thi giac; con `RGBD/ProximityBySpace` chi tim trong mot ban // kinh quanh uoc luong HIEN TAI. Khong co pose ban dau thi o che do // localization no khong bao gio bat duoc vao ban do cu -- do duoc: ATE tho // 9.80 m, 0 lien ket. // // He that giai quyet dung nhu vay: `dock_init.py` phat /initialpose tu dock. // Robot LUON biet no bat dau o dau. Bai test phai mo phong dieu do, neu // khong no dang do mot che do khong ai chay. // // Kidnap = pose ban dau SAI di N met / M do. Do la y nghia dung cua bai // kidnapped-robot: robot TUONG no o mot cho khac. if (localize) { vslam::Pose2D init = frames.front().has_optimized ? frames.front().optimized : frames.front().odom; init.x += kid_m; init.theta = vslam::NormalizeAngle(init.theta + kid_deg * M_PI / 180.0); const vslam::StatusResponse ip = slam.SetInitialPose(init); std::printf("pose ban dau: (%.3f, %.3f, %.1f do)%s%s\n", init.x, init.y, init.theta * 180.0 / M_PI, (kid_m != 0.0 || kid_deg != 0.0) ? " <-- KIDNAP " : "", ip.ok() ? "" : " [LOI]"); } // ============ XUAT NHANH ============ // // `Init()` o che do localization da nap CA do thi va luoi tung node tu DB. // Xuat ban do khong can phat lai mot khung nao. // // Phat lai ~1990 node cua map_hospital.db chi de xuat ban do mat hang chuc // phut (p95 289 ms/khung) va khong them mot thong tin nao -- pose trong DB // da la pose TOI UU. if (export_only) { if (export_map.empty()) { std::fprintf(stderr, "--export-only can kem --export-map out.pgm\n"); return 2; } vslam::OccupancyGrid grid; const vslam::StatusResponse e = slam.ExportMap(&grid); if (!e.ok()) { std::fprintf(stderr, "xuat ban do: %s\n", e.message.c_str()); return 1; } std::string yaml = export_map; const size_t dot = yaml.rfind('.'); if (dot != std::string::npos) yaml = yaml.substr(0, dot); yaml += ".yaml"; const vslam::StatusResponse w = vslam::SaveOccupancyMap(grid, yaml); if (!w.ok()) { std::fprintf(stderr, "ghi ban do: %s\n", w.message.c_str()); return 1; } std::printf("ban do: %ux%u @ %.3f m/o -> %s\n", grid.width, grid.height, static_cast(grid.resolution), yaml.c_str()); slam.Close(false); if (!work_db.empty()) std::remove(work_db.c_str()); return 0; } const vslam::Pose2D kidnap_offset; // odom khong bi dong toi std::vector est, ref; est.reserve(frames.size()); ref.reserve(frames.size()); int processed = 0, loops = 0, prox = 0; double converge_s = -1.0; const double t_start = frames.front().stamp; for (const Frame& f : frames) { vslam::SlamInput in; in.stamp = vslam::UnixTime::fromSec(f.stamp); in.odom = vslam::Pose2DCompose(kidnap_offset, f.odom); in.scan = &f.scan; if (f.has_image) { in.depth = &f.depth_pod; in.depth_info = &f.info; in.infra1 = &f.rgb_pod; } const vslam::SlamOutput o = slam.Process(in); if (!o.processed) continue; processed++; if (o.loop_closure_id > 0) loops++; if (o.proximity_id > 0) prox++; if (f.has_optimized) { est.push_back(o.pose_map); ref.push_back(f.optimized); } if (trace && (processed % 20 == 0)) { std::printf(" [%4d] ms %7.1f wm %4d loop %d prox %d\n", processed, o.process_ms, o.nodes_wm, o.loop_closure_id, o.proximity_id); } if (localize && converge_s < 0.0 && o.localized && f.has_optimized && vslam::Distance2D(o.pose_map, f.optimized) < 0.30) { converge_s = f.stamp - t_start; } } const vslam::SlamStats& s = slam.stats(); std::printf("\n=== ket qua ===\n"); std::printf(" khung vao / xu ly : %llu / %d\n", static_cast(s.frames_in), processed); std::printf(" vong dong / lan can: %d / %d\n", loops, prox); std::printf(" process_ms : cuoi %.1f, max %.1f, p95 %.1f\n", s.last_ms, s.max_ms, s.p95_ms); std::printf(" cap so sanh : %zu (node co pose toi uu)\n", est.size()); const double ate_raw = Rmse(est, ref); const double ate = AteAligned(est, ref); std::printf(" ATE RMSE (tho) : %.4f m\n", ate_raw); std::printf(" ATE RMSE (can chinh): %.4f m <-- chi tieu < 0.10\n", ate); if (converge_s >= 0.0) std::printf(" hoi tu sau : %.2f s\n", converge_s); else if (localize) std::printf(" hoi tu sau : KHONG hoi tu\n"); if (!export_map.empty()) { vslam::OccupancyGrid grid; const vslam::StatusResponse e = slam.ExportMap(&grid); if (e.ok()) { // ⚠️ Truoc day cho nay TINH luoi roi VUT DI: `--export-map` nhan duong // dan, khong ghi gi, va van in dong "ban do xuat" nhu da thanh cong. // Mot co dong lenh hua ra file ma khong ra file la kieu hong te nhat -- // nguoi dung di tim file trong thu muc trong. // // `SaveOccupancyMap` ghi CA .pgm lan .yaml (yaml tro toi pgm), tuc la // dua thang vao duoc `vslam_node --sim --map`. std::string yaml = export_map; const size_t dot = yaml.rfind('.'); if (dot != std::string::npos) yaml = yaml.substr(0, dot); yaml += ".yaml"; const vslam::StatusResponse w = vslam::SaveOccupancyMap(grid, yaml); if (!w.ok()) { std::printf(" ban do xuat : LOI GHI %s\n", w.message.c_str()); return 1; } std::printf(" ban do xuat : %ux%u @ %.3f m/o -> %s\n", grid.width, grid.height, static_cast(grid.resolution), yaml.c_str()); } else { std::printf(" ban do xuat : LOI %s\n", e.message.c_str()); } } slam.Close(false); if (!work_db.empty()) std::remove(work_db.c_str()); return 0; }