The section describes OpenCV 1.x API for creating growable sequences and other dynamic data structures allocated in CvMemStorage. If you use the new C++, Python, Java etc interface, you will unlikely need this functionality. Use std::vector or other highlevel data structures.
A storage for various OpenCV dynamic data structures, such as CvSeq, CvSet etc.
 CvMemBlock* bottom¶
the first memory block in the doublelinked list of blocks
 CvMemBlock* top¶
the current partially allocated memory block in the list of blocks
 CvMemStorage* parent¶
the parent storage (if any) from which the new memory blocks are borrowed.
 int free_space¶
number of free bytes in the top block
 int block_size¶
the total size of the memory blocks
Memory storage is a lowlevel structure used to store dynamically growing data structures such as sequences, contours, graphs, subdivisions, etc. It is organized as a list of memory blocks of equal size  bottom field is the beginning of the list of blocks and top is the currently used block, but not necessarily the last block of the list. All blocks between bottom and top, not including the latter, are considered fully occupied; all blocks between top and the last block, not including top, are considered free and top itself is partly ocupied  free_space contains the number of free bytes left in the end of top.
A new memory buffer that may be allocated explicitly by MemStorageAlloc() function or implicitly by higherlevel functions, such as SeqPush(), GraphAddEdge() etc.
The buffer is put in the end of already allocated space in the top memory block, if there is enough free space. After allocation, free_space is decreased by the size of the allocated buffer plus some padding to keep the proper alignment. When the allocated buffer does not fit into the available portion of top, the next storage block from the list is taken as top and free_space is reset to the whole block size prior to the allocation.
If there are no more free blocks, a new block is allocated (or borrowed from the parent, see CreateChildMemStorage()) and added to the end of list. Thus, the storage behaves as a stack with bottom indicating bottom of the stack and the pair (top, free_space) indicating top of the stack. The stack top may be saved via SaveMemStoragePos(), restored via RestoreMemStoragePos(), or reset via ClearMemStorage().
The structure CvMemBlock represents a single block of memory storage. The actual data in the memory blocks follows the header.
The structure stores the position in the memory storage. It is used by SaveMemStoragePos() and RestoreMemStoragePos().
Dynamically growing sequence.
 int flags¶
sequence flags, including the sequence signature (CV_SEQ_MAGIC_VAL or CV_SET_MAGIC_VAL), type of the elements and some other information about the sequence.
 int header_size¶
size of the sequence header. It should be sizeof(CvSeq) at minimum. See CreateSeq().
 CvSeq* h_prev¶
 CvSeq* h_next¶
 CvSeq* v_prev¶
 CvSeq* v_next¶
pointers to another sequences in a sequence tree. Sequence trees are used to store hierarchical contour structures, retrieved by FindContours()
 int total¶
the number of sequence elements
 int elem_size¶
size of each sequence element in bytes
 CvMemStorage* storage¶
memory storage where the sequence resides. It can be a NULL pointer.
 CvSeqBlock* first¶
pointer to the first data block
The structure CvSeq is a base for all of OpenCV dynamic data structures. There are two types of sequences  dense and sparse. The base type for dense sequences is CvSeq and such sequences are used to represent growable 1d arrays  vectors, stacks, queues, and deques. They have no gaps in the middle  if an element is removed from the middle or inserted into the middle of the sequence, the elements from the closer end are shifted. Sparse sequences have CvSet as a base class and they are discussed later in more detail. They are sequences of nodes; each may be either occupied or free as indicated by the node flag. Such sequences are used for unordered data structures such as sets of elements, graphs, hash tables and so forth.
A sequence slice. In C++ interface the class Range should be used instead.
inclusive start index of the sequence slice
exclusive end index of the sequence slice
There are helper functions to construct the slice and to compute its length:
#define CV_WHOLE_SEQ_END_INDEX 0x3fffffff
#define CV_WHOLE_SEQ cvSlice(0, CV_WHOLE_SEQ_END_INDEX)
Calculates the sequence slice length
Some of functions that operate on sequences take a CvSlice slice parameter that is often set to the whole sequence (CV_WHOLE_SEQ) by default. Either of the start_index and end_index may be negative or exceed the sequence length. If they are equal, the slice is considered empty (i.e., contains no elements). Because sequences are treated as circular structures, the slice may select a few elements in the end of a sequence followed by a few elements at the beginning of the sequence. For example, cvSlice(2, 3) in the case of a 10element sequence will select a 5element slice, containing the prelast (8th), last (9th), the very first (0th), second (1th) and third (2nd) elements. The functions normalize the slice argument in the following way:
 SliceLength() is called to determine the length of the slice,
 start_index of the slice is normalized similarly to the argument of GetSeqElem() (i.e., negative indices are allowed). The actual slice to process starts at the normalized start_index and lasts SliceLength() elements (again, assuming the sequence is a circular structure).
