1 \section{Basic Structures}
3 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
7 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
10 \label{CvPoint}\cvclass{CvPoint}
11 2D point with integer coordinates (usually zero-based).
15 typedef struct CvPoint
24 \cvarg{x}{x-coordinate}
25 \cvarg{y}{y-coordinate}
30 inline CvPoint cvPoint( int x, int y );
32 /* Conversion from CvPoint2D32f */
33 inline CvPoint cvPointFrom32f( CvPoint2D32f point );
36 2D point, represented as a tuple \texttt{(x, y)}, where x and y are integers.
39 \label{CvPoint2D32f}\cvclass{CvPoint2D32f}
40 2D point with floating-point coordinates
44 typedef struct CvPoint2D32f
53 \cvarg{x}{x-coordinate}
54 \cvarg{y}{y-coordinate}
59 inline CvPoint2D32f cvPoint2D32f( double x, double y );
61 /* Conversion from CvPoint */
62 inline CvPoint2D32f cvPointTo32f( CvPoint point );
65 2D point, represented as a tuple \texttt{(x, y)}, where x and y are floats.
69 \label{CvPoint3D32f}\cvclass{CvPoint3D32f}
70 3D point with floating-point coordinates
74 typedef struct CvPoint3D32f
84 \cvarg{x}{x-coordinate}
85 \cvarg{y}{y-coordinate}
86 \cvarg{z}{z-coordinate}
91 inline CvPoint3D32f cvPoint3D32f( double x, double y, double z );
94 3D point, represented as a tuple \texttt{(x, y, z)}, where x, y and z are floats.
97 \label{CvPoint2D64f}\cvclass{CvPoint2D64f}
98 2D point with double precision floating-point coordinates
102 typedef struct CvPoint2D64f
111 \cvarg{x}{x-coordinate}
112 \cvarg{y}{y-coordinate}
117 inline CvPoint2D64f cvPoint2D64f( double x, double y );
119 /* Conversion from CvPoint */
120 inline CvPoint2D64f cvPointTo64f( CvPoint point );
123 2D point, represented as a tuple \texttt{(x, y)}, where x and y are floats.
126 \label{CvPoint3D64f}\cvclass{CvPoint3D64f}
127 3D point with double precision floating-point coordinates
131 typedef struct CvPoint3D64f
141 \cvarg{x}{x-coordinate}
142 \cvarg{y}{y-coordinate}
143 \cvarg{z}{z-coordinate}
148 inline CvPoint3D64f cvPoint3D64f( double x, double y, double z );
151 3D point, represented as a tuple \texttt{(x, y, z)}, where x, y and z are floats.
154 \label{CvSize}\cvclass{CvSize}
155 Pixel-accurate size of a rectangle.
159 typedef struct CvSize
168 \cvarg{width}{Width of the rectangle}
169 \cvarg{height}{Height of the rectangle}
174 inline CvSize cvSize( int width, int height );
177 Size of a rectangle, represented as a tuple \texttt{(width, height)}, where width and height are integers.
180 \label{CvSize2D32f}\cvclass{CvSize2D32f}
181 Sub-pixel accurate size of a rectangle.
185 typedef struct CvSize2D32f
194 \cvarg{width}{Width of the rectangle}
195 \cvarg{height}{Height of the rectangle}
200 inline CvSize2D32f cvSize2D32f( double width, double height );
203 Size of a rectangle, represented as a tuple \texttt{(width, height)}, where width and height are floats.
206 \label{CvRect}\cvclass{CvRect}
207 Offset (usually the top-left corner) and size of a rectangle.
211 typedef struct CvRect
222 \cvarg{x}{x-coordinate of the top-left corner}
223 \cvarg{y}{y-coordinate of the top-left corner (bottom-left for Windows bitmaps)}
224 \cvarg{width}{Width of the rectangle}
225 \cvarg{height}{Height of the rectangle}
230 inline CvRect cvRect( int x, int y, int width, int height );
233 Rectangle, represented as a tuple \texttt{(x, y, width, height)}, where all are integers.
236 \label{CvScalar}\cvclass{CvScalar}
237 A container for 1-,2-,3- or 4-tuples of doubles.
241 typedef struct CvScalar
250 initializes val[0] with val0, val[1] with val1, etc.
252 inline CvScalar cvScalar( double val0, double val1=0,
253 double val2=0, double val3=0 );
255 initializes all of val[0]...val[3] with val0123
257 inline CvScalar cvScalarAll( double val0123 );
260 initializes val[0] with val0, and all of val[1]...val[3] with zeros
262 inline CvScalar cvRealScalar( double val0 );
266 CvScalar is always represented as a 4-tuple.
270 >>> cv.Scalar(1, 2, 3, 4)
276 >>> cv.RGB(17, 110, 255)
277 (255.0, 110.0, 17.0, 0.0)
281 \label{CvTermCriteria}\cvclass{CvTermCriteria}
282 Termination criteria for iterative algorithms.
286 #define CV_TERMCRIT_ITER 1
287 #define CV_TERMCRIT_NUMBER CV_TERMCRIT_ITER
288 #define CV_TERMCRIT_EPS 2
290 typedef struct CvTermCriteria
300 \cvarg{type}{A combination of CV\_TERMCRIT\_ITER and CV\_TERMCRIT\_EPS}
301 \cvarg{max\_iter}{Maximum number of iterations}
302 \cvarg{epsilon}{Required accuracy}
307 inline CvTermCriteria cvTermCriteria( int type, int max_iter, double epsilon );
309 /* Check and transform a CvTermCriteria so that
310 type=CV_TERMCRIT_ITER+CV_TERMCRIT_EPS
311 and both max_iter and epsilon are valid */
312 CvTermCriteria cvCheckTermCriteria( CvTermCriteria criteria,
314 int default_max_iters );
317 Represented by a tuple \texttt{(type, max\_iter, epsilon)}.
320 \cvarg{type}{\texttt{CV\_TERMCRIT\_ITER}, \texttt{CV\_TERMCRIT\_EPS} or \texttt{CV\_TERMCRIT\_ITER | CV\_TERMCRIT\_EPS}}
321 \cvarg{max\_iter}{Maximum number of iterations}
322 \cvarg{epsilon}{Required accuracy}
326 (cv.CV_TERMCRIT_ITER, 10, 0) # terminate after 10 iterations
327 (cv.CV_TERMCRIT_EPS, 0, 0.01) # terminate when epsilon reaches 0.01
328 (cv.CV_TERMCRIT_ITER | cv.CV_TERMCRIT_EPS, 10, 0.01) # terminate as soon as either condition is met
332 \label{CvMat}\cvclass{CvMat}
335 A multi-channel matrix.
375 \cvarg{type}{A CvMat signature (CV\_MAT\_MAGIC\_VAL) containing the type of elements and flags}
376 \cvarg{step}{Full row length in bytes}
377 \cvarg{refcount}{Underlying data reference counter}
378 \cvarg{data}{Pointers to the actual matrix data}
379 \cvarg{rows}{Number of rows}
380 \cvarg{cols}{Number of columns}
383 Matrices are stored row by row. All of the rows are aligned by 4 bytes.
385 A multi-channel 2D matrix. Created by
388 \cross{CreateMatHeader},
392 \cvarg{type}{A CvMat signature containing the type of elements and flags, int}
393 \cvarg{step}{Full row length in bytes, int}
394 \cvarg{rows}{Number of rows, int}
395 \cvarg{cols}{Number of columns, int}
396 \cvarg{tostring() -> str}{Returns the contents of the CvMat as a single string.}
403 \label{CvMatND}\cvclass{CvMatND}
404 Multi-dimensional dense multi-channel array.
408 typedef struct CvMatND
435 \cvarg{type}{A CvMatND signature (CV\_MATND\_MAGIC\_VAL), combining the type of elements and flags}
436 \cvarg{dims}{The number of array dimensions}
437 \cvarg{refcount}{Underlying data reference counter}
438 \cvarg{data}{Pointers to the actual matrix data}
439 \cvarg{dim}{For each dimension, the pair (number of elements, distance between elements in bytes)}
445 \cvarg{type}{A CvMatND signature combining the type of elements and flags, int}
446 \cvarg{tostring() -> str}{Returns the contents of the CvMatND as a single string.}
451 \label{CvSparseMat}\cvclass{CvSparseMat}
452 Multi-dimensional sparse multi-channel array.
455 typedef struct CvSparseMat
466 int size[CV_MAX_DIM];
472 \cvarg{type}{A CvSparseMat signature (CV\_SPARSE\_MAT\_MAGIC\_VAL), combining the type of elements and flags.}
473 \cvarg{dims}{Number of dimensions}
474 \cvarg{refcount}{Underlying reference counter. Not used.}
475 \cvarg{heap}{A pool of hash table nodes}
476 \cvarg{hashtable}{The hash table. Each entry is a list of nodes.}
477 \cvarg{hashsize}{Size of the hash table}
478 \cvarg{total}{Total number of sparse array nodes}
479 \cvarg{valoffset}{The value offset of the array nodes, in bytes}
480 \cvarg{idxoffset}{The index offset of the array nodes, in bytes}
481 \cvarg{size}{Array of dimension sizes}
486 \label{IplImage}\cvclass{IplImage}
491 typedef struct _IplImage
506 struct _IplImage *maskROI;
508 struct _IplTileInfo *tileInfo;
514 char *imageDataOrigin;
520 \cvarg{nSize}{\texttt{sizeof(IplImage)}}
521 \cvarg{ID}{Version, always equals 0}
522 \cvarg{nChannels}{Number of channels. Most OpenCV functions support 1-4 channels.}
523 \cvarg{alphaChannel}{Ignored by OpenCV}
524 \cvarg{depth}{Channel depth in bits + the optional sign bit (\texttt{IPL\_DEPTH\_SIGN}). The supported depths are:
526 \cvarg{IPL\_DEPTH\_8U}{Unsigned 8-bit integer}
527 \cvarg{IPL\_DEPTH\_8S}{Signed 8-bit integer}
528 \cvarg{IPL\_DEPTH\_16U}{Unsigned 16-bit integer}
529 \cvarg{IPL\_DEPTH\_16S}{Signed 16-bit integer}
530 \cvarg{IPL\_DEPTH\_32S}{Signed 32-bit integer}
531 \cvarg{IPL\_DEPTH\_32F}{Single-precision floating point}
532 \cvarg{IPL\_DEPTH\_64F}{Double-precision floating point}
534 \cvarg{colorModel}{Ignored by OpenCV. The OpenCV function \cross{CvtColor} requires the source and destination color spaces as parameters.}
535 \cvarg{channelSeq}{Ignored by OpenCV}
536 \cvarg{dataOrder}{0 = \texttt{IPL\_DATA\_ORDER\_PIXEL} - interleaved color channels, 1 - separate color channels. \cross{CreateImage} only creates images with interleaved channels. For example, the usual layout of a color image is: $ b_{00} g_{00} r_{00} b_{10} g_{10} r_{10} ...$}
537 \cvarg{origin}{0 - top-left origin, 1 - bottom-left origin (Windows bitmap style)}
538 \cvarg{align}{Alignment of image rows (4 or 8). OpenCV ignores this and uses widthStep instead.}
539 \cvarg{width}{Image width in pixels}
540 \cvarg{height}{Image height in pixels}
541 \cvarg{roi}{Region Of Interest (ROI). If not NULL, only this image region will be processed.}
542 \cvarg{maskROI}{Must be NULL in OpenCV}
543 \cvarg{imageId}{Must be NULL in OpenCV}
544 \cvarg{tileInfo}{Must be NULL in OpenCV}
545 \cvarg{imageSize}{Image data size in bytes. For interleaved data, this equals $\texttt{image->height} \cdot \texttt{image->widthStep}$ }
546 \cvarg{imageData}{A pointer to the aligned image data}
547 \cvarg{widthStep}{The size of an aligned image row, in bytes}
548 \cvarg{BorderMode}{Border completion mode, ignored by OpenCV}
549 \cvarg{BorderConst}{Border completion mode, ignored by OpenCV}
550 \cvarg{imageDataOrigin}{A pointer to the origin of the image data (not necessarily aligned). This is used for image deallocation.}
553 The \cross{IplImage} structure was inherited from the Intel Image Processing Library, in which the format is native. OpenCV only supports a subset of possible \cross{IplImage} formats, as outlined in the parameter list above.
555 In addition to the above restrictions, OpenCV handles ROIs differently. OpenCV functions require that the image size or ROI size of all source and destination images match exactly. On the other hand, the Intel Image Processing Library processes the area of intersection between the source and destination images (or ROIs), allowing them to vary independently.
560 The \cross{IplImage} object was inherited from the Intel Image Processing
561 Library, in which the format is native. OpenCV only supports a subset
562 of possible \cross{IplImage} formats.
565 \cvarg{nChannels}{Number of channels, int.}
566 \cvarg{width}{Image width in pixels}
567 \cvarg{height}{Image height in pixels}
568 \cvarg{depth}{Pixel depth in bits. The supported depths are:
570 \cvarg{IPL\_DEPTH\_8U}{Unsigned 8-bit integer}
571 \cvarg{IPL\_DEPTH\_8S}{Signed 8-bit integer}
572 \cvarg{IPL\_DEPTH\_16U}{Unsigned 16-bit integer}
573 \cvarg{IPL\_DEPTH\_16S}{Signed 16-bit integer}
574 \cvarg{IPL\_DEPTH\_32S}{Signed 32-bit integer}
575 \cvarg{IPL\_DEPTH\_32F}{Single-precision floating point}
576 \cvarg{IPL\_DEPTH\_64F}{Double-precision floating point}
578 \cvarg{origin}{0 - top-left origin, 1 - bottom-left origin (Windows bitmap style)}
579 \cvarg{tostring() -> str}{Returns the contents of the CvMatND as a single string.}
583 \label{CvArr}\cvclass{CvArr}
591 The metatype \texttt{CvArr} is used \textit{only} as a function parameter to specify that the function accepts arrays of multiple types, such as IplImage*, CvMat* or even CvSeq* sometimes. The particular array type is determined at runtime by analyzing the first 4 bytes of the header.
595 \texttt{CvArr} is used \textit{only} as a function parameter to specify that the parameter can be:
597 \item{an \cross{IplImage}}
598 \item{a \cross{CvMat}}
599 \item{any other type that exports the \href{http://docs.scipy.org/doc/numpy/reference/arrays.interface.html}{array interface}}
605 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
609 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
612 \subsection{DataType}\label{DataType}
613 Template "traits" class for other OpenCV primitive data types
616 template<typename _Tp> class DataType
618 // value_type is always a synonym for _Tp.
619 typedef _Tp value_type;
621 // intermediate type used for operations on _Tp.
622 // it is int for uchar, signed char, unsigned short, signed short and int,
623 // float for float, double for double, ...
624 typedef <...> work_type;
625 // in the case of multi-channel data it is the data type of each channel
626 typedef <...> channel_type;
630 depth = DataDepth<channel_type>::value,
633 // '1u', '4i', '3f', '2d' etc.
635 // CV_8UC3, CV_32FC2 ...
636 type = CV_MAKETYPE(depth, channels)
641 The template class \texttt{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 \texttt{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 \cross{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 \texttt{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 \cross{Vec}. Multiple instances of such a type can be stored to a \texttt{std::vector}, \texttt{Mat}, \texttt{Mat\_}, \texttt{MatND}, \texttt{MatND\_}, \texttt{SparseMat}, \texttt{SparseMat\_} or any other container that is able to store \cross{Vec} instances.
643 The class \texttt{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 \texttt{DataType} itself that is used, but its specialized versions, such as:
646 template<> class DataType<uchar>
648 typedef uchar value_type;
649 typedef int work_type;
650 typedef uchar channel_type;
651 enum { channel_type = CV_8U, channels = 1, fmt='u', type = CV_8U };
654 template<typename _Tp> DataType<std::complex<_Tp> >
656 typedef std::complex<_Tp> value_type;
657 typedef std::complex<_Tp> work_type;
658 typedef _Tp channel_type;
659 // DataDepth is another helper trait class
660 enum { depth = DataDepth<_Tp>::value, channels=2,
661 fmt=(channels-1)*256+DataDepth<_Tp>::fmt,
662 type=CV_MAKETYPE(depth, channels) };
667 The main purpose of the classes is to convert compile-time type information to OpenCV-compatible data type identifier, for example:
670 // allocates 30x40 floating-point matrix
671 Mat A(30, 40, DataType<float>::type);
673 Mat B = Mat_<std::complex<double> >(3, 3);
674 // the statement below will print 6, 2 /* i.e. depth == CV_64F, channels == 2 */
675 cout << B.depth() << ", " << B.channels() << endl;
678 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 \texttt{B} intialization above compiles because OpenCV defines the proper specialized template class \texttt{DataType<complex<\_Tp> >}). Also, this mechanism is useful (and used in OpenCV this way) for generic algorithms implementations.
681 Template class for 2D points
684 template<typename _Tp> class Point_
687 typedef _Tp value_type;
690 Point_(_Tp _x, _Tp _y);
691 Point_(const Point_& pt);
692 Point_(const CvPoint& pt);
693 Point_(const CvPoint2D32f& pt);
694 Point_(const Size_<_Tp>& sz);
695 Point_(const Vec<_Tp, 2>& v);
696 Point_& operator = (const Point_& pt);
697 template<typename _Tp2> operator Point_<_Tp2>() const;
698 operator CvPoint() const;
699 operator CvPoint2D32f() const;
700 operator Vec<_Tp, 2>() const;
702 // computes dot-product (this->x*pt.x + this->y*pt.y)
703 _Tp dot(const Point_& pt) const;
704 // computes dot-product using double-precision arithmetics
705 double ddot(const Point_& pt) const;
706 // returns true if the point is inside the rectangle "r".
707 bool inside(const Rect_<_Tp>& r) const;
713 The class represents a 2D point, specified by its coordinates $x$ and $y$.
714 Instance of the class is interchangeable with C structures \texttt{CvPoint} and \texttt{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 \hyperref[saturatecast]{saturate\_cast} operation on each of the coordinates. Besides the class members listed in the declaration above, the following operations on points are implemented:
724 double value = norm(pt); // L2 norm
729 For user convenience, the following type aliases are defined:
731 typedef Point_<int> Point2i;
732 typedef Point2i Point;
733 typedef Point_<float> Point2f;
734 typedef Point_<double> Point2d;
737 Here is a short example:
739 Point2f a(0.3f, 0.f), b(0.f, 0.4f);
740 Point pt = (a + b)*10.f;
741 cout << pt.x << ", " << pt.y << endl;
744 \subsection{Point3\_}
746 Template class for 3D points
750 template<typename _Tp> class Point3_
753 typedef _Tp value_type;
756 Point3_(_Tp _x, _Tp _y, _Tp _z);
757 Point3_(const Point3_& pt);
758 explicit Point3_(const Point_<_Tp>& pt);
759 Point3_(const CvPoint3D32f& pt);
760 Point3_(const Vec<_Tp, 3>& v);
761 Point3_& operator = (const Point3_& pt);
762 template<typename _Tp2> operator Point3_<_Tp2>() const;
763 operator CvPoint3D32f() const;
764 operator Vec<_Tp, 3>() const;
766 _Tp dot(const Point3_& pt) const;
767 double ddot(const Point3_& pt) const;
773 The class represents a 3D point, specified by its coordinates $x$, $y$ and $z$.
774 Instance of the class is interchangeable with C structure \texttt{CvPoint2D32f}. Similarly to \texttt{Point\_}, the 3D points' coordinates can be converted to another type, and the vector arithmetic and comparison operations are also supported.
776 The following type aliases are available:
779 typedef Point3_<int> Point3i;
780 typedef Point3_<float> Point3f;
781 typedef Point3_<double> Point3d;
786 Template class for specfying image or rectangle size.
789 template<typename _Tp> class Size_
792 typedef _Tp value_type;
795 Size_(_Tp _width, _Tp _height);
796 Size_(const Size_& sz);
797 Size_(const CvSize& sz);
798 Size_(const CvSize2D32f& sz);
799 Size_(const Point_<_Tp>& pt);
800 Size_& operator = (const Size_& sz);
803 operator Size_<int>() const;
804 operator Size_<float>() const;
805 operator Size_<double>() const;
806 operator CvSize() const;
807 operator CvSize2D32f() const;
813 The class \texttt{Size\_} is similar to \texttt{Point\_}, except that the two members are called \texttt{width} and \texttt{height} instead of \texttt{x} and \texttt{y}. The structure can be converted to and from the old OpenCV structures \cross{CvSize} and \cross{CvSize2D32f}. The same set of arithmetic and comparison operations as for \texttt{Point\_} is available.
815 OpenCV defines the following type aliases:
818 typedef Size_<int> Size2i;
820 typedef Size_<float> Size2f;
825 Template class for 2D rectangles
828 template<typename _Tp> class Rect_
831 typedef _Tp value_type;
834 Rect_(_Tp _x, _Tp _y, _Tp _width, _Tp _height);
835 Rect_(const Rect_& r);
836 Rect_(const CvRect& r);
837 // (x, y) <- org, (width, height) <- sz
838 Rect_(const Point_<_Tp>& org, const Size_<_Tp>& sz);
839 // (x, y) <- min(pt1, pt2), (width, height) <- max(pt1, pt2) - (x, y)
840 Rect_(const Point_<_Tp>& pt1, const Point_<_Tp>& pt2);
841 Rect_& operator = ( const Rect_& r );
842 // returns Point_<_Tp>(x, y)
843 Point_<_Tp> tl() const;
844 // returns Point_<_Tp>(x+width, y+height)
845 Point_<_Tp> br() const;
847 // returns Size_<_Tp>(width, height)
848 Size_<_Tp> size() const;
849 // returns width*height
852 operator Rect_<int>() const;
853 operator Rect_<float>() const;
854 operator Rect_<double>() const;
855 operator CvRect() const;
857 // x <= pt.x && pt.x < x + width &&
858 // y <= pt.y && pt.y < y + height ? true : false
859 bool contains(const Point_<_Tp>& pt) const;
861 _Tp x, y, width, height;
865 The rectangle is described by the coordinates of the top-left corner (which is the default interpretation of \texttt{Rect\_::x} and \texttt{Rect\_::y} in OpenCV; though, in your algorithms you may count \texttt{x} and \texttt{y} from the bottom-left corner), the rectangle width and height.
867 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 \texttt{Rect\_::contains} returns true if
869 x \leq pt.x < x+width,
870 y \leq pt.y < y+height
872 And virtually every loop over an image \cross{ROI} in OpenCV (where ROI is specified by \texttt{Rect\_<int>}) is implemented as:
874 for(int y = roi.y; y < roi.y + rect.height; y++)
875 for(int x = roi.x; x < roi.x + rect.width; x++)
881 In addition to the class members, the following operations on rectangles are implemented:
883 \item $\texttt{rect} = \texttt{rect} \pm \texttt{point}$ (shifting rectangle by a certain offset)
884 \item $\texttt{rect} = \texttt{rect} \pm \texttt{size}$ (expanding or shrinking rectangle by a certain amount)
885 \item \texttt{rect += point, rect -= point, rect += size, rect -= size} (augmenting operations)
886 \item \texttt{rect = rect1 \& rect2} (rectangle intersection)
887 \item \texttt{rect = rect1 | rect2} (minimum area rectangle containing \texttt{rect2} and \texttt{rect3})
888 \item \texttt{rect \&= rect1, rect |= rect1} (and the corresponding augmenting operations)
889 \item \texttt{rect == rect1, rect != rect1} (rectangle comparison)
892 Example. Here is how the partial ordering on rectangles can be established (rect1 $\subseteq$ rect2):
894 template<typename _Tp> inline bool
895 operator <= (const Rect_<_Tp>& r1, const Rect_<_Tp>& r2)
897 return (r1 & r2) == r1;
901 For user convenience, the following type alias is available:
903 typedef Rect_<int> Rect;
906 \subsection{RotatedRect}\label{RotatedRect}
907 Possibly rotated rectangle
915 RotatedRect(const Point2f& _center, const Size2f& _size, float _angle);
916 RotatedRect(const CvBox2D& box);
918 // returns minimal up-right rectangle that contains the rotated rectangle
919 Rect boundingRect() const;
920 // backward conversion to CvBox2D
921 operator CvBox2D() const;
923 // mass center of the rectangle
927 // rotation angle in degrees
932 The class \texttt{RotatedRect} replaces the old \cross{CvBox2D} and fully compatible with it.
934 \subsection{TermCriteria}\label{TermCriteria}
936 Termination criteria for iterative algorithms
942 enum { COUNT=1, MAX_ITER=COUNT, EPS=2 };
946 // type can be MAX_ITER, EPS or MAX_ITER+EPS.
947 // type = MAX_ITER means that only the number of iterations does matter;
948 // type = EPS means that only the required precision (epsilon) does matter
949 // (though, most algorithms put some limit on the number of iterations anyway)
950 // type = MAX_ITER + EPS means that algorithm stops when
951 // either the specified number of iterations is made,
952 // or when the specified accuracy is achieved - whatever happens first.
953 TermCriteria(int _type, int _maxCount, double _epsilon);
954 TermCriteria(const CvTermCriteria& criteria);
955 operator CvTermCriteria() const;
963 The class \texttt{TermCriteria} replaces the old \cross{CvTermCriteria} and fully compatible with it.
966 \subsection{Vec}\label{Vec}
967 Template class for short numerical vectors
970 template<typename _Tp, int cn> class Vec
973 typedef _Tp value_type;
974 enum { depth = DataDepth<_Tp>::value, channels = cn,
975 type = CV_MAKETYPE(depth, channels) };
977 // default constructor: all elements are set to 0
979 // constructors taking up to 10 first elements as parameters
982 Vec(_Tp v0, _Tp v1, _Tp v2);
984 Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4,
985 _Tp v5, _Tp v6, _Tp v7, _Tp v8, _Tp v9);
986 Vec(const Vec<_Tp, cn>& v);
987 // constructs vector with all the components set to alpha.
988 static Vec all(_Tp alpha);
990 // two variants of dot-product
991 _Tp dot(const Vec& v) const;
992 double ddot(const Vec& v) const;
994 // cross-product; valid only when cn == 3.
995 Vec cross(const Vec& v) const;
997 // element type conversion
998 template<typename T2> operator Vec<T2, cn>() const;
1000 // conversion to/from CvScalar (valid only when cn==4)
1001 operator CvScalar() const;
1004 _Tp operator [](int i) const;
1005 _Tp& operator[](int i);
1011 The class is the most universal representation of short numerical vectors or tuples. It is possible to convert \texttt{Vec<T,2>} to/from \texttt{Point\_}, \texttt{Vec<T,3>} to/from \texttt{Point3\_}, and \texttt{Vec<T,4>} to \cross{CvScalar}~. The elements of \texttt{Vec} are accessed using \texttt{operator[]}. All the expected vector operations are implemented too:
1014 \item \texttt{v1 = $v2 \pm v3$, v1 = v2 * $\alpha$, v1 = $\alpha$ * v2} (plus the corresponding augmenting operations; note that these operations apply \hyperref[saturatecast]{saturate\_cast.3C.3E} to the each computed vector component)
1015 \item \texttt{v1 == v2, v1 != v2}
1016 \item \texttt{double n = norm(v1); // $L_2$-norm}
1019 For user convenience, the following type aliases are introduced:
1021 typedef Vec<uchar, 2> Vec2b;
1022 typedef Vec<uchar, 3> Vec3b;
1023 typedef Vec<uchar, 4> Vec4b;
1025 typedef Vec<short, 2> Vec2s;
1026 typedef Vec<short, 3> Vec3s;
1027 typedef Vec<short, 4> Vec4s;
1029 typedef Vec<int, 2> Vec2i;
1030 typedef Vec<int, 3> Vec3i;
1031 typedef Vec<int, 4> Vec4i;
1033 typedef Vec<float, 2> Vec2f;
1034 typedef Vec<float, 3> Vec3f;
1035 typedef Vec<float, 4> Vec4f;
1036 typedef Vec<float, 6> Vec6f;
1038 typedef Vec<double, 2> Vec2d;
1039 typedef Vec<double, 3> Vec3d;
1040 typedef Vec<double, 4> Vec4d;
1041 typedef Vec<double, 6> Vec6d;
1044 The class \texttt{Vec} can be used for declaring various numerical objects, e.g. \texttt{Vec<double,9>} can be used to store a 3x3 double-precision matrix. It is also very useful for declaring and processing multi-channel arrays, see \texttt{Mat\_} description.
1046 \subsection{Scalar\_}
1050 template<typename _Tp> class Scalar_ : public Vec<_Tp, 4>
1054 Scalar_(_Tp v0, _Tp v1, _Tp v2=0, _Tp v3=0);
1055 Scalar_(const CvScalar& s);
1057 static Scalar_<_Tp> all(_Tp v0);
1058 operator CvScalar() const;
1060 template<typename T2> operator Scalar_<T2>() const;
1062 Scalar_<_Tp> mul(const Scalar_<_Tp>& t, double scale=1 ) const;
1063 template<typename T2> void convertTo(T2* buf, int channels, int unroll_to=0) const;
1066 typedef Scalar_<double> Scalar;
1069 The template class \texttt{Scalar\_} and it's double-precision instantiation \texttt{Scalar} represent 4-element vector. Being derived from \texttt{Vec<\_Tp, 4>}, they can be used as typical 4-element vectors, but in addition they can be converted to/from \texttt{CvScalar}. The type \texttt{Scalar} is widely used in OpenCV for passing pixel values and it is a drop-in replacement for \cross{CvScalar} that was used for the same purpose in the earlier versions of OpenCV.
1071 \subsection{Range}\label{Range}
1072 Specifies a continuous subsequence (a.k.a. slice) of a sequence.
1079 Range(int _start, int _end);
1080 Range(const CvSlice& slice);
1084 operator CvSlice() const;
1090 The class is used to specify a row or column span in a matrix (\cross{Mat}), and for many other purposes. \texttt{Range(a,b)} is basically the same as \texttt{a:b} in Matlab or \texttt{a..b} in Python. As in Python, \texttt{start} is inclusive left boundary of the range, and \texttt{end} is exclusive right boundary of the range. Such a half-opened interval is usually denoted as $[start,end)$.
1092 The static method \texttt{Range::all()} returns some special variable that means "the whole sequence" or "the whole range", just like "\texttt{:}" in Matlab or "\texttt{...}" in Python. All the methods and functions in OpenCV that take \texttt{Range} support this special \texttt{Range::all()} value, but of course, in the case of your own custom processing you will probably have to check and handle it explicitly:
1094 void my_function(..., const Range& r, ....)
1096 if(r == Range::all()) {
1097 // process all the data
1100 // process [r.start, r.end)
1105 \subsection{Ptr}\label{Ptr}
1107 A template class for smart reference-counting pointers
1110 template<typename _Tp> class Ptr
1113 // default constructor
1115 // constructor that wraps the object pointer
1117 // destructor: calls release()
1119 // copy constructor; increments ptr's reference counter
1120 Ptr(const Ptr& ptr);
1121 // assignment operator; decrements own reference counter
1122 // (with release()) and increments ptr's reference counter
1123 Ptr& operator = (const Ptr& ptr);
1124 // increments reference counter
1126 // decrements reference counter; when it becomes 0,
1127 // delete_obj() is called
1129 // user-specified custom object deletion operation.
1130 // by default, "delete obj;" is called
1132 // returns true if obj == 0;
1135 // provide access to the object fields and methods
1136 _Tp* operator -> ();
1137 const _Tp* operator -> () const;
1139 // return the underlying object pointer;
1140 // thanks to the methods, the Ptr<_Tp> can be
1141 // used instead of _Tp*
1143 operator const _Tp*() const;
1145 // the encapsulated object pointer
1147 // the associated reference counter
1152 The class \texttt{Ptr<\_Tp>} is a template class that wraps pointers of the corresponding type. It is similar to \texttt{shared\_ptr} that is a part of Boost library (\url{http://www.boost.org/doc/libs/1_40_0/libs/smart_ptr/shared_ptr.htm}) and also a part of the
1153 \href{http://en.wikipedia.org/wiki/C++0x}{C++0x} standard.
1155 By using this class you can get the following capabilities:
1158 \item 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 \texttt{TObj} to \texttt{Ptr<TObj>} you will automatically get all of the necessary constructors and the assignment operator.
1159 \item all the above-mentioned operations running very fast, regardless of the data size, i.e. as "O(1)" operations. Indeed, while some structures, like \texttt{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 \texttt{Ptr<>}, the overhead becomes small and independent of the data size.
1160 \item automatic destruction, even for C structures. See the example below with \texttt{FILE*}.
1161 \item 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 \texttt{base\_class\_t*} instead, but when you loose the automatic memory management. Again, by using \texttt{Ptr<base\_class\_t>()} instead of the raw pointers, you can solve the problem.
1164 The class \texttt{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 \texttt{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 \texttt{delete obj;}.
1165 However, if the object is deallocated in a different way, then the specialized method should be created. For example, if you want to wrap \texttt{FILE}, the \texttt{delete\_obj} may be implemented as following:
1168 template<> inline void Ptr<FILE>::delete_obj()
1170 fclose(obj); // no need to clear the pointer afterwards,
1171 // it is done externally.
1176 Ptr<FILE> f(fopen("myfile.txt", "r"));
1181 // the file will be closed automatically by the Ptr<FILE> destructor.
1184 \textbf{Note}: 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 \cross{Mat} and other C++ OpenCV classes that operate on the reference counters.
1186 \subsection{Mat}\label{Mat}
1188 OpenCV C++ matrix class.
1191 class CV_EXPORTS Mat
1196 // constructs matrix of the specified size and type
1197 // (_type is CV_8UC1, CV_64FC3, CV_32SC(12) etc.)
1198 Mat(int _rows, int _cols, int _type);
1199 Mat(Size _size, int _type);
1200 // constucts matrix and fills it with the specified value _s.
1201 Mat(int _rows, int _cols, int _type, const Scalar& _s);
1202 Mat(Size _size, int _type, const Scalar& _s);
1205 // constructor for matrix headers pointing to user-allocated data
1206 Mat(int _rows, int _cols, int _type, void* _data, size_t _step=AUTO_STEP);
1207 Mat(Size _size, int _type, void* _data, size_t _step=AUTO_STEP);
1208 // creates a matrix header for a part of the bigger matrix
1209 Mat(const Mat& m, const Range& rowRange, const Range& colRange);
1210 Mat(const Mat& m, const Rect& roi);
1211 // converts old-style CvMat to the new matrix; the data is not copied by default
1212 Mat(const CvMat* m, bool copyData=false);
1213 // converts old-style IplImage to the new matrix; the data is not copied by default
1214 Mat(const IplImage* img, bool copyData=false);
1215 // builds matrix from std::vector with or without copying the data
1216 template<typename _Tp> explicit Mat(const vector<_Tp>& vec, bool copyData=false);
1217 // helper constructor to compile matrix expressions
1218 Mat(const MatExpr_Base& expr);
1219 // destructor - calls release()
1221 // assignment operators
1222 Mat& operator = (const Mat& m);
1223 Mat& operator = (const MatExpr_Base& expr);
1225 operator MatExpr_<Mat, Mat>() const;
1227 // returns a new matrix header for the specified row
1228 Mat row(int y) const;
1229 // returns a new matrix header for the specified column
1230 Mat col(int x) const;
1231 // ... for the specified row span
1232 Mat rowRange(int startrow, int endrow) const;
1233 Mat rowRange(const Range& r) const;
1234 // ... for the specified column span
1235 Mat colRange(int startcol, int endcol) const;
1236 Mat colRange(const Range& r) const;
1237 // ... for the specified diagonal
1238 // (d=0 - the main diagonal,
1239 // >0 - a diagonal from the lower half,
1240 // <0 - a diagonal from the upper half)
1241 Mat diag(int d=0) const;
1242 // constructs a square diagonal matrix which main diagonal is vector "d"
1243 static Mat diag(const Mat& d);
1245 // returns deep copy of the matrix, i.e. the data is copied
1247 // copies the matrix content to "m".
1248 // It calls m.create(this->size(), this->type()).
1249 void copyTo( Mat& m ) const;
1250 // copies those matrix elements to "m" that are marked with non-zero mask elements.
1251 void copyTo( Mat& m, const Mat& mask ) const;
1252 // converts matrix to another datatype with optional scalng. See cvConvertScale.
1253 void convertTo( Mat& m, int rtype, double alpha=1, double beta=0 ) const;
1255 void assignTo( Mat& m, int type=-1 ) const;
1257 // sets every matrix element to s
1258 Mat& operator = (const Scalar& s);
1259 // sets some of the matrix elements to s, according to the mask
1260 Mat& setTo(const Scalar& s, const Mat& mask=Mat());
1261 // creates alternative matrix header for the same data, with different
1262 // number of channels and/or different number of rows. see cvReshape.
1263 Mat reshape(int _cn, int _rows=0) const;
1265 // matrix transposition by means of matrix expressions
1266 MatExpr_<MatExpr_Op2_<Mat, double, Mat, MatOp_T_<Mat> >, Mat>
1268 // matrix inversion by means of matrix expressions
1269 MatExpr_<MatExpr_Op2_<Mat, int, Mat, MatOp_Inv_<Mat> >, Mat>
1270 inv(int method=DECOMP_LU) const;
1271 MatExpr_<MatExpr_Op4_<Mat, Mat, double, char, Mat, MatOp_MulDiv_<Mat> >, Mat>
1272 // per-element matrix multiplication by means of matrix expressions
1273 mul(const Mat& m, double scale=1) const;
1274 MatExpr_<MatExpr_Op4_<Mat, Mat, double, char, Mat, MatOp_MulDiv_<Mat> >, Mat>
1275 mul(const MatExpr_<MatExpr_Op2_<Mat, double, Mat, MatOp_Scale_<Mat> >, Mat>& m, double scale=1) const;
1276 MatExpr_<MatExpr_Op4_<Mat, Mat, double, char, Mat, MatOp_MulDiv_<Mat> >, Mat>
1277 mul(const MatExpr_<MatExpr_Op2_<Mat, double, Mat, MatOp_DivRS_<Mat> >, Mat>& m, double scale=1) const;
1279 // computes cross-product of 2 3D vectors
1280 Mat cross(const Mat& m) const;
1281 // computes dot-product
1282 double dot(const Mat& m) const;
1284 // Matlab-style matrix initialization
1285 static MatExpr_Initializer zeros(int rows, int cols, int type);
1286 static MatExpr_Initializer zeros(Size size, int type);
1287 static MatExpr_Initializer ones(int rows, int cols, int type);
1288 static MatExpr_Initializer ones(Size size, int type);
1289 static MatExpr_Initializer eye(int rows, int cols, int type);
1290 static MatExpr_Initializer eye(Size size, int type);
1292 // allocates new matrix data unless the matrix already has specified size and type.
1293 // previous data is unreferenced if needed.
1294 void create(int _rows, int _cols, int _type);
1295 void create(Size _size, int _type);
1296 // increases the reference counter; use with care to avoid memleaks
1298 // decreases reference counter;
1299 // deallocate the data when reference counter reaches 0.
1302 // locates matrix header within a parent matrix. See below
1303 void locateROI( Size& wholeSize, Point& ofs ) const;
1304 // moves/resizes the current matrix ROI inside the parent matrix.
1305 Mat& adjustROI( int dtop, int dbottom, int dleft, int dright );
1306 // extracts a rectangular sub-matrix
1307 // (this is a generalized form of row, rowRange etc.)
1308 Mat operator()( Range rowRange, Range colRange ) const;
1309 Mat operator()( const Rect& roi ) const;
1311 // converts header to CvMat; no data is copied
1312 operator CvMat() const;
1313 // converts header to IplImage; no data is copied
1314 operator IplImage() const;
1316 // returns true iff the matrix data is continuous
1317 // (i.e. when there are no gaps between successive rows).
1318 // similar to CV_IS_MAT_CONT(cvmat->type)
1319 bool isContinuous() const;
1320 // returns element size in bytes,
1321 // similar to CV_ELEM_SIZE(cvmat->type)
1322 size_t elemSize() const;
1323 // returns the size of element channel in bytes.
1324 size_t elemSize1() const;
1325 // returns element type, similar to CV_MAT_TYPE(cvmat->type)
1327 // returns element type, similar to CV_MAT_DEPTH(cvmat->type)
1329 // returns element type, similar to CV_MAT_CN(cvmat->type)
1330 int channels() const;
1331 // returns step/elemSize1()
1332 size_t step1() const;
1333 // returns matrix size:
1334 // width == number of columns, height == number of rows
1336 // returns true if matrix data is NULL
1339 // returns pointer to y-th row
1340 uchar* ptr(int y=0);
1341 const uchar* ptr(int y=0) const;
1343 // template version of the above method
1344 template<typename _Tp> _Tp* ptr(int y=0);
1345 template<typename _Tp> const _Tp* ptr(int y=0) const;
1347 // template methods for read-write or read-only element access.
1348 // note that _Tp must match the actual matrix type -
1349 // the functions do not do any on-fly type conversion
1350 template<typename _Tp> _Tp& at(int y, int x);
1351 template<typename _Tp> _Tp& at(Point pt);
1352 template<typename _Tp> const _Tp& at(int y, int x) const;
1353 template<typename _Tp> const _Tp& at(Point pt) const;
1355 // template methods for iteration over matrix elements.
1356 // the iterators take care of skipping gaps in the end of rows (if any)
1357 template<typename _Tp> MatIterator_<_Tp> begin();
1358 template<typename _Tp> MatIterator_<_Tp> end();
1359 template<typename _Tp> MatConstIterator_<_Tp> begin() const;
1360 template<typename _Tp> MatConstIterator_<_Tp> end() const;
1362 enum { MAGIC_VAL=0x42FF0000, AUTO_STEP=0, CONTINUOUS_FLAG=CV_MAT_CONT_FLAG };
1364 // includes several bit-fields:
1365 // * the magic signature
1366 // * continuity flag
1368 // * number of channels
1370 // the number of rows and columns
1372 // a distance between successive rows in bytes; includes the gap if any
1374 // pointer to the data
1377 // pointer to the reference counter;
1378 // when matrix points to user-allocated data, the pointer is NULL
1381 // helper fields used in locateROI and adjustROI
1387 The class \texttt{Mat} represents a 2D numerical array that can act as a matrix (and further it's referred to as a matrix), image, optical flow map etc. It is very similar to \cross{CvMat} type from earlier versions of OpenCV, and similarly to \texttt{CvMat}, the matrix can be multi-channel, but it also fully supports \cross{ROI} mechanism, just like \cross{IplImage}.
1389 There are many different ways to create \texttt{Mat} object. Here are the some popular ones:
1391 \item using \texttt{create(nrows, ncols, type)} method or
1392 the similar constructor \texttt{Mat(nrows, ncols, type[, fill\_value])} constructor.
1393 A new matrix of the specified size and specifed type will be allocated.
1394 \texttt{type} has the same meaning as in \cvCppCross{cvCreateMat} method,
1395 e.g. \texttt{CV\_8UC1} means 8-bit single-channel matrix,
1396 \texttt{CV\_32FC2} means 2-channel (i.e. complex) floating-point matrix etc:
1399 // make 7x7 complex matrix filled with 1+3j.
1400 cv::Mat M(7,7,CV_32FC2,Scalar(1,3));
1401 // and now turn M to 100x60 15-channel 8-bit matrix.
1402 // The old content will be deallocated
1403 M.create(100,60,CV_8UC(15));
1406 As noted in the introduction of this chapter, \texttt{create()}
1407 will only allocate a new matrix when the current matrix dimensionality
1408 or type are different from the specified.
1410 \item by using a copy constructor or assignment operator, where on the right side it can
1411 be a matrix or expression, see below. Again, as noted in the introduction,
1412 matrix assignment is O(1) operation because it only copies the header
1413 and increases the reference counter. \texttt{Mat::clone()} method can be used to get a full
1414 (a.k.a. deep) copy of the matrix when you need it.
1416 \item by constructing a header for a part of another matrix. It can be a single row, single column,
1417 several rows, several columns, rectangular region in the matrix (called a minor in algebra) or
1418 a diagonal. Such operations are also O(1), because the new header will reference the same data.
1419 You can actually modify a part of the matrix using this feature, e.g.
1422 // add 5-th row, multiplied by 3 to the 3rd row
1423 M.row(3) = M.row(3) + M.row(5)*3;
1425 // now copy 7-th column to the 1-st column
1426 // M.col(1) = M.col(7); // this will not work
1428 M.col(7).copyTo(M1);
1430 // create new 320x240 image
1431 cv::Mat img(Size(320,240),CV_8UC3);
1433 cv::Mat roi(img, Rect(10,10,100,100));
1434 // fill the ROI with (0,255,0) (which is green in RGB space);
1435 // the original 320x240 image will be modified
1436 roi = Scalar(0,255,0);
1439 Thanks to the additional \texttt{datastart} and \texttt{dataend} members, it is possible to
1440 compute the relative sub-matrix position in the main \emph{"container"} matrix using \texttt{locateROI()}:
1443 Mat A = Mat::eye(10, 10, CV_32S);
1444 // extracts A columns, 1 (inclusive) to 3 (exclusive).
1445 Mat B = A(Range::all(), Range(1, 3));
1446 // extracts B rows, 5 (inclusive) to 9 (exclusive).
1447 // that is, C ~ A(Range(5, 9), Range(1, 3))
1448 Mat C = B(Range(5, 9), Range::all());
1449 Size size; Point ofs;
1450 C.locateROI(size, ofs);
1451 // size will be (width=10,height=10) and the ofs will be (x=1, y=5)
1454 As in the case of whole matrices, if you need a deep copy, use \texttt{clone()} method
1455 of the extracted sub-matrices.
1457 \item by making a header for user-allocated-data. It can be useful for
1459 \item processing "foreign" data using OpenCV (e.g. when you implement
1460 a DirectShow filter or a processing module for gstreamer etc.), e.g.
1463 void process_video_frame(const unsigned char* pixels,
1464 int width, int height, int step)
1466 cv::Mat img(height, width, CV_8UC3, pixels, step);
1467 cv::GaussianBlur(img, img, cv::Size(7,7), 1.5, 1.5);
1471 \item for quick initialization of small matrices and/or super-fast element access
1473 double m[3][3] = {{a, b, c}, {d, e, f}, {g, h, i}};
1474 cv::Mat M = cv::Mat(3, 3, CV_64F, m).inv();
1478 partial yet very common cases of this "user-allocated data" case are conversions
1479 from \cross{CvMat} and \cross{IplImage} to \texttt{Mat}. For this purpose there are special constructors
1480 taking pointers to \texttt{CvMat} or \texttt{IplImage} and the optional
1481 flag indicating whether to copy the data or not.
1483 Backward conversion from \texttt{Mat} to \texttt{CvMat} or \texttt{IplImage} is provided via cast operators
1484 \texttt{Mat::operator CvMat() const} an \texttt{Mat::operator IplImage()}.
1485 The operators do \emph{not} copy the data.
1488 IplImage* img = cvLoadImage("greatwave.jpg", 1);
1489 Mat mtx(img); // convert IplImage* -> cv::Mat
1490 CvMat oldmat = mtx; // convert cv::Mat -> CvMat
1491 CV_Assert(oldmat.cols == img->width && oldmat.rows == img->height &&
1492 oldmat.data.ptr == (uchar*)img->imageData && oldmat.step == img->widthStep);
1495 \item by using MATLAB-style matrix initializers, \texttt{zeros(), ones(), eye()}, e.g.:
1498 // create a double-precision identity martix and add it to M.
1499 M += Mat::eye(M.rows, M.cols, CV_64F);
1502 \item by using comma-separated initializer:
1504 // create 3x3 double-precision identity matrix
1505 Mat M = (Mat_<double>(3,3) << 1, 0, 0, 0, 1, 0, 0, 0, 1);
1508 here we first call constructor of \texttt{Mat\_} class (that we describe further) with the proper matrix, and then we just put \texttt{<<} 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.
1512 Once matrix is created, it will be automatically managed by using reference-counting mechanism (unless the matrix header is built on top of user-allocated data, in which case you should handle the data by yourself).
1513 The matrix data will be deallocated when no one points to it; if you want to release the data pointed by a matrix header before the matrix destructor is called, use \texttt{Mat::release()}.
1515 The next important thing to learn about the matrix class is element access. Here is how the matrix is stored. The elements are stored in row-major order (row by row). The \texttt{Mat::data} member points to the first element of the first row, \texttt{Mat::rows} contains the number of matrix rows and \texttt{Mat::cols} -- the number of matrix columns. There is yet another member, called \texttt{Mat::step} that is used to actually compute address of a matrix element. The \texttt{Mat::step} is needed because the matrix can be a part of another matrix or because there can some padding space in the end of each row for a proper alignment.
1516 %\includegraphics[width=1.0\textwidth]{pics/roi.png}
1518 Given these parameters, address of the matrix element $M_{ij}$ is computed as following:
1521 \texttt{addr($M_{ij}$)=M.data + M.step*i + j*M.elemSize()}
1524 if you know the matrix element type, e.g. it is \texttt{float}, then you can use \texttt{at<>()} method:
1527 \texttt{addr($M_{ij}$)=\&M.at<float>(i,j)}
1529 (where \& is used to convert the reference returned by \texttt{at} to a pointer).
1530 if you need to process a whole row of matrix, the most efficient way is to get the pointer to the row first, and then just use plain C operator \texttt{[]}:
1533 // compute sum of positive matrix elements
1534 // (assuming that M is double-precision matrix)
1536 for(int i = 0; i < M.rows; i++)
1538 const double* Mi = M.ptr<double>(i);
1539 for(int j = 0; j < M.cols; j++)
1540 sum += std::max(Mi[j], 0.);
1544 Some operations, like the above one, do not actually depend on the matrix shape, they just process elements of a matrix one by one (or elements from multiple matrices that are sitting in the same place, e.g. matrix addition). Such operations are called element-wise and it makes sense to check whether all the input/output matrices are continuous, i.e. have no gaps in the end of each row, and if yes, process them as a single long row:
1547 // compute sum of positive matrix elements, optimized variant
1549 int cols = M.cols, rows = M.rows;
1550 if(M.isContinuous())
1555 for(int i = 0; i < rows; i++)
1557 const double* Mi = M.ptr<double>(i);
1558 for(int j = 0; j < cols; j++)
1559 sum += std::max(Mi[j], 0.);
1562 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.
1564 Finally, there are STL-style iterators that are smart enough to skip gaps between successive rows:
1566 // compute sum of positive matrix elements, iterator-based variant
1568 MatConstIterator_<double> it = M.begin<double>(), it_end = M.end<double>();
1569 for(; it != it_end; ++it)
1570 sum += std::max(*it, 0.);
1573 The matrix iterators are random-access iterators, so they can be passed to any STL algorithm, including \texttt{std::sort()}.
1575 \subsection{Matrix Expressions}
1577 This is a list of implemented matrix operations that can be combined in arbitrary complex expressions
1578 (here \emph{A}, \emph{B} stand for matrices (\texttt{Mat}), \emph{s} for a scalar (\texttt{Scalar}),
1579 \emph{$\alpha$} for a real-valued scalar (\texttt{double})):
1582 \item addition, subtraction, negation: $\texttt{A}\pm \texttt{B},\;\texttt{A}\pm \texttt{s},\;\texttt{s}\pm \texttt{A},\;-\texttt{A}$
1583 \item scaling: \texttt{A*$\alpha$, A/$\alpha$}
1584 \item per-element multiplication and division: \texttt{A.mul(B), A/B, $\alpha$/A}
1585 \item matrix multiplication: \texttt{A*B}
1586 \item transposition: \texttt{A.t() $\sim A^t$}
1587 \item matrix inversion and pseudo-inversion, solving linear systems and least-squares problems:
1588 \texttt{A.inv([method]) $\sim A^{-1}$}, \texttt{A.inv([method])*B $\sim X:\,AX=B$}
1589 \item comparison: $\texttt{A}\gtreqqless \texttt{B},\;\texttt{A} \ne \texttt{B},\;\texttt{A}\gtreqqless \alpha,\; \texttt{A} \ne \alpha$.
1590 The result of comparison is 8-bit single channel mask, which elements are set to 255
1591 (if the particular element or pair of elements satisfy the condition) and 0 otherwise.
1592 \item bitwise logical operations: \texttt{A \& B, A \& s, A | B, A | s, A \^ B, A \^ s, \textasciitilde A}
1593 \item element-wise minimum and maximum: \texttt{min(A, B), min(A, $\alpha$), max(A, B), max(A, $\alpha$)}
1594 \item element-wise absolute value: \texttt{abs(A)}
1595 \item cross-product, dot-product: \texttt{A.cross(B), A.dot(B)}
1596 \item any function of matrix or matrices and scalars that returns a matrix or a scalar, such as
1597 \cvCppCross{norm}, \cvCppCross{mean}, \cvCppCross{sum}, \cvCppCross{countNonZero}, \cvCppCross{trace},
1598 \cvCppCross{determinant}, \cvCppCross{repeat} etc.
1599 \item matrix initializers (\texttt{eye(), zeros(), ones()}), matrix comma-separated initializers,
1600 matrix constructors and operators that extract sub-matrices (see \cross{Mat} description).
1601 \item \verb"Mat_<destination_type>()" constructors to cast the result to the proper type.
1603 Note, however, that comma-separated initializers and probably some other operations may require additional explicit \texttt{Mat()} or \verb"Mat_<T>()" constuctor calls to resolve possible ambiguity.
1605 Below is the formal description of the \texttt{Mat} methods.
1607 \cvCppFunc{Mat::Mat}
1608 Various matrix constructors
1611 (1) Mat::Mat();\newline
1612 (2) Mat::Mat(int rows, int cols, int type);\newline
1613 (3) Mat::Mat(Size size, int type);\newline
1614 (4) Mat::Mat(int rows, int cols, int type, const Scalar\& s);\newline
1615 (5) Mat::Mat(Size size, int type, const Scalar\& s);\newline
1616 (6) Mat::Mat(const Mat\& m);\newline
1617 (7) Mat::Mat(int rows, int cols, int type, void* data, size\_t step=AUTO\_STEP);\newline
1618 (8) Mat::Mat(Size size, int type, void* data, size\_t step=AUTO\_STEP);\newline
1619 (9) Mat::Mat(const Mat\& m, const Range\& rowRange, const Range\& colRange);\newline
1620 (10) Mat::Mat(const Mat\& m, const Rect\& roi);\newline
1621 (11) Mat::Mat(const CvMat* m, bool copyData=false);\newline
1622 (12) Mat::Mat(const IplImage* img, bool copyData=false);\newline
1623 (13) template<typename \_Tp> explicit Mat::Mat(const vector<\_Tp>\& vec, bool copyData=false);\newline
1624 (14) Mat::Mat(const MatExpr\_Base\& expr);
1627 \cvarg{rows}{The number of matrix rows}
1628 \cvarg{cols}{The number of matrix columns}
1629 \cvarg{size}{The matrix size: \texttt{Size(cols, rows)}. Note that in the \texttt{Size()} constructor the number of rows and the number of columns go in the reverse order.}
1630 \cvarg{type}{The matrix type, use \texttt{CV\_8UC1, ..., CV\_64FC4} to create 1-4 channel matrices, or \texttt{CV\_8UC(n), ..., CV\_64FC(n)} to create multi-channel (up to \texttt{CV\_MAX\_CN} channels) matrices}
1631 \cvarg{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 \texttt{Mat::operator=(const Scalar\& value)}.}
1632 \cvarg{data}{Pointer to the user data. Matrix constructors that take \texttt{data} and \texttt{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.}
1633 \cvarg{step}{The \texttt{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 \texttt{cv::AUTO\_STEP}), no padding is assumed and the actual step is calculated as \texttt{cols*elemSize()}, see \cross{Mat::elemSize}().}
1634 \cvarg{m}{The matrix that (in whole, a partly) is assigned to the constructed matrix. No data is copied by these constructors. Instead, the header pointing to \texttt{m} data, or its rectangular submatrix, is constructed and the associated with it reference counter, if any, is incremented. That is, by modifying the newly constructed matrix, you will also modify the corresponding elements of \texttt{m}.}
1635 \cvarg{img}{Pointer to the old-style \texttt{IplImage} image structure. By default, the data is shared between the original image and the new matrix, but when \texttt{copyData} is set, the full copy of the image data is created.}
1636 \cvarg{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 \cross{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 \texttt{Mat} instances, you should write \texttt{Mat(vec)} explicitly. Another obvious note: unless you copied the data into the matrix (\texttt{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.}
1637 \cvarg{copyData}{Specifies, whether the underlying data of the STL vector, or the old-style \texttt{CvMat} or \texttt{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 \texttt{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.}
1638 \cvarg{rowRange}{The range of the \texttt{m}'s rows to take. As usual, the range start is inclusive and the range end is exclusive. Use \texttt{Range::all()} to take all the rows.}
1639 \cvarg{colRange}{The range of the \texttt{m}'s columns to take. Use \texttt{Range::all()} to take all the columns.}
1640 \cvarg{expr}{Matrix expression. See \cross{Matrix Expressions}.}
1643 These are various constructors that form a matrix. As noticed in the
1644 \hyperref{AutomaticMemoryManagement2}{introduction}, 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 \cross{Mat::create}.
1646 \cvCppFunc{Mat::Mat}index{cv::Mat::\textasciitilde Mat}label{cppfunc.Mat::destructor}
1650 Mat::\textasciitilde Mat();
1653 The matrix destructor calls \cross{Mat::release}.
1655 \cvCppFunc{Mat::operator =}
1656 Matrix assignment operators
1659 Mat\& Mat::operator = (const Mat\& m);\newline
1660 Mat\& Mat::operator = (const MatExpr\_Base\& expr);\newline
1661 Mat\& operator = (const Scalar\& s);
1664 \cvarg{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 \cross{Mat::release}.}
1665 \cvarg{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, \texttt{C=A+B} is expanded to \texttt{cv::add(A, B, C)}, and \cvCppCross{add} will take care of automatic \texttt{C} reallocation.}
1666 \cvarg{s}{The scalar, assigned to each matrix element. The matrix size or type is not changed.}
1669 These are the available assignment operators, and they all are very different, so, please, look at the operator parameters description.
1671 \cvCppFunc{Mat::operator MatExpr}\index{cv::Mat::operator MatExpr\_}\label{cppfunc.Mat::operator MatExpr}
1672 Mat-to-MatExpr cast operator
1675 Mat::operator MatExpr\_<Mat, Mat>() const;
1678 The cast operator should not be called explicitly. It is used internally by the \cross{Matrix Expressions} engine.
1680 \cvCppFunc{Mat::row}
1681 Makes a matrix header for the specified matrix row
1684 Mat Mat::row(int i) const;
1687 \cvarg{i}{the 0-based row index}
1690 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:
1693 inline void matrix_axpy(Mat& A, int i, int j, double alpha)
1695 A.row(i) += A.row(j)*alpha;
1699 \textbf{Important note}. In the current implementation the following code will not work as expected:
1703 A.row(i) = A.row(j); // will not work
1706 This is because \texttt{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 \cross{Mat::copyTo} method:
1711 // works, but looks a bit obscure.
1712 A.row(i) = A.row(j) + 0;
1714 // this is a bit longer, but the recommended method.
1715 Mat Ai = A.row(i); M.row(j).copyTo(Ai);
1719 \cvCppFunc{Mat::col}
1720 Makes a matrix header for the specified matrix column
1723 Mat Mat::col(int j) const;
1726 \cvarg{j}{the 0-based column index}
1729 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 \cross{Mat::row} description.
1732 \cvCppFunc{Mat::rowRange}
1733 Makes a matrix header for the specified row span
1736 Mat Mat::rowRange(int startrow, int endrow) const;\newline
1737 Mat Mat::rowRange(const Range\& r) const;
1740 \cvarg{startrow}{the 0-based start index of the row span}
1741 \cvarg{endrow}{the 0-based ending index of the row span}
1742 \cvarg{r}{The \cvCppCross{Range} structure containing both the start and the end indices}
1745 The method makes a new header for the specified row span of the matrix. Similarly to \cvCppCross{Mat::row} and \cvCppCross{Mat::col}, this is O(1) operation.
1748 \cvCppFunc{Mat::colRange}
1749 Makes a matrix header for the specified row span
1752 Mat Mat::colRange(int startcol, int endcol) const;\newline
1753 Mat Mat::colRange(const Range\& r) const;
1756 \cvarg{startcol}{the 0-based start index of the column span}
1757 \cvarg{endcol}{the 0-based ending index of the column span}
1758 \cvarg{r}{The \cvCppCross{Range} structure containing both the start and the end indices}
1761 The method makes a new header for the specified column span of the matrix. Similarly to \cvCppCross{Mat::row} and \cvCppCross{Mat::col}, this is O(1) operation.
1764 \cvCppFunc{Mat::diag}
1765 Extracts diagonal from a matrix, or creates a diagonal matrix.
1768 Mat Mat::diag(int d) const;
1769 static Mat Mat::diag(const Mat\& matD);
1772 \cvarg{d}{index of the diagonal, with the following meaning:}
1774 \cvarg{d=0}{the main diagonal}
1775 \cvarg{d>0}{a diagonal from the lower half, e.g. \texttt{d=1} means the diagonal immediately below the main one}
1776 \cvarg{d<0}{a diagonal from the upper half, e.g. \texttt{d=1} means the diagonal immediately above the main one}
1778 \cvarg{matD}{single-column matrix that will form the diagonal matrix.}
1781 The method makes a new header for the specified matrix diagonal. The new matrix will be represented as a single-column matrix. Similarly to \cvCppCross{Mat::row} and \cvCppCross{Mat::col}, this is O(1) operation.
1784 \cvCppFunc{Mat::clone}
1785 Creates full copy of the matrix and the underlying data.
1788 Mat Mat::clone() const;
1791 The method creates full copy of the matrix. The original matrix \texttt{step} is not taken into the account, however. The matrix copy will be a continuous matrix occupying \texttt{cols*rows*elemSize()} bytes.
1794 \cvCppFunc{Mat::copyTo}
1795 Copies the matrix to another one.
1798 void Mat::copyTo( Mat\& m ) const;
1799 void Mat::copyTo( Mat\& m, const Mat\& mask ) const;
1802 \cvarg{m}{The destination matrix. If it does not have a proper size or type before the operation, it will be reallocated}
1803 \cvarg{mask}{The operation mask. Its non-zero elements indicate, which matrix elements need to be copied}
1806 The method copies the matrix data to another matrix. Before copying the data, the method invokes
1809 m.create(this->size(), this->type);
1812 so that the destination matrix is reallocated if needed. While \texttt{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.
1814 When the operation mask is specified, and the \texttt{Mat::create} call shown above reallocated the matrix, the newly allocated matrix is initialized with all 0's before copying the data.
1817 \cvCppFunc{Mat::copyTo}
1818 Converts matrix to another datatype with optional scaling.
1821 void Mat::convertTo( Mat\& m, int rtype, double alpha=1, double beta=0 ) const;
1824 \cvarg{m}{The destination matrix. If it does not have a proper size or type before the operation, it will be reallocated}
1825 \cvarg{rtype}{The desired destination matrix type, or rather, the depth (since the number of channels will be the same with the source one). If \texttt{rtype} is negative, the destination matrix will have the same type as the source.}
1826 \cvarg{alpha}{The optional scale factor}
1827 \cvarg{beta}{The optional delta, added to the scaled values.}
1830 The method converts source pixel values to the target datatype. \texttt{saturate\_cast<>} is applied in the end to avoid possible overflows:
1833 m(x,y) = saturate\_cast<rType>(\alpha (*this)(x,y) + \beta)
1836 \cvCppFunc{Mat::assignTo}
1837 Functional form of convertTo
1840 void Mat::assignTo( Mat\& m, int type=-1 ) const;
1843 \cvarg{m}{The destination matrix}
1844 \cvarg{type}{The desired destination matrix depth (or -1 if it should be the same as the source one).}
1847 This is internal-use method called by the \cross{Matrix Expressions} engine.
1849 \cvCppFunc{Mat::setTo}
1850 Sets all or some of the matrix elements to the specified value.
1853 Mat\& Mat::setTo(const Scalar\& s, const Mat\& mask=Mat());
1856 \cvarg{s}{Assigned scalar, which is converted to the actual matrix type}
1857 \cvarg{mask}{The operation mask of the same size as \texttt{*this}}
1860 This is the advanced variant of \texttt{Mat::operator=(const Scalar\& s)} operator.
1863 Changes the matrix's shape and/or the number of channels without copying the data.
1866 Mat Mat::reshape(int cn, int rows=0) const;
1870 \cvarg{cn}{The new number of channels. If the parameter is 0, the number of channels remains the same.}
1871 \cvarg{rows}{The new number of rows. If the parameter is 0, the number of rows remains the same.}
1874 The method makes a new matrix header for \texttt{*this} elements. The new matrix may have different size and/or different number of channels. Any combination is possible, as long as:
1876 \item No extra elements is included into the new matrix and no elements are excluded. Consequently,
1877 the product \texttt{rows*cols*channels()} must stay the same after the transformation.
1878 \item 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 \cvCppCross{Mat::isContinuous}.
1881 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 \texttt{3xN} matrix. Here is how it can be done:
1884 std::vector<cv::Point3f> vec;
1887 Mat pointMat = Mat(vec). // convert vector to Mat, O(1) operation
1888 reshape(1). // make Nx3 1-channel matrix out of Nx1 3-channel.
1889 // Also, an O(1) operation
1890 t(); // finally, transpose the Nx3 matrix.
1891 // This involves copying of all the elements
1895 \cvCppFunc{Mat::t()}
1896 Transposes the matrix
1899 MatExpr\_<MatExpr\_Op2\_<Mat, double, Mat, MatOp\_T\_<Mat> >, Mat>
1902 The method performs matrix transposition by means of matrix expressions.
1903 That is, the method 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:
1906 Mat A1 = A + Mat::eye(A.size(), A.type)*lambda;
1907 Mat C = A1.t()*A1; // compute (A + lambda*I)^t * (A + lamda*I)
1910 \cvCppFunc{Mat::inv}
1914 MatExpr\_<MatExpr\_Op2\_<Mat, int, Mat, MatOp\_Inv\_<Mat> >, Mat>
1915 Mat::inv(int method=DECOMP\_LU) const;
1919 \cvarg{method}{The matrix inversion method, one of}
1921 \cvarg{DECOMP\_LU}{LU decomposition. The matrix must be non-singular}
1922 \cvarg{DECOMP\_CHOLESKY}{Cholesky $LL^T$ decomposition, for symmetrical positively defined matrices only. About twice faster than LU on big matrices.}
1923 \cvarg{DECOMP\_SVD}{SVD decomposition. The matrix can be a singular or even non-square, then the pseudo-inverse is computed}
1927 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.
1929 \cvCppFunc{Mat::mul}
1930 Performs element-wise multiplication or division of the two matrices
1933 MatExpr\_<...MatOp\_MulDiv\_<>...>\newline
1934 Mat::mul(const Mat\& m, double scale=1) const;\newline
1935 MatExpr\_<...MatOp\_MulDiv\_<>...>\newline
1936 Mat::mul(const MatExpr\_<...MatOp\_Scale\_<>...>\& m, double scale=1) const;\newline
1937 MatExpr\_<...MatOp\_MulDiv\_<>...>\newline
1938 Mat::mul(const MatExpr\_<...MatOp\_DivRS\_<>...>\& m, double scale=1) const;
1942 \cvarg{m}{Another matrix, of the same type and the same size as \texttt{*this}, or a scaled matrix, or a scalar divided by a matrix (i.e. a matrix where all the elements are scaled reciprocals of some other matrix)}
1943 \cvarg{scale}{The optional scale factor}
1946 The method returns a temporary object encoding per-element matrix multiply or divide operation, with optional scale. Note that this is not a matrix multiplication, corresponding to the simpler "*" operator.
1948 Here is the example that will automatically invoke the third form of the method:
1951 Mat C = A.mul(5/B); // equivalent to divide(A, B, C, 5)
1954 \cvCppFunc{Mat::cross}
1955 Computes cross-product of two 3-element vectors
1958 Mat Mat::cross(const Mat\& m) const;
1961 \cvarg{m}{Another cross-product operand}
1964 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.
1966 \cvCppFunc{Mat::dot}
1967 Computes dot-product of two vectors
1970 double Mat::dot(const Mat\& m) const;
1973 \cvarg{m}{Another dot-product operand.}
1976 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.
1978 \cvCppFunc{Mat::zeros}
1979 Returns zero matrix of the specified size and type
1982 static MatExpr\_Initializer Mat::zeros(int rows, int cols, int type);
1983 static MatExpr\_Initializer Mat::zeros(Size size, int type);
1986 \cvarg{rows}{The number of rows}
1987 \cvarg{cols}{The number of columns}
1988 \cvarg{size}{Alternative matrix size specification: \texttt{Size(cols, rows)}}
1989 \cvarg{type}{The created matrix type}
1992 The method returns Matlab-style zero matrix initializer. It can be used to quickly form a constant matrix and use it as a function parameter, as a part of matrix expression, or as a matrix initializer.
1996 A = Mat::zeros(3, 3, CV_32F);
1999 Note that in the above sample a new matrix will be allocated only if \texttt{A} is not 3x3 floating-point matrix, otherwise the existing matrix \texttt{A} will be filled with 0's.
2002 \cvCppFunc{Mat::ones}
2003 Returns matrix of all 1's of the specified size and type
2006 static MatExpr\_Initializer Mat::ones(int rows, int cols, int type);
2007 static MatExpr\_Initializer Mat::ones(Size size, int type);
2010 \cvarg{rows}{The number of rows}
2011 \cvarg{cols}{The number of columns}
2012 \cvarg{size}{Alternative matrix size specification: \texttt{Size(cols, rows)}}
2013 \cvarg{type}{The created matrix type}
2016 The method returns Matlab-style ones' matrix initializer, similarly to \cvCppCross{Mat::zeros}. Note that using this method you can initialize a matrix with arbitrary value, using the following Matlab idiom:
2019 Mat A = Mat::ones(100, 100, CV_8U)*3; // make 100x100 matrix filled with 3.
2022 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 expanding the matrix initializer.
2024 \cvCppFunc{Mat::eye}
2025 Returns matrix of all 1's of the specified size and type
2028 static MatExpr\_Initializer Mat::eye(int rows, int cols, int type);
2029 static MatExpr\_Initializer Mat::eye(Size size, int type);
2032 \cvarg{rows}{The number of rows}
2033 \cvarg{cols}{The number of columns}
2034 \cvarg{size}{Alternative matrix size specification: \texttt{Size(cols, rows)}}
2035 \cvarg{type}{The created matrix type}
2038 The method returns Matlab-style identity matrix initializer, similarly to \cvCppCross{Mat::zeros}. Note that using this method you can initialize a matrix with a scaled identity matrix, by multiplying the initializer by the needed scale factor:
2041 // make a 4x4 diagonal matrix with 0.1's on the diagonal.
2042 Mat A = Mat::eye(4, 4, CV_32F)*0.1;
2045 and this is also done very efficiently in O(1) time.
2047 \cvCppFunc{Mat::create}
2048 Allocates new matrix data if needed.
2051 void Mat::create(int rows, int cols, int type);
2052 void create(Size size, int type);
2055 \cvarg{rows}{The new number of rows}
2056 \cvarg{cols}{The new number of columns}
2057 \cvarg{size}{Alternative new matrix size specification: \texttt{Size(cols, rows)}}
2058 \cvarg{type}{The new matrix type}
2061 This is one of the key \texttt{Mat} methods. Most new-style OpenCV functions and methods that produce matrices call this method for each output matrix. The method algorithm is the following:
2064 \item if the current matrix size and the type match the new ones, return immediately.
2065 \item otherwise, dereference the previous data by calling \cvCppCross{Mat::release}
2066 \item initialize the new header
2067 \item allocate the new data of \texttt{rows*cols*elemSize()} bytes
2068 \item allocate the new associated with the data reference counter and set it to 1.
2071 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 matrices.
2073 \cvCppFunc{Mat::addref}
2074 Increments the reference counter
2080 The method increments the reference counter, associated with the matrix data. If the matrix header points to an external data (see \cvCppCross{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.
2083 \cvCppFunc{Mat::release}
2084 Decrements the reference counter and deallocates the matrix if needed
2087 void Mat::release();
2090 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 \cvCppCross{Mat::Mat}), the reference counter is NULL, and the method has no effect in this case.
2092 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.
2094 \cvCppFunc{Mat::locateROI}
2095 Locates matrix header within a parent matrix
2098 void Mat::locateROI( Size\& wholeSize, Point\& ofs ) const;
2101 \cvarg{wholeSize}{The output parameter that will contain size of the whole matrix, which \texttt{*this} is a part of.}
2102 \cvarg{ofs}{The output parameter that will contain offset of \texttt{*this} inside the whole matrix}
2105 After you extracted a submatrix from a matrix using \cvCppCross{Mat::row}, \cvCppCross{Mat::col}, \cvCppCross{Mat::rowRange}, \cvCppCross{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 \texttt{datastart} and \texttt{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 \texttt{locateROI} does exactly that.
2107 \cvCppFunc{Mat::adjustROI}
2108 Adjust submatrix size and position within the parent matrix
2111 Mat\& Mat::adjustROI( int dtop, int dbottom, int dleft, int dright );
2114 \cvarg{dtop}{The shift of the top submatrix boundary upwards}
2115 \cvarg{dbottom}{The shift of the bottom submatrix boundary downwards}
2116 \cvarg{dleft}{The shift of the left submatrix boundary to the left}
2117 \cvarg{dright}{The shift of the right submatrix boundary to the right}
2120 The method is complimentary to the \cvCppCross{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.
2123 A.adjustROI(2, 2, 2, 2);
2126 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.
2128 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.
2130 The function is used internally by the OpenCV filtering functions, like \cvCppCross{filter2D}, morphological operations etc.
2132 See also \cvCppCross{copyMakeBorder}.
2134 \cvCppFunc{Mat::operator()}
2135 Extracts a rectangular submatrix
2138 Mat Mat::operator()( Range rowRange, Range colRange ) const;\newline
2139 Mat Mat::operator()( const Rect\& roi ) const;
2142 \cvarg{rowRange}{The start and the end row of the extracted submatrix. The upper boundary is not included. To select all the rows, use \texttt{Range::all()}}
2143 \cvarg{colRange}{The start and the end column of the extracted submatrix. The upper boundary is not included. To select all the columns, use \texttt{Range::all()}}
2144 \cvarg{roi}{The extracted submatrix specified as a rectangle}
2147 The operators make a new header for the specified submatrix of \texttt{*this}. They are the most generalized forms of \cvCppCross{Mat::row}, \cvCppCross{Mat::col}, \cvCppCross{Mat::rowRange} and \cvCppCross{Mat::colRange}. For example, \texttt{A(Range(0, 10), Range::all())} is equivalent to \texttt{A.rowRange(0, 10)}. Similarly to all of the above, the operators are O(1) operations, i.e. no matrix data is copied.
2149 \cvCppFunc{Mat::operator CvMat}
2150 Creates CvMat header for the matrix
2153 Mat::operator CvMat() const;
2156 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 \texttt{CvMat} header is used. The operator is useful for intermixing the new and the old OpenCV API's, e.g:
2159 Mat img(Size(320, 240), CV_8UC3);
2163 my_old_cv_func( &cvimg, ...);
2166 where \texttt{my\_old\_cv\_func} is some functions written to work with OpenCV 1.x data structures.
2169 \cvCppFunc{Mat::operator IplImage}
2170 Creates IplImage header for the matrix
2173 Mat::operator IplImage() const;
2176 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 \texttt{IplImage} header is used. Similarly to \texttt{Mat::operator CvMat}, the operator is useful for intermixing the new and the old OpenCV API's.
2179 \cvCppFunc{Mat::isContinuous}
2180 Reports whether the matrix is continuous or not
2183 bool Mat::isContinuous() const;
2186 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, \texttt{1x1} or \texttt{1xN} matrices are always continuous. Matrices created with \cvCppCross{Mat::create} are always continuous, but if you extract a part of the matrix using \cvCppCross{Mat::col}, \cvCppCross{Mat::diag} etc. or constructed a matrix header for externally allocated data, such matrices may no longer have this property.
2188 The continuity flag is stored as a bit in \texttt{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:
2191 // alternative implementation of Mat::isContinuous()
2192 bool myCheckMatContinuity(const Mat& m)
2194 //return (m.flags & Mat::CONTINUOUS_FLAG) != 0;
2195 return m.rows == 1 || m.step == m.cols*m.elemSize();
2199 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.
2202 template<typename T>
2203 void alphaBlendRGBA(const Mat& src1, const Mat& src2, Mat& dst)
2205 const float alpha_scale = (float)std::numeric_limits<T>::max(),
2206 inv_scale = 1.f/alpha_scale;
2208 CV_Assert( src1.type() == src2.type() &&
2209 src1.type() == CV_MAKETYPE(DataType<T>::depth, 4) &&
2210 src1.size() == src2.size());
2211 Size size = src1.size();
2212 dst.create(size, src1.type());
2214 // here is the idiom: check the arrays for continuity and,
2215 // if this is the case,
2216 // treat the arrays as 1D vectors
2217 if( src1.isContinuous() && src2.isContinuous() && dst.isContinuous() )
2219 size.width *= size.height;
2224 for( int i = 0; i < size.height; i++ )
2226 // when the arrays are continuous,
2227 // the outer loop is executed only once
2228 const T* ptr1 = src1.ptr<T>(i);
2229 const T* ptr2 = src2.ptr<T>(i);
2230 T* dptr = dst.ptr<T>(i);
2232 for( int j = 0; j < size.width; j += 4 )
2234 float alpha = ptr1[j+3]*inv_scale, beta = ptr2[j+3]*inv_scale;
2235 dptr[j] = saturate_cast<T>(ptr1[j]*alpha + ptr2[j]*beta);
2236 dptr[j+1] = saturate_cast<T>(ptr1[j+1]*alpha + ptr2[j+1]*beta);
2237 dptr[j+2] = saturate_cast<T>(ptr1[j+2]*alpha + ptr2[j+2]*beta);
2238 dptr[j+3] = saturate_cast<T>((1 - (1-alpha)*(1-beta))*alpha_scale);
2244 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.
2246 Also, note that we use another OpenCV idiom in this function - we call \cvCppCross{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 \cvCppCross{create} does not always allocate a new matrix.
2248 \cvCppFunc{Mat::elemSize}
2249 Returns matrix element size in bytes
2252 size\_t Mat::elemSize() const;
2255 The method returns the matrix element size in bytes. For example, if the matrix type is \texttt{CV\_16SC3}, the method will return \texttt{3*sizeof(short)} or 6.
2257 \cvCppFunc{Mat::elemSize1}
2258 Returns size of each matrix element channel in bytes
2261 size\_t Mat::elemSize1() const;
2264 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 \texttt{CV\_16SC3}, the method will return \texttt{sizeof(short)} or 2.
2266 \cvCppFunc{Mat::type}
2267 Returns matrix element type
2270 int Mat::type() const;
2273 The method returns the matrix element type, an id, compatible with the \texttt{CvMat} type system, like \texttt{CV\_16SC3} or 16-bit signed 3-channel array etc.
2275 \cvCppFunc{Mat::depth}
2276 Returns matrix element depth
2279 int Mat::depth() const;
2282 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 \texttt{CV\_16S}. The complete list of matrix types:
2284 \item \texttt{CV\_8U} - 8-bit unsigned integers (\texttt{0..255})
2285 \item \texttt{CV\_8S} - 8-bit signed integers (\texttt{-128..127})
2286 \item \texttt{CV\_16U} - 16-bit unsigned integers (\texttt{0..65535})
2287 \item \texttt{CV\_16S} - 16-bit signed integers (\texttt{-32768..32767})
2288 \item \texttt{CV\_32S} - 32-bit signed integers (\texttt{-2147483648..2147483647})
2289 \item \texttt{CV\_32F} - 32-bit floating-point numbers (\texttt{-FLT\_MAX..FLT\_MAX, INF, NAN})
2290 \item \texttt{CV\_64F} - 64-bit floating-point numbers (\texttt{-DBL\_MAX..DBL\_MAX, INF, NAN})
2293 \cvCppFunc{Mat::channels}
2294 Returns matrix element depth
2297 int Mat::channels() const;
2300 The method returns the number of matrix channels.
2302 \cvCppFunc{Mat::step1}
2303 Returns normalized step
2306 size\_t Mat::step1() const;
2309 The method returns the matrix step, divided by \cvCppCross{Mat::elemSize1()}. It can be useful for fast access to arbitrary matrix element.
2311 \cvCppFunc{Mat::size}
2312 Returns the matrix size
2315 Size Mat::size() const;
2318 The method returns the matrix size: \texttt{Size(cols, rows)}.
2320 \cvCppFunc{Mat::empty}
2321 Returns true if matrix data is not allocated
2324 bool Mat::empty() const;
2327 The method returns true if and only if the matrix data is NULL pointer. The method has been introduced to improve matrix similarity with STL vector.
2329 \cvCppFunc{Mat::ptr}
2330 Return pointer to the specified matrix row
2333 uchar* Mat::ptr(int i=0);\newline
2334 const uchar* Mat::ptr(int i=0) const;\newline
2335 template<typename \_Tp> \_Tp* Mat::ptr(int i=0);\newline
2336 template<typename \_Tp> const \_Tp* Mat::ptr(int i=0) const;
2339 \cvarg{i}{The 0-based row index}
2342 The methods return \texttt{uchar*} or typed pointer to the specified matrix row. See the sample in \cvCppCross{Mat::isContinuous}() on how to use these methods.
2345 Return reference to the specified matrix element
2348 template<typename \_Tp> \_Tp\& Mat::at(int i, int j);\newline
2349 template<typename \_Tp> \_Tp\& Mat::at(Point pt);\newline
2350 template<typename \_Tp> const \_Tp\& Mat::at(int i, int j) const;\newline
2351 template<typename \_Tp> const \_Tp\& Mat::at(Point pt) const;
2354 \cvarg{i}{The 0-based row index}
2355 \cvarg{j}{The 0-based column index}
2356 \cvarg{pt}{The element position specified as \texttt{Point(j,i)}}
2359 The template methods return reference to the specified matrix element. For the sake of higher performance the index range checks are only performed in Debug configuration.
2361 Here is the how you can, for example, create one of the standard poor-conditioned test matrices for various numerical algorithms using the \texttt{Mat::at} method:
2364 Mat H(100, 100, CV_64F);
2365 for(int i = 0; i < H.rows; i++)
2366 for(int j = 0; j < H.cols; j++)
2367 H.at<double>(i,j)=1./(i+j+1);
2370 \cvCppFunc{Mat::begin}
2371 Return the matrix iterator, set to the first matrix element
2374 template<typename \_Tp> MatIterator\_<\_Tp> Mat::begin();
2375 template<typename \_Tp> MatConstIterator\_<\_Tp> Mat::begin() const;
2378 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:
2381 template<typename T>
2382 void alphaBlendRGBA(const Mat& src1, const Mat& src2, Mat& dst)
2384 typedef Vec<T, 4> VT;
2386 const float alpha_scale = (float)std::numeric_limits<T>::max(),
2387 inv_scale = 1.f/alpha_scale;
2389 CV_Assert( src1.type() == src2.type() &&
2390 src1.type() == DataType<VT>::type &&
2391 src1.size() == src2.size());
2392 Size size = src1.size();
2393 dst.create(size, src1.type());
2395 MatConstIterator_<VT> it1 = src1.begin<VT>(), it1_end = src1.end<VT>();
2396 MatConstIterator_<VT> it2 = src2.begin<VT>();
2397 MatIterator_<VT> dst_it = dst.begin<VT>();
2399 for( ; it1 != it1_end; ++it1, ++it2, ++dst_it )
2401 VT pix1 = *it1, pix2 = *it2;
2402 float alpha = pix1[3]*inv_scale, beta = pix2[3]*inv_scale;
2403 *dst_it = VT(saturate_cast<T>(pix1[0]*alpha + pix2[0]*beta),
2404 saturate_cast<T>(pix1[1]*alpha + pix2[1]*beta),
2405 saturate_cast<T>(pix1[2]*alpha + pix2[2]*beta),
2406 saturate_cast<T>((1 - (1-alpha)*(1-beta))*alpha_scale));
2412 \cvCppFunc{Mat::end}
2413 Return the matrix iterator, set to the after-last matrix element
2416 template<typename \_Tp> MatIterator\_<\_Tp> Mat::end();
2417 template<typename \_Tp> MatConstIterator\_<\_Tp> Mat::end() const;
2420 The methods return the matrix read-only or read-write iterators, set to the point following the last matrix element.
2423 \subsection{Mat\_}\label{MatT}
2424 Template matrix class derived from \cross{Mat}
2427 template<typename _Tp> class Mat_ : public Mat
2430 typedef _Tp value_type;
2431 typedef typename DataType<_Tp>::channel_type channel_type;
2432 typedef MatIterator_<_Tp> iterator;
2433 typedef MatConstIterator_<_Tp> const_iterator;
2436 // equivalent to Mat(_rows, _cols, DataType<_Tp>::type)
2437 Mat_(int _rows, int _cols);
2438 // other forms of the above constructor
2439 Mat_(int _rows, int _cols, const _Tp& value);
2440 explicit Mat_(Size _size);
2441 Mat_(Size _size, const _Tp& value);
2442 // copy/conversion contructor. If m is of different type, it's converted
2445 Mat_(const Mat_& m);
2446 // construct a matrix on top of user-allocated data.
2447 // step is in bytes(!!!), regardless of the type
2448 Mat_(int _rows, int _cols, _Tp* _data, size_t _step=AUTO_STEP);
2450 Mat_(const Mat_& m, const Range& rowRange, const Range& colRange);
2451 Mat_(const Mat_& m, const Rect& roi);
2452 // to support complex matrix expressions
2453 Mat_(const MatExpr_Base& expr);
2454 // makes a matrix out of Vec or std::vector. The matrix will have a single column
2455 template<int n> explicit Mat_(const Vec<_Tp, n>& vec);
2456 Mat_(const vector<_Tp>& vec, bool copyData=false);
2458 Mat_& operator = (const Mat& m);
2459 Mat_& operator = (const Mat_& m);
2460 // set all the elements to s.
2461 Mat_& operator = (const _Tp& s);
2463 // iterators; they are smart enough to skip gaps in the end of rows
2466 const_iterator begin() const;
2467 const_iterator end() const;
2469 // equivalent to Mat::create(_rows, _cols, DataType<_Tp>::type)
2470 void create(int _rows, int _cols);
2471 void create(Size _size);
2473 Mat_ cross(const Mat_& m) const;
2474 // to support complex matrix expressions
2475 Mat_& operator = (const MatExpr_Base& expr);
2476 // data type conversion
2477 template<typename T2> operator Mat_<T2>() const;
2478 // overridden forms of Mat::row() etc.
2479 Mat_ row(int y) const;
2480 Mat_ col(int x) const;
2481 Mat_ diag(int d=0) const;
2484 // transposition, inversion, per-element multiplication
2485 MatExpr_<...> t() const;
2486 MatExpr_<...> inv(int method=DECOMP_LU) const;
2488 MatExpr_<...> mul(const Mat_& m, double scale=1) const;
2489 MatExpr_<...> mul(const MatExpr_<...>& m, double scale=1) const;
2491 // overridden forms of Mat::elemSize() etc.
2492 size_t elemSize() const;
2493 size_t elemSize1() const;
2496 int channels() const;
2497 size_t step1() const;
2498 // returns step()/sizeof(_Tp)
2499 size_t stepT() const;
2501 // overridden forms of Mat::zeros() etc. Data type is omitted, of course
2502 static MatExpr_Initializer zeros(int rows, int cols);
2503 static MatExpr_Initializer zeros(Size size);
2504 static MatExpr_Initializer ones(int rows, int cols);
2505 static MatExpr_Initializer ones(Size size);
2506 static MatExpr_Initializer eye(int rows, int cols);
2507 static MatExpr_Initializer eye(Size size);
2509 // some more overriden methods
2510 Mat_ reshape(int _rows) const;
2511 Mat_& adjustROI( int dtop, int dbottom, int dleft, int dright );
2512 Mat_ operator()( const Range& rowRange, const Range& colRange ) const;
2513 Mat_ operator()( const Rect& roi ) const;
2515 // more convenient forms of row and element access operators
2516 _Tp* operator [](int y);
2517 const _Tp* operator [](int y) const;
2519 _Tp& operator ()(int row, int col);
2520 const _Tp& operator ()(int row, int col) const;
2521 _Tp& operator ()(Point pt);
2522 const _Tp& operator ()(Point pt) const;
2524 // to support matrix expressions
2525 operator MatExpr_<Mat_, Mat_>() const;
2527 // conversion to vector.
2528 operator vector<_Tp>() const;
2532 The class \texttt{Mat\_<\_Tp>} is a "thin" template wrapper on top of \texttt{Mat} class. It does not have any extra data fields, nor it or \texttt{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.:
2535 // create 100x100 8-bit matrix
2536 Mat M(100,100,CV_8U);
2537 // this will compile fine. no any data conversion will be done.
2538 Mat_<float>& M1 = (Mat_<float>&)M;
2539 // the program will likely crash at the statement below
2543 While \texttt{Mat} is sufficient in most cases, \texttt{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 \texttt{Mat::at<\_Tp>(int y, int x)} and \texttt{Mat\_<\_Tp>::operator ()(int y, int x)} do absolutely the same and run at the same speed, but the latter is certainly shorter:
2546 Mat_<double> M(20,20);
2547 for(int i = 0; i < M.rows; i++)
2548 for(int j = 0; j < M.cols; j++)
2549 M(i,j) = 1./(i+j+1);
2552 cout << E.at<double>(0,0)/E.at<double>(M.rows-1,0);
2555 \emph{How to use \texttt{Mat\_} for multi-channel images/matrices?}
2557 This is simple - just pass \texttt{Vec} as \texttt{Mat\_} parameter:
2559 // allocate 320x240 color image and fill it with green (in RGB space)
2560 Mat_<Vec3b> img(240, 320, Vec3b(0,255,0));
2561 // now draw a diagonal white line
2562 for(int i = 0; i < 100; i++)
2563 img(i,i)=Vec3b(255,255,255);
2564 // and now scramble the 2nd (red) channel of each pixel
2565 for(int i = 0; i < img.rows; i++)
2566 for(int j = 0; j < img.cols; j++)
2567 img(i,j)[2] ^= (uchar)(i ^ j);
2570 \subsection{MatND}\label{MatND}
2571 n-dimensional dense array
2577 // default constructor
2579 // constructs array with specific size and data type
2580 MatND(int _ndims, const int* _sizes, int _type);
2581 // constructs array and fills it with the specified value
2582 MatND(int _ndims, const int* _sizes, int _type, const Scalar& _s);
2583 // copy constructor. only the header is copied.
2584 MatND(const MatND& m);
2585 // sub-array selection. only the header is copied
2586 MatND(const MatND& m, const Range* ranges);
2587 // converts old-style nd array to MatND; optionally, copies the data
2588 MatND(const CvMatND* m, bool copyData=false);
2590 MatND& operator = (const MatND& m);
2592 // creates a complete copy of the matrix (all the data is copied)
2593 MatND clone() const;
2594 // sub-array selection; only the header is copied
2595 MatND operator()(const Range* ranges) const;
2597 // copies the data to another matrix.
2598 // Calls m.create(this->size(), this->type()) prior to
2600 void copyTo( MatND& m ) const;
2601 // copies only the selected elements to another matrix.
2602 void copyTo( MatND& m, const MatND& mask ) const;
2603 // converts data to the specified data type.
2604 // calls m.create(this->size(), rtype) prior to the conversion
2605 void convertTo( MatND& m, int rtype, double alpha=1, double beta=0 ) const;
2607 // assigns "s" to each array element.
2608 MatND& operator = (const Scalar& s);
2609 // assigns "s" to the selected elements of array
2610 // (or to all the elements if mask==MatND())
2611 MatND& setTo(const Scalar& s, const MatND& mask=MatND());
2612 // modifies geometry of array without copying the data
2613 MatND reshape(int _newcn, int _newndims=0, const int* _newsz=0) const;
2615 // allocates a new buffer for the data unless the current one already
2616 // has the specified size and type.
2617 void create(int _ndims, const int* _sizes, int _type);
2618 // manually increment reference counter (use with care !!!)
2620 // decrements the reference counter. Dealloctes the data when
2621 // the reference counter reaches zero.
2624 // converts the matrix to 2D Mat or to the old-style CvMatND.
2625 // In either case the data is not copied.
2626 operator Mat() const;
2627 operator CvMatND() const;
2628 // returns true if the array data is stored continuously
2629 bool isContinuous() const;
2630 // returns size of each element in bytes
2631 size_t elemSize() const;
2632 // returns size of each element channel in bytes
2633 size_t elemSize1() const;
2634 // returns OpenCV data type id (CV_8UC1, ... CV_64FC4,...)
2636 // returns depth (CV_8U ... CV_64F)
2638 // returns the number of channels
2639 int channels() const;
2640 // step1() ~ step()/elemSize1()
2641 size_t step1(int i) const;
2643 // return pointer to the element (versions for 1D, 2D, 3D and generic nD cases)
2645 const uchar* ptr(int i0) const;
2646 uchar* ptr(int i0, int i1);
2647 const uchar* ptr(int i0, int i1) const;
2648 uchar* ptr(int i0, int i1, int i2);
2649 const uchar* ptr(int i0, int i1, int i2) const;
2650 uchar* ptr(const int* idx);
2651 const uchar* ptr(const int* idx) const;
2653 // convenient template methods for element access.
2654 // note that _Tp must match the actual matrix type -
2655 // the functions do not do any on-fly type conversion
2656 template<typename _Tp> _Tp& at(int i0);
2657 template<typename _Tp> const _Tp& at(int i0) const;
2658 template<typename _Tp> _Tp& at(int i0, int i1);
2659 template<typename _Tp> const _Tp& at(int i0, int i1) const;
2660 template<typename _Tp> _Tp& at(int i0, int i1, int i2);
2661 template<typename _Tp> const _Tp& at(int i0, int i1, int i2) const;
2662 template<typename _Tp> _Tp& at(const int* idx);
2663 template<typename _Tp> const _Tp& at(const int* idx) const;
2665 enum { MAGIC_VAL=0x42FE0000, AUTO_STEP=-1,
2666 CONTINUOUS_FLAG=CV_MAT_CONT_FLAG, MAX_DIM=CV_MAX_DIM };
2668 // combines data type, continuity flag, signature (magic value)
2670 // the array dimensionality
2673 // data reference counter
2675 // pointer to the data
2677 // and its actual beginning and end
2681 // step and size for each dimension, MAX_DIM at max
2683 size_t step[MAX_DIM];
2687 The class \texttt{MatND} describes n-dimensional dense numerical single-channel or multi-channel array. This is a convenient representation for multi-dimensional histograms (when they are not very sparse, otherwise \texttt{SparseMat} will do better), voxel volumes, stacked motion fields etc. The data layout of matrix $M$ is defined by the array of \texttt{M.step[]}, so that the address of element $(i_0,...,i_{M.dims-1})$, where $0\leq i_k<M.size[k]$ is computed as:
2689 addr(M_{i_0,...,i_{M.dims-1}}) = M.data + M.step[0]*i_0 + M.step[1]*i_1 + ... + M.step[M.dims-1]*i_{M.dims-1}
2691 which is more general form of the respective formula for \cross{Mat}, wherein $\texttt{size[0]}\sim\texttt{rows}$,
2692 $\texttt{size[1]}\sim\texttt{cols}$, \texttt{step[0]} was simply called \texttt{step}, and \texttt{step[1]} was not stored at all but computed as \texttt{Mat::elemSize()}.
2694 In other aspects \texttt{MatND} is also very similar to \texttt{Mat}, with the following limitations and differences:
2696 \item much less operations are implemented for \texttt{MatND}
2697 \item currently, algebraic expressions with \texttt{MatND}'s are not supported
2698 \item the \texttt{MatND} iterator is completely different from \texttt{Mat} and \texttt{Mat\_} iterators. The latter are per-element iterators, while the former is per-slice iterator, see below.
2701 Here is how you can use \texttt{MatND} to compute NxNxN histogram of color 8bpp image (i.e. each channel value ranges from 0..255 and we quantize it to 0..N-1):
2704 void computeColorHist(const Mat& image, MatND& hist, int N)
2706 const int histSize[] = {N, N, N};
2708 // make sure that the histogram has proper size and type
2709 hist.create(3, histSize, CV_32F);
2714 // the loop below assumes that the image
2715 // is 8-bit 3-channel, so let's check it.
2716 CV_Assert(image.type() == CV_8UC3);
2717 MatConstIterator_<Vec3b> it = image.begin<Vec3b>(),
2718 it_end = image.end<Vec3b>();
2719 for( ; it != it_end; ++it )
2721 const Vec3b& pix = *it;
2723 // we could have incremented the cells by 1.f/(image.rows*image.cols)
2724 // instead of 1.f to make the histogram normalized.
2725 hist.at<float>(pix[0]*N/256, pix[1]*N/256, pix[2]*N/256) += 1.f;
2730 And here is how you can iterate through \texttt{MatND} elements:
2733 void normalizeColorHist(MatND& hist)
2736 // intialize iterator (the style is different from STL).
2737 // after initialization the iterator will contain
2738 // the number of slices or planes
2739 // the iterator will go through
2740 MatNDIterator it(hist);
2742 // iterate through the matrix. on each iteration
2743 // it.planes[*] (of type Mat) will be set to the current plane.
2744 for(int p = 0; p < it.nplanes; p++, ++it)
2745 s += sum(it.planes[0])[0];
2746 it = MatNDIterator(hist);
2748 for(int p = 0; p < it.nplanes; p++, ++it)
2751 // this is a shorter implementation of the above
2752 // using built-in operations on MatND
2753 double s = sum(hist)[0];
2754 hist.convertTo(hist, hist.type(), 1./s, 0);
2756 // and this is even shorter one
2757 // (assuming that the histogram elements are non-negative)
2758 normalize(hist, hist, 1, 0, NORM_L1);
2763 You can iterate though several matrices simultaneously as long as they have the same geometry (dimensionality and all the dimension sizes are the same), which is useful for binary and n-ary operations on such matrices. Just pass those matrices to \texttt{MatNDIterator}. Then, during the iteration \texttt{it.planes[0]}, \texttt{it.planes[1]}, ... will be the slices of the corresponding matrices.
2765 \subsection{MatND\_}
2766 Template class for n-dimensional dense array derived from \cross{MatND}.
2769 template<typename _Tp> class MatND_ : public MatND
2772 typedef _Tp value_type;
2773 typedef typename DataType<_Tp>::channel_type channel_type;
2775 // constructors, the same as in MatND, only the type is omitted
2777 MatND_(int dims, const int* _sizes);
2778 MatND_(int dims, const int* _sizes, const _Tp& _s);
2779 MatND_(const MatND& m);
2780 MatND_(const MatND_& m);
2781 MatND_(const MatND_& m, const Range* ranges);
2782 MatND_(const CvMatND* m, bool copyData=false);
2783 MatND_& operator = (const MatND& m);
2784 MatND_& operator = (const MatND_& m);
2785 // different initialization function
2786 // where we take _Tp instead of Scalar
2787 MatND_& operator = (const _Tp& s);
2789 // no special destructor is needed; use the one from MatND
2791 void create(int dims, const int* _sizes);
2792 template<typename T2> operator MatND_<T2>() const;
2793 MatND_ clone() const;
2794 MatND_ operator()(const Range* ranges) const;
2796 size_t elemSize() const;
2797 size_t elemSize1() const;
2800 int channels() const;
2801 // step[i]/elemSize()
2802 size_t stepT(int i) const;
2803 size_t step1(int i) const;
2805 // shorter alternatives for MatND::at<_Tp>.
2806 _Tp& operator ()(const int* idx);
2807 const _Tp& operator ()(const int* idx) const;
2808 _Tp& operator ()(int idx0);
2809 const _Tp& operator ()(int idx0) const;
2810 _Tp& operator ()(int idx0, int idx1);
2811 const _Tp& operator ()(int idx0, int idx1) const;
2812 _Tp& operator ()(int idx0, int idx1, int idx2);
2813 const _Tp& operator ()(int idx0, int idx1, int idx2) const;
2814 _Tp& operator ()(int idx0, int idx1, int idx2);
2815 const _Tp& operator ()(int idx0, int idx1, int idx2) const;
2819 \texttt{MatND\_} relates to \texttt{MatND} almost like \texttt{Mat\_} to \texttt{Mat} - it provides a bit more convenient element access operations and adds no extra members of virtual methods to the base class, thus references/pointers to \texttt{MatND\_} and \texttt{MatND} can be easily converted one to another, e.g.
2822 // alternative variant of the above histogram accumulation loop
2824 CV_Assert(hist.type() == CV_32FC1);
2825 MatND_<float>& _hist = (MatND_<float>&)hist;
2826 for( ; it != it_end; ++it )
2828 const Vec3b& pix = *it;
2829 _hist(pix[0]*N/256, pix[1]*N/256, pix[2]*N/256) += 1.f;
2834 \subsection{SparseMat}\label{SparseMat}
2835 Sparse n-dimensional array.
2841 typedef SparseMatIterator iterator;
2842 typedef SparseMatConstIterator const_iterator;
2844 // internal structure - sparse matrix header
2850 // sparse matrix node - element of a hash table
2855 int idx[CV_MAX_DIM];
2858 ////////// constructors and destructor //////////
2859 // default constructor
2861 // creates matrix of the specified size and type
2862 SparseMat(int dims, const int* _sizes, int _type);
2864 SparseMat(const SparseMat& m);
2865 // converts dense 2d matrix to the sparse form,
2866 // if try1d is true and matrix is a single-column matrix (Nx1),
2867 // then the sparse matrix will be 1-dimensional.
2868 SparseMat(const Mat& m, bool try1d=false);
2869 // converts dense n-d matrix to the sparse form
2870 SparseMat(const MatND& m);
2871 // converts old-style sparse matrix to the new-style.
2872 // all the data is copied, so that "m" can be safely
2873 // deleted after the conversion
2874 SparseMat(const CvSparseMat* m);
2878 ///////// assignment operations ///////////
2880 // this is O(1) operation; no data is copied
2881 SparseMat& operator = (const SparseMat& m);
2882 // (equivalent to the corresponding constructor with try1d=false)
2883 SparseMat& operator = (const Mat& m);
2884 SparseMat& operator = (const MatND& m);
2886 // creates full copy of the matrix
2887 SparseMat clone() const;
2889 // copy all the data to the destination matrix.
2890 // the destination will be reallocated if needed.
2891 void copyTo( SparseMat& m ) const;
2892 // converts 1D or 2D sparse matrix to dense 2D matrix.
2893 // If the sparse matrix is 1D, then the result will
2894 // be a single-column matrix.
2895 void copyTo( Mat& m ) const;
2896 // converts arbitrary sparse matrix to dense matrix.
2897 // watch out the memory!
2898 void copyTo( MatND& m ) const;
2899 // multiplies all the matrix elements by the specified scalar
2900 void convertTo( SparseMat& m, int rtype, double alpha=1 ) const;
2901 // converts sparse matrix to dense matrix with optional type conversion and scaling.
2902 // When rtype=-1, the destination element type will be the same
2903 // as the sparse matrix element type.
2904 // Otherwise rtype will specify the depth and
2905 // the number of channels will remain the same is in the sparse matrix
2906 void convertTo( Mat& m, int rtype, double alpha=1, double beta=0 ) const;
2907 void convertTo( MatND& m, int rtype, double alpha=1, double beta=0 ) const;
2910 void assignTo( SparseMat& m, int type=-1 ) const;
2912 // reallocates sparse matrix. If it was already of the proper size and type,
2913 // it is simply cleared with clear(), otherwise,
2914 // the old matrix is released (using release()) and the new one is allocated.
2915 void create(int dims, const int* _sizes, int _type);
2916 // sets all the matrix elements to 0, which means clearing the hash table.
2918 // manually increases reference counter to the header.
2920 // decreses the header reference counter, when it reaches 0,
2921 // the header and all the underlying data are deallocated.
2924 // converts sparse matrix to the old-style representation.
2925 // all the elements are copied.
2926 operator CvSparseMat*() const;
2927 // size of each element in bytes
2928 // (the matrix nodes will be bigger because of
2929 // element indices and other SparseMat::Node elements).
2930 size_t elemSize() const;
2931 // elemSize()/channels()
2932 size_t elemSize1() const;
2934 // the same is in Mat and MatND
2937 int channels() const;
2939 // returns the array of sizes and 0 if the matrix is not allocated
2940 const int* size() const;
2941 // returns i-th size (or 0)
2942 int size(int i) const;
2943 // returns the matrix dimensionality
2945 // returns the number of non-zero elements
2946 size_t nzcount() const;
2948 // compute element hash value from the element indices:
2950 size_t hash(int i0) const;
2952 size_t hash(int i0, int i1) const;
2954 size_t hash(int i0, int i1, int i2) const;
2956 size_t hash(const int* idx) const;
2958 // low-level element-acccess functions,
2959 // special variants for 1D, 2D, 3D cases and the generic one for n-D case.
2961 // return pointer to the matrix element.
2962 // if the element is there (it's non-zero), the pointer to it is returned
2963 // if it's not there and createMissing=false, NULL pointer is returned
2964 // if it's not there and createMissing=true, then the new element
2965 // is created and initialized with 0. Pointer to it is returned
2966 // If the optional hashval pointer is not NULL, the element hash value is
2967 // not computed, but *hashval is taken instead.
2968 uchar* ptr(int i0, bool createMissing, size_t* hashval=0);
2969 uchar* ptr(int i0, int i1, bool createMissing, size_t* hashval=0);
2970 uchar* ptr(int i0, int i1, int i2, bool createMissing, size_t* hashval=0);
2971 uchar* ptr(const int* idx, bool createMissing, size_t* hashval=0);
2973 // higher-level element access functions:
2974 // ref<_Tp>(i0,...[,hashval]) - equivalent to *(_Tp*)ptr(i0,...true[,hashval]).
2975 // always return valid reference to the element.
2976 // If it's did not exist, it is created.
2977 // find<_Tp>(i0,...[,hashval]) - equivalent to (_const Tp*)ptr(i0,...false[,hashval]).
2978 // return pointer to the element or NULL pointer if the element is not there.
2979 // value<_Tp>(i0,...[,hashval]) - equivalent to
2980 // { const _Tp* p = find<_Tp>(i0,...[,hashval]); return p ? *p : _Tp(); }
2981 // that is, 0 is returned when the element is not there.
2982 // note that _Tp must match the actual matrix type -
2983 // the functions do not do any on-fly type conversion
2986 template<typename _Tp> _Tp& ref(int i0, size_t* hashval=0);
2987 template<typename _Tp> _Tp value(int i0, size_t* hashval=0) const;
2988 template<typename _Tp> const _Tp* find(int i0, size_t* hashval=0) const;
2991 template<typename _Tp> _Tp& ref(int i0, int i1, size_t* hashval=0);
2992 template<typename _Tp> _Tp value(int i0, int i1, size_t* hashval=0) const;
2993 template<typename _Tp> const _Tp* find(int i0, int i1, size_t* hashval=0) const;
2996 template<typename _Tp> _Tp& ref(int i0, int i1, int i2, size_t* hashval=0);
2997 template<typename _Tp> _Tp value(int i0, int i1, int i2, size_t* hashval=0) const;
2998 template<typename _Tp> const _Tp* find(int i0, int i1, int i2, size_t* hashval=0) const;
3001 template<typename _Tp> _Tp& ref(const int* idx, size_t* hashval=0);
3002 template<typename _Tp> _Tp value(const int* idx, size_t* hashval=0) const;
3003 template<typename _Tp> const _Tp* find(const int* idx, size_t* hashval=0) const;
3005 // erase the specified matrix element.
3006 // When there is no such element, the methods do nothing
3007 void erase(int i0, int i1, size_t* hashval=0);
3008 void erase(int i0, int i1, int i2, size_t* hashval=0);
3009 void erase(const int* idx, size_t* hashval=0);
3011 // return the matrix iterators,
3012 // pointing to the first sparse matrix element,
3013 SparseMatIterator begin();
3014 SparseMatConstIterator begin() const;
3015 // ... or to the point after the last sparse matrix element
3016 SparseMatIterator end();
3017 SparseMatConstIterator end() const;
3019 // and the template forms of the above methods.
3020 // _Tp must match the actual matrix type.
3021 template<typename _Tp> SparseMatIterator_<_Tp> begin();
3022 template<typename _Tp> SparseMatConstIterator_<_Tp> begin() const;
3023 template<typename _Tp> SparseMatIterator_<_Tp> end();
3024 template<typename _Tp> SparseMatConstIterator_<_Tp> end() const;
3026 // return value stored in the sparse martix node
3027 template<typename _Tp> _Tp& value(Node* n);
3028 template<typename _Tp> const _Tp& value(const Node* n) const;
3030 ////////////// some internal-use methods ///////////////
3033 // pointer to the sparse matrix header
3038 The class \texttt{SparseMat} represents multi-dimensional sparse numerical arrays. Such a sparse array can store elements of any type that \cross{Mat} and \cross{MatND} 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 \texttt{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:
3041 \item query operations (\texttt{SparseMat::ptr} and the higher-level \texttt{SparseMat::ref}, \texttt{SparseMat::value} and \texttt{SparseMat::find}), e.g.:
3044 int size[] = {10, 10, 10, 10, 10};
3045 SparseMat sparse_mat(dims, size, CV_32F);
3046 for(int i = 0; i < 1000; i++)
3049 for(int k = 0; k < dims; k++)
3050 idx[k] = rand()%sparse_mat.size(k);
3051 sparse_mat.ref<float>(idx) += 1.f;
3054 \item sparse matrix iterators. Like \cross{Mat} iterators and unlike \cross{MatND} iterators, the sparse matrix iterators are STL-style, that is, the iteration loop is familiar to C++ users:
3056 // prints elements of a sparse floating-point matrix
3057 // and the sum of elements.
3058 SparseMatConstIterator_<float>
3059 it = sparse_mat.begin<float>(),
3060 it_end = sparse_mat.end<float>();
3062 int dims = sparse_mat.dims();
3063 for(; it != it_end; ++it)
3065 // print element indices and the element value
3066 const Node* n = it.node();
3068 for(int i = 0; i < dims; i++)
3069 printf("%3d%c", n->idx[i], i < dims-1 ? ',' : ')');
3070 printf(": %f\n", *it);
3073 printf("Element sum is %g\n", s);
3075 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.
3076 \item 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:
3078 double cross_corr(const SparseMat& a, const SparseMat& b)
3080 const SparseMat *_a = &a, *_b = &b;
3081 // if b contains less elements than a,
3082 // it's faster to iterate through b
3083 if(_a->nzcount() > _b->nzcount())
3085 SparseMatConstIterator_<float> it = _a->begin<float>(),
3086 it_end = _a->end<float>();
3088 for(; it != it_end; ++it)
3090 // take the next element from the first matrix
3092 const Node* anode = it.node();
3093 // and try to find element with the same index in the second matrix.
3094 // since the hash value depends only on the element index,
3095 // we reuse hashvalue stored in the node
3096 float bvalue = _b->value<float>(anode->idx,&anode->hashval);
3097 ccorr += avalue*bvalue;
3104 \subsection{SparseMat\_}
3105 Template sparse n-dimensional array class derived from \cross{SparseMat}
3108 template<typename _Tp> class SparseMat_ : public SparseMat
3111 typedef SparseMatIterator_<_Tp> iterator;
3112 typedef SparseMatConstIterator_<_Tp> const_iterator;
3115 // the created matrix will have data type = DataType<_Tp>::type
3117 SparseMat_(int dims, const int* _sizes);
3118 SparseMat_(const SparseMat& m);
3119 SparseMat_(const SparseMat_& m);
3120 SparseMat_(const Mat& m);
3121 SparseMat_(const MatND& m);
3122 SparseMat_(const CvSparseMat* m);
3123 // assignment operators; data type conversion is done when necessary
3124 SparseMat_& operator = (const SparseMat& m);
3125 SparseMat_& operator = (const SparseMat_& m);
3126 SparseMat_& operator = (const Mat& m);
3127 SparseMat_& operator = (const MatND& m);
3129 // equivalent to the correspoding parent class methods
3130 SparseMat_ clone() const;
3131 void create(int dims, const int* _sizes);
3132 operator CvSparseMat*() const;
3134 // overriden methods that do extra checks for the data type
3137 int channels() const;
3139 // more convenient element access operations.
3140 // ref() is retained (but <_Tp> specification is not need anymore);
3141 // operator () is equivalent to SparseMat::value<_Tp>
3142 _Tp& ref(int i0, size_t* hashval=0);
3143 _Tp operator()(int i0, size_t* hashval=0) const;
3144 _Tp& ref(int i0, int i1, size_t* hashval=0);
3145 _Tp operator()(int i0, int i1, size_t* hashval=0) const;
3146 _Tp& ref(int i0, int i1, int i2, size_t* hashval=0);
3147 _Tp operator()(int i0, int i1, int i2, size_t* hashval=0) const;
3148 _Tp& ref(const int* idx, size_t* hashval=0);
3149 _Tp operator()(const int* idx, size_t* hashval=0) const;
3152 SparseMatIterator_<_Tp> begin();
3153 SparseMatConstIterator_<_Tp> begin() const;
3154 SparseMatIterator_<_Tp> end();
3155 SparseMatConstIterator_<_Tp> end() const;
3159 \texttt{SparseMat\_} is a thin wrapper on top of \cross{SparseMat}, made in the same way as \texttt{Mat\_} and \texttt{MatND\_}.
3160 It simplifies notation of some operations, and that's it.
3162 int sz[] = {10, 20, 30};
3163 SparseMat_<double> M(3, sz);
3165 M.ref(1, 2, 3) = M(4, 5, 6) + M(7, 8, 9);