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