Merge pull request #1796 from ilya-lavrenov:ocl_cvtColor
[profile/ivi/opencv.git] / modules / ocl / src / imgproc.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) 2010-2012, Institute Of Software Chinese Academy Of Science, all rights reserved.
14 // Copyright (C) 2010-2012, Advanced Micro Devices, Inc., all rights reserved.
15 // Copyright (C) 2010-2012, Multicoreware, Inc., all rights reserved.
16 // Third party copyrights are property of their respective owners.
17 //
18 // @Authors
19 //    Niko Li, newlife20080214@gmail.com
20 //    Jia Haipeng, jiahaipeng95@gmail.com
21 //    Shengen Yan, yanshengen@gmail.com
22 //    Rock Li, Rock.Li@amd.com
23 //    Zero Lin, Zero.Lin@amd.com
24 //    Zhang Ying, zhangying913@gmail.com
25 //    Xu Pang, pangxu010@163.com
26 //    Wu Zailong, bullet@yeah.net
27 //    Wenju He, wenju@multicorewareinc.com
28 //    Sen Liu, swjtuls1987@126.com
29 //
30 // Redistribution and use in source and binary forms, with or without modification,
31 // are permitted provided that the following conditions are met:
32 //
33 //   * Redistribution's of source code must retain the above copyright notice,
34 //     this list of conditions and the following disclaimer.
35 //
36 //   * Redistribution's in binary form must reproduce the above copyright notice,
37 //     this list of conditions and the following disclaimer in the documentation
38 //     and/or other materials provided with the distribution.
39 //
40 //   * The name of the copyright holders may not be used to endorse or promote products
41 //     derived from this software without specific prior written permission.
42 //
43 // This software is provided by the copyright holders and contributors "as is" and
44 // any express or implied warranties, including, but not limited to, the implied
45 // warranties of merchantability and fitness for a particular purpose are disclaimed.
46 // In no event shall the Intel Corporation or contributors be liable for any direct,
47 // indirect, incidental, special, exemplary, or consequential damages
48 // (including, but not limited to, procurement of substitute goods or services;
49 // loss of use, data, or profits; or business interruption) however caused
50 // and on any theory of liability, whether in contract, strict liability,
51 // or tort (including negligence or otherwise) arising in any way out of
52 // the use of this software, even if advised of the possibility of such damage.
53 //
54 //M*/
55
56 #include "precomp.hpp"
57 #include "opencl_kernels.hpp"
58
59 using namespace cv;
60 using namespace cv::ocl;
61
62 namespace cv
63 {
64     namespace ocl
65     {
66         ////////////////////////////////////OpenCL call wrappers////////////////////////////
67
68         template <typename T> struct index_and_sizeof;
69         template <> struct index_and_sizeof<char>
70         {
71             enum { index = 1 };
72         };
73         template <> struct index_and_sizeof<unsigned char>
74         {
75             enum { index = 2 };
76         };
77         template <> struct index_and_sizeof<short>
78         {
79             enum { index = 3 };
80         };
81         template <> struct index_and_sizeof<unsigned short>
82         {
83             enum { index = 4 };
84         };
85         template <> struct index_and_sizeof<int>
86         {
87             enum { index = 5 };
88         };
89         template <> struct index_and_sizeof<float>
90         {
91             enum { index = 6 };
92         };
93         template <> struct index_and_sizeof<double>
94         {
95             enum { index = 7 };
96         };
97
98         /////////////////////////////////////////////////////////////////////////////////////
99         // threshold
100
101         static std::vector<uchar> scalarToVector(const cv::Scalar & sc, int depth, int ocn, int cn)
102         {
103             CV_Assert(ocn == cn || (ocn == 4 && cn == 3));
104
105             static const int sizeMap[] = { sizeof(uchar), sizeof(char), sizeof(ushort),
106                                        sizeof(short), sizeof(int), sizeof(float), sizeof(double) };
107
108             int elemSize1 = sizeMap[depth];
109             int bufSize = elemSize1 * ocn;
110             std::vector<uchar> _buf(bufSize);
111             uchar * buf = &_buf[0];
112             scalarToRawData(sc, buf, CV_MAKE_TYPE(depth, cn));
113             memset(buf + elemSize1 * cn, 0, (ocn - cn) * elemSize1);
114
115             return _buf;
116         }
117
118         static void threshold_runner(const oclMat &src, oclMat &dst, double thresh, double maxVal, int thresholdType)
119         {
120             bool ival = src.depth() < CV_32F;
121             int cn = src.channels(), vecSize = 4, depth = src.depth();
122             std::vector<uchar> thresholdValue = scalarToVector(cv::Scalar::all(ival ? cvFloor(thresh) : thresh), dst.depth(),
123                                                                dst.oclchannels(), dst.channels());
124             std::vector<uchar> maxValue = scalarToVector(cv::Scalar::all(maxVal), dst.depth(), dst.oclchannels(), dst.channels());
125
126             const char * const thresholdMap[] = { "THRESH_BINARY", "THRESH_BINARY_INV", "THRESH_TRUNC",
127                                                   "THRESH_TOZERO", "THRESH_TOZERO_INV" };
128             const char * const channelMap[] = { "", "", "2", "4", "4" };
129             const char * const typeMap[] = { "uchar", "char", "ushort", "short", "int", "float", "double" };
130             std::string buildOptions = format("-D T=%s%s -D %s", typeMap[depth], channelMap[cn], thresholdMap[thresholdType]);
131
132             int elemSize = src.elemSize();
133             int src_step = src.step / elemSize, src_offset = src.offset / elemSize;
134             int dst_step = dst.step / elemSize, dst_offset = dst.offset / elemSize;
135
136             vector< pair<size_t, const void *> > args;
137             args.push_back( make_pair(sizeof(cl_mem), (void *)&src.data));
138             args.push_back( make_pair(sizeof(cl_int), (void *)&src_offset));
139             args.push_back( make_pair(sizeof(cl_int), (void *)&src_step));
140             args.push_back( make_pair(sizeof(cl_mem), (void *)&dst.data));
141             args.push_back( make_pair(sizeof(cl_int), (void *)&dst_offset));
142             args.push_back( make_pair(sizeof(cl_int), (void *)&dst_step));
143             args.push_back( make_pair(thresholdValue.size(), (void *)&thresholdValue[0]));
144             args.push_back( make_pair(maxValue.size(), (void *)&maxValue[0]));
145
146             int max_index = dst.cols, cols = dst.cols;
147             if (cn == 1 && vecSize > 1)
148             {
149                 CV_Assert(((vecSize - 1) & vecSize) == 0 && vecSize <= 16);
150                 cols = divUp(cols, vecSize);
151                 buildOptions += format(" -D VECTORIZED -D VT=%s%d -D VLOADN=vload%d -D VECSIZE=%d -D VSTOREN=vstore%d",
152                                        typeMap[depth], vecSize, vecSize, vecSize, vecSize);
153
154                 int vecSizeBytes = vecSize * dst.elemSize1();
155                 if ((dst.offset % dst.step) % vecSizeBytes == 0 && dst.step % vecSizeBytes == 0)
156                     buildOptions += " -D DST_ALIGNED";
157                 if ((src.offset % src.step) % vecSizeBytes == 0 && src.step % vecSizeBytes == 0)
158                     buildOptions += " -D SRC_ALIGNED";
159
160                 args.push_back( make_pair(sizeof(cl_int), (void *)&max_index));
161             }
162
163             args.push_back( make_pair(sizeof(cl_int), (void *)&dst.rows));
164             args.push_back( make_pair(sizeof(cl_int), (void *)&cols));
165
166             size_t localThreads[3] = { 16, 16, 1 };
167             size_t globalThreads[3] = { cols, dst.rows, 1 };
168
169             openCLExecuteKernel(src.clCxt, &imgproc_threshold, "threshold", globalThreads, localThreads, args,
170                                 -1, -1, buildOptions.c_str());
171         }
172
173         double threshold(const oclMat &src, oclMat &dst, double thresh, double maxVal, int thresholdType)
174         {
175             CV_Assert(thresholdType == THRESH_BINARY || thresholdType == THRESH_BINARY_INV || thresholdType == THRESH_TRUNC
176                       || thresholdType == THRESH_TOZERO || thresholdType == THRESH_TOZERO_INV);
177
178             dst.create(src.size(), src.type());
179             threshold_runner(src, dst, thresh, maxVal, thresholdType);
180
181             return thresh;
182         }
183
184         ////////////////////////////////////////////////////////////////////////////////////////////
185         ///////////////////////////////   remap   //////////////////////////////////////////////////
186         ////////////////////////////////////////////////////////////////////////////////////////////
187
188         void remap( const oclMat &src, oclMat &dst, oclMat &map1, oclMat &map2, int interpolation, int borderType, const Scalar &borderValue )
189         {
190             Context *clCxt = src.clCxt;
191             bool supportsDouble = clCxt->supportsFeature(FEATURE_CL_DOUBLE);
192             if (!supportsDouble && src.depth() == CV_64F)
193             {
194                 CV_Error(CV_OpenCLDoubleNotSupported, "Selected device does not support double");
195                 return;
196             }
197
198             if (map1.empty())
199                 map1.swap(map2);
200
201             CV_Assert(interpolation == INTER_LINEAR || interpolation == INTER_NEAREST);
202             CV_Assert((map1.type() == CV_16SC2 && (map2.empty() || (map2.type() == CV_16UC1 || map2.type() == CV_16SC1)) ) ||
203                       (map1.type() == CV_32FC2 && !map2.data) ||
204                       (map1.type() == CV_32FC1 && map2.type() == CV_32FC1));
205             CV_Assert(!map2.data || map2.size() == map1.size());
206             CV_Assert(borderType == BORDER_CONSTANT || borderType == BORDER_REPLICATE || borderType == BORDER_WRAP
207                       || borderType == BORDER_REFLECT_101 || borderType == BORDER_REFLECT);
208
209             dst.create(map1.size(), src.type());
210
211             const char * const typeMap[] = { "uchar", "char", "ushort", "short", "int", "float", "double" };
212             const char * const channelMap[] = { "", "", "2", "4", "4" };
213             const char * const interMap[] = { "INTER_NEAREST", "INTER_LINEAR", "INTER_CUBIC", "INTER_LINEAR", "INTER_LANCZOS" };
214             const char * const borderMap[] = { "BORDER_CONSTANT", "BORDER_REPLICATE", "BORDER_REFLECT", "BORDER_WRAP",
215                                    "BORDER_REFLECT_101", "BORDER_TRANSPARENT" };
216
217             string kernelName = "remap";
218             if (map1.type() == CV_32FC2 && map2.empty())
219                 kernelName += "_32FC2";
220             else if (map1.type() == CV_16SC2)
221             {
222                 kernelName += "_16SC2";
223                 if (!map2.empty())
224                     kernelName += "_16UC1";
225             }
226             else if (map1.type() == CV_32FC1 && map2.type() == CV_32FC1)
227                 kernelName += "_2_32FC1";
228             else
229                 CV_Error(CV_StsBadArg, "Unsupported map types");
230
231             int ocn = dst.oclchannels();
232             size_t localThreads[3] = { 256, 1, 1 };
233             size_t globalThreads[3] = { dst.cols, dst.rows, 1 };
234
235             Mat scalar(1, 1, CV_MAKE_TYPE(dst.depth(), ocn), borderValue);
236             std::string buildOptions = format("-D %s -D %s -D T=%s%s", interMap[interpolation],
237                                               borderMap[borderType], typeMap[src.depth()], channelMap[ocn]);
238
239             if (interpolation != INTER_NEAREST)
240             {
241                 int wdepth = std::max(CV_32F, dst.depth());
242                 buildOptions += format(" -D WT=%s%s -D convertToT=convert_%s%s%s -D convertToWT=convert_%s%s"
243                                        " -D convertToWT2=convert_%s2 -D WT2=%s2",
244                                        typeMap[wdepth], channelMap[ocn],
245                                        typeMap[src.depth()], channelMap[ocn], src.depth() < CV_32F ? "_sat_rte" : "",
246                                        typeMap[wdepth], channelMap[ocn],
247                                        typeMap[wdepth], typeMap[wdepth]);
248             }
249
250             int src_step = src.step / src.elemSize(), src_offset = src.offset / src.elemSize();
251             int map1_step = map1.step / map1.elemSize(), map1_offset = map1.offset / map1.elemSize();
252             int map2_step = map2.step / map2.elemSize(), map2_offset = map2.offset / map2.elemSize();
253             int dst_step = dst.step / dst.elemSize(), dst_offset = dst.offset / dst.elemSize();
254
255             vector< pair<size_t, const void *> > args;
256             args.push_back( make_pair(sizeof(cl_mem), (void *)&src.data));
257             args.push_back( make_pair(sizeof(cl_mem), (void *)&dst.data));
258             args.push_back( make_pair(sizeof(cl_mem), (void *)&map1.data));
259             if (!map2.empty())
260                 args.push_back( make_pair(sizeof(cl_mem), (void *)&map2.data));
261             args.push_back( make_pair(sizeof(cl_int), (void *)&src_offset));
262             args.push_back( make_pair(sizeof(cl_int), (void *)&dst_offset));
263             args.push_back( make_pair(sizeof(cl_int), (void *)&map1_offset));
264             if (!map2.empty())
265                 args.push_back( make_pair(sizeof(cl_int), (void *)&map2_offset));
266             args.push_back( make_pair(sizeof(cl_int), (void *)&src_step));
267             args.push_back( make_pair(sizeof(cl_int), (void *)&dst_step));
268             args.push_back( make_pair(sizeof(cl_int), (void *)&map1_step));
269             if (!map2.empty())
270                 args.push_back( make_pair(sizeof(cl_int), (void *)&map2_step));
271             args.push_back( make_pair(sizeof(cl_int), (void *)&src.cols));
272             args.push_back( make_pair(sizeof(cl_int), (void *)&src.rows));
273             args.push_back( make_pair(sizeof(cl_int), (void *)&dst.cols));
274             args.push_back( make_pair(sizeof(cl_int), (void *)&dst.rows));
275             args.push_back( make_pair(scalar.elemSize(), (void *)scalar.data));
276
277             openCLExecuteKernel(clCxt, &imgproc_remap, kernelName, globalThreads, localThreads, args, -1, -1, buildOptions.c_str());
278         }
279
280         ////////////////////////////////////////////////////////////////////////////////////////////
281         // resize
282
283         static void resize_gpu( const oclMat &src, oclMat &dst, double fx, double fy, int interpolation)
284         {
285             CV_Assert( (src.channels() == dst.channels()) );
286             Context *clCxt = src.clCxt;
287             float ifx = 1. / fx;
288             float ify = 1. / fy;
289             double ifx_d = 1. / fx;
290             double ify_d = 1. / fy;
291             int srcStep_in_pixel = src.step1() / src.oclchannels();
292             int srcoffset_in_pixel = src.offset / src.elemSize();
293             int dstStep_in_pixel = dst.step1() / dst.oclchannels();
294             int dstoffset_in_pixel = dst.offset / dst.elemSize();
295
296             string kernelName;
297             if (interpolation == INTER_LINEAR)
298                 kernelName = "resizeLN";
299             else if (interpolation == INTER_NEAREST)
300                 kernelName = "resizeNN";
301
302             //TODO: improve this kernel
303             size_t blkSizeX = 16, blkSizeY = 16;
304             size_t glbSizeX;
305             if (src.type() == CV_8UC1)
306             {
307                 size_t cols = (dst.cols + dst.offset % 4 + 3) / 4;
308                 glbSizeX = cols % blkSizeX == 0 && cols != 0 ? cols : (cols / blkSizeX + 1) * blkSizeX;
309             }
310             else
311                 glbSizeX = dst.cols % blkSizeX == 0 && dst.cols != 0 ? dst.cols : (dst.cols / blkSizeX + 1) * blkSizeX;
312
313             size_t glbSizeY = dst.rows % blkSizeY == 0 && dst.rows != 0 ? dst.rows : (dst.rows / blkSizeY + 1) * blkSizeY;
314             size_t globalThreads[3] = {glbSizeX, glbSizeY, 1};
315             size_t localThreads[3] = {blkSizeX, blkSizeY, 1};
316
317             vector< pair<size_t, const void *> > args;
318             if (interpolation == INTER_NEAREST)
319             {
320                 args.push_back( make_pair(sizeof(cl_mem), (void *)&dst.data));
321                 args.push_back( make_pair(sizeof(cl_mem), (void *)&src.data));
322                 args.push_back( make_pair(sizeof(cl_int), (void *)&dstoffset_in_pixel));
323                 args.push_back( make_pair(sizeof(cl_int), (void *)&srcoffset_in_pixel));
324                 args.push_back( make_pair(sizeof(cl_int), (void *)&dstStep_in_pixel));
325                 args.push_back( make_pair(sizeof(cl_int), (void *)&srcStep_in_pixel));
326                 args.push_back( make_pair(sizeof(cl_int), (void *)&src.cols));
327                 args.push_back( make_pair(sizeof(cl_int), (void *)&src.rows));
328                 args.push_back( make_pair(sizeof(cl_int), (void *)&dst.cols));
329                 args.push_back( make_pair(sizeof(cl_int), (void *)&dst.rows));
330                 if (src.clCxt->supportsFeature(FEATURE_CL_DOUBLE))
331                 {
332                     args.push_back( make_pair(sizeof(cl_double), (void *)&ifx_d));
333                     args.push_back( make_pair(sizeof(cl_double), (void *)&ify_d));
334                 }
335                 else
336                 {
337                     args.push_back( make_pair(sizeof(cl_float), (void *)&ifx));
338                     args.push_back( make_pair(sizeof(cl_float), (void *)&ify));
339                 }
340             }
341             else
342             {
343                 args.push_back( make_pair(sizeof(cl_mem), (void *)&dst.data));
344                 args.push_back( make_pair(sizeof(cl_mem), (void *)&src.data));
345                 args.push_back( make_pair(sizeof(cl_int), (void *)&dstoffset_in_pixel));
346                 args.push_back( make_pair(sizeof(cl_int), (void *)&srcoffset_in_pixel));
347                 args.push_back( make_pair(sizeof(cl_int), (void *)&dstStep_in_pixel));
348                 args.push_back( make_pair(sizeof(cl_int), (void *)&srcStep_in_pixel));
349                 args.push_back( make_pair(sizeof(cl_int), (void *)&src.cols));
350                 args.push_back( make_pair(sizeof(cl_int), (void *)&src.rows));
351                 args.push_back( make_pair(sizeof(cl_int), (void *)&dst.cols));
352                 args.push_back( make_pair(sizeof(cl_int), (void *)&dst.rows));
353                 args.push_back( make_pair(sizeof(cl_float), (void *)&ifx));
354                 args.push_back( make_pair(sizeof(cl_float), (void *)&ify));
355             }
356
357             openCLExecuteKernel(clCxt, &imgproc_resize, kernelName, globalThreads, localThreads, args, src.oclchannels(), src.depth());
358         }
359
360         void resize(const oclMat &src, oclMat &dst, Size dsize,
361                     double fx, double fy, int interpolation)
362         {
363             CV_Assert(src.type() == CV_8UC1 || src.type() == CV_8UC3 || src.type() == CV_8UC4
364                       || src.type() == CV_32FC1 || src.type() == CV_32FC3 || src.type() == CV_32FC4);
365             CV_Assert(interpolation == INTER_LINEAR || interpolation == INTER_NEAREST);
366             CV_Assert( src.size().area() > 0 );
367             CV_Assert( !(dsize == Size()) || (fx > 0 && fy > 0) );
368
369             if (!(dsize == Size()) && (fx > 0 && fy > 0))
370                 if (dsize.width != (int)(src.cols * fx) || dsize.height != (int)(src.rows * fy))
371                     CV_Error(CV_StsUnmatchedSizes, "invalid dsize and fx, fy!");
372
373             if ( dsize == Size() )
374                 dsize = Size(saturate_cast<int>(src.cols * fx), saturate_cast<int>(src.rows * fy));
375             else
376             {
377                 fx = (double)dsize.width / src.cols;
378                 fy = (double)dsize.height / src.rows;
379             }
380
381             dst.create(dsize, src.type());
382
383             if ( interpolation == INTER_NEAREST || interpolation == INTER_LINEAR )
384             {
385                 resize_gpu( src, dst, fx, fy, interpolation);
386                 return;
387             }
388
389             CV_Error(CV_StsUnsupportedFormat, "Non-supported interpolation method");
390         }
391
392         ////////////////////////////////////////////////////////////////////////
393         // medianFilter
394
395         void medianFilter(const oclMat &src, oclMat &dst, int m)
396         {
397             CV_Assert( m % 2 == 1 && m > 1 );
398             CV_Assert( (src.depth() == CV_8U || src.depth() == CV_32F) && (src.channels() == 1 || src.channels() == 4));
399             dst.create(src.size(), src.type());
400
401             int srcStep = src.step / src.elemSize(), dstStep = dst.step / dst.elemSize();
402             int srcOffset = src.offset /  src.elemSize(), dstOffset = dst.offset / dst.elemSize();
403
404             Context *clCxt = src.clCxt;
405
406             vector< pair<size_t, const void *> > args;
407             args.push_back( make_pair( sizeof(cl_mem), (void *)&src.data));
408             args.push_back( make_pair( sizeof(cl_mem), (void *)&dst.data));
409             args.push_back( make_pair( sizeof(cl_int), (void *)&srcOffset));
410             args.push_back( make_pair( sizeof(cl_int), (void *)&dstOffset));
411             args.push_back( make_pair( sizeof(cl_int), (void *)&src.cols));
412             args.push_back( make_pair( sizeof(cl_int), (void *)&src.rows));
413             args.push_back( make_pair( sizeof(cl_int), (void *)&srcStep));
414             args.push_back( make_pair( sizeof(cl_int), (void *)&dstStep));
415
416             size_t globalThreads[3] = {(src.cols + 18) / 16 * 16, (src.rows + 15) / 16 * 16, 1};
417             size_t localThreads[3] = {16, 16, 1};
418
419             if (m == 3)
420             {
421                 string kernelName = "medianFilter3";
422                 openCLExecuteKernel(clCxt, &imgproc_median, kernelName, globalThreads, localThreads, args, src.oclchannels(), src.depth());
423             }
424             else if (m == 5)
425             {
426                 string kernelName = "medianFilter5";
427                 openCLExecuteKernel(clCxt, &imgproc_median, kernelName, globalThreads, localThreads, args, src.oclchannels(), src.depth());
428             }
429             else
430                 CV_Error(CV_StsBadArg, "Non-supported filter length");
431         }
432
433         ////////////////////////////////////////////////////////////////////////
434         // copyMakeBorder
435
436         void copyMakeBorder(const oclMat &src, oclMat &dst, int top, int bottom, int left, int right, int bordertype, const Scalar &scalar)
437         {
438             if (!src.clCxt->supportsFeature(FEATURE_CL_DOUBLE) && src.depth() == CV_64F)
439             {
440                 CV_Error(CV_OpenCLDoubleNotSupported, "Selected device does not support double");
441                 return;
442             }
443
444             oclMat _src = src;
445
446             CV_Assert(top >= 0 && bottom >= 0 && left >= 0 && right >= 0);
447
448             if( (_src.wholecols != _src.cols || _src.wholerows != _src.rows) && (bordertype & BORDER_ISOLATED) == 0 )
449             {
450                 Size wholeSize;
451                 Point ofs;
452                 _src.locateROI(wholeSize, ofs);
453                 int dtop = std::min(ofs.y, top);
454                 int dbottom = std::min(wholeSize.height - _src.rows - ofs.y, bottom);
455                 int dleft = std::min(ofs.x, left);
456                 int dright = std::min(wholeSize.width - _src.cols - ofs.x, right);
457                 _src.adjustROI(dtop, dbottom, dleft, dright);
458                 top -= dtop;
459                 left -= dleft;
460                 bottom -= dbottom;
461                 right -= dright;
462             }
463             bordertype &= ~cv::BORDER_ISOLATED;
464
465             dst.create(_src.rows + top + bottom, _src.cols + left + right, _src.type());
466             int srcStep = _src.step / _src.elemSize(),  dstStep = dst.step / dst.elemSize();
467             int srcOffset = _src.offset / _src.elemSize(), dstOffset = dst.offset / dst.elemSize();
468             int depth = _src.depth(), ochannels = _src.oclchannels();
469
470             int __bordertype[] = { BORDER_CONSTANT, BORDER_REPLICATE, BORDER_REFLECT, BORDER_WRAP, BORDER_REFLECT_101 };
471             const char *borderstr[] = { "BORDER_CONSTANT", "BORDER_REPLICATE", "BORDER_REFLECT", "BORDER_WRAP", "BORDER_REFLECT_101" };
472
473             int bordertype_index = -1;
474             for (int i = 0, end = sizeof(__bordertype) / sizeof(int); i < end; i++)
475                 if (__bordertype[i] == bordertype)
476                 {
477                     bordertype_index = i;
478                     break;
479                 }
480             if (bordertype_index < 0)
481                 CV_Error(CV_StsBadArg, "Unsupported border type");
482
483             size_t localThreads[3] = { 16, 16, 1 };
484             size_t globalThreads[3] = { dst.cols, dst.rows, 1 };
485
486             vector< pair<size_t, const void *> > args;
487             args.push_back( make_pair( sizeof(cl_mem), (void *)&_src.data));
488             args.push_back( make_pair( sizeof(cl_mem), (void *)&dst.data));
489             args.push_back( make_pair( sizeof(cl_int), (void *)&dst.cols));
490             args.push_back( make_pair( sizeof(cl_int), (void *)&dst.rows));
491             args.push_back( make_pair( sizeof(cl_int), (void *)&_src.cols));
492             args.push_back( make_pair( sizeof(cl_int), (void *)&_src.rows));
493             args.push_back( make_pair( sizeof(cl_int), (void *)&srcStep));
494             args.push_back( make_pair( sizeof(cl_int), (void *)&srcOffset));
495             args.push_back( make_pair( sizeof(cl_int), (void *)&dstStep));
496             args.push_back( make_pair( sizeof(cl_int), (void *)&dstOffset));
497             args.push_back( make_pair( sizeof(cl_int), (void *)&top));
498             args.push_back( make_pair( sizeof(cl_int), (void *)&left));
499
500             const char * const typeMap[] = { "uchar", "char", "ushort", "short", "int", "float", "double" };
501             const char * const channelMap[] = { "", "", "2", "4", "4" };
502             std::string buildOptions = format("-D GENTYPE=%s%s -D %s",
503                                               typeMap[depth], channelMap[ochannels],
504                                               borderstr[bordertype_index]);
505
506             int cn = src.channels(), ocn = src.oclchannels();
507             int bufSize = src.elemSize1() * ocn;
508             AutoBuffer<uchar> _buf(bufSize);
509             uchar * buf = (uchar *)_buf;
510             scalarToRawData(scalar, buf, dst.type());
511             memset(buf + src.elemSize1() * cn, 0, (ocn - cn) * src.elemSize1());
512
513             args.push_back( make_pair( bufSize , (void *)buf ));
514
515             openCLExecuteKernel(src.clCxt, &imgproc_copymakeboder, "copymakeborder", globalThreads,
516                                 localThreads, args, -1, -1, buildOptions.c_str());
517         }
518
519         ////////////////////////////////////////////////////////////////////////
520         // warp
521
522         namespace
523         {
524 #define F double
525
526             void convert_coeffs(F *M)
527             {
528                 double D = M[0] * M[4] - M[1] * M[3];
529                 D = D != 0 ? 1. / D : 0;
530                 double A11 = M[4] * D, A22 = M[0] * D;
531                 M[0] = A11;
532                 M[1] *= -D;
533                 M[3] *= -D;
534                 M[4] = A22;
535                 double b1 = -M[0] * M[2] - M[1] * M[5];
536                 double b2 = -M[3] * M[2] - M[4] * M[5];
537                 M[2] = b1;
538                 M[5] = b2;
539             }
540
541             double invert(double *M)
542             {
543 #define Sd(y,x) (Sd[y*3+x])
544 #define Dd(y,x) (Dd[y*3+x])
545 #define det3(m)    (m(0,0)*(m(1,1)*m(2,2) - m(1,2)*m(2,1)) -  \
546                     m(0,1)*(m(1,0)*m(2,2) - m(1,2)*m(2,0)) +  \
547                     m(0,2)*(m(1,0)*m(2,1) - m(1,1)*m(2,0)))
548                 double *Sd = M;
549                 double *Dd = M;
550                 double d = det3(Sd);
551                 double result = 0;
552                 if ( d != 0)
553                 {
554                     double t[9];
555                     result = d;
556                     d = 1. / d;
557
558                     t[0] = (Sd(1, 1) * Sd(2, 2) - Sd(1, 2) * Sd(2, 1)) * d;
559                     t[1] = (Sd(0, 2) * Sd(2, 1) - Sd(0, 1) * Sd(2, 2)) * d;
560                     t[2] = (Sd(0, 1) * Sd(1, 2) - Sd(0, 2) * Sd(1, 1)) * d;
561
562                     t[3] = (Sd(1, 2) * Sd(2, 0) - Sd(1, 0) * Sd(2, 2)) * d;
563                     t[4] = (Sd(0, 0) * Sd(2, 2) - Sd(0, 2) * Sd(2, 0)) * d;
564                     t[5] = (Sd(0, 2) * Sd(1, 0) - Sd(0, 0) * Sd(1, 2)) * d;
565
566                     t[6] = (Sd(1, 0) * Sd(2, 1) - Sd(1, 1) * Sd(2, 0)) * d;
567                     t[7] = (Sd(0, 1) * Sd(2, 0) - Sd(0, 0) * Sd(2, 1)) * d;
568                     t[8] = (Sd(0, 0) * Sd(1, 1) - Sd(0, 1) * Sd(1, 0)) * d;
569
570                     Dd(0, 0) = t[0];
571                     Dd(0, 1) = t[1];
572                     Dd(0, 2) = t[2];
573                     Dd(1, 0) = t[3];
574                     Dd(1, 1) = t[4];
575                     Dd(1, 2) = t[5];
576                     Dd(2, 0) = t[6];
577                     Dd(2, 1) = t[7];
578                     Dd(2, 2) = t[8];
579                 }
580                 return result;
581             }
582
583             void warpAffine_gpu(const oclMat &src, oclMat &dst, F coeffs[2][3], int interpolation)
584             {
585                 CV_Assert( (src.oclchannels() == dst.oclchannels()) );
586                 int srcStep = src.step1();
587                 int dstStep = dst.step1();
588                 float float_coeffs[2][3];
589                 cl_mem coeffs_cm;
590
591                 Context *clCxt = src.clCxt;
592                 string s[3] = {"NN", "Linear", "Cubic"};
593                 string kernelName = "warpAffine" + s[interpolation];
594
595                 if (src.clCxt->supportsFeature(FEATURE_CL_DOUBLE))
596                 {
597                     cl_int st;
598                     coeffs_cm = clCreateBuffer(*(cl_context*)clCxt->getOpenCLContextPtr(), CL_MEM_READ_WRITE, sizeof(F) * 2 * 3, NULL, &st );
599                     openCLVerifyCall(st);
600                     openCLSafeCall(clEnqueueWriteBuffer(*(cl_command_queue*)clCxt->getOpenCLCommandQueuePtr(), (cl_mem)coeffs_cm, 1, 0,
601                                                         sizeof(F) * 2 * 3, coeffs, 0, 0, 0));
602                 }
603                 else
604                 {
605                     cl_int st;
606                     for(int m = 0; m < 2; m++)
607                         for(int n = 0; n < 3; n++)
608                             float_coeffs[m][n] = coeffs[m][n];
609
610                     coeffs_cm = clCreateBuffer(*(cl_context*)clCxt->getOpenCLContextPtr(), CL_MEM_READ_WRITE, sizeof(float) * 2 * 3, NULL, &st );
611                     openCLSafeCall(clEnqueueWriteBuffer(*(cl_command_queue*)clCxt->getOpenCLCommandQueuePtr(), (cl_mem)coeffs_cm,
612                                                         1, 0, sizeof(float) * 2 * 3, float_coeffs, 0, 0, 0));
613
614                 }
615                 //TODO: improve this kernel
616                 size_t blkSizeX = 16, blkSizeY = 16;
617                 size_t glbSizeX;
618                 size_t cols;
619
620                 if (src.type() == CV_8UC1 && interpolation != 2)
621                 {
622                     cols = (dst.cols + dst.offset % 4 + 3) / 4;
623                     glbSizeX = cols % blkSizeX == 0 ? cols : (cols / blkSizeX + 1) * blkSizeX;
624                 }
625                 else
626                 {
627                     cols = dst.cols;
628                     glbSizeX = dst.cols % blkSizeX == 0 ? dst.cols : (dst.cols / blkSizeX + 1) * blkSizeX;
629                 }
630
631                 size_t glbSizeY = dst.rows % blkSizeY == 0 ? dst.rows : (dst.rows / blkSizeY + 1) * blkSizeY;
632                 size_t globalThreads[3] = {glbSizeX, glbSizeY, 1};
633                 size_t localThreads[3] = {blkSizeX, blkSizeY, 1};
634
635                 vector< pair<size_t, const void *> > args;
636
637                 args.push_back(make_pair(sizeof(cl_mem), (void *)&src.data));
638                 args.push_back(make_pair(sizeof(cl_mem), (void *)&dst.data));
639                 args.push_back(make_pair(sizeof(cl_int), (void *)&src.cols));
640                 args.push_back(make_pair(sizeof(cl_int), (void *)&src.rows));
641                 args.push_back(make_pair(sizeof(cl_int), (void *)&dst.cols));
642                 args.push_back(make_pair(sizeof(cl_int), (void *)&dst.rows));
643                 args.push_back(make_pair(sizeof(cl_int), (void *)&srcStep));
644                 args.push_back(make_pair(sizeof(cl_int), (void *)&dstStep));
645                 args.push_back(make_pair(sizeof(cl_int), (void *)&src.offset));
646                 args.push_back(make_pair(sizeof(cl_int), (void *)&dst.offset));
647                 args.push_back(make_pair(sizeof(cl_mem), (void *)&coeffs_cm));
648                 args.push_back(make_pair(sizeof(cl_int), (void *)&cols));
649
650                 openCLExecuteKernel(clCxt, &imgproc_warpAffine, kernelName, globalThreads, localThreads, args, src.oclchannels(), src.depth());
651                 openCLSafeCall(clReleaseMemObject(coeffs_cm));
652             }
653
654             void warpPerspective_gpu(const oclMat &src, oclMat &dst, double coeffs[3][3], int interpolation)
655             {
656                 CV_Assert( (src.oclchannels() == dst.oclchannels()) );
657                 int srcStep = src.step1();
658                 int dstStep = dst.step1();
659                 float float_coeffs[3][3];
660                 cl_mem coeffs_cm;
661
662                 Context *clCxt = src.clCxt;
663                 string s[3] = {"NN", "Linear", "Cubic"};
664                 string kernelName = "warpPerspective" + s[interpolation];
665
666                 if (src.clCxt->supportsFeature(FEATURE_CL_DOUBLE))
667                 {
668                     cl_int st;
669                     coeffs_cm = clCreateBuffer(*(cl_context*)clCxt->getOpenCLContextPtr(), CL_MEM_READ_WRITE, sizeof(double) * 3 * 3, NULL, &st );
670                     openCLVerifyCall(st);
671                     openCLSafeCall(clEnqueueWriteBuffer(*(cl_command_queue*)clCxt->getOpenCLCommandQueuePtr(), (cl_mem)coeffs_cm, 1, 0,
672                                                         sizeof(double) * 3 * 3, coeffs, 0, 0, 0));
673                 }
674                 else
675                 {
676                     cl_int st;
677                     for(int m = 0; m < 3; m++)
678                         for(int n = 0; n < 3; n++)
679                             float_coeffs[m][n] = coeffs[m][n];
680
681                     coeffs_cm = clCreateBuffer(*(cl_context*)clCxt->getOpenCLContextPtr(), CL_MEM_READ_WRITE, sizeof(float) * 3 * 3, NULL, &st );
682                     openCLVerifyCall(st);
683                     openCLSafeCall(clEnqueueWriteBuffer(*(cl_command_queue*)clCxt->getOpenCLCommandQueuePtr(), (cl_mem)coeffs_cm, 1, 0,
684                                                         sizeof(float) * 3 * 3, float_coeffs, 0, 0, 0));
685                 }
686
687                 //TODO: improve this kernel
688                 size_t blkSizeX = 16, blkSizeY = 16;
689                 size_t glbSizeX;
690                 size_t cols;
691                 if (src.type() == CV_8UC1 && interpolation == 0)
692                 {
693                     cols = (dst.cols + dst.offset % 4 + 3) / 4;
694                     glbSizeX = cols % blkSizeX == 0 ? cols : (cols / blkSizeX + 1) * blkSizeX;
695                 }
696                 else
697                 {
698                     cols = dst.cols;
699                     glbSizeX = dst.cols % blkSizeX == 0 ? dst.cols : (dst.cols / blkSizeX + 1) * blkSizeX;
700                 }
701
702                 size_t glbSizeY = dst.rows % blkSizeY == 0 ? dst.rows : (dst.rows / blkSizeY + 1) * blkSizeY;
703                 size_t globalThreads[3] = {glbSizeX, glbSizeY, 1};
704                 size_t localThreads[3] = {blkSizeX, blkSizeY, 1};
705
706                 vector< pair<size_t, const void *> > args;
707
708                 args.push_back(make_pair(sizeof(cl_mem), (void *)&src.data));
709                 args.push_back(make_pair(sizeof(cl_mem), (void *)&dst.data));
710                 args.push_back(make_pair(sizeof(cl_int), (void *)&src.cols));
711                 args.push_back(make_pair(sizeof(cl_int), (void *)&src.rows));
712                 args.push_back(make_pair(sizeof(cl_int), (void *)&dst.cols));
713                 args.push_back(make_pair(sizeof(cl_int), (void *)&dst.rows));
714                 args.push_back(make_pair(sizeof(cl_int), (void *)&srcStep));
715                 args.push_back(make_pair(sizeof(cl_int), (void *)&dstStep));
716                 args.push_back(make_pair(sizeof(cl_int), (void *)&src.offset));
717                 args.push_back(make_pair(sizeof(cl_int), (void *)&dst.offset));
718                 args.push_back(make_pair(sizeof(cl_mem), (void *)&coeffs_cm));
719                 args.push_back(make_pair(sizeof(cl_int), (void *)&cols));
720
721                 openCLExecuteKernel(clCxt, &imgproc_warpPerspective, kernelName, globalThreads, localThreads, args, src.oclchannels(), src.depth());
722                 openCLSafeCall(clReleaseMemObject(coeffs_cm));
723             }
724         }
725
726         void warpAffine(const oclMat &src, oclMat &dst, const Mat &M, Size dsize, int flags)
727         {
728             int interpolation = flags & INTER_MAX;
729
730             CV_Assert((src.depth() == CV_8U  || src.depth() == CV_32F) && src.oclchannels() != 2 && src.oclchannels() != 3);
731             CV_Assert(interpolation == INTER_NEAREST || interpolation == INTER_LINEAR || interpolation == INTER_CUBIC);
732
733             dst.create(dsize, src.type());
734
735             CV_Assert(M.rows == 2 && M.cols == 3);
736
737             int warpInd = (flags & WARP_INVERSE_MAP) >> 4;
738             F coeffs[2][3];
739
740             double coeffsM[2*3];
741             Mat coeffsMat(2, 3, CV_64F, (void *)coeffsM);
742             M.convertTo(coeffsMat, coeffsMat.type());
743             if (!warpInd)
744                 convert_coeffs(coeffsM);
745
746             for(int i = 0; i < 2; ++i)
747                 for(int j = 0; j < 3; ++j)
748                     coeffs[i][j] = coeffsM[i*3+j];
749
750             warpAffine_gpu(src, dst, coeffs, interpolation);
751         }
752
753         void warpPerspective(const oclMat &src, oclMat &dst, const Mat &M, Size dsize, int flags)
754         {
755             int interpolation = flags & INTER_MAX;
756
757             CV_Assert((src.depth() == CV_8U  || src.depth() == CV_32F) && src.oclchannels() != 2 && src.oclchannels() != 3);
758             CV_Assert(interpolation == INTER_NEAREST || interpolation == INTER_LINEAR || interpolation == INTER_CUBIC);
759
760             dst.create(dsize, src.type());
761
762
763             CV_Assert(M.rows == 3 && M.cols == 3);
764
765             int warpInd = (flags & WARP_INVERSE_MAP) >> 4;
766             double coeffs[3][3];
767
768             double coeffsM[3*3];
769             Mat coeffsMat(3, 3, CV_64F, (void *)coeffsM);
770             M.convertTo(coeffsMat, coeffsMat.type());
771             if (!warpInd)
772                 invert(coeffsM);
773
774             for(int i = 0; i < 3; ++i)
775                 for(int j = 0; j < 3; ++j)
776                     coeffs[i][j] = coeffsM[i*3+j];
777
778             warpPerspective_gpu(src, dst, coeffs, interpolation);
779         }
780
781         ////////////////////////////////////////////////////////////////////////
782         // integral
783
784         void integral(const oclMat &src, oclMat &sum, oclMat &sqsum, int sdepth)
785         {
786             CV_Assert(src.type() == CV_8UC1);
787             if (!src.clCxt->supportsFeature(ocl::FEATURE_CL_DOUBLE) && src.depth() == CV_64F)
788             {
789                 CV_Error(CV_OpenCLDoubleNotSupported, "Select device doesn't support double");
790                 return;
791             }
792
793             if( sdepth <= 0 )
794                 sdepth = CV_32S;
795             sdepth = CV_MAT_DEPTH(sdepth);
796             int type = CV_MAKE_TYPE(sdepth, 1);
797
798             int vlen = 4;
799             int offset = src.offset / vlen;
800             int pre_invalid = src.offset % vlen;
801             int vcols = (pre_invalid + src.cols + vlen - 1) / vlen;
802
803             oclMat t_sum , t_sqsum;
804             int w = src.cols + 1, h = src.rows + 1;
805
806             char build_option[250];
807             if(Context::getContext()->supportsFeature(ocl::FEATURE_CL_DOUBLE))
808             {
809                 t_sqsum.create(src.cols, src.rows, CV_64FC1);
810                 sqsum.create(h, w, CV_64FC1);
811                 sprintf(build_option, "-D TYPE=double -D TYPE4=double4 -D convert_TYPE4=convert_double4");
812             }
813             else
814             {
815                 t_sqsum.create(src.cols, src.rows, CV_32FC1);
816                 sqsum.create(h, w, CV_32FC1);
817                 sprintf(build_option, "-D TYPE=float -D TYPE4=float4 -D convert_TYPE4=convert_float4");
818             }
819
820             t_sum.create(src.cols, src.rows, type);
821             sum.create(h, w, type);
822
823             int sum_offset = sum.offset / sum.elemSize();
824             int sqsum_offset = sqsum.offset / sqsum.elemSize();
825
826             vector<pair<size_t , const void *> > args;
827             args.push_back( make_pair( sizeof(cl_mem) , (void *)&src.data ));
828             args.push_back( make_pair( sizeof(cl_mem) , (void *)&t_sum.data ));
829             args.push_back( make_pair( sizeof(cl_mem) , (void *)&t_sqsum.data ));
830             args.push_back( make_pair( sizeof(cl_int) , (void *)&offset ));
831             args.push_back( make_pair( sizeof(cl_int) , (void *)&pre_invalid ));
832             args.push_back( make_pair( sizeof(cl_int) , (void *)&src.rows ));
833             args.push_back( make_pair( sizeof(cl_int) , (void *)&src.cols ));
834             args.push_back( make_pair( sizeof(cl_int) , (void *)&src.step ));
835             args.push_back( make_pair( sizeof(cl_int) , (void *)&t_sum.step));
836             args.push_back( make_pair( sizeof(cl_int) , (void *)&t_sqsum.step));
837             size_t gt[3] = {((vcols + 1) / 2) * 256, 1, 1}, lt[3] = {256, 1, 1};
838             openCLExecuteKernel(src.clCxt, &imgproc_integral, "integral_cols", gt, lt, args, -1, sdepth, build_option);
839
840             args.clear();
841             args.push_back( make_pair( sizeof(cl_mem) , (void *)&t_sum.data ));
842             args.push_back( make_pair( sizeof(cl_mem) , (void *)&t_sqsum.data ));
843             args.push_back( make_pair( sizeof(cl_mem) , (void *)&sum.data ));
844             args.push_back( make_pair( sizeof(cl_mem) , (void *)&sqsum.data ));
845             args.push_back( make_pair( sizeof(cl_int) , (void *)&t_sum.rows ));
846             args.push_back( make_pair( sizeof(cl_int) , (void *)&t_sum.cols ));
847             args.push_back( make_pair( sizeof(cl_int) , (void *)&t_sum.step ));
848             args.push_back( make_pair( sizeof(cl_int) , (void *)&t_sqsum.step));
849             args.push_back( make_pair( sizeof(cl_int) , (void *)&sum.step));
850             args.push_back( make_pair( sizeof(cl_int) , (void *)&sqsum.step));
851             args.push_back( make_pair( sizeof(cl_int) , (void *)&sum_offset));
852             args.push_back( make_pair( sizeof(cl_int) , (void *)&sqsum_offset));
853             size_t gt2[3] = {t_sum.cols  * 32, 1, 1}, lt2[3] = {256, 1, 1};
854             openCLExecuteKernel(src.clCxt, &imgproc_integral, "integral_rows", gt2, lt2, args, -1, sdepth, build_option);
855         }
856
857         void integral(const oclMat &src, oclMat &sum, int sdepth)
858         {
859             CV_Assert(src.type() == CV_8UC1);
860             int vlen = 4;
861             int offset = src.offset / vlen;
862             int pre_invalid = src.offset % vlen;
863             int vcols = (pre_invalid + src.cols + vlen - 1) / vlen;
864
865             if( sdepth <= 0 )
866                 sdepth = CV_32S;
867             sdepth = CV_MAT_DEPTH(sdepth);
868             int type = CV_MAKE_TYPE(sdepth, 1);
869
870             oclMat t_sum;
871             int w = src.cols + 1, h = src.rows + 1;
872
873             t_sum.create(src.cols, src.rows, type);
874             sum.create(h, w, type);
875
876             int sum_offset = sum.offset / vlen;
877             vector<pair<size_t , const void *> > args;
878             args.push_back( make_pair( sizeof(cl_mem) , (void *)&src.data ));
879             args.push_back( make_pair( sizeof(cl_mem) , (void *)&t_sum.data ));
880             args.push_back( make_pair( sizeof(cl_int) , (void *)&offset ));
881             args.push_back( make_pair( sizeof(cl_int) , (void *)&pre_invalid ));
882             args.push_back( make_pair( sizeof(cl_int) , (void *)&src.rows ));
883             args.push_back( make_pair( sizeof(cl_int) , (void *)&src.cols ));
884             args.push_back( make_pair( sizeof(cl_int) , (void *)&src.step ));
885             args.push_back( make_pair( sizeof(cl_int) , (void *)&t_sum.step));
886             size_t gt[3] = {((vcols + 1) / 2) * 256, 1, 1}, lt[3] = {256, 1, 1};
887             openCLExecuteKernel(src.clCxt, &imgproc_integral_sum, "integral_sum_cols", gt, lt, args, -1, sdepth);
888
889             args.clear();
890             args.push_back( make_pair( sizeof(cl_mem) , (void *)&t_sum.data ));
891             args.push_back( make_pair( sizeof(cl_mem) , (void *)&sum.data ));
892             args.push_back( make_pair( sizeof(cl_int) , (void *)&t_sum.rows ));
893             args.push_back( make_pair( sizeof(cl_int) , (void *)&t_sum.cols ));
894             args.push_back( make_pair( sizeof(cl_int) , (void *)&t_sum.step ));
895             args.push_back( make_pair( sizeof(cl_int) , (void *)&sum.step));
896             args.push_back( make_pair( sizeof(cl_int) , (void *)&sum_offset));
897             size_t gt2[3] = {t_sum.cols  * 32, 1, 1}, lt2[3] = {256, 1, 1};
898             openCLExecuteKernel(src.clCxt, &imgproc_integral_sum, "integral_sum_rows", gt2, lt2, args, -1, sdepth);
899         }
900
901         /////////////////////// corner //////////////////////////////
902
903         static void extractCovData(const oclMat &src, oclMat &Dx, oclMat &Dy,
904                             int blockSize, int ksize, int borderType)
905         {
906             CV_Assert(src.type() == CV_8UC1 || src.type() == CV_32FC1);
907             double scale = static_cast<double>(1 << ((ksize > 0 ? ksize : 3) - 1)) * blockSize;
908             if (ksize < 0)
909                 scale *= 2.;
910
911             if (src.depth() == CV_8U)
912             {
913                 scale *= 255.;
914                 scale = 1. / scale;
915             }
916             else
917                 scale = 1. / scale;
918
919             if (ksize > 0)
920             {
921                 Context* clCxt = Context::getContext();
922                 if(clCxt->supportsFeature(FEATURE_CL_INTEL_DEVICE) && src.type() == CV_8UC1 &&
923                     src.cols % 8 == 0 && src.rows % 8 == 0 &&
924                     ksize==3 &&
925                     (borderType ==cv::BORDER_REFLECT ||
926                      borderType == cv::BORDER_REPLICATE ||
927                      borderType ==cv::BORDER_REFLECT101 ||
928                      borderType ==cv::BORDER_WRAP))
929                 {
930                     Dx.create(src.size(), CV_32FC1);
931                     Dy.create(src.size(), CV_32FC1);
932
933                     const unsigned int block_x = 8;
934                     const unsigned int block_y = 8;
935
936                     unsigned int src_pitch = src.step;
937                     unsigned int dst_pitch = Dx.cols;
938
939                     float _scale = scale;
940
941                     std::vector<std::pair<size_t , const void *> > args;
942                     args.push_back( std::make_pair( sizeof(cl_mem) , (void *)&src.data ));
943                     args.push_back( std::make_pair( sizeof(cl_mem) , (void *)&Dx.data ));
944                     args.push_back( std::make_pair( sizeof(cl_mem) , (void *)&Dy.data ));
945                     args.push_back( std::make_pair( sizeof(cl_int) , (void *)&src.cols ));
946                     args.push_back( std::make_pair( sizeof(cl_int) , (void *)&src.rows ));
947                     args.push_back( std::make_pair( sizeof(cl_uint) , (void *)&src_pitch ));
948                     args.push_back( std::make_pair( sizeof(cl_uint) , (void *)&dst_pitch ));
949                     args.push_back( std::make_pair( sizeof(cl_float) , (void *)&_scale ));
950                     size_t gt2[3] = {src.cols, src.rows, 1}, lt2[3] = {block_x, block_y, 1};
951
952                     string option = "-D BLK_X=8 -D BLK_Y=8";
953                     switch(borderType)
954                     {
955                     case cv::BORDER_REPLICATE:
956                         option += " -D BORDER_REPLICATE";
957                         break;
958                     case cv::BORDER_REFLECT:
959                         option += " -D BORDER_REFLECT";
960                         break;
961                     case cv::BORDER_REFLECT101:
962                         option += " -D BORDER_REFLECT101";
963                         break;
964                     case cv::BORDER_WRAP:
965                         option += " -D BORDER_WRAP";
966                         break;
967                     }
968                     openCLExecuteKernel(src.clCxt, &imgproc_sobel3, "sobel3", gt2, lt2, args, -1, -1, option.c_str() );
969                 }
970                 else
971                 {
972                     Sobel(src, Dx, CV_32F, 1, 0, ksize, scale, 0, borderType);
973                     Sobel(src, Dy, CV_32F, 0, 1, ksize, scale, 0, borderType);
974                 }
975             }
976             else
977             {
978                 Scharr(src, Dx, CV_32F, 1, 0, scale, 0, borderType);
979                 Scharr(src, Dy, CV_32F, 0, 1, scale, 0, borderType);
980             }
981             CV_Assert(Dx.offset == 0 && Dy.offset == 0);
982         }
983
984         static void corner_ocl(const cv::ocl::ProgramEntry* source, string kernelName, int block_size, float k, oclMat &Dx, oclMat &Dy,
985                         oclMat &dst, int border_type)
986         {
987             char borderType[30];
988             switch (border_type)
989             {
990             case cv::BORDER_CONSTANT:
991                 sprintf(borderType, "BORDER_CONSTANT");
992                 break;
993             case cv::BORDER_REFLECT101:
994                 sprintf(borderType, "BORDER_REFLECT101");
995                 break;
996             case cv::BORDER_REFLECT:
997                 sprintf(borderType, "BORDER_REFLECT");
998                 break;
999             case cv::BORDER_REPLICATE:
1000                 sprintf(borderType, "BORDER_REPLICATE");
1001                 break;
1002             default:
1003                 CV_Error(CV_StsBadFlag, "BORDER type is not supported!");
1004             }
1005
1006             std::string buildOptions = format("-D anX=%d -D anY=%d -D ksX=%d -D ksY=%d -D %s",
1007                     block_size / 2, block_size / 2, block_size, block_size, borderType);
1008
1009             size_t blockSizeX = 256, blockSizeY = 1;
1010             size_t gSize = blockSizeX - block_size / 2 * 2;
1011             size_t globalSizeX = (Dx.cols) % gSize == 0 ? Dx.cols / gSize * blockSizeX : (Dx.cols / gSize + 1) * blockSizeX;
1012             size_t rows_per_thread = 2;
1013             size_t globalSizeY = ((Dx.rows + rows_per_thread - 1) / rows_per_thread) % blockSizeY == 0 ?
1014                                  ((Dx.rows + rows_per_thread - 1) / rows_per_thread) :
1015                                  (((Dx.rows + rows_per_thread - 1) / rows_per_thread) / blockSizeY + 1) * blockSizeY;
1016
1017             size_t gt[3] = { globalSizeX, globalSizeY, 1 };
1018             size_t lt[3]  = { blockSizeX, blockSizeY, 1 };
1019             vector<pair<size_t , const void *> > args;
1020             args.push_back( make_pair( sizeof(cl_mem) , (void *)&Dx.data ));
1021             args.push_back( make_pair( sizeof(cl_mem) , (void *)&Dy.data));
1022             args.push_back( make_pair( sizeof(cl_mem) , (void *)&dst.data));
1023             args.push_back( make_pair( sizeof(cl_int) , (void *)&Dx.offset ));
1024             args.push_back( make_pair( sizeof(cl_int) , (void *)&Dx.wholerows ));
1025             args.push_back( make_pair( sizeof(cl_int) , (void *)&Dx.wholecols ));
1026             args.push_back( make_pair(sizeof(cl_int), (void *)&Dx.step));
1027             args.push_back( make_pair( sizeof(cl_int) , (void *)&Dy.offset ));
1028             args.push_back( make_pair( sizeof(cl_int) , (void *)&Dy.wholerows ));
1029             args.push_back( make_pair( sizeof(cl_int) , (void *)&Dy.wholecols ));
1030             args.push_back( make_pair(sizeof(cl_int), (void *)&Dy.step));
1031             args.push_back( make_pair(sizeof(cl_int), (void *)&dst.offset));
1032             args.push_back( make_pair(sizeof(cl_int), (void *)&dst.rows));
1033             args.push_back( make_pair(sizeof(cl_int), (void *)&dst.cols));
1034             args.push_back( make_pair(sizeof(cl_int), (void *)&dst.step));
1035             args.push_back( make_pair( sizeof(cl_float) , (void *)&k));
1036
1037             openCLExecuteKernel(dst.clCxt, source, kernelName, gt, lt, args, -1, -1, buildOptions.c_str());
1038         }
1039
1040         void cornerHarris(const oclMat &src, oclMat &dst, int blockSize, int ksize,
1041                           double k, int borderType)
1042         {
1043             oclMat dx, dy;
1044             cornerHarris_dxdy(src, dst, dx, dy, blockSize, ksize, k, borderType);
1045         }
1046
1047         void cornerHarris_dxdy(const oclMat &src, oclMat &dst, oclMat &dx, oclMat &dy, int blockSize, int ksize,
1048                           double k, int borderType)
1049         {
1050             if (!src.clCxt->supportsFeature(FEATURE_CL_DOUBLE) && src.depth() == CV_64F)
1051             {
1052                 CV_Error(CV_OpenCLDoubleNotSupported, "Selected device doesn't support double");
1053                 return;
1054             }
1055
1056             CV_Assert(borderType == cv::BORDER_CONSTANT || borderType == cv::BORDER_REFLECT101 || borderType == cv::BORDER_REPLICATE
1057                       || borderType == cv::BORDER_REFLECT);
1058
1059             extractCovData(src, dx, dy, blockSize, ksize, borderType);
1060             dst.create(src.size(), CV_32FC1);
1061             corner_ocl(&imgproc_calcHarris, "calcHarris", blockSize, static_cast<float>(k), dx, dy, dst, borderType);
1062         }
1063
1064         void cornerMinEigenVal(const oclMat &src, oclMat &dst, int blockSize, int ksize, int borderType)
1065         {
1066             oclMat dx, dy;
1067             cornerMinEigenVal_dxdy(src, dst, dx, dy, blockSize, ksize, borderType);
1068         }
1069
1070         void cornerMinEigenVal_dxdy(const oclMat &src, oclMat &dst, oclMat &dx, oclMat &dy, int blockSize, int ksize, int borderType)
1071         {
1072             if (!src.clCxt->supportsFeature(FEATURE_CL_DOUBLE) && src.depth() == CV_64F)
1073             {
1074                 CV_Error(CV_OpenCLDoubleNotSupported, "Selected device doesn't support double");
1075                 return;
1076             }
1077
1078             CV_Assert(borderType == cv::BORDER_CONSTANT || borderType == cv::BORDER_REFLECT101 ||
1079                       borderType == cv::BORDER_REPLICATE || borderType == cv::BORDER_REFLECT);
1080
1081             extractCovData(src, dx, dy, blockSize, ksize, borderType);
1082             dst.create(src.size(), CV_32F);
1083
1084             corner_ocl(&imgproc_calcMinEigenVal, "calcMinEigenVal", blockSize, 0, dx, dy, dst, borderType);
1085         }
1086
1087         /////////////////////////////////// MeanShiftfiltering ///////////////////////////////////////////////
1088
1089         static void meanShiftFiltering_gpu(const oclMat &src, oclMat dst, int sp, int sr, int maxIter, float eps)
1090         {
1091             CV_Assert( (src.cols == dst.cols) && (src.rows == dst.rows) );
1092             CV_Assert( !(dst.step & 0x3) );
1093
1094             //Arrange the NDRange
1095             int col = src.cols, row = src.rows;
1096             int ltx = 16, lty = 8;
1097             if (src.cols % ltx != 0)
1098                 col = (col / ltx + 1) * ltx;
1099             if (src.rows % lty != 0)
1100                 row = (row / lty + 1) * lty;
1101
1102             size_t globalThreads[3] = {col, row, 1};
1103             size_t localThreads[3]  = {ltx, lty, 1};
1104
1105             //set args
1106             vector<pair<size_t , const void *> > args;
1107             args.push_back( make_pair( sizeof(cl_mem) , (void *)&dst.data ));
1108             args.push_back( make_pair( sizeof(cl_int) , (void *)&dst.step ));
1109             args.push_back( make_pair( sizeof(cl_mem) , (void *)&src.data ));
1110             args.push_back( make_pair( sizeof(cl_int) , (void *)&src.step ));
1111             args.push_back( make_pair( sizeof(cl_int) , (void *)&dst.offset ));
1112             args.push_back( make_pair( sizeof(cl_int) , (void *)&src.offset ));
1113             args.push_back( make_pair( sizeof(cl_int) , (void *)&dst.cols ));
1114             args.push_back( make_pair( sizeof(cl_int) , (void *)&dst.rows ));
1115             args.push_back( make_pair( sizeof(cl_int) , (void *)&sp ));
1116             args.push_back( make_pair( sizeof(cl_int) , (void *)&sr ));
1117             args.push_back( make_pair( sizeof(cl_int) , (void *)&maxIter ));
1118             args.push_back( make_pair( sizeof(cl_float) , (void *)&eps ));
1119
1120             openCLExecuteKernel(src.clCxt, &meanShift, "meanshift_kernel", globalThreads, localThreads, args, -1, -1);
1121         }
1122
1123         void meanShiftFiltering(const oclMat &src, oclMat &dst, int sp, int sr, TermCriteria criteria)
1124         {
1125             if ( src.empty() )
1126                 CV_Error( CV_StsBadArg, "The input image is empty" );
1127
1128             if ( src.depth() != CV_8U || src.oclchannels() != 4 )
1129                 CV_Error( CV_StsUnsupportedFormat, "Only 8-bit, 4-channel images are supported" );
1130
1131             dst.create( src.size(), CV_8UC4 );
1132
1133             if ( !(criteria.type & TermCriteria::MAX_ITER) )
1134                 criteria.maxCount = 5;
1135
1136             int maxIter = std::min(std::max(criteria.maxCount, 1), 100);
1137
1138             float eps;
1139             if ( !(criteria.type & TermCriteria::EPS) )
1140                 eps = 1.f;
1141             eps = (float)std::max(criteria.epsilon, 0.0);
1142
1143             meanShiftFiltering_gpu(src, dst, sp, sr, maxIter, eps);
1144         }
1145
1146         static void meanShiftProc_gpu(const oclMat &src, oclMat dstr, oclMat dstsp, int sp, int sr, int maxIter, float eps)
1147         {
1148             //sanity checks
1149             CV_Assert( (src.cols == dstr.cols) && (src.rows == dstr.rows) &&
1150                        (src.rows == dstsp.rows) && (src.cols == dstsp.cols));
1151             CV_Assert( !(dstsp.step & 0x3) );
1152
1153             //Arrange the NDRange
1154             int col = src.cols, row = src.rows;
1155             int ltx = 16, lty = 8;
1156             if (src.cols % ltx != 0)
1157                 col = (col / ltx + 1) * ltx;
1158             if (src.rows % lty != 0)
1159                 row = (row / lty + 1) * lty;
1160
1161             size_t globalThreads[3] = {col, row, 1};
1162             size_t localThreads[3]  = {ltx, lty, 1};
1163
1164             //set args
1165             vector<pair<size_t , const void *> > args;
1166             args.push_back( make_pair( sizeof(cl_mem) , (void *)&src.data ));
1167             args.push_back( make_pair( sizeof(cl_mem) , (void *)&dstr.data ));
1168             args.push_back( make_pair( sizeof(cl_mem) , (void *)&dstsp.data ));
1169             args.push_back( make_pair( sizeof(cl_int) , (void *)&src.step ));
1170             args.push_back( make_pair( sizeof(cl_int) , (void *)&dstr.step ));
1171             args.push_back( make_pair( sizeof(cl_int) , (void *)&dstsp.step ));
1172             args.push_back( make_pair( sizeof(cl_int) , (void *)&src.offset ));
1173             args.push_back( make_pair( sizeof(cl_int) , (void *)&dstr.offset ));
1174             args.push_back( make_pair( sizeof(cl_int) , (void *)&dstsp.offset ));
1175             args.push_back( make_pair( sizeof(cl_int) , (void *)&dstr.cols ));
1176             args.push_back( make_pair( sizeof(cl_int) , (void *)&dstr.rows ));
1177             args.push_back( make_pair( sizeof(cl_int) , (void *)&sp ));
1178             args.push_back( make_pair( sizeof(cl_int) , (void *)&sr ));
1179             args.push_back( make_pair( sizeof(cl_int) , (void *)&maxIter ));
1180             args.push_back( make_pair( sizeof(cl_float) , (void *)&eps ));
1181
1182             openCLExecuteKernel(src.clCxt, &meanShift, "meanshiftproc_kernel", globalThreads, localThreads, args, -1, -1);
1183         }
1184
1185         void meanShiftProc(const oclMat &src, oclMat &dstr, oclMat &dstsp, int sp, int sr, TermCriteria criteria)
1186         {
1187             if ( src.empty() )
1188                 CV_Error( CV_StsBadArg, "The input image is empty" );
1189
1190             if ( src.depth() != CV_8U || src.oclchannels() != 4 )
1191                 CV_Error( CV_StsUnsupportedFormat, "Only 8-bit, 4-channel images are supported" );
1192
1193 //            if (!src.clCxt->supportsFeature(FEATURE_CL_DOUBLE))
1194 //            {
1195 //                CV_Error( CV_OpenCLDoubleNotSupportedNotSupported, "Selected device doesn't support double, so a deviation exists.\nIf the accuracy is acceptable, the error can be ignored.\n");
1196 //                return;
1197 //            }
1198
1199             dstr.create( src.size(), CV_8UC4 );
1200             dstsp.create( src.size(), CV_16SC2 );
1201
1202             if ( !(criteria.type & TermCriteria::MAX_ITER) )
1203                 criteria.maxCount = 5;
1204
1205             int maxIter = std::min(std::max(criteria.maxCount, 1), 100);
1206
1207             float eps;
1208             if ( !(criteria.type & TermCriteria::EPS) )
1209                 eps = 1.f;
1210             eps = (float)std::max(criteria.epsilon, 0.0);
1211
1212             meanShiftProc_gpu(src, dstr, dstsp, sp, sr, maxIter, eps);
1213         }
1214
1215         ///////////////////////////////////////////////////////////////////////////////////////////////////
1216         ////////////////////////////////////////////////////hist///////////////////////////////////////////////
1217         /////////////////////////////////////////////////////////////////////////////////////////////////////
1218
1219         namespace histograms
1220         {
1221             const int PARTIAL_HISTOGRAM256_COUNT = 256;
1222             const int HISTOGRAM256_BIN_COUNT = 256;
1223         }
1224         ///////////////////////////////calcHist/////////////////////////////////////////////////////////////////
1225         static void calc_sub_hist(const oclMat &mat_src, const oclMat &mat_sub_hist)
1226         {
1227             using namespace histograms;
1228
1229             int depth = mat_src.depth();
1230
1231             size_t localThreads[3]  = { HISTOGRAM256_BIN_COUNT, 1, 1 };
1232             size_t globalThreads[3] = { PARTIAL_HISTOGRAM256_COUNT *localThreads[0], 1, 1};
1233
1234             int dataWidth = 16;
1235             int dataWidth_bits = 4;
1236             int mask = dataWidth - 1;
1237
1238             int cols = mat_src.cols * mat_src.oclchannels();
1239             int src_offset = mat_src.offset;
1240             int hist_step = mat_sub_hist.step >> 2;
1241             int left_col = 0, right_col = 0;
1242
1243             if (cols >= dataWidth * 2 - 1)
1244             {
1245                 left_col = dataWidth - (src_offset & mask);
1246                 left_col &= mask;
1247                 src_offset += left_col;
1248                 cols -= left_col;
1249                 right_col = cols & mask;
1250                 cols -= right_col;
1251             }
1252             else
1253             {
1254                 left_col = cols;
1255                 right_col = 0;
1256                 cols = 0;
1257                 globalThreads[0] = 0;
1258             }
1259
1260             vector<pair<size_t , const void *> > args;
1261             if (globalThreads[0] != 0)
1262             {
1263                 int tempcols = cols >> dataWidth_bits;
1264                 int inc_x = globalThreads[0] % tempcols;
1265                 int inc_y = globalThreads[0] / tempcols;
1266                 src_offset >>= dataWidth_bits;
1267                 int src_step = mat_src.step >> dataWidth_bits;
1268                 int datacount = tempcols * mat_src.rows;
1269
1270                 args.push_back( make_pair( sizeof(cl_mem), (void *)&mat_src.data));
1271                 args.push_back( make_pair( sizeof(cl_int), (void *)&src_step));
1272                 args.push_back( make_pair( sizeof(cl_int), (void *)&src_offset));
1273                 args.push_back( make_pair( sizeof(cl_mem), (void *)&mat_sub_hist.data));
1274                 args.push_back( make_pair( sizeof(cl_int), (void *)&datacount));
1275                 args.push_back( make_pair( sizeof(cl_int), (void *)&tempcols));
1276                 args.push_back( make_pair( sizeof(cl_int), (void *)&inc_x));
1277                 args.push_back( make_pair( sizeof(cl_int), (void *)&inc_y));
1278                 args.push_back( make_pair( sizeof(cl_int), (void *)&hist_step));
1279
1280                 openCLExecuteKernel(mat_src.clCxt, &imgproc_histogram, "calc_sub_hist", globalThreads, localThreads, args, -1, depth);
1281             }
1282
1283             if (left_col != 0 || right_col != 0)
1284             {
1285                 src_offset = mat_src.offset;
1286                 localThreads[0] = 1;
1287                 localThreads[1] = 256;
1288                 globalThreads[0] = left_col + right_col;
1289                 globalThreads[1] = mat_src.rows;
1290
1291                 args.clear();
1292                 args.push_back( make_pair( sizeof(cl_mem), (void *)&mat_src.data));
1293                 args.push_back( make_pair( sizeof(cl_int), (void *)&mat_src.step));
1294                 args.push_back( make_pair( sizeof(cl_int), (void *)&src_offset));
1295                 args.push_back( make_pair( sizeof(cl_mem), (void *)&mat_sub_hist.data));
1296                 args.push_back( make_pair( sizeof(cl_int), (void *)&left_col));
1297                 args.push_back( make_pair( sizeof(cl_int), (void *)&cols));
1298                 args.push_back( make_pair( sizeof(cl_int), (void *)&mat_src.rows));
1299                 args.push_back( make_pair( sizeof(cl_int), (void *)&hist_step));
1300
1301                 openCLExecuteKernel(mat_src.clCxt, &imgproc_histogram, "calc_sub_hist_border", globalThreads, localThreads, args, -1, depth);
1302             }
1303         }
1304
1305         static void merge_sub_hist(const oclMat &sub_hist, oclMat &mat_hist)
1306         {
1307             using namespace histograms;
1308
1309             size_t localThreads[3]  = { 256, 1, 1 };
1310             size_t globalThreads[3] = { HISTOGRAM256_BIN_COUNT *localThreads[0], 1, 1};
1311             int src_step = sub_hist.step >> 2;
1312
1313             vector<pair<size_t , const void *> > args;
1314             args.push_back( make_pair( sizeof(cl_mem), (void *)&sub_hist.data));
1315             args.push_back( make_pair( sizeof(cl_mem), (void *)&mat_hist.data));
1316             args.push_back( make_pair( sizeof(cl_int), (void *)&src_step));
1317
1318             openCLExecuteKernel(sub_hist.clCxt, &imgproc_histogram, "merge_hist", globalThreads, localThreads, args, -1, -1);
1319         }
1320
1321         void calcHist(const oclMat &mat_src, oclMat &mat_hist)
1322         {
1323             using namespace histograms;
1324             CV_Assert(mat_src.type() == CV_8UC1);
1325             mat_hist.create(1, 256, CV_32SC1);
1326
1327             oclMat buf(PARTIAL_HISTOGRAM256_COUNT, HISTOGRAM256_BIN_COUNT, CV_32SC1);
1328             buf.setTo(0);
1329
1330             calc_sub_hist(mat_src, buf);
1331             merge_sub_hist(buf, mat_hist);
1332         }
1333
1334         ///////////////////////////////////equalizeHist/////////////////////////////////////////////////////
1335         void equalizeHist(const oclMat &mat_src, oclMat &mat_dst)
1336         {
1337             mat_dst.create(mat_src.rows, mat_src.cols, CV_8UC1);
1338
1339             oclMat mat_hist(1, 256, CV_32SC1);
1340
1341             calcHist(mat_src, mat_hist);
1342
1343             size_t localThreads[3] = { 256, 1, 1};
1344             size_t globalThreads[3] = { 256, 1, 1};
1345             oclMat lut(1, 256, CV_8UC1);
1346             int total = mat_src.rows * mat_src.cols;
1347
1348             vector<pair<size_t , const void *> > args;
1349             args.push_back( make_pair( sizeof(cl_mem), (void *)&lut.data));
1350             args.push_back( make_pair( sizeof(cl_mem), (void *)&mat_hist.data));
1351             args.push_back( make_pair( sizeof(int), (void *)&total));
1352
1353             openCLExecuteKernel(mat_src.clCxt, &imgproc_histogram, "calLUT", globalThreads, localThreads, args, -1, -1);
1354             LUT(mat_src, lut, mat_dst);
1355         }
1356
1357         ////////////////////////////////////////////////////////////////////////
1358         // CLAHE
1359         namespace clahe
1360         {
1361             static void calcLut(const oclMat &src, oclMat &dst,
1362                 const int tilesX, const int tilesY, const cv::Size tileSize,
1363                 const int clipLimit, const float lutScale)
1364             {
1365                 cl_int2 tile_size;
1366                 tile_size.s[0] = tileSize.width;
1367                 tile_size.s[1] = tileSize.height;
1368
1369                 std::vector<pair<size_t , const void *> > args;
1370                 args.push_back( std::make_pair( sizeof(cl_mem), (void *)&src.data ));
1371                 args.push_back( std::make_pair( sizeof(cl_mem), (void *)&dst.data ));
1372                 args.push_back( std::make_pair( sizeof(cl_int), (void *)&src.step ));
1373                 args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst.step ));
1374                 args.push_back( std::make_pair( sizeof(cl_int2), (void *)&tile_size ));
1375                 args.push_back( std::make_pair( sizeof(cl_int), (void *)&tilesX ));
1376                 args.push_back( std::make_pair( sizeof(cl_int), (void *)&clipLimit ));
1377                 args.push_back( std::make_pair( sizeof(cl_float), (void *)&lutScale ));
1378                 args.push_back( std::make_pair( sizeof(cl_int), (void *)&src.offset ));
1379                 args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst.offset ));
1380
1381                 String kernelName = "calcLut";
1382                 size_t localThreads[3]  = { 32, 8, 1 };
1383                 size_t globalThreads[3] = { tilesX * localThreads[0], tilesY * localThreads[1], 1 };
1384                 bool is_cpu = isCpuDevice();
1385                 if (is_cpu)
1386                     openCLExecuteKernel(Context::getContext(), &imgproc_clahe, kernelName, globalThreads, localThreads, args, -1, -1, (char*)"-D CPU");
1387                 else
1388                 {
1389                     cl_kernel kernel = openCLGetKernelFromSource(Context::getContext(), &imgproc_clahe, kernelName);
1390                     int wave_size = (int)queryWaveFrontSize(kernel);
1391                     openCLSafeCall(clReleaseKernel(kernel));
1392
1393                     std::string opt = format("-D WAVE_SIZE=%d", wave_size);
1394                     openCLExecuteKernel(Context::getContext(), &imgproc_clahe, kernelName, globalThreads, localThreads, args, -1, -1, opt.c_str());
1395                 }
1396             }
1397
1398             static void transform(const oclMat &src, oclMat &dst, const oclMat &lut,
1399                 const int tilesX, const int tilesY, const Size & tileSize)
1400             {
1401                 cl_int2 tile_size;
1402                 tile_size.s[0] = tileSize.width;
1403                 tile_size.s[1] = tileSize.height;
1404
1405                 std::vector<pair<size_t , const void *> > args;
1406                 args.push_back( std::make_pair( sizeof(cl_mem), (void *)&src.data ));
1407                 args.push_back( std::make_pair( sizeof(cl_mem), (void *)&dst.data ));
1408                 args.push_back( std::make_pair( sizeof(cl_mem), (void *)&lut.data ));
1409                 args.push_back( std::make_pair( sizeof(cl_int), (void *)&src.step ));
1410                 args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst.step ));
1411                 args.push_back( std::make_pair( sizeof(cl_int), (void *)&lut.step ));
1412                 args.push_back( std::make_pair( sizeof(cl_int), (void *)&src.cols ));
1413                 args.push_back( std::make_pair( sizeof(cl_int), (void *)&src.rows ));
1414                 args.push_back( std::make_pair( sizeof(cl_int2), (void *)&tile_size ));
1415                 args.push_back( std::make_pair( sizeof(cl_int), (void *)&tilesX ));
1416                 args.push_back( std::make_pair( sizeof(cl_int), (void *)&tilesY ));
1417                 args.push_back( std::make_pair( sizeof(cl_int), (void *)&src.offset ));
1418                 args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst.offset ));
1419                 args.push_back( std::make_pair( sizeof(cl_int), (void *)&lut.offset ));
1420
1421                 size_t localThreads[3]  = { 32, 8, 1 };
1422                 size_t globalThreads[3] = { src.cols, src.rows, 1 };
1423
1424                 openCLExecuteKernel(Context::getContext(), &imgproc_clahe, "transform", globalThreads, localThreads, args, -1, -1);
1425             }
1426         }
1427
1428         namespace
1429         {
1430             class CLAHE_Impl : public cv::CLAHE
1431             {
1432             public:
1433                 CLAHE_Impl(double clipLimit = 40.0, int tilesX = 8, int tilesY = 8);
1434
1435                 cv::AlgorithmInfo* info() const;
1436
1437                 void apply(cv::InputArray src, cv::OutputArray dst);
1438
1439                 void setClipLimit(double clipLimit);
1440                 double getClipLimit() const;
1441
1442                 void setTilesGridSize(cv::Size tileGridSize);
1443                 cv::Size getTilesGridSize() const;
1444
1445                 void collectGarbage();
1446
1447             private:
1448                 double clipLimit_;
1449                 int tilesX_;
1450                 int tilesY_;
1451
1452                 oclMat srcExt_;
1453                 oclMat lut_;
1454             };
1455
1456             CLAHE_Impl::CLAHE_Impl(double clipLimit, int tilesX, int tilesY) :
1457                 clipLimit_(clipLimit), tilesX_(tilesX), tilesY_(tilesY)
1458             {
1459             }
1460
1461             CV_INIT_ALGORITHM(CLAHE_Impl, "CLAHE_OCL",
1462                 obj.info()->addParam(obj, "clipLimit", obj.clipLimit_);
1463                 obj.info()->addParam(obj, "tilesX", obj.tilesX_);
1464                 obj.info()->addParam(obj, "tilesY", obj.tilesY_))
1465
1466             void CLAHE_Impl::apply(cv::InputArray src_raw, cv::OutputArray dst_raw)
1467             {
1468                 oclMat& src = getOclMatRef(src_raw);
1469                 oclMat& dst = getOclMatRef(dst_raw);
1470                 CV_Assert( src.type() == CV_8UC1 );
1471
1472                 dst.create( src.size(), src.type() );
1473
1474                 const int histSize = 256;
1475
1476                 ensureSizeIsEnough(tilesX_ * tilesY_, histSize, CV_8UC1, lut_);
1477
1478                 cv::Size tileSize;
1479                 oclMat srcForLut;
1480
1481                 if (src.cols % tilesX_ == 0 && src.rows % tilesY_ == 0)
1482                 {
1483                     tileSize = cv::Size(src.cols / tilesX_, src.rows / tilesY_);
1484                     srcForLut = src;
1485                 }
1486                 else
1487                 {
1488                     ocl::copyMakeBorder(src, srcExt_, 0, tilesY_ - (src.rows % tilesY_), 0,
1489                                             tilesX_ - (src.cols % tilesX_), BORDER_REFLECT_101, Scalar::all(0));
1490
1491                     tileSize = Size(srcExt_.cols / tilesX_, srcExt_.rows / tilesY_);
1492                     srcForLut = srcExt_;
1493                 }
1494
1495                 const int tileSizeTotal = tileSize.area();
1496                 const float lutScale = static_cast<float>(histSize - 1) / tileSizeTotal;
1497
1498                 int clipLimit = 0;
1499                 if (clipLimit_ > 0.0)
1500                 {
1501                     clipLimit = static_cast<int>(clipLimit_ * tileSizeTotal / histSize);
1502                     clipLimit = std::max(clipLimit, 1);
1503                 }
1504
1505                 clahe::calcLut(srcForLut, lut_, tilesX_, tilesY_, tileSize, clipLimit, lutScale);
1506                 clahe::transform(src, dst, lut_, tilesX_, tilesY_, tileSize);
1507             }
1508
1509             void CLAHE_Impl::setClipLimit(double clipLimit)
1510             {
1511                 clipLimit_ = clipLimit;
1512             }
1513
1514             double CLAHE_Impl::getClipLimit() const
1515             {
1516                 return clipLimit_;
1517             }
1518
1519             void CLAHE_Impl::setTilesGridSize(cv::Size tileGridSize)
1520             {
1521                 tilesX_ = tileGridSize.width;
1522                 tilesY_ = tileGridSize.height;
1523             }
1524
1525             cv::Size CLAHE_Impl::getTilesGridSize() const
1526             {
1527                 return cv::Size(tilesX_, tilesY_);
1528             }
1529
1530             void CLAHE_Impl::collectGarbage()
1531             {
1532                 srcExt_.release();
1533                 lut_.release();
1534             }
1535         }
1536
1537         cv::Ptr<cv::CLAHE> createCLAHE(double clipLimit, cv::Size tileGridSize)
1538         {
1539             return new CLAHE_Impl(clipLimit, tileGridSize.width, tileGridSize.height);
1540         }
1541
1542         //////////////////////////////////bilateralFilter////////////////////////////////////////////////////
1543
1544         static void oclbilateralFilter_8u( const oclMat &src, oclMat &dst, int d,
1545                                double sigma_color, double sigma_space,
1546                                int borderType )
1547         {
1548             int cn = src.channels();
1549             int i, j, maxk, radius;
1550
1551             CV_Assert( (src.channels() == 1 || src.channels() == 3) &&
1552                        src.type() == dst.type() && src.size() == dst.size() &&
1553                        src.data != dst.data );
1554
1555             if ( sigma_color <= 0 )
1556                 sigma_color = 1;
1557             if ( sigma_space <= 0 )
1558                 sigma_space = 1;
1559
1560             double gauss_color_coeff = -0.5 / (sigma_color * sigma_color);
1561             double gauss_space_coeff = -0.5 / (sigma_space * sigma_space);
1562
1563             if ( d <= 0 )
1564                 radius = cvRound(sigma_space * 1.5);
1565             else
1566                 radius = d / 2;
1567             radius = MAX(radius, 1);
1568             d = radius * 2 + 1;
1569
1570             oclMat temp;
1571             copyMakeBorder( src, temp, radius, radius, radius, radius, borderType );
1572
1573             vector<float> _color_weight(cn * 256);
1574             vector<float> _space_weight(d * d);
1575             vector<int> _space_ofs(d * d);
1576             float *color_weight = &_color_weight[0];
1577             float *space_weight = &_space_weight[0];
1578             int *space_ofs = &_space_ofs[0];
1579
1580             int dst_step_in_pixel = dst.step / dst.elemSize();
1581             int dst_offset_in_pixel = dst.offset / dst.elemSize();
1582             int temp_step_in_pixel = temp.step / temp.elemSize();
1583
1584             // initialize color-related bilateral filter coefficients
1585             for( i = 0; i < 256 * cn; i++ )
1586                 color_weight[i] = (float)std::exp(i * i * gauss_color_coeff);
1587
1588             // initialize space-related bilateral filter coefficients
1589             for( i = -radius, maxk = 0; i <= radius; i++ )
1590                 for( j = -radius; j <= radius; j++ )
1591                 {
1592                     double r = std::sqrt((double)i * i + (double)j * j);
1593                     if ( r > radius )
1594                         continue;
1595                     space_weight[maxk] = (float)std::exp(r * r * gauss_space_coeff);
1596                     space_ofs[maxk++] = (int)(i * temp_step_in_pixel + j);
1597                 }
1598
1599             oclMat oclcolor_weight(1, cn * 256, CV_32FC1, color_weight);
1600             oclMat oclspace_weight(1, d * d, CV_32FC1, space_weight);
1601             oclMat oclspace_ofs(1, d * d, CV_32SC1, space_ofs);
1602
1603             string kernelName = "bilateral";
1604             size_t localThreads[3]  = { 16, 16, 1 };
1605             size_t globalThreads[3] = { dst.cols, dst.rows, 1 };
1606
1607             if ((dst.type() == CV_8UC1) && ((dst.offset & 3) == 0) && ((dst.cols & 3) == 0))
1608             {
1609                 kernelName = "bilateral2";
1610                 globalThreads[0] = dst.cols >> 2;
1611             }
1612
1613             vector<pair<size_t , const void *> > args;
1614             args.push_back( make_pair( sizeof(cl_mem), (void *)&dst.data ));
1615             args.push_back( make_pair( sizeof(cl_mem), (void *)&temp.data ));
1616             args.push_back( make_pair( sizeof(cl_int), (void *)&dst.rows ));
1617             args.push_back( make_pair( sizeof(cl_int), (void *)&dst.cols ));
1618             args.push_back( make_pair( sizeof(cl_int), (void *)&maxk ));
1619             args.push_back( make_pair( sizeof(cl_int), (void *)&radius ));
1620             args.push_back( make_pair( sizeof(cl_int), (void *)&dst_step_in_pixel ));
1621             args.push_back( make_pair( sizeof(cl_int), (void *)&dst_offset_in_pixel ));
1622             args.push_back( make_pair( sizeof(cl_int), (void *)&temp_step_in_pixel ));
1623             args.push_back( make_pair( sizeof(cl_int), (void *)&temp.rows ));
1624             args.push_back( make_pair( sizeof(cl_int), (void *)&temp.cols ));
1625             args.push_back( make_pair( sizeof(cl_mem), (void *)&oclcolor_weight.data ));
1626             args.push_back( make_pair( sizeof(cl_mem), (void *)&oclspace_weight.data ));
1627             args.push_back( make_pair( sizeof(cl_mem), (void *)&oclspace_ofs.data ));
1628
1629             openCLExecuteKernel(src.clCxt, &imgproc_bilateral, kernelName, globalThreads, localThreads, args, dst.oclchannels(), dst.depth());
1630         }
1631
1632         void bilateralFilter(const oclMat &src, oclMat &dst, int radius, double sigmaclr, double sigmaspc, int borderType)
1633         {
1634             dst.create( src.size(), src.type() );
1635             if ( src.depth() == CV_8U )
1636                 oclbilateralFilter_8u( src, dst, radius, sigmaclr, sigmaspc, borderType );
1637             else
1638                 CV_Error( CV_StsUnsupportedFormat, "Bilateral filtering is only implemented for CV_8U images" );
1639         }
1640
1641     }
1642 }
1643 //////////////////////////////////convolve////////////////////////////////////////////////////
1644
1645 static void convolve_run(const oclMat &src, const oclMat &temp1, oclMat &dst, string kernelName, const cv::ocl::ProgramEntry* source)
1646 {
1647     dst.create(src.size(), src.type());
1648
1649     size_t localThreads[3]  = { 16, 16, 1 };
1650     size_t globalThreads[3] = { dst.cols, dst.rows, 1 };
1651
1652     int src_step = src.step / src.elemSize(), src_offset = src.offset / src.elemSize();
1653     int dst_step = dst.step / dst.elemSize(), dst_offset = dst.offset / dst.elemSize();
1654     int temp1_step = temp1.step / temp1.elemSize(), temp1_offset = temp1.offset / temp1.elemSize();
1655
1656     vector<pair<size_t , const void *> > args;
1657     args.push_back( make_pair( sizeof(cl_mem), (void *)&src.data ));
1658     args.push_back( make_pair( sizeof(cl_mem), (void *)&temp1.data ));
1659     args.push_back( make_pair( sizeof(cl_mem), (void *)&dst.data ));
1660     args.push_back( make_pair( sizeof(cl_int), (void *)&src.rows ));
1661     args.push_back( make_pair( sizeof(cl_int), (void *)&src.cols ));
1662     args.push_back( make_pair( sizeof(cl_int), (void *)&src_step ));
1663     args.push_back( make_pair( sizeof(cl_int), (void *)&dst_step ));
1664     args.push_back( make_pair( sizeof(cl_int), (void *)&temp1_step ));
1665     args.push_back( make_pair( sizeof(cl_int), (void *)&temp1.rows ));
1666     args.push_back( make_pair( sizeof(cl_int), (void *)&temp1.cols ));
1667     args.push_back( make_pair( sizeof(cl_int), (void *)&src_offset ));
1668     args.push_back( make_pair( sizeof(cl_int), (void *)&dst_offset ));
1669     args.push_back( make_pair( sizeof(cl_int), (void *)&temp1_offset ));
1670
1671     openCLExecuteKernel(src.clCxt, source, kernelName, globalThreads, localThreads, args, -1, dst.depth());
1672 }
1673
1674 void cv::ocl::convolve(const oclMat &x, const oclMat &t, oclMat &y)
1675 {
1676     CV_Assert(x.depth() == CV_32F && t.depth() == CV_32F);
1677     CV_Assert(t.cols <= 17 && t.rows <= 17);
1678
1679     y.create(x.size(), x.type());
1680
1681     convolve_run(x, t, y, "convolve", &imgproc_convolve);
1682 }