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"
51 * This file includes the code, contributed by Simon Perreault
52 * (the function icvMedianBlur_8u_O1)
54 * Constant-time median filtering -- http://nomis80.org/ctmf.html
55 * Copyright (C) 2006 Simon Perreault
58 * Laboratoire de vision et systemes numeriques
59 * Pavillon Adrien-Pouliot
61 * Sainte-Foy, Quebec, Canada
64 * perreaul@gel.ulaval.ca
70 /****************************************************************************************\
72 \****************************************************************************************/
74 template<typename T, typename ST>
78 RowSum( int _ksize, int _anchor ) :
85 virtual void operator()(const uchar* src, uchar* dst, int width, int cn)
87 const T* S = (const T*)src;
89 int i = 0, k, ksz_cn = ksize*cn;
91 width = (width - 1)*cn;
94 for( i = 0; i < width + cn; i++ )
96 D[i] = (ST)S[i] + (ST)S[i+cn] + (ST)S[i+cn*2];
101 for( i = 0; i < width + cn; i++ )
103 D[i] = (ST)S[i] + (ST)S[i+cn] + (ST)S[i+cn*2] + (ST)S[i + cn*3] + (ST)S[i + cn*4];
109 for( i = 0; i < ksz_cn; i++ )
112 for( i = 0; i < width; i++ )
114 s += (ST)S[i + ksz_cn] - (ST)S[i];
120 ST s0 = 0, s1 = 0, s2 = 0;
121 for( i = 0; i < ksz_cn; i += 3 )
130 for( i = 0; i < width; i += 3 )
132 s0 += (ST)S[i + ksz_cn] - (ST)S[i];
133 s1 += (ST)S[i + ksz_cn + 1] - (ST)S[i + 1];
134 s2 += (ST)S[i + ksz_cn + 2] - (ST)S[i + 2];
142 ST s0 = 0, s1 = 0, s2 = 0, s3 = 0;
143 for( i = 0; i < ksz_cn; i += 4 )
154 for( i = 0; i < width; i += 4 )
156 s0 += (ST)S[i + ksz_cn] - (ST)S[i];
157 s1 += (ST)S[i + ksz_cn + 1] - (ST)S[i + 1];
158 s2 += (ST)S[i + ksz_cn + 2] - (ST)S[i + 2];
159 s3 += (ST)S[i + ksz_cn + 3] - (ST)S[i + 3];
167 for( k = 0; k < cn; k++, S++, D++ )
170 for( i = 0; i < ksz_cn; i += cn )
173 for( i = 0; i < width; i += cn )
175 s += (ST)S[i + ksz_cn] - (ST)S[i];
183 template<typename ST, typename T>
185 public BaseColumnFilter
187 ColumnSum( int _ksize, int _anchor, double _scale ) :
196 virtual void reset() { sumCount = 0; }
198 virtual void operator()(const uchar** src, uchar* dst, int dststep, int count, int width)
202 bool haveScale = scale != 1;
203 double _scale = scale;
205 if( width != (int)sum.size() )
214 memset((void*)SUM, 0, width*sizeof(ST));
216 for( ; sumCount < ksize - 1; sumCount++, src++ )
218 const ST* Sp = (const ST*)src[0];
220 for( i = 0; i < width; i++ )
226 CV_Assert( sumCount == ksize-1 );
230 for( ; count--; src++ )
232 const ST* Sp = (const ST*)src[0];
233 const ST* Sm = (const ST*)src[1-ksize];
237 for( i = 0; i <= width - 2; i += 2 )
239 ST s0 = SUM[i] + Sp[i], s1 = SUM[i+1] + Sp[i+1];
240 D[i] = saturate_cast<T>(s0*_scale);
241 D[i+1] = saturate_cast<T>(s1*_scale);
242 s0 -= Sm[i]; s1 -= Sm[i+1];
243 SUM[i] = s0; SUM[i+1] = s1;
246 for( ; i < width; i++ )
248 ST s0 = SUM[i] + Sp[i];
249 D[i] = saturate_cast<T>(s0*_scale);
255 for( i = 0; i <= width - 2; i += 2 )
257 ST s0 = SUM[i] + Sp[i], s1 = SUM[i+1] + Sp[i+1];
258 D[i] = saturate_cast<T>(s0);
259 D[i+1] = saturate_cast<T>(s1);
260 s0 -= Sm[i]; s1 -= Sm[i+1];
261 SUM[i] = s0; SUM[i+1] = s1;
264 for( ; i < width; i++ )
266 ST s0 = SUM[i] + Sp[i];
267 D[i] = saturate_cast<T>(s0);
282 struct ColumnSum<int, uchar> :
283 public BaseColumnFilter
285 ColumnSum( int _ksize, int _anchor, double _scale ) :
294 virtual void reset() { sumCount = 0; }
296 virtual void operator()(const uchar** src, uchar* dst, int dststep, int count, int width)
299 bool haveScale = scale != 1;
300 double _scale = scale;
303 bool haveSIMD128 = hasSIMD128();
306 if( width != (int)sum.size() )
315 memset((void*)SUM, 0, width*sizeof(int));
316 for( ; sumCount < ksize - 1; sumCount++, src++ )
318 const int* Sp = (const int*)src[0];
323 for (; i <= width - 4; i += 4)
325 v_store(SUM + i, v_load(SUM + i) + v_load(Sp + i));
329 for( ; i < width; i++ )
335 CV_Assert( sumCount == ksize-1 );
339 for( ; count--; src++ )
341 const int* Sp = (const int*)src[0];
342 const int* Sm = (const int*)src[1-ksize];
343 uchar* D = (uchar*)dst;
351 v_float32x4 v_scale = v_setall_f32((float)_scale);
352 for( ; i <= width-8; i+=8 )
354 v_int32x4 v_s0 = v_load(SUM + i) + v_load(Sp + i);
355 v_int32x4 v_s01 = v_load(SUM + i + 4) + v_load(Sp + i + 4);
357 v_uint32x4 v_s0d = v_reinterpret_as_u32(v_round(v_cvt_f32(v_s0) * v_scale));
358 v_uint32x4 v_s01d = v_reinterpret_as_u32(v_round(v_cvt_f32(v_s01) * v_scale));
360 v_uint16x8 v_dst = v_pack(v_s0d, v_s01d);
361 v_pack_store(D + i, v_dst);
363 v_store(SUM + i, v_s0 - v_load(Sm + i));
364 v_store(SUM + i + 4, v_s01 - v_load(Sm + i + 4));
368 for( ; i < width; i++ )
370 int s0 = SUM[i] + Sp[i];
371 D[i] = saturate_cast<uchar>(s0*_scale);
381 for( ; i <= width-8; i+=8 )
383 v_int32x4 v_s0 = v_load(SUM + i) + v_load(Sp + i);
384 v_int32x4 v_s01 = v_load(SUM + i + 4) + v_load(Sp + i + 4);
386 v_uint16x8 v_dst = v_pack(v_reinterpret_as_u32(v_s0), v_reinterpret_as_u32(v_s01));
387 v_pack_store(D + i, v_dst);
389 v_store(SUM + i, v_s0 - v_load(Sm + i));
390 v_store(SUM + i + 4, v_s01 - v_load(Sm + i + 4));
395 for( ; i < width; i++ )
397 int s0 = SUM[i] + Sp[i];
398 D[i] = saturate_cast<uchar>(s0);
408 std::vector<int> sum;
413 struct ColumnSum<ushort, uchar> :
414 public BaseColumnFilter
418 ColumnSum( int _ksize, int _anchor, double _scale ) :
429 int d = cvRound(1./scale);
430 double scalef = ((double)(1 << SHIFT))/d;
431 divScale = cvFloor(scalef);
441 virtual void reset() { sumCount = 0; }
443 virtual void operator()(const uchar** src, uchar* dst, int dststep, int count, int width)
445 const int ds = divScale;
446 const int dd = divDelta;
448 const bool haveScale = scale != 1;
451 bool haveSIMD128 = hasSIMD128();
454 if( width != (int)sum.size() )
463 memset((void*)SUM, 0, width*sizeof(SUM[0]));
464 for( ; sumCount < ksize - 1; sumCount++, src++ )
466 const ushort* Sp = (const ushort*)src[0];
471 for( ; i <= width - 8; i += 8 )
473 v_store(SUM + i, v_load(SUM + i) + v_load(Sp + i));
477 for( ; i < width; i++ )
483 CV_Assert( sumCount == ksize-1 );
487 for( ; count--; src++ )
489 const ushort* Sp = (const ushort*)src[0];
490 const ushort* Sm = (const ushort*)src[1-ksize];
491 uchar* D = (uchar*)dst;
496 v_uint32x4 ds4 = v_setall_u32((unsigned)ds);
497 v_uint16x8 dd8 = v_setall_u16((ushort)dd);
499 for( ; i <= width-16; i+=16 )
501 v_uint16x8 _sm0 = v_load(Sm + i);
502 v_uint16x8 _sm1 = v_load(Sm + i + 8);
504 v_uint16x8 _s0 = v_add_wrap(v_load(SUM + i), v_load(Sp + i));
505 v_uint16x8 _s1 = v_add_wrap(v_load(SUM + i + 8), v_load(Sp + i + 8));
507 v_uint32x4 _s00, _s01, _s10, _s11;
509 v_expand(_s0 + dd8, _s00, _s01);
510 v_expand(_s1 + dd8, _s10, _s11);
512 _s00 = v_shr<SHIFT>(_s00*ds4);
513 _s01 = v_shr<SHIFT>(_s01*ds4);
514 _s10 = v_shr<SHIFT>(_s10*ds4);
515 _s11 = v_shr<SHIFT>(_s11*ds4);
517 v_int16x8 r0 = v_pack(v_reinterpret_as_s32(_s00), v_reinterpret_as_s32(_s01));
518 v_int16x8 r1 = v_pack(v_reinterpret_as_s32(_s10), v_reinterpret_as_s32(_s11));
520 _s0 = v_sub_wrap(_s0, _sm0);
521 _s1 = v_sub_wrap(_s1, _sm1);
523 v_store(D + i, v_pack_u(r0, r1));
524 v_store(SUM + i, _s0);
525 v_store(SUM + i + 8, _s1);
528 for( ; i < width; i++ )
530 int s0 = SUM[i] + Sp[i];
531 D[i] = (uchar)((s0 + dd)*ds >> SHIFT);
532 SUM[i] = (ushort)(s0 - Sm[i]);
538 for( ; i < width; i++ )
540 int s0 = SUM[i] + Sp[i];
541 D[i] = saturate_cast<uchar>(s0);
542 SUM[i] = (ushort)(s0 - Sm[i]);
553 std::vector<ushort> sum;
558 struct ColumnSum<int, short> :
559 public BaseColumnFilter
561 ColumnSum( int _ksize, int _anchor, double _scale ) :
570 virtual void reset() { sumCount = 0; }
572 virtual void operator()(const uchar** src, uchar* dst, int dststep, int count, int width)
576 bool haveScale = scale != 1;
577 double _scale = scale;
580 bool haveSIMD128 = hasSIMD128();
583 if( width != (int)sum.size() )
592 memset((void*)SUM, 0, width*sizeof(int));
593 for( ; sumCount < ksize - 1; sumCount++, src++ )
595 const int* Sp = (const int*)src[0];
600 for( ; i <= width - 4; i+=4 )
602 v_store(SUM + i, v_load(SUM + i) + v_load(Sp + i));
606 for( ; i < width; i++ )
612 CV_Assert( sumCount == ksize-1 );
616 for( ; count--; src++ )
618 const int* Sp = (const int*)src[0];
619 const int* Sm = (const int*)src[1-ksize];
620 short* D = (short*)dst;
627 v_float32x4 v_scale = v_setall_f32((float)_scale);
628 for( ; i <= width-8; i+=8 )
630 v_int32x4 v_s0 = v_load(SUM + i) + v_load(Sp + i);
631 v_int32x4 v_s01 = v_load(SUM + i + 4) + v_load(Sp + i + 4);
633 v_int32x4 v_s0d = v_round(v_cvt_f32(v_s0) * v_scale);
634 v_int32x4 v_s01d = v_round(v_cvt_f32(v_s01) * v_scale);
635 v_store(D + i, v_pack(v_s0d, v_s01d));
637 v_store(SUM + i, v_s0 - v_load(Sm + i));
638 v_store(SUM + i + 4, v_s01 - v_load(Sm + i + 4));
642 for( ; i < width; i++ )
644 int s0 = SUM[i] + Sp[i];
645 D[i] = saturate_cast<short>(s0*_scale);
655 for( ; i <= width-8; i+=8 )
657 v_int32x4 v_s0 = v_load(SUM + i) + v_load(Sp + i);
658 v_int32x4 v_s01 = v_load(SUM + i + 4) + v_load(Sp + i + 4);
660 v_store(D + i, v_pack(v_s0, v_s01));
662 v_store(SUM + i, v_s0 - v_load(Sm + i));
663 v_store(SUM + i + 4, v_s01 - v_load(Sm + i + 4));
668 for( ; i < width; i++ )
670 int s0 = SUM[i] + Sp[i];
671 D[i] = saturate_cast<short>(s0);
681 std::vector<int> sum;
686 struct ColumnSum<int, ushort> :
687 public BaseColumnFilter
689 ColumnSum( int _ksize, int _anchor, double _scale ) :
698 virtual void reset() { sumCount = 0; }
700 virtual void operator()(const uchar** src, uchar* dst, int dststep, int count, int width)
703 bool haveScale = scale != 1;
704 double _scale = scale;
707 bool haveSIMD128 = hasSIMD128();
710 if( width != (int)sum.size() )
719 memset((void*)SUM, 0, width*sizeof(int));
720 for( ; sumCount < ksize - 1; sumCount++, src++ )
722 const int* Sp = (const int*)src[0];
727 for (; i <= width - 4; i += 4)
729 v_store(SUM + i, v_load(SUM + i) + v_load(Sp + i));
733 for( ; i < width; i++ )
739 CV_Assert( sumCount == ksize-1 );
743 for( ; count--; src++ )
745 const int* Sp = (const int*)src[0];
746 const int* Sm = (const int*)src[1-ksize];
747 ushort* D = (ushort*)dst;
754 v_float32x4 v_scale = v_setall_f32((float)_scale);
755 for( ; i <= width-8; i+=8 )
757 v_int32x4 v_s0 = v_load(SUM + i) + v_load(Sp + i);
758 v_int32x4 v_s01 = v_load(SUM + i + 4) + v_load(Sp + i + 4);
760 v_uint32x4 v_s0d = v_reinterpret_as_u32(v_round(v_cvt_f32(v_s0) * v_scale));
761 v_uint32x4 v_s01d = v_reinterpret_as_u32(v_round(v_cvt_f32(v_s01) * v_scale));
762 v_store(D + i, v_pack(v_s0d, v_s01d));
764 v_store(SUM + i, v_s0 - v_load(Sm + i));
765 v_store(SUM + i + 4, v_s01 - v_load(Sm + i + 4));
769 for( ; i < width; i++ )
771 int s0 = SUM[i] + Sp[i];
772 D[i] = saturate_cast<ushort>(s0*_scale);
782 for( ; i <= width-8; i+=8 )
784 v_int32x4 v_s0 = v_load(SUM + i) + v_load(Sp + i);
785 v_int32x4 v_s01 = v_load(SUM + i + 4) + v_load(Sp + i + 4);
787 v_store(D + i, v_pack(v_reinterpret_as_u32(v_s0), v_reinterpret_as_u32(v_s01)));
789 v_store(SUM + i, v_s0 - v_load(Sm + i));
790 v_store(SUM + i + 4, v_s01 - v_load(Sm + i + 4));
794 for( ; i < width; i++ )
796 int s0 = SUM[i] + Sp[i];
797 D[i] = saturate_cast<ushort>(s0);
807 std::vector<int> sum;
811 struct ColumnSum<int, int> :
812 public BaseColumnFilter
814 ColumnSum( int _ksize, int _anchor, double _scale ) :
823 virtual void reset() { sumCount = 0; }
825 virtual void operator()(const uchar** src, uchar* dst, int dststep, int count, int width)
828 bool haveScale = scale != 1;
829 double _scale = scale;
832 bool haveSIMD128 = hasSIMD128();
835 if( width != (int)sum.size() )
844 memset((void*)SUM, 0, width*sizeof(int));
845 for( ; sumCount < ksize - 1; sumCount++, src++ )
847 const int* Sp = (const int*)src[0];
852 for( ; i <= width - 4; i+=4 )
854 v_store(SUM + i, v_load(SUM + i) + v_load(Sp + i));
858 for( ; i < width; i++ )
864 CV_Assert( sumCount == ksize-1 );
868 for( ; count--; src++ )
870 const int* Sp = (const int*)src[0];
871 const int* Sm = (const int*)src[1-ksize];
879 v_float32x4 v_scale = v_setall_f32((float)_scale);
880 for( ; i <= width-4; i+=4 )
882 v_int32x4 v_s0 = v_load(SUM + i) + v_load(Sp + i);
883 v_int32x4 v_s0d = v_round(v_cvt_f32(v_s0) * v_scale);
885 v_store(D + i, v_s0d);
886 v_store(SUM + i, v_s0 - v_load(Sm + i));
890 for( ; i < width; i++ )
892 int s0 = SUM[i] + Sp[i];
893 D[i] = saturate_cast<int>(s0*_scale);
903 for( ; i <= width-4; i+=4 )
905 v_int32x4 v_s0 = v_load(SUM + i) + v_load(Sp + i);
907 v_store(D + i, v_s0);
908 v_store(SUM + i, v_s0 - v_load(Sm + i));
912 for( ; i < width; i++ )
914 int s0 = SUM[i] + Sp[i];
925 std::vector<int> sum;
930 struct ColumnSum<int, float> :
931 public BaseColumnFilter
933 ColumnSum( int _ksize, int _anchor, double _scale ) :
942 virtual void reset() { sumCount = 0; }
944 virtual void operator()(const uchar** src, uchar* dst, int dststep, int count, int width)
947 bool haveScale = scale != 1;
948 double _scale = scale;
951 bool haveSIMD128 = hasSIMD128();
954 if( width != (int)sum.size() )
963 memset((void*)SUM, 0, width*sizeof(int));
964 for( ; sumCount < ksize - 1; sumCount++, src++ )
966 const int* Sp = (const int*)src[0];
971 for( ; i <= width - 4; i+=4 )
973 v_store(SUM + i, v_load(SUM + i) + v_load(Sp + i));
978 for( ; i < width; i++ )
984 CV_Assert( sumCount == ksize-1 );
988 for( ; count--; src++ )
990 const int * Sp = (const int*)src[0];
991 const int * Sm = (const int*)src[1-ksize];
992 float* D = (float*)dst;
1000 v_float32x4 v_scale = v_setall_f32((float)_scale);
1001 for (; i <= width - 8; i += 8)
1003 v_int32x4 v_s0 = v_load(SUM + i) + v_load(Sp + i);
1004 v_int32x4 v_s01 = v_load(SUM + i + 4) + v_load(Sp + i + 4);
1006 v_store(D + i, v_cvt_f32(v_s0) * v_scale);
1007 v_store(D + i + 4, v_cvt_f32(v_s01) * v_scale);
1009 v_store(SUM + i, v_s0 - v_load(Sm + i));
1010 v_store(SUM + i + 4, v_s01 - v_load(Sm + i + 4));
1014 for( ; i < width; i++ )
1016 int s0 = SUM[i] + Sp[i];
1017 D[i] = (float)(s0*_scale);
1018 SUM[i] = s0 - Sm[i];
1028 for( ; i <= width-8; i+=8 )
1030 v_int32x4 v_s0 = v_load(SUM + i) + v_load(Sp + i);
1031 v_int32x4 v_s01 = v_load(SUM + i + 4) + v_load(Sp + i + 4);
1033 v_store(D + i, v_cvt_f32(v_s0));
1034 v_store(D + i + 4, v_cvt_f32(v_s01));
1036 v_store(SUM + i, v_s0 - v_load(Sm + i));
1037 v_store(SUM + i + 4, v_s01 - v_load(Sm + i + 4));
1041 for( ; i < width; i++ )
1043 int s0 = SUM[i] + Sp[i];
1045 SUM[i] = s0 - Sm[i];
1054 std::vector<int> sum;
1059 static bool ocl_boxFilter3x3_8UC1( InputArray _src, OutputArray _dst, int ddepth,
1060 Size ksize, Point anchor, int borderType, bool normalize )
1062 const ocl::Device & dev = ocl::Device::getDefault();
1063 int type = _src.type(), sdepth = CV_MAT_DEPTH(type), cn = CV_MAT_CN(type);
1069 anchor.x = ksize.width / 2;
1071 anchor.y = ksize.height / 2;
1073 if ( !(dev.isIntel() && (type == CV_8UC1) &&
1074 (_src.offset() == 0) && (_src.step() % 4 == 0) &&
1075 (_src.cols() % 16 == 0) && (_src.rows() % 2 == 0) &&
1076 (anchor.x == 1) && (anchor.y == 1) &&
1077 (ksize.width == 3) && (ksize.height == 3)) )
1080 float alpha = 1.0f / (ksize.height * ksize.width);
1081 Size size = _src.size();
1082 size_t globalsize[2] = { 0, 0 };
1083 size_t localsize[2] = { 0, 0 };
1084 const char * const borderMap[] = { "BORDER_CONSTANT", "BORDER_REPLICATE", "BORDER_REFLECT", 0, "BORDER_REFLECT_101" };
1086 globalsize[0] = size.width / 16;
1087 globalsize[1] = size.height / 2;
1089 char build_opts[1024];
1090 sprintf(build_opts, "-D %s %s", borderMap[borderType], normalize ? "-D NORMALIZE" : "");
1092 ocl::Kernel kernel("boxFilter3x3_8UC1_cols16_rows2", cv::ocl::imgproc::boxFilter3x3_oclsrc, build_opts);
1096 UMat src = _src.getUMat();
1097 _dst.create(size, CV_MAKETYPE(ddepth, cn));
1098 if (!(_dst.offset() == 0 && _dst.step() % 4 == 0))
1100 UMat dst = _dst.getUMat();
1102 int idxArg = kernel.set(0, ocl::KernelArg::PtrReadOnly(src));
1103 idxArg = kernel.set(idxArg, (int)src.step);
1104 idxArg = kernel.set(idxArg, ocl::KernelArg::PtrWriteOnly(dst));
1105 idxArg = kernel.set(idxArg, (int)dst.step);
1106 idxArg = kernel.set(idxArg, (int)dst.rows);
1107 idxArg = kernel.set(idxArg, (int)dst.cols);
1109 idxArg = kernel.set(idxArg, (float)alpha);
1111 return kernel.run(2, globalsize, (localsize[0] == 0) ? NULL : localsize, false);
1114 #define DIVUP(total, grain) ((total + grain - 1) / (grain))
1115 #define ROUNDUP(sz, n) ((sz) + (n) - 1 - (((sz) + (n) - 1) % (n)))
1117 static bool ocl_boxFilter( InputArray _src, OutputArray _dst, int ddepth,
1118 Size ksize, Point anchor, int borderType, bool normalize, bool sqr = false )
1120 const ocl::Device & dev = ocl::Device::getDefault();
1121 int type = _src.type(), sdepth = CV_MAT_DEPTH(type), cn = CV_MAT_CN(type), esz = CV_ELEM_SIZE(type);
1122 bool doubleSupport = dev.doubleFPConfig() > 0;
1127 if (cn > 4 || (!doubleSupport && (sdepth == CV_64F || ddepth == CV_64F)) ||
1128 _src.offset() % esz != 0 || _src.step() % esz != 0)
1132 anchor.x = ksize.width / 2;
1134 anchor.y = ksize.height / 2;
1136 int computeUnits = ocl::Device::getDefault().maxComputeUnits();
1137 float alpha = 1.0f / (ksize.height * ksize.width);
1138 Size size = _src.size(), wholeSize;
1139 bool isolated = (borderType & BORDER_ISOLATED) != 0;
1140 borderType &= ~BORDER_ISOLATED;
1141 int wdepth = std::max(CV_32F, std::max(ddepth, sdepth)),
1142 wtype = CV_MAKE_TYPE(wdepth, cn), dtype = CV_MAKE_TYPE(ddepth, cn);
1144 const char * const borderMap[] = { "BORDER_CONSTANT", "BORDER_REPLICATE", "BORDER_REFLECT", 0, "BORDER_REFLECT_101" };
1145 size_t globalsize[2] = { (size_t)size.width, (size_t)size.height };
1146 size_t localsize_general[2] = { 0, 1 }, * localsize = NULL;
1148 UMat src = _src.getUMat();
1152 src.locateROI(wholeSize, ofs);
1155 int h = isolated ? size.height : wholeSize.height;
1156 int w = isolated ? size.width : wholeSize.width;
1158 size_t maxWorkItemSizes[32];
1159 ocl::Device::getDefault().maxWorkItemSizes(maxWorkItemSizes);
1160 int tryWorkItems = (int)maxWorkItemSizes[0];
1164 if (dev.isIntel() && !(dev.type() & ocl::Device::TYPE_CPU) &&
1165 ((ksize.width < 5 && ksize.height < 5 && esz <= 4) ||
1166 (ksize.width == 5 && ksize.height == 5 && cn == 1)))
1168 if (w < ksize.width || h < ksize.height)
1171 // Figure out what vector size to use for loading the pixels.
1172 int pxLoadNumPixels = cn != 1 || size.width % 4 ? 1 : 4;
1173 int pxLoadVecSize = cn * pxLoadNumPixels;
1175 // Figure out how many pixels per work item to compute in X and Y
1176 // directions. Too many and we run out of registers.
1177 int pxPerWorkItemX = 1, pxPerWorkItemY = 1;
1178 if (cn <= 2 && ksize.width <= 4 && ksize.height <= 4)
1180 pxPerWorkItemX = size.width % 8 ? size.width % 4 ? size.width % 2 ? 1 : 2 : 4 : 8;
1181 pxPerWorkItemY = size.height % 2 ? 1 : 2;
1183 else if (cn < 4 || (ksize.width <= 4 && ksize.height <= 4))
1185 pxPerWorkItemX = size.width % 2 ? 1 : 2;
1186 pxPerWorkItemY = size.height % 2 ? 1 : 2;
1188 globalsize[0] = size.width / pxPerWorkItemX;
1189 globalsize[1] = size.height / pxPerWorkItemY;
1191 // Need some padding in the private array for pixels
1192 int privDataWidth = ROUNDUP(pxPerWorkItemX + ksize.width - 1, pxLoadNumPixels);
1194 // Make the global size a nice round number so the runtime can pick
1195 // from reasonable choices for the workgroup size
1196 const int wgRound = 256;
1197 globalsize[0] = ROUNDUP(globalsize[0], wgRound);
1199 char build_options[1024], cvt[2][40];
1200 sprintf(build_options, "-D cn=%d "
1201 "-D ANCHOR_X=%d -D ANCHOR_Y=%d -D KERNEL_SIZE_X=%d -D KERNEL_SIZE_Y=%d "
1202 "-D PX_LOAD_VEC_SIZE=%d -D PX_LOAD_NUM_PX=%d "
1203 "-D PX_PER_WI_X=%d -D PX_PER_WI_Y=%d -D PRIV_DATA_WIDTH=%d -D %s -D %s "
1204 "-D PX_LOAD_X_ITERATIONS=%d -D PX_LOAD_Y_ITERATIONS=%d "
1205 "-D srcT=%s -D srcT1=%s -D dstT=%s -D dstT1=%s -D WT=%s -D WT1=%s "
1206 "-D convertToWT=%s -D convertToDstT=%s%s%s -D PX_LOAD_FLOAT_VEC_CONV=convert_%s -D OP_BOX_FILTER",
1207 cn, anchor.x, anchor.y, ksize.width, ksize.height,
1208 pxLoadVecSize, pxLoadNumPixels,
1209 pxPerWorkItemX, pxPerWorkItemY, privDataWidth, borderMap[borderType],
1210 isolated ? "BORDER_ISOLATED" : "NO_BORDER_ISOLATED",
1211 privDataWidth / pxLoadNumPixels, pxPerWorkItemY + ksize.height - 1,
1212 ocl::typeToStr(type), ocl::typeToStr(sdepth), ocl::typeToStr(dtype),
1213 ocl::typeToStr(ddepth), ocl::typeToStr(wtype), ocl::typeToStr(wdepth),
1214 ocl::convertTypeStr(sdepth, wdepth, cn, cvt[0]),
1215 ocl::convertTypeStr(wdepth, ddepth, cn, cvt[1]),
1216 normalize ? " -D NORMALIZE" : "", sqr ? " -D SQR" : "",
1217 ocl::typeToStr(CV_MAKE_TYPE(wdepth, pxLoadVecSize)) //PX_LOAD_FLOAT_VEC_CONV
1221 if (!kernel.create("filterSmall", cv::ocl::imgproc::filterSmall_oclsrc, build_options))
1226 localsize = localsize_general;
1229 int BLOCK_SIZE_X = tryWorkItems, BLOCK_SIZE_Y = std::min(ksize.height * 10, size.height);
1231 while (BLOCK_SIZE_X > 32 && BLOCK_SIZE_X >= ksize.width * 2 && BLOCK_SIZE_X > size.width * 2)
1233 while (BLOCK_SIZE_Y < BLOCK_SIZE_X / 8 && BLOCK_SIZE_Y * computeUnits * 32 < size.height)
1236 if (ksize.width > BLOCK_SIZE_X || w < ksize.width || h < ksize.height)
1240 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"
1241 " -D ANCHOR_X=%d -D ANCHOR_Y=%d -D KERNEL_SIZE_X=%d -D KERNEL_SIZE_Y=%d -D %s%s%s%s%s"
1242 " -D ST1=%s -D DT1=%s -D cn=%d",
1243 BLOCK_SIZE_X, BLOCK_SIZE_Y, ocl::typeToStr(type), ocl::typeToStr(CV_MAKE_TYPE(ddepth, cn)),
1244 ocl::typeToStr(CV_MAKE_TYPE(wdepth, cn)),
1245 ocl::convertTypeStr(wdepth, ddepth, cn, cvt[0]),
1246 ocl::convertTypeStr(sdepth, wdepth, cn, cvt[1]),
1247 anchor.x, anchor.y, ksize.width, ksize.height, borderMap[borderType],
1248 isolated ? " -D BORDER_ISOLATED" : "", doubleSupport ? " -D DOUBLE_SUPPORT" : "",
1249 normalize ? " -D NORMALIZE" : "", sqr ? " -D SQR" : "",
1250 ocl::typeToStr(sdepth), ocl::typeToStr(ddepth), cn);
1252 localsize[0] = BLOCK_SIZE_X;
1253 globalsize[0] = DIVUP(size.width, BLOCK_SIZE_X - (ksize.width - 1)) * BLOCK_SIZE_X;
1254 globalsize[1] = DIVUP(size.height, BLOCK_SIZE_Y);
1256 kernel.create("boxFilter", cv::ocl::imgproc::boxFilter_oclsrc, opts);
1260 size_t kernelWorkGroupSize = kernel.workGroupSize();
1261 if (localsize[0] <= kernelWorkGroupSize)
1263 if (BLOCK_SIZE_X < (int)kernelWorkGroupSize)
1266 tryWorkItems = (int)kernelWorkGroupSize;
1270 _dst.create(size, CV_MAKETYPE(ddepth, cn));
1271 UMat dst = _dst.getUMat();
1273 int idxArg = kernel.set(0, ocl::KernelArg::PtrReadOnly(src));
1274 idxArg = kernel.set(idxArg, (int)src.step);
1275 int srcOffsetX = (int)((src.offset % src.step) / src.elemSize());
1276 int srcOffsetY = (int)(src.offset / src.step);
1277 int srcEndX = isolated ? srcOffsetX + size.width : wholeSize.width;
1278 int srcEndY = isolated ? srcOffsetY + size.height : wholeSize.height;
1279 idxArg = kernel.set(idxArg, srcOffsetX);
1280 idxArg = kernel.set(idxArg, srcOffsetY);
1281 idxArg = kernel.set(idxArg, srcEndX);
1282 idxArg = kernel.set(idxArg, srcEndY);
1283 idxArg = kernel.set(idxArg, ocl::KernelArg::WriteOnly(dst));
1285 idxArg = kernel.set(idxArg, (float)alpha);
1287 return kernel.run(2, globalsize, localsize, false);
1297 cv::Ptr<cv::BaseRowFilter> cv::getRowSumFilter(int srcType, int sumType, int ksize, int anchor)
1299 int sdepth = CV_MAT_DEPTH(srcType), ddepth = CV_MAT_DEPTH(sumType);
1300 CV_Assert( CV_MAT_CN(sumType) == CV_MAT_CN(srcType) );
1305 if( sdepth == CV_8U && ddepth == CV_32S )
1306 return makePtr<RowSum<uchar, int> >(ksize, anchor);
1307 if( sdepth == CV_8U && ddepth == CV_16U )
1308 return makePtr<RowSum<uchar, ushort> >(ksize, anchor);
1309 if( sdepth == CV_8U && ddepth == CV_64F )
1310 return makePtr<RowSum<uchar, double> >(ksize, anchor);
1311 if( sdepth == CV_16U && ddepth == CV_32S )
1312 return makePtr<RowSum<ushort, int> >(ksize, anchor);
1313 if( sdepth == CV_16U && ddepth == CV_64F )
1314 return makePtr<RowSum<ushort, double> >(ksize, anchor);
1315 if( sdepth == CV_16S && ddepth == CV_32S )
1316 return makePtr<RowSum<short, int> >(ksize, anchor);
1317 if( sdepth == CV_32S && ddepth == CV_32S )
1318 return makePtr<RowSum<int, int> >(ksize, anchor);
1319 if( sdepth == CV_16S && ddepth == CV_64F )
1320 return makePtr<RowSum<short, double> >(ksize, anchor);
1321 if( sdepth == CV_32F && ddepth == CV_64F )
1322 return makePtr<RowSum<float, double> >(ksize, anchor);
1323 if( sdepth == CV_64F && ddepth == CV_64F )
1324 return makePtr<RowSum<double, double> >(ksize, anchor);
1326 CV_Error_( CV_StsNotImplemented,
1327 ("Unsupported combination of source format (=%d), and buffer format (=%d)",
1330 return Ptr<BaseRowFilter>();
1334 cv::Ptr<cv::BaseColumnFilter> cv::getColumnSumFilter(int sumType, int dstType, int ksize,
1335 int anchor, double scale)
1337 int sdepth = CV_MAT_DEPTH(sumType), ddepth = CV_MAT_DEPTH(dstType);
1338 CV_Assert( CV_MAT_CN(sumType) == CV_MAT_CN(dstType) );
1343 if( ddepth == CV_8U && sdepth == CV_32S )
1344 return makePtr<ColumnSum<int, uchar> >(ksize, anchor, scale);
1345 if( ddepth == CV_8U && sdepth == CV_16U )
1346 return makePtr<ColumnSum<ushort, uchar> >(ksize, anchor, scale);
1347 if( ddepth == CV_8U && sdepth == CV_64F )
1348 return makePtr<ColumnSum<double, uchar> >(ksize, anchor, scale);
1349 if( ddepth == CV_16U && sdepth == CV_32S )
1350 return makePtr<ColumnSum<int, ushort> >(ksize, anchor, scale);
1351 if( ddepth == CV_16U && sdepth == CV_64F )
1352 return makePtr<ColumnSum<double, ushort> >(ksize, anchor, scale);
1353 if( ddepth == CV_16S && sdepth == CV_32S )
1354 return makePtr<ColumnSum<int, short> >(ksize, anchor, scale);
1355 if( ddepth == CV_16S && sdepth == CV_64F )
1356 return makePtr<ColumnSum<double, short> >(ksize, anchor, scale);
1357 if( ddepth == CV_32S && sdepth == CV_32S )
1358 return makePtr<ColumnSum<int, int> >(ksize, anchor, scale);
1359 if( ddepth == CV_32F && sdepth == CV_32S )
1360 return makePtr<ColumnSum<int, float> >(ksize, anchor, scale);
1361 if( ddepth == CV_32F && sdepth == CV_64F )
1362 return makePtr<ColumnSum<double, float> >(ksize, anchor, scale);
1363 if( ddepth == CV_64F && sdepth == CV_32S )
1364 return makePtr<ColumnSum<int, double> >(ksize, anchor, scale);
1365 if( ddepth == CV_64F && sdepth == CV_64F )
1366 return makePtr<ColumnSum<double, double> >(ksize, anchor, scale);
1368 CV_Error_( CV_StsNotImplemented,
1369 ("Unsupported combination of sum format (=%d), and destination format (=%d)",
1372 return Ptr<BaseColumnFilter>();
1376 cv::Ptr<cv::FilterEngine> cv::createBoxFilter( int srcType, int dstType, Size ksize,
1377 Point anchor, bool normalize, int borderType )
1379 int sdepth = CV_MAT_DEPTH(srcType);
1380 int cn = CV_MAT_CN(srcType), sumType = CV_64F;
1381 if( sdepth == CV_8U && CV_MAT_DEPTH(dstType) == CV_8U &&
1382 ksize.width*ksize.height <= 256 )
1384 else if( sdepth <= CV_32S && (!normalize ||
1385 ksize.width*ksize.height <= (sdepth == CV_8U ? (1<<23) :
1386 sdepth == CV_16U ? (1 << 15) : (1 << 16))) )
1388 sumType = CV_MAKETYPE( sumType, cn );
1390 Ptr<BaseRowFilter> rowFilter = getRowSumFilter(srcType, sumType, ksize.width, anchor.x );
1391 Ptr<BaseColumnFilter> columnFilter = getColumnSumFilter(sumType,
1392 dstType, ksize.height, anchor.y, normalize ? 1./(ksize.width*ksize.height) : 1);
1394 return makePtr<FilterEngine>(Ptr<BaseFilter>(), rowFilter, columnFilter,
1395 srcType, dstType, sumType, borderType );
1402 template <> inline bool skipSmallImages<VX_KERNEL_BOX_3x3>(int w, int h) { return w*h < 640 * 480; }
1404 static bool openvx_boxfilter(InputArray _src, OutputArray _dst, int ddepth,
1405 Size ksize, Point anchor,
1406 bool normalize, int borderType)
1410 if (_src.type() != CV_8UC1 || ddepth != CV_8U || !normalize ||
1411 _src.cols() < 3 || _src.rows() < 3 ||
1412 ksize.width != 3 || ksize.height != 3 ||
1413 (anchor.x >= 0 && anchor.x != 1) ||
1414 (anchor.y >= 0 && anchor.y != 1) ||
1415 ovx::skipSmallImages<VX_KERNEL_BOX_3x3>(_src.cols(), _src.rows()))
1418 Mat src = _src.getMat();
1420 if ((borderType & BORDER_ISOLATED) == 0 && src.isSubmatrix())
1421 return false; //Process isolated borders only
1423 switch (borderType & ~BORDER_ISOLATED)
1425 case BORDER_CONSTANT:
1426 border = VX_BORDER_CONSTANT;
1428 case BORDER_REPLICATE:
1429 border = VX_BORDER_REPLICATE;
1435 _dst.create(src.size(), CV_8UC1);
1436 Mat dst = _dst.getMat();
1440 ivx::Context ctx = ovx::getOpenVXContext();
1443 if (dst.data != src.data)
1449 ia = ivx::Image::createFromHandle(ctx, VX_DF_IMAGE_U8,
1450 ivx::Image::createAddressing(a.cols, a.rows, 1, (vx_int32)(a.step)), a.data),
1451 ib = ivx::Image::createFromHandle(ctx, VX_DF_IMAGE_U8,
1452 ivx::Image::createAddressing(dst.cols, dst.rows, 1, (vx_int32)(dst.step)), dst.data);
1454 //ATTENTION: VX_CONTEXT_IMMEDIATE_BORDER attribute change could lead to strange issues in multi-threaded environments
1455 //since OpenVX standart says nothing about thread-safety for now
1456 ivx::border_t prevBorder = ctx.immediateBorder();
1457 ctx.setImmediateBorder(border, (vx_uint8)(0));
1458 ivx::IVX_CHECK_STATUS(vxuBox3x3(ctx, ia, ib));
1459 ctx.setImmediateBorder(prevBorder);
1461 catch (ivx::RuntimeError & e)
1463 VX_DbgThrow(e.what());
1465 catch (ivx::WrapperError & e)
1467 VX_DbgThrow(e.what());
1475 #if defined(HAVE_IPP)
1478 static bool ipp_boxfilter(Mat &src, Mat &dst, Size ksize, Point anchor, bool normalize, int borderType)
1481 CV_INSTRUMENT_REGION_IPP()
1483 #if IPP_VERSION_X100 < 201801
1484 // Problem with SSE42 optimization for 16s and some 8u modes
1485 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))))
1488 // Other optimizations has some degradations too
1489 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))))
1496 if(!ippiCheckAnchor(anchor, ksize))
1501 ::ipp::IwiImage iwSrc = ippiGetImage(src);
1502 ::ipp::IwiImage iwDst = ippiGetImage(dst);
1503 ::ipp::IwiSize iwKSize = ippiGetSize(ksize);
1504 ::ipp::IwiBorderSize borderSize(iwKSize);
1505 ::ipp::IwiBorderType ippBorder(ippiGetBorder(iwSrc, borderType, borderSize));
1509 CV_INSTRUMENT_FUN_IPP(::ipp::iwiFilterBox, iwSrc, iwDst, iwKSize, ::ipp::IwDefault(), ippBorder);
1511 catch (::ipp::IwException)
1518 CV_UNUSED(src); CV_UNUSED(dst); CV_UNUSED(ksize); CV_UNUSED(anchor); CV_UNUSED(normalize); CV_UNUSED(borderType);
1526 void cv::boxFilter( InputArray _src, OutputArray _dst, int ddepth,
1527 Size ksize, Point anchor,
1528 bool normalize, int borderType )
1530 CV_INSTRUMENT_REGION()
1532 CV_OCL_RUN(_dst.isUMat() &&
1533 (borderType == BORDER_REPLICATE || borderType == BORDER_CONSTANT ||
1534 borderType == BORDER_REFLECT || borderType == BORDER_REFLECT_101),
1535 ocl_boxFilter3x3_8UC1(_src, _dst, ddepth, ksize, anchor, borderType, normalize))
1537 CV_OCL_RUN(_dst.isUMat(), ocl_boxFilter(_src, _dst, ddepth, ksize, anchor, borderType, normalize))
1540 openvx_boxfilter(_src, _dst, ddepth, ksize, anchor, normalize, borderType))
1542 Mat src = _src.getMat();
1543 int stype = src.type(), sdepth = CV_MAT_DEPTH(stype), cn = CV_MAT_CN(stype);
1546 _dst.create( src.size(), CV_MAKETYPE(ddepth, cn) );
1547 Mat dst = _dst.getMat();
1548 if( borderType != BORDER_CONSTANT && normalize && (borderType & BORDER_ISOLATED) != 0 )
1555 #ifdef HAVE_TEGRA_OPTIMIZATION
1556 if ( tegra::useTegra() && tegra::box(src, dst, ksize, anchor, normalize, borderType) )
1560 CV_IPP_RUN_FAST(ipp_boxfilter(src, dst, ksize, anchor, normalize, borderType));
1563 Size wsz(src.cols, src.rows);
1564 if(!(borderType&BORDER_ISOLATED))
1565 src.locateROI( wsz, ofs );
1566 borderType = (borderType&~BORDER_ISOLATED);
1568 Ptr<FilterEngine> f = createBoxFilter( src.type(), dst.type(),
1569 ksize, anchor, normalize, borderType );
1571 f->apply( src, dst, wsz, ofs );
1575 void cv::blur( InputArray src, OutputArray dst,
1576 Size ksize, Point anchor, int borderType )
1578 CV_INSTRUMENT_REGION()
1580 boxFilter( src, dst, -1, ksize, anchor, true, borderType );
1584 /****************************************************************************************\
1586 \****************************************************************************************/
1591 template<typename T, typename ST>
1593 public BaseRowFilter
1595 SqrRowSum( int _ksize, int _anchor ) :
1602 virtual void operator()(const uchar* src, uchar* dst, int width, int cn)
1604 const T* S = (const T*)src;
1606 int i = 0, k, ksz_cn = ksize*cn;
1608 width = (width - 1)*cn;
1609 for( k = 0; k < cn; k++, S++, D++ )
1612 for( i = 0; i < ksz_cn; i += cn )
1618 for( i = 0; i < width; i += cn )
1620 ST val0 = (ST)S[i], val1 = (ST)S[i + ksz_cn];
1621 s += val1*val1 - val0*val0;
1628 static Ptr<BaseRowFilter> getSqrRowSumFilter(int srcType, int sumType, int ksize, int anchor)
1630 int sdepth = CV_MAT_DEPTH(srcType), ddepth = CV_MAT_DEPTH(sumType);
1631 CV_Assert( CV_MAT_CN(sumType) == CV_MAT_CN(srcType) );
1636 if( sdepth == CV_8U && ddepth == CV_32S )
1637 return makePtr<SqrRowSum<uchar, int> >(ksize, anchor);
1638 if( sdepth == CV_8U && ddepth == CV_64F )
1639 return makePtr<SqrRowSum<uchar, double> >(ksize, anchor);
1640 if( sdepth == CV_16U && ddepth == CV_64F )
1641 return makePtr<SqrRowSum<ushort, double> >(ksize, anchor);
1642 if( sdepth == CV_16S && ddepth == CV_64F )
1643 return makePtr<SqrRowSum<short, double> >(ksize, anchor);
1644 if( sdepth == CV_32F && ddepth == CV_64F )
1645 return makePtr<SqrRowSum<float, double> >(ksize, anchor);
1646 if( sdepth == CV_64F && ddepth == CV_64F )
1647 return makePtr<SqrRowSum<double, double> >(ksize, anchor);
1649 CV_Error_( CV_StsNotImplemented,
1650 ("Unsupported combination of source format (=%d), and buffer format (=%d)",
1653 return Ptr<BaseRowFilter>();
1658 void cv::sqrBoxFilter( InputArray _src, OutputArray _dst, int ddepth,
1659 Size ksize, Point anchor,
1660 bool normalize, int borderType )
1662 CV_INSTRUMENT_REGION()
1664 int srcType = _src.type(), sdepth = CV_MAT_DEPTH(srcType), cn = CV_MAT_CN(srcType);
1665 Size size = _src.size();
1668 ddepth = sdepth < CV_32F ? CV_32F : CV_64F;
1670 if( borderType != BORDER_CONSTANT && normalize )
1672 if( size.height == 1 )
1674 if( size.width == 1 )
1678 CV_OCL_RUN(_dst.isUMat() && _src.dims() <= 2,
1679 ocl_boxFilter(_src, _dst, ddepth, ksize, anchor, borderType, normalize, true))
1681 int sumDepth = CV_64F;
1682 if( sdepth == CV_8U )
1684 int sumType = CV_MAKETYPE( sumDepth, cn ), dstType = CV_MAKETYPE(ddepth, cn);
1686 Mat src = _src.getMat();
1687 _dst.create( size, dstType );
1688 Mat dst = _dst.getMat();
1690 Ptr<BaseRowFilter> rowFilter = getSqrRowSumFilter(srcType, sumType, ksize.width, anchor.x );
1691 Ptr<BaseColumnFilter> columnFilter = getColumnSumFilter(sumType,
1692 dstType, ksize.height, anchor.y,
1693 normalize ? 1./(ksize.width*ksize.height) : 1);
1695 Ptr<FilterEngine> f = makePtr<FilterEngine>(Ptr<BaseFilter>(), rowFilter, columnFilter,
1696 srcType, dstType, sumType, borderType );
1698 Size wsz(src.cols, src.rows);
1699 src.locateROI( wsz, ofs );
1701 f->apply( src, dst, wsz, ofs );
1705 /****************************************************************************************\
1707 \****************************************************************************************/
1709 cv::Mat cv::getGaussianKernel( int n, double sigma, int ktype )
1711 const int SMALL_GAUSSIAN_SIZE = 7;
1712 static const float small_gaussian_tab[][SMALL_GAUSSIAN_SIZE] =
1715 {0.25f, 0.5f, 0.25f},
1716 {0.0625f, 0.25f, 0.375f, 0.25f, 0.0625f},
1717 {0.03125f, 0.109375f, 0.21875f, 0.28125f, 0.21875f, 0.109375f, 0.03125f}
1720 const float* fixed_kernel = n % 2 == 1 && n <= SMALL_GAUSSIAN_SIZE && sigma <= 0 ?
1721 small_gaussian_tab[n>>1] : 0;
1723 CV_Assert( ktype == CV_32F || ktype == CV_64F );
1724 Mat kernel(n, 1, ktype);
1725 float* cf = kernel.ptr<float>();
1726 double* cd = kernel.ptr<double>();
1728 double sigmaX = sigma > 0 ? sigma : ((n-1)*0.5 - 1)*0.3 + 0.8;
1729 double scale2X = -0.5/(sigmaX*sigmaX);
1733 for( i = 0; i < n; i++ )
1735 double x = i - (n-1)*0.5;
1736 double t = fixed_kernel ? (double)fixed_kernel[i] : std::exp(scale2X*x*x);
1737 if( ktype == CV_32F )
1750 for( i = 0; i < n; i++ )
1752 if( ktype == CV_32F )
1753 cf[i] = (float)(cf[i]*sum);
1763 static void createGaussianKernels( Mat & kx, Mat & ky, int type, Size ksize,
1764 double sigma1, double sigma2 )
1766 int depth = CV_MAT_DEPTH(type);
1770 // automatic detection of kernel size from sigma
1771 if( ksize.width <= 0 && sigma1 > 0 )
1772 ksize.width = cvRound(sigma1*(depth == CV_8U ? 3 : 4)*2 + 1)|1;
1773 if( ksize.height <= 0 && sigma2 > 0 )
1774 ksize.height = cvRound(sigma2*(depth == CV_8U ? 3 : 4)*2 + 1)|1;
1776 CV_Assert( ksize.width > 0 && ksize.width % 2 == 1 &&
1777 ksize.height > 0 && ksize.height % 2 == 1 );
1779 sigma1 = std::max( sigma1, 0. );
1780 sigma2 = std::max( sigma2, 0. );
1782 kx = getGaussianKernel( ksize.width, sigma1, std::max(depth, CV_32F) );
1783 if( ksize.height == ksize.width && std::abs(sigma1 - sigma2) < DBL_EPSILON )
1786 ky = getGaussianKernel( ksize.height, sigma2, std::max(depth, CV_32F) );
1791 cv::Ptr<cv::FilterEngine> cv::createGaussianFilter( int type, Size ksize,
1792 double sigma1, double sigma2,
1796 createGaussianKernels(kx, ky, type, ksize, sigma1, sigma2);
1798 return createSeparableLinearFilter( type, type, kx, ky, Point(-1,-1), 0, borderType );
1805 static bool ocl_GaussianBlur_8UC1(InputArray _src, OutputArray _dst, Size ksize, int ddepth,
1806 InputArray _kernelX, InputArray _kernelY, int borderType)
1808 const ocl::Device & dev = ocl::Device::getDefault();
1809 int type = _src.type(), sdepth = CV_MAT_DEPTH(type), cn = CV_MAT_CN(type);
1811 if ( !(dev.isIntel() && (type == CV_8UC1) &&
1812 (_src.offset() == 0) && (_src.step() % 4 == 0) &&
1813 ((ksize.width == 5 && (_src.cols() % 4 == 0)) ||
1814 (ksize.width == 3 && (_src.cols() % 16 == 0) && (_src.rows() % 2 == 0)))) )
1817 Mat kernelX = _kernelX.getMat().reshape(1, 1);
1818 if (kernelX.cols % 2 != 1)
1820 Mat kernelY = _kernelY.getMat().reshape(1, 1);
1821 if (kernelY.cols % 2 != 1)
1827 Size size = _src.size();
1828 size_t globalsize[2] = { 0, 0 };
1829 size_t localsize[2] = { 0, 0 };
1831 if (ksize.width == 3)
1833 globalsize[0] = size.width / 16;
1834 globalsize[1] = size.height / 2;
1836 else if (ksize.width == 5)
1838 globalsize[0] = size.width / 4;
1839 globalsize[1] = size.height / 1;
1842 const char * const borderMap[] = { "BORDER_CONSTANT", "BORDER_REPLICATE", "BORDER_REFLECT", 0, "BORDER_REFLECT_101" };
1843 char build_opts[1024];
1844 sprintf(build_opts, "-D %s %s%s", borderMap[borderType],
1845 ocl::kernelToStr(kernelX, CV_32F, "KERNEL_MATRIX_X").c_str(),
1846 ocl::kernelToStr(kernelY, CV_32F, "KERNEL_MATRIX_Y").c_str());
1850 if (ksize.width == 3)
1851 kernel.create("gaussianBlur3x3_8UC1_cols16_rows2", cv::ocl::imgproc::gaussianBlur3x3_oclsrc, build_opts);
1852 else if (ksize.width == 5)
1853 kernel.create("gaussianBlur5x5_8UC1_cols4", cv::ocl::imgproc::gaussianBlur5x5_oclsrc, build_opts);
1858 UMat src = _src.getUMat();
1859 _dst.create(size, CV_MAKETYPE(ddepth, cn));
1860 if (!(_dst.offset() == 0 && _dst.step() % 4 == 0))
1862 UMat dst = _dst.getUMat();
1864 int idxArg = kernel.set(0, ocl::KernelArg::PtrReadOnly(src));
1865 idxArg = kernel.set(idxArg, (int)src.step);
1866 idxArg = kernel.set(idxArg, ocl::KernelArg::PtrWriteOnly(dst));
1867 idxArg = kernel.set(idxArg, (int)dst.step);
1868 idxArg = kernel.set(idxArg, (int)dst.rows);
1869 idxArg = kernel.set(idxArg, (int)dst.cols);
1871 return kernel.run(2, globalsize, (localsize[0] == 0) ? NULL : localsize, false);
1879 template <> inline bool skipSmallImages<VX_KERNEL_GAUSSIAN_3x3>(int w, int h) { return w*h < 320 * 240; }
1881 static bool openvx_gaussianBlur(InputArray _src, OutputArray _dst, Size ksize,
1882 double sigma1, double sigma2, int borderType)
1886 // automatic detection of kernel size from sigma
1887 if (ksize.width <= 0 && sigma1 > 0)
1888 ksize.width = cvRound(sigma1*6 + 1) | 1;
1889 if (ksize.height <= 0 && sigma2 > 0)
1890 ksize.height = cvRound(sigma2*6 + 1) | 1;
1892 if (_src.type() != CV_8UC1 ||
1893 _src.cols() < 3 || _src.rows() < 3 ||
1894 ksize.width != 3 || ksize.height != 3)
1897 sigma1 = std::max(sigma1, 0.);
1898 sigma2 = std::max(sigma2, 0.);
1900 if (!(sigma1 == 0.0 || (sigma1 - 0.8) < DBL_EPSILON) || !(sigma2 == 0.0 || (sigma2 - 0.8) < DBL_EPSILON) ||
1901 ovx::skipSmallImages<VX_KERNEL_GAUSSIAN_3x3>(_src.cols(), _src.rows()))
1904 Mat src = _src.getMat();
1905 Mat dst = _dst.getMat();
1907 if ((borderType & BORDER_ISOLATED) == 0 && src.isSubmatrix())
1908 return false; //Process isolated borders only
1910 switch (borderType & ~BORDER_ISOLATED)
1912 case BORDER_CONSTANT:
1913 border = VX_BORDER_CONSTANT;
1915 case BORDER_REPLICATE:
1916 border = VX_BORDER_REPLICATE;
1924 ivx::Context ctx = ovx::getOpenVXContext();
1927 if (dst.data != src.data)
1933 ia = ivx::Image::createFromHandle(ctx, VX_DF_IMAGE_U8,
1934 ivx::Image::createAddressing(a.cols, a.rows, 1, (vx_int32)(a.step)), a.data),
1935 ib = ivx::Image::createFromHandle(ctx, VX_DF_IMAGE_U8,
1936 ivx::Image::createAddressing(dst.cols, dst.rows, 1, (vx_int32)(dst.step)), dst.data);
1938 //ATTENTION: VX_CONTEXT_IMMEDIATE_BORDER attribute change could lead to strange issues in multi-threaded environments
1939 //since OpenVX standart says nothing about thread-safety for now
1940 ivx::border_t prevBorder = ctx.immediateBorder();
1941 ctx.setImmediateBorder(border, (vx_uint8)(0));
1942 ivx::IVX_CHECK_STATUS(vxuGaussian3x3(ctx, ia, ib));
1943 ctx.setImmediateBorder(prevBorder);
1945 catch (ivx::RuntimeError & e)
1947 VX_DbgThrow(e.what());
1949 catch (ivx::WrapperError & e)
1951 VX_DbgThrow(e.what());
1959 #if IPP_VERSION_X100 == 201702 // IW 2017u2 has bug which doesn't allow use of partial inMem with tiling
1960 #define IPP_GAUSSIANBLUR_PARALLEL 0
1962 #define IPP_GAUSSIANBLUR_PARALLEL 1
1967 class ipp_gaussianBlurParallel: public ParallelLoopBody
1970 ipp_gaussianBlurParallel(::ipp::IwiImage &src, ::ipp::IwiImage &dst, int kernelSize, float sigma, ::ipp::IwiBorderType &border, bool *pOk):
1971 m_src(src), m_dst(dst), m_kernelSize(kernelSize), m_sigma(sigma), m_border(border), m_pOk(pOk) {
1974 ~ipp_gaussianBlurParallel()
1978 virtual void operator() (const Range& range) const
1980 CV_INSTRUMENT_REGION_IPP()
1987 ::ipp::IwiTile tile = ::ipp::IwiRoi(0, range.start, m_dst.m_size.width, range.end - range.start);
1988 CV_INSTRUMENT_FUN_IPP(::ipp::iwiFilterGaussian, m_src, m_dst, m_kernelSize, m_sigma, ::ipp::IwDefault(), m_border, tile);
1990 catch(::ipp::IwException e)
1997 ::ipp::IwiImage &m_src;
1998 ::ipp::IwiImage &m_dst;
2002 ::ipp::IwiBorderType &m_border;
2004 volatile bool *m_pOk;
2005 const ipp_gaussianBlurParallel& operator= (const ipp_gaussianBlurParallel&);
2010 static bool ipp_GaussianBlur(InputArray _src, OutputArray _dst, Size ksize,
2011 double sigma1, double sigma2, int borderType )
2014 CV_INSTRUMENT_REGION_IPP()
2016 #if IPP_VERSION_X100 < 201800 && ((defined _MSC_VER && defined _M_IX86) || (defined __GNUC__ && defined __i386__))
2017 CV_UNUSED(_src); CV_UNUSED(_dst); CV_UNUSED(ksize); CV_UNUSED(sigma1); CV_UNUSED(sigma2); CV_UNUSED(borderType);
2018 return false; // bug on ia32
2020 if(sigma1 != sigma2)
2023 if(sigma1 < FLT_EPSILON)
2026 if(ksize.width != ksize.height)
2029 // Acquire data and begin processing
2032 Mat src = _src.getMat();
2033 Mat dst = _dst.getMat();
2034 ::ipp::IwiImage iwSrc = ippiGetImage(src);
2035 ::ipp::IwiImage iwDst = ippiGetImage(dst);
2036 ::ipp::IwiBorderSize borderSize = ::ipp::iwiSizeToBorderSize(ippiGetSize(ksize));
2037 ::ipp::IwiBorderType ippBorder(ippiGetBorder(iwSrc, borderType, borderSize));
2041 const int threads = ippiSuggestThreadsNum(iwDst, 2);
2042 if(IPP_GAUSSIANBLUR_PARALLEL && threads > 1) {
2044 ipp_gaussianBlurParallel invoker(iwSrc, iwDst, ksize.width, (float) sigma1, ippBorder, &ok);
2048 const Range range(0, (int) iwDst.m_size.height);
2049 parallel_for_(range, invoker, threads*4);
2054 CV_INSTRUMENT_FUN_IPP(::ipp::iwiFilterGaussian, iwSrc, iwDst, ksize.width, sigma1, ::ipp::IwDefault(), ippBorder);
2057 catch (::ipp::IwException ex)
2065 CV_UNUSED(_src); CV_UNUSED(_dst); CV_UNUSED(ksize); CV_UNUSED(sigma1); CV_UNUSED(sigma2); CV_UNUSED(borderType);
2072 void cv::GaussianBlur( InputArray _src, OutputArray _dst, Size ksize,
2073 double sigma1, double sigma2,
2076 CV_INSTRUMENT_REGION()
2078 int type = _src.type();
2079 Size size = _src.size();
2080 _dst.create( size, type );
2082 if( borderType != BORDER_CONSTANT && (borderType & BORDER_ISOLATED) != 0 )
2084 if( size.height == 1 )
2086 if( size.width == 1 )
2090 if( ksize.width == 1 && ksize.height == 1 )
2097 openvx_gaussianBlur(_src, _dst, ksize, sigma1, sigma2, borderType))
2099 #ifdef HAVE_TEGRA_OPTIMIZATION
2100 Mat src = _src.getMat();
2101 Mat dst = _dst.getMat();
2102 if(sigma1 == 0 && sigma2 == 0 && tegra::useTegra() && tegra::gaussian(src, dst, ksize, borderType))
2105 bool useOpenCL = (ocl::useOpenCL() && _dst.isUMat() && _src.dims() <= 2 &&
2106 ((ksize.width == 3 && ksize.height == 3) ||
2107 (ksize.width == 5 && ksize.height == 5)) &&
2108 _src.rows() > ksize.height && _src.cols() > ksize.width);
2111 CV_IPP_RUN(!useOpenCL, ipp_GaussianBlur( _src, _dst, ksize, sigma1, sigma2, borderType));
2114 createGaussianKernels(kx, ky, type, ksize, sigma1, sigma2);
2116 CV_OCL_RUN(useOpenCL, ocl_GaussianBlur_8UC1(_src, _dst, ksize, CV_MAT_DEPTH(type), kx, ky, borderType));
2118 sepFilter2D(_src, _dst, CV_MAT_DEPTH(type), kx, ky, Point(-1,-1), 0, borderType );
2121 /****************************************************************************************\
2123 \****************************************************************************************/
2130 * This structure represents a two-tier histogram. The first tier (known as the
2131 * "coarse" level) is 4 bit wide and the second tier (known as the "fine" level)
2132 * is 8 bit wide. Pixels inserted in the fine level also get inserted into the
2133 * coarse bucket designated by the 4 MSBs of the fine bucket value.
2135 * The structure is aligned on 16 bits, which is a prerequisite for SIMD
2136 * instructions. Each bucket is 16 bit wide, which means that extra care must be
2137 * taken to prevent overflow.
2148 static inline void histogram_add_simd( const HT x[16], HT y[16] )
2150 v_store(y, v_load(x) + v_load(y));
2151 v_store(y + 8, v_load(x + 8) + v_load(y + 8));
2154 static inline void histogram_sub_simd( const HT x[16], HT y[16] )
2156 v_store(y, v_load(y) - v_load(x));
2157 v_store(y + 8, v_load(y + 8) - v_load(x + 8));
2163 static inline void histogram_add( const HT x[16], HT y[16] )
2166 for( i = 0; i < 16; ++i )
2167 y[i] = (HT)(y[i] + x[i]);
2170 static inline void histogram_sub( const HT x[16], HT y[16] )
2173 for( i = 0; i < 16; ++i )
2174 y[i] = (HT)(y[i] - x[i]);
2177 static inline void histogram_muladd( int a, const HT x[16],
2180 for( int i = 0; i < 16; ++i )
2181 y[i] = (HT)(y[i] + a * x[i]);
2185 medianBlur_8u_O1( const Mat& _src, Mat& _dst, int ksize )
2188 * HOP is short for Histogram OPeration. This macro makes an operation \a op on
2189 * histogram \a h for pixel value \a x. It takes care of handling both levels.
2191 #define HOP(h,x,op) \
2192 h.coarse[x>>4] op, \
2193 *((HT*)h.fine + x) op
2195 #define COP(c,j,x,op) \
2196 h_coarse[ 16*(n*c+j) + (x>>4) ] op, \
2197 h_fine[ 16 * (n*(16*c+(x>>4)) + j) + (x & 0xF) ] op
2199 int cn = _dst.channels(), m = _dst.rows, r = (ksize-1)/2;
2200 CV_Assert(cn > 0 && cn <= 4);
2201 size_t sstep = _src.step, dstep = _dst.step;
2202 Histogram CV_DECL_ALIGNED(16) H[4];
2203 HT CV_DECL_ALIGNED(16) luc[4][16];
2205 int STRIPE_SIZE = std::min( _dst.cols, 512/cn );
2207 std::vector<HT> _h_coarse(1 * 16 * (STRIPE_SIZE + 2*r) * cn + 16);
2208 std::vector<HT> _h_fine(16 * 16 * (STRIPE_SIZE + 2*r) * cn + 16);
2209 HT* h_coarse = alignPtr(&_h_coarse[0], 16);
2210 HT* h_fine = alignPtr(&_h_fine[0], 16);
2212 volatile bool useSIMD = hasSIMD128();
2215 for( int x = 0; x < _dst.cols; x += STRIPE_SIZE )
2217 int i, j, k, c, n = std::min(_dst.cols - x, STRIPE_SIZE) + r*2;
2218 const uchar* src = _src.ptr() + x*cn;
2219 uchar* dst = _dst.ptr() + (x - r)*cn;
2221 memset( h_coarse, 0, 16*n*cn*sizeof(h_coarse[0]) );
2222 memset( h_fine, 0, 16*16*n*cn*sizeof(h_fine[0]) );
2224 // First row initialization
2225 for( c = 0; c < cn; c++ )
2227 for( j = 0; j < n; j++ )
2228 COP( c, j, src[cn*j+c], += (cv::HT)(r+2) );
2230 for( i = 1; i < r; i++ )
2232 const uchar* p = src + sstep*std::min(i, m-1);
2233 for ( j = 0; j < n; j++ )
2234 COP( c, j, p[cn*j+c], ++ );
2238 for( i = 0; i < m; i++ )
2240 const uchar* p0 = src + sstep * std::max( 0, i-r-1 );
2241 const uchar* p1 = src + sstep * std::min( m-1, i+r );
2243 memset( H, 0, cn*sizeof(H[0]) );
2244 memset( luc, 0, cn*sizeof(luc[0]) );
2245 for( c = 0; c < cn; c++ )
2247 // Update column histograms for the entire row.
2248 for( j = 0; j < n; j++ )
2250 COP( c, j, p0[j*cn + c], -- );
2251 COP( c, j, p1[j*cn + c], ++ );
2254 // First column initialization
2255 for( k = 0; k < 16; ++k )
2256 histogram_muladd( 2*r+1, &h_fine[16*n*(16*c+k)], &H[c].fine[k][0] );
2261 for( j = 0; j < 2*r; ++j )
2262 histogram_add_simd( &h_coarse[16*(n*c+j)], H[c].coarse );
2264 for( j = r; j < n-r; j++ )
2266 int t = 2*r*r + 2*r, b, sum = 0;
2269 histogram_add_simd( &h_coarse[16*(n*c + std::min(j+r,n-1))], H[c].coarse );
2271 // Find median at coarse level
2272 for ( k = 0; k < 16 ; ++k )
2274 sum += H[c].coarse[k];
2277 sum -= H[c].coarse[k];
2281 CV_Assert( k < 16 );
2283 /* Update corresponding histogram segment */
2284 if ( luc[c][k] <= j-r )
2286 memset( &H[c].fine[k], 0, 16 * sizeof(HT) );
2287 for ( luc[c][k] = cv::HT(j-r); luc[c][k] < MIN(j+r+1,n); ++luc[c][k] )
2288 histogram_add_simd( &h_fine[16*(n*(16*c+k)+luc[c][k])], H[c].fine[k] );
2290 if ( luc[c][k] < j+r+1 )
2292 histogram_muladd( j+r+1 - n, &h_fine[16*(n*(16*c+k)+(n-1))], &H[c].fine[k][0] );
2293 luc[c][k] = (HT)(j+r+1);
2298 for ( ; luc[c][k] < j+r+1; ++luc[c][k] )
2300 histogram_sub_simd( &h_fine[16*(n*(16*c+k)+MAX(luc[c][k]-2*r-1,0))], H[c].fine[k] );
2301 histogram_add_simd( &h_fine[16*(n*(16*c+k)+MIN(luc[c][k],n-1))], H[c].fine[k] );
2305 histogram_sub_simd( &h_coarse[16*(n*c+MAX(j-r,0))], H[c].coarse );
2307 /* Find median in segment */
2308 segment = H[c].fine[k];
2309 for ( b = 0; b < 16 ; b++ )
2314 dst[dstep*i+cn*j+c] = (uchar)(16*k + b);
2318 CV_Assert( b < 16 );
2324 for( j = 0; j < 2*r; ++j )
2325 histogram_add( &h_coarse[16*(n*c+j)], H[c].coarse );
2327 for( j = r; j < n-r; j++ )
2329 int t = 2*r*r + 2*r, b, sum = 0;
2332 histogram_add( &h_coarse[16*(n*c + std::min(j+r,n-1))], H[c].coarse );
2334 // Find median at coarse level
2335 for ( k = 0; k < 16 ; ++k )
2337 sum += H[c].coarse[k];
2340 sum -= H[c].coarse[k];
2344 CV_Assert( k < 16 );
2346 /* Update corresponding histogram segment */
2347 if ( luc[c][k] <= j-r )
2349 memset( &H[c].fine[k], 0, 16 * sizeof(HT) );
2350 for ( luc[c][k] = cv::HT(j-r); luc[c][k] < MIN(j+r+1,n); ++luc[c][k] )
2351 histogram_add( &h_fine[16*(n*(16*c+k)+luc[c][k])], H[c].fine[k] );
2353 if ( luc[c][k] < j+r+1 )
2355 histogram_muladd( j+r+1 - n, &h_fine[16*(n*(16*c+k)+(n-1))], &H[c].fine[k][0] );
2356 luc[c][k] = (HT)(j+r+1);
2361 for ( ; luc[c][k] < j+r+1; ++luc[c][k] )
2363 histogram_sub( &h_fine[16*(n*(16*c+k)+MAX(luc[c][k]-2*r-1,0))], H[c].fine[k] );
2364 histogram_add( &h_fine[16*(n*(16*c+k)+MIN(luc[c][k],n-1))], H[c].fine[k] );
2368 histogram_sub( &h_coarse[16*(n*c+MAX(j-r,0))], H[c].coarse );
2370 /* Find median in segment */
2371 segment = H[c].fine[k];
2372 for ( b = 0; b < 16 ; b++ )
2377 dst[dstep*i+cn*j+c] = (uchar)(16*k + b);
2381 CV_Assert( b < 16 );
2393 medianBlur_8u_Om( const Mat& _src, Mat& _dst, int m )
2400 Size size = _dst.size();
2401 const uchar* src = _src.ptr();
2402 uchar* dst = _dst.ptr();
2403 int src_step = (int)_src.step, dst_step = (int)_dst.step;
2404 int cn = _src.channels();
2405 const uchar* src_max = src + size.height*src_step;
2406 CV_Assert(cn > 0 && cn <= 4);
2408 #define UPDATE_ACC01( pix, cn, op ) \
2412 zone0[cn][p >> 4] op; \
2415 //CV_Assert( size.height >= nx && size.width >= nx );
2416 for( x = 0; x < size.width; x++, src += cn, dst += cn )
2418 uchar* dst_cur = dst;
2419 const uchar* src_top = src;
2420 const uchar* src_bottom = src;
2422 int src_step1 = src_step, dst_step1 = dst_step;
2426 src_bottom = src_top += src_step*(size.height-1);
2427 dst_cur += dst_step*(size.height-1);
2428 src_step1 = -src_step1;
2429 dst_step1 = -dst_step1;
2433 memset( zone0, 0, sizeof(zone0[0])*cn );
2434 memset( zone1, 0, sizeof(zone1[0])*cn );
2436 for( y = 0; y <= m/2; y++ )
2438 for( c = 0; c < cn; c++ )
2442 for( k = 0; k < m*cn; k += cn )
2443 UPDATE_ACC01( src_bottom[k+c], c, ++ );
2447 for( k = 0; k < m*cn; k += cn )
2448 UPDATE_ACC01( src_bottom[k+c], c, += m/2+1 );
2452 if( (src_step1 > 0 && y < size.height-1) ||
2453 (src_step1 < 0 && size.height-y-1 > 0) )
2454 src_bottom += src_step1;
2457 for( y = 0; y < size.height; y++, dst_cur += dst_step1 )
2460 for( c = 0; c < cn; c++ )
2465 int t = s + zone0[c][k];
2476 dst_cur[c] = (uchar)k;
2479 if( y+1 == size.height )
2484 for( k = 0; k < m; k++ )
2487 int q = src_bottom[k];
2496 for( k = 0; k < m*3; k += 3 )
2498 UPDATE_ACC01( src_top[k], 0, -- );
2499 UPDATE_ACC01( src_top[k+1], 1, -- );
2500 UPDATE_ACC01( src_top[k+2], 2, -- );
2502 UPDATE_ACC01( src_bottom[k], 0, ++ );
2503 UPDATE_ACC01( src_bottom[k+1], 1, ++ );
2504 UPDATE_ACC01( src_bottom[k+2], 2, ++ );
2510 for( k = 0; k < m*4; k += 4 )
2512 UPDATE_ACC01( src_top[k], 0, -- );
2513 UPDATE_ACC01( src_top[k+1], 1, -- );
2514 UPDATE_ACC01( src_top[k+2], 2, -- );
2515 UPDATE_ACC01( src_top[k+3], 3, -- );
2517 UPDATE_ACC01( src_bottom[k], 0, ++ );
2518 UPDATE_ACC01( src_bottom[k+1], 1, ++ );
2519 UPDATE_ACC01( src_bottom[k+2], 2, ++ );
2520 UPDATE_ACC01( src_bottom[k+3], 3, ++ );
2524 if( (src_step1 > 0 && src_bottom + src_step1 < src_max) ||
2525 (src_step1 < 0 && src_bottom + src_step1 >= src) )
2526 src_bottom += src_step1;
2529 src_top += src_step1;
2539 typedef uchar value_type;
2540 typedef int arg_type;
2542 arg_type load(const uchar* ptr) { return *ptr; }
2543 void store(uchar* ptr, arg_type val) { *ptr = (uchar)val; }
2544 void operator()(arg_type& a, arg_type& b) const
2546 int t = CV_FAST_CAST_8U(a - b);
2553 typedef ushort value_type;
2554 typedef int arg_type;
2556 arg_type load(const ushort* ptr) { return *ptr; }
2557 void store(ushort* ptr, arg_type val) { *ptr = (ushort)val; }
2558 void operator()(arg_type& a, arg_type& b) const
2568 typedef short value_type;
2569 typedef int arg_type;
2571 arg_type load(const short* ptr) { return *ptr; }
2572 void store(short* ptr, arg_type val) { *ptr = (short)val; }
2573 void operator()(arg_type& a, arg_type& b) const
2583 typedef float value_type;
2584 typedef float arg_type;
2586 arg_type load(const float* ptr) { return *ptr; }
2587 void store(float* ptr, arg_type val) { *ptr = val; }
2588 void operator()(arg_type& a, arg_type& b) const
2600 typedef uchar value_type;
2601 typedef v_uint8x16 arg_type;
2603 arg_type load(const uchar* ptr) { return v_load(ptr); }
2604 void store(uchar* ptr, const arg_type &val) { v_store(ptr, val); }
2605 void operator()(arg_type& a, arg_type& b) const
2616 typedef ushort value_type;
2617 typedef v_uint16x8 arg_type;
2619 arg_type load(const ushort* ptr) { return v_load(ptr); }
2620 void store(ushort* ptr, const arg_type &val) { v_store(ptr, val); }
2621 void operator()(arg_type& a, arg_type& b) const
2632 typedef short value_type;
2633 typedef v_int16x8 arg_type;
2635 arg_type load(const short* ptr) { return v_load(ptr); }
2636 void store(short* ptr, const arg_type &val) { v_store(ptr, val); }
2637 void operator()(arg_type& a, arg_type& b) const
2648 typedef float value_type;
2649 typedef v_float32x4 arg_type;
2651 arg_type load(const float* ptr) { return v_load(ptr); }
2652 void store(float* ptr, const arg_type &val) { v_store(ptr, val); }
2653 void operator()(arg_type& a, arg_type& b) const
2663 typedef MinMax8u MinMaxVec8u;
2664 typedef MinMax16u MinMaxVec16u;
2665 typedef MinMax16s MinMaxVec16s;
2666 typedef MinMax32f MinMaxVec32f;
2670 template<class Op, class VecOp>
2672 medianBlur_SortNet( const Mat& _src, Mat& _dst, int m )
2674 typedef typename Op::value_type T;
2675 typedef typename Op::arg_type WT;
2676 typedef typename VecOp::arg_type VT;
2678 const T* src = _src.ptr<T>();
2679 T* dst = _dst.ptr<T>();
2680 int sstep = (int)(_src.step/sizeof(T));
2681 int dstep = (int)(_dst.step/sizeof(T));
2682 Size size = _dst.size();
2683 int i, j, k, cn = _src.channels();
2686 volatile bool useSIMD = hasSIMD128();
2690 if( size.width == 1 || size.height == 1 )
2692 int len = size.width + size.height - 1;
2693 int sdelta = size.height == 1 ? cn : sstep;
2694 int sdelta0 = size.height == 1 ? 0 : sstep - cn;
2695 int ddelta = size.height == 1 ? cn : dstep;
2697 for( i = 0; i < len; i++, src += sdelta0, dst += ddelta )
2698 for( j = 0; j < cn; j++, src++ )
2700 WT p0 = src[i > 0 ? -sdelta : 0];
2702 WT p2 = src[i < len - 1 ? sdelta : 0];
2704 op(p0, p1); op(p1, p2); op(p0, p1);
2711 for( i = 0; i < size.height; i++, dst += dstep )
2713 const T* row0 = src + std::max(i - 1, 0)*sstep;
2714 const T* row1 = src + i*sstep;
2715 const T* row2 = src + std::min(i + 1, size.height-1)*sstep;
2716 int limit = useSIMD ? cn : size.width;
2720 for( ; j < limit; j++ )
2722 int j0 = j >= cn ? j - cn : j;
2723 int j2 = j < size.width - cn ? j + cn : j;
2724 WT p0 = row0[j0], p1 = row0[j], p2 = row0[j2];
2725 WT p3 = row1[j0], p4 = row1[j], p5 = row1[j2];
2726 WT p6 = row2[j0], p7 = row2[j], p8 = row2[j2];
2728 op(p1, p2); op(p4, p5); op(p7, p8); op(p0, p1);
2729 op(p3, p4); op(p6, p7); op(p1, p2); op(p4, p5);
2730 op(p7, p8); op(p0, p3); op(p5, p8); op(p4, p7);
2731 op(p3, p6); op(p1, p4); op(p2, p5); op(p4, p7);
2732 op(p4, p2); op(p6, p4); op(p4, p2);
2736 if( limit == size.width )
2739 for( ; j <= size.width - VecOp::SIZE - cn; j += VecOp::SIZE )
2741 VT p0 = vop.load(row0+j-cn), p1 = vop.load(row0+j), p2 = vop.load(row0+j+cn);
2742 VT p3 = vop.load(row1+j-cn), p4 = vop.load(row1+j), p5 = vop.load(row1+j+cn);
2743 VT p6 = vop.load(row2+j-cn), p7 = vop.load(row2+j), p8 = vop.load(row2+j+cn);
2745 vop(p1, p2); vop(p4, p5); vop(p7, p8); vop(p0, p1);
2746 vop(p3, p4); vop(p6, p7); vop(p1, p2); vop(p4, p5);
2747 vop(p7, p8); vop(p0, p3); vop(p5, p8); vop(p4, p7);
2748 vop(p3, p6); vop(p1, p4); vop(p2, p5); vop(p4, p7);
2749 vop(p4, p2); vop(p6, p4); vop(p4, p2);
2750 vop.store(dst+j, p4);
2759 if( size.width == 1 || size.height == 1 )
2761 int len = size.width + size.height - 1;
2762 int sdelta = size.height == 1 ? cn : sstep;
2763 int sdelta0 = size.height == 1 ? 0 : sstep - cn;
2764 int ddelta = size.height == 1 ? cn : dstep;
2766 for( i = 0; i < len; i++, src += sdelta0, dst += ddelta )
2767 for( j = 0; j < cn; j++, src++ )
2769 int i1 = i > 0 ? -sdelta : 0;
2770 int i0 = i > 1 ? -sdelta*2 : i1;
2771 int i3 = i < len-1 ? sdelta : 0;
2772 int i4 = i < len-2 ? sdelta*2 : i3;
2773 WT p0 = src[i0], p1 = src[i1], p2 = src[0], p3 = src[i3], p4 = src[i4];
2775 op(p0, p1); op(p3, p4); op(p2, p3); op(p3, p4); op(p0, p2);
2776 op(p2, p4); op(p1, p3); op(p1, p2);
2783 for( i = 0; i < size.height; i++, dst += dstep )
2786 row[0] = src + std::max(i - 2, 0)*sstep;
2787 row[1] = src + std::max(i - 1, 0)*sstep;
2788 row[2] = src + i*sstep;
2789 row[3] = src + std::min(i + 1, size.height-1)*sstep;
2790 row[4] = src + std::min(i + 2, size.height-1)*sstep;
2791 int limit = useSIMD ? cn*2 : size.width;
2795 for( ; j < limit; j++ )
2798 int j1 = j >= cn ? j - cn : j;
2799 int j0 = j >= cn*2 ? j - cn*2 : j1;
2800 int j3 = j < size.width - cn ? j + cn : j;
2801 int j4 = j < size.width - cn*2 ? j + cn*2 : j3;
2802 for( k = 0; k < 5; k++ )
2804 const T* rowk = row[k];
2805 p[k*5] = rowk[j0]; p[k*5+1] = rowk[j1];
2806 p[k*5+2] = rowk[j]; p[k*5+3] = rowk[j3];
2807 p[k*5+4] = rowk[j4];
2810 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]);
2811 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]);
2812 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]);
2813 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]);
2814 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]);
2815 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]);
2816 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]);
2817 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]);
2818 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]);
2819 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]);
2820 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]);
2821 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]);
2822 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]);
2823 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]);
2824 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]);
2825 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]);
2826 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]);
2827 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]);
2828 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]);
2829 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]);
2830 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]);
2831 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]);
2832 op(p[7], p[11]); op(p[11], p[13]); op(p[11], p[12]);
2836 if( limit == size.width )
2839 for( ; j <= size.width - VecOp::SIZE - cn*2; j += VecOp::SIZE )
2842 for( k = 0; k < 5; k++ )
2844 const T* rowk = row[k];
2845 p[k*5] = vop.load(rowk+j-cn*2); p[k*5+1] = vop.load(rowk+j-cn);
2846 p[k*5+2] = vop.load(rowk+j); p[k*5+3] = vop.load(rowk+j+cn);
2847 p[k*5+4] = vop.load(rowk+j+cn*2);
2850 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]);
2851 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]);
2852 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]);
2853 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]);
2854 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]);
2855 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]);
2856 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]);
2857 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]);
2858 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]);
2859 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]);
2860 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]);
2861 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]);
2862 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]);
2863 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]);
2864 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]);
2865 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]);
2866 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]);
2867 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]);
2868 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]);
2869 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]);
2870 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]);
2871 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]);
2872 vop(p[7], p[11]); vop(p[11], p[13]); vop(p[11], p[12]);
2873 vop.store(dst+j, p[12]);
2884 static bool ocl_medianFilter(InputArray _src, OutputArray _dst, int m)
2886 size_t localsize[2] = { 16, 16 };
2887 size_t globalsize[2];
2888 int type = _src.type(), depth = CV_MAT_DEPTH(type), cn = CV_MAT_CN(type);
2890 if ( !((depth == CV_8U || depth == CV_16U || depth == CV_16S || depth == CV_32F) && cn <= 4 && (m == 3 || m == 5)) )
2893 Size imgSize = _src.size();
2894 bool useOptimized = (1 == cn) &&
2895 (size_t)imgSize.width >= localsize[0] * 8 &&
2896 (size_t)imgSize.height >= localsize[1] * 8 &&
2897 imgSize.width % 4 == 0 &&
2898 imgSize.height % 4 == 0 &&
2899 (ocl::Device::getDefault().isIntel());
2901 cv::String kname = format( useOptimized ? "medianFilter%d_u" : "medianFilter%d", m) ;
2902 cv::String kdefs = useOptimized ?
2903 format("-D T=%s -D T1=%s -D T4=%s%d -D cn=%d -D USE_4OPT", ocl::typeToStr(type),
2904 ocl::typeToStr(depth), ocl::typeToStr(depth), cn*4, cn)
2906 format("-D T=%s -D T1=%s -D cn=%d", ocl::typeToStr(type), ocl::typeToStr(depth), cn) ;
2908 ocl::Kernel k(kname.c_str(), ocl::imgproc::medianFilter_oclsrc, kdefs.c_str() );
2913 UMat src = _src.getUMat();
2914 _dst.create(src.size(), type);
2915 UMat dst = _dst.getUMat();
2917 k.args(ocl::KernelArg::ReadOnlyNoSize(src), ocl::KernelArg::WriteOnly(dst));
2921 globalsize[0] = DIVUP(src.cols / 4, localsize[0]) * localsize[0];
2922 globalsize[1] = DIVUP(src.rows / 4, localsize[1]) * localsize[1];
2926 globalsize[0] = (src.cols + localsize[0] + 2) / localsize[0] * localsize[0];
2927 globalsize[1] = (src.rows + localsize[1] - 1) / localsize[1] * localsize[1];
2930 return k.run(2, globalsize, localsize, false);
2941 template <> inline bool skipSmallImages<VX_KERNEL_MEDIAN_3x3>(int w, int h) { return w*h < 1280 * 720; }
2943 static bool openvx_medianFilter(InputArray _src, OutputArray _dst, int ksize)
2945 if (_src.type() != CV_8UC1 || _dst.type() != CV_8U
2946 #ifndef VX_VERSION_1_1
2952 Mat src = _src.getMat();
2953 Mat dst = _dst.getMat();
2956 #ifdef VX_VERSION_1_1
2957 ksize != 3 ? ovx::skipSmallImages<VX_KERNEL_NON_LINEAR_FILTER>(src.cols, src.rows) :
2959 ovx::skipSmallImages<VX_KERNEL_MEDIAN_3x3>(src.cols, src.rows)
2965 ivx::Context ctx = ovx::getOpenVXContext();
2966 #ifdef VX_VERSION_1_1
2967 if ((vx_size)ksize > ctx.nonlinearMaxDimension())
2972 if (dst.data != src.data)
2978 ia = ivx::Image::createFromHandle(ctx, VX_DF_IMAGE_U8,
2979 ivx::Image::createAddressing(a.cols, a.rows, 1, (vx_int32)(a.step)), a.data),
2980 ib = ivx::Image::createFromHandle(ctx, VX_DF_IMAGE_U8,
2981 ivx::Image::createAddressing(dst.cols, dst.rows, 1, (vx_int32)(dst.step)), dst.data);
2983 //ATTENTION: VX_CONTEXT_IMMEDIATE_BORDER attribute change could lead to strange issues in multi-threaded environments
2984 //since OpenVX standart says nothing about thread-safety for now
2985 ivx::border_t prevBorder = ctx.immediateBorder();
2986 ctx.setImmediateBorder(VX_BORDER_REPLICATE);
2987 #ifdef VX_VERSION_1_1
2991 ivx::IVX_CHECK_STATUS(vxuMedian3x3(ctx, ia, ib));
2993 #ifdef VX_VERSION_1_1
2998 mtx = ivx::Matrix::createFromPattern(ctx, VX_PATTERN_BOX, ksize, ksize);
3001 vx_size supportedSize;
3002 ivx::IVX_CHECK_STATUS(vxQueryContext(ctx, VX_CONTEXT_NONLINEAR_MAX_DIMENSION, &supportedSize, sizeof(supportedSize)));
3003 if ((vx_size)ksize > supportedSize)
3005 ctx.setImmediateBorder(prevBorder);
3008 Mat mask(ksize, ksize, CV_8UC1, Scalar(255));
3009 mtx = ivx::Matrix::create(ctx, VX_TYPE_UINT8, ksize, ksize);
3012 ivx::IVX_CHECK_STATUS(vxuNonLinearFilter(ctx, VX_NONLINEAR_FILTER_MEDIAN, ia, mtx, ib));
3015 ctx.setImmediateBorder(prevBorder);
3017 catch (ivx::RuntimeError & e)
3019 VX_DbgThrow(e.what());
3021 catch (ivx::WrapperError & e)
3023 VX_DbgThrow(e.what());
3034 static bool ipp_medianFilter(Mat &src0, Mat &dst, int ksize)
3036 CV_INSTRUMENT_REGION_IPP()
3038 #if IPP_VERSION_X100 < 201801
3039 // Degradations for big kernel
3046 IppiSize dstRoiSize = ippiSize(dst.cols, dst.rows), maskSize = ippiSize(ksize, ksize);
3047 IppDataType ippType = ippiGetDataType(src0.type());
3048 int channels = src0.channels();
3049 IppAutoBuffer<Ipp8u> buffer;
3051 if(src0.isSubmatrix())
3055 if(dst.data != src0.data)
3060 if(ippiFilterMedianBorderGetBufferSize(dstRoiSize, maskSize, ippType, channels, &bufSize) < 0)
3063 buffer.allocate(bufSize);
3069 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;
3070 else if(channels == 3)
3071 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;
3072 else if(channels == 4)
3073 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;
3078 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;
3079 else if(channels == 3)
3080 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;
3081 else if(channels == 4)
3082 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;
3087 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;
3088 else if(channels == 3)
3089 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;
3090 else if(channels == 4)
3091 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;
3096 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;
3107 void cv::medianBlur( InputArray _src0, OutputArray _dst, int ksize )
3109 CV_INSTRUMENT_REGION()
3111 CV_Assert( (ksize % 2 == 1) && (_src0.dims() <= 2 ));
3113 if( ksize <= 1 || _src0.empty() )
3119 CV_OCL_RUN(_dst.isUMat(),
3120 ocl_medianFilter(_src0,_dst, ksize))
3122 Mat src0 = _src0.getMat();
3123 _dst.create( src0.size(), src0.type() );
3124 Mat dst = _dst.getMat();
3126 CALL_HAL(medianBlur, cv_hal_medianBlur, src0.data, src0.step, dst.data, dst.step, src0.cols, src0.rows, src0.depth(),
3127 src0.channels(), ksize);
3130 openvx_medianFilter(_src0, _dst, ksize))
3132 CV_IPP_RUN_FAST(ipp_medianFilter(src0, dst, ksize));
3134 #ifdef HAVE_TEGRA_OPTIMIZATION
3135 if (tegra::useTegra() && tegra::medianBlur(src0, dst, ksize))
3139 bool useSortNet = ksize == 3 || (ksize == 5
3141 && ( src0.depth() > CV_8U || src0.channels() == 2 || src0.channels() > 4 )
3148 if( dst.data != src0.data )
3153 if( src.depth() == CV_8U )
3154 medianBlur_SortNet<MinMax8u, MinMaxVec8u>( src, dst, ksize );
3155 else if( src.depth() == CV_16U )
3156 medianBlur_SortNet<MinMax16u, MinMaxVec16u>( src, dst, ksize );
3157 else if( src.depth() == CV_16S )
3158 medianBlur_SortNet<MinMax16s, MinMaxVec16s>( src, dst, ksize );
3159 else if( src.depth() == CV_32F )
3160 medianBlur_SortNet<MinMax32f, MinMaxVec32f>( src, dst, ksize );
3162 CV_Error(CV_StsUnsupportedFormat, "");
3168 cv::copyMakeBorder( src0, src, 0, 0, ksize/2, ksize/2, BORDER_REPLICATE|BORDER_ISOLATED);
3170 int cn = src0.channels();
3171 CV_Assert( src.depth() == CV_8U && (cn == 1 || cn == 3 || cn == 4) );
3173 double img_size_mp = (double)(src0.total())/(1 << 20);
3174 if( ksize <= 3 + (img_size_mp < 1 ? 12 : img_size_mp < 4 ? 6 : 2)*
3175 (CV_SIMD128 && hasSIMD128() ? 1 : 3))
3176 medianBlur_8u_Om( src, dst, ksize );
3178 medianBlur_8u_O1( src, dst, ksize );
3182 /****************************************************************************************\
3184 \****************************************************************************************/
3189 class BilateralFilter_8u_Invoker :
3190 public ParallelLoopBody
3193 BilateralFilter_8u_Invoker(Mat& _dest, const Mat& _temp, int _radius, int _maxk,
3194 int* _space_ofs, float *_space_weight, float *_color_weight) :
3195 temp(&_temp), dest(&_dest), radius(_radius),
3196 maxk(_maxk), space_ofs(_space_ofs), space_weight(_space_weight), color_weight(_color_weight)
3200 virtual void operator() (const Range& range) const
3202 int i, j, cn = dest->channels(), k;
3203 Size size = dest->size();
3205 int CV_DECL_ALIGNED(16) buf[4];
3206 bool haveSIMD128 = hasSIMD128();
3209 for( i = range.start; i < range.end; i++ )
3211 const uchar* sptr = temp->ptr(i+radius) + radius*cn;
3212 uchar* dptr = dest->ptr(i);
3216 for( j = 0; j < size.width; j++ )
3218 float sum = 0, wsum = 0;
3224 v_float32x4 _val0 = v_setall_f32(static_cast<float>(val0));
3225 v_float32x4 vsumw = v_setzero_f32();
3226 v_float32x4 vsumc = v_setzero_f32();
3228 for( ; k <= maxk - 4; k += 4 )
3230 v_float32x4 _valF = v_float32x4(sptr[j + space_ofs[k]],
3231 sptr[j + space_ofs[k + 1]],
3232 sptr[j + space_ofs[k + 2]],
3233 sptr[j + space_ofs[k + 3]]);
3234 v_float32x4 _val = v_abs(_valF - _val0);
3235 v_store(buf, v_round(_val));
3237 v_float32x4 _cw = v_float32x4(color_weight[buf[0]],
3238 color_weight[buf[1]],
3239 color_weight[buf[2]],
3240 color_weight[buf[3]]);
3241 v_float32x4 _sw = v_load(space_weight+k);
3242 v_float32x4 _w = _cw * _sw;
3248 float *bufFloat = (float*)buf;
3249 v_float32x4 sum4 = v_reduce_sum4(vsumw, vsumc, vsumw, vsumc);
3250 v_store(bufFloat, sum4);
3252 wsum += bufFloat[0];
3255 for( ; k < maxk; k++ )
3257 int val = sptr[j + space_ofs[k]];
3258 float w = space_weight[k]*color_weight[std::abs(val - val0)];
3262 // overflow is not possible here => there is no need to use cv::saturate_cast
3263 dptr[j] = (uchar)cvRound(sum/wsum);
3269 for( j = 0; j < size.width*3; j += 3 )
3271 float sum_b = 0, sum_g = 0, sum_r = 0, wsum = 0;
3272 int b0 = sptr[j], g0 = sptr[j+1], r0 = sptr[j+2];
3277 v_float32x4 vsumw = v_setzero_f32();
3278 v_float32x4 vsumb = v_setzero_f32();
3279 v_float32x4 vsumg = v_setzero_f32();
3280 v_float32x4 vsumr = v_setzero_f32();
3281 const v_float32x4 _b0 = v_setall_f32(static_cast<float>(b0));
3282 const v_float32x4 _g0 = v_setall_f32(static_cast<float>(g0));
3283 const v_float32x4 _r0 = v_setall_f32(static_cast<float>(r0));
3285 for( ; k <= maxk - 4; k += 4 )
3287 const uchar* const sptr_k0 = sptr + j + space_ofs[k];
3288 const uchar* const sptr_k1 = sptr + j + space_ofs[k+1];
3289 const uchar* const sptr_k2 = sptr + j + space_ofs[k+2];
3290 const uchar* const sptr_k3 = sptr + j + space_ofs[k+3];
3292 v_float32x4 __b = v_cvt_f32(v_reinterpret_as_s32(v_load_expand_q(sptr_k0)));
3293 v_float32x4 __g = v_cvt_f32(v_reinterpret_as_s32(v_load_expand_q(sptr_k1)));
3294 v_float32x4 __r = v_cvt_f32(v_reinterpret_as_s32(v_load_expand_q(sptr_k2)));
3295 v_float32x4 __z = v_cvt_f32(v_reinterpret_as_s32(v_load_expand_q(sptr_k3)));
3296 v_float32x4 _b, _g, _r, _z;
3298 v_transpose4x4(__b, __g, __r, __z, _b, _g, _r, _z);
3300 v_float32x4 bt = v_abs(_b -_b0);
3301 v_float32x4 gt = v_abs(_g -_g0);
3302 v_float32x4 rt = v_abs(_r -_r0);
3305 v_store(buf, v_round(bt));
3307 v_float32x4 _w = v_float32x4(color_weight[buf[0]],color_weight[buf[1]],
3308 color_weight[buf[2]],color_weight[buf[3]]);
3309 v_float32x4 _sw = v_load(space_weight+k);
3321 float *bufFloat = (float*)buf;
3322 v_float32x4 sum4 = v_reduce_sum4(vsumw, vsumb, vsumg, vsumr);
3323 v_store(bufFloat, sum4);
3324 wsum += bufFloat[0];
3325 sum_b += bufFloat[1];
3326 sum_g += bufFloat[2];
3327 sum_r += bufFloat[3];
3331 for( ; k < maxk; k++ )
3333 const uchar* sptr_k = sptr + j + space_ofs[k];
3334 int b = sptr_k[0], g = sptr_k[1], r = sptr_k[2];
3335 float w = space_weight[k]*color_weight[std::abs(b - b0) +
3336 std::abs(g - g0) + std::abs(r - r0)];
3337 sum_b += b*w; sum_g += g*w; sum_r += r*w;
3341 b0 = cvRound(sum_b*wsum);
3342 g0 = cvRound(sum_g*wsum);
3343 r0 = cvRound(sum_r*wsum);
3344 dptr[j] = (uchar)b0; dptr[j+1] = (uchar)g0; dptr[j+2] = (uchar)r0;
3353 int radius, maxk, *space_ofs;
3354 float *space_weight, *color_weight;
3359 static bool ocl_bilateralFilter_8u(InputArray _src, OutputArray _dst, int d,
3360 double sigma_color, double sigma_space,
3364 if (ocl::Device::getDefault().isNVidia())
3368 int type = _src.type(), depth = CV_MAT_DEPTH(type), cn = CV_MAT_CN(type);
3369 int i, j, maxk, radius;
3371 if (depth != CV_8U || cn > 4)
3374 if (sigma_color <= 0)
3376 if (sigma_space <= 0)
3379 double gauss_color_coeff = -0.5 / (sigma_color * sigma_color);
3380 double gauss_space_coeff = -0.5 / (sigma_space * sigma_space);
3383 radius = cvRound(sigma_space * 1.5);
3386 radius = MAX(radius, 1);
3389 UMat src = _src.getUMat(), dst = _dst.getUMat(), temp;
3393 copyMakeBorder(src, temp, radius, radius, radius, radius, borderType);
3394 std::vector<float> _space_weight(d * d);
3395 std::vector<int> _space_ofs(d * d);
3396 float * const space_weight = &_space_weight[0];
3397 int * const space_ofs = &_space_ofs[0];
3399 // initialize space-related bilateral filter coefficients
3400 for( i = -radius, maxk = 0; i <= radius; i++ )
3401 for( j = -radius; j <= radius; j++ )
3403 double r = std::sqrt((double)i * i + (double)j * j);
3406 space_weight[maxk] = (float)std::exp(r * r * gauss_space_coeff);
3407 space_ofs[maxk++] = (int)(i * temp.step + j * cn);
3411 String cnstr = cn > 1 ? format("%d", cn) : "";
3412 String kernelName("bilateral");
3414 if ((ocl::Device::getDefault().isIntel()) &&
3415 (ocl::Device::getDefault().type() == ocl::Device::TYPE_GPU))
3418 if (dst.cols % 4 == 0 && cn == 1) // For single channel x4 sized images.
3420 kernelName = "bilateral_float4";
3424 ocl::Kernel k(kernelName.c_str(), ocl::imgproc::bilateral_oclsrc,
3425 format("-D radius=%d -D maxk=%d -D cn=%d -D int_t=%s -D uint_t=uint%s -D convert_int_t=%s"
3426 " -D uchar_t=%s -D float_t=%s -D convert_float_t=%s -D convert_uchar_t=%s -D gauss_color_coeff=(float)%f",
3427 radius, maxk, cn, ocl::typeToStr(CV_32SC(cn)), cnstr.c_str(),
3428 ocl::convertTypeStr(CV_8U, CV_32S, cn, cvt[0]),
3429 ocl::typeToStr(type), ocl::typeToStr(CV_32FC(cn)),
3430 ocl::convertTypeStr(CV_32S, CV_32F, cn, cvt[1]),
3431 ocl::convertTypeStr(CV_32F, CV_8U, cn, cvt[2]), gauss_color_coeff));
3435 Mat mspace_weight(1, d * d, CV_32FC1, space_weight);
3436 Mat mspace_ofs(1, d * d, CV_32SC1, space_ofs);
3437 UMat ucolor_weight, uspace_weight, uspace_ofs;
3439 mspace_weight.copyTo(uspace_weight);
3440 mspace_ofs.copyTo(uspace_ofs);
3442 k.args(ocl::KernelArg::ReadOnlyNoSize(temp), ocl::KernelArg::WriteOnly(dst),
3443 ocl::KernelArg::PtrReadOnly(uspace_weight),
3444 ocl::KernelArg::PtrReadOnly(uspace_ofs));
3446 size_t globalsize[2] = { (size_t)dst.cols / sizeDiv, (size_t)dst.rows };
3447 return k.run(2, globalsize, NULL, false);
3452 bilateralFilter_8u( const Mat& src, Mat& dst, int d,
3453 double sigma_color, double sigma_space,
3456 int cn = src.channels();
3457 int i, j, maxk, radius;
3458 Size size = src.size();
3460 CV_Assert( (src.type() == CV_8UC1 || src.type() == CV_8UC3) && src.data != dst.data );
3462 if( sigma_color <= 0 )
3464 if( sigma_space <= 0 )
3467 double gauss_color_coeff = -0.5/(sigma_color*sigma_color);
3468 double gauss_space_coeff = -0.5/(sigma_space*sigma_space);
3471 radius = cvRound(sigma_space*1.5);
3474 radius = MAX(radius, 1);
3478 copyMakeBorder( src, temp, radius, radius, radius, radius, borderType );
3480 std::vector<float> _color_weight(cn*256);
3481 std::vector<float> _space_weight(d*d);
3482 std::vector<int> _space_ofs(d*d);
3483 float* color_weight = &_color_weight[0];
3484 float* space_weight = &_space_weight[0];
3485 int* space_ofs = &_space_ofs[0];
3487 // initialize color-related bilateral filter coefficients
3489 for( i = 0; i < 256*cn; i++ )
3490 color_weight[i] = (float)std::exp(i*i*gauss_color_coeff);
3492 // initialize space-related bilateral filter coefficients
3493 for( i = -radius, maxk = 0; i <= radius; i++ )
3497 for( ; j <= radius; j++ )
3499 double r = std::sqrt((double)i*i + (double)j*j);
3502 space_weight[maxk] = (float)std::exp(r*r*gauss_space_coeff);
3503 space_ofs[maxk++] = (int)(i*temp.step + j*cn);
3507 BilateralFilter_8u_Invoker body(dst, temp, radius, maxk, space_ofs, space_weight, color_weight);
3508 parallel_for_(Range(0, size.height), body, dst.total()/(double)(1<<16));
3512 class BilateralFilter_32f_Invoker :
3513 public ParallelLoopBody
3517 BilateralFilter_32f_Invoker(int _cn, int _radius, int _maxk, int *_space_ofs,
3518 const Mat& _temp, Mat& _dest, float _scale_index, float *_space_weight, float *_expLUT) :
3519 cn(_cn), radius(_radius), maxk(_maxk), space_ofs(_space_ofs),
3520 temp(&_temp), dest(&_dest), scale_index(_scale_index), space_weight(_space_weight), expLUT(_expLUT)
3524 virtual void operator() (const Range& range) const
3527 Size size = dest->size();
3529 int CV_DECL_ALIGNED(16) idxBuf[4];
3530 bool haveSIMD128 = hasSIMD128();
3533 for( i = range.start; i < range.end; i++ )
3535 const float* sptr = temp->ptr<float>(i+radius) + radius*cn;
3536 float* dptr = dest->ptr<float>(i);
3540 for( j = 0; j < size.width; j++ )
3542 float sum = 0, wsum = 0;
3543 float val0 = sptr[j];
3548 v_float32x4 vecwsum = v_setzero_f32();
3549 v_float32x4 vecvsum = v_setzero_f32();
3550 const v_float32x4 _val0 = v_setall_f32(sptr[j]);
3551 const v_float32x4 _scale_index = v_setall_f32(scale_index);
3553 for (; k <= maxk - 4; k += 4)
3555 v_float32x4 _sw = v_load(space_weight + k);
3556 v_float32x4 _val = v_float32x4(sptr[j + space_ofs[k]],
3557 sptr[j + space_ofs[k + 1]],
3558 sptr[j + space_ofs[k + 2]],
3559 sptr[j + space_ofs[k + 3]]);
3560 v_float32x4 _alpha = v_abs(_val - _val0) * _scale_index;
3562 v_int32x4 _idx = v_round(_alpha);
3563 v_store(idxBuf, _idx);
3564 _alpha -= v_cvt_f32(_idx);
3566 v_float32x4 _explut = v_float32x4(expLUT[idxBuf[0]],
3570 v_float32x4 _explut1 = v_float32x4(expLUT[idxBuf[0] + 1],
3571 expLUT[idxBuf[1] + 1],
3572 expLUT[idxBuf[2] + 1],
3573 expLUT[idxBuf[3] + 1]);
3575 v_float32x4 _w = _sw * (_explut + (_alpha * (_explut1 - _explut)));
3581 float *bufFloat = (float*)idxBuf;
3582 v_float32x4 sum4 = v_reduce_sum4(vecwsum, vecvsum, vecwsum, vecvsum);
3583 v_store(bufFloat, sum4);
3585 wsum += bufFloat[0];
3589 for( ; k < maxk; k++ )
3591 float val = sptr[j + space_ofs[k]];
3592 float alpha = (float)(std::abs(val - val0)*scale_index);
3593 int idx = cvFloor(alpha);
3595 float w = space_weight[k]*(expLUT[idx] + alpha*(expLUT[idx+1] - expLUT[idx]));
3599 dptr[j] = (float)(sum/wsum);
3604 CV_Assert( cn == 3 );
3605 for( j = 0; j < size.width*3; j += 3 )
3607 float sum_b = 0, sum_g = 0, sum_r = 0, wsum = 0;
3608 float b0 = sptr[j], g0 = sptr[j+1], r0 = sptr[j+2];
3613 v_float32x4 sumw = v_setzero_f32();
3614 v_float32x4 sumb = v_setzero_f32();
3615 v_float32x4 sumg = v_setzero_f32();
3616 v_float32x4 sumr = v_setzero_f32();
3617 const v_float32x4 _b0 = v_setall_f32(b0);
3618 const v_float32x4 _g0 = v_setall_f32(g0);
3619 const v_float32x4 _r0 = v_setall_f32(r0);
3620 const v_float32x4 _scale_index = v_setall_f32(scale_index);
3622 for( ; k <= maxk-4; k += 4 )
3624 v_float32x4 _sw = v_load(space_weight + k);
3626 const float* const sptr_k0 = sptr + j + space_ofs[k];
3627 const float* const sptr_k1 = sptr + j + space_ofs[k+1];
3628 const float* const sptr_k2 = sptr + j + space_ofs[k+2];
3629 const float* const sptr_k3 = sptr + j + space_ofs[k+3];
3631 v_float32x4 _v0 = v_load(sptr_k0);
3632 v_float32x4 _v1 = v_load(sptr_k1);
3633 v_float32x4 _v2 = v_load(sptr_k2);
3634 v_float32x4 _v3 = v_load(sptr_k3);
3635 v_float32x4 _b, _g, _r, _dummy;
3637 v_transpose4x4(_v0, _v1, _v2, _v3, _b, _g, _r, _dummy);
3639 v_float32x4 _bt = v_abs(_b - _b0);
3640 v_float32x4 _gt = v_abs(_g - _g0);
3641 v_float32x4 _rt = v_abs(_r - _r0);
3642 v_float32x4 _alpha = _scale_index * (_bt + _gt + _rt);
3644 v_int32x4 _idx = v_round(_alpha);
3645 v_store((int*)idxBuf, _idx);
3646 _alpha -= v_cvt_f32(_idx);
3648 v_float32x4 _explut = v_float32x4(expLUT[idxBuf[0]],
3652 v_float32x4 _explut1 = v_float32x4(expLUT[idxBuf[0] + 1],
3653 expLUT[idxBuf[1] + 1],
3654 expLUT[idxBuf[2] + 1],
3655 expLUT[idxBuf[3] + 1]);
3657 v_float32x4 _w = _sw * (_explut + (_alpha * (_explut1 - _explut)));
3667 v_float32x4 sum4 = v_reduce_sum4(sumw, sumb, sumg, sumr);
3668 float *bufFloat = (float*)idxBuf;
3669 v_store(bufFloat, sum4);
3670 wsum += bufFloat[0];
3671 sum_b += bufFloat[1];
3672 sum_g += bufFloat[2];
3673 sum_r += bufFloat[3];
3677 for(; k < maxk; k++ )
3679 const float* sptr_k = sptr + j + space_ofs[k];
3680 float b = sptr_k[0], g = sptr_k[1], r = sptr_k[2];
3681 float alpha = (float)((std::abs(b - b0) +
3682 std::abs(g - g0) + std::abs(r - r0))*scale_index);
3683 int idx = cvFloor(alpha);
3685 float w = space_weight[k]*(expLUT[idx] + alpha*(expLUT[idx+1] - expLUT[idx]));
3686 sum_b += b*w; sum_g += g*w; sum_r += r*w;
3693 dptr[j] = b0; dptr[j+1] = g0; dptr[j+2] = r0;
3700 int cn, radius, maxk, *space_ofs;
3703 float scale_index, *space_weight, *expLUT;
3708 bilateralFilter_32f( const Mat& src, Mat& dst, int d,
3709 double sigma_color, double sigma_space,
3712 int cn = src.channels();
3713 int i, j, maxk, radius;
3714 double minValSrc=-1, maxValSrc=1;
3715 const int kExpNumBinsPerChannel = 1 << 12;
3716 int kExpNumBins = 0;
3717 float lastExpVal = 1.f;
3718 float len, scale_index;
3719 Size size = src.size();
3721 CV_Assert( (src.type() == CV_32FC1 || src.type() == CV_32FC3) && src.data != dst.data );
3723 if( sigma_color <= 0 )
3725 if( sigma_space <= 0 )
3728 double gauss_color_coeff = -0.5/(sigma_color*sigma_color);
3729 double gauss_space_coeff = -0.5/(sigma_space*sigma_space);
3732 radius = cvRound(sigma_space*1.5);
3735 radius = MAX(radius, 1);
3737 // compute the min/max range for the input image (even if multichannel)
3739 minMaxLoc( src.reshape(1), &minValSrc, &maxValSrc );
3740 if(std::abs(minValSrc - maxValSrc) < FLT_EPSILON)
3746 // temporary copy of the image with borders for easy processing
3748 copyMakeBorder( src, temp, radius, radius, radius, radius, borderType );
3749 const double insteadNaNValue = -5. * sigma_color;
3750 patchNaNs( temp, insteadNaNValue ); // this replacement of NaNs makes the assumption that depth values are nonnegative
3751 // TODO: make insteadNaNValue avalible in the outside function interface to control the cases breaking the assumption
3752 // allocate lookup tables
3753 std::vector<float> _space_weight(d*d);
3754 std::vector<int> _space_ofs(d*d);
3755 float* space_weight = &_space_weight[0];
3756 int* space_ofs = &_space_ofs[0];
3758 // assign a length which is slightly more than needed
3759 len = (float)(maxValSrc - minValSrc) * cn;
3760 kExpNumBins = kExpNumBinsPerChannel * cn;
3761 std::vector<float> _expLUT(kExpNumBins+2);
3762 float* expLUT = &_expLUT[0];
3764 scale_index = kExpNumBins/len;
3766 // initialize the exp LUT
3767 for( i = 0; i < kExpNumBins+2; i++ )
3769 if( lastExpVal > 0.f )
3771 double val = i / scale_index;
3772 expLUT[i] = (float)std::exp(val * val * gauss_color_coeff);
3773 lastExpVal = expLUT[i];
3779 // initialize space-related bilateral filter coefficients
3780 for( i = -radius, maxk = 0; i <= radius; i++ )
3781 for( j = -radius; j <= radius; j++ )
3783 double r = std::sqrt((double)i*i + (double)j*j);
3786 space_weight[maxk] = (float)std::exp(r*r*gauss_space_coeff);
3787 space_ofs[maxk++] = (int)(i*(temp.step/sizeof(float)) + j*cn);
3790 // parallel_for usage
3792 BilateralFilter_32f_Invoker body(cn, radius, maxk, space_ofs, temp, dst, scale_index, space_weight, expLUT);
3793 parallel_for_(Range(0, size.height), body, dst.total()/(double)(1<<16));
3797 #define IPP_BILATERAL_PARALLEL 1
3800 class ipp_bilateralFilterParallel: public ParallelLoopBody
3803 ipp_bilateralFilterParallel(::ipp::IwiImage &_src, ::ipp::IwiImage &_dst, int _radius, Ipp32f _valSquareSigma, Ipp32f _posSquareSigma, ::ipp::IwiBorderType _borderType, bool *_ok):
3804 src(_src), dst(_dst)
3809 valSquareSigma = _valSquareSigma;
3810 posSquareSigma = _posSquareSigma;
3811 borderType = _borderType;
3815 ~ipp_bilateralFilterParallel() {}
3817 virtual void operator() (const Range& range) const
3824 ::ipp::IwiTile tile = ::ipp::IwiRoi(0, range.start, dst.m_size.width, range.end - range.start);
3825 CV_INSTRUMENT_FUN_IPP(::ipp::iwiFilterBilateral, src, dst, radius, valSquareSigma, posSquareSigma, ::ipp::IwDefault(), borderType, tile);
3827 catch(::ipp::IwException)
3834 ::ipp::IwiImage &src;
3835 ::ipp::IwiImage &dst;
3838 Ipp32f valSquareSigma;
3839 Ipp32f posSquareSigma;
3840 ::ipp::IwiBorderType borderType;
3843 const ipp_bilateralFilterParallel& operator= (const ipp_bilateralFilterParallel&);
3847 static bool ipp_bilateralFilter(Mat &src, Mat &dst, int d, double sigmaColor, double sigmaSpace, int borderType)
3850 CV_INSTRUMENT_REGION_IPP()
3852 int radius = IPP_MAX(((d <= 0)?cvRound(sigmaSpace*1.5):d/2), 1);
3853 Ipp32f valSquareSigma = (Ipp32f)((sigmaColor <= 0)?1:sigmaColor*sigmaColor);
3854 Ipp32f posSquareSigma = (Ipp32f)((sigmaSpace <= 0)?1:sigmaSpace*sigmaSpace);
3856 // Acquire data and begin processing
3859 ::ipp::IwiImage iwSrc = ippiGetImage(src);
3860 ::ipp::IwiImage iwDst = ippiGetImage(dst);
3861 ::ipp::IwiBorderSize borderSize(radius);
3862 ::ipp::IwiBorderType ippBorder(ippiGetBorder(iwSrc, borderType, borderSize));
3866 const int threads = ippiSuggestThreadsNum(iwDst, 2);
3867 if(IPP_BILATERAL_PARALLEL && threads > 1) {
3869 Range range(0, (int)iwDst.m_size.height);
3870 ipp_bilateralFilterParallel invoker(iwSrc, iwDst, radius, valSquareSigma, posSquareSigma, ippBorder, &ok);
3874 parallel_for_(range, invoker, threads*4);
3879 CV_INSTRUMENT_FUN_IPP(::ipp::iwiFilterBilateral, iwSrc, iwDst, radius, valSquareSigma, posSquareSigma, ::ipp::IwDefault(), ippBorder);
3882 catch (::ipp::IwException)
3888 CV_UNUSED(src); CV_UNUSED(dst); CV_UNUSED(d); CV_UNUSED(sigmaColor); CV_UNUSED(sigmaSpace); CV_UNUSED(borderType);
3896 void cv::bilateralFilter( InputArray _src, OutputArray _dst, int d,
3897 double sigmaColor, double sigmaSpace,
3900 CV_INSTRUMENT_REGION()
3902 _dst.create( _src.size(), _src.type() );
3904 CV_OCL_RUN(_src.dims() <= 2 && _dst.isUMat(),
3905 ocl_bilateralFilter_8u(_src, _dst, d, sigmaColor, sigmaSpace, borderType))
3907 Mat src = _src.getMat(), dst = _dst.getMat();
3909 CV_IPP_RUN_FAST(ipp_bilateralFilter(src, dst, d, sigmaColor, sigmaSpace, borderType));
3911 if( src.depth() == CV_8U )
3912 bilateralFilter_8u( src, dst, d, sigmaColor, sigmaSpace, borderType );
3913 else if( src.depth() == CV_32F )
3914 bilateralFilter_32f( src, dst, d, sigmaColor, sigmaSpace, borderType );
3916 CV_Error( CV_StsUnsupportedFormat,
3917 "Bilateral filtering is only implemented for 8u and 32f images" );
3920 //////////////////////////////////////////////////////////////////////////////////////////
3923 cvSmooth( const void* srcarr, void* dstarr, int smooth_type,
3924 int param1, int param2, double param3, double param4 )
3926 cv::Mat src = cv::cvarrToMat(srcarr), dst0 = cv::cvarrToMat(dstarr), dst = dst0;
3928 CV_Assert( dst.size() == src.size() &&
3929 (smooth_type == CV_BLUR_NO_SCALE || dst.type() == src.type()) );
3934 if( smooth_type == CV_BLUR || smooth_type == CV_BLUR_NO_SCALE )
3935 cv::boxFilter( src, dst, dst.depth(), cv::Size(param1, param2), cv::Point(-1,-1),
3936 smooth_type == CV_BLUR, cv::BORDER_REPLICATE );
3937 else if( smooth_type == CV_GAUSSIAN )
3938 cv::GaussianBlur( src, dst, cv::Size(param1, param2), param3, param4, cv::BORDER_REPLICATE );
3939 else if( smooth_type == CV_MEDIAN )
3940 cv::medianBlur( src, dst, param1 );
3942 cv::bilateralFilter( src, dst, param1, param3, param4, cv::BORDER_REPLICATE );
3944 if( dst.data != dst0.data )
3945 CV_Error( CV_StsUnmatchedFormats, "The destination image does not have the proper type" );