You can store and then restore various OpenCV data structures to/from XML (http://www.w3c.org/XML) or YAML (http://www.yaml.org) formats. Also, it is possible store and load arbitrarily complex data structures, which include OpenCV data structures, as well as primitive data types (integer and floating-point numbers and text strings) as their elements.
FileStorage
and open it for writing. It can be done with a single call to FileStorage::FileStorage()
constructor that takes a filename, or you can use the default constructor and then call FileStorage::open()
. Format of the file (XML or YAML) is determined from the filename extension (”.xml” and ”.yml”/”.yaml”, respectively)<<
, just like in the case of STL streams.FileStorage::release()
. FileStorage
destructor also closes the file.Here is an example:
#include "opencv2/opencv.hpp"
#include <time.h>
using namespace cv;
int main(int, char** argv)
{
FileStorage fs("test.yml", FileStorage::WRITE);
fs << "frameCount" << 5;
time_t rawtime; time(&rawtime);
fs << "calibrationDate" << asctime(localtime(&rawtime));
Mat cameraMatrix = (Mat_<double>(3,3) << 1000, 0, 320, 0, 1000, 240, 0, 0, 1);
Mat distCoeffs = (Mat_<double>(5,1) << 0.1, 0.01, -0.001, 0, 0);
fs << "cameraMatrix" << cameraMatrix << "distCoeffs" << distCoeffs;
fs << "features" << "[";
for( int i = 0; i < 3; i++ )
{
int x = rand() % 640;
int y = rand() % 480;
uchar lbp = rand() % 256;
fs << "{:" << "x" << x << "y" << y << "lbp" << "[:";
for( int j = 0; j < 8; j++ )
fs << ((lbp >> j) & 1);
fs << "]" << "}";
}
fs << "]";
fs.release();
return 0;
}
The sample above stores to XML and integer, text string (calibration date), 2 matrices, and a custom structure “feature”, which includes feature coordinates and LBP (local binary pattern) value. Here is output of the sample:
%YAML:1.0
frameCount: 5
calibrationDate: "Fri Jun 17 14:09:29 2011\n"
cameraMatrix: !!opencv-matrix
rows: 3
cols: 3
dt: d
data: [ 1000., 0., 320., 0., 1000., 240., 0., 0., 1. ]
distCoeffs: !!opencv-matrix
rows: 5
cols: 1
dt: d
data: [ 1.0000000000000001e-01, 1.0000000000000000e-02,
-1.0000000000000000e-03, 0., 0. ]
features:
- { x:167, y:49, lbp:[ 1, 0, 0, 1, 1, 0, 1, 1 ] }
- { x:298, y:130, lbp:[ 0, 0, 0, 1, 0, 0, 1, 1 ] }
- { x:344, y:158, lbp:[ 1, 1, 0, 0, 0, 0, 1, 0 ] }
As an exercise, you can replace ”.yml” with ”.xml” in the sample above and see, how the corresponding XML file will look like.
The produced YAML (and XML) consists of heterogeneous collections that can be nested. There are 2 types of collections: named collections (mappings) and unnamed collections (sequences). In mappings each element has a name and is accessed by name. This is similar to structures and std::map
in C/C++ and dictionaries in Python. In sequences elements do not have names, they are accessed by indices. This is similar to arrays and std::vector
in C/C++ and lists, tuples in Python. “Heterogeneous” means that elements of each single collection can have different types.
Top-level collection in YAML/XML is a mapping. Each matrix is stored as a mapping, and the matrix elements are stored as a sequence. Then, there is a sequence of features, where each feature is represented a mapping, and lbp value in a nested sequence.
When you write to a mapping (a structure), you write element name followed by its value. When you write to a sequence, you simply write the elements one by one. OpenCV data structures (such as cv::Mat) are written in absolutely the same way as simple C data structures - using ``<<`` operator.
To write a mapping, you first write the special string “{“ to the storage, then write the elements as pairs (fs << <element_name> << <element_value>
) and then write the closing “}”.
To write a sequence, you first write the special string “[“, then write the elements, then write the closing “]”.
In YAML (but not XML), mappings and sequences can be written in a compact Python-like inline form. In the sample above matrix elements, as well as each feature, including its lbp value, is stored in such inline form. To store a mapping/sequence in a compact form, put ”:” after the opening character, e.g. use “{:” instead of “{“ and “[:” instead of “[“. When the data is written to XML, those extra ”:” are ignored.
Note
To read the previously written XML or YAML file, do the following:
- Open the file storage using
FileStorage::FileStorage()
constructor orFileStorage::open()
method. In the current implementation the whole file is parsed and the whole representation of file storage is built in memory as a hierarchy of file nodes (seeFileNode
)- Read the data you are interested in. Use
FileStorage::operator []()
,FileNode::operator []()
and/orFileNodeIterator
.- Close the storage using
FileStorage::release()
.
Here is how to read the file created by the code sample above:
FileStorage fs2("test.yml", FileStorage::READ);
// first method: use (type) operator on FileNode.
int frameCount = (int)fs2["frameCount"];
std::string date;
// second method: use FileNode::operator >>
fs2["calibrationDate"] >> date;
Mat cameraMatrix2, distCoeffs2;
fs2["cameraMatrix"] >> cameraMatrix2;
fs2["distCoeffs"] >> distCoeffs2;
cout << "frameCount: " << frameCount << endl
<< "calibration date: " << date << endl
<< "camera matrix: " << cameraMatrix2 << endl
<< "distortion coeffs: " << distCoeffs2 << endl;
FileNode features = fs2["features"];
FileNodeIterator it = features.begin(), it_end = features.end();
int idx = 0;
std::vector<uchar> lbpval;
// iterate through a sequence using FileNodeIterator
for( ; it != it_end; ++it, idx++ )
{
cout << "feature #" << idx << ": ";
cout << "x=" << (int)(*it)["x"] << ", y=" << (int)(*it)["y"] << ", lbp: (";
// you can also easily read numerical arrays using FileNode >> std::vector operator.
(*it)["lbp"] >> lbpval;
for( int i = 0; i < (int)lbpval.size(); i++ )
cout << " " << (int)lbpval[i];
cout << ")" << endl;
}
fs.release();
FileStorage
¶XML/YAML file storage class that encapsulates all the information necessary for writing or reading data to/from a file.
The constructors.
FileStorage::
FileStorage
()¶
FileStorage::
FileStorage
(const string& source, int flags, const string& encoding=string())¶Parameters: |
|
---|
The full constructor opens the file. Alternatively you can use the default constructor and then call FileStorage::open()
.
Opens a file.
bool FileStorage::
open
(const string& filename, int flags, const string& encoding=string())¶Parameters: |
|
---|
See description of parameters in FileStorage::FileStorage()
. The method calls FileStorage::release()
before opening the file.
Checks whether the file is opened.
bool FileStorage::
isOpened
() const
¶Returns: | true if the object is associated with the current file and false otherwise. |
---|
It is a good practice to call this method after you tried to open a file.
Closes the file and releases all the memory buffers.
void FileStorage::
release
()¶Call this method after all I/O operations with the storage are finished.
Closes the file and releases all the memory buffers.
string FileStorage::
releaseAndGetString
()¶Call this method after all I/O operations with the storage are finished. If the storage was opened for writing data and FileStorage::WRITE
was specified
Returns the first element of the top-level mapping.
FileNode FileStorage::
getFirstTopLevelNode
() const
¶Returns: | The first element of the top-level mapping. |
---|
Returns the top-level mapping
FileNode FileStorage::
root
(int streamidx=0) const
¶Parameters: |
|
---|---|
Returns: | The top-level mapping. |
Returns the specified element of the top-level mapping.
FileNode FileStorage::
operator[]
(const string& nodename) const
¶
FileNode FileStorage::
operator[]
(const char* nodename) const
¶Parameters: |
|
---|---|
Returns: | Node with the given name. |
Returns the obsolete C FileStorage structure.
CvFileStorage* FileStorage::
operator*
()¶
const CvFileStorage* FileStorage::
operator*
() const
¶Returns: | Pointer to the underlying C FileStorage structure |
---|
Writes multiple numbers.
void FileStorage::
writeRaw
(const string& fmt, const uchar* vec, size_t len)¶Parameters: |
|
---|
Writes one or more numbers of the specified format to the currently written structure. Usually it is more convenient to use operator <<()
instead of this method.
Writes the registered C structure (CvMat, CvMatND, CvSeq).
void FileStorage::
writeObj
(const string& name, const void* obj)¶Parameters: |
|
---|
See Write()
for details.
Returns the normalized object name for the specified name of a file.
static string FileStorage::
getDefaultObjectName
(const string& filename)¶Parameters: |
|
---|---|
Returns: | The normalized object name. |
Writes data to a file storage.
template<typename _Tp> FileStorage& operator<<
(FileStorage& fs, const _Tp& value)¶
template<typename _Tp> FileStorage& operator<<
(FileStorage& fs, const vector<_Tp>& vec)¶Parameters: |
|
---|
It is the main function to write data to a file storage. See an example of its usage at the beginning of the section.
Reads data from a file storage.
template<typename _Tp> void operator>>
(const FileNode& n, _Tp& value)¶
template<typename _Tp> void operator>>
(const FileNode& n, vector<_Tp>& vec)¶
template<typename _Tp> FileNodeIterator& operator>>
(FileNodeIterator& it, _Tp& value)¶
template<typename _Tp> FileNodeIterator& operator>>
(FileNodeIterator& it, vector<_Tp>& vec)¶Parameters: |
|
---|
It is the main function to read data from a file storage. See an example of its usage at the beginning of the section.
FileNode
¶File Storage Node class. The node is used to store each and every element of the file storage opened for reading. When XML/YAML file is read, it is first parsed and stored in the memory as a hierarchical collection of nodes. Each node can be a “leaf” that is contain a single number or a string, or be a collection of other nodes. There can be named collections (mappings) where each element has a name and it is accessed by a name, and ordered collections (sequences) where elements do not have names but rather accessed by index. Type of the file node can be determined using FileNode::type()
method.
Note that file nodes are only used for navigating file storages opened for reading. When a file storage is opened for writing, no data is stored in memory after it is written.
The constructors.
FileNode::
FileNode
()¶
FileNode::
FileNode
(const CvFileStorage* fs, const CvFileNode* node)¶
FileNode::
FileNode
(const FileNode& node)¶Parameters: |
|
---|
These constructors are used to create a default file node, construct it from obsolete structures or from the another file node.
Returns element of a mapping node or a sequence node.
FileNode FileNode::
operator[]
(const string& nodename) const
¶
FileNode FileNode::
operator[]
(const char* nodename) const
¶
FileNode FileNode::
operator[]
(int i) const
¶Parameters: |
|
---|---|
Returns: | Returns the element with the given identifier. |
Returns type of the node.
int FileNode::
type
() const
¶Returns: | Type of the node. Possible values are:
|
---|
Checks whether the node is empty.
bool FileNode::
empty
() const
¶Returns: | true if the node is empty. |
---|
Checks whether the node is a “none” object
bool FileNode::
isNone
() const
¶Returns: | true if the node is a “none” object. |
---|
Checks whether the node is a sequence.
bool FileNode::
isSeq
() const
¶Returns: | true if the node is a sequence. |
---|
Checks whether the node is a mapping.
bool FileNode::
isMap
() const
¶Returns: | true if the node is a mapping. |
---|
Checks whether the node is an integer.
bool FileNode::
isInt
() const
¶Returns: | true if the node is an integer. |
---|
Checks whether the node is a floating-point number.
bool FileNode::
isReal
() const
¶Returns: | true if the node is a floating-point number. |
---|
Checks whether the node is a text string.
bool FileNode::
isString
() const
¶Returns: | true if the node is a text string. |
---|
Checks whether the node has a name.
bool FileNode::
isNamed
() const
¶Returns: | true if the node has a name. |
---|
Returns the node name.
string FileNode::
name
() const
¶Returns: | The node name or an empty string if the node is nameless. |
---|
Returns the number of elements in the node.
size_t FileNode::
size
() const
¶Returns: | The number of elements in the node, if it is a sequence or mapping, or 1 otherwise. |
---|
Returns the node content as an integer.
FileNode::
operator
int() const
¶Returns: | The node content as an integer. If the node stores a floating-point number, it is rounded. |
---|
Returns the node content as float.
FileNode::
operator
float() const
¶Returns: | The node content as float. |
---|
Returns the node content as double.
FileNode::
operator
double() const
¶Returns: | The node content as double. |
---|
Returns the node content as text string.
FileNode::
operator
string() const
¶Returns: | The node content as a text string. |
---|
Returns pointer to the underlying obsolete file node structure.
CvFileNode* FileNode::
operator*
()¶Returns: | Pointer to the underlying obsolete file node structure. |
---|
Returns the iterator pointing to the first node element.
FileNodeIterator FileNode::
begin
() const
¶Returns: | Iterator pointing to the first node element. |
---|
Returns the iterator pointing to the element following the last node element.
FileNodeIterator FileNode::
end
() const
¶Returns: | Iterator pointing to the element following the last node element. |
---|
Reads node elements to the buffer with the specified format.
void FileNode::
readRaw
(const string& fmt, uchar* vec, size_t len) const
¶Parameters: |
|
---|
Usually it is more convenient to use operator >>()
instead of this method.
Reads the registered object.
void* FileNode::
readObj
() const
¶Returns: | Pointer to the read object. |
---|
See Read()
for details.
FileNodeIterator
¶The class FileNodeIterator
is used to iterate through sequences and mappings. A standard STL notation, with node.begin()
, node.end()
denoting the beginning and the end of a sequence, stored in node
. See the data reading sample in the beginning of the section.
The constructors.
FileNodeIterator::
FileNodeIterator
()¶
FileNodeIterator::
FileNodeIterator
(const CvFileStorage* fs, const CvFileNode* node, size_t ofs=0)¶
FileNodeIterator::
FileNodeIterator
(const FileNodeIterator& it)¶Parameters: |
|
---|
These constructors are used to create a default iterator, set it to specific element in a file node or construct it from another iterator.
Returns the currently observed element.
FileNode FileNodeIterator::
operator*
() const
¶Returns: | Currently observed element. |
---|
Accesses methods of the currently observed element.
FileNode FileNodeIterator::
operator->
() const
¶Moves iterator to the next node.
FileNodeIterator& FileNodeIterator::
operator++
()¶
FileNodeIterator FileNodeIterator::
operator++
(int None)¶Moves iterator to the previous node.
FileNodeIterator& FileNodeIterator::
operator--
()¶
FileNodeIterator FileNodeIterator::
operator--
(int None)¶Moves iterator forward by the specified offset.
FileNodeIterator& FileNodeIterator::
operator+=
(int ofs)¶Parameters: |
|
---|
Moves iterator backward by the specified offset (possibly negative).
FileNodeIterator& FileNodeIterator::
operator-=
(int ofs)¶Parameters: |
|
---|
Reads node elements to the buffer with the specified format.
FileNodeIterator& FileNodeIterator::
readRaw
(const string& fmt, uchar* vec, size_t maxCount=(size_t)INT_MAX )¶Parameters: |
|
---|
Usually it is more convenient to use operator >>()
instead of this method.