some formal changes (generally adding constness)
[profile/ivi/opencv.git] / modules / imgproc / test / test_imgwarp_strict.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 "test_precomp.hpp"
43
44 #include <cmath>
45 #include <vector>
46 #include <iostream>
47
48 using namespace cv;
49
50 namespace
51 {
52     void __wrap_printf_func(const char* fmt, ...)
53     {
54         va_list args;
55         va_start(args, fmt);
56         char buffer[256];
57         vsprintf (buffer, fmt, args);
58         cvtest::TS::ptr()->printf(cvtest::TS::SUMMARY, buffer);
59         va_end(args);
60     }
61
62     #define PRINT_TO_LOG __wrap_printf_func
63 }
64
65 #define SHOW_IMAGE
66 #undef SHOW_IMAGE
67
68 ////////////////////////////////////////////////////////////////////////////////////////////////////////
69 // ImageWarpBaseTest
70 ////////////////////////////////////////////////////////////////////////////////////////////////////////
71
72 class CV_ImageWarpBaseTest :
73     public cvtest::BaseTest
74 {
75 public:
76     enum { cell_size = 10 };
77
78     CV_ImageWarpBaseTest();
79     virtual ~CV_ImageWarpBaseTest();
80
81     virtual void run(int);
82 protected:
83     virtual void generate_test_data();
84
85     virtual void run_func() = 0;
86     virtual void run_reference_func() = 0;
87     virtual void validate_results() const;
88     virtual void prepare_test_data_for_reference_func();
89
90     Size randSize(RNG& rng) const;
91
92     const char* interpolation_to_string(int inter_type) const;
93
94     int interpolation;
95     Mat src;
96     Mat dst;
97     Mat reference_dst;
98 };
99
100 CV_ImageWarpBaseTest::CV_ImageWarpBaseTest() :
101     BaseTest(), interpolation(-1),
102     src(), dst(), reference_dst()
103 {
104     test_case_count = 40;
105     ts->set_failed_test_info(cvtest::TS::OK);
106 }
107
108 CV_ImageWarpBaseTest::~CV_ImageWarpBaseTest()
109 {
110 }
111
112 const char* CV_ImageWarpBaseTest::interpolation_to_string(int inter) const
113 {
114     if (inter == INTER_NEAREST)
115         return "INTER_NEAREST";
116     if (inter == INTER_LINEAR)
117         return "INTER_LINEAR";
118     if (inter == INTER_AREA)
119         return "INTER_AREA";
120     if (inter == INTER_CUBIC)
121         return "INTER_CUBIC";
122     if (inter == INTER_LANCZOS4)
123         return "INTER_LANCZOS4";
124     if (inter == INTER_LANCZOS4 + 1)
125         return "INTER_AREA_FAST";
126     return "Unsupported/Unkown interpolation type";
127 }
128
129 Size CV_ImageWarpBaseTest::randSize(RNG& rng) const
130 {
131     Size size;
132     size.width = static_cast<int>(std::exp(rng.uniform(1.0f, 7.0f)));
133     size.height = static_cast<int>(std::exp(rng.uniform(1.0f, 7.0f)));
134
135     return size;
136 }
137
138 void CV_ImageWarpBaseTest::generate_test_data()
139 {
140     RNG& rng = ts->get_rng();
141
142     // generating the src matrix structure
143     Size ssize = randSize(rng), dsize;
144
145     int depth = rng.uniform(0, CV_64F);
146     while (depth == CV_8S || depth == CV_32S)
147         depth = rng.uniform(0, CV_64F);
148
149     int cn = rng.uniform(1, 4);
150     while (cn == 2)
151         cn = rng.uniform(1, 4);
152
153     src.create(ssize, CV_MAKE_TYPE(depth, cn));
154
155     // generating the src matrix
156     int x, y;
157     if (cvtest::randInt(rng) % 2)
158     {
159         for (y = 0; y < ssize.height; y += cell_size)
160             for (x = 0; x < ssize.width; x += cell_size)
161                 rectangle(src, Point(x, y), Point(x + std::min<int>(cell_size, ssize.width - x), y +
162                         std::min<int>(cell_size, ssize.height - y)), Scalar::all((x + y) % 2 ? 255: 0), CV_FILLED);
163     }
164     else
165     {
166         src = Scalar::all(255);
167         for (y = cell_size; y < src.rows; y += cell_size)
168             line(src, Point2i(0, y), Point2i(src.cols, y), Scalar::all(0), 1);
169         for (x = cell_size; x < src.cols; x += cell_size)
170             line(src, Point2i(x, 0), Point2i(x, src.rows), Scalar::all(0), 1);
171     }
172
173     // generating an interpolation type
174     interpolation = rng.uniform(0, CV_INTER_LANCZOS4 + 1);
175
176     // generating the dst matrix structure
177     double scale_x, scale_y;
178     if (interpolation == INTER_AREA)
179     {
180         bool area_fast = rng.uniform(0., 1.) > 0.5;
181         if (area_fast)
182         {
183             scale_x = rng.uniform(2, 5);
184             scale_y = rng.uniform(2, 5);
185         }
186         else
187         {
188             scale_x = rng.uniform(1.0, 3.0);
189             scale_y = rng.uniform(1.0, 3.0);
190         }
191     }
192     else
193     {
194         scale_x = rng.uniform(0.4, 4.0);
195         scale_y = rng.uniform(0.4, 4.0);
196     }
197     CV_Assert(scale_x > 0.0f && scale_y > 0.0f);
198
199     dsize.width = saturate_cast<int>((ssize.width + scale_x - 1) / scale_x);
200     dsize.height = saturate_cast<int>((ssize.height + scale_y - 1) / scale_y);
201
202     dst = Mat::zeros(dsize, src.type());
203     reference_dst = Mat::zeros(dst.size(), CV_MAKE_TYPE(CV_32F, dst.channels()));
204
205     scale_x = src.cols / static_cast<double>(dst.cols);
206     scale_y = src.rows / static_cast<double>(dst.rows);
207
208     if (interpolation == INTER_AREA && (scale_x < 1.0 || scale_y < 1.0))
209         interpolation = INTER_LINEAR;
210 }
211
212 void CV_ImageWarpBaseTest::run(int)
213 {
214     for (int i = 0; i < test_case_count; ++i)
215     {
216         generate_test_data();
217         run_func();
218         run_reference_func();
219         if (ts->get_err_code() < 0)
220             break;
221         validate_results();
222         if (ts->get_err_code() < 0)
223             break;
224         ts->update_context(this, i, true);
225     }
226     ts->set_gtest_status();
227 }
228
229 void CV_ImageWarpBaseTest::validate_results() const
230 {
231     Mat _dst;
232     dst.convertTo(_dst, reference_dst.depth());
233
234     Size dsize = dst.size(), ssize = src.size();
235     int cn = _dst.channels();
236     dsize.width *= cn;
237     float t = 1.0f;
238     if (interpolation == INTER_CUBIC)
239         t = 1.0f;
240     else if (interpolation == INTER_LANCZOS4)
241         t = 1.0f;
242     else if (interpolation == INTER_NEAREST)
243         t = 1.0f;
244     else if (interpolation == INTER_AREA)
245         t = 2.0f;
246
247     for (int dy = 0; dy < dsize.height; ++dy)
248     {
249         const float* rD = reference_dst.ptr<float>(dy);
250         const float* D = _dst.ptr<float>(dy);
251
252         for (int dx = 0; dx < dsize.width; ++dx)
253             if (fabs(rD[dx] - D[dx]) > t &&
254 //                fabs(rD[dx] - D[dx]) < 250.0f &&
255                 rD[dx] <= 255.0f && D[dx] <= 255.0f && rD[dx] >= 0.0f && D[dx] >= 0.0f)
256             {
257                 PRINT_TO_LOG("\nNorm of the difference: %lf\n", cvtest::norm(reference_dst, _dst, NORM_INF));
258                 PRINT_TO_LOG("Error in (dx, dy): (%d, %d)\n", dx / cn + 1, dy + 1);
259                 PRINT_TO_LOG("Tuple (rD, D): (%f, %f)\n", rD[dx], D[dx]);
260                 PRINT_TO_LOG("Dsize: (%d, %d)\n", dsize.width / cn, dsize.height);
261                 PRINT_TO_LOG("Ssize: (%d, %d)\n", src.cols, src.rows);
262
263                 double scale_x = static_cast<double>(ssize.width) / dsize.width;
264                 double scale_y = static_cast<double>(ssize.height) / dsize.height;
265                 bool area_fast = interpolation == INTER_AREA &&
266                     fabs(scale_x - cvRound(scale_x)) < FLT_EPSILON &&
267                     fabs(scale_y - cvRound(scale_y)) < FLT_EPSILON;
268                 if (area_fast)
269                 {
270                     scale_y = cvRound(scale_y);
271                     scale_x = cvRound(scale_x);
272                 }
273
274                 PRINT_TO_LOG("Interpolation: %s\n", interpolation_to_string(area_fast ? INTER_LANCZOS4 + 1 : interpolation));
275                 PRINT_TO_LOG("Scale (x, y): (%lf, %lf)\n", scale_x, scale_y);
276                 PRINT_TO_LOG("Elemsize: %d\n", src.elemSize1());
277                 PRINT_TO_LOG("Channels: %d\n", cn);
278
279 #ifdef SHOW_IMAGE
280                 const std::string w1("OpenCV impl (run func)"), w2("Reference func"), w3("Src image"), w4("Diff");
281                 namedWindow(w1, CV_WINDOW_KEEPRATIO);
282                 namedWindow(w2, CV_WINDOW_KEEPRATIO);
283                 namedWindow(w3, CV_WINDOW_KEEPRATIO);
284                 namedWindow(w4, CV_WINDOW_KEEPRATIO);
285
286                 Mat diff;
287                 absdiff(reference_dst, _dst, diff);
288
289                 imshow(w1, dst);
290                 imshow(w2, reference_dst);
291                 imshow(w3, src);
292                 imshow(w4, diff);
293
294                 waitKey();
295 #endif
296
297                 const int radius = 3;
298                 int rmin = MAX(dy - radius, 0), rmax = MIN(dy + radius, dsize.height);
299                 int cmin = MAX(dx / cn - radius, 0), cmax = MIN(dx / cn + radius, dsize.width);
300
301                 std::cout << "opencv result:\n" << dst(Range(rmin, rmax), Range(cmin, cmax)) << std::endl;
302                 std::cout << "reference result:\n" << reference_dst(Range(rmin, rmax), Range(cmin, cmax)) << std::endl;
303
304                 ts->set_failed_test_info(cvtest::TS::FAIL_BAD_ACCURACY);
305                 return;
306             }
307     }
308 }
309
310 void CV_ImageWarpBaseTest::prepare_test_data_for_reference_func()
311 {
312     if (src.depth() != CV_32F)
313     {
314         Mat tmp;
315         src.convertTo(tmp, CV_32F);
316         src = tmp;
317     }
318 }
319
320 ////////////////////////////////////////////////////////////////////////////////////////////////////////
321 // Resize
322 ////////////////////////////////////////////////////////////////////////////////////////////////////////
323
324 class CV_Resize_Test :
325     public CV_ImageWarpBaseTest
326 {
327 public:
328     CV_Resize_Test();
329     virtual ~CV_Resize_Test();
330
331 protected:
332     virtual void generate_test_data();
333
334     virtual void run_func();
335     virtual void run_reference_func();
336
337 private:
338     double scale_x;
339     double scale_y;
340     bool area_fast;
341
342     void resize_generic();
343     void resize_area();
344     double getWeight(double a, double b, int x);
345
346     typedef std::vector<std::pair<int, double> > dim;
347     void generate_buffer(double scale, dim& _dim);
348     void resize_1d(const Mat& _src, Mat& _dst, int dy, const dim& _dim);
349 };
350
351 CV_Resize_Test::CV_Resize_Test() :
352     CV_ImageWarpBaseTest(), scale_x(),
353     scale_y(), area_fast(false)
354 {
355 }
356
357 CV_Resize_Test::~CV_Resize_Test()
358 {
359 }
360
361 namespace
362 {
363     void interpolateLinear(float x, float* coeffs)
364     {
365         coeffs[0] = 1.f - x;
366         coeffs[1] = x;
367     }
368
369     void interpolateCubic(float x, float* coeffs)
370     {
371         const float A = -0.75f;
372
373         coeffs[0] = ((A*(x + 1) - 5*A)*(x + 1) + 8*A)*(x + 1) - 4*A;
374         coeffs[1] = ((A + 2)*x - (A + 3))*x*x + 1;
375         coeffs[2] = ((A + 2)*(1 - x) - (A + 3))*(1 - x)*(1 - x) + 1;
376         coeffs[3] = 1.f - coeffs[0] - coeffs[1] - coeffs[2];
377     }
378
379     void interpolateLanczos4(float x, float* coeffs)
380     {
381         static const double s45 = 0.70710678118654752440084436210485;
382         static const double cs[][2]=
383         {{1, 0}, {-s45, -s45}, {0, 1}, {s45, -s45}, {-1, 0}, {s45, s45}, {0, -1}, {-s45, s45}};
384
385         if( x < FLT_EPSILON )
386         {
387             for( int i = 0; i < 8; i++ )
388                 coeffs[i] = 0;
389             coeffs[3] = 1;
390             return;
391         }
392
393         float sum = 0;
394         double y0=-(x+3)*CV_PI*0.25, s0 = sin(y0), c0=cos(y0);
395         for(int i = 0; i < 8; i++ )
396         {
397             double y = -(x+3-i)*CV_PI*0.25;
398             coeffs[i] = (float)((cs[i][0]*s0 + cs[i][1]*c0)/(y*y));
399             sum += coeffs[i];
400         }
401
402         sum = 1.f/sum;
403         for(int i = 0; i < 8; i++ )
404             coeffs[i] *= sum;
405     }
406
407     typedef void (*interpolate_method)(float x, float* coeffs);
408     interpolate_method inter_array[] = { &interpolateLinear, &interpolateCubic, &interpolateLanczos4 };
409 }
410
411 void CV_Resize_Test::generate_test_data()
412 {
413     CV_ImageWarpBaseTest::generate_test_data();
414
415     scale_x = src.cols / static_cast<double>(dst.cols);
416     scale_y = src.rows / static_cast<double>(dst.rows);
417
418     area_fast = interpolation == INTER_AREA &&
419         fabs(scale_x - cvRound(scale_x)) < FLT_EPSILON &&
420         fabs(scale_y - cvRound(scale_y)) < FLT_EPSILON;
421     if (area_fast)
422     {
423         scale_x = cvRound(scale_x);
424         scale_y = cvRound(scale_y);
425     }
426 }
427
428 void CV_Resize_Test::run_func()
429 {
430     cv::resize(src, dst, dst.size(), 0, 0, interpolation);
431 }
432
433 void CV_Resize_Test::run_reference_func()
434 {
435     CV_ImageWarpBaseTest::prepare_test_data_for_reference_func();
436
437     if (interpolation == INTER_AREA)
438         resize_area();
439     else
440         resize_generic();
441 }
442
443 double CV_Resize_Test::getWeight(double a, double b, int x)
444 {
445     double w = std::min(static_cast<double>(x + 1), b) - std::max(static_cast<double>(x), a);
446     CV_Assert(w >= 0);
447     return w;
448 }
449
450 void CV_Resize_Test::resize_area()
451 {
452     Size ssize = src.size(), dsize = reference_dst.size();
453     CV_Assert(ssize.area() > 0 && dsize.area() > 0);
454     int cn = src.channels();
455
456     CV_Assert(scale_x >= 1.0 && scale_y >= 1.0);
457
458     double fsy0 = 0, fsy1 = scale_y;
459     for (int dy = 0; dy < dsize.height; ++dy)
460     {
461         float* yD = reference_dst.ptr<float>(dy);
462         int isy0 = cvFloor(fsy0), isy1 = std::min(cvFloor(fsy1), ssize.height - 1);
463         CV_Assert(isy1 <= ssize.height && isy0 < ssize.height);
464
465         double fsx0 = 0, fsx1 = scale_x;
466
467         for (int dx = 0; dx < dsize.width; ++dx)
468         {
469             float* xyD = yD + cn * dx;
470             int isx0 = cvFloor(fsx0), isx1 = std::min(ssize.width - 1, cvFloor(fsx1));
471
472             CV_Assert(isx1 <= ssize.width);
473             CV_Assert(isx0 < ssize.width);
474
475             // for each pixel of dst
476             for (int r = 0; r < cn; ++r)
477             {
478                 xyD[r] = 0.0f;
479                 double area = 0.0;
480                 for (int sy = isy0; sy <= isy1; ++sy)
481                 {
482                     const float* yS = src.ptr<float>(sy);
483                     for (int sx = isx0; sx <= isx1; ++sx)
484                     {
485                         double wy = getWeight(fsy0, fsy1, sy);
486                         double wx = getWeight(fsx0, fsx1, sx);
487                         double w = wx * wy;
488                         xyD[r] += static_cast<float>(yS[sx * cn + r] * w);
489                         area += w;
490                     }
491                 }
492
493                 CV_Assert(area != 0);
494                 // norming pixel
495                 xyD[r] = static_cast<float>(xyD[r] / area);
496             }
497             fsx1 = std::min((fsx0 = fsx1) + scale_x, static_cast<double>(ssize.width));
498         }
499         fsy1 = std::min((fsy0 = fsy1) + scale_y, static_cast<double>(ssize.height));
500     }
501 }
502
503 // for interpolation type : INTER_LINEAR, INTER_LINEAR, INTER_CUBIC, INTER_LANCZOS4
504 void CV_Resize_Test::resize_1d(const Mat& _src, Mat& _dst, int dy, const dim& _dim)
505 {
506     Size dsize = _dst.size();
507     int cn = _dst.channels();
508     float* yD = _dst.ptr<float>(dy);
509
510     if (interpolation == INTER_NEAREST)
511     {
512         const float* yS = _src.ptr<float>(dy);
513         for (int dx = 0; dx < dsize.width; ++dx)
514         {
515             int isx = _dim[dx].first;
516             const float* xyS = yS + isx * cn;
517             float* xyD = yD + dx * cn;
518
519             for (int r = 0; r < cn; ++r)
520                 xyD[r] = xyS[r];
521         }
522     }
523     else if (interpolation == INTER_LINEAR || interpolation == INTER_CUBIC || interpolation == INTER_LANCZOS4)
524     {
525         interpolate_method inter_func = inter_array[interpolation - (interpolation == INTER_LANCZOS4 ? 2 : 1)];
526         size_t elemsize = _src.elemSize();
527
528         int ofs = 0, ksize = 2;
529         if (interpolation == INTER_CUBIC)
530             ofs = 1, ksize = 4;
531         else if (interpolation == INTER_LANCZOS4)
532             ofs = 3, ksize = 8;
533
534         Mat _extended_src_row(1, _src.cols + ksize * 2, _src.type());
535         const uchar* srow = _src.ptr(dy);
536         memcpy(_extended_src_row.data + elemsize * ksize, srow, _src.step);
537         for (int k = 0; k < ksize; ++k)
538         {
539             memcpy(_extended_src_row.data + k * elemsize, srow, elemsize);
540             memcpy(_extended_src_row.data + (ksize + k) * elemsize + _src.step, srow + _src.step - elemsize, elemsize);
541         }
542
543         for (int dx = 0; dx < dsize.width; ++dx)
544         {
545             int isx = _dim[dx].first;
546             double fsx = _dim[dx].second;
547
548             float *xyD = yD + dx * cn;
549             const float* xyS = _extended_src_row.ptr<float>(0) + (isx + ksize - ofs) * cn;
550
551             float w[8];
552             inter_func(static_cast<float>(fsx), w);
553
554             for (int r = 0; r < cn; ++r)
555             {
556                 xyD[r] = 0;
557                 for (int k = 0; k < ksize; ++k)
558                     xyD[r] += w[k] * xyS[k * cn + r];
559             }
560         }
561     }
562     else
563         CV_Assert(0);
564 }
565
566 void CV_Resize_Test::generate_buffer(double scale, dim& _dim)
567 {
568     size_t length = _dim.size();
569     for (size_t dx = 0; dx < length; ++dx)
570     {
571         double fsx = scale * (dx + 0.5) - 0.5;
572         int isx = cvFloor(fsx);
573         _dim[dx] = std::make_pair(isx, fsx - isx);
574     }
575 }
576
577 void CV_Resize_Test::resize_generic()
578 {
579     Size dsize = reference_dst.size(), ssize = src.size();
580     CV_Assert(dsize.area() > 0 && ssize.area() > 0);
581
582     dim dims[] = { dim(dsize.width), dim(dsize.height) };
583     if (interpolation == INTER_NEAREST)
584     {
585         for (int dx = 0; dx < dsize.width; ++dx)
586             dims[0][dx].first = std::min(cvFloor(dx * scale_x), ssize.width - 1);
587         for (int dy = 0; dy < dsize.height; ++dy)
588             dims[1][dy].first = std::min(cvFloor(dy * scale_y), ssize.height - 1);
589     }
590     else
591     {
592         generate_buffer(scale_x, dims[0]);
593         generate_buffer(scale_y, dims[1]);
594     }
595
596     Mat tmp(ssize.height, dsize.width, reference_dst.type());
597     for (int dy = 0; dy < tmp.rows; ++dy)
598         resize_1d(src, tmp, dy, dims[0]);
599
600     transpose(tmp, tmp);
601     transpose(reference_dst, reference_dst);
602
603     for (int dy = 0; dy < tmp.rows; ++dy)
604         resize_1d(tmp, reference_dst, dy, dims[1]);
605     transpose(reference_dst, reference_dst);
606 }
607
608 ////////////////////////////////////////////////////////////////////////////////////////////////////////
609 // remap
610 ////////////////////////////////////////////////////////////////////////////////////////////////////////
611
612 class CV_Remap_Test :
613     public CV_ImageWarpBaseTest
614 {
615 public:
616     CV_Remap_Test();
617
618     virtual ~CV_Remap_Test();
619
620 private:
621     typedef void (CV_Remap_Test::*remap_func)(const Mat&, Mat&);
622
623 protected:
624     virtual void generate_test_data();
625     virtual void prepare_test_data_for_reference_func();
626
627     virtual void run_func();
628     virtual void run_reference_func();
629
630     Mat mapx, mapy;
631     int borderType;
632     Scalar borderValue;
633
634     remap_func funcs[2];
635
636 private:
637     void remap_nearest(const Mat&, Mat&);
638     void remap_generic(const Mat&, Mat&);
639
640     void convert_maps();
641     const char* borderType_to_string() const;
642     virtual void validate_results() const;
643 };
644
645 CV_Remap_Test::CV_Remap_Test() :
646     CV_ImageWarpBaseTest(), mapx(), mapy(),
647     borderType(-1), borderValue()
648 {
649     funcs[0] = &CV_Remap_Test::remap_nearest;
650     funcs[1] = &CV_Remap_Test::remap_generic;
651 }
652
653 CV_Remap_Test::~CV_Remap_Test()
654 {
655 }
656
657 void CV_Remap_Test::generate_test_data()
658 {
659     CV_ImageWarpBaseTest::generate_test_data();
660
661     RNG& rng = ts->get_rng();
662     borderType = rng.uniform(1, BORDER_WRAP);
663     borderValue = Scalar::all(rng.uniform(0, 255));
664
665     // generating the mapx, mapy matrices
666     static const int mapx_types[] = { CV_16SC2, CV_32FC1, CV_32FC2 };
667     mapx.create(dst.size(), mapx_types[rng.uniform(0, sizeof(mapx_types) / sizeof(int))]);
668     mapy = Mat();
669
670     const int n = std::min(std::min(src.cols, src.rows) / 10 + 1, 2);
671     float _n = 0; //static_cast<float>(-n);
672
673     switch (mapx.type())
674     {
675         case CV_16SC2:
676         {
677             MatIterator_<Vec2s> begin_x = mapx.begin<Vec2s>(), end_x = mapx.end<Vec2s>();
678             for ( ; begin_x != end_x; ++begin_x)
679             {
680                 (*begin_x)[0] = static_cast<short>(rng.uniform(static_cast<int>(_n), std::max(src.cols + n - 1, 0)));
681                 (*begin_x)[1] = static_cast<short>(rng.uniform(static_cast<int>(_n), std::max(src.rows + n - 1, 0)));
682             }
683
684             if (interpolation != INTER_NEAREST)
685             {
686                 static const int mapy_types[] = { CV_16UC1, CV_16SC1 };
687                 mapy.create(dst.size(), mapy_types[rng.uniform(0, sizeof(mapy_types) / sizeof(int))]);
688
689                 switch (mapy.type())
690                 {
691                     case CV_16UC1:
692                     {
693                         MatIterator_<ushort> begin_y = mapy.begin<ushort>(), end_y = mapy.end<ushort>();
694                         for ( ; begin_y != end_y; ++begin_y)
695                             begin_y[0] = static_cast<short>(rng.uniform(0, 1024));
696                     }
697                     break;
698
699                     case CV_16SC1:
700                     {
701                         MatIterator_<short> begin_y = mapy.begin<short>(), end_y = mapy.end<short>();
702                         for ( ; begin_y != end_y; ++begin_y)
703                             begin_y[0] = static_cast<short>(rng.uniform(0, 1024));
704                     }
705                     break;
706                 }
707             }
708         }
709         break;
710
711         case CV_32FC1:
712         {
713             mapy.create(dst.size(), CV_32FC1);
714             float fscols = static_cast<float>(std::max(src.cols - 1 + n, 0)),
715                     fsrows = static_cast<float>(std::max(src.rows - 1 + n, 0));
716             MatIterator_<float> begin_x = mapx.begin<float>(), end_x = mapx.end<float>();
717             MatIterator_<float> begin_y = mapy.begin<float>();
718             for ( ; begin_x != end_x; ++begin_x, ++begin_y)
719             {
720                 begin_x[0] = rng.uniform(_n, fscols);
721                 begin_y[0] = rng.uniform(_n, fsrows);
722             }
723         }
724         break;
725
726         case CV_32FC2:
727         {
728             MatIterator_<Vec2f> begin_x = mapx.begin<Vec2f>(), end_x = mapx.end<Vec2f>();
729             float fscols = static_cast<float>(std::max(src.cols - 1 + n, 0)),
730                     fsrows = static_cast<float>(std::max(src.rows - 1 + n, 0));
731             for ( ; begin_x != end_x; ++begin_x)
732             {
733                 begin_x[0] = rng.uniform(_n, fscols);
734                 begin_x[1] = rng.uniform(_n, fsrows);
735             }
736         }
737         break;
738
739         default:
740             assert(0);
741         break;
742     }
743 }
744
745 void CV_Remap_Test::run_func()
746 {
747     remap(src, dst, mapx, mapy, interpolation, borderType, borderValue);
748 }
749
750 void CV_Remap_Test::convert_maps()
751 {
752     if (mapx.type() != CV_16SC2)
753         convertMaps(mapx.clone(), mapy.clone(), mapx, mapy, CV_16SC2, interpolation == INTER_NEAREST);
754     else if (interpolation != INTER_NEAREST)
755         if (mapy.type() != CV_16UC1)
756             mapy.clone().convertTo(mapy, CV_16UC1);
757
758     if (interpolation == INTER_NEAREST)
759         mapy = Mat();
760     CV_Assert(((interpolation == INTER_NEAREST && !mapy.data) || mapy.type() == CV_16UC1 ||
761                mapy.type() == CV_16SC1) && mapx.type() == CV_16SC2);
762 }
763
764 const char* CV_Remap_Test::borderType_to_string() const
765 {
766     if (borderType == BORDER_CONSTANT)
767         return "BORDER_CONSTANT";
768     if (borderType == BORDER_REPLICATE)
769         return "BORDER_REPLICATE";
770     if (borderType == BORDER_REFLECT)
771         return "BORDER_REFLECT";
772     return "Unsupported/Unkown border type";
773 }
774
775 void CV_Remap_Test::prepare_test_data_for_reference_func()
776 {
777     CV_ImageWarpBaseTest::prepare_test_data_for_reference_func();
778     convert_maps();
779 /*
780     const int ksize = 3;
781     Mat kernel = getStructuringElement(CV_MOP_ERODE, Size(ksize, ksize));
782     Mat mask(src.size(), CV_8UC1, Scalar::all(255)), dst_mask;
783     cv::erode(src, erode_src, kernel);
784     cv::erode(mask, dst_mask, kernel, Point(-1, -1), 1, BORDER_CONSTANT, Scalar::all(0));
785     bitwise_not(dst_mask, mask);
786     src.copyTo(erode_src, mask);
787     dst_mask.release();
788
789     mask = Scalar::all(0);
790     kernel = getStructuringElement(CV_MOP_DILATE, kernel.size());
791     cv::dilate(src, dilate_src, kernel);
792     cv::dilate(mask, dst_mask, kernel, Point(-1, -1), 1, BORDER_CONSTANT, Scalar::all(255));
793     src.copyTo(dilate_src, dst_mask);
794     dst_mask.release();
795 */
796 }
797
798 void CV_Remap_Test::run_reference_func()
799 {
800     prepare_test_data_for_reference_func();
801
802     if (interpolation == INTER_AREA)
803         interpolation = INTER_LINEAR;
804
805     int index = interpolation == INTER_NEAREST ? 0 : 1;
806     (this->*funcs[index])(src, reference_dst);
807 }
808
809 void CV_Remap_Test::remap_nearest(const Mat& _src, Mat& _dst)
810 {
811     CV_Assert(_src.depth() == CV_32F && _dst.type() == _src.type());
812     CV_Assert(mapx.type() == CV_16SC2 && !mapy.data);
813
814     Size ssize = _src.size(), dsize = _dst.size();
815     CV_Assert(ssize.area() > 0 && dsize.area() > 0);
816     int cn = _src.channels();
817
818     for (int dy = 0; dy < dsize.height; ++dy)
819     {
820         const short* yM = mapx.ptr<short>(dy);
821         float* yD = _dst.ptr<float>(dy);
822
823         for (int dx = 0; dx < dsize.width; ++dx)
824         {
825             float* xyD = yD + cn * dx;
826             int sx = yM[dx * 2], sy = yM[dx * 2 + 1];
827
828             if (sx >= 0 && sx < ssize.width && sy >= 0 && sy < ssize.height)
829             {
830                 const float *xyS = _src.ptr<float>(sy) + sx * cn;
831
832                 for (int r = 0; r < cn; ++r)
833                     xyD[r] = xyS[r];
834             }
835             else if (borderType != BORDER_TRANSPARENT)
836             {
837                 if (borderType == BORDER_CONSTANT)
838                     for (int r = 0; r < cn; ++r)
839                         xyD[r] = saturate_cast<float>(borderValue[r]);
840                 else
841                 {
842                     sx = borderInterpolate(sx, ssize.width, borderType);
843                     sy = borderInterpolate(sy, ssize.height, borderType);
844                     CV_Assert(sx >= 0 && sy >= 0 && sx < ssize.width && sy < ssize.height);
845
846                     const float *xyS = _src.ptr<float>(sy) + sx * cn;
847
848                     for (int r = 0; r < cn; ++r)
849                         xyD[r] = xyS[r];
850                 }
851             }
852         }
853     }
854 }
855
856 void CV_Remap_Test::remap_generic(const Mat& _src, Mat& _dst)
857 {
858     CV_Assert(mapx.type() == CV_16SC2 && mapy.type() == CV_16UC1);
859
860     int ksize = 2;
861     if (interpolation == INTER_CUBIC)
862         ksize = 4;
863     else if (interpolation == INTER_LANCZOS4)
864         ksize = 8;
865     else if (interpolation != INTER_LINEAR)
866         assert(0);
867     int ofs = (ksize / 2) - 1;
868
869     CV_Assert(_src.depth() == CV_32F && _dst.type() == _src.type());
870     Size ssize = _src.size(), dsize = _dst.size();
871     int cn = _src.channels(), width1 = std::max(ssize.width - ksize + 1, 0),
872         height1 = std::max(ssize.height - ksize + 1, 0);
873
874     float ix[8], w[16];
875     interpolate_method inter_func = inter_array[interpolation - (interpolation == INTER_LANCZOS4 ? 2 : 1)];
876
877     for (int dy = 0; dy < dsize.height; ++dy)
878     {
879         const short* yMx = mapx.ptr<short>(dy);
880         const ushort* yMy = mapy.ptr<ushort>(dy);
881
882         float* yD = _dst.ptr<float>(dy);
883
884         for (int dx = 0; dx < dsize.width; ++dx)
885         {
886             float* xyD = yD + dx * cn;
887             float sx = yMx[dx * 2], sy = yMx[dx * 2 + 1];
888             int isx = cvFloor(sx), isy = cvFloor(sy);
889
890             inter_func((yMy[dx] & (INTER_TAB_SIZE - 1)) / static_cast<float>(INTER_TAB_SIZE), w);
891             inter_func(((yMy[dx] >> INTER_BITS) & (INTER_TAB_SIZE - 1)) / static_cast<float>(INTER_TAB_SIZE), w + ksize);
892
893             isx -= ofs;
894             isy -= ofs;
895
896             if (isx >= 0 && isx < width1 && isy >= 0 && isy < height1)
897             {
898                 for (int r = 0; r < cn; ++r)
899                 {
900                     for (int y = 0; y < ksize; ++y)
901                     {
902                         const float* xyS = _src.ptr<float>(isy + y) + isx * cn;
903
904                         ix[y] = 0;
905                         for (int i = 0; i < ksize; ++i)
906                             ix[y] += w[i] * xyS[i * cn + r];
907                     }
908                     xyD[r] = 0;
909                     for (int i = 0; i < ksize; ++i)
910                         xyD[r] += w[ksize + i] * ix[i];
911                 }
912             }
913             else if (borderType != BORDER_TRANSPARENT)
914             {
915                 int ar_x[8], ar_y[8];
916
917                 for (int k = 0; k < ksize; k++)
918                 {
919                     ar_x[k] = borderInterpolate(isx + k, ssize.width, borderType) * cn;
920                     ar_y[k] = borderInterpolate(isy + k, ssize.height, borderType);
921                 }
922
923                 for (int r = 0; r < cn; r++)
924                 {
925                     xyD[r] = 0;
926                     for (int i = 0; i < ksize; ++i)
927                     {
928                         ix[i] = 0;
929                         if (ar_y[i] >= 0)
930                         {
931                             const float* yS = _src.ptr<float>(ar_y[i]);
932                             for (int j = 0; j < ksize; ++j)
933                                 ix[i] += saturate_cast<float>((ar_x[j] >= 0 ? yS[ar_x[j] + r] : borderValue[r]) * w[j]);
934                         }
935                         else
936                             for (int j = 0; j < ksize; ++j)
937                                 ix[i] += saturate_cast<float>(borderValue[r] * w[j]);
938                     }
939                     for (int i = 0; i < ksize; ++i)
940                         xyD[r] += saturate_cast<float>(w[ksize + i] * ix[i]);
941                 }
942             }
943         }
944     }
945 }
946
947 void CV_Remap_Test::validate_results() const
948 {
949     CV_ImageWarpBaseTest::validate_results();
950     if (cvtest::TS::ptr()->get_err_code() == cvtest::TS::FAIL_BAD_ACCURACY)
951     {
952         PRINT_TO_LOG("BorderType: %s\n", borderType_to_string());
953         PRINT_TO_LOG("BorderValue: (%f, %f, %f, %f)\n",
954                      borderValue[0], borderValue[1], borderValue[2], borderValue[3]);
955     }
956 }
957
958 ////////////////////////////////////////////////////////////////////////////////////////////////////////
959 // warpAffine
960 ////////////////////////////////////////////////////////////////////////////////////////////////////////
961
962 class CV_WarpAffine_Test :
963     public CV_Remap_Test
964 {
965 public:
966     CV_WarpAffine_Test();
967
968     virtual ~CV_WarpAffine_Test();
969
970 protected:
971     virtual void generate_test_data();
972     virtual void prepare_test_data_for_reference_func();
973
974     virtual void run_func();
975     virtual void run_reference_func();
976
977     Mat M;
978 private:
979     void warpAffine(const Mat&, Mat&);
980 };
981
982 CV_WarpAffine_Test::CV_WarpAffine_Test() :
983     CV_Remap_Test()
984 {
985 }
986
987 CV_WarpAffine_Test::~CV_WarpAffine_Test()
988 {
989 }
990
991 void CV_WarpAffine_Test::generate_test_data()
992 {
993     CV_Remap_Test::generate_test_data();
994
995     RNG& rng = ts->get_rng();
996
997     // generating the M 2x3 matrix
998     static const int depths[] = { CV_32FC1, CV_64FC1 };
999
1000     // generating 2d matrix
1001     M = getRotationMatrix2D(Point2f(src.cols / 2.f, src.rows / 2.f),
1002         rng.uniform(-180.f, 180.f), rng.uniform(0.4f, 2.0f));
1003     int depth = depths[rng.uniform(0, sizeof(depths) / sizeof(depths[0]))];
1004     if (M.depth() != depth)
1005     {
1006         Mat tmp;
1007         M.convertTo(tmp, depth);
1008         M = tmp;
1009     }
1010
1011     // warp_matrix is inverse
1012     if (rng.uniform(0., 1.) > 0)
1013         interpolation |= CV_WARP_INVERSE_MAP;
1014 }
1015
1016 void CV_WarpAffine_Test::run_func()
1017 {
1018     cv::warpAffine(src, dst, M, dst.size(), interpolation, borderType, borderValue);
1019 }
1020
1021 void CV_WarpAffine_Test::prepare_test_data_for_reference_func()
1022 {
1023     CV_ImageWarpBaseTest::prepare_test_data_for_reference_func();
1024 }
1025
1026 void CV_WarpAffine_Test::run_reference_func()
1027 {
1028     prepare_test_data_for_reference_func();
1029
1030     warpAffine(src, reference_dst);
1031 }
1032
1033 void CV_WarpAffine_Test::warpAffine(const Mat& _src, Mat& _dst)
1034 {
1035     Size dsize = _dst.size();
1036
1037     CV_Assert(_src.size().area() > 0);
1038     CV_Assert(dsize.area() > 0);
1039     CV_Assert(_src.type() == _dst.type());
1040
1041     Mat tM;
1042     M.convertTo(tM, CV_64F);
1043
1044     int inter = interpolation & INTER_MAX;
1045     if (inter == INTER_AREA)
1046         inter = INTER_LINEAR;
1047
1048     mapx.create(dsize, CV_16SC2);
1049     if (inter != INTER_NEAREST)
1050         mapy.create(dsize, CV_16SC1);
1051     else
1052         mapy = Mat();
1053
1054     if (!(interpolation & CV_WARP_INVERSE_MAP))
1055         invertAffineTransform(tM.clone(), tM);
1056
1057     const int AB_BITS = MAX(10, (int)INTER_BITS);
1058     const int AB_SCALE = 1 << AB_BITS;
1059     int round_delta = (inter == INTER_NEAREST) ? AB_SCALE / 2 : (AB_SCALE / INTER_TAB_SIZE / 2);
1060
1061     const double* data_tM = tM.ptr<double>(0);
1062     for (int dy = 0; dy < dsize.height; ++dy)
1063     {
1064         short* yM = mapx.ptr<short>(dy);
1065         for (int dx = 0; dx < dsize.width; ++dx, yM += 2)
1066         {
1067             int v1 = saturate_cast<int>(saturate_cast<int>(data_tM[0] * dx * AB_SCALE) +
1068                     saturate_cast<int>((data_tM[1] * dy + data_tM[2]) * AB_SCALE) + round_delta),
1069                    v2 = saturate_cast<int>(saturate_cast<int>(data_tM[3] * dx * AB_SCALE) +
1070                     saturate_cast<int>((data_tM[4] * dy + data_tM[5]) * AB_SCALE) + round_delta);
1071             v1 >>= AB_BITS - INTER_BITS;
1072             v2 >>= AB_BITS - INTER_BITS;
1073
1074             yM[0] = saturate_cast<short>(v1 >> INTER_BITS);
1075             yM[1] = saturate_cast<short>(v2 >> INTER_BITS);
1076
1077             if (inter != INTER_NEAREST)
1078                 mapy.ptr<short>(dy)[dx] = ((v2 & (INTER_TAB_SIZE - 1)) * INTER_TAB_SIZE + (v1 & (INTER_TAB_SIZE - 1)));
1079         }
1080     }
1081
1082     CV_Assert(mapx.type() == CV_16SC2 && ((inter == INTER_NEAREST && !mapy.data) || mapy.type() == CV_16SC1));
1083     cv::remap(_src, _dst, mapx, mapy, inter, borderType, borderValue);
1084 }
1085
1086 ////////////////////////////////////////////////////////////////////////////////////////////////////////
1087 // warpPerspective
1088 ////////////////////////////////////////////////////////////////////////////////////////////////////////
1089
1090 class CV_WarpPerspective_Test :
1091     public CV_WarpAffine_Test
1092 {
1093 public:
1094     CV_WarpPerspective_Test();
1095
1096     virtual ~CV_WarpPerspective_Test();
1097
1098 protected:
1099     virtual void generate_test_data();
1100
1101     virtual void run_func();
1102     virtual void run_reference_func();
1103
1104 private:
1105     void warpPerspective(const Mat&, Mat&);
1106 };
1107
1108 CV_WarpPerspective_Test::CV_WarpPerspective_Test() :
1109     CV_WarpAffine_Test()
1110 {
1111 }
1112
1113 CV_WarpPerspective_Test::~CV_WarpPerspective_Test()
1114 {
1115 }
1116
1117 void CV_WarpPerspective_Test::generate_test_data()
1118 {
1119     CV_Remap_Test::generate_test_data();
1120
1121     // generating the M 3x3 matrix
1122     RNG& rng = ts->get_rng();
1123
1124     float cols = static_cast<float>(src.cols), rows = static_cast<float>(src.rows);
1125     Point2f sp[] = { Point2f(0.0f, 0.0f), Point2f(cols, 0.0f), Point2f(0.0f, rows), Point2f(cols, rows) };
1126     Point2f dp[] = { Point2f(rng.uniform(0.0f, cols), rng.uniform(0.0f, rows)),
1127         Point2f(rng.uniform(0.0f, cols), rng.uniform(0.0f, rows)),
1128         Point2f(rng.uniform(0.0f, cols), rng.uniform(0.0f, rows)),
1129         Point2f(rng.uniform(0.0f, cols), rng.uniform(0.0f, rows)) };
1130     M = getPerspectiveTransform(sp, dp);
1131
1132     static const int depths[] = { CV_32F, CV_64F };
1133     int depth = depths[rng.uniform(0, 2)];
1134     M.clone().convertTo(M, depth);
1135 }
1136
1137 void CV_WarpPerspective_Test::run_func()
1138 {
1139     cv::warpPerspective(src, dst, M, dst.size(), interpolation, borderType, borderValue);
1140 }
1141
1142 void CV_WarpPerspective_Test::run_reference_func()
1143 {
1144     prepare_test_data_for_reference_func();
1145
1146     warpPerspective(src, reference_dst);
1147 }
1148
1149 void CV_WarpPerspective_Test::warpPerspective(const Mat& _src, Mat& _dst)
1150 {
1151     Size ssize = _src.size(), dsize = _dst.size();
1152
1153     CV_Assert(ssize.area() > 0);
1154     CV_Assert(dsize.area() > 0);
1155     CV_Assert(_src.type() == _dst.type());
1156
1157     if (M.depth() != CV_64F)
1158     {
1159         Mat tmp;
1160         M.convertTo(tmp, CV_64F);
1161         M = tmp;
1162     }
1163
1164     if (!(interpolation & CV_WARP_INVERSE_MAP))
1165     {
1166         Mat tmp;
1167         invert(M, tmp);
1168         M = tmp;
1169     }
1170
1171     int inter = interpolation & INTER_MAX;
1172     if (inter == INTER_AREA)
1173         inter = INTER_LINEAR;
1174
1175     mapx.create(dsize, CV_16SC2);
1176     if (inter != INTER_NEAREST)
1177         mapy.create(dsize, CV_16SC1);
1178     else
1179         mapy = Mat();
1180
1181     double* tM = M.ptr<double>(0);
1182     for (int dy = 0; dy < dsize.height; ++dy)
1183     {
1184         short* yMx = mapx.ptr<short>(dy);
1185
1186         for (int dx = 0; dx < dsize.width; ++dx, yMx += 2)
1187         {
1188             double den = tM[6] * dx + tM[7] * dy + tM[8];
1189             den = den ? 1.0 / den : 0.0;
1190
1191             if (inter == INTER_NEAREST)
1192             {
1193                 yMx[0] = saturate_cast<short>((tM[0] * dx + tM[1] * dy + tM[2]) * den);
1194                 yMx[1] = saturate_cast<short>((tM[3] * dx + tM[4] * dy + tM[5]) * den);
1195                 continue;
1196             }
1197
1198             den *= INTER_TAB_SIZE;
1199             int v0 = saturate_cast<int>((tM[0] * dx + tM[1] * dy + tM[2]) * den);
1200             int v1 = saturate_cast<int>((tM[3] * dx + tM[4] * dy + tM[5]) * den);
1201
1202             yMx[0] = saturate_cast<short>(v0 >> INTER_BITS);
1203             yMx[1] = saturate_cast<short>(v1 >> INTER_BITS);
1204             mapy.ptr<short>(dy)[dx] = saturate_cast<short>((v1 & (INTER_TAB_SIZE - 1)) *
1205                     INTER_TAB_SIZE + (v0 & (INTER_TAB_SIZE - 1)));
1206         }
1207     }
1208
1209     CV_Assert(mapx.type() == CV_16SC2 && ((inter == INTER_NEAREST && !mapy.data) || mapy.type() == CV_16SC1));
1210     cv::remap(_src, _dst, mapx, mapy, inter, borderType, borderValue);
1211 }
1212
1213 ////////////////////////////////////////////////////////////////////////////////////////////////////////
1214 // Tests
1215 ////////////////////////////////////////////////////////////////////////////////////////////////////////
1216
1217 TEST(Imgproc_Resize_Test, accuracy) { CV_Resize_Test test; test.safe_run(); }
1218 TEST(Imgproc_Remap_Test, accuracy) { CV_Remap_Test test; test.safe_run(); }
1219 TEST(Imgproc_WarpAffine_Test, accuracy) { CV_WarpAffine_Test test; test.safe_run(); }
1220 TEST(Imgproc_WarpPerspective_Test, accuracy) { CV_WarpPerspective_Test test; test.safe_run(); }