Direct Graphical Models  v.1.7.0
serialize.h
1 // OpenCV Mat Serialization Class Interface
2 // Written by Sergey Kosov in 2015 for Project X
3 #pragma once
4 
5 #include "types.h"
6 #include "macroses.h"
7 
8 namespace DirectGraphicalModels
9 {
10  // ================================ Serialize Namespace ==============================
15  namespace Serialize
16  {
22  void to(const std::string &fileName, const Mat &m)
23  {
24  FILE *pFile = fopen(fileName.c_str(), "wb");
25  // Header
26  int height = m.rows;
27  int width = m.cols;
28  int depth = m.depth();
29  int channels = m.channels();
30 
31  fwrite(&height, sizeof(int), 1, pFile);
32  fwrite(&width, sizeof(int), 1, pFile);
33  fwrite(&depth, sizeof(int), 1, pFile);
34  fwrite(&channels, sizeof(int), 1, pFile);
35 
36  int elementSize;
37  switch (depth) {
38  case CV_8U: elementSize = 1; break;
39  case CV_8S: elementSize = 1; break;
40  case CV_16U: elementSize = 2; break;
41  case CV_16S: elementSize = 2; break;
42  case CV_32S: elementSize = 4; break;
43  case CV_32F: elementSize = 4; break;
44  case CV_64F: elementSize = 8; break;
45  default:
46  DGM_WARNING("Custom matrix type is not supported");
47  elementSize = 0;
48  break;
49  }
50 
51  fwrite(m.data, elementSize, height * width * channels, pFile);
52  fclose(pFile);
53  }
54 
59  Mat from(const std::string &fileName)
60  {
61  FILE *pFile = fopen(fileName.c_str(), "rb");
62  if (!pFile) return Mat();
63 
64  // Header
65  int height, width, depth, channels;
66 
67  fread(&height, sizeof(int), 1, pFile);
68  fread(&width, sizeof(int), 1, pFile);
69  fread(&depth, sizeof(int), 1, pFile);
70  fread(&channels, sizeof(int), 1, pFile);
71 
72  int elementSize;
73  switch (depth) {
74  case CV_8U: elementSize = 1; break;
75  case CV_8S: elementSize = 1; break;
76  case CV_16U: elementSize = 2; break;
77  case CV_16S: elementSize = 2; break;
78  case CV_32S: elementSize = 4; break;
79  case CV_32F: elementSize = 4; break;
80  case CV_64F: elementSize = 8; break;
81  default:
82  DGM_WARNING("Custom matrix type is not supported");
83  elementSize = 0;
84  break;
85  }
86 
87  Mat res(height, width, CV_MAKETYPE(depth, channels));
88  fread(res.data, elementSize, height * width * channels, pFile);
89  fclose(pFile);
90  return res;
91  }
92  }
93 }
void to(const std::string &fileName, const Mat &m)
Saves matrix m into the file fileName.
Definition: serialize.h:22
Mat from(const std::string &fileName)
Loads the matrix from file filename.
Definition: serialize.h:59