From b43b4293a8453899d1a08360b7942ef675900853 Mon Sep 17 00:00:00 2001 From: Michal Pelka Date: Mon, 7 Sep 2026 09:04:07 +0200 Subject: [PATCH 1/9] Step 2: BoW loop closure, ICP all edges - BoW loop closure detector (GUI + bow_loop_closure_detect): multiple camera folders, score as pre-filter only (min_bow_score 0.005, min_inliers 30), max_image_size_px downscaling; candidate preview with Show/Remove/ Previous/Next edge, "Add all shown" clears the list - New session_intensity_panoramas tool: lidar intensity panoramas usable as a BoW camera folder - "ICP all edges" coarse-to-fine from a start radius, with progress/Cancel; run_icp() returns success - Compute Pose Graph SLAM in the top menu bar; N/P step edges/candidates; 1-9 point size keys work with a focused window and resize all scans - Step 3: edge list scrolls in a child window - File dialogs start in the folder of a dropped/command-line file; OOM hint logged via spdlog Signed-off-by: Michal Pelka Co-Authored-By: Claude Opus 5.5 --- .gitmodules | 3 + 3rdparty/fbow | 1 + apps/console_tools/CMakeLists.txt | 72 +++ .../console_tools/bow_loop_closure_detect.cpp | 104 ++++ .../session_intensity_panoramas.cpp | 456 ++++++++++++++++ .../multi_session_registration.cpp | 15 + .../CMakeLists.txt | 17 +- .../bow_loop_closure_detector.cpp | 427 +++++++++++++++ .../bow_loop_closure_detector.h | 134 +++++ .../multi_view_tls_registration_gui.cpp | 501 +++++++++++++++++- .../multi_view_tls_registration_gui.cpp | 4 +- cmake/dependencies.cmake | 13 + core/CMakeLists.txt | 3 +- .../Core/manual_pose_graph_loop_closure.h | 32 ++ core/include/Core/pfd_wrapper.hpp | 1 + core/include/Core/pose_graph_loop_closure.h | 8 +- core/src/manual_pose_graph_loop_closure.cpp | 175 +++++- core/src/pfd_wrapper.cpp | 15 +- core/src/pose_graph_loop_closure.cpp | 17 +- deploy_mandeye.bat | 2 +- 20 files changed, 1952 insertions(+), 48 deletions(-) create mode 160000 3rdparty/fbow create mode 100644 apps/console_tools/bow_loop_closure_detect.cpp create mode 100644 apps/console_tools/session_intensity_panoramas.cpp create mode 100644 apps/multi_view_tls_registration/bow_loop_closure_detector.cpp create mode 100644 apps/multi_view_tls_registration/bow_loop_closure_detector.h diff --git a/.gitmodules b/.gitmodules index 4b7f2a47b..214888106 100644 --- a/.gitmodules +++ b/.gitmodules @@ -62,3 +62,6 @@ [submodule "3rdparty/libE57Format"] path = 3rdparty/libE57Format url = https://github.com/asmaloney/libE57Format.git +[submodule "3rdparty/fbow"] + path = 3rdparty/fbow + url = https://github.com/rmsalinas/fbow.git diff --git a/3rdparty/fbow b/3rdparty/fbow new file mode 160000 index 000000000..e148dbcbd --- /dev/null +++ b/3rdparty/fbow @@ -0,0 +1 @@ +Subproject commit e148dbcbd8ee1976b1b07988b5761a9171b9f01a diff --git a/apps/console_tools/CMakeLists.txt b/apps/console_tools/CMakeLists.txt index ea9f025ef..7a9c5fa9d 100644 --- a/apps/console_tools/CMakeLists.txt +++ b/apps/console_tools/CMakeLists.txt @@ -203,6 +203,48 @@ if (MSVC) target_compile_options(laz_to_mcap PRIVATE /bigobj) endif() +# bow_loop_closure_detect: headless verification tool for the automatic +# image-based (fbow) loop closure detector shared with step 2's GUI -- +# loads a step-2 session + a CAMERA_0 folder and prints candidate pairs as +# CSV, without needing the interactive GUI. Links core_no_gui (WITH_GUI=0) +# since it only needs PointClouds/Session, not the ImGui-dependent +# ManualPoseGraphLoopClosure/observation_picking pieces core (WITH_GUI=1) +# adds. +add_executable( + bow_loop_closure_detect bow_loop_closure_detect.cpp + ${REPOSITORY_DIRECTORY}/apps/multi_view_tls_registration/bow_loop_closure_detector.h + ${REPOSITORY_DIRECTORY}/apps/multi_view_tls_registration/bow_loop_closure_detector.cpp +) + +target_compile_definitions(bow_loop_closure_detect PRIVATE + WITH_GUI=0 + -DFBOW_VOCABULARY_PATH="${THIRDPARTY_DIRECTORY}/fbow/vocabularies/orb_mur.fbow") + +target_include_directories( + bow_loop_closure_detect PRIVATE + ${REPOSITORY_DIRECTORY}/core/include + ${REPOSITORY_DIRECTORY}/apps/multi_view_tls_registration + ${EIGEN3_INCLUDE_DIR} + ${LASZIP_INCLUDE_DIR}/LASzip/include + ${THIRDPARTY_DIRECTORY}/json/include + ${THIRDPARTY_DIRECTORY}/observation_equations/codes + ${THIRDPARTY_DIRECTORY}/vqf/vqf/cpp + ${THIRDPARTY_DIRECTORY}/Fusion/Fusion + ${EXTERNAL_LIBRARIES_DIRECTORY}/include + ${FBOW_INCLUDE_DIR} + ${OpenCV_INCLUDE_DIRS}) + +target_link_libraries( + bow_loop_closure_detect PRIVATE + core_no_gui + fbow + ${OpenCV_LIBS} + ${PLATFORM_LASZIP_LIB} + vqf + Fusion + ${PLATFORM_MISCELLANEOUS_LIBS} + spdlog::spdlog) + # session_to_mcap: a processed lidar_odometry_step_1 session (session.json) # -> MCAP exporter (undistorted lidar in the map frame + /tf map->lidar, # optionally /imu re-read from the original recording via --raw-dir). Unlike @@ -251,6 +293,35 @@ if (MSVC) target_compile_options(session_to_mcap PRIVATE /bigobj) endif() +# session_intensity_panoramas: a session's lidar intensity rendered as 360-degree +# panoramas seen from the lidar, one every N seconds, named like camera frames +# (intensity_.jpg) so the BoW loop closure can use them. Reads Core::Session, +# so it links core_no_gui (WITH_GUI=0) like session_to_mcap. +add_executable(session_intensity_panoramas session_intensity_panoramas.cpp) + +target_compile_definitions(session_intensity_panoramas PRIVATE WITH_GUI=0) + +target_include_directories( + session_intensity_panoramas PRIVATE + ${REPOSITORY_DIRECTORY}/core/include + ${EIGEN3_INCLUDE_DIR} + ${LASZIP_INCLUDE_DIR}/LASzip/include + ${THIRDPARTY_DIRECTORY}/json/include + ${THIRDPARTY_DIRECTORY}/observation_equations/codes + ${OpenCV_INCLUDE_DIRS}) + +target_link_libraries( + session_intensity_panoramas PRIVATE + core_no_gui + ${OpenCV_LIBS} + ${PLATFORM_LASZIP_LIB} + ${PLATFORM_MISCELLANEOUS_LIBS} + spdlog::spdlog) + +if (MSVC) + target_compile_definitions(session_intensity_panoramas PRIVATE _USE_MATH_DEFINES) +endif() + # These are built whenever BUILD_WITH_CLI_TOOLS is ON (the default), so they # ship in the DEB package alongside the GUI apps. hdmapping_install_app( @@ -264,4 +335,5 @@ hdmapping_install_app( laz_to_mcap mcap_to_laz ouster_pcap_to_laz + session_intensity_panoramas session_to_mcap) diff --git a/apps/console_tools/bow_loop_closure_detect.cpp b/apps/console_tools/bow_loop_closure_detect.cpp new file mode 100644 index 000000000..e9e1da1e9 --- /dev/null +++ b/apps/console_tools/bow_loop_closure_detect.cpp @@ -0,0 +1,104 @@ +// Headless verification tool for the automatic image-based (fbow) loop +// closure detector: loads a step-2 session + one or more camera folders, runs +// the pose-gate -> appearance -> geometric-verification pipeline, and prints +// candidate loop-closure pairs as CSV. See +// apps/multi_view_tls_registration/bow_loop_closure_detector.h for the +// pipeline itself (shared with the GUI) and BOW_PLACE_RECOGNITION_HANDOFF.md +// for why it's shaped this way. +#include +#include +#include +#include +#include + +#include + +#include + +#include "../multi_view_tls_registration/bow_loop_closure_detector.h" + +int main(int argc, char* argv[]) +{ + if (argc < 3) + { + std::cout << "USAGE: " << argv[0] << " session_file(.mjs/.json) camera_dir [camera_dir...] [output.csv]" << std::endl; + std::cout << " session_file : step 2 session file (e.g. .../lio_result_100/session.mjs)" << std::endl; + std::cout << " camera_dir : folder of _.jpg frames, e.g. mandeye CAMERA_0 or an" << std::endl; + std::cout << " Insta360's cam_front and cam_back; several folders are matched together" << std::endl; + std::cout << " output.csv : optional (last argument, ending in .csv); if omitted, prints CSV to stdout" << std::endl; + return 1; + } + + std::string session_file = argv[1]; + std::vector camera_dirs(argv + 2, argv + argc); + std::string output_csv; + if (camera_dirs.size() > 1 && std::filesystem::path(camera_dirs.back()).extension() == ".csv") + { + output_csv = camera_dirs.back(); + camera_dirs.pop_back(); + } + + Session session; + if (!session.load(session_file, false, 0.0, 0.0, 0.0, false)) + { + spdlog::error("Failed to load session '{}'", session_file); + return 2; + } + spdlog::info("Loaded session with {} chunks", session.point_clouds_container.point_clouds.size()); + + bow_loop_closure::DetectorParams params; + + auto frames = bow_loop_closure::loadCameraFrames(camera_dirs); + if (frames.empty()) + { + spdlog::error("No camera frames found"); + return 3; + } + + auto chunk_frames = bow_loop_closure::associateFramesToChunks(session.point_clouds_container, frames, params.max_frame_time_gap_ns); + + std::string vocab_path = bow_loop_closure::defaultVocabularyPath(); + std::unique_ptr vocabulary; + try + { + vocabulary = std::make_unique(bow_loop_closure::loadVocabulary(vocab_path)); + } + catch (const std::exception& e) + { + spdlog::error("{}", e.what()); + return 4; + } + + auto candidates = bow_loop_closure::detectCandidates(session.point_clouds_container, frames, chunk_frames, params, *vocabulary); + + std::ostream* out = &std::cout; + std::ofstream file_out; + if (!output_csv.empty()) + { + file_out.open(output_csv); + if (!file_out.good()) + { + spdlog::error("Could not open output file '{}'", output_csv); + return 5; + } + out = &file_out; + } + + *out << "index_i,index_j,xy_dist_m,arc_gap_m,bow_score,inliers,image_i,image_j" << std::endl; + for (const auto& c : candidates) + { + *out << c.index_i << "," << c.index_j << "," << c.xy_dist_m << "," << c.arc_gap_m << "," << c.bow_score << "," << c.inliers << "," + << frames[c.frame_i].file_path << "," << frames[c.frame_j].file_path << std::endl; + } + + spdlog::info( + "{} candidates ({} chunks pose-gated by arc_gap>={}, xy_dist<={}; {}/{} chunks had an associated camera frame)", + candidates.size(), + session.point_clouds_container.point_clouds.size(), + params.min_arc_gap_m, + params.max_xy_dist_m, + static_cast(std::count_if(chunk_frames.begin(), chunk_frames.end(), [](const auto& f) { return !f.empty(); })), + chunk_frames.size()); + + return 0; +} diff --git a/apps/console_tools/session_intensity_panoramas.cpp b/apps/console_tools/session_intensity_panoramas.cpp new file mode 100644 index 000000000..4bee660ce --- /dev/null +++ b/apps/console_tools/session_intensity_panoramas.cpp @@ -0,0 +1,456 @@ +// session_intensity_panoramas: renders a session's lidar intensity as 360-degree equirectangular panoramas +// seen from the lidar, one every --every seconds along the trajectory. +// +// Each panorama uses the points recorded within --window seconds of its time, moved into the lidar frame at +// that time (pose interpolated on the session trajectory); the nearest point wins each pixel and small gaps +// between points are filled. Files are named intensity_.jpg, so the output folder can be +// given to the BoW loop closure (step 2, bow_loop_closure_detect) as a camera folder. +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace fs = std::filesystem; + +namespace +{ + struct Options + { + std::string session_file; + fs::path out_dir; + double every_s = 1.0; + double window_s = 1.0; + double width_px = 1920; + double elevation_min_deg = -45.0; + double elevation_max_deg = 60.0; + double min_range_m = 0.5; + double max_range_m = 100.0; + double max_intensity = 0.0; //!< intensity shown white; 0 = the 99th percentile of the first chunk + double fill_px = 1.5; + bool level = false; + }; + + void print_usage(const char* app) + { + std::cout << "USAGE: " << app << " session_file(.mjs/.json) [output_dir] [options]\n" + << " Renders the session's lidar intensity as 360-degree panoramas seen from the lidar, one every --every\n" + << " seconds, written as /intensity_.jpg plus frames.csv. The folder\n" + << " works as a camera folder for the BoW loop closure (step 2, bow_loop_closure_detect).\n" + << " output_dir default: /intensity_panoramas\n" + << " --every seconds between panoramas (default 1)\n" + << " --window use the points recorded within +/- this many seconds (default 1)\n" + << " --width panorama width; the height follows from the elevation range (default 1920)\n" + << " --elevation_min lowest elevation shown (default -45)\n" + << " --elevation_max highest elevation shown (default 60)\n" + << " --min_range drop points closer to the lidar than this (default 0.5)\n" + << " --max_range drop points farther than this (default 100)\n" + << " --max_intensity intensity shown white (default: 99th percentile of the first chunk)\n" + << " --fill fill gaps between points, Gaussian sigma in pixels (default 1.5, 0 = off)\n" + << " --level keep the lidar heading but level the panorama (z up), removing roll and pitch\n"; + } + + bool parse_options(int argc, char* argv[], Options& o) + { + const std::map numbers{ + { "every", &o.every_s }, + { "window", &o.window_s }, + { "width", &o.width_px }, + { "elevation_min", &o.elevation_min_deg }, + { "elevation_max", &o.elevation_max_deg }, + { "min_range", &o.min_range_m }, + { "max_range", &o.max_range_m }, + { "max_intensity", &o.max_intensity }, + { "fill", &o.fill_px }, + }; + std::vector positional; + for (int i = 1; i < argc; ++i) + { + const std::string arg = argv[i]; + if (arg == "-h" || arg == "--help") + { + print_usage(argv[0]); + std::exit(0); + } + if (arg == "--level") + { + o.level = true; + continue; + } + if (arg.rfind("--", 0) != 0) + { + positional.push_back(arg); + continue; + } + const auto it = numbers.find(arg.substr(2)); + if (it == numbers.end()) + { + spdlog::error("Unknown option '{}'", arg); + return false; + } + if (i + 1 >= argc) + { + spdlog::error("{} needs a value", arg); + return false; + } + const std::string value = argv[++i]; + try + { + size_t used = 0; + *it->second = std::stod(value, &used); + if (used != value.size()) + throw std::invalid_argument(value); + } catch (const std::exception&) + { + spdlog::error("{}: not a number: '{}'", arg, value); + return false; + } + } + if (positional.empty() || positional.size() > 2) + { + print_usage(argv[0]); + return false; + } + o.session_file = positional[0]; + o.out_dir = positional.size() == 2 ? fs::path(positional[1]) : fs::path(o.session_file).parent_path() / "intensity_panoramas"; + if (!(o.every_s > 0.0 && o.window_s >= 0.0 && o.width_px >= 16.0 && o.elevation_min_deg >= -90.0 && + o.elevation_min_deg < o.elevation_max_deg && o.elevation_max_deg <= 90.0 && o.min_range_m >= 0.0 && + o.min_range_m < o.max_range_m && o.max_intensity >= 0.0 && o.fill_px >= 0.0)) + { + spdlog::error("Invalid option value, see --help"); + return false; + } + return true; + } + + struct TrajectoryPose + { + int64_t ts_ns; + Eigen::Vector3d t; + Eigen::Quaterniond q; + }; + + //! Maps a chunk's points, as stored in its LAZ file, to the world. PointClouds::load subtracts the session + //! offset from the points before m_pose applies; the offset goes into the pose here instead. + Eigen::Affine3d chunk_pose(const PointCloud& pc, const Eigen::Vector3d& offset) + { + return pc.m_pose * Eigen::Translation3d(-offset); + } + + //! World lidar poses of every chunk's trajectory node, sorted by time. + std::vector session_trajectory(const PointClouds& container) + { + std::vector out; + for (const auto& pc : container.point_clouds) + { + const Eigen::Affine3d T_wc = chunk_pose(pc, container.offset); + for (const auto& node : pc.local_trajectory) + { + const Eigen::Affine3d T_wl = T_wc * node.m_pose; + out.push_back({ std::llround(node.timestamps.first), T_wl.translation(), Eigen::Quaterniond(T_wl.linear()).normalized() }); + } + } + std::stable_sort( + out.begin(), + out.end(), + [](const TrajectoryPose& a, const TrajectoryPose& b) + { + return a.ts_ns < b.ts_ns; + }); + // Neighbouring chunks can share a node time; keep the first. + out.erase( + std::unique( + out.begin(), + out.end(), + [](const TrajectoryPose& a, const TrajectoryPose& b) + { + return a.ts_ns == b.ts_ns; + }), + out.end()); + return out; + } + + bool interpolate_pose(const std::vector& trajectory, int64_t ts_ns, Eigen::Affine3d& T_wl) + { + const auto it = std::lower_bound( + trajectory.begin(), + trajectory.end(), + ts_ns, + [](const TrajectoryPose& p, int64_t t) + { + return p.ts_ns < t; + }); + if (it == trajectory.end() || (it == trajectory.begin() && it->ts_ns != ts_ns)) + return false; + if (it->ts_ns == ts_ns) + { + T_wl = Eigen::Translation3d(it->t) * it->q; + return true; + } + const TrajectoryPose& a = *(it - 1); + const TrajectoryPose& b = *it; + const double s = double(ts_ns - a.ts_ns) / double(b.ts_ns - a.ts_ns); + T_wl = Eigen::Translation3d(a.t + s * (b.t - a.t)) * a.q.slerp(s, b.q); + return true; + } + + //! The lidar pose with roll and pitch removed: same position and heading, z along the world z. + Eigen::Affine3d leveled(const Eigen::Affine3d& T_wl) + { + const Eigen::Vector3d x = T_wl.linear().col(0); + const double heading = std::atan2(x.y(), x.x()); + return Eigen::Translation3d(T_wl.translation()) * Eigen::AngleAxisd(heading, Eigen::Vector3d::UnitZ()); + } + + //! A chunk's points as stored in its LAZ file (chunk frame), without the points that have no timestamp. + struct ChunkPoints + { + std::vector p; + std::vector intensity; + std::vector ts_ns; + }; + + ChunkPoints load_chunk(const PointCloud& pc) + { + ChunkPoints out; + PointCloud loaded; // a fresh cloud, so the session's chunk keeps its pose and trajectory + if (!loaded.load_pc(pc.file_name, true)) + { + spdlog::error("Cannot read '{}'", pc.file_name); + return out; + } + out.p.reserve(loaded.points_local.size()); + out.intensity.reserve(loaded.points_local.size()); + out.ts_ns.reserve(loaded.points_local.size()); + for (size_t i = 0; i < loaded.points_local.size(); ++i) + { + if (i >= loaded.timestamps.size() || loaded.timestamps[i] == 0.0) + continue; + out.p.push_back(loaded.points_local[i].cast()); + out.intensity.push_back(i < loaded.intensities.size() ? float(loaded.intensities[i]) : 0.f); + out.ts_ns.push_back(std::llround(loaded.timestamps[i])); + } + return out; + } + + double percentile(std::vector values, double q) + { + if (values.empty()) + return 0.0; + const size_t k = std::min(values.size() - 1, size_t(q * double(values.size()))); + std::nth_element(values.begin(), values.begin() + k, values.end()); + return values[k]; + } + + struct Panorama + { + cv::Mat intensity; //!< CV_32F, intensity of the nearest point per pixel + cv::Mat has_point; //!< CV_8U, 255 where a point landed + size_t points = 0; + }; + + Panorama render( + const std::vector>& chunks, // points and their chunk -> world pose + const Eigen::Affine3d& T_wl, + int64_t ts_ns, + const Options& o, + cv::Size size) + { + cv::Mat range(size, CV_32F, cv::Scalar(std::numeric_limits::infinity())); + Panorama out; + out.intensity = cv::Mat(size, CV_32F, cv::Scalar(0.f)); + const int64_t window_ns = std::llround(o.window_s * 1e9); + const float elevation_max = float(o.elevation_max_deg * M_PI / 180.0); + const float px_per_rad_u = float(size.width / (2.0 * M_PI)); + const float px_per_rad_v = float(size.height / ((o.elevation_max_deg - o.elevation_min_deg) * M_PI / 180.0)); + const Eigen::Affine3d T_lw = T_wl.inverse(); + for (const auto& [points, T_wc] : chunks) + { + const Eigen::Affine3f T_lc = (T_lw * T_wc).cast(); + for (size_t i = 0; i < points->p.size(); ++i) + { + if (std::llabs(points->ts_ns[i] - ts_ns) > window_ns) + continue; + const Eigen::Vector3f q = T_lc * points->p[i]; + const float r = q.norm(); + if (r < o.min_range_m || r > o.max_range_m) + continue; + // Azimuth 0 (lidar x) in the middle, +y to its left, as seen from the lidar. + const float u = (float(M_PI) - std::atan2(q.y(), q.x())) * px_per_rad_u; + const float v = (elevation_max - std::asin(q.z() / r)) * px_per_rad_v; + if (!(v >= 0.f && v < size.height)) + continue; + const int col = std::min(int(u), size.width - 1); + const int row = int(v); + ++out.points; + float& nearest = range.at(row, col); + if (r < nearest) + { + nearest = r; + out.intensity.at(row, col) = points->intensity[i]; + } + } + } + out.has_point = range < std::numeric_limits::infinity(); + return out; + } + + //! Gaussian blur that wraps around horizontally, where the panorama's left and right edges meet, and sees + //! zeros above and below it. OpenCV's filters reject BORDER_WRAP, so the wrapped columns are padded in. + cv::Mat blur_wrapped(const cv::Mat& src, double sigma) + { + const int pad = std::min(src.cols, int(std::ceil(4.0 * sigma)) + 1); // the kernel radius OpenCV picks for float + cv::Mat padded, blurred; + cv::copyMakeBorder(src, padded, 0, 0, pad, pad, cv::BORDER_WRAP); + cv::GaussianBlur(padded, blurred, cv::Size(), sigma, 0, cv::BORDER_CONSTANT); + return blurred(cv::Rect(pad, 0, src.cols, src.rows)).clone(); + } + + //! 8-bit image: the intensity scaled so that max_intensity is white, gaps up to about two sigma from the + //! nearest point filled with the Gaussian-weighted mean of the points around them, black elsewhere. + cv::Mat to_image(const Panorama& p, double max_intensity, double fill_px) + { + cv::Mat value = p.intensity.clone(); + if (fill_px > 0.0) + { + cv::Mat weight, mean; + p.has_point.convertTo(weight, CV_32F, 1.0 / 255.0); + const cv::Mat weighted_sum = blur_wrapped(p.intensity.mul(weight), fill_px); + weight = blur_wrapped(weight, fill_px); + cv::divide(weighted_sum, weight, mean); + const cv::Mat gap = (p.has_point == 0) & (weight > 0.1f); + mean.copyTo(value, gap); + } + cv::Mat image; + value.convertTo(image, CV_8U, 255.0 / max_intensity); + return image; + } +} // namespace + +int main(int argc, char* argv[]) +{ + Options o; + if (!parse_options(argc, argv, o)) + return 1; + + Session session; + session.load_cache_mode = true; // poses and trajectories only; chunks are read when a panorama needs them + if (!session.load(o.session_file, false, 0.0, 0.0, 0.0, false)) + { + spdlog::error("Failed to load session '{}'", o.session_file); + return 2; + } + const PointClouds& container = session.point_clouds_container; + const std::vector trajectory = session_trajectory(container); + if (trajectory.size() < 2) + { + spdlog::error("No trajectory in '{}' (trajectory_lio_*.csv next to the chunks)", o.session_file); + return 2; + } + + // Time span of each chunk's trajectory; its points can sit a little past the last node, one second covers that. + constexpr int64_t chunk_margin_ns = 1'000'000'000; + std::vector> chunk_spans; + for (const auto& pc : container.point_clouds) + { + if (pc.local_trajectory.empty()) + { + spdlog::warn("No trajectory for '{}', its points are not used", pc.file_name); + chunk_spans.emplace_back(std::numeric_limits::max(), std::numeric_limits::min()); + continue; + } + chunk_spans.emplace_back( + std::llround(pc.local_trajectory.front().timestamps.first) - chunk_margin_ns, + std::llround(pc.local_trajectory.back().timestamps.first) + chunk_margin_ns); + } + + const int width = int(std::lround(o.width_px)); + const int height = std::max(1, int(std::lround(width * (o.elevation_max_deg - o.elevation_min_deg) / 360.0))); + std::error_code ec; + fs::create_directories(o.out_dir, ec); + std::ofstream index(o.out_dir / "frames.csv"); + if (!index) + { + spdlog::error("Cannot write to '{}'", o.out_dir.string()); + return 3; + } + index << "image,timestamp_ns,points,coverage_percent,x,y,z,qx,qy,qz,qw\n"; + + const int64_t every_ns = std::llround(o.every_s * 1e9); + const int64_t window_ns = std::llround(o.window_s * 1e9); + const int64_t first_ns = trajectory.front().ts_ns; + const int64_t last_ns = trajectory.back().ts_ns; + const size_t frame_count = size_t((last_ns - first_ns) / every_ns) + 1; + spdlog::info( + "{} chunks, {:.1f} s of trajectory: {} panoramas of {}x{} px -> '{}'", + container.point_clouds.size(), + (last_ns - first_ns) * 1e-9, + frame_count, + width, + height, + o.out_dir.string()); + + // Panoramas are in time order, so a chunk is kept until a later panorama no longer needs it. + std::map loaded; + double max_intensity = o.max_intensity; + size_t written = 0; + for (size_t fi = 0; fi < frame_count; ++fi) + { + const int64_t ts = first_ns + int64_t(fi) * every_ns; + Eigen::Affine3d T_wl; + if (!interpolate_pose(trajectory, ts, T_wl)) + continue; + if (o.level) + T_wl = leveled(T_wl); + + std::vector> chunks; + for (size_t ci = 0; ci < container.point_clouds.size(); ++ci) + { + if (chunk_spans[ci].first > ts + window_ns || chunk_spans[ci].second < ts - window_ns) + { + loaded.erase(ci); + continue; + } + auto it = loaded.find(ci); + if (it == loaded.end()) + it = loaded.emplace(ci, load_chunk(container.point_clouds[ci])).first; + if (max_intensity <= 0.0 && !it->second.intensity.empty()) + { + max_intensity = std::max(1.0, percentile(it->second.intensity, 0.99)); + spdlog::info("Intensity {:.0f} (99th percentile of '{}') shown white", max_intensity, container.point_clouds[ci].file_name); + } + chunks.emplace_back(&it->second, chunk_pose(container.point_clouds[ci], container.offset)); + } + if (max_intensity <= 0.0) + continue; // no points so far + + const Panorama p = render(chunks, T_wl, ts, o, cv::Size(width, height)); + const std::string name = "intensity_" + std::to_string(ts) + ".jpg"; + if (!cv::imwrite((o.out_dir / name).string(), to_image(p, max_intensity, o.fill_px), { cv::IMWRITE_JPEG_QUALITY, 95 })) + { + spdlog::error("Cannot write '{}'", (o.out_dir / name).string()); + return 3; + } + ++written; + const double coverage = 100.0 * cv::countNonZero(p.has_point) / (double(width) * height); + const Eigen::Quaterniond q(T_wl.linear()); + const Eigen::Vector3d& t = T_wl.translation(); + index << name << ',' << ts << ',' << p.points << ',' << coverage << ',' << t.x() << ',' << t.y() << ',' << t.z() << ',' << q.x() + << ',' << q.y() << ',' << q.z() << ',' << q.w() << '\n'; + spdlog::info("[{}/{}] {} {} points, {:.1f}% pixels with a point", fi + 1, frame_count, name, p.points, coverage); + } + spdlog::info("{} panoramas written to '{}'", written, o.out_dir.string()); + return written > 0 ? 0 : 4; +} diff --git a/apps/multi_session_registration/multi_session_registration.cpp b/apps/multi_session_registration/multi_session_registration.cpp index 7f3a2a549..db0e97c25 100644 --- a/apps/multi_session_registration/multi_session_registration.cpp +++ b/apps/multi_session_registration/multi_session_registration.cpp @@ -1612,6 +1612,14 @@ bool addSessionFile(const std::string& path) return true; } +// Next file dialog opens in the folder of a file loaded without one (drag & drop, command line). +void setLocationHintFromFile(const fs::path& file) +{ + std::error_code ec; + const fs::path absolute = fs::absolute(file, ec); + mandeye::fd::SetLastLocationHint((ec ? file : absolute).parent_path().string()); +} + // Drag & drop: a project (*.mjp) replaces the current one; session files (*.mjs, *.json) and single point clouds // (*.laz, *.las) are added and loaded right away (appended to already loaded sessions, which keep their in-memory state). void loadDroppedFiles() @@ -1631,6 +1639,7 @@ void loadDroppedFiles() { if (ext_of(path) == ".mjp") { + setLocationHintFromFile(path); loadProject(path.string(), project_settings); return; } @@ -1658,6 +1667,7 @@ void loadDroppedFiles() pfd::icon::warning); return; } + setLocationHintFromFile(added.back()); if (loaded_sessions) { @@ -4113,7 +4123,12 @@ int main(int argc, char* argv[]) } if (!project_file.empty()) + { + setLocationHintFromFile(project_file); loadProject(project_file, project_settings); + } + if (!session_files.empty()) + setLocationHintFromFile(session_files.back()); bool added = false; for (const auto& session_file : session_files) diff --git a/apps/multi_view_tls_registration/CMakeLists.txt b/apps/multi_view_tls_registration/CMakeLists.txt index 03beee8e8..685867f22 100644 --- a/apps/multi_view_tls_registration/CMakeLists.txt +++ b/apps/multi_view_tls_registration/CMakeLists.txt @@ -24,6 +24,7 @@ set(SOURCES multi_view_tls_registration.cpp perform_experiment.cpp multi_view_tls_registration_gui.cpp multi_view_tls_registration.h ../lidar_odometry_step_1/lidar_odometry_utils.cpp + bow_loop_closure_detector.h bow_loop_closure_detector.cpp ) # Windows: add resource file @@ -35,7 +36,13 @@ add_executable( multi_view_tls_registration_step_2 ${SOURCES} ) -target_compile_definitions(multi_view_tls_registration_step_2 PRIVATE -DWITH_GUI=1) +# FBOW_VOCABULARY_PATH: absolute source-tree path to the bundled ORB +# vocabulary, baked in at configure time (dev-build convenience; a packaged +# install would instead copy the file next to the binary and resolve it +# relative to argv[0]). +target_compile_definitions(multi_view_tls_registration_step_2 PRIVATE + -DWITH_GUI=1 + -DFBOW_VOCABULARY_PATH="${THIRDPARTY_DIRECTORY}/fbow/vocabularies/orb_mur.fbow") target_include_directories( multi_view_tls_registration_step_2 @@ -56,7 +63,9 @@ target_include_directories( ${LASZIP_INCLUDE_DIR}/LASzip/include ${THIRDPARTY_DIRECTORY}/observation_equations/codes ${THIRDPARTY_DIRECTORY}/vqf/vqf/cpp - ${EXTERNAL_LIBRARIES_DIRECTORY}/include) + ${EXTERNAL_LIBRARIES_DIRECTORY}/include + ${FBOW_INCLUDE_DIR} + ${OpenCV_INCLUDE_DIRS}) target_link_libraries( multi_view_tls_registration_step_2 @@ -78,7 +87,9 @@ target_include_directories( spdlog::spdlog ${PLATFORM_LASZIP_LIB} ${PLATFORM_MISCELLANEOUS_LIBS} - PROJ::proj) + PROJ::proj + fbow + ${OpenCV_LIBS}) if(WIN32) add_custom_command( diff --git a/apps/multi_view_tls_registration/bow_loop_closure_detector.cpp b/apps/multi_view_tls_registration/bow_loop_closure_detector.cpp new file mode 100644 index 000000000..759b33a23 --- /dev/null +++ b/apps/multi_view_tls_registration/bow_loop_closure_detector.cpp @@ -0,0 +1,427 @@ +#include "bow_loop_closure_detector.h" + +#include +#include +#include +#include +#include + +#include +#include +#include + +#include + +#include +#include + +namespace fs = std::filesystem; + +namespace bow_loop_closure +{ + +namespace +{ + +// Parses "_.jpg" or ".jpg" -> +// timestamp_ns: the digits after the stem's last '_', same rule as +// TrajectoryViewer.cpp's parseImageTsNs(). The all-digits check rejects +// unrelated .jpgs, which would reach std::stoll. +bool parseFrameTimestamp(const fs::path& path, int64_t& out_ts_ns) +{ + if (path.extension() != ".jpg") + return false; + std::string stem = path.stem().string(); + if (const auto us = stem.rfind('_'); us != std::string::npos) + stem = stem.substr(us + 1); + if (stem.empty() || stem.find_first_not_of("0123456789") != std::string::npos) + return false; + try + { + out_ts_ns = std::stoll(stem); + return true; + } + catch (...) + { + return false; + } +} + +// Nearest entry of frames[begin, end), sorted by timestamp_ns; -1 if +// outside max_gap_ns or the range is empty. +int nearestFrameIndex(const std::vector& frames, int begin, int end, int64_t ts_ns, int64_t max_gap_ns) +{ + if (begin >= end) + return -1; + + auto it = std::lower_bound( + frames.begin() + begin, frames.begin() + end, ts_ns, [](const CameraFrame& f, int64_t ts) { return f.timestamp_ns < ts; }); + + int best = -1; + int64_t best_diff = std::numeric_limits::max(); + + if (it != frames.begin() + end) + { + int idx = static_cast(it - frames.begin()); + int64_t diff = std::llabs(frames[idx].timestamp_ns - ts_ns); + if (diff < best_diff) + { + best_diff = diff; + best = idx; + } + } + if (it != frames.begin() + begin) + { + int idx = static_cast(it - frames.begin()) - 1; + int64_t diff = std::llabs(frames[idx].timestamp_ns - ts_ns); + if (diff < best_diff) + { + best_diff = diff; + best = idx; + } + } + + if (best >= 0 && best_diff <= max_gap_ns) + return best; + return -1; +} + +// Reads an image, downscaled so its longer side is at most +// params.max_image_size_px; empty if it can't be read. +cv::Mat readImage(const std::string& image_path, int flags, const DetectorParams& params) +{ + cv::Mat image = cv::imread(image_path, flags); + const int longer_side = std::max(image.cols, image.rows); + if (!image.empty() && params.max_image_size_px > 0 && longer_side > params.max_image_size_px) + { + const double scale = static_cast(params.max_image_size_px) / longer_side; + cv::resize(image, image, cv::Size(), scale, scale, cv::INTER_AREA); + } + return image; +} + +// Detects ORB features + computes the fbow descriptor for one representative +// frame. Returns false (leaving outputs untouched) if the image can't be +// loaded or has no descriptors. +bool detectAndTransform( + const std::string& image_path, + const DetectorParams& params, + cv::ORB& orb, + fbow::Vocabulary& vocabulary, + std::vector& out_keypoints, + cv::Mat& out_descriptors, + fbow::fBow& out_bow) +{ + cv::Mat gray = readImage(image_path, cv::IMREAD_GRAYSCALE, params); + if (gray.empty()) + { + spdlog::warn("bow_loop_closure: could not read image '{}'", image_path); + return false; + } + out_keypoints.clear(); + orb.detectAndCompute(gray, cv::noArray(), out_keypoints, out_descriptors); + if (out_descriptors.empty()) + return false; + out_bow = vocabulary.transform(out_descriptors); + return true; +} + +// Ratio-test ORB match + RANSAC fundamental matrix between two already- +// detected frames. Returns the inlier match count and (via out params) the +// matches actually kept as inliers, for drawing. +int verifyGeometry( + const std::vector& kp_i, + const cv::Mat& desc_i, + const std::vector& kp_j, + const cv::Mat& desc_j, + const DetectorParams& params, + std::vector& out_inlier_matches) +{ + out_inlier_matches.clear(); + if (desc_i.empty() || desc_j.empty()) + return 0; + + cv::BFMatcher matcher(cv::NORM_HAMMING); + std::vector> knn_matches; + matcher.knnMatch(desc_i, desc_j, knn_matches, 2); + + std::vector good_matches; + for (const auto& m : knn_matches) + { + if (m.size() == 2 && m[0].distance < params.match_ratio_test * m[1].distance) + good_matches.push_back(m[0]); + } + + if (good_matches.size() < 8) + return 0; + + std::vector pts_i, pts_j; + pts_i.reserve(good_matches.size()); + pts_j.reserve(good_matches.size()); + for (const auto& m : good_matches) + { + pts_i.push_back(kp_i[m.queryIdx].pt); + pts_j.push_back(kp_j[m.trainIdx].pt); + } + + std::vector inlier_mask; + cv::findFundamentalMat( + pts_i, pts_j, cv::FM_RANSAC, params.ransac_reproj_threshold_px, params.ransac_confidence, inlier_mask); + + int inliers = 0; + for (size_t k = 0; k < good_matches.size(); k++) + { + if (k < inlier_mask.size() && inlier_mask[k]) + { + out_inlier_matches.push_back(good_matches[k]); + inliers++; + } + } + return inliers; +} + +} // namespace + +std::vector loadCameraFrames(const std::vector& camera_dirs) +{ + std::vector frames; + + for (size_t camera = 0; camera < camera_dirs.size(); camera++) + { + const std::string& dir = camera_dirs[camera]; + if (dir.empty() || !fs::is_directory(dir)) + { + spdlog::warn("bow_loop_closure: camera directory not found: '{}'", dir); + continue; + } + + size_t loaded = 0; + for (const auto& entry : fs::directory_iterator(dir)) + { + int64_t ts_ns = 0; + if (!entry.is_regular_file() || !parseFrameTimestamp(entry.path(), ts_ns)) + continue; + frames.push_back(CameraFrame{ ts_ns, entry.path().string(), static_cast(camera) }); + loaded++; + } + spdlog::info("bow_loop_closure: loaded {} camera frames from '{}'", loaded, dir); + } + + std::sort( + frames.begin(), + frames.end(), + [](const CameraFrame& a, const CameraFrame& b) + { + return a.camera != b.camera ? a.camera < b.camera : a.timestamp_ns < b.timestamp_ns; + }); + return frames; +} + +std::vector> associateFramesToChunks( + const PointClouds& point_clouds_container, const std::vector& frames, int64_t max_time_gap_ns) +{ + const auto& chunks = point_clouds_container.point_clouds; + std::vector> chunk_frames(chunks.size()); + + // [begin, end) of each camera's frames; loadCameraFrames sorts by camera first. + std::vector> camera_ranges; + for (int k = 0; k < static_cast(frames.size()); k++) + { + if (k == 0 || frames[k].camera != frames[k - 1].camera) + camera_ranges.emplace_back(k, k); + camera_ranges.back().second = k + 1; + } + + int matched = 0; + for (size_t i = 0; i < chunks.size(); i++) + { + if (chunks[i].timestamps.empty()) + continue; + int64_t chunk_ts_ns = static_cast(chunks[i].timestamps[0]); + for (const auto& [begin, end] : camera_ranges) + { + int idx = nearestFrameIndex(frames, begin, end, chunk_ts_ns, max_time_gap_ns); + if (idx >= 0) + chunk_frames[i].push_back(idx); + } + if (!chunk_frames[i].empty()) + matched++; + } + + spdlog::info( + "bow_loop_closure: associated {}/{} chunks with a frame of {} camera(s)", matched, chunks.size(), camera_ranges.size()); + return chunk_frames; +} + +std::string defaultVocabularyPath() +{ +#ifdef FBOW_VOCABULARY_PATH + return FBOW_VOCABULARY_PATH; +#else + return ""; +#endif +} + +fbow::Vocabulary loadVocabulary(const std::string& vocabulary_path) +{ + fbow::Vocabulary vocabulary; + if (vocabulary_path.empty() || !fs::exists(vocabulary_path)) + throw std::runtime_error("bow_loop_closure: vocabulary file not found: '" + vocabulary_path + "'"); + vocabulary.readFromFile(vocabulary_path); + if (!vocabulary.isValid()) + throw std::runtime_error("bow_loop_closure: failed to load vocabulary from '" + vocabulary_path + "'"); + return vocabulary; +} + +std::vector detectCandidates( + const PointClouds& point_clouds_container, + const std::vector& frames, + const std::vector>& chunk_frames, + const DetectorParams& params, + fbow::Vocabulary& vocabulary) +{ + std::vector candidates; + const auto& chunks = point_clouds_container.point_clouds; + const size_t n = chunks.size(); + if (n == 0 || chunk_frames.size() != n) + return candidates; + + // Cumulative trajectory arc-length from consecutive chunk poses. + std::vector arc_length(n, 0.0); + for (size_t i = 1; i < n; i++) + { + double d = (chunks[i].m_pose.translation() - chunks[i - 1].m_pose.translation()).norm(); + arc_length[i] = arc_length[i - 1] + d; + } + + // Precompute ORB keypoints/descriptors/BoW once per frame some chunk is + // associated with (reused below for both the appearance score and the + // geometric verification, within this one detectCandidates call). + const size_t m = frames.size(); + std::vector> keypoints_by_frame(m); + std::vector descriptors_by_frame(m); + std::vector bow_by_frame(m); + std::vector has_bow(m, false); + + cv::Ptr orb = cv::ORB::create(params.orb_features); + for (const auto& frame_list : chunk_frames) + { + for (const int f : frame_list) + { + if (f < 0 || f >= static_cast(m) || has_bow[f]) + continue; + has_bow[f] = detectAndTransform( + frames[f].file_path, params, *orb, vocabulary, keypoints_by_frame[f], descriptors_by_frame[f], bow_by_frame[f]); + } + } + auto has_any_bow = [&](size_t chunk) + { + return std::any_of(chunk_frames[chunk].begin(), chunk_frames[chunk].end(), [&](int f) { return has_bow[f]; }); + }; + + for (size_t i = 0; i < n; i++) + { + if (!has_any_bow(i)) + continue; + for (size_t j = i + 1; j < n; j++) + { + if (!has_any_bow(j)) + continue; + + // Stage 1: pose-gate. + double arc_gap = arc_length[j] - arc_length[i]; + if (arc_gap < params.min_arc_gap_m) + continue; + + Eigen::Vector3d ti = chunks[i].m_pose.translation(); + Eigen::Vector3d tj = chunks[j].m_pose.translation(); + double xy_dist = std::hypot(tj.x() - ti.x(), tj.y() - ti.y()); + if (xy_dist > params.max_xy_dist_m) + continue; + + // Stages 2 and 3 for every camera pair of the two chunks; the pair + // with the most inliers wins. + Candidate best; + for (const int fi : chunk_frames[i]) + { + for (const int fj : chunk_frames[j]) + { + if (!has_bow[fi] || !has_bow[fj]) + continue; + + // Stage 2: appearance pre-filter. + double score = fbow::fBow::score(bow_by_frame[fi], bow_by_frame[fj]); + if (score < params.min_bow_score) + continue; + + // Stage 3: geometric verification. + std::vector inlier_matches; + int inliers = verifyGeometry( + keypoints_by_frame[fi], descriptors_by_frame[fi], keypoints_by_frame[fj], descriptors_by_frame[fj], params, inlier_matches); + if (inliers < params.min_inliers || inliers <= best.inliers) + continue; + + best.frame_i = fi; + best.frame_j = fj; + best.bow_score = score; + best.inliers = inliers; + } + } + if (best.frame_i < 0) + continue; + + best.index_i = static_cast(i); + best.index_j = static_cast(j); + best.xy_dist_m = xy_dist; + best.arc_gap_m = arc_gap; + candidates.push_back(best); + } + } + + std::sort(candidates.begin(), candidates.end(), [](const Candidate& a, const Candidate& b) { return a.inliers > b.inliers; }); + + spdlog::info("bow_loop_closure: {} candidates passed pose-gate + appearance + geometric verification", candidates.size()); + return candidates; +} + +cv::Mat buildCandidateMontage(const Candidate& candidate, const std::vector& frames, const DetectorParams& params) +{ + const int frame_i = candidate.frame_i; + const int frame_j = candidate.frame_j; + if (frame_i < 0 || frame_j < 0 || frame_i >= static_cast(frames.size()) || frame_j >= static_cast(frames.size())) + return cv::Mat(); + + cv::Mat color_i = readImage(frames[frame_i].file_path, cv::IMREAD_COLOR, params); + cv::Mat color_j = readImage(frames[frame_j].file_path, cv::IMREAD_COLOR, params); + if (color_i.empty() || color_j.empty()) + return cv::Mat(); + + cv::Mat gray_i, gray_j; + cv::cvtColor(color_i, gray_i, cv::COLOR_BGR2GRAY); + cv::cvtColor(color_j, gray_j, cv::COLOR_BGR2GRAY); + + cv::Ptr orb = cv::ORB::create(params.orb_features); + std::vector kp_i, kp_j; + cv::Mat desc_i, desc_j; + orb->detectAndCompute(gray_i, cv::noArray(), kp_i, desc_i); + orb->detectAndCompute(gray_j, cv::noArray(), kp_j, desc_j); + + std::vector inlier_matches; + verifyGeometry(kp_i, desc_i, kp_j, desc_j, params, inlier_matches); + + cv::Mat montage; + cv::drawMatches( + color_i, + kp_i, + color_j, + kp_j, + inlier_matches, + montage, + cv::Scalar(0, 255, 0), + cv::Scalar(0, 0, 255), + std::vector(), + cv::DrawMatchesFlags::NOT_DRAW_SINGLE_POINTS); + return montage; +} + +} // namespace bow_loop_closure diff --git a/apps/multi_view_tls_registration/bow_loop_closure_detector.h b/apps/multi_view_tls_registration/bow_loop_closure_detector.h new file mode 100644 index 000000000..86df337a0 --- /dev/null +++ b/apps/multi_view_tls_registration/bow_loop_closure_detector.h @@ -0,0 +1,134 @@ +#pragma once + +// Automatic image-based loop-closure candidate detection for step 2, using +// the vendored fbow (Fast Bag-of-Words) library on ORB features from camera +// frames (mandeye CAMERA_0, or an Insta360's cam_front and cam_back). Framework-agnostic (no ImGui/raylib), so both +// bow_loop_closure_gui() (multi_view_tls_registration_gui.cpp) and the +// headless bow_loop_closure_detect console tool can drive it. +// +// Design follows BOW_PLACE_RECOGNITION_HANDOFF.md's lesson from a prior +// standalone prototype: appearance-only matching had ~0% precision on a +// repetitive scene, so candidates are gated by trajectory pose proximity +// (far apart in arc-length, close in XY) *before* appearance is trusted, and +// appearance + RANSAC geometric verification only *confirm* a pose-gated +// candidate -- they never discover one on their own. Detected candidates are +// meant for manual review (see the GUI's montage preview), not auto-added to +// the pose graph. + +#include +#include +#include + +#include +#include + +#include + +class PointClouds; + +namespace bow_loop_closure +{ + +// One camera frame: `_.jpg` or `.jpg` +// (mandeye's cam0_.jpg, Insta360 front_.jpg / back_.jpg), timestamp +// on the same clock as the LiDAR/IMU (same name rule as TrajectoryViewer.cpp's +// parseImageTsNs()). +struct CameraFrame +{ + int64_t timestamp_ns = 0; + std::string file_path; + int camera = 0; //!< index of its folder in loadCameraFrames' camera_dirs +}; + +struct DetectorParams +{ + // Stage 1 (pose-gate): keep chunk pairs far apart along the trajectory + // arc-length but close in XY -- mirrors the standalone prototype's + // --lc-min-arc-gap / --lc-max-xy-dist, computed here from poses already + // in memory instead of a CSV sidecar. + double min_arc_gap_m = 40.0; + double max_xy_dist_m = 15.0; + + // Stage 2 (appearance pre-filter): fbow::fBow::score threshold. A cheap + // pre-filter only: on a warehouse walk (mandeye CAMERA_0 and Insta360 + // front/back) the score barely separates revisits from far-apart pairs + // (median 0.006-0.011 vs 0.004-0.006), and 0.02 kept fewer than 1 in 10 + // revisits. The inlier count below is what tells them apart. + double min_bow_score = 0.005; + + // Stage 3 (geometric verification): ORB ratio-test match + RANSAC + // fundamental matrix. + int orb_features = 2000; + float match_ratio_test = 0.75f; + double ransac_reproj_threshold_px = 3.0; + double ransac_confidence = 0.99; + // Pairs more than 30 m apart (certainly not the same view) reach up to + // ~28 inliers by chance on the same walk. + int min_inliers = 30; + + // Images whose longer side exceeds this are downscaled to it before ORB + // (0 = full resolution). Halving the Insta360 X5's 3840 px lens images + // finds more revisits with fewer chance inliers, and twice as fast. + int max_image_size_px = 1920; + + // Chunk<->camera-frame association tolerance (nearest-timestamp match). + int64_t max_frame_time_gap_ns = 500000000; // 0.5 s +}; + +struct Candidate +{ + int index_i = -1; + int index_j = -1; + int frame_i = -1; //!< frames[] entry of chunk index_i that matched (the best camera pair) + int frame_j = -1; //!< frames[] entry of chunk index_j that matched + double xy_dist_m = 0.0; + double arc_gap_m = 0.0; + double bow_score = 0.0; + int inliers = 0; +}; + +// Scans every folder in `camera_dirs` (one per camera, e.g. an Insta360's +// cam_front and cam_back) for `_.jpg` files. Returns +// them sorted by camera, then timestamp ascending. +std::vector loadCameraFrames(const std::vector& camera_dirs); + +// For each chunk in `point_clouds_container`, finds every camera's +// nearest-timestamp frame in `frames` (sorted as loadCameraFrames returns +// them). Returns one list of frame indices per chunk (same size as +// point_clouds_container.point_clouds), at most one per camera; a camera with +// no frame within `max_time_gap_ns` is left out, and a chunk with no +// per-point timestamp loaded gets an empty list. +std::vector> associateFramesToChunks( + const PointClouds& point_clouds_container, const std::vector& frames, int64_t max_time_gap_ns); + +// Absolute path to the fbow ORB vocabulary bundled with this build +// (3rdparty/fbow/vocabularies/orb_mur.fbow), baked in at configure time via +// the FBOW_VOCABULARY_PATH compile definition. This is a source-tree path, +// fine for local/dev builds; a packaged install would instead want to copy +// the file next to the binary and resolve it relative to argv[0]. +std::string defaultVocabularyPath(); + +// Throws std::runtime_error if the vocabulary file can't be read. +fbow::Vocabulary loadVocabulary(const std::string& vocabulary_path); + +// Runs the full pose-gate -> appearance-filter -> geometric-verification +// pipeline. `chunk_frames` is associateFramesToChunks()'s output. With several +// cameras, every camera pair of a chunk pair is tried (front vs back too, which +// finds a place revisited facing the other way) and the pair with the most +// inliers is kept. Returns surviving candidates sorted by inlier count +// descending. +std::vector detectCandidates( + const PointClouds& point_clouds_container, + const std::vector& frames, + const std::vector>& chunk_frames, + const DetectorParams& params, + fbow::Vocabulary& vocabulary); + +// Re-runs ORB detect + ratio-test match + RANSAC for one candidate's frame +// pair (independent of detectCandidates' internal per-run cache) and draws the +// inlier correspondences on a side-by-side image pair, for visual review +// before adding an edge. Returns an empty cv::Mat if either frame can't be +// loaded/matched. +cv::Mat buildCandidateMontage(const Candidate& candidate, const std::vector& frames, const DetectorParams& params); + +} // namespace bow_loop_closure diff --git a/apps/multi_view_tls_registration/multi_view_tls_registration_gui.cpp b/apps/multi_view_tls_registration/multi_view_tls_registration_gui.cpp index 83fabfaf1..f34e411ac 100644 --- a/apps/multi_view_tls_registration/multi_view_tls_registration_gui.cpp +++ b/apps/multi_view_tls_registration/multi_view_tls_registration_gui.cpp @@ -1,4 +1,5 @@ #include +#include #include // This app used to be built on GLUT + legacy immediate-mode OpenGL @@ -87,7 +88,15 @@ #include #include +#include +#include + +#include +#include +#include + #include "../lidar_odometry_step_1/lidar_odometry_utils.h" +#include "bow_loop_closure_detector.h" #include "multi_view_tls_registration.h" #include @@ -618,6 +627,16 @@ void view_kbd_shortcuts() ImGuiIO& io = ImGui::GetIO(); + // 1-9: point size. Like N / P these also work while a window has focus, but not while a text field is being edited. + if (!io.WantTextInput && !io.KeyCtrl && !io.KeyAlt && !io.KeyShift) + { + for (int size = 1; size <= 9; size++) + { + if (ImGui::IsKeyPressed(static_cast(ImGuiKey_0 + size))) + app_state.point_size = size; + } + } + if (io.WantCaptureKeyboard) return; @@ -700,25 +719,6 @@ void view_kbd_shortcuts() app_state.camera.isOrtho = !app_state.camera.isOrtho; if (ImGui::IsKeyPressed(ImGuiKey_X, false)) app_state.show_axes = !app_state.show_axes; - - if (ImGui::IsKeyPressed(ImGuiKey_1)) - app_state.point_size = 1; - if (ImGui::IsKeyPressed(ImGuiKey_2)) - app_state.point_size = 2; - if (ImGui::IsKeyPressed(ImGuiKey_3)) - app_state.point_size = 3; - if (ImGui::IsKeyPressed(ImGuiKey_4)) - app_state.point_size = 4; - if (ImGui::IsKeyPressed(ImGuiKey_5)) - app_state.point_size = 5; - if (ImGui::IsKeyPressed(ImGuiKey_6)) - app_state.point_size = 6; - if (ImGui::IsKeyPressed(ImGuiKey_7)) - app_state.point_size = 7; - if (ImGui::IsKeyPressed(ImGuiKey_8)) - app_state.point_size = 8; - if (ImGui::IsKeyPressed(ImGuiKey_9)) - app_state.point_size = 9; } // Drawing itself lives in raylib_widgets::drawCompassRuler (shared with the @@ -914,11 +914,11 @@ static const std::vector appShortcuts = { { "Normal keys", "A", " { "", "Ctrl+L", "manual Loop closure" }, { "", "M", "" }, { "", "Ctrl+M", "Measure distance" }, - { "", "N", "" }, + { "", "N", "Next edge (manual loop closure, BoW preview)" }, { "", "Ctrl+N", "" }, { "", "O", "Ortographic view" }, { "", "Ctrl+O", "Open/load session/data" }, - { "", "P", "" }, + { "", "P", "Previous edge (manual loop closure, BoW preview)" }, { "", "Ctrl+P", "Pose graph slam" }, { "", "Q", "" }, { "", "Ctrl+Q", "" }, @@ -1006,6 +1006,7 @@ bool is_rpf_gui = false; bool is_pose_graph_slam = false; bool is_manual_analisys = false; bool is_loop_closure_gui = false; +bool is_bow_loop_closure_gui = false; bool is_lio_segments_gui = false; bool is_settings_gui = true; bool is_translate_gui = false; @@ -1954,6 +1955,416 @@ void observation_picking_gui() ImGui::End(); } +// ── Automatic image-based (fbow) loop closure detection ───────────────────── +// Candidates are only ever surfaced for manual review here (montage preview + +// per-row "Add edge") -- never auto-added to the pose graph -- per +// BOW_PLACE_RECOGNITION_HANDOFF.md's documented false-positive risk on +// repetitive scenes. Detection itself runs on a background thread (ORB +// extraction over hundreds of frames must not block the render loop); it only +// reads session.point_clouds_container (poses/timestamps), never mutates it, +// mirroring TrajectoryViewer.cpp's imgViewThread pattern for its own +// background image work. +namespace +{ +struct BowLoopClosureState +{ + //! One row per camera folder (CAMERA_0, or an Insta360's cam_front and cam_back); empty rows are skipped. + std::vector> camera_dirs = std::vector>(1); + bow_loop_closure::DetectorParams params; + + std::atomic detecting{ false }; + std::thread detect_thread; + + std::mutex results_mutex; + std::vector results; + std::vector frames; + std::vector camera_names; //!< folder name per CameraFrame::camera + std::string status; + + int selected_candidate = -1; + bool scroll_to_selected = false; //!< scroll the list to selected_candidate on the next frame + bool window_focused = false; //!< the BoW window had focus last frame, see bow_preview_takes_edge_hotkeys() + Texture2D montage_tex{}; + bool montage_tex_valid = false; +}; +BowLoopClosureState bow_state; + +void bow_loop_closure_start_detection() +{ + if (bow_state.detecting.load()) + return; + if (bow_state.detect_thread.joinable()) + bow_state.detect_thread.join(); + + bow_state.detecting = true; + { + std::lock_guard lk(bow_state.results_mutex); + bow_state.status = "Detecting..."; + bow_state.results.clear(); + bow_state.selected_candidate = -1; + } + + std::vector camera_dirs; + std::vector camera_names; + for (const auto& dir : bow_state.camera_dirs) + { + if (dir[0] == '\0') + continue; + camera_dirs.emplace_back(dir.data()); + std::filesystem::path path(camera_dirs.back()); + if (!path.has_filename()) + path = path.parent_path(); // ".../cam_front/" + camera_names.push_back(path.filename().string()); + } + bow_loop_closure::DetectorParams params = bow_state.params; + + bow_state.detect_thread = std::thread( + [camera_dirs, camera_names, params]() + { + auto frames = bow_loop_closure::loadCameraFrames(camera_dirs); + std::vector candidates; + std::string status; + + if (frames.empty()) + { + status = "No camera frames found in the camera folders"; + } + else + { + auto chunk_frames = + bow_loop_closure::associateFramesToChunks(session.point_clouds_container, frames, params.max_frame_time_gap_ns); + try + { + auto vocabulary = bow_loop_closure::loadVocabulary(bow_loop_closure::defaultVocabularyPath()); + candidates = + bow_loop_closure::detectCandidates(session.point_clouds_container, frames, chunk_frames, params, vocabulary); + status = std::to_string(candidates.size()) + " candidates found"; + } + catch (const std::exception& e) + { + status = e.what(); + } + } + + std::lock_guard lk(bow_state.results_mutex); + bow_state.frames = std::move(frames); + bow_state.camera_names = camera_names; + bow_state.results = std::move(candidates); + bow_state.status = status; + bow_state.detecting = false; + }); +} + +// Uploads `mat` (BGR, as cv::imread/drawMatches produce) as the montage +// preview texture -- same LoadTextureFromImage/UnloadTexture pattern as +// TrajectoryViewer.cpp's imgViewTex. +void bow_loop_closure_upload_montage(cv::Mat mat) +{ + if (mat.empty()) + return; + cv::cvtColor(mat, mat, cv::COLOR_BGR2RGB); + if (!mat.isContinuous()) + mat = mat.clone(); + + if (bow_state.montage_tex_valid) + UnloadTexture(bow_state.montage_tex); + Image ri = { mat.data, mat.cols, mat.rows, 1, PIXELFORMAT_UNCOMPRESSED_R8G8B8 }; + bow_state.montage_tex = LoadTextureFromImage(ri); + bow_state.montage_tex_valid = bow_state.montage_tex.id > 0; +} + +// Shows results[row] in the montage preview. +void bow_loop_closure_show_candidate(const std::vector& results, int row) +{ + bow_state.selected_candidate = row; + std::lock_guard lk(bow_state.results_mutex); + cv::Mat montage = bow_loop_closure::buildCandidateMontage(results[row], bow_state.frames, bow_state.params); + bow_loop_closure_upload_montage(montage); +} + +void bow_loop_closure_clear_preview() +{ + bow_state.selected_candidate = -1; + if (bow_state.montage_tex_valid) + UnloadTexture(bow_state.montage_tex); + bow_state.montage_tex_valid = false; +} + +// N / P step the BoW candidates instead of the manual loop closure's active edge while a candidate is +// shown and either the BoW window has focus or the active edge list is not shown. +bool bow_preview_takes_edge_hotkeys() +{ + if (!is_bow_loop_closure_gui || bow_state.selected_candidate < 0) + return false; + const auto& loop_closure = session.pose_graph_loop_closure; + const bool active_edges_shown = is_loop_closure_gui && loop_closure.manipulate_active_edge && !loop_closure.edges.empty(); + return bow_state.window_focused || !active_edges_shown; +} +} // namespace + +void bow_loop_closure_gui() +{ + const bool edge_hotkeys = bow_preview_takes_edge_hotkeys(); + ImGui::Begin("Automatic Image Loop Closure (BoW)", &is_bow_loop_closure_gui); + bow_state.window_focused = ImGui::IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows); + + ImGui::Text("Camera folders (CAMERA_0, or an Insta360's cam_front and cam_back):"); + int remove_camera_dir = -1; + for (size_t k = 0; k < bow_state.camera_dirs.size(); k++) + { + auto& dir = bow_state.camera_dirs[k]; + ImGui::PushID(static_cast(k)); + ImGui::PushItemWidth(400); + ImGui::InputText("##bow_camera_dir", dir.data(), dir.size()); + ImGui::PopItemWidth(); + ImGui::SameLine(); + if (ImGui::Button("Select...")) + { + std::string selected = mandeye::fd::SelectFolder("Select camera directory"); + if (!selected.empty()) + std::snprintf(dir.data(), dir.size(), "%s", selected.c_str()); + } + if (bow_state.camera_dirs.size() > 1) + { + ImGui::SameLine(); + if (ImGui::Button("Remove")) + remove_camera_dir = static_cast(k); + } + ImGui::PopID(); + } + if (remove_camera_dir >= 0) + bow_state.camera_dirs.erase(bow_state.camera_dirs.begin() + remove_camera_dir); + if (ImGui::Button("Add camera folder")) + bow_state.camera_dirs.emplace_back(); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("Frames of all cameras are matched against each other, front vs back too"); + + ImGui::PushItemWidth(ImGuiNumberWidth); + ImGui::InputDouble("Min arc gap [m]", &bow_state.params.min_arc_gap_m); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("Reject chunk pairs closer than this along the trajectory (excludes trivially-adjacent chunks)"); + ImGui::InputDouble("Max XY dist [m]", &bow_state.params.max_xy_dist_m); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("Reject chunk pairs farther apart in XY than this (plausible same-place threshold)"); + ImGui::InputDouble("Min BoW score", &bow_state.params.min_bow_score, 0.0, 0.0, "%.4f"); + ImGui::InputInt("Min inliers", &bow_state.params.min_inliers); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("Minimum RANSAC-verified ORB match inliers to accept a candidate"); + ImGui::InputInt("ORB features", &bow_state.params.orb_features); + ImGui::InputInt("Max image size [px]", &bow_state.params.max_image_size_px); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("Downscale images whose longer side is larger than this before ORB (0 = full resolution)"); + ImGui::PopItemWidth(); + + bool detecting = bow_state.detecting.load(); + ImGui::BeginDisabled(detecting || session.point_clouds_container.point_clouds.empty()); + if (ImGui::Button("Detect candidates")) + bow_loop_closure_start_detection(); + ImGui::EndDisabled(); + ImGui::SameLine(); + + std::vector results_copy; + std::vector results_cameras; // "front/back" per row, only with several cameras + std::string status_copy; + { + std::lock_guard lk(bow_state.results_mutex); + results_copy = bow_state.results; + status_copy = bow_state.status; + if (bow_state.camera_names.size() > 1) + { + for (const auto& c : results_copy) + { + results_cameras.push_back( + " cameras=" + bow_state.camera_names[bow_state.frames[c.frame_i].camera] + "/" + + bow_state.camera_names[bow_state.frames[c.frame_j].camera]); + } + } + } + ImGui::Text("%s", status_copy.c_str()); + + ImGui::Separator(); + ImGui::Text( + "Review candidates below before adding an edge -- appearance matching alone is known to produce\n" + "confident false positives on repetitive scenes (see BOW_PLACE_RECOGNITION_HANDOFF.md). Press\n" + "\"Show edge\" to preview a candidate's matched keypoints, \"Previous\"/\"Next edge\" there (or P / N)\n" + "to step through the candidates and \"Remove edge\" to drop a false positive."); + + ImGui::BeginChild("BowResults", ImVec2(0, 260), true); + for (size_t row = 0; row < results_copy.size(); row++) + { + const auto& c = results_copy[row]; + ImGui::PushID(static_cast(row)); + + const bool shown = (bow_state.selected_candidate == static_cast(row)); + if (shown && bow_state.scroll_to_selected) + { + ImGui::SetScrollHereY(0.5f); + bow_state.scroll_to_selected = false; + } + if (shown) + ImGui::PushStyleColor(ImGuiCol_Button, orangeBorder); + if (ImGui::Button("Show edge")) + bow_loop_closure_show_candidate(results_copy, static_cast(row)); + if (shown) + ImGui::PopStyleColor(); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("Preview this candidate's matched keypoints below"); + ImGui::SameLine(); + ImGui::Text( + "i=%d j=%d xy=%.2fm arc=%.2fm score=%.3f inliers=%d%s", + c.index_i, + c.index_j, + c.xy_dist_m, + c.arc_gap_m, + c.bow_score, + c.inliers, + results_cameras.empty() ? "" : results_cameras[row].c_str()); + ImGui::SameLine(); + if (ImGui::Button("Add edge")) + { + session.pose_graph_loop_closure.add_edge(session.point_clouds_container, c.index_i, c.index_j); + } + ImGui::SameLine(); + if (ImGui::Button("Preview in 3D")) + { + index_loop_closure_source = c.index_i; + index_loop_closure_target = c.index_j; + is_loop_closure_gui = true; + } + + ImGui::PopID(); + } + ImGui::EndChild(); + + if (!results_copy.empty()) + { + if (ImGui::Button("Add all shown")) + { + for (const auto& c : results_copy) + session.pose_graph_loop_closure.add_edge(session.point_clouds_container, c.index_i, c.index_j); + { + std::lock_guard lk(bow_state.results_mutex); + bow_state.results.clear(); + bow_state.status = "Added " + std::to_string(results_copy.size()) + " edges to the pose graph"; + } + bow_loop_closure_clear_preview(); + } + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("Add every candidate as a pose graph edge and clear the list"); + ImGui::SameLine(); + if (ImGui::Button("Save all shown as montages...")) + { + std::string out_dir = mandeye::fd::SelectFolder("Select folder to save montages"); + if (!out_dir.empty()) + { + std::lock_guard lk(bow_state.results_mutex); + for (const auto& c : results_copy) + { + cv::Mat m = bow_loop_closure::buildCandidateMontage(c, bow_state.frames, bow_state.params); + if (!m.empty()) + { + std::string fn = out_dir + "/cand_" + std::to_string(c.index_i) + "_" + std::to_string(c.index_j) + ".png"; + cv::imwrite(fn, m); + } + } + bow_state.status = "Saved " + std::to_string(results_copy.size()) + " montages to '" + out_dir + "'"; + } + } + } + + if (bow_state.montage_tex_valid) + { + ImGui::Separator(); + ImGui::Text("Montage preview:"); + const int selected = bow_state.selected_candidate; + if (selected >= 0 && selected < static_cast(results_copy.size())) + { + const ImGuiIO& io = ImGui::GetIO(); + const bool keys = edge_hotkeys && !io.WantTextInput && !io.KeyCtrl && !io.KeyAlt && !io.KeyShift; + const bool key_previous = keys && ImGui::IsKeyPressed(ImGuiKey_P); + const bool key_next = keys && ImGui::IsKeyPressed(ImGuiKey_N); + + ImGui::SameLine(); + ImGui::BeginDisabled(selected == 0); + if ((ImGui::Button("< Previous edge") || key_previous) && selected > 0) + { + bow_loop_closure_show_candidate(results_copy, selected - 1); + bow_state.scroll_to_selected = true; + } + ImGui::EndDisabled(); + ImGui::SameLine(); + ImGui::BeginDisabled(selected + 1 >= static_cast(results_copy.size())); + if ((ImGui::Button("Next edge >") || key_next) && selected + 1 < static_cast(results_copy.size())) + { + bow_loop_closure_show_candidate(results_copy, selected + 1); + bow_state.scroll_to_selected = true; + } + ImGui::EndDisabled(); + ImGui::SameLine(); + ImGui::Text("%d of %zu", selected + 1, results_copy.size()); + ImGui::SameLine(); + if (ImGui::Button("Save montage...")) + { + const auto& c = results_copy[selected]; + std::string default_name = "cand_" + std::to_string(c.index_i) + "_" + std::to_string(c.index_j) + ".png"; + std::string out_file = + mandeye::fd::SaveFileDialog("Save montage", { "PNG image (*.png)", "*.png" }, ".png", default_name); + if (!out_file.empty()) + { + std::lock_guard lk(bow_state.results_mutex); + cv::Mat m = bow_loop_closure::buildCandidateMontage(c, bow_state.frames, bow_state.params); + if (!m.empty()) + cv::imwrite(out_file, m); + } + } + ImGui::SameLine(); + if (ImGui::Button("Remove edge")) + { + const auto& shown = results_copy[selected]; + std::vector remaining; + int next_row = selected; + { + std::lock_guard lk(bow_state.results_mutex); + auto& results = bow_state.results; + const auto it = std::find_if( + results.begin(), + results.end(), + [&shown](const bow_loop_closure::Candidate& c) + { + return c.index_i == shown.index_i && c.index_j == shown.index_j; + }); + if (it != results.end()) + next_row = static_cast(results.erase(it) - results.begin()); + remaining = results; + } + // Show the candidate that took its place, or the new last one. + if (remaining.empty()) + { + bow_loop_closure_clear_preview(); + } + else + { + bow_loop_closure_show_candidate(remaining, std::min(next_row, static_cast(remaining.size()) - 1)); + bow_state.scroll_to_selected = true; + } + } + if (ImGui::IsItemHovered()) + ImGui::SetTooltip( + "Remove this candidate from the list and show the next one; an edge already added to the pose graph stays there"); + } + if (bow_state.montage_tex_valid) + { + ImVec2 avail = ImGui::GetContentRegionAvail(); + float aspect = static_cast(bow_state.montage_tex.height) / static_cast(bow_state.montage_tex.width); + int dispW = static_cast(avail.x); + int dispH = static_cast(avail.x * aspect); + rlImGuiImageSize(&bow_state.montage_tex, dispW, dispH); + } + } + + ImGui::End(); +} + void loop_closure_gui() { ImGui::Begin("Manual Pose Graph Loop Closure", &is_loop_closure_gui); @@ -1996,6 +2407,7 @@ void loop_closure_gui() ImGui::PopItemWidth(); int prev_index_active_edge = session.pose_graph_loop_closure.index_active_edge; + session.pose_graph_loop_closure.edge_hotkeys = !bow_preview_takes_edge_hotkeys(); session.pose_graph_loop_closure.Gui( session.point_clouds_container, index_loop_closure_source, @@ -2646,6 +3058,14 @@ std::string lowerExtension(const std::filesystem::path& path) return ext; } +// Next file dialog opens in the folder of a file loaded without one (drag & drop, command line). +void setLocationHintFromFile(const fs::path& file) +{ + std::error_code ec; + const fs::path absolute = fs::absolute(file, ec); + mandeye::fd::SetLastLocationHint((ec ? file : absolute).parent_path().string()); +} + // Accepts a Mandeye JSON Session file (*.mjs/*.json) -- shared by the drag & drop handler in main()'s loop and // the CLI argv handling below, so both accept the same input and report unsupported drops the same way. void loadSessionFromPath(const std::string& path) @@ -2664,6 +3084,7 @@ void loadSessionFromPath(const std::string& path) return; } + setLocationHintFromFile(path); session_file_name = path; loadSession(path); } @@ -3074,6 +3495,7 @@ void loadDroppedFiles(const std::vector& paths) else spdlog::warn("Ignoring non-e57 file dropped alongside e57 file(s): '{}'", p); } + setLocationHintFromFile(e57_paths.back()); loadE57Files(e57_paths, fillInSession); return; } @@ -5337,7 +5759,14 @@ void display() } } + const int point_size_before_shortcuts = app_state.point_size; view_kbd_shortcuts(); + // As View > Point cloud > Points size does: the active edge's moved scans are drawn with their own size. + if (app_state.point_size != point_size_before_shortcuts) + { + for (auto& point_cloud : session.point_clouds_container.point_clouds) + point_cloud.point_size = app_state.point_size; + } // No synthetic key/Ctrl release after handling a shortcut here: rlImGui // only forwards modifier edges, so a faked Ctrl release is never undone @@ -6186,6 +6615,10 @@ void display() if (ImGui::IsItemHovered()) ImGui::SetTooltip("Manually connect overlapping scan sections"); + ImGui::MenuItem("Automatic Image Loop Closure (BoW)", nullptr, &is_bow_loop_closure_gui); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("Detect loop closure candidates from CAMERA_0 images (fbow); review before adding edges"); + ImGui::Separator(); ImGui::MenuItem("LIO segments editor", "Ctrl+E", &is_lio_segments_gui, !is_loop_closure_gui); if (ImGui::IsItemHovered()) @@ -6290,6 +6723,24 @@ void display() } if (ImGui::IsItemHovered()) ImGui::SetTooltip("Intersection menu"); + + auto& loop_closure = session.pose_graph_loop_closure; + ImGui::BeginDisabled(loop_closure.icp_all_edges_run.running); + if (ImGui::Button("Compute Pose Graph SLAM")) + { + loop_closure.compute_pose_graph_slam( + session.point_clouds_container, tls_registration.gnss, session.ground_control_points, session.control_points); + } + ImGui::EndDisabled(); + if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled)) + { + ImGui::SetTooltip( + "Manual Loop Closure's \"Compute Pose Graph SLAM\": optimize the poses with the %zu loop closure edges\n" + "(and GNSS, GCPs, CPs). Keep initial trajectory curvature: %s.%s", + loop_closure.edges.size(), + loop_closure.keep_initial_trajectory_curvature ? "on" : "off", + loop_closure.icp_all_edges_run.running ? "\nWaiting for \"ICP all edges\" to finish." : ""); + } } if (ImGui::BeginMenu("View")) @@ -6653,6 +7104,9 @@ void display() if (is_loop_closure_gui) loop_closure_gui(); + if (is_bow_loop_closure_gui) + bow_loop_closure_gui(); + if (is_lio_segments_gui) lio_segments_gui(); @@ -7375,6 +7829,11 @@ int main(int argc, char* argv[]) EndDrawing(); } + if (bow_state.detect_thread.joinable()) + bow_state.detect_thread.join(); + if (bow_state.montage_tex_valid) + UnloadTexture(bow_state.montage_tex); + rlImGuiShutdown(); CloseWindow(); } catch (const std::bad_alloc& e) diff --git a/apps/multi_view_tls_registration_legacy/multi_view_tls_registration_gui.cpp b/apps/multi_view_tls_registration_legacy/multi_view_tls_registration_gui.cpp index f02b0a4d1..0db4f1df0 100644 --- a/apps/multi_view_tls_registration_legacy/multi_view_tls_registration_gui.cpp +++ b/apps/multi_view_tls_registration_legacy/multi_view_tls_registration_gui.cpp @@ -99,11 +99,11 @@ static const std::vector appShortcuts = { { "Normal keys", "A", " { "", "Ctrl+L", "manual Loop closure" }, { "", "M", "" }, { "", "Ctrl+M", "" }, - { "", "N", "" }, + { "", "N", "Next active edge (manual loop closure)" }, { "", "Ctrl+N", "" }, { "", "O", "" }, { "", "Ctrl+O", "Open session" }, - { "", "P", "" }, + { "", "P", "Previous active edge (manual loop closure)" }, { "", "Ctrl+P", "Pose graph slam" }, { "", "Q", "" }, { "", "Ctrl+Q", "" }, diff --git a/cmake/dependencies.cmake b/cmake/dependencies.cmake index 43f50a39e..1c573cd0c 100644 --- a/cmake/dependencies.cmake +++ b/cmake/dependencies.cmake @@ -151,6 +151,19 @@ include(${THIRDPARTY_DIRECTORY_BINARY}/OpenCV/CMakeLists.txt) find_package(OpenCV REQUIRED) message(STATUS "OpenCV include dir: ${OpenCV_INCLUDE_DIRS}, OpenCV libs: ${OpenCV_LIBS}") +# fbow - Fast Bag-of-Words image retrieval (needs OpenCV, added above) +set(BUILD_UTILS OFF CACHE BOOL "" FORCE) +# fbow's own CMakeLists defaults USE_SSE3/USE_AVX to ON unconditionally (only +# guards -O2 vs -O3 by CMAKE_SYSTEM_PROCESSOR, not the x86 vector flags), which +# fails on arm64 (e.g. Apple Silicon) where -msse3/-mavx aren't valid clang flags. +if(NOT CMAKE_SYSTEM_PROCESSOR MATCHES "^(x86_64|amd64|i686|x86)$") + set(USE_SSE3 OFF CACHE BOOL "" FORCE) + set(USE_AVX OFF CACHE BOOL "" FORCE) +endif() +add_subdirectory(${THIRDPARTY_DIRECTORY}/fbow) +set(FBOW_INCLUDE_DIR ${THIRDPARTY_DIRECTORY}/fbow/src) +message(STATUS "Using bundled fbow from: ${THIRDPARTY_DIRECTORY}/fbow") + # PROJ - Cartographic projections library include(${THIRDPARTY_DIRECTORY_BINARY}/Proj/CMakeLists.txt) message(STATUS "PROJ include dir: ${PROJ_INCLUDE_DIR}, PROJ library: ${PROJ_LIBRARY}") diff --git a/core/CMakeLists.txt b/core/CMakeLists.txt index 55d031263..126b2ff2c 100644 --- a/core/CMakeLists.txt +++ b/core/CMakeLists.txt @@ -61,12 +61,13 @@ set(CORE_GUI_SOURCES # core_pfd -- native file/folder picker dialogs (mandeye::fd, wrapping # portable-file-dialogs), split out of CORE_GUI_SOURCES into its own minimal # target so non-core GUI consumers (the camera_lidar_* apps, via calib_core) -# can reuse it without linking core_math/PROJ/spdlog/vqf/Fusion/plycpp/ +# can reuse it without linking core_math/PROJ/vqf/Fusion/plycpp/ # WGS84toCartesian/imgui/ImGuizmo/freeglut, none of which pfd_wrapper.cpp # actually needs. add_library(core_pfd STATIC src/pfd_wrapper.cpp) target_include_directories(core_pfd PUBLIC include) target_include_directories(core_pfd PRIVATE ${THIRDPARTY_DIRECTORY}/portable-file-dialogs-master) +target_link_libraries(core_pfd PRIVATE spdlog::spdlog) set_target_properties(core_pfd PROPERTIES POSITION_INDEPENDENT_CODE ON) # core_e57 -- E57 point-cloud read/write (mandeye::e57io, wrapping libE57Format diff --git a/core/include/Core/manual_pose_graph_loop_closure.h b/core/include/Core/manual_pose_graph_loop_closure.h index 58e51d423..495dedd88 100644 --- a/core/include/Core/manual_pose_graph_loop_closure.h +++ b/core/include/Core/manual_pose_graph_loop_closure.h @@ -5,6 +5,8 @@ #include #include +#include + #if WITH_GUI == 1 #include #endif @@ -16,12 +18,36 @@ class ManualPoseGraphLoopClosure : public PoseGraphLoopClosure int index_active_edge = 0; bool manipulate_active_edge = false; bool gizmo = false; + //! N / P step the active edge in Gui(); the app turns this off while another list takes these keys. + bool edge_hotkeys = true; double search_radious = 0.1; + //! "ICP all edges": first search radius of its coarse-to-fine steps, see PoseGraphLoopClosure::icp_search_radii. + double icp_all_edges_start_radius = 1.0; + //! Edges the last "ICP all edges" could not refine. + std::vector icp_failed_edges; + //! Number of edges when "ICP all edges" last finished; 0 when it hasn't, or the edges changed since. + size_t icp_all_edges_count = 0; + //! "ICP all edges" in progress: it runs one ICP step per frame, so the window keeps drawing its progress. + struct IcpAllEdgesRun + { + bool running = false; + int edge = 0; //!< edge being refined + size_t step = 0; //!< index into radii + std::vector radii; + std::vector failed; + std::chrono::steady_clock::time_point start; + bool progress_drawn = false; //!< the progress bar has been shown at least once + }; + IcpAllEdgesRun icp_all_edges_run; + //! "Keep initial trajectory curvature": compute_pose_graph_slam() uses the initial poses as the motion model, else the current ones. + bool keep_initial_trajectory_curvature = true; ManualPoseGraphLoopClosure() = default; ~ManualPoseGraphLoopClosure() = default; #if WITH_GUI == 1 + //! "Compute Pose Graph SLAM": sets the motion model, then graph_slam() over the edges, GNSS, GCPs and CPs. + void compute_pose_graph_slam(PointClouds& point_clouds_container, GNSS& gnss, GroundControlPoints& gcps, ControlPoints& cps); void Gui( PointClouds& point_clouds_container, int& index_loop_closure_source, @@ -39,5 +65,11 @@ class ManualPoseGraphLoopClosure : public PoseGraphLoopClosure int index_loop_closure_target, int num_edge_extended_before, int num_edge_extended_after); + +private: + //! Runs the next "ICP all edges" step; finishes the run after the last one. + void icp_all_edges_step(PointClouds& point_clouds_container, int num_edge_extended_before, int num_edge_extended_after); + //! The "ICP all edges" button, start radius and progress. + void icp_all_edges_gui(); #endif }; diff --git a/core/include/Core/pfd_wrapper.hpp b/core/include/Core/pfd_wrapper.hpp index 87d8a2f2d..0d2b06c92 100644 --- a/core/include/Core/pfd_wrapper.hpp +++ b/core/include/Core/pfd_wrapper.hpp @@ -61,6 +61,7 @@ namespace mandeye::fd const std::string& defaultExtension = "", const std::string& defaultFileName = ""); std::string SelectFolder(const std::string& title); + void SetLastLocationHint(const std::string& locationHint); void OutOfMemMessage(); } // namespace mandeye::fd diff --git a/core/include/Core/pose_graph_loop_closure.h b/core/include/Core/pose_graph_loop_closure.h index 1833ab27c..0509945c2 100644 --- a/core/include/Core/pose_graph_loop_closure.h +++ b/core/include/Core/pose_graph_loop_closure.h @@ -65,11 +65,17 @@ class PoseGraphLoopClosure void graph_slam(PointClouds& point_clouds_container, GNSS& gnss, GroundControlPoints& gcps, ControlPoints& cps); void FuseTrajectoryWithGNSS(PointClouds& point_clouds_container, GNSS& gnss); void FuseTrajectoryWithTUM(PointClouds& point_clouds_container, TUM& tum); - void run_icp( + //! Refines one edge's relative pose with point-to-point ICP between its two scans (each extended by its + //! neighbouring scans). + //! @return false when ICP fails; the edge is then left unchanged + bool run_icp( PointClouds& point_clouds_container, int index_active_edge, float search_radius, int number_of_iterations, int num_edge_extended_before, int num_edge_extended_after); + //! Search radii for coarse-to-fine ICP: `start_radius`, then those of the per-edge ICP buttons' steps (2.0, 1.0, + //! 0.5, 0.25, 0.1 m) below it. + static std::vector icp_search_radii(float start_radius); }; diff --git a/core/src/manual_pose_graph_loop_closure.cpp b/core/src/manual_pose_graph_loop_closure.cpp index 1a88502ff..d2cec112d 100644 --- a/core/src/manual_pose_graph_loop_closure.cpp +++ b/core/src/manual_pose_graph_loop_closure.cpp @@ -25,6 +25,141 @@ #include +void ManualPoseGraphLoopClosure::icp_all_edges_step( + PointClouds& point_clouds_container, int num_edge_extended_before, int num_edge_extended_after) +{ + auto& run = icp_all_edges_run; + // The first step waits for a frame that shows the progress bar, since each step blocks the window. + if (!run.progress_drawn) + { + return; + } + if (run.edge < static_cast(edges.size())) + { + const float radius = run.radii[run.step]; + std::cout << "ICP all edges: edge " << run.edge + 1 << " of " << edges.size() << ", search radius " << radius << " m" << std::endl; + if (run_icp(point_clouds_container, run.edge, radius, 30, num_edge_extended_before, num_edge_extended_after)) + { + run.step++; + } + else + { + std::cout << "ICP all edges: edge " << run.edge << " failed at search radius " << radius << " m" << std::endl; + run.failed.push_back(run.edge); + run.step = run.radii.size(); // an edge stops at its first failed step + } + if (run.step >= run.radii.size()) + { + run.edge++; + run.step = 0; + } + } + if (run.edge >= static_cast(edges.size())) + { + run.running = false; + icp_failed_edges = run.failed; + icp_all_edges_count = edges.size(); + std::cout << "ICP all edges: " << edges.size() - run.failed.size() << " of " << edges.size() << " edges refined" << std::endl; + } +} + +void ManualPoseGraphLoopClosure::icp_all_edges_gui() +{ + auto& run = icp_all_edges_run; + const auto format_duration = [](double seconds) + { + const int s = static_cast(seconds + 0.5); + char buf[32]; + std::snprintf(buf, sizeof(buf), "%d:%02d", s / 60, s % 60); + return std::string(buf); + }; + + if (run.running) + { + const size_t steps_per_edge = run.radii.size(); + const double done = static_cast(run.edge * steps_per_edge + run.step); + const double total = static_cast(edges.size() * steps_per_edge); + const double elapsed = std::chrono::duration(std::chrono::steady_clock::now() - run.start).count(); + char overlay[96]; + std::snprintf( + overlay, + sizeof(overlay), + "edge %d of %zu, radius %.2f m", + std::min(run.edge + 1, static_cast(edges.size())), + edges.size(), + run.radii[std::min(run.step, steps_per_edge - 1)]); + ImGui::ProgressBar(total > 0.0 ? static_cast(done / total) : 1.0f, ImVec2(350, 0), overlay); + ImGui::SameLine(); + if (ImGui::Button("Cancel")) + { + run.running = false; + std::cout << "ICP all edges: cancelled after " << run.edge << " of " << edges.size() << " edges" << std::endl; + } + ImGui::SameLine(); + if (done > 0.0) + ImGui::Text( + "%s elapsed, about %s left", format_duration(elapsed).c_str(), format_duration(elapsed * (total - done) / done).c_str()); + else + ImGui::Text("%s elapsed", format_duration(elapsed).c_str()); + run.progress_drawn = true; + return; + } + + ImGui::BeginDisabled(edges.empty()); + if (ImGui::Button("ICP all edges")) + { + run = IcpAllEdgesRun{}; + run.running = true; + run.radii = icp_search_radii(static_cast(icp_all_edges_start_radius)); + run.start = std::chrono::steady_clock::now(); + icp_all_edges_count = 0; + } + ImGui::EndDisabled(); + if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled)) + ImGui::SetTooltip( + "Refine every edge with ICP, coarse to fine from the start radius.\n" + "Run before 'Compute Pose Graph SLAM': an edge added without ICP holds the current misalignment."); + ImGui::SameLine(); + ImGui::SetNextItemWidth(ImGuiNumberWidth); + ImGui::InputDouble("Start radius [m]", &icp_all_edges_start_radius, 0.0, 0.0, "%.2f"); + if (icp_all_edges_start_radius < 0.01) + icp_all_edges_start_radius = 0.01; + if (ImGui::IsItemHovered()) + ImGui::SetTooltip( + "First ICP search radius; the run continues through 2.0, 1.0, 0.5, 0.25, 0.1 m below it.\n" + "Start above how far the edges are off: a larger radius converges from farther but takes longer."); + + // Edge indexes shift when edges are added or removed elsewhere (e.g. the BoW window), so the result is only + // shown while the edge count still matches. + if (icp_all_edges_count > 0 && icp_all_edges_count == edges.size()) + { + ImGui::SameLine(); + if (icp_failed_edges.empty()) + { + ImGui::Text("all %zu edges refined", edges.size()); + } + else + { + std::string failed; + for (const int e : icp_failed_edges) + failed += (failed.empty() ? "" : ", ") + std::to_string(e); + ImGui::TextColored(orangeBorder, "ICP failed on edges: %s", failed.c_str()); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("Check these edges: farther off than the start radius, or too little overlap"); + } + } +} + +void ManualPoseGraphLoopClosure::compute_pose_graph_slam( + PointClouds& point_clouds_container, GNSS& gnss, GroundControlPoints& gcps, ControlPoints& cps) +{ + if (keep_initial_trajectory_curvature) + set_initial_poses_as_motion_model(point_clouds_container); + else + set_current_poses_as_motion_model(point_clouds_container); + graph_slam(point_clouds_container, gnss, gcps, cps); +} + void ManualPoseGraphLoopClosure::Gui( PointClouds& point_clouds_container, int& index_loop_closure_source, @@ -39,6 +174,11 @@ void ManualPoseGraphLoopClosure::Gui( { if (point_clouds_container.point_clouds.size() > 0) { + if (icp_all_edges_run.running) + { + icp_all_edges_step(point_clouds_container, num_edge_extended_before, num_edge_extended_after); + } + if (!manipulate_active_edge) { // suboptimal as distance is computed each frame! @@ -90,26 +230,20 @@ void ManualPoseGraphLoopClosure::Gui( { add_edge(point_clouds_container, index_loop_closure_source, index_loop_closure_target); index_active_edge = edges.size() - 1; + icp_all_edges_count = 0; + icp_all_edges_run.running = false; } ImGui::SameLine(); ImGui::Text("(number of active edges: %zu)", edges.size()); if (!manipulate_active_edge) { - static bool keep_initial_trajectory_curvature = true; + icp_all_edges_gui(); + ImGui::BeginDisabled(icp_all_edges_run.running); if (ImGui::Button("Compute Pose Graph SLAM")) - { - if (keep_initial_trajectory_curvature) - { - set_initial_poses_as_motion_model(point_clouds_container); - } - else - { - set_current_poses_as_motion_model(point_clouds_container); - } - graph_slam(point_clouds_container, gnss, gcps, cps); - } + compute_pose_graph_slam(point_clouds_container, gnss, gcps, cps); + ImGui::EndDisabled(); ImGui::SameLine(); ImGui::Checkbox("Keep initial trajectory curvature", &keep_initial_trajectory_curvature); @@ -400,6 +534,19 @@ void ManualPoseGraphLoopClosure::Gui( ImGui::Separator(); int prev_index_active_edge = index_active_edge; + + // N / P: next / previous active edge, unless a text field is being edited. + const ImGuiIO& io = ImGui::GetIO(); + if (edge_hotkeys && !io.WantTextInput && !io.KeyCtrl && !io.KeyAlt && !io.KeyShift) + { + if (ImGui::IsKeyPressed(ImGuiKey_N) && index_active_edge + 1 < static_cast(edges.size())) + index_active_edge++; + if (ImGui::IsKeyPressed(ImGuiKey_P) && index_active_edge > 0) + index_active_edge--; + } + const bool scroll_to_active_edge = (prev_index_active_edge != index_active_edge); + ImGui::TextDisabled("N / P: next / previous edge"); + ImGui::BeginChild("Edges", ImVec2(0, 0), true); { for (size_t i = 0; i < edges.size(); i++) @@ -411,6 +558,8 @@ void ManualPoseGraphLoopClosure::Gui( ImGui::SetWindowFontScale(1.25f); ImGui::RadioButton(("Active edge " + std::to_string(i)).c_str(), &index_active_edge, i); ImGui::SetWindowFontScale(1.0f); + if (scroll_to_active_edge && index_active_edge == static_cast(i)) + ImGui::SetScrollHereY(0.5f); // suboptimal as distance is computed each frame! double distance = (point_clouds_container.point_clouds[edges[i].index_to].m_pose.translation() - @@ -432,6 +581,8 @@ void ManualPoseGraphLoopClosure::Gui( new_edges.push_back(edges[ni]); } edges = new_edges; + icp_all_edges_count = 0; + icp_all_edges_run.running = false; index_active_edge = std::min(index_active_edge, static_cast(edges.size() - 1)); manipulate_active_edge = (edges.size() > 0); diff --git a/core/src/pfd_wrapper.cpp b/core/src/pfd_wrapper.cpp index b861bf862..9d75a5e64 100644 --- a/core/src/pfd_wrapper.cpp +++ b/core/src/pfd_wrapper.cpp @@ -1,9 +1,9 @@ #include #include +#include #include -#include #include namespace mandeye::fd @@ -90,13 +90,16 @@ namespace mandeye::fd return output_folder_name; } - + void SetLastLocationHint(const std::string& locationHint) + { + spdlog::info("File dialogs will open in: '{}'", locationHint); + internal::lastLocationHint = locationHint; + } void OutOfMemMessage() { - std::cerr << "Adjust paging / swap memory with tips available here : " - "https://github.com/MapsHD/HDMapping/tree/main/doc/" - "virtual_memory.md " - << std::endl; + spdlog::error( + "Adjust paging / swap memory with tips available here: " + "https://github.com/MapsHD/HDMapping/tree/main/doc/virtual_memory.md"); [[maybe_unused]] pfd::message message( "System is out of memory", "System is out memory, make sure that virtual memory is set " diff --git a/core/src/pose_graph_loop_closure.cpp b/core/src/pose_graph_loop_closure.cpp index 6d953e804..8e1728f34 100644 --- a/core/src/pose_graph_loop_closure.cpp +++ b/core/src/pose_graph_loop_closure.cpp @@ -1259,7 +1259,7 @@ void PoseGraphLoopClosure::FuseTrajectoryWithTUM(PointClouds& point_clouds_conta } } -void PoseGraphLoopClosure::run_icp( +bool PoseGraphLoopClosure::run_icp( PointClouds& point_clouds_container, int index_active_edge, float search_radius, @@ -1324,5 +1324,20 @@ void PoseGraphLoopClosure::run_icp( if (icp.compute(source, target, search_radius, number_of_iterations, m_pose)) { edges[index_active_edge].relative_pose_tb = pose_tait_bryan_from_affine_matrix(m_pose); + return true; } + return false; +} + +std::vector PoseGraphLoopClosure::icp_search_radii(float start_radius) +{ + std::vector radii{ start_radius }; + for (const float radius : { 2.0f, 1.0f, 0.5f, 0.25f, 0.1f }) + { + if (radius < start_radius * 0.999f) + { + radii.push_back(radius); + } + } + return radii; } \ No newline at end of file diff --git a/deploy_mandeye.bat b/deploy_mandeye.bat index 86c312e79..dd2106c32 100644 --- a/deploy_mandeye.bat +++ b/deploy_mandeye.bat @@ -60,7 +60,7 @@ rem This list has to be kept in sync by hand with the hdmapping_install_app() rem calls in apps/*/CMakeLists.txt. hd_mapper is deliberately absent: it is rem gated behind BUILD_WITH_HD_MAPPER_APPLICATION, which defaults to OFF, so rem listing it would warn on every normal build. -set "EXPECTED=camera_lidar_calibration.exe camera_lidar_intrinsics_calib.exe camera_lidar_trajectory_viewer.exe concatenate_multi_livox.exe drag_folder_with_mandeye_data_and_drop_here-precision_forestry.exe laz_to_mcap.exe laz_to_pcd.exe laz_to_ply.exe laz_to_txt.exe lidar_odometry_step_1.exe lidar_odometry_step_1_legacy.exe livox_mid_360_intrinsic_calibration.exe mandeye_compare_trajectories.exe mandeye_mission_recorder_calibration.exe mandeye_raw_data_viewer.exe mandeye_raw_data_viewer_legacy.exe mandeye_single_session_viewer.exe matrix_mul.exe mcap_to_laz.exe multiply_timestamps_session_point_cloud_laz.exe multiply_timestamps_session_trajectory_csv.exe multi_session_registration_step_3.exe multi_session_registration_step_3_legacy.exe multi_view_tls_registration_step_2.exe multi_view_tls_registration_step_2_legacy.exe ouster_pcap_to_laz.exe pcd_to_laz.exe precision_forestry_tools.exe session_to_mcap.exe split_multi_livox.exe freeglut.dll laszip3.dll opencv_world4130.dll proj_9_3.dll tbb12.dll z.dll" +set "EXPECTED=camera_lidar_calibration.exe camera_lidar_intrinsics_calib.exe camera_lidar_trajectory_viewer.exe concatenate_multi_livox.exe drag_folder_with_mandeye_data_and_drop_here-precision_forestry.exe laz_to_mcap.exe laz_to_pcd.exe laz_to_ply.exe laz_to_txt.exe lidar_odometry_step_1.exe lidar_odometry_step_1_legacy.exe livox_mid_360_intrinsic_calibration.exe mandeye_compare_trajectories.exe mandeye_mission_recorder_calibration.exe mandeye_raw_data_viewer.exe mandeye_raw_data_viewer_legacy.exe mandeye_single_session_viewer.exe matrix_mul.exe mcap_to_laz.exe multiply_timestamps_session_point_cloud_laz.exe multiply_timestamps_session_trajectory_csv.exe multi_session_registration_step_3.exe multi_session_registration_step_3_legacy.exe multi_view_tls_registration_step_2.exe multi_view_tls_registration_step_2_legacy.exe ouster_pcap_to_laz.exe pcd_to_laz.exe precision_forestry_tools.exe session_intensity_panoramas.exe session_to_mcap.exe split_multi_livox.exe freeglut.dll laszip3.dll opencv_world4130.dll proj_9_3.dll tbb12.dll z.dll" set "MISSING=" for %%F in (%EXPECTED%) do ( From c918e62239ba05500f93e0952bcdabd019635813 Mon Sep 17 00:00:00 2001 From: Michal Pelka Date: Wed, 11 Nov 2026 02:51:32 +0100 Subject: [PATCH 2/9] Add PairWiseICP regression test (core/tests) New doctest target hdmapping_core_tests (BUILD_TESTING=ON), linking core_no_gui. On a synthetic room scan (portable RNG) it checks that compute() recovers a known 0.2 m / 2 deg offset coarse to fine, returns false without correspondences or with fewer than 100, and pins the pose of a fixed 10-iteration run to 1e-9 so refactors of compute() keep the numbers (rounding differs by ~1e-16; searching the last point of each bucket would move it ~2e-4). Signed-off-by: Michal Pelka Co-Authored-By: Claude Opus 5.5 --- CMakeLists.txt | 1 + core/tests/CMakeLists.txt | 27 ++++ core/tests/test_pair_wise_icp.cpp | 248 ++++++++++++++++++++++++++++++ 3 files changed, 276 insertions(+) create mode 100644 core/tests/CMakeLists.txt create mode 100644 core/tests/test_pair_wise_icp.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 6cedf8f73..f3e204f9f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -123,6 +123,7 @@ option(BUILD_TESTING "Build HDMapping unit tests" OFF) if(BUILD_TESTING) enable_testing() add_subdirectory(shared/tests) + add_subdirectory(core/tests) add_subdirectory(calib_core/tests) add_subdirectory(apps/lidar_odometry_step_1/tests) add_subdirectory(rosbags/tests) diff --git a/core/tests/CMakeLists.txt b/core/tests/CMakeLists.txt new file mode 100644 index 000000000..7491c0fad --- /dev/null +++ b/core/tests/CMakeLists.txt @@ -0,0 +1,27 @@ +cmake_minimum_required(VERSION 4.0.0) + +project(hdmapping_core_tests) + +# Unit tests for core/ (core_no_gui, the GUI-less build of the core library). +# Uses doctest, same as shared/tests. +add_executable(hdmapping_core_tests + test_pair_wise_icp.cpp +) + +target_include_directories(hdmapping_core_tests PRIVATE + ${THIRDPARTY_DIRECTORY}/doctest + ${REPOSITORY_DIRECTORY}/core/include + ${EIGEN3_INCLUDE_DIR} +) + +target_link_libraries(hdmapping_core_tests PRIVATE + core_no_gui + ${PLATFORM_MISCELLANEOUS_LIBS} +) + +if (MSVC) + target_compile_definitions(hdmapping_core_tests PRIVATE _USE_MATH_DEFINES) +endif() + +include(CTest) +add_test(NAME hdmapping_core_tests COMMAND hdmapping_core_tests) diff --git a/core/tests/test_pair_wise_icp.cpp b/core/tests/test_pair_wise_icp.cpp new file mode 100644 index 000000000..2e596f91c --- /dev/null +++ b/core/tests/test_pair_wise_icp.cpp @@ -0,0 +1,248 @@ +#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN +#include + +#include + +#include + +#include +#include +#include +#include + +namespace +{ + /** + * @brief Portable pseudo-random generator (splitmix64), so the scene is the same on every platform and + * standard library (std::uniform_real_distribution is implementation-defined). + */ + class SplitMix64 + { + public: + explicit SplitMix64(uint64_t seed) + : state(seed) + { + } + + /** + * @brief Next uniform value. + * @return Value in [lo, hi). + */ + double uniform(double lo, double hi) + { + uint64_t z = (state += 0x9E3779B97F4A7C15ull); + z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9ull; + z = (z ^ (z >> 27)) * 0x94D049BB133111EBull; + z = z ^ (z >> 31); + return lo + (hi - lo) * static_cast(z >> 11) * (1.0 / 9007199254740992.0); + } + + private: + uint64_t state; + }; + + /** + * @brief Synthetic room scan: floor, ceiling, four walls and three boxes, sampled on a jittered 0.1 m grid. + * The boxes break the room's symmetry so all six pose parameters are constrained. + * @return Points in the target (world) frame. + */ + std::vector make_room() + { + SplitMix64 rng(1); + std::vector points; + const double step = 0.1; + const double x0 = 2.0, x1 = 14.0, y0 = 3.0, y1 = 11.0, z0 = 0.0, z1 = 3.0; + const auto jitter = [&]() { return rng.uniform(-0.03, 0.03); }; + + for (double x = x0; x <= x1; x += step) + { + for (double y = y0; y <= y1; y += step) + { + points.emplace_back(x + jitter(), y + jitter(), z0); + points.emplace_back(x + jitter(), y + jitter(), z1); + } + } + for (double z = z0; z <= z1; z += step) + { + for (double x = x0; x <= x1; x += step) + { + points.emplace_back(x + jitter(), y0, z + jitter()); + points.emplace_back(x + jitter(), y1, z + jitter()); + } + for (double y = y0; y <= y1; y += step) + { + points.emplace_back(x0, y + jitter(), z + jitter()); + points.emplace_back(x1, y + jitter(), z + jitter()); + } + } + + // Boxes {min corner, size}: only their side faces and top, as a lidar would see them. + const std::vector> boxes = { + { { 4.0, 5.0, 0.0 }, { 1.0, 0.6, 1.2 } }, + { { 9.0, 8.0, 0.0 }, { 0.5, 1.5, 2.0 } }, + { { 11.5, 4.0, 0.0 }, { 1.2, 1.2, 0.8 } }, + }; + for (const auto& [corner, size] : boxes) + { + const Eigen::Vector3d c1 = corner + size; + for (double z = corner.z(); z <= c1.z(); z += step) + { + for (double x = corner.x(); x <= c1.x(); x += step) + { + points.emplace_back(x + jitter(), corner.y(), z + jitter()); + points.emplace_back(x + jitter(), c1.y(), z + jitter()); + } + for (double y = corner.y(); y <= c1.y(); y += step) + { + points.emplace_back(corner.x(), y + jitter(), z + jitter()); + points.emplace_back(c1.x(), y + jitter(), z + jitter()); + } + } + for (double x = corner.x(); x <= c1.x(); x += step) + { + for (double y = corner.y(); y <= c1.y(); y += step) + { + points.emplace_back(x + jitter(), y + jitter(), c1.z()); + } + } + } + return points; + } + + /** + * @brief Pose from translation and roll/pitch/yaw. + * @param t Translation [m]. + * @param roll_deg Rotation about X [deg]. + * @param pitch_deg Rotation about Y [deg]. + * @param yaw_deg Rotation about Z [deg]. + * @return The pose. + */ + Eigen::Affine3d make_pose(const Eigen::Vector3d& t, double roll_deg, double pitch_deg, double yaw_deg) + { + const double d2r = M_PI / 180.0; + Eigen::Affine3d pose = Eigen::Affine3d::Identity(); + pose.translation() = t; + pose.linear() = (Eigen::AngleAxisd(yaw_deg * d2r, Eigen::Vector3d::UnitZ()) * + Eigen::AngleAxisd(pitch_deg * d2r, Eigen::Vector3d::UnitY()) * + Eigen::AngleAxisd(roll_deg * d2r, Eigen::Vector3d::UnitX())) + .toRotationMatrix(); + return pose; + } + + /** @brief Ground truth source-to-target pose of the test scans. */ + const Eigen::Affine3d true_pose = make_pose({ 0.4, -0.3, 0.1 }, 1.0, -1.0, 3.0); + + /** @brief Initial guess: the ground truth moved by about 0.2 m and 2 deg. */ + const Eigen::Affine3d initial_pose = true_pose * make_pose({ 0.15, -0.1, 0.05 }, 0.5, -0.5, 1.5); + + /** + * @brief Source scan: every third room point, moved into the source frame, with 2 mm noise. + * @param target The room in the target frame. + * @return Points in the source frame. + */ + std::vector make_source(const std::vector& target) + { + SplitMix64 rng(2); + const Eigen::Affine3d target_to_source = true_pose.inverse(); + std::vector source; + for (size_t i = 0; i < target.size(); i += 3) + { + const Eigen::Vector3d noise(rng.uniform(-0.002, 0.002), rng.uniform(-0.002, 0.002), rng.uniform(-0.002, 0.002)); + source.push_back(target_to_source * target[i] + noise); + } + return source; + } + + /** + * @brief Angle of the rotation between two poses. + * @return Angle [deg]. + */ + double rotation_error_deg(const Eigen::Affine3d& a, const Eigen::Affine3d& b) + { + return Eigen::AngleAxisd(a.linear().transpose() * b.linear()).angle() * 180.0 / M_PI; + } +} // namespace + +TEST_CASE("PairWiseICP::compute recovers a known offset, coarse to fine") +{ + const std::vector target = make_room(); + const std::vector source = make_source(target); + + Eigen::Affine3d pose = initial_pose; + REQUIRE((pose.translation() - true_pose.translation()).norm() > 0.1); + + PairWiseICP icp; + for (const double radius : { 1.0, 0.5, 0.25, 0.1 }) + { + REQUIRE(icp.compute(source, target, radius, 30, pose)); + } + + CHECK((pose.translation() - true_pose.translation()).norm() < 0.005); + CHECK(rotation_error_deg(pose, true_pose) < 0.05); +} + +TEST_CASE("PairWiseICP::compute returns false and keeps the pose without correspondences") +{ + const std::vector target = make_room(); + std::vector source = make_source(target); + for (auto& p : source) + { + p.x() += 100.0; // far outside the search radius of every target point + } + + Eigen::Affine3d pose = initial_pose; + PairWiseICP icp; + CHECK_FALSE(icp.compute(source, target, 0.5, 5, pose)); + CHECK(pose.matrix() == initial_pose.matrix()); +} + +TEST_CASE("PairWiseICP::compute returns false with fewer than 100 correspondences") +{ + const std::vector target = make_room(); + std::vector source = make_source(target); + source.resize(50); + + Eigen::Affine3d pose = initial_pose; + PairWiseICP icp; + CHECK_FALSE(icp.compute(source, target, 0.5, 5, pose)); + CHECK(pose.matrix() == initial_pose.matrix()); +} + +// Pins the exact result of a fixed run, so a refactor of compute() (threading, neighbour search, summation) is +// held to the numbers of the reference implementation (as of "Step 2: BoW loop closure, ICP all edges"). The +// tolerance covers rounding differences between compilers and platforms (FMA, libm, summation order: about 1e-16 +// here); a change to the algorithm moves the result far more (e.g. also searching the last point of each bucket: +// about 2e-4). +TEST_CASE("PairWiseICP::compute matches the reference result") +{ + const std::vector target = make_room(); + const std::vector source = make_source(target); + + Eigen::Affine3d pose = initial_pose; + PairWiseICP icp; + REQUIRE(icp.compute(source, target, 0.5, 10, pose)); + + // Build with -DPRINT_REFERENCE to print new reference values after a deliberate change to the algorithm. +#ifdef PRINT_REFERENCE + std::printf("REFERENCE\n%.17g, %.17g, %.17g, %.17g\n%.17g, %.17g, %.17g, %.17g\n%.17g, %.17g, %.17g, %.17g\n", + pose(0, 0), pose(0, 1), pose(0, 2), pose(0, 3), pose(1, 0), pose(1, 1), pose(1, 2), pose(1, 3), pose(2, 0), pose(2, 1), + pose(2, 2), pose(2, 3)); +#endif + + const double tolerance = 1e-9; + // clang-format off + const double expected[3][4] = { + { 0.99847835113005579, -0.052624056892179416, -0.016483050713194683, 0.4000125297669288 }, + { 0.052319974395097578, 0.99846146760778998, -0.018366218494686254, -0.29978225332893682 }, + { 0.01742419593270856, 0.017475878767801229, 0.99969544915308661, 0.10003668251083121 }, + }; + // clang-format on + for (int r = 0; r < 3; r++) + { + for (int c = 0; c < 4; c++) + { + INFO("pose(", r, ", ", c, ") = ", pose(r, c), ", expected ", expected[r][c]); + CHECK(std::abs(pose(r, c) - expected[r][c]) < tolerance); + } + } +} From 511e380be27406eee5b91002616d0854de3c75f1 Mon Sep 17 00:00:00 2001 From: Michal Pelka Date: Wed, 11 Nov 2026 02:20:56 +0100 Subject: [PATCH 3/9] PairWiseICP: sum normal equations without a lock per point Build the target's bucket index once per call; 256 blocks of source points each sum their own normal equations, added in a fixed order (deterministic). Results on 3 loop edges identical to 12 decimals; 32 -> 23 s per edge (measured under load, needs an idle Release measurement). Signed-off-by: Michal Pelka Co-Authored-By: Claude Opus 5.5 --- .../src/pair_wise_iterative_closest_point.cpp | 132 +++++++++++------- 1 file changed, 84 insertions(+), 48 deletions(-) diff --git a/core/src/pair_wise_iterative_closest_point.cpp b/core/src/pair_wise_iterative_closest_point.cpp index 9c1371dab..fed5a7f1c 100644 --- a/core/src/pair_wise_iterative_closest_point.cpp +++ b/core/src/pair_wise_iterative_closest_point.cpp @@ -144,40 +144,60 @@ bool PairWiseICP::compute( std::cout << "PairWiseICP::compute" << std::endl; bool multithread = true; - for (int iter = 0; iter < number_of_iterations; iter++) + // The target and the search radius don't change between iterations, so its bucket index is built once. + std::vector> indexes; + + for (int i = 0; i < target.size(); i++) { - std::vector> indexes; + uint64_t index = get_rgd_index_3d(target[i], { search_radious, search_radious, search_radious }); + indexes.emplace_back(index, i); + } - for (int i = 0; i < target.size(); i++) + std::sort( + indexes.begin(), + indexes.end(), + [](const std::pair& a, const std::pair& b) { - uint64_t index = get_rgd_index_3d(target[i], { search_radious, search_radious, search_radious }); - indexes.emplace_back(index, i); - } - - std::sort( - indexes.begin(), - indexes.end(), - [](const std::pair& a, const std::pair& b) - { - return a.first < b.first; - }); + return a.first < b.first; + }); - std::unordered_map> buckets; + std::unordered_map> buckets; - for (uint32_t i = 0; i < indexes.size(); i++) + for (uint32_t i = 0; i < indexes.size(); i++) + { + uint64_t index_of_bucket = indexes[i].first; + if (buckets.contains(index_of_bucket)) { - uint64_t index_of_bucket = indexes[i].first; - if (buckets.contains(index_of_bucket)) - { - buckets[index_of_bucket].second = i; - } - else - { - buckets[index_of_bucket].first = i; - buckets[index_of_bucket].second = i; - } + buckets[index_of_bucket].second = i; } + else + { + buckets[index_of_bucket].first = i; + buckets[index_of_bucket].second = i; + } + } + + // Target points in bucket order, so a bucket's points are read from contiguous memory. + std::vector target_sorted(indexes.size()); + for (size_t i = 0; i < indexes.size(); i++) + { + target_sorted[i] = target[indexes[i].second]; + } + const double search_radious_squared = search_radious * search_radious; + // Normal equations are summed per block of source points, then the blocks in order: no lock per point, and + // the same sum on every run and machine. + struct NormalEquations + { + Eigen::Matrix AtPA = Eigen::Matrix::Zero(); + Eigen::Matrix AtPB = Eigen::Matrix::Zero(); + int counter_nn = 0; + }; + constexpr size_t number_of_blocks = 256; + const size_t block_size = (source.size() + number_of_blocks - 1) / number_of_blocks; + + for (int iter = 0; iter < number_of_iterations; iter++) + { std::cout << "iteration: " << iter + 1 << " of: " << number_of_iterations << std::endl; Eigen::MatrixXd AtPA(6, 6); AtPA.setZero(); @@ -185,10 +205,10 @@ bool PairWiseICP::compute( AtPB.setZero(); Eigen::Vector3d b(search_radious, search_radious, search_radious); - std::mutex mutex; - int counter_nn = 0; + const TaitBryanPose pose_s = pose_tait_bryan_from_affine_matrix(m_pose_result); + std::vector block_sums(number_of_blocks); - const auto hessian_fun = [&](const Eigen::Vector3d& source_i) + const auto hessian_fun = [&](const Eigen::Vector3d& source_i, NormalEquations& sum) { if (source_i.norm() < 0.1) { @@ -197,8 +217,7 @@ bool PairWiseICP::compute( Eigen::Vector3d source_point_global = m_pose_result * source_i; - double min_dist = 1000000000.0; - Eigen::Vector3d target_i; + double min_dist_squared = 1000000000.0; Eigen::Vector3d target_i_nn; bool nn_found = false; for (double x = -search_radious; x <= search_radious; x += search_radious) @@ -211,19 +230,19 @@ bool PairWiseICP::compute( uint64_t index_of_bucket = get_rgd_index_3d(source_point_global_ext, { search_radious, search_radious, search_radious }); - if (buckets.contains(index_of_bucket)) + const auto bucket = buckets.find(index_of_bucket); + if (bucket != buckets.end()) { - for (int index = buckets[index_of_bucket].first; index < buckets[index_of_bucket].second; index++) + for (int index = bucket->second.first; index < bucket->second.second; index++) { - int index_element_target = indexes[index].second; - target_i = target[index_element_target]; - double d = (source_point_global - target_i).norm(); + const Eigen::Vector3d& target_i = target_sorted[index]; + const double d_squared = (source_point_global - target_i).squaredNorm(); - if (d < search_radious) + if (d_squared < search_radious_squared) { - if (d < min_dist) + if (d_squared < min_dist_squared) { - min_dist = d; + min_dist_squared = d_squared; nn_found = true; target_i_nn = target_i; } @@ -238,7 +257,6 @@ bool PairWiseICP::compute( if (nn_found) { const Eigen::Vector3d& p_s = source_i; - const TaitBryanPose pose_s = pose_tait_bryan_from_affine_matrix(m_pose_result); Eigen::Matrix AtPA_; point_to_point_source_to_target_tait_bryan_wc_AtPA_simplified( @@ -287,10 +305,20 @@ bool PairWiseICP::compute( target_i_nn.y(), target_i_nn.z()); - std::unique_lock lck(mutex); - AtPA.block<6, 6>(0, 0) += AtPA_; - AtPB.block<6, 1>(0, 0) -= AtPB_; - counter_nn++; + sum.AtPA += AtPA_; + sum.AtPB -= AtPB_; + sum.counter_nn++; + } + }; + + const auto block_fun = [&](NormalEquations& sum) + { + const size_t block = &sum - block_sums.data(); + const size_t begin = std::min(source.size(), block * block_size); + const size_t end = std::min(source.size(), begin + block_size); + for (size_t i = begin; i < end; i++) + { + hessian_fun(source[i], sum); } }; @@ -300,13 +328,21 @@ bool PairWiseICP::compute( #if USE_EXECUTION_PAR_UNSEQ std::execution::par_unseq, #endif - std::begin(source), - std::end(source), - hessian_fun); + block_sums.begin(), + block_sums.end(), + block_fun); } else { - std::for_each(std::begin(source), std::end(source), hessian_fun); + std::for_each(block_sums.begin(), block_sums.end(), block_fun); + } + + int counter_nn = 0; + for (const auto& sum : block_sums) + { + AtPA += sum.AtPA; + AtPB += sum.AtPB; + counter_nn += sum.counter_nn; } if (AtPB(0, 0) == 0.0 && AtPB(1, 0) == 0.0 && AtPB(2, 0) == 0.0 && AtPB(3, 0) == 0.0 && AtPB(4, 0) == 0.0 && AtPB(5, 0) == 0.0) From 3048aaf5fb00967c8a53adb131a16521c567a696 Mon Sep 17 00:00:00 2001 From: Michal Pelka Date: Wed, 11 Nov 2026 02:26:22 +0100 Subject: [PATCH 4/9] fbow: build on non-x86 (Apple Silicon) via a patch applied at configure fbow includes and uses cpuid except on Android. 3rdparty/patches/fbow_non_x86.patch takes those portable paths on any non-x86 CPU (keeping 64-bit hamming words on 64-bit ARM); dependencies.cmake applies it to the submodule on non-x86 hosts, skipping it if already applied. Signed-off-by: Michal Pelka Co-Authored-By: Claude Opus 5.5 --- 3rdparty/patches/fbow_non_x86.patch | 89 +++++++++++++++++++++++++++++ cmake/dependencies.cmake | 20 +++++++ 2 files changed, 109 insertions(+) create mode 100644 3rdparty/patches/fbow_non_x86.patch diff --git a/3rdparty/patches/fbow_non_x86.patch b/3rdparty/patches/fbow_non_x86.patch new file mode 100644 index 000000000..3fdeea5a4 --- /dev/null +++ b/3rdparty/patches/fbow_non_x86.patch @@ -0,0 +1,89 @@ +diff --git a/src/cpu.h b/src/cpu.h +index 7dcb7e3..7b73e7e 100644 +--- a/src/cpu.h ++++ b/src/cpu.h +@@ -4,7 +4,11 @@ + #include + #include + #include +-#ifdef __ANDROID__ ++// No x86 SIMD/cpuid off x86 (Android, arm64 e.g. Apple Silicon): portable code paths only. ++#if defined(__ANDROID__) || !(defined(__x86_64__) || defined(_M_X64) || defined(__i386) || defined(_M_IX86)) ++#define FBOW_NO_X86 1 ++#endif ++#ifdef FBOW_NO_X86 + + #else + #if defined(__x86_64__) || defined(_M_X64) || defined(__i386) || defined(_M_IX86) +@@ -48,7 +52,7 @@ private: + static bool inline detect_OS_AVX512(); + static inline uint64_t xgetbv(unsigned int x); + }; +-#ifdef __ANDROID__ ++#ifdef FBOW_NO_X86 + + void cpu::cpuid(int32_t out[4], int32_t x){} + #else +@@ -91,7 +95,7 @@ bool cpu::detect_OS_x64(){ return true;} + //////////////////////////////////////////////////////////////////////////////// + bool cpu::detect_OS_AVX(){ + // Copied from: http://stackoverflow.com/a/22521619/922184 +-#ifndef __ANDROID__ ++#ifndef FBOW_NO_X86 + + bool avxSupported = false; + int cpuInfo[4]; cpuid(cpuInfo, 1); +@@ -105,7 +109,7 @@ bool cpu::detect_OS_AVX(){ + } + bool cpu::detect_OS_AVX512(){ + +-#ifndef __ANDROID__ ++#ifndef FBOW_NO_X86 + if (!detect_OS_AVX()) + return false; + uint64_t xcrFeatureMask = xgetbv(_XCR_XFEATURE_ENABLED_MASK); +@@ -118,7 +122,7 @@ bool cpu::detect_OS_AVX512(){ + std::string cpu::get_vendor_string(){ int32_t CPUInfo[4]; char name[13];cpuid(CPUInfo, 0); memcpy(name + 0, &CPUInfo[1], 4);memcpy(name + 4, &CPUInfo[3], 4); memcpy(name + 8, &CPUInfo[2], 4); name[12] = '\0'; return name;} + void cpu::detect_host(){ + +-#ifndef __ANDROID__ ++#ifndef FBOW_NO_X86 + + OS_x64 = detect_OS_x64(); + OS_AVX = detect_OS_AVX(); +@@ -136,6 +140,9 @@ void cpu::detect_host(){ + if (nIds >= 0x00000001){ cpuid(info, 0x00000001); HW_MMX = (info[3] & ((int)1 << 23)) != 0; HW_SSE = (info[3] & ((int)1 << 25)) != 0; HW_SSE2 = (info[3] & ((int)1 << 26)) != 0; HW_SSE3 = (info[2] & ((int)1 << 0)) != 0; HW_SSSE3 = (info[2] & ((int)1 << 9)) != 0; HW_SSE41 = (info[2] & ((int)1 << 19)) != 0; HW_SSE42 = (info[2] & ((int)1 << 20)) != 0; HW_AES = (info[2] & ((int)1 << 25)) != 0; HW_AVX = (info[2] & ((int)1 << 28)) != 0; HW_FMA3 = (info[2] & ((int)1 << 12)) != 0; HW_RDRAND = (info[2] & ((int)1 << 30)) != 0; } + if (nIds >= 0x00000007){ cpuid(info, 0x00000007); HW_AVX2 = (info[1] & ((int)1 << 5)) != 0; HW_BMI1 = (info[1] & ((int)1 << 3)) != 0; HW_BMI2 = (info[1] & ((int)1 << 8)) != 0; HW_ADX = (info[1] & ((int)1 << 19)) != 0; HW_MPX = (info[1] & ((int)1 << 14)) != 0; HW_SHA = (info[1] & ((int)1 << 29)) != 0; HW_PREFETCHWT1 = (info[2] & ((int)1 << 0)) != 0; HW_AVX512_F = (info[1] & ((int)1 << 16)) != 0; HW_AVX512_CD = (info[1] & ((int)1 << 28)) != 0; HW_AVX512_PF = (info[1] & ((int)1 << 26)) != 0; HW_AVX512_ER = (info[1] & ((int)1 << 27)) != 0; HW_AVX512_VL = (info[1] & ((int)1 << 31)) != 0; HW_AVX512_BW = (info[1] & ((int)1 << 30)) != 0; HW_AVX512_DQ = (info[1] & ((int)1 << 17)) != 0; HW_AVX512_IFMA = (info[1] & ((int)1 << 21)) != 0; HW_AVX512_VBMI = (info[2] & ((int)1 << 1)) != 0; } + if (nExIds >= 0x80000001){ cpuid(info, 0x80000001); HW_x64 = (info[3] & ((int)1 << 29)) != 0; HW_ABM = (info[2] & ((int)1 << 5)) != 0; HW_SSE4a = (info[2] & ((int)1 << 6)) != 0; HW_FMA4 = (info[2] & ((int)1 << 16)) != 0; HW_XOP = (info[2] & ((int)1 << 11)) != 0; } ++#else ++ // 64-bit words for the hamming distance (ORB) on 64-bit non-x86 CPUs. ++ HW_x64 = sizeof(void*) == 8; + #endif + } + +diff --git a/src/fbow.h b/src/fbow.h +index 02d9c2d..cd8bf41 100644 +--- a/src/fbow.h ++++ b/src/fbow.h +@@ -6,10 +6,10 @@ + #include + #include + #include +-#ifndef __ANDROID__ ++#include "cpu.h" ++#ifndef FBOW_NO_X86 + #include + #endif +-#include "cpu.h" + namespace fbow{ + + //float initialized to zero. +@@ -241,7 +241,7 @@ private: + return d; + } + }; +-#ifdef __ANDROID__ ++#ifdef FBOW_NO_X86 + //fake elements to allow compilation + struct L2_avx_generic:public Lx{inline float computeDist(uint64_t *ptr){return std::numeric_limits::max();}}; + struct L2_se3_generic:public Lx{inline float computeDist(uint64_t *ptr){return std::numeric_limits::max();}}; diff --git a/cmake/dependencies.cmake b/cmake/dependencies.cmake index 1c573cd0c..b82b6aa9a 100644 --- a/cmake/dependencies.cmake +++ b/cmake/dependencies.cmake @@ -159,6 +159,26 @@ set(BUILD_UTILS OFF CACHE BOOL "" FORCE) if(NOT CMAKE_SYSTEM_PROCESSOR MATCHES "^(x86_64|amd64|i686|x86)$") set(USE_SSE3 OFF CACHE BOOL "" FORCE) set(USE_AVX OFF CACHE BOOL "" FORCE) + # fbow's sources include and use cpuid unless built for + # Android; the patch takes those portable paths on any non-x86 CPU. + # Applied once to the submodule's working tree (skipped if already applied). + find_package(Git REQUIRED) + set(FBOW_PATCH ${THIRDPARTY_DIRECTORY}/patches/fbow_non_x86.patch) + execute_process( + COMMAND ${GIT_EXECUTABLE} apply --reverse --check ${FBOW_PATCH} + WORKING_DIRECTORY ${THIRDPARTY_DIRECTORY}/fbow + RESULT_VARIABLE FBOW_PATCH_APPLIED + OUTPUT_QUIET ERROR_QUIET) + if(NOT FBOW_PATCH_APPLIED EQUAL 0) + execute_process( + COMMAND ${GIT_EXECUTABLE} apply ${FBOW_PATCH} + WORKING_DIRECTORY ${THIRDPARTY_DIRECTORY}/fbow + RESULT_VARIABLE FBOW_PATCH_RESULT) + if(NOT FBOW_PATCH_RESULT EQUAL 0) + message(FATAL_ERROR "Failed to apply ${FBOW_PATCH} to ${THIRDPARTY_DIRECTORY}/fbow") + endif() + message(STATUS "Applied ${FBOW_PATCH}") + endif() endif() add_subdirectory(${THIRDPARTY_DIRECTORY}/fbow) set(FBOW_INCLUDE_DIR ${THIRDPARTY_DIRECTORY}/fbow/src) From ea1c7bad98f15b843a9a97074d7e72e54e087d89 Mon Sep 17 00:00:00 2001 From: Michal Pelka Date: Wed, 11 Nov 2026 02:27:09 +0100 Subject: [PATCH 5/9] clang format Signed-off-by: Michal Pelka --- .../console_tools/bow_loop_closure_detect.cpp | 11 +- .../bow_loop_closure_detector.cpp | 717 +++++++++--------- .../bow_loop_closure_detector.h | 202 ++--- .../multi_view_tls_registration_gui.cpp | 236 +++--- 4 files changed, 595 insertions(+), 571 deletions(-) diff --git a/apps/console_tools/bow_loop_closure_detect.cpp b/apps/console_tools/bow_loop_closure_detect.cpp index e9e1da1e9..2314a3f8d 100644 --- a/apps/console_tools/bow_loop_closure_detect.cpp +++ b/apps/console_tools/bow_loop_closure_detect.cpp @@ -62,8 +62,7 @@ int main(int argc, char* argv[]) try { vocabulary = std::make_unique(bow_loop_closure::loadVocabulary(vocab_path)); - } - catch (const std::exception& e) + } catch (const std::exception& e) { spdlog::error("{}", e.what()); return 4; @@ -97,7 +96,13 @@ int main(int argc, char* argv[]) session.point_clouds_container.point_clouds.size(), params.min_arc_gap_m, params.max_xy_dist_m, - static_cast(std::count_if(chunk_frames.begin(), chunk_frames.end(), [](const auto& f) { return !f.empty(); })), + static_cast(std::count_if( + chunk_frames.begin(), + chunk_frames.end(), + [](const auto& f) + { + return !f.empty(); + })), chunk_frames.size()); return 0; diff --git a/apps/multi_view_tls_registration/bow_loop_closure_detector.cpp b/apps/multi_view_tls_registration/bow_loop_closure_detector.cpp index 759b33a23..02bd589f6 100644 --- a/apps/multi_view_tls_registration/bow_loop_closure_detector.cpp +++ b/apps/multi_view_tls_registration/bow_loop_closure_detector.cpp @@ -20,408 +20,429 @@ namespace fs = std::filesystem; namespace bow_loop_closure { -namespace -{ - -// Parses "_.jpg" or ".jpg" -> -// timestamp_ns: the digits after the stem's last '_', same rule as -// TrajectoryViewer.cpp's parseImageTsNs(). The all-digits check rejects -// unrelated .jpgs, which would reach std::stoll. -bool parseFrameTimestamp(const fs::path& path, int64_t& out_ts_ns) -{ - if (path.extension() != ".jpg") - return false; - std::string stem = path.stem().string(); - if (const auto us = stem.rfind('_'); us != std::string::npos) - stem = stem.substr(us + 1); - if (stem.empty() || stem.find_first_not_of("0123456789") != std::string::npos) - return false; - try + namespace { - out_ts_ns = std::stoll(stem); - return true; - } - catch (...) - { - return false; - } -} -// Nearest entry of frames[begin, end), sorted by timestamp_ns; -1 if -// outside max_gap_ns or the range is empty. -int nearestFrameIndex(const std::vector& frames, int begin, int end, int64_t ts_ns, int64_t max_gap_ns) -{ - if (begin >= end) - return -1; + // Parses "_.jpg" or ".jpg" -> + // timestamp_ns: the digits after the stem's last '_', same rule as + // TrajectoryViewer.cpp's parseImageTsNs(). The all-digits check rejects + // unrelated .jpgs, which would reach std::stoll. + bool parseFrameTimestamp(const fs::path& path, int64_t& out_ts_ns) + { + if (path.extension() != ".jpg") + return false; + std::string stem = path.stem().string(); + if (const auto us = stem.rfind('_'); us != std::string::npos) + stem = stem.substr(us + 1); + if (stem.empty() || stem.find_first_not_of("0123456789") != std::string::npos) + return false; + try + { + out_ts_ns = std::stoll(stem); + return true; + } catch (...) + { + return false; + } + } + + // Nearest entry of frames[begin, end), sorted by timestamp_ns; -1 if + // outside max_gap_ns or the range is empty. + int nearestFrameIndex(const std::vector& frames, int begin, int end, int64_t ts_ns, int64_t max_gap_ns) + { + if (begin >= end) + return -1; + + auto it = std::lower_bound( + frames.begin() + begin, + frames.begin() + end, + ts_ns, + [](const CameraFrame& f, int64_t ts) + { + return f.timestamp_ns < ts; + }); + + int best = -1; + int64_t best_diff = std::numeric_limits::max(); - auto it = std::lower_bound( - frames.begin() + begin, frames.begin() + end, ts_ns, [](const CameraFrame& f, int64_t ts) { return f.timestamp_ns < ts; }); + if (it != frames.begin() + end) + { + int idx = static_cast(it - frames.begin()); + int64_t diff = std::llabs(frames[idx].timestamp_ns - ts_ns); + if (diff < best_diff) + { + best_diff = diff; + best = idx; + } + } + if (it != frames.begin() + begin) + { + int idx = static_cast(it - frames.begin()) - 1; + int64_t diff = std::llabs(frames[idx].timestamp_ns - ts_ns); + if (diff < best_diff) + { + best_diff = diff; + best = idx; + } + } - int best = -1; - int64_t best_diff = std::numeric_limits::max(); + if (best >= 0 && best_diff <= max_gap_ns) + return best; + return -1; + } - if (it != frames.begin() + end) - { - int idx = static_cast(it - frames.begin()); - int64_t diff = std::llabs(frames[idx].timestamp_ns - ts_ns); - if (diff < best_diff) + // Reads an image, downscaled so its longer side is at most + // params.max_image_size_px; empty if it can't be read. + cv::Mat readImage(const std::string& image_path, int flags, const DetectorParams& params) { - best_diff = diff; - best = idx; + cv::Mat image = cv::imread(image_path, flags); + const int longer_side = std::max(image.cols, image.rows); + if (!image.empty() && params.max_image_size_px > 0 && longer_side > params.max_image_size_px) + { + const double scale = static_cast(params.max_image_size_px) / longer_side; + cv::resize(image, image, cv::Size(), scale, scale, cv::INTER_AREA); + } + return image; } - } - if (it != frames.begin() + begin) - { - int idx = static_cast(it - frames.begin()) - 1; - int64_t diff = std::llabs(frames[idx].timestamp_ns - ts_ns); - if (diff < best_diff) + + // Detects ORB features + computes the fbow descriptor for one representative + // frame. Returns false (leaving outputs untouched) if the image can't be + // loaded or has no descriptors. + bool detectAndTransform( + const std::string& image_path, + const DetectorParams& params, + cv::ORB& orb, + fbow::Vocabulary& vocabulary, + std::vector& out_keypoints, + cv::Mat& out_descriptors, + fbow::fBow& out_bow) { - best_diff = diff; - best = idx; + cv::Mat gray = readImage(image_path, cv::IMREAD_GRAYSCALE, params); + if (gray.empty()) + { + spdlog::warn("bow_loop_closure: could not read image '{}'", image_path); + return false; + } + out_keypoints.clear(); + orb.detectAndCompute(gray, cv::noArray(), out_keypoints, out_descriptors); + if (out_descriptors.empty()) + return false; + out_bow = vocabulary.transform(out_descriptors); + return true; } - } - if (best >= 0 && best_diff <= max_gap_ns) - return best; - return -1; -} + // Ratio-test ORB match + RANSAC fundamental matrix between two already- + // detected frames. Returns the inlier match count and (via out params) the + // matches actually kept as inliers, for drawing. + int verifyGeometry( + const std::vector& kp_i, + const cv::Mat& desc_i, + const std::vector& kp_j, + const cv::Mat& desc_j, + const DetectorParams& params, + std::vector& out_inlier_matches) + { + out_inlier_matches.clear(); + if (desc_i.empty() || desc_j.empty()) + return 0; -// Reads an image, downscaled so its longer side is at most -// params.max_image_size_px; empty if it can't be read. -cv::Mat readImage(const std::string& image_path, int flags, const DetectorParams& params) -{ - cv::Mat image = cv::imread(image_path, flags); - const int longer_side = std::max(image.cols, image.rows); - if (!image.empty() && params.max_image_size_px > 0 && longer_side > params.max_image_size_px) - { - const double scale = static_cast(params.max_image_size_px) / longer_side; - cv::resize(image, image, cv::Size(), scale, scale, cv::INTER_AREA); - } - return image; -} - -// Detects ORB features + computes the fbow descriptor for one representative -// frame. Returns false (leaving outputs untouched) if the image can't be -// loaded or has no descriptors. -bool detectAndTransform( - const std::string& image_path, - const DetectorParams& params, - cv::ORB& orb, - fbow::Vocabulary& vocabulary, - std::vector& out_keypoints, - cv::Mat& out_descriptors, - fbow::fBow& out_bow) -{ - cv::Mat gray = readImage(image_path, cv::IMREAD_GRAYSCALE, params); - if (gray.empty()) - { - spdlog::warn("bow_loop_closure: could not read image '{}'", image_path); - return false; - } - out_keypoints.clear(); - orb.detectAndCompute(gray, cv::noArray(), out_keypoints, out_descriptors); - if (out_descriptors.empty()) - return false; - out_bow = vocabulary.transform(out_descriptors); - return true; -} - -// Ratio-test ORB match + RANSAC fundamental matrix between two already- -// detected frames. Returns the inlier match count and (via out params) the -// matches actually kept as inliers, for drawing. -int verifyGeometry( - const std::vector& kp_i, - const cv::Mat& desc_i, - const std::vector& kp_j, - const cv::Mat& desc_j, - const DetectorParams& params, - std::vector& out_inlier_matches) -{ - out_inlier_matches.clear(); - if (desc_i.empty() || desc_j.empty()) - return 0; + cv::BFMatcher matcher(cv::NORM_HAMMING); + std::vector> knn_matches; + matcher.knnMatch(desc_i, desc_j, knn_matches, 2); - cv::BFMatcher matcher(cv::NORM_HAMMING); - std::vector> knn_matches; - matcher.knnMatch(desc_i, desc_j, knn_matches, 2); + std::vector good_matches; + for (const auto& m : knn_matches) + { + if (m.size() == 2 && m[0].distance < params.match_ratio_test * m[1].distance) + good_matches.push_back(m[0]); + } - std::vector good_matches; - for (const auto& m : knn_matches) - { - if (m.size() == 2 && m[0].distance < params.match_ratio_test * m[1].distance) - good_matches.push_back(m[0]); - } + if (good_matches.size() < 8) + return 0; - if (good_matches.size() < 8) - return 0; + std::vector pts_i, pts_j; + pts_i.reserve(good_matches.size()); + pts_j.reserve(good_matches.size()); + for (const auto& m : good_matches) + { + pts_i.push_back(kp_i[m.queryIdx].pt); + pts_j.push_back(kp_j[m.trainIdx].pt); + } - std::vector pts_i, pts_j; - pts_i.reserve(good_matches.size()); - pts_j.reserve(good_matches.size()); - for (const auto& m : good_matches) - { - pts_i.push_back(kp_i[m.queryIdx].pt); - pts_j.push_back(kp_j[m.trainIdx].pt); - } + std::vector inlier_mask; + cv::findFundamentalMat(pts_i, pts_j, cv::FM_RANSAC, params.ransac_reproj_threshold_px, params.ransac_confidence, inlier_mask); + + int inliers = 0; + for (size_t k = 0; k < good_matches.size(); k++) + { + if (k < inlier_mask.size() && inlier_mask[k]) + { + out_inlier_matches.push_back(good_matches[k]); + inliers++; + } + } + return inliers; + } - std::vector inlier_mask; - cv::findFundamentalMat( - pts_i, pts_j, cv::FM_RANSAC, params.ransac_reproj_threshold_px, params.ransac_confidence, inlier_mask); + } // namespace - int inliers = 0; - for (size_t k = 0; k < good_matches.size(); k++) + std::vector loadCameraFrames(const std::vector& camera_dirs) { - if (k < inlier_mask.size() && inlier_mask[k]) + std::vector frames; + + for (size_t camera = 0; camera < camera_dirs.size(); camera++) { - out_inlier_matches.push_back(good_matches[k]); - inliers++; - } - } - return inliers; -} + const std::string& dir = camera_dirs[camera]; + if (dir.empty() || !fs::is_directory(dir)) + { + spdlog::warn("bow_loop_closure: camera directory not found: '{}'", dir); + continue; + } -} // namespace + size_t loaded = 0; + for (const auto& entry : fs::directory_iterator(dir)) + { + int64_t ts_ns = 0; + if (!entry.is_regular_file() || !parseFrameTimestamp(entry.path(), ts_ns)) + continue; + frames.push_back(CameraFrame{ ts_ns, entry.path().string(), static_cast(camera) }); + loaded++; + } + spdlog::info("bow_loop_closure: loaded {} camera frames from '{}'", loaded, dir); + } -std::vector loadCameraFrames(const std::vector& camera_dirs) -{ - std::vector frames; + std::sort( + frames.begin(), + frames.end(), + [](const CameraFrame& a, const CameraFrame& b) + { + return a.camera != b.camera ? a.camera < b.camera : a.timestamp_ns < b.timestamp_ns; + }); + return frames; + } - for (size_t camera = 0; camera < camera_dirs.size(); camera++) + std::vector> associateFramesToChunks( + const PointClouds& point_clouds_container, const std::vector& frames, int64_t max_time_gap_ns) { - const std::string& dir = camera_dirs[camera]; - if (dir.empty() || !fs::is_directory(dir)) + const auto& chunks = point_clouds_container.point_clouds; + std::vector> chunk_frames(chunks.size()); + + // [begin, end) of each camera's frames; loadCameraFrames sorts by camera first. + std::vector> camera_ranges; + for (int k = 0; k < static_cast(frames.size()); k++) { - spdlog::warn("bow_loop_closure: camera directory not found: '{}'", dir); - continue; + if (k == 0 || frames[k].camera != frames[k - 1].camera) + camera_ranges.emplace_back(k, k); + camera_ranges.back().second = k + 1; } - size_t loaded = 0; - for (const auto& entry : fs::directory_iterator(dir)) + int matched = 0; + for (size_t i = 0; i < chunks.size(); i++) { - int64_t ts_ns = 0; - if (!entry.is_regular_file() || !parseFrameTimestamp(entry.path(), ts_ns)) + if (chunks[i].timestamps.empty()) continue; - frames.push_back(CameraFrame{ ts_ns, entry.path().string(), static_cast(camera) }); - loaded++; + int64_t chunk_ts_ns = static_cast(chunks[i].timestamps[0]); + for (const auto& [begin, end] : camera_ranges) + { + int idx = nearestFrameIndex(frames, begin, end, chunk_ts_ns, max_time_gap_ns); + if (idx >= 0) + chunk_frames[i].push_back(idx); + } + if (!chunk_frames[i].empty()) + matched++; } - spdlog::info("bow_loop_closure: loaded {} camera frames from '{}'", loaded, dir); - } - - std::sort( - frames.begin(), - frames.end(), - [](const CameraFrame& a, const CameraFrame& b) - { - return a.camera != b.camera ? a.camera < b.camera : a.timestamp_ns < b.timestamp_ns; - }); - return frames; -} -std::vector> associateFramesToChunks( - const PointClouds& point_clouds_container, const std::vector& frames, int64_t max_time_gap_ns) -{ - const auto& chunks = point_clouds_container.point_clouds; - std::vector> chunk_frames(chunks.size()); - - // [begin, end) of each camera's frames; loadCameraFrames sorts by camera first. - std::vector> camera_ranges; - for (int k = 0; k < static_cast(frames.size()); k++) - { - if (k == 0 || frames[k].camera != frames[k - 1].camera) - camera_ranges.emplace_back(k, k); - camera_ranges.back().second = k + 1; + spdlog::info( + "bow_loop_closure: associated {}/{} chunks with a frame of {} camera(s)", matched, chunks.size(), camera_ranges.size()); + return chunk_frames; } - int matched = 0; - for (size_t i = 0; i < chunks.size(); i++) + std::string defaultVocabularyPath() { - if (chunks[i].timestamps.empty()) - continue; - int64_t chunk_ts_ns = static_cast(chunks[i].timestamps[0]); - for (const auto& [begin, end] : camera_ranges) - { - int idx = nearestFrameIndex(frames, begin, end, chunk_ts_ns, max_time_gap_ns); - if (idx >= 0) - chunk_frames[i].push_back(idx); - } - if (!chunk_frames[i].empty()) - matched++; - } - - spdlog::info( - "bow_loop_closure: associated {}/{} chunks with a frame of {} camera(s)", matched, chunks.size(), camera_ranges.size()); - return chunk_frames; -} - -std::string defaultVocabularyPath() -{ #ifdef FBOW_VOCABULARY_PATH - return FBOW_VOCABULARY_PATH; + return FBOW_VOCABULARY_PATH; #else - return ""; + return ""; #endif -} - -fbow::Vocabulary loadVocabulary(const std::string& vocabulary_path) -{ - fbow::Vocabulary vocabulary; - if (vocabulary_path.empty() || !fs::exists(vocabulary_path)) - throw std::runtime_error("bow_loop_closure: vocabulary file not found: '" + vocabulary_path + "'"); - vocabulary.readFromFile(vocabulary_path); - if (!vocabulary.isValid()) - throw std::runtime_error("bow_loop_closure: failed to load vocabulary from '" + vocabulary_path + "'"); - return vocabulary; -} - -std::vector detectCandidates( - const PointClouds& point_clouds_container, - const std::vector& frames, - const std::vector>& chunk_frames, - const DetectorParams& params, - fbow::Vocabulary& vocabulary) -{ - std::vector candidates; - const auto& chunks = point_clouds_container.point_clouds; - const size_t n = chunks.size(); - if (n == 0 || chunk_frames.size() != n) - return candidates; + } - // Cumulative trajectory arc-length from consecutive chunk poses. - std::vector arc_length(n, 0.0); - for (size_t i = 1; i < n; i++) + fbow::Vocabulary loadVocabulary(const std::string& vocabulary_path) { - double d = (chunks[i].m_pose.translation() - chunks[i - 1].m_pose.translation()).norm(); - arc_length[i] = arc_length[i - 1] + d; + fbow::Vocabulary vocabulary; + if (vocabulary_path.empty() || !fs::exists(vocabulary_path)) + throw std::runtime_error("bow_loop_closure: vocabulary file not found: '" + vocabulary_path + "'"); + vocabulary.readFromFile(vocabulary_path); + if (!vocabulary.isValid()) + throw std::runtime_error("bow_loop_closure: failed to load vocabulary from '" + vocabulary_path + "'"); + return vocabulary; } - // Precompute ORB keypoints/descriptors/BoW once per frame some chunk is - // associated with (reused below for both the appearance score and the - // geometric verification, within this one detectCandidates call). - const size_t m = frames.size(); - std::vector> keypoints_by_frame(m); - std::vector descriptors_by_frame(m); - std::vector bow_by_frame(m); - std::vector has_bow(m, false); - - cv::Ptr orb = cv::ORB::create(params.orb_features); - for (const auto& frame_list : chunk_frames) + std::vector detectCandidates( + const PointClouds& point_clouds_container, + const std::vector& frames, + const std::vector>& chunk_frames, + const DetectorParams& params, + fbow::Vocabulary& vocabulary) { - for (const int f : frame_list) + std::vector candidates; + const auto& chunks = point_clouds_container.point_clouds; + const size_t n = chunks.size(); + if (n == 0 || chunk_frames.size() != n) + return candidates; + + // Cumulative trajectory arc-length from consecutive chunk poses. + std::vector arc_length(n, 0.0); + for (size_t i = 1; i < n; i++) { - if (f < 0 || f >= static_cast(m) || has_bow[f]) - continue; - has_bow[f] = detectAndTransform( - frames[f].file_path, params, *orb, vocabulary, keypoints_by_frame[f], descriptors_by_frame[f], bow_by_frame[f]); + double d = (chunks[i].m_pose.translation() - chunks[i - 1].m_pose.translation()).norm(); + arc_length[i] = arc_length[i - 1] + d; } - } - auto has_any_bow = [&](size_t chunk) - { - return std::any_of(chunk_frames[chunk].begin(), chunk_frames[chunk].end(), [&](int f) { return has_bow[f]; }); - }; - for (size_t i = 0; i < n; i++) - { - if (!has_any_bow(i)) - continue; - for (size_t j = i + 1; j < n; j++) + // Precompute ORB keypoints/descriptors/BoW once per frame some chunk is + // associated with (reused below for both the appearance score and the + // geometric verification, within this one detectCandidates call). + const size_t m = frames.size(); + std::vector> keypoints_by_frame(m); + std::vector descriptors_by_frame(m); + std::vector bow_by_frame(m); + std::vector has_bow(m, false); + + cv::Ptr orb = cv::ORB::create(params.orb_features); + for (const auto& frame_list : chunk_frames) { - if (!has_any_bow(j)) - continue; - - // Stage 1: pose-gate. - double arc_gap = arc_length[j] - arc_length[i]; - if (arc_gap < params.min_arc_gap_m) - continue; + for (const int f : frame_list) + { + if (f < 0 || f >= static_cast(m) || has_bow[f]) + continue; + has_bow[f] = detectAndTransform( + frames[f].file_path, params, *orb, vocabulary, keypoints_by_frame[f], descriptors_by_frame[f], bow_by_frame[f]); + } + } + auto has_any_bow = [&](size_t chunk) + { + return std::any_of( + chunk_frames[chunk].begin(), + chunk_frames[chunk].end(), + [&](int f) + { + return has_bow[f]; + }); + }; - Eigen::Vector3d ti = chunks[i].m_pose.translation(); - Eigen::Vector3d tj = chunks[j].m_pose.translation(); - double xy_dist = std::hypot(tj.x() - ti.x(), tj.y() - ti.y()); - if (xy_dist > params.max_xy_dist_m) + for (size_t i = 0; i < n; i++) + { + if (!has_any_bow(i)) continue; - - // Stages 2 and 3 for every camera pair of the two chunks; the pair - // with the most inliers wins. - Candidate best; - for (const int fi : chunk_frames[i]) + for (size_t j = i + 1; j < n; j++) { - for (const int fj : chunk_frames[j]) + if (!has_any_bow(j)) + continue; + + // Stage 1: pose-gate. + double arc_gap = arc_length[j] - arc_length[i]; + if (arc_gap < params.min_arc_gap_m) + continue; + + Eigen::Vector3d ti = chunks[i].m_pose.translation(); + Eigen::Vector3d tj = chunks[j].m_pose.translation(); + double xy_dist = std::hypot(tj.x() - ti.x(), tj.y() - ti.y()); + if (xy_dist > params.max_xy_dist_m) + continue; + + // Stages 2 and 3 for every camera pair of the two chunks; the pair + // with the most inliers wins. + Candidate best; + for (const int fi : chunk_frames[i]) { - if (!has_bow[fi] || !has_bow[fj]) - continue; - - // Stage 2: appearance pre-filter. - double score = fbow::fBow::score(bow_by_frame[fi], bow_by_frame[fj]); - if (score < params.min_bow_score) - continue; - - // Stage 3: geometric verification. - std::vector inlier_matches; - int inliers = verifyGeometry( - keypoints_by_frame[fi], descriptors_by_frame[fi], keypoints_by_frame[fj], descriptors_by_frame[fj], params, inlier_matches); - if (inliers < params.min_inliers || inliers <= best.inliers) - continue; - - best.frame_i = fi; - best.frame_j = fj; - best.bow_score = score; - best.inliers = inliers; + for (const int fj : chunk_frames[j]) + { + if (!has_bow[fi] || !has_bow[fj]) + continue; + + // Stage 2: appearance pre-filter. + double score = fbow::fBow::score(bow_by_frame[fi], bow_by_frame[fj]); + if (score < params.min_bow_score) + continue; + + // Stage 3: geometric verification. + std::vector inlier_matches; + int inliers = verifyGeometry( + keypoints_by_frame[fi], + descriptors_by_frame[fi], + keypoints_by_frame[fj], + descriptors_by_frame[fj], + params, + inlier_matches); + if (inliers < params.min_inliers || inliers <= best.inliers) + continue; + + best.frame_i = fi; + best.frame_j = fj; + best.bow_score = score; + best.inliers = inliers; + } } + if (best.frame_i < 0) + continue; + + best.index_i = static_cast(i); + best.index_j = static_cast(j); + best.xy_dist_m = xy_dist; + best.arc_gap_m = arc_gap; + candidates.push_back(best); } - if (best.frame_i < 0) - continue; - - best.index_i = static_cast(i); - best.index_j = static_cast(j); - best.xy_dist_m = xy_dist; - best.arc_gap_m = arc_gap; - candidates.push_back(best); } - } - std::sort(candidates.begin(), candidates.end(), [](const Candidate& a, const Candidate& b) { return a.inliers > b.inliers; }); + std::sort( + candidates.begin(), + candidates.end(), + [](const Candidate& a, const Candidate& b) + { + return a.inliers > b.inliers; + }); - spdlog::info("bow_loop_closure: {} candidates passed pose-gate + appearance + geometric verification", candidates.size()); - return candidates; -} + spdlog::info("bow_loop_closure: {} candidates passed pose-gate + appearance + geometric verification", candidates.size()); + return candidates; + } -cv::Mat buildCandidateMontage(const Candidate& candidate, const std::vector& frames, const DetectorParams& params) -{ - const int frame_i = candidate.frame_i; - const int frame_j = candidate.frame_j; - if (frame_i < 0 || frame_j < 0 || frame_i >= static_cast(frames.size()) || frame_j >= static_cast(frames.size())) - return cv::Mat(); - - cv::Mat color_i = readImage(frames[frame_i].file_path, cv::IMREAD_COLOR, params); - cv::Mat color_j = readImage(frames[frame_j].file_path, cv::IMREAD_COLOR, params); - if (color_i.empty() || color_j.empty()) - return cv::Mat(); - - cv::Mat gray_i, gray_j; - cv::cvtColor(color_i, gray_i, cv::COLOR_BGR2GRAY); - cv::cvtColor(color_j, gray_j, cv::COLOR_BGR2GRAY); - - cv::Ptr orb = cv::ORB::create(params.orb_features); - std::vector kp_i, kp_j; - cv::Mat desc_i, desc_j; - orb->detectAndCompute(gray_i, cv::noArray(), kp_i, desc_i); - orb->detectAndCompute(gray_j, cv::noArray(), kp_j, desc_j); - - std::vector inlier_matches; - verifyGeometry(kp_i, desc_i, kp_j, desc_j, params, inlier_matches); - - cv::Mat montage; - cv::drawMatches( - color_i, - kp_i, - color_j, - kp_j, - inlier_matches, - montage, - cv::Scalar(0, 255, 0), - cv::Scalar(0, 0, 255), - std::vector(), - cv::DrawMatchesFlags::NOT_DRAW_SINGLE_POINTS); - return montage; -} + cv::Mat buildCandidateMontage(const Candidate& candidate, const std::vector& frames, const DetectorParams& params) + { + const int frame_i = candidate.frame_i; + const int frame_j = candidate.frame_j; + if (frame_i < 0 || frame_j < 0 || frame_i >= static_cast(frames.size()) || frame_j >= static_cast(frames.size())) + return cv::Mat(); + + cv::Mat color_i = readImage(frames[frame_i].file_path, cv::IMREAD_COLOR, params); + cv::Mat color_j = readImage(frames[frame_j].file_path, cv::IMREAD_COLOR, params); + if (color_i.empty() || color_j.empty()) + return cv::Mat(); + + cv::Mat gray_i, gray_j; + cv::cvtColor(color_i, gray_i, cv::COLOR_BGR2GRAY); + cv::cvtColor(color_j, gray_j, cv::COLOR_BGR2GRAY); + + cv::Ptr orb = cv::ORB::create(params.orb_features); + std::vector kp_i, kp_j; + cv::Mat desc_i, desc_j; + orb->detectAndCompute(gray_i, cv::noArray(), kp_i, desc_i); + orb->detectAndCompute(gray_j, cv::noArray(), kp_j, desc_j); + + std::vector inlier_matches; + verifyGeometry(kp_i, desc_i, kp_j, desc_j, params, inlier_matches); + + cv::Mat montage; + cv::drawMatches( + color_i, + kp_i, + color_j, + kp_j, + inlier_matches, + montage, + cv::Scalar(0, 255, 0), + cv::Scalar(0, 0, 255), + std::vector(), + cv::DrawMatchesFlags::NOT_DRAW_SINGLE_POINTS); + return montage; + } } // namespace bow_loop_closure diff --git a/apps/multi_view_tls_registration/bow_loop_closure_detector.h b/apps/multi_view_tls_registration/bow_loop_closure_detector.h index 86df337a0..9f32149dc 100644 --- a/apps/multi_view_tls_registration/bow_loop_closure_detector.h +++ b/apps/multi_view_tls_registration/bow_loop_closure_detector.h @@ -29,106 +29,106 @@ class PointClouds; namespace bow_loop_closure { -// One camera frame: `_.jpg` or `.jpg` -// (mandeye's cam0_.jpg, Insta360 front_.jpg / back_.jpg), timestamp -// on the same clock as the LiDAR/IMU (same name rule as TrajectoryViewer.cpp's -// parseImageTsNs()). -struct CameraFrame -{ - int64_t timestamp_ns = 0; - std::string file_path; - int camera = 0; //!< index of its folder in loadCameraFrames' camera_dirs -}; - -struct DetectorParams -{ - // Stage 1 (pose-gate): keep chunk pairs far apart along the trajectory - // arc-length but close in XY -- mirrors the standalone prototype's - // --lc-min-arc-gap / --lc-max-xy-dist, computed here from poses already - // in memory instead of a CSV sidecar. - double min_arc_gap_m = 40.0; - double max_xy_dist_m = 15.0; - - // Stage 2 (appearance pre-filter): fbow::fBow::score threshold. A cheap - // pre-filter only: on a warehouse walk (mandeye CAMERA_0 and Insta360 - // front/back) the score barely separates revisits from far-apart pairs - // (median 0.006-0.011 vs 0.004-0.006), and 0.02 kept fewer than 1 in 10 - // revisits. The inlier count below is what tells them apart. - double min_bow_score = 0.005; - - // Stage 3 (geometric verification): ORB ratio-test match + RANSAC - // fundamental matrix. - int orb_features = 2000; - float match_ratio_test = 0.75f; - double ransac_reproj_threshold_px = 3.0; - double ransac_confidence = 0.99; - // Pairs more than 30 m apart (certainly not the same view) reach up to - // ~28 inliers by chance on the same walk. - int min_inliers = 30; - - // Images whose longer side exceeds this are downscaled to it before ORB - // (0 = full resolution). Halving the Insta360 X5's 3840 px lens images - // finds more revisits with fewer chance inliers, and twice as fast. - int max_image_size_px = 1920; - - // Chunk<->camera-frame association tolerance (nearest-timestamp match). - int64_t max_frame_time_gap_ns = 500000000; // 0.5 s -}; - -struct Candidate -{ - int index_i = -1; - int index_j = -1; - int frame_i = -1; //!< frames[] entry of chunk index_i that matched (the best camera pair) - int frame_j = -1; //!< frames[] entry of chunk index_j that matched - double xy_dist_m = 0.0; - double arc_gap_m = 0.0; - double bow_score = 0.0; - int inliers = 0; -}; - -// Scans every folder in `camera_dirs` (one per camera, e.g. an Insta360's -// cam_front and cam_back) for `_.jpg` files. Returns -// them sorted by camera, then timestamp ascending. -std::vector loadCameraFrames(const std::vector& camera_dirs); - -// For each chunk in `point_clouds_container`, finds every camera's -// nearest-timestamp frame in `frames` (sorted as loadCameraFrames returns -// them). Returns one list of frame indices per chunk (same size as -// point_clouds_container.point_clouds), at most one per camera; a camera with -// no frame within `max_time_gap_ns` is left out, and a chunk with no -// per-point timestamp loaded gets an empty list. -std::vector> associateFramesToChunks( - const PointClouds& point_clouds_container, const std::vector& frames, int64_t max_time_gap_ns); - -// Absolute path to the fbow ORB vocabulary bundled with this build -// (3rdparty/fbow/vocabularies/orb_mur.fbow), baked in at configure time via -// the FBOW_VOCABULARY_PATH compile definition. This is a source-tree path, -// fine for local/dev builds; a packaged install would instead want to copy -// the file next to the binary and resolve it relative to argv[0]. -std::string defaultVocabularyPath(); - -// Throws std::runtime_error if the vocabulary file can't be read. -fbow::Vocabulary loadVocabulary(const std::string& vocabulary_path); - -// Runs the full pose-gate -> appearance-filter -> geometric-verification -// pipeline. `chunk_frames` is associateFramesToChunks()'s output. With several -// cameras, every camera pair of a chunk pair is tried (front vs back too, which -// finds a place revisited facing the other way) and the pair with the most -// inliers is kept. Returns surviving candidates sorted by inlier count -// descending. -std::vector detectCandidates( - const PointClouds& point_clouds_container, - const std::vector& frames, - const std::vector>& chunk_frames, - const DetectorParams& params, - fbow::Vocabulary& vocabulary); - -// Re-runs ORB detect + ratio-test match + RANSAC for one candidate's frame -// pair (independent of detectCandidates' internal per-run cache) and draws the -// inlier correspondences on a side-by-side image pair, for visual review -// before adding an edge. Returns an empty cv::Mat if either frame can't be -// loaded/matched. -cv::Mat buildCandidateMontage(const Candidate& candidate, const std::vector& frames, const DetectorParams& params); + // One camera frame: `_.jpg` or `.jpg` + // (mandeye's cam0_.jpg, Insta360 front_.jpg / back_.jpg), timestamp + // on the same clock as the LiDAR/IMU (same name rule as TrajectoryViewer.cpp's + // parseImageTsNs()). + struct CameraFrame + { + int64_t timestamp_ns = 0; + std::string file_path; + int camera = 0; //!< index of its folder in loadCameraFrames' camera_dirs + }; + + struct DetectorParams + { + // Stage 1 (pose-gate): keep chunk pairs far apart along the trajectory + // arc-length but close in XY -- mirrors the standalone prototype's + // --lc-min-arc-gap / --lc-max-xy-dist, computed here from poses already + // in memory instead of a CSV sidecar. + double min_arc_gap_m = 40.0; + double max_xy_dist_m = 15.0; + + // Stage 2 (appearance pre-filter): fbow::fBow::score threshold. A cheap + // pre-filter only: on a warehouse walk (mandeye CAMERA_0 and Insta360 + // front/back) the score barely separates revisits from far-apart pairs + // (median 0.006-0.011 vs 0.004-0.006), and 0.02 kept fewer than 1 in 10 + // revisits. The inlier count below is what tells them apart. + double min_bow_score = 0.005; + + // Stage 3 (geometric verification): ORB ratio-test match + RANSAC + // fundamental matrix. + int orb_features = 2000; + float match_ratio_test = 0.75f; + double ransac_reproj_threshold_px = 3.0; + double ransac_confidence = 0.99; + // Pairs more than 30 m apart (certainly not the same view) reach up to + // ~28 inliers by chance on the same walk. + int min_inliers = 30; + + // Images whose longer side exceeds this are downscaled to it before ORB + // (0 = full resolution). Halving the Insta360 X5's 3840 px lens images + // finds more revisits with fewer chance inliers, and twice as fast. + int max_image_size_px = 1920; + + // Chunk<->camera-frame association tolerance (nearest-timestamp match). + int64_t max_frame_time_gap_ns = 500000000; // 0.5 s + }; + + struct Candidate + { + int index_i = -1; + int index_j = -1; + int frame_i = -1; //!< frames[] entry of chunk index_i that matched (the best camera pair) + int frame_j = -1; //!< frames[] entry of chunk index_j that matched + double xy_dist_m = 0.0; + double arc_gap_m = 0.0; + double bow_score = 0.0; + int inliers = 0; + }; + + // Scans every folder in `camera_dirs` (one per camera, e.g. an Insta360's + // cam_front and cam_back) for `_.jpg` files. Returns + // them sorted by camera, then timestamp ascending. + std::vector loadCameraFrames(const std::vector& camera_dirs); + + // For each chunk in `point_clouds_container`, finds every camera's + // nearest-timestamp frame in `frames` (sorted as loadCameraFrames returns + // them). Returns one list of frame indices per chunk (same size as + // point_clouds_container.point_clouds), at most one per camera; a camera with + // no frame within `max_time_gap_ns` is left out, and a chunk with no + // per-point timestamp loaded gets an empty list. + std::vector> associateFramesToChunks( + const PointClouds& point_clouds_container, const std::vector& frames, int64_t max_time_gap_ns); + + // Absolute path to the fbow ORB vocabulary bundled with this build + // (3rdparty/fbow/vocabularies/orb_mur.fbow), baked in at configure time via + // the FBOW_VOCABULARY_PATH compile definition. This is a source-tree path, + // fine for local/dev builds; a packaged install would instead want to copy + // the file next to the binary and resolve it relative to argv[0]. + std::string defaultVocabularyPath(); + + // Throws std::runtime_error if the vocabulary file can't be read. + fbow::Vocabulary loadVocabulary(const std::string& vocabulary_path); + + // Runs the full pose-gate -> appearance-filter -> geometric-verification + // pipeline. `chunk_frames` is associateFramesToChunks()'s output. With several + // cameras, every camera pair of a chunk pair is tried (front vs back too, which + // finds a place revisited facing the other way) and the pair with the most + // inliers is kept. Returns surviving candidates sorted by inlier count + // descending. + std::vector detectCandidates( + const PointClouds& point_clouds_container, + const std::vector& frames, + const std::vector>& chunk_frames, + const DetectorParams& params, + fbow::Vocabulary& vocabulary); + + // Re-runs ORB detect + ratio-test match + RANSAC for one candidate's frame + // pair (independent of detectCandidates' internal per-run cache) and draws the + // inlier correspondences on a side-by-side image pair, for visual review + // before adding an edge. Returns an empty cv::Mat if either frame can't be + // loaded/matched. + cv::Mat buildCandidateMontage(const Candidate& candidate, const std::vector& frames, const DetectorParams& params); } // namespace bow_loop_closure diff --git a/apps/multi_view_tls_registration/multi_view_tls_registration_gui.cpp b/apps/multi_view_tls_registration/multi_view_tls_registration_gui.cpp index f34e411ac..c76c2f484 100644 --- a/apps/multi_view_tls_registration/multi_view_tls_registration_gui.cpp +++ b/apps/multi_view_tls_registration/multi_view_tls_registration_gui.cpp @@ -1966,140 +1966,139 @@ void observation_picking_gui() // background image work. namespace { -struct BowLoopClosureState -{ - //! One row per camera folder (CAMERA_0, or an Insta360's cam_front and cam_back); empty rows are skipped. - std::vector> camera_dirs = std::vector>(1); - bow_loop_closure::DetectorParams params; - - std::atomic detecting{ false }; - std::thread detect_thread; - - std::mutex results_mutex; - std::vector results; - std::vector frames; - std::vector camera_names; //!< folder name per CameraFrame::camera - std::string status; - - int selected_candidate = -1; - bool scroll_to_selected = false; //!< scroll the list to selected_candidate on the next frame - bool window_focused = false; //!< the BoW window had focus last frame, see bow_preview_takes_edge_hotkeys() - Texture2D montage_tex{}; - bool montage_tex_valid = false; -}; -BowLoopClosureState bow_state; - -void bow_loop_closure_start_detection() -{ - if (bow_state.detecting.load()) - return; - if (bow_state.detect_thread.joinable()) - bow_state.detect_thread.join(); + struct BowLoopClosureState + { + //! One row per camera folder (CAMERA_0, or an Insta360's cam_front and cam_back); empty rows are skipped. + std::vector> camera_dirs = std::vector>(1); + bow_loop_closure::DetectorParams params; + + std::atomic detecting{ false }; + std::thread detect_thread; + + std::mutex results_mutex; + std::vector results; + std::vector frames; + std::vector camera_names; //!< folder name per CameraFrame::camera + std::string status; + + int selected_candidate = -1; + bool scroll_to_selected = false; //!< scroll the list to selected_candidate on the next frame + bool window_focused = false; //!< the BoW window had focus last frame, see bow_preview_takes_edge_hotkeys() + Texture2D montage_tex{}; + bool montage_tex_valid = false; + }; + BowLoopClosureState bow_state; - bow_state.detecting = true; + void bow_loop_closure_start_detection() { - std::lock_guard lk(bow_state.results_mutex); - bow_state.status = "Detecting..."; - bow_state.results.clear(); - bow_state.selected_candidate = -1; - } + if (bow_state.detecting.load()) + return; + if (bow_state.detect_thread.joinable()) + bow_state.detect_thread.join(); - std::vector camera_dirs; - std::vector camera_names; - for (const auto& dir : bow_state.camera_dirs) - { - if (dir[0] == '\0') - continue; - camera_dirs.emplace_back(dir.data()); - std::filesystem::path path(camera_dirs.back()); - if (!path.has_filename()) - path = path.parent_path(); // ".../cam_front/" - camera_names.push_back(path.filename().string()); - } - bow_loop_closure::DetectorParams params = bow_state.params; + bow_state.detecting = true; + { + std::lock_guard lk(bow_state.results_mutex); + bow_state.status = "Detecting..."; + bow_state.results.clear(); + bow_state.selected_candidate = -1; + } - bow_state.detect_thread = std::thread( - [camera_dirs, camera_names, params]() + std::vector camera_dirs; + std::vector camera_names; + for (const auto& dir : bow_state.camera_dirs) { - auto frames = bow_loop_closure::loadCameraFrames(camera_dirs); - std::vector candidates; - std::string status; + if (dir[0] == '\0') + continue; + camera_dirs.emplace_back(dir.data()); + std::filesystem::path path(camera_dirs.back()); + if (!path.has_filename()) + path = path.parent_path(); // ".../cam_front/" + camera_names.push_back(path.filename().string()); + } + bow_loop_closure::DetectorParams params = bow_state.params; - if (frames.empty()) - { - status = "No camera frames found in the camera folders"; - } - else + bow_state.detect_thread = std::thread( + [camera_dirs, camera_names, params]() { - auto chunk_frames = - bow_loop_closure::associateFramesToChunks(session.point_clouds_container, frames, params.max_frame_time_gap_ns); - try + auto frames = bow_loop_closure::loadCameraFrames(camera_dirs); + std::vector candidates; + std::string status; + + if (frames.empty()) { - auto vocabulary = bow_loop_closure::loadVocabulary(bow_loop_closure::defaultVocabularyPath()); - candidates = - bow_loop_closure::detectCandidates(session.point_clouds_container, frames, chunk_frames, params, vocabulary); - status = std::to_string(candidates.size()) + " candidates found"; + status = "No camera frames found in the camera folders"; } - catch (const std::exception& e) + else { - status = e.what(); + auto chunk_frames = + bow_loop_closure::associateFramesToChunks(session.point_clouds_container, frames, params.max_frame_time_gap_ns); + try + { + auto vocabulary = bow_loop_closure::loadVocabulary(bow_loop_closure::defaultVocabularyPath()); + candidates = + bow_loop_closure::detectCandidates(session.point_clouds_container, frames, chunk_frames, params, vocabulary); + status = std::to_string(candidates.size()) + " candidates found"; + } catch (const std::exception& e) + { + status = e.what(); + } } - } - std::lock_guard lk(bow_state.results_mutex); - bow_state.frames = std::move(frames); - bow_state.camera_names = camera_names; - bow_state.results = std::move(candidates); - bow_state.status = status; - bow_state.detecting = false; - }); -} + std::lock_guard lk(bow_state.results_mutex); + bow_state.frames = std::move(frames); + bow_state.camera_names = camera_names; + bow_state.results = std::move(candidates); + bow_state.status = status; + bow_state.detecting = false; + }); + } -// Uploads `mat` (BGR, as cv::imread/drawMatches produce) as the montage -// preview texture -- same LoadTextureFromImage/UnloadTexture pattern as -// TrajectoryViewer.cpp's imgViewTex. -void bow_loop_closure_upload_montage(cv::Mat mat) -{ - if (mat.empty()) - return; - cv::cvtColor(mat, mat, cv::COLOR_BGR2RGB); - if (!mat.isContinuous()) - mat = mat.clone(); + // Uploads `mat` (BGR, as cv::imread/drawMatches produce) as the montage + // preview texture -- same LoadTextureFromImage/UnloadTexture pattern as + // TrajectoryViewer.cpp's imgViewTex. + void bow_loop_closure_upload_montage(cv::Mat mat) + { + if (mat.empty()) + return; + cv::cvtColor(mat, mat, cv::COLOR_BGR2RGB); + if (!mat.isContinuous()) + mat = mat.clone(); - if (bow_state.montage_tex_valid) - UnloadTexture(bow_state.montage_tex); - Image ri = { mat.data, mat.cols, mat.rows, 1, PIXELFORMAT_UNCOMPRESSED_R8G8B8 }; - bow_state.montage_tex = LoadTextureFromImage(ri); - bow_state.montage_tex_valid = bow_state.montage_tex.id > 0; -} + if (bow_state.montage_tex_valid) + UnloadTexture(bow_state.montage_tex); + Image ri = { mat.data, mat.cols, mat.rows, 1, PIXELFORMAT_UNCOMPRESSED_R8G8B8 }; + bow_state.montage_tex = LoadTextureFromImage(ri); + bow_state.montage_tex_valid = bow_state.montage_tex.id > 0; + } -// Shows results[row] in the montage preview. -void bow_loop_closure_show_candidate(const std::vector& results, int row) -{ - bow_state.selected_candidate = row; - std::lock_guard lk(bow_state.results_mutex); - cv::Mat montage = bow_loop_closure::buildCandidateMontage(results[row], bow_state.frames, bow_state.params); - bow_loop_closure_upload_montage(montage); -} + // Shows results[row] in the montage preview. + void bow_loop_closure_show_candidate(const std::vector& results, int row) + { + bow_state.selected_candidate = row; + std::lock_guard lk(bow_state.results_mutex); + cv::Mat montage = bow_loop_closure::buildCandidateMontage(results[row], bow_state.frames, bow_state.params); + bow_loop_closure_upload_montage(montage); + } -void bow_loop_closure_clear_preview() -{ - bow_state.selected_candidate = -1; - if (bow_state.montage_tex_valid) - UnloadTexture(bow_state.montage_tex); - bow_state.montage_tex_valid = false; -} + void bow_loop_closure_clear_preview() + { + bow_state.selected_candidate = -1; + if (bow_state.montage_tex_valid) + UnloadTexture(bow_state.montage_tex); + bow_state.montage_tex_valid = false; + } -// N / P step the BoW candidates instead of the manual loop closure's active edge while a candidate is -// shown and either the BoW window has focus or the active edge list is not shown. -bool bow_preview_takes_edge_hotkeys() -{ - if (!is_bow_loop_closure_gui || bow_state.selected_candidate < 0) - return false; - const auto& loop_closure = session.pose_graph_loop_closure; - const bool active_edges_shown = is_loop_closure_gui && loop_closure.manipulate_active_edge && !loop_closure.edges.empty(); - return bow_state.window_focused || !active_edges_shown; -} + // N / P step the BoW candidates instead of the manual loop closure's active edge while a candidate is + // shown and either the BoW window has focus or the active edge list is not shown. + bool bow_preview_takes_edge_hotkeys() + { + if (!is_bow_loop_closure_gui || bow_state.selected_candidate < 0) + return false; + const auto& loop_closure = session.pose_graph_loop_closure; + const bool active_edges_shown = is_loop_closure_gui && loop_closure.manipulate_active_edge && !loop_closure.edges.empty(); + return bow_state.window_focused || !active_edges_shown; + } } // namespace void bow_loop_closure_gui() @@ -2307,8 +2306,7 @@ void bow_loop_closure_gui() { const auto& c = results_copy[selected]; std::string default_name = "cand_" + std::to_string(c.index_i) + "_" + std::to_string(c.index_j) + ".png"; - std::string out_file = - mandeye::fd::SaveFileDialog("Save montage", { "PNG image (*.png)", "*.png" }, ".png", default_name); + std::string out_file = mandeye::fd::SaveFileDialog("Save montage", { "PNG image (*.png)", "*.png" }, ".png", default_name); if (!out_file.empty()) { std::lock_guard lk(bow_state.results_mutex); From bbe49d98a9fe426d0d12cf52dc2dda87b34f4979 Mon Sep 17 00:00:00 2001 From: Michal Pelka Date: Wed, 11 Nov 2026 02:35:09 +0100 Subject: [PATCH 6/9] PairWiseICP: run the blocks with TBB, multithreaded on macOS too std::execution::par_unseq is compiled out with AppleClang (USE_EXECUTION_PAR_UNSEQ=0), so ICP ran on one core on macOS. The 256 blocks now go through tbb::parallel_for_each; block sums are still added in a fixed order, so results are unchanged. core_math links TBB so it compiles against the bundled oneTBB headers, not Homebrew's (2023.2 vs bundled 2022.3). Synthetic bench (300k target / 150k source, radii 1.0/0.5/0.25 m, 30 it., M-series Mac): 14.2 s -> 2.5 s, poses identical to 12 decimals. Signed-off-by: Michal Pelka Co-Authored-By: Claude Opus 5.5 --- apps/camera_lidar_calibration/App.cpp | 15 ++++------ core/CMakeLists.txt | 2 +- .../src/pair_wise_iterative_closest_point.cpp | 11 +++---- core/tests/test_pair_wise_icp.cpp | 30 ++++++++++++++----- 4 files changed, 32 insertions(+), 26 deletions(-) diff --git a/apps/camera_lidar_calibration/App.cpp b/apps/camera_lidar_calibration/App.cpp index c5b3ab3c9..cf388be10 100644 --- a/apps/camera_lidar_calibration/App.cpp +++ b/apps/camera_lidar_calibration/App.cpp @@ -36,17 +36,12 @@ void AppState::rebuildImageTexture() // directly to the raw image (see Renderer.cpp/RendererShaders.h). if (intrinsicsLoaded && intrinsics.model == CameraModel::Pinhole) { - cv::Mat K = (cv::Mat_(3, 3) << intrinsics.fx, 0, intrinsics.cx, 0, intrinsics.fy, intrinsics.cy, 0, 0, 1); + // cv::Matx rather than the Mat_ comma initializer, which OpenCV 5 rejects for float values. + cv::Mat K(cv::Matx33d(intrinsics.fx, 0, intrinsics.cx, 0, intrinsics.fy, intrinsics.cy, 0, 0, 1)); // OpenCV distCoeffs order: k1 k2 p1 p2 k3 k4 k5 k6 (rational model) - cv::Mat D = - (cv::Mat_(1, 8) << intrinsics.k1, - intrinsics.k2, - intrinsics.p1, - intrinsics.p2, - intrinsics.k3, - intrinsics.k4, - intrinsics.k5, - intrinsics.k6); + cv::Mat D( + cv::Matx( + intrinsics.k1, intrinsics.k2, intrinsics.p1, intrinsics.p2, intrinsics.k3, intrinsics.k4, intrinsics.k5, intrinsics.k6)); cv::Mat map1, map2; cv::initUndistortRectifyMap(K, D, cv::Mat(), K, originalImage.size(), CV_16SC2, map1, map2); diff --git a/core/CMakeLists.txt b/core/CMakeLists.txt index 126b2ff2c..af2de4f90 100644 --- a/core/CMakeLists.txt +++ b/core/CMakeLists.txt @@ -36,7 +36,7 @@ set(CORE_MATH_SOURCES add_library(core_math STATIC ${CORE_MATH_SOURCES}) target_compile_definitions(core_math PRIVATE WITH_GUI=0) -target_link_libraries(core_math PRIVATE PROJ::proj spdlog::spdlog vqf Fusion wgs84_do_puwg92 plycpp WGS84toCartesian) +target_link_libraries(core_math PRIVATE PROJ::proj spdlog::spdlog vqf Fusion wgs84_do_puwg92 plycpp WGS84toCartesian ${PLATFORM_MISCELLANEOUS_LIBS}) target_include_directories(core_math PRIVATE include ${EIGEN3_INCLUDE_DIR} diff --git a/core/src/pair_wise_iterative_closest_point.cpp b/core/src/pair_wise_iterative_closest_point.cpp index fed5a7f1c..e3572d8d2 100644 --- a/core/src/pair_wise_iterative_closest_point.cpp +++ b/core/src/pair_wise_iterative_closest_point.cpp @@ -5,6 +5,8 @@ #include #include +#include + #include inline void point_to_point_source_to_target_tait_bryan_wc_AtPA_simplified_4( @@ -324,13 +326,8 @@ bool PairWiseICP::compute( if (multithread) { - std::for_each( -#if USE_EXECUTION_PAR_UNSEQ - std::execution::par_unseq, -#endif - block_sums.begin(), - block_sums.end(), - block_fun); + // TBB rather than std::execution, which AppleClang's libc++ doesn't run in parallel. + tbb::parallel_for_each(block_sums.begin(), block_sums.end(), block_fun); } else { diff --git a/core/tests/test_pair_wise_icp.cpp b/core/tests/test_pair_wise_icp.cpp index 2e596f91c..f01b6c402 100644 --- a/core/tests/test_pair_wise_icp.cpp +++ b/core/tests/test_pair_wise_icp.cpp @@ -52,7 +52,10 @@ namespace std::vector points; const double step = 0.1; const double x0 = 2.0, x1 = 14.0, y0 = 3.0, y1 = 11.0, z0 = 0.0, z1 = 3.0; - const auto jitter = [&]() { return rng.uniform(-0.03, 0.03); }; + const auto jitter = [&]() + { + return rng.uniform(-0.03, 0.03); + }; for (double x = x0; x <= x1; x += step) { @@ -122,10 +125,10 @@ namespace const double d2r = M_PI / 180.0; Eigen::Affine3d pose = Eigen::Affine3d::Identity(); pose.translation() = t; - pose.linear() = (Eigen::AngleAxisd(yaw_deg * d2r, Eigen::Vector3d::UnitZ()) * - Eigen::AngleAxisd(pitch_deg * d2r, Eigen::Vector3d::UnitY()) * - Eigen::AngleAxisd(roll_deg * d2r, Eigen::Vector3d::UnitX())) - .toRotationMatrix(); + pose.linear() = + (Eigen::AngleAxisd(yaw_deg * d2r, Eigen::Vector3d::UnitZ()) * Eigen::AngleAxisd(pitch_deg * d2r, Eigen::Vector3d::UnitY()) * + Eigen::AngleAxisd(roll_deg * d2r, Eigen::Vector3d::UnitX())) + .toRotationMatrix(); return pose; } @@ -224,9 +227,20 @@ TEST_CASE("PairWiseICP::compute matches the reference result") // Build with -DPRINT_REFERENCE to print new reference values after a deliberate change to the algorithm. #ifdef PRINT_REFERENCE - std::printf("REFERENCE\n%.17g, %.17g, %.17g, %.17g\n%.17g, %.17g, %.17g, %.17g\n%.17g, %.17g, %.17g, %.17g\n", - pose(0, 0), pose(0, 1), pose(0, 2), pose(0, 3), pose(1, 0), pose(1, 1), pose(1, 2), pose(1, 3), pose(2, 0), pose(2, 1), - pose(2, 2), pose(2, 3)); + std::printf( + "REFERENCE\n%.17g, %.17g, %.17g, %.17g\n%.17g, %.17g, %.17g, %.17g\n%.17g, %.17g, %.17g, %.17g\n", + pose(0, 0), + pose(0, 1), + pose(0, 2), + pose(0, 3), + pose(1, 0), + pose(1, 1), + pose(1, 2), + pose(1, 3), + pose(2, 0), + pose(2, 1), + pose(2, 2), + pose(2, 3)); #endif const double tolerance = 1e-9; From 80ba17eed38ff7d8d3e29d700c2b7312432cecdb Mon Sep 17 00:00:00 2001 From: Michal Pelka Date: Wed, 11 Nov 2026 23:05:04 +0100 Subject: [PATCH 7/9] CI: keep fbow from leaking global cache vars; link spdlog in pybind fbow's CMakeLists sets BUILD_SHARED_LIBS=ON and, on Windows, the EXECUTABLE/LIBRARY/RUNTIME_OUTPUT_PATH cache entries, which turned raylib and glad into shared libs (undefined glfw*/glad_gl* at link) and moved vqf.lib out of lib/Release. Pin BUILD_SHARED_LIBS=OFF around fbow and drop the leaked entries afterwards, as already done for Xerces. multi_session_registration_py compiles pfd_wrapper.cpp, which now includes spdlog, so link spdlog::spdlog. Co-Authored-By: Claude Opus 5.5 --- cmake/dependencies.cmake | 24 ++++++++++++++++++++++++ pybind/CMakeLists.txt | 2 ++ 2 files changed, 26 insertions(+) diff --git a/cmake/dependencies.cmake b/cmake/dependencies.cmake index b82b6aa9a..b9bb64d93 100644 --- a/cmake/dependencies.cmake +++ b/cmake/dependencies.cmake @@ -180,7 +180,31 @@ if(NOT CMAKE_SYSTEM_PROCESSOR MATCHES "^(x86_64|amd64|i686|x86)$") message(STATUS "Applied ${FBOW_PATCH}") endif() endif() +# fbow's CMakeLists leaks global cache entries that would break every target +# added after it (same trap as Xerces above): +# option(BUILD_SHARED_LIBS ... ON) -- flips raylib, glad, ... to shared libs +# that hide their bundled glfw/glad symbols (undefined glfw*/glad_gl* at link); +# WIN32: EXECUTABLE/LIBRARY/RUNTIME_OUTPUT_PATH -- redirect every later +# target's output (e.g. vqf.lib no longer under lib/Release). +# Pin BUILD_SHARED_LIBS=OFF so fbow builds static and the option() is a no-op, +# then restore/remove those cache entries once fbow is configured. +if(DEFINED CACHE{BUILD_SHARED_LIBS}) + set(_hd_bsl_prev "$CACHE{BUILD_SHARED_LIBS}") + set(_hd_bsl_restore ON) +else() + set(_hd_bsl_restore OFF) +endif() +set(BUILD_SHARED_LIBS OFF CACHE BOOL "HDMapping links fbow statically" FORCE) +set(FBOW_DEVINSTALL OFF CACHE BOOL "" FORCE) add_subdirectory(${THIRDPARTY_DIRECTORY}/fbow) +if(_hd_bsl_restore) + set(BUILD_SHARED_LIBS "${_hd_bsl_prev}" CACHE BOOL "Build shared libraries" FORCE) +else() + unset(BUILD_SHARED_LIBS CACHE) +endif() +unset(EXECUTABLE_OUTPUT_PATH CACHE) +unset(LIBRARY_OUTPUT_PATH CACHE) +unset(RUNTIME_OUTPUT_PATH CACHE) set(FBOW_INCLUDE_DIR ${THIRDPARTY_DIRECTORY}/fbow/src) message(STATUS "Using bundled fbow from: ${THIRDPARTY_DIRECTORY}/fbow") diff --git a/pybind/CMakeLists.txt b/pybind/CMakeLists.txt index 180da5746..fd3947065 100644 --- a/pybind/CMakeLists.txt +++ b/pybind/CMakeLists.txt @@ -185,6 +185,8 @@ target_link_libraries( core_no_gui + spdlog::spdlog + ${PLATFORM_LASZIP_LIB} vqf From 98828685b6a8b43c34f0d7109f35e2ac0491333d Mon Sep 17 00:00:00 2001 From: Michal Pelka Date: Thu, 12 Nov 2026 00:00:10 +0100 Subject: [PATCH 8/9] PairWiseICP: search every point of a bucket, order buckets by index The neighbour search skipped the last target point of each bucket, and std::sort leaves the order within a bucket to the standard library, so libc++, libstdc++ and MSVC skipped different points and the reference test failed on Linux and Windows (about 2e-4 apart). Search the whole bucket and break sort ties by point index (also in compute_fast), so the result is the same on every platform. Reference values regenerated; the result is closer to the ground truth. Co-Authored-By: Claude Opus 5.5 --- core/src/pair_wise_iterative_closest_point.cpp | 10 +++++++--- core/tests/test_pair_wise_icp.cpp | 14 +++++++------- 2 files changed, 14 insertions(+), 10 deletions(-) diff --git a/core/src/pair_wise_iterative_closest_point.cpp b/core/src/pair_wise_iterative_closest_point.cpp index e3572d8d2..669b2d3d6 100644 --- a/core/src/pair_wise_iterative_closest_point.cpp +++ b/core/src/pair_wise_iterative_closest_point.cpp @@ -155,12 +155,14 @@ bool PairWiseICP::compute( indexes.emplace_back(index, i); } + // Ties broken by point index: std::sort leaves the order within a bucket to the standard library, and the + // search below skips each bucket's last point, so without this the result differs between platforms. std::sort( indexes.begin(), indexes.end(), [](const std::pair& a, const std::pair& b) { - return a.first < b.first; + return a.first != b.first ? a.first < b.first : a.second < b.second; }); std::unordered_map> buckets; @@ -235,7 +237,7 @@ bool PairWiseICP::compute( const auto bucket = buckets.find(index_of_bucket); if (bucket != buckets.end()) { - for (int index = bucket->second.first; index < bucket->second.second; index++) + for (int index = bucket->second.first; index <= bucket->second.second; index++) { const Eigen::Vector3d& target_i = target_sorted[index]; const double d_squared = (source_point_global - target_i).squaredNorm(); @@ -428,12 +430,14 @@ bool PairWiseICP::compute_fast( indexes.emplace_back(index, i); } + // Ties broken by point index: std::sort leaves the order within a bucket to the standard library, and the + // search below skips each bucket's last point, so without this the result differs between platforms. std::sort( indexes.begin(), indexes.end(), [](const std::pair& a, const std::pair& b) { - return a.first < b.first; + return a.first != b.first ? a.first < b.first : a.second < b.second; }); std::unordered_map> buckets; diff --git a/core/tests/test_pair_wise_icp.cpp b/core/tests/test_pair_wise_icp.cpp index f01b6c402..2b5c6f413 100644 --- a/core/tests/test_pair_wise_icp.cpp +++ b/core/tests/test_pair_wise_icp.cpp @@ -212,10 +212,10 @@ TEST_CASE("PairWiseICP::compute returns false with fewer than 100 correspondence } // Pins the exact result of a fixed run, so a refactor of compute() (threading, neighbour search, summation) is -// held to the numbers of the reference implementation (as of "Step 2: BoW loop closure, ICP all edges"). The -// tolerance covers rounding differences between compilers and platforms (FMA, libm, summation order: about 1e-16 -// here); a change to the algorithm moves the result far more (e.g. also searching the last point of each bucket: -// about 2e-4). +// held to the numbers of the reference implementation (searching every point of each bucket, buckets ordered by +// point index). The tolerance covers rounding differences between compilers and platforms (FMA, libm, summation +// order: about 1e-16 here); a change to the algorithm moves the result far more (e.g. skipping the last point of +// each bucket: about 2e-4). TEST_CASE("PairWiseICP::compute matches the reference result") { const std::vector target = make_room(); @@ -246,9 +246,9 @@ TEST_CASE("PairWiseICP::compute matches the reference result") const double tolerance = 1e-9; // clang-format off const double expected[3][4] = { - { 0.99847835113005579, -0.052624056892179416, -0.016483050713194683, 0.4000125297669288 }, - { 0.052319974395097578, 0.99846146760778998, -0.018366218494686254, -0.29978225332893682 }, - { 0.01742419593270856, 0.017475878767801229, 0.99969544915308661, 0.10003668251083121 }, + { 0.99847729809823327, -0.052634179800603725, -0.016514487553943396, 0.40002885380785902 }, + { 0.052329963103019038, 0.99846138157059194, -0.018342422789298693, -0.30000900062787589 }, + { 0.017454516438111307, 0.017450290222871295, 0.99969536721295715, 0.099966409536268633 }, }; // clang-format on for (int r = 0; r < 3; r++) From 7378c90ca1e8e86bf7813dad91d7012e9035a482 Mon Sep 17 00:00:00 2001 From: Michal Pelka Date: Thu, 12 Nov 2026 00:55:36 +0100 Subject: [PATCH 9/9] PairWiseICP test: draw random values in a fixed order The scene was built with several jitter()/rng.uniform() calls in one argument list, whose evaluation order is unspecified (clang: left to right; GCC, MSVC: right to left), so each compiler built a different room and the reference test failed on Linux and Windows. Draw them in separate statements in x, y, z order, as clang did, so the reference values are unchanged. Co-Authored-By: Claude Opus 5.5 --- core/tests/test_pair_wise_icp.cpp | 38 +++++++++++++++++++++---------- 1 file changed, 26 insertions(+), 12 deletions(-) diff --git a/core/tests/test_pair_wise_icp.cpp b/core/tests/test_pair_wise_icp.cpp index 2b5c6f413..a46db3d25 100644 --- a/core/tests/test_pair_wise_icp.cpp +++ b/core/tests/test_pair_wise_icp.cpp @@ -56,26 +56,36 @@ namespace { return rng.uniform(-0.03, 0.03); }; + // Jitter drawn in x, y, z order as separate statements: the evaluation order of function arguments is + // unspecified (clang: left to right; GCC, MSVC: right to left), so jitter() calls inside one argument list + // would build a different room on each compiler. + const auto add_jittered = [&](double x, double y, double z, bool jitter_x, bool jitter_y, bool jitter_z) + { + const double dx = jitter_x ? jitter() : 0.0; + const double dy = jitter_y ? jitter() : 0.0; + const double dz = jitter_z ? jitter() : 0.0; + points.emplace_back(x + dx, y + dy, z + dz); + }; for (double x = x0; x <= x1; x += step) { for (double y = y0; y <= y1; y += step) { - points.emplace_back(x + jitter(), y + jitter(), z0); - points.emplace_back(x + jitter(), y + jitter(), z1); + add_jittered(x, y, z0, true, true, false); + add_jittered(x, y, z1, true, true, false); } } for (double z = z0; z <= z1; z += step) { for (double x = x0; x <= x1; x += step) { - points.emplace_back(x + jitter(), y0, z + jitter()); - points.emplace_back(x + jitter(), y1, z + jitter()); + add_jittered(x, y0, z, true, false, true); + add_jittered(x, y1, z, true, false, true); } for (double y = y0; y <= y1; y += step) { - points.emplace_back(x0, y + jitter(), z + jitter()); - points.emplace_back(x1, y + jitter(), z + jitter()); + add_jittered(x0, y, z, false, true, true); + add_jittered(x1, y, z, false, true, true); } } @@ -92,20 +102,20 @@ namespace { for (double x = corner.x(); x <= c1.x(); x += step) { - points.emplace_back(x + jitter(), corner.y(), z + jitter()); - points.emplace_back(x + jitter(), c1.y(), z + jitter()); + add_jittered(x, corner.y(), z, true, false, true); + add_jittered(x, c1.y(), z, true, false, true); } for (double y = corner.y(); y <= c1.y(); y += step) { - points.emplace_back(corner.x(), y + jitter(), z + jitter()); - points.emplace_back(c1.x(), y + jitter(), z + jitter()); + add_jittered(corner.x(), y, z, false, true, true); + add_jittered(c1.x(), y, z, false, true, true); } } for (double x = corner.x(); x <= c1.x(); x += step) { for (double y = corner.y(); y <= c1.y(); y += step) { - points.emplace_back(x + jitter(), y + jitter(), c1.z()); + add_jittered(x, y, c1.z(), true, true, false); } } } @@ -150,7 +160,11 @@ namespace std::vector source; for (size_t i = 0; i < target.size(); i += 3) { - const Eigen::Vector3d noise(rng.uniform(-0.002, 0.002), rng.uniform(-0.002, 0.002), rng.uniform(-0.002, 0.002)); + // Separate statements, so the draws are in x, y, z order on every compiler (see make_room). + const double noise_x = rng.uniform(-0.002, 0.002); + const double noise_y = rng.uniform(-0.002, 0.002); + const double noise_z = rng.uniform(-0.002, 0.002); + const Eigen::Vector3d noise(noise_x, noise_y, noise_z); source.push_back(target_to_source * target[i] + noise); } return source;