The template class ``DataType`` is descriptive class for OpenCV primitive data types and other types that comply with the following definition. A primitive OpenCV data type is one of ``unsigned char, bool, signed char, unsigned short, signed short, int, float, double`` or a tuple of values of one of these types, where all the values in the tuple have the same type. If you are familiar with OpenCV
:ref:`CvMat` 's type notation, CV_8U ... CV_32FC3, CV_64FC2 etc., then a primitive type can be defined as a type for which you can give a unique identifier in a form ``CV_<bit-depth>{U|S|F}C<number_of_channels>`` . A universal OpenCV structure able to store a single instance of such primitive data type is
:ref:`Vec` . Multiple instances of such a type can be stored to a ``std::vector``,``Mat``,``Mat_``,``SparseMat``,``SparseMat_`` or any other container that is able to store
:ref:`Vec` instances.
The class ``DataType`` is basically used to provide some description of such primitive data types without adding any fields or methods to the corresponding classes (and it is actually impossible to add anything to primitive C/C++ data types). This technique is known in C++ as class traits. It's not ``DataType`` itself that is used, but its specialized versions, such as: ::
that is, such traits are used to tell OpenCV which data type you are working with, even if such a type is not native to OpenCV (the matrix ``B`` intialization above compiles because OpenCV defines the proper specialized template class ``DataType<complex<_Tp> >`` ). Also, this mechanism is useful (and used in OpenCV this way) for generic algorithms implementations.
The class represents a 2D point, specified by its coordinates
:math:`x` and
:math:`y` .
Instance of the class is interchangeable with C structures ``CvPoint`` and ``CvPoint2D32f`` . There is also cast operator to convert point coordinates to the specified type. The conversion from floating-point coordinates to integer coordinates is done by rounding; in general case the conversion uses
operation on each of the coordinates. Besides the class members listed in the declaration above, the following operations on points are implemented: ::
The class represents a 3D point, specified by its coordinates
:math:`x`,:math:`y` and
:math:`z` .
Instance of the class is interchangeable with C structure ``CvPoint2D32f`` . Similarly to ``Point_`` , the 3D points' coordinates can be converted to another type, and the vector arithmetic and comparison operations are also supported.
The class ``Size_`` is similar to ``Point_`` , except that the two members are called ``width`` and ``height`` instead of ``x`` and ``y`` . The structure can be converted to and from the old OpenCV structures
:ref:`CvSize` and
:ref:`CvSize2D32f` . The same set of arithmetic and comparison operations as for ``Point_`` is available.
The rectangle is described by the coordinates of the top-left corner (which is the default interpretation of ``Rect_::x`` and ``Rect_::y`` in OpenCV; though, in your algorithms you may count ``x`` and ``y`` from the bottom-left corner), the rectangle width and height.
Another assumption OpenCV usually makes is that the top and left boundary of the rectangle are inclusive, while the right and bottom boundaries are not, for example, the method ``Rect_::contains`` returns true if
``Vec`` is a partial case of ``Matx`` . It is possible to convert ``Vec<T,2>`` to/from ``Point_``,``Vec<T,3>`` to/from ``Point3_`` , and ``Vec<T,4>`` to :ref:`CvScalar` or :ref:`Scalar`. The elements of ``Vec`` are accessed using ``operator[]``. All the expected vector operations are implemented too:
The template class ``Scalar_`` and it's double-precision instantiation ``Scalar`` represent 4-element vector. Being derived from ``Vec<_Tp, 4>`` , they can be used as typical 4-element vectors, but in addition they can be converted to/from ``CvScalar`` . The type ``Scalar`` is widely used in OpenCV for passing pixel values and it is a drop-in replacement for
:ref:`CvScalar` that was used for the same purpose in the earlier versions of OpenCV.
:ref:`Mat` ), and for many other purposes. ``Range(a,b)`` is basically the same as ``a:b`` in Matlab or ``a..b`` in Python. As in Python, ``start`` is inclusive left boundary of the range, and ``end`` is exclusive right boundary of the range. Such a half-opened interval is usually denoted as
:math:`[start,end)` .
The static method ``Range::all()`` returns some special variable that means "the whole sequence" or "the whole range", just like " ``:`` " in Matlab or " ``...`` " in Python. All the methods and functions in OpenCV that take ``Range`` support this special ``Range::all()`` value, but of course, in the case of your own custom processing you will probably have to check and handle it explicitly: ::
The class ``Ptr<_Tp>`` is a template class that wraps pointers of the corresponding type. It is similar to ``shared_ptr`` that is a part of Boost library (
default constructor, copy constructor and assignment operator for an arbitrary C++ class or a C structure. For some objects, like files, windows, mutexes, sockets etc, copy constructor or assignment operator are difficult to define. For some other objects, like complex classifiers in OpenCV, copy constructors are absent and not easy to implement. Finally, some of complex OpenCV and your own data structures may have been written in C. However, copy constructors and default constructors can simplify programming a lot; besides, they are often required (e.g. by STL containers). By wrapping a pointer to such a complex object ``TObj`` to ``Ptr<TObj>`` you will automatically get all of the necessary constructors and the assignment operator.
all the above-mentioned operations running very fast, regardless of the data size, i.e. as "O(1)" operations. Indeed, while some structures, like ``std::vector`` provide a copy constructor and an assignment operator, the operations may take considerable time if the data structures are big. But if the structures are put into ``Ptr<>`` , the overhead becomes small and independent of the data size.
heterogeneous collections of objects. The standard STL and most other C++ and OpenCV containers can only store objects of the same type and the same size. The classical solution to store objects of different types in the same container is to store pointers to the base class ``base_class_t*`` instead, but when you loose the automatic memory management. Again, by using ``Ptr<base_class_t>()`` instead of the raw pointers, you can solve the problem.
The class ``Ptr`` treats the wrapped object as a black box, the reference counter is allocated and managed separately. The only thing the pointer class needs to know about the object is how to deallocate it. This knowledge is incapsulated in ``Ptr::delete_obj()`` method, which is called when the reference counter becomes 0. If the object is a C++ class instance, no additional coding is needed, because the default implementation of this method calls ``delete obj;`` .
However, if the object is deallocated in a different way, then the specialized method should be created. For example, if you want to wrap ``FILE`` , the ``delete_obj`` may be implemented as following: ::
: The reference increment/decrement operations are implemented as atomic operations, and therefore it is normally safe to use the classes in multi-threaded applications. The same is true for
:ref:`Mat` and other C++ OpenCV classes that operate on the reference counters.
The class ``Mat`` represents an n-dimensional dense numerical single-channel or multi-channel array. It can be used to store real or complex-valued vectors and matrices, grayscale or color images, voxel volumes, vector fields, point clouds, tensors, histograms (though, very high-dimensional histograms may be better stored in a ``SparseMat`` ). The data layout of array
:math:`M` is defined by the array ``M.step[]`` , so that the address of element
Note that ``M.step[i] >= M.step[i+1]`` (in fact, ``M.step[i] >= M.step[i+1]*M.size[i+1]`` ), that is, 2-dimensional matrices are stored row-by-row, 3-dimensional matrices are stored plane-by-plane etc. ``M.step[M.dims-1]`` is minimal and always equal to the element size ``M.elemSize()`` .
That is, the data layout in ``Mat`` is fully compatible with ``CvMat``,``IplImage`` and ``CvMatND`` types from OpenCV 1.x, as well as with majority of dense array types from the standard toolkits and SDKs, such as Numpy (ndarray), Win32 (independent device bitmaps) etc, i.e. any other array that uses "steps", a.k.a. "strides", to compute position of a pixel. Because of such compatibility, it is possible to make a ``Mat`` header for user-allocated data and process it in-place using OpenCV functions.
note that it is pass number of dimensions =1 to the ``Mat`` constructor, but the created array will be 2-dimensional, with the number of columns set to 1. That's why ``Mat::dims`` is always >= 2 (can also be 0 when the array is empty)
Thanks to the additional ``datastart`` and ``dataend`` members, it is possible to compute the relative sub-array position in the main *"container"* array using ``locateROI()``:
partial yet very common cases of this "user-allocated data" case are conversions from :ref:`CvMat` and :ref:`IplImage` to ``Mat``. For this purpose there are special constructors taking pointers to ``CvMat`` or ``IplImage`` and the optional flag indicating whether to copy the data or not.
Backward conversion from ``Mat`` to ``CvMat`` or ``IplImage`` is provided via cast operators ``Mat::operator CvMat() const`` an ``Mat::operator IplImage()``. The operators do *not* copy the data.
here we first call constructor of ``Mat_`` class (that we describe further) with the proper parameters, and then we just put ``<<`` operator followed by comma-separated values that can be constants, variables, expressions etc. Also, note the extra parentheses that are needed to avoid compiler errors.
Once array is created, it will be automatically managed by using reference-counting mechanism (unless the array header is built on top of user-allocated data, in which case you should handle the data by yourself).
The array data will be deallocated when no one points to it; if you want to release the data pointed by a array header before the array destructor is called, use ``Mat::release()`` .
The next important thing to learn about the array class is element access. Earlier it was shown how to compute address of each array element. Normally, it's not needed to use the formula directly in your code. If you know the array element type (which can be retrieved using the method ``Mat::type()`` ), you can access element
If you need to process a whole row of a 2d array, the most efficient way is to get the pointer to the row first, and then just use plain C operator ``[]`` : ::
Some operations, like the above one, do not actually depend on the array shape, they just process elements of an array one by one (or elements from multiple arrays that have the same coordinates, e.g. array addition). Such operations are called element-wise and it makes sense to check whether all the input/output arrays are continuous, i.e. have no gaps in the end of each row, and if yes, process them as a single long row: ::
in the case of continuous matrix the outer loop body will be executed just once, so the overhead will be smaller, which will be especially noticeable in the case of small matrices.
:math:`A\gtreqqless B,\;A \ne B,\;A \gtreqqless \alpha,\;A \ne \alpha`. The result of comparison is 8-bit single channel mask, which elements are set to 255 (if the particular element or pair of elements satisfy the condition) and 0 otherwise.
Note, however, that comma-separated initializers and probably some other operations may require additional explicit ``Mat()`` or ``Mat_<T>()`` constuctor calls to resolve possible ambiguity.
:param size:The 2D array size: ``Size(cols, rows)`` . Note that in the ``Size()`` constructor the number of rows and the number of columns go in the reverse order.
:param type:The array type, use ``CV_8UC1, ..., CV_64FC4`` to create 1-4 channel matrices, or ``CV_8UC(n), ..., CV_64FC(n)`` to create multi-channel (up to ``CV_MAX_CN`` channels) matrices
:param s:The optional value to initialize each matrix element with. To set all the matrix elements to the particular value after the construction, use the assignment operator ``Mat::operator=(const Scalar& value)`` .
:param data:Pointer to the user data. Matrix constructors that take ``data`` and ``step`` parameters do not allocate matrix data. Instead, they just initialize the matrix header that points to the specified data, i.e. no data is copied. This operation is very efficient and can be used to process external data using OpenCV functions. The external data is not automatically deallocated, user should take care of it.
:param step:The ``data`` buddy. This optional parameter specifies the number of bytes that each matrix row occupies. The value should include the padding bytes in the end of each row, if any. If the parameter is missing (set to ``AUTO_STEP`` ), no padding is assumed and the actual step is calculated as ``cols*elemSize()`` , see :ref:`Mat::elemSize` ().
:param steps:The array of ``ndims-1`` steps in the case of multi-dimensional array (the last step is always set to the element size). If not specified, the matrix is assumed to be continuous.
:param m:The array that (in whole, a partly) is assigned to the constructed matrix. No data is copied by these constructors. Instead, the header pointing to ``m`` data, or its sub-array, is constructed and the associated with it reference counter, if any, is incremented. That is, when you modify the matrix formed using such a constructor, you will also modify the corresponding elements of ``m`` . If you want to have an independent copy of the sub-array, use ``Mat::clone()`` .
:param img:Pointer to the old-style ``IplImage`` image structure. By default, the data is shared between the original image and the new matrix, but when ``copyData`` is set, the full copy of the image data is created.
:param vec:STL vector, which elements will form the matrix. The matrix will have a single column and the number of rows equal to the number of vector elements. Type of the matrix will match the type of vector elements. The constructor can handle arbitrary types, for which there is properly declared :ref:`DataType` , i.e. the vector elements must be primitive numbers or uni-type numerical tuples of numbers. Mixed-type structures are not supported, of course. Note that the corresponding constructor is explicit, meaning that STL vectors are not automatically converted to ``Mat`` instances, you should write ``Mat(vec)`` explicitly. Another obvious note: unless you copied the data into the matrix ( ``copyData=true`` ), no new elements should be added to the vector, because it can potentially yield vector data reallocation, and thus the matrix data pointer will become invalid.
:param copyData:Specifies, whether the underlying data of the STL vector, or the old-style ``CvMat`` or ``IplImage`` should be copied to (true) or shared with (false) the newly constructed matrix. When the data is copied, the allocated buffer will be managed using ``Mat`` 's reference counting mechanism. While when the data is shared, the reference counter will be NULL, and you should not deallocate the data until the matrix is not destructed.
:param rowRange:The range of the ``m`` 's rows to take. As usual, the range start is inclusive and the range end is exclusive. Use ``Range::all()`` to take all the rows.
These are various constructors that form a matrix. As noticed in the
, often the default constructor is enough, and the proper matrix will be allocated by an OpenCV function. The constructed matrix can further be assigned to another matrix or matrix expression, in which case the old content is dereferenced, or be allocated with
:param m:The assigned, right-hand-side matrix. Matrix assignment is O(1) operation, that is, no data is copied. Instead, the data is shared and the reference counter, if any, is incremented. Before assigning new data, the old data is dereferenced via :ref:`Mat::release` .
:param expr:The assigned matrix expression object. As opposite to the first form of assignment operation, the second form can reuse already allocated matrix if it has the right size and type to fit the matrix expression result. It is automatically handled by the real function that the matrix expressions is expanded to. For example, ``C=A+B`` is expanded to ``add(A, B, C)`` , and :func:`add` will take care of automatic ``C`` reallocation.
The method makes a new header for the specified matrix row and returns it. This is O(1) operation, regardless of the matrix size. The underlying data of the new matrix will be shared with the original matrix. Here is the example of one of the classical basic matrix processing operations, axpy, used by LU and many other algorithms: ::
This is because ``A.row(i)`` forms a temporary header, which is further assigned another header. Remember, each of these operations is O(1), i.e. no data is copied. Thus, the above assignment will have absolutely no effect, while you may have expected j-th row being copied to i-th row. To achieve that, you should either turn this simple assignment into an expression, or use
The method makes a new header for the specified matrix column and returns it. This is O(1) operation, regardless of the matrix size. The underlying data of the new matrix will be shared with the original matrix. See also
The method creates full copy of the array. The original ``step[]`` are not taken into the account. That is, the array copy will be a continuous array occupying ``total()*elemSize()`` bytes.
so that the destination matrix is reallocated if needed. While ``m.copyTo(m);`` will work as expected, i.e. will have no effect, the function does not handle the case of a partial overlap between the source and the destination matrices.
When the operation mask is specified, and the ``Mat::create`` call shown above reallocated the matrix, the newly allocated matrix is initialized with all 0's before copying the data.
:param rtype:The desired destination matrix type, or rather, the depth (since the number of channels will be the same with the source one). If ``rtype`` is negative, the destination matrix will have the same type as the source.
The method makes a new matrix header for ``*this`` elements. The new matrix may have different size and/or different number of channels. Any combination is possible, as long as:
No data is copied, i.e. this is O(1) operation. Consequently, if you change the number of rows, or the operation changes elements' row indices in some other way, the matrix must be continuous. See
Here is some small example. Assuming, there is a set of 3D points that are stored as STL vector, and you want to represent the points as ``3xN`` matrix. Here is how it can be done: ::
It does not perform the actual transposition, but returns a temporary "matrix transposition" object that can be further used as a part of more complex matrix expression or be assigned to a matrix: ::
***DECOMP_CHOLESKY** Cholesky :math:`LL^T` decomposition, for symmetrical positively defined matrices only. About twice faster than LU on big matrices.
The method performs matrix inversion by means of matrix expressions, i.e. a temporary "matrix inversion" object is returned by the method, and can further be used as a part of more complex matrix expression or be assigned to a matrix.
The method returns a temporary object encoding per-element array multiplication, with optional scale. Note that this is not a matrix multiplication, which corresponds to a simpler "*" operator.
The method computes cross-product of the two 3-element vectors. The vectors must be 3-elements floating-point vectors of the same shape and the same size. The result will be another 3-element vector of the same shape and the same type as operands.
The method computes dot-product of the two matrices. If the matrices are not single-column or single-row vectors, the top-to-bottom left-to-right scan ordering is used to treat them as 1D vectors. The vectors must have the same size and the same type. If the matrices have more than one channel, the dot products from all the channels are summed together.
The method returns Matlab-style zero array initializer. It can be used to quickly form a constant array and use it as a function parameter, as a part of matrix expression, or as a matrix initializer. ::
Note that in the above sample a new matrix will be allocated only if ``A`` is not 3x3 floating-point matrix, otherwise the existing matrix ``A`` will be filled with 0's.
The above operation will not form 100x100 matrix of ones and then multiply it by 3. Instead, it will just remember the scale factor (3 in this case) and use it when actually invoking the matrix initializer.
This is one of the key ``Mat`` methods. Most new-style OpenCV functions and methods that produce arrays call this method for each output array. The method uses the following algorithm:
Such a scheme makes the memory management robust and efficient at the same time, and also saves quite a bit of typing for the user, i.e. usually there is no need to explicitly allocate output arrays. That is, instead of writing: ::
The method increments the reference counter, associated with the matrix data. If the matrix header points to an external data (see
:func:`Mat::Mat` ), the reference counter is NULL, and the method has no effect in this case. Normally, the method should not be called explicitly, to avoid memory leaks. It is called implicitly by the matrix assignment operator. The reference counter increment is the atomic operation on the platforms that support it, thus it is safe to operate on the same matrices asynchronously in different threads.
The method decrements the reference counter, associated with the matrix data. When the reference counter reaches 0, the matrix data is deallocated and the data and the reference counter pointers are set to NULL's. If the matrix header points to an external data (see
:func:`Mat::Mat` ), the reference counter is NULL, and the method has no effect in this case.
This method can be called manually to force the matrix data deallocation. But since this method is automatically called in the destructor, or by any other method that changes the data pointer, it is usually not needed. The reference counter decrement and check for 0 is the atomic operation on the platforms that support it, thus it is safe to operate on the same matrices asynchronously in different threads.
The method changes the number of matrix rows. If the matrix is reallocated, the first ``min(Mat::rows, sz)`` rows are preserved. The method emulates the corresponding method of STL vector class.
The methods add one or more elements to the bottom of the matrix. They emulate the corresponding method of STL vector class. When ``elem`` is ``Mat`` , its type and the number of columns must be the same as in the container matrix.
After you extracted a submatrix from a matrix using
:func:`Mat::row`,:func:`Mat::col`,:func:`Mat::rowRange`,:func:`Mat::colRange` etc., the result submatrix will point just to the part of the original big matrix. However, each submatrix contains some information (represented by ``datastart`` and ``dataend`` fields), using which it is possible to reconstruct the original matrix size and the position of the extracted submatrix within the original matrix. The method ``locateROI`` does exactly that.
:func:`Mat::locateROI` . Indeed, the typical use of these functions is to determine the submatrix position within the parent matrix and then shift the position somehow. Typically it can be needed for filtering operations, when pixels outside of the ROI should be taken into account. When all the method's parameters are positive, it means that the ROI needs to grow in all directions by the specified amount, i.e. ::
increases the matrix size by 4 elements in each direction and shifts it by 2 elements to the left and 2 elements up, which brings in all the necessary pixels for the filtering with 5x5 kernel.
It's user responsibility to make sure that adjustROI does not cross the parent matrix boundary. If it does, the function will signal an error.
:param rowRange:The start and the end row of the extracted submatrix. The upper boundary is not included. To select all the rows, use ``Range::all()`` :param colRange: The start and the end column of the extracted submatrix. The upper boundary is not included. To select all the columns, use ``Range::all()`` :param roi: The extracted submatrix specified as a rectangle
The operators make a new header for the specified sub-array of ``*this`` . They are the most generalized forms of
:func:`Mat::row`,:func:`Mat::col`,:func:`Mat::rowRange` and
:func:`Mat::colRange` . For example, ``A(Range(0, 10), Range::all())`` is equivalent to ``A.rowRange(0, 10)`` . Similarly to all of the above, the operators are O(1) operations, i.e. no matrix data is copied.
The operator makes CvMat header for the matrix without copying the underlying data. The reference counter is not taken into account by this operation, thus you should make sure than the original matrix is not deallocated while the ``CvMat`` header is used. The operator is useful for intermixing the new and the old OpenCV API's, e.g: ::
The operator makes IplImage header for the matrix without copying the underlying data. You should make sure than the original matrix is not deallocated while the ``IplImage`` header is used. Similarly to ``Mat::operator CvMat`` , the operator is useful for intermixing the new and the old OpenCV API's.
The method returns true if the matrix elements are stored continuously, i.e. without gaps in the end of each row, and false otherwise. Obviously, ``1x1`` or ``1xN`` matrices are always continuous. Matrices created with
:func:`Mat::create` are always continuous, but if you extract a part of the matrix using
:func:`Mat::col`,:func:`Mat::diag` etc. or constructed a matrix header for externally allocated data, such matrices may no longer have this property.
The continuity flag is stored as a bit in ``Mat::flags`` field, and is computed automatically when you construct a matrix header, thus the continuity check is very fast operation, though it could be, in theory, done as following: ::
The method is used in a quite a few of OpenCV functions, and you are welcome to use it as well. The point is that element-wise operations (such as arithmetic and logical operations, math functions, alpha blending, color space transformations etc.) do not depend on the image geometry, and thus, if all the input and all the output arrays are continuous, the functions can process them as very long single-row vectors. Here is the example of how alpha-blending function can be implemented. ::
This trick, while being very simple, can boost performance of a simple element-operation by 10-20 percents, especially if the image is rather small and the operation is quite simple.
Also, note that we use another OpenCV idiom in this function - we call
:func:`Mat::create` for the destination array instead of checking that it already has the proper size and type. And while the newly allocated arrays are always continuous, we still check the destination array, because
:func:`create` does not always allocate a new matrix.
The method returns the matrix element size in bytes. For example, if the matrix type is ``CV_16SC3`` , the method will return ``3*sizeof(short)`` or 6.
The method returns the matrix element channel size in bytes, that is, it ignores the number of channels. For example, if the matrix type is ``CV_16SC3`` , the method will return ``sizeof(short)`` or 2.
The method returns the matrix element depth id, i.e. the type of each individual channel. For example, for 16-bit signed 3-channel array the method will return ``CV_16S`` . The complete list of matrix types:
The method returns true if ``Mat::total()`` is 0 or if ``Mat::data`` is NULL. Because of ``pop_back()`` and ``resize()`` methods ``M.total() == 0`` does not imply that ``M.data == NULL`` .
The template methods return reference to the specified array element. For the sake of higher performance the index range checks are only performed in Debug configuration.
Note that the variants with a single index (i) can be used to access elements of single-row or single-column 2-dimensional arrays. That is, if, for example, ``A`` is ``1 x N`` floating-point matrix and ``B`` is ``M x 1`` integer matrix, you can simply write ``A.at<float>(k+4)`` and ``B.at<int>(2*i+1)`` instead of ``A.at<float>(0,k+4)`` and ``B.at<int>(2*i+1,0)`` , respectively.
The methods return the matrix read-only or read-write iterators. The use of matrix iterators is very similar to the use of bi-directional STL iterators. Here is the alpha blending function rewritten using the matrix iterators: ::
The class ``Mat_<_Tp>`` is a "thin" template wrapper on top of ``Mat`` class. It does not have any extra data fields, nor it or ``Mat`` have any virtual methods and thus references or pointers to these two classes can be freely converted one to another. But do it with care, e.g.: ::
While ``Mat`` is sufficient in most cases, ``Mat_`` can be more convenient if you use a lot of element access operations and if you know matrix type at compile time. Note that ``Mat::at<_Tp>(int y, int x)`` and ``Mat_<_Tp>::operator ()(int y, int x)`` do absolutely the same and run at the same speed, but the latter is certainly shorter: ::
The class is used for implementation of unary, binary and, generally, n-ary element-wise operations on multi-dimensional arrays. Some of the arguments of n-ary function may be continuous arrays, some may be not. It is possible to use conventional
:ref:`MatIterator` 's for each array, but it can be a big overhead to increment all of the iterators after each small operations. That's where ``NAryMatIterator`` can be used. Using it, you can iterate though several matrices simultaneously as long as they have the same geometry (dimensionality and all the dimension sizes are the same). On each iteration ``it.planes[0]``,``it.planes[1]`` , ... will be the slices of the corresponding matrices.
The class ``SparseMat`` represents multi-dimensional sparse numerical arrays. Such a sparse array can store elements of any type that
:ref:`Mat` can store. "Sparse" means that only non-zero elements are stored (though, as a result of operations on a sparse matrix, some of its stored elements can actually become 0. It's up to the user to detect such elements and delete them using ``SparseMat::erase`` ). The non-zero elements are stored in a hash table that grows when it's filled enough, so that the search time is O(1) in average (regardless of whether element is there or not). Elements can be accessed using the following methods:
If you run this loop, you will notice that elements are enumerated in no any logical order (lexicographical etc.), they come in the same order as they stored in the hash table, i.e. semi-randomly. You may collect pointers to the nodes and sort them to get the proper ordering. Note, however, that pointers to the nodes may become invalid when you add more elements to the matrix; this is because of possible buffer reallocation.
#.
a combination of the above 2 methods when you need to process 2 or more sparse matrices simultaneously, e.g. this is how you can compute unnormalized cross-correlation of the 2 floating-point sparse matrices: