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++ construrtors 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 functions return 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 functions return 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 simulteneously
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 /** Tranposes 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 specifed 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 /********************************** High-level functions ********************************/
1974
1975 /** @brief Opens file storage for reading or writing data.
1976
1977 The function opens file storage for reading or writing data. In the latter case, a new file is
1978 created or an existing file is rewritten. The type of the read or written file is determined by the
1979 filename extension: .xml for XML and .yml or .yaml for YAML. The function returns a pointer to the
1980 CvFileStorage structure. If the file cannot be opened then the function returns NULL.
1981 @param filename Name of the file associated with the storage
1982 @param memstorage Memory storage used for temporary data and for
1983 : storing dynamic structures, such as CvSeq or CvGraph . If it is NULL, a temporary memory
1984 storage is created and used.
1985 @param flags Can be one of the following:
1986 > - **CV_STORAGE_READ** the storage is open for reading
1987 > - **CV_STORAGE_WRITE** the storage is open for writing
1988 @param encoding
1989 */
1990 CVAPI(CvFileStorage*) cvOpenFileStorage( const char* filename, CvMemStorage* memstorage,
1991 int flags, const char* encoding CV_DEFAULT(NULL) );
1992
1993 /** @brief Releases file storage.
1994
1995 The function closes the file associated with the storage and releases all the temporary structures.
1996 It must be called after all I/O operations with the storage are finished.
1997 @param fs Double pointer to the released file storage
1998 */
1999 CVAPI(void) cvReleaseFileStorage( CvFileStorage** fs );
2000
2001 /** returns attribute value or 0 (NULL) if there is no such attribute */
2002 CVAPI(const char*) cvAttrValue( const CvAttrList* attr, const char* attr_name );
2003
2004 /** @brief Starts writing a new structure.
2005
2006 The function starts writing a compound structure (collection) that can be a sequence or a map. After
2007 all the structure fields, which can be scalars or structures, are written, cvEndWriteStruct should
2008 be called. The function can be used to group some objects or to implement the write function for a
2009 some user object (see CvTypeInfo).
2010 @param fs File storage
2011 @param name Name of the written structure. The structure can be accessed by this name when the
2012 storage is read.
2013 @param struct_flags A combination one of the following values:
2014 - **CV_NODE_SEQ** the written structure is a sequence (see discussion of CvFileStorage ),
2015 that is, its elements do not have a name.
2016 - **CV_NODE_MAP** the written structure is a map (see discussion of CvFileStorage ), that
2017 is, all its elements have names.
2018 One and only one of the two above flags must be specified
2019 - **CV_NODE_FLOW** the optional flag that makes sense only for YAML streams. It means that
2020 the structure is written as a flow (not as a block), which is more compact. It is
2021 recommended to use this flag for structures or arrays whose elements are all scalars.
2022 @param type_name Optional parameter - the object type name. In
2023 case of XML it is written as a type_id attribute of the structure opening tag. In the case of
2024 YAML it is written after a colon following the structure name (see the example in
2025 CvFileStorage description). Mainly it is used with user objects. When the storage is read, the
2026 encoded type name is used to determine the object type (see CvTypeInfo and cvFindType ).
2027 @param attributes This parameter is not used in the current implementation
2028 */
2029 CVAPI(void) cvStartWriteStruct( CvFileStorage* fs, const char* name,
2030 int struct_flags, const char* type_name CV_DEFAULT(NULL),
2031 CvAttrList attributes CV_DEFAULT(cvAttrList()));
2032
2033 /** @brief Finishes writing to a file node collection.
2034 @param fs File storage
2035 @sa cvStartWriteStruct.
2036 */
2037 CVAPI(void) cvEndWriteStruct( CvFileStorage* fs );
2038
2039 /** @brief Writes an integer value.
2040
2041 The function writes a single integer value (with or without a name) to the file storage.
2042 @param fs File storage
2043 @param name Name of the written value. Should be NULL if and only if the parent structure is a
2044 sequence.
2045 @param value The written value
2046 */
2047 CVAPI(void) cvWriteInt( CvFileStorage* fs, const char* name, int value );
2048
2049 /** @brief Writes a floating-point value.
2050
2051 The function writes a single floating-point value (with or without a name) to file storage. Special
2052 values are encoded as follows: NaN (Not A Number) as .NaN, infinity as +.Inf or -.Inf.
2053
2054 The following example shows how to use the low-level writing functions to store custom structures,
2055 such as termination criteria, without registering a new type. :
2056 @code
2057 void write_termcriteria( CvFileStorage* fs, const char* struct_name,
2058 CvTermCriteria* termcrit )
2059 {
2060 cvStartWriteStruct( fs, struct_name, CV_NODE_MAP, NULL, cvAttrList(0,0));
2061 cvWriteComment( fs, "termination criteria", 1 ); // just a description
2062 if( termcrit->type & CV_TERMCRIT_ITER )
2063 cvWriteInteger( fs, "max_iterations", termcrit->max_iter );
2064 if( termcrit->type & CV_TERMCRIT_EPS )
2065 cvWriteReal( fs, "accuracy", termcrit->epsilon );
2066 cvEndWriteStruct( fs );
2067 }
2068 @endcode
2069 @param fs File storage
2070 @param name Name of the written value. Should be NULL if and only if the parent structure is a
2071 sequence.
2072 @param value The written value
2073 */
2074 CVAPI(void) cvWriteReal( CvFileStorage* fs, const char* name, double value );
2075
2076 /** @brief Writes a text string.
2077
2078 The function writes a text string to file storage.
2079 @param fs File storage
2080 @param name Name of the written string . Should be NULL if and only if the parent structure is a
2081 sequence.
2082 @param str The written text string
2083 @param quote If non-zero, the written string is put in quotes, regardless of whether they are
2084 required. Otherwise, if the flag is zero, quotes are used only when they are required (e.g. when
2085 the string starts with a digit or contains spaces).
2086 */
2087 CVAPI(void) cvWriteString( CvFileStorage* fs, const char* name,
2088 const char* str, int quote CV_DEFAULT(0) );
2089
2090 /** @brief Writes a comment.
2091
2092 The function writes a comment into file storage. The comments are skipped when the storage is read.
2093 @param fs File storage
2094 @param comment The written comment, single-line or multi-line
2095 @param eol_comment If non-zero, the function tries to put the comment at the end of current line.
2096 If the flag is zero, if the comment is multi-line, or if it does not fit at the end of the current
2097 line, the comment starts a new line.
2098 */
2099 CVAPI(void) cvWriteComment( CvFileStorage* fs, const char* comment,
2100 int eol_comment );
2101
2102 /** @brief Writes an object to file storage.
2103
2104 The function writes an object to file storage. First, the appropriate type info is found using
2105 cvTypeOf. Then, the write method associated with the type info is called.
2106
2107 Attributes are used to customize the writing procedure. The standard types support the following
2108 attributes (all the dt attributes have the same format as in cvWriteRawData):
2109
2110 -# CvSeq
2111 - **header_dt** description of user fields of the sequence header that follow CvSeq, or
2112 CvChain (if the sequence is a Freeman chain) or CvContour (if the sequence is a contour or
2113 point sequence)
2114 - **dt** description of the sequence elements.
2115 - **recursive** if the attribute is present and is not equal to "0" or "false", the whole
2116 tree of sequences (contours) is stored.
2117 -# CvGraph
2118 - **header_dt** description of user fields of the graph header that follows CvGraph;
2119 - **vertex_dt** description of user fields of graph vertices
2120 - **edge_dt** description of user fields of graph edges (note that the edge weight is
2121 always written, so there is no need to specify it explicitly)
2122
2123 Below is the code that creates the YAML file shown in the CvFileStorage description:
2124 @code
2125 #include "cxcore.h"
2126
2127 int main( int argc, char** argv )
2128 {
2129 CvMat* mat = cvCreateMat( 3, 3, CV_32F );
2130 CvFileStorage* fs = cvOpenFileStorage( "example.yml", 0, CV_STORAGE_WRITE );
2131
2132 cvSetIdentity( mat );
2133 cvWrite( fs, "A", mat, cvAttrList(0,0) );
2134
2135 cvReleaseFileStorage( &fs );
2136 cvReleaseMat( &mat );
2137 return 0;
2138 }
2139 @endcode
2140 @param fs File storage
2141 @param name Name of the written object. Should be NULL if and only if the parent structure is a
2142 sequence.
2143 @param ptr Pointer to the object
2144 @param attributes The attributes of the object. They are specific for each particular type (see
2145 the discussion below).
2146 */
2147 CVAPI(void) cvWrite( CvFileStorage* fs, const char* name, const void* ptr,
2148 CvAttrList attributes CV_DEFAULT(cvAttrList()));
2149
2150 /** @brief Starts the next stream.
2151
2152 The function finishes the currently written stream and starts the next stream. In the case of XML
2153 the file with multiple streams looks like this:
2154 @code{.xml}
2155 <opencv_storage>
2156 <!-- stream #1 data -->
2157 </opencv_storage>
2158 <opencv_storage>
2159 <!-- stream #2 data -->
2160 </opencv_storage>
2161 ...
2162 @endcode
2163 The YAML file will look like this:
2164 @code{.yaml}
2165 %YAML:1.0
2166 # stream #1 data
2167 ...
2168 ---
2169 # stream #2 data
2170 @endcode
2171 This is useful for concatenating files or for resuming the writing process.
2172 @param fs File storage
2173 */
2174 CVAPI(void) cvStartNextStream( CvFileStorage* fs );
2175
2176 /** @brief Writes multiple numbers.
2177
2178 The function writes an array, whose elements consist of single or multiple numbers. The function
2179 call can be replaced with a loop containing a few cvWriteInt and cvWriteReal calls, but a single
2180 call is more efficient. Note that because none of the elements have a name, they should be written
2181 to a sequence rather than a map.
2182 @param fs File storage
2183 @param src Pointer to the written array
2184 @param len Number of the array elements to write
2185 @param dt Specification of each array element, see @ref format_spec "format specification"
2186 */
2187 CVAPI(void) cvWriteRawData( CvFileStorage* fs, const void* src,
2188 int len, const char* dt );
2189
2190 /** @brief Returns a unique pointer for a given name.
2191
2192 The function returns a unique pointer for each particular file node name. This pointer can be then
2193 passed to the cvGetFileNode function that is faster than cvGetFileNodeByName because it compares
2194 text strings by comparing pointers rather than the strings' content.
2195
2196 Consider the following example where an array of points is encoded as a sequence of 2-entry maps:
2197 @code
2198 points:
2199 - { x: 10, y: 10 }
2200 - { x: 20, y: 20 }
2201 - { x: 30, y: 30 }
2202 # ...
2203 @endcode
2204 Then, it is possible to get hashed "x" and "y" pointers to speed up decoding of the points. :
2205 @code
2206 #include "cxcore.h"
2207
2208 int main( int argc, char** argv )
2209 {
2210 CvFileStorage* fs = cvOpenFileStorage( "points.yml", 0, CV_STORAGE_READ );
2211 CvStringHashNode* x_key = cvGetHashedNode( fs, "x", -1, 1 );
2212 CvStringHashNode* y_key = cvGetHashedNode( fs, "y", -1, 1 );
2213 CvFileNode* points = cvGetFileNodeByName( fs, 0, "points" );
2214
2215 if( CV_NODE_IS_SEQ(points->tag) )
2216 {
2217 CvSeq* seq = points->data.seq;
2218 int i, total = seq->total;
2219 CvSeqReader reader;
2220 cvStartReadSeq( seq, &reader, 0 );
2221 for( i = 0; i < total; i++ )
2222 {
2223 CvFileNode* pt = (CvFileNode*)reader.ptr;
2224 #if 1 // faster variant
2225 CvFileNode* xnode = cvGetFileNode( fs, pt, x_key, 0 );
2226 CvFileNode* ynode = cvGetFileNode( fs, pt, y_key, 0 );
2227 assert( xnode && CV_NODE_IS_INT(xnode->tag) &&
2228 ynode && CV_NODE_IS_INT(ynode->tag));
2229 int x = xnode->data.i; // or x = cvReadInt( xnode, 0 );
2230 int y = ynode->data.i; // or y = cvReadInt( ynode, 0 );
2231 #elif 1 // slower variant; does not use x_key & y_key
2232 CvFileNode* xnode = cvGetFileNodeByName( fs, pt, "x" );
2233 CvFileNode* ynode = cvGetFileNodeByName( fs, pt, "y" );
2234 assert( xnode && CV_NODE_IS_INT(xnode->tag) &&
2235 ynode && CV_NODE_IS_INT(ynode->tag));
2236 int x = xnode->data.i; // or x = cvReadInt( xnode, 0 );
2237 int y = ynode->data.i; // or y = cvReadInt( ynode, 0 );
2238 #else // the slowest yet the easiest to use variant
2239 int x = cvReadIntByName( fs, pt, "x", 0 );
2240 int y = cvReadIntByName( fs, pt, "y", 0 );
2241 #endif
2242 CV_NEXT_SEQ_ELEM( seq->elem_size, reader );
2243 printf("
2244 }
2245 }
2246 cvReleaseFileStorage( &fs );
2247 return 0;
2248 }
2249 @endcode
2250 Please note that whatever method of accessing a map you are using, it is still much slower than
2251 using plain sequences; for example, in the above example, it is more efficient to encode the points
2252 as pairs of integers in a single numeric sequence.
2253 @param fs File storage
2254 @param name Literal node name
2255 @param len Length of the name (if it is known apriori), or -1 if it needs to be calculated
2256 @param create_missing Flag that specifies, whether an absent key should be added into the hash table
2257 */
2258 CVAPI(CvStringHashNode*) cvGetHashedKey( CvFileStorage* fs, const char* name,
2259 int len CV_DEFAULT(-1),
2260 int create_missing CV_DEFAULT(0));
2261
2262 /** @brief Retrieves one of the top-level nodes of the file storage.
2263
2264 The function returns one of the top-level file nodes. The top-level nodes do not have a name, they
2265 correspond to the streams that are stored one after another in the file storage. If the index is out
2266 of range, the function returns a NULL pointer, so all the top-level nodes can be iterated by
2267 subsequent calls to the function with stream_index=0,1,..., until the NULL pointer is returned.
2268 This function can be used as a base for recursive traversal of the file storage.
2269 @param fs File storage
2270 @param stream_index Zero-based index of the stream. See cvStartNextStream . In most cases,
2271 there is only one stream in the file; however, there can be several.
2272 */
2273 CVAPI(CvFileNode*) cvGetRootFileNode( const CvFileStorage* fs,
2274 int stream_index CV_DEFAULT(0) );
2275
2276 /** @brief Finds a node in a map or file storage.
2277
2278 The function finds a file node. It is a faster version of cvGetFileNodeByName (see
2279 cvGetHashedKey discussion). Also, the function can insert a new node, if it is not in the map yet.
2280 @param fs File storage
2281 @param map The parent map. If it is NULL, the function searches a top-level node. If both map and
2282 key are NULLs, the function returns the root file node - a map that contains top-level nodes.
2283 @param key Unique pointer to the node name, retrieved with cvGetHashedKey
2284 @param create_missing Flag that specifies whether an absent node should be added to the map
2285 */
2286 CVAPI(CvFileNode*) cvGetFileNode( CvFileStorage* fs, CvFileNode* map,
2287 const CvStringHashNode* key,
2288 int create_missing CV_DEFAULT(0) );
2289
2290 /** @brief Finds a node in a map or file storage.
2291
2292 The function finds a file node by name. The node is searched either in map or, if the pointer is
2293 NULL, among the top-level file storage nodes. Using this function for maps and cvGetSeqElem (or
2294 sequence reader) for sequences, it is possible to navigate through the file storage. To speed up
2295 multiple queries for a certain key (e.g., in the case of an array of structures) one may use a
2296 combination of cvGetHashedKey and cvGetFileNode.
2297 @param fs File storage
2298 @param map The parent map. If it is NULL, the function searches in all the top-level nodes
2299 (streams), starting with the first one.
2300 @param name The file node name
2301 */
2302 CVAPI(CvFileNode*) cvGetFileNodeByName( const CvFileStorage* fs,
2303 const CvFileNode* map,
2304 const char* name );
2305
2306 /** @brief Retrieves an integer value from a file node.
2307
2308 The function returns an integer that is represented by the file node. If the file node is NULL, the
2309 default_value is returned (thus, it is convenient to call the function right after cvGetFileNode
2310 without checking for a NULL pointer). If the file node has type CV_NODE_INT, then node-\>data.i is
2311 returned. If the file node has type CV_NODE_REAL, then node-\>data.f is converted to an integer
2312 and returned. Otherwise the error is reported.
2313 @param node File node
2314 @param default_value The value that is returned if node is NULL
2315 */
2316 CV_INLINE int cvReadInt( const CvFileNode* node, int default_value CV_DEFAULT(0) )
2317 {
2318 return !node ? default_value :
2319 CV_NODE_IS_INT(node->tag) ? node->data.i :
2320 CV_NODE_IS_REAL(node->tag) ? cvRound(node->data.f) : 0x7fffffff;
2321 }
2322
2323 /** @brief Finds a file node and returns its value.
2324
2325 The function is a simple superposition of cvGetFileNodeByName and cvReadInt.
2326 @param fs File storage
2327 @param map The parent map. If it is NULL, the function searches a top-level node.
2328 @param name The node name
2329 @param default_value The value that is returned if the file node is not found
2330 */
2331 CV_INLINE int cvReadIntByName( const CvFileStorage* fs, const CvFileNode* map,
2332 const char* name, int default_value CV_DEFAULT(0) )
2333 {
2334 return cvReadInt( cvGetFileNodeByName( fs, map, name ), default_value );
2335 }
2336
2337 /** @brief Retrieves a floating-point value from a file node.
2338
2339 The function returns a floating-point value that is represented by the file node. If the file node
2340 is NULL, the default_value is returned (thus, it is convenient to call the function right after
2341 cvGetFileNode without checking for a NULL pointer). If the file node has type CV_NODE_REAL ,
2342 then node-\>data.f is returned. If the file node has type CV_NODE_INT , then node-:math:\>data.f
2343 is converted to floating-point and returned. Otherwise the result is not determined.
2344 @param node File node
2345 @param default_value The value that is returned if node is NULL
2346 */
2347 CV_INLINE double cvReadReal( const CvFileNode* node, double default_value CV_DEFAULT(0.) )
2348 {
2349 return !node ? default_value :
2350 CV_NODE_IS_INT(node->tag) ? (double)node->data.i :
2351 CV_NODE_IS_REAL(node->tag) ? node->data.f : 1e300;
2352 }
2353
2354 /** @brief Finds a file node and returns its value.
2355
2356 The function is a simple superposition of cvGetFileNodeByName and cvReadReal .
2357 @param fs File storage
2358 @param map The parent map. If it is NULL, the function searches a top-level node.
2359 @param name The node name
2360 @param default_value The value that is returned if the file node is not found
2361 */
2362 CV_INLINE double cvReadRealByName( const CvFileStorage* fs, const CvFileNode* map,
2363 const char* name, double default_value CV_DEFAULT(0.) )
2364 {
2365 return cvReadReal( cvGetFileNodeByName( fs, map, name ), default_value );
2366 }
2367
2368 /** @brief Retrieves a text string from a file node.
2369
2370 The function returns a text string that is represented by the file node. If the file node is NULL,
2371 the default_value is returned (thus, it is convenient to call the function right after
2372 cvGetFileNode without checking for a NULL pointer). If the file node has type CV_NODE_STR , then
2373 node-:math:\>data.str.ptr is returned. Otherwise the result is not determined.
2374 @param node File node
2375 @param default_value The value that is returned if node is NULL
2376 */
cvReadString(const CvFileNode * node,const char * default_value CV_DEFAULT (NULL))2377 CV_INLINE const char* cvReadString( const CvFileNode* node,
2378 const char* default_value CV_DEFAULT(NULL) )
2379 {
2380 return !node ? default_value : CV_NODE_IS_STRING(node->tag) ? node->data.str.ptr : 0;
2381 }
2382
2383 /** @brief Finds a file node by its name and returns its value.
2384
2385 The function is a simple superposition of cvGetFileNodeByName and cvReadString .
2386 @param fs File storage
2387 @param map The parent map. If it is NULL, the function searches a top-level node.
2388 @param name The node name
2389 @param default_value The value that is returned if the file node is not found
2390 */
cvReadStringByName(const CvFileStorage * fs,const CvFileNode * map,const char * name,const char * default_value CV_DEFAULT (NULL))2391 CV_INLINE const char* cvReadStringByName( const CvFileStorage* fs, const CvFileNode* map,
2392 const char* name, const char* default_value CV_DEFAULT(NULL) )
2393 {
2394 return cvReadString( cvGetFileNodeByName( fs, map, name ), default_value );
2395 }
2396
2397
2398 /** @brief Decodes an object and returns a pointer to it.
2399
2400 The function decodes a user object (creates an object in a native representation from the file
2401 storage subtree) and returns it. The object to be decoded must be an instance of a registered type
2402 that supports the read method (see CvTypeInfo). The type of the object is determined by the type
2403 name that is encoded in the file. If the object is a dynamic structure, it is created either in
2404 memory storage and passed to cvOpenFileStorage or, if a NULL pointer was passed, in temporary
2405 memory storage, which is released when cvReleaseFileStorage is called. Otherwise, if the object is
2406 not a dynamic structure, it is created in a heap and should be released with a specialized function
2407 or by using the generic cvRelease.
2408 @param fs File storage
2409 @param node The root object node
2410 @param attributes Unused parameter
2411 */
2412 CVAPI(void*) cvRead( CvFileStorage* fs, CvFileNode* node,
2413 CvAttrList* attributes CV_DEFAULT(NULL));
2414
2415 /** @brief Finds an object by name and decodes it.
2416
2417 The function is a simple superposition of cvGetFileNodeByName and cvRead.
2418 @param fs File storage
2419 @param map The parent map. If it is NULL, the function searches a top-level node.
2420 @param name The node name
2421 @param attributes Unused parameter
2422 */
cvReadByName(CvFileStorage * fs,const CvFileNode * map,const char * name,CvAttrList * attributes CV_DEFAULT (NULL))2423 CV_INLINE void* cvReadByName( CvFileStorage* fs, const CvFileNode* map,
2424 const char* name, CvAttrList* attributes CV_DEFAULT(NULL) )
2425 {
2426 return cvRead( fs, cvGetFileNodeByName( fs, map, name ), attributes );
2427 }
2428
2429
2430 /** @brief Initializes the file node sequence reader.
2431
2432 The function initializes the sequence reader to read data from a file node. The initialized reader
2433 can be then passed to cvReadRawDataSlice.
2434 @param fs File storage
2435 @param src The file node (a sequence) to read numbers from
2436 @param reader Pointer to the sequence reader
2437 */
2438 CVAPI(void) cvStartReadRawData( const CvFileStorage* fs, const CvFileNode* src,
2439 CvSeqReader* reader );
2440
2441 /** @brief Initializes file node sequence reader.
2442
2443 The function reads one or more elements from the file node, representing a sequence, to a
2444 user-specified array. The total number of read sequence elements is a product of total and the
2445 number of components in each array element. For example, if dt=2if, the function will read total\*3
2446 sequence elements. As with any sequence, some parts of the file node sequence can be skipped or read
2447 repeatedly by repositioning the reader using cvSetSeqReaderPos.
2448 @param fs File storage
2449 @param reader The sequence reader. Initialize it with cvStartReadRawData .
2450 @param count The number of elements to read
2451 @param dst Pointer to the destination array
2452 @param dt Specification of each array element. It has the same format as in cvWriteRawData .
2453 */
2454 CVAPI(void) cvReadRawDataSlice( const CvFileStorage* fs, CvSeqReader* reader,
2455 int count, void* dst, const char* dt );
2456
2457 /** @brief Reads multiple numbers.
2458
2459 The function reads elements from a file node that represents a sequence of scalars.
2460 @param fs File storage
2461 @param src The file node (a sequence) to read numbers from
2462 @param dst Pointer to the destination array
2463 @param dt Specification of each array element. It has the same format as in cvWriteRawData .
2464 */
2465 CVAPI(void) cvReadRawData( const CvFileStorage* fs, const CvFileNode* src,
2466 void* dst, const char* dt );
2467
2468 /** @brief Writes a file node to another file storage.
2469
2470 The function writes a copy of a file node to file storage. Possible applications of the function are
2471 merging several file storages into one and conversion between XML and YAML formats.
2472 @param fs Destination file storage
2473 @param new_node_name New name of the file node in the destination file storage. To keep the
2474 existing name, use cvcvGetFileNodeName
2475 @param node The written node
2476 @param embed If the written node is a collection and this parameter is not zero, no extra level of
2477 hierarchy is created. Instead, all the elements of node are written into the currently written
2478 structure. Of course, map elements can only be embedded into another map, and sequence elements
2479 can only be embedded into another sequence.
2480 */
2481 CVAPI(void) cvWriteFileNode( CvFileStorage* fs, const char* new_node_name,
2482 const CvFileNode* node, int embed );
2483
2484 /** @brief Returns the name of a file node.
2485
2486 The function returns the name of a file node or NULL, if the file node does not have a name or if
2487 node is NULL.
2488 @param node File node
2489 */
2490 CVAPI(const char*) cvGetFileNodeName( const CvFileNode* node );
2491
2492 /*********************************** Adding own types ***********************************/
2493
2494 /** @brief Registers a new type.
2495
2496 The function registers a new type, which is described by info . The function creates a copy of the
2497 structure, so the user should delete it after calling the function.
2498 @param info Type info structure
2499 */
2500 CVAPI(void) cvRegisterType( const CvTypeInfo* info );
2501
2502 /** @brief Unregisters the type.
2503
2504 The function unregisters a type with a specified name. If the name is unknown, it is possible to
2505 locate the type info by an instance of the type using cvTypeOf or by iterating the type list,
2506 starting from cvFirstType, and then calling cvUnregisterType(info-\>typeName).
2507 @param type_name Name of an unregistered type
2508 */
2509 CVAPI(void) cvUnregisterType( const char* type_name );
2510
2511 /** @brief Returns the beginning of a type list.
2512
2513 The function returns the first type in the list of registered types. Navigation through the list can
2514 be done via the prev and next fields of the CvTypeInfo structure.
2515 */
2516 CVAPI(CvTypeInfo*) cvFirstType(void);
2517
2518 /** @brief Finds a type by its name.
2519
2520 The function finds a registered type by its name. It returns NULL if there is no type with the
2521 specified name.
2522 @param type_name Type name
2523 */
2524 CVAPI(CvTypeInfo*) cvFindType( const char* type_name );
2525
2526 /** @brief Returns the type of an object.
2527
2528 The function finds the type of a given object. It iterates through the list of registered types and
2529 calls the is_instance function/method for every type info structure with that object until one of
2530 them returns non-zero or until the whole list has been traversed. In the latter case, the function
2531 returns NULL.
2532 @param struct_ptr The object pointer
2533 */
2534 CVAPI(CvTypeInfo*) cvTypeOf( const void* struct_ptr );
2535
2536 /** @brief Releases an object.
2537
2538 The function finds the type of a given object and calls release with the double pointer.
2539 @param struct_ptr Double pointer to the object
2540 */
2541 CVAPI(void) cvRelease( void** struct_ptr );
2542
2543 /** @brief Makes a clone of an object.
2544
2545 The function finds the type of a given object and calls clone with the passed object. Of course, if
2546 you know the object type, for example, struct_ptr is CvMat\*, it is faster to call the specific
2547 function, like cvCloneMat.
2548 @param struct_ptr The object to clone
2549 */
2550 CVAPI(void*) cvClone( const void* struct_ptr );
2551
2552 /** @brief Saves an object to a file.
2553
2554 The function saves an object to a file. It provides a simple interface to cvWrite .
2555 @param filename File name
2556 @param struct_ptr Object to save
2557 @param name Optional object name. If it is NULL, the name will be formed from filename .
2558 @param comment Optional comment to put in the beginning of the file
2559 @param attributes Optional attributes passed to cvWrite
2560 */
2561 CVAPI(void) cvSave( const char* filename, const void* struct_ptr,
2562 const char* name CV_DEFAULT(NULL),
2563 const char* comment CV_DEFAULT(NULL),
2564 CvAttrList attributes CV_DEFAULT(cvAttrList()));
2565
2566 /** @brief Loads an object from a file.
2567
2568 The function loads an object from a file. It basically reads the specified file, find the first
2569 top-level node and calls cvRead for that node. If the file node does not have type information or
2570 the type information can not be found by the type name, the function returns NULL. After the object
2571 is loaded, the file storage is closed and all the temporary buffers are deleted. Thus, to load a
2572 dynamic structure, such as a sequence, contour, or graph, one should pass a valid memory storage
2573 destination to the function.
2574 @param filename File name
2575 @param memstorage Memory storage for dynamic structures, such as CvSeq or CvGraph . It is not used
2576 for matrices or images.
2577 @param name Optional object name. If it is NULL, the first top-level object in the storage will be
2578 loaded.
2579 @param real_name Optional output parameter that will contain the name of the loaded object
2580 (useful if name=NULL )
2581 */
2582 CVAPI(void*) cvLoad( const char* filename,
2583 CvMemStorage* memstorage CV_DEFAULT(NULL),
2584 const char* name CV_DEFAULT(NULL),
2585 const char** real_name CV_DEFAULT(NULL) );
2586
2587 /*********************************** Measuring Execution Time ***************************/
2588
2589 /** helper functions for RNG initialization and accurate time measurement:
2590 uses internal clock counter on x86 */
2591 CVAPI(int64) cvGetTickCount( void );
2592 CVAPI(double) cvGetTickFrequency( void );
2593
2594 /*********************************** CPU capabilities ***********************************/
2595
2596 CVAPI(int) cvCheckHardwareSupport(int feature);
2597
2598 /*********************************** Multi-Threading ************************************/
2599
2600 /** retrieve/set the number of threads used in OpenMP implementations */
2601 CVAPI(int) cvGetNumThreads( void );
2602 CVAPI(void) cvSetNumThreads( int threads CV_DEFAULT(0) );
2603 /** get index of the thread being executed */
2604 CVAPI(int) cvGetThreadNum( void );
2605
2606
2607 /********************************** Error Handling **************************************/
2608
2609 /** Get current OpenCV error status */
2610 CVAPI(int) cvGetErrStatus( void );
2611
2612 /** Sets error status silently */
2613 CVAPI(void) cvSetErrStatus( int status );
2614
2615 #define CV_ErrModeLeaf 0 /* Print error and exit program */
2616 #define CV_ErrModeParent 1 /* Print error and continue */
2617 #define CV_ErrModeSilent 2 /* Don't print and continue */
2618
2619 /** Retrives current error processing mode */
2620 CVAPI(int) cvGetErrMode( void );
2621
2622 /** Sets error processing mode, returns previously used mode */
2623 CVAPI(int) cvSetErrMode( int mode );
2624
2625 /** Sets error status and performs some additonal actions (displaying message box,
2626 writing message to stderr, terminating application etc.)
2627 depending on the current error mode */
2628 CVAPI(void) cvError( int status, const char* func_name,
2629 const char* err_msg, const char* file_name, int line );
2630
2631 /** Retrieves textual description of the error given its code */
2632 CVAPI(const char*) cvErrorStr( int status );
2633
2634 /** Retrieves detailed information about the last error occured */
2635 CVAPI(int) cvGetErrInfo( const char** errcode_desc, const char** description,
2636 const char** filename, int* line );
2637
2638 /** Maps IPP error codes to the counterparts from OpenCV */
2639 CVAPI(int) cvErrorFromIppStatus( int ipp_status );
2640
2641 typedef int (CV_CDECL *CvErrorCallback)( int status, const char* func_name,
2642 const char* err_msg, const char* file_name, int line, void* userdata );
2643
2644 /** Assigns a new error-handling function */
2645 CVAPI(CvErrorCallback) cvRedirectError( CvErrorCallback error_handler,
2646 void* userdata CV_DEFAULT(NULL),
2647 void** prev_userdata CV_DEFAULT(NULL) );
2648
2649 /** Output nothing */
2650 CVAPI(int) cvNulDevReport( int status, const char* func_name, const char* err_msg,
2651 const char* file_name, int line, void* userdata );
2652
2653 /** Output to console(fprintf(stderr,...)) */
2654 CVAPI(int) cvStdErrReport( int status, const char* func_name, const char* err_msg,
2655 const char* file_name, int line, void* userdata );
2656
2657 /** Output to MessageBox(WIN32) */
2658 CVAPI(int) cvGuiBoxReport( int status, const char* func_name, const char* err_msg,
2659 const char* file_name, int line, void* userdata );
2660
2661 #define OPENCV_ERROR(status,func,context) \
2662 cvError((status),(func),(context),__FILE__,__LINE__)
2663
2664 #define OPENCV_ASSERT(expr,func,context) \
2665 {if (! (expr)) \
2666 {OPENCV_ERROR(CV_StsInternal,(func),(context));}}
2667
2668 #define OPENCV_CALL( Func ) \
2669 { \
2670 Func; \
2671 }
2672
2673
2674 /** CV_FUNCNAME macro defines icvFuncName constant which is used by CV_ERROR macro */
2675 #ifdef CV_NO_FUNC_NAMES
2676 #define CV_FUNCNAME( Name )
2677 #define cvFuncName ""
2678 #else
2679 #define CV_FUNCNAME( Name ) \
2680 static char cvFuncName[] = Name
2681 #endif
2682
2683
2684 /**
2685 CV_ERROR macro unconditionally raises error with passed code and message.
2686 After raising error, control will be transferred to the exit label.
2687 */
2688 #define CV_ERROR( Code, Msg ) \
2689 { \
2690 cvError( (Code), cvFuncName, Msg, __FILE__, __LINE__ ); \
2691 __CV_EXIT__; \
2692 }
2693
2694 /**
2695 CV_CHECK macro checks error status after CV (or IPL)
2696 function call. If error detected, control will be transferred to the exit
2697 label.
2698 */
2699 #define CV_CHECK() \
2700 { \
2701 if( cvGetErrStatus() < 0 ) \
2702 CV_ERROR( CV_StsBackTrace, "Inner function failed." ); \
2703 }
2704
2705
2706 /**
2707 CV_CALL macro calls CV (or IPL) function, checks error status and
2708 signals a error if the function failed. Useful in "parent node"
2709 error procesing mode
2710 */
2711 #define CV_CALL( Func ) \
2712 { \
2713 Func; \
2714 CV_CHECK(); \
2715 }
2716
2717
2718 /** Runtime assertion macro */
2719 #define CV_ASSERT( Condition ) \
2720 { \
2721 if( !(Condition) ) \
2722 CV_ERROR( CV_StsInternal, "Assertion: " #Condition " failed" ); \
2723 }
2724
2725 #define __CV_BEGIN__ {
2726 #define __CV_END__ goto exit; exit: ; }
2727 #define __CV_EXIT__ goto exit
2728
2729 /** @} core_c */
2730
2731 #ifdef __cplusplus
2732 } // extern "C"
2733 #endif
2734
2735 #ifdef __cplusplus
2736
2737 //! @addtogroup core_c_glue
2738 //! @{
2739
2740 //! class for automatic module/RTTI data registration/unregistration
2741 struct CV_EXPORTS CvType
2742 {
2743 CvType( const char* type_name,
2744 CvIsInstanceFunc is_instance, CvReleaseFunc release=0,
2745 CvReadFunc read=0, CvWriteFunc write=0, CvCloneFunc clone=0 );
2746 ~CvType();
2747 CvTypeInfo* info;
2748
2749 static CvTypeInfo* first;
2750 static CvTypeInfo* last;
2751 };
2752
2753 //! @}
2754
2755 #include "opencv2/core/utility.hpp"
2756
2757 namespace cv
2758 {
2759
2760 //! @addtogroup core_c_glue
2761 //! @{
2762
2763 /////////////////////////////////////////// glue ///////////////////////////////////////////
2764
2765 //! converts array (CvMat or IplImage) to cv::Mat
2766 CV_EXPORTS Mat cvarrToMat(const CvArr* arr, bool copyData=false,
2767 bool allowND=true, int coiMode=0,
2768 AutoBuffer<double>* buf=0);
2769
2770 static inline Mat cvarrToMatND(const CvArr* arr, bool copyData=false, int coiMode=0)
2771 {
2772 return cvarrToMat(arr, copyData, true, coiMode);
2773 }
2774
2775
2776 //! extracts Channel of Interest from CvMat or IplImage and makes cv::Mat out of it.
2777 CV_EXPORTS void extractImageCOI(const CvArr* arr, OutputArray coiimg, int coi=-1);
2778 //! inserts single-channel cv::Mat into a multi-channel CvMat or IplImage
2779 CV_EXPORTS void insertImageCOI(InputArray coiimg, CvArr* arr, int coi=-1);
2780
2781
2782
2783 ////// specialized implementations of DefaultDeleter::operator() for classic OpenCV types //////
2784
2785 template<> CV_EXPORTS void DefaultDeleter<CvMat>::operator ()(CvMat* obj) const;
2786 template<> CV_EXPORTS void DefaultDeleter<IplImage>::operator ()(IplImage* obj) const;
2787 template<> CV_EXPORTS void DefaultDeleter<CvMatND>::operator ()(CvMatND* obj) const;
2788 template<> CV_EXPORTS void DefaultDeleter<CvSparseMat>::operator ()(CvSparseMat* obj) const;
2789 template<> CV_EXPORTS void DefaultDeleter<CvMemStorage>::operator ()(CvMemStorage* obj) const;
2790
2791 ////////////// convenient wrappers for operating old-style dynamic structures //////////////
2792
2793 template<typename _Tp> class SeqIterator;
2794
2795 typedef Ptr<CvMemStorage> MemStorage;
2796
2797 /*!
2798 Template Sequence Class derived from CvSeq
2799
2800 The class provides more convenient access to sequence elements,
2801 STL-style operations and iterators.
2802
2803 \note The class is targeted for simple data types,
2804 i.e. no constructors or destructors
2805 are called for the sequence elements.
2806 */
2807 template<typename _Tp> class Seq
2808 {
2809 public:
2810 typedef SeqIterator<_Tp> iterator;
2811 typedef SeqIterator<_Tp> const_iterator;
2812
2813 //! the default constructor
2814 Seq();
2815 //! the constructor for wrapping CvSeq structure. The real element type in CvSeq should match _Tp.
2816 Seq(const CvSeq* seq);
2817 //! creates the empty sequence that resides in the specified storage
2818 Seq(MemStorage& storage, int headerSize = sizeof(CvSeq));
2819 //! returns read-write reference to the specified element
2820 _Tp& operator [](int idx);
2821 //! returns read-only reference to the specified element
2822 const _Tp& operator[](int idx) const;
2823 //! returns iterator pointing to the beginning of the sequence
2824 SeqIterator<_Tp> begin() const;
2825 //! returns iterator pointing to the element following the last sequence element
2826 SeqIterator<_Tp> end() const;
2827 //! returns the number of elements in the sequence
2828 size_t size() const;
2829 //! returns the type of sequence elements (CV_8UC1 ... CV_64FC(CV_CN_MAX) ...)
2830 int type() const;
2831 //! returns the depth of sequence elements (CV_8U ... CV_64F)
2832 int depth() const;
2833 //! returns the number of channels in each sequence element
2834 int channels() const;
2835 //! returns the size of each sequence element
2836 size_t elemSize() const;
2837 //! returns index of the specified sequence element
2838 size_t index(const _Tp& elem) const;
2839 //! appends the specified element to the end of the sequence
2840 void push_back(const _Tp& elem);
2841 //! appends the specified element to the front of the sequence
2842 void push_front(const _Tp& elem);
2843 //! appends zero or more elements to the end of the sequence
2844 void push_back(const _Tp* elems, size_t count);
2845 //! appends zero or more elements to the front of the sequence
2846 void push_front(const _Tp* elems, size_t count);
2847 //! inserts the specified element to the specified position
2848 void insert(int idx, const _Tp& elem);
2849 //! inserts zero or more elements to the specified position
2850 void insert(int idx, const _Tp* elems, size_t count);
2851 //! removes element at the specified position
2852 void remove(int idx);
2853 //! removes the specified subsequence
2854 void remove(const Range& r);
2855
2856 //! returns reference to the first sequence element
2857 _Tp& front();
2858 //! returns read-only reference to the first sequence element
2859 const _Tp& front() const;
2860 //! returns reference to the last sequence element
2861 _Tp& back();
2862 //! returns read-only reference to the last sequence element
2863 const _Tp& back() const;
2864 //! returns true iff the sequence contains no elements
2865 bool empty() const;
2866
2867 //! removes all the elements from the sequence
2868 void clear();
2869 //! removes the first element from the sequence
2870 void pop_front();
2871 //! removes the last element from the sequence
2872 void pop_back();
2873 //! removes zero or more elements from the beginning of the sequence
2874 void pop_front(_Tp* elems, size_t count);
2875 //! removes zero or more elements from the end of the sequence
2876 void pop_back(_Tp* elems, size_t count);
2877
2878 //! copies the whole sequence or the sequence slice to the specified vector
2879 void copyTo(std::vector<_Tp>& vec, const Range& range=Range::all()) const;
2880 //! returns the vector containing all the sequence elements
2881 operator std::vector<_Tp>() const;
2882
2883 CvSeq* seq;
2884 };
2885
2886
2887 /*!
2888 STL-style Sequence Iterator inherited from the CvSeqReader structure
2889 */
2890 template<typename _Tp> class SeqIterator : public CvSeqReader
2891 {
2892 public:
2893 //! the default constructor
2894 SeqIterator();
2895 //! the constructor setting the iterator to the beginning or to the end of the sequence
2896 SeqIterator(const Seq<_Tp>& seq, bool seekEnd=false);
2897 //! positions the iterator within the sequence
2898 void seek(size_t pos);
2899 //! reports the current iterator position
2900 size_t tell() const;
2901 //! returns reference to the current sequence element
2902 _Tp& operator *();
2903 //! returns read-only reference to the current sequence element
2904 const _Tp& operator *() const;
2905 //! moves iterator to the next sequence element
2906 SeqIterator& operator ++();
2907 //! moves iterator to the next sequence element
2908 SeqIterator operator ++(int) const;
2909 //! moves iterator to the previous sequence element
2910 SeqIterator& operator --();
2911 //! moves iterator to the previous sequence element
2912 SeqIterator operator --(int) const;
2913
2914 //! moves iterator forward by the specified offset (possibly negative)
2915 SeqIterator& operator +=(int);
2916 //! moves iterator backward by the specified offset (possibly negative)
2917 SeqIterator& operator -=(int);
2918
2919 // this is index of the current element module seq->total*2
2920 // (to distinguish between 0 and seq->total)
2921 int index;
2922 };
2923
2924
2925
2926 // bridge C++ => C Seq API
2927 CV_EXPORTS schar* seqPush( CvSeq* seq, const void* element=0);
2928 CV_EXPORTS schar* seqPushFront( CvSeq* seq, const void* element=0);
2929 CV_EXPORTS void seqPop( CvSeq* seq, void* element=0);
2930 CV_EXPORTS void seqPopFront( CvSeq* seq, void* element=0);
2931 CV_EXPORTS void seqPopMulti( CvSeq* seq, void* elements,
2932 int count, int in_front=0 );
2933 CV_EXPORTS void seqRemove( CvSeq* seq, int index );
2934 CV_EXPORTS void clearSeq( CvSeq* seq );
2935 CV_EXPORTS schar* getSeqElem( const CvSeq* seq, int index );
2936 CV_EXPORTS void seqRemoveSlice( CvSeq* seq, CvSlice slice );
2937 CV_EXPORTS void seqInsertSlice( CvSeq* seq, int before_index, const CvArr* from_arr );
2938
Seq()2939 template<typename _Tp> inline Seq<_Tp>::Seq() : seq(0) {}
Seq(const CvSeq * _seq)2940 template<typename _Tp> inline Seq<_Tp>::Seq( const CvSeq* _seq ) : seq((CvSeq*)_seq)
2941 {
2942 CV_Assert(!_seq || _seq->elem_size == sizeof(_Tp));
2943 }
2944
Seq(MemStorage & storage,int headerSize)2945 template<typename _Tp> inline Seq<_Tp>::Seq( MemStorage& storage,
2946 int headerSize )
2947 {
2948 CV_Assert(headerSize >= (int)sizeof(CvSeq));
2949 seq = cvCreateSeq(DataType<_Tp>::type, headerSize, sizeof(_Tp), storage);
2950 }
2951
2952 template<typename _Tp> inline _Tp& Seq<_Tp>::operator [](int idx)
2953 { return *(_Tp*)getSeqElem(seq, idx); }
2954
2955 template<typename _Tp> inline const _Tp& Seq<_Tp>::operator [](int idx) const
2956 { return *(_Tp*)getSeqElem(seq, idx); }
2957
begin()2958 template<typename _Tp> inline SeqIterator<_Tp> Seq<_Tp>::begin() const
2959 { return SeqIterator<_Tp>(*this); }
2960
end()2961 template<typename _Tp> inline SeqIterator<_Tp> Seq<_Tp>::end() const
2962 { return SeqIterator<_Tp>(*this, true); }
2963
size()2964 template<typename _Tp> inline size_t Seq<_Tp>::size() const
2965 { return seq ? seq->total : 0; }
2966
type()2967 template<typename _Tp> inline int Seq<_Tp>::type() const
2968 { return seq ? CV_MAT_TYPE(seq->flags) : 0; }
2969
depth()2970 template<typename _Tp> inline int Seq<_Tp>::depth() const
2971 { return seq ? CV_MAT_DEPTH(seq->flags) : 0; }
2972
channels()2973 template<typename _Tp> inline int Seq<_Tp>::channels() const
2974 { return seq ? CV_MAT_CN(seq->flags) : 0; }
2975
elemSize()2976 template<typename _Tp> inline size_t Seq<_Tp>::elemSize() const
2977 { return seq ? seq->elem_size : 0; }
2978
index(const _Tp & elem)2979 template<typename _Tp> inline size_t Seq<_Tp>::index(const _Tp& elem) const
2980 { return cvSeqElemIdx(seq, &elem); }
2981
push_back(const _Tp & elem)2982 template<typename _Tp> inline void Seq<_Tp>::push_back(const _Tp& elem)
2983 { cvSeqPush(seq, &elem); }
2984
push_front(const _Tp & elem)2985 template<typename _Tp> inline void Seq<_Tp>::push_front(const _Tp& elem)
2986 { cvSeqPushFront(seq, &elem); }
2987
push_back(const _Tp * elem,size_t count)2988 template<typename _Tp> inline void Seq<_Tp>::push_back(const _Tp* elem, size_t count)
2989 { cvSeqPushMulti(seq, elem, (int)count, 0); }
2990
push_front(const _Tp * elem,size_t count)2991 template<typename _Tp> inline void Seq<_Tp>::push_front(const _Tp* elem, size_t count)
2992 { cvSeqPushMulti(seq, elem, (int)count, 1); }
2993
back()2994 template<typename _Tp> inline _Tp& Seq<_Tp>::back()
2995 { return *(_Tp*)getSeqElem(seq, -1); }
2996
back()2997 template<typename _Tp> inline const _Tp& Seq<_Tp>::back() const
2998 { return *(const _Tp*)getSeqElem(seq, -1); }
2999
front()3000 template<typename _Tp> inline _Tp& Seq<_Tp>::front()
3001 { return *(_Tp*)getSeqElem(seq, 0); }
3002
front()3003 template<typename _Tp> inline const _Tp& Seq<_Tp>::front() const
3004 { return *(const _Tp*)getSeqElem(seq, 0); }
3005
empty()3006 template<typename _Tp> inline bool Seq<_Tp>::empty() const
3007 { return !seq || seq->total == 0; }
3008
clear()3009 template<typename _Tp> inline void Seq<_Tp>::clear()
3010 { if(seq) clearSeq(seq); }
3011
pop_back()3012 template<typename _Tp> inline void Seq<_Tp>::pop_back()
3013 { seqPop(seq); }
3014
pop_front()3015 template<typename _Tp> inline void Seq<_Tp>::pop_front()
3016 { seqPopFront(seq); }
3017
pop_back(_Tp * elem,size_t count)3018 template<typename _Tp> inline void Seq<_Tp>::pop_back(_Tp* elem, size_t count)
3019 { seqPopMulti(seq, elem, (int)count, 0); }
3020
pop_front(_Tp * elem,size_t count)3021 template<typename _Tp> inline void Seq<_Tp>::pop_front(_Tp* elem, size_t count)
3022 { seqPopMulti(seq, elem, (int)count, 1); }
3023
insert(int idx,const _Tp & elem)3024 template<typename _Tp> inline void Seq<_Tp>::insert(int idx, const _Tp& elem)
3025 { seqInsert(seq, idx, &elem); }
3026
insert(int idx,const _Tp * elems,size_t count)3027 template<typename _Tp> inline void Seq<_Tp>::insert(int idx, const _Tp* elems, size_t count)
3028 {
3029 CvMat m = cvMat(1, count, DataType<_Tp>::type, elems);
3030 seqInsertSlice(seq, idx, &m);
3031 }
3032
remove(int idx)3033 template<typename _Tp> inline void Seq<_Tp>::remove(int idx)
3034 { seqRemove(seq, idx); }
3035
remove(const Range & r)3036 template<typename _Tp> inline void Seq<_Tp>::remove(const Range& r)
3037 { seqRemoveSlice(seq, cvSlice(r.start, r.end)); }
3038
copyTo(std::vector<_Tp> & vec,const Range & range)3039 template<typename _Tp> inline void Seq<_Tp>::copyTo(std::vector<_Tp>& vec, const Range& range) const
3040 {
3041 size_t len = !seq ? 0 : range == Range::all() ? seq->total : range.end - range.start;
3042 vec.resize(len);
3043 if( seq && len )
3044 cvCvtSeqToArray(seq, &vec[0], range);
3045 }
3046
3047 template<typename _Tp> inline Seq<_Tp>::operator std::vector<_Tp>() const
3048 {
3049 std::vector<_Tp> vec;
3050 copyTo(vec);
3051 return vec;
3052 }
3053
SeqIterator()3054 template<typename _Tp> inline SeqIterator<_Tp>::SeqIterator()
3055 { memset(this, 0, sizeof(*this)); }
3056
SeqIterator(const Seq<_Tp> & _seq,bool seekEnd)3057 template<typename _Tp> inline SeqIterator<_Tp>::SeqIterator(const Seq<_Tp>& _seq, bool seekEnd)
3058 {
3059 cvStartReadSeq(_seq.seq, this);
3060 index = seekEnd ? _seq.seq->total : 0;
3061 }
3062
seek(size_t pos)3063 template<typename _Tp> inline void SeqIterator<_Tp>::seek(size_t pos)
3064 {
3065 cvSetSeqReaderPos(this, (int)pos, false);
3066 index = pos;
3067 }
3068
tell()3069 template<typename _Tp> inline size_t SeqIterator<_Tp>::tell() const
3070 { return index; }
3071
3072 template<typename _Tp> inline _Tp& SeqIterator<_Tp>::operator *()
3073 { return *(_Tp*)ptr; }
3074
3075 template<typename _Tp> inline const _Tp& SeqIterator<_Tp>::operator *() const
3076 { return *(const _Tp*)ptr; }
3077
3078 template<typename _Tp> inline SeqIterator<_Tp>& SeqIterator<_Tp>::operator ++()
3079 {
3080 CV_NEXT_SEQ_ELEM(sizeof(_Tp), *this);
3081 if( ++index >= seq->total*2 )
3082 index = 0;
3083 return *this;
3084 }
3085
3086 template<typename _Tp> inline SeqIterator<_Tp> SeqIterator<_Tp>::operator ++(int) const
3087 {
3088 SeqIterator<_Tp> it = *this;
3089 ++*this;
3090 return it;
3091 }
3092
3093 template<typename _Tp> inline SeqIterator<_Tp>& SeqIterator<_Tp>::operator --()
3094 {
3095 CV_PREV_SEQ_ELEM(sizeof(_Tp), *this);
3096 if( --index < 0 )
3097 index = seq->total*2-1;
3098 return *this;
3099 }
3100
3101 template<typename _Tp> inline SeqIterator<_Tp> SeqIterator<_Tp>::operator --(int) const
3102 {
3103 SeqIterator<_Tp> it = *this;
3104 --*this;
3105 return it;
3106 }
3107
3108 template<typename _Tp> inline SeqIterator<_Tp>& SeqIterator<_Tp>::operator +=(int delta)
3109 {
3110 cvSetSeqReaderPos(this, delta, 1);
3111 index += delta;
3112 int n = seq->total*2;
3113 if( index < 0 )
3114 index += n;
3115 if( index >= n )
3116 index -= n;
3117 return *this;
3118 }
3119
3120 template<typename _Tp> inline SeqIterator<_Tp>& SeqIterator<_Tp>::operator -=(int delta)
3121 {
3122 return (*this += -delta);
3123 }
3124
3125 template<typename _Tp> inline ptrdiff_t operator - (const SeqIterator<_Tp>& a,
3126 const SeqIterator<_Tp>& b)
3127 {
3128 ptrdiff_t delta = a.index - b.index, n = a.seq->total;
3129 if( delta > n || delta < -n )
3130 delta += delta < 0 ? n : -n;
3131 return delta;
3132 }
3133
3134 template<typename _Tp> inline bool operator == (const SeqIterator<_Tp>& a,
3135 const SeqIterator<_Tp>& b)
3136 {
3137 return a.seq == b.seq && a.index == b.index;
3138 }
3139
3140 template<typename _Tp> inline bool operator != (const SeqIterator<_Tp>& a,
3141 const SeqIterator<_Tp>& b)
3142 {
3143 return !(a == b);
3144 }
3145
3146 //! @}
3147
3148 } // cv
3149
3150 #endif
3151
3152 #endif
3153