1
File Input and Output using XML and YAML files {#tutorial_file_input_output_with_xml_yml}
2
==============================================
7
You'll find answers for the following questions:
9
- How to print and read text entries to a file and OpenCV using YAML or XML files?
10
- How to do the same for OpenCV data structures?
11
- How to do this for your data structures?
12
- Usage of OpenCV data structures such as @ref cv::FileStorage , @ref cv::FileNode or @ref
13
cv::FileNodeIterator .
18
You can [download this from here
19
](https://github.com/Itseez/opencv/tree/master/samples/cpp/tutorial_code/core/file_input_output/file_input_output.cpp) or find it in the
20
`samples/cpp/tutorial_code/core/file_input_output/file_input_output.cpp` of the OpenCV source code
23
Here's a sample code of how to achieve all the stuff enumerated at the goal list.
25
@include cpp/tutorial_code/core/file_input_output/file_input_output.cpp
30
Here we talk only about XML and YAML file inputs. Your output (and its respective input) file may
31
have only one of these extensions and the structure coming from this. They are two kinds of data
32
structures you may serialize: *mappings* (like the STL map) and *element sequence* (like the STL
33
vector). The difference between these is that in a map every element has a unique name through what
34
you may access it. For sequences you need to go through them to query a specific item.
36
-# **XML/YAML File Open and Close.** Before you write any content to such file you need to open it
37
and at the end to close it. The XML/YAML data structure in OpenCV is @ref cv::FileStorage . To
38
specify that this structure to which file binds on your hard drive you can use either its
39
constructor or the *open()* function of this:
41
string filename = "I.xml";
42
FileStorage fs(filename, FileStorage::WRITE);
44
fs.open(filename, FileStorage::READ);
46
Either one of this you use the second argument is a constant specifying the type of operations
47
you'll be able to on them: WRITE, READ or APPEND. The extension specified in the file name also
48
determinates the output format that will be used. The output may be even compressed if you
49
specify an extension such as *.xml.gz*.
51
The file automatically closes when the @ref cv::FileStorage objects is destroyed. However, you
52
may explicitly call for this by using the *release* function:
54
fs.release(); // explicit close
56
-# **Input and Output of text and numbers.** The data structure uses the same \<\< output operator
57
that the STL library. For outputting any type of data structure we need first to specify its
58
name. We do this by just simply printing out the name of this. For basic types you may follow
59
this with the print of the value :
61
fs << "iterationNr" << 100;
63
Reading in is a simple addressing (via the [] operator) and casting operation or a read via
67
fs["iterationNr"] >> itNr;
68
itNr = (int) fs["iterationNr"];
70
-# **Input/Output of OpenCV Data structures.** Well these behave exactly just as the basic C++
73
Mat R = Mat_<uchar >::eye (3, 3),
74
T = Mat_<double>::zeros(3, 1);
76
fs << "R" << R; // Write cv::Mat
79
fs["R"] >> R; // Read cv::Mat
82
-# **Input/Output of vectors (arrays) and associative maps.** As I mentioned beforehand, we can
83
output maps and sequences (array, vector) too. Again we first print the name of the variable and
84
then we have to specify if our output is either a sequence or map.
86
For sequence before the first element print the "[" character and after the last one the "]"
89
fs << "strings" << "["; // text - string sequence
90
fs << "image1.jpg" << "Awesomeness" << "baboon.jpg";
91
fs << "]"; // close sequence
93
For maps the drill is the same however now we use the "{" and "}" delimiter characters:
95
fs << "Mapping"; // text - mapping
96
fs << "{" << "One" << 1;
97
fs << "Two" << 2 << "}";
99
To read from these we use the @ref cv::FileNode and the @ref cv::FileNodeIterator data
100
structures. The [] operator of the @ref cv::FileStorage class returns a @ref cv::FileNode data
101
type. If the node is sequential we can use the @ref cv::FileNodeIterator to iterate through the
104
FileNode n = fs["strings"]; // Read string sequence - Get node
105
if (n.type() != FileNode::SEQ)
107
cerr << "strings is not a sequence! FAIL" << endl;
111
FileNodeIterator it = n.begin(), it_end = n.end(); // Go through the node
112
for (; it != it_end; ++it)
113
cout << (string)*it << endl;
115
For maps you can use the [] operator again to acces the given item (or the \>\> operator too):
117
n = fs["Mapping"]; // Read mappings from a sequence
118
cout << "Two " << (int)(n["Two"]) << "; ";
119
cout << "One " << (int)(n["One"]) << endl << endl;
121
-# **Read and write your own data structures.** Suppose you have a data structure such as:
126
MyData() : A(0), X(0), id() {}
127
public: // Data Members
133
It's possible to serialize this through the OpenCV I/O XML/YAML interface (just as in case of
134
the OpenCV data structures) by adding a read and a write function inside and outside of your
135
class. For the inside part:
137
void write(FileStorage& fs) const //Write serialization for this class
139
fs << "{" << "A" << A << "X" << X << "id" << id << "}";
142
void read(const FileNode& node) //Read serialization for this class
145
X = (double)node["X"];
146
id = (string)node["id"];
149
Then you need to add the following functions definitions outside the class:
151
void write(FileStorage& fs, const std::string&, const MyData& x)
156
void read(const FileNode& node, MyData& x, const MyData& default_value = MyData())
164
Here you can observe that in the read section we defined what happens if the user tries to read
165
a non-existing node. In this case we just return the default initialization value, however a
166
more verbose solution would be to return for instance a minus one value for an object ID.
168
Once you added these four functions use the \>\> operator for write and the \<\< operator for
172
fs << "MyData" << m; // your own data structures
173
fs["MyData"] >> m; // Read your own structure_
175
Or to try out reading a non-existing read:
177
fs["NonExisting"] >> m; // Do not add a fs << "NonExisting" << m command for this to work
178
cout << endl << "NonExisting = " << endl << m << endl;
184
Well mostly we just print out the defined numbers. On the screen of your console you could see:
201
{ id = mydata1234, X = 3.14159, A = 97}
203
Attempt to read NonExisting (should initialize the data structure with its default).
205
{ id = , X = 0, A = 0}
207
Tip: Open up output.xml with a text editor to see the serialized data.
209
Nevertheless, it's much more interesting what you may see in the output xml file:
211
<?xml version="1.0"?>
213
<iterationNr>100</iterationNr>
215
image1.jpg Awesomeness baboon.jpg</strings>
218
<Two>2</Two></Mapping>
219
<R type_id="opencv-matrix">
224
1 0 0 0 1 0 0 0 1</data></R>
225
<T type_id="opencv-matrix">
233
<X>3.1415926535897931e+000</X>
234
<id>mydata1234</id></MyData>
252
data: [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ]
260
X: 3.1415926535897931e+000
263
You may observe a runtime instance of this on the [YouTube
264
here](https://www.youtube.com/watch?v=A4yqVnByMMM) .
268
<iframe title="File Input and Output using XML and YAML files in OpenCV" width="560" height="349" src="http://www.youtube.com/embed/A4yqVnByMMM?rel=0&loop=1" frameborder="0" allowfullscreen align="middle"></iframe>