小案例:
把数据写入xml文件中,如图像宽高、相机标定参数等等。
如,把width=320,height=380,即1行5列、值为3的Mat,3*3的单位矩阵写入xml,形式如图:
代码:
#include <iostream>
#include "opencv2/opencv.hpp"
using namespace std;
#define XML_TEST
int main() {
#ifdef XML_TEST //写xml
int width = 320;
int height = 280;
cv::Mat r_data = cv::Mat::ones(1, 5, CV_32F) * 3;//set initial value: 3
cv::Mat r_eye = cv::Mat::eye(3, 3, CV_64F);
cv::FileStorage fs("./test.xml", cv::FileStorage::WRITE);
if(fs.isOpened())
{
//write data to xml file
fs << "width" << width << "height" << height <<"m_data" << r_data << "m_eye" << r_eye;
fs.release();//release after used
}
#else //从xml读数据
int width;
int height;
cv::Mat r_data, r_eye;
int i = 0, j = 0;
cv::FileStorage fs("./test.xml", cv::FileStorage::READ);
if(fs.isOpened()) {
//read params from xml
fs["width"] >> width;
fs["height"] >> height;
fs["m_data"] >> r_data;
fs["m_eye"] >> r_eye;
fs.release();
cout << "r_data: " << r_data << endl;
cout << "r_eye: " << endl << r_eye << endl;
cout << "[";
for (i = 0; i < r_eye.size().height; i++) {
for (j = 0; j < r_eye.size().width; j++) {
cout << r_eye.at<double>(i, j);//read every element value
if(j != r_eye.size().width - 1){
cout << ", ";
}
else if(i != r_eye.size().height - 1){
cout << ";" << endl;
} else{
cout << "]" << endl;
}
}
}
}
#endif
return 0;
}
读取结果: