]> rtime.felk.cvut.cz Git - opencv.git/blob - opencv/include/opencv/cxcore.h
moved some stuff from cv to cxcore: cvCompleteSymm etc,
[opencv.git] / opencv / include / opencv / cxcore.h
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 //                        Intel License Agreement
11 //                For Open Source Computer Vision Library
12 //
13 // Copyright (C) 2000, Intel Corporation, all rights reserved.
14 // Third party copyrights are property of their respective owners.
15 //
16 // Redistribution and use in source and binary forms, with or without modification,
17 // are permitted provided that the following conditions are met:
18 //
19 //   * Redistribution's of source code must retain the above copyright notice,
20 //     this list of conditions and the following disclaimer.
21 //
22 //   * Redistribution's in binary form must reproduce the above copyright notice,
23 //     this list of conditions and the following disclaimer in the documentation
24 //     and/or other materials provided with the distribution.
25 //
26 //   * The name of Intel Corporation may not be used to endorse or promote products
27 //     derived from this software without specific prior written permission.
28 //
29 // This software is provided by the copyright holders and contributors "as is" and
30 // any express or implied warranties, including, but not limited to, the implied
31 // warranties of merchantability and fitness for a particular purpose are disclaimed.
32 // In no event shall the Intel Corporation or contributors be liable for any direct,
33 // indirect, incidental, special, exemplary, or consequential damages
34 // (including, but not limited to, procurement of substitute goods or services;
35 // loss of use, data, or profits; or business interruption) however caused
36 // and on any theory of liability, whether in contract, strict liability,
37 // or tort (including negligence or otherwise) arising in any way out of
38 // the use of this software, even if advised of the possibility of such damage.
39 //
40 //M*/
41
42
43 #ifndef _CXCORE_H_
44 #define _CXCORE_H_
45
46 #ifdef __IPL_H__
47 #define HAVE_IPL
48 #endif
49
50 #ifndef SKIP_INCLUDES
51   #if defined HAVE_IPL && !defined __IPL_H__
52     #ifndef _INC_WINDOWS
53         #define CV_PRETEND_WINDOWS
54         #define _INC_WINDOWS
55         typedef struct tagBITMAPINFOHEADER BITMAPINFOHEADER;
56         typedef int BOOL;
57     #endif
58     #if defined WIN32 || defined WIN64
59       #include "ipl.h"
60     #else
61       #include "ipl/ipl.h"
62     #endif
63     #ifdef CV_PRETEND_WINDOWS
64         #undef _INC_WINDOWS
65     #endif
66   #endif
67 #endif // SKIP_INCLUDES
68
69 #include "cxtypes.h"
70 #include "cxerror.h"
71 #include "cvver.h"
72
73 #ifdef __cplusplus
74 extern "C" {
75 #endif
76
77 /****************************************************************************************\
78 *          Array allocation, deallocation, initialization and access to elements         *
79 \****************************************************************************************/
80
81 /* <malloc> wrapper.
82    If there is no enough memory, the function
83    (as well as other OpenCV functions that call cvAlloc)
84    raises an error. */
85 CVAPI(void*)  cvAlloc( size_t size );
86
87 /* <free> wrapper.
88    Here and further all the memory releasing functions
89    (that all call cvFree) take double pointer in order to
90    to clear pointer to the data after releasing it.
91    Passing pointer to NULL pointer is Ok: nothing happens in this case
92 */
93 CVAPI(void)   cvFree_( void* ptr );
94 #define cvFree(ptr) (cvFree_(*(ptr)), *(ptr)=0)
95
96 /* Allocates and initializes IplImage header */
97 CVAPI(IplImage*)  cvCreateImageHeader( CvSize size, int depth, int channels );
98
99 /* Inializes IplImage header */
100 CVAPI(IplImage*) cvInitImageHeader( IplImage* image, CvSize size, int depth,
101                                    int channels, int origin CV_DEFAULT(0),
102                                    int align CV_DEFAULT(4));
103
104 /* Creates IPL image (header and data) */
105 CVAPI(IplImage*)  cvCreateImage( CvSize size, int depth, int channels );
106
107 /* Releases (i.e. deallocates) IPL image header */
108 CVAPI(void)  cvReleaseImageHeader( IplImage** image );
109
110 /* Releases IPL image header and data */
111 CVAPI(void)  cvReleaseImage( IplImage** image );
112
113 /* Creates a copy of IPL image (widthStep may differ) */
114 CVAPI(IplImage*) cvCloneImage( const IplImage* image );
115
116 /* Sets a Channel Of Interest (only a few functions support COI) -
117    use cvCopy to extract the selected channel and/or put it back */
118 CVAPI(void)  cvSetImageCOI( IplImage* image, int coi );
119
120 /* Retrieves image Channel Of Interest */
121 CVAPI(int)  cvGetImageCOI( const IplImage* image );
122
123 /* Sets image ROI (region of interest) (COI is not changed) */
124 CVAPI(void)  cvSetImageROI( IplImage* image, CvRect rect );
125
126 /* Resets image ROI and COI */
127 CVAPI(void)  cvResetImageROI( IplImage* image );
128
129 /* Retrieves image ROI */
130 CVAPI(CvRect) cvGetImageROI( const IplImage* image );
131
132 /* Allocates and initalizes CvMat header */
133 CVAPI(CvMat*)  cvCreateMatHeader( int rows, int cols, int type );
134
135 #define CV_AUTOSTEP  0x7fffffff
136
137 /* Initializes CvMat header */
138 CVAPI(CvMat*) cvInitMatHeader( CvMat* mat, int rows, int cols,
139                               int type, void* data CV_DEFAULT(NULL),
140                               int step CV_DEFAULT(CV_AUTOSTEP) );
141
142 /* Allocates and initializes CvMat header and allocates data */
143 CVAPI(CvMat*)  cvCreateMat( int rows, int cols, int type );
144
145 /* Releases CvMat header and deallocates matrix data
146    (reference counting is used for data) */
147 CVAPI(void)  cvReleaseMat( CvMat** mat );
148
149 /* Decrements CvMat data reference counter and deallocates the data if
150    it reaches 0 */
151 CV_INLINE  void  cvDecRefData( CvArr* arr )
152 {
153     if( CV_IS_MAT( arr ))
154     {
155         CvMat* mat = (CvMat*)arr;
156         mat->data.ptr = NULL;
157         if( mat->refcount != NULL && --*mat->refcount == 0 )
158             cvFree( &mat->refcount );
159         mat->refcount = NULL;
160     }
161     else if( CV_IS_MATND( arr ))
162     {
163         CvMatND* mat = (CvMatND*)arr;
164         mat->data.ptr = NULL;
165         if( mat->refcount != NULL && --*mat->refcount == 0 )
166             cvFree( &mat->refcount );
167         mat->refcount = NULL;
168     }
169 }
170
171 /* Increments CvMat data reference counter */
172 CV_INLINE  int  cvIncRefData( CvArr* arr )
173 {
174     int refcount = 0;
175     if( CV_IS_MAT( arr ))
176     {
177         CvMat* mat = (CvMat*)arr;
178         if( mat->refcount != NULL )
179             refcount = ++*mat->refcount;
180     }
181     else if( CV_IS_MATND( arr ))
182     {
183         CvMatND* mat = (CvMatND*)arr;
184         if( mat->refcount != NULL )
185             refcount = ++*mat->refcount;
186     }
187     return refcount;
188 }
189
190
191 /* Creates an exact copy of the input matrix (except, may be, step value) */
192 CVAPI(CvMat*) cvCloneMat( const CvMat* mat );
193
194
195 /* Makes a new matrix from <rect> subrectangle of input array.
196    No data is copied */
197 CVAPI(CvMat*) cvGetSubRect( const CvArr* arr, CvMat* submat, CvRect rect );
198 #define cvGetSubArr cvGetSubRect
199
200 /* Selects row span of the input array: arr(start_row:delta_row:end_row,:)
201     (end_row is not included into the span). */
202 CVAPI(CvMat*) cvGetRows( const CvArr* arr, CvMat* submat,
203                         int start_row, int end_row,
204                         int delta_row CV_DEFAULT(1));
205
206 CV_INLINE  CvMat*  cvGetRow( const CvArr* arr, CvMat* submat, int row )
207 {
208     return cvGetRows( arr, submat, row, row + 1, 1 );
209 }
210
211
212 /* Selects column span of the input array: arr(:,start_col:end_col)
213    (end_col is not included into the span) */
214 CVAPI(CvMat*) cvGetCols( const CvArr* arr, CvMat* submat,
215                         int start_col, int end_col );
216
217 CV_INLINE  CvMat*  cvGetCol( const CvArr* arr, CvMat* submat, int col )
218 {
219     return cvGetCols( arr, submat, col, col + 1 );
220 }
221
222 /* Select a diagonal of the input array.
223    (diag = 0 means the main diagonal, >0 means a diagonal above the main one,
224    <0 - below the main one).
225    The diagonal will be represented as a column (nx1 matrix). */
226 CVAPI(CvMat*) cvGetDiag( const CvArr* arr, CvMat* submat,
227                             int diag CV_DEFAULT(0));
228
229 /* low-level scalar <-> raw data conversion functions */
230 CVAPI(void) cvScalarToRawData( const CvScalar* scalar, void* data, int type,
231                               int extend_to_12 CV_DEFAULT(0) );
232
233 CVAPI(void) cvRawDataToScalar( const void* data, int type, CvScalar* scalar );
234
235 /* Allocates and initializes CvMatND header */
236 CVAPI(CvMatND*)  cvCreateMatNDHeader( int dims, const int* sizes, int type );
237
238 /* Allocates and initializes CvMatND header and allocates data */
239 CVAPI(CvMatND*)  cvCreateMatND( int dims, const int* sizes, int type );
240
241 /* Initializes preallocated CvMatND header */
242 CVAPI(CvMatND*)  cvInitMatNDHeader( CvMatND* mat, int dims, const int* sizes,
243                                     int type, void* data CV_DEFAULT(NULL) );
244
245 /* Releases CvMatND */
246 CV_INLINE  void  cvReleaseMatND( CvMatND** mat )
247 {
248     cvReleaseMat( (CvMat**)mat );
249 }
250
251 /* Creates a copy of CvMatND (except, may be, steps) */
252 CVAPI(CvMatND*) cvCloneMatND( const CvMatND* mat );
253
254 /* Allocates and initializes CvSparseMat header and allocates data */
255 CVAPI(CvSparseMat*)  cvCreateSparseMat( int dims, const int* sizes, int type );
256
257 /* Releases CvSparseMat */
258 CVAPI(void)  cvReleaseSparseMat( CvSparseMat** mat );
259
260 /* Creates a copy of CvSparseMat (except, may be, zero items) */
261 CVAPI(CvSparseMat*) cvCloneSparseMat( const CvSparseMat* mat );
262
263 /* Initializes sparse array iterator
264    (returns the first node or NULL if the array is empty) */
265 CVAPI(CvSparseNode*) cvInitSparseMatIterator( const CvSparseMat* mat,
266                                               CvSparseMatIterator* mat_iterator );
267
268 // returns next sparse array node (or NULL if there is no more nodes)
269 CV_INLINE CvSparseNode* cvGetNextSparseNode( CvSparseMatIterator* mat_iterator )
270 {
271     if( mat_iterator->node->next )
272         return mat_iterator->node = mat_iterator->node->next;
273     else
274     {
275         int idx;
276         for( idx = ++mat_iterator->curidx; idx < mat_iterator->mat->hashsize; idx++ )
277         {
278             CvSparseNode* node = (CvSparseNode*)mat_iterator->mat->hashtable[idx];
279             if( node )
280             {
281                 mat_iterator->curidx = idx;
282                 return mat_iterator->node = node;
283             }
284         }
285         return NULL;
286     }
287 }
288
289 /**************** matrix iterator: used for n-ary operations on dense arrays *********/
290
291 #define CV_MAX_ARR 10
292
293 typedef struct CvNArrayIterator
294 {
295     int count; /* number of arrays */
296     int dims; /* number of dimensions to iterate */
297     CvSize size; /* maximal common linear size: { width = size, height = 1 } */
298     uchar* ptr[CV_MAX_ARR]; /* pointers to the array slices */
299     int stack[CV_MAX_DIM]; /* for internal use */
300     CvMatND* hdr[CV_MAX_ARR]; /* pointers to the headers of the
301                                  matrices that are processed */
302 }
303 CvNArrayIterator;
304
305 #define CV_NO_DEPTH_CHECK     1
306 #define CV_NO_CN_CHECK        2
307 #define CV_NO_SIZE_CHECK      4
308
309 /* initializes iterator that traverses through several arrays simulteneously
310    (the function together with cvNextArraySlice is used for
311     N-ari element-wise operations) */
312 CVAPI(int) cvInitNArrayIterator( int count, CvArr** arrs,
313                                  const CvArr* mask, CvMatND* stubs,
314                                  CvNArrayIterator* array_iterator,
315                                  int flags CV_DEFAULT(0) );
316
317 /* returns zero value if iteration is finished, non-zero (slice length) otherwise */
318 CVAPI(int) cvNextNArraySlice( CvNArrayIterator* array_iterator );
319
320
321 /* Returns type of array elements:
322    CV_8UC1 ... CV_64FC4 ... */
323 CVAPI(int) cvGetElemType( const CvArr* arr );
324
325 /* Retrieves number of an array dimensions and
326    optionally sizes of the dimensions */
327 CVAPI(int) cvGetDims( const CvArr* arr, int* sizes CV_DEFAULT(NULL) );
328
329
330 /* Retrieves size of a particular array dimension.
331    For 2d arrays cvGetDimSize(arr,0) returns number of rows (image height)
332    and cvGetDimSize(arr,1) returns number of columns (image width) */
333 CVAPI(int) cvGetDimSize( const CvArr* arr, int index );
334
335
336 /* ptr = &arr(idx0,idx1,...). All indexes are zero-based,
337    the major dimensions go first (e.g. (y,x) for 2D, (z,y,x) for 3D */
338 CVAPI(uchar*) cvPtr1D( const CvArr* arr, int idx0, int* type CV_DEFAULT(NULL));
339 CVAPI(uchar*) cvPtr2D( const CvArr* arr, int idx0, int idx1, int* type CV_DEFAULT(NULL) );
340 CVAPI(uchar*) cvPtr3D( const CvArr* arr, int idx0, int idx1, int idx2,
341                       int* type CV_DEFAULT(NULL));
342
343 /* For CvMat or IplImage number of indices should be 2
344    (row index (y) goes first, column index (x) goes next).
345    For CvMatND or CvSparseMat number of infices should match number of <dims> and
346    indices order should match the array dimension order. */
347 CVAPI(uchar*) cvPtrND( const CvArr* arr, const int* idx, int* type CV_DEFAULT(NULL),
348                       int create_node CV_DEFAULT(1),
349                       unsigned* precalc_hashval CV_DEFAULT(NULL));
350
351 /* value = arr(idx0,idx1,...) */
352 CVAPI(CvScalar) cvGet1D( const CvArr* arr, int idx0 );
353 CVAPI(CvScalar) cvGet2D( const CvArr* arr, int idx0, int idx1 );
354 CVAPI(CvScalar) cvGet3D( const CvArr* arr, int idx0, int idx1, int idx2 );
355 CVAPI(CvScalar) cvGetND( const CvArr* arr, const int* idx );
356
357 /* for 1-channel arrays */
358 CVAPI(double) cvGetReal1D( const CvArr* arr, int idx0 );
359 CVAPI(double) cvGetReal2D( const CvArr* arr, int idx0, int idx1 );
360 CVAPI(double) cvGetReal3D( const CvArr* arr, int idx0, int idx1, int idx2 );
361 CVAPI(double) cvGetRealND( const CvArr* arr, const int* idx );
362
363 /* arr(idx0,idx1,...) = value */
364 CVAPI(void) cvSet1D( CvArr* arr, int idx0, CvScalar value );
365 CVAPI(void) cvSet2D( CvArr* arr, int idx0, int idx1, CvScalar value );
366 CVAPI(void) cvSet3D( CvArr* arr, int idx0, int idx1, int idx2, CvScalar value );
367 CVAPI(void) cvSetND( CvArr* arr, const int* idx, CvScalar value );
368
369 /* for 1-channel arrays */
370 CVAPI(void) cvSetReal1D( CvArr* arr, int idx0, double value );
371 CVAPI(void) cvSetReal2D( CvArr* arr, int idx0, int idx1, double value );
372 CVAPI(void) cvSetReal3D( CvArr* arr, int idx0,
373                         int idx1, int idx2, double value );
374 CVAPI(void) cvSetRealND( CvArr* arr, const int* idx, double value );
375
376 /* clears element of ND dense array,
377    in case of sparse arrays it deletes the specified node */
378 CVAPI(void) cvClearND( CvArr* arr, const int* idx );
379
380 /* Converts CvArr (IplImage or CvMat,...) to CvMat.
381    If the last parameter is non-zero, function can
382    convert multi(>2)-dimensional array to CvMat as long as
383    the last array's dimension is continous. The resultant
384    matrix will be have appropriate (a huge) number of rows */
385 CVAPI(CvMat*) cvGetMat( const CvArr* arr, CvMat* header,
386                        int* coi CV_DEFAULT(NULL),
387                        int allowND CV_DEFAULT(0));
388
389 /* Converts CvArr (IplImage or CvMat) to IplImage */
390 CVAPI(IplImage*) cvGetImage( const CvArr* arr, IplImage* image_header );
391
392
393 /* Changes a shape of multi-dimensional array.
394    new_cn == 0 means that number of channels remains unchanged.
395    new_dims == 0 means that number and sizes of dimensions remain the same
396    (unless they need to be changed to set the new number of channels)
397    if new_dims == 1, there is no need to specify new dimension sizes
398    The resultant configuration should be achievable w/o data copying.
399    If the resultant array is sparse, CvSparseMat header should be passed
400    to the function else if the result is 1 or 2 dimensional,
401    CvMat header should be passed to the function
402    else CvMatND header should be passed */
403 CVAPI(CvArr*) cvReshapeMatND( const CvArr* arr,
404                              int sizeof_header, CvArr* header,
405                              int new_cn, int new_dims, int* new_sizes );
406
407 #define cvReshapeND( arr, header, new_cn, new_dims, new_sizes )   \
408       cvReshapeMatND( (arr), sizeof(*(header)), (header),         \
409                       (new_cn), (new_dims), (new_sizes))
410
411 CVAPI(CvMat*) cvReshape( const CvArr* arr, CvMat* header,
412                         int new_cn, int new_rows CV_DEFAULT(0) );
413
414 /* Repeats source 2d array several times in both horizontal and
415    vertical direction to fill destination array */
416 CVAPI(void) cvRepeat( const CvArr* src, CvArr* dst );
417
418 /* Allocates array data */
419 CVAPI(void)  cvCreateData( CvArr* arr );
420
421 /* Releases array data */
422 CVAPI(void)  cvReleaseData( CvArr* arr );
423
424 /* Attaches user data to the array header. The step is reffered to
425    the pre-last dimension. That is, all the planes of the array
426    must be joint (w/o gaps) */
427 CVAPI(void)  cvSetData( CvArr* arr, void* data, int step );
428
429 /* Retrieves raw data of CvMat, IplImage or CvMatND.
430    In the latter case the function raises an error if
431    the array can not be represented as a matrix */
432 CVAPI(void) cvGetRawData( const CvArr* arr, uchar** data,
433                          int* step CV_DEFAULT(NULL),
434                          CvSize* roi_size CV_DEFAULT(NULL));
435
436 /* Returns width and height of array in elements */
437 CVAPI(CvSize) cvGetSize( const CvArr* arr );
438
439 /* Copies source array to destination array */
440 CVAPI(void)  cvCopy( const CvArr* src, CvArr* dst,
441                      const CvArr* mask CV_DEFAULT(NULL) );
442
443 /* Sets all or "masked" elements of input array
444    to the same value*/
445 CVAPI(void)  cvSet( CvArr* arr, CvScalar value,
446                     const CvArr* mask CV_DEFAULT(NULL) );
447
448 /* Clears all the array elements (sets them to 0) */
449 CVAPI(void)  cvSetZero( CvArr* arr );
450 #define cvZero  cvSetZero
451
452
453 /* Splits a multi-channel array into the set of single-channel arrays or
454    extracts particular [color] plane */
455 CVAPI(void)  cvSplit( const CvArr* src, CvArr* dst0, CvArr* dst1,
456                       CvArr* dst2, CvArr* dst3 );
457
458 /* Merges a set of single-channel arrays into the single multi-channel array
459    or inserts one particular [color] plane to the array */
460 CVAPI(void)  cvMerge( const CvArr* src0, const CvArr* src1,
461                       const CvArr* src2, const CvArr* src3,
462                       CvArr* dst );
463
464 /* Copies several channels from input arrays to
465    certain channels of output arrays */
466 CVAPI(void)  cvMixChannels( const CvArr** src, int src_count,
467                             CvArr** dst, int dst_count,
468                             const int* from_to, int pair_count );
469
470 /* Performs linear transformation on every source array element:
471    dst(x,y,c) = scale*src(x,y,c)+shift.
472    Arbitrary combination of input and output array depths are allowed
473    (number of channels must be the same), thus the function can be used
474    for type conversion */
475 CVAPI(void)  cvConvertScale( const CvArr* src, CvArr* dst,
476                              double scale CV_DEFAULT(1),
477                              double shift CV_DEFAULT(0) );
478 #define cvCvtScale cvConvertScale
479 #define cvScale  cvConvertScale
480 #define cvConvert( src, dst )  cvConvertScale( (src), (dst), 1, 0 )
481
482
483 /* Performs linear transformation on every source array element,
484    stores absolute value of the result:
485    dst(x,y,c) = abs(scale*src(x,y,c)+shift).
486    destination array must have 8u type.
487    In other cases one may use cvConvertScale + cvAbsDiffS */
488 CVAPI(void)  cvConvertScaleAbs( const CvArr* src, CvArr* dst,
489                                 double scale CV_DEFAULT(1),
490                                 double shift CV_DEFAULT(0) );
491 #define cvCvtScaleAbs  cvConvertScaleAbs
492
493
494 /* checks termination criteria validity and
495    sets eps to default_eps (if it is not set),
496    max_iter to default_max_iters (if it is not set)
497 */
498 CVAPI(CvTermCriteria) cvCheckTermCriteria( CvTermCriteria criteria,
499                                            double default_eps,
500                                            int default_max_iters );
501
502 /****************************************************************************************\
503 *                   Arithmetic, logic and comparison operations                          *
504 \****************************************************************************************/
505
506 /* dst(mask) = src1(mask) + src2(mask) */
507 CVAPI(void)  cvAdd( const CvArr* src1, const CvArr* src2, CvArr* dst,
508                     const CvArr* mask CV_DEFAULT(NULL));
509
510 /* dst(mask) = src(mask) + value */
511 CVAPI(void)  cvAddS( const CvArr* src, CvScalar value, CvArr* dst,
512                      const CvArr* mask CV_DEFAULT(NULL));
513
514 /* dst(mask) = src1(mask) - src2(mask) */
515 CVAPI(void)  cvSub( const CvArr* src1, const CvArr* src2, CvArr* dst,
516                     const CvArr* mask CV_DEFAULT(NULL));
517
518 /* dst(mask) = src(mask) - value = src(mask) + (-value) */
519 CV_INLINE  void  cvSubS( const CvArr* src, CvScalar value, CvArr* dst,
520                          const CvArr* mask CV_DEFAULT(NULL))
521 {
522     cvAddS( src, cvScalar( -value.val[0], -value.val[1], -value.val[2], -value.val[3]),
523             dst, mask );
524 }
525
526 /* dst(mask) = value - src(mask) */
527 CVAPI(void)  cvSubRS( const CvArr* src, CvScalar value, CvArr* dst,
528                       const CvArr* mask CV_DEFAULT(NULL));
529
530 /* dst(idx) = src1(idx) * src2(idx) * scale
531    (scaled element-wise multiplication of 2 arrays) */
532 CVAPI(void)  cvMul( const CvArr* src1, const CvArr* src2,
533                     CvArr* dst, double scale CV_DEFAULT(1) );
534
535 /* element-wise division/inversion with scaling:
536     dst(idx) = src1(idx) * scale / src2(idx)
537     or dst(idx) = scale / src2(idx) if src1 == 0 */
538 CVAPI(void)  cvDiv( const CvArr* src1, const CvArr* src2,
539                     CvArr* dst, double scale CV_DEFAULT(1));
540
541 /* dst = src1 * scale + src2 */
542 CVAPI(void)  cvScaleAdd( const CvArr* src1, CvScalar scale,
543                          const CvArr* src2, CvArr* dst );
544 #define cvAXPY( A, real_scalar, B, C ) cvScaleAdd(A, cvRealScalar(real_scalar), B, C)
545
546 /* dst = src1 * alpha + src2 * beta + gamma */
547 CVAPI(void)  cvAddWeighted( const CvArr* src1, double alpha,
548                             const CvArr* src2, double beta,
549                             double gamma, CvArr* dst );
550
551 /* result = sum_i(src1(i) * src2(i)) (results for all channels are accumulated together) */
552 CVAPI(double)  cvDotProduct( const CvArr* src1, const CvArr* src2 );
553
554 /* dst(idx) = src1(idx) & src2(idx) */
555 CVAPI(void) cvAnd( const CvArr* src1, const CvArr* src2,
556                   CvArr* dst, const CvArr* mask CV_DEFAULT(NULL));
557
558 /* dst(idx) = src(idx) & value */
559 CVAPI(void) cvAndS( const CvArr* src, CvScalar value,
560                    CvArr* dst, const CvArr* mask CV_DEFAULT(NULL));
561
562 /* dst(idx) = src1(idx) | src2(idx) */
563 CVAPI(void) cvOr( const CvArr* src1, const CvArr* src2,
564                  CvArr* dst, const CvArr* mask CV_DEFAULT(NULL));
565
566 /* dst(idx) = src(idx) | value */
567 CVAPI(void) cvOrS( const CvArr* src, CvScalar value,
568                   CvArr* dst, const CvArr* mask CV_DEFAULT(NULL));
569
570 /* dst(idx) = src1(idx) ^ src2(idx) */
571 CVAPI(void) cvXor( const CvArr* src1, const CvArr* src2,
572                   CvArr* dst, const CvArr* mask CV_DEFAULT(NULL));
573
574 /* dst(idx) = src(idx) ^ value */
575 CVAPI(void) cvXorS( const CvArr* src, CvScalar value,
576                    CvArr* dst, const CvArr* mask CV_DEFAULT(NULL));
577
578 /* dst(idx) = ~src(idx) */
579 CVAPI(void) cvNot( const CvArr* src, CvArr* dst );
580
581 /* dst(idx) = lower(idx) <= src(idx) < upper(idx) */
582 CVAPI(void) cvInRange( const CvArr* src, const CvArr* lower,
583                       const CvArr* upper, CvArr* dst );
584
585 /* dst(idx) = lower <= src(idx) < upper */
586 CVAPI(void) cvInRangeS( const CvArr* src, CvScalar lower,
587                        CvScalar upper, CvArr* dst );
588
589 #define CV_CMP_EQ   0
590 #define CV_CMP_GT   1
591 #define CV_CMP_GE   2
592 #define CV_CMP_LT   3
593 #define CV_CMP_LE   4
594 #define CV_CMP_NE   5
595
596 /* The comparison operation support single-channel arrays only.
597    Destination image should be 8uC1 or 8sC1 */
598
599 /* dst(idx) = src1(idx) _cmp_op_ src2(idx) */
600 CVAPI(void) cvCmp( const CvArr* src1, const CvArr* src2, CvArr* dst, int cmp_op );
601
602 /* dst(idx) = src1(idx) _cmp_op_ value */
603 CVAPI(void) cvCmpS( const CvArr* src, double value, CvArr* dst, int cmp_op );
604
605 /* dst(idx) = min(src1(idx),src2(idx)) */
606 CVAPI(void) cvMin( const CvArr* src1, const CvArr* src2, CvArr* dst );
607
608 /* dst(idx) = max(src1(idx),src2(idx)) */
609 CVAPI(void) cvMax( const CvArr* src1, const CvArr* src2, CvArr* dst );
610
611 /* dst(idx) = min(src(idx),value) */
612 CVAPI(void) cvMinS( const CvArr* src, double value, CvArr* dst );
613
614 /* dst(idx) = max(src(idx),value) */
615 CVAPI(void) cvMaxS( const CvArr* src, double value, CvArr* dst );
616
617 /* dst(x,y,c) = abs(src1(x,y,c) - src2(x,y,c)) */
618 CVAPI(void) cvAbsDiff( const CvArr* src1, const CvArr* src2, CvArr* dst );
619
620 /* dst(x,y,c) = abs(src(x,y,c) - value(c)) */
621 CVAPI(void) cvAbsDiffS( const CvArr* src, CvArr* dst, CvScalar value );
622 #define cvAbs( src, dst ) cvAbsDiffS( (src), (dst), cvScalarAll(0))
623
624 /****************************************************************************************\
625 *                                Math operations                                         *
626 \****************************************************************************************/
627
628 /* Does cartesian->polar coordinates conversion.
629    Either of output components (magnitude or angle) is optional */
630 CVAPI(void)  cvCartToPolar( const CvArr* x, const CvArr* y,
631                             CvArr* magnitude, CvArr* angle CV_DEFAULT(NULL),
632                             int angle_in_degrees CV_DEFAULT(0));
633
634 /* Does polar->cartesian coordinates conversion.
635    Either of output components (magnitude or angle) is optional.
636    If magnitude is missing it is assumed to be all 1's */
637 CVAPI(void)  cvPolarToCart( const CvArr* magnitude, const CvArr* angle,
638                             CvArr* x, CvArr* y,
639                             int angle_in_degrees CV_DEFAULT(0));
640
641 /* Does powering: dst(idx) = src(idx)^power */
642 CVAPI(void)  cvPow( const CvArr* src, CvArr* dst, double power );
643
644 /* Does exponention: dst(idx) = exp(src(idx)).
645    Overflow is not handled yet. Underflow is handled.
646    Maximal relative error is ~7e-6 for single-precision input */
647 CVAPI(void)  cvExp( const CvArr* src, CvArr* dst );
648
649 /* Calculates natural logarithms: dst(idx) = log(abs(src(idx))).
650    Logarithm of 0 gives large negative number(~-700)
651    Maximal relative error is ~3e-7 for single-precision output
652 */
653 CVAPI(void)  cvLog( const CvArr* src, CvArr* dst );
654
655 /* Fast arctangent calculation */
656 CVAPI(float) cvFastArctan( float y, float x );
657
658 /* Fast cubic root calculation */
659 CVAPI(float)  cvCbrt( float value );
660
661 /* Checks array values for NaNs, Infs or simply for too large numbers
662    (if CV_CHECK_RANGE is set). If CV_CHECK_QUIET is set,
663    no runtime errors is raised (function returns zero value in case of "bad" values).
664    Otherwise cvError is called */
665 #define  CV_CHECK_RANGE    1
666 #define  CV_CHECK_QUIET    2
667 CVAPI(int)  cvCheckArr( const CvArr* arr, int flags CV_DEFAULT(0),
668                         double min_val CV_DEFAULT(0), double max_val CV_DEFAULT(0));
669 #define cvCheckArray cvCheckArr
670
671 #define CV_RAND_UNI      0
672 #define CV_RAND_NORMAL   1
673 CVAPI(void) cvRandArr( CvRNG* rng, CvArr* arr, int dist_type,
674                       CvScalar param1, CvScalar param2 );
675
676 CVAPI(void) cvRandShuffle( CvArr* mat, CvRNG* rng,
677                            double iter_factor CV_DEFAULT(1.));
678
679 /* Finds real roots of a cubic equation */
680 CVAPI(int) cvSolveCubic( const CvMat* coeffs, CvMat* roots );
681
682 /* Finds all real and complex roots of a polynomial equation */
683 CVAPI(void) cvSolvePoly(const CvMat* coeffs, CvMat *roots,
684                         int maxiter CV_DEFAULT(0), int fig CV_DEFAULT(0));
685
686 /****************************************************************************************\
687 *                                Matrix operations                                       *
688 \****************************************************************************************/
689
690 /* Calculates cross product of two 3d vectors */
691 CVAPI(void)  cvCrossProduct( const CvArr* src1, const CvArr* src2, CvArr* dst );
692
693 /* Matrix transform: dst = A*B + C, C is optional */
694 #define cvMatMulAdd( src1, src2, src3, dst ) cvGEMM( (src1), (src2), 1., (src3), 1., (dst), 0 )
695 #define cvMatMul( src1, src2, dst )  cvMatMulAdd( (src1), (src2), NULL, (dst))
696
697 #define CV_GEMM_A_T 1
698 #define CV_GEMM_B_T 2
699 #define CV_GEMM_C_T 4
700 /* Extended matrix transform:
701    dst = alpha*op(A)*op(B) + beta*op(C), where op(X) is X or X^T */
702 CVAPI(void)  cvGEMM( const CvArr* src1, const CvArr* src2, double alpha,
703                      const CvArr* src3, double beta, CvArr* dst,
704                      int tABC CV_DEFAULT(0));
705 #define cvMatMulAddEx cvGEMM
706
707 /* Transforms each element of source array and stores
708    resultant vectors in destination array */
709 CVAPI(void)  cvTransform( const CvArr* src, CvArr* dst,
710                           const CvMat* transmat,
711                           const CvMat* shiftvec CV_DEFAULT(NULL));
712 #define cvMatMulAddS cvTransform
713
714 /* Does perspective transform on every element of input array */
715 CVAPI(void)  cvPerspectiveTransform( const CvArr* src, CvArr* dst,
716                                      const CvMat* mat );
717
718 /* Calculates (A-delta)*(A-delta)^T (order=0) or (A-delta)^T*(A-delta) (order=1) */
719 CVAPI(void) cvMulTransposed( const CvArr* src, CvArr* dst, int order,
720                              const CvArr* delta CV_DEFAULT(NULL),
721                              double scale CV_DEFAULT(1.) );
722
723 /* Tranposes matrix. Square matrices can be transposed in-place */
724 CVAPI(void)  cvTranspose( const CvArr* src, CvArr* dst );
725 #define cvT cvTranspose
726
727 /* Completes the symmetric matrix from the lower (LtoR=0) or from the upper (LtoR!=0) part */
728 CVAPI(void)  cvCompleteSymm( CvMat* matrix, int LtoR CV_DEFAULT(0) );
729
730 /* Mirror array data around horizontal (flip=0),
731    vertical (flip=1) or both(flip=-1) axises:
732    cvFlip(src) flips images vertically and sequences horizontally (inplace) */
733 CVAPI(void)  cvFlip( const CvArr* src, CvArr* dst CV_DEFAULT(NULL),
734                      int flip_mode CV_DEFAULT(0));
735 #define cvMirror cvFlip
736
737
738 #define CV_SVD_MODIFY_A   1
739 #define CV_SVD_U_T        2
740 #define CV_SVD_V_T        4
741
742 /* Performs Singular Value Decomposition of a matrix */
743 CVAPI(void)   cvSVD( CvArr* A, CvArr* W, CvArr* U CV_DEFAULT(NULL),
744                      CvArr* V CV_DEFAULT(NULL), int flags CV_DEFAULT(0));
745
746 /* Performs Singular Value Back Substitution (solves A*X = B):
747    flags must be the same as in cvSVD */
748 CVAPI(void)   cvSVBkSb( const CvArr* W, const CvArr* U,
749                         const CvArr* V, const CvArr* B,
750                         CvArr* X, int flags );
751
752 #define CV_LU  0
753 #define CV_SVD 1
754 #define CV_SVD_SYM 2
755 #define CV_LSQ 8
756
757 /* Inverts matrix */
758 CVAPI(double)  cvInvert( const CvArr* src, CvArr* dst,
759                          int method CV_DEFAULT(CV_LU));
760 #define cvInv cvInvert
761
762 /* Solves linear system (src1)*(dst) = (src2)
763    (returns 0 if src1 is a singular and CV_LU method is used) */
764 CVAPI(int)  cvSolve( const CvArr* src1, const CvArr* src2, CvArr* dst,
765                      int method CV_DEFAULT(CV_LU));
766
767 /* Calculates determinant of input matrix */
768 CVAPI(double) cvDet( const CvArr* mat );
769
770 /* Calculates trace of the matrix (sum of elements on the main diagonal) */
771 CVAPI(CvScalar) cvTrace( const CvArr* mat );
772
773 /* Finds eigen values and vectors of a symmetric matrix */
774 CVAPI(void)  cvEigenVV( CvArr* mat, CvArr* evects,
775                         CvArr* evals, double eps CV_DEFAULT(0));
776
777 /* Makes an identity matrix (mat_ij = i == j) */
778 CVAPI(void)  cvSetIdentity( CvArr* mat, CvScalar value CV_DEFAULT(cvRealScalar(1)) );
779
780 /* Fills matrix with given range of numbers */
781 CVAPI(CvArr*)  cvRange( CvArr* mat, double start, double end );
782
783 /* Calculates covariation matrix for a set of vectors */
784 /* transpose([v1-avg, v2-avg,...]) * [v1-avg,v2-avg,...] */
785 #define CV_COVAR_SCRAMBLED 0
786
787 /* [v1-avg, v2-avg,...] * transpose([v1-avg,v2-avg,...]) */
788 #define CV_COVAR_NORMAL    1
789
790 /* do not calc average (i.e. mean vector) - use the input vector instead
791    (useful for calculating covariance matrix by parts) */
792 #define CV_COVAR_USE_AVG   2
793
794 /* scale the covariance matrix coefficients by number of the vectors */
795 #define CV_COVAR_SCALE     4
796
797 /* all the input vectors are stored in a single matrix, as its rows */
798 #define CV_COVAR_ROWS      8
799
800 /* all the input vectors are stored in a single matrix, as its columns */
801 #define CV_COVAR_COLS     16
802
803 CVAPI(void)  cvCalcCovarMatrix( const CvArr** vects, int count,
804                                 CvArr* cov_mat, CvArr* avg, int flags );
805
806 #define CV_PCA_DATA_AS_ROW 0
807 #define CV_PCA_DATA_AS_COL 1
808 #define CV_PCA_USE_AVG 2
809 CVAPI(void)  cvCalcPCA( const CvArr* data, CvArr* mean,
810                         CvArr* eigenvals, CvArr* eigenvects, int flags );
811
812 CVAPI(void)  cvProjectPCA( const CvArr* data, const CvArr* mean,
813                            const CvArr* eigenvects, CvArr* result );
814
815 CVAPI(void)  cvBackProjectPCA( const CvArr* proj, const CvArr* mean,
816                                const CvArr* eigenvects, CvArr* result );
817
818 /* Calculates Mahalanobis(weighted) distance */
819 CVAPI(double)  cvMahalanobis( const CvArr* vec1, const CvArr* vec2, CvArr* mat );
820 #define cvMahalonobis  cvMahalanobis
821
822 /****************************************************************************************\
823 *                                    Array Statistics                                    *
824 \****************************************************************************************/
825
826 /* Finds sum of array elements */
827 CVAPI(CvScalar)  cvSum( const CvArr* arr );
828
829 /* Calculates number of non-zero pixels */
830 CVAPI(int)  cvCountNonZero( const CvArr* arr );
831
832 /* Calculates mean value of array elements */
833 CVAPI(CvScalar)  cvAvg( const CvArr* arr, const CvArr* mask CV_DEFAULT(NULL) );
834
835 /* Calculates mean and standard deviation of pixel values */
836 CVAPI(void)  cvAvgSdv( const CvArr* arr, CvScalar* mean, CvScalar* std_dev,
837                        const CvArr* mask CV_DEFAULT(NULL) );
838
839 /* Finds global minimum, maximum and their positions */
840 CVAPI(void)  cvMinMaxLoc( const CvArr* arr, double* min_val, double* max_val,
841                           CvPoint* min_loc CV_DEFAULT(NULL),
842                           CvPoint* max_loc CV_DEFAULT(NULL),
843                           const CvArr* mask CV_DEFAULT(NULL) );
844
845 /* types of array norm */
846 #define CV_C            1
847 #define CV_L1           2
848 #define CV_L2           4
849 #define CV_NORM_MASK    7
850 #define CV_RELATIVE     8
851 #define CV_DIFF         16
852 #define CV_MINMAX       32
853
854 #define CV_DIFF_C       (CV_DIFF | CV_C)
855 #define CV_DIFF_L1      (CV_DIFF | CV_L1)
856 #define CV_DIFF_L2      (CV_DIFF | CV_L2)
857 #define CV_RELATIVE_C   (CV_RELATIVE | CV_C)
858 #define CV_RELATIVE_L1  (CV_RELATIVE | CV_L1)
859 #define CV_RELATIVE_L2  (CV_RELATIVE | CV_L2)
860
861 /* Finds norm, difference norm or relative difference norm for an array (or two arrays) */
862 CVAPI(double)  cvNorm( const CvArr* arr1, const CvArr* arr2 CV_DEFAULT(NULL),
863                        int norm_type CV_DEFAULT(CV_L2),
864                        const CvArr* mask CV_DEFAULT(NULL) );
865
866 CVAPI(void)  cvNormalize( const CvArr* src, CvArr* dst,
867                           double a CV_DEFAULT(1.), double b CV_DEFAULT(0.),
868                           int norm_type CV_DEFAULT(CV_L2),
869                           const CvArr* mask CV_DEFAULT(NULL) );
870
871
872 #define CV_REDUCE_SUM 0
873 #define CV_REDUCE_AVG 1
874 #define CV_REDUCE_MAX 2
875 #define CV_REDUCE_MIN 3
876
877 CVAPI(void)  cvReduce( const CvArr* src, CvArr* dst, int dim CV_DEFAULT(-1),
878                        int op CV_DEFAULT(CV_REDUCE_SUM) );
879
880 /****************************************************************************************\
881 *                      Discrete Linear Transforms and Related Functions                  *
882 \****************************************************************************************/
883
884 #define CV_DXT_FORWARD  0
885 #define CV_DXT_INVERSE  1
886 #define CV_DXT_SCALE    2 /* divide result by size of array */
887 #define CV_DXT_INV_SCALE (CV_DXT_INVERSE + CV_DXT_SCALE)
888 #define CV_DXT_INVERSE_SCALE CV_DXT_INV_SCALE
889 #define CV_DXT_ROWS     4 /* transform each row individually */
890 #define CV_DXT_MUL_CONJ 8 /* conjugate the second argument of cvMulSpectrums */
891
892 /* Discrete Fourier Transform:
893     complex->complex,
894     real->ccs (forward),
895     ccs->real (inverse) */
896 CVAPI(void)  cvDFT( const CvArr* src, CvArr* dst, int flags,
897                     int nonzero_rows CV_DEFAULT(0) );
898 #define cvFFT cvDFT
899
900 /* Multiply results of DFTs: DFT(X)*DFT(Y) or DFT(X)*conj(DFT(Y)) */
901 CVAPI(void)  cvMulSpectrums( const CvArr* src1, const CvArr* src2,
902                              CvArr* dst, int flags );
903
904 /* Finds optimal DFT vector size >= size0 */
905 CVAPI(int)  cvGetOptimalDFTSize( int size0 );
906
907 /* Discrete Cosine Transform */
908 CVAPI(void)  cvDCT( const CvArr* src, CvArr* dst, int flags );
909
910 /****************************************************************************************\
911 *                              Dynamic data structures                                   *
912 \****************************************************************************************/
913
914 /* Calculates length of sequence slice (with support of negative indices). */
915 CVAPI(int) cvSliceLength( CvSlice slice, const CvSeq* seq );
916
917
918 /* Creates new memory storage.
919    block_size == 0 means that default,
920    somewhat optimal size, is used (currently, it is 64K) */
921 CVAPI(CvMemStorage*)  cvCreateMemStorage( int block_size CV_DEFAULT(0));
922
923
924 /* Creates a memory storage that will borrow memory blocks from parent storage */
925 CVAPI(CvMemStorage*)  cvCreateChildMemStorage( CvMemStorage* parent );
926
927
928 /* Releases memory storage. All the children of a parent must be released before
929    the parent. A child storage returns all the blocks to parent when it is released */
930 CVAPI(void)  cvReleaseMemStorage( CvMemStorage** storage );
931
932
933 /* Clears memory storage. This is the only way(!!!) (besides cvRestoreMemStoragePos)
934    to reuse memory allocated for the storage - cvClearSeq,cvClearSet ...
935    do not free any memory.
936    A child storage returns all the blocks to the parent when it is cleared */
937 CVAPI(void)  cvClearMemStorage( CvMemStorage* storage );
938
939 /* Remember a storage "free memory" position */
940 CVAPI(void)  cvSaveMemStoragePos( const CvMemStorage* storage, CvMemStoragePos* pos );
941
942 /* Restore a storage "free memory" position */
943 CVAPI(void)  cvRestoreMemStoragePos( CvMemStorage* storage, CvMemStoragePos* pos );
944
945 /* Allocates continuous buffer of the specified size in the storage */
946 CVAPI(void*) cvMemStorageAlloc( CvMemStorage* storage, size_t size );
947
948 /* Allocates string in memory storage */
949 CVAPI(CvString) cvMemStorageAllocString( CvMemStorage* storage, const char* ptr,
950                                         int len CV_DEFAULT(-1) );
951
952 /* Creates new empty sequence that will reside in the specified storage */
953 CVAPI(CvSeq*)  cvCreateSeq( int seq_flags, int header_size,
954                             int elem_size, CvMemStorage* storage );
955
956 /* Changes default size (granularity) of sequence blocks.
957    The default size is ~1Kbyte */
958 CVAPI(void)  cvSetSeqBlockSize( CvSeq* seq, int delta_elems );
959
960
961 /* Adds new element to the end of sequence. Returns pointer to the element */
962 CVAPI(schar*)  cvSeqPush( CvSeq* seq, void* element CV_DEFAULT(NULL));
963
964
965 /* Adds new element to the beginning of sequence. Returns pointer to it */
966 CVAPI(schar*)  cvSeqPushFront( CvSeq* seq, void* element CV_DEFAULT(NULL));
967
968
969 /* Removes the last element from sequence and optionally saves it */
970 CVAPI(void)  cvSeqPop( CvSeq* seq, void* element CV_DEFAULT(NULL));
971
972
973 /* Removes the first element from sequence and optioanally saves it */
974 CVAPI(void)  cvSeqPopFront( CvSeq* seq, void* element CV_DEFAULT(NULL));
975
976
977 #define CV_FRONT 1
978 #define CV_BACK 0
979 /* Adds several new elements to the end of sequence */
980 CVAPI(void)  cvSeqPushMulti( CvSeq* seq, void* elements,
981                              int count, int in_front CV_DEFAULT(0) );
982
983 /* Removes several elements from the end of sequence and optionally saves them */
984 CVAPI(void)  cvSeqPopMulti( CvSeq* seq, void* elements,
985                             int count, int in_front CV_DEFAULT(0) );
986
987 /* Inserts a new element in the middle of sequence.
988    cvSeqInsert(seq,0,elem) == cvSeqPushFront(seq,elem) */
989 CVAPI(schar*)  cvSeqInsert( CvSeq* seq, int before_index,
990                             void* element CV_DEFAULT(NULL));
991
992 /* Removes specified sequence element */
993 CVAPI(void)  cvSeqRemove( CvSeq* seq, int index );
994
995
996 /* Removes all the elements from the sequence. The freed memory
997    can be reused later only by the same sequence unless cvClearMemStorage
998    or cvRestoreMemStoragePos is called */
999 CVAPI(void)  cvClearSeq( CvSeq* seq );
1000
1001
1002 /* Retrieves pointer to specified sequence element.
1003    Negative indices are supported and mean counting from the end
1004    (e.g -1 means the last sequence element) */
1005 CVAPI(schar*)  cvGetSeqElem( const CvSeq* seq, int index );
1006
1007 /* Calculates index of the specified sequence element.
1008    Returns -1 if element does not belong to the sequence */
1009 CVAPI(int)  cvSeqElemIdx( const CvSeq* seq, const void* element,
1010                          CvSeqBlock** block CV_DEFAULT(NULL) );
1011
1012 /* Initializes sequence writer. The new elements will be added to the end of sequence */
1013 CVAPI(void)  cvStartAppendToSeq( CvSeq* seq, CvSeqWriter* writer );
1014
1015
1016 /* Combination of cvCreateSeq and cvStartAppendToSeq */
1017 CVAPI(void)  cvStartWriteSeq( int seq_flags, int header_size,
1018                               int elem_size, CvMemStorage* storage,
1019                               CvSeqWriter* writer );
1020
1021 /* Closes sequence writer, updates sequence header and returns pointer
1022    to the resultant sequence
1023    (which may be useful if the sequence was created using cvStartWriteSeq))
1024 */
1025 CVAPI(CvSeq*)  cvEndWriteSeq( CvSeqWriter* writer );
1026
1027
1028 /* Updates sequence header. May be useful to get access to some of previously
1029    written elements via cvGetSeqElem or sequence reader */
1030 CVAPI(void)   cvFlushSeqWriter( CvSeqWriter* writer );
1031
1032
1033 /* Initializes sequence reader.
1034    The sequence can be read in forward or backward direction */
1035 CVAPI(void) cvStartReadSeq( const CvSeq* seq, CvSeqReader* reader,
1036                            int reverse CV_DEFAULT(0) );
1037
1038
1039 /* Returns current sequence reader position (currently observed sequence element) */
1040 CVAPI(int)  cvGetSeqReaderPos( CvSeqReader* reader );
1041
1042
1043 /* Changes sequence reader position. It may seek to an absolute or
1044    to relative to the current position */
1045 CVAPI(void)   cvSetSeqReaderPos( CvSeqReader* reader, int index,
1046                                  int is_relative CV_DEFAULT(0));
1047
1048 /* Copies sequence content to a continuous piece of memory */
1049 CVAPI(void*)  cvCvtSeqToArray( const CvSeq* seq, void* elements,
1050                                CvSlice slice CV_DEFAULT(CV_WHOLE_SEQ) );
1051
1052 /* Creates sequence header for array.
1053    After that all the operations on sequences that do not alter the content
1054    can be applied to the resultant sequence */
1055 CVAPI(CvSeq*) cvMakeSeqHeaderForArray( int seq_type, int header_size,
1056                                        int elem_size, void* elements, int total,
1057                                        CvSeq* seq, CvSeqBlock* block );
1058
1059 /* Extracts sequence slice (with or without copying sequence elements) */
1060 CVAPI(CvSeq*) cvSeqSlice( const CvSeq* seq, CvSlice slice,
1061                          CvMemStorage* storage CV_DEFAULT(NULL),
1062                          int copy_data CV_DEFAULT(0));
1063
1064 CV_INLINE CvSeq* cvCloneSeq( const CvSeq* seq, CvMemStorage* storage CV_DEFAULT(NULL))
1065 {
1066     return cvSeqSlice( seq, CV_WHOLE_SEQ, storage, 1 );
1067 }
1068
1069 /* Removes sequence slice */
1070 CVAPI(void)  cvSeqRemoveSlice( CvSeq* seq, CvSlice slice );
1071
1072 /* Inserts a sequence or array into another sequence */
1073 CVAPI(void)  cvSeqInsertSlice( CvSeq* seq, int before_index, const CvArr* from_arr );
1074
1075 /* a < b ? -1 : a > b ? 1 : 0 */
1076 typedef int (CV_CDECL* CvCmpFunc)(const void* a, const void* b, void* userdata );
1077
1078 /* Sorts sequence in-place given element comparison function */
1079 CVAPI(void) cvSeqSort( CvSeq* seq, CvCmpFunc func, void* userdata CV_DEFAULT(NULL) );
1080
1081 /* Finds element in a [sorted] sequence */
1082 CVAPI(schar*) cvSeqSearch( CvSeq* seq, const void* elem, CvCmpFunc func,
1083                            int is_sorted, int* elem_idx,
1084                            void* userdata CV_DEFAULT(NULL) );
1085
1086 /* Reverses order of sequence elements in-place */
1087 CVAPI(void) cvSeqInvert( CvSeq* seq );
1088
1089 /* Splits sequence into one or more equivalence classes using the specified criteria */
1090 CVAPI(int)  cvSeqPartition( const CvSeq* seq, CvMemStorage* storage,
1091                             CvSeq** labels, CvCmpFunc is_equal, void* userdata );
1092
1093 /************ Internal sequence functions ************/
1094 CVAPI(void)  cvChangeSeqBlock( void* reader, int direction );
1095 CVAPI(void)  cvCreateSeqBlock( CvSeqWriter* writer );
1096
1097
1098 /* Creates a new set */
1099 CVAPI(CvSet*)  cvCreateSet( int set_flags, int header_size,
1100                             int elem_size, CvMemStorage* storage );
1101
1102 /* Adds new element to the set and returns pointer to it */
1103 CVAPI(int)  cvSetAdd( CvSet* set_header, CvSetElem* elem CV_DEFAULT(NULL),
1104                       CvSetElem** inserted_elem CV_DEFAULT(NULL) );
1105
1106 /* Fast variant of cvSetAdd */
1107 CV_INLINE  CvSetElem* cvSetNew( CvSet* set_header )
1108 {
1109     CvSetElem* elem = set_header->free_elems;
1110     if( elem )
1111     {
1112         set_header->free_elems = elem->next_free;
1113         elem->flags = elem->flags & CV_SET_ELEM_IDX_MASK;
1114         set_header->active_count++;
1115     }
1116     else
1117         cvSetAdd( set_header, NULL, (CvSetElem**)&elem );
1118     return elem;
1119 }
1120
1121 /* Removes set element given its pointer */
1122 CV_INLINE  void cvSetRemoveByPtr( CvSet* set_header, void* elem )
1123 {
1124     CvSetElem* _elem = (CvSetElem*)elem;
1125     assert( _elem->flags >= 0 /*&& (elem->flags & CV_SET_ELEM_IDX_MASK) < set_header->total*/ );
1126     _elem->next_free = set_header->free_elems;
1127     _elem->flags = (_elem->flags & CV_SET_ELEM_IDX_MASK) | CV_SET_ELEM_FREE_FLAG;
1128     set_header->free_elems = _elem;
1129     set_header->active_count--;
1130 }
1131
1132 /* Removes element from the set by its index  */
1133 CVAPI(void)   cvSetRemove( CvSet* set_header, int index );
1134
1135 /* Returns a set element by index. If the element doesn't belong to the set,
1136    NULL is returned */
1137 CV_INLINE CvSetElem* cvGetSetElem( const CvSet* set_header, int index )
1138 {
1139     CvSetElem* elem = (CvSetElem*)cvGetSeqElem( (CvSeq*)set_header, index );
1140     return elem && CV_IS_SET_ELEM( elem ) ? elem : 0;
1141 }
1142
1143 /* Removes all the elements from the set */
1144 CVAPI(void)  cvClearSet( CvSet* set_header );
1145
1146 /* Creates new graph */
1147 CVAPI(CvGraph*)  cvCreateGraph( int graph_flags, int header_size,
1148                                 int vtx_size, int edge_size,
1149                                 CvMemStorage* storage );
1150
1151 /* Adds new vertex to the graph */
1152 CVAPI(int)  cvGraphAddVtx( CvGraph* graph, const CvGraphVtx* vtx CV_DEFAULT(NULL),
1153                            CvGraphVtx** inserted_vtx CV_DEFAULT(NULL) );
1154
1155
1156 /* Removes vertex from the graph together with all incident edges */
1157 CVAPI(int)  cvGraphRemoveVtx( CvGraph* graph, int index );
1158 CVAPI(int)  cvGraphRemoveVtxByPtr( CvGraph* graph, CvGraphVtx* vtx );
1159
1160
1161 /* Link two vertices specifed by indices or pointers if they
1162    are not connected or return pointer to already existing edge
1163    connecting the vertices.
1164    Functions return 1 if a new edge was created, 0 otherwise */
1165 CVAPI(int)  cvGraphAddEdge( CvGraph* graph,
1166                             int start_idx, int end_idx,
1167                             const CvGraphEdge* edge CV_DEFAULT(NULL),
1168                             CvGraphEdge** inserted_edge CV_DEFAULT(NULL) );
1169
1170 CVAPI(int)  cvGraphAddEdgeByPtr( CvGraph* graph,
1171                                CvGraphVtx* start_vtx, CvGraphVtx* end_vtx,
1172                                const CvGraphEdge* edge CV_DEFAULT(NULL),
1173                                CvGraphEdge** inserted_edge CV_DEFAULT(NULL) );
1174
1175 /* Remove edge connecting two vertices */
1176 CVAPI(void)  cvGraphRemoveEdge( CvGraph* graph, int start_idx, int end_idx );
1177 CVAPI(void)  cvGraphRemoveEdgeByPtr( CvGraph* graph, CvGraphVtx* start_vtx,
1178                                      CvGraphVtx* end_vtx );
1179
1180 /* Find edge connecting two vertices */
1181 CVAPI(CvGraphEdge*)  cvFindGraphEdge( const CvGraph* graph, int start_idx, int end_idx );
1182 CVAPI(CvGraphEdge*)  cvFindGraphEdgeByPtr( const CvGraph* graph,
1183                                            const CvGraphVtx* start_vtx,
1184                                            const CvGraphVtx* end_vtx );
1185 #define cvGraphFindEdge cvFindGraphEdge
1186 #define cvGraphFindEdgeByPtr cvFindGraphEdgeByPtr
1187
1188 /* Remove all vertices and edges from the graph */
1189 CVAPI(void)  cvClearGraph( CvGraph* graph );
1190
1191
1192 /* Count number of edges incident to the vertex */
1193 CVAPI(int)  cvGraphVtxDegree( const CvGraph* graph, int vtx_idx );
1194 CVAPI(int)  cvGraphVtxDegreeByPtr( const CvGraph* graph, const CvGraphVtx* vtx );
1195
1196
1197 /* Retrieves graph vertex by given index */
1198 #define cvGetGraphVtx( graph, idx ) (CvGraphVtx*)cvGetSetElem((CvSet*)(graph), (idx))
1199
1200 /* Retrieves index of a graph vertex given its pointer */
1201 #define cvGraphVtxIdx( graph, vtx ) ((vtx)->flags & CV_SET_ELEM_IDX_MASK)
1202
1203 /* Retrieves index of a graph edge given its pointer */
1204 #define cvGraphEdgeIdx( graph, edge ) ((edge)->flags & CV_SET_ELEM_IDX_MASK)
1205
1206 #define cvGraphGetVtxCount( graph ) ((graph)->active_count)
1207 #define cvGraphGetEdgeCount( graph ) ((graph)->edges->active_count)
1208
1209 #define  CV_GRAPH_VERTEX        1
1210 #define  CV_GRAPH_TREE_EDGE     2
1211 #define  CV_GRAPH_BACK_EDGE     4
1212 #define  CV_GRAPH_FORWARD_EDGE  8
1213 #define  CV_GRAPH_CROSS_EDGE    16
1214 #define  CV_GRAPH_ANY_EDGE      30
1215 #define  CV_GRAPH_NEW_TREE      32
1216 #define  CV_GRAPH_BACKTRACKING  64
1217 #define  CV_GRAPH_OVER          -1
1218
1219 #define  CV_GRAPH_ALL_ITEMS    -1
1220
1221 /* flags for graph vertices and edges */
1222 #define  CV_GRAPH_ITEM_VISITED_FLAG  (1 << 30)
1223 #define  CV_IS_GRAPH_VERTEX_VISITED(vtx) \
1224     (((CvGraphVtx*)(vtx))->flags & CV_GRAPH_ITEM_VISITED_FLAG)
1225 #define  CV_IS_GRAPH_EDGE_VISITED(edge) \
1226     (((CvGraphEdge*)(edge))->flags & CV_GRAPH_ITEM_VISITED_FLAG)
1227 #define  CV_GRAPH_SEARCH_TREE_NODE_FLAG   (1 << 29)
1228 #define  CV_GRAPH_FORWARD_EDGE_FLAG       (1 << 28)
1229
1230 typedef struct CvGraphScanner
1231 {
1232     CvGraphVtx* vtx;       /* current graph vertex (or current edge origin) */
1233     CvGraphVtx* dst;       /* current graph edge destination vertex */
1234     CvGraphEdge* edge;     /* current edge */
1235
1236     CvGraph* graph;        /* the graph */
1237     CvSeq*   stack;        /* the graph vertex stack */
1238     int      index;        /* the lower bound of certainly visited vertices */
1239     int      mask;         /* event mask */
1240 }
1241 CvGraphScanner;
1242
1243 /* Creates new graph scanner. */
1244 CVAPI(CvGraphScanner*)  cvCreateGraphScanner( CvGraph* graph,
1245                                              CvGraphVtx* vtx CV_DEFAULT(NULL),
1246                                              int mask CV_DEFAULT(CV_GRAPH_ALL_ITEMS));
1247
1248 /* Releases graph scanner. */
1249 CVAPI(void) cvReleaseGraphScanner( CvGraphScanner** scanner );
1250
1251 /* Get next graph element */
1252 CVAPI(int)  cvNextGraphItem( CvGraphScanner* scanner );
1253
1254 /* Creates a copy of graph */
1255 CVAPI(CvGraph*) cvCloneGraph( const CvGraph* graph, CvMemStorage* storage );
1256
1257 /****************************************************************************************\
1258 *                                     Drawing                                            *
1259 \****************************************************************************************/
1260
1261 /****************************************************************************************\
1262 *       Drawing functions work with images/matrices of arbitrary type.                   *
1263 *       For color images the channel order is BGR[A]                                     *
1264 *       Antialiasing is supported only for 8-bit image now.                              *
1265 *       All the functions include parameter color that means rgb value (that may be      *
1266 *       constructed with CV_RGB macro) for color images and brightness                   *
1267 *       for grayscale images.                                                            *
1268 *       If a drawn figure is partially or completely outside of the image, it is clipped.*
1269 \****************************************************************************************/
1270
1271 #define CV_RGB( r, g, b )  cvScalar( (b), (g), (r), 0 )
1272 #define CV_FILLED -1
1273
1274 #define CV_AA 16
1275
1276 /* Draws 4-connected, 8-connected or antialiased line segment connecting two points */
1277 CVAPI(void)  cvLine( CvArr* img, CvPoint pt1, CvPoint pt2,
1278                      CvScalar color, int thickness CV_DEFAULT(1),
1279                      int line_type CV_DEFAULT(8), int shift CV_DEFAULT(0) );
1280
1281 /* Draws a rectangle given two opposite corners of the rectangle (pt1 & pt2),
1282    if thickness<0 (e.g. thickness == CV_FILLED), the filled box is drawn */
1283 CVAPI(void)  cvRectangle( CvArr* img, CvPoint pt1, CvPoint pt2,
1284                           CvScalar color, int thickness CV_DEFAULT(1),
1285                           int line_type CV_DEFAULT(8),
1286                           int shift CV_DEFAULT(0));
1287
1288 /* Draws a circle with specified center and radius.
1289    Thickness works in the same way as with cvRectangle */
1290 CVAPI(void)  cvCircle( CvArr* img, CvPoint center, int radius,
1291                        CvScalar color, int thickness CV_DEFAULT(1),
1292                        int line_type CV_DEFAULT(8), int shift CV_DEFAULT(0));
1293
1294 /* Draws ellipse outline, filled ellipse, elliptic arc or filled elliptic sector,
1295    depending on <thickness>, <start_angle> and <end_angle> parameters. The resultant figure
1296    is rotated by <angle>. All the angles are in degrees */
1297 CVAPI(void)  cvEllipse( CvArr* img, CvPoint center, CvSize axes,
1298                         double angle, double start_angle, double end_angle,
1299                         CvScalar color, int thickness CV_DEFAULT(1),
1300                         int line_type CV_DEFAULT(8), int shift CV_DEFAULT(0));
1301
1302 CV_INLINE  void  cvEllipseBox( CvArr* img, CvBox2D box, CvScalar color,
1303                                int thickness CV_DEFAULT(1),
1304                                int line_type CV_DEFAULT(8), int shift CV_DEFAULT(0) )
1305 {
1306     CvSize axes;
1307     axes.width = cvRound(box.size.height*0.5);
1308     axes.height = cvRound(box.size.width*0.5);
1309
1310     cvEllipse( img, cvPointFrom32f( box.center ), axes, box.angle,
1311                0, 360, color, thickness, line_type, shift );
1312 }
1313
1314 /* Fills convex or monotonous polygon. */
1315 CVAPI(void)  cvFillConvexPoly( CvArr* img, CvPoint* pts, int npts, CvScalar color,
1316                                int line_type CV_DEFAULT(8), int shift CV_DEFAULT(0));
1317
1318 /* Fills an area bounded by one or more arbitrary polygons */
1319 CVAPI(void)  cvFillPoly( CvArr* img, CvPoint** pts, int* npts, int contours, CvScalar color,
1320                          int line_type CV_DEFAULT(8), int shift CV_DEFAULT(0) );
1321
1322 /* Draws one or more polygonal curves */
1323 CVAPI(void)  cvPolyLine( CvArr* img, CvPoint** pts, int* npts, int contours,
1324                          int is_closed, CvScalar color, int thickness CV_DEFAULT(1),
1325                          int line_type CV_DEFAULT(8), int shift CV_DEFAULT(0) );
1326
1327 #define cvDrawRect cvRectangle
1328 #define cvDrawLine cvLine
1329 #define cvDrawCircle cvCircle
1330 #define cvDrawEllipse cvEllipse
1331 #define cvDrawPolyLine cvPolyLine
1332
1333 /* Clips the line segment connecting *pt1 and *pt2
1334    by the rectangular window
1335    (0<=x<img_size.width, 0<=y<img_size.height). */
1336 CVAPI(int) cvClipLine( CvSize img_size, CvPoint* pt1, CvPoint* pt2 );
1337
1338 /* Initializes line iterator. Initially, line_iterator->ptr will point
1339    to pt1 (or pt2, see left_to_right description) location in the image.
1340    Returns the number of pixels on the line between the ending points. */
1341 CVAPI(int)  cvInitLineIterator( const CvArr* image, CvPoint pt1, CvPoint pt2,
1342                                 CvLineIterator* line_iterator,
1343                                 int connectivity CV_DEFAULT(8),
1344                                 int left_to_right CV_DEFAULT(0));
1345
1346 /* Moves iterator to the next line point */
1347 #define CV_NEXT_LINE_POINT( line_iterator )                     \
1348 {                                                               \
1349     int _line_iterator_mask = (line_iterator).err < 0 ? -1 : 0; \
1350     (line_iterator).err += (line_iterator).minus_delta +        \
1351         ((line_iterator).plus_delta & _line_iterator_mask);     \
1352     (line_iterator).ptr += (line_iterator).minus_step +         \
1353         ((line_iterator).plus_step & _line_iterator_mask);      \
1354 }
1355
1356
1357 /* basic font types */
1358 #define CV_FONT_HERSHEY_SIMPLEX         0
1359 #define CV_FONT_HERSHEY_PLAIN           1
1360 #define CV_FONT_HERSHEY_DUPLEX          2
1361 #define CV_FONT_HERSHEY_COMPLEX         3
1362 #define CV_FONT_HERSHEY_TRIPLEX         4
1363 #define CV_FONT_HERSHEY_COMPLEX_SMALL   5
1364 #define CV_FONT_HERSHEY_SCRIPT_SIMPLEX  6
1365 #define CV_FONT_HERSHEY_SCRIPT_COMPLEX  7
1366
1367 /* font flags */
1368 #define CV_FONT_ITALIC                 16
1369
1370 #define CV_FONT_VECTOR0    CV_FONT_HERSHEY_SIMPLEX
1371
1372 /* Font structure */
1373 typedef struct CvFont
1374 {
1375     int         font_face; /* =CV_FONT_* */
1376     const int*  ascii; /* font data and metrics */
1377     const int*  greek;
1378     const int*  cyrillic;
1379     float       hscale, vscale;
1380     float       shear; /* slope coefficient: 0 - normal, >0 - italic */
1381     int         thickness; /* letters thickness */
1382     float       dx; /* horizontal interval between letters */
1383     int         line_type;
1384 }
1385 CvFont;
1386
1387 /* Initializes font structure used further in cvPutText */
1388 CVAPI(void)  cvInitFont( CvFont* font, int font_face,
1389                          double hscale, double vscale,
1390                          double shear CV_DEFAULT(0),
1391                          int thickness CV_DEFAULT(1),
1392                          int line_type CV_DEFAULT(8));
1393
1394 CV_INLINE CvFont cvFont( double scale, int thickness CV_DEFAULT(1) )
1395 {
1396     CvFont font;
1397     cvInitFont( &font, CV_FONT_HERSHEY_PLAIN, scale, scale, 0, thickness, CV_AA );
1398     return font;
1399 }
1400
1401 /* Renders text stroke with specified font and color at specified location.
1402    CvFont should be initialized with cvInitFont */
1403 CVAPI(void)  cvPutText( CvArr* img, const char* text, CvPoint org,
1404                         const CvFont* font, CvScalar color );
1405
1406 /* Calculates bounding box of text stroke (useful for alignment) */
1407 CVAPI(void)  cvGetTextSize( const char* text_string, const CvFont* font,
1408                             CvSize* text_size, int* baseline );
1409
1410 /* Unpacks color value, if arrtype is CV_8UC?, <color> is treated as
1411    packed color value, otherwise the first channels (depending on arrtype)
1412    of destination scalar are set to the same value = <color> */
1413 CVAPI(CvScalar)  cvColorToScalar( double packed_color, int arrtype );
1414
1415 /* Returns the polygon points which make up the given ellipse.  The ellipse is define by
1416    the box of size 'axes' rotated 'angle' around the 'center'.  A partial sweep
1417    of the ellipse arc can be done by spcifying arc_start and arc_end to be something
1418    other than 0 and 360, respectively.  The input array 'pts' must be large enough to
1419    hold the result.  The total number of points stored into 'pts' is returned by this
1420    function. */
1421 CVAPI(int) cvEllipse2Poly( CvPoint center, CvSize axes,
1422                  int angle, int arc_start, int arc_end, CvPoint * pts, int delta );
1423
1424 /* Draws contour outlines or filled interiors on the image */
1425 CVAPI(void)  cvDrawContours( CvArr *img, CvSeq* contour,
1426                             CvScalar external_color, CvScalar hole_color,
1427                             int max_level, int thickness CV_DEFAULT(1),
1428                             int line_type CV_DEFAULT(8),
1429                             CvPoint offset CV_DEFAULT(cvPoint(0,0)));
1430
1431 /* Does look-up transformation. Elements of the source array
1432    (that should be 8uC1 or 8sC1) are used as indexes in lutarr 256-element table */
1433 CVAPI(void) cvLUT( const CvArr* src, CvArr* dst, const CvArr* lut );
1434
1435
1436 /******************* Iteration through the sequence tree *****************/
1437 typedef struct CvTreeNodeIterator
1438 {
1439     const void* node;
1440     int level;
1441     int max_level;
1442 }
1443 CvTreeNodeIterator;
1444
1445 CVAPI(void) cvInitTreeNodeIterator( CvTreeNodeIterator* tree_iterator,
1446                                    const void* first, int max_level );
1447 CVAPI(void*) cvNextTreeNode( CvTreeNodeIterator* tree_iterator );
1448 CVAPI(void*) cvPrevTreeNode( CvTreeNodeIterator* tree_iterator );
1449
1450 /* Inserts sequence into tree with specified "parent" sequence.
1451    If parent is equal to frame (e.g. the most external contour),
1452    then added contour will have null pointer to parent. */
1453 CVAPI(void) cvInsertNodeIntoTree( void* node, void* parent, void* frame );
1454
1455 /* Removes contour from tree (together with the contour children). */
1456 CVAPI(void) cvRemoveNodeFromTree( void* node, void* frame );
1457
1458 /* Gathers pointers to all the sequences,
1459    accessible from the <first>, to the single sequence */
1460 CVAPI(CvSeq*) cvTreeToNodeSeq( const void* first, int header_size,
1461                               CvMemStorage* storage );
1462
1463 /* The function implements the K-means algorithm for clustering an array of sample
1464    vectors in a specified number of classes */
1465 CVAPI(void)  cvKMeans2( const CvArr* samples, int cluster_count,
1466                         CvArr* labels, CvTermCriteria termcrit );
1467
1468 /****************************************************************************************\
1469 *                                    System functions                                    *
1470 \****************************************************************************************/
1471
1472 /* Add the function pointers table with associated information to the IPP primitives list */
1473 CVAPI(int)  cvRegisterModule( const CvModuleInfo* module_info );
1474
1475 /* Loads optimized functions from IPP, MKL etc. or switches back to pure C code */
1476 CVAPI(int)  cvUseOptimized( int on_off );
1477
1478 /* Retrieves information about the registered modules and loaded optimized plugins */
1479 CVAPI(void)  cvGetModuleInfo( const char* module_name,
1480                               const char** version,
1481                               const char** loaded_addon_plugins );
1482
1483 /* Get current OpenCV error status */
1484 CVAPI(int) cvGetErrStatus( void );
1485
1486 /* Sets error status silently */
1487 CVAPI(void) cvSetErrStatus( int status );
1488
1489 #define CV_ErrModeLeaf     0   /* Print error and exit program */
1490 #define CV_ErrModeParent   1   /* Print error and continue */
1491 #define CV_ErrModeSilent   2   /* Don't print and continue */
1492
1493 /* Retrives current error processing mode */
1494 CVAPI(int)  cvGetErrMode( void );
1495
1496 /* Sets error processing mode, returns previously used mode */
1497 CVAPI(int) cvSetErrMode( int mode );
1498
1499 /* Sets error status and performs some additonal actions (displaying message box,
1500    writing message to stderr, terminating application etc.)
1501    depending on the current error mode */
1502 CVAPI(void) cvError( int status, const char* func_name,
1503                     const char* err_msg, const char* file_name, int line );
1504
1505 /* Retrieves textual description of the error given its code */
1506 CVAPI(const char*) cvErrorStr( int status );
1507
1508 /* Retrieves detailed information about the last error occured */
1509 CVAPI(int) cvGetErrInfo( const char** errcode_desc, const char** description,
1510                         const char** filename, int* line );
1511
1512 /* Maps IPP error codes to the counterparts from OpenCV */
1513 CVAPI(int) cvErrorFromIppStatus( int ipp_status );
1514
1515 typedef int (CV_CDECL *CvErrorCallback)( int status, const char* func_name,
1516                     const char* err_msg, const char* file_name, int line, void* userdata );
1517
1518 /* Assigns a new error-handling function */
1519 CVAPI(CvErrorCallback) cvRedirectError( CvErrorCallback error_handler,
1520                                        void* userdata CV_DEFAULT(NULL),
1521                                        void** prev_userdata CV_DEFAULT(NULL) );
1522
1523 /*
1524     Output to:
1525         cvNulDevReport - nothing
1526         cvStdErrReport - console(fprintf(stderr,...))
1527         cvGuiBoxReport - MessageBox(WIN32)
1528 */
1529 CVAPI(int) cvNulDevReport( int status, const char* func_name, const char* err_msg,
1530                           const char* file_name, int line, void* userdata );
1531
1532 CVAPI(int) cvStdErrReport( int status, const char* func_name, const char* err_msg,
1533                           const char* file_name, int line, void* userdata );
1534
1535 CVAPI(int) cvGuiBoxReport( int status, const char* func_name, const char* err_msg,
1536                           const char* file_name, int line, void* userdata );
1537
1538 typedef void* (CV_CDECL *CvAllocFunc)(size_t size, void* userdata);
1539 typedef int (CV_CDECL *CvFreeFunc)(void* pptr, void* userdata);
1540
1541 /* Set user-defined memory managment functions (substitutors for malloc and free) that
1542    will be called by cvAlloc, cvFree and higher-level functions (e.g. cvCreateImage) */
1543 CVAPI(void) cvSetMemoryManager( CvAllocFunc alloc_func CV_DEFAULT(NULL),
1544                                CvFreeFunc free_func CV_DEFAULT(NULL),
1545                                void* userdata CV_DEFAULT(NULL));
1546
1547
1548 typedef IplImage* (CV_STDCALL* Cv_iplCreateImageHeader)
1549                             (int,int,int,char*,char*,int,int,int,int,int,
1550                             IplROI*,IplImage*,void*,IplTileInfo*);
1551 typedef void (CV_STDCALL* Cv_iplAllocateImageData)(IplImage*,int,int);
1552 typedef void (CV_STDCALL* Cv_iplDeallocate)(IplImage*,int);
1553 typedef IplROI* (CV_STDCALL* Cv_iplCreateROI)(int,int,int,int,int);
1554 typedef IplImage* (CV_STDCALL* Cv_iplCloneImage)(const IplImage*);
1555
1556 /* Makes OpenCV use IPL functions for IplImage allocation/deallocation */
1557 CVAPI(void) cvSetIPLAllocators( Cv_iplCreateImageHeader create_header,
1558                                Cv_iplAllocateImageData allocate_data,
1559                                Cv_iplDeallocate deallocate,
1560                                Cv_iplCreateROI create_roi,
1561                                Cv_iplCloneImage clone_image );
1562
1563 #define CV_TURN_ON_IPL_COMPATIBILITY()                                  \
1564     cvSetIPLAllocators( iplCreateImageHeader, iplAllocateImage,         \
1565                         iplDeallocate, iplCreateROI, iplCloneImage )
1566
1567 /****************************************************************************************\
1568 *                                    Data Persistence                                    *
1569 \****************************************************************************************/
1570
1571 /********************************** High-level functions ********************************/
1572
1573 /* opens existing or creates new file storage */
1574 CVAPI(CvFileStorage*)  cvOpenFileStorage( const char* filename,
1575                                           CvMemStorage* memstorage,
1576                                           int flags );
1577
1578 /* closes file storage and deallocates buffers */
1579 CVAPI(void) cvReleaseFileStorage( CvFileStorage** fs );
1580
1581 /* returns attribute value or 0 (NULL) if there is no such attribute */
1582 CVAPI(const char*) cvAttrValue( const CvAttrList* attr, const char* attr_name );
1583
1584 /* starts writing compound structure (map or sequence) */
1585 CVAPI(void) cvStartWriteStruct( CvFileStorage* fs, const char* name,
1586                                 int struct_flags, const char* type_name CV_DEFAULT(NULL),
1587                                 CvAttrList attributes CV_DEFAULT(cvAttrList()));
1588
1589 /* finishes writing compound structure */
1590 CVAPI(void) cvEndWriteStruct( CvFileStorage* fs );
1591
1592 /* writes an integer */
1593 CVAPI(void) cvWriteInt( CvFileStorage* fs, const char* name, int value );
1594
1595 /* writes a floating-point number */
1596 CVAPI(void) cvWriteReal( CvFileStorage* fs, const char* name, double value );
1597
1598 /* writes a string */
1599 CVAPI(void) cvWriteString( CvFileStorage* fs, const char* name,
1600                            const char* str, int quote CV_DEFAULT(0) );
1601
1602 /* writes a comment */
1603 CVAPI(void) cvWriteComment( CvFileStorage* fs, const char* comment,
1604                             int eol_comment );
1605
1606 /* writes instance of a standard type (matrix, image, sequence, graph etc.)
1607    or user-defined type */
1608 CVAPI(void) cvWrite( CvFileStorage* fs, const char* name, const void* ptr,
1609                          CvAttrList attributes CV_DEFAULT(cvAttrList()));
1610
1611 /* starts the next stream */
1612 CVAPI(void) cvStartNextStream( CvFileStorage* fs );
1613
1614 /* helper function: writes multiple integer or floating-point numbers */
1615 CVAPI(void) cvWriteRawData( CvFileStorage* fs, const void* src,
1616                                 int len, const char* dt );
1617
1618 /* returns the hash entry corresponding to the specified literal key string or 0
1619    if there is no such a key in the storage */
1620 CVAPI(CvStringHashNode*) cvGetHashedKey( CvFileStorage* fs, const char* name,
1621                                         int len CV_DEFAULT(-1),
1622                                         int create_missing CV_DEFAULT(0));
1623
1624 /* returns file node with the specified key within the specified map
1625    (collection of named nodes) */
1626 CVAPI(CvFileNode*) cvGetRootFileNode( const CvFileStorage* fs,
1627                                      int stream_index CV_DEFAULT(0) );
1628
1629 /* returns file node with the specified key within the specified map
1630    (collection of named nodes) */
1631 CVAPI(CvFileNode*) cvGetFileNode( CvFileStorage* fs, CvFileNode* map,
1632                                  const CvStringHashNode* key,
1633                                  int create_missing CV_DEFAULT(0) );
1634
1635 /* this is a slower version of cvGetFileNode that takes the key as a literal string */
1636 CVAPI(CvFileNode*) cvGetFileNodeByName( const CvFileStorage* fs,
1637                                        const CvFileNode* map,
1638                                        const char* name );
1639
1640 CV_INLINE int cvReadInt( const CvFileNode* node, int default_value CV_DEFAULT(0) )
1641 {
1642     return !node ? default_value :
1643         CV_NODE_IS_INT(node->tag) ? node->data.i :
1644         CV_NODE_IS_REAL(node->tag) ? cvRound(node->data.f) : 0x7fffffff;
1645 }
1646
1647
1648 CV_INLINE int cvReadIntByName( const CvFileStorage* fs, const CvFileNode* map,
1649                          const char* name, int default_value CV_DEFAULT(0) )
1650 {
1651     return cvReadInt( cvGetFileNodeByName( fs, map, name ), default_value );
1652 }
1653
1654
1655 CV_INLINE double cvReadReal( const CvFileNode* node, double default_value CV_DEFAULT(0.) )
1656 {
1657     return !node ? default_value :
1658         CV_NODE_IS_INT(node->tag) ? (double)node->data.i :
1659         CV_NODE_IS_REAL(node->tag) ? node->data.f : 1e300;
1660 }
1661
1662
1663 CV_INLINE double cvReadRealByName( const CvFileStorage* fs, const CvFileNode* map,
1664                         const char* name, double default_value CV_DEFAULT(0.) )
1665 {
1666     return cvReadReal( cvGetFileNodeByName( fs, map, name ), default_value );
1667 }
1668
1669
1670 CV_INLINE const char* cvReadString( const CvFileNode* node,
1671                         const char* default_value CV_DEFAULT(NULL) )
1672 {
1673     return !node ? default_value : CV_NODE_IS_STRING(node->tag) ? node->data.str.ptr : 0;
1674 }
1675
1676
1677 CV_INLINE const char* cvReadStringByName( const CvFileStorage* fs, const CvFileNode* map,
1678                         const char* name, const char* default_value CV_DEFAULT(NULL) )
1679 {
1680     return cvReadString( cvGetFileNodeByName( fs, map, name ), default_value );
1681 }
1682
1683
1684 /* decodes standard or user-defined object and returns it */
1685 CVAPI(void*) cvRead( CvFileStorage* fs, CvFileNode* node,
1686                         CvAttrList* attributes CV_DEFAULT(NULL));
1687
1688 /* decodes standard or user-defined object and returns it */
1689 CV_INLINE void* cvReadByName( CvFileStorage* fs, const CvFileNode* map,
1690                               const char* name, CvAttrList* attributes CV_DEFAULT(NULL) )
1691 {
1692     return cvRead( fs, cvGetFileNodeByName( fs, map, name ), attributes );
1693 }
1694
1695
1696 /* starts reading data from sequence or scalar numeric node */
1697 CVAPI(void) cvStartReadRawData( const CvFileStorage* fs, const CvFileNode* src,
1698                                CvSeqReader* reader );
1699
1700 /* reads multiple numbers and stores them to array */
1701 CVAPI(void) cvReadRawDataSlice( const CvFileStorage* fs, CvSeqReader* reader,
1702                                int count, void* dst, const char* dt );
1703
1704 /* combination of two previous functions for easier reading of whole sequences */
1705 CVAPI(void) cvReadRawData( const CvFileStorage* fs, const CvFileNode* src,
1706                           void* dst, const char* dt );
1707
1708 /* writes a copy of file node to file storage */
1709 CVAPI(void) cvWriteFileNode( CvFileStorage* fs, const char* new_node_name,
1710                             const CvFileNode* node, int embed );
1711
1712 /* returns name of file node */
1713 CVAPI(const char*) cvGetFileNodeName( const CvFileNode* node );
1714
1715 /*********************************** Adding own types ***********************************/
1716
1717 CVAPI(void) cvRegisterType( const CvTypeInfo* info );
1718 CVAPI(void) cvUnregisterType( const char* type_name );
1719 CVAPI(CvTypeInfo*) cvFirstType(void);
1720 CVAPI(CvTypeInfo*) cvFindType( const char* type_name );
1721 CVAPI(CvTypeInfo*) cvTypeOf( const void* struct_ptr );
1722
1723 /* universal functions */
1724 CVAPI(void) cvRelease( void** struct_ptr );
1725 CVAPI(void*) cvClone( const void* struct_ptr );
1726
1727 /* simple API for reading/writing data */
1728 CVAPI(void) cvSave( const char* filename, const void* struct_ptr,
1729                     const char* name CV_DEFAULT(NULL),
1730                     const char* comment CV_DEFAULT(NULL),
1731                     CvAttrList attributes CV_DEFAULT(cvAttrList()));
1732 CVAPI(void*) cvLoad( const char* filename,
1733                      CvMemStorage* memstorage CV_DEFAULT(NULL),
1734                      const char* name CV_DEFAULT(NULL),
1735                      const char** real_name CV_DEFAULT(NULL) );
1736
1737 /*********************************** Measuring Execution Time ***************************/
1738
1739 /* helper functions for RNG initialization and accurate time measurement:
1740    uses internal clock counter on x86 */
1741 CVAPI(int64)  cvGetTickCount( void );
1742 CVAPI(double) cvGetTickFrequency( void );
1743
1744 /*********************************** Multi-Threading ************************************/
1745
1746 /* retrieve/set the number of threads used in OpenMP implementations */
1747 CVAPI(int)  cvGetNumThreads( void );
1748 CVAPI(void) cvSetNumThreads( int threads CV_DEFAULT(0) );
1749 /* get index of the thread being executed */
1750 CVAPI(int)  cvGetThreadNum( void );
1751
1752 /*************** Convenience functions for better interaction with HighGUI **************/
1753
1754 typedef IplImage* (CV_CDECL * CvLoadImageFunc)( const char* filename, int colorness );
1755 typedef CvMat* (CV_CDECL * CvLoadImageMFunc)( const char* filename, int colorness );
1756 typedef int (CV_CDECL * CvSaveImageFunc)( const char* filename, const CvArr* image );
1757 typedef void (CV_CDECL * CvShowImageFunc)( const char* windowname, const CvArr* image );
1758
1759 CVAPI(int) cvSetImageIOFunctions( CvLoadImageFunc _load_image, CvLoadImageMFunc _load_image_m,
1760                             CvSaveImageFunc _save_image, CvShowImageFunc _show_image );
1761
1762 #define CV_SET_IMAGE_IO_FUNCTIONS() \
1763     cvSetImageIOFunctions( cvLoadImage, cvLoadImageM, cvSaveImage, cvShowImage )
1764
1765 #ifdef __cplusplus
1766 }
1767
1768 #include "cxcore.hpp"
1769 #endif
1770
1771 #endif /*_CXCORE_H_*/