If a function does not accept a slice argument, but you want to process only a part of the sequence, the subsequence may be extracted using the SeqSlice() function, or stored into a continuous buffer with CvtSeqToArray() (optionally, followed by MakeSeqHeaderForArray()).
The structure CvSet is a base for OpenCV 1.x sparse data structures. It is derived from CvSeq and includes an additional member free_elems  a list of free nodes. Every node of the set, whether free or not, is an element of the underlying sequence. While there are no restrictions on elements of dense sequences, the set (and derived structures) elements must start with an integer field and be able to fit CvSetElem structure, because these two fields (an integer followed by a pointer) are required for the organization of a node set with the list of free nodes. If a node is free, the flags field is negative (the mostsignificant bit, or MSB, of the field is set), and the next_free points to the next free node (the first free node is referenced by the free_elems field of CvSet). And if a node is occupied, the flags field is positive and contains the node index that may be retrieved using the (set_elem>flags & CV_SET_ELEM_IDX_MASK) expressions, the rest of the node content is determined by the user. In particular, the occupied nodes are not linked as the free nodes are, so the second field can be used for such a link as well as for some different purpose. The macro CV_IS_SET_ELEM(set_elem_ptr) can be used to determined whether the specified node is occupied or not.
Initially the set and the free node list are empty. When a new node is requested from the set, it is taken from the list of free nodes, which is then updated. If the list appears to be empty, a new sequence block is allocated and all the nodes within the block are joined in the list of free nodes. Thus, the total field of the set is the total number of nodes both occupied and free. When an occupied node is released, it is added to the list of free nodes. The node released last will be occupied first.
CvSet is used to represent graphs (CvGraph), sparse multidimensional arrays (CvSparseMat), and planar subdivisions (CvSubdiv2D).
The structure CvGraph is a base for graphs used in OpenCV 1.x. It inherits from CvSet, that is, it is considered as a set of vertices. Besides, it contains another set as a member, a set of graph edges. Graphs in OpenCV are represented using adjacency lists format.
The structure CvGraphScanner is used for depthfirst graph traversal. See discussion of the functions below.
The structure CvTreeNodeIterator is used to traverse trees of sequences.
Clears a graph.
Parameters: 


The function removes all vertices and edges from a graph. The function has O(1) time complexity.
Clears memory storage.
Parameters: 


The function resets the top (free space boundary) of the storage to the very beginning. This function does not deallocate any memory. If the storage has a parent, the function returns all blocks to the parent.
Clears a sequence.
Parameters: 


The function removes all elements from a sequence. The function does not return the memory to the storage block, but this memory is reused later when new elements are added to the sequence. The function has ‘O(1)’ time complexity.
Note
It is impossible to deallocate a sequence, i.e. free space in the memory storage occupied by the sequence. Instead, call ClearMemStorage() or ReleaseMemStorage() from time to time somewhere in a toplevel processing loop.
Clears a set.
Parameters: 


The function removes all elements from set. It has O(1) time complexity.
Clones a graph.
Parameters: 


