OpenCV的FileStorage类实现.xml或.yml(.yaml)格式文件的数据存储,其中,.yml文件比起.xml文件更加简洁。
其中:第二行是该文件存储内容的名称,由
本文中以OpenCV中的Mat对象为例,来演示FileStorage类实现.yml格式文件的读写的功能。
本示例中需要包含的头文件如下:
- #include <opencv2\opencv.hpp>
- #include <iostream>
- using namespace cv;
- using namespace std;
(1).yml的数据存储
- int _tmain(int argc, _TCHAR* argv[])
- {
- // write data
- // step 1
- const string path = "D:\\test.yml";
- FileStorage fs(path, FileStorage::WRITE); //> 构造FileStorage类对象
- if (!fs.isOpened()) return 0; //> 打开FileStorage类对象
- // step 2
- Mat Matrix = (Mat_<float>(2,3) << 1456, 0.751, 320, 1005.6, 12.345, 10);
- //> 又一种Mat初始化方式,构建一个内部数据元素为float类型的2行3列的Mat类对象
- fs << "Matrix" << Matrix; //> 将Mat类对象写入FileStorage类对象中进行存储
- // step 3
- fs.release(); //> 释放FileStorage类对象
- system("pause");
- return 0;
- }
其中FileStorage的构造函数为:
- //! the full constructor that opens file storage for reading or writing
- CV_WRAP FileStorage(const string& source, int flags, const string& encoding=string());
参数:
source –存储或读取数据的文件名(字符串),其扩展名(.xml 或 .yml/.yaml)决定文件格式。
flags – 操作模式,包括:
- FileStorage::READ 打开文件进行读操作
- FileStorage::WRITE 打开文件进行写操作
- FileStorage::APPEND打开文件进行附加操作
- FileStorage::MEMORY 从source读数据,或向内部缓存写入数据(由FileStorage::release返回)
encoding – 文件编码方式。目前不支持UTF-16 XML 编码,应使用 8-bit 编码。
由此可以得到D盘下生成的test.yml文件,用Notepad++可以查看其内容如下图所示:

- fs << "Matrix" << Matrix; //> 将Mat类对象写入FileStorage类对象中进行存储
代码中双引号内部的字符串来设置。
第五行表示存储内容的数据格式f表示是float,对应的int由i表示,double由d表示等。
从data开始,[]内村数的是数据内容。
(2).yml的数据读取
- int _tmain(int argc, _TCHAR* argv[])
- {
- // read data
- // step 1
- const string path = "D:\\test.yml";
- FileStorage fs(path, FileStorage::READ);
- if (!fs.isOpened()) return 0;
- // step 2
- Mat Matrix;
- fs["Matrix"] >> Matrix; //> 将FileStorage类对象fs存储的名称为Matrix的数据读入
- // 输出数据内容
- for (int row = 0; row < Matrix.rows; row++)
- {
- for (int col =0; col < Matrix.cols; col++)
- {
- cout << "[" << row << "," << col << "] = ";
- cout << Matrix.at<float>(row,col) << endl;
- }
- }
- // step 3
- fs.release();
- system("pause");
- return 0;
- }
整体思路与写.yml文件相一致,打印输出得到的结果如下图:
