licornea_tools
json.cc
Go to the documentation of this file.
1 #include "json.h"
2 #include "string.h"
3 #include <fstream>
4 #include <vector>
5 #include <cstdint>
6 
7 namespace tlz {
8 
9 void export_json_file(const json& j, const std::string& filename, bool compact) {
10  std::string ext = file_name_extension(filename);
11  if(ext == "json") {
12  std::ofstream output(filename);
13  output << j.dump(compact ? -1 : 4);
14  } else if(ext == "cbor") {
15  std::vector<std::uint8_t> cbor_data = json::to_cbor(j);
16  std::ofstream output(filename, std::ios_base::out | std::ios_base::binary);
17  output.write(reinterpret_cast<const std::ofstream::char_type*>(cbor_data.data()), cbor_data.size());
18  } else {
19  throw std::runtime_error("unknown json filename extension");
20  }
21 }
22 
23 
24 json import_json_file(const std::string& filename) {
25  json j;
26  std::ifstream input(filename);
27  input >> j;
28  return j;
29 }
30 
31 
32 cv::Mat_<real> decode_mat(const json& j) {
33  int rows = j.size();
34  if(j[0].is_array()) {
35  int cols = j[0].size();
36  cv::Mat_<real> mat(rows, cols);
37  for(int row = 0; row < rows; ++row) for(int col = 0; col < cols; ++col)
38  mat(row, col) = j[row][col].get<real>();
39  return mat;
40 
41  } else {
42  cv::Mat_<real> mat(rows, 1);
43  for(int row = 0; row < rows; ++row)
44  mat(row, 0) = j[row].get<real>();
45  return mat;
46 
47  }
48 }
49 
50 
51 json encode_mat_(const cv::Mat_<real>& mat) {
52  json j = json::array();
53  if(mat.cols == 1) {
54  for(int row = 0; row < mat.rows; ++row) j.push_back(mat(row, 0));
55  } else {
56  for(int row = 0; row < mat.rows; ++row) {
57  json j_row = json::array();
58  for(int col = 0; col < mat.cols; ++col) j_row.push_back(mat(row, col));
59  j.push_back(j_row);
60  }
61  }
62  return j;
63 }
64 
65 
66 }
int rows
cv::Mat_< real > decode_mat(const json &j)
Definition: json.cc:32
double real
Definition: common.h:16
void export_json_file(const json &j, const std::string &filename, bool compact)
Definition: json.cc:9
int cols
std::string file_name_extension(const std::string &filename)
Definition: string.cc:9
nlohmann::json json
Definition: json.h:11
json import_json_file(const std::string &filename)
Definition: json.cc:24
json encode_mat_(const cv::Mat_< real > &mat)
Definition: json.cc:51