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