The function creates a full copy of the specified graph. If the graph vertices or edges have pointers to some external data, it can still be shared between the copies. The vertex and edge indices in the new graph may be different from the original because the function defragments the vertex and edge sets.
Creates a copy of a sequence.
Parameters: 


The function makes a complete copy of the input sequence and returns it.
The call cvCloneSeq( seq, storage ) is equivalent to cvSeqSlice( seq, CV_WHOLE_SEQ, storage, 1 ).
Creates child memory storage.
Parameters: 


The function creates a child memory storage that is similar to simple memory storage except for the differences in the memory allocation/deallocation mechanism. When a child storage needs a new block to add to the block list, it tries to get this block from the parent. The first unoccupied parent block available is taken and excluded from the parent block list. If no blocks are available, the parent either allocates a block or borrows one from its own parent, if any. In other words, the chain, or a more complex structure, of memory storages where every storage is a child/parent of another is possible. When a child storage is released or even cleared, it returns all blocks to the parent. In other aspects, child storage is the same as simple storage.
Child storage is useful in the following situation. Imagine that the user needs to process dynamic data residing in a given storage area and put the result back to that same storage area. With the simplest approach, when temporary data is resided in the same storage area as the input and output data, the storage area will look as follows after processing:
Dynamic data processing without using child storage
That is, garbage appears in the middle of the storage. However, if one creates a child memory storage at the beginning of processing, writes temporary data there, and releases the child storage at the end, no garbage will appear in the source/destination storage:
Dynamic data processing using a child storage
Creates an empty graph.
Parameters: 


The function creates an empty graph and returns a pointer to it.
Creates structure for depthfirst graph traversal.
Parameters: 


The function creates a structure for depthfirst graph traversal/search. The initialized structure is used in the NextGraphItem() function  the incremental traversal procedure.
Creates memory storage.
Parameters:  blockSize – Size of the storage blocks in bytes. If it is 0, the block size is set to a default value  currently it is about 64K. 

The function creates an empty memory storage. See CvMemStorage description.
Creates a sequence.
Parameters: 


The function creates a sequence and returns the pointer to it. The function allocates the sequence header in the storage block as one continuous chunk and sets the structure fields flags , elemSize , headerSize , and storage to passed values, sets delta_elems to the default value (that may be reassigned using the SetSeqBlockSize() function), and clears other header fields, including the space following the first sizeof(CvSeq) bytes.
Creates an empty set.
Parameters: 


The function creates an empty set with a specified header size and element size, and returns the pointer to the set. This function is just a thin layer on top of CreateSeq().
Copies a sequence to one continuous block of memory.
Parameters: 


The function copies the entire sequence or subsequence to the specified buffer and returns the pointer to the buffer.
Finishes the process of writing a sequence.
Parameters: 


The function finishes the writing process and returns the pointer to the written sequence. The function also truncates the last incomplete sequence block to return the remaining part of the block to memory storage. After that, the sequence can be read and modified safely. See StartWriteSeq() and StartAppendToSeq()
Finds an edge in a graph.
Parameters: 


#define cvGraphFindEdge cvFindGraphEdge
The function finds the graph edge connecting two specified vertices and returns a pointer to it or NULL if the edge does not exist.
Finds an edge in a graph by using its pointer.
Parameters: 


#define cvGraphFindEdgeByPtr cvFindGraphEdgeByPtr
The function finds the graph edge connecting two specified vertices and returns pointer to it or NULL if the edge does not exists.
Updates sequence headers from the writer.
Parameters: 


The function is intended to enable the user to read sequence elements, whenever required, during the writing process, e.g., in order to check specific conditions. The function updates the sequence headers to make reading from the sequence possible. The writer is not closed, however, so that the writing process can be continued at any time. If an algorithm requires frequent flushes, consider using SeqPush() instead.
Finds a graph vertex by using its index.
Parameters: 


The function finds the graph vertex by using its index and returns the pointer to it or NULL if the vertex does not belong to the graph.
Returns a pointer to a sequence element according to its index.
Parameters: 


