1 | /*M/////////////////////////////////////////////////////////////////////////////////////// |
2 | // |
3 | // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. |
4 | // |
5 | // By downloading, copying, installing or using the software you agree to this license. |
6 | // If you do not agree to this license, do not download, install, |
7 | // copy or use the software. |
8 | // |
9 | // |
10 | // License Agreement |
11 | // For Open Source Computer Vision Library |
12 | // |
13 | // Copyright (C) 2000-2015, Intel Corporation, all rights reserved. |
14 | // Copyright (C) 2009-2011, Willow Garage Inc., all rights reserved. |
15 | // Copyright (C) 2015, OpenCV Foundation, all rights reserved. |
16 | // Copyright (C) 2015, Itseez Inc., all rights reserved. |
17 | // Third party copyrights are property of their respective owners. |
18 | // |
19 | // Redistribution and use in source and binary forms, with or without modification, |
20 | // are permitted provided that the following conditions are met: |
21 | // |
22 | // * Redistribution's of source code must retain the above copyright notice, |
23 | // this list of conditions and the following disclaimer. |
24 | // |
25 | // * Redistribution's in binary form must reproduce the above copyright notice, |
26 | // this list of conditions and the following disclaimer in the documentation |
27 | // and/or other materials provided with the distribution. |
28 | // |
29 | // * The name of the copyright holders may not be used to endorse or promote products |
30 | // derived from this software without specific prior written permission. |
31 | // |
32 | // This software is provided by the copyright holders and contributors "as is" and |
33 | // any express or implied warranties, including, but not limited to, the implied |
34 | // warranties of merchantability and fitness for a particular purpose are disclaimed. |
35 | // In no event shall the Intel Corporation or contributors be liable for any direct, |
36 | // indirect, incidental, special, exemplary, or consequential damages |
37 | // (including, but not limited to, procurement of substitute goods or services; |
38 | // loss of use, data, or profits; or business interruption) however caused |
39 | // and on any theory of liability, whether in contract, strict liability, |
40 | // or tort (including negligence or otherwise) arising in any way out of |
41 | // the use of this software, even if advised of the possibility of such damage. |
42 | // |
43 | //M*/ |
44 | |
45 | #ifndef OPENCV_CORE_HPP |
46 | #define OPENCV_CORE_HPP |
47 | |
48 | #ifndef __cplusplus |
49 | # error core.hpp header must be compiled as C++ |
50 | #endif |
51 | |
52 | #include "opencv2/core/cvdef.h" |
53 | #include "opencv2/core/base.hpp" |
54 | #include "opencv2/core/cvstd.hpp" |
55 | #include "opencv2/core/traits.hpp" |
56 | #include "opencv2/core/matx.hpp" |
57 | #include "opencv2/core/types.hpp" |
58 | #include "opencv2/core/mat.hpp" |
59 | #include "opencv2/core/persistence.hpp" |
60 | |
61 | /** |
62 | @defgroup core Core functionality |
63 | |
64 | The Core module is the backbone of OpenCV, offering fundamental data structures, matrix operations, |
65 | and utility functions that other modules depend on. It’s essential for handling image data, |
66 | performing mathematical computations, and managing memory efficiently within the OpenCV ecosystem. |
67 | |
68 | @{ |
69 | @defgroup core_basic Basic structures |
70 | @defgroup core_array Operations on arrays |
71 | @defgroup core_async Asynchronous API |
72 | @defgroup core_xml XML/YAML/JSON Persistence |
73 | @defgroup core_cluster Clustering |
74 | @defgroup core_utils Utility and system functions and macros |
75 | @{ |
76 | @defgroup core_logging Logging facilities |
77 | @defgroup core_utils_sse SSE utilities |
78 | @defgroup core_utils_neon NEON utilities |
79 | @defgroup core_utils_vsx VSX utilities |
80 | @defgroup core_utils_softfloat Softfloat support |
81 | @defgroup core_utils_samples Utility functions for OpenCV samples |
82 | @} |
83 | @defgroup core_opengl OpenGL interoperability |
84 | @defgroup core_optim Optimization Algorithms |
85 | @defgroup core_directx DirectX interoperability |
86 | @defgroup core_eigen Eigen support |
87 | @defgroup core_opencl OpenCL support |
88 | @defgroup core_va_intel Intel VA-API/OpenCL (CL-VA) interoperability |
89 | @defgroup core_hal Hardware Acceleration Layer |
90 | @{ |
91 | @defgroup core_hal_functions Functions |
92 | @defgroup core_hal_interface Interface |
93 | @defgroup core_hal_intrin Universal intrinsics |
94 | @{ |
95 | @defgroup core_hal_intrin_impl Private implementation helpers |
96 | @} |
97 | @defgroup core_lowlevel_api Low-level API for external libraries / plugins |
98 | @} |
99 | @defgroup core_parallel Parallel Processing |
100 | @{ |
101 | @defgroup core_parallel_backend Parallel backends API |
102 | @} |
103 | @defgroup core_quaternion Quaternion |
104 | @} |
105 | */ |
106 | |
107 | namespace cv { |
108 | |
109 | //! @addtogroup core_utils |
110 | //! @{ |
111 | |
112 | /*! @brief Class passed to an error. |
113 | |
114 | This class encapsulates all or almost all necessary |
115 | information about the error happened in the program. The exception is |
116 | usually constructed and thrown implicitly via CV_Error and CV_Error_ macros. |
117 | @see error |
118 | */ |
119 | class CV_EXPORTS Exception : public std::exception |
120 | { |
121 | public: |
122 | /*! |
123 | Default constructor |
124 | */ |
125 | Exception(); |
126 | /*! |
127 | Full constructor. Normally the constructor is not called explicitly. |
128 | Instead, the macros CV_Error(), CV_Error_() and CV_Assert() are used. |
129 | */ |
130 | Exception(int _code, const String& _err, const String& _func, const String& _file, int _line); |
131 | virtual ~Exception() CV_NOEXCEPT; |
132 | |
133 | /*! |
134 | \return the error description and the context as a text string. |
135 | */ |
136 | virtual const char *what() const CV_NOEXCEPT CV_OVERRIDE; |
137 | void formatMessage(); |
138 | |
139 | String msg; ///< the formatted error message |
140 | |
141 | int code; ///< error code @see CVStatus |
142 | String err; ///< error description |
143 | String func; ///< function name. Available only when the compiler supports getting it |
144 | String file; ///< source file name where the error has occurred |
145 | int line; ///< line number in the source file where the error has occurred |
146 | }; |
147 | |
148 | /*! @brief Signals an error and raises the exception. |
149 | |
150 | By default the function prints information about the error to stderr, |
151 | then it either stops if cv::setBreakOnError() had been called before or raises the exception. |
152 | It is possible to alternate error processing by using #redirectError(). |
153 | @param exc the exception raisen. |
154 | @deprecated drop this version |
155 | */ |
156 | CV_EXPORTS CV_NORETURN void error(const Exception& exc); |
157 | |
158 | enum SortFlags { SORT_EVERY_ROW = 0, //!< each matrix row is sorted independently |
159 | SORT_EVERY_COLUMN = 1, //!< each matrix column is sorted |
160 | //!< independently; this flag and the previous one are |
161 | //!< mutually exclusive. |
162 | SORT_ASCENDING = 0, //!< each matrix row is sorted in the ascending |
163 | //!< order. |
164 | SORT_DESCENDING = 16 //!< each matrix row is sorted in the |
165 | //!< descending order; this flag and the previous one are also |
166 | //!< mutually exclusive. |
167 | }; |
168 | |
169 | //! @} core_utils |
170 | |
171 | //! @addtogroup core_array |
172 | //! @{ |
173 | |
174 | //! Covariation flags |
175 | enum CovarFlags { |
176 | /** The output covariance matrix is calculated as: |
177 | \f[\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} ,...],\f] |
178 | The covariance matrix will be nsamples x nsamples. Such an unusual covariance matrix is used |
179 | for fast PCA of a set of very large vectors (see, for example, the EigenFaces technique for |
180 | face recognition). Eigenvalues of this "scrambled" matrix match the eigenvalues of the true |
181 | covariance matrix. The "true" eigenvectors can be easily calculated from the eigenvectors of |
182 | the "scrambled" covariance matrix. */ |
183 | COVAR_SCRAMBLED = 0, |
184 | /**The output covariance matrix is calculated as: |
185 | \f[\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,\f] |
186 | covar will be a square matrix of the same size as the total number of elements in each input |
187 | vector. One and only one of #COVAR_SCRAMBLED and #COVAR_NORMAL must be specified.*/ |
188 | COVAR_NORMAL = 1, |
189 | /** If the flag is specified, the function does not calculate mean from |
190 | the input vectors but, instead, uses the passed mean vector. This is useful if mean has been |
191 | pre-calculated or known in advance, or if the covariance matrix is calculated by parts. In |
192 | this case, mean is not a mean vector of the input sub-set of vectors but rather the mean |
193 | vector of the whole set.*/ |
194 | COVAR_USE_AVG = 2, |
195 | /** If the flag is specified, the covariance matrix is scaled. In the |
196 | "normal" mode, scale is 1./nsamples . In the "scrambled" mode, scale is the reciprocal of the |
197 | total number of elements in each input vector. By default (if the flag is not specified), the |
198 | covariance matrix is not scaled ( scale=1 ).*/ |
199 | COVAR_SCALE = 4, |
200 | /** If the flag is |
201 | specified, all the input vectors are stored as rows of the samples matrix. mean should be a |
202 | single-row vector in this case.*/ |
203 | COVAR_ROWS = 8, |
204 | /** If the flag is |
205 | specified, all the input vectors are stored as columns of the samples matrix. mean should be a |
206 | single-column vector in this case.*/ |
207 | COVAR_COLS = 16 |
208 | }; |
209 | |
210 | enum ReduceTypes { REDUCE_SUM = 0, //!< the output is the sum of all rows/columns of the matrix. |
211 | REDUCE_AVG = 1, //!< the output is the mean vector of all rows/columns of the matrix. |
212 | REDUCE_MAX = 2, //!< the output is the maximum (column/row-wise) of all rows/columns of the matrix. |
213 | REDUCE_MIN = 3, //!< the output is the minimum (column/row-wise) of all rows/columns of the matrix. |
214 | REDUCE_SUM2 = 4 //!< the output is the sum of all squared rows/columns of the matrix. |
215 | }; |
216 | |
217 | /** @brief Swaps two matrices |
218 | */ |
219 | CV_EXPORTS void swap(Mat& a, Mat& b); |
220 | /** @overload */ |
221 | CV_EXPORTS void swap( UMat& a, UMat& b ); |
222 | |
223 | /** @brief Computes the source location of an extrapolated pixel. |
224 | |
225 | The function computes and returns the coordinate of a donor pixel corresponding to the specified |
226 | extrapolated pixel when using the specified extrapolation border mode. For example, if you use |
227 | cv::BORDER_WRAP mode in the horizontal direction, cv::BORDER_REFLECT_101 in the vertical direction and |
228 | want to compute value of the "virtual" pixel Point(-5, 100) in a floating-point image img, it |
229 | looks like: |
230 | @code{.cpp} |
231 | float val = img.at<float>(borderInterpolate(100, img.rows, cv::BORDER_REFLECT_101), |
232 | borderInterpolate(-5, img.cols, cv::BORDER_WRAP)); |
233 | @endcode |
234 | Normally, the function is not called directly. It is used inside filtering functions and also in |
235 | copyMakeBorder. |
236 | @param p 0-based coordinate of the extrapolated pixel along one of the axes, likely \<0 or \>= len |
237 | @param len Length of the array along the corresponding axis. |
238 | @param borderType Border type, one of the #BorderTypes, except for #BORDER_TRANSPARENT and |
239 | #BORDER_ISOLATED. When borderType==#BORDER_CONSTANT, the function always returns -1, regardless |
240 | of p and len. |
241 | |
242 | @sa copyMakeBorder |
243 | */ |
244 | CV_EXPORTS_W int borderInterpolate(int p, int len, int borderType); |
245 | |
246 | /** @example samples/cpp/tutorial_code/ImgTrans/copyMakeBorder_demo.cpp |
247 | An example using copyMakeBorder function. |
248 | Check @ref tutorial_copyMakeBorder "the corresponding tutorial" for more details |
249 | */ |
250 | |
251 | /** @brief Forms a border around an image. |
252 | |
253 | The function copies the source image into the middle of the destination image. The areas to the |
254 | left, to the right, above and below the copied source image will be filled with extrapolated |
255 | pixels. This is not what filtering functions based on it do (they extrapolate pixels on-fly), but |
256 | what other more complex functions, including your own, may do to simplify image boundary handling. |
257 | |
258 | The function supports the mode when src is already in the middle of dst . In this case, the |
259 | function does not copy src itself but simply constructs the border, for example: |
260 | |
261 | @code{.cpp} |
262 | // let border be the same in all directions |
263 | int border=2; |
264 | // constructs a larger image to fit both the image and the border |
265 | Mat gray_buf(rgb.rows + border*2, rgb.cols + border*2, rgb.depth()); |
266 | // select the middle part of it w/o copying data |
267 | Mat gray(gray_canvas, Rect(border, border, rgb.cols, rgb.rows)); |
268 | // convert image from RGB to grayscale |
269 | cvtColor(rgb, gray, COLOR_RGB2GRAY); |
270 | // form a border in-place |
271 | copyMakeBorder(gray, gray_buf, border, border, |
272 | border, border, BORDER_REPLICATE); |
273 | // now do some custom filtering ... |
274 | ... |
275 | @endcode |
276 | @note When the source image is a part (ROI) of a bigger image, the function will try to use the |
277 | pixels outside of the ROI to form a border. To disable this feature and always do extrapolation, as |
278 | if src was not a ROI, use borderType | #BORDER_ISOLATED. |
279 | |
280 | @param src Source image. |
281 | @param dst Destination image of the same type as src and the size Size(src.cols+left+right, |
282 | src.rows+top+bottom) . |
283 | @param top the top pixels |
284 | @param bottom the bottom pixels |
285 | @param left the left pixels |
286 | @param right Parameter specifying how many pixels in each direction from the source image rectangle |
287 | to extrapolate. For example, top=1, bottom=1, left=1, right=1 mean that 1 pixel-wide border needs |
288 | to be built. |
289 | @param borderType Border type. See borderInterpolate for details. |
290 | @param value Border value if borderType==BORDER_CONSTANT . |
291 | |
292 | @sa borderInterpolate |
293 | */ |
294 | CV_EXPORTS_W void copyMakeBorder(InputArray src, OutputArray dst, |
295 | int top, int bottom, int left, int right, |
296 | int borderType, const Scalar& value = Scalar() ); |
297 | |
298 | /** @brief Calculates the per-element sum of two arrays or an array and a scalar. |
299 | |
300 | The function add calculates: |
301 | - Sum of two arrays when both input arrays have the same size and the same number of channels: |
302 | \f[\texttt{dst}(I) = \texttt{saturate} ( \texttt{src1}(I) + \texttt{src2}(I)) \quad \texttt{if mask}(I) \ne0\f] |
303 | - Sum of an array and a scalar when src2 is constructed from Scalar or has the same number of |
304 | elements as `src1.channels()`: |
305 | \f[\texttt{dst}(I) = \texttt{saturate} ( \texttt{src1}(I) + \texttt{src2} ) \quad \texttt{if mask}(I) \ne0\f] |
306 | - Sum of a scalar and an array when src1 is constructed from Scalar or has the same number of |
307 | elements as `src2.channels()`: |
308 | \f[\texttt{dst}(I) = \texttt{saturate} ( \texttt{src1} + \texttt{src2}(I) ) \quad \texttt{if mask}(I) \ne0\f] |
309 | where `I` is a multi-dimensional index of array elements. In case of multi-channel arrays, each |
310 | channel is processed independently. |
311 | |
312 | The first function in the list above can be replaced with matrix expressions: |
313 | @code{.cpp} |
314 | dst = src1 + src2; |
315 | dst += src1; // equivalent to add(dst, src1, dst); |
316 | @endcode |
317 | The input arrays and the output array can all have the same or different depths. For example, you |
318 | can add a 16-bit unsigned array to a 8-bit signed array and store the sum as a 32-bit |
319 | floating-point array. Depth of the output array is determined by the dtype parameter. In the second |
320 | and third cases above, as well as in the first case, when src1.depth() == src2.depth(), dtype can |
321 | be set to the default -1. In this case, the output array will have the same depth as the input |
322 | array, be it src1, src2 or both. |
323 | @note Saturation is not applied when the output array has the depth CV_32S. You may even get |
324 | result of an incorrect sign in the case of overflow. |
325 | @note (Python) Be careful to difference behaviour between src1/src2 are single number and they are tuple/array. |
326 | `add(src,X)` means `add(src,(X,X,X,X))`. |
327 | `add(src,(X,))` means `add(src,(X,0,0,0))`. |
328 | @param src1 first input array or a scalar. |
329 | @param src2 second input array or a scalar. |
330 | @param dst output array that has the same size and number of channels as the input array(s); the |
331 | depth is defined by dtype or src1/src2. |
332 | @param mask optional operation mask - 8-bit single channel array, that specifies elements of the |
333 | output array to be changed. |
334 | @param dtype optional depth of the output array (see the discussion below). |
335 | @sa subtract, addWeighted, scaleAdd, Mat::convertTo |
336 | */ |
337 | CV_EXPORTS_W void add(InputArray src1, InputArray src2, OutputArray dst, |
338 | InputArray mask = noArray(), int dtype = -1); |
339 | |
340 | /** @brief Calculates the per-element difference between two arrays or array and a scalar. |
341 | |
342 | The function subtract calculates: |
343 | - Difference between two arrays, when both input arrays have the same size and the same number of |
344 | channels: |
345 | \f[\texttt{dst}(I) = \texttt{saturate} ( \texttt{src1}(I) - \texttt{src2}(I)) \quad \texttt{if mask}(I) \ne0\f] |
346 | - Difference between an array and a scalar, when src2 is constructed from Scalar or has the same |
347 | number of elements as `src1.channels()`: |
348 | \f[\texttt{dst}(I) = \texttt{saturate} ( \texttt{src1}(I) - \texttt{src2} ) \quad \texttt{if mask}(I) \ne0\f] |
349 | - Difference between a scalar and an array, when src1 is constructed from Scalar or has the same |
350 | number of elements as `src2.channels()`: |
351 | \f[\texttt{dst}(I) = \texttt{saturate} ( \texttt{src1} - \texttt{src2}(I) ) \quad \texttt{if mask}(I) \ne0\f] |
352 | - The reverse difference between a scalar and an array in the case of `SubRS`: |
353 | \f[\texttt{dst}(I) = \texttt{saturate} ( \texttt{src2} - \texttt{src1}(I) ) \quad \texttt{if mask}(I) \ne0\f] |
354 | where I is a multi-dimensional index of array elements. In case of multi-channel arrays, each |
355 | channel is processed independently. |
356 | |
357 | The first function in the list above can be replaced with matrix expressions: |
358 | @code{.cpp} |
359 | dst = src1 - src2; |
360 | dst -= src1; // equivalent to subtract(dst, src1, dst); |
361 | @endcode |
362 | The input arrays and the output array can all have the same or different depths. For example, you |
363 | can subtract to 8-bit unsigned arrays and store the difference in a 16-bit signed array. Depth of |
364 | the output array is determined by dtype parameter. In the second and third cases above, as well as |
365 | in the first case, when src1.depth() == src2.depth(), dtype can be set to the default -1. In this |
366 | case the output array will have the same depth as the input array, be it src1, src2 or both. |
367 | @note Saturation is not applied when the output array has the depth CV_32S. You may even get |
368 | result of an incorrect sign in the case of overflow. |
369 | @note (Python) Be careful to difference behaviour between src1/src2 are single number and they are tuple/array. |
370 | `subtract(src,X)` means `subtract(src,(X,X,X,X))`. |
371 | `subtract(src,(X,))` means `subtract(src,(X,0,0,0))`. |
372 | @param src1 first input array or a scalar. |
373 | @param src2 second input array or a scalar. |
374 | @param dst output array of the same size and the same number of channels as the input array. |
375 | @param mask optional operation mask; this is an 8-bit single channel array that specifies elements |
376 | of the output array to be changed. |
377 | @param dtype optional depth of the output array |
378 | @sa add, addWeighted, scaleAdd, Mat::convertTo |
379 | */ |
380 | CV_EXPORTS_W void subtract(InputArray src1, InputArray src2, OutputArray dst, |
381 | InputArray mask = noArray(), int dtype = -1); |
382 | |
383 | |
384 | /** @brief Calculates the per-element scaled product of two arrays. |
385 | |
386 | The function multiply calculates the per-element product of two arrays: |
387 | |
388 | \f[\texttt{dst} (I)= \texttt{saturate} ( \texttt{scale} \cdot \texttt{src1} (I) \cdot \texttt{src2} (I))\f] |
389 | |
390 | There is also a @ref MatrixExpressions -friendly variant of the first function. See Mat::mul . |
391 | |
392 | For a not-per-element matrix product, see gemm . |
393 | |
394 | @note Saturation is not applied when the output array has the depth |
395 | CV_32S. You may even get result of an incorrect sign in the case of |
396 | overflow. |
397 | @note (Python) Be careful to difference behaviour between src1/src2 are single number and they are tuple/array. |
398 | `multiply(src,X)` means `multiply(src,(X,X,X,X))`. |
399 | `multiply(src,(X,))` means `multiply(src,(X,0,0,0))`. |
400 | @param src1 first input array. |
401 | @param src2 second input array of the same size and the same type as src1. |
402 | @param dst output array of the same size and type as src1. |
403 | @param scale optional scale factor. |
404 | @param dtype optional depth of the output array |
405 | @sa add, subtract, divide, scaleAdd, addWeighted, accumulate, accumulateProduct, accumulateSquare, |
406 | Mat::convertTo |
407 | */ |
408 | CV_EXPORTS_W void multiply(InputArray src1, InputArray src2, |
409 | OutputArray dst, double scale = 1, int dtype = -1); |
410 | |
411 | /** @brief Performs per-element division of two arrays or a scalar by an array. |
412 | |
413 | The function cv::divide divides one array by another: |
414 | \f[\texttt{dst(I) = saturate(src1(I)*scale/src2(I))}\f] |
415 | or a scalar by an array when there is no src1 : |
416 | \f[\texttt{dst(I) = saturate(scale/src2(I))}\f] |
417 | |
418 | Different channels of multi-channel arrays are processed independently. |
419 | |
420 | For integer types when src2(I) is zero, dst(I) will also be zero. |
421 | |
422 | @note In case of floating point data there is no special defined behavior for zero src2(I) values. |
423 | Regular floating-point division is used. |
424 | Expect correct IEEE-754 behaviour for floating-point data (with NaN, Inf result values). |
425 | |
426 | @note Saturation is not applied when the output array has the depth CV_32S. You may even get |
427 | result of an incorrect sign in the case of overflow. |
428 | @note (Python) Be careful to difference behaviour between src1/src2 are single number and they are tuple/array. |
429 | `divide(src,X)` means `divide(src,(X,X,X,X))`. |
430 | `divide(src,(X,))` means `divide(src,(X,0,0,0))`. |
431 | @param src1 first input array. |
432 | @param src2 second input array of the same size and type as src1. |
433 | @param scale scalar factor. |
434 | @param dst output array of the same size and type as src2. |
435 | @param dtype optional depth of the output array; if -1, dst will have depth src2.depth(), but in |
436 | case of an array-by-array division, you can only pass -1 when src1.depth()==src2.depth(). |
437 | @sa multiply, add, subtract |
438 | */ |
439 | CV_EXPORTS_W void divide(InputArray src1, InputArray src2, OutputArray dst, |
440 | double scale = 1, int dtype = -1); |
441 | |
442 | /** @overload */ |
443 | CV_EXPORTS_W void divide(double scale, InputArray src2, |
444 | OutputArray dst, int dtype = -1); |
445 | |
446 | /** @brief Calculates the sum of a scaled array and another array. |
447 | |
448 | The function scaleAdd is one of the classical primitive linear algebra operations, known as DAXPY |
449 | or SAXPY in [BLAS](http://en.wikipedia.org/wiki/Basic_Linear_Algebra_Subprograms). It calculates |
450 | the sum of a scaled array and another array: |
451 | \f[\texttt{dst} (I)= \texttt{scale} \cdot \texttt{src1} (I) + \texttt{src2} (I)\f] |
452 | The function can also be emulated with a matrix expression, for example: |
453 | @code{.cpp} |
454 | Mat A(3, 3, CV_64F); |
455 | ... |
456 | A.row(0) = A.row(1)*2 + A.row(2); |
457 | @endcode |
458 | @param src1 first input array. |
459 | @param alpha scale factor for the first array. |
460 | @param src2 second input array of the same size and type as src1. |
461 | @param dst output array of the same size and type as src1. |
462 | @sa add, addWeighted, subtract, Mat::dot, Mat::convertTo |
463 | */ |
464 | CV_EXPORTS_W void scaleAdd(InputArray src1, double alpha, InputArray src2, OutputArray dst); |
465 | |
466 | /** @brief Calculates the weighted sum of two arrays. |
467 | |
468 | The function addWeighted calculates the weighted sum of two arrays as follows: |
469 | \f[\texttt{dst} (I)= \texttt{saturate} ( \texttt{src1} (I)* \texttt{alpha} + \texttt{src2} (I)* \texttt{beta} + \texttt{gamma} )\f] |
470 | where I is a multi-dimensional index of array elements. In case of multi-channel arrays, each |
471 | channel is processed independently. |
472 | The function can be replaced with a matrix expression: |
473 | @code{.cpp} |
474 | dst = src1*alpha + src2*beta + gamma; |
475 | @endcode |
476 | @note Saturation is not applied when the output array has the depth CV_32S. You may even get |
477 | result of an incorrect sign in the case of overflow. |
478 | @param src1 first input array. |
479 | @param alpha weight of the first array elements. |
480 | @param src2 second input array of the same size and channel number as src1. |
481 | @param beta weight of the second array elements. |
482 | @param gamma scalar added to each sum. |
483 | @param dst output array that has the same size and number of channels as the input arrays. |
484 | @param dtype optional depth of the output array; when both input arrays have the same depth, dtype |
485 | can be set to -1, which will be equivalent to src1.depth(). |
486 | @sa add, subtract, scaleAdd, Mat::convertTo |
487 | */ |
488 | CV_EXPORTS_W void addWeighted(InputArray src1, double alpha, InputArray src2, |
489 | double beta, double gamma, OutputArray dst, int dtype = -1); |
490 | |
491 | /** @brief Scales, calculates absolute values, and converts the result to 8-bit. |
492 | |
493 | On each element of the input array, the function convertScaleAbs |
494 | performs three operations sequentially: scaling, taking an absolute |
495 | value, conversion to an unsigned 8-bit type: |
496 | \f[\texttt{dst} (I)= \texttt{saturate\_cast<uchar>} (| \texttt{src} (I)* \texttt{alpha} + \texttt{beta} |)\f] |
497 | In case of multi-channel arrays, the function processes each channel |
498 | independently. When the output is not 8-bit, the operation can be |
499 | emulated by calling the Mat::convertTo method (or by using matrix |
500 | expressions) and then by calculating an absolute value of the result. |
501 | For example: |
502 | @code{.cpp} |
503 | Mat_<float> A(30,30); |
504 | randu(A, Scalar(-100), Scalar(100)); |
505 | Mat_<float> B = A*5 + 3; |
506 | B = abs(B); |
507 | // Mat_<float> B = abs(A*5+3) will also do the job, |
508 | // but it will allocate a temporary matrix |
509 | @endcode |
510 | @param src input array. |
511 | @param dst output array. |
512 | @param alpha optional scale factor. |
513 | @param beta optional delta added to the scaled values. |
514 | @sa Mat::convertTo, cv::abs(const Mat&) |
515 | */ |
516 | CV_EXPORTS_W void convertScaleAbs(InputArray src, OutputArray dst, |
517 | double alpha = 1, double beta = 0); |
518 | |
519 | /** @brief Converts an array to half precision floating number. |
520 | |
521 | This function converts FP32 (single precision floating point) from/to FP16 (half precision floating point). CV_16S format is used to represent FP16 data. |
522 | There are two use modes (src -> dst): CV_32F -> CV_16S and CV_16S -> CV_32F. The input array has to have type of CV_32F or |
523 | CV_16S to represent the bit depth. If the input array is neither of them, the function will raise an error. |
524 | The format of half precision floating point is defined in IEEE 754-2008. |
525 | |
526 | @param src input array. |
527 | @param dst output array. |
528 | |
529 | @deprecated Use Mat::convertTo with CV_16F instead. |
530 | */ |
531 | CV_EXPORTS_W void convertFp16(InputArray src, OutputArray dst); |
532 | |
533 | /** @example samples/cpp/tutorial_code/core/how_to_scan_images/how_to_scan_images.cpp |
534 | Check @ref tutorial_how_to_scan_images "the corresponding tutorial" for more details |
535 | */ |
536 | |
537 | /** @brief Performs a look-up table transform of an array. |
538 | |
539 | The function LUT fills the output array with values from the look-up table. Indices of the entries |
540 | are taken from the input array. That is, the function processes each element of src as follows: |
541 | \f[\texttt{dst} (I) \leftarrow \texttt{lut(src(I) + d)}\f] |
542 | where |
543 | \f[d = \fork{0}{if \(\texttt{src}\) has depth \(\texttt{CV_8U}\)}{128}{if \(\texttt{src}\) has depth \(\texttt{CV_8S}\)}\f] |
544 | @param src input array of 8-bit elements. |
545 | @param lut look-up table of 256 elements; in case of multi-channel input array, the table should |
546 | either have a single channel (in this case the same table is used for all channels) or the same |
547 | number of channels as in the input array. |
548 | @param dst output array of the same size and number of channels as src, and the same depth as lut. |
549 | @sa convertScaleAbs, Mat::convertTo |
550 | */ |
551 | CV_EXPORTS_W void LUT(InputArray src, InputArray lut, OutputArray dst); |
552 | |
553 | /** @brief Calculates the sum of array elements. |
554 | |
555 | The function cv::sum calculates and returns the sum of array elements, |
556 | independently for each channel. |
557 | @param src input array that must have from 1 to 4 channels. |
558 | @sa countNonZero, mean, meanStdDev, norm, minMaxLoc, reduce |
559 | */ |
560 | CV_EXPORTS_AS(sumElems) Scalar sum(InputArray src); |
561 | |
562 | /** @brief Checks for the presence of at least one non-zero array element. |
563 | |
564 | The function returns whether there are non-zero elements in src |
565 | |
566 | The function do not work with multi-channel arrays. If you need to check non-zero array |
567 | elements across all the channels, use Mat::reshape first to reinterpret the array as |
568 | single-channel. Or you may extract the particular channel using either extractImageCOI, or |
569 | mixChannels, or split. |
570 | |
571 | @note |
572 | - If the location of non-zero array elements is important, @ref findNonZero is helpful. |
573 | - If the count of non-zero array elements is important, @ref countNonZero is helpful. |
574 | @param src single-channel array. |
575 | @sa mean, meanStdDev, norm, minMaxLoc, calcCovarMatrix |
576 | @sa findNonZero, countNonZero |
577 | */ |
578 | CV_EXPORTS_W bool hasNonZero( InputArray src ); |
579 | |
580 | /** @brief Counts non-zero array elements. |
581 | |
582 | The function returns the number of non-zero elements in src : |
583 | \f[\sum _{I: \; \texttt{src} (I) \ne0 } 1\f] |
584 | |
585 | The function do not work with multi-channel arrays. If you need to count non-zero array |
586 | elements across all the channels, use Mat::reshape first to reinterpret the array as |
587 | single-channel. Or you may extract the particular channel using either extractImageCOI, or |
588 | mixChannels, or split. |
589 | |
590 | @note |
591 | - If only whether there are non-zero elements is important, @ref hasNonZero is helpful. |
592 | - If the location of non-zero array elements is important, @ref findNonZero is helpful. |
593 | @param src single-channel array. |
594 | @sa mean, meanStdDev, norm, minMaxLoc, calcCovarMatrix |
595 | @sa findNonZero, hasNonZero |
596 | */ |
597 | CV_EXPORTS_W int countNonZero( InputArray src ); |
598 | |
599 | /** @brief Returns the list of locations of non-zero pixels |
600 | |
601 | Given a binary matrix (likely returned from an operation such |
602 | as threshold(), compare(), >, ==, etc, return all of |
603 | the non-zero indices as a cv::Mat or std::vector<cv::Point> (x,y) |
604 | For example: |
605 | @code{.cpp} |
606 | cv::Mat binaryImage; // input, binary image |
607 | cv::Mat locations; // output, locations of non-zero pixels |
608 | cv::findNonZero(binaryImage, locations); |
609 | |
610 | // access pixel coordinates |
611 | Point pnt = locations.at<Point>(i); |
612 | @endcode |
613 | or |
614 | @code{.cpp} |
615 | cv::Mat binaryImage; // input, binary image |
616 | vector<Point> locations; // output, locations of non-zero pixels |
617 | cv::findNonZero(binaryImage, locations); |
618 | |
619 | // access pixel coordinates |
620 | Point pnt = locations[i]; |
621 | @endcode |
622 | |
623 | The function do not work with multi-channel arrays. If you need to find non-zero |
624 | elements across all the channels, use Mat::reshape first to reinterpret the array as |
625 | single-channel. Or you may extract the particular channel using either extractImageCOI, or |
626 | mixChannels, or split. |
627 | |
628 | @note |
629 | - If only count of non-zero array elements is important, @ref countNonZero is helpful. |
630 | - If only whether there are non-zero elements is important, @ref hasNonZero is helpful. |
631 | @param src single-channel array |
632 | @param idx the output array, type of cv::Mat or std::vector<Point>, corresponding to non-zero indices in the input |
633 | @sa countNonZero, hasNonZero |
634 | */ |
635 | CV_EXPORTS_W void findNonZero( InputArray src, OutputArray idx ); |
636 | |
637 | /** @brief Calculates an average (mean) of array elements. |
638 | |
639 | The function cv::mean calculates the mean value M of array elements, |
640 | independently for each channel, and return it: |
641 | \f[\begin{array}{l} N = \sum _{I: \; \texttt{mask} (I) \ne 0} 1 \\ M_c = \left ( \sum _{I: \; \texttt{mask} (I) \ne 0}{ \texttt{mtx} (I)_c} \right )/N \end{array}\f] |
642 | When all the mask elements are 0's, the function returns Scalar::all(0) |
643 | @param src input array that should have from 1 to 4 channels so that the result can be stored in |
644 | Scalar_ . |
645 | @param mask optional operation mask. |
646 | @sa countNonZero, meanStdDev, norm, minMaxLoc |
647 | */ |
648 | CV_EXPORTS_W Scalar mean(InputArray src, InputArray mask = noArray()); |
649 | |
650 | /** Calculates a mean and standard deviation of array elements. |
651 | |
652 | The function cv::meanStdDev calculates the mean and the standard deviation M |
653 | of array elements independently for each channel and returns it via the |
654 | output parameters: |
655 | \f[\begin{array}{l} N = \sum _{I, \texttt{mask} (I) \ne 0} 1 \\ \texttt{mean} _c = \frac{\sum_{ I: \; \texttt{mask}(I) \ne 0} \texttt{src} (I)_c}{N} \\ \texttt{stddev} _c = \sqrt{\frac{\sum_{ I: \; \texttt{mask}(I) \ne 0} \left ( \texttt{src} (I)_c - \texttt{mean} _c \right )^2}{N}} \end{array}\f] |
656 | When all the mask elements are 0's, the function returns |
657 | mean=stddev=Scalar::all(0). |
658 | @note The calculated standard deviation is only the diagonal of the |
659 | complete normalized covariance matrix. If the full matrix is needed, you |
660 | can reshape the multi-channel array M x N to the single-channel array |
661 | M\*N x mtx.channels() (only possible when the matrix is continuous) and |
662 | then pass the matrix to calcCovarMatrix . |
663 | @param src input array that should have from 1 to 4 channels so that the results can be stored in |
664 | Scalar_ 's. |
665 | @param mean output parameter: calculated mean value. |
666 | @param stddev output parameter: calculated standard deviation. |
667 | @param mask optional operation mask. |
668 | @sa countNonZero, mean, norm, minMaxLoc, calcCovarMatrix |
669 | */ |
670 | CV_EXPORTS_W void meanStdDev(InputArray src, OutputArray mean, OutputArray stddev, |
671 | InputArray mask=noArray()); |
672 | |
673 | /** @brief Calculates the absolute norm of an array. |
674 | |
675 | This version of #norm calculates the absolute norm of src1. The type of norm to calculate is specified using #NormTypes. |
676 | |
677 | As example for one array consider the function \f$r(x)= \begin{pmatrix} x \\ 1-x \end{pmatrix}, x \in [-1;1]\f$. |
678 | The \f$ L_{1}, L_{2} \f$ and \f$ L_{\infty} \f$ norm for the sample value \f$r(-1) = \begin{pmatrix} -1 \\ 2 \end{pmatrix}\f$ |
679 | is calculated as follows |
680 | \f{align*} |
681 | \| r(-1) \|_{L_1} &= |-1| + |2| = 3 \\ |
682 | \| r(-1) \|_{L_2} &= \sqrt{(-1)^{2} + (2)^{2}} = \sqrt{5} \\ |
683 | \| r(-1) \|_{L_\infty} &= \max(|-1|,|2|) = 2 |
684 | \f} |
685 | and for \f$r(0.5) = \begin{pmatrix} 0.5 \\ 0.5 \end{pmatrix}\f$ the calculation is |
686 | \f{align*} |
687 | \| r(0.5) \|_{L_1} &= |0.5| + |0.5| = 1 \\ |
688 | \| r(0.5) \|_{L_2} &= \sqrt{(0.5)^{2} + (0.5)^{2}} = \sqrt{0.5} \\ |
689 | \| r(0.5) \|_{L_\infty} &= \max(|0.5|,|0.5|) = 0.5. |
690 | \f} |
691 | The following graphic shows all values for the three norm functions \f$\| r(x) \|_{L_1}, \| r(x) \|_{L_2}\f$ and \f$\| r(x) \|_{L_\infty}\f$. |
692 | It is notable that the \f$ L_{1} \f$ norm forms the upper and the \f$ L_{\infty} \f$ norm forms the lower border for the example function \f$ r(x) \f$. |
693 |  |
694 | |
695 | When the mask parameter is specified and it is not empty, the norm is |
696 | |
697 | If normType is not specified, #NORM_L2 is used. |
698 | calculated only over the region specified by the mask. |
699 | |
700 | Multi-channel input arrays are treated as single-channel arrays, that is, |
701 | the results for all channels are combined. |
702 | |
703 | Hamming norms can only be calculated with CV_8U depth arrays. |
704 | |
705 | @param src1 first input array. |
706 | @param normType type of the norm (see #NormTypes). |
707 | @param mask optional operation mask; it must have the same size as src1 and CV_8UC1 type. |
708 | */ |
709 | CV_EXPORTS_W double norm(InputArray src1, int normType = NORM_L2, InputArray mask = noArray()); |
710 | |
711 | /** @brief Calculates an absolute difference norm or a relative difference norm. |
712 | |
713 | This version of cv::norm calculates the absolute difference norm |
714 | or the relative difference norm of arrays src1 and src2. |
715 | The type of norm to calculate is specified using #NormTypes. |
716 | |
717 | @param src1 first input array. |
718 | @param src2 second input array of the same size and the same type as src1. |
719 | @param normType type of the norm (see #NormTypes). |
720 | @param mask optional operation mask; it must have the same size as src1 and CV_8UC1 type. |
721 | */ |
722 | CV_EXPORTS_W double norm(InputArray src1, InputArray src2, |
723 | int normType = NORM_L2, InputArray mask = noArray()); |
724 | /** @overload |
725 | @param src first input array. |
726 | @param normType type of the norm (see #NormTypes). |
727 | */ |
728 | CV_EXPORTS double norm( const SparseMat& src, int normType ); |
729 | |
730 | /** @brief Computes the Peak Signal-to-Noise Ratio (PSNR) image quality metric. |
731 | |
732 | This function calculates the Peak Signal-to-Noise Ratio (PSNR) image quality metric in decibels (dB), |
733 | between two input arrays src1 and src2. The arrays must have the same type. |
734 | |
735 | The PSNR is calculated as follows: |
736 | |
737 | \f[ |
738 | \texttt{PSNR} = 10 \cdot \log_{10}{\left( \frac{R^2}{MSE} \right) } |
739 | \f] |
740 | |
741 | where R is the maximum integer value of depth (e.g. 255 in the case of CV_8U data) |
742 | and MSE is the mean squared error between the two arrays. |
743 | |
744 | @param src1 first input array. |
745 | @param src2 second input array of the same size as src1. |
746 | @param R the maximum pixel value (255 by default) |
747 | |
748 | */ |
749 | CV_EXPORTS_W double PSNR(InputArray src1, InputArray src2, double R=255.); |
750 | |
751 | /** @brief naive nearest neighbor finder |
752 | |
753 | see http://en.wikipedia.org/wiki/Nearest_neighbor_search |
754 | @todo document |
755 | */ |
756 | CV_EXPORTS_W void batchDistance(InputArray src1, InputArray src2, |
757 | OutputArray dist, int dtype, OutputArray nidx, |
758 | int normType = NORM_L2, int K = 0, |
759 | InputArray mask = noArray(), int update = 0, |
760 | bool crosscheck = false); |
761 | |
762 | /** @brief Normalizes the norm or value range of an array. |
763 | |
764 | The function cv::normalize normalizes scale and shift the input array elements so that |
765 | \f[\| \texttt{dst} \| _{L_p}= \texttt{alpha}\f] |
766 | (where p=Inf, 1 or 2) when normType=NORM_INF, NORM_L1, or NORM_L2, respectively; or so that |
767 | \f[\min _I \texttt{dst} (I)= \texttt{alpha} , \, \, \max _I \texttt{dst} (I)= \texttt{beta}\f] |
768 | |
769 | when normType=NORM_MINMAX (for dense arrays only). The optional mask specifies a sub-array to be |
770 | normalized. This means that the norm or min-n-max are calculated over the sub-array, and then this |
771 | sub-array is modified to be normalized. If you want to only use the mask to calculate the norm or |
772 | min-max but modify the whole array, you can use norm and Mat::convertTo. |
773 | |
774 | In case of sparse matrices, only the non-zero values are analyzed and transformed. Because of this, |
775 | the range transformation for sparse matrices is not allowed since it can shift the zero level. |
776 | |
777 | Possible usage with some positive example data: |
778 | @code{.cpp} |
779 | vector<double> positiveData = { 2.0, 8.0, 10.0 }; |
780 | vector<double> normalizedData_l1, normalizedData_l2, normalizedData_inf, normalizedData_minmax; |
781 | |
782 | // Norm to probability (total count) |
783 | // sum(numbers) = 20.0 |
784 | // 2.0 0.1 (2.0/20.0) |
785 | // 8.0 0.4 (8.0/20.0) |
786 | // 10.0 0.5 (10.0/20.0) |
787 | normalize(positiveData, normalizedData_l1, 1.0, 0.0, NORM_L1); |
788 | |
789 | // Norm to unit vector: ||positiveData|| = 1.0 |
790 | // 2.0 0.15 |
791 | // 8.0 0.62 |
792 | // 10.0 0.77 |
793 | normalize(positiveData, normalizedData_l2, 1.0, 0.0, NORM_L2); |
794 | |
795 | // Norm to max element |
796 | // 2.0 0.2 (2.0/10.0) |
797 | // 8.0 0.8 (8.0/10.0) |
798 | // 10.0 1.0 (10.0/10.0) |
799 | normalize(positiveData, normalizedData_inf, 1.0, 0.0, NORM_INF); |
800 | |
801 | // Norm to range [0.0;1.0] |
802 | // 2.0 0.0 (shift to left border) |
803 | // 8.0 0.75 (6.0/8.0) |
804 | // 10.0 1.0 (shift to right border) |
805 | normalize(positiveData, normalizedData_minmax, 1.0, 0.0, NORM_MINMAX); |
806 | @endcode |
807 | |
808 | @param src input array. |
809 | @param dst output array of the same size as src . |
810 | @param alpha norm value to normalize to or the lower range boundary in case of the range |
811 | normalization. |
812 | @param beta upper range boundary in case of the range normalization; it is not used for the norm |
813 | normalization. |
814 | @param norm_type normalization type (see cv::NormTypes). |
815 | @param dtype when negative, the output array has the same type as src; otherwise, it has the same |
816 | number of channels as src and the depth =CV_MAT_DEPTH(dtype). |
817 | @param mask optional operation mask. |
818 | @sa norm, Mat::convertTo, SparseMat::convertTo |
819 | */ |
820 | CV_EXPORTS_W void normalize( InputArray src, InputOutputArray dst, double alpha = 1, double beta = 0, |
821 | int norm_type = NORM_L2, int dtype = -1, InputArray mask = noArray()); |
822 | |
823 | /** @overload |
824 | @param src input array. |
825 | @param dst output array of the same size as src . |
826 | @param alpha norm value to normalize to or the lower range boundary in case of the range |
827 | normalization. |
828 | @param normType normalization type (see cv::NormTypes). |
829 | */ |
830 | CV_EXPORTS void normalize( const SparseMat& src, SparseMat& dst, double alpha, int normType ); |
831 | |
832 | /** @brief Finds the global minimum and maximum in an array. |
833 | |
834 | The function cv::minMaxLoc finds the minimum and maximum element values and their positions. The |
835 | extrema are searched across the whole array or, if mask is not an empty array, in the specified |
836 | array region. |
837 | |
838 | In C++, if the input is multi-channel, you should omit the minLoc, maxLoc, and mask arguments |
839 | (i.e. leave them as NULL, NULL, and noArray() respectively). These arguments are not |
840 | supported for multi-channel input arrays. If working with multi-channel input and you |
841 | need the minLoc, maxLoc, or mask arguments, then use Mat::reshape first to reinterpret |
842 | the array as single-channel. Alternatively, you can extract the particular channel using either |
843 | extractImageCOI, mixChannels, or split. |
844 | |
845 | In Python, multi-channel input is not supported at all due to a limitation in the |
846 | binding generation process (there is no way to set minLoc and maxLoc to NULL). A |
847 | workaround is to operate on each channel individually or to use NumPy to achieve the same |
848 | functionality. |
849 | |
850 | @param src input single-channel array. |
851 | @param minVal pointer to the returned minimum value; NULL is used if not required. |
852 | @param maxVal pointer to the returned maximum value; NULL is used if not required. |
853 | @param minLoc pointer to the returned minimum location (in 2D case); NULL is used if not required. |
854 | @param maxLoc pointer to the returned maximum location (in 2D case); NULL is used if not required. |
855 | @param mask optional mask used to select a sub-array. |
856 | @sa max, min, reduceArgMin, reduceArgMax, compare, inRange, extractImageCOI, mixChannels, split, Mat::reshape |
857 | */ |
858 | CV_EXPORTS_W void minMaxLoc(InputArray src, CV_OUT double* minVal, |
859 | CV_OUT double* maxVal = 0, CV_OUT Point* minLoc = 0, |
860 | CV_OUT Point* maxLoc = 0, InputArray mask = noArray()); |
861 | |
862 | /** |
863 | * @brief Finds indices of min elements along provided axis |
864 | * |
865 | * @note |
866 | * - If input or output array is not continuous, this function will create an internal copy. |
867 | * - NaN handling is left unspecified, see patchNaNs(). |
868 | * - The returned index is always in bounds of input matrix. |
869 | * |
870 | * @param src input single-channel array. |
871 | * @param dst output array of type CV_32SC1 with the same dimensionality as src, |
872 | * except for axis being reduced - it should be set to 1. |
873 | * @param lastIndex whether to get the index of first or last occurrence of min. |
874 | * @param axis axis to reduce along. |
875 | * @sa reduceArgMax, minMaxLoc, min, max, compare, reduce |
876 | */ |
877 | CV_EXPORTS_W void reduceArgMin(InputArray src, OutputArray dst, int axis, bool lastIndex = false); |
878 | |
879 | /** |
880 | * @brief Finds indices of max elements along provided axis |
881 | * |
882 | * @note |
883 | * - If input or output array is not continuous, this function will create an internal copy. |
884 | * - NaN handling is left unspecified, see patchNaNs(). |
885 | * - The returned index is always in bounds of input matrix. |
886 | * |
887 | * @param src input single-channel array. |
888 | * @param dst output array of type CV_32SC1 with the same dimensionality as src, |
889 | * except for axis being reduced - it should be set to 1. |
890 | * @param lastIndex whether to get the index of first or last occurrence of max. |
891 | * @param axis axis to reduce along. |
892 | * @sa reduceArgMin, minMaxLoc, min, max, compare, reduce |
893 | */ |
894 | CV_EXPORTS_W void reduceArgMax(InputArray src, OutputArray dst, int axis, bool lastIndex = false); |
895 | |
896 | /** @brief Finds the global minimum and maximum in an array |
897 | |
898 | The function cv::minMaxIdx finds the minimum and maximum element values and their positions. The |
899 | extremums are searched across the whole array or, if mask is not an empty array, in the specified |
900 | array region. In case of a sparse matrix, the minimum is found among non-zero elements |
901 | only. Multi-channel input is supported without mask and extremums indexes (should be nullptr). |
902 | @note When minIdx is not NULL, it must have at least 2 elements (as well as maxIdx), even if src is |
903 | a single-row or single-column matrix. In OpenCV (following MATLAB) each array has at least 2 |
904 | dimensions, i.e. single-column matrix is Mx1 matrix (and therefore minIdx/maxIdx will be |
905 | (i1,0)/(i2,0)) and single-row matrix is 1xN matrix (and therefore minIdx/maxIdx will be |
906 | (0,j1)/(0,j2)). |
907 | @param src input single-channel array. |
908 | @param minVal pointer to the returned minimum value; NULL is used if not required. |
909 | @param maxVal pointer to the returned maximum value; NULL is used if not required. |
910 | @param minIdx pointer to the returned minimum location (in nD case); NULL is used if not required; |
911 | Otherwise, it must point to an array of src.dims elements, the coordinates of the minimum element |
912 | in each dimension are stored there sequentially. |
913 | @param maxIdx pointer to the returned maximum location (in nD case). NULL is used if not required. |
914 | @param mask specified array region |
915 | */ |
916 | CV_EXPORTS void minMaxIdx(InputArray src, double* minVal, double* maxVal = 0, |
917 | int* minIdx = 0, int* maxIdx = 0, InputArray mask = noArray()); |
918 | |
919 | /** @overload |
920 | @param a input single-channel array. |
921 | @param minVal pointer to the returned minimum value; NULL is used if not required. |
922 | @param maxVal pointer to the returned maximum value; NULL is used if not required. |
923 | @param minIdx pointer to the returned minimum location (in nD case); NULL is used if not required; |
924 | Otherwise, it must point to an array of src.dims elements, the coordinates of the minimum element |
925 | in each dimension are stored there sequentially. |
926 | @param maxIdx pointer to the returned maximum location (in nD case). NULL is used if not required. |
927 | */ |
928 | CV_EXPORTS void minMaxLoc(const SparseMat& a, double* minVal, |
929 | double* maxVal, int* minIdx = 0, int* maxIdx = 0); |
930 | |
931 | /** @brief Reduces a matrix to a vector. |
932 | |
933 | The function #reduce reduces the matrix to a vector by treating the matrix rows/columns as a set of |
934 | 1D vectors and performing the specified operation on the vectors until a single row/column is |
935 | obtained. For example, the function can be used to compute horizontal and vertical projections of a |
936 | raster image. In case of #REDUCE_MAX and #REDUCE_MIN, the output image should have the same type as the source one. |
937 | In case of #REDUCE_SUM, #REDUCE_SUM2 and #REDUCE_AVG, the output may have a larger element bit-depth to preserve accuracy. |
938 | And multi-channel arrays are also supported in these two reduction modes. |
939 | |
940 | The following code demonstrates its usage for a single channel matrix. |
941 | @snippet snippets/core_reduce.cpp example |
942 | |
943 | And the following code demonstrates its usage for a two-channel matrix. |
944 | @snippet snippets/core_reduce.cpp example2 |
945 | |
946 | @param src input 2D matrix. |
947 | @param dst output vector. Its size and type is defined by dim and dtype parameters. |
948 | @param dim dimension index along which the matrix is reduced. 0 means that the matrix is reduced to |
949 | a single row. 1 means that the matrix is reduced to a single column. |
950 | @param rtype reduction operation that could be one of #ReduceTypes |
951 | @param dtype when negative, the output vector will have the same type as the input matrix, |
952 | otherwise, its type will be CV_MAKE_TYPE(CV_MAT_DEPTH(dtype), src.channels()). |
953 | @sa repeat, reduceArgMin, reduceArgMax |
954 | */ |
955 | CV_EXPORTS_W void reduce(InputArray src, OutputArray dst, int dim, int rtype, int dtype = -1); |
956 | |
957 | /** @brief Creates one multi-channel array out of several single-channel ones. |
958 | |
959 | The function cv::merge merges several arrays to make a single multi-channel array. That is, each |
960 | element of the output array will be a concatenation of the elements of the input arrays, where |
961 | elements of i-th input array are treated as mv[i].channels()-element vectors. |
962 | |
963 | The function cv::split does the reverse operation. If you need to shuffle channels in some other |
964 | advanced way, use cv::mixChannels. |
965 | |
966 | The following example shows how to merge 3 single channel matrices into a single 3-channel matrix. |
967 | @snippet snippets/core_merge.cpp example |
968 | |
969 | @param mv input array of matrices to be merged; all the matrices in mv must have the same |
970 | size and the same depth. |
971 | @param count number of input matrices when mv is a plain C array; it must be greater than zero. |
972 | @param dst output array of the same size and the same depth as mv[0]; The number of channels will |
973 | be equal to the parameter count. |
974 | @sa mixChannels, split, Mat::reshape |
975 | */ |
976 | CV_EXPORTS void merge(const Mat* mv, size_t count, OutputArray dst); |
977 | |
978 | /** @overload |
979 | @param mv input vector of matrices to be merged; all the matrices in mv must have the same |
980 | size and the same depth. |
981 | @param dst output array of the same size and the same depth as mv[0]; The number of channels will |
982 | be the total number of channels in the matrix array. |
983 | */ |
984 | CV_EXPORTS_W void merge(InputArrayOfArrays mv, OutputArray dst); |
985 | |
986 | /** @brief Divides a multi-channel array into several single-channel arrays. |
987 | |
988 | The function cv::split splits a multi-channel array into separate single-channel arrays: |
989 | \f[\texttt{mv} [c](I) = \texttt{src} (I)_c\f] |
990 | If you need to extract a single channel or do some other sophisticated channel permutation, use |
991 | mixChannels. |
992 | |
993 | The following example demonstrates how to split a 3-channel matrix into 3 single channel matrices. |
994 | @snippet snippets/core_split.cpp example |
995 | |
996 | @param src input multi-channel array. |
997 | @param mvbegin output array; the number of arrays must match src.channels(); the arrays themselves are |
998 | reallocated, if needed. |
999 | @sa merge, mixChannels, cvtColor |
1000 | */ |
1001 | CV_EXPORTS void split(const Mat& src, Mat* mvbegin); |
1002 | |
1003 | /** @overload |
1004 | @param m input multi-channel array. |
1005 | @param mv output vector of arrays; the arrays themselves are reallocated, if needed. |
1006 | */ |
1007 | CV_EXPORTS_W void split(InputArray m, OutputArrayOfArrays mv); |
1008 | |
1009 | /** @brief Copies specified channels from input arrays to the specified channels of |
1010 | output arrays. |
1011 | |
1012 | The function cv::mixChannels provides an advanced mechanism for shuffling image channels. |
1013 | |
1014 | cv::split,cv::merge,cv::extractChannel,cv::insertChannel and some forms of cv::cvtColor are partial cases of cv::mixChannels. |
1015 | |
1016 | In the example below, the code splits a 4-channel BGRA image into a 3-channel BGR (with B and R |
1017 | channels swapped) and a separate alpha-channel image: |
1018 | @code{.cpp} |
1019 | Mat bgra( 100, 100, CV_8UC4, Scalar(255,0,0,255) ); |
1020 | Mat bgr( bgra.rows, bgra.cols, CV_8UC3 ); |
1021 | Mat alpha( bgra.rows, bgra.cols, CV_8UC1 ); |
1022 | |
1023 | // forming an array of matrices is a quite efficient operation, |
1024 | // because the matrix data is not copied, only the headers |
1025 | Mat out[] = { bgr, alpha }; |
1026 | // bgra[0] -> bgr[2], bgra[1] -> bgr[1], |
1027 | // bgra[2] -> bgr[0], bgra[3] -> alpha[0] |
1028 | int from_to[] = { 0,2, 1,1, 2,0, 3,3 }; |
1029 | mixChannels( &bgra, 1, out, 2, from_to, 4 ); |
1030 | @endcode |
1031 | @note Unlike many other new-style C++ functions in OpenCV (see the introduction section and |
1032 | Mat::create ), cv::mixChannels requires the output arrays to be pre-allocated before calling the |
1033 | function. |
1034 | @param src input array or vector of matrices; all of the matrices must have the same size and the |
1035 | same depth. |
1036 | @param nsrcs number of matrices in `src`. |
1037 | @param dst output array or vector of matrices; all the matrices **must be allocated**; their size and |
1038 | depth must be the same as in `src[0]`. |
1039 | @param ndsts number of matrices in `dst`. |
1040 | @param fromTo array of index pairs specifying which channels are copied and where; fromTo[k\*2] is |
1041 | a 0-based index of the input channel in src, fromTo[k\*2+1] is an index of the output channel in |
1042 | dst; the continuous channel numbering is used: the first input image channels are indexed from 0 to |
1043 | src[0].channels()-1, the second input image channels are indexed from src[0].channels() to |
1044 | src[0].channels() + src[1].channels()-1, and so on, the same scheme is used for the output image |
1045 | channels; as a special case, when fromTo[k\*2] is negative, the corresponding output channel is |
1046 | filled with zero . |
1047 | @param npairs number of index pairs in `fromTo`. |
1048 | @sa split, merge, extractChannel, insertChannel, cvtColor |
1049 | */ |
1050 | CV_EXPORTS void mixChannels(const Mat* src, size_t nsrcs, Mat* dst, size_t ndsts, |
1051 | const int* fromTo, size_t npairs); |
1052 | |
1053 | /** @overload |
1054 | @param src input array or vector of matrices; all of the matrices must have the same size and the |
1055 | same depth. |
1056 | @param dst output array or vector of matrices; all the matrices **must be allocated**; their size and |
1057 | depth must be the same as in src[0]. |
1058 | @param fromTo array of index pairs specifying which channels are copied and where; fromTo[k\*2] is |
1059 | a 0-based index of the input channel in src, fromTo[k\*2+1] is an index of the output channel in |
1060 | dst; the continuous channel numbering is used: the first input image channels are indexed from 0 to |
1061 | src[0].channels()-1, the second input image channels are indexed from src[0].channels() to |
1062 | src[0].channels() + src[1].channels()-1, and so on, the same scheme is used for the output image |
1063 | channels; as a special case, when fromTo[k\*2] is negative, the corresponding output channel is |
1064 | filled with zero . |
1065 | @param npairs number of index pairs in fromTo. |
1066 | */ |
1067 | CV_EXPORTS void mixChannels(InputArrayOfArrays src, InputOutputArrayOfArrays dst, |
1068 | const int* fromTo, size_t npairs); |
1069 | |
1070 | /** @overload |
1071 | @param src input array or vector of matrices; all of the matrices must have the same size and the |
1072 | same depth. |
1073 | @param dst output array or vector of matrices; all the matrices **must be allocated**; their size and |
1074 | depth must be the same as in src[0]. |
1075 | @param fromTo array of index pairs specifying which channels are copied and where; fromTo[k\*2] is |
1076 | a 0-based index of the input channel in src, fromTo[k\*2+1] is an index of the output channel in |
1077 | dst; the continuous channel numbering is used: the first input image channels are indexed from 0 to |
1078 | src[0].channels()-1, the second input image channels are indexed from src[0].channels() to |
1079 | src[0].channels() + src[1].channels()-1, and so on, the same scheme is used for the output image |
1080 | channels; as a special case, when fromTo[k\*2] is negative, the corresponding output channel is |
1081 | filled with zero . |
1082 | */ |
1083 | CV_EXPORTS_W void mixChannels(InputArrayOfArrays src, InputOutputArrayOfArrays dst, |
1084 | const std::vector<int>& fromTo); |
1085 | |
1086 | /** @brief Extracts a single channel from src (coi is 0-based index) |
1087 | @param src input array |
1088 | @param dst output array |
1089 | @param coi index of channel to extract |
1090 | @sa mixChannels, split |
1091 | */ |
1092 | CV_EXPORTS_W void (InputArray src, OutputArray dst, int coi); |
1093 | |
1094 | /** @brief Inserts a single channel to dst (coi is 0-based index) |
1095 | @param src input array |
1096 | @param dst output array |
1097 | @param coi index of channel for insertion |
1098 | @sa mixChannels, merge |
1099 | */ |
1100 | CV_EXPORTS_W void insertChannel(InputArray src, InputOutputArray dst, int coi); |
1101 | |
1102 | /** @brief Flips a 2D array around vertical, horizontal, or both axes. |
1103 | |
1104 | The function cv::flip flips the array in one of three different ways (row |
1105 | and column indices are 0-based): |
1106 | \f[\texttt{dst} _{ij} = |
1107 | \left\{ |
1108 | \begin{array}{l l} |
1109 | \texttt{src} _{\texttt{src.rows}-i-1,j} & if\; \texttt{flipCode} = 0 \\ |
1110 | \texttt{src} _{i, \texttt{src.cols} -j-1} & if\; \texttt{flipCode} > 0 \\ |
1111 | \texttt{src} _{ \texttt{src.rows} -i-1, \texttt{src.cols} -j-1} & if\; \texttt{flipCode} < 0 \\ |
1112 | \end{array} |
1113 | \right.\f] |
1114 | The example scenarios of using the function are the following: |
1115 | * Vertical flipping of the image (flipCode == 0) to switch between |
1116 | top-left and bottom-left image origin. This is a typical operation |
1117 | in video processing on Microsoft Windows\* OS. |
1118 | * Horizontal flipping of the image with the subsequent horizontal |
1119 | shift and absolute difference calculation to check for a |
1120 | vertical-axis symmetry (flipCode \> 0). |
1121 | * Simultaneous horizontal and vertical flipping of the image with |
1122 | the subsequent shift and absolute difference calculation to check |
1123 | for a central symmetry (flipCode \< 0). |
1124 | * Reversing the order of point arrays (flipCode \> 0 or |
1125 | flipCode == 0). |
1126 | @param src input array. |
1127 | @param dst output array of the same size and type as src. |
1128 | @param flipCode a flag to specify how to flip the array; 0 means |
1129 | flipping around the x-axis and positive value (for example, 1) means |
1130 | flipping around y-axis. Negative value (for example, -1) means flipping |
1131 | around both axes. |
1132 | @sa transpose, repeat, completeSymm |
1133 | */ |
1134 | CV_EXPORTS_W void flip(InputArray src, OutputArray dst, int flipCode); |
1135 | |
1136 | /** @brief Flips a n-dimensional at given axis |
1137 | * @param src input array |
1138 | * @param dst output array that has the same shape of src |
1139 | * @param axis axis that performs a flip on. 0 <= axis < src.dims. |
1140 | */ |
1141 | CV_EXPORTS_W void flipND(InputArray src, OutputArray dst, int axis); |
1142 | |
1143 | /** @brief Broadcast the given Mat to the given shape. |
1144 | * @param src input array |
1145 | * @param shape target shape. Should be a list of CV_32S numbers. Note that negative values are not supported. |
1146 | * @param dst output array that has the given shape |
1147 | */ |
1148 | CV_EXPORTS_W void broadcast(InputArray src, InputArray shape, OutputArray dst); |
1149 | |
1150 | enum RotateFlags { |
1151 | ROTATE_90_CLOCKWISE = 0, //!<Rotate 90 degrees clockwise |
1152 | ROTATE_180 = 1, //!<Rotate 180 degrees clockwise |
1153 | ROTATE_90_COUNTERCLOCKWISE = 2, //!<Rotate 270 degrees clockwise |
1154 | }; |
1155 | /** @brief Rotates a 2D array in multiples of 90 degrees. |
1156 | The function cv::rotate rotates the array in one of three different ways: |
1157 | * Rotate by 90 degrees clockwise (rotateCode = ROTATE_90_CLOCKWISE). |
1158 | * Rotate by 180 degrees clockwise (rotateCode = ROTATE_180). |
1159 | * Rotate by 270 degrees clockwise (rotateCode = ROTATE_90_COUNTERCLOCKWISE). |
1160 | @param src input array. |
1161 | @param dst output array of the same type as src. The size is the same with ROTATE_180, |
1162 | and the rows and cols are switched for ROTATE_90_CLOCKWISE and ROTATE_90_COUNTERCLOCKWISE. |
1163 | @param rotateCode an enum to specify how to rotate the array; see the enum #RotateFlags |
1164 | @sa transpose, repeat, completeSymm, flip, RotateFlags |
1165 | */ |
1166 | CV_EXPORTS_W void rotate(InputArray src, OutputArray dst, int rotateCode); |
1167 | |
1168 | /** @brief Fills the output array with repeated copies of the input array. |
1169 | |
1170 | The function cv::repeat duplicates the input array one or more times along each of the two axes: |
1171 | \f[\texttt{dst} _{ij}= \texttt{src} _{i\mod src.rows, \; j\mod src.cols }\f] |
1172 | The second variant of the function is more convenient to use with @ref MatrixExpressions. |
1173 | @param src input array to replicate. |
1174 | @param ny Flag to specify how many times the `src` is repeated along the |
1175 | vertical axis. |
1176 | @param nx Flag to specify how many times the `src` is repeated along the |
1177 | horizontal axis. |
1178 | @param dst output array of the same type as `src`. |
1179 | @sa cv::reduce |
1180 | */ |
1181 | CV_EXPORTS_W void repeat(InputArray src, int ny, int nx, OutputArray dst); |
1182 | |
1183 | /** @overload |
1184 | @param src input array to replicate. |
1185 | @param ny Flag to specify how many times the `src` is repeated along the |
1186 | vertical axis. |
1187 | @param nx Flag to specify how many times the `src` is repeated along the |
1188 | horizontal axis. |
1189 | */ |
1190 | CV_EXPORTS Mat repeat(const Mat& src, int ny, int nx); |
1191 | |
1192 | /** @brief Applies horizontal concatenation to given matrices. |
1193 | |
1194 | The function horizontally concatenates two or more cv::Mat matrices (with the same number of rows). |
1195 | @code{.cpp} |
1196 | cv::Mat matArray[] = { cv::Mat(4, 1, CV_8UC1, cv::Scalar(1)), |
1197 | cv::Mat(4, 1, CV_8UC1, cv::Scalar(2)), |
1198 | cv::Mat(4, 1, CV_8UC1, cv::Scalar(3)),}; |
1199 | |
1200 | cv::Mat out; |
1201 | cv::hconcat( matArray, 3, out ); |
1202 | //out: |
1203 | //[1, 2, 3; |
1204 | // 1, 2, 3; |
1205 | // 1, 2, 3; |
1206 | // 1, 2, 3] |
1207 | @endcode |
1208 | @param src input array or vector of matrices. all of the matrices must have the same number of rows and the same depth. |
1209 | @param nsrc number of matrices in src. |
1210 | @param dst output array. It has the same number of rows and depth as the src, and the sum of cols of the src. |
1211 | @sa cv::vconcat(const Mat*, size_t, OutputArray), @sa cv::vconcat(InputArrayOfArrays, OutputArray) and @sa cv::vconcat(InputArray, InputArray, OutputArray) |
1212 | */ |
1213 | CV_EXPORTS void hconcat(const Mat* src, size_t nsrc, OutputArray dst); |
1214 | /** @overload |
1215 | @code{.cpp} |
1216 | cv::Mat_<float> A = (cv::Mat_<float>(3, 2) << 1, 4, |
1217 | 2, 5, |
1218 | 3, 6); |
1219 | cv::Mat_<float> B = (cv::Mat_<float>(3, 2) << 7, 10, |
1220 | 8, 11, |
1221 | 9, 12); |
1222 | |
1223 | cv::Mat C; |
1224 | cv::hconcat(A, B, C); |
1225 | //C: |
1226 | //[1, 4, 7, 10; |
1227 | // 2, 5, 8, 11; |
1228 | // 3, 6, 9, 12] |
1229 | @endcode |
1230 | @param src1 first input array to be considered for horizontal concatenation. |
1231 | @param src2 second input array to be considered for horizontal concatenation. |
1232 | @param dst output array. It has the same number of rows and depth as the src1 and src2, and the sum of cols of the src1 and src2. |
1233 | */ |
1234 | CV_EXPORTS void hconcat(InputArray src1, InputArray src2, OutputArray dst); |
1235 | /** @overload |
1236 | @code{.cpp} |
1237 | std::vector<cv::Mat> matrices = { cv::Mat(4, 1, CV_8UC1, cv::Scalar(1)), |
1238 | cv::Mat(4, 1, CV_8UC1, cv::Scalar(2)), |
1239 | cv::Mat(4, 1, CV_8UC1, cv::Scalar(3)),}; |
1240 | |
1241 | cv::Mat out; |
1242 | cv::hconcat( matrices, out ); |
1243 | //out: |
1244 | //[1, 2, 3; |
1245 | // 1, 2, 3; |
1246 | // 1, 2, 3; |
1247 | // 1, 2, 3] |
1248 | @endcode |
1249 | @param src input array or vector of matrices. all of the matrices must have the same number of rows and the same depth. |
1250 | @param dst output array. It has the same number of rows and depth as the src, and the sum of cols of the src. |
1251 | same depth. |
1252 | */ |
1253 | CV_EXPORTS_W void hconcat(InputArrayOfArrays src, OutputArray dst); |
1254 | |
1255 | /** @brief Applies vertical concatenation to given matrices. |
1256 | |
1257 | The function vertically concatenates two or more cv::Mat matrices (with the same number of cols). |
1258 | @code{.cpp} |
1259 | cv::Mat matArray[] = { cv::Mat(1, 4, CV_8UC1, cv::Scalar(1)), |
1260 | cv::Mat(1, 4, CV_8UC1, cv::Scalar(2)), |
1261 | cv::Mat(1, 4, CV_8UC1, cv::Scalar(3)),}; |
1262 | |
1263 | cv::Mat out; |
1264 | cv::vconcat( matArray, 3, out ); |
1265 | //out: |
1266 | //[1, 1, 1, 1; |
1267 | // 2, 2, 2, 2; |
1268 | // 3, 3, 3, 3] |
1269 | @endcode |
1270 | @param src input array or vector of matrices. all of the matrices must have the same number of cols and the same depth. |
1271 | @param nsrc number of matrices in src. |
1272 | @param dst output array. It has the same number of cols and depth as the src, and the sum of rows of the src. |
1273 | @sa cv::hconcat(const Mat*, size_t, OutputArray), @sa cv::hconcat(InputArrayOfArrays, OutputArray) and @sa cv::hconcat(InputArray, InputArray, OutputArray) |
1274 | */ |
1275 | CV_EXPORTS void vconcat(const Mat* src, size_t nsrc, OutputArray dst); |
1276 | /** @overload |
1277 | @code{.cpp} |
1278 | cv::Mat_<float> A = (cv::Mat_<float>(3, 2) << 1, 7, |
1279 | 2, 8, |
1280 | 3, 9); |
1281 | cv::Mat_<float> B = (cv::Mat_<float>(3, 2) << 4, 10, |
1282 | 5, 11, |
1283 | 6, 12); |
1284 | |
1285 | cv::Mat C; |
1286 | cv::vconcat(A, B, C); |
1287 | //C: |
1288 | //[1, 7; |
1289 | // 2, 8; |
1290 | // 3, 9; |
1291 | // 4, 10; |
1292 | // 5, 11; |
1293 | // 6, 12] |
1294 | @endcode |
1295 | @param src1 first input array to be considered for vertical concatenation. |
1296 | @param src2 second input array to be considered for vertical concatenation. |
1297 | @param dst output array. It has the same number of cols and depth as the src1 and src2, and the sum of rows of the src1 and src2. |
1298 | */ |
1299 | CV_EXPORTS void vconcat(InputArray src1, InputArray src2, OutputArray dst); |
1300 | /** @overload |
1301 | @code{.cpp} |
1302 | std::vector<cv::Mat> matrices = { cv::Mat(1, 4, CV_8UC1, cv::Scalar(1)), |
1303 | cv::Mat(1, 4, CV_8UC1, cv::Scalar(2)), |
1304 | cv::Mat(1, 4, CV_8UC1, cv::Scalar(3)),}; |
1305 | |
1306 | cv::Mat out; |
1307 | cv::vconcat( matrices, out ); |
1308 | //out: |
1309 | //[1, 1, 1, 1; |
1310 | // 2, 2, 2, 2; |
1311 | // 3, 3, 3, 3] |
1312 | @endcode |
1313 | @param src input array or vector of matrices. all of the matrices must have the same number of cols and the same depth |
1314 | @param dst output array. It has the same number of cols and depth as the src, and the sum of rows of the src. |
1315 | same depth. |
1316 | */ |
1317 | CV_EXPORTS_W void vconcat(InputArrayOfArrays src, OutputArray dst); |
1318 | |
1319 | /** @brief computes bitwise conjunction of the two arrays (dst = src1 & src2) |
1320 | Calculates the per-element bit-wise conjunction of two arrays or an |
1321 | array and a scalar. |
1322 | |
1323 | The function cv::bitwise_and calculates the per-element bit-wise logical conjunction for: |
1324 | * Two arrays when src1 and src2 have the same size: |
1325 | \f[\texttt{dst} (I) = \texttt{src1} (I) \wedge \texttt{src2} (I) \quad \texttt{if mask} (I) \ne0\f] |
1326 | * An array and a scalar when src2 is constructed from Scalar or has |
1327 | the same number of elements as `src1.channels()`: |
1328 | \f[\texttt{dst} (I) = \texttt{src1} (I) \wedge \texttt{src2} \quad \texttt{if mask} (I) \ne0\f] |
1329 | * A scalar and an array when src1 is constructed from Scalar or has |
1330 | the same number of elements as `src2.channels()`: |
1331 | \f[\texttt{dst} (I) = \texttt{src1} \wedge \texttt{src2} (I) \quad \texttt{if mask} (I) \ne0\f] |
1332 | In case of floating-point arrays, their machine-specific bit |
1333 | representations (usually IEEE754-compliant) are used for the operation. |
1334 | In case of multi-channel arrays, each channel is processed |
1335 | independently. In the second and third cases above, the scalar is first |
1336 | converted to the array type. |
1337 | @param src1 first input array or a scalar. |
1338 | @param src2 second input array or a scalar. |
1339 | @param dst output array that has the same size and type as the input |
1340 | arrays. |
1341 | @param mask optional operation mask, 8-bit single channel array, that |
1342 | specifies elements of the output array to be changed. |
1343 | */ |
1344 | CV_EXPORTS_W void bitwise_and(InputArray src1, InputArray src2, |
1345 | OutputArray dst, InputArray mask = noArray()); |
1346 | |
1347 | /** @brief Calculates the per-element bit-wise disjunction of two arrays or an |
1348 | array and a scalar. |
1349 | |
1350 | The function cv::bitwise_or calculates the per-element bit-wise logical disjunction for: |
1351 | * Two arrays when src1 and src2 have the same size: |
1352 | \f[\texttt{dst} (I) = \texttt{src1} (I) \vee \texttt{src2} (I) \quad \texttt{if mask} (I) \ne0\f] |
1353 | * An array and a scalar when src2 is constructed from Scalar or has |
1354 | the same number of elements as `src1.channels()`: |
1355 | \f[\texttt{dst} (I) = \texttt{src1} (I) \vee \texttt{src2} \quad \texttt{if mask} (I) \ne0\f] |
1356 | * A scalar and an array when src1 is constructed from Scalar or has |
1357 | the same number of elements as `src2.channels()`: |
1358 | \f[\texttt{dst} (I) = \texttt{src1} \vee \texttt{src2} (I) \quad \texttt{if mask} (I) \ne0\f] |
1359 | In case of floating-point arrays, their machine-specific bit |
1360 | representations (usually IEEE754-compliant) are used for the operation. |
1361 | In case of multi-channel arrays, each channel is processed |
1362 | independently. In the second and third cases above, the scalar is first |
1363 | converted to the array type. |
1364 | @param src1 first input array or a scalar. |
1365 | @param src2 second input array or a scalar. |
1366 | @param dst output array that has the same size and type as the input |
1367 | arrays. |
1368 | @param mask optional operation mask, 8-bit single channel array, that |
1369 | specifies elements of the output array to be changed. |
1370 | */ |
1371 | CV_EXPORTS_W void bitwise_or(InputArray src1, InputArray src2, |
1372 | OutputArray dst, InputArray mask = noArray()); |
1373 | |
1374 | /** @brief Calculates the per-element bit-wise "exclusive or" operation on two |
1375 | arrays or an array and a scalar. |
1376 | |
1377 | The function cv::bitwise_xor calculates the per-element bit-wise logical "exclusive-or" |
1378 | operation for: |
1379 | * Two arrays when src1 and src2 have the same size: |
1380 | \f[\texttt{dst} (I) = \texttt{src1} (I) \oplus \texttt{src2} (I) \quad \texttt{if mask} (I) \ne0\f] |
1381 | * An array and a scalar when src2 is constructed from Scalar or has |
1382 | the same number of elements as `src1.channels()`: |
1383 | \f[\texttt{dst} (I) = \texttt{src1} (I) \oplus \texttt{src2} \quad \texttt{if mask} (I) \ne0\f] |
1384 | * A scalar and an array when src1 is constructed from Scalar or has |
1385 | the same number of elements as `src2.channels()`: |
1386 | \f[\texttt{dst} (I) = \texttt{src1} \oplus \texttt{src2} (I) \quad \texttt{if mask} (I) \ne0\f] |
1387 | In case of floating-point arrays, their machine-specific bit |
1388 | representations (usually IEEE754-compliant) are used for the operation. |
1389 | In case of multi-channel arrays, each channel is processed |
1390 | independently. In the 2nd and 3rd cases above, the scalar is first |
1391 | converted to the array type. |
1392 | @param src1 first input array or a scalar. |
1393 | @param src2 second input array or a scalar. |
1394 | @param dst output array that has the same size and type as the input |
1395 | arrays. |
1396 | @param mask optional operation mask, 8-bit single channel array, that |
1397 | specifies elements of the output array to be changed. |
1398 | */ |
1399 | CV_EXPORTS_W void bitwise_xor(InputArray src1, InputArray src2, |
1400 | OutputArray dst, InputArray mask = noArray()); |
1401 | |
1402 | /** @brief Inverts every bit of an array. |
1403 | |
1404 | The function cv::bitwise_not calculates per-element bit-wise inversion of the input |
1405 | array: |
1406 | \f[\texttt{dst} (I) = \neg \texttt{src} (I)\f] |
1407 | In case of a floating-point input array, its machine-specific bit |
1408 | representation (usually IEEE754-compliant) is used for the operation. In |
1409 | case of multi-channel arrays, each channel is processed independently. |
1410 | @param src input array. |
1411 | @param dst output array that has the same size and type as the input |
1412 | array. |
1413 | @param mask optional operation mask, 8-bit single channel array, that |
1414 | specifies elements of the output array to be changed. |
1415 | */ |
1416 | CV_EXPORTS_W void bitwise_not(InputArray src, OutputArray dst, |
1417 | InputArray mask = noArray()); |
1418 | |
1419 | /** @brief Calculates the per-element absolute difference between two arrays or between an array and a scalar. |
1420 | |
1421 | The function cv::absdiff calculates: |
1422 | * Absolute difference between two arrays when they have the same |
1423 | size and type: |
1424 | \f[\texttt{dst}(I) = \texttt{saturate} (| \texttt{src1}(I) - \texttt{src2}(I)|)\f] |
1425 | * Absolute difference between an array and a scalar when the second |
1426 | array is constructed from Scalar or has as many elements as the |
1427 | number of channels in `src1`: |
1428 | \f[\texttt{dst}(I) = \texttt{saturate} (| \texttt{src1}(I) - \texttt{src2} |)\f] |
1429 | * Absolute difference between a scalar and an array when the first |
1430 | array is constructed from Scalar or has as many elements as the |
1431 | number of channels in `src2`: |
1432 | \f[\texttt{dst}(I) = \texttt{saturate} (| \texttt{src1} - \texttt{src2}(I) |)\f] |
1433 | where I is a multi-dimensional index of array elements. In case of |
1434 | multi-channel arrays, each channel is processed independently. |
1435 | @note Saturation is not applied when the arrays have the depth CV_32S. |
1436 | You may even get a negative value in the case of overflow. |
1437 | @note (Python) Be careful to difference behaviour between src1/src2 are single number and they are tuple/array. |
1438 | `absdiff(src,X)` means `absdiff(src,(X,X,X,X))`. |
1439 | `absdiff(src,(X,))` means `absdiff(src,(X,0,0,0))`. |
1440 | @param src1 first input array or a scalar. |
1441 | @param src2 second input array or a scalar. |
1442 | @param dst output array that has the same size and type as input arrays. |
1443 | @sa cv::abs(const Mat&) |
1444 | */ |
1445 | CV_EXPORTS_W void absdiff(InputArray src1, InputArray src2, OutputArray dst); |
1446 | |
1447 | /** @brief This is an overloaded member function, provided for convenience (python) |
1448 | Copies the matrix to another one. |
1449 | When the operation mask is specified, if the Mat::create call shown above reallocates the matrix, the newly allocated matrix is initialized with all zeros before copying the data. |
1450 | @param src source matrix. |
1451 | @param dst Destination matrix. If it does not have a proper size or type before the operation, it is |
1452 | reallocated. |
1453 | @param mask Operation mask of the same size as \*this. Its non-zero elements indicate which matrix |
1454 | elements need to be copied. The mask has to be of type CV_8U and can have 1 or multiple channels. |
1455 | */ |
1456 | |
1457 | void CV_EXPORTS_W copyTo(InputArray src, OutputArray dst, InputArray mask); |
1458 | /** @brief Checks if array elements lie between the elements of two other arrays. |
1459 | |
1460 | The function checks the range as follows: |
1461 | - For every element of a single-channel input array: |
1462 | \f[\texttt{dst} (I)= \texttt{lowerb} (I)_0 \leq \texttt{src} (I)_0 \leq \texttt{upperb} (I)_0\f] |
1463 | - For two-channel arrays: |
1464 | \f[\texttt{dst} (I)= \texttt{lowerb} (I)_0 \leq \texttt{src} (I)_0 \leq \texttt{upperb} (I)_0 \land \texttt{lowerb} (I)_1 \leq \texttt{src} (I)_1 \leq \texttt{upperb} (I)_1\f] |
1465 | - and so forth. |
1466 | |
1467 | That is, dst (I) is set to 255 (all 1 -bits) if src (I) is within the |
1468 | specified 1D, 2D, 3D, ... box and 0 otherwise. |
1469 | |
1470 | When the lower and/or upper boundary parameters are scalars, the indexes |
1471 | (I) at lowerb and upperb in the above formulas should be omitted. |
1472 | @param src first input array. |
1473 | @param lowerb inclusive lower boundary array or a scalar. |
1474 | @param upperb inclusive upper boundary array or a scalar. |
1475 | @param dst output array of the same size as src and CV_8U type. |
1476 | */ |
1477 | CV_EXPORTS_W void inRange(InputArray src, InputArray lowerb, |
1478 | InputArray upperb, OutputArray dst); |
1479 | |
1480 | /** @brief Performs the per-element comparison of two arrays or an array and scalar value. |
1481 | |
1482 | The function compares: |
1483 | * Elements of two arrays when src1 and src2 have the same size: |
1484 | \f[\texttt{dst} (I) = \texttt{src1} (I) \,\texttt{cmpop}\, \texttt{src2} (I)\f] |
1485 | * Elements of src1 with a scalar src2 when src2 is constructed from |
1486 | Scalar or has a single element: |
1487 | \f[\texttt{dst} (I) = \texttt{src1}(I) \,\texttt{cmpop}\, \texttt{src2}\f] |
1488 | * src1 with elements of src2 when src1 is constructed from Scalar or |
1489 | has a single element: |
1490 | \f[\texttt{dst} (I) = \texttt{src1} \,\texttt{cmpop}\, \texttt{src2} (I)\f] |
1491 | When the comparison result is true, the corresponding element of output |
1492 | array is set to 255. The comparison operations can be replaced with the |
1493 | equivalent matrix expressions: |
1494 | @code{.cpp} |
1495 | Mat dst1 = src1 >= src2; |
1496 | Mat dst2 = src1 < 8; |
1497 | ... |
1498 | @endcode |
1499 | @param src1 first input array or a scalar; when it is an array, it must have a single channel. |
1500 | @param src2 second input array or a scalar; when it is an array, it must have a single channel. |
1501 | @param dst output array of type ref CV_8U that has the same size and the same number of channels as |
1502 | the input arrays. |
1503 | @param cmpop a flag, that specifies correspondence between the arrays (cv::CmpTypes) |
1504 | @sa checkRange, min, max, threshold |
1505 | */ |
1506 | CV_EXPORTS_W void compare(InputArray src1, InputArray src2, OutputArray dst, int cmpop); |
1507 | |
1508 | /** @brief Calculates per-element minimum of two arrays or an array and a scalar. |
1509 | |
1510 | The function cv::min calculates the per-element minimum of two arrays: |
1511 | \f[\texttt{dst} (I)= \min ( \texttt{src1} (I), \texttt{src2} (I))\f] |
1512 | or array and a scalar: |
1513 | \f[\texttt{dst} (I)= \min ( \texttt{src1} (I), \texttt{value} )\f] |
1514 | @param src1 first input array. |
1515 | @param src2 second input array of the same size and type as src1. |
1516 | @param dst output array of the same size and type as src1. |
1517 | @sa max, compare, inRange, minMaxLoc |
1518 | */ |
1519 | CV_EXPORTS_W void min(InputArray src1, InputArray src2, OutputArray dst); |
1520 | /** @overload |
1521 | needed to avoid conflicts with const _Tp& std::min(const _Tp&, const _Tp&, _Compare) |
1522 | */ |
1523 | CV_EXPORTS void min(const Mat& src1, const Mat& src2, Mat& dst); |
1524 | /** @overload |
1525 | needed to avoid conflicts with const _Tp& std::min(const _Tp&, const _Tp&, _Compare) |
1526 | */ |
1527 | CV_EXPORTS void min(const UMat& src1, const UMat& src2, UMat& dst); |
1528 | |
1529 | /** @brief Calculates per-element maximum of two arrays or an array and a scalar. |
1530 | |
1531 | The function cv::max calculates the per-element maximum of two arrays: |
1532 | \f[\texttt{dst} (I)= \max ( \texttt{src1} (I), \texttt{src2} (I))\f] |
1533 | or array and a scalar: |
1534 | \f[\texttt{dst} (I)= \max ( \texttt{src1} (I), \texttt{value} )\f] |
1535 | @param src1 first input array. |
1536 | @param src2 second input array of the same size and type as src1 . |
1537 | @param dst output array of the same size and type as src1. |
1538 | @sa min, compare, inRange, minMaxLoc, @ref MatrixExpressions |
1539 | */ |
1540 | CV_EXPORTS_W void max(InputArray src1, InputArray src2, OutputArray dst); |
1541 | /** @overload |
1542 | needed to avoid conflicts with const _Tp& std::min(const _Tp&, const _Tp&, _Compare) |
1543 | */ |
1544 | CV_EXPORTS void max(const Mat& src1, const Mat& src2, Mat& dst); |
1545 | /** @overload |
1546 | needed to avoid conflicts with const _Tp& std::min(const _Tp&, const _Tp&, _Compare) |
1547 | */ |
1548 | CV_EXPORTS void max(const UMat& src1, const UMat& src2, UMat& dst); |
1549 | |
1550 | /** @brief Calculates a square root of array elements. |
1551 | |
1552 | The function cv::sqrt calculates a square root of each input array element. |
1553 | In case of multi-channel arrays, each channel is processed |
1554 | independently. The accuracy is approximately the same as of the built-in |
1555 | std::sqrt . |
1556 | @param src input floating-point array. |
1557 | @param dst output array of the same size and type as src. |
1558 | */ |
1559 | CV_EXPORTS_W void sqrt(InputArray src, OutputArray dst); |
1560 | |
1561 | /** @brief Raises every array element to a power. |
1562 | |
1563 | The function cv::pow raises every element of the input array to power : |
1564 | \f[\texttt{dst} (I) = \fork{\texttt{src}(I)^{power}}{if \(\texttt{power}\) is integer}{|\texttt{src}(I)|^{power}}{otherwise}\f] |
1565 | |
1566 | So, for a non-integer power exponent, the absolute values of input array |
1567 | elements are used. However, it is possible to get true values for |
1568 | negative values using some extra operations. In the example below, |
1569 | computing the 5th root of array src shows: |
1570 | @code{.cpp} |
1571 | Mat mask = src < 0; |
1572 | pow(src, 1./5, dst); |
1573 | subtract(Scalar::all(0), dst, dst, mask); |
1574 | @endcode |
1575 | For some values of power, such as integer values, 0.5 and -0.5, |
1576 | specialized faster algorithms are used. |
1577 | |
1578 | Special values (NaN, Inf) are not handled. |
1579 | @param src input array. |
1580 | @param power exponent of power. |
1581 | @param dst output array of the same size and type as src. |
1582 | @sa sqrt, exp, log, cartToPolar, polarToCart |
1583 | */ |
1584 | CV_EXPORTS_W void pow(InputArray src, double power, OutputArray dst); |
1585 | |
1586 | /** @brief Calculates the exponent of every array element. |
1587 | |
1588 | The function cv::exp calculates the exponent of every element of the input |
1589 | array: |
1590 | \f[\texttt{dst} [I] = e^{ src(I) }\f] |
1591 | |
1592 | The maximum relative error is about 7e-6 for single-precision input and |
1593 | less than 1e-10 for double-precision input. Currently, the function |
1594 | converts denormalized values to zeros on output. Special values (NaN, |
1595 | Inf) are not handled. |
1596 | @param src input array. |
1597 | @param dst output array of the same size and type as src. |
1598 | @sa log, cartToPolar, polarToCart, phase, pow, sqrt, magnitude |
1599 | */ |
1600 | CV_EXPORTS_W void exp(InputArray src, OutputArray dst); |
1601 | |
1602 | /** @brief Calculates the natural logarithm of every array element. |
1603 | |
1604 | The function cv::log calculates the natural logarithm of every element of the input array: |
1605 | \f[\texttt{dst} (I) = \log (\texttt{src}(I)) \f] |
1606 | |
1607 | Output on zero, negative and special (NaN, Inf) values is undefined. |
1608 | |
1609 | @param src input array. |
1610 | @param dst output array of the same size and type as src . |
1611 | @sa exp, cartToPolar, polarToCart, phase, pow, sqrt, magnitude |
1612 | */ |
1613 | CV_EXPORTS_W void log(InputArray src, OutputArray dst); |
1614 | |
1615 | /** @brief Calculates x and y coordinates of 2D vectors from their magnitude and angle. |
1616 | |
1617 | The function cv::polarToCart calculates the Cartesian coordinates of each 2D |
1618 | vector represented by the corresponding elements of magnitude and angle: |
1619 | \f[\begin{array}{l} \texttt{x} (I) = \texttt{magnitude} (I) \cos ( \texttt{angle} (I)) \\ \texttt{y} (I) = \texttt{magnitude} (I) \sin ( \texttt{angle} (I)) \\ \end{array}\f] |
1620 | |
1621 | The relative accuracy of the estimated coordinates is about 1e-6. |
1622 | @param magnitude input floating-point array of magnitudes of 2D vectors; |
1623 | it can be an empty matrix (=Mat()), in this case, the function assumes |
1624 | that all the magnitudes are =1; if it is not empty, it must have the |
1625 | same size and type as angle. |
1626 | @param angle input floating-point array of angles of 2D vectors. |
1627 | @param x output array of x-coordinates of 2D vectors; it has the same |
1628 | size and type as angle. |
1629 | @param y output array of y-coordinates of 2D vectors; it has the same |
1630 | size and type as angle. |
1631 | @param angleInDegrees when true, the input angles are measured in |
1632 | degrees, otherwise, they are measured in radians. |
1633 | @sa cartToPolar, magnitude, phase, exp, log, pow, sqrt |
1634 | */ |
1635 | CV_EXPORTS_W void polarToCart(InputArray magnitude, InputArray angle, |
1636 | OutputArray x, OutputArray y, bool angleInDegrees = false); |
1637 | |
1638 | /** @brief Calculates the magnitude and angle of 2D vectors. |
1639 | |
1640 | The function cv::cartToPolar calculates either the magnitude, angle, or both |
1641 | for every 2D vector (x(I),y(I)): |
1642 | \f[\begin{array}{l} \texttt{magnitude} (I)= \sqrt{\texttt{x}(I)^2+\texttt{y}(I)^2} , \\ \texttt{angle} (I)= \texttt{atan2} ( \texttt{y} (I), \texttt{x} (I))[ \cdot180 / \pi ] \end{array}\f] |
1643 | |
1644 | The angles are calculated with accuracy about 0.3 degrees. For the point |
1645 | (0,0), the angle is set to 0. |
1646 | @param x array of x-coordinates; this must be a single-precision or |
1647 | double-precision floating-point array. |
1648 | @param y array of y-coordinates, that must have the same size and same type as x. |
1649 | @param magnitude output array of magnitudes of the same size and type as x. |
1650 | @param angle output array of angles that has the same size and type as |
1651 | x; the angles are measured in radians (from 0 to 2\*Pi) or in degrees (0 to 360 degrees). |
1652 | @param angleInDegrees a flag, indicating whether the angles are measured |
1653 | in radians (which is by default), or in degrees. |
1654 | @sa Sobel, Scharr |
1655 | */ |
1656 | CV_EXPORTS_W void cartToPolar(InputArray x, InputArray y, |
1657 | OutputArray magnitude, OutputArray angle, |
1658 | bool angleInDegrees = false); |
1659 | |
1660 | /** @brief Calculates the rotation angle of 2D vectors. |
1661 | |
1662 | The function cv::phase calculates the rotation angle of each 2D vector that |
1663 | is formed from the corresponding elements of x and y : |
1664 | \f[\texttt{angle} (I) = \texttt{atan2} ( \texttt{y} (I), \texttt{x} (I))\f] |
1665 | |
1666 | The angle estimation accuracy is about 0.3 degrees. When x(I)=y(I)=0 , |
1667 | the corresponding angle(I) is set to 0. |
1668 | @param x input floating-point array of x-coordinates of 2D vectors. |
1669 | @param y input array of y-coordinates of 2D vectors; it must have the |
1670 | same size and the same type as x. |
1671 | @param angle output array of vector angles; it has the same size and |
1672 | same type as x . |
1673 | @param angleInDegrees when true, the function calculates the angle in |
1674 | degrees, otherwise, they are measured in radians. |
1675 | */ |
1676 | CV_EXPORTS_W void phase(InputArray x, InputArray y, OutputArray angle, |
1677 | bool angleInDegrees = false); |
1678 | |
1679 | /** @brief Calculates the magnitude of 2D vectors. |
1680 | |
1681 | The function cv::magnitude calculates the magnitude of 2D vectors formed |
1682 | from the corresponding elements of x and y arrays: |
1683 | \f[\texttt{dst} (I) = \sqrt{\texttt{x}(I)^2 + \texttt{y}(I)^2}\f] |
1684 | @param x floating-point array of x-coordinates of the vectors. |
1685 | @param y floating-point array of y-coordinates of the vectors; it must |
1686 | have the same size as x. |
1687 | @param magnitude output array of the same size and type as x. |
1688 | @sa cartToPolar, polarToCart, phase, sqrt |
1689 | */ |
1690 | CV_EXPORTS_W void magnitude(InputArray x, InputArray y, OutputArray magnitude); |
1691 | |
1692 | /** @brief Checks every element of an input array for invalid values. |
1693 | |
1694 | The function cv::checkRange checks that every array element is neither NaN nor infinite. When minVal \> |
1695 | -DBL_MAX and maxVal \< DBL_MAX, the function also checks that each value is between minVal and |
1696 | maxVal. In case of multi-channel arrays, each channel is processed independently. If some values |
1697 | are out of range, position of the first outlier is stored in pos (when pos != NULL). Then, the |
1698 | function either returns false (when quiet=true) or throws an exception. |
1699 | @param a input array. |
1700 | @param quiet a flag, indicating whether the functions quietly return false when the array elements |
1701 | are out of range or they throw an exception. |
1702 | @param pos optional output parameter, when not NULL, must be a pointer to array of src.dims |
1703 | elements. |
1704 | @param minVal inclusive lower boundary of valid values range. |
1705 | @param maxVal exclusive upper boundary of valid values range. |
1706 | */ |
1707 | CV_EXPORTS_W bool checkRange(InputArray a, bool quiet = true, CV_OUT Point* pos = 0, |
1708 | double minVal = -DBL_MAX, double maxVal = DBL_MAX); |
1709 | |
1710 | /** @brief Replaces NaNs by given number |
1711 | @param a input/output matrix (CV_32F type). |
1712 | @param val value to convert the NaNs |
1713 | */ |
1714 | CV_EXPORTS_W void patchNaNs(InputOutputArray a, double val = 0); |
1715 | |
1716 | /** @brief Performs generalized matrix multiplication. |
1717 | |
1718 | The function cv::gemm performs generalized matrix multiplication similar to the |
1719 | gemm functions in BLAS level 3. For example, |
1720 | `gemm(src1, src2, alpha, src3, beta, dst, GEMM_1_T + GEMM_3_T)` |
1721 | corresponds to |
1722 | \f[\texttt{dst} = \texttt{alpha} \cdot \texttt{src1} ^T \cdot \texttt{src2} + \texttt{beta} \cdot \texttt{src3} ^T\f] |
1723 | |
1724 | In case of complex (two-channel) data, performed a complex matrix |
1725 | multiplication. |
1726 | |
1727 | The function can be replaced with a matrix expression. For example, the |
1728 | above call can be replaced with: |
1729 | @code{.cpp} |
1730 | dst = alpha*src1.t()*src2 + beta*src3.t(); |
1731 | @endcode |
1732 | @param src1 first multiplied input matrix that could be real(CV_32FC1, |
1733 | CV_64FC1) or complex(CV_32FC2, CV_64FC2). |
1734 | @param src2 second multiplied input matrix of the same type as src1. |
1735 | @param alpha weight of the matrix product. |
1736 | @param src3 third optional delta matrix added to the matrix product; it |
1737 | should have the same type as src1 and src2. |
1738 | @param beta weight of src3. |
1739 | @param dst output matrix; it has the proper size and the same type as |
1740 | input matrices. |
1741 | @param flags operation flags (cv::GemmFlags) |
1742 | @sa mulTransposed, transform |
1743 | */ |
1744 | CV_EXPORTS_W void gemm(InputArray src1, InputArray src2, double alpha, |
1745 | InputArray src3, double beta, OutputArray dst, int flags = 0); |
1746 | |
1747 | /** @brief Calculates the product of a matrix and its transposition. |
1748 | |
1749 | The function cv::mulTransposed calculates the product of src and its |
1750 | transposition: |
1751 | \f[\texttt{dst} = \texttt{scale} ( \texttt{src} - \texttt{delta} )^T ( \texttt{src} - \texttt{delta} )\f] |
1752 | if aTa=true, and |
1753 | \f[\texttt{dst} = \texttt{scale} ( \texttt{src} - \texttt{delta} ) ( \texttt{src} - \texttt{delta} )^T\f] |
1754 | otherwise. The function is used to calculate the covariance matrix. With |
1755 | zero delta, it can be used as a faster substitute for general matrix |
1756 | product A\*B when B=A' |
1757 | @param src input single-channel matrix. Note that unlike gemm, the |
1758 | function can multiply not only floating-point matrices. |
1759 | @param dst output square matrix. |
1760 | @param aTa Flag specifying the multiplication ordering. See the |
1761 | description below. |
1762 | @param delta Optional delta matrix subtracted from src before the |
1763 | multiplication. When the matrix is empty ( delta=noArray() ), it is |
1764 | assumed to be zero, that is, nothing is subtracted. If it has the same |
1765 | size as src, it is simply subtracted. Otherwise, it is "repeated" (see |
1766 | repeat ) to cover the full src and then subtracted. Type of the delta |
1767 | matrix, when it is not empty, must be the same as the type of created |
1768 | output matrix. See the dtype parameter description below. |
1769 | @param scale Optional scale factor for the matrix product. |
1770 | @param dtype Optional type of the output matrix. When it is negative, |
1771 | the output matrix will have the same type as src . Otherwise, it will be |
1772 | type=CV_MAT_DEPTH(dtype) that should be either CV_32F or CV_64F . |
1773 | @sa calcCovarMatrix, gemm, repeat, reduce |
1774 | */ |
1775 | CV_EXPORTS_W void mulTransposed( InputArray src, OutputArray dst, bool aTa, |
1776 | InputArray delta = noArray(), |
1777 | double scale = 1, int dtype = -1 ); |
1778 | |
1779 | /** @brief Transposes a matrix. |
1780 | |
1781 | The function cv::transpose transposes the matrix src : |
1782 | \f[\texttt{dst} (i,j) = \texttt{src} (j,i)\f] |
1783 | @note No complex conjugation is done in case of a complex matrix. It |
1784 | should be done separately if needed. |
1785 | @param src input array. |
1786 | @param dst output array of the same type as src. |
1787 | */ |
1788 | CV_EXPORTS_W void transpose(InputArray src, OutputArray dst); |
1789 | |
1790 | /** @brief Transpose for n-dimensional matrices. |
1791 | * |
1792 | * @note Input should be continuous single-channel matrix. |
1793 | * @param src input array. |
1794 | * @param order a permutation of [0,1,..,N-1] where N is the number of axes of src. |
1795 | * The i'th axis of dst will correspond to the axis numbered order[i] of the input. |
1796 | * @param dst output array of the same type as src. |
1797 | */ |
1798 | CV_EXPORTS_W void transposeND(InputArray src, const std::vector<int>& order, OutputArray dst); |
1799 | |
1800 | /** @brief Performs the matrix transformation of every array element. |
1801 | |
1802 | The function cv::transform performs the matrix transformation of every |
1803 | element of the array src and stores the results in dst : |
1804 | \f[\texttt{dst} (I) = \texttt{m} \cdot \texttt{src} (I)\f] |
1805 | (when m.cols=src.channels() ), or |
1806 | \f[\texttt{dst} (I) = \texttt{m} \cdot [ \texttt{src} (I); 1]\f] |
1807 | (when m.cols=src.channels()+1 ) |
1808 | |
1809 | Every element of the N -channel array src is interpreted as N -element |
1810 | vector that is transformed using the M x N or M x (N+1) matrix m to |
1811 | M-element vector - the corresponding element of the output array dst . |
1812 | |
1813 | The function may be used for geometrical transformation of |
1814 | N -dimensional points, arbitrary linear color space transformation (such |
1815 | as various kinds of RGB to YUV transforms), shuffling the image |
1816 | channels, and so forth. |
1817 | @param src input array that must have as many channels (1 to 4) as |
1818 | m.cols or m.cols-1. |
1819 | @param dst output array of the same size and depth as src; it has as |
1820 | many channels as m.rows. |
1821 | @param m transformation 2x2 or 2x3 floating-point matrix. |
1822 | @sa perspectiveTransform, getAffineTransform, estimateAffine2D, warpAffine, warpPerspective |
1823 | */ |
1824 | CV_EXPORTS_W void transform(InputArray src, OutputArray dst, InputArray m ); |
1825 | |
1826 | /** @brief Performs the perspective matrix transformation of vectors. |
1827 | |
1828 | The function cv::perspectiveTransform transforms every element of src by |
1829 | treating it as a 2D or 3D vector, in the following way: |
1830 | \f[(x, y, z) \rightarrow (x'/w, y'/w, z'/w)\f] |
1831 | where |
1832 | \f[(x', y', z', w') = \texttt{mat} \cdot \begin{bmatrix} x & y & z & 1 \end{bmatrix}\f] |
1833 | and |
1834 | \f[w = \fork{w'}{if \(w' \ne 0\)}{\infty}{otherwise}\f] |
1835 | |
1836 | Here a 3D vector transformation is shown. In case of a 2D vector |
1837 | transformation, the z component is omitted. |
1838 | |
1839 | @note The function transforms a sparse set of 2D or 3D vectors. If you |
1840 | want to transform an image using perspective transformation, use |
1841 | warpPerspective . If you have an inverse problem, that is, you want to |
1842 | compute the most probable perspective transformation out of several |
1843 | pairs of corresponding points, you can use getPerspectiveTransform or |
1844 | findHomography . |
1845 | @param src input two-channel or three-channel floating-point array; each |
1846 | element is a 2D/3D vector to be transformed. |
1847 | @param dst output array of the same size and type as src. |
1848 | @param m 3x3 or 4x4 floating-point transformation matrix. |
1849 | @sa transform, warpPerspective, getPerspectiveTransform, findHomography |
1850 | */ |
1851 | CV_EXPORTS_W void perspectiveTransform(InputArray src, OutputArray dst, InputArray m ); |
1852 | |
1853 | /** @brief Copies the lower or the upper half of a square matrix to its another half. |
1854 | |
1855 | The function cv::completeSymm copies the lower or the upper half of a square matrix to |
1856 | its another half. The matrix diagonal remains unchanged: |
1857 | - \f$\texttt{m}_{ij}=\texttt{m}_{ji}\f$ for \f$i > j\f$ if |
1858 | lowerToUpper=false |
1859 | - \f$\texttt{m}_{ij}=\texttt{m}_{ji}\f$ for \f$i < j\f$ if |
1860 | lowerToUpper=true |
1861 | |
1862 | @param m input-output floating-point square matrix. |
1863 | @param lowerToUpper operation flag; if true, the lower half is copied to |
1864 | the upper half. Otherwise, the upper half is copied to the lower half. |
1865 | @sa flip, transpose |
1866 | */ |
1867 | CV_EXPORTS_W void completeSymm(InputOutputArray m, bool lowerToUpper = false); |
1868 | |
1869 | /** @brief Initializes a scaled identity matrix. |
1870 | |
1871 | The function cv::setIdentity initializes a scaled identity matrix: |
1872 | \f[\texttt{mtx} (i,j)= \fork{\texttt{value}}{ if \(i=j\)}{0}{otherwise}\f] |
1873 | |
1874 | The function can also be emulated using the matrix initializers and the |
1875 | matrix expressions: |
1876 | @code |
1877 | Mat A = Mat::eye(4, 3, CV_32F)*5; |
1878 | // A will be set to [[5, 0, 0], [0, 5, 0], [0, 0, 5], [0, 0, 0]] |
1879 | @endcode |
1880 | @param mtx matrix to initialize (not necessarily square). |
1881 | @param s value to assign to diagonal elements. |
1882 | @sa Mat::zeros, Mat::ones, Mat::setTo, Mat::operator= |
1883 | */ |
1884 | CV_EXPORTS_W void setIdentity(InputOutputArray mtx, const Scalar& s = Scalar(1)); |
1885 | |
1886 | /** @brief Returns the determinant of a square floating-point matrix. |
1887 | |
1888 | The function cv::determinant calculates and returns the determinant of the |
1889 | specified matrix. For small matrices ( mtx.cols=mtx.rows\<=3 ), the |
1890 | direct method is used. For larger matrices, the function uses LU |
1891 | factorization with partial pivoting. |
1892 | |
1893 | For symmetric positively-determined matrices, it is also possible to use |
1894 | eigen decomposition to calculate the determinant. |
1895 | @param mtx input matrix that must have CV_32FC1 or CV_64FC1 type and |
1896 | square size. |
1897 | @sa trace, invert, solve, eigen, @ref MatrixExpressions |
1898 | */ |
1899 | CV_EXPORTS_W double determinant(InputArray mtx); |
1900 | |
1901 | /** @brief Returns the trace of a matrix. |
1902 | |
1903 | The function cv::trace returns the sum of the diagonal elements of the |
1904 | matrix mtx . |
1905 | \f[\mathrm{tr} ( \texttt{mtx} ) = \sum _i \texttt{mtx} (i,i)\f] |
1906 | @param mtx input matrix. |
1907 | */ |
1908 | CV_EXPORTS_W Scalar trace(InputArray mtx); |
1909 | |
1910 | /** @brief Finds the inverse or pseudo-inverse of a matrix. |
1911 | |
1912 | The function cv::invert inverts the matrix src and stores the result in dst |
1913 | . When the matrix src is singular or non-square, the function calculates |
1914 | the pseudo-inverse matrix (the dst matrix) so that norm(src\*dst - I) is |
1915 | minimal, where I is an identity matrix. |
1916 | |
1917 | In case of the #DECOMP_LU method, the function returns non-zero value if |
1918 | the inverse has been successfully calculated and 0 if src is singular. |
1919 | |
1920 | In case of the #DECOMP_SVD method, the function returns the inverse |
1921 | condition number of src (the ratio of the smallest singular value to the |
1922 | largest singular value) and 0 if src is singular. The SVD method |
1923 | calculates a pseudo-inverse matrix if src is singular. |
1924 | |
1925 | Similarly to #DECOMP_LU, the method #DECOMP_CHOLESKY works only with |
1926 | non-singular square matrices that should also be symmetrical and |
1927 | positively defined. In this case, the function stores the inverted |
1928 | matrix in dst and returns non-zero. Otherwise, it returns 0. |
1929 | |
1930 | @param src input floating-point M x N matrix. |
1931 | @param dst output matrix of N x M size and the same type as src. |
1932 | @param flags inversion method (cv::DecompTypes) |
1933 | @sa solve, SVD |
1934 | */ |
1935 | CV_EXPORTS_W double invert(InputArray src, OutputArray dst, int flags = DECOMP_LU); |
1936 | |
1937 | /** @brief Solves one or more linear systems or least-squares problems. |
1938 | |
1939 | The function cv::solve solves a linear system or least-squares problem (the |
1940 | latter is possible with SVD or QR methods, or by specifying the flag |
1941 | #DECOMP_NORMAL ): |
1942 | \f[\texttt{dst} = \arg \min _X \| \texttt{src1} \cdot \texttt{X} - \texttt{src2} \|\f] |
1943 | |
1944 | If #DECOMP_LU or #DECOMP_CHOLESKY method is used, the function returns 1 |
1945 | if src1 (or \f$\texttt{src1}^T\texttt{src1}\f$ ) is non-singular. Otherwise, |
1946 | it returns 0. In the latter case, dst is not valid. Other methods find a |
1947 | pseudo-solution in case of a singular left-hand side part. |
1948 | |
1949 | @note If you want to find a unity-norm solution of an under-defined |
1950 | singular system \f$\texttt{src1}\cdot\texttt{dst}=0\f$ , the function solve |
1951 | will not do the work. Use SVD::solveZ instead. |
1952 | |
1953 | @param src1 input matrix on the left-hand side of the system. |
1954 | @param src2 input matrix on the right-hand side of the system. |
1955 | @param dst output solution. |
1956 | @param flags solution (matrix inversion) method (#DecompTypes) |
1957 | @sa invert, SVD, eigen |
1958 | */ |
1959 | CV_EXPORTS_W bool solve(InputArray src1, InputArray src2, |
1960 | OutputArray dst, int flags = DECOMP_LU); |
1961 | |
1962 | /** @brief Sorts each row or each column of a matrix. |
1963 | |
1964 | The function cv::sort sorts each matrix row or each matrix column in |
1965 | ascending or descending order. So you should pass two operation flags to |
1966 | get desired behaviour. If you want to sort matrix rows or columns |
1967 | lexicographically, you can use STL std::sort generic function with the |
1968 | proper comparison predicate. |
1969 | |
1970 | @param src input single-channel array. |
1971 | @param dst output array of the same size and type as src. |
1972 | @param flags operation flags, a combination of #SortFlags |
1973 | @sa sortIdx, randShuffle |
1974 | */ |
1975 | CV_EXPORTS_W void sort(InputArray src, OutputArray dst, int flags); |
1976 | |
1977 | /** @brief Sorts each row or each column of a matrix. |
1978 | |
1979 | The function cv::sortIdx sorts each matrix row or each matrix column in the |
1980 | ascending or descending order. So you should pass two operation flags to |
1981 | get desired behaviour. Instead of reordering the elements themselves, it |
1982 | stores the indices of sorted elements in the output array. For example: |
1983 | @code |
1984 | Mat A = Mat::eye(3,3,CV_32F), B; |
1985 | sortIdx(A, B, SORT_EVERY_ROW + SORT_ASCENDING); |
1986 | // B will probably contain |
1987 | // (because of equal elements in A some permutations are possible): |
1988 | // [[1, 2, 0], [0, 2, 1], [0, 1, 2]] |
1989 | @endcode |
1990 | @param src input single-channel array. |
1991 | @param dst output integer array of the same size as src. |
1992 | @param flags operation flags that could be a combination of cv::SortFlags |
1993 | @sa sort, randShuffle |
1994 | */ |
1995 | CV_EXPORTS_W void sortIdx(InputArray src, OutputArray dst, int flags); |
1996 | |
1997 | /** @brief Finds the real roots of a cubic equation. |
1998 | |
1999 | The function solveCubic finds the real roots of a cubic equation: |
2000 | - if coeffs is a 4-element vector: |
2001 | \f[\texttt{coeffs} [0] x^3 + \texttt{coeffs} [1] x^2 + \texttt{coeffs} [2] x + \texttt{coeffs} [3] = 0\f] |
2002 | - if coeffs is a 3-element vector: |
2003 | \f[x^3 + \texttt{coeffs} [0] x^2 + \texttt{coeffs} [1] x + \texttt{coeffs} [2] = 0\f] |
2004 | |
2005 | The roots are stored in the roots array. |
2006 | @param coeffs equation coefficients, an array of 3 or 4 elements. |
2007 | @param roots output array of real roots that has 1 or 3 elements. |
2008 | @return number of real roots. It can be 0, 1 or 2. |
2009 | */ |
2010 | CV_EXPORTS_W int solveCubic(InputArray coeffs, OutputArray roots); |
2011 | |
2012 | /** @brief Finds the real or complex roots of a polynomial equation. |
2013 | |
2014 | The function cv::solvePoly finds real and complex roots of a polynomial equation: |
2015 | \f[\texttt{coeffs} [n] x^{n} + \texttt{coeffs} [n-1] x^{n-1} + ... + \texttt{coeffs} [1] x + \texttt{coeffs} [0] = 0\f] |
2016 | @param coeffs array of polynomial coefficients. |
2017 | @param roots output (complex) array of roots. |
2018 | @param maxIters maximum number of iterations the algorithm does. |
2019 | */ |
2020 | CV_EXPORTS_W double solvePoly(InputArray coeffs, OutputArray roots, int maxIters = 300); |
2021 | |
2022 | /** @brief Calculates eigenvalues and eigenvectors of a symmetric matrix. |
2023 | |
2024 | The function cv::eigen calculates just eigenvalues, or eigenvalues and eigenvectors of the symmetric |
2025 | matrix src: |
2026 | @code |
2027 | src*eigenvectors.row(i).t() = eigenvalues.at<srcType>(i)*eigenvectors.row(i).t() |
2028 | @endcode |
2029 | |
2030 | @note Use cv::eigenNonSymmetric for calculation of real eigenvalues and eigenvectors of non-symmetric matrix. |
2031 | |
2032 | @param src input matrix that must have CV_32FC1 or CV_64FC1 type, square size and be symmetrical |
2033 | (src ^T^ == src). |
2034 | @param eigenvalues output vector of eigenvalues of the same type as src; the eigenvalues are stored |
2035 | in the descending order. |
2036 | @param eigenvectors output matrix of eigenvectors; it has the same size and type as src; the |
2037 | eigenvectors are stored as subsequent matrix rows, in the same order as the corresponding |
2038 | eigenvalues. |
2039 | @sa eigenNonSymmetric, completeSymm, PCA |
2040 | */ |
2041 | CV_EXPORTS_W bool eigen(InputArray src, OutputArray eigenvalues, |
2042 | OutputArray eigenvectors = noArray()); |
2043 | |
2044 | /** @brief Calculates eigenvalues and eigenvectors of a non-symmetric matrix (real eigenvalues only). |
2045 | |
2046 | @note Assumes real eigenvalues. |
2047 | |
2048 | The function calculates eigenvalues and eigenvectors (optional) of the square matrix src: |
2049 | @code |
2050 | src*eigenvectors.row(i).t() = eigenvalues.at<srcType>(i)*eigenvectors.row(i).t() |
2051 | @endcode |
2052 | |
2053 | @param src input matrix (CV_32FC1 or CV_64FC1 type). |
2054 | @param eigenvalues output vector of eigenvalues (type is the same type as src). |
2055 | @param eigenvectors output matrix of eigenvectors (type is the same type as src). The eigenvectors are stored as subsequent matrix rows, in the same order as the corresponding eigenvalues. |
2056 | @sa eigen |
2057 | */ |
2058 | CV_EXPORTS_W void eigenNonSymmetric(InputArray src, OutputArray eigenvalues, |
2059 | OutputArray eigenvectors); |
2060 | |
2061 | /** @brief Calculates the covariance matrix of a set of vectors. |
2062 | |
2063 | The function cv::calcCovarMatrix calculates the covariance matrix and, optionally, the mean vector of |
2064 | the set of input vectors. |
2065 | @param samples samples stored as separate matrices |
2066 | @param nsamples number of samples |
2067 | @param covar output covariance matrix of the type ctype and square size. |
2068 | @param mean input or output (depending on the flags) array as the average value of the input vectors. |
2069 | @param flags operation flags as a combination of #CovarFlags |
2070 | @param ctype type of the matrixl; it equals 'CV_64F' by default. |
2071 | @sa PCA, mulTransposed, Mahalanobis |
2072 | @todo InputArrayOfArrays |
2073 | */ |
2074 | CV_EXPORTS void calcCovarMatrix( const Mat* samples, int nsamples, Mat& covar, Mat& mean, |
2075 | int flags, int ctype = CV_64F); |
2076 | |
2077 | /** @overload |
2078 | @note use #COVAR_ROWS or #COVAR_COLS flag |
2079 | @param samples samples stored as rows/columns of a single matrix. |
2080 | @param covar output covariance matrix of the type ctype and square size. |
2081 | @param mean input or output (depending on the flags) array as the average value of the input vectors. |
2082 | @param flags operation flags as a combination of #CovarFlags |
2083 | @param ctype type of the matrixl; it equals 'CV_64F' by default. |
2084 | */ |
2085 | CV_EXPORTS_W void calcCovarMatrix( InputArray samples, OutputArray covar, |
2086 | InputOutputArray mean, int flags, int ctype = CV_64F); |
2087 | |
2088 | /** wrap PCA::operator() */ |
2089 | CV_EXPORTS_W void PCACompute(InputArray data, InputOutputArray mean, |
2090 | OutputArray eigenvectors, int maxComponents = 0); |
2091 | |
2092 | /** wrap PCA::operator() and add eigenvalues output parameter */ |
2093 | CV_EXPORTS_AS(PCACompute2) void PCACompute(InputArray data, InputOutputArray mean, |
2094 | OutputArray eigenvectors, OutputArray eigenvalues, |
2095 | int maxComponents = 0); |
2096 | |
2097 | /** wrap PCA::operator() */ |
2098 | CV_EXPORTS_W void PCACompute(InputArray data, InputOutputArray mean, |
2099 | OutputArray eigenvectors, double retainedVariance); |
2100 | |
2101 | /** wrap PCA::operator() and add eigenvalues output parameter */ |
2102 | CV_EXPORTS_AS(PCACompute2) void PCACompute(InputArray data, InputOutputArray mean, |
2103 | OutputArray eigenvectors, OutputArray eigenvalues, |
2104 | double retainedVariance); |
2105 | |
2106 | /** wrap PCA::project */ |
2107 | CV_EXPORTS_W void PCAProject(InputArray data, InputArray mean, |
2108 | InputArray eigenvectors, OutputArray result); |
2109 | |
2110 | /** wrap PCA::backProject */ |
2111 | CV_EXPORTS_W void PCABackProject(InputArray data, InputArray mean, |
2112 | InputArray eigenvectors, OutputArray result); |
2113 | |
2114 | /** wrap SVD::compute */ |
2115 | CV_EXPORTS_W void SVDecomp( InputArray src, OutputArray w, OutputArray u, OutputArray vt, int flags = 0 ); |
2116 | |
2117 | /** wrap SVD::backSubst */ |
2118 | CV_EXPORTS_W void SVBackSubst( InputArray w, InputArray u, InputArray vt, |
2119 | InputArray rhs, OutputArray dst ); |
2120 | |
2121 | /** @brief Calculates the Mahalanobis distance between two vectors. |
2122 | |
2123 | The function cv::Mahalanobis calculates and returns the weighted distance between two vectors: |
2124 | \f[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)})} }\f] |
2125 | The covariance matrix may be calculated using the #calcCovarMatrix function and then inverted using |
2126 | the invert function (preferably using the #DECOMP_SVD method, as the most accurate). |
2127 | @param v1 first 1D input vector. |
2128 | @param v2 second 1D input vector. |
2129 | @param icovar inverse covariance matrix. |
2130 | */ |
2131 | CV_EXPORTS_W double Mahalanobis(InputArray v1, InputArray v2, InputArray icovar); |
2132 | |
2133 | /** @brief Performs a forward or inverse Discrete Fourier transform of a 1D or 2D floating-point array. |
2134 | |
2135 | The function cv::dft performs one of the following: |
2136 | - Forward the Fourier transform of a 1D vector of N elements: |
2137 | \f[Y = F^{(N)} \cdot X,\f] |
2138 | where \f$F^{(N)}_{jk}=\exp(-2\pi i j k/N)\f$ and \f$i=\sqrt{-1}\f$ |
2139 | - Inverse the Fourier transform of a 1D vector of N elements: |
2140 | \f[\begin{array}{l} X'= \left (F^{(N)} \right )^{-1} \cdot Y = \left (F^{(N)} \right )^* \cdot y \\ X = (1/N) \cdot X, \end{array}\f] |
2141 | where \f$F^*=\left(\textrm{Re}(F^{(N)})-\textrm{Im}(F^{(N)})\right)^T\f$ |
2142 | - Forward the 2D Fourier transform of a M x N matrix: |
2143 | \f[Y = F^{(M)} \cdot X \cdot F^{(N)}\f] |
2144 | - Inverse the 2D Fourier transform of a M x N matrix: |
2145 | \f[\begin{array}{l} X'= \left (F^{(M)} \right )^* \cdot Y \cdot \left (F^{(N)} \right )^* \\ X = \frac{1}{M \cdot N} \cdot X' \end{array}\f] |
2146 | |
2147 | In case of real (single-channel) data, the output spectrum of the forward Fourier transform or input |
2148 | spectrum of the inverse Fourier transform can be represented in a packed format called *CCS* |
2149 | (complex-conjugate-symmetrical). It was borrowed from IPL (Intel\* Image Processing Library). Here |
2150 | is how 2D *CCS* spectrum looks: |
2151 | \f[\begin{bmatrix} 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} \\ 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} \\ 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} \\ \hdotsfor{9} \\ 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} \\ 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} \\ 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} \end{bmatrix}\f] |
2152 | |
2153 | In case of 1D transform of a real vector, the output looks like the first row of the matrix above. |
2154 | |
2155 | So, the function chooses an operation mode depending on the flags and size of the input array: |
2156 | - If #DFT_ROWS is set or the input array has a single row or single column, the function |
2157 | performs a 1D forward or inverse transform of each row of a matrix when #DFT_ROWS is set. |
2158 | Otherwise, it performs a 2D transform. |
2159 | - If the input array is real and #DFT_INVERSE is not set, the function performs a forward 1D or |
2160 | 2D transform: |
2161 | - When #DFT_COMPLEX_OUTPUT is set, the output is a complex matrix of the same size as |
2162 | input. |
2163 | - When #DFT_COMPLEX_OUTPUT is not set, the output is a real matrix of the same size as |
2164 | input. In case of 2D transform, it uses the packed format as shown above. In case of a |
2165 | single 1D transform, it looks like the first row of the matrix above. In case of |
2166 | multiple 1D transforms (when using the #DFT_ROWS flag), each row of the output matrix |
2167 | looks like the first row of the matrix above. |
2168 | - If the input array is complex and either #DFT_INVERSE or #DFT_REAL_OUTPUT are not set, the |
2169 | output is a complex array of the same size as input. The function performs a forward or |
2170 | inverse 1D or 2D transform of the whole input array or each row of the input array |
2171 | independently, depending on the flags DFT_INVERSE and DFT_ROWS. |
2172 | - When #DFT_INVERSE is set and the input array is real, or it is complex but #DFT_REAL_OUTPUT |
2173 | is set, the output is a real array of the same size as input. The function performs a 1D or 2D |
2174 | inverse transformation of the whole input array or each individual row, depending on the flags |
2175 | #DFT_INVERSE and #DFT_ROWS. |
2176 | |
2177 | If #DFT_SCALE is set, the scaling is done after the transformation. |
2178 | |
2179 | Unlike dct, the function supports arrays of arbitrary size. But only those arrays are processed |
2180 | efficiently, whose sizes can be factorized in a product of small prime numbers (2, 3, and 5 in the |
2181 | current implementation). Such an efficient DFT size can be calculated using the getOptimalDFTSize |
2182 | method. |
2183 | |
2184 | The sample below illustrates how to calculate a DFT-based convolution of two 2D real arrays: |
2185 | @code |
2186 | void convolveDFT(InputArray A, InputArray B, OutputArray C) |
2187 | { |
2188 | // reallocate the output array if needed |
2189 | C.create(abs(A.rows - B.rows)+1, abs(A.cols - B.cols)+1, A.type()); |
2190 | Size dftSize; |
2191 | // calculate the size of DFT transform |
2192 | dftSize.width = getOptimalDFTSize(A.cols + B.cols - 1); |
2193 | dftSize.height = getOptimalDFTSize(A.rows + B.rows - 1); |
2194 | |
2195 | // allocate temporary buffers and initialize them with 0's |
2196 | Mat tempA(dftSize, A.type(), Scalar::all(0)); |
2197 | Mat tempB(dftSize, B.type(), Scalar::all(0)); |
2198 | |
2199 | // copy A and B to the top-left corners of tempA and tempB, respectively |
2200 | Mat roiA(tempA, Rect(0,0,A.cols,A.rows)); |
2201 | A.copyTo(roiA); |
2202 | Mat roiB(tempB, Rect(0,0,B.cols,B.rows)); |
2203 | B.copyTo(roiB); |
2204 | |
2205 | // now transform the padded A & B in-place; |
2206 | // use "nonzeroRows" hint for faster processing |
2207 | dft(tempA, tempA, 0, A.rows); |
2208 | dft(tempB, tempB, 0, B.rows); |
2209 | |
2210 | // multiply the spectrums; |
2211 | // the function handles packed spectrum representations well |
2212 | mulSpectrums(tempA, tempB, tempA); |
2213 | |
2214 | // transform the product back from the frequency domain. |
2215 | // Even though all the result rows will be non-zero, |
2216 | // you need only the first C.rows of them, and thus you |
2217 | // pass nonzeroRows == C.rows |
2218 | dft(tempA, tempA, DFT_INVERSE + DFT_SCALE, C.rows); |
2219 | |
2220 | // now copy the result back to C. |
2221 | tempA(Rect(0, 0, C.cols, C.rows)).copyTo(C); |
2222 | |
2223 | // all the temporary buffers will be deallocated automatically |
2224 | } |
2225 | @endcode |
2226 | To optimize this sample, consider the following approaches: |
2227 | - Since nonzeroRows != 0 is passed to the forward transform calls and since A and B are copied to |
2228 | the top-left corners of tempA and tempB, respectively, it is not necessary to clear the whole |
2229 | tempA and tempB. It is only necessary to clear the tempA.cols - A.cols ( tempB.cols - B.cols) |
2230 | rightmost columns of the matrices. |
2231 | - This DFT-based convolution does not have to be applied to the whole big arrays, especially if B |
2232 | is significantly smaller than A or vice versa. Instead, you can calculate convolution by parts. |
2233 | To do this, you need to split the output array C into multiple tiles. For each tile, estimate |
2234 | which parts of A and B are required to calculate convolution in this tile. If the tiles in C are |
2235 | too small, the speed will decrease a lot because of repeated work. In the ultimate case, when |
2236 | each tile in C is a single pixel, the algorithm becomes equivalent to the naive convolution |
2237 | algorithm. If the tiles are too big, the temporary arrays tempA and tempB become too big and |
2238 | there is also a slowdown because of bad cache locality. So, there is an optimal tile size |
2239 | somewhere in the middle. |
2240 | - If different tiles in C can be calculated in parallel and, thus, the convolution is done by |
2241 | parts, the loop can be threaded. |
2242 | |
2243 | All of the above improvements have been implemented in #matchTemplate and #filter2D . Therefore, by |
2244 | using them, you can get the performance even better than with the above theoretically optimal |
2245 | implementation. Though, those two functions actually calculate cross-correlation, not convolution, |
2246 | so you need to "flip" the second convolution operand B vertically and horizontally using flip . |
2247 | @note |
2248 | - An example using the discrete fourier transform can be found at |
2249 | opencv_source_code/samples/cpp/dft.cpp |
2250 | - (Python) An example using the dft functionality to perform Wiener deconvolution can be found |
2251 | at opencv_source/samples/python/deconvolution.py |
2252 | - (Python) An example rearranging the quadrants of a Fourier image can be found at |
2253 | opencv_source/samples/python/dft.py |
2254 | @param src input array that could be real or complex. |
2255 | @param dst output array whose size and type depends on the flags . |
2256 | @param flags transformation flags, representing a combination of the #DftFlags |
2257 | @param nonzeroRows when the parameter is not zero, the function assumes that only the first |
2258 | nonzeroRows rows of the input array (#DFT_INVERSE is not set) or only the first nonzeroRows of the |
2259 | output array (#DFT_INVERSE is set) contain non-zeros, thus, the function can handle the rest of the |
2260 | rows more efficiently and save some time; this technique is very useful for calculating array |
2261 | cross-correlation or convolution using DFT. |
2262 | @sa dct, getOptimalDFTSize, mulSpectrums, filter2D, matchTemplate, flip, cartToPolar, |
2263 | magnitude, phase |
2264 | */ |
2265 | CV_EXPORTS_W void dft(InputArray src, OutputArray dst, int flags = 0, int nonzeroRows = 0); |
2266 | |
2267 | /** @brief Calculates the inverse Discrete Fourier Transform of a 1D or 2D array. |
2268 | |
2269 | idft(src, dst, flags) is equivalent to dft(src, dst, flags | #DFT_INVERSE) . |
2270 | @note None of dft and idft scales the result by default. So, you should pass #DFT_SCALE to one of |
2271 | dft or idft explicitly to make these transforms mutually inverse. |
2272 | @sa dft, dct, idct, mulSpectrums, getOptimalDFTSize |
2273 | @param src input floating-point real or complex array. |
2274 | @param dst output array whose size and type depend on the flags. |
2275 | @param flags operation flags (see dft and #DftFlags). |
2276 | @param nonzeroRows number of dst rows to process; the rest of the rows have undefined content (see |
2277 | the convolution sample in dft description. |
2278 | */ |
2279 | CV_EXPORTS_W void idft(InputArray src, OutputArray dst, int flags = 0, int nonzeroRows = 0); |
2280 | |
2281 | /** @brief Performs a forward or inverse discrete Cosine transform of 1D or 2D array. |
2282 | |
2283 | The function cv::dct performs a forward or inverse discrete Cosine transform (DCT) of a 1D or 2D |
2284 | floating-point array: |
2285 | - Forward Cosine transform of a 1D vector of N elements: |
2286 | \f[Y = C^{(N)} \cdot X\f] |
2287 | where |
2288 | \f[C^{(N)}_{jk}= \sqrt{\alpha_j/N} \cos \left ( \frac{\pi(2k+1)j}{2N} \right )\f] |
2289 | and |
2290 | \f$\alpha_0=1\f$, \f$\alpha_j=2\f$ for *j \> 0*. |
2291 | - Inverse Cosine transform of a 1D vector of N elements: |
2292 | \f[X = \left (C^{(N)} \right )^{-1} \cdot Y = \left (C^{(N)} \right )^T \cdot Y\f] |
2293 | (since \f$C^{(N)}\f$ is an orthogonal matrix, \f$C^{(N)} \cdot \left(C^{(N)}\right)^T = I\f$ ) |
2294 | - Forward 2D Cosine transform of M x N matrix: |
2295 | \f[Y = C^{(N)} \cdot X \cdot \left (C^{(N)} \right )^T\f] |
2296 | - Inverse 2D Cosine transform of M x N matrix: |
2297 | \f[X = \left (C^{(N)} \right )^T \cdot X \cdot C^{(N)}\f] |
2298 | |
2299 | The function chooses the mode of operation by looking at the flags and size of the input array: |
2300 | - If (flags & #DCT_INVERSE) == 0, the function does a forward 1D or 2D transform. Otherwise, it |
2301 | is an inverse 1D or 2D transform. |
2302 | - If (flags & #DCT_ROWS) != 0, the function performs a 1D transform of each row. |
2303 | - If the array is a single column or a single row, the function performs a 1D transform. |
2304 | - If none of the above is true, the function performs a 2D transform. |
2305 | |
2306 | @note Currently dct supports even-size arrays (2, 4, 6 ...). For data analysis and approximation, you |
2307 | can pad the array when necessary. |
2308 | Also, the function performance depends very much, and not monotonically, on the array size (see |
2309 | getOptimalDFTSize ). In the current implementation DCT of a vector of size N is calculated via DFT |
2310 | of a vector of size N/2 . Thus, the optimal DCT size N1 \>= N can be calculated as: |
2311 | @code |
2312 | size_t getOptimalDCTSize(size_t N) { return 2*getOptimalDFTSize((N+1)/2); } |
2313 | N1 = getOptimalDCTSize(N); |
2314 | @endcode |
2315 | @param src input floating-point array. |
2316 | @param dst output array of the same size and type as src . |
2317 | @param flags transformation flags as a combination of cv::DftFlags (DCT_*) |
2318 | @sa dft, getOptimalDFTSize, idct |
2319 | */ |
2320 | CV_EXPORTS_W void dct(InputArray src, OutputArray dst, int flags = 0); |
2321 | |
2322 | /** @brief Calculates the inverse Discrete Cosine Transform of a 1D or 2D array. |
2323 | |
2324 | idct(src, dst, flags) is equivalent to dct(src, dst, flags | DCT_INVERSE). |
2325 | @param src input floating-point single-channel array. |
2326 | @param dst output array of the same size and type as src. |
2327 | @param flags operation flags. |
2328 | @sa dct, dft, idft, getOptimalDFTSize |
2329 | */ |
2330 | CV_EXPORTS_W void idct(InputArray src, OutputArray dst, int flags = 0); |
2331 | |
2332 | /** @brief Performs the per-element multiplication of two Fourier spectrums. |
2333 | |
2334 | The function cv::mulSpectrums performs the per-element multiplication of the two CCS-packed or complex |
2335 | matrices that are results of a real or complex Fourier transform. |
2336 | |
2337 | The function, together with dft and idft, may be used to calculate convolution (pass conjB=false ) |
2338 | or correlation (pass conjB=true ) of two arrays rapidly. When the arrays are complex, they are |
2339 | simply multiplied (per element) with an optional conjugation of the second-array elements. When the |
2340 | arrays are real, they are assumed to be CCS-packed (see dft for details). |
2341 | @param a first input array. |
2342 | @param b second input array of the same size and type as src1 . |
2343 | @param c output array of the same size and type as src1 . |
2344 | @param flags operation flags; currently, the only supported flag is cv::DFT_ROWS, which indicates that |
2345 | each row of src1 and src2 is an independent 1D Fourier spectrum. If you do not want to use this flag, then simply add a `0` as value. |
2346 | @param conjB optional flag that conjugates the second input array before the multiplication (true) |
2347 | or not (false). |
2348 | */ |
2349 | CV_EXPORTS_W void mulSpectrums(InputArray a, InputArray b, OutputArray c, |
2350 | int flags, bool conjB = false); |
2351 | |
2352 | /** @brief Returns the optimal DFT size for a given vector size. |
2353 | |
2354 | DFT performance is not a monotonic function of a vector size. Therefore, when you calculate |
2355 | convolution of two arrays or perform the spectral analysis of an array, it usually makes sense to |
2356 | pad the input data with zeros to get a bit larger array that can be transformed much faster than the |
2357 | original one. Arrays whose size is a power-of-two (2, 4, 8, 16, 32, ...) are the fastest to process. |
2358 | Though, the arrays whose size is a product of 2's, 3's, and 5's (for example, 300 = 5\*5\*3\*2\*2) |
2359 | are also processed quite efficiently. |
2360 | |
2361 | The function cv::getOptimalDFTSize returns the minimum number N that is greater than or equal to vecsize |
2362 | so that the DFT of a vector of size N can be processed efficiently. In the current implementation N |
2363 | = 2 ^p^ \* 3 ^q^ \* 5 ^r^ for some integer p, q, r. |
2364 | |
2365 | The function returns a negative number if vecsize is too large (very close to INT_MAX ). |
2366 | |
2367 | While the function cannot be used directly to estimate the optimal vector size for DCT transform |
2368 | (since the current DCT implementation supports only even-size vectors), it can be easily processed |
2369 | as getOptimalDFTSize((vecsize+1)/2)\*2. |
2370 | @param vecsize vector size. |
2371 | @sa dft, dct, idft, idct, mulSpectrums |
2372 | */ |
2373 | CV_EXPORTS_W int getOptimalDFTSize(int vecsize); |
2374 | |
2375 | /** @brief Returns the default random number generator. |
2376 | |
2377 | The function cv::theRNG returns the default random number generator. For each thread, there is a |
2378 | separate random number generator, so you can use the function safely in multi-thread environments. |
2379 | If you just need to get a single random number using this generator or initialize an array, you can |
2380 | use randu or randn instead. But if you are going to generate many random numbers inside a loop, it |
2381 | is much faster to use this function to retrieve the generator and then use RNG::operator _Tp() . |
2382 | @sa RNG, randu, randn |
2383 | */ |
2384 | CV_EXPORTS RNG& theRNG(); |
2385 | |
2386 | /** @brief Sets state of default random number generator. |
2387 | |
2388 | The function cv::setRNGSeed sets state of default random number generator to custom value. |
2389 | @param seed new state for default random number generator |
2390 | @sa RNG, randu, randn |
2391 | */ |
2392 | CV_EXPORTS_W void setRNGSeed(int seed); |
2393 | |
2394 | /** @brief Generates a single uniformly-distributed random number or an array of random numbers. |
2395 | |
2396 | Non-template variant of the function fills the matrix dst with uniformly-distributed |
2397 | random numbers from the specified range: |
2398 | \f[\texttt{low} _c \leq \texttt{dst} (I)_c < \texttt{high} _c\f] |
2399 | @param dst output array of random numbers; the array must be pre-allocated. |
2400 | @param low inclusive lower boundary of the generated random numbers. |
2401 | @param high exclusive upper boundary of the generated random numbers. |
2402 | @sa RNG, randn, theRNG |
2403 | */ |
2404 | CV_EXPORTS_W void randu(InputOutputArray dst, InputArray low, InputArray high); |
2405 | |
2406 | /** @brief Fills the array with normally distributed random numbers. |
2407 | |
2408 | The function cv::randn fills the matrix dst with normally distributed random numbers with the specified |
2409 | mean vector and the standard deviation matrix. The generated random numbers are clipped to fit the |
2410 | value range of the output array data type. |
2411 | @param dst output array of random numbers; the array must be pre-allocated and have 1 to 4 channels. |
2412 | @param mean mean value (expectation) of the generated random numbers. |
2413 | @param stddev standard deviation of the generated random numbers; it can be either a vector (in |
2414 | which case a diagonal standard deviation matrix is assumed) or a square matrix. |
2415 | @sa RNG, randu |
2416 | */ |
2417 | CV_EXPORTS_W void randn(InputOutputArray dst, InputArray mean, InputArray stddev); |
2418 | |
2419 | /** @brief Shuffles the array elements randomly. |
2420 | |
2421 | The function cv::randShuffle shuffles the specified 1D array by randomly choosing pairs of elements and |
2422 | swapping them. The number of such swap operations will be dst.rows\*dst.cols\*iterFactor . |
2423 | @param dst input/output numerical 1D array. |
2424 | @param iterFactor scale factor that determines the number of random swap operations (see the details |
2425 | below). |
2426 | @param rng optional random number generator used for shuffling; if it is zero, theRNG () is used |
2427 | instead. |
2428 | @sa RNG, sort |
2429 | */ |
2430 | CV_EXPORTS_W void randShuffle(InputOutputArray dst, double iterFactor = 1., RNG* rng = 0); |
2431 | |
2432 | /** @brief Principal Component Analysis |
2433 | |
2434 | The class is used to calculate a special basis for a set of vectors. The |
2435 | basis will consist of eigenvectors of the covariance matrix calculated |
2436 | from the input set of vectors. The class %PCA can also transform |
2437 | vectors to/from the new coordinate space defined by the basis. Usually, |
2438 | in this new coordinate system, each vector from the original set (and |
2439 | any linear combination of such vectors) can be quite accurately |
2440 | approximated by taking its first few components, corresponding to the |
2441 | eigenvectors of the largest eigenvalues of the covariance matrix. |
2442 | Geometrically it means that you calculate a projection of the vector to |
2443 | a subspace formed by a few eigenvectors corresponding to the dominant |
2444 | eigenvalues of the covariance matrix. And usually such a projection is |
2445 | very close to the original vector. So, you can represent the original |
2446 | vector from a high-dimensional space with a much shorter vector |
2447 | consisting of the projected vector's coordinates in the subspace. Such a |
2448 | transformation is also known as Karhunen-Loeve Transform, or KLT. |
2449 | See http://en.wikipedia.org/wiki/Principal_component_analysis |
2450 | |
2451 | The sample below is the function that takes two matrices. The first |
2452 | function stores a set of vectors (a row per vector) that is used to |
2453 | calculate PCA. The second function stores another "test" set of vectors |
2454 | (a row per vector). First, these vectors are compressed with PCA, then |
2455 | reconstructed back, and then the reconstruction error norm is computed |
2456 | and printed for each vector. : |
2457 | |
2458 | @code{.cpp} |
2459 | using namespace cv; |
2460 | |
2461 | PCA compressPCA(const Mat& pcaset, int maxComponents, |
2462 | const Mat& testset, Mat& compressed) |
2463 | { |
2464 | PCA pca(pcaset, // pass the data |
2465 | Mat(), // we do not have a pre-computed mean vector, |
2466 | // so let the PCA engine to compute it |
2467 | PCA::DATA_AS_ROW, // indicate that the vectors |
2468 | // are stored as matrix rows |
2469 | // (use PCA::DATA_AS_COL if the vectors are |
2470 | // the matrix columns) |
2471 | maxComponents // specify, how many principal components to retain |
2472 | ); |
2473 | // if there is no test data, just return the computed basis, ready-to-use |
2474 | if( !testset.data ) |
2475 | return pca; |
2476 | CV_Assert( testset.cols == pcaset.cols ); |
2477 | |
2478 | compressed.create(testset.rows, maxComponents, testset.type()); |
2479 | |
2480 | Mat reconstructed; |
2481 | for( int i = 0; i < testset.rows; i++ ) |
2482 | { |
2483 | Mat vec = testset.row(i), coeffs = compressed.row(i), reconstructed; |
2484 | // compress the vector, the result will be stored |
2485 | // in the i-th row of the output matrix |
2486 | pca.project(vec, coeffs); |
2487 | // and then reconstruct it |
2488 | pca.backProject(coeffs, reconstructed); |
2489 | // and measure the error |
2490 | printf("%d. diff = %g\n", i, norm(vec, reconstructed, NORM_L2)); |
2491 | } |
2492 | return pca; |
2493 | } |
2494 | @endcode |
2495 | @sa calcCovarMatrix, mulTransposed, SVD, dft, dct |
2496 | */ |
2497 | class CV_EXPORTS PCA |
2498 | { |
2499 | public: |
2500 | enum Flags { DATA_AS_ROW = 0, //!< indicates that the input samples are stored as matrix rows |
2501 | DATA_AS_COL = 1, //!< indicates that the input samples are stored as matrix columns |
2502 | USE_AVG = 2 //! |
2503 | }; |
2504 | |
2505 | /** @brief default constructor |
2506 | |
2507 | The default constructor initializes an empty %PCA structure. The other |
2508 | constructors initialize the structure and call PCA::operator()(). |
2509 | */ |
2510 | PCA(); |
2511 | |
2512 | /** @overload |
2513 | @param data input samples stored as matrix rows or matrix columns. |
2514 | @param mean optional mean value; if the matrix is empty (@c noArray()), |
2515 | the mean is computed from the data. |
2516 | @param flags operation flags; currently the parameter is only used to |
2517 | specify the data layout (PCA::Flags) |
2518 | @param maxComponents maximum number of components that %PCA should |
2519 | retain; by default, all the components are retained. |
2520 | */ |
2521 | PCA(InputArray data, InputArray mean, int flags, int maxComponents = 0); |
2522 | |
2523 | /** @overload |
2524 | @param data input samples stored as matrix rows or matrix columns. |
2525 | @param mean optional mean value; if the matrix is empty (noArray()), |
2526 | the mean is computed from the data. |
2527 | @param flags operation flags; currently the parameter is only used to |
2528 | specify the data layout (PCA::Flags) |
2529 | @param retainedVariance Percentage of variance that PCA should retain. |
2530 | Using this parameter will let the PCA decided how many components to |
2531 | retain but it will always keep at least 2. |
2532 | */ |
2533 | PCA(InputArray data, InputArray mean, int flags, double retainedVariance); |
2534 | |
2535 | /** @brief performs %PCA |
2536 | |
2537 | The operator performs %PCA of the supplied dataset. It is safe to reuse |
2538 | the same PCA structure for multiple datasets. That is, if the structure |
2539 | has been previously used with another dataset, the existing internal |
2540 | data is reclaimed and the new @ref eigenvalues, @ref eigenvectors and @ref |
2541 | mean are allocated and computed. |
2542 | |
2543 | The computed @ref eigenvalues are sorted from the largest to the smallest and |
2544 | the corresponding @ref eigenvectors are stored as eigenvectors rows. |
2545 | |
2546 | @param data input samples stored as the matrix rows or as the matrix |
2547 | columns. |
2548 | @param mean optional mean value; if the matrix is empty (noArray()), |
2549 | the mean is computed from the data. |
2550 | @param flags operation flags; currently the parameter is only used to |
2551 | specify the data layout. (Flags) |
2552 | @param maxComponents maximum number of components that PCA should |
2553 | retain; by default, all the components are retained. |
2554 | */ |
2555 | PCA& operator()(InputArray data, InputArray mean, int flags, int maxComponents = 0); |
2556 | |
2557 | /** @overload |
2558 | @param data input samples stored as the matrix rows or as the matrix |
2559 | columns. |
2560 | @param mean optional mean value; if the matrix is empty (noArray()), |
2561 | the mean is computed from the data. |
2562 | @param flags operation flags; currently the parameter is only used to |
2563 | specify the data layout. (PCA::Flags) |
2564 | @param retainedVariance Percentage of variance that %PCA should retain. |
2565 | Using this parameter will let the %PCA decided how many components to |
2566 | retain but it will always keep at least 2. |
2567 | */ |
2568 | PCA& operator()(InputArray data, InputArray mean, int flags, double retainedVariance); |
2569 | |
2570 | /** @brief Projects vector(s) to the principal component subspace. |
2571 | |
2572 | The methods project one or more vectors to the principal component |
2573 | subspace, where each vector projection is represented by coefficients in |
2574 | the principal component basis. The first form of the method returns the |
2575 | matrix that the second form writes to the result. So the first form can |
2576 | be used as a part of expression while the second form can be more |
2577 | efficient in a processing loop. |
2578 | @param vec input vector(s); must have the same dimensionality and the |
2579 | same layout as the input data used at %PCA phase, that is, if |
2580 | DATA_AS_ROW are specified, then `vec.cols==data.cols` |
2581 | (vector dimensionality) and `vec.rows` is the number of vectors to |
2582 | project, and the same is true for the PCA::DATA_AS_COL case. |
2583 | */ |
2584 | Mat project(InputArray vec) const; |
2585 | |
2586 | /** @overload |
2587 | @param vec input vector(s); must have the same dimensionality and the |
2588 | same layout as the input data used at PCA phase, that is, if |
2589 | DATA_AS_ROW are specified, then `vec.cols==data.cols` |
2590 | (vector dimensionality) and `vec.rows` is the number of vectors to |
2591 | project, and the same is true for the PCA::DATA_AS_COL case. |
2592 | @param result output vectors; in case of PCA::DATA_AS_COL, the |
2593 | output matrix has as many columns as the number of input vectors, this |
2594 | means that `result.cols==vec.cols` and the number of rows match the |
2595 | number of principal components (for example, `maxComponents` parameter |
2596 | passed to the constructor). |
2597 | */ |
2598 | void project(InputArray vec, OutputArray result) const; |
2599 | |
2600 | /** @brief Reconstructs vectors from their PC projections. |
2601 | |
2602 | The methods are inverse operations to PCA::project. They take PC |
2603 | coordinates of projected vectors and reconstruct the original vectors. |
2604 | Unless all the principal components have been retained, the |
2605 | reconstructed vectors are different from the originals. But typically, |
2606 | the difference is small if the number of components is large enough (but |
2607 | still much smaller than the original vector dimensionality). As a |
2608 | result, PCA is used. |
2609 | @param vec coordinates of the vectors in the principal component |
2610 | subspace, the layout and size are the same as of PCA::project output |
2611 | vectors. |
2612 | */ |
2613 | Mat backProject(InputArray vec) const; |
2614 | |
2615 | /** @overload |
2616 | @param vec coordinates of the vectors in the principal component |
2617 | subspace, the layout and size are the same as of PCA::project output |
2618 | vectors. |
2619 | @param result reconstructed vectors; the layout and size are the same as |
2620 | of PCA::project input vectors. |
2621 | */ |
2622 | void backProject(InputArray vec, OutputArray result) const; |
2623 | |
2624 | /** @brief write PCA objects |
2625 | |
2626 | Writes @ref eigenvalues @ref eigenvectors and @ref mean to specified FileStorage |
2627 | */ |
2628 | void write(FileStorage& fs) const; |
2629 | |
2630 | /** @brief load PCA objects |
2631 | |
2632 | Loads @ref eigenvalues @ref eigenvectors and @ref mean from specified FileNode |
2633 | */ |
2634 | void read(const FileNode& fn); |
2635 | |
2636 | Mat eigenvectors; //!< eigenvectors of the covariation matrix |
2637 | Mat eigenvalues; //!< eigenvalues of the covariation matrix |
2638 | Mat mean; //!< mean value subtracted before the projection and added after the back projection |
2639 | }; |
2640 | |
2641 | /** @example samples/cpp/pca.cpp |
2642 | An example using %PCA for dimensionality reduction while maintaining an amount of variance |
2643 | */ |
2644 | |
2645 | /** @example samples/cpp/tutorial_code/ml/introduction_to_pca/introduction_to_pca.cpp |
2646 | Check @ref tutorial_introduction_to_pca "the corresponding tutorial" for more details |
2647 | */ |
2648 | |
2649 | /** |
2650 | @brief Linear Discriminant Analysis |
2651 | @todo document this class |
2652 | */ |
2653 | class CV_EXPORTS LDA |
2654 | { |
2655 | public: |
2656 | /** @brief constructor |
2657 | Initializes a LDA with num_components (default 0). |
2658 | */ |
2659 | explicit LDA(int num_components = 0); |
2660 | |
2661 | /** Initializes and performs a Discriminant Analysis with Fisher's |
2662 | Optimization Criterion on given data in src and corresponding labels |
2663 | in labels. If 0 (or less) number of components are given, they are |
2664 | automatically determined for given data in computation. |
2665 | */ |
2666 | LDA(InputArrayOfArrays src, InputArray labels, int num_components = 0); |
2667 | |
2668 | /** Serializes this object to a given filename. |
2669 | */ |
2670 | void save(const String& filename) const; |
2671 | |
2672 | /** Deserializes this object from a given filename. |
2673 | */ |
2674 | void load(const String& filename); |
2675 | |
2676 | /** Serializes this object to a given cv::FileStorage. |
2677 | */ |
2678 | void save(FileStorage& fs) const; |
2679 | |
2680 | /** Deserializes this object from a given cv::FileStorage. |
2681 | */ |
2682 | void load(const FileStorage& node); |
2683 | |
2684 | /** destructor |
2685 | */ |
2686 | ~LDA(); |
2687 | |
2688 | /** Compute the discriminants for data in src (row aligned) and labels. |
2689 | */ |
2690 | void compute(InputArrayOfArrays src, InputArray labels); |
2691 | |
2692 | /** Projects samples into the LDA subspace. |
2693 | src may be one or more row aligned samples. |
2694 | */ |
2695 | Mat project(InputArray src); |
2696 | |
2697 | /** Reconstructs projections from the LDA subspace. |
2698 | src may be one or more row aligned projections. |
2699 | */ |
2700 | Mat reconstruct(InputArray src); |
2701 | |
2702 | /** Returns the eigenvectors of this LDA. |
2703 | */ |
2704 | Mat eigenvectors() const { return _eigenvectors; } |
2705 | |
2706 | /** Returns the eigenvalues of this LDA. |
2707 | */ |
2708 | Mat eigenvalues() const { return _eigenvalues; } |
2709 | |
2710 | static Mat subspaceProject(InputArray W, InputArray mean, InputArray src); |
2711 | static Mat subspaceReconstruct(InputArray W, InputArray mean, InputArray src); |
2712 | |
2713 | protected: |
2714 | int _num_components; |
2715 | Mat _eigenvectors; |
2716 | Mat _eigenvalues; |
2717 | void lda(InputArrayOfArrays src, InputArray labels); |
2718 | }; |
2719 | |
2720 | /** @brief Singular Value Decomposition |
2721 | |
2722 | Class for computing Singular Value Decomposition of a floating-point |
2723 | matrix. The Singular Value Decomposition is used to solve least-square |
2724 | problems, under-determined linear systems, invert matrices, compute |
2725 | condition numbers, and so on. |
2726 | |
2727 | If you want to compute a condition number of a matrix or an absolute value of |
2728 | its determinant, you do not need `u` and `vt`. You can pass |
2729 | flags=SVD::NO_UV|... . Another flag SVD::FULL_UV indicates that full-size u |
2730 | and vt must be computed, which is not necessary most of the time. |
2731 | |
2732 | @sa invert, solve, eigen, determinant |
2733 | */ |
2734 | class CV_EXPORTS SVD |
2735 | { |
2736 | public: |
2737 | enum Flags { |
2738 | /** allow the algorithm to modify the decomposed matrix; it can save space and speed up |
2739 | processing. currently ignored. */ |
2740 | MODIFY_A = 1, |
2741 | /** indicates that only a vector of singular values `w` is to be processed, while u and vt |
2742 | will be set to empty matrices */ |
2743 | NO_UV = 2, |
2744 | /** when the matrix is not square, by default the algorithm produces u and vt matrices of |
2745 | sufficiently large size for the further A reconstruction; if, however, FULL_UV flag is |
2746 | specified, u and vt will be full-size square orthogonal matrices.*/ |
2747 | FULL_UV = 4 |
2748 | }; |
2749 | |
2750 | /** @brief the default constructor |
2751 | |
2752 | initializes an empty SVD structure |
2753 | */ |
2754 | SVD(); |
2755 | |
2756 | /** @overload |
2757 | initializes an empty SVD structure and then calls SVD::operator() |
2758 | @param src decomposed matrix. The depth has to be CV_32F or CV_64F. |
2759 | @param flags operation flags (SVD::Flags) |
2760 | */ |
2761 | SVD( InputArray src, int flags = 0 ); |
2762 | |
2763 | /** @brief the operator that performs SVD. The previously allocated u, w and vt are released. |
2764 | |
2765 | The operator performs the singular value decomposition of the supplied |
2766 | matrix. The u,`vt` , and the vector of singular values w are stored in |
2767 | the structure. The same SVD structure can be reused many times with |
2768 | different matrices. Each time, if needed, the previous u,`vt` , and w |
2769 | are reclaimed and the new matrices are created, which is all handled by |
2770 | Mat::create. |
2771 | @param src decomposed matrix. The depth has to be CV_32F or CV_64F. |
2772 | @param flags operation flags (SVD::Flags) |
2773 | */ |
2774 | SVD& operator ()( InputArray src, int flags = 0 ); |
2775 | |
2776 | /** @brief decomposes matrix and stores the results to user-provided matrices |
2777 | |
2778 | The methods/functions perform SVD of matrix. Unlike SVD::SVD constructor |
2779 | and SVD::operator(), they store the results to the user-provided |
2780 | matrices: |
2781 | |
2782 | @code{.cpp} |
2783 | Mat A, w, u, vt; |
2784 | SVD::compute(A, w, u, vt); |
2785 | @endcode |
2786 | |
2787 | @param src decomposed matrix. The depth has to be CV_32F or CV_64F. |
2788 | @param w calculated singular values |
2789 | @param u calculated left singular vectors |
2790 | @param vt transposed matrix of right singular vectors |
2791 | @param flags operation flags - see SVD::Flags. |
2792 | */ |
2793 | static void compute( InputArray src, OutputArray w, |
2794 | OutputArray u, OutputArray vt, int flags = 0 ); |
2795 | |
2796 | /** @overload |
2797 | computes singular values of a matrix |
2798 | @param src decomposed matrix. The depth has to be CV_32F or CV_64F. |
2799 | @param w calculated singular values |
2800 | @param flags operation flags - see SVD::Flags. |
2801 | */ |
2802 | static void compute( InputArray src, OutputArray w, int flags = 0 ); |
2803 | |
2804 | /** @brief performs back substitution |
2805 | */ |
2806 | static void backSubst( InputArray w, InputArray u, |
2807 | InputArray vt, InputArray rhs, |
2808 | OutputArray dst ); |
2809 | |
2810 | /** @brief solves an under-determined singular linear system |
2811 | |
2812 | The method finds a unit-length solution x of a singular linear system |
2813 | A\*x = 0. Depending on the rank of A, there can be no solutions, a |
2814 | single solution or an infinite number of solutions. In general, the |
2815 | algorithm solves the following problem: |
2816 | \f[dst = \arg \min _{x: \| x \| =1} \| src \cdot x \|\f] |
2817 | @param src left-hand-side matrix. |
2818 | @param dst found solution. |
2819 | */ |
2820 | static void solveZ( InputArray src, OutputArray dst ); |
2821 | |
2822 | /** @brief performs a singular value back substitution. |
2823 | |
2824 | The method calculates a back substitution for the specified right-hand |
2825 | side: |
2826 | |
2827 | \f[\texttt{x} = \texttt{vt} ^T \cdot diag( \texttt{w} )^{-1} \cdot \texttt{u} ^T \cdot \texttt{rhs} \sim \texttt{A} ^{-1} \cdot \texttt{rhs}\f] |
2828 | |
2829 | Using this technique you can either get a very accurate solution of the |
2830 | convenient linear system, or the best (in the least-squares terms) |
2831 | pseudo-solution of an overdetermined linear system. |
2832 | |
2833 | @param rhs right-hand side of a linear system (u\*w\*v')\*dst = rhs to |
2834 | be solved, where A has been previously decomposed. |
2835 | |
2836 | @param dst found solution of the system. |
2837 | |
2838 | @note Explicit SVD with the further back substitution only makes sense |
2839 | if you need to solve many linear systems with the same left-hand side |
2840 | (for example, src ). If all you need is to solve a single system |
2841 | (possibly with multiple rhs immediately available), simply call solve |
2842 | add pass #DECOMP_SVD there. It does absolutely the same thing. |
2843 | */ |
2844 | void backSubst( InputArray rhs, OutputArray dst ) const; |
2845 | |
2846 | /** @todo document */ |
2847 | template<typename _Tp, int m, int n, int nm> static |
2848 | void compute( const Matx<_Tp, m, n>& a, Matx<_Tp, nm, 1>& w, Matx<_Tp, m, nm>& u, Matx<_Tp, n, nm>& vt ); |
2849 | |
2850 | /** @todo document */ |
2851 | template<typename _Tp, int m, int n, int nm> static |
2852 | void compute( const Matx<_Tp, m, n>& a, Matx<_Tp, nm, 1>& w ); |
2853 | |
2854 | /** @todo document */ |
2855 | template<typename _Tp, int m, int n, int nm, int nb> static |
2856 | void backSubst( const Matx<_Tp, nm, 1>& w, const Matx<_Tp, m, nm>& u, const Matx<_Tp, n, nm>& vt, const Matx<_Tp, m, nb>& rhs, Matx<_Tp, n, nb>& dst ); |
2857 | |
2858 | Mat u, w, vt; |
2859 | }; |
2860 | |
2861 | /** @brief Random Number Generator |
2862 | |
2863 | Random number generator. It encapsulates the state (currently, a 64-bit |
2864 | integer) and has methods to return scalar random values and to fill |
2865 | arrays with random values. Currently it supports uniform and Gaussian |
2866 | (normal) distributions. The generator uses Multiply-With-Carry |
2867 | algorithm, introduced by G. Marsaglia ( |
2868 | <http://en.wikipedia.org/wiki/Multiply-with-carry> ). |
2869 | Gaussian-distribution random numbers are generated using the Ziggurat |
2870 | algorithm ( <http://en.wikipedia.org/wiki/Ziggurat_algorithm> ), |
2871 | introduced by G. Marsaglia and W. W. Tsang. |
2872 | */ |
2873 | class CV_EXPORTS RNG |
2874 | { |
2875 | public: |
2876 | enum { UNIFORM = 0, |
2877 | NORMAL = 1 |
2878 | }; |
2879 | |
2880 | /** @brief constructor |
2881 | |
2882 | These are the RNG constructors. The first form sets the state to some |
2883 | pre-defined value, equal to 2\*\*32-1 in the current implementation. The |
2884 | second form sets the state to the specified value. If you passed state=0 |
2885 | , the constructor uses the above default value instead to avoid the |
2886 | singular random number sequence, consisting of all zeros. |
2887 | */ |
2888 | RNG(); |
2889 | /** @overload |
2890 | @param state 64-bit value used to initialize the RNG. |
2891 | */ |
2892 | RNG(uint64 state); |
2893 | /**The method updates the state using the MWC algorithm and returns the |
2894 | next 32-bit random number.*/ |
2895 | unsigned next(); |
2896 | |
2897 | /**Each of the methods updates the state using the MWC algorithm and |
2898 | returns the next random number of the specified type. In case of integer |
2899 | types, the returned number is from the available value range for the |
2900 | specified type. In case of floating-point types, the returned value is |
2901 | from [0,1) range. |
2902 | */ |
2903 | operator uchar(); |
2904 | /** @overload */ |
2905 | operator schar(); |
2906 | /** @overload */ |
2907 | operator ushort(); |
2908 | /** @overload */ |
2909 | operator short(); |
2910 | /** @overload */ |
2911 | operator unsigned(); |
2912 | /** @overload */ |
2913 | operator int(); |
2914 | /** @overload */ |
2915 | operator float(); |
2916 | /** @overload */ |
2917 | operator double(); |
2918 | |
2919 | /** @brief returns a random integer sampled uniformly from [0, N). |
2920 | |
2921 | The methods transform the state using the MWC algorithm and return the |
2922 | next random number. The first form is equivalent to RNG::next . The |
2923 | second form returns the random number modulo N, which means that the |
2924 | result is in the range [0, N) . |
2925 | */ |
2926 | unsigned operator ()(); |
2927 | /** @overload |
2928 | @param N upper non-inclusive boundary of the returned random number. |
2929 | */ |
2930 | unsigned operator ()(unsigned N); |
2931 | |
2932 | /** @brief returns uniformly distributed integer random number from [a,b) range |
2933 | |
2934 | The methods transform the state using the MWC algorithm and return the |
2935 | next uniformly-distributed random number of the specified type, deduced |
2936 | from the input parameter type, from the range [a, b) . There is a nuance |
2937 | illustrated by the following sample: |
2938 | |
2939 | @code{.cpp} |
2940 | RNG rng; |
2941 | |
2942 | // always produces 0 |
2943 | double a = rng.uniform(0, 1); |
2944 | |
2945 | // produces double from [0, 1) |
2946 | double a1 = rng.uniform((double)0, (double)1); |
2947 | |
2948 | // produces float from [0, 1) |
2949 | float b = rng.uniform(0.f, 1.f); |
2950 | |
2951 | // produces double from [0, 1) |
2952 | double c = rng.uniform(0., 1.); |
2953 | |
2954 | // may cause compiler error because of ambiguity: |
2955 | // RNG::uniform(0, (int)0.999999)? or RNG::uniform((double)0, 0.99999)? |
2956 | double d = rng.uniform(0, 0.999999); |
2957 | @endcode |
2958 | |
2959 | The compiler does not take into account the type of the variable to |
2960 | which you assign the result of RNG::uniform . The only thing that |
2961 | matters to the compiler is the type of a and b parameters. So, if you |
2962 | want a floating-point random number, but the range boundaries are |
2963 | integer numbers, either put dots in the end, if they are constants, or |
2964 | use explicit type cast operators, as in the a1 initialization above. |
2965 | @param a lower inclusive boundary of the returned random number. |
2966 | @param b upper non-inclusive boundary of the returned random number. |
2967 | */ |
2968 | int uniform(int a, int b); |
2969 | /** @overload */ |
2970 | float uniform(float a, float b); |
2971 | /** @overload */ |
2972 | double uniform(double a, double b); |
2973 | |
2974 | /** @brief Fills arrays with random numbers. |
2975 | |
2976 | @param mat 2D or N-dimensional matrix; currently matrices with more than |
2977 | 4 channels are not supported by the methods, use Mat::reshape as a |
2978 | possible workaround. |
2979 | @param distType distribution type, RNG::UNIFORM or RNG::NORMAL. |
2980 | @param a first distribution parameter; in case of the uniform |
2981 | distribution, this is an inclusive lower boundary, in case of the normal |
2982 | distribution, this is a mean value. |
2983 | @param b second distribution parameter; in case of the uniform |
2984 | distribution, this is a non-inclusive upper boundary, in case of the |
2985 | normal distribution, this is a standard deviation (diagonal of the |
2986 | standard deviation matrix or the full standard deviation matrix). |
2987 | @param saturateRange pre-saturation flag; for uniform distribution only; |
2988 | if true, the method will first convert a and b to the acceptable value |
2989 | range (according to the mat datatype) and then will generate uniformly |
2990 | distributed random numbers within the range [saturate(a), saturate(b)), |
2991 | if saturateRange=false, the method will generate uniformly distributed |
2992 | random numbers in the original range [a, b) and then will saturate them, |
2993 | it means, for example, that |
2994 | <tt>theRNG().fill(mat_8u, RNG::UNIFORM, -DBL_MAX, DBL_MAX)</tt> will likely |
2995 | produce array mostly filled with 0's and 255's, since the range (0, 255) |
2996 | is significantly smaller than [-DBL_MAX, DBL_MAX). |
2997 | |
2998 | Each of the methods fills the matrix with the random values from the |
2999 | specified distribution. As the new numbers are generated, the RNG state |
3000 | is updated accordingly. In case of multiple-channel images, every |
3001 | channel is filled independently, which means that RNG cannot generate |
3002 | samples from the multi-dimensional Gaussian distribution with |
3003 | non-diagonal covariance matrix directly. To do that, the method |
3004 | generates samples from multi-dimensional standard Gaussian distribution |
3005 | with zero mean and identity covariation matrix, and then transforms them |
3006 | using transform to get samples from the specified Gaussian distribution. |
3007 | */ |
3008 | void fill( InputOutputArray mat, int distType, InputArray a, InputArray b, bool saturateRange = false ); |
3009 | |
3010 | /** @brief Returns the next random number sampled from the Gaussian distribution |
3011 | @param sigma standard deviation of the distribution. |
3012 | |
3013 | The method transforms the state using the MWC algorithm and returns the |
3014 | next random number from the Gaussian distribution N(0,sigma) . That is, |
3015 | the mean value of the returned random numbers is zero and the standard |
3016 | deviation is the specified sigma . |
3017 | */ |
3018 | double gaussian(double sigma); |
3019 | |
3020 | uint64 state; |
3021 | |
3022 | bool operator ==(const RNG& other) const; |
3023 | }; |
3024 | |
3025 | /** @brief Mersenne Twister random number generator |
3026 | |
3027 | Inspired by http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/MT2002/CODES/mt19937ar.c |
3028 | @todo document |
3029 | */ |
3030 | class CV_EXPORTS RNG_MT19937 |
3031 | { |
3032 | public: |
3033 | RNG_MT19937(); |
3034 | RNG_MT19937(unsigned s); |
3035 | void seed(unsigned s); |
3036 | |
3037 | unsigned next(); |
3038 | |
3039 | operator int(); |
3040 | operator unsigned(); |
3041 | operator float(); |
3042 | operator double(); |
3043 | |
3044 | unsigned operator ()(unsigned N); |
3045 | unsigned operator ()(); |
3046 | |
3047 | /** @brief returns uniformly distributed integer random number from [a,b) range*/ |
3048 | int uniform(int a, int b); |
3049 | /** @brief returns uniformly distributed floating-point random number from [a,b) range*/ |
3050 | float uniform(float a, float b); |
3051 | /** @brief returns uniformly distributed double-precision floating-point random number from [a,b) range*/ |
3052 | double uniform(double a, double b); |
3053 | |
3054 | private: |
3055 | enum PeriodParameters {N = 624, M = 397}; |
3056 | unsigned state[N]; |
3057 | int mti; |
3058 | }; |
3059 | |
3060 | //! @} core_array |
3061 | |
3062 | //! @addtogroup core_cluster |
3063 | //! @{ |
3064 | |
3065 | //! k-means flags |
3066 | enum KmeansFlags { |
3067 | /** Select random initial centers in each attempt.*/ |
3068 | KMEANS_RANDOM_CENTERS = 0, |
3069 | /** Use kmeans++ center initialization by Arthur and Vassilvitskii [Arthur2007].*/ |
3070 | KMEANS_PP_CENTERS = 2, |
3071 | /** During the first (and possibly the only) attempt, use the |
3072 | user-supplied labels instead of computing them from the initial centers. For the second and |
3073 | further attempts, use the random or semi-random centers. Use one of KMEANS_\*_CENTERS flag |
3074 | to specify the exact method.*/ |
3075 | KMEANS_USE_INITIAL_LABELS = 1 |
3076 | }; |
3077 | |
3078 | /** @example samples/cpp/kmeans.cpp |
3079 | An example on k-means clustering |
3080 | */ |
3081 | |
3082 | /** @brief Finds centers of clusters and groups input samples around the clusters. |
3083 | |
3084 | The function kmeans implements a k-means algorithm that finds the centers of cluster_count clusters |
3085 | and groups the input samples around the clusters. As an output, \f$\texttt{bestLabels}_i\f$ contains a |
3086 | 0-based cluster index for the sample stored in the \f$i^{th}\f$ row of the samples matrix. |
3087 | |
3088 | @note |
3089 | - (Python) An example on k-means clustering can be found at |
3090 | opencv_source_code/samples/python/kmeans.py |
3091 | @param data Data for clustering. An array of N-Dimensional points with float coordinates is needed. |
3092 | Examples of this array can be: |
3093 | - Mat points(count, 2, CV_32F); |
3094 | - Mat points(count, 1, CV_32FC2); |
3095 | - Mat points(1, count, CV_32FC2); |
3096 | - std::vector\<cv::Point2f\> points(sampleCount); |
3097 | @param K Number of clusters to split the set by. |
3098 | @param bestLabels Input/output integer array that stores the cluster indices for every sample. |
3099 | @param criteria The algorithm termination criteria, that is, the maximum number of iterations and/or |
3100 | the desired accuracy. The accuracy is specified as criteria.epsilon. As soon as each of the cluster |
3101 | centers moves by less than criteria.epsilon on some iteration, the algorithm stops. |
3102 | @param attempts Flag to specify the number of times the algorithm is executed using different |
3103 | initial labellings. The algorithm returns the labels that yield the best compactness (see the last |
3104 | function parameter). |
3105 | @param flags Flag that can take values of cv::KmeansFlags |
3106 | @param centers Output matrix of the cluster centers, one row per each cluster center. |
3107 | @return The function returns the compactness measure that is computed as |
3108 | \f[\sum _i \| \texttt{samples} _i - \texttt{centers} _{ \texttt{labels} _i} \| ^2\f] |
3109 | after every attempt. The best (minimum) value is chosen and the corresponding labels and the |
3110 | compactness value are returned by the function. Basically, you can use only the core of the |
3111 | function, set the number of attempts to 1, initialize labels each time using a custom algorithm, |
3112 | pass them with the ( flags = #KMEANS_USE_INITIAL_LABELS ) flag, and then choose the best |
3113 | (most-compact) clustering. |
3114 | */ |
3115 | CV_EXPORTS_W double kmeans( InputArray data, int K, InputOutputArray bestLabels, |
3116 | TermCriteria criteria, int attempts, |
3117 | int flags, OutputArray centers = noArray() ); |
3118 | |
3119 | //! @} core_cluster |
3120 | |
3121 | //! @addtogroup core_basic |
3122 | //! @{ |
3123 | |
3124 | /////////////////////////////// Formatted output of cv::Mat /////////////////////////// |
3125 | |
3126 | /** @todo document */ |
3127 | class CV_EXPORTS Formatted |
3128 | { |
3129 | public: |
3130 | virtual const char* next() = 0; |
3131 | virtual void reset() = 0; |
3132 | virtual ~Formatted(); |
3133 | }; |
3134 | |
3135 | /** @todo document */ |
3136 | class CV_EXPORTS Formatter |
3137 | { |
3138 | public: |
3139 | enum FormatType { |
3140 | FMT_DEFAULT = 0, |
3141 | FMT_MATLAB = 1, |
3142 | FMT_CSV = 2, |
3143 | FMT_PYTHON = 3, |
3144 | FMT_NUMPY = 4, |
3145 | FMT_C = 5 |
3146 | }; |
3147 | |
3148 | virtual ~Formatter(); |
3149 | |
3150 | virtual Ptr<Formatted> format(const Mat& mtx) const = 0; |
3151 | |
3152 | virtual void set16fPrecision(int p = 4) = 0; |
3153 | virtual void set32fPrecision(int p = 8) = 0; |
3154 | virtual void set64fPrecision(int p = 16) = 0; |
3155 | virtual void setMultiline(bool ml = true) = 0; |
3156 | |
3157 | static Ptr<Formatter> get(Formatter::FormatType fmt = FMT_DEFAULT); |
3158 | |
3159 | }; |
3160 | |
3161 | static inline |
3162 | String& operator << (String& out, Ptr<Formatted> fmtd) |
3163 | { |
3164 | fmtd->reset(); |
3165 | for(const char* str = fmtd->next(); str; str = fmtd->next()) |
3166 | out += cv::String(str); |
3167 | return out; |
3168 | } |
3169 | |
3170 | static inline |
3171 | String& operator << (String& out, const Mat& mtx) |
3172 | { |
3173 | return out << Formatter::get()->format(mtx); |
3174 | } |
3175 | |
3176 | //////////////////////////////////////// Algorithm //////////////////////////////////// |
3177 | |
3178 | class CV_EXPORTS Algorithm; |
3179 | |
3180 | template<typename _Tp, typename _EnumTp = void> struct ParamType {}; |
3181 | |
3182 | |
3183 | /** @brief This is a base class for all more or less complex algorithms in OpenCV |
3184 | |
3185 | especially for classes of algorithms, for which there can be multiple implementations. The examples |
3186 | are stereo correspondence (for which there are algorithms like block matching, semi-global block |
3187 | matching, graph-cut etc.), background subtraction (which can be done using mixture-of-gaussians |
3188 | models, codebook-based algorithm etc.), optical flow (block matching, Lucas-Kanade, Horn-Schunck |
3189 | etc.). |
3190 | |
3191 | Here is example of SimpleBlobDetector use in your application via Algorithm interface: |
3192 | @snippet snippets/core_various.cpp Algorithm |
3193 | */ |
3194 | class CV_EXPORTS_W Algorithm |
3195 | { |
3196 | public: |
3197 | Algorithm(); |
3198 | virtual ~Algorithm(); |
3199 | |
3200 | /** @brief Clears the algorithm state |
3201 | */ |
3202 | CV_WRAP virtual void clear() {} |
3203 | |
3204 | /** @brief Stores algorithm parameters in a file storage |
3205 | */ |
3206 | CV_WRAP virtual void write(FileStorage& fs) const { CV_UNUSED(fs); } |
3207 | |
3208 | /** |
3209 | * @overload |
3210 | */ |
3211 | CV_WRAP void write(FileStorage& fs, const String& name) const; |
3212 | #if CV_VERSION_MAJOR < 5 |
3213 | /** @deprecated */ |
3214 | void write(const Ptr<FileStorage>& fs, const String& name = String()) const; |
3215 | #endif |
3216 | |
3217 | /** @brief Reads algorithm parameters from a file storage |
3218 | */ |
3219 | CV_WRAP virtual void read(const FileNode& fn) { CV_UNUSED(fn); } |
3220 | |
3221 | /** @brief Returns true if the Algorithm is empty (e.g. in the very beginning or after unsuccessful read |
3222 | */ |
3223 | CV_WRAP virtual bool empty() const { return false; } |
3224 | |
3225 | /** @brief Reads algorithm from the file node |
3226 | |
3227 | This is static template method of Algorithm. It's usage is following (in the case of SVM): |
3228 | @code |
3229 | cv::FileStorage fsRead("example.xml", FileStorage::READ); |
3230 | Ptr<SVM> svm = Algorithm::read<SVM>(fsRead.root()); |
3231 | @endcode |
3232 | In order to make this method work, the derived class must overwrite Algorithm::read(const |
3233 | FileNode& fn) and also have static create() method without parameters |
3234 | (or with all the optional parameters) |
3235 | */ |
3236 | template<typename _Tp> static Ptr<_Tp> read(const FileNode& fn) |
3237 | { |
3238 | Ptr<_Tp> obj = _Tp::create(); |
3239 | obj->read(fn); |
3240 | return !obj->empty() ? obj : Ptr<_Tp>(); |
3241 | } |
3242 | |
3243 | /** @brief Loads algorithm from the file |
3244 | |
3245 | @param filename Name of the file to read. |
3246 | @param objname The optional name of the node to read (if empty, the first top-level node will be used) |
3247 | |
3248 | This is static template method of Algorithm. It's usage is following (in the case of SVM): |
3249 | @code |
3250 | Ptr<SVM> svm = Algorithm::load<SVM>("my_svm_model.xml"); |
3251 | @endcode |
3252 | In order to make this method work, the derived class must overwrite Algorithm::read(const |
3253 | FileNode& fn). |
3254 | */ |
3255 | template<typename _Tp> static Ptr<_Tp> load(const String& filename, const String& objname=String()) |
3256 | { |
3257 | FileStorage fs(filename, FileStorage::READ); |
3258 | CV_Assert(fs.isOpened()); |
3259 | FileNode fn = objname.empty() ? fs.getFirstTopLevelNode() : fs[objname]; |
3260 | if (fn.empty()) return Ptr<_Tp>(); |
3261 | Ptr<_Tp> obj = _Tp::create(); |
3262 | obj->read(fn); |
3263 | return !obj->empty() ? obj : Ptr<_Tp>(); |
3264 | } |
3265 | |
3266 | /** @brief Loads algorithm from a String |
3267 | |
3268 | @param strModel The string variable containing the model you want to load. |
3269 | @param objname The optional name of the node to read (if empty, the first top-level node will be used) |
3270 | |
3271 | This is static template method of Algorithm. It's usage is following (in the case of SVM): |
3272 | @code |
3273 | Ptr<SVM> svm = Algorithm::loadFromString<SVM>(myStringModel); |
3274 | @endcode |
3275 | */ |
3276 | template<typename _Tp> static Ptr<_Tp> loadFromString(const String& strModel, const String& objname=String()) |
3277 | { |
3278 | FileStorage fs(strModel, FileStorage::READ + FileStorage::MEMORY); |
3279 | FileNode fn = objname.empty() ? fs.getFirstTopLevelNode() : fs[objname]; |
3280 | Ptr<_Tp> obj = _Tp::create(); |
3281 | obj->read(fn); |
3282 | return !obj->empty() ? obj : Ptr<_Tp>(); |
3283 | } |
3284 | |
3285 | /** Saves the algorithm to a file. |
3286 | In order to make this method work, the derived class must implement Algorithm::write(FileStorage& fs). */ |
3287 | CV_WRAP virtual void save(const String& filename) const; |
3288 | |
3289 | /** Returns the algorithm string identifier. |
3290 | This string is used as top level xml/yml node tag when the object is saved to a file or string. */ |
3291 | CV_WRAP virtual String getDefaultName() const; |
3292 | |
3293 | protected: |
3294 | void writeFormat(FileStorage& fs) const; |
3295 | }; |
3296 | |
3297 | enum struct Param { |
3298 | INT=0, BOOLEAN=1, REAL=2, STRING=3, MAT=4, MAT_VECTOR=5, ALGORITHM=6, FLOAT=7, |
3299 | UNSIGNED_INT=8, UINT64=9, UCHAR=11, SCALAR=12 |
3300 | }; |
3301 | |
3302 | |
3303 | |
3304 | template<> struct ParamType<bool> |
3305 | { |
3306 | typedef bool const_param_type; |
3307 | typedef bool member_type; |
3308 | |
3309 | static const Param type = Param::BOOLEAN; |
3310 | }; |
3311 | |
3312 | template<> struct ParamType<int> |
3313 | { |
3314 | typedef int const_param_type; |
3315 | typedef int member_type; |
3316 | |
3317 | static const Param type = Param::INT; |
3318 | }; |
3319 | |
3320 | template<> struct ParamType<double> |
3321 | { |
3322 | typedef double const_param_type; |
3323 | typedef double member_type; |
3324 | |
3325 | static const Param type = Param::REAL; |
3326 | }; |
3327 | |
3328 | template<> struct ParamType<String> |
3329 | { |
3330 | typedef const String& const_param_type; |
3331 | typedef String member_type; |
3332 | |
3333 | static const Param type = Param::STRING; |
3334 | }; |
3335 | |
3336 | template<> struct ParamType<Mat> |
3337 | { |
3338 | typedef const Mat& const_param_type; |
3339 | typedef Mat member_type; |
3340 | |
3341 | static const Param type = Param::MAT; |
3342 | }; |
3343 | |
3344 | template<> struct ParamType<std::vector<Mat> > |
3345 | { |
3346 | typedef const std::vector<Mat>& const_param_type; |
3347 | typedef std::vector<Mat> member_type; |
3348 | |
3349 | static const Param type = Param::MAT_VECTOR; |
3350 | }; |
3351 | |
3352 | template<> struct ParamType<Algorithm> |
3353 | { |
3354 | typedef const Ptr<Algorithm>& const_param_type; |
3355 | typedef Ptr<Algorithm> member_type; |
3356 | |
3357 | static const Param type = Param::ALGORITHM; |
3358 | }; |
3359 | |
3360 | template<> struct ParamType<float> |
3361 | { |
3362 | typedef float const_param_type; |
3363 | typedef float member_type; |
3364 | |
3365 | static const Param type = Param::FLOAT; |
3366 | }; |
3367 | |
3368 | template<> struct ParamType<unsigned> |
3369 | { |
3370 | typedef unsigned const_param_type; |
3371 | typedef unsigned member_type; |
3372 | |
3373 | static const Param type = Param::UNSIGNED_INT; |
3374 | }; |
3375 | |
3376 | template<> struct ParamType<uint64> |
3377 | { |
3378 | typedef uint64 const_param_type; |
3379 | typedef uint64 member_type; |
3380 | |
3381 | static const Param type = Param::UINT64; |
3382 | }; |
3383 | |
3384 | template<> struct ParamType<uchar> |
3385 | { |
3386 | typedef uchar const_param_type; |
3387 | typedef uchar member_type; |
3388 | |
3389 | static const Param type = Param::UCHAR; |
3390 | }; |
3391 | |
3392 | template<> struct ParamType<Scalar> |
3393 | { |
3394 | typedef const Scalar& const_param_type; |
3395 | typedef Scalar member_type; |
3396 | |
3397 | static const Param type = Param::SCALAR; |
3398 | }; |
3399 | |
3400 | template<typename _Tp> |
3401 | struct ParamType<_Tp, typename std::enable_if< std::is_enum<_Tp>::value >::type> |
3402 | { |
3403 | typedef typename std::underlying_type<_Tp>::type const_param_type; |
3404 | typedef typename std::underlying_type<_Tp>::type member_type; |
3405 | |
3406 | static const Param type = Param::INT; |
3407 | }; |
3408 | |
3409 | //! @} core_basic |
3410 | |
3411 | } //namespace cv |
3412 | |
3413 | #include "opencv2/core/operations.hpp" |
3414 | #include "opencv2/core/cvstd.inl.hpp" |
3415 | #include "opencv2/core/utility.hpp" |
3416 | #include "opencv2/core/optim.hpp" |
3417 | #include "opencv2/core/ovx.hpp" |
3418 | |
3419 | #endif /*OPENCV_CORE_HPP*/ |
3420 | |