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.
11 // For Open Source Computer Vision Library
13 // Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
14 // Copyright (C) 2009, Willow Garage Inc., all rights reserved.
15 // Copyright (C) 2014-2015, Itseez Inc., all rights reserved.
16 // Third party copyrights are property of their respective owners.
18 // Redistribution and use in source and binary forms, with or without modification,
19 // are permitted provided that the following conditions are met:
21 // * Redistribution's of source code must retain the above copyright notice,
22 // this list of conditions and the following disclaimer.
24 // * Redistribution's in binary form must reproduce the above copyright notice,
25 // this list of conditions and the following disclaimer in the documentation
26 // and/or other materials provided with the distribution.
28 // * The name of the copyright holders may not be used to endorse or promote products
29 // derived from this software without specific prior written permission.
31 // This software is provided by the copyright holders and contributors "as is" and
32 // any express or implied warranties, including, but not limited to, the implied
33 // warranties of merchantability and fitness for a particular purpose are disclaimed.
34 // In no event shall the Intel Corporation or contributors be liable for any direct,
35 // indirect, incidental, special, exemplary, or consequential damages
36 // (including, but not limited to, procurement of substitute goods or services;
37 // loss of use, data, or profits; or business interruption) however caused
38 // and on any theory of liability, whether in contract, strict liability,
39 // or tort (including negligence or otherwise) arising in any way out of
40 // the use of this software, even if advised of the possibility of such damage.
44 #include "precomp.hpp"
45 #include "opencv2/core/hal/intrin.hpp"
46 #include "opencl_kernels_imgproc.hpp"
48 #include "opencv2/core/openvx/ovx_defs.hpp"
53 * This file includes the code, contributed by Simon Perreault
54 * (the function icvMedianBlur_8u_O1)
56 * Constant-time median filtering -- http://nomis80.org/ctmf.html
57 * Copyright (C) 2006 Simon Perreault
60 * Laboratoire de vision et systemes numeriques
61 * Pavillon Adrien-Pouliot
63 * Sainte-Foy, Quebec, Canada
66 * perreaul@gel.ulaval.ca
72 /****************************************************************************************\
74 \****************************************************************************************/
76 template<typename T, typename ST>
80 RowSum( int _ksize, int _anchor ) :
87 virtual void operator()(const uchar* src, uchar* dst, int width, int cn)
89 const T* S = (const T*)src;
91 int i = 0, k, ksz_cn = ksize*cn;
93 width = (width - 1)*cn;
96 for( i = 0; i < width + cn; i++ )
98 D[i] = (ST)S[i] + (ST)S[i+cn] + (ST)S[i+cn*2];
101 else if( ksize == 5 )
103 for( i = 0; i < width + cn; i++ )
105 D[i] = (ST)S[i] + (ST)S[i+cn] + (ST)S[i+cn*2] + (ST)S[i + cn*3] + (ST)S[i + cn*4];
111 for( i = 0; i < ksz_cn; i++ )
114 for( i = 0; i < width; i++ )
116 s += (ST)S[i + ksz_cn] - (ST)S[i];
122 ST s0 = 0, s1 = 0, s2 = 0;
123 for( i = 0; i < ksz_cn; i += 3 )
132 for( i = 0; i < width; i += 3 )
134 s0 += (ST)S[i + ksz_cn] - (ST)S[i];
135 s1 += (ST)S[i + ksz_cn + 1] - (ST)S[i + 1];
136 s2 += (ST)S[i + ksz_cn + 2] - (ST)S[i + 2];
144 ST s0 = 0, s1 = 0, s2 = 0, s3 = 0;
145 for( i = 0; i < ksz_cn; i += 4 )
156 for( i = 0; i < width; i += 4 )
158 s0 += (ST)S[i + ksz_cn] - (ST)S[i];
159 s1 += (ST)S[i + ksz_cn + 1] - (ST)S[i + 1];
160 s2 += (ST)S[i + ksz_cn + 2] - (ST)S[i + 2];
161 s3 += (ST)S[i + ksz_cn + 3] - (ST)S[i + 3];
169 for( k = 0; k < cn; k++, S++, D++ )
172 for( i = 0; i < ksz_cn; i += cn )
175 for( i = 0; i < width; i += cn )
177 s += (ST)S[i + ksz_cn] - (ST)S[i];
185 template<typename ST, typename T>
187 public BaseColumnFilter
189 ColumnSum( int _ksize, int _anchor, double _scale ) :
198 virtual void reset() { sumCount = 0; }
200 virtual void operator()(const uchar** src, uchar* dst, int dststep, int count, int width)
204 bool haveScale = scale != 1;
205 double _scale = scale;
207 if( width != (int)sum.size() )
216 memset((void*)SUM, 0, width*sizeof(ST));
218 for( ; sumCount < ksize - 1; sumCount++, src++ )
220 const ST* Sp = (const ST*)src[0];
222 for( i = 0; i < width; i++ )
228 CV_Assert( sumCount == ksize-1 );
232 for( ; count--; src++ )
234 const ST* Sp = (const ST*)src[0];
235 const ST* Sm = (const ST*)src[1-ksize];
239 for( i = 0; i <= width - 2; i += 2 )
241 ST s0 = SUM[i] + Sp[i], s1 = SUM[i+1] + Sp[i+1];
242 D[i] = saturate_cast<T>(s0*_scale);
243 D[i+1] = saturate_cast<T>(s1*_scale);
244 s0 -= Sm[i]; s1 -= Sm[i+1];
245 SUM[i] = s0; SUM[i+1] = s1;
248 for( ; i < width; i++ )
250 ST s0 = SUM[i] + Sp[i];
251 D[i] = saturate_cast<T>(s0*_scale);
257 for( i = 0; i <= width - 2; i += 2 )
259 ST s0 = SUM[i] + Sp[i], s1 = SUM[i+1] + Sp[i+1];
260 D[i] = saturate_cast<T>(s0);
261 D[i+1] = saturate_cast<T>(s1);
262 s0 -= Sm[i]; s1 -= Sm[i+1];
263 SUM[i] = s0; SUM[i+1] = s1;
266 for( ; i < width; i++ )
268 ST s0 = SUM[i] + Sp[i];
269 D[i] = saturate_cast<T>(s0);
284 struct ColumnSum<int, uchar> :
285 public BaseColumnFilter
287 ColumnSum( int _ksize, int _anchor, double _scale ) :
296 virtual void reset() { sumCount = 0; }
298 virtual void operator()(const uchar** src, uchar* dst, int dststep, int count, int width)
301 bool haveScale = scale != 1;
302 double _scale = scale;
305 bool haveSIMD128 = hasSIMD128();
308 if( width != (int)sum.size() )
317 memset((void*)SUM, 0, width*sizeof(int));
318 for( ; sumCount < ksize - 1; sumCount++, src++ )
320 const int* Sp = (const int*)src[0];
325 for (; i <= width - 4; i += 4)
327 v_store(SUM + i, v_load(SUM + i) + v_load(Sp + i));
331 for( ; i < width; i++ )
337 CV_Assert( sumCount == ksize-1 );
341 for( ; count--; src++ )
343 const int* Sp = (const int*)src[0];
344 const int* Sm = (const int*)src[1-ksize];
345 uchar* D = (uchar*)dst;
353 v_float32x4 v_scale = v_setall_f32((float)_scale);
354 for( ; i <= width-8; i+=8 )
356 v_int32x4 v_s0 = v_load(SUM + i) + v_load(Sp + i);
357 v_int32x4 v_s01 = v_load(SUM + i + 4) + v_load(Sp + i + 4);
359 v_uint32x4 v_s0d = v_reinterpret_as_u32(v_round(v_cvt_f32(v_s0) * v_scale));
360 v_uint32x4 v_s01d = v_reinterpret_as_u32(v_round(v_cvt_f32(v_s01) * v_scale));
362 v_uint16x8 v_dst = v_pack(v_s0d, v_s01d);
363 v_pack_store(D + i, v_dst);
365 v_store(SUM + i, v_s0 - v_load(Sm + i));
366 v_store(SUM + i + 4, v_s01 - v_load(Sm + i + 4));
370 for( ; i < width; i++ )
372 int s0 = SUM[i] + Sp[i];
373 D[i] = saturate_cast<uchar>(s0*_scale);
383 for( ; i <= width-8; i+=8 )
385 v_int32x4 v_s0 = v_load(SUM + i) + v_load(Sp + i);
386 v_int32x4 v_s01 = v_load(SUM + i + 4) + v_load(Sp + i + 4);
388 v_uint16x8 v_dst = v_pack(v_reinterpret_as_u32(v_s0), v_reinterpret_as_u32(v_s01));
389 v_pack_store(D + i, v_dst);
391 v_store(SUM + i, v_s0 - v_load(Sm + i));
392 v_store(SUM + i + 4, v_s01 - v_load(Sm + i + 4));
397 for( ; i < width; i++ )
399 int s0 = SUM[i] + Sp[i];
400 D[i] = saturate_cast<uchar>(s0);
410 std::vector<int> sum;
415 struct ColumnSum<ushort, uchar> :
416 public BaseColumnFilter
420 ColumnSum( int _ksize, int _anchor, double _scale ) :
431 int d = cvRound(1./scale);
432 double scalef = ((double)(1 << SHIFT))/d;
433 divScale = cvFloor(scalef);
443 virtual void reset() { sumCount = 0; }
445 virtual void operator()(const uchar** src, uchar* dst, int dststep, int count, int width)
447 const int ds = divScale;
448 const int dd = divDelta;
450 const bool haveScale = scale != 1;
453 bool haveSIMD128 = hasSIMD128();
456 if( width != (int)sum.size() )
465 memset((void*)SUM, 0, width*sizeof(SUM[0]));
466 for( ; sumCount < ksize - 1; sumCount++, src++ )
468 const ushort* Sp = (const ushort*)src[0];
473 for( ; i <= width - 8; i += 8 )
475 v_store(SUM + i, v_load(SUM + i) + v_load(Sp + i));
479 for( ; i < width; i++ )
485 CV_Assert( sumCount == ksize-1 );
489 for( ; count--; src++ )
491 const ushort* Sp = (const ushort*)src[0];
492 const ushort* Sm = (const ushort*)src[1-ksize];
493 uchar* D = (uchar*)dst;
498 v_uint32x4 ds4 = v_setall_u32((unsigned)ds);
499 v_uint16x8 dd8 = v_setall_u16((ushort)dd);
501 for( ; i <= width-16; i+=16 )
503 v_uint16x8 _sm0 = v_load(Sm + i);
504 v_uint16x8 _sm1 = v_load(Sm + i + 8);
506 v_uint16x8 _s0 = v_add_wrap(v_load(SUM + i), v_load(Sp + i));
507 v_uint16x8 _s1 = v_add_wrap(v_load(SUM + i + 8), v_load(Sp + i + 8));
509 v_uint32x4 _s00, _s01, _s10, _s11;
511 v_expand(_s0 + dd8, _s00, _s01);
512 v_expand(_s1 + dd8, _s10, _s11);
514 _s00 = v_shr<SHIFT>(_s00*ds4);
515 _s01 = v_shr<SHIFT>(_s01*ds4);
516 _s10 = v_shr<SHIFT>(_s10*ds4);
517 _s11 = v_shr<SHIFT>(_s11*ds4);
519 v_int16x8 r0 = v_pack(v_reinterpret_as_s32(_s00), v_reinterpret_as_s32(_s01));
520 v_int16x8 r1 = v_pack(v_reinterpret_as_s32(_s10), v_reinterpret_as_s32(_s11));
522 _s0 = v_sub_wrap(_s0, _sm0);
523 _s1 = v_sub_wrap(_s1, _sm1);
525 v_store(D + i, v_pack_u(r0, r1));
526 v_store(SUM + i, _s0);
527 v_store(SUM + i + 8, _s1);
530 for( ; i < width; i++ )
532 int s0 = SUM[i] + Sp[i];
533 D[i] = (uchar)((s0 + dd)*ds >> SHIFT);
534 SUM[i] = (ushort)(s0 - Sm[i]);
540 for( ; i < width; i++ )
542 int s0 = SUM[i] + Sp[i];
543 D[i] = saturate_cast<uchar>(s0);
544 SUM[i] = (ushort)(s0 - Sm[i]);
555 std::vector<ushort> sum;
560 struct ColumnSum<int, short> :
561 public BaseColumnFilter
563 ColumnSum( int _ksize, int _anchor, double _scale ) :
572 virtual void reset() { sumCount = 0; }
574 virtual void operator()(const uchar** src, uchar* dst, int dststep, int count, int width)
578 bool haveScale = scale != 1;
579 double _scale = scale;
582 bool haveSIMD128 = hasSIMD128();
585 if( width != (int)sum.size() )
594 memset((void*)SUM, 0, width*sizeof(int));
595 for( ; sumCount < ksize - 1; sumCount++, src++ )
597 const int* Sp = (const int*)src[0];
602 for( ; i <= width - 4; i+=4 )
604 v_store(SUM + i, v_load(SUM + i) + v_load(Sp + i));
608 for( ; i < width; i++ )
614 CV_Assert( sumCount == ksize-1 );
618 for( ; count--; src++ )
620 const int* Sp = (const int*)src[0];
621 const int* Sm = (const int*)src[1-ksize];
622 short* D = (short*)dst;
629 v_float32x4 v_scale = v_setall_f32((float)_scale);
630 for( ; i <= width-8; i+=8 )
632 v_int32x4 v_s0 = v_load(SUM + i) + v_load(Sp + i);
633 v_int32x4 v_s01 = v_load(SUM + i + 4) + v_load(Sp + i + 4);
635 v_int32x4 v_s0d = v_round(v_cvt_f32(v_s0) * v_scale);
636 v_int32x4 v_s01d = v_round(v_cvt_f32(v_s01) * v_scale);
637 v_store(D + i, v_pack(v_s0d, v_s01d));
639 v_store(SUM + i, v_s0 - v_load(Sm + i));
640 v_store(SUM + i + 4, v_s01 - v_load(Sm + i + 4));
644 for( ; i < width; i++ )
646 int s0 = SUM[i] + Sp[i];
647 D[i] = saturate_cast<short>(s0*_scale);
657 for( ; i <= width-8; i+=8 )
659 v_int32x4 v_s0 = v_load(SUM + i) + v_load(Sp + i);
660 v_int32x4 v_s01 = v_load(SUM + i + 4) + v_load(Sp + i + 4);
662 v_store(D + i, v_pack(v_s0, v_s01));
664 v_store(SUM + i, v_s0 - v_load(Sm + i));
665 v_store(SUM + i + 4, v_s01 - v_load(Sm + i + 4));
670 for( ; i < width; i++ )
672 int s0 = SUM[i] + Sp[i];
673 D[i] = saturate_cast<short>(s0);
683 std::vector<int> sum;
688 struct ColumnSum<int, ushort> :
689 public BaseColumnFilter
691 ColumnSum( int _ksize, int _anchor, double _scale ) :
700 virtual void reset() { sumCount = 0; }
702 virtual void operator()(const uchar** src, uchar* dst, int dststep, int count, int width)
705 bool haveScale = scale != 1;
706 double _scale = scale;
709 bool haveSIMD128 = hasSIMD128();
712 if( width != (int)sum.size() )
721 memset((void*)SUM, 0, width*sizeof(int));
722 for( ; sumCount < ksize - 1; sumCount++, src++ )
724 const int* Sp = (const int*)src[0];
729 for (; i <= width - 4; i += 4)
731 v_store(SUM + i, v_load(SUM + i) + v_load(Sp + i));
735 for( ; i < width; i++ )
741 CV_Assert( sumCount == ksize-1 );
745 for( ; count--; src++ )
747 const int* Sp = (const int*)src[0];
748 const int* Sm = (const int*)src[1-ksize];
749 ushort* D = (ushort*)dst;
756 v_float32x4 v_scale = v_setall_f32((float)_scale);
757 for( ; i <= width-8; i+=8 )
759 v_int32x4 v_s0 = v_load(SUM + i) + v_load(Sp + i);
760 v_int32x4 v_s01 = v_load(SUM + i + 4) + v_load(Sp + i + 4);
762 v_uint32x4 v_s0d = v_reinterpret_as_u32(v_round(v_cvt_f32(v_s0) * v_scale));
763 v_uint32x4 v_s01d = v_reinterpret_as_u32(v_round(v_cvt_f32(v_s01) * v_scale));
764 v_store(D + i, v_pack(v_s0d, v_s01d));
766 v_store(SUM + i, v_s0 - v_load(Sm + i));
767 v_store(SUM + i + 4, v_s01 - v_load(Sm + i + 4));
771 for( ; i < width; i++ )
773 int s0 = SUM[i] + Sp[i];
774 D[i] = saturate_cast<ushort>(s0*_scale);
784 for( ; i <= width-8; i+=8 )
786 v_int32x4 v_s0 = v_load(SUM + i) + v_load(Sp + i);
787 v_int32x4 v_s01 = v_load(SUM + i + 4) + v_load(Sp + i + 4);
789 v_store(D + i, v_pack(v_reinterpret_as_u32(v_s0), v_reinterpret_as_u32(v_s01)));
791 v_store(SUM + i, v_s0 - v_load(Sm + i));
792 v_store(SUM + i + 4, v_s01 - v_load(Sm + i + 4));
796 for( ; i < width; i++ )
798 int s0 = SUM[i] + Sp[i];
799 D[i] = saturate_cast<ushort>(s0);
809 std::vector<int> sum;
813 struct ColumnSum<int, int> :
814 public BaseColumnFilter
816 ColumnSum( int _ksize, int _anchor, double _scale ) :
825 virtual void reset() { sumCount = 0; }
827 virtual void operator()(const uchar** src, uchar* dst, int dststep, int count, int width)
830 bool haveScale = scale != 1;
831 double _scale = scale;
834 bool haveSIMD128 = hasSIMD128();
837 if( width != (int)sum.size() )
846 memset((void*)SUM, 0, width*sizeof(int));
847 for( ; sumCount < ksize - 1; sumCount++, src++ )
849 const int* Sp = (const int*)src[0];
854 for( ; i <= width - 4; i+=4 )
856 v_store(SUM + i, v_load(SUM + i) + v_load(Sp + i));
860 for( ; i < width; i++ )
866 CV_Assert( sumCount == ksize-1 );
870 for( ; count--; src++ )
872 const int* Sp = (const int*)src[0];
873 const int* Sm = (const int*)src[1-ksize];
881 v_float32x4 v_scale = v_setall_f32((float)_scale);
882 for( ; i <= width-4; i+=4 )
884 v_int32x4 v_s0 = v_load(SUM + i) + v_load(Sp + i);
885 v_int32x4 v_s0d = v_round(v_cvt_f32(v_s0) * v_scale);
887 v_store(D + i, v_s0d);
888 v_store(SUM + i, v_s0 - v_load(Sm + i));
892 for( ; i < width; i++ )
894 int s0 = SUM[i] + Sp[i];
895 D[i] = saturate_cast<int>(s0*_scale);
905 for( ; i <= width-4; i+=4 )
907 v_int32x4 v_s0 = v_load(SUM + i) + v_load(Sp + i);
909 v_store(D + i, v_s0);
910 v_store(SUM + i, v_s0 - v_load(Sm + i));
914 for( ; i < width; i++ )
916 int s0 = SUM[i] + Sp[i];
927 std::vector<int> sum;
932 struct ColumnSum<int, float> :
933 public BaseColumnFilter
935 ColumnSum( int _ksize, int _anchor, double _scale ) :
944 virtual void reset() { sumCount = 0; }
946 virtual void operator()(const uchar** src, uchar* dst, int dststep, int count, int width)
949 bool haveScale = scale != 1;
950 double _scale = scale;
953 bool haveSIMD128 = hasSIMD128();
956 if( width != (int)sum.size() )
965 memset((void*)SUM, 0, width*sizeof(int));
966 for( ; sumCount < ksize - 1; sumCount++, src++ )
968 const int* Sp = (const int*)src[0];
973 for( ; i <= width - 4; i+=4 )
975 v_store(SUM + i, v_load(SUM + i) + v_load(Sp + i));
980 for( ; i < width; i++ )
986 CV_Assert( sumCount == ksize-1 );
990 for( ; count--; src++ )
992 const int * Sp = (const int*)src[0];
993 const int * Sm = (const int*)src[1-ksize];
994 float* D = (float*)dst;
1002 v_float32x4 v_scale = v_setall_f32((float)_scale);
1003 for (; i <= width - 8; i += 8)
1005 v_int32x4 v_s0 = v_load(SUM + i) + v_load(Sp + i);
1006 v_int32x4 v_s01 = v_load(SUM + i + 4) + v_load(Sp + i + 4);
1008 v_store(D + i, v_cvt_f32(v_s0) * v_scale);
1009 v_store(D + i + 4, v_cvt_f32(v_s01) * v_scale);
1011 v_store(SUM + i, v_s0 - v_load(Sm + i));
1012 v_store(SUM + i + 4, v_s01 - v_load(Sm + i + 4));
1016 for( ; i < width; i++ )
1018 int s0 = SUM[i] + Sp[i];
1019 D[i] = (float)(s0*_scale);
1020 SUM[i] = s0 - Sm[i];
1030 for( ; i <= width-8; i+=8 )
1032 v_int32x4 v_s0 = v_load(SUM + i) + v_load(Sp + i);
1033 v_int32x4 v_s01 = v_load(SUM + i + 4) + v_load(Sp + i + 4);
1035 v_store(D + i, v_cvt_f32(v_s0));
1036 v_store(D + i + 4, v_cvt_f32(v_s01));
1038 v_store(SUM + i, v_s0 - v_load(Sm + i));
1039 v_store(SUM + i + 4, v_s01 - v_load(Sm + i + 4));
1043 for( ; i < width; i++ )
1045 int s0 = SUM[i] + Sp[i];
1047 SUM[i] = s0 - Sm[i];
1056 std::vector<int> sum;
1061 static bool ocl_boxFilter3x3_8UC1( InputArray _src, OutputArray _dst, int ddepth,
1062 Size ksize, Point anchor, int borderType, bool normalize )
1064 const ocl::Device & dev = ocl::Device::getDefault();
1065 int type = _src.type(), sdepth = CV_MAT_DEPTH(type), cn = CV_MAT_CN(type);
1071 anchor.x = ksize.width / 2;
1073 anchor.y = ksize.height / 2;
1075 if ( !(dev.isIntel() && (type == CV_8UC1) &&
1076 (_src.offset() == 0) && (_src.step() % 4 == 0) &&
1077 (_src.cols() % 16 == 0) && (_src.rows() % 2 == 0) &&
1078 (anchor.x == 1) && (anchor.y == 1) &&
1079 (ksize.width == 3) && (ksize.height == 3)) )
1082 float alpha = 1.0f / (ksize.height * ksize.width);
1083 Size size = _src.size();
1084 size_t globalsize[2] = { 0, 0 };
1085 size_t localsize[2] = { 0, 0 };
1086 const char * const borderMap[] = { "BORDER_CONSTANT", "BORDER_REPLICATE", "BORDER_REFLECT", 0, "BORDER_REFLECT_101" };
1088 globalsize[0] = size.width / 16;
1089 globalsize[1] = size.height / 2;
1091 char build_opts[1024];
1092 sprintf(build_opts, "-D %s %s", borderMap[borderType], normalize ? "-D NORMALIZE" : "");
1094 ocl::Kernel kernel("boxFilter3x3_8UC1_cols16_rows2", cv::ocl::imgproc::boxFilter3x3_oclsrc, build_opts);
1098 UMat src = _src.getUMat();
1099 _dst.create(size, CV_MAKETYPE(ddepth, cn));
1100 if (!(_dst.offset() == 0 && _dst.step() % 4 == 0))
1102 UMat dst = _dst.getUMat();
1104 int idxArg = kernel.set(0, ocl::KernelArg::PtrReadOnly(src));
1105 idxArg = kernel.set(idxArg, (int)src.step);
1106 idxArg = kernel.set(idxArg, ocl::KernelArg::PtrWriteOnly(dst));
1107 idxArg = kernel.set(idxArg, (int)dst.step);
1108 idxArg = kernel.set(idxArg, (int)dst.rows);
1109 idxArg = kernel.set(idxArg, (int)dst.cols);
1111 idxArg = kernel.set(idxArg, (float)alpha);
1113 return kernel.run(2, globalsize, (localsize[0] == 0) ? NULL : localsize, false);
1116 #define DIVUP(total, grain) ((total + grain - 1) / (grain))
1117 #define ROUNDUP(sz, n) ((sz) + (n) - 1 - (((sz) + (n) - 1) % (n)))
1119 static bool ocl_boxFilter( InputArray _src, OutputArray _dst, int ddepth,
1120 Size ksize, Point anchor, int borderType, bool normalize, bool sqr = false )
1122 const ocl::Device & dev = ocl::Device::getDefault();
1123 int type = _src.type(), sdepth = CV_MAT_DEPTH(type), cn = CV_MAT_CN(type), esz = CV_ELEM_SIZE(type);
1124 bool doubleSupport = dev.doubleFPConfig() > 0;
1129 if (cn > 4 || (!doubleSupport && (sdepth == CV_64F || ddepth == CV_64F)) ||
1130 _src.offset() % esz != 0 || _src.step() % esz != 0)
1134 anchor.x = ksize.width / 2;
1136 anchor.y = ksize.height / 2;
1138 int computeUnits = ocl::Device::getDefault().maxComputeUnits();
1139 float alpha = 1.0f / (ksize.height * ksize.width);
1140 Size size = _src.size(), wholeSize;
1141 bool isolated = (borderType & BORDER_ISOLATED) != 0;
1142 borderType &= ~BORDER_ISOLATED;
1143 int wdepth = std::max(CV_32F, std::max(ddepth, sdepth)),
1144 wtype = CV_MAKE_TYPE(wdepth, cn), dtype = CV_MAKE_TYPE(ddepth, cn);
1146 const char * const borderMap[] = { "BORDER_CONSTANT", "BORDER_REPLICATE", "BORDER_REFLECT", 0, "BORDER_REFLECT_101" };
1147 size_t globalsize[2] = { (size_t)size.width, (size_t)size.height };
1148 size_t localsize_general[2] = { 0, 1 }, * localsize = NULL;
1150 UMat src = _src.getUMat();
1154 src.locateROI(wholeSize, ofs);
1157 int h = isolated ? size.height : wholeSize.height;
1158 int w = isolated ? size.width : wholeSize.width;
1160 size_t maxWorkItemSizes[32];
1161 ocl::Device::getDefault().maxWorkItemSizes(maxWorkItemSizes);
1162 int tryWorkItems = (int)maxWorkItemSizes[0];
1166 if (dev.isIntel() && !(dev.type() & ocl::Device::TYPE_CPU) &&
1167 ((ksize.width < 5 && ksize.height < 5 && esz <= 4) ||
1168 (ksize.width == 5 && ksize.height == 5 && cn == 1)))
1170 if (w < ksize.width || h < ksize.height)
1173 // Figure out what vector size to use for loading the pixels.
1174 int pxLoadNumPixels = cn != 1 || size.width % 4 ? 1 : 4;
1175 int pxLoadVecSize = cn * pxLoadNumPixels;
1177 // Figure out how many pixels per work item to compute in X and Y
1178 // directions. Too many and we run out of registers.
1179 int pxPerWorkItemX = 1, pxPerWorkItemY = 1;
1180 if (cn <= 2 && ksize.width <= 4 && ksize.height <= 4)
1182 pxPerWorkItemX = size.width % 8 ? size.width % 4 ? size.width % 2 ? 1 : 2 : 4 : 8;
1183 pxPerWorkItemY = size.height % 2 ? 1 : 2;
1185 else if (cn < 4 || (ksize.width <= 4 && ksize.height <= 4))
1187 pxPerWorkItemX = size.width % 2 ? 1 : 2;
1188 pxPerWorkItemY = size.height % 2 ? 1 : 2;
1190 globalsize[0] = size.width / pxPerWorkItemX;
1191 globalsize[1] = size.height / pxPerWorkItemY;
1193 // Need some padding in the private array for pixels
1194 int privDataWidth = ROUNDUP(pxPerWorkItemX + ksize.width - 1, pxLoadNumPixels);
1196 // Make the global size a nice round number so the runtime can pick
1197 // from reasonable choices for the workgroup size
1198 const int wgRound = 256;
1199 globalsize[0] = ROUNDUP(globalsize[0], wgRound);
1201 char build_options[1024], cvt[2][40];
1202 sprintf(build_options, "-D cn=%d "
1203 "-D ANCHOR_X=%d -D ANCHOR_Y=%d -D KERNEL_SIZE_X=%d -D KERNEL_SIZE_Y=%d "
1204 "-D PX_LOAD_VEC_SIZE=%d -D PX_LOAD_NUM_PX=%d "
1205 "-D PX_PER_WI_X=%d -D PX_PER_WI_Y=%d -D PRIV_DATA_WIDTH=%d -D %s -D %s "
1206 "-D PX_LOAD_X_ITERATIONS=%d -D PX_LOAD_Y_ITERATIONS=%d "
1207 "-D srcT=%s -D srcT1=%s -D dstT=%s -D dstT1=%s -D WT=%s -D WT1=%s "
1208 "-D convertToWT=%s -D convertToDstT=%s%s%s -D PX_LOAD_FLOAT_VEC_CONV=convert_%s -D OP_BOX_FILTER",
1209 cn, anchor.x, anchor.y, ksize.width, ksize.height,
1210 pxLoadVecSize, pxLoadNumPixels,
1211 pxPerWorkItemX, pxPerWorkItemY, privDataWidth, borderMap[borderType],
1212 isolated ? "BORDER_ISOLATED" : "NO_BORDER_ISOLATED",
1213 privDataWidth / pxLoadNumPixels, pxPerWorkItemY + ksize.height - 1,
1214 ocl::typeToStr(type), ocl::typeToStr(sdepth), ocl::typeToStr(dtype),
1215 ocl::typeToStr(ddepth), ocl::typeToStr(wtype), ocl::typeToStr(wdepth),
1216 ocl::convertTypeStr(sdepth, wdepth, cn, cvt[0]),
1217 ocl::convertTypeStr(wdepth, ddepth, cn, cvt[1]),
1218 normalize ? " -D NORMALIZE" : "", sqr ? " -D SQR" : "",
1219 ocl::typeToStr(CV_MAKE_TYPE(wdepth, pxLoadVecSize)) //PX_LOAD_FLOAT_VEC_CONV
1223 if (!kernel.create("filterSmall", cv::ocl::imgproc::filterSmall_oclsrc, build_options))
1228 localsize = localsize_general;
1231 int BLOCK_SIZE_X = tryWorkItems, BLOCK_SIZE_Y = std::min(ksize.height * 10, size.height);
1233 while (BLOCK_SIZE_X > 32 && BLOCK_SIZE_X >= ksize.width * 2 && BLOCK_SIZE_X > size.width * 2)
1235 while (BLOCK_SIZE_Y < BLOCK_SIZE_X / 8 && BLOCK_SIZE_Y * computeUnits * 32 < size.height)
1238 if (ksize.width > BLOCK_SIZE_X || w < ksize.width || h < ksize.height)
1242 String opts = format("-D LOCAL_SIZE_X=%d -D BLOCK_SIZE_Y=%d -D ST=%s -D DT=%s -D WT=%s -D convertToDT=%s -D convertToWT=%s"
1243 " -D ANCHOR_X=%d -D ANCHOR_Y=%d -D KERNEL_SIZE_X=%d -D KERNEL_SIZE_Y=%d -D %s%s%s%s%s"
1244 " -D ST1=%s -D DT1=%s -D cn=%d",
1245 BLOCK_SIZE_X, BLOCK_SIZE_Y, ocl::typeToStr(type), ocl::typeToStr(CV_MAKE_TYPE(ddepth, cn)),
1246 ocl::typeToStr(CV_MAKE_TYPE(wdepth, cn)),
1247 ocl::convertTypeStr(wdepth, ddepth, cn, cvt[0]),
1248 ocl::convertTypeStr(sdepth, wdepth, cn, cvt[1]),
1249 anchor.x, anchor.y, ksize.width, ksize.height, borderMap[borderType],
1250 isolated ? " -D BORDER_ISOLATED" : "", doubleSupport ? " -D DOUBLE_SUPPORT" : "",
1251 normalize ? " -D NORMALIZE" : "", sqr ? " -D SQR" : "",
1252 ocl::typeToStr(sdepth), ocl::typeToStr(ddepth), cn);
1254 localsize[0] = BLOCK_SIZE_X;
1255 globalsize[0] = DIVUP(size.width, BLOCK_SIZE_X - (ksize.width - 1)) * BLOCK_SIZE_X;
1256 globalsize[1] = DIVUP(size.height, BLOCK_SIZE_Y);
1258 kernel.create("boxFilter", cv::ocl::imgproc::boxFilter_oclsrc, opts);
1262 size_t kernelWorkGroupSize = kernel.workGroupSize();
1263 if (localsize[0] <= kernelWorkGroupSize)
1265 if (BLOCK_SIZE_X < (int)kernelWorkGroupSize)
1268 tryWorkItems = (int)kernelWorkGroupSize;
1272 _dst.create(size, CV_MAKETYPE(ddepth, cn));
1273 UMat dst = _dst.getUMat();
1275 int idxArg = kernel.set(0, ocl::KernelArg::PtrReadOnly(src));
1276 idxArg = kernel.set(idxArg, (int)src.step);
1277 int srcOffsetX = (int)((src.offset % src.step) / src.elemSize());
1278 int srcOffsetY = (int)(src.offset / src.step);
1279 int srcEndX = isolated ? srcOffsetX + size.width : wholeSize.width;
1280 int srcEndY = isolated ? srcOffsetY + size.height : wholeSize.height;
1281 idxArg = kernel.set(idxArg, srcOffsetX);
1282 idxArg = kernel.set(idxArg, srcOffsetY);
1283 idxArg = kernel.set(idxArg, srcEndX);
1284 idxArg = kernel.set(idxArg, srcEndY);
1285 idxArg = kernel.set(idxArg, ocl::KernelArg::WriteOnly(dst));
1287 idxArg = kernel.set(idxArg, (float)alpha);
1289 return kernel.run(2, globalsize, localsize, false);
1299 cv::Ptr<cv::BaseRowFilter> cv::getRowSumFilter(int srcType, int sumType, int ksize, int anchor)
1301 int sdepth = CV_MAT_DEPTH(srcType), ddepth = CV_MAT_DEPTH(sumType);
1302 CV_Assert( CV_MAT_CN(sumType) == CV_MAT_CN(srcType) );
1307 if( sdepth == CV_8U && ddepth == CV_32S )
1308 return makePtr<RowSum<uchar, int> >(ksize, anchor);
1309 if( sdepth == CV_8U && ddepth == CV_16U )
1310 return makePtr<RowSum<uchar, ushort> >(ksize, anchor);
1311 if( sdepth == CV_8U && ddepth == CV_64F )
1312 return makePtr<RowSum<uchar, double> >(ksize, anchor);
1313 if( sdepth == CV_16U && ddepth == CV_32S )
1314 return makePtr<RowSum<ushort, int> >(ksize, anchor);
1315 if( sdepth == CV_16U && ddepth == CV_64F )
1316 return makePtr<RowSum<ushort, double> >(ksize, anchor);
1317 if( sdepth == CV_16S && ddepth == CV_32S )
1318 return makePtr<RowSum<short, int> >(ksize, anchor);
1319 if( sdepth == CV_32S && ddepth == CV_32S )
1320 return makePtr<RowSum<int, int> >(ksize, anchor);
1321 if( sdepth == CV_16S && ddepth == CV_64F )
1322 return makePtr<RowSum<short, double> >(ksize, anchor);
1323 if( sdepth == CV_32F && ddepth == CV_64F )
1324 return makePtr<RowSum<float, double> >(ksize, anchor);
1325 if( sdepth == CV_64F && ddepth == CV_64F )
1326 return makePtr<RowSum<double, double> >(ksize, anchor);
1328 CV_Error_( CV_StsNotImplemented,
1329 ("Unsupported combination of source format (=%d), and buffer format (=%d)",
1332 return Ptr<BaseRowFilter>();
1336 cv::Ptr<cv::BaseColumnFilter> cv::getColumnSumFilter(int sumType, int dstType, int ksize,
1337 int anchor, double scale)
1339 int sdepth = CV_MAT_DEPTH(sumType), ddepth = CV_MAT_DEPTH(dstType);
1340 CV_Assert( CV_MAT_CN(sumType) == CV_MAT_CN(dstType) );
1345 if( ddepth == CV_8U && sdepth == CV_32S )
1346 return makePtr<ColumnSum<int, uchar> >(ksize, anchor, scale);
1347 if( ddepth == CV_8U && sdepth == CV_16U )
1348 return makePtr<ColumnSum<ushort, uchar> >(ksize, anchor, scale);
1349 if( ddepth == CV_8U && sdepth == CV_64F )
1350 return makePtr<ColumnSum<double, uchar> >(ksize, anchor, scale);
1351 if( ddepth == CV_16U && sdepth == CV_32S )
1352 return makePtr<ColumnSum<int, ushort> >(ksize, anchor, scale);
1353 if( ddepth == CV_16U && sdepth == CV_64F )
1354 return makePtr<ColumnSum<double, ushort> >(ksize, anchor, scale);
1355 if( ddepth == CV_16S && sdepth == CV_32S )
1356 return makePtr<ColumnSum<int, short> >(ksize, anchor, scale);
1357 if( ddepth == CV_16S && sdepth == CV_64F )
1358 return makePtr<ColumnSum<double, short> >(ksize, anchor, scale);
1359 if( ddepth == CV_32S && sdepth == CV_32S )
1360 return makePtr<ColumnSum<int, int> >(ksize, anchor, scale);
1361 if( ddepth == CV_32F && sdepth == CV_32S )
1362 return makePtr<ColumnSum<int, float> >(ksize, anchor, scale);
1363 if( ddepth == CV_32F && sdepth == CV_64F )
1364 return makePtr<ColumnSum<double, float> >(ksize, anchor, scale);
1365 if( ddepth == CV_64F && sdepth == CV_32S )
1366 return makePtr<ColumnSum<int, double> >(ksize, anchor, scale);
1367 if( ddepth == CV_64F && sdepth == CV_64F )
1368 return makePtr<ColumnSum<double, double> >(ksize, anchor, scale);
1370 CV_Error_( CV_StsNotImplemented,
1371 ("Unsupported combination of sum format (=%d), and destination format (=%d)",
1374 return Ptr<BaseColumnFilter>();
1378 cv::Ptr<cv::FilterEngine> cv::createBoxFilter( int srcType, int dstType, Size ksize,
1379 Point anchor, bool normalize, int borderType )
1381 int sdepth = CV_MAT_DEPTH(srcType);
1382 int cn = CV_MAT_CN(srcType), sumType = CV_64F;
1383 if( sdepth == CV_8U && CV_MAT_DEPTH(dstType) == CV_8U &&
1384 ksize.width*ksize.height <= 256 )
1386 else if( sdepth <= CV_32S && (!normalize ||
1387 ksize.width*ksize.height <= (sdepth == CV_8U ? (1<<23) :
1388 sdepth == CV_16U ? (1 << 15) : (1 << 16))) )
1390 sumType = CV_MAKETYPE( sumType, cn );
1392 Ptr<BaseRowFilter> rowFilter = getRowSumFilter(srcType, sumType, ksize.width, anchor.x );
1393 Ptr<BaseColumnFilter> columnFilter = getColumnSumFilter(sumType,
1394 dstType, ksize.height, anchor.y, normalize ? 1./(ksize.width*ksize.height) : 1);
1396 return makePtr<FilterEngine>(Ptr<BaseFilter>(), rowFilter, columnFilter,
1397 srcType, dstType, sumType, borderType );
1404 template <> inline bool skipSmallImages<VX_KERNEL_BOX_3x3>(int w, int h) { return w*h < 640 * 480; }
1406 static bool openvx_boxfilter(InputArray _src, OutputArray _dst, int ddepth,
1407 Size ksize, Point anchor,
1408 bool normalize, int borderType)
1412 if (_src.type() != CV_8UC1 || ddepth != CV_8U || !normalize ||
1413 _src.cols() < 3 || _src.rows() < 3 ||
1414 ksize.width != 3 || ksize.height != 3 ||
1415 (anchor.x >= 0 && anchor.x != 1) ||
1416 (anchor.y >= 0 && anchor.y != 1) ||
1417 ovx::skipSmallImages<VX_KERNEL_BOX_3x3>(_src.cols(), _src.rows()))
1420 Mat src = _src.getMat();
1422 if ((borderType & BORDER_ISOLATED) == 0 && src.isSubmatrix())
1423 return false; //Process isolated borders only
1425 switch (borderType & ~BORDER_ISOLATED)
1427 case BORDER_CONSTANT:
1428 border = VX_BORDER_CONSTANT;
1430 case BORDER_REPLICATE:
1431 border = VX_BORDER_REPLICATE;
1437 _dst.create(src.size(), CV_8UC1);
1438 Mat dst = _dst.getMat();
1442 ivx::Context ctx = ovx::getOpenVXContext();
1445 if (dst.data != src.data)
1451 ia = ivx::Image::createFromHandle(ctx, VX_DF_IMAGE_U8,
1452 ivx::Image::createAddressing(a.cols, a.rows, 1, (vx_int32)(a.step)), a.data),
1453 ib = ivx::Image::createFromHandle(ctx, VX_DF_IMAGE_U8,
1454 ivx::Image::createAddressing(dst.cols, dst.rows, 1, (vx_int32)(dst.step)), dst.data);
1456 //ATTENTION: VX_CONTEXT_IMMEDIATE_BORDER attribute change could lead to strange issues in multi-threaded environments
1457 //since OpenVX standart says nothing about thread-safety for now
1458 ivx::border_t prevBorder = ctx.immediateBorder();
1459 ctx.setImmediateBorder(border, (vx_uint8)(0));
1460 ivx::IVX_CHECK_STATUS(vxuBox3x3(ctx, ia, ib));
1461 ctx.setImmediateBorder(prevBorder);
1463 catch (ivx::RuntimeError & e)
1465 VX_DbgThrow(e.what());
1467 catch (ivx::WrapperError & e)
1469 VX_DbgThrow(e.what());
1477 #if defined(HAVE_IPP)
1480 static bool ipp_boxfilter(Mat &src, Mat &dst, Size ksize, Point anchor, bool normalize, int borderType)
1483 CV_INSTRUMENT_REGION_IPP()
1485 #if IPP_VERSION_X100 < 201801
1486 // Problem with SSE42 optimization for 16s and some 8u modes
1487 if(ipp::getIppTopFeatures() == ippCPUID_SSE42 && (((src.depth() == CV_16S || src.depth() == CV_16U) && (src.channels() == 3 || src.channels() == 4)) || (src.depth() == CV_8U && src.channels() == 3 && (ksize.width > 5 || ksize.height > 5))))
1490 // Other optimizations has some degradations too
1491 if((((src.depth() == CV_16S || src.depth() == CV_16U) && (src.channels() == 4)) || (src.depth() == CV_8U && src.channels() == 1 && (ksize.width > 5 || ksize.height > 5))))
1498 if(!ippiCheckAnchor(anchor, ksize))
1503 ::ipp::IwiImage iwSrc = ippiGetImage(src);
1504 ::ipp::IwiImage iwDst = ippiGetImage(dst);
1505 ::ipp::IwiSize iwKSize = ippiGetSize(ksize);
1506 ::ipp::IwiBorderSize borderSize(iwKSize);
1507 ::ipp::IwiBorderType ippBorder(ippiGetBorder(iwSrc, borderType, borderSize));
1511 CV_INSTRUMENT_FUN_IPP(::ipp::iwiFilterBox, iwSrc, iwDst, iwKSize, ::ipp::IwDefault(), ippBorder);
1513 catch (::ipp::IwException)
1520 CV_UNUSED(src); CV_UNUSED(dst); CV_UNUSED(ksize); CV_UNUSED(anchor); CV_UNUSED(normalize); CV_UNUSED(borderType);
1528 void cv::boxFilter( InputArray _src, OutputArray _dst, int ddepth,
1529 Size ksize, Point anchor,
1530 bool normalize, int borderType )
1532 CV_INSTRUMENT_REGION()
1534 CV_OCL_RUN(_dst.isUMat() &&
1535 (borderType == BORDER_REPLICATE || borderType == BORDER_CONSTANT ||
1536 borderType == BORDER_REFLECT || borderType == BORDER_REFLECT_101),
1537 ocl_boxFilter3x3_8UC1(_src, _dst, ddepth, ksize, anchor, borderType, normalize))
1539 CV_OCL_RUN(_dst.isUMat(), ocl_boxFilter(_src, _dst, ddepth, ksize, anchor, borderType, normalize))
1541 Mat src = _src.getMat();
1542 int stype = src.type(), sdepth = CV_MAT_DEPTH(stype), cn = CV_MAT_CN(stype);
1545 _dst.create( src.size(), CV_MAKETYPE(ddepth, cn) );
1546 Mat dst = _dst.getMat();
1547 if( borderType != BORDER_CONSTANT && normalize && (borderType & BORDER_ISOLATED) != 0 )
1556 Size wsz(src.cols, src.rows);
1557 if(!(borderType&BORDER_ISOLATED))
1558 src.locateROI( wsz, ofs );
1560 CALL_HAL(boxFilter, cv_hal_boxFilter, src.ptr(), src.step, dst.ptr(), dst.step, src.cols, src.rows, sdepth, ddepth, cn,
1561 ofs.x, ofs.y, wsz.width - src.cols - ofs.x, wsz.height - src.rows - ofs.y, ksize.width, ksize.height,
1562 anchor.x, anchor.y, normalize, borderType&~BORDER_ISOLATED);
1565 openvx_boxfilter(src, dst, ddepth, ksize, anchor, normalize, borderType))
1567 CV_IPP_RUN_FAST(ipp_boxfilter(src, dst, ksize, anchor, normalize, borderType));
1569 borderType = (borderType&~BORDER_ISOLATED);
1571 Ptr<FilterEngine> f = createBoxFilter( src.type(), dst.type(),
1572 ksize, anchor, normalize, borderType );
1574 f->apply( src, dst, wsz, ofs );
1578 void cv::blur( InputArray src, OutputArray dst,
1579 Size ksize, Point anchor, int borderType )
1581 CV_INSTRUMENT_REGION()
1583 boxFilter( src, dst, -1, ksize, anchor, true, borderType );
1587 /****************************************************************************************\
1589 \****************************************************************************************/
1594 template<typename T, typename ST>
1596 public BaseRowFilter
1598 SqrRowSum( int _ksize, int _anchor ) :
1605 virtual void operator()(const uchar* src, uchar* dst, int width, int cn)
1607 const T* S = (const T*)src;
1609 int i = 0, k, ksz_cn = ksize*cn;
1611 width = (width - 1)*cn;
1612 for( k = 0; k < cn; k++, S++, D++ )
1615 for( i = 0; i < ksz_cn; i += cn )
1621 for( i = 0; i < width; i += cn )
1623 ST val0 = (ST)S[i], val1 = (ST)S[i + ksz_cn];
1624 s += val1*val1 - val0*val0;
1631 static Ptr<BaseRowFilter> getSqrRowSumFilter(int srcType, int sumType, int ksize, int anchor)
1633 int sdepth = CV_MAT_DEPTH(srcType), ddepth = CV_MAT_DEPTH(sumType);
1634 CV_Assert( CV_MAT_CN(sumType) == CV_MAT_CN(srcType) );
1639 if( sdepth == CV_8U && ddepth == CV_32S )
1640 return makePtr<SqrRowSum<uchar, int> >(ksize, anchor);
1641 if( sdepth == CV_8U && ddepth == CV_64F )
1642 return makePtr<SqrRowSum<uchar, double> >(ksize, anchor);
1643 if( sdepth == CV_16U && ddepth == CV_64F )
1644 return makePtr<SqrRowSum<ushort, double> >(ksize, anchor);
1645 if( sdepth == CV_16S && ddepth == CV_64F )
1646 return makePtr<SqrRowSum<short, double> >(ksize, anchor);
1647 if( sdepth == CV_32F && ddepth == CV_64F )
1648 return makePtr<SqrRowSum<float, double> >(ksize, anchor);
1649 if( sdepth == CV_64F && ddepth == CV_64F )
1650 return makePtr<SqrRowSum<double, double> >(ksize, anchor);
1652 CV_Error_( CV_StsNotImplemented,
1653 ("Unsupported combination of source format (=%d), and buffer format (=%d)",
1656 return Ptr<BaseRowFilter>();
1661 void cv::sqrBoxFilter( InputArray _src, OutputArray _dst, int ddepth,
1662 Size ksize, Point anchor,
1663 bool normalize, int borderType )
1665 CV_INSTRUMENT_REGION()
1667 int srcType = _src.type(), sdepth = CV_MAT_DEPTH(srcType), cn = CV_MAT_CN(srcType);
1668 Size size = _src.size();
1671 ddepth = sdepth < CV_32F ? CV_32F : CV_64F;
1673 if( borderType != BORDER_CONSTANT && normalize )
1675 if( size.height == 1 )
1677 if( size.width == 1 )
1681 CV_OCL_RUN(_dst.isUMat() && _src.dims() <= 2,
1682 ocl_boxFilter(_src, _dst, ddepth, ksize, anchor, borderType, normalize, true))
1684 int sumDepth = CV_64F;
1685 if( sdepth == CV_8U )
1687 int sumType = CV_MAKETYPE( sumDepth, cn ), dstType = CV_MAKETYPE(ddepth, cn);
1689 Mat src = _src.getMat();
1690 _dst.create( size, dstType );
1691 Mat dst = _dst.getMat();
1693 Ptr<BaseRowFilter> rowFilter = getSqrRowSumFilter(srcType, sumType, ksize.width, anchor.x );
1694 Ptr<BaseColumnFilter> columnFilter = getColumnSumFilter(sumType,
1695 dstType, ksize.height, anchor.y,
1696 normalize ? 1./(ksize.width*ksize.height) : 1);
1698 Ptr<FilterEngine> f = makePtr<FilterEngine>(Ptr<BaseFilter>(), rowFilter, columnFilter,
1699 srcType, dstType, sumType, borderType );
1701 Size wsz(src.cols, src.rows);
1702 src.locateROI( wsz, ofs );
1704 f->apply( src, dst, wsz, ofs );
1708 /****************************************************************************************\
1710 \****************************************************************************************/
1712 cv::Mat cv::getGaussianKernel( int n, double sigma, int ktype )
1714 const int SMALL_GAUSSIAN_SIZE = 7;
1715 static const float small_gaussian_tab[][SMALL_GAUSSIAN_SIZE] =
1718 {0.25f, 0.5f, 0.25f},
1719 {0.0625f, 0.25f, 0.375f, 0.25f, 0.0625f},
1720 {0.03125f, 0.109375f, 0.21875f, 0.28125f, 0.21875f, 0.109375f, 0.03125f}
1723 const float* fixed_kernel = n % 2 == 1 && n <= SMALL_GAUSSIAN_SIZE && sigma <= 0 ?
1724 small_gaussian_tab[n>>1] : 0;
1726 CV_Assert( ktype == CV_32F || ktype == CV_64F );
1727 Mat kernel(n, 1, ktype);
1728 float* cf = kernel.ptr<float>();
1729 double* cd = kernel.ptr<double>();
1731 double sigmaX = sigma > 0 ? sigma : ((n-1)*0.5 - 1)*0.3 + 0.8;
1732 double scale2X = -0.5/(sigmaX*sigmaX);
1736 for( i = 0; i < n; i++ )
1738 double x = i - (n-1)*0.5;
1739 double t = fixed_kernel ? (double)fixed_kernel[i] : std::exp(scale2X*x*x);
1740 if( ktype == CV_32F )
1753 for( i = 0; i < n; i++ )
1755 if( ktype == CV_32F )
1756 cf[i] = (float)(cf[i]*sum);
1766 static void createGaussianKernels( Mat & kx, Mat & ky, int type, Size ksize,
1767 double sigma1, double sigma2 )
1769 int depth = CV_MAT_DEPTH(type);
1773 // automatic detection of kernel size from sigma
1774 if( ksize.width <= 0 && sigma1 > 0 )
1775 ksize.width = cvRound(sigma1*(depth == CV_8U ? 3 : 4)*2 + 1)|1;
1776 if( ksize.height <= 0 && sigma2 > 0 )
1777 ksize.height = cvRound(sigma2*(depth == CV_8U ? 3 : 4)*2 + 1)|1;
1779 CV_Assert( ksize.width > 0 && ksize.width % 2 == 1 &&
1780 ksize.height > 0 && ksize.height % 2 == 1 );
1782 sigma1 = std::max( sigma1, 0. );
1783 sigma2 = std::max( sigma2, 0. );
1785 kx = getGaussianKernel( ksize.width, sigma1, std::max(depth, CV_32F) );
1786 if( ksize.height == ksize.width && std::abs(sigma1 - sigma2) < DBL_EPSILON )
1789 ky = getGaussianKernel( ksize.height, sigma2, std::max(depth, CV_32F) );
1794 cv::Ptr<cv::FilterEngine> cv::createGaussianFilter( int type, Size ksize,
1795 double sigma1, double sigma2,
1799 createGaussianKernels(kx, ky, type, ksize, sigma1, sigma2);
1801 return createSeparableLinearFilter( type, type, kx, ky, Point(-1,-1), 0, borderType );
1808 static bool ocl_GaussianBlur_8UC1(InputArray _src, OutputArray _dst, Size ksize, int ddepth,
1809 InputArray _kernelX, InputArray _kernelY, int borderType)
1811 const ocl::Device & dev = ocl::Device::getDefault();
1812 int type = _src.type(), sdepth = CV_MAT_DEPTH(type), cn = CV_MAT_CN(type);
1814 if ( !(dev.isIntel() && (type == CV_8UC1) &&
1815 (_src.offset() == 0) && (_src.step() % 4 == 0) &&
1816 ((ksize.width == 5 && (_src.cols() % 4 == 0)) ||
1817 (ksize.width == 3 && (_src.cols() % 16 == 0) && (_src.rows() % 2 == 0)))) )
1820 Mat kernelX = _kernelX.getMat().reshape(1, 1);
1821 if (kernelX.cols % 2 != 1)
1823 Mat kernelY = _kernelY.getMat().reshape(1, 1);
1824 if (kernelY.cols % 2 != 1)
1830 Size size = _src.size();
1831 size_t globalsize[2] = { 0, 0 };
1832 size_t localsize[2] = { 0, 0 };
1834 if (ksize.width == 3)
1836 globalsize[0] = size.width / 16;
1837 globalsize[1] = size.height / 2;
1839 else if (ksize.width == 5)
1841 globalsize[0] = size.width / 4;
1842 globalsize[1] = size.height / 1;
1845 const char * const borderMap[] = { "BORDER_CONSTANT", "BORDER_REPLICATE", "BORDER_REFLECT", 0, "BORDER_REFLECT_101" };
1846 char build_opts[1024];
1847 sprintf(build_opts, "-D %s %s%s", borderMap[borderType],
1848 ocl::kernelToStr(kernelX, CV_32F, "KERNEL_MATRIX_X").c_str(),
1849 ocl::kernelToStr(kernelY, CV_32F, "KERNEL_MATRIX_Y").c_str());
1853 if (ksize.width == 3)
1854 kernel.create("gaussianBlur3x3_8UC1_cols16_rows2", cv::ocl::imgproc::gaussianBlur3x3_oclsrc, build_opts);
1855 else if (ksize.width == 5)
1856 kernel.create("gaussianBlur5x5_8UC1_cols4", cv::ocl::imgproc::gaussianBlur5x5_oclsrc, build_opts);
1861 UMat src = _src.getUMat();
1862 _dst.create(size, CV_MAKETYPE(ddepth, cn));
1863 if (!(_dst.offset() == 0 && _dst.step() % 4 == 0))
1865 UMat dst = _dst.getUMat();
1867 int idxArg = kernel.set(0, ocl::KernelArg::PtrReadOnly(src));
1868 idxArg = kernel.set(idxArg, (int)src.step);
1869 idxArg = kernel.set(idxArg, ocl::KernelArg::PtrWriteOnly(dst));
1870 idxArg = kernel.set(idxArg, (int)dst.step);
1871 idxArg = kernel.set(idxArg, (int)dst.rows);
1872 idxArg = kernel.set(idxArg, (int)dst.cols);
1874 return kernel.run(2, globalsize, (localsize[0] == 0) ? NULL : localsize, false);
1882 template <> inline bool skipSmallImages<VX_KERNEL_GAUSSIAN_3x3>(int w, int h) { return w*h < 320 * 240; }
1884 static bool openvx_gaussianBlur(InputArray _src, OutputArray _dst, Size ksize,
1885 double sigma1, double sigma2, int borderType)
1889 // automatic detection of kernel size from sigma
1890 if (ksize.width <= 0 && sigma1 > 0)
1891 ksize.width = cvRound(sigma1*6 + 1) | 1;
1892 if (ksize.height <= 0 && sigma2 > 0)
1893 ksize.height = cvRound(sigma2*6 + 1) | 1;
1895 if (_src.type() != CV_8UC1 ||
1896 _src.cols() < 3 || _src.rows() < 3 ||
1897 ksize.width != 3 || ksize.height != 3)
1900 sigma1 = std::max(sigma1, 0.);
1901 sigma2 = std::max(sigma2, 0.);
1903 if (!(sigma1 == 0.0 || (sigma1 - 0.8) < DBL_EPSILON) || !(sigma2 == 0.0 || (sigma2 - 0.8) < DBL_EPSILON) ||
1904 ovx::skipSmallImages<VX_KERNEL_GAUSSIAN_3x3>(_src.cols(), _src.rows()))
1907 Mat src = _src.getMat();
1908 Mat dst = _dst.getMat();
1910 if ((borderType & BORDER_ISOLATED) == 0 && src.isSubmatrix())
1911 return false; //Process isolated borders only
1913 switch (borderType & ~BORDER_ISOLATED)
1915 case BORDER_CONSTANT:
1916 border = VX_BORDER_CONSTANT;
1918 case BORDER_REPLICATE:
1919 border = VX_BORDER_REPLICATE;
1927 ivx::Context ctx = ovx::getOpenVXContext();
1930 if (dst.data != src.data)
1936 ia = ivx::Image::createFromHandle(ctx, VX_DF_IMAGE_U8,
1937 ivx::Image::createAddressing(a.cols, a.rows, 1, (vx_int32)(a.step)), a.data),
1938 ib = ivx::Image::createFromHandle(ctx, VX_DF_IMAGE_U8,
1939 ivx::Image::createAddressing(dst.cols, dst.rows, 1, (vx_int32)(dst.step)), dst.data);
1941 //ATTENTION: VX_CONTEXT_IMMEDIATE_BORDER attribute change could lead to strange issues in multi-threaded environments
1942 //since OpenVX standart says nothing about thread-safety for now
1943 ivx::border_t prevBorder = ctx.immediateBorder();
1944 ctx.setImmediateBorder(border, (vx_uint8)(0));
1945 ivx::IVX_CHECK_STATUS(vxuGaussian3x3(ctx, ia, ib));
1946 ctx.setImmediateBorder(prevBorder);
1948 catch (ivx::RuntimeError & e)
1950 VX_DbgThrow(e.what());
1952 catch (ivx::WrapperError & e)
1954 VX_DbgThrow(e.what());
1962 #if IPP_VERSION_X100 == 201702 // IW 2017u2 has bug which doesn't allow use of partial inMem with tiling
1963 #define IPP_GAUSSIANBLUR_PARALLEL 0
1965 #define IPP_GAUSSIANBLUR_PARALLEL 1
1970 class ipp_gaussianBlurParallel: public ParallelLoopBody
1973 ipp_gaussianBlurParallel(::ipp::IwiImage &src, ::ipp::IwiImage &dst, int kernelSize, float sigma, ::ipp::IwiBorderType &border, bool *pOk):
1974 m_src(src), m_dst(dst), m_kernelSize(kernelSize), m_sigma(sigma), m_border(border), m_pOk(pOk) {
1977 ~ipp_gaussianBlurParallel()
1981 virtual void operator() (const Range& range) const
1983 CV_INSTRUMENT_REGION_IPP()
1990 ::ipp::IwiTile tile = ::ipp::IwiRoi(0, range.start, m_dst.m_size.width, range.end - range.start);
1991 CV_INSTRUMENT_FUN_IPP(::ipp::iwiFilterGaussian, m_src, m_dst, m_kernelSize, m_sigma, ::ipp::IwDefault(), m_border, tile);
1993 catch(::ipp::IwException e)
2000 ::ipp::IwiImage &m_src;
2001 ::ipp::IwiImage &m_dst;
2005 ::ipp::IwiBorderType &m_border;
2007 volatile bool *m_pOk;
2008 const ipp_gaussianBlurParallel& operator= (const ipp_gaussianBlurParallel&);
2013 static bool ipp_GaussianBlur(InputArray _src, OutputArray _dst, Size ksize,
2014 double sigma1, double sigma2, int borderType )
2017 CV_INSTRUMENT_REGION_IPP()
2019 #if IPP_VERSION_X100 < 201800 && ((defined _MSC_VER && defined _M_IX86) || (defined __GNUC__ && defined __i386__))
2020 CV_UNUSED(_src); CV_UNUSED(_dst); CV_UNUSED(ksize); CV_UNUSED(sigma1); CV_UNUSED(sigma2); CV_UNUSED(borderType);
2021 return false; // bug on ia32
2023 if(sigma1 != sigma2)
2026 if(sigma1 < FLT_EPSILON)
2029 if(ksize.width != ksize.height)
2032 // Acquire data and begin processing
2035 Mat src = _src.getMat();
2036 Mat dst = _dst.getMat();
2037 ::ipp::IwiImage iwSrc = ippiGetImage(src);
2038 ::ipp::IwiImage iwDst = ippiGetImage(dst);
2039 ::ipp::IwiBorderSize borderSize = ::ipp::iwiSizeToBorderSize(ippiGetSize(ksize));
2040 ::ipp::IwiBorderType ippBorder(ippiGetBorder(iwSrc, borderType, borderSize));
2044 const int threads = ippiSuggestThreadsNum(iwDst, 2);
2045 if(IPP_GAUSSIANBLUR_PARALLEL && threads > 1) {
2047 ipp_gaussianBlurParallel invoker(iwSrc, iwDst, ksize.width, (float) sigma1, ippBorder, &ok);
2051 const Range range(0, (int) iwDst.m_size.height);
2052 parallel_for_(range, invoker, threads*4);
2057 CV_INSTRUMENT_FUN_IPP(::ipp::iwiFilterGaussian, iwSrc, iwDst, ksize.width, sigma1, ::ipp::IwDefault(), ippBorder);
2060 catch (::ipp::IwException ex)
2068 CV_UNUSED(_src); CV_UNUSED(_dst); CV_UNUSED(ksize); CV_UNUSED(sigma1); CV_UNUSED(sigma2); CV_UNUSED(borderType);
2075 void cv::GaussianBlur( InputArray _src, OutputArray _dst, Size ksize,
2076 double sigma1, double sigma2,
2079 CV_INSTRUMENT_REGION()
2081 int type = _src.type();
2082 Size size = _src.size();
2083 _dst.create( size, type );
2085 if( borderType != BORDER_CONSTANT && (borderType & BORDER_ISOLATED) != 0 )
2087 if( size.height == 1 )
2089 if( size.width == 1 )
2093 if( ksize.width == 1 && ksize.height == 1 )
2099 bool useOpenCL = (ocl::isOpenCLActivated() && _dst.isUMat() && _src.dims() <= 2 &&
2100 ((ksize.width == 3 && ksize.height == 3) ||
2101 (ksize.width == 5 && ksize.height == 5)) &&
2102 _src.rows() > ksize.height && _src.cols() > ksize.width);
2105 int sdepth = CV_MAT_DEPTH(type), cn = CV_MAT_CN(type);
2108 createGaussianKernels(kx, ky, type, ksize, sigma1, sigma2);
2110 CV_OCL_RUN(useOpenCL, ocl_GaussianBlur_8UC1(_src, _dst, ksize, CV_MAT_DEPTH(type), kx, ky, borderType));
2112 CV_OCL_RUN(_dst.isUMat() && _src.dims() <= 2 && (size_t)_src.rows() > kx.total() && (size_t)_src.cols() > kx.total(),
2113 ocl_sepFilter2D(_src, _dst, sdepth, kx, ky, Point(-1, -1), 0, borderType))
2115 Mat src = _src.getMat();
2116 Mat dst = _dst.getMat();
2119 Size wsz(src.cols, src.rows);
2120 if(!(borderType & BORDER_ISOLATED))
2121 src.locateROI( wsz, ofs );
2123 CALL_HAL(gaussianBlur, cv_hal_gaussianBlur, src.ptr(), src.step, dst.ptr(), dst.step, src.cols, src.rows, sdepth, cn,
2124 ofs.x, ofs.y, wsz.width - src.cols - ofs.x, wsz.height - src.rows - ofs.y, ksize.width, ksize.height,
2125 sigma1, sigma2, borderType&~BORDER_ISOLATED);
2128 openvx_gaussianBlur(src, dst, ksize, sigma1, sigma2, borderType))
2130 CV_IPP_RUN_FAST(ipp_GaussianBlur(src, dst, ksize, sigma1, sigma2, borderType));
2132 sepFilter2D(src, dst, sdepth, kx, ky, Point(-1, -1), 0, borderType);
2135 /****************************************************************************************\
2137 \****************************************************************************************/
2144 * This structure represents a two-tier histogram. The first tier (known as the
2145 * "coarse" level) is 4 bit wide and the second tier (known as the "fine" level)
2146 * is 8 bit wide. Pixels inserted in the fine level also get inserted into the
2147 * coarse bucket designated by the 4 MSBs of the fine bucket value.
2149 * The structure is aligned on 16 bits, which is a prerequisite for SIMD
2150 * instructions. Each bucket is 16 bit wide, which means that extra care must be
2151 * taken to prevent overflow.
2162 static inline void histogram_add_simd( const HT x[16], HT y[16] )
2164 v_store(y, v_load(x) + v_load(y));
2165 v_store(y + 8, v_load(x + 8) + v_load(y + 8));
2168 static inline void histogram_sub_simd( const HT x[16], HT y[16] )
2170 v_store(y, v_load(y) - v_load(x));
2171 v_store(y + 8, v_load(y + 8) - v_load(x + 8));
2177 static inline void histogram_add( const HT x[16], HT y[16] )
2180 for( i = 0; i < 16; ++i )
2181 y[i] = (HT)(y[i] + x[i]);
2184 static inline void histogram_sub( const HT x[16], HT y[16] )
2187 for( i = 0; i < 16; ++i )
2188 y[i] = (HT)(y[i] - x[i]);
2191 static inline void histogram_muladd( int a, const HT x[16],
2194 for( int i = 0; i < 16; ++i )
2195 y[i] = (HT)(y[i] + a * x[i]);
2199 medianBlur_8u_O1( const Mat& _src, Mat& _dst, int ksize )
2202 * HOP is short for Histogram OPeration. This macro makes an operation \a op on
2203 * histogram \a h for pixel value \a x. It takes care of handling both levels.
2205 #define HOP(h,x,op) \
2206 h.coarse[x>>4] op, \
2207 *((HT*)h.fine + x) op
2209 #define COP(c,j,x,op) \
2210 h_coarse[ 16*(n*c+j) + (x>>4) ] op, \
2211 h_fine[ 16 * (n*(16*c+(x>>4)) + j) + (x & 0xF) ] op
2213 int cn = _dst.channels(), m = _dst.rows, r = (ksize-1)/2;
2214 CV_Assert(cn > 0 && cn <= 4);
2215 size_t sstep = _src.step, dstep = _dst.step;
2216 Histogram CV_DECL_ALIGNED(16) H[4];
2217 HT CV_DECL_ALIGNED(16) luc[4][16];
2219 int STRIPE_SIZE = std::min( _dst.cols, 512/cn );
2221 std::vector<HT> _h_coarse(1 * 16 * (STRIPE_SIZE + 2*r) * cn + 16);
2222 std::vector<HT> _h_fine(16 * 16 * (STRIPE_SIZE + 2*r) * cn + 16);
2223 HT* h_coarse = alignPtr(&_h_coarse[0], 16);
2224 HT* h_fine = alignPtr(&_h_fine[0], 16);
2226 volatile bool useSIMD = hasSIMD128();
2229 for( int x = 0; x < _dst.cols; x += STRIPE_SIZE )
2231 int i, j, k, c, n = std::min(_dst.cols - x, STRIPE_SIZE) + r*2;
2232 const uchar* src = _src.ptr() + x*cn;
2233 uchar* dst = _dst.ptr() + (x - r)*cn;
2235 memset( h_coarse, 0, 16*n*cn*sizeof(h_coarse[0]) );
2236 memset( h_fine, 0, 16*16*n*cn*sizeof(h_fine[0]) );
2238 // First row initialization
2239 for( c = 0; c < cn; c++ )
2241 for( j = 0; j < n; j++ )
2242 COP( c, j, src[cn*j+c], += (cv::HT)(r+2) );
2244 for( i = 1; i < r; i++ )
2246 const uchar* p = src + sstep*std::min(i, m-1);
2247 for ( j = 0; j < n; j++ )
2248 COP( c, j, p[cn*j+c], ++ );
2252 for( i = 0; i < m; i++ )
2254 const uchar* p0 = src + sstep * std::max( 0, i-r-1 );
2255 const uchar* p1 = src + sstep * std::min( m-1, i+r );
2257 memset( H, 0, cn*sizeof(H[0]) );
2258 memset( luc, 0, cn*sizeof(luc[0]) );
2259 for( c = 0; c < cn; c++ )
2261 // Update column histograms for the entire row.
2262 for( j = 0; j < n; j++ )
2264 COP( c, j, p0[j*cn + c], -- );
2265 COP( c, j, p1[j*cn + c], ++ );
2268 // First column initialization
2269 for( k = 0; k < 16; ++k )
2270 histogram_muladd( 2*r+1, &h_fine[16*n*(16*c+k)], &H[c].fine[k][0] );
2275 for( j = 0; j < 2*r; ++j )
2276 histogram_add_simd( &h_coarse[16*(n*c+j)], H[c].coarse );
2278 for( j = r; j < n-r; j++ )
2280 int t = 2*r*r + 2*r, b, sum = 0;
2283 histogram_add_simd( &h_coarse[16*(n*c + std::min(j+r,n-1))], H[c].coarse );
2285 // Find median at coarse level
2286 for ( k = 0; k < 16 ; ++k )
2288 sum += H[c].coarse[k];
2291 sum -= H[c].coarse[k];
2295 CV_Assert( k < 16 );
2297 /* Update corresponding histogram segment */
2298 if ( luc[c][k] <= j-r )
2300 memset( &H[c].fine[k], 0, 16 * sizeof(HT) );
2301 for ( luc[c][k] = cv::HT(j-r); luc[c][k] < MIN(j+r+1,n); ++luc[c][k] )
2302 histogram_add_simd( &h_fine[16*(n*(16*c+k)+luc[c][k])], H[c].fine[k] );
2304 if ( luc[c][k] < j+r+1 )
2306 histogram_muladd( j+r+1 - n, &h_fine[16*(n*(16*c+k)+(n-1))], &H[c].fine[k][0] );
2307 luc[c][k] = (HT)(j+r+1);
2312 for ( ; luc[c][k] < j+r+1; ++luc[c][k] )
2314 histogram_sub_simd( &h_fine[16*(n*(16*c+k)+MAX(luc[c][k]-2*r-1,0))], H[c].fine[k] );
2315 histogram_add_simd( &h_fine[16*(n*(16*c+k)+MIN(luc[c][k],n-1))], H[c].fine[k] );
2319 histogram_sub_simd( &h_coarse[16*(n*c+MAX(j-r,0))], H[c].coarse );
2321 /* Find median in segment */
2322 segment = H[c].fine[k];
2323 for ( b = 0; b < 16 ; b++ )
2328 dst[dstep*i+cn*j+c] = (uchar)(16*k + b);
2332 CV_Assert( b < 16 );
2338 for( j = 0; j < 2*r; ++j )
2339 histogram_add( &h_coarse[16*(n*c+j)], H[c].coarse );
2341 for( j = r; j < n-r; j++ )
2343 int t = 2*r*r + 2*r, b, sum = 0;
2346 histogram_add( &h_coarse[16*(n*c + std::min(j+r,n-1))], H[c].coarse );
2348 // Find median at coarse level
2349 for ( k = 0; k < 16 ; ++k )
2351 sum += H[c].coarse[k];
2354 sum -= H[c].coarse[k];
2358 CV_Assert( k < 16 );
2360 /* Update corresponding histogram segment */
2361 if ( luc[c][k] <= j-r )
2363 memset( &H[c].fine[k], 0, 16 * sizeof(HT) );
2364 for ( luc[c][k] = cv::HT(j-r); luc[c][k] < MIN(j+r+1,n); ++luc[c][k] )
2365 histogram_add( &h_fine[16*(n*(16*c+k)+luc[c][k])], H[c].fine[k] );
2367 if ( luc[c][k] < j+r+1 )
2369 histogram_muladd( j+r+1 - n, &h_fine[16*(n*(16*c+k)+(n-1))], &H[c].fine[k][0] );
2370 luc[c][k] = (HT)(j+r+1);
2375 for ( ; luc[c][k] < j+r+1; ++luc[c][k] )
2377 histogram_sub( &h_fine[16*(n*(16*c+k)+MAX(luc[c][k]-2*r-1,0))], H[c].fine[k] );
2378 histogram_add( &h_fine[16*(n*(16*c+k)+MIN(luc[c][k],n-1))], H[c].fine[k] );
2382 histogram_sub( &h_coarse[16*(n*c+MAX(j-r,0))], H[c].coarse );
2384 /* Find median in segment */
2385 segment = H[c].fine[k];
2386 for ( b = 0; b < 16 ; b++ )
2391 dst[dstep*i+cn*j+c] = (uchar)(16*k + b);
2395 CV_Assert( b < 16 );
2407 medianBlur_8u_Om( const Mat& _src, Mat& _dst, int m )
2414 Size size = _dst.size();
2415 const uchar* src = _src.ptr();
2416 uchar* dst = _dst.ptr();
2417 int src_step = (int)_src.step, dst_step = (int)_dst.step;
2418 int cn = _src.channels();
2419 const uchar* src_max = src + size.height*src_step;
2420 CV_Assert(cn > 0 && cn <= 4);
2422 #define UPDATE_ACC01( pix, cn, op ) \
2426 zone0[cn][p >> 4] op; \
2429 //CV_Assert( size.height >= nx && size.width >= nx );
2430 for( x = 0; x < size.width; x++, src += cn, dst += cn )
2432 uchar* dst_cur = dst;
2433 const uchar* src_top = src;
2434 const uchar* src_bottom = src;
2436 int src_step1 = src_step, dst_step1 = dst_step;
2440 src_bottom = src_top += src_step*(size.height-1);
2441 dst_cur += dst_step*(size.height-1);
2442 src_step1 = -src_step1;
2443 dst_step1 = -dst_step1;
2447 memset( zone0, 0, sizeof(zone0[0])*cn );
2448 memset( zone1, 0, sizeof(zone1[0])*cn );
2450 for( y = 0; y <= m/2; y++ )
2452 for( c = 0; c < cn; c++ )
2456 for( k = 0; k < m*cn; k += cn )
2457 UPDATE_ACC01( src_bottom[k+c], c, ++ );
2461 for( k = 0; k < m*cn; k += cn )
2462 UPDATE_ACC01( src_bottom[k+c], c, += m/2+1 );
2466 if( (src_step1 > 0 && y < size.height-1) ||
2467 (src_step1 < 0 && size.height-y-1 > 0) )
2468 src_bottom += src_step1;
2471 for( y = 0; y < size.height; y++, dst_cur += dst_step1 )
2474 for( c = 0; c < cn; c++ )
2479 int t = s + zone0[c][k];
2490 dst_cur[c] = (uchar)k;
2493 if( y+1 == size.height )
2498 for( k = 0; k < m; k++ )
2501 int q = src_bottom[k];
2510 for( k = 0; k < m*3; k += 3 )
2512 UPDATE_ACC01( src_top[k], 0, -- );
2513 UPDATE_ACC01( src_top[k+1], 1, -- );
2514 UPDATE_ACC01( src_top[k+2], 2, -- );
2516 UPDATE_ACC01( src_bottom[k], 0, ++ );
2517 UPDATE_ACC01( src_bottom[k+1], 1, ++ );
2518 UPDATE_ACC01( src_bottom[k+2], 2, ++ );
2524 for( k = 0; k < m*4; k += 4 )
2526 UPDATE_ACC01( src_top[k], 0, -- );
2527 UPDATE_ACC01( src_top[k+1], 1, -- );
2528 UPDATE_ACC01( src_top[k+2], 2, -- );
2529 UPDATE_ACC01( src_top[k+3], 3, -- );
2531 UPDATE_ACC01( src_bottom[k], 0, ++ );
2532 UPDATE_ACC01( src_bottom[k+1], 1, ++ );
2533 UPDATE_ACC01( src_bottom[k+2], 2, ++ );
2534 UPDATE_ACC01( src_bottom[k+3], 3, ++ );
2538 if( (src_step1 > 0 && src_bottom + src_step1 < src_max) ||
2539 (src_step1 < 0 && src_bottom + src_step1 >= src) )
2540 src_bottom += src_step1;
2543 src_top += src_step1;
2553 typedef uchar value_type;
2554 typedef int arg_type;
2556 arg_type load(const uchar* ptr) { return *ptr; }
2557 void store(uchar* ptr, arg_type val) { *ptr = (uchar)val; }
2558 void operator()(arg_type& a, arg_type& b) const
2560 int t = CV_FAST_CAST_8U(a - b);
2567 typedef ushort value_type;
2568 typedef int arg_type;
2570 arg_type load(const ushort* ptr) { return *ptr; }
2571 void store(ushort* ptr, arg_type val) { *ptr = (ushort)val; }
2572 void operator()(arg_type& a, arg_type& b) const
2582 typedef short value_type;
2583 typedef int arg_type;
2585 arg_type load(const short* ptr) { return *ptr; }
2586 void store(short* ptr, arg_type val) { *ptr = (short)val; }
2587 void operator()(arg_type& a, arg_type& b) const
2597 typedef float value_type;
2598 typedef float arg_type;
2600 arg_type load(const float* ptr) { return *ptr; }
2601 void store(float* ptr, arg_type val) { *ptr = val; }
2602 void operator()(arg_type& a, arg_type& b) const
2614 typedef uchar value_type;
2615 typedef v_uint8x16 arg_type;
2617 arg_type load(const uchar* ptr) { return v_load(ptr); }
2618 void store(uchar* ptr, const arg_type &val) { v_store(ptr, val); }
2619 void operator()(arg_type& a, arg_type& b) const
2630 typedef ushort value_type;
2631 typedef v_uint16x8 arg_type;
2633 arg_type load(const ushort* ptr) { return v_load(ptr); }
2634 void store(ushort* ptr, const arg_type &val) { v_store(ptr, val); }
2635 void operator()(arg_type& a, arg_type& b) const
2646 typedef short value_type;
2647 typedef v_int16x8 arg_type;
2649 arg_type load(const short* ptr) { return v_load(ptr); }
2650 void store(short* ptr, const arg_type &val) { v_store(ptr, val); }
2651 void operator()(arg_type& a, arg_type& b) const
2662 typedef float value_type;
2663 typedef v_float32x4 arg_type;
2665 arg_type load(const float* ptr) { return v_load(ptr); }
2666 void store(float* ptr, const arg_type &val) { v_store(ptr, val); }
2667 void operator()(arg_type& a, arg_type& b) const
2677 typedef MinMax8u MinMaxVec8u;
2678 typedef MinMax16u MinMaxVec16u;
2679 typedef MinMax16s MinMaxVec16s;
2680 typedef MinMax32f MinMaxVec32f;
2684 template<class Op, class VecOp>
2686 medianBlur_SortNet( const Mat& _src, Mat& _dst, int m )
2688 typedef typename Op::value_type T;
2689 typedef typename Op::arg_type WT;
2690 typedef typename VecOp::arg_type VT;
2692 const T* src = _src.ptr<T>();
2693 T* dst = _dst.ptr<T>();
2694 int sstep = (int)(_src.step/sizeof(T));
2695 int dstep = (int)(_dst.step/sizeof(T));
2696 Size size = _dst.size();
2697 int i, j, k, cn = _src.channels();
2700 volatile bool useSIMD = hasSIMD128();
2704 if( size.width == 1 || size.height == 1 )
2706 int len = size.width + size.height - 1;
2707 int sdelta = size.height == 1 ? cn : sstep;
2708 int sdelta0 = size.height == 1 ? 0 : sstep - cn;
2709 int ddelta = size.height == 1 ? cn : dstep;
2711 for( i = 0; i < len; i++, src += sdelta0, dst += ddelta )
2712 for( j = 0; j < cn; j++, src++ )
2714 WT p0 = src[i > 0 ? -sdelta : 0];
2716 WT p2 = src[i < len - 1 ? sdelta : 0];
2718 op(p0, p1); op(p1, p2); op(p0, p1);
2725 for( i = 0; i < size.height; i++, dst += dstep )
2727 const T* row0 = src + std::max(i - 1, 0)*sstep;
2728 const T* row1 = src + i*sstep;
2729 const T* row2 = src + std::min(i + 1, size.height-1)*sstep;
2730 int limit = useSIMD ? cn : size.width;
2734 for( ; j < limit; j++ )
2736 int j0 = j >= cn ? j - cn : j;
2737 int j2 = j < size.width - cn ? j + cn : j;
2738 WT p0 = row0[j0], p1 = row0[j], p2 = row0[j2];
2739 WT p3 = row1[j0], p4 = row1[j], p5 = row1[j2];
2740 WT p6 = row2[j0], p7 = row2[j], p8 = row2[j2];
2742 op(p1, p2); op(p4, p5); op(p7, p8); op(p0, p1);
2743 op(p3, p4); op(p6, p7); op(p1, p2); op(p4, p5);
2744 op(p7, p8); op(p0, p3); op(p5, p8); op(p4, p7);
2745 op(p3, p6); op(p1, p4); op(p2, p5); op(p4, p7);
2746 op(p4, p2); op(p6, p4); op(p4, p2);
2750 if( limit == size.width )
2753 for( ; j <= size.width - VecOp::SIZE - cn; j += VecOp::SIZE )
2755 VT p0 = vop.load(row0+j-cn), p1 = vop.load(row0+j), p2 = vop.load(row0+j+cn);
2756 VT p3 = vop.load(row1+j-cn), p4 = vop.load(row1+j), p5 = vop.load(row1+j+cn);
2757 VT p6 = vop.load(row2+j-cn), p7 = vop.load(row2+j), p8 = vop.load(row2+j+cn);
2759 vop(p1, p2); vop(p4, p5); vop(p7, p8); vop(p0, p1);
2760 vop(p3, p4); vop(p6, p7); vop(p1, p2); vop(p4, p5);
2761 vop(p7, p8); vop(p0, p3); vop(p5, p8); vop(p4, p7);
2762 vop(p3, p6); vop(p1, p4); vop(p2, p5); vop(p4, p7);
2763 vop(p4, p2); vop(p6, p4); vop(p4, p2);
2764 vop.store(dst+j, p4);
2773 if( size.width == 1 || size.height == 1 )
2775 int len = size.width + size.height - 1;
2776 int sdelta = size.height == 1 ? cn : sstep;
2777 int sdelta0 = size.height == 1 ? 0 : sstep - cn;
2778 int ddelta = size.height == 1 ? cn : dstep;
2780 for( i = 0; i < len; i++, src += sdelta0, dst += ddelta )
2781 for( j = 0; j < cn; j++, src++ )
2783 int i1 = i > 0 ? -sdelta : 0;
2784 int i0 = i > 1 ? -sdelta*2 : i1;
2785 int i3 = i < len-1 ? sdelta : 0;
2786 int i4 = i < len-2 ? sdelta*2 : i3;
2787 WT p0 = src[i0], p1 = src[i1], p2 = src[0], p3 = src[i3], p4 = src[i4];
2789 op(p0, p1); op(p3, p4); op(p2, p3); op(p3, p4); op(p0, p2);
2790 op(p2, p4); op(p1, p3); op(p1, p2);
2797 for( i = 0; i < size.height; i++, dst += dstep )
2800 row[0] = src + std::max(i - 2, 0)*sstep;
2801 row[1] = src + std::max(i - 1, 0)*sstep;
2802 row[2] = src + i*sstep;
2803 row[3] = src + std::min(i + 1, size.height-1)*sstep;
2804 row[4] = src + std::min(i + 2, size.height-1)*sstep;
2805 int limit = useSIMD ? cn*2 : size.width;
2809 for( ; j < limit; j++ )
2812 int j1 = j >= cn ? j - cn : j;
2813 int j0 = j >= cn*2 ? j - cn*2 : j1;
2814 int j3 = j < size.width - cn ? j + cn : j;
2815 int j4 = j < size.width - cn*2 ? j + cn*2 : j3;
2816 for( k = 0; k < 5; k++ )
2818 const T* rowk = row[k];
2819 p[k*5] = rowk[j0]; p[k*5+1] = rowk[j1];
2820 p[k*5+2] = rowk[j]; p[k*5+3] = rowk[j3];
2821 p[k*5+4] = rowk[j4];
2824 op(p[1], p[2]); op(p[0], p[1]); op(p[1], p[2]); op(p[4], p[5]); op(p[3], p[4]);
2825 op(p[4], p[5]); op(p[0], p[3]); op(p[2], p[5]); op(p[2], p[3]); op(p[1], p[4]);
2826 op(p[1], p[2]); op(p[3], p[4]); op(p[7], p[8]); op(p[6], p[7]); op(p[7], p[8]);
2827 op(p[10], p[11]); op(p[9], p[10]); op(p[10], p[11]); op(p[6], p[9]); op(p[8], p[11]);
2828 op(p[8], p[9]); op(p[7], p[10]); op(p[7], p[8]); op(p[9], p[10]); op(p[0], p[6]);
2829 op(p[4], p[10]); op(p[4], p[6]); op(p[2], p[8]); op(p[2], p[4]); op(p[6], p[8]);
2830 op(p[1], p[7]); op(p[5], p[11]); op(p[5], p[7]); op(p[3], p[9]); op(p[3], p[5]);
2831 op(p[7], p[9]); op(p[1], p[2]); op(p[3], p[4]); op(p[5], p[6]); op(p[7], p[8]);
2832 op(p[9], p[10]); op(p[13], p[14]); op(p[12], p[13]); op(p[13], p[14]); op(p[16], p[17]);
2833 op(p[15], p[16]); op(p[16], p[17]); op(p[12], p[15]); op(p[14], p[17]); op(p[14], p[15]);
2834 op(p[13], p[16]); op(p[13], p[14]); op(p[15], p[16]); op(p[19], p[20]); op(p[18], p[19]);
2835 op(p[19], p[20]); op(p[21], p[22]); op(p[23], p[24]); op(p[21], p[23]); op(p[22], p[24]);
2836 op(p[22], p[23]); op(p[18], p[21]); op(p[20], p[23]); op(p[20], p[21]); op(p[19], p[22]);
2837 op(p[22], p[24]); op(p[19], p[20]); op(p[21], p[22]); op(p[23], p[24]); op(p[12], p[18]);
2838 op(p[16], p[22]); op(p[16], p[18]); op(p[14], p[20]); op(p[20], p[24]); op(p[14], p[16]);
2839 op(p[18], p[20]); op(p[22], p[24]); op(p[13], p[19]); op(p[17], p[23]); op(p[17], p[19]);
2840 op(p[15], p[21]); op(p[15], p[17]); op(p[19], p[21]); op(p[13], p[14]); op(p[15], p[16]);
2841 op(p[17], p[18]); op(p[19], p[20]); op(p[21], p[22]); op(p[23], p[24]); op(p[0], p[12]);
2842 op(p[8], p[20]); op(p[8], p[12]); op(p[4], p[16]); op(p[16], p[24]); op(p[12], p[16]);
2843 op(p[2], p[14]); op(p[10], p[22]); op(p[10], p[14]); op(p[6], p[18]); op(p[6], p[10]);
2844 op(p[10], p[12]); op(p[1], p[13]); op(p[9], p[21]); op(p[9], p[13]); op(p[5], p[17]);
2845 op(p[13], p[17]); op(p[3], p[15]); op(p[11], p[23]); op(p[11], p[15]); op(p[7], p[19]);
2846 op(p[7], p[11]); op(p[11], p[13]); op(p[11], p[12]);
2850 if( limit == size.width )
2853 for( ; j <= size.width - VecOp::SIZE - cn*2; j += VecOp::SIZE )
2856 for( k = 0; k < 5; k++ )
2858 const T* rowk = row[k];
2859 p[k*5] = vop.load(rowk+j-cn*2); p[k*5+1] = vop.load(rowk+j-cn);
2860 p[k*5+2] = vop.load(rowk+j); p[k*5+3] = vop.load(rowk+j+cn);
2861 p[k*5+4] = vop.load(rowk+j+cn*2);
2864 vop(p[1], p[2]); vop(p[0], p[1]); vop(p[1], p[2]); vop(p[4], p[5]); vop(p[3], p[4]);
2865 vop(p[4], p[5]); vop(p[0], p[3]); vop(p[2], p[5]); vop(p[2], p[3]); vop(p[1], p[4]);
2866 vop(p[1], p[2]); vop(p[3], p[4]); vop(p[7], p[8]); vop(p[6], p[7]); vop(p[7], p[8]);
2867 vop(p[10], p[11]); vop(p[9], p[10]); vop(p[10], p[11]); vop(p[6], p[9]); vop(p[8], p[11]);
2868 vop(p[8], p[9]); vop(p[7], p[10]); vop(p[7], p[8]); vop(p[9], p[10]); vop(p[0], p[6]);
2869 vop(p[4], p[10]); vop(p[4], p[6]); vop(p[2], p[8]); vop(p[2], p[4]); vop(p[6], p[8]);
2870 vop(p[1], p[7]); vop(p[5], p[11]); vop(p[5], p[7]); vop(p[3], p[9]); vop(p[3], p[5]);
2871 vop(p[7], p[9]); vop(p[1], p[2]); vop(p[3], p[4]); vop(p[5], p[6]); vop(p[7], p[8]);
2872 vop(p[9], p[10]); vop(p[13], p[14]); vop(p[12], p[13]); vop(p[13], p[14]); vop(p[16], p[17]);
2873 vop(p[15], p[16]); vop(p[16], p[17]); vop(p[12], p[15]); vop(p[14], p[17]); vop(p[14], p[15]);
2874 vop(p[13], p[16]); vop(p[13], p[14]); vop(p[15], p[16]); vop(p[19], p[20]); vop(p[18], p[19]);
2875 vop(p[19], p[20]); vop(p[21], p[22]); vop(p[23], p[24]); vop(p[21], p[23]); vop(p[22], p[24]);
2876 vop(p[22], p[23]); vop(p[18], p[21]); vop(p[20], p[23]); vop(p[20], p[21]); vop(p[19], p[22]);
2877 vop(p[22], p[24]); vop(p[19], p[20]); vop(p[21], p[22]); vop(p[23], p[24]); vop(p[12], p[18]);
2878 vop(p[16], p[22]); vop(p[16], p[18]); vop(p[14], p[20]); vop(p[20], p[24]); vop(p[14], p[16]);
2879 vop(p[18], p[20]); vop(p[22], p[24]); vop(p[13], p[19]); vop(p[17], p[23]); vop(p[17], p[19]);
2880 vop(p[15], p[21]); vop(p[15], p[17]); vop(p[19], p[21]); vop(p[13], p[14]); vop(p[15], p[16]);
2881 vop(p[17], p[18]); vop(p[19], p[20]); vop(p[21], p[22]); vop(p[23], p[24]); vop(p[0], p[12]);
2882 vop(p[8], p[20]); vop(p[8], p[12]); vop(p[4], p[16]); vop(p[16], p[24]); vop(p[12], p[16]);
2883 vop(p[2], p[14]); vop(p[10], p[22]); vop(p[10], p[14]); vop(p[6], p[18]); vop(p[6], p[10]);
2884 vop(p[10], p[12]); vop(p[1], p[13]); vop(p[9], p[21]); vop(p[9], p[13]); vop(p[5], p[17]);
2885 vop(p[13], p[17]); vop(p[3], p[15]); vop(p[11], p[23]); vop(p[11], p[15]); vop(p[7], p[19]);
2886 vop(p[7], p[11]); vop(p[11], p[13]); vop(p[11], p[12]);
2887 vop.store(dst+j, p[12]);
2898 static bool ocl_medianFilter(InputArray _src, OutputArray _dst, int m)
2900 size_t localsize[2] = { 16, 16 };
2901 size_t globalsize[2];
2902 int type = _src.type(), depth = CV_MAT_DEPTH(type), cn = CV_MAT_CN(type);
2904 if ( !((depth == CV_8U || depth == CV_16U || depth == CV_16S || depth == CV_32F) && cn <= 4 && (m == 3 || m == 5)) )
2907 Size imgSize = _src.size();
2908 bool useOptimized = (1 == cn) &&
2909 (size_t)imgSize.width >= localsize[0] * 8 &&
2910 (size_t)imgSize.height >= localsize[1] * 8 &&
2911 imgSize.width % 4 == 0 &&
2912 imgSize.height % 4 == 0 &&
2913 (ocl::Device::getDefault().isIntel());
2915 cv::String kname = format( useOptimized ? "medianFilter%d_u" : "medianFilter%d", m) ;
2916 cv::String kdefs = useOptimized ?
2917 format("-D T=%s -D T1=%s -D T4=%s%d -D cn=%d -D USE_4OPT", ocl::typeToStr(type),
2918 ocl::typeToStr(depth), ocl::typeToStr(depth), cn*4, cn)
2920 format("-D T=%s -D T1=%s -D cn=%d", ocl::typeToStr(type), ocl::typeToStr(depth), cn) ;
2922 ocl::Kernel k(kname.c_str(), ocl::imgproc::medianFilter_oclsrc, kdefs.c_str() );
2927 UMat src = _src.getUMat();
2928 _dst.create(src.size(), type);
2929 UMat dst = _dst.getUMat();
2931 k.args(ocl::KernelArg::ReadOnlyNoSize(src), ocl::KernelArg::WriteOnly(dst));
2935 globalsize[0] = DIVUP(src.cols / 4, localsize[0]) * localsize[0];
2936 globalsize[1] = DIVUP(src.rows / 4, localsize[1]) * localsize[1];
2940 globalsize[0] = (src.cols + localsize[0] + 2) / localsize[0] * localsize[0];
2941 globalsize[1] = (src.rows + localsize[1] - 1) / localsize[1] * localsize[1];
2944 return k.run(2, globalsize, localsize, false);
2955 template <> inline bool skipSmallImages<VX_KERNEL_MEDIAN_3x3>(int w, int h) { return w*h < 1280 * 720; }
2957 static bool openvx_medianFilter(InputArray _src, OutputArray _dst, int ksize)
2959 if (_src.type() != CV_8UC1 || _dst.type() != CV_8U
2960 #ifndef VX_VERSION_1_1
2966 Mat src = _src.getMat();
2967 Mat dst = _dst.getMat();
2970 #ifdef VX_VERSION_1_1
2971 ksize != 3 ? ovx::skipSmallImages<VX_KERNEL_NON_LINEAR_FILTER>(src.cols, src.rows) :
2973 ovx::skipSmallImages<VX_KERNEL_MEDIAN_3x3>(src.cols, src.rows)
2979 ivx::Context ctx = ovx::getOpenVXContext();
2980 #ifdef VX_VERSION_1_1
2981 if ((vx_size)ksize > ctx.nonlinearMaxDimension())
2986 if (dst.data != src.data)
2992 ia = ivx::Image::createFromHandle(ctx, VX_DF_IMAGE_U8,
2993 ivx::Image::createAddressing(a.cols, a.rows, 1, (vx_int32)(a.step)), a.data),
2994 ib = ivx::Image::createFromHandle(ctx, VX_DF_IMAGE_U8,
2995 ivx::Image::createAddressing(dst.cols, dst.rows, 1, (vx_int32)(dst.step)), dst.data);
2997 //ATTENTION: VX_CONTEXT_IMMEDIATE_BORDER attribute change could lead to strange issues in multi-threaded environments
2998 //since OpenVX standart says nothing about thread-safety for now
2999 ivx::border_t prevBorder = ctx.immediateBorder();
3000 ctx.setImmediateBorder(VX_BORDER_REPLICATE);
3001 #ifdef VX_VERSION_1_1
3005 ivx::IVX_CHECK_STATUS(vxuMedian3x3(ctx, ia, ib));
3007 #ifdef VX_VERSION_1_1
3012 mtx = ivx::Matrix::createFromPattern(ctx, VX_PATTERN_BOX, ksize, ksize);
3015 vx_size supportedSize;
3016 ivx::IVX_CHECK_STATUS(vxQueryContext(ctx, VX_CONTEXT_NONLINEAR_MAX_DIMENSION, &supportedSize, sizeof(supportedSize)));
3017 if ((vx_size)ksize > supportedSize)
3019 ctx.setImmediateBorder(prevBorder);
3022 Mat mask(ksize, ksize, CV_8UC1, Scalar(255));
3023 mtx = ivx::Matrix::create(ctx, VX_TYPE_UINT8, ksize, ksize);
3026 ivx::IVX_CHECK_STATUS(vxuNonLinearFilter(ctx, VX_NONLINEAR_FILTER_MEDIAN, ia, mtx, ib));
3029 ctx.setImmediateBorder(prevBorder);
3031 catch (ivx::RuntimeError & e)
3033 VX_DbgThrow(e.what());
3035 catch (ivx::WrapperError & e)
3037 VX_DbgThrow(e.what());
3048 static bool ipp_medianFilter(Mat &src0, Mat &dst, int ksize)
3050 CV_INSTRUMENT_REGION_IPP()
3052 #if IPP_VERSION_X100 < 201801
3053 // Degradations for big kernel
3060 IppiSize dstRoiSize = ippiSize(dst.cols, dst.rows), maskSize = ippiSize(ksize, ksize);
3061 IppDataType ippType = ippiGetDataType(src0.type());
3062 int channels = src0.channels();
3063 IppAutoBuffer<Ipp8u> buffer;
3065 if(src0.isSubmatrix())
3069 if(dst.data != src0.data)
3074 if(ippiFilterMedianBorderGetBufferSize(dstRoiSize, maskSize, ippType, channels, &bufSize) < 0)
3077 buffer.allocate(bufSize);
3083 return CV_INSTRUMENT_FUN_IPP(ippiFilterMedianBorder_8u_C1R, src.ptr<Ipp8u>(), (int)src.step, dst.ptr<Ipp8u>(), (int)dst.step, dstRoiSize, maskSize, ippBorderRepl, 0, buffer) >= 0;
3084 else if(channels == 3)
3085 return CV_INSTRUMENT_FUN_IPP(ippiFilterMedianBorder_8u_C3R, src.ptr<Ipp8u>(), (int)src.step, dst.ptr<Ipp8u>(), (int)dst.step, dstRoiSize, maskSize, ippBorderRepl, 0, buffer) >= 0;
3086 else if(channels == 4)
3087 return CV_INSTRUMENT_FUN_IPP(ippiFilterMedianBorder_8u_C4R, src.ptr<Ipp8u>(), (int)src.step, dst.ptr<Ipp8u>(), (int)dst.step, dstRoiSize, maskSize, ippBorderRepl, 0, buffer) >= 0;
3092 return CV_INSTRUMENT_FUN_IPP(ippiFilterMedianBorder_16u_C1R, src.ptr<Ipp16u>(), (int)src.step, dst.ptr<Ipp16u>(), (int)dst.step, dstRoiSize, maskSize, ippBorderRepl, 0, buffer) >= 0;
3093 else if(channels == 3)
3094 return CV_INSTRUMENT_FUN_IPP(ippiFilterMedianBorder_16u_C3R, src.ptr<Ipp16u>(), (int)src.step, dst.ptr<Ipp16u>(), (int)dst.step, dstRoiSize, maskSize, ippBorderRepl, 0, buffer) >= 0;
3095 else if(channels == 4)
3096 return CV_INSTRUMENT_FUN_IPP(ippiFilterMedianBorder_16u_C4R, src.ptr<Ipp16u>(), (int)src.step, dst.ptr<Ipp16u>(), (int)dst.step, dstRoiSize, maskSize, ippBorderRepl, 0, buffer) >= 0;
3101 return CV_INSTRUMENT_FUN_IPP(ippiFilterMedianBorder_16s_C1R, src.ptr<Ipp16s>(), (int)src.step, dst.ptr<Ipp16s>(), (int)dst.step, dstRoiSize, maskSize, ippBorderRepl, 0, buffer) >= 0;
3102 else if(channels == 3)
3103 return CV_INSTRUMENT_FUN_IPP(ippiFilterMedianBorder_16s_C3R, src.ptr<Ipp16s>(), (int)src.step, dst.ptr<Ipp16s>(), (int)dst.step, dstRoiSize, maskSize, ippBorderRepl, 0, buffer) >= 0;
3104 else if(channels == 4)
3105 return CV_INSTRUMENT_FUN_IPP(ippiFilterMedianBorder_16s_C4R, src.ptr<Ipp16s>(), (int)src.step, dst.ptr<Ipp16s>(), (int)dst.step, dstRoiSize, maskSize, ippBorderRepl, 0, buffer) >= 0;
3110 return CV_INSTRUMENT_FUN_IPP(ippiFilterMedianBorder_32f_C1R, src.ptr<Ipp32f>(), (int)src.step, dst.ptr<Ipp32f>(), (int)dst.step, dstRoiSize, maskSize, ippBorderRepl, 0, buffer) >= 0;
3121 void cv::medianBlur( InputArray _src0, OutputArray _dst, int ksize )
3123 CV_INSTRUMENT_REGION()
3125 CV_Assert( (ksize % 2 == 1) && (_src0.dims() <= 2 ));
3127 if( ksize <= 1 || _src0.empty() )
3133 CV_OCL_RUN(_dst.isUMat(),
3134 ocl_medianFilter(_src0,_dst, ksize))
3136 Mat src0 = _src0.getMat();
3137 _dst.create( src0.size(), src0.type() );
3138 Mat dst = _dst.getMat();
3140 CALL_HAL(medianBlur, cv_hal_medianBlur, src0.data, src0.step, dst.data, dst.step, src0.cols, src0.rows, src0.depth(),
3141 src0.channels(), ksize);
3144 openvx_medianFilter(_src0, _dst, ksize))
3146 CV_IPP_RUN_FAST(ipp_medianFilter(src0, dst, ksize));
3148 #ifdef HAVE_TEGRA_OPTIMIZATION
3149 if (tegra::useTegra() && tegra::medianBlur(src0, dst, ksize))
3153 bool useSortNet = ksize == 3 || (ksize == 5
3155 && ( src0.depth() > CV_8U || src0.channels() == 2 || src0.channels() > 4 )
3162 if( dst.data != src0.data )
3167 if( src.depth() == CV_8U )
3168 medianBlur_SortNet<MinMax8u, MinMaxVec8u>( src, dst, ksize );
3169 else if( src.depth() == CV_16U )
3170 medianBlur_SortNet<MinMax16u, MinMaxVec16u>( src, dst, ksize );
3171 else if( src.depth() == CV_16S )
3172 medianBlur_SortNet<MinMax16s, MinMaxVec16s>( src, dst, ksize );
3173 else if( src.depth() == CV_32F )
3174 medianBlur_SortNet<MinMax32f, MinMaxVec32f>( src, dst, ksize );
3176 CV_Error(CV_StsUnsupportedFormat, "");
3182 cv::copyMakeBorder( src0, src, 0, 0, ksize/2, ksize/2, BORDER_REPLICATE|BORDER_ISOLATED);
3184 int cn = src0.channels();
3185 CV_Assert( src.depth() == CV_8U && (cn == 1 || cn == 3 || cn == 4) );
3187 double img_size_mp = (double)(src0.total())/(1 << 20);
3188 if( ksize <= 3 + (img_size_mp < 1 ? 12 : img_size_mp < 4 ? 6 : 2)*
3189 (CV_SIMD128 && hasSIMD128() ? 1 : 3))
3190 medianBlur_8u_Om( src, dst, ksize );
3192 medianBlur_8u_O1( src, dst, ksize );
3196 /****************************************************************************************\
3198 \****************************************************************************************/
3203 class BilateralFilter_8u_Invoker :
3204 public ParallelLoopBody
3207 BilateralFilter_8u_Invoker(Mat& _dest, const Mat& _temp, int _radius, int _maxk,
3208 int* _space_ofs, float *_space_weight, float *_color_weight) :
3209 temp(&_temp), dest(&_dest), radius(_radius),
3210 maxk(_maxk), space_ofs(_space_ofs), space_weight(_space_weight), color_weight(_color_weight)
3214 virtual void operator() (const Range& range) const
3216 int i, j, cn = dest->channels(), k;
3217 Size size = dest->size();
3219 int CV_DECL_ALIGNED(16) buf[4];
3220 bool haveSIMD128 = hasSIMD128();
3223 for( i = range.start; i < range.end; i++ )
3225 const uchar* sptr = temp->ptr(i+radius) + radius*cn;
3226 uchar* dptr = dest->ptr(i);
3230 for( j = 0; j < size.width; j++ )
3232 float sum = 0, wsum = 0;
3238 v_float32x4 _val0 = v_setall_f32(static_cast<float>(val0));
3239 v_float32x4 vsumw = v_setzero_f32();
3240 v_float32x4 vsumc = v_setzero_f32();
3242 for( ; k <= maxk - 4; k += 4 )
3244 v_float32x4 _valF = v_float32x4(sptr[j + space_ofs[k]],
3245 sptr[j + space_ofs[k + 1]],
3246 sptr[j + space_ofs[k + 2]],
3247 sptr[j + space_ofs[k + 3]]);
3248 v_float32x4 _val = v_abs(_valF - _val0);
3249 v_store(buf, v_round(_val));
3251 v_float32x4 _cw = v_float32x4(color_weight[buf[0]],
3252 color_weight[buf[1]],
3253 color_weight[buf[2]],
3254 color_weight[buf[3]]);
3255 v_float32x4 _sw = v_load(space_weight+k);
3256 v_float32x4 _w = _cw * _sw;
3262 float *bufFloat = (float*)buf;
3263 v_float32x4 sum4 = v_reduce_sum4(vsumw, vsumc, vsumw, vsumc);
3264 v_store(bufFloat, sum4);
3266 wsum += bufFloat[0];
3269 for( ; k < maxk; k++ )
3271 int val = sptr[j + space_ofs[k]];
3272 float w = space_weight[k]*color_weight[std::abs(val - val0)];
3276 // overflow is not possible here => there is no need to use cv::saturate_cast
3277 dptr[j] = (uchar)cvRound(sum/wsum);
3283 for( j = 0; j < size.width*3; j += 3 )
3285 float sum_b = 0, sum_g = 0, sum_r = 0, wsum = 0;
3286 int b0 = sptr[j], g0 = sptr[j+1], r0 = sptr[j+2];
3291 v_float32x4 vsumw = v_setzero_f32();
3292 v_float32x4 vsumb = v_setzero_f32();
3293 v_float32x4 vsumg = v_setzero_f32();
3294 v_float32x4 vsumr = v_setzero_f32();
3295 const v_float32x4 _b0 = v_setall_f32(static_cast<float>(b0));
3296 const v_float32x4 _g0 = v_setall_f32(static_cast<float>(g0));
3297 const v_float32x4 _r0 = v_setall_f32(static_cast<float>(r0));
3299 for( ; k <= maxk - 4; k += 4 )
3301 const uchar* const sptr_k0 = sptr + j + space_ofs[k];
3302 const uchar* const sptr_k1 = sptr + j + space_ofs[k+1];
3303 const uchar* const sptr_k2 = sptr + j + space_ofs[k+2];
3304 const uchar* const sptr_k3 = sptr + j + space_ofs[k+3];
3306 v_float32x4 __b = v_cvt_f32(v_reinterpret_as_s32(v_load_expand_q(sptr_k0)));
3307 v_float32x4 __g = v_cvt_f32(v_reinterpret_as_s32(v_load_expand_q(sptr_k1)));
3308 v_float32x4 __r = v_cvt_f32(v_reinterpret_as_s32(v_load_expand_q(sptr_k2)));
3309 v_float32x4 __z = v_cvt_f32(v_reinterpret_as_s32(v_load_expand_q(sptr_k3)));
3310 v_float32x4 _b, _g, _r, _z;
3312 v_transpose4x4(__b, __g, __r, __z, _b, _g, _r, _z);
3314 v_float32x4 bt = v_abs(_b -_b0);
3315 v_float32x4 gt = v_abs(_g -_g0);
3316 v_float32x4 rt = v_abs(_r -_r0);
3319 v_store(buf, v_round(bt));
3321 v_float32x4 _w = v_float32x4(color_weight[buf[0]],color_weight[buf[1]],
3322 color_weight[buf[2]],color_weight[buf[3]]);
3323 v_float32x4 _sw = v_load(space_weight+k);
3335 float *bufFloat = (float*)buf;
3336 v_float32x4 sum4 = v_reduce_sum4(vsumw, vsumb, vsumg, vsumr);
3337 v_store(bufFloat, sum4);
3338 wsum += bufFloat[0];
3339 sum_b += bufFloat[1];
3340 sum_g += bufFloat[2];
3341 sum_r += bufFloat[3];
3345 for( ; k < maxk; k++ )
3347 const uchar* sptr_k = sptr + j + space_ofs[k];
3348 int b = sptr_k[0], g = sptr_k[1], r = sptr_k[2];
3349 float w = space_weight[k]*color_weight[std::abs(b - b0) +
3350 std::abs(g - g0) + std::abs(r - r0)];
3351 sum_b += b*w; sum_g += g*w; sum_r += r*w;
3355 b0 = cvRound(sum_b*wsum);
3356 g0 = cvRound(sum_g*wsum);
3357 r0 = cvRound(sum_r*wsum);
3358 dptr[j] = (uchar)b0; dptr[j+1] = (uchar)g0; dptr[j+2] = (uchar)r0;
3367 int radius, maxk, *space_ofs;
3368 float *space_weight, *color_weight;
3373 static bool ocl_bilateralFilter_8u(InputArray _src, OutputArray _dst, int d,
3374 double sigma_color, double sigma_space,
3378 if (ocl::Device::getDefault().isNVidia())
3382 int type = _src.type(), depth = CV_MAT_DEPTH(type), cn = CV_MAT_CN(type);
3383 int i, j, maxk, radius;
3385 if (depth != CV_8U || cn > 4)
3388 if (sigma_color <= 0)
3390 if (sigma_space <= 0)
3393 double gauss_color_coeff = -0.5 / (sigma_color * sigma_color);
3394 double gauss_space_coeff = -0.5 / (sigma_space * sigma_space);
3397 radius = cvRound(sigma_space * 1.5);
3400 radius = MAX(radius, 1);
3403 UMat src = _src.getUMat(), dst = _dst.getUMat(), temp;
3407 copyMakeBorder(src, temp, radius, radius, radius, radius, borderType);
3408 std::vector<float> _space_weight(d * d);
3409 std::vector<int> _space_ofs(d * d);
3410 float * const space_weight = &_space_weight[0];
3411 int * const space_ofs = &_space_ofs[0];
3413 // initialize space-related bilateral filter coefficients
3414 for( i = -radius, maxk = 0; i <= radius; i++ )
3415 for( j = -radius; j <= radius; j++ )
3417 double r = std::sqrt((double)i * i + (double)j * j);
3420 space_weight[maxk] = (float)std::exp(r * r * gauss_space_coeff);
3421 space_ofs[maxk++] = (int)(i * temp.step + j * cn);
3425 String cnstr = cn > 1 ? format("%d", cn) : "";
3426 String kernelName("bilateral");
3428 if ((ocl::Device::getDefault().isIntel()) &&
3429 (ocl::Device::getDefault().type() == ocl::Device::TYPE_GPU))
3432 if (dst.cols % 4 == 0 && cn == 1) // For single channel x4 sized images.
3434 kernelName = "bilateral_float4";
3438 ocl::Kernel k(kernelName.c_str(), ocl::imgproc::bilateral_oclsrc,
3439 format("-D radius=%d -D maxk=%d -D cn=%d -D int_t=%s -D uint_t=uint%s -D convert_int_t=%s"
3440 " -D uchar_t=%s -D float_t=%s -D convert_float_t=%s -D convert_uchar_t=%s -D gauss_color_coeff=(float)%f",
3441 radius, maxk, cn, ocl::typeToStr(CV_32SC(cn)), cnstr.c_str(),
3442 ocl::convertTypeStr(CV_8U, CV_32S, cn, cvt[0]),
3443 ocl::typeToStr(type), ocl::typeToStr(CV_32FC(cn)),
3444 ocl::convertTypeStr(CV_32S, CV_32F, cn, cvt[1]),
3445 ocl::convertTypeStr(CV_32F, CV_8U, cn, cvt[2]), gauss_color_coeff));
3449 Mat mspace_weight(1, d * d, CV_32FC1, space_weight);
3450 Mat mspace_ofs(1, d * d, CV_32SC1, space_ofs);
3451 UMat ucolor_weight, uspace_weight, uspace_ofs;
3453 mspace_weight.copyTo(uspace_weight);
3454 mspace_ofs.copyTo(uspace_ofs);
3456 k.args(ocl::KernelArg::ReadOnlyNoSize(temp), ocl::KernelArg::WriteOnly(dst),
3457 ocl::KernelArg::PtrReadOnly(uspace_weight),
3458 ocl::KernelArg::PtrReadOnly(uspace_ofs));
3460 size_t globalsize[2] = { (size_t)dst.cols / sizeDiv, (size_t)dst.rows };
3461 return k.run(2, globalsize, NULL, false);
3466 bilateralFilter_8u( const Mat& src, Mat& dst, int d,
3467 double sigma_color, double sigma_space,
3470 int cn = src.channels();
3471 int i, j, maxk, radius;
3472 Size size = src.size();
3474 CV_Assert( (src.type() == CV_8UC1 || src.type() == CV_8UC3) && src.data != dst.data );
3476 if( sigma_color <= 0 )
3478 if( sigma_space <= 0 )
3481 double gauss_color_coeff = -0.5/(sigma_color*sigma_color);
3482 double gauss_space_coeff = -0.5/(sigma_space*sigma_space);
3485 radius = cvRound(sigma_space*1.5);
3488 radius = MAX(radius, 1);
3492 copyMakeBorder( src, temp, radius, radius, radius, radius, borderType );
3494 std::vector<float> _color_weight(cn*256);
3495 std::vector<float> _space_weight(d*d);
3496 std::vector<int> _space_ofs(d*d);
3497 float* color_weight = &_color_weight[0];
3498 float* space_weight = &_space_weight[0];
3499 int* space_ofs = &_space_ofs[0];
3501 // initialize color-related bilateral filter coefficients
3503 for( i = 0; i < 256*cn; i++ )
3504 color_weight[i] = (float)std::exp(i*i*gauss_color_coeff);
3506 // initialize space-related bilateral filter coefficients
3507 for( i = -radius, maxk = 0; i <= radius; i++ )
3511 for( ; j <= radius; j++ )
3513 double r = std::sqrt((double)i*i + (double)j*j);
3516 space_weight[maxk] = (float)std::exp(r*r*gauss_space_coeff);
3517 space_ofs[maxk++] = (int)(i*temp.step + j*cn);
3521 BilateralFilter_8u_Invoker body(dst, temp, radius, maxk, space_ofs, space_weight, color_weight);
3522 parallel_for_(Range(0, size.height), body, dst.total()/(double)(1<<16));
3526 class BilateralFilter_32f_Invoker :
3527 public ParallelLoopBody
3531 BilateralFilter_32f_Invoker(int _cn, int _radius, int _maxk, int *_space_ofs,
3532 const Mat& _temp, Mat& _dest, float _scale_index, float *_space_weight, float *_expLUT) :
3533 cn(_cn), radius(_radius), maxk(_maxk), space_ofs(_space_ofs),
3534 temp(&_temp), dest(&_dest), scale_index(_scale_index), space_weight(_space_weight), expLUT(_expLUT)
3538 virtual void operator() (const Range& range) const
3541 Size size = dest->size();
3543 int CV_DECL_ALIGNED(16) idxBuf[4];
3544 bool haveSIMD128 = hasSIMD128();
3547 for( i = range.start; i < range.end; i++ )
3549 const float* sptr = temp->ptr<float>(i+radius) + radius*cn;
3550 float* dptr = dest->ptr<float>(i);
3554 for( j = 0; j < size.width; j++ )
3556 float sum = 0, wsum = 0;
3557 float val0 = sptr[j];
3562 v_float32x4 vecwsum = v_setzero_f32();
3563 v_float32x4 vecvsum = v_setzero_f32();
3564 const v_float32x4 _val0 = v_setall_f32(sptr[j]);
3565 const v_float32x4 _scale_index = v_setall_f32(scale_index);
3567 for (; k <= maxk - 4; k += 4)
3569 v_float32x4 _sw = v_load(space_weight + k);
3570 v_float32x4 _val = v_float32x4(sptr[j + space_ofs[k]],
3571 sptr[j + space_ofs[k + 1]],
3572 sptr[j + space_ofs[k + 2]],
3573 sptr[j + space_ofs[k + 3]]);
3574 v_float32x4 _alpha = v_abs(_val - _val0) * _scale_index;
3576 v_int32x4 _idx = v_round(_alpha);
3577 v_store(idxBuf, _idx);
3578 _alpha -= v_cvt_f32(_idx);
3580 v_float32x4 _explut = v_float32x4(expLUT[idxBuf[0]],
3584 v_float32x4 _explut1 = v_float32x4(expLUT[idxBuf[0] + 1],
3585 expLUT[idxBuf[1] + 1],
3586 expLUT[idxBuf[2] + 1],
3587 expLUT[idxBuf[3] + 1]);
3589 v_float32x4 _w = _sw * (_explut + (_alpha * (_explut1 - _explut)));
3595 float *bufFloat = (float*)idxBuf;
3596 v_float32x4 sum4 = v_reduce_sum4(vecwsum, vecvsum, vecwsum, vecvsum);
3597 v_store(bufFloat, sum4);
3599 wsum += bufFloat[0];
3603 for( ; k < maxk; k++ )
3605 float val = sptr[j + space_ofs[k]];
3606 float alpha = (float)(std::abs(val - val0)*scale_index);
3607 int idx = cvFloor(alpha);
3609 float w = space_weight[k]*(expLUT[idx] + alpha*(expLUT[idx+1] - expLUT[idx]));
3613 dptr[j] = (float)(sum/wsum);
3618 CV_Assert( cn == 3 );
3619 for( j = 0; j < size.width*3; j += 3 )
3621 float sum_b = 0, sum_g = 0, sum_r = 0, wsum = 0;
3622 float b0 = sptr[j], g0 = sptr[j+1], r0 = sptr[j+2];
3627 v_float32x4 sumw = v_setzero_f32();
3628 v_float32x4 sumb = v_setzero_f32();
3629 v_float32x4 sumg = v_setzero_f32();
3630 v_float32x4 sumr = v_setzero_f32();
3631 const v_float32x4 _b0 = v_setall_f32(b0);
3632 const v_float32x4 _g0 = v_setall_f32(g0);
3633 const v_float32x4 _r0 = v_setall_f32(r0);
3634 const v_float32x4 _scale_index = v_setall_f32(scale_index);
3636 for( ; k <= maxk-4; k += 4 )
3638 v_float32x4 _sw = v_load(space_weight + k);
3640 const float* const sptr_k0 = sptr + j + space_ofs[k];
3641 const float* const sptr_k1 = sptr + j + space_ofs[k+1];
3642 const float* const sptr_k2 = sptr + j + space_ofs[k+2];
3643 const float* const sptr_k3 = sptr + j + space_ofs[k+3];
3645 v_float32x4 _v0 = v_load(sptr_k0);
3646 v_float32x4 _v1 = v_load(sptr_k1);
3647 v_float32x4 _v2 = v_load(sptr_k2);
3648 v_float32x4 _v3 = v_load(sptr_k3);
3649 v_float32x4 _b, _g, _r, _dummy;
3651 v_transpose4x4(_v0, _v1, _v2, _v3, _b, _g, _r, _dummy);
3653 v_float32x4 _bt = v_abs(_b - _b0);
3654 v_float32x4 _gt = v_abs(_g - _g0);
3655 v_float32x4 _rt = v_abs(_r - _r0);
3656 v_float32x4 _alpha = _scale_index * (_bt + _gt + _rt);
3658 v_int32x4 _idx = v_round(_alpha);
3659 v_store((int*)idxBuf, _idx);
3660 _alpha -= v_cvt_f32(_idx);
3662 v_float32x4 _explut = v_float32x4(expLUT[idxBuf[0]],
3666 v_float32x4 _explut1 = v_float32x4(expLUT[idxBuf[0] + 1],
3667 expLUT[idxBuf[1] + 1],
3668 expLUT[idxBuf[2] + 1],
3669 expLUT[idxBuf[3] + 1]);
3671 v_float32x4 _w = _sw * (_explut + (_alpha * (_explut1 - _explut)));
3681 v_float32x4 sum4 = v_reduce_sum4(sumw, sumb, sumg, sumr);
3682 float *bufFloat = (float*)idxBuf;
3683 v_store(bufFloat, sum4);
3684 wsum += bufFloat[0];
3685 sum_b += bufFloat[1];
3686 sum_g += bufFloat[2];
3687 sum_r += bufFloat[3];
3691 for(; k < maxk; k++ )
3693 const float* sptr_k = sptr + j + space_ofs[k];
3694 float b = sptr_k[0], g = sptr_k[1], r = sptr_k[2];
3695 float alpha = (float)((std::abs(b - b0) +
3696 std::abs(g - g0) + std::abs(r - r0))*scale_index);
3697 int idx = cvFloor(alpha);
3699 float w = space_weight[k]*(expLUT[idx] + alpha*(expLUT[idx+1] - expLUT[idx]));
3700 sum_b += b*w; sum_g += g*w; sum_r += r*w;
3707 dptr[j] = b0; dptr[j+1] = g0; dptr[j+2] = r0;
3714 int cn, radius, maxk, *space_ofs;
3717 float scale_index, *space_weight, *expLUT;
3722 bilateralFilter_32f( const Mat& src, Mat& dst, int d,
3723 double sigma_color, double sigma_space,
3726 int cn = src.channels();
3727 int i, j, maxk, radius;
3728 double minValSrc=-1, maxValSrc=1;
3729 const int kExpNumBinsPerChannel = 1 << 12;
3730 int kExpNumBins = 0;
3731 float lastExpVal = 1.f;
3732 float len, scale_index;
3733 Size size = src.size();
3735 CV_Assert( (src.type() == CV_32FC1 || src.type() == CV_32FC3) && src.data != dst.data );
3737 if( sigma_color <= 0 )
3739 if( sigma_space <= 0 )
3742 double gauss_color_coeff = -0.5/(sigma_color*sigma_color);
3743 double gauss_space_coeff = -0.5/(sigma_space*sigma_space);
3746 radius = cvRound(sigma_space*1.5);
3749 radius = MAX(radius, 1);
3751 // compute the min/max range for the input image (even if multichannel)
3753 minMaxLoc( src.reshape(1), &minValSrc, &maxValSrc );
3754 if(std::abs(minValSrc - maxValSrc) < FLT_EPSILON)
3760 // temporary copy of the image with borders for easy processing
3762 copyMakeBorder( src, temp, radius, radius, radius, radius, borderType );
3763 const double insteadNaNValue = -5. * sigma_color;
3764 patchNaNs( temp, insteadNaNValue ); // this replacement of NaNs makes the assumption that depth values are nonnegative
3765 // TODO: make insteadNaNValue avalible in the outside function interface to control the cases breaking the assumption
3766 // allocate lookup tables
3767 std::vector<float> _space_weight(d*d);
3768 std::vector<int> _space_ofs(d*d);
3769 float* space_weight = &_space_weight[0];
3770 int* space_ofs = &_space_ofs[0];
3772 // assign a length which is slightly more than needed
3773 len = (float)(maxValSrc - minValSrc) * cn;
3774 kExpNumBins = kExpNumBinsPerChannel * cn;
3775 std::vector<float> _expLUT(kExpNumBins+2);
3776 float* expLUT = &_expLUT[0];
3778 scale_index = kExpNumBins/len;
3780 // initialize the exp LUT
3781 for( i = 0; i < kExpNumBins+2; i++ )
3783 if( lastExpVal > 0.f )
3785 double val = i / scale_index;
3786 expLUT[i] = (float)std::exp(val * val * gauss_color_coeff);
3787 lastExpVal = expLUT[i];
3793 // initialize space-related bilateral filter coefficients
3794 for( i = -radius, maxk = 0; i <= radius; i++ )
3795 for( j = -radius; j <= radius; j++ )
3797 double r = std::sqrt((double)i*i + (double)j*j);
3800 space_weight[maxk] = (float)std::exp(r*r*gauss_space_coeff);
3801 space_ofs[maxk++] = (int)(i*(temp.step/sizeof(float)) + j*cn);
3804 // parallel_for usage
3806 BilateralFilter_32f_Invoker body(cn, radius, maxk, space_ofs, temp, dst, scale_index, space_weight, expLUT);
3807 parallel_for_(Range(0, size.height), body, dst.total()/(double)(1<<16));
3811 #define IPP_BILATERAL_PARALLEL 1
3814 class ipp_bilateralFilterParallel: public ParallelLoopBody
3817 ipp_bilateralFilterParallel(::ipp::IwiImage &_src, ::ipp::IwiImage &_dst, int _radius, Ipp32f _valSquareSigma, Ipp32f _posSquareSigma, ::ipp::IwiBorderType _borderType, bool *_ok):
3818 src(_src), dst(_dst)
3823 valSquareSigma = _valSquareSigma;
3824 posSquareSigma = _posSquareSigma;
3825 borderType = _borderType;
3829 ~ipp_bilateralFilterParallel() {}
3831 virtual void operator() (const Range& range) const
3838 ::ipp::IwiTile tile = ::ipp::IwiRoi(0, range.start, dst.m_size.width, range.end - range.start);
3839 CV_INSTRUMENT_FUN_IPP(::ipp::iwiFilterBilateral, src, dst, radius, valSquareSigma, posSquareSigma, ::ipp::IwDefault(), borderType, tile);
3841 catch(::ipp::IwException)
3848 ::ipp::IwiImage &src;
3849 ::ipp::IwiImage &dst;
3852 Ipp32f valSquareSigma;
3853 Ipp32f posSquareSigma;
3854 ::ipp::IwiBorderType borderType;
3857 const ipp_bilateralFilterParallel& operator= (const ipp_bilateralFilterParallel&);
3861 static bool ipp_bilateralFilter(Mat &src, Mat &dst, int d, double sigmaColor, double sigmaSpace, int borderType)
3864 CV_INSTRUMENT_REGION_IPP()
3866 int radius = IPP_MAX(((d <= 0)?cvRound(sigmaSpace*1.5):d/2), 1);
3867 Ipp32f valSquareSigma = (Ipp32f)((sigmaColor <= 0)?1:sigmaColor*sigmaColor);
3868 Ipp32f posSquareSigma = (Ipp32f)((sigmaSpace <= 0)?1:sigmaSpace*sigmaSpace);
3870 // Acquire data and begin processing
3873 ::ipp::IwiImage iwSrc = ippiGetImage(src);
3874 ::ipp::IwiImage iwDst = ippiGetImage(dst);
3875 ::ipp::IwiBorderSize borderSize(radius);
3876 ::ipp::IwiBorderType ippBorder(ippiGetBorder(iwSrc, borderType, borderSize));
3880 const int threads = ippiSuggestThreadsNum(iwDst, 2);
3881 if(IPP_BILATERAL_PARALLEL && threads > 1) {
3883 Range range(0, (int)iwDst.m_size.height);
3884 ipp_bilateralFilterParallel invoker(iwSrc, iwDst, radius, valSquareSigma, posSquareSigma, ippBorder, &ok);
3888 parallel_for_(range, invoker, threads*4);
3893 CV_INSTRUMENT_FUN_IPP(::ipp::iwiFilterBilateral, iwSrc, iwDst, radius, valSquareSigma, posSquareSigma, ::ipp::IwDefault(), ippBorder);
3896 catch (::ipp::IwException)
3902 CV_UNUSED(src); CV_UNUSED(dst); CV_UNUSED(d); CV_UNUSED(sigmaColor); CV_UNUSED(sigmaSpace); CV_UNUSED(borderType);
3910 void cv::bilateralFilter( InputArray _src, OutputArray _dst, int d,
3911 double sigmaColor, double sigmaSpace,
3914 CV_INSTRUMENT_REGION()
3916 _dst.create( _src.size(), _src.type() );
3918 CV_OCL_RUN(_src.dims() <= 2 && _dst.isUMat(),
3919 ocl_bilateralFilter_8u(_src, _dst, d, sigmaColor, sigmaSpace, borderType))
3921 Mat src = _src.getMat(), dst = _dst.getMat();
3923 CV_IPP_RUN_FAST(ipp_bilateralFilter(src, dst, d, sigmaColor, sigmaSpace, borderType));
3925 if( src.depth() == CV_8U )
3926 bilateralFilter_8u( src, dst, d, sigmaColor, sigmaSpace, borderType );
3927 else if( src.depth() == CV_32F )
3928 bilateralFilter_32f( src, dst, d, sigmaColor, sigmaSpace, borderType );
3930 CV_Error( CV_StsUnsupportedFormat,
3931 "Bilateral filtering is only implemented for 8u and 32f images" );
3934 //////////////////////////////////////////////////////////////////////////////////////////
3937 cvSmooth( const void* srcarr, void* dstarr, int smooth_type,
3938 int param1, int param2, double param3, double param4 )
3940 cv::Mat src = cv::cvarrToMat(srcarr), dst0 = cv::cvarrToMat(dstarr), dst = dst0;
3942 CV_Assert( dst.size() == src.size() &&
3943 (smooth_type == CV_BLUR_NO_SCALE || dst.type() == src.type()) );
3948 if( smooth_type == CV_BLUR || smooth_type == CV_BLUR_NO_SCALE )
3949 cv::boxFilter( src, dst, dst.depth(), cv::Size(param1, param2), cv::Point(-1,-1),
3950 smooth_type == CV_BLUR, cv::BORDER_REPLICATE );
3951 else if( smooth_type == CV_GAUSSIAN )
3952 cv::GaussianBlur( src, dst, cv::Size(param1, param2), param3, param4, cv::BORDER_REPLICATE );
3953 else if( smooth_type == CV_MEDIAN )
3954 cv::medianBlur( src, dst, param1 );
3956 cv::bilateralFilter( src, dst, param1, param3, param4, cv::BORDER_REPLICATE );
3958 if( dst.data != dst0.data )
3959 CV_Error( CV_StsUnmatchedFormats, "The destination image does not have the proper type" );