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