OpenCV------- 对XML和YAML文件实现I/O操作

来源:互联网 发布:云计算产业的盈利模式 编辑:程序博客网 时间:2024/05/18 01:31

 

OpenCV——XMLYAML文件实现I/O操作


1. XMLYAML文件的打开和关闭

XML\YAML文件在OpenCV中的数据结构为FileStorage,打开操作例如:

[cpp] view plaincopy

  1. string filename = "I.xml";  
  2. FileStorage fs(filename, FileStorage::WRITE);  
  3. \\...  
  4. fs.open(filename, FileStorage::READ);  


文件关闭操作会在FileStorage结构销毁时自动进行,但也可调用如下函数实现

[cpp] view plaincopy

  1. fs.release();  

 

2.文本和数字的输入和输出

写入文件使用  <<  运算符,例如:

[cpp] view plaincopy

  1. fs << "iterationNr" << 100;  


读取文件,使用 >> 运算符,例如

[cpp] view plaincopy

  1. int itNr;  
  2. fs["iterationNr"] >> itNr;  
  3. itNr = (int) fs["iterationNr"];  



3. OpenCV
数据结构的输入和输出,和基本的C++形式相同

[cpp] view plaincopy

  1. Mat R = Mat_<uchar >::eye (3, 3),  
  2. T = Mat_<double>::zeros(3, 1);  
  3. fs << "R" << R; // Write cv::Mat  
  4. fs << "T" << T;  
  5. fs["R"] >> R; // Read cv::Mat  
  6. fs["T"] >> T;  



4. vector
arrays maps的输入和输出