#define CV_GET_SEQ_ELEM( TYPE, seq, index ) (TYPE*)cvGetSeqElem( (CvSeq*)(seq), (index) )
The function finds the element with the given index in the sequence and returns the pointer to it. If the element is not found, the function returns 0. The function supports negative indices, where 1 stands for the last sequence element, 2 stands for the one before last, etc. If the sequence is most likely to consist of a single sequence block or the desired element is likely to be located in the first block, then the macro CV_GET_SEQ_ELEM( elemType, seq, index ) should be used, where the parameter elemType is the type of sequence elements ( CvPoint for example), the parameter seq is a sequence, and the parameter index is the index of the desired element. The macro checks first whether the desired element belongs to the first block of the sequence and returns it if it does; otherwise the macro calls the main function GetSeqElem . Negative indices always cause the GetSeqElem() call. The function has O(1) time complexity assuming that the number of blocks is much smaller than the number of elements.
Returns the current reader position.
Parameters: 


The function returns the current reader position (within 0 ... reader>seq>total  1).
Finds a set element by its index.
Parameters: 


The function finds a set element by its index. The function returns the pointer to it or 0 if the index is invalid or the corresponding node is free. The function supports negative indices as it uses GetSeqElem() to locate the node.
Adds an edge to a graph.
Parameters: 


The function connects two specified vertices. The function returns 1 if the edge has been added successfully, 0 if the edge connecting the two vertices exists already and 1 if either of the vertices was not found, the starting and the ending vertex are the same, or there is some other critical situation. In the latter case (i.e., when the result is negative), the function also reports an error by default.
Adds an edge to a graph by using its pointer.
Parameters: 


The function connects two specified vertices. The function returns 1 if the edge has been added successfully, 0 if the edge connecting the two vertices exists already, and 1 if either of the vertices was not found, the starting and the ending vertex are the same or there is some other critical situation. In the latter case (i.e., when the result is negative), the function also reports an error by default.
Adds a vertex to a graph.
Parameters: 


The function adds a vertex to the graph and returns the vertex index.
Returns the index of a graph edge.
Parameters: 


The function returns the index of a graph edge.
Removes an edge from a graph.
Parameters: 


The function removes the edge connecting two specified vertices. If the vertices are not connected [in that order], the function does nothing.
Removes an edge from a graph by using its pointer.
Parameters: 


The function removes the edge connecting two specified vertices. If the vertices are not connected [in that order], the function does nothing.
Removes a vertex from a graph.
Parameters: 


The function removes a vertex from a graph together with all the edges incident to it. The function reports an error if the input vertex does not belong to the graph. The return value is the number of edges deleted, or 1 if the vertex does not belong to the graph.
Removes a vertex from a graph by using its pointer.
Parameters: 


The function removes a vertex from the graph by using its pointer together with all the edges incident to it. The function reports an error if the vertex does not belong to the graph. The return value is the number of edges deleted, or 1 if the vertex does not belong to the graph.
Counts the number of edges indicent to the vertex.
Parameters: 


The function returns the number of edges incident to the specified vertex, both incoming and outgoing. To count the edges, the following code is used:
CvGraphEdge* edge = vertex>first; int count = 0;
while( edge )
{
edge = CV_NEXT_GRAPH_EDGE( edge, vertex );
count++;
}
The macro CV_NEXT_GRAPH_EDGE( edge, vertex ) returns the edge incident to vertex that follows after edge .
Finds an edge in a graph.
Parameters: 


The function returns the number of edges incident to the specified vertex, both incoming and outcoming.
Returns the index of a graph vertex.
Parameters: 


The function returns the index of a graph vertex.
Initializes the tree node iterator.
Parameters: 


The function initializes the tree iterator. The tree is traversed in depthfirst order.
Adds a new node to a tree.
Parameters: 


The function adds another node into tree. The function does not allocate any memory, it can only modify links of the tree nodes.
Constructs a sequence header for an array.
Parameters: 


