Merge pull request #10629 from GlueCrow:ocl_mog2_test_fix
[platform/upstream/opencv.git] / modules / imgproc / src / smooth.cpp
1 /*M///////////////////////////////////////////////////////////////////////////////////////
2 //
3 //  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
4 //
5 //  By downloading, copying, installing or using the software you agree to this license.
6 //  If you do not agree to this license, do not download, install,
7 //  copy or use the software.
8 //
9 //
10 //                           License Agreement
11 //                For Open Source Computer Vision Library
12 //
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.
17 //
18 // Redistribution and use in source and binary forms, with or without modification,
19 // are permitted provided that the following conditions are met:
20 //
21 //   * Redistribution's of source code must retain the above copyright notice,
22 //     this list of conditions and the following disclaimer.
23 //
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.
27 //
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.
30 //
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.
41 //
42 //M*/
43
44 #include "precomp.hpp"
45 #include "opencv2/core/hal/intrin.hpp"
46 #include "opencl_kernels_imgproc.hpp"
47
48 #include "opencv2/core/openvx/ovx_defs.hpp"
49
50 #include "filter.hpp"
51
52 /*
53  * This file includes the code, contributed by Simon Perreault
54  * (the function icvMedianBlur_8u_O1)
55  *
56  * Constant-time median filtering -- http://nomis80.org/ctmf.html
57  * Copyright (C) 2006 Simon Perreault
58  *
59  * Contact:
60  *  Laboratoire de vision et systemes numeriques
61  *  Pavillon Adrien-Pouliot
62  *  Universite Laval
63  *  Sainte-Foy, Quebec, Canada
64  *  G1K 7P4
65  *
66  *  perreaul@gel.ulaval.ca
67  */
68
69 namespace cv
70 {
71
72 /****************************************************************************************\
73                                          Box Filter
74 \****************************************************************************************/
75
76 template<typename T, typename ST>
77 struct RowSum :
78         public BaseRowFilter
79 {
80     RowSum( int _ksize, int _anchor ) :
81         BaseRowFilter()
82     {
83         ksize = _ksize;
84         anchor = _anchor;
85     }
86
87     virtual void operator()(const uchar* src, uchar* dst, int width, int cn)
88     {
89         const T* S = (const T*)src;
90         ST* D = (ST*)dst;
91         int i = 0, k, ksz_cn = ksize*cn;
92
93         width = (width - 1)*cn;
94         if( ksize == 3 )
95         {
96             for( i = 0; i < width + cn; i++ )
97             {
98                 D[i] = (ST)S[i] + (ST)S[i+cn] + (ST)S[i+cn*2];
99             }
100         }
101         else if( ksize == 5 )
102         {
103             for( i = 0; i < width + cn; i++ )
104             {
105                 D[i] = (ST)S[i] + (ST)S[i+cn] + (ST)S[i+cn*2] + (ST)S[i + cn*3] + (ST)S[i + cn*4];
106             }
107         }
108         else if( cn == 1 )
109         {
110             ST s = 0;
111             for( i = 0; i < ksz_cn; i++ )
112                 s += (ST)S[i];
113             D[0] = s;
114             for( i = 0; i < width; i++ )
115             {
116                 s += (ST)S[i + ksz_cn] - (ST)S[i];
117                 D[i+1] = s;
118             }
119         }
120         else if( cn == 3 )
121         {
122             ST s0 = 0, s1 = 0, s2 = 0;
123             for( i = 0; i < ksz_cn; i += 3 )
124             {
125                 s0 += (ST)S[i];
126                 s1 += (ST)S[i+1];
127                 s2 += (ST)S[i+2];
128             }
129             D[0] = s0;
130             D[1] = s1;
131             D[2] = s2;
132             for( i = 0; i < width; i += 3 )
133             {
134                 s0 += (ST)S[i + ksz_cn] - (ST)S[i];
135                 s1 += (ST)S[i + ksz_cn + 1] - (ST)S[i + 1];
136                 s2 += (ST)S[i + ksz_cn + 2] - (ST)S[i + 2];
137                 D[i+3] = s0;
138                 D[i+4] = s1;
139                 D[i+5] = s2;
140             }
141         }
142         else if( cn == 4 )
143         {
144             ST s0 = 0, s1 = 0, s2 = 0, s3 = 0;
145             for( i = 0; i < ksz_cn; i += 4 )
146             {
147                 s0 += (ST)S[i];
148                 s1 += (ST)S[i+1];
149                 s2 += (ST)S[i+2];
150                 s3 += (ST)S[i+3];
151             }
152             D[0] = s0;
153             D[1] = s1;
154             D[2] = s2;
155             D[3] = s3;
156             for( i = 0; i < width; i += 4 )
157             {
158                 s0 += (ST)S[i + ksz_cn] - (ST)S[i];
159                 s1 += (ST)S[i + ksz_cn + 1] - (ST)S[i + 1];
160                 s2 += (ST)S[i + ksz_cn + 2] - (ST)S[i + 2];
161                 s3 += (ST)S[i + ksz_cn + 3] - (ST)S[i + 3];
162                 D[i+4] = s0;
163                 D[i+5] = s1;
164                 D[i+6] = s2;
165                 D[i+7] = s3;
166             }
167         }
168         else
169             for( k = 0; k < cn; k++, S++, D++ )
170             {
171                 ST s = 0;
172                 for( i = 0; i < ksz_cn; i += cn )
173                     s += (ST)S[i];
174                 D[0] = s;
175                 for( i = 0; i < width; i += cn )
176                 {
177                     s += (ST)S[i + ksz_cn] - (ST)S[i];
178                     D[i+cn] = s;
179                 }
180             }
181     }
182 };
183
184
185 template<typename ST, typename T>
186 struct ColumnSum :
187         public BaseColumnFilter
188 {
189     ColumnSum( int _ksize, int _anchor, double _scale ) :
190         BaseColumnFilter()
191     {
192         ksize = _ksize;
193         anchor = _anchor;
194         scale = _scale;
195         sumCount = 0;
196     }
197
198     virtual void reset() { sumCount = 0; }
199
200     virtual void operator()(const uchar** src, uchar* dst, int dststep, int count, int width)
201     {
202         int i;
203         ST* SUM;
204         bool haveScale = scale != 1;
205         double _scale = scale;
206
207         if( width != (int)sum.size() )
208         {
209             sum.resize(width);
210             sumCount = 0;
211         }
212
213         SUM = &sum[0];
214         if( sumCount == 0 )
215         {
216             memset((void*)SUM, 0, width*sizeof(ST));
217
218             for( ; sumCount < ksize - 1; sumCount++, src++ )
219             {
220                 const ST* Sp = (const ST*)src[0];
221
222                 for( i = 0; i < width; i++ )
223                     SUM[i] += Sp[i];
224             }
225         }
226         else
227         {
228             CV_Assert( sumCount == ksize-1 );
229             src += ksize-1;
230         }
231
232         for( ; count--; src++ )
233         {
234             const ST* Sp = (const ST*)src[0];
235             const ST* Sm = (const ST*)src[1-ksize];
236             T* D = (T*)dst;
237             if( haveScale )
238             {
239                 for( i = 0; i <= width - 2; i += 2 )
240                 {
241                     ST s0 = SUM[i] + Sp[i], s1 = SUM[i+1] + Sp[i+1];
242                     D[i] = saturate_cast<T>(s0*_scale);
243                     D[i+1] = saturate_cast<T>(s1*_scale);
244                     s0 -= Sm[i]; s1 -= Sm[i+1];
245                     SUM[i] = s0; SUM[i+1] = s1;
246                 }
247
248                 for( ; i < width; i++ )
249                 {
250                     ST s0 = SUM[i] + Sp[i];
251                     D[i] = saturate_cast<T>(s0*_scale);
252                     SUM[i] = s0 - Sm[i];
253                 }
254             }
255             else
256             {
257                 for( i = 0; i <= width - 2; i += 2 )
258                 {
259                     ST s0 = SUM[i] + Sp[i], s1 = SUM[i+1] + Sp[i+1];
260                     D[i] = saturate_cast<T>(s0);
261                     D[i+1] = saturate_cast<T>(s1);
262                     s0 -= Sm[i]; s1 -= Sm[i+1];
263                     SUM[i] = s0; SUM[i+1] = s1;
264                 }
265
266                 for( ; i < width; i++ )
267                 {
268                     ST s0 = SUM[i] + Sp[i];
269                     D[i] = saturate_cast<T>(s0);
270                     SUM[i] = s0 - Sm[i];
271                 }
272             }
273             dst += dststep;
274         }
275     }
276
277     double scale;
278     int sumCount;
279     std::vector<ST> sum;
280 };
281
282
283 template<>
284 struct ColumnSum<int, uchar> :
285         public BaseColumnFilter
286 {
287     ColumnSum( int _ksize, int _anchor, double _scale ) :
288         BaseColumnFilter()
289     {
290         ksize = _ksize;
291         anchor = _anchor;
292         scale = _scale;
293         sumCount = 0;
294     }
295
296     virtual void reset() { sumCount = 0; }
297
298     virtual void operator()(const uchar** src, uchar* dst, int dststep, int count, int width)
299     {
300         int* SUM;
301         bool haveScale = scale != 1;
302         double _scale = scale;
303
304 #if CV_SIMD128
305         bool haveSIMD128 = hasSIMD128();
306 #endif
307
308         if( width != (int)sum.size() )
309         {
310             sum.resize(width);
311             sumCount = 0;
312         }
313
314         SUM = &sum[0];
315         if( sumCount == 0 )
316         {
317             memset((void*)SUM, 0, width*sizeof(int));
318             for( ; sumCount < ksize - 1; sumCount++, src++ )
319             {
320                 const int* Sp = (const int*)src[0];
321                 int i = 0;
322 #if CV_SIMD128
323                 if( haveSIMD128 )
324                 {
325                     for (; i <= width - 4; i += 4)
326                     {
327                         v_store(SUM + i, v_load(SUM + i) + v_load(Sp + i));
328                     }
329                 }
330 #endif
331                 for( ; i < width; i++ )
332                     SUM[i] += Sp[i];
333             }
334         }
335         else
336         {
337             CV_Assert( sumCount == ksize-1 );
338             src += ksize-1;
339         }
340
341         for( ; count--; src++ )
342         {
343             const int* Sp = (const int*)src[0];
344             const int* Sm = (const int*)src[1-ksize];
345             uchar* D = (uchar*)dst;
346             if( haveScale )
347             {
348                 int i = 0;
349 #if CV_SIMD128
350                 if( haveSIMD128 )
351                 {
352
353                     v_float32x4 v_scale = v_setall_f32((float)_scale);
354                     for( ; i <= width-8; i+=8 )
355                     {
356                         v_int32x4 v_s0 = v_load(SUM + i) + v_load(Sp + i);
357                         v_int32x4 v_s01 = v_load(SUM + i + 4) + v_load(Sp + i + 4);
358
359                         v_uint32x4 v_s0d = v_reinterpret_as_u32(v_round(v_cvt_f32(v_s0) * v_scale));
360                         v_uint32x4 v_s01d = v_reinterpret_as_u32(v_round(v_cvt_f32(v_s01) * v_scale));
361
362                         v_uint16x8 v_dst = v_pack(v_s0d, v_s01d);
363                         v_pack_store(D + i, v_dst);
364
365                         v_store(SUM + i, v_s0 - v_load(Sm + i));
366                         v_store(SUM + i + 4, v_s01 - v_load(Sm + i + 4));
367                     }
368                 }
369 #endif
370                 for( ; i < width; i++ )
371                 {
372                     int s0 = SUM[i] + Sp[i];
373                     D[i] = saturate_cast<uchar>(s0*_scale);
374                     SUM[i] = s0 - Sm[i];
375                 }
376             }
377             else
378             {
379                 int i = 0;
380 #if CV_SIMD128
381                 if( haveSIMD128 )
382                 {
383                     for( ; i <= width-8; i+=8 )
384                     {
385                         v_int32x4 v_s0 = v_load(SUM + i) + v_load(Sp + i);
386                         v_int32x4 v_s01 = v_load(SUM + i + 4) + v_load(Sp + i + 4);
387
388                         v_uint16x8 v_dst = v_pack(v_reinterpret_as_u32(v_s0), v_reinterpret_as_u32(v_s01));
389                         v_pack_store(D + i, v_dst);
390
391                         v_store(SUM + i, v_s0 - v_load(Sm + i));
392                         v_store(SUM + i + 4, v_s01 - v_load(Sm + i + 4));
393                     }
394                 }
395 #endif
396
397                 for( ; i < width; i++ )
398                 {
399                     int s0 = SUM[i] + Sp[i];
400                     D[i] = saturate_cast<uchar>(s0);
401                     SUM[i] = s0 - Sm[i];
402                 }
403             }
404             dst += dststep;
405         }
406     }
407
408     double scale;
409     int sumCount;
410     std::vector<int> sum;
411 };
412
413
414 template<>
415 struct ColumnSum<ushort, uchar> :
416 public BaseColumnFilter
417 {
418     enum { SHIFT = 23 };
419
420     ColumnSum( int _ksize, int _anchor, double _scale ) :
421     BaseColumnFilter()
422     {
423         ksize = _ksize;
424         anchor = _anchor;
425         scale = _scale;
426         sumCount = 0;
427         divDelta = 0;
428         divScale = 1;
429         if( scale != 1 )
430         {
431             int d = cvRound(1./scale);
432             double scalef = ((double)(1 << SHIFT))/d;
433             divScale = cvFloor(scalef);
434             scalef -= divScale;
435             divDelta = d/2;
436             if( scalef < 0.5 )
437                 divDelta++;
438             else
439                 divScale++;
440         }
441     }
442
443     virtual void reset() { sumCount = 0; }
444
445     virtual void operator()(const uchar** src, uchar* dst, int dststep, int count, int width)
446     {
447         const int ds = divScale;
448         const int dd = divDelta;
449         ushort* SUM;
450         const bool haveScale = scale != 1;
451
452 #if CV_SIMD128
453         bool haveSIMD128 = hasSIMD128();
454 #endif
455
456         if( width != (int)sum.size() )
457         {
458             sum.resize(width);
459             sumCount = 0;
460         }
461
462         SUM = &sum[0];
463         if( sumCount == 0 )
464         {
465             memset((void*)SUM, 0, width*sizeof(SUM[0]));
466             for( ; sumCount < ksize - 1; sumCount++, src++ )
467             {
468                 const ushort* Sp = (const ushort*)src[0];
469                 int i = 0;
470 #if CV_SIMD128
471                 if( haveSIMD128 )
472                 {
473                     for( ; i <= width - 8; i += 8 )
474                     {
475                         v_store(SUM + i, v_load(SUM + i) + v_load(Sp + i));
476                     }
477                 }
478 #endif
479                 for( ; i < width; i++ )
480                     SUM[i] += Sp[i];
481             }
482         }
483         else
484         {
485             CV_Assert( sumCount == ksize-1 );
486             src += ksize-1;
487         }
488
489         for( ; count--; src++ )
490         {
491             const ushort* Sp = (const ushort*)src[0];
492             const ushort* Sm = (const ushort*)src[1-ksize];
493             uchar* D = (uchar*)dst;
494             if( haveScale )
495             {
496                 int i = 0;
497             #if CV_SIMD128
498                 v_uint32x4 ds4 = v_setall_u32((unsigned)ds);
499                 v_uint16x8 dd8 = v_setall_u16((ushort)dd);
500
501                 for( ; i <= width-16; i+=16 )
502                 {
503                     v_uint16x8 _sm0 = v_load(Sm + i);
504                     v_uint16x8 _sm1 = v_load(Sm + i + 8);
505
506                     v_uint16x8 _s0 = v_add_wrap(v_load(SUM + i), v_load(Sp + i));
507                     v_uint16x8 _s1 = v_add_wrap(v_load(SUM + i + 8), v_load(Sp + i + 8));
508
509                     v_uint32x4 _s00, _s01, _s10, _s11;
510
511                     v_expand(_s0 + dd8, _s00, _s01);
512                     v_expand(_s1 + dd8, _s10, _s11);
513
514                     _s00 = v_shr<SHIFT>(_s00*ds4);
515                     _s01 = v_shr<SHIFT>(_s01*ds4);
516                     _s10 = v_shr<SHIFT>(_s10*ds4);
517                     _s11 = v_shr<SHIFT>(_s11*ds4);
518
519                     v_int16x8 r0 = v_pack(v_reinterpret_as_s32(_s00), v_reinterpret_as_s32(_s01));
520                     v_int16x8 r1 = v_pack(v_reinterpret_as_s32(_s10), v_reinterpret_as_s32(_s11));
521
522                     _s0 = v_sub_wrap(_s0, _sm0);
523                     _s1 = v_sub_wrap(_s1, _sm1);
524
525                     v_store(D + i, v_pack_u(r0, r1));
526                     v_store(SUM + i, _s0);
527                     v_store(SUM + i + 8, _s1);
528                 }
529             #endif
530                 for( ; i < width; i++ )
531                 {
532                     int s0 = SUM[i] + Sp[i];
533                     D[i] = (uchar)((s0 + dd)*ds >> SHIFT);
534                     SUM[i] = (ushort)(s0 - Sm[i]);
535                 }
536             }
537             else
538             {
539                 int i = 0;
540                 for( ; i < width; i++ )
541                 {
542                     int s0 = SUM[i] + Sp[i];
543                     D[i] = saturate_cast<uchar>(s0);
544                     SUM[i] = (ushort)(s0 - Sm[i]);
545                 }
546             }
547             dst += dststep;
548         }
549     }
550
551     double scale;
552     int sumCount;
553     int divDelta;
554     int divScale;
555     std::vector<ushort> sum;
556 };
557
558
559 template<>
560 struct ColumnSum<int, short> :
561         public BaseColumnFilter
562 {
563     ColumnSum( int _ksize, int _anchor, double _scale ) :
564         BaseColumnFilter()
565     {
566         ksize = _ksize;
567         anchor = _anchor;
568         scale = _scale;
569         sumCount = 0;
570     }
571
572     virtual void reset() { sumCount = 0; }
573
574     virtual void operator()(const uchar** src, uchar* dst, int dststep, int count, int width)
575     {
576         int i;
577         int* SUM;
578         bool haveScale = scale != 1;
579         double _scale = scale;
580
581 #if CV_SIMD128
582         bool haveSIMD128 = hasSIMD128();
583 #endif
584
585         if( width != (int)sum.size() )
586         {
587             sum.resize(width);
588             sumCount = 0;
589         }
590
591         SUM = &sum[0];
592         if( sumCount == 0 )
593         {
594             memset((void*)SUM, 0, width*sizeof(int));
595             for( ; sumCount < ksize - 1; sumCount++, src++ )
596             {
597                 const int* Sp = (const int*)src[0];
598                 i = 0;
599 #if CV_SIMD128
600                 if( haveSIMD128 )
601                 {
602                     for( ; i <= width - 4; i+=4 )
603                     {
604                         v_store(SUM + i, v_load(SUM + i) + v_load(Sp + i));
605                     }
606                 }
607                 #endif
608                 for( ; i < width; i++ )
609                     SUM[i] += Sp[i];
610             }
611         }
612         else
613         {
614             CV_Assert( sumCount == ksize-1 );
615             src += ksize-1;
616         }
617
618         for( ; count--; src++ )
619         {
620             const int* Sp = (const int*)src[0];
621             const int* Sm = (const int*)src[1-ksize];
622             short* D = (short*)dst;
623             if( haveScale )
624             {
625                 i = 0;
626 #if CV_SIMD128
627                 if( haveSIMD128 )
628                 {
629                     v_float32x4 v_scale = v_setall_f32((float)_scale);
630                     for( ; i <= width-8; i+=8 )
631                     {
632                         v_int32x4 v_s0 = v_load(SUM + i) + v_load(Sp + i);
633                         v_int32x4 v_s01 = v_load(SUM + i + 4) + v_load(Sp + i + 4);
634
635                         v_int32x4 v_s0d =  v_round(v_cvt_f32(v_s0) * v_scale);
636                         v_int32x4 v_s01d = v_round(v_cvt_f32(v_s01) * v_scale);
637                         v_store(D + i, v_pack(v_s0d, v_s01d));
638
639                         v_store(SUM + i, v_s0 - v_load(Sm + i));
640                         v_store(SUM + i + 4, v_s01 - v_load(Sm + i + 4));
641                     }
642                 }
643 #endif
644                 for( ; i < width; i++ )
645                 {
646                     int s0 = SUM[i] + Sp[i];
647                     D[i] = saturate_cast<short>(s0*_scale);
648                     SUM[i] = s0 - Sm[i];
649                 }
650             }
651             else
652             {
653                 i = 0;
654 #if CV_SIMD128
655                 if( haveSIMD128 )
656                 {
657                     for( ; i <= width-8; i+=8 )
658                     {
659                         v_int32x4 v_s0 = v_load(SUM + i) + v_load(Sp + i);
660                         v_int32x4 v_s01 = v_load(SUM + i + 4) + v_load(Sp + i + 4);
661
662                         v_store(D + i, v_pack(v_s0, v_s01));
663
664                         v_store(SUM + i, v_s0 - v_load(Sm + i));
665                         v_store(SUM + i + 4, v_s01 - v_load(Sm + i + 4));
666                     }
667                 }
668 #endif
669
670                 for( ; i < width; i++ )
671                 {
672                     int s0 = SUM[i] + Sp[i];
673                     D[i] = saturate_cast<short>(s0);
674                     SUM[i] = s0 - Sm[i];
675                 }
676             }
677             dst += dststep;
678         }
679     }
680
681     double scale;
682     int sumCount;
683     std::vector<int> sum;
684 };
685
686
687 template<>
688 struct ColumnSum<int, ushort> :
689         public BaseColumnFilter
690 {
691     ColumnSum( int _ksize, int _anchor, double _scale ) :
692         BaseColumnFilter()
693     {
694         ksize = _ksize;
695         anchor = _anchor;
696         scale = _scale;
697         sumCount = 0;
698     }
699
700     virtual void reset() { sumCount = 0; }
701
702     virtual void operator()(const uchar** src, uchar* dst, int dststep, int count, int width)
703     {
704         int* SUM;
705         bool haveScale = scale != 1;
706         double _scale = scale;
707
708 #if CV_SIMD128
709         bool haveSIMD128 = hasSIMD128();
710 #endif
711
712         if( width != (int)sum.size() )
713         {
714             sum.resize(width);
715             sumCount = 0;
716         }
717
718         SUM = &sum[0];
719         if( sumCount == 0 )
720         {
721             memset((void*)SUM, 0, width*sizeof(int));
722             for( ; sumCount < ksize - 1; sumCount++, src++ )
723             {
724                 const int* Sp = (const int*)src[0];
725                 int i = 0;
726 #if CV_SIMD128
727                 if( haveSIMD128 )
728                 {
729                     for (; i <= width - 4; i += 4)
730                     {
731                         v_store(SUM + i, v_load(SUM + i) + v_load(Sp + i));
732                     }
733                 }
734 #endif
735                 for( ; i < width; i++ )
736                     SUM[i] += Sp[i];
737             }
738         }
739         else
740         {
741             CV_Assert( sumCount == ksize-1 );
742             src += ksize-1;
743         }
744
745         for( ; count--; src++ )
746         {
747             const int* Sp = (const int*)src[0];
748             const int* Sm = (const int*)src[1-ksize];
749             ushort* D = (ushort*)dst;
750             if( haveScale )
751             {
752                 int i = 0;
753 #if CV_SIMD128
754                 if( haveSIMD128 )
755                 {
756                     v_float32x4 v_scale = v_setall_f32((float)_scale);
757                     for( ; i <= width-8; i+=8 )
758                     {
759                         v_int32x4 v_s0 = v_load(SUM + i) + v_load(Sp + i);
760                         v_int32x4 v_s01 = v_load(SUM + i + 4) + v_load(Sp + i + 4);
761
762                         v_uint32x4 v_s0d = v_reinterpret_as_u32(v_round(v_cvt_f32(v_s0) * v_scale));
763                         v_uint32x4 v_s01d = v_reinterpret_as_u32(v_round(v_cvt_f32(v_s01) * v_scale));
764                         v_store(D + i, v_pack(v_s0d, v_s01d));
765
766                         v_store(SUM + i, v_s0 - v_load(Sm + i));
767                         v_store(SUM + i + 4, v_s01 - v_load(Sm + i + 4));
768                     }
769                 }
770 #endif
771                 for( ; i < width; i++ )
772                 {
773                     int s0 = SUM[i] + Sp[i];
774                     D[i] = saturate_cast<ushort>(s0*_scale);
775                     SUM[i] = s0 - Sm[i];
776                 }
777             }
778             else
779             {
780                 int i = 0;
781 #if CV_SIMD128
782                 if( haveSIMD128 )
783                 {
784                     for( ; i <= width-8; i+=8 )
785                     {
786                         v_int32x4 v_s0 = v_load(SUM + i) + v_load(Sp + i);
787                         v_int32x4 v_s01 = v_load(SUM + i + 4) + v_load(Sp + i + 4);
788
789                         v_store(D + i, v_pack(v_reinterpret_as_u32(v_s0), v_reinterpret_as_u32(v_s01)));
790
791                         v_store(SUM + i, v_s0 - v_load(Sm + i));
792                         v_store(SUM + i + 4, v_s01 - v_load(Sm + i + 4));
793                     }
794                 }
795 #endif
796                 for( ; i < width; i++ )
797                 {
798                     int s0 = SUM[i] + Sp[i];
799                     D[i] = saturate_cast<ushort>(s0);
800                     SUM[i] = s0 - Sm[i];
801                 }
802             }
803             dst += dststep;
804         }
805     }
806
807     double scale;
808     int sumCount;
809     std::vector<int> sum;
810 };
811
812 template<>
813 struct ColumnSum<int, int> :
814         public BaseColumnFilter
815 {
816     ColumnSum( int _ksize, int _anchor, double _scale ) :
817         BaseColumnFilter()
818     {
819         ksize = _ksize;
820         anchor = _anchor;
821         scale = _scale;
822         sumCount = 0;
823     }
824
825     virtual void reset() { sumCount = 0; }
826
827     virtual void operator()(const uchar** src, uchar* dst, int dststep, int count, int width)
828     {
829         int* SUM;
830         bool haveScale = scale != 1;
831         double _scale = scale;
832
833 #if CV_SIMD128
834         bool haveSIMD128 = hasSIMD128();
835 #endif
836
837         if( width != (int)sum.size() )
838         {
839             sum.resize(width);
840             sumCount = 0;
841         }
842
843         SUM = &sum[0];
844         if( sumCount == 0 )
845         {
846             memset((void*)SUM, 0, width*sizeof(int));
847             for( ; sumCount < ksize - 1; sumCount++, src++ )
848             {
849                 const int* Sp = (const int*)src[0];
850                 int i = 0;
851 #if CV_SIMD128
852                 if( haveSIMD128 )
853                 {
854                     for( ; i <= width - 4; i+=4 )
855                     {
856                         v_store(SUM + i, v_load(SUM + i) + v_load(Sp + i));
857                     }
858                 }
859 #endif
860                 for( ; i < width; i++ )
861                     SUM[i] += Sp[i];
862             }
863         }
864         else
865         {
866             CV_Assert( sumCount == ksize-1 );
867             src += ksize-1;
868         }
869
870         for( ; count--; src++ )
871         {
872             const int* Sp = (const int*)src[0];
873             const int* Sm = (const int*)src[1-ksize];
874             int* D = (int*)dst;
875             if( haveScale )
876             {
877                 int i = 0;
878 #if CV_SIMD128
879                 if( haveSIMD128 )
880                 {
881                     v_float32x4 v_scale = v_setall_f32((float)_scale);
882                     for( ; i <= width-4; i+=4 )
883                     {
884                         v_int32x4 v_s0 = v_load(SUM + i) + v_load(Sp + i);
885                         v_int32x4 v_s0d = v_round(v_cvt_f32(v_s0) * v_scale);
886
887                         v_store(D + i, v_s0d);
888                         v_store(SUM + i, v_s0 - v_load(Sm + i));
889                     }
890                 }
891 #endif
892                 for( ; i < width; i++ )
893                 {
894                     int s0 = SUM[i] + Sp[i];
895                     D[i] = saturate_cast<int>(s0*_scale);
896                     SUM[i] = s0 - Sm[i];
897                 }
898             }
899             else
900             {
901                 int i = 0;
902 #if CV_SIMD128
903                 if( haveSIMD128 )
904                 {
905                     for( ; i <= width-4; i+=4 )
906                     {
907                         v_int32x4 v_s0 = v_load(SUM + i) + v_load(Sp + i);
908
909                         v_store(D + i, v_s0);
910                         v_store(SUM + i, v_s0 - v_load(Sm + i));
911                     }
912                 }
913 #endif
914                 for( ; i < width; i++ )
915                 {
916                     int s0 = SUM[i] + Sp[i];
917                     D[i] = s0;
918                     SUM[i] = s0 - Sm[i];
919                 }
920             }
921             dst += dststep;
922         }
923     }
924
925     double scale;
926     int sumCount;
927     std::vector<int> sum;
928 };
929
930
931 template<>
932 struct ColumnSum<int, float> :
933         public BaseColumnFilter
934 {
935     ColumnSum( int _ksize, int _anchor, double _scale ) :
936         BaseColumnFilter()
937     {
938         ksize = _ksize;
939         anchor = _anchor;
940         scale = _scale;
941         sumCount = 0;
942     }
943
944     virtual void reset() { sumCount = 0; }
945
946     virtual void operator()(const uchar** src, uchar* dst, int dststep, int count, int width)
947     {
948         int* SUM;
949         bool haveScale = scale != 1;
950         double _scale = scale;
951
952 #if CV_SIMD128
953         bool haveSIMD128 = hasSIMD128();
954 #endif
955
956         if( width != (int)sum.size() )
957         {
958             sum.resize(width);
959             sumCount = 0;
960         }
961
962         SUM = &sum[0];
963         if( sumCount == 0 )
964         {
965             memset((void*)SUM, 0, width*sizeof(int));
966             for( ; sumCount < ksize - 1; sumCount++, src++ )
967             {
968                 const int* Sp = (const int*)src[0];
969                 int i = 0;
970 #if CV_SIMD128
971                 if( haveSIMD128 )
972                 {
973                     for( ; i <= width - 4; i+=4 )
974                     {
975                         v_store(SUM + i, v_load(SUM + i) + v_load(Sp + i));
976                     }
977                 }
978 #endif
979
980                 for( ; i < width; i++ )
981                     SUM[i] += Sp[i];
982             }
983         }
984         else
985         {
986             CV_Assert( sumCount == ksize-1 );
987             src += ksize-1;
988         }
989
990         for( ; count--; src++ )
991         {
992             const int * Sp = (const int*)src[0];
993             const int * Sm = (const int*)src[1-ksize];
994             float* D = (float*)dst;
995             if( haveScale )
996             {
997                 int i = 0;
998
999 #if CV_SIMD128
1000                 if( haveSIMD128 )
1001                 {
1002                     v_float32x4 v_scale = v_setall_f32((float)_scale);
1003                     for (; i <= width - 8; i += 8)
1004                     {
1005                         v_int32x4 v_s0 = v_load(SUM + i) + v_load(Sp + i);
1006                         v_int32x4 v_s01 = v_load(SUM + i + 4) + v_load(Sp + i + 4);
1007
1008                         v_store(D + i, v_cvt_f32(v_s0) * v_scale);
1009                         v_store(D + i + 4, v_cvt_f32(v_s01) * v_scale);
1010
1011                         v_store(SUM + i, v_s0 - v_load(Sm + i));
1012                         v_store(SUM + i + 4, v_s01 - v_load(Sm + i + 4));
1013                     }
1014                 }
1015 #endif
1016                 for( ; i < width; i++ )
1017                 {
1018                     int s0 = SUM[i] + Sp[i];
1019                     D[i] = (float)(s0*_scale);
1020                     SUM[i] = s0 - Sm[i];
1021                 }
1022             }
1023             else
1024             {
1025                 int i = 0;
1026
1027 #if CV_SIMD128
1028                 if( haveSIMD128 )
1029                 {
1030                     for( ; i <= width-8; i+=8 )
1031                     {
1032                         v_int32x4 v_s0 = v_load(SUM + i) + v_load(Sp + i);
1033                         v_int32x4 v_s01 = v_load(SUM + i + 4) + v_load(Sp + i + 4);
1034
1035                         v_store(D + i, v_cvt_f32(v_s0));
1036                         v_store(D + i + 4, v_cvt_f32(v_s01));
1037
1038                         v_store(SUM + i, v_s0 - v_load(Sm + i));
1039                         v_store(SUM + i + 4, v_s01 - v_load(Sm + i + 4));
1040                     }
1041                 }
1042 #endif
1043                 for( ; i < width; i++ )
1044                 {
1045                     int s0 = SUM[i] + Sp[i];
1046                     D[i] = (float)(s0);
1047                     SUM[i] = s0 - Sm[i];
1048                 }
1049             }
1050             dst += dststep;
1051         }
1052     }
1053
1054     double scale;
1055     int sumCount;
1056     std::vector<int> sum;
1057 };
1058
1059 #ifdef HAVE_OPENCL
1060
1061 static bool ocl_boxFilter3x3_8UC1( InputArray _src, OutputArray _dst, int ddepth,
1062                                    Size ksize, Point anchor, int borderType, bool normalize )
1063 {
1064     const ocl::Device & dev = ocl::Device::getDefault();
1065     int type = _src.type(), sdepth = CV_MAT_DEPTH(type), cn = CV_MAT_CN(type);
1066
1067     if (ddepth < 0)
1068         ddepth = sdepth;
1069
1070     if (anchor.x < 0)
1071         anchor.x = ksize.width / 2;
1072     if (anchor.y < 0)
1073         anchor.y = ksize.height / 2;
1074
1075     if ( !(dev.isIntel() && (type == CV_8UC1) &&
1076          (_src.offset() == 0) && (_src.step() % 4 == 0) &&
1077          (_src.cols() % 16 == 0) && (_src.rows() % 2 == 0) &&
1078          (anchor.x == 1) && (anchor.y == 1) &&
1079          (ksize.width == 3) && (ksize.height == 3)) )
1080         return false;
1081
1082     float alpha = 1.0f / (ksize.height * ksize.width);
1083     Size size = _src.size();
1084     size_t globalsize[2] = { 0, 0 };
1085     size_t localsize[2] = { 0, 0 };
1086     const char * const borderMap[] = { "BORDER_CONSTANT", "BORDER_REPLICATE", "BORDER_REFLECT", 0, "BORDER_REFLECT_101" };
1087
1088     globalsize[0] = size.width / 16;
1089     globalsize[1] = size.height / 2;
1090
1091     char build_opts[1024];
1092     sprintf(build_opts, "-D %s %s", borderMap[borderType], normalize ? "-D NORMALIZE" : "");
1093
1094     ocl::Kernel kernel("boxFilter3x3_8UC1_cols16_rows2", cv::ocl::imgproc::boxFilter3x3_oclsrc, build_opts);
1095     if (kernel.empty())
1096         return false;
1097
1098     UMat src = _src.getUMat();
1099     _dst.create(size, CV_MAKETYPE(ddepth, cn));
1100     if (!(_dst.offset() == 0 && _dst.step() % 4 == 0))
1101         return false;
1102     UMat dst = _dst.getUMat();
1103
1104     int idxArg = kernel.set(0, ocl::KernelArg::PtrReadOnly(src));
1105     idxArg = kernel.set(idxArg, (int)src.step);
1106     idxArg = kernel.set(idxArg, ocl::KernelArg::PtrWriteOnly(dst));
1107     idxArg = kernel.set(idxArg, (int)dst.step);
1108     idxArg = kernel.set(idxArg, (int)dst.rows);
1109     idxArg = kernel.set(idxArg, (int)dst.cols);
1110     if (normalize)
1111         idxArg = kernel.set(idxArg, (float)alpha);
1112
1113     return kernel.run(2, globalsize, (localsize[0] == 0) ? NULL : localsize, false);
1114 }
1115
1116 #define DIVUP(total, grain) ((total + grain - 1) / (grain))
1117 #define ROUNDUP(sz, n)      ((sz) + (n) - 1 - (((sz) + (n) - 1) % (n)))
1118
1119 static bool ocl_boxFilter( InputArray _src, OutputArray _dst, int ddepth,
1120                            Size ksize, Point anchor, int borderType, bool normalize, bool sqr = false )
1121 {
1122     const ocl::Device & dev = ocl::Device::getDefault();
1123     int type = _src.type(), sdepth = CV_MAT_DEPTH(type), cn = CV_MAT_CN(type), esz = CV_ELEM_SIZE(type);
1124     bool doubleSupport = dev.doubleFPConfig() > 0;
1125
1126     if (ddepth < 0)
1127         ddepth = sdepth;
1128
1129     if (cn > 4 || (!doubleSupport && (sdepth == CV_64F || ddepth == CV_64F)) ||
1130         _src.offset() % esz != 0 || _src.step() % esz != 0)
1131         return false;
1132
1133     if (anchor.x < 0)
1134         anchor.x = ksize.width / 2;
1135     if (anchor.y < 0)
1136         anchor.y = ksize.height / 2;
1137
1138     int computeUnits = ocl::Device::getDefault().maxComputeUnits();
1139     float alpha = 1.0f / (ksize.height * ksize.width);
1140     Size size = _src.size(), wholeSize;
1141     bool isolated = (borderType & BORDER_ISOLATED) != 0;
1142     borderType &= ~BORDER_ISOLATED;
1143     int wdepth = std::max(CV_32F, std::max(ddepth, sdepth)),
1144         wtype = CV_MAKE_TYPE(wdepth, cn), dtype = CV_MAKE_TYPE(ddepth, cn);
1145
1146     const char * const borderMap[] = { "BORDER_CONSTANT", "BORDER_REPLICATE", "BORDER_REFLECT", 0, "BORDER_REFLECT_101" };
1147     size_t globalsize[2] = { (size_t)size.width, (size_t)size.height };
1148     size_t localsize_general[2] = { 0, 1 }, * localsize = NULL;
1149
1150     UMat src = _src.getUMat();
1151     if (!isolated)
1152     {
1153         Point ofs;
1154         src.locateROI(wholeSize, ofs);
1155     }
1156
1157     int h = isolated ? size.height : wholeSize.height;
1158     int w = isolated ? size.width : wholeSize.width;
1159
1160     size_t maxWorkItemSizes[32];
1161     ocl::Device::getDefault().maxWorkItemSizes(maxWorkItemSizes);
1162     int tryWorkItems = (int)maxWorkItemSizes[0];
1163
1164     ocl::Kernel kernel;
1165
1166     if (dev.isIntel() && !(dev.type() & ocl::Device::TYPE_CPU) &&
1167         ((ksize.width < 5 && ksize.height < 5 && esz <= 4) ||
1168          (ksize.width == 5 && ksize.height == 5 && cn == 1)))
1169     {
1170         if (w < ksize.width || h < ksize.height)
1171             return false;
1172
1173         // Figure out what vector size to use for loading the pixels.
1174         int pxLoadNumPixels = cn != 1 || size.width % 4 ? 1 : 4;
1175         int pxLoadVecSize = cn * pxLoadNumPixels;
1176
1177         // Figure out how many pixels per work item to compute in X and Y
1178         // directions.  Too many and we run out of registers.
1179         int pxPerWorkItemX = 1, pxPerWorkItemY = 1;
1180         if (cn <= 2 && ksize.width <= 4 && ksize.height <= 4)
1181         {
1182             pxPerWorkItemX = size.width % 8 ? size.width % 4 ? size.width % 2 ? 1 : 2 : 4 : 8;
1183             pxPerWorkItemY = size.height % 2 ? 1 : 2;
1184         }
1185         else if (cn < 4 || (ksize.width <= 4 && ksize.height <= 4))
1186         {
1187             pxPerWorkItemX = size.width % 2 ? 1 : 2;
1188             pxPerWorkItemY = size.height % 2 ? 1 : 2;
1189         }
1190         globalsize[0] = size.width / pxPerWorkItemX;
1191         globalsize[1] = size.height / pxPerWorkItemY;
1192
1193         // Need some padding in the private array for pixels
1194         int privDataWidth = ROUNDUP(pxPerWorkItemX + ksize.width - 1, pxLoadNumPixels);
1195
1196         // Make the global size a nice round number so the runtime can pick
1197         // from reasonable choices for the workgroup size
1198         const int wgRound = 256;
1199         globalsize[0] = ROUNDUP(globalsize[0], wgRound);
1200
1201         char build_options[1024], cvt[2][40];
1202         sprintf(build_options, "-D cn=%d "
1203                 "-D ANCHOR_X=%d -D ANCHOR_Y=%d -D KERNEL_SIZE_X=%d -D KERNEL_SIZE_Y=%d "
1204                 "-D PX_LOAD_VEC_SIZE=%d -D PX_LOAD_NUM_PX=%d "
1205                 "-D PX_PER_WI_X=%d -D PX_PER_WI_Y=%d -D PRIV_DATA_WIDTH=%d -D %s -D %s "
1206                 "-D PX_LOAD_X_ITERATIONS=%d -D PX_LOAD_Y_ITERATIONS=%d "
1207                 "-D srcT=%s -D srcT1=%s -D dstT=%s -D dstT1=%s -D WT=%s -D WT1=%s "
1208                 "-D convertToWT=%s -D convertToDstT=%s%s%s -D PX_LOAD_FLOAT_VEC_CONV=convert_%s -D OP_BOX_FILTER",
1209                 cn, anchor.x, anchor.y, ksize.width, ksize.height,
1210                 pxLoadVecSize, pxLoadNumPixels,
1211                 pxPerWorkItemX, pxPerWorkItemY, privDataWidth, borderMap[borderType],
1212                 isolated ? "BORDER_ISOLATED" : "NO_BORDER_ISOLATED",
1213                 privDataWidth / pxLoadNumPixels, pxPerWorkItemY + ksize.height - 1,
1214                 ocl::typeToStr(type), ocl::typeToStr(sdepth), ocl::typeToStr(dtype),
1215                 ocl::typeToStr(ddepth), ocl::typeToStr(wtype), ocl::typeToStr(wdepth),
1216                 ocl::convertTypeStr(sdepth, wdepth, cn, cvt[0]),
1217                 ocl::convertTypeStr(wdepth, ddepth, cn, cvt[1]),
1218                 normalize ? " -D NORMALIZE" : "", sqr ? " -D SQR" : "",
1219                 ocl::typeToStr(CV_MAKE_TYPE(wdepth, pxLoadVecSize)) //PX_LOAD_FLOAT_VEC_CONV
1220                 );
1221
1222
1223         if (!kernel.create("filterSmall", cv::ocl::imgproc::filterSmall_oclsrc, build_options))
1224             return false;
1225     }
1226     else
1227     {
1228         localsize = localsize_general;
1229         for ( ; ; )
1230         {
1231             int BLOCK_SIZE_X = tryWorkItems, BLOCK_SIZE_Y = std::min(ksize.height * 10, size.height);
1232
1233             while (BLOCK_SIZE_X > 32 && BLOCK_SIZE_X >= ksize.width * 2 && BLOCK_SIZE_X > size.width * 2)
1234                 BLOCK_SIZE_X /= 2;
1235             while (BLOCK_SIZE_Y < BLOCK_SIZE_X / 8 && BLOCK_SIZE_Y * computeUnits * 32 < size.height)
1236                 BLOCK_SIZE_Y *= 2;
1237
1238             if (ksize.width > BLOCK_SIZE_X || w < ksize.width || h < ksize.height)
1239                 return false;
1240
1241             char cvt[2][50];
1242             String opts = format("-D LOCAL_SIZE_X=%d -D BLOCK_SIZE_Y=%d -D ST=%s -D DT=%s -D WT=%s -D convertToDT=%s -D convertToWT=%s"
1243                                  " -D ANCHOR_X=%d -D ANCHOR_Y=%d -D KERNEL_SIZE_X=%d -D KERNEL_SIZE_Y=%d -D %s%s%s%s%s"
1244                                  " -D ST1=%s -D DT1=%s -D cn=%d",
1245                                  BLOCK_SIZE_X, BLOCK_SIZE_Y, ocl::typeToStr(type), ocl::typeToStr(CV_MAKE_TYPE(ddepth, cn)),
1246                                  ocl::typeToStr(CV_MAKE_TYPE(wdepth, cn)),
1247                                  ocl::convertTypeStr(wdepth, ddepth, cn, cvt[0]),
1248                                  ocl::convertTypeStr(sdepth, wdepth, cn, cvt[1]),
1249                                  anchor.x, anchor.y, ksize.width, ksize.height, borderMap[borderType],
1250                                  isolated ? " -D BORDER_ISOLATED" : "", doubleSupport ? " -D DOUBLE_SUPPORT" : "",
1251                                  normalize ? " -D NORMALIZE" : "", sqr ? " -D SQR" : "",
1252                                  ocl::typeToStr(sdepth), ocl::typeToStr(ddepth), cn);
1253
1254             localsize[0] = BLOCK_SIZE_X;
1255             globalsize[0] = DIVUP(size.width, BLOCK_SIZE_X - (ksize.width - 1)) * BLOCK_SIZE_X;
1256             globalsize[1] = DIVUP(size.height, BLOCK_SIZE_Y);
1257
1258             kernel.create("boxFilter", cv::ocl::imgproc::boxFilter_oclsrc, opts);
1259             if (kernel.empty())
1260                 return false;
1261
1262             size_t kernelWorkGroupSize = kernel.workGroupSize();
1263             if (localsize[0] <= kernelWorkGroupSize)
1264                 break;
1265             if (BLOCK_SIZE_X < (int)kernelWorkGroupSize)
1266                 return false;
1267
1268             tryWorkItems = (int)kernelWorkGroupSize;
1269         }
1270     }
1271
1272     _dst.create(size, CV_MAKETYPE(ddepth, cn));
1273     UMat dst = _dst.getUMat();
1274
1275     int idxArg = kernel.set(0, ocl::KernelArg::PtrReadOnly(src));
1276     idxArg = kernel.set(idxArg, (int)src.step);
1277     int srcOffsetX = (int)((src.offset % src.step) / src.elemSize());
1278     int srcOffsetY = (int)(src.offset / src.step);
1279     int srcEndX = isolated ? srcOffsetX + size.width : wholeSize.width;
1280     int srcEndY = isolated ? srcOffsetY + size.height : wholeSize.height;
1281     idxArg = kernel.set(idxArg, srcOffsetX);
1282     idxArg = kernel.set(idxArg, srcOffsetY);
1283     idxArg = kernel.set(idxArg, srcEndX);
1284     idxArg = kernel.set(idxArg, srcEndY);
1285     idxArg = kernel.set(idxArg, ocl::KernelArg::WriteOnly(dst));
1286     if (normalize)
1287         idxArg = kernel.set(idxArg, (float)alpha);
1288
1289     return kernel.run(2, globalsize, localsize, false);
1290 }
1291
1292 #undef ROUNDUP
1293
1294 #endif
1295
1296 }
1297
1298
1299 cv::Ptr<cv::BaseRowFilter> cv::getRowSumFilter(int srcType, int sumType, int ksize, int anchor)
1300 {
1301     int sdepth = CV_MAT_DEPTH(srcType), ddepth = CV_MAT_DEPTH(sumType);
1302     CV_Assert( CV_MAT_CN(sumType) == CV_MAT_CN(srcType) );
1303
1304     if( anchor < 0 )
1305         anchor = ksize/2;
1306
1307     if( sdepth == CV_8U && ddepth == CV_32S )
1308         return makePtr<RowSum<uchar, int> >(ksize, anchor);
1309     if( sdepth == CV_8U && ddepth == CV_16U )
1310         return makePtr<RowSum<uchar, ushort> >(ksize, anchor);
1311     if( sdepth == CV_8U && ddepth == CV_64F )
1312         return makePtr<RowSum<uchar, double> >(ksize, anchor);
1313     if( sdepth == CV_16U && ddepth == CV_32S )
1314         return makePtr<RowSum<ushort, int> >(ksize, anchor);
1315     if( sdepth == CV_16U && ddepth == CV_64F )
1316         return makePtr<RowSum<ushort, double> >(ksize, anchor);
1317     if( sdepth == CV_16S && ddepth == CV_32S )
1318         return makePtr<RowSum<short, int> >(ksize, anchor);
1319     if( sdepth == CV_32S && ddepth == CV_32S )
1320         return makePtr<RowSum<int, int> >(ksize, anchor);
1321     if( sdepth == CV_16S && ddepth == CV_64F )
1322         return makePtr<RowSum<short, double> >(ksize, anchor);
1323     if( sdepth == CV_32F && ddepth == CV_64F )
1324         return makePtr<RowSum<float, double> >(ksize, anchor);
1325     if( sdepth == CV_64F && ddepth == CV_64F )
1326         return makePtr<RowSum<double, double> >(ksize, anchor);
1327
1328     CV_Error_( CV_StsNotImplemented,
1329         ("Unsupported combination of source format (=%d), and buffer format (=%d)",
1330         srcType, sumType));
1331
1332     return Ptr<BaseRowFilter>();
1333 }
1334
1335
1336 cv::Ptr<cv::BaseColumnFilter> cv::getColumnSumFilter(int sumType, int dstType, int ksize,
1337                                                      int anchor, double scale)
1338 {
1339     int sdepth = CV_MAT_DEPTH(sumType), ddepth = CV_MAT_DEPTH(dstType);
1340     CV_Assert( CV_MAT_CN(sumType) == CV_MAT_CN(dstType) );
1341
1342     if( anchor < 0 )
1343         anchor = ksize/2;
1344
1345     if( ddepth == CV_8U && sdepth == CV_32S )
1346         return makePtr<ColumnSum<int, uchar> >(ksize, anchor, scale);
1347     if( ddepth == CV_8U && sdepth == CV_16U )
1348         return makePtr<ColumnSum<ushort, uchar> >(ksize, anchor, scale);
1349     if( ddepth == CV_8U && sdepth == CV_64F )
1350         return makePtr<ColumnSum<double, uchar> >(ksize, anchor, scale);
1351     if( ddepth == CV_16U && sdepth == CV_32S )
1352         return makePtr<ColumnSum<int, ushort> >(ksize, anchor, scale);
1353     if( ddepth == CV_16U && sdepth == CV_64F )
1354         return makePtr<ColumnSum<double, ushort> >(ksize, anchor, scale);
1355     if( ddepth == CV_16S && sdepth == CV_32S )
1356         return makePtr<ColumnSum<int, short> >(ksize, anchor, scale);
1357     if( ddepth == CV_16S && sdepth == CV_64F )
1358         return makePtr<ColumnSum<double, short> >(ksize, anchor, scale);
1359     if( ddepth == CV_32S && sdepth == CV_32S )
1360         return makePtr<ColumnSum<int, int> >(ksize, anchor, scale);
1361     if( ddepth == CV_32F && sdepth == CV_32S )
1362         return makePtr<ColumnSum<int, float> >(ksize, anchor, scale);
1363     if( ddepth == CV_32F && sdepth == CV_64F )
1364         return makePtr<ColumnSum<double, float> >(ksize, anchor, scale);
1365     if( ddepth == CV_64F && sdepth == CV_32S )
1366         return makePtr<ColumnSum<int, double> >(ksize, anchor, scale);
1367     if( ddepth == CV_64F && sdepth == CV_64F )
1368         return makePtr<ColumnSum<double, double> >(ksize, anchor, scale);
1369
1370     CV_Error_( CV_StsNotImplemented,
1371         ("Unsupported combination of sum format (=%d), and destination format (=%d)",
1372         sumType, dstType));
1373
1374     return Ptr<BaseColumnFilter>();
1375 }
1376
1377
1378 cv::Ptr<cv::FilterEngine> cv::createBoxFilter( int srcType, int dstType, Size ksize,
1379                     Point anchor, bool normalize, int borderType )
1380 {
1381     int sdepth = CV_MAT_DEPTH(srcType);
1382     int cn = CV_MAT_CN(srcType), sumType = CV_64F;
1383     if( sdepth == CV_8U && CV_MAT_DEPTH(dstType) == CV_8U &&
1384         ksize.width*ksize.height <= 256 )
1385         sumType = CV_16U;
1386     else if( sdepth <= CV_32S && (!normalize ||
1387         ksize.width*ksize.height <= (sdepth == CV_8U ? (1<<23) :
1388             sdepth == CV_16U ? (1 << 15) : (1 << 16))) )
1389         sumType = CV_32S;
1390     sumType = CV_MAKETYPE( sumType, cn );
1391
1392     Ptr<BaseRowFilter> rowFilter = getRowSumFilter(srcType, sumType, ksize.width, anchor.x );
1393     Ptr<BaseColumnFilter> columnFilter = getColumnSumFilter(sumType,
1394         dstType, ksize.height, anchor.y, normalize ? 1./(ksize.width*ksize.height) : 1);
1395
1396     return makePtr<FilterEngine>(Ptr<BaseFilter>(), rowFilter, columnFilter,
1397            srcType, dstType, sumType, borderType );
1398 }
1399
1400 #ifdef HAVE_OPENVX
1401 namespace cv
1402 {
1403     namespace ovx {
1404         template <> inline bool skipSmallImages<VX_KERNEL_BOX_3x3>(int w, int h) { return w*h < 640 * 480; }
1405     }
1406     static bool openvx_boxfilter(InputArray _src, OutputArray _dst, int ddepth,
1407                                  Size ksize, Point anchor,
1408                                  bool normalize, int borderType)
1409     {
1410         if (ddepth < 0)
1411             ddepth = CV_8UC1;
1412         if (_src.type() != CV_8UC1 || ddepth != CV_8U || !normalize ||
1413             _src.cols() < 3 || _src.rows() < 3 ||
1414             ksize.width != 3 || ksize.height != 3 ||
1415             (anchor.x >= 0 && anchor.x != 1) ||
1416             (anchor.y >= 0 && anchor.y != 1) ||
1417             ovx::skipSmallImages<VX_KERNEL_BOX_3x3>(_src.cols(), _src.rows()))
1418             return false;
1419
1420         Mat src = _src.getMat();
1421
1422         if ((borderType & BORDER_ISOLATED) == 0 && src.isSubmatrix())
1423             return false; //Process isolated borders only
1424         vx_enum border;
1425         switch (borderType & ~BORDER_ISOLATED)
1426         {
1427         case BORDER_CONSTANT:
1428             border = VX_BORDER_CONSTANT;
1429             break;
1430         case BORDER_REPLICATE:
1431             border = VX_BORDER_REPLICATE;
1432             break;
1433         default:
1434             return false;
1435         }
1436
1437         _dst.create(src.size(), CV_8UC1);
1438         Mat dst = _dst.getMat();
1439
1440         try
1441         {
1442             ivx::Context ctx = ovx::getOpenVXContext();
1443
1444             Mat a;
1445             if (dst.data != src.data)
1446                 a = src;
1447             else
1448                 src.copyTo(a);
1449
1450             ivx::Image
1451                 ia = ivx::Image::createFromHandle(ctx, VX_DF_IMAGE_U8,
1452                                                   ivx::Image::createAddressing(a.cols, a.rows, 1, (vx_int32)(a.step)), a.data),
1453                 ib = ivx::Image::createFromHandle(ctx, VX_DF_IMAGE_U8,
1454                                                   ivx::Image::createAddressing(dst.cols, dst.rows, 1, (vx_int32)(dst.step)), dst.data);
1455
1456             //ATTENTION: VX_CONTEXT_IMMEDIATE_BORDER attribute change could lead to strange issues in multi-threaded environments
1457             //since OpenVX standart says nothing about thread-safety for now
1458             ivx::border_t prevBorder = ctx.immediateBorder();
1459             ctx.setImmediateBorder(border, (vx_uint8)(0));
1460             ivx::IVX_CHECK_STATUS(vxuBox3x3(ctx, ia, ib));
1461             ctx.setImmediateBorder(prevBorder);
1462         }
1463         catch (ivx::RuntimeError & e)
1464         {
1465             VX_DbgThrow(e.what());
1466         }
1467         catch (ivx::WrapperError & e)
1468         {
1469             VX_DbgThrow(e.what());
1470         }
1471
1472         return true;
1473     }
1474 }
1475 #endif
1476
1477 #if defined(HAVE_IPP)
1478 namespace cv
1479 {
1480 static bool ipp_boxfilter(Mat &src, Mat &dst, Size ksize, Point anchor, bool normalize, int borderType)
1481 {
1482 #ifdef HAVE_IPP_IW
1483     CV_INSTRUMENT_REGION_IPP()
1484
1485 #if IPP_VERSION_X100 < 201801
1486     // Problem with SSE42 optimization for 16s and some 8u modes
1487     if(ipp::getIppTopFeatures() == ippCPUID_SSE42 && (((src.depth() == CV_16S || src.depth() == CV_16U) && (src.channels() == 3 || src.channels() == 4)) || (src.depth() == CV_8U && src.channels() == 3 && (ksize.width > 5 || ksize.height > 5))))
1488         return false;
1489
1490     // Other optimizations has some degradations too
1491     if((((src.depth() == CV_16S || src.depth() == CV_16U) && (src.channels() == 4)) || (src.depth() == CV_8U && src.channels() == 1 && (ksize.width > 5 || ksize.height > 5))))
1492         return false;
1493 #endif
1494
1495     if(!normalize)
1496         return false;
1497
1498     if(!ippiCheckAnchor(anchor, ksize))
1499         return false;
1500
1501     try
1502     {
1503         ::ipp::IwiImage       iwSrc      = ippiGetImage(src);
1504         ::ipp::IwiImage       iwDst      = ippiGetImage(dst);
1505         ::ipp::IwiSize        iwKSize    = ippiGetSize(ksize);
1506         ::ipp::IwiBorderSize  borderSize(iwKSize);
1507         ::ipp::IwiBorderType  ippBorder(ippiGetBorder(iwSrc, borderType, borderSize));
1508         if(!ippBorder)
1509             return false;
1510
1511         CV_INSTRUMENT_FUN_IPP(::ipp::iwiFilterBox, iwSrc, iwDst, iwKSize, ::ipp::IwDefault(), ippBorder);
1512     }
1513     catch (::ipp::IwException)
1514     {
1515         return false;
1516     }
1517
1518     return true;
1519 #else
1520     CV_UNUSED(src); CV_UNUSED(dst); CV_UNUSED(ksize); CV_UNUSED(anchor); CV_UNUSED(normalize); CV_UNUSED(borderType);
1521     return false;
1522 #endif
1523 }
1524 }
1525 #endif
1526
1527
1528 void cv::boxFilter( InputArray _src, OutputArray _dst, int ddepth,
1529                 Size ksize, Point anchor,
1530                 bool normalize, int borderType )
1531 {
1532     CV_INSTRUMENT_REGION()
1533
1534     CV_OCL_RUN(_dst.isUMat() &&
1535                (borderType == BORDER_REPLICATE || borderType == BORDER_CONSTANT ||
1536                 borderType == BORDER_REFLECT || borderType == BORDER_REFLECT_101),
1537                ocl_boxFilter3x3_8UC1(_src, _dst, ddepth, ksize, anchor, borderType, normalize))
1538
1539     CV_OCL_RUN(_dst.isUMat(), ocl_boxFilter(_src, _dst, ddepth, ksize, anchor, borderType, normalize))
1540
1541     Mat src = _src.getMat();
1542     int stype = src.type(), sdepth = CV_MAT_DEPTH(stype), cn = CV_MAT_CN(stype);
1543     if( ddepth < 0 )
1544         ddepth = sdepth;
1545     _dst.create( src.size(), CV_MAKETYPE(ddepth, cn) );
1546     Mat dst = _dst.getMat();
1547     if( borderType != BORDER_CONSTANT && normalize && (borderType & BORDER_ISOLATED) != 0 )
1548     {
1549         if( src.rows == 1 )
1550             ksize.height = 1;
1551         if( src.cols == 1 )
1552             ksize.width = 1;
1553     }
1554
1555     Point ofs;
1556     Size wsz(src.cols, src.rows);
1557     if(!(borderType&BORDER_ISOLATED))
1558         src.locateROI( wsz, ofs );
1559
1560     CALL_HAL(boxFilter, cv_hal_boxFilter, src.ptr(), src.step, dst.ptr(), dst.step, src.cols, src.rows, sdepth, ddepth, cn,
1561              ofs.x, ofs.y, wsz.width - src.cols - ofs.x, wsz.height - src.rows - ofs.y, ksize.width, ksize.height,
1562              anchor.x, anchor.y, normalize, borderType&~BORDER_ISOLATED);
1563
1564     CV_OVX_RUN(true,
1565                openvx_boxfilter(src, dst, ddepth, ksize, anchor, normalize, borderType))
1566
1567     CV_IPP_RUN_FAST(ipp_boxfilter(src, dst, ksize, anchor, normalize, borderType));
1568
1569     borderType = (borderType&~BORDER_ISOLATED);
1570
1571     Ptr<FilterEngine> f = createBoxFilter( src.type(), dst.type(),
1572                         ksize, anchor, normalize, borderType );
1573
1574     f->apply( src, dst, wsz, ofs );
1575 }
1576
1577
1578 void cv::blur( InputArray src, OutputArray dst,
1579            Size ksize, Point anchor, int borderType )
1580 {
1581     CV_INSTRUMENT_REGION()
1582
1583     boxFilter( src, dst, -1, ksize, anchor, true, borderType );
1584 }
1585
1586
1587 /****************************************************************************************\
1588                                     Squared Box Filter
1589 \****************************************************************************************/
1590
1591 namespace cv
1592 {
1593
1594 template<typename T, typename ST>
1595 struct SqrRowSum :
1596         public BaseRowFilter
1597 {
1598     SqrRowSum( int _ksize, int _anchor ) :
1599         BaseRowFilter()
1600     {
1601         ksize = _ksize;
1602         anchor = _anchor;
1603     }
1604
1605     virtual void operator()(const uchar* src, uchar* dst, int width, int cn)
1606     {
1607         const T* S = (const T*)src;
1608         ST* D = (ST*)dst;
1609         int i = 0, k, ksz_cn = ksize*cn;
1610
1611         width = (width - 1)*cn;
1612         for( k = 0; k < cn; k++, S++, D++ )
1613         {
1614             ST s = 0;
1615             for( i = 0; i < ksz_cn; i += cn )
1616             {
1617                 ST val = (ST)S[i];
1618                 s += val*val;
1619             }
1620             D[0] = s;
1621             for( i = 0; i < width; i += cn )
1622             {
1623                 ST val0 = (ST)S[i], val1 = (ST)S[i + ksz_cn];
1624                 s += val1*val1 - val0*val0;
1625                 D[i+cn] = s;
1626             }
1627         }
1628     }
1629 };
1630
1631 static Ptr<BaseRowFilter> getSqrRowSumFilter(int srcType, int sumType, int ksize, int anchor)
1632 {
1633     int sdepth = CV_MAT_DEPTH(srcType), ddepth = CV_MAT_DEPTH(sumType);
1634     CV_Assert( CV_MAT_CN(sumType) == CV_MAT_CN(srcType) );
1635
1636     if( anchor < 0 )
1637         anchor = ksize/2;
1638
1639     if( sdepth == CV_8U && ddepth == CV_32S )
1640         return makePtr<SqrRowSum<uchar, int> >(ksize, anchor);
1641     if( sdepth == CV_8U && ddepth == CV_64F )
1642         return makePtr<SqrRowSum<uchar, double> >(ksize, anchor);
1643     if( sdepth == CV_16U && ddepth == CV_64F )
1644         return makePtr<SqrRowSum<ushort, double> >(ksize, anchor);
1645     if( sdepth == CV_16S && ddepth == CV_64F )
1646         return makePtr<SqrRowSum<short, double> >(ksize, anchor);
1647     if( sdepth == CV_32F && ddepth == CV_64F )
1648         return makePtr<SqrRowSum<float, double> >(ksize, anchor);
1649     if( sdepth == CV_64F && ddepth == CV_64F )
1650         return makePtr<SqrRowSum<double, double> >(ksize, anchor);
1651
1652     CV_Error_( CV_StsNotImplemented,
1653               ("Unsupported combination of source format (=%d), and buffer format (=%d)",
1654                srcType, sumType));
1655
1656     return Ptr<BaseRowFilter>();
1657 }
1658
1659 }
1660
1661 void cv::sqrBoxFilter( InputArray _src, OutputArray _dst, int ddepth,
1662                        Size ksize, Point anchor,
1663                        bool normalize, int borderType )
1664 {
1665     CV_INSTRUMENT_REGION()
1666
1667     int srcType = _src.type(), sdepth = CV_MAT_DEPTH(srcType), cn = CV_MAT_CN(srcType);
1668     Size size = _src.size();
1669
1670     if( ddepth < 0 )
1671         ddepth = sdepth < CV_32F ? CV_32F : CV_64F;
1672
1673     if( borderType != BORDER_CONSTANT && normalize )
1674     {
1675         if( size.height == 1 )
1676             ksize.height = 1;
1677         if( size.width == 1 )
1678             ksize.width = 1;
1679     }
1680
1681     CV_OCL_RUN(_dst.isUMat() && _src.dims() <= 2,
1682                ocl_boxFilter(_src, _dst, ddepth, ksize, anchor, borderType, normalize, true))
1683
1684     int sumDepth = CV_64F;
1685     if( sdepth == CV_8U )
1686         sumDepth = CV_32S;
1687     int sumType = CV_MAKETYPE( sumDepth, cn ), dstType = CV_MAKETYPE(ddepth, cn);
1688
1689     Mat src = _src.getMat();
1690     _dst.create( size, dstType );
1691     Mat dst = _dst.getMat();
1692
1693     Ptr<BaseRowFilter> rowFilter = getSqrRowSumFilter(srcType, sumType, ksize.width, anchor.x );
1694     Ptr<BaseColumnFilter> columnFilter = getColumnSumFilter(sumType,
1695                                                             dstType, ksize.height, anchor.y,
1696                                                             normalize ? 1./(ksize.width*ksize.height) : 1);
1697
1698     Ptr<FilterEngine> f = makePtr<FilterEngine>(Ptr<BaseFilter>(), rowFilter, columnFilter,
1699                                                 srcType, dstType, sumType, borderType );
1700     Point ofs;
1701     Size wsz(src.cols, src.rows);
1702     src.locateROI( wsz, ofs );
1703
1704     f->apply( src, dst, wsz, ofs );
1705 }
1706
1707
1708 /****************************************************************************************\
1709                                      Gaussian Blur
1710 \****************************************************************************************/
1711
1712 cv::Mat cv::getGaussianKernel( int n, double sigma, int ktype )
1713 {
1714     const int SMALL_GAUSSIAN_SIZE = 7;
1715     static const float small_gaussian_tab[][SMALL_GAUSSIAN_SIZE] =
1716     {
1717         {1.f},
1718         {0.25f, 0.5f, 0.25f},
1719         {0.0625f, 0.25f, 0.375f, 0.25f, 0.0625f},
1720         {0.03125f, 0.109375f, 0.21875f, 0.28125f, 0.21875f, 0.109375f, 0.03125f}
1721     };
1722
1723     const float* fixed_kernel = n % 2 == 1 && n <= SMALL_GAUSSIAN_SIZE && sigma <= 0 ?
1724         small_gaussian_tab[n>>1] : 0;
1725
1726     CV_Assert( ktype == CV_32F || ktype == CV_64F );
1727     Mat kernel(n, 1, ktype);
1728     float* cf = kernel.ptr<float>();
1729     double* cd = kernel.ptr<double>();
1730
1731     double sigmaX = sigma > 0 ? sigma : ((n-1)*0.5 - 1)*0.3 + 0.8;
1732     double scale2X = -0.5/(sigmaX*sigmaX);
1733     double sum = 0;
1734
1735     int i;
1736     for( i = 0; i < n; i++ )
1737     {
1738         double x = i - (n-1)*0.5;
1739         double t = fixed_kernel ? (double)fixed_kernel[i] : std::exp(scale2X*x*x);
1740         if( ktype == CV_32F )
1741         {
1742             cf[i] = (float)t;
1743             sum += cf[i];
1744         }
1745         else
1746         {
1747             cd[i] = t;
1748             sum += cd[i];
1749         }
1750     }
1751
1752     sum = 1./sum;
1753     for( i = 0; i < n; i++ )
1754     {
1755         if( ktype == CV_32F )
1756             cf[i] = (float)(cf[i]*sum);
1757         else
1758             cd[i] *= sum;
1759     }
1760
1761     return kernel;
1762 }
1763
1764 namespace cv {
1765
1766 static void createGaussianKernels( Mat & kx, Mat & ky, int type, Size & ksize,
1767                                    double sigma1, double sigma2 )
1768 {
1769     int depth = CV_MAT_DEPTH(type);
1770     if( sigma2 <= 0 )
1771         sigma2 = sigma1;
1772
1773     // automatic detection of kernel size from sigma
1774     if( ksize.width <= 0 && sigma1 > 0 )
1775         ksize.width = cvRound(sigma1*(depth == CV_8U ? 3 : 4)*2 + 1)|1;
1776     if( ksize.height <= 0 && sigma2 > 0 )
1777         ksize.height = cvRound(sigma2*(depth == CV_8U ? 3 : 4)*2 + 1)|1;
1778
1779     CV_Assert( ksize.width > 0 && ksize.width % 2 == 1 &&
1780         ksize.height > 0 && ksize.height % 2 == 1 );
1781
1782     sigma1 = std::max( sigma1, 0. );
1783     sigma2 = std::max( sigma2, 0. );
1784
1785     kx = getGaussianKernel( ksize.width, sigma1, std::max(depth, CV_32F) );
1786     if( ksize.height == ksize.width && std::abs(sigma1 - sigma2) < DBL_EPSILON )
1787         ky = kx;
1788     else
1789         ky = getGaussianKernel( ksize.height, sigma2, std::max(depth, CV_32F) );
1790 }
1791
1792 }
1793
1794 cv::Ptr<cv::FilterEngine> cv::createGaussianFilter( int type, Size ksize,
1795                                         double sigma1, double sigma2,
1796                                         int borderType )
1797 {
1798     Mat kx, ky;
1799     createGaussianKernels(kx, ky, type, ksize, sigma1, sigma2);
1800
1801     return createSeparableLinearFilter( type, type, kx, ky, Point(-1,-1), 0, borderType );
1802 }
1803
1804 namespace cv
1805 {
1806 #ifdef HAVE_OPENCL
1807
1808 static bool ocl_GaussianBlur_8UC1(InputArray _src, OutputArray _dst, Size ksize, int ddepth,
1809                                   InputArray _kernelX, InputArray _kernelY, int borderType)
1810 {
1811     const ocl::Device & dev = ocl::Device::getDefault();
1812     int type = _src.type(), sdepth = CV_MAT_DEPTH(type), cn = CV_MAT_CN(type);
1813
1814     if ( !(dev.isIntel() && (type == CV_8UC1) &&
1815          (_src.offset() == 0) && (_src.step() % 4 == 0) &&
1816          ((ksize.width == 5 && (_src.cols() % 4 == 0)) ||
1817          (ksize.width == 3 && (_src.cols() % 16 == 0) && (_src.rows() % 2 == 0)))) )
1818         return false;
1819
1820     Mat kernelX = _kernelX.getMat().reshape(1, 1);
1821     if (kernelX.cols % 2 != 1)
1822         return false;
1823     Mat kernelY = _kernelY.getMat().reshape(1, 1);
1824     if (kernelY.cols % 2 != 1)
1825         return false;
1826
1827     if (ddepth < 0)
1828         ddepth = sdepth;
1829
1830     Size size = _src.size();
1831     size_t globalsize[2] = { 0, 0 };
1832     size_t localsize[2] = { 0, 0 };
1833
1834     if (ksize.width == 3)
1835     {
1836         globalsize[0] = size.width / 16;
1837         globalsize[1] = size.height / 2;
1838     }
1839     else if (ksize.width == 5)
1840     {
1841         globalsize[0] = size.width / 4;
1842         globalsize[1] = size.height / 1;
1843     }
1844
1845     const char * const borderMap[] = { "BORDER_CONSTANT", "BORDER_REPLICATE", "BORDER_REFLECT", 0, "BORDER_REFLECT_101" };
1846     char build_opts[1024];
1847     sprintf(build_opts, "-D %s %s%s", borderMap[borderType & ~BORDER_ISOLATED],
1848             ocl::kernelToStr(kernelX, CV_32F, "KERNEL_MATRIX_X").c_str(),
1849             ocl::kernelToStr(kernelY, CV_32F, "KERNEL_MATRIX_Y").c_str());
1850
1851     ocl::Kernel kernel;
1852
1853     if (ksize.width == 3)
1854         kernel.create("gaussianBlur3x3_8UC1_cols16_rows2", cv::ocl::imgproc::gaussianBlur3x3_oclsrc, build_opts);
1855     else if (ksize.width == 5)
1856         kernel.create("gaussianBlur5x5_8UC1_cols4", cv::ocl::imgproc::gaussianBlur5x5_oclsrc, build_opts);
1857
1858     if (kernel.empty())
1859         return false;
1860
1861     UMat src = _src.getUMat();
1862     _dst.create(size, CV_MAKETYPE(ddepth, cn));
1863     if (!(_dst.offset() == 0 && _dst.step() % 4 == 0))
1864         return false;
1865     UMat dst = _dst.getUMat();
1866
1867     int idxArg = kernel.set(0, ocl::KernelArg::PtrReadOnly(src));
1868     idxArg = kernel.set(idxArg, (int)src.step);
1869     idxArg = kernel.set(idxArg, ocl::KernelArg::PtrWriteOnly(dst));
1870     idxArg = kernel.set(idxArg, (int)dst.step);
1871     idxArg = kernel.set(idxArg, (int)dst.rows);
1872     idxArg = kernel.set(idxArg, (int)dst.cols);
1873
1874     return kernel.run(2, globalsize, (localsize[0] == 0) ? NULL : localsize, false);
1875 }
1876
1877 #endif
1878
1879 #ifdef HAVE_OPENVX
1880
1881 namespace ovx {
1882     template <> inline bool skipSmallImages<VX_KERNEL_GAUSSIAN_3x3>(int w, int h) { return w*h < 320 * 240; }
1883 }
1884 static bool openvx_gaussianBlur(InputArray _src, OutputArray _dst, Size ksize,
1885                                 double sigma1, double sigma2, int borderType)
1886 {
1887     if (sigma2 <= 0)
1888         sigma2 = sigma1;
1889     // automatic detection of kernel size from sigma
1890     if (ksize.width <= 0 && sigma1 > 0)
1891         ksize.width = cvRound(sigma1*6 + 1) | 1;
1892     if (ksize.height <= 0 && sigma2 > 0)
1893         ksize.height = cvRound(sigma2*6 + 1) | 1;
1894
1895     if (_src.type() != CV_8UC1 ||
1896         _src.cols() < 3 || _src.rows() < 3 ||
1897         ksize.width != 3 || ksize.height != 3)
1898         return false;
1899
1900     sigma1 = std::max(sigma1, 0.);
1901     sigma2 = std::max(sigma2, 0.);
1902
1903     if (!(sigma1 == 0.0 || (sigma1 - 0.8) < DBL_EPSILON) || !(sigma2 == 0.0 || (sigma2 - 0.8) < DBL_EPSILON) ||
1904         ovx::skipSmallImages<VX_KERNEL_GAUSSIAN_3x3>(_src.cols(), _src.rows()))
1905         return false;
1906
1907     Mat src = _src.getMat();
1908     Mat dst = _dst.getMat();
1909
1910     if ((borderType & BORDER_ISOLATED) == 0 && src.isSubmatrix())
1911         return false; //Process isolated borders only
1912     vx_enum border;
1913     switch (borderType & ~BORDER_ISOLATED)
1914     {
1915     case BORDER_CONSTANT:
1916         border = VX_BORDER_CONSTANT;
1917         break;
1918     case BORDER_REPLICATE:
1919         border = VX_BORDER_REPLICATE;
1920         break;
1921     default:
1922         return false;
1923     }
1924
1925     try
1926     {
1927         ivx::Context ctx = ovx::getOpenVXContext();
1928
1929         Mat a;
1930         if (dst.data != src.data)
1931             a = src;
1932         else
1933             src.copyTo(a);
1934
1935         ivx::Image
1936             ia = ivx::Image::createFromHandle(ctx, VX_DF_IMAGE_U8,
1937                 ivx::Image::createAddressing(a.cols, a.rows, 1, (vx_int32)(a.step)), a.data),
1938             ib = ivx::Image::createFromHandle(ctx, VX_DF_IMAGE_U8,
1939                 ivx::Image::createAddressing(dst.cols, dst.rows, 1, (vx_int32)(dst.step)), dst.data);
1940
1941         //ATTENTION: VX_CONTEXT_IMMEDIATE_BORDER attribute change could lead to strange issues in multi-threaded environments
1942         //since OpenVX standart says nothing about thread-safety for now
1943         ivx::border_t prevBorder = ctx.immediateBorder();
1944         ctx.setImmediateBorder(border, (vx_uint8)(0));
1945         ivx::IVX_CHECK_STATUS(vxuGaussian3x3(ctx, ia, ib));
1946         ctx.setImmediateBorder(prevBorder);
1947     }
1948     catch (ivx::RuntimeError & e)
1949     {
1950         VX_DbgThrow(e.what());
1951     }
1952     catch (ivx::WrapperError & e)
1953     {
1954         VX_DbgThrow(e.what());
1955     }
1956     return true;
1957 }
1958
1959 #endif
1960
1961 #ifdef HAVE_IPP
1962 #if IPP_VERSION_X100 == 201702  // IW 2017u2 has bug which doesn't allow use of partial inMem with tiling
1963 #define IPP_GAUSSIANBLUR_PARALLEL 0
1964 #else
1965 #define IPP_GAUSSIANBLUR_PARALLEL 1
1966 #endif
1967
1968 #ifdef HAVE_IPP_IW
1969
1970 class ipp_gaussianBlurParallel: public ParallelLoopBody
1971 {
1972 public:
1973     ipp_gaussianBlurParallel(::ipp::IwiImage &src, ::ipp::IwiImage &dst, int kernelSize, float sigma, ::ipp::IwiBorderType &border, bool *pOk):
1974         m_src(src), m_dst(dst), m_kernelSize(kernelSize), m_sigma(sigma), m_border(border), m_pOk(pOk) {
1975         *m_pOk = true;
1976     }
1977     ~ipp_gaussianBlurParallel()
1978     {
1979     }
1980
1981     virtual void operator() (const Range& range) const
1982     {
1983         CV_INSTRUMENT_REGION_IPP()
1984
1985         if(!*m_pOk)
1986             return;
1987
1988         try
1989         {
1990             ::ipp::IwiTile tile = ::ipp::IwiRoi(0, range.start, m_dst.m_size.width, range.end - range.start);
1991             CV_INSTRUMENT_FUN_IPP(::ipp::iwiFilterGaussian, m_src, m_dst, m_kernelSize, m_sigma, ::ipp::IwDefault(), m_border, tile);
1992         }
1993         catch(::ipp::IwException e)
1994         {
1995             *m_pOk = false;
1996             return;
1997         }
1998     }
1999 private:
2000     ::ipp::IwiImage &m_src;
2001     ::ipp::IwiImage &m_dst;
2002
2003     int m_kernelSize;
2004     float m_sigma;
2005     ::ipp::IwiBorderType &m_border;
2006
2007     volatile bool *m_pOk;
2008     const ipp_gaussianBlurParallel& operator= (const ipp_gaussianBlurParallel&);
2009 };
2010
2011 #endif
2012
2013 static bool ipp_GaussianBlur(InputArray _src, OutputArray _dst, Size ksize,
2014                    double sigma1, double sigma2, int borderType )
2015 {
2016 #ifdef HAVE_IPP_IW
2017     CV_INSTRUMENT_REGION_IPP()
2018
2019 #if IPP_VERSION_X100 < 201800 && ((defined _MSC_VER && defined _M_IX86) || (defined __GNUC__ && defined __i386__))
2020     CV_UNUSED(_src); CV_UNUSED(_dst); CV_UNUSED(ksize); CV_UNUSED(sigma1); CV_UNUSED(sigma2); CV_UNUSED(borderType);
2021     return false; // bug on ia32
2022 #else
2023     if(sigma1 != sigma2)
2024         return false;
2025
2026     if(sigma1 < FLT_EPSILON)
2027         return false;
2028
2029     if(ksize.width != ksize.height)
2030         return false;
2031
2032     // Acquire data and begin processing
2033     try
2034     {
2035         Mat src = _src.getMat();
2036         Mat dst = _dst.getMat();
2037         ::ipp::IwiImage       iwSrc      = ippiGetImage(src);
2038         ::ipp::IwiImage       iwDst      = ippiGetImage(dst);
2039         ::ipp::IwiBorderSize  borderSize = ::ipp::iwiSizeToBorderSize(ippiGetSize(ksize));
2040         ::ipp::IwiBorderType  ippBorder(ippiGetBorder(iwSrc, borderType, borderSize));
2041         if(!ippBorder)
2042             return false;
2043
2044         const int threads = ippiSuggestThreadsNum(iwDst, 2);
2045         if(IPP_GAUSSIANBLUR_PARALLEL && threads > 1) {
2046             bool ok;
2047             ipp_gaussianBlurParallel invoker(iwSrc, iwDst, ksize.width, (float) sigma1, ippBorder, &ok);
2048
2049             if(!ok)
2050                 return false;
2051             const Range range(0, (int) iwDst.m_size.height);
2052             parallel_for_(range, invoker, threads*4);
2053
2054             if(!ok)
2055                 return false;
2056         } else {
2057             CV_INSTRUMENT_FUN_IPP(::ipp::iwiFilterGaussian, iwSrc, iwDst, ksize.width, sigma1, ::ipp::IwDefault(), ippBorder);
2058         }
2059     }
2060     catch (::ipp::IwException ex)
2061     {
2062         return false;
2063     }
2064
2065     return true;
2066 #endif
2067 #else
2068     CV_UNUSED(_src); CV_UNUSED(_dst); CV_UNUSED(ksize); CV_UNUSED(sigma1); CV_UNUSED(sigma2); CV_UNUSED(borderType);
2069     return false;
2070 #endif
2071 }
2072 #endif
2073 }
2074
2075 void cv::GaussianBlur( InputArray _src, OutputArray _dst, Size ksize,
2076                    double sigma1, double sigma2,
2077                    int borderType )
2078 {
2079     CV_INSTRUMENT_REGION()
2080
2081     int type = _src.type();
2082     Size size = _src.size();
2083     _dst.create( size, type );
2084
2085     if( borderType != BORDER_CONSTANT && (borderType & BORDER_ISOLATED) != 0 )
2086     {
2087         if( size.height == 1 )
2088             ksize.height = 1;
2089         if( size.width == 1 )
2090             ksize.width = 1;
2091     }
2092
2093     if( ksize.width == 1 && ksize.height == 1 )
2094     {
2095         _src.copyTo(_dst);
2096         return;
2097     }
2098
2099     bool useOpenCL = (ocl::isOpenCLActivated() && _dst.isUMat() && _src.dims() <= 2 &&
2100                ((ksize.width == 3 && ksize.height == 3) ||
2101                (ksize.width == 5 && ksize.height == 5)) &&
2102                _src.rows() > ksize.height && _src.cols() > ksize.width);
2103     (void)useOpenCL;
2104
2105     int sdepth = CV_MAT_DEPTH(type), cn = CV_MAT_CN(type);
2106
2107     Mat kx, ky;
2108     createGaussianKernels(kx, ky, type, ksize, sigma1, sigma2);
2109
2110     CV_OCL_RUN(useOpenCL, ocl_GaussianBlur_8UC1(_src, _dst, ksize, CV_MAT_DEPTH(type), kx, ky, borderType));
2111
2112     CV_OCL_RUN(_dst.isUMat() && _src.dims() <= 2 && (size_t)_src.rows() > kx.total() && (size_t)_src.cols() > kx.total(),
2113                ocl_sepFilter2D(_src, _dst, sdepth, kx, ky, Point(-1, -1), 0, borderType))
2114
2115     Mat src = _src.getMat();
2116     Mat dst = _dst.getMat();
2117
2118     Point ofs;
2119     Size wsz(src.cols, src.rows);
2120     if(!(borderType & BORDER_ISOLATED))
2121         src.locateROI( wsz, ofs );
2122
2123     CALL_HAL(gaussianBlur, cv_hal_gaussianBlur, src.ptr(), src.step, dst.ptr(), dst.step, src.cols, src.rows, sdepth, cn,
2124              ofs.x, ofs.y, wsz.width - src.cols - ofs.x, wsz.height - src.rows - ofs.y, ksize.width, ksize.height,
2125              sigma1, sigma2, borderType&~BORDER_ISOLATED);
2126
2127     CV_OVX_RUN(true,
2128                openvx_gaussianBlur(src, dst, ksize, sigma1, sigma2, borderType))
2129
2130     CV_IPP_RUN_FAST(ipp_GaussianBlur(src, dst, ksize, sigma1, sigma2, borderType));
2131
2132     sepFilter2D(src, dst, sdepth, kx, ky, Point(-1, -1), 0, borderType);
2133 }
2134
2135 /****************************************************************************************\
2136                                       Median Filter
2137 \****************************************************************************************/
2138
2139 namespace cv
2140 {
2141 typedef ushort HT;
2142
2143 /**
2144  * This structure represents a two-tier histogram. The first tier (known as the
2145  * "coarse" level) is 4 bit wide and the second tier (known as the "fine" level)
2146  * is 8 bit wide. Pixels inserted in the fine level also get inserted into the
2147  * coarse bucket designated by the 4 MSBs of the fine bucket value.
2148  *
2149  * The structure is aligned on 16 bits, which is a prerequisite for SIMD
2150  * instructions. Each bucket is 16 bit wide, which means that extra care must be
2151  * taken to prevent overflow.
2152  */
2153 typedef struct
2154 {
2155     HT coarse[16];
2156     HT fine[16][16];
2157 } Histogram;
2158
2159
2160 #if CV_SIMD128
2161
2162 static inline void histogram_add_simd( const HT x[16], HT y[16] )
2163 {
2164     v_store(y, v_load(x) + v_load(y));
2165     v_store(y + 8, v_load(x + 8) + v_load(y + 8));
2166 }
2167
2168 static inline void histogram_sub_simd( const HT x[16], HT y[16] )
2169 {
2170     v_store(y, v_load(y) - v_load(x));
2171     v_store(y + 8, v_load(y + 8) - v_load(x + 8));
2172 }
2173
2174 #endif
2175
2176
2177 static inline void histogram_add( const HT x[16], HT y[16] )
2178 {
2179     int i;
2180     for( i = 0; i < 16; ++i )
2181         y[i] = (HT)(y[i] + x[i]);
2182 }
2183
2184 static inline void histogram_sub( const HT x[16], HT y[16] )
2185 {
2186     int i;
2187     for( i = 0; i < 16; ++i )
2188         y[i] = (HT)(y[i] - x[i]);
2189 }
2190
2191 static inline void histogram_muladd( int a, const HT x[16],
2192         HT y[16] )
2193 {
2194     for( int i = 0; i < 16; ++i )
2195         y[i] = (HT)(y[i] + a * x[i]);
2196 }
2197
2198 static void
2199 medianBlur_8u_O1( const Mat& _src, Mat& _dst, int ksize )
2200 {
2201 /**
2202  * HOP is short for Histogram OPeration. This macro makes an operation \a op on
2203  * histogram \a h for pixel value \a x. It takes care of handling both levels.
2204  */
2205 #define HOP(h,x,op) \
2206     h.coarse[x>>4] op, \
2207     *((HT*)h.fine + x) op
2208
2209 #define COP(c,j,x,op) \
2210     h_coarse[ 16*(n*c+j) + (x>>4) ] op, \
2211     h_fine[ 16 * (n*(16*c+(x>>4)) + j) + (x & 0xF) ] op
2212
2213     int cn = _dst.channels(), m = _dst.rows, r = (ksize-1)/2;
2214     CV_Assert(cn > 0 && cn <= 4);
2215     size_t sstep = _src.step, dstep = _dst.step;
2216     Histogram CV_DECL_ALIGNED(16) H[4];
2217     HT CV_DECL_ALIGNED(16) luc[4][16];
2218
2219     int STRIPE_SIZE = std::min( _dst.cols, 512/cn );
2220
2221     std::vector<HT> _h_coarse(1 * 16 * (STRIPE_SIZE + 2*r) * cn + 16);
2222     std::vector<HT> _h_fine(16 * 16 * (STRIPE_SIZE + 2*r) * cn + 16);
2223     HT* h_coarse = alignPtr(&_h_coarse[0], 16);
2224     HT* h_fine = alignPtr(&_h_fine[0], 16);
2225 #if CV_SIMD128
2226     volatile bool useSIMD = hasSIMD128();
2227 #endif
2228
2229     for( int x = 0; x < _dst.cols; x += STRIPE_SIZE )
2230     {
2231         int i, j, k, c, n = std::min(_dst.cols - x, STRIPE_SIZE) + r*2;
2232         const uchar* src = _src.ptr() + x*cn;
2233         uchar* dst = _dst.ptr() + (x - r)*cn;
2234
2235         memset( h_coarse, 0, 16*n*cn*sizeof(h_coarse[0]) );
2236         memset( h_fine, 0, 16*16*n*cn*sizeof(h_fine[0]) );
2237
2238         // First row initialization
2239         for( c = 0; c < cn; c++ )
2240         {
2241             for( j = 0; j < n; j++ )
2242                 COP( c, j, src[cn*j+c], += (cv::HT)(r+2) );
2243
2244             for( i = 1; i < r; i++ )
2245             {
2246                 const uchar* p = src + sstep*std::min(i, m-1);
2247                 for ( j = 0; j < n; j++ )
2248                     COP( c, j, p[cn*j+c], ++ );
2249             }
2250         }
2251
2252         for( i = 0; i < m; i++ )
2253         {
2254             const uchar* p0 = src + sstep * std::max( 0, i-r-1 );
2255             const uchar* p1 = src + sstep * std::min( m-1, i+r );
2256
2257             memset( H, 0, cn*sizeof(H[0]) );
2258             memset( luc, 0, cn*sizeof(luc[0]) );
2259             for( c = 0; c < cn; c++ )
2260             {
2261                 // Update column histograms for the entire row.
2262                 for( j = 0; j < n; j++ )
2263                 {
2264                     COP( c, j, p0[j*cn + c], -- );
2265                     COP( c, j, p1[j*cn + c], ++ );
2266                 }
2267
2268                 // First column initialization
2269                 for( k = 0; k < 16; ++k )
2270                     histogram_muladd( 2*r+1, &h_fine[16*n*(16*c+k)], &H[c].fine[k][0] );
2271
2272 #if CV_SIMD128
2273                 if( useSIMD )
2274                 {
2275                     for( j = 0; j < 2*r; ++j )
2276                         histogram_add_simd( &h_coarse[16*(n*c+j)], H[c].coarse );
2277
2278                     for( j = r; j < n-r; j++ )
2279                     {
2280                         int t = 2*r*r + 2*r, b, sum = 0;
2281                         HT* segment;
2282
2283                         histogram_add_simd( &h_coarse[16*(n*c + std::min(j+r,n-1))], H[c].coarse );
2284
2285                         // Find median at coarse level
2286                         for ( k = 0; k < 16 ; ++k )
2287                         {
2288                             sum += H[c].coarse[k];
2289                             if ( sum > t )
2290                             {
2291                                 sum -= H[c].coarse[k];
2292                                 break;
2293                             }
2294                         }
2295                         CV_Assert( k < 16 );
2296
2297                         /* Update corresponding histogram segment */
2298                         if ( luc[c][k] <= j-r )
2299                         {
2300                             memset( &H[c].fine[k], 0, 16 * sizeof(HT) );
2301                             for ( luc[c][k] = cv::HT(j-r); luc[c][k] < MIN(j+r+1,n); ++luc[c][k] )
2302                                 histogram_add_simd( &h_fine[16*(n*(16*c+k)+luc[c][k])], H[c].fine[k] );
2303
2304                             if ( luc[c][k] < j+r+1 )
2305                             {
2306                                 histogram_muladd( j+r+1 - n, &h_fine[16*(n*(16*c+k)+(n-1))], &H[c].fine[k][0] );
2307                                 luc[c][k] = (HT)(j+r+1);
2308                             }
2309                         }
2310                         else
2311                         {
2312                             for ( ; luc[c][k] < j+r+1; ++luc[c][k] )
2313                             {
2314                                 histogram_sub_simd( &h_fine[16*(n*(16*c+k)+MAX(luc[c][k]-2*r-1,0))], H[c].fine[k] );
2315                                 histogram_add_simd( &h_fine[16*(n*(16*c+k)+MIN(luc[c][k],n-1))], H[c].fine[k] );
2316                             }
2317                         }
2318
2319                         histogram_sub_simd( &h_coarse[16*(n*c+MAX(j-r,0))], H[c].coarse );
2320
2321                         /* Find median in segment */
2322                         segment = H[c].fine[k];
2323                         for ( b = 0; b < 16 ; b++ )
2324                         {
2325                             sum += segment[b];
2326                             if ( sum > t )
2327                             {
2328                                 dst[dstep*i+cn*j+c] = (uchar)(16*k + b);
2329                                 break;
2330                             }
2331                         }
2332                         CV_Assert( b < 16 );
2333                     }
2334                 }
2335                 else
2336 #endif
2337                 {
2338                     for( j = 0; j < 2*r; ++j )
2339                         histogram_add( &h_coarse[16*(n*c+j)], H[c].coarse );
2340
2341                     for( j = r; j < n-r; j++ )
2342                     {
2343                         int t = 2*r*r + 2*r, b, sum = 0;
2344                         HT* segment;
2345
2346                         histogram_add( &h_coarse[16*(n*c + std::min(j+r,n-1))], H[c].coarse );
2347
2348                         // Find median at coarse level
2349                         for ( k = 0; k < 16 ; ++k )
2350                         {
2351                             sum += H[c].coarse[k];
2352                             if ( sum > t )
2353                             {
2354                                 sum -= H[c].coarse[k];
2355                                 break;
2356                             }
2357                         }
2358                         CV_Assert( k < 16 );
2359
2360                         /* Update corresponding histogram segment */
2361                         if ( luc[c][k] <= j-r )
2362                         {
2363                             memset( &H[c].fine[k], 0, 16 * sizeof(HT) );
2364                             for ( luc[c][k] = cv::HT(j-r); luc[c][k] < MIN(j+r+1,n); ++luc[c][k] )
2365                                 histogram_add( &h_fine[16*(n*(16*c+k)+luc[c][k])], H[c].fine[k] );
2366
2367                             if ( luc[c][k] < j+r+1 )
2368                             {
2369                                 histogram_muladd( j+r+1 - n, &h_fine[16*(n*(16*c+k)+(n-1))], &H[c].fine[k][0] );
2370                                 luc[c][k] = (HT)(j+r+1);
2371                             }
2372                         }
2373                         else
2374                         {
2375                             for ( ; luc[c][k] < j+r+1; ++luc[c][k] )
2376                             {
2377                                 histogram_sub( &h_fine[16*(n*(16*c+k)+MAX(luc[c][k]-2*r-1,0))], H[c].fine[k] );
2378                                 histogram_add( &h_fine[16*(n*(16*c+k)+MIN(luc[c][k],n-1))], H[c].fine[k] );
2379                             }
2380                         }
2381
2382                         histogram_sub( &h_coarse[16*(n*c+MAX(j-r,0))], H[c].coarse );
2383
2384                         /* Find median in segment */
2385                         segment = H[c].fine[k];
2386                         for ( b = 0; b < 16 ; b++ )
2387                         {
2388                             sum += segment[b];
2389                             if ( sum > t )
2390                             {
2391                                 dst[dstep*i+cn*j+c] = (uchar)(16*k + b);
2392                                 break;
2393                             }
2394                         }
2395                         CV_Assert( b < 16 );
2396                     }
2397                 }
2398             }
2399         }
2400     }
2401
2402 #undef HOP
2403 #undef COP
2404 }
2405
2406 static void
2407 medianBlur_8u_Om( const Mat& _src, Mat& _dst, int m )
2408 {
2409     #define N  16
2410     int     zone0[4][N];
2411     int     zone1[4][N*N];
2412     int     x, y;
2413     int     n2 = m*m/2;
2414     Size    size = _dst.size();
2415     const uchar* src = _src.ptr();
2416     uchar*  dst = _dst.ptr();
2417     int     src_step = (int)_src.step, dst_step = (int)_dst.step;
2418     int     cn = _src.channels();
2419     const uchar*  src_max = src + size.height*src_step;
2420     CV_Assert(cn > 0 && cn <= 4);
2421
2422     #define UPDATE_ACC01( pix, cn, op ) \
2423     {                                   \
2424         int p = (pix);                  \
2425         zone1[cn][p] op;                \
2426         zone0[cn][p >> 4] op;           \
2427     }
2428
2429     //CV_Assert( size.height >= nx && size.width >= nx );
2430     for( x = 0; x < size.width; x++, src += cn, dst += cn )
2431     {
2432         uchar* dst_cur = dst;
2433         const uchar* src_top = src;
2434         const uchar* src_bottom = src;
2435         int k, c;
2436         int src_step1 = src_step, dst_step1 = dst_step;
2437
2438         if( x % 2 != 0 )
2439         {
2440             src_bottom = src_top += src_step*(size.height-1);
2441             dst_cur += dst_step*(size.height-1);
2442             src_step1 = -src_step1;
2443             dst_step1 = -dst_step1;
2444         }
2445
2446         // init accumulator
2447         memset( zone0, 0, sizeof(zone0[0])*cn );
2448         memset( zone1, 0, sizeof(zone1[0])*cn );
2449
2450         for( y = 0; y <= m/2; y++ )
2451         {
2452             for( c = 0; c < cn; c++ )
2453             {
2454                 if( y > 0 )
2455                 {
2456                     for( k = 0; k < m*cn; k += cn )
2457                         UPDATE_ACC01( src_bottom[k+c], c, ++ );
2458                 }
2459                 else
2460                 {
2461                     for( k = 0; k < m*cn; k += cn )
2462                         UPDATE_ACC01( src_bottom[k+c], c, += m/2+1 );
2463                 }
2464             }
2465
2466             if( (src_step1 > 0 && y < size.height-1) ||
2467                 (src_step1 < 0 && size.height-y-1 > 0) )
2468                 src_bottom += src_step1;
2469         }
2470
2471         for( y = 0; y < size.height; y++, dst_cur += dst_step1 )
2472         {
2473             // find median
2474             for( c = 0; c < cn; c++ )
2475             {
2476                 int s = 0;
2477                 for( k = 0; ; k++ )
2478                 {
2479                     int t = s + zone0[c][k];
2480                     if( t > n2 ) break;
2481                     s = t;
2482                 }
2483
2484                 for( k *= N; ;k++ )
2485                 {
2486                     s += zone1[c][k];
2487                     if( s > n2 ) break;
2488                 }
2489
2490                 dst_cur[c] = (uchar)k;
2491             }
2492
2493             if( y+1 == size.height )
2494                 break;
2495
2496             if( cn == 1 )
2497             {
2498                 for( k = 0; k < m; k++ )
2499                 {
2500                     int p = src_top[k];
2501                     int q = src_bottom[k];
2502                     zone1[0][p]--;
2503                     zone0[0][p>>4]--;
2504                     zone1[0][q]++;
2505                     zone0[0][q>>4]++;
2506                 }
2507             }
2508             else if( cn == 3 )
2509             {
2510                 for( k = 0; k < m*3; k += 3 )
2511                 {
2512                     UPDATE_ACC01( src_top[k], 0, -- );
2513                     UPDATE_ACC01( src_top[k+1], 1, -- );
2514                     UPDATE_ACC01( src_top[k+2], 2, -- );
2515
2516                     UPDATE_ACC01( src_bottom[k], 0, ++ );
2517                     UPDATE_ACC01( src_bottom[k+1], 1, ++ );
2518                     UPDATE_ACC01( src_bottom[k+2], 2, ++ );
2519                 }
2520             }
2521             else
2522             {
2523                 assert( cn == 4 );
2524                 for( k = 0; k < m*4; k += 4 )
2525                 {
2526                     UPDATE_ACC01( src_top[k], 0, -- );
2527                     UPDATE_ACC01( src_top[k+1], 1, -- );
2528                     UPDATE_ACC01( src_top[k+2], 2, -- );
2529                     UPDATE_ACC01( src_top[k+3], 3, -- );
2530
2531                     UPDATE_ACC01( src_bottom[k], 0, ++ );
2532                     UPDATE_ACC01( src_bottom[k+1], 1, ++ );
2533                     UPDATE_ACC01( src_bottom[k+2], 2, ++ );
2534                     UPDATE_ACC01( src_bottom[k+3], 3, ++ );
2535                 }
2536             }
2537
2538             if( (src_step1 > 0 && src_bottom + src_step1 < src_max) ||
2539                 (src_step1 < 0 && src_bottom + src_step1 >= src) )
2540                 src_bottom += src_step1;
2541
2542             if( y >= m/2 )
2543                 src_top += src_step1;
2544         }
2545     }
2546 #undef N
2547 #undef UPDATE_ACC
2548 }
2549
2550
2551 struct MinMax8u
2552 {
2553     typedef uchar value_type;
2554     typedef int arg_type;
2555     enum { SIZE = 1 };
2556     arg_type load(const uchar* ptr) { return *ptr; }
2557     void store(uchar* ptr, arg_type val) { *ptr = (uchar)val; }
2558     void operator()(arg_type& a, arg_type& b) const
2559     {
2560         int t = CV_FAST_CAST_8U(a - b);
2561         b += t; a -= t;
2562     }
2563 };
2564
2565 struct MinMax16u
2566 {
2567     typedef ushort value_type;
2568     typedef int arg_type;
2569     enum { SIZE = 1 };
2570     arg_type load(const ushort* ptr) { return *ptr; }
2571     void store(ushort* ptr, arg_type val) { *ptr = (ushort)val; }
2572     void operator()(arg_type& a, arg_type& b) const
2573     {
2574         arg_type t = a;
2575         a = std::min(a, b);
2576         b = std::max(b, t);
2577     }
2578 };
2579
2580 struct MinMax16s
2581 {
2582     typedef short value_type;
2583     typedef int arg_type;
2584     enum { SIZE = 1 };
2585     arg_type load(const short* ptr) { return *ptr; }
2586     void store(short* ptr, arg_type val) { *ptr = (short)val; }
2587     void operator()(arg_type& a, arg_type& b) const
2588     {
2589         arg_type t = a;
2590         a = std::min(a, b);
2591         b = std::max(b, t);
2592     }
2593 };
2594
2595 struct MinMax32f
2596 {
2597     typedef float value_type;
2598     typedef float arg_type;
2599     enum { SIZE = 1 };
2600     arg_type load(const float* ptr) { return *ptr; }
2601     void store(float* ptr, arg_type val) { *ptr = val; }
2602     void operator()(arg_type& a, arg_type& b) const
2603     {
2604         arg_type t = a;
2605         a = std::min(a, b);
2606         b = std::max(b, t);
2607     }
2608 };
2609
2610 #if CV_SIMD128
2611
2612 struct MinMaxVec8u
2613 {
2614     typedef uchar value_type;
2615     typedef v_uint8x16 arg_type;
2616     enum { SIZE = 16 };
2617     arg_type load(const uchar* ptr) { return v_load(ptr); }
2618     void store(uchar* ptr, const arg_type &val) { v_store(ptr, val); }
2619     void operator()(arg_type& a, arg_type& b) const
2620     {
2621         arg_type t = a;
2622         a = v_min(a, b);
2623         b = v_max(b, t);
2624     }
2625 };
2626
2627
2628 struct MinMaxVec16u
2629 {
2630     typedef ushort value_type;
2631     typedef v_uint16x8 arg_type;
2632     enum { SIZE = 8 };
2633     arg_type load(const ushort* ptr) { return v_load(ptr); }
2634     void store(ushort* ptr, const arg_type &val) { v_store(ptr, val); }
2635     void operator()(arg_type& a, arg_type& b) const
2636     {
2637         arg_type t = a;
2638         a = v_min(a, b);
2639         b = v_max(b, t);
2640     }
2641 };
2642
2643
2644 struct MinMaxVec16s
2645 {
2646     typedef short value_type;
2647     typedef v_int16x8 arg_type;
2648     enum { SIZE = 8 };
2649     arg_type load(const short* ptr) { return v_load(ptr); }
2650     void store(short* ptr, const arg_type &val) { v_store(ptr, val); }
2651     void operator()(arg_type& a, arg_type& b) const
2652     {
2653         arg_type t = a;
2654         a = v_min(a, b);
2655         b = v_max(b, t);
2656     }
2657 };
2658
2659
2660 struct MinMaxVec32f
2661 {
2662     typedef float value_type;
2663     typedef v_float32x4 arg_type;
2664     enum { SIZE = 4 };
2665     arg_type load(const float* ptr) { return v_load(ptr); }
2666     void store(float* ptr, const arg_type &val) { v_store(ptr, val); }
2667     void operator()(arg_type& a, arg_type& b) const
2668     {
2669         arg_type t = a;
2670         a = v_min(a, b);
2671         b = v_max(b, t);
2672     }
2673 };
2674
2675 #else
2676
2677 typedef MinMax8u MinMaxVec8u;
2678 typedef MinMax16u MinMaxVec16u;
2679 typedef MinMax16s MinMaxVec16s;
2680 typedef MinMax32f MinMaxVec32f;
2681
2682 #endif
2683
2684 template<class Op, class VecOp>
2685 static void
2686 medianBlur_SortNet( const Mat& _src, Mat& _dst, int m )
2687 {
2688     typedef typename Op::value_type T;
2689     typedef typename Op::arg_type WT;
2690     typedef typename VecOp::arg_type VT;
2691
2692     const T* src = _src.ptr<T>();
2693     T* dst = _dst.ptr<T>();
2694     int sstep = (int)(_src.step/sizeof(T));
2695     int dstep = (int)(_dst.step/sizeof(T));
2696     Size size = _dst.size();
2697     int i, j, k, cn = _src.channels();
2698     Op op;
2699     VecOp vop;
2700     volatile bool useSIMD = hasSIMD128();
2701
2702     if( m == 3 )
2703     {
2704         if( size.width == 1 || size.height == 1 )
2705         {
2706             int len = size.width + size.height - 1;
2707             int sdelta = size.height == 1 ? cn : sstep;
2708             int sdelta0 = size.height == 1 ? 0 : sstep - cn;
2709             int ddelta = size.height == 1 ? cn : dstep;
2710
2711             for( i = 0; i < len; i++, src += sdelta0, dst += ddelta )
2712                 for( j = 0; j < cn; j++, src++ )
2713                 {
2714                     WT p0 = src[i > 0 ? -sdelta : 0];
2715                     WT p1 = src[0];
2716                     WT p2 = src[i < len - 1 ? sdelta : 0];
2717
2718                     op(p0, p1); op(p1, p2); op(p0, p1);
2719                     dst[j] = (T)p1;
2720                 }
2721             return;
2722         }
2723
2724         size.width *= cn;
2725         for( i = 0; i < size.height; i++, dst += dstep )
2726         {
2727             const T* row0 = src + std::max(i - 1, 0)*sstep;
2728             const T* row1 = src + i*sstep;
2729             const T* row2 = src + std::min(i + 1, size.height-1)*sstep;
2730             int limit = useSIMD ? cn : size.width;
2731
2732             for(j = 0;; )
2733             {
2734                 for( ; j < limit; j++ )
2735                 {
2736                     int j0 = j >= cn ? j - cn : j;
2737                     int j2 = j < size.width - cn ? j + cn : j;
2738                     WT p0 = row0[j0], p1 = row0[j], p2 = row0[j2];
2739                     WT p3 = row1[j0], p4 = row1[j], p5 = row1[j2];
2740                     WT p6 = row2[j0], p7 = row2[j], p8 = row2[j2];
2741
2742                     op(p1, p2); op(p4, p5); op(p7, p8); op(p0, p1);
2743                     op(p3, p4); op(p6, p7); op(p1, p2); op(p4, p5);
2744                     op(p7, p8); op(p0, p3); op(p5, p8); op(p4, p7);
2745                     op(p3, p6); op(p1, p4); op(p2, p5); op(p4, p7);
2746                     op(p4, p2); op(p6, p4); op(p4, p2);
2747                     dst[j] = (T)p4;
2748                 }
2749
2750                 if( limit == size.width )
2751                     break;
2752
2753                 for( ; j <= size.width - VecOp::SIZE - cn; j += VecOp::SIZE )
2754                 {
2755                     VT p0 = vop.load(row0+j-cn), p1 = vop.load(row0+j), p2 = vop.load(row0+j+cn);
2756                     VT p3 = vop.load(row1+j-cn), p4 = vop.load(row1+j), p5 = vop.load(row1+j+cn);
2757                     VT p6 = vop.load(row2+j-cn), p7 = vop.load(row2+j), p8 = vop.load(row2+j+cn);
2758
2759                     vop(p1, p2); vop(p4, p5); vop(p7, p8); vop(p0, p1);
2760                     vop(p3, p4); vop(p6, p7); vop(p1, p2); vop(p4, p5);
2761                     vop(p7, p8); vop(p0, p3); vop(p5, p8); vop(p4, p7);
2762                     vop(p3, p6); vop(p1, p4); vop(p2, p5); vop(p4, p7);
2763                     vop(p4, p2); vop(p6, p4); vop(p4, p2);
2764                     vop.store(dst+j, p4);
2765                 }
2766
2767                 limit = size.width;
2768             }
2769         }
2770     }
2771     else if( m == 5 )
2772     {
2773         if( size.width == 1 || size.height == 1 )
2774         {
2775             int len = size.width + size.height - 1;
2776             int sdelta = size.height == 1 ? cn : sstep;
2777             int sdelta0 = size.height == 1 ? 0 : sstep - cn;
2778             int ddelta = size.height == 1 ? cn : dstep;
2779
2780             for( i = 0; i < len; i++, src += sdelta0, dst += ddelta )
2781                 for( j = 0; j < cn; j++, src++ )
2782                 {
2783                     int i1 = i > 0 ? -sdelta : 0;
2784                     int i0 = i > 1 ? -sdelta*2 : i1;
2785                     int i3 = i < len-1 ? sdelta : 0;
2786                     int i4 = i < len-2 ? sdelta*2 : i3;
2787                     WT p0 = src[i0], p1 = src[i1], p2 = src[0], p3 = src[i3], p4 = src[i4];
2788
2789                     op(p0, p1); op(p3, p4); op(p2, p3); op(p3, p4); op(p0, p2);
2790                     op(p2, p4); op(p1, p3); op(p1, p2);
2791                     dst[j] = (T)p2;
2792                 }
2793             return;
2794         }
2795
2796         size.width *= cn;
2797         for( i = 0; i < size.height; i++, dst += dstep )
2798         {
2799             const T* row[5];
2800             row[0] = src + std::max(i - 2, 0)*sstep;
2801             row[1] = src + std::max(i - 1, 0)*sstep;
2802             row[2] = src + i*sstep;
2803             row[3] = src + std::min(i + 1, size.height-1)*sstep;
2804             row[4] = src + std::min(i + 2, size.height-1)*sstep;
2805             int limit = useSIMD ? cn*2 : size.width;
2806
2807             for(j = 0;; )
2808             {
2809                 for( ; j < limit; j++ )
2810                 {
2811                     WT p[25];
2812                     int j1 = j >= cn ? j - cn : j;
2813                     int j0 = j >= cn*2 ? j - cn*2 : j1;
2814                     int j3 = j < size.width - cn ? j + cn : j;
2815                     int j4 = j < size.width - cn*2 ? j + cn*2 : j3;
2816                     for( k = 0; k < 5; k++ )
2817                     {
2818                         const T* rowk = row[k];
2819                         p[k*5] = rowk[j0]; p[k*5+1] = rowk[j1];
2820                         p[k*5+2] = rowk[j]; p[k*5+3] = rowk[j3];
2821                         p[k*5+4] = rowk[j4];
2822                     }
2823
2824                     op(p[1], p[2]); op(p[0], p[1]); op(p[1], p[2]); op(p[4], p[5]); op(p[3], p[4]);
2825                     op(p[4], p[5]); op(p[0], p[3]); op(p[2], p[5]); op(p[2], p[3]); op(p[1], p[4]);
2826                     op(p[1], p[2]); op(p[3], p[4]); op(p[7], p[8]); op(p[6], p[7]); op(p[7], p[8]);
2827                     op(p[10], p[11]); op(p[9], p[10]); op(p[10], p[11]); op(p[6], p[9]); op(p[8], p[11]);
2828                     op(p[8], p[9]); op(p[7], p[10]); op(p[7], p[8]); op(p[9], p[10]); op(p[0], p[6]);
2829                     op(p[4], p[10]); op(p[4], p[6]); op(p[2], p[8]); op(p[2], p[4]); op(p[6], p[8]);
2830                     op(p[1], p[7]); op(p[5], p[11]); op(p[5], p[7]); op(p[3], p[9]); op(p[3], p[5]);
2831                     op(p[7], p[9]); op(p[1], p[2]); op(p[3], p[4]); op(p[5], p[6]); op(p[7], p[8]);
2832                     op(p[9], p[10]); op(p[13], p[14]); op(p[12], p[13]); op(p[13], p[14]); op(p[16], p[17]);
2833                     op(p[15], p[16]); op(p[16], p[17]); op(p[12], p[15]); op(p[14], p[17]); op(p[14], p[15]);
2834                     op(p[13], p[16]); op(p[13], p[14]); op(p[15], p[16]); op(p[19], p[20]); op(p[18], p[19]);
2835                     op(p[19], p[20]); op(p[21], p[22]); op(p[23], p[24]); op(p[21], p[23]); op(p[22], p[24]);
2836                     op(p[22], p[23]); op(p[18], p[21]); op(p[20], p[23]); op(p[20], p[21]); op(p[19], p[22]);
2837                     op(p[22], p[24]); op(p[19], p[20]); op(p[21], p[22]); op(p[23], p[24]); op(p[12], p[18]);
2838                     op(p[16], p[22]); op(p[16], p[18]); op(p[14], p[20]); op(p[20], p[24]); op(p[14], p[16]);
2839                     op(p[18], p[20]); op(p[22], p[24]); op(p[13], p[19]); op(p[17], p[23]); op(p[17], p[19]);
2840                     op(p[15], p[21]); op(p[15], p[17]); op(p[19], p[21]); op(p[13], p[14]); op(p[15], p[16]);
2841                     op(p[17], p[18]); op(p[19], p[20]); op(p[21], p[22]); op(p[23], p[24]); op(p[0], p[12]);
2842                     op(p[8], p[20]); op(p[8], p[12]); op(p[4], p[16]); op(p[16], p[24]); op(p[12], p[16]);
2843                     op(p[2], p[14]); op(p[10], p[22]); op(p[10], p[14]); op(p[6], p[18]); op(p[6], p[10]);
2844                     op(p[10], p[12]); op(p[1], p[13]); op(p[9], p[21]); op(p[9], p[13]); op(p[5], p[17]);
2845                     op(p[13], p[17]); op(p[3], p[15]); op(p[11], p[23]); op(p[11], p[15]); op(p[7], p[19]);
2846                     op(p[7], p[11]); op(p[11], p[13]); op(p[11], p[12]);
2847                     dst[j] = (T)p[12];
2848                 }
2849
2850                 if( limit == size.width )
2851                     break;
2852
2853                 for( ; j <= size.width - VecOp::SIZE - cn*2; j += VecOp::SIZE )
2854                 {
2855                     VT p[25];
2856                     for( k = 0; k < 5; k++ )
2857                     {
2858                         const T* rowk = row[k];
2859                         p[k*5] = vop.load(rowk+j-cn*2); p[k*5+1] = vop.load(rowk+j-cn);
2860                         p[k*5+2] = vop.load(rowk+j); p[k*5+3] = vop.load(rowk+j+cn);
2861                         p[k*5+4] = vop.load(rowk+j+cn*2);
2862                     }
2863
2864                     vop(p[1], p[2]); vop(p[0], p[1]); vop(p[1], p[2]); vop(p[4], p[5]); vop(p[3], p[4]);
2865                     vop(p[4], p[5]); vop(p[0], p[3]); vop(p[2], p[5]); vop(p[2], p[3]); vop(p[1], p[4]);
2866                     vop(p[1], p[2]); vop(p[3], p[4]); vop(p[7], p[8]); vop(p[6], p[7]); vop(p[7], p[8]);
2867                     vop(p[10], p[11]); vop(p[9], p[10]); vop(p[10], p[11]); vop(p[6], p[9]); vop(p[8], p[11]);
2868                     vop(p[8], p[9]); vop(p[7], p[10]); vop(p[7], p[8]); vop(p[9], p[10]); vop(p[0], p[6]);
2869                     vop(p[4], p[10]); vop(p[4], p[6]); vop(p[2], p[8]); vop(p[2], p[4]); vop(p[6], p[8]);
2870                     vop(p[1], p[7]); vop(p[5], p[11]); vop(p[5], p[7]); vop(p[3], p[9]); vop(p[3], p[5]);
2871                     vop(p[7], p[9]); vop(p[1], p[2]); vop(p[3], p[4]); vop(p[5], p[6]); vop(p[7], p[8]);
2872                     vop(p[9], p[10]); vop(p[13], p[14]); vop(p[12], p[13]); vop(p[13], p[14]); vop(p[16], p[17]);
2873                     vop(p[15], p[16]); vop(p[16], p[17]); vop(p[12], p[15]); vop(p[14], p[17]); vop(p[14], p[15]);
2874                     vop(p[13], p[16]); vop(p[13], p[14]); vop(p[15], p[16]); vop(p[19], p[20]); vop(p[18], p[19]);
2875                     vop(p[19], p[20]); vop(p[21], p[22]); vop(p[23], p[24]); vop(p[21], p[23]); vop(p[22], p[24]);
2876                     vop(p[22], p[23]); vop(p[18], p[21]); vop(p[20], p[23]); vop(p[20], p[21]); vop(p[19], p[22]);
2877                     vop(p[22], p[24]); vop(p[19], p[20]); vop(p[21], p[22]); vop(p[23], p[24]); vop(p[12], p[18]);
2878                     vop(p[16], p[22]); vop(p[16], p[18]); vop(p[14], p[20]); vop(p[20], p[24]); vop(p[14], p[16]);
2879                     vop(p[18], p[20]); vop(p[22], p[24]); vop(p[13], p[19]); vop(p[17], p[23]); vop(p[17], p[19]);
2880                     vop(p[15], p[21]); vop(p[15], p[17]); vop(p[19], p[21]); vop(p[13], p[14]); vop(p[15], p[16]);
2881                     vop(p[17], p[18]); vop(p[19], p[20]); vop(p[21], p[22]); vop(p[23], p[24]); vop(p[0], p[12]);
2882                     vop(p[8], p[20]); vop(p[8], p[12]); vop(p[4], p[16]); vop(p[16], p[24]); vop(p[12], p[16]);
2883                     vop(p[2], p[14]); vop(p[10], p[22]); vop(p[10], p[14]); vop(p[6], p[18]); vop(p[6], p[10]);
2884                     vop(p[10], p[12]); vop(p[1], p[13]); vop(p[9], p[21]); vop(p[9], p[13]); vop(p[5], p[17]);
2885                     vop(p[13], p[17]); vop(p[3], p[15]); vop(p[11], p[23]); vop(p[11], p[15]); vop(p[7], p[19]);
2886                     vop(p[7], p[11]); vop(p[11], p[13]); vop(p[11], p[12]);
2887                     vop.store(dst+j, p[12]);
2888                 }
2889
2890                 limit = size.width;
2891             }
2892         }
2893     }
2894 }
2895
2896 #ifdef HAVE_OPENCL
2897
2898 static bool ocl_medianFilter(InputArray _src, OutputArray _dst, int m)
2899 {
2900     size_t localsize[2] = { 16, 16 };
2901     size_t globalsize[2];
2902     int type = _src.type(), depth = CV_MAT_DEPTH(type), cn = CV_MAT_CN(type);
2903
2904     if ( !((depth == CV_8U || depth == CV_16U || depth == CV_16S || depth == CV_32F) && cn <= 4 && (m == 3 || m == 5)) )
2905         return false;
2906
2907     Size imgSize = _src.size();
2908     bool useOptimized = (1 == cn) &&
2909                         (size_t)imgSize.width >= localsize[0] * 8  &&
2910                         (size_t)imgSize.height >= localsize[1] * 8 &&
2911                         imgSize.width % 4 == 0 &&
2912                         imgSize.height % 4 == 0 &&
2913                         (ocl::Device::getDefault().isIntel());
2914
2915     cv::String kname = format( useOptimized ? "medianFilter%d_u" : "medianFilter%d", m) ;
2916     cv::String kdefs = useOptimized ?
2917                          format("-D T=%s -D T1=%s -D T4=%s%d -D cn=%d -D USE_4OPT", ocl::typeToStr(type),
2918                          ocl::typeToStr(depth), ocl::typeToStr(depth), cn*4, cn)
2919                          :
2920                          format("-D T=%s -D T1=%s -D cn=%d", ocl::typeToStr(type), ocl::typeToStr(depth), cn) ;
2921
2922     ocl::Kernel k(kname.c_str(), ocl::imgproc::medianFilter_oclsrc, kdefs.c_str() );
2923
2924     if (k.empty())
2925         return false;
2926
2927     UMat src = _src.getUMat();
2928     _dst.create(src.size(), type);
2929     UMat dst = _dst.getUMat();
2930
2931     k.args(ocl::KernelArg::ReadOnlyNoSize(src), ocl::KernelArg::WriteOnly(dst));
2932
2933     if( useOptimized )
2934     {
2935         globalsize[0] = DIVUP(src.cols / 4, localsize[0]) * localsize[0];
2936         globalsize[1] = DIVUP(src.rows / 4, localsize[1]) * localsize[1];
2937     }
2938     else
2939     {
2940         globalsize[0] = (src.cols + localsize[0] + 2) / localsize[0] * localsize[0];
2941         globalsize[1] = (src.rows + localsize[1] - 1) / localsize[1] * localsize[1];
2942     }
2943
2944     return k.run(2, globalsize, localsize, false);
2945 }
2946
2947 #endif
2948
2949 }
2950
2951 #ifdef HAVE_OPENVX
2952 namespace cv
2953 {
2954     namespace ovx {
2955         template <> inline bool skipSmallImages<VX_KERNEL_MEDIAN_3x3>(int w, int h) { return w*h < 1280 * 720; }
2956     }
2957     static bool openvx_medianFilter(InputArray _src, OutputArray _dst, int ksize)
2958     {
2959         if (_src.type() != CV_8UC1 || _dst.type() != CV_8U
2960 #ifndef VX_VERSION_1_1
2961             || ksize != 3
2962 #endif
2963             )
2964             return false;
2965
2966         Mat src = _src.getMat();
2967         Mat dst = _dst.getMat();
2968
2969         if (
2970 #ifdef VX_VERSION_1_1
2971              ksize != 3 ? ovx::skipSmallImages<VX_KERNEL_NON_LINEAR_FILTER>(src.cols, src.rows) :
2972 #endif
2973              ovx::skipSmallImages<VX_KERNEL_MEDIAN_3x3>(src.cols, src.rows)
2974            )
2975             return false;
2976
2977         try
2978         {
2979             ivx::Context ctx = ovx::getOpenVXContext();
2980 #ifdef VX_VERSION_1_1
2981             if ((vx_size)ksize > ctx.nonlinearMaxDimension())
2982                 return false;
2983 #endif
2984
2985             Mat a;
2986             if (dst.data != src.data)
2987                 a = src;
2988             else
2989                 src.copyTo(a);
2990
2991             ivx::Image
2992                 ia = ivx::Image::createFromHandle(ctx, VX_DF_IMAGE_U8,
2993                     ivx::Image::createAddressing(a.cols, a.rows, 1, (vx_int32)(a.step)), a.data),
2994                 ib = ivx::Image::createFromHandle(ctx, VX_DF_IMAGE_U8,
2995                     ivx::Image::createAddressing(dst.cols, dst.rows, 1, (vx_int32)(dst.step)), dst.data);
2996
2997             //ATTENTION: VX_CONTEXT_IMMEDIATE_BORDER attribute change could lead to strange issues in multi-threaded environments
2998             //since OpenVX standart says nothing about thread-safety for now
2999             ivx::border_t prevBorder = ctx.immediateBorder();
3000             ctx.setImmediateBorder(VX_BORDER_REPLICATE);
3001 #ifdef VX_VERSION_1_1
3002             if (ksize == 3)
3003 #endif
3004             {
3005                 ivx::IVX_CHECK_STATUS(vxuMedian3x3(ctx, ia, ib));
3006             }
3007 #ifdef VX_VERSION_1_1
3008             else
3009             {
3010                 ivx::Matrix mtx;
3011                 if(ksize == 5)
3012                     mtx = ivx::Matrix::createFromPattern(ctx, VX_PATTERN_BOX, ksize, ksize);
3013                 else
3014                 {
3015                     vx_size supportedSize;
3016                     ivx::IVX_CHECK_STATUS(vxQueryContext(ctx, VX_CONTEXT_NONLINEAR_MAX_DIMENSION, &supportedSize, sizeof(supportedSize)));
3017                     if ((vx_size)ksize > supportedSize)
3018                     {
3019                         ctx.setImmediateBorder(prevBorder);
3020                         return false;
3021                     }
3022                     Mat mask(ksize, ksize, CV_8UC1, Scalar(255));
3023                     mtx = ivx::Matrix::create(ctx, VX_TYPE_UINT8, ksize, ksize);
3024                     mtx.copyFrom(mask);
3025                 }
3026                 ivx::IVX_CHECK_STATUS(vxuNonLinearFilter(ctx, VX_NONLINEAR_FILTER_MEDIAN, ia, mtx, ib));
3027             }
3028 #endif
3029             ctx.setImmediateBorder(prevBorder);
3030         }
3031         catch (ivx::RuntimeError & e)
3032         {
3033             VX_DbgThrow(e.what());
3034         }
3035         catch (ivx::WrapperError & e)
3036         {
3037             VX_DbgThrow(e.what());
3038         }
3039
3040         return true;
3041     }
3042 }
3043 #endif
3044
3045 #ifdef HAVE_IPP
3046 namespace cv
3047 {
3048 static bool ipp_medianFilter(Mat &src0, Mat &dst, int ksize)
3049 {
3050     CV_INSTRUMENT_REGION_IPP()
3051
3052 #if IPP_VERSION_X100 < 201801
3053     // Degradations for big kernel
3054     if(ksize > 7)
3055         return false;
3056 #endif
3057
3058     {
3059         int         bufSize;
3060         IppiSize    dstRoiSize = ippiSize(dst.cols, dst.rows), maskSize = ippiSize(ksize, ksize);
3061         IppDataType ippType = ippiGetDataType(src0.type());
3062         int         channels = src0.channels();
3063         IppAutoBuffer<Ipp8u> buffer;
3064
3065         if(src0.isSubmatrix())
3066             return false;
3067
3068         Mat src;
3069         if(dst.data != src0.data)
3070             src = src0;
3071         else
3072             src0.copyTo(src);
3073
3074         if(ippiFilterMedianBorderGetBufferSize(dstRoiSize, maskSize, ippType, channels, &bufSize) < 0)
3075             return false;
3076
3077         buffer.allocate(bufSize);
3078
3079         switch(ippType)
3080         {
3081         case ipp8u:
3082             if(channels == 1)
3083                 return CV_INSTRUMENT_FUN_IPP(ippiFilterMedianBorder_8u_C1R, src.ptr<Ipp8u>(), (int)src.step, dst.ptr<Ipp8u>(), (int)dst.step, dstRoiSize, maskSize, ippBorderRepl, 0, buffer) >= 0;
3084             else if(channels == 3)
3085                 return CV_INSTRUMENT_FUN_IPP(ippiFilterMedianBorder_8u_C3R, src.ptr<Ipp8u>(), (int)src.step, dst.ptr<Ipp8u>(), (int)dst.step, dstRoiSize, maskSize, ippBorderRepl, 0, buffer) >= 0;
3086             else if(channels == 4)
3087                 return CV_INSTRUMENT_FUN_IPP(ippiFilterMedianBorder_8u_C4R, src.ptr<Ipp8u>(), (int)src.step, dst.ptr<Ipp8u>(), (int)dst.step, dstRoiSize, maskSize, ippBorderRepl, 0, buffer) >= 0;
3088             else
3089                 return false;
3090         case ipp16u:
3091             if(channels == 1)
3092                 return CV_INSTRUMENT_FUN_IPP(ippiFilterMedianBorder_16u_C1R, src.ptr<Ipp16u>(), (int)src.step, dst.ptr<Ipp16u>(), (int)dst.step, dstRoiSize, maskSize, ippBorderRepl, 0, buffer) >= 0;
3093             else if(channels == 3)
3094                 return CV_INSTRUMENT_FUN_IPP(ippiFilterMedianBorder_16u_C3R, src.ptr<Ipp16u>(), (int)src.step, dst.ptr<Ipp16u>(), (int)dst.step, dstRoiSize, maskSize, ippBorderRepl, 0, buffer) >= 0;
3095             else if(channels == 4)
3096                 return CV_INSTRUMENT_FUN_IPP(ippiFilterMedianBorder_16u_C4R, src.ptr<Ipp16u>(), (int)src.step, dst.ptr<Ipp16u>(), (int)dst.step, dstRoiSize, maskSize, ippBorderRepl, 0, buffer) >= 0;
3097             else
3098                 return false;
3099         case ipp16s:
3100             if(channels == 1)
3101                 return CV_INSTRUMENT_FUN_IPP(ippiFilterMedianBorder_16s_C1R, src.ptr<Ipp16s>(), (int)src.step, dst.ptr<Ipp16s>(), (int)dst.step, dstRoiSize, maskSize, ippBorderRepl, 0, buffer) >= 0;
3102             else if(channels == 3)
3103                 return CV_INSTRUMENT_FUN_IPP(ippiFilterMedianBorder_16s_C3R, src.ptr<Ipp16s>(), (int)src.step, dst.ptr<Ipp16s>(), (int)dst.step, dstRoiSize, maskSize, ippBorderRepl, 0, buffer) >= 0;
3104             else if(channels == 4)
3105                 return CV_INSTRUMENT_FUN_IPP(ippiFilterMedianBorder_16s_C4R, src.ptr<Ipp16s>(), (int)src.step, dst.ptr<Ipp16s>(), (int)dst.step, dstRoiSize, maskSize, ippBorderRepl, 0, buffer) >= 0;
3106             else
3107                 return false;
3108         case ipp32f:
3109             if(channels == 1)
3110                 return CV_INSTRUMENT_FUN_IPP(ippiFilterMedianBorder_32f_C1R, src.ptr<Ipp32f>(), (int)src.step, dst.ptr<Ipp32f>(), (int)dst.step, dstRoiSize, maskSize, ippBorderRepl, 0, buffer) >= 0;
3111             else
3112                 return false;
3113         default:
3114             return false;
3115         }
3116     }
3117 }
3118 }
3119 #endif
3120
3121 void cv::medianBlur( InputArray _src0, OutputArray _dst, int ksize )
3122 {
3123     CV_INSTRUMENT_REGION()
3124
3125     CV_Assert( (ksize % 2 == 1) && (_src0.dims() <= 2 ));
3126
3127     if( ksize <= 1 || _src0.empty() )
3128     {
3129         _src0.copyTo(_dst);
3130         return;
3131     }
3132
3133     CV_OCL_RUN(_dst.isUMat(),
3134                ocl_medianFilter(_src0,_dst, ksize))
3135
3136     Mat src0 = _src0.getMat();
3137     _dst.create( src0.size(), src0.type() );
3138     Mat dst = _dst.getMat();
3139
3140     CALL_HAL(medianBlur, cv_hal_medianBlur, src0.data, src0.step, dst.data, dst.step, src0.cols, src0.rows, src0.depth(),
3141              src0.channels(), ksize);
3142
3143     CV_OVX_RUN(true,
3144                openvx_medianFilter(_src0, _dst, ksize))
3145
3146     CV_IPP_RUN_FAST(ipp_medianFilter(src0, dst, ksize));
3147
3148 #ifdef HAVE_TEGRA_OPTIMIZATION
3149     if (tegra::useTegra() && tegra::medianBlur(src0, dst, ksize))
3150         return;
3151 #endif
3152
3153     bool useSortNet = ksize == 3 || (ksize == 5
3154 #if !(CV_SIMD128)
3155             && ( src0.depth() > CV_8U || src0.channels() == 2 || src0.channels() > 4 )
3156 #endif
3157         );
3158
3159     Mat src;
3160     if( useSortNet )
3161     {
3162         if( dst.data != src0.data )
3163             src = src0;
3164         else
3165             src0.copyTo(src);
3166
3167         if( src.depth() == CV_8U )
3168             medianBlur_SortNet<MinMax8u, MinMaxVec8u>( src, dst, ksize );
3169         else if( src.depth() == CV_16U )
3170             medianBlur_SortNet<MinMax16u, MinMaxVec16u>( src, dst, ksize );
3171         else if( src.depth() == CV_16S )
3172             medianBlur_SortNet<MinMax16s, MinMaxVec16s>( src, dst, ksize );
3173         else if( src.depth() == CV_32F )
3174             medianBlur_SortNet<MinMax32f, MinMaxVec32f>( src, dst, ksize );
3175         else
3176             CV_Error(CV_StsUnsupportedFormat, "");
3177
3178         return;
3179     }
3180     else
3181     {
3182         cv::copyMakeBorder( src0, src, 0, 0, ksize/2, ksize/2, BORDER_REPLICATE|BORDER_ISOLATED);
3183
3184         int cn = src0.channels();
3185         CV_Assert( src.depth() == CV_8U && (cn == 1 || cn == 3 || cn == 4) );
3186
3187         double img_size_mp = (double)(src0.total())/(1 << 20);
3188         if( ksize <= 3 + (img_size_mp < 1 ? 12 : img_size_mp < 4 ? 6 : 2)*
3189             (CV_SIMD128 && hasSIMD128() ? 1 : 3))
3190             medianBlur_8u_Om( src, dst, ksize );
3191         else
3192             medianBlur_8u_O1( src, dst, ksize );
3193     }
3194 }
3195
3196 /****************************************************************************************\
3197                                    Bilateral Filtering
3198 \****************************************************************************************/
3199
3200 namespace cv
3201 {
3202
3203 class BilateralFilter_8u_Invoker :
3204     public ParallelLoopBody
3205 {
3206 public:
3207     BilateralFilter_8u_Invoker(Mat& _dest, const Mat& _temp, int _radius, int _maxk,
3208         int* _space_ofs, float *_space_weight, float *_color_weight) :
3209         temp(&_temp), dest(&_dest), radius(_radius),
3210         maxk(_maxk), space_ofs(_space_ofs), space_weight(_space_weight), color_weight(_color_weight)
3211     {
3212     }
3213
3214     virtual void operator() (const Range& range) const
3215     {
3216         int i, j, cn = dest->channels(), k;
3217         Size size = dest->size();
3218 #if CV_SIMD128
3219         int CV_DECL_ALIGNED(16) buf[4];
3220         bool haveSIMD128 = hasSIMD128();
3221 #endif
3222
3223         for( i = range.start; i < range.end; i++ )
3224         {
3225             const uchar* sptr = temp->ptr(i+radius) + radius*cn;
3226             uchar* dptr = dest->ptr(i);
3227
3228             if( cn == 1 )
3229             {
3230                 for( j = 0; j < size.width; j++ )
3231                 {
3232                     float sum = 0, wsum = 0;
3233                     int val0 = sptr[j];
3234                     k = 0;
3235 #if CV_SIMD128
3236                     if( haveSIMD128 )
3237                     {
3238                         v_float32x4 _val0 = v_setall_f32(static_cast<float>(val0));
3239                         v_float32x4 vsumw = v_setzero_f32();
3240                         v_float32x4 vsumc = v_setzero_f32();
3241
3242                         for( ; k <= maxk - 4; k += 4 )
3243                         {
3244                             v_float32x4 _valF = v_float32x4(sptr[j + space_ofs[k]],
3245                                 sptr[j + space_ofs[k + 1]],
3246                                 sptr[j + space_ofs[k + 2]],
3247                                 sptr[j + space_ofs[k + 3]]);
3248                             v_float32x4 _val = v_abs(_valF - _val0);
3249                             v_store(buf, v_round(_val));
3250
3251                             v_float32x4 _cw = v_float32x4(color_weight[buf[0]],
3252                                 color_weight[buf[1]],
3253                                 color_weight[buf[2]],
3254                                 color_weight[buf[3]]);
3255                             v_float32x4 _sw = v_load(space_weight+k);
3256                             v_float32x4 _w = _cw * _sw;
3257                             _cw = _w * _valF;
3258
3259                             vsumw += _w;
3260                             vsumc += _cw;
3261                         }
3262                         float *bufFloat = (float*)buf;
3263                         v_float32x4 sum4 = v_reduce_sum4(vsumw, vsumc, vsumw, vsumc);
3264                         v_store(bufFloat, sum4);
3265                         sum += bufFloat[1];
3266                         wsum += bufFloat[0];
3267                     }
3268 #endif
3269                     for( ; k < maxk; k++ )
3270                     {
3271                         int val = sptr[j + space_ofs[k]];
3272                         float w = space_weight[k]*color_weight[std::abs(val - val0)];
3273                         sum += val*w;
3274                         wsum += w;
3275                     }
3276                     // overflow is not possible here => there is no need to use cv::saturate_cast
3277                     dptr[j] = (uchar)cvRound(sum/wsum);
3278                 }
3279             }
3280             else
3281             {
3282                 assert( cn == 3 );
3283                 for( j = 0; j < size.width*3; j += 3 )
3284                 {
3285                     float sum_b = 0, sum_g = 0, sum_r = 0, wsum = 0;
3286                     int b0 = sptr[j], g0 = sptr[j+1], r0 = sptr[j+2];
3287                     k = 0;
3288 #if CV_SIMD128
3289                     if( haveSIMD128 )
3290                     {
3291                         v_float32x4 vsumw = v_setzero_f32();
3292                         v_float32x4 vsumb = v_setzero_f32();
3293                         v_float32x4 vsumg = v_setzero_f32();
3294                         v_float32x4 vsumr = v_setzero_f32();
3295                         const v_float32x4 _b0 = v_setall_f32(static_cast<float>(b0));
3296                         const v_float32x4 _g0 = v_setall_f32(static_cast<float>(g0));
3297                         const v_float32x4 _r0 = v_setall_f32(static_cast<float>(r0));
3298
3299                         for( ; k <= maxk - 4; k += 4 )
3300                         {
3301                             const uchar* const sptr_k0  = sptr + j + space_ofs[k];
3302                             const uchar* const sptr_k1  = sptr + j + space_ofs[k+1];
3303                             const uchar* const sptr_k2  = sptr + j + space_ofs[k+2];
3304                             const uchar* const sptr_k3  = sptr + j + space_ofs[k+3];
3305
3306                             v_float32x4 __b = v_cvt_f32(v_reinterpret_as_s32(v_load_expand_q(sptr_k0)));
3307                             v_float32x4 __g = v_cvt_f32(v_reinterpret_as_s32(v_load_expand_q(sptr_k1)));
3308                             v_float32x4 __r = v_cvt_f32(v_reinterpret_as_s32(v_load_expand_q(sptr_k2)));
3309                             v_float32x4 __z = v_cvt_f32(v_reinterpret_as_s32(v_load_expand_q(sptr_k3)));
3310                             v_float32x4 _b, _g, _r, _z;
3311
3312                             v_transpose4x4(__b, __g, __r, __z, _b, _g, _r, _z);
3313
3314                             v_float32x4 bt = v_abs(_b -_b0);
3315                             v_float32x4 gt = v_abs(_g -_g0);
3316                             v_float32x4 rt = v_abs(_r -_r0);
3317
3318                             bt = rt + bt + gt;
3319                             v_store(buf, v_round(bt));
3320
3321                             v_float32x4 _w  = v_float32x4(color_weight[buf[0]],color_weight[buf[1]],
3322                                                     color_weight[buf[2]],color_weight[buf[3]]);
3323                             v_float32x4 _sw = v_load(space_weight+k);
3324
3325                             _w *= _sw;
3326                             _b *=  _w;
3327                             _g *=  _w;
3328                             _r *=  _w;
3329
3330                             vsumw += _w;
3331                             vsumb += _b;
3332                             vsumg += _g;
3333                             vsumr += _r;
3334                         }
3335                         float *bufFloat = (float*)buf;
3336                         v_float32x4 sum4 = v_reduce_sum4(vsumw, vsumb, vsumg, vsumr);
3337                         v_store(bufFloat, sum4);
3338                         wsum += bufFloat[0];
3339                         sum_b += bufFloat[1];
3340                         sum_g += bufFloat[2];
3341                         sum_r += bufFloat[3];
3342                     }
3343 #endif
3344
3345                     for( ; k < maxk; k++ )
3346                     {
3347                         const uchar* sptr_k = sptr + j + space_ofs[k];
3348                         int b = sptr_k[0], g = sptr_k[1], r = sptr_k[2];
3349                         float w = space_weight[k]*color_weight[std::abs(b - b0) +
3350                                                                std::abs(g - g0) + std::abs(r - r0)];
3351                         sum_b += b*w; sum_g += g*w; sum_r += r*w;
3352                         wsum += w;
3353                     }
3354                     wsum = 1.f/wsum;
3355                     b0 = cvRound(sum_b*wsum);
3356                     g0 = cvRound(sum_g*wsum);
3357                     r0 = cvRound(sum_r*wsum);
3358                     dptr[j] = (uchar)b0; dptr[j+1] = (uchar)g0; dptr[j+2] = (uchar)r0;
3359                 }
3360             }
3361         }
3362     }
3363
3364 private:
3365     const Mat *temp;
3366     Mat *dest;
3367     int radius, maxk, *space_ofs;
3368     float *space_weight, *color_weight;
3369 };
3370
3371 #ifdef HAVE_OPENCL
3372
3373 static bool ocl_bilateralFilter_8u(InputArray _src, OutputArray _dst, int d,
3374                                    double sigma_color, double sigma_space,
3375                                    int borderType)
3376 {
3377 #ifdef __ANDROID__
3378     if (ocl::Device::getDefault().isNVidia())
3379         return false;
3380 #endif
3381
3382     int type = _src.type(), depth = CV_MAT_DEPTH(type), cn = CV_MAT_CN(type);
3383     int i, j, maxk, radius;
3384
3385     if (depth != CV_8U || cn > 4)
3386         return false;
3387
3388     if (sigma_color <= 0)
3389         sigma_color = 1;
3390     if (sigma_space <= 0)
3391         sigma_space = 1;
3392
3393     double gauss_color_coeff = -0.5 / (sigma_color * sigma_color);
3394     double gauss_space_coeff = -0.5 / (sigma_space * sigma_space);
3395
3396     if ( d <= 0 )
3397         radius = cvRound(sigma_space * 1.5);
3398     else
3399         radius = d / 2;
3400     radius = MAX(radius, 1);
3401     d = radius * 2 + 1;
3402
3403     UMat src = _src.getUMat(), dst = _dst.getUMat(), temp;
3404     if (src.u == dst.u)
3405         return false;
3406
3407     copyMakeBorder(src, temp, radius, radius, radius, radius, borderType);
3408     std::vector<float> _space_weight(d * d);
3409     std::vector<int> _space_ofs(d * d);
3410     float * const space_weight = &_space_weight[0];
3411     int * const space_ofs = &_space_ofs[0];
3412
3413     // initialize space-related bilateral filter coefficients
3414     for( i = -radius, maxk = 0; i <= radius; i++ )
3415         for( j = -radius; j <= radius; j++ )
3416         {
3417             double r = std::sqrt((double)i * i + (double)j * j);
3418             if ( r > radius )
3419                 continue;
3420             space_weight[maxk] = (float)std::exp(r * r * gauss_space_coeff);
3421             space_ofs[maxk++] = (int)(i * temp.step + j * cn);
3422         }
3423
3424     char cvt[3][40];
3425     String cnstr = cn > 1 ? format("%d", cn) : "";
3426     String kernelName("bilateral");
3427     size_t sizeDiv = 1;
3428     if ((ocl::Device::getDefault().isIntel()) &&
3429         (ocl::Device::getDefault().type() == ocl::Device::TYPE_GPU))
3430     {
3431             //Intel GPU
3432             if (dst.cols % 4 == 0 && cn == 1) // For single channel x4 sized images.
3433             {
3434                 kernelName = "bilateral_float4";
3435                 sizeDiv = 4;
3436             }
3437      }
3438      ocl::Kernel k(kernelName.c_str(), ocl::imgproc::bilateral_oclsrc,
3439             format("-D radius=%d -D maxk=%d -D cn=%d -D int_t=%s -D uint_t=uint%s -D convert_int_t=%s"
3440             " -D uchar_t=%s -D float_t=%s -D convert_float_t=%s -D convert_uchar_t=%s -D gauss_color_coeff=(float)%f",
3441             radius, maxk, cn, ocl::typeToStr(CV_32SC(cn)), cnstr.c_str(),
3442             ocl::convertTypeStr(CV_8U, CV_32S, cn, cvt[0]),
3443             ocl::typeToStr(type), ocl::typeToStr(CV_32FC(cn)),
3444             ocl::convertTypeStr(CV_32S, CV_32F, cn, cvt[1]),
3445             ocl::convertTypeStr(CV_32F, CV_8U, cn, cvt[2]), gauss_color_coeff));
3446     if (k.empty())
3447         return false;
3448
3449     Mat mspace_weight(1, d * d, CV_32FC1, space_weight);
3450     Mat mspace_ofs(1, d * d, CV_32SC1, space_ofs);
3451     UMat ucolor_weight, uspace_weight, uspace_ofs;
3452
3453     mspace_weight.copyTo(uspace_weight);
3454     mspace_ofs.copyTo(uspace_ofs);
3455
3456     k.args(ocl::KernelArg::ReadOnlyNoSize(temp), ocl::KernelArg::WriteOnly(dst),
3457            ocl::KernelArg::PtrReadOnly(uspace_weight),
3458            ocl::KernelArg::PtrReadOnly(uspace_ofs));
3459
3460     size_t globalsize[2] = { (size_t)dst.cols / sizeDiv, (size_t)dst.rows };
3461     return k.run(2, globalsize, NULL, false);
3462 }
3463
3464 #endif
3465 static void
3466 bilateralFilter_8u( const Mat& src, Mat& dst, int d,
3467     double sigma_color, double sigma_space,
3468     int borderType )
3469 {
3470     int cn = src.channels();
3471     int i, j, maxk, radius;
3472     Size size = src.size();
3473
3474     CV_Assert( (src.type() == CV_8UC1 || src.type() == CV_8UC3) && src.data != dst.data );
3475
3476     if( sigma_color <= 0 )
3477         sigma_color = 1;
3478     if( sigma_space <= 0 )
3479         sigma_space = 1;
3480
3481     double gauss_color_coeff = -0.5/(sigma_color*sigma_color);
3482     double gauss_space_coeff = -0.5/(sigma_space*sigma_space);
3483
3484     if( d <= 0 )
3485         radius = cvRound(sigma_space*1.5);
3486     else
3487         radius = d/2;
3488     radius = MAX(radius, 1);
3489     d = radius*2 + 1;
3490
3491     Mat temp;
3492     copyMakeBorder( src, temp, radius, radius, radius, radius, borderType );
3493
3494     std::vector<float> _color_weight(cn*256);
3495     std::vector<float> _space_weight(d*d);
3496     std::vector<int> _space_ofs(d*d);
3497     float* color_weight = &_color_weight[0];
3498     float* space_weight = &_space_weight[0];
3499     int* space_ofs = &_space_ofs[0];
3500
3501     // initialize color-related bilateral filter coefficients
3502
3503     for( i = 0; i < 256*cn; i++ )
3504         color_weight[i] = (float)std::exp(i*i*gauss_color_coeff);
3505
3506     // initialize space-related bilateral filter coefficients
3507     for( i = -radius, maxk = 0; i <= radius; i++ )
3508     {
3509         j = -radius;
3510
3511         for( ; j <= radius; j++ )
3512         {
3513             double r = std::sqrt((double)i*i + (double)j*j);
3514             if( r > radius )
3515                 continue;
3516             space_weight[maxk] = (float)std::exp(r*r*gauss_space_coeff);
3517             space_ofs[maxk++] = (int)(i*temp.step + j*cn);
3518         }
3519     }
3520
3521     BilateralFilter_8u_Invoker body(dst, temp, radius, maxk, space_ofs, space_weight, color_weight);
3522     parallel_for_(Range(0, size.height), body, dst.total()/(double)(1<<16));
3523 }
3524
3525
3526 class BilateralFilter_32f_Invoker :
3527     public ParallelLoopBody
3528 {
3529 public:
3530
3531     BilateralFilter_32f_Invoker(int _cn, int _radius, int _maxk, int *_space_ofs,
3532         const Mat& _temp, Mat& _dest, float _scale_index, float *_space_weight, float *_expLUT) :
3533         cn(_cn), radius(_radius), maxk(_maxk), space_ofs(_space_ofs),
3534         temp(&_temp), dest(&_dest), scale_index(_scale_index), space_weight(_space_weight), expLUT(_expLUT)
3535     {
3536     }
3537
3538     virtual void operator() (const Range& range) const
3539     {
3540         int i, j, k;
3541         Size size = dest->size();
3542 #if CV_SIMD128
3543         int CV_DECL_ALIGNED(16) idxBuf[4];
3544         bool haveSIMD128 = hasSIMD128();
3545 #endif
3546
3547         for( i = range.start; i < range.end; i++ )
3548         {
3549             const float* sptr = temp->ptr<float>(i+radius) + radius*cn;
3550             float* dptr = dest->ptr<float>(i);
3551
3552             if( cn == 1 )
3553             {
3554                 for( j = 0; j < size.width; j++ )
3555                 {
3556                     float sum = 0, wsum = 0;
3557                     float val0 = sptr[j];
3558                     k = 0;
3559 #if CV_SIMD128
3560                     if( haveSIMD128 )
3561                     {
3562                         v_float32x4 vecwsum = v_setzero_f32();
3563                         v_float32x4 vecvsum = v_setzero_f32();
3564                         const v_float32x4 _val0 = v_setall_f32(sptr[j]);
3565                         const v_float32x4 _scale_index = v_setall_f32(scale_index);
3566
3567                         for (; k <= maxk - 4; k += 4)
3568                         {
3569                             v_float32x4 _sw = v_load(space_weight + k);
3570                             v_float32x4 _val = v_float32x4(sptr[j + space_ofs[k]],
3571                                 sptr[j + space_ofs[k + 1]],
3572                                 sptr[j + space_ofs[k + 2]],
3573                                 sptr[j + space_ofs[k + 3]]);
3574                             v_float32x4 _alpha = v_abs(_val - _val0) * _scale_index;
3575
3576                             v_int32x4 _idx = v_round(_alpha);
3577                             v_store(idxBuf, _idx);
3578                             _alpha -= v_cvt_f32(_idx);
3579
3580                             v_float32x4 _explut = v_float32x4(expLUT[idxBuf[0]],
3581                                 expLUT[idxBuf[1]],
3582                                 expLUT[idxBuf[2]],
3583                                 expLUT[idxBuf[3]]);
3584                             v_float32x4 _explut1 = v_float32x4(expLUT[idxBuf[0] + 1],
3585                                 expLUT[idxBuf[1] + 1],
3586                                 expLUT[idxBuf[2] + 1],
3587                                 expLUT[idxBuf[3] + 1]);
3588
3589                             v_float32x4 _w = _sw * (_explut + (_alpha * (_explut1 - _explut)));
3590                             _val *= _w;
3591
3592                             vecwsum += _w;
3593                             vecvsum += _val;
3594                         }
3595                         float *bufFloat = (float*)idxBuf;
3596                         v_float32x4 sum4 = v_reduce_sum4(vecwsum, vecvsum, vecwsum, vecvsum);
3597                         v_store(bufFloat, sum4);
3598                         sum += bufFloat[1];
3599                         wsum += bufFloat[0];
3600                     }
3601 #endif
3602
3603                     for( ; k < maxk; k++ )
3604                     {
3605                         float val = sptr[j + space_ofs[k]];
3606                         float alpha = (float)(std::abs(val - val0)*scale_index);
3607                         int idx = cvFloor(alpha);
3608                         alpha -= idx;
3609                         float w = space_weight[k]*(expLUT[idx] + alpha*(expLUT[idx+1] - expLUT[idx]));
3610                         sum += val*w;
3611                         wsum += w;
3612                     }
3613                     dptr[j] = (float)(sum/wsum);
3614                 }
3615             }
3616             else
3617             {
3618                 CV_Assert( cn == 3 );
3619                 for( j = 0; j < size.width*3; j += 3 )
3620                 {
3621                     float sum_b = 0, sum_g = 0, sum_r = 0, wsum = 0;
3622                     float b0 = sptr[j], g0 = sptr[j+1], r0 = sptr[j+2];
3623                     k = 0;
3624 #if CV_SIMD128
3625                     if( haveSIMD128 )
3626                     {
3627                         v_float32x4 sumw = v_setzero_f32();
3628                         v_float32x4 sumb = v_setzero_f32();
3629                         v_float32x4 sumg = v_setzero_f32();
3630                         v_float32x4 sumr = v_setzero_f32();
3631                         const v_float32x4 _b0 = v_setall_f32(b0);
3632                         const v_float32x4 _g0 = v_setall_f32(g0);
3633                         const v_float32x4 _r0 = v_setall_f32(r0);
3634                         const v_float32x4 _scale_index = v_setall_f32(scale_index);
3635
3636                         for( ; k <= maxk-4; k += 4 )
3637                         {
3638                             v_float32x4 _sw = v_load(space_weight + k);
3639
3640                             const float* const sptr_k0 = sptr + j + space_ofs[k];
3641                             const float* const sptr_k1 = sptr + j + space_ofs[k+1];
3642                             const float* const sptr_k2 = sptr + j + space_ofs[k+2];
3643                             const float* const sptr_k3 = sptr + j + space_ofs[k+3];
3644
3645                             v_float32x4 _v0 = v_load(sptr_k0);
3646                             v_float32x4 _v1 = v_load(sptr_k1);
3647                             v_float32x4 _v2 = v_load(sptr_k2);
3648                             v_float32x4 _v3 = v_load(sptr_k3);
3649                             v_float32x4 _b, _g, _r, _dummy;
3650
3651                             v_transpose4x4(_v0, _v1, _v2, _v3, _b, _g, _r, _dummy);
3652
3653                             v_float32x4 _bt = v_abs(_b - _b0);
3654                             v_float32x4 _gt = v_abs(_g - _g0);
3655                             v_float32x4 _rt = v_abs(_r - _r0);
3656                             v_float32x4 _alpha = _scale_index * (_bt + _gt + _rt);
3657
3658                             v_int32x4 _idx = v_round(_alpha);
3659                             v_store((int*)idxBuf, _idx);
3660                             _alpha -= v_cvt_f32(_idx);
3661
3662                             v_float32x4 _explut = v_float32x4(expLUT[idxBuf[0]],
3663                                 expLUT[idxBuf[1]],
3664                                 expLUT[idxBuf[2]],
3665                                 expLUT[idxBuf[3]]);
3666                             v_float32x4 _explut1 = v_float32x4(expLUT[idxBuf[0] + 1],
3667                                 expLUT[idxBuf[1] + 1],
3668                                 expLUT[idxBuf[2] + 1],
3669                                 expLUT[idxBuf[3] + 1]);
3670
3671                             v_float32x4 _w = _sw * (_explut + (_alpha * (_explut1 - _explut)));
3672
3673                             _b *=  _w;
3674                             _g *=  _w;
3675                             _r *=  _w;
3676                             sumw += _w;
3677                             sumb += _b;
3678                             sumg += _g;
3679                             sumr += _r;
3680                         }
3681                         v_float32x4 sum4 = v_reduce_sum4(sumw, sumb, sumg, sumr);
3682                         float *bufFloat = (float*)idxBuf;
3683                         v_store(bufFloat, sum4);
3684                         wsum += bufFloat[0];
3685                         sum_b += bufFloat[1];
3686                         sum_g += bufFloat[2];
3687                         sum_r += bufFloat[3];
3688                     }
3689 #endif
3690
3691                     for(; k < maxk; k++ )
3692                     {
3693                         const float* sptr_k = sptr + j + space_ofs[k];
3694                         float b = sptr_k[0], g = sptr_k[1], r = sptr_k[2];
3695                         float alpha = (float)((std::abs(b - b0) +
3696                             std::abs(g - g0) + std::abs(r - r0))*scale_index);
3697                         int idx = cvFloor(alpha);
3698                         alpha -= idx;
3699                         float w = space_weight[k]*(expLUT[idx] + alpha*(expLUT[idx+1] - expLUT[idx]));
3700                         sum_b += b*w; sum_g += g*w; sum_r += r*w;
3701                         wsum += w;
3702                     }
3703                     wsum = 1.f/wsum;
3704                     b0 = sum_b*wsum;
3705                     g0 = sum_g*wsum;
3706                     r0 = sum_r*wsum;
3707                     dptr[j] = b0; dptr[j+1] = g0; dptr[j+2] = r0;
3708                 }
3709             }
3710         }
3711     }
3712
3713 private:
3714     int cn, radius, maxk, *space_ofs;
3715     const Mat* temp;
3716     Mat *dest;
3717     float scale_index, *space_weight, *expLUT;
3718 };
3719
3720
3721 static void
3722 bilateralFilter_32f( const Mat& src, Mat& dst, int d,
3723                      double sigma_color, double sigma_space,
3724                      int borderType )
3725 {
3726     int cn = src.channels();
3727     int i, j, maxk, radius;
3728     double minValSrc=-1, maxValSrc=1;
3729     const int kExpNumBinsPerChannel = 1 << 12;
3730     int kExpNumBins = 0;
3731     float lastExpVal = 1.f;
3732     float len, scale_index;
3733     Size size = src.size();
3734
3735     CV_Assert( (src.type() == CV_32FC1 || src.type() == CV_32FC3) && src.data != dst.data );
3736
3737     if( sigma_color <= 0 )
3738         sigma_color = 1;
3739     if( sigma_space <= 0 )
3740         sigma_space = 1;
3741
3742     double gauss_color_coeff = -0.5/(sigma_color*sigma_color);
3743     double gauss_space_coeff = -0.5/(sigma_space*sigma_space);
3744
3745     if( d <= 0 )
3746         radius = cvRound(sigma_space*1.5);
3747     else
3748         radius = d/2;
3749     radius = MAX(radius, 1);
3750     d = radius*2 + 1;
3751     // compute the min/max range for the input image (even if multichannel)
3752
3753     minMaxLoc( src.reshape(1), &minValSrc, &maxValSrc );
3754     if(std::abs(minValSrc - maxValSrc) < FLT_EPSILON)
3755     {
3756         src.copyTo(dst);
3757         return;
3758     }
3759
3760     // temporary copy of the image with borders for easy processing
3761     Mat temp;
3762     copyMakeBorder( src, temp, radius, radius, radius, radius, borderType );
3763     const double insteadNaNValue = -5. * sigma_color;
3764     patchNaNs( temp, insteadNaNValue ); // this replacement of NaNs makes the assumption that depth values are nonnegative
3765                                         // TODO: make insteadNaNValue avalible in the outside function interface to control the cases breaking the assumption
3766     // allocate lookup tables
3767     std::vector<float> _space_weight(d*d);
3768     std::vector<int> _space_ofs(d*d);
3769     float* space_weight = &_space_weight[0];
3770     int* space_ofs = &_space_ofs[0];
3771
3772     // assign a length which is slightly more than needed
3773     len = (float)(maxValSrc - minValSrc) * cn;
3774     kExpNumBins = kExpNumBinsPerChannel * cn;
3775     std::vector<float> _expLUT(kExpNumBins+2);
3776     float* expLUT = &_expLUT[0];
3777
3778     scale_index = kExpNumBins/len;
3779
3780     // initialize the exp LUT
3781     for( i = 0; i < kExpNumBins+2; i++ )
3782     {
3783         if( lastExpVal > 0.f )
3784         {
3785             double val =  i / scale_index;
3786             expLUT[i] = (float)std::exp(val * val * gauss_color_coeff);
3787             lastExpVal = expLUT[i];
3788         }
3789         else
3790             expLUT[i] = 0.f;
3791     }
3792
3793     // initialize space-related bilateral filter coefficients
3794     for( i = -radius, maxk = 0; i <= radius; i++ )
3795         for( j = -radius; j <= radius; j++ )
3796         {
3797             double r = std::sqrt((double)i*i + (double)j*j);
3798             if( r > radius )
3799                 continue;
3800             space_weight[maxk] = (float)std::exp(r*r*gauss_space_coeff);
3801             space_ofs[maxk++] = (int)(i*(temp.step/sizeof(float)) + j*cn);
3802         }
3803
3804     // parallel_for usage
3805
3806     BilateralFilter_32f_Invoker body(cn, radius, maxk, space_ofs, temp, dst, scale_index, space_weight, expLUT);
3807     parallel_for_(Range(0, size.height), body, dst.total()/(double)(1<<16));
3808 }
3809
3810 #ifdef HAVE_IPP
3811 #define IPP_BILATERAL_PARALLEL 1
3812
3813 #ifdef HAVE_IPP_IW
3814 class ipp_bilateralFilterParallel: public ParallelLoopBody
3815 {
3816 public:
3817     ipp_bilateralFilterParallel(::ipp::IwiImage &_src, ::ipp::IwiImage &_dst, int _radius, Ipp32f _valSquareSigma, Ipp32f _posSquareSigma, ::ipp::IwiBorderType _borderType, bool *_ok):
3818         src(_src), dst(_dst)
3819     {
3820         pOk = _ok;
3821
3822         radius          = _radius;
3823         valSquareSigma  = _valSquareSigma;
3824         posSquareSigma  = _posSquareSigma;
3825         borderType      = _borderType;
3826
3827         *pOk = true;
3828     }
3829     ~ipp_bilateralFilterParallel() {}
3830
3831     virtual void operator() (const Range& range) const
3832     {
3833         if(*pOk == false)
3834             return;
3835
3836         try
3837         {
3838             ::ipp::IwiTile tile = ::ipp::IwiRoi(0, range.start, dst.m_size.width, range.end - range.start);
3839             CV_INSTRUMENT_FUN_IPP(::ipp::iwiFilterBilateral, src, dst, radius, valSquareSigma, posSquareSigma, ::ipp::IwDefault(), borderType, tile);
3840         }
3841         catch(::ipp::IwException)
3842         {
3843             *pOk = false;
3844             return;
3845         }
3846     }
3847 private:
3848     ::ipp::IwiImage &src;
3849     ::ipp::IwiImage &dst;
3850
3851     int                  radius;
3852     Ipp32f               valSquareSigma;
3853     Ipp32f               posSquareSigma;
3854     ::ipp::IwiBorderType borderType;
3855
3856     bool  *pOk;
3857     const ipp_bilateralFilterParallel& operator= (const ipp_bilateralFilterParallel&);
3858 };
3859 #endif
3860
3861 static bool ipp_bilateralFilter(Mat &src, Mat &dst, int d, double sigmaColor, double sigmaSpace, int borderType)
3862 {
3863 #ifdef HAVE_IPP_IW
3864     CV_INSTRUMENT_REGION_IPP()
3865
3866     int         radius         = IPP_MAX(((d <= 0)?cvRound(sigmaSpace*1.5):d/2), 1);
3867     Ipp32f      valSquareSigma = (Ipp32f)((sigmaColor <= 0)?1:sigmaColor*sigmaColor);
3868     Ipp32f      posSquareSigma = (Ipp32f)((sigmaSpace <= 0)?1:sigmaSpace*sigmaSpace);
3869
3870     // Acquire data and begin processing
3871     try
3872     {
3873         ::ipp::IwiImage      iwSrc = ippiGetImage(src);
3874         ::ipp::IwiImage      iwDst = ippiGetImage(dst);
3875         ::ipp::IwiBorderSize borderSize(radius);
3876         ::ipp::IwiBorderType ippBorder(ippiGetBorder(iwSrc, borderType, borderSize));
3877         if(!ippBorder)
3878             return false;
3879
3880         const int threads = ippiSuggestThreadsNum(iwDst, 2);
3881         if(IPP_BILATERAL_PARALLEL && threads > 1) {
3882             bool  ok      = true;
3883             Range range(0, (int)iwDst.m_size.height);
3884             ipp_bilateralFilterParallel invoker(iwSrc, iwDst, radius, valSquareSigma, posSquareSigma, ippBorder, &ok);
3885             if(!ok)
3886                 return false;
3887
3888             parallel_for_(range, invoker, threads*4);
3889
3890             if(!ok)
3891                 return false;
3892         } else {
3893             CV_INSTRUMENT_FUN_IPP(::ipp::iwiFilterBilateral, iwSrc, iwDst, radius, valSquareSigma, posSquareSigma, ::ipp::IwDefault(), ippBorder);
3894         }
3895     }
3896     catch (::ipp::IwException)
3897     {
3898         return false;
3899     }
3900     return true;
3901 #else
3902     CV_UNUSED(src); CV_UNUSED(dst); CV_UNUSED(d); CV_UNUSED(sigmaColor); CV_UNUSED(sigmaSpace); CV_UNUSED(borderType);
3903     return false;
3904 #endif
3905 }
3906 #endif
3907
3908 }
3909
3910 void cv::bilateralFilter( InputArray _src, OutputArray _dst, int d,
3911                       double sigmaColor, double sigmaSpace,
3912                       int borderType )
3913 {
3914     CV_INSTRUMENT_REGION()
3915
3916     _dst.create( _src.size(), _src.type() );
3917
3918     CV_OCL_RUN(_src.dims() <= 2 && _dst.isUMat(),
3919                ocl_bilateralFilter_8u(_src, _dst, d, sigmaColor, sigmaSpace, borderType))
3920
3921     Mat src = _src.getMat(), dst = _dst.getMat();
3922
3923     CV_IPP_RUN_FAST(ipp_bilateralFilter(src, dst, d, sigmaColor, sigmaSpace, borderType));
3924
3925     if( src.depth() == CV_8U )
3926         bilateralFilter_8u( src, dst, d, sigmaColor, sigmaSpace, borderType );
3927     else if( src.depth() == CV_32F )
3928         bilateralFilter_32f( src, dst, d, sigmaColor, sigmaSpace, borderType );
3929     else
3930         CV_Error( CV_StsUnsupportedFormat,
3931         "Bilateral filtering is only implemented for 8u and 32f images" );
3932 }
3933
3934 //////////////////////////////////////////////////////////////////////////////////////////
3935
3936 CV_IMPL void
3937 cvSmooth( const void* srcarr, void* dstarr, int smooth_type,
3938           int param1, int param2, double param3, double param4 )
3939 {
3940     cv::Mat src = cv::cvarrToMat(srcarr), dst0 = cv::cvarrToMat(dstarr), dst = dst0;
3941
3942     CV_Assert( dst.size() == src.size() &&
3943         (smooth_type == CV_BLUR_NO_SCALE || dst.type() == src.type()) );
3944
3945     if( param2 <= 0 )
3946         param2 = param1;
3947
3948     if( smooth_type == CV_BLUR || smooth_type == CV_BLUR_NO_SCALE )
3949         cv::boxFilter( src, dst, dst.depth(), cv::Size(param1, param2), cv::Point(-1,-1),
3950             smooth_type == CV_BLUR, cv::BORDER_REPLICATE );
3951     else if( smooth_type == CV_GAUSSIAN )
3952         cv::GaussianBlur( src, dst, cv::Size(param1, param2), param3, param4, cv::BORDER_REPLICATE );
3953     else if( smooth_type == CV_MEDIAN )
3954         cv::medianBlur( src, dst, param1 );
3955     else
3956         cv::bilateralFilter( src, dst, param1, param3, param4, cv::BORDER_REPLICATE );
3957
3958     if( dst.data != dst0.data )
3959         CV_Error( CV_StsUnmatchedFormats, "The destination image does not have the proper type" );
3960 }
3961
3962 /* End of file. */