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

前端之家收集整理的这篇文章主要介绍了对XML和YAML文件实现I/O操作前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

CPOY FROM:http://blog.csdn.net/yang_xian521/article/details/6897684?reload


1. XML、YAML文件的打开和关闭

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

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

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

copy

    fs.release();

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

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

copy

    fs<<"iterationNr"<<100;

读取文件,使用 >> 运算符,例如 copy
    intitNr;
  1. fs["iterationNr"]>>itNr;
  2. itNr=(int)fs["iterationNr"];


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

copy
    MatR=Mat_<uchar>::eye(3,3),
  1. T=Mat_<double>::zeros(3,1);
  2. fs<<"R"<<R;//Writecv::Mat
  3. fs<<"T"<<T;
  4. fs["R"]>>R;//Readcv::Mat
  5. fs["T"]>>T;

4. vector(arrays) 和 maps的输入和输出
vector要注意在第一个元素前加上“[”,在最后一个元素前加上"]"。例如:

copy

    fs<<"strings"<<"[";//text-stringsequence
  1. fs<<"image1.jpg"<<"Awesomeness"<<"baboon.jpg";
  2. fs<<"]";//closesequence

对于map结构的操作使用的符号是"{"和"}",例如:
copy
    fs<<"Mapping";//text-mapping
  1. fs<<"{"<<"One"<<1;
  2. fs<<"Two"<<2<<"}";

读取这些结构的时候,会用到FileNode和FileNodeIterator数据结构。对FileStorage类的[]操作符会返回FileNode数据类型,对于一连串的node,可以使用FileNodeIterator结构,例如:
copy
    FileNoden=fs["strings"];//Readstringsequence-Getnode
  1. if(n.type()!=FileNode::SEQ)
  2. {
  3. cerr<<"stringsisnotasequence!FAIL"<<endl;
  4. return1;
  5. }
  6. FileNodeIteratorit=n.begin(),it_end=n.end();//Gothroughthenode
  7. for(;it!=it_end;++it)
  8. cout<<(string)*it<<endl;

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

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

文件里填入如下代码

copy

    #include<opencv2/core/core.hpp>
  1. #include<iostream>
  2. #include<string>
  3. usingnamespacecv;
  4. namespacestd;
  5. voidhelp(char**av)
  6. cout<<endl
  7. <<av[0]<<"showstheusageoftheOpenCVserializationfunctionality."<<endl
  8. <<"usage:"<<endl
  9. <<av[0]<<"outputfile.yml.gz"<<endl
  10. <<"TheoutputfilemaybeeitherXML(xml)orYAML(yml/yaml).Youcanevencompressitby"
  11. <<"specifyingthisinitsextensionlikexml.gzyaml.gzetc..."<<endl
  12. <<"WithFileStorageyoucanserializeobjectsinOpenCVbyusingthe<<and>>operators"<<endl
  13. <<"Forexample:-createaclassandhaveitserialized"<<endl
  14. <<"-useittoreadandwritematrices."<<endl;
  15. }
  16. classMyData
  17. {
  18. public:
  19. MyData():A(0),X(0),id()
  20. {}
  21. explicitMyData(int):A(97),X(CV_PI),id("mydata1234")//explicittoavoidimplicitconversion
  22. voidwrite(FileStorage&fs)const//Writeserializationforthisclass
  23. fs<<"{"<<"A"<<A<<"X"<<X<<"id"<<id<<"}";
  24. voidread(constFileNode&node)//Readserializationforthisclass
  25. A=(int)node["A"];
  26. X=(double)node["X"];
  27. id=(string)node["id"];
  28. public://DataMembers
  29. @H_301_680@intA;
  30. doubleX;
  31. stringid;
  32. };
  33. //ThesewriteandreadfunctionsmustbedefinedfortheserializationinFileStoragetowork
  34. voidwrite(FileStorage&fs,conststd::string&,153); background-color:inherit; font-weight:bold">constMyData&x)
  35. x.write(fs);
  36. constFileNode&node,MyData&x,153); background-color:inherit; font-weight:bold">constMyData&default_value=MyData()){
  37. if(node.empty())
  38. x=default_value;
  39. else
  40. x.read(node);
  41. //Thisfunctionwillprintourcustomclasstotheconsole
  42. ostream&operator<<(ostream&out,constMyData&m)
  43. out<<"{id="<<m.id<<",";
  44. out<<"X="<<m.X<<",";
  45. out<<"A="<<m.A<<"}";
  46. returnout;
  47. @H_301_680@intmain(intac,char**av)
  48. if(ac!=2)
  49. help(av);
  50. return1;
  51. stringfilename=av[1];
  52. {//write
  53. MatR=Mat_<uchar>::eye(3,
  54. MyDatam(1);
  55. FileStoragefs(filename,FileStorage::WRITE);
  56. fs<<"iterationNr"<<100;
  57. fs<<"strings"<<"[";//text-stringsequence
  58. fs<<"image1.jpg"<<"Awesomeness"<<"baboon.jpg";
  59. fs<<"]";//closesequence
  60. fs<<"Mapping";//text-mapping
  61. fs<<"{"<<"One"<<1;
  62. fs<<"Two"<<2<<"}";
  63. fs<<"R"<<R;//cv::Mat
  64. fs<<"T"<<T;
  65. fs<<"MyData"<<m;//yourowndatastructures
  66. fs.release();//explicitclose
  67. cout<<"WriteDone."<<endl;
  68. {//read
  69. cout<<endl<<"Reading:"<<endl;
  70. FileStoragefs;
  71. 301_680@intitNr;
  72. //fs["iterationNr"]>>itNr;
  73. itNr=(int)fs["iterationNr"];
  74. cout<<itNr;
  75. if(!fs.isOpened())
  76. cerr<<"Failedtoopen"<<filename<<endl;
  77. FileNoden=fs["strings"]; FileNodeIteratorit=n.begin(),0); background-color:inherit">//Gothroughthenode
  78. for(;it!=it_end;++it)
  79. cout<<(string)*it<<endl;
  80. n=fs["Mapping"];//Readmappingsfromasequence
  81. cout<<"Two"<<(int)(n["Two"])<<";";
  82. cout<<"One"<<(int)(n["One"])<<endl<<endl;
  83. MyDatam;
  84. MatR,T;
  85. fs["T"]>>T;
  86. fs["MyData"]>>m;//Readyourownstructure_
  87. cout<<endl
  88. <<"R="<<R<<endl;
  89. cout<<"T="<<T<<endl<<endl;
  90. cout<<"MyData="<<endl<<m<<endl<<endl;
  91. //Showdefaultbehaviorfornonexistingnodes
  92. cout<<"AttempttoreadNonExisting(shouldinitializethedatastructurewithitsdefault).";
  93. fs["NonExisting"]>>m;
  94. cout<<endl<<"NonExisting="<<endl<<m<<endl;
  95. <<"Tip:Openup"<<filename<<"withatexteditortoseetheserializeddata."<<endl;
  96. return0;
  97. }

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

[html] copy
    <?xmlversion="1.0"?>
  1. -<opencv_storage>
  2. iterationNr>100</>
  3. strings>image1.jpgAwesomenessbaboon.jpg -MappingOne>1Two>2Rtype_id="opencv-matrix"rows>3colsdt>udata>100010001RTtype_id="opencv-matrix">d>0.0.0.TMyDataA>97X>3.1415926535897931e+000id>mydata1234>

猜你在找的XML相关文章