33f90a9e7356388dfc7eff2daa6b6bc3732cb8e8
[opencv] / tests / cv / src / atemplmatch.cpp
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 //                        Intel License Agreement
11 //                For Open Source Computer Vision Library
12 //
13 // Copyright (C) 2000, Intel Corporation, all rights reserved.
14 // Third party copyrights are property of their respective owners.
15 //
16 // Redistribution and use in source and binary forms, with or without modification,
17 // are permitted provided that the following conditions are met:
18 //
19 //   * Redistribution's of source code must retain the above copyright notice,
20 //     this list of conditions and the following disclaimer.
21 //
22 //   * Redistribution's in binary form must reproduce the above copyright notice,
23 //     this list of conditions and the following disclaimer in the documentation
24 //     and/or other materials provided with the distribution.
25 //
26 //   * The name of Intel Corporation may not be used to endorse or promote products
27 //     derived from this software without specific prior written permission.
28 //
29 // This software is provided by the copyright holders and contributors "as is" and
30 // any express or implied warranties, including, but not limited to, the implied
31 // warranties of merchantability and fitness for a particular purpose are disclaimed.
32 // In no event shall the Intel Corporation or contributors be liable for any direct,
33 // indirect, incidental, special, exemplary, or consequential damages
34 // (including, but not limited to, procurement of substitute goods or services;
35 // loss of use, data, or profits; or business interruption) however caused
36 // and on any theory of liability, whether in contract, strict liability,
37 // or tort (including negligence or otherwise) arising in any way out of
38 // the use of this software, even if advised of the possibility of such damage.
39 //
40 //M*/
41
42 #include "cvtest.h"
43
44 static const char* templmatch_param_names[] = { "template_size", "method", "size", "channels", "depth", 0 };
45 static const int templmatch_depths[] = { CV_8U, CV_32F, -1 };
46 static const int templmatch_channels[] = { 1, 3, -1 };
47
48 static const CvSize templmatch_sizes[] = {{320, 240}, {1024,768}, {-1,-1}};
49 static const CvSize templmatch_whole_sizes[] = {{320,240}, {1024,768}, {-1,-1}};
50 static const CvSize templmatch_template_sizes[] = {{15,15}, {60,60}, {-1,-1}};
51 static const char* templmatch_methods[] = { "sqdiff", "sqdiff_norm", "ccorr", "ccorr_normed", "ccoeff", "ccoeff_normed", 0 };
52
53 class CV_TemplMatchTest : public CvArrTest
54 {
55 public:
56     CV_TemplMatchTest();
57
58 protected:
59     int read_params( CvFileStorage* fs );
60     void get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types );
61     void get_minmax_bounds( int i, int j, int type, CvScalar* low, CvScalar* high );
62     double get_success_error_level( int test_case_idx, int i, int j );
63     void run_func();
64     void prepare_to_validation( int );
65
66     int write_default_params(CvFileStorage* fs);
67     void get_timing_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types,
68                                                 CvSize** whole_sizes, bool *are_images );
69     void print_timing_params( int test_case_idx, char* ptr, int params_left );
70
71     int max_template_size;
72     int method;
73 };
74
75
76 CV_TemplMatchTest::CV_TemplMatchTest()
77     : CvArrTest( "match-template", "cvMatchTemplate", "" )
78 {
79     test_array[INPUT].push(NULL);
80     test_array[INPUT].push(NULL);
81     test_array[OUTPUT].push(NULL);
82     test_array[REF_OUTPUT].push(NULL);
83     element_wise_relative_error = false;
84     max_template_size = 100;
85     method = 0;
86
87     size_list = templmatch_sizes;
88     whole_size_list = templmatch_whole_sizes;
89     cn_list = templmatch_channels;
90     depth_list = templmatch_depths;
91
92     default_timing_param_names = templmatch_param_names;
93 }
94
95
96 int CV_TemplMatchTest::read_params( CvFileStorage* fs )
97 {
98     int code = CvArrTest::read_params( fs );
99     if( code < 0 )
100         return code;
101
102     if( ts->get_testing_mode() == CvTS::CORRECTNESS_CHECK_MODE )
103     {
104         max_template_size = cvReadInt( find_param( fs, "max_template_size" ), max_template_size );
105         max_template_size = cvTsClipInt( max_template_size, 1, 100 );
106     }
107
108     return code;
109 }
110
111
112 int CV_TemplMatchTest::write_default_params( CvFileStorage* fs )
113 {
114     int code = CvArrTest::write_default_params( fs );
115     if( code < 0 )
116         return code;
117     
118     if( ts->get_testing_mode() == CvTS::CORRECTNESS_CHECK_MODE )
119     {
120         write_param( fs, "max_template_size", max_template_size );
121     }
122     else
123     {
124         int i;
125         start_write_param( fs );        
126         
127         cvStartWriteStruct( fs, "template_size", CV_NODE_SEQ+CV_NODE_FLOW );
128         for( i = 0; templmatch_template_sizes[i].width >= 0; i++ )
129         {
130             cvStartWriteStruct( fs, 0, CV_NODE_SEQ+CV_NODE_FLOW );
131             cvWriteInt( fs, 0, templmatch_template_sizes[i].width );
132             cvWriteInt( fs, 0, templmatch_template_sizes[i].height );
133             cvEndWriteStruct(fs);
134         }
135         cvEndWriteStruct(fs);
136
137         write_string_list( fs, "method", templmatch_methods );
138     }
139
140     return code;
141 }
142
143
144 void CV_TemplMatchTest::get_minmax_bounds( int i, int j, int type, CvScalar* low, CvScalar* high )
145 {
146     CvArrTest::get_minmax_bounds( i, j, type, low, high );
147     int depth = CV_MAT_DEPTH(type);
148     if( depth == CV_32F )
149     {
150         *low = cvScalarAll(-10.);
151         *high = cvScalarAll(10.);
152     }
153 }
154
155
156 void CV_TemplMatchTest::get_test_array_types_and_sizes( int test_case_idx,
157                                                 CvSize** sizes, int** types )
158 {
159     CvRNG* rng = ts->get_rng();
160     int depth = cvTsRandInt(rng) % 2, cn = cvTsRandInt(rng) & 1 ? 3 : 1;
161     CvArrTest::get_test_array_types_and_sizes( test_case_idx, sizes, types );
162     depth = depth == 0 ? CV_8U : CV_32F;
163
164     types[INPUT][0] = types[INPUT][1] = CV_MAKETYPE(depth,cn);
165     types[OUTPUT][0] = types[REF_OUTPUT][0] = CV_32FC1;
166
167     sizes[INPUT][1].width = cvTsRandInt(rng)%MIN(sizes[INPUT][1].width,max_template_size) + 1;
168     sizes[INPUT][1].height = cvTsRandInt(rng)%MIN(sizes[INPUT][1].height,max_template_size) + 1;
169     sizes[OUTPUT][0].width = sizes[INPUT][0].width - sizes[INPUT][1].width + 1;
170     sizes[OUTPUT][0].height = sizes[INPUT][0].height - sizes[INPUT][1].height + 1;
171     sizes[REF_OUTPUT][0] = sizes[OUTPUT][0];
172
173     method = cvTsRandInt(rng)%6;
174 }
175
176
177 void CV_TemplMatchTest::get_timing_test_array_types_and_sizes( int test_case_idx,
178                 CvSize** sizes, int** types, CvSize** whole_sizes, bool *are_images )
179 {
180     CvArrTest::get_timing_test_array_types_and_sizes( test_case_idx, sizes, types,
181                                                       whole_sizes, are_images );
182     const char* method_str = cvReadString( find_timing_param( "method" ), "ccorr" );
183     const CvFileNode* node = find_timing_param( "template_size" );
184     CvSize templ_size, result_size;
185
186     assert( node && CV_NODE_IS_SEQ( node->tag ));
187
188     method = strncmp( method_str, "sqdiff", 6 ) == 0 ? CV_TM_SQDIFF :
189              strncmp( method_str, "ccorr", 5 ) == 0 ? CV_TM_CCORR : CV_TM_CCOEFF;
190     method += strstr( method_str, "_normed" ) != 0;
191
192     cvReadRawData( ts->get_file_storage(), node, &templ_size, "2i" );
193
194     sizes[INPUT][1] = whole_sizes[INPUT][1] = templ_size;
195     result_size.width = sizes[INPUT][0].width - templ_size.width + 1;
196     result_size.height = sizes[INPUT][0].height - templ_size.height + 1;
197     assert( result_size.width > 0 && result_size.height > 0 );
198     sizes[OUTPUT][0] = whole_sizes[OUTPUT][0] = result_size;
199
200     types[OUTPUT][0] = CV_32FC1;
201 }
202
203
204 void CV_TemplMatchTest::print_timing_params( int test_case_idx, char* ptr, int params_left )
205 {
206     sprintf( ptr, "%s,", cvReadString( find_timing_param( "method" ), "ccorr" ) );
207     ptr += strlen(ptr);
208     sprintf( ptr, "templ_size=%dx%d,", test_mat[INPUT][1].width, test_mat[INPUT][1].height );
209     ptr += strlen(ptr);
210     params_left -= 2;
211
212     CvArrTest::print_timing_params( test_case_idx, ptr, params_left );
213 }
214
215
216 double CV_TemplMatchTest::get_success_error_level( int /*test_case_idx*/, int /*i*/, int /*j*/ )
217 {
218     if( CV_MAT_DEPTH(test_mat[INPUT][1].type) == CV_8U ||
219         method >= CV_TM_CCOEFF && test_mat[INPUT][1].cols*test_mat[INPUT][1].rows <= 2 )
220         return 1e-2;
221     else
222         return 1e-3;
223 }
224
225
226 void CV_TemplMatchTest::run_func()
227 {
228     cvMatchTemplate( test_array[INPUT][0], test_array[INPUT][1], test_array[OUTPUT][0], method );
229 }
230
231
232 static void cvTsMatchTemplate( const CvMat* img, const CvMat* templ, CvMat* result, int method )
233 {
234     int i, j, k, l;
235     int depth = CV_MAT_DEPTH(img->type), cn = CV_MAT_CN(img->type);
236     int width_n = templ->cols*cn, height = templ->rows;
237     int a_step = img->step / CV_ELEM_SIZE(img->type & CV_MAT_DEPTH_MASK);
238     int b_step = templ->step / CV_ELEM_SIZE(templ->type & CV_MAT_DEPTH_MASK);
239     CvScalar b_mean, b_sdv;
240     double b_denom = 1., b_sum2 = 0;
241     int area = templ->rows*templ->cols;
242
243     cvTsMeanStdDevNonZero( templ, 0, &b_mean, &b_sdv, 0 );
244
245     for( i = 0; i < cn; i++ )
246         b_sum2 += (b_sdv.val[i]*b_sdv.val[i] + b_mean.val[i]*b_mean.val[i])*area;
247
248     if( CV_SQR(b_sdv.val[0]) + CV_SQR(b_sdv.val[1]) +
249         CV_SQR(b_sdv.val[2]) + CV_SQR(b_sdv.val[3]) < DBL_EPSILON &&
250         method == CV_TM_CCOEFF_NORMED )
251     {
252         cvSet( result, cvScalarAll(1.) );
253         return;
254     }
255     
256     if( method & 1 )
257     {
258         b_denom = 0;
259         if( method != CV_TM_CCOEFF_NORMED )
260         {
261             b_denom = b_sum2;
262         }
263         else
264         {
265             for( i = 0; i < cn; i++ )
266                 b_denom += b_sdv.val[i]*b_sdv.val[i]*area;
267         }
268         b_denom = sqrt(b_denom);
269         if( b_denom == 0 )
270             b_denom = 1.;
271     }
272
273     assert( CV_TM_SQDIFF <= method && method <= CV_TM_CCOEFF_NORMED );
274
275     for( i = 0; i < result->rows; i++ )
276     {
277         for( j = 0; j < result->cols; j++ )
278         {
279             CvScalar a_sum = {{ 0, 0, 0, 0 }}, a_sum2 = {{ 0, 0, 0, 0 }};
280             CvScalar ccorr = {{ 0, 0, 0, 0 }};
281             double value = 0.;
282             
283             if( depth == CV_8U )
284             {
285                 const uchar* a = img->data.ptr + i*img->step + j*cn;
286                 const uchar* b = templ->data.ptr;
287                 
288                 if( cn == 1 || method < CV_TM_CCOEFF )
289                 {
290                     for( k = 0; k < height; k++, a += a_step, b += b_step )
291                         for( l = 0; l < width_n; l++ )
292                         {
293                             ccorr.val[0] += a[l]*b[l];
294                             a_sum.val[0] += a[l];
295                             a_sum2.val[0] += a[l]*a[l];
296                         }
297                 }
298                 else
299                 {
300                     for( k = 0; k < height; k++, a += a_step, b += b_step )
301                         for( l = 0; l < width_n; l += 3 )
302                         {
303                             ccorr.val[0] += a[l]*b[l];
304                             ccorr.val[1] += a[l+1]*b[l+1];
305                             ccorr.val[2] += a[l+2]*b[l+2];
306                             a_sum.val[0] += a[l];
307                             a_sum.val[1] += a[l+1];
308                             a_sum.val[2] += a[l+2];
309                             a_sum2.val[0] += a[l]*a[l];
310                             a_sum2.val[1] += a[l+1]*a[l+1];
311                             a_sum2.val[2] += a[l+2]*a[l+2];
312                         }
313                 }
314             }
315             else
316             {
317                 const float* a = (const float*)(img->data.ptr + i*img->step) + j*cn;
318                 const float* b = (const float*)templ->data.ptr;
319                 
320                 if( cn == 1 || method < CV_TM_CCOEFF )
321                 {
322                     for( k = 0; k < height; k++, a += a_step, b += b_step )
323                         for( l = 0; l < width_n; l++ )
324                         {
325                             ccorr.val[0] += a[l]*b[l];
326                             a_sum.val[0] += a[l];
327                             a_sum2.val[0] += a[l]*a[l];
328                         }
329                 }
330                 else
331                 {
332                     for( k = 0; k < height; k++, a += a_step, b += b_step )
333                         for( l = 0; l < width_n; l += 3 )
334                         {
335                             ccorr.val[0] += a[l]*b[l];
336                             ccorr.val[1] += a[l+1]*b[l+1];
337                             ccorr.val[2] += a[l+2]*b[l+2];
338                             a_sum.val[0] += a[l];
339                             a_sum.val[1] += a[l+1];
340                             a_sum.val[2] += a[l+2];
341                             a_sum2.val[0] += a[l]*a[l];
342                             a_sum2.val[1] += a[l+1]*a[l+1];
343                             a_sum2.val[2] += a[l+2]*a[l+2];
344                         }
345                 }
346             }
347
348             switch( method )
349             {
350             case CV_TM_CCORR:
351             case CV_TM_CCORR_NORMED:
352                 value = ccorr.val[0];
353                 break;
354             case CV_TM_SQDIFF:
355             case CV_TM_SQDIFF_NORMED:
356                 value = (a_sum2.val[0] + b_sum2 - 2*ccorr.val[0]);
357                 break;
358             default:
359                 value = (ccorr.val[0] - a_sum.val[0]*b_mean.val[0]+
360                          ccorr.val[1] - a_sum.val[1]*b_mean.val[1]+
361                          ccorr.val[2] - a_sum.val[2]*b_mean.val[2]);
362             }
363
364             if( method & 1 )
365             {
366                 double denom;
367                 
368                 // calc denominator
369                 if( method != CV_TM_CCOEFF_NORMED )
370                 {
371                     denom = a_sum2.val[0] + a_sum2.val[1] + a_sum2.val[2];
372                 }
373                 else
374                 {
375                     denom = a_sum2.val[0] - (a_sum.val[0]*a_sum.val[0])/area;
376                     denom += a_sum2.val[1] - (a_sum.val[1]*a_sum.val[1])/area;
377                     denom += a_sum2.val[2] - (a_sum.val[2]*a_sum.val[2])/area;
378                 }
379                 denom = sqrt(MAX(denom,0))*b_denom;
380                 if( denom > DBL_EPSILON )
381                 {
382                     value /= denom;
383                     if( fabs(value) > 1 )
384                         value = value < 0 ? -1. : 1.;
385                 }
386                 else
387                     value = method != CV_TM_SQDIFF_NORMED || value < DBL_EPSILON ? 0 : 1;
388             }
389             
390             ((float*)(result->data.ptr + result->step*i))[j] = (float)value;
391         }
392     }
393 }
394
395
396 void CV_TemplMatchTest::prepare_to_validation( int /*test_case_idx*/ )
397 {
398     cvTsMatchTemplate( &test_mat[INPUT][0], &test_mat[INPUT][1],
399                        &test_mat[REF_OUTPUT][0], method );
400
401     //if( ts->get_current_test_info()->test_case_idx == 0 )
402     /*{
403         CvFileStorage* fs = cvOpenFileStorage( "_match_template.yml", 0, CV_STORAGE_WRITE );
404         cvWrite( fs, "image", &test_mat[INPUT][0] );
405         cvWrite( fs, "template", &test_mat[INPUT][1] );
406         cvWrite( fs, "ref", &test_mat[REF_OUTPUT][0] );
407         cvWrite( fs, "opencv", &test_mat[OUTPUT][0] );
408         cvWriteInt( fs, "method", method );
409         cvReleaseFileStorage( &fs );
410     }*/
411
412     if( method >= CV_TM_CCOEFF )
413     {
414         // avoid numerical stability problems in singular cases (when the results are near to 0)
415         const double delta = 10.;
416         cvTsAdd( &test_mat[REF_OUTPUT][0], cvScalar(1.), 0, cvScalar(0.),
417                  cvScalar(delta), &test_mat[REF_OUTPUT][0], 0 );
418         cvTsAdd( &test_mat[OUTPUT][0], cvScalar(1.), 0, cvScalar(0.),
419                  cvScalar(delta), &test_mat[OUTPUT][0], 0 );
420     }
421 }
422
423
424 CV_TemplMatchTest templ_match;