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 high-level data structures.
CvMemStorage
------------
..ocv:struct:: CvMemStorage
A storage for various OpenCV dynamic data structures, such as ``CvSeq``, ``CvSet`` etc.
Memory storage is a low-level 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 occupied - ``free_space`` contains the number of free bytes left in the end of ``top``.
A new memory buffer that may be allocated explicitly by :ocv:cfunc:`MemStorageAlloc` function or implicitly by higher-level functions, such as :ocv:cfunc:`SeqPush`, :ocv:cfunc:`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 :ocv:cfunc:`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``)
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.
pointers to another sequences in a sequence tree. Sequence trees are used to store hierarchical contour structures, retrieved by :ocv:cfunc:`FindContours`
There are two types of sequences - dense and sparse. The base type for dense
sequences is :ocv:struct:`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 :ocv:struct:`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.
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 10-element sequence will select a 5-element slice, containing the pre-last (8th), last (9th), the very first (0th), second (1th) and third (2nd)
elements. The functions normalize the slice argument in the following way:
#.:ocv:cfunc:`SliceLength` is called to determine the length of the slice,
#.``start_index`` of the slice is normalized similarly to the argument of :ocv:cfunc:`GetSeqElem` (i.e., negative indices are allowed). The actual slice to process starts at the normalized ``start_index`` and lasts :ocv:cfunc:`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 sub-sequence may be extracted using the :ocv:cfunc:`SeqSlice` function, or stored into a continuous
buffer with :ocv:cfunc:`CvtSeqToArray` (optionally, followed by :ocv:cfunc:`MakeSeqHeaderForArray`).
CvSet
-----
..ocv:struct:: CvSet
The structure ``CvSet`` is a base for OpenCV 1.x sparse data structures. It is derived from :ocv:struct:`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 most-significant 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 :ocv:struct:`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 (:ocv:struct:`CvGraph`), sparse multi-dimensional arrays (:ocv:struct:`CvSparseMat`), and planar subdivisions (:ocv:struct:`CvSubdiv2D`).
:ocv:struct:`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.
CvGraphScanner
--------------
..ocv:struct:: CvGraphScanner
The structure ``CvGraphScanner`` is used for depth-first graph traversal. See discussion of the functions below.
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.
ClearSeq
--------
Clears a sequence.
..ocv:cfunction:: void cvClearSeq( CvSeq* seq )
:param seq:Sequence
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 :ocv:cfunc:`ClearMemStorage` or :ocv:cfunc:`ReleaseMemStorage` from time to time somewhere in a top-level processing loop.
:param storage:The destination storage block to hold the new sequence header and the copied data, if any. If it is NULL, the function uses the storage block containing the input sequence.
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 )``.
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
..image:: pics/memstorage1.png
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
..image:: pics/memstorage2.png
CreateGraph
-----------
Creates an empty graph.
..ocv:cfunction:: CvGraph* cvCreateGraph( int graph_flags, int header_size, int vtx_size, int edge_size, CvMemStorage* storage )
:param graph_flags:Type of the created graph. Usually, it is either ``CV_SEQ_KIND_GRAPH`` for generic unoriented graphs and ``CV_SEQ_KIND_GRAPH | CV_GRAPH_FLAG_ORIENTED`` for generic oriented graphs.
:param header_size:Graph header size; may not be less than ``sizeof(CvGraph)``
:param vtx_size:Graph vertex size; the custom vertex structure must start with :ocv:struct:`CvGraphVtx` (use ``CV_GRAPH_VERTEX_FIELDS()`` )
:param edge_size:Graph edge size; the custom edge structure must start with :ocv:struct:`CvGraphEdge` (use ``CV_GRAPH_EDGE_FIELDS()`` )
:param storage:The graph container
The function creates an empty graph and returns a pointer to it.
CreateGraphScanner
------------------
Creates structure for depth-first graph traversal.
..ocv:cfunction:: CvGraphScanner* cvCreateGraphScanner( CvGraph* graph, CvGraphVtx* vtx=NULL, int mask=CV_GRAPH_ALL_ITEMS )
:param vtx:Initial vertex to start from. If NULL, the traversal starts from the first vertex (a vertex with the minimal index in the sequence of vertices).
:param mask:Event mask indicating which events are of interest to the user (where :ocv:cfunc:`NextGraphItem` function returns control to the user) It can be ``CV_GRAPH_ALL_ITEMS`` (all events are of interest) or a combination of the following flags:
***CV_GRAPH_VERTEX** stop at the graph vertices visited for the first time
***CV_GRAPH_TREE_EDGE** stop at tree edges ( ``tree edge`` is the edge connecting the last visited vertex and the vertex to be visited next)
***CV_GRAPH_BACK_EDGE** stop at back edges ( ``back edge`` is an edge connecting the last visited vertex with some of its ancestors in the search tree)
***CV_GRAPH_FORWARD_EDGE** stop at forward edges ( ``forward edge`` is an edge connecting the last visited vertex with some of its descendants in the search tree. The forward edges are only possible during oriented graph traversal)
***CV_GRAPH_CROSS_EDGE** stop at cross edges ( ``cross edge`` is an edge connecting different search trees or branches of the same tree. The ``cross edges`` are only possible during oriented graph traversal)
***CV_GRAPH_ANY_EDGE** stop at any edge ( ``tree, back, forward`` , and ``cross edges`` )
***CV_GRAPH_NEW_TREE** stop in the beginning of every new search tree. When the traversal procedure visits all vertices and edges reachable from the initial vertex (the visited vertices together with tree edges make up a tree), it searches for some unvisited vertex in the graph and resumes the traversal process from that vertex. Before starting a new tree (including the very first tree when ``cvNextGraphItem`` is called for the first time) it generates a ``CV_GRAPH_NEW_TREE`` event. For unoriented graphs, each search tree corresponds to a connected component of the graph.
:param seqFlags:Flags of the created sequence. If the sequence is not passed to any function working with a specific type of sequences, the sequence value may be set to 0, otherwise the appropriate type must be selected from the list of predefined sequence types.
:param headerSize:Size of the sequence header; must be greater than or equal to ``sizeof(CvSeq)`` . If a specific type or its extension is indicated, this type must fit the base type header.
:param elemSize:Size of the sequence elements in bytes. The size must be consistent with the sequence type. For example, for a sequence of points to be created, the element type ``CV_SEQ_ELTYPE_POINT`` should be specified and the parameter ``elemSize`` must be equal to ``sizeof(CvPoint)`` .
:param storage:Sequence location
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
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
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
..ocv:cfunction:: int cvGraphAddEdge( CvGraph* graph, int start_idx, int end_idx, const CvGraphEdge* edge=NULL, CvGraphEdge** inserted_edge=NULL )
:param graph:Graph
:param start_idx:Index of the starting vertex of the edge
:param end_idx:Index of the ending vertex of the edge. For an unoriented graph, the order of the vertex parameters does not matter.
:param edge:Optional input parameter, initialization data for the edge
:param inserted_edge:Optional output parameter to contain the address of the inserted edge
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.
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.
GraphRemoveVtxByPtr
-------------------
Removes a vertex from a graph by using its pointer.
..ocv:cfunction:: int cvGraphRemoveVtxByPtr( CvGraph* graph, CvGraphVtx* vtx )
:param graph:Graph
:param vtx:Pointer to the removed vertex
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.
:param tree_iterator:Tree iterator initialized by the function
:param first:The initial node to start traversing from
:param max_level:The maximal level of the tree ( ``first`` node assumed to be at the first level) to traverse up to. For example, 1 means that only nodes at the same level as ``first`` should be visited, 2 means that the nodes on the same level as ``first`` and their direct children should be visited, and so forth.
The function initializes the tree iterator. The tree is traversed in depth-first order.
:param parent:The parent node that is already in the tree
:param frame:The top level node. If ``parent`` and ``frame`` are the same, the ``v_prev`` field of ``node`` is set to NULL rather than ``parent`` .
The function adds another node into tree. The function does not allocate any memory, it can only modify links of the tree nodes.
MakeSeqHeaderForArray
---------------------
Constructs a sequence header for an array.
..ocv:cfunction:: CvSeq* cvMakeSeqHeaderForArray( int seq_type, int header_size, int elem_size, void* elements, int total, CvSeq* seq, CvSeqBlock* block )
:param seq_type:Type of the created sequence
:param header_size:Size of the header of the sequence. Parameter sequence must point to the structure of that size or greater
:param elem_size:Size of the sequence elements
:param elements:Elements that will form a sequence
:param total:Total number of elements in the sequence. The number of array elements must be equal to the value of this parameter.
:param seq:Pointer to the local variable that is used as the sequence header
:param block:Pointer to the local variable that is the header of the single sequence block
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
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.
:param element:Pointer to the element within the sequence
:param block:Optional argument. If the pointer is not ``NULL`` , the address of the sequence block that contains the element is stored in this location.
The function returns the index of a sequence element or a negative number if the element is not found.
SeqInsert
---------
Inserts an element in the middle of a sequence.
..ocv:cfunction:: char* cvSeqInsert( CvSeq* seq, int beforeIndex, void* element=NULL )
:param seq:Sequence
:param beforeIndex:Index before which the element is inserted. Inserting before 0 (the minimal allowed value of the parameter) is equal to :ocv:cfunc:`SeqPushFront` and inserting before ``seq->total`` (the maximal allowed value of the parameter) is equal to :ocv:cfunc:`SeqPush` .
:param element:Optional parameter. If the pointer is not zero, the function copies the removed element to this location.
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.
SeqPopMulti
-----------
Removes several elements from either end of a sequence.
..ocv:cfunction:: void cvSeqPopMulti( CvSeq* seq, void* elements, int count, int in_front=0 )
***CV_FRONT** the elements are added to the beginning of the sequence
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.
:param func:The comparison function that returns negative, zero or positive value depending on the relationships among the elements (see also :ocv:cfunc:`SeqSort` )
:param is_sorted:Whether the sequence is sorted or not
:param elem_idx:Output parameter; index of the found element
:param slice:The part of the sequence to be extracted
:param storage:The destination storage block to hold the new sequence header and the copied data, if any. If it is NULL, the function uses the storage block containing the input sequence.
:param copy_data:The flag that indicates whether to copy the elements of the extracted slice ( ``copy_data!=0`` ) or not ( ``copy_data=0`` )
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 sub-sequence may be extracted using this function.
SeqSort
-------
Sorts sequence element using the specified comparison function.
:param func:The comparison function that returns a negative, zero, or positive value depending on the relationships among the elements (see the above declaration and the example below) - a similar function is used by ``qsort`` from C runline except that in the latter, ``userdata`` is not used
..ocv:cfunction:: int cvSetAdd( CvSet* setHeader, CvSetElem* elem=NULL, CvSetElem** inserted_elem=NULL )
:param setHeader:Set
:param elem:Optional input argument, an inserted element. If not NULL, the function copies the data to the allocated node (the MSB of the first integer field is cleared after copying).
:param inserted_elem:Optional output argument; the pointer to the allocated cell
The function allocates a new node, optionally copies
input element data to it, and returns the pointer and the index to the
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.
SetSeqReaderPos
---------------
Moves the reader to the specified position.
..ocv:cfunction:: void cvSetSeqReaderPos( CvSeqReader* reader, int index, int is_relative=0 )
:param reader:Reader state
:param index:The destination position. If the positioning mode is used (see the next parameter), the actual position will be ``index`` mod ``reader->seq->total`` .
:param is_relative:If it is not zero, then ``index`` is a relative to the current position
The function moves the read position to an absolute position or relative to the current position.
StartAppendToSeq
----------------
Initializes the process of writing data to a sequence.
:param reader:Reader state; initialized by the function
:param reverse:Determines the direction of the sequence traversal. If ``reverse`` is 0, the reader is positioned at the first sequence element; otherwise it is positioned at the last element.
The function initializes the reader state. After
that, all the sequence elements from the first one down to the last one
Creates a new sequence and initializes a writer for it.
..ocv:cfunction:: void cvStartWriteSeq( int seq_flags, int header_size, int elem_size, CvMemStorage* storage, CvSeqWriter* writer )
:param seq_flags:Flags of the created sequence. If the sequence is not passed to any function working with a specific type of sequences, the sequence value may be equal to 0; otherwise the appropriate type must be selected from the list of predefined sequence types.
:param header_size:Size of the sequence header. The parameter value may not be less than ``sizeof(CvSeq)`` . If a certain type or extension is specified, it must fit within the base type header.
:param elem_size:Size of the sequence elements in bytes; must be consistent with the sequence type. For example, if a sequence of points is created (element type ``CV_SEQ_ELTYPE_POINT`` ), then the parameter ``elem_size`` must be equal to ``sizeof(CvPoint)`` .
:param storage:Sequence location
:param writer:Writer state; initialized by the function
The function puts pointers of all nodes reachable from ``first`` into a single sequence. The pointers are written sequentially in the depth-first order.