源码
链接 link
#include <opencv2/core.hpp>
#include <iostream>
#include <string>
using namespace cv;
using namespace std;
// 帮助信息函数
static void help(char** av)
{
cout << endl
<< av[0] << " shows the usage of the OpenCV serialization functionality." << endl
<< "usage: " << endl
<< av[0] << " outputfile.yml.gz" << endl
<< "The output file may be either XML (xml) or YAML (yml/yaml). You can even compress it by "
<< "specifying this in its extension like xml.gz yaml.gz etc... " << endl
<< "With FileStorage you can serialize objects in OpenCV by using the << and >> operators" << endl
<< "For example: - create a class and have it serialized" << endl
<< " - use it to read and write matrices." << endl;
}
// 自定义数据结构 MyData
// 主要提供序列化和反序列化相关的读写功能
class MyData
{
public:
MyData() : A(0), X(0), id() {
}
explicit MyData(int) : A(97), X(CV_PI), id("mydata1234") {
}
void write(FileStorage& fs) const
{
fs << "{" << "A" << A << "X" << X << "id" << id << "}";
}
void read(const FileNode& node)
{
A = (int)node["A"];
X = (double)node["X"];
id = (string)node["id"];
}
public:
int A;
double X;
string id;
};
// 序列化和反序列化的辅助函数
static void write(FileStorage& fs, const std::string&, const MyData& x)
{
x.write(fs);
}
static void read(const FileNode& node, MyData& x, const MyData& default_value = MyData())
{
if (node.empty())
x = default_value