test_canny.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  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. static void Canny_reference_follow( int x, int y, float lowThreshold, const Mat& mag, Mat& dst )
  44. {
  45. static const int ofs[][2] = {{1,0},{1,-1},{0,-1},{-1,-1},{-1,0},{-1,1},{0,1},{1,1}};
  46. int i;
  47. dst.at<uchar>(y, x) = (uchar)255;
  48. for( i = 0; i < 8; i++ )
  49. {
  50. int x1 = x + ofs[i][0];
  51. int y1 = y + ofs[i][1];
  52. if( (unsigned)x1 < (unsigned)mag.cols &&
  53. (unsigned)y1 < (unsigned)mag.rows &&
  54. mag.at<float>(y1, x1) > lowThreshold &&
  55. !dst.at<uchar>(y1, x1) )
  56. Canny_reference_follow( x1, y1, lowThreshold, mag, dst );
  57. }
  58. }
  59. static void Canny_reference( const Mat& src, Mat& dst,
  60. double threshold1, double threshold2,
  61. int aperture_size, bool use_true_gradient )
  62. {
  63. dst.create(src.size(), src.type());
  64. int m = aperture_size;
  65. Point anchor(m/2, m/2);
  66. const double tan_pi_8 = tan(CV_PI/8.);
  67. const double tan_3pi_8 = tan(CV_PI*3/8);
  68. float lowThreshold = (float)MIN(threshold1, threshold2);
  69. float highThreshold = (float)MAX(threshold1, threshold2);
  70. int x, y, width = src.cols, height = src.rows;
  71. Mat dxkernel = cvtest::calcSobelKernel2D( 1, 0, m, 0 );
  72. Mat dykernel = cvtest::calcSobelKernel2D( 0, 1, m, 0 );
  73. Mat dx, dy, mag(height, width, CV_32F);
  74. cvtest::filter2D(src, dx, CV_32S, dxkernel, anchor, 0, BORDER_REPLICATE);
  75. cvtest::filter2D(src, dy, CV_32S, dykernel, anchor, 0, BORDER_REPLICATE);
  76. // calc gradient magnitude
  77. for( y = 0; y < height; y++ )
  78. {
  79. for( x = 0; x < width; x++ )
  80. {
  81. int dxval = dx.at<int>(y, x), dyval = dy.at<int>(y, x);
  82. mag.at<float>(y, x) = use_true_gradient ?
  83. (float)sqrt((double)(dxval*dxval + dyval*dyval)) :
  84. (float)(fabs((double)dxval) + fabs((double)dyval));
  85. }
  86. }
  87. // calc gradient direction, do nonmaxima suppression
  88. for( y = 0; y < height; y++ )
  89. {
  90. for( x = 0; x < width; x++ )
  91. {
  92. float a = mag.at<float>(y, x), b = 0, c = 0;
  93. int y1 = 0, y2 = 0, x1 = 0, x2 = 0;
  94. if( a <= lowThreshold )
  95. continue;
  96. int dxval = dx.at<int>(y, x);
  97. int dyval = dy.at<int>(y, x);
  98. double tg = dxval ? (double)dyval/dxval : DBL_MAX*CV_SIGN(dyval);
  99. if( fabs(tg) < tan_pi_8 )
  100. {
  101. y1 = y2 = y; x1 = x + 1; x2 = x - 1;
  102. }
  103. else if( tan_pi_8 <= tg && tg <= tan_3pi_8 )
  104. {
  105. y1 = y + 1; y2 = y - 1; x1 = x + 1; x2 = x - 1;
  106. }
  107. else if( -tan_3pi_8 <= tg && tg <= -tan_pi_8 )
  108. {
  109. y1 = y - 1; y2 = y + 1; x1 = x + 1; x2 = x - 1;
  110. }
  111. else
  112. {
  113. CV_Assert( fabs(tg) > tan_3pi_8 );
  114. x1 = x2 = x; y1 = y + 1; y2 = y - 1;
  115. }
  116. if( (unsigned)y1 < (unsigned)height && (unsigned)x1 < (unsigned)width )
  117. b = (float)fabs(mag.at<float>(y1, x1));
  118. if( (unsigned)y2 < (unsigned)height && (unsigned)x2 < (unsigned)width )
  119. c = (float)fabs(mag.at<float>(y2, x2));
  120. if( (a > b || (a == b && ((x1 == x+1 && y1 == y) || (x1 == x && y1 == y+1)))) && a > c )
  121. ;
  122. else
  123. mag.at<float>(y, x) = -a;
  124. }
  125. }
  126. dst = Scalar::all(0);
  127. // hysteresis threshold
  128. for( y = 0; y < height; y++ )
  129. {
  130. for( x = 0; x < width; x++ )
  131. if( mag.at<float>(y, x) > highThreshold && !dst.at<uchar>(y, x) )
  132. Canny_reference_follow( x, y, lowThreshold, mag, dst );
  133. }
  134. }
  135. //==============================================================================
  136. // aperture, true gradient
  137. typedef testing::TestWithParam<testing::tuple<int, bool>> Canny_Modes;
  138. TEST_P(Canny_Modes, accuracy)
  139. {
  140. const int aperture = get<0>(GetParam());
  141. const bool trueGradient = get<1>(GetParam());
  142. const double range = aperture == 3 ? 300. : 1000.;
  143. RNG & rng = TS::ptr()->get_rng();
  144. for (int ITER = 0; ITER < 20; ++ITER)
  145. {
  146. SCOPED_TRACE(cv::format("iteration %d", ITER));
  147. const std::string fname = cvtest::findDataFile("shared/fruits.png");
  148. const Mat original = cv::imread(fname, IMREAD_GRAYSCALE);
  149. const double thresh1 = rng.uniform(0., range);
  150. const double thresh2 = rng.uniform(0., range * 0.3);
  151. const Size sz(rng.uniform(127, 800), rng.uniform(127, 600));
  152. const Size osz = original.size();
  153. // preparation
  154. Mat img;
  155. if (sz.width >= osz.width || sz.height >= osz.height)
  156. {
  157. // larger image -> scale
  158. resize(original, img, sz, 0, 0, INTER_LINEAR_EXACT);
  159. }
  160. else
  161. {
  162. // smaller image -> crop
  163. Point origin(rng.uniform(0, osz.width - sz.width), rng.uniform(0, osz.height - sz.height));
  164. Rect roi(origin, sz);
  165. original(roi).copyTo(img);
  166. }
  167. GaussianBlur(img, img, Size(5, 5), 0);
  168. // regular function
  169. Mat result;
  170. {
  171. cv::Canny(img, result, thresh1, thresh2, aperture, trueGradient);
  172. }
  173. // custom derivatives
  174. Mat customResult;
  175. {
  176. Mat dxkernel = cvtest::calcSobelKernel2D(1, 0, aperture, 0);
  177. Mat dykernel = cvtest::calcSobelKernel2D(0, 1, aperture, 0);
  178. Point anchor(aperture / 2, aperture / 2);
  179. cv::Mat dx, dy;
  180. cvtest::filter2D(img, dx, CV_16S, dxkernel, anchor, 0, BORDER_REPLICATE);
  181. cvtest::filter2D(img, dy, CV_16S, dykernel, anchor, 0, BORDER_REPLICATE);
  182. cv::Canny(dx, dy, customResult, thresh1, thresh2, trueGradient);
  183. }
  184. Mat reference;
  185. Canny_reference(img, reference, thresh1, thresh2, aperture, trueGradient);
  186. EXPECT_MAT_NEAR(result, reference, 0);
  187. EXPECT_MAT_NEAR(customResult, reference, 0);
  188. }
  189. }
  190. INSTANTIATE_TEST_CASE_P(/**/, Canny_Modes,
  191. testing::Combine(
  192. testing::Values(3, 5),
  193. testing::Values(true, false)));
  194. /*
  195. * Comparing OpenVX based implementation with the main one
  196. */
  197. #ifndef IMPLEMENT_PARAM_CLASS
  198. #define IMPLEMENT_PARAM_CLASS(name, type) \
  199. class name \
  200. { \
  201. public: \
  202. name ( type arg = type ()) : val_(arg) {} \
  203. operator type () const {return val_;} \
  204. private: \
  205. type val_; \
  206. }; \
  207. inline void PrintTo( name param, std::ostream* os) \
  208. { \
  209. *os << #name << "(" << testing::PrintToString(static_cast< type >(param)) << ")"; \
  210. }
  211. #endif // IMPLEMENT_PARAM_CLASS
  212. IMPLEMENT_PARAM_CLASS(ImagePath, string)
  213. IMPLEMENT_PARAM_CLASS(ApertureSize, int)
  214. IMPLEMENT_PARAM_CLASS(L2gradient, bool)
  215. PARAM_TEST_CASE(CannyVX, ImagePath, ApertureSize, L2gradient)
  216. {
  217. string imgPath;
  218. int kSize;
  219. bool useL2;
  220. Mat src, dst;
  221. virtual void SetUp()
  222. {
  223. imgPath = GET_PARAM(0);
  224. kSize = GET_PARAM(1);
  225. useL2 = GET_PARAM(2);
  226. }
  227. void loadImage()
  228. {
  229. src = cv::imread(cvtest::TS::ptr()->get_data_path() + imgPath, IMREAD_GRAYSCALE);
  230. ASSERT_FALSE(src.empty()) << "can't load image: " << imgPath;
  231. }
  232. };
  233. TEST_P(CannyVX, Accuracy)
  234. {
  235. if(haveOpenVX())
  236. {
  237. loadImage();
  238. setUseOpenVX(false);
  239. Mat canny;
  240. cv::Canny(src, canny, 100, 150, 3);
  241. setUseOpenVX(true);
  242. Mat cannyVX;
  243. cv::Canny(src, cannyVX, 100, 150, 3);
  244. // 'smart' diff check (excluding isolated pixels)
  245. Mat diff, diff1;
  246. absdiff(canny, cannyVX, diff);
  247. boxFilter(diff, diff1, -1, Size(3,3));
  248. const int minPixelsAroud = 3; // empirical number
  249. diff1 = diff1 > 255/9 * minPixelsAroud;
  250. erode(diff1, diff1, Mat());
  251. double error = cv::norm(diff1, NORM_L1) / 255;
  252. const int maxError = std::min(10, diff.size().area()/100); // empirical number
  253. if(error > maxError)
  254. {
  255. string outPath =
  256. string("CannyVX-diff-") +
  257. imgPath + '-' +
  258. 'k' + char(kSize+'0') + '-' +
  259. (useL2 ? "l2" : "l1");
  260. std::replace(outPath.begin(), outPath.end(), '/', '_');
  261. std::replace(outPath.begin(), outPath.end(), '\\', '_');
  262. std::replace(outPath.begin(), outPath.end(), '.', '_');
  263. imwrite(outPath+".png", diff);
  264. }
  265. ASSERT_LE(error, maxError);
  266. }
  267. }
  268. INSTANTIATE_TEST_CASE_P(
  269. ImgProc, CannyVX,
  270. testing::Combine(
  271. testing::Values(
  272. string("shared/baboon.png"),
  273. string("shared/fruits.png"),
  274. string("shared/lena.png"),
  275. string("shared/pic1.png"),
  276. string("shared/pic3.png"),
  277. string("shared/pic5.png"),
  278. string("shared/pic6.png")
  279. ),
  280. testing::Values(ApertureSize(3), ApertureSize(5)),
  281. testing::Values(L2gradient(false), L2gradient(true))
  282. )
  283. );
  284. }} // namespace
  285. /* End of file. */