Update to 2.0.0 tree from current Fremantle build
[opencv] / doc / CxCore-cpp.tex
1 \chapter{C++ Interface}
2
3 \section{CXCORE. Basic Functionality}
4
5 \subsection{Introduction}
6
7 Starting from OpenCV 2.0 the new modern C++ interface has been introduced.
8 It is crisp (less typing is needed to code the same thing), type-safe (no more \texttt{CvArr*} a.k.a. \texttt{void*})
9 and, in general, more convenient to use. Here is a short example of what it looks like:
10
11 \begin{lstlisting}
12 //
13 // Simple retro-style photo effect done by adding noise to
14 // the luminance channel and reducing intensity of the chroma channels
15 //
16
17 // include standard OpenCV headers, same as before
18 #include "cv.h"
19 #include "highgui.h"
20
21 // all the new API is put into "cv" namespace. Export its content
22 using namespace cv;
23
24 // enable/disable use of mixed API in the code below.
25 #define DEMO_MIXED_API_USE 1
26
27 int main( int argc, char** argv )
28 {
29     const char* imagename = argc > 1 ? argv[1] : "lena.jpg";
30 #if DEMO_MIXED_API_USE
31     // Ptr<T> is safe ref-conting pointer class
32     Ptr<IplImage> iplimg = cvLoadImage(imagename);
33     
34     // cv::Mat replaces the CvMat and IplImage, but it's easy to convert
35     // between the old and the new data structures
36     // (by default, only the header is converted and the data is shared)
37     Mat img(iplimg); 
38 #else
39     // the newer cvLoadImage alternative with MATLAB-style name
40     Mat img = imread(imagename);
41 #endif
42
43     if( !img.data ) // check if the image has been loaded properly
44         return -1;
45
46     Mat img_yuv;
47     // convert image to YUV color space.
48     // The output image will be allocated automatically
49     cvtColor(img, img_yuv, CV_BGR2YCrCb); 
50
51     // split the image into separate color planes
52     vector<Mat> planes;
53     split(img_yuv, planes);
54
55     // another Mat constructor; allocates a matrix of the specified size and type
56     Mat noise(img.size(), CV_8U);
57     
58     // fills the matrix with normally distributed random values;
59     // there is also randu() for uniformly distributed random numbers. 
60     // Scalar replaces CvScalar, Scalar::all() replaces cvScalarAll().
61     randn(noise, Scalar::all(128), Scalar::all(20));
62                                                      
63     // blur the noise a bit, kernel size is 3x3 and both sigma's are set to 0.5
64     GaussianBlur(noise, noise, Size(3, 3), 0.5, 0.5);
65
66     const double brightness_gain = 0;
67     const double contrast_gain = 1.7;
68 #if DEMO_MIXED_API_USE
69     // it's easy to pass the new matrices to the functions that
70     // only work with IplImage or CvMat:
71     // step 1) - convert the headers, data will not be copied
72     IplImage cv_planes_0 = planes[0], cv_noise = noise;
73     // step 2) call the function; do not forget unary "&" to form pointers
74     cvAddWeighted(&cv_planes_0, contrast_gain, &cv_noise, 1,
75                  -128 + brightness_gain, &cv_planes_0);
76 #else
77     addWeighted(planes[0], constrast_gain, noise, 1,
78                 -128 + brightness_gain, planes[0]);
79 #endif
80     const double color_scale = 0.5;
81     // Mat::convertTo() replaces cvConvertScale.
82     // One must explicitly specify the output matrix type
83     // (we keep it intact, i.e. pass planes[1].type())
84     planes[1].convertTo(planes[1], planes[1].type(),
85                         color_scale, 128*(1-color_scale));
86
87     // alternative form of convertTo if we know the datatype
88     // at compile time ("uchar" here).
89     // This expression will not create any temporary arrays
90     // and should be almost as fast as the above variant
91     planes[2] = Mat_<uchar>(planes[2]*color_scale + 128*(1-color_scale));
92
93     // Mat::mul replaces cvMul(). Again, no temporary arrays are
94     // created in the case of simple expressions.
95     planes[0] = planes[0].mul(planes[0], 1./255);
96
97     // now merge the results back
98     merge(planes, img_yuv);
99     // and produce the output RGB image
100     cvtColor(img_yuv, img, CV_YCrCb2BGR);
101
102     // this is counterpart for cvNamedWindow
103     namedWindow("image with grain", CV_WINDOW_AUTOSIZE);
104 #if DEMO_MIXED_API_USE
105     // this is to demonstrate that img and iplimg really share the data -
106     // the result of the above processing is stored to img and thus in iplimg too.
107     cvShowImage("image with grain", iplimg);
108 #else
109     imshow("image with grain", img);
110 #endif
111     waitKey();
112
113     return 0;
114     // all the memory will automatically be released
115     // by vector<>, Mat and Ptr<> destructors.
116 }
117 \end{lstlisting}
118
119 In the rest of the introduction we discuss the key features of the new interface in more details.
120
121 \subsection{Namespace \texttt{cv} and Function Naming}
122
123 All the newly introduced classes and functions are placed into \texttt{cv} namespace. Therefore, to access this functionality from your code, use \texttt{cv::} specifier or \texttt{"using namespace cv;"} directive:
124 \begin{lstlisting}
125 #include "cv.h"
126
127 ...
128 cv::Mat H = cv::findHomography(points1, points2, cv::RANSAC, 5);
129 ...
130 \end{lstlisting}
131 or
132 \begin{lstlisting}
133 #include "cv.h"
134
135 using namespace cv;
136
137 ...
138 Mat H = findHomography(points1, points2, RANSAC, 5 );
139 ...
140 \end{lstlisting}
141
142 It is probable that some of the current or future OpenCV external names conflict with STL
143 or other libraries, in this case use explicit namespace specifiers to resolve the name conflicts:
144 \begin{lstlisting}
145 Mat a(100, 100, CV_32F);
146 randu(a, Scalar::all(1), Scalar::all(std::rand()%256+1));
147 cv::log(a, a);
148 a /= std::log(2.);
149 \end{lstlisting}
150
151 For the most of the C functions and structures from OpenCV 1.x you may find the direct counterparts in the new C++ interface. The name is usually formed by omitting \texttt{cv} or \texttt{Cv} prefix and turning the first letter to the low case (unless it's a own name, like Canny, Sobel etc). In case when there is no the new-style counterpart, it's possible to use the old functions with the new structures, as shown the first sample in the chapter.
152
153 \subsection{Memory Management}
154
155 When using the new interface, the most of memory deallocation and even memory allocation operations are done automatically when needed.
156
157 First of all, \cross{Mat}, \cross{SparseMat} and other classes have destructors
158 that deallocate memory buffers occupied by the structures when needed.
159
160 Secondly, this "when needed" means that the destructors do not always deallocate the buffers, they take into account possible data sharing.
161 That is, in a destructor the reference counter associated with the underlying data is decremented and the data is deallocated
162 if and only if the reference counter becomes zero, that is, when no other structures refer to the same buffer. When such a structure
163 containing a reference counter is copied, usually just the header is duplicated, while the underlying data is not; instead, the reference counter is incremented to memorize that there is another owner of the same data.
164 Also, some structures, such as \texttt{Mat}, can refer to the user-allocated data.
165 In this case the reference counter is \texttt{NULL} pointer and then no reference counting is done - the data is not deallocated by the destructors and should be deallocated manually by the user. We saw this scheme in the first example in the chapter:
166 \begin{lstlisting}
167 // allocates IplImages and wraps it into shared pointer class.
168 Ptr<IplImage> iplimg = cvLoadImage(...);
169
170 // constructs Mat header for IplImage data;
171 // does not copy the data;
172 // the reference counter will be NULL
173 Mat img(iplimg);
174 ...
175 // in the end of the block img destructor is called,
176 // which does not try to deallocate the data because
177 // of NULL pointer to the reference counter.
178 //
179 // Then Ptr<IplImage> destructor is called that decrements
180 // the reference counter and, as the counter becomes 0 in this case,
181 // the destructor calls cvReleaseImage().
182 \end{lstlisting}
183
184 The copying semantics was mentioned in the above paragraph, but deserves a dedicated discussion.
185 By default, the new OpenCV structures implement shallow, so called O(1) (i.e. constant-time) assignment operations. It gives user possibility to pass quite big data structures to functions (though, e.g. passing \texttt{const Mat\&} is still faster than passing \texttt{Mat}), return them (e.g. see the example with \cross{findHomography} above), store them in OpenCV and STL containers etc. - and do all of this very efficiently. On the other hand, most of the new data structures provide \texttt{clone()} method that creates a full copy of an object. Here is the sample:
186 \begin{lstlisting}
187 // create a big 8Mb matrix
188 Mat A(1000, 1000, CV_64F);
189
190 // create another header for the same matrix;
191 // this is instant operation, regardless of the matrix size.
192 Mat B = A;
193 // create another header for the 3-rd row of A; no data is copied either
194 Mat C = B.row(3);
195 // now create a separate copy of the matrix
196 Mat D = B.clone();
197 // copy the 5-th row of B to C, that is, copy the 5-th row of A to the 3-rd row of A.
198 B.row(5).copyTo(C);
199 // now let A and D share the data; after that the modified version
200 // of A is still referenced by B and C.
201 A = D;
202 // now make B an empty matrix (which references no memory buffers),
203 // but the modified version of A will still be referenced by C,
204 // despite that C is just a single row of the original A
205 B.release(); 
206              
207 // finally, make a full copy of C. In result, the big modified
208 // matrix will be deallocated, since it's not referenced by anyone
209 C = C.clone();
210 \end{lstlisting}
211
212 Memory management of the new data structures is automatic and thus easy. If, however, your code uses \cross{IplImage},
213 \cross{CvMat} or other C data structures a lot, memory management can still be automated without immediate migration
214 to \cross{Mat} by using the already mentioned template class \cross{Ptr}, similar to \texttt{shared\_ptr} from Boost and C++ TR1.
215 It wraps a pointer to an arbitrary object, provides transparent access to all the object fields and associates a reference counter with it.
216 Instance of the class can be passed to any function that expects the original pointer. For correct deallocation of the object, you should specialize \texttt{Ptr<T>::delete\_obj()} method. Such specialized methods already exist for the classical OpenCV structures, e.g.:
217 \begin{lstlisting}
218 // cxoperations.hpp:
219 ...
220 template<> inline Ptr<IplImage>::delete_obj() {
221     cvReleaseImage(&obj);
222 }
223 ...
224 \end{lstlisting}
225 See \cross{Ptr} description for more details and other usage scenarios.
226
227
228 \subsection{Memory Management Part II. Automatic Data Allocation}\label{AutomaticMemoryManagement2}
229
230 With the new interface not only explicit memory deallocation is not needed anymore,
231 but the memory allocation is often done automatically too. That was demonstrated in the example
232 in the beginning of the chapter when \texttt{cvtColor} was called, and here are some more details.
233
234 \cross{Mat} and other array classes provide method \texttt{create} that allocates a new buffer for array
235 data if and only if the currently allocated array is not of the required size and type.
236 If a new buffer is needed, the previously allocated buffer is released
237 (by engaging all the reference counting mechanism described in the previous section).
238 Now, since it is very quick to check whether the needed memory buffer is already allocated,
239 most new OpenCV functions that have arrays as output parameters call the \texttt{create} method and
240 this way the \emph{automatic data allocation} concept is implemented. Here is the example:
241 \begin{lstlisting}
242 #include "cv.h"
243 #include "highgui.h"
244
245 int main(int, char**)
246 {
247     VideoCapture cap(0);
248     if(!cap.isOpened()) return -1;
249
250     Mat edges;
251     namedWindow("edges",1);
252     for(;;)
253     {
254         Mat frame;
255         cap >> frame;
256         cvtColor(frame, edges, CV_BGR2GRAY);
257         GaussianBlur(edges, edges, Size(7,7), 1.5, 1.5);
258         Canny(edges, edges, 0, 30, 3);
259         imshow("edges", edges);
260         if(waitKey(30) >= 0) break;
261     }
262     return 0;
263 }
264 \end{lstlisting}
265 The matrix \texttt{edges} is allocated during the first frame processing and unless the resolution will suddenly change,
266 the same buffer will be reused for every next frame's edge map.
267
268 In many cases the output array type and size can be inferenced from the input arrays' respective characteristics, but not always.
269 In these rare cases the corresponding functions take separate input parameters that specify the data type and/or size of the output arrays,
270 like \cross{resize}. Anyway, a vast majority of the new-style array processing functions call \texttt{create}
271 for each of the output array, with just a few exceptions like \texttt{mixChannels}, \texttt{RNG::fill} and some others.
272
273 Note that this output array allocation semantic is only implemented in the new functions. If you want to pass the new structures to some old OpenCV function, you should first allocate the output arrays using \texttt{create} method, then make \texttt{CvMat} or \texttt{IplImage} headers and after that call the function.
274
275 \subsection{Algebraic Operations}
276
277 Just like in v1.x, OpenCV 2.x provides some basic functions operating on matrices, like \texttt{add},
278 \texttt{subtract}, \texttt{gemm} etc. In addition, it introduces overloaded operators that give the user a convenient
279 algebraic notation, which is nearly as fast as using the functions directly. For example, here is how the least squares problem $Ax=b$
280 can be solved using normal equations:
281 \begin{lstlisting}
282 Mat x = (A.t()*A).inv()*(A.t()*b);
283 \end{lstlisting}
284
285 The complete list of overloaded operators can be found in \cross{Matrix Expressions}.
286
287 \subsection{Fast Element Access}
288
289 Historically, OpenCV provided many different ways to access image and matrix elements, and none of them was both fast and convenient.
290 With the new data structures, OpenCV 2.x introduces a few more alternatives, hopefully more convenient than before. For detailed description of the operations, please, check \cross{Mat} and \hyperref[MatT]{Mat\_} description. Here is part of the retro-photo-styling example rewritten (in simplified form) using the element access operations:
291
292 \begin{lstlisting}
293 ...
294 // split the image into separate color planes
295 vector<Mat> planes;
296 split(img_yuv, planes);
297
298 // method 1. process Y plane using an iterator
299 MatIterator_<uchar> it = planes[0].begin<uchar>(),
300                     it_end = planes[0].end<uchar>();
301 for(; it != it_end; ++it)
302 {
303     double v = *it*1.7 + rand()%21-10;
304     *it = saturate_cast<uchar>(v*v/255.);
305 }
306
307 // method 2. process the first chroma plane using pre-stored row pointer.
308 // method 3. process the second chroma plane using
309              individual element access operations
310 for( int y = 0; y < img_yuv.rows; y++ )
311 {
312     uchar* Uptr = planes[1].ptr<uchar>(y);
313     for( int x = 0; x < img_yuv.cols; x++ )
314     {
315         Uptr[x] = saturate_cast<uchar>((Uptr[x]-128)/2 + 128);
316         uchar& Vxy = planes[2].at<uchar>(y, x);
317         Vxy = saturate_cast<uchar>((Vxy-128)/2 + 128);
318     }
319 }
320
321 merge(planes, img_yuv);
322 ...
323 \end{lstlisting}
324
325
326 \subsection{Saturation Arithmetics}
327
328 In the above sample you may have noticed \hyperref[saturatecast]{saturate\_cast} operator, and that's how all the pixel processing is done in OpenCV. When a result of image operation is 8-bit image with pixel values ranging from 0 to 255, each output pixel value is clipped to this available range:
329
330 \[
331 I(x,y)=\min(\max(value, 0), 255)
332 \]
333
334 and the similar rules are applied to 8-bit signed and 16-bit signed and unsigned types. This "saturation" semantics (different from usual C language "wrapping" semantics, where lowest bits are taken, is implemented in every image processing function, from the simple \texttt{cv::add} to \texttt{cv::cvtColor}, \texttt{cv::resize}, \texttt{cv::filter2D} etc.
335 It is not a new feature of OpenCV v2.x, it was there from very beginning. In the new version this special \hyperref[saturatecast]{saturate\_cast} template operator is introduced to simplify implementation of this semantic in your own functions.
336
337
338 \subsection{Error handling}
339
340 The modern error handling mechanism in OpenCV uses exceptions, as opposite to the manual stack unrolling used in previous versions. When OpenCV is built in DEBUG configuration, the error handler provokes memory access violation, so that the full call stack and context can be analyzed with debugger.
341
342 \subsection{Threading and Reenterability}
343
344 OpenCV uses OpenMP to run some time-consuming operations in parallel. Threading can be explicitly controlled by \cross{setNumThreads} function. Also, functions and "const" methods of the classes are generally re-enterable, that is, they can be called from different threads asynchronously.
345
346 \subsection{Basic Structures}
347
348 \cvfunc{DataType}\label{DataType}
349 Template "traits" class for other OpenCV primitive data types
350
351 \begin{lstlisting}
352 template<typename _Tp> class DataType
353 {
354     // value_type is always a synonym for _Tp.
355     typedef _Tp value_type;
356     
357     // intermediate type used for operations on _Tp.
358     // it is int for uchar, signed char, unsigned short, signed short and int,
359     // float for float, double for double, ...
360     typedef <...> work_type;
361     // in the case of multi-channel data it is the data type of each channel
362     typedef <...> channel_type;
363     enum
364     {
365         // CV_8U ... CV_64F
366         depth = DataDepth<channel_type>::value,
367         // 1 ... 
368         channels = <...>,
369         // '1u', '4i', '3f', '2d' etc.
370         fmt=<...>,
371         // CV_8UC3, CV_32FC2 ...
372         type = CV_MAKETYPE(depth, channels)
373     };
374 };
375 \end{lstlisting}
376
377 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 ($\sim$unsigned char), 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 \verb*"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.
378  
379 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:
380
381 \begin{lstlisting}
382 template<> class DataType<uchar>
383 {
384     typedef uchar value_type;
385     typedef int work_type;
386     typedef uchar channel_type;
387     enum { channel_type = CV_8U, channels = 1, fmt='u', type = CV_8U };
388 };
389 ...
390 template<typename _Tp> DataType<std::complex<_Tp> >
391 {
392     typedef std::complex<_Tp> value_type;
393     typedef std::complex<_Tp> work_type;
394     typedef _Tp channel_type;
395     // DataDepth is another helper trait class
396     enum { depth = DataDepth<_Tp>::value, channels=2,
397         fmt=(channels-1)*256+DataDepth<_Tp>::fmt,
398         type=CV_MAKETYPE(depth, channels) };
399 };
400 ...
401 \end{lstlisting}
402
403 The main purpose of the classes is to convert compile-time type information to OpenCV-compatible data type identifier, for example:
404
405 \begin{lstlisting}
406 // allocates 30x40 floating-point matrix
407 Mat A(30, 40, DataType<float>::type);
408
409 Mat B = Mat_<std::complex<double> >(3, 3);
410 // the statement below will print 6, 2 /* i.e. depth == CV_64F, channels == 2 */ 
411 cout << B.depth() << ", " << B.channels() << endl; 
412 \end{lstlisting}
413
414 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.
415
416 \cvfunc{Point\_}
417 Template class for 2D points
418
419 \begin{lstlisting}
420 template<typename _Tp> class Point_
421 {
422 public:
423     typedef _Tp value_type;
424     
425     Point_();
426     Point_(_Tp _x, _Tp _y);
427     Point_(const Point_& pt);
428     Point_(const CvPoint& pt);
429     Point_(const CvPoint2D32f& pt);
430     Point_(const Size_<_Tp>& sz);
431     Point_(const Vec<_Tp, 2>& v);
432     Point_& operator = (const Point_& pt);
433     template<typename _Tp2> operator Point_<_Tp2>() const;
434     operator CvPoint() const;
435     operator CvPoint2D32f() const;
436     operator Vec<_Tp, 2>() const;
437
438     // computes dot-product (this->x*pt.x + this->y*pt.y)
439     _Tp dot(const Point_& pt) const;
440     // computes dot-product using double-precision arithmetics
441     double ddot(const Point_& pt) const;
442     // returns true if the point is inside the rectangle "r".
443     bool inside(const Rect_<_Tp>& r) const;
444     
445     _Tp x, y;
446 };
447 \end{lstlisting}
448
449 The class represents a 2D point, specified by its coordinates $x$ and $y$.
450 Instance of the class is interchangeable with Ð¡ 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:
451
452 \begin{itemize}
453     \item \texttt{pt1 = pt2 $\pm$ pt3}
454     \item \texttt{pt1 = pt2 * $\alpha$, pt1 = $\alpha$ * pt2}
455     \item \texttt{pt1 += pt2, pt1 -= pt2, pt1 *= $\alpha$}
456     \item \texttt{double value = norm(pt); // $L_2$-norm}
457     \item \texttt{pt1 == pt2, pt1 != pt2}    
458 \end{itemize}
459
460 For user convenience, the following type aliases are defined:
461 \begin{lstlisting}
462 typedef Point_<int> Point2i;
463 typedef Point2i Point;
464 typedef Point_<float> Point2f;
465 typedef Point_<double> Point2d;
466 \end{lstlisting}
467
468 Here is a short example:
469 \begin{lstlisting}
470 Point2f a(0.3f, 0.f), b(0.f, 0.4f);
471 Point pt = (a + b)*10.f;
472 cout << pt.x << ", " << pt.y << endl; 
473 \end{lstlisting}
474
475 \cvfunc{Point3\_}
476
477 Template class for 3D points
478
479 \begin{lstlisting}
480
481 template<typename _Tp> class Point3_
482 {
483 public:
484     typedef _Tp value_type;
485     
486     Point3_();
487     Point3_(_Tp _x, _Tp _y, _Tp _z);
488     Point3_(const Point3_& pt);
489     explicit Point3_(const Point_<_Tp>& pt);
490     Point3_(const CvPoint3D32f& pt);
491     Point3_(const Vec<_Tp, 3>& v);
492     Point3_& operator = (const Point3_& pt);
493     template<typename _Tp2> operator Point3_<_Tp2>() const;
494     operator CvPoint3D32f() const;
495     operator Vec<_Tp, 3>() const;
496
497     _Tp dot(const Point3_& pt) const;
498     double ddot(const Point3_& pt) const;
499     
500     _Tp x, y, z;
501 };
502 \end{lstlisting}
503
504 The class represents a 3D point, specified by its coordinates $x$, $y$ and $z$.
505 Instance of the class is interchangeable with Ð¡ 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.
506
507 The following type aliases are available:
508
509 \begin{lstlisting}
510 typedef Point3_<int> Point3i;
511 typedef Point3_<float> Point3f;
512 typedef Point3_<double> Point3d;
513 \end{lstlisting}
514
515 \cvfunc{Size\_}
516
517 Template class for specfying image or rectangle size.
518
519 \begin{lstlisting}
520 template<typename _Tp> class Size_
521 {
522 public:
523     typedef _Tp value_type;
524     
525     Size_();
526     Size_(_Tp _width, _Tp _height);
527     Size_(const Size_& sz);
528     Size_(const CvSize& sz);
529     Size_(const CvSize2D32f& sz);
530     Size_(const Point_<_Tp>& pt);
531     Size_& operator = (const Size_& sz);
532     _Tp area() const;
533
534     operator Size_<int>() const;
535     operator Size_<float>() const;
536     operator Size_<double>() const;
537     operator CvSize() const;
538     operator CvSize2D32f() const;
539
540     _Tp width, height;
541 };
542 \end{lstlisting}
543
544 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. 
545
546 OpenCV defines the following type aliases:
547
548 \begin{lstlisting}
549 typedef Size_<int> Size2i;
550 typedef Size2i Size;
551 typedef Size_<float> Size2f;
552 \end{lstlisting}
553
554 \cvfunc{Rect\_}
555
556 Template class for 2D rectangles
557
558 \begin{lstlisting}
559 template<typename _Tp> class Rect_
560 {
561 public:
562     typedef _Tp value_type;
563     
564     Rect_();
565     Rect_(_Tp _x, _Tp _y, _Tp _width, _Tp _height);
566     Rect_(const Rect_& r);
567     Rect_(const CvRect& r);
568     // (x, y) <- org, (width, height) <- sz
569     Rect_(const Point_<_Tp>& org, const Size_<_Tp>& sz);
570     // (x, y) <- min(pt1, pt2), (width, height) <- max(pt1, pt2) - (x, y)
571     Rect_(const Point_<_Tp>& pt1, const Point_<_Tp>& pt2);
572     Rect_& operator = ( const Rect_& r );
573     // returns Point_<_Tp>(x, y)
574     Point_<_Tp> tl() const;
575     // returns Point_<_Tp>(x+width, y+height)
576     Point_<_Tp> br() const;
577     
578     // returns Size_<_Tp>(width, height)
579     Size_<_Tp> size() const;
580     // returns width*height
581     _Tp area() const;
582
583     operator Rect_<int>() const;
584     operator Rect_<float>() const;
585     operator Rect_<double>() const;
586     operator CvRect() const;
587
588     // x <= pt.x && pt.x < x + width &&
589     // y <= pt.y && pt.y < y + height ? true : false
590     bool contains(const Point_<_Tp>& pt) const;
591
592     _Tp x, y, width, height;
593 };
594 \end{lstlisting}
595
596 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.
597
598 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
599 \begin{eqnarray*}
600       x \leq pt.x < x+width,\\
601       y \leq pt.y < y+height
602 \end{eqnarray*}
603 And virtually every loop over an image \cross{ROI} in OpenCV (where ROI is specified by \texttt{Rect\_<int>}) is implemented as:
604 \begin{lstlisting}
605 for(int y = roi.y; y < roi.y + rect.height; y++)
606     for(int x = roi.x; x < roi.x + rect.width; x++)
607     {
608         // ...
609     }
610 \end{lstlisting}
611
612 In addition to the class members, the following operations on rectangles are implemented:
613 \begin{itemize}
614     \item \texttt{rect1 = rect1 $\pm$ point1} (shifting rectangle by a certain offset)
615     \item \texttt{rect1 = rect1 $\pm$ size1} (expanding or shrinking rectangle by a certain amount)
616     \item \texttt{rect1 += point1, rect1 -= point1, rect1 += size1, rect1 -= size1} (augmenting operations)
617     \item \texttt{rect1 = rect2 \& rect3} (rectangle intersection)
618     \item \texttt{rect1 = rect2 | rect3} (minimum area rectangle containing \texttt{rect2} and \texttt{rect3})
619     \item \texttt{rect1 \&= rect2, rect1 |= rect2} (and the corresponding augmenting operations)
620     \item \texttt{rect1 == rect2, rect1 != rect2} (rectangle comparison)
621 \end{itemize}
622
623 Example. Here is how the partial ordering on rectangles can be established (rect1 $\subseteq$ rect2):
624 \begin{lstlisting}
625 template<typename _Tp> inline bool
626 operator <= (const Rect_<_Tp>& r1, const Rect_<_Tp>& r2)
627 {
628     return (r1 & r2) == r1;
629 }
630 \end{lstlisting}
631
632 For user convenience, the following type alias is available:
633 \begin{lstlisting}
634 typedef Rect_<int> Rect;
635 \end{lstlisting}
636
637 \cvfunc{RotatedRect}\label{RotatedRect}
638 Possibly rotated rectangle
639
640 \begin{lstlisting}
641 class RotatedRect
642 {
643 public:
644     // constructors
645     RotatedRect();
646     RotatedRect(const Point2f& _center, const Size2f& _size, float _angle);
647     RotatedRect(const CvBox2D& box);
648     
649     // returns minimal up-right rectangle that contains the rotated rectangle
650     Rect boundingRect() const;
651     // backward conversion to CvBox2D
652     operator CvBox2D() const;
653     
654     // mass center of the rectangle
655     Point2f center;
656     // size
657     Size2f size;
658     // rotation angle in degrees
659     float angle;
660 };
661 \end{lstlisting}
662
663 The class \texttt{RotatedRect} replaces the old \cross{CvBox2D} and fully compatible with it.
664
665 \cvfunc{TermCriteria}\label{TermCriteria}
666
667 Termination criteria for iterative algorithms
668
669 \begin{lstlisting}
670 class TermCriteria
671 {
672 public:
673     enum { COUNT=1, MAX_ITER=COUNT, EPS=2 };
674
675     // constructors
676     TermCriteria();
677     // type can be MAX_ITER, EPS or MAX_ITER+EPS.
678     // type = MAX_ITER means that only the number of iterations does matter;
679     // type = EPS means that only the required precision (epsilon) does matter
680     //    (though, most algorithms put some limit on the number of iterations anyway)
681     // type = MAX_ITER + EPS means that algorithm stops when
682     // either the specified number of iterations is made,
683     // or when the specified accuracy is achieved - whatever happens first.
684     TermCriteria(int _type, int _maxCount, double _epsilon);
685     TermCriteria(const CvTermCriteria& criteria);
686     operator CvTermCriteria() const;
687
688     int type;
689     int maxCount;
690     double epsilon;
691 };
692 \end{lstlisting}
693
694 The class \texttt{TermCriteria} replaces the old \cross{CvTermCriteria} and fully compatible with it.
695
696
697 \cvfunc{Vec}\label{Vec}
698 Template class for short numerical vectors
699
700 \begin{lstlisting}
701 template<typename _Tp, int cn> class Vec
702 {
703 public:
704     typedef _Tp value_type;
705     enum { depth = DataDepth<_Tp>::value, channels = cn,
706            type = CV_MAKETYPE(depth, channels) };
707     
708     // default constructor: all elements are set to 0
709     Vec();
710     // constructors taking up to 10 first elements as parameters
711     Vec(_Tp v0);
712     Vec(_Tp v0, _Tp v1);
713     Vec(_Tp v0, _Tp v1, _Tp v2);
714     ...
715     Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4,
716         _Tp v5, _Tp v6, _Tp v7, _Tp v8, _Tp v9);
717     Vec(const Vec<_Tp, cn>& v);
718     // constructs vector with all the components set to alpha.
719     static Vec all(_Tp alpha);
720     
721     // two variants of dot-product
722     _Tp dot(const Vec& v) const;
723     double ddot(const Vec& v) const;
724     
725     // cross-product; valid only when cn == 3.
726     Vec cross(const Vec& v) const;
727     
728     // element type conversion
729     template<typename T2> operator Vec<T2, cn>() const;
730     
731     // conversion to/from CvScalar (valid only when cn==4)
732     operator CvScalar() const;
733     
734     // element access
735     _Tp operator [](int i) const;
736     _Tp& operator[](int i);
737
738     _Tp val[cn];
739 };
740 \end{lstlisting}
741
742 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:
743
744 \begin{itemize}
745     \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)
746     \item \texttt{v1 == v2, v1 != v2}
747     \item \texttt{double n = norm(v1); // $L_2$-norm}
748 \end{itemize}
749
750 For user convenience, the following type aliases are introduced:
751 \begin{lstlisting}
752 typedef Vec<uchar, 2> Vec2b;
753 typedef Vec<uchar, 3> Vec3b;
754 typedef Vec<uchar, 4> Vec4b;
755
756 typedef Vec<short, 2> Vec2s;
757 typedef Vec<short, 3> Vec3s;
758 typedef Vec<short, 4> Vec4s;
759
760 typedef Vec<int, 2> Vec2i;
761 typedef Vec<int, 3> Vec3i;
762 typedef Vec<int, 4> Vec4i;
763
764 typedef Vec<float, 2> Vec2f;
765 typedef Vec<float, 3> Vec3f;
766 typedef Vec<float, 4> Vec4f;
767 typedef Vec<float, 6> Vec6f;
768
769 typedef Vec<double, 2> Vec2d;
770 typedef Vec<double, 3> Vec3d;
771 typedef Vec<double, 4> Vec4d;
772 typedef Vec<double, 6> Vec6d;
773 \end{lstlisting}
774
775 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.
776
777 \cvfunc{Scalar\_}
778 4-element vector
779
780 \begin{lstlisting}
781 template<typename _Tp> class Scalar_ : public Vec<_Tp, 4>
782 {
783 public:
784     Scalar_();
785     Scalar_(_Tp v0, _Tp v1, _Tp v2=0, _Tp v3=0);
786     Scalar_(const CvScalar& s);
787     Scalar_(_Tp v0);
788     static Scalar_<_Tp> all(_Tp v0);
789     operator CvScalar() const;
790
791     template<typename T2> operator Scalar_<T2>() const;
792
793     Scalar_<_Tp> mul(const Scalar_<_Tp>& t, double scale=1 ) const;
794     template<typename T2> void convertTo(T2* buf, int channels, int unroll_to=0) const;
795 };
796
797 typedef Scalar_<double> Scalar;
798 \end{lstlisting}
799
800 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.
801
802 \cvfunc{Range}\label{Range}
803 Specifies a continuous subsequence (a.k.a. slice) of a sequence.
804
805 \begin{lstlisting}
806 class Range
807 {
808 public:
809     Range();
810     Range(int _start, int _end);
811     Range(const CvSlice& slice);
812     int size() const;
813     bool empty() const;
814     static Range all();
815     operator CvSlice() const;
816
817     int start, end;
818 };
819 \end{lstlisting}
820
821 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)$.
822
823 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:
824 \begin{lstlisting}
825 void my_function(..., const Range& r, ....)
826 {
827     if(r == Range::all()) {
828         // process all the data
829     }
830     else {
831         // process [r.start, r.end)
832     } 
833 }
834 \end{lstlisting}
835
836 \cvfunc{Ptr}\label{Ptr}
837
838 A template class for smart reference-counting pointers
839
840 \begin{lstlisting}
841 template<typename _Tp> class Ptr
842 {
843 public:
844     // default constructor
845     Ptr();
846     // constructor that wraps the object pointer
847     Ptr(_Tp* _obj);
848     // destructor: calls release()
849     ~Ptr();
850     // copy constructor; increments ptr's reference counter
851     Ptr(const Ptr& ptr);
852     // assignment operator; decrements own reference counter
853     // (with release()) and increments ptr's reference counter 
854     Ptr& operator = (const Ptr& ptr);
855     // increments reference counter
856     void addref();
857     // decrements reference counter; when it becomes 0,
858     // delete_obj() is called
859     void release();
860     // user-specified custom object deletion operation.
861     // by default, "delete obj;" is called
862     void delete_obj();
863     // returns true if obj == 0;
864     bool empty() const;
865
866     // provide access to the object fields and methods
867     _Tp* operator -> ();
868     const _Tp* operator -> () const;
869
870     // return the underlying object pointer;
871     // thanks to the methods, the Ptr<_Tp> can be
872     // used instead of _Tp*
873     operator _Tp* ();
874     operator const _Tp*() const;
875 protected:
876     // the incapsulated object pointer
877     _Tp* obj;
878     // the associated reference counter
879     int* refcount;
880 };
881 \end{lstlisting}
882
883 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
884 \href{http://en.wikipedia.org/wiki/C%2B%2B0x}{C++0x} standard. 
885
886 By using this class you can get the following capabilities:
887
888 \begin{itemize}
889     \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.
890     \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.
891     \item automatic destruction, even for C structures. See the example below with \texttt{FILE*}.  
892     \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.
893 \end{itemize}    
894
895 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;}.
896 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:
897
898 \begin{lstlisting}
899 template<> inline void Ptr<FILE>::delete_obj()
900 {
901     fclose(obj); // no need to clear the pointer afterwards,
902                  // it is done externally.
903 }
904 ...
905
906 // now use it:
907 Ptr<FILE> f(fopen("myfile.txt", "r"));
908 if(f.empty())
909     throw ...;
910 fprintf(f, ....);
911 ...
912 // the file will be closed automatically by the Ptr<FILE> destructor.
913 \end{lstlisting}  
914
915 \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.
916
917 \cvfunc{Mat}\label{Mat}
918
919 OpenCV C++ matrix class.
920
921 \begin{lstlisting}
922 class Mat
923 {
924 public:
925     // constructors
926     Mat();
927     // constructs matrix of the specified size and type
928     // (_type is CV_8UC1, CV_64FC3, CV_32SC(12) etc.)
929     Mat(int _rows, int _cols, int _type);
930     // constucts matrix and fills it with the specified value _s.
931     Mat(int _rows, int _cols, int _type, const Scalar& _s);
932     Mat(Size _size, int _type);
933     // copy constructor
934     Mat(const Mat& m);
935     // constructor for matrix headers pointing to user-allocated data
936     Mat(int _rows, int _cols, int _type, void* _data, size_t _step=AUTO_STEP);
937     Mat(Size _size, int _type, void* _data, size_t _step=AUTO_STEP);
938     // creates a matrix header for a part of the bigger matrix
939     Mat(const Mat& m, const Range& rowRange, const Range& colRange);
940     Mat(const Mat& m, const Rect& roi);
941     // converts old-style CvMat to the new matrix; the data is not copied by default
942     Mat(const CvMat* m, bool copyData=false);
943     // converts old-style IplImage to the new matrix; the data is not copied by default
944     Mat(const IplImage* img, bool copyData=false);
945     // builds matrix from std::vector with or without copying the data
946     template<typename _Tp> Mat(const vector<_Tp>& vec, bool copyData=false);
947     // helper constructor to compile matrix expressions
948     Mat(const MatExpr_Base& expr);
949     // destructor - calls release()
950     ~Mat();
951     // assignment operators
952     Mat& operator = (const Mat& m);
953     Mat& operator = (const MatExpr_Base& expr);
954
955     ...
956     // returns a new matrix header for the specified row
957     Mat row(int y) const;
958     // returns a new matrix header for the specified column
959     Mat col(int x) const;
960     // ... for the specified row span
961     Mat rowRange(int startrow, int endrow) const;
962     Mat rowRange(const Range& r) const;
963     // ... for the specified column span
964     Mat colRange(int startcol, int endcol) const;
965     Mat colRange(const Range& r) const;
966     // ... for the specified diagonal
967     // (d=0 - the main diagonal,
968     //  >0 - a diagonal from the lower half,
969     //  <0 - a diagonal from the upper half)
970     Mat diag(int d=0) const;
971     // constructs a square diagonal matrix which main diagonal is vector "d"
972     static Mat diag(const Mat& d);
973
974     // returns deep copy of the matrix, i.e. the data is copied
975     Mat clone() const;
976     // copies the matrix content to "m".
977     // It calls m.create(this->size(), this->type()).
978     void copyTo( Mat& m ) const;
979     // copies those matrix elements to "m" that are marked with non-zero mask elements.
980     void copyTo( Mat& m, const Mat& mask ) const;
981     // converts matrix to another datatype with optional scalng. See cvConvertScale.
982     void convertTo( Mat& m, int rtype, double alpha=1, double beta=0 ) const;
983
984     ...
985     // sets every matrix element to s
986     Mat& operator = (const Scalar& s);
987     // sets some of the matrix elements to s, according to the mask
988     Mat& setTo(const Scalar& s, const Mat& mask=Mat());
989     // creates alternative matrix header for the same data, with different
990     // number of channels and/or different number of rows. see cvReshape.
991     Mat reshape(int _cn, int _rows=0) const;
992
993     // matrix transposition by means of matrix expressions
994     MatExpr_<...> t() const;
995     // matrix inversion by means of matrix expressions
996     MatExpr_<...> inv(int method=DECOMP_LU) const;
997     // per-element matrix multiplication by means of matrix expressions
998     MatExpr_<...> mul(const Mat& m, double scale=1) const;
999     MatExpr_<...> mul(const MatExpr_<...>& m, double scale=1) const;
1000
1001     // computes cross-product of 2 3D vectors
1002     Mat cross(const Mat& m) const;
1003     // computes dot-product
1004     double dot(const Mat& m) const;
1005
1006     // Matlab-style matrix initialization. see the description
1007     static MatExpr_Initializer zeros(int rows, int cols, int type);
1008     static MatExpr_Initializer zeros(Size size, int type);
1009     static MatExpr_Initializer ones(int rows, int cols, int type);
1010     static MatExpr_Initializer ones(Size size, int type);
1011     static MatExpr_Initializer eye(int rows, int cols, int type);
1012     static MatExpr_Initializer eye(Size size, int type);
1013     
1014     // allocates new matrix data unless the matrix already has specified size and type.
1015     // previous data is unreferenced if needed.
1016     void create(int _rows, int _cols, int _type);
1017     void create(Size _size, int _type);
1018     // increases the reference counter; use with care to avoid memleaks
1019     void addref();
1020     // decreases reference counter;
1021     // deallocate the data when reference counter reaches 0.
1022     void release();
1023
1024     // locates matrix header within a parent matrix. See below
1025     void locateROI( Size& wholeSize, Point& ofs ) const;
1026     // moves/resizes the current matrix ROI inside the parent matrix.
1027     Mat& adjustROI( int dtop, int dbottom, int dleft, int dright );
1028     // extracts a rectangular sub-matrix
1029     // (this is a generalized form of row, rowRange etc.)
1030     Mat operator()( Range rowRange, Range colRange ) const;
1031     Mat operator()( const Rect& roi ) const;
1032
1033     // converts header to CvMat; no data is copied
1034     operator CvMat() const;
1035     // converts header to IplImage; no data is copied
1036     operator IplImage() const;
1037     
1038     // returns true iff the matrix data is continuous
1039     // (i.e. when there are no gaps between successive rows).
1040     // similar to CV_IS_MAT_CONT(cvmat->type)
1041     bool isContinuous() const;
1042     // returns element size in bytes,
1043     // similar to CV_ELEM_SIZE(cvmat->type)
1044     size_t elemSize() const;
1045     // returns the size of element channel in bytes.
1046     size_t elemSize1() const;
1047     // returns element type, similar to CV_MAT_TYPE(cvmat->type)
1048     int type() const;
1049     // returns element type, similar to CV_MAT_DEPTH(cvmat->type)
1050     int depth() const;
1051     // returns element type, similar to CV_MAT_CN(cvmat->type)
1052     int channels() const;
1053     // returns step/elemSize1()
1054     size_t step1() const;
1055     // returns matrix size:
1056     // width == number of columns, height == number of rows
1057     Size size() const;
1058     // returns true if matrix data is NULL
1059     bool empty() const;
1060
1061     // returns pointer to y-th row
1062     uchar* ptr(int y=0);
1063     const uchar* ptr(int y=0) const;
1064
1065     // template version of the above method
1066     template<typename _Tp> _Tp* ptr(int y=0);
1067     template<typename _Tp> const _Tp* ptr(int y=0) const;
1068     
1069     // template methods for read-write or read-only element access.
1070     // note that _Tp must match the actual matrix type -
1071     // the functions do not do any on-fly type conversion
1072     template<typename _Tp> _Tp& at(int y, int x);
1073     template<typename _Tp> _Tp& at(Point pt);
1074     template<typename _Tp> const _Tp& at(int y, int x) const;
1075     template<typename _Tp> const _Tp& at(Point pt) const;
1076     
1077     // template methods for iteration over matrix elements.
1078     // the iterators take care of skipping gaps in the end of rows (if any)
1079     template<typename _Tp> MatIterator_<_Tp> begin();
1080     template<typename _Tp> MatIterator_<_Tp> end();
1081     template<typename _Tp> MatConstIterator_<_Tp> begin() const;
1082     template<typename _Tp> MatConstIterator_<_Tp> end() const;
1083
1084     enum { MAGIC_VAL=0x42FF0000, AUTO_STEP=0, CONTINUOUS_FLAG=CV_MAT_CONT_FLAG };
1085
1086     // includes several bit-fields:
1087     //  * the magic signature
1088     //  * continuity flag
1089     //  * depth
1090     //  * number of channels
1091     int flags;
1092     // the number of rows and columns
1093     int rows, cols;
1094     // a distance between successive rows in bytes; includes the gap if any
1095     size_t step;
1096     // pointer to the data
1097     uchar* data;
1098
1099     // pointer to the reference counter;
1100     // when matrix points to user-allocated data, the pointer is NULL
1101     int* refcount;
1102     
1103     // helper fields used in locateROI and adjustROI
1104     uchar* datastart;
1105     uchar* dataend;
1106 };
1107 \end{lstlisting}
1108
1109 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}.
1110
1111 There are many different ways to create \texttt{Mat} object. Here are the some popular ones:
1112 \begin{itemize}
1113 \item using \texttt{create(nrows, ncols, type)} method or
1114     the similar constructor \texttt{Mat(nrows, ncols, type[, fill\_value])} constructor.
1115     A new matrix of the specified size and specifed type will be allocated.
1116     \texttt{type} has the same meaning as in \cross{cvCreateMat} method,
1117     e.g. \texttt{CV\_8UC1} means 8-bit single-channel matrix,
1118     \texttt{CV\_32FC2} means 2-channel (i.e. complex) floating-point matrix etc:
1119         
1120 \begin{lstlisting}
1121 // make 7x7 complex matrix filled with 1+3j.
1122 cv::Mat M(7,7,CV_32FC2,Scalar(1,3));
1123 // and now turn M to 100x60 15-channel 8-bit matrix.
1124 // The old content will be deallocated
1125 M.create(100,60,CV_8UC(15));
1126 \end{lstlisting}
1127         
1128     As noted in the introduction of this chapter, \texttt{create()}
1129     will only allocate a new matrix when the current matrix dimensionality
1130     or type are different from the specified.
1131         
1132 \item by using a copy constructor or assignment operator, where on the right side it can
1133       be a matrix or expression, see below. Again, as noted in the introduction,
1134       matrix assignment is O(1) operation because it only copies the header
1135       and increases the reference counter. \texttt{Mat::clone()} method can be used to get a full
1136       (a.k.a. deep) copy of the matrix when you need it.
1137           
1138 \item by constructing a header for a part of another matrix. It can be a single row, single column,
1139       several rows, several columns, rectangular region in the matrix (called a minor in algebra) or
1140       a diagonal. Such operations are also O(1), because the new header will reference the same data.
1141       You can actually modify a part of the matrix using this feature, e.g.
1142           
1143 \begin{lstlisting}
1144 // add 5-th row, multiplied by 3 to the 3rd row
1145 M.row(3) = M.row(3) + M.row(5)*3;
1146
1147 // now copy 7-th column to the 1-st column
1148 // M.col(1) = M.col(7); // this will not work
1149 Mat M1 = M.col(1);
1150 M.col(7).copyTo(M1);
1151
1152 // create new 320x240 image
1153 cv::Mat img(Size(320,240),CV_8UC3);
1154 // select a roi
1155 cv::Mat roi(img, Rect(10,10,100,100));
1156 // fill the ROI with (0,255,0) (which is green in RGB space);
1157 // the original 320x240 image will be modified
1158 roi = Scalar(0,255,0);
1159 \end{lstlisting}
1160
1161       Thanks to the additional \texttt{datastart} and \texttt{dataend} members, it is possible to
1162       compute the relative sub-matrix position in the main \emph{"container"} matrix using \texttt{locateROI()}:
1163       
1164 \begin{lstlisting}
1165 Mat A = Mat::eye(10, 10, CV_32S);
1166 // extracts A columns, 1 (inclusive) to 3 (exclusive).
1167 Mat B = A(Range::all(), Range(1, 3));
1168 // extracts B rows, 5 (inclusive) to 9 (exclusive).
1169 // that is, C ~ A(Range(5, 9), Range(1, 3))
1170 Mat C = B(Range(5, 9), Range::all());
1171 Size size; Point ofs;
1172 C.locateROI(size, ofs);
1173 // size will be (width=10,height=10) and the ofs will be (x=1, y=5)
1174 \end{lstlisting}
1175           
1176       As in the case of whole matrices, if you need a deep copy, use \texttt{clone()} method
1177       of the extracted sub-matrices.
1178           
1179 \item by making a header for user-allocated-data. It can be useful for
1180     \begin{enumerate}
1181         \item processing "foreign" data using OpenCV (e.g. when you implement
1182         a DirectShow filter or a processing module for gstreamer etc.), e.g.
1183             
1184 \begin{lstlisting}
1185 void process_video_frame(const unsigned char* pixels,
1186                          int width, int height, int step)
1187 {
1188     cv::Mat img(height, width, CV_8UC3, pixels, step);
1189     cv::GaussianBlur(img, img, cv::Size(7,7), 1.5, 1.5);
1190 }
1191 \end{lstlisting}
1192             
1193         \item for quick initialization of small matrices and/or super-fast element access
1194 \begin{lstlisting}
1195 double m[3][3] = {{a, b, c}, {d, e, f}, {g, h, i}};
1196 cv::Mat M = cv::Mat(3, 3, CV_64F, m).inv();
1197 \end{lstlisting}
1198         \end{enumerate}
1199         
1200         partial yet very common cases of this "user-allocated data" case are conversions
1201         from \cross{CvMat} and \cross{IplImage} to \texttt{Mat}. For this purpose there are special constructors
1202         taking pointers to \texttt{CvMat} or \texttt{IplImage} and the optional
1203         flag indicating whether to copy the data or not.
1204         
1205         Backward conversion from \texttt{Mat} to \texttt{CvMat} or \texttt{IplImage} is provided via cast operators
1206         \texttt{Mat::operator CvMat() const} an \texttt{Mat::operator IplImage()}.
1207         The operators do \emph{not} copy the data.
1208         
1209 \begin{lstlisting}
1210 IplImage* img = cvLoadImage("greatwave.jpg", 1);
1211 Mat mtx(img); // convert IplImage* -> cv::Mat
1212 CvMat oldmat = mtx; // convert cv::Mat -> CvMat
1213 CV_Assert(oldmat.cols == img->width && oldmat.rows == img->height &&
1214     oldmat.data.ptr == (uchar*)img->imageData && oldmat.step == img->widthStep);
1215 \end{lstlisting}
1216         
1217 \item by using MATLAB-style matrix initializers, \texttt{zeros(), ones(), eye()}, e.g.:
1218
1219 \begin{lstlisting}
1220 // create a double-precision identity martix and add it to M.
1221 M += Mat::eye(M.rows, M.cols, CV_64F);
1222 \end{lstlisting}
1223
1224 \item by using comma-separated initializer:
1225 \begin{lstlisting}
1226 // create 3x3 double-precision identity matrix
1227 Mat M = (Mat_<double>(3,3) << 1, 0, 0, 0, 1, 0, 0, 0, 1);
1228 \end{lstlisting}
1229
1230 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.
1231         
1232 \end{itemize}
1233
1234 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).
1235 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()}.
1236
1237 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.
1238 %\includegraphics[width=1.0\textwidth]{pics/roi.png}
1239
1240 Given these parameters, address of the matrix element $M_{ij}$ is computed as following:
1241
1242
1243 \texttt{addr($M_{ij}$)=M.data + M.step*i + j*M.elemSize()}
1244
1245
1246 if you know the matrix element type, e.g. it is \texttt{float}, then you can use \texttt{at<>()} method:
1247
1248
1249 \texttt{addr($M_{ij}$)=\&M.at<float>(i,j)}
1250
1251 (where \& is used to convert the reference returned by \texttt{at} to a pointer).
1252 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{[]}:
1253
1254 \begin{lstlisting}
1255 // compute sum of positive matrix elements
1256 // (assuming that M is double-precision matrix)
1257 double sum=0;
1258 for(int i = 0; i < M.rows; i++)
1259 {
1260     const double* Mi = M.ptr<double>(i);
1261     for(int j = 0; j < M.cols; j++)
1262         sum += std::max(Mi[j], 0.);
1263 }
1264 \end{lstlisting}
1265
1266 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:
1267
1268 \begin{lstlisting}
1269 // compute sum of positive matrix elements, optimized variant
1270 double sum=0;
1271 int cols = M.cols, rows = M.rows;
1272 if(M.isContinuous())
1273 {
1274     cols *= rows;
1275     rows = 1;
1276 }
1277 for(int i = 0; i < rows; i++)
1278 {
1279     const double* Mi = M.ptr<double>(i);
1280     for(int j = 0; j < cols; j++)
1281         sum += std::max(Mi[j], 0.);
1282 }
1283 \end{lstlisting}
1284 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.
1285
1286 Finally, there are STL-style iterators that are smart enough to skip gaps between successive rows:
1287 \begin{lstlisting}
1288 // compute sum of positive matrix elements, iterator-based variant
1289 double sum=0;
1290 MatConstIterator_<double> it = M.begin<double>(), it_end = M.end<double>();
1291 for(; it != it_end; ++it)
1292     sum += std::max(*it, 0.);
1293 \end{lstlisting}
1294
1295 The matrix iterators are random-access iterators, so they can be passed to any STL algorithm, including \texttt{std::sort()}.
1296
1297 \cvfunc{Matrix Expressions}\label{Matrix Expressions}
1298
1299 This is a list of implemented matrix operations that can be combined in arbitrary complex expressions
1300 (here \emph{A}, \emph{B} stand for matrices (\texttt{Mat}), \emph{s} for a scalar (\texttt{Scalar}),
1301 \emph{$\alpha$} for a real-valued scalar (\texttt{double})):
1302
1303 \begin{itemize}
1304     \item addition, subtraction, negation: \texttt{A$\pm$B, A$\pm$s, s$\pm$A, -A}
1305     \item scaling: \texttt{A*$\alpha$, A/$\alpha$}
1306     \item per-element multiplication and division: \texttt{A.mul(B), A/B, $\alpha$/A}
1307     \item matrix multiplication: \texttt{A*B}
1308     \item transposition: \texttt{A.t() $\sim A^t$}
1309     \item matrix inversion and pseudo-inversion, solving linear systems and least-squares problems:
1310         \texttt{A.inv([method]) $\sim A^{-1}$}, \texttt{A.inv([method])*B $\sim X:\,AX=B$}
1311     \item comparison: \texttt{A$\gtreqqless$ B, A $\ne$ B, A$\gtreqqless \alpha$, A $\ne \alpha$}.
1312           The result of comparison is 8-bit single channel mask, which elements are set to 255
1313           (if the particular element or pair of elements satisfy the condition) and 0 otherwise.
1314     \item bitwise logical operations: \verb"A & B, A & s, A | B, A | s, A ^ B, A ^ s, ~A"
1315     \item element-wise minimum and maximum: \texttt{min(A, B), min(A, $\alpha$), max(A, B), max(A, $\alpha$)}
1316     \item element-wise absolute value: \texttt{abs(A)}
1317     \item cross-product, dot-product: \texttt{A.cross(B), A.dot(B)}
1318     \item any function of matrix or matrices and scalars that returns a matrix or a scalar, such as
1319           \cross{norm}, \cross{mean}, \cross{sum}, \cross{countNonZero}, \cross{trace},
1320           \cross{determinant}, \cross{repeat} etc.
1321     \item matrix initializers (\texttt{eye(), zeros(), ones()}), matrix comma-separated initializers,
1322           matrix constructors and operators that extract sub-matrices (see \cross{Mat} description).
1323     \item \verb"Mat_<destination_type>()" constructors to cast the result to the proper type.
1324 \end{itemize}
1325 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.
1326
1327 \cvfunc{Mat\_}\label{MatT}
1328 Template matrix class derived from \cross{Mat}
1329
1330 \begin{lstlisting}
1331 template<typename _Tp> class Mat_ : public Mat
1332 {
1333 public:
1334     typedef _Tp value_type;
1335     typedef typename DataType<_Tp>::channel_type channel_type;
1336     typedef MatIterator_<_Tp> iterator;
1337     typedef MatConstIterator_<_Tp> const_iterator;
1338
1339     Mat_();
1340     // equivalent to Mat(_rows, _cols, DataType<_Tp>::type)
1341     Mat_(int _rows, int _cols);
1342     // other forms of the above constructor
1343     Mat_(int _rows, int _cols, const _Tp& value);
1344     explicit Mat_(Size _size);
1345     Mat_(Size _size, const _Tp& value);
1346     // copy/conversion contructor. If m is of different type, it's converted
1347     Mat_(const Mat& m);
1348     // copy constructor
1349     Mat_(const Mat_& m);
1350     // construct a matrix on top of user-allocated data.
1351     // step is in bytes(!!!), regardless of the type
1352     Mat_(int _rows, int _cols, _Tp* _data, size_t _step=AUTO_STEP);
1353     // minor selection
1354     Mat_(const Mat_& m, const Range& rowRange, const Range& colRange);
1355     Mat_(const Mat_& m, const Rect& roi);
1356     // to support complex matrix expressions
1357     Mat_(const MatExpr_Base& expr);
1358     // makes a matrix out of Vec or std::vector. The matrix will have a single column
1359     template<int n> explicit Mat_(const Vec<_Tp, n>& vec);
1360     Mat_(const vector<_Tp>& vec, bool copyData=false);
1361
1362     Mat_& operator = (const Mat& m);
1363     Mat_& operator = (const Mat_& m);
1364     // set all the elements to s.
1365     Mat_& operator = (const _Tp& s);
1366
1367     // iterators; they are smart enough to skip gaps in the end of rows
1368     iterator begin();
1369     iterator end();
1370     const_iterator begin() const;
1371     const_iterator end() const;
1372
1373     // equivalent to Mat::create(_rows, _cols, DataType<_Tp>::type)
1374     void create(int _rows, int _cols);
1375     void create(Size _size);
1376     // cross-product
1377     Mat_ cross(const Mat_& m) const;
1378     // to support complex matrix expressions
1379     Mat_& operator = (const MatExpr_Base& expr);
1380     // data type conversion
1381     template<typename T2> operator Mat_<T2>() const;
1382     // overridden forms of Mat::row() etc.
1383     Mat_ row(int y) const;
1384     Mat_ col(int x) const;
1385     Mat_ diag(int d=0) const;
1386     Mat_ clone() const;
1387
1388     // transposition, inversion, per-element multiplication
1389     MatExpr_<...> t() const;
1390     MatExpr_<...> inv(int method=DECOMP_LU) const;
1391
1392     MatExpr_<...> mul(const Mat_& m, double scale=1) const;
1393     MatExpr_<...> mul(const MatExpr_<...>& m, double scale=1) const;
1394
1395     // overridden forms of Mat::elemSize() etc.
1396     size_t elemSize() const;
1397     size_t elemSize1() const;
1398     int type() const;
1399     int depth() const;
1400     int channels() const;
1401     size_t step1() const;
1402     // returns step()/sizeof(_Tp)
1403     size_t stepT() const;
1404
1405     // overridden forms of Mat::zeros() etc. Data type is omitted, of course
1406     static MatExpr_Initializer zeros(int rows, int cols);
1407     static MatExpr_Initializer zeros(Size size);
1408     static MatExpr_Initializer ones(int rows, int cols);
1409     static MatExpr_Initializer ones(Size size);
1410     static MatExpr_Initializer eye(int rows, int cols);
1411     static MatExpr_Initializer eye(Size size);
1412
1413     // some more overriden methods
1414     Mat_ reshape(int _rows) const;
1415     Mat_& adjustROI( int dtop, int dbottom, int dleft, int dright );
1416     Mat_ operator()( const Range& rowRange, const Range& colRange ) const;
1417     Mat_ operator()( const Rect& roi ) const;
1418
1419     // more convenient forms of row and element access operators 
1420     _Tp* operator [](int y);
1421     const _Tp* operator [](int y) const;
1422
1423     _Tp& operator ()(int row, int col);
1424     const _Tp& operator ()(int row, int col) const;
1425     _Tp& operator ()(Point pt);
1426     const _Tp& operator ()(Point pt) const;
1427
1428     // to support matrix expressions
1429     operator MatExpr_<Mat_, Mat_>() const;
1430     
1431     // conversion to vector.
1432     operator vector<_Tp>() const;
1433 };
1434 \end{lstlisting}
1435
1436 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.:
1437
1438 \begin{lstlisting}
1439 // create 100x100 8-bit matrix
1440 Mat M(100,100,CV_8U);
1441 // this will compile fine. no any data conversion will be done.
1442 Mat_<float>& M1 = (Mat_<float>&)M;
1443 // the program will likely crash at the statement below
1444 M1(99,99) = 1.f;
1445 \end{lstlisting}
1446
1447 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:
1448
1449 \begin{lstlisting}
1450 Mat_<double> M(20,20);
1451 for(int i = 0; i < M.rows; i++)
1452     for(int j = 0; j < M.cols; j++)
1453         M(i,j) = 1./(i+j+1);
1454 Mat E, V;
1455 eigen(M,E,V);
1456 cout << E.at<double>(0,0)/E.at<double>(M.rows-1,0);
1457 \end{lstlisting}
1458
1459 \emph{How to use \texttt{Mat\_} for multi-channel images/matrices?}
1460
1461 This is simple - just pass \texttt{Vec} as \texttt{Mat\_} parameter:
1462 \begin{lstlisting}
1463 // allocate 320x240 color image and fill it with green (in RGB space)
1464 Mat_<Vec3b> img(240, 320, Vec3b(0,255,0));
1465 // now draw a diagonal white line
1466 for(int i = 0; i < 100; i++)
1467     img(i,i)=Vec3b(255,255,255);
1468 // and now scramble the 2nd (red) channel of each pixel
1469 for(int i = 0; i < img.rows; i++)
1470     for(int j = 0; j < img.cols; j++)
1471         img(i,j)[2] ^= (uchar)(i ^ j);
1472 \end{lstlisting}
1473
1474 \cvfunc{MatND}\label{MatND}
1475 n-dimensional dense array
1476
1477 \begin{lstlisting}
1478 class MatND
1479 {
1480 public:
1481     // default constructor
1482     MatND();
1483     // constructs array with specific size and data type
1484     MatND(int _ndims, const int* _sizes, int _type);
1485     // constructs array and fills it with the specified value
1486     MatND(int _ndims, const int* _sizes, int _type, const Scalar& _s);
1487     // copy constructor. only the header is copied.
1488     MatND(const MatND& m);
1489     // sub-array selection. only the header is copied
1490     MatND(const MatND& m, const Range* ranges);
1491     // converts old-style nd array to MatND; optionally, copies the data
1492     MatND(const CvMatND* m, bool copyData=false);
1493     ~MatND();
1494     MatND& operator = (const MatND& m);
1495
1496     // creates a complete copy of the matrix (all the data is copied)
1497     MatND clone() const;
1498     // sub-array selection; only the header is copied
1499     MatND operator()(const Range* ranges) const;
1500
1501     // copies the data to another matrix.
1502     // Calls m.create(this->size(), this->type()) prior to
1503     // copying the data
1504     void copyTo( MatND& m ) const;
1505     // copies only the selected elements to another matrix.
1506     void copyTo( MatND& m, const MatND& mask ) const;
1507     // converts data to the specified data type.
1508     // calls m.create(this->size(), rtype) prior to the conversion
1509     void convertTo( MatND& m, int rtype, double alpha=1, double beta=0 ) const;
1510
1511     // assigns "s" to each array element. 
1512     MatND& operator = (const Scalar& s);
1513     // assigns "s" to the selected elements of array
1514     // (or to all the elements if mask==MatND())
1515     MatND& setTo(const Scalar& s, const MatND& mask=MatND());
1516     // modifies geometry of array without copying the data
1517     MatND reshape(int _newcn, int _newndims=0, const int* _newsz=0) const;
1518
1519     // allocates a new buffer for the data unless the current one already
1520     // has the specified size and type.
1521     void create(int _ndims, const int* _sizes, int _type);
1522     // manually increment reference counter (use with care !!!)
1523     void addref();
1524     // decrements the reference counter. Dealloctes the data when
1525     // the reference counter reaches zero.
1526     void release();
1527
1528     // converts the matrix to 2D Mat or to the old-style CvMatND.
1529     // In either case the data is not copied.
1530     operator Mat() const;
1531     operator CvMatND() const;
1532     // returns true if the array data is stored continuously 
1533     bool isContinuous() const;
1534     // returns size of each element in bytes
1535     size_t elemSize() const;
1536     // returns size of each element channel in bytes
1537     size_t elemSize1() const;
1538     // returns OpenCV data type id (CV_8UC1, ... CV_64FC4,...)
1539     int type() const;
1540     // returns depth (CV_8U ... CV_64F)
1541     int depth() const;
1542     // returns the number of channels
1543     int channels() const;
1544     // step1() ~ step()/elemSize1()
1545     size_t step1(int i) const;
1546
1547     // return pointer to the element (versions for 1D, 2D, 3D and generic nD cases)
1548     uchar* ptr(int i0);
1549     const uchar* ptr(int i0) const;
1550     uchar* ptr(int i0, int i1);
1551     const uchar* ptr(int i0, int i1) const;
1552     uchar* ptr(int i0, int i1, int i2);
1553     const uchar* ptr(int i0, int i1, int i2) const;
1554     uchar* ptr(const int* idx);
1555     const uchar* ptr(const int* idx) const;
1556
1557     // convenient template methods for element access.
1558     // note that _Tp must match the actual matrix type -
1559     // the functions do not do any on-fly type conversion
1560     template<typename _Tp> _Tp& at(int i0);
1561     template<typename _Tp> const _Tp& at(int i0) const;
1562     template<typename _Tp> _Tp& at(int i0, int i1);
1563     template<typename _Tp> const _Tp& at(int i0, int i1) const;
1564     template<typename _Tp> _Tp& at(int i0, int i1, int i2);
1565     template<typename _Tp> const _Tp& at(int i0, int i1, int i2) const;
1566     template<typename _Tp> _Tp& at(const int* idx);
1567     template<typename _Tp> const _Tp& at(const int* idx) const;
1568
1569     enum { MAGIC_VAL=0x42FE0000, AUTO_STEP=-1,
1570         CONTINUOUS_FLAG=CV_MAT_CONT_FLAG, MAX_DIM=CV_MAX_DIM };
1571
1572     // combines data type, continuity flag, signature (magic value) 
1573     int flags;
1574     // the array dimensionality
1575     int dims;
1576
1577     // data reference counter
1578     int* refcount;
1579     // pointer to the data
1580     uchar* data;
1581     // and its actual beginning and end
1582     uchar* datastart;
1583     uchar* dataend;
1584
1585     // step and size for each dimension, MAX_DIM at max
1586     int size[MAX_DIM];
1587     size_t step[MAX_DIM];
1588 };
1589 \end{lstlisting}
1590
1591 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:
1592 \[
1593 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}
1594 \]
1595 which is more general form of the respective formula for \cross{Mat}, wherein \texttt{size[0]}$\sim$\texttt{rows},
1596 \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()}.
1597
1598 In other aspects \texttt{MatND} is also very similar to \texttt{Mat}, with the following limitations and differences:
1599 \begin{itemize}
1600     \item much less operations are implemented for \texttt{MatND}
1601     \item currently, algebraic expressions with \texttt{MatND}'s are not supported
1602     \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.
1603 \end{itemize}
1604
1605 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):
1606
1607 \begin{lstlisting}
1608 void computeColorHist(const Mat& image, MatND& hist, int N)
1609 {
1610     const int histSize[] = {N, N, N};
1611     
1612     // make sure that the histogram has proper size and type
1613     hist.create(3, histSize, CV_32F);
1614     
1615     // and clear it
1616     hist = Scalar(0);
1617     
1618     // the loop below assumes that the image
1619     // is 8-bit 3-channel, so let's check it.
1620     CV_Assert(image.type() == CV_8UC3);
1621     MatConstIterator_<Vec3b> it = image.begin<Vec3b>(),
1622                              it_end = image.end<Vec3b>();    
1623     for( ; it != it_end; ++it )
1624     {
1625         const Vec3b& pix = *it;
1626         
1627         // we could have incremented the cells by 1.f/(image.rows*image.cols)
1628         // instead of 1.f to make the histogram normalized.
1629         hist.at<float>(pix[0]*N/256, pix[1]*N/256, pix[2]*N/256) += 1.f;
1630     }
1631 }
1632 \end{lstlisting}
1633
1634 And here is how you can iterate through \texttt{MatND} elements:
1635
1636 \begin{lstlisting}
1637 void normalizeColorHist(MatND& hist)
1638 {
1639 #if 1    
1640     // intialize iterator (the style is different from STL).
1641     // after initialization the iterator will contain
1642     // the number of slices or planes
1643     // the iterator will go through
1644     MatNDIterator it(hist);
1645     double s = 0;
1646     // iterate through the matrix. on each iteration
1647     // it.planes[*] (of type Mat) will be set to the current plane.
1648     for(int p = 0; p < it.nplanes; p++, ++it)
1649         s += sum(it.planes[0])[0];
1650     it = MatNDIterator(hist);
1651     s = 1./s;
1652     for(int p = 0; p < it.nplanes; p++, ++it)
1653         it.planes[0] *= s;
1654 #elif 1
1655     // this is a shorter implementation of the above
1656     // using built-in operations on MatND
1657     double s = sum(hist)[0];
1658     hist.convertTo(hist, hist.type(), 1./s, 0);
1659 #else
1660     // and this is even shorter one
1661     // (assuming that the histogram elements are non-negative)
1662     normalize(hist, hist, 1, 0, NORM_L1);
1663 #endif
1664 }
1665 \end{lstlisting}
1666
1667 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.
1668
1669 \cvfunc{MatND\_}
1670 Template class for n-dimensional dense array derived from \cross{MatND}.
1671
1672 \begin{lstlisting}
1673 template<typename _Tp> class MatND_ : public MatND
1674 {
1675 public:
1676     typedef _Tp value_type;
1677     typedef typename DataType<_Tp>::channel_type channel_type;
1678
1679     // constructors, the same as in MatND, only the type is omitted
1680     MatND_();
1681     MatND_(int dims, const int* _sizes);
1682     MatND_(int dims, const int* _sizes, const _Tp& _s);
1683     MatND_(const MatND& m);
1684     MatND_(const MatND_& m);
1685     MatND_(const MatND_& m, const Range* ranges);
1686     MatND_(const CvMatND* m, bool copyData=false);
1687     MatND_& operator = (const MatND& m);
1688     MatND_& operator = (const MatND_& m);
1689     // different initialization function
1690     // where we take _Tp instead of Scalar
1691     MatND_& operator = (const _Tp& s);
1692
1693     // no special destructor is needed; use the one from MatND
1694
1695     void create(int dims, const int* _sizes);
1696     template<typename T2> operator MatND_<T2>() const;
1697     MatND_ clone() const;
1698     MatND_ operator()(const Range* ranges) const;
1699
1700     size_t elemSize() const;
1701     size_t elemSize1() const;
1702     int type() const;
1703     int depth() const;
1704     int channels() const;
1705     // step[i]/elemSize()
1706     size_t stepT(int i) const;
1707     size_t step1(int i) const;
1708
1709     // shorter alternatives for MatND::at<_Tp>.
1710     _Tp& operator ()(const int* idx);
1711     const _Tp& operator ()(const int* idx) const;
1712     _Tp& operator ()(int idx0);
1713     const _Tp& operator ()(int idx0) const;
1714     _Tp& operator ()(int idx0, int idx1);
1715     const _Tp& operator ()(int idx0, int idx1) const;
1716     _Tp& operator ()(int idx0, int idx1, int idx2);
1717     const _Tp& operator ()(int idx0, int idx1, int idx2) const;
1718     _Tp& operator ()(int idx0, int idx1, int idx2);
1719     const _Tp& operator ()(int idx0, int idx1, int idx2) const;
1720 };
1721 \end{lstlisting}
1722
1723 \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.
1724
1725 \begin{lstlisting}
1726 // alternative variant of the above histogram accumulation loop
1727 ...
1728 CV_Assert(hist.type() == CV_32FC1);
1729 MatND_<float>& _hist = (MatND_<float>&)hist;
1730 for( ; it != it_end; ++it )
1731 {
1732     const Vec3b& pix = *it;
1733     _hist(pix[0]*N/256, pix[1]*N/256, pix[2]*N/256) += 1.f;
1734 }
1735 ...
1736 \end{lstlisting}
1737
1738 \cvfunc{SparseMat}\label{SparseMat}
1739 Sparse n-dimensional array.
1740
1741 \begin{lstlisting}
1742 class SparseMat
1743 {
1744 public:
1745     typedef SparseMatIterator iterator;
1746     typedef SparseMatConstIterator const_iterator;
1747
1748     // internal structure - sparse matrix header
1749     struct Hdr
1750     {
1751         ...
1752     };
1753
1754     // sparse matrix node - element of a hash table
1755     struct Node
1756     {
1757         size_t hashval;
1758         size_t next;
1759         int idx[CV_MAX_DIM];
1760     };
1761
1762     ////////// constructors and destructor //////////
1763     // default constructor
1764     SparseMat();
1765     // creates matrix of the specified size and type
1766     SparseMat(int dims, const int* _sizes, int _type);
1767     // copy constructor
1768     SparseMat(const SparseMat& m);
1769     // converts dense 2d matrix to the sparse form,
1770     // if try1d is true and matrix is a single-column matrix (Nx1),
1771     // then the sparse matrix will be 1-dimensional.
1772     SparseMat(const Mat& m, bool try1d=false);
1773     // converts dense n-d matrix to the sparse form
1774     SparseMat(const MatND& m);
1775     // converts old-style sparse matrix to the new-style.
1776     // all the data is copied, so that "m" can be safely
1777     // deleted after the conversion
1778     SparseMat(const CvSparseMat* m);
1779     // destructor
1780     ~SparseMat();
1781     
1782     ///////// assignment operations /////////// 
1783     
1784     // this is O(1) operation; no data is copied
1785     SparseMat& operator = (const SparseMat& m);
1786     // (equivalent to the corresponding constructor with try1d=false)
1787     SparseMat& operator = (const Mat& m);
1788     SparseMat& operator = (const MatND& m);
1789
1790     // creates full copy of the matrix
1791     SparseMat clone() const;
1792     
1793     // copy all the data to the destination matrix.
1794     // the destination will be reallocated if needed.
1795     void copyTo( SparseMat& m ) const;
1796     // converts 1D or 2D sparse matrix to dense 2D matrix.
1797     // If the sparse matrix is 1D, then the result will
1798     // be a single-column matrix.
1799     void copyTo( Mat& m ) const;
1800     // converts arbitrary sparse matrix to dense matrix.
1801     // watch out the memory!
1802     void copyTo( MatND& m ) const;
1803     // multiplies all the matrix elements by the specified scalar
1804     void convertTo( SparseMat& m, int rtype, double alpha=1 ) const;
1805     // converts sparse matrix to dense matrix with optional type conversion and scaling.
1806     // When rtype=-1, the destination element type will be the same
1807     // as the sparse matrix element type.
1808     // Otherwise rtype will specify the depth and
1809     // the number of channels will remain the same is in the sparse matrix
1810     void convertTo( Mat& m, int rtype, double alpha=1, double beta=0 ) const;
1811     void convertTo( MatND& m, int rtype, double alpha=1, double beta=0 ) const;
1812
1813     // not used now
1814     void assignTo( SparseMat& m, int type=-1 ) const;
1815
1816     // reallocates sparse matrix. If it was already of the proper size and type,
1817     // it is simply cleared with clear(), otherwise,
1818     // the old matrix is released (using release()) and the new one is allocated.
1819     void create(int dims, const int* _sizes, int _type);
1820     // sets all the matrix elements to 0, which means clearing the hash table.
1821     void clear();
1822     // manually increases reference counter to the header.
1823     void addref();
1824     // decreses the header reference counter, when it reaches 0,
1825     // the header and all the underlying data are deallocated.
1826     void release();
1827
1828     // converts sparse matrix to the old-style representation.
1829     // all the elements are copied.
1830     operator CvSparseMat*() const;
1831     // size of each element in bytes
1832     // (the matrix nodes will be bigger because of
1833     //  element indices and other SparseMat::Node elements).
1834     size_t elemSize() const;
1835     // elemSize()/channels()
1836     size_t elemSize1() const;
1837     
1838     // the same is in Mat and MatND
1839     int type() const;
1840     int depth() const;
1841     int channels() const;
1842     
1843     // returns the array of sizes and 0 if the matrix is not allocated
1844     const int* size() const;
1845     // returns i-th size (or 0)
1846     int size(int i) const;
1847     // returns the matrix dimensionality
1848     int dims() const;
1849     // returns the number of non-zero elements
1850     size_t nzcount() const;
1851     
1852     // compute element hash value from the element indices:
1853     // 1D case
1854     size_t hash(int i0) const;
1855     // 2D case
1856     size_t hash(int i0, int i1) const;
1857     // 3D case
1858     size_t hash(int i0, int i1, int i2) const;
1859     // n-D case
1860     size_t hash(const int* idx) const;
1861     
1862     // low-level element-acccess functions,
1863     // special variants for 1D, 2D, 3D cases and the generic one for n-D case.
1864     //
1865     // return pointer to the matrix element.
1866     //  if the element is there (it's non-zero), the pointer to it is returned
1867     //  if it's not there and createMissing=false, NULL pointer is returned
1868     //  if it's not there and createMissing=true, then the new element
1869     //    is created and initialized with 0. Pointer to it is returned
1870     //  If the optional hashval pointer is not NULL, the element hash value is
1871     //  not computed, but *hashval is taken instead.
1872     uchar* ptr(int i0, bool createMissing, size_t* hashval=0);
1873     uchar* ptr(int i0, int i1, bool createMissing, size_t* hashval=0);
1874     uchar* ptr(int i0, int i1, int i2, bool createMissing, size_t* hashval=0);
1875     uchar* ptr(const int* idx, bool createMissing, size_t* hashval=0);
1876
1877     // higher-level element access functions:
1878     // ref<_Tp>(i0,...[,hashval]) - equivalent to *(_Tp*)ptr(i0,...true[,hashval]).
1879     //    always return valid reference to the element.
1880     //    If it's did not exist, it is created.
1881     // find<_Tp>(i0,...[,hashval]) - equivalent to (_const Tp*)ptr(i0,...false[,hashval]).
1882     //    return pointer to the element or NULL pointer if the element is not there.
1883     // value<_Tp>(i0,...[,hashval]) - equivalent to
1884     //    { const _Tp* p = find<_Tp>(i0,...[,hashval]); return p ? *p : _Tp(); }
1885     //    that is, 0 is returned when the element is not there.
1886     // note that _Tp must match the actual matrix type -
1887     // the functions do not do any on-fly type conversion
1888     
1889     // 1D case
1890     template<typename _Tp> _Tp& ref(int i0, size_t* hashval=0);   
1891     template<typename _Tp> _Tp value(int i0, size_t* hashval=0) const;
1892     template<typename _Tp> const _Tp* find(int i0, size_t* hashval=0) const;
1893
1894     // 2D case
1895     template<typename _Tp> _Tp& ref(int i0, int i1, size_t* hashval=0);   
1896     template<typename _Tp> _Tp value(int i0, int i1, size_t* hashval=0) const;
1897     template<typename _Tp> const _Tp* find(int i0, int i1, size_t* hashval=0) const;
1898     
1899     // 3D case
1900     template<typename _Tp> _Tp& ref(int i0, int i1, int i2, size_t* hashval=0);
1901     template<typename _Tp> _Tp value(int i0, int i1, int i2, size_t* hashval=0) const;
1902     template<typename _Tp> const _Tp* find(int i0, int i1, int i2, size_t* hashval=0) const;
1903
1904     // n-D case
1905     template<typename _Tp> _Tp& ref(const int* idx, size_t* hashval=0);
1906     template<typename _Tp> _Tp value(const int* idx, size_t* hashval=0) const;
1907     template<typename _Tp> const _Tp* find(const int* idx, size_t* hashval=0) const;
1908
1909     // erase the specified matrix element.
1910     // When there is no such element, the methods do nothing
1911     void erase(int i0, int i1, size_t* hashval=0);
1912     void erase(int i0, int i1, int i2, size_t* hashval=0);
1913     void erase(const int* idx, size_t* hashval=0);
1914
1915     // return the matrix iterators,
1916     //   pointing to the first sparse matrix element,
1917     SparseMatIterator begin();
1918     SparseMatConstIterator begin() const;
1919     //   ... or to the point after the last sparse matrix element
1920     SparseMatIterator end();
1921     SparseMatConstIterator end() const;
1922     
1923     // and the template forms of the above methods.
1924     // _Tp must match the actual matrix type.
1925     template<typename _Tp> SparseMatIterator_<_Tp> begin();
1926     template<typename _Tp> SparseMatConstIterator_<_Tp> begin() const;
1927     template<typename _Tp> SparseMatIterator_<_Tp> end();
1928     template<typename _Tp> SparseMatConstIterator_<_Tp> end() const;
1929
1930     // return value stored in the sparse martix node
1931     template<typename _Tp> _Tp& value(Node* n);
1932     template<typename _Tp> const _Tp& value(const Node* n) const;
1933     
1934     ////////////// some internal-use methods ///////////////
1935     ...
1936
1937     // pointer to the sparse matrix header
1938     Hdr* hdr;
1939 };
1940 \end{lstlisting}
1941
1942 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:
1943
1944 \begin{enumerate}
1945     \item query operations (\texttt{SparseMat::ptr} and the higher-level \texttt{SparseMat::ref}, \texttt{SparseMat::value} and \texttt{SparseMat::find}), e.g.:
1946     \begin{lstlisting}
1947     const int dims = 5;
1948     int size[] = {10, 10, 10, 10, 10};
1949     SparseMat sparse_mat(dims, size, CV_32F);
1950     for(int i = 0; i < 1000; i++)
1951     {
1952         int idx[dims];
1953         for(int k = 0; k < dims; k++)
1954             idx[k] = rand()%sparse_mat.size(k);
1955         sparse_mat.ref<float>(idx) += 1.f;
1956     }
1957     \end{lstlisting}
1958     \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:
1959     \begin{lstlisting}
1960     // prints elements of a sparse floating-point matrix
1961     // and the sum of elements.
1962     SparseMatConstIterator_<float>
1963         it = sparse_mat.begin<float>(),
1964         it_end = sparse_mat.end<float>();
1965     double s = 0;
1966     int dims = sparse_mat.dims();
1967     for(; it != it_end; ++it)
1968     {
1969         // print element indices and the element value
1970         const Node* n = it.node();
1971         printf("(")
1972         for(int i = 0; i < dims; i++)
1973             printf("%3d%c", n->idx[i], i < dims-1 ? ',' : ')');
1974         printf(": %f\n", *it);    
1975         s += *it;
1976     }
1977     printf("Element sum is %g\n", s);
1978     \end{lstlisting}
1979     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.
1980     \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:
1981     \begin{lstlisting}
1982     double cross_corr(const SparseMat& a, const SparseMat& b)
1983     {
1984         const SparseMat *_a = &a, *_b = &b;
1985         // if b contains less elements than a,
1986         // it's faster to iterate through b
1987         if(_a->nzcount() > _b->nzcount())
1988             std::swap(_a, _b);
1989         SparseMatConstIterator_<float> it = _a->begin<float>(),
1990                                        it_end = _a->end<float>();
1991         double ccorr = 0;
1992         for(; it != it_end; ++it)
1993         {
1994             // take the next element from the first matrix
1995             float avalue = *it;
1996             const Node* anode = it.node();
1997             // and try to find element with the same index in the second matrix.
1998             // since the hash value depends only on the element index,
1999             // we reuse hashvalue stored in the node
2000             float bvalue = _b->value<float>(anode->idx,&anode->hashval);
2001             ccorr += avalue*bvalue;
2002         }
2003         return ccorr;
2004     }
2005     \end{lstlisting}
2006 \end{enumerate}
2007
2008 \cvfunc{SparseMat\_}
2009 Template sparse n-dimensional array class derived from \cross{SparseMat}
2010
2011 \begin{lstlisting}
2012 template<typename _Tp> class SparseMat_ : public SparseMat
2013 {
2014 public:
2015     typedef SparseMatIterator_<_Tp> iterator;
2016     typedef SparseMatConstIterator_<_Tp> const_iterator;
2017
2018     // constructors;
2019     // the created matrix will have data type = DataType<_Tp>::type
2020     SparseMat_();
2021     SparseMat_(int dims, const int* _sizes);
2022     SparseMat_(const SparseMat& m);
2023     SparseMat_(const SparseMat_& m);
2024     SparseMat_(const Mat& m);
2025     SparseMat_(const MatND& m);
2026     SparseMat_(const CvSparseMat* m);
2027     // assignment operators; data type conversion is done when necessary
2028     SparseMat_& operator = (const SparseMat& m);
2029     SparseMat_& operator = (const SparseMat_& m);
2030     SparseMat_& operator = (const Mat& m);
2031     SparseMat_& operator = (const MatND& m);
2032
2033     // equivalent to the correspoding parent class methods
2034     SparseMat_ clone() const;
2035     void create(int dims, const int* _sizes);
2036     operator CvSparseMat*() const;
2037
2038     // overriden methods that do extra checks for the data type
2039     int type() const;
2040     int depth() const;
2041     int channels() const;
2042     
2043     // more convenient element access operations.
2044     // ref() is retained (but <_Tp> specification is not need anymore);
2045     // operator () is equivalent to SparseMat::value<_Tp>
2046     _Tp& ref(int i0, size_t* hashval=0);
2047     _Tp operator()(int i0, size_t* hashval=0) const;
2048     _Tp& ref(int i0, int i1, size_t* hashval=0);
2049     _Tp operator()(int i0, int i1, size_t* hashval=0) const;
2050     _Tp& ref(int i0, int i1, int i2, size_t* hashval=0);
2051     _Tp operator()(int i0, int i1, int i2, size_t* hashval=0) const;
2052     _Tp& ref(const int* idx, size_t* hashval=0);
2053     _Tp operator()(const int* idx, size_t* hashval=0) const;
2054
2055     // iterators
2056     SparseMatIterator_<_Tp> begin();
2057     SparseMatConstIterator_<_Tp> begin() const;
2058     SparseMatIterator_<_Tp> end();
2059     SparseMatConstIterator_<_Tp> end() const;
2060 };
2061 \end{lstlisting}
2062
2063 \texttt{SparseMat\_} is a thin wrapper on top of \cross{SparseMat}, made in the same way as \texttt{Mat\_} and \texttt{MatND\_}.
2064 It simplifies notation of some operations, and that's it.
2065 \begin{lstlisting}
2066 int sz[] = {10, 20, 30};
2067 SparseMat_<double> M(3, sz);
2068 ...
2069 M.ref(1, 2, 3) = M(4, 5, 6) + M(7, 8, 9);
2070 \end{lstlisting}
2071
2072 \subsection{Basic Functions}
2073
2074 \cvfunc{abs}\label{abs}
2075 Computes absolute value of each matrix element
2076
2077 \begin{lstlisting}
2078 MatExpr<...> abs(const Mat& src);
2079 MatExpr<...> abs(const MatExpr<...>& src);
2080 \end{lstlisting}
2081 \begin{description}
2082 \cvarg{src}{matrix or matrix expression}
2083 \end{description}
2084
2085 \texttt{abs} is a meta-function that is expanded to one of \cross{absdiff} forms:
2086
2087 \begin{itemize}
2088     \item \texttt{C = abs(A-B)} is equivalent to \texttt{absdiff(A, B, C)} and
2089     \item \texttt{C = abs(A)} is equivalent to \texttt{absdiff(A, Scalar::all(0), C)}.
2090     \item \texttt{C = Mat\_<Vec<uchar,\emph{n}> >(abs(A*$\alpha$ + $\beta$))} is equivalent to \texttt{convertScaleAbs(A, C, alpha, beta)}
2091 \end{itemize}
2092
2093 The output matrix will have the same size and the same type as the input one
2094 (except for the last case, where \texttt{C} will be \texttt{depth=CV\_8U}).
2095
2096 See also: \cross{Matrix Expressions}, \cross{absdiff}, \hyperref[saturatecast]{saturate\_cast}
2097
2098 \cvfunc{absdiff}\label{absdiff}
2099 Computes per-element absolute difference between 2 arrays or between array and a scalar.
2100
2101 \begin{lstlisting}
2102 void absdiff(const Mat& src1, const Mat& src2, Mat& dst);
2103 void absdiff(const Mat& src1, const Scalar& sc, Mat& dst);
2104 void absdiff(const MatND& src1, const MatND& src2, MatND& dst);
2105 void absdiff(const MatND& src1, const Scalar& sc, MatND& dst);
2106 \end{lstlisting}
2107 \begin{description}
2108 \cvarg{src1}{The first input array}
2109 \cvarg{src2}{The second input array; Must be the same size and same type as \texttt{a}}
2110 \cvarg{sc}{Scalar; the second input parameter}
2111 \cvarg{dst}{The destination array; it will have the same size and same type as \texttt{src1}; see \texttt{Mat::create}}
2112 \end{description}
2113
2114 The functions \texttt{absdiff} compute:
2115 \begin{itemize}
2116     \item absolute difference between two arrays
2117     \[\texttt{dst}(I) = \texttt{saturate}(|\texttt{src1}(I) - \texttt{src2}(I)|)\]
2118     \item or absolute difference between array and a scalar:
2119     \[\texttt{dst}(I) = \texttt{saturate}(|\texttt{src1}(I) - \texttt{sc}|)\]
2120 \end{itemize}
2121 where \texttt{I} is multi-dimensional index of array elements.
2122 in the case of multi-channel arrays each channel is processed independently.
2123
2124 See also: \cross{abs}, \hyperref[saturatecast]{saturate\_cast}
2125
2126 \cvfunc{add}\label{add}
2127 Computes the per-element sum of two arrays or an array and a scalar.
2128
2129 \begin{lstlisting}
2130 void add(const Mat& src1, const Mat& src2, Mat& dst);
2131 void add(const Mat& src1, const Mat& src2, Mat& dst, const Mat& mask);
2132 void add(const Mat& src1, const Scalar& sc, Mat& dst, const Mat& mask=Mat());
2133 void add(const MatND& src1, const MatND& src2, MatND& dst);
2134 void add(const MatND& src1, const MatND& src2, MatND& dst, const MatND& mask);
2135 void add(const MatND& src1, const Scalar& sc, MatND& dst, const MatND& mask=MatND());
2136 \end{lstlisting}
2137 \begin{description}
2138 \cvarg{src1}{The first source array}
2139 \cvarg{src2}{The second source array. It must have the same size and same type as \texttt{src1}}
2140 \cvarg{sc}{Scalar; the second input parameter}
2141 \cvarg{dst}{The destination array; it will have the same size and same type as \texttt{src1}; see \texttt{Mat::create}}
2142 \cvarg{mask}{The optional operation mask, 8-bit single channel array;
2143              specifies elements of the destination array to be changed}
2144 \end{description}
2145
2146 The functions \texttt{add} compute:
2147 \begin{itemize}
2148     \item the sum of two arrays:
2149     \[\texttt{dst}(I) = \texttt{saturate}(\texttt{src1}(I) + \texttt{src2}(I))\quad\texttt{if mask}(I)\ne0\]
2150     \item or the sum of array and a scalar:
2151     \[\texttt{dst}(I) = \texttt{saturate}(\texttt{src1}(I) + \texttt{sc})\quad\texttt{if mask}(I)\ne0\]
2152 \end{itemize}
2153 where \texttt{I} is multi-dimensional index of array elements.
2154
2155 The first function in the above list can be replaced with matrix expressions:
2156 \begin{lstlisting}
2157 dst = src1 + src2;
2158 dst += src1; // equivalent to add(dst, src1, dst);
2159 \end{lstlisting}
2160
2161 in the case of multi-channel arrays each channel is processed independently.
2162
2163 See also: \cross{subtract}, \cross{addWeighted}, \cross{scaleAdd}, \cross{convertScale},
2164 \cross{Matrix Expressions}, \hyperref[saturatecast]{saturate\_cast}.
2165
2166 \cvfunc{addWeighted}\label{addWeighted}
2167 Computes the weighted sum of two arrays.
2168
2169 \begin{lstlisting}
2170 void addWeighted(const Mat& src1, double alpha, const Mat& src2,
2171                  double beta, double gamma, Mat& dst);
2172 void addWeighted(const MatND& src1, double alpha, const MatND& src2,
2173                  double beta, double gamma, MatND& dst);
2174 \end{lstlisting}
2175 \begin{description}
2176 \cvarg{src1}{The first source array}
2177 \cvarg{alpha}{Weight for the first array elements}
2178 \cvarg{src2}{The second source array; must have the same size and same type as \texttt{src1}}
2179 \cvarg{beta}{Weight for the second array elements}
2180 \cvarg{dst}{The destination array; it will have the same size and same type as \texttt{src1}}
2181 \cvarg{gamma}{Scalar, added to each sum}
2182 \end{description}
2183
2184 The functions \texttt{addWeighted} calculate the weighted sum of two arrays as follows:
2185 \[\texttt{dst}(I)=\texttt{saturate}(\texttt{src1}(I)*\texttt{alpha} + \texttt{src2}(I)*\texttt{beta} + \texttt{gamma})\]
2186 where \texttt{I} is multi-dimensional index of array elements.
2187
2188 The first function can be replaced with a matrix expression:
2189 \begin{lstlisting}
2190 dst = src1*alpha + src2*beta + gamma;
2191 \end{lstlisting}
2192
2193 In the case of multi-channel arrays each channel is processed independently.
2194
2195 See also: \cross{add}, \cross{subtract}, \cross{scaleAdd}, \cross{convertScale},
2196 \cross{Matrix Expressions}, \hyperref[saturatecast]{saturate\_cast}.
2197
2198 \cvfunc{bitwise\_and}\label{bitwise and}
2199 Calculates per-element bit-wise conjunction of two arrays and an array and a scalar.
2200
2201 \begin{lstlisting}
2202 void bitwise_and(const Mat& src1, const Mat& src2, Mat& dst, const Mat& mask=Mat());
2203 void bitwise_and(const Mat& src1, const Scalar& sc, Mat& dst, const Mat& mask=Mat());
2204 void bitwise_and(const MatND& src1, const MatND& src2, MatND& dst, const MatND& mask=MatND());
2205 void bitwise_and(const MatND& src1, const Scalar& sc, MatND& dst, const MatND& mask=MatND());
2206 \end{lstlisting}
2207 \begin{description}
2208 \cvarg{src1}{The first source array}
2209 \cvarg{src2}{The second source array. It must have the same size and same type as \texttt{src1}}
2210 \cvarg{sc}{Scalar; the second input parameter}
2211 \cvarg{dst}{The destination array; it will have the same size and same type as \texttt{src1}; see \texttt{Mat::create}}
2212 \cvarg{mask}{The optional operation mask, 8-bit single channel array;
2213              specifies elements of the destination array to be changed}
2214 \end{description}
2215
2216 The functions \texttt{bitwise\_and} compute per-element bit-wise logical conjunction:
2217 \begin{itemize}
2218     \item of two arrays
2219     \[\texttt{dst}(I) = \texttt{src1}(I) \wedge \texttt{src2}(I)\quad\texttt{if mask}(I)\ne0\]
2220     \item or array and a scalar:
2221     \[\texttt{dst}(I) = \texttt{src1}(I) \wedge \texttt{sc}\quad\texttt{if mask}(I)\ne0\]
2222 \end{itemize}
2223
2224 In the case of floating-point arrays their machine-specific bit representations (usually IEEE754-compliant) are used for the operation, and in the case of multi-channel arrays each channel is processed independently.
2225
2226 See also: \hyperref[bitwise.and]{bitwise\_and}, \hyperref[bitwise.not]{bitwise\_not}, \hyperref[bitwise.xor]{bitwise\_xor}
2227
2228 \cvfunc{bitwise\_not}
2229 Inverts every bit of array
2230
2231 \begin{lstlisting}
2232 void bitwise_not(const Mat& src, Mat& dst);
2233 void bitwise_not(const MatND& src, MatND& dst);
2234 \end{lstlisting}
2235 \begin{description}
2236 \cvarg{src1}{The source array}
2237 \cvarg{dst}{The destination array; it is reallocated to be of the same size and
2238             the same type as \texttt{src}; see \texttt{Mat::create}}
2239 \cvarg{mask}{The optional operation mask, 8-bit single channel array;
2240              specifies elements of the destination array to be changed}
2241 \end{description}
2242
2243 The functions \texttt{bitwise\_not} compute per-element bit-wise inversion of the source array:
2244 \[\texttt{dst}(I) = \neg\texttt{src}(I)\]
2245
2246 In the case of floating-point source array its machine-specific bit representation (usually IEEE754-compliant) is used for the operation. in the case of multi-channel arrays each channel is processed independently.
2247
2248 See also: \hyperref[bitwise.and]{bitwise\_and}, \hyperref[bitwise.or]{bitwise\_or}, \hyperref[bitwise.xor]{bitwise\_xor}
2249
2250
2251 \cvfunc{bitwise\_or}
2252 Calculates per-element bit-wise disjunction of two arrays and an array and a scalar.
2253
2254 \begin{lstlisting}
2255 void bitwise_or(const Mat& src1, const Mat& src2, Mat& dst, const Mat& mask=Mat());
2256 void bitwise_or(const Mat& src1, const Scalar& s, Mat& dst, const Mat& mask=Mat());
2257 void bitwise_or(const MatND& src1, const MatND& src2, MatND& dst, const MatND& mask=MatND());
2258 void bitwise_or(const MatND& src1, const Scalar& s, MatND& dst, const MatND& mask=MatND());
2259 \end{lstlisting}
2260 \begin{description}
2261 \cvarg{src1}{The first source array}
2262 \cvarg{src2}{The second source array. It must have the same size and same type as \texttt{src1}}
2263 \cvarg{sc}{Scalar; the second input parameter}
2264 \cvarg{dst}{The destination array; it is reallocated to be of the same size and
2265             the same type as \texttt{src1}; see \texttt{Mat::create}}
2266 \cvarg{mask}{The optional operation mask, 8-bit single channel array;
2267              specifies elements of the destination array to be changed}
2268 \end{description}
2269
2270 The functions \texttt{bitwise\_or} compute per-element bit-wise logical disjunction
2271 \begin{itemize}
2272     \item of two arrays
2273     \[\texttt{dst}(I) = \texttt{src1}(I) \vee \texttt{src2}(I)\quad\texttt{if mask}(I)\ne0\]
2274     \item or array and a scalar:
2275     \[\texttt{dst}(I) = \texttt{src1}(I) \vee \texttt{sc}\quad\texttt{if mask}(I)\ne0\]
2276 \end{itemize}
2277
2278 In the case of floating-point arrays their machine-specific bit representations (usually IEEE754-compliant) are used for the operation. in the case of multi-channel arrays each channel is processed independently.
2279
2280 See also: \hyperref[bitwise.and]{bitwise\_and}, \hyperref[bitwise.not]{bitwise\_not}, \hyperref[bitwise.or]{bitwise\_or}
2281
2282 \cvfunc{bitwise\_xor}
2283 Calculates per-element bit-wise "exclusive or" operation on two arrays and an array and a scalar.
2284
2285 \begin{lstlisting}
2286 void bitwise_xor(const Mat& src1, const Mat& src2, Mat& dst, const Mat& mask=Mat());
2287 void bitwise_xor(const Mat& src1, const Scalar& s, Mat& dst, const Mat& mask=Mat());
2288 void bitwise_xor(const MatND& src1, const MatND& src2, MatND& dst, const MatND& mask=MatND());
2289 void bitwise_xor(const MatND& src1, const Scalar& s, MatND& dst, const MatND& mask=MatND());
2290 \end{lstlisting}
2291 \begin{description}
2292 \cvarg{src1}{The first source array}
2293 \cvarg{src2}{The second source array. It must have the same size and same type as \texttt{src1}}
2294 \cvarg{sc}{Scalar; the second input parameter}
2295 \cvarg{dst}{The destination array; it is reallocated to be of the same size and
2296             the same type as \texttt{src1}; see \texttt{Mat::create}}
2297 \cvarg{mask}{The optional operation mask, 8-bit single channel array;
2298              specifies elements of the destination array to be changed}
2299 \end{description}
2300
2301 The functions \texttt{bitwise\_xor} compute per-element bit-wise logical "exclusive or" operation
2302
2303 \begin{itemize}
2304     \item on two arrays
2305     \[\texttt{dst}(I) = \texttt{src1}(I) \oplus \texttt{src2}(I)\quad\texttt{if mask}(I)\ne0\]
2306     \item or array and a scalar:
2307     \[\texttt{dst}(I) = \texttt{src1}(I) \oplus \texttt{sc}\quad\texttt{if mask}(I)\ne0\]
2308 \end{itemize}
2309
2310 In the case of floating-point arrays their machine-specific bit representations (usually IEEE754-compliant) are used for the operation. in the case of multi-channel arrays each channel is processed independently.
2311
2312 See also: \hyperref[bitwise.and]{bitwise\_and}, \hyperref[bitwise.not]{bitwise\_not}, \hyperref[bitwise.or]{bitwise\_or}
2313
2314 \cvfunc{calcCovarMatrix}\label{calcCovarMatrix}
2315 Calculates covariation matrix of a set of vectors
2316
2317 \begin{lstlisting}
2318 void calcCovarMatrix( const Mat* samples, int nsamples,
2319                       Mat& covar, Mat& mean,
2320                       int flags, int ctype=CV_64F);
2321 void calcCovarMatrix( const Mat& samples, Mat& covar, Mat& mean,
2322                       int flags, int ctype=CV_64F);
2323 \end{lstlisting}
2324 \begin{description}
2325 \cvarg{samples}{The samples, stored as separate matrices, or as rows or columns of a single matrix}
2326 \cvarg{nsamples}{The number of samples when they are stored separately}
2327 \cvarg{covar}{The output covariance matrix; it will have type=\texttt{ctype} and square size}
2328 \cvarg{mean}{The input or output (depending on the flags) array - the mean (average) vector of the input vectors}
2329 \cvarg{flags}{The operation flags, a combination of the following values
2330 \begin{description}
2331 \cvarg{CV\_COVAR\_SCRAMBLED}{The output covariance matrix is calculated as:
2332 \[
2333  \texttt{scale} \cdot [ \texttt{vects} [0]- \texttt{mean} ,\texttt{vects} [1]- \texttt{mean} ,...]^T \cdot [\texttt{vects} [0]-\texttt{mean} ,\texttt{vects} [1]-\texttt{mean} ,...] 
2334 \],
2335 that is, the covariance matrix will be $\texttt{nsamples} \times \texttt{nsamples}$.
2336 Such an unusual covariance matrix is used for fast PCA
2337 of a set of very large vectors (see, for example, the EigenFaces technique
2338 for face recognition). Eigenvalues of this "scrambled" matrix will
2339 match the eigenvalues of the true covariance matrix and the "true"
2340 eigenvectors can be easily calculated from the eigenvectors of the
2341 "scrambled" covariance matrix.}
2342 \cvarg{CV\_COVAR\_NORMAL}{The output covariance matrix is calculated as:
2343 \[
2344  \texttt{scale} \cdot [ \texttt{vects} [0]- \texttt{mean} ,\texttt{vects} [1]- \texttt{mean} ,...] \cdot [\texttt{vects} [0]-\texttt{mean} ,\texttt{vects} [1]-\texttt{mean} ,...]^T 
2345 \],
2346 that is, \texttt{covar} will be a square matrix
2347 of the same size as the total number of elements in each
2348 input vector. One and only one of \texttt{CV\_COVAR\_SCRAMBLED} and
2349 \texttt{CV\_COVAR\_NORMAL} must be specified}
2350 \cvarg{CV\_COVAR\_USE\_AVG}{If the flag is specified, the function does not calculate \texttt{mean} from the input vectors, but, instead, uses the passed \texttt{mean} vector. This is useful if \texttt{mean} has been pre-computed or known a-priori, or if the covariance matrix is calculated by parts - in this case, \texttt{mean} is not a mean vector of the input sub-set of vectors, but rather the mean vector of the whole set.}
2351 \cvarg{CV\_COVAR\_SCALE}{If the flag is specified, the covariance matrix is scaled. In the "normal" mode \texttt{scale} is \texttt{1./nsamples}; in the "scrambled" mode \texttt{scale} is the reciprocal of the total number of elements in each input vector. By default (if the flag is not specified) the covariance matrix is not scaled (i.e. \texttt{scale=1}).}
2352
2353 \cvarg{CV\_COVAR\_ROWS}{[Only useful in the second variant of the function] The flag means that all the input vectors are stored as rows of the \texttt{samples} matrix. \texttt{mean} should be a single-row vector in this case.}
2354 \cvarg{CV\_COVAR\_COLS}{[Only useful in the second variant of the function] The flag means that all the input vectors are stored as columns of the \texttt{samples} matrix. \texttt{mean} should be a single-column vector in this case.}
2355
2356 \end{description}}
2357 \end{description}
2358
2359 The functions \texttt{calcCovarMatrix} calculate the covariance matrix
2360 and, optionally, the mean vector of the set of input vectors.
2361
2362 See also: \cross{PCA}, \cross{mulTransposed}, \cross{Mahalanobis}
2363
2364 \cvfunc{cartToPolar}\label{cartToPolar}
2365 Calculates the magnitude and angle of 2d vectors.
2366
2367 \begin{lstlisting}
2368 void cartToPolar(const Mat& x, const Mat& y,
2369                  Mat& magnitude, Mat& angle,
2370                  bool angleInDegrees=false);
2371 \end{lstlisting}
2372 \begin{description}
2373 \cvarg{x}{The array of x-coordinates; must be single-precision or double-precision floating-point array}
2374 \cvarg{y}{The array of y-coordinates; it must have the same size and same type as \texttt{x}}
2375 \cvarg{magnitude}{The destination array of magnitudes of the same size and same type as \texttt{x}}
2376 \cvarg{angle}{The destination array of angles of the same size and same type as \texttt{x}.
2377 The angles are measured in radians $(0$ to $2 \pi )$ or in degrees (0 to 360 degrees).}
2378 \cvarg{angleInDegrees}{The flag indicating whether the angles are measured in radians, which is default mode, or in degrees}
2379 \end{description}
2380
2381 The function \texttt{cartToPolar} calculates either the magnitude, angle, or both of every 2d vector (x(I),y(I)):
2382
2383 \[
2384 \begin{array}{l}
2385 \texttt{magnitude}(I)=\sqrt{\texttt{x}(I)^2+\texttt{y}(I)^2},\\
2386 \texttt{angle}(I)=\texttt{atan2}(\texttt{y}(I), \texttt{x}(I))[\cdot180/\pi]
2387 \end{array}
2388 \]
2389
2390 The angles are calculated with $\sim\,0.3^\circ$ accuracy. For the (0,0) point, the angle is set to 0.
2391
2392 \cvfunc{checkRange}\label{checkRange}
2393 Checks every element of an input array for invalid values.
2394
2395 \begin{lstlisting}
2396 bool checkRange(const Mat& src, bool quiet=true, Point* pos=0,
2397                 double minVal=-DBL_MAX, double maxVal=DBL_MAX);
2398 bool checkRange(const MatND& src, bool quiet=true, int* pos=0,
2399                 double minVal=-DBL_MAX, double maxVal=DBL_MAX);
2400 \end{lstlisting}
2401 \begin{description}
2402 \cvarg{src}{The array to check}
2403 \cvarg{quiet}{The flag indicating whether the functions quietly return false when the array elements are out of range, or they throw an exception.}
2404 \cvarg{pos}{The optional output parameter, where the position of the first outlier is stored. In the second function \texttt{pos}, when not NULL, must be a pointer to array of \texttt{src.dims} elements}
2405 \cvarg{minVal}{The inclusive lower boundary of valid values range}
2406 \cvarg{maxVal}{The exclusive upper boundary of valid values range}
2407 \end{description}
2408
2409 The functions \texttt{checkRange} check that every array element is
2410 neither NaN nor $ \pm \infty $. When \texttt{minVal < -DBL\_MAX} and \texttt{maxVal < DBL\_MAX}, then the functions also check that
2411 each value is between \texttt{minVal} and \texttt{maxVal}. in the case of multi-channel arrays each channel is processed independently.
2412 If some values are out of range, position of the first outlier is stored in \texttt{pos} (when $\texttt{pos}\ne0$), and then the functions either return false (when \texttt{quiet=true}) or throw an exception.
2413
2414
2415 \cvfunc{compare}\label{compare}
2416 Performs per-element comparison of two arrays or an array and scalar value.
2417
2418 \begin{lstlisting}
2419 void compare(const Mat& src1, const Mat& src2, Mat& dst, int cmpop);
2420 void compare(const Mat& src1, double value, Mat& dst, int cmpop);
2421 void compare(const MatND& src1, const MatND& src2, MatND& dst, int cmpop);
2422 void compare(const MatND& src1, double value, MatND& dst, int cmpop);
2423 \end{lstlisting}
2424 \begin{description}
2425 \cvarg{src1}{The first source array}
2426 \cvarg{src2}{The second source array; must have the same size and same type as \texttt{src1}}
2427 \cvarg{value}{The scalar value to compare each array element with}
2428 \cvarg{dst}{The destination array; will have the same size as \texttt{src1} and type=\texttt{CV\_8UC1}}
2429 \cvarg{cmpop}{The flag specifying the relation between the elements to be checked
2430 \begin{description}
2431  \cvarg{CMP\_EQ}{$\texttt{src1}(I) = \texttt{src2}(I)$ or $\texttt{src1}(I) = \texttt{value}$}
2432  \cvarg{CMP\_GT}{$\texttt{src1}(I) > \texttt{src2}(I)$ or $\texttt{src1}(I) > \texttt{value}$}
2433  \cvarg{CMP\_GE}{$\texttt{src1}(I) \geq \texttt{src2}(I)$ or $\texttt{src1}(I) \geq \texttt{value}$}
2434  \cvarg{CMP\_LT}{$\texttt{src1}(I) < \texttt{src2}(I)$ or $\texttt{src1}(I) < \texttt{value}$}
2435  \cvarg{CMP\_LE}{$\texttt{src1}(I) \leq \texttt{src2}(I)$ or $\texttt{src1}(I) \leq \texttt{value}$}
2436  \cvarg{CMP\_NE}{$\texttt{src1}(I) \ne \texttt{src2}(I)$ or $\texttt{src1}(I) \ne \texttt{value}$}
2437 \end{description}}
2438 \end{description}
2439
2440 The functions \texttt{compare} compare each element of \texttt{src1} with the corresponding element of \texttt{src2}
2441 or with real scalar \texttt{value}. When the comparison result is true, the corresponding element of destination array is set to 255, otherwise it is set to 0:
2442 \begin{itemize}
2443     \item \texttt{dst(I) = src1(I) cmpop src2(I) ? 255 : 0}
2444     \item \texttt{dst(I) = src1(I) cmpop value ? 255 : 0}
2445 \end{itemize}
2446
2447 The comparison operations can be replaced with the equivalent matrix expressions:
2448
2449 \begin{lstlisting}
2450 Mat dst1 = src1 >= src2;
2451 Mat dst2 = src1 < 8;
2452 ...
2453 \end{lstlisting}
2454
2455 See also: \cross{checkRange}, \cross{min}, \cross{max}, \cross{threshold}, \cross{Matrix Expressions}
2456
2457 \cvfunc{completeSymm}\label{completeSymm}
2458 Copies the lower or the upper half of a square matrix to another half.
2459
2460 \begin{lstlisting}
2461 void completeSymm(Mat& mtx, bool lowerToUpper=false);
2462 \end{lstlisting}
2463 \begin{description}
2464 \cvarg{mtx}{Input-output floating-point square matrix}
2465 \cvarg{lowerToUpper}{If true, the lower half is copied to the upper half, otherwise the upper half is copied to the lower half}
2466 \end{description}
2467
2468 The function \texttt{completeSymm} copies the lower half of a square matrix to its another half; the matrix diagonal remains unchanged:
2469
2470 \begin{itemize}
2471     \item $\texttt{mtx}_{ij}=\texttt{mtx}_{ji}$ for $i > j$ if \texttt{lowerToUpper=false}
2472     \item $\texttt{mtx}_{ij}=\texttt{mtx}_{ji}$ for $i < j$ if \texttt{lowerToUpper=true}
2473 \end{itemize}
2474
2475 See also: \cross{flip}, \cross{transpose}
2476
2477 \cvfunc{convertScaleAbs}\label{convertScaleAbs}
2478 Scales, computes absolute values and converts the result to 8-bit.
2479
2480 \begin{lstlisting}
2481 void convertScaleAbs(const Mat& src, Mat& dst, double alpha=1, double beta=0);
2482 \end{lstlisting}
2483 \begin{description}
2484 \cvarg{src}{The source array}
2485 \cvarg{dst}{The destination array}
2486 \cvarg{alpha}{The optional scale factor}
2487 \cvarg{beta}{The optional delta added to the scaled values}
2488 \end{description}
2489
2490 On each element of the input array the function \texttt{convertScaleAbs} performs 3 operations sequentially: scaling, taking absolute value, conversion to unsigned 8-bit type:
2491 \[\texttt{dst}(I)=\texttt{saturate\_cast<uchar>}(|\texttt{src}(I)*\texttt{alpha} + \texttt{beta}|)\]
2492
2493 in the case of multi-channel arrays the function processes each channel independently. When the output is not 8-bit, the operation can be emulated by calling \texttt{Mat::convertTo} method (or by using matrix expressions) and then by computing absolute value of the result, for example:
2494
2495 \begin{lstlisting}
2496 Mat_<float> A(30,30);
2497 randu(A, Scalar(-100), Scalar(100));
2498 Mat_<float> B = A*5 + 3;
2499 B = abs(B);
2500 // Mat_<float> B = abs(A*5+3) will also do the job,
2501 // but it will allocate a temporary matrix
2502 \end{lstlisting}
2503
2504 See also: \cross{Mat::convertTo}, \cross{abs}
2505
2506 \cvfunc{countNonZero}\label{countNonZero}
2507 Counts non-zero array elements.
2508
2509 \begin{lstlisting}
2510 int countNonZero( const Mat& mtx );
2511 int countNonZero( const MatND& mtx );
2512 \end{lstlisting}
2513 \begin{description}
2514 \cvarg{mtx}Single-channel array
2515 \end{description}
2516
2517 The function \texttt{cvCountNonZero} returns the number of non-zero elements in mtx:
2518
2519 \[ \sum_{I:\;\texttt{mtx}(I)\ne0} 1 \]
2520
2521 See also: \cross{mean}, \cross{meanStdDev}, \cross{norm}, \cross{minMaxLoc}, \cross{calcCovarMatrix}
2522
2523 \cvfunc{cubeRoot}\label{cubeRoot}
2524 Computes cube root of the argument
2525
2526 \begin{lstlisting}
2527 float cubeRoot(float val);
2528 \end{lstlisting}
2529 \begin{description}
2530 \cvarg{val}The function argument
2531 \end{description}
2532
2533 The function \texttt{cubeRoot} computes $\sqrt[3]{\texttt{val}}$.
2534 Negative arguments are handled correctly, \emph{NaN} and $\pm\infty$ are not handled.
2535 The accuracy approaches the maximum possible accuracy for single-precision data.
2536
2537 \cvfunc{cvsrcToMat}\label{cvsrcToMat}
2538 Converts \cross{CvMat}, \cross{IplImage} or \cross{CvMatND} to \cross{Mat}.
2539
2540 \begin{lstlisting}
2541 Mat cvsrcToMat(const CvArr* src, bool copyData=false, bool allowND=true, int coiMode=0);
2542 \end{lstlisting}
2543 \begin{description}
2544 \cvarg{src}{The source \texttt{CvMat}, \texttt{IplImage} or \texttt{CvMatND}}
2545 \cvarg{copyData}{When it is false (default value), no data is copied, only the new header is created.
2546  In this case the original array should not be deallocated while the new matrix header is used. The the parameter is true, all the data is copied, then user may deallocate the original array right after the conversion}
2547 \cvarg{allowND}{When it is true (default value), then \texttt{CvMatND} is converted to \texttt{Mat} if it's possible
2548 (e.g. then the data is contiguous). If it's not possible, or when the parameter is false, the function will report an error}
2549 \cvarg{coiMode}{The parameter specifies how the IplImage COI (when set) is handled.
2550 \begin{itemize}
2551     \item If \texttt{coiMode=0}, the function will report an error if COI is set.
2552     \item If \texttt{coiMode=1}, the function will never report an error; instead it returns the header to the whole original image and user will have to check and process COI manually, see \cross{extractImageCOI}.
2553 %    \item If \texttt{coiMode=2}, the function will extract the COI into the separate matrix. \emph{This is also done when the COI is set and }\texttt{copyData=true}}
2554 \end{itemize}}
2555 \end{description}
2556
2557 The function \texttt{cvsrcToMat} converts \cross{CvMat}, \cross{IplImage} or \cross{CvMatND} header to \cross{Mat} header, and optionally duplicates the underlying data. The constructed header is returned by the function.
2558
2559 When \texttt{copyData=false}, the conversion is done really fast (in O(1) time) and the newly created matrix header will have \texttt{refcount=0}, which means that no reference counting is done for the matrix data, and user has to preserve the data until the new header is destructed. Otherwise, when \texttt{copyData=true}, the new buffer will be allocated and managed as if you created a new matrix from scratch and copy the data there. That is,
2560 \texttt{cvsrcToMat(src, true) $\sim$ cvsrcToMat(src, false).clone()} (assuming that COI is not set). The function provides uniform way of supporting \cross{CvArr} paradigm in the code that is migrated to use new-style data structures internally. The reverse transformation, from \cross{Mat} to \cross{CvMat} or \cross{IplImage} can be done by simple assignment:
2561
2562 \begin{lstlisting}
2563 CvMat* A = cvCreateMat(10, 10, CV_32F);
2564 cvSetIdentity(A);
2565 IplImage A1; cvGetImage(A, &A1);
2566 Mat B = cvsrcToMat(A);
2567 Mat B1 = cvsrcToMat(&A1);
2568 IplImage C = B;
2569 CvMat C1 = B1;
2570 // now A, A1, B, B1, C and C1 are different headers
2571 // for the same 10x10 floating-point array.
2572 // note, that you will need to use "&"
2573 // to pass C & C1 to OpenCV functions, e.g:
2574 printf("%g", cvDet(&C1));
2575 \end{lstlisting}
2576
2577 Normally, the function is used to convert an old-style 2D array (\cross{CvMat} or \cross{IplImage}) to \texttt{Mat}, however, the function can also take \cross{CvMatND} on input and create \cross{Mat} for it, if it's possible. And for \texttt{CvMatND A} it is possible if and only if \texttt{A.dim[i].size*A.dim.step[i] == A.dim.step[i-1]} for all or for all but one \texttt{i, 0 < i < A.dims}. That is, the matrix data should be continuous or it should be representable as a sequence of continuous matrices. By using this function in this way, you can process \cross{CvMatND} using arbitrary element-wise function. But for more complex operations, such as filtering functions, it will not work, and you need to convert \cross{CvMatND} to \cross{MatND} using the corresponding constructor of the latter.
2578
2579 The last parameter, \texttt{coiMode}, specifies how to react on an image with COI set: by default it's 0, and then the function reports an error when an image with COI comes in. And \texttt{coiMode=1} means that no error is signaled - user has to check COI presence and handle it manually. The modern structures, such as \cross{Mat} and \cross{MatND} do not support COI natively. To process individual channel of an new-style array, you will need either to organize loop over the array (e.g. using matrix iterators) where the channel of interest will be processed, or extract the COI using \cross{mixChannels} (for new-style arrays) or \cross{extractImageCOI} (for old-style arrays), process this individual channel and insert it back to the destination array if need (using \cross{mixChannel} or \cross{insertImageCOI}, respectively).
2580
2581 See also: \cross{cvGetImage}, \cross{cvGetMat}, \cross{cvGetMatND}, \cross{extractImageCOI}, \cross{insertImageCOI}, \cross{mixChannels}
2582
2583
2584 \cvfunc{dct}\label{dct}
2585 Performs a forward or inverse discrete cosine transform of 1D or 2D array
2586
2587 \begin{lstlisting}
2588 void dct(const Mat& src, Mat& dst, int flags=0);
2589 \end{lstlisting}
2590 \begin{description}
2591 \cvarg{src}{The source floating-point array}
2592 \cvarg{dst}{The destination array; will have the same size and same type as \texttt{src}}
2593 \cvarg{flags}\cvarg{flags}{Transformation flags, a combination of the following values
2594 \begin{description}
2595 \cvarg{DCT\_INVERSE}{do an inverse 1D or 2D transform instead of the default forward transform.}
2596 \cvarg{DCT\_ROWS}{do a forward or inverse transform of every individual row of the input matrix. This flag allows user to transform multiple vectors simultaneously and can be used to decrease the overhead (which is sometimes several times larger than the processing itself), to do 3D and higher-dimensional transforms and so forth.}
2597 \end{description}}
2598 \end{description}
2599
2600 The function \texttt{dct} performs a forward or inverse discrete cosine transform (DCT) of a 1D or 2D floating-point array:
2601
2602 Forward Cosine transform of 1D vector of $N$ elements:
2603 \[Y = C^{(N)} \cdot X\]
2604 where
2605 \[C^{(N)}_{jk}=\sqrt{\alpha_j/N}\cos\left(\frac{\pi(2k+1)j}{2N}\right)\]
2606 and $\alpha_0=1$, $\alpha_j=2$ for $j > 0$.
2607
2608 Inverse Cosine transform of 1D vector of N elements:
2609 \[X = \left(C^{(N)}\right)^{-1} \cdot Y = \left(C^{(N)}\right)^T \cdot Y\]
2610 (since $C^{(N)}$ is orthogonal matrix, $C^{(N)} \cdot \left(C^{(N)}\right)^T = I$)
2611
2612 Forward Cosine transform of 2D $M \times N$ matrix:
2613 \[Y = C^{(N)} \cdot X \cdot \left(C^{(N)}\right)^T\]
2614
2615 Inverse Cosine transform of 2D vector of $M \times N$ elements:
2616 \[X = \left(C^{(N)}\right)^T \cdot X \cdot C^{(N)}\]
2617
2618 The function chooses the mode of operation by looking at the flags and size of the input array:
2619 \begin{itemize}
2620     \item if \texttt{(flags \& DCT\_INVERSE) == 0}, the function does forward 1D or 2D transform, otherwise it is inverse 1D or 2D transform.
2621     \item if \texttt{(flags \& DCT\_ROWS) $\ne$ 0}, the function performs 1D transform of each row.
2622     \item otherwise, if the array is a single column or a single row, the function performs 1D transform
2623     \item otherwise it performs 2D transform.
2624 \end{itemize}
2625
2626 \textbf{Important note}: currently cv::dct supports even-size arrays (2, 4, 6 ...). For data analysis and approximation you can pad the array when necessary.
2627
2628 Also, the function's performance depends very much, and not monotonically, on the array size, see \cross{getOptimalDFTSize}. In the current implementation DCT of a vector of size \texttt{N} is computed via DFT of a vector of size \texttt{N/2}, thus the optimal DCT size $\texttt{N}^*\geq\texttt{N}$ can be computed as:
2629
2630 \begin{lstlisting}
2631 size_t getOptimalDCTSize(size_t N) { return 2*getOptimalDFTSize((N+1)/2); }
2632 \end{lstlisting}
2633
2634 See also: \cross{dft}, \cross{getOptimalDFTSize}, \cross{idct}
2635
2636
2637 \cvfunc{dft}\label{dft}
2638 Performs a forward or inverse Discrete Fourier transform of 1D or 2D floating-point array.
2639
2640 \begin{lstlisting}
2641 void dft(const Mat& src, Mat& dst, int flags=0, int nonzeroRows=0);
2642 \end{lstlisting}
2643 \begin{description}
2644 \cvarg{src}{The source array, real or complex}
2645 \cvarg{dst}{The destination array, which size and type depends on the \texttt{flags}}
2646 \cvarg{flags}{Transformation flags, a combination of the following values
2647 \begin{description}
2648 \cvarg{DFT\_INVERSE}{do an inverse 1D or 2D transform instead of the default forward transform.}
2649 \cvarg{DFT\_SCALE}{scale the result: divide it by the number of array elements. Normally, it is combined with \texttt{DFT\_INVERSE}}.
2650 \cvarg{DFT\_ROWS}{do a forward or inverse transform of every individual row of the input matrix. This flag allows the user to transform multiple vectors simultaneously and can be used to decrease the overhead (which is sometimes several times larger than the processing itself), to do 3D and higher-dimensional transforms and so forth.}
2651 \cvarg{DFT\_COMPLEX\_OUTPUT}{then the function performs forward transformation of 1D or 2D real array, the result, though being a complex array, has complex-conjugate symmetry (\emph{CCS}), see the description below. Such an array can be packed into real array of the same size as input, which is the fastest option and which is what the function does by default. However, you may wish to get the full complex array (for simpler spectrum analysis etc.). Pass the flag to tell the function to produce full-size complex output array.}
2652 \cvarg{DFT\_REAL\_OUTPUT}{then the function performs inverse transformation of 1D or 2D complex array, the result is normally a complex array of the same size. However, if the source array has conjugate-complex symmetry (for example, it is a result of forward transformation with \texttt{DFT\_COMPLEX\_OUTPUT} flag), then the output is real array. While the function itself does not check whether the input is symmetrical or not, you can pass the flag and then the function will assume the symmetry and produce the real output array. Note that when the input is packed real array and inverse transformation is executed, the function treats the input as packed complex-conjugate symmetrical array, so the output will also be real array}
2653 \end{description}}
2654 \cvarg{nonzeroRows}{When $\ne$ 0, the function assumes that only the first \texttt{nonzeroRows} rows of the input array (when \texttt{(flags \& DFT\_INVERSE) = 0} or only the first \texttt{nonzeroRows} o the output array (when \texttt{(flags \& DFT\_INVERSE) $\ne$ 0} contain non-zeros, thus the function can handle the rest of the rows more efficiently and thus save some time. This technique is very useful for computing array cross-correlation or convolution using DFT}
2655 \end{description}
2656
2657 Forward Fourier transform of 1D vector of N elements:
2658 \[Y = F^{(N)} \cdot X,\]
2659 where $F^{(N)}_{jk}=\exp(-2\pi i j k/N)$ and $i=\sqrt{-1}$
2660
2661 Inverse Fourier transform of 1D vector of N elements:
2662 \[
2663 \begin{array}{l}
2664 X'= \left(F^{(N)}\right)^{-1} \cdot Y = \left(F^{(N)}\right)^* \cdot y \\
2665 X = (1/N) \cdot X,
2666 \end{array}
2667 \]
2668 where $F^*=\left(\textrm{Re}(F^{(N)})-\textrm{Im}(F^{(N)})\right)^T$
2669
2670 Forward Fourier transform of 2D vector of M $\times$ N elements:
2671 \[Y = F^{(M)} \cdot X \cdot F^{(N)}\]
2672
2673 Inverse Fourier transform of 2D vector of M $\times$ N elements:
2674 \[
2675 \begin{array}{l}
2676 X'= \left(F^{(M)}\right)^* \cdot Y \cdot \left(F^{(N)}\right)^*\\
2677 X = \frac{1}{M \cdot N} \cdot X'
2678 \end{array}
2679 \]
2680
2681 In the case of real (single-channel) data, the packed format called \emph{CCS} (complex-conjugate-symmetrical) that was borrowed from IPL and used to represent the result of a forward Fourier transform or input for an inverse Fourier transform:
2682
2683 \[\begin{bmatrix}
2684 Re Y_{0,0} & Re Y_{0,1} & Im Y_{0,1} & Re Y_{0,2} & Im Y_{0,2} & \cdots & Re Y_{0,N/2-1} & Im Y_{0,N/2-1} & Re Y_{0,N/2} \\
2685 Re Y_{1,0} & Re Y_{1,1} & Im Y_{1,1} & Re Y_{1,2} & Im Y_{1,2} & \cdots & Re Y_{1,N/2-1} & Im Y_{1,N/2-1} & Re Y_{1,N/2} \\
2686 Im Y_{1,0} & Re Y_{2,1} & Im Y_{2,1} & Re Y_{2,2} & Im Y_{2,2} & \cdots & Re Y_{2,N/2-1} & Im Y_{2,N/2-1} & Im Y_{1,N/2} \\
2687 \hdotsfor{9} \\
2688 Re Y_{M/2-1,0} &  Re Y_{M-3,1}  & Im Y_{M-3,1} & \hdotsfor{3} & Re Y_{M-3,N/2-1} & Im Y_{M-3,N/2-1}& Re Y_{M/2-1,N/2} \\
2689 Im Y_{M/2-1,0} &  Re Y_{M-2,1}  & Im Y_{M-2,1} & \hdotsfor{3} & Re Y_{M-2,N/2-1} & Im Y_{M-2,N/2-1}& Im Y_{M/2-1,N/2} \\
2690 Re Y_{M/2,0}  &  Re Y_{M-1,1} &  Im Y_{M-1,1} & \hdotsfor{3} & Re Y_{M-1,N/2-1} & Im Y_{M-1,N/2-1}& Re Y_{M/2,N/2}
2691 \end{bmatrix}
2692 \]
2693
2694 in the case of 1D transform of real vector, the output will look as the first row of the above matrix. 
2695
2696 So, the function chooses the operation mode depending on the flags and size of the input array:
2697 \begin{itemize}
2698     \item if \texttt{(flags \& DFT\_ROWS) $\ne$ 0} or the input array has single row or single column then the function performs 1D forward or inverse transform (of each row of a matrix when \texttt{(flags \& DFT\_ROWS) $\ne$ 0}), otherwise it will be 2D transform.
2699     \item if input array is real and \texttt{(flags \& DFT\_INVERSE) == 0}, the function does forward 1D or 2D transform:
2700     \begin{itemize}
2701         \item when \texttt{(flags \& DFT\_COMPLEX\_OUTPUT) $\ne$ 0)} then the output will be complex matrix of the same size as input.
2702         \item otherwise the output will be a real matrix of the same size as input. in the case of 2D transform it will use the packed format as shown above; in the case of single 1D transform it will look as the first row of the above matrix; in the case of multiple 1D transforms (when using \texttt{DCT\_ROWS} flag) each row of the output matrix will look like the first row of the above matrix.
2703     \end{itemize}
2704     \item otherwise, if the input array is complex and \texttt{(flags \& DFT\_INVERSE) == 0} or \texttt{(flags \& DFT\_REAL\_OUTPUT) == 0} then the output will be a complex array of the same size as input and the function will perform the forward or inverse 1D or 2D transform of the whole input array or each row of the input array independently, depending on the flags \texttt{DFT\_INVERSE} and \texttt{DFT\_ROWS}.
2705     \item otherwise, i.e. when \texttt{(flags \& DFT\_INVERSE) $\ne$ 0}, the input array is real, or it is complex but \texttt{(flags \& DFT\_REAL\_OUTPUT) $\ne$ 0}, the output will be a real array of the same size as input, and the function will perform 1D or 2D inverse transformation of the whole input array or each individual row, depending on the flags \texttt{DFT\_INVERSE} and \texttt{DFT\_ROWS}.
2706 \end{itemize}
2707
2708 The scaling is done if needed (\texttt{(flags \& DFT\_SCALE) $\ne$ 0}) after the transformation.
2709
2710 Unlike \cross{dct}, the function supports arrays of arbitrary size, but only those arrays are processed efficiently, which sizes can be factorized in a product of small prime numbers (2, 3 and 5 in the current implementation). Such an efficient DFT size can be computed using \cross{getOptimalDFTSize} method.
2711
2712 Here is the sample on how to compute DFT-based convolution of two 2D real arrays:
2713 \begin{lstlisting}
2714 void convolveDFT(const Mat& A, const Mat& B, Mat& C)
2715 {
2716     // reallocate the output array if needed
2717     C.create(abs(A.rows - B.rows)+1, abs(A.cols - B.cols)+1, A.type());
2718     Size dftSize;
2719     // compute the size of DFT transform
2720     dftSize.width = getOptimalDFTSize(A.cols + B.cols - 1);
2721     dftSize.height = getOptimalDFTSize(A.rows + B.rows - 1);
2722     
2723     // allocate temporary buffers and initialize them with 0's
2724     Mat tempA(dftSize, A.type(), Scalar::all(0));
2725     Mat tempB(dftSize, B.type(), Scalar::all(0));
2726     
2727     // copy A and B to the top-left corners of tempA and tempB, respectively
2728     Mat roiA(tempA, Rect(0,0,A.cols,A.rows));
2729     A.copyTo(roiA);
2730     Mat roiB(tempB, Rect(0,0,B.cols,B.rows));
2731     B.copyTo(roiB);
2732     
2733     // now transform the padded A & B in-place;
2734     // use "nonzeroRows" hint for faster processing
2735     dft(tempA, tempA, 0, A.rows);
2736     dft(tempB, tempB, 0, B.rows);
2737     
2738     // multiply the spectrums;
2739     // the function handles packed spectrum representations well
2740     mulSpectrums(tempA, tempB, tempA);
2741     
2742     // transform the product back from the frequency domain.
2743     // Even though all the result rows will be non-zero,
2744     // we need only the first C.rows of them, and thus we
2745     // pass nonzeroRows == C.rows
2746     dft(tempA, tempA, DFT_INVERSE + DFT_SCALE, C.rows);
2747     
2748     // now copy the result back to C.
2749     tempA(Rect(0, 0, C.cols, C.rows)).copyTo(C);
2750     
2751     // all the temporary buffers will be deallocated automatically
2752 }
2753 \end{lstlisting}
2754
2755 What can be optimized in the above sample?
2756 \begin{itemize}
2757     \item since we passed \texttt{nonzeroRows $\ne$ 0} to the forward transform calls and
2758     since we copied \texttt{A}/\texttt{B} to the top-left corners of \texttt{tempA}/\texttt{tempB}, respectively,
2759     it's not necessary to clear the whole \texttt{tempA} and \texttt{tempB};
2760     it is only necessary to clear the \texttt{tempA.cols - A.cols} (\texttt{tempB.cols - B.cols})
2761     rightmost columns of the matrices.
2762     \item this DFT-based convolution does not have to be applied to the whole big arrays,
2763     especially if \texttt{B} is significantly smaller than \texttt{A} or vice versa.
2764     Instead, we can compute convolution by parts. For that we need to split the destination array
2765     \texttt{C} into multiple tiles and for each tile estimate, which parts of \texttt{A} and \texttt{B}
2766     are required to compute convolution in this tile. If the tiles in \texttt{C} are too small,
2767     the speed will decrease a lot, because of repeated work - in the ultimate case, when each tile in \texttt{C} is a single pixel,
2768     the algorithm becomes equivalent to the naive convolution algorithm.
2769     If the tiles are too big, the temporary arrays \texttt{tempA} and \texttt{tempB} become too big
2770     and there is also slowdown because of bad cache locality. So there is optimal tile size somewhere in the middle.
2771     \item if the convolution is done by parts, since different tiles in \texttt{C} can be computed in parallel, the loop can be threaded.
2772 \end{itemize}
2773
2774 All of the above improvements have been implemented in \cross{matchTemplate} and \cross{filter2D}, therefore, by using them, you can get even better performance than with the above theoretically optimal implementation (though, those two functions actually compute cross-correlation, not convolution, so you will need to "flip" the kernel or the image around the center using \cross{flip}).
2775
2776 See also: \cross{dct}, \cross{getOptimalDFTSize}, \cross{mulSpectrums}, \cross{filter2D}, \cross{matchTemplate}, \cross{flip}, \cross{cartToPolar}, \cross{magnitude}, \cross{phase}
2777
2778 \cvfunc{divide}\label{divide}
2779
2780 Performs per-element division of two arrays or a scalar by an array.
2781
2782 \begin{lstlisting}
2783 void divide(const Mat& src1, const Mat& src2, Mat& dst, double scale=1);
2784 void divide(double scale, const Mat& src2, Mat& dst);
2785 void divide(const MatND& src1, const MatND& src2, MatND& dst, double scale=1);
2786 void divide(double scale, const MatND& src2, MatND& dst);
2787 \end{lstlisting}
2788 \begin{description}
2789 \cvarg{src1}{The first source array}
2790 \cvarg{src2}{The second source array; should have the same size and same type as \texttt{src1}}
2791 \cvarg{scale}{Scale factor}
2792 \cvarg{dst}{The destination array; will have the same size and same type as \texttt{src2}}
2793 \end{description}
2794
2795 The functions \texttt{divide} divide one array by another:
2796 \[\texttt{dst(I) = saturate(src1(I)*scale/src2(I))} \]
2797
2798 or a scalar by array, when there is no \texttt{src1}:
2799 \[\texttt{dst(I) = saturate(scale/src2(I))} \]
2800
2801 The result will have the same type as \texttt{src1}. When \texttt{src2(I)=0}, \texttt{dst(I)=0} too.
2802
2803 See also: \cross{multiply}, \cross{add}, \cross{subtract}, \cross{Matrix Expressions}
2804
2805 \cvfunc{determinant}\label{determinant}
2806
2807 Returns determinant of a square floating-point matrix.
2808
2809 \begin{lstlisting}
2810 double determinant(const Mat& mtx);
2811 \end{lstlisting}
2812 \begin{description}
2813 \cvarg{mtx}{The input matrix; must have \texttt{CV\_32FC1} or \texttt{CV\_64FC1} type and square size}
2814 \end{description}
2815
2816 The function \texttt{determinant} computes and returns determinant of the specified matrix. For small matrices (\texttt{mtx.cols=mtx.rows<=3})
2817 the direct method is used; for larger matrices the function uses LU factorization.
2818
2819 For symmetric positive-determined matrices, it is also possible to compute \cross{SVD}: $\texttt{mtx}=U \cdot W \cdot V^T$ and then calculate the determinant as a product of the diagonal elements of $W$.
2820
2821 See also: \cross{SVD}, \cross{trace}, \cross{invert}, \cross{solve}, \cross{Matrix Expressions}
2822
2823 \cvfunc{eigen}\label{eigen}
2824 Computes eigenvalues and eigenvectors of a symmetric matrix.
2825
2826 \begin{lstlisting}
2827 bool eigen(const Mat& src, Mat& eigenvalues, int lowindex, int highindex);
2828 bool eigen(const Mat& src, Mat& eigenvalues, Mat& eigenvectors, int lowindex,
2829 int highindex);
2830 \end{lstlisting}
2831 \begin{description}
2832 \cvarg{src}{The input matrix; must have \texttt{CV\_32FC1} or \texttt{CV\_64FC1} type, square size and be symmetric: $\texttt{src}^T=\texttt{src}$}
2833 \cvarg{eigenvalues}{The output vector of eigenvalues of the same type as \texttt{src}; The eigenvalues are stored in the descending order.}
2834 \cvarg{eigenvectors}{The output matrix of eigenvectors; It will have the same size and the same type as \texttt{src}; The eigenvectors are stored as subsequent matrix rows, in the same order as the corresponding eigenvalues}
2835 \cvarg{lowindex}{Optional index of largest eigenvalue/-vector to calculate.
2836 (See below.)}
2837 \cvarg{highindex}{Optional index of smallest eigenvalue/-vector to calculate.
2838 (See below.)}
2839 \end{description}
2840
2841 The functions \texttt{eigen} compute just eigenvalues, or eigenvalues and eigenvectors of symmetric matrix \texttt{src}:
2842
2843 \begin{lstlisting}
2844 src*eigenvectors(i,:)' = eigenvalues(i)*eigenvectors(i,:)' (in MATLAB notation)
2845 \end{lstlisting}
2846
2847 If either low- or highindex is supplied the other is required, too.
2848 Indexing is 0-based. Example: To calculate the largest eigenvector/-value set
2849 lowindex = highindex = 0.
2850 For legacy reasons this function always returns a square matrix the same size
2851 as the source matrix with eigenvectors and a vector the length of the source
2852 matrix with eigenvalues. The selected eigenvectors/-values are always in the
2853 first highindex - lowindex + 1 rows.
2854
2855 See also: \cross{SVD}, \cross{completeSymm}, \cross{PCA}
2856
2857 \cvfunc{exp}\label{exp}
2858 Calculates the exponent of every array element.
2859
2860 \begin{lstlisting}
2861 void exp(const Mat& src, Mat& dst);
2862 void exp(const MatND& src, MatND& dst);
2863 \end{lstlisting}
2864 \begin{description}
2865 \cvarg{src}{The source array}
2866 \cvarg{dst}{The destination array; will have the same size and same type as \texttt{src}}
2867 \end{description}
2868
2869 The function \texttt{exp} calculates the exponent of every element of the input array:
2870
2871 \[
2872 \texttt{dst} [I] = e^{\texttt{src}}(I)
2873 \]
2874
2875 The maximum relative error is about $7 \times 10^{-6}$ for single-precision and less than $10^{-10}$ for double-precision. Currently, the function converts denormalized values to zeros on output. Special values (NaN, $\pm \infty$) are not handled.
2876
2877 See also: \cross{log}, \cross{cartToPolar}, \cross{polarToCart}, \cross{phase}, \cross{pow}, \cross{sqrt}, \cross{magnitude}
2878
2879 \cvfunc{extractImageCOI}\label{extractImageCOI}
2880
2881 Extract the selected image channel
2882
2883 \begin{lstlisting}
2884 void extractImageCOI(const CvArr* src, Mat& dst, int coi=-1);
2885 \end{lstlisting}
2886 \begin{description}
2887 \cvarg{src}{The source array. It should be a pointer to \cross{CvMat} or \cross{IplImage}}
2888 \cvarg{dst}{The destination array; will have single-channel, and the same size and the same depth as \texttt{src}}
2889 \cvarg{coi}{If the parameter is \texttt{>=0}, it specifies the channel to extract;
2890 If it is \texttt{<0}, \texttt{src} must be a pointer to \texttt{IplImage} with valid COI set - then the selected COI is extracted.}
2891 \end{description}
2892
2893 The function \texttt{extractImageCOI} is used to extract image COI from an old-style array and put the result to the new-style C++ matrix. As usual, the destination matrix is reallocated using \texttt{Mat::create} if needed.
2894
2895 To extract a channel from a new-style matrix, use \cross{mixChannels} or \cross{split}
2896
2897 See also: \cross{mixChannels}, \cross{split}, \cross{merge}, \cross{cvsrcToMat}, \cross{cvSetImageCOI}, \cross{cvGetImageCOI}
2898
2899
2900 \cvfunc{fastAtan2}\label{fastAtan2}
2901 Calculates the angle of a 2D vector in degrees
2902
2903 \begin{lstlisting}
2904 float fastAtan2(float y, float x);
2905 \end{lstlisting}
2906 \begin{description}
2907 \cvarg{x}{x-coordinate of the vector}
2908 \cvarg{y}{y-coordinate of the vector}
2909 \end{description}
2910
2911 The function \texttt{fastAtan2} calculates the full-range angle of an input 2D vector. The angle is 
2912 measured in degrees and varies from $0^\circ$ to $360^\circ$. The accuracy is about $0.3^\circ$.
2913
2914 \cvfunc{flip}\label{flip}
2915 Flips a 2D array around vertical, horizontal or both axes.
2916
2917 \begin{lstlisting}
2918 void flip(const Mat& src, Mat& dst, int flipCode);
2919 \end{lstlisting}
2920 \begin{description}
2921 \cvarg{src}{The source array}
2922 \cvarg{dst}{The destination array; will have the same size and same type as \texttt{src}}
2923 \cvarg{flipCode}{Specifies how to flip the array:
2924 0 means flipping around the x-axis, positive (e.g., 1) means flipping around y-axis, and negative (e.g., -1) means flipping around both axes. See also the discussion below for the formulas.}
2925 \end{description}
2926
2927 The function \texttt{flip} flips the array in one of three different ways (row and column indices are 0-based):
2928
2929 \[
2930 \texttt{dst}_{ij} = \forkthree
2931 {\texttt{src}_{\texttt{src.rows}-i-1,j}}{if \texttt{flipCode} = 0}
2932 {\texttt{src}_{i,\texttt{src.cols}-j-1}}{if \texttt{flipCode} > 0}
2933 {\texttt{src}_{\texttt{src.rows}-i-1,\texttt{src.cols}-j-1}}{if \texttt{flipCode} < 0}
2934 \]
2935
2936 The example scenarios of function use are:
2937 \begin{itemize}
2938   \item vertical flipping of the image ($\texttt{flipCode} = 0$) to switch between top-left and bottom-left image origin, which is a typical operation in video processing in Windows.
2939   \item horizontal flipping of the image with subsequent horizontal shift and absolute difference calculation to check for a vertical-axis symmetry ($\texttt{flipCode} > 0$)
2940   \item simultaneous horizontal and vertical flipping of the image with subsequent shift and absolute difference calculation to check for a central symmetry ($\texttt{flipCode} < 0$)
2941   \item reversing the order of 1d point arrays ($\texttt{flipCode} > 0$ or $\texttt{flipCode} = 0$)
2942 \end{itemize}
2943
2944 See also: \cross{transpose}, \cross{repeat}, \cross{completeSymm}
2945
2946 \cvfunc{gemm}\label{gemm}
2947 Performs generalized matrix multiplication.
2948
2949 \begin{lstlisting}
2950 void gemm(const Mat& src1, const Mat& src2, double alpha,
2951           const Mat& src3, double beta, Mat& dst, int flags=0);
2952 \end{lstlisting}
2953 \begin{description}
2954 \cvarg{src1}{The first multiplied input matrix; should have \texttt{CV\_32FC1}, \texttt{CV\_64FC1}, \texttt{CV\_32FC2} or \texttt{CV\_64FC2} type}
2955 \cvarg{src2}{The second multiplied input matrix; should have the same type as \texttt{src1}}
2956 \cvarg{alpha}{The weight of the matrix product}
2957 \cvarg{src3}{The third optional delta matrix added to the matrix product; should have the same type as \texttt{src1} and \texttt{src2}}
2958 \cvarg{beta}{The weight of \texttt{src3}}
2959 \cvarg{dst}{The destination matrix; It will have the proper size and the same type as input matrices}
2960 \cvarg{flags}{Operation flags:
2961 \begin{description}
2962     \cvarg{GEMM\_1\_T}{transpose \texttt{src1}}
2963     \cvarg{GEMM\_2\_T}{transpose \texttt{src2}}
2964     \cvarg{GEMM\_3\_T}{transpose \texttt{src3}}
2965 \end{description}}
2966 \end{description}
2967
2968 The function performs generalized matrix multiplication and similar to the corresponding functions \texttt{*gemm} in BLAS level 3.
2969 For example, \texttt{gemm(src1, src2, alpha, src3, beta, dst, GEMM\_1\_T + GEMM\_3\_T)} corresponds to
2970 \[
2971 \texttt{dst} = \texttt{alpha} \cdot \texttt{src1} ^T \cdot \texttt{src2} + \texttt{beta} \cdot \texttt{src3} ^T
2972 \]
2973
2974 The function can be replaced with a matrix expression, e.g. the above call can be replaced with:
2975 \begin{lstlisting}
2976 dst = alpha*src1.t()*src2 + beta*src3.t();
2977 \end{lstlisting}
2978
2979 See also: \cross{mulTransposed}, \cross{transform}, \cross{Matrix Expressions}
2980
2981
2982 \cvfunc{getConvertElem}\label{getConvertElem}
2983 Returns conversion function for a single pixel
2984
2985 \begin{lstlisting}
2986 ConvertData getConvertElem(int fromType, int toType);
2987 ConvertScaleData getConvertScaleElem(int fromType, int toType);
2988
2989 typedef void (*ConvertData)(const void* from, void* to, int cn);
2990 typedef void (*ConvertScaleData)(const void* from, void* to,
2991                                  int cn, double alpha, double beta);
2992 \end{lstlisting}
2993 \begin{description}
2994 \cvarg{fromType}{The source pixel type}
2995 \cvarg{toType}{The destination pixel type}
2996 \cvarg{from}{Callback parameter: pointer to the input pixel}
2997 \cvarg{to}{Callback parameter: pointer to the output pixel}
2998 \cvarg{cn}{Callback parameter: the number of channels; can be arbitrary, 1, 100, 100000, ...}
2999 \cvarg{alpha}{ConvertScaleData callback optional parameter: the scale factor}
3000 \cvarg{beta}{ConvertScaleData callback optional parameter: the delta or offset}
3001 \end{description}
3002
3003 The functions \texttt{getConvertElem} and \texttt{getConvertScaleElem} return pointers to the functions for converting individual pixels from one type to another. While the main function purpose is to convert single pixels (actually, for converting sparse matrices from one type to another), you can use them to convert the whole row of a dense matrix or the whole matrix at once, by setting \texttt{cn = matrix.cols*matrix.rows*matrix.channels()} if the matrix data is continuous.
3004
3005 See also: \cross{Mat::convertTo}, \cross{MatND::convertTo}, \cross{SparseMat::convertTo}
3006
3007
3008 \cvfunc{getOptimalDFTSize}\label{getOptimalDFTSize}
3009 Returns optimal DFT size for a given vector size.
3010
3011 \begin{lstlisting}
3012 int getOptimalDFTSize(int vecsize);
3013 \end{lstlisting}
3014 \begin{description}
3015 \cvarg{vecsize}{Vector size}
3016 \end{description}
3017
3018 DFT performance is not a monotonic function of a vector size, therefore, when you compute convolution of two arrays or do a spectral analysis of array, it usually makes sense to pad the input data with zeros to get a bit larger array that can be transformed much faster than the original one.
3019 Arrays, which size is a power-of-two (2, 4, 8, 16, 32, ...) are the fastest to process, though, the arrays, which size is a product of 2's, 3's and 5's (e.g. 300 = 5*5*3*2*2), are also processed quite efficiently.
3020
3021 The function \texttt{getOptimalDFTSize} returns the minimum number \texttt{N} that is greater than or equal to \texttt{vecsize}, such that the DFT
3022 of a vector of size \texttt{N} can be computed efficiently. In the current implementation $N=2^p \times 3^q \times 5^r$, for some $p$, $q$, $r$.
3023
3024 The function returns a negative number if \texttt{vecsize} is too large (very close to \texttt{INT\_MAX}).
3025
3026 While the function cannot be used directly to estimate the optimal vector size for DCT transform (since the current DCT implementation supports only even-size vectors), it can be easily computed as \texttt{getOptimalDFTSize((vecsize+1)/2)*2}.
3027
3028 See also: \cross{dft}, \cross{dct}, \cross{idft}, \cross{idct}, \cross{mulSpectrums}
3029
3030 \cvfunc{idct}\label{idct}
3031 Computes inverse Discrete Cosine Transform of a 1D or 2D array
3032
3033 \begin{lstlisting}
3034 void idct(const Mat& src, Mat& dst, int flags=0);
3035 \end{lstlisting}
3036 \begin{description}
3037 \cvarg{src}{The source floating-point single-channel array}
3038 \cvarg{dst}{The destination array. Will have the same size and same type as \texttt{src}}
3039 \cvarg{flags}{The operation flags.}
3040 \end{description}
3041
3042 \texttt{idct(src, dst, flags)} is equivalent to \texttt{dct(src, dst, flags | DCT\_INVERSE)}.
3043 See \cross{dct} for details.
3044
3045 See also: \cross{dct}, \cross{dft}, \cross{idft}, \cross{getOptimalDFTSize}
3046
3047
3048 \cvfunc{idft}\label{idft}
3049 Computes inverse Discrete Fourier Transform of a 1D or 2D array
3050
3051 \begin{lstlisting}
3052 void idft(const Mat& src, Mat& dst, int flags=0, int outputRows=0);
3053 \end{lstlisting}
3054 \begin{description}
3055 \cvarg{src}{The source floating-point real or complex array}
3056 \cvarg{dst}{The destination array, which size and type depends on the \texttt{flags}}
3057 \cvarg{flags}{The operation flags. See \cross{dft}}
3058 \cvarg{nonzeroRows}{The number of \texttt{dst} rows to compute.
3059 The rest of the rows will have undefined content.
3060 See the convolution sample in \cross{dft} description}
3061 \end{description}
3062
3063 \texttt{idft(src, dst, flags)} is equivalent to \texttt{dct(src, dst, flags | DFT\_INVERSE)}.
3064 See \cross{dft} for details.
3065 Note, that none of \texttt{dft} and \texttt{idft} scale the result by default.
3066 Thus, you should pass \texttt{DFT\_SCALE} to one of \texttt{dft} or \texttt{idft}
3067 explicitly to make these transforms mutually inverse.
3068
3069 See also: \cross{dft}, \cross{dct}, \cross{idct}, \cross{mulSpectrums}, \cross{getOptimalDFTSize}
3070
3071
3072 \cvfunc{inRange}\label{inRange}
3073 Checks if array elements lie between the elements of two other arrays.
3074
3075 \begin{lstlisting}
3076 void inRange(const Mat& src, const Mat& lowerb,
3077              const Mat& upperb, Mat& dst);
3078 void inRange(const Mat& src, const Scalar& lowerb,
3079              const Scalar& upperb, Mat& dst);
3080 void inRange(const MatND& src, const MatND& lowerb,
3081              const MatND& upperb, MatND& dst);
3082 void inRange(const MatND& src, const Scalar& lowerb,
3083              const Scalar& upperb, MatND& dst);
3084 \end{lstlisting}
3085 \begin{description}
3086 \cvarg{src}{The first source array}
3087 \cvarg{lowerb}{The inclusive lower boundary array of the same size and type as \texttt{src}}
3088 \cvarg{upperb}{The exclusive upper boundary array of the same size and type as \texttt{src}}
3089 \cvarg{dst}{The destination array, will have the same size as \texttt{src} and \texttt{CV\_8U} type}
3090 \end{description}
3091
3092 The functions \texttt{inRange} do the range check for every element of the input array:
3093
3094 \[
3095 \texttt{dst}(I)=\texttt{lowerb}(I)_0 \leq \texttt{src}(I)_0 < \texttt{upperb}(I)_0
3096 \]
3097
3098 for single-channel arrays,
3099
3100 \[
3101 \texttt{dst}(I)=
3102 \texttt{lowerb}(I)_0 \leq \texttt{src}(I)_0 < \texttt{upperb}(I)_0 \land
3103 \texttt{lowerb}(I)_1 \leq \texttt{src}(I)_1 < \texttt{upperb}(I)_1
3104 \]
3105
3106 for two-channel arrays and so forth.
3107 \texttt{dst}(I) is set to 255 (all \texttt{1}-bits) if \texttt{src}(I) is within the specified range and 0 otherwise.
3108
3109
3110 \cvfunc{invert}\label{invert}
3111 Finds the inverse or pseudo-inverse of a matrix
3112
3113 \begin{lstlisting}
3114 double invert(const Mat& src, Mat& dst, int method=DECOMP_LU);
3115 \end{lstlisting}
3116 \begin{description}
3117 \cvarg{src}{The source floating-point $M \times N$ matrix}
3118 \cvarg{dst}{The destination matrix; will have $N \times M$ size and the same type as \texttt{src}}
3119 \cvarg{flags}{The inversion method :
3120 \begin{description}
3121  \cvarg{DECOMP\_LU}{Gaussian elimination with optimal pivot element chosen}
3122  \cvarg{DECOMP\_SVD}{Singular value decomposition (SVD) method}
3123  \cvarg{DECOMP\_CHOLESKY}{Cholesky decomposion. The matrix must be symmetrical and positively defined}
3124 \end{description}}
3125 \end{description}
3126
3127 The function \texttt{invert} inverts matrix \texttt{src} and stores the result in \texttt{dst}.
3128 When the matrix \texttt{src} is singular or non-square, the function computes the pseudo-inverse matrix, i.e. the matrix \texttt{dst}, such that $\|\texttt{src} \cdot \texttt{dst} - I\|$ is minimal.
3129
3130 In the case of \texttt{DECOMP\_LU} method, the function returns the \texttt{src} determinant (\texttt{src} must be square). If it is 0, the matrix is not inverted and \texttt{dst} is filled with zeros.
3131
3132 In the case of \texttt{DECOMP\_SVD} method, the function returns the inversed condition number of \texttt{src} (the ratio of the smallest singular value to the largest singular value) and 0 if \texttt{src} is singular. The SVD method calculates a pseudo-inverse matrix if \texttt{src} is singular.
3133
3134 Similarly to \texttt{DECOMP\_LU}, the method \texttt{DECOMP\_CHOLESKY} works only with non-singular square matrices. In this case the function stores the inverted matrix in \texttt{dst} and returns non-zero, otherwise it returns 0.
3135
3136 See also: \cross{solve}, \cross{SVD}
3137
3138
3139 \cvfunc{log}\label{log}
3140 Calculates the natural logarithm of every array element.
3141
3142 \begin{lstlisting}
3143 void log(const Mat& src, Mat& dst);
3144 void log(const MatND& src, MatND& dst);
3145 \end{lstlisting}
3146 \begin{description}
3147 \cvarg{src}{The source array}
3148 \cvarg{dst}{The destination array; will have the same size and same type as \texttt{src}}
3149 \end{description}
3150
3151 The function \texttt{log} calculates the natural logarithm of the absolute value of every element of the input array:
3152
3153 \[
3154 \texttt{dst}(I) = \fork
3155 {\log |\texttt{src}(I)|}{if $\texttt{src}(I) \ne 0$ }
3156 {\texttt{C}}{otherwise}
3157 \]
3158
3159 Where \texttt{C} is a large negative number (about -700 in the current implementation).
3160 The maximum relative error is about $7 \times 10^{-6}$ for single-precision input and less than $10^{-10}$ for double-precision input. Special values (NaN, $\pm \infty$) are not handled.
3161
3162 See also: \cross{exp}, \cross{cartToPolar}, \cross{polarToCart}, \cross{phase}, \cross{pow}, \cross{sqrt}, \cross{magnitude}
3163
3164
3165 \cvfunc{LUT}\label{LUT}
3166 Performs a look-up table transform of an array.
3167
3168 \begin{lstlisting}
3169 void LUT(const Mat& src, const Mat& lut, Mat& dst);
3170 \end{lstlisting}
3171 \begin{description}
3172 \cvarg{src}{Source array of 8-bit elements}
3173 \cvarg{lut}{Look-up table of 256 elements. In the case of multi-channel source array, the table should either have a single channel (in this case the same table is used for all channels) or the same number of channels as in the source array}
3174 \cvarg{dst}{Destination array; will have the same size and the same number of channels as \texttt{src}, and the same depth as \texttt{lut}}
3175 \end{description}
3176
3177 The function \texttt{LUT} fills the destination array with values from the look-up table. Indices of the entries are taken from the source array. That is, the function processes each element of \texttt{src} as follows:
3178
3179 \[
3180 \texttt{dst}(I) \leftarrow \texttt{lut(src(I) + d)}
3181 \]
3182
3183 where
3184
3185 \[
3186 d = \fork
3187 {0}{if \texttt{src} has depth \texttt{CV\_8U}}
3188 {128}{if \texttt{src} has depth \texttt{CV\_8S}}
3189 \]
3190
3191 See also: \cross{convertScaleAbs}, \texttt{Mat::convertTo}
3192
3193 \cvfunc{magnitude}\label{magnitude}
3194 Calculates magnitude of 2D vectors.
3195
3196 \begin{lstlisting}
3197 void magnitude(const Mat& x, const Mat& y, Mat& magnitude);
3198 \end{lstlisting}
3199 \begin{description}
3200 \cvarg{x}{The floating-point array of x-coordinates of the vectors}
3201 \cvarg{y}{The floating-point array of y-coordinates of the vectors; must have the same size as \texttt{x}}
3202 \cvarg{dst}{The destination array; will have the same size and same type as \texttt{x}}
3203 \end{description}
3204
3205 The function \texttt{magnitude} calculates magnitude of 2D vectors formed from the corresponding elements of \texttt{x} and \texttt{y} arrays:
3206
3207 \[
3208 \texttt{dst}(I) = \sqrt{\texttt{x}(I)^2 + \texttt{y}(I)^2}
3209 \]
3210
3211 See also: \cross{cartToPolar}, \cross{polarToCart}, \cross{phase}, \cross{sqrt}
3212
3213
3214 \cvfunc{Mahalanobis}\label{Mahalanobis}
3215 Calculates the Mahalanobis distance between two vectors.
3216
3217 \begin{lstlisting}
3218 double Mahalanobis(const Mat& vec1, const Mat& vec2, const Mat& icovar);
3219 double Mahalonobis(const Mat& vec1, const Mat& vec2, const Mat& icovar);
3220 \end{lstlisting}
3221 \begin{description}
3222 \cvarg{vec1}{The first 1D source vector}
3223 \cvarg{vec2}{The second 1D source vector}
3224 \cvarg{icovar}{The inverse covariance matrix}
3225 \end{description}
3226
3227 The function \texttt{cvMahalonobis} calculates and returns the weighted distance between two vectors:
3228
3229 \[
3230 d(\texttt{vec1},\texttt{vec2})=\sqrt{\sum_{i,j}{\texttt{icovar(i,j)}\cdot(\texttt{vec1}(I)-\texttt{vec2}(I))\cdot(\texttt{vec1(j)}-\texttt{vec2(j)})}}
3231 \]
3232
3233 The covariance matrix may be calculated using the \cross{calcCovarMatrix} function and then inverted using the \cross{invert} function (preferably using DECOMP\_SVD method, as the most accurate).
3234
3235
3236 \cvfunc{max}\label{max}
3237 Calculates per-element maximum of two arrays or array and a scalar
3238
3239 \begin{lstlisting}
3240 Mat_Expr<...> max(const Mat& src1, const Mat& src2);
3241 Mat_Expr<...> max(const Mat& src1, double value);
3242 Mat_Expr<...> max(double value, const Mat& src1);
3243 void max(const Mat& src1, const Mat& src2, Mat& dst);
3244 void max(const Mat& src1, double value, Mat& dst);
3245 void max(const MatND& src1, const MatND& src2, MatND& dst);
3246 void max(const MatND& src1, double value, MatND& dst);
3247 \end{lstlisting}
3248 \begin{description}
3249 \cvarg{src1}{The first source array}
3250 \cvarg{src2}{The second source array of the same size and type as \texttt{src1}}
3251 \cvarg{value}{The real scalar value}
3252 \cvarg{dst}{The destination array; will have the same size and type as \texttt{src1}}
3253 \end{description}
3254
3255 The functions \texttt{max} compute per-element maximum of two arrays:
3256 \[\texttt{dst}(I)=\max(\texttt{src1}(I), \texttt{src2}(I))\]
3257 or array and a scalar:
3258 \[\texttt{dst}(I)=\max(\texttt{src1}(I), \texttt{value})\]
3259
3260 In the second variant, when the source array is multi-channel, each channel is compared with \texttt{value} independently.
3261
3262 The first 3 variants of the function listed above are actually a part of \cross{Matrix Expressions}, they return the expression object that can be further transformed, or assigned to a matrix, or passed to a function etc.
3263
3264 See also: \cross{min}, \cross{compare}, \cross{inRange}, \cross{minMaxLoc}, \cross{Matrix Expressions}
3265
3266 \cvfunc{mean}\label{mean}
3267 Calculates average (mean) of array elements
3268
3269 \begin{lstlisting}
3270 Scalar mean(const Mat& mtx);
3271 Scalar mean(const Mat& mtx, const Mat& mask);
3272 Scalar mean(const MatND& mtx);
3273 Scalar mean(const MatND& mtx, const MatND& mask);
3274 \end{lstlisting}
3275 \begin{description}
3276 \cvarg{mtx}{The source array; it should have 1 to 4 channels (so that the result can be stored in \cross{Scalar})}
3277 \cvarg{mask}{The optional operation mask}
3278 \end{description}
3279
3280 The functions \texttt{mean} compute mean value \texttt{M} of array elements, independently for each channel, and return it:
3281
3282 \[
3283 \begin{array}{l}
3284 N = \sum_{I:\;\texttt{mask}(I)\ne 0} 1\\
3285 M_c = \left(\sum_{I:\;\texttt{mask}(I)\ne 0}{\texttt{mtx}(I)_c}\right)/N
3286 \end{array}
3287 \]
3288
3289 When all the mask elements are 0's, the functions return \texttt{Scalar::all(0)}.
3290
3291 See also: \cross{countNonZero}, \cross{meanStdDev}, \cross{norm}, \cross{minMaxLoc}
3292
3293 \cvfunc{meanStdDev}\label{meanStdDev}
3294 Calculates mean and standard deviation of array elements
3295
3296 \begin{lstlisting}
3297 void meanStdDev(const Mat& mtx, Scalar& mean, Scalar& stddev, const Mat& mask=Mat());
3298 void meanStdDev(const MatND& mtx, Scalar& mean, Scalar& stddev, const MatND& mask=MatND());
3299 \end{lstlisting}
3300 \begin{description}
3301 \cvarg{mtx}{The source array; it should have 1 to 4 channels (so that the results can be stored in \cross{Scalar}'s)}
3302 \cvarg{mean}{The output parameter: computed mean value}
3303 \cvarg{stddev}{The output parameter: computed standard deviation}
3304 \cvarg{mask}{The optional operation mask}
3305 \end{description}
3306
3307 The functions \texttt{meanStdDev} compute the mean and the standard deviation \texttt{M} of array elements, independently for each channel, and return it via the output parameters:
3308
3309 \[
3310 \begin{array}{l}
3311 N = \sum_{I, \texttt{mask}(I) \ne 0} 1\\
3312 \texttt{mean}_c = \frac{\sum_{ I: \; \texttt{mask}(I) \ne 0} \texttt{src}(I)_c}{N}\\
3313 \texttt{stddev}_c = \sqrt{\sum_{ I: \; \texttt{mask}(I) \ne 0} \left(\texttt{src}(I)_c - \texttt{mean}_c\right)^2}
3314 \end{array}
3315 \]
3316
3317 When all the mask elements are 0's, the functions return \texttt{mean=stddev=Scalar::all(0)}.
3318 Note that the computed standard deviation is only the diagonal of the complete normalized covariance matrix. If the full matrix is needed, you can reshape the multi-channel array $M \times N$ to the single-channel array $M*N \times \texttt{mtx.channels}()$ (only possible when the matrix is continuous) and then pass the matrix to \cross{calcCovarMatrix}.
3319
3320 See also: \cross{countNonZero}, \cross{mean}, \cross{norm}, \cross{minMaxLoc}, \cross{calcCovarMatrix}
3321
3322
3323 \cvfunc{merge}\label{merge}
3324 Composes a multi-channel array from several single-channel arrays.
3325
3326 \begin{lstlisting}
3327 void merge(const Mat* mv, size_t count, Mat& dst);
3328 void merge(const vector<Mat>& mv, Mat& dst);
3329 void merge(const MatND* mv, size_t count, MatND& dst);
3330 void merge(const vector<MatND>& mv, MatND& dst);
3331 \end{lstlisting}
3332 \begin{description}
3333 \cvarg{mv}{The source array or vector of the single-channel matrices to be merged. All the matrices in \texttt{mv} must have the same size and the same type}
3334 \cvarg{count}{The number of source matrices when \texttt{mv} is a plain C array; must be greater than zero}
3335 \cvarg{dst}{The destination array; will have the same size and the same depth as \texttt{mv[0]}, the number of channels will match the number of source matrices}
3336 \end{description}
3337     
3338 The functions \texttt{merge} merge several single-channel arrays (or rather interleave their elements) to make a single multi-channel array.
3339
3340 \[\texttt{dst}(I)_c = \texttt{mv}[c](I)\]
3341
3342 The function \cross{split} does the reverse operation and if you need to merge several multi-channel images or shuffle channels in some other advanced way, use \cross{mixChannels}
3343
3344 See also: \cross{mixChannels}, \cross{split}, \cross{reshape}
3345
3346 \cvfunc{min}\label{min}
3347 Calculates per-element minimum of two arrays or array and a scalar
3348
3349 \begin{lstlisting}
3350 Mat_Expr<...> min(const Mat& src1, const Mat& src2);
3351 Mat_Expr<...> min(const Mat& src1, double value);
3352 Mat_Expr<...> min(double value, const Mat& src1);
3353 void min(const Mat& src1, const Mat& src2, Mat& dst);
3354 void min(const Mat& src1, double value, Mat& dst);
3355 void min(const MatND& src1, const MatND& src2, MatND& dst);
3356 void min(const MatND& src1, double value, MatND& dst);
3357 \end{lstlisting}
3358 \begin{description}
3359 \cvarg{src1}{The first source array}
3360 \cvarg{src2}{The second source array of the same size and type as \texttt{src1}}
3361 \cvarg{value}{The real scalar value}
3362 \cvarg{dst}{The destination array; will have the same size and type as \texttt{src1}}
3363 \end{description}
3364
3365 The functions \texttt{min} compute per-element minimum of two arrays:
3366 \[\texttt{dst}(I)=\min(\texttt{src1}(I), \texttt{src2}(I))\]
3367 or array and a scalar:
3368 \[\texttt{dst}(I)=\min(\texttt{src1}(I), \texttt{value})\]
3369
3370 In the second variant, when the source array is multi-channel, each channel is compared with \texttt{value} independently.
3371
3372 The first 3 variants of the function listed above are actually a part of \cross{Matrix Expressions}, they return the expression object that can be further transformed, or assigned to a matrix, or passed to a function etc.
3373
3374 See also: \cross{max}, \cross{compare}, \cross{inRange}, \cross{minMaxLoc}, \cross{Matrix Expressions}
3375
3376 \cvfunc{minMaxLoc}\label{minMaxLoc}
3377 Finds global minimum and maximum in a whole array or sub-array
3378
3379 \begin{lstlisting}
3380 void minMaxLoc(const Mat& src, double* minVal,
3381                double* maxVal=0, Point* minLoc=0,
3382                Point* maxLoc=0, const Mat& mask=Mat());
3383 void minMaxLoc(const MatND& src, double* minVal,
3384                double* maxVal, int* minIdx=0, int* maxIdx=0,
3385                const MatND& mask=MatND());
3386 void minMaxLoc(const SparseMat& src, double* minVal,
3387                double* maxVal, int* minIdx=0, int* maxIdx=0);
3388 \end{lstlisting}
3389 \begin{description}
3390 \cvarg{src}{The source single-channel array}
3391 \cvarg{minVal}{Pointer to returned minimum value; \texttt{NULL} if not required}
3392 \cvarg{maxVal}{Pointer to returned maximum value; \texttt{NULL} if not required}
3393 \cvarg{minLoc}{Pointer to returned minimum location (in 2D case); \texttt{NULL} if not required}
3394 \cvarg{maxLoc}{Pointer to returned maximum location (in 2D case); \texttt{NULL} if not required}
3395 \cvarg{minIdx}{Pointer to returned minimum location (in nD case);
3396  \texttt{NULL} if not required, otherwise must point to an array of \texttt{src.dims} elements and the coordinates of minimum element in each dimensions will be stored sequentially there.}
3397 \cvarg{maxIdx}{Pointer to returned maximum location (in nD case); \texttt{NULL} if not required}
3398 \cvarg{mask}{The optional mask used to select a sub-array}
3399 \end{description}
3400
3401 The functions \texttt{ninMaxLoc} find minimum and maximum element values
3402 and their positions. The extremums are searched across the whole array, or,
3403 if \texttt{mask} is not \texttt{NULL}, in the specified array region.
3404
3405 The functions do not work with multi-channel arrays. If you need to find minimum or maximum elements across all the channels, use \cross{reshape} first to reinterpret the array as single-channel. Or you may extract the particular channel using \cross{extractImageCOI} or \cross{mixChannels} or \cross{split}.
3406
3407 in the case of a sparse matrix the minimum is found among non-zero elements only.
3408
3409 See also: \cross{max}, \cross{min}, \cross{compare}, \cross{inRange}, \cross{extractImageCOI}, \cross{mixChannels}, \cross{split}, \cross{reshape}.
3410
3411 \cvfunc{mixChannels}\label{mixChannels}
3412 Copies specified channels from input arrays to the specified channels of output arrays
3413
3414 \begin{lstlisting}
3415 void mixChannels(const Mat* srcv, int nsrc, Mat* dstv, int ndst,
3416                  const int* fromTo, size_t npairs);
3417 void mixChannels(const MatND* srcv, int nsrc, MatND* dstv, int ndst,
3418                  const int* fromTo, size_t npairs);
3419 void mixChannels(const vector<Mat>& srcv, vector<Mat>& dstv,
3420                  const int* fromTo, int npairs);
3421 void mixChannels(const vector<MatND>& srcv, vector<MatND>& dstv,
3422                  const int* fromTo, int npairs);
3423 \end{lstlisting}
3424 \begin{description}
3425 \cvarg{srcv}{The input array or vector of matrices.
3426 All the matrices must have the same size and the same depth}
3427 \cvarg{nsrc}{The number of elements in \texttt{srcv}}
3428 \cvarg{dstv}{The output array or vector of matrices.
3429 All the matrices \emph{must be allocated}, their size and depth must be the same as in \texttt{srcv[0]}}
3430 \cvarg{ndst}{The number of elements in \texttt{dstv}}
3431 \cvarg{fromTo}{The array of index pairs, specifying which channels are copied and where.
3432 \texttt{fromTo[k*2]} is the 0-based index of the input channel in \texttt{srcv} and
3433 \texttt{fromTo[k*2+1]} is the index of the output channel in \texttt{dstv}. Here the continuous channel numbering is used, that is,
3434 the first input image channels are indexed from \texttt{0} to \texttt{srcv[0].channels()-1}, the second input image channels are indexed from \texttt{srcv[0].channels()} to \texttt{srcv[0].channels() + srcv[1].channels()-1} etc., and the same for the output image channels.
3435 As a special case, when \texttt{fromTo[k*2]} is negative, the corresponding output channel is filled with zero.
3436 }
3437 \texttt{npairs}{The number of pairs. In the latter case the parameter is not passed explicitly, but computed as \texttt{srcv.size()} (=\texttt{dstv.size()})}
3438 \end{description}
3439
3440 The functions \texttt{mixChannels} provide an advanced mechanism for shuffling image channels. \cross{split} and \cross{merge} and some forms of \cross{cvtColor} are partial cases of \texttt{mixChannels}.
3441
3442 As an example, this code splits a 4-channel RGBA image into a 3-channel
3443 BGR (i.e. with R and B channels swapped) and separate alpha channel image:
3444
3445 \begin{lstlisting}
3446 Mat rgba( 100, 100, CV_8UC4, Scalar(1,2,3,4) );
3447 Mat bgr( rgba.rows, rgba.cols, CV_8UC3 );
3448 Mat alpha( rgba.rows, rgba.cols, CV_8UC1 );
3449
3450 // forming array of matrices is quite efficient operations,
3451 // because the matrix data is not copied, only the headers
3452 Mat out[] = { bgr, alpha };
3453 // rgba[0] -> bgr[2], rgba[1] -> bgr[1],
3454 // rgba[2] -> bgr[0], rgba[3] -> alpha[0]
3455 int from_to[] = { 0,2,  1,1,  2,0,  3,3 };
3456 mixChannels( &rgba, 1, out, 2, from_to, 4 );
3457 \end{lstlisting}
3458
3459 Note that, unlike many other new-style C++ functions in OpenCV (see the introduction section and \cross{Mat::create}),
3460 \texttt{mixChannels} requires the destination arrays be pre-allocated before calling the function.
3461
3462 See also: \cross{split}, \cross{merge}, \cross{cvtColor} 
3463
3464
3465 \cvfunc{mulSpectrums}\label{mulSpectrums}
3466 Performs per-element multiplication of two Fourier spectrums.
3467
3468 \begin{lstlisting}
3469 void mulSpectrums(const Mat& src1, const Mat& src2, Mat& dst,
3470                   int flags, bool conj=false);
3471 \end{lstlisting}
3472 \begin{description}
3473 \cvarg{src1}{The first source array}
3474 \cvarg{src2}{The second source array; must have the same size and the same type as \texttt{src1}}
3475 \cvarg{dst}{The destination array; will have the same size and the same type as \texttt{src1}}
3476 \cvarg{flags}{The same flags as passed to \cross{dft}; only the flag \texttt{DFT\_ROWS} is checked for}
3477 \cvarg{conj}{The optional flag that conjugate the second source array before the multiplication (true) or not (false)}
3478 \end{description}
3479
3480 The function \texttt{mulSpectrums} performs per-element multiplication of the two CCS-packed or complex matrices that are results of a real or complex Fourier transform.
3481
3482 The function, together with \cross{dft} and \cross{idft}, may be used to calculate convolution (pass \texttt{conj=false}) or correlation (pass \texttt{conj=false}) of two arrays rapidly. When the arrays are complex, they are simply multiplied (per-element) with optional conjugation of the second array elements. When the arrays are real, they assumed to be CCS-packed (see \cross{dft} for details).
3483
3484 \cvfunc{multiply}\label{multiply}
3485 Calculates the per-element scaled product of two arrays
3486
3487 \begin{lstlisting}
3488 void multiply(const Mat& src1, const Mat& src2, Mat& dst, double scale=1);
3489 void multiply(const MatND& src1, const MatND& src2, MatND& dst, double scale=1);
3490 \end{lstlisting}
3491 \begin{description}
3492 \cvarg{src1}{The first source array}
3493 \cvarg{src2}{The second source array of the same size and the same type as \texttt{src1}}
3494 \cvarg{dst}{The destination array; will have the same size and the same type as \texttt{src1}}
3495 \cvarg{scale}{The optional scale factor}
3496 \end{description}
3497
3498 The function \texttt{multiply} calculates the per-element product of two arrays:
3499
3500 \[
3501 \texttt{dst}(I)=\texttt{saturate}(\texttt{scale} \cdot \texttt{src1}(I) \cdot \texttt{src2}(I))
3502 \]
3503
3504 There is also \cross{Matrix Expressions}-friendly variant of the first function, see \cross{Mat::mul}.
3505
3506 If you are looking for a matrix product, not per-element product, see \cross{gemm}.
3507
3508 See also: \cross{add}, \cross{substract}, \cross{divide}, \cross{Matrix Expressions}, \cross{scaleAdd}, \cross{addWeighted}, \cross{accumulate}, \cross{accumulateProduct}, \cross{accumulateSquare}, \cross{Mat::convertTo}
3509
3510 \cvfunc{mulTransposed}\label{mulTransposed}
3511 Calculates the product of a matrix and its transposition.
3512
3513 \begin{lstlisting}
3514 void mulTransposed( const Mat& src, Mat& dst, bool aTa,
3515                     const Mat& delta=Mat(),
3516                     double scale=1, int rtype=-1 );
3517 \end{lstlisting}
3518 \begin{description}
3519 \cvarg{src}{The source matrix}
3520 \cvarg{dst}{The destination square matrix}
3521 \cvarg{aTa}{Specifies the multiplication ordering; see the description below}
3522 \cvarg{delta}{The optional delta matrix, subtracted from \texttt{src} before the multiplication. When the matrix is empty (\texttt{delta=Mat()}), it's assumed to be zero, i.e. nothing is subtracted, otherwise if it has the same size as \texttt{src}, then it's simply subtracted, otherwise it is "repeated" (see \cross{repeat}) to cover the full \texttt{src} and then subtracted. Type of the delta matrix, when it's not empty, must be the same as the type of created destination matrix, see the \texttt{rtype} description}
3523 \cvarg{scale}{The optional scale factor for the matrix product}
3524 \cvarg{rtype}{When it's negative, the destination matrix will have the same type as \texttt{src}. Otherwise, it will have \texttt{type=CV\_MAT\_DEPTH(rtype)}, which should be either \texttt{CV\_32F} or \texttt{CV\_64F}}
3525 \end{description}
3526
3527 The function \texttt{mulTransposed} calculates the product of \texttt{src} and its transposition:
3528 \[
3529 \texttt{dst}=\texttt{scale} (\texttt{src}-\texttt{delta})^T (\texttt{src}-\texttt{delta})
3530 \]
3531 if \texttt{aTa=true}, and
3532
3533 \[
3534 \texttt{dst}=\texttt{scale} (\texttt{src}-\texttt{delta}) (\texttt{src}-\texttt{delta})^T
3535 \]
3536
3537 otherwise. The function is used to compute covariance matrix and with zero delta can be used as a faster substitute for general matrix product $A*B$ when $B=A^T$.
3538
3539 See also: \cross{calcCovarMatrix}, \cross{gemm}, \cross{repeat}, \cross{reduce}
3540
3541
3542 \cvfunc{norm}\label{norm}
3543 Calculates absolute array norm, absolute difference norm, or relative difference norm.
3544
3545 \begin{lstlisting}
3546 double norm(const Mat& src1, int normType=NORM_L2);
3547 double norm(const Mat& src1, const Mat& src2, int normType=NORM_L2);
3548 double norm(const Mat& src1, int normType, const Mat& mask);
3549 double norm(const Mat& src1, const Mat& src2, int normType, const Mat& mask);
3550 double norm(const MatND& src1, int normType=NORM_L2, const MatND& mask=MatND());
3551 double norm(const MatND& src1, const MatND& src2,
3552             int normType=NORM_L2, const MatND& mask=MatND());
3553 double norm( const SparseMat& src, int normType );
3554 \end{lstlisting}
3555 \begin{description}
3556 \cvarg{src1}{The first source array}
3557 \cvarg{src2}{The second source array of the same size and the same type as \texttt{src1}}
3558 \cvarg{normType}{Type of the norm; see the discussion below}
3559 \cvarg{mask}{The optional operation mask}
3560 \end{description}
3561
3562 The functions \texttt{norm} calculate the absolute norm of \texttt{src1} (when there is no \texttt{src2}):
3563 \[
3564 norm = \forkthree
3565 {\|\texttt{src1}\|_{L_{\infty}}    = \max_I |\texttt{src1}(I)|}{if $\texttt{normType} = \texttt{NORM\_INF}$}
3566 {\|\texttt{src1}\|_{L_1} = \sum_I |\texttt{src1}(I)|}{if $\texttt{normType} = \texttt{NORM\_L1}$}
3567 {\|\texttt{src1}\|_{L_2} = \sqrt{\sum_I \texttt{src1}(I)^2}}{if $\texttt{normType} = \texttt{NORM\_L2}$}
3568 \]
3569
3570 or an absolute or relative difference norm if \texttt{src2} is there:
3571 \[
3572 norm = \forkthree
3573 {\|\texttt{src1}-\texttt{src2}\|_{L_{\infty}}    = \max_I |\texttt{src1}(I) - \texttt{src2}(I)|}{if $\texttt{normType} = \texttt{NORM\_INF}$}
3574 {\|\texttt{src1}-\texttt{src2}\|_{L_1} = \sum_I |\texttt{src1}(I) - \texttt{src2}(I)|}{if $\texttt{normType} = \texttt{NORM\_L1}$}
3575 {\|\texttt{src1}-\texttt{src2}\|_{L_2} = \sqrt{\sum_I (\texttt{src1}(I) - \texttt{src2}(I))^2}}{if $\texttt{normType} = \texttt{NORM\_L2}$}
3576 \]
3577
3578 or
3579
3580 \[
3581 norm = \forkthree
3582 {\frac{\|\texttt{src1}-\texttt{src2}\|_{L_{\infty}}    }{\|\texttt{src2}\|_{L_{\infty}}   }}{if $\texttt{normType} = \texttt{NORM\_RELATIVE\_INF}$}
3583 {\frac{\|\texttt{src1}-\texttt{src2}\|_{L_1} }{\|\texttt{src2}\|_{L_1}}}{if $\texttt{normType} = \texttt{NORM\_RELATIVE\_L1}$}
3584 {\frac{\|\texttt{src1}-\texttt{src2}\|_{L_2} }{\|\texttt{src2}\|_{L_2}}}{if $\texttt{normType} = \texttt{NORM\_RELATIVE\_L2}$}
3585 \]
3586
3587 The functions \texttt{norm} return the calculated norm.
3588
3589 When there is \texttt{mask} parameter, and it is not empty (then it should have type \texttt{CV\_8U} and the same size as \texttt{src1}), the norm is computed only over the specified by the mask region.
3590
3591 A multiple-channel source arrays are treated as a single-channel, that is, the results for all channels are combined.
3592
3593
3594 \cvfunc{normalize}\label{normalize}
3595 Normalizes array's norm or the range
3596
3597 \begin{lstlisting}
3598 void normalize( const Mat& src, Mat& dst, double alpha=1, double beta=0,
3599                 int normType=NORM_L2, int rtype=-1, const Mat& mask=Mat());
3600 void normalize( const MatND& src, MatND& dst, double alpha=1, double beta=0,
3601                 int normType=NORM_L2, int rtype=-1, const MatND& mask=MatND());
3602 void normalize( const SparseMat& src, SparseMat& dst, double alpha, int normType );
3603 \end{lstlisting}
3604 \begin{description}
3605 \cvarg{src}{The source array}
3606 \cvarg{dst}{The destination array; will have the same size as \texttt{src}}
3607 \cvarg{alpha}{The norm value to normalize to or the lower range boundary in the case of range normalization}
3608 \cvarg{beta}{The upper range boundary in the case of range normalization; not used for norm normalization}
3609 \cvarg{normType}{The normalization type, see the discussion}
3610 \cvarg{rtype}{When the parameter is negative, the destination array will have the same type as \texttt{src}, otherwise it will have the same number of channels as \texttt{src} and the depth\texttt{=CV\_MAT\_DEPTH(rtype)}}
3611 \cvarg{mask}{The optional operation mask}
3612 \end{description}
3613
3614 The functions \texttt{normalize} scale and shift the source array elements, so that
3615 \[\|\texttt{dst}\|_{L_p}=\texttt{alpha}\]
3616 (where $p=\infty$, 1 or 2) when \texttt{normType=NORM\_INF}, \texttt{NORM\_L1} or \texttt{NORM\_L2},
3617 or so that
3618 \[\min_I \texttt{dst}(I)=\texttt{alpha},\,\,\max_I \texttt{dst}(I)=\texttt{beta}\]
3619 when \texttt{normType=NORM\_MINMAX} (for dense arrays only).
3620
3621 The optional mask specifies the sub-array to be normalize, that is, the norm or min-n-max are computed over the sub-array and then this sub-array is modified to be normalized. If you want to only use the mask to compute the norm or min-max, but modify the whole array, you can use \cross{norm} and \cross{Mat::convertScale}/\cross{MatND::convertScale}/cross{SparseMat::convertScale} separately.
3622
3623 in the case of sparse matrices, only the non-zero values are analyzed and transformed. Because of this, the range transformation for sparse matrices is not allowed, since it can shift the zero level. 
3624
3625 See also: \cross{norm}, \cross{Mat::convertScale}, \cross{MatND::convertScale}, \cross{SparseMat::convertScale}
3626
3627
3628 \cvfunc{PCA}\label{PCA}
3629 Class for Principal Component Analysis
3630
3631 \begin{lstlisting}
3632 class PCA
3633 {
3634 public:
3635     // default constructor
3636     PCA();
3637     // computes PCA for a set of vectors stored as data rows or columns.
3638     PCA(const Mat& data, const Mat& mean, int flags, int maxComponents=0);
3639     // computes PCA for a set of vectors stored as data rows or columns
3640     PCA& operator()(const Mat& data, const Mat& mean, int flags, int maxComponents=0);
3641     // projects vector into the principal components space
3642     Mat project(const Mat& vec) const;
3643     void project(const Mat& vec, Mat& result) const;
3644     // reconstructs the vector from its PC projection
3645     Mat backProject(const Mat& vec) const;
3646     void backProject(const Mat& vec, Mat& result) const;
3647
3648     // eigenvectors of the PC space, stored as the matrix rows
3649     Mat eigenvectors;
3650     // the corresponding eigenvalues; not used for PCA compression/decompression
3651     Mat eigenvalues;
3652     // mean vector, subtracted from the projected vector
3653     // or added to the reconstructed vector
3654     Mat mean;
3655 };
3656 \end{lstlisting}
3657
3658 The class \texttt{PCA} is used to compute the special basis for a set of vectors. The basis will consist of eigenvectors of the covariance matrix computed from the input set of vectors. And also the class \texttt{PCA} can transform vectors to/from the new coordinate space, defined by the basis. Usually, in this new coordinate system each vector from the original set (and any linear combination of such vectors) can be quite accurately approximated by taking just the first few its components, corresponding to the eigenvectors of the largest eigenvalues of the covariance matrix. Geometrically it means that we compute projection of the vector to a subspace formed by a few eigenvectors corresponding to the dominant eigenvalues of the covariation matrix. And usually such a projection is very close to the original vector. That is, we can represent the original vector from a high-dimensional space with a much shorter vector consisting of the projected vector's coordinates in the subspace. Such a transformation is also known as Karhunen-Loeve Transform, or KLT. See \url{http://en.wikipedia.org/wiki/Principal\_component\_analysis}
3659
3660 The following sample is the function that takes two matrices. The first one stores the set of vectors (a row per vector) that is used to compute PCA, the second one stores another "test" set of vectors (a row per vector) that are first compressed with PCA, then reconstructed back and then the reconstruction error norm is computed and printed for each vector.
3661 \begin{lstlisting}
3662 PCA compressPCA(const Mat& pcaset, int maxComponents,
3663                 const Mat& testset, Mat& compressed)
3664 {
3665     PCA pca(pcaset, // pass the data
3666             Mat(), // we do not have a pre-computed mean vector,
3667                    // so let the PCA engine to compute it
3668             CV_PCA_DATA_AS_ROW, // indicate that the vectors
3669                                 // are stored as matrix rows
3670                                 // (use CV_PCA_DATA_AS_COL if the vectors are
3671                                 // the matrix columns)
3672             maxComponents // specify, how many principal components to retain
3673             );
3674     // if there is no test data, just return the computed basis, ready-to-use
3675     if( !testset.data )
3676         return pca;
3677     CV_Assert( testset.cols == pcaset.cols );
3678
3679     compressed.create(testset.rows, maxComponents, testset.type());
3680
3681     Mat reconstructed;
3682     for( int i = 0; i < testset.rows; i++ )
3683     {
3684         Mat vec = testset.row(i), coeffs = compressed.row(i);
3685         // compress the vector, the result will be stored
3686         // in the i-th row of the output matrix
3687         pca.project(vec, coeffs);
3688         // and then reconstruct it
3689         pca.backProject(coeffs, reconstructed);
3690         // and measure the error
3691         printf("%d. diff = %g\n", i, norm(vec, reconstructed, NORM_L2));
3692     }
3693     return pca;
3694 }
3695 \end{lstlisting}
3696
3697 See also: \cross{calcCovarMatrix}, \cross{mulTransposed}, \cross{SVD}, \cross{dft}, \cross{dct}
3698
3699 \cvfunc{perspectiveTransform}\label{perspectiveTransform}
3700 Performs perspective matrix transformation of vectors.
3701
3702 \begin{lstlisting}
3703 void perspectiveTransform(const Mat& src, Mat& dst, const Mat& mtx );
3704 \end{lstlisting}
3705 \begin{description}
3706 \cvarg{src}{The source two-channel or three-channel floating-point array;
3707             each element is 2D/3D vector to be transformed}
3708 \cvarg{dst}{The destination array; it will have the same size and same type as \texttt{src}}
3709 \cvarg{mtx}{$3\times 3$ or $4 \times 4$ transformation matrix}
3710 \end{description}
3711
3712 The function \texttt{perspectiveTransform} transforms every element of \texttt{src},
3713 by treating it as 2D or 3D vector, in the following way (here 3D vector transformation is shown; in the case of 2D vector transformation the $z$ component is omitted):
3714
3715 \[ (x, y, z) \rightarrow (x'/w, y'/w, z'/w) \]
3716
3717 where
3718
3719 \[
3720 (x', y', z', w') = \texttt{mat} \cdot
3721 \begin{bmatrix} x & y & z & 1 \end{bmatrix}
3722 \]
3723
3724 and
3725 \[ w = \fork{w'}{if $w' \ne 0$}{\infty}{otherwise} \]
3726
3727 Note that the function transforms a sparse set of 2D or 3D vectors. If you want to transform an image using perspective transformation, use \cross{warpPerspective}. If you have an inverse task, i.e. want to compute the most probable perspective transformation out of several pairs of corresponding points, you can use \cross{getPerspectiveTransform} or \cross{findHomography}.
3728
3729 See also: \cross{transform}, \cross{warpPerspective}, \cross{getPerspectiveTransform}, \cross{findHomography}
3730
3731 \cvfunc{phase}\label{phase}
3732 Calculates the rotation angle of 2d vectors
3733
3734 \begin{lstlisting}
3735 void phase(const Mat& x, const Mat& y, Mat& angle,
3736            bool angleInDegrees=false);
3737 \end{lstlisting}
3738 \begin{description}
3739 \cvarg{x}{The source floating-point array of x-coordinates of 2D vectors}
3740 \cvarg{y}{The source array of y-coordinates of 2D vectors; must have the same size and the same type as \texttt{x}}
3741 \cvarg{angle}{The destination array of vector angles; it will have the same size and same type as \texttt{x}}
3742 \cvarg{angleInDegrees}{When it is true, the function will compute angle in degrees, otherwise they will be measured in radians}
3743 \end{description}
3744
3745 The function \texttt{phase} computes the rotation angle of each 2D vector that is formed from the corresponding elements of \texttt{x} and \texttt{y}:
3746
3747 \[\texttt{angle}(I) = \texttt{atan2}(\texttt{y}(I), \texttt{x}(I))\]
3748
3749 The angle estimation accuracy is $\sim\,0.3^\circ$, when \texttt{x(I)=y(I)=0}, the corresponding \texttt{angle}(I) is set to $0$.
3750
3751 See also:
3752
3753 \cvfunc{polarToCart}\label{polarToCart}
3754 Computes x and y coordinates of 2D vectors from their magnitude and angle.
3755
3756 \begin{lstlisting}
3757 void polarToCart(const Mat& magnitude, const Mat& angle,
3758                  Mat& x, Mat& y, bool angleInDegrees=false);
3759 \end{lstlisting}
3760 \begin{description}
3761 \cvarg{magnitude}{The source floating-point array of magnitudes of 2D vectors. It can be an empty matrix (\texttt{=Mat()}) - in this case the function assumes that all the magnitudes are =1. If it's not empty, it must have the same size and same type as \texttt{angle}}
3762 \cvarg{angle}{The source floating-point array of angles of the 2D vectors}
3763 \cvarg{x}{The destination array of x-coordinates of 2D vectors; will have the same size and the same type as \texttt{angle}}
3764 \cvarg{y}{The destination array of y-coordinates of 2D vectors; will have the same size and the same type as \texttt{angle}}
3765 \cvarg{angleInDegrees}{When it is true, the input angles are measured in degrees, otherwise they are measured in radians}
3766 \end{description}
3767
3768 The function \texttt{polarToCart} computes the cartesian coordinates of each 2D vector represented by the corresponding elements of \texttt{magnitude} and \texttt{angle}:
3769
3770 \[
3771 \begin{array}{l}
3772 \texttt{x}(I) = \texttt{magnitude}(I)\cos(\texttt{angle}(I))\\
3773 \texttt{y}(I) = \texttt{magnitude}(I)\sin(\texttt{angle}(I))\\
3774 \end{array}
3775 \]
3776
3777 The relative accuracy of the estimated coordinates is $\sim\,10^{-6}$.
3778
3779 See also: \cross{cartToPolar}, \cross{magnitude}, \cross{phase}, \cross{exp}, \cross{log}, \cross{pow}, \cross{sqrt}
3780
3781 \cvfunc{pow}\label{pow}
3782 Raises every array element to a power.
3783
3784 \begin{lstlisting}
3785 void pow(const Mat& src, double p, Mat& dst);
3786 void pow(const MatND& src, double p, MatND& dst);
3787 \end{lstlisting}
3788 \begin{description}
3789 \cvarg{src}{The source array}
3790 \cvarg{p}{The exponent of power}
3791 \cvarg{dst}{The destination array; will have the same size and the same type as \texttt{src}}
3792 \end{description}
3793
3794 The function \texttt{pow} raises every element of the input array to \texttt{p}:
3795
3796 \[
3797 \texttt{dst}(I) = \fork
3798 {\texttt{src}(I)^p}{if \texttt{p} is integer}
3799 {|\texttt{src}(I)|^p}{otherwise}
3800 \]
3801
3802 That is, for a non-integer power exponent the absolute values of input array elements are used. However, it is possible to get true values for negative values using some extra operations, as the following example, computing the 5th root of array \texttt{src}, shows:
3803
3804 \begin{lstlisting}
3805 Mat mask = src < 0;
3806 pow(src, 5, dst);
3807 subtract(Scalar::all(0), dst, dst, mask);
3808 \end{lstlisting}
3809
3810 For some values of \texttt{p}, such as integer values, 0.5, and -0.5, specialized faster algorithms are used.
3811
3812 See also: \cross{sqrt}, \cross{exp}, \cross{log}, \cross{cartToPolar}, \cross{polarToCart}
3813
3814 \cvfunc{randu}\label{randu}
3815 Generates a single uniformly-distributed random number or array of random numbers
3816
3817 \begin{lstlisting}
3818 template<typename _Tp> _Tp randu();
3819 void randu(Mat& mtx, const Scalar& low, const Scalar& high);
3820 \end{lstlisting}
3821 \begin{description}
3822 \cvarg{mtx}{The output array of random numbers. The array must be pre-allocated and have 1 to 4 channels}
3823 \cvarg{low}{The inclusive lower boundary of the generated random numbers}
3824 \cvarg{high}{The exclusive upper boundary of the generated random numbers}
3825 \end{description}
3826
3827 The template functions \texttt{randu} generate and return the next uniformly-distributed random value of the specified type. \texttt{randu<int>()} is equivalent to \texttt{(int)theRNG();} etc. See \cross{RNG} description.
3828
3829 The second non-template variant of the function fills the matrix \texttt{mtx} with uniformly-distributed random numbers from the specified range:
3830
3831 \[\texttt{low}_c \leq \texttt{mtx}(I)_c < \texttt{high}_c\]
3832
3833 See also: \cross{RNG}, \cross{randn}, \cross{theRNG}.
3834
3835 \cvfunc{randn}\label{randn}
3836 Fills array with normally distributed random numbers
3837
3838 \begin{lstlisting}
3839 void randn(Mat& mtx, const Scalar& mean, const Scalar& stddev);
3840 \end{lstlisting}
3841 \begin{description}
3842 \cvarg{mtx}{The output array of random numbers. The array must be pre-allocated and have 1 to 4 channels}
3843 \cvarg{mean}{The mean value (expectation) of the generated random numbers}
3844 \cvarg{stddev}{The standard deviation of the generated random numbers}
3845 \end{description}
3846
3847 The function \texttt{randn} fills the matrix \texttt{mtx} with normally distributed random numbers with the specified mean and standard deviation. \hyperref[saturatecast]{saturate\_cast} is applied to the generated numbers (i.e. the values are clipped)
3848
3849 See also: \cross{RNG}, \cross{randu}
3850
3851 \cvfunc{randShuffle}\label{randShuffle}
3852 Shuffles the array elements randomly
3853
3854 \begin{lstlisting}
3855 void randShuffle(Mat& mtx, double iterFactor=1., RNG* rng=0);
3856 \end{lstlisting}
3857 \begin{description}
3858 \cvarg{mtx}{The input/output numerical 1D array}
3859 \cvarg{iterFactor}{The scale factor that determines the number of random swap operations. See the discussion}
3860 \cvarg{rng}{The optional random number generator used for shuffling. If it is zero, \cross{theRNG}() is used instead}
3861 \end{description}
3862
3863 The function \texttt{randShuffle} shuffles the specified 1D array by randomly choosing pairs of elements and swapping them. The number of such swap operations will be \texttt{mtx.rows*mtx.cols*iterFactor}
3864
3865 See also: \cross{RNG}, \cross{sort}
3866
3867 \cvfunc{reduce}\label{reduce}
3868 Reduces a matrix to a vector
3869
3870 \begin{lstlisting}
3871 void reduce(const Mat& mtx, Mat& vec, int dim, int reduceOp, int dtype=-1);
3872 \end{lstlisting}
3873 \begin{description}
3874 \cvarg{mtx}{The source 2D matrix}
3875 \cvarg{vec}{The destination vector. Its size and type is defined by \texttt{dim} and \texttt{dtype} parameters}
3876 \cvarg{dim}{The dimension index along which the matrix is reduced. 0 means that the matrix is reduced to a single row and 1 means that the matrix is reduced to a single column}
3877 \cvarg{reduceOp}{The reduction operation, one of:
3878 \begin{description}
3879 \cvarg{CV\_REDUCE\_SUM}{The output is the sum of all of the matrix's rows/columns.}
3880 \cvarg{CV\_REDUCE\_AVG}{The output is the mean vector of all of the matrix's rows/columns.}
3881 \cvarg{CV\_REDUCE\_MAX}{The output is the maximum (column/row-wise) of all of the matrix's rows/columns.}
3882 \cvarg{CV\_REDUCE\_MIN}{The output is the minimum (column/row-wise) of all of the matrix's rows/columns.}
3883 \end{description}}
3884 \cvarg{dtype}{When it is negative, the destination vector will have the same type as the source matrix, otherwise, its type will be \texttt{CV\_MAKE\_TYPE(CV\_MAT\_DEPTH(dtype), mtx.channels())}}
3885 \end{description}
3886
3887 The function \texttt{reduce} reduces matrix to a vector by treating the matrix rows/columns as a set of 1D vectors and performing the specified operation on the vectors until a single row/column is obtained. For example, the function can be used to compute horizontal and vertical projections of an raster image. In the case of \texttt{CV\_REDUCE\_SUM} and \texttt{CV\_REDUCE\_AVG} the output may have a larger element bit-depth to preserve accuracy. And multi-channel arrays are also supported in these two reduction modes. 
3888
3889 See also: \cross{repeat}
3890
3891 \cvfunc{repeat}\label{repeat}
3892 Fill the destination array with repeated copies of the source array.
3893
3894 \begin{lstlisting}
3895 void repeat(const Mat& src, int ny, int nx, Mat& dst);
3896 Mat repeat(const Mat& src, int ny, int nx);
3897 \end{lstlisting}
3898 \begin{description}
3899 \cvarg{src}{The source array to replicate}
3900 \cvarg{dst}{The destination array; will have the same size as \texttt{src}}
3901 \cvarg{ny}{How many times the \texttt{src} is repeated along the vertical axis}
3902 \cvarg{nx}{How many times the \texttt{src} is repeated along the horizontal axis}
3903 \end{description}
3904
3905 The functions \cross{repeat} duplicate the source array one or more times along each of the two axes:
3906
3907 \[\texttt{dst}_{ij}=\texttt{src}_{i\mod\texttt{src.rows},\;j\mod\texttt{src.cols}}\]
3908
3909 The second variant of the function is more convenient to use with \cross{Matrix Expressions}
3910
3911 See also: \cross{reduce}, \cross{Matrix Expressions}
3912
3913 \cvfunc{saturate\_cast}\label{saturatecast}
3914 Template function for accurate conversion from one primitive type to another
3915
3916 \begin{lstlisting}
3917 template<typename _Tp> inline _Tp saturate_cast(unsigned char v);
3918 template<typename _Tp> inline _Tp saturate_cast(signed char v);
3919 template<typename _Tp> inline _Tp saturate_cast(unsigned short v);
3920 template<typename _Tp> inline _Tp saturate_cast(signed short v);
3921 template<typename _Tp> inline _Tp saturate_cast(int v);
3922 template<typename _Tp> inline _Tp saturate_cast(unsigned int v);
3923 template<typename _Tp> inline _Tp saturate_cast(float v);
3924 template<typename _Tp> inline _Tp saturate_cast(double v);
3925 \end{lstlisting}
3926 \begin{description}
3927 \cvarg{v}{The function parameter}
3928 \end{description}
3929
3930 The functions \texttt{saturate\_cast} resembles the standard C++ cast operations, such as \texttt{static\_cast<T>()} etc. They perform an efficient and accurate conversion from one primitive type to another, see the introduction. "saturate" in the name means that when the input value \texttt{v} is out of range of the target type, the result will not be formed just by taking low bits of the input, but instead the value will be clipped. For example:
3931
3932 \begin{lstlisting}
3933 uchar a = saturate_cast<uchar>(-100); // a = 0 (UCHAR_MIN)
3934 short b = saturate_cast<short>(33333.33333); // b = 32768 (SHRT_MAX)
3935 \end{lstlisting}
3936
3937 Such clipping is done when the target type is \texttt{unsigned char, signed char, unsigned short or signed short} - for 32-bit integers no clipping is done.
3938
3939 When the parameter is floating-point value and the target type is an integer (8-, 16- or 32-bit), the floating-point value is first rounded to the nearest integer and then clipped if needed (when the target type is 8- or 16-bit).
3940
3941 This operation is used in most simple or complex image processing functions in OpenCV.
3942
3943 See also: \cross{add}, \cross{subtract}, \cross{multiply}, \cross{divide}, \cross{Mat::convertTo}
3944
3945 \cvfunc{scaleAdd}\label{scaleAdd}
3946 Calculates the sum of a scaled array and another array.
3947
3948 \begin{lstlisting}
3949 void scaleAdd(const Mat& src1, double scale, const Mat& src2, Mat& dst);
3950 void scaleAdd(const MatND& src1, double scale, const MatND& src2, MatND& dst);
3951 \end{lstlisting}
3952 \begin{description}
3953 \cvarg{src1}{The first source array}
3954 \cvarg{scale}{Scale factor for the first array}
3955 \cvarg{src2}{The second source array; must have the same size and the same type as \texttt{src1}}
3956 \cvarg{dst}{The destination array; will have the same size and the same type as \texttt{src1}}
3957 \end{description}
3958
3959 The function \texttt{cvScaleAdd} is one of the classical primitive linear algebra operations, known as \texttt{DAXPY} or \texttt{SAXPY} in \href{http://en.wikipedia.org/wiki/Basic_Linear_Algebra_Subprograms}{BLAS}. It calculates the sum of a scaled array and another array:
3960
3961 \[
3962 \texttt{dst}(I)=\texttt{scale} \cdot \texttt{src1}(I) + \texttt{src2}(I)
3963 \]
3964
3965 The function can also be emulated with a matrix expression, for example:
3966
3967 \begin{lstlisting}
3968 Mat A(3, 3, CV_64F);
3969 ...
3970 A.row(0) = A.row(1)*2 + A.row(2);
3971 \end{lstlisting}
3972
3973 See also: \cross{add}, \cross{addWeighted}, \cross{subtract}, \cross{Mat::dot}, \cross{Mat::convertTo}, \cross{Matrix Expressions}
3974
3975 \cvfunc{setIdentity}\label{setIdentity}
3976 Initializes a scaled identity matrix
3977
3978 \begin{lstlisting}
3979 void setIdentity(Mat& dst, const Scalar& value=Scalar(1));
3980 \end{lstlisting}
3981 \begin{description}
3982 \cvarg{dst}{The matrix to initialize (not necessarily square)}
3983 \cvarg{value}{The value to assign to the diagonal elements}
3984 \end{description}
3985
3986 The function \cross{setIdentity} initializes a scaled identity matrix:
3987
3988 \[
3989 \texttt{dst}(i,j)=\fork{\texttt{value}}{ if $i=j$}{0}{otherwise}
3990 \]
3991
3992 The function can also be emulated using the matrix initializers and the matrix expressions:
3993 \begin{lstlisting}
3994 Mat A = Mat::eye(4, 3, CV_32F)*5;
3995 // A will be set to [[5, 0, 0], [0, 5, 0], [0, 0, 5], [0, 0, 0]]
3996 \end{lstlisting}
3997
3998 See also: \cross{Mat::zeros}, \cross{Mat::ones}, \cross{Matrix Expressions},
3999 \cross{Mat::setTo}, \cross{Mat::operator=},
4000
4001 \cvfunc{solve}\label{solve}
4002 Solves one or more linear systems or least-squares problems.
4003
4004 \begin{lstlisting}
4005 bool solve(const Mat& src1, const Mat& src2, Mat& dst, int flags=DECOMP_LU);
4006 \end{lstlisting}
4007 \begin{description}
4008 \cvarg{src1}{The input matrix on the left-hand side of the system}
4009 \cvarg{src2}{The input matrix on the right-hand side of the system}
4010 \cvarg{dst}{The output solution}
4011 \cvarg{flags}{The solution (matrix inversion) method
4012 \begin{description}
4013  \cvarg{DECOMP\_LU}{Gaussian elimination with optimal pivot element chosen}
4014  \cvarg{DECOMP\_CHOLESKY}{Cholesky $LL^T$ factorization; the matrix \texttt{src1} must be symmetrical and positively defined}
4015  \cvarg{DECOMP\_EIG}{Eigenvalue decomposition; the matrix \texttt{src1} must be symmetrical}
4016  \cvarg{DECOMP\_SVD}{Singular value decomposition (SVD) method; the system can be over-defined and/or the matrix \texttt{src1} can be singular}
4017  \cvarg{DECOMP\_QR}{QR factorization; the system can be over-defined and/or the matrix \texttt{src1} can be singular}
4018  \cvarg{DECOMP\_NORMAL}{While all the previous flags are mutually exclusive, this flag can be used together with any of the previous. It means that the normal equations $\texttt{src1}^T\cdot\texttt{src1}\cdot\texttt{dst}=\texttt{src1}^T\texttt{src2}$ are solved instead of the original system $\texttt{src1}\cdot\texttt{dst}=\texttt{src2}$}
4019 \end{description}}
4020 \end{description}
4021
4022 The function \texttt{solve} solves a linear system or least-squares problem (the latter is possible with SVD or QR methods, or by specifying the flag \texttt{DECOMP\_NORMAL}):
4023
4024 \[
4025 \texttt{dst} = \arg \min_X\|\texttt{src1}\cdot\texttt{X} - \texttt{src2}\|
4026 \]
4027
4028 If \texttt{DECOMP\_LU} or \texttt{DECOMP\_CHOLESKY} method is used, the function returns 1 if \texttt{src1} (or $\texttt{src1}^T\texttt{src1}$) is non-singular and 0 otherwise; in the latter case \texttt{dst} is not valid. Other methods find some pseudo-solution in the case of singular left-hand side part.
4029
4030 Note that if you want to find unity-norm solution of an under-defined singular system $\texttt{src1}\cdot\texttt{dst}=0$, the function \texttt{solve} will not do the work. Use \cross{SVD::solveZ} instead.
4031
4032 See also: \cross{invert}, \cross{SVD}, \cross{eigen}
4033
4034 \cvfunc{solveCubic}\label{solveCubic}
4035 Finds the real roots of a cubic equation.
4036
4037 \begin{lstlisting}
4038 void solveCubic(const Mat& coeffs, Mat& roots);
4039 \end{lstlisting}
4040 \begin{description}
4041 \cvarg{coeffs}{The equation coefficients, an array of 3 or 4 elements}
4042 \cvarg{roots}{The destination array of real roots which will have 1 or 3 elements}
4043 \end{description}
4044
4045 The function \texttt{solveCubic} finds the real roots of a cubic equation:
4046
4047 (if coeffs is a 4-element vector)
4048
4049 \[
4050 \texttt{coeffs}[0] x^3 + \texttt{coeffs}[1] x^2 + \texttt{coeffs}[2] x + \texttt{coeffs}[3] = 0
4051 \]
4052
4053 or (if coeffs is 3-element vector):
4054
4055 \[
4056 x^3 + \texttt{coeffs}[0] x^2 + \texttt{coeffs}[1] x + \texttt{coeffs}[2] = 0
4057 \]
4058
4059 The roots are stored to \texttt{roots} array.
4060
4061 \cvfunc{solvePoly}\label{solvePoly}
4062 Finds the real or complex roots of a polynomial equation
4063
4064 \begin{lstlisting}
4065 void solvePoly(const Mat& coeffs, Mat& roots, int maxIters=20, int fig=100);
4066 \end{lstlisting}
4067 \begin{description}
4068 \cvarg{coeffs}{The array of polynomial coefficients}
4069 \cvarg{roots}{The destination (complex) array of roots}
4070 \cvarg{maxIters}{The maximum number of iterations the algorithm does}
4071 \cvarg{fig}{}
4072 \end{description}
4073
4074 The function \texttt{solvePoly} finds real and complex roots of a polynomial equation:
4075 \[
4076 \texttt{coeffs}[0] x^{n} + \texttt{coeffs}[1] x^{n-1} + ... + \texttt{coeffs}[n-1] x + \texttt{coeffs}[n] = 0
4077 \]
4078
4079 \cvfunc{sort}\label{sort}
4080 Sorts each row or each column of a matrix
4081
4082 \begin{lstlisting}
4083 void sort(const Mat& src, Mat& dst, int flags);
4084 \end{lstlisting}
4085 \begin{description}
4086 \cvarg{src}{The source single-channel array}
4087 \cvarg{dst}{The destination array of the same size and the same type as \texttt{src}}
4088 \cvarg{flags}{The operation flags, a combination of the following values:
4089 \begin{description}
4090     \cvarg{CV\_SORT\_EVERY\_ROW}{Each matrix row is sorted independently}
4091     \cvarg{CV\_SORT\_EVERY\_COLUMN}{Each matrix column is sorted independently. This flag and the previous one are mutually exclusive}
4092     \cvarg{CV\_SORT\_ASCENDING}{Each matrix row is sorted in the ascending order}
4093     \cvarg{CV\_SORT\_DESCENDING}{Each matrix row is sorted in the descending order. This flag and the previous one are also mutually exclusive}
4094 \end{description}}
4095 \end{description}
4096
4097 The function \texttt{sort} sorts each matrix row or each matrix column in ascending or descending order. If you want to sort matrix rows or columns lexicographically, you can use STL \texttt{std::sort} generic function with the proper comparison predicate.
4098
4099 See also: \cross{sortIdx}, \cross{randShuffle}
4100
4101 \cvfunc{sortIdx}\label{sortIdx}
4102 Sorts each row or each column of a matrix
4103
4104 \begin{lstlisting}
4105 void sortIdx(const Mat& src, Mat& dst, int flags);
4106 \end{lstlisting}
4107 \begin{description}
4108 \cvarg{src}{The source single-channel array}
4109 \cvarg{dst}{The destination integer array of the same size as \texttt{src}}
4110 \cvarg{flags}{The operation flags, a combination of the following values:
4111 \begin{description}
4112     \cvarg{CV\_SORT\_EVERY\_ROW}{Each matrix row is sorted independently}
4113     \cvarg{CV\_SORT\_EVERY\_COLUMN}{Each matrix column is sorted independently. This flag and the previous one are mutually exclusive}
4114     \cvarg{CV\_SORT\_ASCENDING}{Each matrix row is sorted in the ascending order}
4115     \cvarg{CV\_SORT\_DESCENDING}{Each matrix row is sorted in the descending order. This flag and the previous one are also mutually exclusive}
4116 \end{description}}
4117 \end{description}
4118
4119 The function \texttt{sortIdx} sorts each matrix row or each matrix column in ascending or descending order. Instead of reordering the elements themselves, it stores the indices of sorted elements in the destination array. For example:
4120
4121 \begin{lstlisting}
4122 Mat A = Mat::eye(3,3,CV_32F), B;
4123 sortIdx(A, B, CV_SORT_EVERY_ROW + CV_SORT_ASCENDING);
4124 // B will probably contain
4125 // (because of equal elements in A some permutations are possible):
4126 // [[1, 2, 0], [0, 2, 1], [0, 1, 2]]
4127 \end{lstlisting}
4128
4129 See also: \cross{sort}, \cross{randShuffle}
4130
4131 \cvfunc{split}\label{split}
4132 Divides multi-channel array into several single-channel arrays
4133
4134 \begin{lstlisting}
4135 void split(const Mat& mtx, Mat* mv);
4136 void split(const Mat& mtx, vector<Mat>& mv);
4137 void split(const MatND& mtx, MatND* mv);
4138 void split(const MatND& mtx, vector<MatND>& mv);
4139 \end{lstlisting}
4140 \begin{description}
4141 \cvarg{mtx}{The source multi-channel array}
4142 \cvarg{mv}{The destination array or vector of arrays; The number of arrays must match \texttt{mtx.channels()}. The arrays themselves will be reallocated if needed}
4143 \end{description}
4144
4145 The functions \texttt{split} split multi-channel array into separate single-channel arrays:
4146
4147 \[ \texttt{mv}[c](I) = \texttt{mtx}(I)_c \]
4148
4149 If you need to extract a single-channel or do some other sophisticated channel permutation, use \cross{mixChannels}
4150
4151 See also: \cross{merge}, \cross{mixChannels}, \cross{cvtColor}
4152
4153 \cvfunc{sqrt}\label{sqrt}
4154 Calculates square root of array elements
4155
4156 \begin{lstlisting}
4157 void sqrt(const Mat& src, Mat& dst);
4158 void sqrt(const MatND& src, MatND& dst);
4159 \end{lstlisting}
4160 \begin{description}
4161 \cvarg{src}{The source floating-point array}
4162 \cvarg{dst}{The destination array; will have the same size and the same type as \texttt{src}}
4163 \end{description}
4164
4165 The functions \texttt{sqrt} calculate square root of each source array element. in the case of multi-channel arrays each channel is processed independently. The function accuracy is approximately the same as of the built-in \texttt{std::sqrt}.
4166
4167 See also: \cross{pow}, \cross{magnitude}
4168
4169 \cvfunc{subtract}\label{subtract}
4170 Calculates per-element difference between two arrays or array and a scalar
4171
4172 \begin{lstlisting}
4173 void subtract(const Mat& src1, const Mat& src2, Mat& dst);
4174 void subtract(const Mat& src1, const Mat& src2, Mat& dst, const Mat& mask);
4175 void subtract(const Mat& src1, const Scalar& sc, Mat& dst, const Mat& mask=Mat());
4176 void subtract(const Scalar& sc, const Mat& src2, Mat& dst, const Mat& mask=Mat());
4177 void subtract(const MatND& src1, const MatND& src2, MatND& dst);
4178 void subtract(const MatND& src1, const MatND& src2, MatND& dst, const MatND& mask);
4179 void subtract(const MatND& src1, const Scalar& sc, MatND& dst, const MatND& mask=MatND());
4180 void subtract(const Scalar& sc, const MatND& src2, MatND& dst, const MatND& mask=MatND());
4181 \end{lstlisting}
4182 \begin{description}
4183 \cvarg{src1}{The first source array}
4184 \cvarg{src2}{The second source array. It must have the same size and same type as \texttt{src1}}
4185 \cvarg{sc}{Scalar; the first or the second input parameter}
4186 \cvarg{dst}{The destination array; it will have the same size and same type as \texttt{src1}; see \texttt{Mat::create}}
4187 \cvarg{mask}{The optional operation mask, 8-bit single channel array;
4188              specifies elements of the destination array to be changed}
4189 \end{description}
4190
4191 The functions \texttt{subtract} compute
4192
4193 \begin{itemize}
4194     \item the difference between two arrays
4195     \[\texttt{dst}(I) = \texttt{saturate}(\texttt{src1}(I) - \texttt{src2}(I))\quad\texttt{if mask}(I)\ne0\]
4196     \item the difference between array and a scalar:
4197     \[\texttt{dst}(I) = \texttt{saturate}(\texttt{src1}(I) - \texttt{sc})\quad\texttt{if mask}(I)\ne0\]
4198     \item the difference between scalar and an array:
4199     \[\texttt{dst}(I) = \texttt{saturate}(\texttt{sc} - \texttt{src2}(I))\quad\texttt{if mask}(I)\ne0\]
4200 \end{itemize}
4201
4202 where \texttt{I} is multi-dimensional index of array elements.
4203
4204 The first function in the above list can be replaced with matrix expressions:
4205 \begin{lstlisting}
4206 dst = src1 - src2;
4207 dst -= src2; // equivalent to subtract(dst, src2, dst);
4208 \end{lstlisting}
4209
4210 See also: \cross{add}, \cross{addWeighted}, \cross{scaleAdd}, \cross{convertScale},
4211 \cross{Matrix Expressions}, \hyperref[saturatecast]{saturate\_cast}.
4212
4213 \cvfunc{SVD}\label{SVD}
4214 Class for computing Singular Value Decomposition
4215
4216 \begin{lstlisting}
4217 class SVD
4218 {
4219 public:
4220     enum { MODIFY_A=1, NO_UV=2, FULL_UV=4 };
4221     // default empty constructor
4222     SVD();
4223     // decomposes m into u, w and vt: m = u*w*vt;
4224     // u and vt are orthogonal, w is diagonal
4225     SVD( const Mat& m, int flags=0 );
4226     // decomposes m into u, w and vt.
4227     SVD& operator ()( const Mat& m, int flags=0 );
4228
4229     // finds such vector x, norm(x)=1, so that m*x = 0,
4230     // where m is singular matrix
4231     static void solveZ( const Mat& m, Mat& dst );
4232     // does back-subsitution:
4233     // dst = vt.t()*inv(w)*u.t()*rhs ~ inv(m)*rhs
4234     void backSubst( const Mat& rhs, Mat& dst ) const;
4235
4236     Mat u, w, vt;
4237 };
4238 \end{lstlisting}
4239
4240 The class \texttt{SVD} is used to compute Singular Value Decomposition of a floating-point matrix and then use it to solve least-square problems, under-determined linear systems, invert matrices, compute condition numbers etc.
4241 For a bit faster operation you can pass \texttt{flags=SVD::MODIFY\_A|...} to modify the decomposed matrix when it is not necessarily to preserve it. If you want to compute condition number of a matrix or absolute value of its determinant - you do not need \texttt{u} and \texttt{vt}, so you can pass \texttt{flags=SVD::NO\_UV|...}. Another flag \texttt{FULL\_UV} indicates that full-size \texttt{u} and \texttt{vt} must be computed, which is not necessary most of the time.
4242
4243 See also: \cross{invert}, \cross{solve}, \cross{eigen}, \cross{determinant}
4244
4245 \cvfunc{sum}\label{sum}
4246 Calculates sum of array elements
4247
4248 \begin{lstlisting}
4249 Scalar sum(const Mat& mtx);
4250 Scalar sum(const MatND& mtx);
4251 \end{lstlisting}
4252 \begin{description}
4253 \cvarg{mtx}{The source array; must have 1 to 4 channels}
4254 \end{description}
4255
4256 The functions \texttt{sum} calculate and return the sum of array elements, independently for each channel.
4257
4258 See also: \cross{countNonZero}, \cross{mean}, \cross{meanStdDev}, \cross{norm}, \cross{minMaxLoc}, \cross{reduce}
4259
4260 \cvfunc{theRNG}\label{theRNG}
4261 Returns the default random number generator
4262
4263 \begin{lstlisting}
4264 RNG& theRNG();
4265 \end{lstlisting}
4266
4267 The function \texttt{theRNG} returns the default random number generator. For each thread there is separate random number generator, so you can use the function safely in multi-thread environments. If you just need to get a single random number using this generator or initialize an array, you can use \cross{randu} or \cross{randn} instead. But if you are going to generate many random numbers inside a loop, it will be much faster to use this function to retrieve the generator and then use \texttt{RNG::operator \_Tp()}.
4268
4269 See also: \cross{RNG}, \cross{randu}, \cross{randn}
4270
4271 \cvfunc{trace}\label{trace}
4272 Returns the trace of a matrix
4273
4274 \begin{lstlisting}
4275 Scalar trace(const Mat& mtx);
4276 \end{lstlisting}
4277 \begin{description}
4278 \cvarg{mtx}{The source matrix}
4279 \end{description}
4280
4281 The function \texttt{trace} returns the sum of the diagonal elements of the matrix \texttt{mtx}.
4282
4283 \[ \mathrm{tr}(\texttt{mtx}) = \sum_i \texttt{mtx}(i,i) \]
4284
4285
4286 \cvfunc{transform}\label{transform}
4287 Performs matrix transformation of every array element.
4288
4289 \begin{lstlisting}
4290 void transform(const Mat& src, Mat& dst, const Mat& mtx );
4291 \end{lstlisting}
4292 \begin{description}
4293 \cvarg{src}{The source array; must have as many channels (1 to 4) as \texttt{mtx.cols} or \texttt{mtx.cols-1}}
4294 \cvarg{dst}{The destination array; will have the same size and depth as \texttt{src} and as many channels as \texttt{mtx.rows}}
4295 \cvarg{mtx}{The transformation matrix}
4296 \end{description}
4297
4298 The function \texttt{transform} performs matrix transformation of every element of array \texttt{src} and stores the results in \texttt{dst}:
4299
4300 \[
4301 \texttt{dst}(I) = \texttt{mtx} \cdot \texttt{src}(I)
4302 \]
4303 (when \texttt{mtx.cols=src.channels()}), or
4304
4305 \[
4306 \texttt{dst}(I) = \texttt{mtx} \cdot [\texttt{src}(I); 1]
4307 \]
4308 (when \texttt{mtx.cols=src.channels()+1})
4309
4310 That is, every element of an \texttt{N}-channel array \texttt{src} is
4311 considered as \texttt{N}-element vector, which is transformed using
4312 a $\texttt{M} \times \texttt{N}$ or $\texttt{M} \times \texttt{N+1}$ matrix \texttt{mtx} into
4313 an element of \texttt{M}-channel array \texttt{dst}.
4314
4315 The function may be used for geometrical transformation of $N$-dimensional
4316 points, arbitrary linear color space transformation (such as various kinds of RGB$\rightarrow$YUV transforms), shuffling the image channels and so forth.
4317
4318 See also: \cross{perspectiveTransform}, \cross{getAffineTransform}, \cross{estimateRigidTransform}, \cross{warpAffine}, \cross{warpPerspective}
4319
4320 \cvfunc{transpose}\label{transpose}
4321 Transposes a matrix
4322
4323 \begin{lstlisting}
4324 void transpose(const Mat& src, Mat& dst);
4325 \end{lstlisting}
4326 \begin{description}
4327 \cvarg{src}{The source array}
4328 \cvarg{dst}{The destination array of the same type as \texttt{src}}
4329 \end{description}
4330
4331 The function \cross{transpose} transposes the matrix \texttt{src}:
4332
4333 \[ \texttt{dst}(i,j) = \texttt{src}(j,i) \]
4334
4335 Note that no complex conjugation is done in the case of a complex
4336 matrix, it should be done separately if needed.
4337
4338
4339 \subsection{Drawing Operations}
4340
4341 Drawing functions work with matrices/images of arbitrary depth.
4342 The boundaries of the shapes can be rendered with antialiasing (implemented only for 8-bit images for now).
4343 All the functions include the parameter color that uses a rgb value (that may be constructed
4344 with \texttt{CV\_RGB} macro or the \cross{Scalar} constructor) for color
4345 images and brightness for grayscale images. For color images the order channel
4346 is normally \emph{Blue, Green, Red}, this is what \cross{imshow}, \cross{imread} and \cross{imwrite} expect,
4347 so if you form a color using \cross{Scalar} constructor, it should look like:
4348
4349 \[\texttt{Scalar}(blue\_component, green\_component, red\_component[, alpha\_component])\]
4350
4351 If you are using your own image rendering and I/O functions, you can use any channel ordering, the drawing functions process each channel independently and do not depend on the channel order or even on the color space used. The whole image can be converted from BGR to RGB or to a different color space using \cross{cvtColor}.
4352
4353 If a drawn figure is partially or completely outside the image, the drawing functions clip it. Also, many drawing functions can handle pixel coordinates specified with sub-pixel accuracy, that is, the coordinates can be passed as fixed-point numbers, encoded as integers. The number of fractional bits is specified by the \texttt{shift} parameter and the real point coordinates are calculated as $\texttt{Point}(x,y)\rightarrow\texttt{Point2f}(x*2^{-shift},y*2^{-shift})$. This feature is especially effective wehn rendering antialiased shapes.
4354
4355 Also, note that the functions do not support alpha-transparency - when the target image is 4-channnel, then the \texttt{color[3]} is simply copied to the repainted pixels. Thus, if you want to paint semi-transparent shapes, you can paint them in a separate buffer and then blend it with the main image.
4356
4357 \cvfunc{circle}\label{circle}
4358 Draws a circle
4359
4360 \begin{lstlisting}
4361 void circle(Mat& img, Point center, int radius,
4362             const Scalar& color, int thickness=1,
4363             int lineType=8, int shift=0);
4364 \end{lstlisting}
4365 \begin{description}
4366 \cvarg{img}{Image where the circle is drawn}
4367 \cvarg{center}{Center of the circle}
4368 \cvarg{radius}{Radius of the circle}
4369 \cvarg{color}{Circle color}
4370 \cvarg{thickness}{Thickness of the circle outline if positive; negative thickness means that a filled circle is to be drawn}
4371 \cvarg{lineType}{Type of the circle boundary, see \cross{line} description}
4372 \cvarg{shift}{Number of fractional bits in the center coordinates and radius value}
4373 \end{description}
4374
4375 The function \texttt{circle} draws a simple or filled circle with a
4376 given center and radius.
4377
4378 \cvfunc{clipLine}\label{clipLine}
4379 Clips the line against the image rectangle
4380
4381 \begin{lstlisting}
4382 bool clipLine(Size imgSize, Point& pt1, Point& pt2);
4383 bool clipLine(Rect imgRect, Point& pt1, Point& pt2);
4384 \end{lstlisting}
4385 \begin{description}
4386 \cvarg{imgSize}{The image size; the image rectangle will be \texttt{Rect(0, 0, imgSize.width, imgSize.height)}}
4387 \cvarg{imgSize}{The image rectangle}
4388 \cvarg{pt1}{The first line point}
4389 \cvarg{pt2}{The second line point}
4390 \end{description}
4391
4392 The functions \texttt{clipLine} calculate a part of the line
4393 segment which is entirely within the specified rectangle.
4394 They return \texttt{false} if the line segment is completely outside the rectangle and \texttt{true} otherwise.
4395
4396
4397 \cvfunc{ellipse}\label{ellipse}
4398 Draws a simple or thick elliptic arc or an fills ellipse sector.
4399
4400 \begin{lstlisting}
4401 void ellipse(Mat& img, Point center, Size axes,
4402              double angle, double startAngle, double endAngle,
4403              const Scalar& color, int thickness=1,
4404              int lineType=8, int shift=0);
4405 void ellipse(Mat& img, const RotatedRect& box, const Scalar& color,
4406              int thickness=1, int lineType=8);
4407 \end{lstlisting}
4408 \begin{description}
4409 \cvarg{img}{The image}
4410 \cvarg{center}{Center of the ellipse}
4411 \cvarg{axes}{Length of the ellipse axes}
4412 \cvarg{angle}{The ellipse rotation angle in degrees}
4413 \cvarg{startAngle}{Starting angle of the elliptic arc in degrees}
4414 \cvarg{endAngle}{Ending angle of the elliptic arc in degrees}
4415 \cvarg{box}{Alternative ellipse representation via a \cross{RotatedRect}, i.e. the function draws an ellipse inscribed in the rotated rectangle}
4416 \cvarg{color}{Ellipse color}
4417 \cvarg{thickness}{Thickness of the ellipse arc outline if positive, otherwise this indicates that a filled ellipse sector is to be drawn}
4418 \cvarg{lineType}{Type of the ellipse boundary, see \cross{line} description}
4419 \cvarg{shift}{Number of fractional bits in the center coordinates and axes' values}
4420 \end{description}
4421
4422 The functions \texttt{ellipse} with less parameters draw an ellipse outline, a filled ellipse, an elliptic
4423 arc or a filled ellipse sector. 
4424 A piecewise-linear curve is used to approximate the elliptic arc boundary. If you need more control of the ellipse rendering, you can retrieve the curve using \cross{ellipse2Poly} and then render it with \cross{polylines} or fill it with \cross{fillPoly}. If you use the first variant of the function and want to draw the whole ellipse, not an arc, pass \texttt{startAngle=0} and \texttt{endAngle=360}. The picture below
4425 explains the meaning of the parameters.
4426
4427 Parameters of Elliptic Arc
4428
4429 \includegraphics[width=0.5\textwidth]{pics/ellipse.png}
4430
4431 \cvfunc{ellipse2Poly}\label{ellipse2Poly}
4432 Approximates an elliptic arc with a polyline
4433
4434 \begin{lstlisting}
4435 void ellipse2Poly( Point center, Size axes, int angle,
4436                    int startAngle, int endAngle, int delta,
4437                    vector<Point>& pts );
4438 \end{lstlisting}
4439 \begin{description}
4440 \cvarg{center}{Center of the arc}
4441 \cvarg{axes}{Half-sizes of the arc. See \cross{ellipse}}
4442 \cvarg{angle}{Rotation angle of the ellipse in degrees. See \cross{ellipse}}
4443 \cvarg{startAngle}{Starting angle of the elliptic arc in degrees}
4444 \cvarg{endAngle}{Ending angle of the elliptic arc in degrees}
4445 \cvarg{delta}{Angle between the subsequent polyline vertices. It defines the approximation accuracy.}
4446 \cvarg{pts}{The output vector of polyline vertices}
4447 \end{description}
4448
4449 The function \texttt{ellipse2Poly} computes the vertices of a polyline that approximates the specified elliptic arc. It is used by \cross{ellipse}.
4450
4451 \cvfunc{fillConvexPoly}\label{fillConvexPoly}
4452 Fills a convex polygon.
4453
4454 \begin{lstlisting}
4455 void fillConvexPoly(Mat& img, const Point* pts, int npts,
4456                     const Scalar& color, int lineType=8,
4457                     int shift=0);
4458 \end{lstlisting}
4459 \begin{description}
4460 \cvarg{img}{Image}
4461 \cvarg{pts}{The polygon vertices}
4462 \cvarg{npts}{The number of polygon vertices}
4463 \cvarg{color}{Polygon color}
4464 \cvarg{lineType}{Type of the polygon boundaries, see \cross{line} description}
4465 \cvarg{shift}{The number of fractional bits in the vertex coordinates}
4466 \end{description}
4467
4468 The function \texttt{fillConvexPoly} draws a filled convex polygon.
4469 This function is much faster than the function \texttt{fillPoly}
4470 and can fill not only convex polygons but any monotonic polygon without self-intersections,
4471 i.e., a polygon whose contour intersects every horizontal line (scan
4472 line) twice at the most (though, its top-most and/or the bottom edge could be horizontal).
4473
4474 \cvfunc{fillPoly}\label{fillPoly}
4475 Fills the area bounded by one or more polygons
4476
4477 \begin{lstlisting}
4478 void fillPoly(Mat& img, const Point** pts, const int* npts, int ncontours,
4479               const Scalar& color, int lineType=8, int shift=0,
4480               Point offset=Point() );
4481 \end{lstlisting}
4482 \begin{description}
4483 \cvarg{img}{Image}
4484 \cvarg{pts}{Array of polygons, each represented as an array of points}
4485 \cvarg{npts}{The array of polygon vertex counters}
4486 \cvarg{ncontours}{The number of contours that bind the filled region}
4487 \cvarg{color}{Polygon color}
4488 \cvarg{lineType}{Type of the polygon boundaries, see \cross{line} description}
4489 \cvarg{shift}{The number of fractional bits in the vertex coordinates}
4490 \end{description}
4491
4492 The function \texttt{fillPoly} fills an area bounded by several
4493 polygonal contours. The function can fills complex areas, for example,
4494 areas with holes, contours with self-intersections (some of thier parts), and so forth.
4495
4496 \cvfunc{getTextSize}\label{getTextSize}
4497 Calculates the width and height of a text string.
4498
4499 \begin{lstlisting}
4500 Size getTextSize(const string& text, int fontFace,
4501                  double fontScale, int thickness,
4502                  int* baseLine);
4503 \end{lstlisting}
4504 \begin{description}
4505 \cvarg{text}{The input text string}
4506 \cvarg{fontFace}{The font to use; see \cross{putText}}
4507 \cvarg{fontScale}{The font scale; see \cross{putText}}
4508 \cvarg{thickness}{The thickness of lines used to render the text; see \cross{putText}}
4509 \cvarg{baseLine}{The output parameter - y-coordinate of the baseline relative to the bottom-most text point}
4510 \end{description}
4511
4512 The function \texttt{getTextSize} calculates and returns size of the box that contain the specified text.
4513 That is, the following code will render some text, the tight box surrounding it and the baseline:
4514
4515 \begin{lstlisting}
4516 // Use "y" to show that the baseLine is about
4517 string text = "Funny text inside the box";
4518 int fontFace = FONT_HERSHEY_SCRIPT_SIMPLEX;
4519 double fontScale = 2;
4520 int thickness = 3;
4521
4522 Mat img(600, 800, CV_8UC3, Scalar::all(0));
4523
4524 int baseline=0;
4525 Size textSize = getTextSize(text, fontFace,
4526                             fontScale, thickness, &baseline);
4527 baseline += thickness;
4528
4529 // center the text
4530 Point textOrg((img.cols - textSize.width)/2,
4531               (img.rows + textSize.height)/2);
4532
4533 // draw the box
4534 rectangle(img, textOrg + Point(0, baseline),
4535           textOrg + Point(textSize.width, -textSize.height),
4536           Scalar(0,0,255));
4537 // ... and the baseline first
4538 line(img, textOrg + Point(0, thickness),
4539      textOrg + Point(textSize.width, thickness),
4540      Scalar(0, 0, 255));
4541
4542 // then put the text itself
4543 putText(img, text, textOrg, fontFace, fontScale,
4544         Scalar::all(255), thickness, 8);
4545 \end{lstlisting}
4546         
4547         
4548 \cvfunc{line}\label{line}
4549 Draws a line segment connecting two points
4550
4551 \begin{lstlisting}
4552 void line(Mat& img, Point pt1, Point pt2, const Scalar& color,
4553           int thickness=1, int lineType=8, int shift=0);
4554 \end{lstlisting}
4555 \begin{description}
4556 \cvarg{img}{The image}
4557 \cvarg{pt1}{First point of the line segment}
4558 \cvarg{pt2}{Second point of the line segment}
4559 \cvarg{color}{Line color}
4560 \cvarg{thickness}{Line thickness}
4561 \cvarg{lineType}{Type of the line:
4562   \begin{description}
4563   \cvarg{8}{(or omitted) 8-connected line.}
4564   \cvarg{4}{4-connected line.}
4565   \cvarg{CV\_AA}{antialiased line.}
4566   \end{description}}
4567 \cvarg{shift}{Number of fractional bits in the point coordinates}
4568 \end{description}
4569
4570 The function \texttt{line} draws the line segment between
4571 \texttt{pt1} and \texttt{pt2} points in the image. The line is
4572 clipped by the image boundaries. For non-antialiased lines
4573 with integer coordinates the 8-connected or 4-connected Bresenham
4574 algorithm is used. Thick lines are drawn with rounding endings.
4575 Antialiased lines are drawn using Gaussian filtering. To specify
4576 the line color, the user may use the macro
4577 \texttt{CV\_RGB(r, g, b)}.
4578
4579
4580 \cvfunc{LineIterator}\label{LineIterator}
4581 Class for iterating pixels on a raster line
4582
4583 \begin{lstlisting}
4584 class LineIterator
4585 {
4586 public:
4587     // creates iterators for the line connecting pt1 and pt2
4588     // the line will be clipped on the image boundaries
4589     // the line is 8-connected or 4-connected
4590     // If leftToRight=true, then the iteration is always done
4591     // from the left-most point to the right most,
4592     // not to depend on the ordering of pt1 and pt2 parameters
4593     LineIterator(const Mat& img, Point pt1, Point pt2,
4594                  int connectivity=8, bool leftToRight=false);
4595     // returns pointer to the current line pixel
4596     uchar* operator *();
4597     // move the iterator to the next pixel
4598     LineIterator& operator ++();
4599     LineIterator operator ++(int);
4600
4601     // internal state of the iterator
4602     uchar* ptr;
4603     int err, count;
4604     int minusDelta, plusDelta;
4605     int minusStep, plusStep;
4606 };
4607 \end{lstlisting}
4608
4609 The class \texttt{LineIterator} is used to get each pixel of a raster line. It can be treated as versatile implementation of the Bresenham algorithm, where you can stop at each pixel and do some extra processing, for example, grab pixel values along the line, or draw a line with some effect (e.g. with XOR operation).
4610
4611 The number of pixels along the line is store in \texttt{LineIterator::count}.
4612
4613 \begin{lstlisting}
4614 \\ grabs pixels along the line (pt1, pt2)
4615 \\ from 8-bit 3-channel image to the buffer
4616 LineIterator it(img, pt1, pt2, 8);
4617 vector<Vec3b> buf(it.count);
4618
4619 for(int i = 0; i < it.count; i++, ++it)
4620     buf[i] = *(const Vec3b)*it;
4621 \end{lstlisting}
4622
4623
4624 \cvfunc{rectangle}\label{rectangle}
4625 Draws a simple, thick, or filled up-right rectangle.
4626
4627 \begin{lstlisting}
4628 void rectangle(Mat& img, Point pt1, Point pt2,
4629                const Scalar& color, int thickness=1,
4630                int lineType=8, int shift=0);
4631 \end{lstlisting}
4632 \begin{description}
4633 \cvarg{img}{Image}
4634 \cvarg{pt1}{One of the rectangle's vertices}
4635 \cvarg{pt2}{Opposite to \texttt{pt1} rectangle vertex}
4636 \cvarg{color}{Rectangle color or brightness (grayscale image)}
4637 \cvarg{thickness}{Thickness of lines that make up the rectangle. Negative values, e.g. \texttt{CV\_FILLED}, mean that the function has to draw a filled rectangle.}
4638 \cvarg{lineType}{Type of the line, see \cross{line} description}
4639 \cvarg{shift}{Number of fractional bits in the point coordinates}
4640 \end{description}
4641
4642 The function \texttt{rectangle} draws a rectangle outline or a filled rectangle, which two opposite corners are \texttt{pt1} and \texttt{pt2}.
4643                
4644
4645 \cvfunc{polylines}\label{polylines}
4646 Draws several polygonal curves
4647
4648 \begin{lstlisting}
4649 void polylines(Mat& img, const Point** pts, const int* npts,
4650                int ncontours, bool isClosed, const Scalar& color,
4651                int thickness=1, int lineType=8, int shift=0 );
4652 \end{lstlisting}
4653 \begin{description}
4654 \cvarg{img}{The image}
4655 \cvarg{pts}{Array of polygonal curves}
4656 \cvarg{npts}{Array of polygon vertex counters}
4657 \cvarg{ncontours}{The number of curves}
4658 \cvarg{isClosed}{Indicates whether the drawn polylines are closed or not. If they are closed, the function draws the line from the last vertex of each curve to its first vertex}
4659 \cvarg{color}{Polyline color}
4660 \cvarg{thickness}{Thickness of the polyline edges}
4661 \cvarg{lineType}{Type of the line segments, see \cross{line} description}
4662 \cvarg{shift}{The number of fractional bits in the vertex coordinates}
4663 \end{description}
4664
4665 The function \texttt{polylines} draws one or more polygonal curves.
4666
4667 \cvfunc{putText}\label{putText}
4668 Draws a text string
4669
4670 \begin{lstlisting}
4671 void putText( Mat& img, const string& text, Point org,
4672               int fontFace, double fontScale, Scalar color,
4673               int thickness=1, int lineType=8,
4674               bool bottomLeftOrigin=false );
4675 enum
4676 {
4677  FONT_HERSHEY_SIMPLEX = 0,
4678  FONT_HERSHEY_PLAIN = 1,
4679  FONT_HERSHEY_DUPLEX = 2,
4680  FONT_HERSHEY_COMPLEX = 3,
4681  FONT_HERSHEY_TRIPLEX = 4,
4682  FONT_HERSHEY_COMPLEX_SMALL = 5,
4683  FONT_HERSHEY_SCRIPT_SIMPLEX = 6,
4684  FONT_HERSHEY_SCRIPT_COMPLEX = 7,
4685  FONT_ITALIC = 16
4686 };
4687 \end{lstlisting}
4688 \begin{description}
4689 \cvarg{img}{The image}
4690 \cvarg{text}{The text string to be drawn}
4691 \cvarg{org}{The bottom-left corner of the text string in the image}
4692 \cvarg{fontFace}{The font type, one of \texttt{FONT\_HERSHEY\_...}}
4693 \cvarg{fontScale}{The font scale factor that is multiplied by the font-specific base size}
4694 \cvarg{thickness}{Thickness of the lines used to draw the text}
4695 \cvarg{lineType}{The line type; see \texttt{line} for details}
4696 \cvarg{bottomLeftOrigin}{When true, the image data origin is at the bottom-left corner, otherwise it's at the top-left corner}
4697 \end{description}
4698
4699 The function \texttt{putText} draws a text string in the image.
4700 Symbols that can not be rendered using the specified font are
4701 replaced question marks. See \cross{getTextSize} for a text rendering code example.
4702
4703 \subsection{XML/YAML Persistence}
4704
4705 \cvfunc{FileStorage}\label{FileStorage}
4706 The XML/YAML file storage class
4707
4708 \begin{lstlisting}
4709 class FileStorage
4710 {
4711 public:
4712     enum { READ=0, WRITE=1, APPEND=2 };
4713     enum { UNDEFINED=0, VALUE_EXPECTED=1, NAME_EXPECTED=2, INSIDE_MAP=4 };
4714     // the default constructor
4715     FileStorage();
4716     // the constructor that opens the file for reading
4717     // (flags=FileStorage::READ) or writing (flags=FileStorage::WRITE)
4718     FileStorage(const string& filename, int flags);
4719     // wraps the already opened CvFileStorage*
4720     FileStorage(CvFileStorage* fs);
4721     // the destructor; closes the file if needed
4722     virtual ~FileStorage();
4723
4724     // opens the specified file for reading (flags=FileStorage::READ)
4725     // or writing (flags=FileStorage::WRITE)
4726     virtual bool open(const string& filename, int flags);
4727     // checks if the storage is opened
4728     virtual bool isOpened() const;
4729     // closes the file
4730     virtual void release();
4731
4732     // returns the first top-level node
4733     FileNode getFirstTopLevelNode() const;
4734     // returns the root file node
4735     // (it's the parent of the first top-level node)
4736     FileNode root(int streamidx=0) const;
4737     // returns the top-level node by name
4738     FileNode operator[](const string& nodename) const;
4739     FileNode operator[](const char* nodename) const;
4740
4741     // returns the underlying CvFileStorage*
4742     CvFileStorage* operator *() { return fs; }
4743     const CvFileStorage* operator *() const { return fs; }
4744     
4745     // writes the certain number of elements of the specified format
4746     // (see DataType) without any headers
4747     void writeRaw( const string& fmt, const uchar* vec, size_t len );
4748     
4749     // writes an old-style object (CvMat, CvMatND etc.)
4750     void writeObj( const string& name, const void* obj );
4751
4752     // returns the default object name from the filename
4753     // (used by cvSave() with the default object name etc.)
4754     static string getDefaultObjectName(const string& filename);
4755
4756     Ptr<CvFileStorage> fs;
4757     string elname;
4758     vector<char> structs;
4759     int state;
4760 };
4761 \end{lstlisting}
4762
4763
4764 \cvfunc{FileNode}\label{FileNode}
4765 The XML/YAML file node class
4766
4767 \begin{lstlisting}
4768 class CV_EXPORTS FileNode
4769 {
4770 public:
4771     enum { NONE=0, INT=1, REAL=2, FLOAT=REAL, STR=3,
4772         STRING=STR, REF=4, SEQ=5, MAP=6, TYPE_MASK=7,
4773         FLOW=8, USER=16, EMPTY=32, NAMED=64 };
4774     FileNode();
4775     FileNode(const CvFileStorage* fs, const CvFileNode* node);
4776     FileNode(const FileNode& node);
4777     FileNode operator[](const string& nodename) const;
4778     FileNode operator[](const char* nodename) const;
4779     FileNode operator[](int i) const;
4780     int type() const;
4781     int rawDataSize(const string& fmt) const;
4782     bool empty() const;
4783     bool isNone() const;
4784     bool isSeq() const;
4785     bool isMap() const;
4786     bool isInt() const;
4787     bool isReal() const;
4788     bool isString() const;
4789     bool isNamed() const;
4790     string name() const;
4791     size_t size() const;
4792     operator int() const;
4793     operator float() const;
4794     operator double() const;
4795     operator string() const;
4796
4797     FileNodeIterator begin() const;
4798     FileNodeIterator end() const;
4799
4800     void readRaw( const string& fmt, uchar* vec, size_t len ) const;
4801     void* readObj() const;
4802
4803     // do not use wrapper pointer classes for better efficiency
4804     const CvFileStorage* fs;
4805     const CvFileNode* node;
4806 };
4807 \end{lstlisting}
4808
4809 \cvfunc{FileNodeIterator}\label{FileNodeIterator}
4810 The XML/YAML file node iterator class
4811
4812 \begin{lstlisting}
4813 class CV_EXPORTS FileNodeIterator
4814 {
4815 public:
4816     FileNodeIterator();
4817     FileNodeIterator(const CvFileStorage* fs,
4818         const CvFileNode* node, size_t ofs=0);
4819     FileNodeIterator(const FileNodeIterator& it);
4820     FileNode operator *() const;
4821     FileNode operator ->() const;
4822
4823     FileNodeIterator& operator ++();
4824     FileNodeIterator operator ++(int);
4825     FileNodeIterator& operator --();
4826     FileNodeIterator operator --(int);
4827     FileNodeIterator& operator += (int);
4828     FileNodeIterator& operator -= (int);
4829
4830     FileNodeIterator& readRaw( const string& fmt, uchar* vec,
4831                                size_t maxCount=(size_t)INT_MAX );
4832
4833     const CvFileStorage* fs;
4834     const CvFileNode* container;
4835     CvSeqReader reader;
4836     size_t remaining;
4837 };
4838 \end{lstlisting}
4839
4840 \subsection{Clustering and Search in Multi-Dimensional Spaces}
4841
4842 \cvfunc{kmeans}\label{kmeans}
4843
4844 \begin{lstlisting}
4845 double kmeans( const Mat& samples, int clusterCount, Mat& labels,
4846                TermCriteria termcrit, int attempts,
4847                int flags, Mat* centers );
4848 enum { KMEANS_RANDOM_CENTERS=0,
4849        KMEANS_PP_CENTERS=2,
4850        KMEANS_USE_INITIAL_LABELS=1 };
4851 \end{lstlisting}
4852 \begin{description}
4853 \cvarg{samples}{Floating-point matrix of input samples, one row per sample}
4854 \cvarg{clusterCount}{The number of clusters to split the set by}
4855 \cvarg{labels}{The input/output integer array that will store the cluster indices for every sample}
4856 \cvarg{termcrit}{Specifies maximum number of iterations and/or accuracy (distance the centers can move by between subsequent iterations)}
4857
4858 \cvarg{attempts}{How many times the algorithm is executed using different initial labelings. The algorithm returns the labels that yield the best compactness (see the last function parameter)}
4859 \cvarg{flags}{It can take the following values:
4860 \begin{description}
4861 \cvarg{KMEANS\_RANDOM\_CENTERS}{Random initial centers are selected in each attempt}
4862 \cvarg{KMEANS\_PP\_CENTERS}{Use kmeans++ center initialization by Arthur and Vassilvitskii}
4863 \cvarg{KMEANS\_USE\_INITIAL\_LABELS}{During the first (and possibly the only) attempt, the
4864 function uses the user-supplied labels instaed of computing them from the initial centers. For the second and further attempts, the function will use the random or semi-random centers (use one of \texttt{KMEANS\_*\_CENTERS} flag to specify the exact method)}
4865 \end{description}}
4866 \cvarg{centers}{The output matrix of the cluster centers, one row per each cluster center}
4867 \end{description}
4868
4869 The function \texttt{kmeans} implements a k-means algorithm that finds the
4870 centers of \texttt{clusterCount} clusters and groups the input samples
4871 around the clusters. On output, $\texttt{labels}_i$ contains a 0-based cluster index for
4872 the sample stored in the $i^{th}$ row of the \texttt{samples} matrix.
4873
4874 The function returns the compactness measure, which is computed as
4875 \[
4876 \sum_i \|\texttt{samples}_i - \texttt{centers}_{\texttt{labels}_i}\|^2
4877 \]
4878 after every attempt; the best (minimum) value is chosen and the
4879 corresponding labels and the compactness value are returned by the function.
4880 Basically, the user can use only the core of the function, set the number of
4881 attempts to 1, initialize labels each time using some custom algorithm and pass them with
4882 \newline (\texttt{flags}=\texttt{KMEAN\_USE\_INITIAL\_LABELS}) flag, and then choose the best (most-compact) clustering.
4883
4884 \cvfunc{partition}\label{partition}
4885 Splits an element set into equivalency classes.
4886
4887 \begin{lstlisting}
4888 template<typename _Tp, class _EqPredicate> int
4889     partition( const vector<_Tp>& vec, vector<int>& labels,
4890                _EqPredicate predicate=_EqPredicate());
4891 \end{lstlisting}
4892 \begin{description}
4893 \cvarg{vec}{The set of elements stored as a vector}
4894 \cvarg{labels}{The output vector of labels; will contain as many elements as \texttt{vec}. Each label \texttt{labels[i]} is 0-based cluster index of \texttt{vec[i]}}
4895 \cvarg{predicate}{The equivalence predicate (i.e. pointer to a boolean function of two arguments or an instance of the class that has the method \texttt{bool operator()(const \_Tp\& a, const \_Tp\& b)}. The predicate returns true when the elements are certainly if the same class, and false if they may or may not be in the same class}
4896 \end{description}
4897
4898 The generic function \texttt{partition} implements an $O(N^2)$ algorithm for
4899 splitting a set of $N$ elements into one or more equivalency classes, as described in \url{http://en.wikipedia.org/wiki/Disjoint-set_data_structure}. The function
4900 returns the number of equivalency classes.
4901
4902
4903 \subsection{Fast Aproximate Nearest Neighbor Search}
4904
4905 \def\urltilda{\kern -.05em\lower .7ex\hbox{\~{}}\kern .04em}
4906
4907 This section documents OpenCV's interface to the FLANN\footnote{http://people.cs.ubc.ca/\urltilda mariusm/flann} library. FLANN (Fast Library for Approximate Nearest Neighbors) is a library that
4908 contains a collection of algorithms optimized for fast nearest neighbor search in large datasets and for high dimensional features. More 
4909 information about FLANN can be found in \cite{muja_flann_2009}.
4910
4911 \cvfunc{flann::Index}\label{flann::Index}
4912 The FLANN nearest neighbor index class.
4913 \begin{lstlisting}
4914   namespace flann {
4915
4916     class Index 
4917     {
4918     public:
4919             Index(const Mat& features, const IndexParams& params);
4920
4921             void knnSearch(const vector<float>& query, 
4922                            vector<int>& indices, 
4923                            vector<float>& dists, 
4924                            int knn, 
4925                            const SearchParams& params);
4926             void knnSearch(const Mat& queries, 
4927                            Mat& indices, 
4928                            Mat& dists, 
4929                            int knn, 
4930                            const SearchParams& params);
4931
4932             int radiusSearch(const vector<float>& query, 
4933                              vector<int>& indices, 
4934                              vector<float>& dists, 
4935                              float radius, 
4936                              const SearchParams& params);
4937             int radiusSearch(const Mat& query, 
4938                              Mat& indices, 
4939                              Mat& dists, 
4940                              float radius, 
4941                              const SearchParams& params);
4942
4943             void save(std::string filename);
4944
4945             int veclen() const;
4946
4947             int size() const;
4948     };
4949   }
4950 \end{lstlisting}
4951
4952 \cvfunc{flann::Index::Index}\label{flann::Index::Index}
4953 Constructs a nearest neighbor search index for a given dataset.
4954 \begin{lstlisting}
4955 Index::Index(const Mat& features, const IndexParams& params);
4956 \end{lstlisting}
4957 \begin{description}
4958 \cvarg{features}{ Matrix of type CV\_32F containing the features(points) to index. The size of the matrix is num\_features x feature\_dimensionality.}
4959 \cvarg{params}{Structure containing the index parameters. The type of index that will be constructed depends on the type of this parameter.}
4960 \end{description}
4961
4962 The possible parameter types are:
4963
4964 \begin {itemize}
4965  \item \texttt{LinearIndexParams} - When passing an object of this type, the index will perform a linear, brute-force search.
4966 \begin{lstlisting}
4967   struct LinearIndexParams : public IndexParams 
4968   {
4969   };
4970 \end{lstlisting}
4971
4972  \item \texttt{KDTreeIndexParams} - When passing an object of this type the index constructed will consist of a set 
4973 of randomized kd-trees which will be searched in parallel.
4974 \begin{lstlisting}
4975   struct KDTreeIndexParams : public IndexParams 
4976   {
4977         KDTreeIndexParams( int trees = 4 );
4978   };
4979 \end{lstlisting}
4980 \begin{description}
4981 \cvarg{trees}{The number of parallel kd-trees to use. Good values are in the range [1..16]}
4982 \end{description}
4983
4984  \item \texttt{KMeansIndexParams}  - When passing an object of this type the index constructed will be a hierarchical k-means tree. 
4985 \begin{lstlisting}
4986   struct KMeansIndexParams : public IndexParams 
4987   {
4988         KMeansIndexParams( int branching = 32, 
4989                            int iterations = 11,
4990                            flann_centers_init_t centers_init = CENTERS_RANDOM, 
4991                            float cb_index = 0.2 );      
4992   };
4993 \end{lstlisting}
4994 \begin{description}
4995 \cvarg{branching}{ The branching factor to use for the hierarchical k-means tree }
4996 \cvarg{iterations}{ The maximum number of iterations to use in the k-means clustering 
4997                     stage when building the k-means tree. A value of -1 used here means
4998                     that the k-means clustering should be iterated until convergence}
4999 \cvarg{centers\_init}{ The algorithm to use for selecting the initial
5000                   centers when performing a k-means clustering step. The possible values are
5001                   CENTERS\_RANDOM (picks the initial cluster centers randomly), CENTERS\_GONZALES (picks the
5002                   initial centers using Gonzales' algorithm) and CENTERS\_KMEANSPP (picks the initial
5003                 centers using the algorithm suggested in \cite{arthur_kmeanspp_2007}) }
5004 \cvarg{cb\_index} { This parameter (cluster boundary index) influences the
5005                   way exploration is performed in the hierarchical kmeans tree. When \texttt{cb\_index} is zero
5006                   the next kmeans domain to be explored is choosen to be the one with the closest center. 
5007                   A value greater then zero also takes into account the size of the domain.}
5008 \end{description}
5009
5010  \item \texttt{CompositeIndexParams} - When using a parameters object of this type the index created combines the randomized kd-trees 
5011         and the hierarchical k-means tree.
5012 \begin{lstlisting}
5013   struct CompositeIndexParams : public IndexParams 
5014   {
5015         CompositeIndexParams( int trees = 4, 
5016                               int branching = 32, 
5017                               int iterations = 11,
5018                               flann_centers_init_t centers_init = CENTERS_RANDOM, 
5019                               float cb_index = 0.2 );
5020   };
5021 \end{lstlisting}
5022
5023  \item \texttt{AutotunedIndexParams} - When passing an object of this type the index created is automatically tuned to offer 
5024 the best performance, by choosing the optimal index type (randomized kd-trees, hierarchical kmeans, linear) and parameters for the
5025 dataset provided.
5026 \begin{lstlisting}
5027   struct AutotunedIndexParams : public IndexParams 
5028   {
5029         AutotunedIndexParams( float target_precision = 0.9, 
5030                               float build_weight = 0.01,
5031                               float memory_weight = 0, 
5032                               float sample_fraction = 0.1 );
5033   };
5034 \end{lstlisting}
5035 \begin{description}
5036 \cvarg{target\_precision}{ Is a number between 0 and 1 specifying the
5037 percentage of the approximate nearest-neighbor searches that return the
5038 exact nearest-neighbor. Using a higher value for this parameter gives
5039 more accurate results, but the search takes longer. The optimum value
5040 usually depends on the application. }
5041
5042 \cvarg{build\_weight}{ Specifies the importance of the
5043 index build time raported to the nearest-neighbor search time. In some
5044 applications it's acceptable for the index build step to take a long time
5045 if the subsequent searches in the index can be performed very fast. In
5046 other applications it's required that the index be build as fast as
5047 possible even if that leads to slightly longer search times.}
5048
5049 \cvarg{memory\_weight} {Is used to specify the tradeoff between
5050 time (index build time and search time) and memory used by the index. A
5051 value less than 1 gives more importance to the time spent and a value
5052 greater than 1 gives more importance to the memory usage.}
5053
5054 \cvarg{sample\_fraction} {Is a number between 0 and 1 indicating what fraction
5055 of the dataset to use in the automatic parameter configuration algorithm. Running the 
5056 algorithm on the full dataset gives the most accurate results, but for
5057 very large datasets can take longer than desired. In such case using just a fraction of the
5058 data helps speeding up this algorithm while still giving good approximations of the
5059 optimum parameters.}
5060 \end{description}
5061
5062  \item \texttt{SavedIndexParams} - This object type is used for loading a previously saved index from the disk.
5063 \begin{lstlisting}
5064   struct SavedIndexParams : public IndexParams {
5065         SavedIndexParams( std::string filename );
5066   };
5067 \end{lstlisting}
5068 \begin{description}
5069 \cvarg{filename}{ The filename in which the index was saved. }
5070 \end{description}
5071 \end {itemize}
5072
5073
5074 \cvfunc{flann::Index::knnSearch}\label{flann::Index::knnSearch}
5075 Performs a K-nearest neighbor search for a given query point using the index.
5076 \begin{lstlisting}
5077 void Index::knnSearch(const vector<float>& query, 
5078                 vector<int>& indices, 
5079                 vector<float>& dists, 
5080                 int knn, 
5081                 const SearchParams& params);
5082 \end{lstlisting}
5083 \begin{description}
5084 \cvarg{query}{The query point}
5085 \cvarg{indices}{Vector that will contain the indices of the K-nearest neighbors found. It must have at least knn size.}
5086 \cvarg{dists}{Vector that will contain the distances to the K-nearest neighbors found. It must have at least knn size.}
5087 \cvarg{knn}{Number of nearest neighbors to search for.}
5088 \cvarg{params}{Search parameters}
5089 \begin{lstlisting}
5090   struct SearchParams {
5091           SearchParams(int checks = 32);
5092   };
5093 \end{lstlisting}
5094 \begin{description}
5095 \cvarg{checks}{ The number of times the tree(s) in the index should be recursively traversed. A
5096 higher value for this parameter would give better search precision, but
5097 also take more time. If automatic configuration was used when the
5098 index was created, the number of checks required to achieve the specified
5099 precision was also computed, in which case this parameter is ignored.}
5100 \end{description}
5101 \end{description}
5102
5103 \cvfunc{flann::Index::knnSearch}\label{flann::Index::knnSearch}
5104 Performs a K-nearest neighbor search for multiple query points.
5105 \begin{lstlisting}
5106 void Index::knnSearch(const Mat& queries, 
5107                 Mat& indices, 
5108                 Mat& dists, 
5109                 int knn, 
5110                 const SearchParams& params);
5111 \end{lstlisting}
5112 \begin{description}
5113 \cvarg{queries}{The query points, one per row}
5114 \cvarg{indices}{Indices of the nearest neighbors found }
5115 \cvarg{dists}{Distances to the nearest neighbors found}
5116 \cvarg{knn}{Number of nearest neighbors to search for}
5117 \cvarg{params}{Search parameters}
5118 \end{description}
5119
5120
5121 \cvfunc{flann::Index::radiusSearch}\label{flann::Index::radiusSearch}
5122 Performs a radius nearest neighbor search for a given query point.
5123 \begin{lstlisting}
5124 int Index::radiusSearch(const vector<float>& query, 
5125                   vector<int>& indices, 
5126                   vector<float>& dists, 
5127                   float radius, 
5128                   const SearchParams& params);
5129 \end{lstlisting}
5130 \begin{description}
5131 \cvarg{query}{The query point}
5132 \cvarg{indices}{Vector that will contain the indices of the points found within the search radius in decreasing order of the distance to the query point. If the number of neighbors in the search radius is bigger than the size of this vector, the ones that don't fit in the vector are ignored. }
5133 \cvarg{dists}{Vector that will contain the distances to the points found within the search radius}
5134 \cvarg{radius}{The search radius}
5135 \cvarg{params}{Search parameters}
5136 \end{description}
5137
5138
5139 \cvfunc{flann::Index::radiusSearch}\label{flann::Index::radiusSearch}
5140 Performs a radius nearest neighbor search for multiple query points.
5141 \begin{lstlisting}
5142 int Index::radiusSearch(const Mat& query, 
5143                   Mat& indices, 
5144                   Mat& dists, 
5145                   float radius, 
5146                   const SearchParams& params);
5147 \end{lstlisting}
5148 \begin{description}
5149 \cvarg{queries}{The query points, one per row}
5150 \cvarg{indices}{Indices of the nearest neighbors found}
5151 \cvarg{dists}{Distances to the nearest neighbors found}
5152 \cvarg{radius}{The search radius}
5153 \cvarg{params}{Search parameters}
5154 \end{description}
5155
5156
5157 \cvfunc{flann::Index::save}\label{flann::Index::save}
5158 Saves the index to a file.
5159 \begin{lstlisting}
5160 void Index::save(std::string filename);
5161 \end{lstlisting}
5162 \begin{description}
5163 \cvarg{filename}{The file to save the index to}
5164 \end{description}
5165
5166
5167 \cvfunc{flann::hierarchicalClustering}\label{flann::hierarchicalClustering}
5168 Clusters the given points by constructing a hierarchical k-means tree and choosing a cut in the tree that minimizes the cluster's variance.
5169 \begin{lstlisting}
5170 int hierarchicalClustering(const Mat& features, Mat& centers,
5171                                       const KMeansIndexParams& params);
5172 \end{lstlisting}
5173 \begin{description}
5174 \cvarg{features}{The points to be clustered}
5175 \cvarg{centers}{The centers of the clusters obtained. The number of rows in this matrix represents the number of clusters desired, 
5176 however, because of the way the cut in the hierarchical tree is choosen, the number of clusters computed will be
5177  the highest number of the form $(branching-1)*k+1$ that's lower than the number of clusters desired, where $branching$ is the tree's 
5178 branching factor (see description of the KMeansIndexParams).  }
5179 \cvarg{params}{Parameters used in the construction of the hierarchical k-means tree}
5180 \end{description}
5181 The function returns the number of clusters computed.
5182
5183
5184
5185 \subsection{Utility and System Functions and Macros}
5186
5187 \cvfunc{alignPtr}\label{alignPtr}
5188 Aligns pointer to the specified number of bytes
5189
5190 \begin{lstlisting}
5191 template<typename _Tp> _Tp* alignPtr(_Tp* ptr, int n=sizeof(_Tp));
5192 \end{lstlisting}
5193 \begin{description}
5194 \cvarg{ptr}{The aligned pointer}
5195 \cvarg{n}{The alignment size; must be a power of two}
5196 \end{description}
5197
5198 The function returns the aligned pointer of the same type as the input pointer:
5199 \[\texttt{(\_Tp*)(((size\_t)ptr + n-1) \& -n)}\]
5200
5201
5202 \cvfunc{alignSize}\label{alignSize}
5203 Aligns a buffer size to the specified number of bytes
5204
5205 \begin{lstlisting}
5206 size_t alignSize(size_t sz, int n);
5207 \end{lstlisting}
5208 \begin{description}
5209 \cvarg{sz}{The buffer size to align}
5210 \cvarg{n}{The alignment size; must be a power of two}
5211 \end{description}
5212
5213 The function returns the minimum number that is greater or equal to \texttt{sz} and is divisble by \texttt{n}:
5214 \[\texttt{(sz + n-1) \& -n}\]
5215
5216
5217 \cvfunc{allocate}\label{allocate}
5218 Allocates an array of elements
5219
5220 \begin{lstlisting}
5221 template<typename _Tp> _Tp* allocate(size_t n);
5222 \end{lstlisting}
5223 \begin{description}
5224 \cvarg{n}{The number of elements to allocate}
5225 \end{description}
5226
5227 The generic function \texttt{allocate} allocates buffer for the specified number of elements. For each element the default constructor is called.
5228
5229
5230 \cvfunc{allocate}\label{allocate}
5231 Allocates an array of elements
5232
5233 \begin{lstlisting}
5234 template<typename _Tp> void deallocate(_Tp* ptr, size_t n);
5235 \end{lstlisting}
5236 \begin{description}
5237 \cvarg{ptr}{Pointer to the deallocated buffer}
5238 \cvarg{n}{The number of elements in the buffer}
5239 \end{description}
5240
5241 The generic function \texttt{deallocate} deallocates the buffer allocated with \cross{allocate}. The number of elements must match the number passed to \cross{allocate}.
5242
5243 \cvfunc{CV\_Assert}\label{CV Assert}
5244 Checks a condition at runtime.
5245
5246 \begin{lstlisting}
5247 #define CV_Assert( expr ) ...
5248 #define CV_DbgAssert(expr) ...
5249 \end{lstlisting}
5250
5251 \begin{description}
5252 \cvarg{expr}{The checked expression}
5253 \end{description}
5254
5255 The macros \texttt{CV\_Assert} and \texttt{CV\_DbgAssert} evaluate the specified expression and if it is 0, the macros raise an error (see \cross{error}). The macro \texttt{CV\_Assert} checks the condition in both Debug and Release configurations, while \texttt{CV\_DbgAssert} is only retained in the Debug configuration.
5256
5257 \cvfunc{error}\label{error}
5258 Signals an error and raises the exception
5259
5260 \begin{lstlisting}
5261 void error( const Exception& exc );
5262
5263 #define CV_Error( code, msg )
5264 #define CV_Error_( code, args )
5265 \end{lstlisting}
5266 \begin{description}
5267 \cvarg{exc}{The exception to throw}
5268 \cvarg{code}{The error code, normally, a negative value. The list of pre-defined error codes can be found in \texttt{cxerror.h}}
5269 \cvarg{msg}{Text of the error message}
5270 \cvarg{args}{printf-like formatted error message in parantheses}
5271 \end{description}
5272
5273 The function \texttt{error} and the helper macros \texttt{CV\_Error} and \texttt{CV\_Error\_} call the error handler. Currently, the error handler prints the error code (\texttt{exc.code}), the context (\texttt{exc.file}, \texttt{exc.line} and the error message \texttt{exc.err} to the standard error stream \texttt{stderr}. In Debug configuration it then provokes memory access violation, so that the execution stack and all the parameters can be analyzed in debugger. In Release configuration the exception \texttt{exc} is thrown.
5274
5275 The macro \texttt{CV\_Error\_} can be used to construct the error message on-fly to include some dynamic information, for example:
5276
5277 \begin{lstlisting}
5278 // note the extra parentheses around the formatted text message
5279 CV_Error_(CV_StsOutOfRange,
5280     ("the matrix element (%d,%d)=%g is out of range",
5281     i, j, mtx.at<float>(i,j)))
5282 \end{lstlisting}
5283
5284
5285 \cvfunc{Exception}\label{Exception}
5286 The exception class passed to error
5287
5288 \begin{lstlisting}
5289 class  Exception
5290 {
5291 public:
5292     // various constructors and the copy operation
5293     Exception() { code = 0; line = 0; }
5294     Exception(int _code, const string& _err,
5295               const string& _func, const string& _file, int _line);
5296     Exception(const Exception& exc);
5297     Exception& operator = (const Exception& exc);
5298
5299     // the error code
5300     int code;
5301     // the error text message
5302     string err;
5303     // function name where the error happened
5304     string func;
5305     // the source file name where the error happened
5306     string file;
5307     // the source file line where the error happened
5308     int line;
5309 };
5310 \end{lstlisting}
5311
5312 The class \texttt{Exception} encapsulates all or almost all the necessary information about the error happened in the program. The exception is usually constructed and thrown implicitly, via \texttt{CV\_Error} and \texttt{CV\_Error\_} macros, see \cross{error}.
5313
5314
5315 \cvfunc{fastMalloc}\label{fastMalloc}
5316 Allocates aligned memory buffer
5317
5318 \begin{lstlisting}
5319 void* fastMalloc(size_t size);
5320 \end{lstlisting}
5321 \begin{description}
5322 \cvarg{size}{The allocated buffer size}
5323 \end{description}
5324  
5325 The function \texttt{fastMalloc} allocates buffer of the specified size and returns it. When the buffer size is 16 bytes or more, the returned buffer is aligned on 16 bytes.
5326
5327 \cvfunc{fastFree}\label{fastFree}
5328 Deallocates memory buffer
5329
5330 \begin{lstlisting}
5331 void fastFree(void* ptr);
5332 \end{lstlisting}
5333 \begin{description}
5334 \cvarg{ptr}{Pointer to the allocated buffer}
5335 \end{description}
5336
5337 The function \texttt{fastFree} deallocates the buffer, allocated with \cross{fastMalloc}.
5338 If NULL pointer is passed, the function does nothing.
5339
5340 \cvfunc{format}\label{format}
5341 Returns a text string formatted using printf-like expression
5342
5343 \begin{lstlisting}
5344 string format( const char* fmt, ... );
5345 \end{lstlisting}
5346 \begin{description}
5347 \cvarg{fmt}{The printf-compatible formatting specifiers}
5348 \end{description}
5349
5350 The function \texttt{format} acts like \texttt{sprintf}, but forms and returns STL string. It can be used for form the error message in \cross{Exception} constructor.
5351
5352 \cvfunc{getNumThreads}\label{getNumThreads}
5353 Returns the number of threads used by OpenCV
5354
5355 \begin{lstlisting}
5356 int getNumThreads();
5357 \end{lstlisting}
5358
5359 The function returns the number of threads that is used by OpenCV.
5360
5361 See also: \cross{setNumThreads}, \cross{getThreadNum}.
5362
5363
5364 \cvfunc{getThreadNum}\label{getThreadNum}
5365 Returns index of the currently executed thread
5366
5367 \begin{lstlisting}
5368 int getThreadNum();
5369 \end{lstlisting}
5370
5371 The function returns 0-based index of the currently executed thread. The function is only valid inside a parallel OpenMP region. When OpenCV is built without OpenMP support, the function always returns 0.
5372
5373 See also: \cross{setNumThreads}, \cross{getNumThreads}.
5374
5375 \cvfunc{getTickCount}\label{getTickCount}
5376 Returns the number of ticks
5377
5378 \begin{lstlisting}
5379 int64 getTickCount();
5380 \end{lstlisting}
5381
5382 The function returns the number of ticks since the certain event (e.g. when the machine was turned on).
5383 It can be used to initialize \cross{RNG} or to measure a function execution time by reading the tick count before and after the function call. See also the tick frequency.
5384
5385 \cvfunc{getTickFrequency}\label{getTickFrequency}
5386 Returns the number of ticks per second
5387
5388 \begin{lstlisting}
5389 double getTickFrequency();
5390 \end{lstlisting}
5391
5392 The function returns the number of ticks per second.
5393 That is, the following code computes the executing time in seconds.
5394 \begin{lstlisting}
5395 double t = (double)getTickCount();
5396 // do something ...
5397 t = ((double)getTickCount() - t)/getTickFrequency();
5398 \end{lstlisting}
5399
5400 \cvfunc{setNumThreads}\label{setNumThreads}
5401 Sets the number of threads used by OpenCV
5402
5403 \begin{lstlisting}
5404 void setNumThreads(int nthreads);
5405 \end{lstlisting}
5406 \begin{description}
5407 \cvarg{nthreads}{The number of threads used by OpenCV}
5408 \end{description}
5409
5410 The function sets the number of threads used by OpenCV in parallel OpenMP regions. If \texttt{nthreads=0}, the function will use the default number of threads, which is usually equal to the number of the processing cores.
5411
5412 See also: \cross{getNumThreads}, \cross{getThreadNum}