Calibration Library 1.0.0
A C++ library for camera calibration and vision-related geometric transformations
Loading...
Searching...
No Matches
serialization.h
Go to the documentation of this file.
1#pragma once
2
3#include <Eigen/Geometry>
4#include <nlohmann/json.hpp>
5
6#include "calib/io/json.h"
7
8// Make Eigen types natively serializable for nlohmann::json
9namespace nlohmann {
10
11template <typename Scalar, int Rows, int Cols, int Options, int MaxRows, int MaxCols>
12struct adl_serializer<Eigen::Matrix<Scalar, Rows, Cols, Options, MaxRows, MaxCols>> {
13 static void to_json(json& j,
14 const Eigen::Matrix<Scalar, Rows, Cols, Options, MaxRows, MaxCols>& m) {
15 if (m.rows() == 1 || m.cols() == 1) {
16 j = json::array();
17 const auto n = static_cast<size_t>(m.size());
18 for (size_t i = 0; i < n; ++i) j.push_back(m(Eigen::Index(i)));
19 } else {
20 j = json::array();
21 for (Eigen::Index r = 0; r < m.rows(); ++r) {
22 json row = json::array();
23 for (Eigen::Index c = 0; c < m.cols(); ++c) row.push_back(m(r, c));
24 j.push_back(row);
25 }
26 }
27 }
28
29 static void from_json(const json& j,
30 Eigen::Matrix<Scalar, Rows, Cols, Options, MaxRows, MaxCols>& m) {
31 if (!j.is_array()) throw std::runtime_error("Eigen JSON: expected array");
32 if (!j.empty() && j.front().is_array()) {
33 const Eigen::Index rows = static_cast<Eigen::Index>(j.size());
34 const Eigen::Index cols = static_cast<Eigen::Index>(j.front().size());
35 m.resize(rows, cols);
36 for (Eigen::Index r = 0; r < rows; ++r)
37 for (Eigen::Index c = 0; c < cols; ++c) m(r, c) = j[r][c].get<Scalar>();
38 } else {
39 const Eigen::Index n = static_cast<Eigen::Index>(j.size());
40 if constexpr (Cols == 1 || Rows == 1) {
41 m.resize((Rows == 1 ? 1 : n), (Cols == 1 ? 1 : n));
42 } else {
43 m.resize(n, 1);
44 }
45 for (Eigen::Index i = 0; i < n; ++i) m(Eigen::Index(i)) = j[i].get<Scalar>();
46 }
47 }
48};
49
50template <typename Scalar, int Dim, int Mode, int Options>
51struct adl_serializer<Eigen::Transform<Scalar, Dim, Mode, Options>> {
52 static void to_json(json& j, const Eigen::Transform<Scalar, Dim, Mode, Options>& T) {
53 const auto M = T.matrix();
54 j = M;
55 }
56 static void from_json(const json& j, Eigen::Transform<Scalar, Dim, Mode, Options>& T) {
57 Eigen::Matrix<Scalar, Dim + 1, Dim + 1> M =
58 j.get<Eigen::Matrix<Scalar, Dim + 1, Dim + 1>>();
59 T.matrix() = M;
60 }
61};
62
63} // namespace nlohmann
static void to_json(json &j, const Eigen::Matrix< Scalar, Rows, Cols, Options, MaxRows, MaxCols > &m)
static void from_json(const json &j, Eigen::Matrix< Scalar, Rows, Cols, Options, MaxRows, MaxCols > &m)
static void to_json(json &j, const Eigen::Transform< Scalar, Dim, Mode, Options > &T)
static void from_json(const json &j, Eigen::Transform< Scalar, Dim, Mode, Options > &T)