vector要注意在第一个元素前加上“[”,在最后一个元素前加上"]"。例如:

[cpp] view plaincopy

  1. fs << "strings" << "["// text - string sequence  
  2. fs << "image1.jpg" << "Awesomeness" << "baboon.jpg";  
  3. fs << "]"// close sequence  


对于map结构的操作使用的符号是"{""}",例如:

[cpp] view plaincopy

  1. fs << "Mapping"// text - mapping  
  2. fs << "{" << "One" << 1;  
  3. fs << "Two" << 2 << "}";  


读取这些结构的时候,会用到FileNodeFileNodeIterator数据结构。

FileStorage类的[]操作符会返回FileNode数据类型,对于一连串的node,可以使用FileNodeIterator结构,例如:

[cpp] view plaincopy

  1. FileNode n = fs["strings"]; // Read string sequence - Get node  
  2. if (n.type() != FileNode::SEQ)  
  3. {  
  4. cerr << "strings is not a sequence! FAIL" << endl;  
  5. return 1;  
  6. }  
  7. FileNodeIterator it = n.begin(), it_end = n.end(); // Go through the node  
  8. for (; it != it_end; ++it)  
  9. cout << (string)*it << endl;  


5.
读写自己的数据结构

这部分比较复杂,参考最后的实例中的MyData结构自己领悟吧

最后,我这里上一个实例,供大家参考。

源文件里填入如下代码:

[cpp] view plaincopy

  1. #include <opencv2/core/core.hpp>  
  2. #include <iostream>  
  3. #include <string>  
  4.   
  5. using namespace cv;  
  6. using namespace std;  
  7.   
  8. void help(char** av)  
  9. {  
  10.     cout << endl   
  11.         << av[0] << " shows the usage of the OpenCV serialization functionality."         << endl  
  12.         << "usage: "                                                                      << endl  
  13.         <<  av[0] << " outputfile.yml.gz"                                                 << endl  
  14.         << "The output file may be either XML (xml) or YAML (yml/yaml). You can even compress it by "  
  15.         << "specifying this in its extension like xml.gz yaml.gz etc... "                  << endl  
  16.         << "With FileStorage you can serialize objects in OpenCV by using the << and >> operators" << endl  
  17.         << "For example: - create a class and have it serialized"                         << endl  
  18.         << "             - use it to read and write matrices."                            << endl;  
  19. }  
  20.   
  21. class MyData  
  22. {  
  23. public:  
  24.     MyData() : A(0), X(0), id()  
  25.     {}  
  26.     explicit MyData(int) : A(97), X(CV_PI), id("mydata1234"// explicit to avoid implicit conversion  
  27.     {}  
  28.     void write(FileStorage& fs) const                        //Write serialization for this class  
  29.     {  
  30.         fs << "{" << "A" << A << "X" << X << "id" << id << "}";  
  31.     }  
  32.     void read(const FileNode& node)                          //Read serialization for this class  
  33.     {  
  34.         A = (int)node["A"];  
  35.         X = (double)node["X"];  
  36.         id = (string)node["id"];  
  37.     }  
  38. public:   // Data Members  
  39.     int A;  
  40.     double X;  
  41.     string id;  
  42. };  
  43.   
  44. //These write and read functions must be defined for the serialization in FileStorage to work  
  45. void write(FileStorage& fs, const std::string&, const MyData& x)  
  46. {  
  47.     x.write(fs);  
  48. }  
  49. void read(const FileNode& node, MyData& x, const MyData& default_value = MyData()){  
  50.     if(node.empty())  
  51.         x = default_value;  
  52.     else  
  53.         x.read(node);  
  54. }  
  55.   
  56. // This function will print our custom class to the console  
  57. ostream& operator<<(ostream& out, const MyData& m)   
  58. {   
  59.     out << "{ id = " << m.id << ", ";  
  60.     out << "X = " << m.X << ", ";  
  61.     out << "A = " << m.A << "}";  
  62.     return out;  
  63. }  
  64.   
  65. int main(int ac, char** av)  
  66. {  
  67.     if (ac != 2)  
  68.     {  
  69.         help(av);  
  70.         return 1;  
  71.     }  
  72.   
  73.     string filename = av[1];  
  74.     { //write  
  75.         Mat R = Mat_<uchar>::eye(3, 3),  
  76.             T = Mat_<double>::zeros(3, 1);  
  77.         MyData m(1);  
  78.   
  79.         FileStorage fs(filename, FileStorage::WRITE);  
  80.   
  81.         fs << "iterationNr" << 100;  
  82.         fs << "strings" << "[";                              // text - string sequence  
  83.         fs << "image1.jpg" << "Awesomeness" << "baboon.jpg";  
  84.         fs << "]";                                           // close sequence  
  85.           
  86.         fs << "Mapping";                              // text - mapping  
  87.         fs << "{" << "One" << 1;  
  88.         fs <<        "Two" << 2 << "}";                 
  89.   
  90.         fs << "R" << R;                                      // cv::Mat  
  91.         fs << "T" << T;  
  92.   
  93.         fs << "MyData" << m;                                // your own data structures  
  94.   
  95.         fs.release();                                       // explicit close  
  96.         cout << "Write Done." << endl;  
  97.     }  
  98.   
  99.     {//read  
  100.         cout << endl << "Reading: " << endl;  
  101.         FileStorage fs;   
  102.         fs.open(filename, FileStorage::READ);  
  103.   
  104.         int itNr;   
  105.         //fs["iterationNr"] >> itNr;  
  106.         itNr = (int) fs["iterationNr"];  
  107.         cout << itNr;  
  108.         if (!fs.isOpened())  
  109.         {  
  110.             cerr << "Failed to open " << filename << endl;  
  111.             help(av);  
  112.             return 1;  
  113.         }  
  114.   
  115.         FileNode n = fs["strings"];                         // Read string sequence - Get node  
  116.         if (n.type() != FileNode::SEQ)  
  117.         {  
  118.             cerr << "strings is not a sequence! FAIL" << endl;  
  119.             return 1;  
  120.         }  
  121.   
  122.         FileNodeIterator it = n.begin(), it_end = n.end(); // Go through the node  
  123.         for (; it != it_end; ++it)  
  124.             cout << (string)*it << endl;  
  125.           
  126.           
  127.         n = fs["Mapping"];                                // Read mappings from a sequence  
  128.         cout << "Two  " << (int)(n["Two"]) << "; ";   
  129.         cout << "One  " << (int)(n["One"]) << endl << endl;   
  130.           
  131.   
  132.         MyData m;  
  133.         Mat R, T;  
  134.   
  135.         fs["R"] >> R;                                      // Read cv::Mat  
  136.         fs["T"] >> T;  
  137.         fs["MyData"] >> m;                                 // Read your own structure_  
  138.   
  139.         cout << endl   
  140.             << "R = " << R << endl;  
  141.         cout << "T = " << T << endl << endl;  
  142.         cout << "MyData = " << endl << m << endl << endl;  
  143.   
  144.         //Show default behavior for non existing nodes  
  145.         cout << "Attempt to read NonExisting (should initialize the data structure with its default).";    
  146.         fs["NonExisting"] >> m;  
  147.         cout << endl << "NonExisting = " << endl << m << endl;  
  148.     }  
  149.   
  150.     cout << endl   
  151.         << "Tip: Open up " << filename << " with a text editor to see the serialized data." << endl;  
  152.   
  153.     return 0;  
  154. }  


编译后,在命令行进入到文件目录,执行test test.xml,运行结果如下,生成一个test . xml文件,内容如下:

[html] view plaincopy

  1.   <?xml version="1.0" ?>   
  2. <opencv_storage>  
  3.   <iterationNr>100</iterationNr>   
  4.   <strings>image1.jpg Awesomeness baboon.jpg</strings>   
  5. <Mapping>  
  6.   <One>1</One>   
  7.   <Two>2</Two>   
  8.   </Mapping>  
  9. <R type_id="opencv-matrix">  
  10.   <rows>3</rows>   
  11.   <cols>3</cols>   
  12.   <dt>u</dt>   
  13.   <data>1 0 0 0 1 0 0 0 1</data>   
  14.   </R>  
  15. <T type_id="opencv-matrix">  
  16.   <rows>3</rows>   
  17.   <cols>1</cols>   
  18.   <dt>d</dt>   
  19.   <data>0. 0. 0.</data>   
  20.   </T>  
  21. <MyData>  
  22.   <A>97</A>   
  23.   <X>3.1415926535897931e+000</X>   
  24.   <id>mydata1234</id>   
  25.   </MyData>  
  26.   </opencv_storage>  

 

 

0 0