一. 实验描述
用OpenCV来进行XML和YAML文件的写入和读取。
二. 实验代码
//XML和YAML文件的写入
class Task11 {
public:
void deal() {
FileStorage fs("test.xml",FileStorage::WRITE);
// FileStorage fs("test.yaml",FileStorage::WRITE);
fs << "frame_count" << 5;
time_t rawtime;
time(&rawtime);
fs << "time" << asctime(localtime(&rawtime));
Mat camera_mat = (Mat_<double>(3,3) << 1000,0,320,1000,240,1);
Mat dist_coeffs = (Mat_<double>(5,1) << 0.1,0.01,-0.001,0);
fs << "camera_mat" << camera_mat << "dist_coeffs" << dist_coeffs;
fs << "features" << "[";
for (int i = 0; i < 3; ++i) {
int x = rand() % 640;
int y = rand() % 480;
uchar lbp = rand() % 256;
fs << "{:" << "x" << x << "y" << y << "lbp" << "[:";
for (int j = 0; j < 8; ++j) {
fs << ((lbp >> j) & 1);
}
fs << "]" << "}";
}
fs << "]";
fs.release();
printf("生成文件完毕\n");
}
};
//XML和YAML文件的读取
class Task12 {
public:
void deal() {
FileStorage fs("test.xml",FileStorage::READ);
// FileStorage fs("test.yaml",FileStorage::READ);
int frame_count = fs["frame_count"]; //bug
cout << "frame_count: " << frame_count << endl;
string time;
fs["time"] >> time;
cout << "time:" << time << endl;
Mat camera_mat;
fs["camera_mat"] >> camera_mat;
cout << "camera_mat:" << camera_mat << endl;
Mat dist_coeffs;
fs["dist_coeffs"] >> dist_coeffs;
cout << "dist_coeffs:" << dist_coeffs << endl;
FileNode features = fs["features"];
FileNodeIterator it = features.begin(),it_end = features.end();
int idx = 0;
vector<uchar> ibpval;
for (; it != it_end; ++it,++idx) {
cout << "features #" << idx << ":";
cout << "x=" << (int)(*it)["x"] << ",y=" << (int)(*it)["y"] << ",lbp:(";
(*it)["lbp"] >> ibpval;
for (int i = 0; i < ibpval.size(); ++i) {
cout << " " << (int)ibpval[i];
}
cout << ")" << endl;
}
fs.release();
}
};
三. 实验结果
<?xml version="1.0"?>
<opencv_storage>
<frame_count>5</frame_count>
<time>"Sat Aug 27 22:04:44 2016
"</time>
<camera_mat type_id="opencv-matrix">
<rows>3</rows>
<cols>3</cols>
<dt>d</dt>
<data>
1000. 0. 320. 0. 1000. 240. 0. 0. 1.</data></camera_mat>
<dist_coeffs type_id="opencv-matrix">
<rows>5</rows>
<cols>1</cols>
<dt>d</dt>
<data>
1.0000000000000001e-001 1.0000000000000000e-002
-1.0000000000000000e-003 0. 0.</data></dist_coeffs>
<features>
<_><x>41</x>
<y>227</y>
<lbp>
0 1 1 1 1 1 0 1</lbp></_>
<_><x>260</x>
<y>449</y>
<lbp>
0 0 1 1 0 1 1 0</lbp></_>
<_><x>598</x>
<y>78</y>
<lbp>
0 1 0 0 1 0 1 0</lbp></_></features>
</opencv_storage>
%YAML:1.0
frame_count: 5
time: "Sat Aug 27 22:03:38 2016\n"
camera_mat: !!opencv-matrix
rows: 3
cols: 3
dt: d
data: [ 1000.,0.,320.,1000.,240.,1. ]
dist_coeffs: !!opencv-matrix
rows: 5
cols: 1
dt: d
data: [ 1.0000000000000001e-001,1.0000000000000000e-002,-1.0000000000000000e-003,0.,0. ] features:
- { x:41,y:227,lbp:[ 0,1,1 ] } - { x:260,y:449,0 ] } - { x:598,y:78,0 ] }
@H_32_502@ 原文链接:https://www.f2er.com/xml/294862.html