官术网_书友最值得收藏!

Writing to FileStorage

To write a file with some OpenCV or other numeric data, we can use the FileStorage class, using a streaming << operator such as STL streaming:

#include "opencv2/opencv.hpp" 
using namespace cv; 
 
int main(int, char** argv) 
{ 
   // create our writer 
    FileStorage fs("test.yml", FileStorage::WRITE); 
    // Save an int 
    int fps= 5; 
    fs << "fps" << fps; 
    // Create some mat sample 
    Mat m1= Mat::eye(2,3, CV_32F); 
    Mat m2= Mat::ones(3,2, CV_32F); 
    Mat result= (m1+1).mul(m1+3); 
    // write the result 
    fs << "Result" << result; 
    // release the file 
    fs.release(); 
 
    FileStorage fs2("test.yml", FileStorage::READ); 
 
    Mat r; 
    fs2["Result"] >> r; 
    std::cout << r << std::endl; 
 
    fs2.release(); 
 
    return 0; 
} 

To create a file storage where we save the data, we only need to call the constructor, giving a path filename with the extension format desired (XML or YAML), and the second parameter set to write:

FileStorage fs("test.yml", FileStorage::WRITE); 

If we want to save data, we only need to use the stream operator by giving an identifier in the first stage, and later the matrix or value that we want to save. For example, to save an int variable, we only have to write the following lines of code:

int fps= 5; 
fs << "fps" << fps; 

Otherwise, we can write/save mat as shown:

Mat m1= Mat::eye(2,3, CV_32F); 
Mat m2= Mat::ones(3,2, CV_32F); 
Mat result= (m1+1).mul(m1+3); 
// write the result 
fs << "Result" << result;

The result of the preceding code is a YAML format:

%YAML:1.0 
fps: 5 
Result: !!opencv-matrix 
   rows: 2 
   cols: 3 
   dt: f 
   data: [ 8., 3., 3., 3., 8., 3. ] 

Reading from a file storage to read a file saved previously is very similar to the save functions:

#include "opencv2/opencv.hpp" 
using namespace cv; 
 
int main(int, char** argv) 
{ 
   FileStorage fs2("test.yml", FileStorage::READ); 
 
   Mat r; 
   fs2["Result"] >> r; 
   std::cout << r << std::endl; 
 
   fs2.release(); 
 
   return 0; 
} 

The first stage is to open a saved file with the FileStorage constructor using the appropriate parameters, path, and FileStorage::READ:

FileStorage fs2("test.yml", FileStorage::READ); 

To read any stored variable, we only need to use the common stream operator >> using our FileStorage object and the identifier with the [] operator:

Mat r; 
fs2["Result"] >> r; 
主站蜘蛛池模板: 五河县| 侯马市| 东乡县| 玉溪市| 阿克陶县| 雅安市| 柞水县| 苗栗县| 宝鸡市| 东莞市| 二连浩特市| 天等县| 玉环县| 云浮市| 明溪县| 南郑县| 栾城县| 瑞金市| 伽师县| 阿尔山市| 封丘县| 城固县| 石阡县| 阿勒泰市| 平陆县| 措勤县| 广宗县| 福鼎市| 九龙坡区| 巴塘县| 开阳县| 屏南县| 盘锦市| 武平县| 星座| 南宁市| 北安市| 彰武县| 温宿县| 新野县| 尼玛县|