经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » C++ » 查看文章
C++ OpenCV读写XML或YAML文件的方法详解
来源:jb51  时间:2022/5/9 11:08:00  对本文有异议

前言

本节我们将认识XML和YAML这两种文件类型。

所谓XML,即eXtensible Markup Language,翻译成中文为“可扩展标识语言”。首先,XML是一种元标记语言。所谓元标记,就是开发者可以根据自身需要定义自己的标记,比如可以定义标记<book>、<name>。任何满足XML命名规则的名称都可以标记,这就向不同的应用程序打开了的大门。此外,XML是一种语义、结构化语言,它描述了文档的结构与语义。

YAML是YAML Ain’t a Markup Language(YAML不是一种置标语言)的缩写。YAML是一个可读性高,用来表达资料序列的格式。它参考了其他多种语言,包括:XML、C语言、Python、Perl以及电子邮件格式RFC2822。

1.如何使用

XML和YAML是使用非常广泛的文件格式。可以利用XML或者YAML格式的文件存储和还原各式各样的数据结构。当然,它们还可以存储和载入任意复杂的数据结构,其中就包括了OpenCV相关周边的数据结构,以及各种原始数据类型,如整数、浮点数和文本字符串。

我们一般使用如下过程来写入或者读取数据到XML或YAML文件中。

(1)实例化一个FileStorage类的对象,用默认带参数的构造函数完成初始化,或者用FileStorage::open()成员函数辅助初始化。

(2)使用流操作符<<进行文件写入操作,或者>>进行文件读取操作,类似C++中的文件输入输出流。

(3)使用FileStorage::release()函数析构掉FileStorage类对象,同时关闭文件。

1.1第一步:XML、YAML文件的打开

(1)准备文件写操作

FileStorage是OpenCV中XML和YAML文件的存储类,封装了所有相关的信息。它是OpenCV从文件中读数据或向文件中写数据时必须要使用的一个类。

此类的构造函数为FileStorage::FileStorage,有两个重载,如下:

  1. C++:FileStorage::FileStorage()
  2. C++:FileStorage::FileStorage(const string& source, int flags, const string& encoding=string())

构造函数在实际使用中,一般有两种方法。

1)对于第二种带参数的构造函数,进行写操作范例如下:

  1. FileStorage fs("abc.xml", FileStorage::WRITE);

2)对于第一种不带参数的构造函数,可以使用其成员函数FileStorage::open进行数据的写操作,范例如下:

  1. FileStorage fs;
  2. fs.open("abc.xml",FileStorage::WRITE);

(2)准备文件读操作

上面讲到的都是以FileStorage::WRITE为标识符的写操作,而读操作,采用FileStorage::READ标识符即可,相关示例代码如下:

1)第一种方式

  1. FileStorage fs(“abc.xml”, FileStorage::READ);

2)第二种方式

  1. FileStorage fs;
  2. fs.open(“abc.xml”, FileStorage::READ);

另外需要注意的是,上面的这些操作示例是对XML文件为例子作演示的,而对YAML文件,操作方法是类似的,就是将XML文件换为YAML文件即可。

1.2 第二步:进行文件读写操作

(1)文本和数字的输入和输出

定义好FileStorage类对象之后,写入文件可以使用<<运算符,例如:

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

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

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

(2)OpenCV数据结构的输入和输出

关于OpenCV数据结构的输入和输出,和基本的C++形式相同,范例如下:

  1. // 数据结构的初始化
  2. Mat R = Mat_<uchar>::eye(3,3);
  3. Mat T = Mat_<double>::zeros(3, 1);
  4. // 向Mat中写入数据
  5. fs << "R" << R;
  6. fs << "T" << T;
  7. // 从Mat中读取数据
  8. fs["R"] >> R;
  9. fs["T"] >> T;

1.3 第三步:vector(array)和map的输入和输出

对于vector结构的输出和输出,要注意在第一个元素前加上”[“,在最后一个元素后加上”]“。例如:

  1. fs << "strings"<<"["; //开始读入string文本序列
  2. fs << "image1.jpg" << "Awesomeness" << "baboon.jpg";
  3. fs << "]"; //关闭序列

而对于map结构的操作,使用的符号是”{“和”}“,例如:

  1. fs << "Mapping";//开始读入Mapping文本
  2. fs << "{" << "One" << 1;
  3. fs << "Two" << 2 << "}";

