OPenCv采用FileStorage类读写xml或者yml文件----程序

来源:互联网 发布:什么是人工智能英文 编辑:程序博客网 时间:2024/05/02 05:06
         

        Opencv采用FileStorage类读写xml文件。

        用opencv进行人脸检测时可以看到opencv自带的人脸分类器实际上是一个个的xml文件。存放在安装路径下的opencv\data\haarcascades\的文件里。如下:


       这些文件里面的数据长这样:

        那么,这些文件里的数据是怎么写入的呢,又是怎么读出来的呢?是用opencv的FileStorage类的写方式写入的。具体的示例程序如下:

#include "stdafx.h"#include <iostream>#include <sstream>#include <string>#include <time.h>#include <stdio.h>#include <opencv/cv.h>//#include <opencv2/core/core.hpp>//#include <opencv2/imgproc/imgproc.hpp>//#include <opencv2/calib3d/calib3d.hpp>//#include <opencv2/highgui/highgui.hpp>using namespace cv;using namespace std;void main(){//opencv写xml格式的文件,写入mat,int或者string等类型   Mat cameraMatrix0 = Mat::eye(3, 3, CV_64F),cameraMatrix1 = Mat::eye(3, 3, CV_64F);//Mat::eye,返回一个恒等指定大小和类型矩阵。Mat distCoeffs0= Mat::eye(1, 5, CV_64F),distCoeffs1= Mat::eye(1, 5, CV_64F);//mat矩阵型数据int rows0=1; //整数型数字string date0="2014.09.29--星期一";  //字符串型数字FileStorage fs("haha.xml", CV_STORAGE_WRITE);//用FileStorage类打开一个xml文件,方式为写。if( fs.isOpened() ){fs << "M1" << cameraMatrix0 << "D1" << distCoeffs0 <<"M2" << cameraMatrix1 << "D2" << distCoeffs1 << "rows0" <<rows0<<"date0"<<date0;fs.release();}}

        这个程序运行后就在工程里面生成了一个xml文件如下:

        这个文件打开后可以看到内容如下:

        我想要的是那些红色或蓝色的数据,而不要在尖括号里面蓝色的字母。对这样的文件进行数据读取也是采用FileStorage类里面的读方式,下面程序是读取数据存入指定类型的变量中并在command命令行里打印出来:

#include "stdafx.h"#include <iostream>#include <sstream>#include <string>#include <time.h>#include <stdio.h>#include <opencv/cv.h>using namespace cv;using namespace std;void main(){//opencv读取xml文件格式,获取其中的mat,int或者string等类型FileStorage fs("haha.xml", FileStorage::READ);//打开xml文件,以写的方式//方式一: []寻址操作符 和 >>强制转换类型int framerows = (int)fs["rows0"];  //将存储名为rows0的整数放到变量framerows里面。string date;fs["date0"] >> date; //将存储名为date0的字符串放到字符串变量date中。Mat cameraMatrix1, distCoeffs1;fs["M1"] >> cameraMatrix1;  //将存储名为M1的矩阵放到Mat型数据中。fs["D1"] >> distCoeffs1;//输出到命令行cout << endl << "M1 = " << cameraMatrix1 << endl;cout << "D1 = " << distCoeffs1<<endl; cout<< "rows0= "<< framerows<<endl;cout<< "Date= " << date  <<endl;//方式二: FileNode::operator >>()读取string类型FileNode n = fs["date0"]; //   FileNodeIterator it = n.begin(), it_end = n.end(); // 从头到尾遍历string类型依次输出每个字符for (; it != it_end; ++it)  cout << (string)*it << endl;fs.release();system("pause");}

       读出每个数据并显示到命令行,结果如下:



0 0