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 );
34 \cvstruct{CvPoint2D32f}\label{CvPoint2D32f}
36 2D point with floating-point coordinates
40 typedef struct CvPoint2D32f
49 \cvarg{x}{x-coordinate}
50 \cvarg{y}{y-coordinate}
55 inline CvPoint2D32f cvPoint2D32f( double x, double y );
57 /* Conversion from CvPoint */
58 inline CvPoint2D32f cvPointTo32f( CvPoint point );
63 \cvstruct{CvPoint3D32f}\label{CvPoint3D32f}
65 3D point with floating-point coordinates
69 typedef struct CvPoint3D32f
79 \cvarg{x}{x-coordinate}
80 \cvarg{y}{y-coordinate}
81 \cvarg{z}{z-coordinate}
86 inline CvPoint3D32f cvPoint3D32f( double x, double y, double z );
90 \cvstruct{CvPoint2D64f}\label{CvPoint2D64f}
92 2D point with double precision floating-point coordinates
96 typedef struct CvPoint2D64f
105 \cvarg{x}{x-coordinate}
106 \cvarg{y}{y-coordinate}
111 inline CvPoint2D64f cvPoint2D64f( double x, double y );
113 /* Conversion from CvPoint */
114 inline CvPoint2D64f cvPointTo64f( CvPoint point );
118 \cvstruct{CvPoint3D64f}\label{CvPoint3D64f}
120 3D point with double precision floating-point coordinates
124 typedef struct CvPoint3D64f
134 \cvarg{x}{x-coordinate}
135 \cvarg{y}{y-coordinate}
136 \cvarg{z}{z-coordinate}
141 inline CvPoint3D64f cvPoint3D64f( double x, double y, double z );
145 \cvstruct{CvSize}\label{CvSize}
147 Pixel-accurate size of a rectangle.
151 typedef struct CvSize
160 \cvarg{width}{Width of the rectangle}
161 \cvarg{height}{Height of the rectangle}
166 inline CvSize cvSize( int width, int height );
170 \cvstruct{CvSize2D32f}\label{CvSize2D32f}
172 Sub-pixel accurate size of a rectangle.
176 typedef struct CvSize2D32f
185 \cvarg{width}{Width of the rectangle}
186 \cvarg{height}{Height of the rectangle}
191 inline CvSize2D32f cvSize2D32f( double width, double height );
195 \cvstruct{CvRect}\label{CvRect}
197 Offset (usually the top-left corner) and size of a rectangle.
201 typedef struct CvRect
212 \cvarg{x}{x-coordinate of the top-left corner}
213 \cvarg{y}{y-coordinate of the top-left corner (bottom-left for Windows bitmaps)}
214 \cvarg{width}{Width of the rectangle}
215 \cvarg{height}{Height of the rectangle}
220 inline CvRect cvRect( int x, int y, int width, int height );
224 \cvstruct{CvScalar}\label{CvScalar}
226 A container for 1-,2-,3- or 4-tuples of doubles.
230 typedef struct CvScalar
240 initializes val[0] with val0, val[1] with val1, etc.
242 inline CvScalar cvScalar( double val0, double val1=0,
243 double val2=0, double val3=0 );
245 initializes all of val[0]...val[3] with val0123
247 inline CvScalar cvScalarAll( double val0123 );
250 initializes val[0] with val0, and all of val[1]...val[3] with zeros
252 inline CvScalar cvRealScalar( double val0 );
256 \cvstruct{CvTermCriteria}\label{CvTermCriteria}
258 Termination criteria for iterative algorithms.
262 #define CV_TERMCRIT_ITER 1
263 #define CV_TERMCRIT_NUMBER CV_TERMCRIT_ITER
264 #define CV_TERMCRIT_EPS 2
266 typedef struct CvTermCriteria
276 \cvarg{type}{A combination of CV\_TERMCRIT\_ITER and CV\_TERMCRIT\_EPS}
277 \cvarg{max\_iter}{Maximum number of iterations}
278 \cvarg{epsilon}{Required accuracy}
283 inline CvTermCriteria cvTermCriteria( int type, int max_iter, double epsilon );
285 /* Check and transform a CvTermCriteria so that
286 type=CV_TERMCRIT_ITER+CV_TERMCRIT_EPS
287 and both max_iter and epsilon are valid */
288 CvTermCriteria cvCheckTermCriteria( CvTermCriteria criteria,
290 int default_max_iters );
294 \cvstruct{CvMat}\label{CvMat}
296 A multi-channel matrix.
338 \cvarg{type}{A CvMat signature (CV\_MAT\_MAGIC\_VAL) containing the type of elements and flags}
339 \cvarg{step}{Full row length in bytes}
340 \cvarg{refcount}{Underlying data reference counter}
341 \cvarg{data}{Pointers to the actual matrix data}
342 \cvarg{rows}{Number of rows}
343 \cvarg{cols}{Number of columns}
347 Matrices are stored row by row. All of the rows are aligned by 4 bytes.
350 \cvstruct{CvMatND}\label{CvMatND}
352 Multi-dimensional dense multi-channel array.
356 typedef struct CvMatND
384 \cvarg{type}{A CvMatND signature (CV\_MATND\_MAGIC\_VAL), combining the type of elements and flags}
385 \cvarg{dims}{The number of array dimensions}
386 \cvarg{refcount}{Underlying data reference counter}
387 \cvarg{data}{Pointers to the actual matrix data}
388 \cvarg{dim}{For each dimension, the pair (number of elements, distance between elements in bytes)}
391 \cvstruct{CvSparseMat}\label{CvSparseMat}
393 Multi-dimensional sparse multi-channel array.
397 typedef struct CvSparseMat
408 int size[CV_MAX_DIM];
415 \cvarg{type}{A CvSparseMat signature (CV\_SPARSE\_MAT\_MAGIC\_VAL), combining the type of elements and flags.}
416 \cvarg{dims}{Number of dimensions}
417 \cvarg{refcount}{Underlying reference counter. Not used.}
418 \cvarg{heap}{A pool of hash table nodes}
419 \cvarg{hashtable}{The hash table. Each entry is a list of nodes.}
420 \cvarg{hashsize}{Size of the hash table}
421 \cvarg{total}{Total number of sparse array nodes}
422 \cvarg{valoffset}{The value offset of the array nodes, in bytes}
423 \cvarg{idxoffset}{The index offset of the array nodes, in bytes}
424 \cvarg{size}{Array of dimension sizes}
427 \cvstruct{IplImage}\label{IplImage}
433 typedef struct _IplImage
448 struct _IplImage *maskROI;
450 struct _IplTileInfo *tileInfo;
456 char *imageDataOrigin;
463 \cvarg{nSize}{\texttt{sizeof(IplImage)}}
464 \cvarg{ID}{Version, always equals 0}
465 \cvarg{nChannels}{Number of channels. Most OpenCV functions support 1-4 channels.}
466 \cvarg{alphaChannel}{Ignored by OpenCV}
467 \cvarg{depth}{Pixel depth in bits. The supported depths are:
469 \cvarg{IPL\_DEPTH\_8U}{Unsigned 8-bit integer}
470 \cvarg{IPL\_DEPTH\_8S}{Signed 8-bit integer}
471 \cvarg{IPL\_DEPTH\_16U}{Unsigned 16-bit integer}
472 \cvarg{IPL\_DEPTH\_16S}{Signed 16-bit integer}
473 \cvarg{IPL\_DEPTH\_32S}{Signed 32-bit integer}
474 \cvarg{IPL\_DEPTH\_32F}{Single-precision floating point}
475 \cvarg{IPL\_DEPTH\_64F}{Double-precision floating point}
477 \cvarg{colorModel}{Ignored by OpenCV. The OpenCV function \cross{CvtColor} requires the source and destination color spaces as parameters.}
478 \cvarg{channelSeq}{Ignored by OpenCV}
479 \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} ...$}
480 \cvarg{origin}{0 - top-left origin, 1 - bottom-left origin (Windows bitmap style)}
481 \cvarg{align}{Alignment of image rows (4 or 8). OpenCV ignores this and uses widthStep instead.}
482 \cvarg{width}{Image width in pixels}
483 \cvarg{height}{Image height in pixels}
484 \cvarg{roi}{Region Of Interest (ROI). If not NULL, only this image region will be processed.}
485 \cvarg{maskROI}{Must be NULL in OpenCV}
486 \cvarg{imageId}{Must be NULL in OpenCV}
487 \cvarg{tileInfo}{Must be NULL in OpenCV}
488 \cvarg{imageSize}{Image data size in bytes. For interleaved data, this equals $\texttt{image->height} \cdot \texttt{image->widthStep}$ }
489 \cvarg{imageData}{A pointer to the aligned image data}
490 \cvarg{widthStep}{The size of an aligned image row, in bytes}
491 \cvarg{BorderMode}{Border completion mode, ignored by OpenCV}
492 \cvarg{BorderConst}{Border completion mode, ignored by OpenCV}
493 \cvarg{imageDataOrigin}{A pointer to the origin of the image data (not necessarily aligned). This is used for image deallocation.}
496 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.
498 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.
500 \cvstruct{CvArr}\label{CvArr}
510 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.
513 \section{Operations on Arrays}
515 \subsection{Initialization}
517 \cvfunc{CreateImage}\label{CreateImage}
519 Creates an image header and allocates the image data.
522 IplImage* cvCreateImage(
529 }{CPP}{CreateImage(size, depth, channels)->image}
532 \cvarg{size}{Image width and height}
533 \cvarg{depth}{Bit depth of image elements. See \cross{IplImage} for valid depths.}
534 \cvarg{channels}{Number of channels per pixel. See \cross{IplImage} for details. This function only creates images with interleaved channels.}
537 This call is a shortened form of
540 header = cvCreateImageHeader( size, depth, channels );
541 cvCreateData( header );
545 \cvfunc{CreateImageHeader}\label{CreateImageHeader}
547 Creates an image header but does not allocate the image data.
550 IplImage* cvCreateImageHeader(
558 CreateImageHeader(size, depth, channels) -> image
562 \cvarg{size}{Image width and height}
563 \cvarg{depth}{Image depth (see \cross{CreateImage})}
564 \cvarg{channels}{Number of channels (see \cross{CreateImage})}
567 This call is an analogue of
570 iplCreateImageHeader( channels, 0, depth,
571 channels == 1 ? "GRAY" : "RGB",
572 channels == 1 ? "GRAY" : channels == 3 ? "BGR" :
573 channels == 4 ? "BGRA" : "",
574 IPL_DATA_ORDER_PIXEL, IPL_ORIGIN_TL, 4,
575 size.width, size.height,
579 but it does not use IPL functions by default (see the \texttt{CV\_TURN\_ON\_IPL\_COMPATIBILITY} macro).
583 \cvfunc{ReleaseImageHeader}\label{ReleaseImageHeader}
585 Deallocates an image header.
588 void cvReleaseImageHeader( IplImage** image );
592 \cvarg{image}{Double pointer to the image header}
595 This call is an analogue of
600 iplDeallocate( *image, IPL_IMAGE_HEADER | IPL_IMAGE_ROI );
605 but it does not use IPL functions by default (see the \texttt{CV\_TURN\_ON\_IPL\_COMPATIBILITY} macro).
607 \cvfunc{ReleaseImage}\label{ReleaseImage}
609 Deallocates the image header and the image data.
613 void cvReleaseImage( IplImage** image );
618 \cvarg{image}{Double pointer to the image header}
621 This call is a shortened form of
627 cvReleaseData( *image );
628 cvReleaseImageHeader( image );
633 \cvfunc{InitImageHeader}\label{InitImageHeader}
635 Initializes an image header that was previously allocated.
639 IplImage* cvInitImageHeader( \par IplImage* image,\par CvSize size,\par int depth,\par int channels,\par int origin=0,\par int align=4 );
644 \cvarg{image}{Image header to initialize}
645 \cvarg{size}{Image width and height}
646 \cvarg{depth}{Image depth (see \cross{CreateImage})}
647 \cvarg{channels}{Number of channels (see \cross{CreateImage})}
648 \cvarg{origin}{Top-left \texttt{IPL\_ORIGIN\_TL} or bottom-left \texttt{IPL\_ORIGIN\_BL}}
649 \cvarg{align}{Alignment for image rows, typically 4 or 8 bytes}
652 The returned \texttt{IplImage*} points to the initialized header.
656 \cvfunc{CloneImage}\label{CloneImage}
658 Makes a full copy of an image, including the header, data, and ROI.
662 IplImage* cvCloneImage( const IplImage* image );
664 }{CPP}{CloneImage(image)-> copy}
667 \cvarg{image}{The original image}
670 The returned \texttt{IplImage*} points to the image copy.
672 \cvfunc{SetImageCOI}\label{SetImageCOI}
674 Sets the channel of interest in an IplImage.
678 void cvSetImageCOI( \par IplImage* image,\par int coi );
680 }{CPP}{SetImageCOI(image, coi)-> None}
683 \cvarg{image}{A pointer to the image header}
684 \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.}
687 If the ROI is set to \texttt{NULL} and the coi is \textit{not} 0,
688 the ROI is allocated. Most OpenCV functions do \textit{not} support
689 the COI setting, so to process an individual image/matrix channel one
690 may copy (via \cross{Copy} or \cross{Split}) the channel to a separate
691 image/matrix, process it and then copy the result back (via \cross{Copy}
692 or \cross{Merge}) if needed.
694 \cvfunc{GetImageCOI}\label{GetImageCOI}
696 Returns the index of the channel of interest.
700 int cvGetImageCOI( const IplImage* image );
702 }{CPP}{GetImageCOI(image)-> channel}
705 \cvarg{image}{A pointer to the image header}
708 Returns the channel of interest of in an IplImage. Returned values correspond to the \texttt{coi} in \cross{SetImageCOI}.
710 \cvfunc{SetImageROI}\label{SetImageROI}\label{ROI}
712 Sets an image Region Of Interest (ROI) for a given rectangle.
716 void cvSetImageROI( \par IplImage* image,\par CvRect rect );
718 }{CPP}{SetImageROI(image, rect)-> None}
721 \cvarg{image}{A pointer to the image header}
722 \cvarg{rect}{The ROI rectangle}
725 If the original image ROI was \texttt{NULL} and the \texttt{rect} is not the whole image, the ROI structure is allocated.
727 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.
729 \cvfunc{ResetImageROI}\label{ResetImageROI}
731 Resets the image ROI to include the entire image and releases the ROI structure.
735 void cvResetImageROI( IplImage* image );
737 }{CPP}{ResetImageROI(image)-> None}
740 \cvarg{image}{A pointer to the image header}
743 This produces a similar result to the following, but in addition it releases the ROI structure.
747 cvSetImageROI( image, cvRect( 0, 0, image->width, image->height ));
748 cvSetImageCOI( image, 0 );
753 \cvfunc{GetImageROI}\label{GetImageROI}
755 Returns the image ROI.
759 CvRect cvGetImageROI( const IplImage* image );
761 }{CPP}{GetImageROI(image)-> CvRect}
764 \cvarg{image}{A pointer to the image header}
768 If there is no ROI set, \texttt{cvRect(0,0,image->width,image->height)} is returned.
771 \cvfunc{CreateMat}\label{CreateMat}\label{cvCreateMat}
773 Creates a matrix header and allocates the matrix data.
777 CvMat* cvCreateMat( \par int rows,\par int cols,\par int type );
779 }{CPP}{CreateMat(row, cols, type) -> mat}
782 \cvarg{rows}{Number of rows in the matrix}
783 \cvarg{cols}{Number of columns in the matrix}
784 \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.}
787 This is the concise form for:
791 CvMat* mat = cvCreateMatHeader( rows, cols, type );
796 \cvfunc{CreateMatHeader}\label{CreateMatHeader}
798 Creates a matrix header but does not allocate the matrix data.
802 CvMat* cvCreateMatHeader( \par int rows,\par int cols,\par int type );
804 }{CPP}{CreateMatHeader(rows, cols, type) -> mat}
807 \cvarg{rows}{Number of rows in the matrix}
808 \cvarg{cols}{Number of columns in the matrix}
809 \cvarg{type}{Type of the matrix elements, see \cross{CreateMat}}
812 The function \texttt{cvCreateMatHeader} allocates a new matrix header and returns a pointer to it. The matrix data can then be allocated using \cross{CreateData} or set explicitly to user-allocated data via \cross{SetData}.
816 \cvfunc{ReleaseMat}\label{ReleaseMat}
818 Deallocates a matrix.
822 void cvReleaseMat( CvMat** mat );
827 \cvarg{mat}{Double pointer to the matrix}
831 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.
836 cvDecRefData( *mat );
837 cvFree( (void**)mat );
842 \cvfunc{InitMatHeader}\label{InitMatHeader}
844 Initializes a pre-allocated matrix header.
848 CvMat* cvInitMatHeader(\par CvMat* mat,\par int rows,\par int cols,\par int type, \par void* data=NULL,\par int step=CV\_AUTOSTEP );
853 \cvarg{mat}{A pointer to the matrix header to be initialized}
854 \cvarg{rows}{Number of rows in the matrix}
855 \cvarg{cols}{Number of columns in the matrix}
856 \cvarg{type}{Type of the matrix elements, see \cross{CreateMat}.}
857 \cvarg{data}{Optional: data pointer assigned to the matrix header}
858 \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.}
861 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:
865 double a[] = { 1, 2, 3, 4,
869 double b[] = { 1, 5, 9,
877 cvInitMatHeader( &Ma, 3, 4, CV_64FC1, a );
878 cvInitMatHeader( &Mb, 4, 3, CV_64FC1, b );
879 cvInitMatHeader( &Mc, 3, 3, CV_64FC1, c );
881 cvMatMulAdd( &Ma, &Mb, 0, &Mc );
882 // the c array now contains the product of a (3x4) and b (4x3)
886 \cvfunc{Mat}\label{Mat}
888 Initializes matrix header (lightweight variant).
892 CvMat cvMat(\par int rows,\par int cols,\par int type,\par void* data=NULL );
897 \cvarg{rows}{Number of rows in the matrix}
898 \cvarg{cols}{Number of columns in the matrix}
899 \cvarg{type}{Type of the matrix elements - see \cross{CreateMat}}
900 \cvarg{data}{Optional data pointer assigned to the matrix header}
903 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.)
905 This function is a fast inline substitution for \cross{InitMatHeader}. Namely, it is equivalent to:
910 cvInitMatHeader( &mat, rows, cols, type, data, CV\_AUTOSTEP );
915 \cvfunc{CloneMat}\label{CloneMat}
917 Creates a full matrix copy.
921 CvMat* cvCloneMat( const CvMat* mat );
923 }{CPP}{CloneMat(mat)-> copy}
926 \cvarg{mat}{Matrix to be copied}
929 Creates a full copy of a matrix and returns a pointer to the copy.
931 \cvfunc{CreateMatND}\label{CreateMatND}
933 Creates the header and allocates the data for a multi-dimensional dense array.
937 CvMatND* cvCreateMatND(\par int dims,\par const int* sizes,\par int type );
939 }{CPP}{CreateMatND(dims, type)}
943 \cvarg{dims}{List or tuple of array dimensions, up to 32 in length.}
945 \cvarg{dims}{Number of array dimensions. This must not exceed CV\_MAX\_DIM (32 by default, but can be changed at build time).}
946 \cvarg{sizes}{Array of dimension sizes.}
948 \cvarg{type}{Type of array elements, see \cross{CreateMat}.}
951 This is a short form for:
955 CvMatND* mat = cvCreateMatNDHeader( dims, sizes, type );
960 \cvfunc{CreateMatNDHeader}\label{CreateMatNDHeader}
962 Creates a new matrix header but does not allocate the matrix data.
966 CvMatND* cvCreateMatNDHeader(\par int dims,\par const int* sizes,\par int type );
968 }{CPP}{CreateMatNDHeader(dims, type)}
972 \cvarg{dims}{List or tuple of array dimensions, up to 32 in length.}
974 \cvarg{dims}{Number of array dimensions}
975 \cvarg{sizes}{Array of dimension sizes}
977 \cvarg{type}{Type of array elements, see \cross{CreateMat}}
980 The function \texttt{cvCreateMatND} allocates a header for a multi-dimensional dense array. The array data can further be allocated using \cross{CreateData} or set explicitly to user-allocated data via \cross{SetData}.
984 \cvfunc{ReleaseMatND}\label{ReleaseMatND}
986 Deallocates a multi-dimensional array.
990 void cvReleaseMatND( CvMatND** mat );
995 \cvarg{mat}{Double pointer to the array}
998 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.
1003 cvDecRefData( *mat );
1004 cvFree( (void**)mat );
1008 \cvfunc{InitMatNDHeader}\label{InitMatNDHeader}
1010 Initializes a pre-allocated multi-dimensional array header.
1014 CvMatND* cvInitMatNDHeader( \par CvMatND* mat,\par int dims,\par const int* sizes,\par int type,\par void* data=NULL );
1019 \cvarg{mat}{A pointer to the array header to be initialized}
1020 \cvarg{dims}{The number of array dimensions}
1021 \cvarg{sizes}{An array of dimension sizes}
1022 \cvarg{type}{Type of array elements, see \cross{CreateMat}}
1023 \cvarg{data}{Optional data pointer assigned to the matrix header}
1026 \cvfunc{CloneMatND}\label{CloneMatND}
1028 Creates full copy of a multi-dimensional array and returns a pointer to the copy.
1032 CvMatND* cvCloneMatND( const CvMatND* mat );
1034 }{CPP}{CloneMatND(mat)-> copy}
1037 \cvarg{mat}{Input array}
1041 \cvfunc{DecRefData}\label{DecRefData}
1043 Decrements an array data reference counter.
1047 void cvDecRefData( CvArr* arr );
1052 \cvarg{arr}{Pointer to an array header}
1055 The function \texttt{cvDecRefData} decrements the data reference counter in a \cross{CvMat} or
1056 \cross{CvMatND} if the reference counter pointer
1057 is not NULL. If the counter reaches zero, the data is deallocated. In the
1058 current implementation the reference counter is not NULL only if the data
1059 was allocated using the \cross{CreateData} function. The counter will be NULL in other cases such as:
1060 external data was assigned to the header using \cross{SetData}, the matrix
1061 header is part of a larger matrix or image, or the header was converted from an image or n-dimensional matrix header.
1064 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1066 \cvfunc{IncRefData}\label{IncRefData}
1068 Increments array data reference counter.
1072 int cvIncRefData( CvArr* arr );
1077 \cvarg{arr}{Array header}
1081 The function \texttt{cvIncRefData} increments \cross{CvMat} or
1082 \cross{CvMatND} data reference counter and returns the new counter value
1083 if the reference counter pointer is not NULL, otherwise it returns zero.
1086 \cvfunc{CreateData}\label{CreateData}
1088 Allocates array data
1092 void cvCreateData( CvArr* arr );
1094 }{CPP}{CreateData(arr)}
1097 \cvarg{arr}{Array header}
1101 The function \texttt{cvCreateData} allocates image, matrix or
1102 multi-dimensional array data. Note that in the case of matrix types OpenCV
1103 allocation functions are used and in the case of IplImage they are used
1104 unless \texttt{CV\_TURN\_ON\_IPL\_COMPATIBILITY} was called. In the
1105 latter case IPL functions are used to allocate the data.
1109 \cvfunc{ReleaseData}\label{ReleaseData}
1111 Releases array data.
1115 void cvReleaseData( CvArr* arr );
1120 \cvarg{arr}{Array header}
1124 The function \texttt{cvReleaseData} releases the array data. In the 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}.
1128 \cvfunc{SetData}\label{SetData}
1130 Assigns user data to the array header.
1134 void cvSetData( CvArr* arr, void* data, int step );
1136 }{CPP}{SetData(arr, data, step)}
1139 \cvarg{arr}{Array header}
1140 \cvarg{data}{User data}
1141 \cvarg{step}{Full row length in bytes}
1145 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 the case of matrix) function.
1148 \cvfunc{GetRawData}\label{GetRawData}
1150 Retrieves low-level information about the array.
1154 void cvGetRawData( const CvArr* arr, uchar** data,
1155 int* step=NULL, CvSize* roi\_size=NULL );
1160 \cvarg{arr}{Array header}
1161 \cvarg{data}{Output pointer to the whole image origin or ROI origin if ROI is set}
1162 \cvarg{step}{Output full row length in bytes}
1163 \cvarg{roi\_size}{Output ROI size}
1166 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, the parameters of ROI are returned.
1168 The following example shows how to get access to array elements. GetRawData calculates the absolute value of the elements in a single-channel, floating-point array.
1178 cvGetRawData( array, (uchar**)&data, &step, &size );
1179 step /= sizeof(data[0]);
1181 for( y = 0; y < size.height; y++, data += step )
1182 for( x = 0; x < size.width; x++ )
1183 data[x] = (float)fabs(data[x]);
1188 \cvfunc{GetMat}\label{GetMat}
1190 Returns matrix header for arbitrary array.
1194 CvMat* cvGetMat( const CvArr* arr, CvMat* header, int* coi=NULL, int allowND=0 );
1196 }{CPP}{GetMat(arr) -> cvmat }
1199 \cvarg{arr}{Input array}
1201 \cvarg{header}{Pointer to \cross{CvMat} structure used as a temporary buffer}
1202 \cvarg{coi}{Optional output parameter for storing COI}
1203 \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.}
1207 The function \texttt{cvGetMat} returns a matrix header for the input array that can be a matrix -
1209 \cross{CvMat}, an image - \texttt{IplImage} or a 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 the \texttt{header} structure with parameters of the current image ROI and returns the pointer to this temporary structure. Because COI is not supported by \cross{CvMat}, it is returned separately.
1211 The function provides an easy way to handle both types of arrays - \texttt{IplImage} and \cross{CvMat} - using the same code. Reverse transform from \cross{CvMat} to \texttt{IplImage} can be done using the \cross{GetImage} function.
1213 Input array must have underlying data allocated or attached, otherwise the function fails.
1215 If the input array is \texttt{IplImage} with planar data layout and COI set, the function returns the pointer to the selected plane and COI = 0. It enables per-plane processing of multi-channel images with planar data layout using OpenCV functions.
1217 \cvfunc{GetImage}\label{GetImage}
1219 Returns image header for arbitrary array.
1223 IplImage* cvGetImage( const CvArr* arr, IplImage* image\_header );
1225 }{CPP}{GetImage(arr) -> iplimage}
1228 \cvarg{arr}{Input array}
1230 \cvarg{image\_header}{Pointer to \texttt{IplImage} structure used as a temporary buffer}
1234 The function \texttt{cvGetImage} returns the image header for the input array
1235 that can be a matrix - \cross{CvMat}, or an image - \texttt{IplImage*}. In
1236 the case of an image the function simply returns the input pointer. In the
1237 case of \cross{CvMat} it initializes an \texttt{image\_header} structure
1238 with the parameters of the input matrix. Note that if we transform
1239 \texttt{IplImage} to \cross{CvMat} and then transform CvMat back to
1240 IplImage, we can get different headers if the ROI is set, and thus some
1241 IPL functions that calculate image stride from its width and align may
1242 fail on the resultant image.
1244 \cvfunc{CreateSparseMat}\label{CreateSparseMat}
1246 Creates sparse array.
1250 CvSparseMat* cvCreateSparseMat( int dims, const int* sizes, int type );
1252 }{CPP}{CreateSparseMat(dims, type) -> cvmat}
1256 \cvarg{dims}{Number of array dimensions. In contrast to the dense matrix, the number of dimensions is practically unlimited (up to $2^{16}$).}
1257 \cvarg{sizes}{Array of dimension sizes}
1259 \cvarg{dims}{List or tuple of array dimensions.}
1261 \cvarg{type}{Type of array elements. The same as for CvMat}
1264 The function \texttt{cvCreateSparseMat} allocates a multi-dimensional sparse array. Initially the array contain no elements, that is \cross{Get} or \cross{GetReal} returns zero for every index.
1267 \cvfunc{ReleaseSparseMat}\label{ReleaseSparseMat}
1269 Deallocates sparse array.
1273 void cvReleaseSparseMat( CvSparseMat** mat );
1278 \cvarg{mat}{Double pointer to the array}
1282 The function \texttt{cvReleaseSparseMat} releases the sparse array and clears the array pointer upon exit.
1285 \cvfunc{CloneSparseMat}\label{CloneSparseMat}
1287 Creates full copy of sparse array.
1291 CvSparseMat* cvCloneSparseMat( const CvSparseMat* mat );
1293 }{CPP}{CloneSparseMat(mat) -> mat}
1296 \cvarg{mat}{Input array}
1299 The function \texttt{cvCloneSparseMat} creates a copy of the input array and returns pointer to the copy.
1301 \subsection{Accessing Elements and sub-Arrays}
1303 \cvfunc{GetSubRect}\label{GetSubRect}
1305 Returns matrix header corresponding to the rectangular sub-array of input image or matrix.
1309 CvMat* cvGetSubRect( const CvArr* arr, CvMat* submat, CvRect rect );
1311 }{CPP}{GetSubRect(arr, rect) -> cvmat}
1314 \cvarg{arr}{Input array}
1316 \cvarg{submat}{Pointer to the resultant sub-array header}
1318 \cvarg{rect}{Zero-based coordinates of the rectangle of interest}
1321 The function \texttt{cvGetSubRect} returns header, corresponding to
1322 a specified rectangle of the input array. In other words, it allows
1323 the user to treat a rectangular part of input array as a stand-alone
1324 array. ROI is taken into account by the function so the sub-array of
1325 ROI is actually extracted.
1327 \cvfunc{GetRow, GetRows}\label{GetRow, GetRows}
1329 Returns array row or row span.
1332 CvMat* cvGetRow( const CvArr* arr, CvMat* submat, int row );
1333 }{CPP}{GetRow(arr,submat,row)-> None}
1335 CvMat* cvGetRows( const CvArr* arr, CvMat* submat, int start\_row, int end\_row, int delta\_row=1 );
1336 }{CPP}{GetRows(arr,submat,start\_row,end\_row,delta\_row=-1)-> None}
1339 \cvarg{arr}{Input array}
1340 \cvarg{submat}{Pointer to the resulting sub-array header}
1341 \cvarg{row}{Zero-based index of the selected row}
1342 \cvarg{start\_row}{Zero-based index of the starting row (inclusive) of the span}
1343 \cvarg{end\_row}{Zero-based index of the ending row (exclusive) of the span}
1344 \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}.}
1348 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}:
1352 cvGetRow( arr, submat, row ) ~ cvGetRows( arr, submat, row, row + 1, 1 );
1357 \cvfunc{GetCol, GetCols}\label{GetCol, GetCols}
1359 Returns array column or column span.
1362 CvMat* cvGetCol( const CvArr* arr, CvMat* submat, int col );
1363 }{CPP}{GetCol(arr,submat,row)-> None}
1365 CvMat* cvGetCols( const CvArr* arr, CvMat* submat, int start\_col, int end\_col );
1366 }{CPP}{GetCols(arr,submat,start\_col,end\_col,delta\_col=-1)-> None}
1369 \cvarg{arr}{Input array}
1370 \cvarg{submat}{Pointer to the resulting sub-array header}
1371 \cvarg{col}{Zero-based index of the selected column}
1372 \cvarg{start\_col}{Zero-based index of the starting column (inclusive) of the span}
1373 \cvarg{end\_col}{Zero-based index of the ending column (exclusive) of the span}
1376 The functions \texttt{GetCol} and \texttt{GetCols} return the header, corresponding to a specified column span of the input array. Note that \texttt{GetCol} is a shortcut for \cross{GetCols}:
1380 cvGetCol( arr, submat, col ); // ~ cvGetCols( arr, submat, col, col + 1 );
1384 \cvfunc{GetDiag}\label{GetDiag}
1386 Returns one of array diagonals.
1390 CvMat* cvGetDiag( const CvArr* arr, CvMat* submat, int diag=0 );
1392 }{CPP}{GetDiag(arr,submat,diag=0)-> None}
1395 \cvarg{arr}{Input array}
1396 \cvarg{submat}{Pointer to the resulting sub-array header}
1397 \cvarg{diag}{Array diagonal. Zero corresponds to the main diagonal, -1 corresponds to the diagonal above the main , 1 corresponds to the diagonal below the main, and so forth.}
1400 The function \texttt{cvGetDiag} returns the header, corresponding to a specified diagonal of the input array.
1402 \cvfunc{GetSize}\label{GetSize}
1404 Returns size of matrix or image ROI.
1408 CvSize cvGetSize( const CvArr* arr );
1410 }{CPP}{GetSize(arr)-> CvSize}
1413 \cvarg{arr}{array header}
1416 The function \texttt{cvGetSize} returns number of rows (CvSize::height) and number of columns (CvSize::width) of the input matrix or image. In the case of image the size of ROI is returned.
1420 \cvfunc{InitSparseMatIterator}\label{InitSparseMatIterator}
1422 Initializes sparse array elements iterator.
1426 CvSparseNode* cvInitSparseMatIterator( const CvSparseMat* mat,
1427 CvSparseMatIterator* mat\_iterator );
1432 \cvarg{mat}{Input array}
1433 \cvarg{mat\_iterator}{Initialized iterator}
1436 The function \texttt{cvInitSparseMatIterator} initializes iterator of
1437 sparse array elements and returns pointer to the first element, or NULL
1438 if the array is empty.
1440 \cvfunc{GetNextSparseNode}\label{GetNextSparseNode}
1442 Initializes sparse array elements iterator.
1446 CvSparseNode* cvGetNextSparseNode( CvSparseMatIterator* mat\_iterator );
1451 \cvarg{mat\_iterator}{Sparse array iterator}
1455 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 the hash table. The sample below demonstrates how to iterate through the sparse matrix:
1457 Using \cross{InitSparseMatIterator} and \cross{GetNextSparseNode} to calculate sum of floating-point sparse array.
1462 int i, dims = cvGetDims( array );
1463 CvSparseMatIterator mat_iterator;
1464 CvSparseNode* node = cvInitSparseMatIterator( array, &mat_iterator );
1466 for( ; node != 0; node = cvGetNextSparseNode( &mat_iterator ))
1468 /* get pointer to the element indices */
1469 int* idx = CV_NODE_IDX( array, node );
1470 /* get value of the element (assume that the type is CV_32FC1) */
1471 float val = *(float*)CV_NODE_VAL( array, node );
1473 for( i = 0; i < dims; i++ )
1474 printf( "%4d%s", idx[i], i < dims - 1 "," : "): " );
1475 printf( "%g\n", val );
1480 printf( "\nTotal sum = %g\n", sum );
1486 \cvfunc{GetElemType}\label{GetElemType}
1488 Returns type of array elements.
1492 int cvGetElemType( const CvArr* arr );
1494 }{CPP}{GetElemType(arr)-> int}
1497 \cvarg{arr}{Input array}
1501 The functions \texttt{GetElemType} returns type of the array elements
1502 as described in \cross{CreateMat} discussion: \texttt{CV\_8UC1}
1503 ... \texttt{CV\_64FC4}.
1506 \cvfunc{GetDims, GetDimSize}\label{GetDims, GetDimSize}
1508 Return number of array dimensions and their sizes or the size of a particular dimension.
1512 int cvGetDims( const CvArr* arr, int* sizes=NULL );
1515 int cvGetDimSize( const CvArr* arr, int index );
1519 \cvarg{arr}{Input array}
1520 \cvarg{sizes}{Optional output vector of the array dimension sizes. For
1521 2d arrays the number of rows (height) goes first, number of columns
1523 \cvarg{index}{Zero-based dimension index (for matrices 0 means number
1524 of rows, 1 means number of columns; for images 0 means height, 1 means
1529 The function \texttt{cvGetDims} returns number of array dimensions and
1530 their sizes. In the case of \texttt{IplImage} or \cross{CvMat} it always
1531 returns 2 regardless of number of image/matrix rows. The function
1532 \texttt{cvGetDimSize} returns the particular dimension size (number of
1533 elements per that dimension). For example, the following code calculates
1534 total number of array elements in two ways:
1539 int sizes[CV_MAX_DIM];
1541 int dims = cvGetDims( arr, size );
1542 for( i = 0; i < dims; i++ )
1545 // via cvGetDims() and cvGetDimSize()
1547 int dims = cvGetDims( arr );
1548 for( i = 0; i < dims; i++ )
1549 total *= cvGetDimsSize( arr, i );
1553 \cvexp{C}{CPP}{GetDims(arr)}
1556 \cvarg{arr}{Input array}
1560 The function \texttt{cvGetDims} returns a list of array dimensions.
1561 In the case of \texttt{IplImage} or \cross{CvMat} it always
1562 returns a list of length 2.
1566 \cvfunc{Ptr1D} \cvexp{uchar* cvPtr1D( const CvArr* arr, int idx0, int* type=NULL );}{}{}
1567 \cvfunc{Ptr2D} \cvexp{uchar* cvPtr2D( const CvArr* arr, int idx0, int idx1, int* type=NULL );}{}{}
1568 \cvfunc{Ptr3D} \cvexp{uchar* cvPtr3D( const CvArr* arr, int idx0, int idx1, int idx2, int* type=NULL );}{}{}
1570 Return pointer to a particular array element.
1571 \cvexp{uchar* cvPtrND( const CvArr* arr, int* idx, int* type=NULL, int create\_node=1, unsigned* precalc\_hashval=NULL );}{}{}
1573 \cvfunc{Ptr*D}\label{Ptr*D}
1575 Return pointer to a particular array element.
1579 uchar* cvPtr1D( const CvArr* arr, int idx0, int* type=NULL );
1580 uchar* cvPtr2D( const CvArr* arr, int idx0, int idx1, int* type=NULL );
1581 uchar* cvPtr3D( const CvArr* arr, int idx0, int idx1, int idx2, int* type=NULL );
1582 uchar* cvPtrND( const CvArr* arr, int* idx, int* type=NULL, int create\_node=1, unsigned* precalc\_hashval=NULL );
1588 \cvarg{arr}{Input array}
1589 \cvarg{idx0}{The first zero-based component of the element index}
1590 \cvarg{idx1}{The second zero-based component of the element index}
1591 \cvarg{idx2}{The third zero-based component of the element index}
1592 \cvarg{idx}{Array of the element indices}
1593 \cvarg{type}{Optional output parameter: type of matrix elements}
1594 \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.}
1595 \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)}
1598 The functions \texttt{cvPtr*D} return a pointer to a specific 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.
1600 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.
1602 All these as well as other functions accessing array elements (\cross{Get}, \cross{GetReal},
1604 \cross{Set}, \cross{SetReal}) raise an error in case if the element index is out of range.
1608 \cvfunc{Get1D} \cvexp{CvScalar cvGet1D( const CvArr* arr, int idx0 );}{}{}
1609 \cvfunc{Get2D} \cvexp{CvScalar cvGet2D( const CvArr* arr, int idx0, int idx1 );}{}{}
1610 \cvfunc{Get3D} \cvexp{CvScalar cvGet3D( const CvArr* arr, int idx0, int idx1, int idx2 );}{}{}
1612 Return a specific array element.
1613 \cvexp{CvScalar cvGetND( const CvArr* arr, int* idx );}{}{}
1616 \cvfunc{Get*D}\label{Get*D}
1618 Return a specific array element.
1622 CvScalar cvGet1D( const CvArr* arr, int idx0 );
1623 CvScalar cvGet2D( const CvArr* arr, int idx0, int idx1 );
1624 CvScalar cvGet3D( const CvArr* arr, int idx0, int idx1, int idx2 );
1625 CvScalar cvGetND( const CvArr* arr, int* idx );
1631 \cvarg{arr}{Input array}
1632 \cvarg{idx0}{The first zero-based component of the element index}
1633 \cvarg{idx1}{The second zero-based component of the element index}
1634 \cvarg{idx2}{The third zero-based component of the element index}
1635 \cvarg{idx}{Array of the element indices}
1639 The functions \texttt{cvGet*D} return a specific array element. In the case of a sparse array the functions return 0 if the requested node does not exist (no new node is created by the functions).
1642 \cvfunc{GetReal1D} \cvexp{double cvGetReal1D( const CvArr* arr, int idx0 );}{}{}
1643 \cvfunc{GetReal2D} \cvexp{double cvGetReal2D( const CvArr* arr, int idx0, int idx1 );}{}{}
1644 \cvfunc{GetReal3D} \cvexp{double cvGetReal3D( const CvArr* arr, int idx0, int idx1, int idx2 );}{}{}
1646 Return a specific element of single-channel array.
1647 \cvexp{double cvGetRealND( const CvArr* arr, int* idx );}{}{}
1650 \cvfunc{GetReal*D}\label{GetReal*D}
1652 Return a specific element of single-channel array.
1656 double cvGetReal1D( const CvArr* arr, int idx0 );
1657 double cvGetReal2D( const CvArr* arr, int idx0, int idx1 );
1658 double cvGetReal3D( const CvArr* arr, int idx0, int idx1, int idx2 );
1659 double cvGetRealND( const CvArr* arr, int* idx );
1665 \cvarg{arr}{Input array. Must have a single channel.}
1666 \cvarg{idx0}{The first zero-based component of the element index}
1667 \cvarg{idx1}{The second zero-based component of the element index}
1668 \cvarg{idx2}{The third zero-based component of the element index}
1669 \cvarg{idx}{Array of the element indices}
1673 The functions \texttt{cvGetReal*D} return a specific element of a single-channel array. If the array has multiple channels, a 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.
1675 In the case of a sparse array the functions return 0 if the requested node does not exist (no new node is created by the functions).
1677 \cvfunc{mGet}\label{mGet}
1679 Returns the particular element of single-channel floating-point matrix.
1683 double cvmGet( const CvMat* mat, int row, int col );
1685 }{CPP}{mGet(mat,row,col)-> double}
1688 \cvarg{mat}{Input matrix}
1689 \cvarg{row}{The zero-based index of row}
1690 \cvarg{col}{The zero-based index of column}
1693 The function \texttt{cvmGet} is a fast replacement for \cross{GetReal2D}
1694 in the case of single-channel floating-point matrices. It is faster because
1695 it is inline, it does fewer checks for array type and array element type,
1696 and it checks for the row and column ranges only in debug mode.
1699 \cvfunc{Set1D} \cvexp{void cvSet1D( CvArr* arr, int idx0, CvScalar value );}{}{}
1700 \cvfunc{Set2D} \cvexp{void cvSet2D( CvArr* arr, int idx0, int idx1, CvScalar value );}{}{}
1701 \cvfunc{Set3D} \cvexp{void cvSet3D( CvArr* arr, int idx0, int idx1, int idx2, CvScalar value );}{}{}
1703 Change the particular array element
1704 \cvexp{void cvSetND( CvArr* arr, int* idx, CvScalar value );}{}{}
1707 \cvfunc{Set*D}\label{Set*D}
1709 Change the particular array element.
1713 void cvSet1D( CvArr* arr, int idx0, CvScalar value );
1714 void cvSet2D( CvArr* arr, int idx0, int idx1, CvScalar value );
1715 void cvSet3D( CvArr* arr, int idx0, int idx1, int idx2, CvScalar value );
1716 void cvSetND( CvArr* arr, int* idx, CvScalar value );
1722 \cvarg{arr}{Input array}
1723 \cvarg{idx0}{The first zero-based component of the element index}
1724 \cvarg{idx1}{The second zero-based component of the element index}
1725 \cvarg{idx2}{The third zero-based component of the element index}
1726 \cvarg{idx}{Array of the element indices}
1727 \cvarg{value}{The assigned value}
1730 The functions \texttt{cvSet*D} assign the new value to a particular array element. In the case of a sparse array the functions create the node if it does not exist yet.
1733 \cvfunc{SetReal1D} \cvexp{void cvSetReal1D( CvArr* arr, int idx0, double value );}{}{}
1734 \cvfunc{SetReal2D} \cvexp{void cvSetReal2D( CvArr* arr, int idx0, int idx1, double value );}{}{}
1735 \cvfunc{SetReal3D} \cvexp{void cvSetReal3D( CvArr* arr, int idx0, int idx1, int idx2, double value );}{}{}
1736 \cvfunc{SetRealND} Change a specific array element.
1737 \cvexp{void cvSetRealND( CvArr* arr, int* idx, double value );}{}{}
1740 \cvfunc{SetReal*D}\label{SetReal*D}
1742 Change a specific array element.
1746 void cvSetReal1D( CvArr* arr, int idx0, double value );
1747 void cvSetReal2D( CvArr* arr, int idx0, int idx1, double value );
1748 void cvSetReal3D( CvArr* arr, int idx0, int idx1, int idx2, double value );
1749 void cvSetRealND( CvArr* arr, int* idx, double value );
1755 \cvarg{arr}{Input array}
1756 \cvarg{idx0}{The first zero-based component of the element index}
1757 \cvarg{idx1}{The second zero-based component of the element index}
1758 \cvarg{idx2}{The third zero-based component of the element index}
1759 \cvarg{idx}{Array of the element indices}
1760 \cvarg{value}{The assigned value}
1763 The functions \texttt{cvSetReal*D} assign a new value to a specific
1764 element of a single-channel array. If the array has multiple channels,
1765 a runtime error is raised. Note that the \cross{Set*D} function can be used
1766 safely for both single-channel and multiple-channel arrays, though they
1769 In the case of a sparse array the functions create the node if it does not yet exist.
1771 \cvfunc{mSet}\label{mSet}
1773 Returns a specific element of a single-channel floating-point matrix.
1777 void cvmSet( CvMat* mat, int row, int col, double value );
1779 }{CPP}{mSet(mat,row,col,value)-> None}
1782 \cvarg{mat}{The matrix}
1783 \cvarg{row}{The zero-based index of row}
1784 \cvarg{col}{The zero-based index of column}
1785 \cvarg{value}{The new value of the matrix element}
1789 The function \texttt{cvmSet} is a fast replacement for \cross{SetReal2D}
1790 in the case of single-channel floating-point matrices. It is faster because
1791 it is inline, it does fewer checks for array type and array element type,
1792 and it checks for the row and column ranges only in debug mode.
1794 \cvfunc{ClearND}\label{ClearND}
1796 Clears a specific array element.
1800 void cvClearND( CvArr* arr, int* idx );
1802 }{CPP}{ClearND(arr,idx)-> None}
1805 \cvarg{arr}{Input array}
1806 \cvarg{idx}{Array of the element indices}
1810 The function \cross{ClearND} clears (sets to zero) a specific element of a dense array or deletes the element of a sparse array. If the element does not exists, the function does nothing.
1813 \subsection{Copying and Filling}
1816 \cvfunc{Copy}\label{Copy}
1818 Copies one array to another.
1822 void cvCopy( const CvArr* src, CvArr* dst, const CvArr* mask=NULL );
1824 }{CPP}{Copy(src,dst,msk=NULL)-> None}
1827 \cvarg{src}{The source array}
1828 \cvarg{dst}{The destination array}
1829 \cvarg{mask}{Operation mask, 8-bit single channel array; specifies elements of the destination array to be changed}
1833 The function \texttt{cvCopy} copies selected elements from an input array to an output array:
1836 \texttt{dst}(I)=\texttt{src}(I) \quad \text{if} \quad \texttt{mask}(I) \ne 0.
1839 If any of the passed arrays is of \texttt{IplImage} type, then its ROI
1840 and COI fields are used. Both arrays must have the same type, the same
1841 number of dimensions, and the same size. The function can also copy sparse
1842 arrays (mask is not supported in this case).
1844 \cvfunc{Set}\label{Set}
1846 Sets every element of an array to a given value.
1850 void cvSet( CvArr* arr, CvScalar value, const CvArr* mask=NULL );
1852 }{CPP}{Set(arr,value,msk=NULL)-> None}
1855 \cvarg{arr}{The destination array}
1856 \cvarg{value}{Fill value}
1857 \cvarg{mask}{Operation mask, 8-bit single channel array; specifies elements of the destination array to be changed}
1861 The function \texttt{cvSet} copies the scalar \texttt{value} to every selected element of the destination array:
1864 \texttt{arr}(I)=\texttt{value} \quad \text{if} \quad \texttt{mask}(I) \ne 0
1867 If array \texttt{arr} is of \texttt{IplImage} type, then is ROI used, but COI must not be set.
1869 \cvfunc{SetZero}\label{SetZero}
1875 void cvSetZero( CvArr* arr );
1877 }{CPP}{SetZero(arr)-> None}
1880 #define cvZero cvSetZero
1884 \cvarg{arr}{Array to be cleared}
1887 The function \texttt{cvSetZero} clears the array. In the case of dense arrays (CvMat, CvMatND or IplImage), cvZero(array) is equivalent to
1888 cvSet(array,cvScalarAll(0),0).
1889 In the case of sparse arrays all the elements are removed.
1891 \subsection{Transforms and Permutations}
1893 \cvfunc{Reshape}\label{Reshape}
1895 Changes shape of matrix/image without copying data.
1899 CvMat* cvReshape( const CvArr* arr, CvMat* header, int new\_cn, int new\_rows=0 );
1901 }{CPP}{Reshape(arr, new\_cn, new\_rows=0) -> cvmat}
1904 \cvarg{arr}{Input array}
1906 \cvarg{header}{Output header to be filled}
1908 \cvarg{new\_cn}{New number of channels. 'new\_cn = 0' means that the number of channels remains unchanged.}
1909 \cvarg{new\_rows}{New number of rows. 'new\_rows = 0' means that the number of rows remains unchanged unless it needs to be changed according to \texttt{new\_cn} value.}
1912 The function \texttt{cvReshape} initializes the CvMat header so that it points to the same data as the original array but has a different shape - different number of channels, different number of rows, or both.
1915 For example, the following code creates one image buffer and two image headers, the first is for a 320x240x3 image and the second is for a 960x240x1 image:
1919 IplImage* color_img = cvCreateImage( cvSize(320,240), IPL_DEPTH_8U, 3 );
1921 IplImage gray_img_hdr, *gray_img;
1922 cvReshape( color_img, &gray_mat_hdr, 1 );
1923 gray_img = cvGetImage( &gray_mat_hdr, &gray_img_hdr );
1927 And the next example converts a 3x3 matrix to a single 1x9 vector:
1931 CvMat* mat = cvCreateMat( 3, 3, CV_32F );
1932 CvMat row_header, *row;
1933 row = cvReshape( mat, &row_header, 0, 1 );
1938 \cvfunc{ReshapeMatND}\label{ReshapeMatND}
1940 Changes the shape of a multi-dimensional array without copying the data.
1944 CvArr* cvReshapeMatND( const CvArr* arr,
1945 int sizeof\_header, CvArr* header,
1946 int new\_cn, int new\_dims, int* new\_sizes );
1947 }{CPP}{ReshapeMatND(arr, new\_cn, new\_dims) -> cvmat}
1951 #define cvReshapeND( arr, header, new\_cn, new\_dims, new\_sizes ) \
1952 cvReshapeMatND( (arr), sizeof(*(header)), (header), \
1953 (new\_cn), (new\_dims), (new\_sizes))
1958 \cvarg{arr}{Input array}
1960 \cvarg{sizeof\_header}{Size of output header to distinguish between IplImage, CvMat and CvMatND output headers}
1961 \cvarg{header}{Output header to be filled}
1962 \cvarg{new\_cn}{New number of channels. $\texttt{new\_cn} = 0$ means that the number of channels remains unchanged.}
1963 \cvarg{new\_dims}{New number of dimensions. $\texttt{new\_dims} = 0$ means that the number of dimensions remains the same.}
1964 \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.
1965 Thus, if $\texttt{new\_dims} = 1$, \texttt{new\_sizes} array is not used.}
1967 \cvarg{new\_dims}{List of new dimensions.}
1971 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}:
1976 IplImage* color_img = cvCreateImage( cvSize(320,240), IPL_DEPTH_8U, 3 );
1977 IplImage gray_img_hdr, *gray_img;
1978 gray_img = (IplImage*)cvReshapeND( color_img, &gray_img_hdr, 1, 0, 0 );
1982 /* second example is modified to convert 2x2x2 array to 8x1 vector */
1983 int size[] = { 2, 2, 2 };
1984 CvMatND* mat = cvCreateMatND( 3, size, CV_32F );
1985 CvMat row_header, *row;
1986 row = cvReshapeND( mat, &row_header, 0, 1, 0 );
1991 \cvfunc{Repeat}\label{Repeat}
1993 Fill the destination array with repeated copies of the source array.
1997 void cvRepeat( const CvArr* src, CvArr* dst );
1999 }{CPP}{Repeat(src,dst)-> None}
2002 \cvarg{src}{Source array, image or matrix}
2003 \cvarg{dst}{Destination array, image or matrix}
2007 The function \texttt{cvRepeat} fills the destination array with repeated copies of the source array:
2010 dst(i,j)=src(i mod rows(src), j mod cols(src))
2013 So the destination array may be as larger as well as smaller than the source array.
2016 \cvfunc{Flip}\label{Flip}
2018 Flip a 2D array around vertical, horizontal or both axes.
2021 void cvFlip( const CvArr* src, CvArr* dst=NULL, int flip\_mode=0);
2022 }{CPP}{Flip(src,dst=NULL,flip\_mode=0)-> None}
2025 #define cvMirror cvFlip
2029 \cvarg{src}{Source array}
2030 \cvarg{dst}{Destination array.
2031 If $\texttt{dst} = \texttt{NULL}$ the flipping is done in place.}
2032 \cvarg{flip\_mode}{Specifies how to flip the array:
2033 0 means flipping around the x-axis, positive (e.g., 1) means flipping around y-axis, and negative (e.g., -1) means flipping around both axes. See also the discussion below for the formulas:}
2036 The function \texttt{cvFlip} flips the array in one of three different ways (row and column indices are 0-based):
2039 dst(i,j) = \forkthree
2040 {\texttt{src}(rows(\texttt{src})-i-1,j)}{if $\texttt{flip\_mode} = 0$}
2041 {\texttt{src}(i,cols(\texttt{src})-j-1)}{if $\texttt{flip\_mode} > 0$}
2042 {\texttt{src}(rows(\texttt{src})-i-1,cols(\texttt{src})-j-1)}{if $\texttt{flip\_mode} < 0$}
2045 The example scenarios of function use are:
2047 \item vertical flipping of the image (flip\_mode = 0) to switch between top-left and bottom-left image origin, which is a typical operation in video processing under Win32 systems.
2048 \item horizontal flipping of the image with subsequent horizontal shift and absolute difference calculation to check for a vertical-axis symmetry (flip\_mode $>$ 0)
2049 \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)
2050 \item reversing the order of 1d point arrays (flip\_mode > 0)
2053 \cvfunc{Split}\label{Split}
2055 Divides multi-channel array into several single-channel arrays or extracts a single channel from the array.
2059 void cvSplit( const CvArr* src, CvArr* dst0, CvArr* dst1,
2060 CvArr* dst2, CvArr* dst3 );
2061 }{CPP}{Split(src,dst0,dst1,dst2,dst3)-> None}
2064 #define cvCvtPixToPlane cvSplit
2068 \cvarg{src}{Source array}
2069 \cvarg{dst0...dst3}{Destination channels}
2072 The function \texttt{cvSplit} divides a multi-channel array into separate
2073 single-channel arrays. Two modes are available for the operation. If the
2074 source array has N channels then if the first N destination channels
2075 are not NULL, they all are extracted from the source array;
2076 if only a single destination channel of the first N is not NULL, this
2077 particular channel is extracted; otherwise an error is raised. The rest
2078 of the destination channels (beyond the first N) must always be NULL. For
2079 IplImage \cross{Copy} with COI set can be also used to extract a single
2080 channel from the image.
2083 \cvfunc{Merge}\label{Merge}
2085 Composes a multi-channel array from several single-channel arrays or inserts a single channel into the array.
2089 void cvMerge( const CvArr* src0, const CvArr* src1,
2090 const CvArr* src2, const CvArr* src3, CvArr* dst );
2091 }{CPP}{Merge(src0,src1,src2,src3,dst)-> None}
2094 #define cvCvtPlaneToPix cvMerge
2098 \cvarg{src0...src3}{Input channels}
2099 \cvarg{dst}{Destination array}
2102 The function \texttt{cvMerge} is the opposite to \cross{Split}. If the destination array has N channels then if the first N input channels are not NULL, they all are copied to the destination array; 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. The rest of the 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.
2104 \cvfunc{MixChannels}\label{MixChannels}
2106 Copies several channels from input arrays to certain channels of output arrays
2110 void cvMixChannels( const CvArr** src, int src\_count, \par
2111 CvArr** dst, int dst\_count, \par
2112 const int* from\_to, int pair\_count );
2114 }{CPP}{MixChannels(src, dst, from\_to) -> None}
2117 \cvarg{src}{Input arrays}
2118 \cvC{\cvarg{src\_count}{The number of input arrays.}}
2119 \cvarg{dst}{Destination arrays}
2120 \cvC{\cvarg{dst\_count}{The number of output arrays.}}
2121 \cvarg{from\_to}{The array of pairs of indices of the planes
2122 copied. \cvC{\texttt{from\_to[k*2]} is the 0-based index of the input plane, and
2123 \texttt{from\_to[k*2+1]} is the index of the output plane in their respective array entries.
2124 As a special case, when the source array entry is \texttt{NULL}, i is ignored
2125 and output plane j is filled with zero.}\cvPy{Each pair (i,j)
2126 means that for the corresponding input and output arrays, plane i is
2127 copied to output plane j.
2128 As a special case, when the source array entry is \texttt{None}, i is
2129 ignored and output plane j is filled with zero.}
2133 The function cvMixChannels is a generalized form of \cross{Split} and \cross{Merge}
2134 and some forms of \cross{CvtColor}. It can be used to change the order of the
2135 planes, add/remove alpha channel, extract or insert a single plane or
2136 multiple planes etc.
2138 As an example, this code splits a 4-channel RGBA image into a 3-channel
2139 BGR (i.e. with R and B swapped) and separate alpha channel image:
2143 rgba = cv.CreateMat(100, 100, cv.CV_8UC4)
2144 bgr = cv.CreateMat(100, 100, cv.CV_8UC3)
2145 alpha = cv.CreateMat(100, 100, cv.CV_8UC1)
2146 cv.Set(rgba, (1,2,3,4))
2147 cv.MixChannels([rgba], [bgr, alpha], [
2148 (0, 2), # rgba[0] -> bgr[2]
2149 (1, 1), # rgba[1] -> bgr[1]
2150 (2, 0), # rgba[2] -> bgr[0]
2151 (3, 3) # rgba[3] -> alpha[0]
2158 CvMat* rgba = cvCreateMat( 100, 100, CV_8UC4 );
2159 CvMat* bgr = cvCreateMat( rgba->rows, rgba->cols, CV_8UC3 );
2160 CvMat* alpha = cvCreateMat( rgba->rows, rgba->cols, CV_8UC1 );
2161 cvSet( rgba, cvScalar(1,2,3,4) );
2163 CvArr* out[] = { bgr, alpha };
2164 int from_to[] = { 0,2, 1,1, 2,0, 3,3 };
2165 cvMixChannels( &bgra, 1, out, 2, from_to, 4 );
2169 \subsection{Arithmetic, Logic and Comparison}
2171 \cvfunc{LUT}\label{LUT}
2173 Performs a look-up table transform of an array.
2177 void cvLUT( const CvArr* src, CvArr* dst, const CvArr* lut );
2179 }{CPP}{LUT(src,dst,lut)-> None}
2182 \cvarg{src}{Source array of 8-bit elements}
2183 \cvarg{dst}{Destination array of a given depth and of the same number of channels as the source array}
2184 \cvarg{lut}{Look-up table of 256 elements; should have the same depth as the destination array. In the 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.}
2187 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 follows:
2190 \texttt{dst}_i \leftarrow \texttt{lut}_{\texttt{src}_i + d}
2197 {0}{if \texttt{src} has depth \texttt{CV\_8U}}
2198 {128}{if \texttt{src} has depth \texttt{CV\_8S}}
2201 \cvfunc{ConvertScale}\label{ConvertScale}
2203 Converts one array to another with optional linear transformation.
2207 void cvConvertScale( const CvArr* src, CvArr* dst, double scale=1, double shift=0 );
2209 }{CPP}{ConvertScale(src,dst,scale=1.0,shift=0.0)-> None}
2212 #define cvCvtScale cvConvertScale
2213 #define cvScale cvConvertScale
2214 #define cvConvert( src, dst ) cvConvertScale( (src), (dst), 1, 0 )
2218 \cvarg{src}{Source array}
2219 \cvarg{dst}{Destination array}
2220 \cvarg{scale}{Scale factor}
2221 \cvarg{shift}{Value added to the scaled source array elements}
2225 The function \texttt{cvConvertScale} has several different purposes, and thus has several different names. It copies one array to another with optional scaling, which is performed first, and/or optional type conversion, performed after:
2228 \texttt{dst}(I) = \texttt{scale} \texttt{src}(I) + (\texttt{shift}_0,\texttt{shift}_1,...)
2231 All the channels of multi-channel arrays are processed independently.
2233 The type of conversion is done with rounding and saturation, that is if the
2234 result of scaling + conversion can not be represented exactly by a value
2235 of the destination array element type, it is set to the nearest representable
2236 value on the real axis.
2238 In the case of \texttt{scale=1, shift=0} no prescaling is done. This is a specially
2239 optimized case and it has the appropriate \cross{Convert} name. If
2240 source and destination array types have equal types, this is also a
2241 special case that can be used to scale and shift a matrix or an image
2242 and that is caled \cross{Scale}.
2244 \cvfunc{ConvertScaleAbs}\label{ConvertScaleAbs}
2246 Converts input array elements to another 8-bit unsigned integer with optional linear transformation.
2249 void cvConvertScaleAbs( const CvArr* src, CvArr* dst, double scale=1, double shift=0 );
2250 }{CPP}{ConvertScaleAbs(src,dst,scale=1.0,shift=0.0)-> None}
2253 #define cvCvtScaleAbs cvConvertScaleAbs
2257 \cvarg{src}{Source array}
2258 \cvarg{dst}{Destination array (should have 8u depth)}
2259 \cvarg{scale}{ScaleAbs factor}
2260 \cvarg{shift}{Value added to the scaled source array elements}
2264 The function \texttt{cvConvertScaleAbs} is similar to \cross{ConvertScale}, but it stores absolute values of the conversion results:
2267 \texttt{dst}(I) = |\texttt{scale} \texttt{src}(I) + (\texttt{shift}_0,\texttt{shift}_1,...)|
2270 The function supports only destination arrays of 8u (8-bit unsigned integers) type; for other types the function can be emulated by a combination of \cross{ConvertScale} and \cross{Abs} functions.
2272 \cvfunc{Add}\label{Add}
2274 Computes the per-element sum of two arrays.
2278 void cvAdd( const CvArr* src1, const CvArr* src2, CvArr* dst, const CvArr* mask=NULL );
2280 }{CPP}{Add(src1,src2,sdt,mask=NULL)-> None}
2283 \cvarg{src1}{The first source array}
2284 \cvarg{src2}{The second source array}
2285 \cvarg{dst}{The destination array}
2286 \cvarg{mask}{Operation mask, 8-bit single channel array; specifies elements of the destination array to be changed}
2289 The function \texttt{cvAdd} adds one array to another:
2292 dst(I)=src1(I)+src2(I) if mask(I)!=0
2295 All the arrays must have the same type, except the mask, and the same size (or ROI size).
2296 For types that have limited range this operation is saturating.
2298 \cvfunc{AddS}\label{AddS}
2300 Computes the sum of an array and a scalar.
2304 void cvAddS( const CvArr* src, CvScalar value, CvArr* dst, const CvArr* mask=NULL );
2306 }{CPP}{AddS(src1,value,dst,mask=NULL)-> None}
2309 \cvarg{src}{The source array}
2310 \cvarg{value}{Added scalar}
2311 \cvarg{dst}{The destination array}
2312 \cvarg{mask}{Operation mask, 8-bit single channel array; specifies elements of the destination array to be changed}
2316 The function \texttt{cvAddS} adds a scalar \texttt{value} to every element in the source array \texttt{src1} and stores the result in \texttt{dst}.
2317 For types that have limited range this operation is saturating.
2320 dst(I)=src(I)+value if mask(I)!=0
2323 All the arrays must have the same type, except the mask, and the same size (or ROI size).
2326 \cvfunc{AddWeighted}\label{AddWeighted}
2328 Computes the weighted sum of two arrays.
2332 void cvAddWeighted( const CvArr* src1, double alpha,
2333 const CvArr* src2, double beta,
2334 double gamma, CvArr* dst );
2336 }{CPP}{AddWeighted(src1,alpha,src2,beta,gamma,dst)-> None}
2339 \cvarg{src1}{The first source array}
2340 \cvarg{alpha}{Weight for the first array elements}
2341 \cvarg{src2}{The second source array}
2342 \cvarg{beta}{Weight for the second array elements}
2343 \cvarg{dst}{The destination array}
2344 \cvarg{gamma}{Scalar, added to each sum}
2347 The function \texttt{cvAddWeighted} calculates the weighted sum of two arrays as follows:
2350 dst(I)=src1(I)*alpha+src2(I)*beta+gamma
2353 All the arrays must have the same type and the same size (or ROI size).
2354 For types that have limited range this operation is saturating.
2357 \cvfunc{Sub}\label{Sub}
2359 Computes the per-element difference between two arrays.
2363 void cvSub( const CvArr* src1, const CvArr* src2, CvArr* dst, const CvArr* mask=NULL );
2365 }{CPP}{Sub(src1,src2,dst,mask=NULL)-> None}
2368 \cvarg{src1}{The first source array}
2369 \cvarg{src2}{The second source array}
2370 \cvarg{dst}{The destination array}
2371 \cvarg{mask}{Operation mask, 8-bit single channel array; specifies elements of the destination array to be changed}
2375 The function \texttt{cvSub} subtracts one array from another one:
2378 dst(I)=src1(I)-src2(I) if mask(I)!=0
2381 All the arrays must have the same type, except the mask, and the same size (or ROI size).
2382 For types that have limited range this operation is saturating.
2384 \cvfunc{SubS}\label{SubS}
2386 Computes the difference between an array and a scalar.
2390 void cvSubS( const CvArr* src, CvScalar value, CvArr* dst, const CvArr* mask=NULL );
2392 }{CPP}{SubS(src1,value,dst,mask=NULL)-> None}
2395 \cvarg{src}{The source array}
2396 \cvarg{value}{Subtracted scalar}
2397 \cvarg{dst}{The destination array}
2398 \cvarg{mask}{Operation mask, 8-bit single channel array; specifies elements of the destination array to be changed}
2401 The function \texttt{cvSubS} subtracts a scalar from every element of the source array:
2404 dst(I)=src(I)-value if mask(I)!=0
2407 All the arrays must have the same type, except the mask, and the same size (or ROI size).
2408 For types that have limited range this operation is saturating.
2411 \cvfunc{SubRS}\label{SubRS}
2413 Computes the difference between a scalar and an array.
2417 void cvSubRS( const CvArr* src, CvScalar value, CvArr* dst, const CvArr* mask=NULL );
2419 }{CPP}{SubRS(src1,value,dst,mask=NULL)-> None}
2422 \cvarg{src}{The first source array}
2423 \cvarg{value}{Scalar to subtract from}
2424 \cvarg{dst}{The destination array}
2425 \cvarg{mask}{Operation mask, 8-bit single channel array; specifies elements of the destination array to be changed}
2429 The function \texttt{cvSubRS} subtracts every element of source array from a scalar:
2432 dst(I)=value-src(I) if mask(I)!=0
2435 All the arrays must have the same type, except the mask, and the same size (or ROI size).
2436 For types that have limited range this operation is saturating.
2438 \cvfunc{Mul}\label{Mul}
2440 Calculates the per-element product of two arrays.
2444 void cvMul( const CvArr* src1, const CvArr* src2, CvArr* dst, double scale=1 );
2446 }{CPP}{Mul(src1,src2,dst,scale)-> None}
2449 \cvarg{src1}{The first source array}
2450 \cvarg{src2}{The second source array}
2451 \cvarg{dst}{The destination array}
2452 \cvarg{scale}{Optional scale factor}
2456 The function \texttt{cvMul} calculates the per-element product of two arrays:
2459 \texttt{dst}(I)=\texttt{scale} \cdot \texttt{src1}(I) \cdot \texttt{src2}(I)
2462 All the arrays must have the same type and the same size (or ROI size).
2463 For types that have limited range this operation is saturating.
2465 \cvfunc{Div}\label{Div}
2467 Performs per-element division of two arrays.
2471 void cvDiv( const CvArr* src1, const CvArr* src2, CvArr* dst, double scale=1 );
2473 }{CPP}{Div(src1,src2,dst,scale)-> None}
2476 \cvarg{src1}{The first source array. If the pointer is NULL, the array is assumed to be all 1's.}
2477 \cvarg{src2}{The second source array}
2478 \cvarg{dst}{The destination array}
2479 \cvarg{scale}{Optional scale factor}
2482 The function \texttt{cvDiv} divides one array by another:
2485 \texttt{dst}(I)=\fork
2486 {\texttt{scale} \cdot \texttt{src1}(I)/\texttt{src2}(I)}{if \texttt{src1} is not \texttt{NULL}}
2487 {\texttt{scale}/\texttt{src2}(I)}{otherwise}
2490 All the arrays must have the same type and the same size (or ROI size).
2493 \cvfunc{And}\label{And}
2495 Calculates per-element bit-wise conjunction of two arrays.
2499 void cvAnd( const CvArr* src1, const CvArr* src2, CvArr* dst, const CvArr* mask=NULL );
2501 }{CPP}{And(src1,src2,dst,mask=NULL)-> None}
2504 \cvarg{src1}{The first source array}
2505 \cvarg{src2}{The second source array}
2506 \cvarg{dst}{The destination array}
2507 \cvarg{mask}{Operation mask, 8-bit single channel array; specifies elements of the destination array to be changed}
2511 The function \texttt{cvAnd} calculates per-element bit-wise logical conjunction of two arrays:
2514 dst(I)=src1(I)&src2(I) if mask(I)!=0
2517 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.
2519 \cvfunc{AndS}\label{AndS}
2521 Calculates per-element bit-wise conjunction of an array and a scalar.
2525 void cvAndS( const CvArr* src, CvScalar value, CvArr* dst, const CvArr* mask=NULL );
2527 }{CPP}{AndS(src1,value,dst,mask=NULL)-> None}
2530 \cvarg{src}{The source array}
2531 \cvarg{value}{Scalar to use in the operation}
2532 \cvarg{dst}{The destination array}
2533 \cvarg{mask}{Operation mask, 8-bit single channel array; specifies elements of the destination array to be changed}
2536 The function AndS calculates per-element bit-wise conjunction of an array and a scalar:
2539 dst(I)=src(I)&value if mask(I)!=0
2542 Prior to the actual operation, the scalar is converted to the same type as that of the array(s). 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.
2544 The following sample demonstrates how to calculate the absolute value of floating-point array elements by clearing the most-significant bit:
2548 float a[] = { -1, 2, -3, 4, -5, 6, -7, 8, -9 };
2549 CvMat A = cvMat( 3, 3, CV\_32F, &a );
2550 int i, abs\_mask = 0x7fffffff;
2551 cvAndS( &A, cvRealScalar(*(float*)&abs\_mask), &A, 0 );
2552 for( i = 0; i < 9; i++ )
2553 printf("%.1f ", a[i] );
2557 The code should print:
2560 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0
2564 \cvfunc{Or}\label{Or}
2566 Calculates per-element bit-wise disjunction of two arrays.
2570 void cvOr( const CvArr* src1, const CvArr* src2, CvArr* dst, const CvArr* mask=NULL );
2572 }{CPP}{Or(src1,src2,dst,mask=NULL)-> None}
2575 \cvarg{src1}{The first source array}
2576 \cvarg{src2}{The second source array}
2577 \cvarg{dst}{The destination array}
2578 \cvarg{mask}{Operation mask, 8-bit single channel array; specifies elements of the destination array to be changed}
2582 The function \texttt{cvOr} calculates per-element bit-wise disjunction of two arrays:
2585 dst(I)=src1(I)|src2(I)
2588 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.
2590 \cvfunc{OrS}\label{OrS}
2592 Calculates a per-element bit-wise disjunction of an array and a scalar.
2596 void cvOrS( const CvArr* src, CvScalar value, CvArr* dst, const CvArr* mask=NULL );
2598 }{CPP}{OrS(src1,value,dst,mask=NULL)-> None}
2601 \cvarg{src1}{The source array}
2602 \cvarg{value}{Scalar to use in the operation}
2603 \cvarg{dst}{The destination array}
2604 \cvarg{mask}{Operation mask, 8-bit single channel array; specifies elements of the destination array to be changed}
2608 The function OrS calculates per-element bit-wise disjunction of an array and a scalar:
2611 dst(I)=src(I)|value if mask(I)!=0
2614 Prior to the actual operation, the scalar is converted to the same type as that of the array(s). 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.
2617 \cvfunc{Xor}\label{Xor}
2619 Performs per-element bit-wise "exclusive or" operation on two arrays.
2623 void cvXor( const CvArr* src1, const CvArr* src2, CvArr* dst, const CvArr* mask=NULL );
2625 }{CPP}{Xor(src1,src2,dst,mask=NULL)-> None}
2628 \cvarg{src1}{The first source array}
2629 \cvarg{src2}{The second source array}
2630 \cvarg{dst}{The destination array}
2631 \cvarg{mask}{Operation mask, 8-bit single channel array; specifies elements of the destination array to be changed}
2634 The function \texttt{cvXor} calculates per-element bit-wise logical conjunction of two arrays:
2637 dst(I)=src1(I)^src2(I) if mask(I)!=0
2640 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.
2642 \cvfunc{XorS}\label{XorS}
2644 Performs per-element bit-wise "exclusive or" operation on an array and a scalar.
2648 void cvXorS( const CvArr* src, CvScalar value, CvArr* dst, const CvArr* mask=NULL );
2650 }{CPP}{XorS(src1,value,dst,mask=NULL)-> None}
2653 \cvarg{src}{The source array}
2654 \cvarg{value}{Scalar to use in the operation}
2655 \cvarg{dst}{The destination array}
2656 \cvarg{mask}{Operation mask, 8-bit single channel array; specifies elements of the destination array to be changed}
2660 The function XorS calculates per-element bit-wise conjunction of an array and a scalar:
2663 dst(I)=src(I)^value if mask(I)!=0
2666 Prior to the actual operation, the scalar is converted to the same type as that of the array(s). 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
2668 The following sample demonstrates how to conjugate complex vector by switching the most-significant bit of imaging part:
2672 float a[] = { 1, 0, 0, 1, -1, 0, 0, -1 }; /* 1, j, -1, -j */
2673 CvMat A = cvMat( 4, 1, CV\_32FC2, &a );
2674 int i, neg\_mask = 0x80000000;
2675 cvXorS( &A, cvScalar( 0, *(float*)&neg\_mask, 0, 0 ), &A, 0 );
2676 for( i = 0; i < 4; i++ )
2677 printf("(%.1f, %.1f) ", a[i*2], a[i*2+1] );
2681 The code should print:
2684 (1.0,0.0) (0.0,-1.0) (-1.0,0.0) (0.0,1.0)
2687 \cvfunc{Not}\label{Not}
2689 Performs per-element bit-wise inversion of array elements.
2693 void cvNot( const CvArr* src, CvArr* dst );
2695 }{CPP}{Not(src,dst)-> None}
2698 \cvarg{src1}{The source array}
2699 \cvarg{dst}{The destination array}
2703 The function Not inverses every bit of every array element:
2710 \cvfunc{Cmp}\label{Cmp}
2712 Performs per-element comparison of two arrays.
2716 void cvCmp( const CvArr* src1, const CvArr* src2, CvArr* dst, int cmp\_op );
2718 }{CPP}{Cmp(src1,src2,dst,cm\_op)-> None}
2721 \cvarg{src1}{The first source array}
2722 \cvarg{src2}{The second source array. Both source arrays must have a single channel.}
2723 \cvarg{dst}{The destination array, must have 8u or 8s type}
2724 \cvarg{cmp\_op}{The flag specifying the relation between the elements to be checked
2726 \cvarg{CV\_CMP\_EQ}{src1(I) "equal to" value}
2727 \cvarg{CV\_CMP\_GT}{src1(I) "greater than" value}
2728 \cvarg{CV\_CMP\_GE}{src1(I) "greater or equal" value}
2729 \cvarg{CV\_CMP\_LT}{src1(I) "less than" value}
2730 \cvarg{CV\_CMP\_LE}{src1(I) "less or equal" value}
2731 \cvarg{CV\_CMP\_NE}{src1(I) "not equal" value}
2735 The function \texttt{cvCmp} compares the corresponding elements of two arrays and fills the destination mask array:
2739 dst(I)=src1(I) op src2(I),
2743 \texttt{dst(I)} is set to 0xff (all \texttt{1}-bits) if the specific 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)
2745 \cvfunc{CmpS}\label{CmpS}
2747 Performs per-element comparison of an array and a scalar.
2751 void cvCmpS( const CvArr* src, double value, CvArr* dst, int cmp\_op );
2753 }{CPP}{CmpS(src1,value,dst,cmp\_op)-> None}
2756 \cvarg{src}{The source array, must have a single channel}
2757 \cvarg{value}{The scalar value to compare each array element with}
2758 \cvarg{dst}{The destination array, must have 8u or 8s type}
2759 \cvarg{cmp\_op}{The flag specifying the relation between the elements to be checked
2761 \cvarg{CV\_CMP\_EQ}{src1(I) "equal to" value}
2762 \cvarg{CV\_CMP\_GT}{src1(I) "greater than" value}
2763 \cvarg{CV\_CMP\_GE}{src1(I) "greater or equal" value}
2764 \cvarg{CV\_CMP\_LT}{src1(I) "less than" value}
2765 \cvarg{CV\_CMP\_LE}{src1(I) "less or equal" value}
2766 \cvarg{CV\_CMP\_NE}{src1(I) "not equal" value}
2770 The function \texttt{CmpS} compares the corresponding elements of an array and a scalar and fills the destination mask array:
2774 dst(I)=src(I) op scalar
2778 where \texttt{op} is $=$, $>$, $\ge$, $<$, $\le$ or $\ne$.
2780 dst(I) is set to 0xff (all \texttt{1}-bits) if the specific relation between the elements is true and 0 otherwise. All the arrays must have the same size (or ROI size).
2782 \cvfunc{InRange}\label{InRange}
2784 Checks that array elements lie between the elements of two other arrays.
2788 void cvInRange( const CvArr* src, const CvArr* lower, const CvArr* upper, CvArr* dst );
2790 }{CPP}{InRange(src,lower,upper,dst)-> None}
2793 \cvarg{src}{The first source array}
2794 \cvarg{lower}{The inclusive lower boundary array}
2795 \cvarg{upper}{The exclusive upper boundary array}
2796 \cvarg{dst}{The destination array, must have 8u or 8s type}
2800 The function \texttt{cvInRange} does the range check for every element of the input array:
2803 \texttt{dst}(I)=\texttt{lower}(I)_0 <= \texttt{src}(I)_0 < \texttt{upper}(I)_0
2806 For single-channel arrays,
2810 \texttt{lower}(I)_0 <= \texttt{src}(I)_0 < \texttt{upper}(I)_0 \land
2811 \texttt{lower}(I)_1 <= \texttt{src}(I)_1 < \texttt{upper}(I)_1
2814 For two-channel arrays and so forth,
2816 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).
2819 \cvfunc{InRangeS}\label{InRangeS}
2821 Checks that array elements lie between two scalars.
2825 void cvInRangeS( const CvArr* src, CvScalar lower, CvScalar upper, CvArr* dst );
2827 }{CPP}{InRangeS(src,lower,upper,dst)-> None}
2830 \cvarg{src}{The first source array}
2831 \cvarg{lower}{The inclusive lower boundary}
2832 \cvarg{upper}{The exclusive upper boundary}
2833 \cvarg{dst}{The destination array, must have 8u or 8s type}
2837 The function \texttt{cvInRangeS} does the range check for every element of the input array:
2840 \texttt{dst}(I)=\texttt{lower}_0 <= \texttt{src}(I)_0 < \texttt{upper}_0
2843 For single-channel arrays,
2847 \texttt{lower}_0 <= \texttt{src}(I)_0 < \texttt{upper}_0 \land
2848 \texttt{lower}_1 <= \texttt{src}(I)_1 < \texttt{upper}_1
2851 For two-channel arrays nd so forth,
2853 '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).
2855 \cvfunc{Max}\label{Max}
2857 Finds per-element maximum of two arrays.
2861 void cvMax( const CvArr* src1, const CvArr* src2, CvArr* dst );
2863 }{CPP}{Max(src1,src2,dst)-> None}
2866 \cvarg{src1}{The first source array}
2867 \cvarg{src2}{The second source array}
2868 \cvarg{dst}{The destination array}
2871 The function \texttt{cvMax} calculates per-element maximum of two arrays:
2874 \texttt{dst}(I)=\max(\texttt{src1}(I), \texttt{src2}(I))
2877 All the arrays must have a single channel, the same data type and the same size (or ROI size).
2880 \cvfunc{MaxS}\label{MaxS}
2882 Finds per-element maximum of array and scalar.
2886 void cvMaxS( const CvArr* src, double value, CvArr* dst );
2888 }{CPP}{MaxS(src1,value,dst)-> None}
2891 \cvarg{src}{The first source array}
2892 \cvarg{value}{The scalar value}
2893 \cvarg{dst}{The destination array}
2896 The function \texttt{cvMaxS} calculates per-element maximum of array and scalar:
2899 \texttt{dst}(I)=\max(\texttt{src}(I), \texttt{value})
2902 All the arrays must have a single channel, the same data type and the same size (or ROI size).
2905 \cvfunc{Min}\label{Min}
2907 Finds per-element minimum of two arrays.
2911 void cvMin( const CvArr* src1, const CvArr* src2, CvArr* dst );
2913 }{CPP}{Min(src1,src2,dst)-> None}
2916 \cvarg{src1}{The first source array}
2917 \cvarg{src2}{The second source array}
2918 \cvarg{dst}{The destination array}
2922 The function \texttt{cvMin} calculates per-element minimum of two arrays:
2925 \texttt{dst}(I)=\min(\texttt{src1}(I),\texttt{src2}(I))
2928 All the arrays must have a single channel, the same data type and the same size (or ROI size).
2931 \cvfunc{MinS}\label{MinS}
2933 Finds per-element minimum of an array and a scalar.
2937 void cvMinS( const CvArr* src, double value, CvArr* dst );
2939 }{CPP}{MinS(src1,value,dst)-> None}
2942 \cvarg{src}{The first source array}
2943 \cvarg{value}{The scalar value}
2944 \cvarg{dst}{The destination array}
2947 The function \texttt{cvMinS} calculates minimum of an array and a scalar:
2950 \texttt{dst}(I)=\min(\texttt{src}(I), \texttt{value})
2953 All the arrays must have a single channel, the same data type and the same size (or ROI size).
2955 \cvfunc{AbsDiff}\label{AbsDiff}
2957 Calculates absolute difference between two arrays.
2961 void cvAbsDiff( const CvArr* src1, const CvArr* src2, CvArr* dst );
2963 }{CPP}{AbsDiff(src1,src2,dst)-> None}
2966 \cvarg{src1}{The first source array}
2967 \cvarg{src2}{The second source array}
2968 \cvarg{dst}{The destination array}
2971 The function \texttt{cvAbsDiff} calculates absolute difference between two arrays.
2973 \[ \texttt{dst}(i)_c = |\texttt{src1}(I)_c - \texttt{src2}(I)_c| \]
2975 All the arrays must have the same data type and the same size (or ROI size).
2977 \cvfunc{AbsDiffS}\label{AbsDiffS}
2979 Calculates absolute difference between an array and a scalar.
2983 void cvAbsDiffS( const CvArr* src, CvArr* dst, CvScalar value );
2984 }{CPP}{AbsDiffS(src1,value,dst)-> None}
2987 #define cvAbs(src, dst) cvAbsDiffS(src, dst, cvScalarAll(0))
2991 \cvarg{src}{The source array}
2992 \cvarg{dst}{The destination array}
2993 \cvarg{value}{The scalar}
2996 The function \texttt{cvAbsDiffS} calculates absolute difference between an array and a scalar.
2998 \[ \texttt{dst}(i)_c = |\texttt{src}(I)_c - \texttt{value}_c| \]
3000 All the arrays must have the same data type and the same size (or ROI size).
3002 \subsection{Statistics}
3004 \cvfunc{CountNonZero}\label{CountNonZero}
3006 Counts non-zero array elements.
3010 int cvCountNonZero( const CvArr* arr );
3012 }{CPP}{CountNonZero(arr)-> int}
3015 \cvarg{arr}{The array must be a single-channel array or a multi-channel image with COI set}
3019 The function \texttt{cvCountNonZero} returns the number of non-zero elements in arr:
3021 \[ \sum_I (\texttt{arr}(I) \ne 0) \]
3023 In the case of \texttt{IplImage} both ROI and COI are supported.
3026 \cvfunc{Sum}\label{Sum}
3028 Adds up array elements.
3032 CvScalar cvSum( const CvArr* arr );
3034 }{CPP}{Sum(arr)-> CvScalar}
3037 \cvarg{arr}{The array}
3041 The function \texttt{cvSum} calculates the sum \texttt{S} of array elements, independently for each channel:
3043 \[ \sum_I \texttt{arr}(I)_c \]
3045 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
3049 \cvfunc{Avg}\label{Avg}
3051 Calculates average (mean) of array elements.
3055 CvScalar cvAvg( const CvArr* arr, const CvArr* mask=NULL );
3057 }{CPP}{Avg(arr,mask=NULL)-> CvScalar}
3060 \cvarg{arr}{The array}
3061 \cvarg{mask}{The optional operation mask}
3065 The function \texttt{cvAvg} calculates the average value \texttt{M} of array elements, independently for each channel:
3069 N = \sum_I (\texttt{mask}(I) \ne 0)\\
3070 M_c = \frac{\sum_{ I, \, \texttt{mask}(I) \ne 0} \texttt{arr}(I)_c}{N}
3074 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 $ .
3076 \cvfunc{AvgSdv}\label{AvgSdv}
3078 Calculates average (mean) of array elements.
3082 void cvAvgSdv( const CvArr* arr, CvScalar* mean, CvScalar* std\_dev, const CvArr* mask=NULL );
3084 }{CPP}{AvgSdv(arr,mask=NULL)-> mean, std\_dev}
3087 \cvarg{arr}{The array}
3089 \cvarg{mean}{Pointer to the mean value, may be NULL if it is not needed}
3090 \cvarg{std\_dev}{Pointer to the standard deviation}
3092 \cvarg{mask}{The optional operation mask}
3094 \cvarg{mean}{Mean value, a CvScalar}
3095 \cvarg{std\_dev}{Standard deviation, a CvScalar}
3100 The function \texttt{cvAvgSdv} calculates the average value and standard deviation of array elements, independently for each channel:
3104 N = \sum_I (\texttt{mask}(I) \ne 0)\\
3105 mean_c = \frac{1}{N} \, \sum_{ I, \, \texttt{mask}(I) \ne 0} \texttt{arr}(I)_c\\
3106 std\_dev_c = \sqrt{\frac{1}{N} \, \sum_{ I, \, \texttt{mask}(I) \ne 0} (\texttt{arr}(I)_c - mean_c)^2}
3110 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 components of the output scalars ($mean_0$ and $std\_dev_0$).
3112 \cvfunc{MinMaxLoc}\label{MinMaxLoc}
3114 Finds global minimum and maximum in array or subarray.
3118 void cvMinMaxLoc( const CvArr* arr, double* min\_val, double* max\_val,
3119 CvPoint* min\_loc=NULL, CvPoint* max\_loc=NULL, const CvArr* mask=NULL );
3121 }{CPP}{MinMaxLoc(arr,mask=NULL)-> min\_val,max\_val,min\_loc,max\_loc}
3124 \cvarg{arr}{The source array, single-channel or multi-channel with COI set}
3125 \cvarg{min\_val}{Pointer to returned minimum value}
3126 \cvarg{max\_val}{Pointer to returned maximum value}
3127 \cvarg{min\_loc}{Pointer to returned minimum location}
3128 \cvarg{max\_loc}{Pointer to returned maximum location}
3129 \cvarg{mask}{The optional mask used to select a subarray}
3132 The function \texttt{MinMaxLoc} finds minimum and maximum element values
3133 and their positions. The extremums are searched across the whole array,
3134 selected \texttt{ROI} (in the case of \texttt{IplImage}) or, if \texttt{mask}
3135 is not \texttt{NULL}, in the specified array region. If the array has
3136 more than one channel, it must be \texttt{IplImage} with \texttt{COI}
3137 set. In the case of multi-dimensional arrays, \texttt{min\_loc->x} and \texttt{max\_loc->x}
3138 will contain raw (linear) positions of the extremums.
3140 \cvfunc{Norm}\label{Norm}
3142 Calculates absolute array norm, absolute difference norm, or relative difference norm.
3146 double cvNorm( const CvArr* arr1, const CvArr* arr2=NULL, int norm\_type=CV\_L2, const CvArr* mask=NULL );
3148 }{CPP}{Norm(arr1,arr2,norm\_type+CV\_L2,mask=NULL)-> double}
3151 \cvarg{arr1}{The first source image}
3152 \cvarg{arr2}{The second source image. If it is NULL, the absolute norm of \texttt{arr1} is calculated, otherwise the absolute or relative norm of \texttt{arr1}-\texttt{arr2} is calculated.}
3153 \cvarg{normType}{Type of norm, see the discussion}
3154 \cvarg{mask}{The optional operation mask}
3157 The function \texttt{cvNorm} calculates the absolute norm of \texttt{arr1} if \texttt{arr2} is NULL:
3160 {||\texttt{arr1}||_C = \max_I |\texttt{arr1}(I)|}{if $\texttt{normType} = \texttt{CV\_C}$}
3161 {||\texttt{arr1}||_{L1} = \sum_I |\texttt{arr1}(I)|}{if $\texttt{normType} = \texttt{CV\_L1}$}
3162 {||\texttt{arr1}||_{L2} = \sqrt{\sum_I \texttt{arr1}(I)^2}}{if $\texttt{normType} = \texttt{CV\_L2}$}
3165 And the function calculates absolute or relative difference norm if \texttt{arr2} is not NULL:
3168 {||\texttt{arr1}-\texttt{arr2}||_C = \max_I |\texttt{arr1}(I) - \texttt{arr2}(I)|}{if $\texttt{normType} = \texttt{CV\_C}$}
3169 {||\texttt{arr1}-\texttt{arr2}||_{L1} = \sum_I |\texttt{arr1}(I) - \texttt{arr2}(I)|}{if $\texttt{normType} = \texttt{CV\_L1}$}
3170 {||\texttt{arr1}-\texttt{arr2}||_{L2} = \sqrt{\sum_I (\texttt{arr1}(I) - \texttt{arr2}(I))^2}}{if $\texttt{normType} = \texttt{CV\_L2}$}
3177 {\frac{||\texttt{arr1}-\texttt{arr2}||_C }{||\texttt{arr2}||_C }}{if $\texttt{normType} = \texttt{CV\_RELATIVE\_C}$}
3178 {\frac{||\texttt{arr1}-\texttt{arr2}||_{L1} }{||\texttt{arr2}||_{L1}}}{if $\texttt{normType} = \texttt{CV\_RELATIVE\_L1}$}
3179 {\frac{||\texttt{arr1}-\texttt{arr2}||_{L2} }{||\texttt{arr2}||_{L2}}}{if $\texttt{normType} = \texttt{CV\_RELATIVE\_L2}$}
3182 The function \texttt{Norm} returns the calculated norm. A multiple-channel array is treated as a single-channel, that is, the results for all channels are combined.
3186 Reduces a matrix to a vector.
3190 void cvReduce( const CvArr* src, CvArr* dst, int op=CV\_REDUCE\_SUM );
3192 }{CPP}{Reduce(src,dst,op=CV\_REDUCE\_SUM)-> None}
3195 \cvarg{src}{The input matrix.}
3196 \cvarg{dst}{The output single-row/single-column vector that accumulates somehow all the matrix rows/columns.}
3197 \cvarg{dim}{The dimension index along which the matrix is reduced. 0 means that the matrix is reduced to a single row, 1 means that the matrix is reduced to a single column and -1 means that the dimension is chosen automatically by analysing the dst size.}
3198 \cvarg{op}{The reduction operation. It can take of the following values:
3200 \cvarg{CV\_REDUCE\_SUM}{The output is the sum of all of the matrix's rows/columns.}
3201 \cvarg{CV\_REDUCE\_AVG}{The output is the mean vector of all of the matrix's rows/columns.}
3202 \cvarg{CV\_REDUCE\_MAX}{The output is the maximum (column/row-wise) of all of the matrix's rows/columns.}
3203 \cvarg{CV\_REDUCE\_MIN}{The output is the minimum (column/row-wise) of all of the matrix's rows/columns.}
3207 The function \texttt{cvReduce} reduces matrix to a vector by treating the matrix rows/columns as a set of 1D vectors and performing the specified operation on the vectors until a single row/column is obtained. For example, the function can be used to compute horizontal and vertical projections of an raster image. In the case of \texttt{CV\_REDUCE\_SUM} and \texttt{CV\_REDUCE\_AVG} the output may have a larger element bit-depth to preserve accuracy. And multi-channel arrays are also supported in these two reduction modes.
3210 \subsection{Linear Algebra}
3212 \cvfunc{SetIdentity}\label{SetIdentity}
3214 Initializes a scaled identity matrix.
3218 void cvSetIdentity( CvArr* mat, CvScalar value=cvRealScalar(1) );
3220 }{CPP}{SetIdentity(mat,value=cvRealScalar(1))-> None}
3223 \cvarg{arr}{The matrix to initialize (not necesserily square)}
3224 \cvarg{value}{The value to assign to the diagonal elements}
3227 The function \texttt{cvSetIdentity} initializes a scaled identity matrix:
3230 \texttt{arr}(i,j)=\fork{\texttt{value}}{ if $i=j$}{0}{otherwise}
3233 \cvfunc{DotProduct}\label{DotProduct}
3235 Calculates the dot product of two arrays in Euclidian metrics.
3239 double cvDotProduct( const CvArr* src1, const CvArr* src2 );
3241 }{CPP}{DotProduct(src1,src2)-> double}
3244 \cvarg{src1}{The first source array}
3245 \cvarg{src2}{The second source array}
3248 The function \texttt{cvDotProduct} calculates and returns the Euclidean dot product of two arrays.
3251 src1 \bullet src2 = \sum_I (\texttt{src1}(I) \texttt{src2}(I))
3254 In the 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$.
3255 The function can process multi-dimensional arrays, row by row, layer by layer, and so on.
3257 \cvfunc{CrossProduct}\label{CrossProduct}
3259 Calculates the cross product of two 3D vectors.
3263 void cvCrossProduct( const CvArr* src1, const CvArr* src2, CvArr* dst );
3265 }{CPP}{CrossProduct(src1,src2,dst)-> None}
3268 \cvarg{src1}{The first source vector}
3269 \cvarg{src2}{The second source vector}
3270 \cvarg{dst}{The destination vector}
3274 The function \texttt{cvCrossProduct} calculates the cross product of two 3D vectors:
3276 \[ \texttt{dst} = \texttt{src1} \times \texttt{src2} \]
3280 \texttt{dst}_1 = \texttt{src1}_2 \texttt{src2}_3 - \texttt{src1}_3 \texttt{src2}_2\\
3281 \texttt{dst}_2 = \texttt{src1}_3 \texttt{src2}_1 - \texttt{src1}_1 \texttt{src2}_3\\
3282 \texttt{dst}_3 = \texttt{src1}_1 \texttt{src2}_2 - \texttt{src1}_2 \texttt{src2}_1
3286 \cvfunc{ScaleAdd}\label{ScaleAdd}
3288 Calculates the sum of a scaled array and another array.
3292 void cvScaleAdd( const CvArr* src1, CvScalar scale, const CvArr* src2, CvArr* dst );
3294 }{CPP}{ScaleAdd(src1,sclae,src2,dst)-> None}
3296 #define cvMulAddS cvScaleAdd
3300 \cvarg{src1}{The first source array}
3301 \cvarg{scale}{Scale factor for the first array}
3302 \cvarg{src2}{The second source array}
3303 \cvarg{dst}{The destination array}
3306 The function \texttt{cvScaleAdd} calculates the sum of a scaled array and another array:
3309 \texttt{dst}(I)=\texttt{scale} \, \texttt{src1}(I) + \texttt{src2}(I)
3312 All array parameters should have the same type and the same size.
3314 \cvfunc{GEMM}\label{GEMM}
3316 Performs generalized matrix multiplication.
3320 void cvGEMM( const CvArr* src1, const CvArr* src2, double alpha,
3321 const CvArr* src3, double beta, CvArr* dst, int tABC=0 );
3323 }{CPP}{GEMM(src1,src2,alphs,src3,beta,dst,tABC=0)-> None}
3325 #define cvMatMulAdd( src1, src2, src3, dst ) cvGEMM( src1, src2, 1, src3, 1, dst, 0 )
3326 #define cvMatMul( src1, src2, dst ) cvMatMulAdd( src1, src2, 0, dst )
3330 \cvarg{src1}{The first source array}
3331 \cvarg{src2}{The second source array}
3332 \cvarg{src3}{The third source array (shift). Can be NULL, if there is no shift.}
3333 \cvarg{dst}{The destination array}
3334 \cvarg{tABC}{The operation flags that can be 0 or a combination of the following values
3336 \cvarg{CV\_GEMM\_A\_T}{transpose src1}
3337 \cvarg{CV\_GEMM\_B\_T}{transpose src2}
3338 \cvarg{CV\_GEMM\_C\_T}{transpose src3}
3340 For example, \texttt{CV\_GEMM\_A\_T+CV\_GEMM\_C\_T} corresponds to
3342 \texttt{alpha} \, \texttt{src1} ^T \, \texttt{src2} + \texttt{beta} \, \texttt{src3} ^T
3346 The function \texttt{cvGEMM} performs generalized matrix multiplication:
3349 \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$}
3352 All the matrices should have the same data type and coordinated sizes. Real or complex floating-point matrices are supported.
3354 \cvfunc{Transform}\label{Transform}
3356 Performs matrix transformation of every array element.
3360 void cvTransform( const CvArr* src, CvArr* dst, const CvMat* transmat, const CvMat* shiftvec=NULL );
3362 }{CPP}{Transform(src,dst,transmat,shiftvec=NULL)-> None}
3365 \cvarg{src}{The first source array}
3366 \cvarg{dst}{The destination array}
3367 \cvarg{transmat}{Transformation matrix}
3368 \cvarg{shiftvec}{Optional shift vector}
3371 The function \texttt{cvTransform} performs matrix transformation of every element of array \texttt{src} and stores the results in \texttt{dst}:
3374 dst(I) = transmat \cdot src(I) + shiftvec % or dst(I),,k,,=sum,,j,,(transmat(k,j)*src(I),,j,,) + shiftvec(k)
3377 That is, every element of an \texttt{N}-channel array \texttt{src} is
3378 considered as an \texttt{N}-element vector which is transformed using
3379 a $\texttt{M} \times \texttt{N}$ matrix \texttt{transmat} and shift
3380 vector \texttt{shiftvec} into an element of \texttt{M}-channel array
3381 \texttt{dst}. There is an option to embedd \texttt{shiftvec} into
3382 \texttt{transmat}. In this case \texttt{transmat} should be a $\texttt{M}
3383 \times (N+1)$ matrix and the rightmost column is treated as the shift
3386 Both source and destination arrays should have the same depth and the
3387 same size or selected ROI size. \texttt{transmat} and \texttt{shiftvec}
3388 should be real floating-point matrices.
3390 The function may be used for geometrical transformation of n dimensional
3391 point set, arbitrary linear color space transformation, shuffling the
3392 channels and so forth.
3394 \cvfunc{PerspectiveTransform}\label{PerspectiveTransform}
3396 Performs perspective matrix transformation of a vector array.
3400 void cvPerspectiveTransform( const CvArr* src, CvArr* dst, const CvMat* mat );
3402 }{CPP}{PerspectiveTransform(src,dst,mat)-> None}
3405 \cvarg{src}{The source three-channel floating-point array}
3406 \cvarg{dst}{The destination three-channel floating-point array}
3407 \cvarg{mat}{$3\times 3$ or $4 \times 4$ transformation matrix}
3411 The function \texttt{PerspectiveTransform} transforms every element of \texttt{src} (by treating it as 2D or 3D vector) in the following way:
3413 \[ (x, y, z) \rightarrow (x'/w, y'/w, z'/w) \]
3418 (x', y', z', w') = \texttt{mat} \cdot
3419 \begin{bmatrix} x & y & z & 1 \end{bmatrix}
3423 \[ w = \fork{w'}{if $w' \ne 0$}{\infty}{otherwise} \]
3425 \cvfunc{MulTransposed}\label{MulTransposed}
3427 Calculates the product of an array and a transposed array.
3431 void cvMulTransposed( const CvArr* src, CvArr* dst, int order, const CvArr* delta=NULL, double scale=1.0 );
3433 }{CPP}{MulTransposed(src,dst,order,delta=NULL)-> None}
3436 \cvarg{src}{The source matrix}
3437 \cvarg{dst}{The destination matrix. Must be \texttt{CV\_32F} or \texttt{CV\_64F}.}
3438 \cvarg{order}{Order of multipliers}
3439 \cvarg{delta}{An optional array, subtracted from \texttt{src} before multiplication}
3440 \cvarg{scale}{An optional scaling}
3443 The function \texttt{MulTransposed} calculates the product of src and its transposition.
3445 The function evaluates
3448 \texttt{dst}=\texttt{scale} (\texttt{src}-\texttt{delta}) (\texttt{src}-\texttt{delta})^T
3451 if $\texttt{order}=0$, and
3454 \texttt{dst}=\texttt{scale} (\texttt{src}-\texttt{delta})^T (\texttt{src}-\texttt{delta})
3459 \cvfunc{Trace}\label{Trace}
3461 Returns the trace of a matrix.
3465 CvScalar cvTrace( const CvArr* mat );
3467 }{CPP}{Trace(mat)-> CvScalar}
3470 \cvarg{mat}{The source matrix}
3474 The function \texttt{cvTrace} returns the sum of the diagonal elements of the matrix \texttt{src1}.
3476 \[ tr(\texttt{mat}) = \sum_i \texttt{mat}(i,i) \]
3478 \cvfunc{Transpose}\label{Transpose}
3480 Transposes a matrix.
3484 void cvTranspose( const CvArr* src, CvArr* dst );
3486 }{CPP}{Transpose(src,dst)-> None}
3489 #define cvT cvTranspose
3493 \cvarg{src}{The source matrix}
3494 \cvarg{dst}{The destination matrix}
3497 The function \texttt{cvTranspose} transposes matrix \texttt{src1}:
3499 \[ \texttt{dst}(i,j) = \texttt{src}(j,i) \]
3501 Note that no complex conjugation is done in the case of a complex
3502 matrix. Conjugation should be done separately: look at the sample code
3503 in \cross{XorS} for an example.
3505 \cvfunc{Det}\label{Det}
3507 Returns the determinant of a matrix.
3511 double cvDet( const CvArr* mat );
3513 }{CPP}{Det(mat)-> double}
3516 \cvarg{mat}{The source matrix}
3519 The function \texttt{cvDet} returns the 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
3521 with $U = V = 0$ and then calculate the determinant as a product of the diagonal elements of $W$.
3523 \cvfunc{Invert}\label{Invert}
3525 Finds the inverse or pseudo-inverse of a matrix.
3529 double cvInvert( const CvArr* src, CvArr* dst, int method=CV\_LU );
3531 }{CPP}{Invert(src,dst,method=CV\_LU)-> double}
3533 #define cvInv cvInvert
3537 \cvarg{src}{The source matrix}
3538 \cvarg{dst}{The destination matrix}
3539 \cvarg{method}{Inversion method
3541 \cvarg{CV\_LU}{Gaussian elimination with optimal pivot element chosen}
3542 \cvarg{CV\_SVD}{Singular value decomposition (SVD) method}
3543 \cvarg{CV\_SVD\_SYM}{SVD method for a symmetric positively-defined matrix}
3547 The function \texttt{cvInvert} inverts matrix \texttt{src1} and stores the result in \texttt{src2}.
3549 In the case of \texttt{LU} method, the function returns the \texttt{src1} determinant (src1 must be square). If it is 0, the matrix is not inverted and \texttt{src2} is filled with zeros.
3551 In the case of \texttt{SVD} methods, the function returns the inversed condition 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.
3554 \cvfunc{Solve}\label{Solve}
3556 Solves a linear system or least-squares problem.
3560 int cvSolve( const CvArr* src1, const CvArr* src2, CvArr* dst, int method=CV\_LU );
3562 }{CPP}{Solve(A,B,X,method=CV\_LU)-> None}
3565 \cvarg{A}{The source matrix}
3566 \cvarg{B}{The right-hand part of the linear system}
3567 \cvarg{X}{The output solution}
3568 \cvarg{method}{The solution (matrix inversion) method
3570 \cvarg{CV\_LU}{Gaussian elimination with optimal pivot element chosen}
3571 \cvarg{CV\_SVD}{Singular value decomposition (SVD) method}
3572 \cvarg{CV\_SVD\_SYM}{SVD method for a symmetric positively-defined matrix.}
3576 The function \texttt{cvSolve} solves a linear system or least-squares problem (the latter is possible with SVD methods):
3579 \texttt{dst} = argmin_X||\texttt{src1} \, \texttt{X} - \texttt{src2}||
3582 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.
3584 \cvfunc{SVD}\label{SVD}
3586 Performs singular value decomposition of a real floating-point matrix.
3590 void cvSVD( \par CvArr* A, \par CvArr* W, \par CvArr* U=NULL, \par CvArr* V=NULL, \par int flags=0 );
3592 }{CPP}{SVD(A,flags=0)-> W,U,V}
3595 \cvarg{A}{Source $\texttt{M} \times \texttt{N}$ matrix}
3596 \cvarg{W}{Resulting singular value matrix ($\texttt{M} \times \texttt{N}$ or $\texttt{N} \times \texttt{N}$) or vector ($\texttt{N} \times 1$)}
3597 \cvarg{U}{Optional left orthogonal matrix ($\texttt{M} \times \texttt{M}$ or $\texttt{M} \times \texttt{N}$).
3598 If \texttt{CV\_SVD\_U\_T} is specified, the number of rows and columns in the preceeding sentence should be swapped.}
3599 \cvarg{V}{Optional right orthogonal matrix ($\texttt{N} \times \texttt{N}$)}
3600 \cvarg{flags}{Operation flags; can be 0 or a combination of the following values:
3602 \cvarg{CV\_SVD\_MODIFY\_A}{enables modification of matrix \texttt{src1} during the operation. It speeds up the processing.}
3603 \cvarg{CV\_SVD\_U\_T}{means that the tranposed matrix \texttt{U} is returned. Specifying the flag speeds up the processing.}
3604 \cvarg{CV\_SVD\_V\_T}{means that the tranposed matrix \texttt{V} is returned. Specifying the flag speeds up the processing.}
3608 The function \texttt{cvSVD} decomposes matrix \texttt{A} into the product of a diagonal matrix and two
3610 orthogonal matrices:
3616 where $W$ is a diagonal matrix of singular values that can be coded as a
3617 1D vector of singular values and $U$ and $V$. All the singular values
3618 are non-negative and sorted (together with $U$ and $V$ columns)
3619 in descending order.
3621 An SVD algorithm is numerically robust and its typical applications include:
3624 \item accurate eigenvalue problem solution when matrix \texttt{A}
3625 is a square, symmetric, and positively defined matrix, for example, when
3626 it is a covariance matrix. $W$ in this case will be a vector
3627 of eigen values, and $U = V$
3628 (thus, only one of $U$ or $V$ needs to be calculated if
3629 the eigen vectors are required).
3630 \item accurate solution of poor-conditioned linear systems.
3631 \item least-squares solution of overdetermined linear systems. This and the preceeding is done by using the \cross{Solve} function with the \texttt{CV\_SVD} method.
3632 \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), and determinant (absolute value of determinant is equal to the product of singular values).
3635 None of the applications above require calculation of the \texttt{U} and \texttt{V} matrices.
3637 \cvfunc{SVBkSb}\label{SVBkSb}
3639 Performs singular value back substitution.
3643 void cvSVBkSb( \par const CvArr* W,\par const CvArr* U,\par const CvArr* V,\par const CvArr* B,\par CvArr* X,\par int flags );
3645 }{CPP}{SVBkSb(W,U,V,B,X,flags)-> None}
3648 \cvarg{W}{Matrix or vector of singular values}
3649 \cvarg{U}{Left orthogonal matrix (tranposed, perhaps)}
3650 \cvarg{V}{Right orthogonal matrix (tranposed, perhaps)}
3651 \cvarg{B}{The matrix to multiply the pseudo-inverse of the original matrix \texttt{A} by. This is an optional parameter. If it is omitted then it is assumed to be an identity matrix of an appropriate size (so that \texttt{X} will be the reconstructed pseudo-inverse of \texttt{A}).}
3652 \cvarg{X}{The destination matrix: result of back substitution}
3653 \cvarg{flags}{Operation flags, should match exactly to the \texttt{flags} passed to \cross{SVD}}
3656 The function \texttt{cvSVBkSb} calculates back substitution for decomposed matrix \texttt{A} (see \cross{SVD} description) and matrix \texttt{B}:
3659 \texttt{X} = \texttt{V} \texttt{W}^{-1} \texttt{U}^T \texttt{B}
3667 {1/W_{(i,i)}}{if $W_{(i,i)} > \epsilon \sum_i{W_{(i,i)}}$ }
3671 and $\epsilon$ is a small number that depends on the matrix data type.
3673 This function together with \cross{SVD} is used inside \cross{Invert}
3674 and \cross{Solve}, and the possible reason to use these (svd and bksb)
3675 "low-level" function, is to avoid allocation of temporary matrices inside
3676 the high-level counterparts (inv and solve).
3678 \cvfunc{EigenVV}\label{EigenVV}
3680 Computes eigenvalues and eigenvectors of a symmetric matrix.
3684 void cvEigenVV( \par CvArr* mat,\par CvArr* evects,\par CvArr* evals,\par double eps=0,
3685 \par int lowindex = 0, \par int highindex = 0 );
3687 }{CPP}{EigenVV(mat,evects,evals,eps,lowindex,highindex)-> None}
3690 \cvarg{mat}{The input symmetric square matrix, modified during the processing}
3691 \cvarg{evects}{The output matrix of eigenvectors, stored as subsequent rows}
3692 \cvarg{evals}{The output vector of eigenvalues, stored in the descending order (order of eigenvalues and eigenvectors is syncronized, of course)}
3693 \cvarg{eps}{Accuracy of diagonalization. Typically, \texttt{DBL\_EPSILON} (about $ 10^{-15} $) works well.
3694 THIS PARAMETER IS CURRENTLY IGNORED.}
3695 \cvarg{lowindex}{Optional index of largest eigenvalue/-vector to calculate.
3697 \cvarg{highindex}{Optional index of smallest eigenvalue/-vector to calculate.
3702 The function \texttt{cvEigenVV} computes the eigenvalues and eigenvectors of matrix \texttt{A}:
3705 mat*evects(i,:)' = evals(i)*evects(i,:)' (in MATLAB notation)
3708 If either low- or highindex is supplied the other is required, too.
3709 Indexing is 1-based. Example: To calculate the largest eigenvector/-value set
3710 lowindex = highindex = 1.
3711 For legacy reasons this function always returns a square matrix the same size
3712 as the source matrix with eigenvectors and a vector the length of the source
3713 matrix with eigenvalues. The selected eigenvectors/-values are always in the
3714 first highindex - lowindex + 1 rows.
3716 The contents of matrix \texttt{A} is destroyed by the function.
3718 Currently the function is slower than \cross{SVD} yet less accurate,
3719 so if \texttt{A} is known to be positively-defined (for example, it
3720 is a covariance matrix)it is recommended to use \cross{SVD} to find
3721 eigenvalues and eigenvectors of \texttt{A}, especially if eigenvectors
3724 \cvfunc{CalcCovarMatrix}\label{CalcCovarMatrix}
3726 Calculates covariance matrix of a set of vectors.
3730 void cvCalcCovarMatrix( \par const CvArr** vects,\par int count,\par CvArr* cov\_mat,\par CvArr* avg,\par int flags );
3732 }{CPP}{CalcCovarMatrix(vects,cov\_mat,avg,flags)-> None}
3735 \cvarg{vects}{The input vectors, all of which must have the same type and the same size. The vectors do not have to be 1D, they can be 2D (e.g., images) and so forth}
3736 \cvarg{count}{The number of input vectors}
3737 \cvarg{cov\_mat}{The output covariance matrix that should be floating-point and square}
3738 \cvarg{avg}{The input or output (depending on the flags) array - the mean (average) vector of the input vectors}
3739 \cvarg{flags}{The operation flags, a combination of the following values
3741 \cvarg{CV\_COVAR\_SCRAMBLED}{The output covariance matrix is calculated as:
3743 \texttt{scale} * [ \texttt{vects} [0]- \texttt{avg} ,\texttt{vects} [1]- \texttt{avg} ,...]^T \cdot [\texttt{vects} [0]-\texttt{avg} ,\texttt{vects} [1]-\texttt{avg} ,...]
3745 that is, the covariance matrix is
3746 $\texttt{count} \times \texttt{count}$.
3747 Such an unusual covariance matrix is used for fast PCA
3748 of a set of very large vectors (see, for example, the EigenFaces technique
3749 for face recognition). Eigenvalues of this "scrambled" matrix will
3750 match the eigenvalues of the true covariance matrix and the "true"
3751 eigenvectors can be easily calculated from the eigenvectors of the
3752 "scrambled" covariance matrix.}
3753 \cvarg{CV\_COVAR\_NORMAL}{The output covariance matrix is calculated as:
3755 \texttt{scale} * [ \texttt{vects} [0]- \texttt{avg} ,\texttt{vects} [1]- \texttt{avg} ,...] \cdot [\texttt{vects} [0]-\texttt{avg} ,\texttt{vects} [1]-\texttt{avg} ,...]^T
3757 that is, \texttt{cov\_mat} will be a covariance matrix
3758 with the same linear size as the total number of elements in each
3759 input vector. One and only one of \texttt{CV\_COVAR\_SCRAMBLED} and
3760 \texttt{CV\_COVAR\_NORMAL} must be specified}
3761 \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 covariance 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.}
3762 \cvarg{CV\_COVAR\_SCALE}{If the flag is specified, the covariance matrix is scaled. In the "normal" mode \texttt{scale} is '1./count'; in the "scrambled" mode \texttt{scale} is the reciprocal of the total number of elements in each input vector. By default (if the flag is not specified) the covariance matrix is not scaled ('scale=1').}
3764 \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.}
3765 \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.}
3770 The function \texttt{cvCalcCovarMatrix} calculates the covariance matrix
3771 and, optionally, the mean vector of the set of input vectors. The function
3772 can be used for PCA, for comparing vectors using Mahalanobis distance and so forth.
3774 \cvfunc{Mahalonobis}\label{Mahalonobis}
3776 Calculates the Mahalonobis distance between two vectors.
3780 double cvMahalanobis( \par const CvArr* vec1,\par const CvArr* vec2,\par CvArr* mat );
3782 }{CPP}{Mahalonobis(vec1,vec2,mat)-> None}
3785 \cvarg{vec1}{The first 1D source vector}
3786 \cvarg{vec2}{The second 1D source vector}
3787 \cvarg{mat}{The inverse covariance matrix}
3791 The function \texttt{cvMahalonobis} calculates and returns the weighted distance between two vectors:
3795 d(vec1,vec2)=sqrt( sum,,i,j,, {mat(i,j)*(vec1(i)-vec2(i))*(vec1(j)-vec2(j))} )
3799 The covariance matrix may be calculated using the \cross{CalcCovarMatrix} function and further inverted using the \cross{Invert} function (CV\_SVD method is the prefered one because the matrix might be singular).
3802 \subsection{Math Functions}
3804 \cvfunc{Round, Floor, Ceil}\label{Round, Floor, Ceil}
3806 Converts a floating-point number to an integer.
3810 int cvRound( double value );
3811 int cvFloor( double value );
3812 int cvCeil( double value );
3814 }{CPP}{Round, Floor, Ceil(value)-> int}
3817 \cvarg{value}{The input floating-point value}
3821 The functions \texttt{cvRound}, \texttt{cvFloor} and \texttt{cvCeil}
3822 convert an input floating-point number to an integer using one of the rounding
3823 modes. \texttt{cvRound} returns the nearest integer value to the
3824 argument. \texttt{cvFloor} returns the maximum integer value that is not
3825 larger than the argument. \texttt{cvCeil} returns the minimum integer
3826 value that is not smaller than the argument. On some architectures the
3827 functions work much faster than the standard cast
3828 operations in C. If the absolute value of the argument is greater than
3829 $2^{31}$, the result is not determined. Special values ( $ \pm \infty$ , NaN)
3832 \cvfunc{Sqrt}\label{Sqrt}
3834 Calculates the square root.
3838 float cvSqrt( float value );
3840 }{CPP}{Sqrt(value)-> float}
3843 \cvarg{value}{The input floating-point value}
3847 The function \texttt{cvSqrt} calculates the square root of the argument. If the argument is negative, the result is not determined.
3849 \cvfunc{InvSqrt}\label{InvSqrt}
3851 Calculates the inverse square root.
3855 float cvInvSqrt( float value );
3857 }{CPP}{InvSqrt(value)-> float}
3860 \cvarg{value}{The input floating-point value}
3864 The function \texttt{cvInvSqrt} calculates the 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.
3866 \cvfunc{Cbrt}\label{Cbrt}
3868 Calculates the cubic root
3872 float cvCbrt( float value );
3874 }{CPP}{Cbrt(value)-> float}
3877 \cvarg{value}{The input floating-point value}
3881 The function \texttt{cvCbrt} calculates the cubic root of the argument, and normally it is faster than \texttt{pow(value,1./3)}. In addition, negative arguments are handled properly. Special values ( $ \pm \infty $, NaN) are not handled.
3883 \cvfunc{FastArctan}\label{FastArctan}
3885 Calculates the angle of a 2D vector.
3889 float cvFastArctan( float y, float x );
3891 }{CPP}{FastArctan(y,x)-> float}
3894 \cvarg{x}{x-coordinate of 2D vector}
3895 \cvarg{y}{y-coordinate of 2D vector}
3899 The function \texttt{cvFastArctan} calculates the full-range angle of an input 2D vector. The angle is
3901 measured in degrees and varies from 0 degrees to 360 degrees . The accuracy is about 0.1 degrees.
3903 \cvfunc{IsNaN}\label{IsNaN}
3905 Determines if the argument is Not A Number.
3909 int cvIsNaN( double value );
3911 }{CPP}{IsNaN(value)-> int}
3914 \cvarg{value}{The input floating-point value}
3918 The function \texttt{cvIsNaN} returns 1 if the argument is Not A Number (as defined by IEEE754 standard), 0 otherwise.
3921 \cvfunc{IsInf}\label{IsInf}
3923 Determines if the argument is Infinity.
3927 int cvIsInf( double value );
3929 }{CPP}{IsInf(value)-> int}
3932 \cvarg{value}{The input floating-point value}
3936 The function \texttt{cvIsInf} returns 1 if the argument is $ \pm \infty $ (as defined by IEEE754 standard), 0 otherwise.
3939 \cvfunc{CartToPolar}\label{CartToPolar}
3941 Calculates the magnitude and/or angle of 2d vectors.
3945 void cvCartToPolar( \par const CvArr* x,\par const CvArr* y,\par CvArr* magnitude,\par CvArr* angle=NULL,\par int angle\_in\_degrees=0 );
3947 }{CPP}{CartToPolar(x,y,magnitude,angle=NULL,angle\_in\_degrees)-> None}
3950 \cvarg{x}{The array of x-coordinates}
3951 \cvarg{y}{The array of y-coordinates}
3952 \cvarg{magnitude}{The destination array of magnitudes, may be set to NULL if it is not needed}
3953 \cvarg{angle}{The destination array of angles, may be set to NULL if it is not needed. The angles are measured in radians $(0$ to $2 \pi )$ or in degrees (0 to 360 degrees).}
3954 \cvarg{angle\_in\_degrees}{The flag indicating whether the angles are measured in radians, which is default mode, or in degrees}
3957 The function \texttt{cvCartToPolar} calculates either the magnitude, angle, or both of every 2d vector (x(I),y(I)):
3961 magnitude(I)=sqrt( x(I)^2^+y(I)^2^ ),
3962 angle(I)=atan( y(I)/x(I) )
3966 The angles are calculated with 0.1 degree accuracy. For the (0,0) point, the angle is set to 0.
3968 \cvfunc{PolarToCart}\label{PolarToCart}
3970 Calculates Cartesian coordinates of 2d vectors represented in polar form.
3974 void cvPolarToCart( \par const CvArr* magnitude,\par const CvArr* angle,\par CvArr* x,\par CvArr* y,\par int angle\_in\_degrees=0 );
3976 }{CPP}{PolarToCart(magnitude,angle=NULL,x,y,angle\_in\_degrees)-> None}
3979 \cvarg{magnitude}{The array of magnitudes. If it is NULL, the magnitudes are assumed to be all 1's.}
3980 \cvarg{angle}{The array of angles, whether in radians or degrees}
3981 \cvarg{x}{The destination array of x-coordinates, may be set to NULL if it is not needed}
3982 \cvarg{y}{The destination array of y-coordinates, mau be set to NULL if it is not needed}
3983 \cvarg{angle\_in\_degrees}{The flag indicating whether the angles are measured in radians, which is default mode, or in degrees}
3986 The function \texttt{cvPolarToCart} calculates either the x-coodinate, y-coordinate or both of every vector \texttt{magnitude(I)*exp(angle(I)*j), j=sqrt(-1)}:
3990 x(I)=magnitude(I)*cos(angle(I)),
3991 y(I)=magnitude(I)*sin(angle(I))
3996 \cvfunc{Pow}\label{Pow}
3998 Raises every array element to a power.
4002 void cvPow( \par const CvArr* src,\par CvArr* dst,\par double power );
4004 }{CPP}{Pow(src,dst,power)-> None}
4007 \cvarg{src}{The source array}
4008 \cvarg{dst}{The destination array, should be the same type as the source}
4009 \cvarg{power}{The exponent of power}
4013 The function \texttt{cvPow} raises every element of the input array to \texttt{p}:
4016 \texttt{dst} [I] = \fork
4017 {\texttt{src}(I)^p}{if \texttt{p} is integer}
4018 {|\texttt{src}(I)^p|}{otherwise}
4021 That is, for a 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 example, computing the cube root of array elements, shows:
4025 CvSize size = cvGetSize(src);
4026 CvMat* mask = cvCreateMat( size.height, size.width, CVg8UC1 );
4027 cvCmpS( src, 0, mask, CVgCMPgLT ); /* find negative elements */
4028 cvPow( src, dst, 1./3 );
4029 cvSubRS( dst, cvScalarAll(0), dst, mask ); /* negate the results of negative inputs */
4030 cvReleaseMat( &mask );
4034 For some values of \texttt{power}, such as integer values, 0.5, and -0.5, specialized faster algorithms are used.
4036 \cvfunc{Exp}\label{Exp}
4038 Calculates the exponent of every array element.
4042 void cvExp( const CvArr* src, CvArr* dst );
4044 }{CPP}{Exp(src,dst)-> None}
4047 \cvarg{src}{The source array}
4048 \cvarg{dst}{The destination array, it should have \texttt{double} type or the same type as the source}
4052 The function \texttt{cvExp} calculates the exponent of every element of the input array:
4055 \texttt{dst} [I] = e^{\texttt{src}(I)}
4058 The maximum relative error is about $7 \times 10^{-6}$. Currently, the function converts denormalized values to zeros on output.
4060 \cvfunc{Log}\label{Log}
4062 Calculates the natural logarithm of every array element's absolute value.
4066 void cvLog( const CvArr* src, CvArr* dst );
4068 }{CPP}{Log(src,dst)-> None}
4071 \cvarg{src}{The source array}
4072 \cvarg{dst}{The destination array, it should have \texttt{double} type or the same type as the source}
4075 The function \texttt{cvLog} calculates the natural logarithm of the absolute value of every element of the input array:
4078 \texttt{dst} [I] = \fork
4079 {\log{|\texttt{src}(I)}}{if $\texttt{src}[I] \ne 0$ }
4080 {\texttt{C}}{otherwise}
4083 Where \texttt{C} is a large negative number ( about -700 in the current implementation).
4085 \cvfunc{SolveCubic}\label{SolveCubic}
4087 Finds the real roots of a cubic equation.
4091 void cvSolveCubic( const CvArr* coeffs, CvArr* roots );
4093 }{CPP}{SolveCubic(coeffs,roots)-> None}
4096 \cvarg{coeffs}{The equation coefficients, an array of 3 or 4 elements}
4097 \cvarg{roots}{The output array of real roots which should have 3 elements}
4100 The function \texttt{cvSolveCubic} finds the real roots of a cubic equation:
4102 If coeffs is a 4-element vector:
4105 \texttt{coeffs}[0] x^3 + \texttt{coeffs}[1] x^2 + \texttt{coeffs}[2] x + \texttt{coeffs}[3] = 0
4108 or if coeffs is 3-element vector:
4111 x^3 + \texttt{coeffs}[0] x^2 + \texttt{coeffs}[1] x + \texttt{coeffs}[2] = 0
4114 The function returns the number of real roots found. The roots are
4115 stored to \texttt{root} array, which is padded with zeros if there is
4118 \subsection{Random Number Generation}
4120 \cvfunc{RNG}\label{RNG}
4122 Initializes a random number generator state.
4126 CvRNG cvRNG( int64 seed=-1 );
4128 }{CPP}{RNG(seed=-1LL)-> CvRNG}
4131 \cvarg{seed}{64-bit value used to initiate a random sequence}
4135 The function \texttt{cvRNG} initializes a random number generator
4136 and returns the state. The pointer to the state can be then passed to the
4137 \cross{RandInt}, \cross{RandReal} and \cross{RandArr} functions. In the
4138 current implementation a multiply-with-carry generator is used.
4140 \cvfunc{RandArr}\label{RandArr}
4142 Fills an array with random numbers and updates the RNG state.
4146 void cvRandArr( \par CvRNG* rng,\par CvArr* arr,\par int dist\_type,\par CvScalar param1,\par CvScalar param2 );
4148 }{CPP}{RandArr(rng,arr,dist\_type,param1,param2)-> None}
4151 \cvarg{rng}{RNG state initialized by \cross{RNG}}
4152 \cvarg{arr}{The destination array}
4153 \cvarg{dist\_type}{Distribution type
4155 \cvarg{CV\_RAND\_UNI}{uniform distribution}
4156 \cvarg{CV\_RAND\_NORMAL}{normal or Gaussian distribution}
4158 \cvarg{param1}{The first parameter of the distribution. In the case of a uniform distribution it is the inclusive lower boundary of the random numbers range. In the case of a normal distribution it is the mean value of the random numbers.}
4159 \cvarg{param2}{The second parameter of the distribution. In the case of a uniform distribution it is the exclusive upper boundary of the random numbers range. In the case of a normal distribution it is the standard deviation of the random numbers.}
4162 The function \texttt{cvRandArr} fills the destination array with uniformly
4163 or normally distributed random numbers. In the example below, the function
4164 is used to add a few normally distributed floating-point numbers to
4165 random locations within a 2d array.
4169 /* let noisy_screen be the floating-point 2d array that is to be "crapped" */
4170 CvRNG rng_state = cvRNG(0xffffffff);
4171 int i, pointCount = 1000;
4172 /* allocate the array of coordinates of points */
4173 CvMat* locations = cvCreateMat( pointCount, 1, CV_32SC2 );
4174 /* arr of random point values */
4175 CvMat* values = cvCreateMat( pointCount, 1, CV_32FC1 );
4176 CvSize size = cvGetSize( noisy_screen );
4178 cvRandInit( &rng_state,
4179 0, 1, /* use dummy parameters now and adjust them further */
4180 0xffffffff /* just use a fixed seed here */,
4181 CV_RAND_UNI /* specify uniform type */ );
4183 /* initialize the locations */
4184 cvRandArr( &rng_state, locations, CV_RAND_UNI, cvScalar(0,0,0,0),
4185 cvScalar(size.width,size.height,0,0) );
4187 /* modify RNG to make it produce normally distributed values */
4188 rng_state.disttype = CV_RAND_NORMAL;
4189 cvRandSetRange( &rng_state,
4191 100 /* average point brightness */,
4192 -1 /* initialize all the dimensions */ );
4193 /* generate values */
4194 cvRandArr( &rng_state, values, CV_RAND_NORMAL,
4195 cvRealScalar(100), // average intensity
4196 cvRealScalar(30) // deviation of the intensity
4199 /* set the points */
4200 for( i = 0; i < pointCount; i++ )
4202 CvPoint pt = *(CvPoint*)cvPtr1D( locations, i, 0 );
4203 float value = *(float*)cvPtr1D( values, i, 0 );
4204 *((float*)cvPtr2D( noisy_screen, pt.y, pt.x, 0 )) += value;
4207 /* not to forget to release the temporary arrays */
4208 cvReleaseMat( &locations );
4209 cvReleaseMat( &values );
4211 /* RNG state does not need to be deallocated */
4215 \cvfunc{RandInt}\label{RandInt}
4217 Returns a 32-bit unsigned integer and updates RNG.
4221 unsigned cvRandInt( CvRNG* rng );
4223 }{CPP}{RandInt(rng)-> unsigned}
4226 \cvarg{rng}{RNG state initialized by \texttt{RandInit} and, optionally, customized by \texttt{RandSetRange} (though, the latter function does not affect the discussed function outcome)}
4229 The function \texttt{cvRandInt} returns a uniformly-distributed random
4230 32-bit unsigned integer and updates the RNG state. It is similar to the rand()
4231 function from the C runtime library, but it always generates a 32-bit number
4232 whereas rand() returns a number in between 0 and \texttt{RAND\_MAX}
4233 which is $2^{16}$ or $2^{32}$, depending on the platform.
4235 The function is useful for generating scalar random numbers, such as
4236 points, patch sizes, table indices, etc., where integer numbers of a certain
4237 range can be generated using a modulo operation and floating-point numbers
4238 can be generated by scaling from 0 to 1 or any other specific range. Here
4239 is the example from the previous function discussion rewritten using
4244 /* the input and the task is the same as in the previous sample. */
4245 CvRNG rnggstate = cvRNG(0xffffffff);
4246 int i, pointCount = 1000;
4247 /* ... - no arrays are allocated here */
4248 CvSize size = cvGetSize( noisygscreen );
4249 /* make a buffer for normally distributed numbers to reduce call overhead */
4250 #define bufferSize 16
4251 float normalValueBuffer[bufferSize];
4252 CvMat normalValueMat = cvMat( bufferSize, 1, CVg32F, normalValueBuffer );
4255 for( i = 0; i < pointCount; i++ )
4258 /* generate random point */
4259 pt.x = cvRandInt( &rnggstate ) % size.width;
4260 pt.y = cvRandInt( &rnggstate ) % size.height;
4262 if( valuesLeft <= 0 )
4264 /* fulfill the buffer with normally distributed numbers
4265 if the buffer is empty */
4266 cvRandArr( &rnggstate, &normalValueMat, CV\_RAND\_NORMAL,
4267 cvRealScalar(100), cvRealScalar(30) );
4268 valuesLeft = bufferSize;
4270 *((float*)cvPtr2D( noisygscreen, pt.y, pt.x, 0 ) =
4271 normalValueBuffer[--valuesLeft];
4274 /* there is no need to deallocate normalValueMat because we have
4275 both the matrix header and the data on stack. It is a common and efficient
4276 practice of working with small, fixed-size matrices */
4280 \cvfunc{RandReal}\label{RandReal}
4282 Returns a floating-point random number and updates RNG.
4286 double cvRandReal( CvRNG* rng );
4288 }{CPP}{RandReal(rng)-> double}
4291 \cvarg{rng}{RNG state initialized by \cross{RNG}}
4295 The function \texttt{cvRandReal} returns a uniformly-distributed random floating-point number between 0 and 1 (1 is not included).
4297 \subsection{Discrete Transforms}
4299 \cvfunc{DFT}\label{DFT}
4301 Performs a forward or inverse Discrete Fourier transform of a 1D or 2D floating-point array.
4305 void cvDFT( const CvArr* src, CvArr* dst, int flags, int nonzero\_rows=0 );
4307 }{CPP}{DFT(src,dst,flags,nonzero\_rows=0)-> None}
4311 #define CV\_DXT\_FORWARD 0
4312 #define CV\_DXT\_INVERSE 1
4313 #define CV\_DXT\_SCALE 2
4314 #define CV\_DXT\_ROWS 4
4315 #define CV\_DXT\_INV\_SCALE (CV\_DXT\_SCALE|CV\_DXT\_INVERSE)
4316 #define CV\_DXT\_INVERSE\_SCALE CV\_DXT\_INV\_SCALE
4321 \cvarg{src}{Source array, real or complex}
4322 \cvarg{dst}{Destination array of the same size and same type as the source}
4323 \cvarg{flags}{Transformation flags, a combination of the following values
4325 \cvarg{CV\_DXT\_FORWARD} - do a forward 1D or 2D transform. The result is not scaled.
4326 \cvarg{CV\_DXT\_INVERSE} - do an inverse 1D or 2D transform. The result is not scaled. \texttt{CV\_DXT\_FORWARD} and \texttt{CV\_DXT\_INVERSE} are mutually exclusive, of course.
4327 \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}.
4328 \cvarg{CV\_DXT\_ROWS} - do a forward or inverse transform of every individual row of the input matrix. This flag allows the 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 and so forth.
4330 \cvarg{nonzero\_rows}{Number of nonzero rows in the source array
4331 (in the case of a forward 2d transform), or a number of rows of interest in
4332 the destination array (in the case of an inverse 2d transform). If the value
4333 is negative, zero, or greater than the total number of rows, it is
4334 ignored. The parameter can be used to speed up 2d convolution/correlation
4335 when computing via DFT. See the example below.}
4338 The function \texttt{cvDFT} performs a forward or inverse transform of a 1D or 2D floating-point array:
4342 Forward Fourier transform of 1D vector of N elements:
4343 \[y = F^{(N)} \cdot x, where F^{(N)}_{jk}=exp(-i \cdot 2\pi \cdot j \cdot k/N)\],
4346 Inverse Fourier transform of 1D vector of N elements:
4347 \[x'= (F^{(N)})^{-1} \cdot y = conj(F^(N)) \cdot y
4350 Forward Fourier transform of 2D vector of M $\times$ N elements:
4351 \[Y = F^{(M)} \cdot X \cdot F^{(N)}\]
4353 Inverse Fourier transform of 2D vector of M $\times$ N elements:
4354 \[X'= conj(F^{(M)}) \cdot Y \cdot conj(F^{(N)})
4355 X = (1/(M \cdot N)) \cdot X'\]
4358 In the case of real (single-channel) data, the packed format, borrowed from IPL, is used to represent the result of a forward Fourier transform or input for an inverse Fourier transform:
4361 \[Re Y_{0,0} \quad Re Y_{0,1} \quad Im Y_{0,1} \quad Re Y_{0,2} \quad Im Y_{0,2} \quad ... \quad Re Y_{0,N/2-1} \quad Im Y_{0,N/2-1} \quad Re Y_{0,N/2}\]
4363 \[Re Y_{1,0} \quad Re Y_{1,1} \quad Im Y_{1,1} \quad Re Y_{1,2} \quad Im Y_{1,2} \quad ... \quad Re Y_{1,N/2-1} \quad Im Y_{1,N/2-1} \quad Re Y_{1,N/2}\]
4365 \[Im Y_{1,0} \quad Re Y_{2,1} \quad Im Y_{2,1} \quad Re Y_{2,2} \quad Im Y_{2,2} \quad ... \quad Re Y_{2,N/2-1} \quad Im Y_{2,N/2-1} \quad Im Y_{2,N/2}\]
4366 \[............................................................................................................................................................\]
4367 \[Re Y_{M/2-1,0} \quad Re Y_{M-3,1} \quad Im Y_{M-3,1} \quad Re Y_{M-3,2} \quad Im Y_{M-3,2} \quad... \quad Re Y_{M-3,N/2-1} \quad Im Y_{M-3,N/2-1}\quad Re Y_{M-3,N/2}\]
4368 \[Im Y_{M/2-1,0} \quad Re Y_{M-2,1} \quad Im Y_{M-2,1} \quad Re Y_{M-2,2} \quad Im Y_{M-2,2} \quad... \quad Re Y_{M-2,N/2-1} \quad Im Y_{M-2,N/2-1}\quad Im Y_{M-2,N/2}\]
4369 \[Re Y_{M/2,0} \quad Re Y_{M-1,1} \quad Im Y_{M-1,1} \quad Re Y_{M-1,2} \quad Im Y_{M-1,2} \quad ... \quad Re Y_{M-1,N/2-1} \quad Im Y_{M-1,N/2-1}\quad Im Y_{M-1,N/2}\]
4372 Note: the last column is present if \texttt{N} is even, the last row is present if \texttt{M} is even.
4374 In the case of 1D real transform the result looks like the first row of the above matrix
4376 Computing 2D Convolution using DFT
4380 CvMat* A = cvCreateMat( M1, N1, CVg32F );
4381 CvMat* B = cvCreateMat( M2, N2, A->type );
4383 // it is also possible to have only abs(M2-M1)+1 \times abs(N2-N1)+1
4384 // part of the full convolution result
4385 CvMat* conv = cvCreateMat( A->rows + B->rows - 1, A->cols + B->cols - 1,
4388 // initialize A and B
4391 int dftgM = cvGetOptimalDFTSize( A->rows + B->rows - 1 );
4392 int dftgN = cvGetOptimalDFTSize( A->cols + B->cols - 1 );
4394 CvMat* dftgA = cvCreateMat( dft\_M, dft\_N, A->type );
4395 CvMat* dftgB = cvCreateMat( dft\_M, dft\_N, B->type );
4398 // copy A to dftgA and pad dft\_A with zeros
4399 cvGetSubRect( dftgA, &tmp, cvRect(0,0,A->cols,A->rows));
4401 cvGetSubRect( dftgA, &tmp, cvRect(A->cols,0,dft\_A->cols - A->cols,A->rows));
4403 // no need to pad bottom part of dftgA with zeros because of
4404 // use nonzerogrows parameter in cvDFT() call below
4406 cvDFT( dftgA, dft\_A, CV\_DXT\_FORWARD, A->rows );
4408 // repeat the same with the second array
4409 cvGetSubRect( dftgB, &tmp, cvRect(0,0,B->cols,B->rows));
4411 cvGetSubRect( dftgB, &tmp, cvRect(B->cols,0,dft\_B->cols - B->cols,B->rows));
4413 // no need to pad bottom part of dftgB with zeros because of
4414 // use nonzerogrows parameter in cvDFT() call below
4416 cvDFT( dftgB, dft\_B, CV\_DXT\_FORWARD, B->rows );
4418 cvMulSpectrums( dftgA, dft\_B, dft\_A, 0 /* or CV\_DXT\_MUL\_CONJ to get
4419 correlation rather than convolution */ );
4421 cvDFT( dftgA, dft\_A, CV\_DXT\_INV\_SCALE, conv->rows ); // calculate only
4423 cvGetSubRect( dftgA, &tmp, cvRect(0,0,conv->cols,conv->rows) );
4425 cvCopy( &tmp, conv );
4429 \cvfunc{GetOptimalDFTSize}\label{GetOptimalDFTSize}
4431 Returns optimal DFT size for a given vector size.
4435 int cvGetOptimalDFTSize( int size0 );
4437 }{CPP}{GetOptimalDFTSize(size0)-> int}
4440 \cvarg{size0}{Vector size}
4444 The function \texttt{cvGetOptimalDFTSize} returns the minimum number
4445 \texttt{N} that is greater than or equal to \texttt{size0}, such that the DFT
4446 of a vector of size \texttt{N} can be computed fast. In the current
4447 implementation $N=2^p \times 3^q \times 5^r$, for some $p$, $q$, $r$.
4449 The function returns a negative number if \texttt{size0} is too large
4450 (very close to \texttt{INT\_MAX})
4453 \cvfunc{MulSpectrums}\label{MulSpectrums}
4455 Performs per-element multiplication of two Fourier spectrums.
4459 void cvMulSpectrums( \par const CvArr* src1,\par const CvArr* src2,\par CvArr* dst,\par int flags );
4461 }{CPP}{MulSpectrums(src1,src2,dst,flags)-> None)}
4464 \cvarg{src1}{The first source array}
4465 \cvarg{src2}{The second source array}
4466 \cvarg{dst}{The destination array of the same type and the same size as the source arrays}
4467 \cvarg{flags}{A combination of the following values;
4469 \cvarg{CV\_DXT\_ROWS}{treats each row of the arrays as a separate spectrum (see \cross{DFT} parameters description).}
4470 \cvarg{CV\_DXT\_MUL\_CONJ}{conjugate the second source array before the multiplication.}
4475 The function \texttt{cvMulSpectrums} performs per-element multiplication of the two CCS-packed or complex matrices that are results of a real or complex Fourier transform.
4477 The function, together with \cross{DFT}, may be used to calculate convolution of two arrays rapidly.
4480 \cvfunc{DCT}\label{DCT}
4482 Performs a forward or inverse Discrete Cosine transform of a 1D or 2D floating-point array.
4486 void cvDCT( const CvArr* src, CvArr* dst, int flags );
4488 }{CPP}{DCT(src,dst,flags)-> None}
4492 #define CV\_DXT\_FORWARD 0
4493 #define CV\_DXT\_INVERSE 1
4494 #define CV\_DXT\_ROWS 4
4499 \cvarg{src}{Source array, real 1D or 2D array}
4500 \cvarg{dst}{Destination array of the same size and same type as the source}
4501 \cvarg{flags}{Transformation flags, a combination of the following values
4503 \cvarg{CV\_DXT\_FORWARD}{do a forward 1D or 2D transform.}
4504 \cvarg{CV\_DXT\_INVERSE}{do an inverse 1D or 2D transform.}
4505 \cvarg{CV\_DXT\_ROWS}{do a 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 and so forth.}
4509 The function \texttt{cvDCT} performs a forward or inverse transform of a 1D or 2D floating-point array:
4513 Forward Cosine transform of 1D vector of N elements:
4514 y = C^(N)^ \cdot x, where C^(N)^,,jk,,=sqrt((j==0?1:2)/N) \cdot cos(Pi \cdot (2k+1) \cdot j/N)
4516 Inverse Cosine transform of 1D vector of N elements:
4517 x = (C^(N)^)^-1^ \cdot y = (C^(N)^)^T^ \cdot y
4519 Forward Cosine transform of 2D vector of M \times N elements:
4520 Y = (C^(M)^) \cdot X \cdot (C^(N)^)^T^
4522 Inverse Cosine transform of 2D vector of M \times N elements:
4523 X = (C^(M)^)^T^ \cdot Y \cdot C^(N)^
4528 \section{Dynamic Structures}
4530 \subsection{Memory Storages}
4533 \cvfunc{CreateMemStorage}\label{CreateMemStorage}
4535 Creates memory storage.
4537 \cvexp{C}{CPP}{CreateMemStorage(block\_size) -> memstorage}
4540 \cvarg{block\_size}{Size of the storage blocks in bytes. If it is 0, the block size is set to a default value - currently it is about 64K.}
4543 The function \texttt{cvCreateMemStorage} creates an empty memory storage object.
4548 \cvstruct{CvMemStorage}\label{CvMemStorage}
4550 Growing memory storage.
4554 typedef struct CvMemStorage
4556 struct CvMemBlock* bottom;/* first allocated block */
4557 struct CvMemBlock* top; /* the current memory block - top of the stack */
4558 struct CvMemStorage* parent; /* borrows new blocks from */
4559 int block\_size; /* block size */
4560 int free\_space; /* free space in the \texttt{top} block (in bytes) */
4565 Memory storage is a low-level structure used to store dynamicly growing
4566 data structures such as sequences, contours, graphs, subdivisions, etc. It
4567 is organized as a list of memory blocks of equal size - \texttt{bottom}
4568 field is the beginning of the list of blocks and \texttt{top} is the
4569 currently used block, but not necessarily the last block of the list. All
4570 blocks between \texttt{bottom} and \texttt{top}, not including the
4571 latter, are considered fully occupied; all blocks between \texttt{top}
4572 and the last block, not including \texttt{top}, are considered free
4573 and \texttt{top} itself is partly ocupied - \texttt{free\_space}
4574 contains the number of free bytes left in the end of \texttt{top}.
4576 A new memory buffer that may be allocated explicitly by
4577 \cross{MemStorageAlloc} function or implicitly by higher-level functions,
4578 such as \cross{SeqPush}, \cross{GraphAddEdge}, etc., \texttt{always}
4579 starts in the end of the current block if it fits there. After allocation,
4580 \texttt{free\_space} is decremented by the size of the allocated buffer
4581 plus some padding to keep the proper alignment. When the allocated buffer
4582 does not fit into the available portion of \texttt{top}, the next storage
4583 block from the list is taken as \texttt{top} and \texttt{free\_space}
4584 is reset to the whole block size prior to the allocation.
4586 If there are no more free blocks, a new block is allocated (or borrowed
4587 from the parent, see \cross{CreateChildMemStorage}) and added to the end of
4588 list. Thus, the storage behaves as a stack with \texttt{bottom} indicating
4589 bottom of the stack and the pair (\texttt{top}, \texttt{free\_space})
4590 indicating top of the stack. The stack top may be saved via
4591 \cross{SaveMemStoragePos}, restored via \cross{RestoreMemStoragePos},
4592 or reset via \cross{ClearStorage}.
4594 \cvstruct{CvMemBlock}\label{CvMemBlock}
4596 Memory storage block.
4600 typedef struct CvMemBlock
4602 struct CvMemBlock* prev;
4603 struct CvMemBlock* next;
4608 The structure \cross{CvMemBlock} represents a single block of memory
4609 storage. The actual data in the memory blocks follows the header, that is,
4610 the $i_{th}$ byte of the memory block can be retrieved with the expression
4611 \texttt{((char*)(mem\_block\_ptr+1))[i]}. However, there is normally no need
4612 to access the storage structure fields directly.
4614 \cvstruct{CvMemStoragePos}\label{CvMemStoragePos}
4616 Memory storage position.
4620 typedef struct CvMemStoragePos
4628 The structure described above stores the position of the stack top that can be saved via \cross{SaveMemStoragePos} and restored via \cross{RestoreMemStoragePos}.
4630 \cvfunc{CreateMemStorage}\label{CreateMemStorage}
4632 Creates memory storage.
4636 CvMemStorage* cvCreateMemStorage( int block\_size=0 );
4641 \cvarg{block\_size}{Size of the storage blocks in bytes. If it is 0, the block size is set to a default value - currently it is about 64K.}
4644 The function \texttt{cvCreateMemStorage} creates a memory storage and returns a pointer to it. Initially the storage is empty. All fields of the header, except the \texttt{block\_size}, are set to 0.
4647 \cvfunc{CreateChildMemStorage}\label{CreateChildMemStorage}
4649 Creates child memory storage.
4653 CvMemStorage* cvCreateChildMemStorage( CvMemStorage* parent );
4658 \cvarg{parent}{Parent memory storage}
4662 The function \texttt{cvCreateChildMemStorage} creates a child memory
4663 storage that is similar to simple memory storage except for the
4664 differences in the memory allocation/deallocation mechanism. When a
4665 child storage needs a new block to add to the block list, it tries
4666 to get this block from the parent. The first unoccupied parent block
4667 available is taken and excluded from the parent block list. If no blocks
4668 are available, the parent either allocates a block or borrows one from
4669 its own parent, if any. In other words, the chain, or a more complex
4670 structure, of memory storages where every storage is a child/parent of
4671 another is possible. When a child storage is released or even cleared,
4672 it returns all blocks to the parent. In other aspects, child storage
4673 is the same as simple storage.
4675 Child storage is useful in the following situation. Imagine
4676 that the user needs to process dynamic data residing in a given storage area and
4677 put the result back to that same storage area. With the simplest approach,
4678 when temporary data is resided in the same storage area as the input and
4679 output data, the storage area will look as follows after processing:
4681 Dynamic data processing without using child storage
4683 \includegraphics[width=0.5\textwidth]{pics/memstorage1.png}
4685 That is, garbage appears in the middle of the storage. However, if
4686 one creates a child memory storage at the beginning of processing,
4687 writes temporary data there, and releases the child storage at the end,
4688 no garbage will appear in the source/destination storage:
4690 Dynamic data processing using a child storage
4692 \includegraphics[width=0.5\textwidth]{pics/memstorage2.png}
4694 \cvfunc{ReleaseMemStorage}\label{ReleaseMemStorage}
4696 Releases memory storage.
4700 void cvReleaseMemStorage( CvMemStorage** storage );
4705 \cvarg{storage}{Pointer to the released storage}
4708 The function \texttt{cvReleaseMemStorage} deallocates all storage memory
4709 blocks or returns them to the parent, if any. Then it deallocates the
4710 storage header and clears the pointer to the storage. All child storage
4711 associated with a given parent storage block must be released before the
4712 parent storage block is released.
4714 \cvfunc{ClearMemStorage}\label{ClearMemStorage}
4716 Clears memory storage.
4720 void cvClearMemStorage( CvMemStorage* storage );
4725 \cvarg{storage}{Memory storage}
4728 The function \texttt{cvClearMemStorage} resets the top (free space
4729 boundary) of the storage to the very beginning. This function does not
4730 deallocate any memory. If the storage has a parent, the function returns
4731 all blocks to the parent.
4733 \cvfunc{MemStorageAlloc}\label{MemStorageAlloc}
4735 Allocates a memory buffer in a storage block.
4739 void* cvMemStorageAlloc( \par CvMemStorage* storage,\par size\_t size );
4744 \cvarg{storage}{Memory storage}
4745 \cvarg{size}{Buffer size}
4748 The function \texttt{cvMemStorageAlloc} allocates a memory buffer in
4749 a storage block. The buffer size must not exceed the storage block size,
4750 otherwise a runtime error is raised. The buffer address is aligned by
4751 \texttt{CV\_STRUCT\_ALIGN=sizeof(double)} (for the moment) bytes.
4753 \cvfunc{MemStorageAllocString}\label{MemStorageAllocString}
4755 Allocates a text string in a storage block.
4759 CvString cvMemStorageAllocString( CvMemStorage* storage, const char* ptr, int len=-1 );
4765 typedef struct CvString
4775 \cvarg{storage}{Memory storage}
4776 \cvarg{ptr}{The string}
4777 \cvarg{len}{Length of the string (not counting the ending \texttt{NUL}) . If the parameter is negative, the function computes the length.}
4780 The function \texttt{cvMemStorageAllocString} creates copy of the string
4781 in memory storage. It returns the structure that contains user-passed
4782 or computed length of the string and pointer to the copied string.
4784 \cvfunc{SaveMemStoragePos}\label{SaveMemStoragePos}
4786 Saves memory storage position.
4790 void cvSaveMemStoragePos( \par const CvMemStorage* storage,\par CvMemStoragePos* pos );
4795 \cvarg{storage}{Memory storage}
4796 \cvarg{pos}{The output position of the storage top}
4799 The function \texttt{cvSaveMemStoragePos} saves the current position
4800 of the storage top to the parameter \texttt{pos}. The function
4801 \texttt{cvRestoreMemStoragePos} can further retrieve this position.
4803 \cvfunc{RestoreMemStoragePos}\label{RestoreMemStoragePos}
4805 Restores memory storage position.
4809 void cvRestoreMemStoragePos( \par CvMemStorage* storage,\par CvMemStoragePos* pos );
4814 \cvarg{storage}{Memory storage}
4815 \cvarg{pos}{New storage top position}
4818 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 an occupied portion of a storage block.
4821 \subsection{Sequences}
4823 \cvstruct{CvSeq}\label{CvSeq}
4825 Growable sequence of elements.
4828 Many OpenCV functions return a CvSeq object. The CvSeq obect is a sequence, so these are all legal:
4830 seq = cv.FindContours(scribble, storage, cv.CV_RETR_CCOMP, cv.CV_CHAIN_APPROX_SIMPLE)
4831 # seq is a sequence of point pairs
4833 # FindContours returns a sequence of (x,y) points, so to print them out:
4836 print seq[10] # tenth entry in the seqeuence
4837 print seq[::-1] # reversed sequence
4838 print sorted(list(seq)) # sorted sequence
4841 Also, a CvSeq object has methods
4844 \texttt{v_next()} and
4846 Some OpenCV functions (for example \cross{FindContours}) can return multiple CvSeq objects, connected by these relations.
4847 In this case the methods return the other sequences. If no relation between sequences exists, then the methods return \texttt{None}.
4854 #define CV_SEQUENCE\_FIELDS() \
4855 int flags; /* micsellaneous flags */ \
4856 int header_size; /* size of sequence header */ \
4857 struct CvSeq* h_prev; /* previous sequence */ \
4858 struct CvSeq* h_next; /* next sequence */ \
4859 struct CvSeq* v_prev; /* 2nd previous sequence */ \
4860 struct CvSeq* v_next; /* 2nd next sequence */ \
4861 int total; /* total number of elements */ \
4862 int elem_size;/* size of sequence element in bytes */ \
4863 char* block_max;/* maximal bound of the last block */ \
4864 char* ptr; /* current write pointer */ \
4865 int delta_elems; /* how many elements allocated when the sequence grows
4866 (sequence granularity) */ \
4867 CvMemStorage* storage; /* where the seq is stored */ \
4868 CvSeqBlock* free_blocks; /* free blocks list */ \
4869 CvSeqBlock* first; /* pointer to the first sequence block */
4871 typedef struct CvSeq
4873 CV_SEQUENCE_FIELDS()
4878 The structure \cross{CvSeq} is a base for all of OpenCV dynamic data structures.
4880 Such an unusual definition via a helper macro simplifies the extension
4881 of the structure \cross{CvSeq} with additional parameters. To extend
4882 \cross{CvSeq} the user may define a new structure and put user-defined
4883 fields after all \cross{CvSeq} fields that are included via the macro
4884 \texttt{CV\_SEQUENCE\_FIELDS()}.
4886 There are two types of sequences - dense and sparse. The base type for dense
4887 sequences is \cross{CvSeq} and such sequences are used to represent
4888 growable 1d arrays - vectors, stacks, queues, and deques. They have no gaps
4889 in the middle - if an element is removed from the middle or inserted
4890 into the middle of the sequence, the elements from the closer end are
4891 shifted. Sparse sequences have \cross{CvSet} as a base class and they are
4892 discussed later in more detail. They are sequences of nodes; each may be either occupied or free as indicated by the node flag. Such
4893 sequences are used for unordered data structures such as sets of elements,
4894 graphs, hash tables and so forth.
4896 The field \texttt{header\_size} contains the actual size of the sequence
4897 header and should be greater than or equal to \texttt{sizeof(CvSeq)}.
4900 \texttt{h\_prev}, \texttt{h\_next}, \texttt{v\_prev}, \texttt{v\_next}
4901 can be used to create hierarchical structures from separate sequences. The
4902 fields \texttt{h\_prev} and \texttt{h\_next} point to the previous and
4903 the next sequences on the same hierarchical level, while the fields
4904 \texttt{v\_prev} and \texttt{v\_next} point to the previous and the
4905 next sequences in the vertical direction, that is, the parent and its first
4906 child. But these are just names and the pointers can be used in a
4909 The field \texttt{first} points to the first sequence block, whose structure is described below.
4911 The field \texttt{total} contains the actual number of dense sequence elements and number of allocated nodes in a sparse sequence.
4913 The field \texttt{flags} contains the particular dynamic type
4914 signature (\texttt{CV\_SEQ\_MAGIC\_VAL} for dense sequences and
4915 \texttt{CV\_SET\_MAGIC\_VAL} for sparse sequences) in the highest 16
4916 bits and miscellaneous information about the sequence. The lowest
4917 \texttt{CV\_SEQ\_ELTYPE\_BITS} bits contain the ID of the element
4918 type. Most of sequence processing functions do not use element type but rather
4919 element size stored in \texttt{elem\_size}. If a sequence contains the
4920 numeric data for one of the \cross{CvMat} type then the element type matches
4921 to the corresponding \cross{CvMat} element type, e.g., \texttt{CV\_32SC2} may be
4922 used for a sequence of 2D points, \texttt{CV\_32FC1} for sequences of floating-point
4923 values, etc. A \texttt{CV\_SEQ\_ELTYPE(seq\_header\_ptr)} macro retrieves the
4924 type of sequence elements. Processing functions that work with numerical
4925 sequences check that \texttt{elem\_size} is equal to that calculated from
4926 the type element size. Besides \cross{CvMat} compatible types, there
4927 are few extra element types defined in the \texttt{cvtypes.h} header:
4929 Standard Types of Sequence Elements
4933 #define CV_SEQ_ELTYPE_POINT CV_32SC2 /* (x,y) */
4934 #define CV_SEQ_ELTYPE_CODE CV_8UC1 /* freeman code: 0..7 */
4935 #define CV_SEQ_ELTYPE_GENERIC 0 /* unspecified type of
4936 sequence elements */
4937 #define CV_SEQ_ELTYPE_PTR CV_USRTYPE1 /* =6 */
4938 #define CV_SEQ_ELTYPE_PPOINT CV_SEQ_ELTYPE_PTR /* &elem: pointer to
4939 element of other sequence */
4940 #define CV_SEQ_ELTYPE_INDEX CV_32SC1 /* #elem: index of element of
4941 some other sequence */
4942 #define CV_SEQ_ELTYPE_GRAPH_EDGE CV_SEQ_ELTYPE_GENERIC /* &next_o,
4943 &next_d, &vtx_o, &vtx_d */
4944 #define CV_SEQ_ELTYPE_GRAPH_VERTEX CV_SEQ_ELTYPE_GENERIC /* first_edge,
4946 #define CV_SEQ_ELTYPE_TRIAN_ATR CV_SEQ_ELTYPE_GENERIC /* vertex of the
4948 #define CV_SEQ_ELTYPE_CONNECTED_COMP CV_SEQ_ELTYPE_GENERIC /* connected
4950 #define CV_SEQ_ELTYPE_POINT3D CV_32FC3 /* (x,y,z) */
4954 The next \texttt{CV\_SEQ\_KIND\_BITS} bits specify the kind of sequence:
4956 Standard Kinds of Sequences
4960 /* generic (unspecified) kind of sequence */
4961 #define CV_SEQ_KIND_GENERIC (0 << CV_SEQ_ELTYPE_BITS)
4963 /* dense sequence suntypes */
4964 #define CV_SEQ_KIND_CURVE (1 << CV_SEQ_ELTYPE_BITS)
4965 #define CV_SEQ_KIND_BIN_TREE (2 << CV_SEQ_ELTYPE_BITS)
4967 /* sparse sequence (or set) subtypes */
4968 #define CV_SEQ_KIND_GRAPH (3 << CV_SEQ_ELTYPE_BITS)
4969 #define CV_SEQ_KIND_SUBDIV2D (4 << CV_SEQ_ELTYPE_BITS)
4973 The remaining bits are used to identify different features specific
4974 to certain sequence kinds and element types. For example, curves
4975 made of points \texttt{(CV\_SEQ\_KIND\_CURVE|CV\_SEQ\_ELTYPE\_POINT)},
4976 together with the flag \texttt{CV\_SEQ\_FLAG\_CLOSED}, belong to the
4977 type \texttt{CV\_SEQ\_POLYGON} or, if other flags are used, to its
4978 subtype. Many contour processing functions check the type of the input
4979 sequence and report an error if they do not support this type. The
4980 file \texttt{cvtypes.h} stores the complete list of all supported
4981 predefined sequence types and helper macros designed to get the sequence
4982 type of other properties. The definition of the building
4983 blocks of sequences can be found below.
4985 \cvstruct{CvSeqBlock}\label{CvSeqBlock}
4987 Continuous sequence block.
4991 typedef struct CvSeqBlock
4993 struct CvSeqBlock* prev; /* previous sequence block */
4994 struct CvSeqBlock* next; /* next sequence block */
4995 int start_index; /* index of the first element in the block +
4996 sequence->first->start_index */
4997 int count; /* number of elements in the block */
4998 char* data; /* pointer to the first element of the block */
5003 Sequence blocks make up a circular double-linked list, so the pointers
5004 \texttt{prev} and \texttt{next} are never \texttt{NULL} and point to the
5005 previous and the next sequence blocks within the sequence. It means that
5006 \texttt{next} of the last block is the first block and \texttt{prev} of
5007 the first block is the last block. The fields \texttt{start\_index} and
5008 \texttt{count} help to track the block location within the sequence. For
5009 example, if the sequence consists of 10 elements and splits into three
5010 blocks of 3, 5, and 2 elements, and the first block has the parameter
5011 \texttt{start\_index = 2}, then pairs \texttt{(start\_index, count)} for the sequence
5013 (2,3), (5, 5), and (10, 2)
5014 correspondingly. The parameter
5015 \texttt{start\_index} of the first block is usually \texttt{0} unless
5016 some elements have been inserted at the beginning of the sequence.
5018 \cvstruct{CvSlice}\label{CvSlice}
5024 typedef struct CvSlice
5030 inline CvSlice cvSlice( int start, int end );
5031 #define CV_WHOLE_SEQ_END_INDEX 0x3fffffff
5032 #define CV_WHOLE_SEQ cvSlice(0, CV_WHOLE_SEQ_END_INDEX)
5034 /* calculates the sequence slice length */
5035 int cvSliceLength( CvSlice slice, const CvSeq* seq );
5039 Some of functions that operate on sequences take a \texttt{CvSlice slice}
5040 parameter that is often set to the whole sequence (CV\_WHOLE\_SEQ) by
5041 default. Either of the \texttt{start\_index} and \texttt{end\_index}
5042 may be negative or exceed the sequence length, \texttt{start\_index} is
5043 inclusive, and \texttt{end\_index} is an exclusive boundary. If they are equal,
5044 the slice is considered empty (i.e., contains no elements). Because
5045 sequences are treated as circular structures, the slice may select a
5046 few elements in the end of a sequence followed by a few elements at the
5047 beginning of the sequence. For example, \texttt{cvSlice(-2, 3)} in the case of
5048 a 10-element sequence will select a 5-element slice, containing the pre-last
5049 (8th), last (9th), the very first (0th), second (1th) and third (2nd)
5050 elements. The functions normalize the slice argument in the following way:
5051 first, \cross{SliceLength} is called to determine the length of the slice,
5052 then, \texttt{start\_index} of the slice is normalized similarly to the
5053 argument of \cross{GetSeqElem} (i.e., negative indices are allowed). The
5054 actual slice to process starts at the normalized \texttt{start\_index}
5055 and lasts \cross{SliceLength} elements (again, assuming the sequence is
5056 a circular structure).
5058 If a function does not accept a slice argument, but you want to process
5059 only a part of the sequence, the sub-sequence may be extracted
5060 using the \cross{SeqSlice} function, or stored into a continuous
5061 buffer with \cross{CvtSeqToArray} (optionally, followed by
5062 \cross{MakeSeqHeaderForArray}).
5064 \cvfunc{CreateSeq}\label{CreateSeq}
5070 CvSeq* cvCreateSeq( \par int seq\_flags,\par int header\_size,\par int elem\_size,\par CvMemStorage* storage );
5075 \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.}
5076 \cvarg{header\_size}{Size of the sequence header; must be greater than or equal to \texttt{sizeof(CvSeq)}. If a specific type or its extension is indicated, this type must fit the base type header.}
5077 \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 \newline \texttt{CV\_SEQ\_ELTYPE\_POINT} should be specified and the parameter \texttt{elem\_size} must be equal to \texttt{sizeof(CvPoint)}.}
5078 \cvarg{storage}{Sequence location}
5081 The function \texttt{cvCreateSeq} creates a sequence and returns
5082 the pointer to it. The function allocates the sequence header in
5083 the storage block as one continuous chunk and sets the structure
5084 fields \texttt{flags}, \texttt{elem\_size}, \texttt{header\_size}, and
5085 \texttt{storage} to passed values, sets \texttt{delta\_elems} to the
5086 default value (that may be reassigned using the \cross{SetSeqBlockSize}
5087 function), and clears other header fields, including the space following
5088 the first \texttt{sizeof(CvSeq)} bytes.
5090 \cvfunc{SetSeqBlockSize}\label{SetSeqBlockSize}
5092 Sets up sequence block size.
5096 void cvSetSeqBlockSize( \par CvSeq* seq,\par int delta\_elems );
5101 \cvarg{seq}{Sequence}
5102 \cvarg{delta\_elems}{Desirable sequence block size for elements}
5106 The function \texttt{cvSetSeqBlockSize} affects memory allocation
5107 granularity. When the free space in the sequence buffers has run out,
5108 the function allocates the space for \texttt{delta\_elems} sequence
5109 elements. If this block immediately follows the one previously allocated,
5110 the two blocks are concatenated; otherwise, a new sequence block is
5111 created. Therefore, the bigger the parameter is, the lower the possible
5112 sequence fragmentation, but the more space in the storage block is wasted. When
5113 the sequence is created, the parameter \texttt{delta\_elems} is set to
5114 the default value of about 1K. The function can be called any time after
5115 the sequence is created and affects future allocations. The function
5116 can modify the passed value of the parameter to meet memory storage
5119 \cvfunc{SeqPush}\label{SeqPush}
5121 Adds an element to the end of a sequence.
5125 char* cvSeqPush( \par CvSeq* seq,\par void* element=NULL );
5130 \cvarg{seq}{Sequence}
5131 \cvarg{element}{Added element}
5135 The function \texttt{cvSeqPush} adds an element to the end of a sequence and returns a pointer to the allocated element. If the input \texttt{element} is NULL, the function simply allocates a space for one more element.
5137 The following code demonstrates how to create a new sequence using this function:
5141 CvMemStorage* storage = cvCreateMemStorage(0);
5142 CvSeq* seq = cvCreateSeq( CV_32SC1, /* sequence of integer elements */
5143 sizeof(CvSeq), /* header size - no extra fields */
5144 sizeof(int), /* element size */
5145 storage /* the container storage */ );
5147 for( i = 0; i < 100; i++ )
5149 int* added = (int*)cvSeqPush( seq, &i );
5150 printf( "%d is added\n", *added );
5154 /* release memory storage in the end */
5155 cvReleaseMemStorage( &storage );
5159 The function \texttt{cvSeqPush} has O(1) complexity, but there is a faster method for writing large sequences (see \cross{StartWriteSeq} and related functions).
5162 \cvfunc{SeqPop}\label{SeqPop}
5164 Removes an element from the end of a sequence.
5168 void cvSeqPop( \par CvSeq* seq,\par void* element=NULL );
5173 \cvarg{seq}{Sequence}
5174 \cvarg{element}{Optional parameter . If the pointer is not zero, the function copies the removed element to this location.}
5177 The function \texttt{cvSeqPop} removes an element from a sequence. The function reports an error if the sequence is already empty. The function has O(1) complexity.
5179 \cvfunc{SeqPushFront}\label{SeqPushFront}
5181 Adds an element to the beginning of a sequence.
5185 char* cvSeqPushFront( CvSeq* seq, void* element=NULL );
5190 \cvarg{seq}{Sequence}
5191 \cvarg{element}{Added element}
5194 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.
5196 \cvfunc{SeqPopFront}\label{SeqPopFront}
5198 Removes an element from the beginning of a sequence.
5202 void cvSeqPopFront( \par \par CvSeq* seq,\par\par void* element=NULL );
5207 \cvarg{seq}{Sequence}
5208 \cvarg{element}{Optional parameter. If the pointer is not zero, the function copies the removed element to this location.}
5211 The function \texttt{cvSeqPopFront} removes an element from the beginning of a sequence. The function reports an error if the sequence is already empty. The function has O(1) complexity.
5213 \cvfunc{SeqPushMulti}\label{SeqPushMulti}
5215 Pushes several elements to either end of a sequence.
5219 void cvSeqPushMulti( \par CvSeq* seq,\par void* elements,\par int count,\par int in\_front=0 );
5224 \cvarg{seq}{Sequence}
5225 \cvarg{elements}{Added elements}
5226 \cvarg{count}{Number of elements to push}
5227 \cvarg{in\_front}{The flags specifying which end of the modified sequence.
5229 \cvarg{CV\_BACK}{the elements are added to the end of the sequence}
5230 \cvarg{CV\_FRONT}{the elements are added to the beginning of the sequence}
5234 The function \texttt{cvSeqPushMulti} adds several elements to either
5235 end of a sequence. The elements are added to the sequence in the same
5236 order as they are arranged in the input array but they can fall into
5237 different sequence blocks.
5239 \cvfunc{SeqPopMulti}\label{SeqPopMulti}
5241 Removes several elements from either end of a sequence.
5245 void cvSeqPopMulti( \par CvSeq* seq,\par void* elements,\par int count,\par int in\_front=0 );
5250 \cvarg{seq}{Sequence}
5251 \cvarg{elements}{Removed elements}
5252 \cvarg{count}{Number of elements to pop}
5253 \cvarg{in\_front}{The flags specifying which end of the modified sequence.
5255 \cvarg{CV\_BACK}{the elements are added to the end of the sequence}
5256 \cvarg{CV\_FRONT}{the elements are added to the beginning of the sequence}
5260 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.
5262 \cvfunc{SeqInsert}\label{SeqInsert}
5264 Inserts an element in the middle of a sequence.
5268 char* cvSeqInsert( \par CvSeq* seq,\par int before\_index,\par void* element=NULL );
5273 \cvarg{seq}{Sequence}
5274 \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}.}
5275 \cvarg{element}{Inserted element}
5278 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 a pointer to the inserted element.
5281 \cvfunc{SeqRemove}\label{SeqRemove}
5283 Removes an element from the middle of a sequence.
5287 void cvSeqRemove( \par CvSeq* seq,\par int index );
5289 }{CPP}{SeqRemove(seq,index)-> None}
5292 \cvarg{seq}{Sequence}
5293 \cvarg{index}{Index of removed element}
5297 The function \texttt{cvSeqRemove} removes elements with the given
5298 index. If the index is out of range the function reports an error. An
5299 attempt to remove an element from an empty sequence is a special
5300 case of this situation. The function removes an element by shifting
5301 the sequence elements between the nearest end of the sequence and the
5302 \texttt{index}-th position, not counting the latter.
5305 \cvfunc{ClearSeq}\label{ClearSeq}
5311 void cvClearSeq( CvSeq* seq );
5313 }{CPP}{ClearSeq(seq)-> None}
5316 \cvarg{seq}{Sequence}
5320 The function \texttt{cvClearSeq} removes all elements from a
5321 sequence. The function does not return the memory to the storage block, but this
5322 memory is reused later when new elements are added to the sequence. The function has
5323 'O(1)' time complexity.
5326 \cvfunc{GetSeqElem}\label{GetSeqElem}
5328 Returns a pointer to a sequence element according to its index.
5332 char* cvGetSeqElem( const CvSeq* seq, int index );
5337 #define CV_GET_SEQ_ELEM( TYPE, seq, index ) (TYPE*)cvGetSeqElem( (CvSeq*)(seq), (index) )
5341 \cvarg{seq}{Sequence}
5342 \cvarg{index}{Index of element}
5346 The function \texttt{cvGetSeqElem} finds the element with the given
5347 index in the sequence and returns the pointer to it. If the element
5348 is not found, the function returns 0. The function supports negative
5349 indices, where -1 stands for the last sequence element, -2 stands for
5350 the one before last, etc. If the sequence is most likely to consist of
5351 a single sequence block or the desired element is likely to be located
5352 in the first block, then the macro
5353 \texttt{CV\_GET\_SEQ\_ELEM( elemType, seq, index )}
5354 should be used, where the parameter \texttt{elemType} is the
5355 type of sequence elements ( \cross{CvPoint} for example), the parameter
5356 \texttt{seq} is a sequence, and the parameter \texttt{index} is the index
5357 of the desired element. The macro checks first whether the desired element
5358 belongs to the first block of the sequence and returns it if it does;
5359 otherwise the macro calls the main function \texttt{GetSeqElem}. Negative
5360 indices always cause the \cross{GetSeqElem} call. The function has O(1)
5361 time complexity assuming that the number of blocks is much smaller than the
5364 \cvfunc{SeqElemIdx}\label{SeqElemIdx}
5366 Returns the index of a specific sequence element.
5370 int cvSeqElemIdx( \par const CvSeq* seq,\par const void* element,\par CvSeqBlock** block=NULL );
5375 \cvarg{seq}{Sequence}
5376 \cvarg{element}{Pointer to the element within the sequence}
5377 \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.}
5380 The function \texttt{cvSeqElemIdx} returns the index of a sequence element or a negative number if the element is not found.
5382 \cvfunc{CvtSeqToArray}\label{CvtSeqToArray}
5384 Copies a sequence to one continuous block of memory.
5388 void* cvCvtSeqToArray( \par const CvSeq* seq,\par void* elements,\par CvSlice slice=CV\_WHOLE\_SEQ );
5393 \cvarg{seq}{Sequence}
5394 \cvarg{elements}{Pointer to the destination array that must be large enough. It should be a pointer to data, not a matrix header.}
5395 \cvarg{slice}{The sequence portion to copy to the array}
5399 The function \texttt{cvCvtSeqToArray} copies the entire sequence or subsequence to the specified buffer and returns the pointer to the buffer.
5402 \cvfunc{MakeSeqHeaderForArray}\label{MakeSeqHeaderForArray}
5404 Constructs a sequence header for an array.
5408 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 );
5413 \cvarg{seq\_type}{Type of the created sequence}
5414 \cvarg{header\_size}{Size of the header of the sequence. Parameter sequence must point to the structure of that size or greater}
5415 \cvarg{elem\_size}{Size of the sequence elements}
5416 \cvarg{elements}{Elements that will form a sequence}
5417 \cvarg{total}{Total number of elements in the sequence. The number of array elements must be equal to the value of this parameter.}
5418 \cvarg{seq}{Pointer to the local variable that is used as the sequence header}
5419 \cvarg{block}{Pointer to the local variable that is the header of the single sequence block}
5422 The function \texttt{cvMakeSeqHeaderForArray} initializes a sequence
5423 header for an array. The sequence header as well as the sequence block are
5424 allocated by the user (for example, on stack). No data is copied by the
5425 function. The resultant sequence will consists of a single block and
5426 have NULL storage pointer; thus, it is possible to read its elements,
5427 but the attempts to add elements to the sequence will raise an error in
5430 \cvfunc{SeqSlice}\label{SeqSlice}
5432 Makes a separate header for a sequence slice.
5436 CvSeq* cvSeqSlice( \par const CvSeq* seq,\par CvSlice slice,\par CvMemStorage* storage=NULL,\par int copy\_data=0 );
5441 \cvarg{seq}{Sequence}
5442 \cvarg{slice}{The part of the sequence to be extracted}
5443 \cvarg{storage}{The destination storage block to hold the new sequence header and the copied data, if any. If it is NULL, the function uses the storage block containing the input sequence.}
5444 \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})}
5447 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 its 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.
5451 \cvfunc{CloneSeq}\label{CloneSeq}
5453 Creates a copy of a sequence.
5457 CvSeq* cvCloneSeq( \par const CvSeq* seq,\par CvMemStorage* storage=NULL );
5459 }{CPP}{CloneSeq(seq,storage)-> None}
5462 \cvarg{seq}{Sequence}
5463 \cvarg{storage}{The destination storage block to hold the new sequence header and the copied data, if any. If it is NULL, the function uses the storage block containing the input sequence.}
5466 The function \texttt{cvCloneSeq} makes a complete copy of the input sequence and returns it.
5471 cvCloneSeq( seq, storage )
5477 cvSeqSlice]( seq, CV_WHOLE_SEQ, storage, 1 )
5481 \cvfunc{SeqRemoveSlice}\label{SeqRemoveSlice}
5483 Removes a sequence slice.
5487 void cvSeqRemoveSlice( CvSeq* seq, CvSlice slice );
5489 }{CPP}{SeqRemoveSlice(seq,slice)-> None}
5492 \cvarg{seq}{Sequence}
5493 \cvarg{slice}{The part of the sequence to remove}
5497 The function \texttt{cvSeqRemoveSlice} removes a slice from the sequence.
5500 \cvfunc{SeqInsertSlice}\label{SeqInsertSlice}
5502 Inserts an array in the middle of a sequence.
5506 void cvSeqInsertSlice( \par CvSeq* seq,\par int before\_index,\par const CvArr* from\_arr );
5511 \cvarg{seq}{Sequence}
5512 \cvarg{slice}{The part of the sequence to remove}
5513 \cvarg{from\_arr}{The array to take elements from}
5517 The function \texttt{cvSeqInsertSlice} inserts all \texttt{from\_arr}
5518 array elements at the specified position of the sequence. The array
5519 \texttt{from\_arr} can be a matrix or another sequence.
5523 \cvfunc{SeqInvert}\label{SeqInvert}
5525 Reverses the order of sequence elements.
5529 void cvSeqInvert( CvSeq* seq );
5531 }{CPP}{SeqInvert(seq)-> None}
5534 \cvarg{seq}{Sequence}
5538 The function \texttt{cvSeqInvert} reverses the sequence in-place - makes the first element go last, the last element go first and so forth.
5541 \cvfunc{SeqSort}\label{SeqSort}
5543 Sorts sequence element using the specified comparison function.
5547 void cvSeqSort( CvSeq* seq, CvCmpFunc func, void* userdata=NULL );
5552 /* a < b ? -1 : a > b ? 1 : 0 */
5553 typedef int (CV_CDECL* CvCmpFunc)(const void* a, const void* b, void* userdata);
5557 \cvarg{seq}{The sequence to sort}
5558 \cvarg{func}{The comparison function that returns a negative, zero, or positive value depending on the relationships among the elements (see the above declaration and the example below) - a similar function is used by \texttt{qsort} from C runline except that in the latter, \texttt{userdata} is not used}
5559 \cvarg{userdata}{The user parameter passed to the compasion function; helps to avoid global variables in some cases}
5562 The function \texttt{cvSeqSort} sorts the sequence in-place using the specified criteria. Below is an example of using this function:
5566 /* Sort 2d points in top-to-bottom left-to-right order */
5567 static int cmp_func( const void* _a, const void* _b, void* userdata )
5569 CvPoint* a = (CvPoint*)_a;
5570 CvPoint* b = (CvPoint*)_b;
5571 int y_diff = a->y - b->y;
5572 int x_diff = a->x - b->x;
5573 return y_diff ? y_diff : x_diff;
5578 CvMemStorage* storage = cvCreateMemStorage(0);
5579 CvSeq* seq = cvCreateSeq( CV_32SC2, sizeof(CvSeq), sizeof(CvPoint), storage );
5582 for( i = 0; i < 10; i++ )
5585 pt.x = rand() % 1000;
5586 pt.y = rand() % 1000;
5587 cvSeqPush( seq, &pt );
5590 cvSeqSort( seq, cmp_func, 0 /* userdata is not used here */ );
5592 /* print out the sorted sequence */
5593 for( i = 0; i < seq->total; i++ )
5595 CvPoint* pt = (CvPoint*)cvSeqElem( seq, i );
5596 printf( "(%d,%d)\n", pt->x, pt->y );
5599 cvReleaseMemStorage( &storage );
5604 \cvfunc{SeqSearch}\label{SeqSearch}
5606 Searches for an element in a sequence.
5610 /* a < b ? -1 : a > b ? 1 : 0 */
5611 typedef int (CV_CDECL* CvCmpFunc)(const void* a, const void* b, void* userdata);
5613 char* cvSeqSearch( CvSeq* seq, const void* elem, CvCmpFunc func,
5614 int is_sorted, int* elem_idx, void* userdata=NULL );
5619 \cvarg{seq}{The sequence}
5620 \cvarg{elem}{The element to look for}
5621 \cvarg{func}{The comparison function that returns negative, zero or positive value depending on the relationships among the elements (see also \cross{SeqSort})}
5622 \cvarg{is\_sorted}{Whether the sequence is sorted or not}
5623 \cvarg{elem\_idx}{Output parameter; index of the found element}
5624 \cvarg{userdata}{The user parameter passed to the compasion function; helps to avoid global variables in some cases}
5627 The function \texttt{cvSeqSearch} searches for the element in the sequence. If
5628 the sequence is sorted, a binary O(log(N)) search is used; otherwise, a
5629 simple linear search is used. If the element is not found, the function
5630 returns a NULL pointer and the index is set to the number of sequence
5631 elements if a linear search is used, or to the smallest index
5632 \texttt{i, seq(i)>elem}
5635 \cvfunc{StartAppendToSeq}\label{StartAppendToSeq}
5637 Initializes the process of writing data to a sequence.
5641 void cvStartAppendToSeq( \par CvSeq* seq,\par CvSeqWriter* writer );
5646 \cvarg{seq}{Pointer to the sequence}
5647 \cvarg{writer}{Writer state; initialized by the function}
5650 The function \texttt{cvStartAppendToSeq} initializes the process of
5651 writing data to a sequence. Written elements are added to the end of the
5652 sequence by using the
5653 \texttt{CV\_WRITE\_SEQ\_ELEM( written\_elem, writer )}
5655 that during the writing process, other operations on the sequence may
5656 yield an incorrect result or even corrupt the sequence (see description of
5657 \cross{FlushSeqWriter}, which helps to avoid some of these problems).
5659 \cvfunc{StartWriteSeq}\label{StartWriteSeq}
5661 Creates a new sequence and initializes a writer for it.
5665 void cvStartWriteSeq( \par int seq\_flags,\par int header\_size,\par int elem\_size,\par CvMemStorage* storage,\par CvSeqWriter* writer );
5670 \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.}
5671 \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 within the base type header.}
5672 \cvarg{elem\_size}{Size of the sequence elements in bytes; must be consistent with the sequence type. For example, if a sequence of points is created (element type \texttt{CV\_SEQ\_ELTYPE\_POINT} ), then the parameter \texttt{elem\_size} must be equal to \texttt{sizeof(CvPoint)}.}
5673 \cvarg{storage}{Sequence location}
5674 \cvarg{writer}{Writer state; initialized by the function}
5677 The function \texttt{cvStartWriteSeq} is a combination of
5678 \cross{CreateSeq} and \cross{StartAppendToSeq}. The pointer to the
5679 created sequence is stored at
5680 \texttt{writer->seq}
5681 and is also returned by the
5682 \cross{EndWriteSeq} function that should be called at the end.
5684 \cvfunc{EndWriteSeq}\label{EndWriteSeq}
5686 Finishes the process of writing a sequence.
5690 CvSeq* cvEndWriteSeq( CvSeqWriter* writer );
5695 \cvarg{writer}{Writer state}
5699 The function \texttt{cvEndWriteSeq} finishes the writing process and
5700 returns the pointer to the written sequence. The function also truncates
5701 the last incomplete sequence block to return the remaining part of the
5702 block to memory storage. After that, the sequence can be read and
5705 \cvfunc{FlushSeqWriter}\label{FlushSeqWriter}
5707 Updates sequence headers from the writer.
5711 void cvFlushSeqWriter( CvSeqWriter* writer );
5716 \cvarg{writer}{Writer state}
5719 The function \texttt{cvFlushSeqWriter} is intended to enable the user to
5720 read sequence elements, whenever required, during the writing process,
5721 e.g., in order to check specific conditions. The function updates the
5722 sequence headers to make reading from the sequence possible. The writer
5723 is not closed, however, so that the writing process can be continued at
5724 any time. If an algorithm requires frequent flushes, consider using
5725 \cross{SeqPush} instead.
5727 \cvfunc{StartReadSeq}\label{StartReadSeq}
5729 Initializes the process of sequential reading from a sequence.
5733 void cvStartReadSeq( \par const CvSeq* seq,\par CvSeqReader* reader,\par int reverse=0 );
5738 \cvarg{seq}{Sequence}
5739 \cvarg{reader}{Reader state; initialized by the function}
5740 \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. }
5743 The function \texttt{cvStartReadSeq} initializes the reader state. After
5744 that, all the sequence elements from the first one down to the last one
5745 can be read by subsequent calls of the macro
5746 \texttt{CV\_READ\_SEQ\_ELEM( read\_elem, reader )}
5747 in the case of forward reading and by using
5748 \texttt{CV\_REV\_READ\_SEQ\_ELEM( read\_elem, reader )}
5749 in the case of reverse
5750 reading. Both macros put the sequence element to \texttt{read\_elem} and
5751 move the reading pointer toward the next element. A circular structure
5752 of sequence blocks is used for the reading process, that is, after the
5753 last element has been read by the macro \texttt{CV\_READ\_SEQ\_ELEM}, the
5754 first element is read when the macro is called again. The same applies to
5755 \texttt{CV\_REV\_READ\_SEQ\_ELEM}. There is no function to finish the reading
5756 process, since it neither changes the sequence nor creates any temporary
5757 buffers. The reader field \texttt{ptr} points to the current element of
5758 the sequence that is to be read next. The code below demonstrates how
5759 to use the sequence writer and reader.
5763 CvMemStorage* storage = cvCreateMemStorage(0);
5764 CvSeq* seq = cvCreateSeq( CV_32SC1, sizeof(CvSeq), sizeof(int), storage );
5769 cvStartAppendToSeq( seq, &writer );
5770 for( i = 0; i < 10; i++ )
5772 int val = rand()%100;
5773 CV_WRITE_SEQ_ELEM( val, writer );
5774 printf("%d is written\n", val );
5776 cvEndWriteSeq( &writer );
5778 cvStartReadSeq( seq, &reader, 0 );
5779 for( i = 0; i < seq->total; i++ )
5783 CV_READ_SEQ_ELEM( val, reader );
5784 printf("%d is read\n", val );
5785 #else /* alternative way, that is prefferable if sequence elements are large,
5786 or their size/type is unknown at compile time */
5787 printf("%d is read\n", *(int*)reader.ptr );
5788 CV_NEXT_SEQ_ELEM( seq->elem_size, reader );
5793 cvReleaseStorage( &storage );
5797 \cvfunc{GetSeqReaderPos}\label{GetSeqReaderPos}
5799 Returns the current reader position.
5803 int cvGetSeqReaderPos( CvSeqReader* reader );
5808 \cvarg{reader}{Reader state}
5812 The function \texttt{cvGetSeqReaderPos} returns the current reader position (within 0 ... \texttt{reader->seq->total} - 1).
5814 \cvfunc{SetSeqReaderPos}\label{SetSeqReaderPos}
5816 Moves the reader to the specified position.
5820 void cvSetSeqReaderPos( \par CvSeqReader* reader,\par int index,\par int is\_relative=0 );
5825 \cvarg{reader}{Reader state}
5826 \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}.}
5827 \cvarg{is\_relative}{If it is not zero, then \texttt{index} is a relative to the current position}
5830 The function \texttt{cvSetSeqReaderPos} moves the read position to an absolute position or relative to the current position.
5836 \cvstruct{CvSet}\label{CvSet}
5838 Collection of nodes.
5841 Some OpenCV functions return a CvSet object. The CvSeq obect is iterable, for example:
5854 typedef struct CvSetElem
5856 int flags; /* it is negative if the node is free and zero or positive otherwise */
5857 struct CvSetElem* next_free; /* if the node is free, the field is a
5858 pointer to next free node */
5862 #define CV_SET_FIELDS() \
5863 CV_SEQUENCE_FIELDS() /* inherits from [#CvSeq CvSeq] */ \
5864 struct CvSetElem* free_elems; /* list of free nodes */
5866 typedef struct CvSet
5873 The structure \cross{CvSet} is a base for OpenCV sparse data structures.
5875 As follows from the above declaration, \cross{CvSet} inherits from
5876 \cross{CvSeq} and it adds the \texttt{free\_elems} field, which
5877 is a list of free nodes, to it. Every set node, whether free or not, is an
5878 element of the underlying sequence. While there are no restrictions on
5879 elements of dense sequences, the set (and derived structures) elements
5880 must start with an integer field and be able to fit CvSetElem structure,
5881 because these two fields (an integer followed by a pointer) are required
5882 for the organization of a node set with the list of free nodes. If a node is
5883 free, the \texttt{flags} field is negative (the most-significant bit, or
5884 MSB, of the field is set), and the \texttt{next\_free} points to the next
5885 free node (the first free node is referenced by the \texttt{free\_elems}
5886 field of \cross{CvSet}). And if a node is occupied, the \texttt{flags} field
5887 is positive and contains the node index that may be retrieved using the
5888 (\texttt{set\_elem->flags \& CV\_SET\_ELEM\_IDX\_MASK}) expressions, the rest of
5889 the node content is determined by the user. In particular, the occupied
5890 nodes are not linked as the free nodes are, so the second field can be
5891 used for such a link as well as for some different purpose. The macro
5892 \texttt{CV\_IS\_SET\_ELEM(set\_elem\_ptr)} can be used to determined whether
5893 the specified node is occupied or not.
5895 Initially the set and the list are empty. When a new node is requested
5896 from the set, it is taken from the list of free nodes, which is then updated. If the list appears to be empty, a new sequence block is allocated
5897 and all the nodes within the block are joined in the list of free
5898 nodes. Thus, the \texttt{total} field of the set is the total number of nodes
5899 both occupied and free. When an occupied node is released, it is added
5900 to the list of free nodes. The node released last will be occupied first.
5902 In OpenCV \cross{CvSet} is used for representing graphs (\cross{CvGraph}),
5903 sparse multi-dimensional arrays (\cross{CvSparseMat}), and planar subdivisions
5906 \cvfunc{CreateSet}\label{CreateSet}
5908 Creates an empty set.
5912 CvSet* cvCreateSet( \par int set\_flags,\par int header\_size,\par int elem\_size,\par CvMemStorage* storage );
5917 \cvarg{set\_flags}{Type of the created set}
5918 \cvarg{header\_size}{Set header size; may not be less than \texttt{sizeof(CvSet)}}
5919 \cvarg{elem\_size}{Set element size; may not be less than \cross{CvSetElem}}
5920 \cvarg{storage}{Container for the set}
5923 The function \texttt{cvCreateSet} creates an empty set with a specified header size and element size, and returns the pointer to the set. This function is just a thin layer on top of \cross{CreateSeq}.
5925 \cvfunc{SetAdd}\label{SetAdd}
5927 Occupies a node in the set.
5931 int cvSetAdd( \par CvSet* set\_header,\par CvSetElem* elem=NULL,\par CvSetElem** inserted\_elem=NULL );
5936 \cvarg{set\_header}{Set}
5937 \cvarg{elem}{Optional input argument, an 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).}
5938 \cvarg{inserted\_elem}{Optional output argument; the pointer to the allocated cell}
5941 The function \texttt{cvSetAdd} allocates a new node, optionally copies
5942 input element data to it, and returns the pointer and the index to the
5943 node. The index value is taken from the lower bits of the \texttt{flags}
5944 field of the node. The function has O(1) complexity; however, there exists
5945 a faster function for allocating set nodes (see \cross{SetNew}).
5947 \cvfunc{SetRemove}\label{SetRemove}
5949 Removes an element from a set.
5953 void cvSetRemove( \par CvSet* set\_header,\par int index );
5958 \cvarg{set\_header}{Set}
5959 \cvarg{index}{Index of the removed element}
5962 The function \texttt{cvSetRemove} removes an element with a specified
5963 index from the set. If the node at the specified location is not occupied,
5964 the function does nothing. The function has O(1) complexity; however,
5965 \cross{SetRemoveByPtr} provides a quicker way to remove a set element
5966 if it is located already.
5968 \cvfunc{SetNew}\label{SetNew}
5970 Adds an element to a set (fast variant).
5974 CvSetElem* cvSetNew( CvSet* set\_header );
5979 \cvarg{set\_header}{Set}
5983 The function \texttt{cvSetNew} is an inline lightweight variant of \cross{SetAdd}. It occupies a new node and returns a pointer to it rather than an index.
5986 \cvfunc{SetRemoveByPtr}\label{SetRemoveByPtr}
5988 Removes a set element based on its pointer.
5992 void cvSetRemoveByPtr( \par CvSet* set\_header,\par void* elem );
5997 \cvarg{set\_header}{Set}
5998 \cvarg{elem}{Removed element}
6001 The function \texttt{cvSetRemoveByPtr} is an inline lightweight variant of \cross{SetRemove} that requires an element pointer. The function does not check whether the node is occupied or not - the user should take care of that.
6004 \cvfunc{GetSetElem}\label{GetSetElem}
6006 Finds a set element by its index.
6010 CvSetElem* cvGetSetElem( \par const CvSet* set\_header,\par int index );
6015 \cvarg{set\_header}{Set}
6016 \cvarg{index}{Index of the set element within a sequence}
6019 The function \texttt{cvGetSetElem} finds a set element by its 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.
6021 \cvfunc{ClearSet}\label{ClearSet}
6027 void cvClearSet( CvSet* set\_header );
6032 \cvarg{set\_header}{Cleared set}
6036 The function \texttt{cvClearSet} removes all elements from set. It has O(1) time complexity.
6044 \cvstruct{CvGraph}\label{CvGraph}
6046 Oriented or unoriented weighted graph.
6050 #define CV_GRAPH_VERTEX_FIELDS() \
6051 int flags; /* vertex flags */ \
6052 struct CvGraphEdge* first; /* the first incident edge */
6054 typedef struct CvGraphVtx
6056 CV_GRAPH_VERTEX_FIELDS()
6060 #define CV_GRAPH_EDGE_FIELDS() \
6061 int flags; /* edge flags */ \
6062 float weight; /* edge weight */ \
6063 struct CvGraphEdge* next[2]; /* the next edges in the incidence lists for staring (0) */ \
6064 /* and ending (1) vertices */ \
6065 struct CvGraphVtx* vtx[2]; /* the starting (0) and ending (1) vertices */
6067 typedef struct CvGraphEdge
6069 CV_GRAPH_EDGE_FIELDS()
6073 #define CV_GRAPH_FIELDS() \
6074 CV_SET_FIELDS() /* set of vertices */ \
6075 CvSet* edges; /* set of edges */
6077 typedef struct CvGraph
6085 The structure \cross{CvGraph} is a base for graphs used in OpenCV.
6087 The graph structure inherits from \cross{CvSet} - which describes common graph properties and the graph vertices, and contains another set as a member - which describes the graph edges.
6089 The vertex, edge, and the graph header structures are declared using the
6090 same technique as other extendible OpenCV structures - via macros, which
6091 simplify extension and customization of the structures. While the vertex
6092 and edge structures do not inherit from \cross{CvSetElem} explicitly, they
6093 satisfy both conditions of the set elements: having an integer field in
6094 the beginning and fitting within the CvSetElem structure. The \texttt{flags} fields are
6095 used as for indicating occupied vertices and edges as well as for other
6096 purposes, for example, for graph traversal (see \cross{CreateGraphScanner}
6097 et al.), so it is better not to use them directly.
6099 The graph is represented as a set of edges each of which has a list of
6100 incident edges. The incidence lists for different vertices are interleaved
6101 to avoid information duplication as much as posssible.
6103 The graph may be oriented or unoriented. In the latter case there is no
6104 distiction between the edge connecting vertex $A$ with vertex $B$ and the edge
6105 connecting vertex $B$ with vertex $A$ - only one of them can exist in the
6106 graph at the same moment and it represents both $A \rightarrow B$ and
6107 $B \rightarrow A$ edges.
6109 \cvfunc{CreateGraph}\label{CreateGraph}
6111 Creates an empty graph.
6115 CvGraph* cvCreateGraph( \par int graph\_flags,\par int header\_size,\par int vtx\_size,\par int edge\_size,\par CvMemStorage* storage );
6120 \cvarg{graph\_flags}{Type of the created graph. Usually, it is either \texttt{CV\_SEQ\_KIND\_GRAPH} for generic unoriented graphs and
6121 \texttt{CV\_SEQ\_KIND\_GRAPH | CV\_GRAPH\_FLAG\_ORIENTED} for generic oriented graphs.}
6122 \cvarg{header\_size}{Graph header size; may not be less than \texttt{sizeof(CvGraph)}}
6123 \cvarg{vtx\_size}{Graph vertex size; the custom vertex structure must start with \cross{CvGraphVtx} (use \texttt{CV\_GRAPH\_VERTEX\_FIELDS()})}
6124 \cvarg{edge\_size}{Graph edge size; the custom edge structure must start with \cross{CvGraphEdge} (use \texttt{CV\_GRAPH\_EDGE\_FIELDS()})}
6125 \cvarg{storage}{The graph container}
6128 The function \texttt{cvCreateGraph} creates an empty graph and returns a pointer to it.
6130 \cvfunc{GraphAddVtx}\label{GraphAddVtx}
6132 Adds a vertex to a graph.
6136 int cvGraphAddVtx( \par CvGraph* graph,\par const CvGraphVtx* vtx=NULL,\par CvGraphVtx** inserted\_vtx=NULL );
6141 \cvarg{graph}{Graph}
6142 \cvarg{vtx}{Optional input argument used to initialize the added vertex (only user-defined fields beyond \texttt{sizeof(CvGraphVtx)} are copied)}
6143 \cvarg{inserted\_vertex}{Optional output argument. If not \texttt{NULL}, the address of the new vertex is written here.}
6146 The function \texttt{cvGraphAddVtx} adds a vertex to the graph and returns the vertex index.
6148 \cvfunc{GraphRemoveVtx}\label{GraphRemoveVtx}
6150 Removes a vertex from a graph.
6154 int cvGraphRemoveVtx( \par CvGraph* graph,\par int index );
6159 \cvarg{graph}{Graph}
6160 \cvarg{vtx\_idx}{Index of the removed vertex}
6163 The function \texttt{cvGraphRemoveAddVtx} removes a vertex from a graph
6164 together with all the edges incident to it. The function reports an error
6165 if the input vertex does not belong to the graph. The return value is the
6166 number of edges deleted, or -1 if the vertex does not belong to the graph.
6168 \cvfunc{GraphRemoveVtxByPtr}\label{GraphRemoveVtxByPtr}
6170 Removes a vertex from a graph by using its pointer.
6174 int cvGraphRemoveVtxByPtr( \par CvGraph* graph,\par CvGraphVtx* vtx );
6179 \cvarg{graph}{Graph}
6180 \cvarg{vtx}{Pointer to the removed vertex}
6184 The function \texttt{cvGraphRemoveVtxByPtr} removes a vertex from the graph by using its pointer 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 the number of edges deleted, or -1 if the vertex does not belong to the graph.
6186 \cvfunc{GetGraphVtx}\label{GetGraphVtx}
6188 Finds a graph vertex by using its index.
6192 CvGraphVtx* cvGetGraphVtx( \par CvGraph* graph,\par int vtx\_idx );
6197 \cvarg{graph}{Graph}
6198 \cvarg{vtx\_idx}{Index of the vertex}
6202 The function \texttt{cvGetGraphVtx} finds the graph vertex by using its index and returns the pointer to it or NULL if the vertex does not belong to the graph.
6205 \cvfunc{GraphVtxIdx}\label{GraphVtxIdx}
6207 Returns the index of a graph vertex.
6211 int cvGraphVtxIdx( \par CvGraph* graph,\par CvGraphVtx* vtx );
6216 \cvarg{graph}{Graph}
6217 \cvarg{vtx}{Pointer to the graph vertex}
6220 The function \texttt{cvGraphVtxIdx} returns the index of a graph vertex.
6222 \cvfunc{GraphAddEdge}\label{GraphAddEdge}
6224 Adds an edge to a graph.
6228 int cvGraphAddEdge( \par CvGraph* graph,\par int start\_idx,\par int end\_idx,\par const CvGraphEdge* edge=NULL,\par CvGraphEdge** inserted\_edge=NULL );
6233 \cvarg{graph}{Graph}
6234 \cvarg{start\_idx}{Index of the starting vertex of the edge}
6235 \cvarg{end\_idx}{Index of the ending vertex of the edge. For an unoriented graph, the order of the vertex parameters does not matter.}
6236 \cvarg{edge}{Optional input parameter, initialization data for the edge}
6237 \cvarg{inserted\_edge}{Optional output parameter to contain the address of the inserted edge}
6241 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.
6243 \cvfunc{GraphAddEdgeByPtr}\label{GraphAddEdgeByPtr}
6245 Adds an edge to a graph by using its pointer.
6249 int cvGraphAddEdgeByPtr( \par CvGraph* graph,\par CvGraphVtx* start\_vtx,\par CvGraphVtx* end\_vtx,\par const CvGraphEdge* edge=NULL,\par CvGraphEdge** inserted\_edge=NULL );
6254 \cvarg{graph}{Graph}
6255 \cvarg{start\_vtx}{Pointer to the starting vertex of the edge}
6256 \cvarg{end\_vtx}{Pointer to the ending vertex of the edge. For an unoriented graph, the order of the vertex parameters does not matter.}
6257 \cvarg{edge}{Optional input parameter, initialization data for the edge}
6258 \cvarg{inserted\_edge}{Optional output parameter to contain the address of the inserted edge within the edge set}
6261 The function \texttt{cvGraphAddEdge} connects two specified vertices. The
6262 function returns 1 if the edge has been added successfully, 0 if the
6263 edge connecting the two vertices exists already, and -1 if either of the
6264 vertices was not found, the starting and the ending vertex are the same
6265 or there is some other critical situation. In the latter case (i.e., when
6266 the result is negative), the function also reports an error by default.
6268 \cvfunc{GraphRemoveEdge}\label{GraphRemoveEdge}
6270 Removes an edge from a graph.
6274 void cvGraphRemoveEdge( \par CvGraph* graph,\par int start\_idx,\par int end\_idx );
6279 \cvarg{graph}{Graph}
6280 \cvarg{start\_idx}{Index of the starting vertex of the edge}
6281 \cvarg{end\_idx}{Index of the ending vertex of the edge. For an unoriented graph, the order of the vertex parameters does not matter.}
6284 The function \texttt{cvGraphRemoveEdge} removes the edge connecting two specified vertices. If the vertices are not connected [in that order], the function does nothing.
6286 \cvfunc{GraphRemoveEdgeByPtr}\label{GraphRemoveEdgeByPtr}
6288 Removes an edge from a graph by using its pointer.
6292 void cvGraphRemoveEdgeByPtr( \par CvGraph* graph,\par CvGraphVtx* start\_vtx,\par CvGraphVtx* end\_vtx );
6297 \cvarg{graph}{Graph}
6298 \cvarg{start\_vtx}{Pointer to the starting vertex of the edge}
6299 \cvarg{end\_vtx}{Pointer to the ending vertex of the edge. For an unoriented graph, the order of the vertex parameters does not matter.}
6302 The function \texttt{cvGraphRemoveEdgeByPtr} removes the edge connecting two specified vertices. If the vertices are not connected [in that order], the function does nothing.
6304 \cvfunc{FindGraphEdge}\label{FindGraphEdge}
6306 Finds an edge in a graph.
6310 CvGraphEdge* cvFindGraphEdge( const CvGraph* graph, int start\_idx, int end\_idx );
6316 #define cvGraphFindEdge cvFindGraphEdge
6321 \cvarg{graph}{Graph}
6322 \cvarg{start\_idx}{Index of the starting vertex of the edge}
6323 \cvarg{end\_idx}{Index of the ending vertex of the edge. For an unoriented graph, the order of the vertex parameters does not matter.}
6326 The function \texttt{cvFindGraphEdge} finds the graph edge connecting two specified vertices and returns a pointer to it or NULL if the edge does not exist.
6328 \cvfunc{FindGraphEdgeByPtr}\label{FindGraphEdgeByPtr}
6330 Finds an edge in a graph by using its pointer.
6334 CvGraphEdge* cvFindGraphEdgeByPtr( \par const CvGraph* graph,\par const CvGraphVtx* start\_vtx,\par const CvGraphVtx* end\_vtx );
6339 \#define cvGraphFindEdgeByPtr cvFindGraphEdgeByPtr
6343 \cvarg{graph}{Graph}
6344 \cvarg{start\_vtx}{Pointer to the starting vertex of the edge}
6345 \cvarg{end\_vtx}{Pointer to the ending vertex of the edge. For an unoriented graph, the order of the vertex parameters does not matter.}
6348 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.
6350 \cvfunc{GraphEdgeIdx}\label{GraphEdgeIdx}
6352 Returns the index of a graph edge.
6356 int cvGraphEdgeIdx( \par CvGraph* graph,\par CvGraphEdge* edge );
6361 \cvarg{graph}{Graph}
6362 \cvarg{edge}{Pointer to the graph edge}
6365 The function \texttt{cvGraphEdgeIdx} returns the index of a graph edge.
6367 \cvfunc{GraphVtxDegree}\label{GraphVtxDegree}
6369 Counts the number of edges indicent to the vertex.
6373 int cvGraphVtxDegree( const CvGraph* graph, int vtx\_idx );
6378 \cvarg{graph}{Graph}
6379 \cvarg{vtx}{Index of the graph vertex}
6382 The function \texttt{cvGraphVtxDegree} returns the number of edges incident to the specified vertex, both incoming and outgoing. To count the edges, the following code is used:
6386 CvGraphEdge* edge = vertex->first; int count = 0;
6389 edge = CV_NEXT_GRAPH_EDGE( edge, vertex );
6395 The macro \texttt{CV\_NEXT\_GRAPH\_EDGE( edge, vertex )} returns the edge incident to \texttt{vertex} that follows after \texttt{edge}.
6397 \cvfunc{GraphVtxDegreeByPtr}\label{GraphVtxDegreeByPtr}
6399 Finds an edge in a graph.
6403 int cvGraphVtxDegreeByPtr( \par const CvGraph* graph,\par const CvGraphVtx* vtx );
6408 \cvarg{graph}{Graph}
6409 \cvarg{vtx}{Pointer to the graph vertex}
6412 The function \texttt{cvGraphVtxDegree} returns the number of edges incident to the specified vertex, both incoming and outcoming.
6415 \cvfunc{ClearGraph}\label{ClearGraph}
6421 void cvClearGraph( CvGraph* graph );
6426 \cvarg{graph}{Graph}
6429 The function \texttt{cvClearGraph} removes all vertices and edges from a graph. The function has O(1) time complexity.
6431 \cvfunc{CloneGraph}\label{CloneGraph}
6437 CvGraph* cvCloneGraph( \par const CvGraph* graph,\par CvMemStorage* storage );
6442 \cvarg{graph}{The graph to copy}
6443 \cvarg{storage}{Container for the copy}
6447 The function \texttt{cvCloneGraph} creates a full copy of the specified graph. If the
6448 graph vertices or edges have pointers to some external data, it can still be
6449 shared between the copies. The vertex and edge indices in the new graph
6450 may be different from the original because the function defragments
6451 the vertex and edge sets.
6454 \cvstruct{CvGraphScanner}\label{CvGraphScanner}
6456 Graph traversal state.
6460 typedef struct CvGraphScanner
6462 CvGraphVtx* vtx; /* current graph vertex (or current edge origin) */
6463 CvGraphVtx* dst; /* current graph edge destination vertex */
6464 CvGraphEdge* edge; /* current edge */
6466 CvGraph* graph; /* the graph */
6467 CvSeq* stack; /* the graph vertex stack */
6468 int index; /* the lower bound of certainly visited vertices */
6469 int mask; /* event mask */
6475 The structure \cross{CvGraphScanner} is used for depth-first graph traversal. See discussion of the functions below.
6478 \cvfunc{CreateGraphScanner}\label{CreateGraphScanner}
6480 Creates structure for depth-first graph traversal.
6484 CvGraphScanner* cvCreateGraphScanner( \par CvGraph* graph,\par CvGraphVtx* vtx=NULL,\par int mask=CV\_GRAPH\_ALL\_ITEMS );
6489 \cvarg{graph}{Graph}
6490 \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).}
6491 \cvarg{mask}{Event mask indicating which events are of interest to the user (where \cross{NextGraphItem} function returns control to the user) It can be \texttt{CV\_GRAPH\_ALL\_ITEMS} (all events are of interest) or a combination of the following flags:
6494 \cvarg{CV\_GRAPH\_VERTEX}{stop at the graph vertices visited for the first time}
6495 \cvarg{CV\_GRAPH\_TREE\_EDGE}{stop at tree edges (\texttt{tree edge} is the edge connecting the last visited vertex and the vertex to be visited next)}
6496 \cvarg{CV\_GRAPH\_BACK\_EDGE}{stop at back edges (\texttt{back edge} is an edge connecting the last visited vertex with some of its ancestors in the search tree)}
6497 \cvarg{CV\_GRAPH\_FORWARD\_EDGE}{stop at forward edges (\texttt{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)}
6498 \cvarg{CV\_GRAPH\_CROSS\_EDGE}{stop at cross edges (\texttt{cross edge} is an edge connecting different search trees or branches of the same tree. The \texttt{cross edges} are only possible during oriented graph traversal)}
6499 \cvarg{CV\_GRAPH\_ANY\_EDGE}{stop at any edge (\texttt{tree, back, forward}, and \texttt{cross edges})}
6500 \cvarg{CV\_GRAPH\_NEW\_TREE}{stop in the beginning of every new search tree. When the traversal procedure visits all vertices and edges reachable 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 a \texttt{CV\_GRAPH\_NEW\_TREE} event. For unoriented graphs, each search tree corresponds to a connected component of the graph.}
6501 \cvarg{CV\_GRAPH\_BACKTRACKING}{stop at every already visited vertex during backtracking - returning to already visited vertexes of the traversal tree.}
6505 The function \texttt{cvCreateGraphScanner} creates a structure for depth-first graph traversal/search. The initialized structure is used in the \cross{NextGraphItem} function - the incremental traversal procedure.
6507 \cvfunc{NextGraphItem}\label{NextGraphItem}
6509 Executes one or more steps of the graph traversal procedure.
6513 int cvNextGraphItem( CvGraphScanner* scanner );
6518 \cvarg{scanner}{Graph traversal state. It is updated by this function.}
6521 The function \texttt{cvNextGraphItem} traverses through the graph
6522 until an event of interest to the user (that is, an event, specified
6523 in the \texttt{mask} in the \cross{CreateGraphScanner} call) is met or the
6524 traversal is completed. In the first case, it returns one of the events
6525 listed in the description of the \texttt{mask} parameter above and with
6526 the next call it resumes the traversal. In the latter case, it returns
6527 \texttt{CV\_GRAPH\_OVER} (-1). When the event is \texttt{CV\_GRAPH\_VERTEX},
6528 \texttt{CV\_GRAPH\_BACKTRACKING}, or \texttt{CV\_GRAPH\_NEW\_TREE},
6529 the currently observed vertex is stored in \texttt{scanner-$>$vtx}. And if the
6530 event is edge-related, the edge itself is stored at \texttt{scanner-$>$edge},
6531 the previously visited vertex - at \texttt{scanner-$>$vtx} and the other ending
6532 vertex of the edge - at \texttt{scanner-$>$dst}.
6534 \cvfunc{ReleaseGraphScanner}\label{ReleaseGraphScanner}
6536 Completes the graph traversal procedure.
6540 void cvReleaseGraphScanner( CvGraphScanner** scanner );
6545 \cvarg{scanner}{Double pointer to graph traverser}
6549 The function \texttt{cvGraphScanner} completes the graph traversal procedure and releases the traverser state.
6555 \cvmacro{CV\_TREE\_NODE\_FIELDS}\label{CV_TREE_NODE_FIELDS}
6557 Helper macro for a tree node type declaration.
6561 #define CV_TREE_NODE_FIELDS(node_type) \
6562 int flags; /* micsellaneous flags */ \
6563 int header_size; /* size of sequence header */ \
6564 struct node_type* h_prev; /* previous sequence */ \
6565 struct node_type* h_next; /* next sequence */ \
6566 struct node_type* v_prev; /* 2nd previous sequence */ \
6567 struct node_type* v_next; /* 2nd next sequence */
6571 The macro \texttt{CV\_TREE\_NODE\_FIELDS()} is used to declare structures
6572 that can be organized into hierarchical strucutures (trees), such as
6573 \cross{CvSeq} - the basic type for all dynamic structures. The trees
6574 created with nodes declared using this macro can be processed using the
6575 functions described below in this section.
6577 \cvstruct{CvTreeNodeIterator}\label{CvTreeNodeIterator}
6579 Opens existing or creates new file storage.
6583 typedef struct CvTreeNodeIterator
6593 The structure \cross{CvTreeNodeIterator} is used to traverse trees. The tree node declaration should start with the \texttt{CV\_TREE\_NODE\_FIELDS(...)} macro.
6595 \cvfunc{InitTreeNodeIterator}\label{InitTreeNodeIterator}
6597 Initializes the tree node iterator.
6601 void cvInitTreeNodeIterator( \par CvTreeNodeIterator* tree\_iterator,\par const void* first,\par int max\_level );
6606 \cvarg{tree\_iterator}{Tree iterator initialized by the function}
6607 \cvarg{first}{The initial node to start traversing from}
6608 \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, and so forth.}
6611 The function \texttt{cvInitTreeNodeIterator} initializes the tree iterator. The tree is traversed in depth-first order.
6613 \cvfunc{NextTreeNode}\label{NextTreeNode}
6615 Returns the currently observed node and moves the iterator toward the next node.
6619 void* cvNextTreeNode( CvTreeNodeIterator* tree\_iterator );
6624 \cvarg{tree\_iterator}{Tree iterator initialized by the function}
6628 The function \texttt{cvNextTreeNode} returns the currently observed node and then updates the iterator - moving it toward the next node. In other words, the function behavior is similar to the *p++ expression on a typical C pointer or C++ collection iterator. The function returns NULL if there are no more nodes.
6631 \cvfunc{PrevTreeNode}\label{PrevTreeNode}
6633 Returns the currently observed node and moves the iterator toward the previous node.
6637 void* cvPrevTreeNode( CvTreeNodeIterator* tree\_iterator );
6642 \cvarg{tree\_iterator}{Tree iterator initialized by the function}
6646 The function \texttt{cvPrevTreeNode} returns the currently observed node and then updates the iterator - moving it toward the previous node. In other words, the function behavior is similar to the *p-- expression on a typicl C pointer or C++ collection iterator. The function returns NULL if there are no more nodes.
6649 \cvfunc{TreeToNodeSeq}\label{TreeToNodeSeq}
6651 Gathers all node pointers to a single sequence.
6655 CvSeq* cvTreeToNodeSeq( \par const void* first,\par int header\_size,\par CvMemStorage* storage );
6660 \cvarg{first}{The initial tree node}
6661 \cvarg{header\_size}{Header size of the created sequence (sizeof(CvSeq) is the most frequently used value)}
6662 \cvarg{storage}{Container for the sequence}
6665 The function \texttt{cvTreeToNodeSeq} puts pointers of all nodes reacheable from \texttt{first} into a single sequence. The pointers are written sequentially in the depth-first order.
6667 \cvfunc{InsertNodeIntoTree}\label{InsertNodeIntoTree}
6669 Adds a new node to a tree.
6673 void cvInsertNodeIntoTree( \par void* node,\par void* parent,\par void* frame );
6678 \cvarg{node}{The inserted node}
6679 \cvarg{parent}{The parent node that is already in the tree}
6680 \cvarg{frame}{The top level node. If \texttt{parent} and \texttt{frame} are the same, the \texttt{v\_prev} field of \texttt{node} is set to NULL rather than \texttt{parent}.}
6683 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.
6685 \cvfunc{RemoveNodeFromTree}\label{RemoveNodeFromTree}
6687 Removes a node from a tree.
6691 void cvRemoveNodeFromTree( \par void* node,\par void* frame );
6696 \cvarg{node}{The removed node}
6697 \cvarg{frame}{The top level node. If \texttt{node-$>$v\_prev = NULL} and \texttt{node-$>$h\_prev} is NULL (i.e., if \texttt{node} is the first child of \texttt{frame}), \texttt{frame-$>$v\_next} is set to \texttt{node-$>$h\_next} (i.e., the first child or frame is changed).}
6702 The function \texttt{cvRemoveNodeFromTree} removes a node from a tree. The function does not deallocate any memory; it can only modify links of the tree nodes.
6704 \section{Drawing Functions}
6706 Drawing functions work with matrices/images of arbitrary depth.
6707 Antialiasing is implemented only for 8-bit images. All the functions
6708 include the parameter color that uses a rgb value (that may be constructed
6709 with \texttt{CV\_RGB} macro or the \texttt{cvScalar} function) for color
6710 images and brightness for grayscale images.
6712 If a drawn figure is partially or completely outside the image, it
6713 is clipped. For color images the order channel is: Blue Green Red
6714 ... If one needs a different channel order, it is possible to
6715 construct color via \texttt{cvScalar} with the specific channel
6716 order, or to convert the image before and/or after drawing in it with
6717 \cross{CvtColor} or \cross{Transform}.
6719 \subsection{Curves and Shapes}
6721 \cvfunc{CV\_RGB}\label{CV_RGB}
6723 Constructs a color value.
6726 \#define CV\_RGB( r, g, b ) cvScalar( (b), (g), (r) )
6727 }{CPP}{CV\_RGB(red,grn,blu)->CvScalar}
6729 \cvfunc{Line}\label{Line}
6731 Draws a line segment connecting two points.
6734 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 );
6735 }{CPP}{Line(img,pt1,pt2,color,thickness=1,line\_type=8,shift=0)-> None}
6738 \cvarg{img}{The image}
6739 \cvarg{pt1}{First point of the line segment}
6740 \cvarg{pt2}{Second point of the line segment}
6741 \cvarg{color}{Line color}
6742 \cvarg{thickness}{Line thickness}
6743 \cvarg{line\_type}{Type of the line:
6745 \cvarg{8}{(or omitted) 8-connected line.}
6746 \cvarg{4}{4-connected line.}
6747 \cvarg{CV\_AA}{antialiased line.}
6749 \cvarg{shift}{Number of fractional bits in the point coordinates}
6752 The function \texttt{cvLine} draws the line segment between
6753 \texttt{pt1} and \texttt{pt2} points in the image. The line is
6754 clipped by the image or ROI rectangle. For non-antialiased lines
6755 with integer coordinates the 8-connected or 4-connected Bresenham
6756 algorithm is used. Thick lines are drawn with rounding endings.
6757 Antialiased lines are drawn using Gaussian filtering. To specify
6758 the line color, the user may use the macro
6759 \texttt{CV\_RGB( r, g, b )}.
6761 \cvfunc{Rectangle}\label{Rectangle}
6763 Draws a simple, thick, or filled rectangle.
6767 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 );
6769 }{CPP}{Rectangle(img,pt1,pt2,color,thickness=1,line\_type=8,shift=0)-> None}
6773 \cvarg{pt1}{One of the rectangle's vertices}
6774 \cvarg{pt2}{Opposite rectangle vertex}
6775 \cvarg{color}{Line color (RGB) or brightness (grayscale image)}
6776 \cvarg{thickness}{Thickness of lines that make up the rectangle. Negative values, e.g., CV\_FILLED, cause the function to draw a filled rectangle.}
6777 \cvarg{line\_type}{Type of the line, see \cross{Line} description}
6778 \cvarg{shift}{Number of fractional bits in the point coordinates}
6781 The function \texttt{cvRectangle} draws a rectangle with two opposite corners \texttt{pt1} and \texttt{pt2}.
6783 \cvfunc{Circle}\label{Circle}
6789 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 );
6791 }{CPP}{Circle(img,center,radius,color,thickness=1,line\_type=8,shift=0)-> None}
6794 \cvarg{img}{Image where the circle is drawn}
6795 \cvarg{center}{Center of the circle}
6796 \cvarg{radius}{Radius of the circle}
6797 \cvarg{color}{Circle color}
6798 \cvarg{thickness}{Thickness of the circle outline if positive, otherwise this indicates that a filled circle is to be drawn}
6799 \cvarg{line\_type}{Type of the circle boundary, see \cross{Line} description}
6800 \cvarg{shift}{Number of fractional bits in the center coordinates and radius value}
6803 The function \texttt{cvCircle} draws a simple or filled circle with a
6804 given center and radius. The circle is clipped by the ROI rectangle.
6805 To specify the circle color, the user may use the macro
6806 \texttt{CV\_RGB( r, g, b )}.
6808 \cvfunc{Ellipse}\label{Ellipse}
6810 Draws a simple or thick elliptic arc or an fills ellipse sector.
6814 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 );
6816 }{CPP}{Ellipse(img,pt1,axes,angle,start\_angle,end\_angle,color,thickness=1,line\_type=8,shift=0)-> None}
6819 \cvarg{img}{The image}
6820 \cvarg{center}{Center of the ellipse}
6821 \cvarg{axes}{Length of the ellipse axes}
6822 \cvarg{angle}{Rotation angle}
6823 \cvarg{start\_angle}{Starting angle of the elliptic arc}
6824 \cvarg{end\_angle}{Ending angle of the elliptic arc.}
6825 \cvarg{color}{Ellipse color}
6826 \cvarg{thickness}{Thickness of the ellipse arc outline if positive, otherwise this indicates that a filled ellipse sector is to be drawn}
6827 \cvarg{line\_type}{Type of the ellipse boundary, see \cross{Line} description}
6828 \cvarg{shift}{Number of fractional bits in the center coordinates and axes' values}
6831 The function \texttt{cvEllipse} draws a simple or thick elliptic
6832 arc or fills an ellipse sector. The arc is clipped by the ROI rectangle.
6833 A piecewise-linear approximation is used for antialiased arcs and
6834 thick arcs. All the angles are given in degrees. The picture below
6835 explains the meaning of the parameters.
6837 Parameters of Elliptic Arc
6839 \includegraphics[width=0.5\textwidth]{pics/ellipse.png}
6843 Draws a simple or thick elliptic arc or fills an ellipse sector.
6847 void cvEllipseBox( \par CvArr* img, \par CvBox2D box, \par CvScalar color,
6848 \par int thickness=1, \par int line\_type=8, \par int shift=0 );
6850 }{CPP}{EllipseBox(img,box,color,thickness=1,line\_type=8,shift=0)-> None}
6854 \cvarg{box}{The enclosing box of the ellipse drawn}
6855 \cvarg{thickness}{Thickness of the ellipse boundary}
6856 \cvarg{line\_type}{Type of the ellipse boundary, see \cross{Line} description}
6857 \cvarg{shift}{Number of fractional bits in the box vertex coordinates}
6860 The function \texttt{cvEllipseBox} draws a simple or thick ellipse outline, or fills an ellipse. The functions provides a convenient way to draw an ellipse approximating some shape; that is what \cross{CamShift} and \cross{FitEllipse} do. The ellipse drawn is clipped by ROI rectangle. A piecewise-linear approximation is used for antialiased arcs and thick arcs.
6862 \cvfunc{FillPoly}\label{FillPoly}
6864 Fills a polygon's interior.
6868 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 );
6870 }{CPP}{FillPoly(img,polys,color,line\_type=8,shift=0)-> None}
6875 \cvarg{pts}{Array of pointers to polygons}
6876 \cvarg{npts}{Array of polygon vertex counters}
6877 \cvarg{contours}{Number of contours that bind the filled region}
6880 \cvarg{polys}{List of lists of (x,y) pairs. Each list of points is a polygon.}
6882 \cvarg{color}{Polygon color}
6883 \cvarg{line\_type}{Type of the polygon boundaries, see \cross{Line} description}
6884 \cvarg{shift}{Number of fractional bits in the vertex coordinates}
6888 The function \texttt{cvFillPoly} fills an area bounded by several
6889 polygonal contours. The function fills complex areas, for example,
6890 areas with holes, contour self-intersection, and so forth.
6892 \cvfunc{FillConvexPoly}\label{FillConvexPoly}
6894 Fills a convex polygon.
6898 void cvFillConvexPoly( \par CvArr* img,\par CvPoint* pts,\par int npts,\par CvScalar color,\par int line\_type=8,\par int shift=0 );
6900 }{CPP}{FillConvexPoly(img,pn,color,line\_type=8,shift=0)-> None}
6904 \cvarg{pts}{Array of pointers to a single polygon}
6905 \cvarg{npts}{Polygon vertex counter}
6906 \cvarg{color}{Polygon color}
6907 \cvarg{line\_type}{Type of the polygon boundaries, see \cross{Line} description}
6908 \cvarg{shift}{Number of fractional bits in the vertex coordinates}
6911 The function \texttt{cvFillConvexPoly} fills a convex polygon's interior.
6912 This function is much faster than the function \texttt{cvFillPoly}
6913 and can fill not only convex polygons but any monotonic polygon,
6914 i.e., a polygon whose contour intersects every horizontal line (scan
6915 line) twice at the most.
6918 \cvfunc{PolyLine}\label{PolyLine}
6920 Draws simple or thick polygons.
6924 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 );
6926 }{CPP}{PolyLine(img,pts,is\_closed,color,thickness=1,line\_type=8,shift=0)-> None}
6930 \cvarg{pts}{Array of pointers to polygons}
6931 \cvarg{npts}{Array of polygon vertex counters}
6932 \cvarg{contours}{Number of contours that bind the filled region}
6935 \cvarg{polys}{List of lists of (x,y) pairs. Each list of points is a polygon.}
6938 \cvarg{is\_closed}{Indicates whether the polylines must be drawn
6939 closed. If closed, the function draws the line from the last vertex
6940 of every contour to the first vertex.}
6941 \cvarg{color}{Polyline color}
6942 \cvarg{thickness}{Thickness of the polyline edges}
6943 \cvarg{line\_type}{Type of the line segments, see \cross{Line} description}
6944 \cvarg{shift}{Number of fractional bits in the vertex coordinates}
6947 The function \texttt{cvPolyLine} draws single or multiple polygonal curves.
6951 \cvfunc{InitFont}\label{InitFont}
6953 Initializes font structure.
6956 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 );
6957 }{CPP}{InitFont(font\_face,hscale,vscale,shear=0,thickness=1,line\_type=8)-> font}
6960 \cvarg{font}{Pointer to the font structure initialized by the function}
6961 \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:
6963 \cvarg{CV\_FONT\_HERSHEY\_SIMPLEX}{normal size sans-serif font}
6964 \cvarg{CV\_FONT\_HERSHEY\_PLAIN}{small size sans-serif font}
6965 \cvarg{CV\_FONT\_HERSHEY\_DUPLEX}{normal size sans-serif font (more complex than \newline \texttt{CV\_FONT\_HERSHEY\_SIMPLEX})}
6966 \cvarg{CV\_FONT\_HERSHEY\_COMPLEX}{normal size serif font}
6967 \cvarg{CV\_FONT\_HERSHEY\_TRIPLEX}{normal size serif font (more complex than \texttt{CV\_FONT\_HERSHEY\_COMPLEX})}
6968 \cvarg{CV\_FONT\_HERSHEY\_COMPLEX\_SMALL}{smaller version of \texttt{CV\_FONT\_HERSHEY\_COMPLEX}}
6969 \cvarg{CV\_FONT\_HERSHEY\_SCRIPT\_SIMPLEX}{hand-writing style font}
6970 \cvarg{CV\_FONT\_HERSHEY\_SCRIPT\_COMPLEX}{more complex variant of \texttt{CV\_FONT\_HERSHEY\_SCRIPT\_SIMPLEX}}
6972 The parameter can be composited from one of the values above and an optional \texttt{CV\_FONT\_ITALIC} flag, which indicates italic or oblique font.}
6973 \cvarg{hscale}{Horizontal scale. If equal to \texttt{1.0f}, the characters have the original width depending on the font type. If equal to \texttt{0.5f}, the characters are of half the original width.}
6974 \cvarg{vscale}{Vertical scale. If equal to \texttt{1.0f}, the characters have the original height depending on the font type. If equal to \texttt{0.5f}, the characters are of half the original height.}
6975 \cvarg{shear}{Approximate tangent of the character slope relative to the vertical line. A zero value means a non-italic font, \texttt{1.0f} means about a 45 degree slope, etc.}
6976 \cvarg{thickness}{Thickness of the text strokes}
6977 \cvarg{line\_type}{Type of the strokes, see \cross{Line} description}
6980 The function \texttt{cvInitFont} initializes the font structure that can be passed to text rendering functions.
6983 \cvfunc{PutText}\label{PutText}
6985 Draws a text string.
6989 void cvPutText( \par CvArr* img,\par const char* text,\par CvPoint org,\par const CvFont* font,\par CvScalar color );
6991 }{CPP}{PutText(img,text,org,font,color)-> None}
6994 \cvarg{img}{Input image}
6995 \cvarg{text}{String to print}
6996 \cvarg{org}{Coordinates of the bottom-left corner of the first letter}
6997 \cvarg{font}{Pointer to the font structure}
6998 \cvarg{color}{Text color}
7002 The function \texttt{cvPutText} renders the text in the image with
7003 the specified font and color. The printed text is clipped by the ROI
7004 rectangle. Symbols that do not belong to the specified font are
7005 replaced with the symbol for a rectangle.
7007 \cvfunc{GetTextSize}\label{GetTextSize}
7009 Retrieves the width and height of a text string.
7013 void cvGetTextSize( \par const char* text\_string,\par const CvFont* font,\par CvSize* text\_size,\par int* baseline );
7015 }{CPP}{GetTextSize(text\_string,font)-> text\_size,baseline}
7018 \cvarg{font}{Pointer to the font structure}
7019 \cvarg{text\_string}{Input string}
7020 \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.}
7021 \cvarg{baseline}{y-coordinate of the baseline relative to the bottom-most text point}
7024 The function \texttt{cvGetTextSize} calculates the dimensions of a rectangle to enclose a text string when a specified font is used.
7026 \subsection{Point Sets and Contours}
7028 \cvfunc{DrawContours}\label{DrawContours}
7030 Draws contour outlines or interiors in an image.
7034 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 );
7036 }{CPP}{DrawContours(img,contour,external\_color,hole\_color,max\_level,thickness=1,line\_type=8,offset=(0,0)-> None}
7039 \cvarg{img}{Image where the contours are to be drawn. As with any other drawing function, the contours are clipped with the ROI.}
7040 \cvarg{contour}{Pointer to the first contour}
7041 \cvarg{external\_color}{Color of the external contours}
7042 \cvarg{hole\_color}{Color of internal contours (holes)}
7043 \cvarg{max\_level}{Maximal level for drawn contours. If 0, only
7044 \texttt{contour} is drawn. If 1, the contour and all contours following
7045 it on the same level are drawn. If 2, all contours following and all
7046 contours one level below the contours are drawn, and so forth. If the value
7047 is negative, the function does not draw the contours following after
7048 \texttt{contour} but draws the child contours of \texttt{contour} up
7049 to the $ |\texttt{max\_level}|-1$ level.}
7050 \cvarg{thickness}{Thickness of lines the contours are drawn with.
7051 If it is negative (For example, =CV\_FILLED), the contour interiors are
7053 \cvarg{line\_type}{Type of the contour segments, see \cross{Line} description}
7056 The function \texttt{cvDrawContours} draws contour outlines in the image if $\texttt{thickness} \ge 0$ or fills the area bounded by the contours if $ \texttt{thickness}<0$.
7058 \cvfunc{Example: Connected component detection via contour functions}
7063 #include "highgui.h"
7065 int main( int argc, char** argv )
7068 // the first command line parameter must be file name of binary
7069 // (black-n-white) image
7070 if( argc == 2 && (src=cvLoadImage(argv[1], 0))!= 0)
7072 IplImage* dst = cvCreateImage( cvGetSize(src), 8, 3 );
7073 CvMemStorage* storage = cvCreateMemStorage(0);
7076 cvThreshold( src, src, 1, 255, CV_THRESH_BINARY );
7077 cvNamedWindow( "Source", 1 );
7078 cvShowImage( "Source", src );
7080 cvFindContours( src, storage, &contour, sizeof(CvContour),
7081 CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE );
7084 for( ; contour != 0; contour = contour->h_next )
7086 CvScalar color = CV_RGB( rand()&255, rand()&255, rand()&255 );
7087 /* replace CV_FILLED with 1 to see the outlines */
7088 cvDrawContours( dst, contour, color, color, -1, CV_FILLED, 8 );
7091 cvNamedWindow( "Components", 1 );
7092 cvShowImage( "Components", dst );
7099 Replace \texttt{CV\_FILLED} with 1 in the example below to see the contour outlines.
7101 \cvfunc{InitLineIterator}\label{InitLineIterator}
7103 Initializes the line iterator.
7107 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 );
7109 }{CPP}{InitLineIterator(image, pt1, pt2, connectivity=8, left\_to\_right=0)}
7112 \cvarg{image}{Image to sample the line from}
7113 \cvarg{pt1}{First ending point of the line segment}
7114 \cvarg{pt2}{Second ending point of the line segment}
7115 \cvC{\cvarg{line\_iterator}{Pointer to the line iterator state structure}}
7116 \cvarg{connectivity}{The scanned line connectivity, 4 or 8.}
7117 \cvarg{left\_to\_right}{
7118 If ($ \texttt{left\_to\_right} = 0 $ ) then the line is scanned in the specified order, from \texttt{pt1} to \texttt{pt2}.
7119 If ($ \texttt{left\_to\_right} \ne 0$) the line is scanned from left-most point to right-most.}
7122 The function \texttt{cvInitLineIterator} initializes the line
7123 iterator and returns the number of pixels between the two end points.
7124 Both points must be inside the image. After the iterator has been
7125 initialized, all the points on the raster line that connects the
7126 two ending points may be retrieved by successive calls of
7127 \texttt{CV\_NEXT\_LINE\_POINT} point. The points on the line are
7128 calculated one by one using a 4-connected or 8-connected Bresenham
7132 \cvfunc{Example: Using line iterator to calculate the sum of pixel values along the color line}
7136 CvScalar sum_line_pixels( IplImage* image, CvPoint pt1, CvPoint pt2 )
7138 CvLineIterator iterator;
7139 int blue_sum = 0, green_sum = 0, red_sum = 0;
7140 int count = cvInitLineIterator( image, pt1, pt2, &iterator, 8, 0 );
7142 for( int i = 0; i < count; i++ ){
7143 blue_sum += iterator.ptr[0];
7144 green_sum += iterator.ptr[1];
7145 red_sum += iterator.ptr[2];
7146 CV_NEXT_LINE_POINT(iterator);
7148 /* print the pixel coordinates: demonstrates how to calculate the
7152 /* assume that ROI is not set, otherwise need to take it
7154 offset = iterator.ptr - (uchar*)(image->imageData);
7155 y = offset/image->widthStep;
7156 x = (offset - y*image->widthStep)/(3*sizeof(uchar)
7157 /* size of pixel */);
7158 printf("(%d,%d)\n", x, y );
7161 return cvScalar( blue_sum, green_sum, red_sum );
7167 \cvfunc{ClipLine}\label{ClipLine}
7169 Clips the line against the image rectangle.
7173 int cvClipLine( \par CvSize img\_size,\par CvPoint* pt1,\par CvPoint* pt2 );
7175 }{CPP}{ClipLine(img, pt1, pt2) -> (clipped\_pt1, clipped\_pt2)}
7178 \cvarg{img\_size}{Size of the image \cvPy{as a 2-tuple}}
7179 \cvarg{pt1}{First ending point of the line segment. \cvC{It is modified by the function.}}
7180 \cvarg{pt2}{Second ending point of the line segment. \cvC{It is modified by the function.}}
7183 The function \texttt{cvClipLine} calculates a part of the line
7184 segment which is entirely within the image.
7185 \cvC{It returns 0 if the line segment is completely outside the image and 1 otherwise.}
7186 \cvPy{If the line segment is outside the image, it returns None. If the line segment is inside the image it returns a new pair of points.}
7189 \cvfunc{Ellipse2Poly}\label{Ellipse2Poly}
7191 Approximates an elliptic arc with a polyline.
7195 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 );
7200 \cvarg{center}{Center of the arc}
7201 \cvarg{axes}{Half-sizes of the arc. See \cross{Ellipse}.}
7202 \cvarg{angle}{Rotation angle of the ellipse in degrees. See \cross{Ellipse}}
7203 \cvarg{start\_angle}{Starting angle of the elliptic arc}
7204 \cvarg{end\_angle}{Ending angle of the elliptic arc}
7205 \cvarg{pts}{The array of points, filled in by the function}
7206 \cvarg{delta}{Angle between the subsequent polyline vertices, approximation accuracy. So, the total number of output points will
7207 $ \lceil( \texttt{end\_angle} - \texttt{start\_angle} ) / \texttt{delta} \rceil + 1 $
7211 The function \texttt{cvEllipse2Poly} computes the vertices of a polyline that approximates the specified elliptic arc. It is used by \cross{Ellipse}.
7215 \section{Data Persistence and RTTI}
7218 \subsection{File Storage}
7220 \cvstruct{CvFileStorage}\label{CvFileStorage}
7226 typedef struct CvFileStorage
7228 ... // hidden fields
7233 The structure \cross{CvFileStorage} is a "black box" representation
7234 of the file storage associated with a file on disk. Several
7235 functions that are described below take \texttt{CvFileStorage} as
7236 inputs and allow theuser to save or to load hierarchical collections
7237 that consist of scalar values, standard CXCore objects (such as
7238 matrices, sequences, graphs), and user-defined objects.
7240 CXCore can read and write data in XML (http://www.w3c.org/XML) or YAML
7241 (http://www.yaml.org) formats. Below is an example of $3 \times 3$
7242 floating-point identity matrix \texttt{A}, stored in XML and YAML files
7243 using CXCore functions:
7248 <?xml version="1.0">
7250 <A type_id="opencv-matrix">
7254 <data>1. 0. 0. 0. 1. 0. 0. 0. 1.</data>
7267 data: [ 1., 0., 0., 0., 1., 0., 0., 0., 1.]
7270 As it can be seen from the examples, XML uses nested tags to represent
7271 hierarchy, while YAML uses indentation for that purpose (similar
7272 to the Python programming language).
7274 The same CXCore functions can read and write data in both formats;
7275 the particular format is determined by the extension of the opened
7276 file, .xml for XML files and .yml or .yaml for YAML.
7279 \cvstruct{CvFileNode}\label{CvFileNode}
7285 /* file node type */
7286 #define CV_NODE_NONE 0
7287 #define CV_NODE_INT 1
7288 #define CV_NODE_INTEGER CV_NODE_INT
7289 #define CV_NODE_REAL 2
7290 #define CV_NODE_FLOAT CV_NODE_REAL
7291 #define CV_NODE_STR 3
7292 #define CV_NODE_STRING CV_NODE_STR
7293 #define CV_NODE_REF 4 /* not used */
7294 #define CV_NODE_SEQ 5
7295 #define CV_NODE_MAP 6
7296 #define CV_NODE_TYPE_MASK 7
7298 /* optional flags */
7299 #define CV_NODE_USER 16
7300 #define CV_NODE_EMPTY 32
7301 #define CV_NODE_NAMED 64
7303 #define CV_NODE_TYPE(tag) ((tag) & CV_NODE_TYPE_MASK)
7305 #define CV_NODE_IS_INT(tag) (CV_NODE_TYPE(tag) == CV_NODE_INT)
7306 #define CV_NODE_IS_REAL(tag) (CV_NODE_TYPE(tag) == CV_NODE_REAL)
7307 #define CV_NODE_IS_STRING(tag) (CV_NODE_TYPE(tag) == CV_NODE_STRING)
7308 #define CV_NODE_IS_SEQ(tag) (CV_NODE_TYPE(tag) == CV_NODE_SEQ)
7309 #define CV_NODE_IS_MAP(tag) (CV_NODE_TYPE(tag) == CV_NODE_MAP)
7310 #define CV_NODE_IS_COLLECTION(tag) (CV_NODE_TYPE(tag) >= CV_NODE_SEQ)
7311 #define CV_NODE_IS_FLOW(tag) (((tag) & CV_NODE_FLOW) != 0)
7312 #define CV_NODE_IS_EMPTY(tag) (((tag) & CV_NODE_EMPTY) != 0)
7313 #define CV_NODE_IS_USER(tag) (((tag) & CV_NODE_USER) != 0)
7314 #define CV_NODE_HAS_NAME(tag) (((tag) & CV_NODE_NAMED) != 0)
7316 #define CV_NODE_SEQ_SIMPLE 256
7317 #define CV_NODE_SEQ_IS_SIMPLE(seq) (((seq)->flags & CV_NODE_SEQ_SIMPLE) != 0)
7319 typedef struct CvString
7326 /* all the keys (names) of elements in the readed file storage
7327 are stored in the hash to speed up the lookup operations */
7328 typedef struct CvStringHashNode
7332 struct CvStringHashNode* next;
7336 /* basic element of the file storage - scalar or collection */
7337 typedef struct CvFileNode
7340 struct CvTypeInfo* info; /* type information
7341 (only for user-defined object, for others it is 0) */
7344 double f; /* scalar floating-point number */
7345 int i; /* scalar integer number */
7346 CvString str; /* text string */
7347 CvSeq* seq; /* sequence (ordered collection of file nodes) */
7348 struct CvMap* map; /* map (collection of named file nodes) */
7355 The structure is used only for retrieving data from file storage
7356 (i.e., for loading data from the file). When data is written to a file,
7357 it is done sequentially, with minimal buffering. No data is stored
7358 in the file storage.
7360 In opposite, when data is read from a file, the whole file is parsed
7361 and represented in memory as a tree. Every node of the tree is
7362 represented by \cross{CvFileNode}. The type of file node \texttt{N}
7363 can be retrieved as \texttt{CV\_NODE\_TYPE(N->tag)}. Some file nodes
7364 (leaves) are scalars: text strings, integers, or floating-point
7365 numbers. Other file nodes are collections of file nodes, which can
7366 be scalars or collections in their turn. There are two types of
7367 collections: sequences and maps (we use YAML notation, however, the
7368 same is true for XML streams). Sequences (do not mix them with
7369 \cross{CvSeq}) are ordered collections of unnamed file nodes; maps
7370 are unordered collections of named file nodes. Thus, elements of
7371 sequences are accessed by index (\cross{GetSeqElem}), while elements
7372 of maps are accessed by name (\cross{GetFileNodeByName}). The table
7373 below describes the different types of file nodes:
7375 \begin{tabular}{| c | c | c |}
7377 Type & \texttt{CV\_NODE\_TYPE(node->tag)} & Value\\ \hline \hline
7378 Integer & \texttt{CV\_NODE\_INT} & \texttt{node->data.i} \\ \hline
7379 Floating-point & \texttt{CV\_NODE\_REAL} & \texttt{node->data.f} \\ \hline
7380 Text string & \texttt{CV\_NODE\_STR} & \texttt{node->data.str.ptr} \\ \hline
7381 Sequence & \texttt{CV\_NODE\_SEQ} & \texttt{node->data.seq} \\ \hline
7382 Map & \texttt{CV\_NODE\_MAP} & \texttt{node->data.map} (see below)\\ \hline
7385 There is no need to access the \texttt{map} field directly (by the way,
7386 \texttt{CvMap} is a hidden structure). The elements of the map can
7387 be retrieved with the \cross{GetFileNodeByName} function that takes a
7388 pointer to the "map" file node.
7390 A user (custom) object is an instance of either one of the standard CxCore
7391 types, such as \cross{CvMat}, \cross{CvSeq} etc., or any type
7392 registered with \cross{RegisterTypeInfo}. Such an object is initially
7393 represented in a file as a map (as shown in XML and YAML example files
7394 above) after the file storage has been opened and parsed. Then the
7395 object can be decoded (coverted to native representation) by
7396 request - when a user calls the \cross{Read} or \cross{ReadByName} functions.
7399 \cvstruct{CvAttrList}\label{CvAttrList}
7405 typedef struct CvAttrList
7407 const char** attr; /* NULL-terminated array of (attribute\_name,attribute\_value) pairs */
7408 struct CvAttrList* next; /* pointer to next chunk of the attributes list */
7412 /* initializes CvAttrList structure */
7413 inline CvAttrList cvAttrList( const char** attr=NULL, CvAttrList* next=NULL );
7415 /* returns attribute value or 0 (NULL) if there is no such attribute */
7416 const char* cvAttrValue( const CvAttrList* attr, const char* attr\_name );
7420 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, aside from the object type specification (\texttt{type\_id} attribute).
7422 \cvfunc{OpenFileStorage}\label{OpenFileStorage}
7424 Opens file storage for reading or writing data.
7428 CvFileStorage* cvOpenFileStorage( \par const char* filename,\par CvMemStorage* memstorage,\par int flags );
7433 \cvarg{filename}{Name of the file associated with the storage}
7434 \cvarg{memstorage}{Memory storage used for temporary data and for
7435 storing dynamic structures, such as \cross{CvSeq} or \cross{CvGraph}.
7436 If it is NULL, a temporary memory storage is created and used.}
7437 \cvarg{flags}{Can be one of the following:
7439 \cvarg{CV\_STORAGE\_READ}{the storage is open for reading}
7440 \cvarg{CV\_STORAGE\_WRITE}{the storage is open for writing}
7444 The function \texttt{cvOpenFileStorage} opens file storage for
7445 reading or writing data. In the latter case, a new file is created
7446 or an existing file is rewritten. The type of the read or written file is
7447 determined by the filename extension: \texttt{.xml} for \texttt{XML}
7448 and \texttt{.yml} or \texttt{.yaml} for \texttt{YAML}. The function
7449 returns a pointer to the \cross{CvFileStorage} structure.
7451 \cvfunc{ReleaseFileStorage}\label{ReleaseFileStorage}
7453 Releases file storage.
7457 void cvReleaseFileStorage( CvFileStorage** fs );
7462 \cvarg{fs}{Double pointer to the released file storage}
7466 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.
7469 \subsection{Writing Data}
7471 \cvfunc{StartWriteStruct}\label{StartWriteStruct}
7473 Starts writing a new structure.
7477 void cvStartWriteStruct( CvFileStorage* fs,\par const char* name,\par int struct\_flags,\par const char* type\_name=NULL,\par CvAttrList attributes=cvAttrList( \par));
7482 \cvarg{fs}{File storage}
7483 \cvarg{name}{Name of the written structure. The structure can be accessed by this name when the storage is read.}
7484 \cvarg{struct\_flags}{A combination one of the following values:
7486 \cvarg{CV\_NODE\_SEQ}{the written structure is a sequence (see discussion of \cross{CvFileStorage}), that is, its elements do not have a name.}
7487 \cvarg{CV\_NODE\_MAP}{the written structure is a map (see discussion of \cross{CvFileStorage}), that is, all its elements have names.\end{description}}
7488 One and only one of the two above flags must be specified}
7490 \cvarg{CV\_NODE\_FLOW}{the optional flag that makes 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.}
7491 \cvarg{type\_name}{Optional parameter - the object type name. In
7492 case of XML it is written as a \texttt{type\_id} attribute of the
7493 structure opening tag. In the case of YAML it is written after a colon
7494 following the structure name (see the example in \cross{CvFileStorage}
7495 description). Mainly it is used with user objects. When the storage
7496 is read, the encoded type name is used to determine the object type
7497 (see \cross{CvTypeInfo} and \cross{FindTypeInfo}).}
7498 \cvarg{attributes}{This parameter is not used in the current implementation}
7501 The function \texttt{cvStartWriteStruct} starts writing a compound
7502 structure (collection) that can be a sequence or a map. After all
7503 the structure fields, which can be scalars or structures, are
7504 written, \cross{EndWriteStruct} should be called. The function can
7505 be used to group some objects or to implement the \texttt{write}
7506 function for a some user object (see \cross{CvTypeInfo}).
7508 \cvfunc{EndWriteStruct}\label{EndWriteStruct}
7510 Ends the writing of a structure.
7514 void cvEndWriteStruct( CvFileStorage* fs );
7519 \cvarg{fs}{File storage}
7523 The function \texttt{cvEndWriteStruct} finishes the currently written structure.
7525 \cvfunc{WriteInt}\label{WriteInt}
7527 Writes an integer value.
7531 void cvWriteInt( \par CvFileStorage* fs,\par const char* name,\par int value );
7536 \cvarg{fs}{File storage}
7537 \cvarg{name}{Name of the written value. Should be NULL if and only if the parent structure is a sequence.}
7538 \cvarg{value}{The written value}
7541 The function \texttt{cvWriteInt} writes a single integer value (with or without a name) to the file storage.
7543 \cvfunc{WriteReal}\label{WriteReal}
7545 Writes a floating-point value.
7549 void cvWriteReal( \par CvFileStorage* fs,\par const char* name,\par double value );
7554 \cvarg{fs}{File storage}
7555 \cvarg{name}{Name of the written value. Should be NULL if and only if the parent structure is a sequence.}
7556 \cvarg{value}{The written value}
7559 The function \texttt{cvWriteReal} writes a single floating-point
7560 value (with or without a name) to file storage. Special
7561 values are encoded as follows: NaN (Not A Number) as .NaN, $ \pm \infty $ as +.Inf
7564 The following example shows how to use the low-level writing functions
7565 to store custom structures, such as termination criteria, without
7566 registering a new type.
7570 void write_termcriteria( CvFileStorage* fs, const char* struct_name,
7571 CvTermCriteria* termcrit )
7573 cvStartWriteStruct( fs, struct_name, CV_NODE_MAP, NULL, cvAttrList(0,0));
7574 cvWriteComment( fs, "termination criteria", 1 ); // just a description
7575 if( termcrit->type & CV_TERMCRIT_ITER )
7576 cvWriteInteger( fs, "max_iterations", termcrit->max_iter );
7577 if( termcrit->type & CV_TERMCRIT_EPS )
7578 cvWriteReal( fs, "accuracy", termcrit->epsilon );
7579 cvEndWriteStruct( fs );
7584 \cvfunc{WriteString}\label{WriteString}
7586 Writes a text string.
7590 void cvWriteString( \par CvFileStorage* fs,\par const char* name,\par const char* str,\par int quote=0 );
7595 \cvarg{fs}{File storage}
7596 \cvarg{name}{Name of the written string . Should be NULL if and only if the parent structure is a sequence.}
7597 \cvarg{str}{The written text string}
7598 \cvarg{quote}{If non-zero, the written string is put in quotes, regardless of whether they are required. 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).}
7601 The function \texttt{cvWriteString} writes a text string to file storage.
7603 \cvfunc{WriteComment}\label{WriteComment}
7609 void cvWriteComment( \par CvFileStorage* fs,\par const char* comment,\par int eol\_comment );
7614 \cvarg{fs}{File storage}
7615 \cvarg{comment}{The written comment, single-line or multi-line}
7616 \cvarg{eol\_comment}{If non-zero, the function tries to put the comment at the end of current line. If the flag is zero, if the comment is multi-line, or if it does not fit at the end of the current line, the comment starts a new line.}
7619 The function \texttt{cvWriteComment} writes a comment into file storage. The comments are skipped when the storage is read, so they may be used only for debugging or descriptive purposes.
7621 \cvfunc{StartNextStream}\label{StartNextStream}
7623 Starts the next stream.
7627 void cvStartNextStream( CvFileStorage* fs );
7632 \cvarg{fs}{File storage}
7636 The function \texttt{cvStartNextStream} starts the next stream in file storage. Both YAML and XML support multiple "streams." This is useful for concatenating files or for resuming the writing process.
7639 \cvfunc{Write}\label{Write}
7641 Writes a user object.
7645 void cvWrite( CvFileStorage* fs,\par const char* name,\par const void* ptr,\par CvAttrList attributes=cvAttrList( \par) );
7650 \cvarg{fs}{File storage}
7651 \cvarg{name}{Name of the written object. Should be NULL if and only if the parent structure is a sequence.}
7652 \cvarg{ptr}{Pointer to the object}
7653 \cvarg{attributes}{The attributes of the object. They are specific for each particular type (see the dicsussion below).}
7656 The function \texttt{cvWrite} writes an object to file storage. First, the appropriate type info is found using \cross{TypeOf}. Then, the \texttt{write} method associated with the type info is called.
7658 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}):
7662 \cvarg{header\_dt}{description of user fields of the sequence header that follow CvSeq, or CvChain (if the sequence is a Freeman chain) or CvContour (if the sequence is a contour or point sequence)}
7663 \cvarg{dt}{description of the sequence elements.}
7664 \cvarg{recursive}{if the attribute is present and is not equal to "0" or "false", the whole tree of sequences (contours) is stored.}
7668 \cvarg{header\_dt}{description of user fields of the graph header that follows CvGraph;}
7669 \cvarg{vertex\_dt}{description of user fields of graph vertices}
7670 \cvarg{edge\_dt}{description of user fields of graph edges (note that the edge weight is always written, so there is no need to specify it explicitly)}
7673 Below is the code that creates the YAML file shown in the \texttt{CvFileStorage} description:
7679 int main( int argc, char** argv )
7681 CvMat* mat = cvCreateMat( 3, 3, CV\_32F );
7682 CvFileStorage* fs = cvOpenFileStorage( "example.yml", 0, CV\_STORAGE\_WRITE );
7684 cvSetIdentity( mat );
7685 cvWrite( fs, "A", mat, cvAttrList(0,0) );
7687 cvReleaseFileStorage( &fs );
7688 cvReleaseMat( &mat );
7695 \cvfunc{WriteRawData}\label{WriteRawData}
7697 Writes multiple numbers.
7701 void cvWriteRawData( \par CvFileStorage* fs,\par const void* src,\par int len,\par const char* dt );
7706 \cvarg{fs}{File storage}
7707 \cvarg{src}{Pointer to the written array}
7708 \cvarg{len}{Number of the array elements to write}
7709 \cvarg{dt}{Specification of each array element that has the following format \newline
7710 \texttt{([count]\{'u'|'c'|'w'|'s'|'i'|'f'|'d'\})...}
7711 where the characters correspond to fundamental C types:
7713 \cvarg{u}{8-bit unsigned number}
7714 \cvarg{c}{8-bit signed number}
7715 \cvarg{w}{16-bit unsigned number}
7716 \cvarg{s}{16-bit signed number}
7717 \cvarg{i}{32-bit signed number}
7718 \cvarg{f}{single precision floating-point number}
7719 \cvarg{d}{double precision floating-point number}
7720 \cvarg{r}{pointer, 32 lower bits of which are written as a signed integer. The type can be used to store structures with links between the elements.
7721 \texttt{count} is the optional counter of values of a given type. For
7722 example, \texttt{2if} means that each array element is a structure
7723 of 2 integers, followed by a single-precision floating-point number. The
7724 equivalent notations of the above specification are '\texttt{iif}',
7725 '\texttt{2i1f}' and so forth. Other examples: \texttt{u} means that the
7726 array consists of bytes, and \texttt{2d} means the array consists of pairs
7731 The function \texttt{cvWriteRawData} writes an array, whose elements consist
7732 of single or multiple numbers. The function call can be replaced with
7733 a loop containing a few \cross{WriteInt} and \cross{WriteReal} calls, but
7734 a single call is more efficient. Note that because none of the elements
7735 have a name, they should be written to a sequence rather than a map.
7737 \cvfunc{WriteFileNode}\label{WriteFileNode}
7739 Writes a file node to another file storage.
7743 void cvWriteFileNode( \par CvFileStorage* fs,\par const char* new\_node\_name,\par const CvFileNode* node,\par int embed );
7748 \cvarg{fs}{Destination file storage}
7749 \cvarg{new\_file\_node}{New name of the file node in the destination file storage. To keep the existing name, use \cross{cvGetFileNodeName}}
7750 \cvarg{node}{The written node}
7751 \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 a map, and sequence elements may be written only to a sequence.}
7754 The function \texttt{cvWriteFileNode} writes a copy of a file node to file storage. Possible applications of the function are merging several file storages into one and conversion between XML and YAML formats.
7756 \subsection{Reading Data}
7758 Data are retrieved from file storage in 2 steps: first, the file node
7759 containing the requested data is found; then, data is extracted from
7760 the node manually or using a custom \texttt{read} method.
7762 \cvfunc{GetRootFileNode}\label{GetRootFileNode}
7764 Retrieves one of the top-level nodes of the file storage.
7768 CvFileNode* cvGetRootFileNode( \par const CvFileStorage* fs,\par int stream\_index=0 );
7773 \cvarg{fs}{File storage}
7774 \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.}
7777 The function \texttt{cvGetRootFileNode} returns one of the top-level file
7778 nodes. The top-level nodes do not have a name, they correspond to the
7779 streams that are stored one after another in the file storage. If the
7780 index is out of range, the function returns a NULL pointer, so all the
7781 top-level nodes may be iterated by subsequent calls to the function with
7782 \texttt{stream\_index=0,1,...}, until the NULL pointer is returned. This function
7783 may be used as a base for recursive traversal of the file storage.
7785 \cvfunc{GetFileNodeByName}\label{GetFileNodeByName}
7787 Finds a node in a map or file storage.
7791 CvFileNode* cvGetFileNodeByName( \par const CvFileStorage* fs,\par const CvFileNode* map,\par const char* name );
7796 \cvarg{fs}{File storage}
7797 \cvarg{map}{The parent map. If it is NULL, the function searches in all the top-level nodes (streams), starting with the first one.}
7798 \cvarg{name}{The file node name}
7802 The function \texttt{cvGetFileNodeByName} finds a file node by
7803 \texttt{name}. The node is searched either in \texttt{map} or, if the
7804 pointer is NULL, among the top-level file storage nodes. Using
7805 this function for maps and \cross{GetSeqElem} (or sequence reader)
7806 for sequences, it is possible to nagivate through the file storage. To
7807 speed up multiple queries for a certain key (e.g., in the case of an array
7808 of structures) one may use a combination of \cross{GetHashedKey} and
7809 \cross{GetFileNode}.
7811 \cvfunc{GetHashedKey}\label{GetHashedKey}
7813 Returns a unique pointer for a given name.
7817 CvStringHashNode* cvGetHashedKey( \par CvFileStorage* fs,\par const char* name,\par int len=-1,\par int create\_missing=0 );
7822 \cvarg{fs}{File storage}
7823 \cvarg{name}{Literal node name}
7824 \cvarg{len}{Length of the name (if it is known apriori), or -1 if it needs to be calculated}
7825 \cvarg{create\_missing}{Flag that specifies, whether an absent key should be added into the hash table}
7828 The function \texttt{cvGetHashedKey} returns a unique pointer for
7829 each particular file node name. This pointer can be then passed to the
7830 \cross{GetFileNode} function that is faster than \cross{GetFileNodeByName}
7831 because it compares text strings by comparing pointers rather than the
7834 Consider the following example where an array of points is encoded as a sequence of 2-entry maps:
7847 Then, it is possible to get hashed "x" and "y" pointers to speed up decoding of the points.
7848 \cvfunc{Example: Reading an array of structures from file storage}
7854 int main( int argc, char** argv )
7856 CvFileStorage* fs = cvOpenFileStorage( "points.yml", 0, CV\_STORAGE\_READ );
7857 CvStringHashNode* x\_key = cvGetHashedNode( fs, "x", -1, 1 );
7858 CvStringHashNode* y\_key = cvGetHashedNode( fs, "y", -1, 1 );
7859 CvFileNode* points = cvGetFileNodeByName( fs, 0, "points" );
7861 if( CV\_NODE\_IS\_SEQ(points->tag) )
7863 CvSeq* seq = points->data.seq;
7864 int i, total = seq->total;
7866 cvStartReadSeq( seq, &reader, 0 );
7867 for( i = 0; i < total; i++ )
7869 CvFileNode* pt = (CvFileNode*)reader.ptr;
7870 #if 1 /* faster variant */
7871 CvFileNode* xnode = cvGetFileNode( fs, pt, x\_key, 0 );
7872 CvFileNode* ynode = cvGetFileNode( fs, pt, y\_key, 0 );
7873 assert( xnode && CV\_NODE\_IS\_INT(xnode->tag) &&
7874 ynode && CV\_NODE\_IS\_INT(ynode->tag));
7875 int x = xnode->data.i; // or x = cvReadInt( xnode, 0 );
7876 int y = ynode->data.i; // or y = cvReadInt( ynode, 0 );
7877 #elif 1 /* slower variant; does not use x\_key & y\_key */
7878 CvFileNode* xnode = cvGetFileNodeByName( fs, pt, "x" );
7879 CvFileNode* ynode = cvGetFileNodeByName( fs, pt, "y" );
7880 assert( xnode && CV\_NODE\_IS\_INT(xnode->tag) &&
7881 ynode && CV\_NODE\_IS\_INT(ynode->tag));
7882 int x = xnode->data.i; // or x = cvReadInt( xnode, 0 );
7883 int y = ynode->data.i; // or y = cvReadInt( ynode, 0 );
7884 #else /* the slowest yet the easiest to use variant */
7885 int x = cvReadIntByName( fs, pt, "x", 0 /* default value */ );
7886 int y = cvReadIntByName( fs, pt, "y", 0 /* default value */ );
7888 CV\_NEXT\_SEQ\_ELEM( seq->elem\_size, reader );
7889 printf("%d: (%d, %d)\n", i, x, y );
7892 cvReleaseFileStorage( &fs );
7898 Please note that whatever method of accessing a map you are using, it is
7899 still much slower than using plain sequences; for example, in the above
7900 example, it is more efficient to encode the points as pairs of integers
7901 in a single numeric sequence.
7903 \cvfunc{GetFileNode}\label{GetFileNode}
7905 Finds a node in a map or file storage.
7909 CvFileNode* cvGetFileNode( \par CvFileStorage* fs,\par CvFileNode* map,\par const CvStringHashNode* key,\par int create\_missing=0 );
7914 \cvarg{fs}{File storage}
7915 \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.}
7916 \cvarg{key}{Unique pointer to the node name, retrieved with \cross{GetHashedKey}}
7917 \cvarg{create\_missing}{Flag that specifies whether an absent node should be added to the map}
7921 The function \texttt{cvGetFileNode} finds a file node. It is a faster version of \cross{GetFileNodeByName} (see \cross{GetHashedKey} discussion). Also, the function can insert a new node, if it is not in the map yet.
7923 \cvfunc{GetFileNodeName}\label{GetFileNodeName}
7925 Returns the name of a file node.
7929 const char* cvGetFileNodeName( const CvFileNode* node );
7934 \cvarg{node}{File node}
7938 The function \texttt{cvGetFileNodeName} returns the name of a file node or NULL, if the file node does not have a name or if \texttt{node} is \texttt{NULL}.
7941 \cvfunc{ReadInt}\label{ReadInt}
7943 Retrieves an integer value from a file node.
7947 int cvReadInt( \par const CvFileNode* node,\par int default\_value=0 );
7952 \cvarg{node}{File node}
7953 \cvarg{default\_value}{The value that is returned if \texttt{node} is NULL}
7957 The function \texttt{cvReadInt} returns an integer that is represented
7958 by the file node. If the file node is NULL, the \texttt{default\_value}
7959 is returned (thus, it is convenient to call the function right after
7960 \cross{GetFileNode} without checking for a NULL pointer). If
7961 the file node has type \texttt{CV\_NODE\_INT}, then \texttt{node->data.i} is
7962 returned. If the file node has type \texttt{CV\_NODE\_REAL},
7963 then \texttt{node->data.f} is converted to an integer and returned. Otherwise the
7964 result is not determined.
7966 \cvfunc{ReadIntByName}\label{ReadIntByName}
7968 Finds a file node and returns its value.
7972 int cvReadIntByName( \par const CvFileStorage* fs,\par const CvFileNode* map,\par const char* name,\par int default\_value=0 );
7977 \cvarg{fs}{File storage}
7978 \cvarg{map}{The parent map. If it is NULL, the function searches a top-level node.}
7979 \cvarg{name}{The node name}
7980 \cvarg{default\_value}{The value that is returned if the file node is not found}
7983 The function \texttt{cvReadIntByName} is a simple superposition of \cross{GetFileNodeByName} and \cross{ReadInt}.
7986 \cvfunc{ReadReal}\label{ReadReal}
7988 Retrieves a floating-point value from a file node.
7992 double cvReadReal( \par const CvFileNode* node,\par double default\_value=0. );
7997 \cvarg{node}{File node}
7998 \cvarg{default\_value}{The value that is returned if \texttt{node} is NULL}
8001 The function \texttt{cvReadReal} returns a floating-point value
8002 that is represented by the file node. If the file node is NULL, the
8003 \texttt{default\_value} is returned (thus, it is convenient to call
8004 the function right after \cross{GetFileNode} without checking for a NULL
8005 pointer). If the file node has type \texttt{CV\_NODE\_REAL},
8006 then \texttt{node->data.f} is returned. If the file node has type
8007 \texttt{CV\_NODE\_INT}, then \texttt{node-$>$data.f} is converted to floating-point
8008 and returned. Otherwise the result is not determined.
8010 \cvfunc{ReadRealByName}\label{ReadRealByName}
8012 Finds a file node and returns its value.
8016 double cvReadRealByName( \par const CvFileStorage* fs,\par const CvFileNode* map,\par const char* name,\par double default\_value=0. );
8021 \cvarg{fs}{File storage}
8022 \cvarg{map}{The parent map. If it is NULL, the function searches a top-level node.}
8023 \cvarg{name}{The node name}
8024 \cvarg{default\_value}{The value that is returned if the file node is not found}
8027 The function \texttt{cvReadRealByName} is a simple superposition of \cross{GetFileNodeByName} and \cross{ReadReal}.
8029 \cvfunc{ReadString}\label{ReadString}
8031 Retrieves a text string from a file node.
8035 const char* cvReadString( \par const CvFileNode* node,\par const char* default\_value=NULL );
8040 \cvarg{node}{File node}
8041 \cvarg{default\_value}{The value that is returned if \texttt{node} is NULL}
8044 The function \texttt{cvReadString} returns a text string that is represented
8045 by the file node. If the file node is NULL, the \texttt{default\_value}
8046 is returned (thus, it is convenient to call the function right after
8047 \cross{GetFileNode} without checking for a NULL pointer). If
8048 the file node has type \texttt{CV\_NODE\_STR}, then \texttt{node-$>$data.str.ptr}
8049 is returned. Otherwise the result is not determined.
8051 \cvfunc{ReadStringByName}\label{ReadStringByName}
8053 Finds a file node by its name and returns its value.
8057 const char* cvReadStringByName( \par const CvFileStorage* fs,\par const CvFileNode* map,\par const char* name,\par const char* default\_value=NULL );
8062 \cvarg{fs}{File storage}
8063 \cvarg{map}{The parent map. If it is NULL, the function searches a top-level node.}
8064 \cvarg{name}{The node name}
8065 \cvarg{default\_value}{The value that is returned if the file node is not found}
8068 The function \texttt{cvReadStringByName} is a simple superposition of \cross{GetFileNodeByName} and \cross{ReadString}.
8070 \cvfunc{Read}\label{Read}
8072 Decodes an object and returns a pointer to it.
8076 void* cvRead( \par CvFileStorage* fs,\par CvFileNode* node,\par CvAttrList* attributes=NULL );
8081 \cvarg{fs}{File storage}
8082 \cvarg{node}{The root object node}
8083 \cvarg{attributes}{Unused parameter}
8086 The function \texttt{cvRead} decodes a user object (creates an object in a
8087 native representation from the file storage subtree) and returns it. The
8088 object to be decoded must be an instance of a registered type that supports the
8089 \texttt{read} method (see \cross{CvTypeInfo}). The type of the object is
8090 determined by the type name that is encoded in the file. If the object
8091 is a dynamic structure, it is created either in memory storage and passed to
8092 \cross{OpenFileStorage} or, if a NULL pointer was passed, in temporary
8093 memory storage, which is released when \cross{ReleaseFileStorage} is
8094 called. Otherwise, if the object is not a dynamic structure, it is
8095 created in a heap and should be released with a specialized function or by
8096 using the generic \cross{Release}.
8098 \cvfunc{ReadByName}\label{ReadByName}
8100 Finds an object by name and decodes it.
8104 void* cvReadByName( \par CvFileStorage* fs,\par const CvFileNode* map,\par const char* name,\par CvAttrList* attributes=NULL );
8109 \cvarg{fs}{File storage}
8110 \cvarg{map}{The parent map. If it is NULL, the function searches a top-level node.}
8111 \cvarg{name}{The node name}
8112 \cvarg{attributes}{Unused parameter}
8115 The function \texttt{cvReadByName} is a simple superposition of \cross{GetFileNodeByName} and \cross{Read}.
8117 \cvfunc{ReadRawData}\label{ReadRawData}
8119 Reads multiple numbers.
8123 void cvReadRawData( \par const CvFileStorage* fs,\par const CvFileNode* src,\par void* dst,\par const char* dt );
8128 \cvarg{fs}{File storage}
8129 \cvarg{src}{The file node (a sequence) to read numbers from}
8130 \cvarg{dst}{Pointer to the destination array}
8131 \cvarg{dt}{Specification of each array element. It has the same format as in \cross{WriteRawData}.}
8134 The function \texttt{cvReadRawData} reads elements from a file node that represents a sequence of scalars.
8136 \cvfunc{StartReadRawData}\label{StartReadRawData}
8138 Initializes the file node sequence reader.
8142 void cvStartReadRawData( \par const CvFileStorage* fs,\par const CvFileNode* src,\par CvSeqReader* reader );
8147 \cvarg{fs}{File storage}
8148 \cvarg{src}{The file node (a sequence) to read numbers from}
8149 \cvarg{reader}{Pointer to the sequence reader}
8152 The function \texttt{cvStartReadRawData} initializes the sequence reader to read data from a file node. The initialized reader can be then passed to \cross{ReadRawDataSlice}.
8154 \cvfunc{ReadRawDataSlice}\label{ReadRawDataSlice}
8156 Initializes file node sequence reader.
8160 void cvReadRawDataSlice( \par const CvFileStorage* fs,\par CvSeqReader* reader,\par int count,\par void* dst,\par const char* dt );
8165 \cvarg{fs}{File storage}
8166 \cvarg{reader}{The sequence reader. Initialize it with \cross{StartReadRawData}.}
8167 \cvarg{count}{The number of elements to read}
8168 \cvarg{dst}{Pointer to the destination array}
8169 \cvarg{dt}{Specification of each array element. It has the same format as in \cross{WriteRawData}.}
8172 The function \texttt{cvReadRawDataSlice} reads one or more elements from
8173 the file node, representing a sequence, to a user-specified array. The
8174 total number of read sequence elements is a product of \texttt{total}
8175 and the number of components in each array element. For example, if
8176 dt=\texttt{2if}, the function will read $\texttt{total} \times 3$
8177 sequence elements. As with any sequence, some parts of the file node
8178 sequence may be skipped or read repeatedly by repositioning the reader
8179 using \cross{SetSeqReaderPos}.
8183 \subsection{RTTI and Generic Functions}
8186 \cvstruct{CvTypeInfo}\label{CvTypeInfo}
8192 typedef int (CV_CDECL *CvIsInstanceFunc)( const void* struct_ptr );
8193 typedef void (CV_CDECL *CvReleaseFunc)( void** struct_dblptr );
8194 typedef void* (CV_CDECL *CvReadFunc)( CvFileStorage* storage, CvFileNode* node );
8195 typedef void (CV_CDECL *CvWriteFunc)( CvFileStorage* storage,
8197 const void* struct_ptr,
8198 CvAttrList attributes );
8199 typedef void* (CV_CDECL *CvCloneFunc)( const void* struct_ptr );
8201 typedef struct CvTypeInfo
8203 int flags; /* not used */
8204 int header_size; /* sizeof(CvTypeInfo) */
8205 struct CvTypeInfo* prev; /* previous registered type in the list */
8206 struct CvTypeInfo* next; /* next registered type in the list */
8207 const char* type_name; /* type name, written to file storage */
8210 CvIsInstanceFunc is_instance; /* checks if the passed object belongs to the type */
8211 CvReleaseFunc release; /* releases object (memory etc.) */
8212 CvReadFunc read; /* reads object from file storage */
8213 CvWriteFunc write; /* writes object to file storage */
8214 CvCloneFunc clone; /* creates a copy of the object */
8220 The structure \cross{CvTypeInfo} contains information about one of the
8221 standard or user-defined types. Instances of the type may or may not
8222 contain a pointer to the corresponding \cross{CvTypeInfo} structure. In
8223 any case, there is a way to find the type info structure for a given object
8224 using the \cross{TypeOf} function. Aternatively, type info can be found by
8225 type name using \cross{FindType}, which is used when an object is read
8226 from file storage. The user can register a new type with \cross{RegisterType}
8227 that adds the type information structure into the beginning of the type
8228 list. Thus, it is possible to create specialized types from generic
8229 standard types and override the basic methods.
8231 \cvfunc{RegisterType}\label{RegisterType}
8233 Registers a new type.
8237 void cvRegisterType( const CvTypeInfo* info );
8242 \cvarg{info}{Type info structure}
8245 The function \texttt{cvRegisterType} registers a new type, which is
8246 described by \texttt{info}. The function creates a copy of the structure,
8247 so the user should delete it after calling the function.
8249 \cvfunc{UnregisterType}\label{UnregisterType}
8251 Unregisters the type.
8255 void cvUnregisterType( const char* type\_name );
8260 \cvarg{type\_name}{Name of an unregistered type}
8263 The function \texttt{cvUnregisterType} unregisters a type with
8264 a specified name. If the name is unknown, it is possible to locate
8265 the type info by an instance of the type using \cross{TypeOf} or by
8266 iterating the type list, starting from \cross{FirstType}, and then calling
8267 \texttt{cvUnregisterType(info->type\_name)}.
8269 \cvfunc{FirstType}\label{FirstType}
8271 Returns the beginning of a type list.
8275 CvTypeInfo* cvFirstType( void );
8279 The function \texttt{cvFirstType} returns the first type in the list of registered types. Navigation through the list can be done via the \texttt{prev} and \texttt{next} fields of the \cross{CvTypeInfo} structure.
8281 \cvfunc{FindType}\label{FindType}
8283 Finds a type by its name.
8287 CvTypeInfo* cvFindType( const char* type\_name );
8292 \cvarg{type\_name}{Type name}
8295 The function \texttt{cvFindType} finds a registered type by its name. It returns NULL if there is no type with the specified name.
8298 \cvfunc{TypeOf}\label{TypeOf}
8300 Returns the type of an object.
8304 CvTypeInfo* cvTypeOf( const void* struct\_ptr );
8309 \cvarg{struct\_ptr}{The object pointer}
8312 The function \texttt{cvTypeOf} finds the type of a given object. It iterates
8313 through the list of registered types and calls the \texttt{is\_instance}
8314 function/method for every type info structure with that object until one
8315 of them returns non-zero or until the whole list has been traversed. In
8316 the latter case, the function returns NULL.
8318 \cvfunc{Release}\label{Release}
8324 void cvRelease( void** struct\_ptr );
8329 \cvarg{struct\_ptr}{Double pointer to the object}
8332 The function \texttt{cvRelease} finds the type of a given object and calls \texttt{release} with the double pointer.
8334 \cvfunc{Clone}\label{Clone}
8336 Makes a clone of an object.
8340 void* cvClone( const void* struct\_ptr );
8345 \cvarg{struct\_ptr}{The object to clone}
8348 The function \texttt{cvClone} finds the type of a given object and calls \texttt{clone} with the passed object.
8352 \cvfunc{Save}\label{Save}
8354 Saves an object to a file.
8358 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());
8360 }{CPP}{Save(filename,struct\_ptr,name=NULL,comment=NULL)-> None}
8363 \cvarg{filename}{File name}
8364 \cvarg{struct\_ptr}{Object to save}
8365 \cvarg{name}{Optional object name. If it is NULL, the name will be formed from \texttt{filename}.}
8366 \cvarg{comment}{Optional comment to put in the beginning of the file}
8367 \cvC{\cvarg{attributes}{Optional attributes passed to \cross{Write}}}
8370 The function \texttt{cvSave} saves an object to a file. It provides a simple interface to \cross{Write}.
8372 \cvfunc{Load}\label{Load}
8374 Loads an object from a file.
8378 void* cvLoad( \par const char* filename,\par CvMemStorage* memstorage=NULL,\par const char* name=NULL,\par const char** real\_name=NULL );
8380 }{CPP}{Load(filename,storage=NULL,name=NULL)-> generic}
8383 \cvarg{filename}{File name}
8384 \cvarg{memstorage}{Memory storage for dynamic structures, such as \cross{CvSeq} or \cross{CvGraph} . It is not used for matrices or images.}
8385 \cvarg{name}{Optional object name. If it is NULL, the first top-level object in the storage will be loaded.}
8386 \cvC{\cvarg{real\_name}{Optional output parameter that will contain the name of the loaded object (useful if \texttt{name=NULL})}}
8389 The function \texttt{cvLoad} loads an object from a file. It provides a
8390 simple interface to \cross{Read}. After the object is loaded, the file
8391 storage is closed and all the temporary buffers are deleted. Thus,
8392 to load a dynamic structure, such as a sequence, contour, or graph, one
8393 should pass a valid memory storage destination to the function.
8395 \section{Miscellaneous Functions}
8397 \subsection{Miscellaneous Functions}
8399 \cvfunc{CheckArr}\label{CheckArr}
8401 Checks every element of an input array for invalid values.
8405 int cvCheckArr( \par const CvArr* arr,\par int flags=0,\par double min\_val=0,\par double max\_val=0);
8407 }{CPP}{CheckArr(arr,flags=0,min\_val=0,max\_val=0)-> int}
8411 #define cvCheckArray cvCheckArr
8416 \cvarg{arr}{The array to check}
8417 \cvarg{flags}{The operation flags, 0 or combination of:
8419 \cvarg{CV\_CHECK\_RANGE}{if set, the function checks that every value of the array is within [minVal,maxVal), otherwise it just checks that every element is neither NaN nor $\pm \infty$.}
8420 \cvarg{CV\_CHECK\_QUIET}{if set, the function does not raise an error if an element is invalid or out of range}
8422 \cvarg{min\_val}{The inclusive lower boundary of valid values range. It is used only if \texttt{CV\_CHECK\_RANGE} is set.}
8423 \cvarg{max\_val}{The exclusive upper boundary of valid values range. It is used only if \texttt{CV\_CHECK\_RANGE} is set.}
8426 The function \texttt{cvCheckArr} checks that every array element is
8427 neither NaN nor $ \pm \infty $.
8428 If \texttt{CV\_CHECK\_RANGE} is set, it also
8429 checks that every element is greater than or equal to \texttt{minVal}
8430 and less than \texttt{maxVal}. The function returns nonzero if the
8431 check succeeded, i.e., all elements are valid and within the range,
8432 and it returns zero otherwise. In the latter case, if the \texttt{CV\_CHECK\_QUIET}
8433 flag is not set, the function raises a runtime error.
8435 \cvfunc{KMeans2}\label{KMeans2}
8437 Splits set of vectors by a given number of clusters.
8440 void cvKMeans2( \par const CvArr* samples,\par int cluster\_count,\par CvArr* labels,\par CvTermCriteria termcrit );
8441 }{CPP}{KMeans2(samples,cluster\_count,labels,termcrit)-> None}
8444 \cvarg{samples}{Floating-point matrix of input samples, one row per sample}
8445 \cvarg{cluster\_count}{Number of clusters to split the set by}
8446 \cvarg{labels}{Output integer vector storing cluster indices for every sample}
8447 \cvarg{termcrit}{Specifies maximum number of iterations and/or accuracy (distance the centers can move by between subsequent iterations)}
8449 \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)}
8450 \cvarg{rng}{Optional external random number generator; can be used to fully control the function behaviour}
8451 \cvarg{flags}{Can be 0 or \texttt{CV\_KMEANS\_USE\_INITIAL\_LABELS}. The latter
8452 value means that during the first (and possibly the only) attempt, the
8453 function uses the user-supplied labels as the initial approximation
8454 instead of generating random labels. For the second and further attempts,
8455 the function will use randomly generated labels in any case}
8456 \cvarg{centers}{The optional output array of the cluster centers}
8457 \cvarg{compactness}{The optional output parameter, which is computed as
8459 \sum_i ||\texttt{samples}_i - \texttt{centers}_{\texttt{labels}_i}||^2
8461 after every attempt; the best (minimum) value is chosen and the
8462 corresponding labels are returned by the function. Basically, the
8463 user can use only the core of the function, set the number of
8464 attempts to 1, initialize labels each time using a custom algorithm
8465 \newline (\texttt{flags}=\texttt{CV\_KMEAN\_USE\_INITIAL\_LABELS}) and, based on the output compactness
8466 or any other criteria, choose the best clustering.}
8470 The function \texttt{cvKMeans2} implements a k-means algorithm that finds the
8471 centers of \texttt{cluster\_count} clusters and groups the input samples
8472 around the clusters. On output, $\texttt{labels}_i$ contains a cluster index for
8473 samples stored in the row $i$ of the \texttt{samples} matrix.
8476 \cvfunc{Example: Clustering random samples of multi-gaussian distribution with k-means}
8479 #include "highgui.h"
8481 void main( int argc, char** argv )
8483 #define MAX_CLUSTERS 5
8484 CvScalar color_tab[MAX_CLUSTERS];
8485 IplImage* img = cvCreateImage( cvSize( 500, 500 ), 8, 3 );
8486 CvRNG rng = cvRNG(0xffffffff);
8488 color_tab[0] = CV_RGB(255,0,0);
8489 color_tab[1] = CV_RGB(0,255,0);
8490 color_tab[2] = CV_RGB(100,100,255);
8491 color_tab[3] = CV_RGB(255,0,255);
8492 color_tab[4] = CV_RGB(255,255,0);
8494 cvNamedWindow( "clusters", 1 );
8498 int k, cluster_count = cvRandInt(&rng)%MAX_CLUSTERS + 1;
8499 int i, sample_count = cvRandInt(&rng)%1000 + 1;
8500 CvMat* points = cvCreateMat( sample_count, 1, CV_32FC2 );
8501 CvMat* clusters = cvCreateMat( sample_count, 1, CV_32SC1 );
8503 /* generate random sample from multigaussian distribution */
8504 for( k = 0; k < cluster_count; k++ )
8508 center.x = cvRandInt(&rng)%img->width;
8509 center.y = cvRandInt(&rng)%img->height;
8512 k*sample_count/cluster_count,
8513 (k == (cluster_count - 1)) ?
8515 (k+1)*sample_count/cluster_count );
8516 cvRandArr( &rng, &point_chunk, CV_RAND_NORMAL,
8517 cvScalar(center.x,center.y,0,0),
8518 cvScalar(img->width/6, img->height/6,0,0) );
8521 /* shuffle samples */
8522 for( i = 0; i < sample_count/2; i++ )
8525 (CvPoint2D32f*)points->data.fl + cvRandInt(&rng)%sample_count;
8527 (CvPoint2D32f*)points->data.fl + cvRandInt(&rng)%sample_count;
8529 CV_SWAP( *pt1, *pt2, temp );
8532 cvKMeans2( points, cluster_count, clusters,
8533 cvTermCriteria( CV_TERMCRIT_EPS+CV_TERMCRIT_ITER, 10, 1.0 ));
8537 for( i = 0; i < sample_count; i++ )
8539 CvPoint2D32f pt = ((CvPoint2D32f*)points->data.fl)[i];
8540 int cluster_idx = clusters->data.i[i];
8544 color_tab[cluster_idx],
8548 cvReleaseMat( &points );
8549 cvReleaseMat( &clusters );
8551 cvShowImage( "clusters", img );
8553 int key = cvWaitKey(0);
8563 \cvfunc{SeqPartition}\label{SeqPartition}
8565 Splits a sequence into equivalency classes.
8568 typedef int (CV_CDECL* CvCmpFunc)(const void* a, const void* b, void* userdata);
8572 int cvSeqPartition( \par const CvSeq* seq,\par CvMemStorage* storage,\par CvSeq** labels,\par CvCmpFunc is\_equal,\par void* userdata );
8576 \cvarg{seq}{The sequence to partition}
8577 \cvarg{storage}{The storage block to store the sequence of equivalency classes. If it is NULL, the function uses \texttt{seq->storage} for output labels}
8578 \cvarg{labels}{Ouput parameter. Double pointer to the sequence of 0-based labels of input sequence elements}
8579 \cvarg{is\_equal}{The relation function that should return non-zero if the two particular sequence elements are from the same class, and zero otherwise. The partitioning algorithm uses transitive closure of the relation function as an equivalency critria}
8580 \cvarg{userdata}{Pointer that is transparently passed to the \texttt{is\_equal} function}
8583 The function \texttt{cvSeqPartition} implements a quadratic algorithm for
8584 splitting a set into one or more equivalancy classes. The function
8585 returns the number of equivalency classes.
8587 \cvfunc{Example: Partitioning a 2d point set}
8591 #include "highgui.h"
8594 CvSeq* point_seq = 0;
8595 IplImage* canvas = 0;
8596 CvScalar* colors = 0;
8599 int is_equal( const void* _a, const void* _b, void* userdata )
8601 CvPoint a = *(const CvPoint*)_a;
8602 CvPoint b = *(const CvPoint*)_b;
8603 double threshold = *(double*)userdata;
8604 return (double)((a.x - b.x)*(a.x - b.x) + (a.y - b.y)*(a.y - b.y)) <=
8608 void on_track( int pos )
8611 double threshold = pos*pos;
8612 int i, class_count = cvSeqPartition( point_seq,
8617 printf("%4d classes\n", class_count );
8620 for( i = 0; i < labels->total; i++ )
8622 CvPoint pt = *(CvPoint*)cvGetSeqElem( point_seq, i, 0 );
8623 CvScalar color = colors[*(int*)cvGetSeqElem( labels, i, 0 )];
8624 cvCircle( canvas, pt, 1, color, -1 );
8627 cvShowImage( "points", canvas );
8630 int main( int argc, char** argv )
8632 CvMemStorage* storage = cvCreateMemStorage(0);
8633 point_seq = cvCreateSeq( CV_32SC2,
8637 CvRNG rng = cvRNG(0xffffffff);
8639 int width = 500, height = 500;
8640 int i, count = 1000;
8641 canvas = cvCreateImage( cvSize(width,height), 8, 3 );
8643 colors = (CvScalar*)cvAlloc( count*sizeof(colors[0]) );
8644 for( i = 0; i < count; i++ )
8648 pt.x = cvRandInt( &rng ) % width;
8649 pt.y = cvRandInt( &rng ) % height;
8650 cvSeqPush( point_seq, &pt );
8651 icolor = cvRandInt( &rng ) | 0x00404040;
8652 colors[i] = CV_RGB(icolor & 255,
8654 (icolor >> 16)&255);
8657 cvNamedWindow( "points", 1 );
8658 cvCreateTrackbar( "threshold", "points", &pos, 50, on_track );
8667 \section{Error Handling and System Functions}
8669 \subsection{Error Handling}
8672 Errors in argument type cause a \texttt{TypeError} exception.
8673 OpenCV errors cause a cv.error exception.
8677 Error handling in OpenCV is similar to IPL (Image Processing
8678 Library). In the case of an error, functions do not return the error
8679 code. Instead, they raise an error using \texttt{CV\_ERROR}
8680 macro that calls \cross{Error} that, in its turn, sets the error
8681 status with \cross{SetErrStatus} and calls a standard or user-defined
8682 error handler (that can display a message box, write to log, etc., see
8683 \cross{RedirectError}). There is a global variable, one per each program
8684 thread, that contains current error status (an integer value). The status
8685 can be retrieved with the \cross{GetErrStatus} function.
8687 There are three modes of error handling (see \cross{SetErrMode} and
8688 \cross{GetErrMode}):
8691 \cvarg{Leaf}{The program is terminated after the error handler is
8692 called. This is the default value. It is useful for debugging, as the
8693 error is signalled immediately after it occurs. However, for production
8694 systems, other two methods may be preferable as they provide more
8696 \cvarg{Parent}{The program is not terminated, but the error handler
8697 is called. The stack is unwound (it is done w/o using a C++ exception
8698 mechanism). The user may check error code after calling the \texttt{CxCore} function with
8699 \cross{GetErrStatus} and react.}
8700 \cvarg{Silent}{Similar to \texttt{Parent} mode, but no error handler
8704 Actually, the semantics of the \texttt{Leaf} and \texttt{Parent} modes are implemented by error handlers and the above description is true for them. \cross{GuiBoxReport} behaves slightly differently, and some custom error handlers may implement quite different semantics.
8706 \cvfunc{ERROR Handling Macros}\label{ERROR Handling Macros}
8708 Macros for raising an error, checking for errors, etc.
8712 /* special macros for enclosing processing statements within a function and separating
8713 them from prologue (resource initialization) and epilogue (guaranteed resource release) */
8715 #define __END__ goto exit; exit: ; }
8716 /* proceeds to "resource release" stage */
8717 #define EXIT goto exit
8719 /* Declares locally the function name for CV_ERROR() use */
8720 #define CV_FUNCNAME( Name ) \
8721 static char cvFuncName[] = Name
8723 /* Raises an error within the current context */
8724 #define CV_ERROR( Code, Msg ) \
8726 cvError( (Code), cvFuncName, Msg, __FILE__, __LINE__ ); \
8730 /* Checks status after calling CXCORE function */
8731 #define CV_CHECK() \
8733 if( cvGetErrStatus() < 0 ) \
8734 CV_ERROR( CV_StsBackTrace, "Inner function failed." ); \
8737 /* Provies shorthand for CXCORE function call and CV_CHECK() */
8738 #define CV_CALL( Statement ) \
8744 /* Checks some condition in both debug and release configurations */
8745 #define CV_ASSERT( Condition ) \
8747 if( !(Condition) ) \
8748 CV_ERROR( CV_StsInternal, "Assertion: " #Condition " failed" ); \
8751 /* these macros are similar to their CV_... counterparts, but they
8752 do not need exit label nor cvFuncName to be defined */
8753 #define OPENCV_ERROR(status,func_name,err_msg) ...
8754 #define OPENCV_ERRCHK(func_name,err_msg) ...
8755 #define OPENCV_ASSERT(condition,func_name,err_msg) ...
8756 #define OPENCV_CALL(statement) ...
8760 Instead of a discussion, below is a documented example of a typical CXCORE function and an example of the function use.
8762 \cvfunc{Example: Use of Error Handling Macros}
8768 void cvResizeDCT( CvMat* input_array, CvMat* output_array )
8770 CvMat* temp_array = 0; // declare pointer that should be released anyway.
8772 CV_FUNCNAME( "cvResizeDCT" ); // declare cvFuncName
8774 __BEGIN__; // start processing. There may be some declarations just after
8775 // this macro, but they could not be accessed from the epilogue.
8777 if( !CV_IS_MAT(input_array) || !CV_IS_MAT(output_array) )
8778 // use CV_ERROR() to raise an error
8779 CV_ERROR( CV_StsBadArg,
8780 "input_array or output_array are not valid matrices" );
8782 // some restrictions that are going to be removed later, may be checked
8784 CV_ASSERT( input_array->rows == 1 && output_array->rows == 1 );
8786 // use CV_CALL for safe function call
8787 CV_CALL( temp_array = cvCreateMat( input_array->rows,
8788 MAX(input_array->cols,
8789 output_array->cols),
8790 input_array->type ));
8792 if( output_array->cols > input_array->cols )
8793 CV_CALL( cvZero( temp_array ));
8795 temp_array->cols = input_array->cols;
8796 CV_CALL( cvDCT( input_array, temp_array, CV_DXT_FORWARD ));
8797 temp_array->cols = output_array->cols;
8798 CV_CALL( cvDCT( temp_array, output_array, CV_DXT_INVERSE ));
8799 CV_CALL( cvScale( output_array,
8801 1./sqrt((double)input_array->cols*output_array->cols), 0 ));
8803 __END__; // finish processing. Epilogue follows after the macro.
8805 // release temp_array. If temp_array has not been allocated
8806 // before an error occured, cvReleaseMat
8807 // takes care of it and does nothing in this case.
8808 cvReleaseMat( &temp_array );
8811 int main( int argc, char** argv )
8813 CvMat* src = cvCreateMat( 1, 512, CV_32F );
8814 #if 1 /* no errors */
8815 CvMat* dst = cvCreateMat( 1, 256, CV_32F );
8817 CvMat* dst = 0; /* test error processing mechanism */
8819 cvSet( src, cvRealScalar(1.), 0 );
8820 #if 0 /* change 0 to 1 to suppress error handler invocation */
8821 cvSetErrMode( CV_ErrModeSilent );
8823 cvResizeDCT( src, dst ); // if some error occurs, the message
8824 // box will popup, or a message will be
8825 // written to log, or some user-defined
8826 // processing will be done
8827 if( cvGetErrStatus() < 0 )
8828 printf("Some error occured" );
8830 printf("Everything is OK" );
8836 \cvfunc{GetErrStatus}\label{GetErrStatus}
8838 Returns the current error status.
8841 int cvGetErrStatus( void );
8844 The function \texttt{cvGetErrStatus} returns the current error status -
8845 the value set with the last \cross{SetErrStatus} call. Note that in
8846 \texttt{Leaf} mode, the program terminates immediately after an
8847 error occurs, so to always gain control after the function call,
8848 one should call \cross{SetErrMode} and set the \texttt{Parent}
8849 or \texttt{Silent} error mode.
8851 \cvfunc{SetErrStatus}\label{SetErrStatus}
8853 Sets the error status.
8856 void cvSetErrStatus( int status );
8860 \cvarg{status}{The error status}
8863 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 an error. In other cases it is more natural to call \cross{Error} or \texttt{CV\_ERROR}.
8865 \cvfunc{GetErrMode}\label{GetErrMode}
8867 Returns the current error mode.
8870 int cvGetErrMode( void );
8873 The function \texttt{cvGetErrMode} returns the current error mode - the value set with the last \cross{SetErrMode} call.
8875 \cvfunc{SetErrMode}\label{SetErrMode}
8877 Sets the error mode.
8880 #define CV_ErrModeLeaf 0
8881 #define CV_ErrModeParent 1
8882 #define CV_ErrModeSilent 2
8886 int cvSetErrMode( int mode );
8890 \cvarg{mode}{The error mode}
8893 The function \texttt{cvSetErrMode} sets the specified error mode. For descriptions of different error modes, see the beginning of the error section.
8895 \cvfunc{Error}\label{Error}
8900 int cvError( \par int status,\par const char* func\_name,\par const char* err\_msg,\par const char* file\_name,\par int line );
8904 \cvarg{status}{The error status}
8905 \cvarg{func\_name}{Name of the function where the error occured}
8906 \cvarg{err\_msg}{Additional information/diagnostics about the error}
8907 \cvarg{file\_name}{Name of the file where the error occured}
8908 \cvarg{line}{Line number, where the error occured}
8911 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.
8913 \cvfunc{ErrorStr}\label{ErrorStr}
8915 Returns textual description of an error status code.
8918 const char* cvErrorStr( int status );
8922 \cvarg{status}{The error status}
8925 The function \texttt{cvErrorStr} returns the textual description for
8926 the specified error status code. In the case of unknown status, the function
8927 returns a NULL pointer.
8929 \cvfunc{RedirectError}\label{RedirectError}
8931 Sets a new error handler.
8934 typedef int (CV_CDECL *CvErrorCallback)( int status, const char* func_name,
8935 const char* err_msg, const char* file_name, int line );
8939 CvErrorCallback cvRedirectError( \par CvErrorCallback error\_handler,\par void* userdata=NULL,\par void** prev\_userdata=NULL );
8943 \cvarg{error\_handler}{The new error\_handler}
8944 \cvarg{userdata}{Arbitrary pointer that is transparently passed to the error handler}
8945 \cvarg{prev\_userdata}{Pointer to the previously assigned user data pointer}
8948 The function \texttt{cvRedirectError} sets a new error handler that
8949 can be one of the standard handlers or a custom handler
8950 that has a specific interface. The handler takes the same parameters
8951 as the \cross{Error} function. If the handler returns a non-zero value, the
8952 program is terminated; otherwise, it continues. The error handler may
8953 check the current error mode with \cross{GetErrMode} to make a decision.
8956 \cvfunc{cvNulDevReport cvStdErrReport cvGuiBoxReport}
8957 \label{cvNulDevReport}
8958 \label{cvStdErrReport}
8959 \label{cvGuiBoxReport}
8961 Provide standard error handling.
8965 int cvNulDevReport( int status, const char* func_name,
8966 const char* err_msg, const char* file_name,
8967 int line, void* userdata );
8969 int cvStdErrReport( int status, const char* func_name,
8970 const char* err_msg, const char* file_name,
8971 int line, void* userdata );
8973 int cvGuiBoxReport( int status, const char* func_name,
8974 const char* err_msg, const char* file_name,
8975 int line, void* userdata );
8980 \cvarg{status}{The error status}
8981 \cvarg{func\_name}{Name of the function where the error occured}
8982 \cvarg{err\_msg}{Additional information/diagnostics about the error}
8983 \cvarg{file\_name}{Name of the file where the error occured}
8984 \cvarg{line}{Line number, where the error occured}
8985 \cvarg{userdata}{Pointer to the user data. Ignored by the standard handlers}
8988 The functions \texttt{cvNullDevReport}, \texttt{cvStdErrReport},
8989 and \texttt{cvGuiBoxReport} provide standard error
8990 handling. \texttt{cvGuiBoxReport} is the default error
8991 handler on Win32 systems, \texttt{cvStdErrReport} is the default on other
8992 systems. \texttt{cvGuiBoxReport} pops up a message box with the error
8993 description and suggest a few options. Below is an example message box
8994 that may be recieved with the sample code above, if one introduces an
8995 error as described in the sample.
8999 \includegraphics[width=0.5\textwidth]{pics/errmsg.png}
9001 If the error handler is set to \texttt{cvStdErrReport}, the above message will be printed to standard error output and the program will be terminated or continued, depending on the current error mode.
9003 Error Message printed to Standard Error Output (in \texttt{Leaf} mode)
9006 OpenCV ERROR: Bad argument (input_array or output_array are not valid matrices)
9007 in function cvResizeDCT, D:\User\VP\Projects\avl\_proba\a.cpp(75)
9008 Terminating the application...
9014 \subsection{System and Utility Functions}
9016 \cvfunc{Alloc}\label{Alloc}
9018 Allocates a memory buffer.
9021 void* cvAlloc( size\_t size );
9025 \cvarg{size}{Buffer size in bytes}
9028 The function \texttt{cvAlloc} allocates \texttt{size} bytes and returns
9029 a pointer to the allocated buffer. In the case of an error the function reports an
9030 error and returns a NULL pointer. By default, \texttt{cvAlloc} calls
9031 \texttt{icvAlloc} which
9032 itself calls \texttt{malloc}. However it is possible to assign user-defined memory
9033 allocation/deallocation functions using the \cross{SetMemoryManager} function.
9035 \cvfunc{Free}\label{Free}
9037 Deallocates a memory buffer.
9041 void cvFree( void** ptr );
9046 \cvarg{ptr}{Double pointer to released buffer}
9049 The function \texttt{cvFree} deallocates a memory buffer allocated by
9050 \cross{Alloc}. It clears the pointer to buffer upon exit, which is why
9051 the double pointer is used. If the \texttt{*buffer} is already NULL, the function
9054 \cvfunc{GetTickCount}\label{GetTickCount}
9056 Returns the number of ticks.
9059 int64 cvGetTickCount( void );
9062 The function \texttt{cvGetTickCount} returns number of the ticks starting from some platform-dependent event (number of CPU ticks from the startup, number of milliseconds from 1970th year, etc.). The function is useful for accurate measurement of a function/user-code execution time. To convert the number of ticks to time units, use \cross{GetTickFrequency}.
9064 \cvfunc{GetTickFrequency}\label{GetTickFrequency}
9066 Returns the number of ticks per microsecond.
9070 double cvGetTickFrequency( void );
9074 The function \texttt{cvGetTickFrequency} returns the number of ticks per microsecond. Thus, the quotient of \cross{GetTickCount} and \cross{GetTickFrequency} will give the number of microseconds starting from the platform-dependent event.
9076 \cvfunc{RegisterModule}\label{RegisterModule}
9078 Registers another module.
9081 typedef struct CvPluginFuncInfo
9084 void* default_func_addr;
9085 const char* func_names;
9091 typedef struct CvModuleInfo
9093 struct CvModuleInfo* next;
9095 const char* version;
9096 CvPluginFuncInfo* func_tab;
9102 int cvRegisterModule( const CvModuleInfo* module\_info );
9106 \cvarg{module\_info}{Information about the module}
9109 The function \texttt{cvRegisterModule} adds a module to the list of
9110 registered modules. After the module is registered, information about
9111 it can be retrieved using the \cross{GetModuleInfo} function. Also, the
9112 registered module makes full use of optimized plugins (IPP, MKL, ...),
9113 supported by CXCORE. CXCORE itself, CV (computer vision), CVAUX (auxilary
9114 computer vision), and HIGHGUI (visualization and image/video acquisition) are
9115 examples of modules. Registration is usually done when the shared library
9116 is loaded. See \texttt{cxcore/src/cxswitcher.cpp} and
9117 \texttt{cv/src/cvswitcher.cpp} for details about how registration is done
9118 and look at \texttt{cxcore/src/cxswitcher.cpp}, \texttt{cxcore/src/\_cxipp.h}
9119 on how IPP and MKL are connected to the modules.
9121 \cvfunc{GetModuleInfo}\label{GetModuleInfo}
9123 Retrieves information about registered module(s) and plugins.
9126 void cvGetModuleInfo( \par const char* module\_name,\par const char** version,\par const char** loaded\_addon\_plugins );
9130 \cvarg{module\_name}{Name of the module of interest, or NULL, which means all the modules}
9131 \cvarg{version}{The output parameter. Information about the module(s), including version}
9132 \cvarg{loaded\_addon\_plugins}{The list of names and versions of the optimized plugins that CXCORE was able to find and load}
9135 The function \texttt{cvGetModuleInfo} returns information about one or
9136 all of the registered modules. The returned information is stored inside
9137 the libraries, so the user should not deallocate or modify the returned
9140 \cvfunc{UseOptimized}\label{UseOptimized}
9142 Switches between optimized/non-optimized modes.
9146 int cvUseOptimized( int on\_off );
9151 \cvarg{on\_off}{Use optimized ($\ne 0$) or not ($=0$)}
9154 The function \texttt{cvUseOptimized} switches between the mode, where
9155 only pure C implementations from cxcore, OpenCV, etc. are used, and
9156 the mode, where IPP and MKL functions are used if available. When
9157 \texttt{cvUseOptimized(0)} is called, all the optimized libraries are
9158 unloaded. The function may be useful for debugging, IPP and MKL upgrading on
9159 the fly, online speed comparisons, etc. It returns the number of optimized
9160 functions loaded. Note that by default, the optimized plugins are loaded,
9161 so it is not necessary to call \texttt{cvUseOptimized(1)} in the beginning of
9162 the program (actually, it will only increase the startup time).
9164 \cvfunc{SetMemoryManager}\label{SetMemoryManager}
9166 Accesses custom/default memory managing functions.
9169 typedef void* (CV_CDECL *CvAllocFunc)(size_t size, void* userdata);
9170 typedef int (CV_CDECL *CvFreeFunc)(void* pptr, void* userdata);
9174 void cvSetMemoryManager( \par CvAllocFunc alloc\_func=NULL,\par CvFreeFunc free\_func=NULL,\par void* userdata=NULL );
9178 \cvarg{alloc\_func}{Allocation function; the interface is similar to \texttt{malloc}, except that \texttt{userdata} may be used to determine the context}
9179 \cvarg{free\_func}{Deallocation function; the interface is similar to \texttt{free}}
9180 \cvarg{userdata}{User data that is transparently passed to the custom functions}
9183 The function \texttt{cvSetMemoryManager} sets user-defined memory
9184 managment functions (substitutes for \texttt{malloc} and \texttt{free}) that will be called
9185 by \texttt{cvAlloc, cvFree} and higher-level functions (e.g., \texttt{cvCreateImage}). Note
9186 that the function should be called when there is data allocated using
9187 \texttt{cvAlloc}. Also, to avoid infinite recursive calls, it is not
9188 allowed to call \texttt{cvAlloc} and \cross{Free} from the custom
9189 allocation/deallocation functions.
9191 If the \texttt{alloc\_func} and \texttt{free\_func} pointers are
9192 \texttt{NULL}, the default memory managing functions are restored.
9194 \cvfunc{SetIPLAllocators}\label{SetIPLAllocators}
9196 Switches to IPL functions for image allocation/deallocation.
9199 typedef IplImage* (CV_STDCALL* Cv_iplCreateImageHeader)
9200 (int,int,int,char*,char*,int,int,int,int,int,
9201 IplROI*,IplImage*,void*,IplTileInfo*);
9202 typedef void (CV_STDCALL* Cv_iplAllocateImageData)(IplImage*,int,int);
9203 typedef void (CV_STDCALL* Cv_iplDeallocate)(IplImage*,int);
9204 typedef IplROI* (CV_STDCALL* Cv_iplCreateROI)(int,int,int,int,int);
9205 typedef IplImage* (CV_STDCALL* Cv_iplCloneImage)(const IplImage*);
9207 #define CV_TURN_ON_IPL_COMPATIBILITY() \
9208 cvSetIPLAllocators( iplCreateImageHeader, iplAllocateImage, \
9209 iplDeallocate, iplCreateROI, iplCloneImage )
9213 void cvSetIPLAllocators( \par
9214 Cv\_iplCreateImageHeader create\_header, \par
9215 Cv\_iplAllocateImageData allocate\_data, \par
9216 Cv\_iplDeallocate deallocate, \par
9217 Cv\_iplCreateROI create\_roi, \par
9218 Cv\_iplCloneImage clone\_image );
9222 \cvarg{create\_header}{Pointer to iplCreateImageHeader}
9223 \cvarg{allocate\_data}{Pointer to iplAllocateImage}
9224 \cvarg{deallocate}{Pointer to iplDeallocate}
9225 \cvarg{create\_roi}{Pointer to iplCreateROI}
9226 \cvarg{clone\_image}{Pointer to iplCloneImage}
9230 The function \texttt{cvSetIPLAllocators} causes CXCORE to use IPL functions
9231 for image allocation/deallocation operations. For convenience, there
9232 is the wrapping macro \texttt{CV\_TURN\_ON\_IPL\_COMPATIBILITY}. The
9233 function is useful for applications where IPL and CXCORE/OpenCV are used
9234 together and still there are calls to \texttt{iplCreateImageHeader},
9235 etc. The function is not necessary if IPL is called only for data
9236 processing and all the allocation/deallocation is done by CXCORE, or
9237 if all the allocation/deallocation is done by IPL and some of OpenCV
9238 functions are used to process the data.