]> rtime.felk.cvut.cz Git - opencv.git/blob - opencv/doc/cxcore_utilities_system_functions.tex
added partitioned docs
[opencv.git] / opencv / doc / cxcore_utilities_system_functions.tex
1 \section{Utility and System Functions and Macros}
2
3 \ifCPy
4 \cvfunc{Error Handling}\label{Error handling}
5
6 \ifPy
7 Errors in argument type cause a \texttt{TypeError} exception.
8 OpenCV errors cause a cv.error exception.
9 \fi
10
11 \ifC
12 Error handling in OpenCV is similar to IPL (Image Processing
13 Library). In the case of an error, functions do not return the error
14 code. Instead, they raise an error using \texttt{CV\_ERROR}
15 macro that calls \cvCPyCross{Error} that, in its turn, sets the error
16 status with \cvCPyCross{SetErrStatus} and calls a standard or user-defined
17 error handler (that can display a message box, write to log, etc., see
18 \cvCPyCross{RedirectError}).  There is a global variable, one per each program
19 thread, that contains current error status (an integer value). The status
20 can be retrieved with the \cvCPyCross{GetErrStatus} function.
21
22 There are three modes of error handling (see \cvCPyCross{SetErrMode} and
23 \cvCPyCross{GetErrMode}):
24
25 \begin{description}
26 \cvarg{Leaf}{The program is terminated after the error handler is
27 called. This is the default value. It is useful for debugging, as the
28 error is signalled immediately after it occurs. However, for production
29 systems, other two methods may be preferable as they provide more
30 control.}
31 \cvarg{Parent}{The program is not terminated, but the error handler
32 is called. The stack is unwound (it is done w/o using a C++ exception
33 mechanism). The user may check error code after calling the \texttt{CxCore} function with
34 \cvCPyCross{GetErrStatus} and react.}
35 \cvarg{Silent}{Similar to \texttt{Parent} mode, but no error handler
36 is called}
37 \end{description}
38
39 Actually, the semantics of the \texttt{Leaf} and \texttt{Parent} modes are implemented by error handlers and the above description is true for them. \cvCPyCross{GuiBoxReport} behaves slightly differently, and some custom error handlers may implement quite different semantics.  
40
41 Macros for raising an error, checking for errors, etc.
42 \begin{lstlisting}
43
44 /* special macros for enclosing processing statements within a function and separating
45    them from prologue (resource initialization) and epilogue (guaranteed resource release) */
46 #define __BEGIN__       {
47 #define __END__         goto exit; exit: ; }
48 /* proceeds to "resource release" stage */
49 #define EXIT            goto exit
50
51 /* Declares locally the function name for CV_ERROR() use */
52 #define CV_FUNCNAME( Name )  \
53     static char cvFuncName[] = Name
54
55 /* Raises an error within the current context */
56 #define CV_ERROR( Code, Msg )                                       \
57 {                                                                   \
58      cvError( (Code), cvFuncName, Msg, __FILE__, __LINE__ );        \
59      EXIT;                                                          \
60 }
61
62 /* Checks status after calling CXCORE function */
63 #define CV_CHECK()                                                  \
64 {                                                                   \
65     if( cvGetErrStatus() < 0 )                                   \
66         CV_ERROR( CV_StsBackTrace, "Inner function failed." );      \
67 }
68
69 /* Provies shorthand for CXCORE function call and CV_CHECK() */
70 #define CV_CALL( Statement )                                        \
71 {                                                                   \
72     Statement;                                                      \
73     CV_CHECK();                                                     \
74 }
75
76 /* Checks some condition in both debug and release configurations */
77 #define CV_ASSERT( Condition )                                          \
78 {                                                                       \
79     if( !(Condition) )                                                  \
80         CV_ERROR( CV_StsInternal, "Assertion: " #Condition " failed" ); \
81 }
82
83 /* these macros are similar to their CV_... counterparts, but they
84    do not need exit label nor cvFuncName to be defined */
85 #define OPENCV_ERROR(status,func_name,err_msg) ...
86 #define OPENCV_ERRCHK(func_name,err_msg) ...
87 #define OPENCV_ASSERT(condition,func_name,err_msg) ...
88 #define OPENCV_CALL(statement) ...
89
90 \end{lstlisting}
91
92 Instead of a discussion, below is a documented example of a typical CXCORE function and an example of the function use.
93
94 \cvfunc{Example: Use of Error Handling Macros}
95 \begin{lstlisting}
96
97 #include "cxcore.h"
98 #include <stdio.h>
99
100 void cvResizeDCT( CvMat* input_array, CvMat* output_array )
101 {
102     CvMat* temp_array = 0; // declare pointer that should be released anyway.
103
104     CV_FUNCNAME( "cvResizeDCT" ); // declare cvFuncName
105
106     __BEGIN__; // start processing. There may be some declarations just after 
107               // this macro, but they could not be accessed from the epilogue.
108
109     if( !CV_IS_MAT(input_array) || !CV_IS_MAT(output_array) )
110         // use CV_ERROR() to raise an error
111         CV_ERROR( CV_StsBadArg, 
112         "input_array or output_array are not valid matrices" );
113
114     // some restrictions that are going to be removed later, may be checked 
115     // with CV_ASSERT()
116     CV_ASSERT( input_array->rows == 1 && output_array->rows == 1 );
117
118     // use CV_CALL for safe function call
119     CV_CALL( temp_array = cvCreateMat( input_array->rows,
120                                        MAX(input_array->cols,
121                                        output_array->cols),
122                                        input_array->type ));
123
124     if( output_array->cols > input_array->cols )
125         CV_CALL( cvZero( temp_array ));
126
127     temp_array->cols = input_array->cols;
128     CV_CALL( cvDCT( input_array, temp_array, CV_DXT_FORWARD ));
129     temp_array->cols = output_array->cols;
130     CV_CALL( cvDCT( temp_array, output_array, CV_DXT_INVERSE ));
131     CV_CALL( cvScale( output_array,
132                       output_array,
133                       1./sqrt((double)input_array->cols*output_array->cols), 0 ));
134
135     __END__; // finish processing. Epilogue follows after the macro.
136
137     // release temp_array. If temp_array has not been allocated
138     // before an error occured, cvReleaseMat
139     // takes care of it and does nothing in this case.
140     cvReleaseMat( &temp_array );
141 }
142
143 int main( int argc, char** argv )
144 {
145     CvMat* src = cvCreateMat( 1, 512, CV_32F );
146 #if 1 /* no errors */
147     CvMat* dst = cvCreateMat( 1, 256, CV_32F );
148 #else
149     CvMat* dst = 0; /* test error processing mechanism */
150 #endif
151     cvSet( src, cvRealScalar(1.), 0 );
152 #if 0 /* change 0 to 1 to suppress error handler invocation */
153     cvSetErrMode( CV_ErrModeSilent );
154 #endif
155     cvResizeDCT( src, dst ); // if some error occurs, the message
156                              // box will popup, or a message will be
157                              // written to log, or some user-defined
158                              // processing will be done
159     if( cvGetErrStatus() < 0 )
160         printf("Some error occured" );
161     else
162         printf("Everything is OK" );
163     return 0;
164 }
165 \end{lstlisting}
166
167 \cvCPyFunc{GetErrStatus}
168 Returns the current error status.
169
170 \cvcodeC{int cvGetErrStatus( void );}
171
172 The function returns the current error status -
173 the value set with the last \cvCPyCross{SetErrStatus} call. Note that in
174 \texttt{Leaf} mode, the program terminates immediately after an
175 error occurs, so to always gain control after the function call,
176 one should call \cvCPyCross{SetErrMode} and set the \texttt{Parent}
177 or \texttt{Silent} error mode.
178
179 \cvCPyFunc{SetErrStatus}
180 Sets the error status.
181
182 \cvcodeC{void cvSetErrStatus( int status );}
183
184 \begin{description}
185 \cvarg{status}{The error status}
186 \end{description}
187
188 The function sets the error status to the specified value. Mostly, the function is used to reset the error status (set to it \texttt{CV\_StsOk}) to recover after an error. In other cases it is more natural to call \cvCPyCross{Error} or \texttt{CV\_ERROR}.
189
190 \cvCPyFunc{GetErrMode}
191 Returns the current error mode.
192
193 \cvcodeC{int cvGetErrMode(void);}
194
195 The function returns the current error mode - the value set with the last \cvCPyCross{SetErrMode} call.
196
197 \cvCPyFunc{SetErrMode}
198 Sets the error mode.
199
200 \begin{lstlisting}
201 #define CV_ErrModeLeaf    0
202 #define CV_ErrModeParent  1
203 #define CV_ErrModeSilent  2
204 \end{lstlisting}
205
206 \cvcodeC{int cvSetErrMode( int mode );}
207
208 \begin{description}
209 \cvarg{mode}{The error mode}
210 \end{description}
211
212 The function sets the specified error mode. For descriptions of different error modes, see the beginning of the error section.
213
214 \cvCPyFunc{Error}
215 Raises an error.
216
217 \cvcodeC{int cvError( \par int status,\par const char* func\_name,\par const char* err\_msg,\par const char* filename,\par int line );}
218
219 \begin{description}
220 \cvarg{status}{The error status}
221 \cvarg{func\_name}{Name of the function where the error occured}
222 \cvarg{err\_msg}{Additional information/diagnostics about the error}
223 \cvarg{filename}{Name of the file where the error occured}
224 \cvarg{line}{Line number, where the error occured}
225 \end{description}
226
227 The function sets the error status to the specified value (via \cvCPyCross{SetErrStatus}) and, if the error mode is not \texttt{Silent}, calls the error handler.
228
229 \cvCPyFunc{ErrorStr}
230 Returns textual description of an error status code.
231
232 \cvcodeC{const char* cvErrorStr( int status );}
233
234 \begin{description}
235 \cvarg{status}{The error status}
236 \end{description}
237
238 The function returns the textual description for
239 the specified error status code. In the case of unknown status, the function
240 returns a NULL pointer.
241
242 \cvCPyFunc{RedirectError}
243 Sets a new error handler.
244
245 \begin{lstlisting}
246 typedef int (CV_CDECL *CvErrorCallback)( int status, const char* func_name,
247                     const char* err_msg, const char* file_name, int line );
248 \end{lstlisting}
249
250 \cvcodeC{CvErrorCallback cvRedirectError( \par CvErrorCallback error\_handler,\par void* userdata=NULL,\par void** prevUserdata=NULL );}
251
252 \begin{description}
253 \cvarg{error\_handler}{The new error\_handler}
254 \cvarg{userdata}{Arbitrary pointer that is transparently passed to the error handler}
255 \cvarg{prevUserdata}{Pointer to the previously assigned user data pointer}
256 \end{description}
257
258 The function sets a new error handler that
259 can be one of the standard handlers or a custom handler
260 that has a specific interface. The handler takes the same parameters
261 as the \cvCPyCross{Error} function. If the handler returns a non-zero value, the
262 program is terminated; otherwise, it continues. The error handler may
263 check the current error mode with \cvCPyCross{GetErrMode} to make a decision.
264
265
266 \cvfunc{cvNulDevReport cvStdErrReport cvGuiBoxReport}
267 \label{cvNulDevReport}
268 \label{cvStdErrReport}
269 \label{cvGuiBoxReport}
270
271 Provide standard error handling.
272
273 \begin{lstlisting}
274 int cvNulDevReport( int status, const char* func_name,
275                     const char* err_msg, const char* file_name,
276                     int line, void* userdata );
277
278 int cvStdErrReport( int status, const char* func_name,
279                     const char* err_msg, const char* file_name,
280                     int line, void* userdata );
281
282 int cvGuiBoxReport( int status, const char* func_name,
283                     const char* err_msg, const char* file_name,
284                     int line, void* userdata );
285 \end{lstlisting}
286
287 \begin{description}
288 \cvarg{status}{The error status}
289 \cvarg{func\_name}{Name of the function where the error occured}
290 \cvarg{err\_msg}{Additional information/diagnostics about the error}
291 \cvarg{filename}{Name of the file where the error occured}
292 \cvarg{line}{Line number, where the error occured}
293 \cvarg{userdata}{Pointer to the user data. Ignored by the standard handlers}
294 \end{description}
295
296 The functions \texttt{cvNullDevReport}, \texttt{cvStdErrReport},
297 and \texttt{cvGuiBoxReport} provide standard error
298 handling. \texttt{cvGuiBoxReport} is the default error
299 handler on Win32 systems, \texttt{cvStdErrReport} is the default on other
300 systems. \texttt{cvGuiBoxReport} pops up a message box with the error
301 description and suggest a few options. Below is an example message box
302 that may be recieved with the sample code above, if one introduces an
303 error as described in the sample.
304
305 \textbf{Error Message Box}
306 \includegraphics[width=0.5\textwidth]{pics/errmsg.png}
307
308 If the error handler is set to \texttt{cvStdErrReport}, the above message will be printed to standard error output and the program will be terminated or continued, depending on the current error mode.
309
310 \textbf{Error Message printed to Standard Error Output (in \texttt{Leaf} mode)}
311
312 \begin{verbatim}
313 OpenCV ERROR: Bad argument (input_array or output_array are not valid matrices)
314         in function cvResizeDCT, D:\User\VP\Projects\avl\_proba\a.cpp(75)
315 Terminating the application...
316 \end{verbatim}
317
318 \cvCPyFunc{Alloc}
319 Allocates a memory buffer.
320
321 \cvcodeC{void* cvAlloc( size\_t size );}
322
323 \begin{description}
324 \cvarg{size}{Buffer size in bytes}
325 \end{description}
326
327 The function allocates \texttt{size} bytes and returns
328 a pointer to the allocated buffer. In the case of an error the function reports an
329 error and returns a NULL pointer. By default, \texttt{cvAlloc} calls
330 \texttt{icvAlloc} which
331 itself calls \texttt{malloc}. However it is possible to assign user-defined memory
332 allocation/deallocation functions using the \cvCPyCross{SetMemoryManager} function.
333
334 \cvCPyFunc{Free}
335 Deallocates a memory buffer.
336
337 \cvcodeC{void cvFree( void** ptr );}
338
339 \begin{description}
340 \cvarg{ptr}{Double pointer to released buffer}
341 \end{description}
342
343 The function deallocates a memory buffer allocated by
344 \cvCPyCross{Alloc}. It clears the pointer to buffer upon exit, which is why
345 the double pointer is used. If the \texttt{*buffer} is already NULL, the function
346 does nothing.
347
348 \cvCPyFunc{GetTickCount}
349 Returns the number of ticks.
350
351 \cvcodeC{int64 cvGetTickCount( void );}
352
353 The function returns number of the ticks starting from some platform-dependent event (number of CPU ticks from the startup, number of milliseconds from 1970th year, etc.). The function is useful for accurate measurement of a function/user-code execution time. To convert the number of ticks to time units, use \cvCPyCross{GetTickFrequency}.
354
355 \cvCPyFunc{GetTickFrequency}
356 Returns the number of ticks per microsecond.
357
358 \cvcodeC{double cvGetTickFrequency( void );}
359
360 The function returns the number of ticks per microsecond. Thus, the quotient of \cvCPyCross{GetTickCount} and \cvCPyCross{GetTickFrequency} will give the number of microseconds starting from the platform-dependent event.
361
362 \cvCPyFunc{RegisterModule}
363 Registers another module.
364
365 \begin{lstlisting}
366 typedef struct CvPluginFuncInfo
367 {
368     void** func_addr;
369     void* default_func_addr;
370     const char* func_names;
371     int search_modules;
372     int loaded_from;
373 }
374 CvPluginFuncInfo;
375
376 typedef struct CvModuleInfo
377 {
378     struct CvModuleInfo* next;
379     const char* name;
380     const char* version;
381     CvPluginFuncInfo* func_tab;
382 }
383 CvModuleInfo;
384 \end{lstlisting}
385
386 \cvcodeC{int cvRegisterModule( const CvModuleInfo* moduleInfo );}
387
388 \begin{description}
389 \cvarg{moduleInfo}{Information about the module}
390 \end{description}
391
392 The function adds a module to the list of
393 registered modules. After the module is registered, information about
394 it can be retrieved using the \cvCPyCross{GetModuleInfo} function. Also, the
395 registered module makes full use of optimized plugins (IPP, MKL, ...),
396 supported by CXCORE. CXCORE itself, CV (computer vision), CVAUX (auxilary
397 computer vision), and HIGHGUI (visualization and image/video acquisition) are
398 examples of modules. Registration is usually done when the shared library
399 is loaded. See \texttt{cxcore/src/cxswitcher.cpp} and
400 \texttt{cv/src/cvswitcher.cpp} for details about how registration is done
401 and look at \texttt{cxcore/src/cxswitcher.cpp}, \texttt{cxcore/src/\_cxipp.h}
402 on how IPP and MKL are connected to the modules.
403
404 \cvCPyFunc{GetModuleInfo}
405 Retrieves information about registered module(s) and plugins.
406
407 \cvcodeC{
408 void  cvGetModuleInfo( \par const char* moduleName,\par const char** version,\par const char** loadedAddonPlugins);
409 }
410
411 \begin{description}
412 \cvarg{moduleName}{Name of the module of interest, or NULL, which means all the modules}
413 \cvarg{version}{The output parameter. Information about the module(s), including version}
414 \cvarg{loadedAddonPlugins}{The list of names and versions of the optimized plugins that CXCORE was able to find and load}
415 \end{description}
416
417 The function returns information about one or
418 all of the registered modules. The returned information is stored inside
419 the libraries, so the user should not deallocate or modify the returned
420 text strings.
421
422 \cvCPyFunc{UseOptimized}
423 Switches between optimized/non-optimized modes.
424
425 \cvcodeC{int cvUseOptimized( int onoff );}
426
427 \begin{description}
428 \cvarg{onoff}{Use optimized ($\ne 0$) or not ($=0$)}
429 \end{description}
430
431 The function switches between the mode, where
432 only pure C implementations from cxcore, OpenCV, etc. are used, and
433 the mode, where IPP and MKL functions are used if available. When
434 \texttt{cvUseOptimized(0)} is called, all the optimized libraries are
435 unloaded. The function may be useful for debugging, IPP and MKL upgrading on
436 the fly, online speed comparisons, etc. It returns the number of optimized
437 functions loaded. Note that by default, the optimized plugins are loaded,
438 so it is not necessary to call \texttt{cvUseOptimized(1)} in the beginning of
439 the program (actually, it will only increase the startup time).
440
441 \cvCPyFunc{SetMemoryManager}
442 Accesses custom/default memory managing functions.
443
444 \begin{lstlisting}
445 typedef void* (CV_CDECL *CvAllocFunc)(size_t size, void* userdata);
446 typedef int (CV_CDECL *CvFreeFunc)(void* pptr, void* userdata);
447 \end{lstlisting}
448
449 \cvcodeC{
450 void cvSetMemoryManager( \par CvAllocFunc allocFunc=NULL,\par CvFreeFunc freeFunc=NULL,\par void* userdata=NULL );
451 }
452
453 \begin{description}
454 \cvarg{allocFunc}{Allocation function; the interface is similar to \texttt{malloc}, except that \texttt{userdata} may be used to determine the context}
455 \cvarg{freeFunc}{Deallocation function; the interface is similar to \texttt{free}}
456 \cvarg{userdata}{User data that is transparently passed to the custom functions}
457 \end{description}
458
459 The function sets user-defined memory
460 managment functions (substitutes for \texttt{malloc} and \texttt{free}) that will be called
461 by \texttt{cvAlloc, cvFree} and higher-level functions (e.g., \texttt{cvCreateImage}). Note
462 that the function should be called when there is data allocated using
463 \texttt{cvAlloc}. Also, to avoid infinite recursive calls, it is not
464 allowed to call \texttt{cvAlloc} and \cvCPyCross{Free} from the custom
465 allocation/deallocation functions.
466
467 If the \texttt{alloc\_func} and \texttt{free\_func} pointers are
468 \texttt{NULL}, the default memory managing functions are restored.
469
470 \cvCPyFunc{SetIPLAllocators}
471 Switches to IPL functions for image allocation/deallocation.
472
473 \begin{lstlisting}
474 typedef IplImage* (CV_STDCALL* Cv_iplCreateImageHeader)
475                             (int,int,int,char*,char*,int,int,int,int,int,
476                             IplROI*,IplImage*,void*,IplTileInfo*);
477 typedef void (CV_STDCALL* Cv_iplAllocateImageData)(IplImage*,int,int);
478 typedef void (CV_STDCALL* Cv_iplDeallocate)(IplImage*,int);
479 typedef IplROI* (CV_STDCALL* Cv_iplCreateROI)(int,int,int,int,int);
480 typedef IplImage* (CV_STDCALL* Cv_iplCloneImage)(const IplImage*);
481
482 #define CV_TURN_ON_IPL_COMPATIBILITY()                                  \
483     cvSetIPLAllocators( iplCreateImageHeader, iplAllocateImage,         \
484                         iplDeallocate, iplCreateROI, iplCloneImage )
485 \end{lstlisting}
486
487 \cvcodeC{
488 void cvSetIPLAllocators( \par
489                          Cv\_iplCreateImageHeader create\_header, \par
490                          Cv\_iplAllocateImageData allocate\_data, \par
491                          Cv\_iplDeallocate deallocate, \par
492                          Cv\_iplCreateROI create\_roi, \par
493                          Cv\_iplCloneImage clone\_image );
494 }
495
496 \begin{description}
497 \cvarg{create\_header}{Pointer to iplCreateImageHeader}
498 \cvarg{allocate\_data}{Pointer to iplAllocateImage}
499 \cvarg{deallocate}{Pointer to iplDeallocate}
500 \cvarg{create\_roi}{Pointer to iplCreateROI}
501 \cvarg{clone\_image}{Pointer to iplCloneImage}
502 \end{description}
503
504
505 The function causes CXCORE to use IPL functions
506 for image allocation/deallocation operations. For convenience, there
507 is the wrapping macro \texttt{CV\_TURN\_ON\_IPL\_COMPATIBILITY}. The
508 function is useful for applications where IPL and CXCORE/OpenCV are used
509 together and still there are calls to \texttt{iplCreateImageHeader},
510 etc. The function is not necessary if IPL is called only for data
511 processing and all the allocation/deallocation is done by CXCORE, or
512 if all the allocation/deallocation is done by IPL and some of OpenCV
513 functions are used to process the data.
514
515 \fi
516
517 \fi
518
519 \ifCpp
520
521 \cvCppFunc{alignPtr}
522 Aligns pointer to the specified number of bytes
523
524 \begin{lstlisting}
525 template<typename _Tp> _Tp* alignPtr(_Tp* ptr, int n=sizeof(_Tp));
526 \end{lstlisting}
527 \begin{description}
528 \cvarg{ptr}{The aligned pointer}
529 \cvarg{n}{The alignment size; must be a power of two}
530 \end{description}
531
532 The function returns the aligned pointer of the same type as the input pointer:
533 \[\texttt{(\_Tp*)(((size\_t)ptr + n-1) \& -n)}\]
534
535
536 \cvCppFunc{alignSize}
537 Aligns a buffer size to the specified number of bytes
538
539 \begin{lstlisting}
540 size_t alignSize(size_t sz, int n);
541 \end{lstlisting}
542 \begin{description}
543 \cvarg{sz}{The buffer size to align}
544 \cvarg{n}{The alignment size; must be a power of two}
545 \end{description}
546
547 The function returns the minimum number that is greater or equal to \texttt{sz} and is divisble by \texttt{n}:
548 \[\texttt{(sz + n-1) \& -n}\]
549
550
551 \cvCppFunc{allocate}
552 Allocates an array of elements
553
554 \begin{lstlisting}
555 template<typename _Tp> _Tp* allocate(size_t n);
556 \end{lstlisting}
557 \begin{description}
558 \cvarg{n}{The number of elements to allocate}
559 \end{description}
560
561 The generic function \texttt{allocate} allocates buffer for the specified number of elements. For each element the default constructor is called.
562
563
564 \cvCppFunc{deallocate}
565 Allocates an array of elements
566
567 \begin{lstlisting}
568 template<typename _Tp> void deallocate(_Tp* ptr, size_t n);
569 \end{lstlisting}
570 \begin{description}
571 \cvarg{ptr}{Pointer to the deallocated buffer}
572 \cvarg{n}{The number of elements in the buffer}
573 \end{description}
574
575 The generic function \texttt{deallocate} deallocates the buffer allocated with \cvCppCross{allocate}. The number of elements must match the number passed to \cvCppCross{allocate}.
576
577 \cvfunc{CV\_Assert}\label{CV Assert}
578 Checks a condition at runtime.
579
580 \begin{lstlisting}
581 #define CV_Assert( expr ) ...
582 #define CV_DbgAssert(expr) ...
583 \end{lstlisting}
584
585 \begin{description}
586 \cvarg{expr}{The checked expression}
587 \end{description}
588
589 The macros \texttt{CV\_Assert} and \texttt{CV\_DbgAssert} evaluate the specified expression and if it is 0, the macros raise an error (see \cvCppCross{error}). The macro \texttt{CV\_Assert} checks the condition in both Debug and Release configurations, while \texttt{CV\_DbgAssert} is only retained in the Debug configuration.
590
591 \cvCppFunc{error}
592 Signals an error and raises the exception
593
594 \begin{lstlisting}
595 void error( const Exception& exc );
596
597 #define CV_Error( code, msg )
598 #define CV_Error_( code, args )
599 \end{lstlisting}
600 \begin{description}
601 \cvarg{exc}{The exception to throw}
602 \cvarg{code}{The error code, normally, a negative value. The list of pre-defined error codes can be found in \texttt{cxerror.h}}
603 \cvarg{msg}{Text of the error message}
604 \cvarg{args}{printf-like formatted error message in parantheses}
605 \end{description}
606
607 The function and the helper macros \texttt{CV\_Error} and \texttt{CV\_Error\_} call the error handler. Currently, the error handler prints the error code (\texttt{exc.code}), the context (\texttt{exc.file}, \texttt{exc.line} and the error message \texttt{exc.err} to the standard error stream \texttt{stderr}. In Debug configuration it then provokes memory access violation, so that the execution stack and all the parameters can be analyzed in debugger. In Release configuration the exception \texttt{exc} is thrown.
608
609 The macro \texttt{CV\_Error\_} can be used to construct the error message on-fly to include some dynamic information, for example:
610
611 \begin{lstlisting}
612 // note the extra parentheses around the formatted text message
613 CV_Error_(CV_StsOutOfRange,
614     ("the matrix element (%d,%d)=%g is out of range",
615     i, j, mtx.at<float>(i,j)))
616 \end{lstlisting}
617
618
619 \cvCppFunc{Exception}
620 The exception class passed to error
621
622 \begin{lstlisting}
623 class  Exception
624 {
625 public:
626     // various constructors and the copy operation
627     Exception() { code = 0; line = 0; }
628     Exception(int _code, const string& _err,
629               const string& _func, const string& _file, int _line);
630     Exception(const Exception& exc);
631     Exception& operator = (const Exception& exc);
632
633     // the error code
634     int code;
635     // the error text message
636     string err;
637     // function name where the error happened
638     string func;
639     // the source file name where the error happened
640     string file;
641     // the source file line where the error happened
642     int line;
643 };
644 \end{lstlisting}
645
646 The class \texttt{Exception} encapsulates all or almost all the necessary information about the error happened in the program. The exception is usually constructed and thrown implicitly, via \texttt{CV\_Error} and \texttt{CV\_Error\_} macros, see \cvCppCross{error}.
647
648
649 \cvCppFunc{fastMalloc}
650 Allocates aligned memory buffer
651
652 \begin{lstlisting}
653 void* fastMalloc(size_t size);
654 \end{lstlisting}
655 \begin{description}
656 \cvarg{size}{The allocated buffer size}
657 \end{description}
658  
659 The function allocates buffer of the specified size and returns it. When the buffer size is 16 bytes or more, the returned buffer is aligned on 16 bytes.
660
661 \cvCppFunc{fastFree}
662 Deallocates memory buffer
663
664 \begin{lstlisting}
665 void fastFree(void* ptr);
666 \end{lstlisting}
667 \begin{description}
668 \cvarg{ptr}{Pointer to the allocated buffer}
669 \end{description}
670
671 The function deallocates the buffer, allocated with \cvCppCross{fastMalloc}.
672 If NULL pointer is passed, the function does nothing.
673
674 \cvCppFunc{format}
675 Returns a text string formatted using printf-like expression
676
677 \begin{lstlisting}
678 string format( const char* fmt, ... );
679 \end{lstlisting}
680 \begin{description}
681 \cvarg{fmt}{The printf-compatible formatting specifiers}
682 \end{description}
683
684 The function acts like \texttt{sprintf}, but forms and returns STL string. It can be used for form the error message in \cvCppCross{Exception} constructor.
685
686 \cvCppFunc{getNumThreads}
687 Returns the number of threads used by OpenCV
688
689 \begin{lstlisting}
690 int getNumThreads();
691 \end{lstlisting}
692
693 The function returns the number of threads that is used by OpenCV.
694
695 See also: \cvCppCross{setNumThreads}, \cvCppCross{getThreadNum}.
696
697
698 \cvCppFunc{getThreadNum}
699 Returns index of the currently executed thread
700
701 \begin{lstlisting}
702 int getThreadNum();
703 \end{lstlisting}
704
705 The function returns 0-based index of the currently executed thread. The function is only valid inside a parallel OpenMP region. When OpenCV is built without OpenMP support, the function always returns 0.
706
707 See also: \cvCppCross{setNumThreads}, \cvCppCross{getNumThreads}.
708
709 \cvCppFunc{getTickCount}
710 Returns the number of ticks
711
712 \begin{lstlisting}
713 int64 getTickCount();
714 \end{lstlisting}
715
716 The function returns the number of ticks since the certain event (e.g. when the machine was turned on).
717 It can be used to initialize \cvCppCross{RNG} or to measure a function execution time by reading the tick count before and after the function call. See also the tick frequency.
718
719 \cvCppFunc{getTickFrequency}
720 Returns the number of ticks per second
721
722 \begin{lstlisting}
723 double getTickFrequency();
724 \end{lstlisting}
725
726 The function returns the number of ticks per second.
727 That is, the following code computes the executing time in seconds.
728 \begin{lstlisting}
729 double t = (double)getTickCount();
730 // do something ...
731 t = ((double)getTickCount() - t)/getTickFrequency();
732 \end{lstlisting}
733
734 \cvCppFunc{setNumThreads}
735 Sets the number of threads used by OpenCV
736
737 \begin{lstlisting}
738 void setNumThreads(int nthreads);
739 \end{lstlisting}
740 \begin{description}
741 \cvarg{nthreads}{The number of threads used by OpenCV}
742 \end{description}
743
744 The function sets the number of threads used by OpenCV in parallel OpenMP regions. If \texttt{nthreads=0}, the function will use the default number of threads, which is usually equal to the number of the processing cores.
745
746 See also: \cvCppCross{getNumThreads}, \cvCppCross{getThreadNum}
747
748 \fi