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

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; 
主站蜘蛛池模板: 南宫市| 泰兴市| 石台县| 栖霞市| 武城县| 商水县| 封丘县| 安吉县| 临高县| 合江县| 肥城市| 丹东市| 安多县| 宁国市| 那曲县| 枞阳县| 格尔木市| 新竹市| 江北区| 榆树市| 江口县| 陈巴尔虎旗| 华亭县| 武功县| 海林市| 宝丰县| 万山特区| 汽车| 台安县| 齐河县| 广南县| 五原县| 和顺县| 兴化市| 津南区| 高平市| 宁化县| 古田县| 龙里县| 洞口县| 民权县|