The function initializes a sequence header for an array. The sequence header as well as the sequence block are allocated by the user (for example, on stack). No data is copied by the function. The resultant sequence will consists of a single block and have NULL storage pointer; thus, it is possible to read its elements, but the attempts to add elements to the sequence will raise an error in most cases.
Allocates a memory buffer in a storage block.
Parameters: 


The function allocates a memory buffer in a storage block. The buffer size must not exceed the storage block size, otherwise a runtime error is raised. The buffer address is aligned by CV_STRUCT_ALIGN=sizeof(double) (for the moment) bytes.
Allocates a text string in a storage block.
Parameters: 


typedef struct CvString
{
int len;
char* ptr;
}
CvString;
The function creates copy of the string in memory storage. It returns the structure that contains userpassed or computed length of the string and pointer to the copied string.
Executes one or more steps of the graph traversal procedure.
Parameters: 


The function traverses through the graph until an event of interest to the user (that is, an event, specified in the mask in the CreateGraphScanner() call) is met or the traversal is completed. In the first case, it returns one of the events listed in the description of the mask parameter above and with the next call it resumes the traversal. In the latter case, it returns CV_GRAPH_OVER (1). When the event is CV_GRAPH_VERTEX , CV_GRAPH_BACKTRACKING , or CV_GRAPH_NEW_TREE , the currently observed vertex is stored in scanner:math:`>`vtx . And if the event is edgerelated, the edge itself is stored at scanner:math:`>`edge , the previously visited vertex  at scanner:math:`>`vtx and the other ending vertex of the edge  at scanner:math:`>`dst .
Returns the currently observed node and moves the iterator toward the next node.
Parameters: 


The function returns the currently observed node and then updates the iterator  moving it toward the next node. In other words, the function behavior is similar to the *p++ expression on a typical C pointer or C++ collection iterator. The function returns NULL if there are no more nodes.
Returns the currently observed node and moves the iterator toward the previous node.
Parameters: 


The function returns the currently observed node and then updates the iterator  moving it toward the previous node. In other words, the function behavior is similar to the *p expression on a typical C pointer or C++ collection iterator. The function returns NULL if there are no more nodes.
Completes the graph traversal procedure.
Parameters: 


The function completes the graph traversal procedure and releases the traverser state.
Releases memory storage.
Parameters: 


The function deallocates all storage memory blocks or returns them to the parent, if any. Then it deallocates the storage header and clears the pointer to the storage. All child storage associated with a given parent storage block must be released before the parent storage block is released.
Restores memory storage position.
Parameters: 


The function restores the position of the storage top from the parameter pos . This function and the function cvClearMemStorage are the only methods to release memory occupied in memory blocks. Note again that there is no way to free memory in the middle of an occupied portion of a storage block.
Saves memory storage position.
Parameters: 


The function saves the current position of the storage top to the parameter pos . The function cvRestoreMemStoragePos can further retrieve this position.
Returns the index of a specific sequence element.
Parameters: 


The function returns the index of a sequence element or a negative number if the element is not found.
Inserts an element in the middle of a sequence.
Parameters: 


The function shifts the sequence elements from the inserted position to the nearest end of the sequence and copies the element content there if the pointer is not NULL. The function returns a pointer to the inserted element.
Inserts an array in the middle of a sequence.
Parameters: 


The function inserts all fromArr array elements at the specified position of the sequence. The array fromArr can be a matrix or another sequence.
Reverses the order of sequence elements.
Parameters: 


The function reverses the sequence inplace  the first element becomes the last one, the last element becomes the first one and so forth.
Removes an element from the end of a sequence.
Parameters: 


The function removes an element from a sequence. The function reports an error if the sequence is already empty. The function has O(1) complexity.
Removes an element from the beginning of a sequence.
Parameters: 


The function removes an element from the beginning of a sequence. The function reports an error if the sequence is already empty. The function has O(1) complexity.
Removes several elements from either end of a sequence.
Parameters: 


