Fix Android build warnings
[profile/ivi/opencv.git] / modules / ts / include / opencv2 / ts / ts.hpp
1 #ifndef __OPENCV_GTESTCV_HPP__
2 #define __OPENCV_GTESTCV_HPP__
3
4 #if HAVE_CVCONFIG_H
5 #include "cvconfig.h"
6 #endif
7 #ifndef GTEST_CREATE_SHARED_LIBRARY
8 #ifdef BUILD_SHARED_LIBS
9 #define GTEST_LINKED_AS_SHARED_LIBRARY 1
10 #endif
11 #endif
12
13 #ifdef ANDROID
14 # include <android/api-level.h>
15 # define GTEST_HAS_CLONE (__ANDROID_API__ > 7 && !defined __i386__)
16 # define GTEST_HAS_POSIX_RE (__ANDROID_API__ > 7)
17 # if defined _GLIBCXX_USE_WCHAR_T && _GLIBCXX_USE_WCHAR_T
18 #  define GTEST_HAS_STD_WSTRING 1
19 # else
20 #  define GTEST_HAS_STD_WSTRING 0
21 #endif
22 #endif
23
24 #include <stdarg.h> // for va_list
25
26 #ifdef _MSC_VER
27 #pragma warning( disable: 4127 )
28 #endif
29
30 #define GTEST_DONT_DEFINE_FAIL      0
31 #define GTEST_DONT_DEFINE_SUCCEED   0
32 #define GTEST_DONT_DEFINE_ASSERT_EQ 0
33 #define GTEST_DONT_DEFINE_ASSERT_NE 0
34 #define GTEST_DONT_DEFINE_ASSERT_LE 0
35 #define GTEST_DONT_DEFINE_ASSERT_LT 0
36 #define GTEST_DONT_DEFINE_ASSERT_GE 0
37 #define GTEST_DONT_DEFINE_ASSERT_GT 0
38 #define GTEST_DONT_DEFINE_TEST      0
39
40 #include "opencv2/ts/ts_gtest.h"
41
42 #ifndef GTEST_USES_SIMPLE_RE
43 #  define GTEST_USES_SIMPLE_RE 0
44 #endif
45 #ifndef GTEST_USES_POSIX_RE
46 #  define GTEST_USES_POSIX_RE 0
47 #endif
48
49 #include "opencv2/core/core.hpp"
50
51 namespace cvtest
52 {
53
54 using std::vector;
55 using std::string;
56 using cv::RNG;
57 using cv::Mat;
58 using cv::Scalar;
59 using cv::Size;
60 using cv::Point;
61 using cv::Rect;
62
63 class CV_EXPORTS TS;
64
65 CV_EXPORTS int64 readSeed(const char* str);
66
67 CV_EXPORTS void randUni( RNG& rng, Mat& a, const Scalar& param1, const Scalar& param2 );
68
69 inline unsigned randInt( RNG& rng )
70 {
71     return (unsigned)rng;
72 }
73
74 inline  double randReal( RNG& rng )
75 {
76     return (double)rng;
77 }
78
79
80 CV_EXPORTS const char* getTypeName( int type );
81 CV_EXPORTS int typeByName( const char* type_name );
82
83 CV_EXPORTS string vec2str(const string& sep, const int* v, size_t nelems);
84
85 inline int clipInt( int val, int min_val, int max_val )
86 {
87     if( val < min_val )
88         val = min_val;
89     if( val > max_val )
90         val = max_val;
91     return val;
92 }
93
94 CV_EXPORTS double getMinVal(int depth);
95 CV_EXPORTS double getMaxVal(int depth);
96
97 CV_EXPORTS Size randomSize(RNG& rng, double maxSizeLog);
98 CV_EXPORTS void randomSize(RNG& rng, int minDims, int maxDims, double maxSizeLog, vector<int>& sz);
99 CV_EXPORTS int randomType(RNG& rng, int typeMask, int minChannels, int maxChannels);
100 CV_EXPORTS Mat randomMat(RNG& rng, Size size, int type, double minVal, double maxVal, bool useRoi);
101 CV_EXPORTS Mat randomMat(RNG& rng, const vector<int>& size, int type, double minVal, double maxVal, bool useRoi);
102 CV_EXPORTS void add(const Mat& a, double alpha, const Mat& b, double beta,
103                       Scalar gamma, Mat& c, int ctype, bool calcAbs=false);
104 CV_EXPORTS void multiply(const Mat& a, const Mat& b, Mat& c, double alpha=1);
105 CV_EXPORTS void divide(const Mat& a, const Mat& b, Mat& c, double alpha=1);
106
107 CV_EXPORTS void convert(const Mat& src, Mat& dst, int dtype, double alpha=1, double beta=0);
108 CV_EXPORTS void copy(const Mat& src, Mat& dst, const Mat& mask=Mat(), bool invertMask=false);
109 CV_EXPORTS void set(Mat& dst, const Scalar& gamma, const Mat& mask=Mat());
110
111 // working with multi-channel arrays
112 CV_EXPORTS void extract( const Mat& a, Mat& plane, int coi );
113 CV_EXPORTS void insert( const Mat& plane, Mat& a, int coi );
114
115 // checks that the array does not have NaNs and/or Infs and all the elements are
116 // within [min_val,max_val). idx is the index of the first "bad" element.
117 CV_EXPORTS int check( const Mat& data, double min_val, double max_val, vector<int>* idx );
118
119 // modifies values that are close to zero
120 CV_EXPORTS void  patchZeros( Mat& mat, double level );
121
122 CV_EXPORTS void transpose(const Mat& src, Mat& dst);
123 CV_EXPORTS void erode(const Mat& src, Mat& dst, const Mat& _kernel, Point anchor=Point(-1,-1),
124                       int borderType=IPL_BORDER_CONSTANT, const Scalar& borderValue=Scalar());
125 CV_EXPORTS void dilate(const Mat& src, Mat& dst, const Mat& _kernel, Point anchor=Point(-1,-1),
126                        int borderType=IPL_BORDER_CONSTANT, const Scalar& borderValue=Scalar());
127 CV_EXPORTS void filter2D(const Mat& src, Mat& dst, int ddepth, const Mat& kernel,
128                          Point anchor, double delta, int borderType,
129                          const Scalar& borderValue=Scalar());
130 CV_EXPORTS void copyMakeBorder(const Mat& src, Mat& dst, int top, int bottom, int left, int right,
131                                int borderType, const Scalar& borderValue=Scalar());
132 CV_EXPORTS Mat calcSobelKernel2D( int dx, int dy, int apertureSize, int origin=0 );
133 CV_EXPORTS Mat calcLaplaceKernel2D( int aperture_size );
134
135 CV_EXPORTS void initUndistortMap( const Mat& a, const Mat& k, Size sz, Mat& mapx, Mat& mapy );
136
137 CV_EXPORTS void minMaxLoc(const Mat& src, double* minval, double* maxval,
138                           vector<int>* minloc, vector<int>* maxloc, const Mat& mask=Mat());
139 CV_EXPORTS double norm(const Mat& src, int normType, const Mat& mask=Mat());
140 CV_EXPORTS double norm(const Mat& src1, const Mat& src2, int normType, const Mat& mask=Mat());
141 CV_EXPORTS Scalar mean(const Mat& src, const Mat& mask=Mat());
142
143 CV_EXPORTS bool cmpUlps(const Mat& data, const Mat& refdata, int expMaxDiff, double* realMaxDiff, vector<int>* idx);
144
145 // compares two arrays. max_diff is the maximum actual difference,
146 // success_err_level is maximum allowed difference, idx is the index of the first
147 // element for which difference is >success_err_level
148 // (or index of element with the maximum difference)
149 CV_EXPORTS int cmpEps( const Mat& data, const Mat& refdata, double* max_diff,
150                        double success_err_level, vector<int>* idx,
151                        bool element_wise_relative_error );
152
153 // a wrapper for the previous function. in case of error prints the message to log file.
154 CV_EXPORTS int cmpEps2( TS* ts, const Mat& data, const Mat& refdata, double success_err_level,
155                         bool element_wise_relative_error, const char* desc );
156
157 CV_EXPORTS int cmpEps2_64f( TS* ts, const double* val, const double* refval, int len,
158                         double eps, const char* param_name );
159
160 CV_EXPORTS void logicOp(const Mat& src1, const Mat& src2, Mat& dst, char c);
161 CV_EXPORTS void logicOp(const Mat& src, const Scalar& s, Mat& dst, char c);
162 CV_EXPORTS void min(const Mat& src1, const Mat& src2, Mat& dst);
163 CV_EXPORTS void min(const Mat& src, double s, Mat& dst);
164 CV_EXPORTS void max(const Mat& src1, const Mat& src2, Mat& dst);
165 CV_EXPORTS void max(const Mat& src, double s, Mat& dst);
166
167 CV_EXPORTS void compare(const Mat& src1, const Mat& src2, Mat& dst, int cmpop);
168 CV_EXPORTS void compare(const Mat& src, double s, Mat& dst, int cmpop);
169 CV_EXPORTS void gemm(const Mat& src1, const Mat& src2, double alpha,
170                      const Mat& src3, double beta, Mat& dst, int flags);
171     CV_EXPORTS void transform( const Mat& src, Mat& dst, const Mat& transmat, const Mat& shift );
172 CV_EXPORTS double crossCorr(const Mat& src1, const Mat& src2);
173
174 struct CV_EXPORTS MatInfo
175 {
176     MatInfo(const Mat& _m) : m(&_m) {}
177     const Mat* m;
178 };
179
180 CV_EXPORTS std::ostream& operator << (std::ostream& out, const MatInfo& m);
181
182 struct CV_EXPORTS MatComparator
183 {
184 public:
185     MatComparator(double maxdiff, int context);
186
187     ::testing::AssertionResult operator()(const char* expr1, const char* expr2,
188                                           const Mat& m1, const Mat& m2);
189
190     double maxdiff;
191     double realmaxdiff;
192     vector<int> loc0;
193     int context;
194 };
195
196
197
198 class BaseTest;
199 class TS;
200
201 class CV_EXPORTS BaseTest
202 {
203 public:
204     // constructor(s) and destructor
205     BaseTest();
206     virtual ~BaseTest();
207
208     // the main procedure of the test
209     virtual void run( int start_from );
210
211     // the wrapper for run that cares of exceptions
212     virtual void safe_run( int start_from=0 );
213
214     const string& get_name() const { return name; }
215
216     // returns true if and only if the different test cases do not depend on each other
217     // (so that test system could get right to a problematic test case)
218     virtual bool can_do_fast_forward();
219
220     // deallocates all the memory.
221     // called by init() (before initialization) and by the destructor
222     virtual void clear();
223
224 protected:
225     int test_case_count; // the total number of test cases
226
227     // read test params
228     virtual int read_params( CvFileStorage* fs );
229
230     // returns the number of tests or -1 if it is unknown a-priori
231     virtual int get_test_case_count();
232
233     // prepares data for the next test case. rng seed is updated by the function
234     virtual int prepare_test_case( int test_case_idx );
235
236     // checks if the test output is valid and accurate
237     virtual int validate_test_results( int test_case_idx );
238
239     // calls the tested function. the method is called from run_test_case()
240     virtual void run_func(); // runs tested func(s)
241
242     // updates progress bar
243     virtual int update_progress( int progress, int test_case_idx, int count, double dt );
244
245     // finds test parameter
246     const CvFileNode* find_param( CvFileStorage* fs, const char* param_name );
247
248     // name of the test (it is possible to locate a test by its name)
249     string name;
250
251     // pointer to the system that includes the test
252     TS* ts;
253 };
254
255
256 /*****************************************************************************************\
257 *                               Information about a failed test                           *
258 \*****************************************************************************************/
259
260 struct TestInfo
261 {
262     TestInfo();
263
264     // pointer to the test
265     BaseTest* test;
266
267     // failure code (CV_FAIL*)
268     int code;
269
270     // seed value right before the data for the failed test case is prepared.
271     uint64 rng_seed;
272
273     // seed value right before running the test
274     uint64 rng_seed0;
275
276     // index of test case, can be then passed to BaseTest::proceed_to_test_case()
277     int test_case_idx;
278 };
279
280 /*****************************************************************************************\
281 *                                 Base Class for test system                              *
282 \*****************************************************************************************/
283
284 // common parameters:
285 struct CV_EXPORTS TSParams
286 {
287     TSParams();
288
289     // RNG seed, passed to and updated by every test executed.
290     uint64 rng_seed;
291
292     // whether to use IPP, MKL etc. or not
293     bool use_optimized;
294
295     // extensivity of the tests, scale factor for test_case_count
296     double test_case_count_scale;
297 };
298
299
300 class CV_EXPORTS TS
301 {
302 public:
303     // constructor(s) and destructor
304     TS();
305     virtual ~TS();
306
307     enum
308     {
309         NUL=0,
310         SUMMARY_IDX=0,
311         SUMMARY=1 << SUMMARY_IDX,
312         LOG_IDX=1,
313         LOG=1 << LOG_IDX,
314         CSV_IDX=2,
315         CSV=1 << CSV_IDX,
316         CONSOLE_IDX=3,
317         CONSOLE=1 << CONSOLE_IDX,
318         MAX_IDX=4
319     };
320
321     static TS* ptr();
322
323     // initialize test system before running the first test
324     virtual void init( const string& modulename );
325
326     // low-level printing functions that are used by individual tests and by the system itself
327     virtual void printf( int streams, const char* fmt, ... );
328     virtual void vprintf( int streams, const char* fmt, va_list arglist );
329
330     // updates the context: current test, test case, rng state
331     virtual void update_context( BaseTest* test, int test_case_idx, bool update_ts_context );
332
333     const TestInfo* get_current_test_info() { return &current_test_info; }
334
335     // sets information about a failed test
336     virtual void set_failed_test_info( int fail_code );
337
338     virtual void set_gtest_status();
339
340     // test error codes
341     enum
342     {
343         // everything is Ok
344         OK=0,
345
346         // generic error: stub value to be used
347         // temporarily if the error's cause is unknown
348         FAIL_GENERIC=-1,
349
350         // the test is missing some essential data to proceed further
351         FAIL_MISSING_TEST_DATA=-2,
352
353         // the tested function raised an error via cxcore error handler
354         FAIL_ERROR_IN_CALLED_FUNC=-3,
355
356         // an exception has been raised;
357         // for memory and arithmetic exception
358         // there are two specialized codes (see below...)
359         FAIL_EXCEPTION=-4,
360
361         // a memory exception
362         // (access violation, access to missed page, stack overflow etc.)
363         FAIL_MEMORY_EXCEPTION=-5,
364
365         // arithmetic exception (overflow, division by zero etc.)
366         FAIL_ARITHM_EXCEPTION=-6,
367
368         // the tested function corrupted memory (no exception have been raised)
369         FAIL_MEMORY_CORRUPTION_BEGIN=-7,
370         FAIL_MEMORY_CORRUPTION_END=-8,
371
372         // the tested function (or test ifself) do not deallocate some memory
373         FAIL_MEMORY_LEAK=-9,
374
375         // the tested function returned invalid object, e.g. matrix, containing NaNs,
376         // structure with NULL or out-of-range fields (while it should not)
377         FAIL_INVALID_OUTPUT=-10,
378
379         // the tested function returned valid object, but it does not match to
380         // the original (or produced by the test) object
381         FAIL_MISMATCH=-11,
382
383         // the tested function returned valid object (a single number or numerical array),
384         // but it differs too much from the original (or produced by the test) object
385         FAIL_BAD_ACCURACY=-12,
386
387         // the tested function hung. Sometimes, can be determined by unexpectedly long
388         // processing time (in this case there should be possibility to interrupt such a function
389         FAIL_HANG=-13,
390
391         // unexpected responce on passing bad arguments to the tested function
392         // (the function crashed, proceed succesfully (while it should not), or returned
393         // error code that is different from what is expected)
394         FAIL_BAD_ARG_CHECK=-14,
395
396         // the test data (in whole or for the particular test case) is invalid
397         FAIL_INVALID_TEST_DATA=-15,
398
399         // the test has been skipped because it is not in the selected subset of the tests to run,
400         // because it has been run already within the same run with the same parameters, or because
401         // of some other reason and this is not considered as an error.
402         // Normally TS::run() (or overrided method in the derived class) takes care of what
403         // needs to be run, so this code should not occur.
404         SKIPPED=1
405     };
406
407     // get file storage
408     CvFileStorage* get_file_storage();
409
410     // get RNG to generate random input data for a test
411     RNG& get_rng() { return rng; }
412
413     // returns the current error code
414     int get_err_code() { return current_test_info.code; }
415
416     // returns the test extensivity scale
417     double get_test_case_count_scale() { return params.test_case_count_scale; }
418
419     const string& get_data_path() const { return data_path; }
420
421     // returns textual description of failure code
422     static string str_from_code( int code );
423
424 protected:
425
426     // these are allocated within a test to try keep them valid in case of stack corruption
427     RNG rng;
428
429     // information about the current test
430     TestInfo current_test_info;
431
432     // the path to data files used by tests
433     string data_path;
434
435     TSParams params;
436     std::string output_buf[MAX_IDX];
437 };
438
439
440 /*****************************************************************************************\
441 *            Subclass of BaseTest for testing functions that process dense arrays           *
442 \*****************************************************************************************/
443
444 class CV_EXPORTS ArrayTest : public BaseTest
445 {
446 public:
447     // constructor(s) and destructor
448     ArrayTest();
449     virtual ~ArrayTest();
450
451     virtual void clear();
452
453 protected:
454
455     virtual int read_params( CvFileStorage* fs );
456     virtual int prepare_test_case( int test_case_idx );
457     virtual int validate_test_results( int test_case_idx );
458
459     virtual void prepare_to_validation( int test_case_idx );
460     virtual void get_test_array_types_and_sizes( int test_case_idx, vector<vector<Size> >& sizes, vector<vector<int> >& types );
461     virtual void fill_array( int test_case_idx, int i, int j, Mat& arr );
462     virtual void get_minmax_bounds( int i, int j, int type, Scalar& low, Scalar& high );
463     virtual double get_success_error_level( int test_case_idx, int i, int j );
464
465     bool cvmat_allowed;
466     bool iplimage_allowed;
467     bool optional_mask;
468     bool element_wise_relative_error;
469
470     int min_log_array_size;
471     int max_log_array_size;
472
473     enum { INPUT, INPUT_OUTPUT, OUTPUT, REF_INPUT_OUTPUT, REF_OUTPUT, TEMP, MASK, MAX_ARR };
474
475     vector<vector<void*> > test_array;
476     vector<vector<Mat> > test_mat;
477     float buf[4];
478 };
479
480
481 class CV_EXPORTS BadArgTest : public BaseTest
482 {
483 public:
484     // constructor(s) and destructor
485     BadArgTest();
486     virtual ~BadArgTest();
487
488 protected:
489     virtual int run_test_case( int expected_code, const string& descr );
490     virtual void run_func(void) = 0;
491     int test_case_idx;
492     int progress;
493     double t, freq;
494
495     template<class F>
496     int run_test_case( int expected_code, const string& _descr, F f)
497     {
498         double new_t = (double)cv::getTickCount(), dt;
499         if( test_case_idx < 0 )
500         {
501             test_case_idx = 0;
502             progress = 0;
503             dt = 0;
504         }
505         else
506         {
507             dt = (new_t - t)/(freq*1000);
508             t = new_t;
509         }
510         progress = update_progress(progress, test_case_idx, 0, dt);
511
512         int errcount = 0;
513         bool thrown = false;
514         const char* descr = _descr.c_str() ? _descr.c_str() : "";
515
516         try
517         {
518             f();
519         }
520         catch(const cv::Exception& e)
521         {
522             thrown = true;
523             if( e.code != expected_code )
524             {
525                 ts->printf(TS::LOG, "%s (test case #%d): the error code %d is different from the expected %d\n",
526                     descr, test_case_idx, e.code, expected_code);
527                 errcount = 1;
528             }
529         }
530         catch(...)
531         {
532             thrown = true;
533             ts->printf(TS::LOG, "%s  (test case #%d): unknown exception was thrown (the function has likely crashed)\n",
534                        descr, test_case_idx);
535             errcount = 1;
536         }
537         if(!thrown)
538         {
539             ts->printf(TS::LOG, "%s  (test case #%d): no expected exception was thrown\n",
540                        descr, test_case_idx);
541             errcount = 1;
542         }
543         test_case_idx++;
544
545         return errcount;
546     }
547 };
548
549 struct CV_EXPORTS DefaultRngAuto
550 {
551     const uint64 old_state;
552
553     DefaultRngAuto() : old_state(cv::theRNG().state) { cv::theRNG().state = (uint64)-1; }
554     ~DefaultRngAuto() { cv::theRNG().state = old_state; }
555
556     DefaultRngAuto& operator=(const DefaultRngAuto&);
557 };
558
559 }
560
561 // fills c with zeros
562 CV_EXPORTS void cvTsZero( CvMat* c, const CvMat* mask=0 );
563
564 // copies a to b (whole matrix or only the selected region)
565 CV_EXPORTS void cvTsCopy( const CvMat* a, CvMat* b, const CvMat* mask=0 );
566
567 // converts one array to another
568 CV_EXPORTS void  cvTsConvert( const CvMat* src, CvMat* dst );
569
570 CV_EXPORTS void cvTsGEMM( const CvMat* a, const CvMat* b, double alpha,
571                          const CvMat* c, double beta, CvMat* d, int flags );
572
573 #define CV_TEST_MAIN(resourcesubdir) \
574 int main(int argc, char **argv) \
575 { \
576     cvtest::TS::ptr()->init(resourcesubdir); \
577     ::testing::InitGoogleTest(&argc, argv); \
578     return RUN_ALL_TESTS(); \
579 }
580
581 #endif
582
583 #include "ts_perf.hpp"