reloc: VisualVerifier (ORB + PnP bang depth anh ban do) + vslam_pnp_eval -- trung khop ban Python 2430/2430 cap

This commit is contained in:
trung09122002
2026-09-30 15:09:53 +07:00
parent 2fc289db1c
commit c6c42d177f
5 changed files with 268 additions and 0 deletions

View File

@@ -40,6 +40,7 @@ vslam_add_library(vslam_slam
voxel_export.h
global_localizer.h
vpr_encoder.h
visual_verifier.h
FIND_DEPS
vslam_common
RTABMap

View File

@@ -0,0 +1,65 @@
#ifndef VSLAM_VISUAL_VERIFIER_H
#define VSLAM_VISUAL_VERIFIER_H
// Xac minh ung vien VPR bang ANH: so khop diem dac trung (ORB) giua anh hoi va anh ban do,
// nang diem ban do len 3D bang depth cua chinh anh do, roi PnP RANSAC -> pose robot.
//
// Ban C++ cua tools/reloc_pnp_eval.py -- CUNG tham so. Do 2026-09-30 (camera + LiDAR, chot
// khi pose PnP trung khop LiDAR cuc bo quanh node anh VPR): 25/09 85 -> 159 dung, 28/09
// 29 -> 40 dung, 0 chot SAI ca hai. Diem dac trung nho (goc cua, poster) nhin NGUOC lai thi
// khac han -> pha duoc doi xung hanh lang ma LiDAR va hinh khoi depth deu bi lua.
#include <vector>
#include <opencv2/core.hpp>
#include <opencv2/features2d.hpp>
namespace vslam {
struct VisualVerifierConfig {
int orb_features = 1500;
int fast_threshold = 7;
double clahe_clip = 3.0; // anh IR toi: CLAHE cho x2.7 diem ORB
int clahe_grid = 8;
double ratio = 0.8; // ratio test Lowe
double depth_min_m = 0.3;
double depth_max_m = 5.0;
int ransac_iters = 300;
double reproj_px = 4.0;
double confidence = 0.999;
int min_points = 8;
};
// Mot anh da trich dac trung, kem hinh hoc camera.
struct VisualFrame {
std::vector<cv::KeyPoint> kp;
cv::Mat des;
cv::Mat depth; // CV_16UC1 (mm) hoac CV_32FC1 (m); rong neu khong can
cv::Matx33d K;
cv::Matx44d T_base_optical; // base (z tinh tu san) <- optical
};
struct PnpResult {
int matches = 0; // cap qua ratio test
int inliers = 0; // inlier PnP RANSAC; 0 = khong ra nghiem
double x = 0.0, y = 0.0, yaw = 0.0; // base cua anh hoi trong map
double dz = 0.0, tilt_deg = 0.0; // robot tren san: phai ~0 (lech = nghiem suy bien)
};
class VisualVerifier {
public:
explicit VisualVerifier(const VisualVerifierConfig& cfg = VisualVerifierConfig());
// CLAHE + ORB. `depth`, `K`, `T_base_optical` nguoi goi dien sau.
VisualFrame Extract(const cv::Mat& gray) const;
// Pose base cua anh hoi `q` trong map, tu diem khop voi anh ban do `m` (can depth) co pose
// map <- base `T_map_base_m`.
PnpResult Solve(const VisualFrame& q, const VisualFrame& m, const cv::Matx44d& T_map_base_m) const;
private:
VisualVerifierConfig cfg_;
cv::Ptr<cv::ORB> orb_;
};
} // namespace vslam
#endif // VSLAM_VISUAL_VERIFIER_H

View File

@@ -0,0 +1,75 @@
#include "vslam/visual_verifier.h"
#include <algorithm>
#include <cmath>
#include <opencv2/calib3d.hpp>
#include <opencv2/imgproc.hpp>
namespace vslam {
VisualVerifier::VisualVerifier(const VisualVerifierConfig& cfg)
: cfg_(cfg),
orb_(cv::ORB::create(cfg.orb_features, 1.2f, 8, 31, 0, 2, cv::ORB::HARRIS_SCORE, 31,
cfg.fast_threshold)) {}
VisualFrame VisualVerifier::Extract(const cv::Mat& gray) const {
VisualFrame f;
cv::Mat g = gray, eq;
if (g.channels() == 3) cv::cvtColor(gray, g, cv::COLOR_BGR2GRAY);
cv::createCLAHE(cfg_.clahe_clip, cv::Size(cfg_.clahe_grid, cfg_.clahe_grid))->apply(g, eq);
orb_->detectAndCompute(eq, cv::noArray(), f.kp, f.des);
return f;
}
PnpResult VisualVerifier::Solve(const VisualFrame& q, const VisualFrame& m,
const cv::Matx44d& T_map_base_m) const {
PnpResult r;
if (q.des.empty() || m.des.empty() || q.kp.size() < 8 || m.kp.size() < 8 || m.depth.empty()) {
return r;
}
std::vector<std::vector<cv::DMatch>> knn;
cv::BFMatcher(cv::NORM_HAMMING).knnMatch(q.des, m.des, knn, 2);
const cv::Matx44d Twm = T_map_base_m * m.T_base_optical; // map <- optical cua anh ban do
const double fx = m.K(0, 0), fy = m.K(1, 1), cx = m.K(0, 2), cy = m.K(1, 2);
std::vector<cv::Point3d> obj;
std::vector<cv::Point2d> img;
for (const auto& p : knn) {
if (p.size() < 2 || p[0].distance >= cfg_.ratio * p[1].distance) continue;
++r.matches;
const cv::Point2f uv = m.kp[p[0].trainIdx].pt;
const int row = static_cast<int>(std::lround(uv.y)), col = static_cast<int>(std::lround(uv.x));
if (row < 0 || col < 0 || row >= m.depth.rows || col >= m.depth.cols) continue;
const double z = m.depth.type() == CV_16UC1 ? m.depth.at<uint16_t>(row, col) * 0.001
: static_cast<double>(m.depth.at<float>(row, col));
if (!(z > cfg_.depth_min_m && z < cfg_.depth_max_m)) continue;
const cv::Vec4d pc((uv.x - cx) * z / fx, (uv.y - cy) * z / fy, z, 1.0);
const cv::Vec4d pw = Twm * pc;
obj.emplace_back(pw[0], pw[1], pw[2]);
img.emplace_back(q.kp[p[0].queryIdx].pt);
}
if (static_cast<int>(obj.size()) < cfg_.min_points) return r;
cv::Mat rvec, tvec;
std::vector<int> inl;
const bool ok = cv::solvePnPRansac(obj, img, cv::Mat(q.K), cv::noArray(), rvec, tvec, false,
cfg_.ransac_iters, static_cast<float>(cfg_.reproj_px),
cfg_.confidence, inl, cv::SOLVEPNP_EPNP);
if (!ok || inl.empty()) return r;
cv::Mat R;
cv::Rodrigues(rvec, R);
cv::Matx44d Tcw = cv::Matx44d::eye(); // optical <- map
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) Tcw(i, j) = R.at<double>(i, j);
Tcw(i, 3) = tvec.at<double>(i);
}
const cv::Matx44d Twb = Tcw.inv() * q.T_base_optical.inv(); // map <- base cua anh hoi
r.inliers = static_cast<int>(inl.size());
r.x = Twb(0, 3);
r.y = Twb(1, 3);
r.yaw = std::atan2(Twb(1, 0), Twb(0, 0));
r.dz = Twb(2, 3);
r.tilt_deg = std::acos(std::max(-1.0, std::min(1.0, Twb(2, 2)))) * 180.0 / M_PI;
return r;
}
} // namespace vslam

