什么是XML和YAML
示例程序:XML和YAML文件的写入
示例程序:XML和YAML文件的读取
什么是XML和YAML
XML(eXtensible Markup Language)是一种元标记语言。所谓“原标记”,就是开发者可以根据自身需要定义的标记,任何满足XML命名规则的名称都可以标记。此外,XML是一种语义/结构化语言,它描述了文档的结构和语义。
YAML(YAML Ain’t a Markup Language)也是一种置标语言,但它是以数据为中心,而不是以置标语言为重点,用来表达资料序列的格式。
示例程序:XML和YAML文件的写入
让我们先看一个关于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>(5, 1) << 1000, 0, 320, 0, 1000);
Mat distCoeffs = (Mat_<double>(5, 1) << 0.1, 0.01, -0.001, 0, 0);
fs << "cameraMatrix" << cameraMatrix << "distCoeffs" << distCoeffs;
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;
}
效果图
运行此程序,会在工程目录下程序一个名为“test.yaml”的文件
用sublime打开
如果我们修改上面的代码的FileStorage fs(“test.yaml”,FileStorage::WRITE)这一句代码,将其中的“test.yaml”的后缀换为xml、yml、txt甚至doc,都可以得到运行结果的,大家不妨尝试一下。
示例程序: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
<< "calibration 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:(";
(*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;
}
效果图:
此程序需要工程目录下指定文件存在,如我们之前刚刚生成的test.yaml复制到工程目录下,运行此程序,便可以得到正确的结果。