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-2008, Intel Corporation, all rights reserved.
14 // Copyright (C) 2009, Willow Garage Inc., all rights reserved.
15 // Copyright (C) 2013, OpenCV Foundation, all rights reserved.
16 // Copyright (C) 2014, 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_BASE_HPP__
46 #define __OPENCV_CORE_BASE_HPP__
47 
48 #ifndef __cplusplus
49 #  error base.hpp header must be compiled as C++
50 #endif
51 
52 #include <climits>
53 
54 #include "opencv2/core/cvdef.h"
55 #include "opencv2/core/cvstd.hpp"
56 #include "opencv2/hal.hpp"
57 
58 namespace cv
59 {
60 
61 //! @addtogroup core_utils
62 //! @{
63 
64 namespace Error {
65 //! error codes
66 enum Code {
67     StsOk=                       0,  //!< everithing is ok
68     StsBackTrace=               -1,  //!< pseudo error for back trace
69     StsError=                   -2,  //!< unknown /unspecified error
70     StsInternal=                -3,  //!< internal error (bad state)
71     StsNoMem=                   -4,  //!< insufficient memory
72     StsBadArg=                  -5,  //!< function arg/param is bad
73     StsBadFunc=                 -6,  //!< unsupported function
74     StsNoConv=                  -7,  //!< iter. didn't converge
75     StsAutoTrace=               -8,  //!< tracing
76     HeaderIsNull=               -9,  //!< image header is NULL
77     BadImageSize=              -10,  //!< image size is invalid
78     BadOffset=                 -11,  //!< offset is invalid
79     BadDataPtr=                -12,  //!<
80     BadStep=                   -13,  //!<
81     BadModelOrChSeq=           -14,  //!<
82     BadNumChannels=            -15,  //!<
83     BadNumChannel1U=           -16,  //!<
84     BadDepth=                  -17,  //!<
85     BadAlphaChannel=           -18,  //!<
86     BadOrder=                  -19,  //!<
87     BadOrigin=                 -20,  //!<
88     BadAlign=                  -21,  //!<
89     BadCallBack=               -22,  //!<
90     BadTileSize=               -23,  //!<
91     BadCOI=                    -24,  //!<
92     BadROISize=                -25,  //!<
93     MaskIsTiled=               -26,  //!<
94     StsNullPtr=                -27,  //!< null pointer
95     StsVecLengthErr=           -28,  //!< incorrect vector length
96     StsFilterStructContentErr= -29,  //!< incorr. filter structure content
97     StsKernelStructContentErr= -30,  //!< incorr. transform kernel content
98     StsFilterOffsetErr=        -31,  //!< incorrect filter ofset value
99     StsBadSize=                -201, //!< the input/output structure size is incorrect
100     StsDivByZero=              -202, //!< division by zero
101     StsInplaceNotSupported=    -203, //!< in-place operation is not supported
102     StsObjectNotFound=         -204, //!< request can't be completed
103     StsUnmatchedFormats=       -205, //!< formats of input/output arrays differ
104     StsBadFlag=                -206, //!< flag is wrong or not supported
105     StsBadPoint=               -207, //!< bad CvPoint
106     StsBadMask=                -208, //!< bad format of mask (neither 8uC1 nor 8sC1)
107     StsUnmatchedSizes=         -209, //!< sizes of input/output structures do not match
108     StsUnsupportedFormat=      -210, //!< the data format/type is not supported by the function
109     StsOutOfRange=             -211, //!< some of parameters are out of range
110     StsParseError=             -212, //!< invalid syntax/structure of the parsed file
111     StsNotImplemented=         -213, //!< the requested function/feature is not implemented
112     StsBadMemBlock=            -214, //!< an allocated block has been corrupted
113     StsAssert=                 -215, //!< assertion failed
114     GpuNotSupported=           -216,
115     GpuApiCallError=           -217,
116     OpenGlNotSupported=        -218,
117     OpenGlApiCallError=        -219,
118     OpenCLApiCallError=        -220,
119     OpenCLDoubleNotSupported=  -221,
120     OpenCLInitError=           -222,
121     OpenCLNoAMDBlasFft=        -223
122 };
123 } //Error
124 
125 //! @} core_utils
126 
127 //! @addtogroup core_array
128 //! @{
129 
130 //! matrix decomposition types
131 enum DecompTypes {
132     /** Gaussian elimination with the optimal pivot element chosen. */
133     DECOMP_LU       = 0,
134     /** singular value decomposition (SVD) method; the system can be over-defined and/or the matrix
135     src1 can be singular */
136     DECOMP_SVD      = 1,
137     /** eigenvalue decomposition; the matrix src1 must be symmetrical */
138     DECOMP_EIG      = 2,
139     /** Cholesky \f$LL^T\f$ factorization; the matrix src1 must be symmetrical and positively
140     defined */
141     DECOMP_CHOLESKY = 3,
142     /** QR factorization; the system can be over-defined and/or the matrix src1 can be singular */
143     DECOMP_QR       = 4,
144     /** while all the previous flags are mutually exclusive, this flag can be used together with
145     any of the previous; it means that the normal equations
146     \f$\texttt{src1}^T\cdot\texttt{src1}\cdot\texttt{dst}=\texttt{src1}^T\texttt{src2}\f$ are
147     solved instead of the original system
148     \f$\texttt{src1}\cdot\texttt{dst}=\texttt{src2}\f$ */
149     DECOMP_NORMAL   = 16
150 };
151 
152 /** norm types
153 - For one array:
154 \f[norm =  \forkthree{\|\texttt{src1}\|_{L_{\infty}} =  \max _I | \texttt{src1} (I)|}{if  \(\texttt{normType} = \texttt{NORM\_INF}\) }
155 { \| \texttt{src1} \| _{L_1} =  \sum _I | \texttt{src1} (I)|}{if  \(\texttt{normType} = \texttt{NORM\_L1}\) }
156 { \| \texttt{src1} \| _{L_2} =  \sqrt{\sum_I \texttt{src1}(I)^2} }{if  \(\texttt{normType} = \texttt{NORM\_L2}\) }\f]
157 
158 - Absolute norm for two arrays
159 \f[norm =  \forkthree{\|\texttt{src1}-\texttt{src2}\|_{L_{\infty}} =  \max _I | \texttt{src1} (I) -  \texttt{src2} (I)|}{if  \(\texttt{normType} = \texttt{NORM\_INF}\) }
160 { \| \texttt{src1} - \texttt{src2} \| _{L_1} =  \sum _I | \texttt{src1} (I) -  \texttt{src2} (I)|}{if  \(\texttt{normType} = \texttt{NORM\_L1}\) }
161 { \| \texttt{src1} - \texttt{src2} \| _{L_2} =  \sqrt{\sum_I (\texttt{src1}(I) - \texttt{src2}(I))^2} }{if  \(\texttt{normType} = \texttt{NORM\_L2}\) }\f]
162 
163 - Relative norm for two arrays
164 \f[norm =  \forkthree{\frac{\|\texttt{src1}-\texttt{src2}\|_{L_{\infty}}    }{\|\texttt{src2}\|_{L_{\infty}} }}{if  \(\texttt{normType} = \texttt{NORM\_RELATIVE\_INF}\) }
165 { \frac{\|\texttt{src1}-\texttt{src2}\|_{L_1} }{\|\texttt{src2}\|_{L_1}} }{if  \(\texttt{normType} = \texttt{NORM\_RELATIVE\_L1}\) }
166 { \frac{\|\texttt{src1}-\texttt{src2}\|_{L_2} }{\|\texttt{src2}\|_{L_2}} }{if  \(\texttt{normType} = \texttt{NORM\_RELATIVE\_L2}\) }\f]
167   */
168 enum NormTypes { NORM_INF       = 1,
169                  NORM_L1        = 2,
170                  NORM_L2        = 4,
171                  NORM_L2SQR     = 5,
172                  NORM_HAMMING   = 6,
173                  NORM_HAMMING2  = 7,
174                  NORM_TYPE_MASK = 7,
175                  NORM_RELATIVE  = 8, //!< flag
176                  NORM_MINMAX    = 32 //!< flag
177                };
178 
179 //! comparison types
180 enum CmpTypes { CMP_EQ = 0, //!< src1 is equal to src2.
181                 CMP_GT = 1, //!< src1 is greater than src2.
182                 CMP_GE = 2, //!< src1 is greater than or equal to src2.
183                 CMP_LT = 3, //!< src1 is less than src2.
184                 CMP_LE = 4, //!< src1 is less than or equal to src2.
185                 CMP_NE = 5  //!< src1 is unequal to src2.
186               };
187 
188 //! generalized matrix multiplication flags
189 enum GemmFlags { GEMM_1_T = 1, //!< transposes src1
190                  GEMM_2_T = 2, //!< transposes src2
191                  GEMM_3_T = 4 //!< transposes src3
192                };
193 
194 enum DftFlags {
195     /** performs an inverse 1D or 2D transform instead of the default forward
196         transform. */
197     DFT_INVERSE        = 1,
198     /** scales the result: divide it by the number of array elements. Normally, it is
199         combined with DFT_INVERSE. */
200     DFT_SCALE          = 2,
201     /** performs a forward or inverse transform of every individual row of the input
202         matrix; this flag enables you to transform multiple vectors simultaneously and can be used to
203         decrease the overhead (which is sometimes several times larger than the processing itself) to
204         perform 3D and higher-dimensional transformations and so forth.*/
205     DFT_ROWS           = 4,
206     /** performs a forward transformation of 1D or 2D real array; the result,
207         though being a complex array, has complex-conjugate symmetry (*CCS*, see the function
208         description below for details), and such an array can be packed into a real array of the same
209         size as input, which is the fastest option and which is what the function does by default;
210         however, you may wish to get a full complex array (for simpler spectrum analysis, and so on) -
211         pass the flag to enable the function to produce a full-size complex output array. */
212     DFT_COMPLEX_OUTPUT = 16,
213     /** performs an inverse transformation of a 1D or 2D complex array; the
214         result is normally a complex array of the same size, however, if the input array has
215         conjugate-complex symmetry (for example, it is a result of forward transformation with
216         DFT_COMPLEX_OUTPUT flag), the output is a real array; while the function itself does not
217         check whether the input is symmetrical or not, you can pass the flag and then the function
218         will assume the symmetry and produce the real output array (note that when the input is packed
219         into a real array and inverse transformation is executed, the function treats the input as a
220         packed complex-conjugate symmetrical array, and the output will also be a real array). */
221     DFT_REAL_OUTPUT    = 32,
222     /** performs an inverse 1D or 2D transform instead of the default forward transform. */
223     DCT_INVERSE        = DFT_INVERSE,
224     /** performs a forward or inverse transform of every individual row of the input
225         matrix. This flag enables you to transform multiple vectors simultaneously and can be used to
226         decrease the overhead (which is sometimes several times larger than the processing itself) to
227         perform 3D and higher-dimensional transforms and so forth.*/
228     DCT_ROWS           = DFT_ROWS
229 };
230 
231 //! Various border types, image boundaries are denoted with `|`
232 //! @see borderInterpolate, copyMakeBorder
233 enum BorderTypes {
234     BORDER_CONSTANT    = 0, //!< `iiiiii|abcdefgh|iiiiiii`  with some specified `i`
235     BORDER_REPLICATE   = 1, //!< `aaaaaa|abcdefgh|hhhhhhh`
236     BORDER_REFLECT     = 2, //!< `fedcba|abcdefgh|hgfedcb`
237     BORDER_WRAP        = 3, //!< `cdefgh|abcdefgh|abcdefg`
238     BORDER_REFLECT_101 = 4, //!< `gfedcb|abcdefgh|gfedcba`
239     BORDER_TRANSPARENT = 5, //!< `uvwxyz|absdefgh|ijklmno`
240 
241     BORDER_REFLECT101  = BORDER_REFLECT_101, //!< same as BORDER_REFLECT_101
242     BORDER_DEFAULT     = BORDER_REFLECT_101, //!< same as BORDER_REFLECT_101
243     BORDER_ISOLATED    = 16 //!< do not look outside of ROI
244 };
245 
246 //! @} core_array
247 
248 //! @addtogroup core_utils
249 //! @{
250 
251 //! @cond IGNORED
252 
253 //////////////// static assert /////////////////
254 #define CVAUX_CONCAT_EXP(a, b) a##b
255 #define CVAUX_CONCAT(a, b) CVAUX_CONCAT_EXP(a,b)
256 
257 #if defined(__clang__)
258 #  ifndef __has_extension
259 #    define __has_extension __has_feature /* compatibility, for older versions of clang */
260 #  endif
261 #  if __has_extension(cxx_static_assert)
262 #    define CV_StaticAssert(condition, reason)    static_assert((condition), reason " " #condition)
263 #  endif
264 #elif defined(__GNUC__)
265 #  if (defined(__GXX_EXPERIMENTAL_CXX0X__) || __cplusplus >= 201103L)
266 #    define CV_StaticAssert(condition, reason)    static_assert((condition), reason " " #condition)
267 #  endif
268 #elif defined(_MSC_VER)
269 #  if _MSC_VER >= 1600 /* MSVC 10 */
270 #    define CV_StaticAssert(condition, reason)    static_assert((condition), reason " " #condition)
271 #  endif
272 #endif
273 #ifndef CV_StaticAssert
274 #  if defined(__GNUC__) && (__GNUC__ > 3) && (__GNUC_MINOR__ > 2)
275 #    define CV_StaticAssert(condition, reason) ({ extern int __attribute__((error("CV_StaticAssert: " reason " " #condition))) CV_StaticAssert(); ((condition) ? 0 : CV_StaticAssert()); })
276 #  else
277      template <bool x> struct CV_StaticAssert_failed;
278      template <> struct CV_StaticAssert_failed<true> { enum { val = 1 }; };
279      template<int x> struct CV_StaticAssert_test {};
280 #    define CV_StaticAssert(condition, reason)\
281        typedef cv::CV_StaticAssert_test< sizeof(cv::CV_StaticAssert_failed< static_cast<bool>(condition) >) > CVAUX_CONCAT(CV_StaticAssert_failed_at_, __LINE__)
282 #  endif
283 #endif
284 
285 // Suppress warning "-Wdeprecated-declarations" / C4996
286 #if defined(_MSC_VER)
287     #define CV_DO_PRAGMA(x) __pragma(x)
288 #elif defined(__GNUC__)
289     #define CV_DO_PRAGMA(x) _Pragma (#x)
290 #else
291     #define CV_DO_PRAGMA(x)
292 #endif
293 
294 #ifdef _MSC_VER
295 #define CV_SUPPRESS_DEPRECATED_START \
296     CV_DO_PRAGMA(warning(push)) \
297     CV_DO_PRAGMA(warning(disable: 4996))
298 #define CV_SUPPRESS_DEPRECATED_END CV_DO_PRAGMA(warning(pop))
299 #elif defined (__clang__) || ((__GNUC__)  && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5))))
300 #define CV_SUPPRESS_DEPRECATED_START \
301     CV_DO_PRAGMA(GCC diagnostic push) \
302     CV_DO_PRAGMA(GCC diagnostic ignored "-Wdeprecated-declarations")
303 #define CV_SUPPRESS_DEPRECATED_END CV_DO_PRAGMA(GCC diagnostic pop)
304 #else
305 #define CV_SUPPRESS_DEPRECATED_START
306 #define CV_SUPPRESS_DEPRECATED_END
307 #endif
308 //! @endcond
309 
310 /*! @brief Signals an error and raises the exception.
311 
312 By default the function prints information about the error to stderr,
313 then it either stops if setBreakOnError() had been called before or raises the exception.
314 It is possible to alternate error processing by using redirectError().
315 @param _code - error code (Error::Code)
316 @param _err - error description
317 @param _func - function name. Available only when the compiler supports getting it
318 @param _file - source file name where the error has occured
319 @param _line - line number in the source file where the error has occured
320 @see CV_Error, CV_Error_, CV_ErrorNoReturn, CV_ErrorNoReturn_, CV_Assert, CV_DbgAssert
321  */
322 CV_EXPORTS void error(int _code, const String& _err, const char* _func, const char* _file, int _line);
323 
324 #ifdef __GNUC__
325 # if defined __clang__ || defined __APPLE__
326 #   pragma GCC diagnostic push
327 #   pragma GCC diagnostic ignored "-Winvalid-noreturn"
328 # endif
329 #endif
330 
331 /** same as cv::error, but does not return */
errorNoReturn(int _code,const String & _err,const char * _func,const char * _file,int _line)332 CV_INLINE CV_NORETURN void errorNoReturn(int _code, const String& _err, const char* _func, const char* _file, int _line)
333 {
334     error(_code, _err, _func, _file, _line);
335 #ifdef __GNUC__
336 # if !defined __clang__ && !defined __APPLE__
337     // this suppresses this warning: "noreturn" function does return [enabled by default]
338     __builtin_trap();
339     // or use infinite loop: for (;;) {}
340 # endif
341 #endif
342 }
343 #ifdef __GNUC__
344 # if defined __clang__ || defined __APPLE__
345 #   pragma GCC diagnostic pop
346 # endif
347 #endif
348 
349 #if defined __GNUC__
350 #define CV_Func __func__
351 #elif defined _MSC_VER
352 #define CV_Func __FUNCTION__
353 #else
354 #define CV_Func ""
355 #endif
356 
357 /** @brief Call the error handler.
358 
359 Currently, the error handler prints the error code and the error message to the standard
360 error stream `stderr`. In the Debug configuration, it then provokes memory access violation, so that
361 the execution stack and all the parameters can be analyzed by the debugger. In the Release
362 configuration, the exception is thrown.
363 
364 @param code one of Error::Code
365 @param msg error message
366 */
367 #define CV_Error( code, msg ) cv::error( code, msg, CV_Func, __FILE__, __LINE__ )
368 
369 /**  @brief Call the error handler.
370 
371 This macro can be used to construct an error message on-fly to include some dynamic information,
372 for example:
373 @code
374     // note the extra parentheses around the formatted text message
375     CV_Error_( CV_StsOutOfRange,
376     ("the value at (%d, %d)=%g is out of range", badPt.x, badPt.y, badValue));
377 @endcode
378 @param code one of Error::Code
379 @param args printf-like formatted error message in parentheses
380 */
381 #define CV_Error_( code, args ) cv::error( code, cv::format args, CV_Func, __FILE__, __LINE__ )
382 
383 /** @brief Checks a condition at runtime and throws exception if it fails
384 
385 The macros CV_Assert (and CV_DbgAssert(expr)) evaluate the specified expression. If it is 0, the macros
386 raise an error (see cv::error). The macro CV_Assert checks the condition in both Debug and Release
387 configurations while CV_DbgAssert is only retained in the Debug configuration.
388 */
389 #define CV_Assert( expr ) if(!!(expr)) ; else cv::error( cv::Error::StsAssert, #expr, CV_Func, __FILE__, __LINE__ )
390 
391 /** same as CV_Error(code,msg), but does not return */
392 #define CV_ErrorNoReturn( code, msg ) cv::errorNoReturn( code, msg, CV_Func, __FILE__, __LINE__ )
393 
394 /** same as CV_Error_(code,args), but does not return */
395 #define CV_ErrorNoReturn_( code, args ) cv::errorNoReturn( code, cv::format args, CV_Func, __FILE__, __LINE__ )
396 
397 /** replaced with CV_Assert(expr) in Debug configuration */
398 #ifdef _DEBUG
399 #  define CV_DbgAssert(expr) CV_Assert(expr)
400 #else
401 #  define CV_DbgAssert(expr)
402 #endif
403 
404 /*
405  * Hamming distance functor - counts the bit differences between two strings - useful for the Brief descriptor
406  * bit count of A exclusive XOR'ed with B
407  */
408 struct CV_EXPORTS Hamming
409 {
410     enum { normType = NORM_HAMMING };
411     typedef unsigned char ValueType;
412     typedef int ResultType;
413 
414     /** this will count the bits in a ^ b
415      */
416     ResultType operator()( const unsigned char* a, const unsigned char* b, int size ) const;
417 };
418 
419 typedef Hamming HammingLUT;
420 
421 /////////////////////////////////// inline norms ////////////////////////////////////
422 
cv_abs(_Tp x)423 template<typename _Tp> inline _Tp cv_abs(_Tp x) { return std::abs(x); }
cv_abs(uchar x)424 inline int cv_abs(uchar x) { return x; }
cv_abs(schar x)425 inline int cv_abs(schar x) { return std::abs(x); }
cv_abs(ushort x)426 inline int cv_abs(ushort x) { return x; }
cv_abs(short x)427 inline int cv_abs(short x) { return std::abs(x); }
428 
429 template<typename _Tp, typename _AccTp> static inline
normL2Sqr(const _Tp * a,int n)430 _AccTp normL2Sqr(const _Tp* a, int n)
431 {
432     _AccTp s = 0;
433     int i=0;
434 #if CV_ENABLE_UNROLLED
435     for( ; i <= n - 4; i += 4 )
436     {
437         _AccTp v0 = a[i], v1 = a[i+1], v2 = a[i+2], v3 = a[i+3];
438         s += v0*v0 + v1*v1 + v2*v2 + v3*v3;
439     }
440 #endif
441     for( ; i < n; i++ )
442     {
443         _AccTp v = a[i];
444         s += v*v;
445     }
446     return s;
447 }
448 
449 template<typename _Tp, typename _AccTp> static inline
normL1(const _Tp * a,int n)450 _AccTp normL1(const _Tp* a, int n)
451 {
452     _AccTp s = 0;
453     int i = 0;
454 #if CV_ENABLE_UNROLLED
455     for(; i <= n - 4; i += 4 )
456     {
457         s += (_AccTp)cv_abs(a[i]) + (_AccTp)cv_abs(a[i+1]) +
458             (_AccTp)cv_abs(a[i+2]) + (_AccTp)cv_abs(a[i+3]);
459     }
460 #endif
461     for( ; i < n; i++ )
462         s += cv_abs(a[i]);
463     return s;
464 }
465 
466 template<typename _Tp, typename _AccTp> static inline
normInf(const _Tp * a,int n)467 _AccTp normInf(const _Tp* a, int n)
468 {
469     _AccTp s = 0;
470     for( int i = 0; i < n; i++ )
471         s = std::max(s, (_AccTp)cv_abs(a[i]));
472     return s;
473 }
474 
475 template<typename _Tp, typename _AccTp> static inline
normL2Sqr(const _Tp * a,const _Tp * b,int n)476 _AccTp normL2Sqr(const _Tp* a, const _Tp* b, int n)
477 {
478     _AccTp s = 0;
479     int i= 0;
480 #if CV_ENABLE_UNROLLED
481     for(; i <= n - 4; i += 4 )
482     {
483         _AccTp v0 = _AccTp(a[i] - b[i]), v1 = _AccTp(a[i+1] - b[i+1]), v2 = _AccTp(a[i+2] - b[i+2]), v3 = _AccTp(a[i+3] - b[i+3]);
484         s += v0*v0 + v1*v1 + v2*v2 + v3*v3;
485     }
486 #endif
487     for( ; i < n; i++ )
488     {
489         _AccTp v = _AccTp(a[i] - b[i]);
490         s += v*v;
491     }
492     return s;
493 }
494 
normL2Sqr(const float * a,const float * b,int n)495 static inline float normL2Sqr(const float* a, const float* b, int n)
496 {
497     float s = 0.f;
498     for( int i = 0; i < n; i++ )
499     {
500         float v = a[i] - b[i];
501         s += v*v;
502     }
503     return s;
504 }
505 
506 template<typename _Tp, typename _AccTp> static inline
normL1(const _Tp * a,const _Tp * b,int n)507 _AccTp normL1(const _Tp* a, const _Tp* b, int n)
508 {
509     _AccTp s = 0;
510     int i= 0;
511 #if CV_ENABLE_UNROLLED
512     for(; i <= n - 4; i += 4 )
513     {
514         _AccTp v0 = _AccTp(a[i] - b[i]), v1 = _AccTp(a[i+1] - b[i+1]), v2 = _AccTp(a[i+2] - b[i+2]), v3 = _AccTp(a[i+3] - b[i+3]);
515         s += std::abs(v0) + std::abs(v1) + std::abs(v2) + std::abs(v3);
516     }
517 #endif
518     for( ; i < n; i++ )
519     {
520         _AccTp v = _AccTp(a[i] - b[i]);
521         s += std::abs(v);
522     }
523     return s;
524 }
525 
normL1(const float * a,const float * b,int n)526 inline float normL1(const float* a, const float* b, int n)
527 {
528     float s = 0.f;
529     for( int i = 0; i < n; i++ )
530     {
531         s += std::abs(a[i] - b[i]);
532     }
533     return s;
534 }
535 
normL1(const uchar * a,const uchar * b,int n)536 inline int normL1(const uchar* a, const uchar* b, int n)
537 {
538     int s = 0;
539     for( int i = 0; i < n; i++ )
540     {
541         s += std::abs(a[i] - b[i]);
542     }
543     return s;
544 }
545 
546 template<typename _Tp, typename _AccTp> static inline
normInf(const _Tp * a,const _Tp * b,int n)547 _AccTp normInf(const _Tp* a, const _Tp* b, int n)
548 {
549     _AccTp s = 0;
550     for( int i = 0; i < n; i++ )
551     {
552         _AccTp v0 = a[i] - b[i];
553         s = std::max(s, std::abs(v0));
554     }
555     return s;
556 }
557 
558 /** @brief Computes the cube root of an argument.
559 
560  The function cubeRoot computes \f$\sqrt[3]{\texttt{val}}\f$. Negative arguments are handled correctly.
561  NaN and Inf are not handled. The accuracy approaches the maximum possible accuracy for
562  single-precision data.
563  @param val A function argument.
564  */
565 CV_EXPORTS_W float cubeRoot(float val);
566 
567 /** @brief Calculates the angle of a 2D vector in degrees.
568 
569  The function fastAtan2 calculates the full-range angle of an input 2D vector. The angle is measured
570  in degrees and varies from 0 to 360 degrees. The accuracy is about 0.3 degrees.
571  @param x x-coordinate of the vector.
572  @param y y-coordinate of the vector.
573  */
574 CV_EXPORTS_W float fastAtan2(float y, float x);
575 
576 /** proxy for hal::LU */
577 CV_EXPORTS int LU(float* A, size_t astep, int m, float* b, size_t bstep, int n);
578 /** proxy for hal::LU */
579 CV_EXPORTS int LU(double* A, size_t astep, int m, double* b, size_t bstep, int n);
580 /** proxy for hal::Cholesky */
581 CV_EXPORTS bool Cholesky(float* A, size_t astep, int m, float* b, size_t bstep, int n);
582 /** proxy for hal::Cholesky */
583 CV_EXPORTS bool Cholesky(double* A, size_t astep, int m, double* b, size_t bstep, int n);
584 
585 ////////////////// forward declarations for important OpenCV types //////////////////
586 
587 //! @cond IGNORED
588 
589 template<typename _Tp, int cn> class Vec;
590 template<typename _Tp, int m, int n> class Matx;
591 
592 template<typename _Tp> class Complex;
593 template<typename _Tp> class Point_;
594 template<typename _Tp> class Point3_;
595 template<typename _Tp> class Size_;
596 template<typename _Tp> class Rect_;
597 template<typename _Tp> class Scalar_;
598 
599 class CV_EXPORTS RotatedRect;
600 class CV_EXPORTS Range;
601 class CV_EXPORTS TermCriteria;
602 class CV_EXPORTS KeyPoint;
603 class CV_EXPORTS DMatch;
604 class CV_EXPORTS RNG;
605 
606 class CV_EXPORTS Mat;
607 class CV_EXPORTS MatExpr;
608 
609 class CV_EXPORTS UMat;
610 
611 class CV_EXPORTS SparseMat;
612 typedef Mat MatND;
613 
614 template<typename _Tp> class Mat_;
615 template<typename _Tp> class SparseMat_;
616 
617 class CV_EXPORTS MatConstIterator;
618 class CV_EXPORTS SparseMatIterator;
619 class CV_EXPORTS SparseMatConstIterator;
620 template<typename _Tp> class MatIterator_;
621 template<typename _Tp> class MatConstIterator_;
622 template<typename _Tp> class SparseMatIterator_;
623 template<typename _Tp> class SparseMatConstIterator_;
624 
625 namespace ogl
626 {
627     class CV_EXPORTS Buffer;
628     class CV_EXPORTS Texture2D;
629     class CV_EXPORTS Arrays;
630 }
631 
632 namespace cuda
633 {
634     class CV_EXPORTS GpuMat;
635     class CV_EXPORTS HostMem;
636     class CV_EXPORTS Stream;
637     class CV_EXPORTS Event;
638 }
639 
640 namespace cudev
641 {
642     template <typename _Tp> class GpuMat_;
643 }
644 
645 namespace ipp
646 {
647 CV_EXPORTS void setIppStatus(int status, const char * const funcname = NULL, const char * const filename = NULL,
648                              int line = 0);
649 CV_EXPORTS int getIppStatus();
650 CV_EXPORTS String getIppErrorLocation();
651 CV_EXPORTS bool useIPP();
652 CV_EXPORTS void setUseIPP(bool flag);
653 
654 } // ipp
655 
656 //! @endcond
657 
658 //! @} core_utils
659 
660 //! @addtogroup core_utils_neon
661 //! @{
662 
663 #if CV_NEON
664 
cv_vrnd_s32_f32(float32x2_t v)665 inline int32x2_t cv_vrnd_s32_f32(float32x2_t v)
666 {
667     static int32x2_t v_sign = vdup_n_s32(1 << 31),
668         v_05 = vreinterpret_s32_f32(vdup_n_f32(0.5f));
669 
670     int32x2_t v_addition = vorr_s32(v_05, vand_s32(v_sign, vreinterpret_s32_f32(v)));
671     return vcvt_s32_f32(vadd_f32(v, vreinterpret_f32_s32(v_addition)));
672 }
673 
cv_vrndq_s32_f32(float32x4_t v)674 inline int32x4_t cv_vrndq_s32_f32(float32x4_t v)
675 {
676     static int32x4_t v_sign = vdupq_n_s32(1 << 31),
677         v_05 = vreinterpretq_s32_f32(vdupq_n_f32(0.5f));
678 
679     int32x4_t v_addition = vorrq_s32(v_05, vandq_s32(v_sign, vreinterpretq_s32_f32(v)));
680     return vcvtq_s32_f32(vaddq_f32(v, vreinterpretq_f32_s32(v_addition)));
681 }
682 
cv_vrnd_u32_f32(float32x2_t v)683 inline uint32x2_t cv_vrnd_u32_f32(float32x2_t v)
684 {
685     static float32x2_t v_05 = vdup_n_f32(0.5f);
686     return vcvt_u32_f32(vadd_f32(v, v_05));
687 }
688 
cv_vrndq_u32_f32(float32x4_t v)689 inline uint32x4_t cv_vrndq_u32_f32(float32x4_t v)
690 {
691     static float32x4_t v_05 = vdupq_n_f32(0.5f);
692     return vcvtq_u32_f32(vaddq_f32(v, v_05));
693 }
694 
cv_vrecpq_f32(float32x4_t val)695 inline float32x4_t cv_vrecpq_f32(float32x4_t val)
696 {
697     float32x4_t reciprocal = vrecpeq_f32(val);
698     reciprocal = vmulq_f32(vrecpsq_f32(val, reciprocal), reciprocal);
699     reciprocal = vmulq_f32(vrecpsq_f32(val, reciprocal), reciprocal);
700     return reciprocal;
701 }
702 
cv_vrecp_f32(float32x2_t val)703 inline float32x2_t cv_vrecp_f32(float32x2_t val)
704 {
705     float32x2_t reciprocal = vrecpe_f32(val);
706     reciprocal = vmul_f32(vrecps_f32(val, reciprocal), reciprocal);
707     reciprocal = vmul_f32(vrecps_f32(val, reciprocal), reciprocal);
708     return reciprocal;
709 }
710 
cv_vrsqrtq_f32(float32x4_t val)711 inline float32x4_t cv_vrsqrtq_f32(float32x4_t val)
712 {
713     float32x4_t e = vrsqrteq_f32(val);
714     e = vmulq_f32(vrsqrtsq_f32(vmulq_f32(e, e), val), e);
715     e = vmulq_f32(vrsqrtsq_f32(vmulq_f32(e, e), val), e);
716     return e;
717 }
718 
cv_vrsqrt_f32(float32x2_t val)719 inline float32x2_t cv_vrsqrt_f32(float32x2_t val)
720 {
721     float32x2_t e = vrsqrte_f32(val);
722     e = vmul_f32(vrsqrts_f32(vmul_f32(e, e), val), e);
723     e = vmul_f32(vrsqrts_f32(vmul_f32(e, e), val), e);
724     return e;
725 }
726 
cv_vsqrtq_f32(float32x4_t val)727 inline float32x4_t cv_vsqrtq_f32(float32x4_t val)
728 {
729     return cv_vrecpq_f32(cv_vrsqrtq_f32(val));
730 }
731 
cv_vsqrt_f32(float32x2_t val)732 inline float32x2_t cv_vsqrt_f32(float32x2_t val)
733 {
734     return cv_vrecp_f32(cv_vrsqrt_f32(val));
735 }
736 
737 #endif
738 
739 //! @} core_utils_neon
740 
741 } // cv
742 
743 #include "sse_utils.hpp"
744 
745 #endif //__OPENCV_CORE_BASE_HPP__
746