//保存数据
#include <cv.h>
using namespace std;
int
main (int argc, char **argv)
{
char filename[] = "save_cv.xml"; // file name
// (1)create sample data
int a = 10;
float b = 0.1;
cv::Mat mat[3];
for(int i=0; i<3; i++){
mat[i].create(3,3,CV_32FC1);
mat[i].setTo(cv::Scalar(i));
}
// (2)open file storage
cv::FileStorage cvfs(filename,CV_STORAGE_WRITE);
// (3)write data to file
cv::write(cvfs,"a",a);
cv::write(cvfs,"b",b);
cv::WriteStructContext ws(cvfs, "mat_array", CV_NODE_SEQ); // create node
for(int i=0; i<3; i++){
cv::write(cvfs,"",mat[i]);
}
return 0;
}
保存在save_cv.xml的内容为
<?xml version="1.0" ?>
- <opencv_storage>
<a>10</a>
<b>1.0000000149011612e-001</b>
- <mat_array>
- <_ type_id="opencv-matrix">
<rows>3</rows>
<cols>3</cols>
<dt>f</dt>
<data>0. 0. 0. 0. 0. 0. 0. 0. 0.</data>
</_>
- <_ type_id="opencv-matrix">
<rows>3</rows>
<cols>3</cols>
<dt>f</dt>
<data>1. 1. 1. 1. 1. 1. 1. 1. 1.</data>
</_>
- <_ type_id="opencv-matrix">
<rows>3</rows>
<cols>3</cols>
<dt>f</dt>
<data>2. 2. 2. 2. 2. 2. 2. 2. 2.</data>
</_>
</mat_array>
</opencv_storage>
//读取数据
#include "stdafx.h"
#include <iostream>
#include <opencv2/core/core.hpp>
using namespace cv;
using namespace std;
int main (int argc, char **argv)
{
char filename[] = "save_cv.xml"; // file name
int i,j,k;
// (1)memory space for loading data
int a;
float b;
cv::Mat mat[3];
// (2)open file storage
cv::FileStorage cvfs(filename,CV_STORAGE_READ);
// (3)read data from file storage
cv::FileNode node(cvfs.fs, NULL); // Get Top Node
a = node["a"];
b = node["b"];
cv::FileNode fn = node[string("mat_array")];
for(i=0;i<fn.size();i++){
cv::read(fn[i], mat[i]);
}
// (4)print loaded data
cout << "a:" << a << endl;
cout << "b:" << b << endl;
for(i=0; i<3; i++){
cout << "mat" << i << ":" << endl;
for(j=0;j<mat[i].rows;j++){
for(k=0;k<mat[i].cols;k++){
cout << mat[i].at<float>(j,k) << ",";
}
cout << endl;
}
}
return 0;
}