CLAHE Python bindings
[profile/ivi/opencv.git] / modules / core / doc / basic_structures.rst
1 Basic Structures
2 ================
3
4 .. highlight:: cpp
5
6 DataType
7 --------
8 .. ocv:class:: DataType
9
10 Template "trait" class for OpenCV primitive data types. A primitive OpenCV data type is one of ``unsigned char``, ``bool``, ``signed char``, ``unsigned short``, ``signed short``, ``int``, ``float``, ``double``, or a tuple of values of one of these types, where all the values in the tuple have the same type. Any primitive type from the list can be defined by an identifier in the form ``CV_<bit-depth>{U|S|F}C(<number_of_channels>)``, for example: ``uchar`` ~ ``CV_8UC1``, 3-element floating-point tuple ~ ``CV_32FC3``, and so on. A universal OpenCV structure that is able to store a single instance of such a primitive data type is
11 :ocv:class:`Vec`. Multiple instances of such a type can be stored in a ``std::vector``, ``Mat``, ``Mat_``, ``SparseMat``, ``SparseMat_``, or any other container that is able to store ``Vec`` instances.
12
13 The ``DataType`` class is basically used to provide a 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 is not ``DataType`` itself that is used but its specialized versions, such as: ::
14
15     template<> class DataType<uchar>
16     {
17         typedef uchar value_type;
18         typedef int work_type;
19         typedef uchar channel_type;
20         enum { channel_type = CV_8U, channels = 1, fmt='u', type = CV_8U };
21     };
22     ...
23     template<typename _Tp> DataType<std::complex<_Tp> >
24     {
25         typedef std::complex<_Tp> value_type;
26         typedef std::complex<_Tp> work_type;
27         typedef _Tp channel_type;
28         // DataDepth is another helper trait class
29         enum { depth = DataDepth<_Tp>::value, channels=2,
30             fmt=(channels-1)*256+DataDepth<_Tp>::fmt,
31             type=CV_MAKETYPE(depth, channels) };
32     };
33     ...
34
35 The main purpose of this class is to convert compilation-time type information to an OpenCV-compatible data type identifier, for example: ::
36
37     // allocates a 30x40 floating-point matrix
38     Mat A(30, 40, DataType<float>::type);
39
40     Mat B = Mat_<std::complex<double> >(3, 3);
41     // the statement below will print 6, 2 /*, that is depth == CV_64F, channels == 2 */
42     cout << B.depth() << ", " << B.channels() << endl;
43
44
45 So, such traits are used to tell OpenCV which data type you are working with, even if such a type is not native to OpenCV. For example, the matrix ``B`` initialization above is compiled because OpenCV defines the proper specialized template class ``DataType<complex<_Tp> >`` . This mechanism is also useful (and used in OpenCV this way) for generic algorithms implementations.
46
47
48 Point\_
49 -------
50 .. ocv:class:: Point_
51
52 Template class for 2D points specified by its coordinates
53 :math:`x` and
54 :math:`y` .
55 An instance of the class is interchangeable with C structures, ``CvPoint`` and ``CvPoint2D32f`` . There is also a cast operator to convert point coordinates to the specified type. The conversion from floating-point coordinates to integer coordinates is done by rounding. Commonly, the conversion uses this
56 operation for each of the coordinates. Besides the class members listed in the declaration above, the following operations on points are implemented: ::
57
58         pt1 = pt2 + pt3;
59         pt1 = pt2 - pt3;
60         pt1 = pt2 * a;
61         pt1 = a * pt2;
62         pt1 += pt2;
63         pt1 -= pt2;
64         pt1 *= a;
65         double value = norm(pt); // L2 norm
66         pt1 == pt2;
67         pt1 != pt2;
68
69 For your convenience, the following type aliases are defined: ::
70
71     typedef Point_<int> Point2i;
72     typedef Point2i Point;
73     typedef Point_<float> Point2f;
74     typedef Point_<double> Point2d;
75
76 Example: ::
77
78     Point2f a(0.3f, 0.f), b(0.f, 0.4f);
79     Point pt = (a + b)*10.f;
80     cout << pt.x << ", " << pt.y << endl;
81
82
83 Point3\_
84 --------
85 .. ocv:class:: Point3_
86
87 Template class for 3D points specified by its coordinates
88 :math:`x`,
89 :math:`y` and
90 :math:`z` .
91 An instance of the class is interchangeable with the C structure ``CvPoint2D32f`` . Similarly to ``Point_`` , the coordinates of 3D points can be converted to another type. The vector arithmetic and comparison operations are also supported.
92
93 The following ``Point3_<>`` aliases are available: ::
94
95     typedef Point3_<int> Point3i;
96     typedef Point3_<float> Point3f;
97     typedef Point3_<double> Point3d;
98
99 Size\_
100 ------
101 .. ocv:class:: Size_
102
103 Template class for specifying the size of an image or rectangle. The class includes two members called ``width`` and ``height``. The structure can be converted to and from the old OpenCV structures
104 ``CvSize`` and ``CvSize2D32f`` . The same set of arithmetic and comparison operations as for ``Point_`` is available.
105
106 OpenCV defines the following ``Size_<>`` aliases: ::
107
108     typedef Size_<int> Size2i;
109     typedef Size2i Size;
110     typedef Size_<float> Size2f;
111
112 Rect\_
113 ------
114 .. ocv:class:: Rect_
115
116 Template class for 2D rectangles, described by the following parameters:
117
118 * Coordinates of the top-left corner. This is a default interpretation of ``Rect_::x`` and ``Rect_::y`` in OpenCV. Though, in your algorithms you may count ``x`` and ``y`` from the bottom-left corner.
119 * Rectangle width and height.
120
121 OpenCV typically assumes that the top and left boundary of the rectangle are inclusive, while the right and bottom boundaries are not. For example, the method ``Rect_::contains`` returns ``true`` if
122
123 .. math::
124
125     x  \leq pt.x < x+width,
126           y  \leq pt.y < y+height
127
128 Virtually every loop over an image
129 ROI in OpenCV (where ROI is specified by ``Rect_<int>`` ) is implemented as: ::
130
131     for(int y = roi.y; y < roi.y + rect.height; y++)
132         for(int x = roi.x; x < roi.x + rect.width; x++)
133         {
134             // ...
135         }
136
137
138 In addition to the class members, the following operations on rectangles are implemented:
139
140 *
141     :math:`\texttt{rect} = \texttt{rect} \pm \texttt{point}`     (shifting a rectangle by a certain offset)
142
143 *
144     :math:`\texttt{rect} = \texttt{rect} \pm \texttt{size}`     (expanding or shrinking a rectangle by a certain amount)
145
146 * ``rect += point, rect -= point, rect += size, rect -= size``     (augmenting operations)
147
148 * ``rect = rect1 & rect2``     (rectangle intersection)
149
150 * ``rect = rect1 | rect2``     (minimum area rectangle containing ``rect2``     and ``rect3``     )
151
152 * ``rect &= rect1, rect |= rect1``     (and the corresponding augmenting operations)
153
154 * ``rect == rect1, rect != rect1``     (rectangle comparison)
155
156 This is an example how the partial ordering on rectangles can be established (rect1
157 :math:`\subseteq` rect2): ::
158
159     template<typename _Tp> inline bool
160     operator <= (const Rect_<_Tp>& r1, const Rect_<_Tp>& r2)
161     {
162         return (r1 & r2) == r1;
163     }
164
165
166 For your convenience, the ``Rect_<>`` alias is available: ::
167
168     typedef Rect_<int> Rect;
169
170 RotatedRect
171 -----------
172 .. ocv:class:: RotatedRect
173
174 The class represents rotated (i.e. not up-right) rectangles on a plane. Each rectangle is specified by the center point (mass center), length of each side (represented by cv::Size2f structure) and the rotation angle in degrees.
175
176     .. ocv:function:: RotatedRect::RotatedRect()
177     .. ocv:function:: RotatedRect::RotatedRect(const Point2f& center, const Size2f& size, float angle)
178     .. ocv:function:: RotatedRect::RotatedRect(const CvBox2D& box)
179
180         :param center: The rectangle mass center.
181         :param size: Width and height of the rectangle.
182         :param angle: The rotation angle in a clockwise direction. When the angle is 0, 90, 180, 270 etc., the rectangle becomes an up-right rectangle.
183         :param box: The rotated rectangle parameters as the obsolete CvBox2D structure.
184
185     .. ocv:function:: void RotatedRect::points( Point2f pts[] ) const
186     .. ocv:function:: Rect RotatedRect::boundingRect() const
187     .. ocv:function:: RotatedRect::operator CvBox2D() const
188
189         :param pts: The points array for storing rectangle vertices.
190
191 The sample below demonstrates how to use RotatedRect:
192
193 ::
194
195     Mat image(200, 200, CV_8UC3, Scalar(0));
196     RotatedRect rRect = RotatedRect(Point2f(100,100), Size2f(100,50), 30);
197
198     Point2f vertices[4];
199     rRect.points(vertices);
200     for (int i = 0; i < 4; i++)
201         line(image, vertices[i], vertices[(i+1)%4], Scalar(0,255,0));
202
203     Rect brect = rRect.boundingRect();
204     rectangle(image, brect, Scalar(255,0,0));
205
206     imshow("rectangles", image);
207     waitKey(0);
208
209 .. image:: pics/rotatedrect.png
210
211 .. seealso::
212
213     :ocv:func:`CamShift` ,
214     :ocv:func:`fitEllipse` ,
215     :ocv:func:`minAreaRect` ,
216     :ocv:struct:`CvBox2D`
217
218 TermCriteria
219 ------------
220 .. ocv:class:: TermCriteria
221
222   The class defining termination criteria for iterative algorithms. You can initialize it by default constructor and then override any parameters, or the structure may be fully initialized using the advanced variant of the constructor.
223
224 TermCriteria::TermCriteria
225 --------------------------
226 The constructors.
227
228 .. ocv:function:: TermCriteria::TermCriteria()
229
230 .. ocv:function:: TermCriteria::TermCriteria(int type, int maxCount, double epsilon)
231
232 .. ocv:function:: TermCriteria::TermCriteria(const CvTermCriteria& criteria)
233
234     :param type: The type of termination criteria: ``TermCriteria::COUNT``, ``TermCriteria::EPS`` or ``TermCriteria::COUNT`` + ``TermCriteria::EPS``.
235
236     :param maxCount: The maximum number of iterations or elements to compute.
237
238     :param epsilon: The desired accuracy or change in parameters at which the iterative algorithm stops.
239
240     :param criteria: Termination criteria in the deprecated ``CvTermCriteria`` format.
241
242 TermCriteria::operator CvTermCriteria
243 -------------------------------------
244 Converts to the deprecated ``CvTermCriteria`` format.
245
246 .. ocv:function:: TermCriteria::operator CvTermCriteria() const
247
248 Matx
249 ----
250 .. ocv:class:: Matx
251
252 Template class for small matrices whose type and size are known at compilation time: ::
253
254     template<typename _Tp, int m, int n> class Matx {...};
255
256     typedef Matx<float, 1, 2> Matx12f;
257     typedef Matx<double, 1, 2> Matx12d;
258     ...
259     typedef Matx<float, 1, 6> Matx16f;
260     typedef Matx<double, 1, 6> Matx16d;
261
262     typedef Matx<float, 2, 1> Matx21f;
263     typedef Matx<double, 2, 1> Matx21d;
264     ...
265     typedef Matx<float, 6, 1> Matx61f;
266     typedef Matx<double, 6, 1> Matx61d;
267
268     typedef Matx<float, 2, 2> Matx22f;
269     typedef Matx<double, 2, 2> Matx22d;
270     ...
271     typedef Matx<float, 6, 6> Matx66f;
272     typedef Matx<double, 6, 6> Matx66d;
273
274 If you need a more flexible type, use :ocv:class:`Mat` . The elements of the matrix ``M`` are accessible using the ``M(i,j)`` notation. Most of the common matrix operations (see also
275 :ref:`MatrixExpressions` ) are available. To do an operation on ``Matx`` that is not implemented, you can easily convert the matrix to
276 ``Mat`` and backwards. ::
277
278     Matx33f m(1, 2, 3,
279               4, 5, 6,
280               7, 8, 9);
281     cout << sum(Mat(m*m.t())) << endl;
282
283
284 Vec
285 ---
286 .. ocv:class:: Vec
287
288 Template class for short numerical vectors, a partial case of :ocv:class:`Matx`: ::
289
290     template<typename _Tp, int n> class Vec : public Matx<_Tp, n, 1> {...};
291
292     typedef Vec<uchar, 2> Vec2b;
293     typedef Vec<uchar, 3> Vec3b;
294     typedef Vec<uchar, 4> Vec4b;
295
296     typedef Vec<short, 2> Vec2s;
297     typedef Vec<short, 3> Vec3s;
298     typedef Vec<short, 4> Vec4s;
299
300     typedef Vec<int, 2> Vec2i;
301     typedef Vec<int, 3> Vec3i;
302     typedef Vec<int, 4> Vec4i;
303
304     typedef Vec<float, 2> Vec2f;
305     typedef Vec<float, 3> Vec3f;
306     typedef Vec<float, 4> Vec4f;
307     typedef Vec<float, 6> Vec6f;
308
309     typedef Vec<double, 2> Vec2d;
310     typedef Vec<double, 3> Vec3d;
311     typedef Vec<double, 4> Vec4d;
312     typedef Vec<double, 6> Vec6d;
313
314 It is possible to convert ``Vec<T,2>`` to/from ``Point_``, ``Vec<T,3>`` to/from ``Point3_`` , and ``Vec<T,4>`` to :ocv:struct:`CvScalar` or :ocv:class:`Scalar_`. Use ``operator[]`` to access the elements of ``Vec``.
315
316 All the expected vector operations are also implemented:
317
318 * ``v1 = v2 + v3``
319 * ``v1 = v2 - v3``
320 * ``v1 = v2 * scale``
321 * ``v1 = scale * v2``
322 * ``v1 = -v2``
323 * ``v1 += v2`` and other augmenting operations
324 * ``v1 == v2, v1 != v2``
325 * ``norm(v1)``  (euclidean norm)
326
327 The ``Vec`` class is commonly used to describe pixel types of multi-channel arrays. See :ocv:class:`Mat` for details.
328
329 Scalar\_
330 --------
331 .. ocv:class:: Scalar_
332
333 Template class for a 4-element vector derived from Vec. ::
334
335     template<typename _Tp> class Scalar_ : public Vec<_Tp, 4> { ... };
336
337     typedef Scalar_<double> Scalar;
338
339 Being derived from ``Vec<_Tp, 4>`` , ``Scalar_`` and ``Scalar`` can be used just as typical 4-element vectors. In addition, they can be converted to/from ``CvScalar`` . The type ``Scalar`` is widely used in OpenCV to pass pixel values.
340
341 Range
342 -----
343 .. ocv:class:: Range
344
345 Template class specifying a continuous subsequence (slice) of a sequence. ::
346
347     class Range
348     {
349     public:
350         ...
351         int start, end;
352     };
353
354 The class is used to specify a row or a column span in a matrix (
355 :ocv:class:`Mat` ) and for many other purposes. ``Range(a,b)`` is basically the same as ``a:b`` in Matlab or ``a..b`` in Python. As in Python, ``start`` is an inclusive left boundary of the range and ``end`` is an exclusive right boundary of the range. Such a half-opened interval is usually denoted as
356 :math:`[start,end)` .
357
358 The static method ``Range::all()`` returns a special variable that means "the whole sequence" or "the whole range", just like " ``:`` " in Matlab or " ``...`` " in Python. All the methods and functions in OpenCV that take ``Range`` support this special ``Range::all()`` value. But, of course, in case of your own custom processing, you will probably have to check and handle it explicitly: ::
359
360     void my_function(..., const Range& r, ....)
361     {
362         if(r == Range::all()) {
363             // process all the data
364         }
365         else {
366             // process [r.start, r.end)
367         }
368     }
369
370
371 .. _Ptr:
372
373 Ptr
374 ---
375 .. ocv:class:: Ptr
376
377 Template class for smart reference-counting pointers ::
378
379     template<typename _Tp> class Ptr
380     {
381     public:
382         // default constructor
383         Ptr();
384         // constructor that wraps the object pointer
385         Ptr(_Tp* _obj);
386         // destructor: calls release()
387         ~Ptr();
388         // copy constructor; increments ptr's reference counter
389         Ptr(const Ptr& ptr);
390         // assignment operator; decrements own reference counter
391         // (with release()) and increments ptr's reference counter
392         Ptr& operator = (const Ptr& ptr);
393         // increments reference counter
394         void addref();
395         // decrements reference counter; when it becomes 0,
396         // delete_obj() is called
397         void release();
398         // user-specified custom object deletion operation.
399         // by default, "delete obj;" is called
400         void delete_obj();
401         // returns true if obj == 0;
402         bool empty() const;
403
404         // provide access to the object fields and methods
405         _Tp* operator -> ();
406         const _Tp* operator -> () const;
407
408         // return the underlying object pointer;
409         // thanks to the methods, the Ptr<_Tp> can be
410         // used instead of _Tp*
411         operator _Tp* ();
412         operator const _Tp*() const;
413     protected:
414         // the encapsulated object pointer
415         _Tp* obj;
416         // the associated reference counter
417         int* refcount;
418     };
419
420
421 The ``Ptr<_Tp>`` class is a template class that wraps pointers of the corresponding type. It is
422 similar to ``shared_ptr`` that is part of the Boost library
423 (http://www.boost.org/doc/libs/1_40_0/libs/smart_ptr/shared_ptr.htm) and also part of the
424 `C++0x <http://en.wikipedia.org/wiki/C++0x>`_ standard.
425
426 This class provides the following options:
427
428 *
429     Default constructor, copy constructor, and assignment operator for an arbitrary C++ class
430     or a C structure. For some objects, like files, windows, mutexes, sockets, and others, a copy
431     constructor or an assignment operator are difficult to define. For some other objects, like
432     complex classifiers in OpenCV, copy constructors are absent and not easy to implement. Finally,
433     some of complex OpenCV and your own data structures may be written in C.
434     However, copy constructors and default constructors can simplify programming a lot.Besides,
435     they are often required (for example, by STL containers). By wrapping a pointer to such a
436     complex object ``TObj`` to ``Ptr<TObj>``, you automatically get all of the necessary
437     constructors and the assignment operator.
438
439 *
440     *O(1)* complexity of the above-mentioned operations. While some structures, like ``std::vector``,
441     provide a copy constructor and an assignment operator, the operations may take a considerable
442     amount of time if the data structures are large. But if the structures are put into ``Ptr<>``,
443     the overhead is small and independent of the data size.
444
445 *
446     Automatic destruction, even for C structures. See the example below with ``FILE*``.
447
448 *
449     Heterogeneous collections of objects. The standard STL and most other C++ and OpenCV containers
450     can store only objects of the same type and the same size. The classical solution to store objects
451     of different types in the same container is to store pointers to the base class ``base_class_t*``
452     instead but then you loose the automatic memory management. Again, by using ``Ptr<base_class_t>()``
453     instead of the raw pointers, you can solve the problem.
454
455 The ``Ptr`` class treats the wrapped object as a black box. The reference counter is allocated and
456 managed separately. The only thing the pointer class needs to know about the object is how to
457 deallocate it. This knowledge is encapsulated in the ``Ptr::delete_obj()`` method that is called when
458 the reference counter becomes 0. If the object is a C++ class instance, no additional coding is
459 needed, because the default implementation of this method calls ``delete obj;``. However, if the
460 object is deallocated in a different way, the specialized method should be created. For example,
461 if you want to wrap ``FILE``, the ``delete_obj`` may be implemented as follows: ::
462
463     template<> inline void Ptr<FILE>::delete_obj()
464     {
465         fclose(obj); // no need to clear the pointer afterwards,
466                      // it is done externally.
467     }
468     ...
469
470     // now use it:
471     Ptr<FILE> f(fopen("myfile.txt", "r"));
472     if(f.empty())
473         throw ...;
474     fprintf(f, ....);
475     ...
476     // the file will be closed automatically by the Ptr<FILE> destructor.
477
478
479 .. note:: The reference increment/decrement operations are implemented as atomic operations,
480           and therefore it is normally safe to use the classes in multi-threaded applications.
481           The same is true for :ocv:class:`Mat` and other C++ OpenCV classes that operate on
482           the reference counters.
483
484 Ptr::Ptr
485 --------
486 Various Ptr constructors.
487
488 .. ocv:function:: Ptr::Ptr()
489 .. ocv:function:: Ptr::Ptr(_Tp* _obj)
490 .. ocv:function:: Ptr::Ptr(const Ptr& ptr)
491
492 Ptr::~Ptr
493 ---------
494 The Ptr destructor.
495
496 .. ocv:function:: Ptr::~Ptr()
497
498 Ptr::operator =
499 ----------------
500 Assignment operator.
501
502 .. ocv:function:: Ptr& Ptr::operator = (const Ptr& ptr)
503
504 Decrements own reference counter (with ``release()``) and increments ptr's reference counter.
505
506 Ptr::addref
507 -----------
508 Increments reference counter.
509
510 .. ocv:function:: void Ptr::addref()
511
512 Ptr::release
513 ------------
514 Decrements reference counter; when it becomes 0, ``delete_obj()`` is called.
515
516 .. ocv:function:: void Ptr::release()
517
518 Ptr::delete_obj
519 ---------------
520 User-specified custom object deletion operation. By default, ``delete obj;`` is called.
521
522 .. ocv:function:: void Ptr::delete_obj()
523
524 Ptr::empty
525 ----------
526 Returns true if obj == 0;
527
528 bool empty() const;
529
530 Ptr::operator ->
531 ----------------
532 Provide access to the object fields and methods.
533
534  .. ocv:function:: template<typename _Tp> _Tp* Ptr::operator -> ()
535  .. ocv:function:: template<typename _Tp> const _Tp* Ptr::operator -> () const
536
537
538 Ptr::operator _Tp*
539 ------------------
540 Returns the underlying object pointer. Thanks to the methods, the ``Ptr<_Tp>`` can be used instead
541 of ``_Tp*``.
542
543  .. ocv:function:: template<typename _Tp> Ptr::operator _Tp* ()
544  .. ocv:function:: template<typename _Tp> Ptr::operator const _Tp*() const
545
546
547 Mat
548 ---
549 .. ocv:class:: Mat
550
551 OpenCV C++ n-dimensional dense array class ::
552
553     class CV_EXPORTS Mat
554     {
555     public:
556         // ... a lot of methods ...
557         ...
558
559         /*! includes several bit-fields:
560              - the magic signature
561              - continuity flag
562              - depth
563              - number of channels
564          */
565         int flags;
566         //! the array dimensionality, >= 2
567         int dims;
568         //! the number of rows and columns or (-1, -1) when the array has more than 2 dimensions
569         int rows, cols;
570         //! pointer to the data
571         uchar* data;
572
573         //! pointer to the reference counter;
574         // when array points to user-allocated data, the pointer is NULL
575         int* refcount;
576
577         // other members
578         ...
579     };
580
581
582 The class ``Mat`` represents an n-dimensional dense numerical single-channel or multi-channel array. It can be used to store real or complex-valued vectors and matrices, grayscale or color images, voxel volumes, vector fields, point clouds, tensors, histograms (though, very high-dimensional histograms may be better stored in a ``SparseMat`` ). The data layout of the array
583 :math:`M` is defined by the array ``M.step[]``, so that the address of element
584 :math:`(i_0,...,i_{M.dims-1})`, where
585 :math:`0\leq i_k<M.size[k]`, is computed as:
586
587 .. math::
588
589     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}
590
591 In case of a 2-dimensional array, the above formula is reduced to:
592
593 .. math::
594
595     addr(M_{i,j}) = M.data + M.step[0]*i + M.step[1]*j
596
597 Note that ``M.step[i] >= M.step[i+1]`` (in fact, ``M.step[i] >= M.step[i+1]*M.size[i+1]`` ). This means that 2-dimensional matrices are stored row-by-row, 3-dimensional matrices are stored plane-by-plane, and so on. ``M.step[M.dims-1]`` is minimal and always equal to the element size ``M.elemSize()`` .
598
599 So, the data layout in ``Mat`` is fully compatible with ``CvMat``, ``IplImage``, and ``CvMatND`` types from OpenCV 1.x. It is also compatible with the majority of dense array types from the standard toolkits and SDKs, such as Numpy (ndarray), Win32 (independent device bitmaps), and others, that is, with any array that uses *steps* (or *strides*) to compute the position of a pixel. Due to this compatibility, it is possible to make a ``Mat`` header for user-allocated data and process it in-place using OpenCV functions.
600
601 There are many different ways to create a ``Mat`` object. The most popular options are listed below:
602
603 *
604
605     Use the ``create(nrows, ncols, type)``   method or the similar ``Mat(nrows, ncols, type[, fillValue])``     constructor. A new array of the specified size and type is allocated. ``type``     has the same meaning as in the ``cvCreateMat``     method.
606     For example, ``CV_8UC1``     means a 8-bit single-channel array, ``CV_32FC2``     means a 2-channel (complex) floating-point array, and so on.
607
608     ::
609
610         // make a 7x7 complex matrix filled with 1+3j.
611         Mat M(7,7,CV_32FC2,Scalar(1,3));
612         // and now turn M to a 100x60 15-channel 8-bit matrix.
613         // The old content will be deallocated
614         M.create(100,60,CV_8UC(15));
615
616     ..
617
618     As noted in the introduction to this chapter, ``create()`` allocates only  a new array when the shape or type of the current array are different from the specified ones.
619
620 *
621
622     Create a multi-dimensional array:
623
624     ::
625
626         // create a 100x100x100 8-bit array
627         int sz[] = {100, 100, 100};
628         Mat bigCube(3, sz, CV_8U, Scalar::all(0));
629
630     ..
631
632     It passes the number of dimensions =1 to the ``Mat`` constructor but the created array will be 2-dimensional with the number of columns set to 1. So, ``Mat::dims``     is always >= 2 (can also be 0 when the array is empty).
633
634 *
635
636     Use a copy constructor or assignment operator where there can be an array or expression on the right side (see below). As noted in the introduction, the array assignment is an O(1) operation because it only copies the header and increases the reference counter. The ``Mat::clone()``     method can be used to get a full (deep) copy of the array when you need it.
637
638 *
639
640     Construct a header for a part of another array. It can be a single row, single column, several rows, several columns, rectangular region in the array (called a *minor* in algebra) or a diagonal. Such operations are also O(1) because the new header references the same data. You can actually modify a part of the array using this feature, for example:
641
642     ::
643
644         // add the 5-th row, multiplied by 3 to the 3rd row
645         M.row(3) = M.row(3) + M.row(5)*3;
646
647         // now copy the 7-th column to the 1-st column
648         // M.col(1) = M.col(7); // this will not work
649         Mat M1 = M.col(1);
650         M.col(7).copyTo(M1);
651
652         // create a new 320x240 image
653         Mat img(Size(320,240),CV_8UC3);
654         // select a ROI
655         Mat roi(img, Rect(10,10,100,100));
656         // fill the ROI with (0,255,0) (which is green in RGB space);
657         // the original 320x240 image will be modified
658         roi = Scalar(0,255,0);
659
660     ..
661
662     Due to the additional ``datastart`` and ``dataend`` members, it is possible to compute a relative sub-array position in the main *container* array using ``locateROI()``:
663
664     ::
665
666         Mat A = Mat::eye(10, 10, CV_32S);
667         // extracts A columns, 1 (inclusive) to 3 (exclusive).
668         Mat B = A(Range::all(), Range(1, 3));
669         // extracts B rows, 5 (inclusive) to 9 (exclusive).
670         // that is, C ~ A(Range(5, 9), Range(1, 3))
671         Mat C = B(Range(5, 9), Range::all());
672         Size size; Point ofs;
673         C.locateROI(size, ofs);
674         // size will be (width=10,height=10) and the ofs will be (x=1, y=5)
675
676     ..
677
678     As in case of whole matrices, if you need a deep copy, use the ``clone()`` method of the extracted sub-matrices.
679
680 *
681
682     Make a header for user-allocated data. It can be useful to do the following:
683
684     #.
685         Process "foreign" data using OpenCV (for example, when you implement a DirectShow* filter or a processing module for ``gstreamer``, and so on). For example:
686
687         ::
688
689             void process_video_frame(const unsigned char* pixels,
690                                      int width, int height, int step)
691             {
692                 Mat img(height, width, CV_8UC3, pixels, step);
693                 GaussianBlur(img, img, Size(7,7), 1.5, 1.5);
694             }
695
696         ..
697
698     #.
699         Quickly initialize small matrices and/or get a super-fast element access.
700
701         ::
702
703             double m[3][3] = {{a, b, c}, {d, e, f}, {g, h, i}};
704             Mat M = Mat(3, 3, CV_64F, m).inv();
705
706         ..
707
708     Partial yet very common cases of this *user-allocated data* case are conversions from ``CvMat`` and ``IplImage`` to ``Mat``. For this purpose, there are special constructors taking pointers to ``CvMat``     or ``IplImage`` and the optional flag indicating whether to copy the data or not.
709
710         Backward conversion from ``Mat`` to ``CvMat`` or ``IplImage`` is provided via cast operators ``Mat::operator CvMat() const`` and ``Mat::operator IplImage()``. The operators do NOT copy the data.
711
712     ::
713
714         IplImage* img = cvLoadImage("greatwave.jpg", 1);
715         Mat mtx(img); // convert IplImage* -> Mat
716         CvMat oldmat = mtx; // convert Mat -> CvMat
717         CV_Assert(oldmat.cols == img->width && oldmat.rows == img->height &&
718             oldmat.data.ptr == (uchar*)img->imageData && oldmat.step == img->widthStep);
719
720     ..
721
722 *
723
724     Use MATLAB-style array initializers, ``zeros(), ones(), eye()``, for example:
725
726     ::
727
728         // create a double-precision identity martix and add it to M.
729         M += Mat::eye(M.rows, M.cols, CV_64F);
730
731     ..
732
733 *
734
735     Use a comma-separated initializer:
736
737     ::
738
739         // create a 3x3 double-precision identity matrix
740         Mat M = (Mat_<double>(3,3) << 1, 0, 0, 0, 1, 0, 0, 0, 1);
741
742     ..
743
744     With this approach, you first call a constructor of the :ocv:class:`Mat_`  class with the proper parameters, and then you just put ``<<``     operator followed by comma-separated values that can be constants, variables, expressions, and so on. Also, note the extra parentheses required to avoid compilation errors.
745
746 Once the array is created, it is automatically managed via a reference-counting mechanism. If the array header is built on top of user-allocated data, you should handle the data by yourself.
747 The array data is deallocated when no one points to it. If you want to release the data pointed by a array header before the array destructor is called, use ``Mat::release()`` .
748
749 The next important thing to learn about the array class is element access. This manual already described how to compute an address of each array element. Normally, you are not required to use the formula directly in the code. If you know the array element type (which can be retrieved using the method ``Mat::type()`` ), you can access the element
750 :math:`M_{ij}` of a 2-dimensional array as: ::
751
752     M.at<double>(i,j) += 1.f;
753
754
755 assuming that M is a double-precision floating-point array. There are several variants of the method ``at`` for a different number of dimensions.
756
757 If you need to process a whole row of a 2D array, the most efficient way is to get the pointer to the row first, and then just use the plain C operator ``[]`` : ::
758
759     // compute sum of positive matrix elements
760     // (assuming that M isa double-precision matrix)
761     double sum=0;
762     for(int i = 0; i < M.rows; i++)
763     {
764         const double* Mi = M.ptr<double>(i);
765         for(int j = 0; j < M.cols; j++)
766             sum += std::max(Mi[j], 0.);
767     }
768
769
770 Some operations, like the one above, do not actually depend on the array shape. They just process elements of an array one by one (or elements from multiple arrays that have the same coordinates, for example, array addition). Such operations are called *element-wise*. It makes sense to check whether all the input/output arrays are continuous, namely, have no gaps at the end of each row. If yes, process them as a long single row: ::
771
772     // compute the sum of positive matrix elements, optimized variant
773     double sum=0;
774     int cols = M.cols, rows = M.rows;
775     if(M.isContinuous())
776     {
777         cols *= rows;
778         rows = 1;
779     }
780     for(int i = 0; i < rows; i++)
781     {
782         const double* Mi = M.ptr<double>(i);
783         for(int j = 0; j < cols; j++)
784             sum += std::max(Mi[j], 0.);
785     }
786
787
788 In case of the continuous matrix, the outer loop body is executed just once. So, the overhead is smaller, which is especially noticeable in case of small matrices.
789
790 Finally, there are STL-style iterators that are smart enough to skip gaps between successive rows: ::
791
792     // compute sum of positive matrix elements, iterator-based variant
793     double sum=0;
794     MatConstIterator_<double> it = M.begin<double>(), it_end = M.end<double>();
795     for(; it != it_end; ++it)
796         sum += std::max(*it, 0.);
797
798
799 The matrix iterators are random-access iterators, so they can be passed to any STL algorithm, including ``std::sort()`` .
800
801
802 .. _MatrixExpressions:
803
804 Matrix Expressions
805 ------------------
806
807 This is a list of implemented matrix operations that can be combined in arbitrary complex expressions
808 (here ``A``, ``B`` stand for matrices ( ``Mat`` ), ``s`` for a scalar ( ``Scalar`` ),
809 ``alpha`` for a real-valued scalar ( ``double`` )):
810
811 *
812     Addition, subtraction, negation:
813     ``A+B, A-B, A+s, A-s, s+A, s-A, -A``
814
815 *
816     Scaling:
817     ``A*alpha``
818
819 *
820     Per-element multiplication and division:
821     ``A.mul(B), A/B, alpha/A``
822
823 *
824     Matrix multiplication:
825     ``A*B``
826
827 *
828     Transposition:
829     ``A.t()`` (means ``A``\ :sup:`T`)
830
831 *
832     Matrix inversion and pseudo-inversion, solving linear systems and least-squares problems:
833
834     ``A.inv([method])`` (~ ``A``\ :sup:`-1`) ``,   A.inv([method])*B`` (~ ``X: AX=B``)
835
836 *
837     Comparison:
838     ``A cmpop B, A cmpop alpha, alpha cmpop A``, where ``cmpop`` is one of ``:  >, >=, ==, !=, <=, <``. The result of comparison is an 8-bit single channel mask whose elements are set to 255 (if the particular element or pair of elements satisfy the condition) or 0.
839
840 *
841     Bitwise logical operations: ``A logicop B, A logicop s, s logicop A, ~A``, where ``logicop`` is one of ``:  &, |, ^``.
842
843 *
844     Element-wise minimum and maximum:
845     ``min(A, B), min(A, alpha), max(A, B), max(A, alpha)``
846
847 *
848     Element-wise absolute value:
849     ``abs(A)``
850
851 *
852     Cross-product, dot-product:
853     ``A.cross(B)``
854     ``A.dot(B)``
855
856 *
857     Any function of matrix or matrices and scalars that returns a matrix or a scalar, such as ``norm``, ``mean``, ``sum``, ``countNonZero``, ``trace``, ``determinant``, ``repeat``, and others.
858
859 *
860     Matrix initializers ( ``Mat::eye(), Mat::zeros(), Mat::ones()`` ), matrix comma-separated initializers, matrix constructors and operators that extract sub-matrices (see :ocv:class:`Mat` description).
861
862 *
863     ``Mat_<destination_type>()`` constructors to cast the result to the proper type.
864
865 .. note:: Comma-separated initializers and probably some other operations may require additional explicit ``Mat()`` or ``Mat_<T>()`` constructor calls to resolve a possible ambiguity.
866
867 Here are examples of matrix expressions:
868
869 ::
870
871     // compute pseudo-inverse of A, equivalent to A.inv(DECOMP_SVD)
872     SVD svd(A);
873     Mat pinvA = svd.vt.t()*Mat::diag(1./svd.w)*svd.u.t();
874
875     // compute the new vector of parameters in the Levenberg-Marquardt algorithm
876     x -= (A.t()*A + lambda*Mat::eye(A.cols,A.cols,A.type())).inv(DECOMP_CHOLESKY)*(A.t()*err);
877
878     // sharpen image using "unsharp mask" algorithm
879     Mat blurred; double sigma = 1, threshold = 5, amount = 1;
880     GaussianBlur(img, blurred, Size(), sigma, sigma);
881     Mat lowConstrastMask = abs(img - blurred) < threshold;
882     Mat sharpened = img*(1+amount) + blurred*(-amount);
883     img.copyTo(sharpened, lowContrastMask);
884
885 ..
886
887
888 Below is the formal description of the ``Mat`` methods.
889
890 Mat::Mat
891 --------
892 Various Mat constructors
893
894 .. ocv:function:: Mat::Mat()
895
896 .. ocv:function:: Mat::Mat(int rows, int cols, int type)
897
898 .. ocv:function:: Mat::Mat(Size size, int type)
899
900 .. ocv:function:: Mat::Mat(int rows, int cols, int type, const Scalar& s)
901
902 .. ocv:function:: Mat::Mat(Size size, int type, const Scalar& s)
903
904 .. ocv:function:: Mat::Mat(const Mat& m)
905
906 .. ocv:function:: Mat::Mat(int rows, int cols, int type, void* data, size_t step=AUTO_STEP)
907
908 .. ocv:function:: Mat::Mat(Size size, int type, void* data, size_t step=AUTO_STEP)
909
910 .. ocv:function:: Mat::Mat( const Mat& m, const Range& rowRange, const Range& colRange=Range::all() )
911
912 .. ocv:function:: Mat::Mat(const Mat& m, const Rect& roi)
913
914 .. ocv:function:: Mat::Mat(const CvMat* m, bool copyData=false)
915
916 .. ocv:function:: Mat::Mat(const IplImage* img, bool copyData=false)
917
918 .. ocv:function:: template<typename T, int n> explicit Mat::Mat(const Vec<T, n>& vec, bool copyData=true)
919
920 .. ocv:function:: template<typename T, int m, int n> explicit Mat::Mat(const Matx<T, m, n>& vec, bool copyData=true)
921
922 .. ocv:function:: template<typename T> explicit Mat::Mat(const vector<T>& vec, bool copyData=false)
923
924 .. ocv:function:: Mat::Mat(int ndims, const int* sizes, int type)
925
926 .. ocv:function:: Mat::Mat(int ndims, const int* sizes, int type, const Scalar& s)
927
928 .. ocv:function:: Mat::Mat(int ndims, const int* sizes, int type, void* data, const size_t* steps=0)
929
930 .. ocv:function:: Mat::Mat(const Mat& m, const Range* ranges)
931
932     :param ndims: Array dimensionality.
933
934     :param rows: Number of rows in a 2D array.
935
936     :param cols: Number of columns in a 2D array.
937
938     :param roi: Region of interest.
939
940     :param size: 2D array size:  ``Size(cols, rows)`` . In the  ``Size()``  constructor, the number of rows and the number of columns go in the reverse order.
941
942     :param sizes: Array of integers specifying an n-dimensional array shape.
943
944     :param type: Array type. Use  ``CV_8UC1, ..., CV_64FC4``  to create 1-4 channel matrices, or  ``CV_8UC(n), ..., CV_64FC(n)``  to create multi-channel (up to  ``CV_MAX_CN``  channels) matrices.
945
946     :param s: An optional value to initialize each matrix element with. To set all the matrix elements to the particular value after the construction, use the assignment operator  ``Mat::operator=(const Scalar& value)`` .
947
948     :param data: Pointer to the user data. Matrix constructors that take  ``data``  and  ``step``  parameters do not allocate matrix data. Instead, they just initialize the matrix header that points to the specified data, which means that no data is copied. This operation is very efficient and can be used to process external data using OpenCV functions. The external data is not automatically deallocated, so you should take care of it.
949
950     :param step: Number of bytes each matrix row occupies. The value should include the padding bytes at the end of each row, if any. If the parameter is missing (set to  ``AUTO_STEP`` ), no padding is assumed and the actual step is calculated as  ``cols*elemSize()`` . See  :ocv:func:`Mat::elemSize` .
951
952     :param steps: Array of  ``ndims-1``  steps in case of a multi-dimensional array (the last step is always set to the element size). If not specified, the matrix is assumed to be continuous.
953
954     :param m: Array that (as a whole or partly) is assigned to the constructed matrix. No data is copied by these constructors. Instead, the header pointing to  ``m``  data or its sub-array is constructed and associated with it. The reference counter, if any, is incremented. So, when you modify the matrix formed using such a constructor, you also modify the corresponding elements of  ``m`` . If you want to have an independent copy of the sub-array, use  ``Mat::clone()`` .
955
956     :param img: Pointer to the old-style  ``IplImage``  image structure. By default, the data is shared between the original image and the new matrix. But when  ``copyData``  is set, the full copy of the image data is created.
957
958     :param vec: STL vector whose elements form the matrix. The matrix has a single column and the number of rows equal to the number of vector elements. Type of the matrix matches the type of vector elements. The constructor can handle arbitrary types, for which there is a properly declared  :ocv:class:`DataType` . This means that the vector elements must be primitive numbers or uni-type numerical tuples of numbers. Mixed-type structures are not supported. The corresponding constructor is explicit. Since STL vectors are not automatically converted to  ``Mat``  instances, you should write  ``Mat(vec)``  explicitly. Unless you copy the data into the matrix ( ``copyData=true`` ), no new elements will be added to the vector because it can potentially yield vector data reallocation, and, thus, the matrix data pointer will be invalid.
959
960     :param copyData: Flag to specify whether the underlying data of the STL vector or the old-style  ``CvMat``  or  ``IplImage``  should be copied to (``true``) or shared with (``false``) the newly constructed matrix. When the data is copied, the allocated buffer is managed using  ``Mat`` reference counting mechanism. While the data is shared, the reference counter is NULL, and you should not deallocate the data until the matrix is not destructed.
961
962     :param rowRange: Range of the  ``m`` rows to take. As usual, the range start is inclusive and the range end is exclusive. Use  ``Range::all()``  to take all the rows.
963
964     :param colRange: Range of the  ``m`` columns to take. Use  ``Range::all()``  to take all the columns.
965
966     :param ranges: Array of selected ranges of  ``m``  along each dimensionality.
967
968 These are various constructors that form a matrix. As noted in the :ref:`AutomaticAllocation`,
969 often the default constructor is enough, and the proper matrix will be allocated by an OpenCV function. The constructed matrix can further be assigned to another matrix or matrix expression or can be allocated with
970 :ocv:func:`Mat::create` . In the former case, the old content is de-referenced.
971
972
973 Mat::~Mat
974 ---------
975 The Mat destructor.
976
977 .. ocv:function:: Mat::~Mat()
978
979 The matrix destructor calls :ocv:func:`Mat::release` .
980
981
982 Mat::operator =
983 ---------------
984 Provides matrix assignment operators.
985
986 .. ocv:function:: Mat& Mat::operator = (const Mat& m)
987
988 .. ocv:function:: Mat& Mat::operator =( const MatExpr& expr )
989
990 .. ocv:function:: Mat& Mat::operator = (const Scalar& s)
991
992     :param m: Assigned, right-hand-side matrix. Matrix assignment is an O(1) operation. This means that no data is copied but the data is shared and the reference counter, if any, is incremented. Before assigning new data, the old data is de-referenced via  :ocv:func:`Mat::release` .
993
994     :param expr: Assigned matrix expression object. As opposite to the first form of the assignment operation, the second form can reuse already allocated matrix if it has the right size and type to fit the matrix expression result. It is automatically handled by the real function that the matrix expressions is expanded to. For example,  ``C=A+B``  is expanded to  ``add(A, B, C)``, and  :func:`add`  takes care of automatic  ``C``  reallocation.
995
996     :param s: Scalar assigned to each matrix element. The matrix size or type is not changed.
997
998 These are available assignment operators. Since they all are very different, make sure to read the operator parameters description.
999
1000 Mat::row
1001 --------
1002 Creates a matrix header for the specified matrix row.
1003
1004 .. ocv:function:: Mat Mat::row(int y) const
1005
1006     :param y: A 0-based row index.
1007
1008 The method makes a new header for the specified matrix row and returns it. This is an O(1) operation, regardless of the matrix size. The underlying data of the new matrix is shared with the original matrix. Here is the example of one of the classical basic matrix processing operations, ``axpy``, used by LU and many other algorithms: ::
1009
1010     inline void matrix_axpy(Mat& A, int i, int j, double alpha)
1011     {
1012         A.row(i) += A.row(j)*alpha;
1013     }
1014
1015
1016 .. note::
1017
1018     In the current implementation, the following code does not work as expected: ::
1019
1020         Mat A;
1021         ...
1022         A.row(i) = A.row(j); // will not work
1023
1024
1025     This happens because ``A.row(i)`` forms a temporary header that is further assigned to another header. Remember that each of these operations is O(1), that is, no data is copied. Thus, the above assignment is not true if you may have expected the j-th row to be copied to the i-th row. To achieve that, you should either turn this simple assignment into an expression or use the :ocv:func:`Mat::copyTo` method: ::
1026
1027         Mat A;
1028         ...
1029         // works, but looks a bit obscure.
1030         A.row(i) = A.row(j) + 0;
1031
1032         // this is a bit longer, but the recommended method.
1033         A.row(j).copyTo(A.row(i));
1034
1035 Mat::col
1036 --------
1037 Creates a matrix header for the specified matrix column.
1038
1039 .. ocv:function:: Mat Mat::col(int x) const
1040
1041     :param x: A 0-based column index.
1042
1043 The method makes a new header for the specified matrix column and returns it. This is an O(1) operation, regardless of the matrix size. The underlying data of the new matrix is shared with the original matrix. See also the
1044 :ocv:func:`Mat::row` description.
1045
1046
1047 Mat::rowRange
1048 -------------
1049 Creates a matrix header for the specified row span.
1050
1051 .. ocv:function:: Mat Mat::rowRange(int startrow, int endrow) const
1052
1053 .. ocv:function:: Mat Mat::rowRange(const Range& r) const
1054
1055     :param startrow: An inclusive 0-based start index of the row span.
1056
1057     :param endrow: An exclusive 0-based ending index of the row span.
1058
1059     :param r: :ocv:class:`Range` structure containing both the start and the end indices.
1060
1061 The method makes a new header for the specified row span of the matrix. Similarly to
1062 :ocv:func:`Mat::row` and
1063 :ocv:func:`Mat::col` , this is an O(1) operation.
1064
1065 Mat::colRange
1066 -------------
1067 Creates a matrix header for the specified row span.
1068
1069 .. ocv:function:: Mat Mat::colRange(int startcol, int endcol) const
1070
1071 .. ocv:function:: Mat Mat::colRange(const Range& r) const
1072
1073     :param startcol: An inclusive 0-based start index of the column span.
1074
1075     :param endcol: An exclusive 0-based ending index of the column span.
1076
1077     :param r: :ocv:class:`Range`  structure containing both the start and the end indices.
1078
1079 The method makes a new header for the specified column span of the matrix. Similarly to
1080 :ocv:func:`Mat::row` and
1081 :ocv:func:`Mat::col` , this is an O(1) operation.
1082
1083 Mat::diag
1084 ---------
1085 Extracts a diagonal from a matrix, or creates a diagonal matrix.
1086
1087 .. ocv:function:: Mat Mat::diag( int d=0 ) const
1088
1089 .. ocv:function:: static Mat Mat::diag( const Mat& d )
1090
1091     :param d: Single-column matrix that forms a diagonal matrix or index of the diagonal, with the following values:
1092
1093         * **d=0** is the main diagonal.
1094
1095         * **d>0** is a diagonal from the lower half. For example,  ``d=1``  means the diagonal is set immediately below the main one.
1096
1097         * **d<0** is a diagonal from the upper half. For example,  ``d=1``  means the diagonal is set immediately above the main one.
1098
1099 The method makes a new header for the specified matrix diagonal. The new matrix is represented as a single-column matrix. Similarly to
1100 :ocv:func:`Mat::row` and
1101 :ocv:func:`Mat::col` , this is an O(1) operation.
1102
1103 Mat::clone
1104 ----------
1105 Creates a full copy of the array and the underlying data.
1106
1107 .. ocv:function:: Mat Mat::clone() const
1108
1109 The method creates a full copy of the array. The original ``step[]`` is not taken into account. So, the array copy is a continuous array occupying ``total()*elemSize()`` bytes.
1110
1111
1112 Mat::copyTo
1113 -----------
1114 Copies the matrix to another one.
1115
1116 .. ocv:function:: void Mat::copyTo( OutputArray m ) const
1117 .. ocv:function:: void Mat::copyTo( OutputArray m, InputArray mask ) const
1118
1119     :param m: Destination matrix. If it does not have a proper size or type before the operation, it is reallocated.
1120
1121     :param mask: Operation mask. Its non-zero elements indicate which matrix elements need to be copied.
1122
1123 The method copies the matrix data to another matrix. Before copying the data, the method invokes ::
1124
1125     m.create(this->size(), this->type);
1126
1127
1128 so that the destination matrix is reallocated if needed. While ``m.copyTo(m);`` works flawlessly, the function does not handle the case of a partial overlap between the source and the destination matrices.
1129
1130 When the operation mask is specified, and the ``Mat::create`` call shown above reallocated the matrix, the newly allocated matrix is initialized with all zeros before copying the data.
1131
1132 .. _Mat::convertTo:
1133
1134 Mat::convertTo
1135 --------------
1136 Converts an array to another data type with optional scaling.
1137
1138 .. ocv:function:: void Mat::convertTo( OutputArray m, int rtype, double alpha=1, double beta=0 ) const
1139
1140     :param m: output matrix; if it does not have a proper size or type before the operation, it is reallocated.
1141
1142     :param rtype: desired output matrix type or, rather, the depth since the number of channels are the same as the input has; if ``rtype``  is negative, the output matrix will have the same type as the input.
1143
1144     :param alpha: optional scale factor.
1145
1146     :param beta: optional delta added to the scaled values.
1147
1148 The method converts source pixel values to the target data type. ``saturate_cast<>`` is applied at the end to avoid possible overflows:
1149
1150 .. math::
1151
1152     m(x,y) = saturate \_ cast<rType>( \alpha (*this)(x,y) +  \beta )
1153
1154
1155 Mat::assignTo
1156 -------------
1157 Provides a functional form of ``convertTo``.
1158
1159 .. ocv:function:: void Mat::assignTo( Mat& m, int type=-1 ) const
1160
1161     :param m: Destination array.
1162
1163     :param type: Desired destination array depth (or -1 if it should be the same as the source type).
1164
1165 This is an internally used method called by the
1166 :ref:`MatrixExpressions` engine.
1167
1168 Mat::setTo
1169 ----------
1170 Sets all or some of the array elements to the specified value.
1171
1172 .. ocv:function:: Mat& Mat::setTo( InputArray value, InputArray mask=noArray() )
1173
1174     :param value: Assigned scalar converted to the actual array type.
1175
1176     :param mask: Operation mask of the same size as  ``*this``. This is an advanced variant of the ``Mat::operator=(const Scalar& s)`` operator.
1177
1178
1179 Mat::reshape
1180 ------------
1181 Changes the shape and/or the number of channels of a 2D matrix without copying the data.
1182
1183 .. ocv:function:: Mat Mat::reshape(int cn, int rows=0) const
1184
1185     :param cn: New number of channels. If the parameter is 0, the number of channels remains the same.
1186
1187     :param rows: New number of rows. If the parameter is 0, the number of rows remains the same.
1188
1189 The method makes a new matrix header for ``*this`` elements. The new matrix may have a different size and/or different number of channels. Any combination is possible if:
1190
1191 *
1192     No extra elements are included into the new matrix and no elements are excluded. Consequently, the product ``rows*cols*channels()``     must stay the same after the transformation.
1193
1194 *
1195     No data is copied. That is, this is an O(1) operation. Consequently, if you change the number of rows, or the operation changes the indices of elements row  in some other way, the matrix must be continuous. See
1196     :ocv:func:`Mat::isContinuous` .
1197
1198 For example, if there is a set of 3D points stored as an STL vector, and you want to represent the points as a ``3xN`` matrix, do the following: ::
1199
1200     std::vector<Point3f> vec;
1201     ...
1202
1203     Mat pointMat = Mat(vec). // convert vector to Mat, O(1) operation
1204                       reshape(1). // make Nx3 1-channel matrix out of Nx1 3-channel.
1205                                   // Also, an O(1) operation
1206                          t(); // finally, transpose the Nx3 matrix.
1207                               // This involves copying all the elements
1208
1209
1210
1211
1212 Mat::t
1213 ------
1214 Transposes a matrix.
1215
1216 .. ocv:function:: MatExpr Mat::t() const
1217
1218 The method performs matrix transposition by means of matrix expressions. It does not perform the actual transposition but returns a temporary matrix transposition object that can be further used as a part of more complex matrix expressions or can be assigned to a matrix: ::
1219
1220     Mat A1 = A + Mat::eye(A.size(), A.type)*lambda;
1221     Mat C = A1.t()*A1; // compute (A + lambda*I)^t * (A + lamda*I)
1222
1223
1224 Mat::inv
1225 --------
1226 Inverses a matrix.
1227
1228 .. ocv:function:: MatExpr Mat::inv(int method=DECOMP_LU) const
1229
1230     :param method: Matrix inversion method. Possible values are the following:
1231
1232         * **DECOMP_LU** is the LU decomposition. The matrix must be non-singular.
1233
1234         * **DECOMP_CHOLESKY** is the Cholesky  :math:`LL^T`  decomposition for symmetrical positively defined matrices only. This type is about twice faster than LU on big matrices.
1235
1236         * **DECOMP_SVD** is the SVD decomposition. If the matrix is singular or even non-square, the pseudo inversion is computed.
1237
1238 The method performs a matrix inversion by means of matrix expressions. This means that a temporary matrix inversion object is returned by the method and can be used further as a part of more complex matrix expressions or can be assigned to a matrix.
1239
1240
1241 Mat::mul
1242 --------
1243 Performs an element-wise multiplication or division of the two matrices.
1244
1245 .. ocv:function:: MatExpr Mat::mul(InputArray m, double scale=1) const
1246
1247     :param m: Another array of the same type and the same size as ``*this``, or a matrix expression.
1248
1249     :param scale: Optional scale factor.
1250
1251 The method returns a temporary object encoding per-element array multiplication, with optional scale. Note that this is not a matrix multiplication that corresponds to a simpler "*" operator.
1252
1253 Example: ::
1254
1255     Mat C = A.mul(5/B); // equivalent to divide(A, B, C, 5)
1256
1257
1258 Mat::cross
1259 ----------
1260 Computes a cross-product of two 3-element vectors.
1261
1262 .. ocv:function:: Mat Mat::cross(InputArray m) const
1263
1264     :param m: Another cross-product operand.
1265
1266 The method computes a cross-product of two 3-element vectors. The vectors must be 3-element floating-point vectors of the same shape and size. The result is another 3-element vector of the same shape and type as operands.
1267
1268
1269 Mat::dot
1270 --------
1271 Computes a dot-product of two vectors.
1272
1273 .. ocv:function:: double Mat::dot(InputArray m) const
1274
1275     :param m: another dot-product operand.
1276
1277 The method computes a dot-product of two matrices. If the matrices are not single-column or single-row vectors, the top-to-bottom left-to-right scan ordering is used to treat them as 1D vectors. The vectors must have the same size and type. If the matrices have more than one channel, the dot products from all the channels are summed together.
1278
1279
1280 Mat::zeros
1281 ----------
1282 Returns a zero array of the specified size and type.
1283
1284 .. ocv:function:: static MatExpr Mat::zeros(int rows, int cols, int type)
1285 .. ocv:function:: static MatExpr Mat::zeros(Size size, int type)
1286 .. ocv:function:: static MatExpr Mat::zeros( int ndims, const int* sz, int type )
1287
1288     :param ndims: Array dimensionality.
1289
1290     :param rows: Number of rows.
1291
1292     :param cols: Number of columns.
1293
1294     :param size: Alternative to the matrix size specification ``Size(cols, rows)``  .
1295
1296     :param sz: Array of integers specifying the array shape.
1297
1298     :param type: Created matrix type.
1299
1300 The method returns a Matlab-style zero array initializer. It can be used to quickly form a constant array as a function parameter, part of a matrix expression, or as a matrix initializer. ::
1301
1302     Mat A;
1303     A = Mat::zeros(3, 3, CV_32F);
1304
1305
1306 In the example above, a new matrix is allocated only if ``A`` is not a 3x3 floating-point matrix. Otherwise, the existing matrix ``A`` is filled with zeros.
1307
1308
1309 Mat::ones
1310 -------------
1311 Returns an array of all 1's of the specified size and type.
1312
1313 .. ocv:function:: static MatExpr Mat::ones(int rows, int cols, int type)
1314 .. ocv:function:: static MatExpr Mat::ones(Size size, int type)
1315 .. ocv:function:: static MatExpr Mat::ones( int ndims, const int* sz, int type )
1316
1317     :param ndims: Array dimensionality.
1318
1319     :param rows: Number of rows.
1320
1321     :param cols: Number of columns.
1322
1323     :param size: Alternative to the matrix size specification  ``Size(cols, rows)``  .
1324
1325     :param sz: Array of integers specifying the array shape.
1326
1327     :param type: Created matrix type.
1328
1329 The method returns a Matlab-style 1's array initializer, similarly to
1330 :ocv:func:`Mat::zeros`. Note that using this method you can initialize an array with an arbitrary value, using the following Matlab idiom: ::
1331
1332     Mat A = Mat::ones(100, 100, CV_8U)*3; // make 100x100 matrix filled with 3.
1333
1334
1335 The above operation does not form a 100x100 matrix of 1's and then multiply it by 3. Instead, it just remembers the scale factor (3 in this case) and use it when actually invoking the matrix initializer.
1336
1337
1338 Mat::eye
1339 ------------
1340 Returns an identity matrix of the specified size and type.
1341
1342 .. ocv:function:: static MatExpr Mat::eye(int rows, int cols, int type)
1343 .. ocv:function:: static MatExpr Mat::eye(Size size, int type)
1344
1345     :param rows: Number of rows.
1346
1347     :param cols: Number of columns.
1348
1349     :param size: Alternative matrix size specification as  ``Size(cols, rows)`` .
1350
1351     :param type: Created matrix type.
1352
1353 The method returns a Matlab-style identity matrix initializer, similarly to
1354 :ocv:func:`Mat::zeros`. Similarly to
1355 :ocv:func:`Mat::ones`, you can use a scale operation to create a scaled identity matrix efficiently: ::
1356
1357     // make a 4x4 diagonal matrix with 0.1's on the diagonal.
1358     Mat A = Mat::eye(4, 4, CV_32F)*0.1;
1359
1360
1361 Mat::create
1362 ---------------
1363 Allocates new array data if needed.
1364
1365 .. ocv:function:: void Mat::create(int rows, int cols, int type)
1366 .. ocv:function:: void Mat::create(Size size, int type)
1367 .. ocv:function:: void Mat::create(int ndims, const int* sizes, int type)
1368
1369     :param ndims: New array dimensionality.
1370
1371     :param rows: New number of rows.
1372
1373     :param cols: New number of columns.
1374
1375     :param size: Alternative new matrix size specification:  ``Size(cols, rows)``
1376
1377     :param sizes: Array of integers specifying a new array shape.
1378
1379     :param type: New matrix type.
1380
1381 This is one of the key ``Mat`` methods. Most new-style OpenCV functions and methods that produce arrays call this method for each output array. The method uses the following algorithm:
1382
1383 #.
1384     If the current array shape and the type match the new ones, return immediately. Otherwise, de-reference the previous data by calling
1385     :ocv:func:`Mat::release`.
1386
1387 #.
1388     Initialize the new header.
1389
1390 #.
1391     Allocate the new data of ``total()*elemSize()``     bytes.
1392
1393 #.
1394     Allocate the new, associated with the data, reference counter and set it to 1.
1395
1396 Such a scheme makes the memory management robust and efficient at the same time and helps avoid extra typing for you. This means that usually there is no need to explicitly allocate output arrays. That is, instead of writing: ::
1397
1398     Mat color;
1399     ...
1400     Mat gray(color.rows, color.cols, color.depth());
1401     cvtColor(color, gray, CV_BGR2GRAY);
1402
1403
1404 you can simply write: ::
1405
1406     Mat color;
1407     ...
1408     Mat gray;
1409     cvtColor(color, gray, CV_BGR2GRAY);
1410
1411
1412 because ``cvtColor`` , as well as the most of OpenCV functions, calls ``Mat::create()`` for the output array internally.
1413
1414
1415 Mat::addref
1416 -----------
1417 Increments the reference counter.
1418
1419 .. ocv:function:: void Mat::addref()
1420
1421 The method increments the reference counter associated with the matrix data. If the matrix header points to an external data set (see
1422 :ocv:func:`Mat::Mat` ), the reference counter is NULL, and the method has no effect in this case. Normally, to avoid memory leaks, the method should not be called explicitly. It is called implicitly by the matrix assignment operator. The reference counter increment is an atomic operation on the platforms that support it. Thus, it is safe to operate on the same matrices asynchronously in different threads.
1423
1424
1425 Mat::release
1426 ------------
1427 Decrements the reference counter and deallocates the matrix if needed.
1428
1429 .. ocv:function:: void Mat::release()
1430
1431 The method decrements the reference counter associated with the matrix data. When the reference counter reaches 0, the matrix data is deallocated and the data and the reference counter pointers are set to NULL's. If the matrix header points to an external data set (see
1432 :ocv:func:`Mat::Mat` ), the reference counter is NULL, and the method has no effect in this case.
1433
1434 This method can be called manually to force the matrix data deallocation. But since this method is automatically called in the destructor, or by any other method that changes the data pointer, it is usually not needed. The reference counter decrement and check for 0 is an atomic operation on the platforms that support it. Thus, it is safe to operate on the same matrices asynchronously in different threads.
1435
1436 Mat::resize
1437 -----------
1438 Changes the number of matrix rows.
1439
1440 .. ocv:function:: void Mat::resize( size_t sz )
1441 .. ocv:function:: void Mat::resize( size_t sz, const Scalar& s )
1442
1443     :param sz: New number of rows.
1444     :param s: Value assigned to the newly added elements.
1445
1446 The methods change the number of matrix rows. If the matrix is reallocated, the first ``min(Mat::rows, sz)`` rows are preserved. The methods emulate the corresponding methods of the STL vector class.
1447
1448
1449 Mat::reserve
1450 ------------
1451 Reserves space for the certain number of rows.
1452
1453 .. ocv:function:: void Mat::reserve( size_t sz )
1454
1455     :param sz: Number of rows.
1456
1457 The method reserves space for ``sz`` rows. If the matrix already has enough space to store ``sz`` rows, nothing happens. If the matrix is reallocated, the first ``Mat::rows`` rows are preserved. The method emulates the corresponding method of the STL vector class.
1458
1459 Mat::push_back
1460 --------------
1461 Adds elements to the bottom of the matrix.
1462
1463 .. ocv:function:: template<typename T> void Mat::push_back(const T& elem)
1464
1465 .. ocv:function:: void Mat::push_back( const Mat& m )
1466
1467     :param elem: Added element(s).
1468
1469 The methods add one or more elements to the bottom of the matrix. They emulate the corresponding method of the STL vector class. When ``elem`` is ``Mat`` , its type and the number of columns must be the same as in the container matrix.
1470
1471 Mat::pop_back
1472 -------------
1473 Removes elements from the bottom of the matrix.
1474
1475 .. ocv:function:: template<typename T> void Mat::pop_back(size_t nelems=1)
1476
1477     :param nelems: Number of removed rows. If it is greater than the total number of rows, an exception is thrown.
1478
1479 The method removes one or more rows from the bottom of the matrix.
1480
1481
1482 Mat::locateROI
1483 --------------
1484 Locates the matrix header within a parent matrix.
1485
1486 .. ocv:function:: void Mat::locateROI( Size& wholeSize, Point& ofs ) const
1487
1488     :param wholeSize: Output parameter that contains the size of the whole matrix containing ``*this`` as a part.
1489
1490     :param ofs: Output parameter that contains an offset of  ``*this``  inside the whole matrix.
1491
1492 After you extracted a submatrix from a matrix using
1493 :ocv:func:`Mat::row`,
1494 :ocv:func:`Mat::col`,
1495 :ocv:func:`Mat::rowRange`,
1496 :ocv:func:`Mat::colRange` , and others, the resultant submatrix points just to the part of the original big matrix. However, each submatrix contains information (represented by ``datastart`` and ``dataend`` fields) that helps reconstruct the original matrix size and the position of the extracted submatrix within the original matrix. The method ``locateROI`` does exactly that.
1497
1498
1499 Mat::adjustROI
1500 --------------
1501 Adjusts a submatrix size and position within the parent matrix.
1502
1503 .. ocv:function:: Mat& Mat::adjustROI( int dtop, int dbottom, int dleft, int dright )
1504
1505     :param dtop: Shift of the top submatrix boundary upwards.
1506
1507     :param dbottom: Shift of the bottom submatrix boundary downwards.
1508
1509     :param dleft: Shift of the left submatrix boundary to the left.
1510
1511     :param dright: Shift of the right submatrix boundary to the right.
1512
1513 The method is complimentary to
1514 :ocv:func:`Mat::locateROI` . The typical use of these functions is to determine the submatrix position within the parent matrix and then shift the position somehow. Typically, it can be required for filtering operations when pixels outside of the ROI should be taken into account. When all the method parameters are positive, the ROI needs to grow in all directions by the specified amount, for example: ::
1515
1516     A.adjustROI(2, 2, 2, 2);
1517
1518
1519 In this example, the matrix size is increased by 4 elements in each direction. The matrix is shifted by 2 elements to the left and 2 elements up, which brings in all the necessary pixels for the filtering with the 5x5 kernel.
1520
1521 ``adjustROI`` forces the adjusted ROI to be inside of the parent matrix that is boundaries of the adjusted ROI are constrained by boundaries of the parent matrix. For example, if the submatrix ``A`` is located in the first row of a parent matrix and you called ``A.adjustROI(2, 2, 2, 2)`` then ``A`` will not be increased in the upward direction.
1522
1523 The function is used internally by the OpenCV filtering functions, like
1524 :ocv:func:`filter2D` , morphological operations, and so on.
1525
1526 .. seealso:: :ocv:func:`copyMakeBorder`
1527
1528
1529 Mat::operator()
1530 ---------------
1531 Extracts a rectangular submatrix.
1532
1533 .. ocv:function:: Mat Mat::operator()( Range rowRange, Range colRange ) const
1534
1535 .. ocv:function:: Mat Mat::operator()( const Rect& roi ) const
1536
1537 .. ocv:function:: Mat Mat::operator()( const Range* ranges ) const
1538
1539
1540     :param rowRange: Start and end row of the extracted submatrix. The upper boundary is not included. To select all the rows, use ``Range::all()``.
1541
1542     :param colRange: Start and end column of the extracted submatrix. The upper boundary is not included. To select all the columns, use  ``Range::all()``.
1543
1544     :param roi: Extracted submatrix specified as a rectangle.
1545
1546     :param ranges: Array of selected ranges along each array dimension.
1547
1548 The operators make a new header for the specified sub-array of ``*this`` . They are the most generalized forms of
1549 :ocv:func:`Mat::row`,
1550 :ocv:func:`Mat::col`,
1551 :ocv:func:`Mat::rowRange`, and
1552 :ocv:func:`Mat::colRange` . For example, ``A(Range(0, 10), Range::all())`` is equivalent to ``A.rowRange(0, 10)`` . Similarly to all of the above, the operators are O(1) operations, that is, no matrix data is copied.
1553
1554
1555 Mat::operator CvMat
1556 -------------------
1557 Creates the ``CvMat`` header for the matrix.
1558
1559 .. ocv:function:: Mat::operator CvMat() const
1560
1561
1562 The operator creates the ``CvMat`` header for the matrix without copying the underlying data. The reference counter is not taken into account by this operation. Thus, you should make sure than the original matrix is not deallocated while the ``CvMat`` header is used. The operator is useful for intermixing the new and the old OpenCV API's, for example: ::
1563
1564     Mat img(Size(320, 240), CV_8UC3);
1565     ...
1566
1567     CvMat cvimg = img;
1568     mycvOldFunc( &cvimg, ...);
1569
1570
1571 where ``mycvOldFunc`` is a function written to work with OpenCV 1.x data structures.
1572
1573
1574 Mat::operator IplImage
1575 ----------------------
1576 Creates the ``IplImage`` header for the matrix.
1577
1578 .. ocv:function:: Mat::operator IplImage() const
1579
1580 The operator creates the ``IplImage`` header for the matrix without copying the underlying data. You should make sure than the original matrix is not deallocated while the ``IplImage`` header is used. Similarly to ``Mat::operator CvMat`` , the operator is useful for intermixing the new and the old OpenCV API's.
1581
1582 Mat::total
1583 ----------
1584 Returns the total number of array elements.
1585
1586 .. ocv:function:: size_t Mat::total() const
1587
1588 The method returns the number of array elements (a number of pixels if the array represents an image).
1589
1590 Mat::isContinuous
1591 -----------------
1592 Reports whether the matrix is continuous or not.
1593
1594 .. ocv:function:: bool Mat::isContinuous() const
1595
1596 The method returns ``true`` if the matrix elements are stored continuously without gaps at the end of each row. Otherwise, it returns ``false``. Obviously, ``1x1`` or ``1xN`` matrices are always continuous. Matrices created with
1597 :ocv:func:`Mat::create` are always continuous. But if you extract a part of the matrix using
1598 :ocv:func:`Mat::col`,
1599 :ocv:func:`Mat::diag` , and so on, or constructed a matrix header for externally allocated data, such matrices may no longer have this property.
1600
1601 The continuity flag is stored as a bit in the ``Mat::flags`` field and is computed automatically when you construct a matrix header. Thus, the continuity check is a very fast operation, though theoretically it could be done as follows: ::
1602
1603     // alternative implementation of Mat::isContinuous()
1604     bool myCheckMatContinuity(const Mat& m)
1605     {
1606         //return (m.flags & Mat::CONTINUOUS_FLAG) != 0;
1607         return m.rows == 1 || m.step == m.cols*m.elemSize();
1608     }
1609
1610
1611 The method is used in quite a few of OpenCV functions. The point is that element-wise operations (such as arithmetic and logical operations, math functions, alpha blending, color space transformations, and others) do not depend on the image geometry. Thus, if all the input and output arrays are continuous, the functions can process them as very long single-row vectors. The example below illustrates how an alpha-blending function can be implemented. ::
1612
1613     template<typename T>
1614     void alphaBlendRGBA(const Mat& src1, const Mat& src2, Mat& dst)
1615     {
1616         const float alpha_scale = (float)std::numeric_limits<T>::max(),
1617                     inv_scale = 1.f/alpha_scale;
1618
1619         CV_Assert( src1.type() == src2.type() &&
1620                    src1.type() == CV_MAKETYPE(DataType<T>::depth, 4) &&
1621                    src1.size() == src2.size());
1622         Size size = src1.size();
1623         dst.create(size, src1.type());
1624
1625         // here is the idiom: check the arrays for continuity and,
1626         // if this is the case,
1627         // treat the arrays as 1D vectors
1628         if( src1.isContinuous() && src2.isContinuous() && dst.isContinuous() )
1629         {
1630             size.width *= size.height;
1631             size.height = 1;
1632         }
1633         size.width *= 4;
1634
1635         for( int i = 0; i < size.height; i++ )
1636         {
1637             // when the arrays are continuous,
1638             // the outer loop is executed only once
1639             const T* ptr1 = src1.ptr<T>(i);
1640             const T* ptr2 = src2.ptr<T>(i);
1641             T* dptr = dst.ptr<T>(i);
1642
1643             for( int j = 0; j < size.width; j += 4 )
1644             {
1645                 float alpha = ptr1[j+3]*inv_scale, beta = ptr2[j+3]*inv_scale;
1646                 dptr[j] = saturate_cast<T>(ptr1[j]*alpha + ptr2[j]*beta);
1647                 dptr[j+1] = saturate_cast<T>(ptr1[j+1]*alpha + ptr2[j+1]*beta);
1648                 dptr[j+2] = saturate_cast<T>(ptr1[j+2]*alpha + ptr2[j+2]*beta);
1649                 dptr[j+3] = saturate_cast<T>((1 - (1-alpha)*(1-beta))*alpha_scale);
1650             }
1651         }
1652     }
1653
1654
1655 This approach, while being very simple, can boost the performance of a simple element-operation by 10-20 percents, especially if the image is rather small and the operation is quite simple.
1656
1657 Another OpenCV idiom in this function, a call of
1658 :ocv:func:`Mat::create` for the destination array, that allocates the destination array unless it already has the proper size and type. And while the newly allocated arrays are always continuous, you still need to check the destination array because :ocv:func:`Mat::create` does not always allocate a new matrix.
1659
1660
1661 Mat::elemSize
1662 -------------
1663 Returns  the matrix element size in bytes.
1664
1665 .. ocv:function:: size_t Mat::elemSize() const
1666
1667 The method returns the matrix element size in bytes. For example, if the matrix type is ``CV_16SC3`` , the method returns ``3*sizeof(short)`` or 6.
1668
1669
1670 Mat::elemSize1
1671 --------------
1672 Returns the size of each matrix element channel in bytes.
1673
1674 .. ocv:function:: size_t Mat::elemSize1() const
1675
1676 The method returns the matrix element channel size in bytes, that is, it ignores the number of channels. For example, if the matrix type is ``CV_16SC3`` , the method returns ``sizeof(short)`` or 2.
1677
1678
1679 Mat::type
1680 ---------
1681 Returns the type of a matrix element.
1682
1683 .. ocv:function:: int Mat::type() const
1684
1685 The method returns a matrix element type. This is an identifier compatible with the ``CvMat`` type system, like ``CV_16SC3`` or 16-bit signed 3-channel array, and so on.
1686
1687
1688 Mat::depth
1689 ----------
1690 Returns the depth of a matrix element.
1691
1692 .. ocv:function:: int Mat::depth() const
1693
1694 The method returns the identifier of the matrix element depth (the type of each individual channel). For example, for a 16-bit signed element array, the method returns ``CV_16S`` . A complete list of matrix types contains the following values:
1695
1696 * ``CV_8U``     - 8-bit unsigned integers ( ``0..255``     )
1697
1698 * ``CV_8S``     - 8-bit signed integers ( ``-128..127``     )
1699
1700 * ``CV_16U``     - 16-bit unsigned integers ( ``0..65535``     )
1701
1702 * ``CV_16S``     - 16-bit signed integers ( ``-32768..32767``     )
1703
1704 * ``CV_32S``     - 32-bit signed integers ( ``-2147483648..2147483647``     )
1705
1706 * ``CV_32F``     - 32-bit floating-point numbers ( ``-FLT_MAX..FLT_MAX, INF, NAN``     )
1707
1708 * ``CV_64F``     - 64-bit floating-point numbers ( ``-DBL_MAX..DBL_MAX, INF, NAN``     )
1709
1710
1711 Mat::channels
1712 -------------
1713 Returns the number of matrix channels.
1714
1715 .. ocv:function:: int Mat::channels() const
1716
1717 The method returns the number of matrix channels.
1718
1719
1720 Mat::step1
1721 ----------
1722 Returns a normalized step.
1723
1724 .. ocv:function:: size_t Mat::step1( int i=0 ) const
1725
1726 The method returns a matrix step divided by
1727 :ocv:func:`Mat::elemSize1()` . It can be useful to quickly access an arbitrary matrix element.
1728
1729
1730 Mat::size
1731 ---------
1732 Returns a matrix size.
1733
1734 .. ocv:function:: Size Mat::size() const
1735
1736 The method returns a matrix size: ``Size(cols, rows)`` . When the matrix is more than 2-dimensional, the returned size is (-1, -1).
1737
1738
1739 Mat::empty
1740 ----------
1741 Returns ``true`` if the array has no elements.
1742
1743 .. ocv:function:: bool Mat::empty() const
1744
1745 The method returns ``true`` if ``Mat::total()`` is 0 or if ``Mat::data`` is NULL. Because of ``pop_back()`` and ``resize()`` methods ``M.total() == 0`` does not imply that ``M.data == NULL`` .
1746
1747
1748 Mat::ptr
1749 --------
1750 Returns a pointer to the specified matrix row.
1751
1752 .. ocv:function:: uchar* Mat::ptr(int i0=0)
1753
1754 .. ocv:function:: const uchar* Mat::ptr(int i0=0) const
1755
1756 .. ocv:function:: template<typename _Tp> _Tp* Mat::ptr(int i0=0)
1757
1758 .. ocv:function:: template<typename _Tp> const _Tp* Mat::ptr(int i0=0) const
1759
1760     :param i0: A 0-based row index.
1761
1762 The methods return ``uchar*`` or typed pointer to the specified matrix row. See the sample in
1763 :ocv:func:`Mat::isContinuous` to know how to use these methods.
1764
1765
1766 Mat::at
1767 -------
1768 Returns a reference to the specified array element.
1769
1770 .. ocv:function:: template<typename T> T& Mat::at(int i) const
1771
1772 .. ocv:function:: template<typename T> const T& Mat::at(int i) const
1773
1774 .. ocv:function:: template<typename T> T& Mat::at(int i, int j)
1775
1776 .. ocv:function:: template<typename T> const T& Mat::at(int i, int j) const
1777
1778 .. ocv:function:: template<typename T> T& Mat::at(Point pt)
1779
1780 .. ocv:function:: template<typename T> const T& Mat::at(Point pt) const
1781
1782 .. ocv:function:: template<typename T> T& Mat::at(int i, int j, int k)
1783
1784 .. ocv:function:: template<typename T> const T& Mat::at(int i, int j, int k) const
1785
1786 .. ocv:function:: template<typename T> T& Mat::at(const int* idx)
1787
1788 .. ocv:function:: template<typename T> const T& Mat::at(const int* idx) const
1789
1790     :param i: Index along the dimension 0
1791     :param j: Index along the dimension 1
1792     :param k: Index along the dimension 2
1793
1794     :param pt: Element position specified as  ``Point(j,i)`` .
1795
1796     :param idx: Array of  ``Mat::dims``  indices.
1797
1798 The template methods return a reference to the specified array element. For the sake of higher performance, the index range checks are only performed in the Debug configuration.
1799
1800 Note that the variants with a single index (i) can be used to access elements of single-row or single-column 2-dimensional arrays. That is, if, for example, ``A`` is a ``1 x N`` floating-point matrix and ``B`` is an ``M x 1`` integer matrix, you can simply write ``A.at<float>(k+4)`` and ``B.at<int>(2*i+1)`` instead of ``A.at<float>(0,k+4)`` and ``B.at<int>(2*i+1,0)`` , respectively.
1801
1802 The example below initializes a Hilbert matrix: ::
1803
1804     Mat H(100, 100, CV_64F);
1805     for(int i = 0; i < H.rows; i++)
1806         for(int j = 0; j < H.cols; j++)
1807             H.at<double>(i,j)=1./(i+j+1);
1808
1809
1810
1811 Mat::begin
1812 --------------
1813 Returns the matrix iterator and sets it to the first matrix element.
1814
1815 .. ocv:function:: template<typename _Tp> MatIterator_<_Tp> Mat::begin()
1816
1817 .. ocv:function:: template<typename _Tp> MatConstIterator_<_Tp> Mat::begin() const
1818
1819 The methods return the matrix read-only or read-write iterators. The use of matrix iterators is very similar to the use of bi-directional STL iterators. In the example below, the alpha blending function is rewritten using the matrix iterators: ::
1820
1821     template<typename T>
1822     void alphaBlendRGBA(const Mat& src1, const Mat& src2, Mat& dst)
1823     {
1824         typedef Vec<T, 4> VT;
1825
1826         const float alpha_scale = (float)std::numeric_limits<T>::max(),
1827                     inv_scale = 1.f/alpha_scale;
1828
1829         CV_Assert( src1.type() == src2.type() &&
1830                    src1.type() == DataType<VT>::type &&
1831                    src1.size() == src2.size());
1832         Size size = src1.size();
1833         dst.create(size, src1.type());
1834
1835         MatConstIterator_<VT> it1 = src1.begin<VT>(), it1_end = src1.end<VT>();
1836         MatConstIterator_<VT> it2 = src2.begin<VT>();
1837         MatIterator_<VT> dst_it = dst.begin<VT>();
1838
1839         for( ; it1 != it1_end; ++it1, ++it2, ++dst_it )
1840         {
1841             VT pix1 = *it1, pix2 = *it2;
1842             float alpha = pix1[3]*inv_scale, beta = pix2[3]*inv_scale;
1843             *dst_it = VT(saturate_cast<T>(pix1[0]*alpha + pix2[0]*beta),
1844                          saturate_cast<T>(pix1[1]*alpha + pix2[1]*beta),
1845                          saturate_cast<T>(pix1[2]*alpha + pix2[2]*beta),
1846                          saturate_cast<T>((1 - (1-alpha)*(1-beta))*alpha_scale));
1847         }
1848     }
1849
1850
1851
1852 Mat::end
1853 ------------
1854 Returns the matrix iterator and sets it to the after-last matrix element.
1855
1856 .. ocv:function:: template<typename _Tp> MatIterator_<_Tp> Mat::end()
1857
1858 .. ocv:function:: template<typename _Tp> MatConstIterator_<_Tp> Mat::end() const
1859
1860 The methods return the matrix read-only or read-write iterators, set to the point following the last matrix element.
1861
1862 Mat\_
1863 -----
1864 .. ocv:class:: Mat_
1865
1866 Template matrix class derived from
1867 :ocv:class:`Mat` . ::
1868
1869     template<typename _Tp> class Mat_ : public Mat
1870     {
1871     public:
1872         // ... some specific methods
1873         //         and
1874         // no new extra fields
1875     };
1876
1877
1878 The class ``Mat_<_Tp>`` is a "thin" template wrapper on top of the ``Mat`` class. It does not have any extra data fields. Nor this class nor ``Mat`` has any virtual methods. Thus, references or pointers to these two classes can be freely but carefully converted one to another. For example: ::
1879
1880     // create a 100x100 8-bit matrix
1881     Mat M(100,100,CV_8U);
1882     // this will be compiled fine. no any data conversion will be done.
1883     Mat_<float>& M1 = (Mat_<float>&)M;
1884     // the program is likely to crash at the statement below
1885     M1(99,99) = 1.f;
1886
1887
1888 While ``Mat`` is sufficient in most cases, ``Mat_`` can be more convenient if you use a lot of element access operations and if you know matrix type at the compilation time. Note that ``Mat::at<_Tp>(int y, int x)`` and ``Mat_<_Tp>::operator ()(int y, int x)`` do absolutely the same and run at the same speed, but the latter is certainly shorter: ::
1889
1890     Mat_<double> M(20,20);
1891     for(int i = 0; i < M.rows; i++)
1892         for(int j = 0; j < M.cols; j++)
1893             M(i,j) = 1./(i+j+1);
1894     Mat E, V;
1895     eigen(M,E,V);
1896     cout << E.at<double>(0,0)/E.at<double>(M.rows-1,0);
1897
1898
1899 To use ``Mat_`` for multi-channel images/matrices, pass ``Vec`` as a ``Mat_`` parameter: ::
1900
1901     // allocate a 320x240 color image and fill it with green (in RGB space)
1902     Mat_<Vec3b> img(240, 320, Vec3b(0,255,0));
1903     // now draw a diagonal white line
1904     for(int i = 0; i < 100; i++)
1905         img(i,i)=Vec3b(255,255,255);
1906     // and now scramble the 2nd (red) channel of each pixel
1907     for(int i = 0; i < img.rows; i++)
1908         for(int j = 0; j < img.cols; j++)
1909             img(i,j)[2] ^= (uchar)(i ^ j);
1910
1911
1912 InputArray
1913 ----------
1914 .. ocv:class:: InputArray
1915
1916 This is the proxy class for passing read-only input arrays into OpenCV functions. It is defined as ::
1917
1918     typedef const _InputArray& InputArray;
1919
1920 where ``_InputArray`` is a class that can be constructed from ``Mat``, ``Mat_<T>``, ``Matx<T, m, n>``, ``std::vector<T>``, ``std::vector<std::vector<T> >`` or ``std::vector<Mat>``. It can also be constructed from a matrix expression.
1921
1922 Since this is mostly implementation-level class, and its interface may change in future versions, we do not describe it in details. There are a few key things, though, that should be kept in mind:
1923
1924   * When you see in the reference manual or in OpenCV source code a function that takes ``InputArray``, it means that you can actually pass ``Mat``, ``Matx``, ``vector<T>`` etc. (see above the complete list).
1925
1926   * Optional input arguments: If some of the input arrays may be empty, pass ``cv::noArray()`` (or simply ``cv::Mat()`` as you probably did before).
1927
1928   * The class is designed solely for passing parameters. That is, normally you *should not* declare class members, local and global variables of this type.
1929
1930   * If you want to design your own function or a class method that can operate of arrays of multiple types, you can use ``InputArray`` (or ``OutputArray``) for the respective parameters. Inside a function you should use ``_InputArray::getMat()`` method to construct a matrix header for the array (without copying data). ``_InputArray::kind()`` can be used to distinguish ``Mat`` from ``vector<>`` etc., but normally it is not needed.
1931
1932 Here is how you can use a function that takes ``InputArray`` ::
1933
1934     std::vector<Point2f> vec;
1935     // points or a circle
1936     for( int i = 0; i < 30; i++ )
1937         vec.push_back(Point2f((float)(100 + 30*cos(i*CV_PI*2/5)),
1938                               (float)(100 - 30*sin(i*CV_PI*2/5))));
1939     cv::transform(vec, vec, cv::Matx23f(0.707, -0.707, 10, 0.707, 0.707, 20));
1940
1941 That is, we form an STL vector containing points, and apply in-place affine transformation to the vector using the 2x3 matrix created inline as ``Matx<float, 2, 3>`` instance.
1942
1943 Here is how such a function can be implemented (for simplicity, we implement a very specific case of it, according to the assertion statement inside) ::
1944
1945     void myAffineTransform(InputArray _src, OutputArray _dst, InputArray _m)
1946     {
1947         // get Mat headers for input arrays. This is O(1) operation,
1948         // unless _src and/or _m are matrix expressions.
1949         Mat src = _src.getMat(), m = _m.getMat();
1950         CV_Assert( src.type() == CV_32FC2 && m.type() == CV_32F && m.size() == Size(3, 2) );
1951
1952         // [re]create the output array so that it has the proper size and type.
1953         // In case of Mat it calls Mat::create, in case of STL vector it calls vector::resize.
1954         _dst.create(src.size(), src.type());
1955         Mat dst = _dst.getMat();
1956
1957         for( int i = 0; i < src.rows; i++ )
1958             for( int j = 0; j < src.cols; j++ )
1959             {
1960                 Point2f pt = src.at<Point2f>(i, j);
1961                 dst.at<Point2f>(i, j) = Point2f(m.at<float>(0, 0)*pt.x +
1962                                                 m.at<float>(0, 1)*pt.y +
1963                                                 m.at<float>(0, 2),
1964                                                 m.at<float>(1, 0)*pt.x +
1965                                                 m.at<float>(1, 1)*pt.y +
1966                                                 m.at<float>(1, 2));
1967             }
1968     }
1969
1970 There is another related type, ``InputArrayOfArrays``, which is currently defined as a synonym for ``InputArray``: ::
1971
1972     typedef InputArray InputArrayOfArrays;
1973
1974 It denotes function arguments that are either vectors of vectors or vectors of matrices. A separate synonym is needed to generate Python/Java etc. wrappers properly. At the function implementation level their use is similar, but ``_InputArray::getMat(idx)`` should be used to get header for the idx-th component of the outer vector and ``_InputArray::size().area()`` should be used to find the number of components (vectors/matrices) of the outer vector.
1975
1976
1977 OutputArray
1978 -----------
1979 .. ocv:class:: OutputArray : public InputArray
1980
1981 This type is very similar to ``InputArray`` except that it is used for input/output and output function parameters. Just like with ``InputArray``, OpenCV users should not care about ``OutputArray``, they just pass ``Mat``, ``vector<T>`` etc. to the functions. The same limitation as for ``InputArray``: **Do not explicitly create OutputArray instances** applies here too.
1982
1983 If you want to make your function polymorphic (i.e. accept different arrays as output parameters), it is also not very difficult. Take the sample above as the reference. Note that ``_OutputArray::create()`` needs to be called before ``_OutputArray::getMat()``. This way you guarantee that the output array is properly allocated.
1984
1985 Optional output parameters. If you do not need certain output array to be computed and returned to you, pass ``cv::noArray()``, just like you would in the case of optional input array. At the implementation level, use ``_OutputArray::needed()`` to check if certain output array needs to be computed or not.
1986
1987 There are several synonyms for ``OutputArray`` that are used to assist automatic Python/Java/... wrapper generators: ::
1988
1989     typedef OutputArray OutputArrayOfArrays;
1990     typedef OutputArray InputOutputArray;
1991     typedef OutputArray InputOutputArrayOfArrays;
1992
1993 NAryMatIterator
1994 ---------------
1995 .. ocv:class:: NAryMatIterator
1996
1997 n-ary multi-dimensional array iterator. ::
1998
1999     class CV_EXPORTS NAryMatIterator
2000     {
2001     public:
2002         //! the default constructor
2003         NAryMatIterator();
2004         //! the full constructor taking arbitrary number of n-dim matrices
2005         NAryMatIterator(const Mat** arrays, Mat* planes, int narrays=-1);
2006         //! the separate iterator initialization method
2007         void init(const Mat** arrays, Mat* planes, int narrays=-1);
2008
2009         //! proceeds to the next plane of every iterated matrix
2010         NAryMatIterator& operator ++();
2011         //! proceeds to the next plane of every iterated matrix (postfix increment operator)
2012         NAryMatIterator operator ++(int);
2013
2014         ...
2015         int nplanes; // the total number of planes
2016     };
2017
2018
2019 Use the class to implement unary, binary, and, generally, n-ary element-wise operations on multi-dimensional arrays. Some of the arguments of an n-ary function may be continuous arrays, some may be not. It is possible to use conventional
2020 ``MatIterator`` 's for each array but incrementing all of the iterators after each small operations may be a big overhead. In this case consider using ``NAryMatIterator`` to iterate through several matrices simultaneously as long as they have the same geometry (dimensionality and all the dimension sizes are the same). On each iteration ``it.planes[0]``, ``it.planes[1]`` , ... will be the slices of the corresponding matrices.
2021
2022 The example below illustrates how you can compute a normalized and threshold 3D color histogram: ::
2023
2024     void computeNormalizedColorHist(const Mat& image, Mat& hist, int N, double minProb)
2025     {
2026         const int histSize[] = {N, N, N};
2027
2028         // make sure that the histogram has a proper size and type
2029         hist.create(3, histSize, CV_32F);
2030
2031         // and clear it
2032         hist = Scalar(0);
2033
2034         // the loop below assumes that the image
2035         // is a 8-bit 3-channel. check it.
2036         CV_Assert(image.type() == CV_8UC3);
2037         MatConstIterator_<Vec3b> it = image.begin<Vec3b>(),
2038                                  it_end = image.end<Vec3b>();
2039         for( ; it != it_end; ++it )
2040         {
2041             const Vec3b& pix = *it;
2042             hist.at<float>(pix[0]*N/256, pix[1]*N/256, pix[2]*N/256) += 1.f;
2043         }
2044
2045         minProb *= image.rows*image.cols;
2046         Mat plane;
2047         NAryMatIterator it(&hist, &plane, 1);
2048         double s = 0;
2049         // iterate through the matrix. on each iteration
2050         // it.planes[*] (of type Mat) will be set to the current plane.
2051         for(int p = 0; p < it.nplanes; p++, ++it)
2052         {
2053             threshold(it.planes[0], it.planes[0], minProb, 0, THRESH_TOZERO);
2054             s += sum(it.planes[0])[0];
2055         }
2056
2057         s = 1./s;
2058         it = NAryMatIterator(&hist, &plane, 1);
2059         for(int p = 0; p < it.nplanes; p++, ++it)
2060             it.planes[0] *= s;
2061     }
2062
2063
2064 SparseMat
2065 ---------
2066 .. ocv:class:: SparseMat
2067
2068 The class ``SparseMat`` represents multi-dimensional sparse numerical arrays. Such a sparse array can store elements of any type that
2069 :ocv:class:`Mat` can store. *Sparse* means that only non-zero elements are stored (though, as a result of operations on a sparse matrix, some of its stored elements can actually become 0. It is up to you to detect such elements and delete them using ``SparseMat::erase`` ). The non-zero elements are stored in a hash table that grows when it is filled 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:
2070
2071 *
2072     Query operations (``SparseMat::ptr`` and the higher-level ``SparseMat::ref``, ``SparseMat::value`` and ``SparseMat::find``), for example:
2073
2074     ::
2075
2076             const int dims = 5;
2077             int size[] = {10, 10, 10, 10, 10};
2078             SparseMat sparse_mat(dims, size, CV_32F);
2079             for(int i = 0; i < 1000; i++)
2080             {
2081                 int idx[dims];
2082                 for(int k = 0; k < dims; k++)
2083                     idx[k] = rand()
2084                 sparse_mat.ref<float>(idx) += 1.f;
2085             }
2086
2087     ..
2088
2089 *
2090     Sparse matrix iterators. They are similar to ``MatIterator`` but different from :ocv:class:`NAryMatIterator`. That is, the iteration loop is familiar to STL users:
2091
2092     ::
2093
2094             // prints elements of a sparse floating-point matrix
2095             // and the sum of elements.
2096             SparseMatConstIterator_<float>
2097                 it = sparse_mat.begin<float>(),
2098                 it_end = sparse_mat.end<float>();
2099             double s = 0;
2100             int dims = sparse_mat.dims();
2101             for(; it != it_end; ++it)
2102             {
2103                 // print element indices and the element value
2104                 const SparseMat::Node* n = it.node();
2105                 printf("(");
2106                 for(int i = 0; i < dims; i++)
2107                     printf("%d%s", n->idx[i], i < dims-1 ? ", " : ")");
2108                 printf(": %g\n", it.value<float>());
2109                 s += *it;
2110             }
2111             printf("Element sum is %g\n", s);
2112
2113     ..
2114
2115     If you run this loop, you will notice that elements are not enumerated in a logical order (lexicographical, and so on). They come in the same order as they are stored in the hash table (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 may happen due to possible buffer reallocation.
2116
2117 *
2118     Combination of the above 2 methods when you need to process 2 or more sparse matrices simultaneously. For example, this is how you can compute unnormalized cross-correlation of the 2 floating-point sparse matrices:
2119
2120     ::
2121
2122             double cross_corr(const SparseMat& a, const SparseMat& b)
2123             {
2124                 const SparseMat *_a = &a, *_b = &b;
2125                 // if b contains less elements than a,
2126                 // it is faster to iterate through b
2127                 if(_a->nzcount() > _b->nzcount())
2128                     std::swap(_a, _b);
2129                 SparseMatConstIterator_<float> it = _a->begin<float>(),
2130                                                it_end = _a->end<float>();
2131                 double ccorr = 0;
2132                 for(; it != it_end; ++it)
2133                 {
2134                     // take the next element from the first matrix
2135                     float avalue = *it;
2136                     const Node* anode = it.node();
2137                     // and try to find an element with the same index in the second matrix.
2138                     // since the hash value depends only on the element index,
2139                     // reuse the hash value stored in the node
2140                     float bvalue = _b->value<float>(anode->idx,&anode->hashval);
2141                     ccorr += avalue*bvalue;
2142                 }
2143                 return ccorr;
2144             }
2145
2146     ..
2147
2148 SparseMat::SparseMat
2149 --------------------
2150 Various SparseMat constructors.
2151
2152 .. ocv:function:: SparseMat::SparseMat()
2153 .. ocv:function:: SparseMat::SparseMat( int dims, const int* _sizes, int _type )
2154 .. ocv:function:: SparseMat::SparseMat( const SparseMat& m )
2155 .. ocv:function:: SparseMat::SparseMat( const Mat& m )
2156 .. ocv:function:: SparseMat::SparseMat( const CvSparseMat* m )
2157
2158
2159     :param m: Source matrix for copy constructor. If m is dense matrix (ocv:class:`Mat`) then it will be converted to sparse representation.
2160     :param dims: Array dimensionality.
2161     :param _sizes: Sparce matrix size on all dementions.
2162     :param _type: Sparse matrix data type.
2163     :param try1d: if try1d is true and matrix is a single-column matrix (Nx1), then the sparse matrix will be 1-dimensional.
2164
2165 SparseMat::~SparseMat
2166 ---------------------
2167 SparseMat object destructor.
2168
2169 .. ocv:function:: SparseMat::~SparseMat()
2170
2171 SparseMat::operator=
2172 --------------------
2173 Provides sparse matrix assignment operators.
2174
2175 .. ocv:function:: SparseMat& SparseMat::operator = (const SparseMat& m)
2176 .. ocv:function:: SparseMat& SparseMat::operator = (const Mat& m)
2177
2178 The last variant is equivalent to the corresponding constructor with try1d=false.
2179
2180
2181 SparseMat::clone
2182 ----------------
2183 Creates a full copy of the matrix.
2184
2185 .. ocv:function:: SparseMat SparseMat::clone() const
2186
2187 SparseMat::copyTo
2188 -----------------
2189 Copy all the data to the destination matrix.The destination will be reallocated if needed.
2190
2191 .. ocv:function:: void SparseMat::copyTo( SparseMat& m ) const
2192 .. ocv:function:: void SparseMat::copyTo( Mat& m ) const
2193
2194     :param m: Target for copiing.
2195
2196 The last variant converts 1D or 2D sparse matrix to dense 2D matrix. If the sparse matrix is 1D, the result will be a single-column matrix.
2197
2198 SparceMat::convertTo
2199 --------------------
2200 Convert sparse matrix with possible type change and scaling.
2201
2202 .. ocv:function:: void SparseMat::convertTo( SparseMat& m, int rtype, double alpha=1 ) const
2203 .. ocv:function:: void SparseMat::convertTo( Mat& m, int rtype, double alpha=1, double beta=0 ) const
2204
2205 The first version converts arbitrary sparse matrix to dense matrix and multiplies all the matrix elements by the specified scalar.
2206 The second versiob converts sparse matrix to dense matrix with optional type conversion and scaling.
2207 When rtype=-1, the destination element type will be the same as the sparse matrix element type.
2208 Otherwise, rtype will specify the depth and the number of channels will remain the same as in the sparse matrix.
2209
2210 SparseMat:create
2211 ----------------
2212 Reallocates sparse matrix. If it was already of the proper size and type, it is simply cleared with clear(), otherwise,
2213 the old matrix is released (using release()) and the new one is allocated.
2214
2215 .. ocv:function:: void SparseMat::create(int dims, const int* _sizes, int _type)
2216
2217     :param dims: Array dimensionality.
2218     :param _sizes: Sparce matrix size on all dementions.
2219     :param _type: Sparse matrix data type.
2220
2221 SparseMat::clear
2222 ----------------
2223 Sets all the matrix elements to 0, which means clearing the hash table.
2224
2225 .. ocv:function:: void SparseMat::clear()
2226
2227 SparseMat::addref
2228 -----------------
2229 Manually increases reference counter to the header.
2230
2231 .. ocv:function:: void SparseMat::addref()
2232
2233 SparseMat::release
2234 ------------------
2235 Decreses the header reference counter when it reaches 0. The header and all the underlying data are deallocated.
2236
2237 .. ocv:function:: void SparseMat::release()
2238
2239 SparseMat::CvSparseMat *
2240 ------------------------
2241 Converts sparse matrix to the old-style representation. All the elements are copied.
2242
2243 .. ocv:function:: SparseMat::operator CvSparseMat*() const
2244
2245 SparseMat::elemSize
2246 -------------------
2247 Size of each element in bytes (the matrix nodes will be bigger because of element indices and other SparseMat::Node elements).
2248
2249 .. ocv:function:: size_t SparseMat::elemSize() const
2250
2251 SparseMat::elemSize1
2252 --------------------
2253 elemSize()/channels().
2254
2255 .. ocv:function::  size_t SparseMat::elemSize() const
2256
2257 SparseMat::type
2258 ---------------
2259 Returns the type of a matrix element.
2260
2261 .. ocv:function:: int SparseMat::type() const
2262
2263 The method returns a sparse matrix element type. This is an identifier compatible with the ``CvMat`` type system, like ``CV_16SC3`` or 16-bit signed 3-channel array, and so on.
2264
2265 SparseMat::depth
2266 ----------------
2267 Returns the depth of a sparse matrix element.
2268
2269 .. ocv:function:: int SparseMat::depth() const
2270
2271 The method returns the identifier of the matrix element depth (the type of each individual channel). For example, for a 16-bit signed 3-channel array, the method returns ``CV_16S``
2272
2273 * ``CV_8U``     - 8-bit unsigned integers ( ``0..255``     )
2274
2275 * ``CV_8S``     - 8-bit signed integers ( ``-128..127``     )
2276
2277 * ``CV_16U``     - 16-bit unsigned integers ( ``0..65535``     )
2278
2279 * ``CV_16S``     - 16-bit signed integers ( ``-32768..32767``     )
2280
2281 * ``CV_32S``     - 32-bit signed integers ( ``-2147483648..2147483647``     )
2282
2283 * ``CV_32F``     - 32-bit floating-point numbers ( ``-FLT_MAX..FLT_MAX, INF, NAN``     )
2284
2285 * ``CV_64F``     - 64-bit floating-point numbers ( ``-DBL_MAX..DBL_MAX, INF, NAN``     )
2286
2287 SparseMat::channels
2288 -------------------
2289 Returns the number of matrix channels.
2290
2291 .. ocv:function:: int SparseMat::channels() const
2292
2293 The method returns the number of matrix channels.
2294
2295 SparseMat::size
2296 ---------------
2297 Returns the array of sizes or matrix size by i dimention and 0 if the matrix is not allocated.
2298
2299 .. ocv:function:: const int* SparseMat::size() const
2300 .. ocv:function:: int SparseMat::size(int i) const
2301
2302     :param i: Dimention index.
2303
2304 SparseMat::dims
2305 ---------------
2306 Returns the matrix dimensionality.
2307
2308 .. ocv:function:: int SparseMat::dims() const
2309
2310 SparseMat::nzcount
2311 ------------------
2312 Returns the number of non-zero elements.
2313
2314 .. ocv:function:: size_t SparseMat::nzcount() const
2315
2316 SparseMat::hash
2317 ---------------
2318 Compute element hash value from the element indices.
2319
2320 .. ocv:function:: size_t SparseMat::hash(int i0) const
2321 .. ocv:function:: size_t SparseMat::hash(int i0, int i1) const
2322 .. ocv:function:: size_t SparseMat::hash(int i0, int i1, int i2) const
2323 .. ocv:function:: size_t SparseMat::hash(const int* idx) const
2324
2325 SparseMat::ptr
2326 --------------
2327 Low-level element-access functions, special variants for 1D, 2D, 3D cases, and the generic one for n-D case.
2328
2329 .. ocv:function:: uchar* SparseMat::ptr(int i0, bool createMissing, size_t* hashval=0)
2330 .. ocv:function:: uchar* SparseMat::ptr(int i0, int i1, bool createMissing, size_t* hashval=0)
2331 .. ocv:function:: uchar* SparseMat::ptr(int i0, int i1, int i2, bool createMissing, size_t* hashval=0)
2332 .. ocv:function:: uchar* SparseMat::ptr(const int* idx, bool createMissing, size_t* hashval=0)
2333
2334 Return pointer to the matrix element. If the element is there (it is non-zero), the pointer to it is returned.
2335 If it is not there and ``createMissing=false``, NULL pointer is returned. If it is not there and ``createMissing=true``,
2336 the new elementis created and initialized with 0. Pointer to it is returned. If the optional hashval pointer is not ``NULL``,
2337 the element hash value is not computed but ``hashval`` is taken instead.
2338
2339 SparseMat::erase
2340 ----------------
2341 Erase the specified matrix element. When there is no such an element, the methods do nothing.
2342
2343 .. ocv:function:: void SparseMat::erase(int i0, int i1, size_t* hashval=0)
2344 .. ocv:function:: void SparseMat::erase(int i0, int i1, int i2, size_t* hashval=0)
2345 .. ocv:function:: void SparseMat::erase(const int* idx, size_t* hashval=0)
2346
2347 SparseMat\_
2348 -----------
2349 .. ocv:class:: SparseMat_
2350
2351 Template sparse n-dimensional array class derived from
2352 :ocv:class:`SparseMat` ::
2353
2354     template<typename _Tp> class SparseMat_ : public SparseMat
2355     {
2356     public:
2357         typedef SparseMatIterator_<_Tp> iterator;
2358         typedef SparseMatConstIterator_<_Tp> const_iterator;
2359
2360         // constructors;
2361         // the created matrix will have data type = DataType<_Tp>::type
2362         SparseMat_();
2363         SparseMat_(int dims, const int* _sizes);
2364         SparseMat_(const SparseMat& m);
2365         SparseMat_(const SparseMat_& m);
2366         SparseMat_(const Mat& m);
2367         SparseMat_(const CvSparseMat* m);
2368         // assignment operators; data type conversion is done when necessary
2369         SparseMat_& operator = (const SparseMat& m);
2370         SparseMat_& operator = (const SparseMat_& m);
2371         SparseMat_& operator = (const Mat& m);
2372
2373         // equivalent to the correspoding parent class methods
2374         SparseMat_ clone() const;
2375         void create(int dims, const int* _sizes);
2376         operator CvSparseMat*() const;
2377
2378         // overriden methods that do extra checks for the data type
2379         int type() const;
2380         int depth() const;
2381         int channels() const;
2382
2383         // more convenient element access operations.
2384         // ref() is retained (but <_Tp> specification is not needed anymore);
2385         // operator () is equivalent to SparseMat::value<_Tp>
2386         _Tp& ref(int i0, size_t* hashval=0);
2387         _Tp operator()(int i0, size_t* hashval=0) const;
2388         _Tp& ref(int i0, int i1, size_t* hashval=0);
2389         _Tp operator()(int i0, int i1, size_t* hashval=0) const;
2390         _Tp& ref(int i0, int i1, int i2, size_t* hashval=0);
2391         _Tp operator()(int i0, int i1, int i2, size_t* hashval=0) const;
2392         _Tp& ref(const int* idx, size_t* hashval=0);
2393         _Tp operator()(const int* idx, size_t* hashval=0) const;
2394
2395         // iterators
2396         SparseMatIterator_<_Tp> begin();
2397         SparseMatConstIterator_<_Tp> begin() const;
2398         SparseMatIterator_<_Tp> end();
2399         SparseMatConstIterator_<_Tp> end() const;
2400     };
2401
2402 ``SparseMat_`` is a thin wrapper on top of :ocv:class:`SparseMat` created in the same way as ``Mat_`` .
2403 It simplifies notation of some operations. ::
2404
2405     int sz[] = {10, 20, 30};
2406     SparseMat_<double> M(3, sz);
2407     ...
2408     M.ref(1, 2, 3) = M(4, 5, 6) + M(7, 8, 9);
2409
2410
2411 Algorithm
2412 ---------
2413 .. ocv:class:: Algorithm
2414
2415 This is a base class for all more or less complex algorithms in OpenCV, especially for classes of algorithms, for which there can be multiple implementations. The examples are stereo correspondence (for which there are algorithms like block matching, semi-global block matching, graph-cut etc.), background subtraction (which can be done using mixture-of-gaussians models, codebook-based algorithm etc.), optical flow (block matching, Lucas-Kanade, Horn-Schunck etc.).
2416
2417 The class provides the following features for all derived classes:
2418
2419     * so called "virtual constructor". That is, each Algorithm derivative is registered at program start and you can get the list of registered algorithms and create instance of a particular algorithm by its name (see ``Algorithm::create``). If you plan to add your own algorithms, it is good practice to add a unique prefix to your algorithms to distinguish them from other algorithms.
2420
2421     * setting/retrieving algorithm parameters by name. If you used video capturing functionality from OpenCV highgui module, you are probably familar with ``cvSetCaptureProperty()``, ``cvGetCaptureProperty()``, ``VideoCapture::set()`` and ``VideoCapture::get()``. ``Algorithm`` provides similar method where instead of integer id's you specify the parameter names as text strings. See ``Algorithm::set`` and ``Algorithm::get`` for details.
2422
2423     * reading and writing parameters from/to XML or YAML files. Every Algorithm derivative can store all its parameters and then read them back. There is no need to re-implement it each time.
2424
2425 Here is example of SIFT use in your application via Algorithm interface: ::
2426
2427     #include "opencv2/opencv.hpp"
2428     #include "opencv2/nonfree/nonfree.hpp"
2429
2430     ...
2431
2432     initModule_nonfree(); // to load SURF/SIFT etc.
2433
2434     Ptr<Feature2D> sift = Algorithm::create<Feature2D>("Feature2D.SIFT");
2435
2436     FileStorage fs("sift_params.xml", FileStorage::READ);
2437     if( fs.isOpened() ) // if we have file with parameters, read them
2438     {
2439         sift->read(fs["sift_params"]);
2440         fs.release();
2441     }
2442     else // else modify the parameters and store them; user can later edit the file to use different parameters
2443     {
2444         sift->set("contrastThreshold", 0.01f); // lower the contrast threshold, compared to the default value
2445
2446         {
2447         WriteStructContext ws(fs, "sift_params", CV_NODE_MAP);
2448         sift->write(fs);
2449         }
2450     }
2451
2452     Mat image = imread("myimage.png", 0), descriptors;
2453     vector<KeyPoint> keypoints;
2454     (*sift)(image, noArray(), keypoints, descriptors);
2455
2456 Algorithm::name
2457 ---------------
2458 Returns the algorithm name
2459
2460 .. ocv:function:: string Algorithm::name() const
2461
2462 Algorithm::get
2463 --------------
2464 Returns the algorithm parameter
2465
2466 .. ocv:function:: template<typename _Tp> typename ParamType<_Tp>::member_type Algorithm::get(const string& name) const
2467
2468     :param name: The parameter name.
2469
2470 The method returns value of the particular parameter. Since the compiler can not deduce the type of the returned parameter, you should specify it explicitly in angle brackets. Here are the allowed forms of get:
2471
2472     * myalgo.get<int>("param_name")
2473     * myalgo.get<double>("param_name")
2474     * myalgo.get<bool>("param_name")
2475     * myalgo.get<string>("param_name")
2476     * myalgo.get<Mat>("param_name")
2477     * myalgo.get<vector<Mat> >("param_name")
2478     * myalgo.get<Algorithm>("param_name") (it returns Ptr<Algorithm>).
2479
2480 In some cases the actual type of the parameter can be cast to the specified type, e.g. integer parameter can be cast to double, ``bool`` can be cast to ``int``. But "dangerous" transformations (string<->number, double->int, 1x1 Mat<->number, ...) are not performed and the method will throw an exception. In the case of ``Mat`` or ``vector<Mat>`` parameters the method does not clone the matrix data, so do not modify the matrices. Use ``Algorithm::set`` instead - slower, but more safe.
2481
2482
2483 Algorithm::set
2484 --------------
2485 Sets the algorithm parameter
2486
2487 .. ocv:function:: void Algorithm::set(const string& name, int value)
2488 .. ocv:function:: void Algorithm::set(const string& name, double value)
2489 .. ocv:function:: void Algorithm::set(const string& name, bool value)
2490 .. ocv:function:: void Algorithm::set(const string& name, const string& value)
2491 .. ocv:function:: void Algorithm::set(const string& name, const Mat& value)
2492 .. ocv:function:: void Algorithm::set(const string& name, const vector<Mat>& value)
2493 .. ocv:function:: void Algorithm::set(const string& name, const Ptr<Algorithm>& value)
2494
2495     :param name: The parameter name.
2496     :param value: The parameter value.
2497
2498 The method sets value of the particular parameter. Some of the algorithm parameters may be declared as read-only. If you try to set such a parameter, you will get exception with the corresponding error message.
2499
2500
2501 Algorithm::write
2502 ----------------
2503 Stores algorithm parameters in a file storage
2504
2505 .. ocv:function:: void Algorithm::write(FileStorage& fs) const
2506
2507     :param fs: File storage.
2508
2509 The method stores all the algorithm parameters (in alphabetic order) to the file storage. The method is virtual. If you define your own Algorithm derivative, your can override the method and store some extra information. However, it's rarely needed. Here are some examples:
2510
2511  * SIFT feature detector (from nonfree module). The class only stores algorithm parameters and no keypoints or their descriptors. Therefore, it's enough to store the algorithm parameters, which is what ``Algorithm::write()`` does. Therefore, there is no dedicated ``SIFT::write()``.
2512
2513  * Background subtractor (from video module). It has the algorithm parameters and also it has the current background model. However, the background model is not stored. First, it's rather big. Then, if you have stored the background model, it would likely become irrelevant on the next run (because of shifted camera, changed background, different lighting etc.). Therefore, ``BackgroundSubtractorMOG`` and ``BackgroundSubtractorMOG2`` also rely on the standard ``Algorithm::write()`` to store just the algorithm parameters.
2514
2515  * Expectation Maximization (from ml module). The algorithm finds mixture of gaussians that approximates user data best of all. In this case the model may be re-used on the next run to test new data against the trained statistical model. So EM needs to store the model. However, since the model is described by a few parameters that are available as read-only algorithm parameters (i.e. they are available via ``EM::get()``), EM also relies on ``Algorithm::write()`` to store both EM parameters and the model (represented by read-only algorithm parameters).
2516
2517
2518 Algorithm::read
2519 ---------------
2520 Reads algorithm parameters from a file storage
2521
2522 .. ocv:function:: void Algorithm::read(const FileNode& fn)
2523
2524     :param fn: File node of the file storage.
2525
2526 The method reads all the algorithm parameters from the specified node of a file storage. Similarly to ``Algorithm::write()``, if you implement an algorithm that needs to read some extra data and/or re-compute some internal data, you may override the method.
2527
2528 Algorithm::getList
2529 ------------------
2530 Returns the list of registered algorithms
2531
2532 .. ocv:function:: void Algorithm::getList(vector<string>& algorithms)
2533
2534     :param algorithms: The output vector of algorithm names.
2535
2536 This static method returns the list of registered algorithms in alphabetical order. Here is how to use it ::
2537
2538     vector<string> algorithms;
2539     Algorithm::getList(algorithms);
2540     cout << "Algorithms: " << algorithms.size() << endl;
2541     for (size_t i=0; i < algorithms.size(); i++)
2542         cout << algorithms[i] << endl;
2543
2544
2545 Algorithm::create
2546 -----------------
2547 Creates algorithm instance by name
2548
2549 .. ocv:function:: template<typename _Tp> Ptr<_Tp> Algorithm::create(const string& name)
2550
2551     :param name: The algorithm name, one of the names returned by ``Algorithm::getList()``.
2552
2553 This static method creates a new instance of the specified algorithm. If there is no such algorithm, the method will silently return null pointer (that can be checked by ``Ptr::empty()`` method). Also, you should specify the particular ``Algorithm`` subclass as ``_Tp`` (or simply ``Algorithm`` if you do not know it at that point). ::
2554
2555     Ptr<BackgroundSubtractor> bgfg = Algorithm::create<BackgroundSubtractor>("BackgroundSubtractor.MOG2");
2556
2557 .. note:: This is important note about seemingly mysterious behavior of ``Algorithm::create()`` when it returns NULL while it should not. The reason is simple - ``Algorithm::create()`` resides in OpenCV`s core module and the algorithms are implemented in other modules. If you create algorithms dynamically, C++ linker may decide to throw away the modules where the actual algorithms are implemented, since you do not call any functions from the modules. To avoid this problem, you need to call ``initModule_<modulename>();`` somewhere in the beginning of the program before ``Algorithm::create()``. For example, call ``initModule_nonfree()`` in order to use SURF/SIFT, call ``initModule_ml()`` to use expectation maximization etc.
2558
2559 Creating Own Algorithms
2560 -----------------------
2561
2562 The above methods are usually enough for users. If you want to make your own algorithm, derived from ``Algorithm``, you should basically follow a few conventions and add a little semi-standard piece of code to your class:
2563
2564  * Make a class and specify ``Algorithm`` as its base class.
2565  * The algorithm parameters should be the class members. See ``Algorithm::get()`` for the list of possible types of the parameters.
2566  * Add public virtual method ``AlgorithmInfo* info() const;`` to your class.
2567  * Add constructor function, ``AlgorithmInfo`` instance and implement the ``info()`` method. The simplest way is to take  http://code.opencv.org/projects/opencv/repository/revisions/master/entry/modules/ml/src/ml_init.cpp as the reference and modify it according to the list of your parameters.
2568  * Add some public function (e.g. ``initModule_<mymodule>()``) that calls info() of your algorithm and put it into the same source file as ``info()`` implementation. This is to force C++ linker to include this object file into the target application. See ``Algorithm::create()`` for details.
2569