test_approxpoly.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  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. #include "test_precomp.hpp"
  42. namespace opencv_test { namespace {
  43. //
  44. // TODO!!!:
  45. // check_slice (and/or check) seem(s) to be broken, or this is a bug in function
  46. // (or its inability to handle possible self-intersections in the generated contours).
  47. //
  48. // At least, if // return TotalErrors;
  49. // is uncommented in check_slice, the test fails easily.
  50. // So, now (and it looks like since 0.9.6)
  51. // we only check that the set of vertices of the approximated polygon is
  52. // a subset of vertices of the original contour.
  53. //
  54. class CV_ApproxPolyTest : public cvtest::BaseTest
  55. {
  56. public:
  57. CV_ApproxPolyTest();
  58. ~CV_ApproxPolyTest();
  59. void clear();
  60. //int write_default_params(CvFileStorage* fs);
  61. protected:
  62. //int read_params( const cv::FileStorage& fs );
  63. int check_slice( CvPoint StartPt, CvPoint EndPt,
  64. CvSeqReader* SrcReader, float Eps,
  65. int* j, int Count );
  66. int check( CvSeq* SrcSeq, CvSeq* DstSeq, float Eps );
  67. bool get_contour( int /*type*/, CvSeq** Seq, int* d,
  68. CvMemStorage* storage );
  69. void run(int);
  70. };
  71. CV_ApproxPolyTest::CV_ApproxPolyTest()
  72. {
  73. }
  74. CV_ApproxPolyTest::~CV_ApproxPolyTest()
  75. {
  76. clear();
  77. }
  78. void CV_ApproxPolyTest::clear()
  79. {
  80. cvtest::BaseTest::clear();
  81. }
  82. /*int CV_ApproxPolyTest::write_default_params( CvFileStorage* fs )
  83. {
  84. cvtest::BaseTest::write_default_params( fs );
  85. if( ts->get_testing_mode() != cvtest::TS::TIMING_MODE )
  86. {
  87. write_param( fs, "test_case_count", test_case_count );
  88. }
  89. return 0;
  90. }
  91. int CV_ApproxPolyTest::read_params( const cv::FileStorage& fs )
  92. {
  93. int code = cvtest::BaseTest::read_params( fs );
  94. if( code < 0 )
  95. return code;
  96. test_case_count = cvReadInt( find_param( fs, "test_case_count" ), test_case_count );
  97. min_log_size = cvtest::clipInt( min_log_size, 1, 10 );
  98. return 0;
  99. }*/
  100. bool CV_ApproxPolyTest::get_contour( int /*type*/, CvSeq** Seq, int* d,
  101. CvMemStorage* storage )
  102. {
  103. RNG& rng = ts->get_rng();
  104. int max_x = INT_MIN, max_y = INT_MIN, min_x = INT_MAX, min_y = INT_MAX;
  105. int i;
  106. CvSeq* seq;
  107. int total = cvtest::randInt(rng) % 1000 + 1;
  108. Point center;
  109. int radius, angle;
  110. double deg_to_rad = CV_PI/180.;
  111. Point pt;
  112. center.x = cvtest::randInt( rng ) % 1000;
  113. center.y = cvtest::randInt( rng ) % 1000;
  114. radius = cvtest::randInt( rng ) % 1000;
  115. angle = cvtest::randInt( rng ) % 360;
  116. seq = cvCreateSeq( CV_SEQ_POLYGON, sizeof(CvContour), sizeof(CvPoint), storage );
  117. for( i = 0; i < total; i++ )
  118. {
  119. int d_radius = cvtest::randInt( rng ) % 10 - 5;
  120. int d_angle = 360/total;//cvtest::randInt( rng ) % 10 - 5;
  121. pt.x = cvRound( center.x + radius*cos(angle*deg_to_rad));
  122. pt.y = cvRound( center.x - radius*sin(angle*deg_to_rad));
  123. radius += d_radius;
  124. angle += d_angle;
  125. cvSeqPush( seq, &pt );
  126. max_x = MAX( max_x, pt.x );
  127. max_y = MAX( max_y, pt.y );
  128. min_x = MIN( min_x, pt.x );
  129. min_y = MIN( min_y, pt.y );
  130. }
  131. *d = (max_x - min_x)*(max_x - min_x) + (max_y - min_y)*(max_y - min_y);
  132. *Seq = seq;
  133. return true;
  134. }
  135. int CV_ApproxPolyTest::check_slice( CvPoint StartPt, CvPoint EndPt,
  136. CvSeqReader* SrcReader, float Eps,
  137. int* _j, int Count )
  138. {
  139. ///////////
  140. Point Pt;
  141. ///////////
  142. bool flag;
  143. double dy,dx;
  144. double A,B,C;
  145. double Sq;
  146. double sin_a = 0;
  147. double cos_a = 0;
  148. double d = 0;
  149. double dist;
  150. ///////////
  151. int j, TotalErrors = 0;
  152. ////////////////////////////////
  153. if( SrcReader == NULL )
  154. {
  155. CV_Assert( false );
  156. return 0;
  157. }
  158. ///////// init line ////////////
  159. flag = true;
  160. dx = (double)StartPt.x - (double)EndPt.x;
  161. dy = (double)StartPt.y - (double)EndPt.y;
  162. if( ( dx == 0 ) && ( dy == 0 ) ) flag = false;
  163. else
  164. {
  165. A = -dy;
  166. B = dx;
  167. C = dy * (double)StartPt.x - dx * (double)StartPt.y;
  168. Sq = sqrt( A*A + B*B );
  169. sin_a = B/Sq;
  170. cos_a = A/Sq;
  171. d = C/Sq;
  172. }
  173. /////// find start point and check distance ////////
  174. for( j = *_j; j < Count; j++ )
  175. {
  176. { CvPoint pt_ = CV_STRUCT_INITIALIZER; CV_READ_SEQ_ELEM(pt_, *SrcReader); Pt = pt_; }
  177. if( StartPt.x == Pt.x && StartPt.y == Pt.y ) break;
  178. else
  179. {
  180. if( flag ) dist = sin_a * Pt.y + cos_a * Pt.x - d;
  181. else dist = sqrt( (double)(EndPt.y - Pt.y)*(EndPt.y - Pt.y) + (EndPt.x - Pt.x)*(EndPt.x - Pt.x) );
  182. if( dist > Eps ) TotalErrors++;
  183. }
  184. }
  185. *_j = j;
  186. (void) TotalErrors; // To avoid -Wunused-but-set-variable warning
  187. //return TotalErrors;
  188. return 0;
  189. }
  190. int CV_ApproxPolyTest::check( CvSeq* SrcSeq, CvSeq* DstSeq, float Eps )
  191. {
  192. //////////
  193. CvSeqReader DstReader;
  194. CvSeqReader SrcReader;
  195. CvPoint StartPt = {0, 0}, EndPt = {0, 0};
  196. ///////////
  197. int TotalErrors = 0;
  198. ///////////
  199. int Count;
  200. int i,j;
  201. CV_Assert( SrcSeq && DstSeq );
  202. ////////// init ////////////////////
  203. Count = SrcSeq->total;
  204. cvStartReadSeq( DstSeq, &DstReader, 0 );
  205. cvStartReadSeq( SrcSeq, &SrcReader, 0 );
  206. CV_READ_SEQ_ELEM( StartPt, DstReader );
  207. for( i = 0 ; i < Count ; )
  208. {
  209. CV_READ_SEQ_ELEM( EndPt, SrcReader );
  210. i++;
  211. if( StartPt.x == EndPt.x && StartPt.y == EndPt.y ) break;
  212. }
  213. ///////// start ////////////////
  214. for( i = 1, j = 0 ; i <= DstSeq->total ; )
  215. {
  216. ///////// read slice ////////////
  217. EndPt.x = StartPt.x;
  218. EndPt.y = StartPt.y;
  219. CV_READ_SEQ_ELEM( StartPt, DstReader );
  220. i++;
  221. TotalErrors += check_slice( StartPt, EndPt, &SrcReader, Eps, &j, Count );
  222. if( j > Count )
  223. {
  224. TotalErrors++;
  225. return TotalErrors;
  226. } //if( !flag )
  227. } // for( int i = 0 ; i < DstSeq->total ; i++ )
  228. return TotalErrors;
  229. }
  230. //extern CvTestContourGenerator cvTsTestContours[];
  231. void CV_ApproxPolyTest::run( int /*start_from*/ )
  232. {
  233. int code = cvtest::TS::OK;
  234. CvMemStorage* storage = 0;
  235. ////////////// Variables ////////////////
  236. int IntervalsCount = 10;
  237. ///////////
  238. //CvTestContourGenerator Cont;
  239. CvSeq* SrcSeq = NULL;
  240. CvSeq* DstSeq;
  241. int iDiam;
  242. float dDiam, Eps, EpsStep;
  243. for( int i = 0; i < 30; i++ )
  244. {
  245. CvMemStoragePos pos;
  246. ts->update_context( this, i, false );
  247. ///////////////////// init contour /////////
  248. dDiam = 0;
  249. while( sqrt(dDiam) / IntervalsCount == 0 )
  250. {
  251. if( storage != 0 )
  252. cvReleaseMemStorage(&storage);
  253. storage = cvCreateMemStorage( 0 );
  254. if( get_contour( 0, &SrcSeq, &iDiam, storage ) )
  255. dDiam = (float)iDiam;
  256. }
  257. dDiam = (float)sqrt( dDiam );
  258. storage = SrcSeq->storage;
  259. ////////////////// test /////////////
  260. EpsStep = dDiam / IntervalsCount ;
  261. for( Eps = EpsStep ; Eps < dDiam ; Eps += EpsStep )
  262. {
  263. cvSaveMemStoragePos( storage, &pos );
  264. ////////// call function ////////////
  265. DstSeq = cvApproxPoly( SrcSeq, SrcSeq->header_size, storage,
  266. CV_POLY_APPROX_DP, Eps );
  267. if( DstSeq == NULL )
  268. {
  269. ts->printf( cvtest::TS::LOG,
  270. "cvApproxPoly returned NULL for contour #%d, epsilon = %g\n", i, Eps );
  271. code = cvtest::TS::FAIL_INVALID_OUTPUT;
  272. goto _exit_;
  273. } // if( DstSeq == NULL )
  274. code = check( SrcSeq, DstSeq, Eps );
  275. if( code != 0 )
  276. {
  277. ts->printf( cvtest::TS::LOG,
  278. "Incorrect result for the contour #%d approximated with epsilon=%g\n", i, Eps );
  279. code = cvtest::TS::FAIL_BAD_ACCURACY;
  280. goto _exit_;
  281. }
  282. cvRestoreMemStoragePos( storage, &pos );
  283. } // for( Eps = EpsStep ; Eps <= Diam ; Eps += EpsStep )
  284. ///////////// free memory ///////////////////
  285. cvReleaseMemStorage(&storage);
  286. } // for( int i = 0; NULL != ( Cont = Contours[i] ) ; i++ )
  287. _exit_:
  288. cvReleaseMemStorage(&storage);
  289. if( code < 0 )
  290. ts->set_failed_test_info( code );
  291. }
  292. TEST(Imgproc_ApproxPoly, accuracy) { CV_ApproxPolyTest test; test.safe_run(); }
  293. //Tests to make sure that unreasonable epsilon (error)
  294. //values never get passed to the Douglas-Peucker algorithm.
  295. TEST(Imgproc_ApproxPoly, bad_epsilon)
  296. {
  297. std::vector<Point2f> inputPoints;
  298. inputPoints.push_back(Point2f(0.0f, 0.0f));
  299. std::vector<Point2f> outputPoints;
  300. double eps = std::numeric_limits<double>::infinity();
  301. ASSERT_ANY_THROW(approxPolyDP(inputPoints, outputPoints, eps, false));
  302. eps = 9e99;
  303. ASSERT_ANY_THROW(approxPolyDP(inputPoints, outputPoints, eps, false));
  304. eps = -1e-6;
  305. ASSERT_ANY_THROW(approxPolyDP(inputPoints, outputPoints, eps, false));
  306. eps = NAN;
  307. ASSERT_ANY_THROW(approxPolyDP(inputPoints, outputPoints, eps, false));
  308. }
  309. TEST(Imgproc_ApproxPoly, distace_between_point_and_segment)
  310. {
  311. vector<Point2f> inputPoints = {
  312. { {0.f, 0.f}, {4.f, 2.f}, {11.f, 1.f}, {8.f, 0.f} }
  313. };
  314. std::vector<Point2f> result;
  315. approxPolyDP(inputPoints, result, 1.9, false);
  316. vector<Point2f> expectedResult = {
  317. { {0.f, 0.f}, {11.f, 1.f}, {8.f, 0.f} }
  318. };
  319. ASSERT_EQ(result, expectedResult);
  320. }
  321. struct ApproxPolyN: public testing::Test
  322. {
  323. void SetUp()
  324. {
  325. vector<vector<Point>> inputPoints = {
  326. { {87, 103}, {100, 112}, {96, 138}, {80, 169}, {60, 183}, {38, 176}, {41, 145}, {56, 118}, {76, 104} },
  327. { {196, 102}, {205, 118}, {174, 196}, {152, 207}, {102, 194}, {100, 175}, {131, 109} },
  328. { {372, 101}, {377, 119}, {337, 238}, {324, 248}, {240, 229}, {199, 214}, {232, 123}, {245, 103} },
  329. { {463, 86}, {563, 112}, {574, 135}, {596, 221}, {518, 298}, {412, 266}, {385, 164}, {462, 86} }
  330. };
  331. Mat image(600, 600, CV_8UC1, Scalar(0));
  332. for (vector<Point>& polygon : inputPoints) {
  333. polylines(image, { polygon }, true, Scalar(255), 1);
  334. }
  335. findContours(image, contours, RETR_LIST, CHAIN_APPROX_NONE);
  336. }
  337. vector<vector<Point>> contours;
  338. };
  339. TEST_F(ApproxPolyN, accuracyInt)
  340. {
  341. vector<vector<Point>> rightCorners = {
  342. { {72, 187}, {37, 176}, {42, 127}, {133, 64} },
  343. { {168, 212}, {92, 192}, {131, 109}, {213, 100} },
  344. { {72, 187}, {37, 176}, {42, 127}, {133, 64} },
  345. { {384, 100}, {333, 251}, {197, 220}, {239, 103} },
  346. { {168, 212}, {92, 192}, {131, 109}, {213, 100} },
  347. { {333, 251}, {197, 220}, {239, 103}, {384, 100} },
  348. { {542, 6}, {596, 221}, {518, 299}, {312, 236} },
  349. { {596, 221}, {518, 299}, {312, 236}, {542, 6} }
  350. };
  351. EXPECT_EQ(rightCorners.size(), contours.size());
  352. for (size_t i = 0; i < contours.size(); ++i) {
  353. std::vector<Point> corners;
  354. approxPolyN(contours[i], corners, 4, -1, true);
  355. ASSERT_EQ(rightCorners[i], corners );
  356. }
  357. }
  358. TEST_F(ApproxPolyN, accuracyFloat)
  359. {
  360. vector<vector<Point2f>> rightCorners = {
  361. { {72.f, 187.f}, {37.f, 176.f}, {42.f, 127.f}, {133.f, 64.f} },
  362. { {168.f, 212.f}, {92.f, 192.f}, {131.f, 109.f}, {213.f, 100.f} },
  363. { {72.f, 187.f}, {37.f, 176.f}, {42.f, 127.f}, {133.f, 64.f} },
  364. { {384.f, 100.f}, {333.f, 251.f}, {197.f, 220.f}, {239.f, 103.f} },
  365. { {168.f, 212.f}, {92.f, 192.f}, {131.f, 109.f}, {213.f, 100.f} },
  366. { {333.f, 251.f}, {197.f, 220.f}, {239.f, 103.f}, {384.f, 100.f} },
  367. { {542.f, 6.f}, {596.f, 221.f}, {518.f, 299.f}, {312.f, 236.f} },
  368. { {596.f, 221.f}, {518.f, 299.f}, {312.f, 236.f}, {542.f, 6.f} }
  369. };
  370. EXPECT_EQ(rightCorners.size(), contours.size());
  371. for (size_t i = 0; i < contours.size(); ++i) {
  372. std::vector<Point2f> corners;
  373. approxPolyN(contours[i], corners, 4, -1, true);
  374. EXPECT_LT(cvtest::norm(rightCorners[i], corners, NORM_INF), .5f);
  375. }
  376. }
  377. TEST_F(ApproxPolyN, bad_args)
  378. {
  379. Mat contour(10, 1, CV_32FC2);
  380. vector<vector<Point>> bad_contours;
  381. vector<Point> corners;
  382. ASSERT_ANY_THROW(approxPolyN(contour, corners, 0));
  383. ASSERT_ANY_THROW(approxPolyN(contour, corners, 3, 0));
  384. ASSERT_ANY_THROW(approxPolyN(bad_contours, corners, 4));
  385. }
  386. }} // namespace