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