3 \section{Basic Structures}
5 \subsection{Basic Structures}
7 \cvstruct{CvPoint}\label{CvPoint}
9 2D point with integer coordinates (usually zero-based)
12 typedef struct CvPoint
21 \cvarg{x}{x-coordinate}
22 \cvarg{y}{y-coordinate}
27 inline CvPoint cvPoint( int x, int y );
29 /* Conversion from CvPoint2D32f */
30 inline CvPoint cvPointFrom32f( CvPoint2D32f point );
33 \cvstruct{CvPoint2D32f}\label{CvPoint2D32f}
35 2D point with floating-point coordinates
39 typedef struct CvPoint2D32f
48 \cvarg{x}{x-coordinate}
49 \cvarg{y}{y-coordinate}
54 inline CvPoint2D32f cvPoint2D32f( double x, double y );
56 /* Conversion from CvPoint */
57 inline CvPoint2D32f cvPointTo32f( CvPoint point );
62 \cvstruct{CvPoint3D32f}\label{CvPoint3D32f}
64 3D point with floating-point coordinates
68 typedef struct CvPoint3D32f
78 \cvarg{x}{x-coordinate}
79 \cvarg{y}{y-coordinate}
80 \cvarg{z}{z-coordinate}
85 inline CvPoint3D32f cvPoint3D32f( double x, double y, double z );
89 \cvstruct{CvPoint2D64f}\label{CvPoint2D64f}
91 2D point with double precision floating-point coordinates
95 typedef struct CvPoint2D64f
104 \cvarg{x}{x-coordinate}
105 \cvarg{y}{y-coordinate}
110 inline CvPoint2D64f cvPoint2D64f( double x, double y );
112 /* Conversion from CvPoint */
113 inline CvPoint2D64f cvPointTo64f( CvPoint point );
117 \cvstruct{CvPoint3D64f}\label{CvPoint3D64f}
119 3D point with double precision floating-point coordinates
123 typedef struct CvPoint3D64f
133 \cvarg{x}{x-coordinate}
134 \cvarg{y}{y-coordinate}
135 \cvarg{z}{z-coordinate}
140 inline CvPoint3D64f cvPoint3D64f( double x, double y, double z );
144 \cvstruct{CvSize}\label{CvSize}
146 Pixel-accurate size of a rectangle.
150 typedef struct CvSize
159 \cvarg{width}{Width of the rectangle}
160 \cvarg{height}{Height of the rectangle}
165 inline CvSize cvSize( int width, int height );
169 \cvstruct{CvSize2D32f}\label{CvSize2D32f}
171 Sub-pixel accurate size of a rectangle.
175 typedef struct CvSize2D32f
184 \cvarg{width}{Width of the rectangle}
185 \cvarg{height}{Height of the rectangle}
190 inline CvSize2D32f cvSize2D32f( double width, double height );
194 \cvstruct{CvRect}\label{CvRect}
196 Offset (usually the top-left corner) and size of a rectangle.
200 typedef struct CvRect
211 \cvarg{x}{x-coordinate of the top-left corner}
212 \cvarg{y}{y-coordinate of the top-left corner (bottom-left for Windows bitmaps)}
213 \cvarg{width}{Width of the rectangle}
214 \cvarg{height}{Height of the rectangle}
219 inline CvRect cvRect( int x, int y, int width, int height );
223 \cvstruct{CvScalar}\label{CvScalar}
225 A container for 1-,2-,3- or 4-tuples of doubles.
229 typedef struct CvScalar
239 initializes val[0] with val0, val[1] with val1, etc.
241 inline CvScalar cvScalar( double val0, double val1=0,
242 double val2=0, double val3=0 );
244 initializes all of val[0]...val[3] with val0123
246 inline CvScalar cvScalarAll( double val0123 );
249 initializes val[0] with val0, and all of val[1]...val[3] with zeros
251 inline CvScalar cvRealScalar( double val0 );
255 \cvstruct{CvTermCriteria}\label{CvTermCriteria}
257 Termination criteria for iterative algorithms.
261 #define CV_TERMCRIT_ITER 1
262 #define CV_TERMCRIT_NUMBER CV_TERMCRIT_ITER
263 #define CV_TERMCRIT_EPS 2
265 typedef struct CvTermCriteria
275 \cvarg{type}{A combination of CV\_TERMCRIT\_ITER and CV\_TERMCRIT\_EPS}
276 \cvarg{max\_iter}{Maximum number of iterations}
277 \cvarg{epsilon}{Required accuracy}
282 inline CvTermCriteria cvTermCriteria( int type, int max_iter, double epsilon );
284 /* Check and transform a CvTermCriteria so that
285 type=CV_TERMCRIT_ITER+CV_TERMCRIT_EPS
286 and both max_iter and epsilon are valid */
287 CvTermCriteria cvCheckTermCriteria( CvTermCriteria criteria,
289 int default_max_iters );
293 \cvstruct{CvMat}\label{CvMat}
295 A multi-channel matrix.
337 \cvarg{type}{A CvMat signature (CV\_MAT\_MAGIC\_VAL) containing the type of elements and flags}
338 \cvarg{step}{Full row length in bytes}
339 \cvarg{refcount}{Underlying data reference counter}
340 \cvarg{data}{Pointers to the actual matrix data}
341 \cvarg{rows}{Number of rows}
342 \cvarg{cols}{Number of columns}
346 Matrices are stored row by row. All of the rows are aligned by 4 bytes.
349 \cvstruct{CvMatND}\label{CvMatND}
351 Multi-dimensional dense multi-channel array.
355 typedef struct CvMatND
383 \cvarg{type}{A CvMatND signature (CV\_MATND\_MAGIC\_VAL), combining the type of elements and flags}
384 \cvarg{dims}{The number of array dimensions}
385 \cvarg{refcount}{Underlying data reference counter}
386 \cvarg{data}{Pointers to the actual matrix data}
387 \cvarg{dim}{For each dimension, the pair (number of elements, distance between elements in bytes)}
390 \cvstruct{CvSparseMat}\label{CvSparseMat}
392 Multi-dimensional sparse multi-channel array.
396 typedef struct CvSparseMat
407 int size[CV_MAX_DIM];
414 \cvarg{type}{A CvSparseMat signature (CV\_SPARSE\_MAT\_MAGIC\_VAL), combining the type of elements and flags.}
415 \cvarg{dims}{Number of dimensions}
416 \cvarg{refcount}{Underlying reference counter. Not used.}
417 \cvarg{heap}{A pool of hash table nodes}
418 \cvarg{hashtable}{The hash table. Each entry is a list of nodes.}
419 \cvarg{hashsize}{Size of the hash table}
420 \cvarg{total}{Total number of sparse array nodes}
421 \cvarg{valoffset}{The value offset of the array nodes, in bytes}
422 \cvarg{idxoffset}{The index offset of the array nodes, in bytes}
423 \cvarg{size}{Array of dimension sizes}
426 \cvstruct{IplImage}\label{IplImage}
432 typedef struct _IplImage
447 struct _IplImage *maskROI;
449 struct _IplTileInfo *tileInfo;
455 char *imageDataOrigin;
462 \cvarg{nSize}{\texttt{sizeof(IplImage)}}
463 \cvarg{ID}{Version, always equals 0}
464 \cvarg{nChannels}{Number of channels. Most OpenCV functions support 1-4 channels.}
465 \cvarg{alphaChannel}{Ignored by OpenCV}
466 \cvarg{depth}{Pixel depth in bits. The supported depths are:
468 \cvarg{IPL\_DEPTH\_8U}{Unsigned 8-bit integer}
469 \cvarg{IPL\_DEPTH\_8S}{Signed 8-bit integer}
470 \cvarg{IPL\_DEPTH\_16U}{Unsigned 16-bit integer}
471 \cvarg{IPL\_DEPTH\_16S}{Signed 16-bit integer}
472 \cvarg{IPL\_DEPTH\_32S}{Signed 32-bit integer}
473 \cvarg{IPL\_DEPTH\_32F}{Single-precision floating point}
474 \cvarg{IPL\_DEPTH\_64F}{Double-precision floating point}
476 \cvarg{colorModel}{Ignored by OpenCV. The OpenCV function \cross{CvtColor} requires the source and destination color spaces as parameters.}
477 \cvarg{channelSeq}{Ignored by OpenCV}
478 \cvarg{dataOrder}{0 = \texttt{IPL\_DATA\_ORDER\_PIXEL} - interleaved color channels, 1 - separate color channels. \cross{CreateImage} only creates images with interleaved channels. For example, the usual layout of a color image is: $ b_{00} g_{00} r_{00} b_{10} g_{10} r_{10} ...$}
479 \cvarg{origin}{0 - top-left origin, 1 - bottom-left origin (Windows bitmap style)}
480 \cvarg{align}{Alignment of image rows (4 or 8). OpenCV ignores this and uses widthStep instead.}
481 \cvarg{width}{Image width in pixels}
482 \cvarg{height}{Image height in pixels}
483 \cvarg{roi}{Region Of Interest (ROI). If not NULL, only this image region will be processed.}
484 \cvarg{maskROI}{Must be NULL in OpenCV}
485 \cvarg{imageId}{Must be NULL in OpenCV}
486 \cvarg{tileInfo}{Must be NULL in OpenCV}
487 \cvarg{imageSize}{Image data size in bytes. For interleaved data, this equals $\texttt{image->height} \cdot \texttt{image->widthStep}$ }
488 \cvarg{imageData}{A pointer to the aligned image data}
489 \cvarg{widthStep}{The size of an aligned image row, in bytes}
490 \cvarg{BorderMode}{Border completion mode, ignored by OpenCV}
491 \cvarg{BorderConst}{Border completion mode, ignored by OpenCV}
492 \cvarg{imageDataOrigin}{A pointer to the origin of the image data (not necessarily aligned). This is used for image deallocation.}
495 The \cross{IplImage} structure was inherited from the Intel Image Processing Library, in which the format is native. OpenCV only supports a subset of possible \cross{IplImage} formats, as outlined in the parameter list above.
497 In addition to the above restrictions, OpenCV handles ROIs differently. OpenCV functions require that the image size or ROI size of all source and destination images match exactly. On the other hand, the Intel Image Processing Library processes the area of intersection between the source and destination images (or ROIs), allowing them to vary independently.
499 \cvstruct{CvArr}\label{CvArr}
509 The metatype \texttt{CvArr} is used \textit{only} as a function parameter to specify that the function accepts arrays of multiple types, such as IplImage*, CvMat* or even CvSeq*. The particular array type is determined at runtime by analyzing the first 4 bytes of the header.
512 \section{Operations on Arrays}
514 \subsection{Initialization}
516 \cvfunc{CreateImage}\label{CreateImage}
518 Creates an image header and allocates the image data.
521 IplImage* cvCreateImage(
531 \cvarg{size}{Image width and height}
532 \cvarg{depth}{Bit depth of image elements. See \cross{IplImage} for valid depths.}
533 \cvarg{channels}{Number of channels per pixel. See \cross{IplImage} for details. This function only creates images with interleaved channels.}
536 This call is a shortened form of
539 header = cvCreateImageHeader( size, depth, channels );
540 cvCreateData( header );
544 \cvfunc{CreateImageHeader}\label{CreateImageHeader}
546 Creates an image header but does not allocate the image data.
549 IplImage* cvCreateImageHeader(
559 \cvarg{size}{Image width and height}
560 \cvarg{depth}{Image depth (see \cross{CreateImage})}
561 \cvarg{channels}{Number of channels (see \cross{CreateImage})}
564 This call is an analogue of
567 iplCreateImageHeader( channels, 0, depth,
568 channels == 1 ? "GRAY" : "RGB",
569 channels == 1 ? "GRAY" : channels == 3 ? "BGR" :
570 channels == 4 ? "BGRA" : "",
571 IPL_DATA_ORDER_PIXEL, IPL_ORIGIN_TL, 4,
572 size.width, size.height,
576 but it does not use IPL functions by default (see the \texttt{CV\_TURN\_ON\_IPL\_COMPATIBILITY} macro).
578 \cvfunc{ReleaseImageHeader}\label{ReleaseImageHeader}
580 Deallocates an image header.
583 void cvReleaseImageHeader( IplImage** image );
587 \cvarg{image}{Double pointer to the image header}
590 This call is an analogue of
595 iplDeallocate( *image, IPL_IMAGE_HEADER | IPL_IMAGE_ROI );
600 but it does not use IPL functions by default (see the \texttt{CV\_TURN\_ON\_IPL\_COMPATIBILITY} macro).
603 \cvfunc{ReleaseImage}\label{ReleaseImage}
605 Deallocates the image header and the image data.
609 void cvReleaseImage( IplImage** image );
614 \cvarg{image}{Double pointer to the image header}
617 This call is a shortened form of
623 cvReleaseData( *image );
624 cvReleaseImageHeader( image );
630 \cvfunc{InitImageHeader}\label{InitImageHeader}
632 Initializes an image header that was previously allocated
636 IplImage* cvInitImageHeader( \par IplImage* image,\par CvSize size,\par int depth,\par int channels,\par int origin=0,\par int align=4 );
641 \cvarg{image}{Image header to initialize}
642 \cvarg{size}{Image width and height}
643 \cvarg{depth}{Image depth (see \cross{CreateImage})}
644 \cvarg{channels}{Number of channels (see \cross{CreateImage})}
645 \cvarg{origin}{Top-left \texttt{IPL\_ORIGIN\_TL} or bottom-left \texttt{IPL\_ORIGIN\_BL}}
646 \cvarg{align}{Alignment for image rows, typically 4 or 8 bytes}
649 The returned \texttt{IplImage*} points to the initialized header.
651 \cvfunc{CloneImage}\label{CloneImage}
653 Makes a full copy of an image, including the header, data, and ROI.
657 IplImage* cvCloneImage( const IplImage* image );
662 \cvarg{image}{The original image}
665 The returned \texttt{IplImage*} points to the image copy.
667 \cvfunc{SetImageCOI}\label{SetImageCOI}
669 Sets the channel of interest in an IplImage
673 void cvSetImageCOI( \par IplImage* image,\par int coi );
678 \cvarg{image}{A pointer to the image header}
679 \cvarg{coi}{The channel of interest. 0 - all channels are selected, 1 - first channel is selected, etc. Note that the channel indices become 1-based.}
682 If the ROI is set to \texttt{NULL} and the coi is \textit{not} 0,
683 the ROI is allocated. Most OpenCV functions do \textit{not} support
684 the COI setting, so to process an individual image/matrix channel one
685 may copy (via \cross{Copy} or \cross{Split}) the channel to a separate
686 image/matrix, process it and then copy the result back (via \cross{Copy}
687 or \cross{Merge}) if needed.
689 \cvfunc{GetImageCOI}\label{GetImageCOI}
691 Returns the index of the channel of interest.
695 int cvGetImageCOI( const IplImage* image );
700 \cvarg{image}{A pointer to the image header}
703 Returns the channel of interest of in an IplImage. Returned values correspond to the \texttt{coi} in \cross{SetImageCOI}.
705 \cvfunc{SetImageROI}\label{SetImageROI}
707 Sets an image Region Of Interest (ROI) to a given rectangle
711 void cvSetImageROI( \par IplImage* image,\par CvRect rect );
716 \cvarg{image}{A pointer to the image header}
717 \cvarg{rect}{The ROI rectangle}
720 If the original image ROI was \texttt{NULL} and the \texttt{rect} is not the whole image, the ROI structure is allocated.
722 Most OpenCV functions support the use of ROI and treat the image rectangle as a separate image. For example, all of the pixel coordinates are counted from the top-left (or bottom-left) corner of the ROI, not the original image.
724 \cvfunc{ResetImageROI}\label{ResetImageROI}
726 Resets the image ROI to include the entire image and releases the ROI structure.
730 void cvResetImageROI( IplImage* image );
735 \cvarg{image}{A pointer to the image header}
738 This produces a similar result to the following, but in addition it releases the ROI structure.
742 cvSetImageROI( image, cvRect( 0, 0, image->width, image->height ));
743 cvSetImageCOI( image, 0 );
748 \cvfunc{GetImageROI}\label{GetImageROI}
750 Returns the image ROI
754 CvRect cvGetImageROI( const IplImage* image );
759 \cvarg{image}{A pointer to the image header}
763 If there is no ROI set, \texttt{cvRect(0,0,image->width,image->height)} is returned.
766 \cvfunc{CreateMat}\label{CreateMat}
768 Creates a matrix header and allocates the matrix data.
772 CvMat* cvCreateMat( \par int rows,\par int cols,\par int type );
777 \cvarg{rows}{Number of rows in the matrix}
778 \cvarg{cols}{Number of columns in the matrix}
779 \cvarg{type}{The type of the matrix elements in the form \texttt{CV\_<bit depth><S|U|F>C<number of channels>}, where S=signed, U=unsigned, F=float. For example, CV\_8UC1 means the elements are 8-bit unsigned and the there is 1 channel, and CV\_32SC2 means the elements are 32-bit signed and there are 2 channels.}
782 This is the concise form for:
786 CvMat* mat = cvCreateMatHeader( rows, cols, type );
791 \cvfunc{CreateMatHeader}\label{CreateMatHeader}
793 Creates a matrix header but does not allocate the matrix data.
797 CvMat* cvCreateMatHeader( \par int rows,\par int cols,\par int type );
802 \cvarg{rows}{Number of rows in the matrix}
803 \cvarg{cols}{Number of columns in the matrix}
804 \cvarg{type}{Type of the matrix elements, see \cross{CreateMat}}
807 The function \texttt{cvCreateMatHeader} allocates new matrix header and returns pointer to it. The matrix data can then be allocated using \cross{CreateData} or set explicitly to user-allocated data via \cross{SetData}.
810 \cvfunc{ReleaseMat}\label{ReleaseMat}
816 void cvReleaseMat( CvMat** mat );
821 \cvarg{mat}{Double pointer to the matrix}
825 The function \texttt{cvReleaseMat} decrements the matrix data reference counter and deallocates matrix header. If the data reference counter is 0, it also deallocates the data.
830 cvDecRefData( *mat );
831 cvFree( (void**)mat );
836 \cvfunc{InitMatHeader}\label{InitMatHeader}
838 Initializes a pre-allocated matrix header
842 CvMat* cvInitMatHeader(\par CvMat* mat,\par int rows,\par int cols,\par int type, \par void* data=NULL,\par int step=CV\_AUTOSTEP );
847 \cvarg{mat}{A pointer to the matrix header to be initialized}
848 \cvarg{rows}{Number of rows in the matrix}
849 \cvarg{cols}{Number of columns in the matrix}
850 \cvarg{type}{Type of the matrix elements, see \cross{CreateMat}.}
851 \cvarg{data}{Optional: data pointer assigned to the matrix header}
852 \cvarg{step}{Optional: full row width in bytes of the assigned data. By default, the minimal possible step is used which assumes there are no gaps between subsequent rows of the matrix.}
855 This function is often used to process raw data with OpenCV matrix functions. For example, the following code computes the matrix product of two matrices, stored as ordinary arrays:
859 double a[] = { 1, 2, 3, 4
863 double b[] = { 1, 5, 9,
871 cvInitMatHeader( &Ma, 3, 4, CV_64FC1, a );
872 cvInitMatHeader( &Mb, 4, 3, CV_64FC1, b );
873 cvInitMatHeader( &Mc, 3, 3, CV_64FC1, c );
875 cvMatMulAdd( &Ma, &Mb, 0, &Mc );
876 // the c array now contains the product of a (3x4) and b (4x3)
880 \cvfunc{Mat}\label{Mat}
882 Initializes matrix header (light-weight variant)
886 CvMat cvMat(\par int rows,\par int cols,\par int type,\par void* data=NULL );
891 \cvarg{rows}{Number of rows in the matrix}
892 \cvarg{cols}{Number of columns in the matrix}
893 \cvarg{type}{Type of the matrix elements - see \cross{CreateMat}}
894 \cvarg{data}{Optional data pointer assigned to the matrix header}
897 Initializes a matrix header and assigns data to it. The matrix is filled \textit{row}-wise (the first \texttt{cols} elements of data form the first row of the matrix, etc.)
899 This function is a fast inline substitution for \cross{InitMatHeader}. Namely, it is equivalent to:
904 cvInitMatHeader( &mat, rows, cols, type, data, CV\_AUTOSTEP );
909 \cvfunc{CloneMat}\label{CloneMat}
911 Creates a full matrix copy
915 CvMat* cvCloneMat( const CvMat* mat );
920 \cvarg{mat}{Matrix to be copied}
923 Creates a full copy of a matrix and returns a pointer to the copy.
925 \cvfunc{CreateMatND}\label{CreateMatND}
927 Creates the header and allocates the data for a multi-dimensional dense array.
931 CvMatND* cvCreateMatND(\par int dims,\par const int* sizes,\par int type );
936 \cvarg{dims}{Number of array dimensions. this must not exceed CV\_MAX\_DIM (32 by default, but can be changed at build time.)}
937 \cvarg{sizes}{Array of dimension sizes}
938 \cvarg{type}{Type of array elements, see \cross{CreateMat}. }
941 This is a short form for:
945 CvMatND* mat = cvCreateMatNDHeader( dims, sizes, type );
950 \cvfunc{CreateMatNDHeader}\label{CreateMatNDHeader}
952 Creates a new matrix header but does not allocate the matrix data.
956 CvMatND* cvCreateMatNDHeader(\par int dims,\par const int* sizes,\par int type );
961 \cvarg{dims}{Number of array dimensions}
962 \cvarg{sizes}{Array of dimension sizes}
963 \cvarg{type}{Type of array elements, see \cross{CreateMat}}
966 The function \texttt{cvCreateMatND} allocates header for multi-dimensional dense array. The array data can further be allocated using \cross{CreateData} or set explicitly to user-allocated data via \cross{SetData}.
968 \cvfunc{ReleaseMatND}\label{ReleaseMatND}
970 Deallocates a multi-dimensional array
974 void cvReleaseMatND( CvMatND** mat );
979 \cvarg{mat}{Double pointer to the array}
982 The function \texttt{cvReleaseMatND} decrements the array data reference counter and releases the array header. If the reference counter reaches 0, it also deallocates the data.
987 cvDecRefData( *mat );
988 cvFree( (void**)mat );
992 \cvfunc{InitMatNDHeader}\label{InitMatNDHeader}
994 Initializes a pre-allocated multi-dimensional array header.
998 CvMatND* cvInitMatNDHeader( \par CvMatND* mat,\par int dims,\par const int* sizes,\par int type,\par void* data=NULL );
1003 \cvarg{mat}{A pointer to the array header to be initialized}
1004 \cvarg{dims}{The number of array dimensions}
1005 \cvarg{sizes}{An array of dimension sizes}
1006 \cvarg{type}{Type of array elements, see \cross{CreateMat}}
1007 \cvarg{data}{Optional data pointer assigned to the matrix header}
1010 \cvfunc{CloneMatND}\label{CloneMatND}
1012 Creates full copy of a multi-dimensional array and returns a pointer to the copy.
1016 CvMatND* cvCloneMatND( const CvMatND* mat );
1021 \cvarg{mat}{Input array}
1025 \cvfunc{DecRefData}\label{DecRefData}
1027 Decrements an array data reference counter
1031 void cvDecRefData( CvArr* arr );
1036 \cvarg{arr}{Pointer to an array header}
1039 The function \texttt{cvDecRefData} decrements the data reference counter in a \cross{CvMat} or
1040 \cross{CvMatND} if the reference counter pointer
1041 is not NULL. If the counter reaches zero, the data is deallocated. In the
1042 current implementation the reference counter is not NULL only if the data
1043 was allocated using the \cross{CreateData} function. The counter will be NULL in other cases such as:
1044 external data was assigned to the header using \cross{SetData}, the matrix
1045 header is part of a larger matrix or image, or the header was converted from an image or n-dimensional matrix header.
1048 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1050 \cvfunc{IncRefData}\label{IncRefData}
1052 Increments array data reference counter
1056 int cvIncRefData( CvArr* arr );
1061 \cvarg{arr}{array header}
1065 The function \texttt{cvIncRefData} increments \cross{CvMat} or
1066 \cross{CvMatND} data reference counter and returns the new counter value
1067 if the reference counter pointer is not NULL, otherwise it returns zero.
1069 \cvfunc{CreateData}\label{CreateData}
1071 Allocates array data
1075 void cvCreateData( CvArr* arr );
1080 \cvarg{arr}{Array header}
1084 The function \texttt{cvCreateData} allocates image, matrix or
1085 multi-dimensional array data. Note that in case of matrix types OpenCV
1086 allocation functions are used and in case of IplImage they are used
1087 too unless \texttt{CV\_TURN\_ON\_IPL\_COMPATIBILITY} was called. In the
1088 latter case IPL functions are used to allocate the data
1090 \cvfunc{ReleaseData}\label{ReleaseData}
1096 void cvReleaseData( CvArr* arr );
1101 \cvarg{arr}{Array header}
1105 The function \texttt{cvReleaseData} releases the array data. In case of \cross{CvMat} or \cross{CvMatND} it simply calls cvDecRefData(), that is the function can not deallocate external data. See also the note to \cross{CreateData}.
1107 \cvfunc{SetData}\label{SetData}
1109 Assigns user data to the array header
1113 void cvSetData( CvArr* arr, void* data, int step );
1118 \cvarg{arr}{Array header}
1119 \cvarg{data}{User data}
1120 \cvarg{step}{Full row length in bytes}
1124 The function \texttt{cvSetData} assigns user data to the array header. Header should be initialized before using cvCreate*Header, cvInit*Header or \cross{Mat} (in case of matrix) function.
1126 \cvfunc{GetRawData}\label{GetRawData}
1128 Retrieves low-level information about the array
1132 void cvGetRawData( const CvArr* arr, uchar** data,
1133 int* step=NULL, CvSize* roi\_size=NULL );
1138 \cvarg{arr}{Array header}
1139 \cvarg{data}{Output pointer to the whole image origin or ROI origin if ROI is set}
1140 \cvarg{step}{Output full row length in bytes}
1141 \cvarg{roi\_size}{Output ROI size}
1144 The function \texttt{cvGetRawData} fills output variables with low-level information about the array data. All output parameters are optional, so some of the pointers may be set to \texttt{NULL}. If the array is \texttt{IplImage} with ROI set, parameters of ROI are returned.
1146 The following example shows how to get access to array elements using this function.
1148 Using GetRawData to calculate absolute value of elements of a single-channel floating-point array.
1158 cvGetRawData( array, (uchar**)&data, &step, &size );
1159 step /= sizeof(data[0]);
1161 for( y = 0; y < size.height; y++, data += step )
1162 for( x = 0; x < size.width; x++ )
1163 data[x] = (float)fabs(data[x]);
1168 \cvfunc{GetMat}\label{GetMat}
1170 Returns matrix header for arbitrary array
1174 CvMat* cvGetMat( const CvArr* arr, CvMat* header, int* coi=NULL, int allowND=0 );
1179 \cvarg{arr}{Input array}
1180 \cvarg{header}{Pointer to \cross{CvMat} structure used as a temporary buffer}
1181 \cvarg{coi}{Optional output parameter for storing COI}
1182 \cvarg{allowND}{If non-zero, the function accepts multi-dimensional dense arrays (CvMatND*) and returns 2D (if CvMatND has two dimensions) or 1D matrix (when CvMatND has 1 dimension or more than 2 dimensions). The array must be continuous.}
1185 The function \texttt{cvGetMat} returns matrix header for the input array that can be matrix - \cross{CvMat}, image - \texttt{IplImage} or multi-dimensional dense array - \cross{CvMatND} (latter case is allowed only if \texttt{allowND != 0}) . In the case of matrix the function simply returns the input pointer. In the case of \texttt{IplImage*} or \cross{CvMatND} it initializes \texttt{header} structure with parameters of the current image ROI and returns pointer to this temporary structure. Because COI is not supported by \cross{CvMat}, it is returned separately.
1187 The function provides an easy way to handle both types of array - \texttt{IplImage} and \cross{CvMat} -, using the same code. Reverse transform from \cross{CvMat} to \texttt{IplImage} can be done using \cross{GetImage} function.
1189 Input array must have underlying data allocated or attached, otherwise the function fails.
1191 If the input array is \texttt{IplImage} with planar data layout and COI set, the function returns pointer to the selected plane and COI = 0. It enables per-plane processing of multi-channel images with planar data layout using OpenCV functions.
1193 \cvfunc{GetImage}\label{GetImage}
1195 Returns image header for arbitrary array
1199 IplImage* cvGetImage( const CvArr* arr, IplImage* image\_header );
1204 \cvarg{arr}{Input array}
1205 \cvarg{image\_header}{Pointer to \texttt{IplImage} structure used as a temporary buffer}
1208 The function \texttt{cvGetImage} returns image header for the input array
1209 that can be matrix - \cross{CvMat}, or image - \texttt{IplImage*}. In
1210 the case of image the function simply returns the input pointer. In the
1211 case of \cross{CvMat} it initializes \texttt{image\_header} structure
1212 with parameters of the input matrix. Note that if we transform
1213 \texttt{IplImage} to \cross{CvMat} and then transform CvMat back to
1214 IplImage, we can get different headers if the ROI is set, and thus some
1215 IPL functions that calculate image stride from its width and align may
1216 fail on the resultant image.
1218 \cvfunc{CreateSparseMat}\label{CreateSparseMat}
1220 Creates sparse array
1224 CvSparseMat* cvCreateSparseMat( int dims, const int* sizes, int type );
1229 \cvarg{dims}{Number of array dimensions. As opposite to the dense matrix, the number of dimensions is practically unlimited (up to $2^16$).}
1230 \cvarg{sizes}{Array of dimension sizes}
1231 \cvarg{type}{Type of array elements. The same as for CvMat}
1234 The function \texttt{cvCreateSparseMat} allocates multi-dimensional sparse array. Initially the array contain no elements, that is \cross{Get} or \cross{GetReadl} return zero for every index
1236 \cvfunc{ReleaseSparseMat}\label{ReleaseSparseMat}
1238 Deallocates sparse array
1242 void cvReleaseSparseMat( CvSparseMat** mat );
1247 \cvarg{mat}{Double pointer to the array}
1251 The function \texttt{cvReleaseSparseMat} releases the sparse array and clears the array pointer upon exit
1254 \cvfunc{CloneSparseMat}\label{CloneSparseMat}
1256 Creates full copy of sparse array
1260 CvSparseMat* cvCloneSparseMat( const CvSparseMat* mat );
1265 \cvarg{mat}{Input array}
1268 The function \texttt{cvCloneSparseMat} creates a copy of the input array and returns pointer to the copy.
1270 \subsection{Accessing Elements and sub-Arrays}
1272 \cvfunc{GetSubRect}\label{GetSubRect}
1274 Returns matrix header corresponding to the rectangular sub-array of input image or matrix
1278 CvMat* cvGetSubRect( const CvArr* arr, CvMat* submat, CvRect rect );
1283 \cvarg{arr}{Input array}
1284 \cvarg{submat}{Pointer to the resultant sub-array header}
1285 \cvarg{rect}{Zero-based coordinates of the rectangle of interest}
1288 The function \texttt{cvGetSubRect} returns header, corresponding to
1289 a specified rectangle of the input array. In other words, it allows
1290 the user to treat a rectangular part of input array as a stand-alone
1291 array. ROI is taken into account by the function so the sub-array of
1292 ROI is actually extracted.
1294 \cvfunc{GetRow, GetRows}\label{GetRow, GetRows}
1296 Returns array row or row span
1299 CvMat* cvGetRow( const CvArr* arr, CvMat* submat, int row );
1302 CvMat* cvGetRows( const CvArr* arr, CvMat* submat, int start\_row, int end\_row, int delta\_row=1 );
1306 \cvarg{arr}{Input array}
1307 \cvarg{submat}{Pointer to the resulting sub-array header}
1308 \cvarg{row}{Zero-based index of the selected row}
1309 \cvarg{start\_row}{Zero-based index of the starting row (inclusive) of the span}
1310 \cvarg{end\_row}{Zero-based index of the ending row (exclusive) of the span}
1311 \cvarg{delta\_row}{Index step in the row span. That is, the function extracts every \texttt{delta\_row}-th row from \texttt{start\_row} and up to (but not including) \texttt{end\_row}.}
1315 The functions \texttt{GetRow} and \texttt{GetRows} return the header, corresponding to a specified row/row span of the input array. Note that \texttt{GetRow} is a shortcut for \cross{GetRows}:
1319 cvGetRow( arr, submat, row ) ~ cvGetRows( arr, submat, row, row + 1, 1 );
1324 \cvfunc{GetCol, GetCols}\label{GetCol, GetCols}
1326 Returns array column or column span
1329 CvMat* cvGetCol( const CvArr* arr, CvMat* submat, int col );
1332 CvMat* cvGetCols( const CvArr* arr, CvMat* submat, int start\_col, int end\_col );
1336 \cvarg{arr}{Input array}
1337 \cvarg{submat}{Pointer to the resulting sub-array header}
1338 \cvarg{col}{Zero-based index of the selected column}
1339 \cvarg{start\_col}{Zero-based index of the starting column (inclusive) of the span}
1340 \cvarg{end\_col}{Zero-based index of the ending column (exclusive) of the span}
1343 The functions \texttt{GetCol} and \texttt{GetCols} return the header, corresponding to a specified column/column span of the input array. Note that \texttt{GetCol} is a shortcut for \cross{GetCols}:
1347 cvGetCol( arr, submat, col ); // ~ cvGetCols( arr, submat, col, col + 1 );
1351 \cvfunc{GetDiag}\label{GetDiag}
1353 Returns one of array diagonals
1357 CvMat* cvGetDiag( const CvArr* arr, CvMat* submat, int diag=0 );
1362 \cvarg{arr}{Input array}
1363 \cvarg{submat}{Pointer to the resulting sub-array header}
1364 \cvarg{diag}{Array diagonal. Zero corresponds to the main diagonal, -1 corresponds to the diagonal above the main etc., 1 corresponds to the diagonal below the main etc.}
1367 The function \texttt{cvGetDiag} returns the header, corresponding to a specified diagonal of the input array.
1369 \cvfunc{GetSize}\label{GetSize}
1371 Returns size of matrix or image ROI
1375 CvSize cvGetSize( const CvArr* arr );
1380 \cvarg{arr}{array header}
1383 The function \texttt{cvGetSize} returns number of rows (CvSize::height) and number of columns (CvSize::width) of the input matrix or image. In case of image the size of ROI is returned.
1386 \cvfunc{InitSparseMatIterator}\label{InitSparseMatIterator}
1388 Initializes sparse array elements iterator
1392 CvSparseNode* cvInitSparseMatIterator( const CvSparseMat* mat,
1393 CvSparseMatIterator* mat\_iterator );
1398 \cvarg{mat}{Input array}
1399 \cvarg{mat\_iterator}{Initialized iterator}
1402 The function \texttt{cvInitSparseMatIterator} initializes iterator of
1403 sparse array elements and returns pointer to the first element, or NULL
1404 if the array is empty.
1406 \cvfunc{GetNextSparseNode}\label{GetNextSparseNode}
1408 Initializes sparse array elements iterator
1412 CvSparseNode* cvGetNextSparseNode( CvSparseMatIterator* mat\_iterator );
1417 \cvarg{mat\_iterator}{Sparse array iterator}
1421 The function \texttt{cvGetNextSparseNode} moves iterator to the next sparse matrix element and returns pointer to it. In the current version there is no any particular order of the elements, because they are stored in hash table. The sample below demonstrates how to iterate through the sparse matrix:
1423 Using \cross{InitSparseMatIterator} and \cross{GetNextSparseNode} to calculate sum of floating-point sparse array.
1428 int i, dims = cvGetDims( array );
1429 CvSparseMatIterator mat_iterator;
1430 CvSparseNode* node = cvInitSparseMatIterator( array, &mat_iterator );
1432 for( ; node != 0; node = cvGetNextSparseNode( &mat_iterator ))
1434 /* get pointer to the element indices */
1435 int* idx = CV_NODE_IDX( array, node );
1436 /* get value of the element (assume that the type is CV_32FC1) */
1437 float val = *(float*)CV_NODE_VAL( array, node );
1439 for( i = 0; i < dims; i++ )
1440 printf( "%4d%s", idx[i], i < dims - 1 "," : "): " );
1441 printf( "%g\n", val );
1446 printf( "\nTotal sum = %g\n", sum );
1451 \cvfunc{GetElemType}\label{GetElemType}
1453 Returns type of array elements
1457 int cvGetElemType( const CvArr* arr );
1462 \cvarg{arr}{Input array}
1466 The functions \texttt{GetElemType} returns type of the array elements
1467 as it is described in \cross{CreateMat} discussion: \texttt{CV\_8UC1}
1468 ... \texttt{CV\_64FC4}.
1471 \cvfunc{GetDims, GetDimSize}\label{GetDims, GetDimSize}
1473 Return number of array dimensions and their sizes or the size of particular dimension
1476 int cvGetDims( const CvArr* arr, int* sizes=NULL );
1479 int cvGetDimSize( const CvArr* arr, int index );
1483 \cvarg{arr}{Input array}
1484 \cvarg{sizes}{Optional output vector of the array dimension sizes. For
1485 2d arrays the number of rows (height) goes first, number of columns
1487 \cvarg{index}{Zero-based dimension index (for matrices 0 means number
1488 of rows, 1 means number of columns; for images 0 means height, 1 means
1493 The function \texttt{cvGetDims} returns number of array dimensions and
1494 their sizes. In case of \texttt{IplImage} or \cross{CvMat} it always
1495 returns 2 regardless of number of image/matrix rows. The function
1496 \texttt{cvGetDimSize} returns the particular dimension size (number of
1497 elements per that dimension). For example, the following code calculates
1498 total number of array elements in two ways:
1503 int sizes[CV_MAX_DIM];
1505 int dims = cvGetDims( arr, size );
1506 for( i = 0; i < dims; i++ )
1509 // via cvGetDims() and cvGetDimSize()
1511 int dims = cvGetDims( arr );
1512 for( i = 0; i < dims; i++ )
1513 total *= cvGetDimsSize( arr, i );
1518 \cvfunc{PtrnD}\label{PtrnD}
1520 Return pointer to the particular array element
1524 uchar* cvPtr1D( const CvArr* arr, int idx0, int* type=NULL );
1525 uchar* cvPtr2D( const CvArr* arr, int idx0, int idx1, int* type=NULL );
1526 uchar* cvPtr3D( const CvArr* arr, int idx0, int idx1, int idx2, int* type=NULL );
1527 uchar* cvPtrND( const CvArr* arr, int* idx, int* type=NULL, int create\_node=1, unsigned* precalc\_hashval=NULL );
1532 \cvarg{arr}{Input array}
1533 \cvarg{idx0}{The first zero-based component of the element index}
1534 \cvarg{idx1}{The second zero-based component of the element index}
1535 \cvarg{idx2}{The third zero-based component of the element index}
1536 \cvarg{idx}{Array of the element indices}
1537 \cvarg{type}{Optional output parameter: type of matrix elements}
1538 \cvarg{create\_node}{Optional input parameter for sparse matrices. Non-zero value of the parameter means that the requested element is created if it does not exist already.}
1539 \cvarg{precalc\_hashval}{Optional input parameter for sparse matrices. If the pointer is not NULL, the function does not recalculate the node hash value, but takes it from the specified location. It is useful for speeding up pair-wise operations (TODO: provide an example)}
1542 The functions \texttt{cvPtrnD} return pointer to the particular array element. Number of array dimension should match to the number of indices passed to the function except for \texttt{cvPtr1D} function that can be used for sequential access to 1D, 2D or nD dense arrays.
1544 The functions can be used for sparse arrays as well - if the requested node does not exist they create it and set it to zero.
1546 All these as well as other functions accessing array elements (\cross{Get}, \cross{GetReal}, \cross{Set}, \cross{SetReal}) raise an error in case if the element index is out of range.
1548 \cvfunc{Get*D}\label{Get*D}
1550 Return the particular array element
1554 CvScalar cvGet1D( const CvArr* arr, int idx0 );
1555 CvScalar cvGet2D( const CvArr* arr, int idx0, int idx1 );
1556 CvScalar cvGet3D( const CvArr* arr, int idx0, int idx1, int idx2 );
1557 CvScalar cvGetND( const CvArr* arr, int* idx );
1562 \cvarg{arr}{Input array}
1563 \cvarg{idx0}{The first zero-based component of the element index}
1564 \cvarg{idx1}{The second zero-based component of the element index}
1565 \cvarg{idx2}{The third zero-based component of the element index}
1566 \cvarg{idx}{Array of the element indices}
1570 The functions \texttt{cvGet*D} return the particular array element. In case of sparse array the functions return 0 if the requested node does not exist (no new node is created by the functions)
1572 \cvfunc{GetReal*D}\label{GetReal*D}
1574 Return the particular element of single-channel array
1578 double cvGetReal1D( const CvArr* arr, int idx0 );
1579 double cvGetReal2D( const CvArr* arr, int idx0, int idx1 );
1580 double cvGetReal3D( const CvArr* arr, int idx0, int idx1, int idx2 );
1581 double cvGetRealND( const CvArr* arr, int* idx );
1586 \cvarg{arr}{Input array. Must have a single channel.}
1587 \cvarg{idx0}{The first zero-based component of the element index}
1588 \cvarg{idx1}{The second zero-based component of the element index}
1589 \cvarg{idx2}{The third zero-based component of the element index}
1590 \cvarg{idx}{Array of the element indices}
1594 The functions \texttt{cvGetReal*D} return the particular element of single-channel array. If the array has multiple channels, runtime error is raised. Note that \cross{Get} function can be used safely for both single-channel and multiple-channel arrays though they are a bit slower.
1596 In case of sparse array the functions return 0 if the requested node does not exist (no new node is created by the functions)
1598 \cvfunc{mGet}\label{mGet}
1600 Return the particular element of single-channel floating-point matrix
1604 double cvmGet( const CvMat* mat, int row, int col );
1609 \cvarg{mat}{Input matrix}
1610 \cvarg{row}{The zero-based index of row}
1611 \cvarg{col}{The zero-based index of column}
1614 The function \texttt{cvmGet} is a fast replacement for \cross{GetReal2D}
1615 in case of single-channel floating-point matrices. It is faster because
1616 it is inline, it does less checks for array type and array element type
1617 and it checks for the row and column ranges only in debug mode.
1619 \cvfunc{SetnD}\label{SetnD}
1621 Change the particular array element
1625 void cvSet1D( CvArr* arr, int idx0, CvScalar value );
1626 void cvSet2D( CvArr* arr, int idx0, int idx1, CvScalar value );
1627 void cvSet3D( CvArr* arr, int idx0, int idx1, int idx2, CvScalar value );
1628 void cvSetND( CvArr* arr, int* idx, CvScalar value );
1633 \cvarg{arr}{Input array}
1634 \cvarg{idx0}{The first zero-based component of the element index}
1635 \cvarg{idx1}{The second zero-based component of the element index}
1636 \cvarg{idx2}{The third zero-based component of the element index}
1637 \cvarg{idx}{Array of the element indices}
1638 \cvarg{value}{The assigned value}
1642 The functions \texttt{cvSetnD} assign the new value to the particular element of array. In case of sparse array the functions create the node if it does not exist yet
1644 \cvfunc{SetRealnD}\label{SetRealnD}
1646 Change the particular array element
1650 void cvSetReal1D( CvArr* arr, int idx0, double value );
1651 void cvSetReal2D( CvArr* arr, int idx0, int idx1, double value );
1652 void cvSetReal3D( CvArr* arr, int idx0, int idx1, int idx2, double value );
1653 void cvSetRealND( CvArr* arr, int* idx, double value );
1658 \cvarg{arr}{Input array}
1659 \cvarg{idx0}{The first zero-based component of the element index}
1660 \cvarg{idx1}{The second zero-based component of the element index}
1661 \cvarg{idx2}{The third zero-based component of the element index}
1662 \cvarg{idx}{Array of the element indices}
1663 \cvarg{value}{The assigned value}
1666 The functions \texttt{cvSetRealnD} assign the new value to the particular
1667 element of single-channel array. If the array has multiple channels,
1668 runtime error is raised. Note that \cross{SetnD} function can be used
1669 safely for both single-channel and multiple-channel arrays though they
1672 In case of sparse array the functions create the node if it does not exist yet
1674 \cvfunc{mSet}\label{mSet}
1676 Return the particular element of single-channel floating-point matrix
1680 void cvmSet( CvMat* mat, int row, int col, double value );
1685 \cvarg{mat}{The matrix}
1686 \cvarg{row}{The zero-based index of row}
1687 \cvarg{col}{The zero-based index of column}
1688 \cvarg{value}{The new value of the matrix element}
1692 The function \texttt{cvmSet} is a fast replacement for \cross{SetReal2D}
1693 in case of single-channel floating-point matrices. It is faster because
1694 it is inline, it does less checks for array type and array element type
1695 and it checks for the row and column ranges only in debug mode.
1697 \cvfunc{ClearND}\label{ClearND}
1699 Clears the particular array element
1703 void cvClearND( CvArr* arr, int* idx );
1708 \cvarg{arr}{Input array}
1709 \cvarg{idx}{Array of the element indices}
1713 The function \cross{ClearND} clears (sets to zero) the particular element of dense array or deletes the element of sparse array. If the element does not exists, the function does nothing.
1716 \subsection{Copying and Filling}
1719 \cvfunc{Copy}\label{Copy}
1721 Copies one array to another
1725 void cvCopy( const CvArr* src, CvArr* dst, const CvArr* mask=NULL );
1730 \cvarg{src}{The source array}
1731 \cvarg{dst}{The destination array}
1732 \cvarg{mask}{Operation mask, 8-bit single channel array; specifies elements of destination array to be changed}
1736 The function \texttt{cvCopy} copies selected elements from input array to output array:
1739 \texttt{dst}(I)=\texttt{src}(I) \quad \text{if} \quad \texttt{mask}(I) \ne 0.
1742 If any of the passed arrays is of \texttt{IplImage} type, then its ROI
1743 and COI fields are used. Both arrays must have the same type, the same
1744 number of dimensions and the same size. The function can also copy sparse
1745 arrays (mask is not supported in this case).
1747 \cvfunc{Set}\label{Set}
1749 Sets every element of array to given value
1753 void cvSet( CvArr* arr, CvScalar value, const CvArr* mask=NULL );
1758 \cvarg{arr}{The destination array}
1759 \cvarg{value}{Fill value}
1760 \cvarg{mask}{Operation mask, 8-bit single channel array; specifies elements of destination array to be changed}
1764 The function \texttt{cvSet} copies scalar \texttt{value} to every selected element of the destination array:
1767 \texttt{arr}(I)=\texttt{value} \quad \text{if} \quad \texttt{mask}(I) \ne 0
1770 If array \texttt{arr} is of \texttt{IplImage} type, then is ROI used, but COI must not be set.
1772 \cvfunc{SetZero}\label{SetZero}
1778 void cvSetZero( CvArr* arr );
1783 #define cvZero cvSetZero
1787 \cvarg{arr}{array to be cleared}
1790 The function \texttt{cvSetZero} clears the array. In case of dense arrays (CvMat, CvMatND or IplImage) cvZero(array) is equivalent to
1791 cvSet(array,cvScalarAll(0),0).
1792 In case of sparse arrays all the elements are removed.
1794 \subsection{Transforms and Permutations}
1796 \cvfunc{Reshape}\label{Reshape}
1798 Changes shape of matrix/image without copying data
1802 CvMat* cvReshape( const CvArr* arr, CvMat* header, int new\_cn, int new\_rows=0 );
1807 \cvarg{arr}{Input array}
1808 \cvarg{header}{Output header to be filled}
1809 \cvarg{new\_cn}{New number of channels. 'new\_cn = 0' means that number of channels remains unchanged.}
1810 \cvarg{new\_rows}{New number of rows. 'new\_rows = 0' means that number of rows remains unchanged unless it needs to be changed according to \texttt{new\_cn} value. destination array to be changed.}
1813 The function \texttt{cvReshape} initializes CvMat header so that it points to the same data as the original array but has different shape - different number of channels, different number of rows or both.
1815 For example, the following code creates one image buffer and two image headers, first is for 320x240x3 image and the second is for 960x240x1 image:
1819 IplImage* color_img = cvCreateImage( cvSize(320,240), IPL_DEPTH_8U, 3 );
1821 IplImage gray_img_hdr, *gray_img;
1822 cvReshape( color_img, &gray_mat_hdr, 1 );
1823 gray_img = cvGetImage( &gray_mat_hdr, &gray_img_hdr );
1827 And the next example converts 3x3 matrix to a single 1x9 vector
1831 CvMat* mat = cvCreateMat( 3, 3, CV_32F );
1832 CvMat row_header, *row;
1833 row = cvReshape( mat, &row_header, 0, 1 );
1837 \cvfunc{ReshapeMatND}\label{ReshapeMatND}
1839 Changes shape of multi-dimensional array w/o copying data
1843 CvArr* cvReshapeMatND( const CvArr* arr,
1844 int sizeof\_header, CvArr* header,
1845 int new\_cn, int new\_dims, int* new\_sizes );
1849 #define cvReshapeND( arr, header, new\_cn, new\_dims, new\_sizes ) \
1850 cvReshapeMatND( (arr), sizeof(*(header)), (header), \
1851 (new\_cn), (new\_dims), (new\_sizes))
1856 \cvarg{arr}{Input array}
1857 \cvarg{sizeof\_header}{Size of output header to distinguish between IplImage, CvMat and CvMatND output headers}
1858 \cvarg{header}{Output header to be filled}
1859 \cvarg{new\_cn}{New number of channels. $\texttt{new\_cn} = 0$ means that number of channels remains unchanged.}
1860 \cvarg{new\_dims}{New number of dimensions. $\texttt{new\_dims} = 0$ means that number of dimensions remains the same.}
1861 \cvarg{new\_sizes}{Array of new dimension sizes. Only $\texttt{new\_dims}-1$ values are used, because the total number of elements must remain the same.
1862 Thus, if $\texttt{new\_dims} = 1$, \texttt{new\_sizes} array is not used}
1865 The function \texttt{cvReshapeMatND} is an advanced version of \cross{Reshape} that can work with multi-dimensional arrays as well (though, it can work with ordinary images and matrices) and change the number of dimensions. Below are the two samples from the \cross{Reshape} description rewritten using \cross{ReshapeMatND}:
1869 IplImage* color_img = cvCreateImage( cvSize(320,240), IPL_DEPTH_8U, 3 );
1870 IplImage gray_img_hdr, *gray_img;
1871 gray_img = (IplImage*)cvReshapeND( color_img, &gray_img_hdr, 1, 0, 0 );
1875 /* second example is modified to convert 2x2x2 array to 8x1 vector */
1876 int size[] = { 2, 2, 2 };
1877 CvMatND* mat = cvCreateMatND( 3, size, CV_32F );
1878 CvMat row_header, *row;
1879 row = cvReshapeND( mat, &row_header, 0, 1, 0 );
1883 \cvfunc{Repeat}\label{Repeat}
1885 Fill destination array with tiled source array
1889 void cvRepeat( const CvArr* src, CvArr* dst );
1894 \cvarg{src}{Source array, image or matrix}
1895 \cvarg{dst}{Destination array, image or matrix}
1899 The function \texttt{cvRepeat} fills the destination array with source array tiled:
1902 dst(i,j)=src(i mod rows(src), j mod cols(src))
1905 So the destination array may be as larger as well as smaller than the source array.
1908 \cvfunc{Flip}\label{Flip}
1910 Flip a 2D array around vertical, horizontall or both axises
1913 void cvFlip( const CvArr* src, CvArr* dst=NULL, int flip\_mode=0);
1917 #define cvMirror cvFlip
1921 \cvarg{src}{Source array}
1922 \cvarg{dst}{Destination array.
1923 If $\texttt{dst} = \texttt{NULL}$ the flipping is done inplace.}
1924 \cvarg{flip\_mode}{Specifies how to flip the array
1925 0 means flipping around x-axis, positive (e.g. 1) means flipping around y-axis and negative (e.g. -1) means flipping around both axises. See also the discussion below for the formulas}
1928 The function \texttt{cvFlip} flips the array in one of different 3 ways (row and column indices are 0-based):
1931 dst(i,j) = \forkthree
1932 {\texttt{src}(rows(\texttt{src})-i-1,j)}{if $\texttt{flip\_mode} = 0$}
1933 {\texttt{src}(i,cols(\texttt{src})-j-1)}{if $\texttt{flip\_mode} > 0$}
1934 {\texttt{src}(rows(\texttt{src})-i-1,cols(\texttt{src})-j-1)}{if $\texttt{flip\_mode} < 0$}
1937 The example cenaria of the function use are:
1939 \item vertical flipping of the image (flip\_mode > 0) to switch between top-left and bottom-left image origin, which is typical operation in video processing under Win32 systems.
1940 \item horizontal flipping of the image with subsequent horizontal shift and absolute difference calculation to check for a vertical-axis symmetry (flip\_mode > 0)
1941 \item simultaneous horizontal and vertical flipping of the image with subsequent shift and absolute difference calculation to check for a central symmetry (flip\_mode < 0)
1942 \item reversing the order of 1d point arrays(flip\_mode > 0)
1945 \cvfunc{Split}\label{Split}
1947 Divides multi-channel array into several single-channel arrays or extracts a single channel from the array
1951 void cvSplit( const CvArr* src, CvArr* dst0, CvArr* dst1,
1952 CvArr* dst2, CvArr* dst3 );
1956 #define cvCvtPixToPlane cvSplit
1960 \cvarg{src}{Source array}
1961 \cvarg{dst0...dst3}{Destination channels}
1964 The function \texttt{cvSplit} divides a multi-channel array into separate
1965 single-channel arrays. Two modes are available for the operation. If the
1966 source array has N channels then if the first N destination channels
1967 are not NULL, all they are extracted from the source array, otherwise
1968 if only a single destination channel of the first N is not NULL, this
1969 particular channel is extracted, otherwise an error is raised. Rest
1970 of destination channels (beyond the first N) must always be NULL. For
1971 IplImage \cross{Copy} with COI set can be also used to extract a single
1972 channel from the image.
1975 \cvfunc{Merge}\label{Merge}
1977 Composes multi-channel array from several single-channel arrays or inserts a single channel into the array
1981 void cvMerge( const CvArr* src0, const CvArr* src1,
1982 const CvArr* src2, const CvArr* src3, CvArr* dst );
1986 #define cvCvtPlaneToPix cvMerge
1990 \cvarg{src0...src3}{Input channels}
1991 \cvarg{dst}{Destination array}
1994 The function \texttt{cvMerge} is the opposite to the previous. If the destination array has N channels then if the first N input channels are not NULL, all they are copied to the destination array, otherwise if only a single source channel of the first N is not NULL, this particular channel is copied into the destination array, otherwise an error is raised. Rest of source channels (beyond the first N) must always be NULL. For IplImage \cross{Copy} with COI set can be also used to insert a single channel into the image.
1997 \subsection{Arithmetic, Logic and Comparison}
1999 \cvfunc{LUT}\label{LUT}
2001 Performs look-up table transform of array
2005 void cvLUT( const CvArr* src, CvArr* dst, const CvArr* lut );
2010 \cvarg{src}{Source array of 8-bit elements}
2011 \cvarg{dst}{Destination array of arbitrary depth and of the same number of channels as the source array}
2012 \cvarg{lut}{Look-up table of 256 elements; should have the same depth as the destination array. In case of multi-channel source and destination arrays, the table should either have a single-channel (in this case the same table is used for all channels), or the same number of channels as the source/destination array.}
2015 The function \texttt{cvLUT} fills the destination array with values from the look-up table. Indices of the entries are taken from the source array. That is, the function processes each element of \texttt{src} as following:
2018 \texttt{dst}_i \leftarrow \texttt{lut}_{\texttt{src}_i + d}
2025 {0}{if \texttt{src} has depth \texttt{CV\_8U}}
2026 {128}{if \texttt{src} has depth \texttt{CV\_8S}}
2029 \cvfunc{ConvertScale}\label{ConvertScale}
2031 Converts one array to another with optional linear transformation
2035 void cvConvertScale( const CvArr* src, CvArr* dst, double scale=1, double shift=0 );
2040 #define cvCvtScale cvConvertScale
2041 #define cvScale cvConvertScale
2042 #define cvConvert( src, dst ) cvConvertScale( (src), (dst), 1, 0 )
2046 \cvarg{src}{Source array}
2047 \cvarg{dst}{Destination array}
2048 \cvarg{scale}{Scale factor}
2049 \cvarg{shift}{Value added to the scaled source array elements}
2053 The function \texttt{cvConvertScale} has several different purposes and thus has several synonyms. It copies one array to another with optional scaling, which is performed first, and/or optional type conversion, performed after:
2056 \texttt{dst}(I) = \texttt{scale} \texttt{src}(I) + (\texttt{shift}_0,\texttt{shift}_1,...)
2059 All the channels of multi-channel arrays are processed independently.
2061 The type conversion is done with rounding and saturation, that is if a
2062 result of scaling + conversion can not be represented exactly by a value
2063 of destination array element type, it is set to the nearest representable
2064 value on the real axis.
2066 In case of 'scale=1, shift=0' no prescaling is done. This is a specially
2067 optimized case and it has the appropriate \cross{Convert} synonym. If
2068 source and destination array types have equal types, this is also a
2069 special case that can be used to scale and shift a matrix or an image
2070 and that fits to \cross{Scale} synonym.
2072 \cvfunc{ConvertScaleAbs}\label{ConvertScaleAbs}
2074 Converts input array elements to 8-bit unsigned integer another with optional linear transformation
2077 void cvConvertScaleAbs( const CvArr* src, CvArr* dst, double scale=1, double shift=0 );
2081 #define cvCvtScaleAbs cvConvertScaleAbs
2085 \cvarg{src}{Source array}
2086 \cvarg{dst}{Destination array (should have 8u depth)}
2087 \cvarg{scale}{ScaleAbs factor}
2088 \cvarg{shift}{Value added to the scaled source array elements}
2092 The function \texttt{cvConvertScaleAbs} is similar to the previous one, but it stores absolute values of the conversion results:
2095 \texttt{dst}(I) = |\texttt{scale} \texttt{src}(I) + (\texttt{shift}_0,\texttt{shift}_1,...)|
2098 The function supports only destination arrays of 8u (8-bit unsigned integers) type, for other types the function can be emulated by combination of \cross{ConvertScale} and \cross{Abs} functions.
2100 \cvfunc{Add}\label{Add}
2102 Computes per-element sum of two arrays
2106 void cvAdd( const CvArr* src1, const CvArr* src2, CvArr* dst, const CvArr* mask=NULL );
2111 \cvarg{src1}{The first source array}
2112 \cvarg{src2}{The second source array}
2113 \cvarg{dst}{The destination array}
2114 \cvarg{mask}{Operation mask, 8-bit single channel array; specifies elements of destination array to be changed}
2117 The function \texttt{cvAdd} adds one array to another one:
2120 dst(I)=src1(I)+src2(I) if mask(I)!=0
2123 All the arrays must have the same type, except the mask, and the same size (or ROI size)
2126 \cvfunc{AddS}\label{AddS}
2128 Computes sum of array and scalar
2132 void cvAddS( const CvArr* src, CvScalar value, CvArr* dst, const CvArr* mask=NULL );
2137 \cvarg{src}{The source array}
2138 \cvarg{value}{Added scalar}
2139 \cvarg{dst}{The destination array}
2140 \cvarg{mask}{Operation mask, 8-bit single channel array; specifies elements of destination array to be changed}
2144 The function \texttt{cvAddS} adds scalar \texttt{value} to every element in the source array \texttt{src1} and stores the result in \texttt{dst}
2147 dst(I)=src(I)+value if mask(I)!=0
2150 All the arrays must have the same type, except the mask, and the same size (or ROI size)
2153 \cvfunc{AddWeighted}\label{AddWeighted}
2155 Computes weighted sum of two arrays
2159 void cvAddWeighted( const CvArr* src1, double alpha,
2160 const CvArr* src2, double beta,
2161 double gamma, CvArr* dst );
2166 \cvarg{src1}{The first source array}
2167 \cvarg{alpha}{Weight of the first array elements}
2168 \cvarg{src2}{The second source array}
2169 \cvarg{beta}{Weight of the second array elements}
2170 \cvarg{dst}{The destination array}
2171 \cvarg{gamma}{Scalar, added to each sum}
2174 The function \texttt{cvAddWeighted} calculated weighted sum of two arrays as following:
2177 dst(I)=src1(I)*alpha+src2(I)*beta+gamma
2180 All the arrays must have the same type and the same size (or ROI size)
2183 \cvfunc{Sub}\label{Sub}
2185 Computes per-element difference between two arrays
2189 void cvSub( const CvArr* src1, const CvArr* src2, CvArr* dst, const CvArr* mask=NULL );
2194 \cvarg{src1}{The first source array}
2195 \cvarg{src2}{The second source array}
2196 \cvarg{dst}{The destination array}
2197 \cvarg{mask}{Operation mask, 8-bit single channel array; specifies elements of destination array to be changed}
2201 The function \texttt{cvSub} subtracts one array from another one:
2204 dst(I)=src1(I)-src2(I) if mask(I)!=0
2207 All the arrays must have the same type, except the mask, and the same size (or ROI size)
2209 \cvfunc{SubS}\label{SubS}
2211 Computes difference between array and scalar
2215 void cvSubS( const CvArr* src, CvScalar value, CvArr* dst, const CvArr* mask=NULL );
2220 \cvarg{src}{The source array}
2221 \cvarg{value}{Subtracted scalar}
2222 \cvarg{dst}{The destination array}
2223 \cvarg{mask}{Operation mask, 8-bit single channel array; specifies elements of destination array to be changed}
2226 The function \texttt{cvSubS} subtracts a scalar from every element of the source array:
2229 dst(I)=src(I)-value if mask(I)!=0
2232 All the arrays must have the same type, except the mask, and the same size (or ROI size)
2235 \cvfunc{SubRS}\label{SubRS}
2237 Computes difference between scalar and array
2241 void cvSubRS( const CvArr* src, CvScalar value, CvArr* dst, const CvArr* mask=NULL );
2246 \cvarg{src}{The first source array}
2247 \cvarg{value}{Scalar to subtract from}
2248 \cvarg{dst}{The destination array}
2249 \cvarg{mask}{Operation mask, 8-bit single channel array; specifies elements of destination array to be changed}
2253 The function \texttt{cvSubRS} subtracts every element of source array from a scalar:
2256 dst(I)=value-src(I) if mask(I)!=0
2259 All the arrays must have the same type, except the mask, and the same size (or ROI size)
2261 \cvfunc{Mul}\label{Mul}
2263 Calculates per-element product of two arrays
2267 void cvMul( const CvArr* src1, const CvArr* src2, CvArr* dst, double scale=1 );
2272 \cvarg{src1}{The first source array}
2273 \cvarg{src2}{The second source array}
2274 \cvarg{dst}{The destination array}
2275 \cvarg{scale}{Optional scale factor}
2279 The function \texttt{cvMul} calculates per-element product of two arrays:
2282 \texttt{dst}(I)=\texttt{scale} \cdot \texttt{src1}(I) \cdot \texttt{src2}(I)
2285 All the arrays must have the same type, and the same size (or ROI size)
2287 \cvfunc{Div}\label{Div}
2289 Performs per-element division of two arrays
2293 void cvDiv( const CvArr* src1, const CvArr* src2, CvArr* dst, double scale=1 );
2298 \cvarg{src1}{The first source array. If the pointer is NULL, the array is assumed to be all 1's.}
2299 \cvarg{src2}{The second source array}
2300 \cvarg{dst}{The destination array}
2301 \cvarg{scale}{Optional scale factor}
2304 The function \texttt{cvDiv} divides one array by another:
2307 \texttt{dst}(I)=\fork
2308 {\texttt{scale} \cdot \texttt{src1}(I)/\texttt{src2}(I)}{if \texttt{src1} is not \texttt{NULL}}
2309 {\texttt{scale}/\texttt{src2}(I)}{otherwise}
2312 All the arrays must have the same type, and the same size (or ROI size)
2315 \cvfunc{And}\label{And}
2317 Calculates per-element bit-wise conjunction of two arrays
2321 void cvAnd( const CvArr* src1, const CvArr* src2, CvArr* dst, const CvArr* mask=NULL );
2326 \cvarg{src1}{The first source array}
2327 \cvarg{src2}{The second source array}
2328 \cvarg{dst}{The destination array}
2329 \cvarg{mask}{Operation mask, 8-bit single channel array; specifies elements of destination array to be changed}
2333 The function \texttt{cvAnd} calculates per-element bit-wise logical conjunction of two arrays:
2336 dst(I)=src1(I)&src2(I) if mask(I)!=0
2339 In the case of floating-point arrays their bit representations are used for the operation. All the arrays must have the same type, except the mask, and the same size.
2341 \cvfunc{AndS}\label{AndS}
2343 Calculates per-element bit-wise conjunction of array and scalar
2347 void cvAndS( const CvArr* src, CvScalar value, CvArr* dst, const CvArr* mask=NULL );
2352 \cvarg{src}{The source array}
2353 \cvarg{value}{Scalar to use in the operation}
2354 \cvarg{dst}{The destination array}
2355 \cvarg{mask}{Operation mask, 8-bit single channel array; specifies elements of destination array to be changed}
2358 The function AndS calculates per-element bit-wise conjunction of array and scalar:
2361 dst(I)=src(I)&value if mask(I)!=0
2364 Prior to the actual operation the scalar is converted to the same type as the arrays. In the case of floating-point arrays their bit representations are used for the operation. All the arrays must have the same type, except the mask, and the same size
2366 The following sample demonstrates how to calculate absolute value of floating-point array elements by clearing the most-significant bit:
2370 float a[] = { -1, 2, -3, 4, -5, 6, -7, 8, -9 };
2371 CvMat A = cvMat( 3, 3, CV\_32F, &a );
2372 int i, abs\_mask = 0x7fffffff;
2373 cvAndS( &A, cvRealScalar(*(float*)&abs\_mask), &A, 0 );
2374 for( i = 0; i < 9; i++ )
2375 printf("%.1f ", a[i] );
2379 The code should print:
2382 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0
2386 \cvfunc{Or}\label{Or}
2388 Calculates per-element bit-wise disjunction of two arrays
2392 void cvOr( const CvArr* src1, const CvArr* src2, CvArr* dst, const CvArr* mask=NULL );
2397 \cvarg{src1}{The first source array}
2398 \cvarg{src2}{The second source array}
2399 \cvarg{dst}{The destination array}
2400 \cvarg{mask}{Operation mask, 8-bit single channel array; specifies elements of destination array to be changed}
2404 The function \texttt{cvOr} calculates per-element bit-wise disjunction of two arrays:
2407 dst(I)=src1(I)|src2(I)
2410 In the case of floating-point arrays their bit representations are used for the operation. All the arrays must have the same type, except the mask, and the same size
2412 \cvfunc{OrS}\label{OrS}
2414 Calculates per-element bit-wise disjunction of array and scalar
2418 void cvOrS( const CvArr* src, CvScalar value, CvArr* dst, const CvArr* mask=NULL );
2423 \cvarg{src1}{The source array}
2424 \cvarg{value}{Scalar to use in the operation}
2425 \cvarg{dst}{The destination array}
2426 \cvarg{mask}{Operation mask, 8-bit single channel array; specifies elements of destination array to be changed}
2430 The function OrS calculates per-element bit-wise disjunction of array and scalar:
2433 dst(I)=src(I)|value if mask(I)!=0
2436 Prior to the actual operation the scalar is converted to the same type as the arrays. In the case of floating-point arrays their bit representations are used for the operation. All the arrays must have the same type, except the mask, and the same size
2439 \cvfunc{Xor}\label{Xor}
2441 Performs per-element bit-wise "exclusive or" operation on two arrays
2445 void cvXor( const CvArr* src1, const CvArr* src2, CvArr* dst, const CvArr* mask=NULL );
2450 \cvarg{src1}{The first source array}
2451 \cvarg{src2}{The second source array}
2452 \cvarg{dst}{The destination array}
2453 \cvarg{mask}{Operation mask, 8-bit single channel array; specifies elements of destination array to be changed}
2456 The function \texttt{cvXor} calculates per-element bit-wise logical conjunction of two arrays:
2459 dst(I)=src1(I)^src2(I) if mask(I)!=0
2462 In the case of floating-point arrays their bit representations are used for the operation. All the arrays must have the same type, except the mask, and the same size
2464 \cvfunc{XorS}\label{XorS}
2466 Performs per-element bit-wise "exclusive or" operation on array and scalar
2470 void cvXorS( const CvArr* src, CvScalar value, CvArr* dst, const CvArr* mask=NULL );
2475 \cvarg{src}{The source array}
2476 \cvarg{value}{Scalar to use in the operation}
2477 \cvarg{dst}{The destination array}
2478 \cvarg{mask}{Operation mask, 8-bit single channel array; specifies elements of destination array to be changed}
2482 The function XorS calculates per-element bit-wise conjunction of array and scalar:
2485 dst(I)=src(I)^value if mask(I)!=0
2488 Prior to the actual operation the scalar is converted to the same type as the arrays. In the case of floating-point arrays their bit representations are used for the operation. All the arrays must have the same type, except the mask, and the same size
2490 The following sample demonstrates how to conjugate complex vector by switching the most-significant bit of imaging part:
2494 float a[] = { 1, 0, 0, 1, -1, 0, 0, -1 }; /* 1, j, -1, -j */
2495 CvMat A = cvMat( 4, 1, CV\_32FC2, &a );
2496 int i, neg\_mask = 0x80000000;
2497 cvXorS( &A, cvScalar( 0, *(float*)&neg\_mask, 0, 0 ), &A, 0 );
2498 for( i = 0; i < 4; i++ )
2499 printf("(%.1f, %.1f) ", a[i*2], a[i*2+1] );
2503 The code should print:
2506 (1.0,0.0) (0.0,-1.0) (-1.0,0.0) (0.0,1.0)
2509 \cvfunc{Not}\label{Not}
2511 Performs per-element bit-wise inversion of array elements
2515 void cvNot( const CvArr* src, CvArr* dst );
2520 \cvarg{src1}{The source array}
2521 \cvarg{dst}{The destination array}
2525 The function Not inverses every bit of every array element:
2532 \cvfunc{Cmp}\label{Cmp}
2534 Performs per-element comparison of two arrays
2538 void cvCmp( const CvArr* src1, const CvArr* src2, CvArr* dst, int cmp\_op );
2543 \cvarg{src1}{The first source array}
2544 \cvarg{src2}{The second source array. Both source array must have a single channel.}
2545 \cvarg{dst}{The destination array, must have 8u or 8s type}
2546 \cvarg{cmp\_op}{The flag specifying the relation between the elements to be checked
2548 \cvarg{CV\_CMP\_EQ}{src1(I) "equal to" value}
2549 \cvarg{CV\_CMP\_GT}{src1(I) "greater than" value}
2550 \cvarg{CV\_CMP\_GE}{src1(I) "greater or equal" value}
2551 \cvarg{CV\_CMP\_LT}{src1(I) "less than" value}
2552 \cvarg{CV\_CMP\_LE}{src1(I) "less or equal" value}
2553 \cvarg{CV\_CMP\_NE}{src1(I) "not equal" value}
2557 The function \texttt{cvCmp} compares the corresponding elements of two arrays and fills the destination mask array:
2561 dst(I)=src1(I) op src2(I),
2565 \texttt{dst(I)} is set to 0xff (all \texttt{1}-bits) if the particular relation between the elements is true and 0 otherwise. All the arrays must have the same type, except the destination, and the same size (or ROI size)
2567 \cvfunc{CmpS}\label{CmpS}
2569 Performs per-element comparison of array and scalar
2573 void cvCmpS( const CvArr* src, double value, CvArr* dst, int cmp\_op );
2578 \cvarg{src}{The source array, must have a single channel}
2579 \cvarg{value}{The scalar value to compare each array element with}
2580 \cvarg{dst}{The destination array, must have 8u or 8s type}
2581 \cvarg{cmp\_op}{The flag specifying the relation between the elements to be checked
2583 \cvarg{CV\_CMP\_EQ}{src1(I) "equal to" value}
2584 \cvarg{CV\_CMP\_GT}{src1(I) "greater than" value}
2585 \cvarg{CV\_CMP\_GE}{src1(I) "greater or equal" value}
2586 \cvarg{CV\_CMP\_LT}{src1(I) "less than" value}
2587 \cvarg{CV\_CMP\_LE}{src1(I) "less or equal" value}
2588 \cvarg{CV\_CMP\_NE}{src1(I) "not equal" value}
2592 The function \texttt{CmpS} compares the corresponding elements of array and scalar and fills the destination mask array:
2596 dst(I)=src(I) op scalar
2600 where \texttt{op} is $=$, $>$, $\ge$, $<$, $\le$ or $\ne$.
2602 dst(I) is set to 0xff (all \texttt{1}-bits) if the particular relation between the elements is true and 0 otherwise. All the arrays must have the same size (or ROI size)
2604 \cvfunc{InRange}\label{InRange}
2606 Checks that array elements lie between elements of two other arrays
2610 void cvInRange( const CvArr* src, const CvArr* lower, const CvArr* upper, CvArr* dst );
2615 \cvarg{src}{The first source array}
2616 \cvarg{lower}{The inclusive lower boundary array}
2617 \cvarg{upper}{The exclusive upper boundary array}
2618 \cvarg{dst}{The destination array, must have 8u or 8s type}
2622 The function \texttt{cvInRange} does the range check for every element of the input array:
2625 \texttt{dst}(I)=\texttt{lower}(I)_0 <= \texttt{src}(I)_0 < \texttt{upper}(I)_0
2628 for single-channel arrays,
2632 \texttt{lower}(I)_0 <= \texttt{src}(I)_0 < \texttt{upper}(I)_0 \land
2633 \texttt{lower}(I)_1 <= \texttt{src}(I)_1 < \texttt{upper}(I)_1
2636 for two-channel arrays etc.
2638 dst(I) is set to 0xff (all \texttt{1}-bits) if src(I) is within the range and 0 otherwise. All the arrays must have the same type, except the destination, and the same size (or ROI size)
2641 \cvfunc{InRangeS}\label{InRangeS}
2643 Checks that array elements lie between two scalars
2647 void cvInRangeS( const CvArr* src, CvScalar lower, CvScalar upper, CvArr* dst );
2652 \cvarg{src}{The first source array}
2653 \cvarg{lower}{The inclusive lower boundary}
2654 \cvarg{upper}{The exclusive upper boundary}
2655 \cvarg{dst}{The destination array, must have 8u or 8s type}
2659 The function \texttt{cvInRangeS} does the range check for every element of the input array:
2662 \texttt{dst}(I)=\texttt{lower}_0 <= \texttt{src}(I)_0 < \texttt{upper}_0
2665 for single-channel arrays,
2669 \texttt{lower}_0 <= \texttt{src}(I)_0 < \texttt{upper}_0 \land
2670 \texttt{lower}_1 <= \texttt{src}(I)_1 < \texttt{upper}_1
2673 for two-channel arrays etc.
2675 'dst(I)' is set to 0xff (all \texttt{1}-bits) if 'src(I)' is within the range and 0 otherwise. All the arrays must have the same size (or ROI size)
2677 \cvfunc{Max}\label{Max}
2679 Finds per-element maximum of two arrays
2683 void cvMax( const CvArr* src1, const CvArr* src2, CvArr* dst );
2688 \cvarg{src1}{The first source array}
2689 \cvarg{src2}{The second source array}
2690 \cvarg{dst}{The destination array}
2693 The function \texttt{cvMax} calculates per-element maximum of two arrays:
2696 \texttt{dst}(I)=\max(\texttt{src1}(I), \texttt{src2}(I))
2699 All the arrays must have a single channel, the same data type and the same size (or ROI size).
2702 \cvfunc{MaxS}\label{MaxS}
2704 Finds per-element maximum of array and scalar
2708 void cvMaxS( const CvArr* src, double value, CvArr* dst );
2713 \cvarg{src}{The first source array}
2714 \cvarg{value}{The scalar value}
2715 \cvarg{dst}{The destination array}
2718 The function \texttt{cvMaxS} calculates per-element maximum of array and scalar:
2721 \texttt{dst}(I)=\max(\texttt{src}(I), \texttt{value})
2724 All the arrays must have a single channel, the same data type and the same size (or ROI size).
2727 \cvfunc{Min}\label{Min}
2729 Finds per-element minimum of two arrays
2733 void cvMin( const CvArr* src1, const CvArr* src2, CvArr* dst );
2738 \cvarg{src1}{The first source array}
2739 \cvarg{src2}{The second source array}
2740 \cvarg{dst}{The destination array}
2744 The function \texttt{cvMin} calculates per-element minimum of two arrays:
2747 \texttt{dst}(I)=\min(\texttt{src1}(I),\texttt{src2}(I))
2750 All the arrays must have a single channel, the same data type and the same size (or ROI size).
2753 \cvfunc{MinS}\label{MinS}
2755 Finds per-element minimum of array and scalar
2759 void cvMinS( const CvArr* src, double value, CvArr* dst );
2764 \cvarg{src}{The first source array}
2765 \cvarg{value}{The scalar value}
2766 \cvarg{dst}{The destination array}
2769 The function \texttt{cvMinS} calculates minimum of array and scalar:
2772 \texttt{dst}(I)=\min(\texttt{src}(I), \texttt{value})
2775 All the arrays must have a single channel, the same data type and the same size (or ROI size).
2777 \cvfunc{AbsDiff}\label{AbsDiff}
2779 Calculates absolute difference between two arrays
2783 void cvAbsDiff( const CvArr* src1, const CvArr* src2, CvArr* dst );
2788 \cvarg{src1}{The first source array}
2789 \cvarg{src2}{The second source array}
2790 \cvarg{dst}{The destination array}
2793 The function \texttt{cvAbsDiff} calculates absolute difference between two arrays.
2795 \[ \texttt{dst}(i)_c = |\texttt{src1}(I)_c - \texttt{src2}(I)_c| \]
2797 All the arrays must have the same data type and the same size (or ROI size).
2799 \cvfunc{AbsDiffS}\label{AbsDiffS}
2801 Calculates absolute difference between array and scalar
2805 void cvAbsDiffS( const CvArr* src, CvArr* dst, CvScalar value );
2809 #define cvAbs(src, dst) cvAbsDiffS(src, dst, cvScalarAll(0))
2813 \cvarg{src}{The source array}
2814 \cvarg{dst}{The destination array}
2815 \cvarg{value}{The scalar}
2818 The function \texttt{cvAbsDiffS} calculates absolute difference between array and scalar.
2820 \[ \texttt{dst}(i)_c = |\texttt{src}(I)_c - \texttt{value}_c| \]
2822 All the arrays must have the same data type and the same size (or ROI size).
2824 \subsection{Statistics}
2826 \cvfunc{CountNonZero}\label{CountNonZero}
2828 Counts non-zero array elements
2832 int cvCountNonZero( const CvArr* arr );
2837 \cvarg{arr}{The array, must be single-channel array or multi-channel image with COI set}
2841 The function \texttt{cvCountNonZero} returns the number of non-zero elements in arr:
2843 \[ \sum_I (\texttt{arr}(I) \ne 0) \]
2845 In case of \texttt{IplImage} both ROI and COI are supported.
2848 \cvfunc{Sum}\label{Sum}
2850 Summarizes array elements
2854 CvScalar cvSum( const CvArr* arr );
2859 \cvarg{arr}{The array}
2863 The function \texttt{cvSum} calculates sum \texttt{S} of array elements, independently for each channel:
2865 \[ \sum_I \texttt{arr}(I)_c \]
2867 If the array is \texttt{IplImage} and COI is set, the function processes the selected channel only and stores the sum to the first scalar component
2871 \cvfunc{Avg}\label{Avg}
2873 Calculates average (mean) of array elements
2877 CvScalar cvAvg( const CvArr* arr, const CvArr* mask=NULL );
2882 \cvarg{arr}{The array}
2883 \cvarg{mask}{The optional operation mask}
2887 The function \texttt{cvAvg} calculates the average value \texttt{M} of array elements, independently for each channel:
2891 N = \sum_I (\texttt{mask}(I) \ne 0)\\
2892 M_c = \frac{\sum_{ I, \, \texttt{mask}(I) \ne 0} \texttt{arr}(I)_c}{N}
2896 If the array is \texttt{IplImage} and COI is set, the function processes the selected channel only and stores the average to the first scalar component $ S_0 $ .
2898 \cvfunc{AvgSdv}\label{AvgSdv}
2900 Calculates average (mean) of array elements
2904 void cvAvgSdv( const CvArr* arr, CvScalar* mean, CvScalar* std\_dev, const CvArr* mask=NULL );
2909 \cvarg{arr}{The array}
2910 \cvarg{mean}{Pointer to the mean value, may be NULL if it is not needed}
2911 \cvarg{std\_dev}{Pointer to the standard deviation}
2912 \cvarg{mask}{The optional operation mask}
2915 The function \texttt{cvAvgSdv} calculates the average value and standard deviation of array elements, independently for each channel:
2919 N = \sum_I (\texttt{mask}(I) \ne 0)\\
2920 mean_c = \frac{\sum_{ I, \, \texttt{mask}(I) \ne 0} \texttt{arr}(I)_c}{N}\\
2921 std\_dev_c = \sqrt{\sum_{ I, \, \texttt{mask}(I) \ne 0} (\texttt{arr}(I)_c - mean_c)^2}
2925 If the array is \texttt{IplImage} and COI is set, the function processes the selected channel only and stores the average and standard deviation to the first compoenents of output scalars ($mean_0$ and $std\_dev_0$).
2927 \cvfunc{MinMaxLoc}\label{MinMaxLoc}
2929 Finds global minimum and maximum in array or subarray
2933 void cvMinMaxLoc( const CvArr* arr, double* min\_val, double* max\_val,
2934 CvPoint* min\_loc=NULL, CvPoint* max\_loc=NULL, const CvArr* mask=NULL );
2939 \cvarg{arr}{The source array, single-channel or multi-channel with COI set}
2940 \cvarg{min\_val}{Pointer to returned minimum value}
2941 \cvarg{max\_val}{Pointer to returned maximum value}
2942 \cvarg{min\_loc}{Pointer to returned minimum location}
2943 \cvarg{max\_loc}{Pointer to returned maximum location}
2944 \cvarg{mask}{The optional mask that is used to select a subarray}
2947 The function \texttt{MinMaxLoc} finds minimum and maximum element values
2948 and their positions. The extremums are searched over the whole array,
2949 selected \texttt{ROI} (in case of \texttt{IplImage}) or, if \texttt{mask}
2950 is not \texttt{NULL}, in the specified array region. If the array has
2951 more than one channel, it must be \texttt{IplImage} with \texttt{COI}
2952 set. In case if multi-dimensional arrays \texttt{min\_loc->x} and \texttt{max\_loc->x}
2953 will contain raw (linear) positions of the extremums.
2955 \cvfunc{Norm}\label{Norm}
2957 Calculates absolute array norm, absolute difference norm or relative difference norm
2961 double cvNorm( const CvArr* arr1, const CvArr* arr2=NULL, int norm\_type=CV\_L2, const CvArr* mask=NULL );
2966 \cvarg{arr1}{The first source image}
2967 \cvarg{arr2}{The second source image. If it is NULL, the absolute norm of \texttt{arr1} is calculated, otherwise absolute or relative norm of \texttt{arr1}-\texttt{arr2} is calculated.}
2968 \cvarg{normType}{Type of norm, see the discussion}
2969 \cvarg{mask}{The optional operation mask}
2972 The function \texttt{cvNorm} calculates the absolute norm of \texttt{arr1} if \texttt{arr2} is NULL:
2975 {||\texttt{arr1}||_C = \max_I |\texttt{arr1}(I)|}{if $\texttt{normType} = \texttt{CV\_C}$}
2976 {||\texttt{arr1}||_{L1} = \sum_I |\texttt{arr1}(I)|}{if $\texttt{normType} = \texttt{CV\_L1}$}
2977 {||\texttt{arr1}||_{L2} = \sqrt{\sum_I \texttt{arr1}(I)^2}}{if $\texttt{normType} = \texttt{CV\_L2}$}
2980 And the function calculates absolute or relative difference norm if \texttt{arr2} is not NULL:
2983 {||\texttt{arr1}-\texttt{arr2}||_C = \max_I |\texttt{arr1}(I) - \texttt{arr2}(I)|}{if $\texttt{normType} = \texttt{CV\_C}$}
2984 {||\texttt{arr1}-\texttt{arr2}||_{L1} = \sum_I |\texttt{arr1}(I) - \texttt{arr2}(I)|}{if $\texttt{normType} = \texttt{CV\_L1}$}
2985 {||\texttt{arr1}-\texttt{arr2}||_{L2} = \sqrt{\sum_I (\texttt{arr1}(I) - \texttt{arr2}(I))^2}}{if $\texttt{normType} = \texttt{CV\_L2}$}
2992 {\frac{||\texttt{arr1}-\texttt{arr2}||_C }{||\texttt{arr2}||_C }}{if $\texttt{normType} = \texttt{CV\_RELATIVE\_C}$}
2993 {\frac{||\texttt{arr1}-\texttt{arr2}||_{L1} }{||\texttt{arr2}||_{L1}}}{if $\texttt{normType} = \texttt{CV\_RELATIVE\_L1}$}
2994 {\frac{||\texttt{arr1}-\texttt{arr2}||_{L2} }{||\texttt{arr2}||_{L2}}}{if $\texttt{normType} = \texttt{CV\_RELATIVE\_L2}$}
2997 The function \texttt{Norm} returns the calculated norm. The multiple-channel array are treated as single-channel, that is, the results for all channels are combined.
2999 % XXX missing Reduce
3001 \subsection{Linear Algebra}
3003 \cvfunc{SetIdentity}\label{SetIdentity}
3005 Initializes scaled identity matrix
3009 void cvSetIdentity( CvArr* mat, CvScalar value=cvRealScalar(1) );
3014 \cvarg{arr}{The matrix to initialize (not necesserily square)}
3015 \cvarg{value}{The value to assign to the diagonal elements}
3018 The function \texttt{cvSetIdentity} initializes scaled identity matrix:
3021 \texttt{arr}(i,j)=\fork{\texttt{value}}{ if $i=j$}{0}{otherwise}
3024 \cvfunc{DotProduct}\label{DotProduct}
3026 Calculates dot product of two arrays in Euclidian metrics
3030 double cvDotProduct( const CvArr* src1, const CvArr* src2 );
3035 \cvarg{src1}{The first source array}
3036 \cvarg{src2}{The second source array}
3039 The function \texttt{cvDotProduct} calculates and returns the Euclidean dot product of two arrays.
3042 src1 \bullet src2 = \sum_I (\texttt{src1}(I) \texttt{src2}(I))
3045 In case of multiple channel arrays the results for all channels are accumulated. In particular, \texttt{cvDotProduct(a,a)} where \texttt{a} is a complex vector, will return $||\texttt{a}||^2$.
3046 The function can process multi-dimensional arrays, row by row, layer by layer and so on.
3048 \cvfunc{CrossProduct}\label{CrossProduct}
3050 Calculates cross product of two 3D vectors
3054 void cvCrossProduct( const CvArr* src1, const CvArr* src2, CvArr* dst );
3059 \cvarg{src1}{The first source vector}
3060 \cvarg{src2}{The second source vector}
3061 \cvarg{dst}{The destination vector}
3065 The function \texttt{cvCrossProduct} calculates the cross product of two 3D vectors:
3067 \[ \texttt{dst} = \texttt{src1} \times \texttt{src2} \]
3071 \texttt{dst}_1 = \texttt{src1}_2 \texttt{src2}_3 - \texttt{src1}_3 \texttt{src2}_2\\
3072 \texttt{dst}_2 = \texttt{src1}_3 \texttt{src2}_1 - \texttt{src1}_1 \texttt{src2}_3\\
3073 \texttt{dst}_3 = \texttt{src1}_1 \texttt{src2}_2 - \texttt{src1}_2 \texttt{src2}_1
3077 \cvfunc{ScaleAdd}\label{ScaleAdd}
3079 Calculates sum of scaled array and another array
3083 void cvScaleAdd( const CvArr* src1, CvScalar scale, const CvArr* src2, CvArr* dst );
3087 #define cvMulAddS cvScaleAdd
3091 \cvarg{src1}{The first source array}
3092 \cvarg{scale}{Scale factor for the first array}
3093 \cvarg{src2}{The second source array}
3094 \cvarg{dst}{The destination array}
3097 The function \texttt{cvScaleAdd} calculates sum of scaled array and another array:
3100 \texttt{dst}(I)=\texttt{scale} \, \texttt{src1}(I) + \texttt{src2}(I)
3103 All array parameters should have the same type and the same size.
3105 \cvfunc{GEMM}\label{GEMM}
3107 Performs generalized matrix multiplication
3111 void cvGEMM( const CvArr* src1, const CvArr* src2, double alpha,
3112 const CvArr* src3, double beta, CvArr* dst, int tABC=0 );
3116 #define cvMatMulAdd( src1, src2, src3, dst ) cvGEMM( src1, src2, 1, src3, 1, dst, 0 )
3117 #define cvMatMul( src1, src2, dst ) cvMatMulAdd( src1, src2, 0, dst )
3121 \cvarg{src1}{The first source array}
3122 \cvarg{src2}{The second source array}
3123 \cvarg{src3}{The third source array (shift). Can be NULL, if there is no shift.}
3124 \cvarg{dst}{The destination array}
3125 \cvarg{tABC}{The operation flags that can be 0 or combination of the following values
3127 \cvarg{CV\_GEMM\_A\_T}{transpose src1}
3128 \cvarg{CV\_GEMM\_B\_T}{transpose src2}
3129 \cvarg{CV\_GEMM\_C\_T}{transpose src3}
3131 for example, \texttt{CV\_GEMM\_A\_T+CV\_GEMM\_C\_T} corresponds to
3133 \texttt{alpha} \, \texttt{src1} ^T \, \texttt{src2} + \texttt{beta} \, \texttt{src3} ^T
3137 The function \texttt{cvGEMM} performs generalized matrix multiplication:
3140 \texttt{dst} = \texttt{alpha} \, op(\texttt{src1}) \, op(\texttt{src2}) + \texttt{beta} \, op(\texttt{src3}) \quad \text{where $op(X)$ is $X$ or $X^T$}
3143 All the matrices should have the same data type and the coordinated sizes. Real or complex floating-point matrices are supported
3145 \cvfunc{Transform}\label{Transform}
3147 Performs matrix transform of every array element
3151 void cvTransform( const CvArr* src, CvArr* dst, const CvMat* transmat, const CvMat* shiftvec=NULL );
3156 \cvarg{src}{The first source array}
3157 \cvarg{dst}{The destination array}
3158 \cvarg{transmat}{Transformation matrix}
3159 \cvarg{shiftvec}{Optional shift vector}
3162 The function \texttt{cvTransform} performs matrix transformation of every element of array \texttt{src} and stores the results in \texttt{dst}:
3165 dst(I) = transmat \cdot src(I) + shiftvec % or dst(I),,k,,=sum,,j,,(transmat(k,j)*src(I),,j,,) + shiftvec(k)
3168 That is every element of \texttt{N}-channel array \texttt{src} is
3169 considered as \texttt{N}-element vector, which is transformed using
3170 matrix $\texttt{M} \times \texttt{N}$ matrix \texttt{transmat} and shift
3171 vector \texttt{shiftvec} into an element of \texttt{M}-channel array
3172 \texttt{dst}. There is an option to embedd \texttt{shiftvec} into
3173 \texttt{transmat}. In this case \texttt{transmat} should be $\texttt{M}
3174 \times (N+1)$ matrix and the right-most column is treated as the shift
3177 Both source and destination arrays should have the same depth and the
3178 same size or selected ROI size. \texttt{transmat} and \texttt{shiftvec}
3179 should be real floating-point matrices.
3181 The function may be used for geometrical transformation of n dimensional
3182 point set, arbitrary linear color space transformation, shuffling the
3185 \cvfunc{PerspectiveTransform}\label{PerspectiveTransform}
3187 Performs perspective matrix transform of vector array
3191 void cvPerspectiveTransform( const CvArr* src, CvArr* dst, const CvMat* mat );
3196 \cvarg{src}{The source three-channel floating-point array}
3197 \cvarg{dst}{The destination three-channel floating-point array}
3198 \cvarg{mat}{$3\times 3$ or $4 \times 4$ transformation matrix}
3202 The function \texttt{PerspectiveTransform} transforms every element of \texttt{src} (by treating it as 2D or 3D vector) in the following way:
3204 \[ (x, y, z) \rightarrow (x'/w, y'/w, z'/w) \]
3209 (x', y', z', w') = \texttt{mat} \cdot
3210 \begin{bmatrix} x & y & z & 1 \end{bmatrix}
3214 \[ w = \fork{w'}{if $w' \ne 0$}{\infty}{otherwise} \]
3216 \cvfunc{MulTransposed}\label{MulTransposed}
3218 Calculates product of array and transposed array
3222 void cvMulTransposed( const CvArr* src, CvArr* dst, int order, const CvArr* delta=NULL, double scale=1.0 );
3227 \cvarg{src}{The source matrix}
3228 \cvarg{dst}{The destination matrix. Must be \texttt{CV\_32F} or \texttt{CV\_64F}.}
3229 \cvarg{order}{Order of multipliers}
3230 \cvarg{delta}{An optional array, subtracted from \texttt{src} before multiplication}
3231 \cvarg{scale}{An optional scaling}
3234 The function \texttt{MulTransposed} calculates the product of src and its transposition.
3236 The function evaluates
3239 \texttt{dst}=\texttt{scale} (\texttt{src}-\texttt{delta}) (\texttt{src}-\texttt{delta})^T
3242 if $\texttt{order}=0$, and
3245 \texttt{dst}=\texttt{scale} (\texttt{src}-\texttt{delta})^T (\texttt{src}-\texttt{delta})
3250 \cvfunc{Trace}\label{Trace}
3252 Returns trace of matrix
3256 CvScalar cvTrace( const CvArr* mat );
3261 \cvarg{mat}{The source matrix}
3265 The function \texttt{cvTrace} returns sum of diagonal elements of the matrix \texttt{src1}.
3267 \[ tr(\texttt{mat}) = \sum_i \texttt{mat}(i,i) \]
3269 \cvfunc{Transpose}\label{Transpose}
3275 void cvTranspose( const CvArr* src, CvArr* dst );
3280 #define cvT cvTranspose
3284 \cvarg{src}{The source matrix}
3285 \cvarg{dst}{The destination matrix}
3288 The function \texttt{cvTranspose} transposes matrix \texttt{src1}:
3290 \[ \texttt{dst}(i,j) = \texttt{src}(j,i) \]
3292 Note that no complex conjugation is done in case of complex
3293 matrix. Conjugation should be done separately: look at the sample code
3294 in \cross{XorS} for example
3296 \cvfunc{Det}\label{Det}
3298 Returns determinant of matrix
3302 double cvDet( const CvArr* mat );
3307 \cvarg{mat}{The source matrix}
3310 The function \texttt{cvDet} returns determinant of the square matrix \texttt{mat}. The direct method is used for small matrices and Gaussian elimination is used for larger matrices. For symmetric positive-determined matrices it is also possible to run
3312 with $U = V = 0$ and then calculate determinant as a product of the diagonal elements of $W$.
3314 \cvfunc{Invert}\label{Invert}
3316 Finds inverse or pseudo-inverse of matrix
3320 double cvInvert( const CvArr* src, CvArr* dst, int method=CV\_LU );
3324 #define cvInv cvInvert
3328 \cvarg{src}{The source matrix}
3329 \cvarg{dst}{The destination matrix}
3330 \cvarg{method}{Inversion method
3332 \cvarg{CV\_LU}{Gaussian elimination with optimal pivot element chose}
3333 \cvarg{CV\_SVD}{Singular value decomposition (SVD) method}
3334 \cvarg{CV\_SVD\_SYM}{SVD method for a symmetric positively-defined matrix}
3338 The function \texttt{cvInvert} inverts matrix \texttt{src1} and stores the result in \texttt{src2}
3340 In case of \texttt{LU} method the function returns \texttt{src1} determinant (src1 must be square). If it is 0, the matrix is not inverted and \texttt{src2} is filled with zeros.
3342 In case of \texttt{SVD} methods the function returns the inversed condition number of \texttt{src1} (ratio of the smallest singular value to the largest singular value) and 0 if \texttt{src1} is all zeros. The SVD methods calculate a pseudo-inverse matrix if \texttt{src1} is singular
3345 \cvfunc{Solve}\label{Solve}
3347 Solves linear system or least-squares problem
3351 int cvSolve( const CvArr* src1, const CvArr* src2, CvArr* dst, int method=CV\_LU );
3356 \cvarg{A}{The source matrix}
3357 \cvarg{B}{The right-hand part of the linear system}
3358 \cvarg{X}{The output solution}
3359 \cvarg{method}{The solution (matrix inversion) method
3361 \cvarg{CV\_LU}{Gaussian elimination with optimal pivot element chose}
3362 \cvarg{CV\_SVD}{Singular value decomposition (SVD) method}
3363 \cvarg{CV\_SVD\_SYM}{SVD method for a symmetric positively-defined matrix.}
3367 The function \texttt{cvSolve} solves linear system or least-squares problem (the latter is possible with SVD methods):
3370 \texttt{dst} = argmin_X||\texttt{src1} \, \texttt{X} - \texttt{src2}||
3373 If \texttt{CV\_LU} method is used, the function returns 1 if \texttt{src1} is non-singular and 0 otherwise, in the latter case \texttt{dst} is not valid
3375 \cvfunc{SVD}\label{SVD}
3377 Performs singular value decomposition of real floating-point matrix
3381 void cvSVD( \par CvArr* A, \par CvArr* W, \par CvArr* U=NULL, \par CvArr* V=NULL, \par int flags=0 );
3386 \cvarg{A}{Source $\texttt{M} \times \texttt{N}$ matrix}
3387 \cvarg{W}{Resulting singular value matrix ($\texttt{M} \times \texttt{N}$ or $\texttt{N} \times \texttt{N}$) or vector ($\texttt{N} \times 1$)}
3388 \cvarg{U}{Optional left orthogonal matrix ($\texttt{M} \times \texttt{M}$ or $\texttt{M} \times \texttt{N}$)
3389 If \texttt{CV\_SVD\_U\_T} is specified, the number of rows and columns in the sentence above should be swapped.}
3390 \cvarg{V}{Optional right orthogonal matrix ($\texttt{N} \times \texttt{N}$)}
3391 \cvarg{flags}{Operation flags; can be 0 or combination of the following values:
3393 \cvarg{CV\_SVD\_MODIFY\_A}{enables modification of matrix \texttt{src1} during the operation. It speeds up the processing.}
3394 \cvarg{CV\_SVD\_U\_T}{means that the tranposed matrix \texttt{U} is returned. Specifying the flag speeds up the processing.}
3395 \cvarg{CV\_SVD\_V\_T}{means that the tranposed matrix \texttt{V} is returned. Specifying the flag speeds up the processing.}
3399 The function \texttt{cvSVD} decomposes matrix \texttt{A} into a product of a diagonal matrix and two orthogonal matrices:
3405 Where $W$ is diagonal matrix of singular values that can be coded as a
3406 1D vector of singular values and $U$ and $V$. All the singular values
3407 are non-negative and sorted (together with $U$ and and $V$ columns)
3408 in descenting order.
3410 SVD algorithm is numerically robust and its typical applications include:
3413 \item accurate eigenvalue problem solution when matrix \texttt{A}
3414 is square, symmetric and positively defined matrix, for example, when
3415 it is a covariation matrix. $W$ in this case will be a vector
3416 of eigen values, and $U = V$
3417 (thus, only one of $U$ or $V$ needs to be calculated if
3418 the eigen vectors are required)
3419 \item accurate solution of poor-conditioned linear systems
3420 \item least-squares solution of overdetermined linear systems. This and previous is done by \cross{Solve} function with \texttt{CV\_SVD} method
3421 \item accurate calculation of different matrix characteristics such as rank (number of non-zero singular values), condition number (ratio of the largest singular value to the smallest one), determinant (absolute value of determinant is equal to the product of singular values). All the things listed in this item do not require calculation of $U$ and $V$ matrices.
3424 \cvfunc{SVBkSb}\label{SVBkSb}
3426 Performs singular value back substitution
3430 void cvSVBkSb( \par const CvArr* W,\par const CvArr* U,\par const CvArr* V,\par const CvArr* B,\par CvArr* X,\par int flags );
3435 \cvarg{W}{Matrix or vector of singular values}
3436 \cvarg{U}{Left orthogonal matrix (tranposed, perhaps)}
3437 \cvarg{V}{Right orthogonal matrix (tranposed, perhaps)}
3438 \cvarg{B}{The matrix to multiply the pseudo-inverse of the original matrix \texttt{A} by. This is the optional parameter. If it is omitted then it is assumed to be an identity matrix of an appropriate size (So \texttt{X} will be the reconstructed pseudo-inverse of \texttt{A}).}
3439 \cvarg{X}{The destination matrix: result of back substitution.}
3440 \cvarg{flags}{Operation flags, should match exactly to the \texttt{flags} passed to \cross{SVD}}
3443 The function \texttt{cvSVBkSb} calculates back substitution for decomposed matrix \texttt{A} (see \cross{SVD} description) and matrix \texttt{B}:
3446 \texttt{X} = \texttt{V} \texttt{W}^{-1} \texttt{U}^T \texttt{B}
3454 {1/W_{(i,i)}}{if $W_{(i,i)} > \epsilon \sum_i{W_{(i,i)}}$ }
3458 And $\epsilon$ is a small number that depends on the matrix data type.
3460 This function together with \cross{SVD} is used inside \cross{Invert}
3461 and \cross{Solve}, and the possible reason to use these (svd and bksb)
3462 "low-level" function is to avoid temporary matrices allocation inside
3463 the high-level counterparts (inv and solve).
3465 \cvfunc{EigenVV}\label{EigenVV}
3467 Computes eigenvalues and eigenvectors of symmetric matrix
3471 void cvEigenVV( \par CvArr* mat,\par CvArr* evects,\par CvArr* evals,\par double eps=0 );
3476 \cvarg{mat}{The input symmetric square matrix. It is modified during the processing.}
3477 \cvarg{evects}{The output matrix of eigenvectors, stored as a subsequent rows}
3478 \cvarg{evals}{The output vector of eigenvalues, stored in the descenting order (order of eigenvalues and eigenvectors is syncronized, of course)}
3479 \cvarg{eps}{Accuracy of diagonalization. Typically, \texttt{DBL\_EPSILON} (about $ 10^{-15} $) works well}
3483 The function \texttt{cvEigenVV} computes the eigenvalues and eigenvectors of the matrix \texttt{A}:
3486 mat*evects(i,:)' = evals(i)*evects(i,:)' (in MATLAB notation)
3489 The contents of matrix \texttt{A} is destroyed by the function.
3491 Currently the function is slower than \cross{SVD} yet less accurate,
3492 so if \texttt{A} is known to be positively-defined (for example, it
3493 is a covariation matrix), it is recommended to use \cross{SVD} to find
3494 eigenvalues and eigenvectors of \texttt{A}, especially if eigenvectors
3497 \cvfunc{CalcCovarMatrix}\label{CalcCovarMatrix}
3499 Calculates covariation matrix of the set of vectors
3503 void cvCalcCovarMatrix( \par const CvArr** vects,\par int count,\par CvArr* cov\_mat,\par CvArr* avg,\par int flags );
3508 \cvarg{vects}{The input vectors. They all must have the same type and the same size. The vectors do not have to be 1D, they can be 2D (e.g. images) etc.}
3509 \cvarg{count}{The number of input vectors}
3510 \cvarg{cov\_mat}{The output covariation matrix that should be floating-point and square}
3511 \cvarg{avg}{The input or output (depending on the flags) array - the mean (average) vector of the input vectors}
3512 \cvarg{flags}{The operation flags, a combination of the following values
3514 \cvarg{CV\_COVAR\_SCRAMBLED}{the output covaration matrix is calculated as:
3515 $ \texttt{scale} * [ \texttt{vects} [0]- \texttt{avg} ,\texttt{vects} [1]- \texttt{avg} ,...]^T \cdot [\texttt{vects} [0]-\texttt{avg} ,\texttt{vects} [1]-\texttt{avg} ,...] $,
3516 that is, the covariation matrix is
3517 $\texttt{count} \times \texttt{count}$.
3518 Such an unusual covariation matrix is used for fast PCA
3519 of a set of very large vectors (see, for example, EigenFaces technique
3520 for face recognition). Eigenvalues of this "scrambled" matrix will
3521 match to the eigenvalues of the true covariation matrix and the "true"
3522 eigenvectors can be easily calculated from the eigenvectors of the
3523 "scrambled" covariation matrix.
3525 \cvarg{CV\_COVAR\_NORMAL}{the output covaration matrix is calculated as:
3526 $ \texttt{scale} * [ \texttt{vects} [0]- \texttt{avg} ,\texttt{vects} [1]- \texttt{avg} ,...] \cdot [\texttt{vects} [0]-\texttt{avg} ,\texttt{vects} [1]-\texttt{avg} ,...]^T $,
3527 that is, \texttt{cov\_mat} will be a usual covariation matrix
3528 with the same linear size as the total number of elements in every
3529 input vector. One and only one of \texttt{CV\_COVAR\_SCRAMBLED} and
3530 \texttt{CV\_COVAR\_NORMAL} must be specified}
3531 \cvarg{CV\_COVAR\_USE\_AVG}{if the flag is specified, the function does not calculate \texttt{avg} from the input vectors, but, instead, uses the passed \texttt{avg} vector. This is useful if \texttt{avg} has been already calculated somehow, or if the covariation matrix is calculated by parts - in this case, \texttt{avg} is not a mean vector of the input sub-set of vectors, but rather the mean vector of the whole set.}
3532 \cvarg{CV\_COVAR\_SCALE}{if the flag is specified, the covariation matrix is scaled. In the "normal" mode \texttt{scale} is '1./count', in the "scrambled" mode \texttt{scale} is reciprocal of the total number of elements in every input vector. By default (if the flag is not specified) the covariation matrix is not scaled ('scale=1').}
3534 \cvarg{CV\_COVAR\_ROWS}{Means that all the input vectors are stored as rows of a single matrix, \texttt{vects[0]}. \texttt{count} is ignored in this case, and \texttt{avg} should be a single-row vector of an appropriate size.}
3535 \cvarg{CV\_COVAR\_COLS}{Means that all the input vectors are stored as columns of a single matrix, \texttt{vects[0]}. \texttt{count} is ignored in this case, and \texttt{avg} should be a single-column vector of an appropriate size.}
3540 The function \texttt{cvCalcCovarMatrix} calculates the covariation matrix
3541 and, optionally, mean vector of the set of input vectors. The function
3542 can be used for PCA, for comparing vectors using Mahalanobis distance etc.
3544 \cvfunc{Mahalonobis}\label{Mahalonobis}
3546 Calculates Mahalonobis distance between two vectors
3550 double cvMahalanobis( \par const CvArr* vec1,\par const CvArr* vec2,\par CvArr* mat );
3555 \cvarg{vec1}{The first 1D source vector}
3556 \cvarg{vec2}{The second 1D source vector}
3557 \cvarg{mat}{The inverse covariation matrix}
3561 The function \texttt{cvMahalonobis} calculates the weighted distance between two vectors and returns it:
3565 d(vec1,vec2)=sqrt( sum,,i,j,, {mat(i,j)*(vec1(i)-vec2(i))*(vec1(j)-vec2(j))} )
3569 The covariation matrix may be calculated using \cross{CalcCovarMatrix} function and further inverted using \cross{Invert} function (CV\_SVD method is the preffered one, because the matrix might be singular).
3572 \subsection{Math Functions}
3574 \cvfunc{Round, Floor, Ceil}\label{Round, Floor, Ceil}
3576 Converts floating-point number to integer
3580 int cvRound( double value );
3581 int cvFloor( double value );
3582 int cvCeil( double value );
3587 \cvarg{value}{The input floating-point value}
3591 The functions \texttt{cvRound}, \texttt{cvFloor} and \texttt{cvCeil}
3592 convert input floating-point number to integer using one of the rounding
3593 modes. \texttt{cvRound} returns the nearest integer value to the
3594 argument. \texttt{cvFloor} returns the maximum integer value that is not
3595 larger than the argument. \texttt{cvCeil} returns the minimum integer
3596 value that is not smaller than the argument. On some architectures the
3597 functions work much faster than the standard cast
3598 operations in C. If absolute value of the argument is greater than
3599 $2^{31}$, the result is not determined. Special values ( $ \pm \infty$ , NaN)
3602 \cvfunc{Sqrt}\label{Sqrt}
3604 Calculates square root
3608 float cvSqrt( float value );
3613 \cvarg{value}{The input floating-point value}
3617 The function \texttt{cvSqrt} calculates square root of the argument. If the argument is negative, the result is not determined.
3619 \cvfunc{InvSqrt}\label{InvSqrt}
3621 Calculates inverse square root
3625 float cvInvSqrt( float value );
3630 \cvarg{value}{The input floating-point value}
3634 The function \texttt{cvInvSqrt} calculates inverse square root of the argument, and normally it is faster than \texttt{1./sqrt(value)}. If the argument is zero or negative, the result is not determined. Special values ( $ \pm \infty $ , NaN) are not handled.
3636 \cvfunc{Cbrt}\label{Cbrt}
3638 Calculates cubic root
3642 float cvCbrt( float value );
3647 \cvarg{value}{The input floating-point value}
3651 The function \texttt{cvCbrt} calculates cubic root of the argument, and normally it is faster than 'pow(value,1./3)'. Besides, negative arguments are handled properly. Special values ( $ \pm \infty $, NaN) are not handled.
3653 \cvfunc{FastArctan}\label{FastArctan}
3655 Calculates angle of 2D vector
3659 float cvFastArctan( float y, float x );
3664 \cvarg{x}{x-coordinate of 2D vector}
3665 \cvarg{y}{y-coordinate of 2D vector}
3669 The function \texttt{cvFastArctan} calculates full-range angle of input 2D vector. The angle is measured in degrees and varies from 0 degree to 360 degree . The accuracy is about 0.1 degree
3671 \cvfunc{IsNaN}\label{IsNaN}
3673 Determines if the argument is Not A Number
3677 int cvIsNaN( double value );
3682 \cvarg{value}{The input floating-point value}
3686 The function \texttt{cvIsNaN} returns 1 if the argument is Not A Number (as defined by IEEE754 standard), 0 otherwise.
3689 \cvfunc{IsInf}\label{IsInf}
3691 Determines if the argument is Infinity
3695 int cvIsInf( double value );
3700 \cvarg{value}{The input floating-point value}
3704 The function \texttt{cvIsInf} returns 1 if the argument is $ \pm \infty $ (as defined by IEEE754 standard), 0 otherwise.
3707 \cvfunc{CartToPolar}\label{CartToPolar}
3709 Calculates magnitude and/or angle of 2d vectors
3713 void cvCartToPolar( \par const CvArr* x,\par const CvArr* y,\par CvArr* magnitude,\par CvArr* angle=NULL,\par int angle\_in\_degrees=0 );
3718 \cvarg{x}{The array of x-coordinates}
3719 \cvarg{y}{The array of y-coordinates}
3720 \cvarg{magnitude}{The destination array of magnitudes, may be set to NULL if it is not needed}
3721 \cvarg{angle}{The destination array of angles, may be set to NULL if it is not needed. The angles are measured in radians $(0..2 \pi )$ or in degrees (0..360 degree).}
3722 \cvarg{angle\_in\_degrees}{The flag indicating whether the angles are measured in radians, which is default mode, or in degrees}
3725 The function \texttt{cvCartToPolar} calculates either magnitude, angle, or both of every 2d vector (x(I),y(I)):
3729 magnitude(I)=sqrt( x(I)^2^+y(I)^2^ ),
3730 angle(I)=atan( y(I)/x(I) )
3734 The angles are calculated with 0.1 degree accuracy. For (0,0) point the angle is set to 0.
3736 \cvfunc{PolarToCart}\label{PolarToCart}
3738 Calculates cartesian coordinates of 2d vectors represented in polar form
3742 void cvPolarToCart( \par const CvArr* magnitude,\par const CvArr* angle,\par CvArr* x,\par CvArr* y,\par int angle\_in\_degrees=0 );
3747 \cvarg{magnitude}{The array of magnitudes. If it is NULL, the magnitudes are assumed all 1's.}
3748 \cvarg{angle}{The array of angles, whether in radians or degrees}
3749 \cvarg{x}{The destination array of x-coordinates, may be set to NULL if it is not needed}
3750 \cvarg{y}{The destination array of y-coordinates, mau be set to NULL if it is not needed}
3751 \cvarg{angle\_in\_degrees}{The flag indicating whether the angles are measured in radians, which is default mode, or in degrees}
3754 The function \texttt{cvPolarToCart} calculates either x-coodinate, y-coordinate or both of every vector 'magnitude(I)*exp(angle(I)*j), j=sqrt(-1)':
3758 x(I)=magnitude(I)*cos(angle(I)),
3759 y(I)=magnitude(I)*sin(angle(I))
3764 \cvfunc{Pow}\label{Pow}
3766 Raises every array element to power
3770 void cvPow( \par const CvArr* src,\par CvArr* dst,\par double power );
3775 \cvarg{src}{The source array}
3776 \cvarg{dst}{The destination array, should be the same type as the source}
3777 \cvarg{power}{The exponent of power}
3781 The function \texttt{cvPow} raises every element of input array to \texttt{p}:
3784 \texttt{dst} [I] = \fork
3785 {\texttt{src}(I)^p}{if \texttt{p} is integer}
3786 {|\texttt{src}(I)^p|}{otherwise}
3789 That is, for non-integer power exponent the absolute values of input array elements are used. However, it is possible to get true values for negative values using some extra operations, as the following sample, computing cube root of array elements, shows:
3793 CvSize size = cvGetSize(src);
3794 CvMat* mask = cvCreateMat( size.height, size.width, CVg8UC1 );
3795 cvCmpS( src, 0, mask, CVgCMPgLT ); /* find negative elements */
3796 cvPow( src, dst, 1./3 );
3797 cvSubRS( dst, cvScalarAll(0), dst, mask ); /* negate the results of negative inputs */
3798 cvReleaseMat( &mask );
3802 For some values of \texttt{power}, such as integer values, 0.5 and -0.5, specialized faster algorithms are used.
3804 \cvfunc{Exp}\label{Exp}
3806 Calculates exponent of every array element
3810 void cvExp( const CvArr* src, CvArr* dst );
3815 \cvarg{src}{The source array}
3816 \cvarg{dst}{The destination array, it should have \texttt{double} type or the same type as the source}
3820 The function \texttt{cvExp} calculates exponent of every element of input array:
3823 \texttt{dst} [I] = e^{\texttt{src}(I)}
3826 Maximum relative error is about $7 \times 10^{-6}$. Currently, the function converts denormalized values to zeros on output.
3828 \cvfunc{Log}\label{Log}
3830 Calculates natural logarithm of every array element absolute value
3834 void cvLog( const CvArr* src, CvArr* dst );
3839 \cvarg{src}{The source array}
3840 \cvarg{dst}{The destination array, it should have \texttt{double} type or the same type as the source}
3843 The function \texttt{cvLog} calculates natural logarithm of absolute value of every element of input array:
3846 \texttt{dst} [I] = \fork
3847 {\log{|\texttt{src}(I)}}{if $\texttt{src}[I] \ne 0$ }
3848 {\texttt{C}}{otherwise}
3851 Where \texttt{C} is large negative number ( about -700 in the current implementation).
3853 \cvfunc{SolveCubic}\label{SolveCubic}
3855 Finds real roots of a cubic equation
3859 void cvSolveCubic( const CvArr* coeffs, CvArr* roots );
3864 \cvarg{coeffs}{The equation coefficients, array of 3 or 4 elements}
3865 \cvarg{roots}{The output array of real roots. Should have 3 elements.}
3868 The function \texttt{cvSolveCubic} finds real roots of a cubic equation:
3870 if coeffs is 4-element vector:
3873 \texttt{coeffs}[0] x^3 + \texttt{coeffs}[1] x^2 + \texttt{coeffs}[2] x + \texttt{coeffs}[3] = 0
3876 or if coeffs is 3-element vector:
3879 x^3 + \texttt{coeffs}[0] x^2 + \texttt{coeffs}[1] x + \texttt{coeffs}[2] = 0
3882 The function returns the number of real roots found. The roots are
3883 stored to \texttt{root} array, which is padded with zeros if there is
3886 \subsection{Random Number Generation}
3888 \cvfunc{RNG}\label{RNG}
3890 Initializes random number generator state
3894 CvRNG cvRNG( int64 seed=-1 );
3899 \cvarg{seed}{64-bit value used to initiate a random sequence}
3903 The function \texttt{cvRNG} initializes random number generator
3904 and returns the state. Pointer to the state can be then passed to
3905 \cross{RandInt}, \cross{RandReal} and \cross{RandArr} functions. In the
3906 current implementation a multiply-with-carry generator is used.
3908 \cvfunc{RandArr}\label{RandArr}
3910 Fills array with random numbers and updates the RNG state
3914 void cvRandArr( \par CvRNG* rng,\par CvArr* arr,\par int dist\_type,\par CvScalar param1,\par CvScalar param2 );
3919 \cvarg{rng}{RNG state initialized by \cross{RNG}}
3920 \cvarg{arr}{The destination array}
3921 \cvarg{dist\_type}{Distribution type
3923 \cvarg{CV\_RAND\_UNI}{uniform distribution}
3924 \cvarg{CV\_RAND\_NORMAL}{normal or Gaussian distribution}
3926 \cvarg{param1}{The first parameter of distribution . In case of uniform distribution it is the inclusive lower boundary of random numbers range. In case of normal distribution it is the mean value of random numbers.}
3927 \cvarg{param2}{The second parameter of distribution. In case of uniform distribution it is the exclusive upper boundary of random numbers range. In case of normal distribution it is the standard deviation of random numbers.}
3930 The function \texttt{cvRandArr} fills the destination array with uniformly
3931 or normally distributed random numbers. In the sample below the function
3932 is used to add a few normally distributed floating-point numbers to
3933 random locations within a 2d array
3937 /* let noisy\_screen be the floating-point 2d array that is to be "crapped" */
3938 CvRNG rng\_state = cvRNG(0xffffffff);
3939 int i, pointCount = 1000;
3940 /* allocate the array of coordinates of points */
3941 CvMat* locations = cvCreateMat( pointCount, 1, CV\_32SC2 );
3942 /* arr of random point values */
3943 CvMat* values = cvCreateMat( pointCount, 1, CV\_32FC1 );
3944 CvSize size = cvGetSize( noisy\_screen );
3946 cvRandInit( &rng\_state,
3947 0, 1, /* use dummy parameters now and adjust them further */
3948 0xffffffff /* just use a fixed seed here */,
3949 CV\_RAND\_UNI /* specify uniform type */ );
3951 /* initialize the locations */
3952 cvRandArr( &rng\_state, locations, CV\_RAND\_UNI, cvScalar(0,0,0,0), cvScalar(size.width,size.height,0,0) );
3954 /* modify RNG to make it produce normally distributed values */
3955 rng\_state.disttype = CV\_RAND\_NORMAL;
3956 cvRandSetRange( &rng\_state,
3958 100 /* average point brightness */,
3959 -1 /* initialize all the dimensions */ );
3960 /* generate values */
3961 cvRandArr( &rng\_state, values, CV\_RAND\_NORMAL,
3962 cvRealScalar(100), // average intensity
3963 cvRealScalar(30) // deviation of the intensity
3966 /* set the points */
3967 for( i = 0; i < pointCount; i++ )
3969 CvPoint pt = *(CvPoint*)cvPtr1D( locations, i, 0 );
3970 float value = *(float*)cvPtr1D( values, i, 0 );
3971 *((float*)cvPtr2D( noisy\_screen, pt.y, pt.x, 0 )) += value;
3974 /* not to forget to release the temporary arrays */
3975 cvReleaseMat( &locations );
3976 cvReleaseMat( &values );
3978 /* RNG state does not need to be deallocated */
3982 \cvfunc{RandInt}\label{RandInt}
3984 Returns 32-bit unsigned integer and updates RNG
3988 unsigned cvRandInt( CvRNG* rng );
3993 \cvarg{rng}{RNG state initialized by \texttt{RandInit} and, optionally, customized by \texttt{RandSetRange} (though, the latter function does not affect on the discussed function outcome)}
3996 The function \texttt{cvRandInt} returns uniformly-distributed random
3997 32-bit unsigned integer and updates RNG state. It is similar to rand()
3998 function from C runtime library, but it always generates 32-bit number
3999 whereas rand() returns a number in between 0 and \texttt{RAND\_MAX}
4000 which is $2^{16}$ or $2^{32}$, depending on the platform.
4002 The function is useful for generating scalar random numbers, such as
4003 points, patch sizes, table indices etc, where integer numbers of a certain
4004 range can be generated using modulo operation and floating-point numbers
4005 can be generated by scaling to 0..1 of any other specific range. Here
4006 is the example from the previous function discussion rewritten using
4011 /* the input and the task is the same as in the previous sample. */
4012 CvRNG rnggstate = cvRNG(0xffffffff);
4013 int i, pointCount = 1000;
4014 /* ... - no arrays are allocated here */
4015 CvSize size = cvGetSize( noisygscreen );
4016 /* make a buffer for normally distributed numbers to reduce call overhead */
4017 #define bufferSize 16
4018 float normalValueBuffer[bufferSize];
4019 CvMat normalValueMat = cvMat( bufferSize, 1, CVg32F, normalValueBuffer );
4022 for( i = 0; i < pointCount; i++ )
4025 /* generate random point */
4026 pt.x = cvRandInt( &rnggstate ) % size.width;
4027 pt.y = cvRandInt( &rnggstate ) % size.height;
4029 if( valuesLeft <= 0 )
4031 /* fulfill the buffer with normally distributed numbers if the buffer is empty */
4032 cvRandArr( &rnggstate, &normalValueMat, CV\_RAND\_NORMAL, cvRealScalar(100), cvRealScalar(30) );
4033 valuesLeft = bufferSize;
4035 *((float*)cvPtr2D( noisygscreen, pt.y, pt.x, 0 ) = normalValueBuffer[--valuesLeft];
4038 /* there is no need to deallocate normalValueMat because we have
4039 both the matrix header and the data on stack. It is a common and efficient
4040 practice of working with small, fixed-size matrices */
4044 \cvfunc{RandReal}\label{RandReal}
4046 Returns floating-point random number and updates RNG
4050 double cvRandReal( CvRNG* rng );
4055 \cvarg{rng}{RNG state initialized by \cross{RNG}}
4059 The function \texttt{cvRandReal} returns uniformly-distributed random floating-point number from 0..1 range (1 is not included).
4061 \subsection{Discrete Transforms}
4063 \cvfunc{DFT}\label{DFT}
4065 Performs forward or inverse Discrete Fourier transform of 1D or 2D floating-point array
4069 void cvDFT( const CvArr* src, CvArr* dst, int flags, int nonzero\_rows=0 );
4075 #define CV\_DXT\_FORWARD 0
4076 #define CV\_DXT\_INVERSE 1
4077 #define CV\_DXT\_SCALE 2
4078 #define CV\_DXT\_ROWS 4
4079 #define CV\_DXT\_INV\_SCALE (CV\_DXT\_SCALE|CV\_DXT\_INVERSE)
4080 #define CV\_DXT\_INVERSE\_SCALE CV\_DXT\_INV\_SCALE
4085 \cvarg{src}{Source array, real or complex}
4086 \cvarg{dst}{Destination array of the same size and same type as the source}
4087 \cvarg{flags}{Transformation flags, a combination of the following values
4089 \cvarg{CV\_DXT\_FORWARD} - do forward 1D or 2D transform. The result is not scaled.
4090 \cvarg{CV\_DXT\_INVERSE} - do inverse 1D or 2D transform. The result is not scaled. \texttt{CV\_DXT\_FORWARD} and \texttt{CV\_DXT\_INVERSE} are mutually exclusive, of course.
4091 \cvarg{CV\_DXT\_SCALE} - scale the result: divide it by the number of array elements. Usually, it is combined with \texttt{CV\_DXT\_INVERSE}, and one may use a shortcut \texttt{CV\_DXT\_INV\_SCALE}.
4092 \cvarg{CV\_DXT\_ROWS} - do forward or inverse transform of every individual row of the input matrix. This flag allows user to transform multiple vectors simultaneously and can be used to decrease the overhead (which is sometimes several times larger than the processing itself), to do 3D and higher-dimensional transforms etc.
4094 \cvarg{nonzero\_rows}{Number of nonzero rows to in the source array
4095 (in case of forward 2d transform), or a number of rows of interest in
4096 the destination array (in case of inverse 2d transform). If the value
4097 is negative, zero, or greater than the total number of rows, it is
4098 ignored. The parameter can be used to speed up 2d convolution/correlation
4099 when computing them via DFT. See the sample below.}
4102 The function \texttt{cvDFT} performs forward or inverse transform of 1D or 2D floating-point array:
4106 Forward Fourier transform of 1D vector of N elements:
4107 y = F^(N)^ \cdot x, where F^(N)^,,jk,,=exp(-i \cdot 2Pi \cdot j \cdot k/N), i=sqrt(-1)
4109 Inverse Fourier transform of 1D vector of N elements:
4110 x'= (F^(N)^)^-1^ \cdot y = conj(F^(N)^) \cdot y
4113 Forward Fourier transform of 2D vector of M \times N elements:
4114 Y = F^(M)^ \cdot X \cdot F^(N)^
4116 Inverse Fourier transform of 2D vector of M \times N elements:
4117 X'= conj(F^(M)^) \cdot Y \cdot conj(F^(N)^)
4118 X = (1/(M \cdot N)) \cdot X'
4122 In case of real (single-channel) data, the packed format, borrowed from IPL, is used to to represent a result of forward Fourier transform or input for inverse Fourier transform:
4126 Re Y,,0,0,, Re Y,,0,1,, Im Y,,0,1,, Re Y,,0,2,, Im Y,,0,2,, ... Re Y,,0,N/2-1,, Im Y,,0,N/2-1,, Re Y,,0,N/2,,
4127 Re Y,,1,0,, Re Y,,1,1,, Im Y,,1,1,, Re Y,,1,2,, Im Y,,1,2,, ... Re Y,,1,N/2-1,, Im Y,,1,N/2-1,, Re Y,,1,N/2,,
4128 Im Y,,1,0,, Re Y,,2,1,, Im Y,,2,1,, Re Y,,2,2,, Im Y,,2,2,, ... Re Y,,2,N/2-1,, Im Y,,2,N/2-1,, Im Y,,2,N/2,,
4129 ............................................................................................
4130 Re Y,,M/2-1,0,, Re Y,,M-3,1,, Im Y,,M-3,1,, Re Y,,M-3,2,, Im Y,,M-3,2,, ... Re Y,,M-3,N/2-1,, Im Y,,M-3,N/2-1,, Re Y,,M-3,N/2,,
4131 Im Y,,M/2-1,0,, Re Y,,M-2,1,, Im Y,,M-2,1,, Re Y,,M-2,2,, Im Y,,M-2,2,, ... Re Y,,M-2,N/2-1,, Im Y,,M-2,N/2-1,, Im Y,,M-2,N/2,,
4132 Re Y,,M/2,0,, Re Y,,M-1,1,, Im Y,,M-1,1,, Re Y,,M-1,2,, Im Y,,M-1,2,, ... Re Y,,M-1,N/2-1,, Im Y,,M-1,N/2-1,, Im Y,,M-1,N/2,,
4136 Note: the last column is present if \texttt{N} is even, the last row is present if \texttt{M} is even.
4138 In case of 1D real transform the result looks like the first row of the above matrix
4140 Computing 2D Convolution using DFT
4144 CvMat* A = cvCreateMat( M1, N1, CVg32F );
4145 CvMat* B = cvCreateMat( M2, N2, A->type );
4147 // it is also possible to have only abs(M2-M1)+1 \times abs(N2-N1)+1
4148 // part of the full convolution result
4149 CvMat* conv = cvCreateMat( A->rows + B->rows - 1, A->cols + B->cols - 1, A->type );
4151 // initialize A and B
4154 int dftgM = cvGetOptimalDFTSize( A->rows + B->rows - 1 );
4155 int dftgN = cvGetOptimalDFTSize( A->cols + B->cols - 1 );
4157 CvMat* dftgA = cvCreateMat( dft\_M, dft\_N, A->type );
4158 CvMat* dftgB = cvCreateMat( dft\_M, dft\_N, B->type );
4161 // copy A to dftgA and pad dft\_A with zeros
4162 cvGetSubRect( dftgA, &tmp, cvRect(0,0,A->cols,A->rows));
4164 cvGetSubRect( dftgA, &tmp, cvRect(A->cols,0,dft\_A->cols - A->cols,A->rows));
4166 // no need to pad bottom part of dftgA with zeros because of
4167 // use nonzerogrows parameter in cvDFT() call below
4169 cvDFT( dftgA, dft\_A, CV\_DXT\_FORWARD, A->rows );
4171 // repeat the same with the second array
4172 cvGetSubRect( dftgB, &tmp, cvRect(0,0,B->cols,B->rows));
4174 cvGetSubRect( dftgB, &tmp, cvRect(B->cols,0,dft\_B->cols - B->cols,B->rows));
4176 // no need to pad bottom part of dftgB with zeros because of
4177 // use nonzerogrows parameter in cvDFT() call below
4179 cvDFT( dftgB, dft\_B, CV\_DXT\_FORWARD, B->rows );
4181 cvMulSpectrums( dftgA, dft\_B, dft\_A, 0 /* or CV\_DXT\_MUL\_CONJ to get correlation
4182 rather than convolution */ );
4184 cvDFT( dftgA, dft\_A, CV\_DXT\_INV\_SCALE, conv->rows ); // calculate only the top part
4185 cvGetSubRect( dftgA, &tmp, cvRect(0,0,conv->cols,conv->rows) );
4187 cvCopy( &tmp, conv );
4191 \cvfunc{GetOptimalDFTSize}\label{GetOptimalDFTSize}
4193 Returns optimal DFT size for given vector size
4197 int cvGetOptimalDFTSize( int size0 );
4202 \cvarg{size0}{Vector size}
4206 The function \texttt{cvGetOptimalDFTSize} returns the minimum number
4207 \texttt{N} that is greater to equal to \texttt{size0}, such that DFT
4208 of a vector of size \texttt{N} can be computed fast. In the current
4209 implementation $N=2^p \times 3^q \times 5^r$' for some $p$, $q$, $r$.
4211 The function returns a negative number if \texttt{size0} is too large
4212 (very close to \texttt{INT\_MAX})
4215 \cvfunc{MulSpectrums}\label{MulSpectrums}
4217 Performs per-element multiplication of two Fourier spectrums
4221 void cvMulSpectrums( \par const CvArr* src1,\par const CvArr* src2,\par CvArr* dst,\par int flags );
4226 \cvarg{src1}{The first source array}
4227 \cvarg{src2}{The second source array}
4228 \cvarg{dst}{The destination array of the same type and the same size of the sources}
4229 \cvarg{flags}{A combination of the following values
4231 \cvarg{CV\_DXT\_ROWS}{treat each row of the arrays as a separate spectrum (see \cross{DFT} parameters description).}
4232 \cvarg{CV\_DXT\_MUL\_CONJ}{conjugate the second source array before the multiplication.}
4237 The function \texttt{cvMulSpectrums} performs per-element multiplication of the two CCS-packed or complex matrices that are results of real or complex Fourier transform.
4239 The function, together with \cross{DFT}, may be used to calculate convolution of two arrays fast.
4242 \cvfunc{DCT}\label{DCT}
4244 Performs forward or inverse Discrete Cosine transform of 1D or 2D floating-point array
4248 void cvDCT( const CvArr* src, CvArr* dst, int flags );
4254 #define CV\_DXT\_FORWARD 0
4255 #define CV\_DXT\_INVERSE 1
4256 #define CV\_DXT\_ROWS 4
4261 \cvarg{src}{Source array, real 1D or 2D array}
4262 \cvarg{dst}{Destination array of the same size and same type as the source}
4263 \cvarg{flags}{Transformation flags, a combination of the following values
4265 \cvarg{CV\_DXT\_FORWARD}{do forward 1D or 2D transform.}
4266 \cvarg{CV\_DXT\_INVERSE}{do inverse 1D or 2D transform.}
4267 \cvarg{CV\_DXT\_ROWS}{do forward or inverse transform of every individual row of the input matrix. This flag allows user to transform multiple vectors simultaneously and can be used to decrease the overhead (which is sometimes several times larger than the processing itself), to do 3D and higher-dimensional transforms etc.}
4271 The function \texttt{cvDCT} performs forward or inverse transform of 1D or 2D floating-point array:
4275 Forward Cosine transform of 1D vector of N elements:
4276 y = C^(N)^ \cdot x, where C^(N)^,,jk,,=sqrt((j==0?1:2)/N) \cdot cos(Pi \cdot (2k+1) \cdot j/N)
4278 Inverse Cosine transform of 1D vector of N elements:
4279 x = (C^(N)^)^-1^ \cdot y = (C^(N)^)^T^ \cdot y
4281 Forward Cosine transform of 2D vector of M \times N elements:
4282 Y = (C^(M)^) \cdot X \cdot (C^(N)^)^T^
4284 Inverse Cosine transform of 2D vector of M \times N elements:
4285 X = (C^(M)^)^T^ \cdot Y \cdot C^(N)^
4290 \section{Dynamic Structures}
4292 \subsection{Memory Storages}
4294 \cvstruct{CvMemStorage}\label{CvMemStorage}
4296 Growing memory storage
4300 typedef struct CvMemStorage
4302 struct CvMemBlock* bottom;/* first allocated block */
4303 struct CvMemBlock* top; /* the current memory block - top of the stack */
4304 struct CvMemStorage* parent; /* borrows new blocks from */
4305 int block\_size; /* block size */
4306 int free\_space; /* free space in the \texttt{top} block (in bytes) */
4311 Memory storage is a low-level structure used to store dynamically growing
4312 data structures such as sequences, contours, graphs, subdivisions etc. It
4313 is organized as a list of memory blocks of equal size - \texttt{bottom}
4314 field is the beginning of the list of blocks and \texttt{top} is the
4315 currently used block, but not necessarily the last block of the list. All
4316 blocks between \texttt{bottom} and \texttt{top}, not including the
4317 latter, are considered fully ocupied; and all blocks between \texttt{top}
4318 and the last block, not including \texttt{top}, are considered free
4319 and \texttt{top} block itself is partly ocupied - \texttt{free\_space}
4320 contains the number of free bytes left in the end of \texttt{top}.
4322 New memory buffer that may be allocated explicitly by
4323 \cross{MemStorageAlloc} function or implicitly by higher-level functions,
4324 such as \cross{SeqPush}, \cross{GraphAddEdge} etc., \texttt{always}
4325 starts in the end of the current block if it fits there. After allocation
4326 \texttt{free\_space} is decremented by the size of the allocated buffer
4327 plus some padding to keep the proper alignment. When the allocated buffer
4328 does not fit into the available part of \texttt{top}, the next storage
4329 block from the list is taken as \texttt{top} and \texttt{free\_space}
4330 is reset to the whole block size prior to the allocation.
4332 If there is no more free blocks, a new block is allocated (or borrowed
4333 from parent, see \cross{CreateChildMemStorage}) and added to the end of
4334 list. Thus, the storage behaves as a stack with \texttt{bottom} indicating
4335 bottom of the stack and the pair (\texttt{top}, \texttt{free\_space})
4336 indicating top of the stack. The stack top may be saved via
4337 \cross{SaveMemStoragePos}, restored via \cross{RestoreMemStoragePos}
4338 or reset via \cross{ClearStorage}.
4340 \cvstruct{CvMemBlock}\label{CvMemBlock}
4342 Memory storage block
4346 typedef struct CvMemBlock
4348 struct CvMemBlock* prev;
4349 struct CvMemBlock* next;
4354 The structure \cross{CvMemBlock} represents a single block of memory
4355 storage. Actual data of the memory blocks follows the header, that is,
4356 the $i_{th}$ byte of the memory block can be retrieved with the expression
4357 \texttt{((char*)(mem\_block\_ptr+1))[i]}. However, normally there is no need
4358 to access the storage structure fields directly.
4360 \cvstruct{CvMemStoragePos}\label{CvMemStoragePos}
4362 Memory storage position
4366 typedef struct CvMemStoragePos
4374 The structure described below stores the position of the stack top that can be saved via \cross{SaveMemStoragePos} and restored via \cross{RestoreMemStoragePos}.
4376 \cvfunc{CreateMemStorage}\label{CreateMemStorage}
4378 Creates memory storage
4382 CvMemStorage* cvCreateMemStorage( int block\_size=0 );
4387 \cvarg{block\_size}{Size of the storage blocks in bytes. If it is 0, the block size is set to default value - currently it is about 64K.}
4390 The function \texttt{cvCreateMemStorage} creates a memory storage and returns pointer to it. Initially the storage is empty. All fields of the header, except the \texttt{block\_size}, are set to 0.
4393 \cvfunc{CreateChildMemStorage}\label{CreateChildMemStorage}
4395 Creates child memory storage
4399 CvMemStorage* cvCreateChildMemStorage( CvMemStorage* parent );
4404 \cvarg{parent}{Parent memory storage}
4408 The function \texttt{cvCreateChildMemStorage} creates a child memory
4409 storage that is similar to simple memory storage except for the
4410 differences in the memory allocation/deallocation mechanism. When a
4411 child storage needs a new block to add to the block list, it tries
4412 to get this block from the parent. The first unoccupied parent block
4413 available is taken and excluded from the parent block list. If no blocks
4414 are available, the parent either allocates a block or borrows one from
4415 its own parent, if any. In other words, the chain, or a more complex
4416 structure, of memory storages where every storage is a child/parent of
4417 another is possible. When a child storage is released or even cleared,
4418 it returns all blocks to the parent. In other aspects, the child storage
4419 is the same as the simple storage.
4421 The children storages are useful in the following situation. Imagine
4422 that user needs to process dynamical data resided in some storage and
4423 put the result back to the same storage. With the simplest approach,
4424 when temporary data is resided in the same storage as the input and
4425 output data, the storage will look as following after processing:
4427 Dynamic data processing without using child storage
4429 \includegraphics[width=0.5\textwidth]{pics/memstorage1.png}
4431 That is, garbage appears in the middle of the storage. However, if
4432 one creates a child memory storage in the beginning of the processing,
4433 writes temporary data there and releases the child storage in the end,
4434 no garbage will appear in the source/destination storage:
4436 Dynamic data processing using a child storage
4438 \includegraphics[width=0.5\textwidth]{pics/memstorage2.png}
4440 \cvfunc{ReleaseMemStorage}\label{ReleaseMemStorage}
4442 Releases memory storage
4446 void cvReleaseMemStorage( CvMemStorage** storage );
4451 \cvarg{storage}{Pointer to the released storage}
4454 The function \texttt{cvReleaseMemStorage} deallocates all storage memory
4455 blocks or returns them to the parent, if any. Then it deallocates the
4456 storage header and clears the pointer to the storage. All children of
4457 the storage must be released before the parent is released.
4459 \cvfunc{ClearMemStorage}\label{ClearMemStorage}
4461 Clears memory storage
4465 void cvClearMemStorage( CvMemStorage* storage );
4470 \cvarg{storage}{Memory storage}
4473 The function \texttt{cvClearMemStorage} resets the top (free space
4474 boundary) of the storage to the very beginning. This function does not
4475 deallocate any memory. If the storage has a parent, the function returns
4476 all blocks to the parent.
4478 \cvfunc{MemStorageAlloc}\label{MemStorageAlloc}
4480 Allocates memory buffer in the storage
4484 void* cvMemStorageAlloc( \par CvMemStorage* storage,\par size\_t size );
4489 \cvarg{storage}{Memory storage}
4490 \cvarg{size}{Buffer size}
4493 The function \texttt{cvMemStorageAlloc} allocates memory buffer in
4494 the storage. The buffer size must not exceed the storage block size,
4495 otherwise runtime error is raised. The buffer address is aligned by
4496 \texttt{CV\_STRUCT\_ALIGN=sizeof(double)} for the moment) bytes.
4498 \cvfunc{MemStorageAllocString}\label{MemStorageAllocString}
4500 Allocates text string in the storage
4504 CvString cvMemStorageAllocString( CvMemStorage* storage, const char* ptr, int len=-1 );
4510 typedef struct CvString
4520 \cvarg{storage}{Memory storage}
4521 \cvarg{ptr}{The string}
4522 \cvarg{len}{Length of the string (not counting the ending \texttt{NUL}) . If the parameter is negative, the function computes the length.}
4525 The function \texttt{cvMemStorageAllocString} creates copy of the string
4526 in the memory storage. It returns the structure that contains user-passed
4527 or computed length of the string and pointer to the copied string.
4529 \cvfunc{SaveMemStoragePos}\label{SaveMemStoragePos}
4531 Saves memory storage position
4535 void cvSaveMemStoragePos( \par const CvMemStorage* storage,\par CvMemStoragePos* pos );
4540 \cvarg{storage}{Memory storage}
4541 \cvarg{pos}{The output position of the storage top}
4544 The function \texttt{cvSaveMemStoragePos} saves the current position
4545 of the storage top to the parameter \texttt{pos}. The function
4546 \texttt{cvRestoreMemStoragePos} can further retrieve this position.
4548 \cvfunc{RestoreMemStoragePos}\label{RestoreMemStoragePos}
4550 Restores memory storage position
4554 void cvRestoreMemStoragePos( \par CvMemStorage* storage,\par CvMemStoragePos* pos );
4559 \cvarg{storage}{Memory storage}
4560 \cvarg{pos}{New storage top position}
4563 The function \texttt{cvRestoreMemStoragePos} restores the position of the storage top from the parameter \texttt{pos}. This function and The function \texttt{cvClearMemStorage} are the only methods to release memory occupied in memory blocks. Note again that there is no way to free memory in the middle of the occupied part of the storage.
4565 \subsection{Sequences}
4567 \cvstruct{CvSeq}\label{CvSeq}
4569 Growable sequence of elements
4573 #define CVgSEQUENCE\_FIELDS() \
4574 int flags; /* micsellaneous flags */ \
4575 int headergsize; /* size of sequence header */ \
4576 struct CvSeq* hgprev; /* previous sequence */ \
4577 struct CvSeq* hgnext; /* next sequence */ \
4578 struct CvSeq* vgprev; /* 2nd previous sequence */ \
4579 struct CvSeq* vgnext; /* 2nd next sequence */ \
4580 int total; /* total number of elements */ \
4581 int elemgsize;/* size of sequence element in bytes */ \
4582 char* blockgmax;/* maximal bound of the last block */ \
4583 char* ptr; /* current write pointer */ \
4584 int deltagelems; /* how many elements allocated when the sequence grows (sequence granularity) */ \
4585 CvMemStorage* storage; /* where the seq is stored */ \
4586 CvSeqBlock* freegblocks; /* free blocks list */ \
4587 CvSeqBlock* first; /* pointer to the first sequence block */
4589 typedef struct CvSeq
4591 CVgSEQUENCE\_FIELDS()
4596 The structure \cross{CvSeq} is a base for all of OpenCV dynamic data structures.
4598 Such an unusual definition via a helper macro simplifies the extension
4599 of the structure \cross{CvSeq} with additional parameters. To extend
4600 \cross{CvSeq} the user may define a new structure and put user-defined
4601 fields after all \cross{CvSeq} fields that are included via the macro
4602 \texttt{CV\_SEQUENCE\_FIELDS()}.
4604 There are two types of sequences - dense and sparse. Base type for dense
4605 sequences is \cross{CvSeq} and such sequences are used to represent
4606 growable 1d arrays - vectors, stacks, queues, deques. They have no gaps
4607 in the middle - if an element is removed from the middle or inserted
4608 into the middle of the sequence the elements from the closer end are
4609 shifted. Sparse sequences have \cross{CvSet} base class and they are
4610 discussed later in more details. They are sequences of nodes each of
4611 those may be either occupied or free as indicated by the node flag. Such
4612 sequences are used for unordered data structures such as sets of elements,
4613 graphs, hash tables etc.
4615 The field \texttt{header\_size} contains the actual size of the sequence
4616 header and should be greater or equal to \texttt{sizeof(CvSeq)}.
4619 \texttt{h\_prev}, \texttt{h\_next}, \texttt{v\_prev}, \texttt{v\_next}
4620 can be used to create hierarchical structures from separate sequences. The
4621 fields \texttt{h\_prev} and \texttt{h\_next} point to the previous and
4622 the next sequences on the same hierarchical level while the fields
4623 \texttt{v\_prev} and \texttt{v\_next} point to the previous and the
4624 next sequence in the vertical direction, that is, parent and its first
4625 child. But these are just names and the pointers can be used in a
4628 The field \texttt{first} points to the first sequence block, whose structure is described below.
4630 The field \texttt{total} contains the actual number of dense sequence elements and number of allocated nodes in sparse sequence.
4632 The field \texttt{flags}contain the particular dynamic type
4633 signature (\texttt{CV\_SEQ\_MAGIC\_VAL} for dense sequences and
4634 \texttt{CV\_SET\_MAGIC\_VAL} for sparse sequences) in the highest 16
4635 bits and miscellaneous information about the sequence. The lowest
4636 \texttt{CV\_SEQ\_ELTYPE\_BITS} bits contain the ID of the element
4637 type. Most of sequence processing functions do not use element type but
4638 element size stored in \texttt{elem\_size}. If sequence contains the
4639 numeric data of one of \cross{CvMat} type then the element type matches
4640 to the corresponding \cross{CvMat} element type, e.g. \texttt{CV\_32SC2} may be
4641 used for sequence of 2D points, \texttt{CV\_32FC1} for sequences of floating-point
4642 values etc. \texttt{CV\_SEQ\_ELTYPE(seq\_header\_ptr)} macro retrieves the
4643 type of sequence elements. Processing function that work with numerical
4644 sequences check that \texttt{elem\_size} is equal to the calculated from
4645 the type element size. Besides \cross{CvMat} compatible types, there
4646 are few extra element types defined in \texttt{cvtypes.h} header:
4648 Standard Types of Sequence Elements
4652 #define CV_SEQ_ELTYPE_POINT CV_32SC2 /* (x,y) */
4653 #define CV_SEQ_ELTYPE_CODE CV_8UC1 /* freeman code: 0..7 */
4654 #define CV_SEQ_ELTYPE_GENERIC 0 /* unspecified type of sequence elements */
4655 #define CV_SEQ_ELTYPE_PTR CV_USRTYPE1 /* =6 */
4656 #define CV_SEQ_ELTYPE_PPOINT CV_SEQ_ELTYPE_PTR /* &elem: pointer to element of other sequence */
4657 #define CV_SEQ_ELTYPE_INDEX CV_32SC1 /* #elem: index of element of some other sequence */
4658 #define CV_SEQ_ELTYPE_GRAPH_EDGE CV_SEQ_ELTYPE_GENERIC /* &next_o, &next_d, &vtx_o, &vtx_d */
4659 #define CV_SEQ_ELTYPE_GRAPH_VERTEX CV_SEQ_ELTYPE_GENERIC /* first_edge, &(x,y) */
4660 #define CV_SEQ_ELTYPE_TRIAN_ATR CV_SEQ_ELTYPE_GENERIC /* vertex of the binary tree */
4661 #define CV_SEQ_ELTYPE_CONNECTED_COMP CV_SEQ_ELTYPE_GENERIC /* connected component */
4662 #define CV_SEQ_ELTYPE_POINT3D CV_32FC3 /* (x,y,z) */
4666 The next \texttt{CV\_SEQ\_KIND\_BITS} bits specify the kind of the sequence:
4668 Standard Kinds of Sequences
4672 /* generic (unspecified) kind of sequence */
4673 #define CV_SEQ_KIND_GENERIC (0 << CV_SEQ_ELTYPE_BITS)
4675 /* dense sequence suntypes */
4676 #define CV_SEQ_KIND_CURVE (1 << CV_SEQ_ELTYPE_BITS)
4677 #define CV_SEQ_KIND_BIN_TREE (2 << CV_SEQ_ELTYPE_BITS)
4679 /* sparse sequence (or set) subtypes */
4680 #define CV_SEQ_KIND_GRAPH (3 << CV_SEQ_ELTYPE_BITS)
4681 #define CV_SEQ_KIND_SUBDIV2D (4 << CV_SEQ_ELTYPE_BITS)
4685 The remaining bits are used to identify different features specific
4686 to certain sequence kinds and element types. For example, curves
4687 made of points ( \texttt{CV\_SEQ\_KIND\_CURVE|CV\_SEQ\_ELTYPE\_POINT} ),
4688 together with the flag \texttt{CV\_SEQ\_FLAG\_CLOSED} belong to the
4689 type \texttt{CV\_SEQ\_POLYGON} or, if other flags are used, to its
4690 subtype. Many contour processing functions check the type of the input
4691 sequence and report an error if they do not support this type. The
4692 file \texttt{cvtypes.h} stores the complete list of all supported
4693 predefined sequence types and helper macros designed to get the sequence
4694 type of other properties. Below follows the definition of the building
4697 \cvstruct{CvSeqBlock}\label{CvSeqBlock}
4699 Continuous sequence block
4703 typedef struct CvSeqBlock
4705 struct CvSeqBlock* prev; /* previous sequence block */
4706 struct CvSeqBlock* next; /* next sequence block */
4707 int start_index; /* index of the first element in the block +
4708 sequence->first->start_index */
4709 int count; /* number of elements in the block */
4710 char* data; /* pointer to the first element of the block */
4715 Sequence blocks make up a circular double-linked list, so the pointers
4716 \texttt{prev} and \texttt{next} are never \texttt{NULL} and point to the
4717 previous and the next sequence blocks within the sequence. It means that
4718 \texttt{next} of the last block is the first block and \texttt{prev} of
4719 the first block is the last block. The fields \texttt{start\_index} and
4720 \texttt{count} help to track the block location within the sequence. For
4721 example, if the sequence consists of 10 elements and splits into three
4722 blocks of 3, 5, and 2 elements, and the first block has the parameter
4723 \texttt{start\_index = 2}, then pairs \texttt{(start\_index, count)} for the sequence
4725 (2,3), (5, 5), and (10, 2)
4726 correspondingly. The parameter
4727 \texttt{start\_index} of the first block is usually \texttt{0} unless
4728 some elements have been inserted at the beginning of the sequence.
4730 \cvstruct{CvSlice}\label{CvSlice}
4736 typedef struct CvSlice
4742 inline CvSlice cvSlice( int start, int end );
4743 #define CV_WHOLE_SEQ_END_INDEX 0x3fffffff
4744 #define CV_WHOLE_SEQ cvSlice(0, CV_WHOLE_SEQ_END_INDEX)
4746 /* calculates the sequence slice length */
4747 int cvSliceLength( CvSlice slice, const CvSeq* seq );
4751 Some of functions that operate on sequences take \texttt{CvSlice slice}
4752 parameter that is often set to the whole sequence (CV\_WHOLE\_SEQ) by
4753 default. Either of the \texttt{start\_index} and \texttt{end\_index}
4754 may be negative or exceed the sequence length, \texttt{start\_index} is
4755 inclusive, \texttt{end\_index} is exclusive boundary. If they are equal,
4756 the slice is considered empty (i.e. contains no elements). Because
4757 sequences are treated as circular structures, the slice may select a
4758 few elements in the end of a sequence followed by a few elements in the
4759 beginning of the sequence, for example, \texttt{cvSlice(-2, 3)} in case of
4760 10-element sequence will select 5-element slice, containing pre-last
4761 (8th), last (9th), the very first (0th), second (1th) and third (2nd)
4762 elements. The functions normalize the slice argument in the following way:
4763 first, \cross{SliceLength} is called to determine the length of the slice,
4764 then, \texttt{start\_index} of the slice is normalized similarly to the
4765 argument of \cross{GetSeqElem} (i.e. negative indices are allowed). The
4766 actual slice to process starts at the normalized \texttt{start\_index}
4767 and lasts \cross{SliceLength} elements (again, assuming the sequence is
4768 a circular structure).
4770 If a function does not take slice argument, but you want to process
4771 only a part of the sequence, the sub-sequence may be extracted
4772 using \cross{SeqSlice} function, or stored as into a continuous
4773 buffer with \cross{CvtSeqToArray} (optionally, followed by
4774 \cross{MakeSeqHeaderForArray}.
4776 \cvfunc{CreateSeq}\label{CreateSeq}
4782 CvSeq* cvCreateSeq( \par int seq\_flags,\par int header\_size,\par int elem\_size,\par CvMemStorage* storage );
4787 \cvarg{seq\_flags}{Flags of the created sequence. If the sequence is not passed to any function working with a specific type of sequences, the sequence value may be set to 0, otherwise the appropriate type must be selected from the list of predefined sequence types.}
4788 \cvarg{header\_size}{Size of the sequence header; must be greater or equal to \texttt{sizeof(CvSeq)}. If a specific type or its extension is indicated, this type must fit the base type header.}
4789 \cvarg{elem\_size}{Size of the sequence elements in bytes. The size must be consistent with the sequence type. For example, for a sequence of points to be created, the element type \texttt{CV\_SEQ\_ELTYPE\_POINT} should be specified and the parameter \texttt{elem\_size} must be equal to \texttt{sizeof(CvPoint)}}
4790 \cvarg{storage}{Sequence location}
4793 The function \texttt{cvCreateSeq} creates a sequence and returns
4794 the pointer to it. The function allocates the sequence header in
4795 the storage block as one continuous chunk and sets the structure
4796 fields \texttt{flags}, \texttt{elem\_size}, \texttt{header\_size} and
4797 \texttt{storage} to passed values, sets \texttt{delta\_elems} to the
4798 default value (that may be reassigned using \cross{SetSeqBlockSize}
4799 function), and clears other header fields, including the space after
4800 the first \texttt{sizeof(CvSeq)} bytes.
4802 \cvfunc{SetSeqBlockSize}\label{SetSeqBlockSize}
4804 Sets up sequence block size
4808 void cvSetSeqBlockSize( \par CvSeq* seq,\par int delta\_elems );
4813 \cvarg{seq}{Sequence}
4814 \cvarg{delta\_elems}{Desirable sequence block size in elements}
4818 The function \texttt{cvSetSeqBlockSize} affects memory allocation
4819 granularity. When the free space in the sequence buffers has run out,
4820 the function allocates the space for \texttt{delta\_elems} sequence
4821 elements. If this block immediately follows the one previously allocated,
4822 the two blocks are concatenated, otherwise, a new sequence block is
4823 created. Therefore, the bigger the parameter is, the lower the possible
4824 sequence fragmentation, but the more space in the storage is wasted. When
4825 the sequence is created, the parameter \texttt{delta\_elems} is set to
4826 the default value about 1K. The function can be called any time after
4827 the sequence is created and affects future allocations. The function
4828 can modify the passed value of the parameter to meet the memory storage
4831 \cvfunc{SeqPush}\label{SeqPush}
4833 Adds element to sequence end
4837 char* cvSeqPush( \par CvSeq* seq,\par void* element=NULL );
4842 \cvarg{seq}{Sequence}
4843 \cvarg{element}{Added element}
4847 The function \texttt{cvSeqPush} adds an element to the end of sequence and retuns pointer to the allocated element. If the input \texttt{element} is NULL, the function simply allocates a space for one more element.
4849 The following code demonstrates how to create a new sequence using this function:
4853 CvMemStorage* storage = cvCreateMemStorage(0);
4854 CvSeq* seq = cvCreateSeq( CV_32SC1, /* sequence of integer elements */
4855 sizeof(CvSeq), /* header size - no extra fields */
4856 sizeof(int), /* element size */
4857 storage /* the container storage */ );
4859 for( i = 0; i < 100; i++ )
4861 int* added = (int*)cvSeqPush( seq, &i );
4862 printf( "%d is added\n", *added );
4866 /* release memory storage in the end */
4867 cvReleaseMemStorage( &storage );
4871 The function \texttt{cvSeqPush} has O(1) complexity, but there is a faster method for writing large sequences (see \cross{StartWriteSeq} and related functions).
4874 \cvfunc{SeqPop}\label{SeqPop}
4876 Removes element from sequence end
4880 void cvSeqPop( \par CvSeq* seq,\par void* element=NULL );
4885 \cvarg{seq}{Sequence}
4886 \cvarg{element}{Optional parameter . If the pointer is not zero, the function copies the removed element to this location.}
4889 The function \texttt{cvSeqPop} removes an element from the sequence. The function reports an error if the sequence is already empty. The function has O(1) complexity.
4891 \cvfunc{SeqPushFront}\label{SeqPushFront}
4893 Adds element to sequence beginning
4897 char* cvSeqPushFront( CvSeq* seq, void* element=NULL );
4902 \cvarg{seq}{Sequence}
4903 \cvarg{element}{Added element}
4906 The function \texttt{cvSeqPushFront} is similar to \cross{SeqPush} but it adds the new element to the beginning of the sequence. The function has O(1) complexity.
4908 \cvfunc{SeqPopFront}\label{SeqPopFront}
4910 Removes element from sequence beginning
4914 void cvSeqPopFront( \par \par CvSeq* seq,\par\par void* element=NULL );
4919 \cvarg{seq}{Sequence}
4920 \cvarg{element}{Optional parameter. If the pointer is not zero, the function copies the removed element to this location.}
4923 The function \texttt{cvSeqPopFront} removes an element from the beginning of the sequence. The function reports an error if the sequence is already empty. The function has O(1) complexity.
4925 \cvfunc{SeqPushMulti}\label{SeqPushMulti}
4927 Pushes several elements to the either end of sequence
4931 void cvSeqPushMulti( \par CvSeq* seq,\par void* elements,\par int count,\par int in\_front=0 );
4936 \cvarg{seq}{Sequence}
4937 \cvarg{elements}{Added elements}
4938 \cvarg{count}{Number of elements to push}
4939 \cvarg{in\_front}{The flags specifying the modified sequence end
4941 \cvarg{CV\_BACK}{the elements are added to the end of sequence}
4942 \cvarg{CV\_FRONT}{the elements are added to the beginning of sequence}
4946 The function \texttt{cvSeqPushMulti} adds several elements to either
4947 end of the sequence. The elements are added to the sequence in the same
4948 order as they are arranged in the input array but they can fall into
4949 different sequence blocks.
4951 \cvfunc{SeqPopMulti}\label{SeqPopMulti}
4953 Removes several elements from the either end of sequence
4957 void cvSeqPopMulti( \par CvSeq* seq,\par void* elements,\par int count,\par int in\_front=0 );
4962 \cvarg{seq}{Sequence}
4963 \cvarg{elements}{Removed elements}
4964 \cvarg{count}{Number of elements to pop}
4965 \cvarg{in\_front}{The flags specifying the modified sequence end
4967 \cvarg{CV\_BACK}{the elements are added to the end of sequence}
4968 \cvarg{CV\_FRONT}{the elements are added to the beginning of sequence}
4972 The function \texttt{cvSeqPopMulti} removes several elements from either end of the sequence. If the number of the elements to be removed exceeds the total number of elements in the sequence, the function removes as many elements as possible.
4974 \cvfunc{SeqInsert}\label{SeqInsert}
4976 Inserts element in sequence middle
4980 char* cvSeqInsert( \par CvSeq* seq,\par int before\_index,\par void* element=NULL );
4985 \cvarg{seq}{Sequence}
4986 \cvarg{before\_index}{Index before which the element is inserted. Inserting before 0 (the minimal allowed value of the parameter) is equal to \cross{SeqPushFront} and inserting before \texttt{seq->total} (the maximal allowed value of the parameter) is equal to \cross{SeqPush}.}
4987 \cvarg{element}{Inserted element}
4990 The function \texttt{cvSeqInsert} shifts the sequence elements from the inserted position to the nearest end of the sequence and copies the \texttt{element} content there if the pointer is not NULL. The function returns pointer to the inserted element.
4992 \cvfunc{SeqRemove}\label{SeqRemove}
4994 Removes element from sequence middle
4998 void cvSeqRemove( \par CvSeq* seq,\par int index );
5003 \cvarg{seq}{Sequence}
5004 \cvarg{index}{Index of removed element}
5008 The function \texttt{cvSeqRemove} removes elements with the given
5009 index. If the index is out of range the function reports an error. An
5010 attempt to remove an element from an empty sequence is a partitial
5011 case of this situation. The function removes an element by shifting
5012 the sequence elements between the nearest end of the sequence and the
5013 \texttt{index}-th position, not counting the latter.
5016 \cvfunc{ClearSeq}\label{ClearSeq}
5022 void cvClearSeq( CvSeq* seq );
5027 \cvarg{seq}{Sequence}
5031 The function \texttt{cvClearSeq} removes all elements from the
5032 sequence. The function does not return the memory to the storage, but this
5033 memory is reused later when new elements are added to the sequence. This
5034 function time complexity is 'O(1)'.
5036 \cvfunc{GetSeqElem}\label{GetSeqElem}
5038 Returns pointer to sequence element by its index
5042 char* cvGetSeqElem( const CvSeq* seq, int index );
5047 #define CV_GET_SEQ_ELEM( TYPE, seq, index ) (TYPE*)cvGetSeqElem( (CvSeq*)(seq), (index) )
5051 \cvarg{seq}{Sequence}
5052 \cvarg{index}{Index of element}
5056 The function \texttt{cvGetSeqElem} finds the element with the given
5057 index in the sequence and returns the pointer to it. If the element
5058 is not found, the function returns 0. The function supports negative
5059 indices, where -1 stands for the last sequence element, -2 stands for
5060 the one before last, etc. If the sequence is most likely to consist of
5061 a single sequence block or the desired element is likely to be located
5062 in the first block, then the macro
5063 \texttt{CV\_GET\_SEQ\_ELEM( elemType, seq, index )}
5064 should be used, where the parameter \texttt{elemType} is the
5065 type of sequence elements ( \cross{CvPoint} for example), the parameter
5066 \texttt{seq} is a sequence, and the parameter \texttt{index} is the index
5067 of the desired element. The macro checks first whether the desired element
5068 belongs to the first block of the sequence and returns it if it does,
5069 otherwise the macro calls the main function \texttt{GetSeqElem}. Negative
5070 indices always cause the \cross{GetSeqElem} call. The function has O(1)
5071 time complexity assuming that number of blocks is much smaller than the
5074 \cvfunc{SeqElemIdx}\label{SeqElemIdx}
5076 Returns index of concrete sequence element
5080 int cvSeqElemIdx( \par const CvSeq* seq,\par const void* element,\par CvSeqBlock** block=NULL );
5085 \cvarg{seq}{Sequence}
5086 \cvarg{element}{Pointer to the element within the sequence}
5087 \cvarg{block}{Optional argument. If the pointer is not \texttt{NULL}, the address of the sequence block that contains the element is stored in this location.}
5090 The function \texttt{cvSeqElemIdx} returns the index of a sequence element or a negative number if the element is not found.
5092 \cvfunc{CvtSeqToArray}\label{CvtSeqToArray}
5094 Copies sequence to one continuous block of memory
5098 void* cvCvtSeqToArray( \par const CvSeq* seq,\par void* elements,\par CvSlice slice=CV\_WHOLE\_SEQ );
5103 \cvarg{seq}{Sequence}
5104 \cvarg{elements}{Pointer to the destination array that must be large enough. It should be a pointer to data, not a matrix header.}
5105 \cvarg{slice}{The sequence part to copy to the array}
5109 The function \texttt{cvCvtSeqToArray} copies the entire sequence or subsequence to the specified buffer and returns the pointer to the buffer.
5112 \cvfunc{MakeSeqHeaderForArray}\label{MakeSeqHeaderForArray}
5114 Constructs sequence from array
5118 CvSeq* cvMakeSeqHeaderForArray( \par int seq\_type,\par int header\_size,\par int elem\_size,\par void* elements,\par int total,\par CvSeq* seq,\par CvSeqBlock* block );
5123 \cvarg{seq\_type}{Type of the created sequence}
5124 \cvarg{header\_size}{Size of the header of the sequence . Parameter sequence must point to the structure of that size or greater size.}
5125 \cvarg{elem\_size}{Size of the sequence element}
5126 \cvarg{elements}{Elements that will form a sequence}
5127 \cvarg{total}{Total number of elements in the sequence. The number of array elements must be equal to the value of this parameter.}
5128 \cvarg{seq}{Pointer to the local variable that is used as the sequence header}
5129 \cvarg{block}{Pointer to the local variable that is the header of the single sequence block}
5132 The function \texttt{cvMakeSeqHeaderForArray} initializes sequence
5133 header for array. The sequence header as well as the sequence block are
5134 allocated by the user (for example, on stack). No data is copied by the
5135 function. The resultant sequence will consists of a single block and
5136 have NULL storage pointer, thus, it is possible to read its elements,
5137 but the attempts to add elements to the sequence will raise an error in
5140 \cvfunc{SeqSlice}\label{SeqSlice}
5142 Makes separate header for the sequence slice
5146 CvSeq* cvSeqSlice( \par const CvSeq* seq,\par CvSlice slice,\par CvMemStorage* storage=NULL,\par int copy\_data=0 );
5151 \cvarg{seq}{Sequence}
5152 \cvarg{slice}{The part of the sequence to extract}
5153 \cvarg{storage}{The destination storage to keep the new sequence header and the copied data if any . If it is NULL, the function uses the storage containing the input sequence.}
5154 \cvarg{copy\_data}{The flag that indicates whether to copy the elements of the extracted slice (\texttt{copy\_data!=0}) or not (\texttt{copy\_data=0})}
5157 The function \texttt{cvSeqSlice} creates a sequence that represents the specified slice of the input sequence. The new sequence either shares the elements with the original sequence or has own copy of the elements. So if one needs to process a part of sequence but the processing function does not have a slice parameter, the required sub-sequence may be extracted using this function.
5160 \cvfunc{CloneSeq}\label{CloneSeq}
5162 Creates a copy of sequence
5166 CvSeq* cvCloneSeq( \par const CvSeq* seq,\par CvMemStorage* storage=NULL );
5171 \cvarg{seq}{Sequence}
5172 \cvarg{storage}{The destination storage to keep the new sequence header and the copied data if any. If it is NULL, the function uses the storage containing the input sequence.}
5175 The function \texttt{cvCloneSeq} makes a complete copy of the input sequence and returns it. The call
5178 cvCloneSeq( seq, storage )
5184 cvSeqSlice]( seq, CV\_WHOLE\_SEQ, storage, 1 )
5187 \cvfunc{SeqRemoveSlice}\label{SeqRemoveSlice}
5189 Removes sequence slice
5193 void cvSeqRemoveSlice( CvSeq* seq, CvSlice slice );
5198 \cvarg{seq}{Sequence}
5199 \cvarg{slice}{The part of the sequence to remove}
5203 The function \texttt{cvSeqRemoveSlice} removes slice from the sequence.
5205 \cvfunc{SeqInsertSlice}\label{SeqInsertSlice}
5207 Inserts array in the middle of sequence
5211 void cvSeqInsertSlice( \par CvSeq* seq,\par int before\_index,\par const CvArr* from\_arr );
5216 \cvarg{seq}{Sequence}
5217 \cvarg{slice}{The part of the sequence to remove}
5218 \cvarg{from\_arr}{The array to take elements from}
5222 The function \texttt{cvSeqInsertSlice} inserts all \texttt{from\_arr}
5223 array elements at the specified position of the sequence. The array
5224 \texttt{from\_arr} can be a matrix or another sequence.
5226 \cvfunc{SeqInvert}\label{SeqInvert}
5228 Reverses the order of sequence elements
5232 void cvSeqInvert( CvSeq* seq );
5237 \cvarg{seq}{Sequence}
5241 The function \texttt{cvSeqInvert} reverses the sequence in-place - makes the first element go last, the last element go first etc.
5244 \cvfunc{SeqSort}\label{SeqSort}
5246 Sorts sequence element using the specified comparison function
5250 void cvSeqSort( CvSeq* seq, CvCmpFunc func, void* userdata=NULL );
5255 /* a < b ? -1 : a > b ? 1 : 0 */
5256 typedef int (CV_CDECL* CvCmpFunc)(const void* a, const void* b, void* userdata);
5260 \cvarg{seq}{The sequence to sort}
5261 \cvarg{func}{The comparison function that returns negative, zero or positive value depending on the elements relation (see the above declaration and the example below) - similar function is used by \texttt{qsort} from C runline except that in the latter \texttt{userdata} is not used}
5262 \cvarg{userdata}{The user parameter passed to the compasion function; helps to avoid global variables in some cases}
5265 The function \texttt{cvSeqSort} sorts the sequence in-place using the specified criteria. Below is the example of the function use:
5269 /* Sort 2d points in top-to-bottom left-to-right order */
5270 static int cmp_func( const void* _a, const void* _b, void* userdata )
5272 CvPoint* a = (CvPoint*)_a;
5273 CvPoint* b = (CvPoint*)_b;
5274 int y_diff = a->y - b->y;
5275 int x_diff = a->x - b->x;
5276 return y_diff ? y_diff : x_diff;
5281 CvMemStorage* storage = cvCreateMemStorage(0);
5282 CvSeq* seq = cvCreateSeq( CV_32SC2, sizeof(CvSeq), sizeof(CvPoint), storage );
5285 for( i = 0; i < 10; i++ )
5288 pt.x = rand() % 1000;
5289 pt.y = rand() % 1000;
5290 cvSeqPush( seq, &pt );
5293 cvSeqSort( seq, cmp_func, 0 /* userdata is not used here */ );
5295 /* print out the sorted sequence */
5296 for( i = 0; i < seq->total; i++ )
5298 CvPoint* pt = (CvPoint*)cvSeqElem( seq, i );
5299 printf( "(%d,%d)\n", pt->x, pt->y );
5302 cvReleaseMemStorage( &storage );
5307 \cvfunc{SeqSearch}\label{SeqSearch}
5309 Searches element in sequence
5313 /* a < b ? -1 : a > b ? 1 : 0 */
5314 typedef int (CV_CDECL* CvCmpFunc)(const void* a, const void* b, void* userdata);
5316 char* cvSeqSearch( CvSeq* seq, const void* elem, CvCmpFunc func,
5317 int is_sorted, int* elem_idx, void* userdata=NULL );
5322 \cvarg{seq}{The sequence}
5323 \cvarg{elem}{The element to look for}
5324 \cvarg{func}{The comparison function that returns negative, zero or positive value depending on the elements relation (see also \cross{SeqSort})}
5325 \cvarg{is\_sorted}{Whether the sequence is sorted or not}
5326 \cvarg{elem\_idx}{Output parameter; index of the found element}
5327 \cvarg{userdata}{The user parameter passed to the compasion function; helps to avoid global variables in some cases}
5330 The function \texttt{cvSeqSearch} searches the element in the sequence. If
5331 the sequence is sorted, binary O(log(N)) search is used, otherwise, a
5332 simple linear search is used. If the element is not found, the function
5333 returns NULL pointer and the index is set to the number of sequence
5334 elements if the linear search is used, and to the smallest index
5335 \texttt{i, seq(i)>elem}
5338 \cvfunc{StartAppendToSeq}\label{StartAppendToSeq}
5340 Initializes process of writing data to sequence
5344 void cvStartAppendToSeq( \par CvSeq* seq,\par CvSeqWriter* writer );
5349 \cvarg{seq}{Pointer to the sequence}
5350 \cvarg{writer}{Writer state; initialized by the function}
5353 The function \texttt{cvStartAppendToSeq} initializes the process of
5354 writing data to the sequence. Written elements are added to the end of the
5356 \texttt{CV\_WRITE\_SEQ\_ELEM( written\_elem, writer )}
5358 that during the writing process other operations on the sequence may
5359 yield incorrect result or even corrupt the sequence (see description of
5360 \cross{FlushSeqWriter} that helps to avoid some of these problems).
5362 \cvfunc{StartWriteSeq}\label{StartWriteSeq}
5364 Creates new sequence and initializes writer for it
5368 void cvStartWriteSeq( \par int seq\_flags,\par int header\_size,\par int elem\_size,\par CvMemStorage* storage,\par CvSeqWriter* writer );
5373 \cvarg{seq\_flags}{Flags of the created sequence. If the sequence is not passed to any function working with a specific type of sequences, the sequence value may be equal to 0, otherwise the appropriate type must be selected from the list of predefined sequence types.}
5374 \cvarg{header\_size}{Size of the sequence header. The parameter value may not be less than \texttt{sizeof(CvSeq)}. If a certain type or extension is specified, it must fit the base type header.}
5375 \cvarg{elem\_size}{Size of the sequence elements in bytes; must be consistent with the sequence type. For example, if the sequence of points is created (element type \texttt{CV\_SEQ\_ELTYPE\_POINT} ), then the parameter elem\_size must be equal to \texttt{sizeof(CvPoint)}}
5376 \cvarg{storage}{Sequence location}
5377 \cvarg{writer}{Writer state; initialized by the function}
5380 The function \texttt{cvStartWriteSeq} is a composition of
5381 \cross{CreateSeq} and \cross{StartAppendToSeq}. The pointer to the
5382 created sequence is stored at
5383 \texttt{writer->seq}
5384 and is also returned by
5385 \cross{EndWriteSeq} function that should be called in the end.
5387 \cvfunc{EndWriteSeq}\label{EndWriteSeq}
5389 Finishes process of writing sequence
5393 CvSeq* cvEndWriteSeq( CvSeqWriter* writer );
5398 \cvarg{writer}{Writer state}
5402 The function \texttt{cvEndWriteSeq} finishes the writing process and
5403 returns the pointer to the written sequence. The function also truncates
5404 the last incomplete sequence block to return the remaining part of the
5405 block to the memory storage. After that the sequence can be read and
5408 \cvfunc{FlushSeqWriter}\label{FlushSeqWriter}
5410 Updates sequence headers from the writer state
5414 void cvFlushSeqWriter( CvSeqWriter* writer );
5419 \cvarg{writer}{Writer state}
5422 The function \texttt{cvFlushSeqWriter} is intended to enable the user to
5423 read sequence elements, whenever required, during the writing process,
5424 e.g., in order to check specific conditions. The function updates the
5425 sequence headers to make reading from the sequence possible. The writer
5426 is not closed, however, so that the writing process can be continued
5427 any time. In some algorithm requires often flush'es, consider using
5428 \cross{SeqPush} instead.
5430 \cvfunc{StartReadSeq}\label{StartReadSeq}
5432 Initializes process of sequential reading from sequence
5436 void cvStartReadSeq( \par const CvSeq* seq,\par CvSeqReader* reader,\par int reverse=0 );
5441 \cvarg{seq}{Sequence}
5442 \cvarg{reader}{Reader state; initialized by the function}
5443 \cvarg{reverse}{Determines the direction of the sequence traversal. If \texttt{reverse} is 0, the reader is positioned at the first sequence element, otherwise it is positioned at the last element. }
5446 The function \texttt{cvStartReadSeq} initializes the reader state. After
5447 that all the sequence elements from the first down to the last one
5448 can be read by subsequent calls of the macro
5449 \texttt{CV\_READ\_SEQ\_ELEM( read\_elem, reader )}
5450 in case of forward reading and by using
5451 \texttt{CV\_REV\_READ\_SEQ\_ELEM( read\_elem, reader )}
5453 reading. Both macros put the sequence element to \texttt{read\_elem} and
5454 move the reading pointer toward the next element. A circular structure
5455 of sequence blocks is used for the reading process, that is, after the
5456 last element has been read by the macro \texttt{CV\_READ\_SEQ\_ELEM}, the
5457 first element is read when the macro is called again. The same applies to
5458 \texttt{CV\_REV\_READ\_SEQ\_ELEM}. There is no function to finish the reading
5459 process, since it neither changes the sequence nor creates any temporary
5460 buffers. The reader field \texttt{ptr} points to the current element of
5461 the sequence that is to be read next. The code below demonstrates how
5462 to use sequence writer and reader.
5466 CvMemStorage* storage = cvCreateMemStorage(0);
5467 CvSeq* seq = cvCreateSeq( CV_32SC1, sizeof(CvSeq), sizeof(int), storage );
5472 cvStartAppendToSeq( seq, &writer );
5473 for( i = 0; i < 10; i++ )
5475 int val = rand()%100;
5476 CV_WRITE_SEQ_ELEM( val, writer );
5477 printf("%d is written\n", val );
5479 cvEndWriteSeq( &writer );
5481 cvStartReadSeq( seq, &reader, 0 );
5482 for( i = 0; i < seq->total; i++ )
5486 CV_READ_SEQ_ELEM( val, reader );
5487 printf("%d is read\n", val );
5488 #else /* alternative way, that is prefferable if sequence elements are large,
5489 or their size/type is unknown at compile time */
5490 printf("%d is read\n", *(int*)reader.ptr );
5491 CV_NEXT_SEQ_ELEM( seq->elem_size, reader );
5496 cvReleaseStorage( &storage );
5500 \cvfunc{GetSeqReaderPos}\label{GetSeqReaderPos}
5502 Returns the current reader position
5506 int cvGetSeqReaderPos( CvSeqReader* reader );
5511 \cvarg{reader}{Reader state}
5515 The function \texttt{cvGetSeqReaderPos} returns the current reader position (within 0 ... \texttt{reader->seq->total} - 1).
5517 \cvfunc{SetSeqReaderPos}\label{SetSeqReaderPos}
5519 Moves the reader to specified position
5523 void cvSetSeqReaderPos( \par CvSeqReader* reader,\par int index,\par int is\_relative=0 );
5528 \cvarg{reader}{Reader state}
5529 \cvarg{index}{The destination position. If the positioning mode is used (see the next parameter) the actual position will be \texttt{index} mod \texttt{reader->seq->total}.}
5530 \cvarg{is\_relative}{If it is not zero, then \texttt{index} is a relative to the current position}
5533 The function \texttt{cvSetSeqReaderPos} moves the read position to the absolute position or relative to the current position.
5537 \cvstruct{CvSet}\label{CvSet}
5543 typedef struct CvSetElem
5545 int flags; /* it is negative if the node is free and zero or positive otherwise */
5546 struct CvSetElem* next_free; /* if the node is free, the field is a
5547 pointer to next free node */
5551 #define CV_SET_FIELDS() \
5552 CV_SEQUENCE_FIELDS() /* inherits from [#CvSeq CvSeq] */ \
5553 struct CvSetElem* free_elems; /* list of free nodes */
5555 typedef struct CvSet
5562 The structure \cross{CvSet} is a base for OpenCV sparse data structures.
5564 As follows from the above declaration \cross{CvSet} inherits from
5565 \cross{CvSeq} and it adds \texttt{free\_elems} field it to, which
5566 is a list of free nodes. Every set node, whether free or not, is the
5567 element of the underlying sequence. While there is no restrictions on
5568 elements of dense sequences, the set (and derived structures) elements
5569 must start with integer field and be able to fit CvSetElem structure,
5570 because these two fields (integer followed by the pointer) are required
5571 for organization of node set with the list of free nodes. If a node is
5572 free, \texttt{flags} field is negative (the most-significant bit, or
5573 MSB, of the field is set), and \texttt{next\_free} points to the next
5574 free node (the first free node is referenced by \texttt{free\_elems}
5575 field of \cross{CvSet}). And if a node is occupied, \texttt{flags} field
5576 is positive and contains the node index that may be retrieved using
5577 (\texttt{set\_elem->flags \& CV\_SET\_ELEM\_IDX\_MASK}) expression, the rest of
5578 the node content is determined by the user. In particular, the occupied
5579 nodes are not linked as the free nodes are, so the second field can be
5580 used for such a link as well as for some different purpose. The macro
5581 'CV\_IS\_SET\_ELEM(set\_elem\_ptr)' can be used to determined whether
5582 the specified node is occupied or not.
5584 Initially the set and the list are empty. When a new node is requiested
5585 from the set, it is taken from the list of free nodes, which is updated
5586 then. If the list appears to be empty, a new sequence block is allocated
5587 and all the nodes within the block are joined in the list of free
5588 nodes. Thus, \texttt{total} field of the set is the total number of nodes
5589 both occupied and free. When an occupied node is released, it is added
5590 to the list of free nodes. The node released last will be occupied first.
5592 In OpenCV \cross{CvSet} is used for representing graphs (\cross{CvGraph}),
5593 sparse multi-dimensional arrays (\cross{CvSparseMat}), planar subdivisions
5596 \cvfunc{CreateSet}\label{CreateSet}
5602 CvSet* cvCreateSet( \par int set\_flags,\par int header\_size,\par int elem\_size,\par CvMemStorage* storage );
5607 \cvarg{set\_flags}{Type of the created set}
5608 \cvarg{header\_size}{Set header size; may not be less than \texttt{sizeof(CvSet)}}
5609 \cvarg{elem\_size}{Set element size; may not be less than \cross{CvSetElem}}
5610 \cvarg{storage}{Container for the set}
5613 The function \texttt{cvCreateSet} creates an empty set with a specified header size and element size, and returns the pointer to the set. The function is just a thin layer on top of \cross{CreateSeq}.
5615 \cvfunc{SetAdd}\label{SetAdd}
5617 Occupies a node in the set
5621 int cvSetAdd( \par CvSet* set\_header,\par CvSetElem* elem=NULL,\par CvSetElem** inserted\_elem=NULL );
5626 \cvarg{set\_header}{Set}
5627 \cvarg{elem}{Optional input argument, inserted element. If not NULL, the function copies the data to the allocated node (The MSB of the first integer field is cleared after copying).}
5628 \cvarg{inserted\_elem}{Optional output argument; the pointer to the allocated cell}
5631 The function \texttt{cvSetAdd} allocates a new node, optionally copies
5632 input element data to it, and returns the pointer and the index to the
5633 node. The index value is taken from the lower bits of \texttt{flags}
5634 field of the node. The function has O(1) complexity, however there exists
5635 a faster function for allocating set nodes (see \cross{SetNew}).
5637 \cvfunc{SetRemove}\label{SetRemove}
5639 Removes element from set
5643 void cvSetRemove( \par CvSet* set\_header,\par int index );
5648 \cvarg{set\_header}{Set}
5649 \cvarg{index}{Index of the removed element}
5652 The function \texttt{cvSetRemove} removes an element with a specified
5653 index from the set. If the node at the specified location is not occupied
5654 the function does nothing. The function has O(1) complexity, however,
5655 \cross{SetRemoveByPtr} provides yet faster way to remove a set element
5656 if it is located already.
5658 \cvfunc{SetNew}\label{SetNew}
5660 Adds element to set (fast variant)
5664 CvSetElem* cvSetNew( CvSet* set\_header );
5669 \cvarg{set\_header}{Set}
5673 The function \texttt{cvSetNew} is inline light-weight variant of \cross{SetAdd}. It occupies a new node and returns pointer to it rather than index.
5676 \cvfunc{SetRemoveByPtr}\label{SetRemoveByPtr}
5678 Removes set element given its pointer
5682 void cvSetRemoveByPtr( \par CvSet* set\_header,\par void* elem );
5687 \cvarg{set\_header}{Set}
5688 \cvarg{elem}{Removed element}
5691 The function \texttt{cvSetRemoveByPtr} is inline light-weight variant of \cross{SetRemove} that takes element pointer. The function does not check whether the node is occupied or not - the user should take care of it.
5694 \cvfunc{GetSetElem}\label{GetSetElem}
5696 Finds set element by its index
5700 CvSetElem* cvGetSetElem( \par const CvSet* set\_header,\par int index );
5705 \cvarg{set\_header}{Set}
5706 \cvarg{index}{Index of the set element within a sequence}
5709 The function \texttt{cvGetSetElem} finds a set element by index. The function returns the pointer to it or 0 if the index is invalid or the corresponding node is free. The function supports negative indices as it uses \cross{GetSeqElem} to locate the node.
5711 \cvfunc{ClearSet}\label{ClearSet}
5717 void cvClearSet( CvSet* set\_header );
5722 \cvarg{set\_header}{Cleared set}
5726 The function \texttt{cvClearSet} removes all elements from set. It has O(1) time complexity.
5732 \cvstruct{CvGraph}\label{CvGraph}
5734 Oriented or unoriented weigted graph
5738 #define CV_GRAPH_VERTEX_FIELDS() \
5739 int flags; /* vertex flags */ \
5740 struct CvGraphEdge* first; /* the first incident edge */
5742 typedef struct CvGraphVtx
5744 CV_GRAPH_VERTEX_FIELDS()
5748 #define CV_GRAPH_EDGE_FIELDS() \
5749 int flags; /* edge flags */ \
5750 float weight; /* edge weight */ \
5751 struct CvGraphEdge* next[2]; /* the next edges in the incidence lists for staring (0) */ \
5752 /* and ending (1) vertices */ \
5753 struct CvGraphVtx* vtx[2]; /* the starting (0) and ending (1) vertices */
5755 typedef struct CvGraphEdge
5757 CV_GRAPH_EDGE_FIELDS()
5761 #define CV_GRAPH_FIELDS() \
5762 CV_SET_FIELDS() /* set of vertices */ \
5763 CvSet* edges; /* set of edges */
5765 typedef struct CvGraph
5773 The structure \cross{CvGraph} is a base for graphs used in OpenCV.
5775 Graph structure inherits from \cross{CvSet} - this part describes common graph properties and the graph vertices, and contains another set as a member - this part describes the graph edges.
5777 The vertex, edge and the graph header structures are declared using the
5778 same technique as other extendible OpenCV structures - via macros, that
5779 simplifies extension and customization of the structures. While the vertex
5780 and edge structures do not inherit from \cross{CvSetElem} explicitly, they
5781 satisfy both conditions on the set elements - have an integer field in
5782 the beginning and fit CvSetElem structure. The \texttt{flags} fields are
5783 used as for indicating occupied vertices and edges as well as for other
5784 purposes, for example, for graph traversal (see \cross{CreateGraphScanner}
5785 et al.), so it is better not to use them directly.
5787 The graph is represented as a set of edges each of whose has the list of
5788 incident edges. The incidence lists for different vertices are interleaved
5789 to avoid information duplication as much as posssible.
5791 The graph may be oriented or unoriented. In the latter case there is no
5792 distiction between edge connecting vertex $A$ with vertex $B$ and the edge
5793 connecting vertex $B$ with vertex $A$ - only one of them can exist in the
5794 graph at the same moment and it represents both $A \rightarrow B$ and
5795 $B \rightarrow A$ edges..
5797 \cvfunc{CreateGraph}\label{CreateGraph}
5803 CvGraph* cvCreateGraph( \par int graph\_flags,\par int header\_size,\par int vtx\_size,\par int edge\_size,\par CvMemStorage* storage );
5808 \cvarg{graph\_flags}{Type of the created graph. Usually, it is either \texttt{CV\_SEQ\_KIND\_GRAPH} for generic unoriented graphs and
5809 \texttt{CV\_SEQ\_KIND\_GRAPH | CV\_GRAPH\_FLAG\_ORIENTED} for generic oriented graphs.}
5810 \cvarg{header\_size}{Graph header size; may not be less than \texttt{sizeof(CvGraph)}}
5811 \cvarg{vtx\_size}{Graph vertex size; the custom vertex structure must start with \cross{CvGraphVtx} (use 'CV\_GRAPH\_VERTEX\_FIELDS()')}
5812 \cvarg{edge\_size}{Graph edge size; the custom edge structure must start with \cross{CvGraphEdge} (use 'CV\_GRAPH\_EDGE\_FIELDS()')}
5813 \cvarg{storage}{The graph container}
5816 The function \texttt{cvCreateGraph} creates an empty graph and returns pointer to it.
5818 \cvfunc{GraphAddVtx}\label{GraphAddVtx}
5820 Adds vertex to graph
5824 int cvGraphAddVtx( \par CvGraph* graph,\par const CvGraphVtx* vtx=NULL,\par CvGraphVtx** inserted\_vtx=NULL );
5829 \cvarg{graph}{Graph}
5830 \cvarg{vtx}{Optional input argument used to initialize the added vertex (only user-defined fields beyond 'sizeof(CvGraphVtx)' are copied)}
5831 \cvarg{inserted\_vertex}{Optional output argument. If not \texttt{NULL}, the address of the new vertex is written there.}
5834 The function \texttt{cvGraphAddVtx} adds a vertex to the graph and returns the vertex index.
5836 \cvfunc{GraphRemoveVtx}\label{GraphRemoveVtx}
5838 Removes vertex from graph
5842 int cvGraphRemoveVtx( \par CvGraph* graph,\par int index );
5847 \cvarg{graph}{Graph}
5848 \cvarg{vtx\_idx}{Index of the removed vertex}
5851 The function \texttt{cvGraphRemoveAddVtx} removes a vertex from the graph
5852 together with all the edges incident to it. The function reports an error,
5853 if the input vertex does not belong to the graph. The return value is
5854 number of edges deleted, or -1 if the vertex does not belong to the graph.
5856 \cvfunc{GraphRemoveVtxByPtr}\label{GraphRemoveVtxByPtr}
5858 Removes vertex from graph
5862 int cvGraphRemoveVtxByPtr( \par CvGraph* graph,\par CvGraphVtx* vtx );
5867 \cvarg{graph}{Graph}
5868 \cvarg{vtx}{Pointer to the removed vertex}
5872 The function \texttt{cvGraphRemoveVtxByPtr} removes a vertex from the graph together with all the edges incident to it. The function reports an error, if the vertex does not belong to the graph. The return value is number of edges deleted, or -1 if the vertex does not belong to the graph.
5874 \cvfunc{GetGraphVtx}\label{GetGraphVtx}
5876 Finds graph vertex by index
5880 CvGraphVtx* cvGetGraphVtx( \par CvGraph* graph,\par int vtx\_idx );
5885 \cvarg{graph}{Graph}
5886 \cvarg{vtx\_idx}{Index of the vertex}
5890 The function \texttt{cvGetGraphVtx} finds the graph vertex by index and returns the pointer to it or NULL if the vertex does not belong to the graph.
5893 \cvfunc{GraphVtxIdx}\label{GraphVtxIdx}
5895 Returns index of graph vertex
5899 int cvGraphVtxIdx( \par CvGraph* graph,\par CvGraphVtx* vtx );
5904 \cvarg{graph}{Graph}
5905 \cvarg{vtx}{Pointer to the graph vertex}
5908 The function \texttt{cvGraphVtxIdx} returns index of the graph vertex.
5910 \cvfunc{GraphAddEdge}\label{GraphAddEdge}
5916 int cvGraphAddEdge( \par CvGraph* graph,\par int start\_idx,\par int end\_idx,\par const CvGraphEdge* edge=NULL,\par CvGraphEdge** inserted\_edge=NULL );
5921 \cvarg{graph}{Graph}
5922 \cvarg{start\_idx}{Index of the starting vertex of the edge}
5923 \cvarg{end\_idx}{Index of the ending vertex of the edge. For unoriented graph the order of the vertex parameters does not matter.}
5924 \cvarg{edge}{Optional input parameter, initialization data for the edge}
5925 \cvarg{inserted\_edge}{Optional output parameter to contain the address of the inserted edge}
5929 The function \texttt{cvGraphAddEdge} connects two specified vertices. The function returns 1 if the edge has been added successfully, 0 if the edge connecting the two vertices exists already and -1 if either of the vertices was not found, the starting and the ending vertex are the same or there is some other critical situation. In the latter case (i.e. when the result is negative) the function also reports an error by default.
5931 \cvfunc{GraphAddEdgeByPtr}\label{GraphAddEdgeByPtr}
5937 int cvGraphAddEdgeByPtr( \par CvGraph* graph,\par CvGraphVtx* start\_vtx,\par CvGraphVtx* end\_vtx,\par const CvGraphEdge* edge=NULL,\par CvGraphEdge** inserted\_edge=NULL );
5942 \cvarg{graph}{Graph}
5943 \cvarg{start\_vtx}{Pointer to the starting vertex of the edge}
5944 \cvarg{end\_vtx}{Pointer to the ending vertex of the edge. For unoriented graph the order of the vertex parameters does not matter.}
5945 \cvarg{edge}{Optional input parameter, initialization data for the edge}
5946 \cvarg{inserted\_edge}{Optional output parameter to contain the address of the inserted edge within the edge set}
5949 The function \texttt{cvGraphAddEdge} connects two specified vertices. The
5950 function returns 1 if the edge has been added successfully, 0 if the
5951 edge connecting the two vertices exists already and -1 if either of the
5952 vertices was not found, the starting and the ending vertex are the same
5953 or there is some other critical situation. In the latter case (i.e. when
5954 the result is negative) the function also reports an error by default.
5956 \cvfunc{GraphRemoveEdge}\label{GraphRemoveEdge}
5958 Removes edge from graph
5962 void cvGraphRemoveEdge( \par CvGraph* graph,\par int start\_idx,\par int end\_idx );
5967 \cvarg{graph}{Graph}
5968 \cvarg{start\_idx}{Index of the starting vertex of the edge}
5969 \cvarg{end\_idx}{Index of the ending vertex of the edge. For unoriented graph the order of the vertex parameters does not matter.}
5972 The function \texttt{cvGraphRemoveEdge} removes the edge connecting two specified vertices. If the vertices are not connected [in that order], the function does nothing.
5974 \cvfunc{GraphRemoveEdgeByPtr}\label{GraphRemoveEdgeByPtr}
5976 Removes edge from graph
5980 void cvGraphRemoveEdgeByPtr( \par CvGraph* graph,\par CvGraphVtx* start\_vtx,\par CvGraphVtx* end\_vtx );
5985 \cvarg{graph}{Graph}
5986 \cvarg{start\_vtx}{Pointer to the starting vertex of the edge}
5987 \cvarg{end\_vtx}{Pointer to the ending vertex of the edge. For unoriented graph the order of the vertex parameters does not matter.}
5990 The function \texttt{cvGraphRemoveEdgeByPtr} removes the edge connecting two specified vertices. If the vertices are not connected [in that order], the function does nothing.
5992 \cvfunc{FindGraphEdge}\label{FindGraphEdge}
5998 CvGraphEdge* cvFindGraphEdge( const CvGraph* graph, int start\_idx, int end\_idx );
6004 #define cvGraphFindEdge cvFindGraphEdge
6009 \cvarg{graph}{Graph}
6010 \cvarg{start\_idx}{Index of the starting vertex of the edge}
6011 \cvarg{end\_idx}{Index of the ending vertex of the edge. For unoriented graph the order of the vertex parameters does not matter.}
6014 The function \texttt{cvFindGraphEdge} finds the graph edge connecting two specified vertices and returns pointer to it or NULL if the edge does not exists.
6016 \cvfunc{FindGraphEdgeByPtr}\label{FindGraphEdgeByPtr}
6022 CvGraphEdge* cvFindGraphEdgeByPtr( \par const CvGraph* graph,\par const CvGraphVtx* start\_vtx,\par const CvGraphVtx* end\_vtx );
6027 \#define cvGraphFindEdgeByPtr cvFindGraphEdgeByPtr
6031 \cvarg{graph}{Graph}
6032 \cvarg{start\_vtx}{Pointer to the starting vertex of the edge}
6033 \cvarg{end\_vtx}{Pointer to the ending vertex of the edge. For unoriented graph the order of the vertex parameters does not matter.}
6036 The function \texttt{cvFindGraphEdge} finds the graph edge connecting two specified vertices and returns pointer to it or NULL if the edge does not exists.
6038 \cvfunc{GraphEdgeIdx}\label{GraphEdgeIdx}
6040 Returns index of graph edge
6044 int cvGraphEdgeIdx( \par CvGraph* graph,\par CvGraphEdge* edge );
6049 \cvarg{graph}{Graph}
6050 \cvarg{edge}{Pointer to the graph edge}
6053 The function \texttt{cvGraphEdgeIdx} returns index of the graph edge.
6055 \cvfunc{GraphVtxDegree}\label{GraphVtxDegree}
6057 Counts edges indicent to the vertex
6061 int cvGraphVtxDegree( const CvGraph* graph, int vtx\_idx );
6066 \cvarg{graph}{Graph}
6067 \cvarg{vtx}{Index of the graph vertex}
6070 The function \texttt{cvGraphVtxDegree} returns the number of edges incident to the specified vertex, both incoming and outcoming. To count the edges, the following code is used:
6074 CvGraphEdge* edge = vertex->first; int count = 0;
6077 edge = CV_NEXT_GRAPH_EDGE( edge, vertex );
6083 The macro \texttt{CV\_NEXT\_GRAPH\_EDGE( edge, vertex )} returns the edge incident to \texttt{vertex} that follows after \texttt{edge}.
6085 \cvfunc{GraphVtxDegreeByPtr}\label{GraphVtxDegreeByPtr}
6091 int cvGraphVtxDegreeByPtr( \par const CvGraph* graph,\par const CvGraphVtx* vtx );
6096 \cvarg{graph}{Graph}
6097 \cvarg{vtx}{Pointer to the graph vertex}
6100 The function \texttt{cvGraphVtxDegree} returns the number of edges incident to the specified vertex, both incoming and outcoming.
6103 \cvfunc{ClearGraph}\label{ClearGraph}
6109 void cvClearGraph( CvGraph* graph );
6114 \cvarg{graph}{Graph}
6117 The function \texttt{cvClearGraph} removes all vertices and edges from the graph. The function has O(1) time complexity.
6119 \cvfunc{CloneGraph}\label{CloneGraph}
6125 CvGraph* cvCloneGraph( \par const CvGraph* graph,\par CvMemStorage* storage );
6130 \cvarg{graph}{The graph to copy}
6131 \cvarg{storage}{Container for the copy}
6135 The function \texttt{cvCloneGraph} creates full copy of the graph. If the
6136 graph vertices or edges have pointers to some external data, it still be
6137 shared between the copies. The vertex and edge indices in the new graph
6138 may be different from the original, because the function defragments
6139 the vertex and edge sets.
6142 \cvstruct{CvGraphScanner}\label{CvGraphScanner}
6144 Graph traversal state
6148 typedef struct CvGraphScanner
6150 CvGraphVtx* vtx; /* current graph vertex (or current edge origin) */
6151 CvGraphVtx* dst; /* current graph edge destination vertex */
6152 CvGraphEdge* edge; /* current edge */
6154 CvGraph* graph; /* the graph */
6155 CvSeq* stack; /* the graph vertex stack */
6156 int index; /* the lower bound of certainly visited vertices */
6157 int mask; /* event mask */
6163 The structure \cross{CvGraphScanner} is used for depth-first graph traversal. See discussion of the functions below.
6166 \cvfunc{CreateGraphScanner}\label{CreateGraphScanner}
6168 Creates structure for depth-first graph traversal
6172 CvGraphScanner* cvCreateGraphScanner( \par CvGraph* graph,\par CvGraphVtx* vtx=NULL,\par int mask=CV\_GRAPH\_ALL\_ITEMS );
6177 \cvarg{graph}{Graph}
6178 \cvarg{vtx}{Initial vertex to start from. If NULL, the traversal starts from the first vertex (a vertex with the minimal index in the sequence of vertices).}
6179 \cvarg{mask}{Event mask indicating which events are interesting to the user (where \cross{NextGraphItem} function returns control to the user) It can be \texttt{CV\_GRAPH\_ALL\_ITEMS} (all events are interesting) or combination of the following flags:
6182 \cvarg{CV\_GRAPH\_VERTEX}{stop at the graph vertices visited for the first time}
6183 \cvarg{CV\_GRAPH\_TREE\_EDGE}{stop at tree edges ('tree edge' is the edge connecting the last visited vertex and the vertex to be visited next)}
6184 \cvarg{CV\_GRAPH\_BACK\_EDGE}{stop at back edges ('back edge' is an edge connecting the last visited vertex with some of its ancestors in the search tree)}
6185 \cvarg{CV\_GRAPH\_FORWARD\_EDGE}{stop at forward edges ('forward edge' is an edge conecting the last visited vertex with some of its descendants in the search tree). The 'forward edges' are only possible during oriented graph traversal)}
6186 \cvarg{CV\_GRAPH\_CROSS\_EDGE}{stop at cross edges ('cross edge' is an edge connecting different search trees or branches of the same tree. The 'cross edges' are only possible during oriented graphs traversal)}
6187 \cvarg{CV\_GRAPH\_ANY\_EDGE}{stop and any edge ('tree, back, forward' and 'cross edges')}
6188 \cvarg{CV\_GRAPH\_NEW\_TREE}{stop in the beginning of every new search tree. When the traversal procedure visits all vertices and edges reachible from the initial vertex (the visited vertices together with tree edges make up a tree), it searches for some unvisited vertex in the graph and resumes the traversal process from that vertex. Before starting a new tree (including the very first tree when \texttt{cvNextGraphItem} is called for the first time) it generates \texttt{CV\_GRAPH\_NEW\_TREE} event. For unoriented graphs each search tree corresponds to a connected component of the graph.}
6189 \cvarg{CV\_GRAPH\_BACKTRACKING}{stop at every already visited vertex during backtracking - returning to already visited vertexes of the traversal tree.}
6193 The function \texttt{cvCreateGraphScanner} creates structure for depth-first graph traversal/search. The initialized structure is used in \cross{NextGraphItem} function - the incremental traversal procedure.
6195 \cvfunc{NextGraphItem}\label{NextGraphItem}
6197 Makes one or more steps of the graph traversal procedure
6201 int cvNextGraphItem( CvGraphScanner* scanner );
6206 \cvarg{scanner}{Graph traversal state. It is updated by the function.}
6209 The function \texttt{cvNextGraphItem} traverses through the graph
6210 until an event interesting to the user (that is, an event, specified
6211 in the \texttt{mask} in \cross{CreateGraphScanner} call) is met or the
6212 traversal is over. In the first case it returns one of the events,
6213 listed in the description of \texttt{mask} parameter above and with
6214 the next call it resumes the traversal. In the latter case it returns
6215 \texttt{CV\_GRAPH\_OVER} (-1). When the event is \texttt{CV\_GRAPH\_VERTEX},
6216 or \texttt{CV\_GRAPH\_BACKTRACKING} or \texttt{CV\_GRAPH\_NEW\_TREE},
6217 the currently observed vertex is stored in 'scanner->vtx'. And if the
6218 event is edge-related, the edge itself is stored at 'scanner->edge',
6219 the previously visited vertex - at 'scanner->vtx' and the other ending
6220 vertex of the edge - at 'scanner->dst'.
6222 \cvfunc{ReleaseGraphScanner}\label{ReleaseGraphScanner}
6224 Finishes graph traversal procedure
6228 void cvReleaseGraphScanner( CvGraphScanner** scanner );
6233 \cvarg{scanner}{Double pointer to graph traverser}
6237 The function \texttt{cvGraphScanner} finishes graph traversal procedure and releases the traverser state.
6243 \cvmacro{CV\_TREE\_NODE\_FIELDS}\label{CV_TREE_NODE_FIELDS}
6245 Helper macro for a tree node type declaration
6249 #define CV_TREE_NODE_FIELDS(node_type) \
6250 int flags; /* micsellaneous flags */ \
6251 int header_size; /* size of sequence header */ \
6252 struct node_type* h_prev; /* previous sequence */ \
6253 struct node_type* h_next; /* next sequence */ \
6254 struct node_type* v_prev; /* 2nd previous sequence */ \
6255 struct node_type* v_next; /* 2nd next sequence */
6259 The macro \texttt{CV\_TREE\_NODE\_FIELDS()} is used to declare structures
6260 that can be organized into hierarchical strucutures (trees), such as
6261 \cross{CvSeq} - the basic type for all dynamical structures. The trees
6262 made of nodes declared using this macro can be processed using the
6263 functions described below in this section.
6265 \cvstruct{CvTreeNodeIterator}\label{CvTreeNodeIterator}
6267 Opens existing or creates new file storage
6271 typedef struct CvTreeNodeIterator
6281 The structure \cross{CvTreeNodeIterator} is used to traverse trees. The tree node declaration should start with 'CV\_TREE\_NODE\_FIELDS(...)' macro.
6283 \cvfunc{InitTreeNodeIterator}\label{InitTreeNodeIterator}
6285 Initializes tree node iterator
6289 void cvInitTreeNodeIterator( \par CvTreeNodeIterator* tree\_iterator,\par const void* first,\par int max\_level );
6294 \cvarg{tree\_iterator}{Tree iterator initialized by the function}
6295 \cvarg{first}{The initial node to start traversing from}
6296 \cvarg{max\_level}{The maximal level of the tree (\texttt{first} node assumed to be at the first level) to traverse up to. For example, 1 means that only nodes at the same level as \texttt{first} should be visited, 2 means that the nodes on the same level as \texttt{first} and their direct children should be visited etc.}
6299 The function \texttt{cvInitTreeNodeIterator} initializes tree iterator. The tree is traversed in depth-first order.
6301 \cvfunc{NextTreeNode}\label{NextTreeNode}
6303 Returns the currently observed node and moves iterator toward the next node
6307 void* cvNextTreeNode( CvTreeNodeIterator* tree\_iterator );
6312 \cvarg{tree\_iterator}{Tree iterator initialized by the function}
6316 The function \texttt{cvNextTreeNode} returns the currently observed node and then updates the iterator - moves it toward the next node. In other words, the function behavior is similar to *p++ expression on usual C pointer or C++ collection iterator. The function returns NULL if there is no more nodes.
6319 \cvfunc{PrevTreeNode}\label{PrevTreeNode}
6321 Returns the currently observed node and moves iterator toward the previous node
6325 void* cvPrevTreeNode( CvTreeNodeIterator* tree\_iterator );
6330 \cvarg{tree\_iterator}{Tree iterator initialized by the function}
6334 The function \texttt{cvPrevTreeNode} returns the currently observed node and then updates the iterator - moves it toward the previous node. In other words, the function behavior is similar to *p-- expression on usual C pointer or C++ collection iterator. The function returns NULL if there is no more nodes.
6337 \cvfunc{TreeToNodeSeq}\label{TreeToNodeSeq}
6339 Gathers all node pointers to the single sequence
6343 CvSeq* cvTreeToNodeSeq( \par const void* first,\par int header\_size,\par CvMemStorage* storage );
6348 \cvarg{first}{The initial tree node}
6349 \cvarg{header\_size}{Header size of the created sequence (sizeof(CvSeq) is the most used value)}
6350 \cvarg{storage}{Container for the sequence}
6353 The function \texttt{cvTreeToNodeSeq} puts pointers of all nodes reacheable from \texttt{first} to the single sequence. The pointers are written subsequently in the depth-first order.
6355 \cvfunc{InsertNodeIntoTree}\label{InsertNodeIntoTree}
6357 Adds new node to the tree
6361 void cvInsertNodeIntoTree( \par void* node,\par void* parent,\par void* frame );
6366 \cvarg{node}{The inserted node}
6367 \cvarg{parent}{The parent node that is already in the tree}
6368 \cvarg{frame}{The top level node. If \texttt{parent} and \texttt{frame} are the same, \texttt{v\_prev} field of \texttt{node} is set to NULL rather than \texttt{parent}.}
6371 The function \texttt{cvInsertNodeIntoTree} adds another node into tree. The function does not allocate any memory, it can only modify links of the tree nodes.
6373 \cvfunc{RemoveNodeFromTree}\label{RemoveNodeFromTree}
6375 Removes node from tree
6379 void cvRemoveNodeFromTree( \par void* node,\par void* frame );
6384 \cvarg{node}{The removed node}
6385 \cvarg{frame}{The top level node. If 'node->v\_prev = NULL' and 'node->h\_prev' is NULL (i.e. if \texttt{node} is the first child of \texttt{frame}), 'frame->v\_next' is set to 'node->h\_next' (i.e. the first child or frame is changed).}
6388 The function \texttt{cvRemoveNodeFromTree} removes node from tree. The function does not deallocate any memory, it can only modify links of the tree nodes.
6390 \section{Drawing Functions}
6392 Drawing functions work with matrices/images or arbitrary depth.
6393 Antialiasing is implemented only for 8-bit images. All the functions
6394 include parameter color that means rgb value (that may be constructed
6395 with \texttt{CV\_RGB} macro or \texttt{cvScalar} function) for color
6396 images and brightness for grayscale images.
6398 If a drawn figure is partially or completely outside the image, it
6399 is clipped. For color images the order channel is: Blue Green Red
6400 ... If one needs a different channel order, it is possible to
6401 construct color via \texttt{cvScalar} with the particular channel
6402 order, or convert the image before and/or after drawing in it with
6403 \cross{CvtColor} or \cross{Transform}.
6405 \subsection{Curves and Shapes}
6407 \cvfunc{CV\_RGB}\label{CV_RGB}
6409 Constructs a color value
6412 \#define CV\_RGB( r, g, b ) cvScalar( (b), (g), (r) )
6415 \cvfunc{Line}\label{Line}
6417 Draws a line segment connecting two points
6420 void cvLine( \par CvArr* img,\par CvPoint pt1,\par CvPoint pt2,\par CvScalar color,\par int thickness=1,\par int line\_type=8,\par int shift=0 );
6424 \cvarg{img}{The image}
6425 \cvarg{pt1}{First point of the line segment}
6426 \cvarg{pt2}{Second point of the line segment}
6427 \cvarg{color}{Line color}
6428 \cvarg{thickness}{Line thickness}
6429 \cvarg{line\_type}{Type of the line:
6431 \cvarg{8}{(or omitted) 8-connected line.}
6432 \cvarg{4}{4-connected line.}
6433 \cvarg{CV\_AA}{antialiased line.}
6435 \cvarg{shift}{Number of fractional bits in the point coordinates}
6438 The function \texttt{cvLine} draws the line segment between
6439 \texttt{pt1} and \texttt{pt2} points in the image. The line is
6440 clipped by the image or ROI rectangle. For non-antialiased lines
6441 with integer coordinates the 8-connected or 4-connected Bresenham
6442 algorithm is used. Thick lines are drawn with rounding endings.
6443 Antialiased lines are drawn using Gaussian filtering. To specify
6444 the line color, the user may use the macro
6445 \texttt{CV\_RGB( r, g, b )}.
6447 \cvfunc{Rectangle}\label{Rectangle}
6449 Draws simple, thick or filled rectangle
6453 void cvRectangle( \par CvArr* img,\par CvPoint pt1,\par CvPoint pt2,\par CvScalar color,\par int thickness=1,\par int line\_type=8,\par int shift=0 );
6459 \cvarg{pt1}{One of the rectangle vertices}
6460 \cvarg{pt2}{Opposite rectangle vertex}
6461 \cvarg{color}{Line color (RGB) or brightness (grayscale image)}
6462 \cvarg{thickness}{Thickness of lines that make up the rectangle. Negative values, e.g. CV\_FILLED, make the function to draw a filled rectangle.}
6463 \cvarg{line\_type}{Type of the line, see \cross{Line} description}
6464 \cvarg{shift}{Number of fractional bits in the point coordinates}
6467 The function \texttt{cvRectangle} draws a rectangle with two opposite corners \texttt{pt1} and \texttt{pt2}.
6469 \cvfunc{Circle}\label{Circle}
6475 void cvCircle( \par CvArr* img,\par CvPoint center,\par int radius,\par CvScalar color,\par int thickness=1,\par int line\_type=8,\par int shift=0 );
6480 \cvarg{img}{Image where the circle is drawn}
6481 \cvarg{center}{Center of the circle}
6482 \cvarg{radius}{Radius of the circle}
6483 \cvarg{color}{Circle color}
6484 \cvarg{thickness}{Thickness of the circle outline if positive, otherwise indicates that a filled circle has to be drawn}
6485 \cvarg{line\_type}{Type of the circle boundary, see \cross{Line} description}
6486 \cvarg{shift}{Number of fractional bits in the center coordinates and radius value}
6489 The function \texttt{cvCircle} draws a simple or filled circle with
6490 given center and radius. The circle is clipped by ROI rectangle.
6491 To specify the circle color, the user may use the macro
6492 \texttt{CV\_RGB( r, g, b )}.
6494 \cvfunc{Ellipse}\label{Ellipse}
6496 Draws simple or thick elliptic arc or fills ellipse sector
6500 void cvEllipse( \par CvArr* img,\par CvPoint center,\par CvSize axes,\par double angle,\par double start\_angle,\par double end\_angle,\par CvScalar color,\par int thickness=1,\par int line\_type=8,\par int shift=0 );
6505 \cvarg{img}{The image}
6506 \cvarg{center}{Center of the ellipse}
6507 \cvarg{axes}{Length of the ellipse axes}
6508 \cvarg{angle}{Rotation angle}
6509 \cvarg{start\_angle}{Starting angle of the elliptic arc}
6510 \cvarg{end\_angle}{Ending angle of the elliptic arc.}
6511 \cvarg{color}{Ellipse color}
6512 \cvarg{thickness}{Thickness of the ellipse arc outline if positive, otherwise indicates that a filled ellipse sector has to be drawn}
6513 \cvarg{line\_type}{Type of the ellipse boundary, see \cross{Line} description}
6514 \cvarg{shift}{Number of fractional bits in the center coordinates and axes' values}
6517 The function \texttt{cvEllipse} draws a simple or thick elliptic
6518 arc or fills an ellipse sector. The arc is clipped by ROI rectangle.
6519 A piecewise-linear approximation is used for antialiased arcs and
6520 thick arcs. All the angles are given in degrees. The picture below
6521 explains the meaning of the parameters.
6523 Parameters of Elliptic Arc
6525 \includegraphics[width=0.5\textwidth]{pics/ellipse.png}
6527 \cvfunc{FillPoly}\label{FillPoly}
6529 Fills polygons interior
6533 void cvFillPoly( \par CvArr* img,\par CvPoint** pts,\par int* npts,\par int contours,\par CvScalar color,\par int line\_type=8,\par int shift=0 );
6539 \cvarg{pts}{Array of pointers to polygons}
6540 \cvarg{npts}{Array of polygon vertex counters}
6541 \cvarg{contours}{Number of contours that bind the filled region}
6542 \cvarg{color}{Polygon color}
6543 \cvarg{line\_type}{Type of the polygon boundaries, see \cross{Line} description}
6544 \cvarg{shift}{Number of fractional bits in the vertex coordinates}
6548 The function \texttt{cvFillPoly} fills an area bounded by several
6549 polygonal contours. The function fills complex areas, for example,
6550 areas with holes, contour self-intersection, etc.
6552 \cvfunc{FillConvexPoly}\label{FillConvexPoly}
6554 Fills convex polygon
6558 void cvFillConvexPoly( \par CvArr* img,\par CvPoint* pts,\par int npts,\par CvScalar color,\par int line\_type=8,\par int shift=0 );
6564 \cvarg{pts}{Array of pointers to a single polygon}
6565 \cvarg{npts}{Polygon vertex counter}
6566 \cvarg{color}{Polygon color}
6567 \cvarg{line\_type}{Type of the polygon boundaries, see \cross{Line} description}
6568 \cvarg{shift}{Number of fractional bits in the vertex coordinates}
6571 The function \texttt{cvFillConvexPoly} fills convex polygon interior.
6572 This function is much faster than The function \texttt{cvFillPoly}
6573 and can fill not only the convex polygons but any monotonic polygon,
6574 i.e. a polygon whose contour intersects every horizontal line (scan
6575 line) twice at the most.
6578 \cvfunc{PolyLine}\label{PolyLine}
6580 Draws simple or thick polygons
6584 void cvPolyLine( \par CvArr* img,\par CvPoint** pts,\par int* npts,\par int contours,\par int is\_closed,\par CvScalar color,\par int thickness=1,\par int line\_type=8,\par int shift=0 );
6590 \cvarg{pts}{Array of pointers to polylines}
6591 \cvarg{npts}{Array of polyline vertex counters}
6592 \cvarg{contours}{Number of polyline contours}
6593 \cvarg{is\_closed}{Indicates whether the polylines must be drawn
6594 closed. If closed, the function draws the line from the last vertex
6595 of every contour to the first vertex.}
6596 \cvarg{color}{Polyline color}
6597 \cvarg{thickness}{Thickness of the polyline edges}
6598 \cvarg{line\_type}{Type of the line segments, see \cross{Line} description}
6599 \cvarg{shift}{Number of fractional bits in the vertex coordinates}
6602 The function \texttt{cvPolyLine} draws a single or multiple polygonal curves.
6606 \cvfunc{InitFont}\label{InitFont}
6608 Initializes font structure
6611 void cvInitFont( \par CvFont* font,\par int font\_face,\par double hscale,\par double vscale,\par double shear=0,\par int thickness=1,\par int line\_type=8 );
6615 \cvarg{font}{Pointer to the font structure initialized by the function}
6616 \cvarg{font\_face}{Font name identifier. Only a subset of Hershey fonts \url{http://sources.isc.org/utils/misc/hershey-font.txt} are supported now:
6618 \cvarg{CV\_FONT\_HERSHEY\_SIMPLEX}{normal size sans-serif font}
6619 \cvarg{CV\_FONT\_HERSHEY\_PLAIN}{small size sans-serif font}
6620 \cvarg{CV\_FONT\_HERSHEY\_DUPLEX}{normal size sans-serif font (more complex than \texttt{CV\_FONT\_HERSHEY\_SIMPLEX})}
6621 \cvarg{CV\_FONT\_HERSHEY\_COMPLEX}{normal size serif font}
6622 \cvarg{CV\_FONT\_HERSHEY\_TRIPLEX}{normal size serif font (more complex than \texttt{CV\_FONT\_HERSHEY\_COMPLEX})}
6623 \cvarg{CV\_FONT\_HERSHEY\_COMPLEX\_SMALL}{smaller version of \texttt{CV\_FONT\_HERSHEY\_COMPLEX}}
6624 \cvarg{CV\_FONT\_HERSHEY\_SCRIPT\_SIMPLEX}{hand-writing style font}
6625 \cvarg{CV\_FONT\_HERSHEY\_SCRIPT\_COMPLEX}{more complex variant of \texttt{CV\_FONT\_HERSHEY\_SCRIPT\_SIMPLEX}}
6627 The parameter can be composited from one of the values above and optional \texttt{CV\_FONT\_ITALIC} flag, that means italic or oblique font.}
6628 \cvarg{hscale}{Horizontal scale. If equal to '1.0f', the characters have the original width depending on the font type. If equal to '0.5f', the characters are of half the original width.}
6629 \cvarg{vscale}{Vertical scale. If equal to '1.0f', the characters have the original height depending on the font type. If equal to '0.5f', the characters are of half the original height.}
6630 \cvarg{shear}{Approximate tangent of the character slope relative to the vertical line. Zero value means a non-italic font, '1.0f' means ' about 45 degrees ' slope, etc. thickness Thickness of lines composing letters outlines. The function \texttt{cvLine} is used for drawing letters.}
6631 \cvarg{thickness}{Thickness of the text strokes}
6632 \cvarg{line\_type}{Type of the strokes, see \cross{Line} description}
6635 The function \texttt{cvInitFont} initializes the font structure that can be passed to text rendering functions.
6638 \cvfunc{PutText}\label{PutText}
6644 void cvPutText( \par CvArr* img,\par const char* text,\par CvPoint org,\par const CvFont* font,\par CvScalar color );
6649 \cvarg{img}{Input image}
6650 \cvarg{text}{String to print}
6651 \cvarg{org}{Coordinates of the bottom-left corner of the first letter}
6652 \cvarg{font}{Pointer to the font structure}
6653 \cvarg{color}{Text color}
6657 The function \texttt{cvPutText} renders the text in the image with
6658 the specified font and color. The printed text is clipped by ROI
6659 rectangle. Symbols that do not belong to the specified font are
6660 replaced with the rectangle symbol.
6662 \cvfunc{GetTextSize}\label{GetTextSize}
6664 Retrieves width and height of text string
6668 void cvGetTextSize( \par const char* text\_string,\par const CvFont* font,\par CvSize* text\_size,\par int* baseline );
6673 \cvarg{font}{Pointer to the font structure}
6674 \cvarg{text\_string}{Input string}
6675 \cvarg{text\_size}{Resultant size of the text string. Height of the text does not include the height of character parts that are below the baseline.}
6676 \cvarg{baseline}{y-coordinate of the baseline relatively to the bottom-most text point}
6679 The function \texttt{cvGetTextSize} calculates the binding rectangle for the given text string when a specified font is used.
6681 \subsection{Point Sets and Contours}
6683 \cvfunc{DrawContours}\label{DrawContours}
6685 Draws contour outlines or interiors in the image
6689 void cvDrawContours( \par CvArr *img,\par CvSeq* contour,\par CvScalar external\_color,\par CvScalar hole\_color,\par int max\_level,\par int thickness=1,\par int line\_type=8 );
6694 \cvarg{img}{Image where the contours are to be drawn. Like in any other drawing function, the contours are clipped with the ROI.}
6695 \cvarg{contour}{Pointer to the first contour}
6696 \cvarg{external\_color}{Color of the external contours}
6697 \cvarg{hole\_color}{Color of internal contours (holes)}
6698 \cvarg{max\_level}{Maximal level for drawn contours. If 0, only
6699 \texttt{contour} is drawn. If 1, the contour and all contours after
6700 it on the same level are drawn. If 2, all contours after and all
6701 contours one level below the contours are drawn, etc. If the value
6702 is negative, the function does not draw the contours following after
6703 \texttt{contour} but draws child contours of \texttt{contour} up
6704 to $ |\texttt{max\_level}|-1$ level.}
6705 \cvarg{thickness}{Thickness of lines the contours are drawn with.
6706 If it is negative (e.g. =CV\_FILLED), the contour interiors are
6708 \cvarg{line\_type}{Type of the contour segments, see \cross{Line} description}
6711 The function \texttt{cvDrawContours} draws contour outlines in the image if $\texttt{thickness} \ge 0$ or fills area bounded by the contours if $ \texttt{thickness}<0$.
6713 Example. Connected component detection via contour functions
6718 #include "highgui.h"
6720 int main( int argc, char** argv )
6723 // the first command line parameter must be file name of binary (black-n-white) image
6724 if( argc == 2 && (src=cvLoadImage(argv[1], 0))!= 0)
6726 IplImage* dst = cvCreateImage( cvGetSize(src), 8, 3 );
6727 CvMemStorage* storage = cvCreateMemStorage(0);
6730 cvThreshold( src, src, 1, 255, CV_THRESH_BINARY );
6731 cvNamedWindow( "Source", 1 );
6732 cvShowImage( "Source", src );
6734 cvFindContours( src, storage, &contour, sizeof(CvContour), CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE );
6737 for( ; contour != 0; contour = contour->h_next )
6739 CvScalar color = CV_RGB( rand()&255, rand()&255, rand()&255 );
6740 /* replace CV_FILLED with 1 to see the outlines */
6741 cvDrawContours( dst, contour, color, color, -1, CV_FILLED, 8 );
6744 cvNamedWindow( "Components", 1 );
6745 cvShowImage( "Components", dst );
6752 Replace \texttt{CV\_FILLED} with 1 in the sample below to see the contour outlines
6754 \cvfunc{InitLineIterator}\label{InitLineIterator}
6756 Initializes line iterator
6760 int cvInitLineIterator( \par const CvArr* image,\par CvPoint pt1,\par CvPoint pt2,\par CvLineIterator* line\_iterator,\par int connectivity=8,\par int left\_to\_right=0 );
6765 \cvarg{image}{Image to sample the line from}
6766 \cvarg{pt1}{First ending point of the line segment}
6767 \cvarg{pt2}{Second ending point of the line segment}
6768 \cvarg{line\_iterator}{Pointer to the line iterator state structure}
6769 \cvarg{connectivity}{The scanned line connectivity, 4 or 8
6770 be always scanned from the left-most point to the right-most out
6771 of \texttt{pt1} and \texttt{pt2} ($ \texttt{left\_to\_right} \ne 0$), or it
6772 is scanned in the specified order, from \texttt{pt1} to \texttt{pt2}
6773 ($ \texttt{left\_to\_right} = 0 $ )}
6776 The function \texttt{cvInitLineIterator} initializes the line
6777 iterator and returns the number of pixels between two end points.
6778 Both points must be inside the image. After the iterator has been
6779 initialized, all the points on the raster line that connects the
6780 two ending points may be retrieved by successive calls of
6781 \texttt{CV\_NEXT\_LINE\_POINT} point. The points on the line are
6782 calculated one by one using 4-connected or 8-connected Bresenham
6785 Example. Using line iterator to calculate sum of pixel values along the color line
6789 CvScalar sum_line_pixels( IplImage* image, CvPoint pt1, CvPoint pt2 )
6791 CvLineIterator iterator;
6792 int blue_sum = 0, green_sum = 0, red_sum = 0;
6793 int count = cvInitLineIterator( image, pt1, pt2, &iterator, 8, 0 );
6795 for( int i = 0; i < count; i++ ){
6796 blue_sum += iterator.ptr[0];
6797 green_sum += iterator.ptr[1];
6798 red_sum += iterator.ptr[2];
6799 CV_NEXT_LINE_POINT(iterator);
6801 /* print the pixel coordinates: demonstrates how to calculate the coordinates */
6804 /* assume that ROI is not set, otherwise need to take it into account. */
6805 offset = iterator.ptr - (uchar*)(image->imageData);
6806 y = offset/image->widthStep;
6807 x = (offset - y*image->widthStep)/(3*sizeof(uchar) /* size of pixel */);
6808 printf("(%d,%d)\n", x, y );
6811 return cvScalar( blue_sum, green_sum, red_sum );
6816 \cvfunc{ClipLine}\label{ClipLine}
6818 Clips the line against the image rectangle
6822 int cvClipLine( \par CvSize img\_size,\par CvPoint* pt1,\par CvPoint* pt2 );
6827 \cvarg{img\_size}{Size of the image}
6828 \cvarg{pt1}{First ending point of the line segment. It is modified by the function.}
6829 \cvarg{pt2}{Second ending point of the line segment. It is modified by the function.}
6832 The function \texttt{cvClipLine} calculates a part of the line
6833 segment which is entirely in the image. It returns 0 if the line
6834 segment is completely outside the image and 1 otherwise.
6836 \cvfunc{Ellipse2Poly}\label{Ellipse2Poly}
6838 Approximates elliptic arc with polyline
6842 int cvEllipse2Poly( \par CvPoint center,\par CvSize axes,\par int angle,\par int arc\_start,\par int arc\_end,\par CvPoint* pts,\par int delta );
6847 \cvarg{center}{Center of the arc}
6848 \cvarg{axes}{Half-sizes of the arc. See \cross{Ellipse}.}
6849 \cvarg{angle}{Rotation angle of the ellipse in degrees. See \cross{Ellipse}}
6850 \cvarg{start\_angle}{Starting angle of the elliptic arc}
6851 \cvarg{end\_angle}{Ending angle of the elliptic arc}
6852 \cvarg{pts}{The array of points, filled by the function}
6853 \cvarg{delta}{Angle between the subsequent polyline vertices, approximation accuracy. So, the total number of output points will
6854 $ \lceil( \texttt{end\_angle} - \texttt{start\_angle} ) / \texttt{delta} \rceil + 1 $
6858 The function \texttt{cvEllipse2Poly} computes vertices of the polyline that approximates the specified elliptic arc. It is used by \cross{Ellipse}.
6860 \section{Data Persistence and RTTI}
6863 \subsection{File Storage}
6865 \cvstruct{CvFileStorage}\label{CvFileStorage}
6871 typedef struct CvFileStorage
6873 ... // hidden fields
6878 The structure \cross{CvFileStorage} is "black box" representation
6879 of file storage that is associated with a file on disk. Several
6880 functions that are described below take \texttt{CvFileStorage} on
6881 input and allow user to save or to load hierarchical collections
6882 that consist of scalar values, standard CXCore objects (such as
6883 matrices, sequences, graphs) and user-defined objects.
6885 CXCore can read and write data in XML (http://www.w3c.org/XML) or YAML
6886 (http://www.yaml.org) formats. Below is the example of $3 \times 3$
6887 floating-point identity matrix \texttt{A}, stored in XML and YAML files
6888 using CXCore functions:
6893 <?xml version="1.0">
6895 <A type_id="opencv-matrix">
6899 <data>1. 0. 0. 0. 1. 0. 0. 0. 1.</data>
6912 data: [ 1., 0., 0., 0., 1., 0., 0., 0., 1.]
6915 As it can be seen from the examples, XML uses nested tags to represent
6916 hierarchy, while YAML uses indentation for that purpose (similarly
6917 to Python programming language).
6919 The same CXCore functions can read and write data in both formats,
6920 the particular format is determined by the extension of the opened
6921 file, .xml for XML files and .yml or .yaml for YAML.
6924 \cvstruct{CvFileNode}\label{CvFileNode}
6930 /* file node type */
6931 #define CV\_NODE\_NONE 0
6932 #define CV\_NODE\_INT 1
6933 #define CV\_NODE\_INTEGER CV\_NODE\_INT
6934 #define CV\_NODE\_REAL 2
6935 #define CV\_NODE\_FLOAT CV\_NODE\_REAL
6936 #define CV\_NODE\_STR 3
6937 #define CV\_NODE\_STRING CV\_NODE\_STR
6938 #define CV\_NODE\_REF 4 /* not used */
6939 #define CV\_NODE\_SEQ 5
6940 #define CV\_NODE\_MAP 6
6941 #define CV\_NODE\_TYPE\_MASK 7
6943 /* optional flags */
6944 #define CV\_NODE\_USER 16
6945 #define CV\_NODE\_EMPTY 32
6946 #define CV\_NODE\_NAMED 64
6948 #define CV\_NODE\_TYPE(tag) ((tag) & CV\_NODE\_TYPE\_MASK)
6950 #define CV\_NODE\_IS\_INT(tag) (CV\_NODE\_TYPE(tag) == CV\_NODE\_INT)
6951 #define CV\_NODE\_IS\_REAL(tag) (CV\_NODE\_TYPE(tag) == CV\_NODE\_REAL)
6952 #define CV\_NODE\_IS\_STRING(tag) (CV\_NODE\_TYPE(tag) == CV\_NODE\_STRING)
6953 #define CV\_NODE\_IS\_SEQ(tag) (CV\_NODE\_TYPE(tag) == CV\_NODE\_SEQ)
6954 #define CV\_NODE\_IS\_MAP(tag) (CV\_NODE\_TYPE(tag) == CV\_NODE\_MAP)
6955 #define CV\_NODE\_IS\_COLLECTION(tag) (CV\_NODE\_TYPE(tag) >= CV\_NODE\_SEQ)
6956 #define CV\_NODE\_IS\_FLOW(tag) (((tag) & CV\_NODE\_FLOW) != 0)
6957 #define CV\_NODE\_IS\_EMPTY(tag) (((tag) & CV\_NODE\_EMPTY) != 0)
6958 #define CV\_NODE\_IS\_USER(tag) (((tag) & CV\_NODE\_USER) != 0)
6959 #define CV\_NODE\_HAS\_NAME(tag) (((tag) & CV\_NODE\_NAMED) != 0)
6961 #define CV\_NODE\_SEQ\_SIMPLE 256
6962 #define CV\_NODE\_SEQ\_IS\_SIMPLE(seq) (((seq)->flags & CV\_NODE\_SEQ\_SIMPLE) != 0)
6964 typedef struct CvString
6971 /* all the keys (names) of elements in the readed file storage
6972 are stored in the hash to speed up the lookup operations */
6973 typedef struct CvStringHashNode
6977 struct CvStringHashNode* next;
6981 /* basic element of the file storage - scalar or collection */
6982 typedef struct CvFileNode
6985 struct CvTypeInfo* info; /* type information
6986 (only for user-defined object, for others it is 0) */
6989 double f; /* scalar floating-point number */
6990 int i; /* scalar integer number */
6991 CvString str; /* text string */
6992 CvSeq* seq; /* sequence (ordered collection of file nodes) */
6993 struct CvMap* map; /* map (collection of named file nodes) */
7000 The structure is used only for retrieving data from file storage
7001 (i.e. for loading data from file). When data is written to file,
7002 it is done sequentially, with minimal buffering. No data is stored
7003 in the file storage.
7005 In opposite, when data is read from file, the whole file is parsed
7006 and represented in memory as a tree. Every node of the tree is
7007 represented by \cross{CvFileNode}. Type of the file node \texttt{N}
7008 can be retrieved as \texttt{CV\_NODE\_TYPE(N->tag)}. Some file nodes
7009 (leaves) are scalars: text strings, integer or floating-point
7010 numbers. Other file nodes are collections of file nodes, which can
7011 be scalars or collections in their turn. There are two types of
7012 collections: sequences and maps (we use YAML notation, however, the
7013 same is true for XML streams). Sequences (do not mix them with
7014 \cross{CvSeq}) are ordered collections of unnamed file nodes, maps
7015 are unordered collections of named file nodes. Thus, elements of
7016 sequences are accessed by index (\cross{GetSeqElem}), while elements
7017 of maps are accessed by name (\cross{GetFileNodeByName}). The table
7018 below describes the different types of a file node:
7020 \begin{tabular}{| c | c | c |}
7022 Type & \texttt{CV\_NODE\_TYPE(node->tag)} & Value\\ \hline \hline
7023 Integer & \texttt{CV\_NODE\_INT} & \texttt{node->data.i} \\ \hline
7024 Floating-point & \texttt{CV\_NODE\_REAL} & \texttt{node->data.f} \\ \hline
7025 Text string & \texttt{CV\_NODE\_STR} & \texttt{node->data.str.ptr} \\ \hline
7026 Sequence & \texttt{CV\_NODE\_SEQ} & \texttt{node->data.seq} \\ \hline
7027 Map & \texttt{CV\_NODE\_MAP} & \texttt{node->data.map} (see below)\\ \hline
7030 There is no need to access \texttt{map} field directly (BTW,
7031 \texttt{CvMap} is a hidden structure). The elements of the map can
7032 be retrieved with \cross{GetFileNodeByName} function that takes
7033 pointer to the "map" file node.
7035 A user (custom) object is instance of either one of standard CxCore
7036 types, such as \cross{CvMat}, \cross{CvSeq} etc., or any type
7037 registered with \cross{RegisterTypeInfo}. Such an object is initially
7038 represented in file as a map (as shown in XML and YAML sample files
7039 above), after file storage has been opened and parsed. Then the
7040 object can be decoded (coverted to the native representation) by
7041 request - when user calls \cross{Read} or \cross{ReadByName} function.
7044 \cvstruct{CvAttrList}\label{CvAttrList}
7050 typedef struct CvAttrList
7052 const char** attr; /* NULL-terminated array of (attribute\_name,attribute\_value) pairs */
7053 struct CvAttrList* next; /* pointer to next chunk of the attributes list */
7057 /* initializes CvAttrList structure */
7058 inline CvAttrList cvAttrList( const char** attr=NULL, CvAttrList* next=NULL );
7060 /* returns attribute value or 0 (NULL) if there is no such attribute */
7061 const char* cvAttrValue( const CvAttrList* attr, const char* attr\_name );
7065 In the current implementation attributes are used to pass extra parameters when writing user objects (see \cross{Write}). XML attributes inside tags are not supported, besides the object type specification (\texttt{type\_id} attribute).
7067 \cvfunc{OpenFileStorage}\label{OpenFileStorage}
7069 Opens file storage for reading or writing data
7073 CvFileStorage* cvOpenFileStorage( \par const char* filename,\par CvMemStorage* memstorage,\par int flags );
7078 \cvarg{filename}{Name of the file associated with the storage}
7079 \cvarg{memstorage}{Memory storage used for temporary data and for
7080 storing dynamic structures, such as \cross{CvSeq} or \cross{CvGraph}.
7081 If it is NULL, a temporary memory storage is created and used.}
7082 \cvarg{flags}{Can be one of the following:
7084 \cvarg{CV\_STORAGE\_READ}{the storage is open for reading}
7085 \cvarg{CV\_STORAGE\_WRITE}{the storage is open for writing}
7089 The function \texttt{cvOpenFileStorage} opens file storage for
7090 reading or writing data. In the latter case a new file is created
7091 or existing file is rewritten. Type of the read of written file is
7092 determined by the filename extension: '.xml' for \texttt{XML}
7093 and '.yml' or '.yaml' for \texttt{YAML}. The function
7094 returns pointer to \cross{CvFileStorage} structure.
7096 \cvfunc{ReleaseFileStorage}\label{ReleaseFileStorage}
7098 Releases file storage
7102 void cvReleaseFileStorage( CvFileStorage** fs );
7107 \cvarg{fs}{Double pointer to the released file storage}
7111 The function \texttt{cvReleaseFileStorage} closes the file associated with the storage and releases all the temporary structures. It must be called after all I/O operations with the storage are finished.
7114 \subsection{Writing Data}
7116 \cvfunc{StartWriteStruct}\label{StartWriteStruct}
7118 Starts writing a new structure
7122 void cvStartWriteStruct( CvFileStorage* fs,\par const char* name,\par int struct\_flags,\par const char* type\_name=NULL,\par CvAttrList attributes=cvAttrList( \par));
7127 \cvarg{fs}{File storage}
7128 \cvarg{name}{Name of the written structure. The structure can be accessed by this name when the storage is read.}
7129 \cvarg{struct\_flags}{A combination one of the following values:
7131 \cvarg{CV\_NODE\_SEQ}{the written structure is a sequence (see discussion of \cross{CvFileStorage}), that is, its elements do not have a name.}
7132 \cvarg{CV\_NODE\_MAP}{the written structure is a map (see discussion of \cross{CvFileStorage}), that is, all its elements have names. One and only one of the two above flags must be specified}
7134 \cvarg{CV\_NODE\_FLOW}{the optional flag that has sense only for YAML streams. It means that the structure is written as a flow (not as a block), which is more compact. It is recommended to use this flag for structures or arrays whose elements are all scalars.}
7135 \cvarg{type\_name}{Optional parameter - the object type name. In
7136 case of XML it is written as \texttt{type\_id} attribute of the
7137 structure opening tag. In case of YAML it is written after a colon
7138 following the structure name (see the example in \cross{CvFileStorage}
7139 description). Mainly it comes with user objects. When the storage
7140 is read, the encoded type name is used to determine the object type
7141 (see \cross{CvTypeInfo} and \cross{FindTypeInfo}).}
7142 \cvarg{attributes}{This parameter is not used in the current implementation}
7145 The function \texttt{cvStartWriteStruct} starts writing a compound
7146 structure (collection) that can be a sequence or a map. After all
7147 the structure fields, which can be scalars or structures, are
7148 written, \cross{EndWriteStruct} should be called. The function can
7149 be used to group some objects or to implement \texttt{write}
7150 function for a some user object (see \cross{CvTypeInfo}).
7152 \cvfunc{EndWriteStruct}\label{EndWriteStruct}
7154 Ends writing a structure
7158 void cvEndWriteStruct( CvFileStorage* fs );
7163 \cvarg{fs}{File storage}
7167 The function \texttt{cvEndWriteStruct} finishes the currently written structure.
7169 \cvfunc{WriteInt}\label{WriteInt}
7171 Writes an integer value
7175 void cvWriteInt( \par CvFileStorage* fs,\par const char* name,\par int value );
7180 \cvarg{fs}{File storage}
7181 \cvarg{name}{Name of the written value. Should be NULL if and only if the parent structure is a sequence.}
7182 \cvarg{value}{The written value}
7185 The function \texttt{cvWriteInt} writes a single integer value (with or without a name) to the file storage.
7187 \cvfunc{WriteReal}\label{WriteReal}
7189 Writes a floating-point value
7193 void cvWriteReal( \par CvFileStorage* fs,\par const char* name,\par double value );
7198 \cvarg{fs}{File storage}
7199 \cvarg{name}{Name of the written value. Should be NULL if and only if the parent structure is a sequence.}
7200 \cvarg{value}{The written value}
7203 The function \texttt{cvWriteReal} writes a single floating-point
7204 value (with or without a name) to the file storage. The special
7205 values are encoded: NaN (Not A Number) as .NaN, $ \pm \infty $ as +.Inf
7208 The following example shows how to use the low-level writing functions
7209 to store custom structures, such as termination criteria, without
7210 registering a new type.
7214 void write_termcriteria( CvFileStorage* fs, const char* struct_name,
7215 CvTermCriteria* termcrit )
7217 cvStartWriteStruct( fs, struct_name, CV_NODE_MAP, NULL, cvAttrList(0,0));
7218 cvWriteComment( fs, "termination criteria", 1 ); // just a description
7219 if( termcrit->type & CV_TERMCRIT_ITER )
7220 cvWriteInteger( fs, "max_iterations", termcrit->max_iter );
7221 if( termcrit->type & CV_TERMCRIT_EPS )
7222 cvWriteReal( fs, "accuracy", termcrit->epsilon );
7223 cvEndWriteStruct( fs );
7228 \cvfunc{WriteString}\label{WriteString}
7230 Writes a text string
7234 void cvWriteString( \par CvFileStorage* fs,\par const char* name,\par const char* str,\par int quote=0 );
7239 \cvarg{fs}{File storage}
7240 \cvarg{name}{Name of the written string . Should be NULL if and only if the parent structure is a sequence.}
7241 \cvarg{str}{The written text string}
7242 \cvarg{quote}{If non-zero, the written string is put in quotes, regardless of whether they are required or not. Otherwise, if the flag is zero, quotes are used only when they are required (e.g. when the string starts with a digit or contains spaces).}
7245 The function \texttt{cvWriteString} writes a text string to the file storage.
7247 \cvfunc{WriteComment}\label{WriteComment}
7253 void cvWriteComment( \par CvFileStorage* fs,\par const char* comment,\par int eol\_comment );
7258 \cvarg{fs}{File storage}
7259 \cvarg{comment}{The written comment, single-line or multi-line}
7260 \cvarg{eol\_comment}{If non-zero, the function tries to put the comment in the end of current line. If the flag is zero, if the comment is multi-line, or if it does not fit in the end of the current line, the comment starts from a new line.}
7263 The function \texttt{cvWriteComment} writes a comment into the file storage. The comments are skipped when the storage is read, so they may be used only for debugging or descriptive purposes.
7265 \cvfunc{StartNextStream}\label{StartNextStream}
7267 Starts the next stream
7271 void cvStartNextStream( CvFileStorage* fs );
7276 \cvarg{fs}{File storage}
7280 The function \texttt{cvStartNextStream} starts the next stream in the file storage. Both YAML and XML supports multiple "streams". This is useful for concatenating files or for resuming the writing process.
7283 \cvfunc{Write}\label{Write}
7289 void cvWrite( CvFileStorage* fs,\par const char* name,\par const void* ptr,\par CvAttrList attributes=cvAttrList( \par) );
7294 \cvarg{fs}{File storage}
7295 \cvarg{name}{Name, of the written object. Should be NULL if and only if the parent structure is a sequence.}
7296 \cvarg{ptr}{Pointer to the object}
7297 \cvarg{attributes}{The attributes of the object. They are specific for each particular type (see the dicsussion).}
7300 The function \texttt{cvWrite} writes the object to file storage. First, the appropriate type info is found using \cross{TypeOf}. Then, \texttt{write} method of the type info is called.
7302 Attributes are used to customize the writing procedure. The standard types support the following attributes (all the \texttt{*dt} attributes have the same format as in \cross{WriteRawData}):
7306 \cvarg{header\_dt}{description of user fields of the sequence header that follow CvSeq, or CvChain (if the sequence is Freeman chain) or CvContour (if the sequence is a contour or point sequence)}
7307 \cvarg{dt}{description of the sequence elements.}
7308 \cvarg{recursive}{if the attribute is present and is not equal to "0" or "false", the whole tree of sequences (contours) is stored.}
7312 \cvarg{header\_dt}{description of user fields of the graph header that follow CvGraph;}
7313 \cvarg{vertex\_dt}{description of user fields of graph vertices}
7314 \cvarg{edge\_dt}{description of user fields of graph edges (note, that edge weight is always written, so there is no need to specify it explicitly)}
7317 Below is the code that creates the YAML file shown in \texttt{CvFileStorage} description:
7323 int main( int argc, char** argv )
7325 CvMat* mat = cvCreateMat( 3, 3, CV\_32F );
7326 CvFileStorage* fs = cvOpenFileStorage( "example.yml", 0, CV\_STORAGE\_WRITE );
7328 cvSetIdentity( mat );
7329 cvWrite( fs, "A", mat, cvAttrList(0,0) );
7331 cvReleaseFileStorage( &fs );
7332 cvReleaseMat( &mat );
7339 \cvfunc{WriteRawData}\label{WriteRawData}
7341 Writes multiple numbers
7345 void cvWriteRawData( \par CvFileStorage* fs,\par const void* src,\par int len,\par const char* dt );
7350 \cvarg{fs}{File storage}
7351 \cvarg{src}{Pointer to the written array}
7352 \cvarg{len}{Number of the array elements to write}
7353 \cvarg{dt}{Specification of each array element that has the following format
7354 \texttt{([count]\{'u'|'c'|'w'|'s'|'i'|'f'|'d'\})...}
7355 where the characters correspond to fundamental C types:
7357 \cvarg{u}{8-bit unsigned number}
7358 \cvarg{c}{8-bit signed number}
7359 \cvarg{w}{16-bit unsigned number}
7360 \cvarg{s}{16-bit signed number}
7361 \cvarg{i}{32-bit signed number}
7362 \cvarg{f}{single precision floating-point number}
7363 \cvarg{d}{double precision floating-point number}
7364 \cvarg{r}{pointer. 32 lower bits of it are written as a signed integer. The type can be used to store structures with links between the elements.
7365 \texttt{count} is the optional counter of values of the certain type. For
7366 example, \texttt{2if} means that each array element is a structure
7367 of 2 integers, followed by a single-precision floating-point number. The
7368 equivalent notations of the above specification are '\texttt{iif}',
7369 '\texttt{2i1f}' etc. Other examples: \texttt{u} means that the
7370 array consists of bytes, \texttt{2d} - the array consists of pairs
7375 The function \texttt{cvWriteRawData} writes array, which elements consist
7376 of a single of multiple numbers. The function call can be replaced with
7377 a loop containing a few \cross{WriteInt} and \cross{WriteReal} calls, but
7378 a single call is more efficient. Note, that because none of the elements
7379 have a name, they should be written to a sequence rather than a map.
7381 \cvfunc{WriteFileNode}\label{WriteFileNode}
7383 Writes file node to another file storage
7387 void cvWriteFileNode( \par CvFileStorage* fs,\par const char* new\_node\_name,\par const CvFileNode* node,\par int embed );
7392 \cvarg{fs}{Destination file storage}
7393 \cvarg{new\_file\_node}{New name of the file node in the destination file storage. To keep the existing name, use \cross{cvGetFileNodeName}}
7394 \cvarg{node}{The written node}
7395 \cvarg{embed}{If the written node is a collection and this parameter is not zero, no extra level of hiararchy is created. Instead, all the elements of \texttt{node} are written into the currently written structure. Of course, map elements may be written only to map, and sequence elements may be written only to sequence.}
7398 The function \texttt{cvWriteFileNode} writes a copy of file node to file storage. The possible application of the function are: merging several file storages into one. Conversion between XML and YAML formats etc.
7400 \subsection{Reading Data}
7402 Data are retrieved from file storage in 2 steps: first, the file node
7403 containing the requested data is found; then, data is extracted from
7404 the node manually or using custom \texttt{read} method.
7406 \cvfunc{GetRootFileNode}\label{GetRootFileNode}
7408 Retrieves one of top-level nodes of the file storage
7412 CvFileNode* cvGetRootFileNode( \par const CvFileStorage* fs,\par int stream\_index=0 );
7417 \cvarg{fs}{File storage}
7418 \cvarg{stream\_index}{Zero-based index of the stream. See \cross{StartNextStream}. In most cases, there is only one stream in the file, however there can be several.}
7421 The function \texttt{cvGetRootFileNode} returns one of top-level file
7422 nodes. The top-level nodes do not have a name, they correspond to the
7423 streams, that are stored one after another in the file storage. If the
7424 index is out of range, the function returns NULL pointer, so all the
7425 top-level nodes may be iterated by subsequent calls to the function with
7426 'stream\_index=0,1,...', until NULL pointer is returned. This function
7427 may be used as a base for recursive traversal of the file storage.
7429 \cvfunc{GetFileNodeByName}\label{GetFileNodeByName}
7431 Finds node in the map or file storage
7435 CvFileNode* cvGetFileNodeByName( \par const CvFileStorage* fs,\par const CvFileNode* map,\par const char* name );
7440 \cvarg{fs}{File storage}
7441 \cvarg{map}{The parent map. If it is NULL, the function searches in all the top-level nodes (streams), starting from the first one.}
7442 \cvarg{name}{The file node name}
7446 The function \texttt{cvGetFileNodeByName} finds a file node by
7447 \texttt{name}. The node is searched either in \texttt{map} or, if the
7448 pointer is NULL, among the top-level file nodes of the storage. Using
7449 this function for maps and \cross{GetSeqElem} (or sequence reader)
7450 for sequences, it is possible to nagivate through the file storage. To
7451 speed up multiple queries for a certain key (e.g. in case of array
7452 of structures) one may use a pair of \cross{GetHashedKey} and
7453 \cross{GetFileNode}.
7455 \cvfunc{GetHashedKey}\label{GetHashedKey}
7457 Returns a unique pointer for given name
7461 CvStringHashNode* cvGetHashedKey( \par CvFileStorage* fs,\par const char* name,\par int len=-1,\par int create\_missing=0 );
7466 \cvarg{fs}{File storage}
7467 \cvarg{name}{Literal node name}
7468 \cvarg{len}{Length of the name (if it is known apriori), or -1 if it needs to be calculated}
7469 \cvarg{create\_missing}{Flag that specifies, whether an absent key should be added into the hash table, or not}
7472 The function \texttt{cvGetHashedKey} returns the unique pointer for
7473 each particular file node name. This pointer can be then passed to
7474 \cross{GetFileNode} function that is faster than \cross{GetFileNodeByName}
7475 because it compares text strings by comparing pointers rather than the
7478 Consider the following example: an array of points is encoded as a sequence of 2-entry maps, e.g.:
7491 Then, it is possible to get hashed "x" and "y" pointers to speed up decoding of the points.
7493 Example. Reading an array of structures from file storage
7499 int main( int argc, char** argv )
7501 CvFileStorage* fs = cvOpenFileStorage( "points.yml", 0, CV\_STORAGE\_READ );
7502 CvStringHashNode* x\_key = cvGetHashedNode( fs, "x", -1, 1 );
7503 CvStringHashNode* y\_key = cvGetHashedNode( fs, "y", -1, 1 );
7504 CvFileNode* points = cvGetFileNodeByName( fs, 0, "points" );
7506 if( CV\_NODE\_IS\_SEQ(points->tag) )
7508 CvSeq* seq = points->data.seq;
7509 int i, total = seq->total;
7511 cvStartReadSeq( seq, &reader, 0 );
7512 for( i = 0; i < total; i++ )
7514 CvFileNode* pt = (CvFileNode*)reader.ptr;
7515 #if 1 /* faster variant */
7516 CvFileNode* xnode = cvGetFileNode( fs, pt, x\_key, 0 );
7517 CvFileNode* ynode = cvGetFileNode( fs, pt, y\_key, 0 );
7518 assert( xnode && CV\_NODE\_IS\_INT(xnode->tag) &&
7519 ynode && CV\_NODE\_IS\_INT(ynode->tag));
7520 int x = xnode->data.i; // or x = cvReadInt( xnode, 0 );
7521 int y = ynode->data.i; // or y = cvReadInt( ynode, 0 );
7522 #elif 1 /* slower variant; does not use x\_key & y\_key */
7523 CvFileNode* xnode = cvGetFileNodeByName( fs, pt, "x" );
7524 CvFileNode* ynode = cvGetFileNodeByName( fs, pt, "y" );
7525 assert( xnode && CV\_NODE\_IS\_INT(xnode->tag) &&
7526 ynode && CV\_NODE\_IS\_INT(ynode->tag));
7527 int x = xnode->data.i; // or x = cvReadInt( xnode, 0 );
7528 int y = ynode->data.i; // or y = cvReadInt( ynode, 0 );
7529 #else /* the slowest yet the easiest to use variant */
7530 int x = cvReadIntByName( fs, pt, "x", 0 /* default value */ );
7531 int y = cvReadIntByName( fs, pt, "y", 0 /* default value */ );
7533 CV\_NEXT\_SEQ\_ELEM( seq->elem\_size, reader );
7534 printf("%d: (%d, %d)\n", i, x, y );
7537 cvReleaseFileStorage( &fs );
7543 Please note that, whatever method of accessing map you are using, it is
7544 still much slower than using plain sequences, for example, in the above
7545 sample, it is more efficient to encode the points as pairs of integers
7546 in the single numeric sequence.
7548 \cvfunc{GetFileNode}\label{GetFileNode}
7550 Finds node in the map or file storage
7554 CvFileNode* cvGetFileNode( \par CvFileStorage* fs,\par CvFileNode* map,\par const CvStringHashNode* key,\par int create\_missing=0 );
7559 \cvarg{fs}{File storage}
7560 \cvarg{map}{The parent map. If it is NULL, the function searches a top-level node. If both \texttt{map} and \texttt{key} are NULLs, the function returns the root file node - a map that contains top-level nodes.}
7561 \cvarg{key}{Unique pointer to the node name, retrieved with \cross{GetHashedKey}}
7562 \cvarg{create\_missing}{Flag that specifies, whether an absent node should be added to the map, or not}
7566 The function \texttt{cvGetFileNode} finds a file node. It is a faster version \cross{GetFileNodeByName} (see \cross{GetHashedKey} discussion). Also, the function can insert a new node, if it is not in the map yet (which is used by parsing functions).
7568 \cvfunc{GetFileNodeName}\label{GetFileNodeName}
7570 Returns name of file node
7574 const char* cvGetFileNodeName( const CvFileNode* node );
7579 \cvarg{node}{File node}
7583 The function \texttt{cvGetFileNodeName} returns name of the file node or NULL, if the file node does not have a name, or if \texttt{node} is \texttt{NULL}.
7586 \cvfunc{ReadInt}\label{ReadInt}
7588 Retrieves integer value from file node
7592 int cvReadInt( \par const CvFileNode* node,\par int default\_value=0 );
7597 \cvarg{node}{File node}
7598 \cvarg{default\_value}{The value that is returned if \texttt{node} is NULL}
7602 The function \texttt{cvReadInt} returns integer that is represented
7603 by the file node. If the file node is NULL, \texttt{default\_value}
7604 is returned (thus, it is convenient to call the function right after
7605 \cross{GetFileNode} without checking for NULL pointer), otherwise if
7606 the file node has type \texttt{CV\_NODE\_INT}, then \texttt{node->data.i} is
7607 returned, otherwise if the file node has type \texttt{CV\_NODE\_REAL},
7608 then \texttt{node->data.f} is converted to integer and returned, otherwise the
7609 result is not determined.
7611 \cvfunc{ReadIntByName}\label{ReadIntByName}
7613 Finds file node and returns its value
7617 int cvReadIntByName( \par const CvFileStorage* fs,\par const CvFileNode* map,\par const char* name,\par int default\_value=0 );
7622 \cvarg{fs}{File storage}
7623 \cvarg{map}{The parent map. If it is NULL, the function searches a top-level node.}
7624 \cvarg{name}{The node name}
7625 \cvarg{default\_value}{The value that is returned if the file node is not found}
7628 The function \texttt{cvReadIntByName} is a simple superposition of \cross{GetFileNodeByName} and \cross{ReadInt}.
7631 \cvfunc{ReadReal}\label{ReadReal}
7633 Retrieves floating-point value from file node
7637 double cvReadReal( \par const CvFileNode* node,\par double default\_value=0. );
7642 \cvarg{node}{File node}
7643 \cvarg{default\_value}{The value that is returned if \texttt{node} is NULL}
7646 The function \texttt{cvReadReal} returns floating-point value
7647 that is represented by the file node. If the file node is NULL,
7648 \texttt{default\_value} is returned (thus, it is convenient to call
7649 the function right after \cross{GetFileNode} without checking for NULL
7650 pointer), otherwise if the file node has type \texttt{CV\_NODE\_REAL},
7651 then \texttt{node->data.f} is returned, otherwise if the file node has type
7652 \texttt{CV\_NODE\_INT}, then 'node->data.f' is converted to floating-point
7653 and returned, otherwise the result is not determined.
7655 \cvfunc{ReadRealByName}\label{ReadRealByName}
7657 Finds file node and returns its value
7661 double cvReadRealByName( \par const CvFileStorage* fs,\par const CvFileNode* map,\par const char* name,\par double default\_value=0. );
7666 \cvarg{fs}{File storage}
7667 \cvarg{map}{The parent map. If it is NULL, the function searches a top-level node.}
7668 \cvarg{name}{The node name}
7669 \cvarg{default\_value}{The value that is returned if the file node is not found}
7672 The function \texttt{cvReadRealByName} is a simple superposition of \cross{GetFileNodeByName} and \cross{ReadReal}.
7674 \cvfunc{ReadString}\label{ReadString}
7676 Retrieves text string from file node
7680 const char* cvReadString( \par const CvFileNode* node,\par const char* default\_value=NULL );
7685 \cvarg{node}{File node}
7686 \cvarg{default\_value}{The value that is returned if \texttt{node} is NULL}
7689 The function \texttt{cvReadString} returns text string that is represented
7690 by the file node. If the file node is NULL, \texttt{default\_value}
7691 is returned (thus, it is convenient to call the function right after
7692 \cross{GetFileNode} without checking for NULL pointer), otherwise if
7693 the file node has type \texttt{CV\_NODE\_STR}, then 'node->data.str.ptr'
7694 is returned, otherwise the result is not determined.
7696 \cvfunc{ReadStringByName}\label{ReadStringByName}
7698 Finds file node and returns its value
7702 const char* cvReadStringByName( \par const CvFileStorage* fs,\par const CvFileNode* map,\par const char* name,\par const char* default\_value=NULL );
7707 \cvarg{fs}{File storage}
7708 \cvarg{map}{The parent map. If it is NULL, the function searches a top-level node.}
7709 \cvarg{name}{The node name}
7710 \cvarg{default\_value}{The value that is returned if the file node is not found}
7713 The function \texttt{cvReadStringByName} is a simple superposition of \cross{GetFileNodeByName} and \cross{ReadString}.
7715 \cvfunc{Read}\label{Read}
7717 Decodes object and returns pointer to it
7721 void* cvRead( \par CvFileStorage* fs,\par CvFileNode* node,\par CvAttrList* attributes=NULL );
7726 \cvarg{fs}{File storage}
7727 \cvarg{node}{The root object node}
7728 \cvarg{attributes}{Unused parameter}
7731 The function \texttt{cvRead} decodes user object (creates object in a
7732 native representation from the file storage subtree) and returns it. The
7733 object to be decoded must be an instance of registered type that supports
7734 \texttt{read} method (see \cross{CvTypeInfo}). Type of the object is
7735 determined by the type name that is encoded in the file. If the object
7736 is dynamic structure, it is created either in memory storage, passed to
7737 \cross{OpenFileStorage} or, if NULL pointer was passed, in temporary
7738 memory storage, which is release when \cross{ReleaseFileStorage} is
7739 called. Otherwise, if the object is not a dynamic structure, it is
7740 created in heap and should be released with a specialized function or
7741 using generic \cross{Release}.
7743 \cvfunc{ReadByName}\label{ReadByName}
7745 Finds object and decodes it
7749 void* cvReadByName( \par CvFileStorage* fs,\par const CvFileNode* map,\par const char* name,\par CvAttrList* attributes=NULL );
7754 \cvarg{fs}{File storage}
7755 \cvarg{map}{The parent map. If it is NULL, the function searches a top-level node.}
7756 \cvarg{name}{The node name}
7757 \cvarg{attributes}{Unused parameter}
7760 The function \texttt{cvReadByName} is a simple superposition of \cross{GetFileNodeByName} and \cross{Read}.
7762 \cvfunc{ReadRawData}\label{ReadRawData}
7764 Reads multiple numbers
7768 void cvReadRawData( \par const CvFileStorage* fs,\par const CvFileNode* src,\par void* dst,\par const char* dt );
7773 \cvarg{fs}{File storage}
7774 \cvarg{src}{The file node (a sequence) to read numbers from}
7775 \cvarg{dst}{Pointer to the destination array}
7776 \cvarg{dt}{Specification of each array element. It has the same format as in \cross{WriteRawData}.}
7779 The function \texttt{cvReadRawData} reads elements from a file node that represents a sequence of scalars
7781 \cvfunc{StartReadRawData}\label{StartReadRawData}
7783 Initializes file node sequence reader
7787 void cvStartReadRawData( \par const CvFileStorage* fs,\par const CvFileNode* src,\par CvSeqReader* reader );
7792 \cvarg{fs}{File storage}
7793 \cvarg{src}{The file node (a sequence) to read numbers from}
7794 \cvarg{reader}{Pointer to the sequence reader}
7797 The function \texttt{cvStartReadRawData} initializes sequence reader to read data from file node. The initialized reader can be then passed to \cross{ReadRawDataSlice}.
7799 \cvfunc{ReadRawDataSlice}\label{ReadRawDataSlice}
7801 Initializes file node sequence reader
7805 void cvReadRawDataSlice( \par const CvFileStorage* fs,\par CvSeqReader* reader,\par int count,\par void* dst,\par const char* dt );
7810 \cvarg{fs}{File storage}
7811 \cvarg{reader}{The sequence reader. Initialize it with \cross{StartReadRawData}.}
7812 \cvarg{count}{The number of elements to read}
7813 \cvarg{dst}{Pointer to the destination array}
7814 \cvarg{dt}{Specification of each array element. It has the same format as in \cross{WriteRawData}.}
7817 The function \texttt{cvReadRawDataSlice} reads one or more elements from
7818 the file node, representing a sequence, to user-specified array. The
7819 total number of read sequence elements is a product of \texttt{total}
7820 and the number of components in each array element. For example, if
7821 dt=\texttt{2if}, the function will read total*3 sequence elements. As
7822 with any sequence, some parts of the file node sequence may be skipped or
7823 read repeatedly by repositioning the reader using \cross{SetSeqReaderPos}.
7825 \subsection{RTTI and Generic Functions}
7827 \cvstruct{CvTypeInfo}\label{CvTypeInfo}
7833 typedef int (CV_CDECL *CvIsInstanceFunc)( const void* struct_ptr );
7834 typedef void (CV_CDECL *CvReleaseFunc)( void** struct_dblptr );
7835 typedef void* (CV_CDECL *CvReadFunc)( CvFileStorage* storage, CvFileNode* node );
7836 typedef void (CV_CDECL *CvWriteFunc)( CvFileStorage* storage,
7838 const void* struct_ptr,
7839 CvAttrList attributes );
7840 typedef void* (CV_CDECL *CvCloneFunc)( const void* struct_ptr );
7842 typedef struct CvTypeInfo
7844 int flags; /* not used */
7845 int header_size; /* sizeof(CvTypeInfo) */
7846 struct CvTypeInfo* prev; /* previous registered type in the list */
7847 struct CvTypeInfo* next; /* next registered type in the list */
7848 const char* type_name; /* type name, written to file storage */
7851 CvIsInstanceFunc is_instance; /* checks if the passed object belongs to the type */
7852 CvReleaseFunc release; /* releases object (memory etc.) */
7853 CvReadFunc read; /* reads object from file storage */
7854 CvWriteFunc write; /* writes object to file storage */
7855 CvCloneFunc clone; /* creates a copy of the object */
7861 The structure \cross{CvTypeInfo} contains information about one of
7862 standard or user-defined types. Instances of the type may or may not
7863 contain pointer to the corresponding \cross{CvTypeInfo} structure. In
7864 any case there is a way to find type info structure for given object -
7865 using \cross{TypeOf} function. Aternatively, type info can be found by
7866 the type name using \cross{FindType}, which is used when object is read
7867 from file storage. User can register a new type with \cross{RegisterType}
7868 that adds the type information structure into the beginning of the type
7869 list - thus, it is possible to create specialized types from generic
7870 standard types and override the basic methods.
7872 \cvfunc{RegisterType}\label{RegisterType}
7878 void cvRegisterType( const CvTypeInfo* info );
7883 \cvarg{info}{Type info structure}
7886 The function \texttt{cvRegisterType} registers a new type, which is
7887 described by \texttt{info}. The function creates a copy of the structure,
7888 so user should delete it after calling the function.
7890 \cvfunc{UnregisterType}\label{UnregisterType}
7892 Unregisters the type
7896 void cvUnregisterType( const char* type\_name );
7901 \cvarg{type\_name}{Name of the unregistered type}
7904 The function \texttt{cvUnregisterType} unregisters the type with
7905 the specified name. If the name is unknown, it is possible to locate
7906 the type info by an instance of the type using \cross{TypeOf} or by
7907 iterating the type list, starting from \cross{FirstType}, and then call
7908 \texttt{cvUnregisterType(info->type\_name)}.
7910 \cvfunc{FirstType}\label{FirstType}
7912 Returns the beginning of type list
7916 CvTypeInfo* cvFirstType( void );
7920 The function \texttt{cvFirstType} returns the first type of the list of registered types. Navigation through the list can be done via \texttt{prev} and \texttt{next} fields of \cross{CvTypeInfo} structure.
7922 \cvfunc{FindType}\label{FindType}
7924 Finds type by its name
7928 CvTypeInfo* cvFindType( const char* type\_name );
7933 \cvarg{type\_name}{Type name}
7936 The function \texttt{cvFindType} finds a registered type by its name. It returns NULL, if there is no type with the specified name.
7939 \cvfunc{TypeOf}\label{TypeOf}
7941 Returns type of the object
7945 CvTypeInfo* cvTypeOf( const void* struct\_ptr );
7950 \cvarg{struct\_ptr}{The object pointer}
7953 The function \texttt{cvTypeOf} finds the type of given object. It iterates
7954 through the list of registered types and calls \texttt{is\_instance}
7955 function/method of every type info structure with the object until one
7956 of them return non-zero or until the whole list has been traversed. In
7957 the latter case the function returns NULL.
7959 \cvfunc{Release}\label{Release}
7965 void cvRelease( void** struct\_ptr );
7970 \cvarg{struct\_ptr}{Double pointer to the object}
7973 The function \texttt{cvRelease} finds the type of given object and calls \texttt{release} with the double pointer.
7975 \cvfunc{Clone}\label{Clone}
7977 Makes a clone of the object
7981 void* cvClone( const void* struct\_ptr );
7986 \cvarg{struct\_ptr}{The object to clone}
7989 The function \texttt{cvClone} finds the type of given object and calls \texttt{clone} with the passed object.
7991 \cvfunc{Save}\label{Save}
7993 Saves object to file
7997 void cvSave( \par const char* filename,\par const void* struct\_ptr,\par const char* name=NULL,\par const char* comment=NULL,\par CvAttrList attributes=cvAttrList());
8002 \cvarg{filename}{File name}
8003 \cvarg{struct\_ptr}{Object to save}
8004 \cvarg{name}{Optional object name. If it is NULL, the name will be formed from \texttt{filename}.}
8005 \cvarg{comment}{Optional comment to put in the beginning of the file}
8006 \cvarg{attributes}{Optional attributes passed to \cross{Write}}
8009 The function \texttt{cvSave} saves object to file. It provides a simple interface to \cross{Write}.
8011 \cvfunc{Load}\label{Load}
8013 Loads object from file
8017 void* cvLoad( \par const char* filename,\par CvMemStorage* memstorage=NULL,\par const char* name=NULL,\par const char** real\_name=NULL );
8022 \cvarg{filename}{File name}
8023 \cvarg{memstorage}{Memory storage for dynamic structures, such as \cross{CvSeq} or \cross{CvGraph} . It is not used for matrices or images.}
8024 \cvarg{name}{Optional object name. If it is NULL, the first top-level object in the storage will be loaded.}
8025 \cvarg{real\_name}{Optional output parameter that will contain name of the loaded object (useful if \texttt{name=NULL})}
8028 The function \texttt{cvLoad} loads object from file. It provides a
8029 simple interface to \cross{Read}. After object is loaded, the file
8030 storage is closed and all the temporary buffers are deleted. Thus,
8031 to load a dynamic structure, such as sequence, contour or graph, one
8032 should pass a valid destination memory storage to the function.
8034 \section{Miscellaneous Functions}
8036 \subsection{Miscellaneous Functions}
8038 \cvfunc{CheckArr}\label{CheckArr}
8040 Checks every element of input array for invalid values
8044 int cvCheckArr( \par const CvArr* arr,\par int flags=0,\par double min\_val=0,\par double max\_val=0);
8048 #define cvCheckArray cvCheckArr
8052 \cvarg{arr}{The array to check}
8053 \cvarg{flags}{The operation flags, 0 or combination of:
8055 \cvarg{CV\_CHECK\_RANGE}{if set, the function checks that every value of array is within [minVal,maxVal) range, otherwise it just checks that every element is neither NaN nor $\pm \infty$.}
8056 \cvarg{CV\_CHECK\_QUIET}{if set, the function does not raises an error if an element is invalid or out of range}
8058 \cvarg{min\_val}{The inclusive lower boundary of valid values range. It is used only if \texttt{CV\_CHECK\_RANGE} is set.}
8059 \cvarg{max\_val}{The exclusive upper boundary of valid values range. It is used only if \texttt{CV\_CHECK\_RANGE} is set.}
8062 The function \texttt{cvCheckArr} checks that every array element is
8063 neither NaN nor $ \pm \infty $.
8064 If \texttt{CV\_CHECK\_RANGE} is set, it also
8065 checks that every element is greater than or equal to \texttt{minVal}
8066 and less than \texttt{maxVal}. The function returns nonzero if the
8067 check succeeded, i.e. all elements are valid and within the range,
8068 and zero otherwise. In the latter case if \texttt{CV\_CHECK\_QUIET}
8069 flag is not set, the function raises runtime error.
8071 \cvfunc{KMeans2}\label{KMeans2}
8073 Splits set of vectors by given number of clusters
8076 void cvKMeans2( \par const CvArr* samples,\par int cluster\_count,\par CvArr* labels,\par CvTermCriteria termcrit );
8080 \cvarg{samples}{Floating-point matrix of input samples, one row per sample}
8081 \cvarg{cluster\_count}{Number of clusters to split the set by}
8082 \cvarg{labels}{Output integer vector storing cluster indices for every sample}
8083 \cvarg{termcrit}{Specifies maximum number of iterations and/or accuracy (distance the centers move by between the subsequent iterations)}
8084 \cvarg{attempts}{How many times the algorithm is executed using different initial labelings. The algorithm returns labels that yield the best compactness (see the last function parameter)}
8085 \cvarg{rng}{Optional external random number generator; can be used to fully control the function behaviour. }
8086 \cvarg{flags}{Can be 0 or \texttt{CV\_KMEANS\_USE\_INITIAL\_LABELS}. The latter
8087 value means that during the first (and possibly the only) attempt the
8088 function uses the user-supplied labels as the initial approximation,
8089 instead of generating random labels. For the second and further attempts
8090 the function will use randomly generated labels in any case.}
8091 \cvarg{centers}{The optional output array of the cluster centers. }
8092 \cvarg{compactness}{The optional output parameter, which is computed as
8094 \sum_i ||\texttt{samples}_i - \texttt{centers}_{\texttt{labels}_i}||^2
8096 after every attempt; the best (minimum) value is chosen and the
8097 corresponding labels are returned by the function. Basically,
8098 user can use only the core of the function, set the number of
8099 attempts to 1, initialize labels each time using a custom algorithm
8100 (\texttt{flags}=\texttt{CV\_KMEAN\_USE\_INITIAL\_LABELS}) and, based on the output compactness
8101 or any other criteria, choose the best clustering.}
8104 The function \texttt{cvKMeans2} implements k-means algorithm that finds
8105 centers of \texttt{cluster\_count} clusters and groups the input samples
8106 around the clusters. On output $\texttt{labels}_i$ contains a cluster index for
8107 sample stored in the row $i$ of \texttt{samples} matrix.
8109 % Example. Clustering random samples of multi-gaussian distribution with k-means
8112 #include "highgui.h"
8114 void main( int argc, char** argv )
8116 #define MAX_CLUSTERS 5
8117 CvScalar color_tab[MAX_CLUSTERS];
8118 IplImage* img = cvCreateImage( cvSize( 500, 500 ), 8, 3 );
8119 CvRNG rng = cvRNG(0xffffffff);
8121 color_tab[0] = CV_RGB(255,0,0);
8122 color_tab[1] = CV_RGB(0,255,0);
8123 color_tab[2] = CV_RGB(100,100,255);
8124 color_tab[3] = CV_RGB(255,0,255);
8125 color_tab[4] = CV_RGB(255,255,0);
8127 cvNamedWindow( "clusters", 1 );
8131 int k, cluster_count = cvRandInt(&rng)%MAX_CLUSTERS + 1;
8132 int i, sample_count = cvRandInt(&rng)%1000 + 1;
8133 CvMat* points = cvCreateMat( sample_count, 1, CV_32FC2 );
8134 CvMat* clusters = cvCreateMat( sample_count, 1, CV_32SC1 );
8136 /* generate random sample from multigaussian distribution */
8137 for( k = 0; k < cluster_count; k++ )
8141 center.x = cvRandInt(&rng)%img->width;
8142 center.y = cvRandInt(&rng)%img->height;
8145 k*sample_count/cluster_count,
8146 (k == (cluster_count - 1)) ?
8148 (k+1)*sample_count/cluster_count );
8149 cvRandArr( &rng, &point_chunk, CV_RAND_NORMAL,
8150 cvScalar(center.x,center.y,0,0),
8151 cvScalar(img->width/6, img->height/6,0,0) );
8154 /* shuffle samples */
8155 for( i = 0; i < sample_count/2; i++ )
8158 (CvPoint2D32f*)points->data.fl + cvRandInt(&rng)%sample_count;
8160 (CvPoint2D32f*)points->data.fl + cvRandInt(&rng)%sample_count;
8162 CV_SWAP( *pt1, *pt2, temp );
8165 cvKMeans2( points, cluster_count, clusters,
8166 cvTermCriteria( CV_TERMCRIT_EPS+CV_TERMCRIT_ITER, 10, 1.0 ));
8170 for( i = 0; i < sample_count; i++ )
8172 CvPoint2D32f pt = ((CvPoint2D32f*)points->data.fl)[i];
8173 int cluster_idx = clusters->data.i[i];
8177 color_tab[cluster_idx],
8181 cvReleaseMat( &points );
8182 cvReleaseMat( &clusters );
8184 cvShowImage( "clusters", img );
8186 int key = cvWaitKey(0);
8193 \cvfunc{SeqPartition}\label{SeqPartition}
8195 Splits sequence into equivalency classes
8198 typedef int (CV_CDECL* CvCmpFunc)(const void* a, const void* b, void* userdata);
8202 int cvSeqPartition( \par const CvSeq* seq,\par CvMemStorage* storage,\par CvSeq** labels,\par CvCmpFunc is\_equal,\par void* userdata );
8206 \cvarg{seq}{The sequence to partition}
8207 \cvarg{storage}{The storage to store the sequence of equivalency classes. If it is NULL, the function uses \texttt{seq->storage} for output labels.}
8208 \cvarg{labels}{Ouput parameter. Double pointer to the sequence of 0-based labels of input sequence elements.}
8209 \cvarg{is\_equal}{The relation function that should return non-zero if the two particular sequence elements are from the same class, and zero overwise. The partitioning algorithm uses transitive closure of the relation function as equivalency critria.}
8210 \cvarg{userdata}{Pointer that is transparently passed to the \texttt{is\_equal} function}
8213 The function \texttt{cvSeqPartition} implements quadratic algorithm for
8214 splitting a set into one or more classes of equivalency. The function
8215 returns the number of equivalency classes.
8217 % Example. Partitioning 2d point set.
8221 #include "highgui.h"
8224 CvSeq* point_seq = 0;
8225 IplImage* canvas = 0;
8226 CvScalar* colors = 0;
8229 int is_equal( const void* _a, const void* _b, void* userdata )
8231 CvPoint a = *(const CvPoint*)_a;
8232 CvPoint b = *(const CvPoint*)_b;
8233 double threshold = *(double*)userdata;
8234 return (double)((a.x - b.x)*(a.x - b.x) + (a.y - b.y)*(a.y - b.y)) <=
8238 void on_track( int pos )
8241 double threshold = pos*pos;
8242 int i, class_count = cvSeqPartition( point_seq,
8247 printf("%4d classes\n", class_count );
8250 for( i = 0; i < labels->total; i++ )
8252 CvPoint pt = *(CvPoint*)cvGetSeqElem( point_seq, i, 0 );
8253 CvScalar color = colors[*(int*)cvGetSeqElem( labels, i, 0 )];
8254 cvCircle( canvas, pt, 1, color, -1 );
8257 cvShowImage( "points", canvas );
8260 int main( int argc, char** argv )
8262 CvMemStorage* storage = cvCreateMemStorage(0);
8263 point_seq = cvCreateSeq( CV_32SC2,
8267 CvRNG rng = cvRNG(0xffffffff);
8269 int width = 500, height = 500;
8270 int i, count = 1000;
8271 canvas = cvCreateImage( cvSize(width,height), 8, 3 );
8273 colors = (CvScalar*)cvAlloc( count*sizeof(colors[0]) );
8274 for( i = 0; i < count; i++ )
8278 pt.x = cvRandInt( &rng ) % width;
8279 pt.y = cvRandInt( &rng ) % height;
8280 cvSeqPush( point_seq, &pt );
8281 icolor = cvRandInt( &rng ) | 0x00404040;
8282 colors[i] = CV_RGB(icolor & 255,
8284 (icolor >> 16)&255);
8287 cvNamedWindow( "points", 1 );
8288 cvCreateTrackbar( "threshold", "points", &pos, 50, on_track );
8296 \section{Error Handling and System Functions}
8298 \subsection{Error Handling}
8300 Error handling in OpenCV is similar to IPL (Image Processing
8301 Library). In case of error functions do not return the error
8302 code. Instead, they raise an error using \texttt{CV\_ERROR}
8303 macro that calls \cross{Error} that, in its turn, sets the error
8304 status with \cross{SetErrStatus} and calls a standard or user-defined
8305 error handler (that can display a message box, write to log etc., see
8306 \cross{RedirectError}, There is global variable, one per each program
8307 thread, that contains current error status (an integer value). The status
8308 can be retrieved with \cross{GetErrStatus} function.
8310 There are three modes of error handling (see \cross{SetErrMode} and
8311 \cross{GetErrMode}):
8314 \cvarg{Leaf}{The program is terminated after error handler is
8315 called. This is the default value. It is useful for debugging, as the
8316 error is signalled immediately after it occurs. However, for production
8317 systems other two methods may be preferable as they provide more
8319 \cvarg{Parent}{The program is not terminated, but the error handler
8320 is called. The stack is unwinded (it is done w/o using C++ exception
8321 mechanism). User may check error code after calling CxCore function with
8322 \cross{GetErrStatus} and react.}
8323 \cvarg{Silent}{Similar to \texttt{Parent} mode, but no error handler
8327 Actually, the semantics of \texttt{Leaf} and \texttt{Parent} modes is implemented by error handlers and the above description is true for . \cross{GuiBoxReport} behaves slightly differently, and some custom error handler may implement quite different semantics. XXX - unintelligible; rewrite
8329 \cvfunc{ERROR Handling Macros}\label{ERROR Handling Macros}
8331 Macros for raising an error, checking for errors etc.
8335 /* special macros for enclosing processing statements within a function and separating
8336 them from prologue (resource initialization) and epilogue (guaranteed resource release) */
8338 #define __END__ goto exit; exit: ; }
8339 /* proceeds to "resource release" stage */
8340 #define EXIT goto exit
8342 /* Declares locally the function name for CV_ERROR() use */
8343 #define CV_FUNCNAME( Name ) \
8344 static char cvFuncName[] = Name
8346 /* Raises an error within the current context */
8347 #define CV_ERROR( Code, Msg ) \
8349 cvError( (Code), cvFuncName, Msg, __FILE__, __LINE__ ); \
8353 /* Checks status after calling CXCORE function */
8354 #define CV_CHECK() \
8356 if( cvGetErrStatus() < 0 ) \
8357 CV_ERROR( CV_StsBackTrace, "Inner function failed." ); \
8360 /* Provies shorthand for CXCORE function call and CV_CHECK() */
8361 #define CV_CALL( Statement ) \
8367 /* Checks some condition in both debug and release configurations */
8368 #define CV_ASSERT( Condition ) \
8370 if( !(Condition) ) \
8371 CV_ERROR( CV_StsInternal, "Assertion: " #Condition " failed" ); \
8374 /* these macros are similar to their CV_... counterparts, but they
8375 do not need exit label nor cvFuncName to be defined */
8376 #define OPENCV_ERROR(status,func_name,err_msg) ...
8377 #define OPENCV_ERRCHK(func_name,err_msg) ...
8378 #define OPENCV_ASSERT(condition,func_name,err_msg) ...
8379 #define OPENCV_CALL(statement) ...
8383 Instead of a discussion, here are the documented example of typical CXCORE function and the example of the function use.
8385 % Example: Use of Error Handling Macros
8391 void cvResizeDCT( CvMat* input_array, CvMat* output_array )
8393 CvMat* temp_array = 0; // declare pointer that should be released anyway.
8395 CV_FUNCNAME( "cvResizeDCT" ); // declare cvFuncName
8397 __BEGIN__; // start processing. There may be some declarations just after this macro,
8398 // but they couldn't be accessed from the epilogue.
8400 if( !CV_IS_MAT(input_array) || !CV_IS_MAT(output_array) )
8401 // use CV_ERROR() to raise an error
8402 CV_ERROR( CV_StsBadArg, "input_array or output_array are not valid matrices" );
8404 // some restrictions that are going to be removed later, may be checked with CV_ASSERT()
8405 CV_ASSERT( input_array->rows == 1 && output_array->rows == 1 );
8407 // use CV_CALL for safe function call
8408 CV_CALL( temp_array = cvCreateMat( input_array->rows,
8409 MAX(input_array->cols,output_array->cols),
8410 input_array->type ));
8412 if( output_array->cols > input_array->cols )
8413 CV_CALL( cvZero( temp_array ));
8415 temp_array->cols = input_array->cols;
8416 CV_CALL( cvDCT( input_array, temp_array, CV_DXT_FORWARD ));
8417 temp_array->cols = output_array->cols;
8418 CV_CALL( cvDCT( temp_array, output_array, CV_DXT_INVERSE ));
8419 CV_CALL( cvScale( output_array,
8421 1./sqrt((double)input_array->cols*output_array->cols), 0 ));
8423 __END__; // finish processing. Epilogue follows after the macro.
8425 // release temp_array. If temp_array has not been allocated
8426 // before an error occured, cvReleaseMat
8427 // takes care of it and does nothing in this case.
8428 cvReleaseMat( &temp_array );
8431 int main( int argc, char** argv )
8433 CvMat* src = cvCreateMat( 1, 512, CV_32F );
8434 #if 1 /* no errors */
8435 CvMat* dst = cvCreateMat( 1, 256, CV_32F );
8437 CvMat* dst = 0; /* test error processing mechanism */
8439 cvSet( src, cvRealScalar(1.), 0 );
8440 #if 0 /* change 0 to 1 to suppress error handler invocation */
8441 cvSetErrMode( CV_ErrModeSilent );
8443 cvResizeDCT( src, dst ); // if some error occurs, the message
8444 // box will popup, or a message will be
8445 // written to log, or some user-defined
8446 // processing will be done
8447 if( cvGetErrStatus() < 0 )
8448 printf("Some error occured" );
8450 printf("Everything is OK" );
8456 \cvfunc{GetErrStatus}\label{GetErrStatus}
8458 Returns the current error status
8461 int cvGetErrStatus( void );
8464 The function \texttt{cvGetErrStatus} returns the current error status -
8465 the value set with the last \cross{SetErrStatus} call. Note, that in
8466 \texttt{Leaf} mode the program terminates immediately after
8467 error occured, so to always get control after the function call,
8468 one should call \cross{SetErrMode} and set \texttt{Parent}
8469 or \texttt{Silent} error mode.
8471 \cvfunc{SetErrStatus}\label{SetErrStatus}
8473 Sets the error status
8476 void cvSetErrStatus( int status );
8480 \cvarg{status}{The error status}
8483 The function \texttt{cvSetErrStatus} 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 error. In other cases it is more natural to call \cross{Error} or \texttt{CV\_ERROR}.
8485 \cvfunc{GetErrMode}\label{GetErrMode}
8487 Returns the current error mode
8490 int cvGetErrMode( void );
8493 The function \texttt{cvGetErrMode} returns the current error mode - the value set with the last \cross{SetErrMode} call.
8495 \cvfunc{SetErrMode}\label{SetErrMode}
8500 #define CV_ErrModeLeaf 0
8501 #define CV_ErrModeParent 1
8502 #define CV_ErrModeSilent 2
8506 int cvSetErrMode( int mode );
8510 \cvarg{mode}{The error mode}
8513 The function \texttt{cvSetErrMode} sets the specified error mode. For description of different error modes see the beginning of the error section.
8515 \cvfunc{Error}\label{Error}
8520 int cvError( \par int status,\par const char* func\_name,\par const char* err\_msg,\par const char* file\_name,\par int line );
8524 \cvarg{status}{The error status}
8525 \cvarg{func\_name}{Name of the function where the error occured}
8526 \cvarg{err\_msg}{Additional information/diagnostics about the error}
8527 \cvarg{file\_name}{Name of the file where the error occured}
8528 \cvarg{line}{Line number, where the error occured}
8531 The function \texttt{cvError} sets the error status to the specified value (via \cross{SetErrStatus}) and, if the error mode is not \texttt{Silent}, calls the error handler.
8533 \cvfunc{ErrorStr}\label{ErrorStr}
8535 Returns textual description of error status code
8538 const char* cvErrorStr( int status );
8542 \cvarg{status}{The error status}
8545 The function \texttt{cvErrorStr} returns the textual description for
8546 the specified error status code. In case of unknown status the function
8547 returns NULL pointer.
8549 \cvfunc{RedirectError}\label{RedirectError}
8551 Sets a new error handler
8554 typedef int (CV_CDECL *CvErrorCallback)( int status, const char* func_name,
8555 const char* err_msg, const char* file_name, int line );
8559 CvErrorCallback cvRedirectError( \par CvErrorCallback error\_handler,\par void* userdata=NULL,\par void** prev\_userdata=NULL );
8563 \cvarg{error\_handler}{The new error\_handler}
8564 \cvarg{userdata}{Arbitrary pointer that is transparently passed to the error handler}
8565 \cvarg{prev\_userdata}{Pointer to the previously assigned user data pointer}
8568 The function \texttt{cvRedirectError} sets a new error handler that
8569 can be one of standard handlers or a custom handler
8570 that has the certain interface. The handler takes the same parameters
8571 as \cross{Error} function. If the handler returns non-zero value, the
8572 program is terminated, otherwise, it continues. The error handler may
8573 check the current error mode with \cross{GetErrMode} to make a decision.
8576 \cvfunc{cvNulDevReport cvStdErrReport cvGuiBoxReport}
8577 \label{cvNulDevReport}
8578 \label{cvStdErrReport}
8579 \label{cvGuiBoxReport}
8581 Provide standard error handling
8585 int cvNulDevReport( int status, const char* func_name,
8586 const char* err_msg, const char* file_name,
8587 int line, void* userdata );
8589 int cvStdErrReport( int status, const char* func_name,
8590 const char* err_msg, const char* file_name,
8591 int line, void* userdata );
8593 int cvGuiBoxReport( int status, const char* func_name,
8594 const char* err_msg, const char* file_name,
8595 int line, void* userdata );
8600 \cvarg{status}{The error status}
8601 \cvarg{func\_name}{Name of the function where the error occured}
8602 \cvarg{err\_msg}{Additional information/diagnostics about the error}
8603 \cvarg{file\_name}{Name of the file where the error occured}
8604 \cvarg{line}{Line number, where the error occured}
8605 \cvarg{userdata}{Pointer to the user data. Ignored by the standard handlers.}
8608 The functions \texttt{cvNullDevReport}, \texttt{cvStdErrReport}
8609 and \texttt{cvGuiBoxReport} provide standard error
8610 handling. \texttt{cvGuiBoxReport} is the default error
8611 handler on Win32 systems, \texttt{cvStdErrReport} - on other
8612 systems. \texttt{cvGuiBoxReport} pops up message box with the error
8613 description and suggest a few options. Below is the sample message box
8614 that may be recieved with the sample code above, if one introduce an
8615 error as described in the sample
8619 \includegraphics[width=0.5\textwidth]{pics/errmsg.png}
8621 If the error handler is set \texttt{cvStdErrReport}, the above message will be printed to standard error output and program will be terminated or continued, depending on the current error mode.
8623 Error Message printed to Standard Error Output (in \texttt{Leaf} mode)
8626 OpenCV ERROR: Bad argument (input_array or output_array are not valid matrices)
8627 in function cvResizeDCT, D:\User\VP\Projects\avl\_proba\a.cpp(75)
8628 Terminating the application...
8631 \subsection{System and Utility Functions}
8633 \cvfunc{Alloc}\label{Alloc}
8635 Allocates memory buffer
8638 void* cvAlloc( size\_t size );
8642 \cvarg{size}{Buffer size in bytes}
8645 The function \texttt{cvAlloc} allocates \texttt{size} bytes and returns
8646 pointer to the allocated buffer. In case of error the function reports an
8647 error and returns NULL pointer. By default \texttt{cvAlloc} calls
8648 \texttt{icvAlloc} which
8649 itself calls malloc, however it is possible to assign user-defined memory
8650 allocation/deallocation functions using \cross{SetMemoryManager} function.
8652 \cvfunc{Free}\label{Free}
8654 Deallocates memory buffer
8658 void cvFree( void** ptr );
8663 \cvarg{ptr}{Double pointer to released buffer}
8666 The function \texttt{cvFree} deallocates memory buffer allocated by
8667 \cross{Alloc}. It clears the pointer to buffer upon exit, that is why
8668 the double pointer is used. If \texttt{*buffer} is already NULL, the function
8671 \cvfunc{GetTickCount}\label{GetTickCount}
8673 Returns number of ticks
8676 int64 cvGetTickCount( void );
8679 The function \texttt{cvGetTickCount} returns number of 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 \cross{GetTickFrequency}.
8681 \cvfunc{GetTickFrequency}\label{GetTickFrequency}
8683 Returns number of ticks per microsecond
8687 double cvGetTickFrequency( void );
8691 The function \texttt{cvGetTickFrequency} returns number of ticks per microsecond. Thus, the quotient of \cross{GetTickCount} and \cross{GetTickFrequency} will give a number of microseconds starting from the platform-dependent event.
8693 \cvfunc{RegisterModule}\label{RegisterModule}
8695 Registers another module
8698 typedef struct CvPluginFuncInfo
8701 void* default_func_addr;
8702 const char* func_names;
8708 typedef struct CvModuleInfo
8710 struct CvModuleInfo* next;
8712 const char* version;
8713 CvPluginFuncInfo* func_tab;
8719 int cvRegisterModule( const CvModuleInfo* module\_info );
8723 \cvarg{module\_info}{Information about the module}
8726 The function \texttt{cvRegisterModule} adds module to the list of
8727 registered modules. After the module is registered, information about
8728 it can be retrieved using \cross{GetModuleInfo} function. Also, the
8729 registered module makes full use of optimized plugins (IPP, MKL, ...),
8730 supported by CXCORE. CXCORE itself, CV (computer vision), CVAUX (auxilary
8731 computer vision) and HIGHGUI (visualization and image/video acquisition) are
8732 examples of modules. Registration is usually done then the shared library
8733 is loaded. See \texttt{cxcore/src/cxswitcher.cpp} and
8734 \texttt{cv/src/cvswitcher.cpp} for details, how registration is done
8735 and look at \texttt{cxcore/src/cxswitcher.cpp}, \texttt{cxcore/src/\_cxipp.h}
8736 on how IPP and MKL are connected to the modules.
8738 \cvfunc{GetModuleInfo}\label{GetModuleInfo}
8740 Retrieves information about the registered module(s) and plugins
8743 void cvGetModuleInfo( \par const char* module\_name,\par const char** version,\par const char** loaded\_addon\_plugins );
8747 \cvarg{module\_name}{Name of the module of interest, or NULL, which means all the modules}
8748 \cvarg{version}{The output parameter. Information about the module(s), including version.}
8749 \cvarg{loaded\_addon\_plugins}{The list of names and versions of the optimized plugins that CXCORE was able to find and load}
8752 The function \texttt{cvGetModuleInfo} returns information about one of or
8753 all of the registered modules. The returned information is stored inside
8754 the libraries, so user should not deallocate or modify the returned
8757 \cvfunc{UseOptimized}\label{UseOptimized}
8759 Switches between optimized/non-optimized modes
8763 int cvUseOptimized( int on\_off );
8768 \cvarg{on\_off}{Use optimized ($\ne 0$) or not ($=0$)}
8771 The function \texttt{cvUseOptimized} switches between the mode, where
8772 only pure C implementations from cxcore, OpenCV etc. are used, and
8773 the mode, where IPP and MKL functions are used if available. When
8774 \texttt{cvUseOptimized(0)} is called, all the optimized libraries are
8775 unloaded. The function may be useful for debugging, IPP and MKL upgrade on
8776 the fly, online speed comparisons etc. It returns the number of optimized
8777 functions loaded. Note that by default the optimized plugins are loaded,
8778 so it is not necessary to call \texttt{cvUseOptimized(1)} in the beginning of
8779 the program (actually, it will only increase the startup time)
8781 \cvfunc{SetMemoryManager}\label{SetMemoryManager}
8783 Assings custom/default memory managing functions
8786 typedef void* (CV_CDECL *CvAllocFunc)(size_t size, void* userdata);
8787 typedef int (CV_CDECL *CvFreeFunc)(void* pptr, void* userdata);
8791 void cvSetMemoryManager( \par CvAllocFunc alloc\_func=NULL,\par CvFreeFunc free\_func=NULL,\par void* userdata=NULL );
8795 \cvarg{alloc\_func}{Allocation function; the interface is similar to \texttt{malloc}, except that \texttt{userdata} may be used to determine the context}
8796 \cvarg{free\_func}{Deallocation function; the interface is similar to \texttt{free}}
8797 \cvarg{userdata}{User data that is transparetly passed to the custom functions}
8800 The function \texttt{cvSetMemoryManager} sets user-defined memory
8801 managment functions (substitutors for malloc and free) that will be called
8802 by cvAlloc, cvFree and higher-level functions (e.g. cvCreateImage). Note,
8803 that the function should be called when there is data allocated using
8804 cvAlloc. Also, to avoid infinite recursive calls, it is not
8805 allowed to call cvAlloc and \cross{Free} from the custom
8806 allocation/deallocation functions.
8808 If \texttt{alloc\_func} and \texttt{free\_func} pointers are
8809 \texttt{NULL}, the default memory managing functions are restored.
8811 \cvfunc{SetIPLAllocators}\label{SetIPLAllocators}
8813 Switches to IPL functions for image allocation/deallocation
8816 typedef IplImage* (CV_STDCALL* Cv_iplCreateImageHeader)
8817 (int,int,int,char*,char*,int,int,int,int,int,
8818 IplROI*,IplImage*,void*,IplTileInfo*);
8819 typedef void (CV_STDCALL* Cv_iplAllocateImageData)(IplImage*,int,int);
8820 typedef void (CV_STDCALL* Cv_iplDeallocate)(IplImage*,int);
8821 typedef IplROI* (CV_STDCALL* Cv_iplCreateROI)(int,int,int,int,int);
8822 typedef IplImage* (CV_STDCALL* Cv_iplCloneImage)(const IplImage*);
8824 #define CV_TURN_ON_IPL_COMPATIBILITY() \
8825 cvSetIPLAllocators( iplCreateImageHeader, iplAllocateImage, \
8826 iplDeallocate, iplCreateROI, iplCloneImage )
8830 void cvSetIPLAllocators( \par
8831 Cv\_iplCreateImageHeader create\_header, \par
8832 Cv\_iplAllocateImageData allocate\_data, \par
8833 Cv\_iplDeallocate deallocate, \par
8834 Cv\_iplCreateROI create\_roi, \par
8835 Cv\_iplCloneImage clone\_image );
8839 \cvarg{create\_header}{Pointer to iplCreateImageHeader}
8840 \cvarg{allocate\_data}{Pointer to iplAllocateImage}
8841 \cvarg{deallocate}{Pointer to iplDeallocate}
8842 \cvarg{create\_roi}{Pointer to iplCreateROI}
8843 \cvarg{clone\_image}{Pointer to iplCloneImage}
8847 The function \texttt{cvSetIPLAllocators} makes CXCORE to use IPL functions
8848 for image allocation/deallocation operations. For convenience, there
8849 is the wrapping macro \texttt{CV\_TURN\_ON\_IPL\_COMPATIBILITY}. The
8850 function is useful for applications where IPL and CXCORE/OpenCV are used
8851 together and still there are calls to \texttt{iplCreateImageHeader}
8852 etc. The function is not necessary if IPL is called only for data
8853 processing and all the allocation/deallocation is done by CXCORE, or
8854 if all the allocation/deallocation is done by IPL and some of OpenCV
8855 functions are used to process the data.