]> rtime.felk.cvut.cz Git - opencv.git/blob - opencv/doc2/CxCore.tex
preparations for improvement of latex->sphinx rendering
[opencv.git] / opencv / doc2 / 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 \cvstruct{CvPoint2D32f}\label{CvPoint2D32f}
34
35 2D point with floating-point coordinates
36
37 \begin{lstlisting}
38
39 typedef struct CvPoint2D32f
40 {
41     float x;
42     float y; 
43 }
44 CvPoint2D32f;
45 \end{lstlisting}
46
47 \begin{description}
48 \cvarg{x}{x-coordinate}
49 \cvarg{y}{y-coordinate}
50 \end{description}
51
52 \begin{lstlisting}
53 /* Constructor */
54 inline CvPoint2D32f cvPoint2D32f( double x, double y );
55
56 /* Conversion from CvPoint */
57 inline CvPoint2D32f cvPointTo32f( CvPoint point );
58
59 \end{lstlisting}
60
61
62 \cvstruct{CvPoint3D32f}\label{CvPoint3D32f}
63
64 3D point with floating-point coordinates
65
66 \begin{lstlisting}
67
68 typedef struct CvPoint3D32f
69 {
70     float x; 
71     float y; 
72     float z; 
73 }
74 CvPoint3D32f;
75 \end{lstlisting}
76
77 \begin{description}
78 \cvarg{x}{x-coordinate}
79 \cvarg{y}{y-coordinate}
80 \cvarg{z}{z-coordinate}
81 \end{description}
82
83 \begin{lstlisting}
84 /* Constructor */
85 inline CvPoint3D32f cvPoint3D32f( double x, double y, double z );
86
87 \end{lstlisting}
88
89 \cvstruct{CvPoint2D64f}\label{CvPoint2D64f}
90
91 2D point with double precision floating-point coordinates
92
93 \begin{lstlisting}
94
95 typedef struct CvPoint2D64f
96 {
97     double x; 
98     double y; 
99 }
100 CvPoint2D64f;
101 \end{lstlisting}
102
103 \begin{description}
104 \cvarg{x}{x-coordinate}
105 \cvarg{y}{y-coordinate}
106 \end{description}
107
108 \begin{lstlisting}
109 /* Constructor */
110 inline CvPoint2D64f cvPoint2D64f( double x, double y );
111
112 /* Conversion from CvPoint */
113 inline CvPoint2D64f cvPointTo64f( CvPoint point );
114
115 \end{lstlisting}
116
117 \cvstruct{CvPoint3D64f}\label{CvPoint3D64f}
118
119 3D point with double precision floating-point coordinates
120
121 \begin{lstlisting}
122
123 typedef struct CvPoint3D64f
124 {
125     double x; 
126     double y; 
127     double z; 
128 }
129 CvPoint3D64f;
130 \end{lstlisting}
131
132 \begin{description}
133 \cvarg{x}{x-coordinate}
134 \cvarg{y}{y-coordinate}
135 \cvarg{z}{z-coordinate}
136 \end{description}
137
138 \begin{lstlisting}
139 /* Constructor */
140 inline CvPoint3D64f cvPoint3D64f( double x, double y, double z );
141
142 \end{lstlisting}
143
144 \cvstruct{CvSize}\label{CvSize}
145
146 Pixel-accurate size of a rectangle.
147
148 \begin{lstlisting}
149
150 typedef struct CvSize
151 {
152     int width; 
153     int height; 
154 }
155 CvSize;
156 \end{lstlisting}
157
158 \begin{description}
159 \cvarg{width}{Width of the rectangle}
160 \cvarg{height}{Height of the rectangle}
161 \end{description}
162
163 \begin{lstlisting}
164 /* Constructor */
165 inline CvSize cvSize( int width, int height );
166
167 \end{lstlisting}
168
169 \cvstruct{CvSize2D32f}\label{CvSize2D32f}
170
171 Sub-pixel accurate size of a rectangle.
172
173 \begin{lstlisting}
174
175 typedef struct CvSize2D32f
176 {
177     float width; 
178     float height; 
179 }
180 CvSize2D32f;
181 \end{lstlisting}
182
183 \begin{description}
184 \cvarg{width}{Width of the rectangle}
185 \cvarg{height}{Height of the rectangle}
186 \end{description}
187
188 \begin{lstlisting}
189 /* Constructor */
190 inline CvSize2D32f cvSize2D32f( double width, double height );
191
192 \end{lstlisting}
193
194 \cvstruct{CvRect}\label{CvRect}
195
196 Offset (usually the top-left corner) and size of a rectangle.
197
198 \begin{lstlisting}
199
200 typedef struct CvRect
201 {
202     int x; 
203     int y; 
204     int width; 
205     int height; 
206 }
207 CvRect;
208 \end{lstlisting}
209
210 \begin{description}
211 \cvarg{x}{x-coordinate of the top-left corner}
212 \cvarg{y}{y-coordinate of the top-left corner (bottom-left for Windows bitmaps)}
213 \cvarg{width}{Width of the rectangle}
214 \cvarg{height}{Height of the rectangle}
215 \end{description}
216
217 \begin{lstlisting}
218 /* Constructor */
219 inline CvRect cvRect( int x, int y, int width, int height );
220
221 \end{lstlisting}
222
223 \cvstruct{CvScalar}\label{CvScalar}
224
225 A container for 1-,2-,3- or 4-tuples of doubles.
226
227 \begin{lstlisting}
228
229 typedef struct CvScalar
230 {
231     double val[4];
232 }
233 CvScalar;
234
235 \end{lstlisting}
236
237 \begin{lstlisting}
238 /* Constructor: 
239 initializes val[0] with val0, val[1] with val1, etc. 
240 */
241 inline CvScalar cvScalar( double val0, double val1=0,
242                           double val2=0, double val3=0 );
243 /* Constructor: 
244 initializes all of val[0]...val[3] with val0123 
245 */
246 inline CvScalar cvScalarAll( double val0123 );
247
248 /* Constructor: 
249 initializes val[0] with val0, and all of val[1]...val[3] with zeros 
250 */
251 inline CvScalar cvRealScalar( double val0 );
252
253 \end{lstlisting}
254
255 \cvstruct{CvTermCriteria}\label{CvTermCriteria}
256
257 Termination criteria for iterative algorithms.
258
259 \begin{lstlisting}
260
261 #define CV_TERMCRIT_ITER    1
262 #define CV_TERMCRIT_NUMBER  CV_TERMCRIT_ITER
263 #define CV_TERMCRIT_EPS     2
264
265 typedef struct CvTermCriteria
266 {
267     int    type;
268     int    max_iter; 
269     double epsilon; 
270 }
271 CvTermCriteria;
272 \end{lstlisting}
273
274 \begin{description}
275 \cvarg{type}{A combination of CV\_TERMCRIT\_ITER and CV\_TERMCRIT\_EPS}
276 \cvarg{max\_iter}{Maximum number of iterations}
277 \cvarg{epsilon}{Required accuracy}
278 \end{description}
279
280 \begin{lstlisting}
281 /* Constructor */
282 inline CvTermCriteria cvTermCriteria( int type, int max_iter, double epsilon );
283
284 /* Check and transform a CvTermCriteria so that 
285    type=CV_TERMCRIT_ITER+CV_TERMCRIT_EPS
286    and both max_iter and epsilon are valid */
287 CvTermCriteria cvCheckTermCriteria( CvTermCriteria criteria,
288                                     double default_eps,
289                                     int default_max_iters );
290
291 \end{lstlisting}
292
293 \cvstruct{CvMat}\label{CvMat}
294
295 A multi-channel matrix.
296
297 \begin{lstlisting}
298
299 typedef struct CvMat
300 {
301     int type; 
302     int step; 
303
304     int* refcount; 
305
306     union
307     {
308         uchar* ptr;
309         short* s;
310         int* i;
311         float* fl;
312         double* db;
313     } data; 
314
315 #ifdef __cplusplus
316     union
317     {
318         int rows;
319         int height;
320     };
321
322     union
323     {
324         int cols;
325         int width;
326     };
327 #else
328     int rows; 
329     int cols; 
330 #endif
331
332 } CvMat;
333
334 \end{lstlisting}
335
336 \begin{description}
337 \cvarg{type}{A CvMat signature (CV\_MAT\_MAGIC\_VAL) containing the type of elements and flags}
338 \cvarg{step}{Full row length in bytes}
339 \cvarg{refcount}{Underlying data reference counter}
340 \cvarg{data}{Pointers to the actual matrix data}
341 \cvarg{rows}{Number of rows}
342 \cvarg{cols}{Number of columns}
343 \end{description}
344
345
346 Matrices are stored row by row. All of the rows are aligned by 4 bytes.
347
348
349 \cvstruct{CvMatND}\label{CvMatND}
350
351 Multi-dimensional dense multi-channel array.
352
353 \begin{lstlisting}
354
355 typedef struct CvMatND
356 {
357     int type; 
358     int dims;
359
360     int* refcount; 
361
362     union
363     {
364         uchar* ptr;
365         short* s;
366         int* i;
367         float* fl;
368         double* db;
369     } data; 
370
371     struct
372     {
373         int size;
374         int step;
375     }
376     dim[CV_MAX_DIM];
377
378 } CvMatND;
379
380 \end{lstlisting}
381
382 \begin{description}
383 \cvarg{type}{A CvMatND signature (CV\_MATND\_MAGIC\_VAL), combining the type of elements and flags}
384 \cvarg{dims}{The number of array dimensions}
385 \cvarg{refcount}{Underlying data reference counter}
386 \cvarg{data}{Pointers to the actual matrix data}
387 \cvarg{dim}{For each dimension, the pair (number of elements, distance between elements in bytes)}
388 \end{description}
389
390 \cvstruct{CvSparseMat}\label{CvSparseMat}
391
392 Multi-dimensional sparse multi-channel array.
393
394 \begin{lstlisting}
395
396 typedef struct CvSparseMat
397 {
398     int type;
399     int dims; 
400     int* refcount; 
401     struct CvSet* heap; 
402     void** hashtable; 
403     int hashsize;
404     int total; 
405     int valoffset; 
406     int idxoffset; 
407     int size[CV_MAX_DIM]; 
408
409 } CvSparseMat;
410
411 \end{lstlisting}
412
413 \begin{description}
414 \cvarg{type}{A CvSparseMat signature (CV\_SPARSE\_MAT\_MAGIC\_VAL), combining the type of elements and flags.}
415 \cvarg{dims}{Number of dimensions}
416 \cvarg{refcount}{Underlying reference counter. Not used.}
417 \cvarg{heap}{A pool of hash table nodes}
418 \cvarg{hashtable}{The hash table. Each entry is a list of nodes.}
419 \cvarg{hashsize}{Size of the hash table}
420 \cvarg{total}{Total number of sparse array nodes}
421 \cvarg{valoffset}{The value offset of the array nodes, in bytes}
422 \cvarg{idxoffset}{The index offset of the array nodes, in bytes}
423 \cvarg{size}{Array of dimension sizes}
424 \end{description}
425
426 \cvstruct{IplImage}\label{IplImage}
427
428 IPL image header
429
430 \begin{lstlisting}
431
432 typedef struct _IplImage
433 {
434     int  nSize;         
435     int  ID;            
436     int  nChannels;     
437     int  alphaChannel;  
438     int  depth;         
439     char colorModel[4]; 
440     char channelSeq[4]; 
441     int  dataOrder;     
442     int  origin;        
443     int  align;         
444     int  width;         
445     int  height;        
446     struct _IplROI *roi; 
447     struct _IplImage *maskROI; 
448     void  *imageId;     
449     struct _IplTileInfo *tileInfo; 
450     int  imageSize;                             
451     char *imageData;  
452     int  widthStep;   
453     int  BorderMode[4]; 
454     int  BorderConst[4]; 
455     char *imageDataOrigin; 
456 }
457 IplImage;
458
459 \end{lstlisting}
460
461 \begin{description}
462 \cvarg{nSize}{\texttt{sizeof(IplImage)}}
463 \cvarg{ID}{Version, always equals 0}
464 \cvarg{nChannels}{Number of channels. Most OpenCV functions support 1-4 channels.}
465 \cvarg{alphaChannel}{Ignored by OpenCV}
466 \cvarg{depth}{Pixel depth in bits. The supported depths are:
467 \begin{description}
468 \cvarg{IPL\_DEPTH\_8U}{Unsigned 8-bit integer}
469 \cvarg{IPL\_DEPTH\_8S}{Signed 8-bit integer}
470 \cvarg{IPL\_DEPTH\_16U}{Unsigned 16-bit integer}
471 \cvarg{IPL\_DEPTH\_16S}{Signed 16-bit integer}
472 \cvarg{IPL\_DEPTH\_32S}{Signed 32-bit integer}
473 \cvarg{IPL\_DEPTH\_32F}{Single-precision floating point}
474 \cvarg{IPL\_DEPTH\_64F}{Double-precision floating point}
475 \end{description}}
476 \cvarg{colorModel}{Ignored by OpenCV. The OpenCV function \cross{CvtColor} requires the source and destination color spaces as parameters.}
477 \cvarg{channelSeq}{Ignored by OpenCV}
478 \cvarg{dataOrder}{0 = \texttt{IPL\_DATA\_ORDER\_PIXEL} - interleaved color channels, 1 - separate color channels. \cross{CreateImage} only creates images with interleaved channels. For example, the usual layout of a color image is: $ b_{00} g_{00} r_{00} b_{10} g_{10} r_{10} ...$}
479 \cvarg{origin}{0 - top-left origin, 1 - bottom-left origin (Windows bitmap style)}
480 \cvarg{align}{Alignment of image rows (4 or 8). OpenCV ignores this and uses widthStep instead.}
481 \cvarg{width}{Image width in pixels}
482 \cvarg{height}{Image height in pixels}
483 \cvarg{roi}{Region Of Interest (ROI). If not NULL, only this image region will be processed.}
484 \cvarg{maskROI}{Must be NULL in OpenCV}
485 \cvarg{imageId}{Must be NULL in OpenCV}
486 \cvarg{tileInfo}{Must be NULL in OpenCV}
487 \cvarg{imageSize}{Image data size in bytes. For interleaved data, this equals $\texttt{image->height} \cdot \texttt{image->widthStep}$ }
488 \cvarg{imageData}{A pointer to the aligned image data}
489 \cvarg{widthStep}{The size of an aligned image row, in bytes}
490 \cvarg{BorderMode}{Border completion mode, ignored by OpenCV}
491 \cvarg{BorderConst}{Border completion mode, ignored by OpenCV}
492 \cvarg{imageDataOrigin}{A pointer to the origin of the image data (not necessarily aligned). This is used for image deallocation.}
493 \end{description}
494
495 The \cross{IplImage} structure was inherited from the Intel Image Processing Library, in which the format is native. OpenCV only supports a subset of possible \cross{IplImage} formats, as outlined in the parameter list above.
496
497 In addition to the above restrictions, OpenCV handles ROIs differently. OpenCV functions require that the image size or ROI size of all source and destination images match exactly. On the other hand, the Intel Image Processing Library processes the area of intersection between the source and destination images (or ROIs), allowing them to vary independently. 
498
499 \cvstruct{CvArr}\label{CvArr}
500
501 Arbitrary array
502
503 \begin{lstlisting}
504
505 typedef void CvArr;
506
507 \end{lstlisting}
508
509 The metatype \texttt{CvArr} is used \textit{only} as a function parameter to specify that the function accepts arrays of multiple types, such as IplImage*, CvMat* or even CvSeq*. The particular array type is determined at runtime by analyzing the first 4 bytes of the header.
510
511
512 \section{Operations on Arrays}
513
514 \subsection{Initialization}
515
516 \cvfunc{CreateImage}\label{CreateImage}
517
518 Creates an image header and allocates the image data.
519
520 \cvexp{
521 IplImage* cvCreateImage( 
522
523 CvSize size, 
524
525 int depth, 
526
527 int channels );
528 }{CPP}{PYTHON}
529
530 \begin{description}
531 \cvarg{size}{Image width and height}
532 \cvarg{depth}{Bit depth of image elements. See \cross{IplImage} for valid depths.}
533 \cvarg{channels}{Number of channels per pixel. See \cross{IplImage} for details. This function only creates images with interleaved channels.}
534 \end{description}
535
536 This call is a shortened form of
537
538 \begin{lstlisting}
539 header = cvCreateImageHeader( size, depth, channels );
540 cvCreateData( header );
541 \end{lstlisting}
542
543
544 \cvfunc{CreateImageHeader}\label{CreateImageHeader}
545
546 Creates an image header but does not allocate the image data.
547
548 \cvexp{
549 IplImage* cvCreateImageHeader( 
550
551 CvSize size, 
552
553 int depth, 
554
555 int channels );
556 }{CPP}{PYTHON}
557
558 \begin{description}
559 \cvarg{size}{Image width and height}
560 \cvarg{depth}{Image depth (see \cross{CreateImage})}
561 \cvarg{channels}{Number of channels (see \cross{CreateImage})}
562 \end{description}
563
564 This call is an analogue of
565
566 \begin{lstlisting}
567 iplCreateImageHeader( channels, 0, depth,
568                       channels == 1 ? "GRAY" : "RGB",
569                       channels == 1 ? "GRAY" : channels == 3 ? "BGR" :
570                       channels == 4 ? "BGRA" : "",
571                       IPL_DATA_ORDER_PIXEL, IPL_ORIGIN_TL, 4,
572                       size.width, size.height,
573                       0,0,0,0);
574 \end{lstlisting}
575
576 but it does not use IPL functions by default (see the \texttt{CV\_TURN\_ON\_IPL\_COMPATIBILITY} macro).
577
578 \cvfunc{ReleaseImageHeader}\label{ReleaseImageHeader}
579
580 Deallocates an image header.
581
582 \cvexp{
583 void cvReleaseImageHeader( IplImage** image );
584 }{CPP}{PYTHON}
585
586 \begin{description}
587 \cvarg{image}{Double pointer to the image header}
588 \end{description}
589
590 This call is an analogue of
591
592 \begin{lstlisting}
593 if( image )
594 {
595     iplDeallocate( *image, IPL_IMAGE_HEADER | IPL_IMAGE_ROI );
596     *image = 0;
597 }
598 \end{lstlisting}
599
600 but it does not use IPL functions by default (see the \texttt{CV\_TURN\_ON\_IPL\_COMPATIBILITY} macro).
601
602
603 \cvfunc{ReleaseImage}\label{ReleaseImage}
604
605 Deallocates the image header and the image data.
606
607 \cvexp{
608
609 void cvReleaseImage( IplImage** image );
610
611 }{CPP}{PYTHON}
612
613 \begin{description}
614 \cvarg{image}{Double pointer to the image header}
615 \end{description}
616
617 This call is a shortened form of
618
619 \begin{lstlisting}
620
621 if( *image )
622 {
623     cvReleaseData( *image );
624     cvReleaseImageHeader( image );
625 }
626
627 \end{lstlisting}
628
629
630 \cvfunc{InitImageHeader}\label{InitImageHeader}
631
632 Initializes an image header that was previously allocated
633
634 \cvexp{
635
636 IplImage* cvInitImageHeader( \par IplImage* image,\par CvSize size,\par int depth,\par int channels,\par int origin=0,\par int align=4 );
637
638 }{CPP}{PYTHON}
639
640 \begin{description}
641 \cvarg{image}{Image header to initialize}
642 \cvarg{size}{Image width and height}
643 \cvarg{depth}{Image depth (see \cross{CreateImage})}
644 \cvarg{channels}{Number of channels (see \cross{CreateImage})}
645 \cvarg{origin}{Top-left \texttt{IPL\_ORIGIN\_TL} or bottom-left \texttt{IPL\_ORIGIN\_BL}}
646 \cvarg{align}{Alignment for image rows, typically 4 or 8 bytes}
647 \end{description}
648
649 The returned \texttt{IplImage*} points to the initialized header.
650
651 \cvfunc{CloneImage}\label{CloneImage}
652
653 Makes a full copy of an image, including the header, data, and ROI.
654
655 \cvexp{
656
657 IplImage* cvCloneImage( const IplImage* image );
658
659 }{CPP}{PYTHON}
660
661 \begin{description}
662 \cvarg{image}{The original image}
663 \end{description}
664
665 The returned \texttt{IplImage*} points to the image copy.
666
667 \cvfunc{SetImageCOI}\label{SetImageCOI}
668
669 Sets the channel of interest in an IplImage
670
671 \cvexp{
672
673 void cvSetImageCOI( \par IplImage* image,\par int coi );
674
675 }{CPP}{PYTHON}
676
677 \begin{description}
678 \cvarg{image}{A pointer to the image header}
679 \cvarg{coi}{The channel of interest. 0 - all channels are selected, 1 - first channel is selected, etc. Note that the channel indices become 1-based.}
680 \end{description}
681
682 If the ROI is set to \texttt{NULL} and the coi is \textit{not} 0,
683 the ROI is allocated. Most OpenCV functions do \textit{not} support
684 the COI setting, so to process an individual image/matrix channel one
685 may copy (via \cross{Copy} or \cross{Split}) the channel to a separate
686 image/matrix, process it and then copy the result back (via \cross{Copy}
687 or \cross{Merge}) if needed.
688
689 \cvfunc{GetImageCOI}\label{GetImageCOI}
690
691 Returns the index of the channel of interest. 
692
693 \cvexp{
694
695 int cvGetImageCOI( const IplImage* image );
696
697 }{CPP}{PYTHON}
698
699 \begin{description}
700 \cvarg{image}{A pointer to the image header}
701 \end{description}
702
703 Returns the channel of interest of in an IplImage. Returned values correspond to the \texttt{coi} in \cross{SetImageCOI}.
704
705 \cvfunc{SetImageROI}\label{SetImageROI}
706
707 Sets an image Region Of Interest (ROI) to a given rectangle
708
709 \cvexp{
710
711 void cvSetImageROI( \par IplImage* image,\par CvRect rect );
712
713 }{CPP}{PYTHON}
714
715 \begin{description}
716 \cvarg{image}{A pointer to the image header}
717 \cvarg{rect}{The ROI rectangle}
718 \end{description}
719
720 If the original image ROI was \texttt{NULL} and the \texttt{rect} is not the whole image, the ROI structure is allocated.
721
722 Most OpenCV functions support the use of ROI and treat the image rectangle as a separate image. For example, all of the pixel coordinates are counted from the top-left (or bottom-left) corner of the ROI, not the original image.
723
724 \cvfunc{ResetImageROI}\label{ResetImageROI}
725
726 Resets the image ROI to include the entire image and releases the ROI structure.
727
728 \cvexp{
729
730 void cvResetImageROI( IplImage* image );
731
732 }{CPP}{PYTHON}
733
734 \begin{description}
735 \cvarg{image}{A pointer to the image header}
736 \end{description}
737
738 This produces a similar result to the following, but in addition it releases the ROI structure.
739
740 \begin{lstlisting}
741
742 cvSetImageROI( image, cvRect( 0, 0, image->width, image->height ));
743 cvSetImageCOI( image, 0 );
744
745 \end{lstlisting}
746
747
748 \cvfunc{GetImageROI}\label{GetImageROI}
749
750 Returns the image ROI
751
752 \cvexp{
753
754 CvRect cvGetImageROI( const IplImage* image );
755
756 }{CPP}{PYTHON}
757
758 \begin{description}
759 \cvarg{image}{A pointer to the image header}
760 \end{description}
761
762
763 If there is no ROI set, \texttt{cvRect(0,0,image->width,image->height)} is returned.
764
765
766 \cvfunc{CreateMat}\label{CreateMat}
767
768 Creates a matrix header and allocates the matrix data. 
769
770 \cvexp{
771
772 CvMat* cvCreateMat( \par int rows,\par int cols,\par int type );
773
774 }{CPP}{PYTHON}
775
776 \begin{description}
777 \cvarg{rows}{Number of rows in the matrix}
778 \cvarg{cols}{Number of columns in the matrix}
779 \cvarg{type}{The type of the matrix elements in the form \texttt{CV\_<bit depth><S|U|F>C<number of channels>}, where S=signed, U=unsigned, F=float. For example, CV\_8UC1 means the elements are 8-bit unsigned and the there is 1 channel, and CV\_32SC2 means the elements are 32-bit signed and there are 2 channels.}
780 \end{description}
781
782 This is the concise form for:
783
784 \begin{lstlisting}
785
786 CvMat* mat = cvCreateMatHeader( rows, cols, type );
787 cvCreateData( mat );
788
789 \end{lstlisting}
790
791 \cvfunc{CreateMatHeader}\label{CreateMatHeader}
792
793 Creates a matrix header but does not allocate the matrix data.
794
795 \cvexp{
796
797 CvMat* cvCreateMatHeader( \par int rows,\par int cols,\par int type );
798
799 }{CPP}{PYTHON}
800
801 \begin{description}
802 \cvarg{rows}{Number of rows in the matrix}
803 \cvarg{cols}{Number of columns in the matrix}
804 \cvarg{type}{Type of the matrix elements, see \cross{CreateMat}}
805 \end{description}
806
807 The function \texttt{cvCreateMatHeader} allocates new matrix header and returns pointer to it. The matrix data can then be allocated using \cross{CreateData} or set explicitly to user-allocated data via \cross{SetData}.
808
809
810 \cvfunc{ReleaseMat}\label{ReleaseMat}
811
812 Deallocates a matrix
813
814 \cvexp{
815
816 void cvReleaseMat( CvMat** mat );
817
818 }{CPP}{PYTHON}
819
820 \begin{description}
821 \cvarg{mat}{Double pointer to the matrix}
822 \end{description}
823
824
825 The function \texttt{cvReleaseMat} decrements the matrix data reference counter and deallocates matrix header. If the data reference counter is 0, it also deallocates the data.
826
827 \begin{lstlisting}
828
829 if( *mat )
830     cvDecRefData( *mat );
831 cvFree( (void**)mat );
832
833 \end{lstlisting}
834
835
836 \cvfunc{InitMatHeader}\label{InitMatHeader}
837
838 Initializes a pre-allocated matrix header
839
840 \cvexp{
841
842 CvMat* cvInitMatHeader(\par CvMat* mat,\par int rows,\par int cols,\par int type, \par void* data=NULL,\par int step=CV\_AUTOSTEP );
843
844 }{CPP}{PYTHON}
845
846 \begin{description}
847 \cvarg{mat}{A pointer to the matrix header to be initialized}
848 \cvarg{rows}{Number of rows in the matrix}
849 \cvarg{cols}{Number of columns in the matrix}
850 \cvarg{type}{Type of the matrix elements, see \cross{CreateMat}.}
851 \cvarg{data}{Optional: data pointer assigned to the matrix header}
852 \cvarg{step}{Optional: full row width in bytes of the assigned data. By default, the minimal possible step is used which assumes there are no gaps between subsequent rows of the matrix.}
853 \end{description}
854
855 This function is often used to process raw data with OpenCV matrix functions. For example, the following code computes the matrix product of two matrices, stored as ordinary arrays:
856
857 \begin{lstlisting}
858
859 double a[] = { 1, 2, 3, 4
860                5, 6, 7, 8,
861                9, 10, 11, 12 };
862
863 double b[] = { 1, 5, 9,
864                2, 6, 10,
865                3, 7, 11,
866                4, 8, 12 };
867
868 double c[9];
869 CvMat Ma, Mb, Mc ;
870
871 cvInitMatHeader( &Ma, 3, 4, CV_64FC1, a );
872 cvInitMatHeader( &Mb, 4, 3, CV_64FC1, b );
873 cvInitMatHeader( &Mc, 3, 3, CV_64FC1, c );
874
875 cvMatMulAdd( &Ma, &Mb, 0, &Mc );
876 // the c array now contains the product of a (3x4) and b (4x3)
877
878 \end{lstlisting}
879
880 \cvfunc{Mat}\label{Mat}
881
882 Initializes matrix header (light-weight variant)
883
884 \cvexp{
885
886 CvMat cvMat(\par int rows,\par int cols,\par int type,\par void* data=NULL );
887
888 }{CPP}{PYTHON}
889
890 \begin{description}
891 \cvarg{rows}{Number of rows in the matrix}
892 \cvarg{cols}{Number of columns in the matrix}
893 \cvarg{type}{Type of the matrix elements - see \cross{CreateMat}}
894 \cvarg{data}{Optional data pointer assigned to the matrix header}
895 \end{description}
896
897 Initializes a matrix header and assigns data to it. The matrix is filled \textit{row}-wise (the first \texttt{cols} elements of data form the first row of the matrix, etc.)
898
899 This function is a fast inline substitution for \cross{InitMatHeader}. Namely, it is equivalent to:
900
901 \begin{lstlisting}
902
903 CvMat mat;
904 cvInitMatHeader( &mat, rows, cols, type, data, CV\_AUTOSTEP );
905
906 \end{lstlisting}
907
908
909 \cvfunc{CloneMat}\label{CloneMat}
910
911 Creates a full matrix copy
912
913 \cvexp{
914
915 CvMat* cvCloneMat( const CvMat* mat );
916
917 }{CPP}{PYTHON}
918
919 \begin{description}
920 \cvarg{mat}{Matrix to be copied}
921 \end{description}
922
923 Creates a full copy of a matrix and returns a pointer to the copy.
924
925 \cvfunc{CreateMatND}\label{CreateMatND}
926
927 Creates the header and allocates the data for a multi-dimensional dense array.
928
929 \cvexp{
930
931 CvMatND* cvCreateMatND(\par int dims,\par const int* sizes,\par int type );
932
933 }{CPP}{PYTHON}
934
935 \begin{description}
936 \cvarg{dims}{Number of array dimensions. this must not exceed CV\_MAX\_DIM (32 by default, but can be changed at build time.)}
937 \cvarg{sizes}{Array of dimension sizes}
938 \cvarg{type}{Type of array elements, see \cross{CreateMat}. }
939 \end{description}
940
941 This is a short form for:
942
943 \begin{lstlisting}
944
945 CvMatND* mat = cvCreateMatNDHeader( dims, sizes, type );
946 cvCreateData( mat );
947
948 \end{lstlisting}
949
950 \cvfunc{CreateMatNDHeader}\label{CreateMatNDHeader}
951
952 Creates a new matrix header but does not allocate the matrix data.
953
954 \cvexp{
955
956 CvMatND* cvCreateMatNDHeader(\par int dims,\par const int* sizes,\par int type );
957
958 }{CPP}{PYTHON}
959
960 \begin{description}
961 \cvarg{dims}{Number of array dimensions}
962 \cvarg{sizes}{Array of dimension sizes}
963 \cvarg{type}{Type of array elements, see \cross{CreateMat}}
964 \end{description}
965
966 The function \texttt{cvCreateMatND} allocates header for multi-dimensional dense array. The array data can further be allocated using \cross{CreateData} or set explicitly to user-allocated data via \cross{SetData}.
967
968 \cvfunc{ReleaseMatND}\label{ReleaseMatND}
969
970 Deallocates a multi-dimensional array
971
972 \cvexp{
973
974 void cvReleaseMatND( CvMatND** mat );
975
976 }{CPP}{PYTHON}
977
978 \begin{description}
979 \cvarg{mat}{Double pointer to the array}
980 \end{description}
981
982 The function \texttt{cvReleaseMatND} decrements the array data reference counter and releases the array header. If the reference counter reaches 0, it also deallocates the data.
983
984 \begin{lstlisting}
985
986 if( *mat )
987     cvDecRefData( *mat );
988 cvFree( (void**)mat );
989
990 \end{lstlisting}
991
992 \cvfunc{InitMatNDHeader}\label{InitMatNDHeader}
993
994 Initializes a pre-allocated multi-dimensional array header.
995
996 \cvexp{
997
998 CvMatND* cvInitMatNDHeader( \par CvMatND* mat,\par int dims,\par const int* sizes,\par int type,\par void* data=NULL );
999
1000 }{CPP}{PYTHON}
1001
1002 \begin{description}
1003 \cvarg{mat}{A pointer to the array header to be initialized}
1004 \cvarg{dims}{The number of array dimensions}
1005 \cvarg{sizes}{An array of dimension sizes}
1006 \cvarg{type}{Type of array elements, see \cross{CreateMat}}
1007 \cvarg{data}{Optional data pointer assigned to the matrix header}
1008 \end{description}
1009
1010 \cvfunc{CloneMatND}\label{CloneMatND}
1011
1012 Creates full copy of a multi-dimensional array and returns a pointer to the copy.
1013
1014 \cvexp{
1015
1016 CvMatND* cvCloneMatND( const CvMatND* mat );
1017
1018 }{CPP}{PYTHON}
1019
1020 \begin{description}
1021 \cvarg{mat}{Input array}
1022 \end{description}
1023
1024
1025 \cvfunc{DecRefData}\label{DecRefData}
1026
1027 Decrements an array data reference counter
1028
1029 \cvexp{
1030
1031 void cvDecRefData( CvArr* arr );
1032
1033 }{CPP}{PYTHON}
1034
1035 \begin{description}
1036 \cvarg{arr}{Pointer to an array header}
1037 \end{description}
1038
1039 The function \texttt{cvDecRefData} decrements the data reference counter in a \cross{CvMat} or
1040 \cross{CvMatND} if the reference counter pointer
1041 is not NULL. If the counter reaches zero, the data is deallocated. In the
1042 current implementation the reference counter is not NULL only if the data
1043 was allocated using the \cross{CreateData} function. The counter will be NULL in other cases such as:
1044 external data was assigned to the header using \cross{SetData}, the matrix
1045 header is part of a larger matrix or image, or the header was converted from an image or n-dimensional matrix header. 
1046
1047
1048 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1049
1050 \cvfunc{IncRefData}\label{IncRefData}
1051
1052 Increments array data reference counter
1053
1054 \cvexp{
1055
1056 int cvIncRefData( CvArr* arr );
1057
1058 }{CPP}{PYTHON}
1059
1060 \begin{description}
1061 \cvarg{arr}{array header}
1062 \end{description}
1063
1064
1065 The function \texttt{cvIncRefData} increments \cross{CvMat} or
1066 \cross{CvMatND} data reference counter and returns the new counter value
1067 if the reference counter pointer is not NULL, otherwise it returns zero.
1068
1069 \cvfunc{CreateData}\label{CreateData}
1070
1071 Allocates array data
1072
1073 \cvexp{
1074
1075 void cvCreateData( CvArr* arr );
1076
1077 }{CPP}{PYTHON}
1078
1079 \begin{description}
1080 \cvarg{arr}{Array header}
1081 \end{description}
1082
1083
1084 The function \texttt{cvCreateData} allocates image, matrix or
1085 multi-dimensional array data. Note that in case of matrix types OpenCV
1086 allocation functions are used and in case of IplImage they are used
1087 too unless \texttt{CV\_TURN\_ON\_IPL\_COMPATIBILITY} was called. In the
1088 latter case IPL functions are used to allocate the data
1089
1090 \cvfunc{ReleaseData}\label{ReleaseData}
1091
1092 Releases array data
1093
1094 \cvexp{
1095
1096 void cvReleaseData( CvArr* arr );
1097
1098 }{CPP}{PYTHON}
1099
1100 \begin{description}
1101 \cvarg{arr}{Array header}
1102 \end{description}
1103
1104
1105 The function \texttt{cvReleaseData} releases the array data. In case of \cross{CvMat} or \cross{CvMatND} it simply calls cvDecRefData(), that is the function can not deallocate external data. See also the note to \cross{CreateData}.
1106
1107 \cvfunc{SetData}\label{SetData}
1108
1109 Assigns user data to the array header
1110
1111 \cvexp{
1112
1113 void cvSetData( CvArr* arr, void* data, int step );
1114
1115 }{CPP}{PYTHON}
1116
1117 \begin{description}
1118 \cvarg{arr}{Array header}
1119 \cvarg{data}{User data}
1120 \cvarg{step}{Full row length in bytes}
1121 \end{description}
1122
1123
1124 The function \texttt{cvSetData} assigns user data to the array header. Header should be initialized before using cvCreate*Header, cvInit*Header or \cross{Mat} (in case of matrix) function.
1125
1126 \cvfunc{GetRawData}\label{GetRawData}
1127
1128 Retrieves low-level information about the array
1129
1130 \cvexp{
1131
1132 void cvGetRawData( const CvArr* arr, uchar** data,
1133                    int* step=NULL, CvSize* roi\_size=NULL );
1134
1135 }{CPP}{PYTHON}
1136
1137 \begin{description}
1138 \cvarg{arr}{Array header}
1139 \cvarg{data}{Output pointer to the whole image origin or ROI origin if ROI is set}
1140 \cvarg{step}{Output full row length in bytes}
1141 \cvarg{roi\_size}{Output ROI size}
1142 \end{description}
1143
1144 The function \texttt{cvGetRawData} fills output variables with low-level information about the array data. All output parameters are optional, so some of the pointers may be set to \texttt{NULL}. If the array is \texttt{IplImage} with ROI set, parameters of ROI are returned.
1145
1146 The following example shows how to get access to array elements using this function.
1147
1148 Using GetRawData to calculate absolute value of elements of a single-channel floating-point array.
1149
1150 \begin{lstlisting}
1151
1152 float* data;
1153 int step;
1154
1155 CvSize size;
1156 int x, y;
1157
1158 cvGetRawData( array, (uchar**)&data, &step, &size );
1159 step /= sizeof(data[0]);
1160
1161 for( y = 0; y < size.height; y++, data += step )
1162     for( x = 0; x < size.width; x++ )
1163         data[x] = (float)fabs(data[x]);
1164
1165 \end{lstlisting}
1166
1167
1168 \cvfunc{GetMat}\label{GetMat}
1169
1170 Returns matrix header for arbitrary array
1171
1172 \cvexp{
1173
1174 CvMat* cvGetMat( const CvArr* arr, CvMat* header, int* coi=NULL, int allowND=0 );
1175
1176 }{CPP}{PYTHON}
1177
1178 \begin{description}
1179 \cvarg{arr}{Input array}
1180 \cvarg{header}{Pointer to \cross{CvMat} structure used as a temporary buffer}
1181 \cvarg{coi}{Optional output parameter for storing COI}
1182 \cvarg{allowND}{If non-zero, the function accepts multi-dimensional dense arrays (CvMatND*) and returns 2D (if CvMatND has two dimensions) or 1D matrix (when CvMatND has 1 dimension or more than 2 dimensions). The array must be continuous.}
1183 \end{description}
1184
1185 The function \texttt{cvGetMat} returns matrix header for the input array that can be matrix - \cross{CvMat}, image - \texttt{IplImage} or multi-dimensional dense array - \cross{CvMatND} (latter case is allowed only if \texttt{allowND != 0}) . In the case of matrix the function simply returns the input pointer. In the case of \texttt{IplImage*} or \cross{CvMatND} it initializes \texttt{header} structure with parameters of the current image ROI and returns pointer to this temporary structure. Because COI is not supported by \cross{CvMat}, it is returned separately.
1186
1187 The function provides an easy way to handle both types of array - \texttt{IplImage} and \cross{CvMat} -, using the same code. Reverse transform from \cross{CvMat} to \texttt{IplImage} can be done using \cross{GetImage} function.
1188
1189 Input array must have underlying data allocated or attached, otherwise the function fails.
1190
1191 If the input array is \texttt{IplImage} with planar data layout and COI set, the function returns pointer to the selected plane and COI = 0. It enables per-plane processing of multi-channel images with planar data layout using OpenCV functions.
1192
1193 \cvfunc{GetImage}\label{GetImage}
1194
1195 Returns image header for arbitrary array
1196
1197 \cvexp{
1198
1199 IplImage* cvGetImage( const CvArr* arr, IplImage* image\_header );
1200
1201 }{CPP}{PYTHON}
1202
1203 \begin{description}
1204 \cvarg{arr}{Input array}
1205 \cvarg{image\_header}{Pointer to \texttt{IplImage} structure used as a temporary buffer}
1206 \end{description}
1207
1208 The function \texttt{cvGetImage} returns image header for the input array
1209 that can be matrix - \cross{CvMat}, or image - \texttt{IplImage*}. In
1210 the case of image the function simply returns the input pointer. In the
1211 case of \cross{CvMat} it initializes \texttt{image\_header} structure
1212 with parameters of the input matrix. Note that if we transform
1213 \texttt{IplImage} to \cross{CvMat} and then transform CvMat back to
1214 IplImage, we can get different headers if the ROI is set, and thus some
1215 IPL functions that calculate image stride from its width and align may
1216 fail on the resultant image.
1217
1218 \cvfunc{CreateSparseMat}\label{CreateSparseMat}
1219
1220 Creates sparse array
1221
1222 \cvexp{
1223
1224 CvSparseMat* cvCreateSparseMat( int dims, const int* sizes, int type );
1225
1226 }{CPP}{PYTHON}
1227
1228 \begin{description}
1229 \cvarg{dims}{Number of array dimensions. As opposite to the dense matrix, the number of dimensions is practically unlimited (up to $2^16$).}
1230 \cvarg{sizes}{Array of dimension sizes}
1231 \cvarg{type}{Type of array elements. The same as for CvMat}
1232 \end{description}
1233
1234 The function \texttt{cvCreateSparseMat} allocates multi-dimensional sparse array. Initially the array contain no elements, that is \cross{Get} or \cross{GetReadl} return zero for every index
1235
1236 \cvfunc{ReleaseSparseMat}\label{ReleaseSparseMat}
1237
1238 Deallocates sparse array
1239
1240 \cvexp{
1241
1242 void cvReleaseSparseMat( CvSparseMat** mat );
1243
1244 }{CPP}{PYTHON}
1245
1246 \begin{description}
1247 \cvarg{mat}{Double pointer to the array}
1248 \end{description}
1249
1250
1251 The function \texttt{cvReleaseSparseMat} releases the sparse array and clears the array pointer upon exit
1252
1253
1254 \cvfunc{CloneSparseMat}\label{CloneSparseMat}
1255
1256 Creates full copy of sparse array
1257
1258 \cvexp{
1259
1260 CvSparseMat* cvCloneSparseMat( const CvSparseMat* mat );
1261
1262 }{CPP}{PYTHON}
1263
1264 \begin{description}
1265 \cvarg{mat}{Input array}
1266 \end{description}
1267
1268 The function \texttt{cvCloneSparseMat} creates a copy of the input array and returns pointer to the copy.
1269
1270 \subsection{Accessing Elements and sub-Arrays}
1271
1272 \cvfunc{GetSubRect}\label{GetSubRect}
1273
1274 Returns matrix header corresponding to the rectangular sub-array of input image or matrix
1275
1276 \cvexp{
1277
1278 CvMat* cvGetSubRect( const CvArr* arr, CvMat* submat, CvRect rect );
1279
1280 }{CPP}{PYTHON}
1281
1282 \begin{description}
1283 \cvarg{arr}{Input array}
1284 \cvarg{submat}{Pointer to the resultant sub-array header}
1285 \cvarg{rect}{Zero-based coordinates of the rectangle of interest}
1286 \end{description}
1287
1288 The function \texttt{cvGetSubRect} returns header, corresponding to
1289 a specified rectangle of the input array. In other words, it allows
1290 the user to treat a rectangular part of input array as a stand-alone
1291 array. ROI is taken into account by the function so the sub-array of
1292 ROI is actually extracted.
1293
1294 \cvfunc{GetRow, GetRows}\label{GetRow, GetRows}
1295
1296 Returns array row or row span
1297
1298 \cvexp{
1299 CvMat* cvGetRow( const CvArr* arr, CvMat* submat, int row );
1300 }{CPP}{PYTHON}
1301 \cvexp{
1302 CvMat* cvGetRows( const CvArr* arr, CvMat* submat, int start\_row, int end\_row, int delta\_row=1 );
1303 }{CPP}{PYTHON}
1304
1305 \begin{description}
1306 \cvarg{arr}{Input array}
1307 \cvarg{submat}{Pointer to the resulting sub-array header}
1308 \cvarg{row}{Zero-based index of the selected row}
1309 \cvarg{start\_row}{Zero-based index of the starting row (inclusive) of the span}
1310 \cvarg{end\_row}{Zero-based index of the ending row (exclusive) of the span}
1311 \cvarg{delta\_row}{Index step in the row span. That is, the function extracts every \texttt{delta\_row}-th row from \texttt{start\_row} and up to (but not including) \texttt{end\_row}.}
1312 \end{description}
1313
1314
1315 The functions \texttt{GetRow} and \texttt{GetRows} return the header, corresponding to a specified row/row span of the input array. Note that \texttt{GetRow} is a shortcut for \cross{GetRows}:
1316
1317 \begin{lstlisting}
1318
1319 cvGetRow( arr, submat, row ) ~ cvGetRows( arr, submat, row, row + 1, 1 );
1320
1321 \end{lstlisting}
1322
1323
1324 \cvfunc{GetCol, GetCols}\label{GetCol, GetCols}
1325
1326 Returns array column or column span
1327
1328 \cvexp{
1329 CvMat* cvGetCol( const CvArr* arr, CvMat* submat, int col );
1330 }{CPP}{PYTHON}
1331 \cvexp{
1332 CvMat* cvGetCols( const CvArr* arr, CvMat* submat, int start\_col, int end\_col );
1333 }{CPP}{PYTHON}
1334
1335 \begin{description}
1336 \cvarg{arr}{Input array}
1337 \cvarg{submat}{Pointer to the resulting sub-array header}
1338 \cvarg{col}{Zero-based index of the selected column}
1339 \cvarg{start\_col}{Zero-based index of the starting column (inclusive) of the span}
1340 \cvarg{end\_col}{Zero-based index of the ending column (exclusive) of the span}
1341 \end{description}
1342
1343 The functions \texttt{GetCol} and \texttt{GetCols} return the header, corresponding to a specified column/column span of the input array. Note that \texttt{GetCol} is a shortcut for \cross{GetCols}:
1344
1345 \begin{lstlisting}
1346
1347 cvGetCol( arr, submat, col ); // ~ cvGetCols( arr, submat, col, col + 1 );
1348
1349 \end{lstlisting}
1350
1351 \cvfunc{GetDiag}\label{GetDiag}
1352
1353 Returns one of array diagonals
1354
1355 \cvexp{
1356
1357 CvMat* cvGetDiag( const CvArr* arr, CvMat* submat, int diag=0 );
1358
1359 }{CPP}{PYTHON}
1360
1361 \begin{description}
1362 \cvarg{arr}{Input array}
1363 \cvarg{submat}{Pointer to the resulting sub-array header}
1364 \cvarg{diag}{Array diagonal. Zero corresponds to the main diagonal, -1 corresponds to the diagonal above the main etc., 1 corresponds to the diagonal below the main etc.}
1365 \end{description}
1366
1367 The function \texttt{cvGetDiag} returns the header, corresponding to a specified diagonal of the input array.
1368
1369 \cvfunc{GetSize}\label{GetSize}
1370
1371 Returns size of matrix or image ROI
1372
1373 \cvexp{
1374
1375 CvSize cvGetSize( const CvArr* arr );
1376
1377 }{CPP}{PYTHON}
1378
1379 \begin{description}
1380 \cvarg{arr}{array header}
1381 \end{description}
1382
1383 The function \texttt{cvGetSize} returns number of rows (CvSize::height) and number of columns (CvSize::width) of the input matrix or image. In case of image the size of ROI is returned.
1384
1385
1386 \cvfunc{InitSparseMatIterator}\label{InitSparseMatIterator}
1387
1388 Initializes sparse array elements iterator
1389
1390 \cvexp{
1391
1392 CvSparseNode* cvInitSparseMatIterator( const CvSparseMat* mat,
1393                                        CvSparseMatIterator* mat\_iterator );
1394
1395 }{CPP}{PYTHON}
1396
1397 \begin{description}
1398 \cvarg{mat}{Input array}
1399 \cvarg{mat\_iterator}{Initialized iterator}
1400 \end{description}
1401
1402 The function \texttt{cvInitSparseMatIterator} initializes iterator of
1403 sparse array elements and returns pointer to the first element, or NULL
1404 if the array is empty.
1405
1406 \cvfunc{GetNextSparseNode}\label{GetNextSparseNode}
1407
1408 Initializes sparse array elements iterator
1409
1410 \cvexp{
1411
1412 CvSparseNode* cvGetNextSparseNode( CvSparseMatIterator* mat\_iterator );
1413
1414 }{CPP}{PYTHON}
1415
1416 \begin{description}
1417 \cvarg{mat\_iterator}{Sparse array iterator}
1418 \end{description}
1419
1420
1421 The function \texttt{cvGetNextSparseNode} moves iterator to the next sparse matrix element and returns pointer to it. In the current version there is no any particular order of the elements, because they are stored in hash table. The sample below demonstrates how to iterate through the sparse matrix:
1422
1423 Using \cross{InitSparseMatIterator} and \cross{GetNextSparseNode} to calculate sum of floating-point sparse array.
1424
1425 \begin{lstlisting}
1426
1427 double sum;
1428 int i, dims = cvGetDims( array );
1429 CvSparseMatIterator mat_iterator;
1430 CvSparseNode* node = cvInitSparseMatIterator( array, &mat_iterator );
1431
1432 for( ; node != 0; node = cvGetNextSparseNode( &mat_iterator ))
1433 {
1434     /* get pointer to the element indices */
1435     int* idx = CV_NODE_IDX( array, node );
1436     /* get value of the element (assume that the type is CV_32FC1) */
1437     float val = *(float*)CV_NODE_VAL( array, node );
1438     printf( "(" );
1439     for( i = 0; i < dims; i++ )
1440         printf( "%4d%s", idx[i], i < dims - 1 "," : "): " );
1441     printf( "%g\n", val );
1442
1443     sum += val;
1444 }
1445
1446 printf( "\nTotal sum = %g\n", sum );
1447
1448 \end{lstlisting}
1449
1450
1451 \cvfunc{GetElemType}\label{GetElemType}
1452
1453 Returns type of array elements
1454
1455 \cvexp{
1456
1457 int cvGetElemType( const CvArr* arr );
1458
1459 }{CPP}{PYTHON}
1460
1461 \begin{description}
1462 \cvarg{arr}{Input array}
1463 \end{description}
1464
1465
1466 The functions \texttt{GetElemType} returns type of the array elements
1467 as it is described in \cross{CreateMat} discussion: \texttt{CV\_8UC1}
1468 ... \texttt{CV\_64FC4}.
1469
1470
1471 \cvfunc{GetDims, GetDimSize}\label{GetDims, GetDimSize}
1472
1473 Return number of array dimensions and their sizes or the size of particular dimension
1474
1475 \cvexp{
1476 int cvGetDims( const CvArr* arr, int* sizes=NULL );
1477 }{CPP}{PYTHON}
1478 \cvexp{
1479 int cvGetDimSize( const CvArr* arr, int index );
1480 }{CPP}{PYTHON}
1481
1482 \begin{description}
1483 \cvarg{arr}{Input array}
1484 \cvarg{sizes}{Optional output vector of the array dimension sizes. For
1485 2d arrays the number of rows (height) goes first, number of columns
1486 (width) next.}
1487 \cvarg{index}{Zero-based dimension index (for matrices 0 means number
1488 of rows, 1 means number of columns; for images 0 means height, 1 means
1489 width)}
1490 \end{description}
1491
1492
1493 The function \texttt{cvGetDims} returns number of array dimensions and
1494 their sizes. In case of \texttt{IplImage} or \cross{CvMat} it always
1495 returns 2 regardless of number of image/matrix rows. The function
1496 \texttt{cvGetDimSize} returns the particular dimension size (number of
1497 elements per that dimension). For example, the following code calculates
1498 total number of array elements in two ways:
1499
1500 \begin{lstlisting}
1501
1502 // via cvGetDims()
1503 int sizes[CV_MAX_DIM];
1504 int i, total = 1;
1505 int dims = cvGetDims( arr, size );
1506 for( i = 0; i < dims; i++ )
1507     total *= sizes[i];
1508
1509 // via cvGetDims() and cvGetDimSize()
1510 int i, total = 1;
1511 int dims = cvGetDims( arr );
1512 for( i = 0; i < dims; i++ )
1513     total *= cvGetDimsSize( arr, i );
1514
1515 \end{lstlisting}
1516
1517
1518 \cvfunc{PtrnD}\label{PtrnD}
1519
1520 Return pointer to the particular array element
1521
1522 \begin{lstlisting}
1523
1524 uchar* cvPtr1D( const CvArr* arr, int idx0, int* type=NULL );
1525 uchar* cvPtr2D( const CvArr* arr, int idx0, int idx1, int* type=NULL );
1526 uchar* cvPtr3D( const CvArr* arr, int idx0, int idx1, int idx2, int* type=NULL );
1527 uchar* cvPtrND( const CvArr* arr, int* idx, int* type=NULL, int create\_node=1, unsigned* precalc\_hashval=NULL );
1528
1529 \end{lstlisting}
1530
1531 \begin{description}
1532 \cvarg{arr}{Input array}
1533 \cvarg{idx0}{The first zero-based component of the element index}
1534 \cvarg{idx1}{The second zero-based component of the element index}
1535 \cvarg{idx2}{The third zero-based component of the element index}
1536 \cvarg{idx}{Array of the element indices}
1537 \cvarg{type}{Optional output parameter: type of matrix elements}
1538 \cvarg{create\_node}{Optional input parameter for sparse matrices. Non-zero value of the parameter means that the requested element is created if it does not exist already.}
1539 \cvarg{precalc\_hashval}{Optional input parameter for sparse matrices. If the pointer is not NULL, the function does not recalculate the node hash value, but takes it from the specified location. It is useful for speeding up pair-wise operations (TODO: provide an example)}
1540 \end{description}
1541
1542 The functions \texttt{cvPtrnD} return pointer to the particular array element. Number of array dimension should match to the number of indices passed to the function except for \texttt{cvPtr1D} function that can be used for sequential access to 1D, 2D or nD dense arrays.
1543
1544 The functions can be used for sparse arrays as well - if the requested node does not exist they create it and set it to zero.
1545
1546 All these as well as other functions accessing array elements (\cross{Get}, \cross{GetReal}, \cross{Set}, \cross{SetReal}) raise an error in case if the element index is out of range.
1547
1548 \cvfunc{Get*D}\label{Get*D}
1549
1550 Return the particular array element
1551
1552 \begin{lstlisting}
1553
1554 CvScalar cvGet1D( const CvArr* arr, int idx0 );
1555 CvScalar cvGet2D( const CvArr* arr, int idx0, int idx1 );
1556 CvScalar cvGet3D( const CvArr* arr, int idx0, int idx1, int idx2 );
1557 CvScalar cvGetND( const CvArr* arr, int* idx );
1558
1559 \end{lstlisting}
1560
1561 \begin{description}
1562 \cvarg{arr}{Input array}
1563 \cvarg{idx0}{The first zero-based component of the element index}
1564 \cvarg{idx1}{The second zero-based component of the element index}
1565 \cvarg{idx2}{The third zero-based component of the element index}
1566 \cvarg{idx}{Array of the element indices}
1567 \end{description}
1568
1569
1570 The functions \texttt{cvGet*D} return the particular array element. In case of sparse array the functions return 0 if the requested node does not exist (no new node is created by the functions)
1571
1572 \cvfunc{GetReal*D}\label{GetReal*D}
1573
1574 Return the particular element of single-channel array
1575
1576 \begin{lstlisting}
1577
1578 double cvGetReal1D( const CvArr* arr, int idx0 );
1579 double cvGetReal2D( const CvArr* arr, int idx0, int idx1 );
1580 double cvGetReal3D( const CvArr* arr, int idx0, int idx1, int idx2 );
1581 double cvGetRealND( const CvArr* arr, int* idx );
1582
1583 \end{lstlisting}
1584
1585 \begin{description}
1586 \cvarg{arr}{Input array. Must have a single channel.}
1587 \cvarg{idx0}{The first zero-based component of the element index}
1588 \cvarg{idx1}{The second zero-based component of the element index}
1589 \cvarg{idx2}{The third zero-based component of the element index}
1590 \cvarg{idx}{Array of the element indices}
1591 \end{description}
1592
1593
1594 The functions \texttt{cvGetReal*D} return the particular element of single-channel array. If the array has multiple channels, runtime error is raised. Note that \cross{Get} function can be used safely for both single-channel and multiple-channel arrays though they are a bit slower.
1595
1596 In case of sparse array the functions return 0 if the requested node does not exist (no new node is created by the functions)
1597
1598 \cvfunc{mGet}\label{mGet}
1599
1600 Return the particular element of single-channel floating-point matrix
1601
1602 \cvexp{
1603
1604 double cvmGet( const CvMat* mat, int row, int col );
1605
1606 }{CPP}{PYTHON}
1607
1608 \begin{description}
1609 \cvarg{mat}{Input matrix}
1610 \cvarg{row}{The zero-based index of row}
1611 \cvarg{col}{The zero-based index of column}
1612 \end{description}
1613
1614 The function \texttt{cvmGet} is a fast replacement for \cross{GetReal2D}
1615 in case of single-channel floating-point matrices. It is faster because
1616 it is inline, it does less checks for array type and array element type
1617 and it checks for the row and column ranges only in debug mode.
1618
1619 \cvfunc{SetnD}\label{SetnD}
1620
1621 Change the particular array element
1622
1623 \begin{lstlisting}
1624
1625 void cvSet1D( CvArr* arr, int idx0, CvScalar value );
1626 void cvSet2D( CvArr* arr, int idx0, int idx1, CvScalar value );
1627 void cvSet3D( CvArr* arr, int idx0, int idx1, int idx2, CvScalar value );
1628 void cvSetND( CvArr* arr, int* idx, CvScalar value );
1629
1630 \end{lstlisting}
1631
1632 \begin{description}
1633 \cvarg{arr}{Input array}
1634 \cvarg{idx0}{The first zero-based component of the element index}
1635 \cvarg{idx1}{The second zero-based component of the element index}
1636 \cvarg{idx2}{The third zero-based component of the element index}
1637 \cvarg{idx}{Array of the element indices}
1638 \cvarg{value}{The assigned value}
1639 \end{description}
1640
1641
1642 The functions \texttt{cvSetnD} assign the new value to the particular element of array. In case of sparse array the functions create the node if it does not exist yet
1643
1644 \cvfunc{SetRealnD}\label{SetRealnD}
1645
1646 Change the particular array element
1647
1648 \begin{lstlisting}
1649
1650 void cvSetReal1D( CvArr* arr, int idx0, double value );
1651 void cvSetReal2D( CvArr* arr, int idx0, int idx1, double value );
1652 void cvSetReal3D( CvArr* arr, int idx0, int idx1, int idx2, double value );
1653 void cvSetRealND( CvArr* arr, int* idx, double value );
1654
1655 \end{lstlisting}
1656
1657 \begin{description}
1658 \cvarg{arr}{Input array}
1659 \cvarg{idx0}{The first zero-based component of the element index}
1660 \cvarg{idx1}{The second zero-based component of the element index}
1661 \cvarg{idx2}{The third zero-based component of the element index}
1662 \cvarg{idx}{Array of the element indices}
1663 \cvarg{value}{The assigned value}
1664 \end{description}
1665
1666 The functions \texttt{cvSetRealnD} assign the new value to the particular
1667 element of single-channel array. If the array has multiple channels,
1668 runtime error is raised. Note that \cross{SetnD} function can be used
1669 safely for both single-channel and multiple-channel arrays though they
1670 are a bit slower.
1671
1672 In case of sparse array the functions create the node if it does not exist yet
1673
1674 \cvfunc{mSet}\label{mSet}
1675
1676 Return the particular element of single-channel floating-point matrix
1677
1678 \cvexp{
1679
1680 void cvmSet( CvMat* mat, int row, int col, double value );
1681
1682 }{CPP}{PYTHON}
1683
1684 \begin{description}
1685 \cvarg{mat}{The matrix}
1686 \cvarg{row}{The zero-based index of row}
1687 \cvarg{col}{The zero-based index of column}
1688 \cvarg{value}{The new value of the matrix element}
1689 \end{description}
1690
1691
1692 The function \texttt{cvmSet} is a fast replacement for \cross{SetReal2D}
1693 in case of single-channel floating-point matrices. It is faster because
1694 it is inline, it does less checks for array type and array element type
1695 and it checks for the row and column ranges only in debug mode.
1696
1697 \cvfunc{ClearND}\label{ClearND}
1698
1699 Clears the particular array element
1700
1701 \cvexp{
1702
1703 void cvClearND( CvArr* arr, int* idx );
1704
1705 }{CPP}{PYTHON}
1706
1707 \begin{description}
1708 \cvarg{arr}{Input array}
1709 \cvarg{idx}{Array of the element indices}
1710 \end{description}
1711
1712
1713 The function \cross{ClearND} clears (sets to zero) the particular element of dense array or deletes the element of sparse array. If the element does not exists, the function does nothing.
1714
1715
1716 \subsection{Copying and Filling}
1717
1718
1719 \cvfunc{Copy}\label{Copy}
1720
1721 Copies one array to another
1722
1723 \cvexp{
1724
1725 void cvCopy( const CvArr* src, CvArr* dst, const CvArr* mask=NULL );
1726
1727 }{CPP}{PYTHON}
1728
1729 \begin{description}
1730 \cvarg{src}{The source array}
1731 \cvarg{dst}{The destination array}
1732 \cvarg{mask}{Operation mask, 8-bit single channel array; specifies elements of destination array to be changed}
1733 \end{description}
1734
1735
1736 The function \texttt{cvCopy} copies selected elements from input array to output array:
1737
1738 \[
1739 \texttt{dst}(I)=\texttt{src}(I) \quad \text{if} \quad \texttt{mask}(I) \ne 0.
1740 \]
1741
1742 If any of the passed arrays is of \texttt{IplImage} type, then its ROI
1743 and COI fields are used. Both arrays must have the same type, the same
1744 number of dimensions and the same size. The function can also copy sparse
1745 arrays (mask is not supported in this case).
1746
1747 \cvfunc{Set}\label{Set}
1748
1749 Sets every element of array to given value
1750
1751 \cvexp{
1752
1753 void cvSet( CvArr* arr, CvScalar value, const CvArr* mask=NULL );
1754
1755 }{CPP}{PYTHON}
1756
1757 \begin{description}
1758 \cvarg{arr}{The destination array}
1759 \cvarg{value}{Fill value}
1760 \cvarg{mask}{Operation mask, 8-bit single channel array; specifies elements of destination array to be changed}
1761 \end{description}
1762
1763
1764 The function \texttt{cvSet} copies scalar \texttt{value} to every selected element of the destination array:
1765
1766 \[
1767 \texttt{arr}(I)=\texttt{value} \quad \text{if} \quad \texttt{mask}(I) \ne 0
1768 \]
1769
1770 If array \texttt{arr} is of \texttt{IplImage} type, then is ROI used, but COI must not be set.
1771
1772 \cvfunc{SetZero}\label{SetZero}
1773
1774 Clears the array
1775
1776 \cvexp{
1777
1778 void cvSetZero( CvArr* arr );
1779
1780 }{CPP}{PYTHON}
1781
1782 \begin{lstlisting}
1783 #define cvZero cvSetZero
1784 \end{lstlisting}
1785
1786 \begin{description}
1787 \cvarg{arr}{array to be cleared}
1788 \end{description}
1789
1790 The function \texttt{cvSetZero} clears the array. In case of dense arrays (CvMat, CvMatND or IplImage) cvZero(array) is equivalent to
1791 cvSet(array,cvScalarAll(0),0).
1792 In case of sparse arrays all the elements are removed.
1793
1794 \subsection{Transforms and Permutations}
1795
1796 \cvfunc{Reshape}\label{Reshape}
1797
1798 Changes shape of matrix/image without copying data
1799
1800 \cvexp{
1801
1802 CvMat* cvReshape( const CvArr* arr, CvMat* header, int new\_cn, int new\_rows=0 );
1803
1804 }{CPP}{PYTHON}
1805
1806 \begin{description}
1807 \cvarg{arr}{Input array}
1808 \cvarg{header}{Output header to be filled}
1809 \cvarg{new\_cn}{New number of channels. 'new\_cn = 0' means that number of channels remains unchanged.}
1810 \cvarg{new\_rows}{New number of rows. 'new\_rows = 0' means that number of rows remains unchanged unless it needs to be changed according to \texttt{new\_cn} value. destination array to be changed.}
1811 \end{description}
1812
1813 The function \texttt{cvReshape} initializes CvMat header so that it points to the same data as the original array but has different shape - different number of channels, different number of rows or both.
1814
1815 For example, the following code creates one image buffer and two image headers, first is for 320x240x3 image and the second is for 960x240x1 image:
1816
1817 \begin{lstlisting}
1818
1819 IplImage* color_img = cvCreateImage( cvSize(320,240), IPL_DEPTH_8U, 3 );
1820 CvMat gray_mat_hdr;
1821 IplImage gray_img_hdr, *gray_img;
1822 cvReshape( color_img, &gray_mat_hdr, 1 );
1823 gray_img = cvGetImage( &gray_mat_hdr, &gray_img_hdr );
1824
1825 \end{lstlisting}
1826
1827 And the next example converts 3x3 matrix to a single 1x9 vector
1828
1829 \begin{lstlisting}
1830
1831 CvMat* mat = cvCreateMat( 3, 3, CV_32F );
1832 CvMat row_header, *row;
1833 row = cvReshape( mat, &row_header, 0, 1 );
1834
1835 \end{lstlisting}
1836
1837 \cvfunc{ReshapeMatND}\label{ReshapeMatND}
1838
1839 Changes shape of multi-dimensional array w/o copying data
1840
1841 \cvexp{
1842
1843 CvArr* cvReshapeMatND( const CvArr* arr,
1844                        int sizeof\_header, CvArr* header,
1845                        int new\_cn, int new\_dims, int* new\_sizes );
1846 }{CPP}{PYTHON}
1847
1848 \begin{lstlisting}
1849 #define cvReshapeND( arr, header, new\_cn, new\_dims, new\_sizes )   \
1850       cvReshapeMatND( (arr), sizeof(*(header)), (header),         \
1851                       (new\_cn), (new\_dims), (new\_sizes))
1852 \end{lstlisting}
1853
1854
1855 \begin{description}
1856 \cvarg{arr}{Input array}
1857 \cvarg{sizeof\_header}{Size of output header to distinguish between IplImage, CvMat and CvMatND output headers}
1858 \cvarg{header}{Output header to be filled}
1859 \cvarg{new\_cn}{New number of channels. $\texttt{new\_cn} = 0$ means that number of channels remains unchanged.}
1860 \cvarg{new\_dims}{New number of dimensions. $\texttt{new\_dims} = 0$ means that number of dimensions remains the same.}
1861 \cvarg{new\_sizes}{Array of new dimension sizes. Only $\texttt{new\_dims}-1$ values are used, because the total number of elements must remain the same.
1862 Thus, if $\texttt{new\_dims} = 1$, \texttt{new\_sizes} array is not used}
1863 \end{description}
1864
1865 The function \texttt{cvReshapeMatND} is an advanced version of \cross{Reshape} that can work with multi-dimensional arrays as well (though, it can work with ordinary images and matrices) and change the number of dimensions. Below are the two samples from the \cross{Reshape} description rewritten using \cross{ReshapeMatND}:
1866
1867 \begin{lstlisting}
1868
1869 IplImage* color_img = cvCreateImage( cvSize(320,240), IPL_DEPTH_8U, 3 );
1870 IplImage gray_img_hdr, *gray_img;
1871 gray_img = (IplImage*)cvReshapeND( color_img, &gray_img_hdr, 1, 0, 0 );
1872
1873 ...
1874
1875 /* second example is modified to convert 2x2x2 array to 8x1 vector */
1876 int size[] = { 2, 2, 2 };
1877 CvMatND* mat = cvCreateMatND( 3, size, CV_32F );
1878 CvMat row_header, *row;
1879 row = cvReshapeND( mat, &row_header, 0, 1, 0 );
1880
1881 \end{lstlisting}
1882
1883 \cvfunc{Repeat}\label{Repeat}
1884
1885 Fill destination array with tiled source array
1886
1887 \cvexp{
1888
1889 void cvRepeat( const CvArr* src, CvArr* dst );
1890
1891 }{CPP}{PYTHON}
1892
1893 \begin{description}
1894 \cvarg{src}{Source array, image or matrix}
1895 \cvarg{dst}{Destination array, image or matrix}
1896 \end{description}
1897
1898
1899 The function \texttt{cvRepeat} fills the destination array with source array tiled:
1900
1901 \begin{lstlisting}
1902 dst(i,j)=src(i mod rows(src), j mod cols(src))
1903 \end{lstlisting}
1904
1905 So the destination array may be as larger as well as smaller than the source array.
1906
1907
1908 \cvfunc{Flip}\label{Flip}
1909
1910 Flip a 2D array around vertical, horizontall or both axises
1911
1912 \cvexp{
1913 void  cvFlip( const CvArr* src, CvArr* dst=NULL, int flip\_mode=0);
1914 }{CPP}{PYTHON}
1915
1916 \begin{lstlisting}
1917 #define cvMirror cvFlip
1918 \end{lstlisting}
1919
1920 \begin{description}
1921 \cvarg{src}{Source array}
1922 \cvarg{dst}{Destination array.
1923 If $\texttt{dst} = \texttt{NULL}$ the flipping is done inplace.}
1924 \cvarg{flip\_mode}{Specifies how to flip the array
1925 0 means flipping around x-axis, positive (e.g. 1) means flipping around y-axis and negative (e.g. -1) means flipping around both axises. See also the discussion below for the formulas}
1926 \end{description}
1927
1928 The function \texttt{cvFlip} flips the array in one of different 3 ways (row and column indices are 0-based):
1929
1930 \[
1931 dst(i,j) = \forkthree
1932 {\texttt{src}(rows(\texttt{src})-i-1,j)}{if $\texttt{flip\_mode} = 0$}
1933 {\texttt{src}(i,cols(\texttt{src})-j-1)}{if $\texttt{flip\_mode} > 0$}
1934 {\texttt{src}(rows(\texttt{src})-i-1,cols(\texttt{src})-j-1)}{if $\texttt{flip\_mode} < 0$}
1935 \]
1936
1937 The example cenaria of the function use are:
1938 \begin{itemize}
1939   \item vertical flipping of the image (flip\_mode > 0) to switch between top-left and bottom-left image origin, which is typical operation in video processing under Win32 systems.
1940   \item horizontal flipping of the image with subsequent horizontal shift and absolute difference calculation to check for a vertical-axis symmetry (flip\_mode > 0)
1941   \item simultaneous horizontal and vertical flipping of the image with subsequent shift and absolute difference calculation to check for a central symmetry (flip\_mode < 0)
1942   \item reversing the order of 1d point arrays(flip\_mode > 0)
1943 \end{itemize}
1944
1945 \cvfunc{Split}\label{Split}
1946
1947 Divides multi-channel array into several single-channel arrays or extracts a single channel from the array
1948
1949 \cvexp{
1950
1951 void cvSplit( const CvArr* src, CvArr* dst0, CvArr* dst1,
1952               CvArr* dst2, CvArr* dst3 );
1953 }{CPP}{PYTHON}
1954
1955 \begin{lstlisting}
1956 #define cvCvtPixToPlane cvSplit
1957 \end{lstlisting}
1958
1959 \begin{description}
1960 \cvarg{src}{Source array}
1961 \cvarg{dst0...dst3}{Destination channels}
1962 \end{description}
1963
1964 The function \texttt{cvSplit} divides a multi-channel array into separate
1965 single-channel arrays. Two modes are available for the operation. If the
1966 source array has N channels then if the first N destination channels
1967 are not NULL, all they are extracted from the source array, otherwise
1968 if only a single destination channel of the first N is not NULL, this
1969 particular channel is extracted, otherwise an error is raised. Rest
1970 of destination channels (beyond the first N) must always be NULL. For
1971 IplImage \cross{Copy} with COI set can be also used to extract a single
1972 channel from the image.
1973
1974
1975 \cvfunc{Merge}\label{Merge}
1976
1977 Composes multi-channel array from several single-channel arrays or inserts a single channel into the array
1978
1979 \cvexp{
1980
1981 void cvMerge( const CvArr* src0, const CvArr* src1,
1982               const CvArr* src2, const CvArr* src3, CvArr* dst );
1983 }{CPP}{PYTHON}
1984
1985 \begin{lstlisting}
1986 #define cvCvtPlaneToPix cvMerge
1987 \end{lstlisting}
1988
1989 \begin{description}
1990 \cvarg{src0...src3}{Input channels}
1991 \cvarg{dst}{Destination array}
1992 \end{description}
1993
1994 The function \texttt{cvMerge} is the opposite to the previous. If the destination array has N channels then if the first N input channels are not NULL, all they are copied to the destination array, otherwise if only a single source channel of the first N is not NULL, this particular channel is copied into the destination array, otherwise an error is raised. Rest of source channels (beyond the first N) must always be NULL. For IplImage \cross{Copy} with COI set can be also used to insert a single channel into the image.
1995
1996
1997 \subsection{Arithmetic, Logic and Comparison}
1998
1999 \cvfunc{LUT}\label{LUT}
2000
2001 Performs look-up table transform of array
2002
2003 \cvexp{
2004
2005 void cvLUT( const CvArr* src, CvArr* dst, const CvArr* lut );
2006
2007 }{CPP}{PYTHON}
2008
2009 \begin{description}
2010 \cvarg{src}{Source array of 8-bit elements}
2011 \cvarg{dst}{Destination array of arbitrary depth and of the same number of channels as the source array}
2012 \cvarg{lut}{Look-up table of 256 elements; should have the same depth as the destination array. In case of multi-channel source and destination arrays, the table should either have a single-channel (in this case the same table is used for all channels), or the same number of channels as the source/destination array.}
2013 \end{description}
2014
2015 The function \texttt{cvLUT} fills the destination array with values from the look-up table. Indices of the entries are taken from the source array. That is, the function processes each element of \texttt{src} as following:
2016
2017 \[
2018 \texttt{dst}_i \leftarrow \texttt{lut}_{\texttt{src}_i + d}
2019 \]
2020
2021 where
2022
2023 \[
2024 d = \fork
2025 {0}{if \texttt{src} has depth \texttt{CV\_8U}}
2026 {128}{if \texttt{src} has depth \texttt{CV\_8S}}
2027 \]
2028
2029 \cvfunc{ConvertScale}\label{ConvertScale}
2030
2031 Converts one array to another with optional linear transformation
2032
2033 \cvexp{
2034
2035 void cvConvertScale( const CvArr* src, CvArr* dst, double scale=1, double shift=0 );
2036
2037 }{CPP}{PYTHON}
2038
2039 \begin{lstlisting}
2040 #define cvCvtScale cvConvertScale
2041 #define cvScale  cvConvertScale
2042 #define cvConvert( src, dst )  cvConvertScale( (src), (dst), 1, 0 )
2043 \end{lstlisting}
2044
2045 \begin{description}
2046 \cvarg{src}{Source array}
2047 \cvarg{dst}{Destination array}
2048 \cvarg{scale}{Scale factor}
2049 \cvarg{shift}{Value added to the scaled source array elements}
2050 \end{description}
2051
2052
2053 The function \texttt{cvConvertScale} has several different purposes and thus has several synonyms. It copies one array to another with optional scaling, which is performed first, and/or optional type conversion, performed after:
2054
2055 \[
2056 \texttt{dst}(I) = \texttt{scale} \texttt{src}(I) + (\texttt{shift}_0,\texttt{shift}_1,...)
2057 \]
2058
2059 All the channels of multi-channel arrays are processed independently.
2060
2061 The type conversion is done with rounding and saturation, that is if a
2062 result of scaling + conversion can not be represented exactly by a value
2063 of destination array element type, it is set to the nearest representable
2064 value on the real axis.
2065
2066 In case of 'scale=1, shift=0' no prescaling is done. This is a specially
2067 optimized case and it has the appropriate \cross{Convert} synonym. If
2068 source and destination array types have equal types, this is also a
2069 special case that can be used to scale and shift a matrix or an image
2070 and that fits to \cross{Scale} synonym.
2071
2072 \cvfunc{ConvertScaleAbs}\label{ConvertScaleAbs}
2073
2074 Converts input array elements to 8-bit unsigned integer another with optional linear transformation
2075
2076 \cvexp{
2077 void cvConvertScaleAbs( const CvArr* src, CvArr* dst, double scale=1, double shift=0 );
2078 }{CPP}{PYTHON}
2079
2080 \begin{lstlisting}
2081 #define cvCvtScaleAbs cvConvertScaleAbs
2082 \end{lstlisting}
2083
2084 \begin{description}
2085 \cvarg{src}{Source array}
2086 \cvarg{dst}{Destination array (should have 8u depth)}
2087 \cvarg{scale}{ScaleAbs factor}
2088 \cvarg{shift}{Value added to the scaled source array elements}
2089 \end{description}
2090
2091
2092 The function \texttt{cvConvertScaleAbs} is similar to the previous one, but it stores absolute values of the conversion results:
2093
2094 \[
2095 \texttt{dst}(I) = |\texttt{scale} \texttt{src}(I) + (\texttt{shift}_0,\texttt{shift}_1,...)|
2096 \]
2097
2098 The function supports only destination arrays of 8u (8-bit unsigned integers) type, for other types the function can be emulated by combination of \cross{ConvertScale} and \cross{Abs} functions.
2099
2100 \cvfunc{Add}\label{Add}
2101
2102 Computes per-element sum of two arrays
2103
2104 \cvexp{
2105
2106 void cvAdd( const CvArr* src1, const CvArr* src2, CvArr* dst, const CvArr* mask=NULL );
2107
2108 }{CPP}{PYTHON}
2109
2110 \begin{description}
2111 \cvarg{src1}{The first source array}
2112 \cvarg{src2}{The second source array}
2113 \cvarg{dst}{The destination array}
2114 \cvarg{mask}{Operation mask, 8-bit single channel array; specifies elements of destination array to be changed}
2115 \end{description}
2116
2117 The function \texttt{cvAdd} adds one array to another one:
2118
2119 \begin{lstlisting}
2120 dst(I)=src1(I)+src2(I) if mask(I)!=0
2121 \end{lstlisting}
2122
2123 All the arrays must have the same type, except the mask, and the same size (or ROI size)
2124
2125
2126 \cvfunc{AddS}\label{AddS}
2127
2128 Computes sum of array and scalar
2129
2130 \cvexp{
2131
2132 void cvAddS( const CvArr* src, CvScalar value, CvArr* dst, const CvArr* mask=NULL );
2133
2134 }{CPP}{PYTHON}
2135
2136 \begin{description}
2137 \cvarg{src}{The source array}
2138 \cvarg{value}{Added scalar}
2139 \cvarg{dst}{The destination array}
2140 \cvarg{mask}{Operation mask, 8-bit single channel array; specifies elements of destination array to be changed}
2141 \end{description}
2142
2143
2144 The function \texttt{cvAddS} adds scalar \texttt{value} to every element in the source array \texttt{src1} and stores the result in \texttt{dst}
2145
2146 \begin{lstlisting}
2147 dst(I)=src(I)+value if mask(I)!=0
2148 \end{lstlisting}
2149
2150 All the arrays must have the same type, except the mask, and the same size (or ROI size)
2151
2152
2153 \cvfunc{AddWeighted}\label{AddWeighted}
2154
2155 Computes weighted sum of two arrays
2156
2157 \cvexp{
2158
2159 void  cvAddWeighted( const CvArr* src1, double alpha,
2160                      const CvArr* src2, double beta,
2161                      double gamma, CvArr* dst );
2162
2163 }{CPP}{PYTHON}
2164
2165 \begin{description}
2166 \cvarg{src1}{The first source array}
2167 \cvarg{alpha}{Weight of the first array elements}
2168 \cvarg{src2}{The second source array}
2169 \cvarg{beta}{Weight of the second array elements}
2170 \cvarg{dst}{The destination array}
2171 \cvarg{gamma}{Scalar, added to each sum}
2172 \end{description}
2173
2174 The function \texttt{cvAddWeighted} calculated weighted sum of two arrays as following:
2175
2176 \begin{lstlisting}
2177 dst(I)=src1(I)*alpha+src2(I)*beta+gamma
2178 \end{lstlisting}
2179
2180 All the arrays must have the same type and the same size (or ROI size)
2181
2182
2183 \cvfunc{Sub}\label{Sub}
2184
2185 Computes per-element difference between two arrays
2186
2187 \cvexp{
2188
2189 void cvSub( const CvArr* src1, const CvArr* src2, CvArr* dst, const CvArr* mask=NULL );
2190
2191 }{CPP}{PYTHON}
2192
2193 \begin{description}
2194 \cvarg{src1}{The first source array}
2195 \cvarg{src2}{The second source array}
2196 \cvarg{dst}{The destination array}
2197 \cvarg{mask}{Operation mask, 8-bit single channel array; specifies elements of destination array to be changed}
2198 \end{description}
2199
2200
2201 The function \texttt{cvSub} subtracts one array from another one:
2202
2203 \begin{lstlisting}
2204 dst(I)=src1(I)-src2(I) if mask(I)!=0
2205 \end{lstlisting}
2206
2207 All the arrays must have the same type, except the mask, and the same size (or ROI size)
2208
2209 \cvfunc{SubS}\label{SubS}
2210
2211 Computes difference between array and scalar
2212
2213 \cvexp{
2214
2215 void cvSubS( const CvArr* src, CvScalar value, CvArr* dst, const CvArr* mask=NULL );
2216
2217 }{CPP}{PYTHON}
2218
2219 \begin{description}
2220 \cvarg{src}{The source array}
2221 \cvarg{value}{Subtracted scalar}
2222 \cvarg{dst}{The destination array}
2223 \cvarg{mask}{Operation mask, 8-bit single channel array; specifies elements of destination array to be changed}
2224 \end{description}
2225
2226 The function \texttt{cvSubS} subtracts a scalar from every element of the source array:
2227
2228 \begin{lstlisting}
2229 dst(I)=src(I)-value if mask(I)!=0
2230 \end{lstlisting}
2231
2232 All the arrays must have the same type, except the mask, and the same size (or ROI size)
2233
2234
2235 \cvfunc{SubRS}\label{SubRS}
2236
2237 Computes difference between scalar and array
2238
2239 \cvexp{
2240
2241 void cvSubRS( const CvArr* src, CvScalar value, CvArr* dst, const CvArr* mask=NULL );
2242
2243 }{CPP}{PYTHON}
2244
2245 \begin{description}
2246 \cvarg{src}{The first source array}
2247 \cvarg{value}{Scalar to subtract from}
2248 \cvarg{dst}{The destination array}
2249 \cvarg{mask}{Operation mask, 8-bit single channel array; specifies elements of destination array to be changed}
2250 \end{description}
2251
2252
2253 The function \texttt{cvSubRS} subtracts every element of source array from a scalar:
2254
2255 \begin{lstlisting}
2256 dst(I)=value-src(I) if mask(I)!=0
2257 \end{lstlisting}
2258
2259 All the arrays must have the same type, except the mask, and the same size (or ROI size)
2260
2261 \cvfunc{Mul}\label{Mul}
2262
2263 Calculates per-element product of two arrays
2264
2265 \cvexp{
2266
2267 void cvMul( const CvArr* src1, const CvArr* src2, CvArr* dst, double scale=1 );
2268
2269 }{CPP}{PYTHON}
2270
2271 \begin{description}
2272 \cvarg{src1}{The first source array}
2273 \cvarg{src2}{The second source array}
2274 \cvarg{dst}{The destination array}
2275 \cvarg{scale}{Optional scale factor}
2276 \end{description}
2277
2278
2279 The function \texttt{cvMul} calculates per-element product of two arrays:
2280
2281 \[
2282 \texttt{dst}(I)=\texttt{scale} \cdot \texttt{src1}(I) \cdot \texttt{src2}(I)
2283 \]
2284
2285 All the arrays must have the same type, and the same size (or ROI size)
2286
2287 \cvfunc{Div}\label{Div}
2288
2289 Performs per-element division of two arrays
2290
2291 \cvexp{
2292
2293 void cvDiv( const CvArr* src1, const CvArr* src2, CvArr* dst, double scale=1 );
2294
2295 }{CPP}{PYTHON}
2296
2297 \begin{description}
2298 \cvarg{src1}{The first source array. If the pointer is NULL, the array is assumed to be all 1's.}
2299 \cvarg{src2}{The second source array}
2300 \cvarg{dst}{The destination array}
2301 \cvarg{scale}{Optional scale factor}
2302 \end{description}
2303
2304 The function \texttt{cvDiv} divides one array by another:
2305
2306 \[
2307 \texttt{dst}(I)=\fork
2308 {\texttt{scale} \cdot \texttt{src1}(I)/\texttt{src2}(I)}{if \texttt{src1} is not \texttt{NULL}}
2309 {\texttt{scale}/\texttt{src2}(I)}{otherwise}
2310 \]
2311
2312 All the arrays must have the same type, and the same size (or ROI size)
2313
2314
2315 \cvfunc{And}\label{And}
2316
2317 Calculates per-element bit-wise conjunction of two arrays
2318
2319 \cvexp{
2320
2321 void cvAnd( const CvArr* src1, const CvArr* src2, CvArr* dst, const CvArr* mask=NULL );
2322
2323 }{CPP}{PYTHON}
2324
2325 \begin{description}
2326 \cvarg{src1}{The first source array}
2327 \cvarg{src2}{The second source array}
2328 \cvarg{dst}{The destination array}
2329 \cvarg{mask}{Operation mask, 8-bit single channel array; specifies elements of destination array to be changed}
2330 \end{description}
2331
2332
2333 The function \texttt{cvAnd} calculates per-element bit-wise logical conjunction of two arrays:
2334
2335 \begin{lstlisting}
2336 dst(I)=src1(I)&src2(I) if mask(I)!=0
2337 \end{lstlisting}
2338
2339 In the case of floating-point arrays their bit representations are used for the operation. All the arrays must have the same type, except the mask, and the same size.
2340
2341 \cvfunc{AndS}\label{AndS}
2342
2343 Calculates per-element bit-wise conjunction of array and scalar
2344
2345 \cvexp{
2346
2347 void cvAndS( const CvArr* src, CvScalar value, CvArr* dst, const CvArr* mask=NULL );
2348
2349 }{CPP}{PYTHON}
2350
2351 \begin{description}
2352 \cvarg{src}{The source array}
2353 \cvarg{value}{Scalar to use in the operation}
2354 \cvarg{dst}{The destination array}
2355 \cvarg{mask}{Operation mask, 8-bit single channel array; specifies elements of destination array to be changed}
2356 \end{description}
2357
2358 The function AndS calculates per-element bit-wise conjunction of array and scalar:
2359
2360 \begin{lstlisting}
2361 dst(I)=src(I)&value if mask(I)!=0
2362 \end{lstlisting}
2363
2364 Prior to the actual operation the scalar is converted to the same type as the arrays. In the case of floating-point arrays their bit representations are used for the operation. All the arrays must have the same type, except the mask, and the same size
2365
2366 The following sample demonstrates how to calculate absolute value of floating-point array elements by clearing the most-significant bit:
2367
2368 \begin{lstlisting}
2369
2370 float a[] = { -1, 2, -3, 4, -5, 6, -7, 8, -9 };
2371 CvMat A = cvMat( 3, 3, CV\_32F, &a );
2372 int i, abs\_mask = 0x7fffffff;
2373 cvAndS( &A, cvRealScalar(*(float*)&abs\_mask), &A, 0 );
2374 for( i = 0; i < 9; i++ )
2375     printf("%.1f ", a[i] );
2376
2377 \end{lstlisting}
2378
2379 The code should print:
2380
2381 \begin{lstlisting}
2382 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0
2383 \end{lstlisting}
2384
2385
2386 \cvfunc{Or}\label{Or}
2387
2388 Calculates per-element bit-wise disjunction of two arrays
2389
2390 \cvexp{
2391
2392 void cvOr( const CvArr* src1, const CvArr* src2, CvArr* dst, const CvArr* mask=NULL );
2393
2394 }{CPP}{PYTHON}
2395
2396 \begin{description}
2397 \cvarg{src1}{The first source array}
2398 \cvarg{src2}{The second source array}
2399 \cvarg{dst}{The destination array}
2400 \cvarg{mask}{Operation mask, 8-bit single channel array; specifies elements of destination array to be changed}
2401 \end{description}
2402
2403
2404 The function \texttt{cvOr} calculates per-element bit-wise disjunction of two arrays:
2405
2406 \begin{lstlisting}
2407 dst(I)=src1(I)|src2(I)
2408 \end{lstlisting}
2409
2410 In the case of floating-point arrays their bit representations are used for the operation. All the arrays must have the same type, except the mask, and the same size
2411
2412 \cvfunc{OrS}\label{OrS}
2413
2414 Calculates per-element bit-wise disjunction of array and scalar
2415
2416 \cvexp{
2417
2418 void cvOrS( const CvArr* src, CvScalar value, CvArr* dst, const CvArr* mask=NULL );
2419
2420 }{CPP}{PYTHON}
2421
2422 \begin{description}
2423 \cvarg{src1}{The source array}
2424 \cvarg{value}{Scalar to use in the operation}
2425 \cvarg{dst}{The destination array}
2426 \cvarg{mask}{Operation mask, 8-bit single channel array; specifies elements of destination array to be changed}
2427 \end{description}
2428
2429
2430 The function OrS calculates per-element bit-wise disjunction of array and scalar:
2431
2432 \begin{lstlisting}
2433 dst(I)=src(I)|value if mask(I)!=0
2434 \end{lstlisting}
2435
2436 Prior to the actual operation the scalar is converted to the same type as the arrays. In the case of floating-point arrays their bit representations are used for the operation. All the arrays must have the same type, except the mask, and the same size
2437
2438
2439 \cvfunc{Xor}\label{Xor}
2440
2441 Performs per-element bit-wise "exclusive or" operation on two arrays
2442
2443 \cvexp{
2444
2445 void cvXor( const CvArr* src1, const CvArr* src2, CvArr* dst, const CvArr* mask=NULL );
2446
2447 }{CPP}{PYTHON}
2448
2449 \begin{description}
2450 \cvarg{src1}{The first source array}
2451 \cvarg{src2}{The second source array}
2452 \cvarg{dst}{The destination array}
2453 \cvarg{mask}{Operation mask, 8-bit single channel array; specifies elements of destination array to be changed}
2454 \end{description}
2455
2456 The function \texttt{cvXor} calculates per-element bit-wise logical conjunction of two arrays:
2457
2458 \begin{lstlisting}
2459 dst(I)=src1(I)^src2(I) if mask(I)!=0
2460 \end{lstlisting}
2461
2462 In the case of floating-point arrays their bit representations are used for the operation. All the arrays must have the same type, except the mask, and the same size
2463
2464 \cvfunc{XorS}\label{XorS}
2465
2466 Performs per-element bit-wise "exclusive or" operation on array and scalar
2467
2468 \cvexp{
2469
2470 void cvXorS( const CvArr* src, CvScalar value, CvArr* dst, const CvArr* mask=NULL );
2471
2472 }{CPP}{PYTHON}
2473
2474 \begin{description}
2475 \cvarg{src}{The source array}
2476 \cvarg{value}{Scalar to use in the operation}
2477 \cvarg{dst}{The destination array}
2478 \cvarg{mask}{Operation mask, 8-bit single channel array; specifies elements of destination array to be changed}
2479 \end{description}
2480
2481
2482 The function XorS calculates per-element bit-wise conjunction of array and scalar:
2483
2484 \begin{lstlisting}
2485 dst(I)=src(I)^value if mask(I)!=0
2486 \end{lstlisting}
2487
2488 Prior to the actual operation the scalar is converted to the same type as the arrays. In the case of floating-point arrays their bit representations are used for the operation. All the arrays must have the same type, except the mask, and the same size
2489
2490 The following sample demonstrates how to conjugate complex vector by switching the most-significant bit of imaging part:
2491
2492 \begin{lstlisting}
2493
2494 float a[] = { 1, 0, 0, 1, -1, 0, 0, -1 }; /* 1, j, -1, -j */
2495 CvMat A = cvMat( 4, 1, CV\_32FC2, &a );
2496 int i, neg\_mask = 0x80000000;
2497 cvXorS( &A, cvScalar( 0, *(float*)&neg\_mask, 0, 0 ), &A, 0 );
2498 for( i = 0; i < 4; i++ )
2499     printf("(%.1f, %.1f) ", a[i*2], a[i*2+1] );
2500
2501 \end{lstlisting}
2502
2503 The code should print:
2504
2505 \begin{lstlisting}
2506 (1.0,0.0) (0.0,-1.0) (-1.0,0.0) (0.0,1.0)
2507 \end{lstlisting}
2508
2509 \cvfunc{Not}\label{Not}
2510
2511 Performs per-element bit-wise inversion of array elements
2512
2513 \cvexp{
2514
2515 void cvNot( const CvArr* src, CvArr* dst );
2516
2517 }{CPP}{PYTHON}
2518
2519 \begin{description}
2520 \cvarg{src1}{The source array}
2521 \cvarg{dst}{The destination array}
2522 \end{description}
2523
2524
2525 The function Not inverses every bit of every array element:
2526
2527 \begin{lstlisting}
2528 dst(I)=~src(I)
2529 \end{lstlisting}
2530
2531
2532 \cvfunc{Cmp}\label{Cmp}
2533
2534 Performs per-element comparison of two arrays
2535
2536 \cvexp{
2537
2538 void cvCmp( const CvArr* src1, const CvArr* src2, CvArr* dst, int cmp\_op );
2539
2540 }{CPP}{PYTHON}
2541
2542 \begin{description}
2543 \cvarg{src1}{The first source array}
2544 \cvarg{src2}{The second source array. Both source array must have a single channel.}
2545 \cvarg{dst}{The destination array, must have 8u or 8s type}
2546 \cvarg{cmp\_op}{The flag specifying the relation between the elements to be checked
2547 \begin{description}
2548  \cvarg{CV\_CMP\_EQ}{src1(I) "equal to" value}
2549  \cvarg{CV\_CMP\_GT}{src1(I) "greater than" value}
2550  \cvarg{CV\_CMP\_GE}{src1(I) "greater or equal" value}
2551  \cvarg{CV\_CMP\_LT}{src1(I) "less than" value}
2552  \cvarg{CV\_CMP\_LE}{src1(I) "less or equal" value}
2553  \cvarg{CV\_CMP\_NE}{src1(I) "not equal" value}
2554 \end{description}}
2555 \end{description}
2556
2557 The function \texttt{cvCmp} compares the corresponding elements of two arrays and fills the destination mask array:
2558
2559 \begin{lstlisting}
2560
2561 dst(I)=src1(I) op src2(I),
2562
2563 \end{lstlisting}
2564
2565 \texttt{dst(I)} is set to 0xff (all \texttt{1}-bits) if the particular relation between the elements is true and 0 otherwise. All the arrays must have the same type, except the destination, and the same size (or ROI size)
2566
2567 \cvfunc{CmpS}\label{CmpS}
2568
2569 Performs per-element comparison of array and scalar
2570
2571 \cvexp{
2572
2573 void cvCmpS( const CvArr* src, double value, CvArr* dst, int cmp\_op );
2574
2575 }{CPP}{PYTHON}
2576
2577 \begin{description}
2578 \cvarg{src}{The source array, must have a single channel}
2579 \cvarg{value}{The scalar value to compare each array element with}
2580 \cvarg{dst}{The destination array, must have 8u or 8s type}
2581 \cvarg{cmp\_op}{The flag specifying the relation between the elements to be checked
2582 \begin{description}
2583  \cvarg{CV\_CMP\_EQ}{src1(I) "equal to" value}
2584  \cvarg{CV\_CMP\_GT}{src1(I) "greater than" value}
2585  \cvarg{CV\_CMP\_GE}{src1(I) "greater or equal" value}
2586  \cvarg{CV\_CMP\_LT}{src1(I) "less than" value}
2587  \cvarg{CV\_CMP\_LE}{src1(I) "less or equal" value}
2588  \cvarg{CV\_CMP\_NE}{src1(I) "not equal" value}
2589 \end{description}}
2590 \end{description}
2591
2592 The function \texttt{CmpS} compares the corresponding elements of array and scalar and fills the destination mask array:
2593
2594 \begin{lstlisting}
2595
2596 dst(I)=src(I) op scalar
2597
2598 \end{lstlisting}
2599
2600 where \texttt{op} is $=$, $>$, $\ge$, $<$, $\le$ or $\ne$.
2601
2602 dst(I) is set to 0xff (all \texttt{1}-bits) if the particular relation between the elements is true and 0 otherwise. All the arrays must have the same size (or ROI size)
2603
2604 \cvfunc{InRange}\label{InRange}
2605
2606 Checks that array elements lie between elements of two other arrays
2607
2608 \cvexp{
2609
2610 void cvInRange( const CvArr* src, const CvArr* lower, const CvArr* upper, CvArr* dst );
2611
2612 }{CPP}{PYTHON}
2613
2614 \begin{description}
2615 \cvarg{src}{The first source array}
2616 \cvarg{lower}{The inclusive lower boundary array}
2617 \cvarg{upper}{The exclusive upper boundary array}
2618 \cvarg{dst}{The destination array, must have 8u or 8s type}
2619 \end{description}
2620
2621
2622 The function \texttt{cvInRange} does the range check for every element of the input array:
2623
2624 \[
2625 \texttt{dst}(I)=\texttt{lower}(I)_0 <= \texttt{src}(I)_0 < \texttt{upper}(I)_0
2626 \]
2627
2628 for single-channel arrays,
2629
2630 \[
2631 \texttt{dst}(I)=
2632 \texttt{lower}(I)_0 <= \texttt{src}(I)_0 < \texttt{upper}(I)_0 \land
2633 \texttt{lower}(I)_1 <= \texttt{src}(I)_1 < \texttt{upper}(I)_1
2634 \]
2635
2636 for two-channel arrays etc.
2637
2638 dst(I) is set to 0xff (all \texttt{1}-bits) if src(I) is within the range and 0 otherwise. All the arrays must have the same type, except the destination, and the same size (or ROI size)
2639
2640
2641 \cvfunc{InRangeS}\label{InRangeS}
2642
2643 Checks that array elements lie between two scalars
2644
2645 \cvexp{
2646
2647 void cvInRangeS( const CvArr* src, CvScalar lower, CvScalar upper, CvArr* dst );
2648
2649 }{CPP}{PYTHON}
2650
2651 \begin{description}
2652 \cvarg{src}{The first source array}
2653 \cvarg{lower}{The inclusive lower boundary}
2654 \cvarg{upper}{The exclusive upper boundary}
2655 \cvarg{dst}{The destination array, must have 8u or 8s type}
2656 \end{description}
2657
2658
2659 The function \texttt{cvInRangeS} does the range check for every element of the input array:
2660
2661 \[
2662 \texttt{dst}(I)=\texttt{lower}_0 <= \texttt{src}(I)_0 < \texttt{upper}_0
2663 \]
2664
2665 for single-channel arrays,
2666
2667 \[
2668 \texttt{dst}(I)=
2669 \texttt{lower}_0 <= \texttt{src}(I)_0 < \texttt{upper}_0 \land
2670 \texttt{lower}_1 <= \texttt{src}(I)_1 < \texttt{upper}_1
2671 \]
2672
2673 for two-channel arrays etc.
2674
2675 'dst(I)' is set to 0xff (all \texttt{1}-bits) if 'src(I)' is within the range and 0 otherwise. All the arrays must have the same size (or ROI size)
2676
2677 \cvfunc{Max}\label{Max}
2678
2679 Finds per-element maximum of two arrays
2680
2681 \cvexp{
2682
2683 void cvMax( const CvArr* src1, const CvArr* src2, CvArr* dst );
2684
2685 }{CPP}{PYTHON}
2686
2687 \begin{description}
2688 \cvarg{src1}{The first source array}
2689 \cvarg{src2}{The second source array}
2690 \cvarg{dst}{The destination array}
2691 \end{description}
2692
2693 The function \texttt{cvMax} calculates per-element maximum of two arrays:
2694
2695 \[
2696 \texttt{dst}(I)=\max(\texttt{src1}(I), \texttt{src2}(I))
2697 \]
2698
2699 All the arrays must have a single channel, the same data type and the same size (or ROI size).
2700
2701
2702 \cvfunc{MaxS}\label{MaxS}
2703
2704 Finds per-element maximum of array and scalar
2705
2706 \cvexp{
2707
2708 void cvMaxS( const CvArr* src, double value, CvArr* dst );
2709
2710 }{CPP}{PYTHON}
2711
2712 \begin{description}
2713 \cvarg{src}{The first source array}
2714 \cvarg{value}{The scalar value}
2715 \cvarg{dst}{The destination array}
2716 \end{description}
2717
2718 The function \texttt{cvMaxS} calculates per-element maximum of array and scalar:
2719
2720 \[
2721 \texttt{dst}(I)=\max(\texttt{src}(I), \texttt{value})
2722 \]
2723
2724 All the arrays must have a single channel, the same data type and the same size (or ROI size).
2725
2726
2727 \cvfunc{Min}\label{Min}
2728
2729 Finds per-element minimum of two arrays
2730
2731 \cvexp{
2732
2733 void cvMin( const CvArr* src1, const CvArr* src2, CvArr* dst );
2734
2735 }{CPP}{PYTHON}
2736
2737 \begin{description}
2738 \cvarg{src1}{The first source array}
2739 \cvarg{src2}{The second source array}
2740 \cvarg{dst}{The destination array}
2741 \end{description}
2742
2743
2744 The function \texttt{cvMin} calculates per-element minimum of two arrays:
2745
2746 \[
2747 \texttt{dst}(I)=\min(\texttt{src1}(I),\texttt{src2}(I))
2748 \]
2749
2750 All the arrays must have a single channel, the same data type and the same size (or ROI size).
2751
2752
2753 \cvfunc{MinS}\label{MinS}
2754
2755 Finds per-element minimum of array and scalar
2756
2757 \cvexp{
2758
2759 void cvMinS( const CvArr* src, double value, CvArr* dst );
2760
2761 }{CPP}{PYTHON}
2762
2763 \begin{description}
2764 \cvarg{src}{The first source array}
2765 \cvarg{value}{The scalar value}
2766 \cvarg{dst}{The destination array}
2767 \end{description}
2768
2769 The function \texttt{cvMinS} calculates minimum of array and scalar:
2770
2771 \[
2772 \texttt{dst}(I)=\min(\texttt{src}(I), \texttt{value})
2773 \]
2774
2775 All the arrays must have a single channel, the same data type and the same size (or ROI size).
2776
2777 \cvfunc{AbsDiff}\label{AbsDiff}
2778
2779 Calculates absolute difference between two arrays
2780
2781 \cvexp{
2782
2783 void cvAbsDiff( const CvArr* src1, const CvArr* src2, CvArr* dst );
2784
2785 }{CPP}{PYTHON}
2786
2787 \begin{description}
2788 \cvarg{src1}{The first source array}
2789 \cvarg{src2}{The second source array}
2790 \cvarg{dst}{The destination array}
2791 \end{description}
2792
2793 The function \texttt{cvAbsDiff} calculates absolute difference between two arrays.
2794
2795 \[ \texttt{dst}(i)_c = |\texttt{src1}(I)_c - \texttt{src2}(I)_c| \]
2796
2797 All the arrays must have the same data type and the same size (or ROI size).
2798
2799 \cvfunc{AbsDiffS}\label{AbsDiffS}
2800
2801 Calculates absolute difference between array and scalar
2802
2803 \cvexp{
2804
2805 void cvAbsDiffS( const CvArr* src, CvArr* dst, CvScalar value );
2806 }{CPP}{PYTHON}
2807
2808 \begin{lstlisting}
2809 #define cvAbs(src, dst) cvAbsDiffS(src, dst, cvScalarAll(0))
2810 \end{lstlisting}
2811
2812 \begin{description}
2813 \cvarg{src}{The source array}
2814 \cvarg{dst}{The destination array}
2815 \cvarg{value}{The scalar}
2816 \end{description}
2817
2818 The function \texttt{cvAbsDiffS} calculates absolute difference between array and scalar.
2819
2820 \[ \texttt{dst}(i)_c = |\texttt{src}(I)_c - \texttt{value}_c| \]
2821
2822 All the arrays must have the same data type and the same size (or ROI size).
2823
2824 \subsection{Statistics}
2825
2826 \cvfunc{CountNonZero}\label{CountNonZero}
2827
2828 Counts non-zero array elements
2829
2830 \cvexp{
2831
2832 int cvCountNonZero( const CvArr* arr );
2833
2834 }{CPP}{PYTHON}
2835
2836 \begin{description}
2837 \cvarg{arr}{The array, must be single-channel array or multi-channel image with COI set}
2838 \end{description}
2839
2840
2841 The function \texttt{cvCountNonZero} returns the number of non-zero elements in arr:
2842
2843 \[ \sum_I (\texttt{arr}(I) \ne 0) \]
2844
2845 In case of \texttt{IplImage} both ROI and COI are supported.
2846
2847
2848 \cvfunc{Sum}\label{Sum}
2849
2850 Summarizes array elements
2851
2852 \cvexp{
2853
2854 CvScalar cvSum( const CvArr* arr );
2855
2856 }{CPP}{PYTHON}
2857
2858 \begin{description}
2859 \cvarg{arr}{The array}
2860 \end{description}
2861
2862
2863 The function \texttt{cvSum} calculates sum \texttt{S} of array elements, independently for each channel:
2864
2865 \[ \sum_I \texttt{arr}(I)_c \]
2866
2867 If the array is \texttt{IplImage} and COI is set, the function processes the selected channel only and stores the sum to the first scalar component
2868 .
2869
2870
2871 \cvfunc{Avg}\label{Avg}
2872
2873 Calculates average (mean) of array elements
2874
2875 \cvexp{
2876
2877 CvScalar cvAvg( const CvArr* arr, const CvArr* mask=NULL );
2878
2879 }{CPP}{PYTHON}
2880
2881 \begin{description}
2882 \cvarg{arr}{The array}
2883 \cvarg{mask}{The optional operation mask}
2884 \end{description}
2885
2886
2887 The function \texttt{cvAvg} calculates the average value \texttt{M} of array elements, independently for each channel:
2888
2889 \[
2890 \begin{array}{l}
2891 N = \sum_I (\texttt{mask}(I) \ne 0)\\
2892 M_c = \frac{\sum_{ I, \, \texttt{mask}(I) \ne 0} \texttt{arr}(I)_c}{N}
2893 \end{array}
2894 \]
2895
2896 If the array is \texttt{IplImage} and COI is set, the function processes the selected channel only and stores the average to the first scalar component $ S_0 $ .
2897
2898 \cvfunc{AvgSdv}\label{AvgSdv}
2899
2900 Calculates average (mean) of array elements
2901
2902 \cvexp{
2903
2904 void cvAvgSdv( const CvArr* arr, CvScalar* mean, CvScalar* std\_dev, const CvArr* mask=NULL );
2905
2906 }{CPP}{PYTHON}
2907
2908 \begin{description}
2909 \cvarg{arr}{The array}
2910 \cvarg{mean}{Pointer to the mean value, may be NULL if it is not needed}
2911 \cvarg{std\_dev}{Pointer to the standard deviation}
2912 \cvarg{mask}{The optional operation mask}
2913 \end{description}
2914
2915 The function \texttt{cvAvgSdv} calculates the average value and standard deviation of array elements, independently for each channel:
2916
2917 \[
2918 \begin{array}{l}
2919 N = \sum_I (\texttt{mask}(I) \ne 0)\\
2920 mean_c = \frac{\sum_{ I, \, \texttt{mask}(I) \ne 0} \texttt{arr}(I)_c}{N}\\
2921 std\_dev_c = \sqrt{\sum_{ I, \, \texttt{mask}(I) \ne 0} (\texttt{arr}(I)_c - mean_c)^2}
2922 \end{array}
2923 \]
2924
2925 If the array is \texttt{IplImage} and COI is set, the function processes the selected channel only and stores the average and standard deviation to the first compoenents of output scalars ($mean_0$ and $std\_dev_0$).
2926
2927 \cvfunc{MinMaxLoc}\label{MinMaxLoc}
2928
2929 Finds global minimum and maximum in array or subarray
2930
2931 \cvexp{
2932
2933 void cvMinMaxLoc( const CvArr* arr, double* min\_val, double* max\_val,
2934                   CvPoint* min\_loc=NULL, CvPoint* max\_loc=NULL, const CvArr* mask=NULL );
2935
2936 }{CPP}{PYTHON}
2937
2938 \begin{description}
2939 \cvarg{arr}{The source array, single-channel or multi-channel with COI set}
2940 \cvarg{min\_val}{Pointer to returned minimum value}
2941 \cvarg{max\_val}{Pointer to returned maximum value}
2942 \cvarg{min\_loc}{Pointer to returned minimum location}
2943 \cvarg{max\_loc}{Pointer to returned maximum location}
2944 \cvarg{mask}{The optional mask that is used to select a subarray}
2945 \end{description}
2946
2947 The function \texttt{MinMaxLoc} finds minimum and maximum element values
2948 and their positions. The extremums are searched over the whole array,
2949 selected \texttt{ROI} (in case of \texttt{IplImage}) or, if \texttt{mask}
2950 is not \texttt{NULL}, in the specified array region. If the array has
2951 more than one channel, it must be \texttt{IplImage} with \texttt{COI}
2952 set. In case if multi-dimensional arrays \texttt{min\_loc->x} and \texttt{max\_loc->x}
2953 will contain raw (linear) positions of the extremums.
2954
2955 \cvfunc{Norm}\label{Norm}
2956
2957 Calculates absolute array norm, absolute difference norm or relative difference norm
2958
2959 \cvexp{
2960
2961 double cvNorm( const CvArr* arr1, const CvArr* arr2=NULL, int norm\_type=CV\_L2, const CvArr* mask=NULL );
2962
2963 }{CPP}{PYTHON}
2964
2965 \begin{description}
2966 \cvarg{arr1}{The first source image}
2967 \cvarg{arr2}{The second source image. If it is NULL, the absolute norm of \texttt{arr1} is calculated, otherwise absolute or relative norm of \texttt{arr1}-\texttt{arr2} is calculated.}
2968 \cvarg{normType}{Type of norm, see the discussion}
2969 \cvarg{mask}{The optional operation mask}
2970 \end{description}
2971
2972 The function \texttt{cvNorm} calculates the absolute norm of \texttt{arr1} if \texttt{arr2} is NULL:
2973 \[
2974 norm = \forkthree
2975 {||\texttt{arr1}||_C    = \max_I |\texttt{arr1}(I)|}{if $\texttt{normType} = \texttt{CV\_C}$}
2976 {||\texttt{arr1}||_{L1} = \sum_I |\texttt{arr1}(I)|}{if $\texttt{normType} = \texttt{CV\_L1}$}
2977 {||\texttt{arr1}||_{L2} = \sqrt{\sum_I \texttt{arr1}(I)^2}}{if $\texttt{normType} = \texttt{CV\_L2}$}
2978 \]
2979
2980 And the function calculates absolute or relative difference norm if \texttt{arr2} is not NULL:
2981 \[
2982 norm = \forkthree
2983 {||\texttt{arr1}-\texttt{arr2}||_C    = \max_I |\texttt{arr1}(I) - \texttt{arr2}(I)|}{if $\texttt{normType} = \texttt{CV\_C}$}
2984 {||\texttt{arr1}-\texttt{arr2}||_{L1} = \sum_I |\texttt{arr1}(I) - \texttt{arr2}(I)|}{if $\texttt{normType} = \texttt{CV\_L1}$}
2985 {||\texttt{arr1}-\texttt{arr2}||_{L2} = \sqrt{\sum_I (\texttt{arr1}(I) - \texttt{arr2}(I))^2}}{if $\texttt{normType} = \texttt{CV\_L2}$}
2986 \]
2987
2988 or
2989
2990 \[
2991 norm = \forkthree
2992 {\frac{||\texttt{arr1}-\texttt{arr2}||_C    }{||\texttt{arr2}||_C   }}{if $\texttt{normType} = \texttt{CV\_RELATIVE\_C}$}
2993 {\frac{||\texttt{arr1}-\texttt{arr2}||_{L1} }{||\texttt{arr2}||_{L1}}}{if $\texttt{normType} = \texttt{CV\_RELATIVE\_L1}$}
2994 {\frac{||\texttt{arr1}-\texttt{arr2}||_{L2} }{||\texttt{arr2}||_{L2}}}{if $\texttt{normType} = \texttt{CV\_RELATIVE\_L2}$}
2995 \]
2996
2997 The function \texttt{Norm} returns the calculated norm. The multiple-channel array are treated as single-channel, that is, the results for all channels are combined.
2998
2999 % XXX missing Reduce
3000
3001 \subsection{Linear Algebra}
3002
3003 \cvfunc{SetIdentity}\label{SetIdentity}
3004
3005 Initializes scaled identity matrix
3006
3007 \cvexp{
3008
3009 void cvSetIdentity( CvArr* mat, CvScalar value=cvRealScalar(1) );
3010
3011 }{CPP}{PYTHON}
3012
3013 \begin{description}
3014 \cvarg{arr}{The matrix to initialize (not necesserily square)}
3015 \cvarg{value}{The value to assign to the diagonal elements}
3016 \end{description}
3017
3018 The function \texttt{cvSetIdentity} initializes scaled identity matrix:
3019
3020 \[
3021 \texttt{arr}(i,j)=\fork{\texttt{value}}{ if $i=j$}{0}{otherwise}
3022 \]
3023
3024 \cvfunc{DotProduct}\label{DotProduct}
3025
3026 Calculates dot product of two arrays in Euclidian metrics
3027
3028 \cvexp{
3029
3030 double cvDotProduct( const CvArr* src1, const CvArr* src2 );
3031
3032 }{CPP}{PYTHON}
3033
3034 \begin{description}
3035 \cvarg{src1}{The first source array}
3036 \cvarg{src2}{The second source array}
3037 \end{description}
3038
3039 The function \texttt{cvDotProduct} calculates and returns the Euclidean dot product of two arrays.
3040
3041 \[
3042 src1 \bullet src2 = \sum_I (\texttt{src1}(I) \texttt{src2}(I))
3043 \]
3044
3045 In case of multiple channel arrays the results for all channels are accumulated. In particular, \texttt{cvDotProduct(a,a)} where \texttt{a} is a complex vector, will return $||\texttt{a}||^2$.
3046 The function can process multi-dimensional arrays, row by row, layer by layer and so on.
3047
3048 \cvfunc{CrossProduct}\label{CrossProduct}
3049
3050 Calculates cross product of two 3D vectors
3051
3052 \cvexp{
3053
3054 void cvCrossProduct( const CvArr* src1, const CvArr* src2, CvArr* dst );
3055
3056 }{CPP}{PYTHON}
3057
3058 \begin{description}
3059 \cvarg{src1}{The first source vector}
3060 \cvarg{src2}{The second source vector}
3061 \cvarg{dst}{The destination vector}
3062 \end{description}
3063
3064
3065 The function \texttt{cvCrossProduct} calculates the cross product of two 3D vectors:
3066
3067 \[ \texttt{dst} = \texttt{src1} \times \texttt{src2} \]
3068 or:
3069 \[
3070 \begin{array}{l}
3071 \texttt{dst}_1 = \texttt{src1}_2 \texttt{src2}_3 - \texttt{src1}_3 \texttt{src2}_2\\
3072 \texttt{dst}_2 = \texttt{src1}_3 \texttt{src2}_1 - \texttt{src1}_1 \texttt{src2}_3\\
3073 \texttt{dst}_3 = \texttt{src1}_1 \texttt{src2}_2 - \texttt{src1}_2 \texttt{src2}_1
3074 \end{array}
3075 \]
3076
3077 \cvfunc{ScaleAdd}\label{ScaleAdd}
3078
3079 Calculates sum of scaled array and another array
3080
3081 \cvexp{
3082
3083 void cvScaleAdd( const CvArr* src1, CvScalar scale, const CvArr* src2, CvArr* dst );
3084
3085 }{CPP}{PYTHON}
3086 \begin{lstlisting}
3087 #define cvMulAddS cvScaleAdd
3088 \end{lstlisting}
3089
3090 \begin{description}
3091 \cvarg{src1}{The first source array}
3092 \cvarg{scale}{Scale factor for the first array}
3093 \cvarg{src2}{The second source array}
3094 \cvarg{dst}{The destination array}
3095 \end{description}
3096
3097 The function \texttt{cvScaleAdd} calculates sum of scaled array and another array:
3098
3099 \[
3100 \texttt{dst}(I)=\texttt{scale} \, \texttt{src1}(I) + \texttt{src2}(I)
3101 \]
3102
3103 All array parameters should have the same type and the same size.
3104
3105 \cvfunc{GEMM}\label{GEMM}
3106
3107 Performs generalized matrix multiplication
3108
3109 \cvexp{
3110
3111 void  cvGEMM( const CvArr* src1, const CvArr* src2, double alpha,
3112               const CvArr* src3, double beta, CvArr* dst, int tABC=0 );
3113
3114 }{CPP}{PYTHON}
3115 \begin{lstlisting}
3116 #define cvMatMulAdd( src1, src2, src3, dst ) cvGEMM( src1, src2, 1, src3, 1, dst, 0 )
3117 #define cvMatMul( src1, src2, dst ) cvMatMulAdd( src1, src2, 0, dst )
3118 \end{lstlisting}
3119
3120 \begin{description}
3121 \cvarg{src1}{The first source array}
3122 \cvarg{src2}{The second source array}
3123 \cvarg{src3}{The third source array (shift). Can be NULL, if there is no shift.}
3124 \cvarg{dst}{The destination array}
3125 \cvarg{tABC}{The operation flags that can be 0 or combination of the following values
3126 \begin{description}
3127 \cvarg{CV\_GEMM\_A\_T}{transpose src1}
3128 \cvarg{CV\_GEMM\_B\_T}{transpose src2}
3129 \cvarg{CV\_GEMM\_C\_T}{transpose src3}
3130 \end{description}
3131 for example, \texttt{CV\_GEMM\_A\_T+CV\_GEMM\_C\_T} corresponds to
3132 \[
3133 \texttt{alpha} \, \texttt{src1} ^T \, \texttt{src2} + \texttt{beta} \, \texttt{src3} ^T
3134 \]}
3135 \end{description}
3136
3137 The function \texttt{cvGEMM} performs generalized matrix multiplication:
3138
3139 \[
3140 \texttt{dst} = \texttt{alpha} \, op(\texttt{src1}) \, op(\texttt{src2}) + \texttt{beta} \, op(\texttt{src3}) \quad \text{where $op(X)$ is $X$ or $X^T$}
3141 \]
3142
3143 All the matrices should have the same data type and the coordinated sizes. Real or complex floating-point matrices are supported
3144
3145 \cvfunc{Transform}\label{Transform}
3146
3147 Performs matrix transform of every array element
3148
3149 \cvexp{
3150
3151 void cvTransform( const CvArr* src, CvArr* dst, const CvMat* transmat, const CvMat* shiftvec=NULL );
3152
3153 }{CPP}{PYTHON}
3154
3155 \begin{description}
3156 \cvarg{src}{The first source array}
3157 \cvarg{dst}{The destination array}
3158 \cvarg{transmat}{Transformation matrix}
3159 \cvarg{shiftvec}{Optional shift vector}
3160 \end{description}
3161
3162 The function \texttt{cvTransform} performs matrix transformation of every element of array \texttt{src} and stores the results in \texttt{dst}:
3163
3164 \[
3165 dst(I) = transmat \cdot src(I) + shiftvec %  or   dst(I),,k,,=sum,,j,,(transmat(k,j)*src(I),,j,,) + shiftvec(k)
3166 \]
3167
3168 That is every element of \texttt{N}-channel array \texttt{src} is
3169 considered as \texttt{N}-element vector, which is transformed using
3170 matrix $\texttt{M} \times \texttt{N}$ matrix \texttt{transmat} and shift
3171 vector \texttt{shiftvec} into an element of \texttt{M}-channel array
3172 \texttt{dst}. There is an option to embedd \texttt{shiftvec} into
3173 \texttt{transmat}. In this case \texttt{transmat} should be $\texttt{M}
3174 \times (N+1)$ matrix and the right-most column is treated as the shift
3175 vector.
3176
3177 Both source and destination arrays should have the same depth and the
3178 same size or selected ROI size. \texttt{transmat} and \texttt{shiftvec}
3179 should be real floating-point matrices.
3180
3181 The function may be used for geometrical transformation of n dimensional
3182 point set, arbitrary linear color space transformation, shuffling the
3183 channels etc.
3184
3185 \cvfunc{PerspectiveTransform}\label{PerspectiveTransform}
3186
3187 Performs perspective matrix transform of vector array
3188
3189 \cvexp{
3190
3191 void cvPerspectiveTransform( const CvArr* src, CvArr* dst, const CvMat* mat );
3192
3193 }{CPP}{PYTHON}
3194
3195 \begin{description}
3196 \cvarg{src}{The source three-channel floating-point array}
3197 \cvarg{dst}{The destination three-channel floating-point array}
3198 \cvarg{mat}{$3\times 3$ or $4 \times 4$ transformation matrix}
3199 \end{description}
3200
3201
3202 The function \texttt{PerspectiveTransform} transforms every element of \texttt{src} (by treating it as 2D or 3D vector) in the following way:
3203
3204 \[ (x, y, z) \rightarrow (x'/w, y'/w, z'/w) \]
3205
3206 where
3207
3208 \[
3209 (x', y', z', w') = \texttt{mat} \cdot
3210 \begin{bmatrix} x & y & z & 1 \end{bmatrix}
3211 \]
3212
3213 and
3214 \[ w = \fork{w'}{if $w' \ne 0$}{\infty}{otherwise} \]
3215
3216 \cvfunc{MulTransposed}\label{MulTransposed}
3217
3218 Calculates product of array and transposed array
3219
3220 \cvexp{
3221
3222 void cvMulTransposed( const CvArr* src, CvArr* dst, int order, const CvArr* delta=NULL, double scale=1.0 );
3223
3224 }{CPP}{PYTHON}
3225
3226 \begin{description}
3227 \cvarg{src}{The source matrix}
3228 \cvarg{dst}{The destination matrix. Must be \texttt{CV\_32F} or \texttt{CV\_64F}.}
3229 \cvarg{order}{Order of multipliers}
3230 \cvarg{delta}{An optional array, subtracted from \texttt{src} before multiplication}
3231 \cvarg{scale}{An optional scaling}
3232 \end{description}
3233
3234 The function \texttt{MulTransposed} calculates the product of src and its transposition.
3235
3236 The function evaluates
3237
3238 \[
3239 \texttt{dst}=\texttt{scale} (\texttt{src}-\texttt{delta}) (\texttt{src}-\texttt{delta})^T
3240 \]
3241
3242 if $\texttt{order}=0$, and
3243
3244 \[
3245 \texttt{dst}=\texttt{scale} (\texttt{src}-\texttt{delta})^T (\texttt{src}-\texttt{delta})
3246 \]
3247
3248 otherwise.
3249
3250 \cvfunc{Trace}\label{Trace}
3251
3252 Returns trace of matrix
3253
3254 \cvexp{
3255
3256 CvScalar cvTrace( const CvArr* mat );
3257
3258 }{CPP}{PYTHON}
3259
3260 \begin{description}
3261 \cvarg{mat}{The source matrix}
3262 \end{description}
3263
3264
3265 The function \texttt{cvTrace} returns sum of diagonal elements of the matrix \texttt{src1}.
3266
3267 \[ tr(\texttt{mat}) = \sum_i \texttt{mat}(i,i) \]
3268
3269 \cvfunc{Transpose}\label{Transpose}
3270
3271 Transposes matrix
3272
3273 \cvexp{
3274
3275 void cvTranspose( const CvArr* src, CvArr* dst );
3276
3277 }{CPP}{PYTHON}
3278
3279 \begin{lstlisting}
3280 #define cvT cvTranspose
3281 \end{lstlisting}
3282
3283 \begin{description}
3284 \cvarg{src}{The source matrix}
3285 \cvarg{dst}{The destination matrix}
3286 \end{description}
3287
3288 The function \texttt{cvTranspose} transposes matrix \texttt{src1}:
3289
3290 \[ \texttt{dst}(i,j) = \texttt{src}(j,i) \]
3291
3292 Note that no complex conjugation is done in case of complex
3293 matrix. Conjugation should be done separately: look at the sample code
3294 in \cross{XorS} for example
3295
3296 \cvfunc{Det}\label{Det}
3297
3298 Returns determinant of matrix
3299
3300 \cvexp{
3301
3302 double cvDet( const CvArr* mat );
3303
3304 }{CPP}{PYTHON}
3305
3306 \begin{description}
3307 \cvarg{mat}{The source matrix}
3308 \end{description}
3309
3310 The function \texttt{cvDet} returns determinant of the square matrix \texttt{mat}. The direct method is used for small matrices and Gaussian elimination is used for larger matrices. For symmetric positive-determined matrices it is also possible to run
3311 \cross{SVD}
3312 with $U = V = 0$ and then calculate determinant as a product of the diagonal elements of $W$.
3313
3314 \cvfunc{Invert}\label{Invert}
3315
3316 Finds inverse or pseudo-inverse of matrix
3317
3318 \cvexp{
3319
3320 double cvInvert( const CvArr* src, CvArr* dst, int method=CV\_LU );
3321
3322 }{CPP}{PYTHON}
3323 \begin{lstlisting}
3324 #define cvInv cvInvert
3325 \end{lstlisting}
3326
3327 \begin{description}
3328 \cvarg{src}{The source matrix}
3329 \cvarg{dst}{The destination matrix}
3330 \cvarg{method}{Inversion method
3331 \begin{description}
3332  \cvarg{CV\_LU}{Gaussian elimination with optimal pivot element chose}
3333  \cvarg{CV\_SVD}{Singular value decomposition (SVD) method}
3334  \cvarg{CV\_SVD\_SYM}{SVD method for a symmetric positively-defined matrix}
3335 \end{description}}
3336 \end{description}
3337
3338 The function \texttt{cvInvert} inverts matrix \texttt{src1} and stores the result in \texttt{src2}
3339
3340 In case of \texttt{LU} method the function returns \texttt{src1} determinant (src1 must be square). If it is 0, the matrix is not inverted and \texttt{src2} is filled with zeros.
3341
3342 In case of \texttt{SVD} methods the function returns the inversed condition number of \texttt{src1} (ratio of the smallest singular value to the largest singular value) and 0 if \texttt{src1} is all zeros. The SVD methods calculate a pseudo-inverse matrix if \texttt{src1} is singular
3343
3344
3345 \cvfunc{Solve}\label{Solve}
3346
3347 Solves linear system or least-squares problem
3348
3349 \cvexp{
3350
3351 int cvSolve( const CvArr* src1, const CvArr* src2, CvArr* dst, int method=CV\_LU );
3352
3353 }{CPP}{PYTHON}
3354
3355 \begin{description}
3356 \cvarg{A}{The source matrix}
3357 \cvarg{B}{The right-hand part of the linear system}
3358 \cvarg{X}{The output solution}
3359 \cvarg{method}{The solution (matrix inversion) method
3360 \begin{description}
3361  \cvarg{CV\_LU}{Gaussian elimination with optimal pivot element chose}
3362  \cvarg{CV\_SVD}{Singular value decomposition (SVD) method}
3363  \cvarg{CV\_SVD\_SYM}{SVD method for a symmetric positively-defined matrix.}
3364 \end{description}}
3365 \end{description}
3366
3367 The function \texttt{cvSolve} solves linear system or least-squares problem (the latter is possible with SVD methods):
3368
3369 \[
3370 \texttt{dst} = argmin_X||\texttt{src1} \, \texttt{X} - \texttt{src2}||
3371 \]
3372
3373 If \texttt{CV\_LU} method is used, the function returns 1 if \texttt{src1} is non-singular and 0 otherwise, in the latter case \texttt{dst} is not valid
3374
3375 \cvfunc{SVD}\label{SVD}
3376
3377 Performs singular value decomposition of real floating-point matrix
3378
3379 \cvexp{
3380
3381 void cvSVD( \par CvArr* A, \par CvArr* W, \par CvArr* U=NULL, \par CvArr* V=NULL, \par int flags=0 );
3382
3383 }{CPP}{PYTHON}
3384
3385 \begin{description}
3386 \cvarg{A}{Source $\texttt{M} \times \texttt{N}$ matrix}
3387 \cvarg{W}{Resulting singular value matrix ($\texttt{M} \times \texttt{N}$ or $\texttt{N} \times \texttt{N}$) or vector ($\texttt{N} \times 1$)}
3388 \cvarg{U}{Optional left orthogonal matrix ($\texttt{M} \times \texttt{M}$ or $\texttt{M} \times \texttt{N}$)
3389 If \texttt{CV\_SVD\_U\_T} is specified, the number of rows and columns in the sentence above should be swapped.}
3390 \cvarg{V}{Optional right orthogonal matrix ($\texttt{N} \times \texttt{N}$)}
3391 \cvarg{flags}{Operation flags; can be 0 or combination of the following values:
3392 \begin{description}
3393   \cvarg{CV\_SVD\_MODIFY\_A}{enables modification of matrix \texttt{src1} during the operation. It speeds up the processing.}
3394   \cvarg{CV\_SVD\_U\_T}{means that the tranposed matrix \texttt{U} is returned. Specifying the flag speeds up the processing.}
3395   \cvarg{CV\_SVD\_V\_T}{means that the tranposed matrix \texttt{V} is returned. Specifying the flag speeds up the processing.}
3396 \end{description}}
3397 \end{description}
3398
3399 The function \texttt{cvSVD} decomposes matrix \texttt{A} into a product of a diagonal matrix and two orthogonal matrices:
3400
3401 \[
3402 A=U \, W \, V^T
3403 \]
3404
3405 Where $W$ is diagonal matrix of singular values that can be coded as a
3406 1D vector of singular values and $U$ and $V$. All the singular values
3407 are non-negative and sorted (together with $U$ and and $V$ columns)
3408 in descenting order.
3409
3410 SVD algorithm is numerically robust and its typical applications include:
3411
3412 \begin{itemize}
3413   \item accurate eigenvalue problem solution when matrix \texttt{A}
3414   is square, symmetric and positively defined matrix, for example, when
3415   it is a covariation matrix. $W$ in this case will be a vector
3416   of eigen values, and $U = V$
3417   (thus, only one of $U$ or $V$ needs to be calculated if
3418   the eigen vectors are required)
3419   \item accurate solution of poor-conditioned linear systems
3420   \item least-squares solution of overdetermined linear systems. This and previous is done by \cross{Solve} function with \texttt{CV\_SVD} method
3421   \item accurate calculation of different matrix characteristics such as rank (number of non-zero singular values), condition number (ratio of the largest singular value to the smallest one), determinant (absolute value of determinant is equal to the product of singular values). All the things listed in this item do not require calculation of $U$ and $V$ matrices.
3422 \end{itemize}
3423
3424 \cvfunc{SVBkSb}\label{SVBkSb}
3425
3426 Performs singular value back substitution
3427
3428 \cvexp{
3429
3430 void  cvSVBkSb( \par const CvArr* W,\par const CvArr* U,\par const CvArr* V,\par const CvArr* B,\par CvArr* X,\par int flags );
3431
3432 }{CPP}{PYTHON}
3433
3434 \begin{description}
3435 \cvarg{W}{Matrix or vector of singular values}
3436 \cvarg{U}{Left orthogonal matrix (tranposed, perhaps)}
3437 \cvarg{V}{Right orthogonal matrix (tranposed, perhaps)}
3438 \cvarg{B}{The matrix to multiply the pseudo-inverse of the original matrix \texttt{A} by. This is the optional parameter. If it is omitted then it is assumed to be an identity matrix of an appropriate size (So \texttt{X} will be the reconstructed pseudo-inverse of \texttt{A}).}
3439 \cvarg{X}{The destination matrix: result of back substitution.}
3440 \cvarg{flags}{Operation flags, should match exactly to the \texttt{flags} passed to \cross{SVD}}
3441 \end{description}
3442
3443 The function \texttt{cvSVBkSb} calculates back substitution for decomposed matrix \texttt{A} (see \cross{SVD} description) and matrix \texttt{B}:
3444
3445 \[
3446 \texttt{X} = \texttt{V} \texttt{W}^{-1} \texttt{U}^T \texttt{B}
3447 \]
3448
3449 where
3450
3451 \[
3452 W^{-1}_{(i,i)}=
3453 \fork
3454 {1/W_{(i,i)}}{if $W_{(i,i)} > \epsilon \sum_i{W_{(i,i)}}$ }
3455 {0}{otherwise}
3456 \]
3457
3458 And $\epsilon$ is a small number that depends on the matrix data type.
3459
3460 This function together with \cross{SVD} is used inside \cross{Invert}
3461 and \cross{Solve}, and the possible reason to use these (svd and bksb)
3462 "low-level" function is to avoid temporary matrices allocation inside
3463 the high-level counterparts (inv and solve).
3464
3465 \cvfunc{EigenVV}\label{EigenVV}
3466
3467 Computes eigenvalues and eigenvectors of symmetric matrix
3468
3469 \cvexp{
3470
3471 void cvEigenVV( \par CvArr* mat,\par CvArr* evects,\par CvArr* evals,\par double eps=0 );
3472
3473 }{CPP}{PYTHON}
3474
3475 \begin{description}
3476 \cvarg{mat}{The input symmetric square matrix. It is modified during the processing.}
3477 \cvarg{evects}{The output matrix of eigenvectors, stored as a subsequent rows}
3478 \cvarg{evals}{The output vector of eigenvalues, stored in the descenting order (order of eigenvalues and eigenvectors is syncronized, of course)}
3479 \cvarg{eps}{Accuracy of diagonalization. Typically, \texttt{DBL\_EPSILON} (about $ 10^{-15} $) works well}
3480 \end{description}
3481
3482
3483 The function \texttt{cvEigenVV} computes the eigenvalues and eigenvectors of the matrix \texttt{A}:
3484
3485 \begin{lstlisting}
3486 mat*evects(i,:)' = evals(i)*evects(i,:)' (in MATLAB notation)
3487 \end{lstlisting}
3488
3489 The contents of matrix \texttt{A} is destroyed by the function.
3490
3491 Currently the function is slower than \cross{SVD} yet less accurate,
3492 so if \texttt{A} is known to be positively-defined (for example, it
3493 is a covariation matrix), it is recommended to use \cross{SVD} to find
3494 eigenvalues and eigenvectors of \texttt{A}, especially if eigenvectors
3495 are not required.
3496
3497 \cvfunc{CalcCovarMatrix}\label{CalcCovarMatrix}
3498
3499 Calculates covariation matrix of the set of vectors
3500
3501 \cvexp{
3502
3503 void cvCalcCovarMatrix( \par const CvArr** vects,\par int count,\par CvArr* cov\_mat,\par CvArr* avg,\par int flags );
3504
3505 }{CPP}{PYTHON}
3506
3507 \begin{description}
3508 \cvarg{vects}{The input vectors. They all must have the same type and the same size. The vectors do not have to be 1D, they can be 2D (e.g. images) etc.}
3509 \cvarg{count}{The number of input vectors}
3510 \cvarg{cov\_mat}{The output covariation matrix that should be floating-point and square}
3511 \cvarg{avg}{The input or output (depending on the flags) array - the mean (average) vector of the input vectors}
3512 \cvarg{flags}{The operation flags, a combination of the following values
3513 \begin{description}
3514 \cvarg{CV\_COVAR\_SCRAMBLED}{the output covaration matrix is calculated as:
3515 $ \texttt{scale} * [ \texttt{vects} [0]- \texttt{avg} ,\texttt{vects} [1]- \texttt{avg} ,...]^T \cdot [\texttt{vects} [0]-\texttt{avg} ,\texttt{vects} [1]-\texttt{avg} ,...] $,
3516 that is, the covariation matrix is
3517 $\texttt{count} \times \texttt{count}$.
3518 Such an unusual covariation matrix is used for fast PCA
3519 of a set of very large vectors (see, for example, EigenFaces technique
3520 for face recognition). Eigenvalues of this "scrambled" matrix will
3521 match to the eigenvalues of the true covariation matrix and the "true"
3522 eigenvectors can be easily calculated from the eigenvectors of the
3523 "scrambled" covariation matrix.
3524 }
3525 \cvarg{CV\_COVAR\_NORMAL}{the output covaration matrix is calculated as:
3526 $ \texttt{scale} * [ \texttt{vects} [0]- \texttt{avg} ,\texttt{vects} [1]- \texttt{avg} ,...] \cdot [\texttt{vects} [0]-\texttt{avg} ,\texttt{vects} [1]-\texttt{avg} ,...]^T $,
3527 that is, \texttt{cov\_mat} will be a usual covariation matrix
3528 with the same linear size as the total number of elements in every
3529 input vector. One and only one of \texttt{CV\_COVAR\_SCRAMBLED} and
3530 \texttt{CV\_COVAR\_NORMAL} must be specified}
3531 \cvarg{CV\_COVAR\_USE\_AVG}{if the flag is specified, the function does not calculate \texttt{avg} from the input vectors, but, instead, uses the passed \texttt{avg} vector. This is useful if \texttt{avg} has been already calculated somehow, or if the covariation matrix is calculated by parts - in this case, \texttt{avg} is not a mean vector of the input sub-set of vectors, but rather the mean vector of the whole set.}
3532 \cvarg{CV\_COVAR\_SCALE}{if the flag is specified, the covariation matrix is scaled. In the "normal" mode \texttt{scale} is '1./count', in the "scrambled" mode \texttt{scale} is reciprocal of the total number of elements in every input vector. By default (if the flag is not specified) the covariation matrix is not scaled ('scale=1').}
3533
3534 \cvarg{CV\_COVAR\_ROWS}{Means that all the input vectors are stored as rows of a single matrix, \texttt{vects[0]}. \texttt{count} is ignored in this case, and \texttt{avg} should be a single-row vector of an appropriate size.}
3535 \cvarg{CV\_COVAR\_COLS}{Means that all the input vectors are stored as columns of a single matrix, \texttt{vects[0]}. \texttt{count} is ignored in this case, and \texttt{avg} should be a single-column vector of an appropriate size.}
3536
3537 \end{description}}
3538 \end{description}
3539
3540 The function \texttt{cvCalcCovarMatrix} calculates the covariation matrix
3541 and, optionally, mean vector of the set of input vectors. The function
3542 can be used for PCA, for comparing vectors using Mahalanobis distance etc.
3543
3544 \cvfunc{Mahalonobis}\label{Mahalonobis}
3545
3546 Calculates Mahalonobis distance between two vectors
3547
3548 \cvexp{
3549
3550 double cvMahalanobis( \par const CvArr* vec1,\par const CvArr* vec2,\par CvArr* mat );
3551
3552 }{CPP}{PYTHON}
3553
3554 \begin{description}
3555 \cvarg{vec1}{The first 1D source vector}
3556 \cvarg{vec2}{The second 1D source vector}
3557 \cvarg{mat}{The inverse covariation matrix}
3558 \end{description}
3559
3560
3561 The function \texttt{cvMahalonobis} calculates the weighted distance between two vectors and returns it:
3562
3563 \begin{lstlisting}
3564
3565 d(vec1,vec2)=sqrt( sum,,i,j,, {mat(i,j)*(vec1(i)-vec2(i))*(vec1(j)-vec2(j))} )
3566
3567 \end{lstlisting}
3568
3569 The covariation matrix may be calculated using \cross{CalcCovarMatrix} function and further inverted using \cross{Invert} function (CV\_SVD method is the preffered one, because the matrix might be singular).
3570
3571
3572 \subsection{Math Functions}
3573
3574 \cvfunc{Round, Floor, Ceil}\label{Round, Floor, Ceil}
3575
3576 Converts floating-point number to integer
3577
3578 \cvexp{
3579
3580 int cvRound( double value );
3581 int cvFloor( double value );
3582 int cvCeil( double value );
3583
3584 }{CPP}{PYTHON}
3585
3586 \begin{description}
3587 \cvarg{value}{The input floating-point value}
3588 \end{description}
3589
3590
3591 The functions \texttt{cvRound}, \texttt{cvFloor} and \texttt{cvCeil}
3592 convert input floating-point number to integer using one of the rounding
3593 modes. \texttt{cvRound} returns the nearest integer value to the
3594 argument. \texttt{cvFloor} returns the maximum integer value that is not
3595 larger than the argument. \texttt{cvCeil} returns the minimum integer
3596 value that is not smaller than the argument. On some architectures the
3597 functions work much faster than the standard cast
3598 operations in C. If absolute value of the argument is greater than
3599 $2^{31}$, the result is not determined. Special values ( $ \pm \infty$ , NaN)
3600 are not handled.
3601
3602 \cvfunc{Sqrt}\label{Sqrt}
3603
3604 Calculates square root
3605
3606 \cvexp{
3607
3608 float cvSqrt( float value );
3609
3610 }{CPP}{PYTHON}
3611
3612 \begin{description}
3613 \cvarg{value}{The input floating-point value}
3614 \end{description}
3615
3616
3617 The function \texttt{cvSqrt} calculates square root of the argument. If the argument is negative, the result is not determined.
3618
3619 \cvfunc{InvSqrt}\label{InvSqrt}
3620
3621 Calculates inverse square root
3622
3623 \cvexp{
3624
3625 float cvInvSqrt( float value );
3626
3627 }{CPP}{PYTHON}
3628
3629 \begin{description}
3630 \cvarg{value}{The input floating-point value}
3631 \end{description}
3632
3633
3634 The function \texttt{cvInvSqrt} calculates inverse square root of the argument, and normally it is faster than \texttt{1./sqrt(value)}. If the argument is zero or negative, the result is not determined. Special values ( $ \pm \infty $ , NaN) are not handled.
3635
3636 \cvfunc{Cbrt}\label{Cbrt}
3637
3638 Calculates cubic root
3639
3640 \cvexp{
3641
3642 float cvCbrt( float value );
3643
3644 }{CPP}{PYTHON}
3645
3646 \begin{description}
3647 \cvarg{value}{The input floating-point value}
3648 \end{description}
3649
3650
3651 The function \texttt{cvCbrt} calculates cubic root of the argument, and normally it is faster than 'pow(value,1./3)'. Besides, negative arguments are handled properly. Special values ( $ \pm \infty $, NaN) are not handled.
3652
3653 \cvfunc{FastArctan}\label{FastArctan}
3654
3655 Calculates angle of 2D vector
3656
3657 \cvexp{
3658
3659 float cvFastArctan( float y, float x );
3660
3661 }{CPP}{PYTHON}
3662
3663 \begin{description}
3664 \cvarg{x}{x-coordinate of 2D vector}
3665 \cvarg{y}{y-coordinate of 2D vector}
3666 \end{description}
3667
3668
3669 The function \texttt{cvFastArctan} calculates full-range angle of input 2D vector. The angle is measured in degrees and varies from 0 degree  to 360 degree . The accuracy is about 0.1 degree 
3670
3671 \cvfunc{IsNaN}\label{IsNaN}
3672
3673 Determines if the argument is Not A Number
3674
3675 \cvexp{
3676
3677 int cvIsNaN( double value );
3678
3679 }{CPP}{PYTHON}
3680
3681 \begin{description}
3682 \cvarg{value}{The input floating-point value}
3683 \end{description}
3684
3685
3686 The function \texttt{cvIsNaN} returns 1 if the argument is Not A Number (as defined by IEEE754 standard), 0 otherwise.
3687
3688
3689 \cvfunc{IsInf}\label{IsInf}
3690
3691 Determines if the argument is Infinity
3692
3693 \cvexp{
3694
3695 int cvIsInf( double value );
3696
3697 }{CPP}{PYTHON}
3698
3699 \begin{description}
3700 \cvarg{value}{The input floating-point value}
3701 \end{description}
3702
3703
3704 The function \texttt{cvIsInf} returns 1 if the argument is $ \pm \infty $ (as defined by IEEE754 standard), 0 otherwise.
3705
3706
3707 \cvfunc{CartToPolar}\label{CartToPolar}
3708
3709 Calculates magnitude and/or angle of 2d vectors
3710
3711 \cvexp{
3712
3713 void cvCartToPolar( \par const CvArr* x,\par const CvArr* y,\par CvArr* magnitude,\par CvArr* angle=NULL,\par int angle\_in\_degrees=0 );
3714
3715 }{CPP}{PYTHON}
3716
3717 \begin{description}
3718 \cvarg{x}{The array of x-coordinates}
3719 \cvarg{y}{The array of y-coordinates}
3720 \cvarg{magnitude}{The destination array of magnitudes, may be set to NULL if it is not needed}
3721 \cvarg{angle}{The destination array of angles, may be set to NULL if it is not needed. The angles are measured in radians $(0..2 \pi )$ or in degrees (0..360 degree).}
3722 \cvarg{angle\_in\_degrees}{The flag indicating whether the angles are measured in radians, which is default mode, or in degrees}
3723 \end{description}
3724
3725 The function \texttt{cvCartToPolar} calculates either magnitude, angle, or both of every 2d vector (x(I),y(I)):
3726
3727 \begin{lstlisting}
3728
3729 magnitude(I)=sqrt( x(I)^2^+y(I)^2^ ),
3730 angle(I)=atan( y(I)/x(I) )
3731
3732 \end{lstlisting}
3733
3734 The angles are calculated with 0.1 degree accuracy. For (0,0) point the angle is set to 0.
3735
3736 \cvfunc{PolarToCart}\label{PolarToCart}
3737
3738 Calculates cartesian coordinates of 2d vectors represented in polar form
3739
3740 \cvexp{
3741
3742 void cvPolarToCart( \par const CvArr* magnitude,\par const CvArr* angle,\par CvArr* x,\par CvArr* y,\par int angle\_in\_degrees=0 );
3743
3744 }{CPP}{PYTHON}
3745
3746 \begin{description}
3747 \cvarg{magnitude}{The array of magnitudes. If it is NULL, the magnitudes are assumed all 1's.}
3748 \cvarg{angle}{The array of angles, whether in radians or degrees}
3749 \cvarg{x}{The destination array of x-coordinates, may be set to NULL if it is not needed}
3750 \cvarg{y}{The destination array of y-coordinates, mau be set to NULL if it is not needed}
3751 \cvarg{angle\_in\_degrees}{The flag indicating whether the angles are measured in radians, which is default mode, or in degrees}
3752 \end{description}
3753
3754 The function \texttt{cvPolarToCart} calculates either x-coodinate, y-coordinate or both of every vector 'magnitude(I)*exp(angle(I)*j), j=sqrt(-1)':
3755
3756 \begin{lstlisting}
3757
3758 x(I)=magnitude(I)*cos(angle(I)),
3759 y(I)=magnitude(I)*sin(angle(I))
3760
3761 \end{lstlisting}
3762
3763
3764 \cvfunc{Pow}\label{Pow}
3765
3766 Raises every array element to power
3767
3768 \cvexp{
3769
3770 void cvPow( \par const CvArr* src,\par CvArr* dst,\par double power );
3771
3772 }{CPP}{PYTHON}
3773
3774 \begin{description}
3775 \cvarg{src}{The source array}
3776 \cvarg{dst}{The destination array, should be the same type as the source}
3777 \cvarg{power}{The exponent of power}
3778 \end{description}
3779
3780
3781 The function \texttt{cvPow} raises every element of input array to \texttt{p}:
3782
3783 \[
3784 \texttt{dst} [I] = \fork
3785 {\texttt{src}(I)^p}{if \texttt{p} is integer}
3786 {|\texttt{src}(I)^p|}{otherwise}
3787 \]
3788
3789 That is, for non-integer power exponent the absolute values of input array elements are used. However, it is possible to get true values for negative values using some extra operations, as the following sample, computing cube root of array elements, shows:
3790
3791 \begin{lstlisting}
3792
3793 CvSize size = cvGetSize(src);
3794 CvMat* mask = cvCreateMat( size.height, size.width, CVg8UC1 );
3795 cvCmpS( src, 0, mask, CVgCMPgLT ); /* find negative elements */
3796 cvPow( src, dst, 1./3 );
3797 cvSubRS( dst, cvScalarAll(0), dst, mask ); /* negate the results of negative inputs */
3798 cvReleaseMat( &mask );
3799
3800 \end{lstlisting}
3801
3802 For some values of \texttt{power}, such as integer values, 0.5 and -0.5, specialized faster algorithms are used.
3803
3804 \cvfunc{Exp}\label{Exp}
3805
3806 Calculates exponent of every array element
3807
3808 \cvexp{
3809
3810 void cvExp( const CvArr* src, CvArr* dst );
3811
3812 }{CPP}{PYTHON}
3813
3814 \begin{description}
3815 \cvarg{src}{The source array}
3816 \cvarg{dst}{The destination array, it should have \texttt{double} type or the same type as the source}
3817 \end{description}
3818
3819
3820 The function \texttt{cvExp} calculates exponent of every element of input array:
3821
3822 \[
3823 \texttt{dst} [I] = e^{\texttt{src}(I)}
3824 \]
3825
3826 Maximum relative error is about $7 \times 10^{-6}$. Currently, the function converts denormalized values to zeros on output.
3827
3828 \cvfunc{Log}\label{Log}
3829
3830 Calculates natural logarithm of every array element absolute value
3831
3832 \cvexp{
3833
3834 void cvLog( const CvArr* src, CvArr* dst );
3835
3836 }{CPP}{PYTHON}
3837
3838 \begin{description}
3839 \cvarg{src}{The source array}
3840 \cvarg{dst}{The destination array, it should have \texttt{double} type or the same type as the source}
3841 \end{description}
3842
3843 The function \texttt{cvLog} calculates natural logarithm of absolute value of every element of input array:
3844
3845 \[
3846 \texttt{dst} [I] = \fork
3847 {\log{|\texttt{src}(I)}}{if $\texttt{src}[I] \ne 0$ }
3848 {\texttt{C}}{otherwise}
3849 \]
3850
3851 Where \texttt{C} is large negative number ( about -700 in the current implementation).
3852
3853 \cvfunc{SolveCubic}\label{SolveCubic}
3854
3855 Finds real roots of a cubic equation
3856
3857 \cvexp{
3858
3859 void cvSolveCubic( const CvArr* coeffs, CvArr* roots );
3860
3861 }{CPP}{PYTHON}
3862
3863 \begin{description}
3864 \cvarg{coeffs}{The equation coefficients, array of 3 or 4 elements}
3865 \cvarg{roots}{The output array of real roots. Should have 3 elements.}
3866 \end{description}
3867
3868 The function \texttt{cvSolveCubic} finds real roots of a cubic equation:
3869
3870 if coeffs is 4-element vector:
3871
3872 \[
3873 \texttt{coeffs}[0] x^3 + \texttt{coeffs}[1] x^2 + \texttt{coeffs}[2] x + \texttt{coeffs}[3] = 0
3874 \]
3875
3876 or if coeffs is 3-element vector:
3877
3878 \[
3879 x^3 + \texttt{coeffs}[0] x^2 + \texttt{coeffs}[1] x + \texttt{coeffs}[2] = 0
3880 \]
3881
3882 The function returns the number of real roots found. The roots are
3883 stored to \texttt{root} array, which is padded with zeros if there is
3884 only one root.
3885
3886 \subsection{Random Number Generation}
3887
3888 \cvfunc{RNG}\label{RNG}
3889
3890 Initializes random number generator state
3891
3892 \cvexp{
3893
3894 CvRNG cvRNG( int64 seed=-1 );
3895
3896 }{CPP}{PYTHON}
3897
3898 \begin{description}
3899 \cvarg{seed}{64-bit value used to initiate a random sequence}
3900 \end{description}
3901
3902
3903 The function \texttt{cvRNG} initializes random number generator
3904 and returns the state. Pointer to the state can be then passed to
3905 \cross{RandInt}, \cross{RandReal} and \cross{RandArr} functions. In the
3906 current implementation a multiply-with-carry generator is used.
3907
3908 \cvfunc{RandArr}\label{RandArr}
3909
3910 Fills array with random numbers and updates the RNG state
3911
3912 \cvexp{
3913
3914 void cvRandArr( \par CvRNG* rng,\par CvArr* arr,\par int dist\_type,\par CvScalar param1,\par CvScalar param2 );
3915
3916 }{CPP}{PYTHON}
3917
3918 \begin{description}
3919 \cvarg{rng}{RNG state initialized by \cross{RNG}}
3920 \cvarg{arr}{The destination array}
3921 \cvarg{dist\_type}{Distribution type
3922 \begin{description}
3923 \cvarg{CV\_RAND\_UNI}{uniform distribution}
3924 \cvarg{CV\_RAND\_NORMAL}{normal or Gaussian distribution}
3925 \end{description}}
3926 \cvarg{param1}{The first parameter of distribution . In case of uniform distribution it is the inclusive lower boundary of random numbers range. In case of normal distribution it is the mean value of random numbers.}
3927 \cvarg{param2}{The second parameter of distribution. In case of uniform distribution it is the exclusive upper boundary of random numbers range. In case of normal distribution it is the standard deviation of random numbers.}
3928 \end{description}
3929
3930 The function \texttt{cvRandArr} fills the destination array with uniformly
3931 or normally distributed random numbers. In the sample below the function
3932 is used to add a few normally distributed floating-point numbers to
3933 random locations within a 2d array
3934
3935 \begin{lstlisting}
3936
3937 /* let noisy\_screen be the floating-point 2d array that is to be "crapped" */
3938 CvRNG rng\_state = cvRNG(0xffffffff);
3939 int i, pointCount = 1000;
3940 /* allocate the array of coordinates of points */
3941 CvMat* locations = cvCreateMat( pointCount, 1, CV\_32SC2 );
3942 /* arr of random point values */
3943 CvMat* values = cvCreateMat( pointCount, 1, CV\_32FC1 );
3944 CvSize size = cvGetSize( noisy\_screen );
3945
3946 cvRandInit( &rng\_state,
3947             0, 1, /* use dummy parameters now and adjust them further */
3948             0xffffffff /* just use a fixed seed here */,
3949             CV\_RAND\_UNI /* specify uniform type */ );
3950
3951 /* initialize the locations */
3952 cvRandArr( &rng\_state, locations, CV\_RAND\_UNI, cvScalar(0,0,0,0), cvScalar(size.width,size.height,0,0) );
3953
3954 /* modify RNG to make it produce normally distributed values */
3955 rng\_state.disttype = CV\_RAND\_NORMAL;
3956 cvRandSetRange( &rng\_state,
3957                 30 /* deviation */,
3958                 100 /* average point brightness */,
3959                 -1 /* initialize all the dimensions */ );
3960 /* generate values */
3961 cvRandArr( &rng\_state, values, CV\_RAND\_NORMAL,
3962            cvRealScalar(100), // average intensity
3963            cvRealScalar(30) // deviation of the intensity
3964            );
3965
3966 /* set the points */
3967 for( i = 0; i < pointCount; i++ )
3968 {
3969     CvPoint pt = *(CvPoint*)cvPtr1D( locations, i, 0 );
3970     float value = *(float*)cvPtr1D( values, i, 0 );
3971     *((float*)cvPtr2D( noisy\_screen, pt.y, pt.x, 0 )) += value;
3972 }
3973
3974 /* not to forget to release the temporary arrays */
3975 cvReleaseMat( &locations );
3976 cvReleaseMat( &values );
3977
3978 /* RNG state does not need to be deallocated */
3979
3980 \end{lstlisting}
3981
3982 \cvfunc{RandInt}\label{RandInt}
3983
3984 Returns 32-bit unsigned integer and updates RNG
3985
3986 \cvexp{
3987
3988 unsigned cvRandInt( CvRNG* rng );
3989
3990 }{CPP}{PYTHON}
3991
3992 \begin{description}
3993 \cvarg{rng}{RNG state initialized by \texttt{RandInit} and, optionally, customized by \texttt{RandSetRange} (though, the latter function does not affect on the discussed function outcome)}
3994 \end{description}
3995
3996 The function \texttt{cvRandInt} returns uniformly-distributed random
3997 32-bit unsigned integer and updates RNG state. It is similar to rand()
3998 function from C runtime library, but it always generates 32-bit number
3999 whereas rand() returns a number in between 0 and \texttt{RAND\_MAX}
4000 which is $2^{16}$ or $2^{32}$, depending on the platform.
4001
4002 The function is useful for generating scalar random numbers, such as
4003 points, patch sizes, table indices etc, where integer numbers of a certain
4004 range can be generated using modulo operation and floating-point numbers
4005 can be generated by scaling to 0..1 of any other specific range. Here
4006 is the example from the previous function discussion rewritten using
4007 \cross{RandInt}:
4008
4009 \begin{lstlisting}
4010
4011 /* the input and the task is the same as in the previous sample. */
4012 CvRNG rnggstate = cvRNG(0xffffffff);
4013 int i, pointCount = 1000;
4014 /* ... - no arrays are allocated here */
4015 CvSize size = cvGetSize( noisygscreen );
4016 /* make a buffer for normally distributed numbers to reduce call overhead */
4017 #define bufferSize 16
4018 float normalValueBuffer[bufferSize];
4019 CvMat normalValueMat = cvMat( bufferSize, 1, CVg32F, normalValueBuffer );
4020 int valuesLeft = 0;
4021
4022 for( i = 0; i < pointCount; i++ )
4023 {
4024     CvPoint pt;
4025     /* generate random point */
4026     pt.x = cvRandInt( &rnggstate ) % size.width;
4027     pt.y = cvRandInt( &rnggstate ) % size.height;
4028
4029     if( valuesLeft <= 0 )
4030     {
4031         /* fulfill the buffer with normally distributed numbers if the buffer is empty */
4032         cvRandArr( &rnggstate, &normalValueMat, CV\_RAND\_NORMAL, cvRealScalar(100), cvRealScalar(30) );
4033         valuesLeft = bufferSize;
4034     }
4035     *((float*)cvPtr2D( noisygscreen, pt.y, pt.x, 0 ) = normalValueBuffer[--valuesLeft];
4036 }
4037
4038 /* there is no need to deallocate normalValueMat because we have
4039 both the matrix header and the data on stack. It is a common and efficient
4040 practice of working with small, fixed-size matrices */
4041
4042 \end{lstlisting}
4043
4044 \cvfunc{RandReal}\label{RandReal}
4045
4046 Returns floating-point random number and updates RNG
4047
4048 \cvexp{
4049
4050 double cvRandReal( CvRNG* rng );
4051
4052 }{CPP}{PYTHON}
4053
4054 \begin{description}
4055 \cvarg{rng}{RNG state initialized by \cross{RNG}}
4056 \end{description}
4057
4058
4059 The function \texttt{cvRandReal} returns uniformly-distributed random floating-point number from 0..1 range (1 is not included).
4060
4061 \subsection{Discrete Transforms}
4062
4063 \cvfunc{DFT}\label{DFT}
4064
4065 Performs forward or inverse Discrete Fourier transform of 1D or 2D floating-point array
4066
4067 \cvexp{
4068
4069 void cvDFT( const CvArr* src, CvArr* dst, int flags, int nonzero\_rows=0 );
4070
4071 }{CPP}{PYTHON}
4072
4073 \begin{lstlisting}
4074
4075 #define CV\_DXT\_FORWARD  0
4076 #define CV\_DXT\_INVERSE  1
4077 #define CV\_DXT\_SCALE    2
4078 #define CV\_DXT\_ROWS     4
4079 #define CV\_DXT\_INV\_SCALE (CV\_DXT\_SCALE|CV\_DXT\_INVERSE)
4080 #define CV\_DXT\_INVERSE\_SCALE CV\_DXT\_INV\_SCALE
4081
4082 \end{lstlisting}
4083
4084 \begin{description}
4085 \cvarg{src}{Source array, real or complex}
4086 \cvarg{dst}{Destination array of the same size and same type as the source}
4087 \cvarg{flags}{Transformation flags, a combination of the following values
4088 \begin{description}
4089 \cvarg{CV\_DXT\_FORWARD} - do forward 1D or 2D transform. The result is not scaled.
4090 \cvarg{CV\_DXT\_INVERSE} - do inverse 1D or 2D transform. The result is not scaled. \texttt{CV\_DXT\_FORWARD} and \texttt{CV\_DXT\_INVERSE} are mutually exclusive, of course.
4091 \cvarg{CV\_DXT\_SCALE} - scale the result: divide it by the number of array elements. Usually, it is combined with \texttt{CV\_DXT\_INVERSE}, and one may use a shortcut \texttt{CV\_DXT\_INV\_SCALE}.
4092 \cvarg{CV\_DXT\_ROWS} - do forward or inverse transform of every individual row of the input matrix. This flag allows user to transform multiple vectors simultaneously and can be used to decrease the overhead (which is sometimes several times larger than the processing itself), to do 3D and higher-dimensional transforms etc.
4093 \end{description}}
4094 \cvarg{nonzero\_rows}{Number of nonzero rows to in the source array
4095 (in case of forward 2d transform), or a number of rows of interest in
4096 the destination array (in case of inverse 2d transform). If the value
4097 is negative, zero, or greater than the total number of rows, it is
4098 ignored. The parameter can be used to speed up 2d convolution/correlation
4099 when computing them via DFT. See the sample below.}
4100 \end{description}
4101
4102 The function \texttt{cvDFT} performs forward or inverse transform of 1D or 2D floating-point array:
4103
4104 \begin{lstlisting}
4105
4106 Forward Fourier transform of 1D vector of N elements:
4107 y = F^(N)^ \cdot x, where F^(N)^,,jk,,=exp(-i \cdot 2Pi \cdot j \cdot k/N), i=sqrt(-1)
4108
4109 Inverse Fourier transform of 1D vector of N elements:
4110 x'= (F^(N)^)^-1^ \cdot y = conj(F^(N)^) \cdot y
4111 x = (1/N) \cdot x
4112
4113 Forward Fourier transform of 2D vector of M \times N elements:
4114 Y = F^(M)^ \cdot X \cdot F^(N)^
4115
4116 Inverse Fourier transform of 2D vector of M \times N elements:
4117 X'= conj(F^(M)^) \cdot Y \cdot conj(F^(N)^)
4118 X = (1/(M \cdot N)) \cdot X'
4119
4120 \end{lstlisting}
4121
4122 In case of real (single-channel) data, the packed format, borrowed from IPL, is used to to represent a result of forward Fourier transform or input for inverse Fourier transform:
4123
4124 \begin{lstlisting}
4125
4126 Re Y,,0,0,,      Re Y,,0,1,,    Im Y,,0,1,,    Re Y,,0,2,,     Im Y,,0,2,,  ...  Re Y,,0,N/2-1,,   Im Y,,0,N/2-1,,  Re Y,,0,N/2,,
4127 Re Y,,1,0,,      Re Y,,1,1,,    Im Y,,1,1,,    Re Y,,1,2,,     Im Y,,1,2,,  ...  Re Y,,1,N/2-1,,   Im Y,,1,N/2-1,,  Re Y,,1,N/2,,
4128 Im Y,,1,0,,      Re Y,,2,1,,    Im Y,,2,1,,    Re Y,,2,2,,     Im Y,,2,2,,  ...  Re Y,,2,N/2-1,,   Im Y,,2,N/2-1,,  Im Y,,2,N/2,,
4129 ............................................................................................
4130 Re Y,,M/2-1,0,,   Re Y,,M-3,1,,   Im Y,,M-3,1,,  Re Y,,M-3,2,,   Im Y,,M-3,2,, ...  Re Y,,M-3,N/2-1,,  Im Y,,M-3,N/2-1,, Re Y,,M-3,N/2,,
4131 Im Y,,M/2-1,0,,   Re Y,,M-2,1,,   Im Y,,M-2,1,,  Re Y,,M-2,2,,   Im Y,,M-2,2,, ...  Re Y,,M-2,N/2-1,,  Im Y,,M-2,N/2-1,, Im Y,,M-2,N/2,,
4132 Re Y,,M/2,0,,    Re Y,,M-1,1,,   Im Y,,M-1,1,,  Re Y,,M-1,2,,   Im Y,,M-1,2,,  ... Re Y,,M-1,N/2-1,,  Im Y,,M-1,N/2-1,, Im Y,,M-1,N/2,,
4133
4134 \end{lstlisting}
4135
4136 Note: the last column is present if \texttt{N} is even, the last row is present if \texttt{M} is even.
4137
4138 In case of 1D real transform the result looks like the first row of the above matrix
4139
4140 Computing 2D Convolution using DFT
4141
4142 \begin{lstlisting}
4143
4144 CvMat* A = cvCreateMat( M1, N1, CVg32F );
4145 CvMat* B = cvCreateMat( M2, N2, A->type );
4146
4147 // it is also possible to have only abs(M2-M1)+1 \times abs(N2-N1)+1
4148 // part of the full convolution result
4149 CvMat* conv = cvCreateMat( A->rows + B->rows - 1, A->cols + B->cols - 1, A->type );
4150
4151 // initialize A and B
4152 ...
4153
4154 int dftgM = cvGetOptimalDFTSize( A->rows + B->rows - 1 );
4155 int dftgN = cvGetOptimalDFTSize( A->cols + B->cols - 1 );
4156
4157 CvMat* dftgA = cvCreateMat( dft\_M, dft\_N, A->type );
4158 CvMat* dftgB = cvCreateMat( dft\_M, dft\_N, B->type );
4159 CvMat tmp;
4160
4161 // copy A to dftgA and pad dft\_A with zeros
4162 cvGetSubRect( dftgA, &tmp, cvRect(0,0,A->cols,A->rows));
4163 cvCopy( A, &tmp );
4164 cvGetSubRect( dftgA, &tmp, cvRect(A->cols,0,dft\_A->cols - A->cols,A->rows));
4165 cvZero( &tmp );
4166 // no need to pad bottom part of dftgA with zeros because of
4167 // use nonzerogrows parameter in cvDFT() call below
4168
4169 cvDFT( dftgA, dft\_A, CV\_DXT\_FORWARD, A->rows );
4170
4171 // repeat the same with the second array
4172 cvGetSubRect( dftgB, &tmp, cvRect(0,0,B->cols,B->rows));
4173 cvCopy( B, &tmp );
4174 cvGetSubRect( dftgB, &tmp, cvRect(B->cols,0,dft\_B->cols - B->cols,B->rows));
4175 cvZero( &tmp );
4176 // no need to pad bottom part of dftgB with zeros because of
4177 // use nonzerogrows parameter in cvDFT() call below
4178
4179 cvDFT( dftgB, dft\_B, CV\_DXT\_FORWARD, B->rows );
4180
4181 cvMulSpectrums( dftgA, dft\_B, dft\_A, 0 /* or CV\_DXT\_MUL\_CONJ to get correlation
4182                                           rather than convolution */ );
4183
4184 cvDFT( dftgA, dft\_A, CV\_DXT\_INV\_SCALE, conv->rows ); // calculate only the top part
4185 cvGetSubRect( dftgA, &tmp, cvRect(0,0,conv->cols,conv->rows) );
4186
4187 cvCopy( &tmp, conv );
4188
4189 \end{lstlisting}
4190
4191 \cvfunc{GetOptimalDFTSize}\label{GetOptimalDFTSize}
4192
4193 Returns optimal DFT size for given vector size
4194
4195 \cvexp{
4196
4197 int cvGetOptimalDFTSize( int size0 );
4198
4199 }{CPP}{PYTHON}
4200
4201 \begin{description}
4202 \cvarg{size0}{Vector size}
4203 \end{description}
4204
4205
4206 The function \texttt{cvGetOptimalDFTSize} returns the minimum number
4207 \texttt{N} that is greater to equal to \texttt{size0}, such that DFT
4208 of a vector of size \texttt{N} can be computed fast. In the current
4209 implementation $N=2^p \times 3^q \times 5^r$' for some $p$, $q$, $r$.
4210
4211 The function returns a negative number if \texttt{size0} is too large
4212 (very close to \texttt{INT\_MAX})
4213
4214
4215 \cvfunc{MulSpectrums}\label{MulSpectrums}
4216
4217 Performs per-element multiplication of two Fourier spectrums
4218
4219 \cvexp{
4220
4221 void cvMulSpectrums( \par const CvArr* src1,\par const CvArr* src2,\par CvArr* dst,\par int flags );
4222
4223 }{CPP}{PYTHON}
4224
4225 \begin{description}
4226 \cvarg{src1}{The first source array}
4227 \cvarg{src2}{The second source array}
4228 \cvarg{dst}{The destination array of the same type and the same size of the sources}
4229 \cvarg{flags}{A combination of the following values
4230 \begin{description}
4231 \cvarg{CV\_DXT\_ROWS}{treat each row of the arrays as a separate spectrum (see \cross{DFT} parameters description).}
4232 \cvarg{CV\_DXT\_MUL\_CONJ}{conjugate the second source array before the multiplication.}
4233 \end{description}}
4234
4235 \end{description}
4236
4237 The function \texttt{cvMulSpectrums} performs per-element multiplication of the two CCS-packed or complex matrices that are results of real or complex Fourier transform.
4238
4239 The function, together with \cross{DFT}, may be used to calculate convolution of two arrays fast.
4240
4241
4242 \cvfunc{DCT}\label{DCT}
4243
4244 Performs forward or inverse Discrete Cosine transform of 1D or 2D floating-point array
4245
4246 \cvexp{
4247
4248 void cvDCT( const CvArr* src, CvArr* dst, int flags );
4249
4250 }{CPP}{PYTHON}
4251
4252 \begin{lstlisting}
4253
4254 #define CV\_DXT\_FORWARD  0
4255 #define CV\_DXT\_INVERSE  1
4256 #define CV\_DXT\_ROWS     4
4257
4258 \end{lstlisting}
4259
4260 \begin{description}
4261 \cvarg{src}{Source array, real 1D or 2D array}
4262 \cvarg{dst}{Destination array of the same size and same type as the source}
4263 \cvarg{flags}{Transformation flags, a combination of the following values
4264 \begin{description}
4265 \cvarg{CV\_DXT\_FORWARD}{do forward 1D or 2D transform.}
4266 \cvarg{CV\_DXT\_INVERSE}{do inverse 1D or 2D transform.}
4267 \cvarg{CV\_DXT\_ROWS}{do forward or inverse transform of every individual row of the input matrix. This flag allows user to transform multiple vectors simultaneously and can be used to decrease the overhead (which is sometimes several times larger than the processing itself), to do 3D and higher-dimensional transforms etc.}
4268 \end{description}}
4269 \end{description}
4270
4271 The function \texttt{cvDCT} performs forward or inverse transform of 1D or 2D floating-point array:
4272
4273 \begin{lstlisting}
4274
4275 Forward Cosine transform of 1D vector of N elements:
4276 y = C^(N)^ \cdot x, where C^(N)^,,jk,,=sqrt((j==0?1:2)/N) \cdot cos(Pi \cdot (2k+1) \cdot j/N)
4277
4278 Inverse Cosine transform of 1D vector of N elements:
4279 x = (C^(N)^)^-1^ \cdot y = (C^(N)^)^T^ \cdot y
4280
4281 Forward Cosine transform of 2D vector of M \times N elements:
4282 Y = (C^(M)^) \cdot X \cdot (C^(N)^)^T^
4283
4284 Inverse Cosine transform of 2D vector of M \times N elements:
4285 X = (C^(M)^)^T^ \cdot Y \cdot C^(N)^
4286
4287 \end{lstlisting}
4288
4289
4290 \section{Dynamic Structures}
4291
4292 \subsection{Memory Storages}
4293
4294 \cvstruct{CvMemStorage}\label{CvMemStorage}
4295
4296 Growing memory storage
4297
4298 \begin{lstlisting}
4299
4300 typedef struct CvMemStorage
4301 {
4302     struct CvMemBlock* bottom;/* first allocated block */
4303     struct CvMemBlock* top; /* the current memory block - top of the stack */
4304     struct CvMemStorage* parent; /* borrows new blocks from */
4305     int block\_size; /* block size */
4306     int free\_space; /* free space in the \texttt{top} block (in bytes) */
4307 } CvMemStorage;
4308
4309 \end{lstlisting}
4310
4311 Memory storage is a low-level structure used to store dynamically growing
4312 data structures such as sequences, contours, graphs, subdivisions etc. It
4313 is organized as a list of memory blocks of equal size - \texttt{bottom}
4314 field is the beginning of the list of blocks and \texttt{top} is the
4315 currently used block, but not necessarily the last block of the list. All
4316 blocks between \texttt{bottom} and \texttt{top}, not including the
4317 latter, are considered fully ocupied; and all blocks between \texttt{top}
4318 and the last block, not including \texttt{top}, are considered free
4319 and \texttt{top} block itself is partly ocupied - \texttt{free\_space}
4320 contains the number of free bytes left in the end of \texttt{top}.
4321
4322 New memory buffer that may be allocated explicitly by
4323 \cross{MemStorageAlloc} function or implicitly by higher-level functions,
4324 such as \cross{SeqPush}, \cross{GraphAddEdge} etc., \texttt{always}
4325 starts in the end of the current block if it fits there. After allocation
4326 \texttt{free\_space} is decremented by the size of the allocated buffer
4327 plus some padding to keep the proper alignment. When the allocated buffer
4328 does not fit into the available part of \texttt{top}, the next storage
4329 block from the list is taken as \texttt{top} and \texttt{free\_space}
4330 is reset to the whole block size prior to the allocation.
4331
4332 If there is no more free blocks, a new block is allocated (or borrowed
4333 from parent, see \cross{CreateChildMemStorage}) and added to the end of
4334 list. Thus, the storage behaves as a stack with \texttt{bottom} indicating
4335 bottom of the stack and the pair (\texttt{top}, \texttt{free\_space})
4336 indicating top of the stack. The stack top may be saved via
4337 \cross{SaveMemStoragePos}, restored via \cross{RestoreMemStoragePos}
4338 or reset via \cross{ClearStorage}.
4339
4340 \cvstruct{CvMemBlock}\label{CvMemBlock}
4341
4342 Memory storage block
4343
4344 \begin{lstlisting}
4345
4346 typedef struct CvMemBlock
4347 {
4348     struct CvMemBlock* prev;
4349     struct CvMemBlock* next;
4350 } CvMemBlock;
4351
4352 \end{lstlisting}
4353
4354 The structure \cross{CvMemBlock} represents a single block of memory
4355 storage. Actual data of the memory blocks follows the header, that is,
4356 the $i_{th}$ byte of the memory block can be retrieved with the expression
4357 \texttt{((char*)(mem\_block\_ptr+1))[i]}. However, normally there is no need
4358 to access the storage structure fields directly.
4359
4360 \cvstruct{CvMemStoragePos}\label{CvMemStoragePos}
4361
4362 Memory storage position
4363
4364 \begin{lstlisting}
4365
4366 typedef struct CvMemStoragePos
4367 {
4368     CvMemBlock* top;
4369     int free\_space;
4370 } CvMemStoragePos;
4371
4372 \end{lstlisting}
4373
4374 The structure described below stores the position of the stack top that can be saved via \cross{SaveMemStoragePos} and restored via \cross{RestoreMemStoragePos}.
4375
4376 \cvfunc{CreateMemStorage}\label{CreateMemStorage}
4377
4378 Creates memory storage
4379
4380 \cvexp{
4381
4382 CvMemStorage* cvCreateMemStorage( int block\_size=0 );
4383
4384 }{CPP}{PYTHON}
4385
4386 \begin{description}
4387 \cvarg{block\_size}{Size of the storage blocks in bytes. If it is 0, the block size is set to default value - currently it is  about 64K.}
4388 \end{description}
4389
4390 The function \texttt{cvCreateMemStorage} creates a memory storage and returns pointer to it. Initially the storage is empty. All fields of the header, except the \texttt{block\_size}, are set to 0.
4391
4392
4393 \cvfunc{CreateChildMemStorage}\label{CreateChildMemStorage}
4394
4395 Creates child memory storage
4396
4397 \cvexp{
4398
4399 CvMemStorage* cvCreateChildMemStorage( CvMemStorage* parent );
4400
4401 }{CPP}{PYTHON}
4402
4403 \begin{description}
4404 \cvarg{parent}{Parent memory storage}
4405 \end{description}
4406
4407
4408 The function \texttt{cvCreateChildMemStorage} creates a child memory
4409 storage that is similar to simple memory storage except for the
4410 differences in the memory allocation/deallocation mechanism. When a
4411 child storage needs a new block to add to the block list, it tries
4412 to get this block from the parent. The first unoccupied parent block
4413 available is taken and excluded from the parent block list. If no blocks
4414 are available, the parent either allocates a block or borrows one from
4415 its own parent, if any. In other words, the chain, or a more complex
4416 structure, of memory storages where every storage is a child/parent of
4417 another is possible. When a child storage is released or even cleared,
4418 it returns all blocks to the parent. In other aspects, the child storage
4419 is the same as the simple storage.
4420
4421 The children storages are useful in the following situation. Imagine
4422 that user needs to process dynamical data resided in some storage and
4423 put the result back to the same storage. With the simplest approach,
4424 when temporary data is resided in the same storage as the input and
4425 output data, the storage will look as following after processing:
4426
4427 Dynamic data processing without using child storage
4428
4429 \includegraphics[width=0.5\textwidth]{pics/memstorage1.png}
4430
4431 That is, garbage appears in the middle of the storage. However, if
4432 one creates a child memory storage in the beginning of the processing,
4433 writes temporary data there and releases the child storage in the end,
4434 no garbage will appear in the source/destination storage:
4435
4436 Dynamic data processing using a child storage
4437
4438 \includegraphics[width=0.5\textwidth]{pics/memstorage2.png}
4439
4440 \cvfunc{ReleaseMemStorage}\label{ReleaseMemStorage}
4441
4442 Releases memory storage
4443
4444 \cvexp{
4445
4446 void cvReleaseMemStorage( CvMemStorage** storage );
4447
4448 }{CPP}{PYTHON}
4449
4450 \begin{description}
4451 \cvarg{storage}{Pointer to the released storage}
4452 \end{description}
4453
4454 The function \texttt{cvReleaseMemStorage} deallocates all storage memory
4455 blocks or returns them to the parent, if any. Then it deallocates the
4456 storage header and clears the pointer to the storage. All children of
4457 the storage must be released before the parent is released.
4458
4459 \cvfunc{ClearMemStorage}\label{ClearMemStorage}
4460
4461 Clears memory storage
4462
4463 \cvexp{
4464
4465 void cvClearMemStorage( CvMemStorage* storage );
4466
4467 }{CPP}{PYTHON}
4468
4469 \begin{description}
4470 \cvarg{storage}{Memory storage}
4471 \end{description}
4472
4473 The function \texttt{cvClearMemStorage} resets the top (free space
4474 boundary) of the storage to the very beginning. This function does not
4475 deallocate any memory. If the storage has a parent, the function returns
4476 all blocks to the parent.
4477
4478 \cvfunc{MemStorageAlloc}\label{MemStorageAlloc}
4479
4480 Allocates memory buffer in the storage
4481
4482 \cvexp{
4483
4484 void* cvMemStorageAlloc( \par CvMemStorage* storage,\par size\_t size );
4485
4486 }{CPP}{PYTHON}
4487
4488 \begin{description}
4489 \cvarg{storage}{Memory storage}
4490 \cvarg{size}{Buffer size}
4491 \end{description}
4492
4493 The function \texttt{cvMemStorageAlloc} allocates memory buffer in
4494 the storage. The buffer size must not exceed the storage block size,
4495 otherwise runtime error is raised. The buffer address is aligned by
4496 \texttt{CV\_STRUCT\_ALIGN=sizeof(double)} for the moment) bytes.
4497
4498 \cvfunc{MemStorageAllocString}\label{MemStorageAllocString}
4499
4500 Allocates text string in the storage
4501
4502 \cvexp{
4503
4504 CvString cvMemStorageAllocString( CvMemStorage* storage, const char* ptr, int len=-1 );
4505
4506 }{CPP}{PYTHON}
4507
4508 \begin{lstlisting}
4509
4510 typedef struct CvString
4511 {
4512     int len;
4513     char* ptr;
4514 }
4515 CvString;
4516
4517 \end{lstlisting}
4518
4519 \begin{description}
4520 \cvarg{storage}{Memory storage}
4521 \cvarg{ptr}{The string}
4522 \cvarg{len}{Length of the string (not counting the ending \texttt{NUL}) . If the parameter is negative, the function computes the length.}
4523 \end{description}
4524
4525 The function \texttt{cvMemStorageAllocString} creates copy of the string
4526 in the memory storage. It returns the structure that contains user-passed
4527 or computed length of the string and pointer to the copied string.
4528
4529 \cvfunc{SaveMemStoragePos}\label{SaveMemStoragePos}
4530
4531 Saves memory storage position
4532
4533 \cvexp{
4534
4535 void cvSaveMemStoragePos( \par const CvMemStorage* storage,\par CvMemStoragePos* pos );
4536
4537 }{CPP}{PYTHON}
4538
4539 \begin{description}
4540 \cvarg{storage}{Memory storage}
4541 \cvarg{pos}{The output position of the storage top}
4542 \end{description}
4543
4544 The function \texttt{cvSaveMemStoragePos} saves the current position
4545 of the storage top to the parameter \texttt{pos}. The function
4546 \texttt{cvRestoreMemStoragePos} can further retrieve this position.
4547
4548 \cvfunc{RestoreMemStoragePos}\label{RestoreMemStoragePos}
4549
4550 Restores memory storage position
4551
4552 \cvexp{
4553
4554 void cvRestoreMemStoragePos( \par CvMemStorage* storage,\par CvMemStoragePos* pos );
4555
4556 }{CPP}{PYTHON}
4557
4558 \begin{description}
4559 \cvarg{storage}{Memory storage}
4560 \cvarg{pos}{New storage top position}
4561 \end{description}
4562
4563 The function \texttt{cvRestoreMemStoragePos} restores the position of the storage top from the parameter \texttt{pos}. This function and The function \texttt{cvClearMemStorage} are the only methods to release memory occupied in memory blocks. Note again that there is no way to free memory in the middle of the occupied part of the storage.
4564
4565 \subsection{Sequences}
4566
4567 \cvstruct{CvSeq}\label{CvSeq}
4568
4569 Growable sequence of elements
4570
4571 \begin{lstlisting}
4572
4573 #define CVgSEQUENCE\_FIELDS() \
4574     int flags; /* micsellaneous flags */ \
4575     int headergsize; /* size of sequence header */ \
4576     struct CvSeq* hgprev; /* previous sequence */ \
4577     struct CvSeq* hgnext; /* next sequence */ \
4578     struct CvSeq* vgprev; /* 2nd previous sequence */ \
4579     struct CvSeq* vgnext; /* 2nd next sequence */ \
4580     int total; /* total number of elements */ \
4581     int elemgsize;/* size of sequence element in bytes */ \
4582     char* blockgmax;/* maximal bound of the last block */ \
4583     char* ptr; /* current write pointer */ \
4584     int deltagelems; /* how many elements allocated when the sequence grows (sequence granularity) */ \
4585     CvMemStorage* storage; /* where the seq is stored */ \
4586     CvSeqBlock* freegblocks; /* free blocks list */ \
4587     CvSeqBlock* first; /* pointer to the first sequence block */
4588
4589 typedef struct CvSeq
4590 {
4591     CVgSEQUENCE\_FIELDS()
4592 } CvSeq;
4593
4594 \end{lstlisting}
4595
4596 The structure \cross{CvSeq} is a base for all of OpenCV dynamic data structures.
4597
4598 Such an unusual definition via a helper macro simplifies the extension
4599 of the structure \cross{CvSeq} with additional parameters. To extend
4600 \cross{CvSeq} the user may define a new structure and put user-defined
4601 fields after all \cross{CvSeq} fields that are included via the macro
4602 \texttt{CV\_SEQUENCE\_FIELDS()}.
4603
4604 There are two types of sequences - dense and sparse. Base type for dense
4605 sequences is \cross{CvSeq} and such sequences are used to represent
4606 growable 1d arrays - vectors, stacks, queues, deques. They have no gaps
4607 in the middle - if an element is removed from the middle or inserted
4608 into the middle of the sequence the elements from the closer end are
4609 shifted. Sparse sequences have \cross{CvSet} base class and they are
4610 discussed later in more details. They are sequences of nodes each of
4611 those may be either occupied or free as indicated by the node flag. Such
4612 sequences are used for unordered data structures such as sets of elements,
4613 graphs, hash tables etc.
4614
4615 The field \texttt{header\_size} contains the actual size of the sequence
4616 header and should be greater or equal to \texttt{sizeof(CvSeq)}.
4617
4618 The fields
4619 \texttt{h\_prev}, \texttt{h\_next}, \texttt{v\_prev}, \texttt{v\_next}
4620 can be used to create hierarchical structures from separate sequences. The
4621 fields \texttt{h\_prev} and \texttt{h\_next} point to the previous and
4622 the next sequences on the same hierarchical level while the fields
4623 \texttt{v\_prev} and \texttt{v\_next} point to the previous and the
4624 next sequence in the vertical direction, that is, parent and its first
4625 child. But these are just names and the pointers can be used in a
4626 different way.
4627
4628 The field \texttt{first} points to the first sequence block, whose structure is described below.
4629
4630 The field \texttt{total} contains the actual number of dense sequence elements and number of allocated nodes in sparse sequence.
4631
4632 The field \texttt{flags}contain the particular dynamic type
4633 signature (\texttt{CV\_SEQ\_MAGIC\_VAL} for dense sequences and
4634 \texttt{CV\_SET\_MAGIC\_VAL} for sparse sequences) in the highest 16
4635 bits and miscellaneous information about the sequence. The lowest
4636 \texttt{CV\_SEQ\_ELTYPE\_BITS} bits contain the ID of the element
4637 type. Most of sequence processing functions do not use element type but
4638 element size stored in \texttt{elem\_size}. If sequence contains the
4639 numeric data of one of \cross{CvMat} type then the element type matches
4640 to the corresponding \cross{CvMat} element type, e.g. \texttt{CV\_32SC2} may be
4641 used for sequence of 2D points, \texttt{CV\_32FC1} for sequences of floating-point
4642 values etc. \texttt{CV\_SEQ\_ELTYPE(seq\_header\_ptr)} macro retrieves the
4643 type of sequence elements. Processing function that work with numerical
4644 sequences check that \texttt{elem\_size} is equal to the calculated from
4645 the type element size. Besides \cross{CvMat} compatible types, there
4646 are few extra element types defined in \texttt{cvtypes.h} header:
4647
4648 Standard Types of Sequence Elements
4649
4650 \begin{lstlisting}
4651
4652 #define CV_SEQ_ELTYPE_POINT          CV_32SC2  /* (x,y) */
4653 #define CV_SEQ_ELTYPE_CODE           CV_8UC1   /* freeman code: 0..7 */
4654 #define CV_SEQ_ELTYPE_GENERIC        0 /* unspecified type of sequence elements */
4655 #define CV_SEQ_ELTYPE_PTR            CV_USRTYPE1 /* =6 */
4656 #define CV_SEQ_ELTYPE_PPOINT         CV_SEQ_ELTYPE_PTR  /* &elem: pointer to element of other sequence */
4657 #define CV_SEQ_ELTYPE_INDEX          CV_32SC1  /* #elem: index of element of some other sequence */
4658 #define CV_SEQ_ELTYPE_GRAPH_EDGE     CV_SEQ_ELTYPE_GENERIC  /* &next_o, &next_d, &vtx_o, &vtx_d */
4659 #define CV_SEQ_ELTYPE_GRAPH_VERTEX   CV_SEQ_ELTYPE_GENERIC  /* first_edge, &(x,y) */
4660 #define CV_SEQ_ELTYPE_TRIAN_ATR      CV_SEQ_ELTYPE_GENERIC  /* vertex of the binary tree   */
4661 #define CV_SEQ_ELTYPE_CONNECTED_COMP CV_SEQ_ELTYPE_GENERIC  /* connected component  */
4662 #define CV_SEQ_ELTYPE_POINT3D        CV_32FC3  /* (x,y,z)  */
4663
4664 \end{lstlisting}
4665
4666 The next \texttt{CV\_SEQ\_KIND\_BITS} bits specify the kind of the sequence:
4667
4668 Standard Kinds of Sequences
4669
4670 \begin{lstlisting}
4671
4672 /* generic (unspecified) kind of sequence */
4673 #define CV_SEQ_KIND_GENERIC     (0 << CV_SEQ_ELTYPE_BITS)
4674
4675 /* dense sequence suntypes */
4676 #define CV_SEQ_KIND_CURVE       (1 << CV_SEQ_ELTYPE_BITS)
4677 #define CV_SEQ_KIND_BIN_TREE    (2 << CV_SEQ_ELTYPE_BITS)
4678
4679 /* sparse sequence (or set) subtypes */
4680 #define CV_SEQ_KIND_GRAPH       (3 << CV_SEQ_ELTYPE_BITS)
4681 #define CV_SEQ_KIND_SUBDIV2D    (4 << CV_SEQ_ELTYPE_BITS)
4682
4683 \end{lstlisting}
4684
4685 The remaining bits are used to identify different features specific
4686 to certain sequence kinds and element types. For example, curves
4687 made of points ( \texttt{CV\_SEQ\_KIND\_CURVE|CV\_SEQ\_ELTYPE\_POINT} ),
4688 together with the flag \texttt{CV\_SEQ\_FLAG\_CLOSED} belong to the
4689 type \texttt{CV\_SEQ\_POLYGON} or, if other flags are used, to its
4690 subtype. Many contour processing functions check the type of the input
4691 sequence and report an error if they do not support this type. The
4692 file \texttt{cvtypes.h} stores the complete list of all supported
4693 predefined sequence types and helper macros designed to get the sequence
4694 type of other properties. Below follows the definition of the building
4695 block of sequences.
4696
4697 \cvstruct{CvSeqBlock}\label{CvSeqBlock}
4698
4699 Continuous sequence block
4700
4701 \begin{lstlisting}
4702
4703 typedef struct CvSeqBlock
4704 {
4705     struct CvSeqBlock* prev; /* previous sequence block */
4706     struct CvSeqBlock* next; /* next sequence block */
4707     int start_index; /* index of the first element in the block +
4708     sequence->first->start_index */
4709     int count; /* number of elements in the block */
4710     char* data; /* pointer to the first element of the block */
4711 } CvSeqBlock;
4712
4713 \end{lstlisting}
4714
4715 Sequence blocks make up a circular double-linked list, so the pointers
4716 \texttt{prev} and \texttt{next} are never \texttt{NULL} and point to the
4717 previous and the next sequence blocks within the sequence. It means that
4718 \texttt{next} of the last block is the first block and \texttt{prev} of
4719 the first block is the last block. The fields \texttt{start\_index} and
4720 \texttt{count} help to track the block location within the sequence. For
4721 example, if the sequence consists of 10 elements and splits into three
4722 blocks of 3, 5, and 2 elements, and the first block has the parameter
4723 \texttt{start\_index = 2}, then pairs \texttt{(start\_index, count)} for the sequence
4724 blocks are
4725 (2,3), (5, 5), and (10, 2)
4726 correspondingly. The parameter
4727 \texttt{start\_index} of the first block is usually \texttt{0} unless
4728 some elements have been inserted at the beginning of the sequence.
4729
4730 \cvstruct{CvSlice}\label{CvSlice}
4731
4732 A sequence slice
4733
4734 \begin{lstlisting}
4735
4736 typedef struct CvSlice
4737 {
4738     int start_index;
4739     int end_index;
4740 } CvSlice;
4741
4742 inline CvSlice cvSlice( int start, int end );
4743 #define CV_WHOLE_SEQ_END_INDEX 0x3fffffff
4744 #define CV_WHOLE_SEQ  cvSlice(0, CV_WHOLE_SEQ_END_INDEX)
4745
4746 /* calculates the sequence slice length */
4747 int cvSliceLength( CvSlice slice, const CvSeq* seq );
4748
4749 \end{lstlisting}
4750
4751 Some of functions that operate on sequences take \texttt{CvSlice slice}
4752 parameter that is often set to the whole sequence (CV\_WHOLE\_SEQ) by
4753 default. Either of the \texttt{start\_index} and \texttt{end\_index}
4754 may be negative or exceed the sequence length, \texttt{start\_index} is
4755 inclusive, \texttt{end\_index} is exclusive boundary. If they are equal,
4756 the slice is considered empty (i.e. contains no elements). Because
4757 sequences are treated as circular structures, the slice may select a
4758 few elements in the end of a sequence followed by a few elements in the
4759 beginning of the sequence, for example, \texttt{cvSlice(-2, 3)} in case of
4760 10-element sequence will select 5-element slice, containing pre-last
4761 (8th), last (9th), the very first (0th), second (1th) and third (2nd)
4762 elements. The functions normalize the slice argument in the following way:
4763 first, \cross{SliceLength} is called to determine the length of the slice,
4764 then, \texttt{start\_index} of the slice is normalized similarly to the
4765 argument of \cross{GetSeqElem} (i.e. negative indices are allowed). The
4766 actual slice to process starts at the normalized \texttt{start\_index}
4767 and lasts \cross{SliceLength} elements (again, assuming the sequence is
4768 a circular structure).
4769
4770 If a function does not take slice argument, but you want to process
4771 only a part of the sequence, the sub-sequence may be extracted
4772 using \cross{SeqSlice} function, or stored as into a continuous
4773 buffer with \cross{CvtSeqToArray} (optionally, followed by
4774 \cross{MakeSeqHeaderForArray}.
4775
4776 \cvfunc{CreateSeq}\label{CreateSeq}
4777
4778 Creates sequence
4779
4780 \cvexp{
4781
4782 CvSeq* cvCreateSeq( \par int seq\_flags,\par int header\_size,\par int elem\_size,\par CvMemStorage* storage );
4783
4784 }{CPP}{PYTHON}
4785
4786 \begin{description}
4787 \cvarg{seq\_flags}{Flags of the created sequence. If the sequence is not passed to any function working with a specific type of sequences, the sequence value may be set to 0, otherwise the appropriate type must be selected from the list of predefined sequence types.}
4788 \cvarg{header\_size}{Size of the sequence header; must be greater or equal to \texttt{sizeof(CvSeq)}. If a specific type or its extension is indicated, this type must fit the base type header.}
4789 \cvarg{elem\_size}{Size of the sequence elements in bytes. The size must be consistent with the sequence type. For example, for a sequence of points to be created, the element type \texttt{CV\_SEQ\_ELTYPE\_POINT} should be specified and the parameter \texttt{elem\_size} must be equal to \texttt{sizeof(CvPoint)}}
4790 \cvarg{storage}{Sequence location}
4791 \end{description}
4792
4793 The function \texttt{cvCreateSeq} creates a sequence and returns
4794 the pointer to it. The function allocates the sequence header in
4795 the storage block as one continuous chunk and sets the structure
4796 fields \texttt{flags}, \texttt{elem\_size}, \texttt{header\_size} and
4797 \texttt{storage} to passed values, sets \texttt{delta\_elems} to the
4798 default value (that may be reassigned using \cross{SetSeqBlockSize}
4799 function), and clears other header fields, including the space after
4800 the first \texttt{sizeof(CvSeq)} bytes.
4801
4802 \cvfunc{SetSeqBlockSize}\label{SetSeqBlockSize}
4803
4804 Sets up sequence block size
4805
4806 \cvexp{
4807
4808 void cvSetSeqBlockSize( \par CvSeq* seq,\par int delta\_elems );
4809
4810 }{CPP}{PYTHON}
4811
4812 \begin{description}
4813 \cvarg{seq}{Sequence}
4814 \cvarg{delta\_elems}{Desirable sequence block size in elements}
4815 \end{description}
4816
4817
4818 The function \texttt{cvSetSeqBlockSize} affects memory allocation
4819 granularity. When the free space in the sequence buffers has run out,
4820 the function allocates the space for \texttt{delta\_elems} sequence
4821 elements. If this block immediately follows the one previously allocated,
4822 the two blocks are concatenated, otherwise, a new sequence block is
4823 created. Therefore, the bigger the parameter is, the lower the possible
4824 sequence fragmentation, but the more space in the storage is wasted. When
4825 the sequence is created, the parameter \texttt{delta\_elems} is set to
4826 the default value  about 1K. The function can be called any time after
4827 the sequence is created and affects future allocations. The function
4828 can modify the passed value of the parameter to meet the memory storage
4829 constraints.
4830
4831 \cvfunc{SeqPush}\label{SeqPush}
4832
4833 Adds element to sequence end
4834
4835 \cvexp{
4836
4837 char* cvSeqPush( \par CvSeq* seq,\par void* element=NULL );
4838
4839 }{CPP}{PYTHON}
4840
4841 \begin{description}
4842 \cvarg{seq}{Sequence}
4843 \cvarg{element}{Added element}
4844 \end{description}
4845
4846
4847 The function \texttt{cvSeqPush} adds an element to the end of sequence and retuns pointer to the allocated element. If the input \texttt{element} is NULL, the function simply allocates a space for one more element.
4848
4849 The following code demonstrates how to create a new sequence using this function:
4850
4851 \begin{lstlisting}
4852
4853 CvMemStorage* storage = cvCreateMemStorage(0);
4854 CvSeq* seq = cvCreateSeq( CV_32SC1, /* sequence of integer elements */
4855                           sizeof(CvSeq), /* header size - no extra fields */
4856                           sizeof(int), /* element size */
4857                           storage /* the container storage */ );
4858 int i;
4859 for( i = 0; i < 100; i++ )
4860 {
4861     int* added = (int*)cvSeqPush( seq, &i );
4862     printf( "%d is added\n", *added );
4863 }
4864
4865 ...
4866 /* release memory storage in the end */
4867 cvReleaseMemStorage( &storage );
4868
4869 \end{lstlisting}
4870
4871 The function \texttt{cvSeqPush} has O(1) complexity, but there is a faster method for writing large sequences (see \cross{StartWriteSeq} and related functions).
4872
4873
4874 \cvfunc{SeqPop}\label{SeqPop}
4875
4876 Removes element from sequence end
4877
4878 \cvexp{
4879
4880 void cvSeqPop( \par CvSeq* seq,\par void* element=NULL );
4881
4882 }{CPP}{PYTHON}
4883
4884 \begin{description}
4885 \cvarg{seq}{Sequence}
4886 \cvarg{element}{Optional parameter . If the pointer is not zero, the function copies the removed element to this location.}
4887 \end{description}
4888
4889 The function \texttt{cvSeqPop} removes an element from the sequence. The function reports an error if the sequence is already empty. The function has O(1) complexity.
4890
4891 \cvfunc{SeqPushFront}\label{SeqPushFront}
4892
4893 Adds element to sequence beginning
4894
4895 \cvexp{
4896
4897 char* cvSeqPushFront( CvSeq* seq, void* element=NULL );
4898
4899 }{CPP}{PYTHON}
4900
4901 \begin{description}
4902 \cvarg{seq}{Sequence}
4903 \cvarg{element}{Added element}
4904 \end{description}
4905
4906 The function \texttt{cvSeqPushFront} is similar to \cross{SeqPush} but it adds the new element to the beginning of the sequence. The function has O(1) complexity.
4907
4908 \cvfunc{SeqPopFront}\label{SeqPopFront}
4909
4910 Removes element from sequence beginning
4911
4912 \cvexp{
4913
4914 void cvSeqPopFront( \par \par CvSeq* seq,\par\par void* element=NULL );
4915
4916 }{CPP}{PYTHON}
4917
4918 \begin{description}
4919 \cvarg{seq}{Sequence}
4920 \cvarg{element}{Optional parameter. If the pointer is not zero, the function copies the removed element to this location.}
4921 \end{description}
4922
4923 The function \texttt{cvSeqPopFront} removes an element from the beginning of the sequence. The function reports an error if the sequence is already empty. The function has O(1) complexity.
4924
4925 \cvfunc{SeqPushMulti}\label{SeqPushMulti}
4926
4927 Pushes several elements to the either end of sequence
4928
4929 \cvexp{
4930
4931 void cvSeqPushMulti( \par CvSeq* seq,\par void* elements,\par int count,\par int in\_front=0 );
4932
4933 }{CPP}{PYTHON}
4934
4935 \begin{description}
4936 \cvarg{seq}{Sequence}
4937 \cvarg{elements}{Added elements}
4938 \cvarg{count}{Number of elements to push}
4939 \cvarg{in\_front}{The flags specifying the modified sequence end
4940 \begin{description}
4941 \cvarg{CV\_BACK}{the elements are added to the end of sequence}
4942 \cvarg{CV\_FRONT}{the elements are added to the beginning of sequence}
4943 \end{description}}
4944 \end{description}
4945
4946 The function \texttt{cvSeqPushMulti} adds several elements to either
4947 end of the sequence. The elements are added to the sequence in the same
4948 order as they are arranged in the input array but they can fall into
4949 different sequence blocks.
4950
4951 \cvfunc{SeqPopMulti}\label{SeqPopMulti}
4952
4953 Removes several elements from the either end of sequence
4954
4955 \cvexp{
4956
4957 void cvSeqPopMulti( \par CvSeq* seq,\par void* elements,\par int count,\par int in\_front=0 );
4958
4959 }{CPP}{PYTHON}
4960
4961 \begin{description}
4962 \cvarg{seq}{Sequence}
4963 \cvarg{elements}{Removed elements}
4964 \cvarg{count}{Number of elements to pop}
4965 \cvarg{in\_front}{The flags specifying the modified sequence end
4966 \begin{description}
4967 \cvarg{CV\_BACK}{the elements are added to the end of sequence}
4968 \cvarg{CV\_FRONT}{the elements are added to the beginning of sequence}
4969 \end{description}}
4970 \end{description}
4971
4972 The function \texttt{cvSeqPopMulti} removes several elements from either end of the sequence. If the number of the elements to be removed exceeds the total number of elements in the sequence, the function removes as many elements as possible.
4973
4974 \cvfunc{SeqInsert}\label{SeqInsert}
4975
4976 Inserts element in sequence middle
4977
4978 \cvexp{
4979
4980 char* cvSeqInsert( \par CvSeq* seq,\par int before\_index,\par void* element=NULL );
4981
4982 }{CPP}{PYTHON}
4983
4984 \begin{description}
4985 \cvarg{seq}{Sequence}
4986 \cvarg{before\_index}{Index before which the element is inserted. Inserting before 0 (the minimal allowed value of the parameter) is equal to \cross{SeqPushFront} and inserting before \texttt{seq->total} (the maximal allowed value of the parameter) is equal to \cross{SeqPush}.}
4987 \cvarg{element}{Inserted element} 
4988 \end{description}
4989
4990 The function \texttt{cvSeqInsert} shifts the sequence elements from the inserted position to the nearest end of the sequence and copies the \texttt{element} content there if the pointer is not NULL. The function returns pointer to the inserted element.
4991
4992 \cvfunc{SeqRemove}\label{SeqRemove}
4993
4994 Removes element from sequence middle
4995
4996 \cvexp{
4997
4998 void cvSeqRemove( \par CvSeq* seq,\par int index );
4999
5000 }{CPP}{PYTHON}
5001
5002 \begin{description}
5003 \cvarg{seq}{Sequence}
5004 \cvarg{index}{Index of removed element}
5005 \end{description}
5006
5007
5008 The function \texttt{cvSeqRemove} removes elements with the given
5009 index. If the index is out of range the function reports an error. An
5010 attempt to remove an element from an empty sequence is a partitial
5011 case of this situation. The function removes an element by shifting
5012 the sequence elements between the nearest end of the sequence and the
5013 \texttt{index}-th position, not counting the latter.
5014
5015
5016 \cvfunc{ClearSeq}\label{ClearSeq}
5017
5018 Clears sequence
5019
5020 \cvexp{
5021
5022 void cvClearSeq( CvSeq* seq );
5023
5024 }{CPP}{PYTHON}
5025
5026 \begin{description}
5027 \cvarg{seq}{Sequence}
5028 \end{description}
5029
5030
5031 The function \texttt{cvClearSeq} removes all elements from the
5032 sequence. The function does not return the memory to the storage, but this
5033 memory is reused later when new elements are added to the sequence. This
5034 function time complexity is 'O(1)'.
5035
5036 \cvfunc{GetSeqElem}\label{GetSeqElem}
5037
5038 Returns pointer to sequence element by its index
5039
5040 \cvexp{
5041
5042 char* cvGetSeqElem( const CvSeq* seq, int index );
5043
5044 }{CPP}{PYTHON}
5045
5046 \begin{lstlisting}
5047 #define CV_GET_SEQ_ELEM( TYPE, seq, index )  (TYPE*)cvGetSeqElem( (CvSeq*)(seq), (index) )
5048 \end{lstlisting}
5049
5050 \begin{description}
5051 \cvarg{seq}{Sequence}
5052 \cvarg{index}{Index of element}
5053 \end{description}
5054
5055
5056 The function \texttt{cvGetSeqElem} finds the element with the given
5057 index in the sequence and returns the pointer to it. If the element
5058 is not found, the function returns 0. The function supports negative
5059 indices, where -1 stands for the last sequence element, -2 stands for
5060 the one before last, etc. If the sequence is most likely to consist of
5061 a single sequence block or the desired element is likely to be located
5062 in the first block, then the macro
5063 \texttt{CV\_GET\_SEQ\_ELEM( elemType, seq, index )}
5064 should be used, where the parameter \texttt{elemType} is the
5065 type of sequence elements ( \cross{CvPoint} for example), the parameter
5066 \texttt{seq} is a sequence, and the parameter \texttt{index} is the index
5067 of the desired element. The macro checks first whether the desired element
5068 belongs to the first block of the sequence and returns it if it does,
5069 otherwise the macro calls the main function \texttt{GetSeqElem}. Negative
5070 indices always cause the \cross{GetSeqElem} call. The function has O(1)
5071 time complexity assuming that number of blocks is much smaller than the
5072 number of elements.
5073
5074 \cvfunc{SeqElemIdx}\label{SeqElemIdx}
5075
5076 Returns index of concrete sequence element
5077
5078 \cvexp{
5079
5080 int cvSeqElemIdx( \par const CvSeq* seq,\par const void* element,\par CvSeqBlock** block=NULL );
5081
5082 }{CPP}{PYTHON}
5083
5084 \begin{description}
5085 \cvarg{seq}{Sequence}
5086 \cvarg{element}{Pointer to the element within the sequence}
5087 \cvarg{block}{Optional argument. If the pointer is not \texttt{NULL}, the address of the sequence block that contains the element is stored in this location.}
5088 \end{description}
5089
5090 The function \texttt{cvSeqElemIdx} returns the index of a sequence element or a negative number if the element is not found.
5091
5092 \cvfunc{CvtSeqToArray}\label{CvtSeqToArray}
5093
5094 Copies sequence to one continuous block of memory
5095
5096 \cvexp{
5097
5098 void* cvCvtSeqToArray( \par const CvSeq* seq,\par void* elements,\par CvSlice slice=CV\_WHOLE\_SEQ );
5099
5100 }{CPP}{PYTHON}
5101
5102 \begin{description}
5103 \cvarg{seq}{Sequence}
5104 \cvarg{elements}{Pointer to the destination array that must be large enough. It should be a pointer to data, not a matrix header.}
5105 \cvarg{slice}{The sequence part to copy to the array}
5106 \end{description}
5107
5108
5109 The function \texttt{cvCvtSeqToArray} copies the entire sequence or subsequence to the specified buffer and returns the pointer to the buffer.
5110
5111
5112 \cvfunc{MakeSeqHeaderForArray}\label{MakeSeqHeaderForArray}
5113
5114 Constructs sequence from array
5115
5116 \cvexp{
5117
5118 CvSeq* cvMakeSeqHeaderForArray( \par int seq\_type,\par int header\_size,\par int elem\_size,\par void* elements,\par int total,\par CvSeq* seq,\par CvSeqBlock* block );
5119
5120 }{CPP}{PYTHON}
5121
5122 \begin{description}
5123 \cvarg{seq\_type}{Type of the created sequence}
5124 \cvarg{header\_size}{Size of the header of the sequence . Parameter sequence must point to the structure of that size or greater size.}
5125 \cvarg{elem\_size}{Size of the sequence element}
5126 \cvarg{elements}{Elements that will form a sequence}
5127 \cvarg{total}{Total number of elements in the sequence. The number of array elements must be equal to the value of this parameter.}
5128 \cvarg{seq}{Pointer to the local variable that is used as the sequence header}
5129 \cvarg{block}{Pointer to the local variable that is the header of the single sequence block}
5130 \end{description}
5131
5132 The function \texttt{cvMakeSeqHeaderForArray} initializes sequence
5133 header for array. The sequence header as well as the sequence block are
5134 allocated by the user (for example, on stack). No data is copied by the
5135 function. The resultant sequence will consists of a single block and
5136 have NULL storage pointer, thus, it is possible to read its elements,
5137 but the attempts to add elements to the sequence will raise an error in
5138 most cases.
5139
5140 \cvfunc{SeqSlice}\label{SeqSlice}
5141
5142 Makes separate header for the sequence slice
5143
5144 \cvexp{
5145
5146 CvSeq* cvSeqSlice( \par const CvSeq* seq,\par CvSlice slice,\par CvMemStorage* storage=NULL,\par int copy\_data=0 );
5147
5148 }{CPP}{PYTHON}
5149
5150 \begin{description}
5151 \cvarg{seq}{Sequence}
5152 \cvarg{slice}{The part of the sequence to extract}
5153 \cvarg{storage}{The destination storage to keep the new sequence header and the copied data if any . If it is NULL, the function uses the storage containing the input sequence.}
5154 \cvarg{copy\_data}{The flag that indicates whether to copy the elements of the extracted slice (\texttt{copy\_data!=0}) or not (\texttt{copy\_data=0})}
5155 \end{description}
5156
5157 The function \texttt{cvSeqSlice} creates a sequence that represents the specified slice of the input sequence. The new sequence either shares the elements with the original sequence or has own copy of the elements. So if one needs to process a part of sequence but the processing function does not have a slice parameter, the required sub-sequence may be extracted using this function.
5158
5159
5160 \cvfunc{CloneSeq}\label{CloneSeq}
5161
5162 Creates a copy of sequence
5163
5164 \cvexp{
5165
5166 CvSeq* cvCloneSeq( \par const CvSeq* seq,\par CvMemStorage* storage=NULL );
5167
5168 }{CPP}{PYTHON}
5169
5170 \begin{description}
5171 \cvarg{seq}{Sequence}
5172 \cvarg{storage}{The destination storage to keep the new sequence header and the copied data if any. If it is NULL, the function uses the storage containing the input sequence.} 
5173 \end{description}
5174
5175 The function \texttt{cvCloneSeq} makes a complete copy of the input sequence and returns it. The call
5176
5177 \begin{lstlisting}
5178 cvCloneSeq( seq, storage )
5179 \end{lstlisting}
5180
5181 is equivalent to
5182
5183 \begin{lstlisting}
5184 cvSeqSlice]( seq, CV\_WHOLE\_SEQ, storage, 1 )
5185 \end{lstlisting}
5186
5187 \cvfunc{SeqRemoveSlice}\label{SeqRemoveSlice}
5188
5189 Removes sequence slice
5190
5191 \cvexp{
5192
5193 void cvSeqRemoveSlice( CvSeq* seq, CvSlice slice );
5194
5195 }{CPP}{PYTHON}
5196
5197 \begin{description}
5198 \cvarg{seq}{Sequence}
5199 \cvarg{slice}{The part of the sequence to remove}
5200 \end{description}
5201
5202
5203 The function \texttt{cvSeqRemoveSlice} removes slice from the sequence.
5204
5205 \cvfunc{SeqInsertSlice}\label{SeqInsertSlice}
5206
5207 Inserts array in the middle of sequence
5208
5209 \cvexp{
5210
5211 void cvSeqInsertSlice( \par CvSeq* seq,\par int before\_index,\par const CvArr* from\_arr );
5212
5213 }{CPP}{PYTHON}
5214
5215 \begin{description}
5216 \cvarg{seq}{Sequence}
5217 \cvarg{slice}{The part of the sequence to remove}
5218 \cvarg{from\_arr}{The array to take elements from}
5219 \end{description}
5220
5221
5222 The function \texttt{cvSeqInsertSlice} inserts all \texttt{from\_arr}
5223 array elements at the specified position of the sequence. The array
5224 \texttt{from\_arr} can be a matrix or another sequence.
5225
5226 \cvfunc{SeqInvert}\label{SeqInvert}
5227
5228 Reverses the order of sequence elements
5229
5230 \cvexp{
5231
5232 void cvSeqInvert( CvSeq* seq );
5233
5234 }{CPP}{PYTHON}
5235
5236 \begin{description}
5237 \cvarg{seq}{Sequence}
5238 \end{description}
5239
5240
5241 The function \texttt{cvSeqInvert} reverses the sequence in-place - makes the first element go last, the last element go first etc.
5242
5243
5244 \cvfunc{SeqSort}\label{SeqSort}
5245
5246 Sorts sequence element using the specified comparison function
5247
5248 \cvexp{
5249
5250 void cvSeqSort( CvSeq* seq, CvCmpFunc func, void* userdata=NULL );
5251
5252 }{CPP}{PYTHON}
5253
5254 \begin{lstlisting}
5255 /* a < b ? -1 : a > b ? 1 : 0 */
5256 typedef int (CV_CDECL* CvCmpFunc)(const void* a, const void* b, void* userdata);
5257 \end{lstlisting}
5258
5259 \begin{description}
5260 \cvarg{seq}{The sequence to sort}
5261 \cvarg{func}{The comparison function that returns negative, zero or positive value depending on the elements relation (see the above declaration and the example below) - similar function is used by \texttt{qsort} from C runline except that in the latter \texttt{userdata} is not used}
5262 \cvarg{userdata}{The user parameter passed to the compasion function; helps to avoid global variables in some cases}
5263 \end{description}
5264
5265 The function \texttt{cvSeqSort} sorts the sequence in-place using the specified criteria. Below is the example of the function use:
5266
5267 \begin{lstlisting}
5268
5269 /* Sort 2d points in top-to-bottom left-to-right order */
5270 static int cmp_func( const void* _a, const void* _b, void* userdata )
5271 {
5272     CvPoint* a = (CvPoint*)_a;
5273     CvPoint* b = (CvPoint*)_b;
5274     int y_diff = a->y - b->y;
5275     int x_diff = a->x - b->x;
5276     return y_diff ? y_diff : x_diff;
5277 }
5278
5279 ...
5280
5281 CvMemStorage* storage = cvCreateMemStorage(0);
5282 CvSeq* seq = cvCreateSeq( CV_32SC2, sizeof(CvSeq), sizeof(CvPoint), storage );
5283 int i;
5284
5285 for( i = 0; i < 10; i++ )
5286 {
5287     CvPoint pt;
5288     pt.x = rand() % 1000;
5289     pt.y = rand() % 1000;
5290     cvSeqPush( seq, &pt );
5291 }
5292
5293 cvSeqSort( seq, cmp_func, 0 /* userdata is not used here */ );
5294
5295 /* print out the sorted sequence */
5296 for( i = 0; i < seq->total; i++ )
5297 {
5298     CvPoint* pt = (CvPoint*)cvSeqElem( seq, i );
5299     printf( "(%d,%d)\n", pt->x, pt->y );
5300 }
5301
5302 cvReleaseMemStorage( &storage );
5303
5304 \end{lstlisting}
5305
5306
5307 \cvfunc{SeqSearch}\label{SeqSearch}
5308
5309 Searches element in sequence
5310
5311 \begin{lstlisting}
5312
5313 /* a < b ? -1 : a > b ? 1 : 0 */
5314 typedef int (CV_CDECL* CvCmpFunc)(const void* a, const void* b, void* userdata);
5315
5316 char* cvSeqSearch( CvSeq* seq, const void* elem, CvCmpFunc func,
5317                    int is_sorted, int* elem_idx, void* userdata=NULL );
5318
5319 \end{lstlisting}
5320
5321 \begin{description}
5322 \cvarg{seq}{The sequence}
5323 \cvarg{elem}{The element to look for}
5324 \cvarg{func}{The comparison function that returns negative, zero or positive value depending on the elements relation (see also \cross{SeqSort})}
5325 \cvarg{is\_sorted}{Whether the sequence is sorted or not}
5326 \cvarg{elem\_idx}{Output parameter; index of the found element}
5327 \cvarg{userdata}{The user parameter passed to the compasion function; helps to avoid global variables in some cases}
5328 \end{description}
5329
5330 The function \texttt{cvSeqSearch} searches the element in the sequence. If
5331 the sequence is sorted, binary O(log(N)) search is used, otherwise, a
5332 simple linear search is used. If the element is not found, the function
5333 returns NULL pointer and the index is set to the number of sequence
5334 elements if the linear search is used, and to the smallest index
5335 \texttt{i, seq(i)>elem}
5336 .
5337
5338 \cvfunc{StartAppendToSeq}\label{StartAppendToSeq}
5339
5340 Initializes process of writing data to sequence
5341
5342 \cvexp{
5343
5344 void cvStartAppendToSeq( \par CvSeq* seq,\par CvSeqWriter* writer );
5345
5346 }{CPP}{PYTHON}
5347
5348 \begin{description}
5349 \cvarg{seq}{Pointer to the sequence}
5350 \cvarg{writer}{Writer state; initialized by the function}
5351 \end{description}
5352
5353 The function \texttt{cvStartAppendToSeq} initializes the process of
5354 writing data to the sequence. Written elements are added to the end of the
5355 sequence by
5356 \texttt{CV\_WRITE\_SEQ\_ELEM( written\_elem, writer )}
5357 macro. Note
5358 that during the writing process other operations on the sequence may
5359 yield incorrect result or even corrupt the sequence (see description of
5360 \cross{FlushSeqWriter} that helps to avoid some of these problems).
5361
5362 \cvfunc{StartWriteSeq}\label{StartWriteSeq}
5363
5364 Creates new sequence and initializes writer for it
5365
5366 \cvexp{
5367
5368 void cvStartWriteSeq( \par int seq\_flags,\par int header\_size,\par int elem\_size,\par CvMemStorage* storage,\par CvSeqWriter* writer );
5369
5370 }{CPP}{PYTHON}
5371
5372 \begin{description}
5373 \cvarg{seq\_flags}{Flags of the created sequence. If the sequence is not passed to any function working with a specific type of sequences, the sequence value may be equal to 0, otherwise the appropriate type must be selected from the list of predefined sequence types.}
5374 \cvarg{header\_size}{Size of the sequence header. The parameter value may not be less than \texttt{sizeof(CvSeq)}. If a certain type or extension is specified, it must fit the base type header.}
5375 \cvarg{elem\_size}{Size of the sequence elements in bytes; must be consistent with the sequence type. For example, if the sequence of points is created (element type \texttt{CV\_SEQ\_ELTYPE\_POINT} ), then the parameter elem\_size must be equal to \texttt{sizeof(CvPoint)}}
5376 \cvarg{storage}{Sequence location}
5377 \cvarg{writer}{Writer state; initialized by the function}
5378 \end{description}
5379
5380 The function \texttt{cvStartWriteSeq} is a composition of
5381 \cross{CreateSeq} and \cross{StartAppendToSeq}. The pointer to the
5382 created sequence is stored at
5383 \texttt{writer->seq}
5384 and is also returned by
5385 \cross{EndWriteSeq} function that should be called in the end.
5386
5387 \cvfunc{EndWriteSeq}\label{EndWriteSeq}
5388
5389 Finishes process of writing sequence
5390
5391 \cvexp{
5392
5393 CvSeq* cvEndWriteSeq( CvSeqWriter* writer );
5394
5395 }{CPP}{PYTHON}
5396
5397 \begin{description}
5398 \cvarg{writer}{Writer state}
5399 \end{description}
5400
5401
5402 The function \texttt{cvEndWriteSeq} finishes the writing process and
5403 returns the pointer to the written sequence. The function also truncates
5404 the last incomplete sequence block to return the remaining part of the
5405 block to the memory storage. After that the sequence can be read and
5406 modified safely.
5407
5408 \cvfunc{FlushSeqWriter}\label{FlushSeqWriter}
5409
5410 Updates sequence headers from the writer state
5411
5412 \cvexp{
5413
5414 void cvFlushSeqWriter( CvSeqWriter* writer );
5415
5416 }{CPP}{PYTHON}
5417
5418 \begin{description}
5419 \cvarg{writer}{Writer state}
5420 \end{description}
5421
5422 The function \texttt{cvFlushSeqWriter} is intended to enable the user to
5423 read sequence elements, whenever required, during the writing process,
5424 e.g., in order to check specific conditions. The function updates the
5425 sequence headers to make reading from the sequence possible. The writer
5426 is not closed, however, so that the writing process can be continued
5427 any time. In some algorithm requires often flush'es, consider using
5428 \cross{SeqPush} instead.
5429
5430 \cvfunc{StartReadSeq}\label{StartReadSeq}
5431
5432 Initializes process of sequential reading from sequence
5433
5434 \cvexp{
5435
5436 void cvStartReadSeq( \par const CvSeq* seq,\par CvSeqReader* reader,\par int reverse=0 );
5437
5438 }{CPP}{PYTHON}
5439
5440 \begin{description}
5441 \cvarg{seq}{Sequence}
5442 \cvarg{reader}{Reader state; initialized by the function}
5443 \cvarg{reverse}{Determines the direction of the sequence traversal. If \texttt{reverse} is 0, the reader is positioned at the first sequence element, otherwise it is positioned at the last element. }
5444 \end{description}
5445
5446 The function \texttt{cvStartReadSeq} initializes the reader state. After
5447 that all the sequence elements from the first down to the last one
5448 can be read by subsequent calls of the macro
5449 \texttt{CV\_READ\_SEQ\_ELEM( read\_elem, reader )}
5450 in case of forward reading and by using
5451 \texttt{CV\_REV\_READ\_SEQ\_ELEM( read\_elem, reader )}
5452 in case of reversed
5453 reading. Both macros put the sequence element to \texttt{read\_elem} and
5454 move the reading pointer toward the next element. A circular structure
5455 of sequence blocks is used for the reading process, that is, after the
5456 last element has been read by the macro \texttt{CV\_READ\_SEQ\_ELEM}, the
5457 first element is read when the macro is called again. The same applies to
5458 \texttt{CV\_REV\_READ\_SEQ\_ELEM}. There is no function to finish the reading
5459 process, since it neither changes the sequence nor creates any temporary
5460 buffers. The reader field \texttt{ptr} points to the current element of
5461 the sequence that is to be read next. The code below demonstrates how
5462 to use sequence writer and reader.
5463
5464 \begin{lstlisting}
5465
5466 CvMemStorage* storage = cvCreateMemStorage(0);
5467 CvSeq* seq = cvCreateSeq( CV_32SC1, sizeof(CvSeq), sizeof(int), storage );
5468 CvSeqWriter writer;
5469 CvSeqReader reader;
5470 int i;
5471
5472 cvStartAppendToSeq( seq, &writer );
5473 for( i = 0; i < 10; i++ )
5474 {
5475     int val = rand()%100;
5476     CV_WRITE_SEQ_ELEM( val, writer );
5477     printf("%d is written\n", val );
5478 }
5479 cvEndWriteSeq( &writer );
5480
5481 cvStartReadSeq( seq, &reader, 0 );
5482 for( i = 0; i < seq->total; i++ )
5483 {
5484     int val;
5485 #if 1
5486     CV_READ_SEQ_ELEM( val, reader );
5487     printf("%d is read\n", val );
5488 #else /* alternative way, that is prefferable if sequence elements are large,
5489          or their size/type is unknown at compile time */
5490     printf("%d is read\n", *(int*)reader.ptr );
5491     CV_NEXT_SEQ_ELEM( seq->elem_size, reader );
5492 #endif
5493 }
5494 ...
5495
5496 cvReleaseStorage( &storage );
5497
5498 \end{lstlisting}
5499
5500 \cvfunc{GetSeqReaderPos}\label{GetSeqReaderPos}
5501
5502 Returns the current reader position
5503
5504 \cvexp{
5505
5506 int cvGetSeqReaderPos( CvSeqReader* reader );
5507
5508 }{CPP}{PYTHON}
5509
5510 \begin{description}
5511 \cvarg{reader}{Reader state}
5512 \end{description}
5513
5514
5515 The function \texttt{cvGetSeqReaderPos} returns the current reader position (within 0 ... \texttt{reader->seq->total} - 1).
5516
5517 \cvfunc{SetSeqReaderPos}\label{SetSeqReaderPos}
5518
5519 Moves the reader to specified position
5520
5521 \cvexp{
5522
5523 void cvSetSeqReaderPos( \par CvSeqReader* reader,\par int index,\par int is\_relative=0 );
5524
5525 }{CPP}{PYTHON}
5526
5527 \begin{description}
5528 \cvarg{reader}{Reader state}
5529 \cvarg{index}{The destination position. If the positioning mode is used (see the next parameter) the actual position will be \texttt{index} mod \texttt{reader->seq->total}.}
5530 \cvarg{is\_relative}{If it is not zero, then \texttt{index} is a relative to the current position}
5531 \end{description}
5532
5533 The function \texttt{cvSetSeqReaderPos} moves the read position to the absolute position or relative to the current position.
5534
5535 \subsection{Sets}
5536
5537 \cvstruct{CvSet}\label{CvSet}
5538
5539 Collection of nodes
5540
5541 \begin{lstlisting}
5542
5543 typedef struct CvSetElem
5544 {
5545     int flags; /* it is negative if the node is free and zero or positive otherwise */
5546     struct CvSetElem* next_free; /* if the node is free, the field is a
5547                                     pointer to next free node */
5548 }
5549 CvSetElem;
5550
5551 #define CV_SET_FIELDS()    \
5552     CV_SEQUENCE_FIELDS()   /* inherits from [#CvSeq CvSeq] */ \
5553     struct CvSetElem* free_elems; /* list of free nodes */
5554
5555 typedef struct CvSet
5556 {
5557     CV_SET_FIELDS()
5558 } CvSet;
5559
5560 \end{lstlisting}
5561
5562 The structure \cross{CvSet} is a base for OpenCV sparse data structures.
5563
5564 As follows from the above declaration \cross{CvSet} inherits from
5565 \cross{CvSeq} and it adds \texttt{free\_elems} field it to, which
5566 is a list of free nodes. Every set node, whether free or not, is the
5567 element of the underlying sequence. While there is no restrictions on
5568 elements of dense sequences, the set (and derived structures) elements
5569 must start with integer field and be able to fit CvSetElem structure,
5570 because these two fields (integer followed by the pointer) are required
5571 for organization of node set with the list of free nodes. If a node is
5572 free, \texttt{flags} field is negative (the most-significant bit, or
5573 MSB, of the field is set), and \texttt{next\_free} points to the next
5574 free node (the first free node is referenced by \texttt{free\_elems}
5575 field of \cross{CvSet}). And if a node is occupied, \texttt{flags} field
5576 is positive and contains the node index that may be retrieved using
5577 (\texttt{set\_elem->flags \& CV\_SET\_ELEM\_IDX\_MASK}) expression, the rest of
5578 the node content is determined by the user. In particular, the occupied
5579 nodes are not linked as the free nodes are, so the second field can be
5580 used for such a link as well as for some different purpose. The macro
5581 'CV\_IS\_SET\_ELEM(set\_elem\_ptr)' can be used to determined whether
5582 the specified node is occupied or not.
5583
5584 Initially the set and the list are empty. When a new node is requiested
5585 from the set, it is taken from the list of free nodes, which is updated
5586 then. If the list appears to be empty, a new sequence block is allocated
5587 and all the nodes within the block are joined in the list of free
5588 nodes. Thus, \texttt{total} field of the set is the total number of nodes
5589 both occupied and free. When an occupied node is released, it is added
5590 to the list of free nodes. The node released last will be occupied first.
5591
5592 In OpenCV \cross{CvSet} is used for representing graphs (\cross{CvGraph}),
5593 sparse multi-dimensional arrays (\cross{CvSparseMat}), planar subdivisions
5594 \cross{CvSubdiv2D}.
5595
5596 \cvfunc{CreateSet}\label{CreateSet}
5597
5598 Creates empty set
5599
5600 \cvexp{
5601
5602 CvSet* cvCreateSet( \par int set\_flags,\par int header\_size,\par int elem\_size,\par CvMemStorage* storage );
5603
5604 }{CPP}{PYTHON}
5605
5606 \begin{description}
5607 \cvarg{set\_flags}{Type of the created set}
5608 \cvarg{header\_size}{Set header size; may not be less than \texttt{sizeof(CvSet)}}
5609 \cvarg{elem\_size}{Set element size; may not be less than \cross{CvSetElem}}
5610 \cvarg{storage}{Container for the set}
5611 \end{description}
5612
5613 The function \texttt{cvCreateSet} creates an empty set with a specified header size and element size, and returns the pointer to the set. The function is just a thin layer on top of \cross{CreateSeq}.
5614
5615 \cvfunc{SetAdd}\label{SetAdd}
5616
5617 Occupies a node in the set
5618
5619 \cvexp{
5620
5621 int cvSetAdd( \par CvSet* set\_header,\par CvSetElem* elem=NULL,\par CvSetElem** inserted\_elem=NULL );
5622
5623 }{CPP}{PYTHON}
5624
5625 \begin{description}
5626 \cvarg{set\_header}{Set}
5627 \cvarg{elem}{Optional input argument, inserted element. If not NULL, the function copies the data to the allocated node (The MSB of the first integer field is cleared after copying).}
5628 \cvarg{inserted\_elem}{Optional output argument; the pointer to the allocated cell}
5629 \end{description}
5630
5631 The function \texttt{cvSetAdd} allocates a new node, optionally copies
5632 input element data to it, and returns the pointer and the index to the
5633 node. The index value is taken from the lower bits of \texttt{flags}
5634 field of the node. The function has O(1) complexity, however there exists
5635 a faster function for allocating set nodes (see \cross{SetNew}).
5636
5637 \cvfunc{SetRemove}\label{SetRemove}
5638
5639 Removes element from set
5640
5641 \cvexp{
5642
5643 void cvSetRemove( \par CvSet* set\_header,\par int index );
5644
5645 }{CPP}{PYTHON}
5646
5647 \begin{description}
5648 \cvarg{set\_header}{Set}
5649 \cvarg{index}{Index of the removed element}
5650 \end{description}
5651
5652 The function \texttt{cvSetRemove} removes an element with a specified
5653 index from the set. If the node at the specified location is not occupied
5654 the function does nothing. The function has O(1) complexity, however,
5655 \cross{SetRemoveByPtr} provides yet faster way to remove a set element
5656 if it is located already.
5657
5658 \cvfunc{SetNew}\label{SetNew}
5659
5660 Adds element to set (fast variant)
5661
5662 \cvexp{
5663
5664 CvSetElem* cvSetNew( CvSet* set\_header );
5665
5666 }{CPP}{PYTHON}
5667
5668 \begin{description}
5669 \cvarg{set\_header}{Set}
5670 \end{description}
5671
5672
5673 The function \texttt{cvSetNew} is inline light-weight variant of \cross{SetAdd}. It occupies a new node and returns pointer to it rather than index.
5674
5675
5676 \cvfunc{SetRemoveByPtr}\label{SetRemoveByPtr}
5677
5678 Removes set element given its pointer
5679
5680 \cvexp{
5681
5682 void cvSetRemoveByPtr( \par CvSet* set\_header,\par void* elem );
5683
5684 }{CPP}{PYTHON}
5685
5686 \begin{description}
5687 \cvarg{set\_header}{Set}
5688 \cvarg{elem}{Removed element}
5689 \end{description}
5690
5691 The function \texttt{cvSetRemoveByPtr} is inline light-weight variant of \cross{SetRemove} that takes element pointer. The function does not check whether the node is occupied or not - the user should take care of it.
5692
5693
5694 \cvfunc{GetSetElem}\label{GetSetElem}
5695
5696 Finds set element by its index
5697
5698 \cvexp{
5699
5700 CvSetElem* cvGetSetElem( \par const CvSet* set\_header,\par int index );
5701
5702 }{CPP}{PYTHON}
5703
5704 \begin{description}
5705 \cvarg{set\_header}{Set}
5706 \cvarg{index}{Index of the set element within a sequence}
5707 \end{description}
5708
5709 The function \texttt{cvGetSetElem} finds a set element by index. The function returns the pointer to it or 0 if the index is invalid or the corresponding node is free. The function supports negative indices as it uses \cross{GetSeqElem} to locate the node.
5710
5711 \cvfunc{ClearSet}\label{ClearSet}
5712
5713 Clears set
5714
5715 \cvexp{
5716
5717 void cvClearSet( CvSet* set\_header );
5718
5719 }{CPP}{PYTHON}
5720
5721 \begin{description}
5722 \cvarg{set\_header}{Cleared set}
5723 \end{description}
5724
5725
5726 The function \texttt{cvClearSet} removes all elements from set. It has O(1) time complexity.
5727
5728
5729 \subsection{Graphs}
5730
5731
5732 \cvstruct{CvGraph}\label{CvGraph}
5733
5734 Oriented or unoriented weigted graph
5735
5736 \begin{lstlisting}
5737
5738 #define CV_GRAPH_VERTEX_FIELDS()    \
5739     int flags; /* vertex flags */   \
5740     struct CvGraphEdge* first; /* the first incident edge */
5741
5742 typedef struct CvGraphVtx
5743 {
5744     CV_GRAPH_VERTEX_FIELDS()
5745 }
5746 CvGraphVtx;
5747
5748 #define CV_GRAPH_EDGE_FIELDS()      \
5749     int flags; /* edge flags */     \
5750     float weight; /* edge weight */ \
5751     struct CvGraphEdge* next[2]; /* the next edges in the incidence lists for staring (0) */ \
5752                                   /* and ending (1) vertices */ \
5753     struct CvGraphVtx* vtx[2]; /* the starting (0) and ending (1) vertices */
5754
5755 typedef struct CvGraphEdge
5756 {
5757     CV_GRAPH_EDGE_FIELDS()
5758 }
5759 CvGraphEdge;
5760
5761 #define  CV_GRAPH_FIELDS()                  \
5762     CV_SET_FIELDS() /* set of vertices */   \
5763     CvSet* edges;   /* set of edges */
5764
5765 typedef struct CvGraph
5766 {
5767     CV_GRAPH_FIELDS()
5768 }
5769 CvGraph;
5770
5771 \end{lstlisting}
5772
5773 The structure \cross{CvGraph} is a base for graphs used in OpenCV.
5774
5775 Graph structure inherits from \cross{CvSet} - this part describes common graph properties and the graph vertices, and contains another set as a member - this part describes the graph edges.
5776
5777 The vertex, edge and the graph header structures are declared using the
5778 same technique as other extendible OpenCV structures - via macros, that
5779 simplifies extension and customization of the structures. While the vertex
5780 and edge structures do not inherit from \cross{CvSetElem} explicitly, they
5781 satisfy both conditions on the set elements - have an integer field in
5782 the beginning and fit CvSetElem structure. The \texttt{flags} fields are
5783 used as for indicating occupied vertices and edges as well as for other
5784 purposes, for example, for graph traversal (see \cross{CreateGraphScanner}
5785 et al.), so it is better not to use them directly.
5786
5787 The graph is represented as a set of edges each of whose has the list of
5788 incident edges. The incidence lists for different vertices are interleaved
5789 to avoid information duplication as much as posssible.
5790
5791 The graph may be oriented or unoriented. In the latter case there is no
5792 distiction between edge connecting vertex $A$ with vertex $B$ and the edge
5793 connecting vertex $B$ with vertex $A$ - only one of them can exist in the
5794 graph at the same moment and it represents both $A \rightarrow B$ and
5795 $B \rightarrow A$ edges..
5796
5797 \cvfunc{CreateGraph}\label{CreateGraph}
5798
5799 Creates empty graph
5800
5801 \cvexp{
5802
5803 CvGraph* cvCreateGraph( \par int graph\_flags,\par int header\_size,\par int vtx\_size,\par int edge\_size,\par CvMemStorage* storage );
5804
5805 }{CPP}{PYTHON}
5806
5807 \begin{description}
5808 \cvarg{graph\_flags}{Type of the created graph. Usually, it is either \texttt{CV\_SEQ\_KIND\_GRAPH} for generic unoriented graphs and
5809 \texttt{CV\_SEQ\_KIND\_GRAPH | CV\_GRAPH\_FLAG\_ORIENTED} for generic oriented graphs.}
5810 \cvarg{header\_size}{Graph header size; may not be less than \texttt{sizeof(CvGraph)}}
5811 \cvarg{vtx\_size}{Graph vertex size; the custom vertex structure must start with \cross{CvGraphVtx} (use 'CV\_GRAPH\_VERTEX\_FIELDS()')}
5812 \cvarg{edge\_size}{Graph edge size; the custom edge structure must start with \cross{CvGraphEdge} (use 'CV\_GRAPH\_EDGE\_FIELDS()')}
5813 \cvarg{storage}{The graph container}
5814 \end{description}
5815
5816 The function \texttt{cvCreateGraph} creates an empty graph and returns pointer to it.
5817
5818 \cvfunc{GraphAddVtx}\label{GraphAddVtx}
5819
5820 Adds vertex to graph
5821
5822 \cvexp{
5823
5824 int cvGraphAddVtx( \par CvGraph* graph,\par const CvGraphVtx* vtx=NULL,\par CvGraphVtx** inserted\_vtx=NULL );
5825
5826 }{CPP}{PYTHON}
5827
5828 \begin{description}
5829 \cvarg{graph}{Graph}
5830 \cvarg{vtx}{Optional input argument used to initialize the added vertex (only user-defined fields beyond 'sizeof(CvGraphVtx)' are copied)}
5831 \cvarg{inserted\_vertex}{Optional output argument. If not \texttt{NULL}, the address of the new vertex is written there.}
5832 \end{description}
5833
5834 The function \texttt{cvGraphAddVtx} adds a vertex to the graph and returns the vertex index.
5835
5836 \cvfunc{GraphRemoveVtx}\label{GraphRemoveVtx}
5837
5838 Removes vertex from graph
5839
5840 \cvexp{
5841
5842 int cvGraphRemoveVtx( \par CvGraph* graph,\par int index );
5843
5844 }{CPP}{PYTHON}
5845
5846 \begin{description}
5847 \cvarg{graph}{Graph}
5848 \cvarg{vtx\_idx}{Index of the removed vertex}
5849 \end{description}
5850
5851 The function \texttt{cvGraphRemoveAddVtx} removes a vertex from the graph
5852 together with all the edges incident to it. The function reports an error,
5853 if the input vertex does not belong to the graph. The return value is
5854 number of edges deleted, or -1 if the vertex does not belong to the graph.
5855
5856 \cvfunc{GraphRemoveVtxByPtr}\label{GraphRemoveVtxByPtr}
5857
5858 Removes vertex from graph
5859
5860 \cvexp{
5861
5862 int cvGraphRemoveVtxByPtr( \par CvGraph* graph,\par CvGraphVtx* vtx );
5863
5864 }{CPP}{PYTHON}
5865
5866 \begin{description}
5867 \cvarg{graph}{Graph}
5868 \cvarg{vtx}{Pointer to the removed vertex}
5869 \end{description}
5870
5871
5872 The function \texttt{cvGraphRemoveVtxByPtr} removes a vertex from the graph together with all the edges incident to it. The function reports an error, if the vertex does not belong to the graph. The return value is number of edges deleted, or -1 if the vertex does not belong to the graph.
5873
5874 \cvfunc{GetGraphVtx}\label{GetGraphVtx}
5875
5876 Finds graph vertex by index
5877
5878 \cvexp{
5879
5880 CvGraphVtx* cvGetGraphVtx( \par CvGraph* graph,\par int vtx\_idx );
5881
5882 }{CPP}{PYTHON}
5883
5884 \begin{description}
5885 \cvarg{graph}{Graph}
5886 \cvarg{vtx\_idx}{Index of the vertex}
5887 \end{description}
5888
5889
5890 The function \texttt{cvGetGraphVtx} finds the graph vertex by index and returns the pointer to it or NULL if the vertex does not belong to the graph.
5891
5892
5893 \cvfunc{GraphVtxIdx}\label{GraphVtxIdx}
5894
5895 Returns index of graph vertex
5896
5897 \cvexp{
5898
5899 int cvGraphVtxIdx( \par CvGraph* graph,\par CvGraphVtx* vtx );
5900
5901 }{CPP}{PYTHON}
5902
5903 \begin{description}
5904 \cvarg{graph}{Graph}
5905 \cvarg{vtx}{Pointer to the graph vertex}
5906 \end{description}
5907
5908 The function \texttt{cvGraphVtxIdx} returns index of the graph vertex.
5909
5910 \cvfunc{GraphAddEdge}\label{GraphAddEdge}
5911
5912 Adds edge to graph
5913
5914 \cvexp{
5915
5916 int cvGraphAddEdge( \par CvGraph* graph,\par int start\_idx,\par int end\_idx,\par const CvGraphEdge* edge=NULL,\par CvGraphEdge** inserted\_edge=NULL );
5917
5918 }{CPP}{PYTHON}
5919
5920 \begin{description}
5921 \cvarg{graph}{Graph}
5922 \cvarg{start\_idx}{Index of the starting vertex of the edge}
5923 \cvarg{end\_idx}{Index of the ending vertex of the edge. For unoriented graph the order of the vertex parameters does not matter.}
5924 \cvarg{edge}{Optional input parameter, initialization data for the edge}
5925 \cvarg{inserted\_edge}{Optional output parameter to contain the address of the inserted edge}
5926 \end{description}
5927
5928
5929 The function \texttt{cvGraphAddEdge} connects two specified vertices. The function returns 1 if the edge has been added successfully, 0 if the edge connecting the two vertices exists already and -1 if either of the vertices was not found, the starting and the ending vertex are the same or there is some other critical situation. In the latter case (i.e. when the result is negative) the function also reports an error by default.
5930
5931 \cvfunc{GraphAddEdgeByPtr}\label{GraphAddEdgeByPtr}
5932
5933 Adds edge to graph
5934
5935 \cvexp{
5936
5937 int cvGraphAddEdgeByPtr( \par CvGraph* graph,\par CvGraphVtx* start\_vtx,\par CvGraphVtx* end\_vtx,\par const CvGraphEdge* edge=NULL,\par CvGraphEdge** inserted\_edge=NULL );
5938
5939 }{CPP}{PYTHON}
5940
5941 \begin{description}
5942 \cvarg{graph}{Graph}
5943 \cvarg{start\_vtx}{Pointer to the starting vertex of the edge}
5944 \cvarg{end\_vtx}{Pointer to the ending vertex of the edge. For unoriented graph the order of the vertex parameters does not matter.}
5945 \cvarg{edge}{Optional input parameter, initialization data for the edge}
5946 \cvarg{inserted\_edge}{Optional output parameter to contain the address of the inserted edge within the edge set}
5947 \end{description}
5948
5949 The function \texttt{cvGraphAddEdge} connects two specified vertices. The
5950 function returns 1 if the edge has been added successfully, 0 if the
5951 edge connecting the two vertices exists already and -1 if either of the
5952 vertices was not found, the starting and the ending vertex are the same
5953 or there is some other critical situation. In the latter case (i.e. when
5954 the result is negative) the function also reports an error by default.
5955
5956 \cvfunc{GraphRemoveEdge}\label{GraphRemoveEdge}
5957
5958 Removes edge from graph
5959
5960 \cvexp{
5961
5962 void cvGraphRemoveEdge( \par CvGraph* graph,\par int start\_idx,\par int end\_idx );
5963
5964 }{CPP}{PYTHON}
5965
5966 \begin{description}
5967 \cvarg{graph}{Graph}
5968 \cvarg{start\_idx}{Index of the starting vertex of the edge}
5969 \cvarg{end\_idx}{Index of the ending vertex of the edge. For unoriented graph the order of the vertex parameters does not matter.}
5970 \end{description}
5971
5972 The function \texttt{cvGraphRemoveEdge} removes the edge connecting two specified vertices. If the vertices are not connected [in that order], the function does nothing.
5973
5974 \cvfunc{GraphRemoveEdgeByPtr}\label{GraphRemoveEdgeByPtr}
5975
5976 Removes edge from graph
5977
5978 \cvexp{
5979
5980 void cvGraphRemoveEdgeByPtr( \par CvGraph* graph,\par CvGraphVtx* start\_vtx,\par CvGraphVtx* end\_vtx );
5981
5982 }{CPP}{PYTHON}
5983
5984 \begin{description}
5985 \cvarg{graph}{Graph}
5986 \cvarg{start\_vtx}{Pointer to the starting vertex of the edge}
5987 \cvarg{end\_vtx}{Pointer to the ending vertex of the edge. For unoriented graph the order of the vertex parameters does not matter.}
5988 \end{description}
5989
5990 The function \texttt{cvGraphRemoveEdgeByPtr} removes the edge connecting two specified vertices. If the vertices are not connected [in that order], the function does nothing.
5991
5992 \cvfunc{FindGraphEdge}\label{FindGraphEdge}
5993
5994 Finds edge in graph
5995
5996 \cvexp{
5997
5998 CvGraphEdge* cvFindGraphEdge( const CvGraph* graph, int start\_idx, int end\_idx );
5999
6000 }{CPP}{PYTHON}
6001
6002 \begin{lstlisting}
6003
6004 #define cvGraphFindEdge cvFindGraphEdge
6005
6006 \end{lstlisting}
6007
6008 \begin{description}
6009 \cvarg{graph}{Graph}
6010 \cvarg{start\_idx}{Index of the starting vertex of the edge}
6011 \cvarg{end\_idx}{Index of the ending vertex of the edge. For unoriented graph the order of the vertex parameters does not matter.}
6012 \end{description}
6013
6014 The function \texttt{cvFindGraphEdge} finds the graph edge connecting two specified vertices and returns pointer to it or NULL if the edge does not exists.
6015
6016 \cvfunc{FindGraphEdgeByPtr}\label{FindGraphEdgeByPtr}
6017
6018 Finds edge in graph
6019
6020 \cvexp{
6021
6022 CvGraphEdge* cvFindGraphEdgeByPtr( \par const CvGraph* graph,\par const CvGraphVtx* start\_vtx,\par const CvGraphVtx* end\_vtx );
6023
6024 }{CPP}{PYTHON}
6025
6026 \begin{lstlisting}
6027 \#define cvGraphFindEdgeByPtr cvFindGraphEdgeByPtr
6028 \end{lstlisting}
6029
6030 \begin{description}
6031 \cvarg{graph}{Graph}
6032 \cvarg{start\_vtx}{Pointer to the starting vertex of the edge}
6033 \cvarg{end\_vtx}{Pointer to the ending vertex of the edge. For unoriented graph the order of the vertex parameters does not matter.}
6034 \end{description}
6035
6036 The function \texttt{cvFindGraphEdge} finds the graph edge connecting two specified vertices and returns pointer to it or NULL if the edge does not exists.
6037
6038 \cvfunc{GraphEdgeIdx}\label{GraphEdgeIdx}
6039
6040 Returns index of graph edge
6041
6042 \cvexp{
6043
6044 int cvGraphEdgeIdx( \par CvGraph* graph,\par CvGraphEdge* edge );
6045
6046 }{CPP}{PYTHON}
6047
6048 \begin{description}
6049 \cvarg{graph}{Graph}
6050 \cvarg{edge}{Pointer to the graph edge}
6051 \end{description}
6052
6053 The function \texttt{cvGraphEdgeIdx} returns index of the graph edge.
6054
6055 \cvfunc{GraphVtxDegree}\label{GraphVtxDegree}
6056
6057 Counts edges indicent to the vertex
6058
6059 \cvexp{
6060
6061 int cvGraphVtxDegree( const CvGraph* graph, int vtx\_idx );
6062
6063 }{CPP}{PYTHON}
6064
6065 \begin{description}
6066 \cvarg{graph}{Graph}
6067 \cvarg{vtx}{Index of the graph vertex}
6068 \end{description}
6069
6070 The function \texttt{cvGraphVtxDegree} returns the number of edges incident to the specified vertex, both incoming and outcoming. To count the edges, the following code is used:
6071
6072 \begin{lstlisting}
6073
6074 CvGraphEdge* edge = vertex->first; int count = 0;
6075 while( edge )
6076 {
6077     edge = CV_NEXT_GRAPH_EDGE( edge, vertex );
6078     count++;
6079 }
6080
6081 \end{lstlisting}
6082
6083 The macro \texttt{CV\_NEXT\_GRAPH\_EDGE( edge, vertex )} returns the edge incident to \texttt{vertex} that follows after \texttt{edge}.
6084
6085 \cvfunc{GraphVtxDegreeByPtr}\label{GraphVtxDegreeByPtr}
6086
6087 Finds edge in graph
6088
6089 \cvexp{
6090
6091 int cvGraphVtxDegreeByPtr( \par const CvGraph* graph,\par const CvGraphVtx* vtx );
6092
6093 }{CPP}{PYTHON}
6094
6095 \begin{description}
6096 \cvarg{graph}{Graph}
6097 \cvarg{vtx}{Pointer to the graph vertex}
6098 \end{description}
6099
6100 The function \texttt{cvGraphVtxDegree} returns the number of edges incident to the specified vertex, both incoming and outcoming.
6101
6102
6103 \cvfunc{ClearGraph}\label{ClearGraph}
6104
6105 Clears graph
6106
6107 \cvexp{
6108
6109 void cvClearGraph( CvGraph* graph );
6110
6111 }{CPP}{PYTHON}
6112
6113 \begin{description}
6114 \cvarg{graph}{Graph}
6115 \end{description}
6116
6117 The function \texttt{cvClearGraph} removes all vertices and edges from the graph. The function has O(1) time complexity.
6118
6119 \cvfunc{CloneGraph}\label{CloneGraph}
6120
6121 Clone graph
6122
6123 \cvexp{
6124
6125 CvGraph* cvCloneGraph( \par const CvGraph* graph,\par CvMemStorage* storage );
6126
6127 }{CPP}{PYTHON}
6128
6129 \begin{description}
6130 \cvarg{graph}{The graph to copy}
6131 \cvarg{storage}{Container for the copy}
6132 \end{description}
6133
6134
6135 The function \texttt{cvCloneGraph} creates full copy of the graph. If the
6136 graph vertices or edges have pointers to some external data, it still be
6137 shared between the copies. The vertex and edge indices in the new graph
6138 may be different from the original, because the function defragments
6139 the vertex and edge sets.
6140
6141
6142 \cvstruct{CvGraphScanner}\label{CvGraphScanner}
6143
6144 Graph traversal state
6145
6146 \begin{lstlisting}
6147
6148 typedef struct CvGraphScanner
6149 {
6150     CvGraphVtx* vtx;       /* current graph vertex (or current edge origin) */
6151     CvGraphVtx* dst;       /* current graph edge destination vertex */
6152     CvGraphEdge* edge;     /* current edge */
6153
6154     CvGraph* graph;        /* the graph */
6155     CvSeq*   stack;        /* the graph vertex stack */
6156     int      index;        /* the lower bound of certainly visited vertices */
6157     int      mask;         /* event mask */
6158 }
6159 CvGraphScanner;
6160
6161 \end{lstlisting}
6162
6163 The structure \cross{CvGraphScanner} is used for depth-first graph traversal. See discussion of the functions below.
6164
6165
6166 \cvfunc{CreateGraphScanner}\label{CreateGraphScanner}
6167
6168 Creates structure for depth-first graph traversal
6169
6170 \cvexp{
6171
6172 CvGraphScanner*  cvCreateGraphScanner( \par CvGraph* graph,\par CvGraphVtx* vtx=NULL,\par int mask=CV\_GRAPH\_ALL\_ITEMS );
6173
6174 }{CPP}{PYTHON}
6175
6176 \begin{description}
6177 \cvarg{graph}{Graph}
6178 \cvarg{vtx}{Initial vertex to start from. If NULL, the traversal starts from the first vertex (a vertex with the minimal index in the sequence of vertices).}
6179 \cvarg{mask}{Event mask indicating which events are interesting to the user (where \cross{NextGraphItem} function returns control to the user) It can be \texttt{CV\_GRAPH\_ALL\_ITEMS} (all events are interesting) or combination of the following flags:
6180
6181 \begin{description}
6182 \cvarg{CV\_GRAPH\_VERTEX}{stop at the graph vertices visited for the first time}
6183 \cvarg{CV\_GRAPH\_TREE\_EDGE}{stop at tree edges ('tree edge' is the edge connecting the last visited vertex and the vertex to be visited next)}
6184 \cvarg{CV\_GRAPH\_BACK\_EDGE}{stop at back edges ('back edge' is an edge connecting the last visited vertex with some of its ancestors in the search tree)}
6185 \cvarg{CV\_GRAPH\_FORWARD\_EDGE}{stop at forward edges ('forward edge' is an edge conecting the last visited vertex with some of its descendants in the search tree). The 'forward edges' are only possible during oriented graph traversal)}
6186 \cvarg{CV\_GRAPH\_CROSS\_EDGE}{stop at cross edges ('cross edge' is an edge connecting different search trees or branches of the same tree. The 'cross edges' are only possible during oriented graphs traversal)}
6187 \cvarg{CV\_GRAPH\_ANY\_EDGE}{stop and any edge ('tree, back, forward' and 'cross edges')}
6188 \cvarg{CV\_GRAPH\_NEW\_TREE}{stop in the beginning of every new search tree. When the traversal procedure visits all vertices and edges reachible from the initial vertex (the visited vertices together with tree edges make up a tree), it searches for some unvisited vertex in the graph and resumes the traversal process from that vertex. Before starting a new tree (including the very first tree when \texttt{cvNextGraphItem} is called for the first time) it generates \texttt{CV\_GRAPH\_NEW\_TREE} event. For unoriented graphs each search tree corresponds to a connected component of the graph.}
6189 \cvarg{CV\_GRAPH\_BACKTRACKING}{stop at every already visited vertex during backtracking - returning to already visited vertexes of the traversal tree.}
6190 \end{description}}
6191 \end{description}
6192
6193 The function \texttt{cvCreateGraphScanner} creates structure for depth-first graph traversal/search. The initialized structure is used in \cross{NextGraphItem} function - the incremental traversal procedure.
6194
6195 \cvfunc{NextGraphItem}\label{NextGraphItem}
6196
6197 Makes one or more steps of the graph traversal procedure
6198
6199 \cvexp{
6200
6201 int cvNextGraphItem( CvGraphScanner* scanner );
6202
6203 }{CPP}{PYTHON}
6204
6205 \begin{description}
6206 \cvarg{scanner}{Graph traversal state. It is updated by the function.}
6207 \end{description}
6208
6209 The function \texttt{cvNextGraphItem} traverses through the graph
6210 until an event interesting to the user (that is, an event, specified
6211 in the \texttt{mask} in \cross{CreateGraphScanner} call) is met or the
6212 traversal is over. In the first case it returns one of the events,
6213 listed in the description of \texttt{mask} parameter above and with
6214 the next call it resumes the traversal. In the latter case it returns
6215 \texttt{CV\_GRAPH\_OVER} (-1). When the event is \texttt{CV\_GRAPH\_VERTEX},
6216 or \texttt{CV\_GRAPH\_BACKTRACKING} or \texttt{CV\_GRAPH\_NEW\_TREE},
6217 the currently observed vertex is stored in 'scanner->vtx'. And if the
6218 event is edge-related, the edge itself is stored at 'scanner->edge',
6219 the previously visited vertex - at 'scanner->vtx' and the other ending
6220 vertex of the edge - at 'scanner->dst'.
6221
6222 \cvfunc{ReleaseGraphScanner}\label{ReleaseGraphScanner}
6223
6224 Finishes graph traversal procedure
6225
6226 \cvexp{
6227
6228 void cvReleaseGraphScanner( CvGraphScanner** scanner );
6229
6230 }{CPP}{PYTHON}
6231
6232 \begin{description}
6233 \cvarg{scanner}{Double pointer to graph traverser}
6234 \end{description}
6235
6236
6237 The function \texttt{cvGraphScanner} finishes graph traversal procedure and releases the traverser state.
6238
6239
6240 \subsection{Trees}
6241
6242
6243 \cvmacro{CV\_TREE\_NODE\_FIELDS}\label{CV_TREE_NODE_FIELDS}
6244
6245 Helper macro for a tree node type declaration
6246
6247 \begin{lstlisting}
6248
6249 #define CV_TREE_NODE_FIELDS(node_type)                          \
6250     int       flags;         /* micsellaneous flags */          \
6251     int       header_size;   /* size of sequence header */      \
6252     struct    node_type* h_prev; /* previous sequence */        \
6253     struct    node_type* h_next; /* next sequence */            \
6254     struct    node_type* v_prev; /* 2nd previous sequence */    \
6255     struct    node_type* v_next; /* 2nd next sequence */
6256
6257 \end{lstlisting}
6258
6259 The macro \texttt{CV\_TREE\_NODE\_FIELDS()} is used to declare structures
6260 that can be organized into hierarchical strucutures (trees), such as
6261 \cross{CvSeq} - the basic type for all dynamical structures. The trees
6262 made of nodes declared using this macro can be processed using the
6263 functions described below in this section.
6264
6265 \cvstruct{CvTreeNodeIterator}\label{CvTreeNodeIterator}
6266
6267 Opens existing or creates new file storage
6268
6269 \begin{lstlisting}
6270
6271 typedef struct CvTreeNodeIterator
6272 {
6273     const void* node;
6274     int level;
6275     int max_level;
6276 }
6277 CvTreeNodeIterator;
6278
6279 \end{lstlisting}
6280
6281 The structure \cross{CvTreeNodeIterator} is used to traverse trees. The tree node declaration should start with 'CV\_TREE\_NODE\_FIELDS(...)' macro.
6282
6283 \cvfunc{InitTreeNodeIterator}\label{InitTreeNodeIterator}
6284
6285 Initializes tree node iterator
6286
6287 \cvexp{
6288
6289 void cvInitTreeNodeIterator( \par CvTreeNodeIterator* tree\_iterator,\par const void* first,\par int max\_level );
6290
6291 }{CPP}{PYTHON}
6292
6293 \begin{description}
6294 \cvarg{tree\_iterator}{Tree iterator initialized by the function}
6295 \cvarg{first}{The initial node to start traversing from}
6296 \cvarg{max\_level}{The maximal level of the tree (\texttt{first} node assumed to be at the first level) to traverse up to. For example, 1 means that only nodes at the same level as \texttt{first} should be visited, 2 means that the nodes on the same level as \texttt{first} and their direct children should be visited etc.}
6297 \end{description}
6298
6299 The function \texttt{cvInitTreeNodeIterator} initializes tree iterator. The tree is traversed in depth-first order.
6300
6301 \cvfunc{NextTreeNode}\label{NextTreeNode}
6302
6303 Returns the currently observed node and moves iterator toward the next node
6304
6305 \cvexp{
6306
6307 void* cvNextTreeNode( CvTreeNodeIterator* tree\_iterator );
6308
6309 }{CPP}{PYTHON}
6310
6311 \begin{description}
6312 \cvarg{tree\_iterator}{Tree iterator initialized by the function}
6313 \end{description}
6314
6315
6316 The function \texttt{cvNextTreeNode} returns the currently observed node and then updates the iterator - moves it toward the next node. In other words, the function behavior is similar to *p++ expression on usual C pointer or C++ collection iterator. The function returns NULL if there is no more nodes.
6317
6318
6319 \cvfunc{PrevTreeNode}\label{PrevTreeNode}
6320
6321 Returns the currently observed node and moves iterator toward the previous node
6322
6323 \cvexp{
6324
6325 void* cvPrevTreeNode( CvTreeNodeIterator* tree\_iterator );
6326
6327 }{CPP}{PYTHON}
6328
6329 \begin{description}
6330 \cvarg{tree\_iterator}{Tree iterator initialized by the function}
6331 \end{description}
6332
6333
6334 The function \texttt{cvPrevTreeNode} returns the currently observed node and then updates the iterator - moves it toward the previous node. In other words, the function behavior is similar to *p-- expression on usual C pointer or C++ collection iterator. The function returns NULL if there is no more nodes.
6335
6336
6337 \cvfunc{TreeToNodeSeq}\label{TreeToNodeSeq}
6338
6339 Gathers all node pointers to the single sequence
6340
6341 \cvexp{
6342
6343 CvSeq* cvTreeToNodeSeq( \par const void* first,\par int header\_size,\par CvMemStorage* storage );
6344
6345 }{CPP}{PYTHON}
6346
6347 \begin{description}
6348 \cvarg{first}{The initial tree node}
6349 \cvarg{header\_size}{Header size of the created sequence (sizeof(CvSeq) is the most used value)}
6350 \cvarg{storage}{Container for the sequence}
6351 \end{description}
6352
6353 The function \texttt{cvTreeToNodeSeq} puts pointers of all nodes reacheable from \texttt{first} to the single sequence. The pointers are written subsequently in the depth-first order.
6354
6355 \cvfunc{InsertNodeIntoTree}\label{InsertNodeIntoTree}
6356
6357 Adds new node to the tree
6358
6359 \cvexp{
6360
6361 void cvInsertNodeIntoTree( \par void* node,\par void* parent,\par void* frame );
6362
6363 }{CPP}{PYTHON}
6364
6365 \begin{description}
6366 \cvarg{node}{The inserted node}
6367 \cvarg{parent}{The parent node that is already in the tree}
6368 \cvarg{frame}{The top level node. If \texttt{parent} and \texttt{frame} are the same, \texttt{v\_prev} field of \texttt{node} is set to NULL rather than \texttt{parent}.}
6369 \end{description}
6370
6371 The function \texttt{cvInsertNodeIntoTree} adds another node into tree. The function does not allocate any memory, it can only modify links of the tree nodes.
6372
6373 \cvfunc{RemoveNodeFromTree}\label{RemoveNodeFromTree}
6374
6375 Removes node from tree
6376
6377 \cvexp{
6378
6379 void cvRemoveNodeFromTree( \par void* node,\par void* frame );
6380
6381 }{CPP}{PYTHON}
6382
6383 \begin{description}
6384 \cvarg{node}{The removed node}
6385 \cvarg{frame}{The top level node. If 'node->v\_prev = NULL' and 'node->h\_prev' is NULL (i.e. if \texttt{node} is the first child of \texttt{frame}), 'frame->v\_next' is set to 'node->h\_next' (i.e. the first child or frame is changed).}
6386 \end{description}
6387
6388 The function \texttt{cvRemoveNodeFromTree} removes node from tree. The function does not deallocate any memory, it can only modify links of the tree nodes.
6389
6390 \section{Drawing Functions}
6391
6392 Drawing functions work with matrices/images or arbitrary depth.
6393 Antialiasing is implemented only for 8-bit images. All the functions
6394 include parameter color that means rgb value (that may be constructed
6395 with \texttt{CV\_RGB} macro or \texttt{cvScalar} function) for color
6396 images and brightness for grayscale images.
6397
6398 If a drawn figure is partially or completely outside the image, it
6399 is clipped. For color images the order channel is: Blue Green Red
6400 ... If one needs a different channel order, it is possible to
6401 construct color via \texttt{cvScalar} with the particular channel
6402 order, or convert the image before and/or after drawing in it with
6403 \cross{CvtColor} or \cross{Transform}.
6404
6405 \subsection{Curves and Shapes}
6406
6407 \cvfunc{CV\_RGB}\label{CV_RGB}
6408
6409 Constructs a color value
6410
6411 \cvexp{
6412 \#define CV\_RGB( r, g, b )  cvScalar( (b), (g), (r) )
6413 }{CPP}{PYTHON}
6414
6415 \cvfunc{Line}\label{Line}
6416
6417 Draws a line segment connecting two points
6418
6419 \cvexp{
6420 void cvLine( \par CvArr* img,\par CvPoint pt1,\par CvPoint pt2,\par CvScalar color,\par int thickness=1,\par int line\_type=8,\par int shift=0 );
6421 }{CPP}{PYTHON}
6422
6423 \begin{description}
6424 \cvarg{img}{The image}
6425 \cvarg{pt1}{First point of the line segment}
6426 \cvarg{pt2}{Second point of the line segment}
6427 \cvarg{color}{Line color}
6428 \cvarg{thickness}{Line thickness}
6429 \cvarg{line\_type}{Type of the line:
6430   \begin{description}
6431   \cvarg{8}{(or omitted) 8-connected line.}
6432   \cvarg{4}{4-connected line.}
6433   \cvarg{CV\_AA}{antialiased line.}
6434   \end{description}}
6435 \cvarg{shift}{Number of fractional bits in the point coordinates}
6436 \end{description}
6437
6438 The function \texttt{cvLine} draws the line segment between
6439 \texttt{pt1} and \texttt{pt2} points in the image. The line is
6440 clipped by the image or ROI rectangle. For non-antialiased lines
6441 with integer coordinates the 8-connected or 4-connected Bresenham
6442 algorithm is used. Thick lines are drawn with rounding endings.
6443 Antialiased lines are drawn using Gaussian filtering. To specify
6444 the line color, the user may use the macro
6445 \texttt{CV\_RGB( r, g, b )}.
6446
6447 \cvfunc{Rectangle}\label{Rectangle}
6448
6449 Draws simple, thick or filled rectangle
6450
6451 \cvexp{
6452
6453 void cvRectangle( \par CvArr* img,\par CvPoint pt1,\par CvPoint pt2,\par CvScalar color,\par int thickness=1,\par int line\_type=8,\par int shift=0 );
6454
6455 }{CPP}{PYTHON}
6456
6457 \begin{description}
6458 \cvarg{img}{Image}
6459 \cvarg{pt1}{One of the rectangle vertices}
6460 \cvarg{pt2}{Opposite rectangle vertex}
6461 \cvarg{color}{Line color (RGB) or brightness (grayscale image)}
6462 \cvarg{thickness}{Thickness of lines that make up the rectangle. Negative values, e.g. CV\_FILLED, make the function to draw a filled rectangle.}
6463 \cvarg{line\_type}{Type of the line, see \cross{Line} description}
6464 \cvarg{shift}{Number of fractional bits in the point coordinates}
6465 \end{description}
6466
6467 The function \texttt{cvRectangle} draws a rectangle with two opposite corners \texttt{pt1} and \texttt{pt2}.
6468
6469 \cvfunc{Circle}\label{Circle}
6470
6471 Draws a circle
6472
6473 \cvexp{
6474
6475 void cvCircle( \par CvArr* img,\par CvPoint center,\par int radius,\par CvScalar color,\par int thickness=1,\par int line\_type=8,\par int shift=0 );
6476
6477 }{CPP}{PYTHON}
6478
6479 \begin{description}
6480 \cvarg{img}{Image where the circle is drawn}
6481 \cvarg{center}{Center of the circle}
6482 \cvarg{radius}{Radius of the circle}
6483 \cvarg{color}{Circle color}
6484 \cvarg{thickness}{Thickness of the circle outline if positive, otherwise indicates that a filled circle has to be drawn}
6485 \cvarg{line\_type}{Type of the circle boundary, see \cross{Line} description}
6486 \cvarg{shift}{Number of fractional bits in the center coordinates and radius value}
6487 \end{description}
6488
6489 The function \texttt{cvCircle} draws a simple or filled circle with
6490 given center and radius. The circle is clipped by ROI rectangle.
6491 To specify the circle color, the user may use the macro
6492 \texttt{CV\_RGB( r, g, b )}.
6493
6494 \cvfunc{Ellipse}\label{Ellipse}
6495
6496 Draws simple or thick elliptic arc or fills ellipse sector
6497
6498 \cvexp{
6499
6500 void cvEllipse( \par CvArr* img,\par CvPoint center,\par CvSize axes,\par double angle,\par double start\_angle,\par double end\_angle,\par CvScalar color,\par int thickness=1,\par int line\_type=8,\par int shift=0 );
6501
6502 }{CPP}{PYTHON}
6503
6504 \begin{description}
6505 \cvarg{img}{The image}
6506 \cvarg{center}{Center of the ellipse}
6507 \cvarg{axes}{Length of the ellipse axes}
6508 \cvarg{angle}{Rotation angle}
6509 \cvarg{start\_angle}{Starting angle of the elliptic arc}
6510 \cvarg{end\_angle}{Ending angle of the elliptic arc.}
6511 \cvarg{color}{Ellipse color}
6512 \cvarg{thickness}{Thickness of the ellipse arc outline if positive, otherwise indicates that a filled ellipse sector has to be drawn}
6513 \cvarg{line\_type}{Type of the ellipse boundary, see \cross{Line} description}
6514 \cvarg{shift}{Number of fractional bits in the center coordinates and axes' values}
6515 \end{description}
6516
6517 The function \texttt{cvEllipse} draws a simple or thick elliptic
6518 arc or fills an ellipse sector. The arc is clipped by ROI rectangle.
6519 A piecewise-linear approximation is used for antialiased arcs and
6520 thick arcs. All the angles are given in degrees. The picture below
6521 explains the meaning of the parameters.
6522
6523 Parameters of Elliptic Arc
6524
6525 \includegraphics[width=0.5\textwidth]{pics/ellipse.png}
6526
6527 \cvfunc{FillPoly}\label{FillPoly}
6528
6529 Fills polygons interior
6530
6531 \cvexp{
6532
6533 void cvFillPoly( \par CvArr* img,\par CvPoint** pts,\par int* npts,\par int contours,\par CvScalar color,\par int line\_type=8,\par int shift=0 );
6534
6535 }{CPP}{PYTHON}
6536
6537 \begin{description}
6538 \cvarg{img}{Image}
6539 \cvarg{pts}{Array of pointers to polygons}
6540 \cvarg{npts}{Array of polygon vertex counters}
6541 \cvarg{contours}{Number of contours that bind the filled region}
6542 \cvarg{color}{Polygon color}
6543 \cvarg{line\_type}{Type of the polygon boundaries, see \cross{Line} description}
6544 \cvarg{shift}{Number of fractional bits in the vertex coordinates}
6545 \end{description}
6546
6547
6548 The function \texttt{cvFillPoly} fills an area bounded by several
6549 polygonal contours. The function fills complex areas, for example,
6550 areas with holes, contour self-intersection, etc.
6551
6552 \cvfunc{FillConvexPoly}\label{FillConvexPoly}
6553
6554 Fills convex polygon
6555
6556 \cvexp{
6557
6558 void cvFillConvexPoly( \par CvArr* img,\par CvPoint* pts,\par int npts,\par CvScalar color,\par int line\_type=8,\par int shift=0 );
6559
6560 }{CPP}{PYTHON}
6561
6562 \begin{description}
6563 \cvarg{img}{Image}
6564 \cvarg{pts}{Array of pointers to a single polygon}
6565 \cvarg{npts}{Polygon vertex counter}
6566 \cvarg{color}{Polygon color}
6567 \cvarg{line\_type}{Type of the polygon boundaries, see \cross{Line} description}
6568 \cvarg{shift}{Number of fractional bits in the vertex coordinates}
6569 \end{description}
6570
6571 The function \texttt{cvFillConvexPoly} fills convex polygon interior.
6572 This function is much faster than The function \texttt{cvFillPoly}
6573 and can fill not only the convex polygons but any monotonic polygon,
6574 i.e. a polygon whose contour intersects every horizontal line (scan
6575 line) twice at the most.
6576
6577
6578 \cvfunc{PolyLine}\label{PolyLine}
6579
6580 Draws simple or thick polygons
6581
6582 \cvexp{
6583
6584 void cvPolyLine( \par CvArr* img,\par CvPoint** pts,\par int* npts,\par int contours,\par int is\_closed,\par CvScalar color,\par int thickness=1,\par int line\_type=8,\par int shift=0 );
6585
6586 }{CPP}{PYTHON}
6587
6588 \begin{description}
6589 \cvarg{img}{Image}
6590 \cvarg{pts}{Array of pointers to polylines}
6591 \cvarg{npts}{Array of polyline vertex counters}
6592 \cvarg{contours}{Number of polyline contours}
6593 \cvarg{is\_closed}{Indicates whether the polylines must be drawn
6594 closed. If closed, the function draws the line from the last vertex
6595 of every contour to the first vertex.}
6596 \cvarg{color}{Polyline color}
6597 \cvarg{thickness}{Thickness of the polyline edges}
6598 \cvarg{line\_type}{Type of the line segments, see \cross{Line} description}
6599 \cvarg{shift}{Number of fractional bits in the vertex coordinates}
6600 \end{description}
6601
6602 The function \texttt{cvPolyLine} draws a single or multiple polygonal curves.
6603
6604 \subsection{Text}
6605
6606 \cvfunc{InitFont}\label{InitFont}
6607
6608 Initializes font structure
6609
6610 \cvexp{
6611 void cvInitFont( \par CvFont* font,\par int font\_face,\par double hscale,\par double vscale,\par double shear=0,\par int thickness=1,\par int line\_type=8 );
6612 }{CPP}{PYTHON}
6613
6614 \begin{description}
6615 \cvarg{font}{Pointer to the font structure initialized by the function}
6616 \cvarg{font\_face}{Font name identifier. Only a subset of Hershey fonts \url{http://sources.isc.org/utils/misc/hershey-font.txt} are supported now:
6617  \begin{description}
6618  \cvarg{CV\_FONT\_HERSHEY\_SIMPLEX}{normal size sans-serif font}
6619  \cvarg{CV\_FONT\_HERSHEY\_PLAIN}{small size sans-serif font}
6620  \cvarg{CV\_FONT\_HERSHEY\_DUPLEX}{normal size sans-serif font (more complex than \texttt{CV\_FONT\_HERSHEY\_SIMPLEX})}
6621  \cvarg{CV\_FONT\_HERSHEY\_COMPLEX}{normal size serif font}
6622  \cvarg{CV\_FONT\_HERSHEY\_TRIPLEX}{normal size serif font (more complex than \texttt{CV\_FONT\_HERSHEY\_COMPLEX})}
6623  \cvarg{CV\_FONT\_HERSHEY\_COMPLEX\_SMALL}{smaller version of \texttt{CV\_FONT\_HERSHEY\_COMPLEX}}
6624  \cvarg{CV\_FONT\_HERSHEY\_SCRIPT\_SIMPLEX}{hand-writing style font}
6625  \cvarg{CV\_FONT\_HERSHEY\_SCRIPT\_COMPLEX}{more complex variant of \texttt{CV\_FONT\_HERSHEY\_SCRIPT\_SIMPLEX}}
6626  \end{description}
6627  The parameter can be composited from one of the values above and optional \texttt{CV\_FONT\_ITALIC} flag, that means italic or oblique font.}
6628 \cvarg{hscale}{Horizontal scale.  If equal to '1.0f', the characters have the original width depending on the font type. If equal to '0.5f', the characters are of half the original width.}
6629 \cvarg{vscale}{Vertical scale. If equal to '1.0f', the characters have the original height depending on the font type. If equal to '0.5f', the characters are of half the original height.}
6630 \cvarg{shear}{Approximate tangent of the character slope relative to the vertical line.  Zero value means a non-italic font, '1.0f' means ' about 45 degrees ' slope, etc. thickness Thickness of lines composing letters outlines. The function \texttt{cvLine} is used for drawing letters.}
6631 \cvarg{thickness}{Thickness of the text strokes}
6632 \cvarg{line\_type}{Type of the strokes, see \cross{Line} description}
6633 \end{description}
6634
6635 The function \texttt{cvInitFont} initializes the font structure that can be passed to text rendering functions.
6636
6637
6638 \cvfunc{PutText}\label{PutText}
6639
6640 Draws text string
6641
6642 \cvexp{
6643
6644 void cvPutText( \par CvArr* img,\par const char* text,\par CvPoint org,\par const CvFont* font,\par CvScalar color );
6645
6646 }{CPP}{PYTHON}
6647
6648 \begin{description}
6649 \cvarg{img}{Input image}
6650 \cvarg{text}{String to print}
6651 \cvarg{org}{Coordinates of the bottom-left corner of the first letter}
6652 \cvarg{font}{Pointer to the font structure}
6653 \cvarg{color}{Text color}
6654 \end{description}
6655
6656
6657 The function \texttt{cvPutText} renders the text in the image with
6658 the specified font and color. The printed text is clipped by ROI
6659 rectangle. Symbols that do not belong to the specified font are
6660 replaced with the rectangle symbol.
6661
6662 \cvfunc{GetTextSize}\label{GetTextSize}
6663
6664 Retrieves width and height of text string
6665
6666 \cvexp{
6667
6668 void cvGetTextSize( \par const char* text\_string,\par const CvFont* font,\par CvSize* text\_size,\par int* baseline );
6669
6670 }{CPP}{PYTHON}
6671
6672 \begin{description}
6673 \cvarg{font}{Pointer to the font structure}
6674 \cvarg{text\_string}{Input string}
6675 \cvarg{text\_size}{Resultant size of the text string. Height of the text does not include the height of character parts that are below the baseline.}
6676 \cvarg{baseline}{y-coordinate of the baseline relatively to the bottom-most text point}
6677 \end{description}
6678
6679 The function \texttt{cvGetTextSize} calculates the binding rectangle for the given text string when a specified font is used.
6680
6681 \subsection{Point Sets and Contours}
6682
6683 \cvfunc{DrawContours}\label{DrawContours}
6684
6685 Draws contour outlines or interiors in the image
6686
6687 \cvexp{
6688
6689 void cvDrawContours( \par CvArr *img,\par CvSeq* contour,\par CvScalar external\_color,\par CvScalar hole\_color,\par int max\_level,\par int thickness=1,\par int line\_type=8 );
6690
6691 }{CPP}{PYTHON}
6692
6693 \begin{description}
6694 \cvarg{img}{Image where the contours are to be drawn. Like in any other drawing function, the contours are clipped with the ROI.}
6695 \cvarg{contour}{Pointer to the first contour}
6696 \cvarg{external\_color}{Color of the external contours}
6697 \cvarg{hole\_color}{Color of internal contours (holes)}
6698 \cvarg{max\_level}{Maximal level for drawn contours. If 0, only
6699 \texttt{contour} is drawn. If 1, the contour and all contours after
6700 it on the same level are drawn. If 2, all contours after and all
6701 contours one level below the contours are drawn, etc. If the value
6702 is negative, the function does not draw the contours following after
6703 \texttt{contour} but draws child contours of \texttt{contour} up
6704 to $ |\texttt{max\_level}|-1$ level.}
6705 \cvarg{thickness}{Thickness of lines the contours are drawn with.
6706 If it is negative (e.g. =CV\_FILLED), the contour interiors are
6707 drawn.}
6708 \cvarg{line\_type}{Type of the contour segments, see \cross{Line} description}
6709 \end{description}
6710
6711 The function \texttt{cvDrawContours} draws contour outlines in the image if $\texttt{thickness} \ge 0$ or fills area bounded by the contours if $ \texttt{thickness}<0$.
6712
6713 Example. Connected component detection via contour functions
6714
6715 \begin{lstlisting}
6716
6717 #include "cv.h"
6718 #include "highgui.h"
6719
6720 int main( int argc, char** argv )
6721 {
6722     IplImage* src;
6723     // the first command line parameter must be file name of binary (black-n-white) image
6724     if( argc == 2 && (src=cvLoadImage(argv[1], 0))!= 0)
6725     {
6726         IplImage* dst = cvCreateImage( cvGetSize(src), 8, 3 );
6727         CvMemStorage* storage = cvCreateMemStorage(0);
6728         CvSeq* contour = 0;
6729
6730         cvThreshold( src, src, 1, 255, CV_THRESH_BINARY );
6731         cvNamedWindow( "Source", 1 );
6732         cvShowImage( "Source", src );
6733
6734         cvFindContours( src, storage, &contour, sizeof(CvContour), CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE );
6735         cvZero( dst );
6736
6737         for( ; contour != 0; contour = contour->h_next )
6738         {
6739             CvScalar color = CV_RGB( rand()&255, rand()&255, rand()&255 );
6740             /* replace CV_FILLED with 1 to see the outlines */
6741             cvDrawContours( dst, contour, color, color, -1, CV_FILLED, 8 );
6742         }
6743
6744         cvNamedWindow( "Components", 1 );
6745         cvShowImage( "Components", dst );
6746         cvWaitKey(0);
6747     }
6748 }
6749
6750 \end{lstlisting}
6751
6752 Replace \texttt{CV\_FILLED} with 1 in the sample below to see the contour outlines
6753
6754 \cvfunc{InitLineIterator}\label{InitLineIterator}
6755
6756 Initializes line iterator
6757
6758 \cvexp{
6759
6760 int cvInitLineIterator( \par const CvArr* image,\par CvPoint pt1,\par CvPoint pt2,\par CvLineIterator* line\_iterator,\par int connectivity=8,\par int left\_to\_right=0 );
6761
6762 }{CPP}{PYTHON}
6763
6764 \begin{description}
6765 \cvarg{image}{Image to sample the line from}
6766 \cvarg{pt1}{First ending point of the line segment}
6767 \cvarg{pt2}{Second ending point of the line segment}
6768 \cvarg{line\_iterator}{Pointer to the line iterator state structure}
6769 \cvarg{connectivity}{The scanned line connectivity, 4 or 8
6770 be always scanned from the left-most point to the right-most out
6771 of \texttt{pt1} and \texttt{pt2} ($ \texttt{left\_to\_right} \ne 0$), or it
6772 is scanned in the specified order, from \texttt{pt1} to \texttt{pt2}
6773 ($ \texttt{left\_to\_right} = 0 $ )}
6774 \end{description}
6775
6776 The function \texttt{cvInitLineIterator} initializes the line
6777 iterator and returns the number of pixels between two end points.
6778 Both points must be inside the image. After the iterator has been
6779 initialized, all the points on the raster line that connects the
6780 two ending points may be retrieved by successive calls of
6781 \texttt{CV\_NEXT\_LINE\_POINT} point. The points on the line are
6782 calculated one by one using 4-connected or 8-connected Bresenham
6783 algorithm.
6784
6785 Example. Using line iterator to calculate sum of pixel values along the color line
6786
6787 \begin{lstlisting}
6788
6789 CvScalar sum_line_pixels( IplImage* image, CvPoint pt1, CvPoint pt2 )
6790 {
6791     CvLineIterator iterator;
6792     int blue_sum = 0, green_sum = 0, red_sum = 0;
6793     int count = cvInitLineIterator( image, pt1, pt2, &iterator, 8, 0 );
6794
6795     for( int i = 0; i < count; i++ ){
6796         blue_sum += iterator.ptr[0];
6797         green_sum += iterator.ptr[1];
6798         red_sum += iterator.ptr[2];
6799         CV_NEXT_LINE_POINT(iterator);
6800
6801         /* print the pixel coordinates: demonstrates how to calculate the coordinates */
6802         {
6803         int offset, x, y;
6804         /* assume that ROI is not set, otherwise need to take it into account. */
6805         offset = iterator.ptr - (uchar*)(image->imageData);
6806         y = offset/image->widthStep;
6807         x = (offset - y*image->widthStep)/(3*sizeof(uchar) /* size of pixel */);
6808         printf("(%d,%d)\n", x, y );
6809         }
6810     }
6811     return cvScalar( blue_sum, green_sum, red_sum );
6812 }
6813
6814 \end{lstlisting}
6815
6816 \cvfunc{ClipLine}\label{ClipLine}
6817
6818 Clips the line against the image rectangle
6819
6820 \cvexp{
6821
6822 int cvClipLine( \par CvSize img\_size,\par CvPoint* pt1,\par CvPoint* pt2 );
6823
6824 }{CPP}{PYTHON}
6825
6826 \begin{description}
6827 \cvarg{img\_size}{Size of the image}
6828 \cvarg{pt1}{First ending point of the line segment. It is modified by the function.}
6829 \cvarg{pt2}{Second ending point of the line segment. It is modified by the function.}
6830 \end{description}
6831
6832 The function \texttt{cvClipLine} calculates a part of the line
6833 segment which is entirely in the image. It returns 0 if the line
6834 segment is completely outside the image and 1 otherwise.
6835
6836 \cvfunc{Ellipse2Poly}\label{Ellipse2Poly}
6837
6838 Approximates elliptic arc with polyline
6839
6840 \cvexp{
6841
6842 int cvEllipse2Poly( \par CvPoint center,\par CvSize axes,\par int angle,\par int arc\_start,\par int arc\_end,\par CvPoint* pts,\par int delta );
6843
6844 }{CPP}{PYTHON}
6845
6846 \begin{description}
6847 \cvarg{center}{Center of the arc}
6848 \cvarg{axes}{Half-sizes of the arc. See \cross{Ellipse}.}
6849 \cvarg{angle}{Rotation angle of the ellipse in degrees. See \cross{Ellipse}}
6850 \cvarg{start\_angle}{Starting angle of the elliptic arc}
6851 \cvarg{end\_angle}{Ending angle of the elliptic arc}
6852 \cvarg{pts}{The array of points, filled by the function}
6853 \cvarg{delta}{Angle between the subsequent polyline vertices, approximation accuracy. So, the total number of output points will
6854 $ \lceil( \texttt{end\_angle} - \texttt{start\_angle} ) / \texttt{delta} \rceil + 1 $
6855 at max.}
6856 \end{description}
6857
6858 The function \texttt{cvEllipse2Poly} computes vertices of the polyline that approximates the specified elliptic arc. It is used by \cross{Ellipse}.
6859
6860 \section{Data Persistence and RTTI}
6861
6862
6863 \subsection{File Storage}
6864
6865 \cvstruct{CvFileStorage}\label{CvFileStorage}
6866
6867 File Storage
6868
6869 \begin{lstlisting}
6870
6871 typedef struct CvFileStorage
6872 {
6873     ...       // hidden fields
6874 } CvFileStorage;
6875
6876 \end{lstlisting}
6877
6878 The structure \cross{CvFileStorage} is "black box" representation
6879 of file storage that is associated with a file on disk. Several
6880 functions that are described below take \texttt{CvFileStorage} on
6881 input and allow user to save or to load hierarchical collections
6882 that consist of scalar values, standard CXCore objects (such as
6883 matrices, sequences, graphs) and user-defined objects.
6884
6885 CXCore can read and write data in XML (http://www.w3c.org/XML) or YAML
6886 (http://www.yaml.org) formats. Below is the example of $3 \times 3$
6887 floating-point identity matrix \texttt{A}, stored in XML and YAML files
6888 using CXCore functions:
6889
6890 XML:
6891
6892 \begin{verbatim}
6893 <?xml version="1.0">
6894 <opencv_storage>
6895 <A type_id="opencv-matrix">
6896   <rows>3</rows>
6897   <cols>3</cols>
6898   <dt>f</dt>
6899   <data>1. 0. 0. 0. 1. 0. 0. 0. 1.</data>
6900 </A>
6901 </opencv_storage>
6902 \end{verbatim}
6903
6904 YAML:
6905
6906 \begin{verbatim}
6907 %YAML:1.0
6908 A: !!opencv-matrix
6909   rows: 3
6910   cols: 3
6911   dt: f
6912   data: [ 1., 0., 0., 0., 1., 0., 0., 0., 1.]
6913 \end{verbatim}
6914
6915 As it can be seen from the examples, XML uses nested tags to represent
6916 hierarchy, while YAML uses indentation for that purpose (similarly
6917 to Python programming language).
6918
6919 The same CXCore functions can read and write data in both formats,
6920 the particular format is determined by the extension of the opened
6921 file, .xml for XML files and .yml or .yaml for YAML.
6922
6923
6924 \cvstruct{CvFileNode}\label{CvFileNode}
6925
6926 File Storage Node
6927
6928 \begin{lstlisting}
6929
6930 /* file node type */
6931 #define CV\_NODE\_NONE        0
6932 #define CV\_NODE\_INT         1
6933 #define CV\_NODE\_INTEGER     CV\_NODE\_INT
6934 #define CV\_NODE\_REAL        2
6935 #define CV\_NODE\_FLOAT       CV\_NODE\_REAL
6936 #define CV\_NODE\_STR         3
6937 #define CV\_NODE\_STRING      CV\_NODE\_STR
6938 #define CV\_NODE\_REF         4 /* not used */
6939 #define CV\_NODE\_SEQ         5
6940 #define CV\_NODE\_MAP         6
6941 #define CV\_NODE\_TYPE\_MASK   7
6942
6943 /* optional flags */
6944 #define CV\_NODE\_USER        16
6945 #define CV\_NODE\_EMPTY       32
6946 #define CV\_NODE\_NAMED       64
6947
6948 #define CV\_NODE\_TYPE(tag)  ((tag) & CV\_NODE\_TYPE\_MASK)
6949
6950 #define CV\_NODE\_IS\_INT(tag)        (CV\_NODE\_TYPE(tag) == CV\_NODE\_INT)
6951 #define CV\_NODE\_IS\_REAL(tag)       (CV\_NODE\_TYPE(tag) == CV\_NODE\_REAL)
6952 #define CV\_NODE\_IS\_STRING(tag)     (CV\_NODE\_TYPE(tag) == CV\_NODE\_STRING)
6953 #define CV\_NODE\_IS\_SEQ(tag)        (CV\_NODE\_TYPE(tag) == CV\_NODE\_SEQ)
6954 #define CV\_NODE\_IS\_MAP(tag)        (CV\_NODE\_TYPE(tag) == CV\_NODE\_MAP)
6955 #define CV\_NODE\_IS\_COLLECTION(tag) (CV\_NODE\_TYPE(tag) >= CV\_NODE\_SEQ)
6956 #define CV\_NODE\_IS\_FLOW(tag)       (((tag) & CV\_NODE\_FLOW) != 0)
6957 #define CV\_NODE\_IS\_EMPTY(tag)      (((tag) & CV\_NODE\_EMPTY) != 0)
6958 #define CV\_NODE\_IS\_USER(tag)       (((tag) & CV\_NODE\_USER) != 0)
6959 #define CV\_NODE\_HAS\_NAME(tag)      (((tag) & CV\_NODE\_NAMED) != 0)
6960
6961 #define CV\_NODE\_SEQ\_SIMPLE 256
6962 #define CV\_NODE\_SEQ\_IS\_SIMPLE(seq) (((seq)->flags & CV\_NODE\_SEQ\_SIMPLE) != 0)
6963
6964 typedef struct CvString
6965 {
6966     int len;
6967     char* ptr;
6968 }
6969 CvString;
6970
6971 /* all the keys (names) of elements in the readed file storage
6972    are stored in the hash to speed up the lookup operations */
6973 typedef struct CvStringHashNode
6974 {
6975     unsigned hashval;
6976     CvString str;
6977     struct CvStringHashNode* next;
6978 }
6979 CvStringHashNode;
6980
6981 /* basic element of the file storage - scalar or collection */
6982 typedef struct CvFileNode
6983 {
6984     int tag;
6985     struct CvTypeInfo* info; /* type information
6986             (only for user-defined object, for others it is 0) */
6987     union
6988     {
6989         double f; /* scalar floating-point number */
6990         int i;    /* scalar integer number */
6991         CvString str; /* text string */
6992         CvSeq* seq; /* sequence (ordered collection of file nodes) */
6993         struct CvMap* map; /* map (collection of named file nodes) */
6994     } data;
6995 }
6996 CvFileNode;
6997
6998 \end{lstlisting}
6999
7000 The structure is used only for retrieving data from file storage
7001 (i.e. for loading data from file). When data is written to file,
7002 it is done sequentially, with minimal buffering. No data is stored
7003 in the file storage.
7004
7005 In opposite, when data is read from file, the whole file is parsed
7006 and represented in memory as a tree. Every node of the tree is
7007 represented by \cross{CvFileNode}. Type of the file node \texttt{N}
7008 can be retrieved as \texttt{CV\_NODE\_TYPE(N->tag)}. Some file nodes
7009 (leaves) are scalars: text strings, integer or floating-point
7010 numbers. Other file nodes are collections of file nodes, which can
7011 be scalars or collections in their turn. There are two types of
7012 collections: sequences and maps (we use YAML notation, however, the
7013 same is true for XML streams). Sequences (do not mix them with
7014 \cross{CvSeq}) are ordered collections of unnamed file nodes, maps
7015 are unordered collections of named file nodes. Thus, elements of
7016 sequences are accessed by index (\cross{GetSeqElem}), while elements
7017 of maps are accessed by name (\cross{GetFileNodeByName}). The table
7018 below describes the different types of a file node:
7019
7020 \begin{tabular}{| c | c | c |}
7021 \hline
7022 Type           & \texttt{CV\_NODE\_TYPE(node->tag)} & Value\\ \hline \hline
7023 Integer        & \texttt{CV\_NODE\_INT}             & \texttt{node->data.i} \\ \hline
7024 Floating-point & \texttt{CV\_NODE\_REAL}            & \texttt{node->data.f} \\ \hline
7025 Text string    & \texttt{CV\_NODE\_STR}             & \texttt{node->data.str.ptr} \\ \hline
7026 Sequence       & \texttt{CV\_NODE\_SEQ}             & \texttt{node->data.seq} \\ \hline
7027 Map            & \texttt{CV\_NODE\_MAP}             & \texttt{node->data.map} (see below)\\ \hline
7028 \end{tabular}
7029
7030 There is no need to access \texttt{map} field directly (BTW,
7031 \texttt{CvMap} is a hidden structure). The elements of the map can
7032 be retrieved with \cross{GetFileNodeByName} function that takes
7033 pointer to the "map" file node.
7034
7035 A user (custom) object is instance of either one of standard CxCore
7036 types, such as \cross{CvMat}, \cross{CvSeq} etc., or any type
7037 registered with \cross{RegisterTypeInfo}. Such an object is initially
7038 represented in file as a map (as shown in XML and YAML sample files
7039 above), after file storage has been opened and parsed. Then the
7040 object can be decoded (coverted to the native representation) by
7041 request - when user calls \cross{Read} or \cross{ReadByName} function.
7042
7043
7044 \cvstruct{CvAttrList}\label{CvAttrList}
7045
7046 List of attributes
7047
7048 \begin{lstlisting}
7049
7050 typedef struct CvAttrList
7051 {
7052     const char** attr; /* NULL-terminated array of (attribute\_name,attribute\_value) pairs */
7053     struct CvAttrList* next; /* pointer to next chunk of the attributes list */
7054 }
7055 CvAttrList;
7056
7057 /* initializes CvAttrList structure */
7058 inline CvAttrList cvAttrList( const char** attr=NULL, CvAttrList* next=NULL );
7059
7060 /* returns attribute value or 0 (NULL) if there is no such attribute */
7061 const char* cvAttrValue( const CvAttrList* attr, const char* attr\_name );
7062
7063 \end{lstlisting}
7064
7065 In the current implementation attributes are used to pass extra parameters when writing user objects (see \cross{Write}). XML attributes inside tags are not supported, besides the object type specification (\texttt{type\_id} attribute).
7066
7067 \cvfunc{OpenFileStorage}\label{OpenFileStorage}
7068
7069 Opens file storage for reading or writing data
7070
7071 \cvexp{
7072
7073 CvFileStorage* cvOpenFileStorage( \par const char* filename,\par CvMemStorage* memstorage,\par int flags );
7074
7075 }{CPP}{PYTHON}
7076
7077 \begin{description}
7078 \cvarg{filename}{Name of the file associated with the storage}
7079 \cvarg{memstorage}{Memory storage used for temporary data and for
7080 storing dynamic structures, such as \cross{CvSeq} or \cross{CvGraph}.
7081 If it is NULL, a temporary memory storage is created and used.}
7082 \cvarg{flags}{Can be one of the following:
7083   \begin{description}
7084   \cvarg{CV\_STORAGE\_READ}{the storage is open for reading}
7085   \cvarg{CV\_STORAGE\_WRITE}{the storage is open for writing}
7086   \end{description}}
7087 \end{description}
7088
7089 The function \texttt{cvOpenFileStorage} opens file storage for
7090 reading or writing data. In the latter case a new file is created
7091 or existing file is rewritten. Type of the read of written file is
7092 determined by the filename extension: '.xml' for \texttt{XML}
7093 and '.yml' or '.yaml' for \texttt{YAML}. The function
7094 returns pointer to \cross{CvFileStorage} structure.
7095
7096 \cvfunc{ReleaseFileStorage}\label{ReleaseFileStorage}
7097
7098 Releases file storage
7099
7100 \cvexp{
7101
7102 void  cvReleaseFileStorage( CvFileStorage** fs );
7103
7104 }{CPP}{PYTHON}
7105
7106 \begin{description}
7107 \cvarg{fs}{Double pointer to the released file storage}
7108 \end{description}
7109
7110
7111 The function \texttt{cvReleaseFileStorage} closes the file associated with the storage and releases all the temporary structures. It must be called after all I/O operations with the storage are finished.
7112
7113
7114 \subsection{Writing Data}
7115
7116 \cvfunc{StartWriteStruct}\label{StartWriteStruct}
7117
7118 Starts writing a new structure
7119
7120 \cvexp{
7121
7122 void  cvStartWriteStruct( CvFileStorage* fs,\par const char* name,\par int struct\_flags,\par const char* type\_name=NULL,\par CvAttrList attributes=cvAttrList( \par));
7123
7124 }{CPP}{PYTHON}
7125
7126 \begin{description}
7127 \cvarg{fs}{File storage}
7128 \cvarg{name}{Name of the written structure. The structure can be accessed by this name when the storage is read.}
7129 \cvarg{struct\_flags}{A combination one of the following values:
7130 \begin{description}
7131 \cvarg{CV\_NODE\_SEQ}{the written structure is a sequence (see discussion of \cross{CvFileStorage}), that is, its elements do not have a name.}
7132 \cvarg{CV\_NODE\_MAP}{the written structure is a map (see discussion of \cross{CvFileStorage}), that is, all its elements have names. One and only one of the two above flags must be specified}
7133 \end{description}}
7134 \cvarg{CV\_NODE\_FLOW}{the optional flag that has sense only for YAML streams. It means that the structure is written as a flow (not as a block), which is more compact. It is recommended to use this flag for structures or arrays whose elements are all scalars.}
7135 \cvarg{type\_name}{Optional parameter - the object type name. In
7136 case of XML it is written as \texttt{type\_id} attribute of the
7137 structure opening tag. In case of YAML it is written after a colon
7138 following the structure name (see the example in \cross{CvFileStorage}
7139 description). Mainly it comes with user objects. When the storage
7140 is read, the encoded type name is used to determine the object type
7141 (see \cross{CvTypeInfo} and \cross{FindTypeInfo}).}
7142 \cvarg{attributes}{This parameter is not used in the current implementation}
7143 \end{description}
7144
7145 The function \texttt{cvStartWriteStruct} starts writing a compound
7146 structure (collection) that can be a sequence or a map. After all
7147 the structure fields, which can be scalars or structures, are
7148 written, \cross{EndWriteStruct} should be called. The function can
7149 be used to group some objects or to implement \texttt{write}
7150 function for a some user object (see \cross{CvTypeInfo}).
7151
7152 \cvfunc{EndWriteStruct}\label{EndWriteStruct}
7153
7154 Ends writing a structure
7155
7156 \cvexp{
7157
7158 void  cvEndWriteStruct( CvFileStorage* fs );
7159
7160 }{CPP}{PYTHON}
7161
7162 \begin{description}
7163 \cvarg{fs}{File storage}
7164 \end{description}
7165
7166
7167 The function \texttt{cvEndWriteStruct} finishes the currently written structure.
7168
7169 \cvfunc{WriteInt}\label{WriteInt}
7170
7171 Writes an integer value
7172
7173 \cvexp{
7174
7175 void  cvWriteInt( \par CvFileStorage* fs,\par const char* name,\par int value );
7176
7177 }{CPP}{PYTHON}
7178
7179 \begin{description}
7180 \cvarg{fs}{File storage}
7181 \cvarg{name}{Name of the written value. Should be NULL if and only if the parent structure is a sequence.}
7182 \cvarg{value}{The written value}
7183 \end{description}
7184
7185 The function \texttt{cvWriteInt} writes a single integer value (with or without a name) to the file storage.
7186
7187 \cvfunc{WriteReal}\label{WriteReal}
7188
7189 Writes a floating-point value
7190
7191 \cvexp{
7192
7193 void  cvWriteReal( \par CvFileStorage* fs,\par const char* name,\par double value );
7194
7195 }{CPP}{PYTHON}
7196
7197 \begin{description}
7198 \cvarg{fs}{File storage}
7199 \cvarg{name}{Name of the written value. Should be NULL if and only if the parent structure is a sequence.}
7200 \cvarg{value}{The written value}
7201 \end{description}
7202
7203 The function \texttt{cvWriteReal} writes a single floating-point
7204 value (with or without a name) to the file storage. The special
7205 values are encoded: NaN (Not A Number) as .NaN, $ \pm \infty $ as +.Inf
7206 (-.Inf).
7207
7208 The following example shows how to use the low-level writing functions
7209 to store custom structures, such as termination criteria, without
7210 registering a new type.
7211
7212 \begin{lstlisting}
7213
7214 void write_termcriteria( CvFileStorage* fs, const char* struct_name,
7215                          CvTermCriteria* termcrit )
7216 {
7217     cvStartWriteStruct( fs, struct_name, CV_NODE_MAP, NULL, cvAttrList(0,0));
7218     cvWriteComment( fs, "termination criteria", 1 ); // just a description
7219     if( termcrit->type & CV_TERMCRIT_ITER )
7220         cvWriteInteger( fs, "max_iterations", termcrit->max_iter );
7221     if( termcrit->type & CV_TERMCRIT_EPS )
7222         cvWriteReal( fs, "accuracy", termcrit->epsilon );
7223     cvEndWriteStruct( fs );
7224 }
7225
7226 \end{lstlisting}
7227
7228 \cvfunc{WriteString}\label{WriteString}
7229
7230 Writes a text string
7231
7232 \cvexp{
7233
7234 void  cvWriteString( \par CvFileStorage* fs,\par const char* name,\par const char* str,\par int quote=0 );
7235
7236 }{CPP}{PYTHON}
7237
7238 \begin{description}
7239 \cvarg{fs}{File storage}
7240 \cvarg{name}{Name of the written string . Should be NULL if and only if the parent structure is a sequence.}
7241 \cvarg{str}{The written text string}
7242 \cvarg{quote}{If non-zero, the written string is put in quotes, regardless of whether they are required or not. Otherwise, if the flag is zero, quotes are used only when they are required (e.g. when the string starts with a digit or contains spaces).}
7243 \end{description}
7244
7245 The function \texttt{cvWriteString} writes a text string to the file storage.
7246
7247 \cvfunc{WriteComment}\label{WriteComment}
7248
7249 Writes comment
7250
7251 \cvexp{
7252
7253 void  cvWriteComment( \par CvFileStorage* fs,\par const char* comment,\par int eol\_comment );
7254
7255 }{CPP}{PYTHON}
7256
7257 \begin{description}
7258 \cvarg{fs}{File storage}
7259 \cvarg{comment}{The written comment, single-line or multi-line}
7260 \cvarg{eol\_comment}{If non-zero, the function tries to put the comment in the end of current line. If the flag is zero, if the comment is multi-line, or if it does not fit in the end of the current line, the comment starts from a new line.}
7261 \end{description}
7262
7263 The function \texttt{cvWriteComment} writes a comment into the file storage. The comments are skipped when the storage is read, so they may be used only for debugging or descriptive purposes.
7264
7265 \cvfunc{StartNextStream}\label{StartNextStream}
7266
7267 Starts the next stream
7268
7269 \cvexp{
7270
7271 void  cvStartNextStream( CvFileStorage* fs );
7272
7273 }{CPP}{PYTHON}
7274
7275 \begin{description}
7276 \cvarg{fs}{File storage}
7277 \end{description}
7278
7279
7280 The function \texttt{cvStartNextStream} starts the next stream in the file storage. Both YAML and XML supports multiple "streams". This is useful for concatenating files or for resuming the writing process.
7281
7282
7283 \cvfunc{Write}\label{Write}
7284
7285 Writes user object
7286
7287 \cvexp{
7288
7289 void  cvWrite( CvFileStorage* fs,\par const char* name,\par const void* ptr,\par CvAttrList attributes=cvAttrList( \par) );
7290
7291 }{CPP}{PYTHON}
7292
7293 \begin{description}
7294 \cvarg{fs}{File storage}
7295 \cvarg{name}{Name, of the written object. Should be NULL if and only if the parent structure is a sequence.}
7296 \cvarg{ptr}{Pointer to the object}
7297 \cvarg{attributes}{The attributes of the object. They are specific for each particular type (see the dicsussion).}
7298 \end{description}
7299
7300 The function \texttt{cvWrite} writes the object to file storage. First, the appropriate type info is found using \cross{TypeOf}. Then, \texttt{write} method of the type info is called.
7301
7302 Attributes are used to customize the writing procedure. The standard types support the following attributes (all the \texttt{*dt} attributes have the same format as in \cross{WriteRawData}):
7303
7304 CvSeq
7305   \begin{description}
7306   \cvarg{header\_dt}{description of user fields of the sequence header that follow CvSeq, or CvChain (if the sequence is Freeman chain) or CvContour (if the sequence is a contour or point sequence)}
7307   \cvarg{dt}{description of the sequence elements.}
7308   \cvarg{recursive}{if the attribute is present and is not equal to "0" or "false", the whole tree of sequences (contours) is stored.}
7309   \end{description}
7310 Cvgraph
7311   \begin{description}
7312   \cvarg{header\_dt}{description of user fields of the graph header that follow CvGraph;}
7313   \cvarg{vertex\_dt}{description of user fields of graph vertices}
7314   \cvarg{edge\_dt}{description of user fields of graph edges (note, that edge weight is always written, so there is no need to specify it explicitly)}
7315   \end{description}
7316
7317 Below is the code that creates the YAML file shown in \texttt{CvFileStorage} description:
7318
7319 \begin{lstlisting}
7320
7321 #include "cxcore.h"
7322
7323 int main( int argc, char** argv )
7324 {
7325     CvMat* mat = cvCreateMat( 3, 3, CV\_32F );
7326     CvFileStorage* fs = cvOpenFileStorage( "example.yml", 0, CV\_STORAGE\_WRITE );
7327
7328     cvSetIdentity( mat );
7329     cvWrite( fs, "A", mat, cvAttrList(0,0) );
7330
7331     cvReleaseFileStorage( &fs );
7332     cvReleaseMat( &mat );
7333     return 0;
7334 }
7335
7336 \end{lstlisting}
7337
7338
7339 \cvfunc{WriteRawData}\label{WriteRawData}
7340
7341 Writes multiple numbers
7342
7343 \cvexp{
7344
7345 void  cvWriteRawData( \par CvFileStorage* fs,\par const void* src,\par int len,\par const char* dt );
7346
7347 }{CPP}{PYTHON}
7348
7349 \begin{description}
7350 \cvarg{fs}{File storage}
7351 \cvarg{src}{Pointer to the written array}
7352 \cvarg{len}{Number of the array elements to write}
7353 \cvarg{dt}{Specification of each array element that has the following format
7354 \texttt{([count]\{'u'|'c'|'w'|'s'|'i'|'f'|'d'\})...}
7355 where the characters correspond to fundamental C types:
7356 \begin{description}
7357  \cvarg{u}{8-bit unsigned number}
7358  \cvarg{c}{8-bit signed number}
7359  \cvarg{w}{16-bit unsigned number}
7360  \cvarg{s}{16-bit signed number}
7361  \cvarg{i}{32-bit signed number}
7362  \cvarg{f}{single precision floating-point number}
7363  \cvarg{d}{double precision floating-point number}
7364  \cvarg{r}{pointer. 32 lower bits of it are written as a signed integer. The type can be used to store structures with links between the elements.
7365 \texttt{count} is the optional counter of values of the certain type. For
7366 example, \texttt{2if} means that each array element is a structure
7367 of 2 integers, followed by a single-precision floating-point number. The
7368 equivalent notations of the above specification are '\texttt{iif}',
7369 '\texttt{2i1f}' etc. Other examples: \texttt{u} means that the
7370 array consists of bytes, \texttt{2d} - the array consists of pairs
7371 of doubles.}
7372 \end{description}}
7373 \end{description}
7374
7375 The function \texttt{cvWriteRawData} writes array, which elements consist
7376 of a single of multiple numbers. The function call can be replaced with
7377 a loop containing a few \cross{WriteInt} and \cross{WriteReal} calls, but
7378 a single call is more efficient. Note, that because none of the elements
7379 have a name, they should be written to a sequence rather than a map.
7380
7381 \cvfunc{WriteFileNode}\label{WriteFileNode}
7382
7383 Writes file node to another file storage
7384
7385 \cvexp{
7386
7387 void cvWriteFileNode( \par CvFileStorage* fs,\par const char* new\_node\_name,\par const CvFileNode* node,\par int embed );
7388
7389 }{CPP}{PYTHON}
7390
7391 \begin{description}
7392 \cvarg{fs}{Destination file storage}
7393 \cvarg{new\_file\_node}{New name of the file node in the destination file storage. To keep the existing name, use \cross{cvGetFileNodeName}}
7394 \cvarg{node}{The written node}
7395 \cvarg{embed}{If the written node is a collection and this parameter is not zero, no extra level of hiararchy is created. Instead, all the elements of \texttt{node} are written into the currently written structure. Of course, map elements may be written only to map, and sequence elements may be written only to sequence.}
7396 \end{description}
7397
7398 The function \texttt{cvWriteFileNode} writes a copy of file node to file storage. The possible application of the function are: merging several file storages into one. Conversion between XML and YAML formats etc.
7399
7400 \subsection{Reading Data}
7401
7402 Data are retrieved from file storage in 2 steps: first, the file node
7403 containing the requested data is found; then, data is extracted from
7404 the node manually or using custom \texttt{read} method.
7405
7406 \cvfunc{GetRootFileNode}\label{GetRootFileNode}
7407
7408 Retrieves one of top-level nodes of the file storage
7409
7410 \cvexp{
7411
7412 CvFileNode* cvGetRootFileNode( \par const CvFileStorage* fs,\par int stream\_index=0 );
7413
7414 }{CPP}{PYTHON}
7415
7416 \begin{description}
7417 \cvarg{fs}{File storage}
7418 \cvarg{stream\_index}{Zero-based index of the stream. See \cross{StartNextStream}. In most cases, there is only one stream in the file, however there can be several.}
7419 \end{description}
7420
7421 The function \texttt{cvGetRootFileNode} returns one of top-level file
7422 nodes. The top-level nodes do not have a name, they correspond to the
7423 streams, that are stored one after another in the file storage. If the
7424 index is out of range, the function returns NULL pointer, so all the
7425 top-level nodes may be iterated by subsequent calls to the function with
7426 'stream\_index=0,1,...', until NULL pointer is returned. This function
7427 may be used as a base for recursive traversal of the file storage.
7428
7429 \cvfunc{GetFileNodeByName}\label{GetFileNodeByName}
7430
7431 Finds node in the map or file storage
7432
7433 \cvexp{
7434
7435 CvFileNode* cvGetFileNodeByName( \par const CvFileStorage* fs,\par const CvFileNode* map,\par const char* name );
7436
7437 }{CPP}{PYTHON}
7438
7439 \begin{description}
7440 \cvarg{fs}{File storage}
7441 \cvarg{map}{The parent map. If it is NULL, the function searches in all the top-level nodes (streams), starting from the first one.}
7442 \cvarg{name}{The file node name}
7443 \end{description}
7444
7445
7446 The function \texttt{cvGetFileNodeByName} finds a file node by
7447 \texttt{name}. The node is searched either in \texttt{map} or, if the
7448 pointer is NULL, among the top-level file nodes of the storage. Using
7449 this function for maps and \cross{GetSeqElem} (or sequence reader)
7450 for sequences, it is possible to nagivate through the file storage. To
7451 speed up multiple queries for a certain key (e.g. in case of array
7452 of structures) one may use a pair of \cross{GetHashedKey} and
7453 \cross{GetFileNode}.
7454
7455 \cvfunc{GetHashedKey}\label{GetHashedKey}
7456
7457 Returns a unique pointer for given name
7458
7459 \cvexp{
7460
7461 CvStringHashNode* cvGetHashedKey( \par CvFileStorage* fs,\par const char* name,\par int len=-1,\par int create\_missing=0 );
7462
7463 }{CPP}{PYTHON}
7464
7465 \begin{description}
7466 \cvarg{fs}{File storage}
7467 \cvarg{name}{Literal node name}
7468 \cvarg{len}{Length of the name (if it is known apriori), or -1 if it needs to be calculated}
7469 \cvarg{create\_missing}{Flag that specifies, whether an absent key should be added into the hash table, or not}
7470 \end{description}
7471
7472 The function \texttt{cvGetHashedKey} returns the unique pointer for
7473 each particular file node name. This pointer can be then passed to
7474 \cross{GetFileNode} function that is faster than \cross{GetFileNodeByName}
7475 because it compares text strings by comparing pointers rather than the
7476 strings' content.
7477
7478 Consider the following example: an array of points is encoded as a sequence of 2-entry maps, e.g.:
7479
7480 \begin{lstlisting}
7481
7482 %YAML:1.0
7483 points:
7484   - { x: 10, y: 10 }
7485   - { x: 20, y: 20 }
7486   - { x: 30, y: 30 }
7487   # ...
7488
7489 \end{lstlisting}
7490
7491 Then, it is possible to get hashed "x" and "y" pointers to speed up decoding of the points.
7492
7493 Example. Reading an array of structures from file storage
7494
7495 \begin{lstlisting}
7496
7497 #include "cxcore.h"
7498
7499 int main( int argc, char** argv )
7500 {
7501     CvFileStorage* fs = cvOpenFileStorage( "points.yml", 0, CV\_STORAGE\_READ );
7502     CvStringHashNode* x\_key = cvGetHashedNode( fs, "x", -1, 1 );
7503     CvStringHashNode* y\_key = cvGetHashedNode( fs, "y", -1, 1 );
7504     CvFileNode* points = cvGetFileNodeByName( fs, 0, "points" );
7505
7506     if( CV\_NODE\_IS\_SEQ(points->tag) )
7507     {
7508         CvSeq* seq = points->data.seq;
7509         int i, total = seq->total;
7510         CvSeqReader reader;
7511         cvStartReadSeq( seq, &reader, 0 );
7512         for( i = 0; i < total; i++ )
7513         {
7514             CvFileNode* pt = (CvFileNode*)reader.ptr;
7515 #if 1 /* faster variant */
7516             CvFileNode* xnode = cvGetFileNode( fs, pt, x\_key, 0 );
7517             CvFileNode* ynode = cvGetFileNode( fs, pt, y\_key, 0 );
7518             assert( xnode && CV\_NODE\_IS\_INT(xnode->tag) &&
7519                     ynode && CV\_NODE\_IS\_INT(ynode->tag));
7520             int x = xnode->data.i; // or x = cvReadInt( xnode, 0 );
7521             int y = ynode->data.i; // or y = cvReadInt( ynode, 0 );
7522 #elif 1 /* slower variant; does not use x\_key & y\_key */
7523             CvFileNode* xnode = cvGetFileNodeByName( fs, pt, "x" );
7524             CvFileNode* ynode = cvGetFileNodeByName( fs, pt, "y" );
7525             assert( xnode && CV\_NODE\_IS\_INT(xnode->tag) &&
7526                     ynode && CV\_NODE\_IS\_INT(ynode->tag));
7527             int x = xnode->data.i; // or x = cvReadInt( xnode, 0 );
7528             int y = ynode->data.i; // or y = cvReadInt( ynode, 0 );
7529 #else /* the slowest yet the easiest to use variant */
7530             int x = cvReadIntByName( fs, pt, "x", 0 /* default value */ );
7531             int y = cvReadIntByName( fs, pt, "y", 0 /* default value */ );
7532 #endif
7533             CV\_NEXT\_SEQ\_ELEM( seq->elem\_size, reader );
7534             printf("%d: (%d, %d)\n", i, x, y );
7535         }
7536     }
7537     cvReleaseFileStorage( &fs );
7538     return 0;
7539 }
7540
7541 \end{lstlisting}
7542
7543 Please note that, whatever method of accessing map you are using, it is
7544 still much slower than using plain sequences, for example, in the above
7545 sample, it is more efficient to encode the points as pairs of integers
7546 in the single numeric sequence.
7547
7548 \cvfunc{GetFileNode}\label{GetFileNode}
7549
7550 Finds node in the map or file storage
7551
7552 \cvexp{
7553
7554 CvFileNode* cvGetFileNode( \par CvFileStorage* fs,\par CvFileNode* map,\par const CvStringHashNode* key,\par int create\_missing=0 );
7555
7556 }{CPP}{PYTHON}
7557
7558 \begin{description}
7559 \cvarg{fs}{File storage}
7560 \cvarg{map}{The parent map. If it is NULL, the function searches a top-level node. If both \texttt{map} and \texttt{key} are NULLs, the function returns the root file node - a map that contains top-level nodes.}
7561 \cvarg{key}{Unique pointer to the node name, retrieved with \cross{GetHashedKey}}
7562 \cvarg{create\_missing}{Flag that specifies, whether an absent node should be added to the map, or not}
7563 \end{description}
7564
7565
7566 The function \texttt{cvGetFileNode} finds a file node. It is a faster version \cross{GetFileNodeByName} (see \cross{GetHashedKey} discussion). Also, the function can insert a new node, if it is not in the map yet (which is used by parsing functions).
7567
7568 \cvfunc{GetFileNodeName}\label{GetFileNodeName}
7569
7570 Returns name of file node
7571
7572 \cvexp{
7573
7574 const char* cvGetFileNodeName( const CvFileNode* node );
7575
7576 }{CPP}{PYTHON}
7577
7578 \begin{description}
7579 \cvarg{node}{File node}
7580 \end{description}
7581
7582
7583 The function \texttt{cvGetFileNodeName} returns name of the file node or NULL, if the file node does not have a name, or if \texttt{node} is \texttt{NULL}.
7584
7585
7586 \cvfunc{ReadInt}\label{ReadInt}
7587
7588 Retrieves integer value from file node
7589
7590 \cvexp{
7591
7592 int cvReadInt( \par const CvFileNode* node,\par int default\_value=0 );
7593
7594 }{CPP}{PYTHON}
7595
7596 \begin{description}
7597 \cvarg{node}{File node}
7598 \cvarg{default\_value}{The value that is returned if \texttt{node} is NULL}
7599 \end{description}
7600
7601
7602 The function \texttt{cvReadInt} returns integer that is represented
7603 by the file node. If the file node is NULL, \texttt{default\_value}
7604 is returned (thus, it is convenient to call the function right after
7605 \cross{GetFileNode} without checking for NULL pointer), otherwise if
7606 the file node has type \texttt{CV\_NODE\_INT}, then \texttt{node->data.i} is
7607 returned, otherwise if the file node has type \texttt{CV\_NODE\_REAL},
7608 then \texttt{node->data.f} is converted to integer and returned, otherwise the
7609 result is not determined.
7610
7611 \cvfunc{ReadIntByName}\label{ReadIntByName}
7612
7613 Finds file node and returns its value
7614
7615 \cvexp{
7616
7617 int cvReadIntByName( \par const CvFileStorage* fs,\par const CvFileNode* map,\par const char* name,\par int default\_value=0 );
7618
7619 }{CPP}{PYTHON}
7620
7621 \begin{description}
7622 \cvarg{fs}{File storage}
7623 \cvarg{map}{The parent map. If it is NULL, the function searches a top-level node.}
7624 \cvarg{name}{The node name}
7625 \cvarg{default\_value}{The value that is returned if the file node is not found}
7626 \end{description}
7627
7628 The function \texttt{cvReadIntByName} is a simple superposition of \cross{GetFileNodeByName} and \cross{ReadInt}.
7629
7630
7631 \cvfunc{ReadReal}\label{ReadReal}
7632
7633 Retrieves floating-point value from file node
7634
7635 \cvexp{
7636
7637 double cvReadReal( \par const CvFileNode* node,\par double default\_value=0. );
7638
7639 }{CPP}{PYTHON}
7640
7641 \begin{description}
7642 \cvarg{node}{File node}
7643 \cvarg{default\_value}{The value that is returned if \texttt{node} is NULL}
7644 \end{description}
7645
7646 The function \texttt{cvReadReal} returns floating-point value
7647 that is represented by the file node. If the file node is NULL,
7648 \texttt{default\_value} is returned (thus, it is convenient to call
7649 the function right after \cross{GetFileNode} without checking for NULL
7650 pointer), otherwise if the file node has type \texttt{CV\_NODE\_REAL},
7651 then \texttt{node->data.f} is returned, otherwise if the file node has type
7652 \texttt{CV\_NODE\_INT}, then 'node->data.f' is converted to floating-point
7653 and returned, otherwise the result is not determined.
7654
7655 \cvfunc{ReadRealByName}\label{ReadRealByName}
7656
7657 Finds file node and returns its value
7658
7659 \cvexp{
7660
7661 double  cvReadRealByName( \par const CvFileStorage* fs,\par const CvFileNode* map,\par const char* name,\par double default\_value=0. );
7662
7663 }{CPP}{PYTHON}
7664
7665 \begin{description}
7666 \cvarg{fs}{File storage}
7667 \cvarg{map}{The parent map. If it is NULL, the function searches a top-level node.}
7668 \cvarg{name}{The node name}
7669 \cvarg{default\_value}{The value that is returned if the file node is not found}
7670 \end{description}
7671
7672 The function \texttt{cvReadRealByName} is a simple superposition of \cross{GetFileNodeByName} and \cross{ReadReal}.
7673
7674 \cvfunc{ReadString}\label{ReadString}
7675
7676 Retrieves text string from file node
7677
7678 \cvexp{
7679
7680 const char* cvReadString( \par const CvFileNode* node,\par const char* default\_value=NULL );
7681
7682 }{CPP}{PYTHON}
7683
7684 \begin{description}
7685 \cvarg{node}{File node}
7686 \cvarg{default\_value}{The value that is returned if \texttt{node} is NULL}
7687 \end{description}
7688
7689 The function \texttt{cvReadString} returns text string that is represented
7690 by the file node. If the file node is NULL, \texttt{default\_value}
7691 is returned (thus, it is convenient to call the function right after
7692 \cross{GetFileNode} without checking for NULL pointer), otherwise if
7693 the file node has type \texttt{CV\_NODE\_STR}, then 'node->data.str.ptr'
7694 is returned, otherwise the result is not determined.
7695
7696 \cvfunc{ReadStringByName}\label{ReadStringByName}
7697
7698 Finds file node and returns its value
7699
7700 \cvexp{
7701
7702 const char* cvReadStringByName( \par const CvFileStorage* fs,\par const CvFileNode* map,\par const char* name,\par const char* default\_value=NULL );
7703
7704 }{CPP}{PYTHON}
7705
7706 \begin{description}
7707 \cvarg{fs}{File storage}
7708 \cvarg{map}{The parent map. If it is NULL, the function searches a top-level node.}
7709 \cvarg{name}{The node name}
7710 \cvarg{default\_value}{The value that is returned if the file node is not found}
7711 \end{description}
7712
7713 The function \texttt{cvReadStringByName} is a simple superposition of \cross{GetFileNodeByName} and \cross{ReadString}.
7714
7715 \cvfunc{Read}\label{Read}
7716
7717 Decodes object and returns pointer to it
7718
7719 \cvexp{
7720
7721 void* cvRead( \par CvFileStorage* fs,\par CvFileNode* node,\par CvAttrList* attributes=NULL );
7722
7723 }{CPP}{PYTHON}
7724
7725 \begin{description}
7726 \cvarg{fs}{File storage}
7727 \cvarg{node}{The root object node}
7728 \cvarg{attributes}{Unused parameter}
7729 \end{description}
7730
7731 The function \texttt{cvRead} decodes user object (creates object in a
7732 native representation from the file storage subtree) and returns it. The
7733 object to be decoded must be an instance of registered type that supports
7734 \texttt{read} method (see \cross{CvTypeInfo}). Type of the object is
7735 determined by the type name that is encoded in the file. If the object
7736 is dynamic structure, it is created either in memory storage, passed to
7737 \cross{OpenFileStorage} or, if NULL pointer was passed, in temporary
7738 memory storage, which is release when \cross{ReleaseFileStorage} is
7739 called. Otherwise, if the object is not a dynamic structure, it is
7740 created in heap and should be released with a specialized function or
7741 using generic \cross{Release}.
7742
7743 \cvfunc{ReadByName}\label{ReadByName}
7744
7745 Finds object and decodes it
7746
7747 \cvexp{
7748
7749 void* cvReadByName( \par CvFileStorage* fs,\par const CvFileNode* map,\par const char* name,\par CvAttrList* attributes=NULL );
7750
7751 }{CPP}{PYTHON}
7752
7753 \begin{description}
7754 \cvarg{fs}{File storage}
7755 \cvarg{map}{The parent map. If it is NULL, the function searches a top-level node.}
7756 \cvarg{name}{The node name}
7757 \cvarg{attributes}{Unused parameter}
7758 \end{description}
7759
7760 The function \texttt{cvReadByName} is a simple superposition of \cross{GetFileNodeByName} and \cross{Read}.
7761
7762 \cvfunc{ReadRawData}\label{ReadRawData}
7763
7764 Reads multiple numbers
7765
7766 \cvexp{
7767
7768 void cvReadRawData( \par const CvFileStorage* fs,\par const CvFileNode* src,\par void* dst,\par const char* dt );
7769
7770 }{CPP}{PYTHON}
7771
7772 \begin{description}
7773 \cvarg{fs}{File storage}
7774 \cvarg{src}{The file node (a sequence) to read numbers from}
7775 \cvarg{dst}{Pointer to the destination array}
7776 \cvarg{dt}{Specification of each array element. It has the same format as in \cross{WriteRawData}.}
7777 \end{description}
7778
7779 The function \texttt{cvReadRawData} reads elements from a file node that represents a sequence of scalars
7780
7781 \cvfunc{StartReadRawData}\label{StartReadRawData}
7782
7783 Initializes file node sequence reader
7784
7785 \cvexp{
7786
7787 void cvStartReadRawData( \par const CvFileStorage* fs,\par const CvFileNode* src,\par CvSeqReader* reader );
7788
7789 }{CPP}{PYTHON}
7790
7791 \begin{description}
7792 \cvarg{fs}{File storage}
7793 \cvarg{src}{The file node (a sequence) to read numbers from}
7794 \cvarg{reader}{Pointer to the sequence reader}
7795 \end{description}
7796
7797 The function \texttt{cvStartReadRawData} initializes sequence reader to read data from file node. The initialized reader can be then passed to \cross{ReadRawDataSlice}.
7798
7799 \cvfunc{ReadRawDataSlice}\label{ReadRawDataSlice}
7800
7801 Initializes file node sequence reader
7802
7803 \cvexp{
7804
7805 void cvReadRawDataSlice( \par const CvFileStorage* fs,\par CvSeqReader* reader,\par int count,\par void* dst,\par const char* dt );
7806
7807 }{CPP}{PYTHON}
7808
7809 \begin{description}
7810 \cvarg{fs}{File storage}
7811 \cvarg{reader}{The sequence reader. Initialize it with \cross{StartReadRawData}.}
7812 \cvarg{count}{The number of elements to read}
7813 \cvarg{dst}{Pointer to the destination array}
7814 \cvarg{dt}{Specification of each array element. It has the same format as in \cross{WriteRawData}.}
7815 \end{description}
7816
7817 The function \texttt{cvReadRawDataSlice} reads one or more elements from
7818 the file node, representing a sequence, to user-specified array. The
7819 total number of read sequence elements is a product of \texttt{total}
7820 and the number of components in each array element. For example, if
7821 dt=\texttt{2if}, the function will read total*3 sequence elements. As
7822 with any sequence, some parts of the file node sequence may be skipped or
7823 read repeatedly by repositioning the reader using \cross{SetSeqReaderPos}.
7824
7825 \subsection{RTTI and Generic Functions}
7826
7827 \cvstruct{CvTypeInfo}\label{CvTypeInfo}
7828
7829 Type information
7830
7831 \begin{lstlisting}
7832
7833 typedef int (CV_CDECL *CvIsInstanceFunc)( const void* struct_ptr );
7834 typedef void (CV_CDECL *CvReleaseFunc)( void** struct_dblptr );
7835 typedef void* (CV_CDECL *CvReadFunc)( CvFileStorage* storage, CvFileNode* node );
7836 typedef void (CV_CDECL *CvWriteFunc)( CvFileStorage* storage,
7837                                       const char* name,
7838                                       const void* struct_ptr,
7839                                       CvAttrList attributes );
7840 typedef void* (CV_CDECL *CvCloneFunc)( const void* struct_ptr );
7841
7842 typedef struct CvTypeInfo
7843 {
7844     int flags; /* not used */
7845     int header_size; /* sizeof(CvTypeInfo) */
7846     struct CvTypeInfo* prev; /* previous registered type in the list */
7847     struct CvTypeInfo* next; /* next registered type in the list */
7848     const char* type_name; /* type name, written to file storage */
7849
7850     /* methods */
7851     CvIsInstanceFunc is_instance; /* checks if the passed object belongs to the type */
7852     CvReleaseFunc release; /* releases object (memory etc.) */
7853     CvReadFunc read; /* reads object from file storage */
7854     CvWriteFunc write; /* writes object to file storage */
7855     CvCloneFunc clone; /* creates a copy of the object */
7856 }
7857 CvTypeInfo;
7858
7859 \end{lstlisting}
7860
7861 The structure \cross{CvTypeInfo} contains information about one of
7862 standard or user-defined types. Instances of the type may or may not
7863 contain pointer to the corresponding \cross{CvTypeInfo} structure. In
7864 any case there is a way to find type info structure for given object -
7865 using \cross{TypeOf} function. Aternatively, type info can be found by
7866 the type name using \cross{FindType}, which is used when object is read
7867 from file storage. User can register a new type with \cross{RegisterType}
7868 that adds the type information structure into the beginning of the type
7869 list - thus, it is possible to create specialized types from generic
7870 standard types and override the basic methods.
7871
7872 \cvfunc{RegisterType}\label{RegisterType}
7873
7874 Registers new type
7875
7876 \cvexp{
7877
7878 void cvRegisterType( const CvTypeInfo* info );
7879
7880 }{CPP}{PYTHON}
7881
7882 \begin{description}
7883 \cvarg{info}{Type info structure}
7884 \end{description}
7885
7886 The function \texttt{cvRegisterType} registers a new type, which is
7887 described by \texttt{info}. The function creates a copy of the structure,
7888 so user should delete it after calling the function.
7889
7890 \cvfunc{UnregisterType}\label{UnregisterType}
7891
7892 Unregisters the type
7893
7894 \cvexp{
7895
7896 void cvUnregisterType( const char* type\_name );
7897
7898 }{CPP}{PYTHON}
7899
7900 \begin{description}
7901 \cvarg{type\_name}{Name of the unregistered type}
7902 \end{description}
7903
7904 The function \texttt{cvUnregisterType} unregisters the type with
7905 the specified name. If the name is unknown, it is possible to locate
7906 the type info by an instance of the type using \cross{TypeOf} or by
7907 iterating the type list, starting from \cross{FirstType}, and then call
7908 \texttt{cvUnregisterType(info->type\_name)}.
7909
7910 \cvfunc{FirstType}\label{FirstType}
7911
7912 Returns the beginning of type list
7913
7914 \cvexp{
7915
7916 CvTypeInfo* cvFirstType( void );
7917
7918 }{CPP}{PYTHON}
7919
7920 The function \texttt{cvFirstType} returns the first type of the list of registered types. Navigation through the list can be done via \texttt{prev} and \texttt{next} fields of \cross{CvTypeInfo} structure.
7921
7922 \cvfunc{FindType}\label{FindType}
7923
7924 Finds type by its name
7925
7926 \cvexp{
7927
7928 CvTypeInfo* cvFindType( const char* type\_name );
7929
7930 }{CPP}{PYTHON}
7931
7932 \begin{description}
7933 \cvarg{type\_name}{Type name}
7934 \end{description}
7935
7936 The function \texttt{cvFindType} finds a registered type by its name. It returns NULL, if there is no type with the specified name.
7937
7938
7939 \cvfunc{TypeOf}\label{TypeOf}
7940
7941 Returns type of the object
7942
7943 \cvexp{
7944
7945 CvTypeInfo* cvTypeOf( const void* struct\_ptr );
7946
7947 }{CPP}{PYTHON}
7948
7949 \begin{description}
7950 \cvarg{struct\_ptr}{The object pointer}
7951 \end{description}
7952
7953 The function \texttt{cvTypeOf} finds the type of given object. It iterates
7954 through the list of registered types and calls \texttt{is\_instance}
7955 function/method of every type info structure with the object until one
7956 of them return non-zero or until the whole list has been traversed. In
7957 the latter case the function returns NULL.
7958
7959 \cvfunc{Release}\label{Release}
7960
7961 Releases the object
7962
7963 \cvexp{
7964
7965 void cvRelease( void** struct\_ptr );
7966
7967 }{CPP}{PYTHON}
7968
7969 \begin{description}
7970 \cvarg{struct\_ptr}{Double pointer to the object}
7971 \end{description}
7972
7973 The function \texttt{cvRelease} finds the type of given object and calls \texttt{release} with the double pointer.
7974
7975 \cvfunc{Clone}\label{Clone}
7976
7977 Makes a clone of the object
7978
7979 \cvexp{
7980
7981 void* cvClone( const void* struct\_ptr );
7982
7983 }{CPP}{PYTHON}
7984
7985 \begin{description}
7986 \cvarg{struct\_ptr}{The object to clone}
7987 \end{description}
7988
7989 The function \texttt{cvClone} finds the type of given object and calls \texttt{clone} with the passed object.
7990
7991 \cvfunc{Save}\label{Save}
7992
7993 Saves object to file
7994
7995 \cvexp{
7996
7997 void cvSave( \par const char* filename,\par const void* struct\_ptr,\par const char* name=NULL,\par const char* comment=NULL,\par CvAttrList attributes=cvAttrList());
7998
7999 }{CPP}{PYTHON}
8000
8001 \begin{description}
8002 \cvarg{filename}{File name}
8003 \cvarg{struct\_ptr}{Object to save}
8004 \cvarg{name}{Optional object name. If it is NULL, the name will be formed from \texttt{filename}.}
8005 \cvarg{comment}{Optional comment to put in the beginning of the file}
8006 \cvarg{attributes}{Optional attributes passed to \cross{Write}}
8007 \end{description}
8008
8009 The function \texttt{cvSave} saves object to file. It provides a simple interface to \cross{Write}.
8010
8011 \cvfunc{Load}\label{Load}
8012
8013 Loads object from file
8014
8015 \cvexp{
8016
8017 void* cvLoad( \par const char* filename,\par CvMemStorage* memstorage=NULL,\par const char* name=NULL,\par const char** real\_name=NULL );
8018
8019 }{CPP}{PYTHON}
8020
8021 \begin{description}
8022 \cvarg{filename}{File name}
8023 \cvarg{memstorage}{Memory storage for dynamic structures, such as \cross{CvSeq} or \cross{CvGraph} . It is not used for matrices or images.}
8024 \cvarg{name}{Optional object name. If it is NULL, the first top-level object in the storage will be loaded.}
8025 \cvarg{real\_name}{Optional output parameter that will contain name of the loaded object (useful if \texttt{name=NULL})}
8026 \end{description}
8027
8028 The function \texttt{cvLoad} loads object from file. It provides a
8029 simple interface to \cross{Read}. After object is loaded, the file
8030 storage is closed and all the temporary buffers are deleted. Thus,
8031 to load a dynamic structure, such as sequence, contour or graph, one
8032 should pass a valid destination memory storage to the function.
8033
8034 \section{Miscellaneous Functions}
8035
8036 \subsection{Miscellaneous Functions}
8037
8038 \cvfunc{CheckArr}\label{CheckArr}
8039
8040 Checks every element of input array for invalid values
8041
8042 \cvexp{
8043
8044 int  cvCheckArr( \par const CvArr* arr,\par int flags=0,\par double min\_val=0,\par double max\_val=0);
8045
8046 }{CPP}{PYTHON}
8047 \begin{lstlisting}
8048 #define cvCheckArray cvCheckArr
8049 \end{lstlisting}
8050
8051 \begin{description}
8052 \cvarg{arr}{The array to check}
8053 \cvarg{flags}{The operation flags, 0 or combination of:
8054 \begin{description}
8055 \cvarg{CV\_CHECK\_RANGE}{if set, the function checks that every value of array is within [minVal,maxVal) range, otherwise it just checks that every element is neither NaN nor $\pm \infty$.}
8056 \cvarg{CV\_CHECK\_QUIET}{if set, the function does not raises an error if an element is invalid or out of range}
8057 \end{description}}
8058 \cvarg{min\_val}{The inclusive lower boundary of valid values range. It is used only if \texttt{CV\_CHECK\_RANGE} is set.}
8059 \cvarg{max\_val}{The exclusive upper boundary of valid values range. It is used only if \texttt{CV\_CHECK\_RANGE} is set.}
8060 \end{description}
8061
8062 The function \texttt{cvCheckArr} checks that every array element is
8063 neither NaN nor $ \pm \infty $.
8064 If \texttt{CV\_CHECK\_RANGE} is set, it also
8065 checks that every element is greater than or equal to \texttt{minVal}
8066 and less than \texttt{maxVal}. The function returns nonzero if the
8067 check succeeded, i.e. all elements are valid and within the range,
8068 and zero otherwise. In the latter case if \texttt{CV\_CHECK\_QUIET}
8069 flag is not set, the function raises runtime error.
8070
8071 \cvfunc{KMeans2}\label{KMeans2}
8072
8073 Splits set of vectors by given number of clusters
8074
8075 \cvexp{
8076 void cvKMeans2( \par const CvArr* samples,\par int cluster\_count,\par CvArr* labels,\par CvTermCriteria termcrit );
8077 }{CPP}{PYTHON}
8078
8079 \begin{description}
8080 \cvarg{samples}{Floating-point matrix of input samples, one row per sample}
8081 \cvarg{cluster\_count}{Number of clusters to split the set by}
8082 \cvarg{labels}{Output integer vector storing cluster indices for every sample}
8083 \cvarg{termcrit}{Specifies maximum number of iterations and/or accuracy (distance the centers move by between the subsequent iterations)}
8084 \cvarg{attempts}{How many times the algorithm is executed using different initial labelings. The algorithm returns labels that yield the best compactness (see the last function parameter)}
8085 \cvarg{rng}{Optional external random number generator; can be used to fully control the function behaviour. }
8086 \cvarg{flags}{Can be 0 or \texttt{CV\_KMEANS\_USE\_INITIAL\_LABELS}. The latter
8087 value means that during the first (and possibly the only) attempt the
8088 function uses the user-supplied labels as the initial approximation,
8089 instead of generating random labels. For the second and further attempts
8090 the function will use randomly generated labels in any case.}
8091 \cvarg{centers}{The optional output array of the cluster centers. }
8092 \cvarg{compactness}{The optional output parameter, which is computed as
8093 \[
8094 \sum_i ||\texttt{samples}_i - \texttt{centers}_{\texttt{labels}_i}||^2
8095 \]
8096 after every attempt; the best (minimum) value is chosen and the
8097 corresponding labels are returned by the function. Basically,
8098 user can use only the core of the function, set the number of
8099 attempts to 1, initialize labels each time using a custom algorithm
8100 (\texttt{flags}=\texttt{CV\_KMEAN\_USE\_INITIAL\_LABELS}) and, based on the output compactness
8101 or any other criteria, choose the best clustering.}
8102 \end{description}
8103
8104 The function \texttt{cvKMeans2} implements k-means algorithm that finds
8105 centers of \texttt{cluster\_count} clusters and groups the input samples
8106 around the clusters. On output $\texttt{labels}_i$ contains a cluster index for
8107 sample stored in the row $i$ of \texttt{samples} matrix.
8108
8109 % Example. Clustering random samples of multi-gaussian distribution with k-means
8110 \begin{lstlisting}
8111 #include "cxcore.h"
8112 #include "highgui.h"
8113
8114 void main( int argc, char** argv )
8115 {
8116     #define MAX_CLUSTERS 5
8117     CvScalar color_tab[MAX_CLUSTERS];
8118     IplImage* img = cvCreateImage( cvSize( 500, 500 ), 8, 3 );
8119     CvRNG rng = cvRNG(0xffffffff);
8120
8121     color_tab[0] = CV_RGB(255,0,0);
8122     color_tab[1] = CV_RGB(0,255,0);
8123     color_tab[2] = CV_RGB(100,100,255);
8124     color_tab[3] = CV_RGB(255,0,255);
8125     color_tab[4] = CV_RGB(255,255,0);
8126
8127     cvNamedWindow( "clusters", 1 );
8128
8129     for(;;)
8130     {
8131         int k, cluster_count = cvRandInt(&rng)%MAX_CLUSTERS + 1;
8132         int i, sample_count = cvRandInt(&rng)%1000 + 1;
8133         CvMat* points = cvCreateMat( sample_count, 1, CV_32FC2 );
8134         CvMat* clusters = cvCreateMat( sample_count, 1, CV_32SC1 );
8135
8136         /* generate random sample from multigaussian distribution */
8137         for( k = 0; k < cluster_count; k++ )
8138         {
8139             CvPoint center;
8140             CvMat point_chunk;
8141             center.x = cvRandInt(&rng)%img->width;
8142             center.y = cvRandInt(&rng)%img->height;
8143             cvGetRows( points,
8144                        &point_chunk,
8145                        k*sample_count/cluster_count,
8146                        (k == (cluster_count - 1)) ?
8147                            sample_count :
8148                            (k+1)*sample_count/cluster_count );
8149             cvRandArr( &rng, &point_chunk, CV_RAND_NORMAL,
8150                        cvScalar(center.x,center.y,0,0),
8151                        cvScalar(img->width/6, img->height/6,0,0) );
8152         }
8153
8154         /* shuffle samples */
8155         for( i = 0; i < sample_count/2; i++ )
8156         {
8157             CvPoint2D32f* pt1 =
8158                 (CvPoint2D32f*)points->data.fl + cvRandInt(&rng)%sample_count;
8159             CvPoint2D32f* pt2 =
8160                 (CvPoint2D32f*)points->data.fl + cvRandInt(&rng)%sample_count;
8161             CvPoint2D32f temp;
8162             CV_SWAP( *pt1, *pt2, temp );
8163         }
8164
8165         cvKMeans2( points, cluster_count, clusters,
8166                    cvTermCriteria( CV_TERMCRIT_EPS+CV_TERMCRIT_ITER, 10, 1.0 ));
8167
8168         cvZero( img );
8169
8170         for( i = 0; i < sample_count; i++ )
8171         {
8172             CvPoint2D32f pt = ((CvPoint2D32f*)points->data.fl)[i];
8173             int cluster_idx = clusters->data.i[i];
8174             cvCircle( img,
8175                       cvPointFrom32f(pt),
8176                       2,
8177                       color_tab[cluster_idx],
8178                       CV_FILLED );
8179         }
8180
8181         cvReleaseMat( &points );
8182         cvReleaseMat( &clusters );
8183
8184         cvShowImage( "clusters", img );
8185
8186         int key = cvWaitKey(0);
8187         if( key == 27 )
8188             break;
8189     }
8190 }
8191 \end{lstlisting}
8192
8193 \cvfunc{SeqPartition}\label{SeqPartition}
8194
8195 Splits sequence into equivalency classes
8196
8197 \begin{lstlisting}
8198 typedef int (CV_CDECL* CvCmpFunc)(const void* a, const void* b, void* userdata);
8199 \end{lstlisting}
8200
8201 \cvexp{
8202 int cvSeqPartition( \par const CvSeq* seq,\par CvMemStorage* storage,\par CvSeq** labels,\par CvCmpFunc is\_equal,\par void* userdata );
8203 }{CPP}{PYTHON}
8204
8205 \begin{description}
8206 \cvarg{seq}{The sequence to partition}
8207 \cvarg{storage}{The storage to store the sequence of equivalency classes. If it is NULL, the function uses \texttt{seq->storage} for output labels.}
8208 \cvarg{labels}{Ouput parameter. Double pointer to the sequence of 0-based labels of input sequence elements.}
8209 \cvarg{is\_equal}{The relation function that should return non-zero if the two particular sequence elements are from the same class, and zero overwise. The partitioning algorithm uses transitive closure of the relation function as equivalency critria.}
8210 \cvarg{userdata}{Pointer that is transparently passed to the \texttt{is\_equal} function}
8211 \end{description}
8212
8213 The function \texttt{cvSeqPartition} implements quadratic algorithm for
8214 splitting a set into one or more classes of equivalency. The function
8215 returns the number of equivalency classes.
8216
8217 % Example. Partitioning 2d point set.
8218 \begin{lstlisting}
8219
8220 #include "cxcore.h"
8221 #include "highgui.h"
8222 #include <stdio.h>
8223
8224 CvSeq* point_seq = 0;
8225 IplImage* canvas = 0;
8226 CvScalar* colors = 0;
8227 int pos = 10;
8228
8229 int is_equal( const void* _a, const void* _b, void* userdata )
8230 {
8231     CvPoint a = *(const CvPoint*)_a;
8232     CvPoint b = *(const CvPoint*)_b;
8233     double threshold = *(double*)userdata;
8234     return (double)((a.x - b.x)*(a.x - b.x) + (a.y - b.y)*(a.y - b.y)) <=
8235         threshold;
8236 }
8237
8238 void on_track( int pos )
8239 {
8240     CvSeq* labels = 0;
8241     double threshold = pos*pos;
8242     int i, class_count = cvSeqPartition( point_seq,
8243                                          0,
8244                                          &labels,
8245                                          is_equal,
8246                                          &threshold );
8247     printf("%4d classes\n", class_count );
8248     cvZero( canvas );
8249
8250     for( i = 0; i < labels->total; i++ )
8251     {
8252         CvPoint pt = *(CvPoint*)cvGetSeqElem( point_seq, i, 0 );
8253         CvScalar color = colors[*(int*)cvGetSeqElem( labels, i, 0 )];
8254         cvCircle( canvas, pt, 1, color, -1 );
8255     }
8256
8257     cvShowImage( "points", canvas );
8258 }
8259
8260 int main( int argc, char** argv )
8261 {
8262     CvMemStorage* storage = cvCreateMemStorage(0);
8263     point_seq = cvCreateSeq( CV_32SC2,
8264                              sizeof(CvSeq),
8265                              sizeof(CvPoint),
8266                              storage );
8267     CvRNG rng = cvRNG(0xffffffff);
8268
8269     int width = 500, height = 500;
8270     int i, count = 1000;
8271     canvas = cvCreateImage( cvSize(width,height), 8, 3 );
8272
8273     colors = (CvScalar*)cvAlloc( count*sizeof(colors[0]) );
8274     for( i = 0; i < count; i++ )
8275     {
8276         CvPoint pt;
8277         int icolor;
8278         pt.x = cvRandInt( &rng ) % width;
8279         pt.y = cvRandInt( &rng ) % height;
8280         cvSeqPush( point_seq, &pt );
8281         icolor = cvRandInt( &rng ) | 0x00404040;
8282         colors[i] = CV_RGB(icolor & 255,
8283                            (icolor >> 8)&255,
8284                            (icolor >> 16)&255);
8285     }
8286
8287     cvNamedWindow( "points", 1 );
8288     cvCreateTrackbar( "threshold", "points", &pos, 50, on_track );
8289     on_track(pos);
8290     cvWaitKey(0);
8291     return 0;
8292 }
8293 \end{lstlisting}
8294
8295
8296 \section{Error Handling and System Functions}
8297
8298 \subsection{Error Handling}
8299
8300 Error handling in OpenCV is similar to IPL (Image Processing
8301 Library). In case of error functions do not return the error
8302 code. Instead, they raise an error using \texttt{CV\_ERROR}
8303 macro that calls \cross{Error} that, in its turn, sets the error
8304 status with \cross{SetErrStatus} and calls a standard or user-defined
8305 error handler (that can display a message box, write to log etc., see
8306 \cross{RedirectError}, There is global variable, one per each program
8307 thread, that contains current error status (an integer value). The status
8308 can be retrieved with \cross{GetErrStatus} function.
8309
8310 There are three modes of error handling (see \cross{SetErrMode} and
8311 \cross{GetErrMode}):
8312
8313 \begin{description}
8314 \cvarg{Leaf}{The program is terminated after error handler is
8315 called. This is the default value. It is useful for debugging, as the
8316 error is signalled immediately after it occurs. However, for production
8317 systems other two methods may be preferable as they provide more
8318 control.}
8319 \cvarg{Parent}{The program is not terminated, but the error handler
8320 is called. The stack is unwinded (it is done w/o using C++ exception
8321 mechanism). User may check error code after calling CxCore function with
8322 \cross{GetErrStatus} and react.}
8323 \cvarg{Silent}{Similar to \texttt{Parent} mode, but no error handler
8324 is called}
8325 \end{description}
8326
8327 Actually, the semantics of \texttt{Leaf} and \texttt{Parent} modes is implemented by error handlers and the above description is true for . \cross{GuiBoxReport} behaves slightly differently, and some custom error handler may implement quite different semantics.  XXX - unintelligible; rewrite 
8328
8329 \cvfunc{ERROR Handling Macros}\label{ERROR Handling Macros}
8330
8331 Macros for raising an error, checking for errors etc.
8332
8333 \begin{lstlisting}
8334
8335 /* special macros for enclosing processing statements within a function and separating
8336    them from prologue (resource initialization) and epilogue (guaranteed resource release) */
8337 #define __BEGIN__       {
8338 #define __END__         goto exit; exit: ; }
8339 /* proceeds to "resource release" stage */
8340 #define EXIT            goto exit
8341
8342 /* Declares locally the function name for CV_ERROR() use */
8343 #define CV_FUNCNAME( Name )  \
8344     static char cvFuncName[] = Name
8345
8346 /* Raises an error within the current context */
8347 #define CV_ERROR( Code, Msg )                                       \
8348 {                                                                   \
8349      cvError( (Code), cvFuncName, Msg, __FILE__, __LINE__ );        \
8350      EXIT;                                                          \
8351 }
8352
8353 /* Checks status after calling CXCORE function */
8354 #define CV_CHECK()                                                  \
8355 {                                                                   \
8356     if( cvGetErrStatus() < 0 )                                   \
8357         CV_ERROR( CV_StsBackTrace, "Inner function failed." );      \
8358 }
8359
8360 /* Provies shorthand for CXCORE function call and CV_CHECK() */
8361 #define CV_CALL( Statement )                                        \
8362 {                                                                   \
8363     Statement;                                                      \
8364     CV_CHECK();                                                     \
8365 }
8366
8367 /* Checks some condition in both debug and release configurations */
8368 #define CV_ASSERT( Condition )                                          \
8369 {                                                                       \
8370     if( !(Condition) )                                                  \
8371         CV_ERROR( CV_StsInternal, "Assertion: " #Condition " failed" ); \
8372 }
8373
8374 /* these macros are similar to their CV_... counterparts, but they
8375    do not need exit label nor cvFuncName to be defined */
8376 #define OPENCV_ERROR(status,func_name,err_msg) ...
8377 #define OPENCV_ERRCHK(func_name,err_msg) ...
8378 #define OPENCV_ASSERT(condition,func_name,err_msg) ...
8379 #define OPENCV_CALL(statement) ...
8380
8381 \end{lstlisting}
8382
8383 Instead of a discussion, here are the documented example of typical CXCORE function and the example of the function use.
8384
8385 % Example: Use of Error Handling Macros
8386 \begin{lstlisting}
8387
8388 #include "cxcore.h"
8389 #include <stdio.h>
8390
8391 void cvResizeDCT( CvMat* input_array, CvMat* output_array )
8392 {
8393     CvMat* temp_array = 0; // declare pointer that should be released anyway.
8394
8395     CV_FUNCNAME( "cvResizeDCT" ); // declare cvFuncName
8396
8397     __BEGIN__; // start processing. There may be some declarations just after this macro,
8398                // but they couldn't be accessed from the epilogue.
8399
8400     if( !CV_IS_MAT(input_array) || !CV_IS_MAT(output_array) )
8401         // use CV_ERROR() to raise an error
8402         CV_ERROR( CV_StsBadArg, "input_array or output_array are not valid matrices" );
8403
8404     // some restrictions that are going to be removed later, may be checked with CV_ASSERT()
8405     CV_ASSERT( input_array->rows == 1 && output_array->rows == 1 );
8406
8407     // use CV_CALL for safe function call
8408     CV_CALL( temp_array = cvCreateMat( input_array->rows,
8409                                        MAX(input_array->cols,output_array->cols),
8410                                        input_array->type ));
8411
8412     if( output_array->cols > input_array->cols )
8413         CV_CALL( cvZero( temp_array ));
8414
8415     temp_array->cols = input_array->cols;
8416     CV_CALL( cvDCT( input_array, temp_array, CV_DXT_FORWARD ));
8417     temp_array->cols = output_array->cols;
8418     CV_CALL( cvDCT( temp_array, output_array, CV_DXT_INVERSE ));
8419     CV_CALL( cvScale( output_array,
8420                       output_array,
8421                       1./sqrt((double)input_array->cols*output_array->cols), 0 ));
8422
8423     __END__; // finish processing. Epilogue follows after the macro.
8424
8425     // release temp_array. If temp_array has not been allocated
8426     // before an error occured, cvReleaseMat
8427     // takes care of it and does nothing in this case.
8428     cvReleaseMat( &temp_array );
8429 }
8430
8431 int main( int argc, char** argv )
8432 {
8433     CvMat* src = cvCreateMat( 1, 512, CV_32F );
8434 #if 1 /* no errors */
8435     CvMat* dst = cvCreateMat( 1, 256, CV_32F );
8436 #else
8437     CvMat* dst = 0; /* test error processing mechanism */
8438 #endif
8439     cvSet( src, cvRealScalar(1.), 0 );
8440 #if 0 /* change 0 to 1 to suppress error handler invocation */
8441     cvSetErrMode( CV_ErrModeSilent );
8442 #endif
8443     cvResizeDCT( src, dst ); // if some error occurs, the message
8444                              // box will popup, or a message will be
8445                              // written to log, or some user-defined
8446                              // processing will be done
8447     if( cvGetErrStatus() < 0 )
8448         printf("Some error occured" );
8449     else
8450         printf("Everything is OK" );
8451     return 0;
8452 }
8453
8454 \end{lstlisting}
8455
8456 \cvfunc{GetErrStatus}\label{GetErrStatus}
8457
8458 Returns the current error status
8459
8460 \cvexp{
8461 int cvGetErrStatus( void );
8462 }{CPP}{PYTHON}
8463
8464 The function \texttt{cvGetErrStatus} returns the current error status -
8465 the value set with the last \cross{SetErrStatus} call. Note, that in
8466 \texttt{Leaf} mode the program terminates immediately after
8467 error occured, so to always get control after the function call,
8468 one should call \cross{SetErrMode} and set \texttt{Parent}
8469 or \texttt{Silent} error mode.
8470
8471 \cvfunc{SetErrStatus}\label{SetErrStatus}
8472
8473 Sets the error status
8474
8475 \cvexp{
8476 void cvSetErrStatus( int status );
8477 }{CPP}{PYTHON}
8478
8479 \begin{description}
8480 \cvarg{status}{The error status}
8481 \end{description}
8482
8483 The function \texttt{cvSetErrStatus} sets the error status to the specified value. Mostly, the function is used to reset the error status (set to it \texttt{CV\_StsOk}) to recover after error. In other cases it is more natural to call \cross{Error} or \texttt{CV\_ERROR}.
8484
8485 \cvfunc{GetErrMode}\label{GetErrMode}
8486
8487 Returns the current error mode
8488
8489 \cvexp{
8490 int cvGetErrMode( void );
8491 }{CPP}{PYTHON}
8492
8493 The function \texttt{cvGetErrMode} returns the current error mode - the value set with the last \cross{SetErrMode} call.
8494
8495 \cvfunc{SetErrMode}\label{SetErrMode}
8496
8497 Sets the error mode
8498
8499 \begin{lstlisting}
8500 #define CV_ErrModeLeaf    0
8501 #define CV_ErrModeParent  1
8502 #define CV_ErrModeSilent  2
8503 \end{lstlisting}
8504
8505 \cvexp{
8506 int cvSetErrMode( int mode );
8507 }{CPP}{PYTHON}
8508
8509 \begin{description}
8510 \cvarg{mode}{The error mode}
8511 \end{description}
8512
8513 The function \texttt{cvSetErrMode} sets the specified error mode. For description of different error modes see the beginning of the error section.
8514
8515 \cvfunc{Error}\label{Error}
8516
8517 Raises an error
8518
8519 \cvexp{
8520 int cvError( \par int status,\par const char* func\_name,\par const char* err\_msg,\par const char* file\_name,\par int line );
8521 }{CPP}{PYTHON}
8522
8523 \begin{description}
8524 \cvarg{status}{The error status}
8525 \cvarg{func\_name}{Name of the function where the error occured}
8526 \cvarg{err\_msg}{Additional information/diagnostics about the error}
8527 \cvarg{file\_name}{Name of the file where the error occured}
8528 \cvarg{line}{Line number, where the error occured}
8529 \end{description}
8530
8531 The function \texttt{cvError} sets the error status to the specified value (via \cross{SetErrStatus}) and, if the error mode is not \texttt{Silent}, calls the error handler.
8532
8533 \cvfunc{ErrorStr}\label{ErrorStr}
8534
8535 Returns textual description of error status code
8536
8537 \cvexp{
8538 const char* cvErrorStr( int status );
8539 }{CPP}{PYTHON}
8540
8541 \begin{description}
8542 \cvarg{status}{The error status}
8543 \end{description}
8544
8545 The function \texttt{cvErrorStr} returns the textual description for
8546 the specified error status code. In case of unknown status the function
8547 returns NULL pointer.
8548
8549 \cvfunc{RedirectError}\label{RedirectError}
8550
8551 Sets a new error handler
8552
8553 \begin{lstlisting}
8554 typedef int (CV_CDECL *CvErrorCallback)( int status, const char* func_name,
8555                     const char* err_msg, const char* file_name, int line );
8556 \end{lstlisting}
8557
8558 \cvexp{
8559 CvErrorCallback cvRedirectError( \par CvErrorCallback error\_handler,\par void* userdata=NULL,\par void** prev\_userdata=NULL );
8560 }{CPP}{PYTHON}
8561
8562 \begin{description}
8563 \cvarg{error\_handler}{The new error\_handler}
8564 \cvarg{userdata}{Arbitrary pointer that is transparently passed to the error handler}
8565 \cvarg{prev\_userdata}{Pointer to the previously assigned user data pointer}
8566 \end{description}
8567
8568 The function \texttt{cvRedirectError} sets a new error handler that
8569 can be one of standard handlers or a custom handler
8570 that has the certain interface. The handler takes the same parameters
8571 as \cross{Error} function. If the handler returns non-zero value, the
8572 program is terminated, otherwise, it continues. The error handler may
8573 check the current error mode with \cross{GetErrMode} to make a decision.
8574
8575
8576 \cvfunc{cvNulDevReport cvStdErrReport cvGuiBoxReport}
8577 \label{cvNulDevReport}
8578 \label{cvStdErrReport}
8579 \label{cvGuiBoxReport}
8580
8581 Provide standard error handling
8582
8583 \begin{lstlisting}
8584
8585 int cvNulDevReport( int status, const char* func_name,
8586                     const char* err_msg, const char* file_name,
8587                     int line, void* userdata );
8588
8589 int cvStdErrReport( int status, const char* func_name,
8590                     const char* err_msg, const char* file_name,
8591                     int line, void* userdata );
8592
8593 int cvGuiBoxReport( int status, const char* func_name,
8594                     const char* err_msg, const char* file_name,
8595                     int line, void* userdata );
8596
8597 \end{lstlisting}
8598
8599 \begin{description}
8600 \cvarg{status}{The error status}
8601 \cvarg{func\_name}{Name of the function where the error occured}
8602 \cvarg{err\_msg}{Additional information/diagnostics about the error}
8603 \cvarg{file\_name}{Name of the file where the error occured}
8604 \cvarg{line}{Line number, where the error occured}
8605 \cvarg{userdata}{Pointer to the user data. Ignored by the standard handlers.}
8606 \end{description}
8607
8608 The functions \texttt{cvNullDevReport}, \texttt{cvStdErrReport}
8609 and \texttt{cvGuiBoxReport} provide standard error
8610 handling. \texttt{cvGuiBoxReport} is the default error
8611 handler on Win32 systems, \texttt{cvStdErrReport} - on other
8612 systems. \texttt{cvGuiBoxReport} pops up message box with the error
8613 description and suggest a few options. Below is the sample message box
8614 that may be recieved with the sample code above, if one introduce an
8615 error as described in the sample
8616
8617 Error Message Box
8618
8619 \includegraphics[width=0.5\textwidth]{pics/errmsg.png}
8620
8621 If the error handler is set \texttt{cvStdErrReport}, the above message will be printed to standard error output and program will be terminated or continued, depending on the current error mode.
8622
8623 Error Message printed to Standard Error Output (in \texttt{Leaf} mode)
8624
8625 \begin{verbatim}
8626 OpenCV ERROR: Bad argument (input_array or output_array are not valid matrices)
8627         in function cvResizeDCT, D:\User\VP\Projects\avl\_proba\a.cpp(75)
8628 Terminating the application...
8629 \end{verbatim}
8630
8631 \subsection{System and Utility Functions}
8632
8633 \cvfunc{Alloc}\label{Alloc}
8634
8635 Allocates memory buffer
8636
8637 \cvexp{
8638 void* cvAlloc( size\_t size );
8639 }{CPP}{PYTHON}
8640
8641 \begin{description}
8642 \cvarg{size}{Buffer size in bytes}
8643 \end{description}
8644
8645 The function \texttt{cvAlloc} allocates \texttt{size} bytes and returns
8646 pointer to the allocated buffer. In case of error the function reports an
8647 error and returns NULL pointer. By default \texttt{cvAlloc} calls
8648 \texttt{icvAlloc} which
8649 itself calls malloc, however it is possible to assign user-defined memory
8650 allocation/deallocation functions using \cross{SetMemoryManager} function.
8651
8652 \cvfunc{Free}\label{Free}
8653
8654 Deallocates memory buffer
8655
8656 \cvexp{
8657
8658 void cvFree( void** ptr );
8659
8660 }{CPP}{PYTHON}
8661
8662 \begin{description}
8663 \cvarg{ptr}{Double pointer to released buffer}
8664 \end{description}
8665
8666 The function \texttt{cvFree} deallocates memory buffer allocated by
8667 \cross{Alloc}. It clears the pointer to buffer upon exit, that is why
8668 the double pointer is used. If \texttt{*buffer} is already NULL, the function
8669 does nothing
8670
8671 \cvfunc{GetTickCount}\label{GetTickCount}
8672
8673 Returns number of ticks
8674
8675 \cvexp{
8676 int64 cvGetTickCount( void );
8677 }{CPP}{PYTHON}
8678
8679 The function \texttt{cvGetTickCount} returns number of ticks starting from some platform-dependent event (number of CPU ticks from the startup, number of milliseconds from 1970th year etc.). The function is useful for accurate measurement of a function/user-code execution time. To convert the number of ticks to time units, use \cross{GetTickFrequency}.
8680
8681 \cvfunc{GetTickFrequency}\label{GetTickFrequency}
8682
8683 Returns number of ticks per microsecond
8684
8685 \cvexp{
8686
8687 double cvGetTickFrequency( void );
8688
8689 }{CPP}{PYTHON}
8690
8691 The function \texttt{cvGetTickFrequency} returns number of ticks per microsecond. Thus, the quotient of \cross{GetTickCount} and \cross{GetTickFrequency} will give a number of microseconds starting from the platform-dependent event.
8692
8693 \cvfunc{RegisterModule}\label{RegisterModule}
8694
8695 Registers another module
8696
8697 \begin{lstlisting}
8698 typedef struct CvPluginFuncInfo
8699 {
8700     void** func_addr;
8701     void* default_func_addr;
8702     const char* func_names;
8703     int search_modules;
8704     int loaded_from;
8705 }
8706 CvPluginFuncInfo;
8707
8708 typedef struct CvModuleInfo
8709 {
8710     struct CvModuleInfo* next;
8711     const char* name;
8712     const char* version;
8713     CvPluginFuncInfo* func_tab;
8714 }
8715 CvModuleInfo;
8716 \end{lstlisting}
8717
8718 \cvexp{
8719 int cvRegisterModule( const CvModuleInfo* module\_info );
8720 }{CPP}{PYTHON}
8721
8722 \begin{description}
8723 \cvarg{module\_info}{Information about the module}
8724 \end{description}
8725
8726 The function \texttt{cvRegisterModule} adds module to the list of
8727 registered modules. After the module is registered, information about
8728 it can be retrieved using \cross{GetModuleInfo} function. Also, the
8729 registered module makes full use of optimized plugins (IPP, MKL, ...),
8730 supported by CXCORE. CXCORE itself, CV (computer vision), CVAUX (auxilary
8731 computer vision) and HIGHGUI (visualization and image/video acquisition) are
8732 examples of modules. Registration is usually done then the shared library
8733 is loaded. See \texttt{cxcore/src/cxswitcher.cpp} and
8734 \texttt{cv/src/cvswitcher.cpp} for details, how registration is done
8735 and look at \texttt{cxcore/src/cxswitcher.cpp}, \texttt{cxcore/src/\_cxipp.h}
8736 on how IPP and MKL are connected to the modules.
8737
8738 \cvfunc{GetModuleInfo}\label{GetModuleInfo}
8739
8740 Retrieves information about the registered module(s) and plugins
8741
8742 \cvexp{
8743 void  cvGetModuleInfo( \par const char* module\_name,\par const char** version,\par const char** loaded\_addon\_plugins );
8744 }{CPP}{PYTHON}
8745
8746 \begin{description}
8747 \cvarg{module\_name}{Name of the module of interest, or NULL, which means all the modules}
8748 \cvarg{version}{The output parameter. Information about the module(s), including version.}
8749 \cvarg{loaded\_addon\_plugins}{The list of names and versions of the optimized plugins that CXCORE was able to find and load}
8750 \end{description}
8751
8752 The function \texttt{cvGetModuleInfo} returns information about one of or
8753 all of the registered modules. The returned information is stored inside
8754 the libraries, so user should not deallocate or modify the returned
8755 text strings.
8756
8757 \cvfunc{UseOptimized}\label{UseOptimized}
8758
8759 Switches between optimized/non-optimized modes
8760
8761 \cvexp{
8762
8763 int cvUseOptimized( int on\_off );
8764
8765 }{CPP}{PYTHON}
8766
8767 \begin{description}
8768 \cvarg{on\_off}{Use optimized ($\ne 0$) or not ($=0$)}
8769 \end{description}
8770
8771 The function \texttt{cvUseOptimized} switches between the mode, where
8772 only pure C implementations from cxcore, OpenCV etc. are used, and
8773 the mode, where IPP and MKL functions are used if available. When
8774 \texttt{cvUseOptimized(0)} is called, all the optimized libraries are
8775 unloaded. The function may be useful for debugging, IPP and MKL upgrade on
8776 the fly, online speed comparisons etc. It returns the number of optimized
8777 functions loaded. Note that by default the optimized plugins are loaded,
8778 so it is not necessary to call \texttt{cvUseOptimized(1)} in the beginning of
8779 the program (actually, it will only increase the startup time)
8780
8781 \cvfunc{SetMemoryManager}\label{SetMemoryManager}
8782
8783 Assings custom/default memory managing functions
8784
8785 \begin{lstlisting}
8786 typedef void* (CV_CDECL *CvAllocFunc)(size_t size, void* userdata);
8787 typedef int (CV_CDECL *CvFreeFunc)(void* pptr, void* userdata);
8788 \end{lstlisting}
8789
8790 \cvexp{
8791 void cvSetMemoryManager( \par CvAllocFunc alloc\_func=NULL,\par CvFreeFunc free\_func=NULL,\par void* userdata=NULL );
8792 }{CPP}{PYTHON}
8793
8794 \begin{description}
8795 \cvarg{alloc\_func}{Allocation function; the interface is similar to \texttt{malloc}, except that \texttt{userdata} may be used to determine the context}
8796 \cvarg{free\_func}{Deallocation function; the interface is similar to \texttt{free}}
8797 \cvarg{userdata}{User data that is transparetly passed to the custom functions}
8798 \end{description}
8799
8800 The function \texttt{cvSetMemoryManager} sets user-defined memory
8801 managment functions (substitutors for malloc and free) that will be called
8802 by cvAlloc, cvFree and higher-level functions (e.g. cvCreateImage). Note,
8803 that the function should be called when there is data allocated using
8804 cvAlloc. Also, to avoid infinite recursive calls, it is not
8805 allowed to call cvAlloc and \cross{Free} from the custom
8806 allocation/deallocation functions.
8807
8808 If \texttt{alloc\_func} and \texttt{free\_func} pointers are
8809 \texttt{NULL}, the default memory managing functions are restored.
8810
8811 \cvfunc{SetIPLAllocators}\label{SetIPLAllocators}
8812
8813 Switches to IPL functions for image allocation/deallocation
8814
8815 \begin{lstlisting}
8816 typedef IplImage* (CV_STDCALL* Cv_iplCreateImageHeader)
8817                             (int,int,int,char*,char*,int,int,int,int,int,
8818                             IplROI*,IplImage*,void*,IplTileInfo*);
8819 typedef void (CV_STDCALL* Cv_iplAllocateImageData)(IplImage*,int,int);
8820 typedef void (CV_STDCALL* Cv_iplDeallocate)(IplImage*,int);
8821 typedef IplROI* (CV_STDCALL* Cv_iplCreateROI)(int,int,int,int,int);
8822 typedef IplImage* (CV_STDCALL* Cv_iplCloneImage)(const IplImage*);
8823
8824 #define CV_TURN_ON_IPL_COMPATIBILITY()                                  \
8825     cvSetIPLAllocators( iplCreateImageHeader, iplAllocateImage,         \
8826                         iplDeallocate, iplCreateROI, iplCloneImage )
8827 \end{lstlisting}
8828
8829 \cvexp{
8830 void cvSetIPLAllocators( \par
8831                          Cv\_iplCreateImageHeader create\_header, \par
8832                          Cv\_iplAllocateImageData allocate\_data, \par
8833                          Cv\_iplDeallocate deallocate, \par
8834                          Cv\_iplCreateROI create\_roi, \par
8835                          Cv\_iplCloneImage clone\_image );
8836 }{CPP}{PYTHON}
8837
8838 \begin{description}
8839 \cvarg{create\_header}{Pointer to iplCreateImageHeader}
8840 \cvarg{allocate\_data}{Pointer to iplAllocateImage}
8841 \cvarg{deallocate}{Pointer to iplDeallocate}
8842 \cvarg{create\_roi}{Pointer to iplCreateROI}
8843 \cvarg{clone\_image}{Pointer to iplCloneImage}
8844 \end{description}
8845
8846
8847 The function \texttt{cvSetIPLAllocators} makes CXCORE to use IPL functions
8848 for image allocation/deallocation operations. For convenience, there
8849 is the wrapping macro \texttt{CV\_TURN\_ON\_IPL\_COMPATIBILITY}. The
8850 function is useful for applications where IPL and CXCORE/OpenCV are used
8851 together and still there are calls to \texttt{iplCreateImageHeader}
8852 etc. The function is not necessary if IPL is called only for data
8853 processing and all the allocation/deallocation is done by CXCORE, or
8854 if all the allocation/deallocation is done by IPL and some of OpenCV
8855 functions are used to process the data.