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");
}
讀出每個資料并顯示到指令行,結果如下: