opencv: Use cv::AutoBuffer<>::data()
[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
1337
1338 cv::Ptr<cv::BaseColumnFilter> cv::getColumnSumFilter(int sumType, int dstType, int ksize,
1339                                                      int anchor, double scale)
1340 {
1341     int sdepth = CV_MAT_DEPTH(sumType), ddepth = CV_MAT_DEPTH(dstType);
1342     CV_Assert( CV_MAT_CN(sumType) == CV_MAT_CN(dstType) );
1343
1344     if( anchor < 0 )
1345         anchor = ksize/2;
1346
1347     if( ddepth == CV_8U && sdepth == CV_32S )
1348         return makePtr<ColumnSum<int, uchar> >(ksize, anchor, scale);
1349     if( ddepth == CV_8U && sdepth == CV_16U )
1350         return makePtr<ColumnSum<ushort, uchar> >(ksize, anchor, scale);
1351     if( ddepth == CV_8U && sdepth == CV_64F )
1352         return makePtr<ColumnSum<double, uchar> >(ksize, anchor, scale);
1353     if( ddepth == CV_16U && sdepth == CV_32S )
1354         return makePtr<ColumnSum<int, ushort> >(ksize, anchor, scale);
1355     if( ddepth == CV_16U && sdepth == CV_64F )
1356         return makePtr<ColumnSum<double, ushort> >(ksize, anchor, scale);
1357     if( ddepth == CV_16S && sdepth == CV_32S )
1358         return makePtr<ColumnSum<int, short> >(ksize, anchor, scale);
1359     if( ddepth == CV_16S && sdepth == CV_64F )
1360         return makePtr<ColumnSum<double, short> >(ksize, anchor, scale);
1361     if( ddepth == CV_32S && sdepth == CV_32S )
1362         return makePtr<ColumnSum<int, int> >(ksize, anchor, scale);
1363     if( ddepth == CV_32F && sdepth == CV_32S )
1364         return makePtr<ColumnSum<int, float> >(ksize, anchor, scale);
1365     if( ddepth == CV_32F && sdepth == CV_64F )
1366         return makePtr<ColumnSum<double, float> >(ksize, anchor, scale);
1367     if( ddepth == CV_64F && sdepth == CV_32S )
1368         return makePtr<ColumnSum<int, double> >(ksize, anchor, scale);
1369     if( ddepth == CV_64F && sdepth == CV_64F )
1370         return makePtr<ColumnSum<double, double> >(ksize, anchor, scale);
1371
1372     CV_Error_( CV_StsNotImplemented,
1373         ("Unsupported combination of sum format (=%d), and destination format (=%d)",
1374         sumType, dstType));
1375 }
1376
1377
1378 cv::Ptr<cv::FilterEngine> cv::createBoxFilter( int srcType, int dstType, Size ksize,
1379                     Point anchor, bool normalize, int borderType )
1380 {
1381     int sdepth = CV_MAT_DEPTH(srcType);
1382     int cn = CV_MAT_CN(srcType), sumType = CV_64F;
1383     if( sdepth == CV_8U && CV_MAT_DEPTH(dstType) == CV_8U &&
1384         ksize.width*ksize.height <= 256 )
1385         sumType = CV_16U;
1386     else if( sdepth <= CV_32S && (!normalize ||
1387         ksize.width*ksize.height <= (sdepth == CV_8U ? (1<<23) :
1388             sdepth == CV_16U ? (1 << 15) : (1 << 16))) )
1389         sumType = CV_32S;
1390     sumType = CV_MAKETYPE( sumType, cn );
1391
1392     Ptr<BaseRowFilter> rowFilter = getRowSumFilter(srcType, sumType, ksize.width, anchor.x );
1393     Ptr<BaseColumnFilter> columnFilter = getColumnSumFilter(sumType,
1394         dstType, ksize.height, anchor.y, normalize ? 1./(ksize.width*ksize.height) : 1);
1395
1396     return makePtr<FilterEngine>(Ptr<BaseFilter>(), rowFilter, columnFilter,
1397            srcType, dstType, sumType, borderType );
1398 }
1399
1400 #ifdef HAVE_OPENVX
1401 namespace cv
1402 {
1403     namespace ovx {
1404         template <> inline bool skipSmallImages<VX_KERNEL_BOX_3x3>(int w, int h) { return w*h < 640 * 480; }
1405     }
1406     static bool openvx_boxfilter(InputArray _src, OutputArray _dst, int ddepth,
1407                                  Size ksize, Point anchor,
1408                                  bool normalize, int borderType)
1409     {
1410         if (ddepth < 0)
1411             ddepth = CV_8UC1;
1412         if (_src.type() != CV_8UC1 || ddepth != CV_8U || !normalize ||
1413             _src.cols() < 3 || _src.rows() < 3 ||
1414             ksize.width != 3 || ksize.height != 3 ||
1415             (anchor.x >= 0 && anchor.x != 1) ||
1416             (anchor.y >= 0 && anchor.y != 1) ||
1417             ovx::skipSmallImages<VX_KERNEL_BOX_3x3>(_src.cols(), _src.rows()))
1418             return false;
1419
1420         Mat src = _src.getMat();
1421
1422         if ((borderType & BORDER_ISOLATED) == 0 && src.isSubmatrix())
1423             return false; //Process isolated borders only
1424         vx_enum border;
1425         switch (borderType & ~BORDER_ISOLATED)
1426         {
1427         case BORDER_CONSTANT:
1428             border = VX_BORDER_CONSTANT;
1429             break;
1430         case BORDER_REPLICATE:
1431             border = VX_BORDER_REPLICATE;
1432             break;
1433         default:
1434             return false;
1435         }
1436
1437         _dst.create(src.size(), CV_8UC1);
1438         Mat dst = _dst.getMat();
1439
1440         try
1441         {
1442             ivx::Context ctx = ovx::getOpenVXContext();
1443
1444             Mat a;
1445             if (dst.data != src.data)
1446                 a = src;
1447             else
1448                 src.copyTo(a);
1449
1450             ivx::Image
1451                 ia = ivx::Image::createFromHandle(ctx, VX_DF_IMAGE_U8,
1452                                                   ivx::Image::createAddressing(a.cols, a.rows, 1, (vx_int32)(a.step)), a.data),
1453                 ib = ivx::Image::createFromHandle(ctx, VX_DF_IMAGE_U8,
1454                                                   ivx::Image::createAddressing(dst.cols, dst.rows, 1, (vx_int32)(dst.step)), dst.data);
1455
1456             //ATTENTION: VX_CONTEXT_IMMEDIATE_BORDER attribute change could lead to strange issues in multi-threaded environments
1457             //since OpenVX standard says nothing about thread-safety for now
1458             ivx::border_t prevBorder = ctx.immediateBorder();
1459             ctx.setImmediateBorder(border, (vx_uint8)(0));
1460             ivx::IVX_CHECK_STATUS(vxuBox3x3(ctx, ia, ib));
1461             ctx.setImmediateBorder(prevBorder);
1462         }
1463         catch (ivx::RuntimeError & e)
1464         {
1465             VX_DbgThrow(e.what());
1466         }
1467         catch (ivx::WrapperError & e)
1468         {
1469             VX_DbgThrow(e.what());
1470         }
1471
1472         return true;
1473     }
1474 }
1475 #endif
1476
1477 #if defined(HAVE_IPP)
1478 namespace cv
1479 {
1480 static bool ipp_boxfilter(Mat &src, Mat &dst, Size ksize, Point anchor, bool normalize, int borderType)
1481 {
1482 #ifdef HAVE_IPP_IW
1483     CV_INSTRUMENT_REGION_IPP()
1484
1485 #if IPP_VERSION_X100 < 201801
1486     // Problem with SSE42 optimization for 16s and some 8u modes
1487     if(ipp::getIppTopFeatures() == ippCPUID_SSE42 && (((src.depth() == CV_16S || src.depth() == CV_16U) && (src.channels() == 3 || src.channels() == 4)) || (src.depth() == CV_8U && src.channels() == 3 && (ksize.width > 5 || ksize.height > 5))))
1488         return false;
1489
1490     // Other optimizations has some degradations too
1491     if((((src.depth() == CV_16S || src.depth() == CV_16U) && (src.channels() == 4)) || (src.depth() == CV_8U && src.channels() == 1 && (ksize.width > 5 || ksize.height > 5))))
1492         return false;
1493 #endif
1494
1495     if(!normalize)
1496         return false;
1497
1498     if(!ippiCheckAnchor(anchor, ksize))
1499         return false;
1500
1501     try
1502     {
1503         ::ipp::IwiImage       iwSrc      = ippiGetImage(src);
1504         ::ipp::IwiImage       iwDst      = ippiGetImage(dst);
1505         ::ipp::IwiSize        iwKSize    = ippiGetSize(ksize);
1506         ::ipp::IwiBorderSize  borderSize(iwKSize);
1507         ::ipp::IwiBorderType  ippBorder(ippiGetBorder(iwSrc, borderType, borderSize));
1508         if(!ippBorder)
1509             return false;
1510
1511         CV_INSTRUMENT_FUN_IPP(::ipp::iwiFilterBox, iwSrc, iwDst, iwKSize, ::ipp::IwDefault(), ippBorder);
1512     }
1513     catch (::ipp::IwException)
1514     {
1515         return false;
1516     }
1517
1518     return true;
1519 #else
1520     CV_UNUSED(src); CV_UNUSED(dst); CV_UNUSED(ksize); CV_UNUSED(anchor); CV_UNUSED(normalize); CV_UNUSED(borderType);
1521     return false;
1522 #endif
1523 }
1524 }
1525 #endif
1526
1527
1528 void cv::boxFilter( InputArray _src, OutputArray _dst, int ddepth,
1529                 Size ksize, Point anchor,
1530                 bool normalize, int borderType )
1531 {
1532     CV_INSTRUMENT_REGION()
1533
1534     CV_OCL_RUN(_dst.isUMat() &&
1535                (borderType == BORDER_REPLICATE || borderType == BORDER_CONSTANT ||
1536                 borderType == BORDER_REFLECT || borderType == BORDER_REFLECT_101),
1537                ocl_boxFilter3x3_8UC1(_src, _dst, ddepth, ksize, anchor, borderType, normalize))
1538
1539     CV_OCL_RUN(_dst.isUMat(), ocl_boxFilter(_src, _dst, ddepth, ksize, anchor, borderType, normalize))
1540
1541     Mat src = _src.getMat();
1542     int stype = src.type(), sdepth = CV_MAT_DEPTH(stype), cn = CV_MAT_CN(stype);
1543     if( ddepth < 0 )
1544         ddepth = sdepth;
1545     _dst.create( src.size(), CV_MAKETYPE(ddepth, cn) );
1546     Mat dst = _dst.getMat();
1547     if( borderType != BORDER_CONSTANT && normalize && (borderType & BORDER_ISOLATED) != 0 )
1548     {
1549         if( src.rows == 1 )
1550             ksize.height = 1;
1551         if( src.cols == 1 )
1552             ksize.width = 1;
1553     }
1554
1555     Point ofs;
1556     Size wsz(src.cols, src.rows);
1557     if(!(borderType&BORDER_ISOLATED))
1558         src.locateROI( wsz, ofs );
1559
1560     CALL_HAL(boxFilter, cv_hal_boxFilter, src.ptr(), src.step, dst.ptr(), dst.step, src.cols, src.rows, sdepth, ddepth, cn,
1561              ofs.x, ofs.y, wsz.width - src.cols - ofs.x, wsz.height - src.rows - ofs.y, ksize.width, ksize.height,
1562              anchor.x, anchor.y, normalize, borderType&~BORDER_ISOLATED);
1563
1564     CV_OVX_RUN(true,
1565                openvx_boxfilter(src, dst, ddepth, ksize, anchor, normalize, borderType))
1566
1567     CV_IPP_RUN_FAST(ipp_boxfilter(src, dst, ksize, anchor, normalize, borderType));
1568
1569     borderType = (borderType&~BORDER_ISOLATED);
1570
1571     Ptr<FilterEngine> f = createBoxFilter( src.type(), dst.type(),
1572                         ksize, anchor, normalize, borderType );
1573
1574     f->apply( src, dst, wsz, ofs );
1575 }
1576
1577
1578 void cv::blur( InputArray src, OutputArray dst,
1579            Size ksize, Point anchor, int borderType )
1580 {
1581     CV_INSTRUMENT_REGION()
1582
1583     boxFilter( src, dst, -1, ksize, anchor, true, borderType );
1584 }
1585
1586
1587 /****************************************************************************************\
1588                                     Squared Box Filter
1589 \****************************************************************************************/
1590
1591 namespace cv
1592 {
1593
1594 template<typename T, typename ST>
1595 struct SqrRowSum :
1596         public BaseRowFilter
1597 {
1598     SqrRowSum( int _ksize, int _anchor ) :
1599         BaseRowFilter()
1600     {
1601         ksize = _ksize;
1602         anchor = _anchor;
1603     }
1604
1605     virtual void operator()(const uchar* src, uchar* dst, int width, int cn) CV_OVERRIDE
1606     {
1607         const T* S = (const T*)src;
1608         ST* D = (ST*)dst;
1609         int i = 0, k, ksz_cn = ksize*cn;
1610
1611         width = (width - 1)*cn;
1612         for( k = 0; k < cn; k++, S++, D++ )
1613         {
1614             ST s = 0;
1615             for( i = 0; i < ksz_cn; i += cn )
1616             {
1617                 ST val = (ST)S[i];
1618                 s += val*val;
1619             }
1620             D[0] = s;
1621             for( i = 0; i < width; i += cn )
1622             {
1623                 ST val0 = (ST)S[i], val1 = (ST)S[i + ksz_cn];
1624                 s += val1*val1 - val0*val0;
1625                 D[i+cn] = s;
1626             }
1627         }
1628     }
1629 };
1630
1631 static Ptr<BaseRowFilter> getSqrRowSumFilter(int srcType, int sumType, int ksize, int anchor)
1632 {
1633     int sdepth = CV_MAT_DEPTH(srcType), ddepth = CV_MAT_DEPTH(sumType);
1634     CV_Assert( CV_MAT_CN(sumType) == CV_MAT_CN(srcType) );
1635
1636     if( anchor < 0 )
1637         anchor = ksize/2;
1638
1639     if( sdepth == CV_8U && ddepth == CV_32S )
1640         return makePtr<SqrRowSum<uchar, int> >(ksize, anchor);
1641     if( sdepth == CV_8U && ddepth == CV_64F )
1642         return makePtr<SqrRowSum<uchar, double> >(ksize, anchor);
1643     if( sdepth == CV_16U && ddepth == CV_64F )
1644         return makePtr<SqrRowSum<ushort, double> >(ksize, anchor);
1645     if( sdepth == CV_16S && ddepth == CV_64F )
1646         return makePtr<SqrRowSum<short, double> >(ksize, anchor);
1647     if( sdepth == CV_32F && ddepth == CV_64F )
1648         return makePtr<SqrRowSum<float, double> >(ksize, anchor);
1649     if( sdepth == CV_64F && ddepth == CV_64F )
1650         return makePtr<SqrRowSum<double, double> >(ksize, anchor);
1651
1652     CV_Error_( CV_StsNotImplemented,
1653               ("Unsupported combination of source format (=%d), and buffer format (=%d)",
1654                srcType, sumType));
1655 }
1656
1657 }
1658
1659 void cv::sqrBoxFilter( InputArray _src, OutputArray _dst, int ddepth,
1660                        Size ksize, Point anchor,
1661                        bool normalize, int borderType )
1662 {
1663     CV_INSTRUMENT_REGION()
1664
1665     int srcType = _src.type(), sdepth = CV_MAT_DEPTH(srcType), cn = CV_MAT_CN(srcType);
1666     Size size = _src.size();
1667
1668     if( ddepth < 0 )
1669         ddepth = sdepth < CV_32F ? CV_32F : CV_64F;
1670
1671     if( borderType != BORDER_CONSTANT && normalize )
1672     {
1673         if( size.height == 1 )
1674             ksize.height = 1;
1675         if( size.width == 1 )
1676             ksize.width = 1;
1677     }
1678
1679     CV_OCL_RUN(_dst.isUMat() && _src.dims() <= 2,
1680                ocl_boxFilter(_src, _dst, ddepth, ksize, anchor, borderType, normalize, true))
1681
1682     int sumDepth = CV_64F;
1683     if( sdepth == CV_8U )
1684         sumDepth = CV_32S;
1685     int sumType = CV_MAKETYPE( sumDepth, cn ), dstType = CV_MAKETYPE(ddepth, cn);
1686
1687     Mat src = _src.getMat();
1688     _dst.create( size, dstType );
1689     Mat dst = _dst.getMat();
1690
1691     Ptr<BaseRowFilter> rowFilter = getSqrRowSumFilter(srcType, sumType, ksize.width, anchor.x );
1692     Ptr<BaseColumnFilter> columnFilter = getColumnSumFilter(sumType,
1693                                                             dstType, ksize.height, anchor.y,
1694                                                             normalize ? 1./(ksize.width*ksize.height) : 1);
1695
1696     Ptr<FilterEngine> f = makePtr<FilterEngine>(Ptr<BaseFilter>(), rowFilter, columnFilter,
1697                                                 srcType, dstType, sumType, borderType );
1698     Point ofs;
1699     Size wsz(src.cols, src.rows);
1700     src.locateROI( wsz, ofs );
1701
1702     f->apply( src, dst, wsz, ofs );
1703 }
1704
1705
1706 /****************************************************************************************\
1707                                      Gaussian Blur
1708 \****************************************************************************************/
1709
1710 cv::Mat cv::getGaussianKernel( int n, double sigma, int ktype )
1711 {
1712     const int SMALL_GAUSSIAN_SIZE = 7;
1713     static const float small_gaussian_tab[][SMALL_GAUSSIAN_SIZE] =
1714     {
1715         {1.f},
1716         {0.25f, 0.5f, 0.25f},
1717         {0.0625f, 0.25f, 0.375f, 0.25f, 0.0625f},
1718         {0.03125f, 0.109375f, 0.21875f, 0.28125f, 0.21875f, 0.109375f, 0.03125f}
1719     };
1720
1721     const float* fixed_kernel = n % 2 == 1 && n <= SMALL_GAUSSIAN_SIZE && sigma <= 0 ?
1722         small_gaussian_tab[n>>1] : 0;
1723
1724     CV_Assert( ktype == CV_32F || ktype == CV_64F );
1725     Mat kernel(n, 1, ktype);
1726     float* cf = kernel.ptr<float>();
1727     double* cd = kernel.ptr<double>();
1728
1729     double sigmaX = sigma > 0 ? sigma : ((n-1)*0.5 - 1)*0.3 + 0.8;
1730     double scale2X = -0.5/(sigmaX*sigmaX);
1731     double sum = 0;
1732
1733     int i;
1734     for( i = 0; i < n; i++ )
1735     {
1736         double x = i - (n-1)*0.5;
1737         double t = fixed_kernel ? (double)fixed_kernel[i] : std::exp(scale2X*x*x);
1738         if( ktype == CV_32F )
1739         {
1740             cf[i] = (float)t;
1741             sum += cf[i];
1742         }
1743         else
1744         {
1745             cd[i] = t;
1746             sum += cd[i];
1747         }
1748     }
1749
1750     sum = 1./sum;
1751     for( i = 0; i < n; i++ )
1752     {
1753         if( ktype == CV_32F )
1754             cf[i] = (float)(cf[i]*sum);
1755         else
1756             cd[i] *= sum;
1757     }
1758
1759     return kernel;
1760 }
1761
1762 namespace cv {
1763
1764 template <typename T>
1765 static std::vector<T> getFixedpointGaussianKernel( int n, double sigma )
1766 {
1767     if (sigma <= 0)
1768     {
1769         if(n == 1)
1770             return std::vector<T>(1, softdouble(1.0));
1771         else if(n == 3)
1772         {
1773             T v3[] = { softdouble(0.25), softdouble(0.5), softdouble(0.25) };
1774             return std::vector<T>(v3, v3 + 3);
1775         }
1776         else if(n == 5)
1777         {
1778             T v5[] = { softdouble(0.0625), softdouble(0.25), softdouble(0.375), softdouble(0.25), softdouble(0.0625) };
1779             return std::vector<T>(v5, v5 + 5);
1780         }
1781         else if(n == 7)
1782         {
1783             T v7[] = { softdouble(0.03125), softdouble(0.109375), softdouble(0.21875), softdouble(0.28125), softdouble(0.21875), softdouble(0.109375), softdouble(0.03125) };
1784             return std::vector<T>(v7, v7 + 7);
1785         }
1786     }
1787
1788
1789     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)
1790     softdouble scale2X = softdouble(-0.5*0.25)/(sigmaX*sigmaX);
1791     std::vector<softdouble> values(n);
1792     softdouble sum(0.);
1793     for(int i = 0, x = 1 - n; i < n; i++, x+=2 )
1794     {
1795         // x = i - (n - 1)*0.5
1796         // t = std::exp(scale2X*x*x)
1797         values[i] = exp(softdouble(x*x)*scale2X);
1798         sum += values[i];
1799     }
1800     sum = softdouble::one()/sum;
1801
1802     std::vector<T> kernel(n);
1803     for(int i = 0; i < n; i++ )
1804     {
1805         kernel[i] = values[i] * sum;
1806     }
1807
1808     return kernel;
1809 };
1810
1811 template <typename ET, typename FT>
1812 void hlineSmooth1N(const ET* src, int cn, const FT* m, int, FT* dst, int len, int)
1813 {
1814     for (int i = 0; i < len*cn; i++, src++, dst++)
1815         *dst = (*m) * (*src);
1816 }
1817 template <>
1818 void hlineSmooth1N<uint8_t, ufixedpoint16>(const uint8_t* src, int cn, const ufixedpoint16* m, int, ufixedpoint16* dst, int len, int)
1819 {
1820     int lencn = len*cn;
1821     v_uint16x8 v_mul = v_setall_u16(*((uint16_t*)m));
1822     int i = 0;
1823     for (; i <= lencn - 16; i += 16)
1824     {
1825         v_uint8x16 v_src = v_load(src + i);
1826         v_uint16x8 v_tmp0, v_tmp1;
1827         v_expand(v_src, v_tmp0, v_tmp1);
1828         v_store((uint16_t*)dst + i, v_mul*v_tmp0);
1829         v_store((uint16_t*)dst + i + 8, v_mul*v_tmp1);
1830     }
1831     if (i <= lencn - 8)
1832     {
1833         v_uint16x8 v_src = v_load_expand(src + i);
1834         v_store((uint16_t*)dst + i, v_mul*v_src);
1835         i += 8;
1836     }
1837     for (; i < lencn; i++)
1838         dst[i] = m[0] * src[i];
1839 }
1840 template <typename ET, typename FT>
1841 void hlineSmooth1N1(const ET* src, int cn, const FT*, int, FT* dst, int len, int)
1842 {
1843     for (int i = 0; i < len*cn; i++, src++, dst++)
1844         *dst = *src;
1845 }
1846 template <>
1847 void hlineSmooth1N1<uint8_t, ufixedpoint16>(const uint8_t* src, int cn, const ufixedpoint16*, int, ufixedpoint16* dst, int len, int)
1848 {
1849     int lencn = len*cn;
1850     int i = 0;
1851     for (; i <= lencn - 16; i += 16)
1852     {
1853         v_uint8x16 v_src = v_load(src + i);
1854         v_uint16x8 v_tmp0, v_tmp1;
1855         v_expand(v_src, v_tmp0, v_tmp1);
1856         v_store((uint16_t*)dst + i, v_shl<8>(v_tmp0));
1857         v_store((uint16_t*)dst + i + 8, v_shl<8>(v_tmp1));
1858     }
1859     if (i <= lencn - 8)
1860     {
1861         v_uint16x8 v_src = v_load_expand(src + i);
1862         v_store((uint16_t*)dst + i, v_shl<8>(v_src));
1863         i += 8;
1864     }
1865     for (; i < lencn; i++)
1866         dst[i] = src[i];
1867 }
1868 template <typename ET, typename FT>
1869 void hlineSmooth3N(const ET* src, int cn, const FT* m, int, FT* dst, int len, int borderType)
1870 {
1871     if (len == 1)
1872     {
1873         FT msum = borderType != BORDER_CONSTANT ? m[0] + m[1] + m[2] : m[1];
1874         for (int k = 0; k < cn; k++)
1875             dst[k] = msum * src[k];
1876     }
1877     else
1878     {
1879         // Point that fall left from border
1880         for (int k = 0; k < cn; k++)
1881             dst[k] = m[1] * src[k] + m[2] * src[cn + k];
1882         if (borderType != BORDER_CONSTANT)// If BORDER_CONSTANT out of border values are equal to zero and could be skipped
1883         {
1884             int src_idx = borderInterpolate(-1, len, borderType);
1885             for (int k = 0; k < cn; k++)
1886                 dst[k] = dst[k] + m[0] * src[src_idx*cn + k];
1887         }
1888
1889         src += cn; dst += cn;
1890         for (int i = cn; i < (len - 1)*cn; i++, src++, dst++)
1891             *dst = m[0] * src[-cn] + m[1] * src[0] + m[2] * src[cn];
1892
1893         // Point that fall right from border
1894         for (int k = 0; k < cn; k++)
1895             dst[k] = m[0] * src[k - cn] + m[1] * src[k];
1896         if (borderType != BORDER_CONSTANT)// If BORDER_CONSTANT out of border values are equal to zero and could be skipped
1897         {
1898             int src_idx = (borderInterpolate(len, len, borderType) - (len - 1))*cn;
1899             for (int k = 0; k < cn; k++)
1900                 dst[k] = dst[k] + m[2] * src[src_idx + k];
1901         }
1902     }
1903 }
1904 template <>
1905 void hlineSmooth3N<uint8_t, ufixedpoint16>(const uint8_t* src, int cn, const ufixedpoint16* m, int, ufixedpoint16* dst, int len, int borderType)
1906 {
1907     if (len == 1)
1908     {
1909         ufixedpoint16 msum = borderType != BORDER_CONSTANT ? m[0] + m[1] + m[2] : m[1];
1910         for (int k = 0; k < cn; k++)
1911             dst[k] = msum * src[k];
1912     }
1913     else
1914     {
1915         // Point that fall left from border
1916         for (int k = 0; k < cn; k++)
1917             dst[k] = m[1] * src[k] + m[2] * src[cn + k];
1918         if (borderType != BORDER_CONSTANT)// If BORDER_CONSTANT out of border values are equal to zero and could be skipped
1919         {
1920             int src_idx = borderInterpolate(-1, len, borderType);
1921             for (int k = 0; k < cn; k++)
1922                 dst[k] = dst[k] + m[0] * src[src_idx*cn + k];
1923         }
1924
1925         src += cn; dst += cn;
1926         int i = cn, lencn = (len - 1)*cn;
1927         v_uint16x8 v_mul0 = v_setall_u16(*((uint16_t*)m));
1928         v_uint16x8 v_mul1 = v_setall_u16(*((uint16_t*)(m + 1)));
1929         v_uint16x8 v_mul2 = v_setall_u16(*((uint16_t*)(m + 2)));
1930         for (; i <= lencn - 16; i += 16, src += 16, dst += 16)
1931         {
1932             v_uint16x8 v_src00, v_src01, v_src10, v_src11, v_src20, v_src21;
1933             v_expand(v_load(src - cn), v_src00, v_src01);
1934             v_expand(v_load(src), v_src10, v_src11);
1935             v_expand(v_load(src + cn), v_src20, v_src21);
1936             v_store((uint16_t*)dst, v_src00 * v_mul0 + v_src10 * v_mul1 + v_src20 * v_mul2);
1937             v_store((uint16_t*)dst + 8, v_src01 * v_mul0 + v_src11 * v_mul1 + v_src21 * v_mul2);
1938         }
1939         for (; i < lencn; i++, src++, dst++)
1940             *dst = m[0] * src[-cn] + m[1] * src[0] + m[2] * src[cn];
1941
1942         // Point that fall right from border
1943         for (int k = 0; k < cn; k++)
1944             dst[k] = m[0] * src[k - cn] + m[1] * src[k];
1945         if (borderType != BORDER_CONSTANT)// If BORDER_CONSTANT out of border values are equal to zero and could be skipped
1946         {
1947             int src_idx = (borderInterpolate(len, len, borderType) - (len - 1))*cn;
1948             for (int k = 0; k < cn; k++)
1949                 dst[k] = dst[k] + m[2] * src[src_idx + k];
1950         }
1951     }
1952 }
1953 template <typename ET, typename FT>
1954 void hlineSmooth3N121(const ET* src, int cn, const FT*, int, FT* dst, int len, int borderType)
1955 {
1956     if (len == 1)
1957     {
1958         if(borderType != BORDER_CONSTANT)
1959             for (int k = 0; k < cn; k++)
1960                 dst[k] = FT(src[k]);
1961         else
1962             for (int k = 0; k < cn; k++)
1963                 dst[k] = FT(src[k])>>1;
1964     }
1965     else
1966     {
1967         // Point that fall left from border
1968         for (int k = 0; k < cn; k++)
1969             dst[k] = (FT(src[k])>>1) + (FT(src[cn + k])>>2);
1970         if (borderType != BORDER_CONSTANT)// If BORDER_CONSTANT out of border values are equal to zero and could be skipped
1971         {
1972             int src_idx = borderInterpolate(-1, len, borderType);
1973             for (int k = 0; k < cn; k++)
1974                 dst[k] = dst[k] + (FT(src[src_idx*cn + k])>>2);
1975         }
1976
1977         src += cn; dst += cn;
1978         for (int i = cn; i < (len - 1)*cn; i++, src++, dst++)
1979             *dst = (FT(src[-cn])>>2) + (FT(src[cn])>>2) + (FT(src[0])>>1);
1980
1981         // Point that fall right from border
1982         for (int k = 0; k < cn; k++)
1983             dst[k] = (FT(src[k - cn])>>2) + (FT(src[k])>>1);
1984         if (borderType != BORDER_CONSTANT)// If BORDER_CONSTANT out of border values are equal to zero and could be skipped
1985         {
1986             int src_idx = (borderInterpolate(len, len, borderType) - (len - 1))*cn;
1987             for (int k = 0; k < cn; k++)
1988                 dst[k] = dst[k] + (FT(src[src_idx + k])>>2);
1989         }
1990     }
1991 }
1992 template <>
1993 void hlineSmooth3N121<uint8_t, ufixedpoint16>(const uint8_t* src, int cn, const ufixedpoint16*, int, ufixedpoint16* dst, int len, int borderType)
1994 {
1995     if (len == 1)
1996     {
1997         if (borderType != BORDER_CONSTANT)
1998             for (int k = 0; k < cn; k++)
1999                 dst[k] = ufixedpoint16(src[k]);
2000         else
2001             for (int k = 0; k < cn; k++)
2002                 dst[k] = ufixedpoint16(src[k]) >> 1;
2003     }
2004     else
2005     {
2006         // Point that fall left from border
2007         for (int k = 0; k < cn; k++)
2008             dst[k] = (ufixedpoint16(src[k])>>1) + (ufixedpoint16(src[cn + k])>>2);
2009         if (borderType != BORDER_CONSTANT)// If BORDER_CONSTANT out of border values are equal to zero and could be skipped
2010         {
2011             int src_idx = borderInterpolate(-1, len, borderType);
2012             for (int k = 0; k < cn; k++)
2013                 dst[k] = dst[k] + (ufixedpoint16(src[src_idx*cn + k])>>2);
2014         }
2015
2016         src += cn; dst += cn;
2017         int i = cn, lencn = (len - 1)*cn;
2018         for (; i <= lencn - 16; i += 16, src += 16, dst += 16)
2019         {
2020             v_uint16x8 v_src00, v_src01, v_src10, v_src11, v_src20, v_src21;
2021             v_expand(v_load(src - cn), v_src00, v_src01);
2022             v_expand(v_load(src), v_src10, v_src11);
2023             v_expand(v_load(src + cn), v_src20, v_src21);
2024             v_store((uint16_t*)dst, (v_src00 + v_src20 + (v_src10 << 1)) << 6);
2025             v_store((uint16_t*)dst + 8, (v_src01 + v_src21 + (v_src11 << 1)) << 6);
2026         }
2027         for (; i < lencn; i++, src++, dst++)
2028             *((uint16_t*)dst) = (uint16_t(src[-cn]) + uint16_t(src[cn]) + (uint16_t(src[0]) << 1)) << 6;
2029
2030         // Point that fall right from border
2031         for (int k = 0; k < cn; k++)
2032             dst[k] = (ufixedpoint16(src[k - cn])>>2) + (ufixedpoint16(src[k])>>1);
2033         if (borderType != BORDER_CONSTANT)// If BORDER_CONSTANT out of border values are equal to zero and could be skipped
2034         {
2035             int src_idx = (borderInterpolate(len, len, borderType) - (len - 1))*cn;
2036             for (int k = 0; k < cn; k++)
2037                 dst[k] = dst[k] + (ufixedpoint16(src[src_idx + k])>>2);
2038         }
2039     }
2040 }
2041 template <typename ET, typename FT>
2042 void hlineSmooth3Naba(const ET* src, int cn, const FT* m, int, FT* dst, int len, int borderType)
2043 {
2044     if (len == 1)
2045     {
2046         FT msum = borderType != BORDER_CONSTANT ? (m[0]<<1) + m[1] : m[1];
2047         for (int k = 0; k < cn; k++)
2048             dst[k] = msum * src[k];
2049     }
2050     else
2051     {
2052         // Point that fall left from border
2053         if (borderType != BORDER_CONSTANT)// If BORDER_CONSTANT out of border values are equal to zero and could be skipped
2054         {
2055             int src_idx = borderInterpolate(-1, len, borderType);
2056             for (int k = 0; k < cn; k++)
2057                 dst[k] = m[1] * src[k] + m[0] * src[cn + k] + m[0] * src[src_idx*cn + k];
2058         }
2059         else
2060         {
2061             for (int k = 0; k < cn; k++)
2062                 dst[k] = m[1] * src[k] + m[0] * src[cn + k];
2063         }
2064
2065         src += cn; dst += cn;
2066         for (int i = cn; i < (len - 1)*cn; i++, src++, dst++)
2067             *dst = m[1] * src[0] + m[0] * src[-cn] + m[0] * src[cn];
2068
2069         // Point that fall right from border
2070         if (borderType != BORDER_CONSTANT)// If BORDER_CONSTANT out of border values are equal to zero and could be skipped
2071         {
2072             int src_idx = (borderInterpolate(len, len, borderType) - (len - 1))*cn;
2073             for (int k = 0; k < cn; k++)
2074                 dst[k] = m[1] * src[k] + m[0] * src[k - cn] + m[0] * src[src_idx + k];
2075         }
2076         else
2077         {
2078             for (int k = 0; k < cn; k++)
2079                 dst[k] = m[0] * src[k - cn] + m[1] * src[k];
2080         }
2081     }
2082 }
2083 template <>
2084 void hlineSmooth3Naba<uint8_t, ufixedpoint16>(const uint8_t* src, int cn, const ufixedpoint16* m, int, ufixedpoint16* dst, int len, int borderType)
2085 {
2086     if (len == 1)
2087     {
2088         ufixedpoint16 msum = borderType != BORDER_CONSTANT ? (m[0]<<1) + m[1] : m[1];
2089         for (int k = 0; k < cn; k++)
2090             dst[k] = msum * src[k];
2091     }
2092     else
2093     {
2094         // Point that fall left from border
2095         if (borderType != BORDER_CONSTANT)// If BORDER_CONSTANT out of border values are equal to zero and could be skipped
2096         {
2097             int src_idx = borderInterpolate(-1, len, borderType);
2098             for (int k = 0; k < cn; k++)
2099                 ((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]));
2100         }
2101         else
2102         {
2103             for (int k = 0; k < cn; k++)
2104                 dst[k] = m[1] * src[k] + m[0] * src[cn + k];
2105         }
2106
2107         src += cn; dst += cn;
2108         int i = cn, lencn = (len - 1)*cn;
2109         v_uint16x8 v_mul0 = v_setall_u16(*((uint16_t*)m));
2110         v_uint16x8 v_mul1 = v_setall_u16(*((uint16_t*)m+1));
2111         for (; i <= lencn - 16; i += 16, src += 16, dst += 16)
2112         {
2113             v_uint16x8 v_src00, v_src01, v_src10, v_src11, v_src20, v_src21;
2114             v_expand(v_load(src - cn), v_src00, v_src01);
2115             v_expand(v_load(src), v_src10, v_src11);
2116             v_expand(v_load(src + cn), v_src20, v_src21);
2117             v_store((uint16_t*)dst, (v_src00 + v_src20) * v_mul0 + v_src10 * v_mul1);
2118             v_store((uint16_t*)dst + 8, (v_src01 + v_src21) * v_mul0 + v_src11 * v_mul1);
2119         }
2120         for (; i < lencn; i++, src++, dst++)
2121             *((uint16_t*)dst) = ((uint16_t*)m)[1] * src[0] + ((uint16_t*)m)[0] * ((uint16_t)(src[-cn]) + (uint16_t)(src[cn]));
2122
2123         // Point that fall right from border
2124         if (borderType != BORDER_CONSTANT)// If BORDER_CONSTANT out of border values are equal to zero and could be skipped
2125         {
2126             int src_idx = (borderInterpolate(len, len, borderType) - (len - 1))*cn;
2127             for (int k = 0; k < cn; k++)
2128                 ((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]));
2129         }
2130         else
2131         {
2132             for (int k = 0; k < cn; k++)
2133                 dst[k] = m[0] * src[k - cn] + m[1] * src[k];
2134         }
2135     }
2136 }
2137 template <typename ET, typename FT>
2138 void hlineSmooth5N(const ET* src, int cn, const FT* m, int, FT* dst, int len, int borderType)
2139 {
2140     if (len == 1)
2141     {
2142         FT msum = borderType != BORDER_CONSTANT ? m[0] + m[1] + m[2] + m[3] + m[4] : m[2];
2143         for (int k = 0; k < cn; k++)
2144             dst[k] = msum * src[k];
2145     }
2146     else if (len == 2)
2147     {
2148         if (borderType == BORDER_CONSTANT)
2149             for (int k = 0; k < cn; k++)
2150             {
2151                 dst[k   ] = m[2] * src[k] + m[3] * src[k+cn];
2152                 dst[k+cn] = m[1] * src[k] + m[2] * src[k+cn];
2153             }
2154         else
2155         {
2156             int idxm2 = borderInterpolate(-2, len, borderType)*cn;
2157             int idxm1 = borderInterpolate(-1, len, borderType)*cn;
2158             int idxp1 = borderInterpolate(2, len, borderType)*cn;
2159             int idxp2 = borderInterpolate(3, len, borderType)*cn;
2160             for (int k = 0; k < cn; k++)
2161             {
2162                 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];
2163                 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];
2164             }
2165         }
2166     }
2167     else if (len == 3)
2168     {
2169         if (borderType == BORDER_CONSTANT)
2170             for (int k = 0; k < cn; k++)
2171             {
2172                 dst[k       ] = m[2] * src[k] + m[3] * src[k + cn] + m[4] * src[k + 2*cn];
2173                 dst[k +   cn] = m[1] * src[k] + m[2] * src[k + cn] + m[3] * src[k + 2*cn];
2174                 dst[k + 2*cn] = m[0] * src[k] + m[1] * src[k + cn] + m[2] * src[k + 2*cn];
2175             }
2176         else
2177         {
2178             int idxm2 = borderInterpolate(-2, len, borderType)*cn;
2179             int idxm1 = borderInterpolate(-1, len, borderType)*cn;
2180             int idxp1 = borderInterpolate(3, len, borderType)*cn;
2181             int idxp2 = borderInterpolate(4, len, borderType)*cn;
2182             for (int k = 0; k < cn; k++)
2183             {
2184                 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];
2185                 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];
2186                 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];
2187             }
2188         }
2189     }
2190     else
2191     {
2192         // Points that fall left from border
2193         for (int k = 0; k < cn; k++)
2194         {
2195             dst[k] = m[2] * src[k] + m[3] * src[cn + k] + m[4] * src[2*cn + k];
2196             dst[k + cn] = m[1] * src[k] + m[2] * src[cn + k] + m[3] * src[2*cn + k] + m[4] * src[3*cn + k];
2197         }
2198         if (borderType != BORDER_CONSTANT)// If BORDER_CONSTANT out of border values are equal to zero and could be skipped
2199         {
2200             int idxm2 = borderInterpolate(-2, len, borderType)*cn;
2201             int idxm1 = borderInterpolate(-1, len, borderType)*cn;
2202             for (int k = 0; k < cn; k++)
2203             {
2204                 dst[k] = dst[k] + m[0] * src[idxm2 + k] + m[1] * src[idxm1 + k];
2205                 dst[k + cn] = dst[k + cn] + m[0] * src[idxm1 + k];
2206             }
2207         }
2208
2209         src += 2*cn; dst += 2*cn;
2210         for (int i = 2*cn; i < (len - 2)*cn; i++, src++, dst++)
2211             *dst = m[0] * src[-2*cn] + m[1] * src[-cn] + m[2] * src[0] + m[3] * src[cn] + m[4] * src[2*cn];
2212
2213         // Points that fall right from border
2214         for (int k = 0; k < cn; k++)
2215         {
2216             dst[k] = m[0] * src[k - 2*cn] + m[1] * src[k - cn] + m[2] * src[k] + m[3] * src[k + cn];
2217             dst[k + cn] = m[0] * src[k - cn] + m[1] * src[k] + m[2] * src[k + cn];
2218         }
2219         if (borderType != BORDER_CONSTANT)// If BORDER_CONSTANT out of border values are equal to zero and could be skipped
2220         {
2221             int idxp1 = (borderInterpolate(len, len, borderType) - (len - 2))*cn;
2222             int idxp2 = (borderInterpolate(len+1, len, borderType) - (len - 2))*cn;
2223             for (int k = 0; k < cn; k++)
2224             {
2225                 dst[k] = dst[k] + m[4] * src[idxp1 + k];
2226                 dst[k + cn] = dst[k + cn] + m[3] * src[idxp1 + k] + m[4] * src[idxp2 + k];
2227             }
2228         }
2229     }
2230 }
2231 template <>
2232 void hlineSmooth5N<uint8_t, ufixedpoint16>(const uint8_t* src, int cn, const ufixedpoint16* m, int, ufixedpoint16* dst, int len, int borderType)
2233 {
2234     if (len == 1)
2235     {
2236         ufixedpoint16 msum = borderType != BORDER_CONSTANT ? m[0] + m[1] + m[2] + m[3] + m[4] : m[2];
2237         for (int k = 0; k < cn; k++)
2238             dst[k] = msum * src[k];
2239     }
2240     else if (len == 2)
2241     {
2242         if (borderType == BORDER_CONSTANT)
2243             for (int k = 0; k < cn; k++)
2244             {
2245                 dst[k] = m[2] * src[k] + m[3] * src[k + cn];
2246                 dst[k + cn] = m[1] * src[k] + m[2] * src[k + cn];
2247             }
2248         else
2249         {
2250             int idxm2 = borderInterpolate(-2, len, borderType)*cn;
2251             int idxm1 = borderInterpolate(-1, len, borderType)*cn;
2252             int idxp1 = borderInterpolate(2, len, borderType)*cn;
2253             int idxp2 = borderInterpolate(3, len, borderType)*cn;
2254             for (int k = 0; k < cn; k++)
2255             {
2256                 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];
2257                 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];
2258             }
2259         }
2260     }
2261     else if (len == 3)
2262     {
2263         if (borderType == BORDER_CONSTANT)
2264             for (int k = 0; k < cn; k++)
2265             {
2266                 dst[k] = m[2] * src[k] + m[3] * src[k + cn] + m[4] * src[k + 2 * cn];
2267                 dst[k + cn] = m[1] * src[k] + m[2] * src[k + cn] + m[3] * src[k + 2 * cn];
2268                 dst[k + 2 * cn] = m[0] * src[k] + m[1] * src[k + cn] + m[2] * src[k + 2 * cn];
2269             }
2270         else
2271         {
2272             int idxm2 = borderInterpolate(-2, len, borderType)*cn;
2273             int idxm1 = borderInterpolate(-1, len, borderType)*cn;
2274             int idxp1 = borderInterpolate(3, len, borderType)*cn;
2275             int idxp2 = borderInterpolate(4, len, borderType)*cn;
2276             for (int k = 0; k < cn; k++)
2277             {
2278                 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];
2279                 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];
2280                 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];
2281             }
2282         }
2283     }
2284     else
2285     {
2286         // Points that fall left from border
2287         for (int k = 0; k < cn; k++)
2288         {
2289             dst[k] = m[2] * src[k] + m[3] * src[cn + k] + m[4] * src[2 * cn + k];
2290             dst[k + cn] = m[1] * src[k] + m[2] * src[cn + k] + m[3] * src[2 * cn + k] + m[4] * src[3 * cn + k];
2291         }
2292         if (borderType != BORDER_CONSTANT)// If BORDER_CONSTANT out of border values are equal to zero and could be skipped
2293         {
2294             int idxm2 = borderInterpolate(-2, len, borderType)*cn;
2295             int idxm1 = borderInterpolate(-1, len, borderType)*cn;
2296             for (int k = 0; k < cn; k++)
2297             {
2298                 dst[k] = dst[k] + m[0] * src[idxm2 + k] + m[1] * src[idxm1 + k];
2299                 dst[k + cn] = dst[k + cn] + m[0] * src[idxm1 + k];
2300             }
2301         }
2302
2303         src += 2 * cn; dst += 2 * cn;
2304         int i = 2*cn, lencn = (len - 2)*cn;
2305         v_uint16x8 v_mul0 = v_setall_u16(*((uint16_t*)m));
2306         v_uint16x8 v_mul1 = v_setall_u16(*((uint16_t*)(m + 1)));
2307         v_uint16x8 v_mul2 = v_setall_u16(*((uint16_t*)(m + 2)));
2308         v_uint16x8 v_mul3 = v_setall_u16(*((uint16_t*)(m + 3)));
2309         v_uint16x8 v_mul4 = v_setall_u16(*((uint16_t*)(m + 4)));
2310         for (; i <= lencn - 16; i += 16, src += 16, dst += 16)
2311         {
2312             v_uint16x8 v_src00, v_src01, v_src10, v_src11, v_src20, v_src21, v_src30, v_src31, v_src40, v_src41;
2313             v_expand(v_load(src - 2*cn), v_src00, v_src01);
2314             v_expand(v_load(src - cn), v_src10, v_src11);
2315             v_expand(v_load(src), v_src20, v_src21);
2316             v_expand(v_load(src + cn), v_src30, v_src31);
2317             v_expand(v_load(src + 2*cn), v_src40, v_src41);
2318             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);
2319             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);
2320         }
2321         for (; i < lencn; i++, src++, dst++)
2322             *dst = m[0] * src[-2*cn] + m[1] * src[-cn] + m[2] * src[0] + m[3] * src[cn] + m[4] * src[2*cn];
2323
2324         // Points that fall right from border
2325         for (int k = 0; k < cn; k++)
2326         {
2327             dst[k] = m[0] * src[k - 2 * cn] + m[1] * src[k - cn] + m[2] * src[k] + m[3] * src[k + cn];
2328             dst[k + cn] = m[0] * src[k - cn] + m[1] * src[k] + m[2] * src[k + cn];
2329         }
2330         if (borderType != BORDER_CONSTANT)// If BORDER_CONSTANT out of border values are equal to zero and could be skipped
2331         {
2332             int idxp1 = (borderInterpolate(len, len, borderType) - (len - 2))*cn;
2333             int idxp2 = (borderInterpolate(len + 1, len, borderType) - (len - 2))*cn;
2334             for (int k = 0; k < cn; k++)
2335             {
2336                 dst[k] = dst[k] + m[4] * src[idxp1 + k];
2337                 dst[k + cn] = dst[k + cn] + m[3] * src[idxp1 + k] + m[4] * src[idxp2 + k];
2338             }
2339         }
2340     }
2341 }
2342 template <typename ET, typename FT>
2343 void hlineSmooth5N14641(const ET* src, int cn, const FT*, int, FT* dst, int len, int borderType)
2344 {
2345     if (len == 1)
2346     {
2347         if (borderType == BORDER_CONSTANT)
2348             for (int k = 0; k < cn; k++)
2349                 dst[k] = (FT(src[k])>>3)*(uint8_t)3;
2350         else
2351             for (int k = 0; k < cn; k++)
2352                 dst[k] = src[k];
2353     }
2354     else if (len == 2)
2355     {
2356         if (borderType == BORDER_CONSTANT)
2357             for (int k = 0; k < cn; k++)
2358             {
2359                 dst[k] = (FT(src[k])>>4)*(uint8_t)6 + (FT(src[k + cn])>>2);
2360                 dst[k + cn] = (FT(src[k]) >> 2) + (FT(src[k + cn])>>4)*(uint8_t)6;
2361             }
2362         else
2363         {
2364             int idxm2 = borderInterpolate(-2, len, borderType)*cn;
2365             int idxm1 = borderInterpolate(-1, len, borderType)*cn;
2366             int idxp1 = borderInterpolate(2, len, borderType)*cn;
2367             int idxp2 = borderInterpolate(3, len, borderType)*cn;
2368             for (int k = 0; k < cn; k++)
2369             {
2370                 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);
2371                 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);
2372             }
2373         }
2374     }
2375     else if (len == 3)
2376     {
2377         if (borderType == BORDER_CONSTANT)
2378             for (int k = 0; k < cn; k++)
2379             {
2380                 dst[k] = (FT(src[k])>>4)*(uint8_t)6 + (FT(src[k + cn])>>2) + (FT(src[k + 2 * cn])>>4);
2381                 dst[k + cn] = (FT(src[k + cn])>>4)*(uint8_t)6 + (FT(src[k])>>2) + (FT(src[k + 2 * cn])>>2);
2382                 dst[k + 2 * cn] = (FT(src[k + 2 * cn])>>4)*(uint8_t)6 + (FT(src[k + cn])>>2) + (FT(src[k])>>4);
2383             }
2384         else
2385         {
2386             int idxm2 = borderInterpolate(-2, len, borderType)*cn;
2387             int idxm1 = borderInterpolate(-1, len, borderType)*cn;
2388             int idxp1 = borderInterpolate(3, len, borderType)*cn;
2389             int idxp2 = borderInterpolate(4, len, borderType)*cn;
2390             for (int k = 0; k < cn; k++)
2391             {
2392                 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);
2393                 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);
2394                 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);
2395             }
2396         }
2397     }
2398     else
2399     {
2400         // Points that fall left from border
2401         for (int k = 0; k < cn; k++)
2402         {
2403             dst[k] = (FT(src[k])>>4)*(uint8_t)6 + (FT(src[cn + k])>>2) + (FT(src[2 * cn + k])>>4);
2404             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);
2405         }
2406         if (borderType != BORDER_CONSTANT)// If BORDER_CONSTANT out of border values are equal to zero and could be skipped
2407         {
2408             int idxm2 = borderInterpolate(-2, len, borderType)*cn;
2409             int idxm1 = borderInterpolate(-1, len, borderType)*cn;
2410             for (int k = 0; k < cn; k++)
2411             {
2412                 dst[k] = dst[k] + (FT(src[idxm2 + k])>>4) + (FT(src[idxm1 + k])>>2);
2413                 dst[k + cn] = dst[k + cn] + (FT(src[idxm1 + k])>>4);
2414             }
2415         }
2416
2417         src += 2 * cn; dst += 2 * cn;
2418         for (int i = 2 * cn; i < (len - 2)*cn; i++, src++, dst++)
2419             *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);
2420
2421         // Points that fall right from border
2422         for (int k = 0; k < cn; k++)
2423         {
2424             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);
2425             dst[k + cn] = (FT(src[k + cn])>>4)*(uint8_t)6 + (FT(src[k])>>2) + (FT(src[k - cn])>>4);
2426         }
2427         if (borderType != BORDER_CONSTANT)// If BORDER_CONSTANT out of border values are equal to zero and could be skipped
2428         {
2429             int idxp1 = (borderInterpolate(len, len, borderType) - (len - 2))*cn;
2430             int idxp2 = (borderInterpolate(len + 1, len, borderType) - (len - 2))*cn;
2431             for (int k = 0; k < cn; k++)
2432             {
2433                 dst[k] = dst[k] + (FT(src[idxp1 + k])>>4);
2434                 dst[k + cn] = dst[k + cn] + (FT(src[idxp1 + k])>>2) + (FT(src[idxp2 + k])>>4);
2435             }
2436         }
2437     }
2438 }
2439 template <>
2440 void hlineSmooth5N14641<uint8_t, ufixedpoint16>(const uint8_t* src, int cn, const ufixedpoint16*, int, ufixedpoint16* dst, int len, int borderType)
2441 {
2442     if (len == 1)
2443     {
2444         if (borderType == BORDER_CONSTANT)
2445             for (int k = 0; k < cn; k++)
2446                 dst[k] = (ufixedpoint16(src[k])>>3) * (uint8_t)3;
2447         else
2448         {
2449             for (int k = 0; k < cn; k++)
2450                 dst[k] = src[k];
2451         }
2452     }
2453     else if (len == 2)
2454     {
2455         if (borderType == BORDER_CONSTANT)
2456             for (int k = 0; k < cn; k++)
2457             {
2458                 dst[k] = (ufixedpoint16(src[k]) >> 4) * (uint8_t)6 + (ufixedpoint16(src[k + cn]) >> 2);
2459                 dst[k + cn] = (ufixedpoint16(src[k]) >> 2) + (ufixedpoint16(src[k + cn]) >> 4) * (uint8_t)6;
2460             }
2461         else
2462         {
2463             int idxm2 = borderInterpolate(-2, len, borderType)*cn;
2464             int idxm1 = borderInterpolate(-1, len, borderType)*cn;
2465             int idxp1 = borderInterpolate(2, len, borderType)*cn;
2466             int idxp2 = borderInterpolate(3, len, borderType)*cn;
2467             for (int k = 0; k < cn; k++)
2468             {
2469                 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);
2470                 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);
2471             }
2472         }
2473     }
2474     else if (len == 3)
2475     {
2476         if (borderType == BORDER_CONSTANT)
2477             for (int k = 0; k < cn; k++)
2478             {
2479                 dst[k] = (ufixedpoint16(src[k]) >> 4) * (uint8_t)6 + (ufixedpoint16(src[k + cn]) >> 2) + (ufixedpoint16(src[k + 2 * cn]) >> 4);
2480                 dst[k + cn] = (ufixedpoint16(src[k + cn]) >> 4) * (uint8_t)6 + (ufixedpoint16(src[k]) >> 2) + (ufixedpoint16(src[k + 2 * cn]) >> 2);
2481                 dst[k + 2 * cn] = (ufixedpoint16(src[k + 2 * cn]) >> 4) * (uint8_t)6 + (ufixedpoint16(src[k + cn]) >> 2) + (ufixedpoint16(src[k]) >> 4);
2482             }
2483         else
2484         {
2485             int idxm2 = borderInterpolate(-2, len, borderType)*cn;
2486             int idxm1 = borderInterpolate(-1, len, borderType)*cn;
2487             int idxp1 = borderInterpolate(3, len, borderType)*cn;
2488             int idxp2 = borderInterpolate(4, len, borderType)*cn;
2489             for (int k = 0; k < cn; k++)
2490             {
2491                 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);
2492                 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);
2493                 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);
2494             }
2495         }
2496     }
2497     else
2498     {
2499         // Points that fall left from border
2500         for (int k = 0; k < cn; k++)
2501         {
2502             dst[k] = (ufixedpoint16(src[k]) >> 4) * (uint8_t)6 + (ufixedpoint16(src[cn + k]) >> 2) + (ufixedpoint16(src[2 * cn + k]) >> 4);
2503             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);
2504         }
2505         if (borderType != BORDER_CONSTANT)// If BORDER_CONSTANT out of border values are equal to zero and could be skipped
2506         {
2507             int idxm2 = borderInterpolate(-2, len, borderType)*cn;
2508             int idxm1 = borderInterpolate(-1, len, borderType)*cn;
2509             for (int k = 0; k < cn; k++)
2510             {
2511                 dst[k] = dst[k] + (ufixedpoint16(src[idxm2 + k]) >> 4) + (ufixedpoint16(src[idxm1 + k]) >> 2);
2512                 dst[k + cn] = dst[k + cn] + (ufixedpoint16(src[idxm1 + k]) >> 4);
2513             }
2514         }
2515
2516         src += 2 * cn; dst += 2 * cn;
2517         int i = 2 * cn, lencn = (len - 2)*cn;
2518         v_uint16x8 v_6 = v_setall_u16(6);
2519         for (; i <= lencn - 16; i += 16, src += 16, dst += 16)
2520         {
2521             v_uint16x8 v_src00, v_src01, v_src10, v_src11, v_src20, v_src21, v_src30, v_src31, v_src40, v_src41;
2522             v_expand(v_load(src - 2*cn), v_src00, v_src01);
2523             v_expand(v_load(src - cn), v_src10, v_src11);
2524             v_expand(v_load(src), v_src20, v_src21);
2525             v_expand(v_load(src + cn), v_src30, v_src31);
2526             v_expand(v_load(src + 2*cn), v_src40, v_src41);
2527             v_store((uint16_t*)dst, (v_src20 * v_6 + ((v_src10 + v_src30) << 2) + v_src00 + v_src40) << 4);
2528             v_store((uint16_t*)dst + 8, (v_src21 * v_6 + ((v_src11 + v_src31) << 2) + v_src01 + v_src41) << 4);
2529         }
2530         for (; i < lencn; i++, src++, dst++)
2531             *((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;
2532
2533         // Points that fall right from border
2534         for (int k = 0; k < cn; k++)
2535         {
2536             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);
2537             dst[k + cn] = (ufixedpoint16(src[k + cn]) >> 4) * (uint8_t)6 + (ufixedpoint16(src[k]) >> 2) + (ufixedpoint16(src[k - cn]) >> 4);
2538         }
2539         if (borderType != BORDER_CONSTANT)// If BORDER_CONSTANT out of border values are equal to zero and could be skipped
2540         {
2541             int idxp1 = (borderInterpolate(len, len, borderType) - (len - 2))*cn;
2542             int idxp2 = (borderInterpolate(len + 1, len, borderType) - (len - 2))*cn;
2543             for (int k = 0; k < cn; k++)
2544             {
2545                 dst[k] = dst[k] + (ufixedpoint16(src[idxp1 + k]) >> 4);
2546                 dst[k + cn] = dst[k + cn] + (ufixedpoint16(src[idxp1 + k]) >> 2) + (ufixedpoint16(src[idxp2 + k]) >> 4);
2547             }
2548         }
2549     }
2550 }
2551 template <typename ET, typename FT>
2552 void hlineSmooth5Nabcba(const ET* src, int cn, const FT* m, int, FT* dst, int len, int borderType)
2553 {
2554     if (len == 1)
2555     {
2556         FT msum = borderType != BORDER_CONSTANT ? ((m[0] + m[1])<<1) + m[2] : m[2];
2557         for (int k = 0; k < cn; k++)
2558             dst[k] = msum * src[k];
2559     }
2560     else if (len == 2)
2561     {
2562         if (borderType == BORDER_CONSTANT)
2563             for (int k = 0; k < cn; k++)
2564             {
2565                 dst[k] = m[2] * src[k] + m[1] * src[k + cn];
2566                 dst[k + cn] = m[1] * src[k] + m[2] * src[k + cn];
2567             }
2568         else
2569         {
2570             int idxm2 = borderInterpolate(-2, len, borderType)*cn;
2571             int idxm1 = borderInterpolate(-1, len, borderType)*cn;
2572             int idxp1 = borderInterpolate(2, len, borderType)*cn;
2573             int idxp2 = borderInterpolate(3, len, borderType)*cn;
2574             for (int k = 0; k < cn; k++)
2575             {
2576                 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];
2577                 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];
2578             }
2579         }
2580     }
2581     else if (len == 3)
2582     {
2583         if (borderType == BORDER_CONSTANT)
2584             for (int k = 0; k < cn; k++)
2585             {
2586                 dst[k] = m[2] * src[k] + m[1] * src[k + cn] + m[0] * src[k + 2 * cn];
2587                 dst[k + cn] = m[1] * src[k] + m[2] * src[k + cn] + m[1] * src[k + 2 * cn];
2588                 dst[k + 2 * cn] = m[0] * src[k] + m[1] * src[k + cn] + m[2] * src[k + 2 * cn];
2589             }
2590         else
2591         {
2592             int idxm2 = borderInterpolate(-2, len, borderType)*cn;
2593             int idxm1 = borderInterpolate(-1, len, borderType)*cn;
2594             int idxp1 = borderInterpolate(3, len, borderType)*cn;
2595             int idxp2 = borderInterpolate(4, len, borderType)*cn;
2596             for (int k = 0; k < cn; k++)
2597             {
2598                 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];
2599                 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];
2600                 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];
2601             }
2602         }
2603     }
2604     else
2605     {
2606         // Points that fall left from border
2607         for (int k = 0; k < cn; k++)
2608         {
2609             dst[k] = m[2] * src[k] + m[1] * src[cn + k] + m[0] * src[2 * cn + k];
2610             dst[k + cn] = m[1] * src[k] + m[2] * src[cn + k] + m[1] * src[2 * cn + k] + m[0] * src[3 * cn + k];
2611         }
2612         if (borderType != BORDER_CONSTANT)// If BORDER_CONSTANT out of border values are equal to zero and could be skipped
2613         {
2614             int idxm2 = borderInterpolate(-2, len, borderType)*cn;
2615             int idxm1 = borderInterpolate(-1, len, borderType)*cn;
2616             for (int k = 0; k < cn; k++)
2617             {
2618                 dst[k] = dst[k] + m[0] * src[idxm2 + k] + m[1] * src[idxm1 + k];
2619                 dst[k + cn] = dst[k + cn] + m[0] * src[idxm1 + k];
2620             }
2621         }
2622
2623         src += 2 * cn; dst += 2 * cn;
2624         for (int i = 2 * cn; i < (len - 2)*cn; i++, src++, dst++)
2625             *dst = m[0] * src[-2 * cn] + m[1] * src[-cn] + m[2] * src[0] + m[3] * src[cn] + m[4] * src[2 * cn];
2626
2627         // Points that fall right from border
2628         for (int k = 0; k < cn; k++)
2629         {
2630             dst[k] = m[0] * src[k - 2 * cn] + m[1] * src[k - cn] + m[2] * src[k] + m[3] * src[k + cn];
2631             dst[k + cn] = m[0] * src[k - cn] + m[1] * src[k] + m[2] * src[k + cn];
2632         }
2633         if (borderType != BORDER_CONSTANT)// If BORDER_CONSTANT out of border values are equal to zero and could be skipped
2634         {
2635             int idxp1 = (borderInterpolate(len, len, borderType) - (len - 2))*cn;
2636             int idxp2 = (borderInterpolate(len + 1, len, borderType) - (len - 2))*cn;
2637             for (int k = 0; k < cn; k++)
2638             {
2639                 dst[k] = dst[k] + m[0] * src[idxp1 + k];
2640                 dst[k + cn] = dst[k + cn] + m[1] * src[idxp1 + k] + m[0] * src[idxp2 + k];
2641             }
2642         }
2643     }
2644 }
2645 template <>
2646 void hlineSmooth5Nabcba<uint8_t, ufixedpoint16>(const uint8_t* src, int cn, const ufixedpoint16* m, int, ufixedpoint16* dst, int len, int borderType)
2647 {
2648     if (len == 1)
2649     {
2650         ufixedpoint16 msum = borderType != BORDER_CONSTANT ? ((m[0] + m[1]) << 1) + m[2] : m[2];
2651         for (int k = 0; k < cn; k++)
2652             dst[k] = msum * src[k];
2653     }
2654     else if (len == 2)
2655     {
2656         if (borderType == BORDER_CONSTANT)
2657             for (int k = 0; k < cn; k++)
2658             {
2659                 dst[k] = m[2] * src[k] + m[1] * src[k + cn];
2660                 dst[k + cn] = m[1] * src[k] + m[2] * src[k + cn];
2661             }
2662         else
2663         {
2664             int idxm2 = borderInterpolate(-2, len, borderType)*cn;
2665             int idxm1 = borderInterpolate(-1, len, borderType)*cn;
2666             int idxp1 = borderInterpolate(2, len, borderType)*cn;
2667             int idxp2 = borderInterpolate(3, len, borderType)*cn;
2668             for (int k = 0; k < cn; k++)
2669             {
2670                 ((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]));
2671                 ((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];
2672             }
2673         }
2674     }
2675     else if (len == 3)
2676     {
2677         if (borderType == BORDER_CONSTANT)
2678             for (int k = 0; k < cn; k++)
2679             {
2680                 dst[k] = m[2] * src[k] + m[1] * src[k + cn] + m[0] * src[k + 2 * cn];
2681                 ((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];
2682                 dst[k + 2 * cn] = m[0] * src[k] + m[1] * src[k + cn] + m[2] * src[k + 2 * cn];
2683             }
2684         else
2685         {
2686             int idxm2 = borderInterpolate(-2, len, borderType)*cn;
2687             int idxm1 = borderInterpolate(-1, len, borderType)*cn;
2688             int idxp1 = borderInterpolate(3, len, borderType)*cn;
2689             int idxp2 = borderInterpolate(4, len, borderType)*cn;
2690             for (int k = 0; k < cn; k++)
2691             {
2692                 ((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]));
2693                 ((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]));
2694                 ((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];
2695             }
2696         }
2697     }
2698     else
2699     {
2700         // Points that fall left from border
2701         if (borderType != BORDER_CONSTANT)// If BORDER_CONSTANT out of border values are equal to zero and could be skipped
2702         {
2703             int idxm2 = borderInterpolate(-2, len, borderType)*cn;
2704             int idxm1 = borderInterpolate(-1, len, borderType)*cn;
2705             for (int k = 0; k < cn; k++)
2706             {
2707                 ((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]));
2708                 ((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]));
2709             }
2710         }
2711         else
2712         {
2713             for (int k = 0; k < cn; k++)
2714             {
2715                 dst[k] = m[2] * src[k] + m[1] * src[cn + k] + m[0] * src[2 * cn + k];
2716                 ((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];
2717             }
2718         }
2719
2720         src += 2 * cn; dst += 2 * cn;
2721         int i = 2 * cn, lencn = (len - 2)*cn;
2722         v_uint16x8 v_mul0 = v_setall_u16(*((uint16_t*)m));
2723         v_uint16x8 v_mul1 = v_setall_u16(*((uint16_t*)(m + 1)));
2724         v_uint16x8 v_mul2 = v_setall_u16(*((uint16_t*)(m + 2)));
2725         for (; i <= lencn - 16; i += 16, src += 16, dst += 16)
2726         {
2727             v_uint16x8 v_src00, v_src01, v_src10, v_src11, v_src20, v_src21, v_src30, v_src31, v_src40, v_src41;
2728             v_expand(v_load(src - 2 * cn), v_src00, v_src01);
2729             v_expand(v_load(src - cn), v_src10, v_src11);
2730             v_expand(v_load(src), v_src20, v_src21);
2731             v_expand(v_load(src + cn), v_src30, v_src31);
2732             v_expand(v_load(src + 2 * cn), v_src40, v_src41);
2733             v_store((uint16_t*)dst, (v_src00 + v_src40) * v_mul0 + (v_src10 + v_src30)* v_mul1 + v_src20 * v_mul2);
2734             v_store((uint16_t*)dst + 8, (v_src01 + v_src41) * v_mul0 + (v_src11 + v_src31) * v_mul1 + v_src21 * v_mul2);
2735         }
2736         for (; i < lencn; i++, src++, dst++)
2737             *((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];
2738
2739         // Points that fall right from border
2740         if (borderType != BORDER_CONSTANT)// If BORDER_CONSTANT out of border values are equal to zero and could be skipped
2741         {
2742             int idxp1 = (borderInterpolate(len, len, borderType) - (len - 2))*cn;
2743             int idxp2 = (borderInterpolate(len + 1, len, borderType) - (len - 2))*cn;
2744             for (int k = 0; k < cn; k++)
2745             {
2746                 ((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];
2747                 ((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];
2748             }
2749         }
2750         else
2751         {
2752             for (int k = 0; k < cn; k++)
2753             {
2754                 ((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];
2755                 dst[k + cn] = m[0] * src[k - cn] + m[1] * src[k] + m[2] * src[k + cn];
2756             }
2757         }
2758     }
2759 }
2760 template <typename ET, typename FT>
2761 void hlineSmooth(const ET* src, int cn, const FT* m, int n, FT* dst, int len, int borderType)
2762 {
2763     int pre_shift = n / 2;
2764     int post_shift = n - pre_shift;
2765     int i = 0;
2766     for (; i < min(pre_shift, len); i++, dst += cn) // Points that fall left from border
2767     {
2768         for (int k = 0; k < cn; k++)
2769             dst[k] = m[pre_shift-i] * src[k];
2770         if (borderType != BORDER_CONSTANT)// If BORDER_CONSTANT out of border values are equal to zero and could be skipped
2771             for (int j = i - pre_shift, mid = 0; j < 0; j++, mid++)
2772             {
2773                 int src_idx = borderInterpolate(j, len, borderType);
2774                 for (int k = 0; k < cn; k++)
2775                     dst[k] = dst[k] + m[mid] * src[src_idx*cn + k];
2776             }
2777         int j, mid;
2778         for (j = 1, mid = pre_shift - i + 1; j < min(i + post_shift, len); j++, mid++)
2779             for (int k = 0; k < cn; k++)
2780                 dst[k] = dst[k] + m[mid] * src[j*cn + k];
2781         if (borderType != BORDER_CONSTANT)
2782             for (; j < i + post_shift; j++, mid++)
2783             {
2784                 int src_idx = borderInterpolate(j, len, borderType);
2785                 for (int k = 0; k < cn; k++)
2786                     dst[k] = dst[k] + m[mid] * src[src_idx*cn + k];
2787             }
2788     }
2789     i *= cn;
2790     for (; i < (len - post_shift + 1)*cn; i++, src++, dst++)
2791     {
2792         *dst = m[0] * src[0];
2793         for (int j = 1; j < n; j++)
2794             *dst = *dst + m[j] * src[j*cn];
2795     }
2796     i /= cn;
2797     for (i -= pre_shift; i < len - pre_shift; i++, src += cn, dst += cn) // Points that fall right from border
2798     {
2799         for (int k = 0; k < cn; k++)
2800             dst[k] = m[0] * src[k];
2801         int j = 1;
2802         for (; j < len - i; j++)
2803             for (int k = 0; k < cn; k++)
2804                 dst[k] = dst[k] + m[j] * src[j*cn + k];
2805         if (borderType != BORDER_CONSTANT)// If BORDER_CONSTANT out of border values are equal to zero and could be skipped
2806             for (; j < n; j++)
2807             {
2808                 int src_idx = borderInterpolate(i + j, len, borderType) - i;
2809                 for (int k = 0; k < cn; k++)
2810                     dst[k] = dst[k] + m[j] * src[src_idx*cn + k];
2811             }
2812     }
2813 }
2814 template <>
2815 void hlineSmooth<uint8_t, ufixedpoint16>(const uint8_t* src, int cn, const ufixedpoint16* m, int n, ufixedpoint16* dst, int len, int borderType)
2816 {
2817     int pre_shift = n / 2;
2818     int post_shift = n - pre_shift;
2819     int i = 0;
2820     for (; i < min(pre_shift, len); i++, dst += cn) // Points that fall left from border
2821     {
2822         for (int k = 0; k < cn; k++)
2823             dst[k] = m[pre_shift - i] * src[k];
2824         if (borderType != BORDER_CONSTANT)// If BORDER_CONSTANT out of border values are equal to zero and could be skipped
2825             for (int j = i - pre_shift, mid = 0; j < 0; j++, mid++)
2826             {
2827                 int src_idx = borderInterpolate(j, len, borderType);
2828                 for (int k = 0; k < cn; k++)
2829                     dst[k] = dst[k] + m[mid] * src[src_idx*cn + k];
2830             }
2831         int j, mid;
2832         for (j = 1, mid = pre_shift - i + 1; j < min(i + post_shift, len); j++, mid++)
2833             for (int k = 0; k < cn; k++)
2834                 dst[k] = dst[k] + m[mid] * src[j*cn + k];
2835         if (borderType != BORDER_CONSTANT)
2836             for (; j < i + post_shift; j++, mid++)
2837             {
2838                 int src_idx = borderInterpolate(j, len, borderType);
2839                 for (int k = 0; k < cn; k++)
2840                     dst[k] = dst[k] + m[mid] * src[src_idx*cn + k];
2841             }
2842     }
2843     i *= cn;
2844     int lencn = (len - post_shift + 1)*cn;
2845     for (; i <= lencn - 16; i+=16, src+=16, dst+=16)
2846     {
2847         v_uint16x8 v_src0, v_src1;
2848         v_uint16x8 v_mul = v_setall_u16(*((uint16_t*)m));
2849         v_expand(v_load(src), v_src0, v_src1);
2850         v_uint16x8 v_res0 = v_src0 * v_mul;
2851         v_uint16x8 v_res1 = v_src1 * v_mul;
2852         for (int j = 1; j < n; j++)
2853         {
2854             v_mul = v_setall_u16(*((uint16_t*)(m + j)));
2855             v_expand(v_load(src + j * cn), v_src0, v_src1);
2856             v_res0 += v_src0 * v_mul;
2857             v_res1 += v_src1 * v_mul;
2858         }
2859         v_store((uint16_t*)dst, v_res0);
2860         v_store((uint16_t*)dst+8, v_res1);
2861     }
2862     for (; i < lencn; i++, src++, dst++)
2863     {
2864             *dst = m[0] * src[0];
2865             for (int j = 1; j < n; j++)
2866                 *dst = *dst + m[j] * src[j*cn];
2867     }
2868     i /= cn;
2869     for (i -= pre_shift; i < len - pre_shift; i++, src += cn, dst += cn) // Points that fall right from border
2870     {
2871         for (int k = 0; k < cn; k++)
2872             dst[k] = m[0] * src[k];
2873         int j = 1;
2874         for (; j < len - i; j++)
2875             for (int k = 0; k < cn; k++)
2876                 dst[k] = dst[k] + m[j] * src[j*cn + k];
2877         if (borderType != BORDER_CONSTANT)// If BORDER_CONSTANT out of border values are equal to zero and could be skipped
2878             for (; j < n; j++)
2879             {
2880                 int src_idx = borderInterpolate(i + j, len, borderType) - i;
2881                 for (int k = 0; k < cn; k++)
2882                     dst[k] = dst[k] + m[j] * src[src_idx*cn + k];
2883             }
2884     }
2885 }
2886 template <typename ET, typename FT>
2887 void hlineSmoothONa_yzy_a(const ET* src, int cn, const FT* m, int n, FT* dst, int len, int borderType)
2888 {
2889     int pre_shift = n / 2;
2890     int post_shift = n - pre_shift;
2891     int i = 0;
2892     for (; i < min(pre_shift, len); i++, dst += cn) // Points that fall left from border
2893     {
2894         for (int k = 0; k < cn; k++)
2895             dst[k] = m[pre_shift - i] * src[k];
2896         if (borderType != BORDER_CONSTANT)// If BORDER_CONSTANT out of border values are equal to zero and could be skipped
2897             for (int j = i - pre_shift, mid = 0; j < 0; j++, mid++)
2898             {
2899                 int src_idx = borderInterpolate(j, len, borderType);
2900                 for (int k = 0; k < cn; k++)
2901                     dst[k] = dst[k] + m[mid] * src[src_idx*cn + k];
2902             }
2903         int j, mid;
2904         for (j = 1, mid = pre_shift - i + 1; j < min(i + post_shift, len); j++, mid++)
2905             for (int k = 0; k < cn; k++)
2906                 dst[k] = dst[k] + m[mid] * src[j*cn + k];
2907         if (borderType != BORDER_CONSTANT)
2908             for (; j < i + post_shift; j++, mid++)
2909             {
2910                 int src_idx = borderInterpolate(j, len, borderType);
2911                 for (int k = 0; k < cn; k++)
2912                     dst[k] = dst[k] + m[mid] * src[src_idx*cn + k];
2913             }
2914     }
2915     i *= cn;
2916     for (; i < (len - post_shift + 1)*cn; i++, src++, dst++)
2917     {
2918         *dst = m[pre_shift] * src[pre_shift*cn];
2919         for (int j = 0; j < pre_shift; j++)
2920             *dst = *dst + m[j] * src[j*cn] + m[j] * src[(n-1-j)*cn];
2921     }
2922     i /= cn;
2923     for (i -= pre_shift; i < len - pre_shift; i++, src += cn, dst += cn) // Points that fall right from border
2924     {
2925         for (int k = 0; k < cn; k++)
2926             dst[k] = m[0] * src[k];
2927         int j = 1;
2928         for (; j < len - i; j++)
2929             for (int k = 0; k < cn; k++)
2930                 dst[k] = dst[k] + m[j] * src[j*cn + k];
2931         if (borderType != BORDER_CONSTANT)// If BORDER_CONSTANT out of border values are equal to zero and could be skipped
2932             for (; j < n; j++)
2933             {
2934                 int src_idx = borderInterpolate(i + j, len, borderType) - i;
2935                 for (int k = 0; k < cn; k++)
2936                     dst[k] = dst[k] + m[j] * src[src_idx*cn + k];
2937             }
2938     }
2939 }
2940 template <>
2941 void hlineSmoothONa_yzy_a<uint8_t, ufixedpoint16>(const uint8_t* src, int cn, const ufixedpoint16* m, int n, ufixedpoint16* dst, int len, int borderType)
2942 {
2943     int pre_shift = n / 2;
2944     int post_shift = n - pre_shift;
2945     int i = 0;
2946     for (; i < min(pre_shift, len); i++, dst += cn) // Points that fall left from border
2947     {
2948         for (int k = 0; k < cn; k++)
2949             dst[k] = m[pre_shift - i] * src[k];
2950         if (borderType != BORDER_CONSTANT)// If BORDER_CONSTANT out of border values are equal to zero and could be skipped
2951             for (int j = i - pre_shift, mid = 0; j < 0; j++, mid++)
2952             {
2953                 int src_idx = borderInterpolate(j, len, borderType);
2954                 for (int k = 0; k < cn; k++)
2955                     dst[k] = dst[k] + m[mid] * src[src_idx*cn + k];
2956             }
2957         int j, mid;
2958         for (j = 1, mid = pre_shift - i + 1; j < min(i + post_shift, len); j++, mid++)
2959             for (int k = 0; k < cn; k++)
2960                 dst[k] = dst[k] + m[mid] * src[j*cn + k];
2961         if (borderType != BORDER_CONSTANT)
2962             for (; j < i + post_shift; j++, mid++)
2963             {
2964                 int src_idx = borderInterpolate(j, len, borderType);
2965                 for (int k = 0; k < cn; k++)
2966                     dst[k] = dst[k] + m[mid] * src[src_idx*cn + k];
2967             }
2968     }
2969     i *= cn;
2970     int lencn = (len - post_shift + 1)*cn;
2971     for (; i <= lencn - 16; i += 16, src += 16, dst += 16)
2972     {
2973         v_uint16x8 v_src00, v_src01, v_srcN00, v_srcN01;
2974
2975         v_uint16x8 v_mul = v_setall_u16(*((uint16_t*)(m + pre_shift)));
2976         v_expand(v_load(src + pre_shift * cn), v_src00, v_src01);
2977         v_uint16x8 v_res0 = v_src00 * v_mul;
2978         v_uint16x8 v_res1 = v_src01 * v_mul;
2979         for (int j = 0; j < pre_shift; j ++)
2980         {
2981             v_mul = v_setall_u16(*((uint16_t*)(m + j)));
2982             v_expand(v_load(src + j * cn), v_src00, v_src01);
2983             v_expand(v_load(src + (n - 1 - j)*cn), v_srcN00, v_srcN01);
2984             v_res0 += (v_src00 + v_srcN00) * v_mul;
2985             v_res1 += (v_src01 + v_srcN01) * v_mul;
2986         }
2987
2988         v_store((uint16_t*)dst, v_res0);
2989         v_store((uint16_t*)dst + 8, v_res1);
2990     }
2991     for (; i < lencn; i++, src++, dst++)
2992     {
2993         *dst = m[pre_shift] * src[pre_shift*cn];
2994         for (int j = 0; j < pre_shift; j++)
2995             *dst = *dst + m[j] * src[j*cn] + m[j] * src[(n - 1 - j)*cn];
2996     }
2997     i /= cn;
2998     for (i -= pre_shift; i < len - pre_shift; i++, src += cn, dst += cn) // Points that fall right from border
2999     {
3000         for (int k = 0; k < cn; k++)
3001             dst[k] = m[0] * src[k];
3002         int j = 1;
3003         for (; j < len - i; j++)
3004             for (int k = 0; k < cn; k++)
3005                 dst[k] = dst[k] + m[j] * src[j*cn + k];
3006         if (borderType != BORDER_CONSTANT)// If BORDER_CONSTANT out of border values are equal to zero and could be skipped
3007             for (; j < n; j++)
3008             {
3009                 int src_idx = borderInterpolate(i + j, len, borderType) - i;
3010                 for (int k = 0; k < cn; k++)
3011                     dst[k] = dst[k] + m[j] * src[src_idx*cn + k];
3012             }
3013     }
3014 }
3015 template <typename ET, typename FT>
3016 void vlineSmooth1N(const FT* const * src, const FT* m, int, ET* dst, int len)
3017 {
3018     const FT* src0 = src[0];
3019     for (int i = 0; i < len; i++)
3020         dst[i] = *m * src0[i];
3021 }
3022 template <>
3023 void vlineSmooth1N<uint8_t, ufixedpoint16>(const ufixedpoint16* const * src, const ufixedpoint16* m, int, uint8_t* dst, int len)
3024 {
3025     const ufixedpoint16* src0 = src[0];
3026     v_uint16x8 v_mul = v_setall_u16(*((uint16_t*)m));
3027 #if CV_SSE2
3028     v_uint16x8 v_1 = v_setall_u16(1);
3029     v_mul += v_mul;
3030 #endif
3031     int i = 0;
3032     for (; i <= len - 16; i += 16)
3033     {
3034         v_uint16x8 v_src0 = v_load((uint16_t*)src0 + i);
3035         v_uint16x8 v_src1 = v_load((uint16_t*)src0 + i + 8);
3036         v_uint8x16 v_res;
3037 #if CV_SSE2
3038         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),
3039                                      _mm_srli_epi16(_mm_add_epi16(v_1.val, _mm_mulhi_epu16(v_src1.val, v_mul.val)),1));
3040 #else
3041         v_uint32x4 v_res0, v_res1, v_res2, v_res3;
3042         v_mul_expand(v_src0, v_mul, v_res0, v_res1);
3043         v_mul_expand(v_src1, v_mul, v_res2, v_res3);
3044         v_res = v_pack(v_rshr_pack<16>(v_res0, v_res1), v_rshr_pack<16>(v_res2, v_res3));
3045 #endif
3046         v_store(dst + i, v_res);
3047     }
3048     for (; i < len; i++)
3049         dst[i] = m[0] * src0[i];
3050 }
3051 template <typename ET, typename FT>
3052 void vlineSmooth1N1(const FT* const * src, const FT*, int, ET* dst, int len)
3053 {
3054     const FT* src0 = src[0];
3055     for (int i = 0; i < len; i++)
3056         dst[i] = src0[i];
3057 }
3058 template <>
3059 void vlineSmooth1N1<uint8_t, ufixedpoint16>(const ufixedpoint16* const * src, const ufixedpoint16*, int, uint8_t* dst, int len)
3060 {
3061     const ufixedpoint16* src0 = src[0];
3062     int i = 0;
3063     for (; i <= len - 8; i += 8)
3064         v_rshr_pack_store<8>(dst + i, v_load((uint16_t*)(src0 + i)));
3065     for (; i < len; i++)
3066         dst[i] = src0[i];
3067 }
3068 template <typename ET, typename FT>
3069 void vlineSmooth3N(const FT* const * src, const FT* m, int, ET* dst, int len)
3070 {
3071     for (int i = 0; i < len; i++)
3072         dst[i] = m[0] * src[0][i] + m[1] * src[1][i] + m[2] * src[2][i];
3073 }
3074 template <>
3075 void vlineSmooth3N<uint8_t, ufixedpoint16>(const ufixedpoint16* const * src, const ufixedpoint16* m, int, uint8_t* dst, int len)
3076 {
3077     int i = 0;
3078     static const v_int16x8 v_128 = v_reinterpret_as_s16(v_setall_u16((uint16_t)1 << 15));
3079     v_int32x4 v_128_4 = v_setall_s32(128 << 16);
3080     if (len > 7)
3081     {
3082         ufixedpoint32 val[] = { (m[0] + m[1] + m[2]) * ufixedpoint16((uint8_t)128) };
3083         v_128_4 = v_setall_s32(*((int32_t*)val));
3084     }
3085     v_int16x8 v_mul01 = v_reinterpret_as_s16(v_setall_u32(*((uint32_t*)m)));
3086     v_int16x8 v_mul2 = v_reinterpret_as_s16(v_setall_u16(*((uint16_t*)(m + 2))));
3087     for (; i <= len - 32; i += 32)
3088     {
3089         v_int16x8 v_src00, v_src10, v_src01, v_src11, v_src02, v_src12, v_src03, v_src13;
3090         v_int16x8 v_tmp0, v_tmp1;
3091
3092         v_src00 = v_load((int16_t*)(src[0]) + i);
3093         v_src01 = v_load((int16_t*)(src[0]) + i + 8);
3094         v_src02 = v_load((int16_t*)(src[0]) + i + 16);
3095         v_src03 = v_load((int16_t*)(src[0]) + i + 24);
3096         v_src10 = v_load((int16_t*)(src[1]) + i);
3097         v_src11 = v_load((int16_t*)(src[1]) + i + 8);
3098         v_src12 = v_load((int16_t*)(src[1]) + i + 16);
3099         v_src13 = v_load((int16_t*)(src[1]) + i + 24);
3100         v_zip(v_add_wrap(v_src00, v_128), v_add_wrap(v_src10, v_128), v_tmp0, v_tmp1);
3101         v_int32x4 v_res0 = v_dotprod(v_tmp0, v_mul01);
3102         v_int32x4 v_res1 = v_dotprod(v_tmp1, v_mul01);
3103         v_zip(v_add_wrap(v_src01, v_128), v_add_wrap(v_src11, v_128), v_tmp0, v_tmp1);
3104         v_int32x4 v_res2 = v_dotprod(v_tmp0, v_mul01);
3105         v_int32x4 v_res3 = v_dotprod(v_tmp1, v_mul01);
3106         v_zip(v_add_wrap(v_src02, v_128), v_add_wrap(v_src12, v_128), v_tmp0, v_tmp1);
3107         v_int32x4 v_res4 = v_dotprod(v_tmp0, v_mul01);
3108         v_int32x4 v_res5 = v_dotprod(v_tmp1, v_mul01);
3109         v_zip(v_add_wrap(v_src03, v_128), v_add_wrap(v_src13, v_128), v_tmp0, v_tmp1);
3110         v_int32x4 v_res6 = v_dotprod(v_tmp0, v_mul01);
3111         v_int32x4 v_res7 = v_dotprod(v_tmp1, v_mul01);
3112
3113         v_int32x4 v_resj0, v_resj1;
3114         v_src00 = v_load((int16_t*)(src[2]) + i);
3115         v_src01 = v_load((int16_t*)(src[2]) + i + 8);
3116         v_src02 = v_load((int16_t*)(src[2]) + i + 16);
3117         v_src03 = v_load((int16_t*)(src[2]) + i + 24);
3118         v_mul_expand(v_add_wrap(v_src00, v_128), v_mul2, v_resj0, v_resj1);
3119         v_res0 += v_resj0;
3120         v_res1 += v_resj1;
3121         v_mul_expand(v_add_wrap(v_src01, v_128), v_mul2, v_resj0, v_resj1);
3122         v_res2 += v_resj0;
3123         v_res3 += v_resj1;
3124         v_mul_expand(v_add_wrap(v_src02, v_128), v_mul2, v_resj0, v_resj1);
3125         v_res4 += v_resj0;
3126         v_res5 += v_resj1;
3127         v_mul_expand(v_add_wrap(v_src03, v_128), v_mul2, v_resj0, v_resj1);
3128         v_res6 += v_resj0;
3129         v_res7 += v_resj1;
3130
3131         v_res0 += v_128_4;
3132         v_res1 += v_128_4;
3133         v_res2 += v_128_4;
3134         v_res3 += v_128_4;
3135         v_res4 += v_128_4;
3136         v_res5 += v_128_4;
3137         v_res6 += v_128_4;
3138         v_res7 += v_128_4;
3139
3140         v_store(dst + i     , v_pack(v_reinterpret_as_u16(v_rshr_pack<16>(v_res0, v_res1)),
3141                                      v_reinterpret_as_u16(v_rshr_pack<16>(v_res2, v_res3))));
3142         v_store(dst + i + 16, v_pack(v_reinterpret_as_u16(v_rshr_pack<16>(v_res4, v_res5)),
3143                                      v_reinterpret_as_u16(v_rshr_pack<16>(v_res6, v_res7))));
3144     }
3145     for (; i < len; i++)
3146         dst[i] = m[0] * src[0][i] + m[1] * src[1][i] + m[2] * src[2][i];
3147 }
3148 template <typename ET, typename FT>
3149 void vlineSmooth3N121(const FT* const * src, const FT*, int, ET* dst, int len)
3150 {
3151     for (int i = 0; i < len; i++)
3152         dst[i] = (FT::WT(src[0][i]) >> 2) + (FT::WT(src[2][i]) >> 2) + (FT::WT(src[1][i]) >> 1);
3153 }
3154 template <>
3155 void vlineSmooth3N121<uint8_t, ufixedpoint16>(const ufixedpoint16* const * src, const ufixedpoint16*, int, uint8_t* dst, int len)
3156 {
3157     int i = 0;
3158     for (; i <= len - 16; i += 16)
3159     {
3160         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;
3161         v_expand(v_load((uint16_t*)(src[0]) + i), v_src00, v_src01);
3162         v_expand(v_load((uint16_t*)(src[0]) + i + 8), v_src02, v_src03);
3163         v_expand(v_load((uint16_t*)(src[1]) + i), v_src10, v_src11);
3164         v_expand(v_load((uint16_t*)(src[1]) + i + 8), v_src12, v_src13);
3165         v_expand(v_load((uint16_t*)(src[2]) + i), v_src20, v_src21);
3166         v_expand(v_load((uint16_t*)(src[2]) + i + 8), v_src22, v_src23);
3167         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)),
3168                                 v_rshr_pack<10>(v_src02 + v_src22 + (v_src12 + v_src12), v_src03 + v_src23 + (v_src13 + v_src13))));
3169     }
3170     for (; i < len; i++)
3171         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;
3172 }
3173 template <typename ET, typename FT>
3174 void vlineSmooth5N(const FT* const * src, const FT* m, int, ET* dst, int len)
3175 {
3176     for (int i = 0; i < len; i++)
3177         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];
3178 }
3179 template <>
3180 void vlineSmooth5N<uint8_t, ufixedpoint16>(const ufixedpoint16* const * src, const ufixedpoint16* m, int, uint8_t* dst, int len)
3181 {
3182     int i = 0;
3183     static const v_int16x8 v_128 = v_reinterpret_as_s16(v_setall_u16((uint16_t)1 << 15));
3184     v_int32x4 v_128_4 = v_setall_s32(128 << 16);
3185     if (len > 7)
3186     {
3187         ufixedpoint32 val[] = { (m[0] + m[1] + m[2] + m[3] + m[4]) * ufixedpoint16((uint8_t)128) };
3188         v_128_4 = v_setall_s32(*((int32_t*)val));
3189     }
3190     v_int16x8 v_mul01 = v_reinterpret_as_s16(v_setall_u32(*((uint32_t*)m)));
3191     v_int16x8 v_mul23 = v_reinterpret_as_s16(v_setall_u32(*((uint32_t*)(m + 2))));
3192     v_int16x8 v_mul4 = v_reinterpret_as_s16(v_setall_u16(*((uint16_t*)(m + 4))));
3193     for (; i <= len - 32; i += 32)
3194     {
3195         v_int16x8 v_src00, v_src10, v_src01, v_src11, v_src02, v_src12, v_src03, v_src13;
3196         v_int16x8 v_tmp0, v_tmp1;
3197
3198         v_src00 = v_load((int16_t*)(src[0]) + i);
3199         v_src01 = v_load((int16_t*)(src[0]) + i + 8);
3200         v_src02 = v_load((int16_t*)(src[0]) + i + 16);
3201         v_src03 = v_load((int16_t*)(src[0]) + i + 24);
3202         v_src10 = v_load((int16_t*)(src[1]) + i);
3203         v_src11 = v_load((int16_t*)(src[1]) + i + 8);
3204         v_src12 = v_load((int16_t*)(src[1]) + i + 16);
3205         v_src13 = v_load((int16_t*)(src[1]) + i + 24);
3206         v_zip(v_add_wrap(v_src00, v_128), v_add_wrap(v_src10, v_128), v_tmp0, v_tmp1);
3207         v_int32x4 v_res0 = v_dotprod(v_tmp0, v_mul01);
3208         v_int32x4 v_res1 = v_dotprod(v_tmp1, v_mul01);
3209         v_zip(v_add_wrap(v_src01, v_128), v_add_wrap(v_src11, v_128), v_tmp0, v_tmp1);
3210         v_int32x4 v_res2 = v_dotprod(v_tmp0, v_mul01);
3211         v_int32x4 v_res3 = v_dotprod(v_tmp1, v_mul01);
3212         v_zip(v_add_wrap(v_src02, v_128), v_add_wrap(v_src12, v_128), v_tmp0, v_tmp1);
3213         v_int32x4 v_res4 = v_dotprod(v_tmp0, v_mul01);
3214         v_int32x4 v_res5 = v_dotprod(v_tmp1, v_mul01);
3215         v_zip(v_add_wrap(v_src03, v_128), v_add_wrap(v_src13, v_128), v_tmp0, v_tmp1);
3216         v_int32x4 v_res6 = v_dotprod(v_tmp0, v_mul01);
3217         v_int32x4 v_res7 = v_dotprod(v_tmp1, v_mul01);
3218
3219         v_src00 = v_load((int16_t*)(src[2]) + i);
3220         v_src01 = v_load((int16_t*)(src[2]) + i + 8);
3221         v_src02 = v_load((int16_t*)(src[2]) + i + 16);
3222         v_src03 = v_load((int16_t*)(src[2]) + i + 24);
3223         v_src10 = v_load((int16_t*)(src[3]) + i);
3224         v_src11 = v_load((int16_t*)(src[3]) + i + 8);
3225         v_src12 = v_load((int16_t*)(src[3]) + i + 16);
3226         v_src13 = v_load((int16_t*)(src[3]) + i + 24);
3227         v_zip(v_add_wrap(v_src00, v_128), v_add_wrap(v_src10, v_128), v_tmp0, v_tmp1);
3228         v_res0 += v_dotprod(v_tmp0, v_mul23);
3229         v_res1 += v_dotprod(v_tmp1, v_mul23);
3230         v_zip(v_add_wrap(v_src01, v_128), v_add_wrap(v_src11, v_128), v_tmp0, v_tmp1);
3231         v_res2 += v_dotprod(v_tmp0, v_mul23);
3232         v_res3 += v_dotprod(v_tmp1, v_mul23);
3233         v_zip(v_add_wrap(v_src02, v_128), v_add_wrap(v_src12, v_128), v_tmp0, v_tmp1);
3234         v_res4 += v_dotprod(v_tmp0, v_mul23);
3235         v_res5 += v_dotprod(v_tmp1, v_mul23);
3236         v_zip(v_add_wrap(v_src03, v_128), v_add_wrap(v_src13, v_128), v_tmp0, v_tmp1);
3237         v_res6 += v_dotprod(v_tmp0, v_mul23);
3238         v_res7 += v_dotprod(v_tmp1, v_mul23);
3239
3240         v_int32x4 v_resj0, v_resj1;
3241         v_src00 = v_load((int16_t*)(src[4]) + i);
3242         v_src01 = v_load((int16_t*)(src[4]) + i + 8);
3243         v_src02 = v_load((int16_t*)(src[4]) + i + 16);
3244         v_src03 = v_load((int16_t*)(src[4]) + i + 24);
3245         v_mul_expand(v_add_wrap(v_src00, v_128), v_mul4, v_resj0, v_resj1);
3246         v_res0 += v_resj0;
3247         v_res1 += v_resj1;
3248         v_mul_expand(v_add_wrap(v_src01, v_128), v_mul4, v_resj0, v_resj1);
3249         v_res2 += v_resj0;
3250         v_res3 += v_resj1;
3251         v_mul_expand(v_add_wrap(v_src02, v_128), v_mul4, v_resj0, v_resj1);
3252         v_res4 += v_resj0;
3253         v_res5 += v_resj1;
3254         v_mul_expand(v_add_wrap(v_src03, v_128), v_mul4, v_resj0, v_resj1);
3255         v_res6 += v_resj0;
3256         v_res7 += v_resj1;
3257
3258         v_res0 += v_128_4;
3259         v_res1 += v_128_4;
3260         v_res2 += v_128_4;
3261         v_res3 += v_128_4;
3262         v_res4 += v_128_4;
3263         v_res5 += v_128_4;
3264         v_res6 += v_128_4;
3265         v_res7 += v_128_4;
3266
3267         v_store(dst + i     , v_pack(v_reinterpret_as_u16(v_rshr_pack<16>(v_res0, v_res1)),
3268                                      v_reinterpret_as_u16(v_rshr_pack<16>(v_res2, v_res3))));
3269         v_store(dst + i + 16, v_pack(v_reinterpret_as_u16(v_rshr_pack<16>(v_res4, v_res5)),
3270                                      v_reinterpret_as_u16(v_rshr_pack<16>(v_res6, v_res7))));
3271     }
3272     for (; i < len; i++)
3273         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];
3274 }
3275 template <typename ET, typename FT>
3276 void vlineSmooth5N14641(const FT* const * src, const FT*, int, ET* dst, int len)
3277 {
3278     for (int i = 0; i < len; i++)
3279         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;
3280 }
3281 template <>
3282 void vlineSmooth5N14641<uint8_t, ufixedpoint16>(const ufixedpoint16* const * src, const ufixedpoint16*, int, uint8_t* dst, int len)
3283 {
3284     int i = 0;
3285     v_uint32x4 v_6 = v_setall_u32(6);
3286     for (; i <= len - 16; i += 16)
3287     {
3288         v_uint32x4 v_src00, v_src10, v_src20, v_src30, v_src40;
3289         v_uint32x4 v_src01, v_src11, v_src21, v_src31, v_src41;
3290         v_uint32x4 v_src02, v_src12, v_src22, v_src32, v_src42;
3291         v_uint32x4 v_src03, v_src13, v_src23, v_src33, v_src43;
3292         v_expand(v_load((uint16_t*)(src[0]) + i), v_src00, v_src01);
3293         v_expand(v_load((uint16_t*)(src[0]) + i + 8), v_src02, v_src03);
3294         v_expand(v_load((uint16_t*)(src[1]) + i), v_src10, v_src11);
3295         v_expand(v_load((uint16_t*)(src[1]) + i + 8), v_src12, v_src13);
3296         v_expand(v_load((uint16_t*)(src[2]) + i), v_src20, v_src21);
3297         v_expand(v_load((uint16_t*)(src[2]) + i + 8), v_src22, v_src23);
3298         v_expand(v_load((uint16_t*)(src[3]) + i), v_src30, v_src31);
3299         v_expand(v_load((uint16_t*)(src[3]) + i + 8), v_src32, v_src33);
3300         v_expand(v_load((uint16_t*)(src[4]) + i), v_src40, v_src41);
3301         v_expand(v_load((uint16_t*)(src[4]) + i + 8), v_src42, v_src43);
3302         v_store(dst + i, v_pack(v_rshr_pack<12>(v_src20*v_6 + ((v_src10 + v_src30) << 2) + v_src00 + v_src40,
3303                                                 v_src21*v_6 + ((v_src11 + v_src31) << 2) + v_src01 + v_src41),
3304                                 v_rshr_pack<12>(v_src22*v_6 + ((v_src12 + v_src32) << 2) + v_src02 + v_src42,
3305                                                 v_src23*v_6 + ((v_src13 + v_src33) << 2) + v_src03 + v_src43)));
3306     }
3307     for (; i < len; i++)
3308         dst[i] = ((uint32_t)(((uint16_t*)(src[2]))[i]) * 6 +
3309                   (((uint32_t)(((uint16_t*)(src[1]))[i]) + (uint32_t)(((uint16_t*)(src[3]))[i])) << 2) +
3310                   (uint32_t)(((uint16_t*)(src[0]))[i]) + (uint32_t)(((uint16_t*)(src[4]))[i]) + (1 << 11)) >> 12;
3311 }
3312 template <typename ET, typename FT>
3313 void vlineSmooth(const FT* const * src, const FT* m, int n, ET* dst, int len)
3314 {
3315     for (int i = 0; i < len; i++)
3316     {
3317         typename FT::WT val = m[0] * src[0][i];
3318         for (int j = 1; j < n; j++)
3319             val = val + m[j] * src[j][i];
3320         dst[i] = val;
3321     }
3322 }
3323 template <>
3324 void vlineSmooth<uint8_t, ufixedpoint16>(const ufixedpoint16* const * src, const ufixedpoint16* m, int n, uint8_t* dst, int len)
3325 {
3326     int i = 0;
3327     static const v_int16x8 v_128 = v_reinterpret_as_s16(v_setall_u16((uint16_t)1 << 15));
3328     v_int32x4 v_128_4 = v_setall_s32(128 << 16);
3329     if (len > 7)
3330     {
3331         ufixedpoint16 msum = m[0] + m[1];
3332         for (int j = 2; j < n; j++)
3333             msum = msum + m[j];
3334         ufixedpoint32 val[] = { msum * ufixedpoint16((uint8_t)128) };
3335         v_128_4 = v_setall_s32(*((int32_t*)val));
3336     }
3337     for (; i <= len - 32; i += 32)
3338     {
3339         v_int16x8 v_src00, v_src10, v_src01, v_src11, v_src02, v_src12, v_src03, v_src13;
3340         v_int16x8 v_tmp0, v_tmp1;
3341
3342         v_int16x8 v_mul = v_reinterpret_as_s16(v_setall_u32(*((uint32_t*)m)));
3343
3344         v_src00 = v_load((int16_t*)(src[0]) + i);
3345         v_src01 = v_load((int16_t*)(src[0]) + i + 8);
3346         v_src02 = v_load((int16_t*)(src[0]) + i + 16);
3347         v_src03 = v_load((int16_t*)(src[0]) + i + 24);
3348         v_src10 = v_load((int16_t*)(src[1]) + i);
3349         v_src11 = v_load((int16_t*)(src[1]) + i + 8);
3350         v_src12 = v_load((int16_t*)(src[1]) + i + 16);
3351         v_src13 = v_load((int16_t*)(src[1]) + i + 24);
3352         v_zip(v_add_wrap(v_src00, v_128), v_add_wrap(v_src10, v_128), v_tmp0, v_tmp1);
3353         v_int32x4 v_res0 = v_dotprod(v_tmp0, v_mul);
3354         v_int32x4 v_res1 = v_dotprod(v_tmp1, v_mul);
3355         v_zip(v_add_wrap(v_src01, v_128), v_add_wrap(v_src11, v_128), v_tmp0, v_tmp1);
3356         v_int32x4 v_res2 = v_dotprod(v_tmp0, v_mul);
3357         v_int32x4 v_res3 = v_dotprod(v_tmp1, v_mul);
3358         v_zip(v_add_wrap(v_src02, v_128), v_add_wrap(v_src12, v_128), v_tmp0, v_tmp1);
3359         v_int32x4 v_res4 = v_dotprod(v_tmp0, v_mul);
3360         v_int32x4 v_res5 = v_dotprod(v_tmp1, v_mul);
3361         v_zip(v_add_wrap(v_src03, v_128), v_add_wrap(v_src13, v_128), v_tmp0, v_tmp1);
3362         v_int32x4 v_res6 = v_dotprod(v_tmp0, v_mul);
3363         v_int32x4 v_res7 = v_dotprod(v_tmp1, v_mul);
3364
3365         int j = 2;
3366         for (; j < n - 1; j+=2)
3367         {
3368             v_mul = v_reinterpret_as_s16(v_setall_u32(*((uint32_t*)(m+j))));
3369
3370             v_src00 = v_load((int16_t*)(src[j]) + i);
3371             v_src01 = v_load((int16_t*)(src[j]) + i + 8);
3372             v_src02 = v_load((int16_t*)(src[j]) + i + 16);
3373             v_src03 = v_load((int16_t*)(src[j]) + i + 24);
3374             v_src10 = v_load((int16_t*)(src[j+1]) + i);
3375             v_src11 = v_load((int16_t*)(src[j+1]) + i + 8);
3376             v_src12 = v_load((int16_t*)(src[j+1]) + i + 16);
3377             v_src13 = v_load((int16_t*)(src[j+1]) + i + 24);
3378             v_zip(v_add_wrap(v_src00, v_128), v_add_wrap(v_src10, v_128), v_tmp0, v_tmp1);
3379             v_res0 += v_dotprod(v_tmp0, v_mul);
3380             v_res1 += v_dotprod(v_tmp1, v_mul);
3381             v_zip(v_add_wrap(v_src01, v_128), v_add_wrap(v_src11, v_128), v_tmp0, v_tmp1);
3382             v_res2 += v_dotprod(v_tmp0, v_mul);
3383             v_res3 += v_dotprod(v_tmp1, v_mul);
3384             v_zip(v_add_wrap(v_src02, v_128), v_add_wrap(v_src12, v_128), v_tmp0, v_tmp1);
3385             v_res4 += v_dotprod(v_tmp0, v_mul);
3386             v_res5 += v_dotprod(v_tmp1, v_mul);
3387             v_zip(v_add_wrap(v_src03, v_128), v_add_wrap(v_src13, v_128), v_tmp0, v_tmp1);
3388             v_res6 += v_dotprod(v_tmp0, v_mul);
3389             v_res7 += v_dotprod(v_tmp1, v_mul);
3390         }
3391         if(j < n)
3392         {
3393             v_int32x4 v_resj0, v_resj1;
3394             v_mul = v_reinterpret_as_s16(v_setall_u16(*((uint16_t*)(m + j))));
3395             v_src00 = v_load((int16_t*)(src[j]) + i);
3396             v_src01 = v_load((int16_t*)(src[j]) + i + 8);
3397             v_src02 = v_load((int16_t*)(src[j]) + i + 16);
3398             v_src03 = v_load((int16_t*)(src[j]) + i + 24);
3399             v_mul_expand(v_add_wrap(v_src00, v_128), v_mul, v_resj0, v_resj1);
3400             v_res0 += v_resj0;
3401             v_res1 += v_resj1;
3402             v_mul_expand(v_add_wrap(v_src01, v_128), v_mul, v_resj0, v_resj1);
3403             v_res2 += v_resj0;
3404             v_res3 += v_resj1;
3405             v_mul_expand(v_add_wrap(v_src02, v_128), v_mul, v_resj0, v_resj1);
3406             v_res4 += v_resj0;
3407             v_res5 += v_resj1;
3408             v_mul_expand(v_add_wrap(v_src03, v_128), v_mul, v_resj0, v_resj1);
3409             v_res6 += v_resj0;
3410             v_res7 += v_resj1;
3411         }
3412         v_res0 += v_128_4;
3413         v_res1 += v_128_4;
3414         v_res2 += v_128_4;
3415         v_res3 += v_128_4;
3416         v_res4 += v_128_4;
3417         v_res5 += v_128_4;
3418         v_res6 += v_128_4;
3419         v_res7 += v_128_4;
3420
3421         v_store(dst + i     , v_pack(v_reinterpret_as_u16(v_rshr_pack<16>(v_res0, v_res1)),
3422                                      v_reinterpret_as_u16(v_rshr_pack<16>(v_res2, v_res3))));
3423         v_store(dst + i + 16, v_pack(v_reinterpret_as_u16(v_rshr_pack<16>(v_res4, v_res5)),
3424                                      v_reinterpret_as_u16(v_rshr_pack<16>(v_res6, v_res7))));
3425     }
3426     for (; i < len; i++)
3427     {
3428         ufixedpoint32 val = m[0] * src[0][i];
3429         for (int j = 1; j < n; j++)
3430         {
3431             val = val + m[j] * src[j][i];
3432         }
3433         dst[i] = val;
3434     }
3435 }
3436 template <typename ET, typename FT>
3437 void vlineSmoothONa_yzy_a(const FT* const * src, const FT* m, int n, ET* dst, int len)
3438 {
3439     int pre_shift = n / 2;
3440     for (int i = 0; i < len; i++)
3441     {
3442         typename FT::WT val = m[pre_shift] * src[pre_shift][i];
3443         for (int j = 0; j < pre_shift; j++)
3444             val = val + m[j] * src[j][i] + m[j] * src[(n - 1 - j)][i];
3445         dst[i] = val;
3446     }
3447 }
3448 template <>
3449 void vlineSmoothONa_yzy_a<uint8_t, ufixedpoint16>(const ufixedpoint16* const * src, const ufixedpoint16* m, int n, uint8_t* dst, int len)
3450 {
3451     int pre_shift = n / 2;
3452     int i = 0;
3453     static const v_int16x8 v_128 = v_reinterpret_as_s16(v_setall_u16((uint16_t)1 << 15));
3454     v_int32x4 v_128_4 = v_setall_s32(128 << 16);
3455     if (len > 7)
3456     {
3457         ufixedpoint16 msum = m[0] + m[pre_shift] + m[n - 1];
3458         for (int j = 1; j < pre_shift; j++)
3459             msum = msum + m[j] + m[n - 1 - j];
3460         ufixedpoint32 val[] = { msum * ufixedpoint16((uint8_t)128) };
3461         v_128_4 = v_setall_s32(*((int32_t*)val));
3462     }
3463     for (; i <= len - 32; i += 32)
3464     {
3465         v_int16x8 v_src00, v_src10, v_src20, v_src30, v_src01, v_src11, v_src21, v_src31;
3466         v_int32x4 v_res0, v_res1, v_res2, v_res3, v_res4, v_res5, v_res6, v_res7;
3467         v_int16x8 v_tmp0, v_tmp1, v_tmp2, v_tmp3, v_tmp4, v_tmp5, v_tmp6, v_tmp7;
3468
3469         v_int16x8 v_mul = v_reinterpret_as_s16(v_setall_u16(*((uint16_t*)(m + pre_shift))));
3470         v_src00 = v_load((int16_t*)(src[pre_shift]) + i);
3471         v_src10 = v_load((int16_t*)(src[pre_shift]) + i + 8);
3472         v_src20 = v_load((int16_t*)(src[pre_shift]) + i + 16);
3473         v_src30 = v_load((int16_t*)(src[pre_shift]) + i + 24);
3474         v_mul_expand(v_add_wrap(v_src00, v_128), v_mul, v_res0, v_res1);
3475         v_mul_expand(v_add_wrap(v_src10, v_128), v_mul, v_res2, v_res3);
3476         v_mul_expand(v_add_wrap(v_src20, v_128), v_mul, v_res4, v_res5);
3477         v_mul_expand(v_add_wrap(v_src30, v_128), v_mul, v_res6, v_res7);
3478
3479         int j = 0;
3480         for (; j < pre_shift; j++)
3481         {
3482             v_mul = v_reinterpret_as_s16(v_setall_u16(*((uint16_t*)(m + j))));
3483
3484             v_src00 = v_load((int16_t*)(src[j]) + i);
3485             v_src10 = v_load((int16_t*)(src[j]) + i + 8);
3486             v_src20 = v_load((int16_t*)(src[j]) + i + 16);
3487             v_src30 = v_load((int16_t*)(src[j]) + i + 24);
3488             v_src01 = v_load((int16_t*)(src[n - 1 - j]) + i);
3489             v_src11 = v_load((int16_t*)(src[n - 1 - j]) + i + 8);
3490             v_src21 = v_load((int16_t*)(src[n - 1 - j]) + i + 16);
3491             v_src31 = v_load((int16_t*)(src[n - 1 - j]) + i + 24);
3492             v_zip(v_add_wrap(v_src00, v_128), v_add_wrap(v_src01, v_128), v_tmp0, v_tmp1);
3493             v_res0 += v_dotprod(v_tmp0, v_mul);
3494             v_res1 += v_dotprod(v_tmp1, v_mul);
3495             v_zip(v_add_wrap(v_src10, v_128), v_add_wrap(v_src11, v_128), v_tmp2, v_tmp3);
3496             v_res2 += v_dotprod(v_tmp2, v_mul);
3497             v_res3 += v_dotprod(v_tmp3, v_mul);
3498             v_zip(v_add_wrap(v_src20, v_128), v_add_wrap(v_src21, v_128), v_tmp4, v_tmp5);
3499             v_res4 += v_dotprod(v_tmp4, v_mul);
3500             v_res5 += v_dotprod(v_tmp5, v_mul);
3501             v_zip(v_add_wrap(v_src30, v_128), v_add_wrap(v_src31, v_128), v_tmp6, v_tmp7);
3502             v_res6 += v_dotprod(v_tmp6, v_mul);
3503             v_res7 += v_dotprod(v_tmp7, v_mul);
3504         }
3505
3506         v_res0 += v_128_4;
3507         v_res1 += v_128_4;
3508         v_res2 += v_128_4;
3509         v_res3 += v_128_4;
3510         v_res4 += v_128_4;
3511         v_res5 += v_128_4;
3512         v_res6 += v_128_4;
3513         v_res7 += v_128_4;
3514
3515         v_store(dst + i     , v_pack(v_reinterpret_as_u16(v_rshr_pack<16>(v_res0, v_res1)),
3516                                      v_reinterpret_as_u16(v_rshr_pack<16>(v_res2, v_res3))));
3517         v_store(dst + i + 16, v_pack(v_reinterpret_as_u16(v_rshr_pack<16>(v_res4, v_res5)),
3518                                      v_reinterpret_as_u16(v_rshr_pack<16>(v_res6, v_res7))));
3519     }
3520     for (; i < len; i++)
3521     {
3522         ufixedpoint32 val = m[0] * src[0][i];
3523         for (int j = 1; j < n; j++)
3524         {
3525             val = val + m[j] * src[j][i];
3526         }
3527         dst[i] = val;
3528     }
3529 }
3530 template <typename ET, typename FT>
3531 class fixedSmoothInvoker : public ParallelLoopBody
3532 {
3533 public:
3534     fixedSmoothInvoker(const ET* _src, size_t _src_stride, ET* _dst, size_t _dst_stride,
3535                        int _width, int _height, int _cn, const FT* _kx, int _kxlen, const FT* _ky, int _kylen, int _borderType) : ParallelLoopBody(),
3536                        src(_src), dst(_dst), src_stride(_src_stride), dst_stride(_dst_stride),
3537                        width(_width), height(_height), cn(_cn), kx(_kx), ky(_ky), kxlen(_kxlen), kylen(_kylen), borderType(_borderType)
3538     {
3539         if (kxlen == 1)
3540         {
3541             if (kx[0] == FT::one())
3542                 hlineSmoothFunc = hlineSmooth1N1;
3543             else
3544                 hlineSmoothFunc = hlineSmooth1N;
3545         }
3546         else if (kxlen == 3)
3547         {
3548             if (kx[0] == (FT::one()>>2)&&kx[1] == (FT::one()>>1)&&kx[2] == (FT::one()>>2))
3549                 hlineSmoothFunc = hlineSmooth3N121;
3550             else if ((kx[0] - kx[2]).isZero())
3551                     hlineSmoothFunc = hlineSmooth3Naba;
3552             else
3553                 hlineSmoothFunc = hlineSmooth3N;
3554         }
3555         else if (kxlen == 5)
3556         {
3557             if (kx[2] == (FT::one()*(uint8_t)3>>3) &&
3558                 kx[1] == (FT::one()>>2) && kx[3] == (FT::one()>>2) &&
3559                 kx[0] == (FT::one()>>4) && kx[4] == (FT::one()>>4))
3560                 hlineSmoothFunc = hlineSmooth5N14641;
3561             else if (kx[0] == kx[4] && kx[1] == kx[3])
3562                 hlineSmoothFunc = hlineSmooth5Nabcba;
3563             else
3564                 hlineSmoothFunc = hlineSmooth5N;
3565         }
3566         else if (kxlen % 2 == 1)
3567         {
3568             hlineSmoothFunc = hlineSmoothONa_yzy_a;
3569             for (int i = 0; i < kxlen / 2; i++)
3570                 if (!(kx[i] == kx[kxlen - 1 - i]))
3571                 {
3572                     hlineSmoothFunc = hlineSmooth;
3573                     break;
3574                 }
3575         }
3576         else
3577             hlineSmoothFunc = hlineSmooth;
3578         if (kylen == 1)
3579         {
3580             if (ky[0] == FT::one())
3581                 vlineSmoothFunc = vlineSmooth1N1;
3582             else
3583                 vlineSmoothFunc = vlineSmooth1N;
3584         }
3585         else if (kylen == 3)
3586         {
3587             if (ky[0] == (FT::one() >> 2) && ky[1] == (FT::one() >> 1) && ky[2] == (FT::one() >> 2))
3588                 vlineSmoothFunc = vlineSmooth3N121;
3589             else
3590                 vlineSmoothFunc = vlineSmooth3N;
3591         }
3592         else if (kylen == 5)
3593         {
3594             if (ky[2] == (FT::one() * (uint8_t)3 >> 3) &&
3595                 ky[1] == (FT::one() >> 2) && ky[3] == (FT::one() >> 2) &&
3596                 ky[0] == (FT::one() >> 4) && ky[4] == (FT::one() >> 4))
3597                 vlineSmoothFunc = vlineSmooth5N14641;
3598             else
3599                 vlineSmoothFunc = vlineSmooth5N;
3600         }
3601         else if (kylen % 2 == 1)
3602         {
3603             vlineSmoothFunc = vlineSmoothONa_yzy_a;
3604             for (int i = 0; i < kylen / 2; i++)
3605                 if (!(ky[i] == ky[kylen - 1 - i]))
3606                 {
3607                     vlineSmoothFunc = vlineSmooth;
3608                     break;
3609                 }
3610         }
3611         else
3612             vlineSmoothFunc = vlineSmooth;
3613     }
3614     virtual void operator() (const Range& range) const CV_OVERRIDE
3615     {
3616         AutoBuffer<FT> _buf(width*cn*kylen);
3617         FT* buf = _buf.data();
3618         AutoBuffer<FT*> _ptrs(kylen*2);
3619         FT** ptrs = _ptrs.data();
3620
3621         if (kylen == 1)
3622         {
3623             ptrs[0] = buf;
3624             for (int i = range.start; i < range.end; i++)
3625             {
3626                 hlineSmoothFunc(src + i * src_stride, cn, kx, kxlen, ptrs[0], width, borderType);
3627                 vlineSmoothFunc(ptrs, ky, kylen, dst + i * dst_stride, width*cn);
3628             }
3629         }
3630         else if (borderType != BORDER_CONSTANT)// If BORDER_CONSTANT out of border values are equal to zero and could be skipped
3631         {
3632             int pre_shift = kylen / 2;
3633             int post_shift = kylen - pre_shift - 1;
3634             // First line evaluation
3635             int idst = range.start;
3636             int ifrom = max(0, idst - pre_shift);
3637             int ito = idst + post_shift + 1;
3638             int i = ifrom;
3639             int bufline = 0;
3640             for (; i < min(ito, height); i++, bufline++)
3641             {
3642                 ptrs[bufline+kylen] = ptrs[bufline] = buf + bufline * width*cn;
3643                 hlineSmoothFunc(src + i * src_stride, cn, kx, kxlen, ptrs[bufline], width, borderType);
3644             }
3645             for (; i < ito; i++, bufline++)
3646             {
3647                 int src_idx = borderInterpolate(i, height, borderType);
3648                 if (src_idx < ifrom)
3649                 {
3650                     ptrs[bufline + kylen] = ptrs[bufline] = buf + bufline * width*cn;
3651                     hlineSmoothFunc(src + src_idx * src_stride, cn, kx, kxlen, ptrs[bufline], width, borderType);
3652                 }
3653                 else
3654                 {
3655                     ptrs[bufline + kylen] = ptrs[bufline] = ptrs[src_idx - ifrom];
3656                 }
3657             }
3658             for (int j = idst - pre_shift; j < 0; j++)
3659             {
3660                 int src_idx = borderInterpolate(j, height, borderType);
3661                 if (src_idx >= ito)
3662                 {
3663                     ptrs[2*kylen + j] = ptrs[kylen + j] = buf + (kylen + j) * width*cn;
3664                     hlineSmoothFunc(src + src_idx * src_stride, cn, kx, kxlen, ptrs[kylen + j], width, borderType);
3665                 }
3666                 else
3667                 {
3668                     ptrs[2*kylen + j] = ptrs[kylen + j] = ptrs[src_idx];
3669                 }
3670             }
3671             vlineSmoothFunc(ptrs + bufline, ky, kylen, dst + idst*dst_stride, width*cn); idst++;
3672
3673             // border mode dependent part evaluation
3674             // i points to last src row to evaluate in convolution
3675             bufline %= kylen; ito = min(height, range.end + post_shift);
3676             for (; i < min(kylen, ito); i++, idst++)
3677             {
3678                 ptrs[bufline + kylen] = ptrs[bufline] = buf + bufline * width*cn;
3679                 hlineSmoothFunc(src + i * src_stride, cn, kx, kxlen, ptrs[bufline], width, borderType);
3680                 bufline = (bufline + 1) % kylen;
3681                 vlineSmoothFunc(ptrs + bufline, ky, kylen, dst + idst*dst_stride, width*cn);
3682             }
3683             // Points inside the border
3684             for (; i < ito; i++, idst++)
3685             {
3686                 hlineSmoothFunc(src + i * src_stride, cn, kx, kxlen, ptrs[bufline], width, borderType);
3687                 bufline = (bufline + 1) % kylen;
3688                 vlineSmoothFunc(ptrs + bufline, ky, kylen, dst + idst*dst_stride, width*cn);
3689             }
3690             // Points that could fall below border
3691             for (; i < range.end + post_shift; i++, idst++)
3692             {
3693                 int src_idx = borderInterpolate(i, height, borderType);
3694                 if ((i - src_idx) > kylen)
3695                     hlineSmoothFunc(src + src_idx * src_stride, cn, kx, kxlen, ptrs[bufline], width, borderType);
3696                 else
3697                     ptrs[bufline + kylen] = ptrs[bufline] = ptrs[(bufline + kylen - (i - src_idx)) % kylen];
3698                 bufline = (bufline + 1) % kylen;
3699                 vlineSmoothFunc(ptrs + bufline, ky, kylen, dst + idst*dst_stride, width*cn);
3700             }
3701         }
3702         else
3703         {
3704             int pre_shift = kylen / 2;
3705             int post_shift = kylen - pre_shift - 1;
3706             // First line evaluation
3707             int idst = range.start;
3708             int ifrom = idst - pre_shift;
3709             int ito = min(idst + post_shift + 1, height);
3710             int i = max(0, ifrom);
3711             int bufline = 0;
3712             for (; i < ito; i++, bufline++)
3713             {
3714                 ptrs[bufline + kylen] = ptrs[bufline] = buf + bufline * width*cn;
3715                 hlineSmoothFunc(src + i * src_stride, cn, kx, kxlen, ptrs[bufline], width, borderType);
3716             }
3717
3718             if (bufline == 1)
3719                 vlineSmooth1N(ptrs, ky - min(ifrom, 0), bufline, dst + idst*dst_stride, width*cn);
3720             else if (bufline == 3)
3721                 vlineSmooth3N(ptrs, ky - min(ifrom, 0), bufline, dst + idst*dst_stride, width*cn);
3722             else if (bufline == 5)
3723                 vlineSmooth5N(ptrs, ky - min(ifrom, 0), bufline, dst + idst*dst_stride, width*cn);
3724             else
3725                 vlineSmooth(ptrs, ky - min(ifrom, 0), bufline, dst + idst*dst_stride, width*cn);
3726             idst++;
3727
3728             // border mode dependent part evaluation
3729             // i points to last src row to evaluate in convolution
3730             bufline %= kylen; ito = min(height, range.end + post_shift);
3731             for (; i < min(kylen, ito); i++, idst++)
3732             {
3733                 ptrs[bufline + kylen] = ptrs[bufline] = buf + bufline * width*cn;
3734                 hlineSmoothFunc(src + i * src_stride, cn, kx, kxlen, ptrs[bufline], width, borderType);
3735                 bufline++;
3736                 if (bufline == 3)
3737                     vlineSmooth3N(ptrs, ky + kylen - bufline, i + 1, dst + idst*dst_stride, width*cn);
3738                 else if (bufline == 5)
3739                     vlineSmooth5N(ptrs, ky + kylen - bufline, i + 1, dst + idst*dst_stride, width*cn);
3740                 else
3741                     vlineSmooth(ptrs, ky + kylen - bufline, i + 1, dst + idst*dst_stride, width*cn);
3742                 bufline %= kylen;
3743             }
3744             // Points inside the border
3745             if (i - max(0, ifrom) >= kylen)
3746             {
3747                 for (; i < ito; i++, idst++)
3748                 {
3749                     hlineSmoothFunc(src + i * src_stride, cn, kx, kxlen, ptrs[bufline], width, borderType);
3750                     bufline = (bufline + 1) % kylen;
3751                     vlineSmoothFunc(ptrs + bufline, ky, kylen, dst + idst*dst_stride, width*cn);
3752                 }
3753
3754                 // Points that could fall below border
3755                 // i points to first src row to evaluate in convolution
3756                 bufline = (bufline + 1) % kylen;
3757                 for (i = idst - pre_shift; i < range.end - pre_shift; i++, idst++, bufline++)
3758                     if (height - i == 3)
3759                         vlineSmooth3N(ptrs + bufline, ky, height - i, dst + idst*dst_stride, width*cn);
3760                     else if (height - i == 5)
3761                         vlineSmooth5N(ptrs + bufline, ky, height - i, dst + idst*dst_stride, width*cn);
3762                     else
3763                         vlineSmooth(ptrs + bufline, ky, height - i, dst + idst*dst_stride, width*cn);
3764             }
3765             else
3766             {
3767                 // i points to first src row to evaluate in convolution
3768                 for (i = idst - pre_shift; i < min(range.end - pre_shift, 0); i++, idst++)
3769                     if (height == 3)
3770                         vlineSmooth3N(ptrs, ky - i, height, dst + idst*dst_stride, width*cn);
3771                     else if (height == 5)
3772                         vlineSmooth5N(ptrs, ky - i, height, dst + idst*dst_stride, width*cn);
3773                     else
3774                         vlineSmooth(ptrs, ky - i, height, dst + idst*dst_stride, width*cn);
3775                 for (; i < range.end - pre_shift; i++, idst++)
3776                     if (height - i == 3)
3777                         vlineSmooth3N(ptrs + i - max(0, ifrom), ky, height - i, dst + idst*dst_stride, width*cn);
3778                     else if (height - i == 5)
3779                         vlineSmooth5N(ptrs + i - max(0, ifrom), ky, height - i, dst + idst*dst_stride, width*cn);
3780                     else
3781                         vlineSmooth(ptrs + i - max(0, ifrom), ky, height - i, dst + idst*dst_stride, width*cn);
3782             }
3783         }
3784     }
3785 private:
3786     const ET* src;
3787     ET* dst;
3788     size_t src_stride, dst_stride;
3789     int width, height, cn;
3790     const FT *kx, *ky;
3791     int kxlen, kylen;
3792     int borderType;
3793     void(*hlineSmoothFunc)(const ET* src, int cn, const FT* m, int n, FT* dst, int len, int borderType);
3794     void(*vlineSmoothFunc)(const FT* const * src, const FT* m, int n, ET* dst, int len);
3795
3796     fixedSmoothInvoker(const fixedSmoothInvoker&);
3797     fixedSmoothInvoker& operator=(const fixedSmoothInvoker&);
3798 };
3799
3800 static void getGaussianKernel(int n, double sigma, int ktype, Mat& res) { res = getGaussianKernel(n, sigma, ktype); }
3801 template <typename T> static void getGaussianKernel(int n, double sigma, int, std::vector<T>& res) { res = getFixedpointGaussianKernel<T>(n, sigma); }
3802
3803 template <typename T>
3804 static void createGaussianKernels( T & kx, T & ky, int type, Size &ksize,
3805                                    double sigma1, double sigma2 )
3806 {
3807     int depth = CV_MAT_DEPTH(type);
3808     if( sigma2 <= 0 )
3809         sigma2 = sigma1;
3810
3811     // automatic detection of kernel size from sigma
3812     if( ksize.width <= 0 && sigma1 > 0 )
3813         ksize.width = cvRound(sigma1*(depth == CV_8U ? 3 : 4)*2 + 1)|1;
3814     if( ksize.height <= 0 && sigma2 > 0 )
3815         ksize.height = cvRound(sigma2*(depth == CV_8U ? 3 : 4)*2 + 1)|1;
3816
3817     CV_Assert( ksize.width > 0 && ksize.width % 2 == 1 &&
3818         ksize.height > 0 && ksize.height % 2 == 1 );
3819
3820     sigma1 = std::max( sigma1, 0. );
3821     sigma2 = std::max( sigma2, 0. );
3822
3823     getGaussianKernel( ksize.width, sigma1, std::max(depth, CV_32F), kx );
3824     if( ksize.height == ksize.width && std::abs(sigma1 - sigma2) < DBL_EPSILON )
3825         ky = kx;
3826     else
3827         getGaussianKernel( ksize.height, sigma2, std::max(depth, CV_32F), ky );
3828 }
3829
3830 }
3831
3832 cv::Ptr<cv::FilterEngine> cv::createGaussianFilter( int type, Size ksize,
3833                                         double sigma1, double sigma2,
3834                                         int borderType )
3835 {
3836     Mat kx, ky;
3837     createGaussianKernels(kx, ky, type, ksize, sigma1, sigma2);
3838
3839     return createSeparableLinearFilter( type, type, kx, ky, Point(-1,-1), 0, borderType );
3840 }
3841
3842 namespace cv
3843 {
3844 #ifdef HAVE_OPENCL
3845
3846 static bool ocl_GaussianBlur_8UC1(InputArray _src, OutputArray _dst, Size ksize, int ddepth,
3847                                   InputArray _kernelX, InputArray _kernelY, int borderType)
3848 {
3849     const ocl::Device & dev = ocl::Device::getDefault();
3850     int type = _src.type(), sdepth = CV_MAT_DEPTH(type), cn = CV_MAT_CN(type);
3851
3852     if ( !(dev.isIntel() && (type == CV_8UC1) &&
3853          (_src.offset() == 0) && (_src.step() % 4 == 0) &&
3854          ((ksize.width == 5 && (_src.cols() % 4 == 0)) ||
3855          (ksize.width == 3 && (_src.cols() % 16 == 0) && (_src.rows() % 2 == 0)))) )
3856         return false;
3857
3858     Mat kernelX = _kernelX.getMat().reshape(1, 1);
3859     if (kernelX.cols % 2 != 1)
3860         return false;
3861     Mat kernelY = _kernelY.getMat().reshape(1, 1);
3862     if (kernelY.cols % 2 != 1)
3863         return false;
3864
3865     if (ddepth < 0)
3866         ddepth = sdepth;
3867
3868     Size size = _src.size();
3869     size_t globalsize[2] = { 0, 0 };
3870     size_t localsize[2] = { 0, 0 };
3871
3872     if (ksize.width == 3)
3873     {
3874         globalsize[0] = size.width / 16;
3875         globalsize[1] = size.height / 2;
3876     }
3877     else if (ksize.width == 5)
3878     {
3879         globalsize[0] = size.width / 4;
3880         globalsize[1] = size.height / 1;
3881     }
3882
3883     const char * const borderMap[] = { "BORDER_CONSTANT", "BORDER_REPLICATE", "BORDER_REFLECT", 0, "BORDER_REFLECT_101" };
3884     char build_opts[1024];
3885     sprintf(build_opts, "-D %s %s%s", borderMap[borderType & ~BORDER_ISOLATED],
3886             ocl::kernelToStr(kernelX, CV_32F, "KERNEL_MATRIX_X").c_str(),
3887             ocl::kernelToStr(kernelY, CV_32F, "KERNEL_MATRIX_Y").c_str());
3888
3889     ocl::Kernel kernel;
3890
3891     if (ksize.width == 3)
3892         kernel.create("gaussianBlur3x3_8UC1_cols16_rows2", cv::ocl::imgproc::gaussianBlur3x3_oclsrc, build_opts);
3893     else if (ksize.width == 5)
3894         kernel.create("gaussianBlur5x5_8UC1_cols4", cv::ocl::imgproc::gaussianBlur5x5_oclsrc, build_opts);
3895
3896     if (kernel.empty())
3897         return false;
3898
3899     UMat src = _src.getUMat();
3900     _dst.create(size, CV_MAKETYPE(ddepth, cn));
3901     if (!(_dst.offset() == 0 && _dst.step() % 4 == 0))
3902         return false;
3903     UMat dst = _dst.getUMat();
3904
3905     int idxArg = kernel.set(0, ocl::KernelArg::PtrReadOnly(src));
3906     idxArg = kernel.set(idxArg, (int)src.step);
3907     idxArg = kernel.set(idxArg, ocl::KernelArg::PtrWriteOnly(dst));
3908     idxArg = kernel.set(idxArg, (int)dst.step);
3909     idxArg = kernel.set(idxArg, (int)dst.rows);
3910     idxArg = kernel.set(idxArg, (int)dst.cols);
3911
3912     return kernel.run(2, globalsize, (localsize[0] == 0) ? NULL : localsize, false);
3913 }
3914
3915 #endif
3916
3917 #ifdef HAVE_OPENVX
3918
3919 namespace ovx {
3920     template <> inline bool skipSmallImages<VX_KERNEL_GAUSSIAN_3x3>(int w, int h) { return w*h < 320 * 240; }
3921 }
3922 static bool openvx_gaussianBlur(InputArray _src, OutputArray _dst, Size ksize,
3923                                 double sigma1, double sigma2, int borderType)
3924 {
3925     if (sigma2 <= 0)
3926         sigma2 = sigma1;
3927     // automatic detection of kernel size from sigma
3928     if (ksize.width <= 0 && sigma1 > 0)
3929         ksize.width = cvRound(sigma1*6 + 1) | 1;
3930     if (ksize.height <= 0 && sigma2 > 0)
3931         ksize.height = cvRound(sigma2*6 + 1) | 1;
3932
3933     if (_src.type() != CV_8UC1 ||
3934         _src.cols() < 3 || _src.rows() < 3 ||
3935         ksize.width != 3 || ksize.height != 3)
3936         return false;
3937
3938     sigma1 = std::max(sigma1, 0.);
3939     sigma2 = std::max(sigma2, 0.);
3940
3941     if (!(sigma1 == 0.0 || (sigma1 - 0.8) < DBL_EPSILON) || !(sigma2 == 0.0 || (sigma2 - 0.8) < DBL_EPSILON) ||
3942         ovx::skipSmallImages<VX_KERNEL_GAUSSIAN_3x3>(_src.cols(), _src.rows()))
3943         return false;
3944
3945     Mat src = _src.getMat();
3946     Mat dst = _dst.getMat();
3947
3948     if ((borderType & BORDER_ISOLATED) == 0 && src.isSubmatrix())
3949         return false; //Process isolated borders only
3950     vx_enum border;
3951     switch (borderType & ~BORDER_ISOLATED)
3952     {
3953     case BORDER_CONSTANT:
3954         border = VX_BORDER_CONSTANT;
3955         break;
3956     case BORDER_REPLICATE:
3957         border = VX_BORDER_REPLICATE;
3958         break;
3959     default:
3960         return false;
3961     }
3962
3963     try
3964     {
3965         ivx::Context ctx = ovx::getOpenVXContext();
3966
3967         Mat a;
3968         if (dst.data != src.data)
3969             a = src;
3970         else
3971             src.copyTo(a);
3972
3973         ivx::Image
3974             ia = ivx::Image::createFromHandle(ctx, VX_DF_IMAGE_U8,
3975                 ivx::Image::createAddressing(a.cols, a.rows, 1, (vx_int32)(a.step)), a.data),
3976             ib = ivx::Image::createFromHandle(ctx, VX_DF_IMAGE_U8,
3977                 ivx::Image::createAddressing(dst.cols, dst.rows, 1, (vx_int32)(dst.step)), dst.data);
3978
3979         //ATTENTION: VX_CONTEXT_IMMEDIATE_BORDER attribute change could lead to strange issues in multi-threaded environments
3980         //since OpenVX standard says nothing about thread-safety for now
3981         ivx::border_t prevBorder = ctx.immediateBorder();
3982         ctx.setImmediateBorder(border, (vx_uint8)(0));
3983         ivx::IVX_CHECK_STATUS(vxuGaussian3x3(ctx, ia, ib));
3984         ctx.setImmediateBorder(prevBorder);
3985     }
3986     catch (ivx::RuntimeError & e)
3987     {
3988         VX_DbgThrow(e.what());
3989     }
3990     catch (ivx::WrapperError & e)
3991     {
3992         VX_DbgThrow(e.what());
3993     }
3994     return true;
3995 }
3996
3997 #endif
3998
3999 #ifdef HAVE_IPP
4000 // IW 2017u2 has bug which doesn't allow use of partial inMem with tiling
4001 #if IPP_DISABLE_GAUSSIANBLUR_PARALLEL
4002 #define IPP_GAUSSIANBLUR_PARALLEL 0
4003 #else
4004 #define IPP_GAUSSIANBLUR_PARALLEL 1
4005 #endif
4006
4007 #ifdef HAVE_IPP_IW
4008
4009 class ipp_gaussianBlurParallel: public ParallelLoopBody
4010 {
4011 public:
4012     ipp_gaussianBlurParallel(::ipp::IwiImage &src, ::ipp::IwiImage &dst, int kernelSize, float sigma, ::ipp::IwiBorderType &border, bool *pOk):
4013         m_src(src), m_dst(dst), m_kernelSize(kernelSize), m_sigma(sigma), m_border(border), m_pOk(pOk) {
4014         *m_pOk = true;
4015     }
4016     ~ipp_gaussianBlurParallel()
4017     {
4018     }
4019
4020     virtual void operator() (const Range& range) const CV_OVERRIDE
4021     {
4022         CV_INSTRUMENT_REGION_IPP()
4023
4024         if(!*m_pOk)
4025             return;
4026
4027         try
4028         {
4029             ::ipp::IwiTile tile = ::ipp::IwiRoi(0, range.start, m_dst.m_size.width, range.end - range.start);
4030             CV_INSTRUMENT_FUN_IPP(::ipp::iwiFilterGaussian, m_src, m_dst, m_kernelSize, m_sigma, ::ipp::IwDefault(), m_border, tile);
4031         }
4032         catch(::ipp::IwException e)
4033         {
4034             *m_pOk = false;
4035             return;
4036         }
4037     }
4038 private:
4039     ::ipp::IwiImage &m_src;
4040     ::ipp::IwiImage &m_dst;
4041
4042     int m_kernelSize;
4043     float m_sigma;
4044     ::ipp::IwiBorderType &m_border;
4045
4046     volatile bool *m_pOk;
4047     const ipp_gaussianBlurParallel& operator= (const ipp_gaussianBlurParallel&);
4048 };
4049
4050 #endif
4051
4052 static bool ipp_GaussianBlur(InputArray _src, OutputArray _dst, Size ksize,
4053                    double sigma1, double sigma2, int borderType )
4054 {
4055 #ifdef HAVE_IPP_IW
4056     CV_INSTRUMENT_REGION_IPP()
4057
4058 #if IPP_VERSION_X100 < 201800 && ((defined _MSC_VER && defined _M_IX86) || (defined __GNUC__ && defined __i386__))
4059     CV_UNUSED(_src); CV_UNUSED(_dst); CV_UNUSED(ksize); CV_UNUSED(sigma1); CV_UNUSED(sigma2); CV_UNUSED(borderType);
4060     return false; // bug on ia32
4061 #else
4062     if(sigma1 != sigma2)
4063         return false;
4064
4065     if(sigma1 < FLT_EPSILON)
4066         return false;
4067
4068     if(ksize.width != ksize.height)
4069         return false;
4070
4071     // Acquire data and begin processing
4072     try
4073     {
4074         Mat src = _src.getMat();
4075         Mat dst = _dst.getMat();
4076         ::ipp::IwiImage       iwSrc      = ippiGetImage(src);
4077         ::ipp::IwiImage       iwDst      = ippiGetImage(dst);
4078         ::ipp::IwiBorderSize  borderSize = ::ipp::iwiSizeToBorderSize(ippiGetSize(ksize));
4079         ::ipp::IwiBorderType  ippBorder(ippiGetBorder(iwSrc, borderType, borderSize));
4080         if(!ippBorder)
4081             return false;
4082
4083         const int threads = ippiSuggestThreadsNum(iwDst, 2);
4084         if(IPP_GAUSSIANBLUR_PARALLEL && threads > 1) {
4085             bool ok;
4086             ipp_gaussianBlurParallel invoker(iwSrc, iwDst, ksize.width, (float) sigma1, ippBorder, &ok);
4087
4088             if(!ok)
4089                 return false;
4090             const Range range(0, (int) iwDst.m_size.height);
4091             parallel_for_(range, invoker, threads*4);
4092
4093             if(!ok)
4094                 return false;
4095         } else {
4096             CV_INSTRUMENT_FUN_IPP(::ipp::iwiFilterGaussian, iwSrc, iwDst, ksize.width, sigma1, ::ipp::IwDefault(), ippBorder);
4097         }
4098     }
4099     catch (::ipp::IwException ex)
4100     {
4101         return false;
4102     }
4103
4104     return true;
4105 #endif
4106 #else
4107     CV_UNUSED(_src); CV_UNUSED(_dst); CV_UNUSED(ksize); CV_UNUSED(sigma1); CV_UNUSED(sigma2); CV_UNUSED(borderType);
4108     return false;
4109 #endif
4110 }
4111 #endif
4112 }
4113
4114 void cv::GaussianBlur( InputArray _src, OutputArray _dst, Size ksize,
4115                    double sigma1, double sigma2,
4116                    int borderType )
4117 {
4118     CV_INSTRUMENT_REGION()
4119
4120     int type = _src.type();
4121     Size size = _src.size();
4122     _dst.create( size, type );
4123
4124     if( (borderType & ~BORDER_ISOLATED) != BORDER_CONSTANT &&
4125         ((borderType & BORDER_ISOLATED) != 0 || !_src.getMat().isSubmatrix()) )
4126     {
4127         if( size.height == 1 )
4128             ksize.height = 1;
4129         if( size.width == 1 )
4130             ksize.width = 1;
4131     }
4132
4133     if( ksize.width == 1 && ksize.height == 1 )
4134     {
4135         _src.copyTo(_dst);
4136         return;
4137     }
4138
4139     bool useOpenCL = (ocl::isOpenCLActivated() && _dst.isUMat() && _src.dims() <= 2 &&
4140                ((ksize.width == 3 && ksize.height == 3) ||
4141                (ksize.width == 5 && ksize.height == 5)) &&
4142                _src.rows() > ksize.height && _src.cols() > ksize.width);
4143     (void)useOpenCL;
4144
4145     int sdepth = CV_MAT_DEPTH(type), cn = CV_MAT_CN(type);
4146
4147     if(sdepth == CV_8U && ((borderType & BORDER_ISOLATED) || !_src.getMat().isSubmatrix()))
4148     {
4149         std::vector<ufixedpoint16> fkx, fky;
4150         createGaussianKernels(fkx, fky, type, ksize, sigma1, sigma2);
4151         Mat src = _src.getMat();
4152         Mat dst = _dst.getMat();
4153         if (src.data == dst.data)
4154             src = src.clone();
4155         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);
4156         parallel_for_(Range(0, dst.rows), invoker, std::max(1, std::min(getNumThreads(), getNumberOfCPUs())));
4157         return;
4158     }
4159
4160
4161     Mat kx, ky;
4162     createGaussianKernels(kx, ky, type, ksize, sigma1, sigma2);
4163
4164     CV_OCL_RUN(useOpenCL, ocl_GaussianBlur_8UC1(_src, _dst, ksize, CV_MAT_DEPTH(type), kx, ky, borderType));
4165
4166     CV_OCL_RUN(_dst.isUMat() && _src.dims() <= 2 && (size_t)_src.rows() > kx.total() && (size_t)_src.cols() > kx.total(),
4167                ocl_sepFilter2D(_src, _dst, sdepth, kx, ky, Point(-1, -1), 0, borderType))
4168
4169     Mat src = _src.getMat();
4170     Mat dst = _dst.getMat();
4171
4172     Point ofs;
4173     Size wsz(src.cols, src.rows);
4174     if(!(borderType & BORDER_ISOLATED))
4175         src.locateROI( wsz, ofs );
4176
4177     CALL_HAL(gaussianBlur, cv_hal_gaussianBlur, src.ptr(), src.step, dst.ptr(), dst.step, src.cols, src.rows, sdepth, cn,
4178              ofs.x, ofs.y, wsz.width - src.cols - ofs.x, wsz.height - src.rows - ofs.y, ksize.width, ksize.height,
4179              sigma1, sigma2, borderType&~BORDER_ISOLATED);
4180
4181     CV_OVX_RUN(true,
4182                openvx_gaussianBlur(src, dst, ksize, sigma1, sigma2, borderType))
4183
4184     CV_IPP_RUN_FAST(ipp_GaussianBlur(src, dst, ksize, sigma1, sigma2, borderType));
4185
4186     sepFilter2D(src, dst, sdepth, kx, ky, Point(-1, -1), 0, borderType);
4187 }
4188
4189 /****************************************************************************************\
4190                                       Median Filter
4191 \****************************************************************************************/
4192
4193 namespace cv
4194 {
4195 typedef ushort HT;
4196
4197 /**
4198  * This structure represents a two-tier histogram. The first tier (known as the
4199  * "coarse" level) is 4 bit wide and the second tier (known as the "fine" level)
4200  * is 8 bit wide. Pixels inserted in the fine level also get inserted into the
4201  * coarse bucket designated by the 4 MSBs of the fine bucket value.
4202  *
4203  * The structure is aligned on 16 bits, which is a prerequisite for SIMD
4204  * instructions. Each bucket is 16 bit wide, which means that extra care must be
4205  * taken to prevent overflow.
4206  */
4207 typedef struct
4208 {
4209     HT coarse[16];
4210     HT fine[16][16];
4211 } Histogram;
4212
4213
4214 #if CV_SIMD128
4215
4216 static inline void histogram_add_simd( const HT x[16], HT y[16] )
4217 {
4218     v_store(y, v_load(x) + v_load(y));
4219     v_store(y + 8, v_load(x + 8) + v_load(y + 8));
4220 }
4221
4222 static inline void histogram_sub_simd( const HT x[16], HT y[16] )
4223 {
4224     v_store(y, v_load(y) - v_load(x));
4225     v_store(y + 8, v_load(y + 8) - v_load(x + 8));
4226 }
4227
4228 #endif
4229
4230
4231 static inline void histogram_add( const HT x[16], HT y[16] )
4232 {
4233     int i;
4234     for( i = 0; i < 16; ++i )
4235         y[i] = (HT)(y[i] + x[i]);
4236 }
4237
4238 static inline void histogram_sub( const HT x[16], HT y[16] )
4239 {
4240     int i;
4241     for( i = 0; i < 16; ++i )
4242         y[i] = (HT)(y[i] - x[i]);
4243 }
4244
4245 static inline void histogram_muladd( int a, const HT x[16],
4246         HT y[16] )
4247 {
4248     for( int i = 0; i < 16; ++i )
4249         y[i] = (HT)(y[i] + a * x[i]);
4250 }
4251
4252 static void
4253 medianBlur_8u_O1( const Mat& _src, Mat& _dst, int ksize )
4254 {
4255 /**
4256  * HOP is short for Histogram OPeration. This macro makes an operation \a op on
4257  * histogram \a h for pixel value \a x. It takes care of handling both levels.
4258  */
4259 #define HOP(h,x,op) \
4260     h.coarse[x>>4] op, \
4261     *((HT*)h.fine + x) op
4262
4263 #define COP(c,j,x,op) \
4264     h_coarse[ 16*(n*c+j) + (x>>4) ] op, \
4265     h_fine[ 16 * (n*(16*c+(x>>4)) + j) + (x & 0xF) ] op
4266
4267     int cn = _dst.channels(), m = _dst.rows, r = (ksize-1)/2;
4268     CV_Assert(cn > 0 && cn <= 4);
4269     size_t sstep = _src.step, dstep = _dst.step;
4270     Histogram CV_DECL_ALIGNED(16) H[4];
4271     HT CV_DECL_ALIGNED(16) luc[4][16];
4272
4273     int STRIPE_SIZE = std::min( _dst.cols, 512/cn );
4274
4275     std::vector<HT> _h_coarse(1 * 16 * (STRIPE_SIZE + 2*r) * cn + 16);
4276     std::vector<HT> _h_fine(16 * 16 * (STRIPE_SIZE + 2*r) * cn + 16);
4277     HT* h_coarse = alignPtr(&_h_coarse[0], 16);
4278     HT* h_fine = alignPtr(&_h_fine[0], 16);
4279 #if CV_SIMD128
4280     volatile bool useSIMD = hasSIMD128();
4281 #endif
4282
4283     for( int x = 0; x < _dst.cols; x += STRIPE_SIZE )
4284     {
4285         int i, j, k, c, n = std::min(_dst.cols - x, STRIPE_SIZE) + r*2;
4286         const uchar* src = _src.ptr() + x*cn;
4287         uchar* dst = _dst.ptr() + (x - r)*cn;
4288
4289         memset( h_coarse, 0, 16*n*cn*sizeof(h_coarse[0]) );
4290         memset( h_fine, 0, 16*16*n*cn*sizeof(h_fine[0]) );
4291
4292         // First row initialization
4293         for( c = 0; c < cn; c++ )
4294         {
4295             for( j = 0; j < n; j++ )
4296                 COP( c, j, src[cn*j+c], += (cv::HT)(r+2) );
4297
4298             for( i = 1; i < r; i++ )
4299             {
4300                 const uchar* p = src + sstep*std::min(i, m-1);
4301                 for ( j = 0; j < n; j++ )
4302                     COP( c, j, p[cn*j+c], ++ );
4303             }
4304         }
4305
4306         for( i = 0; i < m; i++ )
4307         {
4308             const uchar* p0 = src + sstep * std::max( 0, i-r-1 );
4309             const uchar* p1 = src + sstep * std::min( m-1, i+r );
4310
4311             memset( H, 0, cn*sizeof(H[0]) );
4312             memset( luc, 0, cn*sizeof(luc[0]) );
4313             for( c = 0; c < cn; c++ )
4314             {
4315                 // Update column histograms for the entire row.
4316                 for( j = 0; j < n; j++ )
4317                 {
4318                     COP( c, j, p0[j*cn + c], -- );
4319                     COP( c, j, p1[j*cn + c], ++ );
4320                 }
4321
4322                 // First column initialization
4323                 for( k = 0; k < 16; ++k )
4324                     histogram_muladd( 2*r+1, &h_fine[16*n*(16*c+k)], &H[c].fine[k][0] );
4325
4326 #if CV_SIMD128
4327                 if( useSIMD )
4328                 {
4329                     for( j = 0; j < 2*r; ++j )
4330                         histogram_add_simd( &h_coarse[16*(n*c+j)], H[c].coarse );
4331
4332                     for( j = r; j < n-r; j++ )
4333                     {
4334                         int t = 2*r*r + 2*r, b, sum = 0;
4335                         HT* segment;
4336
4337                         histogram_add_simd( &h_coarse[16*(n*c + std::min(j+r,n-1))], H[c].coarse );
4338
4339                         // Find median at coarse level
4340                         for ( k = 0; k < 16 ; ++k )
4341                         {
4342                             sum += H[c].coarse[k];
4343                             if ( sum > t )
4344                             {
4345                                 sum -= H[c].coarse[k];
4346                                 break;
4347                             }
4348                         }
4349                         CV_Assert( k < 16 );
4350
4351                         /* Update corresponding histogram segment */
4352                         if ( luc[c][k] <= j-r )
4353                         {
4354                             memset( &H[c].fine[k], 0, 16 * sizeof(HT) );
4355                             for ( luc[c][k] = cv::HT(j-r); luc[c][k] < MIN(j+r+1,n); ++luc[c][k] )
4356                                 histogram_add_simd( &h_fine[16*(n*(16*c+k)+luc[c][k])], H[c].fine[k] );
4357
4358                             if ( luc[c][k] < j+r+1 )
4359                             {
4360                                 histogram_muladd( j+r+1 - n, &h_fine[16*(n*(16*c+k)+(n-1))], &H[c].fine[k][0] );
4361                                 luc[c][k] = (HT)(j+r+1);
4362                             }
4363                         }
4364                         else
4365                         {
4366                             for ( ; luc[c][k] < j+r+1; ++luc[c][k] )
4367                             {
4368                                 histogram_sub_simd( &h_fine[16*(n*(16*c+k)+MAX(luc[c][k]-2*r-1,0))], H[c].fine[k] );
4369                                 histogram_add_simd( &h_fine[16*(n*(16*c+k)+MIN(luc[c][k],n-1))], H[c].fine[k] );
4370                             }
4371                         }
4372
4373                         histogram_sub_simd( &h_coarse[16*(n*c+MAX(j-r,0))], H[c].coarse );
4374
4375                         /* Find median in segment */
4376                         segment = H[c].fine[k];
4377                         for ( b = 0; b < 16 ; b++ )
4378                         {
4379                             sum += segment[b];
4380                             if ( sum > t )
4381                             {
4382                                 dst[dstep*i+cn*j+c] = (uchar)(16*k + b);
4383                                 break;
4384                             }
4385                         }
4386                         CV_Assert( b < 16 );
4387                     }
4388                 }
4389                 else
4390 #endif
4391                 {
4392                     for( j = 0; j < 2*r; ++j )
4393                         histogram_add( &h_coarse[16*(n*c+j)], H[c].coarse );
4394
4395                     for( j = r; j < n-r; j++ )
4396                     {
4397                         int t = 2*r*r + 2*r, b, sum = 0;
4398                         HT* segment;
4399
4400                         histogram_add( &h_coarse[16*(n*c + std::min(j+r,n-1))], H[c].coarse );
4401
4402                         // Find median at coarse level
4403                         for ( k = 0; k < 16 ; ++k )
4404                         {
4405                             sum += H[c].coarse[k];
4406                             if ( sum > t )
4407                             {
4408                                 sum -= H[c].coarse[k];
4409                                 break;
4410                             }
4411                         }
4412                         CV_Assert( k < 16 );
4413
4414                         /* Update corresponding histogram segment */
4415                         if ( luc[c][k] <= j-r )
4416                         {
4417                             memset( &H[c].fine[k], 0, 16 * sizeof(HT) );
4418                             for ( luc[c][k] = cv::HT(j-r); luc[c][k] < MIN(j+r+1,n); ++luc[c][k] )
4419                                 histogram_add( &h_fine[16*(n*(16*c+k)+luc[c][k])], H[c].fine[k] );
4420
4421                             if ( luc[c][k] < j+r+1 )
4422                             {
4423                                 histogram_muladd( j+r+1 - n, &h_fine[16*(n*(16*c+k)+(n-1))], &H[c].fine[k][0] );
4424                                 luc[c][k] = (HT)(j+r+1);
4425                             }
4426                         }
4427                         else
4428                         {
4429                             for ( ; luc[c][k] < j+r+1; ++luc[c][k] )
4430                             {
4431                                 histogram_sub( &h_fine[16*(n*(16*c+k)+MAX(luc[c][k]-2*r-1,0))], H[c].fine[k] );
4432                                 histogram_add( &h_fine[16*(n*(16*c+k)+MIN(luc[c][k],n-1))], H[c].fine[k] );
4433                             }
4434                         }
4435
4436                         histogram_sub( &h_coarse[16*(n*c+MAX(j-r,0))], H[c].coarse );
4437
4438                         /* Find median in segment */
4439                         segment = H[c].fine[k];
4440                         for ( b = 0; b < 16 ; b++ )
4441                         {
4442                             sum += segment[b];
4443                             if ( sum > t )
4444                             {
4445                                 dst[dstep*i+cn*j+c] = (uchar)(16*k + b);
4446                                 break;
4447                             }
4448                         }
4449                         CV_Assert( b < 16 );
4450                     }
4451                 }
4452             }
4453         }
4454     }
4455
4456 #undef HOP
4457 #undef COP
4458 }
4459
4460 static void
4461 medianBlur_8u_Om( const Mat& _src, Mat& _dst, int m )
4462 {
4463     #define N  16
4464     int     zone0[4][N];
4465     int     zone1[4][N*N];
4466     int     x, y;
4467     int     n2 = m*m/2;
4468     Size    size = _dst.size();
4469     const uchar* src = _src.ptr();
4470     uchar*  dst = _dst.ptr();
4471     int     src_step = (int)_src.step, dst_step = (int)_dst.step;
4472     int     cn = _src.channels();
4473     const uchar*  src_max = src + size.height*src_step;
4474     CV_Assert(cn > 0 && cn <= 4);
4475
4476     #define UPDATE_ACC01( pix, cn, op ) \
4477     {                                   \
4478         int p = (pix);                  \
4479         zone1[cn][p] op;                \
4480         zone0[cn][p >> 4] op;           \
4481     }
4482
4483     //CV_Assert( size.height >= nx && size.width >= nx );
4484     for( x = 0; x < size.width; x++, src += cn, dst += cn )
4485     {
4486         uchar* dst_cur = dst;
4487         const uchar* src_top = src;
4488         const uchar* src_bottom = src;
4489         int k, c;
4490         int src_step1 = src_step, dst_step1 = dst_step;
4491
4492         if( x % 2 != 0 )
4493         {
4494             src_bottom = src_top += src_step*(size.height-1);
4495             dst_cur += dst_step*(size.height-1);
4496             src_step1 = -src_step1;
4497             dst_step1 = -dst_step1;
4498         }
4499
4500         // init accumulator
4501         memset( zone0, 0, sizeof(zone0[0])*cn );
4502         memset( zone1, 0, sizeof(zone1[0])*cn );
4503
4504         for( y = 0; y <= m/2; y++ )
4505         {
4506             for( c = 0; c < cn; c++ )
4507             {
4508                 if( y > 0 )
4509                 {
4510                     for( k = 0; k < m*cn; k += cn )
4511                         UPDATE_ACC01( src_bottom[k+c], c, ++ );
4512                 }
4513                 else
4514                 {
4515                     for( k = 0; k < m*cn; k += cn )
4516                         UPDATE_ACC01( src_bottom[k+c], c, += m/2+1 );
4517                 }
4518             }
4519
4520             if( (src_step1 > 0 && y < size.height-1) ||
4521                 (src_step1 < 0 && size.height-y-1 > 0) )
4522                 src_bottom += src_step1;
4523         }
4524
4525         for( y = 0; y < size.height; y++, dst_cur += dst_step1 )
4526         {
4527             // find median
4528             for( c = 0; c < cn; c++ )
4529             {
4530                 int s = 0;
4531                 for( k = 0; ; k++ )
4532                 {
4533                     int t = s + zone0[c][k];
4534                     if( t > n2 ) break;
4535                     s = t;
4536                 }
4537
4538                 for( k *= N; ;k++ )
4539                 {
4540                     s += zone1[c][k];
4541                     if( s > n2 ) break;
4542                 }
4543
4544                 dst_cur[c] = (uchar)k;
4545             }
4546
4547             if( y+1 == size.height )
4548                 break;
4549
4550             if( cn == 1 )
4551             {
4552                 for( k = 0; k < m; k++ )
4553                 {
4554                     int p = src_top[k];
4555                     int q = src_bottom[k];
4556                     zone1[0][p]--;
4557                     zone0[0][p>>4]--;
4558                     zone1[0][q]++;
4559                     zone0[0][q>>4]++;
4560                 }
4561             }
4562             else if( cn == 3 )
4563             {
4564                 for( k = 0; k < m*3; k += 3 )
4565                 {
4566                     UPDATE_ACC01( src_top[k], 0, -- );
4567                     UPDATE_ACC01( src_top[k+1], 1, -- );
4568                     UPDATE_ACC01( src_top[k+2], 2, -- );
4569
4570                     UPDATE_ACC01( src_bottom[k], 0, ++ );
4571                     UPDATE_ACC01( src_bottom[k+1], 1, ++ );
4572                     UPDATE_ACC01( src_bottom[k+2], 2, ++ );
4573                 }
4574             }
4575             else
4576             {
4577                 assert( cn == 4 );
4578                 for( k = 0; k < m*4; k += 4 )
4579                 {
4580                     UPDATE_ACC01( src_top[k], 0, -- );
4581                     UPDATE_ACC01( src_top[k+1], 1, -- );
4582                     UPDATE_ACC01( src_top[k+2], 2, -- );
4583                     UPDATE_ACC01( src_top[k+3], 3, -- );
4584
4585                     UPDATE_ACC01( src_bottom[k], 0, ++ );
4586                     UPDATE_ACC01( src_bottom[k+1], 1, ++ );
4587                     UPDATE_ACC01( src_bottom[k+2], 2, ++ );
4588                     UPDATE_ACC01( src_bottom[k+3], 3, ++ );
4589                 }
4590             }
4591
4592             if( (src_step1 > 0 && src_bottom + src_step1 < src_max) ||
4593                 (src_step1 < 0 && src_bottom + src_step1 >= src) )
4594                 src_bottom += src_step1;
4595
4596             if( y >= m/2 )
4597                 src_top += src_step1;
4598         }
4599     }
4600 #undef N
4601 #undef UPDATE_ACC
4602 }
4603
4604
4605 struct MinMax8u
4606 {
4607     typedef uchar value_type;
4608     typedef int arg_type;
4609     enum { SIZE = 1 };
4610     arg_type load(const uchar* ptr) { return *ptr; }
4611     void store(uchar* ptr, arg_type val) { *ptr = (uchar)val; }
4612     void operator()(arg_type& a, arg_type& b) const
4613     {
4614         int t = CV_FAST_CAST_8U(a - b);
4615         b += t; a -= t;
4616     }
4617 };
4618
4619 struct MinMax16u
4620 {
4621     typedef ushort value_type;
4622     typedef int arg_type;
4623     enum { SIZE = 1 };
4624     arg_type load(const ushort* ptr) { return *ptr; }
4625     void store(ushort* ptr, arg_type val) { *ptr = (ushort)val; }
4626     void operator()(arg_type& a, arg_type& b) const
4627     {
4628         arg_type t = a;
4629         a = std::min(a, b);
4630         b = std::max(b, t);
4631     }
4632 };
4633
4634 struct MinMax16s
4635 {
4636     typedef short value_type;
4637     typedef int arg_type;
4638     enum { SIZE = 1 };
4639     arg_type load(const short* ptr) { return *ptr; }
4640     void store(short* ptr, arg_type val) { *ptr = (short)val; }
4641     void operator()(arg_type& a, arg_type& b) const
4642     {
4643         arg_type t = a;
4644         a = std::min(a, b);
4645         b = std::max(b, t);
4646     }
4647 };
4648
4649 struct MinMax32f
4650 {
4651     typedef float value_type;
4652     typedef float arg_type;
4653     enum { SIZE = 1 };
4654     arg_type load(const float* ptr) { return *ptr; }
4655     void store(float* ptr, arg_type val) { *ptr = val; }
4656     void operator()(arg_type& a, arg_type& b) const
4657     {
4658         arg_type t = a;
4659         a = std::min(a, b);
4660         b = std::max(b, t);
4661     }
4662 };
4663
4664 #if CV_SIMD128
4665
4666 struct MinMaxVec8u
4667 {
4668     typedef uchar value_type;
4669     typedef v_uint8x16 arg_type;
4670     enum { SIZE = 16 };
4671     arg_type load(const uchar* ptr) { return v_load(ptr); }
4672     void store(uchar* ptr, const arg_type &val) { v_store(ptr, val); }
4673     void operator()(arg_type& a, arg_type& b) const
4674     {
4675         arg_type t = a;
4676         a = v_min(a, b);
4677         b = v_max(b, t);
4678     }
4679 };
4680
4681
4682 struct MinMaxVec16u
4683 {
4684     typedef ushort value_type;
4685     typedef v_uint16x8 arg_type;
4686     enum { SIZE = 8 };
4687     arg_type load(const ushort* ptr) { return v_load(ptr); }
4688     void store(ushort* ptr, const arg_type &val) { v_store(ptr, val); }
4689     void operator()(arg_type& a, arg_type& b) const
4690     {
4691         arg_type t = a;
4692         a = v_min(a, b);
4693         b = v_max(b, t);
4694     }
4695 };
4696
4697
4698 struct MinMaxVec16s
4699 {
4700     typedef short value_type;
4701     typedef v_int16x8 arg_type;
4702     enum { SIZE = 8 };
4703     arg_type load(const short* ptr) { return v_load(ptr); }
4704     void store(short* ptr, const arg_type &val) { v_store(ptr, val); }
4705     void operator()(arg_type& a, arg_type& b) const
4706     {
4707         arg_type t = a;
4708         a = v_min(a, b);
4709         b = v_max(b, t);
4710     }
4711 };
4712
4713
4714 struct MinMaxVec32f
4715 {
4716     typedef float value_type;
4717     typedef v_float32x4 arg_type;
4718     enum { SIZE = 4 };
4719     arg_type load(const float* ptr) { return v_load(ptr); }
4720     void store(float* ptr, const arg_type &val) { v_store(ptr, val); }
4721     void operator()(arg_type& a, arg_type& b) const
4722     {
4723         arg_type t = a;
4724         a = v_min(a, b);
4725         b = v_max(b, t);
4726     }
4727 };
4728
4729 #else
4730
4731 typedef MinMax8u MinMaxVec8u;
4732 typedef MinMax16u MinMaxVec16u;
4733 typedef MinMax16s MinMaxVec16s;
4734 typedef MinMax32f MinMaxVec32f;
4735
4736 #endif
4737
4738 template<class Op, class VecOp>
4739 static void
4740 medianBlur_SortNet( const Mat& _src, Mat& _dst, int m )
4741 {
4742     typedef typename Op::value_type T;
4743     typedef typename Op::arg_type WT;
4744     typedef typename VecOp::arg_type VT;
4745
4746     const T* src = _src.ptr<T>();
4747     T* dst = _dst.ptr<T>();
4748     int sstep = (int)(_src.step/sizeof(T));
4749     int dstep = (int)(_dst.step/sizeof(T));
4750     Size size = _dst.size();
4751     int i, j, k, cn = _src.channels();
4752     Op op;
4753     VecOp vop;
4754     volatile bool useSIMD = hasSIMD128();
4755
4756     if( m == 3 )
4757     {
4758         if( size.width == 1 || size.height == 1 )
4759         {
4760             int len = size.width + size.height - 1;
4761             int sdelta = size.height == 1 ? cn : sstep;
4762             int sdelta0 = size.height == 1 ? 0 : sstep - cn;
4763             int ddelta = size.height == 1 ? cn : dstep;
4764
4765             for( i = 0; i < len; i++, src += sdelta0, dst += ddelta )
4766                 for( j = 0; j < cn; j++, src++ )
4767                 {
4768                     WT p0 = src[i > 0 ? -sdelta : 0];
4769                     WT p1 = src[0];
4770                     WT p2 = src[i < len - 1 ? sdelta : 0];
4771
4772                     op(p0, p1); op(p1, p2); op(p0, p1);
4773                     dst[j] = (T)p1;
4774                 }
4775             return;
4776         }
4777
4778         size.width *= cn;
4779         for( i = 0; i < size.height; i++, dst += dstep )
4780         {
4781             const T* row0 = src + std::max(i - 1, 0)*sstep;
4782             const T* row1 = src + i*sstep;
4783             const T* row2 = src + std::min(i + 1, size.height-1)*sstep;
4784             int limit = useSIMD ? cn : size.width;
4785
4786             for(j = 0;; )
4787             {
4788                 for( ; j < limit; j++ )
4789                 {
4790                     int j0 = j >= cn ? j - cn : j;
4791                     int j2 = j < size.width - cn ? j + cn : j;
4792                     WT p0 = row0[j0], p1 = row0[j], p2 = row0[j2];
4793                     WT p3 = row1[j0], p4 = row1[j], p5 = row1[j2];
4794                     WT p6 = row2[j0], p7 = row2[j], p8 = row2[j2];
4795
4796                     op(p1, p2); op(p4, p5); op(p7, p8); op(p0, p1);
4797                     op(p3, p4); op(p6, p7); op(p1, p2); op(p4, p5);
4798                     op(p7, p8); op(p0, p3); op(p5, p8); op(p4, p7);
4799                     op(p3, p6); op(p1, p4); op(p2, p5); op(p4, p7);
4800                     op(p4, p2); op(p6, p4); op(p4, p2);
4801                     dst[j] = (T)p4;
4802                 }
4803
4804                 if( limit == size.width )
4805                     break;
4806
4807                 for( ; j <= size.width - VecOp::SIZE - cn; j += VecOp::SIZE )
4808                 {
4809                     VT p0 = vop.load(row0+j-cn), p1 = vop.load(row0+j), p2 = vop.load(row0+j+cn);
4810                     VT p3 = vop.load(row1+j-cn), p4 = vop.load(row1+j), p5 = vop.load(row1+j+cn);
4811                     VT p6 = vop.load(row2+j-cn), p7 = vop.load(row2+j), p8 = vop.load(row2+j+cn);
4812
4813                     vop(p1, p2); vop(p4, p5); vop(p7, p8); vop(p0, p1);
4814                     vop(p3, p4); vop(p6, p7); vop(p1, p2); vop(p4, p5);
4815                     vop(p7, p8); vop(p0, p3); vop(p5, p8); vop(p4, p7);
4816                     vop(p3, p6); vop(p1, p4); vop(p2, p5); vop(p4, p7);
4817                     vop(p4, p2); vop(p6, p4); vop(p4, p2);
4818                     vop.store(dst+j, p4);
4819                 }
4820
4821                 limit = size.width;
4822             }
4823         }
4824     }
4825     else if( m == 5 )
4826     {
4827         if( size.width == 1 || size.height == 1 )
4828         {
4829             int len = size.width + size.height - 1;
4830             int sdelta = size.height == 1 ? cn : sstep;
4831             int sdelta0 = size.height == 1 ? 0 : sstep - cn;
4832             int ddelta = size.height == 1 ? cn : dstep;
4833
4834             for( i = 0; i < len; i++, src += sdelta0, dst += ddelta )
4835                 for( j = 0; j < cn; j++, src++ )
4836                 {
4837                     int i1 = i > 0 ? -sdelta : 0;
4838                     int i0 = i > 1 ? -sdelta*2 : i1;
4839                     int i3 = i < len-1 ? sdelta : 0;
4840                     int i4 = i < len-2 ? sdelta*2 : i3;
4841                     WT p0 = src[i0], p1 = src[i1], p2 = src[0], p3 = src[i3], p4 = src[i4];
4842
4843                     op(p0, p1); op(p3, p4); op(p2, p3); op(p3, p4); op(p0, p2);
4844                     op(p2, p4); op(p1, p3); op(p1, p2);
4845                     dst[j] = (T)p2;
4846                 }
4847             return;
4848         }
4849
4850         size.width *= cn;
4851         for( i = 0; i < size.height; i++, dst += dstep )
4852         {
4853             const T* row[5];
4854             row[0] = src + std::max(i - 2, 0)*sstep;
4855             row[1] = src + std::max(i - 1, 0)*sstep;
4856             row[2] = src + i*sstep;
4857             row[3] = src + std::min(i + 1, size.height-1)*sstep;
4858             row[4] = src + std::min(i + 2, size.height-1)*sstep;
4859             int limit = useSIMD ? cn*2 : size.width;
4860
4861             for(j = 0;; )
4862             {
4863                 for( ; j < limit; j++ )
4864                 {
4865                     WT p[25];
4866                     int j1 = j >= cn ? j - cn : j;
4867                     int j0 = j >= cn*2 ? j - cn*2 : j1;
4868                     int j3 = j < size.width - cn ? j + cn : j;
4869                     int j4 = j < size.width - cn*2 ? j + cn*2 : j3;
4870                     for( k = 0; k < 5; k++ )
4871                     {
4872                         const T* rowk = row[k];
4873                         p[k*5] = rowk[j0]; p[k*5+1] = rowk[j1];
4874                         p[k*5+2] = rowk[j]; p[k*5+3] = rowk[j3];
4875                         p[k*5+4] = rowk[j4];
4876                     }
4877
4878                     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]);
4879                     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]);
4880                     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]);
4881                     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]);
4882                     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]);
4883                     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]);
4884                     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]);
4885                     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]);
4886                     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]);
4887                     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]);
4888                     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]);
4889                     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]);
4890                     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]);
4891                     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]);
4892                     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]);
4893                     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]);
4894                     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]);
4895                     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]);
4896                     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]);
4897                     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]);
4898                     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]);
4899                     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]);
4900                     op(p[7], p[11]); op(p[11], p[13]); op(p[11], p[12]);
4901                     dst[j] = (T)p[12];
4902                 }
4903
4904                 if( limit == size.width )
4905                     break;
4906
4907                 for( ; j <= size.width - VecOp::SIZE - cn*2; j += VecOp::SIZE )
4908                 {
4909                     VT p[25];
4910                     for( k = 0; k < 5; k++ )
4911                     {
4912                         const T* rowk = row[k];
4913                         p[k*5] = vop.load(rowk+j-cn*2); p[k*5+1] = vop.load(rowk+j-cn);
4914                         p[k*5+2] = vop.load(rowk+j); p[k*5+3] = vop.load(rowk+j+cn);
4915                         p[k*5+4] = vop.load(rowk+j+cn*2);
4916                     }
4917
4918                     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]);
4919                     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]);
4920                     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]);
4921                     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]);
4922                     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]);
4923                     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]);
4924                     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]);
4925                     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]);
4926                     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]);
4927                     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]);
4928                     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]);
4929                     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]);
4930                     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]);
4931                     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]);
4932                     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]);
4933                     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]);
4934                     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]);
4935                     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]);
4936                     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]);
4937                     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]);
4938                     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]);
4939                     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]);
4940                     vop(p[7], p[11]); vop(p[11], p[13]); vop(p[11], p[12]);
4941                     vop.store(dst+j, p[12]);
4942                 }
4943
4944                 limit = size.width;
4945             }
4946         }
4947     }
4948 }
4949
4950 #ifdef HAVE_OPENCL
4951
4952 static bool ocl_medianFilter(InputArray _src, OutputArray _dst, int m)
4953 {
4954     size_t localsize[2] = { 16, 16 };
4955     size_t globalsize[2];
4956     int type = _src.type(), depth = CV_MAT_DEPTH(type), cn = CV_MAT_CN(type);
4957
4958     if ( !((depth == CV_8U || depth == CV_16U || depth == CV_16S || depth == CV_32F) && cn <= 4 && (m == 3 || m == 5)) )
4959         return false;
4960
4961     Size imgSize = _src.size();
4962     bool useOptimized = (1 == cn) &&
4963                         (size_t)imgSize.width >= localsize[0] * 8  &&
4964                         (size_t)imgSize.height >= localsize[1] * 8 &&
4965                         imgSize.width % 4 == 0 &&
4966                         imgSize.height % 4 == 0 &&
4967                         (ocl::Device::getDefault().isIntel());
4968
4969     cv::String kname = format( useOptimized ? "medianFilter%d_u" : "medianFilter%d", m) ;
4970     cv::String kdefs = useOptimized ?
4971                          format("-D T=%s -D T1=%s -D T4=%s%d -D cn=%d -D USE_4OPT", ocl::typeToStr(type),
4972                          ocl::typeToStr(depth), ocl::typeToStr(depth), cn*4, cn)
4973                          :
4974                          format("-D T=%s -D T1=%s -D cn=%d", ocl::typeToStr(type), ocl::typeToStr(depth), cn) ;
4975
4976     ocl::Kernel k(kname.c_str(), ocl::imgproc::medianFilter_oclsrc, kdefs.c_str() );
4977
4978     if (k.empty())
4979         return false;
4980
4981     UMat src = _src.getUMat();
4982     _dst.create(src.size(), type);
4983     UMat dst = _dst.getUMat();
4984
4985     k.args(ocl::KernelArg::ReadOnlyNoSize(src), ocl::KernelArg::WriteOnly(dst));
4986
4987     if( useOptimized )
4988     {
4989         globalsize[0] = DIVUP(src.cols / 4, localsize[0]) * localsize[0];
4990         globalsize[1] = DIVUP(src.rows / 4, localsize[1]) * localsize[1];
4991     }
4992     else
4993     {
4994         globalsize[0] = (src.cols + localsize[0] + 2) / localsize[0] * localsize[0];
4995         globalsize[1] = (src.rows + localsize[1] - 1) / localsize[1] * localsize[1];
4996     }
4997
4998     return k.run(2, globalsize, localsize, false);
4999 }
5000
5001 #endif
5002
5003 }
5004
5005 #ifdef HAVE_OPENVX
5006 namespace cv
5007 {
5008     namespace ovx {
5009         template <> inline bool skipSmallImages<VX_KERNEL_MEDIAN_3x3>(int w, int h) { return w*h < 1280 * 720; }
5010     }
5011     static bool openvx_medianFilter(InputArray _src, OutputArray _dst, int ksize)
5012     {
5013         if (_src.type() != CV_8UC1 || _dst.type() != CV_8U
5014 #ifndef VX_VERSION_1_1
5015             || ksize != 3
5016 #endif
5017             )
5018             return false;
5019
5020         Mat src = _src.getMat();
5021         Mat dst = _dst.getMat();
5022
5023         if (
5024 #ifdef VX_VERSION_1_1
5025              ksize != 3 ? ovx::skipSmallImages<VX_KERNEL_NON_LINEAR_FILTER>(src.cols, src.rows) :
5026 #endif
5027              ovx::skipSmallImages<VX_KERNEL_MEDIAN_3x3>(src.cols, src.rows)
5028            )
5029             return false;
5030
5031         try
5032         {
5033             ivx::Context ctx = ovx::getOpenVXContext();
5034 #ifdef VX_VERSION_1_1
5035             if ((vx_size)ksize > ctx.nonlinearMaxDimension())
5036                 return false;
5037 #endif
5038
5039             Mat a;
5040             if (dst.data != src.data)
5041                 a = src;
5042             else
5043                 src.copyTo(a);
5044
5045             ivx::Image
5046                 ia = ivx::Image::createFromHandle(ctx, VX_DF_IMAGE_U8,
5047                     ivx::Image::createAddressing(a.cols, a.rows, 1, (vx_int32)(a.step)), a.data),
5048                 ib = ivx::Image::createFromHandle(ctx, VX_DF_IMAGE_U8,
5049                     ivx::Image::createAddressing(dst.cols, dst.rows, 1, (vx_int32)(dst.step)), dst.data);
5050
5051             //ATTENTION: VX_CONTEXT_IMMEDIATE_BORDER attribute change could lead to strange issues in multi-threaded environments
5052             //since OpenVX standard says nothing about thread-safety for now
5053             ivx::border_t prevBorder = ctx.immediateBorder();
5054             ctx.setImmediateBorder(VX_BORDER_REPLICATE);
5055 #ifdef VX_VERSION_1_1
5056             if (ksize == 3)
5057 #endif
5058             {
5059                 ivx::IVX_CHECK_STATUS(vxuMedian3x3(ctx, ia, ib));
5060             }
5061 #ifdef VX_VERSION_1_1
5062             else
5063             {
5064                 ivx::Matrix mtx;
5065                 if(ksize == 5)
5066                     mtx = ivx::Matrix::createFromPattern(ctx, VX_PATTERN_BOX, ksize, ksize);
5067                 else
5068                 {
5069                     vx_size supportedSize;
5070                     ivx::IVX_CHECK_STATUS(vxQueryContext(ctx, VX_CONTEXT_NONLINEAR_MAX_DIMENSION, &supportedSize, sizeof(supportedSize)));
5071                     if ((vx_size)ksize > supportedSize)
5072                     {
5073                         ctx.setImmediateBorder(prevBorder);
5074                         return false;
5075                     }
5076                     Mat mask(ksize, ksize, CV_8UC1, Scalar(255));
5077                     mtx = ivx::Matrix::create(ctx, VX_TYPE_UINT8, ksize, ksize);
5078                     mtx.copyFrom(mask);
5079                 }
5080                 ivx::IVX_CHECK_STATUS(vxuNonLinearFilter(ctx, VX_NONLINEAR_FILTER_MEDIAN, ia, mtx, ib));
5081             }
5082 #endif
5083             ctx.setImmediateBorder(prevBorder);
5084         }
5085         catch (ivx::RuntimeError & e)
5086         {
5087             VX_DbgThrow(e.what());
5088         }
5089         catch (ivx::WrapperError & e)
5090         {
5091             VX_DbgThrow(e.what());
5092         }
5093
5094         return true;
5095     }
5096 }
5097 #endif
5098
5099 #ifdef HAVE_IPP
5100 namespace cv
5101 {
5102 static bool ipp_medianFilter(Mat &src0, Mat &dst, int ksize)
5103 {
5104     CV_INSTRUMENT_REGION_IPP()
5105
5106 #if IPP_VERSION_X100 < 201801
5107     // Degradations for big kernel
5108     if(ksize > 7)
5109         return false;
5110 #endif
5111
5112     {
5113         int         bufSize;
5114         IppiSize    dstRoiSize = ippiSize(dst.cols, dst.rows), maskSize = ippiSize(ksize, ksize);
5115         IppDataType ippType = ippiGetDataType(src0.type());
5116         int         channels = src0.channels();
5117         IppAutoBuffer<Ipp8u> buffer;
5118
5119         if(src0.isSubmatrix())
5120             return false;
5121
5122         Mat src;
5123         if(dst.data != src0.data)
5124             src = src0;
5125         else
5126             src0.copyTo(src);
5127
5128         if(ippiFilterMedianBorderGetBufferSize(dstRoiSize, maskSize, ippType, channels, &bufSize) < 0)
5129             return false;
5130
5131         buffer.allocate(bufSize);
5132
5133         switch(ippType)
5134         {
5135         case ipp8u:
5136             if(channels == 1)
5137                 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;
5138             else if(channels == 3)
5139                 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;
5140             else if(channels == 4)
5141                 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;
5142             else
5143                 return false;
5144         case ipp16u:
5145             if(channels == 1)
5146                 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;
5147             else if(channels == 3)
5148                 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;
5149             else if(channels == 4)
5150                 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;
5151             else
5152                 return false;
5153         case ipp16s:
5154             if(channels == 1)
5155                 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;
5156             else if(channels == 3)
5157                 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;
5158             else if(channels == 4)
5159                 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;
5160             else
5161                 return false;
5162         case ipp32f:
5163             if(channels == 1)
5164                 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;
5165             else
5166                 return false;
5167         default:
5168             return false;
5169         }
5170     }
5171 }
5172 }
5173 #endif
5174
5175 void cv::medianBlur( InputArray _src0, OutputArray _dst, int ksize )
5176 {
5177     CV_INSTRUMENT_REGION()
5178
5179     CV_Assert( (ksize % 2 == 1) && (_src0.dims() <= 2 ));
5180
5181     if( ksize <= 1 || _src0.empty() )
5182     {
5183         _src0.copyTo(_dst);
5184         return;
5185     }
5186
5187     CV_OCL_RUN(_dst.isUMat(),
5188                ocl_medianFilter(_src0,_dst, ksize))
5189
5190     Mat src0 = _src0.getMat();
5191     _dst.create( src0.size(), src0.type() );
5192     Mat dst = _dst.getMat();
5193
5194     CALL_HAL(medianBlur, cv_hal_medianBlur, src0.data, src0.step, dst.data, dst.step, src0.cols, src0.rows, src0.depth(),
5195              src0.channels(), ksize);
5196
5197     CV_OVX_RUN(true,
5198                openvx_medianFilter(_src0, _dst, ksize))
5199
5200     CV_IPP_RUN_FAST(ipp_medianFilter(src0, dst, ksize));
5201
5202 #ifdef HAVE_TEGRA_OPTIMIZATION
5203     if (tegra::useTegra() && tegra::medianBlur(src0, dst, ksize))
5204         return;
5205 #endif
5206
5207     bool useSortNet = ksize == 3 || (ksize == 5
5208 #if !(CV_SIMD128)
5209             && ( src0.depth() > CV_8U || src0.channels() == 2 || src0.channels() > 4 )
5210 #endif
5211         );
5212
5213     Mat src;
5214     if( useSortNet )
5215     {
5216         if( dst.data != src0.data )
5217             src = src0;
5218         else
5219             src0.copyTo(src);
5220
5221         if( src.depth() == CV_8U )
5222             medianBlur_SortNet<MinMax8u, MinMaxVec8u>( src, dst, ksize );
5223         else if( src.depth() == CV_16U )
5224             medianBlur_SortNet<MinMax16u, MinMaxVec16u>( src, dst, ksize );
5225         else if( src.depth() == CV_16S )
5226             medianBlur_SortNet<MinMax16s, MinMaxVec16s>( src, dst, ksize );
5227         else if( src.depth() == CV_32F )
5228             medianBlur_SortNet<MinMax32f, MinMaxVec32f>( src, dst, ksize );
5229         else
5230             CV_Error(CV_StsUnsupportedFormat, "");
5231
5232         return;
5233     }
5234     else
5235     {
5236         cv::copyMakeBorder( src0, src, 0, 0, ksize/2, ksize/2, BORDER_REPLICATE|BORDER_ISOLATED);
5237
5238         int cn = src0.channels();
5239         CV_Assert( src.depth() == CV_8U && (cn == 1 || cn == 3 || cn == 4) );
5240
5241         double img_size_mp = (double)(src0.total())/(1 << 20);
5242         if( ksize <= 3 + (img_size_mp < 1 ? 12 : img_size_mp < 4 ? 6 : 2)*
5243             (CV_SIMD128 && hasSIMD128() ? 1 : 3))
5244             medianBlur_8u_Om( src, dst, ksize );
5245         else
5246             medianBlur_8u_O1( src, dst, ksize );
5247     }
5248 }
5249
5250 /****************************************************************************************\
5251                                    Bilateral Filtering
5252 \****************************************************************************************/
5253
5254 namespace cv
5255 {
5256
5257 class BilateralFilter_8u_Invoker :
5258     public ParallelLoopBody
5259 {
5260 public:
5261     BilateralFilter_8u_Invoker(Mat& _dest, const Mat& _temp, int _radius, int _maxk,
5262         int* _space_ofs, float *_space_weight, float *_color_weight) :
5263         temp(&_temp), dest(&_dest), radius(_radius),
5264         maxk(_maxk), space_ofs(_space_ofs), space_weight(_space_weight), color_weight(_color_weight)
5265     {
5266     }
5267
5268     virtual void operator() (const Range& range) const CV_OVERRIDE
5269     {
5270         int i, j, cn = dest->channels(), k;
5271         Size size = dest->size();
5272 #if CV_SIMD128
5273         int CV_DECL_ALIGNED(16) buf[4];
5274         bool haveSIMD128 = hasSIMD128();
5275 #endif
5276
5277         for( i = range.start; i < range.end; i++ )
5278         {
5279             const uchar* sptr = temp->ptr(i+radius) + radius*cn;
5280             uchar* dptr = dest->ptr(i);
5281
5282             if( cn == 1 )
5283             {
5284                 for( j = 0; j < size.width; j++ )
5285                 {
5286                     float sum = 0, wsum = 0;
5287                     int val0 = sptr[j];
5288                     k = 0;
5289 #if CV_SIMD128
5290                     if( haveSIMD128 )
5291                     {
5292                         v_float32x4 _val0 = v_setall_f32(static_cast<float>(val0));
5293                         v_float32x4 vsumw = v_setzero_f32();
5294                         v_float32x4 vsumc = v_setzero_f32();
5295
5296                         for( ; k <= maxk - 4; k += 4 )
5297                         {
5298                             v_float32x4 _valF = v_float32x4(sptr[j + space_ofs[k]],
5299                                 sptr[j + space_ofs[k + 1]],
5300                                 sptr[j + space_ofs[k + 2]],
5301                                 sptr[j + space_ofs[k + 3]]);
5302                             v_float32x4 _val = v_abs(_valF - _val0);
5303                             v_store(buf, v_round(_val));
5304
5305                             v_float32x4 _cw = v_float32x4(color_weight[buf[0]],
5306                                 color_weight[buf[1]],
5307                                 color_weight[buf[2]],
5308                                 color_weight[buf[3]]);
5309                             v_float32x4 _sw = v_load(space_weight+k);
5310 #if defined(_MSC_VER) && _MSC_VER == 1700/* MSVS 2012 */ && CV_AVX
5311                             // details: https://github.com/opencv/opencv/issues/11004
5312                             vsumw += _cw * _sw;
5313                             vsumc += _cw * _sw * _valF;
5314 #else
5315                             v_float32x4 _w = _cw * _sw;
5316                             _cw = _w * _valF;
5317
5318                             vsumw += _w;
5319                             vsumc += _cw;
5320 #endif
5321                         }
5322                         float *bufFloat = (float*)buf;
5323                         v_float32x4 sum4 = v_reduce_sum4(vsumw, vsumc, vsumw, vsumc);
5324                         v_store(bufFloat, sum4);
5325                         sum += bufFloat[1];
5326                         wsum += bufFloat[0];
5327                     }
5328 #endif
5329                     for( ; k < maxk; k++ )
5330                     {
5331                         int val = sptr[j + space_ofs[k]];
5332                         float w = space_weight[k]*color_weight[std::abs(val - val0)];
5333                         sum += val*w;
5334                         wsum += w;
5335                     }
5336                     // overflow is not possible here => there is no need to use cv::saturate_cast
5337                     dptr[j] = (uchar)cvRound(sum/wsum);
5338                 }
5339             }
5340             else
5341             {
5342                 assert( cn == 3 );
5343                 for( j = 0; j < size.width*3; j += 3 )
5344                 {
5345                     float sum_b = 0, sum_g = 0, sum_r = 0, wsum = 0;
5346                     int b0 = sptr[j], g0 = sptr[j+1], r0 = sptr[j+2];
5347                     k = 0;
5348 #if CV_SIMD128
5349                     if( haveSIMD128 )
5350                     {
5351                         v_float32x4 vsumw = v_setzero_f32();
5352                         v_float32x4 vsumb = v_setzero_f32();
5353                         v_float32x4 vsumg = v_setzero_f32();
5354                         v_float32x4 vsumr = v_setzero_f32();
5355                         const v_float32x4 _b0 = v_setall_f32(static_cast<float>(b0));
5356                         const v_float32x4 _g0 = v_setall_f32(static_cast<float>(g0));
5357                         const v_float32x4 _r0 = v_setall_f32(static_cast<float>(r0));
5358
5359                         for( ; k <= maxk - 4; k += 4 )
5360                         {
5361                             const uchar* const sptr_k0  = sptr + j + space_ofs[k];
5362                             const uchar* const sptr_k1  = sptr + j + space_ofs[k+1];
5363                             const uchar* const sptr_k2  = sptr + j + space_ofs[k+2];
5364                             const uchar* const sptr_k3  = sptr + j + space_ofs[k+3];
5365
5366                             v_float32x4 __b = v_cvt_f32(v_reinterpret_as_s32(v_load_expand_q(sptr_k0)));
5367                             v_float32x4 __g = v_cvt_f32(v_reinterpret_as_s32(v_load_expand_q(sptr_k1)));
5368                             v_float32x4 __r = v_cvt_f32(v_reinterpret_as_s32(v_load_expand_q(sptr_k2)));
5369                             v_float32x4 __z = v_cvt_f32(v_reinterpret_as_s32(v_load_expand_q(sptr_k3)));
5370                             v_float32x4 _b, _g, _r, _z;
5371
5372                             v_transpose4x4(__b, __g, __r, __z, _b, _g, _r, _z);
5373
5374                             v_float32x4 bt = v_abs(_b -_b0);
5375                             v_float32x4 gt = v_abs(_g -_g0);
5376                             v_float32x4 rt = v_abs(_r -_r0);
5377
5378                             bt = rt + bt + gt;
5379                             v_store(buf, v_round(bt));
5380
5381                             v_float32x4 _w  = v_float32x4(color_weight[buf[0]],color_weight[buf[1]],
5382                                                     color_weight[buf[2]],color_weight[buf[3]]);
5383                             v_float32x4 _sw = v_load(space_weight+k);
5384
5385 #if defined(_MSC_VER) && _MSC_VER == 1700/* MSVS 2012 */ && CV_AVX
5386                             // details: https://github.com/opencv/opencv/issues/11004
5387                             vsumw += _w * _sw;
5388                             vsumb += _w * _sw * _b;
5389                             vsumg += _w * _sw * _g;
5390                             vsumr += _w * _sw * _r;
5391 #else
5392                             _w *= _sw;
5393                             _b *=  _w;
5394                             _g *=  _w;
5395                             _r *=  _w;
5396
5397                             vsumw += _w;
5398                             vsumb += _b;
5399                             vsumg += _g;
5400                             vsumr += _r;
5401 #endif
5402                         }
5403                         float *bufFloat = (float*)buf;
5404                         v_float32x4 sum4 = v_reduce_sum4(vsumw, vsumb, vsumg, vsumr);
5405                         v_store(bufFloat, sum4);
5406                         wsum += bufFloat[0];
5407                         sum_b += bufFloat[1];
5408                         sum_g += bufFloat[2];
5409                         sum_r += bufFloat[3];
5410                     }
5411 #endif
5412
5413                     for( ; k < maxk; k++ )
5414                     {
5415                         const uchar* sptr_k = sptr + j + space_ofs[k];
5416                         int b = sptr_k[0], g = sptr_k[1], r = sptr_k[2];
5417                         float w = space_weight[k]*color_weight[std::abs(b - b0) +
5418                                                                std::abs(g - g0) + std::abs(r - r0)];
5419                         sum_b += b*w; sum_g += g*w; sum_r += r*w;
5420                         wsum += w;
5421                     }
5422                     wsum = 1.f/wsum;
5423                     b0 = cvRound(sum_b*wsum);
5424                     g0 = cvRound(sum_g*wsum);
5425                     r0 = cvRound(sum_r*wsum);
5426                     dptr[j] = (uchar)b0; dptr[j+1] = (uchar)g0; dptr[j+2] = (uchar)r0;
5427                 }
5428             }
5429         }
5430     }
5431
5432 private:
5433     const Mat *temp;
5434     Mat *dest;
5435     int radius, maxk, *space_ofs;
5436     float *space_weight, *color_weight;
5437 };
5438
5439 #ifdef HAVE_OPENCL
5440
5441 static bool ocl_bilateralFilter_8u(InputArray _src, OutputArray _dst, int d,
5442                                    double sigma_color, double sigma_space,
5443                                    int borderType)
5444 {
5445 #ifdef __ANDROID__
5446     if (ocl::Device::getDefault().isNVidia())
5447         return false;
5448 #endif
5449
5450     int type = _src.type(), depth = CV_MAT_DEPTH(type), cn = CV_MAT_CN(type);
5451     int i, j, maxk, radius;
5452
5453     if (depth != CV_8U || cn > 4)
5454         return false;
5455
5456     if (sigma_color <= 0)
5457         sigma_color = 1;
5458     if (sigma_space <= 0)
5459         sigma_space = 1;
5460
5461     double gauss_color_coeff = -0.5 / (sigma_color * sigma_color);
5462     double gauss_space_coeff = -0.5 / (sigma_space * sigma_space);
5463
5464     if ( d <= 0 )
5465         radius = cvRound(sigma_space * 1.5);
5466     else
5467         radius = d / 2;
5468     radius = MAX(radius, 1);
5469     d = radius * 2 + 1;
5470
5471     UMat src = _src.getUMat(), dst = _dst.getUMat(), temp;
5472     if (src.u == dst.u)
5473         return false;
5474
5475     copyMakeBorder(src, temp, radius, radius, radius, radius, borderType);
5476     std::vector<float> _space_weight(d * d);
5477     std::vector<int> _space_ofs(d * d);
5478     float * const space_weight = &_space_weight[0];
5479     int * const space_ofs = &_space_ofs[0];
5480
5481     // initialize space-related bilateral filter coefficients
5482     for( i = -radius, maxk = 0; i <= radius; i++ )
5483         for( j = -radius; j <= radius; j++ )
5484         {
5485             double r = std::sqrt((double)i * i + (double)j * j);
5486             if ( r > radius )
5487                 continue;
5488             space_weight[maxk] = (float)std::exp(r * r * gauss_space_coeff);
5489             space_ofs[maxk++] = (int)(i * temp.step + j * cn);
5490         }
5491
5492     char cvt[3][40];
5493     String cnstr = cn > 1 ? format("%d", cn) : "";
5494     String kernelName("bilateral");
5495     size_t sizeDiv = 1;
5496     if ((ocl::Device::getDefault().isIntel()) &&
5497         (ocl::Device::getDefault().type() == ocl::Device::TYPE_GPU))
5498     {
5499             //Intel GPU
5500             if (dst.cols % 4 == 0 && cn == 1) // For single channel x4 sized images.
5501             {
5502                 kernelName = "bilateral_float4";
5503                 sizeDiv = 4;
5504             }
5505      }
5506      ocl::Kernel k(kernelName.c_str(), ocl::imgproc::bilateral_oclsrc,
5507             format("-D radius=%d -D maxk=%d -D cn=%d -D int_t=%s -D uint_t=uint%s -D convert_int_t=%s"
5508             " -D uchar_t=%s -D float_t=%s -D convert_float_t=%s -D convert_uchar_t=%s -D gauss_color_coeff=(float)%f",
5509             radius, maxk, cn, ocl::typeToStr(CV_32SC(cn)), cnstr.c_str(),
5510             ocl::convertTypeStr(CV_8U, CV_32S, cn, cvt[0]),
5511             ocl::typeToStr(type), ocl::typeToStr(CV_32FC(cn)),
5512             ocl::convertTypeStr(CV_32S, CV_32F, cn, cvt[1]),
5513             ocl::convertTypeStr(CV_32F, CV_8U, cn, cvt[2]), gauss_color_coeff));
5514     if (k.empty())
5515         return false;
5516
5517     Mat mspace_weight(1, d * d, CV_32FC1, space_weight);
5518     Mat mspace_ofs(1, d * d, CV_32SC1, space_ofs);
5519     UMat ucolor_weight, uspace_weight, uspace_ofs;
5520
5521     mspace_weight.copyTo(uspace_weight);
5522     mspace_ofs.copyTo(uspace_ofs);
5523
5524     k.args(ocl::KernelArg::ReadOnlyNoSize(temp), ocl::KernelArg::WriteOnly(dst),
5525            ocl::KernelArg::PtrReadOnly(uspace_weight),
5526            ocl::KernelArg::PtrReadOnly(uspace_ofs));
5527
5528     size_t globalsize[2] = { (size_t)dst.cols / sizeDiv, (size_t)dst.rows };
5529     return k.run(2, globalsize, NULL, false);
5530 }
5531
5532 #endif
5533 static void
5534 bilateralFilter_8u( const Mat& src, Mat& dst, int d,
5535     double sigma_color, double sigma_space,
5536     int borderType )
5537 {
5538     int cn = src.channels();
5539     int i, j, maxk, radius;
5540     Size size = src.size();
5541
5542     CV_Assert( (src.type() == CV_8UC1 || src.type() == CV_8UC3) && src.data != dst.data );
5543
5544     if( sigma_color <= 0 )
5545         sigma_color = 1;
5546     if( sigma_space <= 0 )
5547         sigma_space = 1;
5548
5549     double gauss_color_coeff = -0.5/(sigma_color*sigma_color);
5550     double gauss_space_coeff = -0.5/(sigma_space*sigma_space);
5551
5552     if( d <= 0 )
5553         radius = cvRound(sigma_space*1.5);
5554     else
5555         radius = d/2;
5556     radius = MAX(radius, 1);
5557     d = radius*2 + 1;
5558
5559     Mat temp;
5560     copyMakeBorder( src, temp, radius, radius, radius, radius, borderType );
5561
5562     std::vector<float> _color_weight(cn*256);
5563     std::vector<float> _space_weight(d*d);
5564     std::vector<int> _space_ofs(d*d);
5565     float* color_weight = &_color_weight[0];
5566     float* space_weight = &_space_weight[0];
5567     int* space_ofs = &_space_ofs[0];
5568
5569     // initialize color-related bilateral filter coefficients
5570
5571     for( i = 0; i < 256*cn; i++ )
5572         color_weight[i] = (float)std::exp(i*i*gauss_color_coeff);
5573
5574     // initialize space-related bilateral filter coefficients
5575     for( i = -radius, maxk = 0; i <= radius; i++ )
5576     {
5577         j = -radius;
5578
5579         for( ; j <= radius; j++ )
5580         {
5581             double r = std::sqrt((double)i*i + (double)j*j);
5582             if( r > radius )
5583                 continue;
5584             space_weight[maxk] = (float)std::exp(r*r*gauss_space_coeff);
5585             space_ofs[maxk++] = (int)(i*temp.step + j*cn);
5586         }
5587     }
5588
5589     BilateralFilter_8u_Invoker body(dst, temp, radius, maxk, space_ofs, space_weight, color_weight);
5590     parallel_for_(Range(0, size.height), body, dst.total()/(double)(1<<16));
5591 }
5592
5593
5594 class BilateralFilter_32f_Invoker :
5595     public ParallelLoopBody
5596 {
5597 public:
5598
5599     BilateralFilter_32f_Invoker(int _cn, int _radius, int _maxk, int *_space_ofs,
5600         const Mat& _temp, Mat& _dest, float _scale_index, float *_space_weight, float *_expLUT) :
5601         cn(_cn), radius(_radius), maxk(_maxk), space_ofs(_space_ofs),
5602         temp(&_temp), dest(&_dest), scale_index(_scale_index), space_weight(_space_weight), expLUT(_expLUT)
5603     {
5604     }
5605
5606     virtual void operator() (const Range& range) const CV_OVERRIDE
5607     {
5608         int i, j, k;
5609         Size size = dest->size();
5610 #if CV_SIMD128
5611         int CV_DECL_ALIGNED(16) idxBuf[4];
5612         bool haveSIMD128 = hasSIMD128();
5613 #endif
5614
5615         for( i = range.start; i < range.end; i++ )
5616         {
5617             const float* sptr = temp->ptr<float>(i+radius) + radius*cn;
5618             float* dptr = dest->ptr<float>(i);
5619
5620             if( cn == 1 )
5621             {
5622                 for( j = 0; j < size.width; j++ )
5623                 {
5624                     float sum = 0, wsum = 0;
5625                     float val0 = sptr[j];
5626                     k = 0;
5627 #if CV_SIMD128
5628                     if( haveSIMD128 )
5629                     {
5630                         v_float32x4 vecwsum = v_setzero_f32();
5631                         v_float32x4 vecvsum = v_setzero_f32();
5632                         const v_float32x4 _val0 = v_setall_f32(sptr[j]);
5633                         const v_float32x4 _scale_index = v_setall_f32(scale_index);
5634
5635                         for (; k <= maxk - 4; k += 4)
5636                         {
5637                             v_float32x4 _sw = v_load(space_weight + k);
5638                             v_float32x4 _val = v_float32x4(sptr[j + space_ofs[k]],
5639                                 sptr[j + space_ofs[k + 1]],
5640                                 sptr[j + space_ofs[k + 2]],
5641                                 sptr[j + space_ofs[k + 3]]);
5642                             v_float32x4 _alpha = v_abs(_val - _val0) * _scale_index;
5643
5644                             v_int32x4 _idx = v_round(_alpha);
5645                             v_store(idxBuf, _idx);
5646                             _alpha -= v_cvt_f32(_idx);
5647
5648                             v_float32x4 _explut = v_float32x4(expLUT[idxBuf[0]],
5649                                 expLUT[idxBuf[1]],
5650                                 expLUT[idxBuf[2]],
5651                                 expLUT[idxBuf[3]]);
5652                             v_float32x4 _explut1 = v_float32x4(expLUT[idxBuf[0] + 1],
5653                                 expLUT[idxBuf[1] + 1],
5654                                 expLUT[idxBuf[2] + 1],
5655                                 expLUT[idxBuf[3] + 1]);
5656
5657                             v_float32x4 _w = _sw * (_explut + (_alpha * (_explut1 - _explut)));
5658                             _val *= _w;
5659
5660                             vecwsum += _w;
5661                             vecvsum += _val;
5662                         }
5663                         float *bufFloat = (float*)idxBuf;
5664                         v_float32x4 sum4 = v_reduce_sum4(vecwsum, vecvsum, vecwsum, vecvsum);
5665                         v_store(bufFloat, sum4);
5666                         sum += bufFloat[1];
5667                         wsum += bufFloat[0];
5668                     }
5669 #endif
5670
5671                     for( ; k < maxk; k++ )
5672                     {
5673                         float val = sptr[j + space_ofs[k]];
5674                         float alpha = (float)(std::abs(val - val0)*scale_index);
5675                         int idx = cvFloor(alpha);
5676                         alpha -= idx;
5677                         float w = space_weight[k]*(expLUT[idx] + alpha*(expLUT[idx+1] - expLUT[idx]));
5678                         sum += val*w;
5679                         wsum += w;
5680                     }
5681                     dptr[j] = (float)(sum/wsum);
5682                 }
5683             }
5684             else
5685             {
5686                 CV_Assert( cn == 3 );
5687                 for( j = 0; j < size.width*3; j += 3 )
5688                 {
5689                     float sum_b = 0, sum_g = 0, sum_r = 0, wsum = 0;
5690                     float b0 = sptr[j], g0 = sptr[j+1], r0 = sptr[j+2];
5691                     k = 0;
5692 #if CV_SIMD128
5693                     if( haveSIMD128 )
5694                     {
5695                         v_float32x4 sumw = v_setzero_f32();
5696                         v_float32x4 sumb = v_setzero_f32();
5697                         v_float32x4 sumg = v_setzero_f32();
5698                         v_float32x4 sumr = v_setzero_f32();
5699                         const v_float32x4 _b0 = v_setall_f32(b0);
5700                         const v_float32x4 _g0 = v_setall_f32(g0);
5701                         const v_float32x4 _r0 = v_setall_f32(r0);
5702                         const v_float32x4 _scale_index = v_setall_f32(scale_index);
5703
5704                         for( ; k <= maxk-4; k += 4 )
5705                         {
5706                             v_float32x4 _sw = v_load(space_weight + k);
5707
5708                             const float* const sptr_k0 = sptr + j + space_ofs[k];
5709                             const float* const sptr_k1 = sptr + j + space_ofs[k+1];
5710                             const float* const sptr_k2 = sptr + j + space_ofs[k+2];
5711                             const float* const sptr_k3 = sptr + j + space_ofs[k+3];
5712
5713                             v_float32x4 _v0 = v_load(sptr_k0);
5714                             v_float32x4 _v1 = v_load(sptr_k1);
5715                             v_float32x4 _v2 = v_load(sptr_k2);
5716                             v_float32x4 _v3 = v_load(sptr_k3);
5717                             v_float32x4 _b, _g, _r, _dummy;
5718
5719                             v_transpose4x4(_v0, _v1, _v2, _v3, _b, _g, _r, _dummy);
5720
5721                             v_float32x4 _bt = v_abs(_b - _b0);
5722                             v_float32x4 _gt = v_abs(_g - _g0);
5723                             v_float32x4 _rt = v_abs(_r - _r0);
5724                             v_float32x4 _alpha = _scale_index * (_bt + _gt + _rt);
5725
5726                             v_int32x4 _idx = v_round(_alpha);
5727                             v_store((int*)idxBuf, _idx);
5728                             _alpha -= v_cvt_f32(_idx);
5729
5730                             v_float32x4 _explut = v_float32x4(expLUT[idxBuf[0]],
5731                                 expLUT[idxBuf[1]],
5732                                 expLUT[idxBuf[2]],
5733                                 expLUT[idxBuf[3]]);
5734                             v_float32x4 _explut1 = v_float32x4(expLUT[idxBuf[0] + 1],
5735                                 expLUT[idxBuf[1] + 1],
5736                                 expLUT[idxBuf[2] + 1],
5737                                 expLUT[idxBuf[3] + 1]);
5738
5739                             v_float32x4 _w = _sw * (_explut + (_alpha * (_explut1 - _explut)));
5740
5741                             _b *=  _w;
5742                             _g *=  _w;
5743                             _r *=  _w;
5744                             sumw += _w;
5745                             sumb += _b;
5746                             sumg += _g;
5747                             sumr += _r;
5748                         }
5749                         v_float32x4 sum4 = v_reduce_sum4(sumw, sumb, sumg, sumr);
5750                         float *bufFloat = (float*)idxBuf;
5751                         v_store(bufFloat, sum4);
5752                         wsum += bufFloat[0];
5753                         sum_b += bufFloat[1];
5754                         sum_g += bufFloat[2];
5755                         sum_r += bufFloat[3];
5756                     }
5757 #endif
5758
5759                     for(; k < maxk; k++ )
5760                     {
5761                         const float* sptr_k = sptr + j + space_ofs[k];
5762                         float b = sptr_k[0], g = sptr_k[1], r = sptr_k[2];
5763                         float alpha = (float)((std::abs(b - b0) +
5764                             std::abs(g - g0) + std::abs(r - r0))*scale_index);
5765                         int idx = cvFloor(alpha);
5766                         alpha -= idx;
5767                         float w = space_weight[k]*(expLUT[idx] + alpha*(expLUT[idx+1] - expLUT[idx]));
5768                         sum_b += b*w; sum_g += g*w; sum_r += r*w;
5769                         wsum += w;
5770                     }
5771                     wsum = 1.f/wsum;
5772                     b0 = sum_b*wsum;
5773                     g0 = sum_g*wsum;
5774                     r0 = sum_r*wsum;
5775                     dptr[j] = b0; dptr[j+1] = g0; dptr[j+2] = r0;
5776                 }
5777             }
5778         }
5779     }
5780
5781 private:
5782     int cn, radius, maxk, *space_ofs;
5783     const Mat* temp;
5784     Mat *dest;
5785     float scale_index, *space_weight, *expLUT;
5786 };
5787
5788
5789 static void
5790 bilateralFilter_32f( const Mat& src, Mat& dst, int d,
5791                      double sigma_color, double sigma_space,
5792                      int borderType )
5793 {
5794     int cn = src.channels();
5795     int i, j, maxk, radius;
5796     double minValSrc=-1, maxValSrc=1;
5797     const int kExpNumBinsPerChannel = 1 << 12;
5798     int kExpNumBins = 0;
5799     float lastExpVal = 1.f;
5800     float len, scale_index;
5801     Size size = src.size();
5802
5803     CV_Assert( (src.type() == CV_32FC1 || src.type() == CV_32FC3) && src.data != dst.data );
5804
5805     if( sigma_color <= 0 )
5806         sigma_color = 1;
5807     if( sigma_space <= 0 )
5808         sigma_space = 1;
5809
5810     double gauss_color_coeff = -0.5/(sigma_color*sigma_color);
5811     double gauss_space_coeff = -0.5/(sigma_space*sigma_space);
5812
5813     if( d <= 0 )
5814         radius = cvRound(sigma_space*1.5);
5815     else
5816         radius = d/2;
5817     radius = MAX(radius, 1);
5818     d = radius*2 + 1;
5819     // compute the min/max range for the input image (even if multichannel)
5820
5821     minMaxLoc( src.reshape(1), &minValSrc, &maxValSrc );
5822     if(std::abs(minValSrc - maxValSrc) < FLT_EPSILON)
5823     {
5824         src.copyTo(dst);
5825         return;
5826     }
5827
5828     // temporary copy of the image with borders for easy processing
5829     Mat temp;
5830     copyMakeBorder( src, temp, radius, radius, radius, radius, borderType );
5831     const double insteadNaNValue = -5. * sigma_color;
5832     patchNaNs( temp, insteadNaNValue ); // this replacement of NaNs makes the assumption that depth values are nonnegative
5833                                         // TODO: make insteadNaNValue avalible in the outside function interface to control the cases breaking the assumption
5834     // allocate lookup tables
5835     std::vector<float> _space_weight(d*d);
5836     std::vector<int> _space_ofs(d*d);
5837     float* space_weight = &_space_weight[0];
5838     int* space_ofs = &_space_ofs[0];
5839
5840     // assign a length which is slightly more than needed
5841     len = (float)(maxValSrc - minValSrc) * cn;
5842     kExpNumBins = kExpNumBinsPerChannel * cn;
5843     std::vector<float> _expLUT(kExpNumBins+2);
5844     float* expLUT = &_expLUT[0];
5845
5846     scale_index = kExpNumBins/len;
5847
5848     // initialize the exp LUT
5849     for( i = 0; i < kExpNumBins+2; i++ )
5850     {
5851         if( lastExpVal > 0.f )
5852         {
5853             double val =  i / scale_index;
5854             expLUT[i] = (float)std::exp(val * val * gauss_color_coeff);
5855             lastExpVal = expLUT[i];
5856         }
5857         else
5858             expLUT[i] = 0.f;
5859     }
5860
5861     // initialize space-related bilateral filter coefficients
5862     for( i = -radius, maxk = 0; i <= radius; i++ )
5863         for( j = -radius; j <= radius; j++ )
5864         {
5865             double r = std::sqrt((double)i*i + (double)j*j);
5866             if( r > radius )
5867                 continue;
5868             space_weight[maxk] = (float)std::exp(r*r*gauss_space_coeff);
5869             space_ofs[maxk++] = (int)(i*(temp.step/sizeof(float)) + j*cn);
5870         }
5871
5872     // parallel_for usage
5873
5874     BilateralFilter_32f_Invoker body(cn, radius, maxk, space_ofs, temp, dst, scale_index, space_weight, expLUT);
5875     parallel_for_(Range(0, size.height), body, dst.total()/(double)(1<<16));
5876 }
5877
5878 #ifdef HAVE_IPP
5879 #define IPP_BILATERAL_PARALLEL 1
5880
5881 #ifdef HAVE_IPP_IW
5882 class ipp_bilateralFilterParallel: public ParallelLoopBody
5883 {
5884 public:
5885     ipp_bilateralFilterParallel(::ipp::IwiImage &_src, ::ipp::IwiImage &_dst, int _radius, Ipp32f _valSquareSigma, Ipp32f _posSquareSigma, ::ipp::IwiBorderType _borderType, bool *_ok):
5886         src(_src), dst(_dst)
5887     {
5888         pOk = _ok;
5889
5890         radius          = _radius;
5891         valSquareSigma  = _valSquareSigma;
5892         posSquareSigma  = _posSquareSigma;
5893         borderType      = _borderType;
5894
5895         *pOk = true;
5896     }
5897     ~ipp_bilateralFilterParallel() {}
5898
5899     virtual void operator() (const Range& range) const CV_OVERRIDE
5900     {
5901         if(*pOk == false)
5902             return;
5903
5904         try
5905         {
5906             ::ipp::IwiTile tile = ::ipp::IwiRoi(0, range.start, dst.m_size.width, range.end - range.start);
5907             CV_INSTRUMENT_FUN_IPP(::ipp::iwiFilterBilateral, src, dst, radius, valSquareSigma, posSquareSigma, ::ipp::IwDefault(), borderType, tile);
5908         }
5909         catch(::ipp::IwException)
5910         {
5911             *pOk = false;
5912             return;
5913         }
5914     }
5915 private:
5916     ::ipp::IwiImage &src;
5917     ::ipp::IwiImage &dst;
5918
5919     int                  radius;
5920     Ipp32f               valSquareSigma;
5921     Ipp32f               posSquareSigma;
5922     ::ipp::IwiBorderType borderType;
5923
5924     bool  *pOk;
5925     const ipp_bilateralFilterParallel& operator= (const ipp_bilateralFilterParallel&);
5926 };
5927 #endif
5928
5929 static bool ipp_bilateralFilter(Mat &src, Mat &dst, int d, double sigmaColor, double sigmaSpace, int borderType)
5930 {
5931 #ifdef HAVE_IPP_IW
5932     CV_INSTRUMENT_REGION_IPP()
5933
5934     int         radius         = IPP_MAX(((d <= 0)?cvRound(sigmaSpace*1.5):d/2), 1);
5935     Ipp32f      valSquareSigma = (Ipp32f)((sigmaColor <= 0)?1:sigmaColor*sigmaColor);
5936     Ipp32f      posSquareSigma = (Ipp32f)((sigmaSpace <= 0)?1:sigmaSpace*sigmaSpace);
5937
5938     // Acquire data and begin processing
5939     try
5940     {
5941         ::ipp::IwiImage      iwSrc = ippiGetImage(src);
5942         ::ipp::IwiImage      iwDst = ippiGetImage(dst);
5943         ::ipp::IwiBorderSize borderSize(radius);
5944         ::ipp::IwiBorderType ippBorder(ippiGetBorder(iwSrc, borderType, borderSize));
5945         if(!ippBorder)
5946             return false;
5947
5948         const int threads = ippiSuggestThreadsNum(iwDst, 2);
5949         if(IPP_BILATERAL_PARALLEL && threads > 1) {
5950             bool  ok      = true;
5951             Range range(0, (int)iwDst.m_size.height);
5952             ipp_bilateralFilterParallel invoker(iwSrc, iwDst, radius, valSquareSigma, posSquareSigma, ippBorder, &ok);
5953             if(!ok)
5954                 return false;
5955
5956             parallel_for_(range, invoker, threads*4);
5957
5958             if(!ok)
5959                 return false;
5960         } else {
5961             CV_INSTRUMENT_FUN_IPP(::ipp::iwiFilterBilateral, iwSrc, iwDst, radius, valSquareSigma, posSquareSigma, ::ipp::IwDefault(), ippBorder);
5962         }
5963     }
5964     catch (::ipp::IwException)
5965     {
5966         return false;
5967     }
5968     return true;
5969 #else
5970     CV_UNUSED(src); CV_UNUSED(dst); CV_UNUSED(d); CV_UNUSED(sigmaColor); CV_UNUSED(sigmaSpace); CV_UNUSED(borderType);
5971     return false;
5972 #endif
5973 }
5974 #endif
5975
5976 }
5977
5978 void cv::bilateralFilter( InputArray _src, OutputArray _dst, int d,
5979                       double sigmaColor, double sigmaSpace,
5980                       int borderType )
5981 {
5982     CV_INSTRUMENT_REGION()
5983
5984     _dst.create( _src.size(), _src.type() );
5985
5986     CV_OCL_RUN(_src.dims() <= 2 && _dst.isUMat(),
5987                ocl_bilateralFilter_8u(_src, _dst, d, sigmaColor, sigmaSpace, borderType))
5988
5989     Mat src = _src.getMat(), dst = _dst.getMat();
5990
5991     CV_IPP_RUN_FAST(ipp_bilateralFilter(src, dst, d, sigmaColor, sigmaSpace, borderType));
5992
5993     if( src.depth() == CV_8U )
5994         bilateralFilter_8u( src, dst, d, sigmaColor, sigmaSpace, borderType );
5995     else if( src.depth() == CV_32F )
5996         bilateralFilter_32f( src, dst, d, sigmaColor, sigmaSpace, borderType );
5997     else
5998         CV_Error( CV_StsUnsupportedFormat,
5999         "Bilateral filtering is only implemented for 8u and 32f images" );
6000 }
6001
6002 //////////////////////////////////////////////////////////////////////////////////////////
6003
6004 CV_IMPL void
6005 cvSmooth( const void* srcarr, void* dstarr, int smooth_type,
6006           int param1, int param2, double param3, double param4 )
6007 {
6008     cv::Mat src = cv::cvarrToMat(srcarr), dst0 = cv::cvarrToMat(dstarr), dst = dst0;
6009
6010     CV_Assert( dst.size() == src.size() &&
6011         (smooth_type == CV_BLUR_NO_SCALE || dst.type() == src.type()) );
6012
6013     if( param2 <= 0 )
6014         param2 = param1;
6015
6016     if( smooth_type == CV_BLUR || smooth_type == CV_BLUR_NO_SCALE )
6017         cv::boxFilter( src, dst, dst.depth(), cv::Size(param1, param2), cv::Point(-1,-1),
6018             smooth_type == CV_BLUR, cv::BORDER_REPLICATE );
6019     else if( smooth_type == CV_GAUSSIAN )
6020         cv::GaussianBlur( src, dst, cv::Size(param1, param2), param3, param4, cv::BORDER_REPLICATE );
6021     else if( smooth_type == CV_MEDIAN )
6022         cv::medianBlur( src, dst, param1 );
6023     else
6024         cv::bilateralFilter( src, dst, param1, param3, param4, cv::BORDER_REPLICATE );
6025
6026     if( dst.data != dst0.data )
6027         CV_Error( CV_StsUnmatchedFormats, "The destination image does not have the proper type" );
6028 }
6029
6030 /* End of file. */