The function removes several elements from either end of the sequence. If the number of the elements to be removed exceeds the total number of elements in the sequence, the function removes as many elements as possible.
Adds an element to the end of a sequence.
Parameters: 


The function adds an element to the end of a sequence and returns a pointer to the allocated element. If the input element is NULL, the function simply allocates a space for one more element.
The following code demonstrates how to create a new sequence using this function:
CvMemStorage* storage = cvCreateMemStorage(0);
CvSeq* seq = cvCreateSeq( CV_32SC1, /* sequence of integer elements */
sizeof(CvSeq), /* header size  no extra fields */
sizeof(int), /* element size */
storage /* the container storage */ );
int i;
for( i = 0; i < 100; i++ )
{
int* added = (int*)cvSeqPush( seq, &i );
printf( "
}
...
/* release memory storage in the end */
cvReleaseMemStorage( &storage );
The function has O(1) complexity, but there is a faster method for writing large sequences (see StartWriteSeq() and related functions).
Adds an element to the beginning of a sequence.
Parameters: 


The function is similar to SeqPush() but it adds the new element to the beginning of the sequence. The function has O(1) complexity.
Pushes several elements to either end of a sequence.
Parameters: 


The function adds several elements to either end of a sequence. The elements are added to the sequence in the same order as they are arranged in the input array but they can fall into different sequence blocks.
Removes an element from the middle of a sequence.
Parameters: 


The function removes elements with the given index. If the index is out of range the function reports an error. An attempt to remove an element from an empty sequence is a special case of this situation. The function removes an element by shifting the sequence elements between the nearest end of the sequence and the index th position, not counting the latter.
Removes a sequence slice.
Parameters: 


The function removes a slice from the sequence.
Searches for an element in a sequence.
Parameters: 


/* a < b ? 1 : a > b ? 1 : 0 */
typedef int (CV_CDECL* CvCmpFunc)(const void* a, const void* b, void* userdata);
The function searches for the element in the sequence. If the sequence is sorted, a binary O(log(N)) search is used; otherwise, a simple linear search is used. If the element is not found, the function returns a NULL pointer and the index is set to the number of sequence elements if a linear search is used, or to the smallest index i, seq(i)>elem .
Makes a separate header for a sequence slice.
Parameters: 


The function creates a sequence that represents the specified slice of the input sequence. The new sequence either shares the elements with the original sequence or has its own copy of the elements. So if one needs to process a part of sequence but the processing function does not have a slice parameter, the required subsequence may be extracted using this function.
Sorts sequence element using the specified comparison function.
Parameters: 


/* a < b ? 1 : a > b ? 1 : 0 */
typedef int (CV_CDECL* CvCmpFunc)(const void* a, const void* b, void* userdata);
The function sorts the sequence inplace using the specified criteria. Below is an example of using this function:
/* Sort 2d points in toptobottom lefttoright order */
static int cmp_func( const void* _a, const void* _b, void* userdata )
{
CvPoint* a = (CvPoint*)_a;
CvPoint* b = (CvPoint*)_b;
int y_diff = a>y  b>y;
int x_diff = a>x  b>x;
return y_diff ? y_diff : x_diff;
}
...
CvMemStorage* storage = cvCreateMemStorage(0);
CvSeq* seq = cvCreateSeq( CV_32SC2, sizeof(CvSeq), sizeof(CvPoint), storage );
int i;
for( i = 0; i < 10; i++ )
{
CvPoint pt;
pt.x = rand()
pt.y = rand()
cvSeqPush( seq, &pt );
}
cvSeqSort( seq, cmp_func, 0 /* userdata is not used here */ );
/* print out the sorted sequence */
for( i = 0; i < seq>total; i++ )
{
CvPoint* pt = (CvPoint*)cvSeqElem( seq, i );
printf( "(
}
cvReleaseMemStorage( &storage );
Occupies a node in the set.
Parameters: 


The function allocates a new node, optionally copies input element data to it, and returns the pointer and the index to the node. The index value is taken from the lower bits of the flags field of the node. The function has O(1) complexity; however, there exists a faster function for allocating set nodes (see SetNew() ).
Adds an element to a set (fast variant).
Parameters: 


The function is an inline lightweight variant of SetAdd() . It occupies a new node and returns a pointer to it rather than an index.
Removes an element from a set.
Parameters: 


The function removes an element with a specified index from the set. If the node at the specified location is not occupied, the function does nothing. The function has O(1) complexity; however, SetRemoveByPtr() provides a quicker way to remove a set element if it is located already.
Removes a set element based on its pointer.
Parameters: 


The function is an inline lightweight variant of SetRemove() that requires an element pointer. The function does not check whether the node is occupied or not  the user should take care of that.
Sets up sequence block size.
Parameters: 


The function affects memory allocation granularity. When the free space in the sequence buffers has run out, the function allocates the space for deltaElems sequence elements. If this block immediately follows the one previously allocated, the two blocks are concatenated; otherwise, a new sequence block is created. Therefore, the bigger the parameter is, the lower the possible sequence fragmentation, but the more space in the storage block is wasted. When the sequence is created, the parameter deltaElems is set to the default value of about 1K. The function can be called any time after the sequence is created and affects future allocations. The function can modify the passed value of the parameter to meet memory storage constraints.
Moves the reader to the specified position.
Parameters: 


The function moves the read position to an absolute position or relative to the current position.
Initializes the process of writing data to a sequence.
Parameters: 


The function initializes the process of writing data to a sequence. Written elements are added to the end of the sequence by using the CV_WRITE_SEQ_ELEM( written_elem, writer ) macro. Note that during the writing process, other operations on the sequence may yield an incorrect result or even corrupt the sequence (see description of FlushSeqWriter() , which helps to avoid some of these problems).
Initializes the process of sequential reading from a sequence.
Parameters: 


The function initializes the reader state. After that, all the sequence elements from the first one down to the last one can be read by subsequent calls of the macro CV_READ_SEQ_ELEM( read_elem, reader ) in the case of forward reading and by using CV_REV_READ_SEQ_ELEM( read_elem, reader ) in the case of reverse reading. Both macros put the sequence element to read_elem and move the reading pointer toward the next element. A circular structure of sequence blocks is used for the reading process, that is, after the last element has been read by the macro CV_READ_SEQ_ELEM , the first element is read when the macro is called again. The same applies to CV_REV_READ_SEQ_ELEM . There is no function to finish the reading process, since it neither changes the sequence nor creates any temporary buffers. The reader field ptr points to the current element of the sequence that is to be read next. The code below demonstrates how to use the sequence writer and reader.
CvMemStorage* storage = cvCreateMemStorage(0);
CvSeq* seq = cvCreateSeq( CV_32SC1, sizeof(CvSeq), sizeof(int), storage );
CvSeqWriter writer;
CvSeqReader reader;
int i;
cvStartAppendToSeq( seq, &writer );
for( i = 0; i < 10; i++ )
{
int val = rand()
CV_WRITE_SEQ_ELEM( val, writer );
printf("
}
cvEndWriteSeq( &writer );
cvStartReadSeq( seq, &reader, 0 );
for( i = 0; i < seq>total; i++ )
{
int val;
#if 1
CV_READ_SEQ_ELEM( val, reader );
printf("
#else /* alternative way, that is prefferable if sequence elements are large,
or their size/type is unknown at compile time */
printf("
CV_NEXT_SEQ_ELEM( seq>elem_size, reader );
#endif
}
...
cvReleaseStorage( &storage );
Creates a new sequence and initializes a writer for it.
Parameters: 


The function is a combination of CreateSeq() and StartAppendToSeq() . The pointer to the created sequence is stored at writer>seq and is also returned by the EndWriteSeq() function that should be called at the end.
Gathers all node pointers to a single sequence.
Parameters: 


The function puts pointers of all nodes reacheable from first into a single sequence. The pointers are written sequentially in the depthfirst order.