示例程序:XML和YAML文件的写入
//----------------输入输出XML和YAML文件------------------------------------
//描述:XML:可扩展标识语言----开发者根据自身需要可定义自己的标记。后缀:.yml
// TAML:是一个可读性高,用来表达资料序列的格式。后缀:.yaml
// 储存类为:FileStorage
//----------------------------------------------------------------------
//----------------【XML和YAML文件的写入】---------------------
// "<<"文件写入操作;“>>”文件读取操作
//vector(arrays)结构的输入输出在第一个元素前加“[”,最后一个元素上加“[”
//map结构的操作使用符号“{”和“}”
#include <opencv2/opencv.hpp>
#include <time.h>
using namespace cv;
#define _CRT_SECURE_NO_WARNINGS
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 distCoeffs = (Mat_<double>(5,1)<<0.1,0.01,-0.001,0,0);
//向Mat中写入数据
fs << "cameraMatrix" <<cameraMatrix<<"distCoffs"<<distCoeffs ;
fs << "features" << "[";//开始读入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;
}
运行结果:
XML和YAML文件的读取:
//-----------------【XML和YAML文件的读取】---------------------------
#include <opencv2/opencv.hpp>
#include <time.h>
using namespace cv;
using namespace std;
int main() {
//改变console字体颜色
system("color 6F");
//初始化
FileStorage fs2("test.yaml",FileStorage::READ);//要读取的文件
//第一种方法,对FileNode操作
int frameCount = (int)fs2["frameCount"];
std::string date;
//第二种方法,使用FileNode运算符>>
fs2["calibrationDate"] >> date;
Mat cameraMatrix2, distCoeffs2;
fs2["cameraMatrix"] >> cameraMatrix2;
fs2["distCoeffs"] >> distCoeffs2;
cout << "frameCount:" << frameCount << endl
<< "calibratioin date:"<<date << endl
<< "camera matrix:" << cameraMatrix2 << endl
<< "distortion coeffs:" << distCoeffs2 << endl;
FileNode features = fs2["features"];
FileNodeIterator it = features.begin(), it_end = features.end();
int idx = 0;
std::vector<uchar> lbpval;
//使用FileNodeIterator遍历序列
for (; it != it_end;++it,idx++) {
cout << "feature #" << idx << ":";
cout << "x=" << (int)(*it)["x"] << ",y=" << (int)(*it)["y"] << ", lbp: (";
//我们也可以使用filenode>>std::veator操作符来很容易的读数值阵列
(*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;
}
运行结果: