加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 09:31:12 所属栏目:百科 来源:网络整理
导读:Opencv采用FileStorage类读写xml文件。 用opencv进行人脸检测时可以看到opencv自带的人脸分类器实际上是一个个的xml文件。存放在安装路径下的opencvdatahaarcascades的文件里。如下: 这些文件里面的数据长这样: 那么,这些文件里的数据是怎么写入的呢,

Opencv采用FileStorage类读写xml文件。

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


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

那么,这些文件里的数据是怎么写入的呢,又是怎么读出来的呢?是用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,CV_64F);//Mat::eye,返回一个恒等指定大小和类型矩阵。
	Mat distCoeffs0= Mat::eye(1,5,distCoeffs1= Mat::eye(1,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");
}

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读