]> rtime.felk.cvut.cz Git - opencv.git/blob - opencv/doc/cxcore_array_operations.tex
Problems found by tool. Added GetRows deltaRow arg; SVD args fixed; FindHomography...
[opencv.git] / opencv / doc / cxcore_array_operations.tex
1 \section{Operations on Arrays}
2
3 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4 %                                                                                    %
5 %                                         C                                          %
6 %                                                                                    %
7 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
8
9 \ifCPy
10
11 \cvCPyFunc{AbsDiff}
12 Calculates absolute difference between two arrays.
13
14 \cvdefC{void cvAbsDiff(const CvArr* src1, const CvArr* src2, CvArr* dst);}
15 \cvdefPy{AbsDiff(src1,src2,dst)-> None}
16
17 \begin{description}
18 \cvarg{src1}{The first source array}
19 \cvarg{src2}{The second source array}
20 \cvarg{dst}{The destination array}
21 \end{description}
22
23 The function calculates absolute difference between two arrays.
24
25 \[ \texttt{dst}(i)_c = |\texttt{src1}(I)_c - \texttt{src2}(I)_c| \]
26
27 All the arrays must have the same data type and the same size (or ROI size).
28
29 \cvCPyFunc{AbsDiffS}
30 Calculates absolute difference between an array and a scalar.
31
32 \cvdefC{void cvAbsDiffS(const CvArr* src, CvArr* dst, CvScalar value);}
33 \cvdefPy{AbsDiffS(src,value,dst)-> None}
34 \ifC
35 \begin{lstlisting}
36 #define cvAbs(src, dst) cvAbsDiffS(src, dst, cvScalarAll(0))
37 \end{lstlisting}
38 \fi
39 \begin{description}
40 \cvarg{src}{The source array}
41 \cvarg{dst}{The destination array}
42 \cvarg{value}{The scalar}
43 \end{description}
44
45 The function calculates absolute difference between an array and a scalar.
46
47 \[ \texttt{dst}(i)_c = |\texttt{src}(I)_c - \texttt{value}_c| \]
48
49 All the arrays must have the same data type and the same size (or ROI size).
50
51
52 \cvCPyFunc{Add}
53 Computes the per-element sum of two arrays.
54
55 \cvdefC{void cvAdd(const CvArr* src1, const CvArr* src2, CvArr* dst, const CvArr* mask=NULL);}
56 \cvdefPy{Add(src1,src2,dst,mask=NULL)-> None}
57
58 \begin{description}
59 \cvarg{src1}{The first source array}
60 \cvarg{src2}{The second source array}
61 \cvarg{dst}{The destination array}
62 \cvarg{mask}{Operation mask, 8-bit single channel array; specifies elements of the destination array to be changed}
63 \end{description}
64
65 The function adds one array to another:
66
67 \begin{lstlisting}
68 dst(I)=src1(I)+src2(I) if mask(I)!=0
69 \end{lstlisting}
70
71 All the arrays must have the same type, except the mask, and the same size (or ROI size).
72 For types that have limited range this operation is saturating.
73
74 \cvCPyFunc{AddS}
75 Computes the sum of an array and a scalar.
76
77 \cvdefC{void cvAddS(const CvArr* src, CvScalar value, CvArr* dst, const CvArr* mask=NULL);}
78 \cvdefPy{AddS(src,value,dst,mask=NULL)-> None}
79
80 \begin{description}
81 \cvarg{src}{The source array}
82 \cvarg{value}{Added scalar}
83 \cvarg{dst}{The destination array}
84 \cvarg{mask}{Operation mask, 8-bit single channel array; specifies elements of the destination array to be changed}
85 \end{description}
86
87 The function adds a scalar \texttt{value} to every element in the source array \texttt{src1} and stores the result in \texttt{dst}.
88 For types that have limited range this operation is saturating.
89
90 \begin{lstlisting}
91 dst(I)=src(I)+value if mask(I)!=0
92 \end{lstlisting}
93
94 All the arrays must have the same type, except the mask, and the same size (or ROI size).
95
96
97 \cvCPyFunc{AddWeighted}
98 Computes the weighted sum of two arrays.
99
100 \cvdefC{void  cvAddWeighted(const CvArr* src1, double alpha,
101                      const CvArr* src2, double beta,
102                      double gamma, CvArr* dst);}
103 \cvdefPy{AddWeighted(src1,alpha,src2,beta,gamma,dst)-> None}
104
105 \begin{description}
106 \cvarg{src1}{The first source array}
107 \cvarg{alpha}{Weight for the first array elements}
108 \cvarg{src2}{The second source array}
109 \cvarg{beta}{Weight for the second array elements}
110 \cvarg{dst}{The destination array}
111 \cvarg{gamma}{Scalar, added to each sum}
112 \end{description}
113
114 The function calculates the weighted sum of two arrays as follows:
115
116 \begin{lstlisting}
117 dst(I)=src1(I)*alpha+src2(I)*beta+gamma
118 \end{lstlisting}
119
120 All the arrays must have the same type and the same size (or ROI size).
121 For types that have limited range this operation is saturating.
122
123
124 \cvCPyFunc{And}
125 Calculates per-element bit-wise conjunction of two arrays.
126
127 \cvdefC{void cvAnd(const CvArr* src1, const CvArr* src2, CvArr* dst, const CvArr* mask=NULL);}
128 \cvdefPy{And(src1,src2,dst,mask=NULL)-> None}
129
130 \begin{description}
131 \cvarg{src1}{The first source array}
132 \cvarg{src2}{The second source array}
133 \cvarg{dst}{The destination array}
134 \cvarg{mask}{Operation mask, 8-bit single channel array; specifies elements of the destination array to be changed}
135 \end{description}
136
137 The function calculates per-element bit-wise logical conjunction of two arrays:
138
139 \begin{lstlisting}
140 dst(I)=src1(I)&src2(I) if mask(I)!=0
141 \end{lstlisting}
142
143 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.
144
145 \cvCPyFunc{AndS}
146 Calculates per-element bit-wise conjunction of an array and a scalar.
147
148 \cvdefC{void cvAndS(const CvArr* src, CvScalar value, CvArr* dst, const CvArr* mask=NULL);}
149 \cvdefPy{AndS(src,value,dst,mask=NULL)-> None}
150
151 \begin{description}
152 \cvarg{src}{The source array}
153 \cvarg{value}{Scalar to use in the operation}
154 \cvarg{dst}{The destination array}
155 \cvarg{mask}{Operation mask, 8-bit single channel array; specifies elements of the destination array to be changed}
156 \end{description}
157
158 The function calculates per-element bit-wise conjunction of an array and a scalar:
159
160 \begin{lstlisting}
161 dst(I)=src(I)&value if mask(I)!=0
162 \end{lstlisting}
163
164 Prior to the actual operation, the scalar is converted to the same type as that of the array(s). In the case of floating-point arrays their bit representations are used for the operation. All the arrays must have the same type, except the mask, and the same size.
165
166 The following sample demonstrates how to calculate the absolute value of floating-point array elements by clearing the most-significant bit:
167
168 \begin{lstlisting}
169 float a[] = { -1, 2, -3, 4, -5, 6, -7, 8, -9 };
170 CvMat A = cvMat(3, 3, CV\_32F, &a);
171 int i, absMask = 0x7fffffff;
172 cvAndS(&A, cvRealScalar(*(float*)&absMask), &A, 0);
173 for(i = 0; i < 9; i++ )
174     printf("%.1f ", a[i]);
175 \end{lstlisting}
176
177 The code should print:
178
179 \begin{lstlisting}
180 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0
181 \end{lstlisting}
182
183
184 \cvCPyFunc{Avg}
185 Calculates average (mean) of array elements.
186
187 \cvdefC{CvScalar cvAvg(const CvArr* arr, const CvArr* mask=NULL);}
188 \cvdefPy{Avg(arr,mask=NULL)-> CvScalar}
189
190 \begin{description}
191 \cvarg{arr}{The array}
192 \cvarg{mask}{The optional operation mask}
193 \end{description}
194
195 The function calculates the average value \texttt{M} of array elements, independently for each channel:
196
197 \[
198 \begin{array}{l}
199 N = \sum_I (\texttt{mask}(I) \ne 0)\\
200 M_c = \frac{\sum_{ I, \, \texttt{mask}(I) \ne 0} \texttt{arr}(I)_c}{N}
201 \end{array}
202 \]
203
204 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 $ .
205
206 \cvCPyFunc{AvgSdv}
207 Calculates average (mean) of array elements.
208
209 \cvdefC{void cvAvgSdv(const CvArr* arr, CvScalar* mean, CvScalar* stdDev, const CvArr* mask=NULL);}
210 \cvdefPy{AvgSdv(arr,mask=NULL)-> (mean, stdDev)}
211
212 \begin{description}
213 \cvarg{arr}{The array}
214 \ifC
215 \cvarg{mean}{Pointer to the output mean value, may be NULL if it is not needed}
216 \cvarg{stdDev}{Pointer to the output standard deviation}
217 \fi
218 \cvarg{mask}{The optional operation mask}
219 \ifPy
220 \cvarg{mean}{Mean value, a CvScalar}
221 \cvarg{stdDev}{Standard deviation, a CvScalar}
222 \fi
223
224 \end{description}
225
226 The function calculates the average value and standard deviation of array elements, independently for each channel:
227
228 \[
229 \begin{array}{l}
230 N = \sum_I (\texttt{mask}(I) \ne 0)\\
231 mean_c = \frac{1}{N} \, \sum_{ I, \, \texttt{mask}(I) \ne 0} \texttt{arr}(I)_c\\
232 stdDev_c = \sqrt{\frac{1}{N} \, \sum_{ I, \, \texttt{mask}(I) \ne 0} (\texttt{arr}(I)_c - mean_c)^2}
233 \end{array}
234 \]
235
236 If the array is \texttt{IplImage} and COI is set, the function processes the selected channel only and stores the average and standard deviation to the first components of the output scalars ($mean_0$ and $stdDev_0$).
237
238 \cvCPyFunc{CalcCovarMatrix}
239 Calculates covariance matrix of a set of vectors.
240
241 \cvdefC{
242 void cvCalcCovarMatrix(\par const CvArr** vects,\par int count,\par CvArr* covMat,\par CvArr* avg,\par int flags);}
243 \cvdefPy{CalcCovarMatrix(vects,covMat,avg,flags)-> None}
244
245 \begin{description}
246 \cvarg{vects}{The input vectors, all of which must have the same type and the same size. The vectors do not have to be 1D, they can be 2D (e.g., images) and so forth}
247 \ifC
248 \cvarg{count}{The number of input vectors}
249 \fi
250 \cvarg{covMat}{The output covariance matrix that should be floating-point and square}
251 \cvarg{avg}{The input or output (depending on the flags) array - the mean (average) vector of the input vectors}
252 \cvarg{flags}{The operation flags, a combination of the following values
253 \begin{description}
254 \cvarg{CV\_COVAR\_SCRAMBLED}{The output covariance matrix is calculated as:
255 \[
256  \texttt{scale} * [ \texttt{vects} [0]- \texttt{avg} ,\texttt{vects} [1]- \texttt{avg} ,...]^T \cdot [\texttt{vects} [0]-\texttt{avg} ,\texttt{vects} [1]-\texttt{avg} ,...] 
257 \],
258 that is, the covariance matrix is
259 $\texttt{count} \times \texttt{count}$.
260 Such an unusual covariance matrix is used for fast PCA
261 of a set of very large vectors (see, for example, the EigenFaces technique
262 for face recognition). Eigenvalues of this "scrambled" matrix will
263 match the eigenvalues of the true covariance matrix and the "true"
264 eigenvectors can be easily calculated from the eigenvectors of the
265 "scrambled" covariance matrix.}
266 \cvarg{CV\_COVAR\_NORMAL}{The output covariance matrix is calculated as:
267 \[
268  \texttt{scale} * [ \texttt{vects} [0]- \texttt{avg} ,\texttt{vects} [1]- \texttt{avg} ,...] \cdot [\texttt{vects} [0]-\texttt{avg} ,\texttt{vects} [1]-\texttt{avg} ,...]^T 
269 \],
270 that is, \texttt{covMat} will be a covariance matrix
271 with the same linear size as the total number of elements in each
272 input vector. One and only one of \texttt{CV\_COVAR\_SCRAMBLED} and
273 \texttt{CV\_COVAR\_NORMAL} must be specified}
274 \cvarg{CV\_COVAR\_USE\_AVG}{If the flag is specified, the function does not calculate \texttt{avg} from the input vectors, but, instead, uses the passed \texttt{avg} vector. This is useful if \texttt{avg} has been already calculated somehow, or if the covariance matrix is calculated by parts - in this case, \texttt{avg} is not a mean vector of the input sub-set of vectors, but rather the mean vector of the whole set.}
275 \cvarg{CV\_COVAR\_SCALE}{If the flag is specified, the covariance matrix is scaled. In the "normal" mode \texttt{scale} is '1./count'; in the "scrambled" mode \texttt{scale} is the reciprocal of the total number of elements in each input vector. By default (if the flag is not specified) the covariance matrix is not scaled ('scale=1').}
276
277 \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.}
278 \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.}
279
280 \end{description}}
281 \end{description}
282
283 The function calculates the covariance matrix
284 and, optionally, the mean vector of the set of input vectors. The function
285 can be used for PCA, for comparing vectors using Mahalanobis distance and so forth.
286
287 \cvCPyFunc{CartToPolar}
288 Calculates the magnitude and/or angle of 2d vectors.
289
290 \cvdefC{void cvCartToPolar(\par const CvArr* x,\par const CvArr* y,\par CvArr* magnitude,\par CvArr* angle=NULL,\par int angleInDegrees=0);}
291 \cvdefPy{CartToPolar(x,y,magnitude,angle=NULL,angleInDegrees=0)-> None}
292
293 \begin{description}
294 \cvarg{x}{The array of x-coordinates}
295 \cvarg{y}{The array of y-coordinates}
296 \cvarg{magnitude}{The destination array of magnitudes, may be set to NULL if it is not needed}
297 \cvarg{angle}{The destination array of angles, may be set to NULL if it is not needed. The angles are measured in radians $(0$ to $2 \pi )$ or in degrees (0 to 360 degrees).}
298 \cvarg{angleInDegrees}{The flag indicating whether the angles are measured in radians, which is default mode, or in degrees}
299 \end{description}
300
301 The function calculates either the magnitude, angle, or both of every 2d vector (x(I),y(I)):
302
303 \begin{lstlisting}
304
305 magnitude(I)=sqrt(x(I)^2^+y(I)^2^ ),
306 angle(I)=atan(y(I)/x(I) )
307
308 \end{lstlisting}
309
310 The angles are calculated with 0.1 degree accuracy. For the (0,0) point, the angle is set to 0.
311
312 \cvCPyFunc{Cbrt}
313 Calculates the cubic root
314
315 \cvdefC{float cvCbrt(float value);}
316 \cvdefPy{Cbrt(value)-> float}
317
318 \begin{description}
319 \cvarg{value}{The input floating-point value}
320 \end{description}
321
322
323 The function calculates the cubic root of the argument, and normally it is faster than \texttt{pow(value,1./3)}. In addition, negative arguments are handled properly. Special values ($\pm \infty $, NaN) are not handled.
324
325 \cvCPyFunc{ClearND}
326 Clears a specific array element.
327 \cvdefC{void cvClearND(CvArr* arr, int* idx);}
328 \cvdefPy{ClearND(arr,idx)-> None}
329
330 \begin{description}
331 \cvarg{arr}{Input array}
332 \cvarg{idx}{Array of the element indices}
333 \end{description}
334
335 The function \cvCPyCross{ClearND} clears (sets to zero) a specific element of a dense array or deletes the element of a sparse array. If the sparse array element does not exists, the function does nothing.
336
337 \cvCPyFunc{CloneImage}
338 Makes a full copy of an image, including the header, data, and ROI.
339
340 \cvdefC{IplImage* cvCloneImage(const IplImage* image);}
341 \cvdefPy{CloneImage(image)-> copy}
342
343 \begin{description}
344 \cvarg{image}{The original image}
345 \end{description}
346
347 The returned \texttt{IplImage*} points to the image copy.
348
349 \cvCPyFunc{CloneMat}
350 Creates a full matrix copy.
351
352 \cvdefC{CvMat* cvCloneMat(const CvMat* mat);}
353 \cvdefPy{CloneMat(mat)-> copy}
354
355 \begin{description}
356 \cvarg{mat}{Matrix to be copied}
357 \end{description}
358
359 Creates a full copy of a matrix and returns a pointer to the copy.
360
361 \cvCPyFunc{CloneMatND}
362 Creates full copy of a multi-dimensional array and returns a pointer to the copy.
363
364 \cvdefC{CvMatND* cvCloneMatND(const CvMatND* mat);}
365 \cvdefPy{CloneMatND(mat)-> copy}
366
367 \begin{description}
368 \cvarg{mat}{Input array}
369 \end{description}
370
371
372 \cvCPyFunc{CloneSparseMat}
373 Creates full copy of sparse array.
374
375 \cvdefC{CvSparseMat* cvCloneSparseMat(const CvSparseMat* mat);}
376 \cvdefPy{CloneSparseMat(mat) -> mat}
377
378 \begin{description}
379 \cvarg{mat}{Input array}
380 \end{description}
381
382 The function creates a copy of the input array and returns pointer to the copy.
383
384 \cvCPyFunc{Cmp}
385 Performs per-element comparison of two arrays.
386
387 \cvdefC{void cvCmp(const CvArr* src1, const CvArr* src2, CvArr* dst, int cmpOp);}
388 \cvdefPy{Cmp(src1,src2,dst,cmpOp)-> None}
389
390 \begin{description}
391 \cvarg{src1}{The first source array}
392 \cvarg{src2}{The second source array. Both source arrays must have a single channel.}
393 \cvarg{dst}{The destination array, must have 8u or 8s type}
394 \cvarg{cmpOp}{The flag specifying the relation between the elements to be checked
395 \begin{description}
396  \cvarg{CV\_CMP\_EQ}{src1(I) "equal to" value}
397  \cvarg{CV\_CMP\_GT}{src1(I) "greater than" value}
398  \cvarg{CV\_CMP\_GE}{src1(I) "greater or equal" value}
399  \cvarg{CV\_CMP\_LT}{src1(I) "less than" value}
400  \cvarg{CV\_CMP\_LE}{src1(I) "less or equal" value}
401  \cvarg{CV\_CMP\_NE}{src1(I) "not equal" value}
402 \end{description}}
403 \end{description}
404
405 The function compares the corresponding elements of two arrays and fills the destination mask array:
406
407 \begin{lstlisting}
408 dst(I)=src1(I) op src2(I),
409 \end{lstlisting}
410
411 \texttt{dst(I)} is set to 0xff (all \texttt{1}-bits) if the specific relation between the elements is true and 0 otherwise. All the arrays must have the same type, except the destination, and the same size (or ROI size)
412
413 \cvCPyFunc{CmpS}
414 Performs per-element comparison of an array and a scalar.
415
416 \cvdefC{void cvCmpS(const CvArr* src, double value, CvArr* dst, int cmpOp);}
417 \cvdefPy{CmpS(src,value,dst,cmpOp)-> None}
418
419 \begin{description}
420 \cvarg{src}{The source array, must have a single channel}
421 \cvarg{value}{The scalar value to compare each array element with}
422 \cvarg{dst}{The destination array, must have 8u or 8s type}
423 \cvarg{cmpOp}{The flag specifying the relation between the elements to be checked
424 \begin{description}
425  \cvarg{CV\_CMP\_EQ}{src1(I) "equal to" value}
426  \cvarg{CV\_CMP\_GT}{src1(I) "greater than" value}
427  \cvarg{CV\_CMP\_GE}{src1(I) "greater or equal" value}
428  \cvarg{CV\_CMP\_LT}{src1(I) "less than" value}
429  \cvarg{CV\_CMP\_LE}{src1(I) "less or equal" value}
430  \cvarg{CV\_CMP\_NE}{src1(I) "not equal" value}
431 \end{description}}
432 \end{description}
433
434 The function compares the corresponding elements of an array and a scalar and fills the destination mask array:
435
436 \begin{lstlisting}
437 dst(I)=src(I) op scalar
438 \end{lstlisting}
439
440 where \texttt{op} is $=,\; >,\; \ge,\; <,\; \le\; or\; \ne$.
441
442 \texttt{dst(I)} is set to 0xff (all \texttt{1}-bits) if the specific relation between the elements is true and 0 otherwise. All the arrays must have the same size (or ROI size).
443
444 \cvCPyFunc{ConvertScale}
445 Converts one array to another with optional linear transformation.
446
447 \cvdefC{void cvConvertScale(const CvArr* src, CvArr* dst, double scale=1, double shift=0);}
448 \cvdefPy{ConvertScale(src,dst,scale=1.0,shift=0.0)-> None}
449
450 \begin{lstlisting}
451 #define cvCvtScale cvConvertScale
452 #define cvScale  cvConvertScale
453 #define cvConvert(src, dst )  cvConvertScale((src), (dst), 1, 0 )
454 \end{lstlisting}
455
456 \begin{description}
457 \cvarg{src}{Source array}
458 \cvarg{dst}{Destination array}
459 \cvarg{scale}{Scale factor}
460 \cvarg{shift}{Value added to the scaled source array elements}
461 \end{description}
462
463
464 The function has several different purposes, and thus has several different names. It copies one array to another with optional scaling, which is performed first, and/or optional type conversion, performed after:
465
466 \[
467 \texttt{dst}(I) = \texttt{scale} \texttt{src}(I) + (\texttt{shift}_0,\texttt{shift}_1,...)
468 \]
469
470 All the channels of multi-channel arrays are processed independently.
471
472 The type of conversion is done with rounding and saturation, that is if the
473 result of scaling + conversion can not be represented exactly by a value
474 of the destination array element type, it is set to the nearest representable
475 value on the real axis.
476
477 In the case of \texttt{scale=1, shift=0} no prescaling is done. This is a specially
478 optimized case and it has the appropriate \cvCPyCross{Convert} name. If
479 source and destination array types have equal types, this is also a
480 special case that can be used to scale and shift a matrix or an image
481 and that is caled \cvCPyCross{Scale}.
482
483 \cvCPyFunc{ConvertScaleAbs}
484 Converts input array elements to another 8-bit unsigned integer with optional linear transformation.
485
486 \cvdefC{void cvConvertScaleAbs(const CvArr* src, CvArr* dst, double scale=1, double shift=0);}
487 \cvdefPy{ConvertScaleAbs(src,dst,scale=1.0,shift=0.0)-> None}
488
489 \begin{lstlisting}
490 #define cvCvtScaleAbs cvConvertScaleAbs
491 \end{lstlisting}
492
493 \begin{description}
494 \cvarg{src}{Source array}
495 \cvarg{dst}{Destination array (should have 8u depth)}
496 \cvarg{scale}{ScaleAbs factor}
497 \cvarg{shift}{Value added to the scaled source array elements}
498 \end{description}
499
500
501 The function is similar to \cvCPyCross{ConvertScale}, but it stores absolute values of the conversion results:
502
503 \[
504 \texttt{dst}(I) = |\texttt{scale} \texttt{src}(I) + (\texttt{shift}_0,\texttt{shift}_1,...)|
505 \]
506
507 The function supports only destination arrays of 8u (8-bit unsigned integers) type; for other types the function can be emulated by a combination of \cvCPyCross{ConvertScale} and \cvCPyCross{Abs} functions.
508
509 \cvCPyFunc{Copy}
510 Copies one array to another.
511
512 \cvdefC{void cvCopy(const CvArr* src, CvArr* dst, const CvArr* mask=NULL);}
513 \cvdefPy{Copy(src,dst,mask=NULL)-> None}
514
515 \begin{description}
516 \cvarg{src}{The source array}
517 \cvarg{dst}{The destination array}
518 \cvarg{mask}{Operation mask, 8-bit single channel array; specifies elements of the destination array to be changed}
519 \end{description}
520
521
522 The function copies selected elements from an input array to an output array:
523
524 \[
525 \texttt{dst}(I)=\texttt{src}(I) \quad \text{if} \quad \texttt{mask}(I) \ne 0.
526 \]
527
528 If any of the passed arrays is of \texttt{IplImage} type, then its ROI
529 and COI fields are used. Both arrays must have the same type, the same
530 number of dimensions, and the same size. The function can also copy sparse
531 arrays (mask is not supported in this case).
532
533 \cvCPyFunc{CountNonZero}
534 Counts non-zero array elements.
535
536 \cvdefC{int cvCountNonZero(const CvArr* arr);}
537 \cvdefPy{CountNonZero(arr)-> int}
538
539 \begin{description}
540 \cvarg{arr}{The array must be a single-channel array or a multi-channel image with COI set}
541 \end{description}
542
543
544 The function returns the number of non-zero elements in arr:
545
546 \[ \sum_I (\texttt{arr}(I) \ne 0) \]
547
548 In the case of \texttt{IplImage} both ROI and COI are supported.
549
550
551 \cvCPyFunc{CreateData}
552 Allocates array data
553
554 \cvdefC{void cvCreateData(CvArr* arr);}
555 \cvdefPy{CreateData(arr) -> None}
556
557 \begin{description}
558 \cvarg{arr}{Array header}
559 \end{description}
560
561
562 The function allocates image, matrix or
563 multi-dimensional array data. Note that in the case of matrix types OpenCV
564 allocation functions are used and in the case of IplImage they are used
565 unless \texttt{CV\_TURN\_ON\_IPL\_COMPATIBILITY} was called. In the
566 latter case IPL functions are used to allocate the data.
567
568 \cvCPyFunc{CreateImage}
569 Creates an image header and allocates the image data.
570
571 \cvdefC{IplImage* cvCreateImage(CvSize size, int depth, int channels);}
572 \cvdefPy{CreateImage(size, depth, channels)->image}
573
574 \begin{description}
575 \cvarg{size}{Image width and height}
576 \cvarg{depth}{Bit depth of image elements. See \cross{IplImage} for valid depths.}
577 \cvarg{channels}{Number of channels per pixel. See \cross{IplImage} for details. This function only creates images with interleaved channels.}
578 \end{description}
579
580 This call is a shortened form of
581 \begin{lstlisting}
582 header = cvCreateImageHeader(size, depth, channels);
583 cvCreateData(header);
584 \end{lstlisting}
585
586
587 \cvCPyFunc{CreateImageHeader}
588 Creates an image header but does not allocate the image data.
589
590 \cvdefC{IplImage* cvCreateImageHeader(CvSize size, int depth, int channels);}
591 \cvdefPy{CreateImageHeader(size, depth, channels) -> image}
592
593 \begin{description}
594 \cvarg{size}{Image width and height}
595 \cvarg{depth}{Image depth (see \cvCPyCross{CreateImage})}
596 \cvarg{channels}{Number of channels (see \cvCPyCross{CreateImage})}
597 \end{description}
598
599 This call is an analogue of
600 \begin{lstlisting}
601 hdr=iplCreateImageHeader(channels, 0, depth,
602                       channels == 1 ? "GRAY" : "RGB",
603                       channels == 1 ? "GRAY" : channels == 3 ? "BGR" :
604                       channels == 4 ? "BGRA" : "",
605                       IPL_DATA_ORDER_PIXEL, IPL_ORIGIN_TL, 4,
606                       size.width, size.height,
607                       0,0,0,0);
608 \end{lstlisting}
609 but it does not use IPL functions by default (see the \texttt{CV\_TURN\_ON\_IPL\_COMPATIBILITY} macro).
610
611 \cvCPyFunc{CreateMat}\label{cvCreateMat}
612 Creates a matrix header and allocates the matrix data. 
613
614 \cvdefC{CvMat* cvCreateMat(\par int rows,\par int cols,\par int type);}
615 \cvdefPy{CreateMat(rows, cols, type) -> mat}
616
617 \begin{description}
618 \cvarg{rows}{Number of rows in the matrix}
619 \cvarg{cols}{Number of columns in the matrix}
620 \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.}
621 \end{description}
622
623 This is the concise form for:
624
625 \begin{lstlisting}
626 CvMat* mat = cvCreateMatHeader(rows, cols, type);
627 cvCreateData(mat);
628 \end{lstlisting}
629
630 \cvCPyFunc{CreateMatHeader}
631 Creates a matrix header but does not allocate the matrix data.
632
633 \cvdefC{CvMat* cvCreateMatHeader(\par int rows,\par int cols,\par int type);}
634 \cvdefPy{CreateMatHeader(rows, cols, type) -> mat}
635
636 \begin{description}
637 \cvarg{rows}{Number of rows in the matrix}
638 \cvarg{cols}{Number of columns in the matrix}
639 \cvarg{type}{Type of the matrix elements, see \cvCPyCross{CreateMat}}
640 \end{description}
641
642 The function allocates a new matrix header and returns a pointer to it. The matrix data can then be allocated using \cvCPyCross{CreateData} or set explicitly to user-allocated data via \cvCPyCross{SetData}.
643
644 \cvCPyFunc{CreateMatND}
645 Creates the header and allocates the data for a multi-dimensional dense array.
646
647 \cvdefC{CvMatND* cvCreateMatND(\par int dims,\par const int* sizes,\par int type);}
648 \cvdefPy{CreateMatND(dims, type) -> None}
649
650 \begin{description}
651 \ifPy
652 \cvarg{dims}{List or tuple of array dimensions, up to 32 in length.}
653 \else
654 \cvarg{dims}{Number of array dimensions. This must not exceed CV\_MAX\_DIM (32 by default, but can be changed at build time).}
655 \cvarg{sizes}{Array of dimension sizes.}
656 \fi
657 \cvarg{type}{Type of array elements, see \cvCPyCross{CreateMat}.}
658 \end{description}
659
660 This is a short form for:
661
662 \begin{lstlisting}
663 CvMatND* mat = cvCreateMatNDHeader(dims, sizes, type);
664 cvCreateData(mat);
665 \end{lstlisting}
666
667 \cvCPyFunc{CreateMatNDHeader}
668 Creates a new matrix header but does not allocate the matrix data.
669
670 \cvdefC{CvMatND* cvCreateMatNDHeader(\par int dims,\par const int* sizes,\par int type);}
671 \cvdefPy{CreateMatNDHeader(dims, type) -> None}
672
673 \begin{description}
674 \ifPy
675 \cvarg{dims}{List or tuple of array dimensions, up to 32 in length.}
676 \else
677 \cvarg{dims}{Number of array dimensions}
678 \cvarg{sizes}{Array of dimension sizes}
679 \fi
680 \cvarg{type}{Type of array elements, see \cvCPyCross{CreateMat}}
681 \end{description}
682
683 The function allocates a header for a multi-dimensional dense array. The array data can further be allocated using \cvCPyCross{CreateData} or set explicitly to user-allocated data via \cvCPyCross{SetData}.
684
685 \cvCPyFunc{CreateSparseMat}
686 Creates sparse array.
687
688 \cvdefC{CvSparseMat* cvCreateSparseMat(int dims, const int* sizes, int type);}
689 \cvdefPy{CreateSparseMat(dims, type) -> cvmat}
690
691 \begin{description}
692 \ifC
693 \cvarg{dims}{Number of array dimensions. In contrast to the dense matrix, the number of dimensions is practically unlimited (up to $2^{16}$).}
694 \cvarg{sizes}{Array of dimension sizes}
695 \else
696 \cvarg{dims}{List or tuple of array dimensions.}
697 \fi
698 \cvarg{type}{Type of array elements. The same as for CvMat}
699 \end{description}
700
701 The function allocates a multi-dimensional sparse array. Initially the array contain no elements, that is \cvCPyCross{Get} or \cvCPyCross{GetReal} returns zero for every index.
702
703
704 \cvCPyFunc{CrossProduct}
705 Calculates the cross product of two 3D vectors.
706
707 \cvdefC{void cvCrossProduct(const CvArr* src1, const CvArr* src2, CvArr* dst);}
708 \cvdefPy{CrossProduct(src1,src2,dst)-> None}
709
710 \begin{description}
711 \cvarg{src1}{The first source vector}
712 \cvarg{src2}{The second source vector}
713 \cvarg{dst}{The destination vector}
714 \end{description}
715
716
717 The function calculates the cross product of two 3D vectors:
718
719 \[ \texttt{dst} = \texttt{src1} \times \texttt{src2} \]
720 or:
721 \[
722 \begin{array}{l}
723 \texttt{dst}_1 = \texttt{src1}_2 \texttt{src2}_3 - \texttt{src1}_3 \texttt{src2}_2\\
724 \texttt{dst}_2 = \texttt{src1}_3 \texttt{src2}_1 - \texttt{src1}_1 \texttt{src2}_3\\
725 \texttt{dst}_3 = \texttt{src1}_1 \texttt{src2}_2 - \texttt{src1}_2 \texttt{src2}_1
726 \end{array}
727 \]
728
729 \cvCPyFunc{DCT}
730 Performs a forward or inverse Discrete Cosine transform of a 1D or 2D floating-point array.
731
732 \cvdefC{void cvDCT(const CvArr* src, CvArr* dst, int flags);}
733 \cvdefPy{DCT(src,dst,flags)-> None}
734
735 \begin{lstlisting}
736 #define CV_DXT_FORWARD  0
737 #define CV_DXT_INVERSE  1
738 #define CV_DXT_ROWS     4
739 \end{lstlisting}
740
741 \begin{description}
742 \cvarg{src}{Source array, real 1D or 2D array}
743 \cvarg{dst}{Destination array of the same size and same type as the source}
744 \cvarg{flags}{Transformation flags, a combination of the following values
745 \begin{description}
746 \cvarg{CV\_DXT\_FORWARD}{do a forward 1D or 2D transform.}
747 \cvarg{CV\_DXT\_INVERSE}{do an inverse 1D or 2D transform.}
748 \cvarg{CV\_DXT\_ROWS}{do a forward or inverse transform of every individual row of the input matrix. This flag allows user to transform multiple vectors simultaneously and can be used to decrease the overhead (which is sometimes several times larger than the processing itself), to do 3D and higher-dimensional transforms and so forth.}
749 \end{description}}
750 \end{description}
751
752 The function performs a forward or inverse transform of a 1D or 2D floating-point array:
753
754 Forward Cosine transform of 1D vector of $N$ elements:
755 \[Y = C^{(N)} \cdot X\]
756 where
757 \[C^{(N)}_{jk}=\sqrt{\alpha_j/N}\cos\left(\frac{\pi(2k+1)j}{2N}\right)\]
758 and $\alpha_0=1$, $\alpha_j=2$ for $j > 0$.
759
760 Inverse Cosine transform of 1D vector of N elements:
761 \[X = \left(C^{(N)}\right)^{-1} \cdot Y = \left(C^{(N)}\right)^T \cdot Y\]
762 (since $C^{(N)}$ is orthogonal matrix, $C^{(N)} \cdot \left(C^{(N)}\right)^T = I$)
763
764 Forward Cosine transform of 2D $M \times N$ matrix:
765 \[Y = C^{(N)} \cdot X \cdot \left(C^{(N)}\right)^T\]
766
767 Inverse Cosine transform of 2D vector of $M \times N$ elements:
768 \[X = \left(C^{(N)}\right)^T \cdot X \cdot C^{(N)}\]
769
770
771 \cvCPyFunc{DFT}
772 Performs a forward or inverse Discrete Fourier transform of a 1D or 2D floating-point array.
773
774 \cvdefC{void cvDFT(const CvArr* src, CvArr* dst, int flags, int nonzeroRows=0);}
775 \cvdefPy{DFT(src,dst,flags,nonzeroRows=0)-> None}
776
777 \begin{lstlisting}
778 #define CV_DXT_FORWARD  0
779 #define CV_DXT_INVERSE  1
780 #define CV_DXT_SCALE    2
781 #define CV_DXT_ROWS     4
782 #define CV_DXT_INV_SCALE (CV_DXT_SCALE|CV_DXT_INVERSE)
783 #define CV_DXT_INVERSE_SCALE CV_DXT_INV_SCALE
784 \end{lstlisting}
785
786 \begin{description}
787 \cvarg{src}{Source array, real or complex}
788 \cvarg{dst}{Destination array of the same size and same type as the source}
789 \cvarg{flags}{Transformation flags, a combination of the following values
790 \begin{description}
791 \cvarg{CV\_DXT\_FORWARD}{do a forward 1D or 2D transform. The result is not scaled.}
792 \cvarg{CV\_DXT\_INVERSE}{do an inverse 1D or 2D transform. The result is not scaled. \texttt{CV\_DXT\_FORWARD} and \texttt{CV\_DXT\_INVERSE} are mutually exclusive, of course.}
793 \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}.}
794 \cvarg{CV\_DXT\_ROWS}{do a forward or inverse transform of every individual row of the input matrix. This flag allows the user to transform multiple vectors simultaneously and can be used to decrease the overhead (which is sometimes several times larger than the processing itself), to do 3D and higher-dimensional transforms and so forth.}
795 \end{description}}
796 \cvarg{nonzeroRows}{Number of nonzero rows in the source array
797 (in the case of a forward 2d transform), or a number of rows of interest in
798 the destination array (in the case of an inverse 2d transform). If the value
799 is negative, zero, or greater than the total number of rows, it is
800 ignored. The parameter can be used to speed up 2d convolution/correlation
801 when computing via DFT. See the example below.}
802 \end{description}
803
804 The function performs a forward or inverse transform of a 1D or 2D floating-point array:
805
806
807 Forward Fourier transform of 1D vector of N elements:
808 \[y = F^{(N)} \cdot x, where F^{(N)}_{jk}=exp(-i \cdot 2\pi \cdot j \cdot k/N)\], 
809 \[i=sqrt(-1)\]
810
811 Inverse Fourier transform of 1D vector of N elements:
812 \[x'= (F^{(N)})^{-1} \cdot y = conj(F^(N)) \cdot y
813 x = (1/N) \cdot x\]
814
815 Forward Fourier transform of 2D vector of M $\times$ N elements:
816 \[Y = F^{(M)} \cdot X \cdot F^{(N)}\]
817
818 Inverse Fourier transform of 2D vector of M $\times$ N elements:
819 \[X'= conj(F^{(M)}) \cdot Y \cdot conj(F^{(N)})
820 X = (1/(M \cdot N)) \cdot X'\]
821
822
823 In the case of real (single-channel) data, the packed format, borrowed from IPL, is used to represent the result of a forward Fourier transform or input for an inverse Fourier transform:
824
825 \[\begin{bmatrix}
826 Re Y_{0,0} & Re Y_{0,1} & Im Y_{0,1} & Re Y_{0,2} & Im Y_{0,2} & \cdots & Re Y_{0,N/2-1} & Im Y_{0,N/2-1} & Re Y_{0,N/2} \\
827 Re Y_{1,0} & Re Y_{1,1} & Im Y_{1,1} & Re Y_{1,2} & Im Y_{1,2} & \cdots & Re Y_{1,N/2-1} & Im Y_{1,N/2-1} & Re Y_{1,N/2} \\
828 Im Y_{1,0} & Re Y_{2,1} & Im Y_{2,1} & Re Y_{2,2} & Im Y_{2,2} & \cdots & Re Y_{2,N/2-1} & Im Y_{2,N/2-1} & Im Y_{1,N/2} \\
829 \hdotsfor{9} \\
830 Re Y_{M/2-1,0} &  Re Y_{M-3,1}  & Im Y_{M-3,1} & \hdotsfor{3} & Re Y_{M-3,N/2-1} & Im Y_{M-3,N/2-1}& Re Y_{M/2-1,N/2} \\
831 Im Y_{M/2-1,0} &  Re Y_{M-2,1}  & Im Y_{M-2,1} & \hdotsfor{3} & Re Y_{M-2,N/2-1} & Im Y_{M-2,N/2-1}& Im Y_{M/2-1,N/2} \\
832 Re Y_{M/2,0}  &  Re Y_{M-1,1} &  Im Y_{M-1,1} & \hdotsfor{3} & Re Y_{M-1,N/2-1} & Im Y_{M-1,N/2-1}& Re Y_{M/2,N/2}
833 \end{bmatrix}
834 \]
835
836
837 Note: the last column is present if \texttt{N} is even, the last row is present if \texttt{M} is even.
838 In the case of 1D real transform the result looks like the first row of the above matrix.
839
840 Here is the example of how to compute 2D convolution using DFT.
841
842 \begin{lstlisting}
843 CvMat* A = cvCreateMat(M1, N1, CVg32F);
844 CvMat* B = cvCreateMat(M2, N2, A->type);
845
846 // it is also possible to have only abs(M2-M1)+1 times abs(N2-N1)+1
847 // part of the full convolution result
848 CvMat* conv = cvCreateMat(A->rows + B->rows - 1, A->cols + B->cols - 1, 
849                            A->type);
850
851 // initialize A and B
852 ...
853
854 int dftgM = cvGetOptimalDFTSize(A->rows + B->rows - 1);
855 int dftgN = cvGetOptimalDFTSize(A->cols + B->cols - 1);
856
857 CvMat* dftgA = cvCreateMat(dft\_M, dft\_N, A->type);
858 CvMat* dftgB = cvCreateMat(dft\_M, dft\_N, B->type);
859 CvMat tmp;
860
861 // copy A to dftgA and pad dft\_A with zeros
862 cvGetSubRect(dftgA, &tmp, cvRect(0,0,A->cols,A->rows));
863 cvCopy(A, &tmp);
864 cvGetSubRect(dftgA, &tmp, cvRect(A->cols,0,dft\_A->cols - A->cols,A->rows));
865 cvZero(&tmp);
866 // no need to pad bottom part of dftgA with zeros because of
867 // use nonzerogrows parameter in cvDFT() call below
868
869 cvDFT(dftgA, dft\_A, CV\_DXT\_FORWARD, A->rows);
870
871 // repeat the same with the second array
872 cvGetSubRect(dftgB, &tmp, cvRect(0,0,B->cols,B->rows));
873 cvCopy(B, &tmp);
874 cvGetSubRect(dftgB, &tmp, cvRect(B->cols,0,dft\_B->cols - B->cols,B->rows));
875 cvZero(&tmp);
876 // no need to pad bottom part of dftgB with zeros because of
877 // use nonzerogrows parameter in cvDFT() call below
878
879 cvDFT(dftgB, dft\_B, CV\_DXT\_FORWARD, B->rows);
880
881 cvMulSpectrums(dftgA, dft\_B, dft\_A, 0 /* or CV\_DXT\_MUL\_CONJ to get 
882                 correlation rather than convolution */);
883
884 cvDFT(dftgA, dft\_A, CV\_DXT\_INV\_SCALE, conv->rows); // calculate only 
885                                                          // the top part
886 cvGetSubRect(dftgA, &tmp, cvRect(0,0,conv->cols,conv->rows));
887
888 cvCopy(&tmp, conv);
889 \end{lstlisting}
890
891 \ifC
892
893 \cvCPyFunc{DecRefData}
894 Decrements an array data reference counter.
895
896 \cvdefC{void cvDecRefData(CvArr* arr);}
897
898 \begin{description}
899 \cvarg{arr}{Pointer to an array header}
900 \end{description}
901
902 The function decrements the data reference counter in a \cross{CvMat} or
903 \cross{CvMatND} if the reference counter pointer
904 is not NULL. If the counter reaches zero, the data is deallocated. In the
905 current implementation the reference counter is not NULL only if the data
906 was allocated using the \cvCPyCross{CreateData} function. The counter will be NULL in other cases such as:
907 external data was assigned to the header using \cvCPyCross{SetData}, the matrix
908 header is part of a larger matrix or image, or the header was converted from an image or n-dimensional matrix header. 
909
910 \fi
911
912
913 \cvCPyFunc{Det}
914 Returns the determinant of a matrix.
915
916 \cvdefC{double cvDet(const CvArr* mat);}
917 \cvdefPy{Det(mat)-> double}
918
919 \begin{description}
920 \cvarg{mat}{The source matrix}
921 \end{description}
922
923 The function returns the determinant of the square matrix \texttt{mat}. The direct method is used for small matrices and Gaussian elimination is used for larger matrices. For symmetric positive-determined matrices, it is also possible to run
924 \cvCPyCross{SVD}
925 with $U = V = 0$ and then calculate the determinant as a product of the diagonal elements of $W$.
926
927 \cvCPyFunc{Div}
928 Performs per-element division of two arrays.
929
930 \cvdefC{void cvDiv(const CvArr* src1, const CvArr* src2, CvArr* dst, double scale=1);}
931 \cvdefPy{Div(src1,src2,dst,scale)-> None}
932
933 \begin{description}
934 \cvarg{src1}{The first source array. If the pointer is NULL, the array is assumed to be all 1's.}
935 \cvarg{src2}{The second source array}
936 \cvarg{dst}{The destination array}
937 \cvarg{scale}{Optional scale factor}
938 \end{description}
939
940 The function divides one array by another:
941
942 \[
943 \texttt{dst}(I)=\fork
944 {\texttt{scale} \cdot \texttt{src1}(I)/\texttt{src2}(I)}{if \texttt{src1} is not \texttt{NULL}}
945 {\texttt{scale}/\texttt{src2}(I)}{otherwise}
946 \]
947
948 All the arrays must have the same type and the same size (or ROI size).
949
950
951 \cvCPyFunc{DotProduct}
952 Calculates the dot product of two arrays in Euclidian metrics.
953
954 \cvdefC{double cvDotProduct(const CvArr* src1, const CvArr* src2);}
955 \cvdefPy{DotProduct(src1,src2)-> double}
956
957 \begin{description}
958 \cvarg{src1}{The first source array}
959 \cvarg{src2}{The second source array}
960 \end{description}
961
962 The function calculates and returns the Euclidean dot product of two arrays.
963
964 \[
965 src1 \bullet src2 = \sum_I (\texttt{src1}(I) \texttt{src2}(I))
966 \]
967
968 In the case of multiple channel arrays, the results for all channels are accumulated. In particular, \texttt{cvDotProduct(a,a)} where \texttt{a} is a complex vector, will return $||\texttt{a}||^2$.
969 The function can process multi-dimensional arrays, row by row, layer by layer, and so on.
970
971 \cvCPyFunc{EigenVV}
972 Computes eigenvalues and eigenvectors of a symmetric matrix.
973
974 \cvdefC{
975 void cvEigenVV(\par CvArr* mat,\par CvArr* evects,\par CvArr* evals,\par double eps=0,
976 \par int lowindex = 0, \par int highindex = 0);}
977 \cvdefPy{EigenVV(mat,evects,evals,eps,lowindex,highindex)-> None}
978
979 \begin{description}
980 \cvarg{mat}{The input symmetric square matrix, modified during the processing}
981 \cvarg{evects}{The output matrix of eigenvectors, stored as subsequent rows}
982 \cvarg{evals}{The output vector of eigenvalues, stored in the descending order (order of eigenvalues and eigenvectors is syncronized, of course)}
983 \cvarg{eps}{Accuracy of diagonalization. Typically, \texttt{DBL\_EPSILON} (about $ 10^{-15} $) works well.
984 THIS PARAMETER IS CURRENTLY IGNORED.}
985 \cvarg{lowindex}{Optional index of largest eigenvalue/-vector to calculate.
986 (See below.)}
987 \cvarg{highindex}{Optional index of smallest eigenvalue/-vector to calculate.
988 (See below.)}
989 \end{description}
990
991
992 The function computes the eigenvalues and eigenvectors of matrix \texttt{A}:
993
994 \begin{lstlisting}
995 mat*evects(i,:)' = evals(i)*evects(i,:)' (in MATLAB notation)
996 \end{lstlisting}
997
998 If either low- or highindex is supplied the other is required, too.
999 Indexing is 1-based. Example: To calculate the largest eigenvector/-value set
1000 lowindex = highindex = 1.
1001 For legacy reasons this function always returns a square matrix the same size
1002 as the source matrix with eigenvectors and a vector the length of the source
1003 matrix with eigenvalues. The selected eigenvectors/-values are always in the
1004 first highindex - lowindex + 1 rows.
1005
1006 The contents of matrix \texttt{A} is destroyed by the function.
1007
1008 Currently the function is slower than \cvCPyCross{SVD} yet less accurate,
1009 so if \texttt{A} is known to be positively-defined (for example, it
1010 is a covariance matrix)it is recommended to use \cvCPyCross{SVD} to find
1011 eigenvalues and eigenvectors of \texttt{A}, especially if eigenvectors
1012 are not required.
1013
1014 \cvCPyFunc{Exp}
1015 Calculates the exponent of every array element.
1016
1017 \cvdefC{void cvExp(const CvArr* src, CvArr* dst);}
1018 \cvdefPy{Exp(src,dst)-> None}
1019
1020 \begin{description}
1021 \cvarg{src}{The source array}
1022 \cvarg{dst}{The destination array, it should have \texttt{double} type or the same type as the source}
1023 \end{description}
1024
1025
1026 The function calculates the exponent of every element of the input array:
1027
1028 \[
1029 \texttt{dst} [I] = e^{\texttt{src}(I)}
1030 \]
1031
1032 The maximum relative error is about $7 \times 10^{-6}$. Currently, the function converts denormalized values to zeros on output.
1033
1034 \cvCPyFunc{FastArctan}
1035 Calculates the angle of a 2D vector.
1036
1037 \cvdefC{float cvFastArctan(float y, float x);}
1038 \cvdefPy{FastArctan(y,x)-> float}
1039
1040 \begin{description}
1041 \cvarg{x}{x-coordinate of 2D vector}
1042 \cvarg{y}{y-coordinate of 2D vector}
1043 \end{description}
1044
1045
1046 The function calculates the full-range angle of an input 2D vector. The angle is 
1047 measured in degrees and varies from 0 degrees to 360 degrees. The accuracy is about 0.1 degrees.
1048
1049 \cvCPyFunc{Flip}
1050 Flip a 2D array around vertical, horizontal or both axes.
1051
1052 \cvdefC{void  cvFlip(const CvArr* src, CvArr* dst=NULL, int flipMode=0);}
1053 \cvdefPy{Flip(src,dst=NULL,flipMode=0)-> None}
1054
1055 \begin{lstlisting}
1056 #define cvMirror cvFlip
1057 \end{lstlisting}
1058
1059 \begin{description}
1060 \cvarg{src}{Source array}
1061 \cvarg{dst}{Destination array.
1062 If $\texttt{dst} = \texttt{NULL}$ the flipping is done in place.}
1063 \cvarg{flipMode}{Specifies how to flip the array:
1064 0 means flipping around the x-axis, positive (e.g., 1) means flipping around y-axis, and negative (e.g., -1) means flipping around both axes. See also the discussion below for the formulas:}
1065 \end{description}
1066
1067 The function flips the array in one of three different ways (row and column indices are 0-based):
1068
1069 \[
1070 dst(i,j) = \forkthree
1071 {\texttt{src}(rows(\texttt{src})-i-1,j)}{if $\texttt{flipMode} = 0$}
1072 {\texttt{src}(i,cols(\texttt{src})-j-1)}{if $\texttt{flipMode} > 0$}
1073 {\texttt{src}(rows(\texttt{src})-i-1,cols(\texttt{src})-j-1)}{if $\texttt{flipMode} < 0$}
1074 \]
1075
1076 The example scenarios of function use are:
1077 \begin{itemize}
1078   \item vertical flipping of the image (flipMode = 0) to switch between top-left and bottom-left image origin, which is a typical operation in video processing under Win32 systems.
1079   \item horizontal flipping of the image with subsequent horizontal shift and absolute difference calculation to check for a vertical-axis symmetry (flipMode $>$ 0)
1080   \item simultaneous horizontal and vertical flipping of the image with subsequent shift and absolute difference calculation to check for a central symmetry (flipMode $<$ 0)
1081   \item reversing the order of 1d point arrays (flipMode > 0)
1082 \end{itemize}
1083
1084 \cvCPyFunc{GEMM}
1085 Performs generalized matrix multiplication.
1086
1087 \cvdefC{void cvGEMM(\par const CvArr* src1, \par const CvArr* src2, double alpha,
1088               \par const CvArr* src3, \par double beta, \par CvArr* dst, \par int tABC=0);\newline
1089 \#define cvMatMulAdd(src1, src2, src3, dst ) cvGEMM(src1, src2, 1, src3, 1, dst, 0 )\par
1090 \#define cvMatMul(src1, src2, dst ) cvMatMulAdd(src1, src2, 0, dst )}
1091               
1092 \cvdefPy{GEMM(src1,src2,alphs,src3,beta,dst,tABC=0)-> None}
1093
1094 \begin{description}
1095 \cvarg{src1}{The first source array}
1096 \cvarg{src2}{The second source array}
1097 \cvarg{src3}{The third source array (shift). Can be NULL, if there is no shift.}
1098 \cvarg{dst}{The destination array}
1099 \cvarg{tABC}{The operation flags that can be 0 or a combination of the following values
1100 \begin{description}
1101 \cvarg{CV\_GEMM\_A\_T}{transpose src1}
1102 \cvarg{CV\_GEMM\_B\_T}{transpose src2}
1103 \cvarg{CV\_GEMM\_C\_T}{transpose src3}
1104 \end{description}
1105
1106 For example, \texttt{CV\_GEMM\_A\_T+CV\_GEMM\_C\_T} corresponds to
1107 \[
1108 \texttt{alpha} \, \texttt{src1} ^T \, \texttt{src2} + \texttt{beta} \, \texttt{src3} ^T
1109 \]}
1110 \end{description}
1111
1112 The function performs generalized matrix multiplication:
1113
1114 \[
1115 \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$}
1116 \]
1117
1118 All the matrices should have the same data type and coordinated sizes. Real or complex floating-point matrices are supported.
1119
1120 \ifC  % {
1121
1122 \cvCPyFunc{Get?D}
1123 Return a specific array element.
1124
1125 \cvdefC{
1126 CvScalar cvGet1D(const CvArr* arr, int idx0);
1127 CvScalar cvGet2D(const CvArr* arr, int idx0, int idx1);
1128 CvScalar cvGet3D(const CvArr* arr, int idx0, int idx1, int idx2);
1129 CvScalar cvGetND(const CvArr* arr, int* idx);
1130 }
1131
1132 \begin{description}
1133 \cvarg{arr}{Input array}
1134 \cvarg{idx0}{The first zero-based component of the element index}
1135 \cvarg{idx1}{The second zero-based component of the element index}
1136 \cvarg{idx2}{The third zero-based component of the element index}
1137 \cvarg{idx}{Array of the element indices}
1138 \end{description}
1139
1140 The functions return a specific array element. In the case of a sparse array the functions return 0 if the requested node does not exist (no new node is created by the functions).
1141 \else % }{
1142
1143 \cvCPyFunc{Get1D}
1144 Return a specific array element.
1145
1146 \cvdefPy{ Get1D(arr, idx) -> scalar }
1147
1148 \begin{description}
1149 \cvarg{arr}{Input array}
1150 \cvarg{idx}{Zero-based element index}
1151 \end{description}
1152
1153 Return a specific array element.  Array must have dimension 3.
1154
1155 \cvCPyFunc{Get2D}
1156 Return a specific array element.
1157
1158 \cvdefPy{ Get2D(arr, idx0, idx1) -> scalar }
1159
1160 \begin{description}
1161 \cvarg{arr}{Input array}
1162 \cvarg{idx0}{Zero-based element row index}
1163 \cvarg{idx1}{Zero-based element column index}
1164 \end{description}
1165
1166 Return a specific array element.  Array must have dimension 2.
1167
1168 \cvCPyFunc{Get3D}
1169 Return a specific array element.
1170
1171 \cvdefPy{ Get3D(arr, idx0, idx1, idx2) -> scalar }
1172
1173 \begin{description}
1174 \cvarg{arr}{Input array}
1175 \cvarg{idx0}{Zero-based element index}
1176 \cvarg{idx1}{Zero-based element index}
1177 \cvarg{idx2}{Zero-based element index}
1178 \end{description}
1179
1180 Return a specific array element.  Array must have dimension 3.
1181
1182 \cvCPyFunc{GetND}
1183 Return a specific array element.
1184
1185 \cvdefPy{ GetND(arr, indices) -> scalar }
1186
1187 \begin{description}
1188 \cvarg{arr}{Input array}
1189 \cvarg{indices}{List of zero-based element indices}
1190 \end{description}
1191
1192 Return a specific array element.  The length of array indices must be the same as the dimension of the array.
1193
1194 \fi % }
1195
1196 \ifC % {
1197 \cvCPyFunc{GetCol(s)}
1198 Returns array column or column span.
1199
1200 \cvdefC{CvMat* cvGetCol(const CvArr* arr, CvMat* submat, int col);}
1201 \cvdefPy{GetCol(arr,row)-> submat}
1202 \cvdefC{CvMat* cvGetCols(const CvArr* arr, CvMat* submat, int startCol, int endCol);}
1203 \cvdefPy{GetCols(arr,startCol,endCol)-> submat}
1204
1205 \begin{description}
1206 \cvarg{arr}{Input array}
1207 \cvarg{submat}{Pointer to the resulting sub-array header}
1208 \cvarg{col}{Zero-based index of the selected column}
1209 \cvarg{startCol}{Zero-based index of the starting column (inclusive) of the span}
1210 \cvarg{endCol}{Zero-based index of the ending column (exclusive) of the span}
1211 \end{description}
1212
1213 The functions \texttt{GetCol} and \texttt{GetCols} return the header, corresponding to a specified column span of the input array. \texttt{GetCol} is a shortcut for \cvCPyCross{GetCols}:
1214
1215 \begin{lstlisting}
1216 cvGetCol(arr, submat, col); // ~ cvGetCols(arr, submat, col, col + 1);
1217 \end{lstlisting}
1218
1219 \else % }{
1220
1221 \cvCPyFunc{GetCol}
1222 Returns array column.
1223
1224 \cvdefPy{GetCol(arr,col)-> submat}
1225
1226 \begin{description}
1227 \cvarg{arr}{Input array}
1228 \cvarg{col}{Zero-based index of the selected column}
1229 \cvarg{submat}{resulting single-column array}
1230 \end{description}
1231
1232 The function \texttt{GetCol} returns a single column from the input array.
1233
1234 \cvCPyFunc{GetCols}
1235 Returns array column span.
1236
1237 \cvdefPy{GetCols(arr,startCol,endCol)-> submat}
1238
1239 \begin{description}
1240 \cvarg{arr}{Input array}
1241 \cvarg{startCol}{Zero-based index of the starting column (inclusive) of the span}
1242 \cvarg{endCol}{Zero-based index of the ending column (exclusive) of the span}
1243 \cvarg{submat}{resulting multi-column array}
1244 \end{description}
1245
1246 The function \texttt{GetCols} returns a column span from the input array.
1247
1248 \fi % }
1249
1250 \cvCPyFunc{GetDiag}
1251 Returns one of array diagonals.
1252
1253 \cvdefC{CvMat* cvGetDiag(const CvArr* arr, CvMat* submat, int diag=0);}
1254 \cvdefPy{GetDiag(arr,diag=0)-> submat}
1255
1256 \begin{description}
1257 \cvarg{arr}{Input array}
1258 \cvarg{submat}{Pointer to the resulting sub-array header}
1259 \cvarg{diag}{Array diagonal. Zero corresponds to the main diagonal, -1 corresponds to the diagonal above the main , 1 corresponds to the diagonal below the main, and so forth.}
1260 \end{description}
1261
1262 The function returns the header, corresponding to a specified diagonal of the input array.
1263
1264 \ifC
1265 \subsection{cvGetDims, cvGetDimSize}\label{cvGetDims}
1266
1267 Return number of array dimensions and their sizes or the size of a particular dimension.
1268
1269 \cvdefC{int cvGetDims(const CvArr* arr, int* sizes=NULL);}
1270 \cvdefC{int cvGetDimSize(const CvArr* arr, int index);}
1271
1272 \begin{description}
1273 \cvarg{arr}{Input array}
1274 \cvarg{sizes}{Optional output vector of the array dimension sizes. For
1275 2d arrays the number of rows (height) goes first, number of columns
1276 (width) next.}
1277 \cvarg{index}{Zero-based dimension index (for matrices 0 means number
1278 of rows, 1 means number of columns; for images 0 means height, 1 means
1279 width)}
1280 \end{description}
1281
1282 The function \texttt{cvGetDims} returns the array dimensionality and the
1283 array of dimension sizes. In the case of \texttt{IplImage} or \cross{CvMat} it always
1284 returns 2 regardless of number of image/matrix rows. The function
1285 \texttt{cvGetDimSize} returns the particular dimension size (number of
1286 elements per that dimension). For example, the following code calculates
1287 total number of array elements in two ways:
1288
1289 \begin{lstlisting}
1290 // via cvGetDims()
1291 int sizes[CV_MAX_DIM];
1292 int i, total = 1;
1293 int dims = cvGetDims(arr, size);
1294 for(i = 0; i < dims; i++ )
1295     total *= sizes[i];
1296
1297 // via cvGetDims() and cvGetDimSize()
1298 int i, total = 1;
1299 int dims = cvGetDims(arr);
1300 for(i = 0; i < dims; i++ )
1301     total *= cvGetDimsSize(arr, i);
1302 \end{lstlisting}
1303 \fi
1304
1305 \ifPy
1306 \cvCPyFunc{GetDims}
1307 Returns list of array dimensions
1308
1309 \cvdefPy{GetDims(arr)-> list}
1310
1311 \begin{description}
1312 \cvarg{arr}{Input array}
1313 \end{description}
1314
1315 The function returns a list of array dimensions.
1316 In the case of \texttt{IplImage} or \cross{CvMat} it always
1317 returns a list of length 2.
1318 \fi
1319
1320
1321 \cvCPyFunc{GetElemType}
1322 Returns type of array elements.
1323
1324 \cvdefC{int cvGetElemType(const CvArr* arr);}
1325 \cvdefPy{GetElemType(arr)-> int}
1326
1327 \begin{description}
1328 \cvarg{arr}{Input array}
1329 \end{description}
1330
1331 The function returns type of the array elements
1332 as described in \cvCPyCross{CreateMat} discussion: \texttt{CV\_8UC1} ... \texttt{CV\_64FC4}.
1333
1334
1335 \cvCPyFunc{GetImage}
1336 Returns image header for arbitrary array.
1337
1338 \cvdefC{IplImage* cvGetImage(const CvArr* arr, IplImage* imageHeader);}
1339 \cvdefPy{GetImage(arr) -> iplimage}
1340
1341 \begin{description}
1342 \cvarg{arr}{Input array}
1343 \ifC
1344 \cvarg{imageHeader}{Pointer to \texttt{IplImage} structure used as a temporary buffer}
1345 \fi
1346 \end{description}
1347
1348 The function returns the image header for the input array
1349 that can be a matrix - \cross{CvMat}, or an image - \texttt{IplImage*}. In
1350 the case of an image the function simply returns the input pointer. In the
1351 case of \cross{CvMat} it initializes an \texttt{imageHeader} structure
1352 with the parameters of the input matrix. Note that if we transform
1353 \texttt{IplImage} to \cross{CvMat} and then transform CvMat back to
1354 IplImage, we can get different headers if the ROI is set, and thus some
1355 IPL functions that calculate image stride from its width and align may
1356 fail on the resultant image.
1357
1358 \cvCPyFunc{GetImageCOI}
1359 Returns the index of the channel of interest. 
1360
1361 \cvdefC{int cvGetImageCOI(const IplImage* image);}
1362 \cvdefPy{GetImageCOI(image)-> channel}
1363
1364 \begin{description}
1365 \cvarg{image}{A pointer to the image header}
1366 \end{description}
1367
1368 Returns the channel of interest of in an IplImage. Returned values correspond to the \texttt{coi} in \cvCPyCross{SetImageCOI}.
1369
1370 \cvCPyFunc{GetImageROI}
1371 Returns the image ROI.
1372
1373 \cvdefC{CvRect cvGetImageROI(const IplImage* image);}
1374 \cvdefPy{GetImageROI(image)-> CvRect}
1375
1376 \begin{description}
1377 \cvarg{image}{A pointer to the image header}
1378 \end{description}
1379
1380 If there is no ROI set, \texttt{cvRect(0,0,image->width,image->height)} is returned.
1381
1382 \cvCPyFunc{GetMat}
1383 Returns matrix header for arbitrary array.
1384
1385 \cvdefC{CvMat* cvGetMat(const CvArr* arr, CvMat* header, int* coi=NULL, int allowND=0);}
1386 \cvdefPy{GetMat(arr) -> cvmat }
1387
1388 \begin{description}
1389 \cvarg{arr}{Input array}
1390 \ifC
1391 \cvarg{header}{Pointer to \cross{CvMat} structure used as a temporary buffer}
1392 \cvarg{coi}{Optional output parameter for storing COI}
1393 \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.}
1394 \fi
1395 \end{description}
1396
1397 The function returns a matrix header for the input array that can be a matrix - 
1398
1399 \cross{CvMat}, an image - \texttt{IplImage} or a multi-dimensional dense array - \cross{CvMatND} (latter case is allowed only if \texttt{allowND != 0}) . In the case of matrix the function simply returns the input pointer. In the case of \texttt{IplImage*} or \cross{CvMatND} it initializes the \texttt{header} structure with parameters of the current image ROI and returns the pointer to this temporary structure. Because COI is not supported by \cross{CvMat}, it is returned separately.
1400
1401 The function provides an easy way to handle both types of arrays - \texttt{IplImage} and \cross{CvMat} - using the same code. Reverse transform from \cross{CvMat} to \texttt{IplImage} can be done using the \cvCPyCross{GetImage} function.
1402
1403 Input array must have underlying data allocated or attached, otherwise the function fails.
1404
1405 If the input array is \texttt{IplImage} with planar data layout and COI set, the function returns the pointer to the selected plane and COI = 0. It enables per-plane processing of multi-channel images with planar data layout using OpenCV functions.
1406
1407 \ifC
1408 \cvCPyFunc{GetNextSparseNode} 
1409 Returns the next sparse matrix element
1410
1411 \cvdefC{CvSparseNode* cvGetNextSparseNode(CvSparseMatIterator* matIterator);}
1412
1413 \begin{description}
1414 \cvarg{matIterator}{Sparse array iterator}
1415 \end{description}
1416
1417
1418 The function moves iterator to the next sparse matrix element and returns pointer to it. In the current version there is no any particular order of the elements, because they are stored in the hash table. The sample below demonstrates how to iterate through the sparse matrix:
1419
1420 Using \cvCPyCross{InitSparseMatIterator} and \cvCPyCross{GetNextSparseNode} to calculate sum of floating-point sparse array.
1421
1422 \begin{lstlisting}
1423 double sum;
1424 int i, dims = cvGetDims(array);
1425 CvSparseMatIterator mat_iterator;
1426 CvSparseNode* node = cvInitSparseMatIterator(array, &mat_iterator);
1427
1428 for(; node != 0; node = cvGetNextSparseNode(&mat_iterator ))
1429 {
1430     /* get pointer to the element indices */
1431     int* idx = CV_NODE_IDX(array, node);
1432     /* get value of the element (assume that the type is CV_32FC1) */
1433     float val = *(float*)CV_NODE_VAL(array, node);
1434     printf("(");
1435     for(i = 0; i < dims; i++ )
1436         printf("%4d%s", idx[i], i < dims - 1 "," : "): ");
1437     printf("%g\n", val);
1438
1439     sum += val;
1440 }
1441
1442 printf("\nTotal sum = %g\n", sum);
1443 \end{lstlisting}
1444
1445 \fi
1446
1447 \cvCPyFunc{GetOptimalDFTSize}
1448 Returns optimal DFT size for a given vector size.
1449
1450 \cvdefC{int cvGetOptimalDFTSize(int size0);}
1451 \cvdefPy{GetOptimalDFTSize(size0)-> int}
1452
1453 \begin{description}
1454 \cvarg{size0}{Vector size}
1455 \end{description}
1456
1457 The function returns the minimum number
1458 \texttt{N} that is greater than or equal to \texttt{size0}, such that the DFT
1459 of a vector of size \texttt{N} can be computed fast. In the current
1460 implementation $N=2^p \times 3^q \times 5^r$, for some $p$, $q$, $r$.
1461
1462 The function returns a negative number if \texttt{size0} is too large
1463 (very close to \texttt{INT\_MAX})
1464
1465
1466 \ifC
1467 \cvCPyFunc{GetRawData}
1468 Retrieves low-level information about the array.
1469
1470 \cvdefC{void cvGetRawData(const CvArr* arr, uchar** data,
1471                    int* step=NULL, CvSize* roiSize=NULL);}
1472
1473 \begin{description}
1474 \cvarg{arr}{Array header}
1475 \cvarg{data}{Output pointer to the whole image origin or ROI origin if ROI is set}
1476 \cvarg{step}{Output full row length in bytes}
1477 \cvarg{roiSize}{Output ROI size}
1478 \end{description}
1479
1480 The function fills output variables with low-level information about the array data. All output parameters are optional, so some of the pointers may be set to \texttt{NULL}. If the array is \texttt{IplImage} with ROI set, the parameters of ROI are returned.
1481
1482 The following example shows how to get access to array elements. GetRawData calculates the absolute value of the elements in a single-channel, floating-point array.
1483
1484 \begin{lstlisting}
1485 float* data;
1486 int step;
1487
1488 CvSize size;
1489 int x, y;
1490
1491 cvGetRawData(array, (uchar**)&data, &step, &size);
1492 step /= sizeof(data[0]);
1493
1494 for(y = 0; y < size.height; y++, data += step )
1495     for(x = 0; x < size.width; x++ )
1496         data[x] = (float)fabs(data[x]);
1497
1498 \end{lstlisting}
1499
1500 \cvCPyFunc{GetReal?D}
1501 Return a specific element of single-channel array.
1502
1503 \begin{lstlisting}
1504 double cvGetReal1D(const CvArr* arr, int idx0);
1505 double cvGetReal2D(const CvArr* arr, int idx0, int idx1);
1506 double cvGetReal3D(const CvArr* arr, int idx0, int idx1, int idx2);
1507 double cvGetRealND(const CvArr* arr, int* idx);
1508 \end{lstlisting}
1509
1510 \begin{description}
1511 \cvarg{arr}{Input array. Must have a single channel.}
1512 \cvarg{idx0}{The first zero-based component of the element index}
1513 \cvarg{idx1}{The second zero-based component of the element index}
1514 \cvarg{idx2}{The third zero-based component of the element index}
1515 \cvarg{idx}{Array of the element indices}
1516 \end{description}
1517
1518
1519 The functions \texttt{cvGetReal*D} return a specific element of a single-channel array. If the array has multiple channels, a runtime error is raised. Note that \cvCPyCross{Get} function can be used safely for both single-channel and multiple-channel arrays though they are a bit slower.
1520
1521 In the case of a sparse array the functions return 0 if the requested node does not exist (no new node is created by the functions).
1522
1523 \fi
1524
1525 \ifC %{
1526 \cvCPyFunc{GetRow(s)}
1527 Returns array row or row span.
1528
1529 \cvdefC{CvMat* cvGetRow(const CvArr* arr, CvMat* submat, int row);}
1530 \cvdefPy{GetRow(arr,row)-> submat}
1531 \cvdefC{CvMat* cvGetRows(const CvArr* arr, CvMat* submat, int startRow, int endRow, int deltaRow=1);}
1532 \cvdefPy{GetRows(arr,startRow,endRow,deltaRow=1)-> submat}
1533
1534 \begin{description}
1535 \cvarg{arr}{Input array}
1536 \cvarg{submat}{Pointer to the resulting sub-array header}
1537 \cvarg{row}{Zero-based index of the selected row}
1538 \cvarg{startRow}{Zero-based index of the starting row (inclusive) of the span}
1539 \cvarg{endRow}{Zero-based index of the ending row (exclusive) of the span}
1540 \cvarg{deltaRow}{Index step in the row span. That is, the function extracts every \texttt{deltaRow}-th row from \texttt{startRow} and up to (but not including) \texttt{endRow}.}
1541 \end{description}
1542
1543 The functions return the header, corresponding to a specified row/row span of the input array. Note that \texttt{GetRow} is a shortcut for \cvCPyCross{GetRows}:
1544
1545 \begin{lstlisting}
1546 cvGetRow(arr, submat, row ) ~ cvGetRows(arr, submat, row, row + 1, 1);
1547 \end{lstlisting}
1548
1549 \else % }{
1550
1551 \cvCPyFunc{GetRow}
1552 Returns array row.
1553
1554 \cvdefPy{GetRow(arr,row)-> submat}
1555
1556 \begin{description}
1557 \cvarg{arr}{Input array}
1558 \cvarg{row}{Zero-based index of the selected row}
1559 \cvarg{submat}{resulting single-row array}
1560 \end{description}
1561
1562 The function \texttt{GetRow} returns a single row from the input array.
1563
1564 \cvCPyFunc{GetRows}
1565 Returns array row span.
1566
1567 \cvdefPy{GetRows(arr,startRow,endRow,deltaRow=1)-> submat}
1568
1569 \begin{description}
1570 \cvarg{arr}{Input array}
1571 \cvarg{startRow}{Zero-based index of the starting row (inclusive) of the span}
1572 \cvarg{endRow}{Zero-based index of the ending row (exclusive) of the span}
1573 \cvarg{deltaRow}{Index step in the row span.}
1574 \cvarg{submat}{resulting multi-row array}
1575 \end{description}
1576
1577 The function \texttt{GetRows} returns a row span from the input array.
1578
1579 \fi % }
1580
1581 \cvCPyFunc{GetSize}
1582 Returns size of matrix or image ROI.
1583
1584 \cvdefC{CvSize cvGetSize(const CvArr* arr);}
1585 \cvdefPy{GetSize(arr)-> CvSize}
1586
1587 \begin{description}
1588 \cvarg{arr}{array header}
1589 \end{description}
1590
1591 The function returns number of rows (CvSize::height) and number of columns (CvSize::width) of the input matrix or image. In the case of image the size of ROI is returned.
1592
1593
1594 \cvCPyFunc{GetSubRect}
1595 Returns matrix header corresponding to the rectangular sub-array of input image or matrix.
1596
1597 \cvdefC{CvMat* cvGetSubRect(const CvArr* arr, CvMat* submat, CvRect rect);}
1598 \cvdefPy{GetSubRect(arr, rect) -> cvmat}
1599
1600 \begin{description}
1601 \cvarg{arr}{Input array}
1602 \ifC
1603 \cvarg{submat}{Pointer to the resultant sub-array header}
1604 \fi
1605 \cvarg{rect}{Zero-based coordinates of the rectangle of interest}
1606 \end{description}
1607
1608 The function returns header, corresponding to
1609 a specified rectangle of the input array. In other words, it allows
1610 the user to treat a rectangular part of input array as a stand-alone
1611 array. ROI is taken into account by the function so the sub-array of
1612 ROI is actually extracted.
1613
1614 \cvCPyFunc{InRange}
1615 Checks that array elements lie between the elements of two other arrays.
1616
1617 \cvdefC{void cvInRange(const CvArr* src, const CvArr* lower, const CvArr* upper, CvArr* dst);}
1618 \cvdefPy{InRange(src,lower,upper,dst)-> None}
1619
1620 \begin{description}
1621 \cvarg{src}{The first source array}
1622 \cvarg{lower}{The inclusive lower boundary array}
1623 \cvarg{upper}{The exclusive upper boundary array}
1624 \cvarg{dst}{The destination array, must have 8u or 8s type}
1625 \end{description}
1626
1627
1628 The function does the range check for every element of the input array:
1629
1630 \[
1631 \texttt{dst}(I)=\texttt{lower}(I)_0 <= \texttt{src}(I)_0 < \texttt{upper}(I)_0
1632 \]
1633
1634 For single-channel arrays,
1635
1636 \[
1637 \texttt{dst}(I)=
1638 \texttt{lower}(I)_0 <= \texttt{src}(I)_0 < \texttt{upper}(I)_0 \land
1639 \texttt{lower}(I)_1 <= \texttt{src}(I)_1 < \texttt{upper}(I)_1
1640 \]
1641
1642 For two-channel arrays and so forth,
1643
1644 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).
1645
1646
1647 \cvCPyFunc{InRangeS}
1648 Checks that array elements lie between two scalars.
1649
1650 \cvdefC{void cvInRangeS(const CvArr* src, CvScalar lower, CvScalar upper, CvArr* dst);}
1651 \cvdefPy{InRangeS(src,lower,upper,dst)-> None}
1652
1653 \begin{description}
1654 \cvarg{src}{The first source array}
1655 \cvarg{lower}{The inclusive lower boundary}
1656 \cvarg{upper}{The exclusive upper boundary}
1657 \cvarg{dst}{The destination array, must have 8u or 8s type}
1658 \end{description}
1659
1660
1661 The function does the range check for every element of the input array:
1662
1663 \[
1664 \texttt{dst}(I)=\texttt{lower}_0 <= \texttt{src}(I)_0 < \texttt{upper}_0
1665 \]
1666
1667 For single-channel arrays,
1668
1669 \[
1670 \texttt{dst}(I)=
1671 \texttt{lower}_0 <= \texttt{src}(I)_0 < \texttt{upper}_0 \land
1672 \texttt{lower}_1 <= \texttt{src}(I)_1 < \texttt{upper}_1
1673 \]
1674
1675 For two-channel arrays nd so forth,
1676
1677 '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).
1678
1679 \ifC
1680 \cvCPyFunc{IncRefData}
1681 Increments array data reference counter.
1682
1683 \cvdefC{int cvIncRefData(CvArr* arr);}
1684
1685 \begin{description}
1686 \cvarg{arr}{Array header}
1687 \end{description}
1688
1689 The function increments \cross{CvMat} or
1690 \cross{CvMatND} data reference counter and returns the new counter value
1691 if the reference counter pointer is not NULL, otherwise it returns zero.
1692
1693 \cvCPyFunc{InitImageHeader}
1694 Initializes an image header that was previously allocated.
1695
1696 \cvdefC{IplImage* cvInitImageHeader(\par IplImage* image,\par CvSize size,\par int depth,\par int channels,\par int origin=0,\par int align=4);}
1697
1698 \begin{description}
1699 \cvarg{image}{Image header to initialize}
1700 \cvarg{size}{Image width and height}
1701 \cvarg{depth}{Image depth (see \cvCPyCross{CreateImage})}
1702 \cvarg{channels}{Number of channels (see \cvCPyCross{CreateImage})}
1703 \cvarg{origin}{Top-left \texttt{IPL\_ORIGIN\_TL} or bottom-left \texttt{IPL\_ORIGIN\_BL}}
1704 \cvarg{align}{Alignment for image rows, typically 4 or 8 bytes}
1705 \end{description}
1706
1707 The returned \texttt{IplImage*} points to the initialized header.
1708
1709 \cvCPyFunc{InitMatHeader}
1710 Initializes a pre-allocated matrix header.
1711
1712 \cvdefC{
1713 CvMat* cvInitMatHeader(\par CvMat* mat,\par int rows,\par int cols,\par int type, \par void* data=NULL,\par int step=CV\_AUTOSTEP);
1714 }
1715
1716 \begin{description}
1717 \cvarg{mat}{A pointer to the matrix header to be initialized}
1718 \cvarg{rows}{Number of rows in the matrix}
1719 \cvarg{cols}{Number of columns in the matrix}
1720 \cvarg{type}{Type of the matrix elements, see \cvCPyCross{CreateMat}.}
1721 \cvarg{data}{Optional: data pointer assigned to the matrix header}
1722 \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.}
1723 \end{description}
1724
1725 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:
1726
1727 \begin{lstlisting}
1728 double a[] = { 1, 2, 3, 4,
1729                5, 6, 7, 8,
1730                9, 10, 11, 12 };
1731
1732 double b[] = { 1, 5, 9,
1733                2, 6, 10,
1734                3, 7, 11,
1735                4, 8, 12 };
1736
1737 double c[9];
1738 CvMat Ma, Mb, Mc ;
1739
1740 cvInitMatHeader(&Ma, 3, 4, CV_64FC1, a);
1741 cvInitMatHeader(&Mb, 4, 3, CV_64FC1, b);
1742 cvInitMatHeader(&Mc, 3, 3, CV_64FC1, c);
1743
1744 cvMatMulAdd(&Ma, &Mb, 0, &Mc);
1745 // the c array now contains the product of a (3x4) and b (4x3)
1746
1747 \end{lstlisting}
1748
1749 \cvCPyFunc{InitMatNDHeader}
1750 Initializes a pre-allocated multi-dimensional array header.
1751
1752 \cvdefC{CvMatND* cvInitMatNDHeader(\par CvMatND* mat,\par int dims,\par const int* sizes,\par int type,\par void* data=NULL);}
1753
1754 \begin{description}
1755 \cvarg{mat}{A pointer to the array header to be initialized}
1756 \cvarg{dims}{The number of array dimensions}
1757 \cvarg{sizes}{An array of dimension sizes}
1758 \cvarg{type}{Type of array elements, see \cvCPyCross{CreateMat}}
1759 \cvarg{data}{Optional data pointer assigned to the matrix header}
1760 \end{description}
1761
1762 \cvCPyFunc{InitSparseMatIterator}
1763 Initializes sparse array elements iterator.
1764
1765 \cvdefC{CvSparseNode* cvInitSparseMatIterator(const CvSparseMat* mat,
1766                                        CvSparseMatIterator* matIterator);}
1767
1768 \begin{description}
1769 \cvarg{mat}{Input array}
1770 \cvarg{matIterator}{Initialized iterator}
1771 \end{description}
1772
1773 The function initializes iterator of
1774 sparse array elements and returns pointer to the first element, or NULL
1775 if the array is empty.
1776
1777 \fi
1778
1779 \cvCPyFunc{InvSqrt}
1780 Calculates the inverse square root.
1781
1782 \cvdefC{float cvInvSqrt(float value);}
1783 \cvdefPy{InvSqrt(value)-> float}
1784
1785 \begin{description}
1786 \cvarg{value}{The input floating-point value}
1787 \end{description}
1788
1789
1790 The function calculates the inverse square root of the argument, and normally it is faster than \texttt{1./sqrt(value)}. If the argument is zero or negative, the result is not determined. Special values ($\pm \infty $ , NaN) are not handled.
1791
1792 \cvCPyFunc{Invert}
1793 Finds the inverse or pseudo-inverse of a matrix.
1794
1795 \cvdefC{double cvInvert(const CvArr* src, CvArr* dst, int method=CV\_LU);}
1796 \cvdefPy{Invert(src,dst,method=CV\_LU)-> double}
1797 \begin{lstlisting}
1798 #define cvInv cvInvert
1799 \end{lstlisting}
1800
1801 \begin{description}
1802 \cvarg{src}{The source matrix}
1803 \cvarg{dst}{The destination matrix}
1804 \cvarg{method}{Inversion method
1805 \begin{description}
1806  \cvarg{CV\_LU}{Gaussian elimination with optimal pivot element chosen}
1807  \cvarg{CV\_SVD}{Singular value decomposition (SVD) method}
1808  \cvarg{CV\_SVD\_SYM}{SVD method for a symmetric positively-defined matrix}
1809 \end{description}}
1810 \end{description}
1811
1812 The function inverts matrix \texttt{src1} and stores the result in \texttt{src2}.
1813
1814 In the case of \texttt{LU} method, the function returns the \texttt{src1} determinant (src1 must be square). If it is 0, the matrix is not inverted and \texttt{src2} is filled with zeros.
1815
1816 In the case of \texttt{SVD} methods, the function returns the inversed condition of \texttt{src1} (ratio of the smallest singular value to the largest singular value) and 0 if \texttt{src1} is all zeros. The SVD methods calculate a pseudo-inverse matrix if \texttt{src1} is singular.
1817
1818
1819 \cvCPyFunc{IsInf}
1820 Determines if the argument is Infinity.
1821
1822 \cvdefC{int cvIsInf(double value);}
1823 \cvdefPy{IsInf(value)-> int}
1824
1825 \begin{description}
1826 \cvarg{value}{The input floating-point value}
1827 \end{description}
1828
1829 The function returns 1 if the argument is $\pm \infty $ (as defined by IEEE754 standard), 0 otherwise.
1830
1831 \cvCPyFunc{IsNaN}
1832 Determines if the argument is Not A Number.
1833
1834 \cvdefC{int cvIsNaN(double value);}
1835 \cvdefPy{IsNaN(value)-> int}
1836
1837 \begin{description}
1838 \cvarg{value}{The input floating-point value}
1839 \end{description}
1840
1841 The function returns 1 if the argument is Not A Number (as defined by IEEE754 standard), 0 otherwise.
1842
1843
1844 \cvCPyFunc{LUT}
1845 Performs a look-up table transform of an array.
1846
1847 \cvdefC{void cvLUT(const CvArr* src, CvArr* dst, const CvArr* lut);}
1848 \cvdefPy{LUT(src,dst,lut)-> None}
1849
1850 \begin{description}
1851 \cvarg{src}{Source array of 8-bit elements}
1852 \cvarg{dst}{Destination array of a given depth and of the same number of channels as the source array}
1853 \cvarg{lut}{Look-up table of 256 elements; should have the same depth as the destination array. In the case of multi-channel source and destination arrays, the table should either have a single-channel (in this case the same table is used for all channels) or the same number of channels as the source/destination array.}
1854 \end{description}
1855
1856 The function fills the destination array with values from the look-up table. Indices of the entries are taken from the source array. That is, the function processes each element of \texttt{src} as follows:
1857
1858 \[
1859 \texttt{dst}_i \leftarrow \texttt{lut}_{\texttt{src}_i + d}
1860 \]
1861
1862 where
1863
1864 \[
1865 d = \fork
1866 {0}{if \texttt{src} has depth \texttt{CV\_8U}}
1867 {128}{if \texttt{src} has depth \texttt{CV\_8S}}
1868 \]
1869
1870 \cvCPyFunc{Log}
1871 Calculates the natural logarithm of every array element's absolute value.
1872
1873 \cvdefC{void cvLog(const CvArr* src, CvArr* dst);}
1874 \cvdefPy{Log(src,dst)-> None}
1875
1876 \begin{description}
1877 \cvarg{src}{The source array}
1878 \cvarg{dst}{The destination array, it should have \texttt{double} type or the same type as the source}
1879 \end{description}
1880
1881 The function calculates the natural logarithm of the absolute value of every element of the input array:
1882
1883 \[
1884 \texttt{dst} [I] = \fork
1885 {\log{|\texttt{src}(I)}}{if $\texttt{src}[I] \ne 0$ }
1886 {\texttt{C}}{otherwise}
1887 \]
1888
1889 Where \texttt{C} is a large negative number (about -700 in the current implementation).
1890
1891 \cvCPyFunc{Mahalonobis}
1892 Calculates the Mahalonobis distance between two vectors.
1893
1894 \cvdefC{double cvMahalanobis(\par const CvArr* vec1,\par const CvArr* vec2,\par CvArr* mat);}
1895 \cvdefPy{Mahalonobis(vec1,vec2,mat)-> None}
1896
1897 \begin{description}
1898 \cvarg{vec1}{The first 1D source vector}
1899 \cvarg{vec2}{The second 1D source vector}
1900 \cvarg{mat}{The inverse covariance matrix}
1901 \end{description}
1902
1903
1904 The function calculates and returns the weighted distance between two vectors:
1905
1906 \[
1907 d(\texttt{vec1},\texttt{vec2})=\sqrt{\sum_{i,j}{\texttt{icovar(i,j)}\cdot(\texttt{vec1}(I)-\texttt{vec2}(I))\cdot(\texttt{vec1(j)}-\texttt{vec2(j)})}}
1908 \]
1909
1910 The covariance matrix may be calculated using the \cvCPyCross{CalcCovarMatrix} function and further inverted using the \cvCPyCross{Invert} function (CV\_SVD method is the prefered one because the matrix might be singular).
1911
1912
1913 \ifC
1914 \cvCPyFunc{Mat}
1915 Initializes matrix header (lightweight variant).
1916
1917 \cvdefC{CvMat cvMat(\par int rows,\par int cols,\par int type,\par void* data=NULL);}
1918
1919 \begin{description}
1920 \cvarg{rows}{Number of rows in the matrix}
1921 \cvarg{cols}{Number of columns in the matrix}
1922 \cvarg{type}{Type of the matrix elements - see \cvCPyCross{CreateMat}}
1923 \cvarg{data}{Optional data pointer assigned to the matrix header}
1924 \end{description}
1925
1926 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.)
1927
1928 This function is a fast inline substitution for \cvCPyCross{InitMatHeader}. Namely, it is equivalent to:
1929
1930 \begin{lstlisting}
1931 CvMat mat;
1932 cvInitMatHeader(&mat, rows, cols, type, data, CV\_AUTOSTEP);
1933 \end{lstlisting}
1934 \fi
1935
1936 \cvCPyFunc{Max}
1937 Finds per-element maximum of two arrays.
1938
1939 \cvdefC{void cvMax(const CvArr* src1, const CvArr* src2, CvArr* dst);}
1940 \cvdefPy{Max(src1,src2,dst)-> None}
1941
1942 \begin{description}
1943 \cvarg{src1}{The first source array}
1944 \cvarg{src2}{The second source array}
1945 \cvarg{dst}{The destination array}
1946 \end{description}
1947
1948 The function calculates per-element maximum of two arrays:
1949
1950 \[
1951 \texttt{dst}(I)=\max(\texttt{src1}(I), \texttt{src2}(I))
1952 \]
1953
1954 All the arrays must have a single channel, the same data type and the same size (or ROI size).
1955
1956
1957 \cvCPyFunc{MaxS}
1958 Finds per-element maximum of array and scalar.
1959
1960 \cvdefC{void cvMaxS(const CvArr* src, double value, CvArr* dst);}
1961 \cvdefPy{MaxS(src,value,dst)-> None}
1962
1963 \begin{description}
1964 \cvarg{src}{The first source array}
1965 \cvarg{value}{The scalar value}
1966 \cvarg{dst}{The destination array}
1967 \end{description}
1968
1969 The function calculates per-element maximum of array and scalar:
1970
1971 \[
1972 \texttt{dst}(I)=\max(\texttt{src}(I), \texttt{value})
1973 \]
1974
1975 All the arrays must have a single channel, the same data type and the same size (or ROI size).
1976
1977
1978 \cvCPyFunc{Merge}
1979 Composes a multi-channel array from several single-channel arrays or inserts a single channel into the array.
1980
1981 \cvdefC{void cvMerge(const CvArr* src0, const CvArr* src1,
1982               const CvArr* src2, const CvArr* src3, CvArr* dst);}
1983 \ifC
1984 \begin{lstlisting}
1985 #define cvCvtPlaneToPix cvMerge
1986 \end{lstlisting}
1987 \fi
1988 \cvdefPy{Merge(src0,src1,src2,src3,dst)-> None}
1989
1990 \begin{description}
1991 \cvarg{src0}{Input channel 0}
1992 \cvarg{src1}{Input channel 1}
1993 \cvarg{src2}{Input channel 2}
1994 \cvarg{src3}{Input channel 3}
1995 \cvarg{dst}{Destination array}
1996 \end{description}
1997
1998 The function is the opposite to \cvCPyCross{Split}. If the destination array has N channels then if the first N input channels are not NULL, they all are copied to the destination array; if only a single source channel of the first N is not NULL, this particular channel is copied into the destination array; otherwise an error is raised. The rest of the source channels (beyond the first N) must always be NULL. For IplImage \cvCPyCross{Copy} with COI set can be also used to insert a single channel into the image.
1999
2000 \cvCPyFunc{Min}
2001 Finds per-element minimum of two arrays.
2002
2003 \cvdefC{void cvMin(const CvArr* src1, const CvArr* src2, CvArr* dst);}
2004 \cvdefPy{Min(src1,src2,dst)-> None}
2005
2006 \begin{description}
2007 \cvarg{src1}{The first source array}
2008 \cvarg{src2}{The second source array}
2009 \cvarg{dst}{The destination array}
2010 \end{description}
2011
2012
2013 The function calculates per-element minimum of two arrays:
2014
2015 \[
2016 \texttt{dst}(I)=\min(\texttt{src1}(I),\texttt{src2}(I))
2017 \]
2018
2019 All the arrays must have a single channel, the same data type and the same size (or ROI size).
2020
2021
2022 \cvCPyFunc{MinMaxLoc}
2023 Finds global minimum and maximum in array or subarray.
2024
2025 \cvdefC{void cvMinMaxLoc(const CvArr* arr, double* minVal, double* maxVal,
2026                   CvPoint* minLoc=NULL, CvPoint* maxLoc=NULL, const CvArr* mask=NULL);}
2027 \cvdefPy{MinMaxLoc(arr,mask=NULL)-> (minVal,maxVal,minLoc,maxLoc)}
2028
2029 \begin{description}
2030 \cvarg{arr}{The source array, single-channel or multi-channel with COI set}
2031 \cvarg{minVal}{Pointer to returned minimum value}
2032 \cvarg{maxVal}{Pointer to returned maximum value}
2033 \cvarg{minLoc}{Pointer to returned minimum location}
2034 \cvarg{maxLoc}{Pointer to returned maximum location}
2035 \cvarg{mask}{The optional mask used to select a subarray}
2036 \end{description}
2037
2038 The function finds minimum and maximum element values
2039 and their positions. The extremums are searched across the whole array,
2040 selected \texttt{ROI} (in the case of \texttt{IplImage}) or, if \texttt{mask}
2041 is not \texttt{NULL}, in the specified array region. If the array has
2042 more than one channel, it must be \texttt{IplImage} with \texttt{COI}
2043 set. In the case of multi-dimensional arrays, \texttt{minLoc->x} and \texttt{maxLoc->x}
2044 will contain raw (linear) positions of the extremums.
2045
2046 \cvCPyFunc{MinS}
2047 Finds per-element minimum of an array and a scalar.
2048
2049 \cvdefC{void cvMinS(const CvArr* src, double value, CvArr* dst);}
2050 \cvdefPy{MinS(src,value,dst)-> None}
2051
2052 \begin{description}
2053 \cvarg{src}{The first source array}
2054 \cvarg{value}{The scalar value}
2055 \cvarg{dst}{The destination array}
2056 \end{description}
2057
2058 The function calculates minimum of an array and a scalar:
2059
2060 \[
2061 \texttt{dst}(I)=\min(\texttt{src}(I), \texttt{value})
2062 \]
2063
2064 All the arrays must have a single channel, the same data type and the same size (or ROI size).
2065
2066
2067 \cvCPyFunc{MixChannels}
2068 Copies several channels from input arrays to certain channels of output arrays
2069
2070 \cvdefC{void cvMixChannels(const CvArr** src, int srcCount, \par
2071                     CvArr** dst, int dstCount, \par
2072                     const int* fromTo, int pairCount);}
2073 \cvdefPy{MixChannels(src, dst, fromTo) -> None}
2074
2075 \begin{description}
2076 \cvarg{src}{Input arrays}
2077 \cvC{\cvarg{srcCount}{The number of input arrays.}}
2078 \cvarg{dst}{Destination arrays}
2079 \cvC{\cvarg{dstCount}{The number of output arrays.}}
2080 \cvarg{fromTo}{The array of pairs of indices of the planes
2081 copied. \cvC{\texttt{fromTo[k*2]} is the 0-based index of the input channel in \texttt{src} and
2082 \texttt{fromTo[k*2+1]} is the index of the output channel in \texttt{dst}.
2083 Here the continuous channel numbering is used, that is, the first input image channels are indexed
2084 from \texttt{0} to \texttt{channels(src[0])-1}, the second input image channels are indexed from
2085 \texttt{channels(src[0])} to \texttt{channels(src[0]) + channels(src[1])-1} etc., and the same
2086 scheme is used for the output image channels.
2087 As a special case, when \texttt{fromTo[k*2]} is negative,
2088 the corresponding output channel is filled with zero.}\cvPy{Each pair \texttt{fromTo[k]=(i,j)}
2089 means that i-th plane from \texttt{src} is copied to the j-th plane in \texttt{dst}, where continuous
2090 plane numbering is used both in the input array list and the output array list.
2091 As a special case, when the \texttt{fromTo[k][0]} is negative, the corresponding output plane \texttt{j}
2092  is filled with zero.}}
2093 \end{description}
2094
2095 The function is a generalized form of \cvCPyCross{cvSplit} and \cvCPyCross{Merge}
2096 and some forms of \cross{CvtColor}. It can be used to change the order of the
2097 planes, add/remove alpha channel, extract or insert a single plane or
2098 multiple planes etc.
2099
2100 As an example, this code splits a 4-channel RGBA image into a 3-channel
2101 BGR (i.e. with R and B swapped) and separate alpha channel image:
2102
2103 \ifPy
2104 \begin{lstlisting}
2105         rgba = cv.CreateMat(100, 100, cv.CV_8UC4)
2106         bgr =  cv.CreateMat(100, 100, cv.CV_8UC3)
2107         alpha = cv.CreateMat(100, 100, cv.CV_8UC1)
2108         cv.Set(rgba, (1,2,3,4))
2109         cv.MixChannels([rgba], [bgr, alpha], [
2110            (0, 2),    # rgba[0] -> bgr[2]
2111            (1, 1),    # rgba[1] -> bgr[1]
2112            (2, 0),    # rgba[2] -> bgr[0]
2113            (3, 3)     # rgba[3] -> alpha[0]
2114         ])
2115 \end{lstlisting}
2116 \fi
2117
2118 \ifC
2119 \begin{lstlisting}
2120     CvMat* rgba = cvCreateMat(100, 100, CV_8UC4);
2121     CvMat* bgr = cvCreateMat(rgba->rows, rgba->cols, CV_8UC3);
2122     CvMat* alpha = cvCreateMat(rgba->rows, rgba->cols, CV_8UC1);
2123     cvSet(rgba, cvScalar(1,2,3,4));
2124
2125     CvArr* out[] = { bgr, alpha };
2126     int from_to[] = { 0,2,  1,1,  2,0,  3,3 };
2127     cvMixChannels(&bgra, 1, out, 2, from_to, 4);
2128 \end{lstlisting}
2129 \fi
2130
2131 \cvCPyFunc{Mul}
2132 Calculates the per-element product of two arrays.
2133
2134 \cvdefC{void cvMul(const CvArr* src1, const CvArr* src2, CvArr* dst, double scale=1);}
2135 \cvdefPy{Mul(src1,src2,dst,scale)-> None}
2136
2137 \begin{description}
2138 \cvarg{src1}{The first source array}
2139 \cvarg{src2}{The second source array}
2140 \cvarg{dst}{The destination array}
2141 \cvarg{scale}{Optional scale factor}
2142 \end{description}
2143
2144
2145 The function calculates the per-element product of two arrays:
2146
2147 \[
2148 \texttt{dst}(I)=\texttt{scale} \cdot \texttt{src1}(I) \cdot \texttt{src2}(I)
2149 \]
2150
2151 All the arrays must have the same type and the same size (or ROI size).
2152 For types that have limited range this operation is saturating.
2153
2154 \cvCPyFunc{MulSpectrums}
2155 Performs per-element multiplication of two Fourier spectrums.
2156
2157 \cvdefC{void cvMulSpectrums(\par const CvArr* src1,\par const CvArr* src2,\par CvArr* dst,\par int flags);}
2158 \cvdefPy{MulSpectrums(src1,src2,dst,flags)-> None}
2159
2160 \begin{description}
2161 \cvarg{src1}{The first source array}
2162 \cvarg{src2}{The second source array}
2163 \cvarg{dst}{The destination array of the same type and the same size as the source arrays}
2164 \cvarg{flags}{A combination of the following values;
2165 \begin{description}
2166 \cvarg{CV\_DXT\_ROWS}{treats each row of the arrays as a separate spectrum (see \cvCPyCross{DFT} parameters description).}
2167 \cvarg{CV\_DXT\_MUL\_CONJ}{conjugate the second source array before the multiplication.}
2168 \end{description}}
2169
2170 \end{description}
2171
2172 The function performs per-element multiplication of the two CCS-packed or complex matrices that are results of a real or complex Fourier transform.
2173
2174 The function, together with \cvCPyCross{DFT}, may be used to calculate convolution of two arrays rapidly.
2175
2176
2177 \cvCPyFunc{MulTransposed}
2178 Calculates the product of an array and a transposed array.
2179
2180 \cvdefC{void cvMulTransposed(const CvArr* src, CvArr* dst, int order, const CvArr* delta=NULL, double scale=1.0);}
2181 \cvdefPy{MulTransposed(src,dst,order,delta=NULL,scale)-> None}
2182
2183 \begin{description}
2184 \cvarg{src}{The source matrix}
2185 \cvarg{dst}{The destination matrix. Must be \texttt{CV\_32F} or \texttt{CV\_64F}.}
2186 \cvarg{order}{Order of multipliers}
2187 \cvarg{delta}{An optional array, subtracted from \texttt{src} before multiplication}
2188 \cvarg{scale}{An optional scaling}
2189 \end{description}
2190
2191 The function calculates the product of src and its transposition:
2192
2193 \[
2194 \texttt{dst}=\texttt{scale} (\texttt{src}-\texttt{delta}) (\texttt{src}-\texttt{delta})^T
2195 \]
2196
2197 if $\texttt{order}=0$, and
2198
2199 \[
2200 \texttt{dst}=\texttt{scale} (\texttt{src}-\texttt{delta})^T (\texttt{src}-\texttt{delta})
2201 \]
2202
2203 otherwise.
2204
2205 \cvCPyFunc{Norm}
2206 Calculates absolute array norm, absolute difference norm, or relative difference norm.
2207
2208 \cvdefC{double cvNorm(const CvArr* arr1, const CvArr* arr2=NULL, int normType=CV\_L2, const CvArr* mask=NULL);}
2209 \cvdefPy{Norm(arr1,arr2,normType=CV\_L2,mask=NULL)-> double}
2210
2211 \begin{description}
2212 \cvarg{arr1}{The first source image}
2213 \cvarg{arr2}{The second source image. If it is NULL, the absolute norm of \texttt{arr1} is calculated, otherwise the absolute or relative norm of \texttt{arr1}-\texttt{arr2} is calculated.}
2214 \cvarg{normType}{Type of norm, see the discussion}
2215 \cvarg{mask}{The optional operation mask}
2216 \end{description}
2217
2218 The function calculates the absolute norm of \texttt{arr1} if \texttt{arr2} is NULL:
2219 \[
2220 norm = \forkthree
2221 {||\texttt{arr1}||_C    = \max_I |\texttt{arr1}(I)|}{if $\texttt{normType} = \texttt{CV\_C}$}
2222 {||\texttt{arr1}||_{L1} = \sum_I |\texttt{arr1}(I)|}{if $\texttt{normType} = \texttt{CV\_L1}$}
2223 {||\texttt{arr1}||_{L2} = \sqrt{\sum_I \texttt{arr1}(I)^2}}{if $\texttt{normType} = \texttt{CV\_L2}$}
2224 \]
2225
2226 or the absolute difference norm if \texttt{arr2} is not NULL:
2227 \[
2228 norm = \forkthree
2229 {||\texttt{arr1}-\texttt{arr2}||_C    = \max_I |\texttt{arr1}(I) - \texttt{arr2}(I)|}{if $\texttt{normType} = \texttt{CV\_C}$}
2230 {||\texttt{arr1}-\texttt{arr2}||_{L1} = \sum_I |\texttt{arr1}(I) - \texttt{arr2}(I)|}{if $\texttt{normType} = \texttt{CV\_L1}$}
2231 {||\texttt{arr1}-\texttt{arr2}||_{L2} = \sqrt{\sum_I (\texttt{arr1}(I) - \texttt{arr2}(I))^2}}{if $\texttt{normType} = \texttt{CV\_L2}$}
2232 \]
2233
2234 or the relative difference norm if \texttt{arr2} is not NULL and \texttt{(normType \& CV\_RELATIVE) != 0}:
2235
2236 \[
2237 norm = \forkthree
2238 {\frac{||\texttt{arr1}-\texttt{arr2}||_C    }{||\texttt{arr2}||_C   }}{if $\texttt{normType} = \texttt{CV\_RELATIVE\_C}$}
2239 {\frac{||\texttt{arr1}-\texttt{arr2}||_{L1} }{||\texttt{arr2}||_{L1}}}{if $\texttt{normType} = \texttt{CV\_RELATIVE\_L1}$}
2240 {\frac{||\texttt{arr1}-\texttt{arr2}||_{L2} }{||\texttt{arr2}||_{L2}}}{if $\texttt{normType} = \texttt{CV\_RELATIVE\_L2}$}
2241 \]
2242
2243 The function returns the calculated norm. A multiple-channel array is treated as a single-channel, that is, the results for all channels are combined.
2244
2245 \cvCPyFunc{Not}
2246 Performs per-element bit-wise inversion of array elements.
2247
2248 \cvdefC{void cvNot(const CvArr* src, CvArr* dst);}
2249 \cvdefPy{Not(src,dst)-> None}
2250
2251 \begin{description}
2252 \cvarg{src}{The source array}
2253 \cvarg{dst}{The destination array}
2254 \end{description}
2255
2256
2257 The function Not inverses every bit of every array element:
2258
2259 \begin{lstlisting}
2260 dst(I)=~src(I)
2261 \end{lstlisting}
2262
2263
2264 \cvCPyFunc{Or}
2265 Calculates per-element bit-wise disjunction of two arrays.
2266
2267 \cvdefC{void cvOr(const CvArr* src1, const CvArr* src2, CvArr* dst, const CvArr* mask=NULL);}
2268 \cvdefPy{Or(src1,src2,dst,mask=NULL)-> None}
2269
2270 \begin{description}
2271 \cvarg{src1}{The first source array}
2272 \cvarg{src2}{The second source array}
2273 \cvarg{dst}{The destination array}
2274 \cvarg{mask}{Operation mask, 8-bit single channel array; specifies elements of the destination array to be changed}
2275 \end{description}
2276
2277
2278 The function calculates per-element bit-wise disjunction of two arrays:
2279
2280 \begin{lstlisting}
2281 dst(I)=src1(I)|src2(I)
2282 \end{lstlisting}
2283
2284 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.
2285
2286 \cvCPyFunc{OrS}
2287 Calculates a per-element bit-wise disjunction of an array and a scalar.
2288
2289 \cvdefC{void cvOrS(const CvArr* src, CvScalar value, CvArr* dst, const CvArr* mask=NULL);}
2290 \cvdefPy{OrS(src1,value,dst,mask=NULL)-> None}
2291
2292 \begin{description}
2293 \cvarg{src1}{The source array}
2294 \cvarg{value}{Scalar to use in the operation}
2295 \cvarg{dst}{The destination array}
2296 \cvarg{mask}{Operation mask, 8-bit single channel array; specifies elements of the destination array to be changed}
2297 \end{description}
2298
2299
2300 The function OrS calculates per-element bit-wise disjunction of an array and a scalar:
2301
2302 \begin{lstlisting}
2303 dst(I)=src(I)|value if mask(I)!=0
2304 \end{lstlisting}
2305
2306 Prior to the actual operation, the scalar is converted to the same type as that of the array(s). In the case of floating-point arrays their bit representations are used for the operation. All the arrays must have the same type, except the mask, and the same size.
2307
2308
2309 \cvCPyFunc{PerspectiveTransform}
2310 Performs perspective matrix transformation of a vector array.
2311
2312 \cvdefC{void cvPerspectiveTransform(const CvArr* src, CvArr* dst, const CvMat* mat);}
2313 \cvdefPy{PerspectiveTransform(src,dst,mat)-> None}
2314
2315 \begin{description}
2316 \cvarg{src}{The source three-channel floating-point array}
2317 \cvarg{dst}{The destination three-channel floating-point array}
2318 \cvarg{mat}{$3\times 3$ or $4 \times 4$ transformation matrix}
2319 \end{description}
2320
2321
2322 The function transforms every element of \texttt{src} (by treating it as 2D or 3D vector) in the following way:
2323
2324 \[ (x, y, z) \rightarrow (x'/w, y'/w, z'/w) \]
2325
2326 where
2327
2328 \[
2329 (x', y', z', w') = \texttt{mat} \cdot
2330 \begin{bmatrix} x & y & z & 1 \end{bmatrix}
2331 \]
2332
2333 and
2334 \[ w = \fork{w'}{if $w' \ne 0$}{\infty}{otherwise} \]
2335
2336 \cvCPyFunc{PolarToCart}
2337 Calculates Cartesian coordinates of 2d vectors represented in polar form.
2338
2339 \cvdefC{void cvPolarToCart(\par const CvArr* magnitude,\par const CvArr* angle,\par CvArr* x,\par CvArr* y,\par int angleInDegrees=0);}
2340 \cvdefPy{PolarToCart(magnitude,angle,x,y,angleInDegrees=0)-> None}
2341
2342 \begin{description}
2343 \cvarg{magnitude}{The array of magnitudes. If it is NULL, the magnitudes are assumed to be all 1's.}
2344 \cvarg{angle}{The array of angles, whether in radians or degrees}
2345 \cvarg{x}{The destination array of x-coordinates, may be set to NULL if it is not needed}
2346 \cvarg{y}{The destination array of y-coordinates, mau be set to NULL if it is not needed}
2347 \cvarg{angleInDegrees}{The flag indicating whether the angles are measured in radians, which is default mode, or in degrees}
2348 \end{description}
2349
2350 The function calculates either the x-coodinate, y-coordinate or both of every vector \texttt{magnitude(I)*exp(angle(I)*j), j=sqrt(-1)}:
2351
2352 \begin{lstlisting}
2353 x(I)=magnitude(I)*cos(angle(I)),
2354 y(I)=magnitude(I)*sin(angle(I))
2355 \end{lstlisting}
2356
2357
2358 \cvCPyFunc{Pow}
2359 Raises every array element to a power.
2360
2361 \cvdefC{void cvPow(\par const CvArr* src,\par CvArr* dst,\par double power);}
2362 \cvdefPy{Pow(src,dst,power)-> None}
2363
2364 \begin{description}
2365 \cvarg{src}{The source array}
2366 \cvarg{dst}{The destination array, should be the same type as the source}
2367 \cvarg{power}{The exponent of power}
2368 \end{description}
2369
2370
2371 The function raises every element of the input array to \texttt{p}:
2372
2373 \[
2374 \texttt{dst} [I] = \fork
2375 {\texttt{src}(I)^p}{if \texttt{p} is integer}
2376 {|\texttt{src}(I)^p|}{otherwise}
2377 \]
2378
2379 That is, for a non-integer power exponent the absolute values of input array elements are used. However, it is possible to get true values for negative values using some extra operations, as the following example, computing the cube root of array elements, shows:
2380
2381 \begin{lstlisting}
2382 CvSize size = cvGetSize(src);
2383 CvMat* mask = cvCreateMat(size.height, size.width, CVg8UC1);
2384 cvCmpS(src, 0, mask, CVgCMPgLT); /* find negative elements */
2385 cvPow(src, dst, 1./3);
2386 cvSubRS(dst, cvScalarAll(0), dst, mask); /* negate the results of negative inputs */
2387 cvReleaseMat(&mask);
2388 \end{lstlisting}
2389
2390 For some values of \texttt{power}, such as integer values, 0.5, and -0.5, specialized faster algorithms are used.
2391
2392 \ifC
2393 \cvCPyFunc{Ptr?D}
2394 Return pointer to a particular array element.
2395
2396 \begin{lstlisting}
2397 uchar* cvPtr1D(const CvArr* arr, int idx0, int* type=NULL);
2398 uchar* cvPtr2D(const CvArr* arr, int idx0, int idx1, int* type=NULL);
2399 uchar* cvPtr3D(const CvArr* arr, int idx0, int idx1, int idx2, int* type=NULL);
2400 uchar* cvPtrND(const CvArr* arr, int* idx, int* type=NULL, int createNode=1, unsigned* precalcHashval=NULL);
2401 \end{lstlisting}
2402
2403 \begin{description}
2404 \cvarg{arr}{Input array}
2405 \cvarg{idx0}{The first zero-based component of the element index}
2406 \cvarg{idx1}{The second zero-based component of the element index}
2407 \cvarg{idx2}{The third zero-based component of the element index}
2408 \cvarg{idx}{Array of the element indices}
2409 \cvarg{type}{Optional output parameter: type of matrix elements}
2410 \cvarg{createNode}{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.}
2411 \cvarg{precalcHashval}{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)}
2412 \end{description}
2413
2414 The functions return a pointer to a specific array element. Number of array dimension should match to the number of indices passed to the function except for \texttt{cvPtr1D} function that can be used for sequential access to 1D, 2D or nD dense arrays.
2415
2416 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.
2417
2418 All these as well as other functions accessing array elements (\cvCPyCross{Get}, \cvCPyCross{GetReal}, 
2419 \cvCPyCross{Set}, \cvCPyCross{SetReal}) raise an error in case if the element index is out of range.
2420
2421 \fi
2422
2423 \cvCPyFunc{RNG}
2424 Initializes a random number generator state.
2425
2426 \cvdefC{CvRNG cvRNG(int64 seed=-1);}
2427 \cvdefPy{RNG(seed=-1LL)-> CvRNG}
2428
2429 \begin{description}
2430 \cvarg{seed}{64-bit value used to initiate a random sequence}
2431 \end{description}
2432
2433 The function initializes a random number generator
2434 and returns the state. The pointer to the state can be then passed to the
2435 \cvCPyCross{RandInt}, \cvCPyCross{RandReal} and \cvCPyCross{RandArr} functions. In the
2436 current implementation a multiply-with-carry generator is used.
2437
2438 \cvCPyFunc{RandArr}
2439 Fills an array with random numbers and updates the RNG state.
2440
2441 \cvdefC{void cvRandArr(\par CvRNG* rng,\par CvArr* arr,\par int distType,\par CvScalar param1,\par CvScalar param2);}
2442 \cvdefPy{RandArr(rng,arr,distType,param1,param2)-> None}
2443
2444 \begin{description}
2445 \cvarg{rng}{RNG state initialized by \cvCPyCross{RNG}}
2446 \cvarg{arr}{The destination array}
2447 \cvarg{distType}{Distribution type
2448 \begin{description}
2449 \cvarg{CV\_RAND\_UNI}{uniform distribution}
2450 \cvarg{CV\_RAND\_NORMAL}{normal or Gaussian distribution}
2451 \end{description}}
2452 \cvarg{param1}{The first parameter of the distribution. In the case of a uniform distribution it is the inclusive lower boundary of the random numbers range. In the case of a normal distribution it is the mean value of the random numbers.}
2453 \cvarg{param2}{The second parameter of the distribution. In the case of a uniform distribution it is the exclusive upper boundary of the random numbers range. In the case of a normal distribution it is the standard deviation of the random numbers.}
2454 \end{description}
2455
2456 The function fills the destination array with uniformly
2457 or normally distributed random numbers.
2458
2459 \ifC
2460 In the example below, the function
2461 is used to add a few normally distributed floating-point numbers to
2462 random locations within a 2d array.
2463
2464 \begin{lstlisting}
2465 /* let noisy_screen be the floating-point 2d array that is to be "crapped" */
2466 CvRNG rng_state = cvRNG(0xffffffff);
2467 int i, pointCount = 1000;
2468 /* allocate the array of coordinates of points */
2469 CvMat* locations = cvCreateMat(pointCount, 1, CV_32SC2);
2470 /* arr of random point values */
2471 CvMat* values = cvCreateMat(pointCount, 1, CV_32FC1);
2472 CvSize size = cvGetSize(noisy_screen);
2473
2474 /* initialize the locations */
2475 cvRandArr(&rng_state, locations, CV_RAND_UNI, cvScalar(0,0,0,0), 
2476            cvScalar(size.width,size.height,0,0));
2477
2478 /* generate values */
2479 cvRandArr(&rng_state, values, CV_RAND_NORMAL,
2480            cvRealScalar(100), // average intensity
2481            cvRealScalar(30) // deviation of the intensity
2482           );
2483
2484 /* set the points */
2485 for(i = 0; i < pointCount; i++ )
2486 {
2487     CvPoint pt = *(CvPoint*)cvPtr1D(locations, i, 0);
2488     float value = *(float*)cvPtr1D(values, i, 0);
2489     *((float*)cvPtr2D(noisy_screen, pt.y, pt.x, 0 )) += value;
2490 }
2491
2492 /* not to forget to release the temporary arrays */
2493 cvReleaseMat(&locations);
2494 cvReleaseMat(&values);
2495
2496 /* RNG state does not need to be deallocated */
2497 \end{lstlisting}
2498 \fi
2499
2500 \cvCPyFunc{RandInt}
2501 Returns a 32-bit unsigned integer and updates RNG.
2502
2503 \cvdefC{unsigned cvRandInt(CvRNG* rng);}
2504 \cvdefPy{RandInt(rng)-> unsigned}
2505
2506 \begin{description}
2507 \cvarg{rng}{RNG state initialized by \texttt{RandInit} and, optionally, customized by \texttt{RandSetRange} (though, the latter function does not affect the discussed function outcome)}
2508 \end{description}
2509
2510 The function returns a uniformly-distributed random
2511 32-bit unsigned integer and updates the RNG state. It is similar to the rand()
2512 function from the C runtime library, but it always generates a 32-bit number
2513 whereas rand() returns a number in between 0 and \texttt{RAND\_MAX}
2514 which is $2^{16}$ or $2^{32}$, depending on the platform.
2515
2516 The function is useful for generating scalar random numbers, such as
2517 points, patch sizes, table indices, etc., where integer numbers of a certain
2518 range can be generated using a modulo operation and floating-point numbers
2519 can be generated by scaling from 0 to 1 or any other specific range.
2520
2521 \ifC
2522 Here is the example from the previous function discussion rewritten using
2523 \cvCPyCross{RandInt}:
2524
2525 \begin{lstlisting}
2526 /* the input and the task is the same as in the previous sample. */
2527 CvRNG rnggstate = cvRNG(0xffffffff);
2528 int i, pointCount = 1000;
2529 /* ... - no arrays are allocated here */
2530 CvSize size = cvGetSize(noisygscreen);
2531 /* make a buffer for normally distributed numbers to reduce call overhead */
2532 #define bufferSize 16
2533 float normalValueBuffer[bufferSize];
2534 CvMat normalValueMat = cvMat(bufferSize, 1, CVg32F, normalValueBuffer);
2535 int valuesLeft = 0;
2536
2537 for(i = 0; i < pointCount; i++ )
2538 {
2539     CvPoint pt;
2540     /* generate random point */
2541     pt.x = cvRandInt(&rnggstate ) % size.width;
2542     pt.y = cvRandInt(&rnggstate ) % size.height;
2543
2544     if(valuesLeft <= 0 )
2545     {
2546         /* fulfill the buffer with normally distributed numbers 
2547            if the buffer is empty */
2548         cvRandArr(&rnggstate, &normalValueMat, CV\_RAND\_NORMAL, 
2549                    cvRealScalar(100), cvRealScalar(30));
2550         valuesLeft = bufferSize;
2551     }
2552     *((float*)cvPtr2D(noisygscreen, pt.y, pt.x, 0 ) = 
2553                                 normalValueBuffer[--valuesLeft];
2554 }
2555
2556 /* there is no need to deallocate normalValueMat because we have
2557 both the matrix header and the data on stack. It is a common and efficient
2558 practice of working with small, fixed-size matrices */
2559 \end{lstlisting}
2560 \fi
2561
2562 \cvCPyFunc{RandReal}
2563 Returns a floating-point random number and updates RNG.
2564
2565 \cvdefC{double cvRandReal(CvRNG* rng);}
2566 \cvdefPy{RandReal(rng)-> double}
2567
2568 \begin{description}
2569 \cvarg{rng}{RNG state initialized by \cvCPyCross{RNG}}
2570 \end{description}
2571
2572
2573 The function returns a uniformly-distributed random floating-point number between 0 and 1 (1 is not included).
2574
2575 \cvCPyFunc{Reduce}
2576 Reduces a matrix to a vector.
2577
2578 \cvdefC{void cvReduce(const CvArr* src, CvArr* dst, int dim = -1, int op=CV\_REDUCE\_SUM);}
2579 \cvdefPy{Reduce(src,dst,dim=-1,op=CV\_REDUCE\_SUM)-> None}
2580
2581 \begin{description}
2582 \cvarg{src}{The input matrix.}
2583 \cvarg{dst}{The output single-row/single-column vector that accumulates somehow all the matrix rows/columns.}
2584 \cvarg{dim}{The dimension index along which the matrix is reduced. 0 means that the matrix is reduced to a single row, 1 means that the matrix is reduced to a single column and -1 means that the dimension is chosen automatically by analysing the dst size.}
2585 \cvarg{op}{The reduction operation. It can take of the following values:
2586 \begin{description}
2587 \cvarg{CV\_REDUCE\_SUM}{The output is the sum of all of the matrix's rows/columns.}
2588 \cvarg{CV\_REDUCE\_AVG}{The output is the mean vector of all of the matrix's rows/columns.}
2589 \cvarg{CV\_REDUCE\_MAX}{The output is the maximum (column/row-wise) of all of the matrix's rows/columns.}
2590 \cvarg{CV\_REDUCE\_MIN}{The output is the minimum (column/row-wise) of all of the matrix's rows/columns.}
2591 \end{description}}
2592 \end{description}
2593
2594 The function reduces matrix to a vector by treating the matrix rows/columns as a set of 1D vectors and performing the specified operation on the vectors until a single row/column is obtained. For example, the function can be used to compute horizontal and vertical projections of an raster image. In the case of \texttt{CV\_REDUCE\_SUM} and \texttt{CV\_REDUCE\_AVG} the output may have a larger element bit-depth to preserve accuracy. And multi-channel arrays are also supported in these two reduction modes. 
2595
2596 \ifC
2597 \cvCPyFunc{ReleaseData}
2598 Releases array data.
2599
2600 \cvdefC{void cvReleaseData(CvArr* arr);}
2601
2602 \begin{description}
2603 \cvarg{arr}{Array header}
2604 \end{description}
2605
2606 The function releases the array data. In the case of \cross{CvMat} or \cross{CvMatND} it simply calls cvDecRefData(), that is the function can not deallocate external data. See also the note to \cvCPyCross{CreateData}.
2607
2608 \cvCPyFunc{ReleaseImage}
2609 Deallocates the image header and the image data.
2610
2611 \cvdefC{void cvReleaseImage(IplImage** image);}
2612
2613 \begin{description}
2614 \cvarg{image}{Double pointer to the image header}
2615 \end{description}
2616
2617 This call is a shortened form of
2618
2619 \begin{lstlisting}
2620 if(*image )
2621 {
2622     cvReleaseData(*image);
2623     cvReleaseImageHeader(image);
2624 }
2625 \end{lstlisting}
2626
2627
2628 \cvCPyFunc{ReleaseImageHeader}
2629 Deallocates an image header.
2630
2631 \cvdefC{void cvReleaseImageHeader(IplImage** image);}
2632
2633 \begin{description}
2634 \cvarg{image}{Double pointer to the image header}
2635 \end{description}
2636
2637 This call is an analogue of
2638 \begin{lstlisting}
2639 if(image )
2640 {
2641     iplDeallocate(*image, IPL_IMAGE_HEADER | IPL_IMAGE_ROI);
2642     *image = 0;
2643 }
2644 \end{lstlisting}
2645 but it does not use IPL functions by default (see the \texttt{CV\_TURN\_ON\_IPL\_COMPATIBILITY} macro).
2646
2647
2648 \cvCPyFunc{ReleaseMat}
2649 Deallocates a matrix.
2650
2651 \cvdefC{void cvReleaseMat(CvMat** mat);}
2652
2653 \begin{description}
2654 \cvarg{mat}{Double pointer to the matrix}
2655 \end{description}
2656
2657
2658 The function decrements the matrix data reference counter and deallocates matrix header. If the data reference counter is 0, it also deallocates the data.
2659
2660 \begin{lstlisting}
2661 if(*mat )
2662     cvDecRefData(*mat);
2663 cvFree((void**)mat);
2664 \end{lstlisting}
2665
2666
2667 \cvCPyFunc{ReleaseMatND}
2668 Deallocates a multi-dimensional array.
2669
2670 \cvdefC{void cvReleaseMatND(CvMatND** mat);}
2671
2672 \begin{description}
2673 \cvarg{mat}{Double pointer to the array}
2674 \end{description}
2675
2676 The function decrements the array data reference counter and releases the array header. If the reference counter reaches 0, it also deallocates the data.
2677
2678 \begin{lstlisting}
2679 if(*mat )
2680     cvDecRefData(*mat);
2681 cvFree((void**)mat);
2682 \end{lstlisting}
2683
2684 \cvCPyFunc{ReleaseSparseMat}
2685 Deallocates sparse array.
2686
2687 \cvdefC{void cvReleaseSparseMat(CvSparseMat** mat);}
2688
2689 \begin{description}
2690 \cvarg{mat}{Double pointer to the array}
2691 \end{description}
2692
2693 The function releases the sparse array and clears the array pointer upon exit.
2694
2695 \fi
2696
2697 \cvCPyFunc{Repeat}
2698 Fill the destination array with repeated copies of the source array.
2699
2700 \cvdefC{void cvRepeat(const CvArr* src, CvArr* dst);}
2701 \cvdefPy{Repeat(src,dst)-> None}
2702
2703 \begin{description}
2704 \cvarg{src}{Source array, image or matrix}
2705 \cvarg{dst}{Destination array, image or matrix}
2706 \end{description}
2707
2708 The function fills the destination array with repeated copies of the source array:
2709
2710 \begin{lstlisting}
2711 dst(i,j)=src(i mod rows(src), j mod cols(src))
2712 \end{lstlisting}
2713
2714 So the destination array may be as larger as well as smaller than the source array.
2715
2716 \cvCPyFunc{ResetImageROI}
2717 Resets the image ROI to include the entire image and releases the ROI structure.
2718
2719 \cvdefC{void cvResetImageROI(IplImage* image);}
2720 \cvdefPy{ResetImageROI(image)-> None}
2721
2722 \begin{description}
2723 \cvarg{image}{A pointer to the image header}
2724 \end{description}
2725
2726 This produces a similar result to the following, but in addition it releases the ROI structure.
2727
2728 \begin{lstlisting}
2729 cvSetImageROI(image, cvRect(0, 0, image->width, image->height ));
2730 cvSetImageCOI(image, 0);
2731 \end{lstlisting}
2732
2733
2734 \cvCPyFunc{Reshape}
2735 Changes shape of matrix/image without copying data.
2736
2737 \cvdefC{CvMat* cvReshape(const CvArr* arr, CvMat* header, int newCn, int newRows=0);}
2738 \cvdefPy{Reshape(arr, newCn, newRows=0) -> cvmat}
2739
2740 \begin{description}
2741 \cvarg{arr}{Input array}
2742 \ifC
2743 \cvarg{header}{Output header to be filled}
2744 \fi
2745 \cvarg{newCn}{New number of channels. 'newCn = 0' means that the number of channels remains unchanged.}
2746 \cvarg{newRows}{New number of rows. 'newRows = 0' means that the number of rows remains unchanged unless it needs to be changed according to \texttt{newCn} value.}
2747 \end{description}
2748
2749 The function initializes the CvMat header so that it points to the same data as the original array but has a different shape - different number of channels, different number of rows, or both.
2750
2751 \ifC
2752 The following example code creates one image buffer and two image headers, the first is for a 320x240x3 image and the second is for a 960x240x1 image:
2753
2754 \begin{lstlisting}
2755 IplImage* color_img = cvCreateImage(cvSize(320,240), IPL_DEPTH_8U, 3);
2756 CvMat gray_mat_hdr;
2757 IplImage gray_img_hdr, *gray_img;
2758 cvReshape(color_img, &gray_mat_hdr, 1);
2759 gray_img = cvGetImage(&gray_mat_hdr, &gray_img_hdr);
2760 \end{lstlisting}
2761
2762 And the next example converts a 3x3 matrix to a single 1x9 vector:
2763
2764 \begin{lstlisting}
2765 CvMat* mat = cvCreateMat(3, 3, CV_32F);
2766 CvMat row_header, *row;
2767 row = cvReshape(mat, &row_header, 0, 1);
2768 \end{lstlisting}
2769 \fi
2770
2771 \cvCPyFunc{ReshapeMatND}
2772 Changes the shape of a multi-dimensional array without copying the data.
2773
2774 \cvdefC{CvArr* cvReshapeMatND(const CvArr* arr,
2775                        int sizeofHeader, CvArr* header,
2776                        int newCn, int newDims, int* newSizes);}
2777 \cvdefPy{ReshapeMatND(arr, newCn, newDims) -> cvmat}
2778
2779 \ifC
2780 \begin{lstlisting}
2781 #define cvReshapeND(arr, header, newCn, newDims, newSizes )   \
2782       cvReshapeMatND((arr), sizeof(*(header)), (header),         \
2783                       (newCn), (newDims), (newSizes))
2784 \end{lstlisting}
2785 \fi
2786
2787 \begin{description}
2788 \cvarg{arr}{Input array}
2789 \ifC
2790 \cvarg{sizeofHeader}{Size of output header to distinguish between IplImage, CvMat and CvMatND output headers}
2791 \cvarg{header}{Output header to be filled}
2792 \cvarg{newCn}{New number of channels. $\texttt{newCn} = 0$ means that the number of channels remains unchanged.}
2793 \cvarg{newDims}{New number of dimensions. $\texttt{newDims} = 0$ means that the number of dimensions remains the same.}
2794 \cvarg{newSizes}{Array of new dimension sizes. Only $\texttt{newDims}-1$ values are used, because the total number of elements must remain the same.
2795 Thus, if $\texttt{newDims} = 1$, \texttt{newSizes} array is not used.}
2796 \else
2797 \cvarg{newDims}{List of new dimensions.}
2798 \fi
2799 \end{description}
2800
2801 The function is an advanced version of \cvCPyCross{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.
2802
2803 \ifC
2804 Below are the two samples from the \cvCPyCross{Reshape} description rewritten using \cvCPyCross{ReshapeMatND}:
2805
2806 \begin{lstlisting}
2807
2808 IplImage* color_img = cvCreateImage(cvSize(320,240), IPL_DEPTH_8U, 3);
2809 IplImage gray_img_hdr, *gray_img;
2810 gray_img = (IplImage*)cvReshapeND(color_img, &gray_img_hdr, 1, 0, 0);
2811
2812 ...
2813
2814 /* second example is modified to convert 2x2x2 array to 8x1 vector */
2815 int size[] = { 2, 2, 2 };
2816 CvMatND* mat = cvCreateMatND(3, size, CV_32F);
2817 CvMat row_header, *row;
2818 row = (CvMat*)cvReshapeND(mat, &row_header, 0, 1, 0);
2819
2820 \end{lstlisting}
2821 \fi
2822
2823 \ifC
2824 \cvfunc{cvRound, cvFloor, cvCeil}\label{cvRound}
2825
2826 Converts a floating-point number to an integer.
2827
2828 \cvdefC{
2829 int cvRound(double value);
2830 int cvFloor(double value);
2831 int cvCeil(double value);
2832
2833 }\cvdefPy{Round, Floor, Ceil(value)-> int}
2834
2835 \begin{description}
2836 \cvarg{value}{The input floating-point value}
2837 \end{description}
2838
2839
2840 The functions convert the input floating-point number to an integer using one of the rounding
2841 modes. \texttt{Round} returns the nearest integer value to the
2842 argument. \texttt{Floor} returns the maximum integer value that is not
2843 larger than the argument. \texttt{Ceil} returns the minimum integer
2844 value that is not smaller than the argument. On some architectures the
2845 functions work much faster than the standard cast
2846 operations in C. If the absolute value of the argument is greater than
2847 $2^{31}$, the result is not determined. Special values ($\pm \infty$ , NaN)
2848 are not handled.
2849
2850 \else
2851
2852 \cvfunc{Round}
2853
2854 Converts a floating-point number to the nearest integer value.
2855
2856 \cvdefPy{Round(value) -> int}
2857
2858 \begin{description}
2859 \cvarg{value}{The input floating-point value}
2860 \end{description}
2861
2862 On some architectures this function is much faster than the standard cast
2863 operations. If the absolute value of the argument is greater than
2864 $2^{31}$, the result is not determined. Special values ($\pm \infty$ , NaN)
2865 are not handled.
2866
2867 \cvfunc{Floor}
2868
2869 Converts a floating-point number to the nearest integer value that is not larger than the argument.
2870
2871 \cvdefPy{Floor(value) -> int}
2872
2873 \begin{description}
2874 \cvarg{value}{The input floating-point value}
2875 \end{description}
2876
2877 On some architectures this function is much faster than the standard cast
2878 operations. If the absolute value of the argument is greater than
2879 $2^{31}$, the result is not determined. Special values ($\pm \infty$ , NaN)
2880 are not handled.
2881
2882 \cvfunc{Ceil}
2883
2884 Converts a floating-point number to the nearest integer value that is not smaller than the argument.
2885
2886 \cvdefPy{Ceil(value) -> int}
2887
2888 \begin{description}
2889 \cvarg{value}{The input floating-point value}
2890 \end{description}
2891
2892 On some architectures this function is much faster than the standard cast
2893 operations. If the absolute value of the argument is greater than
2894 $2^{31}$, the result is not determined. Special values ($\pm \infty$ , NaN)
2895 are not handled.
2896
2897 \fi
2898
2899
2900 \cvCPyFunc{ScaleAdd}
2901 Calculates the sum of a scaled array and another array.
2902
2903 \cvdefC{void cvScaleAdd(const CvArr* src1, CvScalar scale, const CvArr* src2, CvArr* dst);}
2904 \cvdefPy{ScaleAdd(src1,scale,src2,dst)-> None}
2905
2906 \begin{description}
2907 \cvarg{src1}{The first source array}
2908 \cvarg{scale}{Scale factor for the first array}
2909 \cvarg{src2}{The second source array}
2910 \cvarg{dst}{The destination array}
2911 \end{description}
2912
2913 \begin{lstlisting}
2914 #define cvMulAddS cvScaleAdd
2915 \end{lstlisting}
2916
2917 The function calculates the sum of a scaled array and another array:
2918
2919 \[
2920 \texttt{dst}(I)=\texttt{scale} \, \texttt{src1}(I) + \texttt{src2}(I)
2921 \]
2922
2923 All array parameters should have the same type and the same size.
2924
2925 \cvCPyFunc{Set}
2926 Sets every element of an array to a given value.
2927
2928 \cvdefC{void cvSet(CvArr* arr, CvScalar value, const CvArr* mask=NULL);}
2929 \cvdefPy{Set(arr,value,mask=NULL)-> None}
2930
2931 \begin{description}
2932 \cvarg{arr}{The destination array}
2933 \cvarg{value}{Fill value}
2934 \cvarg{mask}{Operation mask, 8-bit single channel array; specifies elements of the destination array to be changed}
2935 \end{description}
2936
2937
2938 The function copies the scalar \texttt{value} to every selected element of the destination array:
2939
2940 \[
2941 \texttt{arr}(I)=\texttt{value} \quad \text{if} \quad \texttt{mask}(I) \ne 0
2942 \]
2943
2944 If array \texttt{arr} is of \texttt{IplImage} type, then is ROI used, but COI must not be set.
2945
2946 \ifC % {
2947 \cvCPyFunc{Set?D}
2948 Change the particular array element.
2949
2950 \begin{lstlisting}
2951 void cvSet1D(CvArr* arr, int idx0, CvScalar value);
2952 void cvSet2D(CvArr* arr, int idx0, int idx1, CvScalar value);
2953 void cvSet3D(CvArr* arr, int idx0, int idx1, int idx2, CvScalar value);
2954 void cvSetND(CvArr* arr, int* idx, CvScalar value);
2955 \end{lstlisting}
2956
2957 \begin{description}
2958 \cvarg{arr}{Input array}
2959 \cvarg{idx0}{The first zero-based component of the element index}
2960 \cvarg{idx1}{The second zero-based component of the element index}
2961 \cvarg{idx2}{The third zero-based component of the element index}
2962 \cvarg{idx}{Array of the element indices}
2963 \cvarg{value}{The assigned value}
2964 \end{description}
2965
2966 The functions assign the new value to a particular array element. In the case of a sparse array the functions create the node if it does not exist yet.
2967
2968 \else % }{
2969
2970 \cvCPyFunc{Set1D}
2971 Set a specific array element.
2972
2973 \cvdefPy{ Set1D(arr, idx, value) -> None }
2974
2975 \begin{description}
2976 \cvarg{arr}{Input array}
2977 \cvarg{idx}{Zero-based element index}
2978 \cvarg{value}{The value to assign to the element}
2979 \end{description}
2980
2981 Sets a specific array element.  Array must have dimension 1.
2982
2983 \cvCPyFunc{Set2D}
2984 Set a specific array element.
2985
2986 \cvdefPy{ Set2D(arr, idx0, idx1, value) -> None }
2987
2988 \begin{description}
2989 \cvarg{arr}{Input array}
2990 \cvarg{idx0}{Zero-based element row index}
2991 \cvarg{idx1}{Zero-based element column index}
2992 \cvarg{value}{The value to assign to the element}
2993 \end{description}
2994
2995 Sets a specific array element.  Array must have dimension 2.
2996
2997 \cvCPyFunc{Set3D}
2998 Set a specific array element.
2999
3000 \cvdefPy{ Set3D(arr, idx0, idx1, idx2, value) -> None }
3001
3002 \begin{description}
3003 \cvarg{arr}{Input array}
3004 \cvarg{idx0}{Zero-based element index}
3005 \cvarg{idx1}{Zero-based element index}
3006 \cvarg{idx2}{Zero-based element index}
3007 \cvarg{value}{The value to assign to the element}
3008 \end{description}
3009
3010 Sets a specific array element.  Array must have dimension 3.
3011
3012 \cvCPyFunc{SetND}
3013 Set a specific array element.
3014
3015 \cvdefPy{ SetND(arr, indices, value) -> None }
3016
3017 \begin{description}
3018 \cvarg{arr}{Input array}
3019 \cvarg{indices}{List of zero-based element indices}
3020 \cvarg{value}{The value to assign to the element}
3021 \end{description}
3022
3023 Sets a specific array element.  The length of array indices must be the same as the dimension of the array.
3024 \fi % }
3025
3026 \cvCPyFunc{SetData}
3027 Assigns user data to the array header.
3028
3029 \cvdefC{void cvSetData(CvArr* arr, void* data, int step);}
3030 \cvdefPy{SetData(arr, data, step)-> None}
3031
3032 \begin{description}
3033 \cvarg{arr}{Array header}
3034 \cvarg{data}{User data}
3035 \cvarg{step}{Full row length in bytes}
3036 \end{description}
3037
3038 The function assigns user data to the array header. Header should be initialized before using \texttt{cvCreate*Header}, \texttt{cvInit*Header} or \cvCPyCross{Mat} (in the case of matrix) function.
3039
3040 \cvCPyFunc{SetIdentity}
3041 Initializes a scaled identity matrix.
3042
3043 \cvdefC{void cvSetIdentity(CvArr* mat, CvScalar value=cvRealScalar(1));}
3044 \cvdefPy{SetIdentity(mat,value=1)-> None}
3045
3046 \begin{description}
3047 \cvarg{mat}{The matrix to initialize (not necesserily square)}
3048 \cvarg{value}{The value to assign to the diagonal elements}
3049 \end{description}
3050
3051 The function initializes a scaled identity matrix:
3052
3053 \[
3054 \texttt{arr}(i,j)=\fork{\texttt{value}}{ if $i=j$}{0}{otherwise}
3055 \]
3056
3057 \cvCPyFunc{SetImageCOI}
3058 Sets the channel of interest in an IplImage.
3059
3060 \cvdefC{void cvSetImageCOI(\par IplImage* image,\par int coi);}
3061 \cvdefPy{SetImageCOI(image, coi)-> None}
3062
3063 \begin{description}
3064 \cvarg{image}{A pointer to the image header}
3065 \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.}
3066 \end{description}
3067
3068 If the ROI is set to \texttt{NULL} and the coi is \textit{not} 0,
3069 the ROI is allocated. Most OpenCV functions do \textit{not} support
3070 the COI setting, so to process an individual image/matrix channel one
3071 may copy (via \cvCPyCross{Copy} or \cvCPyCross{Split}) the channel to a separate
3072 image/matrix, process it and then copy the result back (via \cvCPyCross{Copy}
3073 or \cvCPyCross{Merge}) if needed.
3074
3075 \cvCPyFunc{SetImageROI}
3076 Sets an image Region Of Interest (ROI) for a given rectangle.
3077
3078 \cvdefC{void cvSetImageROI(\par IplImage* image,\par CvRect rect);}
3079 \cvdefPy{SetImageROI(image, rect)-> None}
3080
3081 \begin{description}
3082 \cvarg{image}{A pointer to the image header}
3083 \cvarg{rect}{The ROI rectangle}
3084 \end{description}
3085
3086 If the original image ROI was \texttt{NULL} and the \texttt{rect} is not the whole image, the ROI structure is allocated.
3087
3088 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.
3089
3090 \if % {
3091 \cvCPyFunc{SetReal?D}
3092 Change a specific array element.
3093
3094 \begin{lstlisting}
3095 void cvSetReal1D(CvArr* arr, int idx0, double value);
3096 void cvSetReal2D(CvArr* arr, int idx0, int idx1, double value);
3097 void cvSetReal3D(CvArr* arr, int idx0, int idx1, int idx2, double value);
3098 void cvSetRealND(CvArr* arr, int* idx, double value);
3099 \end{lstlisting}
3100
3101 \begin{description}
3102 \cvarg{arr}{Input array}
3103 \cvarg{idx0}{The first zero-based component of the element index}
3104 \cvarg{idx1}{The second zero-based component of the element index}
3105 \cvarg{idx2}{The third zero-based component of the element index}
3106 \cvarg{idx}{Array of the element indices}
3107 \cvarg{value}{The assigned value}
3108 \end{description}
3109
3110 The functions assign a new value to a specific
3111 element of a single-channel array. If the array has multiple channels,
3112 a runtime error is raised. Note that the \cvCPyCross{Set*D} function can be used
3113 safely for both single-channel and multiple-channel arrays, though they
3114 are a bit slower.
3115
3116 In the case of a sparse array the functions create the node if it does not yet exist.
3117
3118 \else % }{
3119
3120 \cvCPyFunc{SetReal1D}
3121 Set a specific array element.
3122
3123 \cvdefPy{ SetReal1D(arr, idx, value) -> None }
3124
3125 \begin{description}
3126 \cvarg{arr}{Input array}
3127 \cvarg{idx}{Zero-based element index}
3128 \cvarg{value}{The value to assign to the element}
3129 \end{description}
3130
3131 Sets a specific array element.  Array must have dimension 1.
3132
3133 \cvCPyFunc{SetReal2D}
3134 Set a specific array element.
3135
3136 \cvdefPy{ SetReal2D(arr, idx0, idx1, value) -> None }
3137
3138 \begin{description}
3139 \cvarg{arr}{Input array}
3140 \cvarg{idx0}{Zero-based element row index}
3141 \cvarg{idx1}{Zero-based element column index}
3142 \cvarg{value}{The value to assign to the element}
3143 \end{description}
3144
3145 Sets a specific array element.  Array must have dimension 2.
3146
3147 \cvCPyFunc{SetReal3D}
3148 Set a specific array element.
3149
3150 \cvdefPy{ SetReal3D(arr, idx0, idx1, idx2, value) -> None }
3151
3152 \begin{description}
3153 \cvarg{arr}{Input array}
3154 \cvarg{idx0}{Zero-based element index}
3155 \cvarg{idx1}{Zero-based element index}
3156 \cvarg{idx2}{Zero-based element index}
3157 \cvarg{value}{The value to assign to the element}
3158 \end{description}
3159
3160 Sets a specific array element.  Array must have dimension 3.
3161
3162 \cvCPyFunc{SetRealND}
3163 Set a specific array element.
3164
3165 \cvdefPy{ SetRealND(arr, indices, value) -> None }
3166
3167 \begin{description}
3168 \cvarg{arr}{Input array}
3169 \cvarg{indices}{List of zero-based element indices}
3170 \cvarg{value}{The value to assign to the element}
3171 \end{description}
3172
3173 Sets a specific array element.  The length of array indices must be the same as the dimension of the array.
3174 \fi % }
3175
3176 \cvCPyFunc{SetZero}
3177 Clears the array.
3178
3179 \cvdefC{void cvSetZero(CvArr* arr);}
3180 \cvdefPy{SetZero(arr)-> None}
3181
3182 \ifC
3183 \begin{lstlisting}
3184 #define cvZero cvSetZero
3185 \end{lstlisting}
3186 \fi
3187
3188 \begin{description}
3189 \cvarg{arr}{Array to be cleared}
3190 \end{description}
3191
3192 The function clears the array. In the case of dense arrays (CvMat, CvMatND or IplImage), cvZero(array) is equivalent to cvSet(array,cvScalarAll(0),0).
3193 In the case of sparse arrays all the elements are removed.
3194
3195 \cvCPyFunc{Solve}
3196 Solves a linear system or least-squares problem.
3197
3198 \cvdefC{int cvSolve(const CvArr* src1, const CvArr* src2, CvArr* dst, int method=CV\_LU);}
3199 \cvdefPy{Solve(A,B,X,method=CV\_LU)-> None}
3200
3201 \begin{description}
3202 \cvarg{A}{The source matrix}
3203 \cvarg{B}{The right-hand part of the linear system}
3204 \cvarg{X}{The output solution}
3205 \cvarg{method}{The solution (matrix inversion) method
3206 \begin{description}
3207  \cvarg{CV\_LU}{Gaussian elimination with optimal pivot element chosen}
3208  \cvarg{CV\_SVD}{Singular value decomposition (SVD) method}
3209  \cvarg{CV\_SVD\_SYM}{SVD method for a symmetric positively-defined matrix.}
3210 \end{description}}
3211 \end{description}
3212
3213 The function solves a linear system or least-squares problem (the latter is possible with SVD methods):
3214
3215 \[
3216 \texttt{dst} = argmin_X||\texttt{src1} \, \texttt{X} - \texttt{src2}||
3217 \]
3218
3219 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.
3220
3221 \cvCPyFunc{SolveCubic}
3222 Finds the real roots of a cubic equation.
3223
3224 \cvdefC{void cvSolveCubic(const CvArr* coeffs, CvArr* roots);}
3225 \cvdefPy{SolveCubic(coeffs,roots)-> None}
3226
3227 \begin{description}
3228 \cvarg{coeffs}{The equation coefficients, an array of 3 or 4 elements}
3229 \cvarg{roots}{The output array of real roots which should have 3 elements}
3230 \end{description}
3231
3232 The function finds the real roots of a cubic equation:
3233
3234 If coeffs is a 4-element vector:
3235
3236 \[
3237 \texttt{coeffs}[0] x^3 + \texttt{coeffs}[1] x^2 + \texttt{coeffs}[2] x + \texttt{coeffs}[3] = 0
3238 \]
3239
3240 or if coeffs is 3-element vector:
3241
3242 \[
3243 x^3 + \texttt{coeffs}[0] x^2 + \texttt{coeffs}[1] x + \texttt{coeffs}[2] = 0
3244 \]
3245
3246 The function returns the number of real roots found. The roots are
3247 stored to \texttt{root} array, which is padded with zeros if there is
3248 only one root.
3249
3250 \cvCPyFunc{Split}
3251 Divides multi-channel array into several single-channel arrays or extracts a single channel from the array.
3252
3253 \cvdefC{void cvSplit(const CvArr* src, CvArr* dst0, CvArr* dst1,
3254               CvArr* dst2, CvArr* dst3);}
3255 \cvdefPy{Split(src,dst0,dst1,dst2,dst3)-> None}
3256
3257 \begin{lstlisting}
3258 #define cvCvtPixToPlane cvSplit
3259 \end{lstlisting}
3260
3261 \begin{description}
3262 \cvarg{src}{Source array}
3263 \cvarg{dst0}{Destination channel 0}
3264 \cvarg{dst1}{Destination channel 1}
3265 \cvarg{dst2}{Destination channel 2}
3266 \cvarg{dst3}{Destination channel 3}
3267 \end{description}
3268
3269 The function divides a multi-channel array into separate
3270 single-channel arrays. Two modes are available for the operation. If the
3271 source array has N channels then if the first N destination channels
3272 are not NULL, they all are extracted from the source array;
3273 if only a single destination channel of the first N is not NULL, this
3274 particular channel is extracted; otherwise an error is raised. The rest
3275 of the destination channels (beyond the first N) must always be NULL. For
3276 IplImage \cvCPyCross{Copy} with COI set can be also used to extract a single
3277 channel from the image.
3278
3279
3280 \cvCPyFunc{Sqrt}
3281 Calculates the square root.
3282
3283 \cvdefC{float cvSqrt(float value);}
3284 \cvdefPy{Sqrt(value)-> float}
3285
3286 \begin{description}
3287 \cvarg{value}{The input floating-point value}
3288 \end{description}
3289
3290
3291 The function calculates the square root of the argument. If the argument is negative, the result is not determined.
3292
3293 \cvCPyFunc{Sub}
3294 Computes the per-element difference between two arrays.
3295
3296 \cvdefC{void cvSub(const CvArr* src1, const CvArr* src2, CvArr* dst, const CvArr* mask=NULL);}
3297 \cvdefPy{Sub(src1,src2,dst,mask=NULL)-> None}
3298
3299 \begin{description}
3300 \cvarg{src1}{The first source array}
3301 \cvarg{src2}{The second source array}
3302 \cvarg{dst}{The destination array}
3303 \cvarg{mask}{Operation mask, 8-bit single channel array; specifies elements of the destination array to be changed}
3304 \end{description}
3305
3306
3307 The function subtracts one array from another one:
3308
3309 \begin{lstlisting}
3310 dst(I)=src1(I)-src2(I) if mask(I)!=0
3311 \end{lstlisting}
3312
3313 All the arrays must have the same type, except the mask, and the same size (or ROI size).
3314 For types that have limited range this operation is saturating.
3315
3316 \cvCPyFunc{SubRS}
3317 Computes the difference between a scalar and an array.
3318
3319 \cvdefC{void cvSubRS(const CvArr* src, CvScalar value, CvArr* dst, const CvArr* mask=NULL);}
3320 \cvdefPy{SubRS(src,value,dst,mask=NULL)-> None}
3321
3322 \begin{description}
3323 \cvarg{src}{The first source array}
3324 \cvarg{value}{Scalar to subtract from}
3325 \cvarg{dst}{The destination array}
3326 \cvarg{mask}{Operation mask, 8-bit single channel array; specifies elements of the destination array to be changed}
3327 \end{description}
3328
3329 The function subtracts every element of source array from a scalar:
3330
3331 \begin{lstlisting}
3332 dst(I)=value-src(I) if mask(I)!=0
3333 \end{lstlisting}
3334
3335 All the arrays must have the same type, except the mask, and the same size (or ROI size).
3336 For types that have limited range this operation is saturating.
3337
3338 \cvCPyFunc{SubS}
3339 Computes the difference between an array and a scalar.
3340
3341 \cvdefC{void cvSubS(const CvArr* src, CvScalar value, CvArr* dst, const CvArr* mask=NULL);}
3342 \cvdefPy{SubS(src,value,dst,mask=NULL)-> None}
3343
3344 \begin{description}
3345 \cvarg{src}{The source array}
3346 \cvarg{value}{Subtracted scalar}
3347 \cvarg{dst}{The destination array}
3348 \cvarg{mask}{Operation mask, 8-bit single channel array; specifies elements of the destination array to be changed}
3349 \end{description}
3350
3351 The function subtracts a scalar from every element of the source array:
3352
3353 \begin{lstlisting}
3354 dst(I)=src(I)-value if mask(I)!=0
3355 \end{lstlisting}
3356
3357 All the arrays must have the same type, except the mask, and the same size (or ROI size).
3358 For types that have limited range this operation is saturating.
3359
3360
3361 \cvCPyFunc{Sum}
3362 Adds up array elements.
3363
3364 \cvdefC{CvScalar cvSum(const CvArr* arr);}
3365 \cvdefPy{Sum(arr)-> CvScalar}
3366
3367 \begin{description}
3368 \cvarg{arr}{The array}
3369 \end{description}
3370
3371
3372 The function calculates the sum \texttt{S} of array elements, independently for each channel:
3373
3374 \[ \sum_I \texttt{arr}(I)_c \]
3375
3376 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.
3377
3378
3379 \cvCPyFunc{SVBkSb}
3380 Performs singular value back substitution.
3381
3382 \cvdefC{
3383 void  cvSVBkSb(\par const CvArr* W,\par const CvArr* U,\par const CvArr* V,\par const CvArr* B,\par CvArr* X,\par int flags);}
3384 \cvdefPy{SVBkSb(W,U,V,B,X,flags)-> None}
3385
3386 \begin{description}
3387 \cvarg{W}{Matrix or vector of singular values}
3388 \cvarg{U}{Left orthogonal matrix (tranposed, perhaps)}
3389 \cvarg{V}{Right orthogonal matrix (tranposed, perhaps)}
3390 \cvarg{B}{The matrix to multiply the pseudo-inverse of the original matrix \texttt{A} by. This is an optional parameter. If it is omitted then it is assumed to be an identity matrix of an appropriate size (so that \texttt{X} will be the reconstructed pseudo-inverse of \texttt{A}).}
3391 \cvarg{X}{The destination matrix: result of back substitution}
3392 \cvarg{flags}{Operation flags, should match exactly to the \texttt{flags} passed to \cvCPyCross{SVD}}
3393 \end{description}
3394
3395 The function calculates back substitution for decomposed matrix \texttt{A} (see \cvCPyCross{SVD} description) and matrix \texttt{B}:
3396
3397 \[
3398 \texttt{X} = \texttt{V} \texttt{W}^{-1} \texttt{U}^T \texttt{B}
3399 \]
3400
3401 where
3402
3403 \[
3404 W^{-1}_{(i,i)}=
3405 \fork
3406 {1/W_{(i,i)}}{if $W_{(i,i)} > \epsilon \sum_i{W_{(i,i)}}$ }
3407 {0}{otherwise}
3408 \]
3409
3410 and $\epsilon$ is a small number that depends on the matrix data type.
3411
3412 This function together with \cvCPyCross{SVD} is used inside \cvCPyCross{Invert}
3413 and \cvCPyCross{Solve}, and the possible reason to use these (svd and bksb)
3414 "low-level" function, is to avoid allocation of temporary matrices inside
3415 the high-level counterparts (inv and solve).
3416
3417 \cvCPyFunc{SVD}
3418 Performs singular value decomposition of a real floating-point matrix.
3419
3420 \cvdefC{void cvSVD(\par CvArr* A, \par CvArr* W, \par CvArr* U=NULL, \par CvArr* V=NULL, \par int flags=0);}
3421 \cvdefPy{SVD(A,W, U = None, V = None, flags=0)-> None}
3422
3423 \begin{description}
3424 \cvarg{A}{Source $\texttt{M} \times \texttt{N}$ matrix}
3425 \cvarg{W}{Resulting singular value diagonal matrix ($\texttt{M} \times \texttt{N}$ or $\min(\texttt{M}, \texttt{N})  \times \min(\texttt{M}, \texttt{N})$) or $\min(\texttt{M},\texttt{N}) \times 1$ vector of the singular values}
3426 \cvarg{U}{Optional left orthogonal matrix, $\texttt{M} \times \min(\texttt{M}, \texttt{N})$ (when \texttt{CV\_SVD\_U\_T} is not set), or $\min(\texttt{M},\texttt{N}) \times \texttt{M}$ (when \texttt{CV\_SVD\_U\_T} is set), or $\texttt{M} \times \texttt{M}$ (regardless of \texttt{CV\_SVD\_U\_T} flag).}
3427 \cvarg{V}{Optional right orthogonal matrix, $\texttt{N} \times \min(\texttt{M}, \texttt{N})$ (when \texttt{CV\_SVD\_V\_T} is not set), or $\min(\texttt{M},\texttt{N}) \times \texttt{N}$ (when \texttt{CV\_SVD\_V\_T} is set), or $\texttt{N} \times \texttt{N}$ (regardless of \texttt{CV\_SVD\_V\_T} flag).}
3428 \cvarg{flags}{Operation flags; can be 0 or a combination of the following values:
3429 \begin{description}
3430   \cvarg{CV\_SVD\_MODIFY\_A}{enables modification of matrix \texttt{A} during the operation. It speeds up the processing.}
3431   \cvarg{CV\_SVD\_U\_T}{means that the transposed matrix \texttt{U} is returned. Specifying the flag speeds up the processing.}
3432   \cvarg{CV\_SVD\_V\_T}{means that the transposed matrix \texttt{V} is returned. Specifying the flag speeds up the processing.}
3433 \end{description}}
3434 \end{description}
3435
3436 The function decomposes matrix \texttt{A} into the product of a diagonal matrix and two 
3437
3438 orthogonal matrices:
3439
3440 \[
3441 A=U \, W \, V^T
3442 \]
3443
3444 where $W$ is a diagonal matrix of singular values that can be coded as a
3445 1D vector of singular values and $U$ and $V$. All the singular values
3446 are non-negative and sorted (together with $U$ and $V$ columns)
3447 in descending order.
3448
3449 An SVD algorithm is numerically robust and its typical applications include:
3450
3451 \begin{itemize}
3452   \item accurate eigenvalue problem solution when matrix \texttt{A}
3453   is a square, symmetric, and positively defined matrix, for example, when
3454   it is a covariance matrix. $W$ in this case will be a vector/matrix
3455   of the eigenvalues, and $U = V$ will be a matrix of the eigenvectors.
3456   \item accurate solution of a poor-conditioned linear system.
3457   \item least-squares solution of an overdetermined linear system. This and the preceeding is done by using the \cvCPyCross{Solve} function with the \texttt{CV\_SVD} method.
3458   \item accurate calculation of different matrix characteristics such as the matrix rank (the number of non-zero singular values), condition number (ratio of the largest singular value to the smallest one), and determinant (absolute value of the determinant is equal to the product of singular values). 
3459 \end{itemize}
3460
3461 \cvCPyFunc{Trace}
3462 Returns the trace of a matrix.
3463
3464 \cvdefC{CvScalar cvTrace(const CvArr* mat);}
3465 \cvdefPy{Trace(mat)-> CvScalar}
3466
3467 \begin{description}
3468 \cvarg{mat}{The source matrix}
3469 \end{description}
3470
3471
3472 The function returns the sum of the diagonal elements of the matrix \texttt{src1}.
3473
3474 \[ tr(\texttt{mat}) = \sum_i \texttt{mat}(i,i) \]
3475
3476 \cvCPyFunc{Transform}
3477
3478 Performs matrix transformation of every array element.
3479
3480 \cvdefC{void cvTransform(const CvArr* src, CvArr* dst, const CvMat* transmat, const CvMat* shiftvec=NULL);}
3481 \cvdefPy{Transform(src,dst,transmat,shiftvec=NULL)-> None}
3482
3483 \begin{description}
3484 \cvarg{src}{The first source array}
3485 \cvarg{dst}{The destination array}
3486 \cvarg{transmat}{Transformation matrix}
3487 \cvarg{shiftvec}{Optional shift vector}
3488 \end{description}
3489
3490 The function performs matrix transformation of every element of array \texttt{src} and stores the results in \texttt{dst}:
3491
3492 \[
3493 dst(I) = transmat \cdot src(I) + shiftvec %  or   dst(I),,k,,=sum,,j,,(transmat(k,j)*src(I),,j,,) + shiftvec(k)
3494 \]
3495
3496 That is, every element of an \texttt{N}-channel array \texttt{src} is
3497 considered as an \texttt{N}-element vector which is transformed using
3498 a $\texttt{M} \times \texttt{N}$ matrix \texttt{transmat} and shift
3499 vector \texttt{shiftvec} into an element of \texttt{M}-channel array
3500 \texttt{dst}. There is an option to embedd \texttt{shiftvec} into
3501 \texttt{transmat}. In this case \texttt{transmat} should be a $\texttt{M}
3502 \times (N+1)$ matrix and the rightmost column is treated as the shift
3503 vector.
3504
3505 Both source and destination arrays should have the same depth and the
3506 same size or selected ROI size. \texttt{transmat} and \texttt{shiftvec}
3507 should be real floating-point matrices.
3508
3509 The function may be used for geometrical transformation of n dimensional
3510 point set, arbitrary linear color space transformation, shuffling the
3511 channels and so forth.
3512
3513 \cvCPyFunc{Transpose}
3514 Transposes a matrix.
3515
3516 \cvdefC{void cvTranspose(const CvArr* src, CvArr* dst);}
3517 \cvdefPy{Transpose(src,dst)-> None}
3518
3519 \begin{lstlisting}
3520 #define cvT cvTranspose
3521 \end{lstlisting}
3522
3523 \begin{description}
3524 \cvarg{src}{The source matrix}
3525 \cvarg{dst}{The destination matrix}
3526 \end{description}
3527
3528 The function transposes matrix \texttt{src1}:
3529
3530 \[ \texttt{dst}(i,j) = \texttt{src}(j,i) \]
3531
3532 Note that no complex conjugation is done in the case of a complex
3533 matrix. Conjugation should be done separately: look at the sample code
3534 in \cvCPyCross{XorS} for an example.
3535
3536 \cvCPyFunc{Xor}
3537 Performs per-element bit-wise "exclusive or" operation on two arrays.
3538
3539 \cvdefC{void cvXor(const CvArr* src1, const CvArr* src2, CvArr* dst, const CvArr* mask=NULL);}
3540 \cvdefPy{Xor(src1,src2,dst,mask=NULL)-> None}
3541
3542 \begin{description}
3543 \cvarg{src1}{The first source array}
3544 \cvarg{src2}{The second source array}
3545 \cvarg{dst}{The destination array}
3546 \cvarg{mask}{Operation mask, 8-bit single channel array; specifies elements of the destination array to be changed}
3547 \end{description}
3548
3549 The function calculates per-element bit-wise logical conjunction of two arrays:
3550
3551 \begin{lstlisting}
3552 dst(I)=src1(I)^src2(I) if mask(I)!=0
3553 \end{lstlisting}
3554
3555 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.
3556
3557 \cvCPyFunc{XorS}
3558 Performs per-element bit-wise "exclusive or" operation on an array and a scalar.
3559
3560 \cvdefC{void cvXorS(const CvArr* src, CvScalar value, CvArr* dst, const CvArr* mask=NULL);}
3561 \cvdefPy{XorS(src,value,dst,mask=NULL)-> None}
3562
3563 \begin{description}
3564 \cvarg{src}{The source array}
3565 \cvarg{value}{Scalar to use in the operation}
3566 \cvarg{dst}{The destination array}
3567 \cvarg{mask}{Operation mask, 8-bit single channel array; specifies elements of the destination array to be changed}
3568 \end{description}
3569
3570
3571 The function XorS calculates per-element bit-wise conjunction of an array and a scalar:
3572
3573 \begin{lstlisting}
3574 dst(I)=src(I)^value if mask(I)!=0
3575 \end{lstlisting}
3576
3577 Prior to the actual operation, the scalar is converted to the same type as that of the array(s). In the case of floating-point arrays their bit representations are used for the operation. All the arrays must have the same type, except the mask, and the same size
3578
3579 The following sample demonstrates how to conjugate complex vector by switching the most-significant bit of imaging part:
3580
3581 \begin{lstlisting}
3582
3583 float a[] = { 1, 0, 0, 1, -1, 0, 0, -1 }; /* 1, j, -1, -j */
3584 CvMat A = cvMat(4, 1, CV\_32FC2, &a);
3585 int i, negMask = 0x80000000;
3586 cvXorS(&A, cvScalar(0, *(float*)&negMask, 0, 0 ), &A, 0);
3587 for(i = 0; i < 4; i++ )
3588     printf("(%.1f, %.1f) ", a[i*2], a[i*2+1]);
3589
3590 \end{lstlisting}
3591
3592 The code should print:
3593
3594 \begin{lstlisting}
3595 (1.0,0.0) (0.0,-1.0) (-1.0,0.0) (0.0,1.0)
3596 \end{lstlisting}
3597
3598 \cvCPyFunc{mGet}
3599 Returns the particular element of single-channel floating-point matrix.
3600
3601 \cvdefC{double cvmGet(const CvMat* mat, int row, int col);}
3602 \cvdefPy{mGet(mat,row,col)-> double}
3603
3604 \begin{description}
3605 \cvarg{mat}{Input matrix}
3606 \cvarg{row}{The zero-based index of row}
3607 \cvarg{col}{The zero-based index of column}
3608 \end{description}
3609
3610 The function is a fast replacement for \cvCPyCross{GetReal2D}
3611 in the case of single-channel floating-point matrices. It is faster because
3612 it is inline, it does fewer checks for array type and array element type,
3613 and it checks for the row and column ranges only in debug mode.
3614
3615 \cvCPyFunc{mSet}
3616 Returns a specific element of a single-channel floating-point matrix.
3617
3618 \cvdefC{void cvmSet(CvMat* mat, int row, int col, double value);}
3619 \cvdefPy{mSet(mat,row,col,value)-> None}
3620
3621 \begin{description}
3622 \cvarg{mat}{The matrix}
3623 \cvarg{row}{The zero-based index of row}
3624 \cvarg{col}{The zero-based index of column}
3625 \cvarg{value}{The new value of the matrix element}
3626 \end{description}
3627
3628
3629 The function is a fast replacement for \cvCPyCross{SetReal2D}
3630 in the case of single-channel floating-point matrices. It is faster because
3631 it is inline, it does fewer checks for array type and array element type, 
3632 and it checks for the row and column ranges only in debug mode.
3633
3634 \fi
3635
3636 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3637 %                                                                              %
3638 %                                  C++ API                                     % 
3639 %                                                                              %
3640 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3641
3642 \ifCpp
3643
3644 \cvCppFunc{abs}
3645 Computes absolute value of each matrix element
3646
3647 \cvdefCpp{MatExpr<...> abs(const Mat\& src);\newline
3648 MatExpr<...> abs(const MatExpr<...>\& src);}
3649
3650 \begin{description}
3651 \cvarg{src}{matrix or matrix expression}
3652 \end{description}
3653
3654 \texttt{abs} is a meta-function that is expanded to one of \cvCppCross{absdiff} forms:
3655
3656 \begin{itemize}
3657     \item \texttt{C = abs(A-B)} is equivalent to \texttt{absdiff(A, B, C)} and
3658     \item \texttt{C = abs(A)} is equivalent to \texttt{absdiff(A, Scalar::all(0), C)}.
3659     \item \texttt{C = Mat\_<Vec<uchar,\emph{n}> >(abs(A*$\alpha$ + $\beta$))} is equivalent to \texttt{convertScaleAbs(A, C, alpha, beta)}
3660 \end{itemize}
3661
3662 The output matrix will have the same size and the same type as the input one
3663 (except for the last case, where \texttt{C} will be \texttt{depth=CV\_8U}).
3664
3665 See also: \cross{Matrix Expressions}, \cvCppCross{absdiff}, \hyperref[cppfunc.saturatecast]{saturate\_cast}
3666
3667 \cvCppFunc{absdiff}
3668 Computes per-element absolute difference between 2 arrays or between array and a scalar.
3669
3670 \cvdefCpp{void absdiff(const Mat\& src1, const Mat\& src2, Mat\& dst);\newline
3671 void absdiff(const Mat\& src1, const Scalar\& sc, Mat\& dst);\newline
3672 void absdiff(const MatND\& src1, const MatND\& src2, MatND\& dst);\newline
3673 void absdiff(const MatND\& src1, const Scalar\& sc, MatND\& dst);}
3674
3675 \begin{description}
3676 \cvarg{src1}{The first input array}
3677 \cvarg{src2}{The second input array; Must be the same size and same type as \texttt{src1}}
3678 \cvarg{sc}{Scalar; the second input parameter}
3679 \cvarg{dst}{The destination array; it will have the same size and same type as \texttt{src1}; see \texttt{Mat::create}}
3680 \end{description}
3681
3682 The functions \texttt{absdiff} compute:
3683 \begin{itemize}
3684     \item absolute difference between two arrays
3685     \[\texttt{dst}(I) = \texttt{saturate}(|\texttt{src1}(I) - \texttt{src2}(I)|)\]
3686     \item or absolute difference between array and a scalar:
3687     \[\texttt{dst}(I) = \texttt{saturate}(|\texttt{src1}(I) - \texttt{sc}|)\]
3688 \end{itemize}
3689 where \texttt{I} is multi-dimensional index of array elements.
3690 in the case of multi-channel arrays each channel is processed independently.
3691
3692 See also: \cvCppCross{abs}, \hyperref[cppfunc.saturatecast]{saturate\_cast}
3693
3694 \cvCppFunc{add}
3695 Computes the per-element sum of two arrays or an array and a scalar.
3696
3697 \cvdefCpp{void add(const Mat\& src1, const Mat\& src2, Mat\& dst);\newline
3698 void add(const Mat\& src1, const Mat\& src2, \par Mat\& dst, const Mat\& mask);\newline
3699 void add(const Mat\& src1, const Scalar\& sc, \par Mat\& dst, const Mat\& mask=Mat());\newline
3700 void add(const MatND\& src1, const MatND\& src2, MatND\& dst);\newline
3701 void add(const MatND\& src1, const MatND\& src2, \par MatND\& dst, const MatND\& mask);\newline
3702 void add(const MatND\& src1, const Scalar\& sc, \par MatND\& dst, const MatND\& mask=MatND());}
3703
3704 \begin{description}
3705 \cvarg{src1}{The first source array}
3706 \cvarg{src2}{The second source array. It must have the same size and same type as \texttt{src1}}
3707 \cvarg{sc}{Scalar; the second input parameter}
3708 \cvarg{dst}{The destination array; it will have the same size and same type as \texttt{src1}; see \texttt{Mat::create}}
3709 \cvarg{mask}{The optional operation mask, 8-bit single channel array;
3710              specifies elements of the destination array to be changed}
3711 \end{description}
3712
3713 The functions \texttt{add} compute:
3714 \begin{itemize}
3715     \item the sum of two arrays:
3716     \[\texttt{dst}(I) = \texttt{saturate}(\texttt{src1}(I) + \texttt{src2}(I))\quad\texttt{if mask}(I)\ne0\]
3717     \item or the sum of array and a scalar:
3718     \[\texttt{dst}(I) = \texttt{saturate}(\texttt{src1}(I) + \texttt{sc})\quad\texttt{if mask}(I)\ne0\]
3719 \end{itemize}
3720 where \texttt{I} is multi-dimensional index of array elements.
3721
3722 The first function in the above list can be replaced with matrix expressions:
3723 \begin{lstlisting}
3724 dst = src1 + src2;
3725 dst += src1; // equivalent to add(dst, src1, dst);
3726 \end{lstlisting}
3727
3728 in the case of multi-channel arrays each channel is processed independently.
3729
3730 See also: \cvCppCross{subtract}, \cvCppCross{addWeighted}, \cvCppCross{scaleAdd}, \cvCppCross{convertScale},
3731 \cross{Matrix Expressions}, \hyperref[cppfunc.saturatecast]{saturate\_cast}.
3732
3733 \cvCppFunc{addWeighted}
3734 Computes the weighted sum of two arrays.
3735
3736 \cvdefCpp{void addWeighted(const Mat\& src1, double alpha, const Mat\& src2,\par
3737                  double beta, double gamma, Mat\& dst);\newline
3738 void addWeighted(const MatND\& src1, double alpha, const MatND\& src2,\par
3739                  double beta, double gamma, MatND\& dst);
3740 }
3741
3742 \begin{description}
3743 \cvarg{src1}{The first source array}
3744 \cvarg{alpha}{Weight for the first array elements}
3745 \cvarg{src2}{The second source array; must have the same size and same type as \texttt{src1}}
3746 \cvarg{beta}{Weight for the second array elements}
3747 \cvarg{dst}{The destination array; it will have the same size and same type as \texttt{src1}}
3748 \cvarg{gamma}{Scalar, added to each sum}
3749 \end{description}
3750
3751 The functions \texttt{addWeighted} calculate the weighted sum of two arrays as follows:
3752 \[\texttt{dst}(I)=\texttt{saturate}(\texttt{src1}(I)*\texttt{alpha} + \texttt{src2}(I)*\texttt{beta} + \texttt{gamma})\]
3753 where \texttt{I} is multi-dimensional index of array elements.
3754
3755 The first function can be replaced with a matrix expression:
3756 \begin{lstlisting}
3757 dst = src1*alpha + src2*beta + gamma;
3758 \end{lstlisting}
3759
3760 In the case of multi-channel arrays each channel is processed independently.
3761
3762 See also: \cvCppCross{add}, \cvCppCross{subtract}, \cvCppCross{scaleAdd}, \cvCppCross{convertScale},
3763 \cross{Matrix Expressions}, \hyperref[cppfunc.saturatecast]{saturate\_cast}.
3764
3765 \subsection{cv::bitwise\_and}\label{cppfunc.bitwise.and}
3766 Calculates per-element bit-wise conjunction of two arrays and an array and a scalar.
3767
3768 \cvdefCpp{void bitwise\_and(const Mat\& src1, const Mat\& src2,\par Mat\& dst, const Mat\& mask=Mat());\newline
3769 void bitwise\_and(const Mat\& src1, const Scalar\& sc,\par  Mat\& dst, const Mat\& mask=Mat());\newline
3770 void bitwise\_and(const MatND\& src1, const MatND\& src2,\par  MatND\& dst, const MatND\& mask=MatND());\newline
3771 void bitwise\_and(const MatND\& src1, const Scalar\& sc,\par  MatND\& dst, const MatND\& mask=MatND());}
3772
3773 \begin{description}
3774 \cvarg{src1}{The first source array}
3775 \cvarg{src2}{The second source array. It must have the same size and same type as \texttt{src1}}
3776 \cvarg{sc}{Scalar; the second input parameter}
3777 \cvarg{dst}{The destination array; it will have the same size and same type as \texttt{src1}; see \texttt{Mat::create}}
3778 \cvarg{mask}{The optional operation mask, 8-bit single channel array;
3779              specifies elements of the destination array to be changed}
3780 \end{description}
3781
3782 The functions \texttt{bitwise\_and} compute per-element bit-wise logical conjunction:
3783 \begin{itemize}
3784     \item of two arrays
3785     \[\texttt{dst}(I) = \texttt{src1}(I) \wedge \texttt{src2}(I)\quad\texttt{if mask}(I)\ne0\]
3786     \item or array and a scalar:
3787     \[\texttt{dst}(I) = \texttt{src1}(I) \wedge \texttt{sc}\quad\texttt{if mask}(I)\ne0\]
3788 \end{itemize}
3789
3790 In the case of floating-point arrays their machine-specific bit representations (usually IEEE754-compliant) are used for the operation, and in the case of multi-channel arrays each channel is processed independently.
3791
3792 See also: \hyperref[cppfunc.bitwise.and]{bitwise\_and}, \hyperref[cppfunc.bitwise.not]{bitwise\_not}, \hyperref[cppfunc.bitwise.xor]{bitwise\_xor}
3793
3794 \subsection{cv::bitwise\_not}\label{cppfunc.bitwise.not}
3795 Inverts every bit of array
3796
3797 \cvdefCpp{void bitwise\_not(const Mat\& src, Mat\& dst);\newline
3798 void bitwise\_not(const MatND\& src, MatND\& dst);}
3799 \begin{description}
3800 \cvarg{src1}{The source array}
3801 \cvarg{dst}{The destination array; it is reallocated to be of the same size and
3802             the same type as \texttt{src}; see \texttt{Mat::create}}
3803 \cvarg{mask}{The optional operation mask, 8-bit single channel array;
3804              specifies elements of the destination array to be changed}
3805 \end{description}
3806
3807 The functions \texttt{bitwise\_not} compute per-element bit-wise inversion of the source array:
3808 \[\texttt{dst}(I) = \neg\texttt{src}(I)\]
3809
3810 In the case of floating-point source array its machine-specific bit representation (usually IEEE754-compliant) is used for the operation. in the case of multi-channel arrays each channel is processed independently.
3811
3812 See also: \hyperref[cppfunc.bitwise.and]{bitwise\_and}, \hyperref[cppfunc.bitwise.or]{bitwise\_or}, \hyperref[cppfunc.bitwise.xor]{bitwise\_xor}
3813
3814
3815 \subsection{cv::bitwise\_or}\label{cppfunc.bitwise.or}
3816 Calculates per-element bit-wise disjunction of two arrays and an array and a scalar.
3817
3818 \cvdefCpp{void bitwise\_or(const Mat\& src1, const Mat\& src2,\par Mat\& dst, const Mat\& mask=Mat());\newline
3819 void bitwise\_or(const Mat\& src1, const Scalar\& sc,\par  Mat\& dst, const Mat\& mask=Mat());\newline
3820 void bitwise\_or(const MatND\& src1, const MatND\& src2,\par  MatND\& dst, const MatND\& mask=MatND());\newline
3821 void bitwise\_or(const MatND\& src1, const Scalar\& sc,\par  MatND\& dst, const MatND\& mask=MatND());}
3822 \begin{description}
3823 \cvarg{src1}{The first source array}
3824 \cvarg{src2}{The second source array. It must have the same size and same type as \texttt{src1}}
3825 \cvarg{sc}{Scalar; the second input parameter}
3826 \cvarg{dst}{The destination array; it is reallocated to be of the same size and
3827             the same type as \texttt{src1}; see \texttt{Mat::create}}
3828 \cvarg{mask}{The optional operation mask, 8-bit single channel array;
3829              specifies elements of the destination array to be changed}
3830 \end{description}
3831
3832 The functions \texttt{bitwise\_or} compute per-element bit-wise logical disjunction
3833 \begin{itemize}
3834     \item of two arrays
3835     \[\texttt{dst}(I) = \texttt{src1}(I) \vee \texttt{src2}(I)\quad\texttt{if mask}(I)\ne0\]
3836     \item or array and a scalar:
3837     \[\texttt{dst}(I) = \texttt{src1}(I) \vee \texttt{sc}\quad\texttt{if mask}(I)\ne0\]
3838 \end{itemize}
3839
3840 In the case of floating-point arrays their machine-specific bit representations (usually IEEE754-compliant) are used for the operation. in the case of multi-channel arrays each channel is processed independently.
3841
3842 See also: \hyperref[cppfunc.bitwise.and]{bitwise\_and}, \hyperref[cppfunc.bitwise.not]{bitwise\_not}, \hyperref[cppfunc.bitwise.or]{bitwise\_or}
3843
3844 \subsection{cv::bitwise\_xor}\label{cppfunc.bitwise.xor}
3845 Calculates per-element bit-wise "exclusive or" operation on two arrays and an array and a scalar.
3846
3847 \cvdefCpp{void bitwise\_xor(const Mat\& src1, const Mat\& src2,\par Mat\& dst, const Mat\& mask=Mat());\newline
3848 void bitwise\_xor(const Mat\& src1, const Scalar\& sc,\par  Mat\& dst, const Mat\& mask=Mat());\newline
3849 void bitwise\_xor(const MatND\& src1, const MatND\& src2,\par  MatND\& dst, const MatND\& mask=MatND());\newline
3850 void bitwise\_xor(const MatND\& src1, const Scalar\& sc,\par  MatND\& dst, const MatND\& mask=MatND());}
3851 \begin{description}
3852 \cvarg{src1}{The first source array}
3853 \cvarg{src2}{The second source array. It must have the same size and same type as \texttt{src1}}
3854 \cvarg{sc}{Scalar; the second input parameter}
3855 \cvarg{dst}{The destination array; it is reallocated to be of the same size and
3856             the same type as \texttt{src1}; see \texttt{Mat::create}}
3857 \cvarg{mask}{The optional operation mask, 8-bit single channel array;
3858              specifies elements of the destination array to be changed}
3859 \end{description}
3860
3861 The functions \texttt{bitwise\_xor} compute per-element bit-wise logical "exclusive or" operation
3862
3863 \begin{itemize}
3864     \item on two arrays
3865     \[\texttt{dst}(I) = \texttt{src1}(I) \oplus \texttt{src2}(I)\quad\texttt{if mask}(I)\ne0\]
3866     \item or array and a scalar:
3867     \[\texttt{dst}(I) = \texttt{src1}(I) \oplus \texttt{sc}\quad\texttt{if mask}(I)\ne0\]
3868 \end{itemize}
3869
3870 In the case of floating-point arrays their machine-specific bit representations (usually IEEE754-compliant) are used for the operation. in the case of multi-channel arrays each channel is processed independently.
3871
3872 See also: \hyperref[cppfunc.bitwise.and]{bitwise\_and}, \hyperref[cppfunc.bitwise.not]{bitwise\_not}, \hyperref[cppfunc.bitwise.or]{bitwise\_or}
3873
3874 \cvCppFunc{calcCovarMatrix}
3875 Calculates covariation matrix of a set of vectors
3876
3877 \cvdefCpp{void calcCovarMatrix( const Mat* samples, int nsamples,\par
3878                       Mat\& covar, Mat\& mean,\par
3879                       int flags, int ctype=CV\_64F);\newline
3880 void calcCovarMatrix( const Mat\& samples, Mat\& covar, Mat\& mean,\par
3881                       int flags, int ctype=CV\_64F);}
3882 \begin{description}
3883 \cvarg{samples}{The samples, stored as separate matrices, or as rows or columns of a single matrix}
3884 \cvarg{nsamples}{The number of samples when they are stored separately}
3885 \cvarg{covar}{The output covariance matrix; it will have type=\texttt{ctype} and square size}
3886 \cvarg{mean}{The input or output (depending on the flags) array - the mean (average) vector of the input vectors}
3887 \cvarg{flags}{The operation flags, a combination of the following values
3888 \begin{description}
3889 \cvarg{CV\_COVAR\_SCRAMBLED}{The output covariance matrix is calculated as:
3890 \[
3891  \texttt{scale} \cdot [ \texttt{vects} [0]- \texttt{mean} ,\texttt{vects} [1]- \texttt{mean} ,...]^T \cdot [\texttt{vects} [0]-\texttt{mean} ,\texttt{vects} [1]-\texttt{mean} ,...] 
3892 \],
3893 that is, the covariance matrix will be $\texttt{nsamples} \times \texttt{nsamples}$.
3894 Such an unusual covariance matrix is used for fast PCA
3895 of a set of very large vectors (see, for example, the EigenFaces technique
3896 for face recognition). Eigenvalues of this "scrambled" matrix will
3897 match the eigenvalues of the true covariance matrix and the "true"
3898 eigenvectors can be easily calculated from the eigenvectors of the
3899 "scrambled" covariance matrix.}
3900 \cvarg{CV\_COVAR\_NORMAL}{The output covariance matrix is calculated as:
3901 \[
3902  \texttt{scale} \cdot [ \texttt{vects} [0]- \texttt{mean} ,\texttt{vects} [1]- \texttt{mean} ,...] \cdot [\texttt{vects} [0]-\texttt{mean} ,\texttt{vects} [1]-\texttt{mean} ,...]^T 
3903 \],
3904 that is, \texttt{covar} will be a square matrix
3905 of the same size as the total number of elements in each
3906 input vector. One and only one of \texttt{CV\_COVAR\_SCRAMBLED} and
3907 \texttt{CV\_COVAR\_NORMAL} must be specified}
3908 \cvarg{CV\_COVAR\_USE\_AVG}{If the flag is specified, the function does not calculate \texttt{mean} from the input vectors, but, instead, uses the passed \texttt{mean} vector. This is useful if \texttt{mean} has been pre-computed or known a-priori, or if the covariance matrix is calculated by parts - in this case, \texttt{mean} is not a mean vector of the input sub-set of vectors, but rather the mean vector of the whole set.}
3909 \cvarg{CV\_COVAR\_SCALE}{If the flag is specified, the covariance matrix is scaled. In the "normal" mode \texttt{scale} is \texttt{1./nsamples}; in the "scrambled" mode \texttt{scale} is the reciprocal of the total number of elements in each input vector. By default (if the flag is not specified) the covariance matrix is not scaled (i.e. \texttt{scale=1}).}
3910
3911 \cvarg{CV\_COVAR\_ROWS}{[Only useful in the second variant of the function] The flag means that all the input vectors are stored as rows of the \texttt{samples} matrix. \texttt{mean} should be a single-row vector in this case.}
3912 \cvarg{CV\_COVAR\_COLS}{[Only useful in the second variant of the function] The flag means that all the input vectors are stored as columns of the \texttt{samples} matrix. \texttt{mean} should be a single-column vector in this case.}
3913
3914 \end{description}}
3915 \end{description}
3916
3917 The functions \texttt{calcCovarMatrix} calculate the covariance matrix
3918 and, optionally, the mean vector of the set of input vectors.
3919
3920 See also: \cvCppCross{PCA}, \cvCppCross{mulTransposed}, \cvCppCross{Mahalanobis}
3921
3922 \cvCppFunc{cartToPolar}
3923 Calculates the magnitude and angle of 2d vectors.
3924
3925 \cvdefCpp{void cartToPolar(const Mat\& x, const Mat\& y,\par
3926                  Mat\& magnitude, Mat\& angle,\par
3927                  bool angleInDegrees=false);}
3928 \begin{description}
3929 \cvarg{x}{The array of x-coordinates; must be single-precision or double-precision floating-point array}
3930 \cvarg{y}{The array of y-coordinates; it must have the same size and same type as \texttt{x}}
3931 \cvarg{magnitude}{The destination array of magnitudes of the same size and same type as \texttt{x}}
3932 \cvarg{angle}{The destination array of angles of the same size and same type as \texttt{x}.
3933 The angles are measured in radians $(0$ to $2 \pi )$ or in degrees (0 to 360 degrees).}
3934 \cvarg{angleInDegrees}{The flag indicating whether the angles are measured in radians, which is default mode, or in degrees}
3935 \end{description}
3936
3937 The function \texttt{cartToPolar} calculates either the magnitude, angle, or both of every 2d vector (x(I),y(I)):
3938
3939 \[
3940 \begin{array}{l}
3941 \texttt{magnitude}(I)=\sqrt{\texttt{x}(I)^2+\texttt{y}(I)^2},\\
3942 \texttt{angle}(I)=\texttt{atan2}(\texttt{y}(I), \texttt{x}(I))[\cdot180/\pi]
3943 \end{array}
3944 \]
3945
3946 The angles are calculated with $\sim\,0.3^\circ$ accuracy. For the (0,0) point, the angle is set to 0.
3947
3948 \cvCppFunc{checkRange}
3949 Checks every element of an input array for invalid values.
3950
3951 \cvdefCpp{bool checkRange(const Mat\& src, bool quiet=true, Point* pos=0,\par
3952                 double minVal=-DBL\_MAX, double maxVal=DBL\_MAX);\newline
3953 bool checkRange(const MatND\& src, bool quiet=true, int* pos=0,\par
3954                 double minVal=-DBL\_MAX, double maxVal=DBL\_MAX);}
3955 \begin{description}
3956 \cvarg{src}{The array to check}
3957 \cvarg{quiet}{The flag indicating whether the functions quietly return false when the array elements are out of range, or they throw an exception.}
3958 \cvarg{pos}{The optional output parameter, where the position of the first outlier is stored. In the second function \texttt{pos}, when not NULL, must be a pointer to array of \texttt{src.dims} elements}
3959 \cvarg{minVal}{The inclusive lower boundary of valid values range}
3960 \cvarg{maxVal}{The exclusive upper boundary of valid values range}
3961 \end{description}
3962
3963 The functions \texttt{checkRange} check that every array element is
3964 neither NaN nor $\pm \infty $. When \texttt{minVal < -DBL\_MAX} and \texttt{maxVal < DBL\_MAX}, then the functions also check that
3965 each value is between \texttt{minVal} and \texttt{maxVal}. in the case of multi-channel arrays each channel is processed independently.
3966 If some values are out of range, position of the first outlier is stored in \texttt{pos} (when $\texttt{pos}\ne0$), and then the functions either return false (when \texttt{quiet=true}) or throw an exception.
3967
3968
3969 \cvCppFunc{compare}
3970 Performs per-element comparison of two arrays or an array and scalar value.
3971
3972 \cvdefCpp{void compare(const Mat\& src1, const Mat\& src2, Mat\& dst, int cmpop);\newline
3973 void compare(const Mat\& src1, double value, \par Mat\& dst, int cmpop);\newline
3974 void compare(const MatND\& src1, const MatND\& src2, \par MatND\& dst, int cmpop);\newline
3975 void compare(const MatND\& src1, double value, \par MatND\& dst, int cmpop);}
3976 \begin{description}
3977 \cvarg{src1}{The first source array}
3978 \cvarg{src2}{The second source array; must have the same size and same type as \texttt{src1}}
3979 \cvarg{value}{The scalar value to compare each array element with}
3980 \cvarg{dst}{The destination array; will have the same size as \texttt{src1} and type=\texttt{CV\_8UC1}}
3981 \cvarg{cmpop}{The flag specifying the relation between the elements to be checked
3982 \begin{description}
3983  \cvarg{CMP\_EQ}{$\texttt{src1}(I) = \texttt{src2}(I)$ or $\texttt{src1}(I) = \texttt{value}$}
3984  \cvarg{CMP\_GT}{$\texttt{src1}(I) > \texttt{src2}(I)$ or $\texttt{src1}(I) > \texttt{value}$}
3985  \cvarg{CMP\_GE}{$\texttt{src1}(I) \geq \texttt{src2}(I)$ or $\texttt{src1}(I) \geq \texttt{value}$}
3986  \cvarg{CMP\_LT}{$\texttt{src1}(I) < \texttt{src2}(I)$ or $\texttt{src1}(I) < \texttt{value}$}
3987  \cvarg{CMP\_LE}{$\texttt{src1}(I) \leq \texttt{src2}(I)$ or $\texttt{src1}(I) \leq \texttt{value}$}
3988  \cvarg{CMP\_NE}{$\texttt{src1}(I) \ne \texttt{src2}(I)$ or $\texttt{src1}(I) \ne \texttt{value}$}
3989 \end{description}}
3990 \end{description}
3991
3992 The functions \texttt{compare} compare each element of \texttt{src1} with the corresponding element of \texttt{src2}
3993 or with real scalar \texttt{value}. When the comparison result is true, the corresponding element of destination array is set to 255, otherwise it is set to 0:
3994 \begin{itemize}
3995     \item \texttt{dst(I) = src1(I) cmpop src2(I) ? 255 : 0}
3996     \item \texttt{dst(I) = src1(I) cmpop value ? 255 : 0}
3997 \end{itemize}
3998
3999 The comparison operations can be replaced with the equivalent matrix expressions:
4000
4001 \begin{lstlisting}
4002 Mat dst1 = src1 >= src2;
4003 Mat dst2 = src1 < 8;
4004 ...
4005 \end{lstlisting}
4006
4007 See also: \cvCppCross{checkRange}, \cvCppCross{min}, \cvCppCross{max}, \cvCppCross{threshold}, \cross{Matrix Expressions}
4008
4009 \cvCppFunc{completeSymm}
4010 Copies the lower or the upper half of a square matrix to another half.
4011
4012 \cvdefCpp{void completeSymm(Mat\& mtx, bool lowerToUpper=false);}
4013 \begin{description}
4014 \cvarg{mtx}{Input-output floating-point square matrix}
4015 \cvarg{lowerToUpper}{If true, the lower half is copied to the upper half, otherwise the upper half is copied to the lower half}
4016 \end{description}
4017
4018 The function \texttt{completeSymm} copies the lower half of a square matrix to its another half; the matrix diagonal remains unchanged:
4019
4020 \begin{itemize}
4021     \item $\texttt{mtx}_{ij}=\texttt{mtx}_{ji}$ for $i > j$ if \texttt{lowerToUpper=false}
4022     \item $\texttt{mtx}_{ij}=\texttt{mtx}_{ji}$ for $i < j$ if \texttt{lowerToUpper=true}
4023 \end{itemize}
4024
4025 See also: \cvCppCross{flip}, \cvCppCross{transpose}
4026
4027 \cvCppFunc{convertScaleAbs}
4028 Scales, computes absolute values and converts the result to 8-bit.
4029
4030 \cvdefCpp{void convertScaleAbs(const Mat\& src, Mat\& dst, double alpha=1, double beta=0);}
4031 \begin{description}
4032 \cvarg{src}{The source array}
4033 \cvarg{dst}{The destination array}
4034 \cvarg{alpha}{The optional scale factor}
4035 \cvarg{beta}{The optional delta added to the scaled values}
4036 \end{description}
4037
4038 On each element of the input array the function \texttt{convertScaleAbs} performs 3 operations sequentially: scaling, taking absolute value, conversion to unsigned 8-bit type:
4039 \[\texttt{dst}(I)=\texttt{saturate\_cast<uchar>}(|\texttt{src}(I)*\texttt{alpha} + \texttt{beta}|)\]
4040
4041 in the case of multi-channel arrays the function processes each channel independently. When the output is not 8-bit, the operation can be emulated by calling \texttt{Mat::convertTo} method (or by using matrix expressions) and then by computing absolute value of the result, for example:
4042
4043 \begin{lstlisting}
4044 Mat_<float> A(30,30);
4045 randu(A, Scalar(-100), Scalar(100));
4046 Mat_<float> B = A*5 + 3;
4047 B = abs(B);
4048 // Mat_<float> B = abs(A*5+3) will also do the job,
4049 // but it will allocate a temporary matrix
4050 \end{lstlisting}
4051
4052 See also: \cvCppCross{Mat::convertTo}, \cvCppCross{abs}
4053
4054 \cvCppFunc{countNonZero}
4055 Counts non-zero array elements.
4056
4057 \cvdefCpp{int countNonZero( const Mat\& mtx );\newline
4058 int countNonZero( const MatND\& mtx );}
4059 \begin{description}
4060 \cvarg{mtx}Single-channel array
4061 \end{description}
4062
4063 The function \texttt{cvCountNonZero} returns the number of non-zero elements in mtx:
4064
4065 \[ \sum_{I:\;\texttt{mtx}(I)\ne0} 1 \]
4066
4067 See also: \cvCppCross{mean}, \cvCppCross{meanStdDev}, \cvCppCross{norm}, \cvCppCross{minMaxLoc}, \cvCppCross{calcCovarMatrix}
4068
4069 \cvCppFunc{cubeRoot}
4070 Computes cube root of the argument
4071
4072 \cvdefCpp{float cubeRoot(float val);}
4073 \begin{description}
4074 \cvarg{val}The function argument
4075 \end{description}
4076
4077 The function \texttt{cubeRoot} computes $\sqrt[3]{\texttt{val}}$.
4078 Negative arguments are handled correctly, \emph{NaN} and $\pm\infty$ are not handled.
4079 The accuracy approaches the maximum possible accuracy for single-precision data.
4080
4081 \cvCppFunc{cvarrToMat}
4082 Converts CvMat, IplImage or CvMatND to cv::Mat.
4083
4084 \cvdefCpp{Mat cvarrToMat(const CvArr* src, bool copyData=false, bool allowND=true, int coiMode=0);}
4085 \begin{description}
4086 \cvarg{src}{The source \texttt{CvMat}, \texttt{IplImage} or \texttt{CvMatND}}
4087 \cvarg{copyData}{When it is false (default value), no data is copied, only the new header is created.
4088  In this case the original array should not be deallocated while the new matrix header is used. The the parameter is true, all the data is copied, then user may deallocate the original array right after the conversion}
4089 \cvarg{allowND}{When it is true (default value), then \texttt{CvMatND} is converted to \texttt{Mat} if it's possible
4090 (e.g. then the data is contiguous). If it's not possible, or when the parameter is false, the function will report an error}
4091 \cvarg{coiMode}{The parameter specifies how the IplImage COI (when set) is handled.
4092 \begin{itemize}
4093     \item If \texttt{coiMode=0}, the function will report an error if COI is set.
4094     \item If \texttt{coiMode=1}, the function will never report an error; instead it returns the header to the whole original image and user will have to check and process COI manually, see \cvCppCross{extractImageCOI}.
4095 %    \item If \texttt{coiMode=2}, the function will extract the COI into the separate matrix. \emph{This is also done when the COI is set and }\texttt{copyData=true}}
4096 \end{itemize}}
4097 \end{description}
4098
4099 The function \texttt{cvarrToMat} converts \cross{CvMat}, \cross{IplImage} or \cross{CvMatND} header to \cvCppCross{Mat} header, and optionally duplicates the underlying data. The constructed header is returned by the function.
4100
4101 When \texttt{copyData=false}, the conversion is done really fast (in O(1) time) and the newly created matrix header will have \texttt{refcount=0}, which means that no reference counting is done for the matrix data, and user has to preserve the data until the new header is destructed. Otherwise, when \texttt{copyData=true}, the new buffer will be allocated and managed as if you created a new matrix from scratch and copy the data there. That is,
4102 \texttt{cvarrToMat(src, true) $\sim$ cvarrToMat(src, false).clone()} (assuming that COI is not set). The function provides uniform way of supporting \cross{CvArr} paradigm in the code that is migrated to use new-style data structures internally. The reverse transformation, from \cvCppCross{Mat} to \cross{CvMat} or \cross{IplImage} can be done by simple assignment:
4103
4104 \begin{lstlisting}
4105 CvMat* A = cvCreateMat(10, 10, CV_32F);
4106 cvSetIdentity(A);
4107 IplImage A1; cvGetImage(A, &A1);
4108 Mat B = cvarrToMat(A);
4109 Mat B1 = cvarrToMat(&A1);
4110 IplImage C = B;
4111 CvMat C1 = B1;
4112 // now A, A1, B, B1, C and C1 are different headers
4113 // for the same 10x10 floating-point array.
4114 // note, that you will need to use "&"
4115 // to pass C & C1 to OpenCV functions, e.g:
4116 printf("%g", cvDet(&C1));
4117 \end{lstlisting}
4118
4119 Normally, the function is used to convert an old-style 2D array (\cross{CvMat} or \cross{IplImage}) to \texttt{Mat}, however, the function can also take \cross{CvMatND} on input and create \cvCppCross{Mat} for it, if it's possible. And for \texttt{CvMatND A} it is possible if and only if \texttt{A.dim[i].size*A.dim.step[i] == A.dim.step[i-1]} for all or for all but one \texttt{i, 0 < i < A.dims}. That is, the matrix data should be continuous or it should be representable as a sequence of continuous matrices. By using this function in this way, you can process \cross{CvMatND} using arbitrary element-wise function. But for more complex operations, such as filtering functions, it will not work, and you need to convert \cross{CvMatND} to \cvCppCross{MatND} using the corresponding constructor of the latter.
4120
4121 The last parameter, \texttt{coiMode}, specifies how to react on an image with COI set: by default it's 0, and then the function reports an error when an image with COI comes in. And \texttt{coiMode=1} means that no error is signaled - user has to check COI presence and handle it manually. The modern structures, such as \cvCppCross{Mat} and \cvCppCross{MatND} do not support COI natively. To process individual channel of an new-style array, you will need either to organize loop over the array (e.g. using matrix iterators) where the channel of interest will be processed, or extract the COI using \cvCppCross{mixChannels} (for new-style arrays) or \cvCppCross{extractImageCOI} (for old-style arrays), process this individual channel and insert it back to the destination array if need (using \cvCppCross{mixChannel} or \cvCppCross{insertImageCOI}, respectively).
4122
4123 See also: \cvCppCross{cvGetImage}, \cvCppCross{cvGetMat}, \cvCppCross{cvGetMatND}, \cvCppCross{extractImageCOI}, \cvCppCross{insertImageCOI}, \cvCppCross{mixChannels}
4124
4125
4126 \cvCppFunc{dct}
4127 Performs a forward or inverse discrete cosine transform of 1D or 2D array
4128
4129 \cvdefCpp{void dct(const Mat\& src, Mat\& dst, int flags=0);}
4130 \begin{description}
4131 \cvarg{src}{The source floating-point array}
4132 \cvarg{dst}{The destination array; will have the same size and same type as \texttt{src}}
4133 \cvarg{flags}\cvarg{flags}{Transformation flags, a combination of the following values
4134 \begin{description}
4135 \cvarg{DCT\_INVERSE}{do an inverse 1D or 2D transform instead of the default forward transform.}
4136 \cvarg{DCT\_ROWS}{do a forward or inverse transform of every individual row of the input matrix. This flag allows user to transform multiple vectors simultaneously and can be used to decrease the overhead (which is sometimes several times larger than the processing itself), to do 3D and higher-dimensional transforms and so forth.}
4137 \end{description}}
4138 \end{description}
4139
4140 The function \texttt{dct} performs a forward or inverse discrete cosine transform (DCT) of a 1D or 2D floating-point array:
4141
4142 Forward Cosine transform of 1D vector of $N$ elements:
4143 \[Y = C^{(N)} \cdot X\]
4144 where
4145 \[C^{(N)}_{jk}=\sqrt{\alpha_j/N}\cos\left(\frac{\pi(2k+1)j}{2N}\right)\]
4146 and $\alpha_0=1$, $\alpha_j=2$ for $j > 0$.
4147
4148 Inverse Cosine transform of 1D vector of N elements:
4149 \[X = \left(C^{(N)}\right)^{-1} \cdot Y = \left(C^{(N)}\right)^T \cdot Y\]
4150 (since $C^{(N)}$ is orthogonal matrix, $C^{(N)} \cdot \left(C^{(N)}\right)^T = I$)
4151
4152 Forward Cosine transform of 2D $M \times N$ matrix:
4153 \[Y = C^{(N)} \cdot X \cdot \left(C^{(N)}\right)^T\]
4154
4155 Inverse Cosine transform of 2D vector of $M \times N$ elements:
4156 \[X = \left(C^{(N)}\right)^T \cdot X \cdot C^{(N)}\]
4157
4158 The function chooses the mode of operation by looking at the flags and size of the input array:
4159 \begin{itemize}
4160     \item if \texttt{(flags \& DCT\_INVERSE) == 0}, the function does forward 1D or 2D transform, otherwise it is inverse 1D or 2D transform.
4161     \item if \texttt{(flags \& DCT\_ROWS) $\ne$ 0}, the function performs 1D transform of each row.
4162     \item otherwise, if the array is a single column or a single row, the function performs 1D transform
4163     \item otherwise it performs 2D transform.
4164 \end{itemize}
4165
4166 \textbf{Important note}: currently cv::dct supports even-size arrays (2, 4, 6 ...). For data analysis and approximation you can pad the array when necessary.
4167
4168 Also, the function's performance depends very much, and not monotonically, on the array size, see \cvCppCross{getOptimalDFTSize}. In the current implementation DCT of a vector of size \texttt{N} is computed via DFT of a vector of size \texttt{N/2}, thus the optimal DCT size $\texttt{N}^*\geq\texttt{N}$ can be computed as:
4169
4170 \begin{lstlisting}
4171 size_t getOptimalDCTSize(size_t N) { return 2*getOptimalDFTSize((N+1)/2); }
4172 \end{lstlisting}
4173
4174 See also: \cvCppCross{dft}, \cvCppCross{getOptimalDFTSize}, \cvCppCross{idct}
4175
4176
4177 \cvCppFunc{dft}
4178 Performs a forward or inverse Discrete Fourier transform of 1D or 2D floating-point array.
4179
4180 \cvdefCpp{void dft(const Mat\& src, Mat\& dst, int flags=0, int nonzeroRows=0);}
4181 \begin{description}
4182 \cvarg{src}{The source array, real or complex}
4183 \cvarg{dst}{The destination array, which size and type depends on the \texttt{flags}}
4184 \cvarg{flags}{Transformation flags, a combination of the following values
4185 \begin{description}
4186 \cvarg{DFT\_INVERSE}{do an inverse 1D or 2D transform instead of the default forward transform.}
4187 \cvarg{DFT\_SCALE}{scale the result: divide it by the number of array elements. Normally, it is combined with \texttt{DFT\_INVERSE}}.
4188 \cvarg{DFT\_ROWS}{do a forward or inverse transform of every individual row of the input matrix. This flag allows the user to transform multiple vectors simultaneously and can be used to decrease the overhead (which is sometimes several times larger than the processing itself), to do 3D and higher-dimensional transforms and so forth.}
4189 \cvarg{DFT\_COMPLEX\_OUTPUT}{then the function performs forward transformation of 1D or 2D real array, the result, though being a complex array, has complex-conjugate symmetry (\emph{CCS}), see the description below. Such an array can be packed into real array of the same size as input, which is the fastest option and which is what the function does by default. However, you may wish to get the full complex array (for simpler spectrum analysis etc.). Pass the flag to tell the function to produce full-size complex output array.}
4190 \cvarg{DFT\_REAL\_OUTPUT}{then the function performs inverse transformation of 1D or 2D complex array, the result is normally a complex array of the same size. However, if the source array has conjugate-complex symmetry (for example, it is a result of forward transformation with \texttt{DFT\_COMPLEX\_OUTPUT} flag), then the output is real array. While the function itself does not check whether the input is symmetrical or not, you can pass the flag and then the function will assume the symmetry and produce the real output array. Note that when the input is packed real array and inverse transformation is executed, the function treats the input as packed complex-conjugate symmetrical array, so the output will also be real array}
4191 \end{description}}
4192 \cvarg{nonzeroRows}{When the parameter $\ne 0$, the function assumes that only the first \texttt{nonzeroRows} rows of the input array (\texttt{DFT\_INVERSE} is not set) or only the first \texttt{nonzeroRows} of the output array (\texttt{DFT\_INVERSE} is set) contain non-zeros, thus the function can handle the rest of the rows more efficiently and thus save some time. This technique is very useful for computing array cross-correlation or convolution using DFT}
4193 \end{description}
4194
4195 Forward Fourier transform of 1D vector of N elements:
4196 \[Y = F^{(N)} \cdot X,\]
4197 where $F^{(N)}_{jk}=\exp(-2\pi i j k/N)$ and $i=\sqrt{-1}$
4198
4199 Inverse Fourier transform of 1D vector of N elements:
4200 \[
4201 \begin{array}{l}
4202 X'= \left(F^{(N)}\right)^{-1} \cdot Y = \left(F^{(N)}\right)^* \cdot y \\
4203 X = (1/N) \cdot X,
4204 \end{array}
4205 \]
4206 where $F^*=\left(\textrm{Re}(F^{(N)})-\textrm{Im}(F^{(N)})\right)^T$
4207
4208 Forward Fourier transform of 2D vector of $M \times N$ elements:
4209 \[Y = F^{(M)} \cdot X \cdot F^{(N)}\]
4210
4211 Inverse Fourier transform of 2D vector of $M \times N$ elements:
4212 \[
4213 \begin{array}{l}
4214 X'= \left(F^{(M)}\right)^* \cdot Y \cdot \left(F^{(N)}\right)^*\\
4215 X = \frac{1}{M \cdot N} \cdot X'
4216 \end{array}
4217 \]
4218
4219 In the case of real (single-channel) data, the packed format called \emph{CCS} (complex-conjugate-symmetrical) that was borrowed from IPL and used to represent the result of a forward Fourier transform or input for an inverse Fourier transform:
4220
4221 \[\begin{bmatrix}
4222 Re Y_{0,0} & Re Y_{0,1} & Im Y_{0,1} & Re Y_{0,2} & Im Y_{0,2} & \cdots & Re Y_{0,N/2-1} & Im Y_{0,N/2-1} & Re Y_{0,N/2} \\
4223 Re Y_{1,0} & Re Y_{1,1} & Im Y_{1,1} & Re Y_{1,2} & Im Y_{1,2} & \cdots & Re Y_{1,N/2-1} & Im Y_{1,N/2-1} & Re Y_{1,N/2} \\
4224 Im Y_{1,0} & Re Y_{2,1} & Im Y_{2,1} & Re Y_{2,2} & Im Y_{2,2} & \cdots & Re Y_{2,N/2-1} & Im Y_{2,N/2-1} & Im Y_{1,N/2} \\
4225 \hdotsfor{9} \\
4226 Re Y_{M/2-1,0} &  Re Y_{M-3,1}  & Im Y_{M-3,1} & \hdotsfor{3} & Re Y_{M-3,N/2-1} & Im Y_{M-3,N/2-1}& Re Y_{M/2-1,N/2} \\
4227 Im Y_{M/2-1,0} &  Re Y_{M-2,1}  & Im Y_{M-2,1} & \hdotsfor{3} & Re Y_{M-2,N/2-1} & Im Y_{M-2,N/2-1}& Im Y_{M/2-1,N/2} \\
4228 Re Y_{M/2,0}  &  Re Y_{M-1,1} &  Im Y_{M-1,1} & \hdotsfor{3} & Re Y_{M-1,N/2-1} & Im Y_{M-1,N/2-1}& Re Y_{M/2,N/2}
4229 \end{bmatrix}
4230 \]
4231
4232 in the case of 1D transform of real vector, the output will look as the first row of the above matrix. 
4233
4234 So, the function chooses the operation mode depending on the flags and size of the input array:
4235 \begin{itemize}
4236     \item if \texttt{DFT\_ROWS} is set or the input array has single row or single column then the function performs 1D forward or inverse transform (of each row of a matrix when \texttt{DFT\_ROWS} is set, otherwise it will be 2D transform.
4237     \item if input array is real and \texttt{DFT\_INVERSE} is not set, the function does forward 1D or 2D transform:
4238     \begin{itemize}
4239         \item when \texttt{DFT\_COMPLEX\_OUTPUT} is set then the output will be complex matrix of the same size as input.
4240         \item otherwise the output will be a real matrix of the same size as input. in the case of 2D transform it will use the packed format as shown above; in the case of single 1D transform it will look as the first row of the above matrix; in the case of multiple 1D transforms (when using \texttt{DCT\_ROWS} flag) each row of the output matrix will look like the first row of the above matrix.
4241     \end{itemize}
4242     \item otherwise, if the input array is complex and either \texttt{DFT\_INVERSE} or \texttt{DFT\_REAL\_OUTPUT} are not set then the output will be a complex array of the same size as input and the function will perform the forward or inverse 1D or 2D transform of the whole input array or each row of the input array independently, depending on the flags \texttt{DFT\_INVERSE} and \texttt{DFT\_ROWS}.
4243     \item otherwise, i.e. when \texttt{DFT\_INVERSE} is set, the input array is real, or it is complex but \texttt{DFT\_REAL\_OUTPUT} is set, the output will be a real array of the same size as input, and the function will perform 1D or 2D inverse transformation of the whole input array or each individual row, depending on the flags \texttt{DFT\_INVERSE} and \texttt{DFT\_ROWS}.
4244 \end{itemize}
4245
4246 The scaling is done after the transformation if \texttt{DFT\_SCALE} is set.
4247
4248 Unlike \cvCppCross{dct}, the function supports arrays of arbitrary size, but only those arrays are processed efficiently, which sizes can be factorized in a product of small prime numbers (2, 3 and 5 in the current implementation). Such an efficient DFT size can be computed using \cvCppCross{getOptimalDFTSize} method.
4249
4250 Here is the sample on how to compute DFT-based convolution of two 2D real arrays:
4251 \begin{lstlisting}
4252 void convolveDFT(const Mat& A, const Mat& B, Mat& C)
4253 {
4254     // reallocate the output array if needed
4255     C.create(abs(A.rows - B.rows)+1, abs(A.cols - B.cols)+1, A.type());
4256     Size dftSize;
4257     // compute the size of DFT transform
4258     dftSize.width = getOptimalDFTSize(A.cols + B.cols - 1);
4259     dftSize.height = getOptimalDFTSize(A.rows + B.rows - 1);
4260     
4261     // allocate temporary buffers and initialize them with 0's
4262     Mat tempA(dftSize, A.type(), Scalar::all(0));
4263     Mat tempB(dftSize, B.type(), Scalar::all(0));
4264     
4265     // copy A and B to the top-left corners of tempA and tempB, respectively
4266     Mat roiA(tempA, Rect(0,0,A.cols,A.rows));
4267     A.copyTo(roiA);
4268     Mat roiB(tempB, Rect(0,0,B.cols,B.rows));
4269     B.copyTo(roiB);
4270     
4271     // now transform the padded A & B in-place;
4272     // use "nonzeroRows" hint for faster processing
4273     dft(tempA, tempA, 0, A.rows);
4274     dft(tempB, tempB, 0, B.rows);
4275     
4276     // multiply the spectrums;
4277     // the function handles packed spectrum representations well
4278     mulSpectrums(tempA, tempB, tempA);
4279     
4280     // transform the product back from the frequency domain.
4281     // Even though all the result rows will be non-zero,
4282     // we need only the first C.rows of them, and thus we
4283     // pass nonzeroRows == C.rows
4284     dft(tempA, tempA, DFT_INVERSE + DFT_SCALE, C.rows);
4285     
4286     // now copy the result back to C.
4287     tempA(Rect(0, 0, C.cols, C.rows)).copyTo(C);
4288     
4289     // all the temporary buffers will be deallocated automatically
4290 }
4291 \end{lstlisting}
4292
4293 What can be optimized in the above sample?
4294 \begin{itemize}
4295     \item since we passed $\texttt{nonzeroRows} \ne 0$ to the forward transform calls and
4296     since we copied \texttt{A}/\texttt{B} to the top-left corners of \texttt{tempA}/\texttt{tempB}, respectively,
4297     it's not necessary to clear the whole \texttt{tempA} and \texttt{tempB};
4298     it is only necessary to clear the \texttt{tempA.cols - A.cols} (\texttt{tempB.cols - B.cols})
4299     rightmost columns of the matrices.
4300     \item this DFT-based convolution does not have to be applied to the whole big arrays,
4301     especially if \texttt{B} is significantly smaller than \texttt{A} or vice versa.
4302     Instead, we can compute convolution by parts. For that we need to split the destination array
4303     \texttt{C} into multiple tiles and for each tile estimate, which parts of \texttt{A} and \texttt{B}
4304     are required to compute convolution in this tile. If the tiles in \texttt{C} are too small,
4305     the speed will decrease a lot, because of repeated work - in the ultimate case, when each tile in \texttt{C} is a single pixel,
4306     the algorithm becomes equivalent to the naive convolution algorithm.
4307     If the tiles are too big, the temporary arrays \texttt{tempA} and \texttt{tempB} become too big
4308     and there is also slowdown because of bad cache locality. So there is optimal tile size somewhere in the middle.
4309     \item if the convolution is done by parts, since different tiles in \texttt{C} can be computed in parallel, the loop can be threaded.
4310 \end{itemize}
4311
4312 All of the above improvements have been implemented in \cvCppCross{matchTemplate} and \cvCppCross{filter2D}, therefore, by using them, you can get even better performance than with the above theoretically optimal implementation (though, those two functions actually compute cross-correlation, not convolution, so you will need to "flip" the kernel or the image around the center using \cvCppCross{flip}).
4313
4314 See also: \cvCppCross{dct}, \cvCppCross{getOptimalDFTSize}, \cvCppCross{mulSpectrums}, \cvCppCross{filter2D}, \cvCppCross{matchTemplate}, \cvCppCross{flip}, \cvCppCross{cartToPolar}, \cvCppCross{magnitude}, \cvCppCross{phase}
4315
4316 \cvCppFunc{divide}
4317
4318 Performs per-element division of two arrays or a scalar by an array.
4319
4320 \cvdefCpp{void divide(const Mat\& src1, const Mat\& src2, \par Mat\& dst, double scale=1);\newline
4321 void divide(double scale, const Mat\& src2, Mat\& dst);\newline
4322 void divide(const MatND\& src1, const MatND\& src2, \par MatND\& dst, double scale=1);\newline
4323 void divide(double scale, const MatND\& src2, MatND\& dst);}
4324 \begin{description}
4325 \cvarg{src1}{The first source array}
4326 \cvarg{src2}{The second source array; should have the same size and same type as \texttt{src1}}
4327 \cvarg{scale}{Scale factor}
4328 \cvarg{dst}{The destination array; will have the same size and same type as \texttt{src2}}
4329 \end{description}
4330
4331 The functions \texttt{divide} divide one array by another:
4332 \[\texttt{dst(I) = saturate(src1(I)*scale/src2(I))} \]
4333
4334 or a scalar by array, when there is no \texttt{src1}:
4335 \[\texttt{dst(I) = saturate(scale/src2(I))} \]
4336
4337 The result will have the same type as \texttt{src1}. When \texttt{src2(I)=0}, \texttt{dst(I)=0} too.
4338
4339 See also: \cvCppCross{multiply}, \cvCppCross{add}, \cvCppCross{subtract}, \cross{Matrix Expressions}
4340
4341 \cvCppFunc{determinant}
4342
4343 Returns determinant of a square floating-point matrix.
4344
4345 \cvdefCpp{double determinant(const Mat\& mtx);}
4346 \begin{description}
4347 \cvarg{mtx}{The input matrix; must have \texttt{CV\_32FC1} or \texttt{CV\_64FC1} type and square size}
4348 \end{description}
4349
4350 The function \texttt{determinant} computes and returns determinant of the specified matrix. For small matrices (\texttt{mtx.cols=mtx.rows<=3})
4351 the direct method is used; for larger matrices the function uses LU factorization.
4352
4353 For symmetric positive-determined matrices, it is also possible to compute \cvCppCross{SVD}: $\texttt{mtx}=U \cdot W \cdot V^T$ and then calculate the determinant as a product of the diagonal elements of $W$.
4354
4355 See also: \cvCppCross{SVD}, \cvCppCross{trace}, \cvCppCross{invert}, \cvCppCross{solve}, \cross{Matrix Expressions}
4356
4357 \cvCppFunc{eigen}
4358 Computes eigenvalues and eigenvectors of a symmetric matrix.
4359
4360 \cvdefCpp{bool eigen(const Mat\& src, Mat\& eigenvalues, \par int lowindex=-1, int highindex=-1);\newline
4361 bool eigen(const Mat\& src, Mat\& eigenvalues, \par Mat\& eigenvectors, int lowindex=-1,\par
4362 int highindex=-1);}
4363 \begin{description}
4364 \cvarg{src}{The input matrix; must have \texttt{CV\_32FC1} or \texttt{CV\_64FC1} type, square size and be symmetric: $\texttt{src}^T=\texttt{src}$}
4365 \cvarg{eigenvalues}{The output vector of eigenvalues of the same type as \texttt{src}; The eigenvalues are stored in the descending order.}
4366 \cvarg{eigenvectors}{The output matrix of eigenvectors; It will have the same size and the same type as \texttt{src}; The eigenvectors are stored as subsequent matrix rows, in the same order as the corresponding eigenvalues}
4367 \cvarg{lowindex}{Optional index of largest eigenvalue/-vector to calculate.
4368 (See below.)}
4369 \cvarg{highindex}{Optional index of smallest eigenvalue/-vector to calculate.
4370 (See below.)}
4371 \end{description}
4372
4373 The functions \texttt{eigen} compute just eigenvalues, or eigenvalues and eigenvectors of symmetric matrix \texttt{src}:
4374
4375 \begin{lstlisting}
4376 src*eigenvectors(i,:)' = eigenvalues(i)*eigenvectors(i,:)' (in MATLAB notation)
4377 \end{lstlisting}
4378
4379 If either low- or highindex is supplied the other is required, too.
4380 Indexing is 0-based. Example: To calculate the largest eigenvector/-value set
4381 lowindex = highindex = 0.
4382 For legacy reasons this function always returns a square matrix the same size
4383 as the source matrix with eigenvectors and a vector the length of the source
4384 matrix with eigenvalues. The selected eigenvectors/-values are always in the
4385 first highindex - lowindex + 1 rows.
4386
4387 See also: \cvCppCross{SVD}, \cvCppCross{completeSymm}, \cvCppCross{PCA}
4388
4389 \cvCppFunc{exp}
4390 Calculates the exponent of every array element.
4391
4392 \cvdefCpp{void exp(const Mat\& src, Mat\& dst);\newline
4393 void exp(const MatND\& src, MatND\& dst);}
4394 \begin{description}
4395 \cvarg{src}{The source array}
4396 \cvarg{dst}{The destination array; will have the same size and same type as \texttt{src}}
4397 \end{description}
4398
4399 The function \texttt{exp} calculates the exponent of every element of the input array:
4400
4401 \[
4402 \texttt{dst} [I] = e^{\texttt{src}}(I)
4403 \]
4404
4405 The maximum relative error is about $7 \times 10^{-6}$ for single-precision and less than $10^{-10}$ for double-precision. Currently, the function converts denormalized values to zeros on output. Special values (NaN, $\pm \infty$) are not handled.
4406
4407 See also: \cvCppCross{log}, \cvCppCross{cartToPolar}, \cvCppCross{polarToCart}, \cvCppCross{phase}, \cvCppCross{pow}, \cvCppCross{sqrt}, \cvCppCross{magnitude}
4408
4409 \cvCppFunc{extractImageCOI}
4410
4411 Extract the selected image channel
4412
4413 \cvdefCpp{void extractImageCOI(const CvArr* src, Mat\& dst, int coi=-1);}
4414 \begin{description}
4415 \cvarg{src}{The source array. It should be a pointer to \cross{CvMat} or \cross{IplImage}}
4416 \cvarg{dst}{The destination array; will have single-channel, and the same size and the same depth as \texttt{src}}
4417 \cvarg{coi}{If the parameter is \texttt{>=0}, it specifies the channel to extract;
4418 If it is \texttt{<0}, \texttt{src} must be a pointer to \texttt{IplImage} with valid COI set - then the selected COI is extracted.}
4419 \end{description}
4420
4421 The function \texttt{extractImageCOI} is used to extract image COI from an old-style array and put the result to the new-style C++ matrix. As usual, the destination matrix is reallocated using \texttt{Mat::create} if needed.
4422
4423 To extract a channel from a new-style matrix, use \cvCppCross{mixChannels} or \cvCppCross{split}
4424
4425 See also: \cvCppCross{mixChannels}, \cvCppCross{split}, \cvCppCross{merge}, \cvCppCross{cvarrToMat}, \cvCppCross{cvSetImageCOI}, \cvCppCross{cvGetImageCOI}
4426
4427
4428 \cvCppFunc{fastAtan2}
4429 Calculates the angle of a 2D vector in degrees
4430
4431 \cvdefCpp{float fastAtan2(float y, float x);}
4432 \begin{description}
4433 \cvarg{x}{x-coordinate of the vector}
4434 \cvarg{y}{y-coordinate of the vector}
4435 \end{description}
4436
4437 The function \texttt{fastAtan2} calculates the full-range angle of an input 2D vector. The angle is 
4438 measured in degrees and varies from $0^\circ$ to $360^\circ$. The accuracy is about $0.3^\circ$.
4439
4440 \cvCppFunc{flip}
4441 Flips a 2D array around vertical, horizontal or both axes.
4442
4443 \cvdefCpp{void flip(const Mat\& src, Mat\& dst, int flipCode);}
4444 \begin{description}
4445 \cvarg{src}{The source array}
4446 \cvarg{dst}{The destination array; will have the same size and same type as \texttt{src}}
4447 \cvarg{flipCode}{Specifies how to flip the array:
4448 0 means flipping around the x-axis, positive (e.g., 1) means flipping around y-axis, and negative (e.g., -1) means flipping around both axes. See also the discussion below for the formulas.}
4449 \end{description}
4450
4451 The function \texttt{flip} flips the array in one of three different ways (row and column indices are 0-based):
4452
4453 \[
4454 \texttt{dst}_{ij} = \forkthree
4455 {\texttt{src}_{\texttt{src.rows}-i-1,j}}{if \texttt{flipCode} = 0}
4456 {\texttt{src}_{i,\texttt{src.cols}-j-1}}{if \texttt{flipCode} > 0}
4457 {\texttt{src}_{\texttt{src.rows}-i-1,\texttt{src.cols}-j-1}}{if \texttt{flipCode} < 0}
4458 \]
4459
4460 The example scenarios of function use are:
4461 \begin{itemize}
4462   \item vertical flipping of the image ($\texttt{flipCode} = 0$) to switch between top-left and bottom-left image origin, which is a typical operation in video processing in Windows.
4463   \item horizontal flipping of the image with subsequent horizontal shift and absolute difference calculation to check for a vertical-axis symmetry ($\texttt{flipCode} > 0$)
4464   \item simultaneous horizontal and vertical flipping of the image with subsequent shift and absolute difference calculation to check for a central symmetry ($\texttt{flipCode} < 0$)
4465   \item reversing the order of 1d point arrays ($\texttt{flipCode} > 0$ or $\texttt{flipCode} = 0$)
4466 \end{itemize}
4467
4468 See also: \cvCppCross{transpose}, \cvCppCross{repeat}, \cvCppCross{completeSymm}
4469
4470 \cvCppFunc{gemm}
4471 Performs generalized matrix multiplication.
4472
4473 \cvdefCpp{void gemm(const Mat\& src1, const Mat\& src2, double alpha,\par
4474           const Mat\& src3, double beta, Mat\& dst, int flags=0);}
4475 \begin{description}
4476 \cvarg{src1}{The first multiplied input matrix; should have \texttt{CV\_32FC1}, \texttt{CV\_64FC1}, \texttt{CV\_32FC2} or \texttt{CV\_64FC2} type}
4477 \cvarg{src2}{The second multiplied input matrix; should have the same type as \texttt{src1}}
4478 \cvarg{alpha}{The weight of the matrix product}
4479 \cvarg{src3}{The third optional delta matrix added to the matrix product; should have the same type as \texttt{src1} and \texttt{src2}}
4480 \cvarg{beta}{The weight of \texttt{src3}}
4481 \cvarg{dst}{The destination matrix; It will have the proper size and the same type as input matrices}
4482 \cvarg{flags}{Operation flags:
4483 \begin{description}
4484     \cvarg{GEMM\_1\_T}{transpose \texttt{src1}}
4485     \cvarg{GEMM\_2\_T}{transpose \texttt{src2}}
4486     \cvarg{GEMM\_3\_T}{transpose \texttt{src3}}
4487 \end{description}}
4488 \end{description}
4489
4490 The function performs generalized matrix multiplication and similar to the corresponding functions \texttt{*gemm} in BLAS level 3.
4491 For example, \texttt{gemm(src1, src2, alpha, src3, beta, dst, GEMM\_1\_T + GEMM\_3\_T)} corresponds to
4492 \[
4493 \texttt{dst} = \texttt{alpha} \cdot \texttt{src1} ^T \cdot \texttt{src2} + \texttt{beta} \cdot \texttt{src3} ^T
4494 \]
4495
4496 The function can be replaced with a matrix expression, e.g. the above call can be replaced with:
4497 \begin{lstlisting}
4498 dst = alpha*src1.t()*src2 + beta*src3.t();
4499 \end{lstlisting}
4500
4501 See also: \cvCppCross{mulTransposed}, \cvCppCross{transform}, \cross{Matrix Expressions}
4502
4503
4504 \cvCppFunc{getConvertElem}
4505 Returns conversion function for a single pixel
4506
4507 \cvdefCpp{ConvertData getConvertElem(int fromType, int toType);\newline
4508 ConvertScaleData getConvertScaleElem(int fromType, int toType);\newline
4509 typedef void (*ConvertData)(const void* from, void* to, int cn);\newline
4510 typedef void (*ConvertScaleData)(const void* from, void* to,\par
4511                                  int cn, double alpha, double beta);}
4512 \begin{description}
4513 \cvarg{fromType}{The source pixel type}
4514 \cvarg{toType}{The destination pixel type}
4515 \cvarg{from}{Callback parameter: pointer to the input pixel}
4516 \cvarg{to}{Callback parameter: pointer to the output pixel}
4517 \cvarg{cn}{Callback parameter: the number of channels; can be arbitrary, 1, 100, 100000, ...}
4518 \cvarg{alpha}{ConvertScaleData callback optional parameter: the scale factor}
4519 \cvarg{beta}{ConvertScaleData callback optional parameter: the delta or offset}
4520 \end{description}
4521
4522 The functions \texttt{getConvertElem} and \texttt{getConvertScaleElem} return pointers to the functions for converting individual pixels from one type to another. While the main function purpose is to convert single pixels (actually, for converting sparse matrices from one type to another), you can use them to convert the whole row of a dense matrix or the whole matrix at once, by setting \texttt{cn = matrix.cols*matrix.rows*matrix.channels()} if the matrix data is continuous.
4523
4524 See also: \cvCppCross{Mat::convertTo}, \cvCppCross{MatND::convertTo}, \cvCppCross{SparseMat::convertTo}
4525
4526
4527 \cvCppFunc{getOptimalDFTSize}
4528 Returns optimal DFT size for a given vector size.
4529
4530 \cvdefCpp{int getOptimalDFTSize(int vecsize);}
4531 \begin{description}
4532 \cvarg{vecsize}{Vector size}
4533 \end{description}
4534
4535 DFT performance is not a monotonic function of a vector size, therefore, when you compute convolution of two arrays or do a spectral analysis of array, it usually makes sense to pad the input data with zeros to get a bit larger array that can be transformed much faster than the original one.
4536 Arrays, which size is a power-of-two (2, 4, 8, 16, 32, ...) are the fastest to process, though, the arrays, which size is a product of 2's, 3's and 5's (e.g. 300 = 5*5*3*2*2), are also processed quite efficiently.
4537
4538 The function \texttt{getOptimalDFTSize} returns the minimum number \texttt{N} that is greater than or equal to \texttt{vecsize}, such that the DFT
4539 of a vector of size \texttt{N} can be computed efficiently. In the current implementation $N=2^p \times 3^q \times 5^r$, for some $p$, $q$, $r$.
4540
4541 The function returns a negative number if \texttt{vecsize} is too large (very close to \texttt{INT\_MAX}).
4542
4543 While the function cannot be used directly to estimate the optimal vector size for DCT transform (since the current DCT implementation supports only even-size vectors), it can be easily computed as \texttt{getOptimalDFTSize((vecsize+1)/2)*2}.
4544
4545 See also: \cvCppCross{dft}, \cvCppCross{dct}, \cvCppCross{idft}, \cvCppCross{idct}, \cvCppCross{mulSpectrums}
4546
4547 \cvCppFunc{idct}
4548 Computes inverse Discrete Cosine Transform of a 1D or 2D array
4549
4550 \cvdefCpp{void idct(const Mat\& src, Mat\& dst, int flags=0);}
4551 \begin{description}
4552 \cvarg{src}{The source floating-point single-channel array}
4553 \cvarg{dst}{The destination array. Will have the same size and same type as \texttt{src}}
4554 \cvarg{flags}{The operation flags.}
4555 \end{description}
4556
4557 \texttt{idct(src, dst, flags)} is equivalent to \texttt{dct(src, dst, flags | DCT\_INVERSE)}.
4558 See \cvCppCross{dct} for details.
4559
4560 See also: \cvCppCross{dct}, \cvCppCross{dft}, \cvCppCross{idft}, \cvCppCross{getOptimalDFTSize}
4561
4562
4563 \cvCppFunc{idft}
4564 Computes inverse Discrete Fourier Transform of a 1D or 2D array
4565
4566 \cvdefCpp{void idft(const Mat\& src, Mat\& dst, int flags=0, int outputRows=0);}
4567 \begin{description}
4568 \cvarg{src}{The source floating-point real or complex array}
4569 \cvarg{dst}{The destination array, which size and type depends on the \texttt{flags}}
4570 \cvarg{flags}{The operation flags. See \cvCppCross{dft}}
4571 \cvarg{nonzeroRows}{The number of \texttt{dst} rows to compute.
4572 The rest of the rows will have undefined content.
4573 See the convolution sample in \cvCppCross{dft} description}
4574 \end{description}
4575
4576 \texttt{idft(src, dst, flags)} is equivalent to \texttt{dct(src, dst, flags | DFT\_INVERSE)}.
4577 See \cvCppCross{dft} for details.
4578 Note, that none of \texttt{dft} and \texttt{idft} scale the result by default.
4579 Thus, you should pass \texttt{DFT\_SCALE} to one of \texttt{dft} or \texttt{idft}
4580 explicitly to make these transforms mutually inverse.
4581
4582 See also: \cvCppCross{dft}, \cvCppCross{dct}, \cvCppCross{idct}, \cvCppCross{mulSpectrums}, \cvCppCross{getOptimalDFTSize}
4583
4584
4585 \cvCppFunc{inRange}
4586 Checks if array elements lie between the elements of two other arrays.
4587
4588 \cvdefCpp{void inRange(const Mat\& src, const Mat\& lowerb,\par
4589              const Mat\& upperb, Mat\& dst);\newline
4590 void inRange(const Mat\& src, const Scalar\& lowerb,\par
4591              const Scalar\& upperb, Mat\& dst);\newline
4592 void inRange(const MatND\& src, const MatND\& lowerb,\par
4593              const MatND\& upperb, MatND\& dst);\newline
4594 void inRange(const MatND\& src, const Scalar\& lowerb,\par
4595              const Scalar\& upperb, MatND\& dst);}
4596 \begin{description}
4597 \cvarg{src}{The first source array}
4598 \cvarg{lowerb}{The inclusive lower boundary array of the same size and type as \texttt{src}}
4599 \cvarg{upperb}{The exclusive upper boundary array of the same size and type as \texttt{src}}
4600 \cvarg{dst}{The destination array, will have the same size as \texttt{src} and \texttt{CV\_8U} type}
4601 \end{description}
4602
4603 The functions \texttt{inRange} do the range check for every element of the input array:
4604
4605 \[
4606 \texttt{dst}(I)=\texttt{lowerb}(I)_0 \leq \texttt{src}(I)_0 < \texttt{upperb}(I)_0
4607 \]
4608
4609 for single-channel arrays,
4610
4611 \[
4612 \texttt{dst}(I)=
4613 \texttt{lowerb}(I)_0 \leq \texttt{src}(I)_0 < \texttt{upperb}(I)_0 \land
4614 \texttt{lowerb}(I)_1 \leq \texttt{src}(I)_1 < \texttt{upperb}(I)_1
4615 \]
4616
4617 for two-channel arrays and so forth.
4618 \texttt{dst}(I) is set to 255 (all \texttt{1}-bits) if \texttt{src}(I) is within the specified range and 0 otherwise.
4619
4620
4621 \cvCppFunc{invert}
4622 Finds the inverse or pseudo-inverse of a matrix
4623
4624 \cvdefCpp{double invert(const Mat\& src, Mat\& dst, int method=DECOMP\_LU);}
4625 \begin{description}
4626 \cvarg{src}{The source floating-point $M \times N$ matrix}
4627 \cvarg{dst}{The destination matrix; will have $N \times M$ size and the same type as \texttt{src}}
4628 \cvarg{flags}{The inversion method :
4629 \begin{description}
4630  \cvarg{DECOMP\_LU}{Gaussian elimination with optimal pivot element chosen}
4631  \cvarg{DECOMP\_SVD}{Singular value decomposition (SVD) method}
4632  \cvarg{DECOMP\_CHOLESKY}{Cholesky decomposion. The matrix must be symmetrical and positively defined}
4633 \end{description}}
4634 \end{description}
4635
4636 The function \texttt{invert} inverts matrix \texttt{src} and stores the result in \texttt{dst}.
4637 When the matrix \texttt{src} is singular or non-square, the function computes the pseudo-inverse matrix, i.e. the matrix \texttt{dst}, such that $\|\texttt{src} \cdot \texttt{dst} - I\|$ is minimal.
4638
4639 In the case of \texttt{DECOMP\_LU} method, the function returns the \texttt{src} determinant (\texttt{src} must be square). If it is 0, the matrix is not inverted and \texttt{dst} is filled with zeros.
4640
4641 In the case of \texttt{DECOMP\_SVD} method, the function returns the inversed condition number of \texttt{src} (the ratio of the smallest singular value to the largest singular value) and 0 if \texttt{src} is singular. The SVD method calculates a pseudo-inverse matrix if \texttt{src} is singular.
4642
4643 Similarly to \texttt{DECOMP\_LU}, the method \texttt{DECOMP\_CHOLESKY} works only with non-singular square matrices. In this case the function stores the inverted matrix in \texttt{dst} and returns non-zero, otherwise it returns 0.
4644
4645 See also: \cvCppCross{solve}, \cvCppCross{SVD}
4646
4647
4648 \cvCppFunc{log}
4649 Calculates the natural logarithm of every array element.
4650
4651 \cvdefCpp{void log(const Mat\& src, Mat\& dst);\newline
4652 void log(const MatND\& src, MatND\& dst);}
4653 \begin{description}
4654 \cvarg{src}{The source array}
4655 \cvarg{dst}{The destination array; will have the same size and same type as \texttt{src}}
4656 \end{description}
4657
4658 The function \texttt{log} calculates the natural logarithm of the absolute value of every element of the input array:
4659
4660 \[
4661 \texttt{dst}(I) = \fork
4662 {\log |\texttt{src}(I)|}{if $\texttt{src}(I) \ne 0$ }
4663 {\texttt{C}}{otherwise}
4664 \]
4665
4666 Where \texttt{C} is a large negative number (about -700 in the current implementation).
4667 The maximum relative error is about $7 \times 10^{-6}$ for single-precision input and less than $10^{-10}$ for double-precision input. Special values (NaN, $\pm \infty$) are not handled.
4668
4669 See also: \cvCppCross{exp}, \cvCppCross{cartToPolar}, \cvCppCross{polarToCart}, \cvCppCross{phase}, \cvCppCross{pow}, \cvCppCross{sqrt}, \cvCppCross{magnitude}
4670
4671
4672 \cvCppFunc{LUT}
4673 Performs a look-up table transform of an array.
4674
4675 \cvdefCpp{void LUT(const Mat\& src, const Mat\& lut, Mat\& dst);}
4676 \begin{description}
4677 \cvarg{src}{Source array of 8-bit elements}
4678 \cvarg{lut}{Look-up table of 256 elements. In the case of multi-channel source array, 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 in the source array}
4679 \cvarg{dst}{Destination array; will have the same size and the same number of channels as \texttt{src}, and the same depth as \texttt{lut}}
4680 \end{description}
4681
4682 The function \texttt{LUT} fills the destination array with values from the look-up table. Indices of the entries are taken from the source array. That is, the function processes each element of \texttt{src} as follows:
4683
4684 \[
4685 \texttt{dst}(I) \leftarrow \texttt{lut(src(I) + d)}
4686 \]
4687
4688 where
4689
4690 \[
4691 d = \fork
4692 {0}{if \texttt{src} has depth \texttt{CV\_8U}}
4693 {128}{if \texttt{src} has depth \texttt{CV\_8S}}
4694 \]
4695
4696 See also: \cvCppCross{convertScaleAbs}, \texttt{Mat::convertTo}
4697
4698 \cvCppFunc{magnitude}
4699 Calculates magnitude of 2D vectors.
4700
4701 \cvdefCpp{void magnitude(const Mat\& x, const Mat\& y, Mat\& magnitude);}
4702 \begin{description}
4703 \cvarg{x}{The floating-point array of x-coordinates of the vectors}
4704 \cvarg{y}{The floating-point array of y-coordinates of the vectors; must have the same size as \texttt{x}}
4705 \cvarg{dst}{The destination array; will have the same size and same type as \texttt{x}}
4706 \end{description}
4707
4708 The function \texttt{magnitude} calculates magnitude of 2D vectors formed from the corresponding elements of \texttt{x} and \texttt{y} arrays:
4709
4710 \[
4711 \texttt{dst}(I) = \sqrt{\texttt{x}(I)^2 + \texttt{y}(I)^2}
4712 \]
4713
4714 See also: \cvCppCross{cartToPolar}, \cvCppCross{polarToCart}, \cvCppCross{phase}, \cvCppCross{sqrt}
4715
4716
4717 \cvCppFunc{Mahalanobis}
4718 Calculates the Mahalanobis distance between two vectors.
4719
4720 \cvdefCpp{double Mahalanobis(const Mat\& vec1, const Mat\& vec2, \par const Mat\& icovar);}
4721 \begin{description}
4722 \cvarg{vec1}{The first 1D source vector}
4723 \cvarg{vec2}{The second 1D source vector}
4724 \cvarg{icovar}{The inverse covariance matrix}
4725 \end{description}
4726
4727 The function \texttt{cvMahalonobis} calculates and returns the weighted distance between two vectors:
4728
4729 \[
4730 d(\texttt{vec1},\texttt{vec2})=\sqrt{\sum_{i,j}{\texttt{icovar(i,j)}\cdot(\texttt{vec1}(I)-\texttt{vec2}(I))\cdot(\texttt{vec1(j)}-\texttt{vec2(j)})}}
4731 \]
4732
4733 The covariance matrix may be calculated using the \cvCppCross{calcCovarMatrix} function and then inverted using the \cvCppCross{invert} function (preferably using DECOMP\_SVD method, as the most accurate).
4734
4735
4736 \cvCppFunc{max}
4737 Calculates per-element maximum of two arrays or array and a scalar
4738
4739 \cvdefCpp{Mat\_Expr<...> max(const Mat\& src1, const Mat\& src2);\newline
4740 Mat\_Expr<...> max(const Mat\& src1, double value);\newline
4741 Mat\_Expr<...> max(double value, const Mat\& src1);\newline
4742 void max(const Mat\& src1, const Mat\& src2, Mat\& dst);\newline
4743 void max(const Mat\& src1, double value, Mat\& dst);\newline
4744 void max(const MatND\& src1, const MatND\& src2, MatND\& dst);\newline
4745 void max(const MatND\& src1, double value, MatND\& dst);}
4746 \begin{description}
4747 \cvarg{src1}{The first source array}
4748 \cvarg{src2}{The second source array of the same size and type as \texttt{src1}}
4749 \cvarg{value}{The real scalar value}
4750 \cvarg{dst}{The destination array; will have the same size and type as \texttt{src1}}
4751 \end{description}
4752
4753 The functions \texttt{max} compute per-element maximum of two arrays:
4754 \[\texttt{dst}(I)=\max(\texttt{src1}(I), \texttt{src2}(I))\]
4755 or array and a scalar:
4756 \[\texttt{dst}(I)=\max(\texttt{src1}(I), \texttt{value})\]
4757
4758 In the second variant, when the source array is multi-channel, each channel is compared with \texttt{value} independently.
4759
4760 The first 3 variants of the function listed above are actually a part of \cross{Matrix Expressions}, they return the expression object that can be further transformed, or assigned to a matrix, or passed to a function etc.
4761
4762 See also: \cvCppCross{min}, \cvCppCross{compare}, \cvCppCross{inRange}, \cvCppCross{minMaxLoc}, \cross{Matrix Expressions}
4763
4764 \cvCppFunc{mean}
4765 Calculates average (mean) of array elements
4766
4767 \cvdefCpp{Scalar mean(const Mat\& mtx);\newline
4768 Scalar mean(const Mat\& mtx, const Mat\& mask);\newline
4769 Scalar mean(const MatND\& mtx);\newline
4770 Scalar mean(const MatND\& mtx, const MatND\& mask);}
4771 \begin{description}
4772 \cvarg{mtx}{The source array; it should have 1 to 4 channels (so that the result can be stored in \cvCppCross{Scalar})}
4773 \cvarg{mask}{The optional operation mask}
4774 \end{description}
4775
4776 The functions \texttt{mean} compute mean value \texttt{M} of array elements, independently for each channel, and return it:
4777
4778 \[
4779 \begin{array}{l}
4780 N = \sum_{I:\;\texttt{mask}(I)\ne 0} 1\\
4781 M_c = \left(\sum_{I:\;\texttt{mask}(I)\ne 0}{\texttt{mtx}(I)_c}\right)/N
4782 \end{array}
4783 \]
4784
4785 When all the mask elements are 0's, the functions return \texttt{Scalar::all(0)}.
4786
4787 See also: \cvCppCross{countNonZero}, \cvCppCross{meanStdDev}, \cvCppCross{norm}, \cvCppCross{minMaxLoc}
4788
4789 \cvCppFunc{meanStdDev}
4790 Calculates mean and standard deviation of array elements
4791
4792 \cvdefCpp{void meanStdDev(const Mat\& mtx, Scalar\& mean, \par Scalar\& stddev, const Mat\& mask=Mat());\newline
4793 void meanStdDev(const MatND\& mtx, Scalar\& mean, \par Scalar\& stddev, const MatND\& mask=MatND());}
4794 \begin{description}
4795 \cvarg{mtx}{The source array; it should have 1 to 4 channels (so that the results can be stored in \cvCppCross{Scalar}'s)}
4796 \cvarg{mean}{The output parameter: computed mean value}
4797 \cvarg{stddev}{The output parameter: computed standard deviation}
4798 \cvarg{mask}{The optional operation mask}
4799 \end{description}
4800
4801 The functions \texttt{meanStdDev} compute the mean and the standard deviation \texttt{M} of array elements, independently for each channel, and return it via the output parameters:
4802
4803 \[
4804 \begin{array}{l}
4805 N = \sum_{I, \texttt{mask}(I) \ne 0} 1\\
4806 \texttt{mean}_c = \frac{\sum_{ I: \; \texttt{mask}(I) \ne 0} \texttt{src}(I)_c}{N}\\
4807 \texttt{stddev}_c = \sqrt{\sum_{ I: \; \texttt{mask}(I) \ne 0} \left(\texttt{src}(I)_c - \texttt{mean}_c\right)^2}
4808 \end{array}
4809 \]
4810
4811 When all the mask elements are 0's, the functions return \texttt{mean=stddev=Scalar::all(0)}.
4812 Note that the computed standard deviation is only the diagonal of the complete normalized covariance matrix. If the full matrix is needed, you can reshape the multi-channel array $M \times N$ to the single-channel array $M*N \times \texttt{mtx.channels}()$ (only possible when the matrix is continuous) and then pass the matrix to \cvCppCross{calcCovarMatrix}.
4813
4814 See also: \cvCppCross{countNonZero}, \cvCppCross{mean}, \cvCppCross{norm}, \cvCppCross{minMaxLoc}, \cvCppCross{calcCovarMatrix}
4815
4816
4817 \cvCppFunc{merge}
4818 Composes a multi-channel array from several single-channel arrays.
4819
4820 \cvdefCpp{void merge(const Mat* mv, size\_t count, Mat\& dst);\newline
4821 void merge(const vector<Mat>\& mv, Mat\& dst);\newline
4822 void merge(const MatND* mv, size\_t count, MatND\& dst);\newline
4823 void merge(const vector<MatND>\& mv, MatND\& dst);}
4824 \begin{description}
4825 \cvarg{mv}{The source array or vector of the single-channel matrices to be merged. All the matrices in \texttt{mv} must have the same size and the same type}
4826 \cvarg{count}{The number of source matrices when \texttt{mv} is a plain C array; must be greater than zero}
4827 \cvarg{dst}{The destination array; will have the same size and the same depth as \texttt{mv[0]}, the number of channels will match the number of source matrices}
4828 \end{description}
4829     
4830 The functions \texttt{merge} merge several single-channel arrays (or rather interleave their elements) to make a single multi-channel array.
4831
4832 \[\texttt{dst}(I)_c = \texttt{mv}[c](I)\]
4833
4834 The function \cvCppCross{split} does the reverse operation and if you need to merge several multi-channel images or shuffle channels in some other advanced way, use \cvCppCross{mixChannels}
4835
4836 See also: \cvCppCross{mixChannels}, \cvCppCross{split}, \cvCppCross{reshape}
4837
4838 \cvCppFunc{min}
4839 Calculates per-element minimum of two arrays or array and a scalar
4840
4841 \cvdefCpp{Mat\_Expr<...> min(const Mat\& src1, const Mat\& src2);\newline
4842 Mat\_Expr<...> min(const Mat\& src1, double value);\newline
4843 Mat\_Expr<...> min(double value, const Mat\& src1);\newline
4844 void min(const Mat\& src1, const Mat\& src2, Mat\& dst);\newline
4845 void min(const Mat\& src1, double value, Mat\& dst);\newline
4846 void min(const MatND\& src1, const MatND\& src2, MatND\& dst);\newline
4847 void min(const MatND\& src1, double value, MatND\& dst);}
4848 \begin{description}
4849 \cvarg{src1}{The first source array}
4850 \cvarg{src2}{The second source array of the same size and type as \texttt{src1}}
4851 \cvarg{value}{The real scalar value}
4852 \cvarg{dst}{The destination array; will have the same size and type as \texttt{src1}}
4853 \end{description}
4854
4855 The functions \texttt{min} compute per-element minimum of two arrays:
4856 \[\texttt{dst}(I)=\min(\texttt{src1}(I), \texttt{src2}(I))\]
4857 or array and a scalar:
4858 \[\texttt{dst}(I)=\min(\texttt{src1}(I), \texttt{value})\]
4859
4860 In the second variant, when the source array is multi-channel, each channel is compared with \texttt{value} independently.
4861
4862 The first 3 variants of the function listed above are actually a part of \cross{Matrix Expressions}, they return the expression object that can be further transformed, or assigned to a matrix, or passed to a function etc.
4863
4864 See also: \cvCppCross{max}, \cvCppCross{compare}, \cvCppCross{inRange}, \cvCppCross{minMaxLoc}, \cross{Matrix Expressions}
4865
4866 \cvCppFunc{minMaxLoc}
4867 Finds global minimum and maximum in a whole array or sub-array
4868
4869 \cvdefCpp{void minMaxLoc(const Mat\& src, double* minVal,\par
4870                double* maxVal=0, Point* minLoc=0,\par
4871                Point* maxLoc=0, const Mat\& mask=Mat());\newline
4872 void minMaxLoc(const MatND\& src, double* minVal,\par
4873                double* maxVal, int* minIdx=0, int* maxIdx=0,\par
4874                const MatND\& mask=MatND());\newline
4875 void minMaxLoc(const SparseMat\& src, double* minVal,\par
4876                double* maxVal, int* minIdx=0, int* maxIdx=0);}
4877 \begin{description}
4878 \cvarg{src}{The source single-channel array}
4879 \cvarg{minVal}{Pointer to returned minimum value; \texttt{NULL} if not required}
4880 \cvarg{maxVal}{Pointer to returned maximum value; \texttt{NULL} if not required}
4881 \cvarg{minLoc}{Pointer to returned minimum location (in 2D case); \texttt{NULL} if not required}
4882 \cvarg{maxLoc}{Pointer to returned maximum location (in 2D case); \texttt{NULL} if not required}
4883 \cvarg{minIdx}{Pointer to returned minimum location (in nD case);
4884  \texttt{NULL} if not required, otherwise must point to an array of \texttt{src.dims} elements and the coordinates of minimum element in each dimensions will be stored sequentially there.}
4885 \cvarg{maxIdx}{Pointer to returned maximum location (in nD case); \texttt{NULL} if not required}
4886 \cvarg{mask}{The optional mask used to select a sub-array}
4887 \end{description}
4888
4889 The functions \texttt{ninMaxLoc} find minimum and maximum element values
4890 and their positions. The extremums are searched across the whole array, or,
4891 if \texttt{mask} is not an empty array, in the specified array region.
4892
4893 The functions do not work with multi-channel arrays. If you need to find minimum or maximum elements across all the channels, use \cvCppCross{reshape} first to reinterpret the array as single-channel. Or you may extract the particular channel using \cvCppCross{extractImageCOI} or \cvCppCross{mixChannels} or \cvCppCross{split}.
4894
4895 in the case of a sparse matrix the minimum is found among non-zero elements only.
4896
4897 See also: \cvCppCross{max}, \cvCppCross{min}, \cvCppCross{compare}, \cvCppCross{inRange}, \cvCppCross{extractImageCOI}, \cvCppCross{mixChannels}, \cvCppCross{split}, \cvCppCross{reshape}.
4898
4899 \cvCppFunc{mixChannels}
4900 Copies specified channels from input arrays to the specified channels of output arrays
4901
4902 \cvdefCpp{void mixChannels(const Mat* srcv, int nsrc, Mat* dstv, int ndst,\par
4903                  const int* fromTo, size\_t npairs);\newline
4904 void mixChannels(const MatND* srcv, int nsrc, MatND* dstv, int ndst,\par
4905                  const int* fromTo, size\_t npairs);\newline
4906 void mixChannels(const vector<Mat>\& srcv, vector<Mat>\& dstv,\par
4907                  const int* fromTo, int npairs);\newline
4908 void mixChannels(const vector<MatND>\& srcv, vector<MatND>\& dstv,\par
4909                  const int* fromTo, int npairs);}
4910 \begin{description}
4911 \cvarg{srcv}{The input array or vector of matrices.
4912 All the matrices must have the same size and the same depth}
4913 \cvarg{nsrc}{The number of elements in \texttt{srcv}}
4914 \cvarg{dstv}{The output array or vector of matrices.
4915 All the matrices \emph{must be allocated}, their size and depth must be the same as in \texttt{srcv[0]}}
4916 \cvarg{ndst}{The number of elements in \texttt{dstv}}
4917 \cvarg{fromTo}{The array of index pairs, specifying which channels are copied and where.
4918 \texttt{fromTo[k*2]} is the 0-based index of the input channel in \texttt{srcv} and
4919 \texttt{fromTo[k*2+1]} is the index of the output channel in \texttt{dstv}. Here the continuous channel numbering is used, that is,
4920 the first input image channels are indexed from \texttt{0} to \texttt{srcv[0].channels()-1},
4921 the second input image channels are indexed from \texttt{srcv[0].channels()} to
4922 \texttt{srcv[0].channels() + srcv[1].channels()-1} etc., and the same scheme is used for the output image channels.
4923 As a special case, when \texttt{fromTo[k*2]} is negative, the corresponding output channel is filled with zero.
4924 }
4925 \texttt{npairs}{The number of pairs. In the latter case the parameter is not passed explicitly, but computed as \texttt{srcv.size()} (=\texttt{dstv.size()})}
4926 \end{description}
4927
4928 The functions \texttt{mixChannels} provide an advanced mechanism for shuffling image channels. \cvCppCross{split} and \cvCppCross{merge} and some forms of \cvCppCross{cvtColor} are partial cases of \texttt{mixChannels}.
4929
4930 As an example, this code splits a 4-channel RGBA image into a 3-channel
4931 BGR (i.e. with R and B channels swapped) and separate alpha channel image:
4932
4933 \begin{lstlisting}
4934 Mat rgba( 100, 100, CV_8UC4, Scalar(1,2,3,4) );
4935 Mat bgr( rgba.rows, rgba.cols, CV_8UC3 );
4936 Mat alpha( rgba.rows, rgba.cols, CV_8UC1 );
4937
4938 // forming array of matrices is quite efficient operations,
4939 // because the matrix data is not copied, only the headers
4940 Mat out[] = { bgr, alpha };
4941 // rgba[0] -> bgr[2], rgba[1] -> bgr[1],
4942 // rgba[2] -> bgr[0], rgba[3] -> alpha[0]
4943 int from_to[] = { 0,2,  1,1,  2,0,  3,3 };
4944 mixChannels( &rgba, 1, out, 2, from_to, 4 );
4945 \end{lstlisting}
4946
4947 Note that, unlike many other new-style C++ functions in OpenCV (see the introduction section and \cvCppCross{Mat::create}),
4948 \texttt{mixChannels} requires the destination arrays be pre-allocated before calling the function.
4949
4950 See also: \cvCppCross{split}, \cvCppCross{merge}, \cvCppCross{cvtColor} 
4951
4952
4953 \cvCppFunc{mulSpectrums}
4954 Performs per-element multiplication of two Fourier spectrums.
4955
4956 \cvdefCpp{void mulSpectrums(const Mat\& src1, const Mat\& src2, Mat\& dst,\par
4957                   int flags, bool conj=false);}
4958 \begin{description}
4959 \cvarg{src1}{The first source array}
4960 \cvarg{src2}{The second source array; must have the same size and the same type as \texttt{src1}}
4961 \cvarg{dst}{The destination array; will have the same size and the same type as \texttt{src1}}
4962 \cvarg{flags}{The same flags as passed to \cvCppCross{dft}; only the flag \texttt{DFT\_ROWS} is checked for}
4963 \cvarg{conj}{The optional flag that conjugate the second source array before the multiplication (true) or not (false)}
4964 \end{description}
4965
4966 The function \texttt{mulSpectrums} performs per-element multiplication of the two CCS-packed or complex matrices that are results of a real or complex Fourier transform.
4967
4968 The function, together with \cvCppCross{dft} and \cvCppCross{idft}, may be used to calculate convolution (pass \texttt{conj=false}) or correlation (pass \texttt{conj=false}) of two arrays rapidly. When the arrays are complex, they are simply multiplied (per-element) with optional conjugation of the second array elements. When the arrays are real, they assumed to be CCS-packed (see \cvCppCross{dft} for details).
4969
4970 \cvCppFunc{multiply}
4971 Calculates the per-element scaled product of two arrays
4972
4973 \cvdefCpp{void multiply(const Mat\& src1, const Mat\& src2, \par Mat\& dst, double scale=1);\newline
4974 void multiply(const MatND\& src1, const MatND\& src2, \par MatND\& dst, double scale=1);}
4975 \begin{description}
4976 \cvarg{src1}{The first source array}
4977 \cvarg{src2}{The second source array of the same size and the same type as \texttt{src1}}
4978 \cvarg{dst}{The destination array; will have the same size and the same type as \texttt{src1}}
4979 \cvarg{scale}{The optional scale factor}
4980 \end{description}
4981
4982 The function \texttt{multiply} calculates the per-element product of two arrays:
4983
4984 \[
4985 \texttt{dst}(I)=\texttt{saturate}(\texttt{scale} \cdot \texttt{src1}(I) \cdot \texttt{src2}(I))
4986 \]
4987
4988 There is also \cross{Matrix Expressions}-friendly variant of the first function, see \cvCppCross{Mat::mul}.
4989
4990 If you are looking for a matrix product, not per-element product, see \cvCppCross{gemm}.
4991
4992 See also: \cvCppCross{add}, \cvCppCross{substract}, \cvCppCross{divide}, \cross{Matrix Expressions}, \cvCppCross{scaleAdd}, \cvCppCross{addWeighted}, \cvCppCross{accumulate}, \cvCppCross{accumulateProduct}, \cvCppCross{accumulateSquare}, \cvCppCross{Mat::convertTo}
4993
4994 \cvCppFunc{mulTransposed}
4995 Calculates the product of a matrix and its transposition.
4996
4997 \cvdefCpp{void mulTransposed( const Mat\& src, Mat\& dst, bool aTa,\par
4998                     const Mat\& delta=Mat(),\par
4999                     double scale=1, int rtype=-1 );}
5000 \begin{description}
5001 \cvarg{src}{The source matrix}
5002 \cvarg{dst}{The destination square matrix}
5003 \cvarg{aTa}{Specifies the multiplication ordering; see the description below}
5004 \cvarg{delta}{The optional delta matrix, subtracted from \texttt{src} before the multiplication. When the matrix is empty (\texttt{delta=Mat()}), it's assumed to be zero, i.e. nothing is subtracted, otherwise if it has the same size as \texttt{src}, then it's simply subtracted, otherwise it is "repeated" (see \cvCppCross{repeat}) to cover the full \texttt{src} and then subtracted. Type of the delta matrix, when it's not empty, must be the same as the type of created destination matrix, see the \texttt{rtype} description}
5005 \cvarg{scale}{The optional scale factor for the matrix product}
5006 \cvarg{rtype}{When it's negative, the destination matrix will have the same type as \texttt{src}. Otherwise, it will have \texttt{type=CV\_MAT\_DEPTH(rtype)}, which should be either \texttt{CV\_32F} or \texttt{CV\_64F}}
5007 \end{description}
5008
5009 The function \texttt{mulTransposed} calculates the product of \texttt{src} and its transposition:
5010 \[
5011 \texttt{dst}=\texttt{scale} (\texttt{src}-\texttt{delta})^T (\texttt{src}-\texttt{delta})
5012 \]
5013 if \texttt{aTa=true}, and
5014
5015 \[
5016 \texttt{dst}=\texttt{scale} (\texttt{src}-\texttt{delta}) (\texttt{src}-\texttt{delta})^T
5017 \]
5018
5019 otherwise. The function is used to compute covariance matrix and with zero delta can be used as a faster substitute for general matrix product $A*B$ when $B=A^T$.
5020
5021 See also: \cvCppCross{calcCovarMatrix}, \cvCppCross{gemm}, \cvCppCross{repeat}, \cvCppCross{reduce}
5022
5023
5024 \cvCppFunc{norm}
5025 Calculates absolute array norm, absolute difference norm, or relative difference norm.
5026
5027 \cvdefCpp{double norm(const Mat\& src1, int normType=NORM\_L2);\newline
5028 double norm(const Mat\& src1, const Mat\& src2, int normType=NORM\_L2);\newline
5029 double norm(const Mat\& src1, int normType, const Mat\& mask);\newline
5030 double norm(const Mat\& src1, const Mat\& src2, \par int normType, const Mat\& mask);\newline
5031 double norm(const MatND\& src1, int normType=NORM\_L2, \par const MatND\& mask=MatND());\newline
5032 double norm(const MatND\& src1, const MatND\& src2,\par
5033             int normType=NORM\_L2, const MatND\& mask=MatND());\newline
5034 double norm( const SparseMat\& src, int normType );}
5035 \begin{description}
5036 \cvarg{src1}{The first source array}
5037 \cvarg{src2}{The second source array of the same size and the same type as \texttt{src1}}
5038 \cvarg{normType}{Type of the norm; see the discussion below}
5039 \cvarg{mask}{The optional operation mask}
5040 \end{description}
5041
5042 The functions \texttt{norm} calculate the absolute norm of \texttt{src1} (when there is no \texttt{src2}):
5043 \[
5044 norm = \forkthree
5045 {\|\texttt{src1}\|_{L_{\infty}}    = \max_I |\texttt{src1}(I)|}{if $\texttt{normType} = \texttt{NORM\_INF}$}
5046 {\|\texttt{src1}\|_{L_1} = \sum_I |\texttt{src1}(I)|}{if $\texttt{normType} = \texttt{NORM\_L1}$}
5047 {\|\texttt{src1}\|_{L_2} = \sqrt{\sum_I \texttt{src1}(I)^2}}{if $\texttt{normType} = \texttt{NORM\_L2}$}
5048 \]
5049
5050 or an absolute or relative difference norm if \texttt{src2} is there:
5051 \[
5052 norm = \forkthree
5053 {\|\texttt{src1}-\texttt{src2}\|_{L_{\infty}}    = \max_I |\texttt{src1}(I) - \texttt{src2}(I)|}{if $\texttt{normType} = \texttt{NORM\_INF}$}
5054 {\|\texttt{src1}-\texttt{src2}\|_{L_1} = \sum_I |\texttt{src1}(I) - \texttt{src2}(I)|}{if $\texttt{normType} = \texttt{NORM\_L1}$}
5055 {\|\texttt{src1}-\texttt{src2}\|_{L_2} = \sqrt{\sum_I (\texttt{src1}(I) - \texttt{src2}(I))^2}}{if $\texttt{normType} = \texttt{NORM\_L2}$}
5056 \]
5057
5058 or
5059
5060 \[
5061 norm = \forkthree
5062 {\frac{\|\texttt{src1}-\texttt{src2}\|_{L_{\infty}}    }{\|\texttt{src2}\|_{L_{\infty}}   }}{if $\texttt{normType} = \texttt{NORM\_RELATIVE\_INF}$}
5063 {\frac{\|\texttt{src1}-\texttt{src2}\|_{L_1} }{\|\texttt{src2}\|_{L_1}}}{if $\texttt{normType} = \texttt{NORM\_RELATIVE\_L1}$}
5064 {\frac{\|\texttt{src1}-\texttt{src2}\|_{L_2} }{\|\texttt{src2}\|_{L_2}}}{if $\texttt{normType} = \texttt{NORM\_RELATIVE\_L2}$}
5065 \]
5066
5067 The functions \texttt{norm} return the calculated norm.
5068
5069 When there is \texttt{mask} parameter, and it is not empty (then it should have type \texttt{CV\_8U} and the same size as \texttt{src1}), the norm is computed only over the specified by the mask region.
5070
5071 A multiple-channel source arrays are treated as a single-channel, that is, the results for all channels are combined.
5072
5073
5074 \cvCppFunc{normalize}
5075 Normalizes array's norm or the range
5076
5077 \cvdefCpp{void normalize( const Mat\& src, Mat\& dst, \par double alpha=1, double beta=0,\par
5078                 int normType=NORM\_L2, int rtype=-1, \par const Mat\& mask=Mat());\newline
5079 void normalize( const MatND\& src, MatND\& dst, \par double alpha=1, double beta=0,\par
5080                 int normType=NORM\_L2, int rtype=-1, \par const MatND\& mask=MatND());\newline
5081 void normalize( const SparseMat\& src, SparseMat\& dst, \par double alpha, int normType );}
5082 \begin{description}
5083 \cvarg{src}{The source array}
5084 \cvarg{dst}{The destination array; will have the same size as \texttt{src}}
5085 \cvarg{alpha}{The norm value to normalize to or the lower range boundary in the case of range normalization}
5086 \cvarg{beta}{The upper range boundary in the case of range normalization; not used for norm normalization}
5087 \cvarg{normType}{The normalization type, see the discussion}
5088 \cvarg{rtype}{When the parameter is negative, the destination array will have the same type as \texttt{src}, otherwise it will have the same number of channels as \texttt{src} and the depth\texttt{=CV\_MAT\_DEPTH(rtype)}}
5089 \cvarg{mask}{The optional operation mask}
5090 \end{description}
5091
5092 The functions \texttt{normalize} scale and shift the source array elements, so that
5093 \[\|\texttt{dst}\|_{L_p}=\texttt{alpha}\]
5094 (where $p=\infty$, 1 or 2) when \texttt{normType=NORM\_INF}, \texttt{NORM\_L1} or \texttt{NORM\_L2},
5095 or so that
5096 \[\min_I \texttt{dst}(I)=\texttt{alpha},\,\,\max_I \texttt{dst}(I)=\texttt{beta}\]
5097 when \texttt{normType=NORM\_MINMAX} (for dense arrays only).
5098
5099 The optional mask specifies the sub-array to be normalize, that is, the norm or min-n-max are computed over the sub-array and then this sub-array is modified to be normalized. If you want to only use the mask to compute the norm or min-max, but modify the whole array, you can use \cvCppCross{norm} and \cvCppCross{Mat::convertScale}/\cvCppCross{MatND::convertScale}/cross{SparseMat::convertScale} separately.
5100
5101 in the case of sparse matrices, only the non-zero values are analyzed and transformed. Because of this, the range transformation for sparse matrices is not allowed, since it can shift the zero level. 
5102
5103 See also: \cvCppCross{norm}, \cvCppCross{Mat::convertScale}, \cvCppCross{MatND::convertScale}, \cvCppCross{SparseMat::convertScale}
5104
5105
5106 \cvCppFunc{PCA}
5107 Class for Principal Component Analysis
5108
5109 \begin{lstlisting}
5110 class PCA
5111 {
5112 public:
5113     // default constructor
5114     PCA();newline
5115     // computes PCA for a set of vectors stored as data rows or columns.
5116     PCA(const Mat& data, const Mat& mean, int flags, int maxComponents=0);newline
5117     // computes PCA for a set of vectors stored as data rows or columns
5118     PCA& operator()(const Mat& data, const Mat& mean, int flags, int maxComponents=0);newline
5119     // projects vector into the principal components space
5120     Mat project(const Mat& vec) const;newline
5121     void project(const Mat& vec, Mat& result) const;newline
5122     // reconstructs the vector from its PC projection
5123     Mat backProject(const Mat& vec) const;newline
5124     void backProject(const Mat& vec, Mat& result) const;newline
5125
5126     // eigenvectors of the PC space, stored as the matrix rows
5127     Mat eigenvectors;newline
5128     // the corresponding eigenvalues; not used for PCA compression/decompression
5129     Mat eigenvalues;newline
5130     // mean vector, subtracted from the projected vector
5131     // or added to the reconstructed vector
5132     Mat mean;
5133 };
5134 \end{lstlisting}
5135
5136 The class \texttt{PCA} is used to compute the special basis for a set of vectors. The basis will consist of eigenvectors of the covariance matrix computed from the input set of vectors. And also the class \texttt{PCA} can transform vectors to/from the new coordinate space, defined by the basis. Usually, in this new coordinate system each vector from the original set (and any linear combination of such vectors) can be quite accurately approximated by taking just the first few its components, corresponding to the eigenvectors of the largest eigenvalues of the covariance matrix. Geometrically it means that we compute projection of the vector to a subspace formed by a few eigenvectors corresponding to the dominant eigenvalues of the covariation matrix. And usually such a projection is very close to the original vector. That is, we can represent the original vector from a high-dimensional space with a much shorter vector consisting of the projected vector's coordinates in the subspace. Such a transformation is also known as Karhunen-Loeve Transform, or KLT. See \url{http://en.wikipedia.org/wiki/Principal\_component\_analysis}
5137
5138 The following sample is the function that takes two matrices. The first one stores the set of vectors (a row per vector) that is used to compute PCA, the second one stores another "test" set of vectors (a row per vector) that are first compressed with PCA, then reconstructed back and then the reconstruction error norm is computed and printed for each vector.
5139 \begin{lstlisting}
5140 PCA compressPCA(const Mat& pcaset, int maxComponents,
5141                 const Mat& testset, Mat& compressed)
5142 {
5143     PCA pca(pcaset, // pass the data
5144             Mat(), // we do not have a pre-computed mean vector,
5145                    // so let the PCA engine to compute it
5146             CV_PCA_DATA_AS_ROW, // indicate that the vectors
5147                                 // are stored as matrix rows
5148                                 // (use CV_PCA_DATA_AS_COL if the vectors are
5149                                 // the matrix columns)
5150             maxComponents // specify, how many principal components to retain
5151             );
5152     // if there is no test data, just return the computed basis, ready-to-use
5153     if( !testset.data )
5154         return pca;
5155     CV_Assert( testset.cols == pcaset.cols );
5156
5157     compressed.create(testset.rows, maxComponents, testset.type());
5158
5159     Mat reconstructed;
5160     for( int i = 0; i < testset.rows; i++ )
5161     {
5162         Mat vec = testset.row(i), coeffs = compressed.row(i);
5163         // compress the vector, the result will be stored
5164         // in the i-th row of the output matrix
5165         pca.project(vec, coeffs);
5166         // and then reconstruct it
5167         pca.backProject(coeffs, reconstructed);
5168         // and measure the error
5169         printf("%d. diff = %g\n", i, norm(vec, reconstructed, NORM_L2));
5170     }
5171     return pca;
5172 }
5173 \end{lstlisting}
5174
5175 See also: \cvCppCross{calcCovarMatrix}, \cvCppCross{mulTransposed}, \cvCppCross{SVD}, \cvCppCross{dft}, \cvCppCross{dct}
5176
5177 \cvCppFunc{perspectiveTransform}
5178 Performs perspective matrix transformation of vectors.
5179
5180 \cvdefCpp{void perspectiveTransform(const Mat\& src, \par Mat\& dst, const Mat\& mtx );}
5181 \begin{description}
5182 \cvarg{src}{The source two-channel or three-channel floating-point array;
5183             each element is 2D/3D vector to be transformed}
5184 \cvarg{dst}{The destination array; it will have the same size and same type as \texttt{src}}
5185 \cvarg{mtx}{$3\times 3$ or $4 \times 4$ transformation matrix}
5186 \end{description}
5187
5188 The function \texttt{perspectiveTransform} transforms every element of \texttt{src},
5189 by treating it as 2D or 3D vector, in the following way (here 3D vector transformation is shown; in the case of 2D vector transformation the $z$ component is omitted):
5190
5191 \[ (x, y, z) \rightarrow (x'/w, y'/w, z'/w) \]
5192
5193 where
5194
5195 \[
5196 (x', y', z', w') = \texttt{mat} \cdot
5197 \begin{bmatrix} x & y & z & 1 \end{bmatrix}
5198 \]
5199
5200 and
5201 \[ w = \fork{w'}{if $w' \ne 0$}{\infty}{otherwise} \]
5202
5203 Note that the function transforms a sparse set of 2D or 3D vectors. If you want to transform an image using perspective transformation, use \cvCppCross{warpPerspective}. If you have an inverse task, i.e. want to compute the most probable perspective transformation out of several pairs of corresponding points, you can use \cvCppCross{getPerspectiveTransform} or \cvCppCross{findHomography}.
5204
5205 See also: \cvCppCross{transform}, \cvCppCross{warpPerspective}, \cvCppCross{getPerspectiveTransform}, \cvCppCross{findHomography}
5206
5207 \cvCppFunc{phase}
5208 Calculates the rotation angle of 2d vectors
5209
5210 \cvdefCpp{void phase(const Mat\& x, const Mat\& y, Mat\& angle,\par
5211            bool angleInDegrees=false);}
5212 \begin{description}
5213 \cvarg{x}{The source floating-point array of x-coordinates of 2D vectors}
5214 \cvarg{y}{The source array of y-coordinates of 2D vectors; must have the same size and the same type as \texttt{x}}
5215 \cvarg{angle}{The destination array of vector angles; it will have the same size and same type as \texttt{x}}
5216 \cvarg{angleInDegrees}{When it is true, the function will compute angle in degrees, otherwise they will be measured in radians}
5217 \end{description}
5218
5219 The function \texttt{phase} computes the rotation angle of each 2D vector that is formed from the corresponding elements of \texttt{x} and \texttt{y}:
5220
5221 \[\texttt{angle}(I) = \texttt{atan2}(\texttt{y}(I), \texttt{x}(I))\]
5222
5223 The angle estimation accuracy is $\sim\,0.3^\circ$, when \texttt{x(I)=y(I)=0}, the corresponding \texttt{angle}(I) is set to $0$.
5224
5225 See also:
5226
5227 \cvCppFunc{polarToCart}
5228 Computes x and y coordinates of 2D vectors from their magnitude and angle.
5229
5230 \cvdefCpp{void polarToCart(const Mat\& magnitude, const Mat\& angle,\par
5231                  Mat\& x, Mat\& y, bool angleInDegrees=false);}
5232 \begin{description}
5233 \cvarg{magnitude}{The source floating-point array of magnitudes of 2D vectors. It can be an empty matrix (\texttt{=Mat()}) - in this case the function assumes that all the magnitudes are =1. If it's not empty, it must have the same size and same type as \texttt{angle}}
5234 \cvarg{angle}{The source floating-point array of angles of the 2D vectors}
5235 \cvarg{x}{The destination array of x-coordinates of 2D vectors; will have the same size and the same type as \texttt{angle}}
5236 \cvarg{y}{The destination array of y-coordinates of 2D vectors; will have the same size and the same type as \texttt{angle}}
5237 \cvarg{angleInDegrees}{When it is true, the input angles are measured in degrees, otherwise they are measured in radians}
5238 \end{description}
5239
5240 The function \texttt{polarToCart} computes the cartesian coordinates of each 2D vector represented by the corresponding elements of \texttt{magnitude} and \texttt{angle}:
5241
5242 \[
5243 \begin{array}{l}
5244 \texttt{x}(I) = \texttt{magnitude}(I)\cos(\texttt{angle}(I))\\
5245 \texttt{y}(I) = \texttt{magnitude}(I)\sin(\texttt{angle}(I))\\
5246 \end{array}
5247 \]
5248
5249 The relative accuracy of the estimated coordinates is $\sim\,10^{-6}$.
5250
5251 See also: \cvCppCross{cartToPolar}, \cvCppCross{magnitude}, \cvCppCross{phase}, \cvCppCross{exp}, \cvCppCross{log}, \cvCppCross{pow}, \cvCppCross{sqrt}
5252
5253 \cvCppFunc{pow}
5254 Raises every array element to a power.
5255
5256 \cvdefCpp{void pow(const Mat\& src, double p, Mat\& dst);\newline
5257 void pow(const MatND\& src, double p, MatND\& dst);}
5258 \begin{description}
5259 \cvarg{src}{The source array}
5260 \cvarg{p}{The exponent of power}
5261 \cvarg{dst}{The destination array; will have the same size and the same type as \texttt{src}}
5262 \end{description}
5263
5264 The function \texttt{pow} raises every element of the input array to \texttt{p}:
5265
5266 \[
5267 \texttt{dst}(I) = \fork
5268 {\texttt{src}(I)^p}{if \texttt{p} is integer}
5269 {|\texttt{src}(I)|^p}{otherwise}
5270 \]
5271
5272 That is, for a non-integer power exponent the absolute values of input array elements are used. However, it is possible to get true values for negative values using some extra operations, as the following example, computing the 5th root of array \texttt{src}, shows:
5273
5274 \begin{lstlisting}
5275 Mat mask = src < 0;
5276 pow(src, 1./5, dst);
5277 subtract(Scalar::all(0), dst, dst, mask);
5278 \end{lstlisting}
5279
5280 For some values of \texttt{p}, such as integer values, 0.5, and -0.5, specialized faster algorithms are used.
5281
5282 See also: \cvCppCross{sqrt}, \cvCppCross{exp}, \cvCppCross{log}, \cvCppCross{cartToPolar}, \cvCppCross{polarToCart}
5283
5284 \cvCppFunc{randu}
5285 Generates a single uniformly-distributed random number or array of random numbers
5286
5287 \cvdefCpp{template<typename \_Tp> \_Tp randu();\newline
5288 void randu(Mat\& mtx, const Scalar\& low, const Scalar\& high);}
5289 \begin{description}
5290 \cvarg{mtx}{The output array of random numbers. The array must be pre-allocated and have 1 to 4 channels}
5291 \cvarg{low}{The inclusive lower boundary of the generated random numbers}
5292 \cvarg{high}{The exclusive upper boundary of the generated random numbers}
5293 \end{description}
5294
5295 The template functions \texttt{randu} generate and return the next uniformly-distributed random value of the specified type. \texttt{randu<int>()} is equivalent to \texttt{(int)theRNG();} etc. See \cvCppCross{RNG} description.
5296
5297 The second non-template variant of the function fills the matrix \texttt{mtx} with uniformly-distributed random numbers from the specified range:
5298
5299 \[\texttt{low}_c \leq \texttt{mtx}(I)_c < \texttt{high}_c\]
5300
5301 See also: \cvCppCross{RNG}, \cvCppCross{randn}, \cvCppCross{theRNG}.
5302
5303 \cvCppFunc{randn}
5304 Fills array with normally distributed random numbers
5305
5306 \cvdefCpp{void randn(Mat\& mtx, const Scalar\& mean, const Scalar\& stddev);}
5307 \begin{description}
5308 \cvarg{mtx}{The output array of random numbers. The array must be pre-allocated and have 1 to 4 channels}
5309 \cvarg{mean}{The mean value (expectation) of the generated random numbers}
5310 \cvarg{stddev}{The standard deviation of the generated random numbers}
5311 \end{description}
5312
5313 The function \texttt{randn} fills the matrix \texttt{mtx} with normally distributed random numbers with the specified mean and standard deviation. \hyperref[cppfunc.saturatecast]{saturate\_cast} is applied to the generated numbers (i.e. the values are clipped)
5314
5315 See also: \cvCppCross{RNG}, \cvCppCross{randu}
5316
5317 \cvCppFunc{randShuffle}
5318 Shuffles the array elements randomly
5319
5320 \cvdefCpp{void randShuffle(Mat\& mtx, double iterFactor=1., RNG* rng=0);}
5321 \begin{description}
5322 \cvarg{mtx}{The input/output numerical 1D array}
5323 \cvarg{iterFactor}{The scale factor that determines the number of random swap operations. See the discussion}
5324 \cvarg{rng}{The optional random number generator used for shuffling. If it is zero, \cvCppCross{theRNG}() is used instead}
5325 \end{description}
5326
5327 The function \texttt{randShuffle} shuffles the specified 1D array by randomly choosing pairs of elements and swapping them. The number of such swap operations will be \texttt{mtx.rows*mtx.cols*iterFactor}
5328
5329 See also: \cvCppCross{RNG}, \cvCppCross{sort}
5330
5331 \cvCppFunc{reduce}
5332 Reduces a matrix to a vector
5333
5334 \cvdefCpp{void reduce(const Mat\& mtx, Mat\& vec, \par int dim, int reduceOp, int dtype=-1);}
5335 \begin{description}
5336 \cvarg{mtx}{The source 2D matrix}
5337 \cvarg{vec}{The destination vector. Its size and type is defined by \texttt{dim} and \texttt{dtype} parameters}
5338 \cvarg{dim}{The dimension index along which the matrix is reduced. 0 means that the matrix is reduced to a single row and 1 means that the matrix is reduced to a single column}
5339 \cvarg{reduceOp}{The reduction operation, one of:
5340 \begin{description}
5341 \cvarg{CV\_REDUCE\_SUM}{The output is the sum of all of the matrix's rows/columns.}
5342 \cvarg{CV\_REDUCE\_AVG}{The output is the mean vector of all of the matrix's rows/columns.}
5343 \cvarg{CV\_REDUCE\_MAX}{The output is the maximum (column/row-wise) of all of the matrix's rows/columns.}
5344 \cvarg{CV\_REDUCE\_MIN}{The output is the minimum (column/row-wise) of all of the matrix's rows/columns.}
5345 \end{description}}
5346 \cvarg{dtype}{When it is negative, the destination vector will have the same type as the source matrix, otherwise, its type will be \texttt{CV\_MAKE\_TYPE(CV\_MAT\_DEPTH(dtype), mtx.channels())}}
5347 \end{description}
5348
5349 The function \texttt{reduce} reduces matrix to a vector by treating the matrix rows/columns as a set of 1D vectors and performing the specified operation on the vectors until a single row/column is obtained. For example, the function can be used to compute horizontal and vertical projections of an raster image. In the case of \texttt{CV\_REDUCE\_SUM} and \texttt{CV\_REDUCE\_AVG} the output may have a larger element bit-depth to preserve accuracy. And multi-channel arrays are also supported in these two reduction modes. 
5350
5351 See also: \cvCppCross{repeat}
5352
5353 \cvCppFunc{repeat}
5354 Fill the destination array with repeated copies of the source array.
5355
5356 \cvdefCpp{void repeat(const Mat\& src, int ny, int nx, Mat\& dst);\newline
5357 Mat repeat(const Mat\& src, int ny, int nx);}
5358 \begin{description}
5359 \cvarg{src}{The source array to replicate}
5360 \cvarg{dst}{The destination array; will have the same type as \texttt{src}}
5361 \cvarg{ny}{How many times the \texttt{src} is repeated along the vertical axis}
5362 \cvarg{nx}{How many times the \texttt{src} is repeated along the horizontal axis}
5363 \end{description}
5364
5365 The functions \cvCppCross{repeat} duplicate the source array one or more times along each of the two axes:
5366
5367 \[\texttt{dst}_{ij}=\texttt{src}_{i\mod\texttt{src.rows},\;j\mod\texttt{src.cols}}\]
5368
5369 The second variant of the function is more convenient to use with \cross{Matrix Expressions}
5370
5371 See also: \cvCppCross{reduce}, \cross{Matrix Expressions}
5372
5373 \ifplastex
5374 \subsection{saturate\_cast}\label{cppfunc.saturatecast}
5375 \else
5376 \subsection{cv::saturate\_cast}\label{cppfunc.saturatecast}
5377 \fi
5378 Template function for accurate conversion from one primitive type to another
5379
5380 \cvdefCpp{template<typename \_Tp> inline \_Tp saturate\_cast(unsigned char v);\newline
5381 template<typename \_Tp> inline \_Tp saturate\_cast(signed char v);\newline
5382 template<typename \_Tp> inline \_Tp saturate\_cast(unsigned short v);\newline
5383 template<typename \_Tp> inline \_Tp saturate\_cast(signed short v);\newline
5384 template<typename \_Tp> inline \_Tp saturate\_cast(int v);\newline
5385 template<typename \_Tp> inline \_Tp saturate\_cast(unsigned int v);\newline
5386 template<typename \_Tp> inline \_Tp saturate\_cast(float v);\newline
5387 template<typename \_Tp> inline \_Tp saturate\_cast(double v);}
5388
5389 \begin{description}
5390 \cvarg{v}{The function parameter}
5391 \end{description}
5392
5393 The functions \texttt{saturate\_cast} resembles the standard C++ cast operations, such as \texttt{static\_cast<T>()} etc. They perform an efficient and accurate conversion from one primitive type to another, see the introduction. "saturate" in the name means that when the input value \texttt{v} is out of range of the target type, the result will not be formed just by taking low bits of the input, but instead the value will be clipped. For example:
5394
5395 \begin{lstlisting}
5396 uchar a = saturate_cast<uchar>(-100); // a = 0 (UCHAR_MIN)
5397 short b = saturate_cast<short>(33333.33333); // b = 32767 (SHRT_MAX)
5398 \end{lstlisting}
5399
5400 Such clipping is done when the target type is \texttt{unsigned char, signed char, unsigned short or signed short} - for 32-bit integers no clipping is done.
5401
5402 When the parameter is floating-point value and the target type is an integer (8-, 16- or 32-bit), the floating-point value is first rounded to the nearest integer and then clipped if needed (when the target type is 8- or 16-bit).
5403
5404 This operation is used in most simple or complex image processing functions in OpenCV.
5405
5406 See also: \cvCppCross{add}, \cvCppCross{subtract}, \cvCppCross{multiply}, \cvCppCross{divide}, \cvCppCross{Mat::convertTo}
5407
5408 \cvCppFunc{scaleAdd}
5409 Calculates the sum of a scaled array and another array.
5410
5411 \cvdefCpp{void scaleAdd(const Mat\& src1, double scale, \par const Mat\& src2, Mat\& dst);\newline
5412 void scaleAdd(const MatND\& src1, double scale, \par const MatND\& src2, MatND\& dst);}
5413 \begin{description}
5414 \cvarg{src1}{The first source array}
5415 \cvarg{scale}{Scale factor for the first array}
5416 \cvarg{src2}{The second source array; must have the same size and the same type as \texttt{src1}}
5417 \cvarg{dst}{The destination array; will have the same size and the same type as \texttt{src1}}
5418 \end{description}
5419
5420 The function \texttt{cvScaleAdd} is one of the classical primitive linear algebra operations, known as \texttt{DAXPY} or \texttt{SAXPY} in \href{http://en.wikipedia.org/wiki/Basic_Linear_Algebra_Subprograms}{BLAS}. It calculates the sum of a scaled array and another array:
5421
5422 \[
5423 \texttt{dst}(I)=\texttt{scale} \cdot \texttt{src1}(I) + \texttt{src2}(I)
5424 \]
5425
5426 The function can also be emulated with a matrix expression, for example:
5427
5428 \begin{lstlisting}
5429 Mat A(3, 3, CV_64F);
5430 ...
5431 A.row(0) = A.row(1)*2 + A.row(2);
5432 \end{lstlisting}
5433
5434 See also: \cvCppCross{add}, \cvCppCross{addWeighted}, \cvCppCross{subtract}, \cvCppCross{Mat::dot}, \cvCppCross{Mat::convertTo}, \cross{Matrix Expressions}
5435
5436 \cvCppFunc{setIdentity}
5437 Initializes a scaled identity matrix
5438
5439 \cvdefCpp{void setIdentity(Mat\& dst, const Scalar\& value=Scalar(1));}
5440 \begin{description}
5441 \cvarg{dst}{The matrix to initialize (not necessarily square)}
5442 \cvarg{value}{The value to assign to the diagonal elements}
5443 \end{description}
5444
5445 The function \cvCppCross{setIdentity} initializes a scaled identity matrix:
5446
5447 \[
5448 \texttt{dst}(i,j)=\fork{\texttt{value}}{ if $i=j$}{0}{otherwise}
5449 \]
5450
5451 The function can also be emulated using the matrix initializers and the matrix expressions:
5452 \begin{lstlisting}
5453 Mat A = Mat::eye(4, 3, CV_32F)*5;
5454 // A will be set to [[5, 0, 0], [0, 5, 0], [0, 0, 5], [0, 0, 0]]
5455 \end{lstlisting}
5456
5457 See also: \cvCppCross{Mat::zeros}, \cvCppCross{Mat::ones}, \cross{Matrix Expressions},
5458 \cvCppCross{Mat::setTo}, \cvCppCross{Mat::operator=},
5459
5460 \cvCppFunc{solve}
5461 Solves one or more linear systems or least-squares problems.
5462
5463 \cvdefCpp{bool solve(const Mat\& src1, const Mat\& src2, \par Mat\& dst, int flags=DECOMP\_LU);}
5464 \begin{description}
5465 \cvarg{src1}{The input matrix on the left-hand side of the system}
5466 \cvarg{src2}{The input matrix on the right-hand side of the system}
5467 \cvarg{dst}{The output solution}
5468 \cvarg{flags}{The solution (matrix inversion) method
5469 \begin{description}
5470  \cvarg{DECOMP\_LU}{Gaussian elimination with optimal pivot element chosen}
5471  \cvarg{DECOMP\_CHOLESKY}{Cholesky $LL^T$ factorization; the matrix \texttt{src1} must be symmetrical and positively defined}
5472  \cvarg{DECOMP\_EIG}{Eigenvalue decomposition; the matrix \texttt{src1} must be symmetrical}
5473  \cvarg{DECOMP\_SVD}{Singular value decomposition (SVD) method; the system can be over-defined and/or the matrix \texttt{src1} can be singular}
5474  \cvarg{DECOMP\_QR}{QR factorization; the system can be over-defined and/or the matrix \texttt{src1} can be singular}
5475  \cvarg{DECOMP\_NORMAL}{While all the previous flags are mutually exclusive, this flag can be used together with any of the previous. It means that the normal equations $\texttt{src1}^T\cdot\texttt{src1}\cdot\texttt{dst}=\texttt{src1}^T\texttt{src2}$ are solved instead of the original system $\texttt{src1}\cdot\texttt{dst}=\texttt{src2}$}
5476 \end{description}}
5477 \end{description}
5478
5479 The function \texttt{solve} solves a linear system or least-squares problem (the latter is possible with SVD or QR methods, or by specifying the flag \texttt{DECOMP\_NORMAL}):
5480
5481 \[
5482 \texttt{dst} = \arg \min_X\|\texttt{src1}\cdot\texttt{X} - \texttt{src2}\|
5483 \]
5484
5485 If \texttt{DECOMP\_LU} or \texttt{DECOMP\_CHOLESKY} method is used, the function returns 1 if \texttt{src1} (or $\texttt{src1}^T\texttt{src1}$) is non-singular and 0 otherwise; in the latter case \texttt{dst} is not valid. Other methods find some pseudo-solution in the case of singular left-hand side part.
5486
5487 Note that if you want to find unity-norm solution of an under-defined singular system $\texttt{src1}\cdot\texttt{dst}=0$, the function \texttt{solve} will not do the work. Use \cvCppCross{SVD::solveZ} instead.
5488
5489 See also: \cvCppCross{invert}, \cvCppCross{SVD}, \cvCppCross{eigen}
5490
5491 \cvCppFunc{solveCubic}
5492 Finds the real roots of a cubic equation.
5493
5494 \cvdefCpp{void solveCubic(const Mat\& coeffs, Mat\& roots);}
5495 \begin{description}
5496 \cvarg{coeffs}{The equation coefficients, an array of 3 or 4 elements}
5497 \cvarg{roots}{The destination array of real roots which will have 1 or 3 elements}
5498 \end{description}
5499
5500 The function \texttt{solveCubic} finds the real roots of a cubic equation:
5501
5502 (if coeffs is a 4-element vector)
5503
5504 \[
5505 \texttt{coeffs}[0] x^3 + \texttt{coeffs}[1] x^2 + \texttt{coeffs}[2] x + \texttt{coeffs}[3] = 0
5506 \]
5507
5508 or (if coeffs is 3-element vector):
5509
5510 \[
5511 x^3 + \texttt{coeffs}[0] x^2 + \texttt{coeffs}[1] x + \texttt{coeffs}[2] = 0
5512 \]
5513
5514 The roots are stored to \texttt{roots} array.
5515
5516 \cvCppFunc{solvePoly}
5517 Finds the real or complex roots of a polynomial equation
5518
5519 \cvdefCpp{void solvePoly(const Mat\& coeffs, Mat\& roots, \par int maxIters=20, int fig=100);}
5520 \begin{description}
5521 \cvarg{coeffs}{The array of polynomial coefficients}
5522 \cvarg{roots}{The destination (complex) array of roots}
5523 \cvarg{maxIters}{The maximum number of iterations the algorithm does}
5524 \cvarg{fig}{}
5525 \end{description}
5526
5527 The function \texttt{solvePoly} finds real and complex roots of a polynomial equation:
5528 \[
5529 \texttt{coeffs}[0] x^{n} + \texttt{coeffs}[1] x^{n-1} + ... + \texttt{coeffs}[n-1] x + \texttt{coeffs}[n] = 0
5530 \]
5531
5532 \cvCppFunc{sort}
5533 Sorts each row or each column of a matrix
5534
5535 \cvdefCpp{void sort(const Mat\& src, Mat\& dst, int flags);}
5536 \begin{description}
5537 \cvarg{src}{The source single-channel array}
5538 \cvarg{dst}{The destination array of the same size and the same type as \texttt{src}}
5539 \cvarg{flags}{The operation flags, a combination of the following values:
5540 \begin{description}
5541     \cvarg{CV\_SORT\_EVERY\_ROW}{Each matrix row is sorted independently}
5542     \cvarg{CV\_SORT\_EVERY\_COLUMN}{Each matrix column is sorted independently. This flag and the previous one are mutually exclusive}
5543     \cvarg{CV\_SORT\_ASCENDING}{Each matrix row is sorted in the ascending order}
5544     \cvarg{CV\_SORT\_DESCENDING}{Each matrix row is sorted in the descending order. This flag and the previous one are also mutually exclusive}
5545 \end{description}}
5546 \end{description}
5547
5548 The function \texttt{sort} sorts each matrix row or each matrix column in ascending or descending order. If you want to sort matrix rows or columns lexicographically, you can use STL \texttt{std::sort} generic function with the proper comparison predicate.
5549
5550 See also: \cvCppCross{sortIdx}, \cvCppCross{randShuffle}
5551
5552 \cvCppFunc{sortIdx}
5553 Sorts each row or each column of a matrix
5554
5555 \cvdefCpp{void sortIdx(const Mat\& src, Mat\& dst, int flags);}
5556 \begin{description}
5557 \cvarg{src}{The source single-channel array}
5558 \cvarg{dst}{The destination integer array of the same size as \texttt{src}}
5559 \cvarg{flags}{The operation flags, a combination of the following values:
5560 \begin{description}
5561     \cvarg{CV\_SORT\_EVERY\_ROW}{Each matrix row is sorted independently}
5562     \cvarg{CV\_SORT\_EVERY\_COLUMN}{Each matrix column is sorted independently. This flag and the previous one are mutually exclusive}
5563     \cvarg{CV\_SORT\_ASCENDING}{Each matrix row is sorted in the ascending order}
5564     \cvarg{CV\_SORT\_DESCENDING}{Each matrix row is sorted in the descending order. This flag and the previous one are also mutually exclusive}
5565 \end{description}}
5566 \end{description}
5567
5568 The function \texttt{sortIdx} sorts each matrix row or each matrix column in ascending or descending order. Instead of reordering the elements themselves, it stores the indices of sorted elements in the destination array. For example:
5569
5570 \begin{lstlisting}
5571 Mat A = Mat::eye(3,3,CV_32F), B;
5572 sortIdx(A, B, CV_SORT_EVERY_ROW + CV_SORT_ASCENDING);
5573 // B will probably contain
5574 // (because of equal elements in A some permutations are possible):
5575 // [[1, 2, 0], [0, 2, 1], [0, 1, 2]]
5576 \end{lstlisting}
5577
5578 See also: \cvCppCross{sort}, \cvCppCross{randShuffle}
5579
5580 \cvCppFunc{split}
5581 Divides multi-channel array into several single-channel arrays
5582
5583 \cvdefCpp{void split(const Mat\& mtx, Mat* mv);\newline
5584 void split(const Mat\& mtx, vector<Mat>\& mv);\newline
5585 void split(const MatND\& mtx, MatND* mv);\newline
5586 void split(const MatND\& mtx, vector<MatND>\& mv);}
5587 \begin{description}
5588 \cvarg{mtx}{The source multi-channel array}
5589 \cvarg{mv}{The destination array or vector of arrays; The number of arrays must match \texttt{mtx.channels()}. The arrays themselves will be reallocated if needed}
5590 \end{description}
5591
5592 The functions \texttt{split} split multi-channel array into separate single-channel arrays:
5593
5594 \[ \texttt{mv}[c](I) = \texttt{mtx}(I)_c \]
5595
5596 If you need to extract a single-channel or do some other sophisticated channel permutation, use \cvCppCross{mixChannels}
5597
5598 See also: \cvCppCross{merge}, \cvCppCross{mixChannels}, \cvCppCross{cvtColor}
5599
5600 \cvCppFunc{sqrt}
5601 Calculates square root of array elements
5602
5603 \cvdefCpp{void sqrt(const Mat\& src, Mat\& dst);\newline
5604 void sqrt(const MatND\& src, MatND\& dst);}
5605 \begin{description}
5606 \cvarg{src}{The source floating-point array}
5607 \cvarg{dst}{The destination array; will have the same size and the same type as \texttt{src}}
5608 \end{description}
5609
5610 The functions \texttt{sqrt} calculate square root of each source array element. in the case of multi-channel arrays each channel is processed independently. The function accuracy is approximately the same as of the built-in \texttt{std::sqrt}.
5611
5612 See also: \cvCppCross{pow}, \cvCppCross{magnitude}
5613
5614 \cvCppFunc{subtract}
5615 Calculates per-element difference between two arrays or array and a scalar
5616
5617 \cvdefCpp{void subtract(const Mat\& src1, const Mat\& src2, Mat\& dst);\newline
5618 void subtract(const Mat\& src1, const Mat\& src2, \par Mat\& dst, const Mat\& mask);\newline
5619 void subtract(const Mat\& src1, const Scalar\& sc, \par Mat\& dst, const Mat\& mask=Mat());\newline
5620 void subtract(const Scalar\& sc, const Mat\& src2, \par Mat\& dst, const Mat\& mask=Mat());\newline
5621 void subtract(const MatND\& src1, const MatND\& src2, MatND\& dst);\newline
5622 void subtract(const MatND\& src1, const MatND\& src2, \par MatND\& dst, const MatND\& mask);\newline
5623 void subtract(const MatND\& src1, const Scalar\& sc, \par MatND\& dst, const MatND\& mask=MatND());\newline
5624 void subtract(const Scalar\& sc, const MatND\& src2, \par MatND\& dst, const MatND\& mask=MatND());}
5625 \begin{description}
5626 \cvarg{src1}{The first source array}
5627 \cvarg{src2}{The second source array. It must have the same size and same type as \texttt{src1}}
5628 \cvarg{sc}{Scalar; the first or the second input parameter}
5629 \cvarg{dst}{The destination array; it will have the same size and same type as \texttt{src1}; see \texttt{Mat::create}}
5630 \cvarg{mask}{The optional operation mask, 8-bit single channel array;
5631              specifies elements of the destination array to be changed}
5632 \end{description}
5633
5634 The functions \texttt{subtract} compute
5635
5636 \begin{itemize}
5637     \item the difference between two arrays
5638     \[\texttt{dst}(I) = \texttt{saturate}(\texttt{src1}(I) - \texttt{src2}(I))\quad\texttt{if mask}(I)\ne0\]
5639     \item the difference between array and a scalar:
5640     \[\texttt{dst}(I) = \texttt{saturate}(\texttt{src1}(I) - \texttt{sc})\quad\texttt{if mask}(I)\ne0\]
5641     \item the difference between scalar and an array:
5642     \[\texttt{dst}(I) = \texttt{saturate}(\texttt{sc} - \texttt{src2}(I))\quad\texttt{if mask}(I)\ne0\]
5643 \end{itemize}
5644
5645 where \texttt{I} is multi-dimensional index of array elements.
5646
5647 The first function in the above list can be replaced with matrix expressions:
5648 \begin{lstlisting}
5649 dst = src1 - src2;
5650 dst -= src2; // equivalent to subtract(dst, src2, dst);
5651 \end{lstlisting}
5652
5653 See also: \cvCppCross{add}, \cvCppCross{addWeighted}, \cvCppCross{scaleAdd}, \cvCppCross{convertScale},
5654 \cross{Matrix Expressions}, \hyperref[cppfunc.saturatecast]{saturate\_cast}.
5655
5656 \cvCppFunc{SVD}
5657 Class for computing Singular Value Decomposition
5658
5659 \begin{lstlisting}
5660 class SVD
5661 {
5662 public:
5663     enum { MODIFY_A=1, NO_UV=2, FULL_UV=4 };newline
5664     // default empty constructor
5665     SVD();newline
5666     // decomposes m into u, w and vt: m = u*w*vt;newline
5667     // u and vt are orthogonal, w is diagonal
5668     SVD( const Mat& m, int flags=0 );newline
5669     // decomposes m into u, w and vt.
5670     SVD& operator ()( const Mat& m, int flags=0 );newline
5671
5672     // finds such vector x, norm(x)=1, so that m*x = 0,
5673     // where m is singular matrix
5674     static void solveZ( const Mat& m, Mat& dst );newline
5675     // does back-subsitution:
5676     // dst = vt.t()*inv(w)*u.t()*rhs ~ inv(m)*rhs
5677     void backSubst( const Mat& rhs, Mat& dst ) const;newline
5678
5679     Mat u, w, vt;
5680 };
5681 \end{lstlisting}
5682
5683 The class \texttt{SVD} is used to compute Singular Value Decomposition of a floating-point matrix and then use it to solve least-square problems, under-determined linear systems, invert matrices, compute condition numbers etc.
5684 For a bit faster operation you can pass \texttt{flags=SVD::MODIFY\_A|...} to modify the decomposed matrix when it is not necessarily to preserve it. If you want to compute condition number of a matrix or absolute value of its determinant - you do not need \texttt{u} and \texttt{vt}, so you can pass \texttt{flags=SVD::NO\_UV|...}. Another flag \texttt{FULL\_UV} indicates that full-size \texttt{u} and \texttt{vt} must be computed, which is not necessary most of the time.
5685
5686 See also: \cvCppCross{invert}, \cvCppCross{solve}, \cvCppCross{eigen}, \cvCppCross{determinant}
5687
5688 \cvCppFunc{sum}
5689 Calculates sum of array elements
5690
5691 \cvdefCpp{Scalar sum(const Mat\& mtx);\newline
5692 Scalar sum(const MatND\& mtx);}
5693 \begin{description}
5694 \cvarg{mtx}{The source array; must have 1 to 4 channels}
5695 \end{description}
5696
5697 The functions \texttt{sum} calculate and return the sum of array elements, independently for each channel.
5698
5699 See also: \cvCppCross{countNonZero}, \cvCppCross{mean}, \cvCppCross{meanStdDev}, \cvCppCross{norm}, \cvCppCross{minMaxLoc}, \cvCppCross{reduce}
5700
5701 \cvCppFunc{theRNG}
5702 Returns the default random number generator
5703
5704 \cvdefCpp{RNG\& theRNG();}
5705
5706 The function \texttt{theRNG} returns the default random number generator. For each thread there is separate random number generator, so you can use the function safely in multi-thread environments. If you just need to get a single random number using this generator or initialize an array, you can use \cvCppCross{randu} or \cvCppCross{randn} instead. But if you are going to generate many random numbers inside a loop, it will be much faster to use this function to retrieve the generator and then use \texttt{RNG::operator \_Tp()}.
5707
5708 See also: \cvCppCross{RNG}, \cvCppCross{randu}, \cvCppCross{randn}
5709
5710 \cvCppFunc{trace}
5711 Returns the trace of a matrix
5712
5713 \cvdefCpp{Scalar trace(const Mat\& mtx);}
5714 \begin{description}
5715 \cvarg{mtx}{The source matrix}
5716 \end{description}
5717
5718 The function \texttt{trace} returns the sum of the diagonal elements of the matrix \texttt{mtx}.
5719
5720 \[ \mathrm{tr}(\texttt{mtx}) = \sum_i \texttt{mtx}(i,i) \]
5721
5722
5723 \cvCppFunc{transform}
5724 Performs matrix transformation of every array element.
5725
5726 \cvdefCpp{void transform(const Mat\& src, \par Mat\& dst, const Mat\& mtx );}
5727 \begin{description}
5728 \cvarg{src}{The source array; must have as many channels (1 to 4) as \texttt{mtx.cols} or \texttt{mtx.cols-1}}
5729 \cvarg{dst}{The destination array; will have the same size and depth as \texttt{src} and as many channels as \texttt{mtx.rows}}
5730 \cvarg{mtx}{The transformation matrix}
5731 \end{description}
5732
5733 The function \texttt{transform} performs matrix transformation of every element of array \texttt{src} and stores the results in \texttt{dst}:
5734
5735 \[
5736 \texttt{dst}(I) = \texttt{mtx} \cdot \texttt{src}(I)
5737 \]
5738 (when \texttt{mtx.cols=src.channels()}), or
5739
5740 \[
5741 \texttt{dst}(I) = \texttt{mtx} \cdot [\texttt{src}(I); 1]
5742 \]
5743 (when \texttt{mtx.cols=src.channels()+1})
5744
5745 That is, every element of an \texttt{N}-channel array \texttt{src} is
5746 considered as \texttt{N}-element vector, which is transformed using
5747 a $\texttt{M} \times \texttt{N}$ or $\texttt{M} \times \texttt{N+1}$ matrix \texttt{mtx} into
5748 an element of \texttt{M}-channel array \texttt{dst}.
5749
5750 The function may be used for geometrical transformation of $N$-dimensional
5751 points, arbitrary linear color space transformation (such as various kinds of RGB$\rightarrow$YUV transforms), shuffling the image channels and so forth.
5752
5753 See also: \cvCppCross{perspectiveTransform}, \cvCppCross{getAffineTransform}, \cvCppCross{estimateRigidTransform}, \cvCppCross{warpAffine}, \cvCppCross{warpPerspective}
5754
5755 \cvCppFunc{transpose}
5756 Transposes a matrix
5757
5758 \cvdefCpp{void transpose(const Mat\& src, Mat\& dst);}
5759 \begin{description}
5760 \cvarg{src}{The source array}
5761 \cvarg{dst}{The destination array of the same type as \texttt{src}}
5762 \end{description}
5763
5764 The function \cvCppCross{transpose} transposes the matrix \texttt{src}:
5765
5766 \[ \texttt{dst}(i,j) = \texttt{src}(j,i) \]
5767
5768 Note that no complex conjugation is done in the case of a complex
5769 matrix, it should be done separately if needed.
5770
5771 \fi