diff --git a/3rdparty/observation_equations b/3rdparty/observation_equations index 6850f190..7627530b 160000 --- a/3rdparty/observation_equations +++ b/3rdparty/observation_equations @@ -1 +1 @@ -Subproject commit 6850f190e380b763c0f6a4f93520e61e7c853aae +Subproject commit 7627530b1b85ddcb1751f2e23341c9c7d3a78409 diff --git a/apps/multi_session_registration/multi_session_registration.cpp b/apps/multi_session_registration/multi_session_registration.cpp index 67eefb31..aaf7cb7e 100644 --- a/apps/multi_session_registration/multi_session_registration.cpp +++ b/apps/multi_session_registration/multi_session_registration.cpp @@ -1,6 +1,10 @@ +#include #include #include +#include +#include #include +#include #include #include @@ -17,6 +21,7 @@ #include #include +#include #include #include #include @@ -161,6 +166,7 @@ bool gizmo_all_sessions = false; //!< Stashed Gizmo update when ImGuizmo::IsUsing(). index is sessionId std::map> session_drag_preview_poses; bool is_ndt_gui = false; +bool is_instrument_offset_gui = false; bool is_loop_closure_gui = false; bool prev_is_loop_closure_gui = false; bool remove_gui = false; @@ -409,6 +415,245 @@ void ndt_gui() #endif } +//! Tools > Instrument offset: the fixed pose of one instrument (e.g. a camera session) relative to another (e.g. the +//! lidar session) on the same rig, fitted from their paths (instrument_offset::estimate). +void instrument_offset_gui() +{ + static int reference_index = 0; + static int instrument_index = 1; + static double time_shift_s = 0.0; + static instrument_offset::Options options; + static instrument_offset::Result result; + static std::string reference_name, instrument_name, status; + static int camera_session = 1; // 0: the reference is the camera, 1: the instrument is + static int camera_axes = 0; // instrument_offset::CameraAxes: 0 FLU, 1 optical + static std::string camera_text; // the cam_.json "extrinsics" block shown for copying + + if (!ImGui::Begin("Instrument offset", &is_instrument_offset_gui, ImGuiWindowFlags_AlwaysAutoResize)) + { + ImGui::End(); + return; + } + + const int n = static_cast(sessions.size()); + reference_index = std::clamp(reference_index, 0, std::max(n - 1, 0)); + instrument_index = std::clamp(instrument_index, 0, std::max(n - 1, 0)); + const auto session_label = [](int i) + { + const fs::path p(sessions[i].session_file_name); + return std::to_string(i) + ": " + (p.parent_path().filename() / p.filename()).string(); + }; + const auto session_combo = [&](const char* label, int& index) + { + if (ImGui::BeginCombo(label, n > 0 ? session_label(index).c_str() : "")) + { + for (int i = 0; i < n; i++) + if (ImGui::Selectable(session_label(i).c_str(), i == index)) + index = i; + ImGui::EndCombo(); + } + }; + + ImGui::Text("frame * instrument(t) = reference(t + time shift) * offset"); + session_combo("Reference (e.g. lidar)", reference_index); + session_combo("Instrument (e.g. camera)", instrument_index); + ImGui::InputDouble("Instrument time shift [s]", &time_shift_s, 0.001, 0.01, "%.4f"); + ImGui::Checkbox("Estimate time shift", &options.estimate_time_shift); + ImGui::Checkbox("Estimate frame (sessions not registered)", &options.estimate_frame); + ImGui::Checkbox("Estimate scale of the instrument path", &options.estimate_scale); + + ImGui::BeginDisabled(n < 2 || reference_index == instrument_index); + if (ImGui::Button("Compute")) + { + result = instrument_offset::estimate( + instrument_offset::session_trajectory(sessions[reference_index]), + instrument_offset::session_trajectory(sessions[instrument_index]), + time_shift_s, + options); + reference_name = session_label(reference_index); + instrument_name = session_label(instrument_index); + status = result.valid ? "" : "No result: the instrument path does not overlap the reference path in time"; + if (result.valid) + { + time_shift_s = result.time_shift_s; + const Eigen::Quaterniond q(result.offset.linear()); + spdlog::info( + "instrument offset {} -> {}: t [{:.4f} {:.4f} {:.4f}] m, q xyzw [{:.6f} {:.6f} {:.6f} {:.6f}], time shift {:.4f} s, " + "scale {:.6f}, rms {:.2f} mm / {:.3f} deg, {} pairs", + reference_name, + instrument_name, + result.offset.translation().x(), + result.offset.translation().y(), + result.offset.translation().z(), + q.x(), + q.y(), + q.z(), + q.w(), + result.time_shift_s, + result.scale, + result.rms_translation_m * 1000.0, + result.rms_rotation_deg, + result.pairs); + } + } + ImGui::EndDisabled(); + + if (!status.empty()) + ImGui::TextColored(ImVec4(1.0f, 0.4f, 0.4f, 1.0f), "%s", status.c_str()); + + if (result.valid) + { + const Eigen::Vector3d t = result.offset.translation(); + const Eigen::Quaterniond q(result.offset.linear()); + const TaitBryanPose tb = pose_tait_bryan_from_affine_matrix(result.offset); + const TaitBryanPose fr = pose_tait_bryan_from_affine_matrix(result.frame); + const Eigen::Matrix4d m = result.offset.matrix(); + + ImGui::Separator(); + ImGui::Text("%s -> %s", reference_name.c_str(), instrument_name.c_str()); + ImGui::Text("translation [m] %.4f %.4f %.4f", t.x(), t.y(), t.z()); + ImGui::Text("quaternion x y z w %.6f %.6f %.6f %.6f", q.x(), q.y(), q.z(), q.w()); + ImGui::Text("om fi ka [deg] %.3f %.3f %.3f", rad2deg(tb.om), rad2deg(tb.fi), rad2deg(tb.ka)); + for (int r = 0; r < 4; r++) + ImGui::Text("%10.6f %10.6f %10.6f %10.6f", m(r, 0), m(r, 1), m(r, 2), m(r, 3)); + ImGui::Text("time shift [s] %.4f, scale %.6f", result.time_shift_s, result.scale); + ImGui::Text( + "frame: t [m] %.4f %.4f %.4f, om fi ka [deg] %.3f %.3f %.3f", + fr.px, + fr.py, + fr.pz, + rad2deg(fr.om), + rad2deg(fr.fi), + rad2deg(fr.ka)); + ImGui::Text("pairs %d, residual rms %.2f mm / %.3f deg", result.pairs, result.rms_translation_m * 1000.0, result.rms_rotation_deg); + + // the offset as a camera calibration: cam_.json extrinsics (camera_lidar_calibration, + // camera_lidar_trajectory_viewer), the camera optical frame in the lidar frame + ImGui::Separator(); + ImGui::Text("Camera calibration (cam_.json extrinsics, camera optical frame in the lidar frame)"); + ImGui::RadioButton(("Camera = reference " + reference_name).c_str(), &camera_session, 0); + ImGui::RadioButton(("Camera = instrument " + instrument_name).c_str(), &camera_session, 1); + ImGui::Combo( + "Camera session axes", + &camera_axes, + "FLU: x = optical axis, y left, z up (charuco_trajectory)\0Optical: x right, y down, z forward\0"); + const instrument_offset::CameraExtrinsics ce = instrument_offset::camera_extrinsics( + result, camera_session == 0, camera_axes == 0 ? instrument_offset::CameraAxes::Flu : instrument_offset::CameraAxes::Optical); + const Eigen::Matrix3d cam_r = ce.camera_in_lidar.linear(); + const Eigen::Vector3d cam_c = ce.camera_in_lidar.translation(); + const Eigen::Matrix4d lidar_to_camera = ce.camera_in_lidar.inverse().matrix(); + { + std::ostringstream o; + o << std::setprecision(17); + const auto row = [&o](std::initializer_list values) + { + o << "["; + const char* sep = ""; + for (double v : values) + { + o << sep << v; + sep = ", "; + } + o << "]"; + }; + const auto& T = lidar_to_camera; + o << "\"extrinsics\": {\n \"T_lidar_to_camera_4x4\": [\n"; + for (int r = 0; r < 4; r++) + { + o << " "; + row({ T(r, 0), T(r, 1), T(r, 2), T(r, 3) }); + o << (r < 3 ? ",\n" : "\n"); + } + o << " ],\n \"camera_position_in_world_xyz\": "; + row({ cam_c.x(), cam_c.y(), cam_c.z() }); + o << ",\n \"camera_rotation_matrix_in_world\": [\n"; + for (int r = 0; r < 3; r++) + { + o << " "; + row({ cam_r(r, 0), cam_r(r, 1), cam_r(r, 2) }); + o << (r < 2 ? ",\n" : "\n"); + } + o << " ]\n}"; + camera_text = o.str(); + } + ImGui::Text( + "camera position in the lidar frame [m] %.4f %.4f %.4f, optical axis %.3f %.3f %.3f", + cam_c.x(), + cam_c.y(), + cam_c.z(), + cam_r(0, 2), + cam_r(1, 2), + cam_r(2, 2)); + ImGui::Text("trajectory viewer Time offset (s) %.6f", ce.trajectory_viewer_time_offset_s); + ImGui::InputTextMultiline( + "##camera_extrinsics", + camera_text.data(), + camera_text.size() + 1, + ImVec2(ImGui::GetFontSize() * 50.0f, ImGui::GetTextLineHeightWithSpacing() * 15.0f), + ImGuiInputTextFlags_ReadOnly); + if (ImGui::Button("Copy extrinsics")) + ImGui::SetClipboardText(camera_text.c_str()); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("Paste over the \"extrinsics\" block of a cam_.json"); + ImGui::Separator(); + + nlohmann::json j; + j["reference_session"] = sessions.size() > static_cast(reference_index) ? sessions[reference_index].session_file_name : ""; + j["instrument_session"] = + sessions.size() > static_cast(instrument_index) ? sessions[instrument_index].session_file_name : ""; + j["model"] = "frame * instrument(t) = reference(t + time_shift) * offset, instrument translation scaled by scale"; + j["time_shift_s"] = result.time_shift_s; + j["scale"] = result.scale; + j["pairs"] = result.pairs; + j["translation_m"] = { t.x(), t.y(), t.z() }; + j["quaternion_xyzw"] = { q.x(), q.y(), q.z(), q.w() }; + j["om_fi_ka_deg"] = { rad2deg(tb.om), rad2deg(tb.fi), rad2deg(tb.ka) }; + j["matrix_row_major"] = nlohmann::json::array(); + j["frame_matrix_row_major"] = nlohmann::json::array(); + for (int r = 0; r < 4; r++) + { + j["matrix_row_major"].push_back({ m(r, 0), m(r, 1), m(r, 2), m(r, 3) }); + const Eigen::Matrix4d f = result.frame.matrix(); + j["frame_matrix_row_major"].push_back({ f(r, 0), f(r, 1), f(r, 2), f(r, 3) }); + } + j["residual"] = { { "rms_translation_m", result.rms_translation_m }, { "rms_rotation_deg", result.rms_rotation_deg } }; + nlohmann::json cam; + cam["camera_session"] = j[camera_session == 0 ? "reference_session" : "instrument_session"]; + cam["camera_session_axes"] = camera_axes == 0 ? "flu" : "optical"; + cam["trajectory_viewer_time_offset_s"] = ce.trajectory_viewer_time_offset_s; + cam["extrinsics"]["camera_position_in_world_xyz"] = { cam_c.x(), cam_c.y(), cam_c.z() }; + cam["extrinsics"]["camera_rotation_matrix_in_world"] = nlohmann::json::array(); + cam["extrinsics"]["T_lidar_to_camera_4x4"] = nlohmann::json::array(); + for (int r = 0; r < 4; r++) + { + if (r < 3) + cam["extrinsics"]["camera_rotation_matrix_in_world"].push_back({ cam_r(r, 0), cam_r(r, 1), cam_r(r, 2) }); + cam["extrinsics"]["T_lidar_to_camera_4x4"].push_back( + { lidar_to_camera(r, 0), lidar_to_camera(r, 1), lidar_to_camera(r, 2), lidar_to_camera(r, 3) }); + } + j["camera"] = cam; + + if (ImGui::Button("Copy as JSON")) + ImGui::SetClipboardText(j.dump(2).c_str()); + ImGui::SameLine(); + if (ImGui::Button("Save as JSON...")) + { + const std::string path = mandeye::fd::SaveFileDialog( + "Save instrument offset", { "JSON file (*.json)", "*.json" }, ".json", "instrument_offset.json"); + if (!path.empty()) + { + std::ofstream out(fs::path(path), std::ios::binary); + out << j.dump(2) << "\n"; + if (out) + std::cout << "instrument offset saved to '" << path << "'" << std::endl; + else + std::cerr << "could not write '" << path << "'" << std::endl; + } + } + } + ImGui::End(); +} + // Places the edge gizmo at the active edge's target pose. void setGizmoFromActiveEdge() { @@ -3735,6 +3980,12 @@ void display() ImGui::EndTooltip(); } + ImGui::MenuItem("Instrument offset", nullptr, &is_instrument_offset_gui, !is_loop_closure_gui && (sessions.size() >= 2)); + if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled)) + ImGui::SetTooltip( + "Fixed pose of one instrument (e.g. camera session) relative to another (e.g. lidar session)\n" + "on the same rig, from their trajectories once both are registered. Needs 2 sessions."); + // bool prev_is_loop_closure_gui ImGui::MenuItem( "Manual Loop Closure", @@ -3992,6 +4243,9 @@ void display() if (is_ndt_gui) ndt_gui(); + if (is_instrument_offset_gui) + instrument_offset_gui(); + if (!prev_is_loop_closure_gui && is_loop_closure_gui) { spdlog::debug("Open loop open gui"); @@ -4111,8 +4365,10 @@ int main(int argc, char* argv[]) std::cout << winTitle << "\n\n" << "USAGE:\n" << std::filesystem::path(argv[0]).stem().string() - << " [--mjp ] [--mjs ...] [ ...] /?\n\n" + << " [--downsample ] [--mjp ] [--mjs ...] [ ...] /?\n\n" << "where\n" + << " --downsample Bucket size [m] for downsampling during load; 0 loads full density\n" + << " (default: Settings > Downsample during load, " << bucket_x << " m)\n" << " --mjp Mandeye JSON Project file to open\n" << " --mjs [...] Session file(s) (*.mjs, *.json) to add to the project and load\n" << " *.mjp opens a project, *.mjs / *.json adds a session\n" @@ -4135,6 +4391,36 @@ int main(int argc, char* argv[]) current_flag = arg; continue; } + if (arg == "--downsample") + { + current_flag.clear(); + double bucket = -1.0; + if (i + 1 < argc) + { + try + { + size_t used = 0; + const std::string value(argv[i + 1]); + bucket = std::stod(value, &used); + if (used != value.size()) + bucket = -1.0; + } catch (const std::exception&) + { + bucket = -1.0; + } + } + if (bucket < 0.0) + { + std::cerr << "--downsample needs a bucket size in metres (0 = no downsampling), keeping the current setting" + << std::endl; + continue; + } + i++; + is_decimate = bucket > 0.0; + if (is_decimate) + bucket_x = bucket_y = bucket_z = bucket; + continue; + } if (arg.rfind("--", 0) == 0) { std::cerr << "Unknown option: '" << arg << "'" << std::endl; @@ -4167,6 +4453,11 @@ int main(int argc, char* argv[]) if (!session_files.empty()) setLocationHintFromFile(session_files.back()); + if (is_decimate) + std::cout << "Downsample during load: bucket " << bucket_x << " x " << bucket_y << " x " << bucket_z << " m" << std::endl; + else + std::cout << "Downsample during load: off" << std::endl; + bool added = false; for (const auto& session_file : session_files) added |= addSessionFile(session_file); diff --git a/core/CMakeLists.txt b/core/CMakeLists.txt index af2de4f9..e1f0dcb8 100644 --- a/core/CMakeLists.txt +++ b/core/CMakeLists.txt @@ -8,6 +8,7 @@ set(CORE_BASE_SOURCES src/gnss.cpp src/ground_control_points.cpp src/imu_preintegration.cpp + src/instrument_offset.cpp src/nmea.cpp src/point_cloud.cpp src/point_clouds.cpp diff --git a/core/include/Core/instrument_offset.h b/core/include/Core/instrument_offset.h new file mode 100644 index 00000000..78889949 --- /dev/null +++ b/core/include/Core/instrument_offset.h @@ -0,0 +1,72 @@ +#pragma once + +#include +#include + +class Session; + +//! Rigid offset between two instruments carried on one rig (e.g. a camera and a lidar), from their paths: +//! frame * S(C_i) = L(t_i + time_shift) * offset for every instrument pose C_i, L = reference path, S = instrument +//! translation scaled by scale. Observation equation: path_to_path_tait_bryan_wc (observation_equations). +namespace instrument_offset +{ + struct TimedPose + { + double time_s = 0.0; + Eigen::Affine3d pose = Eigen::Affine3d::Identity(); // world <- body + }; + + struct Options + { + bool estimate_time_shift = true; + bool estimate_frame = false; //!< false: both sessions are registered in one world + bool estimate_scale = false; + int iterations = 30; + }; + + struct Result + { + bool valid = false; + Eigen::Affine3d offset = Eigen::Affine3d::Identity(); //!< instrument pose in the reference body frame + Eigen::Affine3d frame = Eigen::Affine3d::Identity(); //!< reference world <- instrument path world + double time_shift_s = 0.0; //!< added to the instrument timestamps + double scale = 1.0; //!< applied to the instrument path translations + int pairs = 0; + double rms_translation_m = 0.0; + double rms_rotation_deg = 0.0; + }; + + //! World poses of every trajectory node of a session (scan pose * local node pose), sorted by time. + //! Node timestamps are read as nanoseconds (the trajectory_lio_N.csv convention). + std::vector session_trajectory(const Session& session); + + //! Levenberg-Marquardt fit of the offset (and optionally the time shift, frame and scale). + //! @param reference - sorted by time, e.g. the lidar session + //! @param instrument - sorted by time, e.g. the camera session + //! @param time_shift_s - initial time shift, added to the instrument timestamps + Result estimate( + const std::vector& reference, const std::vector& instrument, double time_shift_s, const Options& options); + + //! Axes of the body frame a camera session's poses are given in. + enum class CameraAxes + { + Flu, //!< x forward = optical axis, y left, z up (charuco_trajectory's default --tum-frame flu) + Optical //!< x right, y down, z forward (OpenCV) + }; + + //! Extrinsics of a cam_.json (camera_lidar_calibration, camera_lidar_trajectory_viewer) from a result + //! between a camera session and a lidar session. + struct CameraExtrinsics + { + //! the camera optical frame (x right, y down, z forward) in the lidar frame, metres: + //! linear() = camera_rotation_matrix_in_world, translation() = camera_position_in_world_xyz + Eigen::Affine3d camera_in_lidar = Eigen::Affine3d::Identity(); + //! the trajectory viewer's "Time offset (s)": lidar time = image time + this + double trajectory_viewer_time_offset_s = 0.0; + }; + + //! @param camera_is_reference - true: the camera session was the reference (offset = the lidar in the camera body, + //! translation in the camera path's units, converted to metres with the result's scale); false: it was the + //! instrument (offset = the camera body in the lidar frame) + CameraExtrinsics camera_extrinsics(const Result& result, bool camera_is_reference, CameraAxes axes); +} // namespace instrument_offset diff --git a/core/src/instrument_offset.cpp b/core/src/instrument_offset.cpp new file mode 100644 index 00000000..0018ac19 --- /dev/null +++ b/core/src/instrument_offset.cpp @@ -0,0 +1,270 @@ +#include + +#include +#include +#include +#include + +#include + +#include +#include + +namespace instrument_offset +{ + namespace + { + // reference pose at t; false outside the path or across a hole in it + bool reference_pose(const std::map& reference, double t, Eigen::Affine3d& pose) + { + auto next = reference.lower_bound(t); + if (next == reference.begin() || next == reference.end() || next->first - std::prev(next)->first > 0.1) + return false; + pose = Eigen::Affine3d(getInterpolatedPose(reference, t)); + return true; + } + } // namespace + + std::vector session_trajectory(const Session& session) + { + std::vector trajectory; + for (const auto& pc : session.point_clouds_container.point_clouds) + for (const auto& node : pc.local_trajectory) + trajectory.push_back({ node.timestamps.first * 1e-9, pc.m_pose * node.m_pose }); + std::sort( + trajectory.begin(), + trajectory.end(), + [](const TimedPose& a, const TimedPose& b) + { + return a.time_s < b.time_s; + }); + return trajectory; + } + + Result estimate( + const std::vector& reference_path, const std::vector& instrument, double time_shift_s, const Options& options) + { + std::map reference; + for (const auto& node : reference_path) + reference[node.time_s] = node.pose.matrix(); + + // start: offset seen by the first pair, frame identity, scale 1 + TaitBryanPose offset; + TaitBryanPose frame; + double scale = 1.0; + for (const auto& node : instrument) + { + Eigen::Affine3d l; + if (reference_pose(reference, node.time_s + time_shift_s, l)) + { + offset = pose_tait_bryan_from_affine_matrix(l.inverse() * node.pose); + break; + } + } + + const double rate_dt = 0.01; // reference rate of change from poses 10 ms before and after + const double w_t = 1.0 / (0.01 * 0.01); // 1 cm + const double w_r = 1.0 / ((0.2 * M_PI / 180.0) * (0.2 * M_PI / 180.0)); // 0.2 deg + const double lm_lambda = 1.0; + + for (int iter = 0; iter < options.iterations; iter++) + { + Eigen::Matrix AtPA = Eigen::Matrix::Zero(); + Eigen::Matrix AtPB = Eigen::Matrix::Zero(); + + for (const auto& node : instrument) + { + const double t = node.time_s + time_shift_s; + Eigen::Affine3d l, l_before, l_after; + if (!reference_pose(reference, t, l) || !reference_pose(reference, t - rate_dt, l_before) || + !reference_pose(reference, t + rate_dt, l_after)) + continue; + + const TaitBryanPose r = pose_tait_bryan_from_affine_matrix(l); + const TaitBryanPose a = pose_tait_bryan_from_affine_matrix(l_before); + const TaitBryanPose b = pose_tait_bryan_from_affine_matrix(l_after); + const TaitBryanPose m = pose_tait_bryan_from_affine_matrix(node.pose); + TaitBryanPose v; + v.px = (b.px - a.px) / (2 * rate_dt); + v.py = (b.py - a.py) / (2 * rate_dt); + v.pz = (b.pz - a.pz) / (2 * rate_dt); + v.om = normalize_angle(b.om - a.om) / (2 * rate_dt); + v.fi = normalize_angle(b.fi - a.fi) / (2 * rate_dt); + v.ka = normalize_angle(b.ka - a.ka) / (2 * rate_dt); + + Eigen::Matrix delta; + Eigen::Matrix jacobian; + path_to_path_obs_eq_tait_bryan_wc( + delta, + r.px, + r.py, + r.pz, + r.om, + r.fi, + r.ka, + v.px, + v.py, + v.pz, + v.om, + v.fi, + v.ka, + offset.px, + offset.py, + offset.pz, + offset.om, + offset.fi, + offset.ka, + frame.px, + frame.py, + frame.pz, + frame.om, + frame.fi, + frame.ka, + 0.0, + scale, + m.px, + m.py, + m.pz, + m.om, + m.fi, + m.ka); + path_to_path_obs_eq_tait_bryan_wc_jacobian( + jacobian, + r.px, + r.py, + r.pz, + r.om, + r.fi, + r.ka, + v.px, + v.py, + v.pz, + v.om, + v.fi, + v.ka, + offset.px, + offset.py, + offset.pz, + offset.om, + offset.fi, + offset.ka, + frame.px, + frame.py, + frame.pz, + frame.om, + frame.fi, + frame.ka, + 0.0, + scale, + m.px, + m.py, + m.pz, + m.om, + m.fi, + m.ka); + for (int k = 3; k < 6; k++) + delta(k) = normalize_angle(delta(k)); + + Eigen::Matrix P = Eigen::Matrix::Zero(); + for (int k = 0; k < 6; k++) + P(k, k) = (k < 3 ? w_t : w_r) * get_cauchy_w(delta(k), 1); + + const Eigen::Matrix A = -jacobian; + AtPA += A.transpose() * P * A; + AtPB += A.transpose() * P * delta; + } + + // unknowns that are not estimated stay where they are + std::vector fixed; + if (!options.estimate_frame) + fixed.insert(fixed.end(), { 6, 7, 8, 9, 10, 11 }); + if (!options.estimate_time_shift) + fixed.push_back(12); + if (!options.estimate_scale) + fixed.push_back(13); + for (int k : fixed) + { + AtPA.row(k).setZero(); + AtPA.col(k).setZero(); + AtPA(k, k) = 1.0; + AtPB(k) = 0.0; + } + AtPA += lm_lambda * Eigen::Matrix::Identity(); + + const Eigen::Matrix x = AtPA.ldlt().solve(AtPB); + if (!x.allFinite()) + break; + offset.px += x(0); + offset.py += x(1); + offset.pz += x(2); + offset.om += x(3); + offset.fi += x(4); + offset.ka += x(5); + frame.px += x(6); + frame.py += x(7); + frame.pz += x(8); + frame.om += x(9); + frame.fi += x(10); + frame.ka += x(11); + time_shift_s += x(12); + scale += x(13); + } + + Result result; + result.offset = affine_matrix_from_pose_tait_bryan(offset); + result.frame = affine_matrix_from_pose_tait_bryan(frame); + result.time_shift_s = time_shift_s; + result.scale = scale; + + double sum_t = 0.0, sum_r = 0.0; + for (const auto& node : instrument) + { + Eigen::Affine3d l; + if (!reference_pose(reference, node.time_s + time_shift_s, l)) + continue; + Eigen::Affine3d c = node.pose; + c.translation() *= scale; + const Eigen::Affine3d e = (result.frame * c).inverse() * l * result.offset; + sum_t += e.translation().squaredNorm(); + sum_r += std::pow(Eigen::AngleAxisd(e.linear()).angle() * 180.0 / M_PI, 2); + result.pairs++; + } + if (result.pairs > 0) + { + result.rms_translation_m = std::sqrt(sum_t / result.pairs); + result.rms_rotation_deg = std::sqrt(sum_r / result.pairs); + } + result.valid = result.pairs >= 3 && result.offset.matrix().allFinite(); + return result; + } + + CameraExtrinsics camera_extrinsics(const Result& result, bool camera_is_reference, CameraAxes axes) + { + Eigen::Affine3d camera_body_in_lidar; + if (camera_is_reference) + { + // frame * S(lidar(t)) = camera(t + shift) * offset: the lidar in the camera body, its translation in the + // camera path's units (lidar metres * scale) + Eigen::Affine3d lidar_in_camera = result.offset; + lidar_in_camera.translation() /= result.scale; + camera_body_in_lidar = lidar_in_camera.inverse(); + } + else + { + // frame * S(camera(t)) = lidar(t + shift) * offset: the camera body in the lidar frame, metres + camera_body_in_lidar = result.offset; + } + + // optical axes in the body: FLU x = optical z, FLU y = -optical x, FLU z = -optical y + Eigen::Matrix3d body_from_optical = Eigen::Matrix3d::Identity(); + if (axes == CameraAxes::Flu) + body_from_optical << 0, 0, 1, -1, 0, 0, 0, -1, 0; + + CameraExtrinsics e; + e.camera_in_lidar = camera_body_in_lidar; + e.camera_in_lidar.linear() = camera_body_in_lidar.linear() * body_from_optical; + // camera reference: lidar time t <-> camera time t + shift; camera instrument: camera time t <-> lidar t + shift + e.trajectory_viewer_time_offset_s = camera_is_reference ? -result.time_shift_s : result.time_shift_s; + return e; + } +} // namespace instrument_offset diff --git a/core/tests/CMakeLists.txt b/core/tests/CMakeLists.txt index 7491c0fa..e1df1346 100644 --- a/core/tests/CMakeLists.txt +++ b/core/tests/CMakeLists.txt @@ -6,6 +6,7 @@ project(hdmapping_core_tests) # Uses doctest, same as shared/tests. add_executable(hdmapping_core_tests test_pair_wise_icp.cpp + test_instrument_offset.cpp ) target_include_directories(hdmapping_core_tests PRIVATE diff --git a/core/tests/test_instrument_offset.cpp b/core/tests/test_instrument_offset.cpp new file mode 100644 index 00000000..7b7df29f --- /dev/null +++ b/core/tests/test_instrument_offset.cpp @@ -0,0 +1,161 @@ +#include + +#include + +#include + +#include +#include + +using instrument_offset::TimedPose; + +namespace +{ + // smooth rig motion: translating and turning about all three axes + Eigen::Affine3d rig_pose(double t) + { + Eigen::Affine3d m = Eigen::Affine3d::Identity(); + m.translation() = Eigen::Vector3d(0.5 * std::sin(0.7 * t), 0.3 * std::cos(0.5 * t), 0.1 * t); + m.linear() = + (Eigen::AngleAxisd(0.5 * t, Eigen::Vector3d::UnitZ()) * Eigen::AngleAxisd(0.2 * std::sin(0.3 * t), Eigen::Vector3d::UnitY()) * + Eigen::AngleAxisd(0.3 * std::sin(0.4 * t), Eigen::Vector3d::UnitX())) + .toRotationMatrix(); + return m; + } + + Eigen::Affine3d make_pose(double x, double y, double z, double rz, double rx) + { + Eigen::Affine3d m = Eigen::Affine3d::Identity(); + m.translation() = Eigen::Vector3d(x, y, z); + m.linear() = (Eigen::AngleAxisd(rz, Eigen::Vector3d::UnitZ()) * Eigen::AngleAxisd(rx, Eigen::Vector3d::UnitX())).toRotationMatrix(); + return m; + } + + std::vector reference_path() + { + std::vector r; + for (int i = 0; i <= 2000; i++) // 200 Hz, 10 s + r.push_back({ i * 0.005, rig_pose(i * 0.005) }); + return r; + } + + // 50 Hz, off the reference sample times: frame * S(C) = L(t) * offset, the instrument clock reads clock_late_s late + std::vector instrument_path(const Eigen::Affine3d& offset, double clock_late_s, const Eigen::Affine3d& frame, double scale) + { + std::vector c; + for (int i = 10; i < 490; i++) + { + const double t = i * 0.02 + 0.003; + Eigen::Affine3d pose = frame.inverse() * rig_pose(t) * offset; + pose.translation() /= scale; + c.push_back({ t + clock_late_s, pose }); + } + return c; + } + + 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; + } + + const Eigen::Affine3d known_offset = make_pose(0.12, -0.05, 0.31, 1.2, -0.4); +} // namespace + +TEST_CASE("instrument_offset::estimate recovers the offset of two registered paths") +{ + instrument_offset::Options options; + options.estimate_time_shift = false; + const auto r = + instrument_offset::estimate(reference_path(), instrument_path(known_offset, 0.0, Eigen::Affine3d::Identity(), 1.0), 0.0, options); + + REQUIRE(r.valid); + CHECK(r.pairs == 480); + CHECK((r.offset.translation() - known_offset.translation()).norm() < 1e-4); + CHECK(rotation_error_deg(r.offset, known_offset) < 0.01); +} + +TEST_CASE("instrument_offset::estimate recovers the time shift") +{ + const auto r = instrument_offset::estimate( + reference_path(), instrument_path(known_offset, 0.020, Eigen::Affine3d::Identity(), 1.0), 0.0, instrument_offset::Options{}); + + REQUIRE(r.valid); + CHECK(std::abs(r.time_shift_s - (-0.020)) < 0.0005); + CHECK((r.offset.translation() - known_offset.translation()).norm() < 1e-3); +} + +TEST_CASE("instrument_offset::estimate recovers the frame and scale of the instrument path") +{ + const Eigen::Affine3d frame = make_pose(0.05, -0.02, 0.03, 0.05, 0.02); + instrument_offset::Options options; + options.estimate_time_shift = false; + options.estimate_frame = true; + options.estimate_scale = true; + const auto r = instrument_offset::estimate(reference_path(), instrument_path(known_offset, 0.0, frame, 1.02), 0.0, options); + + REQUIRE(r.valid); + CHECK(std::abs(r.scale - 1.02) < 1e-4); + CHECK((r.frame.translation() - frame.translation()).norm() < 1e-3); + CHECK((r.offset.translation() - known_offset.translation()).norm() < 1e-3); + CHECK(rotation_error_deg(r.offset, known_offset) < 0.01); +} + +TEST_CASE("instrument_offset::estimate is invalid without time overlap") +{ + const auto r = instrument_offset::estimate( + reference_path(), instrument_path(known_offset, 100.0, Eigen::Affine3d::Identity(), 1.0), 0.0, instrument_offset::Options{}); + CHECK_FALSE(r.valid); +} + +TEST_CASE("instrument_offset::camera_extrinsics: FLU body at the lidar origin looks along lidar x") +{ + instrument_offset::Result r; // offset identity: the camera body coincides with the lidar + const auto e = instrument_offset::camera_extrinsics(r, true, instrument_offset::CameraAxes::Flu); + const Eigen::Matrix3d R = e.camera_in_lidar.linear(); + CHECK((R.col(0) - Eigen::Vector3d(0, -1, 0)).norm() < 1e-12); // image right = body right = -y + CHECK((R.col(1) - Eigen::Vector3d(0, 0, -1)).norm() < 1e-12); // image down = -z + CHECK((R.col(2) - Eigen::Vector3d(1, 0, 0)).norm() < 1e-12); // optical axis = x + CHECK(e.camera_in_lidar.translation().norm() < 1e-12); +} + +TEST_CASE("instrument_offset::camera_extrinsics recovers the optical frame in the lidar frame") +{ + // camera optical frame in the lidar frame, and the same camera's FLU body + const Eigen::Affine3d optical_in_lidar = make_pose(-0.01, 0.004, 0.12, 3.1, 0.02); + Eigen::Affine3d optical_in_flu = Eigen::Affine3d::Identity(); + optical_in_flu.linear() << 0, 0, 1, -1, 0, 0, 0, -1, 0; + const Eigen::Affine3d flu_in_lidar = optical_in_lidar * optical_in_flu.inverse(); + const double scale = 1.02, shift = 0.003; + + const auto check = [&](const instrument_offset::CameraExtrinsics& e, double viewer_offset) + { + CHECK((e.camera_in_lidar.translation() - optical_in_lidar.translation()).norm() < 1e-12); + CHECK(rotation_error_deg(e.camera_in_lidar, optical_in_lidar) < 1e-9); + CHECK(std::abs(e.trajectory_viewer_time_offset_s - viewer_offset) < 1e-15); + }; + + SUBCASE("camera = reference, FLU, lidar path scaled into the camera's units") + { + instrument_offset::Result r; + r.offset = flu_in_lidar.inverse(); // the lidar in the camera body + r.offset.translation() *= scale; + r.scale = scale; + r.time_shift_s = shift; // lidar t <-> camera t + shift + check(instrument_offset::camera_extrinsics(r, true, instrument_offset::CameraAxes::Flu), -shift); + } + SUBCASE("camera = instrument, FLU") + { + instrument_offset::Result r; + r.offset = flu_in_lidar; // the camera body in the lidar frame, metres whatever the instrument scale + r.scale = scale; + r.time_shift_s = shift; // camera t <-> lidar t + shift + check(instrument_offset::camera_extrinsics(r, false, instrument_offset::CameraAxes::Flu), shift); + } + SUBCASE("camera = reference, optical axes") + { + instrument_offset::Result r; + r.offset = optical_in_lidar.inverse(); + r.time_shift_s = shift; + check(instrument_offset::camera_extrinsics(r, true, instrument_offset::CameraAxes::Optical), -shift); + } +}