samples/cpp/tutorial_code/core/file_input_output/file_input_output.cpp#

A complete example using the FileStorage interface Check the corresponding tutorial for more details

  1#include <opencv2/core.hpp>
  2#include <iostream>
  3#include <string>
  4
  5using namespace cv;
  6using namespace std;
  7
  8static void help(char** av)
  9{
 10    cout << endl
 11        << av[0] << " shows the usage of the OpenCV serialization functionality."         << endl << endl
 12        << "usage: "                                                                      << endl
 13        <<  av[0] << " [output file name] (default outputfile.yml.gz)"                    << endl << endl
 14        << "The output file may be XML (xml), YAML (yml/yaml), or JSON (json)." << endl
 15        << "You can even compress it by specifying this in its extension like xml.gz yaml.gz etc... " << endl
 16        << "With FileStorage you can serialize objects in OpenCV by using the << and >> operators" << endl
 17        << "For example: - create a class and have it serialized"                         << endl
 18        << "             - use it to read and write matrices."                            << endl << endl;
 19}
 20
 21class MyData
 22{
 23public:
 24    MyData() : A(0), X(0), id()
 25    {}
 26    explicit MyData(int) : A(97), X(CV_PI), id("mydata1234") // explicit to avoid implicit conversion
 27    {}
 28    //! [inside]
 29    void write(FileStorage& fs) const                        //Write serialization for this class
 30    {
 31        fs << "{" << "A" << A << "X" << X << "id" << id << "}";
 32    }
 33    void read(const FileNode& node)                          //Read serialization for this class
 34    {
 35        A = (int)node["A"];
 36        X = (double)node["X"];
 37        id = (string)node["id"];
 38    }
 39    //! [inside]
 40public:   // Data Members
 41    int A;
 42    double X;
 43    string id;
 44};
 45
 46//These write and read functions must be defined for the serialization in FileStorage to work
 47//! [outside]
 48static void write(FileStorage& fs, const std::string&, const MyData& x)
 49{
 50    x.write(fs);
 51}
 52static 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//! [outside]
 59
 60// This function will print our custom class to the console
 61static ostream& operator<<(ostream& out, const MyData& m)
 62{
 63    out << "{ id = " << m.id << ", ";
 64    out << "X = " << m.X << ", ";
 65    out << "A = " << m.A << "}";
 66    return out;
 67}
 68
 69int main(int ac, char** av)
 70{
 71    string filename;
 72
 73    if (ac != 2)
 74    {
 75        help(av);
 76        filename = "outputfile.yml.gz";
 77    }
 78    else
 79        filename = av[1];
 80
 81    { //write
 82        //! [iomati]
 83        Mat R = Mat_<uchar>::eye(3, 3),
 84            T = Mat_<double>::zeros(3, 1);
 85        //! [iomati]
 86        //! [customIOi]
 87        MyData m(1);
 88        //! [customIOi]
 89
 90        //! [open]
 91        FileStorage fs(filename, FileStorage::WRITE);
 92        // or:
 93        // FileStorage fs;
 94        // fs.open(filename, FileStorage::WRITE);
 95        //! [open]
 96
 97        //! [writeNum]
 98        fs << "iterationNr" << 100;
 99        //! [writeNum]
100        //! [writeStr]
101        fs << "strings" << "[";                              // text - string sequence
102        fs << "image1.jpg" << "Awesomeness" << "../data/baboon.jpg";
103        fs << "]";                                           // close sequence
104        //! [writeStr]
105
106        //! [writeMap]
107        fs << "Mapping";                              // text - mapping
108        fs << "{" << "One" << 1;
109        fs <<        "Two" << 2 << "}";
110        //! [writeMap]
111
112        //! [iomatw]
113        fs << "R" << R;                                      // cv::Mat
114        fs << "T" << T;
115        //! [iomatw]
116
117        //! [customIOw]
118        fs << "MyData" << m;                                // your own data structures
119        //! [customIOw]
120
121        //! [close]
122        fs.release();                                       // explicit close
123        //! [close]
124        cout << "Write operation to file:" << filename << " completed successfully." << endl;
125    }
126
127    {//read
128        cout << endl << "Reading: " << endl;
129        FileStorage fs;
130        fs.open(filename, FileStorage::READ);
131
132        //! [readNum]
133        int itNr;
134        //fs["iterationNr"] >> itNr;
135        itNr = (int) fs["iterationNr"];
136        //! [readNum]
137        cout << itNr;
138        if (!fs.isOpened())
139        {
140            cerr << "Failed to open " << filename << endl;
141            help(av);
142            return 1;
143        }
144
145        //! [readStr]
146        FileNode n = fs["strings"];                         // Read string sequence - Get node
147        if (n.type() != FileNode::SEQ)
148        {
149            cerr << "strings is not a sequence! FAIL" << endl;
150            return 1;
151        }
152
153        FileNodeIterator it = n.begin(), it_end = n.end(); // Go through the node
154        for (; it != it_end; ++it)
155            cout << (string)*it << endl;
156        //! [readStr]
157
158
159        //! [readMap]
160        n = fs["Mapping"];                                // Read mappings from a sequence
161        cout << "Two  " << (int)(n["Two"]) << "; ";
162        cout << "One  " << (int)(n["One"]) << endl << endl;
163        //! [readMap]
164
165
166        MyData m;
167        Mat R, T;
168
169        //! [iomat]
170        fs["R"] >> R;                                      // Read cv::Mat
171        fs["T"] >> T;
172        //! [iomat]
173        //! [customIO]
174        fs["MyData"] >> m;                                 // Read your own structure_
175        //! [customIO]
176
177        cout << endl
178            << "R = " << R << endl;
179        cout << "T = " << T << endl << endl;
180        cout << "MyData = " << endl << m << endl << endl;
181
182        //Show default behavior for non existing nodes
183        //! [nonexist]
184        cout << "Attempt to read NonExisting (should initialize the data structure with its default).";
185        fs["NonExisting"] >> m;
186        cout << endl << "NonExisting = " << endl << m << endl;
187        //! [nonexist]
188    }
189
190    cout << endl
191        << "Tip: Open up " << filename << " with a text editor to see the serialized data." << endl;
192
193    return 0;
194}