1 /*M///////////////////////////////////////////////////////////////////////////////////////
2 //
3 //  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
4 //
5 //  By downloading, copying, installing or using the software you agree to this license.
6 //  If you do not agree to this license, do not download, install,
7 //  copy or use the software.
8 //
9 //
10 //                          License Agreement
11 //                For Open Source Computer Vision Library
12 //
13 // Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
14 // Copyright (C) 2009, Willow Garage Inc., all rights reserved.
15 // Copyright (C) 2013, OpenCV Foundation, all rights reserved.
16 // Third party copyrights are property of their respective owners.
17 //
18 // Redistribution and use in source and binary forms, with or without modification,
19 // are permitted provided that the following conditions are met:
20 //
21 //   * Redistribution's of source code must retain the above copyright notice,
22 //     this list of conditions and the following disclaimer.
23 //
24 //   * Redistribution's in binary form must reproduce the above copyright notice,
25 //     this list of conditions and the following disclaimer in the documentation
26 //     and/or other materials provided with the distribution.
27 //
28 //   * The name of the copyright holders may not be used to endorse or promote products
29 //     derived from this software without specific prior written permission.
30 //
31 // This software is provided by the copyright holders and contributors "as is" and
32 // any express or implied warranties, including, but not limited to, the implied
33 // warranties of merchantability and fitness for a particular purpose are disclaimed.
34 // In no event shall the Intel Corporation or contributors be liable for any direct,
35 // indirect, incidental, special, exemplary, or consequential damages
36 // (including, but not limited to, procurement of substitute goods or services;
37 // loss of use, data, or profits; or business interruption) however caused
38 // and on any theory of liability, whether in contract, strict liability,
39 // or tort (including negligence or otherwise) arising in any way out of
40 // the use of this software, even if advised of the possibility of such damage.
41 //
42 //M*/
43 
44 
45 #ifndef OPENCV_CORE_C_H
46 #define OPENCV_CORE_C_H
47 
48 #include "opencv2/core/types_c.h"
49 
50 #ifdef __cplusplus
51 #  ifdef _MSC_VER
52 /* disable warning C4190: 'function' has C-linkage specified, but returns UDT 'typename'
53                           which is incompatible with C
54 
55    It is OK to disable it because we only extend few plain structures with
56    C++ constructors for simpler interoperability with C++ API of the library
57 */
58 #    pragma warning(disable:4190)
59 #  elif defined __clang__ && __clang_major__ >= 3
60 #    pragma GCC diagnostic ignored "-Wreturn-type-c-linkage"
61 #  endif
62 #endif
63 
64 #ifdef __cplusplus
65 extern "C" {
66 #endif
67 
68 /** @addtogroup core_c
69     @{
70 */
71 
72 /****************************************************************************************\
73 *          Array allocation, deallocation, initialization and access to elements         *
74 \****************************************************************************************/
75 
76 /** `malloc` wrapper.
77    If there is no enough memory, the function
78    (as well as other OpenCV functions that call cvAlloc)
79    raises an error. */
80 CVAPI(void*)  cvAlloc( size_t size );
81 
82 /** `free` wrapper.
83    Here and further all the memory releasing functions
84    (that all call cvFree) take double pointer in order to
85    to clear pointer to the data after releasing it.
86    Passing pointer to NULL pointer is Ok: nothing happens in this case
87 */
88 CVAPI(void)   cvFree_( void* ptr );
89 #define cvFree(ptr) (cvFree_(*(ptr)), *(ptr)=0)
90 
91 /** @brief Creates an image header but does not allocate the image data.
92 
93 @param size Image width and height
94 @param depth Image depth (see cvCreateImage )
95 @param channels Number of channels (see cvCreateImage )
96  */
97 CVAPI(IplImage*)  cvCreateImageHeader( CvSize size, int depth, int channels );
98 
99 /** @brief Initializes an image header that was previously allocated.
100 
101 The returned IplImage\* points to the initialized header.
102 @param image Image header to initialize
103 @param size Image width and height
104 @param depth Image depth (see cvCreateImage )
105 @param channels Number of channels (see cvCreateImage )
106 @param origin Top-left IPL_ORIGIN_TL or bottom-left IPL_ORIGIN_BL
107 @param align Alignment for image rows, typically 4 or 8 bytes
108  */
109 CVAPI(IplImage*) cvInitImageHeader( IplImage* image, CvSize size, int depth,
110                                    int channels, int origin CV_DEFAULT(0),
111                                    int align CV_DEFAULT(4));
112 
113 /** @brief Creates an image header and allocates the image data.
114 
115 This function call is equivalent to the following code:
116 @code
117     header = cvCreateImageHeader(size, depth, channels);
118     cvCreateData(header);
119 @endcode
120 @param size Image width and height
121 @param depth Bit depth of image elements. See IplImage for valid depths.
122 @param channels Number of channels per pixel. See IplImage for details. This function only creates
123 images with interleaved channels.
124  */
125 CVAPI(IplImage*)  cvCreateImage( CvSize size, int depth, int channels );
126 
127 /** @brief Deallocates an image header.
128 
129 This call is an analogue of :
130 @code
131     if(image )
132     {
133         iplDeallocate(*image, IPL_IMAGE_HEADER | IPL_IMAGE_ROI);
134         *image = 0;
135     }
136 @endcode
137 but it does not use IPL functions by default (see the CV_TURN_ON_IPL_COMPATIBILITY macro).
138 @param image Double pointer to the image header
139  */
140 CVAPI(void)  cvReleaseImageHeader( IplImage** image );
141 
142 /** @brief Deallocates the image header and the image data.
143 
144 This call is a shortened form of :
145 @code
146     if(*image )
147     {
148         cvReleaseData(*image);
149         cvReleaseImageHeader(image);
150     }
151 @endcode
152 @param image Double pointer to the image header
153 */
154 CVAPI(void)  cvReleaseImage( IplImage** image );
155 
156 /** Creates a copy of IPL image (widthStep may differ) */
157 CVAPI(IplImage*) cvCloneImage( const IplImage* image );
158 
159 /** @brief Sets the channel of interest in an IplImage.
160 
161 If the ROI is set to NULL and the coi is *not* 0, the ROI is allocated. Most OpenCV functions do
162 *not* support the COI setting, so to process an individual image/matrix channel one may copy (via
163 cvCopy or cvSplit) the channel to a separate image/matrix, process it and then copy the result
164 back (via cvCopy or cvMerge) if needed.
165 @param image A pointer to the image header
166 @param coi The channel of interest. 0 - all channels are selected, 1 - first channel is selected,
167 etc. Note that the channel indices become 1-based.
168  */
169 CVAPI(void)  cvSetImageCOI( IplImage* image, int coi );
170 
171 /** @brief Returns the index of the channel of interest.
172 
173 Returns the channel of interest of in an IplImage. Returned values correspond to the coi in
174 cvSetImageCOI.
175 @param image A pointer to the image header
176  */
177 CVAPI(int)  cvGetImageCOI( const IplImage* image );
178 
179 /** @brief Sets an image Region Of Interest (ROI) for a given rectangle.
180 
181 If the original image ROI was NULL and the rect is not the whole image, the ROI structure is
182 allocated.
183 
184 Most OpenCV functions support the use of ROI and treat the image rectangle as a separate image. For
185 example, all of the pixel coordinates are counted from the top-left (or bottom-left) corner of the
186 ROI, not the original image.
187 @param image A pointer to the image header
188 @param rect The ROI rectangle
189  */
190 CVAPI(void)  cvSetImageROI( IplImage* image, CvRect rect );
191 
192 /** @brief Resets the image ROI to include the entire image and releases the ROI structure.
193 
194 This produces a similar result to the following, but in addition it releases the ROI structure. :
195 @code
196     cvSetImageROI(image, cvRect(0, 0, image->width, image->height ));
197     cvSetImageCOI(image, 0);
198 @endcode
199 @param image A pointer to the image header
200  */
201 CVAPI(void)  cvResetImageROI( IplImage* image );
202 
203 /** @brief Returns the image ROI.
204 
205 If there is no ROI set, cvRect(0,0,image-\>width,image-\>height) is returned.
206 @param image A pointer to the image header
207  */
208 CVAPI(CvRect) cvGetImageROI( const IplImage* image );
209 
210 /** @brief Creates a matrix header but does not allocate the matrix data.
211 
212 The function allocates a new matrix header and returns a pointer to it. The matrix data can then be
213 allocated using cvCreateData or set explicitly to user-allocated data via cvSetData.
214 @param rows Number of rows in the matrix
215 @param cols Number of columns in the matrix
216 @param type Type of the matrix elements, see cvCreateMat
217  */
218 CVAPI(CvMat*)  cvCreateMatHeader( int rows, int cols, int type );
219 
220 #define CV_AUTOSTEP  0x7fffffff
221 
222 /** @brief Initializes a pre-allocated matrix header.
223 
224 This function is often used to process raw data with OpenCV matrix functions. For example, the
225 following code computes the matrix product of two matrices, stored as ordinary arrays:
226 @code
227     double a[] = { 1, 2, 3, 4,
228                    5, 6, 7, 8,
229                    9, 10, 11, 12 };
230 
231     double b[] = { 1, 5, 9,
232                    2, 6, 10,
233                    3, 7, 11,
234                    4, 8, 12 };
235 
236     double c[9];
237     CvMat Ma, Mb, Mc ;
238 
239     cvInitMatHeader(&Ma, 3, 4, CV_64FC1, a);
240     cvInitMatHeader(&Mb, 4, 3, CV_64FC1, b);
241     cvInitMatHeader(&Mc, 3, 3, CV_64FC1, c);
242 
243     cvMatMulAdd(&Ma, &Mb, 0, &Mc);
244     // the c array now contains the product of a (3x4) and b (4x3)
245 @endcode
246 @param mat A pointer to the matrix header to be initialized
247 @param rows Number of rows in the matrix
248 @param cols Number of columns in the matrix
249 @param type Type of the matrix elements, see cvCreateMat .
250 @param data Optional: data pointer assigned to the matrix header
251 @param step Optional: full row width in bytes of the assigned data. By default, the minimal
252 possible step is used which assumes there are no gaps between subsequent rows of the matrix.
253  */
254 CVAPI(CvMat*) cvInitMatHeader( CvMat* mat, int rows, int cols,
255                               int type, void* data CV_DEFAULT(NULL),
256                               int step CV_DEFAULT(CV_AUTOSTEP) );
257 
258 /** @brief Creates a matrix header and allocates the matrix data.
259 
260 The function call is equivalent to the following code:
261 @code
262     CvMat* mat = cvCreateMatHeader(rows, cols, type);
263     cvCreateData(mat);
264 @endcode
265 @param rows Number of rows in the matrix
266 @param cols Number of columns in the matrix
267 @param type The type of the matrix elements in the form
268 CV_\<bit depth\>\<S|U|F\>C\<number of channels\> , where S=signed, U=unsigned, F=float. For
269 example, CV _ 8UC1 means the elements are 8-bit unsigned and the there is 1 channel, and CV _
270 32SC2 means the elements are 32-bit signed and there are 2 channels.
271  */
272 CVAPI(CvMat*)  cvCreateMat( int rows, int cols, int type );
273 
274 /** @brief Deallocates a matrix.
275 
276 The function decrements the matrix data reference counter and deallocates matrix header. If the data
277 reference counter is 0, it also deallocates the data. :
278 @code
279     if(*mat )
280         cvDecRefData(*mat);
281     cvFree((void**)mat);
282 @endcode
283 @param mat Double pointer to the matrix
284  */
285 CVAPI(void)  cvReleaseMat( CvMat** mat );
286 
287 /** @brief Decrements an array data reference counter.
288 
289 The function decrements the data reference counter in a CvMat or CvMatND if the reference counter
290 
291 pointer is not NULL. If the counter reaches zero, the data is deallocated. In the current
292 implementation the reference counter is not NULL only if the data was allocated using the
293 cvCreateData function. The counter will be NULL in other cases such as: external data was assigned
294 to the header using cvSetData, header is part of a larger matrix or image, or the header was
295 converted from an image or n-dimensional matrix header.
296 @param arr Pointer to an array header
297  */
cvDecRefData(CvArr * arr)298 CV_INLINE  void  cvDecRefData( CvArr* arr )
299 {
300     if( CV_IS_MAT( arr ))
301     {
302         CvMat* mat = (CvMat*)arr;
303         mat->data.ptr = NULL;
304         if( mat->refcount != NULL && --*mat->refcount == 0 )
305             cvFree( &mat->refcount );
306         mat->refcount = NULL;
307     }
308     else if( CV_IS_MATND( arr ))
309     {
310         CvMatND* mat = (CvMatND*)arr;
311         mat->data.ptr = NULL;
312         if( mat->refcount != NULL && --*mat->refcount == 0 )
313             cvFree( &mat->refcount );
314         mat->refcount = NULL;
315     }
316 }
317 
318 /** @brief Increments array data reference counter.
319 
320 The function increments CvMat or CvMatND data reference counter and returns the new counter value if
321 the reference counter pointer is not NULL, otherwise it returns zero.
322 @param arr Array header
323  */
cvIncRefData(CvArr * arr)324 CV_INLINE  int  cvIncRefData( CvArr* arr )
325 {
326     int refcount = 0;
327     if( CV_IS_MAT( arr ))
328     {
329         CvMat* mat = (CvMat*)arr;
330         if( mat->refcount != NULL )
331             refcount = ++*mat->refcount;
332     }
333     else if( CV_IS_MATND( arr ))
334     {
335         CvMatND* mat = (CvMatND*)arr;
336         if( mat->refcount != NULL )
337             refcount = ++*mat->refcount;
338     }
339     return refcount;
340 }
341 
342 
343 /** Creates an exact copy of the input matrix (except, may be, step value) */
344 CVAPI(CvMat*) cvCloneMat( const CvMat* mat );
345 
346 
347 /** @brief Returns matrix header corresponding to the rectangular sub-array of input image or matrix.
348 
349 The function returns header, corresponding to a specified rectangle of the input array. In other
350 
351 words, it allows the user to treat a rectangular part of input array as a stand-alone array. ROI is
352 taken into account by the function so the sub-array of ROI is actually extracted.
353 @param arr Input array
354 @param submat Pointer to the resultant sub-array header
355 @param rect Zero-based coordinates of the rectangle of interest
356  */
357 CVAPI(CvMat*) cvGetSubRect( const CvArr* arr, CvMat* submat, CvRect rect );
358 #define cvGetSubArr cvGetSubRect
359 
360 /** @brief Returns array row or row span.
361 
362 The function returns the header, corresponding to a specified row/row span of the input array.
363 cvGetRow(arr, submat, row) is a shortcut for cvGetRows(arr, submat, row, row+1).
364 @param arr Input array
365 @param submat Pointer to the resulting sub-array header
366 @param start_row Zero-based index of the starting row (inclusive) of the span
367 @param end_row Zero-based index of the ending row (exclusive) of the span
368 @param delta_row Index step in the row span. That is, the function extracts every delta_row -th
369 row from start_row and up to (but not including) end_row .
370  */
371 CVAPI(CvMat*) cvGetRows( const CvArr* arr, CvMat* submat,
372                         int start_row, int end_row,
373                         int delta_row CV_DEFAULT(1));
374 
375 /** @overload
376 @param arr Input array
377 @param submat Pointer to the resulting sub-array header
378 @param row Zero-based index of the selected row
379 */
cvGetRow(const CvArr * arr,CvMat * submat,int row)380 CV_INLINE  CvMat*  cvGetRow( const CvArr* arr, CvMat* submat, int row )
381 {
382     return cvGetRows( arr, submat, row, row + 1, 1 );
383 }
384 
385 
386 /** @brief Returns one of more array columns.
387 
388 The function returns the header, corresponding to a specified column span of the input array. That
389 
390 is, no data is copied. Therefore, any modifications of the submatrix will affect the original array.
391 If you need to copy the columns, use cvCloneMat. cvGetCol(arr, submat, col) is a shortcut for
392 cvGetCols(arr, submat, col, col+1).
393 @param arr Input array
394 @param submat Pointer to the resulting sub-array header
395 @param start_col Zero-based index of the starting column (inclusive) of the span
396 @param end_col Zero-based index of the ending column (exclusive) of the span
397  */
398 CVAPI(CvMat*) cvGetCols( const CvArr* arr, CvMat* submat,
399                         int start_col, int end_col );
400 
401 /** @overload
402 @param arr Input array
403 @param submat Pointer to the resulting sub-array header
404 @param col Zero-based index of the selected column
405 */
cvGetCol(const CvArr * arr,CvMat * submat,int col)406 CV_INLINE  CvMat*  cvGetCol( const CvArr* arr, CvMat* submat, int col )
407 {
408     return cvGetCols( arr, submat, col, col + 1 );
409 }
410 
411 /** @brief Returns one of array diagonals.
412 
413 The function returns the header, corresponding to a specified diagonal of the input array.
414 @param arr Input array
415 @param submat Pointer to the resulting sub-array header
416 @param diag Index of the array diagonal. Zero value corresponds to the main diagonal, -1
417 corresponds to the diagonal above the main, 1 corresponds to the diagonal below the main, and so
418 forth.
419  */
420 CVAPI(CvMat*) cvGetDiag( const CvArr* arr, CvMat* submat,
421                             int diag CV_DEFAULT(0));
422 
423 /** low-level scalar <-> raw data conversion functions */
424 CVAPI(void) cvScalarToRawData( const CvScalar* scalar, void* data, int type,
425                               int extend_to_12 CV_DEFAULT(0) );
426 
427 CVAPI(void) cvRawDataToScalar( const void* data, int type, CvScalar* scalar );
428 
429 /** @brief Creates a new matrix header but does not allocate the matrix data.
430 
431 The function allocates a header for a multi-dimensional dense array. The array data can further be
432 allocated using cvCreateData or set explicitly to user-allocated data via cvSetData.
433 @param dims Number of array dimensions
434 @param sizes Array of dimension sizes
435 @param type Type of array elements, see cvCreateMat
436  */
437 CVAPI(CvMatND*)  cvCreateMatNDHeader( int dims, const int* sizes, int type );
438 
439 /** @brief Creates the header and allocates the data for a multi-dimensional dense array.
440 
441 This function call is equivalent to the following code:
442 @code
443     CvMatND* mat = cvCreateMatNDHeader(dims, sizes, type);
444     cvCreateData(mat);
445 @endcode
446 @param dims Number of array dimensions. This must not exceed CV_MAX_DIM (32 by default, but can be
447 changed at build time).
448 @param sizes Array of dimension sizes.
449 @param type Type of array elements, see cvCreateMat .
450  */
451 CVAPI(CvMatND*)  cvCreateMatND( int dims, const int* sizes, int type );
452 
453 /** @brief Initializes a pre-allocated multi-dimensional array header.
454 
455 @param mat A pointer to the array header to be initialized
456 @param dims The number of array dimensions
457 @param sizes An array of dimension sizes
458 @param type Type of array elements, see cvCreateMat
459 @param data Optional data pointer assigned to the matrix header
460  */
461 CVAPI(CvMatND*)  cvInitMatNDHeader( CvMatND* mat, int dims, const int* sizes,
462                                     int type, void* data CV_DEFAULT(NULL) );
463 
464 /** @brief Deallocates a multi-dimensional array.
465 
466 The function decrements the array data reference counter and releases the array header. If the
467 reference counter reaches 0, it also deallocates the data. :
468 @code
469     if(*mat )
470         cvDecRefData(*mat);
471     cvFree((void**)mat);
472 @endcode
473 @param mat Double pointer to the array
474  */
cvReleaseMatND(CvMatND ** mat)475 CV_INLINE  void  cvReleaseMatND( CvMatND** mat )
476 {
477     cvReleaseMat( (CvMat**)mat );
478 }
479 
480 /** Creates a copy of CvMatND (except, may be, steps) */
481 CVAPI(CvMatND*) cvCloneMatND( const CvMatND* mat );
482 
483 /** @brief Creates sparse array.
484 
485 The function allocates a multi-dimensional sparse array. Initially the array contain no elements,
486 that is PtrND and other related functions will return 0 for every index.
487 @param dims Number of array dimensions. In contrast to the dense matrix, the number of dimensions is
488 practically unlimited (up to \f$2^{16}\f$ ).
489 @param sizes Array of dimension sizes
490 @param type Type of array elements. The same as for CvMat
491  */
492 CVAPI(CvSparseMat*)  cvCreateSparseMat( int dims, const int* sizes, int type );
493 
494 /** @brief Deallocates sparse array.
495 
496 The function releases the sparse array and clears the array pointer upon exit.
497 @param mat Double pointer to the array
498  */
499 CVAPI(void)  cvReleaseSparseMat( CvSparseMat** mat );
500 
501 /** Creates a copy of CvSparseMat (except, may be, zero items) */
502 CVAPI(CvSparseMat*) cvCloneSparseMat( const CvSparseMat* mat );
503 
504 /** @brief Initializes sparse array elements iterator.
505 
506 The function initializes iterator of sparse array elements and returns pointer to the first element,
507 or NULL if the array is empty.
508 @param mat Input array
509 @param mat_iterator Initialized iterator
510  */
511 CVAPI(CvSparseNode*) cvInitSparseMatIterator( const CvSparseMat* mat,
512                                               CvSparseMatIterator* mat_iterator );
513 
514 /** @brief Returns the next sparse matrix element
515 
516 The function moves iterator to the next sparse matrix element and returns pointer to it. In the
517 current version there is no any particular order of the elements, because they are stored in the
518 hash table. The sample below demonstrates how to iterate through the sparse matrix:
519 @code
520     // print all the non-zero sparse matrix elements and compute their sum
521     double sum = 0;
522     int i, dims = cvGetDims(sparsemat);
523     CvSparseMatIterator it;
524     CvSparseNode* node = cvInitSparseMatIterator(sparsemat, &it);
525 
526     for(; node != 0; node = cvGetNextSparseNode(&it))
527     {
528         int* idx = CV_NODE_IDX(array, node);
529         float val = *(float*)CV_NODE_VAL(array, node);
530         printf("M");
531         for(i = 0; i < dims; i++ )
532             printf("[%d]", idx[i]);
533         printf("=%g\n", val);
534 
535         sum += val;
536     }
537 
538     printf("nTotal sum = %g\n", sum);
539 @endcode
540 @param mat_iterator Sparse array iterator
541  */
cvGetNextSparseNode(CvSparseMatIterator * mat_iterator)542 CV_INLINE CvSparseNode* cvGetNextSparseNode( CvSparseMatIterator* mat_iterator )
543 {
544     if( mat_iterator->node->next )
545         return mat_iterator->node = mat_iterator->node->next;
546     else
547     {
548         int idx;
549         for( idx = ++mat_iterator->curidx; idx < mat_iterator->mat->hashsize; idx++ )
550         {
551             CvSparseNode* node = (CvSparseNode*)mat_iterator->mat->hashtable[idx];
552             if( node )
553             {
554                 mat_iterator->curidx = idx;
555                 return mat_iterator->node = node;
556             }
557         }
558         return NULL;
559     }
560 }
561 
562 
563 #define CV_MAX_ARR 10
564 
565 /** matrix iterator: used for n-ary operations on dense arrays */
566 typedef struct CvNArrayIterator
567 {
568     int count; /**< number of arrays */
569     int dims; /**< number of dimensions to iterate */
570     CvSize size; /**< maximal common linear size: { width = size, height = 1 } */
571     uchar* ptr[CV_MAX_ARR]; /**< pointers to the array slices */
572     int stack[CV_MAX_DIM]; /**< for internal use */
573     CvMatND* hdr[CV_MAX_ARR]; /**< pointers to the headers of the
574                                  matrices that are processed */
575 }
576 CvNArrayIterator;
577 
578 #define CV_NO_DEPTH_CHECK     1
579 #define CV_NO_CN_CHECK        2
580 #define CV_NO_SIZE_CHECK      4
581 
582 /** initializes iterator that traverses through several arrays simultaneously
583    (the function together with cvNextArraySlice is used for
584     N-ari element-wise operations) */
585 CVAPI(int) cvInitNArrayIterator( int count, CvArr** arrs,
586                                  const CvArr* mask, CvMatND* stubs,
587                                  CvNArrayIterator* array_iterator,
588                                  int flags CV_DEFAULT(0) );
589 
590 /** returns zero value if iteration is finished, non-zero (slice length) otherwise */
591 CVAPI(int) cvNextNArraySlice( CvNArrayIterator* array_iterator );
592 
593 
594 /** @brief Returns type of array elements.
595 
596 The function returns type of the array elements. In the case of IplImage the type is converted to
597 CvMat-like representation. For example, if the image has been created as:
598 @code
599     IplImage* img = cvCreateImage(cvSize(640, 480), IPL_DEPTH_8U, 3);
600 @endcode
601 The code cvGetElemType(img) will return CV_8UC3.
602 @param arr Input array
603  */
604 CVAPI(int) cvGetElemType( const CvArr* arr );
605 
606 /** @brief Return number of array dimensions
607 
608 The function returns the array dimensionality and the array of dimension sizes. In the case of
609 IplImage or CvMat it always returns 2 regardless of number of image/matrix rows. For example, the
610 following code calculates total number of array elements:
611 @code
612     int sizes[CV_MAX_DIM];
613     int i, total = 1;
614     int dims = cvGetDims(arr, size);
615     for(i = 0; i < dims; i++ )
616         total *= sizes[i];
617 @endcode
618 @param arr Input array
619 @param sizes Optional output vector of the array dimension sizes. For 2d arrays the number of rows
620 (height) goes first, number of columns (width) next.
621  */
622 CVAPI(int) cvGetDims( const CvArr* arr, int* sizes CV_DEFAULT(NULL) );
623 
624 
625 /** @brief Returns array size along the specified dimension.
626 
627 @param arr Input array
628 @param index Zero-based dimension index (for matrices 0 means number of rows, 1 means number of
629 columns; for images 0 means height, 1 means width)
630  */
631 CVAPI(int) cvGetDimSize( const CvArr* arr, int index );
632 
633 
634 /** @brief Return pointer to a particular array element.
635 
636 The functions return a pointer to a specific array element. Number of array dimension should match
637 to the number of indices passed to the function except for cvPtr1D function that can be used for
638 sequential access to 1D, 2D or nD dense arrays.
639 
640 The functions can be used for sparse arrays as well - if the requested node does not exist they
641 create it and set it to zero.
642 
643 All these as well as other functions accessing array elements ( cvGetND , cvGetRealND , cvSet
644 , cvSetND , cvSetRealND ) raise an error in case if the element index is out of range.
645 @param arr Input array
646 @param idx0 The first zero-based component of the element index
647 @param type Optional output parameter: type of matrix elements
648  */
649 CVAPI(uchar*) cvPtr1D( const CvArr* arr, int idx0, int* type CV_DEFAULT(NULL));
650 /** @overload */
651 CVAPI(uchar*) cvPtr2D( const CvArr* arr, int idx0, int idx1, int* type CV_DEFAULT(NULL) );
652 /** @overload */
653 CVAPI(uchar*) cvPtr3D( const CvArr* arr, int idx0, int idx1, int idx2,
654                       int* type CV_DEFAULT(NULL));
655 /** @overload
656 @param arr Input array
657 @param idx Array of the element indices
658 @param type Optional output parameter: type of matrix elements
659 @param create_node Optional input parameter for sparse matrices. Non-zero value of the parameter
660 means that the requested element is created if it does not exist already.
661 @param precalc_hashval Optional input parameter for sparse matrices. If the pointer is not NULL,
662 the function does not recalculate the node hash value, but takes it from the specified location.
663 It is useful for speeding up pair-wise operations (TODO: provide an example)
664 */
665 CVAPI(uchar*) cvPtrND( const CvArr* arr, const int* idx, int* type CV_DEFAULT(NULL),
666                       int create_node CV_DEFAULT(1),
667                       unsigned* precalc_hashval CV_DEFAULT(NULL));
668 
669 /** @brief Return a specific array element.
670 
671 The functions return a specific array element. In the case of a sparse array the functions return 0
672 if the requested node does not exist (no new node is created by the functions).
673 @param arr Input array
674 @param idx0 The first zero-based component of the element index
675  */
676 CVAPI(CvScalar) cvGet1D( const CvArr* arr, int idx0 );
677 /** @overload */
678 CVAPI(CvScalar) cvGet2D( const CvArr* arr, int idx0, int idx1 );
679 /** @overload */
680 CVAPI(CvScalar) cvGet3D( const CvArr* arr, int idx0, int idx1, int idx2 );
681 /** @overload
682 @param arr Input array
683 @param idx Array of the element indices
684 */
685 CVAPI(CvScalar) cvGetND( const CvArr* arr, const int* idx );
686 
687 /** @brief Return a specific element of single-channel 1D, 2D, 3D or nD array.
688 
689 Returns a specific element of a single-channel array. If the array has multiple channels, a runtime
690 error is raised. Note that Get?D functions can be used safely for both single-channel and
691 multiple-channel arrays though they are a bit slower.
692 
693 In the case of a sparse array the functions return 0 if the requested node does not exist (no new
694 node is created by the functions).
695 @param arr Input array. Must have a single channel.
696 @param idx0 The first zero-based component of the element index
697  */
698 CVAPI(double) cvGetReal1D( const CvArr* arr, int idx0 );
699 /** @overload */
700 CVAPI(double) cvGetReal2D( const CvArr* arr, int idx0, int idx1 );
701 /** @overload */
702 CVAPI(double) cvGetReal3D( const CvArr* arr, int idx0, int idx1, int idx2 );
703 /** @overload
704 @param arr Input array. Must have a single channel.
705 @param idx Array of the element indices
706 */
707 CVAPI(double) cvGetRealND( const CvArr* arr, const int* idx );
708 
709 /** @brief Change the particular array element.
710 
711 The functions assign the new value to a particular array element. In the case of a sparse array the
712 functions create the node if it does not exist yet.
713 @param arr Input array
714 @param idx0 The first zero-based component of the element index
715 @param value The assigned value
716  */
717 CVAPI(void) cvSet1D( CvArr* arr, int idx0, CvScalar value );
718 /** @overload */
719 CVAPI(void) cvSet2D( CvArr* arr, int idx0, int idx1, CvScalar value );
720 /** @overload */
721 CVAPI(void) cvSet3D( CvArr* arr, int idx0, int idx1, int idx2, CvScalar value );
722 /** @overload
723 @param arr Input array
724 @param idx Array of the element indices
725 @param value The assigned value
726 */
727 CVAPI(void) cvSetND( CvArr* arr, const int* idx, CvScalar value );
728 
729 /** @brief Change a specific array element.
730 
731 The functions assign a new value to a specific element of a single-channel array. If the array has
732 multiple channels, a runtime error is raised. Note that the Set\*D function can be used safely for
733 both single-channel and multiple-channel arrays, though they are a bit slower.
734 
735 In the case of a sparse array the functions create the node if it does not yet exist.
736 @param arr Input array
737 @param idx0 The first zero-based component of the element index
738 @param value The assigned value
739  */
740 CVAPI(void) cvSetReal1D( CvArr* arr, int idx0, double value );
741 /** @overload */
742 CVAPI(void) cvSetReal2D( CvArr* arr, int idx0, int idx1, double value );
743 /** @overload */
744 CVAPI(void) cvSetReal3D( CvArr* arr, int idx0,
745                         int idx1, int idx2, double value );
746 /** @overload
747 @param arr Input array
748 @param idx Array of the element indices
749 @param value The assigned value
750 */
751 CVAPI(void) cvSetRealND( CvArr* arr, const int* idx, double value );
752 
753 /** clears element of ND dense array,
754    in case of sparse arrays it deletes the specified node */
755 CVAPI(void) cvClearND( CvArr* arr, const int* idx );
756 
757 /** @brief Returns matrix header for arbitrary array.
758 
759 The function returns a matrix header for the input array that can be a matrix - CvMat, an image -
760 IplImage, or a multi-dimensional dense array - CvMatND (the third option is allowed only if
761 allowND != 0) . In the case of matrix the function simply returns the input pointer. In the case of
762 IplImage\* or CvMatND it initializes the header structure with parameters of the current image ROI
763 and returns &header. Because COI is not supported by CvMat, it is returned separately.
764 
765 The function provides an easy way to handle both types of arrays - IplImage and CvMat using the same
766 code. Input array must have non-zero data pointer, otherwise the function will report an error.
767 
768 @note If the input array is IplImage with planar data layout and COI set, the function returns the
769 pointer to the selected plane and COI == 0. This feature allows user to process IplImage structures
770 with planar data layout, even though OpenCV does not support such images.
771 @param arr Input array
772 @param header Pointer to CvMat structure used as a temporary buffer
773 @param coi Optional output parameter for storing COI
774 @param allowND If non-zero, the function accepts multi-dimensional dense arrays (CvMatND\*) and
775 returns 2D matrix (if CvMatND has two dimensions) or 1D matrix (when CvMatND has 1 dimension or
776 more than 2 dimensions). The CvMatND array must be continuous.
777 @sa cvGetImage, cvarrToMat.
778  */
779 CVAPI(CvMat*) cvGetMat( const CvArr* arr, CvMat* header,
780                        int* coi CV_DEFAULT(NULL),
781                        int allowND CV_DEFAULT(0));
782 
783 /** @brief Returns image header for arbitrary array.
784 
785 The function returns the image header for the input array that can be a matrix (CvMat) or image
786 (IplImage). In the case of an image the function simply returns the input pointer. In the case of
787 CvMat it initializes an image_header structure with the parameters of the input matrix. Note that
788 if we transform IplImage to CvMat using cvGetMat and then transform CvMat back to IplImage using
789 this function, we will get different headers if the ROI is set in the original image.
790 @param arr Input array
791 @param image_header Pointer to IplImage structure used as a temporary buffer
792  */
793 CVAPI(IplImage*) cvGetImage( const CvArr* arr, IplImage* image_header );
794 
795 
796 /** @brief Changes the shape of a multi-dimensional array without copying the data.
797 
798 The function is an advanced version of cvReshape that can work with multi-dimensional arrays as
799 well (though it can work with ordinary images and matrices) and change the number of dimensions.
800 
801 Below are the two samples from the cvReshape description rewritten using cvReshapeMatND:
802 @code
803     IplImage* color_img = cvCreateImage(cvSize(320,240), IPL_DEPTH_8U, 3);
804     IplImage gray_img_hdr, *gray_img;
805     gray_img = (IplImage*)cvReshapeMatND(color_img, sizeof(gray_img_hdr), &gray_img_hdr, 1, 0, 0);
806     ...
807     int size[] = { 2, 2, 2 };
808     CvMatND* mat = cvCreateMatND(3, size, CV_32F);
809     CvMat row_header, *row;
810     row = (CvMat*)cvReshapeMatND(mat, sizeof(row_header), &row_header, 0, 1, 0);
811 @endcode
812 In C, the header file for this function includes a convenient macro cvReshapeND that does away with
813 the sizeof_header parameter. So, the lines containing the call to cvReshapeMatND in the examples
814 may be replaced as follow:
815 @code
816     gray_img = (IplImage*)cvReshapeND(color_img, &gray_img_hdr, 1, 0, 0);
817     ...
818     row = (CvMat*)cvReshapeND(mat, &row_header, 0, 1, 0);
819 @endcode
820 @param arr Input array
821 @param sizeof_header Size of output header to distinguish between IplImage, CvMat and CvMatND
822 output headers
823 @param header Output header to be filled
824 @param new_cn New number of channels. new_cn = 0 means that the number of channels remains
825 unchanged.
826 @param new_dims New number of dimensions. new_dims = 0 means that the number of dimensions
827 remains the same.
828 @param new_sizes Array of new dimension sizes. Only new_dims-1 values are used, because the
829 total number of elements must remain the same. Thus, if new_dims = 1, new_sizes array is not
830 used.
831  */
832 CVAPI(CvArr*) cvReshapeMatND( const CvArr* arr,
833                              int sizeof_header, CvArr* header,
834                              int new_cn, int new_dims, int* new_sizes );
835 
836 #define cvReshapeND( arr, header, new_cn, new_dims, new_sizes )   \
837       cvReshapeMatND( (arr), sizeof(*(header)), (header),         \
838                       (new_cn), (new_dims), (new_sizes))
839 
840 /** @brief Changes shape of matrix/image without copying data.
841 
842 The function initializes the CvMat header so that it points to the same data as the original array
843 but has a different shape - different number of channels, different number of rows, or both.
844 
845 The following example code creates one image buffer and two image headers, the first is for a
846 320x240x3 image and the second is for a 960x240x1 image:
847 @code
848     IplImage* color_img = cvCreateImage(cvSize(320,240), IPL_DEPTH_8U, 3);
849     CvMat gray_mat_hdr;
850     IplImage gray_img_hdr, *gray_img;
851     cvReshape(color_img, &gray_mat_hdr, 1);
852     gray_img = cvGetImage(&gray_mat_hdr, &gray_img_hdr);
853 @endcode
854 And the next example converts a 3x3 matrix to a single 1x9 vector:
855 @code
856     CvMat* mat = cvCreateMat(3, 3, CV_32F);
857     CvMat row_header, *row;
858     row = cvReshape(mat, &row_header, 0, 1);
859 @endcode
860 @param arr Input array
861 @param header Output header to be filled
862 @param new_cn New number of channels. 'new_cn = 0' means that the number of channels remains
863 unchanged.
864 @param new_rows New number of rows. 'new_rows = 0' means that the number of rows remains
865 unchanged unless it needs to be changed according to new_cn value.
866 */
867 CVAPI(CvMat*) cvReshape( const CvArr* arr, CvMat* header,
868                         int new_cn, int new_rows CV_DEFAULT(0) );
869 
870 /** Repeats source 2d array several times in both horizontal and
871    vertical direction to fill destination array */
872 CVAPI(void) cvRepeat( const CvArr* src, CvArr* dst );
873 
874 /** @brief Allocates array data
875 
876 The function allocates image, matrix or multi-dimensional dense array data. Note that in the case of
877 matrix types OpenCV allocation functions are used. In the case of IplImage they are used unless
878 CV_TURN_ON_IPL_COMPATIBILITY() has been called before. In the latter case IPL functions are used
879 to allocate the data.
880 @param arr Array header
881  */
882 CVAPI(void)  cvCreateData( CvArr* arr );
883 
884 /** @brief Releases array data.
885 
886 The function releases the array data. In the case of CvMat or CvMatND it simply calls
887 cvDecRefData(), that is the function can not deallocate external data. See also the note to
888 cvCreateData .
889 @param arr Array header
890  */
891 CVAPI(void)  cvReleaseData( CvArr* arr );
892 
893 /** @brief Assigns user data to the array header.
894 
895 The function assigns user data to the array header. Header should be initialized before using
896 cvCreateMatHeader, cvCreateImageHeader, cvCreateMatNDHeader, cvInitMatHeader,
897 cvInitImageHeader or cvInitMatNDHeader.
898 @param arr Array header
899 @param data User data
900 @param step Full row length in bytes
901  */
902 CVAPI(void)  cvSetData( CvArr* arr, void* data, int step );
903 
904 /** @brief Retrieves low-level information about the array.
905 
906 The function fills output variables with low-level information about the array data. All output
907 
908 parameters are optional, so some of the pointers may be set to NULL. If the array is IplImage with
909 ROI set, the parameters of ROI are returned.
910 
911 The following example shows how to get access to array elements. It computes absolute values of the
912 array elements :
913 @code
914     float* data;
915     int step;
916     CvSize size;
917 
918     cvGetRawData(array, (uchar**)&data, &step, &size);
919     step /= sizeof(data[0]);
920 
921     for(int y = 0; y < size.height; y++, data += step )
922         for(int x = 0; x < size.width; x++ )
923             data[x] = (float)fabs(data[x]);
924 @endcode
925 @param arr Array header
926 @param data Output pointer to the whole image origin or ROI origin if ROI is set
927 @param step Output full row length in bytes
928 @param roi_size Output ROI size
929  */
930 CVAPI(void) cvGetRawData( const CvArr* arr, uchar** data,
931                          int* step CV_DEFAULT(NULL),
932                          CvSize* roi_size CV_DEFAULT(NULL));
933 
934 /** @brief Returns size of matrix or image ROI.
935 
936 The function returns number of rows (CvSize::height) and number of columns (CvSize::width) of the
937 input matrix or image. In the case of image the size of ROI is returned.
938 @param arr array header
939  */
940 CVAPI(CvSize) cvGetSize( const CvArr* arr );
941 
942 /** @brief Copies one array to another.
943 
944 The function copies selected elements from an input array to an output array:
945 
946 \f[\texttt{dst} (I)= \texttt{src} (I)  \quad \text{if} \quad \texttt{mask} (I)  \ne 0.\f]
947 
948 If any of the passed arrays is of IplImage type, then its ROI and COI fields are used. Both arrays
949 must have the same type, the same number of dimensions, and the same size. The function can also
950 copy sparse arrays (mask is not supported in this case).
951 @param src The source array
952 @param dst The destination array
953 @param mask Operation mask, 8-bit single channel array; specifies elements of the destination array
954 to be changed
955  */
956 CVAPI(void)  cvCopy( const CvArr* src, CvArr* dst,
957                      const CvArr* mask CV_DEFAULT(NULL) );
958 
959 /** @brief Sets every element of an array to a given value.
960 
961 The function copies the scalar value to every selected element of the destination array:
962 \f[\texttt{arr} (I)= \texttt{value} \quad \text{if} \quad \texttt{mask} (I)  \ne 0\f]
963 If array arr is of IplImage type, then is ROI used, but COI must not be set.
964 @param arr The destination array
965 @param value Fill value
966 @param mask Operation mask, 8-bit single channel array; specifies elements of the destination
967 array to be changed
968  */
969 CVAPI(void)  cvSet( CvArr* arr, CvScalar value,
970                     const CvArr* mask CV_DEFAULT(NULL) );
971 
972 /** @brief Clears the array.
973 
974 The function clears the array. In the case of dense arrays (CvMat, CvMatND or IplImage),
975 cvZero(array) is equivalent to cvSet(array,cvScalarAll(0),0). In the case of sparse arrays all the
976 elements are removed.
977 @param arr Array to be cleared
978  */
979 CVAPI(void)  cvSetZero( CvArr* arr );
980 #define cvZero  cvSetZero
981 
982 
983 /** Splits a multi-channel array into the set of single-channel arrays or
984    extracts particular [color] plane */
985 CVAPI(void)  cvSplit( const CvArr* src, CvArr* dst0, CvArr* dst1,
986                       CvArr* dst2, CvArr* dst3 );
987 
988 /** Merges a set of single-channel arrays into the single multi-channel array
989    or inserts one particular [color] plane to the array */
990 CVAPI(void)  cvMerge( const CvArr* src0, const CvArr* src1,
991                       const CvArr* src2, const CvArr* src3,
992                       CvArr* dst );
993 
994 /** Copies several channels from input arrays to
995    certain channels of output arrays */
996 CVAPI(void)  cvMixChannels( const CvArr** src, int src_count,
997                             CvArr** dst, int dst_count,
998                             const int* from_to, int pair_count );
999 
1000 /** @brief Converts one array to another with optional linear transformation.
1001 
1002 The function has several different purposes, and thus has several different names. It copies one
1003 array to another with optional scaling, which is performed first, and/or optional type conversion,
1004 performed after:
1005 
1006 \f[\texttt{dst} (I) =  \texttt{scale} \texttt{src} (I) + ( \texttt{shift} _0, \texttt{shift} _1,...)\f]
1007 
1008 All the channels of multi-channel arrays are processed independently.
1009 
1010 The type of conversion is done with rounding and saturation, that is if the result of scaling +
1011 conversion can not be represented exactly by a value of the destination array element type, it is
1012 set to the nearest representable value on the real axis.
1013 @param src Source array
1014 @param dst Destination array
1015 @param scale Scale factor
1016 @param shift Value added to the scaled source array elements
1017  */
1018 CVAPI(void)  cvConvertScale( const CvArr* src, CvArr* dst,
1019                              double scale CV_DEFAULT(1),
1020                              double shift CV_DEFAULT(0) );
1021 #define cvCvtScale cvConvertScale
1022 #define cvScale  cvConvertScale
1023 #define cvConvert( src, dst )  cvConvertScale( (src), (dst), 1, 0 )
1024 
1025 
1026 /** Performs linear transformation on every source array element,
1027    stores absolute value of the result:
1028    dst(x,y,c) = abs(scale*src(x,y,c)+shift).
1029    destination array must have 8u type.
1030    In other cases one may use cvConvertScale + cvAbsDiffS */
1031 CVAPI(void)  cvConvertScaleAbs( const CvArr* src, CvArr* dst,
1032                                 double scale CV_DEFAULT(1),
1033                                 double shift CV_DEFAULT(0) );
1034 #define cvCvtScaleAbs  cvConvertScaleAbs
1035 
1036 
1037 /** checks termination criteria validity and
1038    sets eps to default_eps (if it is not set),
1039    max_iter to default_max_iters (if it is not set)
1040 */
1041 CVAPI(CvTermCriteria) cvCheckTermCriteria( CvTermCriteria criteria,
1042                                            double default_eps,
1043                                            int default_max_iters );
1044 
1045 /****************************************************************************************\
1046 *                   Arithmetic, logic and comparison operations                          *
1047 \****************************************************************************************/
1048 
1049 /** dst(mask) = src1(mask) + src2(mask) */
1050 CVAPI(void)  cvAdd( const CvArr* src1, const CvArr* src2, CvArr* dst,
1051                     const CvArr* mask CV_DEFAULT(NULL));
1052 
1053 /** dst(mask) = src(mask) + value */
1054 CVAPI(void)  cvAddS( const CvArr* src, CvScalar value, CvArr* dst,
1055                      const CvArr* mask CV_DEFAULT(NULL));
1056 
1057 /** dst(mask) = src1(mask) - src2(mask) */
1058 CVAPI(void)  cvSub( const CvArr* src1, const CvArr* src2, CvArr* dst,
1059                     const CvArr* mask CV_DEFAULT(NULL));
1060 
1061 /** dst(mask) = src(mask) - value = src(mask) + (-value) */
cvSubS(const CvArr * src,CvScalar value,CvArr * dst,const CvArr * mask CV_DEFAULT (NULL))1062 CV_INLINE  void  cvSubS( const CvArr* src, CvScalar value, CvArr* dst,
1063                          const CvArr* mask CV_DEFAULT(NULL))
1064 {
1065     cvAddS( src, cvScalar( -value.val[0], -value.val[1], -value.val[2], -value.val[3]),
1066             dst, mask );
1067 }
1068 
1069 /** dst(mask) = value - src(mask) */
1070 CVAPI(void)  cvSubRS( const CvArr* src, CvScalar value, CvArr* dst,
1071                       const CvArr* mask CV_DEFAULT(NULL));
1072 
1073 /** dst(idx) = src1(idx) * src2(idx) * scale
1074    (scaled element-wise multiplication of 2 arrays) */
1075 CVAPI(void)  cvMul( const CvArr* src1, const CvArr* src2,
1076                     CvArr* dst, double scale CV_DEFAULT(1) );
1077 
1078 /** element-wise division/inversion with scaling:
1079     dst(idx) = src1(idx) * scale / src2(idx)
1080     or dst(idx) = scale / src2(idx) if src1 == 0 */
1081 CVAPI(void)  cvDiv( const CvArr* src1, const CvArr* src2,
1082                     CvArr* dst, double scale CV_DEFAULT(1));
1083 
1084 /** dst = src1 * scale + src2 */
1085 CVAPI(void)  cvScaleAdd( const CvArr* src1, CvScalar scale,
1086                          const CvArr* src2, CvArr* dst );
1087 #define cvAXPY( A, real_scalar, B, C ) cvScaleAdd(A, cvRealScalar(real_scalar), B, C)
1088 
1089 /** dst = src1 * alpha + src2 * beta + gamma */
1090 CVAPI(void)  cvAddWeighted( const CvArr* src1, double alpha,
1091                             const CvArr* src2, double beta,
1092                             double gamma, CvArr* dst );
1093 
1094 /** @brief Calculates the dot product of two arrays in Euclidean metrics.
1095 
1096 The function calculates and returns the Euclidean dot product of two arrays.
1097 
1098 \f[src1  \bullet src2 =  \sum _I ( \texttt{src1} (I)  \texttt{src2} (I))\f]
1099 
1100 In the case of multiple channel arrays, the results for all channels are accumulated. In particular,
1101 cvDotProduct(a,a) where a is a complex vector, will return \f$||\texttt{a}||^2\f$. The function can
1102 process multi-dimensional arrays, row by row, layer by layer, and so on.
1103 @param src1 The first source array
1104 @param src2 The second source array
1105  */
1106 CVAPI(double)  cvDotProduct( const CvArr* src1, const CvArr* src2 );
1107 
1108 /** dst(idx) = src1(idx) & src2(idx) */
1109 CVAPI(void) cvAnd( const CvArr* src1, const CvArr* src2,
1110                   CvArr* dst, const CvArr* mask CV_DEFAULT(NULL));
1111 
1112 /** dst(idx) = src(idx) & value */
1113 CVAPI(void) cvAndS( const CvArr* src, CvScalar value,
1114                    CvArr* dst, const CvArr* mask CV_DEFAULT(NULL));
1115 
1116 /** dst(idx) = src1(idx) | src2(idx) */
1117 CVAPI(void) cvOr( const CvArr* src1, const CvArr* src2,
1118                  CvArr* dst, const CvArr* mask CV_DEFAULT(NULL));
1119 
1120 /** dst(idx) = src(idx) | value */
1121 CVAPI(void) cvOrS( const CvArr* src, CvScalar value,
1122                   CvArr* dst, const CvArr* mask CV_DEFAULT(NULL));
1123 
1124 /** dst(idx) = src1(idx) ^ src2(idx) */
1125 CVAPI(void) cvXor( const CvArr* src1, const CvArr* src2,
1126                   CvArr* dst, const CvArr* mask CV_DEFAULT(NULL));
1127 
1128 /** dst(idx) = src(idx) ^ value */
1129 CVAPI(void) cvXorS( const CvArr* src, CvScalar value,
1130                    CvArr* dst, const CvArr* mask CV_DEFAULT(NULL));
1131 
1132 /** dst(idx) = ~src(idx) */
1133 CVAPI(void) cvNot( const CvArr* src, CvArr* dst );
1134 
1135 /** dst(idx) = lower(idx) <= src(idx) < upper(idx) */
1136 CVAPI(void) cvInRange( const CvArr* src, const CvArr* lower,
1137                       const CvArr* upper, CvArr* dst );
1138 
1139 /** dst(idx) = lower <= src(idx) < upper */
1140 CVAPI(void) cvInRangeS( const CvArr* src, CvScalar lower,
1141                        CvScalar upper, CvArr* dst );
1142 
1143 #define CV_CMP_EQ   0
1144 #define CV_CMP_GT   1
1145 #define CV_CMP_GE   2
1146 #define CV_CMP_LT   3
1147 #define CV_CMP_LE   4
1148 #define CV_CMP_NE   5
1149 
1150 /** The comparison operation support single-channel arrays only.
1151    Destination image should be 8uC1 or 8sC1 */
1152 
1153 /** dst(idx) = src1(idx) _cmp_op_ src2(idx) */
1154 CVAPI(void) cvCmp( const CvArr* src1, const CvArr* src2, CvArr* dst, int cmp_op );
1155 
1156 /** dst(idx) = src1(idx) _cmp_op_ value */
1157 CVAPI(void) cvCmpS( const CvArr* src, double value, CvArr* dst, int cmp_op );
1158 
1159 /** dst(idx) = min(src1(idx),src2(idx)) */
1160 CVAPI(void) cvMin( const CvArr* src1, const CvArr* src2, CvArr* dst );
1161 
1162 /** dst(idx) = max(src1(idx),src2(idx)) */
1163 CVAPI(void) cvMax( const CvArr* src1, const CvArr* src2, CvArr* dst );
1164 
1165 /** dst(idx) = min(src(idx),value) */
1166 CVAPI(void) cvMinS( const CvArr* src, double value, CvArr* dst );
1167 
1168 /** dst(idx) = max(src(idx),value) */
1169 CVAPI(void) cvMaxS( const CvArr* src, double value, CvArr* dst );
1170 
1171 /** dst(x,y,c) = abs(src1(x,y,c) - src2(x,y,c)) */
1172 CVAPI(void) cvAbsDiff( const CvArr* src1, const CvArr* src2, CvArr* dst );
1173 
1174 /** dst(x,y,c) = abs(src(x,y,c) - value(c)) */
1175 CVAPI(void) cvAbsDiffS( const CvArr* src, CvArr* dst, CvScalar value );
1176 #define cvAbs( src, dst ) cvAbsDiffS( (src), (dst), cvScalarAll(0))
1177 
1178 /****************************************************************************************\
1179 *                                Math operations                                         *
1180 \****************************************************************************************/
1181 
1182 /** Does cartesian->polar coordinates conversion.
1183    Either of output components (magnitude or angle) is optional */
1184 CVAPI(void)  cvCartToPolar( const CvArr* x, const CvArr* y,
1185                             CvArr* magnitude, CvArr* angle CV_DEFAULT(NULL),
1186                             int angle_in_degrees CV_DEFAULT(0));
1187 
1188 /** Does polar->cartesian coordinates conversion.
1189    Either of output components (magnitude or angle) is optional.
1190    If magnitude is missing it is assumed to be all 1's */
1191 CVAPI(void)  cvPolarToCart( const CvArr* magnitude, const CvArr* angle,
1192                             CvArr* x, CvArr* y,
1193                             int angle_in_degrees CV_DEFAULT(0));
1194 
1195 /** Does powering: dst(idx) = src(idx)^power */
1196 CVAPI(void)  cvPow( const CvArr* src, CvArr* dst, double power );
1197 
1198 /** Does exponention: dst(idx) = exp(src(idx)).
1199    Overflow is not handled yet. Underflow is handled.
1200    Maximal relative error is ~7e-6 for single-precision input */
1201 CVAPI(void)  cvExp( const CvArr* src, CvArr* dst );
1202 
1203 /** Calculates natural logarithms: dst(idx) = log(abs(src(idx))).
1204    Logarithm of 0 gives large negative number(~-700)
1205    Maximal relative error is ~3e-7 for single-precision output
1206 */
1207 CVAPI(void)  cvLog( const CvArr* src, CvArr* dst );
1208 
1209 /** Fast arctangent calculation */
1210 CVAPI(float) cvFastArctan( float y, float x );
1211 
1212 /** Fast cubic root calculation */
1213 CVAPI(float)  cvCbrt( float value );
1214 
1215 #define  CV_CHECK_RANGE    1
1216 #define  CV_CHECK_QUIET    2
1217 /** Checks array values for NaNs, Infs or simply for too large numbers
1218    (if CV_CHECK_RANGE is set). If CV_CHECK_QUIET is set,
1219    no runtime errors is raised (function returns zero value in case of "bad" values).
1220    Otherwise cvError is called */
1221 CVAPI(int)  cvCheckArr( const CvArr* arr, int flags CV_DEFAULT(0),
1222                         double min_val CV_DEFAULT(0), double max_val CV_DEFAULT(0));
1223 #define cvCheckArray cvCheckArr
1224 
1225 #define CV_RAND_UNI      0
1226 #define CV_RAND_NORMAL   1
1227 
1228 /** @brief Fills an array with random numbers and updates the RNG state.
1229 
1230 The function fills the destination array with uniformly or normally distributed random numbers.
1231 @param rng CvRNG state initialized by cvRNG
1232 @param arr The destination array
1233 @param dist_type Distribution type
1234 > -   **CV_RAND_UNI** uniform distribution
1235 > -   **CV_RAND_NORMAL** normal or Gaussian distribution
1236 @param param1 The first parameter of the distribution. In the case of a uniform distribution it is
1237 the inclusive lower boundary of the random numbers range. In the case of a normal distribution it
1238 is the mean value of the random numbers.
1239 @param param2 The second parameter of the distribution. In the case of a uniform distribution it
1240 is the exclusive upper boundary of the random numbers range. In the case of a normal distribution
1241 it is the standard deviation of the random numbers.
1242 @sa randu, randn, RNG::fill.
1243  */
1244 CVAPI(void) cvRandArr( CvRNG* rng, CvArr* arr, int dist_type,
1245                       CvScalar param1, CvScalar param2 );
1246 
1247 CVAPI(void) cvRandShuffle( CvArr* mat, CvRNG* rng,
1248                            double iter_factor CV_DEFAULT(1.));
1249 
1250 #define CV_SORT_EVERY_ROW 0
1251 #define CV_SORT_EVERY_COLUMN 1
1252 #define CV_SORT_ASCENDING 0
1253 #define CV_SORT_DESCENDING 16
1254 
1255 CVAPI(void) cvSort( const CvArr* src, CvArr* dst CV_DEFAULT(NULL),
1256                     CvArr* idxmat CV_DEFAULT(NULL),
1257                     int flags CV_DEFAULT(0));
1258 
1259 /** Finds real roots of a cubic equation */
1260 CVAPI(int) cvSolveCubic( const CvMat* coeffs, CvMat* roots );
1261 
1262 /** Finds all real and complex roots of a polynomial equation */
1263 CVAPI(void) cvSolvePoly(const CvMat* coeffs, CvMat *roots2,
1264       int maxiter CV_DEFAULT(20), int fig CV_DEFAULT(100));
1265 
1266 /****************************************************************************************\
1267 *                                Matrix operations                                       *
1268 \****************************************************************************************/
1269 
1270 /** @brief Calculates the cross product of two 3D vectors.
1271 
1272 The function calculates the cross product of two 3D vectors:
1273 \f[\texttt{dst} =  \texttt{src1} \times \texttt{src2}\f]
1274 or:
1275 \f[\begin{array}{l} \texttt{dst} _1 =  \texttt{src1} _2  \texttt{src2} _3 -  \texttt{src1} _3  \texttt{src2} _2 \\ \texttt{dst} _2 =  \texttt{src1} _3  \texttt{src2} _1 -  \texttt{src1} _1  \texttt{src2} _3 \\ \texttt{dst} _3 =  \texttt{src1} _1  \texttt{src2} _2 -  \texttt{src1} _2  \texttt{src2} _1 \end{array}\f]
1276 @param src1 The first source vector
1277 @param src2 The second source vector
1278 @param dst The destination vector
1279  */
1280 CVAPI(void)  cvCrossProduct( const CvArr* src1, const CvArr* src2, CvArr* dst );
1281 
1282 /** Matrix transform: dst = A*B + C, C is optional */
1283 #define cvMatMulAdd( src1, src2, src3, dst ) cvGEMM( (src1), (src2), 1., (src3), 1., (dst), 0 )
1284 #define cvMatMul( src1, src2, dst )  cvMatMulAdd( (src1), (src2), NULL, (dst))
1285 
1286 #define CV_GEMM_A_T 1
1287 #define CV_GEMM_B_T 2
1288 #define CV_GEMM_C_T 4
1289 /** Extended matrix transform:
1290    dst = alpha*op(A)*op(B) + beta*op(C), where op(X) is X or X^T */
1291 CVAPI(void)  cvGEMM( const CvArr* src1, const CvArr* src2, double alpha,
1292                      const CvArr* src3, double beta, CvArr* dst,
1293                      int tABC CV_DEFAULT(0));
1294 #define cvMatMulAddEx cvGEMM
1295 
1296 /** Transforms each element of source array and stores
1297    resultant vectors in destination array */
1298 CVAPI(void)  cvTransform( const CvArr* src, CvArr* dst,
1299                           const CvMat* transmat,
1300                           const CvMat* shiftvec CV_DEFAULT(NULL));
1301 #define cvMatMulAddS cvTransform
1302 
1303 /** Does perspective transform on every element of input array */
1304 CVAPI(void)  cvPerspectiveTransform( const CvArr* src, CvArr* dst,
1305                                      const CvMat* mat );
1306 
1307 /** Calculates (A-delta)*(A-delta)^T (order=0) or (A-delta)^T*(A-delta) (order=1) */
1308 CVAPI(void) cvMulTransposed( const CvArr* src, CvArr* dst, int order,
1309                              const CvArr* delta CV_DEFAULT(NULL),
1310                              double scale CV_DEFAULT(1.) );
1311 
1312 /** Transposes matrix. Square matrices can be transposed in-place */
1313 CVAPI(void)  cvTranspose( const CvArr* src, CvArr* dst );
1314 #define cvT cvTranspose
1315 
1316 /** Completes the symmetric matrix from the lower (LtoR=0) or from the upper (LtoR!=0) part */
1317 CVAPI(void)  cvCompleteSymm( CvMat* matrix, int LtoR CV_DEFAULT(0) );
1318 
1319 /** Mirror array data around horizontal (flip=0),
1320    vertical (flip=1) or both(flip=-1) axises:
1321    cvFlip(src) flips images vertically and sequences horizontally (inplace) */
1322 CVAPI(void)  cvFlip( const CvArr* src, CvArr* dst CV_DEFAULT(NULL),
1323                      int flip_mode CV_DEFAULT(0));
1324 #define cvMirror cvFlip
1325 
1326 
1327 #define CV_SVD_MODIFY_A   1
1328 #define CV_SVD_U_T        2
1329 #define CV_SVD_V_T        4
1330 
1331 /** Performs Singular Value Decomposition of a matrix */
1332 CVAPI(void)   cvSVD( CvArr* A, CvArr* W, CvArr* U CV_DEFAULT(NULL),
1333                      CvArr* V CV_DEFAULT(NULL), int flags CV_DEFAULT(0));
1334 
1335 /** Performs Singular Value Back Substitution (solves A*X = B):
1336    flags must be the same as in cvSVD */
1337 CVAPI(void)   cvSVBkSb( const CvArr* W, const CvArr* U,
1338                         const CvArr* V, const CvArr* B,
1339                         CvArr* X, int flags );
1340 
1341 #define CV_LU  0
1342 #define CV_SVD 1
1343 #define CV_SVD_SYM 2
1344 #define CV_CHOLESKY 3
1345 #define CV_QR  4
1346 #define CV_NORMAL 16
1347 
1348 /** Inverts matrix */
1349 CVAPI(double)  cvInvert( const CvArr* src, CvArr* dst,
1350                          int method CV_DEFAULT(CV_LU));
1351 #define cvInv cvInvert
1352 
1353 /** Solves linear system (src1)*(dst) = (src2)
1354    (returns 0 if src1 is a singular and CV_LU method is used) */
1355 CVAPI(int)  cvSolve( const CvArr* src1, const CvArr* src2, CvArr* dst,
1356                      int method CV_DEFAULT(CV_LU));
1357 
1358 /** Calculates determinant of input matrix */
1359 CVAPI(double) cvDet( const CvArr* mat );
1360 
1361 /** Calculates trace of the matrix (sum of elements on the main diagonal) */
1362 CVAPI(CvScalar) cvTrace( const CvArr* mat );
1363 
1364 /** Finds eigen values and vectors of a symmetric matrix */
1365 CVAPI(void)  cvEigenVV( CvArr* mat, CvArr* evects, CvArr* evals,
1366                         double eps CV_DEFAULT(0),
1367                         int lowindex CV_DEFAULT(-1),
1368                         int highindex CV_DEFAULT(-1));
1369 
1370 ///* Finds selected eigen values and vectors of a symmetric matrix */
1371 //CVAPI(void)  cvSelectedEigenVV( CvArr* mat, CvArr* evects, CvArr* evals,
1372 //                                int lowindex, int highindex );
1373 
1374 /** Makes an identity matrix (mat_ij = i == j) */
1375 CVAPI(void)  cvSetIdentity( CvArr* mat, CvScalar value CV_DEFAULT(cvRealScalar(1)) );
1376 
1377 /** Fills matrix with given range of numbers */
1378 CVAPI(CvArr*)  cvRange( CvArr* mat, double start, double end );
1379 
1380 /**   @anchor core_c_CovarFlags
1381 @name Flags for cvCalcCovarMatrix
1382 @see cvCalcCovarMatrix
1383   @{
1384 */
1385 
1386 /** flag for cvCalcCovarMatrix, transpose([v1-avg, v2-avg,...]) * [v1-avg,v2-avg,...] */
1387 #define CV_COVAR_SCRAMBLED 0
1388 
1389 /** flag for cvCalcCovarMatrix, [v1-avg, v2-avg,...] * transpose([v1-avg,v2-avg,...]) */
1390 #define CV_COVAR_NORMAL    1
1391 
1392 /** flag for cvCalcCovarMatrix, do not calc average (i.e. mean vector) - use the input vector instead
1393    (useful for calculating covariance matrix by parts) */
1394 #define CV_COVAR_USE_AVG   2
1395 
1396 /** flag for cvCalcCovarMatrix, scale the covariance matrix coefficients by number of the vectors */
1397 #define CV_COVAR_SCALE     4
1398 
1399 /** flag for cvCalcCovarMatrix, all the input vectors are stored in a single matrix, as its rows */
1400 #define CV_COVAR_ROWS      8
1401 
1402 /** flag for cvCalcCovarMatrix, all the input vectors are stored in a single matrix, as its columns */
1403 #define CV_COVAR_COLS     16
1404 
1405 /** @} */
1406 
1407 /** Calculates covariation matrix for a set of vectors
1408 @see @ref core_c_CovarFlags "flags"
1409 */
1410 CVAPI(void)  cvCalcCovarMatrix( const CvArr** vects, int count,
1411                                 CvArr* cov_mat, CvArr* avg, int flags );
1412 
1413 #define CV_PCA_DATA_AS_ROW 0
1414 #define CV_PCA_DATA_AS_COL 1
1415 #define CV_PCA_USE_AVG 2
1416 CVAPI(void)  cvCalcPCA( const CvArr* data, CvArr* mean,
1417                         CvArr* eigenvals, CvArr* eigenvects, int flags );
1418 
1419 CVAPI(void)  cvProjectPCA( const CvArr* data, const CvArr* mean,
1420                            const CvArr* eigenvects, CvArr* result );
1421 
1422 CVAPI(void)  cvBackProjectPCA( const CvArr* proj, const CvArr* mean,
1423                                const CvArr* eigenvects, CvArr* result );
1424 
1425 /** Calculates Mahalanobis(weighted) distance */
1426 CVAPI(double)  cvMahalanobis( const CvArr* vec1, const CvArr* vec2, const CvArr* mat );
1427 #define cvMahalonobis  cvMahalanobis
1428 
1429 /****************************************************************************************\
1430 *                                    Array Statistics                                    *
1431 \****************************************************************************************/
1432 
1433 /** Finds sum of array elements */
1434 CVAPI(CvScalar)  cvSum( const CvArr* arr );
1435 
1436 /** Calculates number of non-zero pixels */
1437 CVAPI(int)  cvCountNonZero( const CvArr* arr );
1438 
1439 /** Calculates mean value of array elements */
1440 CVAPI(CvScalar)  cvAvg( const CvArr* arr, const CvArr* mask CV_DEFAULT(NULL) );
1441 
1442 /** Calculates mean and standard deviation of pixel values */
1443 CVAPI(void)  cvAvgSdv( const CvArr* arr, CvScalar* mean, CvScalar* std_dev,
1444                        const CvArr* mask CV_DEFAULT(NULL) );
1445 
1446 /** Finds global minimum, maximum and their positions */
1447 CVAPI(void)  cvMinMaxLoc( const CvArr* arr, double* min_val, double* max_val,
1448                           CvPoint* min_loc CV_DEFAULT(NULL),
1449                           CvPoint* max_loc CV_DEFAULT(NULL),
1450                           const CvArr* mask CV_DEFAULT(NULL) );
1451 
1452 /** @anchor core_c_NormFlags
1453   @name Flags for cvNorm and cvNormalize
1454   @{
1455 */
1456 #define CV_C            1
1457 #define CV_L1           2
1458 #define CV_L2           4
1459 #define CV_NORM_MASK    7
1460 #define CV_RELATIVE     8
1461 #define CV_DIFF         16
1462 #define CV_MINMAX       32
1463 
1464 #define CV_DIFF_C       (CV_DIFF | CV_C)
1465 #define CV_DIFF_L1      (CV_DIFF | CV_L1)
1466 #define CV_DIFF_L2      (CV_DIFF | CV_L2)
1467 #define CV_RELATIVE_C   (CV_RELATIVE | CV_C)
1468 #define CV_RELATIVE_L1  (CV_RELATIVE | CV_L1)
1469 #define CV_RELATIVE_L2  (CV_RELATIVE | CV_L2)
1470 /** @} */
1471 
1472 /** Finds norm, difference norm or relative difference norm for an array (or two arrays)
1473 @see ref core_c_NormFlags "flags"
1474 */
1475 CVAPI(double)  cvNorm( const CvArr* arr1, const CvArr* arr2 CV_DEFAULT(NULL),
1476                        int norm_type CV_DEFAULT(CV_L2),
1477                        const CvArr* mask CV_DEFAULT(NULL) );
1478 
1479 /** @see ref core_c_NormFlags "flags" */
1480 CVAPI(void)  cvNormalize( const CvArr* src, CvArr* dst,
1481                           double a CV_DEFAULT(1.), double b CV_DEFAULT(0.),
1482                           int norm_type CV_DEFAULT(CV_L2),
1483                           const CvArr* mask CV_DEFAULT(NULL) );
1484 
1485 /** @anchor core_c_ReduceFlags
1486   @name Flags for cvReduce
1487   @{
1488 */
1489 #define CV_REDUCE_SUM 0
1490 #define CV_REDUCE_AVG 1
1491 #define CV_REDUCE_MAX 2
1492 #define CV_REDUCE_MIN 3
1493 /** @} */
1494 
1495 /** @see @ref core_c_ReduceFlags "flags" */
1496 CVAPI(void)  cvReduce( const CvArr* src, CvArr* dst, int dim CV_DEFAULT(-1),
1497                        int op CV_DEFAULT(CV_REDUCE_SUM) );
1498 
1499 /****************************************************************************************\
1500 *                      Discrete Linear Transforms and Related Functions                  *
1501 \****************************************************************************************/
1502 
1503 /** @anchor core_c_DftFlags
1504   @name Flags for cvDFT, cvDCT and cvMulSpectrums
1505   @{
1506   */
1507 #define CV_DXT_FORWARD  0
1508 #define CV_DXT_INVERSE  1
1509 #define CV_DXT_SCALE    2 /**< divide result by size of array */
1510 #define CV_DXT_INV_SCALE (CV_DXT_INVERSE + CV_DXT_SCALE)
1511 #define CV_DXT_INVERSE_SCALE CV_DXT_INV_SCALE
1512 #define CV_DXT_ROWS     4 /**< transform each row individually */
1513 #define CV_DXT_MUL_CONJ 8 /**< conjugate the second argument of cvMulSpectrums */
1514 /** @} */
1515 
1516 /** Discrete Fourier Transform:
1517     complex->complex,
1518     real->ccs (forward),
1519     ccs->real (inverse)
1520 @see core_c_DftFlags "flags"
1521 */
1522 CVAPI(void)  cvDFT( const CvArr* src, CvArr* dst, int flags,
1523                     int nonzero_rows CV_DEFAULT(0) );
1524 #define cvFFT cvDFT
1525 
1526 /** Multiply results of DFTs: DFT(X)*DFT(Y) or DFT(X)*conj(DFT(Y))
1527 @see core_c_DftFlags "flags"
1528 */
1529 CVAPI(void)  cvMulSpectrums( const CvArr* src1, const CvArr* src2,
1530                              CvArr* dst, int flags );
1531 
1532 /** Finds optimal DFT vector size >= size0 */
1533 CVAPI(int)  cvGetOptimalDFTSize( int size0 );
1534 
1535 /** Discrete Cosine Transform
1536 @see core_c_DftFlags "flags"
1537 */
1538 CVAPI(void)  cvDCT( const CvArr* src, CvArr* dst, int flags );
1539 
1540 /****************************************************************************************\
1541 *                              Dynamic data structures                                   *
1542 \****************************************************************************************/
1543 
1544 /** Calculates length of sequence slice (with support of negative indices). */
1545 CVAPI(int) cvSliceLength( CvSlice slice, const CvSeq* seq );
1546 
1547 
1548 /** Creates new memory storage.
1549    block_size == 0 means that default,
1550    somewhat optimal size, is used (currently, it is 64K) */
1551 CVAPI(CvMemStorage*)  cvCreateMemStorage( int block_size CV_DEFAULT(0));
1552 
1553 
1554 /** Creates a memory storage that will borrow memory blocks from parent storage */
1555 CVAPI(CvMemStorage*)  cvCreateChildMemStorage( CvMemStorage* parent );
1556 
1557 
1558 /** Releases memory storage. All the children of a parent must be released before
1559    the parent. A child storage returns all the blocks to parent when it is released */
1560 CVAPI(void)  cvReleaseMemStorage( CvMemStorage** storage );
1561 
1562 
1563 /** Clears memory storage. This is the only way(!!!) (besides cvRestoreMemStoragePos)
1564    to reuse memory allocated for the storage - cvClearSeq,cvClearSet ...
1565    do not free any memory.
1566    A child storage returns all the blocks to the parent when it is cleared */
1567 CVAPI(void)  cvClearMemStorage( CvMemStorage* storage );
1568 
1569 /** Remember a storage "free memory" position */
1570 CVAPI(void)  cvSaveMemStoragePos( const CvMemStorage* storage, CvMemStoragePos* pos );
1571 
1572 /** Restore a storage "free memory" position */
1573 CVAPI(void)  cvRestoreMemStoragePos( CvMemStorage* storage, CvMemStoragePos* pos );
1574 
1575 /** Allocates continuous buffer of the specified size in the storage */
1576 CVAPI(void*) cvMemStorageAlloc( CvMemStorage* storage, size_t size );
1577 
1578 /** Allocates string in memory storage */
1579 //CVAPI(CvString) cvMemStorageAllocString( CvMemStorage* storage, const char* ptr,
1580 //                                         int len CV_DEFAULT(-1) );
1581 
1582 /** Creates new empty sequence that will reside in the specified storage */
1583 CVAPI(CvSeq*)  cvCreateSeq( int seq_flags, size_t header_size,
1584                             size_t elem_size, CvMemStorage* storage );
1585 
1586 /** Changes default size (granularity) of sequence blocks.
1587    The default size is ~1Kbyte */
1588 CVAPI(void)  cvSetSeqBlockSize( CvSeq* seq, int delta_elems );
1589 
1590 
1591 /** Adds new element to the end of sequence. Returns pointer to the element */
1592 CVAPI(schar*)  cvSeqPush( CvSeq* seq, const void* element CV_DEFAULT(NULL));
1593 
1594 
1595 /** Adds new element to the beginning of sequence. Returns pointer to it */
1596 CVAPI(schar*)  cvSeqPushFront( CvSeq* seq, const void* element CV_DEFAULT(NULL));
1597 
1598 
1599 /** Removes the last element from sequence and optionally saves it */
1600 CVAPI(void)  cvSeqPop( CvSeq* seq, void* element CV_DEFAULT(NULL));
1601 
1602 
1603 /** Removes the first element from sequence and optioanally saves it */
1604 CVAPI(void)  cvSeqPopFront( CvSeq* seq, void* element CV_DEFAULT(NULL));
1605 
1606 
1607 #define CV_FRONT 1
1608 #define CV_BACK 0
1609 /** Adds several new elements to the end of sequence */
1610 CVAPI(void)  cvSeqPushMulti( CvSeq* seq, const void* elements,
1611                              int count, int in_front CV_DEFAULT(0) );
1612 
1613 /** Removes several elements from the end of sequence and optionally saves them */
1614 CVAPI(void)  cvSeqPopMulti( CvSeq* seq, void* elements,
1615                             int count, int in_front CV_DEFAULT(0) );
1616 
1617 /** Inserts a new element in the middle of sequence.
1618    cvSeqInsert(seq,0,elem) == cvSeqPushFront(seq,elem) */
1619 CVAPI(schar*)  cvSeqInsert( CvSeq* seq, int before_index,
1620                             const void* element CV_DEFAULT(NULL));
1621 
1622 /** Removes specified sequence element */
1623 CVAPI(void)  cvSeqRemove( CvSeq* seq, int index );
1624 
1625 
1626 /** Removes all the elements from the sequence. The freed memory
1627    can be reused later only by the same sequence unless cvClearMemStorage
1628    or cvRestoreMemStoragePos is called */
1629 CVAPI(void)  cvClearSeq( CvSeq* seq );
1630 
1631 
1632 /** Retrieves pointer to specified sequence element.
1633    Negative indices are supported and mean counting from the end
1634    (e.g -1 means the last sequence element) */
1635 CVAPI(schar*)  cvGetSeqElem( const CvSeq* seq, int index );
1636 
1637 /** Calculates index of the specified sequence element.
1638    Returns -1 if element does not belong to the sequence */
1639 CVAPI(int)  cvSeqElemIdx( const CvSeq* seq, const void* element,
1640                          CvSeqBlock** block CV_DEFAULT(NULL) );
1641 
1642 /** Initializes sequence writer. The new elements will be added to the end of sequence */
1643 CVAPI(void)  cvStartAppendToSeq( CvSeq* seq, CvSeqWriter* writer );
1644 
1645 
1646 /** Combination of cvCreateSeq and cvStartAppendToSeq */
1647 CVAPI(void)  cvStartWriteSeq( int seq_flags, int header_size,
1648                               int elem_size, CvMemStorage* storage,
1649                               CvSeqWriter* writer );
1650 
1651 /** Closes sequence writer, updates sequence header and returns pointer
1652    to the resultant sequence
1653    (which may be useful if the sequence was created using cvStartWriteSeq))
1654 */
1655 CVAPI(CvSeq*)  cvEndWriteSeq( CvSeqWriter* writer );
1656 
1657 
1658 /** Updates sequence header. May be useful to get access to some of previously
1659    written elements via cvGetSeqElem or sequence reader */
1660 CVAPI(void)   cvFlushSeqWriter( CvSeqWriter* writer );
1661 
1662 
1663 /** Initializes sequence reader.
1664    The sequence can be read in forward or backward direction */
1665 CVAPI(void) cvStartReadSeq( const CvSeq* seq, CvSeqReader* reader,
1666                            int reverse CV_DEFAULT(0) );
1667 
1668 
1669 /** Returns current sequence reader position (currently observed sequence element) */
1670 CVAPI(int)  cvGetSeqReaderPos( CvSeqReader* reader );
1671 
1672 
1673 /** Changes sequence reader position. It may seek to an absolute or
1674    to relative to the current position */
1675 CVAPI(void)   cvSetSeqReaderPos( CvSeqReader* reader, int index,
1676                                  int is_relative CV_DEFAULT(0));
1677 
1678 /** Copies sequence content to a continuous piece of memory */
1679 CVAPI(void*)  cvCvtSeqToArray( const CvSeq* seq, void* elements,
1680                                CvSlice slice CV_DEFAULT(CV_WHOLE_SEQ) );
1681 
1682 /** Creates sequence header for array.
1683    After that all the operations on sequences that do not alter the content
1684    can be applied to the resultant sequence */
1685 CVAPI(CvSeq*) cvMakeSeqHeaderForArray( int seq_type, int header_size,
1686                                        int elem_size, void* elements, int total,
1687                                        CvSeq* seq, CvSeqBlock* block );
1688 
1689 /** Extracts sequence slice (with or without copying sequence elements) */
1690 CVAPI(CvSeq*) cvSeqSlice( const CvSeq* seq, CvSlice slice,
1691                          CvMemStorage* storage CV_DEFAULT(NULL),
1692                          int copy_data CV_DEFAULT(0));
1693 
cvCloneSeq(const CvSeq * seq,CvMemStorage * storage CV_DEFAULT (NULL))1694 CV_INLINE CvSeq* cvCloneSeq( const CvSeq* seq, CvMemStorage* storage CV_DEFAULT(NULL))
1695 {
1696     return cvSeqSlice( seq, CV_WHOLE_SEQ, storage, 1 );
1697 }
1698 
1699 /** Removes sequence slice */
1700 CVAPI(void)  cvSeqRemoveSlice( CvSeq* seq, CvSlice slice );
1701 
1702 /** Inserts a sequence or array into another sequence */
1703 CVAPI(void)  cvSeqInsertSlice( CvSeq* seq, int before_index, const CvArr* from_arr );
1704 
1705 /** a < b ? -1 : a > b ? 1 : 0 */
1706 typedef int (CV_CDECL* CvCmpFunc)(const void* a, const void* b, void* userdata );
1707 
1708 /** Sorts sequence in-place given element comparison function */
1709 CVAPI(void) cvSeqSort( CvSeq* seq, CvCmpFunc func, void* userdata CV_DEFAULT(NULL) );
1710 
1711 /** Finds element in a [sorted] sequence */
1712 CVAPI(schar*) cvSeqSearch( CvSeq* seq, const void* elem, CvCmpFunc func,
1713                            int is_sorted, int* elem_idx,
1714                            void* userdata CV_DEFAULT(NULL) );
1715 
1716 /** Reverses order of sequence elements in-place */
1717 CVAPI(void) cvSeqInvert( CvSeq* seq );
1718 
1719 /** Splits sequence into one or more equivalence classes using the specified criteria */
1720 CVAPI(int)  cvSeqPartition( const CvSeq* seq, CvMemStorage* storage,
1721                             CvSeq** labels, CvCmpFunc is_equal, void* userdata );
1722 
1723 /************ Internal sequence functions ************/
1724 CVAPI(void)  cvChangeSeqBlock( void* reader, int direction );
1725 CVAPI(void)  cvCreateSeqBlock( CvSeqWriter* writer );
1726 
1727 
1728 /** Creates a new set */
1729 CVAPI(CvSet*)  cvCreateSet( int set_flags, int header_size,
1730                             int elem_size, CvMemStorage* storage );
1731 
1732 /** Adds new element to the set and returns pointer to it */
1733 CVAPI(int)  cvSetAdd( CvSet* set_header, CvSetElem* elem CV_DEFAULT(NULL),
1734                       CvSetElem** inserted_elem CV_DEFAULT(NULL) );
1735 
1736 /** Fast variant of cvSetAdd */
cvSetNew(CvSet * set_header)1737 CV_INLINE  CvSetElem* cvSetNew( CvSet* set_header )
1738 {
1739     CvSetElem* elem = set_header->free_elems;
1740     if( elem )
1741     {
1742         set_header->free_elems = elem->next_free;
1743         elem->flags = elem->flags & CV_SET_ELEM_IDX_MASK;
1744         set_header->active_count++;
1745     }
1746     else
1747         cvSetAdd( set_header, NULL, &elem );
1748     return elem;
1749 }
1750 
1751 /** Removes set element given its pointer */
cvSetRemoveByPtr(CvSet * set_header,void * elem)1752 CV_INLINE  void cvSetRemoveByPtr( CvSet* set_header, void* elem )
1753 {
1754     CvSetElem* _elem = (CvSetElem*)elem;
1755     assert( _elem->flags >= 0 /*&& (elem->flags & CV_SET_ELEM_IDX_MASK) < set_header->total*/ );
1756     _elem->next_free = set_header->free_elems;
1757     _elem->flags = (_elem->flags & CV_SET_ELEM_IDX_MASK) | CV_SET_ELEM_FREE_FLAG;
1758     set_header->free_elems = _elem;
1759     set_header->active_count--;
1760 }
1761 
1762 /** Removes element from the set by its index  */
1763 CVAPI(void)   cvSetRemove( CvSet* set_header, int index );
1764 
1765 /** Returns a set element by index. If the element doesn't belong to the set,
1766    NULL is returned */
cvGetSetElem(const CvSet * set_header,int idx)1767 CV_INLINE CvSetElem* cvGetSetElem( const CvSet* set_header, int idx )
1768 {
1769     CvSetElem* elem = (CvSetElem*)(void *)cvGetSeqElem( (CvSeq*)set_header, idx );
1770     return elem && CV_IS_SET_ELEM( elem ) ? elem : 0;
1771 }
1772 
1773 /** Removes all the elements from the set */
1774 CVAPI(void)  cvClearSet( CvSet* set_header );
1775 
1776 /** Creates new graph */
1777 CVAPI(CvGraph*)  cvCreateGraph( int graph_flags, int header_size,
1778                                 int vtx_size, int edge_size,
1779                                 CvMemStorage* storage );
1780 
1781 /** Adds new vertex to the graph */
1782 CVAPI(int)  cvGraphAddVtx( CvGraph* graph, const CvGraphVtx* vtx CV_DEFAULT(NULL),
1783                            CvGraphVtx** inserted_vtx CV_DEFAULT(NULL) );
1784 
1785 
1786 /** Removes vertex from the graph together with all incident edges */
1787 CVAPI(int)  cvGraphRemoveVtx( CvGraph* graph, int index );
1788 CVAPI(int)  cvGraphRemoveVtxByPtr( CvGraph* graph, CvGraphVtx* vtx );
1789 
1790 
1791 /** Link two vertices specified by indices or pointers if they
1792    are not connected or return pointer to already existing edge
1793    connecting the vertices.
1794    Functions return 1 if a new edge was created, 0 otherwise */
1795 CVAPI(int)  cvGraphAddEdge( CvGraph* graph,
1796                             int start_idx, int end_idx,
1797                             const CvGraphEdge* edge CV_DEFAULT(NULL),
1798                             CvGraphEdge** inserted_edge CV_DEFAULT(NULL) );
1799 
1800 CVAPI(int)  cvGraphAddEdgeByPtr( CvGraph* graph,
1801                                CvGraphVtx* start_vtx, CvGraphVtx* end_vtx,
1802                                const CvGraphEdge* edge CV_DEFAULT(NULL),
1803                                CvGraphEdge** inserted_edge CV_DEFAULT(NULL) );
1804 
1805 /** Remove edge connecting two vertices */
1806 CVAPI(void)  cvGraphRemoveEdge( CvGraph* graph, int start_idx, int end_idx );
1807 CVAPI(void)  cvGraphRemoveEdgeByPtr( CvGraph* graph, CvGraphVtx* start_vtx,
1808                                      CvGraphVtx* end_vtx );
1809 
1810 /** Find edge connecting two vertices */
1811 CVAPI(CvGraphEdge*)  cvFindGraphEdge( const CvGraph* graph, int start_idx, int end_idx );
1812 CVAPI(CvGraphEdge*)  cvFindGraphEdgeByPtr( const CvGraph* graph,
1813                                            const CvGraphVtx* start_vtx,
1814                                            const CvGraphVtx* end_vtx );
1815 #define cvGraphFindEdge cvFindGraphEdge
1816 #define cvGraphFindEdgeByPtr cvFindGraphEdgeByPtr
1817 
1818 /** Remove all vertices and edges from the graph */
1819 CVAPI(void)  cvClearGraph( CvGraph* graph );
1820 
1821 
1822 /** Count number of edges incident to the vertex */
1823 CVAPI(int)  cvGraphVtxDegree( const CvGraph* graph, int vtx_idx );
1824 CVAPI(int)  cvGraphVtxDegreeByPtr( const CvGraph* graph, const CvGraphVtx* vtx );
1825 
1826 
1827 /** Retrieves graph vertex by given index */
1828 #define cvGetGraphVtx( graph, idx ) (CvGraphVtx*)cvGetSetElem((CvSet*)(graph), (idx))
1829 
1830 /** Retrieves index of a graph vertex given its pointer */
1831 #define cvGraphVtxIdx( graph, vtx ) ((vtx)->flags & CV_SET_ELEM_IDX_MASK)
1832 
1833 /** Retrieves index of a graph edge given its pointer */
1834 #define cvGraphEdgeIdx( graph, edge ) ((edge)->flags & CV_SET_ELEM_IDX_MASK)
1835 
1836 #define cvGraphGetVtxCount( graph ) ((graph)->active_count)
1837 #define cvGraphGetEdgeCount( graph ) ((graph)->edges->active_count)
1838 
1839 #define  CV_GRAPH_VERTEX        1
1840 #define  CV_GRAPH_TREE_EDGE     2
1841 #define  CV_GRAPH_BACK_EDGE     4
1842 #define  CV_GRAPH_FORWARD_EDGE  8
1843 #define  CV_GRAPH_CROSS_EDGE    16
1844 #define  CV_GRAPH_ANY_EDGE      30
1845 #define  CV_GRAPH_NEW_TREE      32
1846 #define  CV_GRAPH_BACKTRACKING  64
1847 #define  CV_GRAPH_OVER          -1
1848 
1849 #define  CV_GRAPH_ALL_ITEMS    -1
1850 
1851 /** flags for graph vertices and edges */
1852 #define  CV_GRAPH_ITEM_VISITED_FLAG  (1 << 30)
1853 #define  CV_IS_GRAPH_VERTEX_VISITED(vtx) \
1854     (((CvGraphVtx*)(vtx))->flags & CV_GRAPH_ITEM_VISITED_FLAG)
1855 #define  CV_IS_GRAPH_EDGE_VISITED(edge) \
1856     (((CvGraphEdge*)(edge))->flags & CV_GRAPH_ITEM_VISITED_FLAG)
1857 #define  CV_GRAPH_SEARCH_TREE_NODE_FLAG   (1 << 29)
1858 #define  CV_GRAPH_FORWARD_EDGE_FLAG       (1 << 28)
1859 
1860 typedef struct CvGraphScanner
1861 {
1862     CvGraphVtx* vtx;       /* current graph vertex (or current edge origin) */
1863     CvGraphVtx* dst;       /* current graph edge destination vertex */
1864     CvGraphEdge* edge;     /* current edge */
1865 
1866     CvGraph* graph;        /* the graph */
1867     CvSeq*   stack;        /* the graph vertex stack */
1868     int      index;        /* the lower bound of certainly visited vertices */
1869     int      mask;         /* event mask */
1870 }
1871 CvGraphScanner;
1872 
1873 /** Creates new graph scanner. */
1874 CVAPI(CvGraphScanner*)  cvCreateGraphScanner( CvGraph* graph,
1875                                              CvGraphVtx* vtx CV_DEFAULT(NULL),
1876                                              int mask CV_DEFAULT(CV_GRAPH_ALL_ITEMS));
1877 
1878 /** Releases graph scanner. */
1879 CVAPI(void) cvReleaseGraphScanner( CvGraphScanner** scanner );
1880 
1881 /** Get next graph element */
1882 CVAPI(int)  cvNextGraphItem( CvGraphScanner* scanner );
1883 
1884 /** Creates a copy of graph */
1885 CVAPI(CvGraph*) cvCloneGraph( const CvGraph* graph, CvMemStorage* storage );
1886 
1887 
1888 /** Does look-up transformation. Elements of the source array
1889    (that should be 8uC1 or 8sC1) are used as indexes in lutarr 256-element table */
1890 CVAPI(void) cvLUT( const CvArr* src, CvArr* dst, const CvArr* lut );
1891 
1892 
1893 /******************* Iteration through the sequence tree *****************/
1894 typedef struct CvTreeNodeIterator
1895 {
1896     const void* node;
1897     int level;
1898     int max_level;
1899 }
1900 CvTreeNodeIterator;
1901 
1902 CVAPI(void) cvInitTreeNodeIterator( CvTreeNodeIterator* tree_iterator,
1903                                    const void* first, int max_level );
1904 CVAPI(void*) cvNextTreeNode( CvTreeNodeIterator* tree_iterator );
1905 CVAPI(void*) cvPrevTreeNode( CvTreeNodeIterator* tree_iterator );
1906 
1907 /** Inserts sequence into tree with specified "parent" sequence.
1908    If parent is equal to frame (e.g. the most external contour),
1909    then added contour will have null pointer to parent. */
1910 CVAPI(void) cvInsertNodeIntoTree( void* node, void* parent, void* frame );
1911 
1912 /** Removes contour from tree (together with the contour children). */
1913 CVAPI(void) cvRemoveNodeFromTree( void* node, void* frame );
1914 
1915 /** Gathers pointers to all the sequences,
1916    accessible from the `first`, to the single sequence */
1917 CVAPI(CvSeq*) cvTreeToNodeSeq( const void* first, int header_size,
1918                               CvMemStorage* storage );
1919 
1920 /** The function implements the K-means algorithm for clustering an array of sample
1921    vectors in a specified number of classes */
1922 #define CV_KMEANS_USE_INITIAL_LABELS    1
1923 CVAPI(int) cvKMeans2( const CvArr* samples, int cluster_count, CvArr* labels,
1924                       CvTermCriteria termcrit, int attempts CV_DEFAULT(1),
1925                       CvRNG* rng CV_DEFAULT(0), int flags CV_DEFAULT(0),
1926                       CvArr* _centers CV_DEFAULT(0), double* compactness CV_DEFAULT(0) );
1927 
1928 /****************************************************************************************\
1929 *                                    System functions                                    *
1930 \****************************************************************************************/
1931 
1932 /** Loads optimized functions from IPP, MKL etc. or switches back to pure C code */
1933 CVAPI(int)  cvUseOptimized( int on_off );
1934 
1935 typedef IplImage* (CV_STDCALL* Cv_iplCreateImageHeader)
1936                             (int,int,int,char*,char*,int,int,int,int,int,
1937                             IplROI*,IplImage*,void*,IplTileInfo*);
1938 typedef void (CV_STDCALL* Cv_iplAllocateImageData)(IplImage*,int,int);
1939 typedef void (CV_STDCALL* Cv_iplDeallocate)(IplImage*,int);
1940 typedef IplROI* (CV_STDCALL* Cv_iplCreateROI)(int,int,int,int,int);
1941 typedef IplImage* (CV_STDCALL* Cv_iplCloneImage)(const IplImage*);
1942 
1943 /** @brief Makes OpenCV use IPL functions for allocating IplImage and IplROI structures.
1944 
1945 Normally, the function is not called directly. Instead, a simple macro
1946 CV_TURN_ON_IPL_COMPATIBILITY() is used that calls cvSetIPLAllocators and passes there pointers
1947 to IPL allocation functions. :
1948 @code
1949     ...
1950     CV_TURN_ON_IPL_COMPATIBILITY()
1951     ...
1952 @endcode
1953 @param create_header pointer to a function, creating IPL image header.
1954 @param allocate_data pointer to a function, allocating IPL image data.
1955 @param deallocate pointer to a function, deallocating IPL image.
1956 @param create_roi pointer to a function, creating IPL image ROI (i.e. Region of Interest).
1957 @param clone_image pointer to a function, cloning an IPL image.
1958  */
1959 CVAPI(void) cvSetIPLAllocators( Cv_iplCreateImageHeader create_header,
1960                                Cv_iplAllocateImageData allocate_data,
1961                                Cv_iplDeallocate deallocate,
1962                                Cv_iplCreateROI create_roi,
1963                                Cv_iplCloneImage clone_image );
1964 
1965 #define CV_TURN_ON_IPL_COMPATIBILITY()                                  \
1966     cvSetIPLAllocators( iplCreateImageHeader, iplAllocateImage,         \
1967                         iplDeallocate, iplCreateROI, iplCloneImage )
1968 
1969 /****************************************************************************************\
1970 *                                    Data Persistence                                    *
1971 \****************************************************************************************/
1972 
1973 #if 0
1974 /********************************** High-level functions ********************************/
1975 
1976 /** @brief Opens file storage for reading or writing data.
1977 
1978 The function opens file storage for reading or writing data. In the latter case, a new file is
1979 created or an existing file is rewritten. The type of the read or written file is determined by the
1980 filename extension: .xml for XML, .yml or .yaml for YAML and .json for JSON.
1981 
1982 At the same time, it also supports adding parameters like "example.xml?base64".
1983 
1984 The function returns a pointer to the CvFileStorage structure.
1985 If the file cannot be opened then the function returns NULL.
1986 @param filename Name of the file associated with the storage
1987 @param memstorage Memory storage used for temporary data and for
1988 :   storing dynamic structures, such as CvSeq or CvGraph . If it is NULL, a temporary memory
1989     storage is created and used.
1990 @param flags Can be one of the following:
1991 > -   **CV_STORAGE_READ** the storage is open for reading
1992 > -   **CV_STORAGE_WRITE** the storage is open for writing
1993       (use **CV_STORAGE_WRITE | CV_STORAGE_WRITE_BASE64** to write rawdata in Base64)
1994 @param encoding
1995  */
1996 CVAPI(CvFileStorage*)  cvOpenFileStorage( const char* filename, CvMemStorage* memstorage,
1997                                           int flags, const char* encoding CV_DEFAULT(NULL) );
1998 
1999 /** @brief Releases file storage.
2000 
2001 The function closes the file associated with the storage and releases all the temporary structures.
2002 It must be called after all I/O operations with the storage are finished.
2003 @param fs Double pointer to the released file storage
2004  */
2005 CVAPI(void) cvReleaseFileStorage( CvFileStorage** fs );
2006 
2007 /** returns attribute value or 0 (NULL) if there is no such attribute */
2008 CVAPI(const char*) cvAttrValue( const CvAttrList* attr, const char* attr_name );
2009 
2010 /** @brief Starts writing a new structure.
2011 
2012 The function starts writing a compound structure (collection) that can be a sequence or a map. After
2013 all the structure fields, which can be scalars or structures, are written, cvEndWriteStruct should
2014 be called. The function can be used to group some objects or to implement the write function for a
2015 some user object (see CvTypeInfo).
2016 @param fs File storage
2017 @param name Name of the written structure. The structure can be accessed by this name when the
2018 storage is read.
2019 @param struct_flags A combination one of the following values:
2020 -   **CV_NODE_SEQ** the written structure is a sequence (see discussion of CvFileStorage ),
2021     that is, its elements do not have a name.
2022 -   **CV_NODE_MAP** the written structure is a map (see discussion of CvFileStorage ), that
2023     is, all its elements have names.
2024 One and only one of the two above flags must be specified
2025 -   **CV_NODE_FLOW** the optional flag that makes sense only for YAML streams. It means that
2026      the structure is written as a flow (not as a block), which is more compact. It is
2027      recommended to use this flag for structures or arrays whose elements are all scalars.
2028 @param type_name Optional parameter - the object type name. In
2029     case of XML it is written as a type_id attribute of the structure opening tag. In the case of
2030     YAML it is written after a colon following the structure name (see the example in
2031     CvFileStorage description). In case of JSON it is written as a name/value pair.
2032     Mainly it is used with user objects. When the storage is read, the
2033     encoded type name is used to determine the object type (see CvTypeInfo and cvFindType ).
2034 @param attributes This parameter is not used in the current implementation
2035  */
2036 CVAPI(void) cvStartWriteStruct( CvFileStorage* fs, const char* name,
2037                                 int struct_flags, const char* type_name CV_DEFAULT(NULL),
2038                                 CvAttrList attributes CV_DEFAULT(cvAttrList()));
2039 
2040 /** @brief Finishes writing to a file node collection.
2041 @param fs File storage
2042 @sa cvStartWriteStruct.
2043  */
2044 CVAPI(void) cvEndWriteStruct( CvFileStorage* fs );
2045 
2046 /** @brief Writes an integer value.
2047 
2048 The function writes a single integer value (with or without a name) to the file storage.
2049 @param fs File storage
2050 @param name Name of the written value. Should be NULL if and only if the parent structure is a
2051 sequence.
2052 @param value The written value
2053  */
2054 CVAPI(void) cvWriteInt( CvFileStorage* fs, const char* name, int value );
2055 
2056 /** @brief Writes a floating-point value.
2057 
2058 The function writes a single floating-point value (with or without a name) to file storage. Special
2059 values are encoded as follows: NaN (Not A Number) as .NaN, infinity as +.Inf or -.Inf.
2060 
2061 The following example shows how to use the low-level writing functions to store custom structures,
2062 such as termination criteria, without registering a new type. :
2063 @code
2064     void write_termcriteria( CvFileStorage* fs, const char* struct_name,
2065                              CvTermCriteria* termcrit )
2066     {
2067         cvStartWriteStruct( fs, struct_name, CV_NODE_MAP, NULL, cvAttrList(0,0));
2068         cvWriteComment( fs, "termination criteria", 1 ); // just a description
2069         if( termcrit->type & CV_TERMCRIT_ITER )
2070             cvWriteInteger( fs, "max_iterations", termcrit->max_iter );
2071         if( termcrit->type & CV_TERMCRIT_EPS )
2072             cvWriteReal( fs, "accuracy", termcrit->epsilon );
2073         cvEndWriteStruct( fs );
2074     }
2075 @endcode
2076 @param fs File storage
2077 @param name Name of the written value. Should be NULL if and only if the parent structure is a
2078 sequence.
2079 @param value The written value
2080 */
2081 CVAPI(void) cvWriteReal( CvFileStorage* fs, const char* name, double value );
2082 
2083 /** @brief Writes a text string.
2084 
2085 The function writes a text string to file storage.
2086 @param fs File storage
2087 @param name Name of the written string . Should be NULL if and only if the parent structure is a
2088 sequence.
2089 @param str The written text string
2090 @param quote If non-zero, the written string is put in quotes, regardless of whether they are
2091 required. Otherwise, if the flag is zero, quotes are used only when they are required (e.g. when
2092 the string starts with a digit or contains spaces).
2093  */
2094 CVAPI(void) cvWriteString( CvFileStorage* fs, const char* name,
2095                            const char* str, int quote CV_DEFAULT(0) );
2096 
2097 /** @brief Writes a comment.
2098 
2099 The function writes a comment into file storage. The comments are skipped when the storage is read.
2100 @param fs File storage
2101 @param comment The written comment, single-line or multi-line
2102 @param eol_comment If non-zero, the function tries to put the comment at the end of current line.
2103 If the flag is zero, if the comment is multi-line, or if it does not fit at the end of the current
2104 line, the comment starts a new line.
2105  */
2106 CVAPI(void) cvWriteComment( CvFileStorage* fs, const char* comment,
2107                             int eol_comment );
2108 
2109 /** @brief Writes an object to file storage.
2110 
2111 The function writes an object to file storage. First, the appropriate type info is found using
2112 cvTypeOf. Then, the write method associated with the type info is called.
2113 
2114 Attributes are used to customize the writing procedure. The standard types support the following
2115 attributes (all the dt attributes have the same format as in cvWriteRawData):
2116 
2117 -# CvSeq
2118     -   **header_dt** description of user fields of the sequence header that follow CvSeq, or
2119         CvChain (if the sequence is a Freeman chain) or CvContour (if the sequence is a contour or
2120         point sequence)
2121     -   **dt** description of the sequence elements.
2122     -   **recursive** if the attribute is present and is not equal to "0" or "false", the whole
2123         tree of sequences (contours) is stored.
2124 -# CvGraph
2125     -   **header_dt** description of user fields of the graph header that follows CvGraph;
2126     -   **vertex_dt** description of user fields of graph vertices
2127     -   **edge_dt** description of user fields of graph edges (note that the edge weight is
2128         always written, so there is no need to specify it explicitly)
2129 
2130 Below is the code that creates the YAML file shown in the CvFileStorage description:
2131 @code
2132     #include "cxcore.h"
2133 
2134     int main( int argc, char** argv )
2135     {
2136         CvMat* mat = cvCreateMat( 3, 3, CV_32F );
2137         CvFileStorage* fs = cvOpenFileStorage( "example.yml", 0, CV_STORAGE_WRITE );
2138 
2139         cvSetIdentity( mat );
2140         cvWrite( fs, "A", mat, cvAttrList(0,0) );
2141 
2142         cvReleaseFileStorage( &fs );
2143         cvReleaseMat( &mat );
2144         return 0;
2145     }
2146 @endcode
2147 @param fs File storage
2148 @param name Name of the written object. Should be NULL if and only if the parent structure is a
2149 sequence.
2150 @param ptr Pointer to the object
2151 @param attributes The attributes of the object. They are specific for each particular type (see
2152 the discussion below).
2153  */
2154 CVAPI(void) cvWrite( CvFileStorage* fs, const char* name, const void* ptr,
2155                          CvAttrList attributes CV_DEFAULT(cvAttrList()));
2156 
2157 /** @brief Starts the next stream.
2158 
2159 The function finishes the currently written stream and starts the next stream. In the case of XML
2160 the file with multiple streams looks like this:
2161 @code{.xml}
2162     <opencv_storage>
2163     <!-- stream #1 data -->
2164     </opencv_storage>
2165     <opencv_storage>
2166     <!-- stream #2 data -->
2167     </opencv_storage>
2168     ...
2169 @endcode
2170 The YAML file will look like this:
2171 @code{.yaml}
2172     %YAML 1.0
2173     # stream #1 data
2174     ...
2175     ---
2176     # stream #2 data
2177 @endcode
2178 This is useful for concatenating files or for resuming the writing process.
2179 @param fs File storage
2180  */
2181 CVAPI(void) cvStartNextStream( CvFileStorage* fs );
2182 
2183 /** @brief Writes multiple numbers.
2184 
2185 The function writes an array, whose elements consist of single or multiple numbers. The function
2186 call can be replaced with a loop containing a few cvWriteInt and cvWriteReal calls, but a single
2187 call is more efficient. Note that because none of the elements have a name, they should be written
2188 to a sequence rather than a map.
2189 @param fs File storage
2190 @param src Pointer to the written array
2191 @param len Number of the array elements to write
2192 @param dt Specification of each array element, see @ref format_spec "format specification"
2193  */
2194 CVAPI(void) cvWriteRawData( CvFileStorage* fs, const void* src,
2195                                 int len, const char* dt );
2196 
2197 /** @brief Writes multiple numbers in Base64.
2198 
2199 If either CV_STORAGE_WRITE_BASE64 or cv::FileStorage::WRITE_BASE64 is used,
2200 this function will be the same as cvWriteRawData. If neither, the main
2201 difference is that it outputs a sequence in Base64 encoding rather than
2202 in plain text.
2203 
2204 This function can only be used to write a sequence with a type "binary".
2205 
2206 @param fs File storage
2207 @param src Pointer to the written array
2208 @param len Number of the array elements to write
2209 @param dt Specification of each array element, see @ref format_spec "format specification"
2210 */
2211 CVAPI(void) cvWriteRawDataBase64( CvFileStorage* fs, const void* src,
2212                                  int len, const char* dt );
2213 
2214 /** @brief Returns a unique pointer for a given name.
2215 
2216 The function returns a unique pointer for each particular file node name. This pointer can be then
2217 passed to the cvGetFileNode function that is faster than cvGetFileNodeByName because it compares
2218 text strings by comparing pointers rather than the strings' content.
2219 
2220 Consider the following example where an array of points is encoded as a sequence of 2-entry maps:
2221 @code
2222     points:
2223       - { x: 10, y: 10 }
2224       - { x: 20, y: 20 }
2225       - { x: 30, y: 30 }
2226       # ...
2227 @endcode
2228 Then, it is possible to get hashed "x" and "y" pointers to speed up decoding of the points. :
2229 @code
2230     #include "cxcore.h"
2231 
2232     int main( int argc, char** argv )
2233     {
2234         CvFileStorage* fs = cvOpenFileStorage( "points.yml", 0, CV_STORAGE_READ );
2235         CvStringHashNode* x_key = cvGetHashedNode( fs, "x", -1, 1 );
2236         CvStringHashNode* y_key = cvGetHashedNode( fs, "y", -1, 1 );
2237         CvFileNode* points = cvGetFileNodeByName( fs, 0, "points" );
2238 
2239         if( CV_NODE_IS_SEQ(points->tag) )
2240         {
2241             CvSeq* seq = points->data.seq;
2242             int i, total = seq->total;
2243             CvSeqReader reader;
2244             cvStartReadSeq( seq, &reader, 0 );
2245             for( i = 0; i < total; i++ )
2246             {
2247                 CvFileNode* pt = (CvFileNode*)reader.ptr;
2248     #if 1 // faster variant
2249                 CvFileNode* xnode = cvGetFileNode( fs, pt, x_key, 0 );
2250                 CvFileNode* ynode = cvGetFileNode( fs, pt, y_key, 0 );
2251                 assert( xnode && CV_NODE_IS_INT(xnode->tag) &&
2252                         ynode && CV_NODE_IS_INT(ynode->tag));
2253                 int x = xnode->data.i; // or x = cvReadInt( xnode, 0 );
2254                 int y = ynode->data.i; // or y = cvReadInt( ynode, 0 );
2255     #elif 1 // slower variant; does not use x_key & y_key
2256                 CvFileNode* xnode = cvGetFileNodeByName( fs, pt, "x" );
2257                 CvFileNode* ynode = cvGetFileNodeByName( fs, pt, "y" );
2258                 assert( xnode && CV_NODE_IS_INT(xnode->tag) &&
2259                         ynode && CV_NODE_IS_INT(ynode->tag));
2260                 int x = xnode->data.i; // or x = cvReadInt( xnode, 0 );
2261                 int y = ynode->data.i; // or y = cvReadInt( ynode, 0 );
2262     #else // the slowest yet the easiest to use variant
2263                 int x = cvReadIntByName( fs, pt, "x", 0 );
2264                 int y = cvReadIntByName( fs, pt, "y", 0 );
2265     #endif
2266                 CV_NEXT_SEQ_ELEM( seq->elem_size, reader );
2267                 printf("
2268             }
2269         }
2270         cvReleaseFileStorage( &fs );
2271         return 0;
2272     }
2273 @endcode
2274 Please note that whatever method of accessing a map you are using, it is still much slower than
2275 using plain sequences; for example, in the above example, it is more efficient to encode the points
2276 as pairs of integers in a single numeric sequence.
2277 @param fs File storage
2278 @param name Literal node name
2279 @param len Length of the name (if it is known apriori), or -1 if it needs to be calculated
2280 @param create_missing Flag that specifies, whether an absent key should be added into the hash table
2281 */
2282 CVAPI(CvStringHashNode*) cvGetHashedKey( CvFileStorage* fs, const char* name,
2283                                         int len CV_DEFAULT(-1),
2284                                         int create_missing CV_DEFAULT(0));
2285 
2286 /** @brief Retrieves one of the top-level nodes of the file storage.
2287 
2288 The function returns one of the top-level file nodes. The top-level nodes do not have a name, they
2289 correspond to the streams that are stored one after another in the file storage. If the index is out
2290 of range, the function returns a NULL pointer, so all the top-level nodes can be iterated by
2291 subsequent calls to the function with stream_index=0,1,..., until the NULL pointer is returned.
2292 This function can be used as a base for recursive traversal of the file storage.
2293 @param fs File storage
2294 @param stream_index Zero-based index of the stream. See cvStartNextStream . In most cases,
2295 there is only one stream in the file; however, there can be several.
2296  */
2297 CVAPI(CvFileNode*) cvGetRootFileNode( const CvFileStorage* fs,
2298                                      int stream_index CV_DEFAULT(0) );
2299 
2300 /** @brief Finds a node in a map or file storage.
2301 
2302 The function finds a file node. It is a faster version of cvGetFileNodeByName (see
2303 cvGetHashedKey discussion). Also, the function can insert a new node, if it is not in the map yet.
2304 @param fs File storage
2305 @param map The parent map. If it is NULL, the function searches a top-level node. If both map and
2306 key are NULLs, the function returns the root file node - a map that contains top-level nodes.
2307 @param key Unique pointer to the node name, retrieved with cvGetHashedKey
2308 @param create_missing Flag that specifies whether an absent node should be added to the map
2309  */
2310 CVAPI(CvFileNode*) cvGetFileNode( CvFileStorage* fs, CvFileNode* map,
2311                                  const CvStringHashNode* key,
2312                                  int create_missing CV_DEFAULT(0) );
2313 
2314 /** @brief Finds a node in a map or file storage.
2315 
2316 The function finds a file node by name. The node is searched either in map or, if the pointer is
2317 NULL, among the top-level file storage nodes. Using this function for maps and cvGetSeqElem (or
2318 sequence reader) for sequences, it is possible to navigate through the file storage. To speed up
2319 multiple queries for a certain key (e.g., in the case of an array of structures) one may use a
2320 combination of cvGetHashedKey and cvGetFileNode.
2321 @param fs File storage
2322 @param map The parent map. If it is NULL, the function searches in all the top-level nodes
2323 (streams), starting with the first one.
2324 @param name The file node name
2325  */
2326 CVAPI(CvFileNode*) cvGetFileNodeByName( const CvFileStorage* fs,
2327                                        const CvFileNode* map,
2328                                        const char* name );
2329 
2330 /** @brief Retrieves an integer value from a file node.
2331 
2332 The function returns an integer that is represented by the file node. If the file node is NULL, the
2333 default_value is returned (thus, it is convenient to call the function right after cvGetFileNode
2334 without checking for a NULL pointer). If the file node has type CV_NODE_INT, then node-\>data.i is
2335 returned. If the file node has type CV_NODE_REAL, then node-\>data.f is converted to an integer
2336 and returned. Otherwise the error is reported.
2337 @param node File node
2338 @param default_value The value that is returned if node is NULL
2339  */
2340 CV_INLINE int cvReadInt( const CvFileNode* node, int default_value CV_DEFAULT(0) )
2341 {
2342     return !node ? default_value :
2343         CV_NODE_IS_INT(node->tag) ? node->data.i :
2344         CV_NODE_IS_REAL(node->tag) ? cvRound(node->data.f) : 0x7fffffff;
2345 }
2346 
2347 /** @brief Finds a file node and returns its value.
2348 
2349 The function is a simple superposition of cvGetFileNodeByName and cvReadInt.
2350 @param fs File storage
2351 @param map The parent map. If it is NULL, the function searches a top-level node.
2352 @param name The node name
2353 @param default_value The value that is returned if the file node is not found
2354  */
2355 CV_INLINE int cvReadIntByName( const CvFileStorage* fs, const CvFileNode* map,
2356                          const char* name, int default_value CV_DEFAULT(0) )
2357 {
2358     return cvReadInt( cvGetFileNodeByName( fs, map, name ), default_value );
2359 }
2360 
2361 /** @brief Retrieves a floating-point value from a file node.
2362 
2363 The function returns a floating-point value that is represented by the file node. If the file node
2364 is NULL, the default_value is returned (thus, it is convenient to call the function right after
2365 cvGetFileNode without checking for a NULL pointer). If the file node has type CV_NODE_REAL ,
2366 then node-\>data.f is returned. If the file node has type CV_NODE_INT , then node-:math:\>data.f
2367 is converted to floating-point and returned. Otherwise the result is not determined.
2368 @param node File node
2369 @param default_value The value that is returned if node is NULL
2370  */
2371 CV_INLINE double cvReadReal( const CvFileNode* node, double default_value CV_DEFAULT(0.) )
2372 {
2373     return !node ? default_value :
2374         CV_NODE_IS_INT(node->tag) ? (double)node->data.i :
2375         CV_NODE_IS_REAL(node->tag) ? node->data.f : 1e300;
2376 }
2377 
2378 /** @brief Finds a file node and returns its value.
2379 
2380 The function is a simple superposition of cvGetFileNodeByName and cvReadReal .
2381 @param fs File storage
2382 @param map The parent map. If it is NULL, the function searches a top-level node.
2383 @param name The node name
2384 @param default_value The value that is returned if the file node is not found
2385  */
2386 CV_INLINE double cvReadRealByName( const CvFileStorage* fs, const CvFileNode* map,
2387                         const char* name, double default_value CV_DEFAULT(0.) )
2388 {
2389     return cvReadReal( cvGetFileNodeByName( fs, map, name ), default_value );
2390 }
2391 
2392 /** @brief Retrieves a text string from a file node.
2393 
2394 The function returns a text string that is represented by the file node. If the file node is NULL,
2395 the default_value is returned (thus, it is convenient to call the function right after
2396 cvGetFileNode without checking for a NULL pointer). If the file node has type CV_NODE_STR , then
2397 node-:math:\>data.str.ptr is returned. Otherwise the result is not determined.
2398 @param node File node
2399 @param default_value The value that is returned if node is NULL
2400  */
cvReadString(const CvFileNode * node,const char * default_value CV_DEFAULT (NULL))2401 CV_INLINE const char* cvReadString( const CvFileNode* node,
2402                         const char* default_value CV_DEFAULT(NULL) )
2403 {
2404     return !node ? default_value : CV_NODE_IS_STRING(node->tag) ? node->data.str.ptr : 0;
2405 }
2406 
2407 /** @brief Finds a file node by its name and returns its value.
2408 
2409 The function is a simple superposition of cvGetFileNodeByName and cvReadString .
2410 @param fs File storage
2411 @param map The parent map. If it is NULL, the function searches a top-level node.
2412 @param name The node name
2413 @param default_value The value that is returned if the file node is not found
2414  */
cvReadStringByName(const CvFileStorage * fs,const CvFileNode * map,const char * name,const char * default_value CV_DEFAULT (NULL))2415 CV_INLINE const char* cvReadStringByName( const CvFileStorage* fs, const CvFileNode* map,
2416                         const char* name, const char* default_value CV_DEFAULT(NULL) )
2417 {
2418     return cvReadString( cvGetFileNodeByName( fs, map, name ), default_value );
2419 }
2420 
2421 
2422 /** @brief Decodes an object and returns a pointer to it.
2423 
2424 The function decodes a user object (creates an object in a native representation from the file
2425 storage subtree) and returns it. The object to be decoded must be an instance of a registered type
2426 that supports the read method (see CvTypeInfo). The type of the object is determined by the type
2427 name that is encoded in the file. If the object is a dynamic structure, it is created either in
2428 memory storage and passed to cvOpenFileStorage or, if a NULL pointer was passed, in temporary
2429 memory storage, which is released when cvReleaseFileStorage is called. Otherwise, if the object is
2430 not a dynamic structure, it is created in a heap and should be released with a specialized function
2431 or by using the generic cvRelease.
2432 @param fs File storage
2433 @param node The root object node
2434 @param attributes Unused parameter
2435  */
2436 CVAPI(void*) cvRead( CvFileStorage* fs, CvFileNode* node,
2437                         CvAttrList* attributes CV_DEFAULT(NULL));
2438 
2439 /** @brief Finds an object by name and decodes it.
2440 
2441 The function is a simple superposition of cvGetFileNodeByName and cvRead.
2442 @param fs File storage
2443 @param map The parent map. If it is NULL, the function searches a top-level node.
2444 @param name The node name
2445 @param attributes Unused parameter
2446  */
cvReadByName(CvFileStorage * fs,const CvFileNode * map,const char * name,CvAttrList * attributes CV_DEFAULT (NULL))2447 CV_INLINE void* cvReadByName( CvFileStorage* fs, const CvFileNode* map,
2448                               const char* name, CvAttrList* attributes CV_DEFAULT(NULL) )
2449 {
2450     return cvRead( fs, cvGetFileNodeByName( fs, map, name ), attributes );
2451 }
2452 
2453 
2454 /** @brief Initializes the file node sequence reader.
2455 
2456 The function initializes the sequence reader to read data from a file node. The initialized reader
2457 can be then passed to cvReadRawDataSlice.
2458 @param fs File storage
2459 @param src The file node (a sequence) to read numbers from
2460 @param reader Pointer to the sequence reader
2461  */
2462 CVAPI(void) cvStartReadRawData( const CvFileStorage* fs, const CvFileNode* src,
2463                                CvSeqReader* reader );
2464 
2465 /** @brief Initializes file node sequence reader.
2466 
2467 The function reads one or more elements from the file node, representing a sequence, to a
2468 user-specified array. The total number of read sequence elements is a product of total and the
2469 number of components in each array element. For example, if dt=2if, the function will read total\*3
2470 sequence elements. As with any sequence, some parts of the file node sequence can be skipped or read
2471 repeatedly by repositioning the reader using cvSetSeqReaderPos.
2472 @param fs File storage
2473 @param reader The sequence reader. Initialize it with cvStartReadRawData .
2474 @param count The number of elements to read
2475 @param dst Pointer to the destination array
2476 @param dt Specification of each array element. It has the same format as in cvWriteRawData .
2477  */
2478 CVAPI(void) cvReadRawDataSlice( const CvFileStorage* fs, CvSeqReader* reader,
2479                                int count, void* dst, const char* dt );
2480 
2481 /** @brief Reads multiple numbers.
2482 
2483 The function reads elements from a file node that represents a sequence of scalars.
2484 @param fs File storage
2485 @param src The file node (a sequence) to read numbers from
2486 @param dst Pointer to the destination array
2487 @param dt Specification of each array element. It has the same format as in cvWriteRawData .
2488  */
2489 CVAPI(void) cvReadRawData( const CvFileStorage* fs, const CvFileNode* src,
2490                           void* dst, const char* dt );
2491 
2492 /** @brief Writes a file node to another file storage.
2493 
2494 The function writes a copy of a file node to file storage. Possible applications of the function are
2495 merging several file storages into one and conversion between XML, YAML and JSON formats.
2496 @param fs Destination file storage
2497 @param new_node_name New name of the file node in the destination file storage. To keep the
2498 existing name, use cvcvGetFileNodeName
2499 @param node The written node
2500 @param embed If the written node is a collection and this parameter is not zero, no extra level of
2501 hierarchy is created. Instead, all the elements of node are written into the currently written
2502 structure. Of course, map elements can only be embedded into another map, and sequence elements
2503 can only be embedded into another sequence.
2504  */
2505 CVAPI(void) cvWriteFileNode( CvFileStorage* fs, const char* new_node_name,
2506                             const CvFileNode* node, int embed );
2507 
2508 /** @brief Returns the name of a file node.
2509 
2510 The function returns the name of a file node or NULL, if the file node does not have a name or if
2511 node is NULL.
2512 @param node File node
2513  */
2514 CVAPI(const char*) cvGetFileNodeName( const CvFileNode* node );
2515 
2516 /*********************************** Adding own types ***********************************/
2517 
2518 /** @brief Registers a new type.
2519 
2520 The function registers a new type, which is described by info . The function creates a copy of the
2521 structure, so the user should delete it after calling the function.
2522 @param info Type info structure
2523  */
2524 CVAPI(void) cvRegisterType( const CvTypeInfo* info );
2525 
2526 /** @brief Unregisters the type.
2527 
2528 The function unregisters a type with a specified name. If the name is unknown, it is possible to
2529 locate the type info by an instance of the type using cvTypeOf or by iterating the type list,
2530 starting from cvFirstType, and then calling cvUnregisterType(info-\>typeName).
2531 @param type_name Name of an unregistered type
2532  */
2533 CVAPI(void) cvUnregisterType( const char* type_name );
2534 
2535 /** @brief Returns the beginning of a type list.
2536 
2537 The function returns the first type in the list of registered types. Navigation through the list can
2538 be done via the prev and next fields of the CvTypeInfo structure.
2539  */
2540 CVAPI(CvTypeInfo*) cvFirstType(void);
2541 
2542 /** @brief Finds a type by its name.
2543 
2544 The function finds a registered type by its name. It returns NULL if there is no type with the
2545 specified name.
2546 @param type_name Type name
2547  */
2548 CVAPI(CvTypeInfo*) cvFindType( const char* type_name );
2549 
2550 /** @brief Returns the type of an object.
2551 
2552 The function finds the type of a given object. It iterates through the list of registered types and
2553 calls the is_instance function/method for every type info structure with that object until one of
2554 them returns non-zero or until the whole list has been traversed. In the latter case, the function
2555 returns NULL.
2556 @param struct_ptr The object pointer
2557  */
2558 CVAPI(CvTypeInfo*) cvTypeOf( const void* struct_ptr );
2559 
2560 #endif
2561 
2562 /** @brief Releases an object.
2563 
2564  The function finds the type of a given object and calls release with the double pointer.
2565  @param struct_ptr Double pointer to the object
2566  */
2567 CVAPI(void) cvRelease( void** struct_ptr );
2568 
2569 /** @brief Makes a clone of an object.
2570 
2571 The function finds the type of a given object and calls clone with the passed object. Of course, if
2572 you know the object type, for example, struct_ptr is CvMat\*, it is faster to call the specific
2573 function, like cvCloneMat.
2574 @param struct_ptr The object to clone
2575  */
2576 CVAPI(void*) cvClone( const void* struct_ptr );
2577 
2578 /*********************************** Measuring Execution Time ***************************/
2579 
2580 /** helper functions for RNG initialization and accurate time measurement:
2581    uses internal clock counter on x86 */
2582 CVAPI(int64)  cvGetTickCount( void );
2583 CVAPI(double) cvGetTickFrequency( void );
2584 
2585 /*********************************** CPU capabilities ***********************************/
2586 
2587 CVAPI(int) cvCheckHardwareSupport(int feature);
2588 
2589 /*********************************** Multi-Threading ************************************/
2590 
2591 /** retrieve/set the number of threads used in OpenMP implementations */
2592 CVAPI(int)  cvGetNumThreads( void );
2593 CVAPI(void) cvSetNumThreads( int threads CV_DEFAULT(0) );
2594 /** get index of the thread being executed */
2595 CVAPI(int)  cvGetThreadNum( void );
2596 
2597 
2598 /********************************** Error Handling **************************************/
2599 
2600 /** Get current OpenCV error status */
2601 CVAPI(int) cvGetErrStatus( void );
2602 
2603 /** Sets error status silently */
2604 CVAPI(void) cvSetErrStatus( int status );
2605 
2606 #define CV_ErrModeLeaf     0   /* Print error and exit program */
2607 #define CV_ErrModeParent   1   /* Print error and continue */
2608 #define CV_ErrModeSilent   2   /* Don't print and continue */
2609 
2610 /** Retrieves current error processing mode */
2611 CVAPI(int)  cvGetErrMode( void );
2612 
2613 /** Sets error processing mode, returns previously used mode */
2614 CVAPI(int) cvSetErrMode( int mode );
2615 
2616 /** Sets error status and performs some additional actions (displaying message box,
2617  writing message to stderr, terminating application etc.)
2618  depending on the current error mode */
2619 CVAPI(void) cvError( int status, const char* func_name,
2620                     const char* err_msg, const char* file_name, int line );
2621 
2622 /** Retrieves textual description of the error given its code */
2623 CVAPI(const char*) cvErrorStr( int status );
2624 
2625 /** Retrieves detailed information about the last error occurred */
2626 CVAPI(int) cvGetErrInfo( const char** errcode_desc, const char** description,
2627                         const char** filename, int* line );
2628 
2629 /** Maps IPP error codes to the counterparts from OpenCV */
2630 CVAPI(int) cvErrorFromIppStatus( int ipp_status );
2631 
2632 typedef int (CV_CDECL *CvErrorCallback)( int status, const char* func_name,
2633                                         const char* err_msg, const char* file_name, int line, void* userdata );
2634 
2635 /** Assigns a new error-handling function */
2636 CVAPI(CvErrorCallback) cvRedirectError( CvErrorCallback error_handler,
2637                                        void* userdata CV_DEFAULT(NULL),
2638                                        void** prev_userdata CV_DEFAULT(NULL) );
2639 
2640 /** Output nothing */
2641 CVAPI(int) cvNulDevReport( int status, const char* func_name, const char* err_msg,
2642                           const char* file_name, int line, void* userdata );
2643 
2644 /** Output to console(fprintf(stderr,...)) */
2645 CVAPI(int) cvStdErrReport( int status, const char* func_name, const char* err_msg,
2646                           const char* file_name, int line, void* userdata );
2647 
2648 /** Output to MessageBox(WIN32) */
2649 CVAPI(int) cvGuiBoxReport( int status, const char* func_name, const char* err_msg,
2650                           const char* file_name, int line, void* userdata );
2651 
2652 #define OPENCV_ERROR(status,func,context)                           \
2653 cvError((status),(func),(context),__FILE__,__LINE__)
2654 
2655 #define OPENCV_ASSERT(expr,func,context)                            \
2656 {if (! (expr))                                      \
2657 {OPENCV_ERROR(CV_StsInternal,(func),(context));}}
2658 
2659 #define OPENCV_CALL( Func )                                         \
2660 {                                                                   \
2661 Func;                                                           \
2662 }
2663 
2664 
2665 /** CV_FUNCNAME macro defines icvFuncName constant which is used by CV_ERROR macro */
2666 #ifdef CV_NO_FUNC_NAMES
2667 #define CV_FUNCNAME( Name )
2668 #define cvFuncName ""
2669 #else
2670 #define CV_FUNCNAME( Name )  \
2671 static char cvFuncName[] = Name
2672 #endif
2673 
2674 
2675 /**
2676  CV_ERROR macro unconditionally raises error with passed code and message.
2677  After raising error, control will be transferred to the exit label.
2678  */
2679 #define CV_ERROR( Code, Msg )                                       \
2680 {                                                                   \
2681     cvError( (Code), cvFuncName, Msg, __FILE__, __LINE__ );        \
2682     __CV_EXIT__;                                                   \
2683 }
2684 
2685 /**
2686  CV_CHECK macro checks error status after CV (or IPL)
2687  function call. If error detected, control will be transferred to the exit
2688  label.
2689  */
2690 #define CV_CHECK()                                                  \
2691 {                                                                   \
2692     if( cvGetErrStatus() < 0 )                                      \
2693         CV_ERROR( CV_StsBackTrace, "Inner function failed." );      \
2694 }
2695 
2696 
2697 /**
2698  CV_CALL macro calls CV (or IPL) function, checks error status and
2699  signals a error if the function failed. Useful in "parent node"
2700  error processing mode
2701  */
2702 #define CV_CALL( Func )                                             \
2703 {                                                                   \
2704     Func;                                                           \
2705     CV_CHECK();                                                     \
2706 }
2707 
2708 
2709 /** Runtime assertion macro */
2710 #define CV_ASSERT( Condition )                                          \
2711 {                                                                       \
2712     if( !(Condition) )                                                  \
2713         CV_ERROR( CV_StsInternal, "Assertion: " #Condition " failed" ); \
2714 }
2715 
2716 #define __CV_BEGIN__       {
2717 #define __CV_END__         goto exit; exit: ; }
2718 #define __CV_EXIT__        goto exit
2719 
2720 /** @} core_c */
2721 
2722 #ifdef __cplusplus
2723 } // extern "C"
2724 #endif
2725 
2726 #ifdef __cplusplus
2727 
2728 #include "opencv2/core/utility.hpp"
2729 
2730 namespace cv
2731 {
2732 
2733 //! @addtogroup core_c_glue
2734 //! @{
2735 
2736 /////////////////////////////////////////// glue ///////////////////////////////////////////
2737 
2738 //! converts array (CvMat or IplImage) to cv::Mat
2739 CV_EXPORTS Mat cvarrToMat(const CvArr* arr, bool copyData=false,
2740                           bool allowND=true, int coiMode=0,
2741                           AutoBuffer<double>* buf=0);
2742 
2743 static inline Mat cvarrToMatND(const CvArr* arr, bool copyData=false, int coiMode=0)
2744 {
2745     return cvarrToMat(arr, copyData, true, coiMode);
2746 }
2747 
2748 
2749 //! extracts Channel of Interest from CvMat or IplImage and makes cv::Mat out of it.
2750 CV_EXPORTS void extractImageCOI(const CvArr* arr, OutputArray coiimg, int coi=-1);
2751 //! inserts single-channel cv::Mat into a multi-channel CvMat or IplImage
2752 CV_EXPORTS void insertImageCOI(InputArray coiimg, CvArr* arr, int coi=-1);
2753 
2754 
2755 
2756 ////// specialized implementations of DefaultDeleter::operator() for classic OpenCV types //////
2757 
2758 template<> struct DefaultDeleter<CvMat>{ CV_EXPORTS void operator ()(CvMat* obj) const; };
2759 template<> struct DefaultDeleter<IplImage>{ CV_EXPORTS void operator ()(IplImage* obj) const; };
2760 template<> struct DefaultDeleter<CvMatND>{ CV_EXPORTS void operator ()(CvMatND* obj) const; };
2761 template<> struct DefaultDeleter<CvSparseMat>{ CV_EXPORTS void operator ()(CvSparseMat* obj) const; };
2762 template<> struct DefaultDeleter<CvMemStorage>{ CV_EXPORTS void operator ()(CvMemStorage* obj) const; };
2763 
2764 ////////////// convenient wrappers for operating old-style dynamic structures //////////////
2765 
2766 template<typename _Tp> class SeqIterator;
2767 
2768 typedef Ptr<CvMemStorage> MemStorage;
2769 
2770 /*!
2771  Template Sequence Class derived from CvSeq
2772 
2773  The class provides more convenient access to sequence elements,
2774  STL-style operations and iterators.
2775 
2776  \note The class is targeted for simple data types,
2777     i.e. no constructors or destructors
2778     are called for the sequence elements.
2779 */
2780 template<typename _Tp> class Seq
2781 {
2782 public:
2783     typedef SeqIterator<_Tp> iterator;
2784     typedef SeqIterator<_Tp> const_iterator;
2785 
2786     //! the default constructor
2787     Seq();
2788     //! the constructor for wrapping CvSeq structure. The real element type in CvSeq should match _Tp.
2789     Seq(const CvSeq* seq);
2790     //! creates the empty sequence that resides in the specified storage
2791     Seq(MemStorage& storage, int headerSize = sizeof(CvSeq));
2792     //! returns read-write reference to the specified element
2793     _Tp& operator [](int idx);
2794     //! returns read-only reference to the specified element
2795     const _Tp& operator[](int idx) const;
2796     //! returns iterator pointing to the beginning of the sequence
2797     SeqIterator<_Tp> begin() const;
2798     //! returns iterator pointing to the element following the last sequence element
2799     SeqIterator<_Tp> end() const;
2800     //! returns the number of elements in the sequence
2801     size_t size() const;
2802     //! returns the type of sequence elements (CV_8UC1 ... CV_64FC(CV_CN_MAX) ...)
2803     int type() const;
2804     //! returns the depth of sequence elements (CV_8U ... CV_64F)
2805     int depth() const;
2806     //! returns the number of channels in each sequence element
2807     int channels() const;
2808     //! returns the size of each sequence element
2809     size_t elemSize() const;
2810     //! returns index of the specified sequence element
2811     size_t index(const _Tp& elem) const;
2812     //! appends the specified element to the end of the sequence
2813     void push_back(const _Tp& elem);
2814     //! appends the specified element to the front of the sequence
2815     void push_front(const _Tp& elem);
2816     //! appends zero or more elements to the end of the sequence
2817     void push_back(const _Tp* elems, size_t count);
2818     //! appends zero or more elements to the front of the sequence
2819     void push_front(const _Tp* elems, size_t count);
2820     //! inserts the specified element to the specified position
2821     void insert(int idx, const _Tp& elem);
2822     //! inserts zero or more elements to the specified position
2823     void insert(int idx, const _Tp* elems, size_t count);
2824     //! removes element at the specified position
2825     void remove(int idx);
2826     //! removes the specified subsequence
2827     void remove(const Range& r);
2828 
2829     //! returns reference to the first sequence element
2830     _Tp& front();
2831     //! returns read-only reference to the first sequence element
2832     const _Tp& front() const;
2833     //! returns reference to the last sequence element
2834     _Tp& back();
2835     //! returns read-only reference to the last sequence element
2836     const _Tp& back() const;
2837     //! returns true iff the sequence contains no elements
2838     bool empty() const;
2839 
2840     //! removes all the elements from the sequence
2841     void clear();
2842     //! removes the first element from the sequence
2843     void pop_front();
2844     //! removes the last element from the sequence
2845     void pop_back();
2846     //! removes zero or more elements from the beginning of the sequence
2847     void pop_front(_Tp* elems, size_t count);
2848     //! removes zero or more elements from the end of the sequence
2849     void pop_back(_Tp* elems, size_t count);
2850 
2851     //! copies the whole sequence or the sequence slice to the specified vector
2852     void copyTo(std::vector<_Tp>& vec, const Range& range=Range::all()) const;
2853     //! returns the vector containing all the sequence elements
2854     operator std::vector<_Tp>() const;
2855 
2856     CvSeq* seq;
2857 };
2858 
2859 
2860 /*!
2861  STL-style Sequence Iterator inherited from the CvSeqReader structure
2862 */
2863 template<typename _Tp> class SeqIterator : public CvSeqReader
2864 {
2865 public:
2866     //! the default constructor
2867     SeqIterator();
2868     //! the constructor setting the iterator to the beginning or to the end of the sequence
2869     SeqIterator(const Seq<_Tp>& seq, bool seekEnd=false);
2870     //! positions the iterator within the sequence
2871     void seek(size_t pos);
2872     //! reports the current iterator position
2873     size_t tell() const;
2874     //! returns reference to the current sequence element
2875     _Tp& operator *();
2876     //! returns read-only reference to the current sequence element
2877     const _Tp& operator *() const;
2878     //! moves iterator to the next sequence element
2879     SeqIterator& operator ++();
2880     //! moves iterator to the next sequence element
2881     SeqIterator operator ++(int) const;
2882     //! moves iterator to the previous sequence element
2883     SeqIterator& operator --();
2884     //! moves iterator to the previous sequence element
2885     SeqIterator operator --(int) const;
2886 
2887     //! moves iterator forward by the specified offset (possibly negative)
2888     SeqIterator& operator +=(int);
2889     //! moves iterator backward by the specified offset (possibly negative)
2890     SeqIterator& operator -=(int);
2891 
2892     // this is index of the current element module seq->total*2
2893     // (to distinguish between 0 and seq->total)
2894     int index;
2895 };
2896 
2897 
2898 
2899 // bridge C++ => C Seq API
2900 CV_EXPORTS schar*  seqPush( CvSeq* seq, const void* element=0);
2901 CV_EXPORTS schar*  seqPushFront( CvSeq* seq, const void* element=0);
2902 CV_EXPORTS void  seqPop( CvSeq* seq, void* element=0);
2903 CV_EXPORTS void  seqPopFront( CvSeq* seq, void* element=0);
2904 CV_EXPORTS void  seqPopMulti( CvSeq* seq, void* elements,
2905                               int count, int in_front=0 );
2906 CV_EXPORTS void  seqRemove( CvSeq* seq, int index );
2907 CV_EXPORTS void  clearSeq( CvSeq* seq );
2908 CV_EXPORTS schar*  getSeqElem( const CvSeq* seq, int index );
2909 CV_EXPORTS void  seqRemoveSlice( CvSeq* seq, CvSlice slice );
2910 CV_EXPORTS void  seqInsertSlice( CvSeq* seq, int before_index, const CvArr* from_arr );
2911 
2912 template<typename _Tp> inline Seq<_Tp>::Seq() : seq(0) {}
2913 template<typename _Tp> inline Seq<_Tp>::Seq( const CvSeq* _seq ) : seq((CvSeq*)_seq)
2914 {
2915     CV_Assert(!_seq || _seq->elem_size == sizeof(_Tp));
2916 }
2917 
2918 template<typename _Tp> inline Seq<_Tp>::Seq( MemStorage& storage,
2919                                              int headerSize )
2920 {
2921     CV_Assert(headerSize >= (int)sizeof(CvSeq));
2922     seq = cvCreateSeq(DataType<_Tp>::type, headerSize, sizeof(_Tp), storage);
2923 }
2924 
2925 template<typename _Tp> inline _Tp& Seq<_Tp>::operator [](int idx)
2926 { return *(_Tp*)getSeqElem(seq, idx); }
2927 
2928 template<typename _Tp> inline const _Tp& Seq<_Tp>::operator [](int idx) const
2929 { return *(_Tp*)getSeqElem(seq, idx); }
2930 
2931 template<typename _Tp> inline SeqIterator<_Tp> Seq<_Tp>::begin() const
2932 { return SeqIterator<_Tp>(*this); }
2933 
2934 template<typename _Tp> inline SeqIterator<_Tp> Seq<_Tp>::end() const
2935 { return SeqIterator<_Tp>(*this, true); }
2936 
2937 template<typename _Tp> inline size_t Seq<_Tp>::size() const
2938 { return seq ? seq->total : 0; }
2939 
2940 template<typename _Tp> inline int Seq<_Tp>::type() const
2941 { return seq ? CV_MAT_TYPE(seq->flags) : 0; }
2942 
2943 template<typename _Tp> inline int Seq<_Tp>::depth() const
2944 { return seq ? CV_MAT_DEPTH(seq->flags) : 0; }
2945 
2946 template<typename _Tp> inline int Seq<_Tp>::channels() const
2947 { return seq ? CV_MAT_CN(seq->flags) : 0; }
2948 
2949 template<typename _Tp> inline size_t Seq<_Tp>::elemSize() const
2950 { return seq ? seq->elem_size : 0; }
2951 
2952 template<typename _Tp> inline size_t Seq<_Tp>::index(const _Tp& elem) const
2953 { return cvSeqElemIdx(seq, &elem); }
2954 
2955 template<typename _Tp> inline void Seq<_Tp>::push_back(const _Tp& elem)
2956 { cvSeqPush(seq, &elem); }
2957 
2958 template<typename _Tp> inline void Seq<_Tp>::push_front(const _Tp& elem)
2959 { cvSeqPushFront(seq, &elem); }
2960 
2961 template<typename _Tp> inline void Seq<_Tp>::push_back(const _Tp* elem, size_t count)
2962 { cvSeqPushMulti(seq, elem, (int)count, 0); }
2963 
2964 template<typename _Tp> inline void Seq<_Tp>::push_front(const _Tp* elem, size_t count)
2965 { cvSeqPushMulti(seq, elem, (int)count, 1); }
2966 
2967 template<typename _Tp> inline _Tp& Seq<_Tp>::back()
2968 { return *(_Tp*)getSeqElem(seq, -1); }
2969 
2970 template<typename _Tp> inline const _Tp& Seq<_Tp>::back() const
2971 { return *(const _Tp*)getSeqElem(seq, -1); }
2972 
2973 template<typename _Tp> inline _Tp& Seq<_Tp>::front()
2974 { return *(_Tp*)getSeqElem(seq, 0); }
2975 
2976 template<typename _Tp> inline const _Tp& Seq<_Tp>::front() const
2977 { return *(const _Tp*)getSeqElem(seq, 0); }
2978 
2979 template<typename _Tp> inline bool Seq<_Tp>::empty() const
2980 { return !seq || seq->total == 0; }
2981 
2982 template<typename _Tp> inline void Seq<_Tp>::clear()
2983 { if(seq) clearSeq(seq); }
2984 
2985 template<typename _Tp> inline void Seq<_Tp>::pop_back()
2986 { seqPop(seq); }
2987 
2988 template<typename _Tp> inline void Seq<_Tp>::pop_front()
2989 { seqPopFront(seq); }
2990 
2991 template<typename _Tp> inline void Seq<_Tp>::pop_back(_Tp* elem, size_t count)
2992 { seqPopMulti(seq, elem, (int)count, 0); }
2993 
2994 template<typename _Tp> inline void Seq<_Tp>::pop_front(_Tp* elem, size_t count)
2995 { seqPopMulti(seq, elem, (int)count, 1); }
2996 
2997 template<typename _Tp> inline void Seq<_Tp>::insert(int idx, const _Tp& elem)
2998 { seqInsert(seq, idx, &elem); }
2999 
3000 template<typename _Tp> inline void Seq<_Tp>::insert(int idx, const _Tp* elems, size_t count)
3001 {
3002     CvMat m = cvMat(1, count, DataType<_Tp>::type, elems);
3003     seqInsertSlice(seq, idx, &m);
3004 }
3005 
3006 template<typename _Tp> inline void Seq<_Tp>::remove(int idx)
3007 { seqRemove(seq, idx); }
3008 
3009 template<typename _Tp> inline void Seq<_Tp>::remove(const Range& r)
3010 { seqRemoveSlice(seq, cvSlice(r.start, r.end)); }
3011 
3012 template<typename _Tp> inline void Seq<_Tp>::copyTo(std::vector<_Tp>& vec, const Range& range) const
3013 {
3014     size_t len = !seq ? 0 : range == Range::all() ? seq->total : range.end - range.start;
3015     vec.resize(len);
3016     if( seq && len )
3017         cvCvtSeqToArray(seq, &vec[0], cvSlice(range));
3018 }
3019 
3020 template<typename _Tp> inline Seq<_Tp>::operator std::vector<_Tp>() const
3021 {
3022     std::vector<_Tp> vec;
3023     copyTo(vec);
3024     return vec;
3025 }
3026 
3027 template<typename _Tp> inline SeqIterator<_Tp>::SeqIterator()
3028 { memset(this, 0, sizeof(*this)); }
3029 
3030 template<typename _Tp> inline SeqIterator<_Tp>::SeqIterator(const Seq<_Tp>& _seq, bool seekEnd)
3031 {
3032     cvStartReadSeq(_seq.seq, this);
3033     index = seekEnd ? _seq.seq->total : 0;
3034 }
3035 
3036 template<typename _Tp> inline void SeqIterator<_Tp>::seek(size_t pos)
3037 {
3038     cvSetSeqReaderPos(this, (int)pos, false);
3039     index = pos;
3040 }
3041 
3042 template<typename _Tp> inline size_t SeqIterator<_Tp>::tell() const
3043 { return index; }
3044 
3045 template<typename _Tp> inline _Tp& SeqIterator<_Tp>::operator *()
3046 { return *(_Tp*)ptr; }
3047 
3048 template<typename _Tp> inline const _Tp& SeqIterator<_Tp>::operator *() const
3049 { return *(const _Tp*)ptr; }
3050 
3051 template<typename _Tp> inline SeqIterator<_Tp>& SeqIterator<_Tp>::operator ++()
3052 {
3053     CV_NEXT_SEQ_ELEM(sizeof(_Tp), *this);
3054     if( ++index >= seq->total*2 )
3055         index = 0;
3056     return *this;
3057 }
3058 
3059 template<typename _Tp> inline SeqIterator<_Tp> SeqIterator<_Tp>::operator ++(int) const
3060 {
3061     SeqIterator<_Tp> it = *this;
3062     ++*this;
3063     return it;
3064 }
3065 
3066 template<typename _Tp> inline SeqIterator<_Tp>& SeqIterator<_Tp>::operator --()
3067 {
3068     CV_PREV_SEQ_ELEM(sizeof(_Tp), *this);
3069     if( --index < 0 )
3070         index = seq->total*2-1;
3071     return *this;
3072 }
3073 
3074 template<typename _Tp> inline SeqIterator<_Tp> SeqIterator<_Tp>::operator --(int) const
3075 {
3076     SeqIterator<_Tp> it = *this;
3077     --*this;
3078     return it;
3079 }
3080 
3081 template<typename _Tp> inline SeqIterator<_Tp>& SeqIterator<_Tp>::operator +=(int delta)
3082 {
3083     cvSetSeqReaderPos(this, delta, 1);
3084     index += delta;
3085     int n = seq->total*2;
3086     if( index < 0 )
3087         index += n;
3088     if( index >= n )
3089         index -= n;
3090     return *this;
3091 }
3092 
3093 template<typename _Tp> inline SeqIterator<_Tp>& SeqIterator<_Tp>::operator -=(int delta)
3094 {
3095     return (*this += -delta);
3096 }
3097 
3098 template<typename _Tp> inline ptrdiff_t operator - (const SeqIterator<_Tp>& a,
3099                                                     const SeqIterator<_Tp>& b)
3100 {
3101     ptrdiff_t delta = a.index - b.index, n = a.seq->total;
3102     if( delta > n || delta < -n )
3103         delta += delta < 0 ? n : -n;
3104     return delta;
3105 }
3106 
3107 template<typename _Tp> inline bool operator == (const SeqIterator<_Tp>& a,
3108                                                 const SeqIterator<_Tp>& b)
3109 {
3110     return a.seq == b.seq && a.index == b.index;
3111 }
3112 
3113 template<typename _Tp> inline bool operator != (const SeqIterator<_Tp>& a,
3114                                                 const SeqIterator<_Tp>& b)
3115 {
3116     return !(a == b);
3117 }
3118 
3119 //! @}
3120 
3121 } // cv
3122 
3123 #endif
3124 
3125 #endif
3126