Update to 2.0.0 tree from current Fremantle build
[opencv] / doc / CxCore.tex
1 \chapter{CXCORE}
2
3 \section{Basic Structures}
4
5 \subsection{Basic Structures}
6
7 \cvstruct{CvPoint}\label{CvPoint}
8
9 2D point with integer coordinates (usually zero-based).
10
11 \begin{lstlisting}
12 typedef struct CvPoint
13 {
14     int x; 
15     int y; 
16 }
17 CvPoint;
18 \end{lstlisting}
19
20 \begin{description}
21 \cvarg{x}{x-coordinate}
22 \cvarg{y}{y-coordinate} 
23 \end{description}
24
25 \begin{lstlisting}
26 /* Constructor */
27 inline CvPoint cvPoint( int x, int y );
28
29 /* Conversion from CvPoint2D32f */
30 inline CvPoint cvPointFrom32f( CvPoint2D32f point );
31 \end{lstlisting}
32
33
34 \cvstruct{CvPoint2D32f}\label{CvPoint2D32f}
35
36 2D point with floating-point coordinates
37
38 \begin{lstlisting}
39
40 typedef struct CvPoint2D32f
41 {
42     float x;
43     float y; 
44 }
45 CvPoint2D32f;
46 \end{lstlisting}
47
48 \begin{description}
49 \cvarg{x}{x-coordinate}
50 \cvarg{y}{y-coordinate}
51 \end{description}
52
53 \begin{lstlisting}
54 /* Constructor */
55 inline CvPoint2D32f cvPoint2D32f( double x, double y );
56
57 /* Conversion from CvPoint */
58 inline CvPoint2D32f cvPointTo32f( CvPoint point );
59
60 \end{lstlisting}
61
62
63 \cvstruct{CvPoint3D32f}\label{CvPoint3D32f}
64
65 3D point with floating-point coordinates
66
67 \begin{lstlisting}
68
69 typedef struct CvPoint3D32f
70 {
71     float x; 
72     float y; 
73     float z; 
74 }
75 CvPoint3D32f;
76 \end{lstlisting}
77
78 \begin{description}
79 \cvarg{x}{x-coordinate}
80 \cvarg{y}{y-coordinate}
81 \cvarg{z}{z-coordinate}
82 \end{description}
83
84 \begin{lstlisting}
85 /* Constructor */
86 inline CvPoint3D32f cvPoint3D32f( double x, double y, double z );
87
88 \end{lstlisting}
89
90 \cvstruct{CvPoint2D64f}\label{CvPoint2D64f}
91
92 2D point with double precision floating-point coordinates
93
94 \begin{lstlisting}
95
96 typedef struct CvPoint2D64f
97 {
98     double x; 
99     double y; 
100 }
101 CvPoint2D64f;
102 \end{lstlisting}
103
104 \begin{description}
105 \cvarg{x}{x-coordinate}
106 \cvarg{y}{y-coordinate}
107 \end{description}
108
109 \begin{lstlisting}
110 /* Constructor */
111 inline CvPoint2D64f cvPoint2D64f( double x, double y );
112
113 /* Conversion from CvPoint */
114 inline CvPoint2D64f cvPointTo64f( CvPoint point );
115
116 \end{lstlisting}
117
118 \cvstruct{CvPoint3D64f}\label{CvPoint3D64f}
119
120 3D point with double precision floating-point coordinates
121
122 \begin{lstlisting}
123
124 typedef struct CvPoint3D64f
125 {
126     double x; 
127     double y; 
128     double z; 
129 }
130 CvPoint3D64f;
131 \end{lstlisting}
132
133 \begin{description}
134 \cvarg{x}{x-coordinate}
135 \cvarg{y}{y-coordinate}
136 \cvarg{z}{z-coordinate}
137 \end{description}
138
139 \begin{lstlisting}
140 /* Constructor */
141 inline CvPoint3D64f cvPoint3D64f( double x, double y, double z );
142
143 \end{lstlisting}
144
145 \cvstruct{CvSize}\label{CvSize}
146
147 Pixel-accurate size of a rectangle.
148
149 \begin{lstlisting}
150
151 typedef struct CvSize
152 {
153     int width; 
154     int height; 
155 }
156 CvSize;
157 \end{lstlisting}
158
159 \begin{description}
160 \cvarg{width}{Width of the rectangle}
161 \cvarg{height}{Height of the rectangle}
162 \end{description}
163
164 \begin{lstlisting}
165 /* Constructor */
166 inline CvSize cvSize( int width, int height );
167
168 \end{lstlisting}
169
170 \cvstruct{CvSize2D32f}\label{CvSize2D32f}
171
172 Sub-pixel accurate size of a rectangle.
173
174 \begin{lstlisting}
175
176 typedef struct CvSize2D32f
177 {
178     float width; 
179     float height; 
180 }
181 CvSize2D32f;
182 \end{lstlisting}
183
184 \begin{description}
185 \cvarg{width}{Width of the rectangle}
186 \cvarg{height}{Height of the rectangle}
187 \end{description}
188
189 \begin{lstlisting}
190 /* Constructor */
191 inline CvSize2D32f cvSize2D32f( double width, double height );
192
193 \end{lstlisting}
194
195 \cvstruct{CvRect}\label{CvRect}
196
197 Offset (usually the top-left corner) and size of a rectangle.
198
199 \begin{lstlisting}
200
201 typedef struct CvRect
202 {
203     int x; 
204     int y; 
205     int width; 
206     int height; 
207 }
208 CvRect;
209 \end{lstlisting}
210
211 \begin{description}
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}
216 \end{description}
217
218 \begin{lstlisting}
219 /* Constructor */
220 inline CvRect cvRect( int x, int y, int width, int height );
221
222 \end{lstlisting}
223
224 \cvstruct{CvScalar}\label{CvScalar}
225
226 A container for 1-,2-,3- or 4-tuples of doubles.
227
228 \begin{lstlisting}
229
230 typedef struct CvScalar
231 {
232     double val[4];
233 }
234 CvScalar;
235
236 \end{lstlisting}
237
238 \begin{lstlisting}
239 /* Constructor: 
240 initializes val[0] with val0, val[1] with val1, etc. 
241 */
242 inline CvScalar cvScalar( double val0, double val1=0,
243                           double val2=0, double val3=0 );
244 /* Constructor: 
245 initializes all of val[0]...val[3] with val0123 
246 */
247 inline CvScalar cvScalarAll( double val0123 );
248
249 /* Constructor: 
250 initializes val[0] with val0, and all of val[1]...val[3] with zeros 
251 */
252 inline CvScalar cvRealScalar( double val0 );
253
254 \end{lstlisting}
255
256 \cvstruct{CvTermCriteria}\label{CvTermCriteria}
257
258 Termination criteria for iterative algorithms.
259
260 \begin{lstlisting}
261
262 #define CV_TERMCRIT_ITER    1
263 #define CV_TERMCRIT_NUMBER  CV_TERMCRIT_ITER
264 #define CV_TERMCRIT_EPS     2
265
266 typedef struct CvTermCriteria
267 {
268     int    type;
269     int    max_iter; 
270     double epsilon; 
271 }
272 CvTermCriteria;
273 \end{lstlisting}
274
275 \begin{description}
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}
279 \end{description}
280
281 \begin{lstlisting}
282 /* Constructor */
283 inline CvTermCriteria cvTermCriteria( int type, int max_iter, double epsilon );
284
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,
289                                     double default_eps,
290                                     int default_max_iters );
291
292 \end{lstlisting}
293
294 \cvstruct{CvMat}\label{CvMat}
295
296 A multi-channel matrix.
297
298 \begin{lstlisting}
299
300 typedef struct CvMat
301 {
302     int type; 
303     int step; 
304
305     int* refcount; 
306
307     union
308     {
309         uchar* ptr;
310         short* s;
311         int* i;
312         float* fl;
313         double* db;
314     } data; 
315
316 #ifdef __cplusplus
317     union
318     {
319         int rows;
320         int height;
321     };
322
323     union
324     {
325         int cols;
326         int width;
327     };
328 #else
329     int rows; 
330     int cols; 
331 #endif
332
333 } CvMat;
334
335 \end{lstlisting}
336
337 \begin{description}
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}
344 \end{description}
345
346
347 Matrices are stored row by row. All of the rows are aligned by 4 bytes.
348
349
350 \cvstruct{CvMatND}\label{CvMatND}
351
352 Multi-dimensional dense multi-channel array.
353
354 \begin{lstlisting}
355
356 typedef struct CvMatND
357 {
358     int type; 
359     int dims;
360
361     int* refcount; 
362
363     union
364     {
365         uchar* ptr;
366         short* s;
367         int* i;
368         float* fl;
369         double* db;
370     } data; 
371
372     struct
373     {
374         int size;
375         int step;
376     }
377     dim[CV_MAX_DIM];
378
379 } CvMatND;
380
381 \end{lstlisting}
382
383 \begin{description}
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)}
389 \end{description}
390
391 \cvstruct{CvSparseMat}\label{CvSparseMat}
392
393 Multi-dimensional sparse multi-channel array.
394
395 \begin{lstlisting}
396
397 typedef struct CvSparseMat
398 {
399     int type;
400     int dims; 
401     int* refcount; 
402     struct CvSet* heap; 
403     void** hashtable; 
404     int hashsize;
405     int total; 
406     int valoffset; 
407     int idxoffset; 
408     int size[CV_MAX_DIM]; 
409
410 } CvSparseMat;
411
412 \end{lstlisting}
413
414 \begin{description}
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}
425 \end{description}
426
427 \cvstruct{IplImage}\label{IplImage}
428
429 IPL image header
430
431 \begin{lstlisting}
432
433 typedef struct _IplImage
434 {
435     int  nSize;         
436     int  ID;            
437     int  nChannels;     
438     int  alphaChannel;  
439     int  depth;         
440     char colorModel[4]; 
441     char channelSeq[4]; 
442     int  dataOrder;     
443     int  origin;        
444     int  align;         
445     int  width;         
446     int  height;        
447     struct _IplROI *roi; 
448     struct _IplImage *maskROI; 
449     void  *imageId;     
450     struct _IplTileInfo *tileInfo; 
451     int  imageSize;                             
452     char *imageData;  
453     int  widthStep;   
454     int  BorderMode[4]; 
455     int  BorderConst[4]; 
456     char *imageDataOrigin; 
457 }
458 IplImage;
459
460 \end{lstlisting}
461
462 \begin{description}
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:
468 \begin{description}
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}
476 \end{description}}
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.}
494 \end{description}
495
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.
497
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. 
499
500 \cvstruct{CvArr}\label{CvArr}
501
502 Arbitrary array
503
504 \begin{lstlisting}
505
506 typedef void CvArr;
507
508 \end{lstlisting}
509
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.
511
512
513 \section{Operations on Arrays}
514
515 \subsection{Initialization}
516
517 \cvfunc{CreateImage}\label{CreateImage}
518
519 Creates an image header and allocates the image data.
520
521 \cvexp{
522 IplImage* cvCreateImage( 
523
524 CvSize size, 
525
526 int depth, 
527
528 int channels );
529 }{CPP}{CreateImage(size, depth, channels)->image}
530
531 \begin{description}
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.}
535 \end{description}
536
537 This call is a shortened form of
538
539 \begin{lstlisting}
540 header = cvCreateImageHeader( size, depth, channels );
541 cvCreateData( header );
542 \end{lstlisting}
543
544
545 \cvfunc{CreateImageHeader}\label{CreateImageHeader}
546
547 Creates an image header but does not allocate the image data.
548
549 \cvexp{
550 IplImage* cvCreateImageHeader( 
551
552 CvSize size, 
553
554 int depth, 
555
556 int channels );
557 }{CPP}{
558 CreateImageHeader(size, depth, channels) -> image
559 }
560
561 \begin{description}
562 \cvarg{size}{Image width and height}
563 \cvarg{depth}{Image depth (see \cross{CreateImage})}
564 \cvarg{channels}{Number of channels (see \cross{CreateImage})}
565 \end{description}
566
567 This call is an analogue of
568
569 \begin{lstlisting}
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,
576                       0,0,0,0);
577 \end{lstlisting}
578
579 but it does not use IPL functions by default (see the \texttt{CV\_TURN\_ON\_IPL\_COMPATIBILITY} macro).
580
581 \ifC
582
583 \cvfunc{ReleaseImageHeader}\label{ReleaseImageHeader}
584
585 Deallocates an image header.
586
587 \cvexp{
588 void cvReleaseImageHeader( IplImage** image );
589 }{CPP}{PYTHON}
590
591 \begin{description}
592 \cvarg{image}{Double pointer to the image header}
593 \end{description}
594
595 This call is an analogue of
596
597 \begin{lstlisting}
598 if( image )
599 {
600     iplDeallocate( *image, IPL_IMAGE_HEADER | IPL_IMAGE_ROI );
601     *image = 0;
602 }
603 \end{lstlisting}
604
605 but it does not use IPL functions by default (see the \texttt{CV\_TURN\_ON\_IPL\_COMPATIBILITY} macro).
606
607 \cvfunc{ReleaseImage}\label{ReleaseImage}
608
609 Deallocates the image header and the image data.
610
611 \cvexp{
612
613 void cvReleaseImage( IplImage** image );
614
615 }{CPP}{PYTHON}
616
617 \begin{description}
618 \cvarg{image}{Double pointer to the image header}
619 \end{description}
620
621 This call is a shortened form of
622
623 \begin{lstlisting}
624
625 if( *image )
626 {
627     cvReleaseData( *image );
628     cvReleaseImageHeader( image );
629 }
630
631 \end{lstlisting}
632
633 \cvfunc{InitImageHeader}\label{InitImageHeader}
634
635 Initializes an image header that was previously allocated.
636
637 \cvexp{
638
639 IplImage* cvInitImageHeader( \par IplImage* image,\par CvSize size,\par int depth,\par int channels,\par int origin=0,\par int align=4 );
640
641 }{CPP}{PYTHON}
642
643 \begin{description}
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}
650 \end{description}
651
652 The returned \texttt{IplImage*} points to the initialized header.
653
654 \fi
655
656 \cvfunc{CloneImage}\label{CloneImage}
657
658 Makes a full copy of an image, including the header, data, and ROI.
659
660 \cvexp{
661
662 IplImage* cvCloneImage( const IplImage* image );
663
664 }{CPP}{CloneImage(image)-> copy}
665
666 \begin{description}
667 \cvarg{image}{The original image}
668 \end{description}
669
670 The returned \texttt{IplImage*} points to the image copy.
671
672 \cvfunc{SetImageCOI}\label{SetImageCOI}
673
674 Sets the channel of interest in an IplImage.
675
676 \cvexp{
677
678 void cvSetImageCOI( \par IplImage* image,\par int coi );
679
680 }{CPP}{SetImageCOI(image, coi)-> None}
681
682 \begin{description}
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.}
685 \end{description}
686
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.
693
694 \cvfunc{GetImageCOI}\label{GetImageCOI}
695
696 Returns the index of the channel of interest. 
697
698 \cvexp{
699
700 int cvGetImageCOI( const IplImage* image );
701
702 }{CPP}{GetImageCOI(image)-> channel}
703
704 \begin{description}
705 \cvarg{image}{A pointer to the image header}
706 \end{description}
707
708 Returns the channel of interest of in an IplImage. Returned values correspond to the \texttt{coi} in \cross{SetImageCOI}.
709
710 \cvfunc{SetImageROI}\label{SetImageROI}\label{ROI}
711
712 Sets an image Region Of Interest (ROI) for a given rectangle.
713
714 \cvexp{
715
716 void cvSetImageROI( \par IplImage* image,\par CvRect rect );
717
718 }{CPP}{SetImageROI(image, rect)-> None}
719
720 \begin{description}
721 \cvarg{image}{A pointer to the image header}
722 \cvarg{rect}{The ROI rectangle}
723 \end{description}
724
725 If the original image ROI was \texttt{NULL} and the \texttt{rect} is not the whole image, the ROI structure is allocated.
726
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.
728
729 \cvfunc{ResetImageROI}\label{ResetImageROI}
730
731 Resets the image ROI to include the entire image and releases the ROI structure.
732
733 \cvexp{
734
735 void cvResetImageROI( IplImage* image );
736
737 }{CPP}{ResetImageROI(image)-> None}
738
739 \begin{description}
740 \cvarg{image}{A pointer to the image header}
741 \end{description}
742
743 This produces a similar result to the following, but in addition it releases the ROI structure.
744
745 \begin{lstlisting}
746
747 cvSetImageROI( image, cvRect( 0, 0, image->width, image->height ));
748 cvSetImageCOI( image, 0 );
749
750 \end{lstlisting}
751
752
753 \cvfunc{GetImageROI}\label{GetImageROI}
754
755 Returns the image ROI.
756
757 \cvexp{
758
759 CvRect cvGetImageROI( const IplImage* image );
760
761 }{CPP}{GetImageROI(image)-> CvRect}
762
763 \begin{description}
764 \cvarg{image}{A pointer to the image header}
765 \end{description}
766
767
768 If there is no ROI set, \texttt{cvRect(0,0,image->width,image->height)} is returned.
769
770
771 \cvfunc{CreateMat}\label{CreateMat}\label{cvCreateMat}
772
773 Creates a matrix header and allocates the matrix data. 
774
775 \cvexp{
776
777 CvMat* cvCreateMat( \par int rows,\par int cols,\par int type );
778
779 }{CPP}{CreateMat(row, cols, type) -> mat}
780
781 \begin{description}
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.}
785 \end{description}
786
787 This is the concise form for:
788
789 \begin{lstlisting}
790
791 CvMat* mat = cvCreateMatHeader( rows, cols, type );
792 cvCreateData( mat );
793
794 \end{lstlisting}
795
796 \cvfunc{CreateMatHeader}\label{CreateMatHeader}
797
798 Creates a matrix header but does not allocate the matrix data.
799
800 \cvexp{
801
802 CvMat* cvCreateMatHeader( \par int rows,\par int cols,\par int type );
803
804 }{CPP}{CreateMatHeader(rows, cols, type) -> mat}
805
806 \begin{description}
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}}
810 \end{description}
811
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}.
813
814 \ifC
815
816 \cvfunc{ReleaseMat}\label{ReleaseMat}
817
818 Deallocates a matrix.
819
820 \cvexp{
821
822 void cvReleaseMat( CvMat** mat );
823
824 }{CPP}{PYTHON}
825
826 \begin{description}
827 \cvarg{mat}{Double pointer to the matrix}
828 \end{description}
829
830
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.
832
833 \begin{lstlisting}
834
835 if( *mat )
836     cvDecRefData( *mat );
837 cvFree( (void**)mat );
838
839 \end{lstlisting}
840
841
842 \cvfunc{InitMatHeader}\label{InitMatHeader}
843
844 Initializes a pre-allocated matrix header.
845
846 \cvexp{
847
848 CvMat* cvInitMatHeader(\par CvMat* mat,\par int rows,\par int cols,\par int type, \par void* data=NULL,\par int step=CV\_AUTOSTEP );
849
850 }{CPP}{PYTHON}
851
852 \begin{description}
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.}
859 \end{description}
860
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:
862
863 \begin{lstlisting}
864
865 double a[] = { 1, 2, 3, 4,
866                5, 6, 7, 8,
867                9, 10, 11, 12 };
868
869 double b[] = { 1, 5, 9,
870                2, 6, 10,
871                3, 7, 11,
872                4, 8, 12 };
873
874 double c[9];
875 CvMat Ma, Mb, Mc ;
876
877 cvInitMatHeader( &Ma, 3, 4, CV_64FC1, a );
878 cvInitMatHeader( &Mb, 4, 3, CV_64FC1, b );
879 cvInitMatHeader( &Mc, 3, 3, CV_64FC1, c );
880
881 cvMatMulAdd( &Ma, &Mb, 0, &Mc );
882 // the c array now contains the product of a (3x4) and b (4x3)
883
884 \end{lstlisting}
885
886 \cvfunc{Mat}\label{Mat}
887
888 Initializes matrix header (lightweight variant).
889
890 \cvexp{
891
892 CvMat cvMat(\par int rows,\par int cols,\par int type,\par void* data=NULL );
893
894 }{CPP}{PYTHON}
895
896 \begin{description}
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}
901 \end{description}
902
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.)
904
905 This function is a fast inline substitution for \cross{InitMatHeader}. Namely, it is equivalent to:
906
907 \begin{lstlisting}
908
909 CvMat mat;
910 cvInitMatHeader( &mat, rows, cols, type, data, CV\_AUTOSTEP );
911
912 \end{lstlisting}
913 \fi
914
915 \cvfunc{CloneMat}\label{CloneMat}
916
917 Creates a full matrix copy.
918
919 \cvexp{
920
921 CvMat* cvCloneMat( const CvMat* mat );
922
923 }{CPP}{CloneMat(mat)-> copy}
924
925 \begin{description}
926 \cvarg{mat}{Matrix to be copied}
927 \end{description}
928
929 Creates a full copy of a matrix and returns a pointer to the copy.
930
931 \cvfunc{CreateMatND}\label{CreateMatND}
932
933 Creates the header and allocates the data for a multi-dimensional dense array.
934
935 \cvexp{
936
937 CvMatND* cvCreateMatND(\par int dims,\par const int* sizes,\par int type );
938
939 }{CPP}{CreateMatND(dims, type)}
940
941 \begin{description}
942 \ifPython
943 \cvarg{dims}{List or tuple of array dimensions, up to 32 in length.}
944 \else
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.}
947 \fi
948 \cvarg{type}{Type of array elements, see \cross{CreateMat}.}
949 \end{description}
950
951 This is a short form for:
952
953 \begin{lstlisting}
954
955 CvMatND* mat = cvCreateMatNDHeader( dims, sizes, type );
956 cvCreateData( mat );
957
958 \end{lstlisting}
959
960 \cvfunc{CreateMatNDHeader}\label{CreateMatNDHeader}
961
962 Creates a new matrix header but does not allocate the matrix data.
963
964 \cvexp{
965
966 CvMatND* cvCreateMatNDHeader(\par int dims,\par const int* sizes,\par int type );
967
968 }{CPP}{CreateMatNDHeader(dims, type)}
969
970 \begin{description}
971 \ifPython
972 \cvarg{dims}{List or tuple of array dimensions, up to 32 in length.}
973 \else
974 \cvarg{dims}{Number of array dimensions}
975 \cvarg{sizes}{Array of dimension sizes}
976 \fi
977 \cvarg{type}{Type of array elements, see \cross{CreateMat}}
978 \end{description}
979
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}.
981
982 \ifC
983
984 \cvfunc{ReleaseMatND}\label{ReleaseMatND}
985
986 Deallocates a multi-dimensional array.
987
988 \cvexp{
989
990 void cvReleaseMatND( CvMatND** mat );
991
992 }{CPP}{PYTHON}
993
994 \begin{description}
995 \cvarg{mat}{Double pointer to the array}
996 \end{description}
997
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.
999
1000 \begin{lstlisting}
1001
1002 if( *mat )
1003     cvDecRefData( *mat );
1004 cvFree( (void**)mat );
1005
1006 \end{lstlisting}
1007
1008 \cvfunc{InitMatNDHeader}\label{InitMatNDHeader}
1009
1010 Initializes a pre-allocated multi-dimensional array header.
1011
1012 \cvexp{
1013
1014 CvMatND* cvInitMatNDHeader( \par CvMatND* mat,\par int dims,\par const int* sizes,\par int type,\par void* data=NULL );
1015
1016 }{CPP}{PYTHON}
1017
1018 \begin{description}
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}
1024 \end{description}
1025
1026 \cvfunc{CloneMatND}\label{CloneMatND}
1027
1028 Creates full copy of a multi-dimensional array and returns a pointer to the copy.
1029
1030 \cvexp{
1031
1032 CvMatND* cvCloneMatND( const CvMatND* mat );
1033
1034 }{CPP}{CloneMatND(mat)-> copy}
1035
1036 \begin{description}
1037 \cvarg{mat}{Input array}
1038 \end{description}
1039
1040
1041 \cvfunc{DecRefData}\label{DecRefData}
1042
1043 Decrements an array data reference counter.
1044
1045 \cvexp{
1046
1047 void cvDecRefData( CvArr* arr );
1048
1049 }{CPP}{PYTHON}
1050
1051 \begin{description}
1052 \cvarg{arr}{Pointer to an array header}
1053 \end{description}
1054
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. 
1062
1063
1064 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1065
1066 \cvfunc{IncRefData}\label{IncRefData}
1067
1068 Increments array data reference counter.
1069
1070 \cvexp{
1071
1072 int cvIncRefData( CvArr* arr );
1073
1074 }{CPP}{PYTHON}
1075
1076 \begin{description}
1077 \cvarg{arr}{Array header}
1078 \end{description}
1079
1080
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.
1084 \fi
1085
1086 \cvfunc{CreateData}\label{CreateData}
1087
1088 Allocates array data
1089
1090 \cvexp{
1091
1092 void cvCreateData( CvArr* arr );
1093
1094 }{CPP}{CreateData(arr)}
1095
1096 \begin{description}
1097 \cvarg{arr}{Array header}
1098 \end{description}
1099
1100
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.
1106
1107 \ifC
1108
1109 \cvfunc{ReleaseData}\label{ReleaseData}
1110
1111 Releases array data.
1112
1113 \cvexp{
1114
1115 void cvReleaseData( CvArr* arr );
1116
1117 }{CPP}{PYTHON}
1118
1119 \begin{description}
1120 \cvarg{arr}{Array header}
1121 \end{description}
1122
1123
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}.
1125
1126 \fi
1127
1128 \cvfunc{SetData}\label{SetData}
1129
1130 Assigns user data to the array header.
1131
1132 \cvexp{
1133
1134 void cvSetData( CvArr* arr, void* data, int step );
1135
1136 }{CPP}{SetData(arr, data, step)}
1137
1138 \begin{description}
1139 \cvarg{arr}{Array header}
1140 \cvarg{data}{User data}
1141 \cvarg{step}{Full row length in bytes}
1142 \end{description}
1143
1144
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.
1146
1147 \ifC
1148 \cvfunc{GetRawData}\label{GetRawData}
1149
1150 Retrieves low-level information about the array.
1151
1152 \cvexp{
1153
1154 void cvGetRawData( const CvArr* arr, uchar** data,
1155                    int* step=NULL, CvSize* roi\_size=NULL );
1156
1157 }{CPP}{PYTHON}
1158
1159 \begin{description}
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}
1164 \end{description}
1165
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.
1167
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.
1169
1170 \begin{lstlisting}
1171
1172 float* data;
1173 int step;
1174
1175 CvSize size;
1176 int x, y;
1177
1178 cvGetRawData( array, (uchar**)&data, &step, &size );
1179 step /= sizeof(data[0]);
1180
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]);
1184
1185 \end{lstlisting}
1186 \fi
1187
1188 \cvfunc{GetMat}\label{GetMat}
1189
1190 Returns matrix header for arbitrary array.
1191
1192 \cvexp{
1193
1194 CvMat* cvGetMat( const CvArr* arr, CvMat* header, int* coi=NULL, int allowND=0 );
1195
1196 }{CPP}{GetMat(arr) -> cvmat }
1197
1198 \begin{description}
1199 \cvarg{arr}{Input array}
1200 \ifC
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.}
1204 \fi
1205 \end{description}
1206
1207 The function \texttt{cvGetMat} returns a matrix header for the input array that can be a matrix - 
1208
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.
1210
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.
1212
1213 Input array must have underlying data allocated or attached, otherwise the function fails.
1214
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.
1216
1217 \cvfunc{GetImage}\label{GetImage}
1218
1219 Returns image header for arbitrary array.
1220
1221 \cvexp{
1222
1223 IplImage* cvGetImage( const CvArr* arr, IplImage* image\_header );
1224
1225 }{CPP}{GetImage(arr) -> iplimage}
1226
1227 \begin{description}
1228 \cvarg{arr}{Input array}
1229 \ifC
1230 \cvarg{image\_header}{Pointer to \texttt{IplImage} structure used as a temporary buffer}
1231 \fi
1232 \end{description}
1233
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.
1243
1244 \cvfunc{CreateSparseMat}\label{CreateSparseMat}
1245
1246 Creates sparse array.
1247
1248 \cvexp{
1249
1250 CvSparseMat* cvCreateSparseMat( int dims, const int* sizes, int type );
1251
1252 }{CPP}{CreateSparseMat(dims, type) -> cvmat}
1253
1254 \begin{description}
1255 \ifC
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}
1258 \else
1259 \cvarg{dims}{List or tuple of array dimensions.}
1260 \fi
1261 \cvarg{type}{Type of array elements. The same as for CvMat}
1262 \end{description}
1263
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.
1265
1266 \ifC
1267 \cvfunc{ReleaseSparseMat}\label{ReleaseSparseMat}
1268
1269 Deallocates sparse array.
1270
1271 \cvexp{
1272
1273 void cvReleaseSparseMat( CvSparseMat** mat );
1274
1275 }{CPP}{PYTHON}
1276
1277 \begin{description}
1278 \cvarg{mat}{Double pointer to the array}
1279 \end{description}
1280
1281
1282 The function \texttt{cvReleaseSparseMat} releases the sparse array and clears the array pointer upon exit.
1283 \fi
1284
1285 \cvfunc{CloneSparseMat}\label{CloneSparseMat}
1286
1287 Creates full copy of sparse array.
1288
1289 \cvexp{
1290
1291 CvSparseMat* cvCloneSparseMat( const CvSparseMat* mat );
1292
1293 }{CPP}{CloneSparseMat(mat) -> mat}
1294
1295 \begin{description}
1296 \cvarg{mat}{Input array}
1297 \end{description}
1298
1299 The function \texttt{cvCloneSparseMat} creates a copy of the input array and returns pointer to the copy.
1300
1301 \subsection{Accessing Elements and sub-Arrays}
1302
1303 \cvfunc{GetSubRect}\label{GetSubRect}
1304
1305 Returns matrix header corresponding to the rectangular sub-array of input image or matrix.
1306
1307 \cvexp{
1308
1309 CvMat* cvGetSubRect( const CvArr* arr, CvMat* submat, CvRect rect );
1310
1311 }{CPP}{GetSubRect(arr, rect) -> cvmat}
1312
1313 \begin{description}
1314 \cvarg{arr}{Input array}
1315 \ifC
1316 \cvarg{submat}{Pointer to the resultant sub-array header}
1317 \fi
1318 \cvarg{rect}{Zero-based coordinates of the rectangle of interest}
1319 \end{description}
1320
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.
1326
1327 \cvfunc{GetRow, GetRows}\label{GetRow, GetRows}
1328
1329 Returns array row or row span.
1330
1331 \cvexp{
1332 CvMat* cvGetRow( const CvArr* arr, CvMat* submat, int row );
1333 }{CPP}{GetRow(arr,submat,row)-> None}
1334 \cvexp{
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}
1337
1338 \begin{description}
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}.}
1345 \end{description}
1346
1347
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}:
1349
1350 \begin{lstlisting}
1351
1352 cvGetRow( arr, submat, row ) ~ cvGetRows( arr, submat, row, row + 1, 1 );
1353
1354 \end{lstlisting}
1355
1356
1357 \cvfunc{GetCol, GetCols}\label{GetCol, GetCols}
1358
1359 Returns array column or column span.
1360
1361 \cvexp{
1362 CvMat* cvGetCol( const CvArr* arr, CvMat* submat, int col );
1363 }{CPP}{GetCol(arr,submat,row)-> None}
1364 \cvexp{
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}
1367
1368 \begin{description}
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}
1374 \end{description}
1375
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}:
1377
1378 \begin{lstlisting}
1379
1380 cvGetCol( arr, submat, col ); // ~ cvGetCols( arr, submat, col, col + 1 );
1381
1382 \end{lstlisting}
1383
1384 \cvfunc{GetDiag}\label{GetDiag}
1385
1386 Returns one of array diagonals.
1387
1388 \cvexp{
1389
1390 CvMat* cvGetDiag( const CvArr* arr, CvMat* submat, int diag=0 );
1391
1392 }{CPP}{GetDiag(arr,submat,diag=0)-> None}
1393
1394 \begin{description}
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.}
1398 \end{description}
1399
1400 The function \texttt{cvGetDiag} returns the header, corresponding to a specified diagonal of the input array.
1401
1402 \cvfunc{GetSize}\label{GetSize}
1403
1404 Returns size of matrix or image ROI.
1405
1406 \cvexp{
1407
1408 CvSize cvGetSize( const CvArr* arr );
1409
1410 }{CPP}{GetSize(arr)-> CvSize}
1411
1412 \begin{description}
1413 \cvarg{arr}{array header}
1414 \end{description}
1415
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.
1417
1418
1419 \ifC
1420 \cvfunc{InitSparseMatIterator}\label{InitSparseMatIterator}
1421
1422 Initializes sparse array elements iterator.
1423
1424 \cvexp{
1425
1426 CvSparseNode* cvInitSparseMatIterator( const CvSparseMat* mat,
1427                                        CvSparseMatIterator* mat\_iterator );
1428
1429 }{CPP}{PYTHON}
1430
1431 \begin{description}
1432 \cvarg{mat}{Input array}
1433 \cvarg{mat\_iterator}{Initialized iterator}
1434 \end{description}
1435
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.
1439
1440 \cvfunc{GetNextSparseNode}\label{GetNextSparseNode}
1441
1442 Initializes sparse array elements iterator.
1443
1444 \cvexp{
1445
1446 CvSparseNode* cvGetNextSparseNode( CvSparseMatIterator* mat\_iterator );
1447
1448 }{CPP}{PYTHON}
1449
1450 \begin{description}
1451 \cvarg{mat\_iterator}{Sparse array iterator}
1452 \end{description}
1453
1454
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:
1456
1457 Using \cross{InitSparseMatIterator} and \cross{GetNextSparseNode} to calculate sum of floating-point sparse array.
1458
1459 \begin{lstlisting}
1460
1461 double sum;
1462 int i, dims = cvGetDims( array );
1463 CvSparseMatIterator mat_iterator;
1464 CvSparseNode* node = cvInitSparseMatIterator( array, &mat_iterator );
1465
1466 for( ; node != 0; node = cvGetNextSparseNode( &mat_iterator ))
1467 {
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 );
1472     printf( "(" );
1473     for( i = 0; i < dims; i++ )
1474         printf( "%4d%s", idx[i], i < dims - 1 "," : "): " );
1475     printf( "%g\n", val );
1476
1477     sum += val;
1478 }
1479
1480 printf( "\nTotal sum = %g\n", sum );
1481
1482 \end{lstlisting}
1483
1484 \fi
1485
1486 \cvfunc{GetElemType}\label{GetElemType}
1487
1488 Returns type of array elements.
1489
1490 \cvexp{
1491
1492 int cvGetElemType( const CvArr* arr );
1493
1494 }{CPP}{GetElemType(arr)-> int}
1495
1496 \begin{description}
1497 \cvarg{arr}{Input array}
1498 \end{description}
1499
1500
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}.
1504
1505
1506 \cvfunc{GetDims, GetDimSize}\label{GetDims, GetDimSize}
1507
1508 Return number of array dimensions and their sizes or the size of a particular dimension.
1509
1510 \ifC
1511 \cvexp{
1512 int cvGetDims( const CvArr* arr, int* sizes=NULL );
1513 }{CPP}{PYTHON}
1514 \cvexp{
1515 int cvGetDimSize( const CvArr* arr, int index );
1516 }{CPP}{PYTHON}
1517
1518 \begin{description}
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
1522 (width) next.}
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
1525 width)}
1526 \end{description}
1527
1528
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:
1535
1536 \begin{lstlisting}
1537
1538 // via cvGetDims()
1539 int sizes[CV_MAX_DIM];
1540 int i, total = 1;
1541 int dims = cvGetDims( arr, size );
1542 for( i = 0; i < dims; i++ )
1543     total *= sizes[i];
1544
1545 // via cvGetDims() and cvGetDimSize()
1546 int i, total = 1;
1547 int dims = cvGetDims( arr );
1548 for( i = 0; i < dims; i++ )
1549     total *= cvGetDimsSize( arr, i );
1550
1551 \end{lstlisting}
1552 \else
1553 \cvexp{C}{CPP}{GetDims(arr)}
1554
1555 \begin{description}
1556 \cvarg{arr}{Input array}
1557 \end{description}
1558
1559
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.
1563 \fi
1564
1565 \ifplastex
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 );}{}{}
1569 \cvfunc{PtrND}
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 );}{}{}
1572 \else
1573 \cvfunc{Ptr*D}\label{Ptr*D}
1574
1575 Return pointer to a particular array element.
1576
1577 \begin{lstlisting}
1578
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 );
1583
1584 \end{lstlisting}
1585 \fi
1586
1587 \begin{description}
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)}
1596 \end{description}
1597
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.
1599
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.
1601
1602 All these as well as other functions accessing array elements (\cross{Get}, \cross{GetReal}, 
1603
1604 \cross{Set}, \cross{SetReal}) raise an error in case if the element index is out of range.
1605
1606
1607 \ifplastex
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 );}{}{}
1611 \cvfunc{GetND} 
1612 Return a specific array element.
1613 \cvexp{CvScalar cvGetND( const CvArr* arr, int* idx );}{}{}
1614
1615 \else
1616 \cvfunc{Get*D}\label{Get*D}
1617
1618 Return a specific array element.
1619
1620 \begin{lstlisting}
1621
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 );
1626
1627 \end{lstlisting}
1628 \fi
1629
1630 \begin{description}
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}
1636 \end{description}
1637
1638
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).
1640
1641 \ifplastex
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 );}{}{}
1645 \cvfunc{GetRealND}
1646 Return a specific element of single-channel array.
1647 \cvexp{double cvGetRealND( const CvArr* arr, int* idx );}{}{}
1648
1649 \else
1650 \cvfunc{GetReal*D}\label{GetReal*D}
1651
1652 Return a specific element of single-channel array.
1653
1654 \begin{lstlisting}
1655
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 );
1660
1661 \end{lstlisting}
1662 \fi
1663
1664 \begin{description}
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}
1670 \end{description}
1671
1672
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.
1674
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).
1676
1677 \cvfunc{mGet}\label{mGet}
1678
1679 Returns the particular element of single-channel floating-point matrix.
1680
1681 \cvexp{
1682
1683 double cvmGet( const CvMat* mat, int row, int col );
1684
1685 }{CPP}{mGet(mat,row,col)-> double}
1686
1687 \begin{description}
1688 \cvarg{mat}{Input matrix}
1689 \cvarg{row}{The zero-based index of row}
1690 \cvarg{col}{The zero-based index of column}
1691 \end{description}
1692
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.
1697
1698 \ifplastex
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 );}{}{}
1702 \cvfunc{SetND}
1703 Change the particular array element
1704 \cvexp{void cvSetND( CvArr* arr, int* idx, CvScalar value );}{}{}
1705
1706 \else
1707 \cvfunc{Set*D}\label{Set*D}
1708
1709 Change the particular array element.
1710
1711 \begin{lstlisting}
1712
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 );
1717
1718 \end{lstlisting}
1719 \fi
1720
1721 \begin{description}
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}
1728 \end{description}
1729
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.
1731
1732 \ifplastex
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 );}{}{}
1738
1739 \else
1740 \cvfunc{SetReal*D}\label{SetReal*D}
1741
1742 Change a specific array element.
1743
1744 \begin{lstlisting}
1745
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 );
1750
1751 \end{lstlisting}
1752 \fi
1753
1754 \begin{description}
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}
1761 \end{description}
1762
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
1767 are a bit slower.
1768
1769 In the case of a sparse array the functions create the node if it does not yet exist.
1770
1771 \cvfunc{mSet}\label{mSet}
1772
1773 Returns a specific element of a single-channel floating-point matrix.
1774
1775 \cvexp{
1776
1777 void cvmSet( CvMat* mat, int row, int col, double value );
1778
1779 }{CPP}{mSet(mat,row,col,value)-> None}
1780
1781 \begin{description}
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}
1786 \end{description}
1787
1788
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.
1793
1794 \cvfunc{ClearND}\label{ClearND}
1795
1796 Clears a specific array element.
1797
1798 \cvexp{
1799
1800 void cvClearND( CvArr* arr, int* idx );
1801
1802 }{CPP}{ClearND(arr,idx)-> None}
1803
1804 \begin{description}
1805 \cvarg{arr}{Input array}
1806 \cvarg{idx}{Array of the element indices}
1807 \end{description}
1808
1809
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.
1811
1812
1813 \subsection{Copying and Filling}
1814
1815
1816 \cvfunc{Copy}\label{Copy}
1817
1818 Copies one array to another.
1819
1820 \cvexp{
1821
1822 void cvCopy( const CvArr* src, CvArr* dst, const CvArr* mask=NULL );
1823
1824 }{CPP}{Copy(src,dst,msk=NULL)-> None}
1825
1826 \begin{description}
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}
1830 \end{description}
1831
1832
1833 The function \texttt{cvCopy} copies selected elements from an input array to an output array:
1834
1835 \[
1836 \texttt{dst}(I)=\texttt{src}(I) \quad \text{if} \quad \texttt{mask}(I) \ne 0.
1837 \]
1838
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).
1843
1844 \cvfunc{Set}\label{Set}
1845
1846 Sets every element of an array to a given value.
1847
1848 \cvexp{
1849
1850 void cvSet( CvArr* arr, CvScalar value, const CvArr* mask=NULL );
1851
1852 }{CPP}{Set(arr,value,msk=NULL)-> None}
1853
1854 \begin{description}
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}
1858 \end{description}
1859
1860
1861 The function \texttt{cvSet} copies the scalar \texttt{value} to every selected element of the destination array:
1862
1863 \[
1864 \texttt{arr}(I)=\texttt{value} \quad \text{if} \quad \texttt{mask}(I) \ne 0
1865 \]
1866
1867 If array \texttt{arr} is of \texttt{IplImage} type, then is ROI used, but COI must not be set.
1868
1869 \cvfunc{SetZero}\label{SetZero}
1870
1871 Clears the array.
1872
1873 \cvexp{
1874
1875 void cvSetZero( CvArr* arr );
1876
1877 }{CPP}{SetZero(arr)-> None}
1878
1879 \begin{lstlisting}
1880 #define cvZero cvSetZero
1881 \end{lstlisting}
1882
1883 \begin{description}
1884 \cvarg{arr}{Array to be cleared}
1885 \end{description}
1886
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.
1890
1891 \subsection{Transforms and Permutations}
1892
1893 \cvfunc{Reshape}\label{Reshape}
1894
1895 Changes shape of matrix/image without copying data.
1896
1897 \cvexp{
1898
1899 CvMat* cvReshape( const CvArr* arr, CvMat* header, int new\_cn, int new\_rows=0 );
1900
1901 }{CPP}{Reshape(arr, new\_cn, new\_rows=0) -> cvmat}
1902
1903 \begin{description}
1904 \cvarg{arr}{Input array}
1905 \ifC
1906 \cvarg{header}{Output header to be filled}
1907 \fi
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.}
1910 \end{description}
1911
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.
1913
1914 \ifC
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:
1916
1917 \begin{lstlisting}
1918
1919 IplImage* color_img = cvCreateImage( cvSize(320,240), IPL_DEPTH_8U, 3 );
1920 CvMat gray_mat_hdr;
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 );
1924
1925 \end{lstlisting}
1926
1927 And the next example converts a 3x3 matrix to a single 1x9 vector:
1928
1929 \begin{lstlisting}
1930
1931 CvMat* mat = cvCreateMat( 3, 3, CV_32F );
1932 CvMat row_header, *row;
1933 row = cvReshape( mat, &row_header, 0, 1 );
1934
1935 \end{lstlisting}
1936 \fi
1937
1938 \cvfunc{ReshapeMatND}\label{ReshapeMatND}
1939
1940 Changes the shape of a multi-dimensional array without copying the data.
1941
1942 \cvexp{
1943
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}
1948
1949 \ifC
1950 \begin{lstlisting}
1951 #define cvReshapeND( arr, header, new\_cn, new\_dims, new\_sizes )   \
1952       cvReshapeMatND( (arr), sizeof(*(header)), (header),         \
1953                       (new\_cn), (new\_dims), (new\_sizes))
1954 \end{lstlisting}
1955 \fi
1956
1957 \begin{description}
1958 \cvarg{arr}{Input array}
1959 \ifC
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.}
1966 \else
1967 \cvarg{new\_dims}{List of new dimensions.}
1968 \fi
1969 \end{description}
1970
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}:
1972
1973 \ifC
1974 \begin{lstlisting}
1975
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 );
1979
1980 ...
1981
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 );
1987
1988 \end{lstlisting}
1989 \fi
1990
1991 \cvfunc{Repeat}\label{Repeat}
1992
1993 Fill the destination array with repeated copies of the source array.
1994
1995 \cvexp{
1996
1997 void cvRepeat( const CvArr* src, CvArr* dst );
1998
1999 }{CPP}{Repeat(src,dst)-> None}
2000
2001 \begin{description}
2002 \cvarg{src}{Source array, image or matrix}
2003 \cvarg{dst}{Destination array, image or matrix}
2004 \end{description}
2005
2006
2007 The function \texttt{cvRepeat} fills the destination array with repeated copies of the source array:
2008
2009 \begin{lstlisting}
2010 dst(i,j)=src(i mod rows(src), j mod cols(src))
2011 \end{lstlisting}
2012
2013 So the destination array may be as larger as well as smaller than the source array.
2014
2015
2016 \cvfunc{Flip}\label{Flip}
2017
2018 Flip a 2D array around vertical, horizontal or both axes.
2019
2020 \cvexp{
2021 void  cvFlip( const CvArr* src, CvArr* dst=NULL, int flip\_mode=0);
2022 }{CPP}{Flip(src,dst=NULL,flip\_mode=0)-> None}
2023
2024 \begin{lstlisting}
2025 #define cvMirror cvFlip
2026 \end{lstlisting}
2027
2028 \begin{description}
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:}
2034 \end{description}
2035
2036 The function \texttt{cvFlip} flips the array in one of three different ways (row and column indices are 0-based):
2037
2038 \[
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$}
2043 \]
2044
2045 The example scenarios of function use are:
2046 \begin{itemize}
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)
2051 \end{itemize}
2052
2053 \cvfunc{Split}\label{Split}
2054
2055 Divides multi-channel array into several single-channel arrays or extracts a single channel from the array.
2056
2057 \cvexp{
2058
2059 void cvSplit( const CvArr* src, CvArr* dst0, CvArr* dst1,
2060               CvArr* dst2, CvArr* dst3 );
2061 }{CPP}{Split(src,dst0,dst1,dst2,dst3)-> None}
2062
2063 \begin{lstlisting}
2064 #define cvCvtPixToPlane cvSplit
2065 \end{lstlisting}
2066
2067 \begin{description}
2068 \cvarg{src}{Source array}
2069 \cvarg{dst0...dst3}{Destination channels}
2070 \end{description}
2071
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.
2081
2082
2083 \cvfunc{Merge}\label{Merge}
2084
2085 Composes a multi-channel array from several single-channel arrays or inserts a single channel into the array.
2086
2087 \cvexp{
2088
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}
2092
2093 \begin{lstlisting}
2094 #define cvCvtPlaneToPix cvMerge
2095 \end{lstlisting}
2096
2097 \begin{description}
2098 \cvarg{src0...src3}{Input channels}
2099 \cvarg{dst}{Destination array}
2100 \end{description}
2101
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.
2103
2104 \cvfunc{MixChannels}\label{MixChannels}
2105
2106 Copies several channels from input arrays to certain channels of output arrays
2107
2108 \cvexp{
2109
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 );
2113
2114 }{CPP}{MixChannels(src, dst, from\_to) -> None}
2115
2116 \begin{description}
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.}
2130 }
2131 \end{description}
2132
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.
2137
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:
2140
2141 \ifPython
2142 \begin{lstlisting}
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]
2152         ])
2153 \end{lstlisting}
2154 \fi
2155
2156 \ifC
2157 \begin{lstlisting}
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) );
2162
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 );
2166 \end{lstlisting}
2167 \fi
2168
2169 \subsection{Arithmetic, Logic and Comparison}
2170
2171 \cvfunc{LUT}\label{LUT}
2172
2173 Performs a look-up table transform of an array.
2174
2175 \cvexp{
2176
2177 void cvLUT( const CvArr* src, CvArr* dst, const CvArr* lut );
2178
2179 }{CPP}{LUT(src,dst,lut)-> None}
2180
2181 \begin{description}
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.}
2185 \end{description}
2186
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:
2188
2189 \[
2190 \texttt{dst}_i \leftarrow \texttt{lut}_{\texttt{src}_i + d}
2191 \]
2192
2193 where
2194
2195 \[
2196 d = \fork
2197 {0}{if \texttt{src} has depth \texttt{CV\_8U}}
2198 {128}{if \texttt{src} has depth \texttt{CV\_8S}}
2199 \]
2200
2201 \cvfunc{ConvertScale}\label{ConvertScale}
2202
2203 Converts one array to another with optional linear transformation.
2204
2205 \cvexp{
2206
2207 void cvConvertScale( const CvArr* src, CvArr* dst, double scale=1, double shift=0 );
2208
2209 }{CPP}{ConvertScale(src,dst,scale=1.0,shift=0.0)-> None}
2210
2211 \begin{lstlisting}
2212 #define cvCvtScale cvConvertScale
2213 #define cvScale  cvConvertScale
2214 #define cvConvert( src, dst )  cvConvertScale( (src), (dst), 1, 0 )
2215 \end{lstlisting}
2216
2217 \begin{description}
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}
2222 \end{description}
2223
2224
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:
2226
2227 \[
2228 \texttt{dst}(I) = \texttt{scale} \texttt{src}(I) + (\texttt{shift}_0,\texttt{shift}_1,...)
2229 \]
2230
2231 All the channels of multi-channel arrays are processed independently.
2232
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.
2237
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}.
2243
2244 \cvfunc{ConvertScaleAbs}\label{ConvertScaleAbs}
2245
2246 Converts input array elements to another 8-bit unsigned integer with optional linear transformation.
2247
2248 \cvexp{
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}
2251
2252 \begin{lstlisting}
2253 #define cvCvtScaleAbs cvConvertScaleAbs
2254 \end{lstlisting}
2255
2256 \begin{description}
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}
2261 \end{description}
2262
2263
2264 The function \texttt{cvConvertScaleAbs} is similar to \cross{ConvertScale}, but it stores absolute values of the conversion results:
2265
2266 \[
2267 \texttt{dst}(I) = |\texttt{scale} \texttt{src}(I) + (\texttt{shift}_0,\texttt{shift}_1,...)|
2268 \]
2269
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.
2271
2272 \cvfunc{Add}\label{Add}
2273
2274 Computes the per-element sum of two arrays.
2275
2276 \cvexp{
2277
2278 void cvAdd( const CvArr* src1, const CvArr* src2, CvArr* dst, const CvArr* mask=NULL );
2279
2280 }{CPP}{Add(src1,src2,sdt,mask=NULL)-> None}
2281
2282 \begin{description}
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}
2287 \end{description}
2288
2289 The function \texttt{cvAdd} adds one array to another:
2290
2291 \begin{lstlisting}
2292 dst(I)=src1(I)+src2(I) if mask(I)!=0
2293 \end{lstlisting}
2294
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.
2297
2298 \cvfunc{AddS}\label{AddS}
2299
2300 Computes the sum of an array and a scalar.
2301
2302 \cvexp{
2303
2304 void cvAddS( const CvArr* src, CvScalar value, CvArr* dst, const CvArr* mask=NULL );
2305
2306 }{CPP}{AddS(src1,value,dst,mask=NULL)-> None}
2307
2308 \begin{description}
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}
2313 \end{description}
2314
2315
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.
2318
2319 \begin{lstlisting}
2320 dst(I)=src(I)+value if mask(I)!=0
2321 \end{lstlisting}
2322
2323 All the arrays must have the same type, except the mask, and the same size (or ROI size).
2324
2325
2326 \cvfunc{AddWeighted}\label{AddWeighted}
2327
2328 Computes the weighted sum of two arrays.
2329
2330 \cvexp{
2331
2332 void  cvAddWeighted( const CvArr* src1, double alpha,
2333                      const CvArr* src2, double beta,
2334                      double gamma, CvArr* dst );
2335
2336 }{CPP}{AddWeighted(src1,alpha,src2,beta,gamma,dst)-> None}
2337
2338 \begin{description}
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}
2345 \end{description}
2346
2347 The function \texttt{cvAddWeighted} calculates the weighted sum of two arrays as follows:
2348
2349 \begin{lstlisting}
2350 dst(I)=src1(I)*alpha+src2(I)*beta+gamma
2351 \end{lstlisting}
2352
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.
2355
2356
2357 \cvfunc{Sub}\label{Sub}
2358
2359 Computes the per-element difference between two arrays.
2360
2361 \cvexp{
2362
2363 void cvSub( const CvArr* src1, const CvArr* src2, CvArr* dst, const CvArr* mask=NULL );
2364
2365 }{CPP}{Sub(src1,src2,dst,mask=NULL)-> None}
2366
2367 \begin{description}
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}
2372 \end{description}
2373
2374
2375 The function \texttt{cvSub} subtracts one array from another one:
2376
2377 \begin{lstlisting}
2378 dst(I)=src1(I)-src2(I) if mask(I)!=0
2379 \end{lstlisting}
2380
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.
2383
2384 \cvfunc{SubS}\label{SubS}
2385
2386 Computes the difference between an array and a scalar.
2387
2388 \cvexp{
2389
2390 void cvSubS( const CvArr* src, CvScalar value, CvArr* dst, const CvArr* mask=NULL );
2391
2392 }{CPP}{SubS(src1,value,dst,mask=NULL)-> None}
2393
2394 \begin{description}
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}
2399 \end{description}
2400
2401 The function \texttt{cvSubS} subtracts a scalar from every element of the source array:
2402
2403 \begin{lstlisting}
2404 dst(I)=src(I)-value if mask(I)!=0
2405 \end{lstlisting}
2406
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.
2409
2410
2411 \cvfunc{SubRS}\label{SubRS}
2412
2413 Computes the difference between a scalar and an array.
2414
2415 \cvexp{
2416
2417 void cvSubRS( const CvArr* src, CvScalar value, CvArr* dst, const CvArr* mask=NULL );
2418
2419 }{CPP}{SubRS(src1,value,dst,mask=NULL)-> None}
2420
2421 \begin{description}
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}
2426 \end{description}
2427
2428
2429 The function \texttt{cvSubRS} subtracts every element of source array from a scalar:
2430
2431 \begin{lstlisting}
2432 dst(I)=value-src(I) if mask(I)!=0
2433 \end{lstlisting}
2434
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.
2437
2438 \cvfunc{Mul}\label{Mul}
2439
2440 Calculates the per-element product of two arrays.
2441
2442 \cvexp{
2443
2444 void cvMul( const CvArr* src1, const CvArr* src2, CvArr* dst, double scale=1 );
2445
2446 }{CPP}{Mul(src1,src2,dst,scale)-> None}
2447
2448 \begin{description}
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}
2453 \end{description}
2454
2455
2456 The function \texttt{cvMul} calculates the per-element product of two arrays:
2457
2458 \[
2459 \texttt{dst}(I)=\texttt{scale} \cdot \texttt{src1}(I) \cdot \texttt{src2}(I)
2460 \]
2461
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.
2464
2465 \cvfunc{Div}\label{Div}
2466
2467 Performs per-element division of two arrays.
2468
2469 \cvexp{
2470
2471 void cvDiv( const CvArr* src1, const CvArr* src2, CvArr* dst, double scale=1 );
2472
2473 }{CPP}{Div(src1,src2,dst,scale)-> None}
2474
2475 \begin{description}
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}
2480 \end{description}
2481
2482 The function \texttt{cvDiv} divides one array by another:
2483
2484 \[
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}
2488 \]
2489
2490 All the arrays must have the same type and the same size (or ROI size).
2491
2492
2493 \cvfunc{And}\label{And}
2494
2495 Calculates per-element bit-wise conjunction of two arrays.
2496
2497 \cvexp{
2498
2499 void cvAnd( const CvArr* src1, const CvArr* src2, CvArr* dst, const CvArr* mask=NULL );
2500
2501 }{CPP}{And(src1,src2,dst,mask=NULL)-> None}
2502
2503 \begin{description}
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}
2508 \end{description}
2509
2510
2511 The function \texttt{cvAnd} calculates per-element bit-wise logical conjunction of two arrays:
2512
2513 \begin{lstlisting}
2514 dst(I)=src1(I)&src2(I) if mask(I)!=0
2515 \end{lstlisting}
2516
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.
2518
2519 \cvfunc{AndS}\label{AndS}
2520
2521 Calculates per-element bit-wise conjunction of an array and a scalar.
2522
2523 \cvexp{
2524
2525 void cvAndS( const CvArr* src, CvScalar value, CvArr* dst, const CvArr* mask=NULL );
2526
2527 }{CPP}{AndS(src1,value,dst,mask=NULL)-> None}
2528
2529 \begin{description}
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}
2534 \end{description}
2535
2536 The function AndS calculates per-element bit-wise conjunction of an array and a scalar:
2537
2538 \begin{lstlisting}
2539 dst(I)=src(I)&value if mask(I)!=0
2540 \end{lstlisting}
2541
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.
2543
2544 The following sample demonstrates how to calculate the absolute value of floating-point array elements by clearing the most-significant bit:
2545
2546 \begin{lstlisting}
2547
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] );
2554
2555 \end{lstlisting}
2556
2557 The code should print:
2558
2559 \begin{lstlisting}
2560 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0
2561 \end{lstlisting}
2562
2563
2564 \cvfunc{Or}\label{Or}
2565
2566 Calculates per-element bit-wise disjunction of two arrays.
2567
2568 \cvexp{
2569
2570 void cvOr( const CvArr* src1, const CvArr* src2, CvArr* dst, const CvArr* mask=NULL );
2571
2572 }{CPP}{Or(src1,src2,dst,mask=NULL)-> None}
2573
2574 \begin{description}
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}
2579 \end{description}
2580
2581
2582 The function \texttt{cvOr} calculates per-element bit-wise disjunction of two arrays:
2583
2584 \begin{lstlisting}
2585 dst(I)=src1(I)|src2(I)
2586 \end{lstlisting}
2587
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.
2589
2590 \cvfunc{OrS}\label{OrS}
2591
2592 Calculates a per-element bit-wise disjunction of an array and a scalar.
2593
2594 \cvexp{
2595
2596 void cvOrS( const CvArr* src, CvScalar value, CvArr* dst, const CvArr* mask=NULL );
2597
2598 }{CPP}{OrS(src1,value,dst,mask=NULL)-> None}
2599
2600 \begin{description}
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}
2605 \end{description}
2606
2607
2608 The function OrS calculates per-element bit-wise disjunction of an array and a scalar:
2609
2610 \begin{lstlisting}
2611 dst(I)=src(I)|value if mask(I)!=0
2612 \end{lstlisting}
2613
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.
2615
2616
2617 \cvfunc{Xor}\label{Xor}
2618
2619 Performs per-element bit-wise "exclusive or" operation on two arrays.
2620
2621 \cvexp{
2622
2623 void cvXor( const CvArr* src1, const CvArr* src2, CvArr* dst, const CvArr* mask=NULL );
2624
2625 }{CPP}{Xor(src1,src2,dst,mask=NULL)-> None}
2626
2627 \begin{description}
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}
2632 \end{description}
2633
2634 The function \texttt{cvXor} calculates per-element bit-wise logical conjunction of two arrays:
2635
2636 \begin{lstlisting}
2637 dst(I)=src1(I)^src2(I) if mask(I)!=0
2638 \end{lstlisting}
2639
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.
2641
2642 \cvfunc{XorS}\label{XorS}
2643
2644 Performs per-element bit-wise "exclusive or" operation on an array and a scalar.
2645
2646 \cvexp{
2647
2648 void cvXorS( const CvArr* src, CvScalar value, CvArr* dst, const CvArr* mask=NULL );
2649
2650 }{CPP}{XorS(src1,value,dst,mask=NULL)-> None}
2651
2652 \begin{description}
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}
2657 \end{description}
2658
2659
2660 The function XorS calculates per-element bit-wise conjunction of an array and a scalar:
2661
2662 \begin{lstlisting}
2663 dst(I)=src(I)^value if mask(I)!=0
2664 \end{lstlisting}
2665
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
2667
2668 The following sample demonstrates how to conjugate complex vector by switching the most-significant bit of imaging part:
2669
2670 \begin{lstlisting}
2671
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] );
2678
2679 \end{lstlisting}
2680
2681 The code should print:
2682
2683 \begin{lstlisting}
2684 (1.0,0.0) (0.0,-1.0) (-1.0,0.0) (0.0,1.0)
2685 \end{lstlisting}
2686
2687 \cvfunc{Not}\label{Not}
2688
2689 Performs per-element bit-wise inversion of array elements.
2690
2691 \cvexp{
2692
2693 void cvNot( const CvArr* src, CvArr* dst );
2694
2695 }{CPP}{Not(src,dst)-> None}
2696
2697 \begin{description}
2698 \cvarg{src1}{The source array}
2699 \cvarg{dst}{The destination array}
2700 \end{description}
2701
2702
2703 The function Not inverses every bit of every array element:
2704
2705 \begin{lstlisting}
2706 dst(I)=~src(I)
2707 \end{lstlisting}
2708
2709
2710 \cvfunc{Cmp}\label{Cmp}
2711
2712 Performs per-element comparison of two arrays.
2713
2714 \cvexp{
2715
2716 void cvCmp( const CvArr* src1, const CvArr* src2, CvArr* dst, int cmp\_op );
2717
2718 }{CPP}{Cmp(src1,src2,dst,cm\_op)-> None}
2719
2720 \begin{description}
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
2725 \begin{description}
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}
2732 \end{description}}
2733 \end{description}
2734
2735 The function \texttt{cvCmp} compares the corresponding elements of two arrays and fills the destination mask array:
2736
2737 \begin{lstlisting}
2738
2739 dst(I)=src1(I) op src2(I),
2740
2741 \end{lstlisting}
2742
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)
2744
2745 \cvfunc{CmpS}\label{CmpS}
2746
2747 Performs per-element comparison of an array and a scalar.
2748
2749 \cvexp{
2750
2751 void cvCmpS( const CvArr* src, double value, CvArr* dst, int cmp\_op );
2752
2753 }{CPP}{CmpS(src1,value,dst,cmp\_op)-> None}
2754
2755 \begin{description}
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
2760 \begin{description}
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}
2767 \end{description}}
2768 \end{description}
2769
2770 The function \texttt{CmpS} compares the corresponding elements of an array and a scalar and fills the destination mask array:
2771
2772 \begin{lstlisting}
2773
2774 dst(I)=src(I) op scalar
2775
2776 \end{lstlisting}
2777
2778 where \texttt{op} is $=$, $>$, $\ge$, $<$, $\le$ or $\ne$.
2779
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).
2781
2782 \cvfunc{InRange}\label{InRange}
2783
2784 Checks that array elements lie between the elements of two other arrays.
2785
2786 \cvexp{
2787
2788 void cvInRange( const CvArr* src, const CvArr* lower, const CvArr* upper, CvArr* dst );
2789
2790 }{CPP}{InRange(src,lower,upper,dst)-> None}
2791
2792 \begin{description}
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}
2797 \end{description}
2798
2799
2800 The function \texttt{cvInRange} does the range check for every element of the input array:
2801
2802 \[
2803 \texttt{dst}(I)=\texttt{lower}(I)_0 <= \texttt{src}(I)_0 < \texttt{upper}(I)_0
2804 \]
2805
2806 For single-channel arrays,
2807
2808 \[
2809 \texttt{dst}(I)=
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
2812 \]
2813
2814 For two-channel arrays and so forth,
2815
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).
2817
2818
2819 \cvfunc{InRangeS}\label{InRangeS}
2820
2821 Checks that array elements lie between two scalars.
2822
2823 \cvexp{
2824
2825 void cvInRangeS( const CvArr* src, CvScalar lower, CvScalar upper, CvArr* dst );
2826
2827 }{CPP}{InRangeS(src,lower,upper,dst)-> None}
2828
2829 \begin{description}
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}
2834 \end{description}
2835
2836
2837 The function \texttt{cvInRangeS} does the range check for every element of the input array:
2838
2839 \[
2840 \texttt{dst}(I)=\texttt{lower}_0 <= \texttt{src}(I)_0 < \texttt{upper}_0
2841 \]
2842
2843 For single-channel arrays,
2844
2845 \[
2846 \texttt{dst}(I)=
2847 \texttt{lower}_0 <= \texttt{src}(I)_0 < \texttt{upper}_0 \land
2848 \texttt{lower}_1 <= \texttt{src}(I)_1 < \texttt{upper}_1
2849 \]
2850
2851 For two-channel arrays nd so forth,
2852
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).
2854
2855 \cvfunc{Max}\label{Max}
2856
2857 Finds per-element maximum of two arrays.
2858
2859 \cvexp{
2860
2861 void cvMax( const CvArr* src1, const CvArr* src2, CvArr* dst );
2862
2863 }{CPP}{Max(src1,src2,dst)-> None}
2864
2865 \begin{description}
2866 \cvarg{src1}{The first source array}
2867 \cvarg{src2}{The second source array}
2868 \cvarg{dst}{The destination array}
2869 \end{description}
2870
2871 The function \texttt{cvMax} calculates per-element maximum of two arrays:
2872
2873 \[
2874 \texttt{dst}(I)=\max(\texttt{src1}(I), \texttt{src2}(I))
2875 \]
2876
2877 All the arrays must have a single channel, the same data type and the same size (or ROI size).
2878
2879
2880 \cvfunc{MaxS}\label{MaxS}
2881
2882 Finds per-element maximum of array and scalar.
2883
2884 \cvexp{
2885
2886 void cvMaxS( const CvArr* src, double value, CvArr* dst );
2887
2888 }{CPP}{MaxS(src1,value,dst)-> None}
2889
2890 \begin{description}
2891 \cvarg{src}{The first source array}
2892 \cvarg{value}{The scalar value}
2893 \cvarg{dst}{The destination array}
2894 \end{description}
2895
2896 The function \texttt{cvMaxS} calculates per-element maximum of array and scalar:
2897
2898 \[
2899 \texttt{dst}(I)=\max(\texttt{src}(I), \texttt{value})
2900 \]
2901
2902 All the arrays must have a single channel, the same data type and the same size (or ROI size).
2903
2904
2905 \cvfunc{Min}\label{Min}
2906
2907 Finds per-element minimum of two arrays.
2908
2909 \cvexp{
2910
2911 void cvMin( const CvArr* src1, const CvArr* src2, CvArr* dst );
2912
2913 }{CPP}{Min(src1,src2,dst)-> None}
2914
2915 \begin{description}
2916 \cvarg{src1}{The first source array}
2917 \cvarg{src2}{The second source array}
2918 \cvarg{dst}{The destination array}
2919 \end{description}
2920
2921
2922 The function \texttt{cvMin} calculates per-element minimum of two arrays:
2923
2924 \[
2925 \texttt{dst}(I)=\min(\texttt{src1}(I),\texttt{src2}(I))
2926 \]
2927
2928 All the arrays must have a single channel, the same data type and the same size (or ROI size).
2929
2930
2931 \cvfunc{MinS}\label{MinS}
2932
2933 Finds per-element minimum of an array and a scalar.
2934
2935 \cvexp{
2936
2937 void cvMinS( const CvArr* src, double value, CvArr* dst );
2938
2939 }{CPP}{MinS(src1,value,dst)-> None}
2940
2941 \begin{description}
2942 \cvarg{src}{The first source array}
2943 \cvarg{value}{The scalar value}
2944 \cvarg{dst}{The destination array}
2945 \end{description}
2946
2947 The function \texttt{cvMinS} calculates minimum of an array and a scalar:
2948
2949 \[
2950 \texttt{dst}(I)=\min(\texttt{src}(I), \texttt{value})
2951 \]
2952
2953 All the arrays must have a single channel, the same data type and the same size (or ROI size).
2954
2955 \cvfunc{AbsDiff}\label{AbsDiff}
2956
2957 Calculates absolute difference between two arrays.
2958
2959 \cvexp{
2960
2961 void cvAbsDiff( const CvArr* src1, const CvArr* src2, CvArr* dst );
2962
2963 }{CPP}{AbsDiff(src1,src2,dst)-> None}
2964
2965 \begin{description}
2966 \cvarg{src1}{The first source array}
2967 \cvarg{src2}{The second source array}
2968 \cvarg{dst}{The destination array}
2969 \end{description}
2970
2971 The function \texttt{cvAbsDiff} calculates absolute difference between two arrays.
2972
2973 \[ \texttt{dst}(i)_c = |\texttt{src1}(I)_c - \texttt{src2}(I)_c| \]
2974
2975 All the arrays must have the same data type and the same size (or ROI size).
2976
2977 \cvfunc{AbsDiffS}\label{AbsDiffS}
2978
2979 Calculates absolute difference between an array and a scalar.
2980
2981 \cvexp{
2982
2983 void cvAbsDiffS( const CvArr* src, CvArr* dst, CvScalar value );
2984 }{CPP}{AbsDiffS(src1,value,dst)-> None}
2985
2986 \begin{lstlisting}
2987 #define cvAbs(src, dst) cvAbsDiffS(src, dst, cvScalarAll(0))
2988 \end{lstlisting}
2989
2990 \begin{description}
2991 \cvarg{src}{The source array}
2992 \cvarg{dst}{The destination array}
2993 \cvarg{value}{The scalar}
2994 \end{description}
2995
2996 The function \texttt{cvAbsDiffS} calculates absolute difference between an array and a scalar.
2997
2998 \[ \texttt{dst}(i)_c = |\texttt{src}(I)_c - \texttt{value}_c| \]
2999
3000 All the arrays must have the same data type and the same size (or ROI size).
3001
3002 \subsection{Statistics}
3003
3004 \cvfunc{CountNonZero}\label{CountNonZero}
3005
3006 Counts non-zero array elements.
3007
3008 \cvexp{
3009
3010 int cvCountNonZero( const CvArr* arr );
3011
3012 }{CPP}{CountNonZero(arr)-> int}
3013
3014 \begin{description}
3015 \cvarg{arr}{The array must be a single-channel array or a multi-channel image with COI set}
3016 \end{description}
3017
3018
3019 The function \texttt{cvCountNonZero} returns the number of non-zero elements in arr:
3020
3021 \[ \sum_I (\texttt{arr}(I) \ne 0) \]
3022
3023 In the case of \texttt{IplImage} both ROI and COI are supported.
3024
3025
3026 \cvfunc{Sum}\label{Sum}
3027
3028 Adds up array elements.
3029
3030 \cvexp{
3031
3032 CvScalar cvSum( const CvArr* arr );
3033
3034 }{CPP}{Sum(arr)-> CvScalar}
3035
3036 \begin{description}
3037 \cvarg{arr}{The array}
3038 \end{description}
3039
3040
3041 The function \texttt{cvSum} calculates the sum \texttt{S} of array elements, independently for each channel:
3042
3043 \[ \sum_I \texttt{arr}(I)_c \]
3044
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
3046 .
3047
3048
3049 \cvfunc{Avg}\label{Avg}
3050
3051 Calculates average (mean) of array elements.
3052
3053 \cvexp{
3054
3055 CvScalar cvAvg( const CvArr* arr, const CvArr* mask=NULL );
3056
3057 }{CPP}{Avg(arr,mask=NULL)-> CvScalar}
3058
3059 \begin{description}
3060 \cvarg{arr}{The array}
3061 \cvarg{mask}{The optional operation mask}
3062 \end{description}
3063
3064
3065 The function \texttt{cvAvg} calculates the average value \texttt{M} of array elements, independently for each channel:
3066
3067 \[
3068 \begin{array}{l}
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}
3071 \end{array}
3072 \]
3073
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 $ .
3075
3076 \cvfunc{AvgSdv}\label{AvgSdv}
3077
3078 Calculates average (mean) of array elements.
3079
3080 \cvexp{
3081
3082 void cvAvgSdv( const CvArr* arr, CvScalar* mean, CvScalar* std\_dev, const CvArr* mask=NULL );
3083
3084 }{CPP}{AvgSdv(arr,mask=NULL)-> mean, std\_dev}
3085
3086 \begin{description}
3087 \cvarg{arr}{The array}
3088 \ifC
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}
3091 \fi
3092 \cvarg{mask}{The optional operation mask}
3093 \ifPython
3094 \cvarg{mean}{Mean value, a CvScalar}
3095 \cvarg{std\_dev}{Standard deviation, a CvScalar}
3096 \fi
3097
3098 \end{description}
3099
3100 The function \texttt{cvAvgSdv} calculates the average value and standard deviation of array elements, independently for each channel:
3101
3102 \[
3103 \begin{array}{l}
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}
3107 \end{array}
3108 \]
3109
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$).
3111
3112 \cvfunc{MinMaxLoc}\label{MinMaxLoc}
3113
3114 Finds global minimum and maximum in array or subarray.
3115
3116 \cvexp{
3117
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 );
3120
3121 }{CPP}{MinMaxLoc(arr,mask=NULL)-> min\_val,max\_val,min\_loc,max\_loc}
3122
3123 \begin{description}
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}
3130 \end{description}
3131
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.
3139
3140 \cvfunc{Norm}\label{Norm}
3141
3142 Calculates absolute array norm, absolute difference norm, or relative difference norm.
3143
3144 \cvexp{
3145
3146 double cvNorm( const CvArr* arr1, const CvArr* arr2=NULL, int norm\_type=CV\_L2, const CvArr* mask=NULL );
3147
3148 }{CPP}{Norm(arr1,arr2,norm\_type+CV\_L2,mask=NULL)-> double}
3149
3150 \begin{description}
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}
3155 \end{description}
3156
3157 The function \texttt{cvNorm} calculates the absolute norm of \texttt{arr1} if \texttt{arr2} is NULL:
3158 \[
3159 norm = \forkthree
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}$}
3163 \]
3164
3165 And the function calculates absolute or relative difference norm if \texttt{arr2} is not NULL:
3166 \[
3167 norm = \forkthree
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}$}
3171 \]
3172
3173 or
3174
3175 \[
3176 norm = \forkthree
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}$}
3180 \]
3181
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.
3183
3184 \cvfunc{Reduce}
3185
3186 Reduces a matrix to a vector.
3187
3188 \cvexp{
3189
3190 void cvReduce( const CvArr* src, CvArr* dst, int op=CV\_REDUCE\_SUM );
3191
3192 }{CPP}{Reduce(src,dst,op=CV\_REDUCE\_SUM)-> None}
3193
3194 \begin{description}
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:
3199 \begin{description}
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.}
3204 \end{description}}
3205 \end{description}
3206
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. 
3208
3209
3210 \subsection{Linear Algebra}
3211
3212 \cvfunc{SetIdentity}\label{SetIdentity}
3213
3214 Initializes a scaled identity matrix.
3215
3216 \cvexp{
3217
3218 void cvSetIdentity( CvArr* mat, CvScalar value=cvRealScalar(1) );
3219
3220 }{CPP}{SetIdentity(mat,value=cvRealScalar(1))-> None}
3221
3222 \begin{description}
3223 \cvarg{arr}{The matrix to initialize (not necesserily square)}
3224 \cvarg{value}{The value to assign to the diagonal elements}
3225 \end{description}
3226
3227 The function \texttt{cvSetIdentity} initializes a scaled identity matrix:
3228
3229 \[
3230 \texttt{arr}(i,j)=\fork{\texttt{value}}{ if $i=j$}{0}{otherwise}
3231 \]
3232
3233 \cvfunc{DotProduct}\label{DotProduct}
3234
3235 Calculates the dot product of two arrays in Euclidian metrics.
3236
3237 \cvexp{
3238
3239 double cvDotProduct( const CvArr* src1, const CvArr* src2 );
3240
3241 }{CPP}{DotProduct(src1,src2)-> double}
3242
3243 \begin{description}
3244 \cvarg{src1}{The first source array}
3245 \cvarg{src2}{The second source array}
3246 \end{description}
3247
3248 The function \texttt{cvDotProduct} calculates and returns the Euclidean dot product of two arrays.
3249
3250 \[
3251 src1 \bullet src2 = \sum_I (\texttt{src1}(I) \texttt{src2}(I))
3252 \]
3253
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.
3256
3257 \cvfunc{CrossProduct}\label{CrossProduct}
3258
3259 Calculates the cross product of two 3D vectors.
3260
3261 \cvexp{
3262
3263 void cvCrossProduct( const CvArr* src1, const CvArr* src2, CvArr* dst );
3264
3265 }{CPP}{CrossProduct(src1,src2,dst)-> None}
3266
3267 \begin{description}
3268 \cvarg{src1}{The first source vector}
3269 \cvarg{src2}{The second source vector}
3270 \cvarg{dst}{The destination vector}
3271 \end{description}
3272
3273
3274 The function \texttt{cvCrossProduct} calculates the cross product of two 3D vectors:
3275
3276 \[ \texttt{dst} = \texttt{src1} \times \texttt{src2} \]
3277 or:
3278 \[
3279 \begin{array}{l}
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
3283 \end{array}
3284 \]
3285
3286 \cvfunc{ScaleAdd}\label{ScaleAdd}
3287
3288 Calculates the sum of a scaled array and another array.
3289
3290 \cvexp{
3291
3292 void cvScaleAdd( const CvArr* src1, CvScalar scale, const CvArr* src2, CvArr* dst );
3293
3294 }{CPP}{ScaleAdd(src1,sclae,src2,dst)-> None}
3295 \begin{lstlisting}
3296 #define cvMulAddS cvScaleAdd
3297 \end{lstlisting}
3298
3299 \begin{description}
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}
3304 \end{description}
3305
3306 The function \texttt{cvScaleAdd} calculates the sum of a scaled array and another array:
3307
3308 \[
3309 \texttt{dst}(I)=\texttt{scale} \, \texttt{src1}(I) + \texttt{src2}(I)
3310 \]
3311
3312 All array parameters should have the same type and the same size.
3313
3314 \cvfunc{GEMM}\label{GEMM}
3315
3316 Performs generalized matrix multiplication.
3317
3318 \cvexp{
3319
3320 void  cvGEMM( const CvArr* src1, const CvArr* src2, double alpha,
3321               const CvArr* src3, double beta, CvArr* dst, int tABC=0 );
3322
3323 }{CPP}{GEMM(src1,src2,alphs,src3,beta,dst,tABC=0)-> None}
3324 \begin{lstlisting}
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 )
3327 \end{lstlisting}
3328
3329 \begin{description}
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
3335 \begin{description}
3336 \cvarg{CV\_GEMM\_A\_T}{transpose src1}
3337 \cvarg{CV\_GEMM\_B\_T}{transpose src2}
3338 \cvarg{CV\_GEMM\_C\_T}{transpose src3}
3339 \end{description}
3340 For example, \texttt{CV\_GEMM\_A\_T+CV\_GEMM\_C\_T} corresponds to
3341 \[
3342 \texttt{alpha} \, \texttt{src1} ^T \, \texttt{src2} + \texttt{beta} \, \texttt{src3} ^T
3343 \]}
3344 \end{description}
3345
3346 The function \texttt{cvGEMM} performs generalized matrix multiplication:
3347
3348 \[
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$}
3350 \]
3351
3352 All the matrices should have the same data type and coordinated sizes. Real or complex floating-point matrices are supported.
3353
3354 \cvfunc{Transform}\label{Transform}
3355
3356 Performs matrix transformation of every array element.
3357
3358 \cvexp{
3359
3360 void cvTransform( const CvArr* src, CvArr* dst, const CvMat* transmat, const CvMat* shiftvec=NULL );
3361
3362 }{CPP}{Transform(src,dst,transmat,shiftvec=NULL)-> None}
3363
3364 \begin{description}
3365 \cvarg{src}{The first source array}
3366 \cvarg{dst}{The destination array}
3367 \cvarg{transmat}{Transformation matrix}
3368 \cvarg{shiftvec}{Optional shift vector}
3369 \end{description}
3370
3371 The function \texttt{cvTransform} performs matrix transformation of every element of array \texttt{src} and stores the results in \texttt{dst}:
3372
3373 \[
3374 dst(I) = transmat \cdot src(I) + shiftvec %  or   dst(I),,k,,=sum,,j,,(transmat(k,j)*src(I),,j,,) + shiftvec(k)
3375 \]
3376
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
3384 vector.
3385
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.
3389
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.
3393
3394 \cvfunc{PerspectiveTransform}\label{PerspectiveTransform}
3395
3396 Performs perspective matrix transformation of a vector array.
3397
3398 \cvexp{
3399
3400 void cvPerspectiveTransform( const CvArr* src, CvArr* dst, const CvMat* mat );
3401
3402 }{CPP}{PerspectiveTransform(src,dst,mat)-> None}
3403
3404 \begin{description}
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}
3408 \end{description}
3409
3410
3411 The function \texttt{PerspectiveTransform} transforms every element of \texttt{src} (by treating it as 2D or 3D vector) in the following way:
3412
3413 \[ (x, y, z) \rightarrow (x'/w, y'/w, z'/w) \]
3414
3415 where
3416
3417 \[
3418 (x', y', z', w') = \texttt{mat} \cdot
3419 \begin{bmatrix} x & y & z & 1 \end{bmatrix}
3420 \]
3421
3422 and
3423 \[ w = \fork{w'}{if $w' \ne 0$}{\infty}{otherwise} \]
3424
3425 \cvfunc{MulTransposed}\label{MulTransposed}
3426
3427 Calculates the product of an array and a transposed array.
3428
3429 \cvexp{
3430
3431 void cvMulTransposed( const CvArr* src, CvArr* dst, int order, const CvArr* delta=NULL, double scale=1.0 );
3432
3433 }{CPP}{MulTransposed(src,dst,order,delta=NULL)-> None}
3434
3435 \begin{description}
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}
3441 \end{description}
3442
3443 The function \texttt{MulTransposed} calculates the product of src and its transposition.
3444
3445 The function evaluates
3446
3447 \[
3448 \texttt{dst}=\texttt{scale} (\texttt{src}-\texttt{delta}) (\texttt{src}-\texttt{delta})^T
3449 \]
3450
3451 if $\texttt{order}=0$, and
3452
3453 \[
3454 \texttt{dst}=\texttt{scale} (\texttt{src}-\texttt{delta})^T (\texttt{src}-\texttt{delta})
3455 \]
3456
3457 otherwise.
3458
3459 \cvfunc{Trace}\label{Trace}
3460
3461 Returns the trace of a matrix.
3462
3463 \cvexp{
3464
3465 CvScalar cvTrace( const CvArr* mat );
3466
3467 }{CPP}{Trace(mat)-> CvScalar}
3468
3469 \begin{description}
3470 \cvarg{mat}{The source matrix}
3471 \end{description}
3472
3473
3474 The function \texttt{cvTrace} returns the sum of the diagonal elements of the matrix \texttt{src1}.
3475
3476 \[ tr(\texttt{mat}) = \sum_i \texttt{mat}(i,i) \]
3477
3478 \cvfunc{Transpose}\label{Transpose}
3479
3480 Transposes a matrix.
3481
3482 \cvexp{
3483
3484 void cvTranspose( const CvArr* src, CvArr* dst );
3485
3486 }{CPP}{Transpose(src,dst)-> None}
3487
3488 \begin{lstlisting}
3489 #define cvT cvTranspose
3490 \end{lstlisting}
3491
3492 \begin{description}
3493 \cvarg{src}{The source matrix}
3494 \cvarg{dst}{The destination matrix}
3495 \end{description}
3496
3497 The function \texttt{cvTranspose} transposes matrix \texttt{src1}:
3498
3499 \[ \texttt{dst}(i,j) = \texttt{src}(j,i) \]
3500
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.
3504
3505 \cvfunc{Det}\label{Det}
3506
3507 Returns the determinant of a matrix.
3508
3509 \cvexp{
3510
3511 double cvDet( const CvArr* mat );
3512
3513 }{CPP}{Det(mat)-> double}
3514
3515 \begin{description}
3516 \cvarg{mat}{The source matrix}
3517 \end{description}
3518
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
3520 \cross{SVD}
3521 with $U = V = 0$ and then calculate the determinant as a product of the diagonal elements of $W$.
3522
3523 \cvfunc{Invert}\label{Invert}
3524
3525 Finds the inverse or pseudo-inverse of a matrix.
3526
3527 \cvexp{
3528
3529 double cvInvert( const CvArr* src, CvArr* dst, int method=CV\_LU );
3530
3531 }{CPP}{Invert(src,dst,method=CV\_LU)-> double}
3532 \begin{lstlisting}
3533 #define cvInv cvInvert
3534 \end{lstlisting}
3535
3536 \begin{description}
3537 \cvarg{src}{The source matrix}
3538 \cvarg{dst}{The destination matrix}
3539 \cvarg{method}{Inversion method
3540 \begin{description}
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}
3544 \end{description}}
3545 \end{description}
3546
3547 The function \texttt{cvInvert} inverts matrix \texttt{src1} and stores the result in \texttt{src2}.
3548
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.
3550
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.
3552
3553
3554 \cvfunc{Solve}\label{Solve}
3555
3556 Solves a linear system or least-squares problem.
3557
3558 \cvexp{
3559
3560 int cvSolve( const CvArr* src1, const CvArr* src2, CvArr* dst, int method=CV\_LU );
3561
3562 }{CPP}{Solve(A,B,X,method=CV\_LU)-> None}
3563
3564 \begin{description}
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
3569 \begin{description}
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.}
3573 \end{description}}
3574 \end{description}
3575
3576 The function \texttt{cvSolve} solves a linear system or least-squares problem (the latter is possible with SVD methods):
3577
3578 \[
3579 \texttt{dst} = argmin_X||\texttt{src1} \, \texttt{X} - \texttt{src2}||
3580 \]
3581
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.
3583
3584 \cvfunc{SVD}\label{SVD}
3585
3586 Performs singular value decomposition of a real floating-point matrix.
3587
3588 \cvexp{
3589
3590 void cvSVD( \par CvArr* A, \par CvArr* W, \par CvArr* U=NULL, \par CvArr* V=NULL, \par int flags=0 );
3591
3592 }{CPP}{SVD(A,flags=0)-> W,U,V}
3593
3594 \begin{description}
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:
3601 \begin{description}
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.}
3605 \end{description}}
3606 \end{description}
3607
3608 The function \texttt{cvSVD} decomposes matrix \texttt{A} into the product of a diagonal matrix and two 
3609
3610 orthogonal matrices:
3611
3612 \[
3613 A=U \, W \, V^T
3614 \]
3615
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.
3620
3621 An SVD algorithm is numerically robust and its typical applications include:
3622
3623 \begin{itemize}
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). 
3633 \end{itemize}
3634
3635 None of the applications above require calculation of the \texttt{U} and \texttt{V} matrices.
3636
3637 \cvfunc{SVBkSb}\label{SVBkSb}
3638
3639 Performs singular value back substitution.
3640
3641 \cvexp{
3642
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 );
3644
3645 }{CPP}{SVBkSb(W,U,V,B,X,flags)-> None}
3646
3647 \begin{description}
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}}
3654 \end{description}
3655
3656 The function \texttt{cvSVBkSb} calculates back substitution for decomposed matrix \texttt{A} (see \cross{SVD} description) and matrix \texttt{B}:
3657
3658 \[
3659 \texttt{X} = \texttt{V} \texttt{W}^{-1} \texttt{U}^T \texttt{B}
3660 \]
3661
3662 where
3663
3664 \[
3665 W^{-1}_{(i,i)}=
3666 \fork
3667 {1/W_{(i,i)}}{if $W_{(i,i)} > \epsilon \sum_i{W_{(i,i)}}$ }
3668 {0}{otherwise}
3669 \]
3670
3671 and $\epsilon$ is a small number that depends on the matrix data type.
3672
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).
3677
3678 \cvfunc{EigenVV}\label{EigenVV}
3679
3680 Computes eigenvalues and eigenvectors of a symmetric matrix.
3681
3682 \cvexp{
3683
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 );
3686
3687 }{CPP}{EigenVV(mat,evects,evals,eps,lowindex,highindex)-> None}
3688
3689 \begin{description}
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.
3696 (See below.)}
3697 \cvarg{highindex}{Optional index of smallest eigenvalue/-vector to calculate.
3698 (See below.)}
3699 \end{description}
3700
3701
3702 The function \texttt{cvEigenVV} computes the eigenvalues and eigenvectors of matrix \texttt{A}:
3703
3704 \begin{lstlisting}
3705 mat*evects(i,:)' = evals(i)*evects(i,:)' (in MATLAB notation)
3706 \end{lstlisting}
3707
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.
3715
3716 The contents of matrix \texttt{A} is destroyed by the function.
3717
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
3722 are not required.
3723
3724 \cvfunc{CalcCovarMatrix}\label{CalcCovarMatrix}
3725
3726 Calculates covariance matrix of a set of vectors.
3727
3728 \cvexp{
3729
3730 void cvCalcCovarMatrix( \par const CvArr** vects,\par int count,\par CvArr* cov\_mat,\par CvArr* avg,\par int flags );
3731
3732 }{CPP}{CalcCovarMatrix(vects,cov\_mat,avg,flags)-> None}
3733
3734 \begin{description}
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
3740 \begin{description}
3741 \cvarg{CV\_COVAR\_SCRAMBLED}{The output covariance matrix is calculated as:
3742 \[
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} ,...] 
3744 \],
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:
3754 \[
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 
3756 \],
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').}
3763
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.}
3766
3767 \end{description}}
3768 \end{description}
3769
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.
3773
3774 \cvfunc{Mahalonobis}\label{Mahalonobis}
3775
3776 Calculates the Mahalonobis distance between two vectors.
3777
3778 \cvexp{
3779
3780 double cvMahalanobis( \par const CvArr* vec1,\par const CvArr* vec2,\par CvArr* mat );
3781
3782 }{CPP}{Mahalonobis(vec1,vec2,mat)-> None}
3783
3784 \begin{description}
3785 \cvarg{vec1}{The first 1D source vector}
3786 \cvarg{vec2}{The second 1D source vector}
3787 \cvarg{mat}{The inverse covariance matrix}
3788 \end{description}
3789
3790
3791 The function \texttt{cvMahalonobis} calculates and returns the weighted distance between two vectors:
3792
3793 \begin{lstlisting}
3794
3795 d(vec1,vec2)=sqrt( sum,,i,j,, {mat(i,j)*(vec1(i)-vec2(i))*(vec1(j)-vec2(j))} )
3796
3797 \end{lstlisting}
3798
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).
3800
3801
3802 \subsection{Math Functions}
3803
3804 \cvfunc{Round, Floor, Ceil}\label{Round, Floor, Ceil}
3805
3806 Converts a floating-point number to an integer.
3807
3808 \cvexp{
3809
3810 int cvRound( double value );
3811 int cvFloor( double value );
3812 int cvCeil( double value );
3813
3814 }{CPP}{Round, Floor, Ceil(value)-> int}
3815
3816 \begin{description}
3817 \cvarg{value}{The input floating-point value}
3818 \end{description}
3819
3820
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)
3830 are not handled.
3831
3832 \cvfunc{Sqrt}\label{Sqrt}
3833
3834 Calculates the square root.
3835
3836 \cvexp{
3837
3838 float cvSqrt( float value );
3839
3840 }{CPP}{Sqrt(value)-> float}
3841
3842 \begin{description}
3843 \cvarg{value}{The input floating-point value}
3844 \end{description}
3845
3846
3847 The function \texttt{cvSqrt} calculates the square root of the argument. If the argument is negative, the result is not determined.
3848
3849 \cvfunc{InvSqrt}\label{InvSqrt}
3850
3851 Calculates the inverse square root.
3852
3853 \cvexp{
3854
3855 float cvInvSqrt( float value );
3856
3857 }{CPP}{InvSqrt(value)-> float}
3858
3859 \begin{description}
3860 \cvarg{value}{The input floating-point value}
3861 \end{description}
3862
3863
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.
3865
3866 \cvfunc{Cbrt}\label{Cbrt}
3867
3868 Calculates the cubic root
3869
3870 \cvexp{
3871
3872 float cvCbrt( float value );
3873
3874 }{CPP}{Cbrt(value)-> float}
3875
3876 \begin{description}
3877 \cvarg{value}{The input floating-point value}
3878 \end{description}
3879
3880
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.
3882
3883 \cvfunc{FastArctan}\label{FastArctan}
3884
3885 Calculates the angle of a 2D vector.
3886
3887 \cvexp{
3888
3889 float cvFastArctan( float y, float x );
3890
3891 }{CPP}{FastArctan(y,x)-> float}
3892
3893 \begin{description}
3894 \cvarg{x}{x-coordinate of 2D vector}
3895 \cvarg{y}{y-coordinate of 2D vector}
3896 \end{description}
3897
3898
3899 The function \texttt{cvFastArctan} calculates the full-range angle of an input 2D vector. The angle is 
3900
3901 measured in degrees and varies from 0 degrees to 360 degrees . The accuracy is about 0.1 degrees.
3902
3903 \cvfunc{IsNaN}\label{IsNaN}
3904
3905 Determines if the argument is Not A Number.
3906
3907 \cvexp{
3908
3909 int cvIsNaN( double value );
3910
3911 }{CPP}{IsNaN(value)-> int}
3912
3913 \begin{description}
3914 \cvarg{value}{The input floating-point value}
3915 \end{description}
3916
3917
3918 The function \texttt{cvIsNaN} returns 1 if the argument is Not A Number (as defined by IEEE754 standard), 0 otherwise.
3919
3920
3921 \cvfunc{IsInf}\label{IsInf}
3922
3923 Determines if the argument is Infinity.
3924
3925 \cvexp{
3926
3927 int cvIsInf( double value );
3928
3929 }{CPP}{IsInf(value)-> int}
3930
3931 \begin{description}
3932 \cvarg{value}{The input floating-point value}
3933 \end{description}
3934
3935
3936 The function \texttt{cvIsInf} returns 1 if the argument is $ \pm \infty $ (as defined by IEEE754 standard), 0 otherwise.
3937
3938
3939 \cvfunc{CartToPolar}\label{CartToPolar}
3940
3941 Calculates the magnitude and/or angle of 2d vectors.
3942
3943 \cvexp{
3944
3945 void cvCartToPolar( \par const CvArr* x,\par const CvArr* y,\par CvArr* magnitude,\par CvArr* angle=NULL,\par int angle\_in\_degrees=0 );
3946
3947 }{CPP}{CartToPolar(x,y,magnitude,angle=NULL,angle\_in\_degrees)-> None}
3948
3949 \begin{description}
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}
3955 \end{description}
3956
3957 The function \texttt{cvCartToPolar} calculates either the magnitude, angle, or both of every 2d vector (x(I),y(I)):
3958
3959 \begin{lstlisting}
3960
3961 magnitude(I)=sqrt( x(I)^2^+y(I)^2^ ),
3962 angle(I)=atan( y(I)/x(I) )
3963
3964 \end{lstlisting}
3965
3966 The angles are calculated with 0.1 degree accuracy. For the (0,0) point, the angle is set to 0.
3967
3968 \cvfunc{PolarToCart}\label{PolarToCart}
3969
3970 Calculates Cartesian coordinates of 2d vectors represented in polar form.
3971
3972 \cvexp{
3973
3974 void cvPolarToCart( \par const CvArr* magnitude,\par const CvArr* angle,\par CvArr* x,\par CvArr* y,\par int angle\_in\_degrees=0 );
3975
3976 }{CPP}{PolarToCart(magnitude,angle=NULL,x,y,angle\_in\_degrees)-> None}
3977
3978 \begin{description}
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}
3984 \end{description}
3985
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)}:
3987
3988 \begin{lstlisting}
3989
3990 x(I)=magnitude(I)*cos(angle(I)),
3991 y(I)=magnitude(I)*sin(angle(I))
3992
3993 \end{lstlisting}
3994
3995
3996 \cvfunc{Pow}\label{Pow}
3997
3998 Raises every array element to a power.
3999
4000 \cvexp{
4001
4002 void cvPow( \par const CvArr* src,\par CvArr* dst,\par double power );
4003
4004 }{CPP}{Pow(src,dst,power)-> None}
4005
4006 \begin{description}
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}
4010 \end{description}
4011
4012
4013 The function \texttt{cvPow} raises every element of the input array to \texttt{p}:
4014
4015 \[
4016 \texttt{dst} [I] = \fork
4017 {\texttt{src}(I)^p}{if \texttt{p} is integer}
4018 {|\texttt{src}(I)^p|}{otherwise}
4019 \]
4020
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:
4022
4023 \begin{lstlisting}
4024
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 );
4031
4032 \end{lstlisting}
4033
4034 For some values of \texttt{power}, such as integer values, 0.5, and -0.5, specialized faster algorithms are used.
4035
4036 \cvfunc{Exp}\label{Exp}
4037
4038 Calculates the exponent of every array element.
4039
4040 \cvexp{
4041
4042 void cvExp( const CvArr* src, CvArr* dst );
4043
4044 }{CPP}{Exp(src,dst)-> None}
4045
4046 \begin{description}
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}
4049 \end{description}
4050
4051
4052 The function \texttt{cvExp} calculates the exponent of every element of the input array:
4053
4054 \[
4055 \texttt{dst} [I] = e^{\texttt{src}(I)}
4056 \]
4057
4058 The maximum relative error is about $7 \times 10^{-6}$. Currently, the function converts denormalized values to zeros on output.
4059
4060 \cvfunc{Log}\label{Log}
4061
4062 Calculates the natural logarithm of every array element's absolute value.
4063
4064 \cvexp{
4065
4066 void cvLog( const CvArr* src, CvArr* dst );
4067
4068 }{CPP}{Log(src,dst)-> None}
4069
4070 \begin{description}
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}
4073 \end{description}
4074
4075 The function \texttt{cvLog} calculates the natural logarithm of the absolute value of every element of the input array:
4076
4077 \[
4078 \texttt{dst} [I] = \fork
4079 {\log{|\texttt{src}(I)}}{if $\texttt{src}[I] \ne 0$ }
4080 {\texttt{C}}{otherwise}
4081 \]
4082
4083 Where \texttt{C} is a large negative number ( about -700 in the current implementation).
4084
4085 \cvfunc{SolveCubic}\label{SolveCubic}
4086
4087 Finds the real roots of a cubic equation.
4088
4089 \cvexp{
4090
4091 void cvSolveCubic( const CvArr* coeffs, CvArr* roots );
4092
4093 }{CPP}{SolveCubic(coeffs,roots)-> None}
4094
4095 \begin{description}
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}
4098 \end{description}
4099
4100 The function \texttt{cvSolveCubic} finds the real roots of a cubic equation:
4101
4102 If coeffs is a 4-element vector:
4103
4104 \[
4105 \texttt{coeffs}[0] x^3 + \texttt{coeffs}[1] x^2 + \texttt{coeffs}[2] x + \texttt{coeffs}[3] = 0
4106 \]
4107
4108 or if coeffs is 3-element vector:
4109
4110 \[
4111 x^3 + \texttt{coeffs}[0] x^2 + \texttt{coeffs}[1] x + \texttt{coeffs}[2] = 0
4112 \]
4113
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
4116 only one root.
4117
4118 \subsection{Random Number Generation}
4119
4120 \cvfunc{RNG}\label{RNG}
4121
4122 Initializes a random number generator state.
4123
4124 \cvexp{
4125
4126 CvRNG cvRNG( int64 seed=-1 );
4127
4128 }{CPP}{RNG(seed=-1LL)-> CvRNG}
4129
4130 \begin{description}
4131 \cvarg{seed}{64-bit value used to initiate a random sequence}
4132 \end{description}
4133
4134
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.
4139
4140 \cvfunc{RandArr}\label{RandArr}
4141
4142 Fills an array with random numbers and updates the RNG state.
4143
4144 \cvexp{
4145
4146 void cvRandArr( \par CvRNG* rng,\par CvArr* arr,\par int dist\_type,\par CvScalar param1,\par CvScalar param2 );
4147
4148 }{CPP}{RandArr(rng,arr,dist\_type,param1,param2)-> None}
4149
4150 \begin{description}
4151 \cvarg{rng}{RNG state initialized by \cross{RNG}}
4152 \cvarg{arr}{The destination array}
4153 \cvarg{dist\_type}{Distribution type
4154 \begin{description}
4155 \cvarg{CV\_RAND\_UNI}{uniform distribution}
4156 \cvarg{CV\_RAND\_NORMAL}{normal or Gaussian distribution}
4157 \end{description}}
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.}
4160 \end{description}
4161
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.
4166
4167 \begin{lstlisting}
4168
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 );
4177
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 */ );
4182
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) );
4186
4187 /* modify RNG to make it produce normally distributed values */
4188 rng_state.disttype = CV_RAND_NORMAL;
4189 cvRandSetRange( &rng_state,
4190                 30 /* deviation */,
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
4197            );
4198
4199 /* set the points */
4200 for( i = 0; i < pointCount; i++ )
4201 {
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;
4205 }
4206
4207 /* not to forget to release the temporary arrays */
4208 cvReleaseMat( &locations );
4209 cvReleaseMat( &values );
4210
4211 /* RNG state does not need to be deallocated */
4212
4213 \end{lstlisting}
4214
4215 \cvfunc{RandInt}\label{RandInt}
4216
4217 Returns a 32-bit unsigned integer and updates RNG.
4218
4219 \cvexp{
4220
4221 unsigned cvRandInt( CvRNG* rng );
4222
4223 }{CPP}{RandInt(rng)-> unsigned}
4224
4225 \begin{description}
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)}
4227 \end{description}
4228
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.
4234
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
4240 \cross{RandInt}:
4241
4242 \begin{lstlisting}
4243
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 );
4253 int valuesLeft = 0;
4254
4255 for( i = 0; i < pointCount; i++ )
4256 {
4257     CvPoint pt;
4258     /* generate random point */
4259     pt.x = cvRandInt( &rnggstate ) % size.width;
4260     pt.y = cvRandInt( &rnggstate ) % size.height;
4261
4262     if( valuesLeft <= 0 )
4263     {
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;
4269     }
4270     *((float*)cvPtr2D( noisygscreen, pt.y, pt.x, 0 ) = 
4271                                 normalValueBuffer[--valuesLeft];
4272 }
4273
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 */
4277
4278 \end{lstlisting}
4279
4280 \cvfunc{RandReal}\label{RandReal}
4281
4282 Returns a floating-point random number and updates RNG.
4283
4284 \cvexp{
4285
4286 double cvRandReal( CvRNG* rng );
4287
4288 }{CPP}{RandReal(rng)-> double}
4289
4290 \begin{description}
4291 \cvarg{rng}{RNG state initialized by \cross{RNG}}
4292 \end{description}
4293
4294
4295 The function \texttt{cvRandReal} returns a uniformly-distributed random floating-point number between 0 and 1 (1 is not included).
4296
4297 \subsection{Discrete Transforms}
4298
4299 \cvfunc{DFT}\label{DFT}
4300
4301 Performs a forward or inverse Discrete Fourier transform of a 1D or 2D floating-point array.
4302
4303 \cvexp{
4304
4305 void cvDFT( const CvArr* src, CvArr* dst, int flags, int nonzero\_rows=0 );
4306
4307 }{CPP}{DFT(src,dst,flags,nonzero\_rows=0)-> None}
4308
4309 \begin{lstlisting}
4310
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
4317
4318 \end{lstlisting}
4319
4320 \begin{description}
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
4324 \begin{description}
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.
4329 \end{description}}
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.}
4336 \end{description}
4337
4338 The function \texttt{cvDFT} performs a forward or inverse transform of a 1D or 2D floating-point array:
4339
4340
4341
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)\], 
4344 \[i=sqrt(-1)\]
4345
4346 Inverse Fourier transform of 1D vector of N elements:
4347 \[x'= (F^{(N)})^{-1} \cdot y = conj(F^(N)) \cdot y
4348 x = (1/N) \cdot x\]
4349
4350 Forward Fourier transform of 2D vector of M $\times$ N elements:
4351 \[Y = F^{(M)} \cdot X \cdot F^{(N)}\]
4352
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'\]
4356
4357
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:
4359
4360
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}\]
4362
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}\]
4364
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}\]
4370
4371
4372 Note: the last column is present if \texttt{N} is even, the last row is present if \texttt{M} is even.
4373
4374 In the case of 1D real transform the result looks like the first row of the above matrix
4375
4376 Computing 2D Convolution using DFT
4377
4378 \begin{lstlisting}
4379
4380 CvMat* A = cvCreateMat( M1, N1, CVg32F );
4381 CvMat* B = cvCreateMat( M2, N2, A->type );
4382
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, 
4386                            A->type );
4387
4388 // initialize A and B
4389 ...
4390
4391 int dftgM = cvGetOptimalDFTSize( A->rows + B->rows - 1 );
4392 int dftgN = cvGetOptimalDFTSize( A->cols + B->cols - 1 );
4393
4394 CvMat* dftgA = cvCreateMat( dft\_M, dft\_N, A->type );
4395 CvMat* dftgB = cvCreateMat( dft\_M, dft\_N, B->type );
4396 CvMat tmp;
4397
4398 // copy A to dftgA and pad dft\_A with zeros
4399 cvGetSubRect( dftgA, &tmp, cvRect(0,0,A->cols,A->rows));
4400 cvCopy( A, &tmp );
4401 cvGetSubRect( dftgA, &tmp, cvRect(A->cols,0,dft\_A->cols - A->cols,A->rows));
4402 cvZero( &tmp );
4403 // no need to pad bottom part of dftgA with zeros because of
4404 // use nonzerogrows parameter in cvDFT() call below
4405
4406 cvDFT( dftgA, dft\_A, CV\_DXT\_FORWARD, A->rows );
4407
4408 // repeat the same with the second array
4409 cvGetSubRect( dftgB, &tmp, cvRect(0,0,B->cols,B->rows));
4410 cvCopy( B, &tmp );
4411 cvGetSubRect( dftgB, &tmp, cvRect(B->cols,0,dft\_B->cols - B->cols,B->rows));
4412 cvZero( &tmp );
4413 // no need to pad bottom part of dftgB with zeros because of
4414 // use nonzerogrows parameter in cvDFT() call below
4415
4416 cvDFT( dftgB, dft\_B, CV\_DXT\_FORWARD, B->rows );
4417
4418 cvMulSpectrums( dftgA, dft\_B, dft\_A, 0 /* or CV\_DXT\_MUL\_CONJ to get 
4419                 correlation rather than convolution */ );
4420
4421 cvDFT( dftgA, dft\_A, CV\_DXT\_INV\_SCALE, conv->rows ); // calculate only 
4422                                                          // the top part
4423 cvGetSubRect( dftgA, &tmp, cvRect(0,0,conv->cols,conv->rows) );
4424
4425 cvCopy( &tmp, conv );
4426
4427 \end{lstlisting}
4428
4429 \cvfunc{GetOptimalDFTSize}\label{GetOptimalDFTSize}
4430
4431 Returns optimal DFT size for a given vector size.
4432
4433 \cvexp{
4434
4435 int cvGetOptimalDFTSize( int size0 );
4436
4437 }{CPP}{GetOptimalDFTSize(size0)-> int}
4438
4439 \begin{description}
4440 \cvarg{size0}{Vector size}
4441 \end{description}
4442
4443
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$.
4448
4449 The function returns a negative number if \texttt{size0} is too large
4450 (very close to \texttt{INT\_MAX})
4451
4452
4453 \cvfunc{MulSpectrums}\label{MulSpectrums}
4454
4455 Performs per-element multiplication of two Fourier spectrums.
4456
4457 \cvexp{
4458
4459 void cvMulSpectrums( \par const CvArr* src1,\par const CvArr* src2,\par CvArr* dst,\par int flags );
4460
4461 }{CPP}{MulSpectrums(src1,src2,dst,flags)-> None)}
4462
4463 \begin{description}
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;
4468 \begin{description}
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.}
4471 \end{description}}
4472
4473 \end{description}
4474
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.
4476
4477 The function, together with \cross{DFT}, may be used to calculate convolution of two arrays rapidly.
4478
4479
4480 \cvfunc{DCT}\label{DCT}
4481
4482 Performs a forward or inverse Discrete Cosine transform of a 1D or 2D floating-point array.
4483
4484 \cvexp{
4485
4486 void cvDCT( const CvArr* src, CvArr* dst, int flags );
4487
4488 }{CPP}{DCT(src,dst,flags)-> None}
4489
4490 \begin{lstlisting}
4491
4492 #define CV\_DXT\_FORWARD  0
4493 #define CV\_DXT\_INVERSE  1
4494 #define CV\_DXT\_ROWS     4
4495
4496 \end{lstlisting}
4497
4498 \begin{description}
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
4502 \begin{description}
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.}
4506 \end{description}}
4507 \end{description}
4508
4509 The function \texttt{cvDCT} performs a forward or inverse transform of a 1D or 2D floating-point array:
4510
4511 \begin{lstlisting}
4512
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)
4515
4516 Inverse Cosine transform of 1D vector of N elements:
4517 x = (C^(N)^)^-1^ \cdot y = (C^(N)^)^T^ \cdot y
4518
4519 Forward Cosine transform of 2D vector of M \times N elements:
4520 Y = (C^(M)^) \cdot X \cdot (C^(N)^)^T^
4521
4522 Inverse Cosine transform of 2D vector of M \times N elements:
4523 X = (C^(M)^)^T^ \cdot Y \cdot C^(N)^
4524
4525 \end{lstlisting}
4526
4527
4528 \section{Dynamic Structures}
4529
4530 \subsection{Memory Storages}
4531
4532 \ifPython
4533 \cvfunc{CreateMemStorage}\label{CreateMemStorage}
4534
4535 Creates memory storage.
4536
4537 \cvexp{C}{CPP}{CreateMemStorage(block\_size) -> memstorage}
4538
4539 \begin{description}
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.}
4541 \end{description}
4542
4543 The function \texttt{cvCreateMemStorage} creates an empty memory storage object.
4544
4545 \fi
4546
4547 \ifC
4548 \cvstruct{CvMemStorage}\label{CvMemStorage}
4549
4550 Growing memory storage.
4551
4552 \begin{lstlisting}
4553
4554 typedef struct CvMemStorage
4555 {
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) */
4561 } CvMemStorage;
4562
4563 \end{lstlisting}
4564
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}.
4575
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.
4585
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}.
4593
4594 \cvstruct{CvMemBlock}\label{CvMemBlock}
4595
4596 Memory storage block.
4597
4598 \begin{lstlisting}
4599
4600 typedef struct CvMemBlock
4601 {
4602     struct CvMemBlock* prev;
4603     struct CvMemBlock* next;
4604 } CvMemBlock;
4605
4606 \end{lstlisting}
4607
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.
4613
4614 \cvstruct{CvMemStoragePos}\label{CvMemStoragePos}
4615
4616 Memory storage position.
4617
4618 \begin{lstlisting}
4619
4620 typedef struct CvMemStoragePos
4621 {
4622     CvMemBlock* top;
4623     int free\_space;
4624 } CvMemStoragePos;
4625
4626 \end{lstlisting}
4627
4628 The structure described above stores the position of the stack top that can be saved via \cross{SaveMemStoragePos} and restored via \cross{RestoreMemStoragePos}.
4629
4630 \cvfunc{CreateMemStorage}\label{CreateMemStorage}
4631
4632 Creates memory storage.
4633
4634 \cvexp{
4635
4636 CvMemStorage* cvCreateMemStorage( int block\_size=0 );
4637
4638 }{CPP}{PYTHON}
4639
4640 \begin{description}
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.}
4642 \end{description}
4643
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.
4645
4646
4647 \cvfunc{CreateChildMemStorage}\label{CreateChildMemStorage}
4648
4649 Creates child memory storage.
4650
4651 \cvexp{
4652
4653 CvMemStorage* cvCreateChildMemStorage( CvMemStorage* parent );
4654
4655 }{CPP}{PYTHON}
4656
4657 \begin{description}
4658 \cvarg{parent}{Parent memory storage}
4659 \end{description}
4660
4661
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.
4674
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:
4680
4681 Dynamic data processing without using child storage
4682
4683 \includegraphics[width=0.5\textwidth]{pics/memstorage1.png}
4684
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:
4689
4690 Dynamic data processing using a child storage
4691
4692 \includegraphics[width=0.5\textwidth]{pics/memstorage2.png}
4693
4694 \cvfunc{ReleaseMemStorage}\label{ReleaseMemStorage}
4695
4696 Releases memory storage.
4697
4698 \cvexp{
4699
4700 void cvReleaseMemStorage( CvMemStorage** storage );
4701
4702 }{CPP}{PYTHON}
4703
4704 \begin{description}
4705 \cvarg{storage}{Pointer to the released storage}
4706 \end{description}
4707
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.
4713
4714 \cvfunc{ClearMemStorage}\label{ClearMemStorage}
4715
4716 Clears memory storage.
4717
4718 \cvexp{
4719
4720 void cvClearMemStorage( CvMemStorage* storage );
4721
4722 }{CPP}{PYTHON}
4723
4724 \begin{description}
4725 \cvarg{storage}{Memory storage}
4726 \end{description}
4727
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.
4732
4733 \cvfunc{MemStorageAlloc}\label{MemStorageAlloc}
4734
4735 Allocates a memory buffer in a storage block.
4736
4737 \cvexp{
4738
4739 void* cvMemStorageAlloc( \par CvMemStorage* storage,\par size\_t size );
4740
4741 }{CPP}{PYTHON}
4742
4743 \begin{description}
4744 \cvarg{storage}{Memory storage}
4745 \cvarg{size}{Buffer size}
4746 \end{description}
4747
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.
4752
4753 \cvfunc{MemStorageAllocString}\label{MemStorageAllocString}
4754
4755 Allocates a text string in a storage block.
4756
4757 \cvexp{
4758
4759 CvString cvMemStorageAllocString( CvMemStorage* storage, const char* ptr, int len=-1 );
4760
4761 }{CPP}{PYTHON}
4762
4763 \begin{lstlisting}
4764
4765 typedef struct CvString
4766 {
4767     int len;
4768     char* ptr;
4769 }
4770 CvString;
4771
4772 \end{lstlisting}
4773
4774 \begin{description}
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.}
4778 \end{description}
4779
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.
4783
4784 \cvfunc{SaveMemStoragePos}\label{SaveMemStoragePos}
4785
4786 Saves memory storage position.
4787
4788 \cvexp{
4789
4790 void cvSaveMemStoragePos( \par const CvMemStorage* storage,\par CvMemStoragePos* pos );
4791
4792 }{CPP}{PYTHON}
4793
4794 \begin{description}
4795 \cvarg{storage}{Memory storage}
4796 \cvarg{pos}{The output position of the storage top}
4797 \end{description}
4798
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.
4802
4803 \cvfunc{RestoreMemStoragePos}\label{RestoreMemStoragePos}
4804
4805 Restores memory storage position.
4806
4807 \cvexp{
4808
4809 void cvRestoreMemStoragePos( \par CvMemStorage* storage,\par CvMemStoragePos* pos );
4810
4811 }{CPP}{PYTHON}
4812
4813 \begin{description}
4814 \cvarg{storage}{Memory storage}
4815 \cvarg{pos}{New storage top position}
4816 \end{description}
4817
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.
4819 \fi
4820
4821 \subsection{Sequences}
4822
4823 \cvstruct{CvSeq}\label{CvSeq}
4824
4825 Growable sequence of elements.
4826
4827 \ifPython
4828 Many OpenCV functions return a CvSeq object.  The CvSeq obect is a sequence, so these are all legal:
4829 \begin{lstlisting}
4830 seq = cv.FindContours(scribble, storage, cv.CV_RETR_CCOMP, cv.CV_CHAIN_APPROX_SIMPLE)
4831 # seq is a sequence of point pairs
4832 print `len'(seq)
4833 # FindContours returns a sequence of (x,y) points, so to print them out:
4834 for (x,y) in seq:
4835    print (x,y)
4836 print seq[10]            # tenth entry in the seqeuence
4837 print seq[::-1]          # reversed sequence
4838 print sorted(list(seq))  # sorted sequence
4839 \end{lstlisting}
4840
4841 Also, a CvSeq object has methods
4842 \texttt{h_next()},
4843 \texttt{h_prev()},
4844 \texttt{v_next()} and
4845 \texttt{v_prev()}.
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}.
4848
4849 \fi
4850
4851 \ifC
4852 \begin{lstlisting}
4853
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 */
4870
4871 typedef struct CvSeq
4872 {
4873     CV_SEQUENCE_FIELDS()
4874 } CvSeq;
4875
4876 \end{lstlisting}
4877
4878 The structure \cross{CvSeq} is a base for all of OpenCV dynamic data structures.
4879
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()}.
4885
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.
4895
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)}.
4898
4899 The fields
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
4907 different way.
4908
4909 The field \texttt{first} points to the first sequence block, whose structure is described below.
4910
4911 The field \texttt{total} contains the actual number of dense sequence elements and number of allocated nodes in a sparse sequence.
4912
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:
4928
4929 Standard Types of Sequence Elements
4930
4931 \begin{lstlisting}
4932
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, 
4945                                                                    &(x,y) */
4946 #define CV_SEQ_ELTYPE_TRIAN_ATR      CV_SEQ_ELTYPE_GENERIC  /* vertex of the 
4947                                                             binary tree   */
4948 #define CV_SEQ_ELTYPE_CONNECTED_COMP CV_SEQ_ELTYPE_GENERIC  /* connected 
4949                                                                component  */
4950 #define CV_SEQ_ELTYPE_POINT3D        CV_32FC3  /* (x,y,z)  */
4951
4952 \end{lstlisting}
4953
4954 The next \texttt{CV\_SEQ\_KIND\_BITS} bits specify the kind of sequence:
4955
4956 Standard Kinds of Sequences
4957
4958 \begin{lstlisting}
4959
4960 /* generic (unspecified) kind of sequence */
4961 #define CV_SEQ_KIND_GENERIC     (0 << CV_SEQ_ELTYPE_BITS)
4962
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)
4966
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)
4970
4971 \end{lstlisting}
4972
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.
4984
4985 \cvstruct{CvSeqBlock}\label{CvSeqBlock}
4986
4987 Continuous sequence block.
4988
4989 \begin{lstlisting}
4990
4991 typedef struct CvSeqBlock
4992 {
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 */
4999 } CvSeqBlock;
5000
5001 \end{lstlisting}
5002
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
5012 blocks are
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.
5017
5018 \cvstruct{CvSlice}\label{CvSlice}
5019
5020 A sequence slice.
5021
5022 \begin{lstlisting}
5023
5024 typedef struct CvSlice
5025 {
5026     int start_index;
5027     int end_index;
5028 } CvSlice;
5029
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)
5033
5034 /* calculates the sequence slice length */
5035 int cvSliceLength( CvSlice slice, const CvSeq* seq );
5036
5037 \end{lstlisting}
5038
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).
5057
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}).
5063
5064 \cvfunc{CreateSeq}\label{CreateSeq}
5065
5066 Creates a sequence.
5067
5068 \cvexp{
5069
5070 CvSeq* cvCreateSeq( \par int seq\_flags,\par int header\_size,\par int elem\_size,\par CvMemStorage* storage );
5071
5072 }{CPP}{PYTHON}
5073
5074 \begin{description}
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}
5079 \end{description}
5080
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.
5089
5090 \cvfunc{SetSeqBlockSize}\label{SetSeqBlockSize}
5091
5092 Sets up sequence block size.
5093
5094 \cvexp{
5095
5096 void cvSetSeqBlockSize( \par CvSeq* seq,\par int delta\_elems );
5097
5098 }{CPP}{PYTHON}
5099
5100 \begin{description}
5101 \cvarg{seq}{Sequence}
5102 \cvarg{delta\_elems}{Desirable sequence block size for elements}
5103 \end{description}
5104
5105
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
5117 constraints.
5118
5119 \cvfunc{SeqPush}\label{SeqPush}
5120
5121 Adds an element to the end of a sequence.
5122
5123 \cvexp{
5124
5125 char* cvSeqPush( \par CvSeq* seq,\par void* element=NULL );
5126
5127 }{CPP}{PYTHON}
5128
5129 \begin{description}
5130 \cvarg{seq}{Sequence}
5131 \cvarg{element}{Added element}
5132 \end{description}
5133
5134
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.
5136
5137 The following code demonstrates how to create a new sequence using this function:
5138
5139 \begin{lstlisting}
5140
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 */ );
5146 int i;
5147 for( i = 0; i < 100; i++ )
5148 {
5149     int* added = (int*)cvSeqPush( seq, &i );
5150     printf( "%d is added\n", *added );
5151 }
5152
5153 ...
5154 /* release memory storage in the end */
5155 cvReleaseMemStorage( &storage );
5156
5157 \end{lstlisting}
5158
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).
5160
5161
5162 \cvfunc{SeqPop}\label{SeqPop}
5163
5164 Removes an element from the end of a sequence.
5165
5166 \cvexp{
5167
5168 void cvSeqPop( \par CvSeq* seq,\par void* element=NULL );
5169
5170 }{CPP}{PYTHON}
5171
5172 \begin{description}
5173 \cvarg{seq}{Sequence}
5174 \cvarg{element}{Optional parameter . If the pointer is not zero, the function copies the removed element to this location.}
5175 \end{description}
5176
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.
5178
5179 \cvfunc{SeqPushFront}\label{SeqPushFront}
5180
5181 Adds an element to the beginning of a sequence.
5182
5183 \cvexp{
5184
5185 char* cvSeqPushFront( CvSeq* seq, void* element=NULL );
5186
5187 }{CPP}{PYTHON}
5188
5189 \begin{description}
5190 \cvarg{seq}{Sequence}
5191 \cvarg{element}{Added element}
5192 \end{description}
5193
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.
5195
5196 \cvfunc{SeqPopFront}\label{SeqPopFront}
5197
5198 Removes an element from the beginning of a sequence.
5199
5200 \cvexp{
5201
5202 void cvSeqPopFront( \par \par CvSeq* seq,\par\par void* element=NULL );
5203
5204 }{CPP}{PYTHON}
5205
5206 \begin{description}
5207 \cvarg{seq}{Sequence}
5208 \cvarg{element}{Optional parameter. If the pointer is not zero, the function copies the removed element to this location.}
5209 \end{description}
5210
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.
5212
5213 \cvfunc{SeqPushMulti}\label{SeqPushMulti}
5214
5215 Pushes several elements to either end of a sequence.
5216
5217 \cvexp{
5218
5219 void cvSeqPushMulti( \par CvSeq* seq,\par void* elements,\par int count,\par int in\_front=0 );
5220
5221 }{CPP}{PYTHON}
5222
5223 \begin{description}
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.
5228 \begin{description}
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}
5231 \end{description}}
5232 \end{description}
5233
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.
5238
5239 \cvfunc{SeqPopMulti}\label{SeqPopMulti}
5240
5241 Removes several elements from either end of a sequence.
5242
5243 \cvexp{
5244
5245 void cvSeqPopMulti( \par CvSeq* seq,\par void* elements,\par int count,\par int in\_front=0 );
5246
5247 }{CPP}{PYTHON}
5248
5249 \begin{description}
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.
5254 \begin{description}
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}
5257 \end{description}}
5258 \end{description}
5259
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.
5261
5262 \cvfunc{SeqInsert}\label{SeqInsert}
5263
5264 Inserts an element in the middle of a sequence.
5265
5266 \cvexp{
5267
5268 char* cvSeqInsert( \par CvSeq* seq,\par int before\_index,\par void* element=NULL );
5269
5270 }{CPP}{PYTHON}
5271
5272 \begin{description}
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} 
5276 \end{description}
5277
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.
5279 \fi
5280
5281 \cvfunc{SeqRemove}\label{SeqRemove}
5282
5283 Removes an element from the middle of a sequence.
5284
5285 \cvexp{
5286
5287 void cvSeqRemove( \par CvSeq* seq,\par int index );
5288
5289 }{CPP}{SeqRemove(seq,index)-> None}
5290
5291 \begin{description}
5292 \cvarg{seq}{Sequence}
5293 \cvarg{index}{Index of removed element}
5294 \end{description}
5295
5296
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.
5303
5304
5305 \cvfunc{ClearSeq}\label{ClearSeq}
5306
5307 Clears a sequence.
5308
5309 \cvexp{
5310
5311 void cvClearSeq( CvSeq* seq );
5312
5313 }{CPP}{ClearSeq(seq)-> None}
5314
5315 \begin{description}
5316 \cvarg{seq}{Sequence}
5317 \end{description}
5318
5319
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.
5324
5325 \ifC
5326 \cvfunc{GetSeqElem}\label{GetSeqElem}
5327
5328 Returns a pointer to a sequence element according to its index.
5329
5330 \cvexp{
5331
5332 char* cvGetSeqElem( const CvSeq* seq, int index );
5333
5334 }{CPP}{PYTHON}
5335
5336 \begin{lstlisting}
5337 #define CV_GET_SEQ_ELEM( TYPE, seq, index )  (TYPE*)cvGetSeqElem( (CvSeq*)(seq), (index) )
5338 \end{lstlisting}
5339
5340 \begin{description}
5341 \cvarg{seq}{Sequence}
5342 \cvarg{index}{Index of element}
5343 \end{description}
5344
5345
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
5362 number of elements.
5363
5364 \cvfunc{SeqElemIdx}\label{SeqElemIdx}
5365
5366 Returns the index of a specific sequence element.
5367
5368 \cvexp{
5369
5370 int cvSeqElemIdx( \par const CvSeq* seq,\par const void* element,\par CvSeqBlock** block=NULL );
5371
5372 }{CPP}{PYTHON}
5373
5374 \begin{description}
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.}
5378 \end{description}
5379
5380 The function \texttt{cvSeqElemIdx} returns the index of a sequence element or a negative number if the element is not found.
5381
5382 \cvfunc{CvtSeqToArray}\label{CvtSeqToArray}
5383
5384 Copies a sequence to one continuous block of memory.
5385
5386 \cvexp{
5387
5388 void* cvCvtSeqToArray( \par const CvSeq* seq,\par void* elements,\par CvSlice slice=CV\_WHOLE\_SEQ );
5389
5390 }{CPP}{PYTHON}
5391
5392 \begin{description}
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}
5396 \end{description}
5397
5398
5399 The function \texttt{cvCvtSeqToArray} copies the entire sequence or subsequence to the specified buffer and returns the pointer to the buffer.
5400
5401
5402 \cvfunc{MakeSeqHeaderForArray}\label{MakeSeqHeaderForArray}
5403
5404 Constructs a sequence header for an array.
5405
5406 \cvexp{
5407
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 );
5409
5410 }{CPP}{PYTHON}
5411
5412 \begin{description}
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}
5420 \end{description}
5421
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
5428 most cases.
5429
5430 \cvfunc{SeqSlice}\label{SeqSlice}
5431
5432 Makes a separate header for a sequence slice.
5433
5434 \cvexp{
5435
5436 CvSeq* cvSeqSlice( \par const CvSeq* seq,\par CvSlice slice,\par CvMemStorage* storage=NULL,\par int copy\_data=0 );
5437
5438 }{CPP}{PYTHON}
5439
5440 \begin{description}
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})}
5445 \end{description}
5446
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.
5448
5449 \fi
5450
5451 \cvfunc{CloneSeq}\label{CloneSeq}
5452
5453 Creates a copy of a sequence.
5454
5455 \cvexp{
5456
5457 CvSeq* cvCloneSeq( \par const CvSeq* seq,\par CvMemStorage* storage=NULL );
5458
5459 }{CPP}{CloneSeq(seq,storage)-> None}
5460
5461 \begin{description}
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.} 
5464 \end{description}
5465
5466 The function \texttt{cvCloneSeq} makes a complete copy of the input sequence and returns it.
5467 \ifC
5468 The call
5469
5470 \begin{lstlisting}
5471 cvCloneSeq( seq, storage )
5472 \end{lstlisting}
5473
5474 is equivalent to
5475
5476 \begin{lstlisting}
5477 cvSeqSlice]( seq, CV_WHOLE_SEQ, storage, 1 )
5478 \end{lstlisting}
5479 \fi
5480
5481 \cvfunc{SeqRemoveSlice}\label{SeqRemoveSlice}
5482
5483 Removes a sequence slice.
5484
5485 \cvexp{
5486
5487 void cvSeqRemoveSlice( CvSeq* seq, CvSlice slice );
5488
5489 }{CPP}{SeqRemoveSlice(seq,slice)-> None}
5490
5491 \begin{description}
5492 \cvarg{seq}{Sequence}
5493 \cvarg{slice}{The part of the sequence to remove}
5494 \end{description}
5495
5496
5497 The function \texttt{cvSeqRemoveSlice} removes a slice from the sequence.
5498
5499 \ifC
5500 \cvfunc{SeqInsertSlice}\label{SeqInsertSlice}
5501
5502 Inserts an array in the middle of a sequence.
5503
5504 \cvexp{
5505
5506 void cvSeqInsertSlice( \par CvSeq* seq,\par int before\_index,\par const CvArr* from\_arr );
5507
5508 }{CPP}{PYTHON}
5509
5510 \begin{description}
5511 \cvarg{seq}{Sequence}
5512 \cvarg{slice}{The part of the sequence to remove}
5513 \cvarg{from\_arr}{The array to take elements from}
5514 \end{description}
5515
5516
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.
5520
5521 \fi
5522
5523 \cvfunc{SeqInvert}\label{SeqInvert}
5524
5525 Reverses the order of sequence elements.
5526
5527 \cvexp{
5528
5529 void cvSeqInvert( CvSeq* seq );
5530
5531 }{CPP}{SeqInvert(seq)-> None}
5532
5533 \begin{description}
5534 \cvarg{seq}{Sequence}
5535 \end{description}
5536
5537
5538 The function \texttt{cvSeqInvert} reverses the sequence in-place - makes the first element go last, the last element go first and so forth.
5539
5540 \ifC
5541 \cvfunc{SeqSort}\label{SeqSort}
5542
5543 Sorts sequence element using the specified comparison function.
5544
5545 \cvexp{
5546
5547 void cvSeqSort( CvSeq* seq, CvCmpFunc func, void* userdata=NULL );
5548
5549 }{CPP}{PYTHON}
5550
5551 \begin{lstlisting}
5552 /* a < b ? -1 : a > b ? 1 : 0 */
5553 typedef int (CV_CDECL* CvCmpFunc)(const void* a, const void* b, void* userdata);
5554 \end{lstlisting}
5555
5556 \begin{description}
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}
5560 \end{description}
5561
5562 The function \texttt{cvSeqSort} sorts the sequence in-place using the specified criteria. Below is an example of using this function:
5563
5564 \begin{lstlisting}
5565
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 )
5568 {
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;
5574 }
5575
5576 ...
5577
5578 CvMemStorage* storage = cvCreateMemStorage(0);
5579 CvSeq* seq = cvCreateSeq( CV_32SC2, sizeof(CvSeq), sizeof(CvPoint), storage );
5580 int i;
5581
5582 for( i = 0; i < 10; i++ )
5583 {
5584     CvPoint pt;
5585     pt.x = rand() % 1000;
5586     pt.y = rand() % 1000;
5587     cvSeqPush( seq, &pt );
5588 }
5589
5590 cvSeqSort( seq, cmp_func, 0 /* userdata is not used here */ );
5591
5592 /* print out the sorted sequence */
5593 for( i = 0; i < seq->total; i++ )
5594 {
5595     CvPoint* pt = (CvPoint*)cvSeqElem( seq, i );
5596     printf( "(%d,%d)\n", pt->x, pt->y );
5597 }
5598
5599 cvReleaseMemStorage( &storage );
5600
5601 \end{lstlisting}
5602
5603
5604 \cvfunc{SeqSearch}\label{SeqSearch}
5605
5606 Searches for an element in a sequence.
5607
5608 \begin{lstlisting}
5609
5610 /* a < b ? -1 : a > b ? 1 : 0 */
5611 typedef int (CV_CDECL* CvCmpFunc)(const void* a, const void* b, void* userdata);
5612
5613 char* cvSeqSearch( CvSeq* seq, const void* elem, CvCmpFunc func,
5614                    int is_sorted, int* elem_idx, void* userdata=NULL );
5615
5616 \end{lstlisting}
5617
5618 \begin{description}
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}
5625 \end{description}
5626
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}
5633 .
5634
5635 \cvfunc{StartAppendToSeq}\label{StartAppendToSeq}
5636
5637 Initializes the process of writing data to a sequence.
5638
5639 \cvexp{
5640
5641 void cvStartAppendToSeq( \par CvSeq* seq,\par CvSeqWriter* writer );
5642
5643 }{CPP}{PYTHON}
5644
5645 \begin{description}
5646 \cvarg{seq}{Pointer to the sequence}
5647 \cvarg{writer}{Writer state; initialized by the function}
5648 \end{description}
5649
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 )}
5654 macro. Note
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).
5658
5659 \cvfunc{StartWriteSeq}\label{StartWriteSeq}
5660
5661 Creates a new sequence and initializes a writer for it.
5662
5663 \cvexp{
5664
5665 void cvStartWriteSeq( \par int seq\_flags,\par int header\_size,\par int elem\_size,\par CvMemStorage* storage,\par CvSeqWriter* writer );
5666
5667 }{CPP}{PYTHON}
5668
5669 \begin{description}
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}
5675 \end{description}
5676
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.
5683
5684 \cvfunc{EndWriteSeq}\label{EndWriteSeq}
5685
5686 Finishes the process of writing a sequence.
5687
5688 \cvexp{
5689
5690 CvSeq* cvEndWriteSeq( CvSeqWriter* writer );
5691
5692 }{CPP}{PYTHON}
5693
5694 \begin{description}
5695 \cvarg{writer}{Writer state}
5696 \end{description}
5697
5698
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
5703 modified safely.
5704
5705 \cvfunc{FlushSeqWriter}\label{FlushSeqWriter}
5706
5707 Updates sequence headers from the writer.
5708
5709 \cvexp{
5710
5711 void cvFlushSeqWriter( CvSeqWriter* writer );
5712
5713 }{CPP}{PYTHON}
5714
5715 \begin{description}
5716 \cvarg{writer}{Writer state}
5717 \end{description}
5718
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.
5726
5727 \cvfunc{StartReadSeq}\label{StartReadSeq}
5728
5729 Initializes the process of sequential reading from a sequence.
5730
5731 \cvexp{
5732
5733 void cvStartReadSeq( \par const CvSeq* seq,\par CvSeqReader* reader,\par int reverse=0 );
5734
5735 }{CPP}{PYTHON}
5736
5737 \begin{description}
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. }
5741 \end{description}
5742
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.
5760
5761 \begin{lstlisting}
5762
5763 CvMemStorage* storage = cvCreateMemStorage(0);
5764 CvSeq* seq = cvCreateSeq( CV_32SC1, sizeof(CvSeq), sizeof(int), storage );
5765 CvSeqWriter writer;
5766 CvSeqReader reader;
5767 int i;
5768
5769 cvStartAppendToSeq( seq, &writer );
5770 for( i = 0; i < 10; i++ )
5771 {
5772     int val = rand()%100;
5773     CV_WRITE_SEQ_ELEM( val, writer );
5774     printf("%d is written\n", val );
5775 }
5776 cvEndWriteSeq( &writer );
5777
5778 cvStartReadSeq( seq, &reader, 0 );
5779 for( i = 0; i < seq->total; i++ )
5780 {
5781     int val;
5782 #if 1
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 );
5789 #endif
5790 }
5791 ...
5792
5793 cvReleaseStorage( &storage );
5794
5795 \end{lstlisting}
5796
5797 \cvfunc{GetSeqReaderPos}\label{GetSeqReaderPos}
5798
5799 Returns the current reader position.
5800
5801 \cvexp{
5802
5803 int cvGetSeqReaderPos( CvSeqReader* reader );
5804
5805 }{CPP}{PYTHON}
5806
5807 \begin{description}
5808 \cvarg{reader}{Reader state}
5809 \end{description}
5810
5811
5812 The function \texttt{cvGetSeqReaderPos} returns the current reader position (within 0 ... \texttt{reader->seq->total} - 1).
5813
5814 \cvfunc{SetSeqReaderPos}\label{SetSeqReaderPos}
5815
5816 Moves the reader to the specified position.
5817
5818 \cvexp{
5819
5820 void cvSetSeqReaderPos( \par CvSeqReader* reader,\par int index,\par int is\_relative=0 );
5821
5822 }{CPP}{PYTHON}
5823
5824 \begin{description}
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}
5828 \end{description}
5829
5830 The function \texttt{cvSetSeqReaderPos} moves the read position to an absolute position or relative to the current position.
5831
5832 \fi
5833
5834 \subsection{Sets}
5835
5836 \cvstruct{CvSet}\label{CvSet}
5837
5838 Collection of nodes.
5839
5840 \ifPython
5841 Some OpenCV functions return a CvSet object. The CvSeq obect is iterable, for example:
5842
5843 \begin{lstlisting}
5844 for i in s:
5845   print i
5846 print set(s)
5847 print list(s)
5848 \end{lstlisting}
5849 \fi
5850
5851 \ifC
5852 \begin{lstlisting}
5853
5854 typedef struct CvSetElem
5855 {
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 */
5859 }
5860 CvSetElem;
5861
5862 #define CV_SET_FIELDS()    \
5863     CV_SEQUENCE_FIELDS()   /* inherits from [#CvSeq CvSeq] */ \
5864     struct CvSetElem* free_elems; /* list of free nodes */
5865
5866 typedef struct CvSet
5867 {
5868     CV_SET_FIELDS()
5869 } CvSet;
5870
5871 \end{lstlisting}
5872
5873 The structure \cross{CvSet} is a base for OpenCV sparse data structures.
5874
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.
5894
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.
5901
5902 In OpenCV \cross{CvSet} is used for representing graphs (\cross{CvGraph}),
5903 sparse multi-dimensional arrays (\cross{CvSparseMat}), and planar subdivisions
5904 \cross{CvSubdiv2D}.
5905
5906 \cvfunc{CreateSet}\label{CreateSet}
5907
5908 Creates an empty set.
5909
5910 \cvexp{
5911
5912 CvSet* cvCreateSet( \par int set\_flags,\par int header\_size,\par int elem\_size,\par CvMemStorage* storage );
5913
5914 }{CPP}{PYTHON}
5915
5916 \begin{description}
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}
5921 \end{description}
5922
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}.
5924
5925 \cvfunc{SetAdd}\label{SetAdd}
5926
5927 Occupies a node in the set.
5928
5929 \cvexp{
5930
5931 int cvSetAdd( \par CvSet* set\_header,\par CvSetElem* elem=NULL,\par CvSetElem** inserted\_elem=NULL );
5932
5933 }{CPP}{PYTHON}
5934
5935 \begin{description}
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}
5939 \end{description}
5940
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}).
5946
5947 \cvfunc{SetRemove}\label{SetRemove}
5948
5949 Removes an element from a set.
5950
5951 \cvexp{
5952
5953 void cvSetRemove( \par CvSet* set\_header,\par int index );
5954
5955 }{CPP}{PYTHON}
5956
5957 \begin{description}
5958 \cvarg{set\_header}{Set}
5959 \cvarg{index}{Index of the removed element}
5960 \end{description}
5961
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.
5967
5968 \cvfunc{SetNew}\label{SetNew}
5969
5970 Adds an element to a set (fast variant).
5971
5972 \cvexp{
5973
5974 CvSetElem* cvSetNew( CvSet* set\_header );
5975
5976 }{CPP}{PYTHON}
5977
5978 \begin{description}
5979 \cvarg{set\_header}{Set}
5980 \end{description}
5981
5982
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.
5984
5985
5986 \cvfunc{SetRemoveByPtr}\label{SetRemoveByPtr}
5987
5988 Removes a set element based on its pointer.
5989
5990 \cvexp{
5991
5992 void cvSetRemoveByPtr( \par CvSet* set\_header,\par void* elem );
5993
5994 }{CPP}{PYTHON}
5995
5996 \begin{description}
5997 \cvarg{set\_header}{Set}
5998 \cvarg{elem}{Removed element}
5999 \end{description}
6000
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.
6002
6003
6004 \cvfunc{GetSetElem}\label{GetSetElem}
6005
6006 Finds a set element by its index.
6007
6008 \cvexp{
6009
6010 CvSetElem* cvGetSetElem( \par const CvSet* set\_header,\par int index );
6011
6012 }{CPP}{PYTHON}
6013
6014 \begin{description}
6015 \cvarg{set\_header}{Set}
6016 \cvarg{index}{Index of the set element within a sequence}
6017 \end{description}
6018
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.
6020
6021 \cvfunc{ClearSet}\label{ClearSet}
6022
6023 Clears a set.
6024
6025 \cvexp{
6026
6027 void cvClearSet( CvSet* set\_header );
6028
6029 }{CPP}{PYTHON}
6030
6031 \begin{description}
6032 \cvarg{set\_header}{Cleared set}
6033 \end{description}
6034
6035
6036 The function \texttt{cvClearSet} removes all elements from set. It has O(1) time complexity.
6037
6038 \fi
6039
6040 \ifC
6041 \subsection{Graphs}
6042
6043
6044 \cvstruct{CvGraph}\label{CvGraph}
6045
6046 Oriented or unoriented weighted graph.
6047
6048 \begin{lstlisting}
6049
6050 #define CV_GRAPH_VERTEX_FIELDS()    \
6051     int flags; /* vertex flags */   \
6052     struct CvGraphEdge* first; /* the first incident edge */
6053
6054 typedef struct CvGraphVtx
6055 {
6056     CV_GRAPH_VERTEX_FIELDS()
6057 }
6058 CvGraphVtx;
6059
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 */
6066
6067 typedef struct CvGraphEdge
6068 {
6069     CV_GRAPH_EDGE_FIELDS()
6070 }
6071 CvGraphEdge;
6072
6073 #define  CV_GRAPH_FIELDS()                  \
6074     CV_SET_FIELDS() /* set of vertices */   \
6075     CvSet* edges;   /* set of edges */
6076
6077 typedef struct CvGraph
6078 {
6079     CV_GRAPH_FIELDS()
6080 }
6081 CvGraph;
6082
6083 \end{lstlisting}
6084
6085 The structure \cross{CvGraph} is a base for graphs used in OpenCV.
6086
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.
6088
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.
6098
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.
6102
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.
6108
6109 \cvfunc{CreateGraph}\label{CreateGraph}
6110
6111 Creates an empty graph.
6112
6113 \cvexp{
6114
6115 CvGraph* cvCreateGraph( \par int graph\_flags,\par int header\_size,\par int vtx\_size,\par int edge\_size,\par CvMemStorage* storage );
6116
6117 }{CPP}{PYTHON}
6118
6119 \begin{description}
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}
6126 \end{description}
6127
6128 The function \texttt{cvCreateGraph} creates an empty graph and returns a pointer to it.
6129
6130 \cvfunc{GraphAddVtx}\label{GraphAddVtx}
6131
6132 Adds a vertex to a graph.
6133
6134 \cvexp{
6135
6136 int cvGraphAddVtx( \par CvGraph* graph,\par const CvGraphVtx* vtx=NULL,\par CvGraphVtx** inserted\_vtx=NULL );
6137
6138 }{CPP}{PYTHON}
6139
6140 \begin{description}
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.}
6144 \end{description}
6145
6146 The function \texttt{cvGraphAddVtx} adds a vertex to the graph and returns the vertex index.
6147
6148 \cvfunc{GraphRemoveVtx}\label{GraphRemoveVtx}
6149
6150 Removes a vertex from a graph.
6151
6152 \cvexp{
6153
6154 int cvGraphRemoveVtx( \par CvGraph* graph,\par int index );
6155
6156 }{CPP}{PYTHON}
6157
6158 \begin{description}
6159 \cvarg{graph}{Graph}
6160 \cvarg{vtx\_idx}{Index of the removed vertex}
6161 \end{description}
6162
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.
6167
6168 \cvfunc{GraphRemoveVtxByPtr}\label{GraphRemoveVtxByPtr}
6169
6170 Removes a vertex from a graph by using its pointer.
6171
6172 \cvexp{
6173
6174 int cvGraphRemoveVtxByPtr( \par CvGraph* graph,\par CvGraphVtx* vtx );
6175
6176 }{CPP}{PYTHON}
6177
6178 \begin{description}
6179 \cvarg{graph}{Graph}
6180 \cvarg{vtx}{Pointer to the removed vertex}
6181 \end{description}
6182
6183
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.
6185
6186 \cvfunc{GetGraphVtx}\label{GetGraphVtx}
6187
6188 Finds a graph vertex by using its index.
6189
6190 \cvexp{
6191
6192 CvGraphVtx* cvGetGraphVtx( \par CvGraph* graph,\par int vtx\_idx );
6193
6194 }{CPP}{PYTHON}
6195
6196 \begin{description}
6197 \cvarg{graph}{Graph}
6198 \cvarg{vtx\_idx}{Index of the vertex}
6199 \end{description}
6200
6201
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.
6203
6204
6205 \cvfunc{GraphVtxIdx}\label{GraphVtxIdx}
6206
6207 Returns the index of a graph vertex.
6208
6209 \cvexp{
6210
6211 int cvGraphVtxIdx( \par CvGraph* graph,\par CvGraphVtx* vtx );
6212
6213 }{CPP}{PYTHON}
6214
6215 \begin{description}
6216 \cvarg{graph}{Graph}
6217 \cvarg{vtx}{Pointer to the graph vertex}
6218 \end{description}
6219
6220 The function \texttt{cvGraphVtxIdx} returns the index of a graph vertex.
6221
6222 \cvfunc{GraphAddEdge}\label{GraphAddEdge}
6223
6224 Adds an edge to a graph.
6225
6226 \cvexp{
6227
6228 int cvGraphAddEdge( \par CvGraph* graph,\par int start\_idx,\par int end\_idx,\par const CvGraphEdge* edge=NULL,\par CvGraphEdge** inserted\_edge=NULL );
6229
6230 }{CPP}{PYTHON}
6231
6232 \begin{description}
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}
6238 \end{description}
6239
6240
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.
6242
6243 \cvfunc{GraphAddEdgeByPtr}\label{GraphAddEdgeByPtr}
6244
6245 Adds an edge to a graph by using its pointer.
6246
6247 \cvexp{
6248
6249 int cvGraphAddEdgeByPtr( \par CvGraph* graph,\par CvGraphVtx* start\_vtx,\par CvGraphVtx* end\_vtx,\par const CvGraphEdge* edge=NULL,\par CvGraphEdge** inserted\_edge=NULL );
6250
6251 }{CPP}{PYTHON}
6252
6253 \begin{description}
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}
6259 \end{description}
6260
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.
6267
6268 \cvfunc{GraphRemoveEdge}\label{GraphRemoveEdge}
6269
6270 Removes an edge from a graph.
6271
6272 \cvexp{
6273
6274 void cvGraphRemoveEdge( \par CvGraph* graph,\par int start\_idx,\par int end\_idx );
6275
6276 }{CPP}{PYTHON}
6277
6278 \begin{description}
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.}
6282 \end{description}
6283
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.
6285
6286 \cvfunc{GraphRemoveEdgeByPtr}\label{GraphRemoveEdgeByPtr}
6287
6288 Removes an edge from a graph by using its pointer.
6289
6290 \cvexp{
6291
6292 void cvGraphRemoveEdgeByPtr( \par CvGraph* graph,\par CvGraphVtx* start\_vtx,\par CvGraphVtx* end\_vtx );
6293
6294 }{CPP}{PYTHON}
6295
6296 \begin{description}
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.}
6300 \end{description}
6301
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.
6303
6304 \cvfunc{FindGraphEdge}\label{FindGraphEdge}
6305
6306 Finds an edge in a graph.
6307
6308 \cvexp{
6309
6310 CvGraphEdge* cvFindGraphEdge( const CvGraph* graph, int start\_idx, int end\_idx );
6311
6312 }{CPP}{PYTHON}
6313
6314 \begin{lstlisting}
6315
6316 #define cvGraphFindEdge cvFindGraphEdge
6317
6318 \end{lstlisting}
6319
6320 \begin{description}
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.}
6324 \end{description}
6325
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.
6327
6328 \cvfunc{FindGraphEdgeByPtr}\label{FindGraphEdgeByPtr}
6329
6330 Finds an edge in a graph by using its pointer.
6331
6332 \cvexp{
6333
6334 CvGraphEdge* cvFindGraphEdgeByPtr( \par const CvGraph* graph,\par const CvGraphVtx* start\_vtx,\par const CvGraphVtx* end\_vtx );
6335
6336 }{CPP}{PYTHON}
6337
6338 \begin{lstlisting}
6339 \#define cvGraphFindEdgeByPtr cvFindGraphEdgeByPtr
6340 \end{lstlisting}
6341
6342 \begin{description}
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.}
6346 \end{description}
6347
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.
6349
6350 \cvfunc{GraphEdgeIdx}\label{GraphEdgeIdx}
6351
6352 Returns the index of a graph edge.
6353
6354 \cvexp{
6355
6356 int cvGraphEdgeIdx( \par CvGraph* graph,\par CvGraphEdge* edge );
6357
6358 }{CPP}{PYTHON}
6359
6360 \begin{description}
6361 \cvarg{graph}{Graph}
6362 \cvarg{edge}{Pointer to the graph edge}
6363 \end{description}
6364
6365 The function \texttt{cvGraphEdgeIdx} returns the index of a graph edge.
6366
6367 \cvfunc{GraphVtxDegree}\label{GraphVtxDegree}
6368
6369 Counts the number of edges indicent to the vertex.
6370
6371 \cvexp{
6372
6373 int cvGraphVtxDegree( const CvGraph* graph, int vtx\_idx );
6374
6375 }{CPP}{PYTHON}
6376
6377 \begin{description}
6378 \cvarg{graph}{Graph}
6379 \cvarg{vtx}{Index of the graph vertex}
6380 \end{description}
6381
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:
6383
6384 \begin{lstlisting}
6385
6386 CvGraphEdge* edge = vertex->first; int count = 0;
6387 while( edge )
6388 {
6389     edge = CV_NEXT_GRAPH_EDGE( edge, vertex );
6390     count++;
6391 }
6392
6393 \end{lstlisting}
6394
6395 The macro \texttt{CV\_NEXT\_GRAPH\_EDGE( edge, vertex )} returns the edge incident to \texttt{vertex} that follows after \texttt{edge}.
6396
6397 \cvfunc{GraphVtxDegreeByPtr}\label{GraphVtxDegreeByPtr}
6398
6399 Finds an edge in a graph.
6400
6401 \cvexp{
6402
6403 int cvGraphVtxDegreeByPtr( \par const CvGraph* graph,\par const CvGraphVtx* vtx );
6404
6405 }{CPP}{PYTHON}
6406
6407 \begin{description}
6408 \cvarg{graph}{Graph}
6409 \cvarg{vtx}{Pointer to the graph vertex}
6410 \end{description}
6411
6412 The function \texttt{cvGraphVtxDegree} returns the number of edges incident to the specified vertex, both incoming and outcoming.
6413
6414
6415 \cvfunc{ClearGraph}\label{ClearGraph}
6416
6417 Clears a graph.
6418
6419 \cvexp{
6420
6421 void cvClearGraph( CvGraph* graph );
6422
6423 }{CPP}{PYTHON}
6424
6425 \begin{description}
6426 \cvarg{graph}{Graph}
6427 \end{description}
6428
6429 The function \texttt{cvClearGraph} removes all vertices and edges from a graph. The function has O(1) time complexity.
6430
6431 \cvfunc{CloneGraph}\label{CloneGraph}
6432
6433 Clones a graph.
6434
6435 \cvexp{
6436
6437 CvGraph* cvCloneGraph( \par const CvGraph* graph,\par CvMemStorage* storage );
6438
6439 }{CPP}{PYTHON}
6440
6441 \begin{description}
6442 \cvarg{graph}{The graph to copy}
6443 \cvarg{storage}{Container for the copy}
6444 \end{description}
6445
6446
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.
6452
6453
6454 \cvstruct{CvGraphScanner}\label{CvGraphScanner}
6455
6456 Graph traversal state.
6457
6458 \begin{lstlisting}
6459
6460 typedef struct CvGraphScanner
6461 {
6462     CvGraphVtx* vtx;       /* current graph vertex (or current edge origin) */
6463     CvGraphVtx* dst;       /* current graph edge destination vertex */
6464     CvGraphEdge* edge;     /* current edge */
6465
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 */
6470 }
6471 CvGraphScanner;
6472
6473 \end{lstlisting}
6474
6475 The structure \cross{CvGraphScanner} is used for depth-first graph traversal. See discussion of the functions below.
6476
6477
6478 \cvfunc{CreateGraphScanner}\label{CreateGraphScanner}
6479
6480 Creates structure for depth-first graph traversal.
6481
6482 \cvexp{
6483
6484 CvGraphScanner*  cvCreateGraphScanner( \par CvGraph* graph,\par CvGraphVtx* vtx=NULL,\par int mask=CV\_GRAPH\_ALL\_ITEMS );
6485
6486 }{CPP}{PYTHON}
6487
6488 \begin{description}
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:
6492
6493 \begin{description}
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.}
6502 \end{description}}
6503 \end{description}
6504
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.
6506
6507 \cvfunc{NextGraphItem}\label{NextGraphItem}
6508
6509 Executes one or more steps of the graph traversal procedure.
6510
6511 \cvexp{
6512
6513 int cvNextGraphItem( CvGraphScanner* scanner );
6514
6515 }{CPP}{PYTHON}
6516
6517 \begin{description}
6518 \cvarg{scanner}{Graph traversal state. It is updated by this function.}
6519 \end{description}
6520
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}.
6533
6534 \cvfunc{ReleaseGraphScanner}\label{ReleaseGraphScanner}
6535
6536 Completes the graph traversal procedure.
6537
6538 \cvexp{
6539
6540 void cvReleaseGraphScanner( CvGraphScanner** scanner );
6541
6542 }{CPP}{PYTHON}
6543
6544 \begin{description}
6545 \cvarg{scanner}{Double pointer to graph traverser}
6546 \end{description}
6547
6548
6549 The function \texttt{cvGraphScanner} completes the graph traversal procedure and releases the traverser state.
6550
6551
6552 \subsection{Trees}
6553
6554
6555 \cvmacro{CV\_TREE\_NODE\_FIELDS}\label{CV_TREE_NODE_FIELDS}
6556
6557 Helper macro for a tree node type declaration.
6558
6559 \begin{lstlisting}
6560
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 */
6568
6569 \end{lstlisting}
6570
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.
6576
6577 \cvstruct{CvTreeNodeIterator}\label{CvTreeNodeIterator}
6578
6579 Opens existing or creates new file storage.
6580
6581 \begin{lstlisting}
6582
6583 typedef struct CvTreeNodeIterator
6584 {
6585     const void* node;
6586     int level;
6587     int max_level;
6588 }
6589 CvTreeNodeIterator;
6590
6591 \end{lstlisting}
6592
6593 The structure \cross{CvTreeNodeIterator} is used to traverse trees. The tree node declaration should start with the \texttt{CV\_TREE\_NODE\_FIELDS(...)} macro.
6594
6595 \cvfunc{InitTreeNodeIterator}\label{InitTreeNodeIterator}
6596
6597 Initializes the tree node iterator.
6598
6599 \cvexp{
6600
6601 void cvInitTreeNodeIterator( \par CvTreeNodeIterator* tree\_iterator,\par const void* first,\par int max\_level );
6602
6603 }{CPP}{PYTHON}
6604
6605 \begin{description}
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.}
6609 \end{description}
6610
6611 The function \texttt{cvInitTreeNodeIterator} initializes the tree iterator. The tree is traversed in depth-first order.
6612
6613 \cvfunc{NextTreeNode}\label{NextTreeNode}
6614
6615 Returns the currently observed node and moves the iterator toward the next node.
6616
6617 \cvexp{
6618
6619 void* cvNextTreeNode( CvTreeNodeIterator* tree\_iterator );
6620
6621 }{CPP}{PYTHON}
6622
6623 \begin{description}
6624 \cvarg{tree\_iterator}{Tree iterator initialized by the function}
6625 \end{description}
6626
6627
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.
6629
6630
6631 \cvfunc{PrevTreeNode}\label{PrevTreeNode}
6632
6633 Returns the currently observed node and moves the iterator toward the previous node.
6634
6635 \cvexp{
6636
6637 void* cvPrevTreeNode( CvTreeNodeIterator* tree\_iterator );
6638
6639 }{CPP}{PYTHON}
6640
6641 \begin{description}
6642 \cvarg{tree\_iterator}{Tree iterator initialized by the function}
6643 \end{description}
6644
6645
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.
6647
6648
6649 \cvfunc{TreeToNodeSeq}\label{TreeToNodeSeq}
6650
6651 Gathers all node pointers to a single sequence.
6652
6653 \cvexp{
6654
6655 CvSeq* cvTreeToNodeSeq( \par const void* first,\par int header\_size,\par CvMemStorage* storage );
6656
6657 }{CPP}{PYTHON}
6658
6659 \begin{description}
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}
6663 \end{description}
6664
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.
6666
6667 \cvfunc{InsertNodeIntoTree}\label{InsertNodeIntoTree}
6668
6669 Adds a new node to a tree.
6670
6671 \cvexp{
6672
6673 void cvInsertNodeIntoTree( \par void* node,\par void* parent,\par void* frame );
6674
6675 }{CPP}{PYTHON}
6676
6677 \begin{description}
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}.}
6681 \end{description}
6682
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.
6684
6685 \cvfunc{RemoveNodeFromTree}\label{RemoveNodeFromTree}
6686
6687 Removes a node from a tree.
6688
6689 \cvexp{
6690
6691 void cvRemoveNodeFromTree( \par void* node,\par void* frame );
6692
6693 }{CPP}{PYTHON}
6694
6695 \begin{description}
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).}
6698 \end{description}
6699
6700 \fi
6701
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.
6703
6704 \section{Drawing Functions}
6705
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.
6711
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}.
6718
6719 \subsection{Curves and Shapes}
6720
6721 \cvfunc{CV\_RGB}\label{CV_RGB}
6722
6723 Constructs a color value.
6724
6725 \cvexp{
6726 \#define CV\_RGB( r, g, b )  cvScalar( (b), (g), (r) )
6727 }{CPP}{CV\_RGB(red,grn,blu)->CvScalar}
6728
6729 \cvfunc{Line}\label{Line}
6730
6731 Draws a line segment connecting two points.
6732
6733 \cvexp{
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}
6736
6737 \begin{description}
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:
6744   \begin{description}
6745   \cvarg{8}{(or omitted) 8-connected line.}
6746   \cvarg{4}{4-connected line.}
6747   \cvarg{CV\_AA}{antialiased line.}
6748   \end{description}}
6749 \cvarg{shift}{Number of fractional bits in the point coordinates}
6750 \end{description}
6751
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 )}.
6760
6761 \cvfunc{Rectangle}\label{Rectangle}
6762
6763 Draws a simple, thick, or filled rectangle.
6764
6765 \cvexp{
6766
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 );
6768
6769 }{CPP}{Rectangle(img,pt1,pt2,color,thickness=1,line\_type=8,shift=0)-> None}
6770
6771 \begin{description}
6772 \cvarg{img}{Image}
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}
6779 \end{description}
6780
6781 The function \texttt{cvRectangle} draws a rectangle with two opposite corners \texttt{pt1} and \texttt{pt2}.
6782
6783 \cvfunc{Circle}\label{Circle}
6784
6785 Draws a circle.
6786
6787 \cvexp{
6788
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 );
6790
6791 }{CPP}{Circle(img,center,radius,color,thickness=1,line\_type=8,shift=0)-> None}
6792
6793 \begin{description}
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}
6801 \end{description}
6802
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 )}.
6807
6808 \cvfunc{Ellipse}\label{Ellipse}
6809
6810 Draws a simple or thick elliptic arc or an fills ellipse sector.
6811
6812 \cvexp{
6813
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 );
6815
6816 }{CPP}{Ellipse(img,pt1,axes,angle,start\_angle,end\_angle,color,thickness=1,line\_type=8,shift=0)-> None}
6817
6818 \begin{description}
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}
6829 \end{description}
6830
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.
6836
6837 Parameters of Elliptic Arc
6838
6839 \includegraphics[width=0.5\textwidth]{pics/ellipse.png}
6840
6841 \cvfunc{EllipseBox}
6842
6843 Draws a simple or thick elliptic arc or fills an ellipse sector.
6844
6845 \cvexp{
6846
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 );
6849
6850 }{CPP}{EllipseBox(img,box,color,thickness=1,line\_type=8,shift=0)-> None}
6851
6852 \begin{description}
6853 \cvarg{img}{Image}
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}
6858 \end{description}
6859
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.
6861
6862 \cvfunc{FillPoly}\label{FillPoly}
6863
6864 Fills a polygon's interior.
6865
6866 \cvexp{
6867
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 );
6869
6870 }{CPP}{FillPoly(img,polys,color,line\_type=8,shift=0)-> None}
6871
6872 \begin{description}
6873 \cvarg{img}{Image}
6874 \ifC
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}
6878 \fi
6879 \ifPython
6880 \cvarg{polys}{List of lists of (x,y) pairs.  Each list of points is a polygon.}
6881 \fi
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}
6885 \end{description}
6886
6887
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.
6891
6892 \cvfunc{FillConvexPoly}\label{FillConvexPoly}
6893
6894 Fills a convex polygon.
6895
6896 \cvexp{
6897
6898 void cvFillConvexPoly( \par CvArr* img,\par CvPoint* pts,\par int npts,\par CvScalar color,\par int line\_type=8,\par int shift=0 );
6899
6900 }{CPP}{FillConvexPoly(img,pn,color,line\_type=8,shift=0)-> None}
6901
6902 \begin{description}
6903 \cvarg{img}{Image}
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}
6909 \end{description}
6910
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.
6916
6917
6918 \cvfunc{PolyLine}\label{PolyLine}
6919
6920 Draws simple or thick polygons.
6921
6922 \cvexp{
6923
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 );
6925
6926 }{CPP}{PolyLine(img,pts,is\_closed,color,thickness=1,line\_type=8,shift=0)-> None}
6927
6928 \begin{description}
6929 \ifC
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}
6933 \fi
6934 \ifPython
6935 \cvarg{polys}{List of lists of (x,y) pairs.  Each list of points is a polygon.}
6936 \fi
6937 \cvarg{img}{Image}
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}
6945 \end{description}
6946
6947 The function \texttt{cvPolyLine} draws single or multiple polygonal curves.
6948
6949 \subsection{Text}
6950
6951 \cvfunc{InitFont}\label{InitFont}
6952
6953 Initializes font structure.
6954
6955 \cvexp{
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}
6958
6959 \begin{description}
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:
6962  \begin{description}
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}}
6971  \end{description}
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}
6978 \end{description}
6979
6980 The function \texttt{cvInitFont} initializes the font structure that can be passed to text rendering functions.
6981
6982
6983 \cvfunc{PutText}\label{PutText}
6984
6985 Draws a text string.
6986
6987 \cvexp{
6988
6989 void cvPutText( \par CvArr* img,\par const char* text,\par CvPoint org,\par const CvFont* font,\par CvScalar color );
6990
6991 }{CPP}{PutText(img,text,org,font,color)-> None}
6992
6993 \begin{description}
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}
6999 \end{description}
7000
7001
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.
7006
7007 \cvfunc{GetTextSize}\label{GetTextSize}
7008
7009 Retrieves the width and height of a text string.
7010
7011 \cvexp{
7012
7013 void cvGetTextSize( \par const char* text\_string,\par const CvFont* font,\par CvSize* text\_size,\par int* baseline );
7014
7015 }{CPP}{GetTextSize(text\_string,font)-> text\_size,baseline}
7016
7017 \begin{description}
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}
7022 \end{description}
7023
7024 The function \texttt{cvGetTextSize} calculates the dimensions of a rectangle to enclose a text string when a specified font is used.
7025
7026 \subsection{Point Sets and Contours}
7027
7028 \cvfunc{DrawContours}\label{DrawContours}
7029
7030 Draws contour outlines or interiors in an image.
7031
7032 \cvexp{
7033
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 );
7035
7036 }{CPP}{DrawContours(img,contour,external\_color,hole\_color,max\_level,thickness=1,line\_type=8,offset=(0,0)-> None}
7037
7038 \begin{description}
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
7052 drawn.}
7053 \cvarg{line\_type}{Type of the contour segments, see \cross{Line} description}
7054 \end{description}
7055
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$.
7057
7058 \cvfunc{Example: Connected component detection via contour functions}
7059
7060 \begin{lstlisting}
7061
7062 #include "cv.h"
7063 #include "highgui.h"
7064
7065 int main( int argc, char** argv )
7066 {
7067     IplImage* src;
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)
7071     {
7072         IplImage* dst = cvCreateImage( cvGetSize(src), 8, 3 );
7073         CvMemStorage* storage = cvCreateMemStorage(0);
7074         CvSeq* contour = 0;
7075
7076         cvThreshold( src, src, 1, 255, CV_THRESH_BINARY );
7077         cvNamedWindow( "Source", 1 );
7078         cvShowImage( "Source", src );
7079
7080         cvFindContours( src, storage, &contour, sizeof(CvContour), 
7081                         CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE );
7082         cvZero( dst );
7083
7084         for( ; contour != 0; contour = contour->h_next )
7085         {
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 );
7089         }
7090
7091         cvNamedWindow( "Components", 1 );
7092         cvShowImage( "Components", dst );
7093         cvWaitKey(0);
7094     }
7095 }
7096
7097 \end{lstlisting}
7098
7099 Replace \texttt{CV\_FILLED} with 1 in the example below to see the contour outlines.
7100
7101 \cvfunc{InitLineIterator}\label{InitLineIterator}
7102
7103 Initializes the line iterator.
7104
7105 \cvexp{
7106
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 );
7108
7109 }{CPP}{InitLineIterator(image, pt1, pt2, connectivity=8, left\_to\_right=0)}
7110
7111 \begin{description}
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.}
7120 \end{description}
7121
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
7129 algorithm.
7130
7131 \ifC
7132 \cvfunc{Example: Using line iterator to calculate the sum of pixel values along the color line}
7133
7134 \begin{lstlisting}
7135
7136 CvScalar sum_line_pixels( IplImage* image, CvPoint pt1, CvPoint pt2 )
7137 {
7138     CvLineIterator iterator;
7139     int blue_sum = 0, green_sum = 0, red_sum = 0;
7140     int count = cvInitLineIterator( image, pt1, pt2, &iterator, 8, 0 );
7141
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);
7147
7148         /* print the pixel coordinates: demonstrates how to calculate the 
7149                                                         coordinates */
7150         {
7151         int offset, x, y;
7152         /* assume that ROI is not set, otherwise need to take it 
7153                                                 into account. */
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 );
7159         }
7160     }
7161     return cvScalar( blue_sum, green_sum, red_sum );
7162 }
7163
7164 \end{lstlisting}
7165 \fi
7166
7167 \cvfunc{ClipLine}\label{ClipLine}
7168
7169 Clips the line against the image rectangle.
7170
7171 \cvexp{
7172
7173 int cvClipLine( \par CvSize img\_size,\par CvPoint* pt1,\par CvPoint* pt2 );
7174
7175 }{CPP}{ClipLine(img, pt1, pt2) -> (clipped\_pt1, clipped\_pt2)}
7176
7177 \begin{description}
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.}}
7181 \end{description}
7182
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.}
7187
7188 \ifC
7189 \cvfunc{Ellipse2Poly}\label{Ellipse2Poly}
7190
7191 Approximates an elliptic arc with a polyline.
7192
7193 \cvexp{
7194
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 );
7196
7197 }{CPP}{PYTHON}
7198
7199 \begin{description}
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 $
7208 at maximum.}
7209 \end{description}
7210
7211 The function \texttt{cvEllipse2Poly} computes the vertices of a polyline that approximates the specified elliptic arc. It is used by \cross{Ellipse}.
7212
7213 \fi
7214
7215 \section{Data Persistence and RTTI}
7216
7217 \ifC
7218 \subsection{File Storage}
7219
7220 \cvstruct{CvFileStorage}\label{CvFileStorage}
7221
7222 File Storage.
7223
7224 \begin{lstlisting}
7225
7226 typedef struct CvFileStorage
7227 {
7228     ...       // hidden fields
7229 } CvFileStorage;
7230
7231 \end{lstlisting}
7232
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.
7239
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:
7244
7245 XML:
7246
7247 \begin{verbatim}
7248 <?xml version="1.0">
7249 <opencv_storage>
7250 <A type_id="opencv-matrix">
7251   <rows>3</rows>
7252   <cols>3</cols>
7253   <dt>f</dt>
7254   <data>1. 0. 0. 0. 1. 0. 0. 0. 1.</data>
7255 </A>
7256 </opencv_storage>
7257 \end{verbatim}
7258
7259 YAML:
7260
7261 \begin{verbatim}
7262 %YAML:1.0
7263 A: !!opencv-matrix
7264   rows: 3
7265   cols: 3
7266   dt: f
7267   data: [ 1., 0., 0., 0., 1., 0., 0., 0., 1.]
7268 \end{verbatim}
7269
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).
7273
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.
7277
7278
7279 \cvstruct{CvFileNode}\label{CvFileNode}
7280
7281 File Storage Node.
7282
7283 \begin{lstlisting}
7284
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
7297
7298 /* optional flags */
7299 #define CV_NODE_USER        16
7300 #define CV_NODE_EMPTY       32
7301 #define CV_NODE_NAMED       64
7302
7303 #define CV_NODE_TYPE(tag)  ((tag) & CV_NODE_TYPE_MASK)
7304
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)
7315
7316 #define CV_NODE_SEQ_SIMPLE 256
7317 #define CV_NODE_SEQ_IS_SIMPLE(seq) (((seq)->flags & CV_NODE_SEQ_SIMPLE) != 0)
7318
7319 typedef struct CvString
7320 {
7321     int len;
7322     char* ptr;
7323 }
7324 CvString;
7325
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
7329 {
7330     unsigned hashval;
7331     CvString str;
7332     struct CvStringHashNode* next;
7333 }
7334 CvStringHashNode;
7335
7336 /* basic element of the file storage - scalar or collection */
7337 typedef struct CvFileNode
7338 {
7339     int tag;
7340     struct CvTypeInfo* info; /* type information
7341             (only for user-defined object, for others it is 0) */
7342     union
7343     {
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) */
7349     } data;
7350 }
7351 CvFileNode;
7352
7353 \end{lstlisting}
7354
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.
7359
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:
7374
7375 \begin{tabular}{| c | c | c |}
7376 \hline
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
7383 \end{tabular}
7384
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.
7389
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.
7397
7398
7399 \cvstruct{CvAttrList}\label{CvAttrList}
7400
7401 List of attributes.
7402
7403 \begin{lstlisting}
7404
7405 typedef struct CvAttrList
7406 {
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 */
7409 }
7410 CvAttrList;
7411
7412 /* initializes CvAttrList structure */
7413 inline CvAttrList cvAttrList( const char** attr=NULL, CvAttrList* next=NULL );
7414
7415 /* returns attribute value or 0 (NULL) if there is no such attribute */
7416 const char* cvAttrValue( const CvAttrList* attr, const char* attr\_name );
7417
7418 \end{lstlisting}
7419
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).
7421
7422 \cvfunc{OpenFileStorage}\label{OpenFileStorage}
7423
7424 Opens file storage for reading or writing data.
7425
7426 \cvexp{
7427
7428 CvFileStorage* cvOpenFileStorage( \par const char* filename,\par CvMemStorage* memstorage,\par int flags );
7429
7430 }{CPP}{PYTHON}
7431
7432 \begin{description}
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:
7438   \begin{description}
7439   \cvarg{CV\_STORAGE\_READ}{the storage is open for reading}
7440   \cvarg{CV\_STORAGE\_WRITE}{the storage is open for writing}
7441   \end{description}}
7442 \end{description}
7443
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.
7450
7451 \cvfunc{ReleaseFileStorage}\label{ReleaseFileStorage}
7452
7453 Releases file storage.
7454
7455 \cvexp{
7456
7457 void  cvReleaseFileStorage( CvFileStorage** fs );
7458
7459 }{CPP}{PYTHON}
7460
7461 \begin{description}
7462 \cvarg{fs}{Double pointer to the released file storage}
7463 \end{description}
7464
7465
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.
7467
7468
7469 \subsection{Writing Data}
7470
7471 \cvfunc{StartWriteStruct}\label{StartWriteStruct}
7472
7473 Starts writing a new structure.
7474
7475 \cvexp{
7476
7477 void  cvStartWriteStruct( CvFileStorage* fs,\par const char* name,\par int struct\_flags,\par const char* type\_name=NULL,\par CvAttrList attributes=cvAttrList( \par));
7478
7479 }{CPP}{PYTHON}
7480
7481 \begin{description}
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:
7485 \begin{description}
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}
7489
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}
7499 \end{description}
7500
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}).
7507
7508 \cvfunc{EndWriteStruct}\label{EndWriteStruct}
7509
7510 Ends the writing of a structure.
7511
7512 \cvexp{
7513
7514 void  cvEndWriteStruct( CvFileStorage* fs );
7515
7516 }{CPP}{PYTHON}
7517
7518 \begin{description}
7519 \cvarg{fs}{File storage}
7520 \end{description}
7521
7522
7523 The function \texttt{cvEndWriteStruct} finishes the currently written structure.
7524
7525 \cvfunc{WriteInt}\label{WriteInt}
7526
7527 Writes an integer value.
7528
7529 \cvexp{
7530
7531 void  cvWriteInt( \par CvFileStorage* fs,\par const char* name,\par int value );
7532
7533 }{CPP}{PYTHON}
7534
7535 \begin{description}
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}
7539 \end{description}
7540
7541 The function \texttt{cvWriteInt} writes a single integer value (with or without a name) to the file storage.
7542
7543 \cvfunc{WriteReal}\label{WriteReal}
7544
7545 Writes a floating-point value.
7546
7547 \cvexp{
7548
7549 void  cvWriteReal( \par CvFileStorage* fs,\par const char* name,\par double value );
7550
7551 }{CPP}{PYTHON}
7552
7553 \begin{description}
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}
7557 \end{description}
7558
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
7562 (-.Inf).
7563
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.
7567
7568 \begin{lstlisting}
7569
7570 void write_termcriteria( CvFileStorage* fs, const char* struct_name,
7571                          CvTermCriteria* termcrit )
7572 {
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 );
7580 }
7581
7582 \end{lstlisting}
7583
7584 \cvfunc{WriteString}\label{WriteString}
7585
7586 Writes a text string.
7587
7588 \cvexp{
7589
7590 void  cvWriteString( \par CvFileStorage* fs,\par const char* name,\par const char* str,\par int quote=0 );
7591
7592 }{CPP}{PYTHON}
7593
7594 \begin{description}
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).}
7599 \end{description}
7600
7601 The function \texttt{cvWriteString} writes a text string to file storage.
7602
7603 \cvfunc{WriteComment}\label{WriteComment}
7604
7605 Writes a comment.
7606
7607 \cvexp{
7608
7609 void  cvWriteComment( \par CvFileStorage* fs,\par const char* comment,\par int eol\_comment );
7610
7611 }{CPP}{PYTHON}
7612
7613 \begin{description}
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.}
7617 \end{description}
7618
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.
7620
7621 \cvfunc{StartNextStream}\label{StartNextStream}
7622
7623 Starts the next stream.
7624
7625 \cvexp{
7626
7627 void  cvStartNextStream( CvFileStorage* fs );
7628
7629 }{CPP}{PYTHON}
7630
7631 \begin{description}
7632 \cvarg{fs}{File storage}
7633 \end{description}
7634
7635
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.
7637
7638
7639 \cvfunc{Write}\label{Write}
7640
7641 Writes a user object.
7642
7643 \cvexp{
7644
7645 void  cvWrite( CvFileStorage* fs,\par const char* name,\par const void* ptr,\par CvAttrList attributes=cvAttrList( \par) );
7646
7647 }{CPP}{PYTHON}
7648
7649 \begin{description}
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).}
7654 \end{description}
7655
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.
7657
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}):
7659
7660 CvSeq
7661   \begin{description}
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.}
7665   \end{description}
7666 Cvgraph
7667   \begin{description}
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)}
7671   \end{description}
7672
7673 Below is the code that creates the YAML file shown in the \texttt{CvFileStorage} description:
7674
7675 \begin{lstlisting}
7676
7677 #include "cxcore.h"
7678
7679 int main( int argc, char** argv )
7680 {
7681     CvMat* mat = cvCreateMat( 3, 3, CV\_32F );
7682     CvFileStorage* fs = cvOpenFileStorage( "example.yml", 0, CV\_STORAGE\_WRITE );
7683
7684     cvSetIdentity( mat );
7685     cvWrite( fs, "A", mat, cvAttrList(0,0) );
7686
7687     cvReleaseFileStorage( &fs );
7688     cvReleaseMat( &mat );
7689     return 0;
7690 }
7691
7692 \end{lstlisting}
7693
7694
7695 \cvfunc{WriteRawData}\label{WriteRawData}
7696
7697 Writes multiple numbers.
7698
7699 \cvexp{
7700
7701 void  cvWriteRawData( \par CvFileStorage* fs,\par const void* src,\par int len,\par const char* dt );
7702
7703 }{CPP}{PYTHON}
7704
7705 \begin{description}
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:
7712 \begin{description}
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
7727 of doubles.}
7728 \end{description}}
7729 \end{description}
7730
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.
7736
7737 \cvfunc{WriteFileNode}\label{WriteFileNode}
7738
7739 Writes a file node to another file storage.
7740
7741 \cvexp{
7742
7743 void cvWriteFileNode( \par CvFileStorage* fs,\par const char* new\_node\_name,\par const CvFileNode* node,\par int embed );
7744
7745 }{CPP}{PYTHON}
7746
7747 \begin{description}
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.}
7752 \end{description}
7753
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.
7755
7756 \subsection{Reading Data}
7757
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.
7761
7762 \cvfunc{GetRootFileNode}\label{GetRootFileNode}
7763
7764 Retrieves one of the top-level nodes of the file storage.
7765
7766 \cvexp{
7767
7768 CvFileNode* cvGetRootFileNode( \par const CvFileStorage* fs,\par int stream\_index=0 );
7769
7770 }{CPP}{PYTHON}
7771
7772 \begin{description}
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.}
7775 \end{description}
7776
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.
7784
7785 \cvfunc{GetFileNodeByName}\label{GetFileNodeByName}
7786
7787 Finds a node in a map or file storage.
7788
7789 \cvexp{
7790
7791 CvFileNode* cvGetFileNodeByName( \par const CvFileStorage* fs,\par const CvFileNode* map,\par const char* name );
7792
7793 }{CPP}{PYTHON}
7794
7795 \begin{description}
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}
7799 \end{description}
7800
7801
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}.
7810
7811 \cvfunc{GetHashedKey}\label{GetHashedKey}
7812
7813 Returns a unique pointer for a given name.
7814
7815 \cvexp{
7816
7817 CvStringHashNode* cvGetHashedKey( \par CvFileStorage* fs,\par const char* name,\par int len=-1,\par int create\_missing=0 );
7818
7819 }{CPP}{PYTHON}
7820
7821 \begin{description}
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}
7826 \end{description}
7827
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
7832 strings' content.
7833
7834 Consider the following example where an array of points is encoded as a sequence of 2-entry maps:
7835
7836 \begin{lstlisting}
7837
7838 %YAML:1.0
7839 points:
7840   - { x: 10, y: 10 }
7841   - { x: 20, y: 20 }
7842   - { x: 30, y: 30 }
7843   # ...
7844
7845 \end{lstlisting}
7846
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}
7849
7850 \begin{lstlisting}
7851
7852 #include "cxcore.h"
7853
7854 int main( int argc, char** argv )
7855 {
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" );
7860
7861     if( CV\_NODE\_IS\_SEQ(points->tag) )
7862     {
7863         CvSeq* seq = points->data.seq;
7864         int i, total = seq->total;
7865         CvSeqReader reader;
7866         cvStartReadSeq( seq, &reader, 0 );
7867         for( i = 0; i < total; i++ )
7868         {
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 */ );
7887 #endif
7888             CV\_NEXT\_SEQ\_ELEM( seq->elem\_size, reader );
7889             printf("%d: (%d, %d)\n", i, x, y );
7890         }
7891     }
7892     cvReleaseFileStorage( &fs );
7893     return 0;
7894 }
7895
7896 \end{lstlisting}
7897
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.
7902
7903 \cvfunc{GetFileNode}\label{GetFileNode}
7904
7905 Finds a node in a map or file storage.
7906
7907 \cvexp{
7908
7909 CvFileNode* cvGetFileNode( \par CvFileStorage* fs,\par CvFileNode* map,\par const CvStringHashNode* key,\par int create\_missing=0 );
7910
7911 }{CPP}{PYTHON}
7912
7913 \begin{description}
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}
7918 \end{description}
7919
7920
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.
7922
7923 \cvfunc{GetFileNodeName}\label{GetFileNodeName}
7924
7925 Returns the name of a file node.
7926
7927 \cvexp{
7928
7929 const char* cvGetFileNodeName( const CvFileNode* node );
7930
7931 }{CPP}{PYTHON}
7932
7933 \begin{description}
7934 \cvarg{node}{File node}
7935 \end{description}
7936
7937
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}.
7939
7940
7941 \cvfunc{ReadInt}\label{ReadInt}
7942
7943 Retrieves an integer value from a file node.
7944
7945 \cvexp{
7946
7947 int cvReadInt( \par const CvFileNode* node,\par int default\_value=0 );
7948
7949 }{CPP}{PYTHON}
7950
7951 \begin{description}
7952 \cvarg{node}{File node}
7953 \cvarg{default\_value}{The value that is returned if \texttt{node} is NULL}
7954 \end{description}
7955
7956
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.
7965
7966 \cvfunc{ReadIntByName}\label{ReadIntByName}
7967
7968 Finds a file node and returns its value.
7969
7970 \cvexp{
7971
7972 int cvReadIntByName( \par const CvFileStorage* fs,\par const CvFileNode* map,\par const char* name,\par int default\_value=0 );
7973
7974 }{CPP}{PYTHON}
7975
7976 \begin{description}
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}
7981 \end{description}
7982
7983 The function \texttt{cvReadIntByName} is a simple superposition of \cross{GetFileNodeByName} and \cross{ReadInt}.
7984
7985
7986 \cvfunc{ReadReal}\label{ReadReal}
7987
7988 Retrieves a floating-point value from a file node.
7989
7990 \cvexp{
7991
7992 double cvReadReal( \par const CvFileNode* node,\par double default\_value=0. );
7993
7994 }{CPP}{PYTHON}
7995
7996 \begin{description}
7997 \cvarg{node}{File node}
7998 \cvarg{default\_value}{The value that is returned if \texttt{node} is NULL}
7999 \end{description}
8000
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.
8009
8010 \cvfunc{ReadRealByName}\label{ReadRealByName}
8011
8012 Finds a file node and returns its value.
8013
8014 \cvexp{
8015
8016 double  cvReadRealByName( \par const CvFileStorage* fs,\par const CvFileNode* map,\par const char* name,\par double default\_value=0. );
8017
8018 }{CPP}{PYTHON}
8019
8020 \begin{description}
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}
8025 \end{description}
8026
8027 The function \texttt{cvReadRealByName} is a simple superposition of \cross{GetFileNodeByName} and \cross{ReadReal}.
8028
8029 \cvfunc{ReadString}\label{ReadString}
8030
8031 Retrieves a text string from a file node.
8032
8033 \cvexp{
8034
8035 const char* cvReadString( \par const CvFileNode* node,\par const char* default\_value=NULL );
8036
8037 }{CPP}{PYTHON}
8038
8039 \begin{description}
8040 \cvarg{node}{File node}
8041 \cvarg{default\_value}{The value that is returned if \texttt{node} is NULL}
8042 \end{description}
8043
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.
8050
8051 \cvfunc{ReadStringByName}\label{ReadStringByName}
8052
8053 Finds a file node by its name and returns its value.
8054
8055 \cvexp{
8056
8057 const char* cvReadStringByName( \par const CvFileStorage* fs,\par const CvFileNode* map,\par const char* name,\par const char* default\_value=NULL );
8058
8059 }{CPP}{PYTHON}
8060
8061 \begin{description}
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}
8066 \end{description}
8067
8068 The function \texttt{cvReadStringByName} is a simple superposition of \cross{GetFileNodeByName} and \cross{ReadString}.
8069
8070 \cvfunc{Read}\label{Read}
8071
8072 Decodes an object and returns a pointer to it.
8073
8074 \cvexp{
8075
8076 void* cvRead( \par CvFileStorage* fs,\par CvFileNode* node,\par CvAttrList* attributes=NULL );
8077
8078 }{CPP}{PYTHON}
8079
8080 \begin{description}
8081 \cvarg{fs}{File storage}
8082 \cvarg{node}{The root object node}
8083 \cvarg{attributes}{Unused parameter}
8084 \end{description}
8085
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}.
8097
8098 \cvfunc{ReadByName}\label{ReadByName}
8099
8100 Finds an object by name and decodes it.
8101
8102 \cvexp{
8103
8104 void* cvReadByName( \par CvFileStorage* fs,\par const CvFileNode* map,\par const char* name,\par CvAttrList* attributes=NULL );
8105
8106 }{CPP}{PYTHON}
8107
8108 \begin{description}
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}
8113 \end{description}
8114
8115 The function \texttt{cvReadByName} is a simple superposition of \cross{GetFileNodeByName} and \cross{Read}.
8116
8117 \cvfunc{ReadRawData}\label{ReadRawData}
8118
8119 Reads multiple numbers.
8120
8121 \cvexp{
8122
8123 void cvReadRawData( \par const CvFileStorage* fs,\par const CvFileNode* src,\par void* dst,\par const char* dt );
8124
8125 }{CPP}{PYTHON}
8126
8127 \begin{description}
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}.}
8132 \end{description}
8133
8134 The function \texttt{cvReadRawData} reads elements from a file node that represents a sequence of scalars.
8135
8136 \cvfunc{StartReadRawData}\label{StartReadRawData}
8137
8138 Initializes the file node sequence reader.
8139
8140 \cvexp{
8141
8142 void cvStartReadRawData( \par const CvFileStorage* fs,\par const CvFileNode* src,\par CvSeqReader* reader );
8143
8144 }{CPP}{PYTHON}
8145
8146 \begin{description}
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}
8150 \end{description}
8151
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}.
8153
8154 \cvfunc{ReadRawDataSlice}\label{ReadRawDataSlice}
8155
8156 Initializes file node sequence reader.
8157
8158 \cvexp{
8159
8160 void cvReadRawDataSlice( \par const CvFileStorage* fs,\par CvSeqReader* reader,\par int count,\par void* dst,\par const char* dt );
8161
8162 }{CPP}{PYTHON}
8163
8164 \begin{description}
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}.}
8170 \end{description}
8171
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}.
8180
8181 \fi
8182
8183 \subsection{RTTI and Generic Functions}
8184
8185 \ifC
8186 \cvstruct{CvTypeInfo}\label{CvTypeInfo}
8187
8188 Type information.
8189
8190 \begin{lstlisting}
8191
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,
8196                                       const char* name,
8197                                       const void* struct_ptr,
8198                                       CvAttrList attributes );
8199 typedef void* (CV_CDECL *CvCloneFunc)( const void* struct_ptr );
8200
8201 typedef struct CvTypeInfo
8202 {
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 */
8208
8209     /* methods */
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 */
8215 }
8216 CvTypeInfo;
8217
8218 \end{lstlisting}
8219
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.
8230
8231 \cvfunc{RegisterType}\label{RegisterType}
8232
8233 Registers a new type.
8234
8235 \cvexp{
8236
8237 void cvRegisterType( const CvTypeInfo* info );
8238
8239 }{CPP}{PYTHON}
8240
8241 \begin{description}
8242 \cvarg{info}{Type info structure}
8243 \end{description}
8244
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.
8248
8249 \cvfunc{UnregisterType}\label{UnregisterType}
8250
8251 Unregisters the type.
8252
8253 \cvexp{
8254
8255 void cvUnregisterType( const char* type\_name );
8256
8257 }{CPP}{PYTHON}
8258
8259 \begin{description}
8260 \cvarg{type\_name}{Name of an unregistered type}
8261 \end{description}
8262
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)}.
8268
8269 \cvfunc{FirstType}\label{FirstType}
8270
8271 Returns the beginning of a type list.
8272
8273 \cvexp{
8274
8275 CvTypeInfo* cvFirstType( void );
8276
8277 }{CPP}{PYTHON}
8278
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.
8280
8281 \cvfunc{FindType}\label{FindType}
8282
8283 Finds a type by its name.
8284
8285 \cvexp{
8286
8287 CvTypeInfo* cvFindType( const char* type\_name );
8288
8289 }{CPP}{PYTHON}
8290
8291 \begin{description}
8292 \cvarg{type\_name}{Type name}
8293 \end{description}
8294
8295 The function \texttt{cvFindType} finds a registered type by its name. It returns NULL if there is no type with the specified name.
8296
8297
8298 \cvfunc{TypeOf}\label{TypeOf}
8299
8300 Returns the type of an object.
8301
8302 \cvexp{
8303
8304 CvTypeInfo* cvTypeOf( const void* struct\_ptr );
8305
8306 }{CPP}{PYTHON}
8307
8308 \begin{description}
8309 \cvarg{struct\_ptr}{The object pointer}
8310 \end{description}
8311
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.
8317
8318 \cvfunc{Release}\label{Release}
8319
8320 Releases an object.
8321
8322 \cvexp{
8323
8324 void cvRelease( void** struct\_ptr );
8325
8326 }{CPP}{PYTHON}
8327
8328 \begin{description}
8329 \cvarg{struct\_ptr}{Double pointer to the object}
8330 \end{description}
8331
8332 The function \texttt{cvRelease} finds the type of a given object and calls \texttt{release} with the double pointer.
8333
8334 \cvfunc{Clone}\label{Clone}
8335
8336 Makes a clone of an object.
8337
8338 \cvexp{
8339
8340 void* cvClone( const void* struct\_ptr );
8341
8342 }{CPP}{PYTHON}
8343
8344 \begin{description}
8345 \cvarg{struct\_ptr}{The object to clone}
8346 \end{description}
8347
8348 The function \texttt{cvClone} finds the type of a given object and calls \texttt{clone} with the passed object.
8349
8350 \fi
8351
8352 \cvfunc{Save}\label{Save}
8353
8354 Saves an object to a file.
8355
8356 \cvexp{
8357
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());
8359
8360 }{CPP}{Save(filename,struct\_ptr,name=NULL,comment=NULL)-> None}
8361
8362 \begin{description}
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}}}
8368 \end{description}
8369
8370 The function \texttt{cvSave} saves an object to a file. It provides a simple interface to \cross{Write}.
8371
8372 \cvfunc{Load}\label{Load}
8373
8374 Loads an object from a file.
8375
8376 \cvexp{
8377
8378 void* cvLoad( \par const char* filename,\par CvMemStorage* memstorage=NULL,\par const char* name=NULL,\par const char** real\_name=NULL );
8379
8380 }{CPP}{Load(filename,storage=NULL,name=NULL)-> generic}
8381
8382 \begin{description}
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})}}
8387 \end{description}
8388
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.
8394
8395 \section{Miscellaneous Functions}
8396
8397 \subsection{Miscellaneous Functions}
8398
8399 \cvfunc{CheckArr}\label{CheckArr}
8400
8401 Checks every element of an input array for invalid values.
8402
8403 \cvexp{
8404
8405 int  cvCheckArr( \par const CvArr* arr,\par int flags=0,\par double min\_val=0,\par double max\_val=0);
8406
8407 }{CPP}{CheckArr(arr,flags=0,min\_val=0,max\_val=0)-> int}
8408
8409 \ifC
8410 \begin{lstlisting}
8411 #define cvCheckArray cvCheckArr
8412 \end{lstlisting}
8413 \fi
8414
8415 \begin{description}
8416 \cvarg{arr}{The array to check}
8417 \cvarg{flags}{The operation flags, 0 or combination of:
8418 \begin{description}
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}
8421 \end{description}}
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.}
8424 \end{description}
8425
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.
8434
8435 \cvfunc{KMeans2}\label{KMeans2}
8436
8437 Splits set of vectors by a given number of clusters.
8438
8439 \cvexp{
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}
8442
8443 \begin{description}
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)}
8448 \ifC
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
8458 \[
8459 \sum_i ||\texttt{samples}_i - \texttt{centers}_{\texttt{labels}_i}||^2
8460 \]
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.}
8467 \fi
8468 \end{description}
8469
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.
8474
8475 \ifC
8476 \cvfunc{Example: Clustering random samples of multi-gaussian distribution with k-means}
8477 \begin{lstlisting}
8478 #include "cxcore.h"
8479 #include "highgui.h"
8480
8481 void main( int argc, char** argv )
8482 {
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);
8487
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);
8493
8494     cvNamedWindow( "clusters", 1 );
8495
8496     for(;;)
8497     {
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 );
8502
8503         /* generate random sample from multigaussian distribution */
8504         for( k = 0; k < cluster_count; k++ )
8505         {
8506             CvPoint center;
8507             CvMat point_chunk;
8508             center.x = cvRandInt(&rng)%img->width;
8509             center.y = cvRandInt(&rng)%img->height;
8510             cvGetRows( points,
8511                        &point_chunk,
8512                        k*sample_count/cluster_count,
8513                        (k == (cluster_count - 1)) ?
8514                            sample_count :
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) );
8519         }
8520
8521         /* shuffle samples */
8522         for( i = 0; i < sample_count/2; i++ )
8523         {
8524             CvPoint2D32f* pt1 =
8525                 (CvPoint2D32f*)points->data.fl + cvRandInt(&rng)%sample_count;
8526             CvPoint2D32f* pt2 =
8527                 (CvPoint2D32f*)points->data.fl + cvRandInt(&rng)%sample_count;
8528             CvPoint2D32f temp;
8529             CV_SWAP( *pt1, *pt2, temp );
8530         }
8531
8532         cvKMeans2( points, cluster_count, clusters,
8533                    cvTermCriteria( CV_TERMCRIT_EPS+CV_TERMCRIT_ITER, 10, 1.0 ));
8534
8535         cvZero( img );
8536
8537         for( i = 0; i < sample_count; i++ )
8538         {
8539             CvPoint2D32f pt = ((CvPoint2D32f*)points->data.fl)[i];
8540             int cluster_idx = clusters->data.i[i];
8541             cvCircle( img,
8542                       cvPointFrom32f(pt),
8543                       2,
8544                       color_tab[cluster_idx],
8545                       CV_FILLED );
8546         }
8547
8548         cvReleaseMat( &points );
8549         cvReleaseMat( &clusters );
8550
8551         cvShowImage( "clusters", img );
8552
8553         int key = cvWaitKey(0);
8554         if( key == 27 )
8555             break;
8556     }
8557 }
8558 \end{lstlisting}
8559
8560 \fi
8561
8562 \ifC
8563 \cvfunc{SeqPartition}\label{SeqPartition}
8564
8565 Splits a sequence into equivalency classes.
8566
8567 \begin{lstlisting}
8568 typedef int (CV_CDECL* CvCmpFunc)(const void* a, const void* b, void* userdata);
8569 \end{lstlisting}
8570
8571 \cvexp{
8572 int cvSeqPartition( \par const CvSeq* seq,\par CvMemStorage* storage,\par CvSeq** labels,\par CvCmpFunc is\_equal,\par void* userdata );
8573 }{CPP}{PYTHON}
8574
8575 \begin{description}
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}
8581 \end{description}
8582
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.
8586
8587 \cvfunc{Example: Partitioning a 2d point set}
8588 \begin{lstlisting}
8589
8590 #include "cxcore.h"
8591 #include "highgui.h"
8592 #include <stdio.h>
8593
8594 CvSeq* point_seq = 0;
8595 IplImage* canvas = 0;
8596 CvScalar* colors = 0;
8597 int pos = 10;
8598
8599 int is_equal( const void* _a, const void* _b, void* userdata )
8600 {
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)) <=
8605         threshold;
8606 }
8607
8608 void on_track( int pos )
8609 {
8610     CvSeq* labels = 0;
8611     double threshold = pos*pos;
8612     int i, class_count = cvSeqPartition( point_seq,
8613                                          0,
8614                                          &labels,
8615                                          is_equal,
8616                                          &threshold );
8617     printf("%4d classes\n", class_count );
8618     cvZero( canvas );
8619
8620     for( i = 0; i < labels->total; i++ )
8621     {
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 );
8625     }
8626
8627     cvShowImage( "points", canvas );
8628 }
8629
8630 int main( int argc, char** argv )
8631 {
8632     CvMemStorage* storage = cvCreateMemStorage(0);
8633     point_seq = cvCreateSeq( CV_32SC2,
8634                              sizeof(CvSeq),
8635                              sizeof(CvPoint),
8636                              storage );
8637     CvRNG rng = cvRNG(0xffffffff);
8638
8639     int width = 500, height = 500;
8640     int i, count = 1000;
8641     canvas = cvCreateImage( cvSize(width,height), 8, 3 );
8642
8643     colors = (CvScalar*)cvAlloc( count*sizeof(colors[0]) );
8644     for( i = 0; i < count; i++ )
8645     {
8646         CvPoint pt;
8647         int icolor;
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,
8653                            (icolor >> 8)&255,
8654                            (icolor >> 16)&255);
8655     }
8656
8657     cvNamedWindow( "points", 1 );
8658     cvCreateTrackbar( "threshold", "points", &pos, 50, on_track );
8659     on_track(pos);
8660     cvWaitKey(0);
8661     return 0;
8662 }
8663 \end{lstlisting}
8664
8665 \fi
8666
8667 \section{Error Handling and System Functions}
8668
8669 \subsection{Error Handling}
8670
8671 \ifPython
8672 Errors in argument type cause a \texttt{TypeError} exception.
8673 OpenCV errors cause a cv.error exception.
8674 \fi
8675
8676 \ifC
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.
8686
8687 There are three modes of error handling (see \cross{SetErrMode} and
8688 \cross{GetErrMode}):
8689
8690 \begin{description}
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
8695 control.}
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
8701 is called}
8702 \end{description}
8703
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.  
8705
8706 \cvfunc{ERROR Handling Macros}\label{ERROR Handling Macros}
8707
8708 Macros for raising an error, checking for errors, etc.
8709
8710 \begin{lstlisting}
8711
8712 /* special macros for enclosing processing statements within a function and separating
8713    them from prologue (resource initialization) and epilogue (guaranteed resource release) */
8714 #define __BEGIN__       {
8715 #define __END__         goto exit; exit: ; }
8716 /* proceeds to "resource release" stage */
8717 #define EXIT            goto exit
8718
8719 /* Declares locally the function name for CV_ERROR() use */
8720 #define CV_FUNCNAME( Name )  \
8721     static char cvFuncName[] = Name
8722
8723 /* Raises an error within the current context */
8724 #define CV_ERROR( Code, Msg )                                       \
8725 {                                                                   \
8726      cvError( (Code), cvFuncName, Msg, __FILE__, __LINE__ );        \
8727      EXIT;                                                          \
8728 }
8729
8730 /* Checks status after calling CXCORE function */
8731 #define CV_CHECK()                                                  \
8732 {                                                                   \
8733     if( cvGetErrStatus() < 0 )                                   \
8734         CV_ERROR( CV_StsBackTrace, "Inner function failed." );      \
8735 }
8736
8737 /* Provies shorthand for CXCORE function call and CV_CHECK() */
8738 #define CV_CALL( Statement )                                        \
8739 {                                                                   \
8740     Statement;                                                      \
8741     CV_CHECK();                                                     \
8742 }
8743
8744 /* Checks some condition in both debug and release configurations */
8745 #define CV_ASSERT( Condition )                                          \
8746 {                                                                       \
8747     if( !(Condition) )                                                  \
8748         CV_ERROR( CV_StsInternal, "Assertion: " #Condition " failed" ); \
8749 }
8750
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) ...
8757
8758 \end{lstlisting}
8759
8760 Instead of a discussion, below is a documented example of a typical CXCORE function and an example of the function use.
8761
8762 \cvfunc{Example: Use of Error Handling Macros}
8763 \begin{lstlisting}
8764
8765 #include "cxcore.h"
8766 #include <stdio.h>
8767
8768 void cvResizeDCT( CvMat* input_array, CvMat* output_array )
8769 {
8770     CvMat* temp_array = 0; // declare pointer that should be released anyway.
8771
8772     CV_FUNCNAME( "cvResizeDCT" ); // declare cvFuncName
8773
8774     __BEGIN__; // start processing. There may be some declarations just after 
8775               // this macro, but they could not be accessed from the epilogue.
8776
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" );
8781
8782     // some restrictions that are going to be removed later, may be checked 
8783     // with CV_ASSERT()
8784     CV_ASSERT( input_array->rows == 1 && output_array->rows == 1 );
8785
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 ));
8791
8792     if( output_array->cols > input_array->cols )
8793         CV_CALL( cvZero( temp_array ));
8794
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,
8800                       output_array,
8801                       1./sqrt((double)input_array->cols*output_array->cols), 0 ));
8802
8803     __END__; // finish processing. Epilogue follows after the macro.
8804
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 );
8809 }
8810
8811 int main( int argc, char** argv )
8812 {
8813     CvMat* src = cvCreateMat( 1, 512, CV_32F );
8814 #if 1 /* no errors */
8815     CvMat* dst = cvCreateMat( 1, 256, CV_32F );
8816 #else
8817     CvMat* dst = 0; /* test error processing mechanism */
8818 #endif
8819     cvSet( src, cvRealScalar(1.), 0 );
8820 #if 0 /* change 0 to 1 to suppress error handler invocation */
8821     cvSetErrMode( CV_ErrModeSilent );
8822 #endif
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" );
8829     else
8830         printf("Everything is OK" );
8831     return 0;
8832 }
8833
8834 \end{lstlisting}
8835
8836 \cvfunc{GetErrStatus}\label{GetErrStatus}
8837
8838 Returns the current error status.
8839
8840 \cvexp{
8841 int cvGetErrStatus( void );
8842 }{CPP}{PYTHON}
8843
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.
8850
8851 \cvfunc{SetErrStatus}\label{SetErrStatus}
8852
8853 Sets the error status.
8854
8855 \cvexp{
8856 void cvSetErrStatus( int status );
8857 }{CPP}{PYTHON}
8858
8859 \begin{description}
8860 \cvarg{status}{The error status}
8861 \end{description}
8862
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}.
8864
8865 \cvfunc{GetErrMode}\label{GetErrMode}
8866
8867 Returns the current error mode.
8868
8869 \cvexp{
8870 int cvGetErrMode( void );
8871 }{CPP}{PYTHON}
8872
8873 The function \texttt{cvGetErrMode} returns the current error mode - the value set with the last \cross{SetErrMode} call.
8874
8875 \cvfunc{SetErrMode}\label{SetErrMode}
8876
8877 Sets the error mode.
8878
8879 \begin{lstlisting}
8880 #define CV_ErrModeLeaf    0
8881 #define CV_ErrModeParent  1
8882 #define CV_ErrModeSilent  2
8883 \end{lstlisting}
8884
8885 \cvexp{
8886 int cvSetErrMode( int mode );
8887 }{CPP}{PYTHON}
8888
8889 \begin{description}
8890 \cvarg{mode}{The error mode}
8891 \end{description}
8892
8893 The function \texttt{cvSetErrMode} sets the specified error mode. For descriptions of different error modes, see the beginning of the error section.
8894
8895 \cvfunc{Error}\label{Error}
8896
8897 Raises an error.
8898
8899 \cvexp{
8900 int cvError( \par int status,\par const char* func\_name,\par const char* err\_msg,\par const char* file\_name,\par int line );
8901 }{CPP}{PYTHON}
8902
8903 \begin{description}
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}
8909 \end{description}
8910
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.
8912
8913 \cvfunc{ErrorStr}\label{ErrorStr}
8914
8915 Returns textual description of an error status code.
8916
8917 \cvexp{
8918 const char* cvErrorStr( int status );
8919 }{CPP}{PYTHON}
8920
8921 \begin{description}
8922 \cvarg{status}{The error status}
8923 \end{description}
8924
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.
8928
8929 \cvfunc{RedirectError}\label{RedirectError}
8930
8931 Sets a new error handler.
8932
8933 \begin{lstlisting}
8934 typedef int (CV_CDECL *CvErrorCallback)( int status, const char* func_name,
8935                     const char* err_msg, const char* file_name, int line );
8936 \end{lstlisting}
8937
8938 \cvexp{
8939 CvErrorCallback cvRedirectError( \par CvErrorCallback error\_handler,\par void* userdata=NULL,\par void** prev\_userdata=NULL );
8940 }{CPP}{PYTHON}
8941
8942 \begin{description}
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}
8946 \end{description}
8947
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.
8954
8955
8956 \cvfunc{cvNulDevReport cvStdErrReport cvGuiBoxReport}
8957 \label{cvNulDevReport}
8958 \label{cvStdErrReport}
8959 \label{cvGuiBoxReport}
8960
8961 Provide standard error handling.
8962
8963 \begin{lstlisting}
8964
8965 int cvNulDevReport( int status, const char* func_name,
8966                     const char* err_msg, const char* file_name,
8967                     int line, void* userdata );
8968
8969 int cvStdErrReport( int status, const char* func_name,
8970                     const char* err_msg, const char* file_name,
8971                     int line, void* userdata );
8972
8973 int cvGuiBoxReport( int status, const char* func_name,
8974                     const char* err_msg, const char* file_name,
8975                     int line, void* userdata );
8976
8977 \end{lstlisting}
8978
8979 \begin{description}
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}
8986 \end{description}
8987
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.
8996
8997 Error Message Box
8998
8999 \includegraphics[width=0.5\textwidth]{pics/errmsg.png}
9000
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.
9002
9003 Error Message printed to Standard Error Output (in \texttt{Leaf} mode)
9004
9005 \begin{verbatim}
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...
9009 \end{verbatim}
9010
9011 \fi
9012
9013 \ifC
9014 \subsection{System and Utility Functions}
9015
9016 \cvfunc{Alloc}\label{Alloc}
9017
9018 Allocates a memory buffer.
9019
9020 \cvexp{
9021 void* cvAlloc( size\_t size );
9022 }{CPP}{PYTHON}
9023
9024 \begin{description}
9025 \cvarg{size}{Buffer size in bytes}
9026 \end{description}
9027
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.
9034
9035 \cvfunc{Free}\label{Free}
9036
9037 Deallocates a memory buffer.
9038
9039 \cvexp{
9040
9041 void cvFree( void** ptr );
9042
9043 }{CPP}{PYTHON}
9044
9045 \begin{description}
9046 \cvarg{ptr}{Double pointer to released buffer}
9047 \end{description}
9048
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
9052 does nothing.
9053
9054 \cvfunc{GetTickCount}\label{GetTickCount}
9055
9056 Returns the number of ticks.
9057
9058 \cvexp{
9059 int64 cvGetTickCount( void );
9060 }{CPP}{PYTHON}
9061
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}.
9063
9064 \cvfunc{GetTickFrequency}\label{GetTickFrequency}
9065
9066 Returns the number of ticks per microsecond.
9067
9068 \cvexp{
9069
9070 double cvGetTickFrequency( void );
9071
9072 }{CPP}{PYTHON}
9073
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.
9075
9076 \cvfunc{RegisterModule}\label{RegisterModule}
9077
9078 Registers another module.
9079
9080 \begin{lstlisting}
9081 typedef struct CvPluginFuncInfo
9082 {
9083     void** func_addr;
9084     void* default_func_addr;
9085     const char* func_names;
9086     int search_modules;
9087     int loaded_from;
9088 }
9089 CvPluginFuncInfo;
9090
9091 typedef struct CvModuleInfo
9092 {
9093     struct CvModuleInfo* next;
9094     const char* name;
9095     const char* version;
9096     CvPluginFuncInfo* func_tab;
9097 }
9098 CvModuleInfo;
9099 \end{lstlisting}
9100
9101 \cvexp{
9102 int cvRegisterModule( const CvModuleInfo* module\_info );
9103 }{CPP}{PYTHON}
9104
9105 \begin{description}
9106 \cvarg{module\_info}{Information about the module}
9107 \end{description}
9108
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.
9120
9121 \cvfunc{GetModuleInfo}\label{GetModuleInfo}
9122
9123 Retrieves information about registered module(s) and plugins.
9124
9125 \cvexp{
9126 void  cvGetModuleInfo( \par const char* module\_name,\par const char** version,\par const char** loaded\_addon\_plugins );
9127 }{CPP}{PYTHON}
9128
9129 \begin{description}
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}
9133 \end{description}
9134
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
9138 text strings.
9139
9140 \cvfunc{UseOptimized}\label{UseOptimized}
9141
9142 Switches between optimized/non-optimized modes.
9143
9144 \cvexp{
9145
9146 int cvUseOptimized( int on\_off );
9147
9148 }{CPP}{PYTHON}
9149
9150 \begin{description}
9151 \cvarg{on\_off}{Use optimized ($\ne 0$) or not ($=0$)}
9152 \end{description}
9153
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).
9163
9164 \cvfunc{SetMemoryManager}\label{SetMemoryManager}
9165
9166 Accesses custom/default memory managing functions.
9167
9168 \begin{lstlisting}
9169 typedef void* (CV_CDECL *CvAllocFunc)(size_t size, void* userdata);
9170 typedef int (CV_CDECL *CvFreeFunc)(void* pptr, void* userdata);
9171 \end{lstlisting}
9172
9173 \cvexp{
9174 void cvSetMemoryManager( \par CvAllocFunc alloc\_func=NULL,\par CvFreeFunc free\_func=NULL,\par void* userdata=NULL );
9175 }{CPP}{PYTHON}
9176
9177 \begin{description}
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}
9181 \end{description}
9182
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.
9190
9191 If the \texttt{alloc\_func} and \texttt{free\_func} pointers are
9192 \texttt{NULL}, the default memory managing functions are restored.
9193
9194 \cvfunc{SetIPLAllocators}\label{SetIPLAllocators}
9195
9196 Switches to IPL functions for image allocation/deallocation.
9197
9198 \begin{lstlisting}
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*);
9206
9207 #define CV_TURN_ON_IPL_COMPATIBILITY()                                  \
9208     cvSetIPLAllocators( iplCreateImageHeader, iplAllocateImage,         \
9209                         iplDeallocate, iplCreateROI, iplCloneImage )
9210 \end{lstlisting}
9211
9212 \cvexp{
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 );
9219 }{CPP}{PYTHON}
9220
9221 \begin{description}
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}
9227 \end{description}
9228
9229
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.
9239
9240 \fi
9241