1、文件的打开关闭
XML\YAML文件在OpenCV中的数据结构为FileStorage,打开操作例如:
string filename = "I.xml";
FileStorage fs(filename, FileStorage::WRITE);
\\...
fs.open(filename, FileStorage::READ);
文件关闭操作会在FileStorage结构销毁时自动进行,但也可调用如下函数实现
fs.release();
2.文本和数字的输入和输出
写入文件使用 << 运算符,例如:
fs << "iterationNr" << 100;
读取文件,使用 >> 运算符,例如
int itNr;
fs["iterationNr"] >> itNr;
itNr = (int) fs["iterationNr"];
3. OpenCV数据结构的输入和输出,和基本的C++形式相同
Mat R = Mat_<uchar >::eye (3, 3),
T = Mat_<double>::zeros(3, 1);
fs << "R" << R; // Write cv::Mat
fs << "T" << T;
fs["R"] >> R; // Read cv::Mat
fs["T"] >> T;
4. vector(arrays) 和 maps的输入和输出
vector要注意在第一个元素前加上“[”,在最后一个元素前加上"]"。例如:
fs << "strings" << "["; // text - string sequence
fs << "image1.jpg" << "Awesomeness" << "baboon.jpg";
fs << "]"; // close sequence
对于map结构的操作使用的符号是"{"和"}",例如
fs << "Mapping"; // text - mapping
fs << "{" << "One" << 1;
fs << "Two" << 2 << "}";
读取这些结构的时候,会用到FileNode和FileNodeIterator数据结构。对FileStorage类的[]操作符会返回FileNode数据类型,对于一连串的node,可以使用FileNodeIterator结构,例如:
5、文件读取
FileNode n = fs["strings"]; // Read string sequence – Get node
if (n.type() != FileNode::SEQ)
{
cerr << "strings is not a sequence! FAIL" << endl;
return 1;
}
FileNodeIterator it = n.begin(), it_end = n.end(); // Go through the node
for (; it != it_end; ++it)
cout << (string)*it << endl;
6、例子介绍
if (filename.empty())
{
return 0;
}
cv::FileStorage fs(filename,cv::FileStorage::WRITE);
if(!fs.isOpened())
{
return 0;
}
fs<<"preFilterCap"<<stBM.state->preFilterCap;
fs<<"SADWindowSize"<<stBM.state->SADWindowSize;
fs<<"minDisparity"<<stBM.state->minDisparity;
fs<<"numberOfDisparities"<<stBM.state->numberOfDisparities;
fs<<"textureThreshold"<<stBM.state->textureThreshold;
fs<<"uniquenessRatio"<<stBM.state->uniquenessRatio;
fs<<"speckleWindowSize"<<stBM.state->speckleWindowSize;
fs<<"speckleRange"<<stBM.state->speckleRange;
fs<<"leftValidArea" ;
fs<<"{"<<"roi1x"<<stBM.state->roi1.x;
fs<<"roi1y"<<stBM.state->roi1.y;
fs<<"roi1width"<<stBM.state->roi1.width;
fs<<"roi1height"<<stBM.state->roi1.height;
fs<<"}" ;
fs<<"rightValidArea" ;
fs<<"{"<<"roi2x"<<stBM.state->roi2.x;
fs<<"roi2y"<<stBM.state->roi2.y;
fs<<"roi2width"<<stBM.state->roi2.width;
fs<<"roi2height"<<stBM.state->roi2.height;
fs<<"}" ;
fs.release();