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;