XML和YAML文件
XML(eXtensible Markup Lauguage)是一种元标记语言,所谓的“元标记”就是开发者可以根据自身需要定义自己的标记。XML时一种语义/结构化语言,它描述了文档的结构和语义
YAML(Ain’t a Markup Language)强调这种语言是以数据为中心的。YAML是一种可读性高,用来表示资料序列的格式
FileStorage 类操作文件的使用引导
- 实例化一个FileStorage类的对象,用默认带参数的构造函数完成初始化。或者用FileStorage::open()成员函数辅助初始化
- 使用流操作<<进行文件写入操作,或者>>进行文件读取操作。类似c++中的文件输入输出流
- 使用FileStorage::release()函数折构掉FileStorage类对象,同时关闭文件。
FileStorage::FileStorage()
FileStorage::FileStorage(const string& source ,int flags,const string& encoding=string)
XML和YAML文件的写入
#include <opencv2/opencv.hpp>
#include <time.h>
using namespace cv;
int main()
{
//初始化
FileStorage fs("test.yaml", FileStorage::WRITE);
//开始文件写入
fs << "frameCount" << 5;
time_t rawtime;
time(&rawtime);
fs << "calibrationDate" << asctime(localtime(&rawtime));
Mat cameraMatrix = (Mat_<double>(3, 3) << 1000, 0, 320, 0, 1000, 240, 0, 0, 1);
Mat disCoeffs = (Mat_<double>(5, 1) << 0.1, 0.01, -0.001, 0, 0);
fs << "cameraMatrix" << cameraMatrix << "disCoeffs" << disCoeffs;
fs << "features" << "[";
for (int i = 0; i < 3; i++)
{
int x = rand() % 640;
int y = rand() % 480;
uchar lbp = rand() % 256;
fs << "{:" << "x" << x << "y" << y << "lbp" << "[:";
for (int j = 0; j < 8; j++)
{
fs << ((lbp >> j) & 1);
}
fs << "]" << "}";
}
fs << "]";
fs.release();
printf("文件读写完毕,请在工程目录下查看生成的文件~");
getchar();
return 0;
}
%YAML:1.0
---
frameCount: 5
calibrationDate: "Wed Aug 1 11:13:44 2018\n"
cameraMatrix: !!opencv-matrix
rows: 3
cols: 3
dt: d
data: [ 1000., 0., 320., 0., 1000., 240., 0., 0., 1. ]
disCoeffs: !!opencv-matrix
rows: 5
cols: 1
dt: d
data: [ 1.0000000000000001e-01, 1.0000000000000000e-02,
-1.0000000000000000e-03, 0., 0. ]
features:
- { x:41, y:227, lbp:[ 0, 1, 1, 1, 1, 1, 0, 1 ] }
- { x:260, y:449, lbp:[ 0, 0, 1, 1, 0, 1, 1, 0 ] }
- { x:598, y:78, lbp:[ 0, 1, 0, 0, 1, 0, 1, 0 ] }
XML和YAML文件读取
#include <opencv2/opencv.hpp>
#include <time.h>
using namespace std;
using namespace cv;
int main()
{
// 改变console字体颜色
system("color 6F");
//初始化
FileStorage fs2("test.yaml", FileStorage::READ);
// 第一种方法 对FileNote操作
int frameCount = (int)fs2["frameCount"];
std::string date;
//第二种方法:使用 FileNote运算符
fs2["calibrationDate"] >> date;
Mat cameraMatrix2, disCoeffs2;
fs2["cameraMatrix"] >> cameraMatrix2;
fs2["disCoeffs"] >> disCoeffs2;
cout << "framCount: " << frameCount << endl
<< "calibration date: " << date << endl
<< "camera matrix: " << cameraMatrix2 << endl
<< "distortion coeffs: " << disCoeffs2 << endl;
FileNode features = fs2["features"];
FileNodeIterator it = features.begin(), it_end = features.end();
int idx = 0;
std::vector<uchar> lbpval;
//使用FileNoteIterator 遍历序列
for (; it != it_end; ++it, ++idx)
{
cout << "feature #" << idx << ": ";
cout << "x=" << (int)(*it)["x"] << ", y =" << (int)(*it)["y"] << ", lbp: (";
(*it)["lbp"] >> lbpval;
for (int i = 0; i < (int)lbpval.size(); i++)
{
cout << " " << (int)lbpval[i];
}
cout << ")" << endl;
}
fs2.release();
printf("\n文件读取完毕,请输入任意键结束程序~");
getchar();
return 0;
}