Merge pull request #11295 from dkurt:dnn_repeated_conv_params
[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
46 #include <vector>
47
48 #include "opencv2/core/hal/intrin.hpp"
49 #include "opencl_kernels_imgproc.hpp"
50
51 #include "opencv2/core/openvx/ovx_defs.hpp"
52
53 #include "filter.hpp"
54
55 #include "fixedpoint.inl.hpp"
56 /*
57  * This file includes the code, contributed by Simon Perreault
58  * (the function icvMedianBlur_8u_O1)
59  *
60  * Constant-time median filtering -- http://nomis80.org/ctmf.html
61  * Copyright (C) 2006 Simon Perreault
62  *
63  * Contact:
64  *  Laboratoire de vision et systemes numeriques
65  *  Pavillon Adrien-Pouliot
66  *  Universite Laval
67  *  Sainte-Foy, Quebec, Canada
68  *  G1K 7P4
69  *
70  *  perreaul@gel.ulaval.ca
71  */
72
73 namespace cv
74 {
75
76 /****************************************************************************************\
77                                          Box Filter
78 \****************************************************************************************/
79
80 template<typename T, typename ST>
81 struct RowSum :
82         public BaseRowFilter
83 {
84     RowSum( int _ksize, int _anchor ) :
85         BaseRowFilter()
86     {
87         ksize = _ksize;
88         anchor = _anchor;
89     }
90
91     virtual void operator()(const uchar* src, uchar* dst, int width, int cn) CV_OVERRIDE
92     {
93         const T* S = (const T*)src;
94         ST* D = (ST*)dst;
95         int i = 0, k, ksz_cn = ksize*cn;
96
97         width = (width - 1)*cn;
98         if( ksize == 3 )
99         {
100             for( i = 0; i < width + cn; i++ )
101             {
102                 D[i] = (ST)S[i] + (ST)S[i+cn] + (ST)S[i+cn*2];
103             }
104         }
105         else if( ksize == 5 )
106         {
107             for( i = 0; i < width + cn; i++ )
108             {
109                 D[i] = (ST)S[i] + (ST)S[i+cn] + (ST)S[i+cn*2] + (ST)S[i + cn*3] + (ST)S[i + cn*4];
110             }
111         }
112         else if( cn == 1 )
113         {
114             ST s = 0;
115             for( i = 0; i < ksz_cn; i++ )
116                 s += (ST)S[i];
117             D[0] = s;
118             for( i = 0; i < width; i++ )
119             {
120                 s += (ST)S[i + ksz_cn] - (ST)S[i];
121                 D[i+1] = s;
122             }
123         }
124         else if( cn == 3 )
125         {
126             ST s0 = 0, s1 = 0, s2 = 0;
127             for( i = 0; i < ksz_cn; i += 3 )
128             {
129                 s0 += (ST)S[i];
130                 s1 += (ST)S[i+1];
131                 s2 += (ST)S[i+2];
132             }
133             D[0] = s0;
134             D[1] = s1;
135             D[2] = s2;
136             for( i = 0; i < width; i += 3 )
137             {
138                 s0 += (ST)S[i + ksz_cn] - (ST)S[i];
139                 s1 += (ST)S[i + ksz_cn + 1] - (ST)S[i + 1];
140                 s2 += (ST)S[i + ksz_cn + 2] - (ST)S[i + 2];
141                 D[i+3] = s0;
142                 D[i+4] = s1;
143                 D[i+5] = s2;
144             }
145         }
146         else if( cn == 4 )
147         {
148             ST s0 = 0, s1 = 0, s2 = 0, s3 = 0;
149             for( i = 0; i < ksz_cn; i += 4 )
150             {
151                 s0 += (ST)S[i];
152                 s1 += (ST)S[i+1];
153                 s2 += (ST)S[i+2];
154                 s3 += (ST)S[i+3];
155             }
156             D[0] = s0;
157             D[1] = s1;
158             D[2] = s2;
159             D[3] = s3;
160             for( i = 0; i < width; i += 4 )
161             {
162                 s0 += (ST)S[i + ksz_cn] - (ST)S[i];
163                 s1 += (ST)S[i + ksz_cn + 1] - (ST)S[i + 1];
164                 s2 += (ST)S[i + ksz_cn + 2] - (ST)S[i + 2];
165                 s3 += (ST)S[i + ksz_cn + 3] - (ST)S[i + 3];
166                 D[i+4] = s0;
167                 D[i+5] = s1;
168                 D[i+6] = s2;
169                 D[i+7] = s3;
170             }
171         }
172         else
173             for( k = 0; k < cn; k++, S++, D++ )
174             {
175                 ST s = 0;
176                 for( i = 0; i < ksz_cn; i += cn )
177                     s += (ST)S[i];
178                 D[0] = s;
179                 for( i = 0; i < width; i += cn )
180                 {
181                     s += (ST)S[i + ksz_cn] - (ST)S[i];
182                     D[i+cn] = s;
183                 }
184             }
185     }
186 };
187
188
189 template<typename ST, typename T>
190 struct ColumnSum :
191         public BaseColumnFilter
192 {
193     ColumnSum( int _ksize, int _anchor, double _scale ) :
194         BaseColumnFilter()
195     {
196         ksize = _ksize;
197         anchor = _anchor;
198         scale = _scale;
199         sumCount = 0;
200     }
201
202     virtual void reset() CV_OVERRIDE { sumCount = 0; }
203
204     virtual void operator()(const uchar** src, uchar* dst, int dststep, int count, int width) CV_OVERRIDE
205     {
206         int i;
207         ST* SUM;
208         bool haveScale = scale != 1;
209         double _scale = scale;
210
211         if( width != (int)sum.size() )
212         {
213             sum.resize(width);
214             sumCount = 0;
215         }
216
217         SUM = &sum[0];
218         if( sumCount == 0 )
219         {
220             memset((void*)SUM, 0, width*sizeof(ST));
221
222             for( ; sumCount < ksize - 1; sumCount++, src++ )
223             {
224                 const ST* Sp = (const ST*)src[0];
225
226                 for( i = 0; i < width; i++ )
227                     SUM[i] += Sp[i];
228             }
229         }
230         else
231         {
232             CV_Assert( sumCount == ksize-1 );
233             src += ksize-1;
234         }
235
236         for( ; count--; src++ )
237         {
238             const ST* Sp = (const ST*)src[0];
239             const ST* Sm = (const ST*)src[1-ksize];
240             T* D = (T*)dst;
241             if( haveScale )
242             {
243                 for( i = 0; i <= width - 2; i += 2 )
244                 {
245                     ST s0 = SUM[i] + Sp[i], s1 = SUM[i+1] + Sp[i+1];
246                     D[i] = saturate_cast<T>(s0*_scale);
247                     D[i+1] = saturate_cast<T>(s1*_scale);
248                     s0 -= Sm[i]; s1 -= Sm[i+1];
249                     SUM[i] = s0; SUM[i+1] = s1;
250                 }
251
252                 for( ; i < width; i++ )
253                 {
254                     ST s0 = SUM[i] + Sp[i];
255                     D[i] = saturate_cast<T>(s0*_scale);
256                     SUM[i] = s0 - Sm[i];
257                 }
258             }
259             else
260             {
261                 for( i = 0; i <= width - 2; i += 2 )
262                 {
263                     ST s0 = SUM[i] + Sp[i], s1 = SUM[i+1] + Sp[i+1];
264                     D[i] = saturate_cast<T>(s0);
265                     D[i+1] = saturate_cast<T>(s1);
266                     s0 -= Sm[i]; s1 -= Sm[i+1];
267                     SUM[i] = s0; SUM[i+1] = s1;
268                 }
269
270                 for( ; i < width; i++ )
271                 {
272                     ST s0 = SUM[i] + Sp[i];
273                     D[i] = saturate_cast<T>(s0);
274                     SUM[i] = s0 - Sm[i];
275                 }
276             }
277             dst += dststep;
278         }
279     }
280
281     double scale;
282     int sumCount;
283     std::vector<ST> sum;
284 };
285
286
287 template<>
288 struct ColumnSum<int, uchar> :
289         public BaseColumnFilter
290 {
291     ColumnSum( int _ksize, int _anchor, double _scale ) :
292         BaseColumnFilter()
293     {
294         ksize = _ksize;
295         anchor = _anchor;
296         scale = _scale;
297         sumCount = 0;
298     }
299
300     virtual void reset() CV_OVERRIDE { sumCount = 0; }
301
302     virtual void operator()(const uchar** src, uchar* dst, int dststep, int count, int width) CV_OVERRIDE
303     {
304         int* SUM;
305         bool haveScale = scale != 1;
306         double _scale = scale;
307
308 #if CV_SIMD128
309         bool haveSIMD128 = hasSIMD128();
310 #endif
311
312         if( width != (int)sum.size() )
313         {
314             sum.resize(width);
315             sumCount = 0;
316         }
317
318         SUM = &sum[0];
319         if( sumCount == 0 )
320         {
321             memset((void*)SUM, 0, width*sizeof(int));
322             for( ; sumCount < ksize - 1; sumCount++, src++ )
323             {
324                 const int* Sp = (const int*)src[0];
325                 int i = 0;
326 #if CV_SIMD128
327                 if( haveSIMD128 )
328                 {
329                     for (; i <= width - 4; i += 4)
330                     {
331                         v_store(SUM + i, v_load(SUM + i) + v_load(Sp + i));
332                     }
333                 }
334 #endif
335                 for( ; i < width; i++ )
336                     SUM[i] += Sp[i];
337             }
338         }
339         else
340         {
341             CV_Assert( sumCount == ksize-1 );
342             src += ksize-1;
343         }
344
345         for( ; count--; src++ )
346         {
347             const int* Sp = (const int*)src[0];
348             const int* Sm = (const int*)src[1-ksize];
349             uchar* D = (uchar*)dst;
350             if( haveScale )
351             {
352                 int i = 0;
353 #if CV_SIMD128
354                 if( haveSIMD128 )
355                 {
356
357                     v_float32x4 v_scale = v_setall_f32((float)_scale);
358                     for( ; i <= width-8; i+=8 )
359                     {
360                         v_int32x4 v_s0 = v_load(SUM + i) + v_load(Sp + i);
361                         v_int32x4 v_s01 = v_load(SUM + i + 4) + v_load(Sp + i + 4);
362
363                         v_uint32x4 v_s0d = v_reinterpret_as_u32(v_round(v_cvt_f32(v_s0) * v_scale));
364                         v_uint32x4 v_s01d = v_reinterpret_as_u32(v_round(v_cvt_f32(v_s01) * v_scale));
365
366                         v_uint16x8 v_dst = v_pack(v_s0d, v_s01d);
367                         v_pack_store(D + i, v_dst);
368
369                         v_store(SUM + i, v_s0 - v_load(Sm + i));
370                         v_store(SUM + i + 4, v_s01 - v_load(Sm + i + 4));
371                     }
372                 }
373 #endif
374                 for( ; i < width; i++ )
375                 {
376                     int s0 = SUM[i] + Sp[i];
377                     D[i] = saturate_cast<uchar>(s0*_scale);
378                     SUM[i] = s0 - Sm[i];
379                 }
380             }
381             else
382             {
383                 int i = 0;
384 #if CV_SIMD128
385                 if( haveSIMD128 )
386                 {
387                     for( ; i <= width-8; i+=8 )
388                     {
389                         v_int32x4 v_s0 = v_load(SUM + i) + v_load(Sp + i);
390                         v_int32x4 v_s01 = v_load(SUM + i + 4) + v_load(Sp + i + 4);
391
392                         v_uint16x8 v_dst = v_pack(v_reinterpret_as_u32(v_s0), v_reinterpret_as_u32(v_s01));
393                         v_pack_store(D + i, v_dst);
394
395                         v_store(SUM + i, v_s0 - v_load(Sm + i));
396                         v_store(SUM + i + 4, v_s01 - v_load(Sm + i + 4));
397                     }
398                 }
399 #endif
400
401                 for( ; i < width; i++ )
402                 {
403                     int s0 = SUM[i] + Sp[i];
404                     D[i] = saturate_cast<uchar>(s0);
405                     SUM[i] = s0 - Sm[i];
406                 }
407             }
408             dst += dststep;
409         }
410     }
411
412     double scale;
413     int sumCount;
414     std::vector<int> sum;
415 };
416
417
418 template<>
419 struct ColumnSum<ushort, uchar> :
420 public BaseColumnFilter
421 {
422     enum { SHIFT = 23 };
423
424     ColumnSum( int _ksize, int _anchor, double _scale ) :
425     BaseColumnFilter()
426     {
427         ksize = _ksize;
428         anchor = _anchor;
429         scale = _scale;
430         sumCount = 0;
431         divDelta = 0;
432         divScale = 1;
433         if( scale != 1 )
434         {
435             int d = cvRound(1./scale);
436             double scalef = ((double)(1 << SHIFT))/d;
437             divScale = cvFloor(scalef);
438             scalef -= divScale;
439             divDelta = d/2;
440             if( scalef < 0.5 )
441                 divDelta++;
442             else
443                 divScale++;
444         }
445     }
446
447     virtual void reset() CV_OVERRIDE { sumCount = 0; }
448
449     virtual void operator()(const uchar** src, uchar* dst, int dststep, int count, int width) CV_OVERRIDE
450     {
451         const int ds = divScale;
452         const int dd = divDelta;
453         ushort* SUM;
454         const bool haveScale = scale != 1;
455
456 #if CV_SIMD128
457         bool haveSIMD128 = hasSIMD128();
458 #endif
459
460         if( width != (int)sum.size() )
461         {
462             sum.resize(width);
463             sumCount = 0;
464         }
465
466         SUM = &sum[0];
467         if( sumCount == 0 )
468         {
469             memset((void*)SUM, 0, width*sizeof(SUM[0]));
470             for( ; sumCount < ksize - 1; sumCount++, src++ )
471             {
472                 const ushort* Sp = (const ushort*)src[0];
473                 int i = 0;
474 #if CV_SIMD128
475                 if( haveSIMD128 )
476                 {
477                     for( ; i <= width - 8; i += 8 )
478                     {
479                         v_store(SUM + i, v_load(SUM + i) + v_load(Sp + i));
480                     }
481                 }
482 #endif
483                 for( ; i < width; i++ )
484                     SUM[i] += Sp[i];
485             }
486         }
487         else
488         {
489             CV_Assert( sumCount == ksize-1 );
490             src += ksize-1;
491         }
492
493         for( ; count--; src++ )
494         {
495             const ushort* Sp = (const ushort*)src[0];
496             const ushort* Sm = (const ushort*)src[1-ksize];
497             uchar* D = (uchar*)dst;
498             if( haveScale )
499             {
500                 int i = 0;
501             #if CV_SIMD128
502                 v_uint32x4 ds4 = v_setall_u32((unsigned)ds);
503                 v_uint16x8 dd8 = v_setall_u16((ushort)dd);
504
505                 for( ; i <= width-16; i+=16 )
506                 {
507                     v_uint16x8 _sm0 = v_load(Sm + i);
508                     v_uint16x8 _sm1 = v_load(Sm + i + 8);
509
510                     v_uint16x8 _s0 = v_add_wrap(v_load(SUM + i), v_load(Sp + i));
511                     v_uint16x8 _s1 = v_add_wrap(v_load(SUM + i + 8), v_load(Sp + i + 8));
512
513                     v_uint32x4 _s00, _s01, _s10, _s11;
514
515                     v_expand(_s0 + dd8, _s00, _s01);
516                     v_expand(_s1 + dd8, _s10, _s11);
517
518                     _s00 = v_shr<SHIFT>(_s00*ds4);
519                     _s01 = v_shr<SHIFT>(_s01*ds4);
520                     _s10 = v_shr<SHIFT>(_s10*ds4);
521                     _s11 = v_shr<SHIFT>(_s11*ds4);
522
523                     v_int16x8 r0 = v_pack(v_reinterpret_as_s32(_s00), v_reinterpret_as_s32(_s01));
524                     v_int16x8 r1 = v_pack(v_reinterpret_as_s32(_s10), v_reinterpret_as_s32(_s11));
525
526                     _s0 = v_sub_wrap(_s0, _sm0);
527                     _s1 = v_sub_wrap(_s1, _sm1);
528
529                     v_store(D + i, v_pack_u(r0, r1));
530                     v_store(SUM + i, _s0);
531                     v_store(SUM + i + 8, _s1);
532                 }
533             #endif
534                 for( ; i < width; i++ )
535                 {
536                     int s0 = SUM[i] + Sp[i];
537                     D[i] = (uchar)((s0 + dd)*ds >> SHIFT);
538                     SUM[i] = (ushort)(s0 - Sm[i]);
539                 }
540             }
541             else
542             {
543                 int i = 0;
544                 for( ; i < width; i++ )
545                 {
546                     int s0 = SUM[i] + Sp[i];
547                     D[i] = saturate_cast<uchar>(s0);
548                     SUM[i] = (ushort)(s0 - Sm[i]);
549                 }
550             }
551             dst += dststep;
552         }
553     }
554
555     double scale;
556     int sumCount;
557     int divDelta;
558     int divScale;
559     std::vector<ushort> sum;
560 };
561
562
563 template<>
564 struct ColumnSum<int, short> :
565         public BaseColumnFilter
566 {
567     ColumnSum( int _ksize, int _anchor, double _scale ) :
568         BaseColumnFilter()
569     {
570         ksize = _ksize;
571         anchor = _anchor;
572         scale = _scale;
573         sumCount = 0;
574     }
575
576     virtual void reset() CV_OVERRIDE { sumCount = 0; }
577
578     virtual void operator()(const uchar** src, uchar* dst, int dststep, int count, int width) CV_OVERRIDE
579     {
580         int i;
581         int* SUM;
582         bool haveScale = scale != 1;
583         double _scale = scale;
584
585 #if CV_SIMD128
586         bool haveSIMD128 = hasSIMD128();
587 #endif
588
589         if( width != (int)sum.size() )
590         {
591             sum.resize(width);
592             sumCount = 0;
593         }
594
595         SUM = &sum[0];
596         if( sumCount == 0 )
597         {
598             memset((void*)SUM, 0, width*sizeof(int));
599             for( ; sumCount < ksize - 1; sumCount++, src++ )
600             {
601                 const int* Sp = (const int*)src[0];
602                 i = 0;
603 #if CV_SIMD128
604                 if( haveSIMD128 )
605                 {
606                     for( ; i <= width - 4; i+=4 )
607                     {
608                         v_store(SUM + i, v_load(SUM + i) + v_load(Sp + i));
609                     }
610                 }
611                 #endif
612                 for( ; i < width; i++ )
613                     SUM[i] += Sp[i];
614             }
615         }
616         else
617         {
618             CV_Assert( sumCount == ksize-1 );
619             src += ksize-1;
620         }
621
622         for( ; count--; src++ )
623         {
624             const int* Sp = (const int*)src[0];
625             const int* Sm = (const int*)src[1-ksize];
626             short* D = (short*)dst;
627             if( haveScale )
628             {
629                 i = 0;
630 #if CV_SIMD128
631                 if( haveSIMD128 )
632                 {
633                     v_float32x4 v_scale = v_setall_f32((float)_scale);
634                     for( ; i <= width-8; i+=8 )
635                     {
636                         v_int32x4 v_s0 = v_load(SUM + i) + v_load(Sp + i);
637                         v_int32x4 v_s01 = v_load(SUM + i + 4) + v_load(Sp + i + 4);
638
639                         v_int32x4 v_s0d =  v_round(v_cvt_f32(v_s0) * v_scale);
640                         v_int32x4 v_s01d = v_round(v_cvt_f32(v_s01) * v_scale);
641                         v_store(D + i, v_pack(v_s0d, v_s01d));
642
643                         v_store(SUM + i, v_s0 - v_load(Sm + i));
644                         v_store(SUM + i + 4, v_s01 - v_load(Sm + i + 4));
645                     }
646                 }
647 #endif
648                 for( ; i < width; i++ )
649                 {
650                     int s0 = SUM[i] + Sp[i];
651                     D[i] = saturate_cast<short>(s0*_scale);
652                     SUM[i] = s0 - Sm[i];
653                 }
654             }
655             else
656             {
657                 i = 0;
658 #if CV_SIMD128
659                 if( haveSIMD128 )
660                 {
661                     for( ; i <= width-8; i+=8 )
662                     {
663                         v_int32x4 v_s0 = v_load(SUM + i) + v_load(Sp + i);
664                         v_int32x4 v_s01 = v_load(SUM + i + 4) + v_load(Sp + i + 4);
665
666                         v_store(D + i, v_pack(v_s0, v_s01));
667
668                         v_store(SUM + i, v_s0 - v_load(Sm + i));
669                         v_store(SUM + i + 4, v_s01 - v_load(Sm + i + 4));
670                     }
671                 }
672 #endif
673
674                 for( ; i < width; i++ )
675                 {
676                     int s0 = SUM[i] + Sp[i];
677                     D[i] = saturate_cast<short>(s0);
678                     SUM[i] = s0 - Sm[i];
679                 }
680             }
681             dst += dststep;
682         }
683     }
684
685     double scale;
686     int sumCount;
687     std::vector<int> sum;
688 };
689
690
691 template<>
692 struct ColumnSum<int, ushort> :
693         public BaseColumnFilter
694 {
695     ColumnSum( int _ksize, int _anchor, double _scale ) :
696         BaseColumnFilter()
697     {
698         ksize = _ksize;
699         anchor = _anchor;
700         scale = _scale;
701         sumCount = 0;
702     }
703
704     virtual void reset() CV_OVERRIDE { sumCount = 0; }
705
706     virtual void operator()(const uchar** src, uchar* dst, int dststep, int count, int width) CV_OVERRIDE
707     {
708         int* SUM;
709         bool haveScale = scale != 1;
710         double _scale = scale;
711
712 #if CV_SIMD128
713         bool haveSIMD128 = hasSIMD128();
714 #endif
715
716         if( width != (int)sum.size() )
717         {
718             sum.resize(width);
719             sumCount = 0;
720         }
721
722         SUM = &sum[0];
723         if( sumCount == 0 )
724         {
725             memset((void*)SUM, 0, width*sizeof(int));
726             for( ; sumCount < ksize - 1; sumCount++, src++ )
727             {
728                 const int* Sp = (const int*)src[0];
729                 int i = 0;
730 #if CV_SIMD128
731                 if( haveSIMD128 )
732                 {
733                     for (; i <= width - 4; i += 4)
734                     {
735                         v_store(SUM + i, v_load(SUM + i) + v_load(Sp + i));
736                     }
737                 }
738 #endif
739                 for( ; i < width; i++ )
740                     SUM[i] += Sp[i];
741             }
742         }
743         else
744         {
745             CV_Assert( sumCount == ksize-1 );
746             src += ksize-1;
747         }
748
749         for( ; count--; src++ )
750         {
751             const int* Sp = (const int*)src[0];
752             const int* Sm = (const int*)src[1-ksize];
753             ushort* D = (ushort*)dst;
754             if( haveScale )
755             {
756                 int i = 0;
757 #if CV_SIMD128
758                 if( haveSIMD128 )
759                 {
760                     v_float32x4 v_scale = v_setall_f32((float)_scale);
761                     for( ; i <= width-8; i+=8 )
762                     {
763                         v_int32x4 v_s0 = v_load(SUM + i) + v_load(Sp + i);
764                         v_int32x4 v_s01 = v_load(SUM + i + 4) + v_load(Sp + i + 4);
765
766                         v_uint32x4 v_s0d = v_reinterpret_as_u32(v_round(v_cvt_f32(v_s0) * v_scale));
767                         v_uint32x4 v_s01d = v_reinterpret_as_u32(v_round(v_cvt_f32(v_s01) * v_scale));
768                         v_store(D + i, v_pack(v_s0d, v_s01d));
769
770                         v_store(SUM + i, v_s0 - v_load(Sm + i));
771                         v_store(SUM + i + 4, v_s01 - v_load(Sm + i + 4));
772                     }
773                 }
774 #endif
775                 for( ; i < width; i++ )
776                 {
777                     int s0 = SUM[i] + Sp[i];
778                     D[i] = saturate_cast<ushort>(s0*_scale);
779                     SUM[i] = s0 - Sm[i];
780                 }
781             }
782             else
783             {
784                 int i = 0;
785 #if CV_SIMD128
786                 if( haveSIMD128 )
787                 {
788                     for( ; i <= width-8; i+=8 )
789                     {
790                         v_int32x4 v_s0 = v_load(SUM + i) + v_load(Sp + i);
791                         v_int32x4 v_s01 = v_load(SUM + i + 4) + v_load(Sp + i + 4);
792
793                         v_store(D + i, v_pack(v_reinterpret_as_u32(v_s0), v_reinterpret_as_u32(v_s01)));
794
795                         v_store(SUM + i, v_s0 - v_load(Sm + i));
796                         v_store(SUM + i + 4, v_s01 - v_load(Sm + i + 4));
797                     }
798                 }
799 #endif
800                 for( ; i < width; i++ )
801                 {
802                     int s0 = SUM[i] + Sp[i];
803                     D[i] = saturate_cast<ushort>(s0);
804                     SUM[i] = s0 - Sm[i];
805                 }
806             }
807             dst += dststep;
808         }
809     }
810
811     double scale;
812     int sumCount;
813     std::vector<int> sum;
814 };
815
816 template<>
817 struct ColumnSum<int, int> :
818         public BaseColumnFilter
819 {
820     ColumnSum( int _ksize, int _anchor, double _scale ) :
821         BaseColumnFilter()
822     {
823         ksize = _ksize;
824         anchor = _anchor;
825         scale = _scale;
826         sumCount = 0;
827     }
828
829     virtual void reset() CV_OVERRIDE { sumCount = 0; }
830
831     virtual void operator()(const uchar** src, uchar* dst, int dststep, int count, int width) CV_OVERRIDE
832     {
833         int* SUM;
834         bool haveScale = scale != 1;
835         double _scale = scale;
836
837 #if CV_SIMD128
838         bool haveSIMD128 = hasSIMD128();
839 #endif
840
841         if( width != (int)sum.size() )
842         {
843             sum.resize(width);
844             sumCount = 0;
845         }
846
847         SUM = &sum[0];
848         if( sumCount == 0 )
849         {
850             memset((void*)SUM, 0, width*sizeof(int));
851             for( ; sumCount < ksize - 1; sumCount++, src++ )
852             {
853                 const int* Sp = (const int*)src[0];
854                 int i = 0;
855 #if CV_SIMD128
856                 if( haveSIMD128 )
857                 {
858                     for( ; i <= width - 4; i+=4 )
859                     {
860                         v_store(SUM + i, v_load(SUM + i) + v_load(Sp + i));
861                     }
862                 }
863 #endif
864                 for( ; i < width; i++ )
865                     SUM[i] += Sp[i];
866             }
867         }
868         else
869         {
870             CV_Assert( sumCount == ksize-1 );
871             src += ksize-1;
872         }
873
874         for( ; count--; src++ )
875         {
876             const int* Sp = (const int*)src[0];
877             const int* Sm = (const int*)src[1-ksize];
878             int* D = (int*)dst;
879             if( haveScale )
880             {
881                 int i = 0;
882 #if CV_SIMD128
883                 if( haveSIMD128 )
884                 {
885                     v_float32x4 v_scale = v_setall_f32((float)_scale);
886                     for( ; i <= width-4; i+=4 )
887                     {
888                         v_int32x4 v_s0 = v_load(SUM + i) + v_load(Sp + i);
889                         v_int32x4 v_s0d = v_round(v_cvt_f32(v_s0) * v_scale);
890
891                         v_store(D + i, v_s0d);
892                         v_store(SUM + i, v_s0 - v_load(Sm + i));
893                     }
894                 }
895 #endif
896                 for( ; i < width; i++ )
897                 {
898                     int s0 = SUM[i] + Sp[i];
899                     D[i] = saturate_cast<int>(s0*_scale);
900                     SUM[i] = s0 - Sm[i];
901                 }
902             }
903             else
904             {
905                 int i = 0;
906 #if CV_SIMD128
907                 if( haveSIMD128 )
908                 {
909                     for( ; i <= width-4; i+=4 )
910                     {
911                         v_int32x4 v_s0 = v_load(SUM + i) + v_load(Sp + i);
912
913                         v_store(D + i, v_s0);
914                         v_store(SUM + i, v_s0 - v_load(Sm + i));
915                     }
916                 }
917 #endif
918                 for( ; i < width; i++ )
919                 {
920                     int s0 = SUM[i] + Sp[i];
921                     D[i] = s0;
922                     SUM[i] = s0 - Sm[i];
923                 }
924             }
925             dst += dststep;
926         }
927     }
928
929     double scale;
930     int sumCount;
931     std::vector<int> sum;
932 };
933
934
935 template<>
936 struct ColumnSum<int, float> :
937         public BaseColumnFilter
938 {
939     ColumnSum( int _ksize, int _anchor, double _scale ) :
940         BaseColumnFilter()
941     {
942         ksize = _ksize;
943         anchor = _anchor;
944         scale = _scale;
945         sumCount = 0;
946     }
947
948     virtual void reset() CV_OVERRIDE { sumCount = 0; }
949
950     virtual void operator()(const uchar** src, uchar* dst, int dststep, int count, int width) CV_OVERRIDE
951     {
952         int* SUM;
953         bool haveScale = scale != 1;
954         double _scale = scale;
955
956 #if CV_SIMD128
957         bool haveSIMD128 = hasSIMD128();
958 #endif
959
960         if( width != (int)sum.size() )
961         {
962             sum.resize(width);
963             sumCount = 0;
964         }
965
966         SUM = &sum[0];
967         if( sumCount == 0 )
968         {
969             memset((void*)SUM, 0, width*sizeof(int));
970             for( ; sumCount < ksize - 1; sumCount++, src++ )
971             {
972                 const int* Sp = (const int*)src[0];
973                 int i = 0;
974 #if CV_SIMD128
975                 if( haveSIMD128 )
976                 {
977                     for( ; i <= width - 4; i+=4 )
978                     {
979                         v_store(SUM + i, v_load(SUM + i) + v_load(Sp + i));
980                     }
981                 }
982 #endif
983
984                 for( ; i < width; i++ )
985                     SUM[i] += Sp[i];
986             }
987         }
988         else
989         {
990             CV_Assert( sumCount == ksize-1 );
991             src += ksize-1;
992         }
993
994         for( ; count--; src++ )
995         {
996             const int * Sp = (const int*)src[0];
997             const int * Sm = (const int*)src[1-ksize];
998             float* D = (float*)dst;
999             if( haveScale )
1000             {
1001                 int i = 0;
1002
1003 #if CV_SIMD128
1004                 if( haveSIMD128 )
1005                 {
1006                     v_float32x4 v_scale = v_setall_f32((float)_scale);
1007                     for (; i <= width - 8; i += 8)
1008                     {
1009                         v_int32x4 v_s0 = v_load(SUM + i) + v_load(Sp + i);
1010                         v_int32x4 v_s01 = v_load(SUM + i + 4) + v_load(Sp + i + 4);
1011
1012                         v_store(D + i, v_cvt_f32(v_s0) * v_scale);
1013                         v_store(D + i + 4, v_cvt_f32(v_s01) * v_scale);
1014
1015                         v_store(SUM + i, v_s0 - v_load(Sm + i));
1016                         v_store(SUM + i + 4, v_s01 - v_load(Sm + i + 4));
1017                     }
1018                 }
1019 #endif
1020                 for( ; i < width; i++ )
1021                 {
1022                     int s0 = SUM[i] + Sp[i];
1023                     D[i] = (float)(s0*_scale);
1024                     SUM[i] = s0 - Sm[i];
1025                 }
1026             }
1027             else
1028             {
1029                 int i = 0;
1030
1031 #if CV_SIMD128
1032                 if( haveSIMD128 )
1033                 {
1034                     for( ; i <= width-8; i+=8 )
1035                     {
1036                         v_int32x4 v_s0 = v_load(SUM + i) + v_load(Sp + i);
1037                         v_int32x4 v_s01 = v_load(SUM + i + 4) + v_load(Sp + i + 4);
1038
1039                         v_store(D + i, v_cvt_f32(v_s0));
1040                         v_store(D + i + 4, v_cvt_f32(v_s01));
1041
1042                         v_store(SUM + i, v_s0 - v_load(Sm + i));
1043                         v_store(SUM + i + 4, v_s01 - v_load(Sm + i + 4));
1044                     }
1045                 }
1046 #endif
1047                 for( ; i < width; i++ )
1048                 {
1049                     int s0 = SUM[i] + Sp[i];
1050                     D[i] = (float)(s0);
1051                     SUM[i] = s0 - Sm[i];
1052                 }
1053             }
1054             dst += dststep;
1055         }
1056     }
1057
1058     double scale;
1059     int sumCount;
1060     std::vector<int> sum;
1061 };
1062
1063 #ifdef HAVE_OPENCL
1064
1065 static bool ocl_boxFilter3x3_8UC1( InputArray _src, OutputArray _dst, int ddepth,
1066                                    Size ksize, Point anchor, int borderType, bool normalize )
1067 {
1068     const ocl::Device & dev = ocl::Device::getDefault();
1069     int type = _src.type(), sdepth = CV_MAT_DEPTH(type), cn = CV_MAT_CN(type);
1070
1071     if (ddepth < 0)
1072         ddepth = sdepth;
1073
1074     if (anchor.x < 0)
1075         anchor.x = ksize.width / 2;
1076     if (anchor.y < 0)
1077         anchor.y = ksize.height / 2;
1078
1079     if ( !(dev.isIntel() && (type == CV_8UC1) &&
1080          (_src.offset() == 0) && (_src.step() % 4 == 0) &&
1081          (_src.cols() % 16 == 0) && (_src.rows() % 2 == 0) &&
1082          (anchor.x == 1) && (anchor.y == 1) &&
1083          (ksize.width == 3) && (ksize.height == 3)) )
1084         return false;
1085
1086     float alpha = 1.0f / (ksize.height * ksize.width);
1087     Size size = _src.size();
1088     size_t globalsize[2] = { 0, 0 };
1089     size_t localsize[2] = { 0, 0 };
1090     const char * const borderMap[] = { "BORDER_CONSTANT", "BORDER_REPLICATE", "BORDER_REFLECT", 0, "BORDER_REFLECT_101" };
1091
1092     globalsize[0] = size.width / 16;
1093     globalsize[1] = size.height / 2;
1094
1095     char build_opts[1024];
1096     sprintf(build_opts, "-D %s %s", borderMap[borderType], normalize ? "-D NORMALIZE" : "");
1097
1098     ocl::Kernel kernel("boxFilter3x3_8UC1_cols16_rows2", cv::ocl::imgproc::boxFilter3x3_oclsrc, build_opts);
1099     if (kernel.empty())
1100         return false;
1101
1102     UMat src = _src.getUMat();
1103     _dst.create(size, CV_MAKETYPE(ddepth, cn));
1104     if (!(_dst.offset() == 0 && _dst.step() % 4 == 0))
1105         return false;
1106     UMat dst = _dst.getUMat();
1107
1108     int idxArg = kernel.set(0, ocl::KernelArg::PtrReadOnly(src));
1109     idxArg = kernel.set(idxArg, (int)src.step);
1110     idxArg = kernel.set(idxArg, ocl::KernelArg::PtrWriteOnly(dst));
1111     idxArg = kernel.set(idxArg, (int)dst.step);
1112     idxArg = kernel.set(idxArg, (int)dst.rows);
1113     idxArg = kernel.set(idxArg, (int)dst.cols);
1114     if (normalize)
1115         idxArg = kernel.set(idxArg, (float)alpha);
1116
1117     return kernel.run(2, globalsize, (localsize[0] == 0) ? NULL : localsize, false);
1118 }
1119
1120 #define DIVUP(total, grain) ((total + grain - 1) / (grain))
1121 #define ROUNDUP(sz, n)      ((sz) + (n) - 1 - (((sz) + (n) - 1) % (n)))
1122
1123 static bool ocl_boxFilter( InputArray _src, OutputArray _dst, int ddepth,
1124                            Size ksize, Point anchor, int borderType, bool normalize, bool sqr = false )
1125 {
1126     const ocl::Device & dev = ocl::Device::getDefault();
1127     int type = _src.type(), sdepth = CV_MAT_DEPTH(type), cn = CV_MAT_CN(type), esz = CV_ELEM_SIZE(type);
1128     bool doubleSupport = dev.doubleFPConfig() > 0;
1129
1130     if (ddepth < 0)
1131         ddepth = sdepth;
1132
1133     if (cn > 4 || (!doubleSupport && (sdepth == CV_64F || ddepth == CV_64F)) ||
1134         _src.offset() % esz != 0 || _src.step() % esz != 0)
1135         return false;
1136
1137     if (anchor.x < 0)
1138         anchor.x = ksize.width / 2;
1139     if (anchor.y < 0)
1140         anchor.y = ksize.height / 2;
1141
1142     int computeUnits = ocl::Device::getDefault().maxComputeUnits();
1143     float alpha = 1.0f / (ksize.height * ksize.width);
1144     Size size = _src.size(), wholeSize;
1145     bool isolated = (borderType & BORDER_ISOLATED) != 0;
1146     borderType &= ~BORDER_ISOLATED;
1147     int wdepth = std::max(CV_32F, std::max(ddepth, sdepth)),
1148         wtype = CV_MAKE_TYPE(wdepth, cn), dtype = CV_MAKE_TYPE(ddepth, cn);
1149
1150     const char * const borderMap[] = { "BORDER_CONSTANT", "BORDER_REPLICATE", "BORDER_REFLECT", 0, "BORDER_REFLECT_101" };
1151     size_t globalsize[2] = { (size_t)size.width, (size_t)size.height };
1152     size_t localsize_general[2] = { 0, 1 }, * localsize = NULL;
1153
1154     UMat src = _src.getUMat();
1155     if (!isolated)
1156     {
1157         Point ofs;
1158         src.locateROI(wholeSize, ofs);
1159     }
1160
1161     int h = isolated ? size.height : wholeSize.height;
1162     int w = isolated ? size.width : wholeSize.width;
1163
1164     size_t maxWorkItemSizes[32];
1165     ocl::Device::getDefault().maxWorkItemSizes(maxWorkItemSizes);
1166     int tryWorkItems = (int)maxWorkItemSizes[0];
1167
1168     ocl::Kernel kernel;
1169
1170     if (dev.isIntel() && !(dev.type() & ocl::Device::TYPE_CPU) &&
1171         ((ksize.width < 5 && ksize.height < 5 && esz <= 4) ||
1172          (ksize.width == 5 && ksize.height == 5 && cn == 1)))
1173     {
1174         if (w < ksize.width || h < ksize.height)
1175             return false;
1176
1177         // Figure out what vector size to use for loading the pixels.
1178         int pxLoadNumPixels = cn != 1 || size.width % 4 ? 1 : 4;
1179         int pxLoadVecSize = cn * pxLoadNumPixels;
1180
1181         // Figure out how many pixels per work item to compute in X and Y
1182         // directions.  Too many and we run out of registers.
1183         int pxPerWorkItemX = 1, pxPerWorkItemY = 1;
1184         if (cn <= 2 && ksize.width <= 4 && ksize.height <= 4)
1185         {
1186             pxPerWorkItemX = size.width % 8 ? size.width % 4 ? size.width % 2 ? 1 : 2 : 4 : 8;
1187             pxPerWorkItemY = size.height % 2 ? 1 : 2;
1188         }
1189         else if (cn < 4 || (ksize.width <= 4 && ksize.height <= 4))
1190         {
1191             pxPerWorkItemX = size.width % 2 ? 1 : 2;
1192             pxPerWorkItemY = size.height % 2 ? 1 : 2;
1193         }
1194         globalsize[0] = size.width / pxPerWorkItemX;
1195         globalsize[1] = size.height / pxPerWorkItemY;
1196
1197         // Need some padding in the private array for pixels
1198         int privDataWidth = ROUNDUP(pxPerWorkItemX + ksize.width - 1, pxLoadNumPixels);
1199
1200         // Make the global size a nice round number so the runtime can pick
1201         // from reasonable choices for the workgroup size
1202         const int wgRound = 256;
1203         globalsize[0] = ROUNDUP(globalsize[0], wgRound);
1204
1205         char build_options[1024], cvt[2][40];
1206         sprintf(build_options, "-D cn=%d "
1207                 "-D ANCHOR_X=%d -D ANCHOR_Y=%d -D KERNEL_SIZE_X=%d -D KERNEL_SIZE_Y=%d "
1208                 "-D PX_LOAD_VEC_SIZE=%d -D PX_LOAD_NUM_PX=%d "
1209                 "-D PX_PER_WI_X=%d -D PX_PER_WI_Y=%d -D PRIV_DATA_WIDTH=%d -D %s -D %s "
1210                 "-D PX_LOAD_X_ITERATIONS=%d -D PX_LOAD_Y_ITERATIONS=%d "
1211                 "-D srcT=%s -D srcT1=%s -D dstT=%s -D dstT1=%s -D WT=%s -D WT1=%s "
1212                 "-D convertToWT=%s -D convertToDstT=%s%s%s -D PX_LOAD_FLOAT_VEC_CONV=convert_%s -D OP_BOX_FILTER",
1213                 cn, anchor.x, anchor.y, ksize.width, ksize.height,
1214                 pxLoadVecSize, pxLoadNumPixels,
1215                 pxPerWorkItemX, pxPerWorkItemY, privDataWidth, borderMap[borderType],
1216                 isolated ? "BORDER_ISOLATED" : "NO_BORDER_ISOLATED",
1217                 privDataWidth / pxLoadNumPixels, pxPerWorkItemY + ksize.height - 1,
1218                 ocl::typeToStr(type), ocl::typeToStr(sdepth), ocl::typeToStr(dtype),
1219                 ocl::typeToStr(ddepth), ocl::typeToStr(wtype), ocl::typeToStr(wdepth),
1220                 ocl::convertTypeStr(sdepth, wdepth, cn, cvt[0]),
1221                 ocl::convertTypeStr(wdepth, ddepth, cn, cvt[1]),
1222                 normalize ? " -D NORMALIZE" : "", sqr ? " -D SQR" : "",
1223                 ocl::typeToStr(CV_MAKE_TYPE(wdepth, pxLoadVecSize)) //PX_LOAD_FLOAT_VEC_CONV
1224                 );
1225
1226
1227         if (!kernel.create("filterSmall", cv::ocl::imgproc::filterSmall_oclsrc, build_options))
1228             return false;
1229     }
1230     else
1231     {
1232         localsize = localsize_general;
1233         for ( ; ; )
1234         {
1235             int BLOCK_SIZE_X = tryWorkItems, BLOCK_SIZE_Y = std::min(ksize.height * 10, size.height);
1236
1237             while (BLOCK_SIZE_X > 32 && BLOCK_SIZE_X >= ksize.width * 2 && BLOCK_SIZE_X > size.width * 2)
1238                 BLOCK_SIZE_X /= 2;
1239             while (BLOCK_SIZE_Y < BLOCK_SIZE_X / 8 && BLOCK_SIZE_Y * computeUnits * 32 < size.height)
1240                 BLOCK_SIZE_Y *= 2;
1241
1242             if (ksize.width > BLOCK_SIZE_X || w < ksize.width || h < ksize.height)
1243                 return false;
1244
1245             char cvt[2][50];
1246             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"
1247                                  " -D ANCHOR_X=%d -D ANCHOR_Y=%d -D KERNEL_SIZE_X=%d -D KERNEL_SIZE_Y=%d -D %s%s%s%s%s"
1248                                  " -D ST1=%s -D DT1=%s -D cn=%d",
1249                                  BLOCK_SIZE_X, BLOCK_SIZE_Y, ocl::typeToStr(type), ocl::typeToStr(CV_MAKE_TYPE(ddepth, cn)),
1250                                  ocl::typeToStr(CV_MAKE_TYPE(wdepth, cn)),
1251                                  ocl::convertTypeStr(wdepth, ddepth, cn, cvt[0]),
1252                                  ocl::convertTypeStr(sdepth, wdepth, cn, cvt[1]),
1253                                  anchor.x, anchor.y, ksize.width, ksize.height, borderMap[borderType],
1254                                  isolated ? " -D BORDER_ISOLATED" : "", doubleSupport ? " -D DOUBLE_SUPPORT" : "",
1255                                  normalize ? " -D NORMALIZE" : "", sqr ? " -D SQR" : "",
1256                                  ocl::typeToStr(sdepth), ocl::typeToStr(ddepth), cn);
1257
1258             localsize[0] = BLOCK_SIZE_X;
1259             globalsize[0] = DIVUP(size.width, BLOCK_SIZE_X - (ksize.width - 1)) * BLOCK_SIZE_X;
1260             globalsize[1] = DIVUP(size.height, BLOCK_SIZE_Y);
1261
1262             kernel.create("boxFilter", cv::ocl::imgproc::boxFilter_oclsrc, opts);
1263             if (kernel.empty())
1264                 return false;
1265
1266             size_t kernelWorkGroupSize = kernel.workGroupSize();
1267             if (localsize[0] <= kernelWorkGroupSize)
1268                 break;
1269             if (BLOCK_SIZE_X < (int)kernelWorkGroupSize)
1270                 return false;
1271
1272             tryWorkItems = (int)kernelWorkGroupSize;
1273         }
1274     }
1275
1276     _dst.create(size, CV_MAKETYPE(ddepth, cn));
1277     UMat dst = _dst.getUMat();
1278
1279     int idxArg = kernel.set(0, ocl::KernelArg::PtrReadOnly(src));
1280     idxArg = kernel.set(idxArg, (int)src.step);
1281     int srcOffsetX = (int)((src.offset % src.step) / src.elemSize());
1282     int srcOffsetY = (int)(src.offset / src.step);
1283     int srcEndX = isolated ? srcOffsetX + size.width : wholeSize.width;
1284     int srcEndY = isolated ? srcOffsetY + size.height : wholeSize.height;
1285     idxArg = kernel.set(idxArg, srcOffsetX);
1286     idxArg = kernel.set(idxArg, srcOffsetY);
1287     idxArg = kernel.set(idxArg, srcEndX);
1288     idxArg = kernel.set(idxArg, srcEndY);
1289     idxArg = kernel.set(idxArg, ocl::KernelArg::WriteOnly(dst));
1290     if (normalize)
1291         idxArg = kernel.set(idxArg, (float)alpha);
1292
1293     return kernel.run(2, globalsize, localsize, false);
1294 }
1295
1296 #undef ROUNDUP
1297
1298 #endif
1299
1300 }
1301
1302
1303 cv::Ptr<cv::BaseRowFilter> cv::getRowSumFilter(int srcType, int sumType, int ksize, int anchor)
1304 {
1305     int sdepth = CV_MAT_DEPTH(srcType), ddepth = CV_MAT_DEPTH(sumType);
1306     CV_Assert( CV_MAT_CN(sumType) == CV_MAT_CN(srcType) );
1307
1308     if( anchor < 0 )
1309         anchor = ksize/2;
1310
1311     if( sdepth == CV_8U && ddepth == CV_32S )
1312         return makePtr<RowSum<uchar, int> >(ksize, anchor);
1313     if( sdepth == CV_8U && ddepth == CV_16U )
1314         return makePtr<RowSum<uchar, ushort> >(ksize, anchor);
1315     if( sdepth == CV_8U && ddepth == CV_64F )
1316         return makePtr<RowSum<uchar, double> >(ksize, anchor);
1317     if( sdepth == CV_16U && ddepth == CV_32S )
1318         return makePtr<RowSum<ushort, int> >(ksize, anchor);
1319     if( sdepth == CV_16U && ddepth == CV_64F )
1320         return makePtr<RowSum<ushort, double> >(ksize, anchor);
1321     if( sdepth == CV_16S && ddepth == CV_32S )
1322         return makePtr<RowSum<short, int> >(ksize, anchor);
1323     if( sdepth == CV_32S && ddepth == CV_32S )
1324         return makePtr<RowSum<int, int> >(ksize, anchor);
1325     if( sdepth == CV_16S && ddepth == CV_64F )
1326         return makePtr<RowSum<short, double> >(ksize, anchor);
1327     if( sdepth == CV_32F && ddepth == CV_64F )
1328         return makePtr<RowSum<float, double> >(ksize, anchor);
1329     if( sdepth == CV_64F && ddepth == CV_64F )
1330         return makePtr<RowSum<double, double> >(ksize, anchor);
1331
1332     CV_Error_( CV_StsNotImplemented,
1333         ("Unsupported combination of source format (=%d), and buffer format (=%d)",
1334         srcType, sumType));
1335
1336     return Ptr<BaseRowFilter>();
1337 }
1338
1339
1340 cv::Ptr<cv::BaseColumnFilter> cv::getColumnSumFilter(int sumType, int dstType, int ksize,
1341                                                      int anchor, double scale)
1342 {
1343     int sdepth = CV_MAT_DEPTH(sumType), ddepth = CV_MAT_DEPTH(dstType);
1344     CV_Assert( CV_MAT_CN(sumType) == CV_MAT_CN(dstType) );
1345
1346     if( anchor < 0 )
1347         anchor = ksize/2;
1348
1349     if( ddepth == CV_8U && sdepth == CV_32S )
1350         return makePtr<ColumnSum<int, uchar> >(ksize, anchor, scale);
1351     if( ddepth == CV_8U && sdepth == CV_16U )
1352         return makePtr<ColumnSum<ushort, uchar> >(ksize, anchor, scale);
1353     if( ddepth == CV_8U && sdepth == CV_64F )
1354         return makePtr<ColumnSum<double, uchar> >(ksize, anchor, scale);
1355     if( ddepth == CV_16U && sdepth == CV_32S )
1356         return makePtr<ColumnSum<int, ushort> >(ksize, anchor, scale);
1357     if( ddepth == CV_16U && sdepth == CV_64F )
1358         return makePtr<ColumnSum<double, ushort> >(ksize, anchor, scale);
1359     if( ddepth == CV_16S && sdepth == CV_32S )
1360         return makePtr<ColumnSum<int, short> >(ksize, anchor, scale);
1361     if( ddepth == CV_16S && sdepth == CV_64F )
1362         return makePtr<ColumnSum<double, short> >(ksize, anchor, scale);
1363     if( ddepth == CV_32S && sdepth == CV_32S )
1364         return makePtr<ColumnSum<int, int> >(ksize, anchor, scale);
1365     if( ddepth == CV_32F && sdepth == CV_32S )
1366         return makePtr<ColumnSum<int, float> >(ksize, anchor, scale);
1367     if( ddepth == CV_32F && sdepth == CV_64F )
1368         return makePtr<ColumnSum<double, float> >(ksize, anchor, scale);
1369     if( ddepth == CV_64F && sdepth == CV_32S )
1370         return makePtr<ColumnSum<int, double> >(ksize, anchor, scale);
1371     if( ddepth == CV_64F && sdepth == CV_64F )
1372         return makePtr<ColumnSum<double, double> >(ksize, anchor, scale);
1373
1374     CV_Error_( CV_StsNotImplemented,
1375         ("Unsupported combination of sum format (=%d), and destination format (=%d)",
1376         sumType, dstType));
1377
1378     return Ptr<BaseColumnFilter>();
1379 }
1380
1381
1382 cv::Ptr<cv::FilterEngine> cv::createBoxFilter( int srcType, int dstType, Size ksize,
1383                     Point anchor, bool normalize, int borderType )
1384 {
1385     int sdepth = CV_MAT_DEPTH(srcType);
1386     int cn = CV_MAT_CN(srcType), sumType = CV_64F;
1387     if( sdepth == CV_8U && CV_MAT_DEPTH(dstType) == CV_8U &&
1388         ksize.width*ksize.height <= 256 )
1389         sumType = CV_16U;
1390     else if( sdepth <= CV_32S && (!normalize ||
1391         ksize.width*ksize.height <= (sdepth == CV_8U ? (1<<23) :
1392             sdepth == CV_16U ? (1 << 15) : (1 << 16))) )
1393         sumType = CV_32S;
1394     sumType = CV_MAKETYPE( sumType, cn );
1395
1396     Ptr<BaseRowFilter> rowFilter = getRowSumFilter(srcType, sumType, ksize.width, anchor.x );
1397     Ptr<BaseColumnFilter> columnFilter = getColumnSumFilter(sumType,
1398         dstType, ksize.height, anchor.y, normalize ? 1./(ksize.width*ksize.height) : 1);
1399
1400     return makePtr<FilterEngine>(Ptr<BaseFilter>(), rowFilter, columnFilter,
1401            srcType, dstType, sumType, borderType );
1402 }
1403
1404 #ifdef HAVE_OPENVX
1405 namespace cv
1406 {
1407     namespace ovx {
1408         template <> inline bool skipSmallImages<VX_KERNEL_BOX_3x3>(int w, int h) { return w*h < 640 * 480; }
1409     }
1410     static bool openvx_boxfilter(InputArray _src, OutputArray _dst, int ddepth,
1411                                  Size ksize, Point anchor,
1412                                  bool normalize, int borderType)
1413     {
1414         if (ddepth < 0)
1415             ddepth = CV_8UC1;
1416         if (_src.type() != CV_8UC1 || ddepth != CV_8U || !normalize ||
1417             _src.cols() < 3 || _src.rows() < 3 ||
1418             ksize.width != 3 || ksize.height != 3 ||
1419             (anchor.x >= 0 && anchor.x != 1) ||
1420             (anchor.y >= 0 && anchor.y != 1) ||
1421             ovx::skipSmallImages<VX_KERNEL_BOX_3x3>(_src.cols(), _src.rows()))
1422             return false;
1423
1424         Mat src = _src.getMat();
1425
1426         if ((borderType & BORDER_ISOLATED) == 0 && src.isSubmatrix())
1427             return false; //Process isolated borders only
1428         vx_enum border;
1429         switch (borderType & ~BORDER_ISOLATED)
1430         {
1431         case BORDER_CONSTANT:
1432             border = VX_BORDER_CONSTANT;
1433             break;
1434         case BORDER_REPLICATE:
1435             border = VX_BORDER_REPLICATE;
1436             break;
1437         default:
1438             return false;
1439         }
1440
1441         _dst.create(src.size(), CV_8UC1);
1442         Mat dst = _dst.getMat();
1443
1444         try
1445         {
1446             ivx::Context ctx = ovx::getOpenVXContext();
1447
1448             Mat a;
1449             if (dst.data != src.data)
1450                 a = src;
1451             else
1452                 src.copyTo(a);
1453
1454             ivx::Image
1455                 ia = ivx::Image::createFromHandle(ctx, VX_DF_IMAGE_U8,
1456                                                   ivx::Image::createAddressing(a.cols, a.rows, 1, (vx_int32)(a.step)), a.data),
1457                 ib = ivx::Image::createFromHandle(ctx, VX_DF_IMAGE_U8,
1458                                                   ivx::Image::createAddressing(dst.cols, dst.rows, 1, (vx_int32)(dst.step)), dst.data);
1459
1460             //ATTENTION: VX_CONTEXT_IMMEDIATE_BORDER attribute change could lead to strange issues in multi-threaded environments
1461             //since OpenVX standard says nothing about thread-safety for now
1462             ivx::border_t prevBorder = ctx.immediateBorder();
1463             ctx.setImmediateBorder(border, (vx_uint8)(0));
1464             ivx::IVX_CHECK_STATUS(vxuBox3x3(ctx, ia, ib));
1465             ctx.setImmediateBorder(prevBorder);
1466         }
1467         catch (ivx::RuntimeError & e)
1468         {
1469             VX_DbgThrow(e.what());
1470         }
1471         catch (ivx::WrapperError & e)
1472         {
1473             VX_DbgThrow(e.what());
1474         }
1475
1476         return true;
1477     }
1478 }
1479 #endif
1480
1481 #if defined(HAVE_IPP)
1482 namespace cv
1483 {
1484 static bool ipp_boxfilter(Mat &src, Mat &dst, Size ksize, Point anchor, bool normalize, int borderType)
1485 {
1486 #ifdef HAVE_IPP_IW
1487     CV_INSTRUMENT_REGION_IPP()
1488
1489 #if IPP_VERSION_X100 < 201801
1490     // Problem with SSE42 optimization for 16s and some 8u modes
1491     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))))
1492         return false;
1493
1494     // Other optimizations has some degradations too
1495     if((((src.depth() == CV_16S || src.depth() == CV_16U) && (src.channels() == 4)) || (src.depth() == CV_8U && src.channels() == 1 && (ksize.width > 5 || ksize.height > 5))))
1496         return false;
1497 #endif
1498
1499     if(!normalize)
1500         return false;
1501
1502     if(!ippiCheckAnchor(anchor, ksize))
1503         return false;
1504
1505     try
1506     {
1507         ::ipp::IwiImage       iwSrc      = ippiGetImage(src);
1508         ::ipp::IwiImage       iwDst      = ippiGetImage(dst);
1509         ::ipp::IwiSize        iwKSize    = ippiGetSize(ksize);
1510         ::ipp::IwiBorderSize  borderSize(iwKSize);
1511         ::ipp::IwiBorderType  ippBorder(ippiGetBorder(iwSrc, borderType, borderSize));
1512         if(!ippBorder)
1513             return false;
1514
1515         CV_INSTRUMENT_FUN_IPP(::ipp::iwiFilterBox, iwSrc, iwDst, iwKSize, ::ipp::IwDefault(), ippBorder);
1516     }
1517     catch (::ipp::IwException)
1518     {
1519         return false;
1520     }
1521
1522     return true;
1523 #else
1524     CV_UNUSED(src); CV_UNUSED(dst); CV_UNUSED(ksize); CV_UNUSED(anchor); CV_UNUSED(normalize); CV_UNUSED(borderType);
1525     return false;
1526 #endif
1527 }
1528 }
1529 #endif
1530
1531
1532 void cv::boxFilter( InputArray _src, OutputArray _dst, int ddepth,
1533                 Size ksize, Point anchor,
1534                 bool normalize, int borderType )
1535 {
1536     CV_INSTRUMENT_REGION()
1537
1538     CV_OCL_RUN(_dst.isUMat() &&
1539                (borderType == BORDER_REPLICATE || borderType == BORDER_CONSTANT ||
1540                 borderType == BORDER_REFLECT || borderType == BORDER_REFLECT_101),
1541                ocl_boxFilter3x3_8UC1(_src, _dst, ddepth, ksize, anchor, borderType, normalize))
1542
1543     CV_OCL_RUN(_dst.isUMat(), ocl_boxFilter(_src, _dst, ddepth, ksize, anchor, borderType, normalize))
1544
1545     Mat src = _src.getMat();
1546     int stype = src.type(), sdepth = CV_MAT_DEPTH(stype), cn = CV_MAT_CN(stype);
1547     if( ddepth < 0 )
1548         ddepth = sdepth;
1549     _dst.create( src.size(), CV_MAKETYPE(ddepth, cn) );
1550     Mat dst = _dst.getMat();
1551     if( borderType != BORDER_CONSTANT && normalize && (borderType & BORDER_ISOLATED) != 0 )
1552     {
1553         if( src.rows == 1 )
1554             ksize.height = 1;
1555         if( src.cols == 1 )
1556             ksize.width = 1;
1557     }
1558
1559     Point ofs;
1560     Size wsz(src.cols, src.rows);
1561     if(!(borderType&BORDER_ISOLATED))
1562         src.locateROI( wsz, ofs );
1563
1564     CALL_HAL(boxFilter, cv_hal_boxFilter, src.ptr(), src.step, dst.ptr(), dst.step, src.cols, src.rows, sdepth, ddepth, cn,
1565              ofs.x, ofs.y, wsz.width - src.cols - ofs.x, wsz.height - src.rows - ofs.y, ksize.width, ksize.height,
1566              anchor.x, anchor.y, normalize, borderType&~BORDER_ISOLATED);
1567
1568     CV_OVX_RUN(true,
1569                openvx_boxfilter(src, dst, ddepth, ksize, anchor, normalize, borderType))
1570
1571     CV_IPP_RUN_FAST(ipp_boxfilter(src, dst, ksize, anchor, normalize, borderType));
1572
1573     borderType = (borderType&~BORDER_ISOLATED);
1574
1575     Ptr<FilterEngine> f = createBoxFilter( src.type(), dst.type(),
1576                         ksize, anchor, normalize, borderType );
1577
1578     f->apply( src, dst, wsz, ofs );
1579 }
1580
1581
1582 void cv::blur( InputArray src, OutputArray dst,
1583            Size ksize, Point anchor, int borderType )
1584 {
1585     CV_INSTRUMENT_REGION()
1586
1587     boxFilter( src, dst, -1, ksize, anchor, true, borderType );
1588 }
1589
1590
1591 /****************************************************************************************\
1592                                     Squared Box Filter
1593 \****************************************************************************************/
1594
1595 namespace cv
1596 {
1597
1598 template<typename T, typename ST>
1599 struct SqrRowSum :
1600         public BaseRowFilter
1601 {
1602     SqrRowSum( int _ksize, int _anchor ) :
1603         BaseRowFilter()
1604     {
1605         ksize = _ksize;
1606         anchor = _anchor;
1607     }
1608
1609     virtual void operator()(const uchar* src, uchar* dst, int width, int cn) CV_OVERRIDE
1610     {
1611         const T* S = (const T*)src;
1612         ST* D = (ST*)dst;
1613         int i = 0, k, ksz_cn = ksize*cn;
1614
1615         width = (width - 1)*cn;
1616         for( k = 0; k < cn; k++, S++, D++ )
1617         {
1618             ST s = 0;
1619             for( i = 0; i < ksz_cn; i += cn )
1620             {
1621                 ST val = (ST)S[i];
1622                 s += val*val;
1623             }
1624             D[0] = s;
1625             for( i = 0; i < width; i += cn )
1626             {
1627                 ST val0 = (ST)S[i], val1 = (ST)S[i + ksz_cn];
1628                 s += val1*val1 - val0*val0;
1629                 D[i+cn] = s;
1630             }
1631         }
1632     }
1633 };
1634
1635 static Ptr<BaseRowFilter> getSqrRowSumFilter(int srcType, int sumType, int ksize, int anchor)
1636 {
1637     int sdepth = CV_MAT_DEPTH(srcType), ddepth = CV_MAT_DEPTH(sumType);
1638     CV_Assert( CV_MAT_CN(sumType) == CV_MAT_CN(srcType) );
1639
1640     if( anchor < 0 )
1641         anchor = ksize/2;
1642
1643     if( sdepth == CV_8U && ddepth == CV_32S )
1644         return makePtr<SqrRowSum<uchar, int> >(ksize, anchor);
1645     if( sdepth == CV_8U && ddepth == CV_64F )
1646         return makePtr<SqrRowSum<uchar, double> >(ksize, anchor);
1647     if( sdepth == CV_16U && ddepth == CV_64F )
1648         return makePtr<SqrRowSum<ushort, double> >(ksize, anchor);
1649     if( sdepth == CV_16S && ddepth == CV_64F )
1650         return makePtr<SqrRowSum<short, double> >(ksize, anchor);
1651     if( sdepth == CV_32F && ddepth == CV_64F )
1652         return makePtr<SqrRowSum<float, double> >(ksize, anchor);
1653     if( sdepth == CV_64F && ddepth == CV_64F )
1654         return makePtr<SqrRowSum<double, double> >(ksize, anchor);
1655
1656     CV_Error_( CV_StsNotImplemented,
1657               ("Unsupported combination of source format (=%d), and buffer format (=%d)",
1658                srcType, sumType));
1659
1660     return Ptr<BaseRowFilter>();
1661 }
1662
1663 }
1664
1665 void cv::sqrBoxFilter( InputArray _src, OutputArray _dst, int ddepth,
1666                        Size ksize, Point anchor,
1667                        bool normalize, int borderType )
1668 {
1669     CV_INSTRUMENT_REGION()
1670
1671     int srcType = _src.type(), sdepth = CV_MAT_DEPTH(srcType), cn = CV_MAT_CN(srcType);
1672     Size size = _src.size();
1673
1674     if( ddepth < 0 )
1675         ddepth = sdepth < CV_32F ? CV_32F : CV_64F;
1676
1677     if( borderType != BORDER_CONSTANT && normalize )
1678     {
1679         if( size.height == 1 )
1680             ksize.height = 1;
1681         if( size.width == 1 )
1682             ksize.width = 1;
1683     }
1684
1685     CV_OCL_RUN(_dst.isUMat() && _src.dims() <= 2,
1686                ocl_boxFilter(_src, _dst, ddepth, ksize, anchor, borderType, normalize, true))
1687
1688     int sumDepth = CV_64F;
1689     if( sdepth == CV_8U )
1690         sumDepth = CV_32S;
1691     int sumType = CV_MAKETYPE( sumDepth, cn ), dstType = CV_MAKETYPE(ddepth, cn);
1692
1693     Mat src = _src.getMat();
1694     _dst.create( size, dstType );
1695     Mat dst = _dst.getMat();
1696
1697     Ptr<BaseRowFilter> rowFilter = getSqrRowSumFilter(srcType, sumType, ksize.width, anchor.x );
1698     Ptr<BaseColumnFilter> columnFilter = getColumnSumFilter(sumType,
1699                                                             dstType, ksize.height, anchor.y,
1700                                                             normalize ? 1./(ksize.width*ksize.height) : 1);
1701
1702     Ptr<FilterEngine> f = makePtr<FilterEngine>(Ptr<BaseFilter>(), rowFilter, columnFilter,
1703                                                 srcType, dstType, sumType, borderType );
1704     Point ofs;
1705     Size wsz(src.cols, src.rows);
1706     src.locateROI( wsz, ofs );
1707
1708     f->apply( src, dst, wsz, ofs );
1709 }
1710
1711
1712 /****************************************************************************************\
1713                                      Gaussian Blur
1714 \****************************************************************************************/
1715
1716 cv::Mat cv::getGaussianKernel( int n, double sigma, int ktype )
1717 {
1718     const int SMALL_GAUSSIAN_SIZE = 7;
1719     static const float small_gaussian_tab[][SMALL_GAUSSIAN_SIZE] =
1720     {
1721         {1.f},
1722         {0.25f, 0.5f, 0.25f},
1723         {0.0625f, 0.25f, 0.375f, 0.25f, 0.0625f},
1724         {0.03125f, 0.109375f, 0.21875f, 0.28125f, 0.21875f, 0.109375f, 0.03125f}
1725     };
1726
1727     const float* fixed_kernel = n % 2 == 1 && n <= SMALL_GAUSSIAN_SIZE && sigma <= 0 ?
1728         small_gaussian_tab[n>>1] : 0;
1729
1730     CV_Assert( ktype == CV_32F || ktype == CV_64F );
1731     Mat kernel(n, 1, ktype);
1732     float* cf = kernel.ptr<float>();
1733     double* cd = kernel.ptr<double>();
1734
1735     double sigmaX = sigma > 0 ? sigma : ((n-1)*0.5 - 1)*0.3 + 0.8;
1736     double scale2X = -0.5/(sigmaX*sigmaX);
1737     double sum = 0;
1738
1739     int i;
1740     for( i = 0; i < n; i++ )
1741     {
1742         double x = i - (n-1)*0.5;
1743         double t = fixed_kernel ? (double)fixed_kernel[i] : std::exp(scale2X*x*x);
1744         if( ktype == CV_32F )
1745         {
1746             cf[i] = (float)t;
1747             sum += cf[i];
1748         }
1749         else
1750         {
1751             cd[i] = t;
1752             sum += cd[i];
1753         }
1754     }
1755
1756     sum = 1./sum;
1757     for( i = 0; i < n; i++ )
1758     {
1759         if( ktype == CV_32F )
1760             cf[i] = (float)(cf[i]*sum);
1761         else
1762             cd[i] *= sum;
1763     }
1764
1765     return kernel;
1766 }
1767
1768 namespace cv {
1769
1770 template <typename T>
1771 static std::vector<T> getFixedpointGaussianKernel( int n, double sigma )
1772 {
1773     if (sigma <= 0)
1774     {
1775         if(n == 1)
1776             return std::vector<T>(1, softdouble(1.0));
1777         else if(n == 3)
1778         {
1779             T v3[] = { softdouble(0.25), softdouble(0.5), softdouble(0.25) };
1780             return std::vector<T>(v3, v3 + 3);
1781         }
1782         else if(n == 5)
1783         {
1784             T v5[] = { softdouble(0.0625), softdouble(0.25), softdouble(0.375), softdouble(0.25), softdouble(0.0625) };
1785             return std::vector<T>(v5, v5 + 5);
1786         }
1787         else if(n == 7)
1788         {
1789             T v7[] = { softdouble(0.03125), softdouble(0.109375), softdouble(0.21875), softdouble(0.28125), softdouble(0.21875), softdouble(0.109375), softdouble(0.03125) };
1790             return std::vector<T>(v7, v7 + 7);
1791         }
1792     }
1793
1794
1795     softdouble sigmaX = sigma > 0 ? softdouble(sigma) : mulAdd(softdouble(n),softdouble(0.15),softdouble(0.35));// softdouble(((n-1)*0.5 - 1)*0.3 + 0.8)
1796     softdouble scale2X = softdouble(-0.5*0.25)/(sigmaX*sigmaX);
1797     std::vector<softdouble> values(n);
1798     softdouble sum(0.);
1799     for(int i = 0, x = 1 - n; i < n; i++, x+=2 )
1800     {
1801         // x = i - (n - 1)*0.5
1802         // t = std::exp(scale2X*x*x)
1803         values[i] = exp(softdouble(x*x)*scale2X);
1804         sum += values[i];
1805     }
1806     sum = softdouble::one()/sum;
1807
1808     std::vector<T> kernel(n);
1809     for(int i = 0; i < n; i++ )
1810     {
1811         kernel[i] = values[i] * sum;
1812     }
1813
1814     return kernel;
1815 };
1816
1817 template <typename ET, typename FT>
1818 void hlineSmooth1N(const ET* src, int cn, const FT* m, int, FT* dst, int len, int)
1819 {
1820     for (int i = 0; i < len*cn; i++, src++, dst++)
1821         *dst = (*m) * (*src);
1822 }
1823 template <>
1824 void hlineSmooth1N<uint8_t, ufixedpoint16>(const uint8_t* src, int cn, const ufixedpoint16* m, int, ufixedpoint16* dst, int len, int)
1825 {
1826     int lencn = len*cn;
1827     v_uint16x8 v_mul = v_setall_u16(*((uint16_t*)m));
1828     int i = 0;
1829     for (; i <= lencn - 16; i += 16)
1830     {
1831         v_uint8x16 v_src = v_load(src + i);
1832         v_uint16x8 v_tmp0, v_tmp1;
1833         v_expand(v_src, v_tmp0, v_tmp1);
1834         v_store((uint16_t*)dst + i, v_mul*v_tmp0);
1835         v_store((uint16_t*)dst + i + 8, v_mul*v_tmp1);
1836     }
1837     if (i <= lencn - 8)
1838     {
1839         v_uint16x8 v_src = v_load_expand(src + i);
1840         v_store((uint16_t*)dst + i, v_mul*v_src);
1841         i += 8;
1842     }
1843     for (; i < lencn; i++)
1844         dst[i] = m[0] * src[i];
1845 }
1846 template <typename ET, typename FT>
1847 void hlineSmooth1N1(const ET* src, int cn, const FT*, int, FT* dst, int len, int)
1848 {
1849     for (int i = 0; i < len*cn; i++, src++, dst++)
1850         *dst = *src;
1851 }
1852 template <>
1853 void hlineSmooth1N1<uint8_t, ufixedpoint16>(const uint8_t* src, int cn, const ufixedpoint16*, int, ufixedpoint16* dst, int len, int)
1854 {
1855     int lencn = len*cn;
1856     int i = 0;
1857     for (; i <= lencn - 16; i += 16)
1858     {
1859         v_uint8x16 v_src = v_load(src + i);
1860         v_uint16x8 v_tmp0, v_tmp1;
1861         v_expand(v_src, v_tmp0, v_tmp1);
1862         v_store((uint16_t*)dst + i, v_shl<8>(v_tmp0));
1863         v_store((uint16_t*)dst + i + 8, v_shl<8>(v_tmp1));
1864     }
1865     if (i <= lencn - 8)
1866     {
1867         v_uint16x8 v_src = v_load_expand(src + i);
1868         v_store((uint16_t*)dst + i, v_shl<8>(v_src));
1869         i += 8;
1870     }
1871     for (; i < lencn; i++)
1872         dst[i] = src[i];
1873 }
1874 template <typename ET, typename FT>
1875 void hlineSmooth3N(const ET* src, int cn, const FT* m, int, FT* dst, int len, int borderType)
1876 {
1877     if (len == 1)
1878     {
1879         FT msum = borderType != BORDER_CONSTANT ? m[0] + m[1] + m[2] : m[1];
1880         for (int k = 0; k < cn; k++)
1881             dst[k] = msum * src[k];
1882     }
1883     else
1884     {
1885         // Point that fall left from border
1886         for (int k = 0; k < cn; k++)
1887             dst[k] = m[1] * src[k] + m[2] * src[cn + k];
1888         if (borderType != BORDER_CONSTANT)// If BORDER_CONSTANT out of border values are equal to zero and could be skipped
1889         {
1890             int src_idx = borderInterpolate(-1, len, borderType);
1891             for (int k = 0; k < cn; k++)
1892                 dst[k] = dst[k] + m[0] * src[src_idx*cn + k];
1893         }
1894
1895         src += cn; dst += cn;
1896         for (int i = cn; i < (len - 1)*cn; i++, src++, dst++)
1897             *dst = m[0] * src[-cn] + m[1] * src[0] + m[2] * src[cn];
1898
1899         // Point that fall right from border
1900         for (int k = 0; k < cn; k++)
1901             dst[k] = m[0] * src[k - cn] + m[1] * src[k];
1902         if (borderType != BORDER_CONSTANT)// If BORDER_CONSTANT out of border values are equal to zero and could be skipped
1903         {
1904             int src_idx = (borderInterpolate(len, len, borderType) - (len - 1))*cn;
1905             for (int k = 0; k < cn; k++)
1906                 dst[k] = dst[k] + m[2] * src[src_idx + k];
1907         }
1908     }
1909 }
1910 template <>
1911 void hlineSmooth3N<uint8_t, ufixedpoint16>(const uint8_t* src, int cn, const ufixedpoint16* m, int, ufixedpoint16* dst, int len, int borderType)
1912 {
1913     if (len == 1)
1914     {
1915         ufixedpoint16 msum = borderType != BORDER_CONSTANT ? m[0] + m[1] + m[2] : m[1];
1916         for (int k = 0; k < cn; k++)
1917             dst[k] = msum * src[k];
1918     }
1919     else
1920     {
1921         // Point that fall left from border
1922         for (int k = 0; k < cn; k++)
1923             dst[k] = m[1] * src[k] + m[2] * src[cn + k];
1924         if (borderType != BORDER_CONSTANT)// If BORDER_CONSTANT out of border values are equal to zero and could be skipped
1925         {
1926             int src_idx = borderInterpolate(-1, len, borderType);
1927             for (int k = 0; k < cn; k++)
1928                 dst[k] = dst[k] + m[0] * src[src_idx*cn + k];
1929         }
1930
1931         src += cn; dst += cn;
1932         int i = cn, lencn = (len - 1)*cn;
1933         v_uint16x8 v_mul0 = v_setall_u16(*((uint16_t*)m));
1934         v_uint16x8 v_mul1 = v_setall_u16(*((uint16_t*)(m + 1)));
1935         v_uint16x8 v_mul2 = v_setall_u16(*((uint16_t*)(m + 2)));
1936         for (; i <= lencn - 16; i += 16, src += 16, dst += 16)
1937         {
1938             v_uint16x8 v_src00, v_src01, v_src10, v_src11, v_src20, v_src21;
1939             v_expand(v_load(src - cn), v_src00, v_src01);
1940             v_expand(v_load(src), v_src10, v_src11);
1941             v_expand(v_load(src + cn), v_src20, v_src21);
1942             v_store((uint16_t*)dst, v_src00 * v_mul0 + v_src10 * v_mul1 + v_src20 * v_mul2);
1943             v_store((uint16_t*)dst + 8, v_src01 * v_mul0 + v_src11 * v_mul1 + v_src21 * v_mul2);
1944         }
1945         for (; i < lencn; i++, src++, dst++)
1946             *dst = m[0] * src[-cn] + m[1] * src[0] + m[2] * src[cn];
1947
1948         // Point that fall right from border
1949         for (int k = 0; k < cn; k++)
1950             dst[k] = m[0] * src[k - cn] + m[1] * src[k];
1951         if (borderType != BORDER_CONSTANT)// If BORDER_CONSTANT out of border values are equal to zero and could be skipped
1952         {
1953             int src_idx = (borderInterpolate(len, len, borderType) - (len - 1))*cn;
1954             for (int k = 0; k < cn; k++)
1955                 dst[k] = dst[k] + m[2] * src[src_idx + k];
1956         }
1957     }
1958 }
1959 template <typename ET, typename FT>
1960 void hlineSmooth3N121(const ET* src, int cn, const FT*, int, FT* dst, int len, int borderType)
1961 {
1962     if (len == 1)
1963     {
1964         if(borderType != BORDER_CONSTANT)
1965             for (int k = 0; k < cn; k++)
1966                 dst[k] = FT(src[k]);
1967         else
1968             for (int k = 0; k < cn; k++)
1969                 dst[k] = FT(src[k])>>1;
1970     }
1971     else
1972     {
1973         // Point that fall left from border
1974         for (int k = 0; k < cn; k++)
1975             dst[k] = (FT(src[k])>>1) + (FT(src[cn + k])>>2);
1976         if (borderType != BORDER_CONSTANT)// If BORDER_CONSTANT out of border values are equal to zero and could be skipped
1977         {
1978             int src_idx = borderInterpolate(-1, len, borderType);
1979             for (int k = 0; k < cn; k++)
1980                 dst[k] = dst[k] + (FT(src[src_idx*cn + k])>>2);
1981         }
1982
1983         src += cn; dst += cn;
1984         for (int i = cn; i < (len - 1)*cn; i++, src++, dst++)
1985             *dst = (FT(src[-cn])>>2) + (FT(src[cn])>>2) + (FT(src[0])>>1);
1986
1987         // Point that fall right from border
1988         for (int k = 0; k < cn; k++)
1989             dst[k] = (FT(src[k - cn])>>2) + (FT(src[k])>>1);
1990         if (borderType != BORDER_CONSTANT)// If BORDER_CONSTANT out of border values are equal to zero and could be skipped
1991         {
1992             int src_idx = (borderInterpolate(len, len, borderType) - (len - 1))*cn;
1993             for (int k = 0; k < cn; k++)
1994                 dst[k] = dst[k] + (FT(src[src_idx + k])>>2);
1995         }
1996     }
1997 }
1998 template <>
1999 void hlineSmooth3N121<uint8_t, ufixedpoint16>(const uint8_t* src, int cn, const ufixedpoint16*, int, ufixedpoint16* dst, int len, int borderType)
2000 {
2001     if (len == 1)
2002     {
2003         if (borderType != BORDER_CONSTANT)
2004             for (int k = 0; k < cn; k++)
2005                 dst[k] = ufixedpoint16(src[k]);
2006         else
2007             for (int k = 0; k < cn; k++)
2008                 dst[k] = ufixedpoint16(src[k]) >> 1;
2009     }
2010     else
2011     {
2012         // Point that fall left from border
2013         for (int k = 0; k < cn; k++)
2014             dst[k] = (ufixedpoint16(src[k])>>1) + (ufixedpoint16(src[cn + k])>>2);
2015         if (borderType != BORDER_CONSTANT)// If BORDER_CONSTANT out of border values are equal to zero and could be skipped
2016         {
2017             int src_idx = borderInterpolate(-1, len, borderType);
2018             for (int k = 0; k < cn; k++)
2019                 dst[k] = dst[k] + (ufixedpoint16(src[src_idx*cn + k])>>2);
2020         }
2021
2022         src += cn; dst += cn;
2023         int i = cn, lencn = (len - 1)*cn;
2024         for (; i <= lencn - 16; i += 16, src += 16, dst += 16)
2025         {
2026             v_uint16x8 v_src00, v_src01, v_src10, v_src11, v_src20, v_src21;
2027             v_expand(v_load(src - cn), v_src00, v_src01);
2028             v_expand(v_load(src), v_src10, v_src11);
2029             v_expand(v_load(src + cn), v_src20, v_src21);
2030             v_store((uint16_t*)dst, (v_src00 + v_src20 + (v_src10 << 1)) << 6);
2031             v_store((uint16_t*)dst + 8, (v_src01 + v_src21 + (v_src11 << 1)) << 6);
2032         }
2033         for (; i < lencn; i++, src++, dst++)
2034             *((uint16_t*)dst) = (uint16_t(src[-cn]) + uint16_t(src[cn]) + (uint16_t(src[0]) << 1)) << 6;
2035
2036         // Point that fall right from border
2037         for (int k = 0; k < cn; k++)
2038             dst[k] = (ufixedpoint16(src[k - cn])>>2) + (ufixedpoint16(src[k])>>1);
2039         if (borderType != BORDER_CONSTANT)// If BORDER_CONSTANT out of border values are equal to zero and could be skipped
2040         {
2041             int src_idx = (borderInterpolate(len, len, borderType) - (len - 1))*cn;
2042             for (int k = 0; k < cn; k++)
2043                 dst[k] = dst[k] + (ufixedpoint16(src[src_idx + k])>>2);
2044         }
2045     }
2046 }
2047 template <typename ET, typename FT>
2048 void hlineSmooth3Naba(const ET* src, int cn, const FT* m, int, FT* dst, int len, int borderType)
2049 {
2050     if (len == 1)
2051     {
2052         FT msum = borderType != BORDER_CONSTANT ? (m[0]<<1) + m[1] : m[1];
2053         for (int k = 0; k < cn; k++)
2054             dst[k] = msum * src[k];
2055     }
2056     else
2057     {
2058         // Point that fall left from border
2059         if (borderType != BORDER_CONSTANT)// If BORDER_CONSTANT out of border values are equal to zero and could be skipped
2060         {
2061             int src_idx = borderInterpolate(-1, len, borderType);
2062             for (int k = 0; k < cn; k++)
2063                 dst[k] = m[1] * src[k] + m[0] * src[cn + k] + m[0] * src[src_idx*cn + k];
2064         }
2065         else
2066         {
2067             for (int k = 0; k < cn; k++)
2068                 dst[k] = m[1] * src[k] + m[0] * src[cn + k];
2069         }
2070
2071         src += cn; dst += cn;
2072         for (int i = cn; i < (len - 1)*cn; i++, src++, dst++)
2073             *dst = m[1] * src[0] + m[0] * src[-cn] + m[0] * src[cn];
2074
2075         // Point that fall right from border
2076         if (borderType != BORDER_CONSTANT)// If BORDER_CONSTANT out of border values are equal to zero and could be skipped
2077         {
2078             int src_idx = (borderInterpolate(len, len, borderType) - (len - 1))*cn;
2079             for (int k = 0; k < cn; k++)
2080                 dst[k] = m[1] * src[k] + m[0] * src[k - cn] + m[0] * src[src_idx + k];
2081         }
2082         else
2083         {
2084             for (int k = 0; k < cn; k++)
2085                 dst[k] = m[0] * src[k - cn] + m[1] * src[k];
2086         }
2087     }
2088 }
2089 template <>
2090 void hlineSmooth3Naba<uint8_t, ufixedpoint16>(const uint8_t* src, int cn, const ufixedpoint16* m, int, ufixedpoint16* dst, int len, int borderType)
2091 {
2092     if (len == 1)
2093     {
2094         ufixedpoint16 msum = borderType != BORDER_CONSTANT ? (m[0]<<1) + m[1] : m[1];
2095         for (int k = 0; k < cn; k++)
2096             dst[k] = msum * src[k];
2097     }
2098     else
2099     {
2100         // Point that fall left from border
2101         if (borderType != BORDER_CONSTANT)// If BORDER_CONSTANT out of border values are equal to zero and could be skipped
2102         {
2103             int src_idx = borderInterpolate(-1, len, borderType);
2104             for (int k = 0; k < cn; k++)
2105                 ((uint16_t*)dst)[k] = ((uint16_t*)m)[1] * src[k] + ((uint16_t*)m)[0] * ((uint16_t)(src[cn + k]) + (uint16_t)(src[src_idx*cn + k]));
2106         }
2107         else
2108         {
2109             for (int k = 0; k < cn; k++)
2110                 dst[k] = m[1] * src[k] + m[0] * src[cn + k];
2111         }
2112
2113         src += cn; dst += cn;
2114         int i = cn, lencn = (len - 1)*cn;
2115         v_uint16x8 v_mul0 = v_setall_u16(*((uint16_t*)m));
2116         v_uint16x8 v_mul1 = v_setall_u16(*((uint16_t*)m+1));
2117         for (; i <= lencn - 16; i += 16, src += 16, dst += 16)
2118         {
2119             v_uint16x8 v_src00, v_src01, v_src10, v_src11, v_src20, v_src21;
2120             v_expand(v_load(src - cn), v_src00, v_src01);
2121             v_expand(v_load(src), v_src10, v_src11);
2122             v_expand(v_load(src + cn), v_src20, v_src21);
2123             v_store((uint16_t*)dst, (v_src00 + v_src20) * v_mul0 + v_src10 * v_mul1);
2124             v_store((uint16_t*)dst + 8, (v_src01 + v_src21) * v_mul0 + v_src11 * v_mul1);
2125         }
2126         for (; i < lencn; i++, src++, dst++)
2127             *((uint16_t*)dst) = ((uint16_t*)m)[1] * src[0] + ((uint16_t*)m)[0] * ((uint16_t)(src[-cn]) + (uint16_t)(src[cn]));
2128
2129         // Point that fall right from border
2130         if (borderType != BORDER_CONSTANT)// If BORDER_CONSTANT out of border values are equal to zero and could be skipped
2131         {
2132             int src_idx = (borderInterpolate(len, len, borderType) - (len - 1))*cn;
2133             for (int k = 0; k < cn; k++)
2134                 ((uint16_t*)dst)[k] = ((uint16_t*)m)[1] * src[k] + ((uint16_t*)m)[0] * ((uint16_t)(src[k - cn]) + (uint16_t)(src[src_idx + k]));
2135         }
2136         else
2137         {
2138             for (int k = 0; k < cn; k++)
2139                 dst[k] = m[0] * src[k - cn] + m[1] * src[k];
2140         }
2141     }
2142 }
2143 template <typename ET, typename FT>
2144 void hlineSmooth5N(const ET* src, int cn, const FT* m, int, FT* dst, int len, int borderType)
2145 {
2146     if (len == 1)
2147     {
2148         FT msum = borderType != BORDER_CONSTANT ? m[0] + m[1] + m[2] + m[3] + m[4] : m[2];
2149         for (int k = 0; k < cn; k++)
2150             dst[k] = msum * src[k];
2151     }
2152     else if (len == 2)
2153     {
2154         if (borderType == BORDER_CONSTANT)
2155             for (int k = 0; k < cn; k++)
2156             {
2157                 dst[k   ] = m[2] * src[k] + m[3] * src[k+cn];
2158                 dst[k+cn] = m[1] * src[k] + m[2] * src[k+cn];
2159             }
2160         else
2161         {
2162             int idxm2 = borderInterpolate(-2, len, borderType)*cn;
2163             int idxm1 = borderInterpolate(-1, len, borderType)*cn;
2164             int idxp1 = borderInterpolate(2, len, borderType)*cn;
2165             int idxp2 = borderInterpolate(3, len, borderType)*cn;
2166             for (int k = 0; k < cn; k++)
2167             {
2168                 dst[k     ] = m[1] * src[k + idxm1] + m[2] * src[k] + m[3] * src[k + cn] + m[4] * src[k + idxp1] + m[0] * src[k + idxm2];
2169                 dst[k + cn] = m[0] * src[k + idxm1] + m[1] * src[k] + m[2] * src[k + cn] + m[3] * src[k + idxp1] + m[4] * src[k + idxp2];
2170             }
2171         }
2172     }
2173     else if (len == 3)
2174     {
2175         if (borderType == BORDER_CONSTANT)
2176             for (int k = 0; k < cn; k++)
2177             {
2178                 dst[k       ] = m[2] * src[k] + m[3] * src[k + cn] + m[4] * src[k + 2*cn];
2179                 dst[k +   cn] = m[1] * src[k] + m[2] * src[k + cn] + m[3] * src[k + 2*cn];
2180                 dst[k + 2*cn] = m[0] * src[k] + m[1] * src[k + cn] + m[2] * src[k + 2*cn];
2181             }
2182         else
2183         {
2184             int idxm2 = borderInterpolate(-2, len, borderType)*cn;
2185             int idxm1 = borderInterpolate(-1, len, borderType)*cn;
2186             int idxp1 = borderInterpolate(3, len, borderType)*cn;
2187             int idxp2 = borderInterpolate(4, len, borderType)*cn;
2188             for (int k = 0; k < cn; k++)
2189             {
2190                 dst[k       ] = m[2] * src[k] + m[3] * src[k + cn] + m[4] * src[k + 2*cn] + m[0] * src[k + idxm2] + m[1] * src[k + idxm1];
2191                 dst[k +   cn] = m[1] * src[k] + m[2] * src[k + cn] + m[3] * src[k + 2*cn] + m[0] * src[k + idxm1] + m[4] * src[k + idxp1];
2192                 dst[k + 2*cn] = m[0] * src[k] + m[1] * src[k + cn] + m[2] * src[k + 2*cn] + m[3] * src[k + idxp1] + m[4] * src[k + idxp2];
2193             }
2194         }
2195     }
2196     else
2197     {
2198         // Points that fall left from border
2199         for (int k = 0; k < cn; k++)
2200         {
2201             dst[k] = m[2] * src[k] + m[3] * src[cn + k] + m[4] * src[2*cn + k];
2202             dst[k + cn] = m[1] * src[k] + m[2] * src[cn + k] + m[3] * src[2*cn + k] + m[4] * src[3*cn + k];
2203         }
2204         if (borderType != BORDER_CONSTANT)// If BORDER_CONSTANT out of border values are equal to zero and could be skipped
2205         {
2206             int idxm2 = borderInterpolate(-2, len, borderType)*cn;
2207             int idxm1 = borderInterpolate(-1, len, borderType)*cn;
2208             for (int k = 0; k < cn; k++)
2209             {
2210                 dst[k] = dst[k] + m[0] * src[idxm2 + k] + m[1] * src[idxm1 + k];
2211                 dst[k + cn] = dst[k + cn] + m[0] * src[idxm1 + k];
2212             }
2213         }
2214
2215         src += 2*cn; dst += 2*cn;
2216         for (int i = 2*cn; i < (len - 2)*cn; i++, src++, dst++)
2217             *dst = m[0] * src[-2*cn] + m[1] * src[-cn] + m[2] * src[0] + m[3] * src[cn] + m[4] * src[2*cn];
2218
2219         // Points that fall right from border
2220         for (int k = 0; k < cn; k++)
2221         {
2222             dst[k] = m[0] * src[k - 2*cn] + m[1] * src[k - cn] + m[2] * src[k] + m[3] * src[k + cn];
2223             dst[k + cn] = m[0] * src[k - cn] + m[1] * src[k] + m[2] * src[k + cn];
2224         }
2225         if (borderType != BORDER_CONSTANT)// If BORDER_CONSTANT out of border values are equal to zero and could be skipped
2226         {
2227             int idxp1 = (borderInterpolate(len, len, borderType) - (len - 2))*cn;
2228             int idxp2 = (borderInterpolate(len+1, len, borderType) - (len - 2))*cn;
2229             for (int k = 0; k < cn; k++)
2230             {
2231                 dst[k] = dst[k] + m[4] * src[idxp1 + k];
2232                 dst[k + cn] = dst[k + cn] + m[3] * src[idxp1 + k] + m[4] * src[idxp2 + k];
2233             }
2234         }
2235     }
2236 }
2237 template <>
2238 void hlineSmooth5N<uint8_t, ufixedpoint16>(const uint8_t* src, int cn, const ufixedpoint16* m, int, ufixedpoint16* dst, int len, int borderType)
2239 {
2240     if (len == 1)
2241     {
2242         ufixedpoint16 msum = borderType != BORDER_CONSTANT ? m[0] + m[1] + m[2] + m[3] + m[4] : m[2];
2243         for (int k = 0; k < cn; k++)
2244             dst[k] = msum * src[k];
2245     }
2246     else if (len == 2)
2247     {
2248         if (borderType == BORDER_CONSTANT)
2249             for (int k = 0; k < cn; k++)
2250             {
2251                 dst[k] = m[2] * src[k] + m[3] * src[k + cn];
2252                 dst[k + cn] = m[1] * src[k] + m[2] * src[k + cn];
2253             }
2254         else
2255         {
2256             int idxm2 = borderInterpolate(-2, len, borderType)*cn;
2257             int idxm1 = borderInterpolate(-1, len, borderType)*cn;
2258             int idxp1 = borderInterpolate(2, len, borderType)*cn;
2259             int idxp2 = borderInterpolate(3, len, borderType)*cn;
2260             for (int k = 0; k < cn; k++)
2261             {
2262                 dst[k] = m[1] * src[k + idxm1] + m[2] * src[k] + m[3] * src[k + cn] + m[4] * src[k + idxp1] + m[0] * src[k + idxm2];
2263                 dst[k + cn] = m[0] * src[k + idxm1] + m[1] * src[k] + m[2] * src[k + cn] + m[3] * src[k + idxp1] + m[4] * src[k + idxp2];
2264             }
2265         }
2266     }
2267     else if (len == 3)
2268     {
2269         if (borderType == BORDER_CONSTANT)
2270             for (int k = 0; k < cn; k++)
2271             {
2272                 dst[k] = m[2] * src[k] + m[3] * src[k + cn] + m[4] * src[k + 2 * cn];
2273                 dst[k + cn] = m[1] * src[k] + m[2] * src[k + cn] + m[3] * src[k + 2 * cn];
2274                 dst[k + 2 * cn] = m[0] * src[k] + m[1] * src[k + cn] + m[2] * src[k + 2 * cn];
2275             }
2276         else
2277         {
2278             int idxm2 = borderInterpolate(-2, len, borderType)*cn;
2279             int idxm1 = borderInterpolate(-1, len, borderType)*cn;
2280             int idxp1 = borderInterpolate(3, len, borderType)*cn;
2281             int idxp2 = borderInterpolate(4, len, borderType)*cn;
2282             for (int k = 0; k < cn; k++)
2283             {
2284                 dst[k] = m[2] * src[k] + m[3] * src[k + cn] + m[4] * src[k + 2 * cn] + m[0] * src[k + idxm2] + m[1] * src[k + idxm1];
2285                 dst[k + cn] = m[1] * src[k] + m[2] * src[k + cn] + m[3] * src[k + 2 * cn] + m[0] * src[k + idxm1] + m[4] * src[k + idxp1];
2286                 dst[k + 2 * cn] = m[0] * src[k] + m[1] * src[k + cn] + m[2] * src[k + 2 * cn] + m[3] * src[k + idxp1] + m[4] * src[k + idxp2];
2287             }
2288         }
2289     }
2290     else
2291     {
2292         // Points that fall left from border
2293         for (int k = 0; k < cn; k++)
2294         {
2295             dst[k] = m[2] * src[k] + m[3] * src[cn + k] + m[4] * src[2 * cn + k];
2296             dst[k + cn] = m[1] * src[k] + m[2] * src[cn + k] + m[3] * src[2 * cn + k] + m[4] * src[3 * cn + k];
2297         }
2298         if (borderType != BORDER_CONSTANT)// If BORDER_CONSTANT out of border values are equal to zero and could be skipped
2299         {
2300             int idxm2 = borderInterpolate(-2, len, borderType)*cn;
2301             int idxm1 = borderInterpolate(-1, len, borderType)*cn;
2302             for (int k = 0; k < cn; k++)
2303             {
2304                 dst[k] = dst[k] + m[0] * src[idxm2 + k] + m[1] * src[idxm1 + k];
2305                 dst[k + cn] = dst[k + cn] + m[0] * src[idxm1 + k];
2306             }
2307         }
2308
2309         src += 2 * cn; dst += 2 * cn;
2310         int i = 2*cn, lencn = (len - 2)*cn;
2311         v_uint16x8 v_mul0 = v_setall_u16(*((uint16_t*)m));
2312         v_uint16x8 v_mul1 = v_setall_u16(*((uint16_t*)(m + 1)));
2313         v_uint16x8 v_mul2 = v_setall_u16(*((uint16_t*)(m + 2)));
2314         v_uint16x8 v_mul3 = v_setall_u16(*((uint16_t*)(m + 3)));
2315         v_uint16x8 v_mul4 = v_setall_u16(*((uint16_t*)(m + 4)));
2316         for (; i <= lencn - 16; i += 16, src += 16, dst += 16)
2317         {
2318             v_uint16x8 v_src00, v_src01, v_src10, v_src11, v_src20, v_src21, v_src30, v_src31, v_src40, v_src41;
2319             v_expand(v_load(src - 2*cn), v_src00, v_src01);
2320             v_expand(v_load(src - cn), v_src10, v_src11);
2321             v_expand(v_load(src), v_src20, v_src21);
2322             v_expand(v_load(src + cn), v_src30, v_src31);
2323             v_expand(v_load(src + 2*cn), v_src40, v_src41);
2324             v_store((uint16_t*)dst, v_src00 * v_mul0 + v_src10 * v_mul1 + v_src20 * v_mul2 + v_src30 * v_mul3 + v_src40 * v_mul4);
2325             v_store((uint16_t*)dst + 8, v_src01 * v_mul0 + v_src11 * v_mul1 + v_src21 * v_mul2 + v_src31 * v_mul3 + v_src41 * v_mul4);
2326         }
2327         for (; i < lencn; i++, src++, dst++)
2328             *dst = m[0] * src[-2*cn] + m[1] * src[-cn] + m[2] * src[0] + m[3] * src[cn] + m[4] * src[2*cn];
2329
2330         // Points that fall right from border
2331         for (int k = 0; k < cn; k++)
2332         {
2333             dst[k] = m[0] * src[k - 2 * cn] + m[1] * src[k - cn] + m[2] * src[k] + m[3] * src[k + cn];
2334             dst[k + cn] = m[0] * src[k - cn] + m[1] * src[k] + m[2] * src[k + cn];
2335         }
2336         if (borderType != BORDER_CONSTANT)// If BORDER_CONSTANT out of border values are equal to zero and could be skipped
2337         {
2338             int idxp1 = (borderInterpolate(len, len, borderType) - (len - 2))*cn;
2339             int idxp2 = (borderInterpolate(len + 1, len, borderType) - (len - 2))*cn;
2340             for (int k = 0; k < cn; k++)
2341             {
2342                 dst[k] = dst[k] + m[4] * src[idxp1 + k];
2343                 dst[k + cn] = dst[k + cn] + m[3] * src[idxp1 + k] + m[4] * src[idxp2 + k];
2344             }
2345         }
2346     }
2347 }
2348 template <typename ET, typename FT>
2349 void hlineSmooth5N14641(const ET* src, int cn, const FT*, int, FT* dst, int len, int borderType)
2350 {
2351     if (len == 1)
2352     {
2353         if (borderType == BORDER_CONSTANT)
2354             for (int k = 0; k < cn; k++)
2355                 dst[k] = (FT(src[k])>>3)*(uint8_t)3;
2356         else
2357             for (int k = 0; k < cn; k++)
2358                 dst[k] = src[k];
2359     }
2360     else if (len == 2)
2361     {
2362         if (borderType == BORDER_CONSTANT)
2363             for (int k = 0; k < cn; k++)
2364             {
2365                 dst[k] = (FT(src[k])>>4)*(uint8_t)6 + (FT(src[k + cn])>>2);
2366                 dst[k + cn] = (FT(src[k]) >> 2) + (FT(src[k + cn])>>4)*(uint8_t)6;
2367             }
2368         else
2369         {
2370             int idxm2 = borderInterpolate(-2, len, borderType)*cn;
2371             int idxm1 = borderInterpolate(-1, len, borderType)*cn;
2372             int idxp1 = borderInterpolate(2, len, borderType)*cn;
2373             int idxp2 = borderInterpolate(3, len, borderType)*cn;
2374             for (int k = 0; k < cn; k++)
2375             {
2376                 dst[k] = (FT(src[k])>>4)*(uint8_t)6 + (FT(src[k + idxm1])>>2) + (FT(src[k + cn])>>2) + (FT(src[k + idxp1])>>4) + (FT(src[k + idxm2])>>4);
2377                 dst[k + cn] = (FT(src[k + cn])>>4)*(uint8_t)6 + (FT(src[k])>>2) + (FT(src[k + idxp1])>>2) + (FT(src[k + idxm1])>>4) + (FT(src[k + idxp2])>>4);
2378             }
2379         }
2380     }
2381     else if (len == 3)
2382     {
2383         if (borderType == BORDER_CONSTANT)
2384             for (int k = 0; k < cn; k++)
2385             {
2386                 dst[k] = (FT(src[k])>>4)*(uint8_t)6 + (FT(src[k + cn])>>2) + (FT(src[k + 2 * cn])>>4);
2387                 dst[k + cn] = (FT(src[k + cn])>>4)*(uint8_t)6 + (FT(src[k])>>2) + (FT(src[k + 2 * cn])>>2);
2388                 dst[k + 2 * cn] = (FT(src[k + 2 * cn])>>4)*(uint8_t)6 + (FT(src[k + cn])>>2) + (FT(src[k])>>4);
2389             }
2390         else
2391         {
2392             int idxm2 = borderInterpolate(-2, len, borderType)*cn;
2393             int idxm1 = borderInterpolate(-1, len, borderType)*cn;
2394             int idxp1 = borderInterpolate(3, len, borderType)*cn;
2395             int idxp2 = borderInterpolate(4, len, borderType)*cn;
2396             for (int k = 0; k < cn; k++)
2397             {
2398                 dst[k] = (FT(src[k])>>4)*(uint8_t)6 + (FT(src[k + cn])>>2) + (FT(src[k + idxm1])>>2) + (FT(src[k + 2 * cn])>>4) + (FT(src[k + idxm2])>>4);
2399                 dst[k + cn] = (FT(src[k + cn])>>4)*(uint8_t)6 + (FT(src[k])>>2) + (FT(src[k + 2 * cn])>>2) + (FT(src[k + idxm1])>>4) + (FT(src[k + idxp1])>>4);
2400                 dst[k + 2 * cn] = (FT(src[k + 2 * cn])>>4)*(uint8_t)6 + (FT(src[k + cn])>>2) + (FT(src[k + idxp1])>>2) + (FT(src[k])>>4) + (FT(src[k + idxp2])>>4);
2401             }
2402         }
2403     }
2404     else
2405     {
2406         // Points that fall left from border
2407         for (int k = 0; k < cn; k++)
2408         {
2409             dst[k] = (FT(src[k])>>4)*(uint8_t)6 + (FT(src[cn + k])>>2) + (FT(src[2 * cn + k])>>4);
2410             dst[k + cn] = (FT(src[cn + k])>>4)*(uint8_t)6 + (FT(src[k])>>2) + (FT(src[2 * cn + k])>>2) + (FT(src[3 * cn + k])>>4);
2411         }
2412         if (borderType != BORDER_CONSTANT)// If BORDER_CONSTANT out of border values are equal to zero and could be skipped
2413         {
2414             int idxm2 = borderInterpolate(-2, len, borderType)*cn;
2415             int idxm1 = borderInterpolate(-1, len, borderType)*cn;
2416             for (int k = 0; k < cn; k++)
2417             {
2418                 dst[k] = dst[k] + (FT(src[idxm2 + k])>>4) + (FT(src[idxm1 + k])>>2);
2419                 dst[k + cn] = dst[k + cn] + (FT(src[idxm1 + k])>>4);
2420             }
2421         }
2422
2423         src += 2 * cn; dst += 2 * cn;
2424         for (int i = 2 * cn; i < (len - 2)*cn; i++, src++, dst++)
2425             *dst = (FT(src[0])>>4)*(uint8_t)6 + (FT(src[-cn])>>2) + (FT(src[cn])>>2) + (FT(src[-2 * cn])>>4) + (FT(src[2 * cn])>>4);
2426
2427         // Points that fall right from border
2428         for (int k = 0; k < cn; k++)
2429         {
2430             dst[k] = (FT(src[k])>>4)*(uint8_t)6 + (FT(src[k - cn])>>2) + (FT(src[k + cn])>>2) + (FT(src[k - 2 * cn])>>4);
2431             dst[k + cn] = (FT(src[k + cn])>>4)*(uint8_t)6 + (FT(src[k])>>2) + (FT(src[k - cn])>>4);
2432         }
2433         if (borderType != BORDER_CONSTANT)// If BORDER_CONSTANT out of border values are equal to zero and could be skipped
2434         {
2435             int idxp1 = (borderInterpolate(len, len, borderType) - (len - 2))*cn;
2436             int idxp2 = (borderInterpolate(len + 1, len, borderType) - (len - 2))*cn;
2437             for (int k = 0; k < cn; k++)
2438             {
2439                 dst[k] = dst[k] + (FT(src[idxp1 + k])>>4);
2440                 dst[k + cn] = dst[k + cn] + (FT(src[idxp1 + k])>>2) + (FT(src[idxp2 + k])>>4);
2441             }
2442         }
2443     }
2444 }
2445 template <>
2446 void hlineSmooth5N14641<uint8_t, ufixedpoint16>(const uint8_t* src, int cn, const ufixedpoint16*, int, ufixedpoint16* dst, int len, int borderType)
2447 {
2448     if (len == 1)
2449     {
2450         if (borderType == BORDER_CONSTANT)
2451             for (int k = 0; k < cn; k++)
2452                 dst[k] = (ufixedpoint16(src[k])>>3) * (uint8_t)3;
2453         else
2454         {
2455             for (int k = 0; k < cn; k++)
2456                 dst[k] = src[k];
2457         }
2458     }
2459     else if (len == 2)
2460     {
2461         if (borderType == BORDER_CONSTANT)
2462             for (int k = 0; k < cn; k++)
2463             {
2464                 dst[k] = (ufixedpoint16(src[k]) >> 4) * (uint8_t)6 + (ufixedpoint16(src[k + cn]) >> 2);
2465                 dst[k + cn] = (ufixedpoint16(src[k]) >> 2) + (ufixedpoint16(src[k + cn]) >> 4) * (uint8_t)6;
2466             }
2467         else
2468         {
2469             int idxm2 = borderInterpolate(-2, len, borderType)*cn;
2470             int idxm1 = borderInterpolate(-1, len, borderType)*cn;
2471             int idxp1 = borderInterpolate(2, len, borderType)*cn;
2472             int idxp2 = borderInterpolate(3, len, borderType)*cn;
2473             for (int k = 0; k < cn; k++)
2474             {
2475                 dst[k] = (ufixedpoint16(src[k]) >> 4) * (uint8_t)6 + (ufixedpoint16(src[k + idxm1]) >> 2) + (ufixedpoint16(src[k + cn]) >> 2) + (ufixedpoint16(src[k + idxp1]) >> 4) + (ufixedpoint16(src[k + idxm2]) >> 4);
2476                 dst[k + cn] = (ufixedpoint16(src[k + cn]) >> 4) * (uint8_t)6 + (ufixedpoint16(src[k]) >> 2) + (ufixedpoint16(src[k + idxp1]) >> 2) + (ufixedpoint16(src[k + idxm1]) >> 4) + (ufixedpoint16(src[k + idxp2]) >> 4);
2477             }
2478         }
2479     }
2480     else if (len == 3)
2481     {
2482         if (borderType == BORDER_CONSTANT)
2483             for (int k = 0; k < cn; k++)
2484             {
2485                 dst[k] = (ufixedpoint16(src[k]) >> 4) * (uint8_t)6 + (ufixedpoint16(src[k + cn]) >> 2) + (ufixedpoint16(src[k + 2 * cn]) >> 4);
2486                 dst[k + cn] = (ufixedpoint16(src[k + cn]) >> 4) * (uint8_t)6 + (ufixedpoint16(src[k]) >> 2) + (ufixedpoint16(src[k + 2 * cn]) >> 2);
2487                 dst[k + 2 * cn] = (ufixedpoint16(src[k + 2 * cn]) >> 4) * (uint8_t)6 + (ufixedpoint16(src[k + cn]) >> 2) + (ufixedpoint16(src[k]) >> 4);
2488             }
2489         else
2490         {
2491             int idxm2 = borderInterpolate(-2, len, borderType)*cn;
2492             int idxm1 = borderInterpolate(-1, len, borderType)*cn;
2493             int idxp1 = borderInterpolate(3, len, borderType)*cn;
2494             int idxp2 = borderInterpolate(4, len, borderType)*cn;
2495             for (int k = 0; k < cn; k++)
2496             {
2497                 dst[k] = (ufixedpoint16(src[k]) >> 4) * (uint8_t)6 + (ufixedpoint16(src[k + cn]) >> 2) + (ufixedpoint16(src[k + idxm1]) >> 2) + (ufixedpoint16(src[k + 2 * cn]) >> 4) + (ufixedpoint16(src[k + idxm2]) >> 4);
2498                 dst[k + cn] = (ufixedpoint16(src[k + cn]) >> 4) * (uint8_t)6 + (ufixedpoint16(src[k]) >> 2) + (ufixedpoint16(src[k + 2 * cn]) >> 2) + (ufixedpoint16(src[k + idxm1]) >> 4) + (ufixedpoint16(src[k + idxp1]) >> 4);
2499                 dst[k + 2 * cn] = (ufixedpoint16(src[k + 2 * cn]) >> 4) * (uint8_t)6 + (ufixedpoint16(src[k + cn]) >> 2) + (ufixedpoint16(src[k + idxp1]) >> 2) + (ufixedpoint16(src[k]) >> 4) + (ufixedpoint16(src[k + idxp2]) >> 4);
2500             }
2501         }
2502     }
2503     else
2504     {
2505         // Points that fall left from border
2506         for (int k = 0; k < cn; k++)
2507         {
2508             dst[k] = (ufixedpoint16(src[k]) >> 4) * (uint8_t)6 + (ufixedpoint16(src[cn + k]) >> 2) + (ufixedpoint16(src[2 * cn + k]) >> 4);
2509             dst[k + cn] = (ufixedpoint16(src[cn + k]) >> 4) * (uint8_t)6 + (ufixedpoint16(src[k]) >> 2) + (ufixedpoint16(src[2 * cn + k]) >> 2) + (ufixedpoint16(src[3 * cn + k]) >> 4);
2510         }
2511         if (borderType != BORDER_CONSTANT)// If BORDER_CONSTANT out of border values are equal to zero and could be skipped
2512         {
2513             int idxm2 = borderInterpolate(-2, len, borderType)*cn;
2514             int idxm1 = borderInterpolate(-1, len, borderType)*cn;
2515             for (int k = 0; k < cn; k++)
2516             {
2517                 dst[k] = dst[k] + (ufixedpoint16(src[idxm2 + k]) >> 4) + (ufixedpoint16(src[idxm1 + k]) >> 2);
2518                 dst[k + cn] = dst[k + cn] + (ufixedpoint16(src[idxm1 + k]) >> 4);
2519             }
2520         }
2521
2522         src += 2 * cn; dst += 2 * cn;
2523         int i = 2 * cn, lencn = (len - 2)*cn;
2524         v_uint16x8 v_6 = v_setall_u16(6);
2525         for (; i <= lencn - 16; i += 16, src += 16, dst += 16)
2526         {
2527             v_uint16x8 v_src00, v_src01, v_src10, v_src11, v_src20, v_src21, v_src30, v_src31, v_src40, v_src41;
2528             v_expand(v_load(src - 2*cn), v_src00, v_src01);
2529             v_expand(v_load(src - cn), v_src10, v_src11);
2530             v_expand(v_load(src), v_src20, v_src21);
2531             v_expand(v_load(src + cn), v_src30, v_src31);
2532             v_expand(v_load(src + 2*cn), v_src40, v_src41);
2533             v_store((uint16_t*)dst, (v_src20 * v_6 + ((v_src10 + v_src30) << 2) + v_src00 + v_src40) << 4);
2534             v_store((uint16_t*)dst + 8, (v_src21 * v_6 + ((v_src11 + v_src31) << 2) + v_src01 + v_src41) << 4);
2535         }
2536         for (; i < lencn; i++, src++, dst++)
2537             *((uint16_t*)dst) = (uint16_t(src[0]) * 6 + ((uint16_t(src[-cn]) + uint16_t(src[cn])) << 2) + uint16_t(src[-2 * cn]) + uint16_t(src[2 * cn])) << 4;
2538
2539         // Points that fall right from border
2540         for (int k = 0; k < cn; k++)
2541         {
2542             dst[k] = (ufixedpoint16(src[k]) >> 4) * (uint8_t)6 + (ufixedpoint16(src[k - cn]) >> 2) + (ufixedpoint16(src[k + cn]) >> 2) + (ufixedpoint16(src[k - 2 * cn]) >> 4);
2543             dst[k + cn] = (ufixedpoint16(src[k + cn]) >> 4) * (uint8_t)6 + (ufixedpoint16(src[k]) >> 2) + (ufixedpoint16(src[k - cn]) >> 4);
2544         }
2545         if (borderType != BORDER_CONSTANT)// If BORDER_CONSTANT out of border values are equal to zero and could be skipped
2546         {
2547             int idxp1 = (borderInterpolate(len, len, borderType) - (len - 2))*cn;
2548             int idxp2 = (borderInterpolate(len + 1, len, borderType) - (len - 2))*cn;
2549             for (int k = 0; k < cn; k++)
2550             {
2551                 dst[k] = dst[k] + (ufixedpoint16(src[idxp1 + k]) >> 4);
2552                 dst[k + cn] = dst[k + cn] + (ufixedpoint16(src[idxp1 + k]) >> 2) + (ufixedpoint16(src[idxp2 + k]) >> 4);
2553             }
2554         }
2555     }
2556 }
2557 template <typename ET, typename FT>
2558 void hlineSmooth5Nabcba(const ET* src, int cn, const FT* m, int, FT* dst, int len, int borderType)
2559 {
2560     if (len == 1)
2561     {
2562         FT msum = borderType != BORDER_CONSTANT ? ((m[0] + m[1])<<1) + m[2] : m[2];
2563         for (int k = 0; k < cn; k++)
2564             dst[k] = msum * src[k];
2565     }
2566     else if (len == 2)
2567     {
2568         if (borderType == BORDER_CONSTANT)
2569             for (int k = 0; k < cn; k++)
2570             {
2571                 dst[k] = m[2] * src[k] + m[1] * src[k + cn];
2572                 dst[k + cn] = m[1] * src[k] + m[2] * src[k + cn];
2573             }
2574         else
2575         {
2576             int idxm2 = borderInterpolate(-2, len, borderType)*cn;
2577             int idxm1 = borderInterpolate(-1, len, borderType)*cn;
2578             int idxp1 = borderInterpolate(2, len, borderType)*cn;
2579             int idxp2 = borderInterpolate(3, len, borderType)*cn;
2580             for (int k = 0; k < cn; k++)
2581             {
2582                 dst[k] = m[1] * src[k + idxm1] + m[2] * src[k] + m[1] * src[k + cn] + m[0] * src[k + idxp1] + m[0] * src[k + idxm2];
2583                 dst[k + cn] = m[0] * src[k + idxm1] + m[1] * src[k] + m[2] * src[k + cn] + m[1] * src[k + idxp1] + m[0] * src[k + idxp2];
2584             }
2585         }
2586     }
2587     else if (len == 3)
2588     {
2589         if (borderType == BORDER_CONSTANT)
2590             for (int k = 0; k < cn; k++)
2591             {
2592                 dst[k] = m[2] * src[k] + m[1] * src[k + cn] + m[0] * src[k + 2 * cn];
2593                 dst[k + cn] = m[1] * src[k] + m[2] * src[k + cn] + m[1] * src[k + 2 * cn];
2594                 dst[k + 2 * cn] = m[0] * src[k] + m[1] * src[k + cn] + m[2] * src[k + 2 * cn];
2595             }
2596         else
2597         {
2598             int idxm2 = borderInterpolate(-2, len, borderType)*cn;
2599             int idxm1 = borderInterpolate(-1, len, borderType)*cn;
2600             int idxp1 = borderInterpolate(3, len, borderType)*cn;
2601             int idxp2 = borderInterpolate(4, len, borderType)*cn;
2602             for (int k = 0; k < cn; k++)
2603             {
2604                 dst[k] = m[2] * src[k] + m[1] * src[k + cn] + m[0] * src[k + 2 * cn] + m[0] * src[k + idxm2] + m[1] * src[k + idxm1];
2605                 dst[k + cn] = m[1] * src[k] + m[2] * src[k + cn] + m[1] * src[k + 2 * cn] + m[0] * src[k + idxm1] + m[0] * src[k + idxp1];
2606                 dst[k + 2 * cn] = m[0] * src[k] + m[1] * src[k + cn] + m[2] * src[k + 2 * cn] + m[1] * src[k + idxp1] + m[0] * src[k + idxp2];
2607             }
2608         }
2609     }
2610     else
2611     {
2612         // Points that fall left from border
2613         for (int k = 0; k < cn; k++)
2614         {
2615             dst[k] = m[2] * src[k] + m[1] * src[cn + k] + m[0] * src[2 * cn + k];
2616             dst[k + cn] = m[1] * src[k] + m[2] * src[cn + k] + m[1] * src[2 * cn + k] + m[0] * src[3 * cn + k];
2617         }
2618         if (borderType != BORDER_CONSTANT)// If BORDER_CONSTANT out of border values are equal to zero and could be skipped
2619         {
2620             int idxm2 = borderInterpolate(-2, len, borderType)*cn;
2621             int idxm1 = borderInterpolate(-1, len, borderType)*cn;
2622             for (int k = 0; k < cn; k++)
2623             {
2624                 dst[k] = dst[k] + m[0] * src[idxm2 + k] + m[1] * src[idxm1 + k];
2625                 dst[k + cn] = dst[k + cn] + m[0] * src[idxm1 + k];
2626             }
2627         }
2628
2629         src += 2 * cn; dst += 2 * cn;
2630         for (int i = 2 * cn; i < (len - 2)*cn; i++, src++, dst++)
2631             *dst = m[0] * src[-2 * cn] + m[1] * src[-cn] + m[2] * src[0] + m[3] * src[cn] + m[4] * src[2 * cn];
2632
2633         // Points that fall right from border
2634         for (int k = 0; k < cn; k++)
2635         {
2636             dst[k] = m[0] * src[k - 2 * cn] + m[1] * src[k - cn] + m[2] * src[k] + m[3] * src[k + cn];
2637             dst[k + cn] = m[0] * src[k - cn] + m[1] * src[k] + m[2] * src[k + cn];
2638         }
2639         if (borderType != BORDER_CONSTANT)// If BORDER_CONSTANT out of border values are equal to zero and could be skipped
2640         {
2641             int idxp1 = (borderInterpolate(len, len, borderType) - (len - 2))*cn;
2642             int idxp2 = (borderInterpolate(len + 1, len, borderType) - (len - 2))*cn;
2643             for (int k = 0; k < cn; k++)
2644             {
2645                 dst[k] = dst[k] + m[0] * src[idxp1 + k];
2646                 dst[k + cn] = dst[k + cn] + m[1] * src[idxp1 + k] + m[0] * src[idxp2 + k];
2647             }
2648         }
2649     }
2650 }
2651 template <>
2652 void hlineSmooth5Nabcba<uint8_t, ufixedpoint16>(const uint8_t* src, int cn, const ufixedpoint16* m, int, ufixedpoint16* dst, int len, int borderType)
2653 {
2654     if (len == 1)
2655     {
2656         ufixedpoint16 msum = borderType != BORDER_CONSTANT ? ((m[0] + m[1]) << 1) + m[2] : m[2];
2657         for (int k = 0; k < cn; k++)
2658             dst[k] = msum * src[k];
2659     }
2660     else if (len == 2)
2661     {
2662         if (borderType == BORDER_CONSTANT)
2663             for (int k = 0; k < cn; k++)
2664             {
2665                 dst[k] = m[2] * src[k] + m[1] * src[k + cn];
2666                 dst[k + cn] = m[1] * src[k] + m[2] * src[k + cn];
2667             }
2668         else
2669         {
2670             int idxm2 = borderInterpolate(-2, len, borderType)*cn;
2671             int idxm1 = borderInterpolate(-1, len, borderType)*cn;
2672             int idxp1 = borderInterpolate(2, len, borderType)*cn;
2673             int idxp2 = borderInterpolate(3, len, borderType)*cn;
2674             for (int k = 0; k < cn; k++)
2675             {
2676                 ((uint16_t*)dst)[k] = ((uint16_t*)m)[1] * ((uint16_t)(src[k + idxm1]) + (uint16_t)(src[k + cn])) + ((uint16_t*)m)[2] * src[k] + ((uint16_t*)m)[0] * ((uint16_t)(src[k + idxp1]) + (uint16_t)(src[k + idxm2]));
2677                 ((uint16_t*)dst)[k + cn] = ((uint16_t*)m)[0] * ((uint16_t)(src[k + idxm1]) + (uint16_t)(src[k + idxp2])) + ((uint16_t*)m)[1] * ((uint16_t)(src[k]) + (uint16_t)(src[k + idxp1])) + ((uint16_t*)m)[2] * src[k + cn];
2678             }
2679         }
2680     }
2681     else if (len == 3)
2682     {
2683         if (borderType == BORDER_CONSTANT)
2684             for (int k = 0; k < cn; k++)
2685             {
2686                 dst[k] = m[2] * src[k] + m[1] * src[k + cn] + m[0] * src[k + 2 * cn];
2687                 ((uint16_t*)dst)[k + cn] = ((uint16_t*)m)[1] * ((uint16_t)(src[k]) + (uint16_t)(src[k + 2 * cn])) + ((uint16_t*)m)[2] * src[k + cn];
2688                 dst[k + 2 * cn] = m[0] * src[k] + m[1] * src[k + cn] + m[2] * src[k + 2 * cn];
2689             }
2690         else
2691         {
2692             int idxm2 = borderInterpolate(-2, len, borderType)*cn;
2693             int idxm1 = borderInterpolate(-1, len, borderType)*cn;
2694             int idxp1 = borderInterpolate(3, len, borderType)*cn;
2695             int idxp2 = borderInterpolate(4, len, borderType)*cn;
2696             for (int k = 0; k < cn; k++)
2697             {
2698                 ((uint16_t*)dst)[k] = ((uint16_t*)m)[2] * src[k] + ((uint16_t*)m)[1] * ((uint16_t)(src[k + cn]) + (uint16_t)(src[k + idxm1])) + ((uint16_t*)m)[0] * ((uint16_t)(src[k + 2 * cn]) + (uint16_t)(src[k + idxm2]));
2699                 ((uint16_t*)dst)[k + cn] = ((uint16_t*)m)[2] * src[k + cn] + ((uint16_t*)m)[1] * ((uint16_t)(src[k]) + (uint16_t)(src[k + 2 * cn])) + ((uint16_t*)m)[0] * ((uint16_t)(src[k + idxm1]) + (uint16_t)(src[k + idxp1]));
2700                 ((uint16_t*)dst)[k + 2 * cn] = ((uint16_t*)m)[0] * ((uint16_t)(src[k]) + (uint16_t)(src[k + idxp2])) + ((uint16_t*)m)[1] * ((uint16_t)(src[k + cn]) + (uint16_t)(src[k + idxp1])) + ((uint16_t*)m)[2] * src[k + 2 * cn];
2701             }
2702         }
2703     }
2704     else
2705     {
2706         // Points that fall left from border
2707         if (borderType != BORDER_CONSTANT)// If BORDER_CONSTANT out of border values are equal to zero and could be skipped
2708         {
2709             int idxm2 = borderInterpolate(-2, len, borderType)*cn;
2710             int idxm1 = borderInterpolate(-1, len, borderType)*cn;
2711             for (int k = 0; k < cn; k++)
2712             {
2713                 ((uint16_t*)dst)[k] = ((uint16_t*)m)[2] * src[k] + ((uint16_t*)m)[1] * ((uint16_t)(src[cn + k]) + (uint16_t)(src[idxm1 + k])) + ((uint16_t*)m)[0] * ((uint16_t)(src[2 * cn + k]) + (uint16_t)(src[idxm2 + k]));
2714                 ((uint16_t*)dst)[k + cn] = ((uint16_t*)m)[1] * ((uint16_t)(src[k]) + (uint16_t)(src[2 * cn + k])) + ((uint16_t*)m)[2] * src[cn + k] + ((uint16_t*)m)[0] * ((uint16_t)(src[3 * cn + k]) + (uint16_t)(src[idxm1 + k]));
2715             }
2716         }
2717         else
2718         {
2719             for (int k = 0; k < cn; k++)
2720             {
2721                 dst[k] = m[2] * src[k] + m[1] * src[cn + k] + m[0] * src[2 * cn + k];
2722                 ((uint16_t*)dst)[k + cn] = ((uint16_t*)m)[1] * ((uint16_t)(src[k]) + (uint16_t)(src[2 * cn + k])) + ((uint16_t*)m)[2] * src[cn + k] + ((uint16_t*)m)[0] * src[3 * cn + k];
2723             }
2724         }
2725
2726         src += 2 * cn; dst += 2 * cn;
2727         int i = 2 * cn, lencn = (len - 2)*cn;
2728         v_uint16x8 v_mul0 = v_setall_u16(*((uint16_t*)m));
2729         v_uint16x8 v_mul1 = v_setall_u16(*((uint16_t*)(m + 1)));
2730         v_uint16x8 v_mul2 = v_setall_u16(*((uint16_t*)(m + 2)));
2731         for (; i <= lencn - 16; i += 16, src += 16, dst += 16)
2732         {
2733             v_uint16x8 v_src00, v_src01, v_src10, v_src11, v_src20, v_src21, v_src30, v_src31, v_src40, v_src41;
2734             v_expand(v_load(src - 2 * cn), v_src00, v_src01);
2735             v_expand(v_load(src - cn), v_src10, v_src11);
2736             v_expand(v_load(src), v_src20, v_src21);
2737             v_expand(v_load(src + cn), v_src30, v_src31);
2738             v_expand(v_load(src + 2 * cn), v_src40, v_src41);
2739             v_store((uint16_t*)dst, (v_src00 + v_src40) * v_mul0 + (v_src10 + v_src30)* v_mul1 + v_src20 * v_mul2);
2740             v_store((uint16_t*)dst + 8, (v_src01 + v_src41) * v_mul0 + (v_src11 + v_src31) * v_mul1 + v_src21 * v_mul2);
2741         }
2742         for (; i < lencn; i++, src++, dst++)
2743             *((uint16_t*)dst) = ((uint16_t*)m)[0] * ((uint16_t)(src[-2 * cn]) + (uint16_t)(src[2 * cn])) + ((uint16_t*)m)[1] * ((uint16_t)(src[-cn]) + (uint16_t)(src[cn])) + ((uint16_t*)m)[2] * src[0];
2744
2745         // Points that fall right from border
2746         if (borderType != BORDER_CONSTANT)// If BORDER_CONSTANT out of border values are equal to zero and could be skipped
2747         {
2748             int idxp1 = (borderInterpolate(len, len, borderType) - (len - 2))*cn;
2749             int idxp2 = (borderInterpolate(len + 1, len, borderType) - (len - 2))*cn;
2750             for (int k = 0; k < cn; k++)
2751             {
2752                 ((uint16_t*)dst)[k] = ((uint16_t*)m)[0] * ((uint16_t)(src[k - 2 * cn]) + (uint16_t)(src[idxp1 + k])) + ((uint16_t*)m)[1] * ((uint16_t)(src[k - cn]) + (uint16_t)(src[k + cn])) + ((uint16_t*)m)[2] * src[k];
2753                 ((uint16_t*)dst)[k + cn] = ((uint16_t*)m)[0] * ((uint16_t)(src[k - cn]) + (uint16_t)(src[idxp2 + k])) + ((uint16_t*)m)[1] * ((uint16_t)(src[k]) + (uint16_t)(src[idxp1 + k])) + ((uint16_t*)m)[2] * src[k + cn];
2754             }
2755         }
2756         else
2757         {
2758             for (int k = 0; k < cn; k++)
2759             {
2760                 ((uint16_t*)dst)[k] = ((uint16_t*)m)[0] * src[k - 2 * cn] + ((uint16_t*)m)[1] * ((uint16_t)(src[k - cn]) + (uint16_t)(src[k + cn])) + ((uint16_t*)m)[2] * src[k];
2761                 dst[k + cn] = m[0] * src[k - cn] + m[1] * src[k] + m[2] * src[k + cn];
2762             }
2763         }
2764     }
2765 }
2766 template <typename ET, typename FT>
2767 void hlineSmooth(const ET* src, int cn, const FT* m, int n, FT* dst, int len, int borderType)
2768 {
2769     int pre_shift = n / 2;
2770     int post_shift = n - pre_shift;
2771     int i = 0;
2772     for (; i < min(pre_shift, len); i++, dst += cn) // Points that fall left from border
2773     {
2774         for (int k = 0; k < cn; k++)
2775             dst[k] = m[pre_shift-i] * src[k];
2776         if (borderType != BORDER_CONSTANT)// If BORDER_CONSTANT out of border values are equal to zero and could be skipped
2777             for (int j = i - pre_shift, mid = 0; j < 0; j++, mid++)
2778             {
2779                 int src_idx = borderInterpolate(j, len, borderType);
2780                 for (int k = 0; k < cn; k++)
2781                     dst[k] = dst[k] + m[mid] * src[src_idx*cn + k];
2782             }
2783         int j, mid;
2784         for (j = 1, mid = pre_shift - i + 1; j < min(i + post_shift, len); j++, mid++)
2785             for (int k = 0; k < cn; k++)
2786                 dst[k] = dst[k] + m[mid] * src[j*cn + k];
2787         if (borderType != BORDER_CONSTANT)
2788             for (; j < i + post_shift; j++, mid++)
2789             {
2790                 int src_idx = borderInterpolate(j, len, borderType);
2791                 for (int k = 0; k < cn; k++)
2792                     dst[k] = dst[k] + m[mid] * src[src_idx*cn + k];
2793             }
2794     }
2795     i *= cn;
2796     for (; i < (len - post_shift + 1)*cn; i++, src++, dst++)
2797     {
2798         *dst = m[0] * src[0];
2799         for (int j = 1; j < n; j++)
2800             *dst = *dst + m[j] * src[j*cn];
2801     }
2802     i /= cn;
2803     for (i -= pre_shift; i < len - pre_shift; i++, src += cn, dst += cn) // Points that fall right from border
2804     {
2805         for (int k = 0; k < cn; k++)
2806             dst[k] = m[0] * src[k];
2807         int j = 1;
2808         for (; j < len - i; j++)
2809             for (int k = 0; k < cn; k++)
2810                 dst[k] = dst[k] + m[j] * src[j*cn + k];
2811         if (borderType != BORDER_CONSTANT)// If BORDER_CONSTANT out of border values are equal to zero and could be skipped
2812             for (; j < n; j++)
2813             {
2814                 int src_idx = borderInterpolate(i + j, len, borderType) - i;
2815                 for (int k = 0; k < cn; k++)
2816                     dst[k] = dst[k] + m[j] * src[src_idx*cn + k];
2817             }
2818     }
2819 }
2820 template <>
2821 void hlineSmooth<uint8_t, ufixedpoint16>(const uint8_t* src, int cn, const ufixedpoint16* m, int n, ufixedpoint16* dst, int len, int borderType)
2822 {
2823     int pre_shift = n / 2;
2824     int post_shift = n - pre_shift;
2825     int i = 0;
2826     for (; i < min(pre_shift, len); i++, dst += cn) // Points that fall left from border
2827     {
2828         for (int k = 0; k < cn; k++)
2829             dst[k] = m[pre_shift - i] * src[k];
2830         if (borderType != BORDER_CONSTANT)// If BORDER_CONSTANT out of border values are equal to zero and could be skipped
2831             for (int j = i - pre_shift, mid = 0; j < 0; j++, mid++)
2832             {
2833                 int src_idx = borderInterpolate(j, len, borderType);
2834                 for (int k = 0; k < cn; k++)
2835                     dst[k] = dst[k] + m[mid] * src[src_idx*cn + k];
2836             }
2837         int j, mid;
2838         for (j = 1, mid = pre_shift - i + 1; j < min(i + post_shift, len); j++, mid++)
2839             for (int k = 0; k < cn; k++)
2840                 dst[k] = dst[k] + m[mid] * src[j*cn + k];
2841         if (borderType != BORDER_CONSTANT)
2842             for (; j < i + post_shift; j++, mid++)
2843             {
2844                 int src_idx = borderInterpolate(j, len, borderType);
2845                 for (int k = 0; k < cn; k++)
2846                     dst[k] = dst[k] + m[mid] * src[src_idx*cn + k];
2847             }
2848     }
2849     i *= cn;
2850     int lencn = (len - post_shift + 1)*cn;
2851     for (; i <= lencn - 16; i+=16, src+=16, dst+=16)
2852     {
2853         v_uint16x8 v_src0, v_src1;
2854         v_uint16x8 v_mul = v_setall_u16(*((uint16_t*)m));
2855         v_expand(v_load(src), v_src0, v_src1);
2856         v_uint16x8 v_res0 = v_src0 * v_mul;
2857         v_uint16x8 v_res1 = v_src1 * v_mul;
2858         for (int j = 1; j < n; j++)
2859         {
2860             v_mul = v_setall_u16(*((uint16_t*)(m + j)));
2861             v_expand(v_load(src + j * cn), v_src0, v_src1);
2862             v_res0 += v_src0 * v_mul;
2863             v_res1 += v_src1 * v_mul;
2864         }
2865         v_store((uint16_t*)dst, v_res0);
2866         v_store((uint16_t*)dst+8, v_res1);
2867     }
2868     for (; i < lencn; i++, src++, dst++)
2869     {
2870             *dst = m[0] * src[0];
2871             for (int j = 1; j < n; j++)
2872                 *dst = *dst + m[j] * src[j*cn];
2873     }
2874     i /= cn;
2875     for (i -= pre_shift; i < len - pre_shift; i++, src += cn, dst += cn) // Points that fall right from border
2876     {
2877         for (int k = 0; k < cn; k++)
2878             dst[k] = m[0] * src[k];
2879         int j = 1;
2880         for (; j < len - i; j++)
2881             for (int k = 0; k < cn; k++)
2882                 dst[k] = dst[k] + m[j] * src[j*cn + k];
2883         if (borderType != BORDER_CONSTANT)// If BORDER_CONSTANT out of border values are equal to zero and could be skipped
2884             for (; j < n; j++)
2885             {
2886                 int src_idx = borderInterpolate(i + j, len, borderType) - i;
2887                 for (int k = 0; k < cn; k++)
2888                     dst[k] = dst[k] + m[j] * src[src_idx*cn + k];
2889             }
2890     }
2891 }
2892 template <typename ET, typename FT>
2893 void hlineSmoothONa_yzy_a(const ET* src, int cn, const FT* m, int n, FT* dst, int len, int borderType)
2894 {
2895     int pre_shift = n / 2;
2896     int post_shift = n - pre_shift;
2897     int i = 0;
2898     for (; i < min(pre_shift, len); i++, dst += cn) // Points that fall left from border
2899     {
2900         for (int k = 0; k < cn; k++)
2901             dst[k] = m[pre_shift - i] * src[k];
2902         if (borderType != BORDER_CONSTANT)// If BORDER_CONSTANT out of border values are equal to zero and could be skipped
2903             for (int j = i - pre_shift, mid = 0; j < 0; j++, mid++)
2904             {
2905                 int src_idx = borderInterpolate(j, len, borderType);
2906                 for (int k = 0; k < cn; k++)
2907                     dst[k] = dst[k] + m[mid] * src[src_idx*cn + k];
2908             }
2909         int j, mid;
2910         for (j = 1, mid = pre_shift - i + 1; j < min(i + post_shift, len); j++, mid++)
2911             for (int k = 0; k < cn; k++)
2912                 dst[k] = dst[k] + m[mid] * src[j*cn + k];
2913         if (borderType != BORDER_CONSTANT)
2914             for (; j < i + post_shift; j++, mid++)
2915             {
2916                 int src_idx = borderInterpolate(j, len, borderType);
2917                 for (int k = 0; k < cn; k++)
2918                     dst[k] = dst[k] + m[mid] * src[src_idx*cn + k];
2919             }
2920     }
2921     i *= cn;
2922     for (; i < (len - post_shift + 1)*cn; i++, src++, dst++)
2923     {
2924         *dst = m[pre_shift] * src[pre_shift*cn];
2925         for (int j = 0; j < pre_shift; j++)
2926             *dst = *dst + m[j] * src[j*cn] + m[j] * src[(n-1-j)*cn];
2927     }
2928     i /= cn;
2929     for (i -= pre_shift; i < len - pre_shift; i++, src += cn, dst += cn) // Points that fall right from border
2930     {
2931         for (int k = 0; k < cn; k++)
2932             dst[k] = m[0] * src[k];
2933         int j = 1;
2934         for (; j < len - i; j++)
2935             for (int k = 0; k < cn; k++)
2936                 dst[k] = dst[k] + m[j] * src[j*cn + k];
2937         if (borderType != BORDER_CONSTANT)// If BORDER_CONSTANT out of border values are equal to zero and could be skipped
2938             for (; j < n; j++)
2939             {
2940                 int src_idx = borderInterpolate(i + j, len, borderType) - i;
2941                 for (int k = 0; k < cn; k++)
2942                     dst[k] = dst[k] + m[j] * src[src_idx*cn + k];
2943             }
2944     }
2945 }
2946 template <>
2947 void hlineSmoothONa_yzy_a<uint8_t, ufixedpoint16>(const uint8_t* src, int cn, const ufixedpoint16* m, int n, ufixedpoint16* dst, int len, int borderType)
2948 {
2949     int pre_shift = n / 2;
2950     int post_shift = n - pre_shift;
2951     int i = 0;
2952     for (; i < min(pre_shift, len); i++, dst += cn) // Points that fall left from border
2953     {
2954         for (int k = 0; k < cn; k++)
2955             dst[k] = m[pre_shift - i] * src[k];
2956         if (borderType != BORDER_CONSTANT)// If BORDER_CONSTANT out of border values are equal to zero and could be skipped
2957             for (int j = i - pre_shift, mid = 0; j < 0; j++, mid++)
2958             {
2959                 int src_idx = borderInterpolate(j, len, borderType);
2960                 for (int k = 0; k < cn; k++)
2961                     dst[k] = dst[k] + m[mid] * src[src_idx*cn + k];
2962             }
2963         int j, mid;
2964         for (j = 1, mid = pre_shift - i + 1; j < min(i + post_shift, len); j++, mid++)
2965             for (int k = 0; k < cn; k++)
2966                 dst[k] = dst[k] + m[mid] * src[j*cn + k];
2967         if (borderType != BORDER_CONSTANT)
2968             for (; j < i + post_shift; j++, mid++)
2969             {
2970                 int src_idx = borderInterpolate(j, len, borderType);
2971                 for (int k = 0; k < cn; k++)
2972                     dst[k] = dst[k] + m[mid] * src[src_idx*cn + k];
2973             }
2974     }
2975     i *= cn;
2976     int lencn = (len - post_shift + 1)*cn;
2977     for (; i <= lencn - 16; i += 16, src += 16, dst += 16)
2978     {
2979         v_uint16x8 v_src00, v_src01, v_srcN00, v_srcN01;
2980
2981         v_uint16x8 v_mul = v_setall_u16(*((uint16_t*)(m + pre_shift)));
2982         v_expand(v_load(src + pre_shift * cn), v_src00, v_src01);
2983         v_uint16x8 v_res0 = v_src00 * v_mul;
2984         v_uint16x8 v_res1 = v_src01 * v_mul;
2985         for (int j = 0; j < pre_shift; j ++)
2986         {
2987             v_mul = v_setall_u16(*((uint16_t*)(m + j)));
2988             v_expand(v_load(src + j * cn), v_src00, v_src01);
2989             v_expand(v_load(src + (n - 1 - j)*cn), v_srcN00, v_srcN01);
2990             v_res0 += (v_src00 + v_srcN00) * v_mul;
2991             v_res1 += (v_src01 + v_srcN01) * v_mul;
2992         }
2993
2994         v_store((uint16_t*)dst, v_res0);
2995         v_store((uint16_t*)dst + 8, v_res1);
2996     }
2997     for (; i < lencn; i++, src++, dst++)
2998     {
2999         *dst = m[pre_shift] * src[pre_shift*cn];
3000         for (int j = 0; j < pre_shift; j++)
3001             *dst = *dst + m[j] * src[j*cn] + m[j] * src[(n - 1 - j)*cn];
3002     }
3003     i /= cn;
3004     for (i -= pre_shift; i < len - pre_shift; i++, src += cn, dst += cn) // Points that fall right from border
3005     {
3006         for (int k = 0; k < cn; k++)
3007             dst[k] = m[0] * src[k];
3008         int j = 1;
3009         for (; j < len - i; j++)
3010             for (int k = 0; k < cn; k++)
3011                 dst[k] = dst[k] + m[j] * src[j*cn + k];
3012         if (borderType != BORDER_CONSTANT)// If BORDER_CONSTANT out of border values are equal to zero and could be skipped
3013             for (; j < n; j++)
3014             {
3015                 int src_idx = borderInterpolate(i + j, len, borderType) - i;
3016                 for (int k = 0; k < cn; k++)
3017                     dst[k] = dst[k] + m[j] * src[src_idx*cn + k];
3018             }
3019     }
3020 }
3021 template <typename ET, typename FT>
3022 void vlineSmooth1N(const FT* const * src, const FT* m, int, ET* dst, int len)
3023 {
3024     const FT* src0 = src[0];
3025     for (int i = 0; i < len; i++)
3026         dst[i] = *m * src0[i];
3027 }
3028 template <>
3029 void vlineSmooth1N<uint8_t, ufixedpoint16>(const ufixedpoint16* const * src, const ufixedpoint16* m, int, uint8_t* dst, int len)
3030 {
3031     const ufixedpoint16* src0 = src[0];
3032     v_uint16x8 v_mul = v_setall_u16(*((uint16_t*)m));
3033 #if CV_SSE2
3034     v_uint16x8 v_1 = v_setall_u16(1);
3035     v_mul += v_mul;
3036 #endif
3037     int i = 0;
3038     for (; i <= len - 16; i += 16)
3039     {
3040         v_uint16x8 v_src0 = v_load((uint16_t*)src0 + i);
3041         v_uint16x8 v_src1 = v_load((uint16_t*)src0 + i + 8);
3042         v_uint8x16 v_res;
3043 #if CV_SSE2
3044         v_res.val = _mm_packus_epi16(_mm_srli_epi16(_mm_add_epi16(v_1.val, _mm_mulhi_epu16(v_src0.val, v_mul.val)),1),
3045                                      _mm_srli_epi16(_mm_add_epi16(v_1.val, _mm_mulhi_epu16(v_src1.val, v_mul.val)),1));
3046 #else
3047         v_uint32x4 v_res0, v_res1, v_res2, v_res3;
3048         v_mul_expand(v_src0, v_mul, v_res0, v_res1);
3049         v_mul_expand(v_src1, v_mul, v_res2, v_res3);
3050         v_res = v_pack(v_rshr_pack<16>(v_res0, v_res1), v_rshr_pack<16>(v_res2, v_res3));
3051 #endif
3052         v_store(dst + i, v_res);
3053     }
3054     for (; i < len; i++)
3055         dst[i] = m[0] * src0[i];
3056 }
3057 template <typename ET, typename FT>
3058 void vlineSmooth1N1(const FT* const * src, const FT*, int, ET* dst, int len)
3059 {
3060     const FT* src0 = src[0];
3061     for (int i = 0; i < len; i++)
3062         dst[i] = src0[i];
3063 }
3064 template <>
3065 void vlineSmooth1N1<uint8_t, ufixedpoint16>(const ufixedpoint16* const * src, const ufixedpoint16*, int, uint8_t* dst, int len)
3066 {
3067     const ufixedpoint16* src0 = src[0];
3068     int i = 0;
3069     for (; i <= len - 8; i += 8)
3070         v_rshr_pack_store<8>(dst + i, v_load((uint16_t*)(src0 + i)));
3071     for (; i < len; i++)
3072         dst[i] = src0[i];
3073 }
3074 template <typename ET, typename FT>
3075 void vlineSmooth3N(const FT* const * src, const FT* m, int, ET* dst, int len)
3076 {
3077     for (int i = 0; i < len; i++)
3078         dst[i] = m[0] * src[0][i] + m[1] * src[1][i] + m[2] * src[2][i];
3079 }
3080 template <>
3081 void vlineSmooth3N<uint8_t, ufixedpoint16>(const ufixedpoint16* const * src, const ufixedpoint16* m, int, uint8_t* dst, int len)
3082 {
3083     int i = 0;
3084     static const v_int16x8 v_128 = v_reinterpret_as_s16(v_setall_u16((uint16_t)1 << 15));
3085     v_int32x4 v_128_4 = v_setall_s32(128 << 16);
3086     if (len > 7)
3087     {
3088         ufixedpoint32 val[] = { (m[0] + m[1] + m[2]) * ufixedpoint16((uint8_t)128) };
3089         v_128_4 = v_setall_s32(*((int32_t*)val));
3090     }
3091     v_int16x8 v_mul01 = v_reinterpret_as_s16(v_setall_u32(*((uint32_t*)m)));
3092     v_int16x8 v_mul2 = v_reinterpret_as_s16(v_setall_u16(*((uint16_t*)(m + 2))));
3093     for (; i <= len - 32; i += 32)
3094     {
3095         v_int16x8 v_src00, v_src10, v_src01, v_src11, v_src02, v_src12, v_src03, v_src13;
3096         v_int16x8 v_tmp0, v_tmp1;
3097
3098         v_src00 = v_load((int16_t*)(src[0]) + i);
3099         v_src01 = v_load((int16_t*)(src[0]) + i + 8);
3100         v_src02 = v_load((int16_t*)(src[0]) + i + 16);
3101         v_src03 = v_load((int16_t*)(src[0]) + i + 24);
3102         v_src10 = v_load((int16_t*)(src[1]) + i);
3103         v_src11 = v_load((int16_t*)(src[1]) + i + 8);
3104         v_src12 = v_load((int16_t*)(src[1]) + i + 16);
3105         v_src13 = v_load((int16_t*)(src[1]) + i + 24);
3106         v_zip(v_add_wrap(v_src00, v_128), v_add_wrap(v_src10, v_128), v_tmp0, v_tmp1);
3107         v_int32x4 v_res0 = v_dotprod(v_tmp0, v_mul01);
3108         v_int32x4 v_res1 = v_dotprod(v_tmp1, v_mul01);
3109         v_zip(v_add_wrap(v_src01, v_128), v_add_wrap(v_src11, v_128), v_tmp0, v_tmp1);
3110         v_int32x4 v_res2 = v_dotprod(v_tmp0, v_mul01);
3111         v_int32x4 v_res3 = v_dotprod(v_tmp1, v_mul01);
3112         v_zip(v_add_wrap(v_src02, v_128), v_add_wrap(v_src12, v_128), v_tmp0, v_tmp1);
3113         v_int32x4 v_res4 = v_dotprod(v_tmp0, v_mul01);
3114         v_int32x4 v_res5 = v_dotprod(v_tmp1, v_mul01);
3115         v_zip(v_add_wrap(v_src03, v_128), v_add_wrap(v_src13, v_128), v_tmp0, v_tmp1);
3116         v_int32x4 v_res6 = v_dotprod(v_tmp0, v_mul01);
3117         v_int32x4 v_res7 = v_dotprod(v_tmp1, v_mul01);
3118
3119         v_int32x4 v_resj0, v_resj1;
3120         v_src00 = v_load((int16_t*)(src[2]) + i);
3121         v_src01 = v_load((int16_t*)(src[2]) + i + 8);
3122         v_src02 = v_load((int16_t*)(src[2]) + i + 16);
3123         v_src03 = v_load((int16_t*)(src[2]) + i + 24);
3124         v_mul_expand(v_add_wrap(v_src00, v_128), v_mul2, v_resj0, v_resj1);
3125         v_res0 += v_resj0;
3126         v_res1 += v_resj1;
3127         v_mul_expand(v_add_wrap(v_src01, v_128), v_mul2, v_resj0, v_resj1);
3128         v_res2 += v_resj0;
3129         v_res3 += v_resj1;
3130         v_mul_expand(v_add_wrap(v_src02, v_128), v_mul2, v_resj0, v_resj1);
3131         v_res4 += v_resj0;
3132         v_res5 += v_resj1;
3133         v_mul_expand(v_add_wrap(v_src03, v_128), v_mul2, v_resj0, v_resj1);
3134         v_res6 += v_resj0;
3135         v_res7 += v_resj1;
3136
3137         v_res0 += v_128_4;
3138         v_res1 += v_128_4;
3139         v_res2 += v_128_4;
3140         v_res3 += v_128_4;
3141         v_res4 += v_128_4;
3142         v_res5 += v_128_4;
3143         v_res6 += v_128_4;
3144         v_res7 += v_128_4;
3145
3146         v_store(dst + i     , v_pack(v_reinterpret_as_u16(v_rshr_pack<16>(v_res0, v_res1)),
3147                                      v_reinterpret_as_u16(v_rshr_pack<16>(v_res2, v_res3))));
3148         v_store(dst + i + 16, v_pack(v_reinterpret_as_u16(v_rshr_pack<16>(v_res4, v_res5)),
3149                                      v_reinterpret_as_u16(v_rshr_pack<16>(v_res6, v_res7))));
3150     }
3151     for (; i < len; i++)
3152         dst[i] = m[0] * src[0][i] + m[1] * src[1][i] + m[2] * src[2][i];
3153 }
3154 template <typename ET, typename FT>
3155 void vlineSmooth3N121(const FT* const * src, const FT*, int, ET* dst, int len)
3156 {
3157     for (int i = 0; i < len; i++)
3158         dst[i] = (FT::WT(src[0][i]) >> 2) + (FT::WT(src[2][i]) >> 2) + (FT::WT(src[1][i]) >> 1);
3159 }
3160 template <>
3161 void vlineSmooth3N121<uint8_t, ufixedpoint16>(const ufixedpoint16* const * src, const ufixedpoint16*, int, uint8_t* dst, int len)
3162 {
3163     int i = 0;
3164     for (; i <= len - 16; i += 16)
3165     {
3166         v_uint32x4 v_src00, v_src01, v_src02, v_src03, v_src10, v_src11, v_src12, v_src13, v_src20, v_src21, v_src22, v_src23;
3167         v_expand(v_load((uint16_t*)(src[0]) + i), v_src00, v_src01);
3168         v_expand(v_load((uint16_t*)(src[0]) + i + 8), v_src02, v_src03);
3169         v_expand(v_load((uint16_t*)(src[1]) + i), v_src10, v_src11);
3170         v_expand(v_load((uint16_t*)(src[1]) + i + 8), v_src12, v_src13);
3171         v_expand(v_load((uint16_t*)(src[2]) + i), v_src20, v_src21);
3172         v_expand(v_load((uint16_t*)(src[2]) + i + 8), v_src22, v_src23);
3173         v_store(dst + i, v_pack(v_rshr_pack<10>(v_src00 + v_src20 + (v_src10 + v_src10), v_src01 + v_src21 + (v_src11 + v_src11)),
3174                                 v_rshr_pack<10>(v_src02 + v_src22 + (v_src12 + v_src12), v_src03 + v_src23 + (v_src13 + v_src13))));
3175     }
3176     for (; i < len; i++)
3177         dst[i] = (((uint32_t)(((uint16_t*)(src[0]))[i]) + (uint32_t)(((uint16_t*)(src[2]))[i]) + ((uint32_t)(((uint16_t*)(src[1]))[i]) << 1)) + (1 << 9)) >> 10;
3178 }
3179 template <typename ET, typename FT>
3180 void vlineSmooth5N(const FT* const * src, const FT* m, int, ET* dst, int len)
3181 {
3182     for (int i = 0; i < len; i++)
3183         dst[i] = m[0] * src[0][i] + m[1] * src[1][i] + m[2] * src[2][i] + m[3] * src[3][i] + m[4] * src[4][i];
3184 }
3185 template <>
3186 void vlineSmooth5N<uint8_t, ufixedpoint16>(const ufixedpoint16* const * src, const ufixedpoint16* m, int, uint8_t* dst, int len)
3187 {
3188     int i = 0;
3189     static const v_int16x8 v_128 = v_reinterpret_as_s16(v_setall_u16((uint16_t)1 << 15));
3190     v_int32x4 v_128_4 = v_setall_s32(128 << 16);
3191     if (len > 7)
3192     {
3193         ufixedpoint32 val[] = { (m[0] + m[1] + m[2] + m[3] + m[4]) * ufixedpoint16((uint8_t)128) };
3194         v_128_4 = v_setall_s32(*((int32_t*)val));
3195     }
3196     v_int16x8 v_mul01 = v_reinterpret_as_s16(v_setall_u32(*((uint32_t*)m)));
3197     v_int16x8 v_mul23 = v_reinterpret_as_s16(v_setall_u32(*((uint32_t*)(m + 2))));
3198     v_int16x8 v_mul4 = v_reinterpret_as_s16(v_setall_u16(*((uint16_t*)(m + 4))));
3199     for (; i <= len - 32; i += 32)
3200     {
3201         v_int16x8 v_src00, v_src10, v_src01, v_src11, v_src02, v_src12, v_src03, v_src13;
3202         v_int16x8 v_tmp0, v_tmp1;
3203
3204         v_src00 = v_load((int16_t*)(src[0]) + i);
3205         v_src01 = v_load((int16_t*)(src[0]) + i + 8);
3206         v_src02 = v_load((int16_t*)(src[0]) + i + 16);
3207         v_src03 = v_load((int16_t*)(src[0]) + i + 24);
3208         v_src10 = v_load((int16_t*)(src[1]) + i);
3209         v_src11 = v_load((int16_t*)(src[1]) + i + 8);
3210         v_src12 = v_load((int16_t*)(src[1]) + i + 16);
3211         v_src13 = v_load((int16_t*)(src[1]) + i + 24);
3212         v_zip(v_add_wrap(v_src00, v_128), v_add_wrap(v_src10, v_128), v_tmp0, v_tmp1);
3213         v_int32x4 v_res0 = v_dotprod(v_tmp0, v_mul01);
3214         v_int32x4 v_res1 = v_dotprod(v_tmp1, v_mul01);
3215         v_zip(v_add_wrap(v_src01, v_128), v_add_wrap(v_src11, v_128), v_tmp0, v_tmp1);
3216         v_int32x4 v_res2 = v_dotprod(v_tmp0, v_mul01);
3217         v_int32x4 v_res3 = v_dotprod(v_tmp1, v_mul01);
3218         v_zip(v_add_wrap(v_src02, v_128), v_add_wrap(v_src12, v_128), v_tmp0, v_tmp1);
3219         v_int32x4 v_res4 = v_dotprod(v_tmp0, v_mul01);
3220         v_int32x4 v_res5 = v_dotprod(v_tmp1, v_mul01);
3221         v_zip(v_add_wrap(v_src03, v_128), v_add_wrap(v_src13, v_128), v_tmp0, v_tmp1);
3222         v_int32x4 v_res6 = v_dotprod(v_tmp0, v_mul01);
3223         v_int32x4 v_res7 = v_dotprod(v_tmp1, v_mul01);
3224
3225         v_src00 = v_load((int16_t*)(src[2]) + i);
3226         v_src01 = v_load((int16_t*)(src[2]) + i + 8);
3227         v_src02 = v_load((int16_t*)(src[2]) + i + 16);
3228         v_src03 = v_load((int16_t*)(src[2]) + i + 24);
3229         v_src10 = v_load((int16_t*)(src[3]) + i);
3230         v_src11 = v_load((int16_t*)(src[3]) + i + 8);
3231         v_src12 = v_load((int16_t*)(src[3]) + i + 16);
3232         v_src13 = v_load((int16_t*)(src[3]) + i + 24);
3233         v_zip(v_add_wrap(v_src00, v_128), v_add_wrap(v_src10, v_128), v_tmp0, v_tmp1);
3234         v_res0 += v_dotprod(v_tmp0, v_mul23);
3235         v_res1 += v_dotprod(v_tmp1, v_mul23);
3236         v_zip(v_add_wrap(v_src01, v_128), v_add_wrap(v_src11, v_128), v_tmp0, v_tmp1);
3237         v_res2 += v_dotprod(v_tmp0, v_mul23);
3238         v_res3 += v_dotprod(v_tmp1, v_mul23);
3239         v_zip(v_add_wrap(v_src02, v_128), v_add_wrap(v_src12, v_128), v_tmp0, v_tmp1);
3240         v_res4 += v_dotprod(v_tmp0, v_mul23);
3241         v_res5 += v_dotprod(v_tmp1, v_mul23);
3242         v_zip(v_add_wrap(v_src03, v_128), v_add_wrap(v_src13, v_128), v_tmp0, v_tmp1);
3243         v_res6 += v_dotprod(v_tmp0, v_mul23);
3244         v_res7 += v_dotprod(v_tmp1, v_mul23);
3245
3246         v_int32x4 v_resj0, v_resj1;
3247         v_src00 = v_load((int16_t*)(src[4]) + i);
3248         v_src01 = v_load((int16_t*)(src[4]) + i + 8);
3249         v_src02 = v_load((int16_t*)(src[4]) + i + 16);
3250         v_src03 = v_load((int16_t*)(src[4]) + i + 24);
3251         v_mul_expand(v_add_wrap(v_src00, v_128), v_mul4, v_resj0, v_resj1);
3252         v_res0 += v_resj0;
3253         v_res1 += v_resj1;
3254         v_mul_expand(v_add_wrap(v_src01, v_128), v_mul4, v_resj0, v_resj1);
3255         v_res2 += v_resj0;
3256         v_res3 += v_resj1;
3257         v_mul_expand(v_add_wrap(v_src02, v_128), v_mul4, v_resj0, v_resj1);
3258         v_res4 += v_resj0;
3259         v_res5 += v_resj1;
3260         v_mul_expand(v_add_wrap(v_src03, v_128), v_mul4, v_resj0, v_resj1);
3261         v_res6 += v_resj0;
3262         v_res7 += v_resj1;
3263
3264         v_res0 += v_128_4;
3265         v_res1 += v_128_4;
3266         v_res2 += v_128_4;
3267         v_res3 += v_128_4;
3268         v_res4 += v_128_4;
3269         v_res5 += v_128_4;
3270         v_res6 += v_128_4;
3271         v_res7 += v_128_4;
3272
3273         v_store(dst + i     , v_pack(v_reinterpret_as_u16(v_rshr_pack<16>(v_res0, v_res1)),
3274                                      v_reinterpret_as_u16(v_rshr_pack<16>(v_res2, v_res3))));
3275         v_store(dst + i + 16, v_pack(v_reinterpret_as_u16(v_rshr_pack<16>(v_res4, v_res5)),
3276                                      v_reinterpret_as_u16(v_rshr_pack<16>(v_res6, v_res7))));
3277     }
3278     for (; i < len; i++)
3279         dst[i] = m[0] * src[0][i] + m[1] * src[1][i] + m[2] * src[2][i] + m[3] * src[3][i] + m[4] * src[4][i];
3280 }
3281 template <typename ET, typename FT>
3282 void vlineSmooth5N14641(const FT* const * src, const FT*, int, ET* dst, int len)
3283 {
3284     for (int i = 0; i < len; i++)
3285         dst[i] = (FT::WT(src[2][i])*(uint8_t)6 + ((FT::WT(src[1][i]) + FT::WT(src[3][i]))<<2) + FT::WT(src[0][i]) + FT::WT(src[4][i])) >> 4;
3286 }
3287 template <>
3288 void vlineSmooth5N14641<uint8_t, ufixedpoint16>(const ufixedpoint16* const * src, const ufixedpoint16*, int, uint8_t* dst, int len)
3289 {
3290     int i = 0;
3291     v_uint32x4 v_6 = v_setall_u32(6);
3292     for (; i <= len - 16; i += 16)
3293     {
3294         v_uint32x4 v_src00, v_src10, v_src20, v_src30, v_src40;
3295         v_uint32x4 v_src01, v_src11, v_src21, v_src31, v_src41;
3296         v_uint32x4 v_src02, v_src12, v_src22, v_src32, v_src42;
3297         v_uint32x4 v_src03, v_src13, v_src23, v_src33, v_src43;
3298         v_expand(v_load((uint16_t*)(src[0]) + i), v_src00, v_src01);
3299         v_expand(v_load((uint16_t*)(src[0]) + i + 8), v_src02, v_src03);
3300         v_expand(v_load((uint16_t*)(src[1]) + i), v_src10, v_src11);
3301         v_expand(v_load((uint16_t*)(src[1]) + i + 8), v_src12, v_src13);
3302         v_expand(v_load((uint16_t*)(src[2]) + i), v_src20, v_src21);
3303         v_expand(v_load((uint16_t*)(src[2]) + i + 8), v_src22, v_src23);
3304         v_expand(v_load((uint16_t*)(src[3]) + i), v_src30, v_src31);
3305         v_expand(v_load((uint16_t*)(src[3]) + i + 8), v_src32, v_src33);
3306         v_expand(v_load((uint16_t*)(src[4]) + i), v_src40, v_src41);
3307         v_expand(v_load((uint16_t*)(src[4]) + i + 8), v_src42, v_src43);
3308         v_store(dst + i, v_pack(v_rshr_pack<12>(v_src20*v_6 + ((v_src10 + v_src30) << 2) + v_src00 + v_src40,
3309                                                 v_src21*v_6 + ((v_src11 + v_src31) << 2) + v_src01 + v_src41),
3310                                 v_rshr_pack<12>(v_src22*v_6 + ((v_src12 + v_src32) << 2) + v_src02 + v_src42,
3311                                                 v_src23*v_6 + ((v_src13 + v_src33) << 2) + v_src03 + v_src43)));
3312     }
3313     for (; i < len; i++)
3314         dst[i] = ((uint32_t)(((uint16_t*)(src[2]))[i]) * 6 +
3315                   (((uint32_t)(((uint16_t*)(src[1]))[i]) + (uint32_t)(((uint16_t*)(src[3]))[i])) << 2) +
3316                   (uint32_t)(((uint16_t*)(src[0]))[i]) + (uint32_t)(((uint16_t*)(src[4]))[i]) + (1 << 11)) >> 12;
3317 }
3318 template <typename ET, typename FT>
3319 void vlineSmooth(const FT* const * src, const FT* m, int n, ET* dst, int len)
3320 {
3321     for (int i = 0; i < len; i++)
3322     {
3323         typename FT::WT val = m[0] * src[0][i];
3324         for (int j = 1; j < n; j++)
3325             val = val + m[j] * src[j][i];
3326         dst[i] = val;
3327     }
3328 }
3329 template <>
3330 void vlineSmooth<uint8_t, ufixedpoint16>(const ufixedpoint16* const * src, const ufixedpoint16* m, int n, uint8_t* dst, int len)
3331 {
3332     int i = 0;
3333     static const v_int16x8 v_128 = v_reinterpret_as_s16(v_setall_u16((uint16_t)1 << 15));
3334     v_int32x4 v_128_4 = v_setall_s32(128 << 16);
3335     if (len > 7)
3336     {
3337         ufixedpoint16 msum = m[0] + m[1];
3338         for (int j = 2; j < n; j++)
3339             msum = msum + m[j];
3340         ufixedpoint32 val[] = { msum * ufixedpoint16((uint8_t)128) };
3341         v_128_4 = v_setall_s32(*((int32_t*)val));
3342     }
3343     for (; i <= len - 32; i += 32)
3344     {
3345         v_int16x8 v_src00, v_src10, v_src01, v_src11, v_src02, v_src12, v_src03, v_src13;
3346         v_int16x8 v_tmp0, v_tmp1;
3347
3348         v_int16x8 v_mul = v_reinterpret_as_s16(v_setall_u32(*((uint32_t*)m)));
3349
3350         v_src00 = v_load((int16_t*)(src[0]) + i);
3351         v_src01 = v_load((int16_t*)(src[0]) + i + 8);
3352         v_src02 = v_load((int16_t*)(src[0]) + i + 16);
3353         v_src03 = v_load((int16_t*)(src[0]) + i + 24);
3354         v_src10 = v_load((int16_t*)(src[1]) + i);
3355         v_src11 = v_load((int16_t*)(src[1]) + i + 8);
3356         v_src12 = v_load((int16_t*)(src[1]) + i + 16);
3357         v_src13 = v_load((int16_t*)(src[1]) + i + 24);
3358         v_zip(v_add_wrap(v_src00, v_128), v_add_wrap(v_src10, v_128), v_tmp0, v_tmp1);
3359         v_int32x4 v_res0 = v_dotprod(v_tmp0, v_mul);
3360         v_int32x4 v_res1 = v_dotprod(v_tmp1, v_mul);
3361         v_zip(v_add_wrap(v_src01, v_128), v_add_wrap(v_src11, v_128), v_tmp0, v_tmp1);
3362         v_int32x4 v_res2 = v_dotprod(v_tmp0, v_mul);
3363         v_int32x4 v_res3 = v_dotprod(v_tmp1, v_mul);
3364         v_zip(v_add_wrap(v_src02, v_128), v_add_wrap(v_src12, v_128), v_tmp0, v_tmp1);
3365         v_int32x4 v_res4 = v_dotprod(v_tmp0, v_mul);
3366         v_int32x4 v_res5 = v_dotprod(v_tmp1, v_mul);
3367         v_zip(v_add_wrap(v_src03, v_128), v_add_wrap(v_src13, v_128), v_tmp0, v_tmp1);
3368         v_int32x4 v_res6 = v_dotprod(v_tmp0, v_mul);
3369         v_int32x4 v_res7 = v_dotprod(v_tmp1, v_mul);
3370
3371         int j = 2;
3372         for (; j < n - 1; j+=2)
3373         {
3374             v_mul = v_reinterpret_as_s16(v_setall_u32(*((uint32_t*)(m+j))));
3375
3376             v_src00 = v_load((int16_t*)(src[j]) + i);
3377             v_src01 = v_load((int16_t*)(src[j]) + i + 8);
3378             v_src02 = v_load((int16_t*)(src[j]) + i + 16);
3379             v_src03 = v_load((int16_t*)(src[j]) + i + 24);
3380             v_src10 = v_load((int16_t*)(src[j+1]) + i);
3381             v_src11 = v_load((int16_t*)(src[j+1]) + i + 8);
3382             v_src12 = v_load((int16_t*)(src[j+1]) + i + 16);
3383             v_src13 = v_load((int16_t*)(src[j+1]) + i + 24);
3384             v_zip(v_add_wrap(v_src00, v_128), v_add_wrap(v_src10, v_128), v_tmp0, v_tmp1);
3385             v_res0 += v_dotprod(v_tmp0, v_mul);
3386             v_res1 += v_dotprod(v_tmp1, v_mul);
3387             v_zip(v_add_wrap(v_src01, v_128), v_add_wrap(v_src11, v_128), v_tmp0, v_tmp1);
3388             v_res2 += v_dotprod(v_tmp0, v_mul);
3389             v_res3 += v_dotprod(v_tmp1, v_mul);
3390             v_zip(v_add_wrap(v_src02, v_128), v_add_wrap(v_src12, v_128), v_tmp0, v_tmp1);
3391             v_res4 += v_dotprod(v_tmp0, v_mul);
3392             v_res5 += v_dotprod(v_tmp1, v_mul);
3393             v_zip(v_add_wrap(v_src03, v_128), v_add_wrap(v_src13, v_128), v_tmp0, v_tmp1);
3394             v_res6 += v_dotprod(v_tmp0, v_mul);
3395             v_res7 += v_dotprod(v_tmp1, v_mul);
3396         }
3397         if(j < n)
3398         {
3399             v_int32x4 v_resj0, v_resj1;
3400             v_mul = v_reinterpret_as_s16(v_setall_u16(*((uint16_t*)(m + j))));
3401             v_src00 = v_load((int16_t*)(src[j]) + i);
3402             v_src01 = v_load((int16_t*)(src[j]) + i + 8);
3403             v_src02 = v_load((int16_t*)(src[j]) + i + 16);
3404             v_src03 = v_load((int16_t*)(src[j]) + i + 24);
3405             v_mul_expand(v_add_wrap(v_src00, v_128), v_mul, v_resj0, v_resj1);
3406             v_res0 += v_resj0;
3407             v_res1 += v_resj1;
3408             v_mul_expand(v_add_wrap(v_src01, v_128), v_mul, v_resj0, v_resj1);
3409             v_res2 += v_resj0;
3410             v_res3 += v_resj1;
3411             v_mul_expand(v_add_wrap(v_src02, v_128), v_mul, v_resj0, v_resj1);
3412             v_res4 += v_resj0;
3413             v_res5 += v_resj1;
3414             v_mul_expand(v_add_wrap(v_src03, v_128), v_mul, v_resj0, v_resj1);
3415             v_res6 += v_resj0;
3416             v_res7 += v_resj1;
3417         }
3418         v_res0 += v_128_4;
3419         v_res1 += v_128_4;
3420         v_res2 += v_128_4;
3421         v_res3 += v_128_4;
3422         v_res4 += v_128_4;
3423         v_res5 += v_128_4;
3424         v_res6 += v_128_4;
3425         v_res7 += v_128_4;
3426
3427         v_store(dst + i     , v_pack(v_reinterpret_as_u16(v_rshr_pack<16>(v_res0, v_res1)),
3428                                      v_reinterpret_as_u16(v_rshr_pack<16>(v_res2, v_res3))));
3429         v_store(dst + i + 16, v_pack(v_reinterpret_as_u16(v_rshr_pack<16>(v_res4, v_res5)),
3430                                      v_reinterpret_as_u16(v_rshr_pack<16>(v_res6, v_res7))));
3431     }
3432     for (; i < len; i++)
3433     {
3434         ufixedpoint32 val = m[0] * src[0][i];
3435         for (int j = 1; j < n; j++)
3436         {
3437             val = val + m[j] * src[j][i];
3438         }
3439         dst[i] = val;
3440     }
3441 }
3442 template <typename ET, typename FT>
3443 void vlineSmoothONa_yzy_a(const FT* const * src, const FT* m, int n, ET* dst, int len)
3444 {
3445     int pre_shift = n / 2;
3446     for (int i = 0; i < len; i++)
3447     {
3448         typename FT::WT val = m[pre_shift] * src[pre_shift][i];
3449         for (int j = 0; j < pre_shift; j++)
3450             val = val + m[j] * src[j][i] + m[j] * src[(n - 1 - j)][i];
3451         dst[i] = val;
3452     }
3453 }
3454 template <>
3455 void vlineSmoothONa_yzy_a<uint8_t, ufixedpoint16>(const ufixedpoint16* const * src, const ufixedpoint16* m, int n, uint8_t* dst, int len)
3456 {
3457     int pre_shift = n / 2;
3458     int i = 0;
3459     static const v_int16x8 v_128 = v_reinterpret_as_s16(v_setall_u16((uint16_t)1 << 15));
3460     v_int32x4 v_128_4 = v_setall_s32(128 << 16);
3461     if (len > 7)
3462     {
3463         ufixedpoint16 msum = m[0] + m[pre_shift] + m[n - 1];
3464         for (int j = 1; j < pre_shift; j++)
3465             msum = msum + m[j] + m[n - 1 - j];
3466         ufixedpoint32 val[] = { msum * ufixedpoint16((uint8_t)128) };
3467         v_128_4 = v_setall_s32(*((int32_t*)val));
3468     }
3469     for (; i <= len - 32; i += 32)
3470     {
3471         v_int16x8 v_src00, v_src10, v_src20, v_src30, v_src01, v_src11, v_src21, v_src31;
3472         v_int32x4 v_res0, v_res1, v_res2, v_res3, v_res4, v_res5, v_res6, v_res7;
3473         v_int16x8 v_tmp0, v_tmp1, v_tmp2, v_tmp3, v_tmp4, v_tmp5, v_tmp6, v_tmp7;
3474
3475         v_int16x8 v_mul = v_reinterpret_as_s16(v_setall_u16(*((uint16_t*)(m + pre_shift))));
3476         v_src00 = v_load((int16_t*)(src[pre_shift]) + i);
3477         v_src10 = v_load((int16_t*)(src[pre_shift]) + i + 8);
3478         v_src20 = v_load((int16_t*)(src[pre_shift]) + i + 16);
3479         v_src30 = v_load((int16_t*)(src[pre_shift]) + i + 24);
3480         v_mul_expand(v_add_wrap(v_src00, v_128), v_mul, v_res0, v_res1);
3481         v_mul_expand(v_add_wrap(v_src10, v_128), v_mul, v_res2, v_res3);
3482         v_mul_expand(v_add_wrap(v_src20, v_128), v_mul, v_res4, v_res5);
3483         v_mul_expand(v_add_wrap(v_src30, v_128), v_mul, v_res6, v_res7);
3484
3485         int j = 0;
3486         for (; j < pre_shift; j++)
3487         {
3488             v_mul = v_reinterpret_as_s16(v_setall_u16(*((uint16_t*)(m + j))));
3489
3490             v_src00 = v_load((int16_t*)(src[j]) + i);
3491             v_src10 = v_load((int16_t*)(src[j]) + i + 8);
3492             v_src20 = v_load((int16_t*)(src[j]) + i + 16);
3493             v_src30 = v_load((int16_t*)(src[j]) + i + 24);
3494             v_src01 = v_load((int16_t*)(src[n - 1 - j]) + i);
3495             v_src11 = v_load((int16_t*)(src[n - 1 - j]) + i + 8);
3496             v_src21 = v_load((int16_t*)(src[n - 1 - j]) + i + 16);
3497             v_src31 = v_load((int16_t*)(src[n - 1 - j]) + i + 24);
3498             v_zip(v_add_wrap(v_src00, v_128), v_add_wrap(v_src01, v_128), v_tmp0, v_tmp1);
3499             v_res0 += v_dotprod(v_tmp0, v_mul);
3500             v_res1 += v_dotprod(v_tmp1, v_mul);
3501             v_zip(v_add_wrap(v_src10, v_128), v_add_wrap(v_src11, v_128), v_tmp2, v_tmp3);
3502             v_res2 += v_dotprod(v_tmp2, v_mul);
3503             v_res3 += v_dotprod(v_tmp3, v_mul);
3504             v_zip(v_add_wrap(v_src20, v_128), v_add_wrap(v_src21, v_128), v_tmp4, v_tmp5);
3505             v_res4 += v_dotprod(v_tmp4, v_mul);
3506             v_res5 += v_dotprod(v_tmp5, v_mul);
3507             v_zip(v_add_wrap(v_src30, v_128), v_add_wrap(v_src31, v_128), v_tmp6, v_tmp7);
3508             v_res6 += v_dotprod(v_tmp6, v_mul);
3509             v_res7 += v_dotprod(v_tmp7, v_mul);
3510         }
3511
3512         v_res0 += v_128_4;
3513         v_res1 += v_128_4;
3514         v_res2 += v_128_4;
3515         v_res3 += v_128_4;
3516         v_res4 += v_128_4;
3517         v_res5 += v_128_4;
3518         v_res6 += v_128_4;
3519         v_res7 += v_128_4;
3520
3521         v_store(dst + i     , v_pack(v_reinterpret_as_u16(v_rshr_pack<16>(v_res0, v_res1)),
3522                                      v_reinterpret_as_u16(v_rshr_pack<16>(v_res2, v_res3))));
3523         v_store(dst + i + 16, v_pack(v_reinterpret_as_u16(v_rshr_pack<16>(v_res4, v_res5)),
3524                                      v_reinterpret_as_u16(v_rshr_pack<16>(v_res6, v_res7))));
3525     }
3526     for (; i < len; i++)
3527     {
3528         ufixedpoint32 val = m[0] * src[0][i];
3529         for (int j = 1; j < n; j++)
3530         {
3531             val = val + m[j] * src[j][i];
3532         }
3533         dst[i] = val;
3534     }
3535 }
3536 template <typename ET, typename FT>
3537 class fixedSmoothInvoker : public ParallelLoopBody
3538 {
3539 public:
3540     fixedSmoothInvoker(const ET* _src, size_t _src_stride, ET* _dst, size_t _dst_stride,
3541                        int _width, int _height, int _cn, const FT* _kx, int _kxlen, const FT* _ky, int _kylen, int _borderType) : ParallelLoopBody(),
3542                        src(_src), dst(_dst), src_stride(_src_stride), dst_stride(_dst_stride),
3543                        width(_width), height(_height), cn(_cn), kx(_kx), ky(_ky), kxlen(_kxlen), kylen(_kylen), borderType(_borderType)
3544     {
3545         if (kxlen == 1)
3546         {
3547             if (kx[0] == FT::one())
3548                 hlineSmoothFunc = hlineSmooth1N1;
3549             else
3550                 hlineSmoothFunc = hlineSmooth1N;
3551         }
3552         else if (kxlen == 3)
3553         {
3554             if (kx[0] == (FT::one()>>2)&&kx[1] == (FT::one()>>1)&&kx[2] == (FT::one()>>2))
3555                 hlineSmoothFunc = hlineSmooth3N121;
3556             else if ((kx[0] - kx[2]).isZero())
3557                     hlineSmoothFunc = hlineSmooth3Naba;
3558             else
3559                 hlineSmoothFunc = hlineSmooth3N;
3560         }
3561         else if (kxlen == 5)
3562         {
3563             if (kx[2] == (FT::one()*(uint8_t)3>>3) &&
3564                 kx[1] == (FT::one()>>2) && kx[3] == (FT::one()>>2) &&
3565                 kx[0] == (FT::one()>>4) && kx[4] == (FT::one()>>4))
3566                 hlineSmoothFunc = hlineSmooth5N14641;
3567             else if (kx[0] == kx[4] && kx[1] == kx[3])
3568                 hlineSmoothFunc = hlineSmooth5Nabcba;
3569             else
3570                 hlineSmoothFunc = hlineSmooth5N;
3571         }
3572         else if (kxlen % 2 == 1)
3573         {
3574             hlineSmoothFunc = hlineSmoothONa_yzy_a;
3575             for (int i = 0; i < kxlen / 2; i++)
3576                 if (!(kx[i] == kx[kxlen - 1 - i]))
3577                 {
3578                     hlineSmoothFunc = hlineSmooth;
3579                     break;
3580                 }
3581         }
3582         else
3583             hlineSmoothFunc = hlineSmooth;
3584         if (kylen == 1)
3585         {
3586             if (ky[0] == FT::one())
3587                 vlineSmoothFunc = vlineSmooth1N1;
3588             else
3589                 vlineSmoothFunc = vlineSmooth1N;
3590         }
3591         else if (kylen == 3)
3592         {
3593             if (ky[0] == (FT::one() >> 2) && ky[1] == (FT::one() >> 1) && ky[2] == (FT::one() >> 2))
3594                 vlineSmoothFunc = vlineSmooth3N121;
3595             else
3596                 vlineSmoothFunc = vlineSmooth3N;
3597         }
3598         else if (kylen == 5)
3599         {
3600             if (ky[2] == (FT::one() * (uint8_t)3 >> 3) &&
3601                 ky[1] == (FT::one() >> 2) && ky[3] == (FT::one() >> 2) &&
3602                 ky[0] == (FT::one() >> 4) && ky[4] == (FT::one() >> 4))
3603                 vlineSmoothFunc = vlineSmooth5N14641;
3604             else
3605                 vlineSmoothFunc = vlineSmooth5N;
3606         }
3607         else if (kylen % 2 == 1)
3608         {
3609             vlineSmoothFunc = vlineSmoothONa_yzy_a;
3610             for (int i = 0; i < kylen / 2; i++)
3611                 if (!(ky[i] == ky[kylen - 1 - i]))
3612                 {
3613                     vlineSmoothFunc = vlineSmooth;
3614                     break;
3615                 }
3616         }
3617         else
3618             vlineSmoothFunc = vlineSmooth;
3619     }
3620     virtual void operator() (const Range& range) const CV_OVERRIDE
3621     {
3622         AutoBuffer<FT> _buf(width*cn*kylen);
3623         FT* buf = _buf;
3624         AutoBuffer<FT*> _ptrs(kylen*2);
3625         FT** ptrs = _ptrs;
3626
3627         if (kylen == 1)
3628         {
3629             ptrs[0] = buf;
3630             for (int i = range.start; i < range.end; i++)
3631             {
3632                 hlineSmoothFunc(src + i * src_stride, cn, kx, kxlen, ptrs[0], width, borderType);
3633                 vlineSmoothFunc(ptrs, ky, kylen, dst + i * dst_stride, width*cn);
3634             }
3635         }
3636         else if (borderType != BORDER_CONSTANT)// If BORDER_CONSTANT out of border values are equal to zero and could be skipped
3637         {
3638             int pre_shift = kylen / 2;
3639             int post_shift = kylen - pre_shift - 1;
3640             // First line evaluation
3641             int idst = range.start;
3642             int ifrom = max(0, idst - pre_shift);
3643             int ito = idst + post_shift + 1;
3644             int i = ifrom;
3645             int bufline = 0;
3646             for (; i < min(ito, height); i++, bufline++)
3647             {
3648                 ptrs[bufline+kylen] = ptrs[bufline] = buf + bufline * width*cn;
3649                 hlineSmoothFunc(src + i * src_stride, cn, kx, kxlen, ptrs[bufline], width, borderType);
3650             }
3651             for (; i < ito; i++, bufline++)
3652             {
3653                 int src_idx = borderInterpolate(i, height, borderType);
3654                 if (src_idx < ifrom)
3655                 {
3656                     ptrs[bufline + kylen] = ptrs[bufline] = buf + bufline * width*cn;
3657                     hlineSmoothFunc(src + src_idx * src_stride, cn, kx, kxlen, ptrs[bufline], width, borderType);
3658                 }
3659                 else
3660                 {
3661                     ptrs[bufline + kylen] = ptrs[bufline] = ptrs[src_idx - ifrom];
3662                 }
3663             }
3664             for (int j = idst - pre_shift; j < 0; j++)
3665             {
3666                 int src_idx = borderInterpolate(j, height, borderType);
3667                 if (src_idx >= ito)
3668                 {
3669                     ptrs[2*kylen + j] = ptrs[kylen + j] = buf + (kylen + j) * width*cn;
3670                     hlineSmoothFunc(src + src_idx * src_stride, cn, kx, kxlen, ptrs[kylen + j], width, borderType);
3671                 }
3672                 else
3673                 {
3674                     ptrs[2*kylen + j] = ptrs[kylen + j] = ptrs[src_idx];
3675                 }
3676             }
3677             vlineSmoothFunc(ptrs + bufline, ky, kylen, dst + idst*dst_stride, width*cn); idst++;
3678
3679             // border mode dependent part evaluation
3680             // i points to last src row to evaluate in convolution
3681             bufline %= kylen; ito = min(height, range.end + post_shift);
3682             for (; i < min(kylen, ito); i++, idst++)
3683             {
3684                 ptrs[bufline + kylen] = ptrs[bufline] = buf + bufline * width*cn;
3685                 hlineSmoothFunc(src + i * src_stride, cn, kx, kxlen, ptrs[bufline], width, borderType);
3686                 bufline = (bufline + 1) % kylen;
3687                 vlineSmoothFunc(ptrs + bufline, ky, kylen, dst + idst*dst_stride, width*cn);
3688             }
3689             // Points inside the border
3690             for (; i < ito; i++, idst++)
3691             {
3692                 hlineSmoothFunc(src + i * src_stride, cn, kx, kxlen, ptrs[bufline], width, borderType);
3693                 bufline = (bufline + 1) % kylen;
3694                 vlineSmoothFunc(ptrs + bufline, ky, kylen, dst + idst*dst_stride, width*cn);
3695             }
3696             // Points that could fall below border
3697             for (; i < range.end + post_shift; i++, idst++)
3698             {
3699                 int src_idx = borderInterpolate(i, height, borderType);
3700                 if ((i - src_idx) > kylen)
3701                     hlineSmoothFunc(src + src_idx * src_stride, cn, kx, kxlen, ptrs[bufline], width, borderType);
3702                 else
3703                     ptrs[bufline + kylen] = ptrs[bufline] = ptrs[(bufline + kylen - (i - src_idx)) % kylen];
3704                 bufline = (bufline + 1) % kylen;
3705                 vlineSmoothFunc(ptrs + bufline, ky, kylen, dst + idst*dst_stride, width*cn);
3706             }
3707         }
3708         else
3709         {
3710             int pre_shift = kylen / 2;
3711             int post_shift = kylen - pre_shift - 1;
3712             // First line evaluation
3713             int idst = range.start;
3714             int ifrom = idst - pre_shift;
3715             int ito = min(idst + post_shift + 1, height);
3716             int i = max(0, ifrom);
3717             int bufline = 0;
3718             for (; i < ito; i++, bufline++)
3719             {
3720                 ptrs[bufline + kylen] = ptrs[bufline] = buf + bufline * width*cn;
3721                 hlineSmoothFunc(src + i * src_stride, cn, kx, kxlen, ptrs[bufline], width, borderType);
3722             }
3723
3724             if (bufline == 1)
3725                 vlineSmooth1N(ptrs, ky - min(ifrom, 0), bufline, dst + idst*dst_stride, width*cn);
3726             else if (bufline == 3)
3727                 vlineSmooth3N(ptrs, ky - min(ifrom, 0), bufline, dst + idst*dst_stride, width*cn);
3728             else if (bufline == 5)
3729                 vlineSmooth5N(ptrs, ky - min(ifrom, 0), bufline, dst + idst*dst_stride, width*cn);
3730             else
3731                 vlineSmooth(ptrs, ky - min(ifrom, 0), bufline, dst + idst*dst_stride, width*cn);
3732             idst++;
3733
3734             // border mode dependent part evaluation
3735             // i points to last src row to evaluate in convolution
3736             bufline %= kylen; ito = min(height, range.end + post_shift);
3737             for (; i < min(kylen, ito); i++, idst++)
3738             {
3739                 ptrs[bufline + kylen] = ptrs[bufline] = buf + bufline * width*cn;
3740                 hlineSmoothFunc(src + i * src_stride, cn, kx, kxlen, ptrs[bufline], width, borderType);
3741                 bufline++;
3742                 if (bufline == 3)
3743                     vlineSmooth3N(ptrs, ky + kylen - bufline, i + 1, dst + idst*dst_stride, width*cn);
3744                 else if (bufline == 5)
3745                     vlineSmooth5N(ptrs, ky + kylen - bufline, i + 1, dst + idst*dst_stride, width*cn);
3746                 else
3747                     vlineSmooth(ptrs, ky + kylen - bufline, i + 1, dst + idst*dst_stride, width*cn);
3748                 bufline %= kylen;
3749             }
3750             // Points inside the border
3751             if (i - max(0, ifrom) >= kylen)
3752             {
3753                 for (; i < ito; i++, idst++)
3754                 {
3755                     hlineSmoothFunc(src + i * src_stride, cn, kx, kxlen, ptrs[bufline], width, borderType);
3756                     bufline = (bufline + 1) % kylen;
3757                     vlineSmoothFunc(ptrs + bufline, ky, kylen, dst + idst*dst_stride, width*cn);
3758                 }
3759
3760                 // Points that could fall below border
3761                 // i points to first src row to evaluate in convolution
3762                 bufline = (bufline + 1) % kylen;
3763                 for (i = idst - pre_shift; i < range.end - pre_shift; i++, idst++, bufline++)
3764                     if (height - i == 3)
3765                         vlineSmooth3N(ptrs + bufline, ky, height - i, dst + idst*dst_stride, width*cn);
3766                     else if (height - i == 5)
3767                         vlineSmooth5N(ptrs + bufline, ky, height - i, dst + idst*dst_stride, width*cn);
3768                     else
3769                         vlineSmooth(ptrs + bufline, ky, height - i, dst + idst*dst_stride, width*cn);
3770             }
3771             else
3772             {
3773                 // i points to first src row to evaluate in convolution
3774                 for (i = idst - pre_shift; i < min(range.end - pre_shift, 0); i++, idst++)
3775                     if (height == 3)
3776                         vlineSmooth3N(ptrs, ky - i, height, dst + idst*dst_stride, width*cn);
3777                     else if (height == 5)
3778                         vlineSmooth5N(ptrs, ky - i, height, dst + idst*dst_stride, width*cn);
3779                     else
3780                         vlineSmooth(ptrs, ky - i, height, dst + idst*dst_stride, width*cn);
3781                 for (; i < range.end - pre_shift; i++, idst++)
3782                     if (height - i == 3)
3783                         vlineSmooth3N(ptrs + i - max(0, ifrom), ky, height - i, dst + idst*dst_stride, width*cn);
3784                     else if (height - i == 5)
3785                         vlineSmooth5N(ptrs + i - max(0, ifrom), ky, height - i, dst + idst*dst_stride, width*cn);
3786                     else
3787                         vlineSmooth(ptrs + i - max(0, ifrom), ky, height - i, dst + idst*dst_stride, width*cn);
3788             }
3789         }
3790     }
3791 private:
3792     const ET* src;
3793     ET* dst;
3794     size_t src_stride, dst_stride;
3795     int width, height, cn;
3796     const FT *kx, *ky;
3797     int kxlen, kylen;
3798     int borderType;
3799     void(*hlineSmoothFunc)(const ET* src, int cn, const FT* m, int n, FT* dst, int len, int borderType);
3800     void(*vlineSmoothFunc)(const FT* const * src, const FT* m, int n, ET* dst, int len);
3801
3802     fixedSmoothInvoker(const fixedSmoothInvoker&);
3803     fixedSmoothInvoker& operator=(const fixedSmoothInvoker&);
3804 };
3805
3806 static void getGaussianKernel(int n, double sigma, int ktype, Mat& res) { res = getGaussianKernel(n, sigma, ktype); }
3807 template <typename T> static void getGaussianKernel(int n, double sigma, int, std::vector<T>& res) { res = getFixedpointGaussianKernel<T>(n, sigma); }
3808
3809 template <typename T>
3810 static void createGaussianKernels( T & kx, T & ky, int type, Size &ksize,
3811                                    double sigma1, double sigma2 )
3812 {
3813     int depth = CV_MAT_DEPTH(type);
3814     if( sigma2 <= 0 )
3815         sigma2 = sigma1;
3816
3817     // automatic detection of kernel size from sigma
3818     if( ksize.width <= 0 && sigma1 > 0 )
3819         ksize.width = cvRound(sigma1*(depth == CV_8U ? 3 : 4)*2 + 1)|1;
3820     if( ksize.height <= 0 && sigma2 > 0 )
3821         ksize.height = cvRound(sigma2*(depth == CV_8U ? 3 : 4)*2 + 1)|1;
3822
3823     CV_Assert( ksize.width > 0 && ksize.width % 2 == 1 &&
3824         ksize.height > 0 && ksize.height % 2 == 1 );
3825
3826     sigma1 = std::max( sigma1, 0. );
3827     sigma2 = std::max( sigma2, 0. );
3828
3829     getGaussianKernel( ksize.width, sigma1, std::max(depth, CV_32F), kx );
3830     if( ksize.height == ksize.width && std::abs(sigma1 - sigma2) < DBL_EPSILON )
3831         ky = kx;
3832     else
3833         getGaussianKernel( ksize.height, sigma2, std::max(depth, CV_32F), ky );
3834 }
3835
3836 }
3837
3838 cv::Ptr<cv::FilterEngine> cv::createGaussianFilter( int type, Size ksize,
3839                                         double sigma1, double sigma2,
3840                                         int borderType )
3841 {
3842     Mat kx, ky;
3843     createGaussianKernels(kx, ky, type, ksize, sigma1, sigma2);
3844
3845     return createSeparableLinearFilter( type, type, kx, ky, Point(-1,-1), 0, borderType );
3846 }
3847
3848 namespace cv
3849 {
3850 #ifdef HAVE_OPENCL
3851
3852 static bool ocl_GaussianBlur_8UC1(InputArray _src, OutputArray _dst, Size ksize, int ddepth,
3853                                   InputArray _kernelX, InputArray _kernelY, int borderType)
3854 {
3855     const ocl::Device & dev = ocl::Device::getDefault();
3856     int type = _src.type(), sdepth = CV_MAT_DEPTH(type), cn = CV_MAT_CN(type);
3857
3858     if ( !(dev.isIntel() && (type == CV_8UC1) &&
3859          (_src.offset() == 0) && (_src.step() % 4 == 0) &&
3860          ((ksize.width == 5 && (_src.cols() % 4 == 0)) ||
3861          (ksize.width == 3 && (_src.cols() % 16 == 0) && (_src.rows() % 2 == 0)))) )
3862         return false;
3863
3864     Mat kernelX = _kernelX.getMat().reshape(1, 1);
3865     if (kernelX.cols % 2 != 1)
3866         return false;
3867     Mat kernelY = _kernelY.getMat().reshape(1, 1);
3868     if (kernelY.cols % 2 != 1)
3869         return false;
3870
3871     if (ddepth < 0)
3872         ddepth = sdepth;
3873
3874     Size size = _src.size();
3875     size_t globalsize[2] = { 0, 0 };
3876     size_t localsize[2] = { 0, 0 };
3877
3878     if (ksize.width == 3)
3879     {
3880         globalsize[0] = size.width / 16;
3881         globalsize[1] = size.height / 2;
3882     }
3883     else if (ksize.width == 5)
3884     {
3885         globalsize[0] = size.width / 4;
3886         globalsize[1] = size.height / 1;
3887     }
3888
3889     const char * const borderMap[] = { "BORDER_CONSTANT", "BORDER_REPLICATE", "BORDER_REFLECT", 0, "BORDER_REFLECT_101" };
3890     char build_opts[1024];
3891     sprintf(build_opts, "-D %s %s%s", borderMap[borderType & ~BORDER_ISOLATED],
3892             ocl::kernelToStr(kernelX, CV_32F, "KERNEL_MATRIX_X").c_str(),
3893             ocl::kernelToStr(kernelY, CV_32F, "KERNEL_MATRIX_Y").c_str());
3894
3895     ocl::Kernel kernel;
3896
3897     if (ksize.width == 3)
3898         kernel.create("gaussianBlur3x3_8UC1_cols16_rows2", cv::ocl::imgproc::gaussianBlur3x3_oclsrc, build_opts);
3899     else if (ksize.width == 5)
3900         kernel.create("gaussianBlur5x5_8UC1_cols4", cv::ocl::imgproc::gaussianBlur5x5_oclsrc, build_opts);
3901
3902     if (kernel.empty())
3903         return false;
3904
3905     UMat src = _src.getUMat();
3906     _dst.create(size, CV_MAKETYPE(ddepth, cn));
3907     if (!(_dst.offset() == 0 && _dst.step() % 4 == 0))
3908         return false;
3909     UMat dst = _dst.getUMat();
3910
3911     int idxArg = kernel.set(0, ocl::KernelArg::PtrReadOnly(src));
3912     idxArg = kernel.set(idxArg, (int)src.step);
3913     idxArg = kernel.set(idxArg, ocl::KernelArg::PtrWriteOnly(dst));
3914     idxArg = kernel.set(idxArg, (int)dst.step);
3915     idxArg = kernel.set(idxArg, (int)dst.rows);
3916     idxArg = kernel.set(idxArg, (int)dst.cols);
3917
3918     return kernel.run(2, globalsize, (localsize[0] == 0) ? NULL : localsize, false);
3919 }
3920
3921 #endif
3922
3923 #ifdef HAVE_OPENVX
3924
3925 namespace ovx {
3926     template <> inline bool skipSmallImages<VX_KERNEL_GAUSSIAN_3x3>(int w, int h) { return w*h < 320 * 240; }
3927 }
3928 static bool openvx_gaussianBlur(InputArray _src, OutputArray _dst, Size ksize,
3929                                 double sigma1, double sigma2, int borderType)
3930 {
3931     if (sigma2 <= 0)
3932         sigma2 = sigma1;
3933     // automatic detection of kernel size from sigma
3934     if (ksize.width <= 0 && sigma1 > 0)
3935         ksize.width = cvRound(sigma1*6 + 1) | 1;
3936     if (ksize.height <= 0 && sigma2 > 0)
3937         ksize.height = cvRound(sigma2*6 + 1) | 1;
3938
3939     if (_src.type() != CV_8UC1 ||
3940         _src.cols() < 3 || _src.rows() < 3 ||
3941         ksize.width != 3 || ksize.height != 3)
3942         return false;
3943
3944     sigma1 = std::max(sigma1, 0.);
3945     sigma2 = std::max(sigma2, 0.);
3946
3947     if (!(sigma1 == 0.0 || (sigma1 - 0.8) < DBL_EPSILON) || !(sigma2 == 0.0 || (sigma2 - 0.8) < DBL_EPSILON) ||
3948         ovx::skipSmallImages<VX_KERNEL_GAUSSIAN_3x3>(_src.cols(), _src.rows()))
3949         return false;
3950
3951     Mat src = _src.getMat();
3952     Mat dst = _dst.getMat();
3953
3954     if ((borderType & BORDER_ISOLATED) == 0 && src.isSubmatrix())
3955         return false; //Process isolated borders only
3956     vx_enum border;
3957     switch (borderType & ~BORDER_ISOLATED)
3958     {
3959     case BORDER_CONSTANT:
3960         border = VX_BORDER_CONSTANT;
3961         break;
3962     case BORDER_REPLICATE:
3963         border = VX_BORDER_REPLICATE;
3964         break;
3965     default:
3966         return false;
3967     }
3968
3969     try
3970     {
3971         ivx::Context ctx = ovx::getOpenVXContext();
3972
3973         Mat a;
3974         if (dst.data != src.data)
3975             a = src;
3976         else
3977             src.copyTo(a);
3978
3979         ivx::Image
3980             ia = ivx::Image::createFromHandle(ctx, VX_DF_IMAGE_U8,
3981                 ivx::Image::createAddressing(a.cols, a.rows, 1, (vx_int32)(a.step)), a.data),
3982             ib = ivx::Image::createFromHandle(ctx, VX_DF_IMAGE_U8,
3983                 ivx::Image::createAddressing(dst.cols, dst.rows, 1, (vx_int32)(dst.step)), dst.data);
3984
3985         //ATTENTION: VX_CONTEXT_IMMEDIATE_BORDER attribute change could lead to strange issues in multi-threaded environments
3986         //since OpenVX standard says nothing about thread-safety for now
3987         ivx::border_t prevBorder = ctx.immediateBorder();
3988         ctx.setImmediateBorder(border, (vx_uint8)(0));
3989         ivx::IVX_CHECK_STATUS(vxuGaussian3x3(ctx, ia, ib));
3990         ctx.setImmediateBorder(prevBorder);
3991     }
3992     catch (ivx::RuntimeError & e)
3993     {
3994         VX_DbgThrow(e.what());
3995     }
3996     catch (ivx::WrapperError & e)
3997     {
3998         VX_DbgThrow(e.what());
3999     }
4000     return true;
4001 }
4002
4003 #endif
4004
4005 #ifdef HAVE_IPP
4006 #if IPP_VERSION_X100 == 201702  // IW 2017u2 has bug which doesn't allow use of partial inMem with tiling
4007 #define IPP_GAUSSIANBLUR_PARALLEL 0
4008 #else
4009 #define IPP_GAUSSIANBLUR_PARALLEL 1
4010 #endif
4011
4012 #ifdef HAVE_IPP_IW
4013
4014 class ipp_gaussianBlurParallel: public ParallelLoopBody
4015 {
4016 public:
4017     ipp_gaussianBlurParallel(::ipp::IwiImage &src, ::ipp::IwiImage &dst, int kernelSize, float sigma, ::ipp::IwiBorderType &border, bool *pOk):
4018         m_src(src), m_dst(dst), m_kernelSize(kernelSize), m_sigma(sigma), m_border(border), m_pOk(pOk) {
4019         *m_pOk = true;
4020     }
4021     ~ipp_gaussianBlurParallel()
4022     {
4023     }
4024
4025     virtual void operator() (const Range& range) const CV_OVERRIDE
4026     {
4027         CV_INSTRUMENT_REGION_IPP()
4028
4029         if(!*m_pOk)
4030             return;
4031
4032         try
4033         {
4034             ::ipp::IwiTile tile = ::ipp::IwiRoi(0, range.start, m_dst.m_size.width, range.end - range.start);
4035             CV_INSTRUMENT_FUN_IPP(::ipp::iwiFilterGaussian, m_src, m_dst, m_kernelSize, m_sigma, ::ipp::IwDefault(), m_border, tile);
4036         }
4037         catch(::ipp::IwException e)
4038         {
4039             *m_pOk = false;
4040             return;
4041         }
4042     }
4043 private:
4044     ::ipp::IwiImage &m_src;
4045     ::ipp::IwiImage &m_dst;
4046
4047     int m_kernelSize;
4048     float m_sigma;
4049     ::ipp::IwiBorderType &m_border;
4050
4051     volatile bool *m_pOk;
4052     const ipp_gaussianBlurParallel& operator= (const ipp_gaussianBlurParallel&);
4053 };
4054
4055 #endif
4056
4057 static bool ipp_GaussianBlur(InputArray _src, OutputArray _dst, Size ksize,
4058                    double sigma1, double sigma2, int borderType )
4059 {
4060 #ifdef HAVE_IPP_IW
4061     CV_INSTRUMENT_REGION_IPP()
4062
4063 #if IPP_VERSION_X100 < 201800 && ((defined _MSC_VER && defined _M_IX86) || (defined __GNUC__ && defined __i386__))
4064     CV_UNUSED(_src); CV_UNUSED(_dst); CV_UNUSED(ksize); CV_UNUSED(sigma1); CV_UNUSED(sigma2); CV_UNUSED(borderType);
4065     return false; // bug on ia32
4066 #else
4067     if(sigma1 != sigma2)
4068         return false;
4069
4070     if(sigma1 < FLT_EPSILON)
4071         return false;
4072
4073     if(ksize.width != ksize.height)
4074         return false;
4075
4076     // Acquire data and begin processing
4077     try
4078     {
4079         Mat src = _src.getMat();
4080         Mat dst = _dst.getMat();
4081         ::ipp::IwiImage       iwSrc      = ippiGetImage(src);
4082         ::ipp::IwiImage       iwDst      = ippiGetImage(dst);
4083         ::ipp::IwiBorderSize  borderSize = ::ipp::iwiSizeToBorderSize(ippiGetSize(ksize));
4084         ::ipp::IwiBorderType  ippBorder(ippiGetBorder(iwSrc, borderType, borderSize));
4085         if(!ippBorder)
4086             return false;
4087
4088         const int threads = ippiSuggestThreadsNum(iwDst, 2);
4089         if(IPP_GAUSSIANBLUR_PARALLEL && threads > 1) {
4090             bool ok;
4091             ipp_gaussianBlurParallel invoker(iwSrc, iwDst, ksize.width, (float) sigma1, ippBorder, &ok);
4092
4093             if(!ok)
4094                 return false;
4095             const Range range(0, (int) iwDst.m_size.height);
4096             parallel_for_(range, invoker, threads*4);
4097
4098             if(!ok)
4099                 return false;
4100         } else {
4101             CV_INSTRUMENT_FUN_IPP(::ipp::iwiFilterGaussian, iwSrc, iwDst, ksize.width, sigma1, ::ipp::IwDefault(), ippBorder);
4102         }
4103     }
4104     catch (::ipp::IwException ex)
4105     {
4106         return false;
4107     }
4108
4109     return true;
4110 #endif
4111 #else
4112     CV_UNUSED(_src); CV_UNUSED(_dst); CV_UNUSED(ksize); CV_UNUSED(sigma1); CV_UNUSED(sigma2); CV_UNUSED(borderType);
4113     return false;
4114 #endif
4115 }
4116 #endif
4117 }
4118
4119 void cv::GaussianBlur( InputArray _src, OutputArray _dst, Size ksize,
4120                    double sigma1, double sigma2,
4121                    int borderType )
4122 {
4123     CV_INSTRUMENT_REGION()
4124
4125     int type = _src.type();
4126     Size size = _src.size();
4127     _dst.create( size, type );
4128
4129     if( (borderType & ~BORDER_ISOLATED) != BORDER_CONSTANT &&
4130         ((borderType & BORDER_ISOLATED) != 0 || !_src.getMat().isSubmatrix()) )
4131     {
4132         if( size.height == 1 )
4133             ksize.height = 1;
4134         if( size.width == 1 )
4135             ksize.width = 1;
4136     }
4137
4138     if( ksize.width == 1 && ksize.height == 1 )
4139     {
4140         _src.copyTo(_dst);
4141         return;
4142     }
4143
4144     bool useOpenCL = (ocl::isOpenCLActivated() && _dst.isUMat() && _src.dims() <= 2 &&
4145                ((ksize.width == 3 && ksize.height == 3) ||
4146                (ksize.width == 5 && ksize.height == 5)) &&
4147                _src.rows() > ksize.height && _src.cols() > ksize.width);
4148     (void)useOpenCL;
4149
4150     int sdepth = CV_MAT_DEPTH(type), cn = CV_MAT_CN(type);
4151
4152     if(sdepth == CV_8U && ((borderType & BORDER_ISOLATED) || !_src.getMat().isSubmatrix()))
4153     {
4154         std::vector<ufixedpoint16> fkx, fky;
4155         createGaussianKernels(fkx, fky, type, ksize, sigma1, sigma2);
4156         Mat src = _src.getMat();
4157         Mat dst = _dst.getMat();
4158         if (src.data == dst.data)
4159             src = src.clone();
4160         fixedSmoothInvoker<uint8_t, ufixedpoint16> invoker(src.ptr<uint8_t>(), src.step1(), dst.ptr<uint8_t>(), dst.step1(), dst.cols, dst.rows, dst.channels(), &fkx[0], (int)fkx.size(), &fky[0], (int)fky.size(), borderType & ~BORDER_ISOLATED);
4161         parallel_for_(Range(0, dst.rows), invoker, std::max(1, std::min(getNumThreads(), getNumberOfCPUs())));
4162         return;
4163     }
4164
4165
4166     Mat kx, ky;
4167     createGaussianKernels(kx, ky, type, ksize, sigma1, sigma2);
4168
4169     CV_OCL_RUN(useOpenCL, ocl_GaussianBlur_8UC1(_src, _dst, ksize, CV_MAT_DEPTH(type), kx, ky, borderType));
4170
4171     CV_OCL_RUN(_dst.isUMat() && _src.dims() <= 2 && (size_t)_src.rows() > kx.total() && (size_t)_src.cols() > kx.total(),
4172                ocl_sepFilter2D(_src, _dst, sdepth, kx, ky, Point(-1, -1), 0, borderType))
4173
4174     Mat src = _src.getMat();
4175     Mat dst = _dst.getMat();
4176
4177     Point ofs;
4178     Size wsz(src.cols, src.rows);
4179     if(!(borderType & BORDER_ISOLATED))
4180         src.locateROI( wsz, ofs );
4181
4182     CALL_HAL(gaussianBlur, cv_hal_gaussianBlur, src.ptr(), src.step, dst.ptr(), dst.step, src.cols, src.rows, sdepth, cn,
4183              ofs.x, ofs.y, wsz.width - src.cols - ofs.x, wsz.height - src.rows - ofs.y, ksize.width, ksize.height,
4184              sigma1, sigma2, borderType&~BORDER_ISOLATED);
4185
4186     CV_OVX_RUN(true,
4187                openvx_gaussianBlur(src, dst, ksize, sigma1, sigma2, borderType))
4188
4189     CV_IPP_RUN_FAST(ipp_GaussianBlur(src, dst, ksize, sigma1, sigma2, borderType));
4190
4191     sepFilter2D(src, dst, sdepth, kx, ky, Point(-1, -1), 0, borderType);
4192 }
4193
4194 /****************************************************************************************\
4195                                       Median Filter
4196 \****************************************************************************************/
4197
4198 namespace cv
4199 {
4200 typedef ushort HT;
4201
4202 /**
4203  * This structure represents a two-tier histogram. The first tier (known as the
4204  * "coarse" level) is 4 bit wide and the second tier (known as the "fine" level)
4205  * is 8 bit wide. Pixels inserted in the fine level also get inserted into the
4206  * coarse bucket designated by the 4 MSBs of the fine bucket value.
4207  *
4208  * The structure is aligned on 16 bits, which is a prerequisite for SIMD
4209  * instructions. Each bucket is 16 bit wide, which means that extra care must be
4210  * taken to prevent overflow.
4211  */
4212 typedef struct
4213 {
4214     HT coarse[16];
4215     HT fine[16][16];
4216 } Histogram;
4217
4218
4219 #if CV_SIMD128
4220
4221 static inline void histogram_add_simd( const HT x[16], HT y[16] )
4222 {
4223     v_store(y, v_load(x) + v_load(y));
4224     v_store(y + 8, v_load(x + 8) + v_load(y + 8));
4225 }
4226
4227 static inline void histogram_sub_simd( const HT x[16], HT y[16] )
4228 {
4229     v_store(y, v_load(y) - v_load(x));
4230     v_store(y + 8, v_load(y + 8) - v_load(x + 8));
4231 }
4232
4233 #endif
4234
4235
4236 static inline void histogram_add( const HT x[16], HT y[16] )
4237 {
4238     int i;
4239     for( i = 0; i < 16; ++i )
4240         y[i] = (HT)(y[i] + x[i]);
4241 }
4242
4243 static inline void histogram_sub( const HT x[16], HT y[16] )
4244 {
4245     int i;
4246     for( i = 0; i < 16; ++i )
4247         y[i] = (HT)(y[i] - x[i]);
4248 }
4249
4250 static inline void histogram_muladd( int a, const HT x[16],
4251         HT y[16] )
4252 {
4253     for( int i = 0; i < 16; ++i )
4254         y[i] = (HT)(y[i] + a * x[i]);
4255 }
4256
4257 static void
4258 medianBlur_8u_O1( const Mat& _src, Mat& _dst, int ksize )
4259 {
4260 /**
4261  * HOP is short for Histogram OPeration. This macro makes an operation \a op on
4262  * histogram \a h for pixel value \a x. It takes care of handling both levels.
4263  */
4264 #define HOP(h,x,op) \
4265     h.coarse[x>>4] op, \
4266     *((HT*)h.fine + x) op
4267
4268 #define COP(c,j,x,op) \
4269     h_coarse[ 16*(n*c+j) + (x>>4) ] op, \
4270     h_fine[ 16 * (n*(16*c+(x>>4)) + j) + (x & 0xF) ] op
4271
4272     int cn = _dst.channels(), m = _dst.rows, r = (ksize-1)/2;
4273     CV_Assert(cn > 0 && cn <= 4);
4274     size_t sstep = _src.step, dstep = _dst.step;
4275     Histogram CV_DECL_ALIGNED(16) H[4];
4276     HT CV_DECL_ALIGNED(16) luc[4][16];
4277
4278     int STRIPE_SIZE = std::min( _dst.cols, 512/cn );
4279
4280     std::vector<HT> _h_coarse(1 * 16 * (STRIPE_SIZE + 2*r) * cn + 16);
4281     std::vector<HT> _h_fine(16 * 16 * (STRIPE_SIZE + 2*r) * cn + 16);
4282     HT* h_coarse = alignPtr(&_h_coarse[0], 16);
4283     HT* h_fine = alignPtr(&_h_fine[0], 16);
4284 #if CV_SIMD128
4285     volatile bool useSIMD = hasSIMD128();
4286 #endif
4287
4288     for( int x = 0; x < _dst.cols; x += STRIPE_SIZE )
4289     {
4290         int i, j, k, c, n = std::min(_dst.cols - x, STRIPE_SIZE) + r*2;
4291         const uchar* src = _src.ptr() + x*cn;
4292         uchar* dst = _dst.ptr() + (x - r)*cn;
4293
4294         memset( h_coarse, 0, 16*n*cn*sizeof(h_coarse[0]) );
4295         memset( h_fine, 0, 16*16*n*cn*sizeof(h_fine[0]) );
4296
4297         // First row initialization
4298         for( c = 0; c < cn; c++ )
4299         {
4300             for( j = 0; j < n; j++ )
4301                 COP( c, j, src[cn*j+c], += (cv::HT)(r+2) );
4302
4303             for( i = 1; i < r; i++ )
4304             {
4305                 const uchar* p = src + sstep*std::min(i, m-1);
4306                 for ( j = 0; j < n; j++ )
4307                     COP( c, j, p[cn*j+c], ++ );
4308             }
4309         }
4310
4311         for( i = 0; i < m; i++ )
4312         {
4313             const uchar* p0 = src + sstep * std::max( 0, i-r-1 );
4314             const uchar* p1 = src + sstep * std::min( m-1, i+r );
4315
4316             memset( H, 0, cn*sizeof(H[0]) );
4317             memset( luc, 0, cn*sizeof(luc[0]) );
4318             for( c = 0; c < cn; c++ )
4319             {
4320                 // Update column histograms for the entire row.
4321                 for( j = 0; j < n; j++ )
4322                 {
4323                     COP( c, j, p0[j*cn + c], -- );
4324                     COP( c, j, p1[j*cn + c], ++ );
4325                 }
4326
4327                 // First column initialization
4328                 for( k = 0; k < 16; ++k )
4329                     histogram_muladd( 2*r+1, &h_fine[16*n*(16*c+k)], &H[c].fine[k][0] );
4330
4331 #if CV_SIMD128
4332                 if( useSIMD )
4333                 {
4334                     for( j = 0; j < 2*r; ++j )
4335                         histogram_add_simd( &h_coarse[16*(n*c+j)], H[c].coarse );
4336
4337                     for( j = r; j < n-r; j++ )
4338                     {
4339                         int t = 2*r*r + 2*r, b, sum = 0;
4340                         HT* segment;
4341
4342                         histogram_add_simd( &h_coarse[16*(n*c + std::min(j+r,n-1))], H[c].coarse );
4343
4344                         // Find median at coarse level
4345                         for ( k = 0; k < 16 ; ++k )
4346                         {
4347                             sum += H[c].coarse[k];
4348                             if ( sum > t )
4349                             {
4350                                 sum -= H[c].coarse[k];
4351                                 break;
4352                             }
4353                         }
4354                         CV_Assert( k < 16 );
4355
4356                         /* Update corresponding histogram segment */
4357                         if ( luc[c][k] <= j-r )
4358                         {
4359                             memset( &H[c].fine[k], 0, 16 * sizeof(HT) );
4360                             for ( luc[c][k] = cv::HT(j-r); luc[c][k] < MIN(j+r+1,n); ++luc[c][k] )
4361                                 histogram_add_simd( &h_fine[16*(n*(16*c+k)+luc[c][k])], H[c].fine[k] );
4362
4363                             if ( luc[c][k] < j+r+1 )
4364                             {
4365                                 histogram_muladd( j+r+1 - n, &h_fine[16*(n*(16*c+k)+(n-1))], &H[c].fine[k][0] );
4366                                 luc[c][k] = (HT)(j+r+1);
4367                             }
4368                         }
4369                         else
4370                         {
4371                             for ( ; luc[c][k] < j+r+1; ++luc[c][k] )
4372                             {
4373                                 histogram_sub_simd( &h_fine[16*(n*(16*c+k)+MAX(luc[c][k]-2*r-1,0))], H[c].fine[k] );
4374                                 histogram_add_simd( &h_fine[16*(n*(16*c+k)+MIN(luc[c][k],n-1))], H[c].fine[k] );
4375                             }
4376                         }
4377
4378                         histogram_sub_simd( &h_coarse[16*(n*c+MAX(j-r,0))], H[c].coarse );
4379
4380                         /* Find median in segment */
4381                         segment = H[c].fine[k];
4382                         for ( b = 0; b < 16 ; b++ )
4383                         {
4384                             sum += segment[b];
4385                             if ( sum > t )
4386                             {
4387                                 dst[dstep*i+cn*j+c] = (uchar)(16*k + b);
4388                                 break;
4389                             }
4390                         }
4391                         CV_Assert( b < 16 );
4392                     }
4393                 }
4394                 else
4395 #endif
4396                 {
4397                     for( j = 0; j < 2*r; ++j )
4398                         histogram_add( &h_coarse[16*(n*c+j)], H[c].coarse );
4399
4400                     for( j = r; j < n-r; j++ )
4401                     {
4402                         int t = 2*r*r + 2*r, b, sum = 0;
4403                         HT* segment;
4404
4405                         histogram_add( &h_coarse[16*(n*c + std::min(j+r,n-1))], H[c].coarse );
4406
4407                         // Find median at coarse level
4408                         for ( k = 0; k < 16 ; ++k )
4409                         {
4410                             sum += H[c].coarse[k];
4411                             if ( sum > t )
4412                             {
4413                                 sum -= H[c].coarse[k];
4414                                 break;
4415                             }
4416                         }
4417                         CV_Assert( k < 16 );
4418
4419                         /* Update corresponding histogram segment */
4420                         if ( luc[c][k] <= j-r )
4421                         {
4422                             memset( &H[c].fine[k], 0, 16 * sizeof(HT) );
4423                             for ( luc[c][k] = cv::HT(j-r); luc[c][k] < MIN(j+r+1,n); ++luc[c][k] )
4424                                 histogram_add( &h_fine[16*(n*(16*c+k)+luc[c][k])], H[c].fine[k] );
4425
4426                             if ( luc[c][k] < j+r+1 )
4427                             {
4428                                 histogram_muladd( j+r+1 - n, &h_fine[16*(n*(16*c+k)+(n-1))], &H[c].fine[k][0] );
4429                                 luc[c][k] = (HT)(j+r+1);
4430                             }
4431                         }
4432                         else
4433                         {
4434                             for ( ; luc[c][k] < j+r+1; ++luc[c][k] )
4435                             {
4436                                 histogram_sub( &h_fine[16*(n*(16*c+k)+MAX(luc[c][k]-2*r-1,0))], H[c].fine[k] );
4437                                 histogram_add( &h_fine[16*(n*(16*c+k)+MIN(luc[c][k],n-1))], H[c].fine[k] );
4438                             }
4439                         }
4440
4441                         histogram_sub( &h_coarse[16*(n*c+MAX(j-r,0))], H[c].coarse );
4442
4443                         /* Find median in segment */
4444                         segment = H[c].fine[k];
4445                         for ( b = 0; b < 16 ; b++ )
4446                         {
4447                             sum += segment[b];
4448                             if ( sum > t )
4449                             {
4450                                 dst[dstep*i+cn*j+c] = (uchar)(16*k + b);
4451                                 break;
4452                             }
4453                         }
4454                         CV_Assert( b < 16 );
4455                     }
4456                 }
4457             }
4458         }
4459     }
4460
4461 #undef HOP
4462 #undef COP
4463 }
4464
4465 static void
4466 medianBlur_8u_Om( const Mat& _src, Mat& _dst, int m )
4467 {
4468     #define N  16
4469     int     zone0[4][N];
4470     int     zone1[4][N*N];
4471     int     x, y;
4472     int     n2 = m*m/2;
4473     Size    size = _dst.size();
4474     const uchar* src = _src.ptr();
4475     uchar*  dst = _dst.ptr();
4476     int     src_step = (int)_src.step, dst_step = (int)_dst.step;
4477     int     cn = _src.channels();
4478     const uchar*  src_max = src + size.height*src_step;
4479     CV_Assert(cn > 0 && cn <= 4);
4480
4481     #define UPDATE_ACC01( pix, cn, op ) \
4482     {                                   \
4483         int p = (pix);                  \
4484         zone1[cn][p] op;                \
4485         zone0[cn][p >> 4] op;           \
4486     }
4487
4488     //CV_Assert( size.height >= nx && size.width >= nx );
4489     for( x = 0; x < size.width; x++, src += cn, dst += cn )
4490     {
4491         uchar* dst_cur = dst;
4492         const uchar* src_top = src;
4493         const uchar* src_bottom = src;
4494         int k, c;
4495         int src_step1 = src_step, dst_step1 = dst_step;
4496
4497         if( x % 2 != 0 )
4498         {
4499             src_bottom = src_top += src_step*(size.height-1);
4500             dst_cur += dst_step*(size.height-1);
4501             src_step1 = -src_step1;
4502             dst_step1 = -dst_step1;
4503         }
4504
4505         // init accumulator
4506         memset( zone0, 0, sizeof(zone0[0])*cn );
4507         memset( zone1, 0, sizeof(zone1[0])*cn );
4508
4509         for( y = 0; y <= m/2; y++ )
4510         {
4511             for( c = 0; c < cn; c++ )
4512             {
4513                 if( y > 0 )
4514                 {
4515                     for( k = 0; k < m*cn; k += cn )
4516                         UPDATE_ACC01( src_bottom[k+c], c, ++ );
4517                 }
4518                 else
4519                 {
4520                     for( k = 0; k < m*cn; k += cn )
4521                         UPDATE_ACC01( src_bottom[k+c], c, += m/2+1 );
4522                 }
4523             }
4524
4525             if( (src_step1 > 0 && y < size.height-1) ||
4526                 (src_step1 < 0 && size.height-y-1 > 0) )
4527                 src_bottom += src_step1;
4528         }
4529
4530         for( y = 0; y < size.height; y++, dst_cur += dst_step1 )
4531         {
4532             // find median
4533             for( c = 0; c < cn; c++ )
4534             {
4535                 int s = 0;
4536                 for( k = 0; ; k++ )
4537                 {
4538                     int t = s + zone0[c][k];
4539                     if( t > n2 ) break;
4540                     s = t;
4541                 }
4542
4543                 for( k *= N; ;k++ )
4544                 {
4545                     s += zone1[c][k];
4546                     if( s > n2 ) break;
4547                 }
4548
4549                 dst_cur[c] = (uchar)k;
4550             }
4551
4552             if( y+1 == size.height )
4553                 break;
4554
4555             if( cn == 1 )
4556             {
4557                 for( k = 0; k < m; k++ )
4558                 {
4559                     int p = src_top[k];
4560                     int q = src_bottom[k];
4561                     zone1[0][p]--;
4562                     zone0[0][p>>4]--;
4563                     zone1[0][q]++;
4564                     zone0[0][q>>4]++;
4565                 }
4566             }
4567             else if( cn == 3 )
4568             {
4569                 for( k = 0; k < m*3; k += 3 )
4570                 {
4571                     UPDATE_ACC01( src_top[k], 0, -- );
4572                     UPDATE_ACC01( src_top[k+1], 1, -- );
4573                     UPDATE_ACC01( src_top[k+2], 2, -- );
4574
4575                     UPDATE_ACC01( src_bottom[k], 0, ++ );
4576                     UPDATE_ACC01( src_bottom[k+1], 1, ++ );
4577                     UPDATE_ACC01( src_bottom[k+2], 2, ++ );
4578                 }
4579             }
4580             else
4581             {
4582                 assert( cn == 4 );
4583                 for( k = 0; k < m*4; k += 4 )
4584                 {
4585                     UPDATE_ACC01( src_top[k], 0, -- );
4586                     UPDATE_ACC01( src_top[k+1], 1, -- );
4587                     UPDATE_ACC01( src_top[k+2], 2, -- );
4588                     UPDATE_ACC01( src_top[k+3], 3, -- );
4589
4590                     UPDATE_ACC01( src_bottom[k], 0, ++ );
4591                     UPDATE_ACC01( src_bottom[k+1], 1, ++ );
4592                     UPDATE_ACC01( src_bottom[k+2], 2, ++ );
4593                     UPDATE_ACC01( src_bottom[k+3], 3, ++ );
4594                 }
4595             }
4596
4597             if( (src_step1 > 0 && src_bottom + src_step1 < src_max) ||
4598                 (src_step1 < 0 && src_bottom + src_step1 >= src) )
4599                 src_bottom += src_step1;
4600
4601             if( y >= m/2 )
4602                 src_top += src_step1;
4603         }
4604     }
4605 #undef N
4606 #undef UPDATE_ACC
4607 }
4608
4609
4610 struct MinMax8u
4611 {
4612     typedef uchar value_type;
4613     typedef int arg_type;
4614     enum { SIZE = 1 };
4615     arg_type load(const uchar* ptr) { return *ptr; }
4616     void store(uchar* ptr, arg_type val) { *ptr = (uchar)val; }
4617     void operator()(arg_type& a, arg_type& b) const
4618     {
4619         int t = CV_FAST_CAST_8U(a - b);
4620         b += t; a -= t;
4621     }
4622 };
4623
4624 struct MinMax16u
4625 {
4626     typedef ushort value_type;
4627     typedef int arg_type;
4628     enum { SIZE = 1 };
4629     arg_type load(const ushort* ptr) { return *ptr; }
4630     void store(ushort* ptr, arg_type val) { *ptr = (ushort)val; }
4631     void operator()(arg_type& a, arg_type& b) const
4632     {
4633         arg_type t = a;
4634         a = std::min(a, b);
4635         b = std::max(b, t);
4636     }
4637 };
4638
4639 struct MinMax16s
4640 {
4641     typedef short value_type;
4642     typedef int arg_type;
4643     enum { SIZE = 1 };
4644     arg_type load(const short* ptr) { return *ptr; }
4645     void store(short* ptr, arg_type val) { *ptr = (short)val; }
4646     void operator()(arg_type& a, arg_type& b) const
4647     {
4648         arg_type t = a;
4649         a = std::min(a, b);
4650         b = std::max(b, t);
4651     }
4652 };
4653
4654 struct MinMax32f
4655 {
4656     typedef float value_type;
4657     typedef float arg_type;
4658     enum { SIZE = 1 };
4659     arg_type load(const float* ptr) { return *ptr; }
4660     void store(float* ptr, arg_type val) { *ptr = val; }
4661     void operator()(arg_type& a, arg_type& b) const
4662     {
4663         arg_type t = a;
4664         a = std::min(a, b);
4665         b = std::max(b, t);
4666     }
4667 };
4668
4669 #if CV_SIMD128
4670
4671 struct MinMaxVec8u
4672 {
4673     typedef uchar value_type;
4674     typedef v_uint8x16 arg_type;
4675     enum { SIZE = 16 };
4676     arg_type load(const uchar* ptr) { return v_load(ptr); }
4677     void store(uchar* ptr, const arg_type &val) { v_store(ptr, val); }
4678     void operator()(arg_type& a, arg_type& b) const
4679     {
4680         arg_type t = a;
4681         a = v_min(a, b);
4682         b = v_max(b, t);
4683     }
4684 };
4685
4686
4687 struct MinMaxVec16u
4688 {
4689     typedef ushort value_type;
4690     typedef v_uint16x8 arg_type;
4691     enum { SIZE = 8 };
4692     arg_type load(const ushort* ptr) { return v_load(ptr); }
4693     void store(ushort* ptr, const arg_type &val) { v_store(ptr, val); }
4694     void operator()(arg_type& a, arg_type& b) const
4695     {
4696         arg_type t = a;
4697         a = v_min(a, b);
4698         b = v_max(b, t);
4699     }
4700 };
4701
4702
4703 struct MinMaxVec16s
4704 {
4705     typedef short value_type;
4706     typedef v_int16x8 arg_type;
4707     enum { SIZE = 8 };
4708     arg_type load(const short* ptr) { return v_load(ptr); }
4709     void store(short* ptr, const arg_type &val) { v_store(ptr, val); }
4710     void operator()(arg_type& a, arg_type& b) const
4711     {
4712         arg_type t = a;
4713         a = v_min(a, b);
4714         b = v_max(b, t);
4715     }
4716 };
4717
4718
4719 struct MinMaxVec32f
4720 {
4721     typedef float value_type;
4722     typedef v_float32x4 arg_type;
4723     enum { SIZE = 4 };
4724     arg_type load(const float* ptr) { return v_load(ptr); }
4725     void store(float* ptr, const arg_type &val) { v_store(ptr, val); }
4726     void operator()(arg_type& a, arg_type& b) const
4727     {
4728         arg_type t = a;
4729         a = v_min(a, b);
4730         b = v_max(b, t);
4731     }
4732 };
4733
4734 #else
4735
4736 typedef MinMax8u MinMaxVec8u;
4737 typedef MinMax16u MinMaxVec16u;
4738 typedef MinMax16s MinMaxVec16s;
4739 typedef MinMax32f MinMaxVec32f;
4740
4741 #endif
4742
4743 template<class Op, class VecOp>
4744 static void
4745 medianBlur_SortNet( const Mat& _src, Mat& _dst, int m )
4746 {
4747     typedef typename Op::value_type T;
4748     typedef typename Op::arg_type WT;
4749     typedef typename VecOp::arg_type VT;
4750
4751     const T* src = _src.ptr<T>();
4752     T* dst = _dst.ptr<T>();
4753     int sstep = (int)(_src.step/sizeof(T));
4754     int dstep = (int)(_dst.step/sizeof(T));
4755     Size size = _dst.size();
4756     int i, j, k, cn = _src.channels();
4757     Op op;
4758     VecOp vop;
4759     volatile bool useSIMD = hasSIMD128();
4760
4761     if( m == 3 )
4762     {
4763         if( size.width == 1 || size.height == 1 )
4764         {
4765             int len = size.width + size.height - 1;
4766             int sdelta = size.height == 1 ? cn : sstep;
4767             int sdelta0 = size.height == 1 ? 0 : sstep - cn;
4768             int ddelta = size.height == 1 ? cn : dstep;
4769
4770             for( i = 0; i < len; i++, src += sdelta0, dst += ddelta )
4771                 for( j = 0; j < cn; j++, src++ )
4772                 {
4773                     WT p0 = src[i > 0 ? -sdelta : 0];
4774                     WT p1 = src[0];
4775                     WT p2 = src[i < len - 1 ? sdelta : 0];
4776
4777                     op(p0, p1); op(p1, p2); op(p0, p1);
4778                     dst[j] = (T)p1;
4779                 }
4780             return;
4781         }
4782
4783         size.width *= cn;
4784         for( i = 0; i < size.height; i++, dst += dstep )
4785         {
4786             const T* row0 = src + std::max(i - 1, 0)*sstep;
4787             const T* row1 = src + i*sstep;
4788             const T* row2 = src + std::min(i + 1, size.height-1)*sstep;
4789             int limit = useSIMD ? cn : size.width;
4790
4791             for(j = 0;; )
4792             {
4793                 for( ; j < limit; j++ )
4794                 {
4795                     int j0 = j >= cn ? j - cn : j;
4796                     int j2 = j < size.width - cn ? j + cn : j;
4797                     WT p0 = row0[j0], p1 = row0[j], p2 = row0[j2];
4798                     WT p3 = row1[j0], p4 = row1[j], p5 = row1[j2];
4799                     WT p6 = row2[j0], p7 = row2[j], p8 = row2[j2];
4800
4801                     op(p1, p2); op(p4, p5); op(p7, p8); op(p0, p1);
4802                     op(p3, p4); op(p6, p7); op(p1, p2); op(p4, p5);
4803                     op(p7, p8); op(p0, p3); op(p5, p8); op(p4, p7);
4804                     op(p3, p6); op(p1, p4); op(p2, p5); op(p4, p7);
4805                     op(p4, p2); op(p6, p4); op(p4, p2);
4806                     dst[j] = (T)p4;
4807                 }
4808
4809                 if( limit == size.width )
4810                     break;
4811
4812                 for( ; j <= size.width - VecOp::SIZE - cn; j += VecOp::SIZE )
4813                 {
4814                     VT p0 = vop.load(row0+j-cn), p1 = vop.load(row0+j), p2 = vop.load(row0+j+cn);
4815                     VT p3 = vop.load(row1+j-cn), p4 = vop.load(row1+j), p5 = vop.load(row1+j+cn);
4816                     VT p6 = vop.load(row2+j-cn), p7 = vop.load(row2+j), p8 = vop.load(row2+j+cn);
4817
4818                     vop(p1, p2); vop(p4, p5); vop(p7, p8); vop(p0, p1);
4819                     vop(p3, p4); vop(p6, p7); vop(p1, p2); vop(p4, p5);
4820                     vop(p7, p8); vop(p0, p3); vop(p5, p8); vop(p4, p7);
4821                     vop(p3, p6); vop(p1, p4); vop(p2, p5); vop(p4, p7);
4822                     vop(p4, p2); vop(p6, p4); vop(p4, p2);
4823                     vop.store(dst+j, p4);
4824                 }
4825
4826                 limit = size.width;
4827             }
4828         }
4829     }
4830     else if( m == 5 )
4831     {
4832         if( size.width == 1 || size.height == 1 )
4833         {
4834             int len = size.width + size.height - 1;
4835             int sdelta = size.height == 1 ? cn : sstep;
4836             int sdelta0 = size.height == 1 ? 0 : sstep - cn;
4837             int ddelta = size.height == 1 ? cn : dstep;
4838
4839             for( i = 0; i < len; i++, src += sdelta0, dst += ddelta )
4840                 for( j = 0; j < cn; j++, src++ )
4841                 {
4842                     int i1 = i > 0 ? -sdelta : 0;
4843                     int i0 = i > 1 ? -sdelta*2 : i1;
4844                     int i3 = i < len-1 ? sdelta : 0;
4845                     int i4 = i < len-2 ? sdelta*2 : i3;
4846                     WT p0 = src[i0], p1 = src[i1], p2 = src[0], p3 = src[i3], p4 = src[i4];
4847
4848                     op(p0, p1); op(p3, p4); op(p2, p3); op(p3, p4); op(p0, p2);
4849                     op(p2, p4); op(p1, p3); op(p1, p2);
4850                     dst[j] = (T)p2;
4851                 }
4852             return;
4853         }
4854
4855         size.width *= cn;
4856         for( i = 0; i < size.height; i++, dst += dstep )
4857         {
4858             const T* row[5];
4859             row[0] = src + std::max(i - 2, 0)*sstep;
4860             row[1] = src + std::max(i - 1, 0)*sstep;
4861             row[2] = src + i*sstep;
4862             row[3] = src + std::min(i + 1, size.height-1)*sstep;
4863             row[4] = src + std::min(i + 2, size.height-1)*sstep;
4864             int limit = useSIMD ? cn*2 : size.width;
4865
4866             for(j = 0;; )
4867             {
4868                 for( ; j < limit; j++ )
4869                 {
4870                     WT p[25];
4871                     int j1 = j >= cn ? j - cn : j;
4872                     int j0 = j >= cn*2 ? j - cn*2 : j1;
4873                     int j3 = j < size.width - cn ? j + cn : j;
4874                     int j4 = j < size.width - cn*2 ? j + cn*2 : j3;
4875                     for( k = 0; k < 5; k++ )
4876                     {
4877                         const T* rowk = row[k];
4878                         p[k*5] = rowk[j0]; p[k*5+1] = rowk[j1];
4879                         p[k*5+2] = rowk[j]; p[k*5+3] = rowk[j3];
4880                         p[k*5+4] = rowk[j4];
4881                     }
4882
4883                     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]);
4884                     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]);
4885                     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]);
4886                     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]);
4887                     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]);
4888                     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]);
4889                     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]);
4890                     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]);
4891                     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]);
4892                     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]);
4893                     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]);
4894                     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]);
4895                     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]);
4896                     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]);
4897                     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]);
4898                     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]);
4899                     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]);
4900                     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]);
4901                     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]);
4902                     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]);
4903                     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]);
4904                     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]);
4905                     op(p[7], p[11]); op(p[11], p[13]); op(p[11], p[12]);
4906                     dst[j] = (T)p[12];
4907                 }
4908
4909                 if( limit == size.width )
4910                     break;
4911
4912                 for( ; j <= size.width - VecOp::SIZE - cn*2; j += VecOp::SIZE )
4913                 {
4914                     VT p[25];
4915                     for( k = 0; k < 5; k++ )
4916                     {
4917                         const T* rowk = row[k];
4918                         p[k*5] = vop.load(rowk+j-cn*2); p[k*5+1] = vop.load(rowk+j-cn);
4919                         p[k*5+2] = vop.load(rowk+j); p[k*5+3] = vop.load(rowk+j+cn);
4920                         p[k*5+4] = vop.load(rowk+j+cn*2);
4921                     }
4922
4923                     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]);
4924                     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]);
4925                     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]);
4926                     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]);
4927                     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]);
4928                     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]);
4929                     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]);
4930                     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]);
4931                     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]);
4932                     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]);
4933                     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]);
4934                     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]);
4935                     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]);
4936                     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]);
4937                     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]);
4938                     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]);
4939                     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]);
4940                     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]);
4941                     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]);
4942                     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]);
4943                     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]);
4944                     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]);
4945                     vop(p[7], p[11]); vop(p[11], p[13]); vop(p[11], p[12]);
4946                     vop.store(dst+j, p[12]);
4947                 }
4948
4949                 limit = size.width;
4950             }
4951         }
4952     }
4953 }
4954
4955 #ifdef HAVE_OPENCL
4956
4957 static bool ocl_medianFilter(InputArray _src, OutputArray _dst, int m)
4958 {
4959     size_t localsize[2] = { 16, 16 };
4960     size_t globalsize[2];
4961     int type = _src.type(), depth = CV_MAT_DEPTH(type), cn = CV_MAT_CN(type);
4962
4963     if ( !((depth == CV_8U || depth == CV_16U || depth == CV_16S || depth == CV_32F) && cn <= 4 && (m == 3 || m == 5)) )
4964         return false;
4965
4966     Size imgSize = _src.size();
4967     bool useOptimized = (1 == cn) &&
4968                         (size_t)imgSize.width >= localsize[0] * 8  &&
4969                         (size_t)imgSize.height >= localsize[1] * 8 &&
4970                         imgSize.width % 4 == 0 &&
4971                         imgSize.height % 4 == 0 &&
4972                         (ocl::Device::getDefault().isIntel());
4973
4974     cv::String kname = format( useOptimized ? "medianFilter%d_u" : "medianFilter%d", m) ;
4975     cv::String kdefs = useOptimized ?
4976                          format("-D T=%s -D T1=%s -D T4=%s%d -D cn=%d -D USE_4OPT", ocl::typeToStr(type),
4977                          ocl::typeToStr(depth), ocl::typeToStr(depth), cn*4, cn)
4978                          :
4979                          format("-D T=%s -D T1=%s -D cn=%d", ocl::typeToStr(type), ocl::typeToStr(depth), cn) ;
4980
4981     ocl::Kernel k(kname.c_str(), ocl::imgproc::medianFilter_oclsrc, kdefs.c_str() );
4982
4983     if (k.empty())
4984         return false;
4985
4986     UMat src = _src.getUMat();
4987     _dst.create(src.size(), type);
4988     UMat dst = _dst.getUMat();
4989
4990     k.args(ocl::KernelArg::ReadOnlyNoSize(src), ocl::KernelArg::WriteOnly(dst));
4991
4992     if( useOptimized )
4993     {
4994         globalsize[0] = DIVUP(src.cols / 4, localsize[0]) * localsize[0];
4995         globalsize[1] = DIVUP(src.rows / 4, localsize[1]) * localsize[1];
4996     }
4997     else
4998     {
4999         globalsize[0] = (src.cols + localsize[0] + 2) / localsize[0] * localsize[0];
5000         globalsize[1] = (src.rows + localsize[1] - 1) / localsize[1] * localsize[1];
5001     }
5002
5003     return k.run(2, globalsize, localsize, false);
5004 }
5005
5006 #endif
5007
5008 }
5009
5010 #ifdef HAVE_OPENVX
5011 namespace cv
5012 {
5013     namespace ovx {
5014         template <> inline bool skipSmallImages<VX_KERNEL_MEDIAN_3x3>(int w, int h) { return w*h < 1280 * 720; }
5015     }
5016     static bool openvx_medianFilter(InputArray _src, OutputArray _dst, int ksize)
5017     {
5018         if (_src.type() != CV_8UC1 || _dst.type() != CV_8U
5019 #ifndef VX_VERSION_1_1
5020             || ksize != 3
5021 #endif
5022             )
5023             return false;
5024
5025         Mat src = _src.getMat();
5026         Mat dst = _dst.getMat();
5027
5028         if (
5029 #ifdef VX_VERSION_1_1
5030              ksize != 3 ? ovx::skipSmallImages<VX_KERNEL_NON_LINEAR_FILTER>(src.cols, src.rows) :
5031 #endif
5032              ovx::skipSmallImages<VX_KERNEL_MEDIAN_3x3>(src.cols, src.rows)
5033            )
5034             return false;
5035
5036         try
5037         {
5038             ivx::Context ctx = ovx::getOpenVXContext();
5039 #ifdef VX_VERSION_1_1
5040             if ((vx_size)ksize > ctx.nonlinearMaxDimension())
5041                 return false;
5042 #endif
5043
5044             Mat a;
5045             if (dst.data != src.data)
5046                 a = src;
5047             else
5048                 src.copyTo(a);
5049
5050             ivx::Image
5051                 ia = ivx::Image::createFromHandle(ctx, VX_DF_IMAGE_U8,
5052                     ivx::Image::createAddressing(a.cols, a.rows, 1, (vx_int32)(a.step)), a.data),
5053                 ib = ivx::Image::createFromHandle(ctx, VX_DF_IMAGE_U8,
5054                     ivx::Image::createAddressing(dst.cols, dst.rows, 1, (vx_int32)(dst.step)), dst.data);
5055
5056             //ATTENTION: VX_CONTEXT_IMMEDIATE_BORDER attribute change could lead to strange issues in multi-threaded environments
5057             //since OpenVX standard says nothing about thread-safety for now
5058             ivx::border_t prevBorder = ctx.immediateBorder();
5059             ctx.setImmediateBorder(VX_BORDER_REPLICATE);
5060 #ifdef VX_VERSION_1_1
5061             if (ksize == 3)
5062 #endif
5063             {
5064                 ivx::IVX_CHECK_STATUS(vxuMedian3x3(ctx, ia, ib));
5065             }
5066 #ifdef VX_VERSION_1_1
5067             else
5068             {
5069                 ivx::Matrix mtx;
5070                 if(ksize == 5)
5071                     mtx = ivx::Matrix::createFromPattern(ctx, VX_PATTERN_BOX, ksize, ksize);
5072                 else
5073                 {
5074                     vx_size supportedSize;
5075                     ivx::IVX_CHECK_STATUS(vxQueryContext(ctx, VX_CONTEXT_NONLINEAR_MAX_DIMENSION, &supportedSize, sizeof(supportedSize)));
5076                     if ((vx_size)ksize > supportedSize)
5077                     {
5078                         ctx.setImmediateBorder(prevBorder);
5079                         return false;
5080                     }
5081                     Mat mask(ksize, ksize, CV_8UC1, Scalar(255));
5082                     mtx = ivx::Matrix::create(ctx, VX_TYPE_UINT8, ksize, ksize);
5083                     mtx.copyFrom(mask);
5084                 }
5085                 ivx::IVX_CHECK_STATUS(vxuNonLinearFilter(ctx, VX_NONLINEAR_FILTER_MEDIAN, ia, mtx, ib));
5086             }
5087 #endif
5088             ctx.setImmediateBorder(prevBorder);
5089         }
5090         catch (ivx::RuntimeError & e)
5091         {
5092             VX_DbgThrow(e.what());
5093         }
5094         catch (ivx::WrapperError & e)
5095         {
5096             VX_DbgThrow(e.what());
5097         }
5098
5099         return true;
5100     }
5101 }
5102 #endif
5103
5104 #ifdef HAVE_IPP
5105 namespace cv
5106 {
5107 static bool ipp_medianFilter(Mat &src0, Mat &dst, int ksize)
5108 {
5109     CV_INSTRUMENT_REGION_IPP()
5110
5111 #if IPP_VERSION_X100 < 201801
5112     // Degradations for big kernel
5113     if(ksize > 7)
5114         return false;
5115 #endif
5116
5117     {
5118         int         bufSize;
5119         IppiSize    dstRoiSize = ippiSize(dst.cols, dst.rows), maskSize = ippiSize(ksize, ksize);
5120         IppDataType ippType = ippiGetDataType(src0.type());
5121         int         channels = src0.channels();
5122         IppAutoBuffer<Ipp8u> buffer;
5123
5124         if(src0.isSubmatrix())
5125             return false;
5126
5127         Mat src;
5128         if(dst.data != src0.data)
5129             src = src0;
5130         else
5131             src0.copyTo(src);
5132
5133         if(ippiFilterMedianBorderGetBufferSize(dstRoiSize, maskSize, ippType, channels, &bufSize) < 0)
5134             return false;
5135
5136         buffer.allocate(bufSize);
5137
5138         switch(ippType)
5139         {
5140         case ipp8u:
5141             if(channels == 1)
5142                 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;
5143             else if(channels == 3)
5144                 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;
5145             else if(channels == 4)
5146                 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;
5147             else
5148                 return false;
5149         case ipp16u:
5150             if(channels == 1)
5151                 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;
5152             else if(channels == 3)
5153                 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;
5154             else if(channels == 4)
5155                 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;
5156             else
5157                 return false;
5158         case ipp16s:
5159             if(channels == 1)
5160                 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;
5161             else if(channels == 3)
5162                 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;
5163             else if(channels == 4)
5164                 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;
5165             else
5166                 return false;
5167         case ipp32f:
5168             if(channels == 1)
5169                 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;
5170             else
5171                 return false;
5172         default:
5173             return false;
5174         }
5175     }
5176 }
5177 }
5178 #endif
5179
5180 void cv::medianBlur( InputArray _src0, OutputArray _dst, int ksize )
5181 {
5182     CV_INSTRUMENT_REGION()
5183
5184     CV_Assert( (ksize % 2 == 1) && (_src0.dims() <= 2 ));
5185
5186     if( ksize <= 1 || _src0.empty() )
5187     {
5188         _src0.copyTo(_dst);
5189         return;
5190     }
5191
5192     CV_OCL_RUN(_dst.isUMat(),
5193                ocl_medianFilter(_src0,_dst, ksize))
5194
5195     Mat src0 = _src0.getMat();
5196     _dst.create( src0.size(), src0.type() );
5197     Mat dst = _dst.getMat();
5198
5199     CALL_HAL(medianBlur, cv_hal_medianBlur, src0.data, src0.step, dst.data, dst.step, src0.cols, src0.rows, src0.depth(),
5200              src0.channels(), ksize);
5201
5202     CV_OVX_RUN(true,
5203                openvx_medianFilter(_src0, _dst, ksize))
5204
5205     CV_IPP_RUN_FAST(ipp_medianFilter(src0, dst, ksize));
5206
5207 #ifdef HAVE_TEGRA_OPTIMIZATION
5208     if (tegra::useTegra() && tegra::medianBlur(src0, dst, ksize))
5209         return;
5210 #endif
5211
5212     bool useSortNet = ksize == 3 || (ksize == 5
5213 #if !(CV_SIMD128)
5214             && ( src0.depth() > CV_8U || src0.channels() == 2 || src0.channels() > 4 )
5215 #endif
5216         );
5217
5218     Mat src;
5219     if( useSortNet )
5220     {
5221         if( dst.data != src0.data )
5222             src = src0;
5223         else
5224             src0.copyTo(src);
5225
5226         if( src.depth() == CV_8U )
5227             medianBlur_SortNet<MinMax8u, MinMaxVec8u>( src, dst, ksize );
5228         else if( src.depth() == CV_16U )
5229             medianBlur_SortNet<MinMax16u, MinMaxVec16u>( src, dst, ksize );
5230         else if( src.depth() == CV_16S )
5231             medianBlur_SortNet<MinMax16s, MinMaxVec16s>( src, dst, ksize );
5232         else if( src.depth() == CV_32F )
5233             medianBlur_SortNet<MinMax32f, MinMaxVec32f>( src, dst, ksize );
5234         else
5235             CV_Error(CV_StsUnsupportedFormat, "");
5236
5237         return;
5238     }
5239     else
5240     {
5241         cv::copyMakeBorder( src0, src, 0, 0, ksize/2, ksize/2, BORDER_REPLICATE|BORDER_ISOLATED);
5242
5243         int cn = src0.channels();
5244         CV_Assert( src.depth() == CV_8U && (cn == 1 || cn == 3 || cn == 4) );
5245
5246         double img_size_mp = (double)(src0.total())/(1 << 20);
5247         if( ksize <= 3 + (img_size_mp < 1 ? 12 : img_size_mp < 4 ? 6 : 2)*
5248             (CV_SIMD128 && hasSIMD128() ? 1 : 3))
5249             medianBlur_8u_Om( src, dst, ksize );
5250         else
5251             medianBlur_8u_O1( src, dst, ksize );
5252     }
5253 }
5254
5255 /****************************************************************************************\
5256                                    Bilateral Filtering
5257 \****************************************************************************************/
5258
5259 namespace cv
5260 {
5261
5262 class BilateralFilter_8u_Invoker :
5263     public ParallelLoopBody
5264 {
5265 public:
5266     BilateralFilter_8u_Invoker(Mat& _dest, const Mat& _temp, int _radius, int _maxk,
5267         int* _space_ofs, float *_space_weight, float *_color_weight) :
5268         temp(&_temp), dest(&_dest), radius(_radius),
5269         maxk(_maxk), space_ofs(_space_ofs), space_weight(_space_weight), color_weight(_color_weight)
5270     {
5271     }
5272
5273     virtual void operator() (const Range& range) const CV_OVERRIDE
5274     {
5275         int i, j, cn = dest->channels(), k;
5276         Size size = dest->size();
5277 #if CV_SIMD128
5278         int CV_DECL_ALIGNED(16) buf[4];
5279         bool haveSIMD128 = hasSIMD128();
5280 #endif
5281
5282         for( i = range.start; i < range.end; i++ )
5283         {
5284             const uchar* sptr = temp->ptr(i+radius) + radius*cn;
5285             uchar* dptr = dest->ptr(i);
5286
5287             if( cn == 1 )
5288             {
5289                 for( j = 0; j < size.width; j++ )
5290                 {
5291                     float sum = 0, wsum = 0;
5292                     int val0 = sptr[j];
5293                     k = 0;
5294 #if CV_SIMD128
5295                     if( haveSIMD128 )
5296                     {
5297                         v_float32x4 _val0 = v_setall_f32(static_cast<float>(val0));
5298                         v_float32x4 vsumw = v_setzero_f32();
5299                         v_float32x4 vsumc = v_setzero_f32();
5300
5301                         for( ; k <= maxk - 4; k += 4 )
5302                         {
5303                             v_float32x4 _valF = v_float32x4(sptr[j + space_ofs[k]],
5304                                 sptr[j + space_ofs[k + 1]],
5305                                 sptr[j + space_ofs[k + 2]],
5306                                 sptr[j + space_ofs[k + 3]]);
5307                             v_float32x4 _val = v_abs(_valF - _val0);
5308                             v_store(buf, v_round(_val));
5309
5310                             v_float32x4 _cw = v_float32x4(color_weight[buf[0]],
5311                                 color_weight[buf[1]],
5312                                 color_weight[buf[2]],
5313                                 color_weight[buf[3]]);
5314                             v_float32x4 _sw = v_load(space_weight+k);
5315 #if defined(_MSC_VER) && _MSC_VER == 1700/* MSVS 2012 */ && CV_AVX
5316                             // details: https://github.com/opencv/opencv/issues/11004
5317                             vsumw += _cw * _sw;
5318                             vsumc += _cw * _sw * _valF;
5319 #else
5320                             v_float32x4 _w = _cw * _sw;
5321                             _cw = _w * _valF;
5322
5323                             vsumw += _w;
5324                             vsumc += _cw;
5325 #endif
5326                         }
5327                         float *bufFloat = (float*)buf;
5328                         v_float32x4 sum4 = v_reduce_sum4(vsumw, vsumc, vsumw, vsumc);
5329                         v_store(bufFloat, sum4);
5330                         sum += bufFloat[1];
5331                         wsum += bufFloat[0];
5332                     }
5333 #endif
5334                     for( ; k < maxk; k++ )
5335                     {
5336                         int val = sptr[j + space_ofs[k]];
5337                         float w = space_weight[k]*color_weight[std::abs(val - val0)];
5338                         sum += val*w;
5339                         wsum += w;
5340                     }
5341                     // overflow is not possible here => there is no need to use cv::saturate_cast
5342                     dptr[j] = (uchar)cvRound(sum/wsum);
5343                 }
5344             }
5345             else
5346             {
5347                 assert( cn == 3 );
5348                 for( j = 0; j < size.width*3; j += 3 )
5349                 {
5350                     float sum_b = 0, sum_g = 0, sum_r = 0, wsum = 0;
5351                     int b0 = sptr[j], g0 = sptr[j+1], r0 = sptr[j+2];
5352                     k = 0;
5353 #if CV_SIMD128
5354                     if( haveSIMD128 )
5355                     {
5356                         v_float32x4 vsumw = v_setzero_f32();
5357                         v_float32x4 vsumb = v_setzero_f32();
5358                         v_float32x4 vsumg = v_setzero_f32();
5359                         v_float32x4 vsumr = v_setzero_f32();
5360                         const v_float32x4 _b0 = v_setall_f32(static_cast<float>(b0));
5361                         const v_float32x4 _g0 = v_setall_f32(static_cast<float>(g0));
5362                         const v_float32x4 _r0 = v_setall_f32(static_cast<float>(r0));
5363
5364                         for( ; k <= maxk - 4; k += 4 )
5365                         {
5366                             const uchar* const sptr_k0  = sptr + j + space_ofs[k];
5367                             const uchar* const sptr_k1  = sptr + j + space_ofs[k+1];
5368                             const uchar* const sptr_k2  = sptr + j + space_ofs[k+2];
5369                             const uchar* const sptr_k3  = sptr + j + space_ofs[k+3];
5370
5371                             v_float32x4 __b = v_cvt_f32(v_reinterpret_as_s32(v_load_expand_q(sptr_k0)));
5372                             v_float32x4 __g = v_cvt_f32(v_reinterpret_as_s32(v_load_expand_q(sptr_k1)));
5373                             v_float32x4 __r = v_cvt_f32(v_reinterpret_as_s32(v_load_expand_q(sptr_k2)));
5374                             v_float32x4 __z = v_cvt_f32(v_reinterpret_as_s32(v_load_expand_q(sptr_k3)));
5375                             v_float32x4 _b, _g, _r, _z;
5376
5377                             v_transpose4x4(__b, __g, __r, __z, _b, _g, _r, _z);
5378
5379                             v_float32x4 bt = v_abs(_b -_b0);
5380                             v_float32x4 gt = v_abs(_g -_g0);
5381                             v_float32x4 rt = v_abs(_r -_r0);
5382
5383                             bt = rt + bt + gt;
5384                             v_store(buf, v_round(bt));
5385
5386                             v_float32x4 _w  = v_float32x4(color_weight[buf[0]],color_weight[buf[1]],
5387                                                     color_weight[buf[2]],color_weight[buf[3]]);
5388                             v_float32x4 _sw = v_load(space_weight+k);
5389
5390 #if defined(_MSC_VER) && _MSC_VER == 1700/* MSVS 2012 */ && CV_AVX
5391                             // details: https://github.com/opencv/opencv/issues/11004
5392                             vsumw += _w * _sw;
5393                             vsumb += _w * _sw * _b;
5394                             vsumg += _w * _sw * _g;
5395                             vsumr += _w * _sw * _r;
5396 #else
5397                             _w *= _sw;
5398                             _b *=  _w;
5399                             _g *=  _w;
5400                             _r *=  _w;
5401
5402                             vsumw += _w;
5403                             vsumb += _b;
5404                             vsumg += _g;
5405                             vsumr += _r;
5406 #endif
5407                         }
5408                         float *bufFloat = (float*)buf;
5409                         v_float32x4 sum4 = v_reduce_sum4(vsumw, vsumb, vsumg, vsumr);
5410                         v_store(bufFloat, sum4);
5411                         wsum += bufFloat[0];
5412                         sum_b += bufFloat[1];
5413                         sum_g += bufFloat[2];
5414                         sum_r += bufFloat[3];
5415                     }
5416 #endif
5417
5418                     for( ; k < maxk; k++ )
5419                     {
5420                         const uchar* sptr_k = sptr + j + space_ofs[k];
5421                         int b = sptr_k[0], g = sptr_k[1], r = sptr_k[2];
5422                         float w = space_weight[k]*color_weight[std::abs(b - b0) +
5423                                                                std::abs(g - g0) + std::abs(r - r0)];
5424                         sum_b += b*w; sum_g += g*w; sum_r += r*w;
5425                         wsum += w;
5426                     }
5427                     wsum = 1.f/wsum;
5428                     b0 = cvRound(sum_b*wsum);
5429                     g0 = cvRound(sum_g*wsum);
5430                     r0 = cvRound(sum_r*wsum);
5431                     dptr[j] = (uchar)b0; dptr[j+1] = (uchar)g0; dptr[j+2] = (uchar)r0;
5432                 }
5433             }
5434         }
5435     }
5436
5437 private:
5438     const Mat *temp;
5439     Mat *dest;
5440     int radius, maxk, *space_ofs;
5441     float *space_weight, *color_weight;
5442 };
5443
5444 #ifdef HAVE_OPENCL
5445
5446 static bool ocl_bilateralFilter_8u(InputArray _src, OutputArray _dst, int d,
5447                                    double sigma_color, double sigma_space,
5448                                    int borderType)
5449 {
5450 #ifdef __ANDROID__
5451     if (ocl::Device::getDefault().isNVidia())
5452         return false;
5453 #endif
5454
5455     int type = _src.type(), depth = CV_MAT_DEPTH(type), cn = CV_MAT_CN(type);
5456     int i, j, maxk, radius;
5457
5458     if (depth != CV_8U || cn > 4)
5459         return false;
5460
5461     if (sigma_color <= 0)
5462         sigma_color = 1;
5463     if (sigma_space <= 0)
5464         sigma_space = 1;
5465
5466     double gauss_color_coeff = -0.5 / (sigma_color * sigma_color);
5467     double gauss_space_coeff = -0.5 / (sigma_space * sigma_space);
5468
5469     if ( d <= 0 )
5470         radius = cvRound(sigma_space * 1.5);
5471     else
5472         radius = d / 2;
5473     radius = MAX(radius, 1);
5474     d = radius * 2 + 1;
5475
5476     UMat src = _src.getUMat(), dst = _dst.getUMat(), temp;
5477     if (src.u == dst.u)
5478         return false;
5479
5480     copyMakeBorder(src, temp, radius, radius, radius, radius, borderType);
5481     std::vector<float> _space_weight(d * d);
5482     std::vector<int> _space_ofs(d * d);
5483     float * const space_weight = &_space_weight[0];
5484     int * const space_ofs = &_space_ofs[0];
5485
5486     // initialize space-related bilateral filter coefficients
5487     for( i = -radius, maxk = 0; i <= radius; i++ )
5488         for( j = -radius; j <= radius; j++ )
5489         {
5490             double r = std::sqrt((double)i * i + (double)j * j);
5491             if ( r > radius )
5492                 continue;
5493             space_weight[maxk] = (float)std::exp(r * r * gauss_space_coeff);
5494             space_ofs[maxk++] = (int)(i * temp.step + j * cn);
5495         }
5496
5497     char cvt[3][40];
5498     String cnstr = cn > 1 ? format("%d", cn) : "";
5499     String kernelName("bilateral");
5500     size_t sizeDiv = 1;
5501     if ((ocl::Device::getDefault().isIntel()) &&
5502         (ocl::Device::getDefault().type() == ocl::Device::TYPE_GPU))
5503     {
5504             //Intel GPU
5505             if (dst.cols % 4 == 0 && cn == 1) // For single channel x4 sized images.
5506             {
5507                 kernelName = "bilateral_float4";
5508                 sizeDiv = 4;
5509             }
5510      }
5511      ocl::Kernel k(kernelName.c_str(), ocl::imgproc::bilateral_oclsrc,
5512             format("-D radius=%d -D maxk=%d -D cn=%d -D int_t=%s -D uint_t=uint%s -D convert_int_t=%s"
5513             " -D uchar_t=%s -D float_t=%s -D convert_float_t=%s -D convert_uchar_t=%s -D gauss_color_coeff=(float)%f",
5514             radius, maxk, cn, ocl::typeToStr(CV_32SC(cn)), cnstr.c_str(),
5515             ocl::convertTypeStr(CV_8U, CV_32S, cn, cvt[0]),
5516             ocl::typeToStr(type), ocl::typeToStr(CV_32FC(cn)),
5517             ocl::convertTypeStr(CV_32S, CV_32F, cn, cvt[1]),
5518             ocl::convertTypeStr(CV_32F, CV_8U, cn, cvt[2]), gauss_color_coeff));
5519     if (k.empty())
5520         return false;
5521
5522     Mat mspace_weight(1, d * d, CV_32FC1, space_weight);
5523     Mat mspace_ofs(1, d * d, CV_32SC1, space_ofs);
5524     UMat ucolor_weight, uspace_weight, uspace_ofs;
5525
5526     mspace_weight.copyTo(uspace_weight);
5527     mspace_ofs.copyTo(uspace_ofs);
5528
5529     k.args(ocl::KernelArg::ReadOnlyNoSize(temp), ocl::KernelArg::WriteOnly(dst),
5530            ocl::KernelArg::PtrReadOnly(uspace_weight),
5531            ocl::KernelArg::PtrReadOnly(uspace_ofs));
5532
5533     size_t globalsize[2] = { (size_t)dst.cols / sizeDiv, (size_t)dst.rows };
5534     return k.run(2, globalsize, NULL, false);
5535 }
5536
5537 #endif
5538 static void
5539 bilateralFilter_8u( const Mat& src, Mat& dst, int d,
5540     double sigma_color, double sigma_space,
5541     int borderType )
5542 {
5543     int cn = src.channels();
5544     int i, j, maxk, radius;
5545     Size size = src.size();
5546
5547     CV_Assert( (src.type() == CV_8UC1 || src.type() == CV_8UC3) && src.data != dst.data );
5548
5549     if( sigma_color <= 0 )
5550         sigma_color = 1;
5551     if( sigma_space <= 0 )
5552         sigma_space = 1;
5553
5554     double gauss_color_coeff = -0.5/(sigma_color*sigma_color);
5555     double gauss_space_coeff = -0.5/(sigma_space*sigma_space);
5556
5557     if( d <= 0 )
5558         radius = cvRound(sigma_space*1.5);
5559     else
5560         radius = d/2;
5561     radius = MAX(radius, 1);
5562     d = radius*2 + 1;
5563
5564     Mat temp;
5565     copyMakeBorder( src, temp, radius, radius, radius, radius, borderType );
5566
5567     std::vector<float> _color_weight(cn*256);
5568     std::vector<float> _space_weight(d*d);
5569     std::vector<int> _space_ofs(d*d);
5570     float* color_weight = &_color_weight[0];
5571     float* space_weight = &_space_weight[0];
5572     int* space_ofs = &_space_ofs[0];
5573
5574     // initialize color-related bilateral filter coefficients
5575
5576     for( i = 0; i < 256*cn; i++ )
5577         color_weight[i] = (float)std::exp(i*i*gauss_color_coeff);
5578
5579     // initialize space-related bilateral filter coefficients
5580     for( i = -radius, maxk = 0; i <= radius; i++ )
5581     {
5582         j = -radius;
5583
5584         for( ; j <= radius; j++ )
5585         {
5586             double r = std::sqrt((double)i*i + (double)j*j);
5587             if( r > radius )
5588                 continue;
5589             space_weight[maxk] = (float)std::exp(r*r*gauss_space_coeff);
5590             space_ofs[maxk++] = (int)(i*temp.step + j*cn);
5591         }
5592     }
5593
5594     BilateralFilter_8u_Invoker body(dst, temp, radius, maxk, space_ofs, space_weight, color_weight);
5595     parallel_for_(Range(0, size.height), body, dst.total()/(double)(1<<16));
5596 }
5597
5598
5599 class BilateralFilter_32f_Invoker :
5600     public ParallelLoopBody
5601 {
5602 public:
5603
5604     BilateralFilter_32f_Invoker(int _cn, int _radius, int _maxk, int *_space_ofs,
5605         const Mat& _temp, Mat& _dest, float _scale_index, float *_space_weight, float *_expLUT) :
5606         cn(_cn), radius(_radius), maxk(_maxk), space_ofs(_space_ofs),
5607         temp(&_temp), dest(&_dest), scale_index(_scale_index), space_weight(_space_weight), expLUT(_expLUT)
5608     {
5609     }
5610
5611     virtual void operator() (const Range& range) const CV_OVERRIDE
5612     {
5613         int i, j, k;
5614         Size size = dest->size();
5615 #if CV_SIMD128
5616         int CV_DECL_ALIGNED(16) idxBuf[4];
5617         bool haveSIMD128 = hasSIMD128();
5618 #endif
5619
5620         for( i = range.start; i < range.end; i++ )
5621         {
5622             const float* sptr = temp->ptr<float>(i+radius) + radius*cn;
5623             float* dptr = dest->ptr<float>(i);
5624
5625             if( cn == 1 )
5626             {
5627                 for( j = 0; j < size.width; j++ )
5628                 {
5629                     float sum = 0, wsum = 0;
5630                     float val0 = sptr[j];
5631                     k = 0;
5632 #if CV_SIMD128
5633                     if( haveSIMD128 )
5634                     {
5635                         v_float32x4 vecwsum = v_setzero_f32();
5636                         v_float32x4 vecvsum = v_setzero_f32();
5637                         const v_float32x4 _val0 = v_setall_f32(sptr[j]);
5638                         const v_float32x4 _scale_index = v_setall_f32(scale_index);
5639
5640                         for (; k <= maxk - 4; k += 4)
5641                         {
5642                             v_float32x4 _sw = v_load(space_weight + k);
5643                             v_float32x4 _val = v_float32x4(sptr[j + space_ofs[k]],
5644                                 sptr[j + space_ofs[k + 1]],
5645                                 sptr[j + space_ofs[k + 2]],
5646                                 sptr[j + space_ofs[k + 3]]);
5647                             v_float32x4 _alpha = v_abs(_val - _val0) * _scale_index;
5648
5649                             v_int32x4 _idx = v_round(_alpha);
5650                             v_store(idxBuf, _idx);
5651                             _alpha -= v_cvt_f32(_idx);
5652
5653                             v_float32x4 _explut = v_float32x4(expLUT[idxBuf[0]],
5654                                 expLUT[idxBuf[1]],
5655                                 expLUT[idxBuf[2]],
5656                                 expLUT[idxBuf[3]]);
5657                             v_float32x4 _explut1 = v_float32x4(expLUT[idxBuf[0] + 1],
5658                                 expLUT[idxBuf[1] + 1],
5659                                 expLUT[idxBuf[2] + 1],
5660                                 expLUT[idxBuf[3] + 1]);
5661
5662                             v_float32x4 _w = _sw * (_explut + (_alpha * (_explut1 - _explut)));
5663                             _val *= _w;
5664
5665                             vecwsum += _w;
5666                             vecvsum += _val;
5667                         }
5668                         float *bufFloat = (float*)idxBuf;
5669                         v_float32x4 sum4 = v_reduce_sum4(vecwsum, vecvsum, vecwsum, vecvsum);
5670                         v_store(bufFloat, sum4);
5671                         sum += bufFloat[1];
5672                         wsum += bufFloat[0];
5673                     }
5674 #endif
5675
5676                     for( ; k < maxk; k++ )
5677                     {
5678                         float val = sptr[j + space_ofs[k]];
5679                         float alpha = (float)(std::abs(val - val0)*scale_index);
5680                         int idx = cvFloor(alpha);
5681                         alpha -= idx;
5682                         float w = space_weight[k]*(expLUT[idx] + alpha*(expLUT[idx+1] - expLUT[idx]));
5683                         sum += val*w;
5684                         wsum += w;
5685                     }
5686                     dptr[j] = (float)(sum/wsum);
5687                 }
5688             }
5689             else
5690             {
5691                 CV_Assert( cn == 3 );
5692                 for( j = 0; j < size.width*3; j += 3 )
5693                 {
5694                     float sum_b = 0, sum_g = 0, sum_r = 0, wsum = 0;
5695                     float b0 = sptr[j], g0 = sptr[j+1], r0 = sptr[j+2];
5696                     k = 0;
5697 #if CV_SIMD128
5698                     if( haveSIMD128 )
5699                     {
5700                         v_float32x4 sumw = v_setzero_f32();
5701                         v_float32x4 sumb = v_setzero_f32();
5702                         v_float32x4 sumg = v_setzero_f32();
5703                         v_float32x4 sumr = v_setzero_f32();
5704                         const v_float32x4 _b0 = v_setall_f32(b0);
5705                         const v_float32x4 _g0 = v_setall_f32(g0);
5706                         const v_float32x4 _r0 = v_setall_f32(r0);
5707                         const v_float32x4 _scale_index = v_setall_f32(scale_index);
5708
5709                         for( ; k <= maxk-4; k += 4 )
5710                         {
5711                             v_float32x4 _sw = v_load(space_weight + k);
5712
5713                             const float* const sptr_k0 = sptr + j + space_ofs[k];
5714                             const float* const sptr_k1 = sptr + j + space_ofs[k+1];
5715                             const float* const sptr_k2 = sptr + j + space_ofs[k+2];
5716                             const float* const sptr_k3 = sptr + j + space_ofs[k+3];
5717
5718                             v_float32x4 _v0 = v_load(sptr_k0);
5719                             v_float32x4 _v1 = v_load(sptr_k1);
5720                             v_float32x4 _v2 = v_load(sptr_k2);
5721                             v_float32x4 _v3 = v_load(sptr_k3);
5722                             v_float32x4 _b, _g, _r, _dummy;
5723
5724                             v_transpose4x4(_v0, _v1, _v2, _v3, _b, _g, _r, _dummy);
5725
5726                             v_float32x4 _bt = v_abs(_b - _b0);
5727                             v_float32x4 _gt = v_abs(_g - _g0);
5728                             v_float32x4 _rt = v_abs(_r - _r0);
5729                             v_float32x4 _alpha = _scale_index * (_bt + _gt + _rt);
5730
5731                             v_int32x4 _idx = v_round(_alpha);
5732                             v_store((int*)idxBuf, _idx);
5733                             _alpha -= v_cvt_f32(_idx);
5734
5735                             v_float32x4 _explut = v_float32x4(expLUT[idxBuf[0]],
5736                                 expLUT[idxBuf[1]],
5737                                 expLUT[idxBuf[2]],
5738                                 expLUT[idxBuf[3]]);
5739                             v_float32x4 _explut1 = v_float32x4(expLUT[idxBuf[0] + 1],
5740                                 expLUT[idxBuf[1] + 1],
5741                                 expLUT[idxBuf[2] + 1],
5742                                 expLUT[idxBuf[3] + 1]);
5743
5744                             v_float32x4 _w = _sw * (_explut + (_alpha * (_explut1 - _explut)));
5745
5746                             _b *=  _w;
5747                             _g *=  _w;
5748                             _r *=  _w;
5749                             sumw += _w;
5750                             sumb += _b;
5751                             sumg += _g;
5752                             sumr += _r;
5753                         }
5754                         v_float32x4 sum4 = v_reduce_sum4(sumw, sumb, sumg, sumr);
5755                         float *bufFloat = (float*)idxBuf;
5756                         v_store(bufFloat, sum4);
5757                         wsum += bufFloat[0];
5758                         sum_b += bufFloat[1];
5759                         sum_g += bufFloat[2];
5760                         sum_r += bufFloat[3];
5761                     }
5762 #endif
5763
5764                     for(; k < maxk; k++ )
5765                     {
5766                         const float* sptr_k = sptr + j + space_ofs[k];
5767                         float b = sptr_k[0], g = sptr_k[1], r = sptr_k[2];
5768                         float alpha = (float)((std::abs(b - b0) +
5769                             std::abs(g - g0) + std::abs(r - r0))*scale_index);
5770                         int idx = cvFloor(alpha);
5771                         alpha -= idx;
5772                         float w = space_weight[k]*(expLUT[idx] + alpha*(expLUT[idx+1] - expLUT[idx]));
5773                         sum_b += b*w; sum_g += g*w; sum_r += r*w;
5774                         wsum += w;
5775                     }
5776                     wsum = 1.f/wsum;
5777                     b0 = sum_b*wsum;
5778                     g0 = sum_g*wsum;
5779                     r0 = sum_r*wsum;
5780                     dptr[j] = b0; dptr[j+1] = g0; dptr[j+2] = r0;
5781                 }
5782             }
5783         }
5784     }
5785
5786 private:
5787     int cn, radius, maxk, *space_ofs;
5788     const Mat* temp;
5789     Mat *dest;
5790     float scale_index, *space_weight, *expLUT;
5791 };
5792
5793
5794 static void
5795 bilateralFilter_32f( const Mat& src, Mat& dst, int d,
5796                      double sigma_color, double sigma_space,
5797                      int borderType )
5798 {
5799     int cn = src.channels();
5800     int i, j, maxk, radius;
5801     double minValSrc=-1, maxValSrc=1;
5802     const int kExpNumBinsPerChannel = 1 << 12;
5803     int kExpNumBins = 0;
5804     float lastExpVal = 1.f;
5805     float len, scale_index;
5806     Size size = src.size();
5807
5808     CV_Assert( (src.type() == CV_32FC1 || src.type() == CV_32FC3) && src.data != dst.data );
5809
5810     if( sigma_color <= 0 )
5811         sigma_color = 1;
5812     if( sigma_space <= 0 )
5813         sigma_space = 1;
5814
5815     double gauss_color_coeff = -0.5/(sigma_color*sigma_color);
5816     double gauss_space_coeff = -0.5/(sigma_space*sigma_space);
5817
5818     if( d <= 0 )
5819         radius = cvRound(sigma_space*1.5);
5820     else
5821         radius = d/2;
5822     radius = MAX(radius, 1);
5823     d = radius*2 + 1;
5824     // compute the min/max range for the input image (even if multichannel)
5825
5826     minMaxLoc( src.reshape(1), &minValSrc, &maxValSrc );
5827     if(std::abs(minValSrc - maxValSrc) < FLT_EPSILON)
5828     {
5829         src.copyTo(dst);
5830         return;
5831     }
5832
5833     // temporary copy of the image with borders for easy processing
5834     Mat temp;
5835     copyMakeBorder( src, temp, radius, radius, radius, radius, borderType );
5836     const double insteadNaNValue = -5. * sigma_color;
5837     patchNaNs( temp, insteadNaNValue ); // this replacement of NaNs makes the assumption that depth values are nonnegative
5838                                         // TODO: make insteadNaNValue avalible in the outside function interface to control the cases breaking the assumption
5839     // allocate lookup tables
5840     std::vector<float> _space_weight(d*d);
5841     std::vector<int> _space_ofs(d*d);
5842     float* space_weight = &_space_weight[0];
5843     int* space_ofs = &_space_ofs[0];
5844
5845     // assign a length which is slightly more than needed
5846     len = (float)(maxValSrc - minValSrc) * cn;
5847     kExpNumBins = kExpNumBinsPerChannel * cn;
5848     std::vector<float> _expLUT(kExpNumBins+2);
5849     float* expLUT = &_expLUT[0];
5850
5851     scale_index = kExpNumBins/len;
5852
5853     // initialize the exp LUT
5854     for( i = 0; i < kExpNumBins+2; i++ )
5855     {
5856         if( lastExpVal > 0.f )
5857         {
5858             double val =  i / scale_index;
5859             expLUT[i] = (float)std::exp(val * val * gauss_color_coeff);
5860             lastExpVal = expLUT[i];
5861         }
5862         else
5863             expLUT[i] = 0.f;
5864     }
5865
5866     // initialize space-related bilateral filter coefficients
5867     for( i = -radius, maxk = 0; i <= radius; i++ )
5868         for( j = -radius; j <= radius; j++ )
5869         {
5870             double r = std::sqrt((double)i*i + (double)j*j);
5871             if( r > radius )
5872                 continue;
5873             space_weight[maxk] = (float)std::exp(r*r*gauss_space_coeff);
5874             space_ofs[maxk++] = (int)(i*(temp.step/sizeof(float)) + j*cn);
5875         }
5876
5877     // parallel_for usage
5878
5879     BilateralFilter_32f_Invoker body(cn, radius, maxk, space_ofs, temp, dst, scale_index, space_weight, expLUT);
5880     parallel_for_(Range(0, size.height), body, dst.total()/(double)(1<<16));
5881 }
5882
5883 #ifdef HAVE_IPP
5884 #define IPP_BILATERAL_PARALLEL 1
5885
5886 #ifdef HAVE_IPP_IW
5887 class ipp_bilateralFilterParallel: public ParallelLoopBody
5888 {
5889 public:
5890     ipp_bilateralFilterParallel(::ipp::IwiImage &_src, ::ipp::IwiImage &_dst, int _radius, Ipp32f _valSquareSigma, Ipp32f _posSquareSigma, ::ipp::IwiBorderType _borderType, bool *_ok):
5891         src(_src), dst(_dst)
5892     {
5893         pOk = _ok;
5894
5895         radius          = _radius;
5896         valSquareSigma  = _valSquareSigma;
5897         posSquareSigma  = _posSquareSigma;
5898         borderType      = _borderType;
5899
5900         *pOk = true;
5901     }
5902     ~ipp_bilateralFilterParallel() {}
5903
5904     virtual void operator() (const Range& range) const CV_OVERRIDE
5905     {
5906         if(*pOk == false)
5907             return;
5908
5909         try
5910         {
5911             ::ipp::IwiTile tile = ::ipp::IwiRoi(0, range.start, dst.m_size.width, range.end - range.start);
5912             CV_INSTRUMENT_FUN_IPP(::ipp::iwiFilterBilateral, src, dst, radius, valSquareSigma, posSquareSigma, ::ipp::IwDefault(), borderType, tile);
5913         }
5914         catch(::ipp::IwException)
5915         {
5916             *pOk = false;
5917             return;
5918         }
5919     }
5920 private:
5921     ::ipp::IwiImage &src;
5922     ::ipp::IwiImage &dst;
5923
5924     int                  radius;
5925     Ipp32f               valSquareSigma;
5926     Ipp32f               posSquareSigma;
5927     ::ipp::IwiBorderType borderType;
5928
5929     bool  *pOk;
5930     const ipp_bilateralFilterParallel& operator= (const ipp_bilateralFilterParallel&);
5931 };
5932 #endif
5933
5934 static bool ipp_bilateralFilter(Mat &src, Mat &dst, int d, double sigmaColor, double sigmaSpace, int borderType)
5935 {
5936 #ifdef HAVE_IPP_IW
5937     CV_INSTRUMENT_REGION_IPP()
5938
5939     int         radius         = IPP_MAX(((d <= 0)?cvRound(sigmaSpace*1.5):d/2), 1);
5940     Ipp32f      valSquareSigma = (Ipp32f)((sigmaColor <= 0)?1:sigmaColor*sigmaColor);
5941     Ipp32f      posSquareSigma = (Ipp32f)((sigmaSpace <= 0)?1:sigmaSpace*sigmaSpace);
5942
5943     // Acquire data and begin processing
5944     try
5945     {
5946         ::ipp::IwiImage      iwSrc = ippiGetImage(src);
5947         ::ipp::IwiImage      iwDst = ippiGetImage(dst);
5948         ::ipp::IwiBorderSize borderSize(radius);
5949         ::ipp::IwiBorderType ippBorder(ippiGetBorder(iwSrc, borderType, borderSize));
5950         if(!ippBorder)
5951             return false;
5952
5953         const int threads = ippiSuggestThreadsNum(iwDst, 2);
5954         if(IPP_BILATERAL_PARALLEL && threads > 1) {
5955             bool  ok      = true;
5956             Range range(0, (int)iwDst.m_size.height);
5957             ipp_bilateralFilterParallel invoker(iwSrc, iwDst, radius, valSquareSigma, posSquareSigma, ippBorder, &ok);
5958             if(!ok)
5959                 return false;
5960
5961             parallel_for_(range, invoker, threads*4);
5962
5963             if(!ok)
5964                 return false;
5965         } else {
5966             CV_INSTRUMENT_FUN_IPP(::ipp::iwiFilterBilateral, iwSrc, iwDst, radius, valSquareSigma, posSquareSigma, ::ipp::IwDefault(), ippBorder);
5967         }
5968     }
5969     catch (::ipp::IwException)
5970     {
5971         return false;
5972     }
5973     return true;
5974 #else
5975     CV_UNUSED(src); CV_UNUSED(dst); CV_UNUSED(d); CV_UNUSED(sigmaColor); CV_UNUSED(sigmaSpace); CV_UNUSED(borderType);
5976     return false;
5977 #endif
5978 }
5979 #endif
5980
5981 }
5982
5983 void cv::bilateralFilter( InputArray _src, OutputArray _dst, int d,
5984                       double sigmaColor, double sigmaSpace,
5985                       int borderType )
5986 {
5987     CV_INSTRUMENT_REGION()
5988
5989     _dst.create( _src.size(), _src.type() );
5990
5991     CV_OCL_RUN(_src.dims() <= 2 && _dst.isUMat(),
5992                ocl_bilateralFilter_8u(_src, _dst, d, sigmaColor, sigmaSpace, borderType))
5993
5994     Mat src = _src.getMat(), dst = _dst.getMat();
5995
5996     CV_IPP_RUN_FAST(ipp_bilateralFilter(src, dst, d, sigmaColor, sigmaSpace, borderType));
5997
5998     if( src.depth() == CV_8U )
5999         bilateralFilter_8u( src, dst, d, sigmaColor, sigmaSpace, borderType );
6000     else if( src.depth() == CV_32F )
6001         bilateralFilter_32f( src, dst, d, sigmaColor, sigmaSpace, borderType );
6002     else
6003         CV_Error( CV_StsUnsupportedFormat,
6004         "Bilateral filtering is only implemented for 8u and 32f images" );
6005 }
6006
6007 //////////////////////////////////////////////////////////////////////////////////////////
6008
6009 CV_IMPL void
6010 cvSmooth( const void* srcarr, void* dstarr, int smooth_type,
6011           int param1, int param2, double param3, double param4 )
6012 {
6013     cv::Mat src = cv::cvarrToMat(srcarr), dst0 = cv::cvarrToMat(dstarr), dst = dst0;
6014
6015     CV_Assert( dst.size() == src.size() &&
6016         (smooth_type == CV_BLUR_NO_SCALE || dst.type() == src.type()) );
6017
6018     if( param2 <= 0 )
6019         param2 = param1;
6020
6021     if( smooth_type == CV_BLUR || smooth_type == CV_BLUR_NO_SCALE )
6022         cv::boxFilter( src, dst, dst.depth(), cv::Size(param1, param2), cv::Point(-1,-1),
6023             smooth_type == CV_BLUR, cv::BORDER_REPLICATE );
6024     else if( smooth_type == CV_GAUSSIAN )
6025         cv::GaussianBlur( src, dst, cv::Size(param1, param2), param3, param4, cv::BORDER_REPLICATE );
6026     else if( smooth_type == CV_MEDIAN )
6027         cv::medianBlur( src, dst, param1 );
6028     else
6029         cv::bilateralFilter( src, dst, param1, param3, param4, cv::BORDER_REPLICATE );
6030
6031     if( dst.data != dst0.data )
6032         CV_Error( CV_StsUnmatchedFormats, "The destination image does not have the proper type" );
6033 }
6034
6035 /* End of file. */