1 /*M///////////////////////////////////////////////////////////////////////////////////////
3 // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
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.
10 // Intel License Agreement
11 // For Open Source Computer Vision Library
13 // Copyright (C) 2000, Intel Corporation, all rights reserved.
14 // Copyright (C) 2014, Itseez Inc., all rights reserved.
15 // Third party copyrights are property of their respective owners.
17 // Redistribution and use in source and binary forms, with or without modification,
18 // are permitted provided that the following conditions are met:
20 // * Redistribution's of source code must retain the above copyright notice,
21 // this list of conditions and the following disclaimer.
23 // * Redistribution's in binary form must reproduce the above copyright notice,
24 // this list of conditions and the following disclaimer in the documentation
25 // and/or other materials provided with the distribution.
27 // * The name of Intel Corporation may not be used to endorse or promote products
28 // derived from this software without specific prior written permission.
30 // This software is provided by the copyright holders and contributors "as is" and
31 // any express or implied warranties, including, but not limited to, the implied
32 // warranties of merchantability and fitness for a particular purpose are disclaimed.
33 // In no event shall the Intel Corporation or contributors be liable for any direct,
34 // indirect, incidental, special, exemplary, or consequential damages
35 // (including, but not limited to, procurement of substitute goods or services;
36 // loss of use, data, or profits; or business interruption) however caused
37 // and on any theory of liability, whether in contract, strict liability,
38 // or tort (including negligence or otherwise) arising in any way out of
39 // the use of this software, even if advised of the possibility of such damage.
43 #include "precomp.hpp"
44 #include "opencl_kernels_imgproc.hpp"
45 #include "opencv2/core/hal/intrin.hpp"
48 #include "opencv2/core/openvx/ovx_defs.hpp"
51 #define CV_MALLOC_SIMD128 16
58 static bool ipp_Canny(const Mat& src , const Mat& dx_, const Mat& dy_, Mat& dst, float low, float high, bool L2gradient, int aperture_size)
61 CV_INSTRUMENT_REGION_IPP()
63 #if IPP_DISABLE_PERF_CANNY_MT
64 if(cv::getNumThreads()>1)
68 ::ipp::IwiSize size(dst.cols, dst.rows);
69 IppDataType type = ippiGetDataType(dst.depth());
70 int channels = dst.channels();
71 IppNormType norm = (L2gradient)?ippNormL2:ippNormL1;
73 if(size.width <= 3 || size.height <= 3)
86 ::ipp::IwiImage iwSrcDx;
87 ::ipp::IwiImage iwSrcDy;
88 ::ipp::IwiImage iwDst;
90 ippiGetImage(dx_, iwSrcDx);
91 ippiGetImage(dy_, iwSrcDy);
92 ippiGetImage(dst, iwDst);
94 CV_INSTRUMENT_FUN_IPP(::ipp::iwiFilterCannyDeriv, iwSrcDx, iwSrcDy, iwDst, low, high, ::ipp::IwiFilterCannyDerivParams(norm));
96 catch (::ipp::IwException ex)
105 if(aperture_size == 3)
106 kernel = ippMskSize3x3;
107 else if(aperture_size == 5)
108 kernel = ippMskSize5x5;
114 ::ipp::IwiImage iwSrc;
115 ::ipp::IwiImage iwDst;
117 ippiGetImage(src, iwSrc);
118 ippiGetImage(dst, iwDst);
120 CV_INSTRUMENT_FUN_IPP(::ipp::iwiFilterCanny, iwSrc, iwDst, low, high, ::ipp::IwiFilterCannyParams(ippFilterSobel, kernel, norm), ippBorderRepl);
122 catch (::ipp::IwException)
130 CV_UNUSED(src); CV_UNUSED(dx_); CV_UNUSED(dy_); CV_UNUSED(dst); CV_UNUSED(low); CV_UNUSED(high); CV_UNUSED(L2gradient); CV_UNUSED(aperture_size);
138 template <bool useCustomDeriv>
139 static bool ocl_Canny(InputArray _src, const UMat& dx_, const UMat& dy_, OutputArray _dst, float low_thresh, float high_thresh,
140 int aperture_size, bool L2gradient, int cn, const Size & size)
142 CV_INSTRUMENT_REGION_OPENCL()
146 const ocl::Device &dev = ocl::Device::getDefault();
147 int max_wg_size = (int)dev.maxWorkGroupSize();
150 int lSizeY = max_wg_size / 32;
155 lSizeY = max_wg_size / 16;
162 if (aperture_size == 7)
164 low_thresh = low_thresh / 16.0f;
165 high_thresh = high_thresh / 16.0f;
170 low_thresh = std::min(32767.0f, low_thresh);
171 high_thresh = std::min(32767.0f, high_thresh);
174 low_thresh *= low_thresh;
176 high_thresh *= high_thresh;
178 int low = cvFloor(low_thresh), high = cvFloor(high_thresh);
180 if (!useCustomDeriv &&
181 aperture_size == 3 && !_src.isSubmatrix())
187 Non maxima suppression
191 ocl::Kernel with_sobel("stage1_with_sobel", ocl::imgproc::canny_oclsrc,
192 format("-D WITH_SOBEL -D cn=%d -D TYPE=%s -D convert_floatN=%s -D floatN=%s -D GRP_SIZEX=%d -D GRP_SIZEY=%d%s",
193 cn, ocl::memopTypeToStr(_src.depth()),
194 ocl::convertTypeStr(_src.depth(), CV_32F, cn, cvt),
195 ocl::typeToStr(CV_MAKE_TYPE(CV_32F, cn)),
197 L2gradient ? " -D L2GRAD" : ""));
198 if (with_sobel.empty())
201 UMat src = _src.getUMat();
202 map.create(size, CV_32S);
203 with_sobel.args(ocl::KernelArg::ReadOnly(src),
204 ocl::KernelArg::WriteOnlyNoSize(map),
205 (float) low, (float) high);
207 size_t globalsize[2] = { (size_t)size.width, (size_t)size.height },
208 localsize[2] = { (size_t)lSizeX, (size_t)lSizeY };
210 if (!with_sobel.run(2, globalsize, localsize, false))
216 stage1_without_sobel:
218 Non maxima suppression
222 if (aperture_size == 7)
230 Sobel(_src, dx, CV_16S, 1, 0, aperture_size, scale, 0, BORDER_REPLICATE);
231 Sobel(_src, dy, CV_16S, 0, 1, aperture_size, scale, 0, BORDER_REPLICATE);
239 ocl::Kernel without_sobel("stage1_without_sobel", ocl::imgproc::canny_oclsrc,
240 format("-D WITHOUT_SOBEL -D cn=%d -D GRP_SIZEX=%d -D GRP_SIZEY=%d%s",
241 cn, lSizeX, lSizeY, L2gradient ? " -D L2GRAD" : ""));
242 if (without_sobel.empty())
245 map.create(size, CV_32S);
246 without_sobel.args(ocl::KernelArg::ReadOnlyNoSize(dx), ocl::KernelArg::ReadOnlyNoSize(dy),
247 ocl::KernelArg::WriteOnly(map),
250 size_t globalsize[2] = { (size_t)size.width, (size_t)size.height },
251 localsize[2] = { (size_t)lSizeX, (size_t)lSizeY };
253 if (!without_sobel.run(2, globalsize, localsize, false))
260 hysteresis (add weak edges if they are connected with strong edges)
263 int sizey = lSizeY / PIX_PER_WI;
267 size_t globalsize[2] = { (size_t)size.width, ((size_t)size.height + PIX_PER_WI - 1) / PIX_PER_WI }, localsize[2] = { (size_t)lSizeX, (size_t)sizey };
269 ocl::Kernel edgesHysteresis("stage2_hysteresis", ocl::imgproc::canny_oclsrc,
270 format("-D STAGE2 -D PIX_PER_WI=%d -D LOCAL_X=%d -D LOCAL_Y=%d",
271 PIX_PER_WI, lSizeX, sizey));
273 if (edgesHysteresis.empty())
276 edgesHysteresis.args(ocl::KernelArg::ReadWrite(map));
277 if (!edgesHysteresis.run(2, globalsize, localsize, false))
282 ocl::Kernel getEdgesKernel("getEdges", ocl::imgproc::canny_oclsrc,
283 format("-D GET_EDGES -D PIX_PER_WI=%d", PIX_PER_WI));
284 if (getEdgesKernel.empty())
287 _dst.create(size, CV_8UC1);
288 UMat dst = _dst.getUMat();
290 getEdgesKernel.args(ocl::KernelArg::ReadOnly(map), ocl::KernelArg::WriteOnlyNoSize(dst));
292 return getEdgesKernel.run(2, globalsize, NULL, false);
297 #define CANNY_PUSH(map, stack) *map = 2, stack.push_back(map)
299 #define CANNY_CHECK_SIMD(m, high, map, stack) \
301 CANNY_PUSH(map, stack); \
305 #define CANNY_CHECK(m, high, map, stack) \
307 CANNY_PUSH(map, stack); \
312 class parallelCanny : public ParallelLoopBody
315 parallelCanny(const Mat &_src, Mat &_map, std::deque<uchar*> &borderPeaksParallel,
316 int _low, int _high, int _aperture_size, bool _L2gradient) :
317 src(_src), src2(_src), map(_map), _borderPeaksParallel(borderPeaksParallel),
318 low(_low), high(_high), aperture_size(_aperture_size), L2gradient(_L2gradient)
321 haveSIMD = hasSIMD128();
323 _map.create(src.rows + 2, (int)alignSize((size_t)(src.cols + CV_MALLOC_SIMD128 + 1), CV_MALLOC_SIMD128), CV_8UC1);
326 _map.create(src.rows + 2, src.cols + 2, CV_8UC1);
329 map.row(src.rows + 1).setTo(1);
335 parallelCanny(const Mat &_dx, const Mat &_dy, Mat &_map, std::deque<uchar*> &borderPeaksParallel,
336 int _low, int _high, bool _L2gradient) :
337 src(_dx), src2(_dy), map(_map), _borderPeaksParallel(borderPeaksParallel),
338 low(_low), high(_high), aperture_size(0), L2gradient(_L2gradient)
341 haveSIMD = hasSIMD128();
343 _map.create(src.rows + 2, (int)alignSize((size_t)(src.cols + CV_MALLOC_SIMD128 + 1), CV_MALLOC_SIMD128), CV_8UC1);
346 _map.create(src.rows + 2, src.cols + 2, CV_8UC1);
349 map.row(src.rows + 1).setTo(1);
351 needGradient = false;
357 parallelCanny& operator=(const parallelCanny&) { return *this; }
359 void operator()(const Range &boundaries) const CV_OVERRIDE
364 AutoBuffer<short> dxMax(0), dyMax(0);
365 std::deque<uchar*> stack, borderPeaksLocal;
366 const int rowStart = max(0, boundaries.start - 1), rowEnd = min(src.rows, boundaries.end + 1);
367 int *_mag_p, *_mag_a, *_mag_n;
368 short *_dx, *_dy, *_dx_a = NULL, *_dy_a = NULL, *_dx_n = NULL, *_dy_n = NULL;
372 CV_TRACE_REGION("gradient")
375 if (aperture_size == 7)
379 Sobel(src.rowRange(rowStart, rowEnd), dx, CV_16S, 1, 0, aperture_size, scale, 0, BORDER_REPLICATE);
380 Sobel(src.rowRange(rowStart, rowEnd), dy, CV_16S, 0, 1, aperture_size, scale, 0, BORDER_REPLICATE);
384 dx = src.rowRange(rowStart, rowEnd);
385 dy = src2.rowRange(rowStart, rowEnd);
388 CV_TRACE_REGION_NEXT("magnitude");
391 dxMax.allocate(2 * dx.cols);
392 dyMax.allocate(2 * dy.cols);
393 _dx_a = (short*)dxMax;
394 _dx_n = _dx_a + dx.cols;
395 _dy_a = (short*)dyMax;
396 _dy_n = _dy_a + dy.cols;
399 // _mag_p: previous row, _mag_a: actual row, _mag_n: next row
401 AutoBuffer<int> buffer(3 * (mapstep * cn + CV_MALLOC_SIMD128));
402 _mag_p = alignPtr((int*)buffer + 1, CV_MALLOC_SIMD128);
403 _mag_a = alignPtr(_mag_p + mapstep * cn, CV_MALLOC_SIMD128);
404 _mag_n = alignPtr(_mag_a + mapstep * cn, CV_MALLOC_SIMD128);
406 AutoBuffer<int> buffer(3 * (mapstep * cn));
407 _mag_p = (int*)buffer + 1;
408 _mag_a = _mag_p + mapstep * cn;
409 _mag_n = _mag_a + mapstep * cn;
412 // For the first time when just 2 rows are filled and for left and right borders
413 if(rowStart == boundaries.start)
414 memset(_mag_n - 1, 0, mapstep * sizeof(int));
416 _mag_n[src.cols] = _mag_n[-1] = 0;
418 _mag_a[src.cols] = _mag_a[-1] = _mag_p[src.cols] = _mag_p[-1] = 0;
420 // calculate magnitude and angle of gradient, perform non-maxima suppression.
421 // fill the map with one of the following values:
422 // 0 - the pixel might belong to an edge
423 // 1 - the pixel can not belong to an edge
424 // 2 - the pixel does belong to an edge
425 for (int i = rowStart; i <= boundaries.end; ++i)
427 // Scroll the ring buffer
428 std::swap(_mag_n, _mag_a);
429 std::swap(_mag_n, _mag_p);
433 // Next row calculation
434 _dx = dx.ptr<short>(i - rowStart);
435 _dy = dy.ptr<short>(i - rowStart);
439 int j = 0, width = src.cols * cn;
443 for ( ; j <= width - 8; j += 8)
445 v_int16x8 v_dx = v_load((const short*)(_dx + j));
446 v_int16x8 v_dy = v_load((const short*)(_dy + j));
448 v_int32x4 v_dxp_low, v_dxp_high;
449 v_int32x4 v_dyp_low, v_dyp_high;
450 v_expand(v_dx, v_dxp_low, v_dxp_high);
451 v_expand(v_dy, v_dyp_low, v_dyp_high);
453 v_store_aligned((int *)(_mag_n + j), v_dxp_low*v_dxp_low+v_dyp_low*v_dyp_low);
454 v_store_aligned((int *)(_mag_n + j + 4), v_dxp_high*v_dxp_high+v_dyp_high*v_dyp_high);
458 for ( ; j < width; ++j)
459 _mag_n[j] = int(_dx[j])*_dx[j] + int(_dy[j])*_dy[j];
463 int j = 0, width = src.cols * cn;
467 for(; j <= width - 8; j += 8)
469 v_int16x8 v_dx = v_load((const short *)(_dx + j));
470 v_int16x8 v_dy = v_load((const short *)(_dy + j));
472 v_dx = v_reinterpret_as_s16(v_abs(v_dx));
473 v_dy = v_reinterpret_as_s16(v_abs(v_dy));
475 v_int32x4 v_dx_ml, v_dy_ml, v_dx_mh, v_dy_mh;
476 v_expand(v_dx, v_dx_ml, v_dx_mh);
477 v_expand(v_dy, v_dy_ml, v_dy_mh);
479 v_store_aligned((int *)(_mag_n + j), v_dx_ml + v_dy_ml);
480 v_store_aligned((int *)(_mag_n + j + 4), v_dx_mh + v_dy_mh);
484 for ( ; j < width; ++j)
485 _mag_n[j] = std::abs(int(_dx[j])) + std::abs(int(_dy[j]));
490 std::swap(_dx_n, _dx_a);
491 std::swap(_dy_n, _dy_a);
493 for(int j = 0, jn = 0; j < src.cols; ++j, jn += cn)
496 for(int k = 1; k < cn; ++k)
497 if(_mag_n[jn + k] > _mag_n[maxIdx]) maxIdx = jn + k;
499 _mag_n[j] = _mag_n[maxIdx];
500 _dx_n[j] = _dx[maxIdx];
501 _dy_n[j] = _dy[maxIdx];
504 _mag_n[src.cols] = 0;
507 // at the very beginning we do not have a complete ring
508 // buffer of 3 magnitude rows for non-maxima suppression
509 if (i <= boundaries.start)
514 memset(_mag_n - 1, 0, mapstep * sizeof(int));
518 std::swap(_dx_n, _dx_a);
519 std::swap(_dy_n, _dy_a);
523 // From here actual src row is (i - 1)
524 // Set left and right border to 1
527 _pmap = map.ptr<uchar>(i) + CV_MALLOC_SIMD128;
530 _pmap = map.ptr<uchar>(i) + 1;
532 _pmap[src.cols] =_pmap[-1] = 1;
536 _dx = dx.ptr<short>(i - rowStart - 1);
537 _dy = dy.ptr<short>(i - rowStart - 1);
545 const int TG22 = 13573;
550 const v_int32x4 v_low = v_setall_s32(low);
551 const v_int8x16 v_one = v_setall_s8(1);
553 for (; j <= src.cols - 32; j += 32)
555 v_int32x4 v_m1 = v_load_aligned((const int*)(_mag_a + j));
556 v_int32x4 v_m2 = v_load_aligned((const int*)(_mag_a + j + 4));
557 v_int32x4 v_m3 = v_load_aligned((const int*)(_mag_a + j + 8));
558 v_int32x4 v_m4 = v_load_aligned((const int*)(_mag_a + j + 12));
560 v_int32x4 v_cmp1 = v_m1 > v_low;
561 v_int32x4 v_cmp2 = v_m2 > v_low;
562 v_int32x4 v_cmp3 = v_m3 > v_low;
563 v_int32x4 v_cmp4 = v_m4 > v_low;
565 v_m1 = v_load_aligned((const int*)(_mag_a + j + 16));
566 v_m2 = v_load_aligned((const int*)(_mag_a + j + 20));
567 v_m3 = v_load_aligned((const int*)(_mag_a + j + 24));
568 v_m4 = v_load_aligned((const int*)(_mag_a + j + 28));
570 v_store_aligned((signed char*)(_pmap + j), v_one);
571 v_store_aligned((signed char*)(_pmap + j + 16), v_one);
573 v_int16x8 v_cmp80 = v_pack(v_cmp1, v_cmp2);
574 v_int16x8 v_cmp81 = v_pack(v_cmp3, v_cmp4);
576 v_cmp1 = v_m1 > v_low;
577 v_cmp2 = v_m2 > v_low;
578 v_cmp3 = v_m3 > v_low;
579 v_cmp4 = v_m4 > v_low;
581 v_int8x16 v_cmp = v_pack(v_cmp80, v_cmp81);
583 v_cmp80 = v_pack(v_cmp1, v_cmp2);
584 v_cmp81 = v_pack(v_cmp3, v_cmp4);
586 unsigned int mask = v_signmask(v_cmp);
588 v_cmp = v_pack(v_cmp80, v_cmp81);
589 mask |= v_signmask(v_cmp) << 16;
597 int l = trailingZeros32(mask);
604 int x = (int)std::abs(xs);
605 int y = (int)std::abs(ys) << 15;
607 int tg22x = x * TG22;
611 if (m > _mag_a[k - 1] && m >= _mag_a[k + 1])
613 CANNY_CHECK_SIMD(m, high, (_pmap+k), stack);
618 int tg67x = tg22x + (x << 16);
621 if (m > _mag_p[k] && m >= _mag_n[k])
623 CANNY_CHECK_SIMD(m, high, (_pmap+k), stack);
628 int s = (xs ^ ys) < 0 ? -1 : 1;
629 if(m > _mag_p[k - s] && m > _mag_n[k + s])
631 CANNY_CHECK_SIMD(m, high, (_pmap+k), stack);
636 } while((mask >>= 1));
640 if (j <= src.cols - 16)
642 v_int32x4 v_m1 = v_load_aligned((const int*)(_mag_a + j));
643 v_int32x4 v_m2 = v_load_aligned((const int*)(_mag_a + j + 4));
644 v_int32x4 v_m3 = v_load_aligned((const int*)(_mag_a + j + 8));
645 v_int32x4 v_m4 = v_load_aligned((const int*)(_mag_a + j + 12));
647 v_store_aligned((signed char*)(_pmap + j), v_one);
649 v_int32x4 v_cmp1 = v_m1 > v_low;
650 v_int32x4 v_cmp2 = v_m2 > v_low;
651 v_int32x4 v_cmp3 = v_m3 > v_low;
652 v_int32x4 v_cmp4 = v_m4 > v_low;
654 v_int16x8 v_cmp80 = v_pack(v_cmp1, v_cmp2);
655 v_int16x8 v_cmp81 = v_pack(v_cmp3, v_cmp4);
657 v_int8x16 v_cmp = v_pack(v_cmp80, v_cmp81);
658 unsigned int mask = v_signmask(v_cmp);
666 int l = trailingZeros32(mask);
673 int x = (int)std::abs(xs);
674 int y = (int)std::abs(ys) << 15;
676 int tg22x = x * TG22;
680 if (m > _mag_a[k - 1] && m >= _mag_a[k + 1])
682 CANNY_CHECK_SIMD(m, high, (_pmap+k), stack);
687 int tg67x = tg22x + (x << 16);
690 if (m > _mag_p[k] && m >= _mag_n[k])
692 CANNY_CHECK_SIMD(m, high, (_pmap+k), stack);
697 int s = (xs ^ ys) < 0 ? -1 : 1;
698 if(m > _mag_p[k - s] && m > _mag_n[k + s])
700 CANNY_CHECK_SIMD(m, high, (_pmap+k), stack);
705 } while((mask >>= 1));
711 for (; j < src.cols; j++)
719 int x = (int)std::abs(xs);
720 int y = (int)std::abs(ys) << 15;
722 int tg22x = x * TG22;
726 if (m > _mag_a[j - 1] && m >= _mag_a[j + 1])
728 CANNY_CHECK(m, high, (_pmap+j), stack);
733 int tg67x = tg22x + (x << 16);
736 if (m > _mag_p[j] && m >= _mag_n[j])
738 CANNY_CHECK(m, high, (_pmap+j), stack);
743 int s = (xs ^ ys) < 0 ? -1 : 1;
744 if(m > _mag_p[j - s] && m > _mag_n[j + s])
746 CANNY_CHECK(m, high, (_pmap+j), stack);
755 // Not for first row of first slice or last row of last slice
756 uchar *pmapLower = (rowStart == 0) ? map.data : (map.data + (boundaries.start + 2) * mapstep);
757 uint pmapDiff = (uint)(((rowEnd == src.rows) ? map.datalimit : (map.data + boundaries.end * mapstep)) - pmapLower);
759 // now track the edges (hysteresis thresholding)
760 CV_TRACE_REGION_NEXT("hysteresis");
761 while (!stack.empty())
763 uchar *m = stack.back();
766 // Stops thresholding from expanding to other slices by sending pixels in the borders of each
767 // slice in a queue to be serially processed later.
768 if((unsigned)(m - pmapLower) < pmapDiff)
770 if (!m[-mapstep-1]) CANNY_PUSH((m-mapstep-1), stack);
771 if (!m[-mapstep]) CANNY_PUSH((m-mapstep), stack);
772 if (!m[-mapstep+1]) CANNY_PUSH((m-mapstep+1), stack);
773 if (!m[-1]) CANNY_PUSH((m-1), stack);
774 if (!m[1]) CANNY_PUSH((m+1), stack);
775 if (!m[mapstep-1]) CANNY_PUSH((m+mapstep-1), stack);
776 if (!m[mapstep]) CANNY_PUSH((m+mapstep), stack);
777 if (!m[mapstep+1]) CANNY_PUSH((m+mapstep+1), stack);
781 borderPeaksLocal.push_back(m);
782 ptrdiff_t mapstep2 = m < pmapLower ? mapstep : -mapstep;
784 if (!m[-1]) CANNY_PUSH((m-1), stack);
785 if (!m[1]) CANNY_PUSH((m+1), stack);
786 if (!m[mapstep2-1]) CANNY_PUSH((m+mapstep2-1), stack);
787 if (!m[mapstep2]) CANNY_PUSH((m+mapstep2), stack);
788 if (!m[mapstep2+1]) CANNY_PUSH((m+mapstep2+1), stack);
792 if(!borderPeaksLocal.empty())
794 AutoLock lock(mutex);
795 _borderPeaksParallel.insert(_borderPeaksParallel.end(), borderPeaksLocal.begin(), borderPeaksLocal.end());
800 const Mat &src, &src2;
802 std::deque<uchar*> &_borderPeaksParallel;
803 int low, high, aperture_size;
804 bool L2gradient, needGradient;
813 class finalPass : public ParallelLoopBody
817 finalPass(const Mat &_map, Mat &_dst) :
822 haveSIMD = hasSIMD128();
828 void operator()(const Range &boundaries) const CV_OVERRIDE
830 // the final pass, form the final image
831 for (int i = boundaries.start; i < boundaries.end; i++)
834 uchar *pdst = dst.ptr<uchar>(i);
835 const uchar *pmap = map.ptr<uchar>(i + 1);
838 pmap += CV_MALLOC_SIMD128;
844 const v_uint8x16 v_zero = v_setzero_u8();
845 const v_uint8x16 v_ff = ~v_zero;
846 const v_uint8x16 v_two(2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2);
848 for (; j <= dst.cols - 16; j += 16)
850 v_uint8x16 v_pmap = v_load_aligned((const unsigned char*)(pmap + j));
851 v_pmap = v_select(v_pmap == v_two, v_ff, v_zero);
852 v_store((pdst + j), v_pmap);
855 if (j <= dst.cols - 8)
857 v_uint8x16 v_pmap = v_load_low((const unsigned char*)(pmap + j));
858 v_pmap = v_select(v_pmap == v_two, v_ff, v_zero);
859 v_store_low((pdst + j), v_pmap);
864 for (; j < dst.cols; j++)
866 pdst[j] = (uchar)-(pmap[j] >> 1);
878 finalPass(const finalPass&); // = delete
879 finalPass& operator=(const finalPass&); // = delete
884 template <> inline bool skipSmallImages<VX_KERNEL_CANNY_EDGE_DETECTOR>(int w, int h) { return w*h < 640 * 480; }
886 static bool openvx_canny(const Mat& src, Mat& dst, int loVal, int hiVal, int kSize, bool useL2)
890 Context context = ovx::getOpenVXContext();
893 Image _src = Image::createFromHandle(
895 Image::matTypeToFormat(src.type()),
896 Image::createAddressing(src),
898 Image _dst = Image::createFromHandle(
900 Image::matTypeToFormat(dst.type()),
901 Image::createAddressing(dst),
903 Threshold threshold = Threshold::createRange(context, VX_TYPE_UINT8, saturate_cast<uchar>(loVal), saturate_cast<uchar>(hiVal));
906 // the code below is disabled because vxuCannyEdgeDetector()
907 // ignores context attribute VX_CONTEXT_IMMEDIATE_BORDER
909 // FIXME: may fail in multithread case
910 border_t prevBorder = context.immediateBorder();
911 context.setImmediateBorder(VX_BORDER_REPLICATE);
912 IVX_CHECK_STATUS( vxuCannyEdgeDetector(context, _src, threshold, kSize, (useL2 ? VX_NORM_L2 : VX_NORM_L1), _dst) );
913 context.setImmediateBorder(prevBorder);
915 // alternative code without vxuCannyEdgeDetector()
916 Graph graph = Graph::create(context);
917 ivx::Node node = ivx::Node(vxCannyEdgeDetectorNode(graph, _src, threshold, kSize, (useL2 ? VX_NORM_L2 : VX_NORM_L1), _dst) );
918 node.setBorder(VX_BORDER_REPLICATE);
923 #ifdef VX_VERSION_1_1
928 catch(const WrapperError& e)
930 VX_DbgThrow(e.what());
932 catch(const RuntimeError& e)
934 VX_DbgThrow(e.what());
939 #endif // HAVE_OPENVX
941 void Canny( InputArray _src, OutputArray _dst,
942 double low_thresh, double high_thresh,
943 int aperture_size, bool L2gradient )
945 CV_INSTRUMENT_REGION()
947 CV_Assert( _src.depth() == CV_8U );
949 const Size size = _src.size();
951 // we don't support inplace parameters in case with RGB/BGR src
952 CV_Assert((_dst.getObj() != _src.getObj() || _src.type() == CV_8UC1) && "Inplace parameters are not supported");
954 _dst.create(size, CV_8U);
956 if (!L2gradient && (aperture_size & CV_CANNY_L2_GRADIENT) == CV_CANNY_L2_GRADIENT)
958 // backward compatibility
959 aperture_size &= ~CV_CANNY_L2_GRADIENT;
963 if ((aperture_size & 1) == 0 || (aperture_size != -1 && (aperture_size < 3 || aperture_size > 7)))
964 CV_Error(CV_StsBadFlag, "Aperture size should be odd between 3 and 7");
966 if (aperture_size == 7)
968 low_thresh = low_thresh / 16.0;
969 high_thresh = high_thresh / 16.0;
972 if (low_thresh > high_thresh)
973 std::swap(low_thresh, high_thresh);
975 CV_OCL_RUN(_dst.isUMat() && (_src.channels() == 1 || _src.channels() == 3),
976 ocl_Canny<false>(_src, UMat(), UMat(), _dst, (float)low_thresh, (float)high_thresh, aperture_size, L2gradient, _src.channels(), size))
978 Mat src0 = _src.getMat(), dst = _dst.getMat();
979 Mat src(src0.size(), src0.type(), src0.data, src0.step);
981 CALL_HAL(canny, cv_hal_canny, src.data, src.step, dst.data, dst.step, src.cols, src.rows, src.channels(),
982 low_thresh, high_thresh, aperture_size, L2gradient);
985 false && /* disabling due to accuracy issues */
986 src.type() == CV_8UC1 &&
987 !src.isSubmatrix() &&
988 src.cols >= aperture_size &&
989 src.rows >= aperture_size &&
990 !ovx::skipSmallImages<VX_KERNEL_CANNY_EDGE_DETECTOR>(src.cols, src.rows),
995 cvFloor(high_thresh),
999 CV_IPP_RUN_FAST(ipp_Canny(src, Mat(), Mat(), dst, (float)low_thresh, (float)high_thresh, L2gradient, aperture_size))
1003 low_thresh = std::min(32767.0, low_thresh);
1004 high_thresh = std::min(32767.0, high_thresh);
1006 if (low_thresh > 0) low_thresh *= low_thresh;
1007 if (high_thresh > 0) high_thresh *= high_thresh;
1009 int low = cvFloor(low_thresh);
1010 int high = cvFloor(high_thresh);
1012 // If Scharr filter: aperture size is 3, ksize2 is 1
1013 int ksize2 = aperture_size < 0 ? 1 : aperture_size / 2;
1014 // Minimum number of threads should be 1, maximum should not exceed number of CPU's, because of overhead
1015 int numOfThreads = std::max(1, std::min(getNumThreads(), getNumberOfCPUs()));
1016 // Make a fallback for pictures with too few rows.
1017 int grainSize = src.rows / numOfThreads;
1018 int minGrainSize = 2 * (ksize2 + 1);
1019 if (grainSize < minGrainSize)
1020 numOfThreads = std::max(1, src.rows / minGrainSize);
1023 std::deque<uchar*> stack;
1025 parallel_for_(Range(0, src.rows), parallelCanny(src, map, stack, low, high, aperture_size, L2gradient), numOfThreads);
1027 CV_TRACE_REGION("global_hysteresis");
1028 // now track the edges (hysteresis thresholding)
1029 ptrdiff_t mapstep = map.cols;
1031 while (!stack.empty())
1033 uchar* m = stack.back();
1036 if (!m[-mapstep-1]) CANNY_PUSH((m-mapstep-1), stack);
1037 if (!m[-mapstep]) CANNY_PUSH((m-mapstep), stack);
1038 if (!m[-mapstep+1]) CANNY_PUSH((m-mapstep+1), stack);
1039 if (!m[-1]) CANNY_PUSH((m-1), stack);
1040 if (!m[1]) CANNY_PUSH((m+1), stack);
1041 if (!m[mapstep-1]) CANNY_PUSH((m+mapstep-1), stack);
1042 if (!m[mapstep]) CANNY_PUSH((m+mapstep), stack);
1043 if (!m[mapstep+1]) CANNY_PUSH((m+mapstep+1), stack);
1046 CV_TRACE_REGION_NEXT("finalPass");
1047 parallel_for_(Range(0, src.rows), finalPass(map, dst), src.total()/(double)(1<<16));
1050 void Canny( InputArray _dx, InputArray _dy, OutputArray _dst,
1051 double low_thresh, double high_thresh,
1054 CV_INSTRUMENT_REGION()
1056 CV_Assert(_dx.dims() == 2);
1057 CV_Assert(_dx.type() == CV_16SC1 || _dx.type() == CV_16SC3);
1058 CV_Assert(_dy.type() == _dx.type());
1059 CV_Assert(_dx.sameSize(_dy));
1061 if (low_thresh > high_thresh)
1062 std::swap(low_thresh, high_thresh);
1064 const Size size = _dx.size();
1066 CV_OCL_RUN(_dst.isUMat(),
1067 ocl_Canny<true>(UMat(), _dx.getUMat(), _dy.getUMat(), _dst, (float)low_thresh, (float)high_thresh, 0, L2gradient, _dx.channels(), size))
1069 _dst.create(size, CV_8U);
1070 Mat dst = _dst.getMat();
1072 Mat dx = _dx.getMat();
1073 Mat dy = _dy.getMat();
1075 CV_IPP_RUN_FAST(ipp_Canny(Mat(), dx, dy, dst, (float)low_thresh, (float)high_thresh, L2gradient, 0))
1079 low_thresh = std::min(32767.0, low_thresh);
1080 high_thresh = std::min(32767.0, high_thresh);
1082 if (low_thresh > 0) low_thresh *= low_thresh;
1083 if (high_thresh > 0) high_thresh *= high_thresh;
1086 int low = cvFloor(low_thresh);
1087 int high = cvFloor(high_thresh);
1089 std::deque<uchar*> stack;
1092 // Minimum number of threads should be 1, maximum should not exceed number of CPU's, because of overhead
1093 int numOfThreads = std::max(1, std::min(getNumThreads(), getNumberOfCPUs()));
1094 if (dx.rows / numOfThreads < 3)
1095 numOfThreads = std::max(1, dx.rows / 3);
1097 parallel_for_(Range(0, dx.rows), parallelCanny(dx, dy, map, stack, low, high, L2gradient), numOfThreads);
1099 CV_TRACE_REGION("global_hysteresis")
1100 // now track the edges (hysteresis thresholding)
1101 ptrdiff_t mapstep = map.cols;
1103 while (!stack.empty())
1105 uchar* m = stack.back();
1108 if (!m[-mapstep-1]) CANNY_PUSH((m-mapstep-1), stack);
1109 if (!m[-mapstep]) CANNY_PUSH((m-mapstep), stack);
1110 if (!m[-mapstep+1]) CANNY_PUSH((m-mapstep+1), stack);
1111 if (!m[-1]) CANNY_PUSH((m-1), stack);
1112 if (!m[1]) CANNY_PUSH((m+1), stack);
1113 if (!m[mapstep-1]) CANNY_PUSH((m+mapstep-1), stack);
1114 if (!m[mapstep]) CANNY_PUSH((m+mapstep), stack);
1115 if (!m[mapstep+1]) CANNY_PUSH((m+mapstep+1), stack);
1118 CV_TRACE_REGION_NEXT("finalPass");
1119 parallel_for_(Range(0, dx.rows), finalPass(map, dst), dx.total()/(double)(1<<16));
1124 void cvCanny( const CvArr* image, CvArr* edges, double threshold1,
1125 double threshold2, int aperture_size )
1127 cv::Mat src = cv::cvarrToMat(image), dst = cv::cvarrToMat(edges);
1128 CV_Assert( src.size == dst.size && src.depth() == CV_8U && dst.type() == CV_8U );
1130 cv::Canny(src, dst, threshold1, threshold2, aperture_size & 255,
1131 (aperture_size & CV_CANNY_L2_GRADIENT) != 0);