读取这些数据结构的时候,会用到FileNode和FileNodeIterator数据结构。对FileStorage类的“[”、“]”操作符会返回FileNode数据类型;对于一连串的node,可以使用FileNodeIterator结构,例如:

  1. ```cpp
  2. FileNode n = fs["strings"];//读取字符串序列以得到节点
  3. if (n.type()!=FileNode::SEQ)
  4. {
  5. cerr << "发生错误!字符串不是一个序列" << endl;
  6. return 1;
  7. }
  8. FileNodeIterator it = n.begin(),it_end = n.end(); //遍历节点
  9. for(;it!=it_end;it++)
  10. cout << (string)*it << endl;

1.4 第四步:文件关闭

需要注意的是,文件关闭操作会在FileStorage类销毁时自动进行,但我们也可以显式调用其析构函数FileStorage::release()实现。FileStorage::release()函数会析构掉FileStorage类对象,同时关闭文件。

调用过程非常简单,如下:fs.release();

2.代码展示

2.1 写文件

  1. #include<opencv2/opencv.hpp>
  2. #include<time.h>
  3. using namespace cv;
  4.  
  5. int main()
  6. {
  7. //初始化
  8. FileStorage fs("test.yaml", FileStorage::WRITE);
  9.  
  10. //开始文件写入
  11. fs << "frameCount" << 5;
  12. time_t rawtime; time(&rawtime);
  13. fs << "calibrationDate" << asctime(localtime(&rawtime));//读取时间量
  14. Mat cameraMatrix = (Mat_<double>(3, 3) << 1000, 0, 320, 0, 1000, 240, 0, 0, 1);
  15. Mat distCoeffs = (Mat_<double>(5, 1) << 0.1, 0.01, -0.001, 0, 0);//畸变参数
  16. fs << "cameraMatrix" << cameraMatrix << "distCoeffs" << distCoeffs;//读取Mat型cameraMatrix,distcoeffs的内容
  17. fs << "feature" << "[";
  18. for (int i = 0; i < 3; i++)
  19. {
  20. int x = rand() % 640;
  21. int y = rand() % 480;
  22. uchar ibp = rand() % 256;
  23.  
  24. fs << "{:" << "x" << x << "y" << y << "ibp" << "[:";
  25. for (int j = 0; j < 8; j++)
  26. fs << ((ibp >> j) & 1);
  27. fs << "]" << "}";
  28. }
  29. fs << "]";
  30. fs.release();
  31. printf("完毕,请在工程目录下查看文件-");
  32. getchar();
  33.  
  34. return 0;
  35. }

上面的示例将一个整数、一个文本字符串(标定日期)、2 个矩阵和一个自定义结构“feature”存储到 YML,其中包括特征坐标和 LBP(局部二进制模式)值。这是样本的输出:

%YAML:1.0
frameCount: 5
calibrationDate: "Fri Jun 17 14:09:29 2011\n"
cameraMatrix: !!opencv-matrix
   rows: 3
   cols: 3
   dt: d
   data: [ 1000., 0., 320., 0., 1000., 240., 0., 0., 1. ]
distCoeffs: !!opencv-matrix
   rows: 5
   cols: 1
   dt: d
   data: [ 1.0000000000000001e-01, 1.0000000000000000e-02,
       -1.0000000000000000e-03, 0., 0. ]
features:
   - { x:167, y:49, lbp:[ 1, 0, 0, 1, 1, 0, 1, 1 ] }
   - { x:298, y:130, lbp:[ 0, 0, 0, 1, 0, 0, 1, 1 ] }
   - { x:344, y:158, lbp:[ 1, 1, 0, 0, 0, 0, 1, 0 ] }

作为练习,您可以将上面示例中的“.yml”替换为“.xml”或“.json”,然后查看相应的 XML 文件的外观。

通过查看示例代码和输出可以注意到几件事:

  • 生成的 YAML(和 XML/JSON)由可以嵌套的异构集合组成。有两种类型的集合:命名集合(映射)和未命名集合(序列)。在映射中,每个元素都有一个名称并通过名称访问。这类似于 C/C++ 中的std::map结构以及 Python 中的字典。在序列中元素没有名称,它们通过索引访问。这类似于 C/C++ 中的std::vector数组以及 Python 中的列表、元组。“异构”意味着每个单一集合的元素可以有不同的类型。
  • YAML/XML/JSON 中的顶级集合是一个映射。每个矩阵存储为一个映射,矩阵元素存储为一个序列。然后,有一个特征序列,其中每个特征都表示一个映射,以及嵌套序列中的 lbp 值。
  • 当您写入映射(结构)时,您写入元素名称后跟其值。当您写入一个序列时,您只需一个一个地写入元素。OpenCV 数据结构(例如cv::Mat)的编写方式与简单的 C 数据结构完全相同 - 使用<<运算符。
  • 要编写映射,首先写入特殊字符串{,然后将元素作为对 ( fs << <element_name> << <element_value>) 写入,然后写入结束符}。
  • 要编写一个序列,首先要编写特殊的字符串[,然后编写元素,然后编写结束]。
  • 在 YAML/JSON(但不是 XML)中,映射和序列可以以类似 Python 的紧凑内联形式编写。在上面的示例中,矩阵元素以及每个特征,包括它的 lbp 值,都以这种内联形式存储。要以紧凑的形式存储映射/序列,请放在:开始字符之后,例如使用{:代替{和[:代替[。当数据写入 XML 时,那些额外:的将被忽略。

2.2 读文件

  1. #include<opencv2/opencv.hpp>
  2. #include<time.h>
  3. using namespace cv;
  4. using namespace std;
  5.  
  6. int main()
  7. {
  8. //改变consolo字体颜色
  9. system("color 6F");
  10.  
  11. //初始化
  12. FileStorage fs2("test.yaml", FileStorage::READ);
  13.  
  14. //开始文件读取
  15. //法一,对FileNode操作
  16. int frameCount2 = (int)fs2["framecount2"];
  17. std::string date;//定义字符串 date
  18.  
  19. //法二,使用FileNode运算符>>
  20. fs2["calibrationDate"] >> date;
  21.  
  22. Mat cameraMatrix2, distCoeffs2;
  23. fs2["cameraMatrix"] >> cameraMatrix2;
  24. fs2["distCoeffs"] >> distCoeffs2;//读取
  25.  
  26. cout << "frameCount2:" << frameCount2 << endl
  27. << "calibration date:" << date << endl
  28. << "camera matrix:" << cameraMatrix2 << endl
  29. << "distortion coeffs:" << distCoeffs2 << endl;
  30.  
  31. FileNode feature = fs2["feature"];
  32. FileNodeIterator it = feature.begin(), it_end = feature.end();//定义it
  33. int idx = 0;
  34. std::vector<uchar>ibpval;//定义向量容器ibpal
  35.  
  36. //使用FileNodeIterator历遍序列(读取)
  37. for (; it != it_end; it++, idx++)
  38. {
  39. cout << "feature#" << idx << ":";
  40. cout << "x=" << (int)(*it)["x"] << ",y=" << (int)(*it)["y"] << ",ibp:(";
  41. //也可以使用filenod>>std::vector操作符很容易读取数值阵列
  42. (*it)["ibp"] >> ibpval;
  43. for (int i = 0; i < (int)ibpval.size(); i++)
  44. cout << "" << (int)ibpval[i];
  45. cout << ")" << endl;
  46. }
  47.  
  48.  
  49. fs2.release();
  50. printf("读取完毕,请按任意键结束-");
  51. getchar();
  52.  
  53. return 0;
  54. }

2.3 完整的示例代码

  1. /*
  2. * filestorage_sample demonstrate the usage of the opencv serialization functionality
  3. */
  4. #include "opencv2/core.hpp"
  5. #include <iostream>
  6. #include <string>
  7. using std::string;
  8. using std::cout;
  9. using std::endl;
  10. using std::cerr;
  11. using std::ostream;
  12. using namespace cv;
  13. static void help(char** av)
  14. {
  15. cout << "\nfilestorage_sample demonstrate the usage of the opencv serialization functionality.\n"
  16. << "usage:\n"
  17. << av[0] << " outputfile.yml.gz\n"
  18. << "\n outputfile above can have many different extensions, see below."
  19. << "\nThis program demonstrates the use of FileStorage for serialization, that is in use << and >> in OpenCV\n"
  20. << "For example, how to create a class and have it serialize, but also how to use it to read and write matrices.\n"
  21. << "FileStorage allows you to serialize to various formats specified by the file end type."
  22. << "\nYou should try using different file extensions.(e.g. yaml yml xml xml.gz yaml.gz etc...)\n" << endl;
  23. }
  24. struct MyData
  25. {
  26. MyData() :
  27. A(0), X(0), id()
  28. {
  29. }
  30. explicit MyData(int) :
  31. A(97), X(CV_PI), id("mydata1234")
  32. {
  33. }
  34. int A;
  35. double X;
  36. string id;
  37. void write(FileStorage& fs) const //Write serialization for this class
  38. {
  39. fs << "{" << "A" << A << "X" << X << "id" << id << "}";
  40. }
  41. void read(const FileNode& node) //Read serialization for this class
  42. {
  43. A = (int)node["A"];
  44. X = (double)node["X"];
  45. id = (string)node["id"];
  46. }
  47. };
  48. //These write and read functions must exist as per the inline functions in operations.hpp
  49. static void write(FileStorage& fs, const std::string&, const MyData& x){
  50. x.write(fs);
  51. }
  52. static void read(const FileNode& node, MyData& x, const MyData& default_value = MyData()){
  53. if(node.empty())
  54. x = default_value;
  55. else
  56. x.read(node);
  57. }
  58. static ostream& operator<<(ostream& out, const MyData& m){
  59. out << "{ id = " << m.id << ", ";
  60. out << "X = " << m.X << ", ";
  61. out << "A = " << m.A << "}";
  62. return out;
  63. }
  64. int main(int ac, char** av)
  65. {
  66. cv::CommandLineParser parser(ac, av,
  67. "{@input||}{help h ||}"
  68. );
  69. if (parser.has("help"))
  70. {
  71. help(av);
  72. return 0;
  73. }
  74. string filename = parser.get<string>("@input");
  75. if (filename.empty())
  76. {
  77. help(av);
  78. return 1;
  79. }
  80. //write
  81. {
  82. FileStorage fs(filename, FileStorage::WRITE);
  83. cout << "writing images\n";
  84. fs << "images" << "[";
  85. fs << "image1.jpg" << "myfi.png" << "baboon.jpg";
  86. cout << "image1.jpg" << " myfi.png" << " baboon.jpg" << endl;
  87. fs << "]";
  88. cout << "writing mats\n";
  89. Mat R =Mat_<double>::eye(3, 3),T = Mat_<double>::zeros(3, 1);
  90. cout << "R = " << R << "\n";
  91. cout << "T = " << T << "\n";
  92. fs << "R" << R;
  93. fs << "T" << T;
  94. cout << "writing MyData struct\n";
  95. MyData m(1);
  96. fs << "mdata" << m;
  97. cout << m << endl;
  98. }
  99. //read
  100. {
  101. FileStorage fs(filename, FileStorage::READ);
  102. if (!fs.isOpened())
  103. {
  104. cerr << "failed to open " << filename << endl;
  105. help(av);
  106. return 1;
  107. }
  108. FileNode n = fs["images"];
  109. if (n.type() != FileNode::SEQ)
  110. {
  111. cerr << "images is not a sequence! FAIL" << endl;
  112. return 1;
  113. }
  114. cout << "reading images\n";
  115. FileNodeIterator it = n.begin(), it_end = n.end();
  116. for (; it != it_end; ++it)
  117. {
  118. cout << (string)*it << "\n";
  119. }
  120. Mat R, T;
  121. cout << "reading R and T" << endl;
  122. fs["R"] >> R;
  123. fs["T"] >> T;
  124. cout << "R = " << R << "\n";
  125. cout << "T = " << T << endl;
  126. MyData m;
  127. fs["mdata"] >> m;
  128. cout << "read mdata\n";
  129. cout << m << endl;
  130. cout << "attempting to read mdata_b\n"; //Show default behavior for empty matrix
  131. fs["mdata_b"] >> m;
  132. cout << "read mdata_b\n";
  133. cout << m << endl;
  134. }
  135. cout << "Try opening " << filename << " to see the serialized data." << endl << endl;
  136. //read from string
  137. {
  138. cout << "Read data from string\n";
  139. string dataString =
  140. "%YAML:1.0\n"
  141. "mdata:\n"
  142. " A: 97\n"
  143. " X: 3.1415926535897931e+00\n"
  144. " id: mydata1234\n";
  145. MyData m;
  146. FileStorage fs(dataString, FileStorage::READ | FileStorage::MEMORY);
  147. cout << "attempting to read mdata_b from string\n"; //Show default behavior for empty matrix
  148. fs["mdata"] >> m;
  149. cout << "read mdata\n";
  150. cout << m << endl;
  151. }
  152. //write to string
  153. {
  154. cout << "Write data to string\n";
  155. FileStorage fs(filename, FileStorage::WRITE | FileStorage::MEMORY | FileStorage::FORMAT_YAML);
  156. cout << "writing MyData struct\n";
  157. MyData m(1);
  158. fs << "mdata" << m;
  159. cout << m << endl;
  160. string createdString = fs.releaseAndGetString();
  161. cout << "Created string:\n" << createdString << "\n";
  162. }
  163. return 0;
  164. }

到此这篇关于C++ OpenCV读写XML或YAML文件的方法详解的文章就介绍到这了,更多相关C++读写XML YAML文件内容请搜索w3xue以前的文章或继续浏览下面的相关文章希望大家以后多多支持w3xue!

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号