opencv/doc/cxcore_persistence.tex

1120 lines
42 KiB
TeX
Raw Normal View History

\section{XML/YAML Persistence}
\ifCPy
\ifC
\cvclass{CvFileStorage}\label{CvFileStorage}
File Storage.
\begin{lstlisting}
typedef struct CvFileStorage
{
... // hidden fields
} CvFileStorage;
\end{lstlisting}
The structure \cross{CvFileStorage} is a "black box" representation
of the file storage associated with a file on disk. Several
functions that are described below take \texttt{CvFileStorage} as
inputs and allow theuser to save or to load hierarchical collections
that consist of scalar values, standard CXCore objects (such as
matrices, sequences, graphs), and user-defined objects.
CXCore can read and write data in XML (http://www.w3c.org/XML) or YAML
(http://www.yaml.org) formats. Below is an example of $3 \times 3$
floating-point identity matrix \texttt{A}, stored in XML and YAML files
using CXCore functions:
XML:
\begin{verbatim}
<?xml version="1.0">
<opencv_storage>
<A type_id="opencv-matrix">
<rows>3</rows>
<cols>3</cols>
<dt>f</dt>
<data>1. 0. 0. 0. 1. 0. 0. 0. 1.</data>
</A>
</opencv_storage>
\end{verbatim}
YAML:
\begin{verbatim}
%YAML:1.0
A: !!opencv-matrix
rows: 3
cols: 3
dt: f
data: [ 1., 0., 0., 0., 1., 0., 0., 0., 1.]
\end{verbatim}
As it can be seen from the examples, XML uses nested tags to represent
hierarchy, while YAML uses indentation for that purpose (similar
to the Python programming language).
The same CXCore functions can read and write data in both formats;
the particular format is determined by the extension of the opened
file, .xml for XML files and .yml or .yaml for YAML.
\cvclass{CvFileNode}\label{CvFileNode}
File Storage Node.
\begin{lstlisting}
/* file node type */
#define CV_NODE_NONE 0
#define CV_NODE_INT 1
#define CV_NODE_INTEGER CV_NODE_INT
#define CV_NODE_REAL 2
#define CV_NODE_FLOAT CV_NODE_REAL
#define CV_NODE_STR 3
#define CV_NODE_STRING CV_NODE_STR
#define CV_NODE_REF 4 /* not used */
#define CV_NODE_SEQ 5
#define CV_NODE_MAP 6
#define CV_NODE_TYPE_MASK 7
/* optional flags */
#define CV_NODE_USER 16
#define CV_NODE_EMPTY 32
#define CV_NODE_NAMED 64
#define CV_NODE_TYPE(tag) ((tag) & CV_NODE_TYPE_MASK)
#define CV_NODE_IS_INT(tag) (CV_NODE_TYPE(tag) == CV_NODE_INT)
#define CV_NODE_IS_REAL(tag) (CV_NODE_TYPE(tag) == CV_NODE_REAL)
#define CV_NODE_IS_STRING(tag) (CV_NODE_TYPE(tag) == CV_NODE_STRING)
#define CV_NODE_IS_SEQ(tag) (CV_NODE_TYPE(tag) == CV_NODE_SEQ)
#define CV_NODE_IS_MAP(tag) (CV_NODE_TYPE(tag) == CV_NODE_MAP)
#define CV_NODE_IS_COLLECTION(tag) (CV_NODE_TYPE(tag) >= CV_NODE_SEQ)
#define CV_NODE_IS_FLOW(tag) (((tag) & CV_NODE_FLOW) != 0)
#define CV_NODE_IS_EMPTY(tag) (((tag) & CV_NODE_EMPTY) != 0)
#define CV_NODE_IS_USER(tag) (((tag) & CV_NODE_USER) != 0)
#define CV_NODE_HAS_NAME(tag) (((tag) & CV_NODE_NAMED) != 0)
#define CV_NODE_SEQ_SIMPLE 256
#define CV_NODE_SEQ_IS_SIMPLE(seq) (((seq)->flags & CV_NODE_SEQ_SIMPLE) != 0)
typedef struct CvString
{
int len;
char* ptr;
}
CvString;
/* all the keys (names) of elements in the readed file storage
are stored in the hash to speed up the lookup operations */
typedef struct CvStringHashNode
{
unsigned hashval;
CvString str;
struct CvStringHashNode* next;
}
CvStringHashNode;
/* basic element of the file storage - scalar or collection */
typedef struct CvFileNode
{
int tag;
struct CvTypeInfo* info; /* type information
(only for user-defined object, for others it is 0) */
union
{
double f; /* scalar floating-point number */
int i; /* scalar integer number */
CvString str; /* text string */
CvSeq* seq; /* sequence (ordered collection of file nodes) */
struct CvMap* map; /* map (collection of named file nodes) */
} data;
}
CvFileNode;
\end{lstlisting}
The structure is used only for retrieving data from file storage
(i.e., for loading data from the file). When data is written to a file,
it is done sequentially, with minimal buffering. No data is stored
in the file storage.
In opposite, when data is read from a file, the whole file is parsed
and represented in memory as a tree. Every node of the tree is
represented by \cross{CvFileNode}. The type of file node \texttt{N}
can be retrieved as \texttt{CV\_NODE\_TYPE(N->tag)}. Some file nodes
(leaves) are scalars: text strings, integers, or floating-point
numbers. Other file nodes are collections of file nodes, which can
be scalars or collections in their turn. There are two types of
collections: sequences and maps (we use YAML notation, however, the
same is true for XML streams). Sequences (do not mix them with
\cross{CvSeq}) are ordered collections of unnamed file nodes; maps
are unordered collections of named file nodes. Thus, elements of
sequences are accessed by index (\cross{GetSeqElem}), while elements
of maps are accessed by name (\cross{GetFileNodeByName}). The table
below describes the different types of file nodes:
\begin{tabular}{| c | c | c |}
\hline
Type & \texttt{CV\_NODE\_TYPE(node->tag)} & Value\\ \hline \hline
Integer & \texttt{CV\_NODE\_INT} & \texttt{node->data.i} \\ \hline
Floating-point & \texttt{CV\_NODE\_REAL} & \texttt{node->data.f} \\ \hline
Text string & \texttt{CV\_NODE\_STR} & \texttt{node->data.str.ptr} \\ \hline
Sequence & \texttt{CV\_NODE\_SEQ} & \texttt{node->data.seq} \\ \hline
Map & \texttt{CV\_NODE\_MAP} & \texttt{node->data.map} (see below)\\ \hline
\end{tabular}
There is no need to access the \texttt{map} field directly (by the way,
\texttt{CvMap} is a hidden structure). The elements of the map can
be retrieved with the \cross{GetFileNodeByName} function that takes a
pointer to the "map" file node.
A user (custom) object is an instance of either one of the standard CxCore
types, such as \cross{CvMat}, \cross{CvSeq} etc., or any type
registered with \cross{RegisterTypeInfo}. Such an object is initially
represented in a file as a map (as shown in XML and YAML example files
above) after the file storage has been opened and parsed. Then the
object can be decoded (coverted to native representation) by
request - when a user calls the \cross{Read} or \cross{ReadByName} functions.
\cvclass{CvAttrList}\label{CvAttrList}
List of attributes.
\begin{lstlisting}
typedef struct CvAttrList
{
const char** attr; /* NULL-terminated array of (attribute\_name,attribute\_value) pairs */
struct CvAttrList* next; /* pointer to next chunk of the attributes list */
}
CvAttrList;
/* initializes CvAttrList structure */
inline CvAttrList cvAttrList( const char** attr=NULL, CvAttrList* next=NULL );
/* returns attribute value or 0 (NULL) if there is no such attribute */
const char* cvAttrValue( const CvAttrList* attr, const char* attr\_name );
\end{lstlisting}
In the current implementation, attributes are used to pass extra parameters when writing user objects (see \cross{Write}). XML attributes inside tags are not supported, aside from the object type specification (\texttt{type\_id} attribute).
\cvclass{CvTypeInfo}\label{CvTypeInfo}
Type information.
\begin{lstlisting}
typedef int (CV_CDECL *CvIsInstanceFunc)( const void* structPtr );
typedef void (CV_CDECL *CvReleaseFunc)( void** structDblPtr );
typedef void* (CV_CDECL *CvReadFunc)( CvFileStorage* storage, CvFileNode* node );
typedef void (CV_CDECL *CvWriteFunc)( CvFileStorage* storage,
const char* name,
const void* structPtr,
CvAttrList attributes );
typedef void* (CV_CDECL *CvCloneFunc)( const void* structPtr );
typedef struct CvTypeInfo
{
int flags; /* not used */
int header_size; /* sizeof(CvTypeInfo) */
struct CvTypeInfo* prev; /* previous registered type in the list */
struct CvTypeInfo* next; /* next registered type in the list */
const char* type_name; /* type name, written to file storage */
/* methods */
CvIsInstanceFunc is_instance; /* checks if the passed object belongs to the type */
CvReleaseFunc release; /* releases object (memory etc.) */
CvReadFunc read; /* reads object from file storage */
CvWriteFunc write; /* writes object to file storage */
CvCloneFunc clone; /* creates a copy of the object */
}
CvTypeInfo;
\end{lstlisting}
The structure \cross{CvTypeInfo} contains information about one of the
standard or user-defined types. Instances of the type may or may not
contain a pointer to the corresponding \cross{CvTypeInfo} structure. In
any case, there is a way to find the type info structure for a given object
using the \cross{TypeOf} function. Aternatively, type info can be found by
type name using \cross{FindType}, which is used when an object is read
from file storage. The user can register a new type with \cross{RegisterType}
that adds the type information structure into the beginning of the type
list. Thus, it is possible to create specialized types from generic
standard types and override the basic methods.
\cvCPyFunc{Clone}
Makes a clone of an object.
\cvdefC{void* cvClone( const void* structPtr );}
\begin{description}
\cvarg{structPtr}{The object to clone}
\end{description}
The function finds the type of a given object and calls \texttt{clone} with the passed object.
\cvCPyFunc{EndWriteStruct}
Ends the writing of a structure.
\cvdefC{void cvEndWriteStruct(CvFileStorage* fs);}
\begin{description}
\cvarg{fs}{File storage}
\end{description}
The function finishes the currently written structure.
\cvCPyFunc{FindType}
Finds a type by its name.
\cvdefC{CvTypeInfo* cvFindType(const char* typeName);}
\begin{description}
\cvarg{typeName}{Type name}
\end{description}
The function finds a registered type by its name. It returns NULL if there is no type with the specified name.
\cvCPyFunc{FirstType}
Returns the beginning of a type list.
\cvdefC{CvTypeInfo* cvFirstType(void);}
The function returns the first type in the list of registered types. Navigation through the list can be done via the \texttt{prev} and \texttt{next} fields of the \cross{CvTypeInfo} structure.
\cvCPyFunc{GetFileNode}
Finds a node in a map or file storage.
\cvdefC{CvFileNode* cvGetFileNode( \par CvFileStorage* fs,\par CvFileNode* map,\par const CvStringHashNode* key,\par int createMissing=0 );}
\begin{description}
\cvarg{fs}{File storage}
\cvarg{map}{The parent map. If it is NULL, the function searches a top-level node. If both \texttt{map} and \texttt{key} are NULLs, the function returns the root file node - a map that contains top-level nodes.}
\cvarg{key}{Unique pointer to the node name, retrieved with \cross{GetHashedKey}}
\cvarg{createMissing}{Flag that specifies whether an absent node should be added to the map}
\end{description}
The function finds a file node. It is a faster version of \cross{GetFileNodeByName} (see \cross{GetHashedKey} discussion). Also, the function can insert a new node, if it is not in the map yet.
\cvCPyFunc{GetFileNodeByName}
Finds a node in a map or file storage.
\cvdefC{CvFileNode* cvGetFileNodeByName( \par const CvFileStorage* fs,\par const CvFileNode* map,\par const char* name);}
\begin{description}
\cvarg{fs}{File storage}
\cvarg{map}{The parent map. If it is NULL, the function searches in all the top-level nodes (streams), starting with the first one.}
\cvarg{name}{The file node name}
\end{description}
The function finds a file node by
\texttt{name}. The node is searched either in \texttt{map} or, if the
pointer is NULL, among the top-level file storage nodes. Using
this function for maps and \cross{GetSeqElem} (or sequence reader)
for sequences, it is possible to nagivate through the file storage. To
speed up multiple queries for a certain key (e.g., in the case of an array
of structures) one may use a combination of \cross{GetHashedKey} and
\cross{GetFileNode}.
\cvCPyFunc{GetFileNodeName}
Returns the name of a file node.
\cvdefC{const char* cvGetFileNodeName( const CvFileNode* node );}
\begin{description}
\cvarg{node}{File node}
\end{description}
The function returns the name of a file node or NULL, if the file node does not have a name or if \texttt{node} is \texttt{NULL}.
\cvCPyFunc{GetHashedKey}
Returns a unique pointer for a given name.
\cvdefC{CvStringHashNode* cvGetHashedKey( \par CvFileStorage* fs,\par const char* name,\par int len=-1,\par int createMissing=0 );}
\begin{description}
\cvarg{fs}{File storage}
\cvarg{name}{Literal node name}
\cvarg{len}{Length of the name (if it is known apriori), or -1 if it needs to be calculated}
\cvarg{createMissing}{Flag that specifies, whether an absent key should be added into the hash table}
\end{description}
The function returns a unique pointer for
each particular file node name. This pointer can be then passed to the
\cross{GetFileNode} function that is faster than \cross{GetFileNodeByName}
because it compares text strings by comparing pointers rather than the
strings' content.
Consider the following example where an array of points is encoded as a sequence of 2-entry maps:
\begin{lstlisting}
%YAML:1.0
points:
- { x: 10, y: 10 }
- { x: 20, y: 20 }
- { x: 30, y: 30 }
# ...
\end{lstlisting}
Then, it is possible to get hashed "x" and "y" pointers to speed up decoding of the points.
% Example: Reading an array of structures from file storage
\begin{lstlisting}
#include "cxcore.h"
int main( int argc, char** argv )
{
CvFileStorage* fs = cvOpenFileStorage( "points.yml", 0, CV\_STORAGE\_READ );
CvStringHashNode* x\_key = cvGetHashedNode( fs, "x", -1, 1 );
CvStringHashNode* y\_key = cvGetHashedNode( fs, "y", -1, 1 );
CvFileNode* points = cvGetFileNodeByName( fs, 0, "points" );
if( CV\_NODE\_IS\_SEQ(points->tag) )
{
CvSeq* seq = points->data.seq;
int i, total = seq->total;
CvSeqReader reader;
cvStartReadSeq( seq, &reader, 0 );
for( i = 0; i < total; i++ )
{
CvFileNode* pt = (CvFileNode*)reader.ptr;
#if 1 /* faster variant */
CvFileNode* xnode = cvGetFileNode( fs, pt, x\_key, 0 );
CvFileNode* ynode = cvGetFileNode( fs, pt, y\_key, 0 );
assert( xnode && CV\_NODE\_IS\_INT(xnode->tag) &&
ynode && CV\_NODE\_IS\_INT(ynode->tag));
int x = xnode->data.i; // or x = cvReadInt( xnode, 0 );
int y = ynode->data.i; // or y = cvReadInt( ynode, 0 );
#elif 1 /* slower variant; does not use x\_key & y\_key */
CvFileNode* xnode = cvGetFileNodeByName( fs, pt, "x" );
CvFileNode* ynode = cvGetFileNodeByName( fs, pt, "y" );
assert( xnode && CV\_NODE\_IS\_INT(xnode->tag) &&
ynode && CV\_NODE\_IS\_INT(ynode->tag));
int x = xnode->data.i; // or x = cvReadInt( xnode, 0 );
int y = ynode->data.i; // or y = cvReadInt( ynode, 0 );
#else /* the slowest yet the easiest to use variant */
int x = cvReadIntByName( fs, pt, "x", 0 /* default value */ );
int y = cvReadIntByName( fs, pt, "y", 0 /* default value */ );
#endif
CV\_NEXT\_SEQ\_ELEM( seq->elem\_size, reader );
printf("%d: (%d, %d)\n", i, x, y );
}
}
cvReleaseFileStorage( &fs );
return 0;
}
\end{lstlisting}
Please note that whatever method of accessing a map you are using, it is
still much slower than using plain sequences; for example, in the above
example, it is more efficient to encode the points as pairs of integers
in a single numeric sequence.
\cvCPyFunc{GetRootFileNode}
Retrieves one of the top-level nodes of the file storage.
\cvdefC{CvFileNode* cvGetRootFileNode( \par const CvFileStorage* fs,\par int stream\_index=0 );}
\begin{description}
\cvarg{fs}{File storage}
\cvarg{stream\_index}{Zero-based index of the stream. See \cross{StartNextStream}. In most cases, there is only one stream in the file; however, there can be several.}
\end{description}
The function returns one of the top-level file
nodes. The top-level nodes do not have a name, they correspond to the
streams that are stored one after another in the file storage. If the
index is out of range, the function returns a NULL pointer, so all the
top-level nodes may be iterated by subsequent calls to the function with
\texttt{stream\_index=0,1,...}, until the NULL pointer is returned. This function
may be used as a base for recursive traversal of the file storage.
\fi
\cvCPyFunc{Load}
Loads an object from a file.
\cvdefC{void* cvLoad( \par const char* filename,\par CvMemStorage* storage=NULL,\par const char* name=NULL,\par const char** realName=NULL );}
\cvdefPy{Load(filename,storage=NULL,name=NULL)-> generic}
\begin{description}
\cvarg{filename}{File name}
\cvarg{storage}{Memory storage for dynamic structures, such as \cross{CvSeq} or \cross{CvGraph} . It is not used for matrices or images.}
\cvarg{name}{Optional object name. If it is NULL, the first top-level object in the storage will be loaded.}
\cvC{\cvarg{realName}{Optional output parameter that will contain the name of the loaded object (useful if \texttt{name=NULL})}}
\end{description}
The function loads an object from a file. It provides a
simple interface to \cvCPyCross{Read}. After the object is loaded, the file
storage is closed and all the temporary buffers are deleted. Thus,
to load a dynamic structure, such as a sequence, contour, or graph, one
should pass a valid memory storage destination to the function.
\ifC
\cvCPyFunc{OpenFileStorage}
Opens file storage for reading or writing data.
\cvdefC{CvFileStorage* cvOpenFileStorage(\par const char* filename,\par CvMemStorage* memstorage,\par int flags);}
\begin{description}
\cvarg{filename}{Name of the file associated with the storage}
\cvarg{memstorage}{Memory storage used for temporary data and for
storing dynamic structures, such as \cross{CvSeq} or \cross{CvGraph}.
If it is NULL, a temporary memory storage is created and used.}
\cvarg{flags}{Can be one of the following:
\begin{description}
\cvarg{CV\_STORAGE\_READ}{the storage is open for reading}
\cvarg{CV\_STORAGE\_WRITE}{the storage is open for writing}
\end{description}}
\end{description}
The function opens file storage for
reading or writing data. In the latter case, a new file is created
or an existing file is rewritten. The type of the read or written file is
determined by the filename extension: \texttt{.xml} for \texttt{XML}
and \texttt{.yml} or \texttt{.yaml} for \texttt{YAML}. The function
returns a pointer to the \cross{CvFileStorage} structure.
\cvCPyFunc{Read}
Decodes an object and returns a pointer to it.
\cvdefC{void* cvRead( \par CvFileStorage* fs,\par CvFileNode* node,\par CvAttrList* attributes=NULL );}
\begin{description}
\cvarg{fs}{File storage}
\cvarg{node}{The root object node}
\cvarg{attributes}{Unused parameter}
\end{description}
The function decodes a user object (creates an object in a
native representation from the file storage subtree) and returns it. The
object to be decoded must be an instance of a registered type that supports the
\texttt{read} method (see \cross{CvTypeInfo}). The type of the object is
determined by the type name that is encoded in the file. If the object
is a dynamic structure, it is created either in memory storage and passed to
\cross{OpenFileStorage} or, if a NULL pointer was passed, in temporary
memory storage, which is released when \cross{ReleaseFileStorage} is
called. Otherwise, if the object is not a dynamic structure, it is
created in a heap and should be released with a specialized function or by
using the generic \cross{Release}.
\cvCPyFunc{ReadByName}
Finds an object by name and decodes it.
\cvdefC{void* cvReadByName( \par CvFileStorage* fs,\par const CvFileNode* map,\par const char* name,\par CvAttrList* attributes=NULL );}
\begin{description}
\cvarg{fs}{File storage}
\cvarg{map}{The parent map. If it is NULL, the function searches a top-level node.}
\cvarg{name}{The node name}
\cvarg{attributes}{Unused parameter}
\end{description}
The function is a simple superposition of \cross{GetFileNodeByName} and \cross{Read}.
\cvCPyFunc{ReadInt}
Retrieves an integer value from a file node.
\cvdefC{int cvReadInt( \par const CvFileNode* node,\par int defaultValue=0 );}
\begin{description}
\cvarg{node}{File node}
\cvarg{defaultValue}{The value that is returned if \texttt{node} is NULL}
\end{description}
The function returns an integer that is represented
by the file node. If the file node is NULL, the \texttt{defaultValue}
is returned (thus, it is convenient to call the function right after
\cross{GetFileNode} without checking for a NULL pointer). If
the file node has type \texttt{CV\_NODE\_INT}, then \texttt{node->data.i} is
returned. If the file node has type \texttt{CV\_NODE\_REAL},
then \texttt{node->data.f} is converted to an integer and returned. Otherwise the
result is not determined.
\cvCPyFunc{ReadIntByName}
Finds a file node and returns its value.
\cvdefC{int cvReadIntByName( \par const CvFileStorage* fs,\par const CvFileNode* map,\par const char* name,\par int defaultValue=0 );}
\begin{description}
\cvarg{fs}{File storage}
\cvarg{map}{The parent map. If it is NULL, the function searches a top-level node.}
\cvarg{name}{The node name}
\cvarg{defaultValue}{The value that is returned if the file node is not found}
\end{description}
The function is a simple superposition of \cross{GetFileNodeByName} and \cross{ReadInt}.
\cvCPyFunc{ReadRawData}
Reads multiple numbers.
\cvdefC{void cvReadRawData(\par const CvFileStorage* fs,\par const CvFileNode* src,\par void* dst,\par const char* dt);}
\begin{description}
\cvarg{fs}{File storage}
\cvarg{src}{The file node (a sequence) to read numbers from}
\cvarg{dst}{Pointer to the destination array}
\cvarg{dt}{Specification of each array element. It has the same format as in \cross{WriteRawData}.}
\end{description}
The function reads elements from a file node that represents a sequence of scalars.
\cvCPyFunc{ReadRawDataSlice}
Initializes file node sequence reader.
\cvdefC{void cvReadRawDataSlice( \par const CvFileStorage* fs,\par CvSeqReader* reader,\par int count,\par void* dst,\par const char* dt );}
\begin{description}
\cvarg{fs}{File storage}
\cvarg{reader}{The sequence reader. Initialize it with \cross{StartReadRawData}.}
\cvarg{count}{The number of elements to read}
\cvarg{dst}{Pointer to the destination array}
\cvarg{dt}{Specification of each array element. It has the same format as in \cross{WriteRawData}.}
\end{description}
The function reads one or more elements from
the file node, representing a sequence, to a user-specified array. The
total number of read sequence elements is a product of \texttt{total}
and the number of components in each array element. For example, if
dt=\texttt{2if}, the function will read $\texttt{total} \times 3$
sequence elements. As with any sequence, some parts of the file node
sequence may be skipped or read repeatedly by repositioning the reader
using \cross{SetSeqReaderPos}.
\cvCPyFunc{ReadReal}
Retrieves a floating-point value from a file node.
\cvdefC{double cvReadReal( \par const CvFileNode* node,\par double defaultValue=0. );}
\begin{description}
\cvarg{node}{File node}
\cvarg{defaultValue}{The value that is returned if \texttt{node} is NULL}
\end{description}
The function returns a floating-point value
that is represented by the file node. If the file node is NULL, the
\texttt{defaultValue} is returned (thus, it is convenient to call
the function right after \cross{GetFileNode} without checking for a NULL
pointer). If the file node has type \texttt{CV\_NODE\_REAL},
then \texttt{node->data.f} is returned. If the file node has type
\texttt{CV\_NODE\_INT}, then \texttt{node-$>$data.f} is converted to floating-point
and returned. Otherwise the result is not determined.
\cvCPyFunc{ReadRealByName}
Finds a file node and returns its value.
\cvdefC{double cvReadRealByName(\par const CvFileStorage* fs,\par const CvFileNode* map,\par const char* name,\par double defaultValue=0.);}
\begin{description}
\cvarg{fs}{File storage}
\cvarg{map}{The parent map. If it is NULL, the function searches a top-level node.}
\cvarg{name}{The node name}
\cvarg{defaultValue}{The value that is returned if the file node is not found}
\end{description}
The function is a simple superposition of \cross{GetFileNodeByName} and \cross{ReadReal}.
\cvCPyFunc{ReadString}
Retrieves a text string from a file node.
\cvdefC{const char* cvReadString( \par const CvFileNode* node,\par const char* defaultValue=NULL );}
\begin{description}
\cvarg{node}{File node}
\cvarg{defaultValue}{The value that is returned if \texttt{node} is NULL}
\end{description}
The function returns a text string that is represented
by the file node. If the file node is NULL, the \texttt{defaultValue}
is returned (thus, it is convenient to call the function right after
\cross{GetFileNode} without checking for a NULL pointer). If
the file node has type \texttt{CV\_NODE\_STR}, then \texttt{node-$>$data.str.ptr}
is returned. Otherwise the result is not determined.
\cvCPyFunc{ReadStringByName}
Finds a file node by its name and returns its value.
\cvdefC{const char* cvReadStringByName( \par const CvFileStorage* fs,\par const CvFileNode* map,\par const char* name,\par const char* defaultValue=NULL );}
\begin{description}
\cvarg{fs}{File storage}
\cvarg{map}{The parent map. If it is NULL, the function searches a top-level node.}
\cvarg{name}{The node name}
\cvarg{defaultValue}{The value that is returned if the file node is not found}
\end{description}
The function is a simple superposition of \cross{GetFileNodeByName} and \cross{ReadString}.
\cvCPyFunc{RegisterType}
Registers a new type.
\cvdefC{void cvRegisterType(const CvTypeInfo* info);}
\begin{description}
\cvarg{info}{Type info structure}
\end{description}
The function registers a new type, which is
described by \texttt{info}. The function creates a copy of the structure,
so the user should delete it after calling the function.
\cvCPyFunc{Release}
Releases an object.
\cvdefC{void cvRelease( void** structPtr );}
\begin{description}
\cvarg{structPtr}{Double pointer to the object}
\end{description}
The function finds the type of a given object and calls \texttt{release} with the double pointer.
\cvCPyFunc{ReleaseFileStorage}
Releases file storage.
\cvdefC{void cvReleaseFileStorage(CvFileStorage** fs);}
\begin{description}
\cvarg{fs}{Double pointer to the released file storage}
\end{description}
The function closes the file associated with the storage and releases all the temporary structures. It must be called after all I/O operations with the storage are finished.
\fi
\cvCPyFunc{Save}
Saves an object to a file.
\cvdefC{void cvSave( \par const char* filename,\par const void* structPtr,\par const char* name=NULL,\par const char* comment=NULL,\par CvAttrList attributes=cvAttrList());}
\cvdefPy{Save(filename,structPtr,name=NULL,comment=NULL)-> None}
\begin{description}
\cvarg{filename}{File name}
\cvarg{structPtr}{Object to save}
\cvarg{name}{Optional object name. If it is NULL, the name will be formed from \texttt{filename}.}
\cvarg{comment}{Optional comment to put in the beginning of the file}
\cvC{\cvarg{attributes}{Optional attributes passed to \cross{Write}}}
\end{description}
The function saves an object to a file. It provides a simple interface to \cross{Write}.
\ifC
\cvCPyFunc{StartNextStream}
Starts the next stream.
\cvdefC{void cvStartNextStream(CvFileStorage* fs);}
\begin{description}
\cvarg{fs}{File storage}
\end{description}
The function starts the next stream in file storage. Both YAML and XML support multiple "streams." This is useful for concatenating files or for resuming the writing process.
\cvCPyFunc{StartReadRawData}
Initializes the file node sequence reader.
\cvdefC{void cvStartReadRawData( \par const CvFileStorage* fs,\par const CvFileNode* src,\par CvSeqReader* reader);}
\begin{description}
\cvarg{fs}{File storage}
\cvarg{src}{The file node (a sequence) to read numbers from}
\cvarg{reader}{Pointer to the sequence reader}
\end{description}
The function initializes the sequence reader to read data from a file node. The initialized reader can be then passed to \cross{ReadRawDataSlice}.
\cvCPyFunc{StartWriteStruct}
Starts writing a new structure.
\cvdefC{void cvStartWriteStruct( CvFileStorage* fs,\par const char* name,\par int struct\_flags,\par const char* typeName=NULL,\par CvAttrList attributes=cvAttrList( \par));}
\begin{description}
\cvarg{fs}{File storage}
\cvarg{name}{Name of the written structure. The structure can be accessed by this name when the storage is read.}
\cvarg{struct\_flags}{A combination one of the following values:
\begin{description}
\cvarg{CV\_NODE\_SEQ}{the written structure is a sequence (see discussion of \cross{CvFileStorage}), that is, its elements do not have a name.}
\cvarg{CV\_NODE\_MAP}{the written structure is a map (see discussion of \cross{CvFileStorage}), that is, all its elements have names.\end{description}}
One and only one of the two above flags must be specified}
\cvarg{CV\_NODE\_FLOW}{the optional flag that makes sense only for YAML streams. It means that the structure is written as a flow (not as a block), which is more compact. It is recommended to use this flag for structures or arrays whose elements are all scalars.}
\cvarg{typeName}{Optional parameter - the object type name. In
case of XML it is written as a \texttt{type\_id} attribute of the
structure opening tag. In the case of YAML it is written after a colon
following the structure name (see the example in \cross{CvFileStorage}
description). Mainly it is used with user objects. When the storage
is read, the encoded type name is used to determine the object type
(see \cross{CvTypeInfo} and \cross{FindTypeInfo}).}
\cvarg{attributes}{This parameter is not used in the current implementation}
\end{description}
The function starts writing a compound
structure (collection) that can be a sequence or a map. After all
the structure fields, which can be scalars or structures, are
written, \cross{EndWriteStruct} should be called. The function can
be used to group some objects or to implement the \texttt{write}
function for a some user object (see \cross{CvTypeInfo}).
\cvCPyFunc{TypeOf}
Returns the type of an object.
\cvdefC{CvTypeInfo* cvTypeOf( const void* structPtr );}
\begin{description}
\cvarg{structPtr}{The object pointer}
\end{description}
The function finds the type of a given object. It iterates
through the list of registered types and calls the \texttt{is\_instance}
function/method for every type info structure with that object until one
of them returns non-zero or until the whole list has been traversed. In
the latter case, the function returns NULL.
\cvCPyFunc{UnregisterType}
Unregisters the type.
\cvdefC{void cvUnregisterType( const char* typeName );}
\begin{description}
\cvarg{typeName}{Name of an unregistered type}
\end{description}
The function unregisters a type with
a specified name. If the name is unknown, it is possible to locate
the type info by an instance of the type using \cross{TypeOf} or by
iterating the type list, starting from \cross{FirstType}, and then calling
\texttt{cvUnregisterType(info->typeName)}.
\cvCPyFunc{Write}
Writes a user object.
\cvdefC{void cvWrite( CvFileStorage* fs,\par const char* name,\par const void* ptr,\par CvAttrList attributes=cvAttrList(\par) );}
\begin{description}
\cvarg{fs}{File storage}
\cvarg{name}{Name of the written object. Should be NULL if and only if the parent structure is a sequence.}
\cvarg{ptr}{Pointer to the object}
\cvarg{attributes}{The attributes of the object. They are specific for each particular type (see the dicsussion below).}
\end{description}
The function writes an object to file storage. First, the appropriate type info is found using \cross{TypeOf}. Then, the \texttt{write} method associated with the type info is called.
Attributes are used to customize the writing procedure. The standard types support the following attributes (all the \texttt{*dt} attributes have the same format as in \cross{WriteRawData}):
\begin{enumerate}
\item CvSeq
\begin{description}
\cvarg{header\_dt}{description of user fields of the sequence header that follow CvSeq, or CvChain (if the sequence is a Freeman chain) or CvContour (if the sequence is a contour or point sequence)}
\cvarg{dt}{description of the sequence elements.}
\cvarg{recursive}{if the attribute is present and is not equal to "0" or "false", the whole tree of sequences (contours) is stored.}
\end{description}
\item Cvgraph
\begin{description}
\cvarg{header\_dt}{description of user fields of the graph header that follows CvGraph;}
\cvarg{vertex\_dt}{description of user fields of graph vertices}
\cvarg{edge\_dt}{description of user fields of graph edges (note that the edge weight is always written, so there is no need to specify it explicitly)}
\end{description}
\end{enumerate}
Below is the code that creates the YAML file shown in the \texttt{CvFileStorage} description:
\begin{lstlisting}
#include "cxcore.h"
int main( int argc, char** argv )
{
CvMat* mat = cvCreateMat( 3, 3, CV\_32F );
CvFileStorage* fs = cvOpenFileStorage( "example.yml", 0, CV\_STORAGE\_WRITE );
cvSetIdentity( mat );
cvWrite( fs, "A", mat, cvAttrList(0,0) );
cvReleaseFileStorage( &fs );
cvReleaseMat( &mat );
return 0;
}
\end{lstlisting}
\cvCPyFunc{WriteComment}
Writes a comment.
\cvdefC{void cvWriteComment(\par CvFileStorage* fs,\par const char* comment,\par int eolComment);}
\begin{description}
\cvarg{fs}{File storage}
\cvarg{comment}{The written comment, single-line or multi-line}
\cvarg{eolComment}{If non-zero, the function tries to put the comment at the end of current line. If the flag is zero, if the comment is multi-line, or if it does not fit at the end of the current line, the comment starts a new line.}
\end{description}
The function writes a comment into file storage. The comments are skipped when the storage is read, so they may be used only for debugging or descriptive purposes.
\cvCPyFunc{WriteFileNode}
Writes a file node to another file storage.
\cvdefC{void cvWriteFileNode( \par CvFileStorage* fs,\par const char* new\_node\_name,\par const CvFileNode* node,\par int embed );}
\begin{description}
\cvarg{fs}{Destination file storage}
\cvarg{new\_file\_node}{New name of the file node in the destination file storage. To keep the existing name, use \cross{cvGetFileNodeName}}
\cvarg{node}{The written node}
\cvarg{embed}{If the written node is a collection and this parameter is not zero, no extra level of hiararchy is created. Instead, all the elements of \texttt{node} are written into the currently written structure. Of course, map elements may be written only to a map, and sequence elements may be written only to a sequence.}
\end{description}
The function writes a copy of a file node to file storage. Possible applications of the function are merging several file storages into one and conversion between XML and YAML formats.
\cvCPyFunc{WriteInt}
Writes an integer value.
\cvdefC{void cvWriteInt(\par CvFileStorage* fs,\par const char* name,\par int value);}
\begin{description}
\cvarg{fs}{File storage}
\cvarg{name}{Name of the written value. Should be NULL if and only if the parent structure is a sequence.}
\cvarg{value}{The written value}
\end{description}
The function writes a single integer value (with or without a name) to the file storage.
\cvCPyFunc{WriteRawData}
Writes multiple numbers.
\cvdefC{void cvWriteRawData( \par CvFileStorage* fs,\par const void* src,\par int len,\par const char* dt );}
\begin{description}
\cvarg{fs}{File storage}
\cvarg{src}{Pointer to the written array}
\cvarg{len}{Number of the array elements to write}
\cvarg{dt}{Specification of each array element that has the following format \newline
\texttt{([count]\{'u'|'c'|'w'|'s'|'i'|'f'|'d'\})...}
where the characters correspond to fundamental C types:
\begin{description}
\cvarg{u}{8-bit unsigned number}
\cvarg{c}{8-bit signed number}
\cvarg{w}{16-bit unsigned number}
\cvarg{s}{16-bit signed number}
\cvarg{i}{32-bit signed number}
\cvarg{f}{single precision floating-point number}
\cvarg{d}{double precision floating-point number}
\cvarg{r}{pointer, 32 lower bits of which are written as a signed integer. The type can be used to store structures with links between the elements.
\texttt{count} is the optional counter of values of a given type. For
example, \texttt{2if} means that each array element is a structure
of 2 integers, followed by a single-precision floating-point number. The
equivalent notations of the above specification are '\texttt{iif}',
'\texttt{2i1f}' and so forth. Other examples: \texttt{u} means that the
array consists of bytes, and \texttt{2d} means the array consists of pairs
of doubles.}
\end{description}}
\end{description}
The function writes an array, whose elements consist
of single or multiple numbers. The function call can be replaced with
a loop containing a few \cross{WriteInt} and \cross{WriteReal} calls, but
a single call is more efficient. Note that because none of the elements
have a name, they should be written to a sequence rather than a map.
\cvCPyFunc{WriteReal}
Writes a floating-point value.
\cvdefC{void cvWriteReal( \par CvFileStorage* fs,\par const char* name,\par double value );}
\begin{description}
\cvarg{fs}{File storage}
\cvarg{name}{Name of the written value. Should be NULL if and only if the parent structure is a sequence.}
\cvarg{value}{The written value}
\end{description}
The function writes a single floating-point
value (with or without a name) to file storage. Special
values are encoded as follows: NaN (Not A Number) as .NaN, $ \pm \infty $ as +.Inf
(-.Inf).
The following example shows how to use the low-level writing functions
to store custom structures, such as termination criteria, without
registering a new type.
\begin{lstlisting}
void write_termcriteria( CvFileStorage* fs, const char* struct_name,
CvTermCriteria* termcrit )
{
cvStartWriteStruct( fs, struct_name, CV_NODE_MAP, NULL, cvAttrList(0,0));
cvWriteComment( fs, "termination criteria", 1 ); // just a description
if( termcrit->type & CV_TERMCRIT_ITER )
cvWriteInteger( fs, "max_iterations", termcrit->max_iter );
if( termcrit->type & CV_TERMCRIT_EPS )
cvWriteReal( fs, "accuracy", termcrit->epsilon );
cvEndWriteStruct( fs );
}
\end{lstlisting}
\cvCPyFunc{WriteString}
Writes a text string.
\cvdefC{void cvWriteString( \par CvFileStorage* fs,\par const char* name,\par const char* str,\par int quote=0 );}
\begin{description}
\cvarg{fs}{File storage}
\cvarg{name}{Name of the written string . Should be NULL if and only if the parent structure is a sequence.}
\cvarg{str}{The written text string}
\cvarg{quote}{If non-zero, the written string is put in quotes, regardless of whether they are required. Otherwise, if the flag is zero, quotes are used only when they are required (e.g. when the string starts with a digit or contains spaces).}
\end{description}
The function writes a text string to file storage.
\fi
\fi
\ifCpp
\cvclass{FileStorage}
The XML/YAML file storage class
\begin{lstlisting}
class FileStorage
{
public:
enum { READ=0, WRITE=1, APPEND=2 };
enum { UNDEFINED=0, VALUE_EXPECTED=1, NAME_EXPECTED=2, INSIDE_MAP=4 };
// the default constructor
FileStorage();
// the constructor that opens the file for reading
// (flags=FileStorage::READ) or writing (flags=FileStorage::WRITE)
FileStorage(const string& filename, int flags);
// wraps the already opened CvFileStorage*
FileStorage(CvFileStorage* fs);
// the destructor; closes the file if needed
virtual ~FileStorage();
// opens the specified file for reading (flags=FileStorage::READ)
// or writing (flags=FileStorage::WRITE)
virtual bool open(const string& filename, int flags);
// checks if the storage is opened
virtual bool isOpened() const;
// closes the file
virtual void release();
// returns the first top-level node
FileNode getFirstTopLevelNode() const;
// returns the root file node
// (it's the parent of the first top-level node)
FileNode root(int streamidx=0) const;
// returns the top-level node by name
FileNode operator[](const string& nodename) const;
FileNode operator[](const char* nodename) const;
// returns the underlying CvFileStorage*
CvFileStorage* operator *() { return fs; }
const CvFileStorage* operator *() const { return fs; }
// writes the certain number of elements of the specified format
// (see DataType) without any headers
void writeRaw( const string& fmt, const uchar* vec, size_t len );
// writes an old-style object (CvMat, CvMatND etc.)
void writeObj( const string& name, const void* obj );
// returns the default object name from the filename
// (used by cvSave() with the default object name etc.)
static string getDefaultObjectName(const string& filename);
Ptr<CvFileStorage> fs;
string elname;
vector<char> structs;
int state;
};
\end{lstlisting}
\cvclass{FileNode}
The XML/YAML file node class
\begin{lstlisting}
class CV_EXPORTS FileNode
{
public:
enum { NONE=0, INT=1, REAL=2, FLOAT=REAL, STR=3,
STRING=STR, REF=4, SEQ=5, MAP=6, TYPE_MASK=7,
FLOW=8, USER=16, EMPTY=32, NAMED=64 };
FileNode();
FileNode(const CvFileStorage* fs, const CvFileNode* node);
FileNode(const FileNode& node);
FileNode operator[](const string& nodename) const;
FileNode operator[](const char* nodename) const;
FileNode operator[](int i) const;
int type() const;
int rawDataSize(const string& fmt) const;
bool empty() const;
bool isNone() const;
bool isSeq() const;
bool isMap() const;
bool isInt() const;
bool isReal() const;
bool isString() const;
bool isNamed() const;
string name() const;
size_t size() const;
operator int() const;
operator float() const;
operator double() const;
operator string() const;
FileNodeIterator begin() const;
FileNodeIterator end() const;
void readRaw( const string& fmt, uchar* vec, size_t len ) const;
void* readObj() const;
// do not use wrapper pointer classes for better efficiency
const CvFileStorage* fs;
const CvFileNode* node;
};
\end{lstlisting}
\cvclass{FileNodeIterator}
The XML/YAML file node iterator class
\begin{lstlisting}
class CV_EXPORTS FileNodeIterator
{
public:
FileNodeIterator();
FileNodeIterator(const CvFileStorage* fs,
const CvFileNode* node, size_t ofs=0);
FileNodeIterator(const FileNodeIterator& it);
FileNode operator *() const;
FileNode operator ->() const;
FileNodeIterator& operator ++();
FileNodeIterator operator ++(int);
FileNodeIterator& operator --();
FileNodeIterator operator --(int);
FileNodeIterator& operator += (int);
FileNodeIterator& operator -= (int);
FileNodeIterator& readRaw( const string& fmt, uchar* vec,
size_t maxCount=(size_t)INT_MAX );
const CvFileStorage* fs;
const CvFileNode* container;
CvSeqReader reader;
size_t remaining;
};
\end{lstlisting}
\fi