test_canny.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  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. class CV_CannyTest : public cvtest::ArrayTest
  44. {
  45. public:
  46. CV_CannyTest(bool custom_deriv = false);
  47. protected:
  48. void get_test_array_types_and_sizes( int test_case_idx, vector<vector<Size> >& sizes, vector<vector<int> >& types );
  49. double get_success_error_level( int test_case_idx, int i, int j );
  50. int prepare_test_case( int test_case_idx );
  51. void run_func();
  52. void prepare_to_validation( int );
  53. int validate_test_results( int /*test_case_idx*/ );
  54. int aperture_size;
  55. bool use_true_gradient;
  56. double threshold1, threshold2;
  57. bool test_cpp;
  58. bool test_custom_deriv;
  59. Mat img;
  60. };
  61. CV_CannyTest::CV_CannyTest(bool custom_deriv)
  62. {
  63. test_array[INPUT].push_back(NULL);
  64. test_array[OUTPUT].push_back(NULL);
  65. test_array[REF_OUTPUT].push_back(NULL);
  66. element_wise_relative_error = true;
  67. aperture_size = 0;
  68. use_true_gradient = false;
  69. threshold1 = threshold2 = 0;
  70. test_custom_deriv = custom_deriv;
  71. const char imgPath[] = "shared/fruits.png";
  72. img = cv::imread(cvtest::TS::ptr()->get_data_path() + imgPath, IMREAD_GRAYSCALE);
  73. }
  74. void CV_CannyTest::get_test_array_types_and_sizes( int test_case_idx,
  75. vector<vector<Size> >& sizes,
  76. vector<vector<int> >& types )
  77. {
  78. RNG& rng = ts->get_rng();
  79. double thresh_range;
  80. cvtest::ArrayTest::get_test_array_types_and_sizes( test_case_idx, sizes, types );
  81. types[INPUT][0] = types[OUTPUT][0] = types[REF_OUTPUT][0] = CV_8U;
  82. aperture_size = cvtest::randInt(rng) % 2 ? 5 : 3;
  83. thresh_range = aperture_size == 3 ? 300 : 1000;
  84. threshold1 = cvtest::randReal(rng)*thresh_range;
  85. threshold2 = cvtest::randReal(rng)*thresh_range*0.3;
  86. if( cvtest::randInt(rng) % 2 )
  87. CV_SWAP( threshold1, threshold2, thresh_range );
  88. use_true_gradient = cvtest::randInt(rng) % 2 != 0;
  89. test_cpp = (cvtest::randInt(rng) & 256) == 0;
  90. ts->printf(cvtest::TS::LOG, "Canny(size = %d x %d, aperture_size = %d, threshold1 = %g, threshold2 = %g, L2 = %s) test_cpp = %s (test case #%d)\n",
  91. sizes[0][0].width, sizes[0][0].height, aperture_size, threshold1, threshold2, use_true_gradient ? "TRUE" : "FALSE", test_cpp ? "TRUE" : "FALSE", test_case_idx);
  92. }
  93. int CV_CannyTest::prepare_test_case( int test_case_idx )
  94. {
  95. int code = cvtest::ArrayTest::prepare_test_case( test_case_idx );
  96. if( code > 0 )
  97. {
  98. RNG& rng = ts->get_rng();
  99. Mat& src = test_mat[INPUT][0];
  100. //GaussianBlur(src, src, Size(11, 11), 5, 5);
  101. if(src.cols > img.cols || src.rows > img.rows)
  102. resize(img, src, src.size(), 0, 0, INTER_LINEAR_EXACT);
  103. else
  104. img(
  105. Rect(
  106. cvtest::randInt(rng) % (img.cols-src.cols),
  107. cvtest::randInt(rng) % (img.rows-src.rows),
  108. src.cols,
  109. src.rows
  110. )
  111. ).copyTo(src);
  112. GaussianBlur(src, src, Size(5, 5), 0);
  113. }
  114. return code;
  115. }
  116. double CV_CannyTest::get_success_error_level( int /*test_case_idx*/, int /*i*/, int /*j*/ )
  117. {
  118. return 0;
  119. }
  120. void CV_CannyTest::run_func()
  121. {
  122. if (test_custom_deriv)
  123. {
  124. cv::Mat _out = cv::cvarrToMat(test_array[OUTPUT][0]);
  125. cv::Mat src = cv::cvarrToMat(test_array[INPUT][0]);
  126. cv::Mat dx, dy;
  127. int m = aperture_size;
  128. Point anchor(m/2, m/2);
  129. Mat dxkernel = cvtest::calcSobelKernel2D( 1, 0, m, 0 );
  130. Mat dykernel = cvtest::calcSobelKernel2D( 0, 1, m, 0 );
  131. cvtest::filter2D(src, dx, CV_16S, dxkernel, anchor, 0, BORDER_REPLICATE);
  132. cvtest::filter2D(src, dy, CV_16S, dykernel, anchor, 0, BORDER_REPLICATE);
  133. cv::Canny(dx, dy, _out, threshold1, threshold2, use_true_gradient);
  134. }
  135. else
  136. {
  137. cv::Mat _out = cv::cvarrToMat(test_array[OUTPUT][0]);
  138. cv::Canny(cv::cvarrToMat(test_array[INPUT][0]), _out, threshold1, threshold2,
  139. aperture_size + (use_true_gradient ? CV_CANNY_L2_GRADIENT : 0));
  140. }
  141. }
  142. static void
  143. cannyFollow( int x, int y, float lowThreshold, const Mat& mag, Mat& dst )
  144. {
  145. static const int ofs[][2] = {{1,0},{1,-1},{0,-1},{-1,-1},{-1,0},{-1,1},{0,1},{1,1}};
  146. int i;
  147. dst.at<uchar>(y, x) = (uchar)255;
  148. for( i = 0; i < 8; i++ )
  149. {
  150. int x1 = x + ofs[i][0];
  151. int y1 = y + ofs[i][1];
  152. if( (unsigned)x1 < (unsigned)mag.cols &&
  153. (unsigned)y1 < (unsigned)mag.rows &&
  154. mag.at<float>(y1, x1) > lowThreshold &&
  155. !dst.at<uchar>(y1, x1) )
  156. cannyFollow( x1, y1, lowThreshold, mag, dst );
  157. }
  158. }
  159. static void
  160. test_Canny( const Mat& src, Mat& dst,
  161. double threshold1, double threshold2,
  162. int aperture_size, bool use_true_gradient )
  163. {
  164. int m = aperture_size;
  165. Point anchor(m/2, m/2);
  166. const double tan_pi_8 = tan(CV_PI/8.);
  167. const double tan_3pi_8 = tan(CV_PI*3/8);
  168. float lowThreshold = (float)MIN(threshold1, threshold2);
  169. float highThreshold = (float)MAX(threshold1, threshold2);
  170. int x, y, width = src.cols, height = src.rows;
  171. Mat dxkernel = cvtest::calcSobelKernel2D( 1, 0, m, 0 );
  172. Mat dykernel = cvtest::calcSobelKernel2D( 0, 1, m, 0 );
  173. Mat dx, dy, mag(height, width, CV_32F);
  174. cvtest::filter2D(src, dx, CV_32S, dxkernel, anchor, 0, BORDER_REPLICATE);
  175. cvtest::filter2D(src, dy, CV_32S, dykernel, anchor, 0, BORDER_REPLICATE);
  176. // calc gradient magnitude
  177. for( y = 0; y < height; y++ )
  178. {
  179. for( x = 0; x < width; x++ )
  180. {
  181. int dxval = dx.at<int>(y, x), dyval = dy.at<int>(y, x);
  182. mag.at<float>(y, x) = use_true_gradient ?
  183. (float)sqrt((double)(dxval*dxval + dyval*dyval)) :
  184. (float)(fabs((double)dxval) + fabs((double)dyval));
  185. }
  186. }
  187. // calc gradient direction, do nonmaxima suppression
  188. for( y = 0; y < height; y++ )
  189. {
  190. for( x = 0; x < width; x++ )
  191. {
  192. float a = mag.at<float>(y, x), b = 0, c = 0;
  193. int y1 = 0, y2 = 0, x1 = 0, x2 = 0;
  194. if( a <= lowThreshold )
  195. continue;
  196. int dxval = dx.at<int>(y, x);
  197. int dyval = dy.at<int>(y, x);
  198. double tg = dxval ? (double)dyval/dxval : DBL_MAX*CV_SIGN(dyval);
  199. if( fabs(tg) < tan_pi_8 )
  200. {
  201. y1 = y2 = y; x1 = x + 1; x2 = x - 1;
  202. }
  203. else if( tan_pi_8 <= tg && tg <= tan_3pi_8 )
  204. {
  205. y1 = y + 1; y2 = y - 1; x1 = x + 1; x2 = x - 1;
  206. }
  207. else if( -tan_3pi_8 <= tg && tg <= -tan_pi_8 )
  208. {
  209. y1 = y - 1; y2 = y + 1; x1 = x + 1; x2 = x - 1;
  210. }
  211. else
  212. {
  213. CV_Assert( fabs(tg) > tan_3pi_8 );
  214. x1 = x2 = x; y1 = y + 1; y2 = y - 1;
  215. }
  216. if( (unsigned)y1 < (unsigned)height && (unsigned)x1 < (unsigned)width )
  217. b = (float)fabs(mag.at<float>(y1, x1));
  218. if( (unsigned)y2 < (unsigned)height && (unsigned)x2 < (unsigned)width )
  219. c = (float)fabs(mag.at<float>(y2, x2));
  220. if( (a > b || (a == b && ((x1 == x+1 && y1 == y) || (x1 == x && y1 == y+1)))) && a > c )
  221. ;
  222. else
  223. mag.at<float>(y, x) = -a;
  224. }
  225. }
  226. dst = Scalar::all(0);
  227. // hysteresis threshold
  228. for( y = 0; y < height; y++ )
  229. {
  230. for( x = 0; x < width; x++ )
  231. if( mag.at<float>(y, x) > highThreshold && !dst.at<uchar>(y, x) )
  232. cannyFollow( x, y, lowThreshold, mag, dst );
  233. }
  234. }
  235. void CV_CannyTest::prepare_to_validation( int )
  236. {
  237. Mat src = test_mat[INPUT][0], dst = test_mat[REF_OUTPUT][0];
  238. test_Canny( src, dst, threshold1, threshold2, aperture_size, use_true_gradient );
  239. }
  240. int CV_CannyTest::validate_test_results( int test_case_idx )
  241. {
  242. int code = cvtest::TS::OK, nz0;
  243. prepare_to_validation(test_case_idx);
  244. double err = cvtest::norm(test_mat[OUTPUT][0], test_mat[REF_OUTPUT][0], CV_L1);
  245. if( err == 0 )
  246. return code;
  247. if( err != cvRound(err) || cvRound(err)%255 != 0 )
  248. {
  249. ts->printf( cvtest::TS::LOG, "Some of the pixels, produced by Canny, are not 0's or 255's; the difference is %g\n", err );
  250. ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
  251. return code;
  252. }
  253. nz0 = cvRound(cvtest::norm(test_mat[REF_OUTPUT][0], CV_L1)/255);
  254. err = (err/255/MAX(nz0,100))*100;
  255. if( err > 1 )
  256. {
  257. ts->printf( cvtest::TS::LOG, "Too high percentage of non-matching edge pixels = %g%%\n", err);
  258. ts->set_failed_test_info( cvtest::TS::FAIL_BAD_ACCURACY );
  259. }
  260. return code;
  261. }
  262. TEST(Imgproc_Canny, accuracy) { CV_CannyTest test; test.safe_run(); }
  263. TEST(Imgproc_Canny, accuracy_deriv) { CV_CannyTest test(true); test.safe_run(); }
  264. /*
  265. * Comparing OpenVX based implementation with the main one
  266. */
  267. #ifndef IMPLEMENT_PARAM_CLASS
  268. #define IMPLEMENT_PARAM_CLASS(name, type) \
  269. class name \
  270. { \
  271. public: \
  272. name ( type arg = type ()) : val_(arg) {} \
  273. operator type () const {return val_;} \
  274. private: \
  275. type val_; \
  276. }; \
  277. inline void PrintTo( name param, std::ostream* os) \
  278. { \
  279. *os << #name << "(" << testing::PrintToString(static_cast< type >(param)) << ")"; \
  280. }
  281. #endif // IMPLEMENT_PARAM_CLASS
  282. IMPLEMENT_PARAM_CLASS(ImagePath, string)
  283. IMPLEMENT_PARAM_CLASS(ApertureSize, int)
  284. IMPLEMENT_PARAM_CLASS(L2gradient, bool)
  285. PARAM_TEST_CASE(CannyVX, ImagePath, ApertureSize, L2gradient)
  286. {
  287. string imgPath;
  288. int kSize;
  289. bool useL2;
  290. Mat src, dst;
  291. virtual void SetUp()
  292. {
  293. imgPath = GET_PARAM(0);
  294. kSize = GET_PARAM(1);
  295. useL2 = GET_PARAM(2);
  296. }
  297. void loadImage()
  298. {
  299. src = cv::imread(cvtest::TS::ptr()->get_data_path() + imgPath, IMREAD_GRAYSCALE);
  300. ASSERT_FALSE(src.empty()) << "can't load image: " << imgPath;
  301. }
  302. };
  303. TEST_P(CannyVX, Accuracy)
  304. {
  305. if(haveOpenVX())
  306. {
  307. loadImage();
  308. setUseOpenVX(false);
  309. Mat canny;
  310. cv::Canny(src, canny, 100, 150, 3);
  311. setUseOpenVX(true);
  312. Mat cannyVX;
  313. cv::Canny(src, cannyVX, 100, 150, 3);
  314. // 'smart' diff check (excluding isolated pixels)
  315. Mat diff, diff1;
  316. absdiff(canny, cannyVX, diff);
  317. boxFilter(diff, diff1, -1, Size(3,3));
  318. const int minPixelsAroud = 3; // empirical number
  319. diff1 = diff1 > 255/9 * minPixelsAroud;
  320. erode(diff1, diff1, Mat());
  321. double error = cv::norm(diff1, NORM_L1) / 255;
  322. const int maxError = std::min(10, diff.size().area()/100); // empirical number
  323. if(error > maxError)
  324. {
  325. string outPath =
  326. string("CannyVX-diff-") +
  327. imgPath + '-' +
  328. 'k' + char(kSize+'0') + '-' +
  329. (useL2 ? "l2" : "l1");
  330. std::replace(outPath.begin(), outPath.end(), '/', '_');
  331. std::replace(outPath.begin(), outPath.end(), '\\', '_');
  332. std::replace(outPath.begin(), outPath.end(), '.', '_');
  333. imwrite(outPath+".png", diff);
  334. }
  335. ASSERT_LE(error, maxError);
  336. }
  337. }
  338. INSTANTIATE_TEST_CASE_P(
  339. ImgProc, CannyVX,
  340. testing::Combine(
  341. testing::Values(
  342. string("shared/baboon.png"),
  343. string("shared/fruits.png"),
  344. string("shared/lena.png"),
  345. string("shared/pic1.png"),
  346. string("shared/pic3.png"),
  347. string("shared/pic5.png"),
  348. string("shared/pic6.png")
  349. ),
  350. testing::Values(ApertureSize(3), ApertureSize(5)),
  351. testing::Values(L2gradient(false), L2gradient(true))
  352. )
  353. );
  354. }} // namespace
  355. /* End of file. */