View File

@@ -46,6 +46,10 @@ if(VSLAM_BUILD_SLAM)
add_executable(vslam_reloc_bench vslam_reloc_bench.cc)
target_link_libraries(vslam_reloc_bench PRIVATE vslam_slam vslam_common)
# vslam_pnp_eval: ban C++ cua reloc_pnp_eval.py -- doi chieu VisualVerifier voi ban da do.
add_executable(vslam_pnp_eval vslam_pnp_eval.cc)
target_link_libraries(vslam_pnp_eval PRIVATE vslam_slam vslam_common)
# vslam_vpr_check: doi chieu VPR TensorRT (C++) voi PyTorch -- chi khi co TensorRT.
if(VSLAM_WITH_TENSORRT)
add_executable(vslam_vpr_check vslam_vpr_check.cc)

123
tools/vslam_pnp_eval.cc Normal file
View File

@@ -0,0 +1,123 @@
// Ban C++ cua tools/reloc_pnp_eval.py, de doi chieu VisualVerifier voi ban Python da do.
//
// vslam_pnp_eval --db DB --in logs/reloc_pnp_R3.csv --out logs/reloc_pnp_R3_cpp.csv
//
// --in la CSV cua reloc_pnp_eval.py (da co truth_wall_overlap). Tinh lai PnP bang C++ cho moi
// dong (node hoi, ung vien VPR), GHI DE cac cot pnp_*, giu nguyen cot khac -> cham bang
// tools/reloc_fusion_analyze.py y nhu ban Python.
#include <rtabmap/core/DBDriver.h>
#include <rtabmap/core/SensorData.h>
#include <cstdio>
#include <fstream>
#include <map>
#include <memory>
#include <sstream>
#include <string>
#include <vector>
#include "vslam/visual_verifier.h"
namespace {
std::vector<std::string> Split(const std::string& s) {
std::vector<std::string> out;
std::stringstream ss(s);
std::string f;
while (std::getline(ss, f, ',')) out.push_back(f);
return out;
}
cv::Matx44d ToMatx(const rtabmap::Transform& t) {
return cv::Matx44d(t.r11(), t.r12(), t.r13(), t.x(), t.r21(), t.r22(), t.r23(), t.y(),
t.r31(), t.r32(), t.r33(), t.z(), 0, 0, 0, 1);
}
} // namespace
int main(int argc, char** argv) {
std::string db, in, out;
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 == "--in") in = next();
else if (a == "--out") out = next();
}
if (db.empty() || in.empty() || out.empty()) {
std::fprintf(stderr, "cach dung: %s --db DB --in PNP_CSV --out CSV\n", argv[0]);
return 2;
}
std::unique_ptr<rtabmap::DBDriver> driver(rtabmap::DBDriver::create());
if (!driver->openConnection(db, false)) {
std::fprintf(stderr, "khong mo duoc %s\n", db.c_str());
return 1;
}
const std::map<int, rtabmap::Transform> opt = driver->loadOptimizedPoses();
vslam::VisualVerifier vv;
std::map<int, vslam::VisualFrame> cache;
auto frame = [&](int id, bool need_depth) -> const vslam::VisualFrame& {
auto it = cache.find(id);
if (it != cache.end() && (!need_depth || !it->second.depth.empty())) return it->second;
rtabmap::SensorData d;
driver->getNodeData(id, d, true, false, false, false);
d.uncompressData();
vslam::VisualFrame f;
if (!d.imageRaw().empty() && !d.cameraModels().empty()) {
f = vv.Extract(d.imageRaw());
const rtabmap::CameraModel& cm = d.cameraModels()[0];
f.K = cv::Matx33d(cm.fx(), 0, cm.cx(), 0, cm.fy(), cm.cy(), 0, 0, 1);
f.T_base_optical = ToMatx(cm.localTransform());
if (need_depth) f.depth = d.depthRaw().clone();
}
return cache[id] = f;
};
std::ifstream fin(in);
std::ofstream fout(out);
std::string line;
if (!std::getline(fin, line)) return 1;
const std::vector<std::string> head = Split(line);
std::map<std::string, size_t> col;
for (size_t i = 0; i < head.size(); ++i) col[head[i]] = i;
for (const char* k : {"query_id", "rank", "vpr_node", "pnp_nmatch", "pnp_inl", "pnp_x", "pnp_y",
"pnp_th", "pnp_dz", "pnp_tilt"}) {
if (!col.count(k)) {
std::fprintf(stderr, "%s thieu cot %s -- can CSV cua reloc_pnp_eval.py\n", in.c_str(), k);
return 1;
}
}
fout << line << "\n";
int rows = 0, solved = 0, both = 0, py_only = 0, cpp_only = 0;
while (std::getline(fin, line)) {
std::vector<std::string> f = Split(line);
if (f.size() != head.size()) continue;
const int qid = std::stoi(f[col["query_id"]]), mid = std::stoi(f[col["vpr_node"]]);
const bool py_ok = std::stoi(f[col["pnp_inl"]]) >= 12;
vslam::PnpResult r;
if (std::stoi(f[col["rank"]]) > 0 && opt.count(mid)) {
r = vv.Solve(frame(qid, false), frame(mid, true), ToMatx(opt.at(mid)));
}
char b[64];
f[col["pnp_nmatch"]] = std::to_string(r.matches);
f[col["pnp_inl"]] = std::to_string(r.inliers);
std::snprintf(b, sizeof(b), "%.3f", r.x); f[col["pnp_x"]] = b;
std::snprintf(b, sizeof(b), "%.3f", r.y); f[col["pnp_y"]] = b;
std::snprintf(b, sizeof(b), "%.4f", r.yaw); f[col["pnp_th"]] = b;
std::snprintf(b, sizeof(b), "%.3f", r.dz); f[col["pnp_dz"]] = b;
std::snprintf(b, sizeof(b), "%.2f", r.tilt_deg); f[col["pnp_tilt"]] = b;
for (size_t i = 0; i < f.size(); ++i) fout << (i ? "," : "") << f[i];
fout << "\n";
++rows;
if (r.inliers > 0) ++solved;
const bool cpp_ok = r.inliers >= 12;
both += py_ok && cpp_ok;
py_only += py_ok && !cpp_ok;
cpp_only += !py_ok && cpp_ok;
}
driver->closeConnection(false);
std::printf("%d dong, C++ PnP ra nghiem %d; >= 12 inlier: ca hai %d, chi Python %d, chi C++ %d -> %s\n",
rows, solved, both, py_only, cpp_only, out.c_str());
return 0;
}