Path: blob/master/modules/imgproc/test/test_canny.cpp
16344 views
/*M///////////////////////////////////////////////////////////////////////////////////////1//2// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.3//4// By downloading, copying, installing or using the software you agree to this license.5// If you do not agree to this license, do not download, install,6// copy or use the software.7//8//9// Intel License Agreement10// For Open Source Computer Vision Library11//12// Copyright (C) 2000, Intel Corporation, all rights reserved.13// Third party copyrights are property of their respective owners.14//15// Redistribution and use in source and binary forms, with or without modification,16// are permitted provided that the following conditions are met:17//18// * Redistribution's of source code must retain the above copyright notice,19// this list of conditions and the following disclaimer.20//21// * Redistribution's in binary form must reproduce the above copyright notice,22// this list of conditions and the following disclaimer in the documentation23// and/or other materials provided with the distribution.24//25// * The name of Intel Corporation may not be used to endorse or promote products26// derived from this software without specific prior written permission.27//28// This software is provided by the copyright holders and contributors "as is" and29// any express or implied warranties, including, but not limited to, the implied30// warranties of merchantability and fitness for a particular purpose are disclaimed.31// In no event shall the Intel Corporation or contributors be liable for any direct,32// indirect, incidental, special, exemplary, or consequential damages33// (including, but not limited to, procurement of substitute goods or services;34// loss of use, data, or profits; or business interruption) however caused35// and on any theory of liability, whether in contract, strict liability,36// or tort (including negligence or otherwise) arising in any way out of37// the use of this software, even if advised of the possibility of such damage.38//39//M*/4041#include "test_precomp.hpp"4243namespace opencv_test { namespace {4445class CV_CannyTest : public cvtest::ArrayTest46{47public:48CV_CannyTest(bool custom_deriv = false);4950protected:51void get_test_array_types_and_sizes( int test_case_idx, vector<vector<Size> >& sizes, vector<vector<int> >& types );52double get_success_error_level( int test_case_idx, int i, int j );53int prepare_test_case( int test_case_idx );54void run_func();55void prepare_to_validation( int );56int validate_test_results( int /*test_case_idx*/ );5758int aperture_size;59bool use_true_gradient;60double threshold1, threshold2;61bool test_cpp;62bool test_custom_deriv;6364Mat img;65};666768CV_CannyTest::CV_CannyTest(bool custom_deriv)69{70test_array[INPUT].push_back(NULL);71test_array[OUTPUT].push_back(NULL);72test_array[REF_OUTPUT].push_back(NULL);73element_wise_relative_error = true;74aperture_size = 0;75use_true_gradient = false;76threshold1 = threshold2 = 0;7778test_cpp = false;79test_custom_deriv = custom_deriv;8081const char imgPath[] = "shared/fruits.png";82img = cv::imread(cvtest::TS::ptr()->get_data_path() + imgPath, IMREAD_GRAYSCALE);83}848586void CV_CannyTest::get_test_array_types_and_sizes( int test_case_idx,87vector<vector<Size> >& sizes,88vector<vector<int> >& types )89{90RNG& rng = ts->get_rng();91double thresh_range;9293cvtest::ArrayTest::get_test_array_types_and_sizes( test_case_idx, sizes, types );94types[INPUT][0] = types[OUTPUT][0] = types[REF_OUTPUT][0] = CV_8U;9596aperture_size = cvtest::randInt(rng) % 2 ? 5 : 3;97thresh_range = aperture_size == 3 ? 300 : 1000;9899threshold1 = cvtest::randReal(rng)*thresh_range;100threshold2 = cvtest::randReal(rng)*thresh_range*0.3;101102if( cvtest::randInt(rng) % 2 )103CV_SWAP( threshold1, threshold2, thresh_range );104105use_true_gradient = cvtest::randInt(rng) % 2 != 0;106test_cpp = (cvtest::randInt(rng) & 256) == 0;107108ts->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",109sizes[0][0].width, sizes[0][0].height, aperture_size, threshold1, threshold2, use_true_gradient ? "TRUE" : "FALSE", test_cpp ? "TRUE" : "FALSE", test_case_idx);110}111112113int CV_CannyTest::prepare_test_case( int test_case_idx )114{115int code = cvtest::ArrayTest::prepare_test_case( test_case_idx );116if( code > 0 )117{118RNG& rng = ts->get_rng();119Mat& src = test_mat[INPUT][0];120//GaussianBlur(src, src, Size(11, 11), 5, 5);121if(src.cols > img.cols || src.rows > img.rows)122resize(img, src, src.size(), 0, 0, INTER_LINEAR_EXACT);123else124img(125Rect(126cvtest::randInt(rng) % (img.cols-src.cols),127cvtest::randInt(rng) % (img.rows-src.rows),128src.cols,129src.rows130)131).copyTo(src);132GaussianBlur(src, src, Size(5, 5), 0);133}134135return code;136}137138139double CV_CannyTest::get_success_error_level( int /*test_case_idx*/, int /*i*/, int /*j*/ )140{141return 0;142}143144145void CV_CannyTest::run_func()146{147if (test_custom_deriv)148{149cv::Mat _out = cv::cvarrToMat(test_array[OUTPUT][0]);150cv::Mat src = cv::cvarrToMat(test_array[INPUT][0]);151cv::Mat dx, dy;152int m = aperture_size;153Point anchor(m/2, m/2);154Mat dxkernel = cvtest::calcSobelKernel2D( 1, 0, m, 0 );155Mat dykernel = cvtest::calcSobelKernel2D( 0, 1, m, 0 );156cvtest::filter2D(src, dx, CV_16S, dxkernel, anchor, 0, BORDER_REPLICATE);157cvtest::filter2D(src, dy, CV_16S, dykernel, anchor, 0, BORDER_REPLICATE);158cv::Canny(dx, dy, _out, threshold1, threshold2, use_true_gradient);159}160else if(!test_cpp)161{162cvCanny( test_array[INPUT][0], test_array[OUTPUT][0], threshold1, threshold2,163aperture_size + (use_true_gradient ? CV_CANNY_L2_GRADIENT : 0));164}165else166{167cv::Mat _out = cv::cvarrToMat(test_array[OUTPUT][0]);168cv::Canny(cv::cvarrToMat(test_array[INPUT][0]), _out, threshold1, threshold2,169aperture_size + (use_true_gradient ? CV_CANNY_L2_GRADIENT : 0));170}171}172173174static void175cannyFollow( int x, int y, float lowThreshold, const Mat& mag, Mat& dst )176{177static const int ofs[][2] = {{1,0},{1,-1},{0,-1},{-1,-1},{-1,0},{-1,1},{0,1},{1,1}};178int i;179180dst.at<uchar>(y, x) = (uchar)255;181182for( i = 0; i < 8; i++ )183{184int x1 = x + ofs[i][0];185int y1 = y + ofs[i][1];186if( (unsigned)x1 < (unsigned)mag.cols &&187(unsigned)y1 < (unsigned)mag.rows &&188mag.at<float>(y1, x1) > lowThreshold &&189!dst.at<uchar>(y1, x1) )190cannyFollow( x1, y1, lowThreshold, mag, dst );191}192}193194195static void196test_Canny( const Mat& src, Mat& dst,197double threshold1, double threshold2,198int aperture_size, bool use_true_gradient )199{200int m = aperture_size;201Point anchor(m/2, m/2);202const double tan_pi_8 = tan(CV_PI/8.);203const double tan_3pi_8 = tan(CV_PI*3/8);204float lowThreshold = (float)MIN(threshold1, threshold2);205float highThreshold = (float)MAX(threshold1, threshold2);206207int x, y, width = src.cols, height = src.rows;208209Mat dxkernel = cvtest::calcSobelKernel2D( 1, 0, m, 0 );210Mat dykernel = cvtest::calcSobelKernel2D( 0, 1, m, 0 );211Mat dx, dy, mag(height, width, CV_32F);212cvtest::filter2D(src, dx, CV_32S, dxkernel, anchor, 0, BORDER_REPLICATE);213cvtest::filter2D(src, dy, CV_32S, dykernel, anchor, 0, BORDER_REPLICATE);214215// calc gradient magnitude216for( y = 0; y < height; y++ )217{218for( x = 0; x < width; x++ )219{220int dxval = dx.at<int>(y, x), dyval = dy.at<int>(y, x);221mag.at<float>(y, x) = use_true_gradient ?222(float)sqrt((double)(dxval*dxval + dyval*dyval)) :223(float)(fabs((double)dxval) + fabs((double)dyval));224}225}226227// calc gradient direction, do nonmaxima suppression228for( y = 0; y < height; y++ )229{230for( x = 0; x < width; x++ )231{232233float a = mag.at<float>(y, x), b = 0, c = 0;234int y1 = 0, y2 = 0, x1 = 0, x2 = 0;235236if( a <= lowThreshold )237continue;238239int dxval = dx.at<int>(y, x);240int dyval = dy.at<int>(y, x);241242double tg = dxval ? (double)dyval/dxval : DBL_MAX*CV_SIGN(dyval);243244if( fabs(tg) < tan_pi_8 )245{246y1 = y2 = y; x1 = x + 1; x2 = x - 1;247}248else if( tan_pi_8 <= tg && tg <= tan_3pi_8 )249{250y1 = y + 1; y2 = y - 1; x1 = x + 1; x2 = x - 1;251}252else if( -tan_3pi_8 <= tg && tg <= -tan_pi_8 )253{254y1 = y - 1; y2 = y + 1; x1 = x + 1; x2 = x - 1;255}256else257{258assert( fabs(tg) > tan_3pi_8 );259x1 = x2 = x; y1 = y + 1; y2 = y - 1;260}261262if( (unsigned)y1 < (unsigned)height && (unsigned)x1 < (unsigned)width )263b = (float)fabs(mag.at<float>(y1, x1));264265if( (unsigned)y2 < (unsigned)height && (unsigned)x2 < (unsigned)width )266c = (float)fabs(mag.at<float>(y2, x2));267268if( (a > b || (a == b && ((x1 == x+1 && y1 == y) || (x1 == x && y1 == y+1)))) && a > c )269;270else271mag.at<float>(y, x) = -a;272}273}274275dst = Scalar::all(0);276277// hysteresis threshold278for( y = 0; y < height; y++ )279{280for( x = 0; x < width; x++ )281if( mag.at<float>(y, x) > highThreshold && !dst.at<uchar>(y, x) )282cannyFollow( x, y, lowThreshold, mag, dst );283}284}285286287void CV_CannyTest::prepare_to_validation( int )288{289Mat src = test_mat[INPUT][0], dst = test_mat[REF_OUTPUT][0];290test_Canny( src, dst, threshold1, threshold2, aperture_size, use_true_gradient );291}292293294int CV_CannyTest::validate_test_results( int test_case_idx )295{296int code = cvtest::TS::OK, nz0;297prepare_to_validation(test_case_idx);298299double err = cvtest::norm(test_mat[OUTPUT][0], test_mat[REF_OUTPUT][0], CV_L1);300if( err == 0 )301return code;302303if( err != cvRound(err) || cvRound(err)%255 != 0 )304{305ts->printf( cvtest::TS::LOG, "Some of the pixels, produced by Canny, are not 0's or 255's; the difference is %g\n", err );306ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );307return code;308}309310nz0 = cvRound(cvtest::norm(test_mat[REF_OUTPUT][0], CV_L1)/255);311err = (err/255/MAX(nz0,100))*100;312if( err > 1 )313{314ts->printf( cvtest::TS::LOG, "Too high percentage of non-matching edge pixels = %g%%\n", err);315ts->set_failed_test_info( cvtest::TS::FAIL_BAD_ACCURACY );316}317318return code;319}320321TEST(Imgproc_Canny, accuracy) { CV_CannyTest test; test.safe_run(); }322TEST(Imgproc_Canny, accuracy_deriv) { CV_CannyTest test(true); test.safe_run(); }323324325/*326* Comparing OpenVX based implementation with the main one327*/328329#ifndef IMPLEMENT_PARAM_CLASS330#define IMPLEMENT_PARAM_CLASS(name, type) \331class name \332{ \333public: \334name ( type arg = type ()) : val_(arg) {} \335operator type () const {return val_;} \336private: \337type val_; \338}; \339inline void PrintTo( name param, std::ostream* os) \340{ \341*os << #name << "(" << testing::PrintToString(static_cast< type >(param)) << ")"; \342}343#endif // IMPLEMENT_PARAM_CLASS344345IMPLEMENT_PARAM_CLASS(ImagePath, string)346IMPLEMENT_PARAM_CLASS(ApertureSize, int)347IMPLEMENT_PARAM_CLASS(L2gradient, bool)348349PARAM_TEST_CASE(CannyVX, ImagePath, ApertureSize, L2gradient)350{351string imgPath;352int kSize;353bool useL2;354Mat src, dst;355356virtual void SetUp()357{358imgPath = GET_PARAM(0);359kSize = GET_PARAM(1);360useL2 = GET_PARAM(2);361}362363void loadImage()364{365src = cv::imread(cvtest::TS::ptr()->get_data_path() + imgPath, IMREAD_GRAYSCALE);366ASSERT_FALSE(src.empty()) << "cann't load image: " << imgPath;367}368};369370TEST_P(CannyVX, Accuracy)371{372if(haveOpenVX())373{374loadImage();375376setUseOpenVX(false);377Mat canny;378cv::Canny(src, canny, 100, 150, 3);379380setUseOpenVX(true);381Mat cannyVX;382cv::Canny(src, cannyVX, 100, 150, 3);383384// 'smart' diff check (excluding isolated pixels)385Mat diff, diff1;386absdiff(canny, cannyVX, diff);387boxFilter(diff, diff1, -1, Size(3,3));388const int minPixelsAroud = 3; // empirical number389diff1 = diff1 > 255/9 * minPixelsAroud;390erode(diff1, diff1, Mat());391double error = cv::norm(diff1, NORM_L1) / 255;392const int maxError = std::min(10, diff.size().area()/100); // empirical number393if(error > maxError)394{395string outPath =396string("CannyVX-diff-") +397imgPath + '-' +398'k' + char(kSize+'0') + '-' +399(useL2 ? "l2" : "l1");400std::replace(outPath.begin(), outPath.end(), '/', '_');401std::replace(outPath.begin(), outPath.end(), '\\', '_');402std::replace(outPath.begin(), outPath.end(), '.', '_');403imwrite(outPath+".png", diff);404}405ASSERT_LE(error, maxError);406407}408}409410INSTANTIATE_TEST_CASE_P(411ImgProc, CannyVX,412testing::Combine(413testing::Values(414string("shared/baboon.png"),415string("shared/fruits.png"),416string("shared/lena.png"),417string("shared/pic1.png"),418string("shared/pic3.png"),419string("shared/pic5.png"),420string("shared/pic6.png")421),422testing::Values(ApertureSize(3), ApertureSize(5)),423testing::Values(L2gradient(false), L2gradient(true))424)425);426427}} // namespace428/* End of file. */429430431