Merge pull request #1722 from StevenPuttemans:feature_1631_second
[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             float ifx = 1.f / fx, ify = 1.f / fy;
286             int src_step = src.step / src.elemSize(), src_offset = src.offset / src.elemSize();
287             int dst_step = dst.step / dst.elemSize(), dst_offset = dst.offset / dst.elemSize();
288             int ocn = interpolation == INTER_LINEAR ? dst.oclchannels() : -1;
289             int depth = interpolation == INTER_LINEAR ? dst.depth() : -1;
290
291             const char * const interMap[] = { "NN", "LN", "CUBIC", "AREA", "LAN4" };
292             std::string kernelName = std::string("resize") + interMap[interpolation];
293
294             const char * const typeMap[] = { "uchar", "uchar", "ushort", "ushort", "int", "int", "double" };
295             const char * const channelMap[] = { "" , "", "2", "4", "4" };
296             std::string buildOption = format("-D %s -D T=%s%s", interMap[interpolation], typeMap[dst.depth()], channelMap[dst.oclchannels()]);
297
298             //TODO: improve this kernel
299             size_t blkSizeX = 16, blkSizeY = 16;
300             size_t glbSizeX;
301             if (src.type() == CV_8UC1 && interpolation == INTER_LINEAR)
302             {
303                 size_t cols = (dst.cols + dst.offset % 4 + 3) / 4;
304                 glbSizeX = cols % blkSizeX == 0 && cols != 0 ? cols : (cols / blkSizeX + 1) * blkSizeX;
305             }
306             else
307                 glbSizeX = dst.cols;
308
309             size_t globalThreads[3] = { glbSizeX, dst.rows, 1 };
310             size_t localThreads[3] = { blkSizeX, blkSizeY, 1 };
311
312             std::vector< std::pair<size_t, const void *> > args;
313             args.push_back( make_pair(sizeof(cl_mem), (void *)&dst.data));
314             args.push_back( make_pair(sizeof(cl_mem), (void *)&src.data));
315             args.push_back( make_pair(sizeof(cl_int), (void *)&dst_offset));
316             args.push_back( make_pair(sizeof(cl_int), (void *)&src_offset));
317             args.push_back( make_pair(sizeof(cl_int), (void *)&dst_step));
318             args.push_back( make_pair(sizeof(cl_int), (void *)&src_step));
319             args.push_back( make_pair(sizeof(cl_int), (void *)&src.cols));
320             args.push_back( make_pair(sizeof(cl_int), (void *)&src.rows));
321             args.push_back( make_pair(sizeof(cl_int), (void *)&dst.cols));
322             args.push_back( make_pair(sizeof(cl_int), (void *)&dst.rows));
323             args.push_back( make_pair(sizeof(cl_float), (void *)&ifx));
324             args.push_back( make_pair(sizeof(cl_float), (void *)&ify));
325
326             openCLExecuteKernel(src.clCxt, &imgproc_resize, kernelName, globalThreads, localThreads, args,
327                                 ocn, depth, buildOption.c_str());
328         }
329
330         void resize(const oclMat &src, oclMat &dst, Size dsize, double fx, double fy, int interpolation)
331         {
332             CV_Assert(src.type() == CV_8UC1 || src.type() == CV_8UC3 || src.type() == CV_8UC4
333                       || src.type() == CV_32FC1 || src.type() == CV_32FC3 || src.type() == CV_32FC4);
334             CV_Assert(interpolation == INTER_LINEAR || interpolation == INTER_NEAREST);
335             CV_Assert(dsize.area() > 0 || (fx > 0 && fy > 0));
336
337             if (dsize.area() == 0)
338             {
339                 dsize = Size(saturate_cast<int>(src.cols * fx), saturate_cast<int>(src.rows * fy));
340                 CV_Assert(dsize.area() > 0);
341             }
342             else
343             {
344                 fx = (double)dsize.width / src.cols;
345                 fy = (double)dsize.height / src.rows;
346             }
347
348             dst.create(dsize, src.type());
349
350             resize_gpu( src, dst, fx, fy, interpolation);
351         }
352
353         ////////////////////////////////////////////////////////////////////////
354         // medianFilter
355
356         void medianFilter(const oclMat &src, oclMat &dst, int m)
357         {
358             CV_Assert( m % 2 == 1 && m > 1 );
359             CV_Assert( (src.depth() == CV_8U || src.depth() == CV_32F) && (src.channels() == 1 || src.channels() == 4));
360             dst.create(src.size(), src.type());
361
362             int srcStep = src.step / src.elemSize(), dstStep = dst.step / dst.elemSize();
363             int srcOffset = src.offset /  src.elemSize(), dstOffset = dst.offset / dst.elemSize();
364
365             Context *clCxt = src.clCxt;
366
367             vector< pair<size_t, const void *> > args;
368             args.push_back( make_pair( sizeof(cl_mem), (void *)&src.data));
369             args.push_back( make_pair( sizeof(cl_mem), (void *)&dst.data));
370             args.push_back( make_pair( sizeof(cl_int), (void *)&srcOffset));
371             args.push_back( make_pair( sizeof(cl_int), (void *)&dstOffset));
372             args.push_back( make_pair( sizeof(cl_int), (void *)&src.cols));
373             args.push_back( make_pair( sizeof(cl_int), (void *)&src.rows));
374             args.push_back( make_pair( sizeof(cl_int), (void *)&srcStep));
375             args.push_back( make_pair( sizeof(cl_int), (void *)&dstStep));
376
377             size_t globalThreads[3] = {(src.cols + 18) / 16 * 16, (src.rows + 15) / 16 * 16, 1};
378             size_t localThreads[3] = {16, 16, 1};
379
380             if (m == 3)
381             {
382                 string kernelName = "medianFilter3";
383                 openCLExecuteKernel(clCxt, &imgproc_median, kernelName, globalThreads, localThreads, args, src.oclchannels(), src.depth());
384             }
385             else if (m == 5)
386             {
387                 string kernelName = "medianFilter5";
388                 openCLExecuteKernel(clCxt, &imgproc_median, kernelName, globalThreads, localThreads, args, src.oclchannels(), src.depth());
389             }
390             else
391                 CV_Error(CV_StsBadArg, "Non-supported filter length");
392         }
393
394         ////////////////////////////////////////////////////////////////////////
395         // copyMakeBorder
396
397         void copyMakeBorder(const oclMat &src, oclMat &dst, int top, int bottom, int left, int right, int bordertype, const Scalar &scalar)
398         {
399             if (!src.clCxt->supportsFeature(FEATURE_CL_DOUBLE) && src.depth() == CV_64F)
400             {
401                 CV_Error(CV_OpenCLDoubleNotSupported, "Selected device does not support double");
402                 return;
403             }
404
405             oclMat _src = src;
406
407             CV_Assert(top >= 0 && bottom >= 0 && left >= 0 && right >= 0);
408
409             if( (_src.wholecols != _src.cols || _src.wholerows != _src.rows) && (bordertype & BORDER_ISOLATED) == 0 )
410             {
411                 Size wholeSize;
412                 Point ofs;
413                 _src.locateROI(wholeSize, ofs);
414                 int dtop = std::min(ofs.y, top);
415                 int dbottom = std::min(wholeSize.height - _src.rows - ofs.y, bottom);
416                 int dleft = std::min(ofs.x, left);
417                 int dright = std::min(wholeSize.width - _src.cols - ofs.x, right);
418                 _src.adjustROI(dtop, dbottom, dleft, dright);
419                 top -= dtop;
420                 left -= dleft;
421                 bottom -= dbottom;
422                 right -= dright;
423             }
424             bordertype &= ~cv::BORDER_ISOLATED;
425
426             dst.create(_src.rows + top + bottom, _src.cols + left + right, _src.type());
427             int srcStep = _src.step / _src.elemSize(),  dstStep = dst.step / dst.elemSize();
428             int srcOffset = _src.offset / _src.elemSize(), dstOffset = dst.offset / dst.elemSize();
429             int depth = _src.depth(), ochannels = _src.oclchannels();
430
431             int __bordertype[] = { BORDER_CONSTANT, BORDER_REPLICATE, BORDER_REFLECT, BORDER_WRAP, BORDER_REFLECT_101 };
432             const char *borderstr[] = { "BORDER_CONSTANT", "BORDER_REPLICATE", "BORDER_REFLECT", "BORDER_WRAP", "BORDER_REFLECT_101" };
433
434             int bordertype_index = -1;
435             for (int i = 0, end = sizeof(__bordertype) / sizeof(int); i < end; i++)
436                 if (__bordertype[i] == bordertype)
437                 {
438                     bordertype_index = i;
439                     break;
440                 }
441             if (bordertype_index < 0)
442                 CV_Error(CV_StsBadArg, "Unsupported border type");
443
444             size_t localThreads[3] = { 16, 16, 1 };
445             size_t globalThreads[3] = { dst.cols, dst.rows, 1 };
446
447             vector< pair<size_t, const void *> > args;
448             args.push_back( make_pair( sizeof(cl_mem), (void *)&_src.data));
449             args.push_back( make_pair( sizeof(cl_mem), (void *)&dst.data));
450             args.push_back( make_pair( sizeof(cl_int), (void *)&dst.cols));
451             args.push_back( make_pair( sizeof(cl_int), (void *)&dst.rows));
452             args.push_back( make_pair( sizeof(cl_int), (void *)&_src.cols));
453             args.push_back( make_pair( sizeof(cl_int), (void *)&_src.rows));
454             args.push_back( make_pair( sizeof(cl_int), (void *)&srcStep));
455             args.push_back( make_pair( sizeof(cl_int), (void *)&srcOffset));
456             args.push_back( make_pair( sizeof(cl_int), (void *)&dstStep));
457             args.push_back( make_pair( sizeof(cl_int), (void *)&dstOffset));
458             args.push_back( make_pair( sizeof(cl_int), (void *)&top));
459             args.push_back( make_pair( sizeof(cl_int), (void *)&left));
460
461             const char * const typeMap[] = { "uchar", "char", "ushort", "short", "int", "float", "double" };
462             const char * const channelMap[] = { "", "", "2", "4", "4" };
463             std::string buildOptions = format("-D GENTYPE=%s%s -D %s",
464                                               typeMap[depth], channelMap[ochannels],
465                                               borderstr[bordertype_index]);
466
467             int cn = src.channels(), ocn = src.oclchannels();
468             int bufSize = src.elemSize1() * ocn;
469             AutoBuffer<uchar> _buf(bufSize);
470             uchar * buf = (uchar *)_buf;
471             scalarToRawData(scalar, buf, dst.type());
472             memset(buf + src.elemSize1() * cn, 0, (ocn - cn) * src.elemSize1());
473
474             args.push_back( make_pair( bufSize , (void *)buf ));
475
476             openCLExecuteKernel(src.clCxt, &imgproc_copymakeboder, "copymakeborder", globalThreads,
477                                 localThreads, args, -1, -1, buildOptions.c_str());
478         }
479
480         ////////////////////////////////////////////////////////////////////////
481         // warp
482
483         namespace
484         {
485 #define F double
486
487             void convert_coeffs(F *M)
488             {
489                 double D = M[0] * M[4] - M[1] * M[3];
490                 D = D != 0 ? 1. / D : 0;
491                 double A11 = M[4] * D, A22 = M[0] * D;
492                 M[0] = A11;
493                 M[1] *= -D;
494                 M[3] *= -D;
495                 M[4] = A22;
496                 double b1 = -M[0] * M[2] - M[1] * M[5];
497                 double b2 = -M[3] * M[2] - M[4] * M[5];
498                 M[2] = b1;
499                 M[5] = b2;
500             }
501
502             double invert(double *M)
503             {
504 #define Sd(y,x) (Sd[y*3+x])
505 #define Dd(y,x) (Dd[y*3+x])
506 #define det3(m)    (m(0,0)*(m(1,1)*m(2,2) - m(1,2)*m(2,1)) -  \
507                     m(0,1)*(m(1,0)*m(2,2) - m(1,2)*m(2,0)) +  \
508                     m(0,2)*(m(1,0)*m(2,1) - m(1,1)*m(2,0)))
509                 double *Sd = M;
510                 double *Dd = M;
511                 double d = det3(Sd);
512                 double result = 0;
513                 if ( d != 0)
514                 {
515                     double t[9];
516                     result = d;
517                     d = 1. / d;
518
519                     t[0] = (Sd(1, 1) * Sd(2, 2) - Sd(1, 2) * Sd(2, 1)) * d;
520                     t[1] = (Sd(0, 2) * Sd(2, 1) - Sd(0, 1) * Sd(2, 2)) * d;
521                     t[2] = (Sd(0, 1) * Sd(1, 2) - Sd(0, 2) * Sd(1, 1)) * d;
522
523                     t[3] = (Sd(1, 2) * Sd(2, 0) - Sd(1, 0) * Sd(2, 2)) * d;
524                     t[4] = (Sd(0, 0) * Sd(2, 2) - Sd(0, 2) * Sd(2, 0)) * d;
525                     t[5] = (Sd(0, 2) * Sd(1, 0) - Sd(0, 0) * Sd(1, 2)) * d;
526
527                     t[6] = (Sd(1, 0) * Sd(2, 1) - Sd(1, 1) * Sd(2, 0)) * d;
528                     t[7] = (Sd(0, 1) * Sd(2, 0) - Sd(0, 0) * Sd(2, 1)) * d;
529                     t[8] = (Sd(0, 0) * Sd(1, 1) - Sd(0, 1) * Sd(1, 0)) * d;
530
531                     Dd(0, 0) = t[0];
532                     Dd(0, 1) = t[1];
533                     Dd(0, 2) = t[2];
534                     Dd(1, 0) = t[3];
535                     Dd(1, 1) = t[4];
536                     Dd(1, 2) = t[5];
537                     Dd(2, 0) = t[6];
538                     Dd(2, 1) = t[7];
539                     Dd(2, 2) = t[8];
540                 }
541                 return result;
542             }
543
544             void warpAffine_gpu(const oclMat &src, oclMat &dst, F coeffs[2][3], int interpolation)
545             {
546                 CV_Assert( (src.oclchannels() == dst.oclchannels()) );
547                 int srcStep = src.step1();
548                 int dstStep = dst.step1();
549                 float float_coeffs[2][3];
550                 cl_mem coeffs_cm;
551
552                 Context *clCxt = src.clCxt;
553                 string s[3] = {"NN", "Linear", "Cubic"};
554                 string kernelName = "warpAffine" + s[interpolation];
555
556                 if (src.clCxt->supportsFeature(FEATURE_CL_DOUBLE))
557                 {
558                     cl_int st;
559                     coeffs_cm = clCreateBuffer(*(cl_context*)clCxt->getOpenCLContextPtr(), CL_MEM_READ_WRITE, sizeof(F) * 2 * 3, NULL, &st );
560                     openCLVerifyCall(st);
561                     openCLSafeCall(clEnqueueWriteBuffer(*(cl_command_queue*)clCxt->getOpenCLCommandQueuePtr(), (cl_mem)coeffs_cm, 1, 0,
562                                                         sizeof(F) * 2 * 3, coeffs, 0, 0, 0));
563                 }
564                 else
565                 {
566                     cl_int st;
567                     for(int m = 0; m < 2; m++)
568                         for(int n = 0; n < 3; n++)
569                             float_coeffs[m][n] = coeffs[m][n];
570
571                     coeffs_cm = clCreateBuffer(*(cl_context*)clCxt->getOpenCLContextPtr(), CL_MEM_READ_WRITE, sizeof(float) * 2 * 3, NULL, &st );
572                     openCLSafeCall(clEnqueueWriteBuffer(*(cl_command_queue*)clCxt->getOpenCLCommandQueuePtr(), (cl_mem)coeffs_cm,
573                                                         1, 0, sizeof(float) * 2 * 3, float_coeffs, 0, 0, 0));
574
575                 }
576                 //TODO: improve this kernel
577                 size_t blkSizeX = 16, blkSizeY = 16;
578                 size_t glbSizeX;
579                 size_t cols;
580
581                 if (src.type() == CV_8UC1 && interpolation != 2)
582                 {
583                     cols = (dst.cols + dst.offset % 4 + 3) / 4;
584                     glbSizeX = cols % blkSizeX == 0 ? cols : (cols / blkSizeX + 1) * blkSizeX;
585                 }
586                 else
587                 {
588                     cols = dst.cols;
589                     glbSizeX = dst.cols % blkSizeX == 0 ? dst.cols : (dst.cols / blkSizeX + 1) * blkSizeX;
590                 }
591
592                 size_t glbSizeY = dst.rows % blkSizeY == 0 ? dst.rows : (dst.rows / blkSizeY + 1) * blkSizeY;
593                 size_t globalThreads[3] = {glbSizeX, glbSizeY, 1};
594                 size_t localThreads[3] = {blkSizeX, blkSizeY, 1};
595
596                 vector< pair<size_t, const void *> > args;
597
598                 args.push_back(make_pair(sizeof(cl_mem), (void *)&src.data));
599                 args.push_back(make_pair(sizeof(cl_mem), (void *)&dst.data));
600                 args.push_back(make_pair(sizeof(cl_int), (void *)&src.cols));
601                 args.push_back(make_pair(sizeof(cl_int), (void *)&src.rows));
602                 args.push_back(make_pair(sizeof(cl_int), (void *)&dst.cols));
603                 args.push_back(make_pair(sizeof(cl_int), (void *)&dst.rows));
604                 args.push_back(make_pair(sizeof(cl_int), (void *)&srcStep));
605                 args.push_back(make_pair(sizeof(cl_int), (void *)&dstStep));
606                 args.push_back(make_pair(sizeof(cl_int), (void *)&src.offset));
607                 args.push_back(make_pair(sizeof(cl_int), (void *)&dst.offset));
608                 args.push_back(make_pair(sizeof(cl_mem), (void *)&coeffs_cm));
609                 args.push_back(make_pair(sizeof(cl_int), (void *)&cols));
610
611                 openCLExecuteKernel(clCxt, &imgproc_warpAffine, kernelName, globalThreads, localThreads, args, src.oclchannels(), src.depth());
612                 openCLSafeCall(clReleaseMemObject(coeffs_cm));
613             }
614
615             void warpPerspective_gpu(const oclMat &src, oclMat &dst, double coeffs[3][3], int interpolation)
616             {
617                 CV_Assert( (src.oclchannels() == dst.oclchannels()) );
618                 int srcStep = src.step1();
619                 int dstStep = dst.step1();
620                 float float_coeffs[3][3];
621                 cl_mem coeffs_cm;
622
623                 Context *clCxt = src.clCxt;
624                 string s[3] = {"NN", "Linear", "Cubic"};
625                 string kernelName = "warpPerspective" + s[interpolation];
626
627                 if (src.clCxt->supportsFeature(FEATURE_CL_DOUBLE))
628                 {
629                     cl_int st;
630                     coeffs_cm = clCreateBuffer(*(cl_context*)clCxt->getOpenCLContextPtr(), CL_MEM_READ_WRITE, sizeof(double) * 3 * 3, NULL, &st );
631                     openCLVerifyCall(st);
632                     openCLSafeCall(clEnqueueWriteBuffer(*(cl_command_queue*)clCxt->getOpenCLCommandQueuePtr(), (cl_mem)coeffs_cm, 1, 0,
633                                                         sizeof(double) * 3 * 3, coeffs, 0, 0, 0));
634                 }
635                 else
636                 {
637                     cl_int st;
638                     for(int m = 0; m < 3; m++)
639                         for(int n = 0; n < 3; n++)
640                             float_coeffs[m][n] = coeffs[m][n];
641
642                     coeffs_cm = clCreateBuffer(*(cl_context*)clCxt->getOpenCLContextPtr(), CL_MEM_READ_WRITE, sizeof(float) * 3 * 3, NULL, &st );
643                     openCLVerifyCall(st);
644                     openCLSafeCall(clEnqueueWriteBuffer(*(cl_command_queue*)clCxt->getOpenCLCommandQueuePtr(), (cl_mem)coeffs_cm, 1, 0,
645                                                         sizeof(float) * 3 * 3, float_coeffs, 0, 0, 0));
646                 }
647
648                 //TODO: improve this kernel
649                 size_t blkSizeX = 16, blkSizeY = 16;
650                 size_t glbSizeX;
651                 size_t cols;
652                 if (src.type() == CV_8UC1 && interpolation == 0)
653                 {
654                     cols = (dst.cols + dst.offset % 4 + 3) / 4;
655                     glbSizeX = cols % blkSizeX == 0 ? cols : (cols / blkSizeX + 1) * blkSizeX;
656                 }
657                 else
658                 {
659                     cols = dst.cols;
660                     glbSizeX = dst.cols % blkSizeX == 0 ? dst.cols : (dst.cols / blkSizeX + 1) * blkSizeX;
661                 }
662
663                 size_t glbSizeY = dst.rows % blkSizeY == 0 ? dst.rows : (dst.rows / blkSizeY + 1) * blkSizeY;
664                 size_t globalThreads[3] = {glbSizeX, glbSizeY, 1};
665                 size_t localThreads[3] = {blkSizeX, blkSizeY, 1};
666
667                 vector< pair<size_t, const void *> > args;
668
669                 args.push_back(make_pair(sizeof(cl_mem), (void *)&src.data));
670                 args.push_back(make_pair(sizeof(cl_mem), (void *)&dst.data));
671                 args.push_back(make_pair(sizeof(cl_int), (void *)&src.cols));
672                 args.push_back(make_pair(sizeof(cl_int), (void *)&src.rows));
673                 args.push_back(make_pair(sizeof(cl_int), (void *)&dst.cols));
674                 args.push_back(make_pair(sizeof(cl_int), (void *)&dst.rows));
675                 args.push_back(make_pair(sizeof(cl_int), (void *)&srcStep));
676                 args.push_back(make_pair(sizeof(cl_int), (void *)&dstStep));
677                 args.push_back(make_pair(sizeof(cl_int), (void *)&src.offset));
678                 args.push_back(make_pair(sizeof(cl_int), (void *)&dst.offset));
679                 args.push_back(make_pair(sizeof(cl_mem), (void *)&coeffs_cm));
680                 args.push_back(make_pair(sizeof(cl_int), (void *)&cols));
681
682                 openCLExecuteKernel(clCxt, &imgproc_warpPerspective, kernelName, globalThreads, localThreads, args, src.oclchannels(), src.depth());
683                 openCLSafeCall(clReleaseMemObject(coeffs_cm));
684             }
685         }
686
687         void warpAffine(const oclMat &src, oclMat &dst, const Mat &M, Size dsize, int flags)
688         {
689             int interpolation = flags & INTER_MAX;
690
691             CV_Assert((src.depth() == CV_8U  || src.depth() == CV_32F) && src.oclchannels() != 2 && src.oclchannels() != 3);
692             CV_Assert(interpolation == INTER_NEAREST || interpolation == INTER_LINEAR || interpolation == INTER_CUBIC);
693
694             dst.create(dsize, src.type());
695
696             CV_Assert(M.rows == 2 && M.cols == 3);
697
698             int warpInd = (flags & WARP_INVERSE_MAP) >> 4;
699             F coeffs[2][3];
700
701             double coeffsM[2*3];
702             Mat coeffsMat(2, 3, CV_64F, (void *)coeffsM);
703             M.convertTo(coeffsMat, coeffsMat.type());
704             if (!warpInd)
705                 convert_coeffs(coeffsM);
706
707             for(int i = 0; i < 2; ++i)
708                 for(int j = 0; j < 3; ++j)
709                     coeffs[i][j] = coeffsM[i*3+j];
710
711             warpAffine_gpu(src, dst, coeffs, interpolation);
712         }
713
714         void warpPerspective(const oclMat &src, oclMat &dst, const Mat &M, Size dsize, int flags)
715         {
716             int interpolation = flags & INTER_MAX;
717
718             CV_Assert((src.depth() == CV_8U  || src.depth() == CV_32F) && src.oclchannels() != 2 && src.oclchannels() != 3);
719             CV_Assert(interpolation == INTER_NEAREST || interpolation == INTER_LINEAR || interpolation == INTER_CUBIC);
720
721             dst.create(dsize, src.type());
722
723
724             CV_Assert(M.rows == 3 && M.cols == 3);
725
726             int warpInd = (flags & WARP_INVERSE_MAP) >> 4;
727             double coeffs[3][3];
728
729             double coeffsM[3*3];
730             Mat coeffsMat(3, 3, CV_64F, (void *)coeffsM);
731             M.convertTo(coeffsMat, coeffsMat.type());
732             if (!warpInd)
733                 invert(coeffsM);
734
735             for(int i = 0; i < 3; ++i)
736                 for(int j = 0; j < 3; ++j)
737                     coeffs[i][j] = coeffsM[i*3+j];
738
739             warpPerspective_gpu(src, dst, coeffs, interpolation);
740         }
741
742         ////////////////////////////////////////////////////////////////////////
743         // integral
744
745         void integral(const oclMat &src, oclMat &sum, oclMat &sqsum, int sdepth)
746         {
747             CV_Assert(src.type() == CV_8UC1);
748             if (!src.clCxt->supportsFeature(ocl::FEATURE_CL_DOUBLE) && src.depth() == CV_64F)
749             {
750                 CV_Error(CV_OpenCLDoubleNotSupported, "Select device doesn't support double");
751                 return;
752             }
753
754             if( sdepth <= 0 )
755                 sdepth = CV_32S;
756             sdepth = CV_MAT_DEPTH(sdepth);
757             int type = CV_MAKE_TYPE(sdepth, 1);
758
759             int vlen = 4;
760             int offset = src.offset / vlen;
761             int pre_invalid = src.offset % vlen;
762             int vcols = (pre_invalid + src.cols + vlen - 1) / vlen;
763
764             oclMat t_sum , t_sqsum;
765             int w = src.cols + 1, h = src.rows + 1;
766
767             char build_option[250];
768             if(Context::getContext()->supportsFeature(ocl::FEATURE_CL_DOUBLE))
769             {
770                 t_sqsum.create(src.cols, src.rows, CV_64FC1);
771                 sqsum.create(h, w, CV_64FC1);
772                 sprintf(build_option, "-D TYPE=double -D TYPE4=double4 -D convert_TYPE4=convert_double4");
773             }
774             else
775             {
776                 t_sqsum.create(src.cols, src.rows, CV_32FC1);
777                 sqsum.create(h, w, CV_32FC1);
778                 sprintf(build_option, "-D TYPE=float -D TYPE4=float4 -D convert_TYPE4=convert_float4");
779             }
780
781             t_sum.create(src.cols, src.rows, type);
782             sum.create(h, w, type);
783
784             int sum_offset = sum.offset / sum.elemSize();
785             int sqsum_offset = sqsum.offset / sqsum.elemSize();
786
787             vector<pair<size_t , const void *> > args;
788             args.push_back( make_pair( sizeof(cl_mem) , (void *)&src.data ));
789             args.push_back( make_pair( sizeof(cl_mem) , (void *)&t_sum.data ));
790             args.push_back( make_pair( sizeof(cl_mem) , (void *)&t_sqsum.data ));
791             args.push_back( make_pair( sizeof(cl_int) , (void *)&offset ));
792             args.push_back( make_pair( sizeof(cl_int) , (void *)&pre_invalid ));
793             args.push_back( make_pair( sizeof(cl_int) , (void *)&src.rows ));
794             args.push_back( make_pair( sizeof(cl_int) , (void *)&src.cols ));
795             args.push_back( make_pair( sizeof(cl_int) , (void *)&src.step ));
796             args.push_back( make_pair( sizeof(cl_int) , (void *)&t_sum.step));
797             args.push_back( make_pair( sizeof(cl_int) , (void *)&t_sqsum.step));
798             size_t gt[3] = {((vcols + 1) / 2) * 256, 1, 1}, lt[3] = {256, 1, 1};
799             openCLExecuteKernel(src.clCxt, &imgproc_integral, "integral_cols", gt, lt, args, -1, sdepth, build_option);
800
801             args.clear();
802             args.push_back( make_pair( sizeof(cl_mem) , (void *)&t_sum.data ));
803             args.push_back( make_pair( sizeof(cl_mem) , (void *)&t_sqsum.data ));
804             args.push_back( make_pair( sizeof(cl_mem) , (void *)&sum.data ));
805             args.push_back( make_pair( sizeof(cl_mem) , (void *)&sqsum.data ));
806             args.push_back( make_pair( sizeof(cl_int) , (void *)&t_sum.rows ));
807             args.push_back( make_pair( sizeof(cl_int) , (void *)&t_sum.cols ));
808             args.push_back( make_pair( sizeof(cl_int) , (void *)&t_sum.step ));
809             args.push_back( make_pair( sizeof(cl_int) , (void *)&t_sqsum.step));
810             args.push_back( make_pair( sizeof(cl_int) , (void *)&sum.step));
811             args.push_back( make_pair( sizeof(cl_int) , (void *)&sqsum.step));
812             args.push_back( make_pair( sizeof(cl_int) , (void *)&sum_offset));
813             args.push_back( make_pair( sizeof(cl_int) , (void *)&sqsum_offset));
814             size_t gt2[3] = {t_sum.cols  * 32, 1, 1}, lt2[3] = {256, 1, 1};
815             openCLExecuteKernel(src.clCxt, &imgproc_integral, "integral_rows", gt2, lt2, args, -1, sdepth, build_option);
816         }
817
818         void integral(const oclMat &src, oclMat &sum, int sdepth)
819         {
820             CV_Assert(src.type() == CV_8UC1);
821             int vlen = 4;
822             int offset = src.offset / vlen;
823             int pre_invalid = src.offset % vlen;
824             int vcols = (pre_invalid + src.cols + vlen - 1) / vlen;
825
826             if( sdepth <= 0 )
827                 sdepth = CV_32S;
828             sdepth = CV_MAT_DEPTH(sdepth);
829             int type = CV_MAKE_TYPE(sdepth, 1);
830
831             oclMat t_sum;
832             int w = src.cols + 1, h = src.rows + 1;
833
834             t_sum.create(src.cols, src.rows, type);
835             sum.create(h, w, type);
836
837             int sum_offset = sum.offset / vlen;
838             vector<pair<size_t , const void *> > args;
839             args.push_back( make_pair( sizeof(cl_mem) , (void *)&src.data ));
840             args.push_back( make_pair( sizeof(cl_mem) , (void *)&t_sum.data ));
841             args.push_back( make_pair( sizeof(cl_int) , (void *)&offset ));
842             args.push_back( make_pair( sizeof(cl_int) , (void *)&pre_invalid ));
843             args.push_back( make_pair( sizeof(cl_int) , (void *)&src.rows ));
844             args.push_back( make_pair( sizeof(cl_int) , (void *)&src.cols ));
845             args.push_back( make_pair( sizeof(cl_int) , (void *)&src.step ));
846             args.push_back( make_pair( sizeof(cl_int) , (void *)&t_sum.step));
847             size_t gt[3] = {((vcols + 1) / 2) * 256, 1, 1}, lt[3] = {256, 1, 1};
848             openCLExecuteKernel(src.clCxt, &imgproc_integral_sum, "integral_sum_cols", gt, lt, args, -1, sdepth);
849
850             args.clear();
851             args.push_back( make_pair( sizeof(cl_mem) , (void *)&t_sum.data ));
852             args.push_back( make_pair( sizeof(cl_mem) , (void *)&sum.data ));
853             args.push_back( make_pair( sizeof(cl_int) , (void *)&t_sum.rows ));
854             args.push_back( make_pair( sizeof(cl_int) , (void *)&t_sum.cols ));
855             args.push_back( make_pair( sizeof(cl_int) , (void *)&t_sum.step ));
856             args.push_back( make_pair( sizeof(cl_int) , (void *)&sum.step));
857             args.push_back( make_pair( sizeof(cl_int) , (void *)&sum_offset));
858             size_t gt2[3] = {t_sum.cols  * 32, 1, 1}, lt2[3] = {256, 1, 1};
859             openCLExecuteKernel(src.clCxt, &imgproc_integral_sum, "integral_sum_rows", gt2, lt2, args, -1, sdepth);
860         }
861
862         /////////////////////// corner //////////////////////////////
863
864         static void extractCovData(const oclMat &src, oclMat &Dx, oclMat &Dy,
865                             int blockSize, int ksize, int borderType)
866         {
867             CV_Assert(src.type() == CV_8UC1 || src.type() == CV_32FC1);
868             double scale = static_cast<double>(1 << ((ksize > 0 ? ksize : 3) - 1)) * blockSize;
869             if (ksize < 0)
870                 scale *= 2.;
871
872             if (src.depth() == CV_8U)
873             {
874                 scale *= 255.;
875                 scale = 1. / scale;
876             }
877             else
878                 scale = 1. / scale;
879
880             if (ksize > 0)
881             {
882                 Context* clCxt = Context::getContext();
883                 if(clCxt->supportsFeature(FEATURE_CL_INTEL_DEVICE) && src.type() == CV_8UC1 &&
884                     src.cols % 8 == 0 && src.rows % 8 == 0 &&
885                     ksize==3 &&
886                     (borderType ==cv::BORDER_REFLECT ||
887                      borderType == cv::BORDER_REPLICATE ||
888                      borderType ==cv::BORDER_REFLECT101 ||
889                      borderType ==cv::BORDER_WRAP))
890                 {
891                     Dx.create(src.size(), CV_32FC1);
892                     Dy.create(src.size(), CV_32FC1);
893
894                     const unsigned int block_x = 8;
895                     const unsigned int block_y = 8;
896
897                     unsigned int src_pitch = src.step;
898                     unsigned int dst_pitch = Dx.cols;
899
900                     float _scale = scale;
901
902                     std::vector<std::pair<size_t , const void *> > args;
903                     args.push_back( std::make_pair( sizeof(cl_mem) , (void *)&src.data ));
904                     args.push_back( std::make_pair( sizeof(cl_mem) , (void *)&Dx.data ));
905                     args.push_back( std::make_pair( sizeof(cl_mem) , (void *)&Dy.data ));
906                     args.push_back( std::make_pair( sizeof(cl_int) , (void *)&src.cols ));
907                     args.push_back( std::make_pair( sizeof(cl_int) , (void *)&src.rows ));
908                     args.push_back( std::make_pair( sizeof(cl_uint) , (void *)&src_pitch ));
909                     args.push_back( std::make_pair( sizeof(cl_uint) , (void *)&dst_pitch ));
910                     args.push_back( std::make_pair( sizeof(cl_float) , (void *)&_scale ));
911                     size_t gt2[3] = {src.cols, src.rows, 1}, lt2[3] = {block_x, block_y, 1};
912
913                     string option = "-D BLK_X=8 -D BLK_Y=8";
914                     switch(borderType)
915                     {
916                     case cv::BORDER_REPLICATE:
917                         option += " -D BORDER_REPLICATE";
918                         break;
919                     case cv::BORDER_REFLECT:
920                         option += " -D BORDER_REFLECT";
921                         break;
922                     case cv::BORDER_REFLECT101:
923                         option += " -D BORDER_REFLECT101";
924                         break;
925                     case cv::BORDER_WRAP:
926                         option += " -D BORDER_WRAP";
927                         break;
928                     }
929                     openCLExecuteKernel(src.clCxt, &imgproc_sobel3, "sobel3", gt2, lt2, args, -1, -1, option.c_str() );
930                 }
931                 else
932                 {
933                     Sobel(src, Dx, CV_32F, 1, 0, ksize, scale, 0, borderType);
934                     Sobel(src, Dy, CV_32F, 0, 1, ksize, scale, 0, borderType);
935                 }
936             }
937             else
938             {
939                 Scharr(src, Dx, CV_32F, 1, 0, scale, 0, borderType);
940                 Scharr(src, Dy, CV_32F, 0, 1, scale, 0, borderType);
941             }
942             CV_Assert(Dx.offset == 0 && Dy.offset == 0);
943         }
944
945         static void corner_ocl(const cv::ocl::ProgramEntry* source, string kernelName, int block_size, float k, oclMat &Dx, oclMat &Dy,
946                         oclMat &dst, int border_type)
947         {
948             char borderType[30];
949             switch (border_type)
950             {
951             case cv::BORDER_CONSTANT:
952                 sprintf(borderType, "BORDER_CONSTANT");
953                 break;
954             case cv::BORDER_REFLECT101:
955                 sprintf(borderType, "BORDER_REFLECT101");
956                 break;
957             case cv::BORDER_REFLECT:
958                 sprintf(borderType, "BORDER_REFLECT");
959                 break;
960             case cv::BORDER_REPLICATE:
961                 sprintf(borderType, "BORDER_REPLICATE");
962                 break;
963             default:
964                 CV_Error(CV_StsBadFlag, "BORDER type is not supported!");
965             }
966
967             std::string buildOptions = format("-D anX=%d -D anY=%d -D ksX=%d -D ksY=%d -D %s",
968                     block_size / 2, block_size / 2, block_size, block_size, borderType);
969
970             size_t blockSizeX = 256, blockSizeY = 1;
971             size_t gSize = blockSizeX - block_size / 2 * 2;
972             size_t globalSizeX = (Dx.cols) % gSize == 0 ? Dx.cols / gSize * blockSizeX : (Dx.cols / gSize + 1) * blockSizeX;
973             size_t rows_per_thread = 2;
974             size_t globalSizeY = ((Dx.rows + rows_per_thread - 1) / rows_per_thread) % blockSizeY == 0 ?
975                                  ((Dx.rows + rows_per_thread - 1) / rows_per_thread) :
976                                  (((Dx.rows + rows_per_thread - 1) / rows_per_thread) / blockSizeY + 1) * blockSizeY;
977
978             size_t gt[3] = { globalSizeX, globalSizeY, 1 };
979             size_t lt[3]  = { blockSizeX, blockSizeY, 1 };
980             vector<pair<size_t , const void *> > args;
981             args.push_back( make_pair( sizeof(cl_mem) , (void *)&Dx.data ));
982             args.push_back( make_pair( sizeof(cl_mem) , (void *)&Dy.data));
983             args.push_back( make_pair( sizeof(cl_mem) , (void *)&dst.data));
984             args.push_back( make_pair( sizeof(cl_int) , (void *)&Dx.offset ));
985             args.push_back( make_pair( sizeof(cl_int) , (void *)&Dx.wholerows ));
986             args.push_back( make_pair( sizeof(cl_int) , (void *)&Dx.wholecols ));
987             args.push_back( make_pair(sizeof(cl_int), (void *)&Dx.step));
988             args.push_back( make_pair( sizeof(cl_int) , (void *)&Dy.offset ));
989             args.push_back( make_pair( sizeof(cl_int) , (void *)&Dy.wholerows ));
990             args.push_back( make_pair( sizeof(cl_int) , (void *)&Dy.wholecols ));
991             args.push_back( make_pair(sizeof(cl_int), (void *)&Dy.step));
992             args.push_back( make_pair(sizeof(cl_int), (void *)&dst.offset));
993             args.push_back( make_pair(sizeof(cl_int), (void *)&dst.rows));
994             args.push_back( make_pair(sizeof(cl_int), (void *)&dst.cols));
995             args.push_back( make_pair(sizeof(cl_int), (void *)&dst.step));
996             args.push_back( make_pair( sizeof(cl_float) , (void *)&k));
997
998             openCLExecuteKernel(dst.clCxt, source, kernelName, gt, lt, args, -1, -1, buildOptions.c_str());
999         }
1000
1001         void cornerHarris(const oclMat &src, oclMat &dst, int blockSize, int ksize,
1002                           double k, int borderType)
1003         {
1004             oclMat dx, dy;
1005             cornerHarris_dxdy(src, dst, dx, dy, blockSize, ksize, k, borderType);
1006         }
1007
1008         void cornerHarris_dxdy(const oclMat &src, oclMat &dst, oclMat &dx, oclMat &dy, int blockSize, int ksize,
1009                           double k, int borderType)
1010         {
1011             if (!src.clCxt->supportsFeature(FEATURE_CL_DOUBLE) && src.depth() == CV_64F)
1012             {
1013                 CV_Error(CV_OpenCLDoubleNotSupported, "Selected device doesn't support double");
1014                 return;
1015             }
1016
1017             CV_Assert(borderType == cv::BORDER_CONSTANT || borderType == cv::BORDER_REFLECT101 || borderType == cv::BORDER_REPLICATE
1018                       || borderType == cv::BORDER_REFLECT);
1019
1020             extractCovData(src, dx, dy, blockSize, ksize, borderType);
1021             dst.create(src.size(), CV_32FC1);
1022             corner_ocl(&imgproc_calcHarris, "calcHarris", blockSize, static_cast<float>(k), dx, dy, dst, borderType);
1023         }
1024
1025         void cornerMinEigenVal(const oclMat &src, oclMat &dst, int blockSize, int ksize, int borderType)
1026         {
1027             oclMat dx, dy;
1028             cornerMinEigenVal_dxdy(src, dst, dx, dy, blockSize, ksize, borderType);
1029         }
1030
1031         void cornerMinEigenVal_dxdy(const oclMat &src, oclMat &dst, oclMat &dx, oclMat &dy, int blockSize, int ksize, int borderType)
1032         {
1033             if (!src.clCxt->supportsFeature(FEATURE_CL_DOUBLE) && src.depth() == CV_64F)
1034             {
1035                 CV_Error(CV_OpenCLDoubleNotSupported, "Selected device doesn't support double");
1036                 return;
1037             }
1038
1039             CV_Assert(borderType == cv::BORDER_CONSTANT || borderType == cv::BORDER_REFLECT101 ||
1040                       borderType == cv::BORDER_REPLICATE || borderType == cv::BORDER_REFLECT);
1041
1042             extractCovData(src, dx, dy, blockSize, ksize, borderType);
1043             dst.create(src.size(), CV_32F);
1044
1045             corner_ocl(&imgproc_calcMinEigenVal, "calcMinEigenVal", blockSize, 0, dx, dy, dst, borderType);
1046         }
1047
1048         /////////////////////////////////// MeanShiftfiltering ///////////////////////////////////////////////
1049
1050         static void meanShiftFiltering_gpu(const oclMat &src, oclMat dst, int sp, int sr, int maxIter, float eps)
1051         {
1052             CV_Assert( (src.cols == dst.cols) && (src.rows == dst.rows) );
1053             CV_Assert( !(dst.step & 0x3) );
1054
1055             //Arrange the NDRange
1056             int col = src.cols, row = src.rows;
1057             int ltx = 16, lty = 8;
1058             if (src.cols % ltx != 0)
1059                 col = (col / ltx + 1) * ltx;
1060             if (src.rows % lty != 0)
1061                 row = (row / lty + 1) * lty;
1062
1063             size_t globalThreads[3] = {col, row, 1};
1064             size_t localThreads[3]  = {ltx, lty, 1};
1065
1066             //set args
1067             vector<pair<size_t , const void *> > args;
1068             args.push_back( make_pair( sizeof(cl_mem) , (void *)&dst.data ));
1069             args.push_back( make_pair( sizeof(cl_int) , (void *)&dst.step ));
1070             args.push_back( make_pair( sizeof(cl_mem) , (void *)&src.data ));
1071             args.push_back( make_pair( sizeof(cl_int) , (void *)&src.step ));
1072             args.push_back( make_pair( sizeof(cl_int) , (void *)&dst.offset ));
1073             args.push_back( make_pair( sizeof(cl_int) , (void *)&src.offset ));
1074             args.push_back( make_pair( sizeof(cl_int) , (void *)&dst.cols ));
1075             args.push_back( make_pair( sizeof(cl_int) , (void *)&dst.rows ));
1076             args.push_back( make_pair( sizeof(cl_int) , (void *)&sp ));
1077             args.push_back( make_pair( sizeof(cl_int) , (void *)&sr ));
1078             args.push_back( make_pair( sizeof(cl_int) , (void *)&maxIter ));
1079             args.push_back( make_pair( sizeof(cl_float) , (void *)&eps ));
1080
1081             openCLExecuteKernel(src.clCxt, &meanShift, "meanshift_kernel", globalThreads, localThreads, args, -1, -1);
1082         }
1083
1084         void meanShiftFiltering(const oclMat &src, oclMat &dst, int sp, int sr, TermCriteria criteria)
1085         {
1086             if ( src.empty() )
1087                 CV_Error( CV_StsBadArg, "The input image is empty" );
1088
1089             if ( src.depth() != CV_8U || src.oclchannels() != 4 )
1090                 CV_Error( CV_StsUnsupportedFormat, "Only 8-bit, 4-channel images are supported" );
1091
1092             dst.create( src.size(), CV_8UC4 );
1093
1094             if ( !(criteria.type & TermCriteria::MAX_ITER) )
1095                 criteria.maxCount = 5;
1096
1097             int maxIter = std::min(std::max(criteria.maxCount, 1), 100);
1098
1099             float eps;
1100             if ( !(criteria.type & TermCriteria::EPS) )
1101                 eps = 1.f;
1102             eps = (float)std::max(criteria.epsilon, 0.0);
1103
1104             meanShiftFiltering_gpu(src, dst, sp, sr, maxIter, eps);
1105         }
1106
1107         static void meanShiftProc_gpu(const oclMat &src, oclMat dstr, oclMat dstsp, int sp, int sr, int maxIter, float eps)
1108         {
1109             //sanity checks
1110             CV_Assert( (src.cols == dstr.cols) && (src.rows == dstr.rows) &&
1111                        (src.rows == dstsp.rows) && (src.cols == dstsp.cols));
1112             CV_Assert( !(dstsp.step & 0x3) );
1113
1114             //Arrange the NDRange
1115             int col = src.cols, row = src.rows;
1116             int ltx = 16, lty = 8;
1117             if (src.cols % ltx != 0)
1118                 col = (col / ltx + 1) * ltx;
1119             if (src.rows % lty != 0)
1120                 row = (row / lty + 1) * lty;
1121
1122             size_t globalThreads[3] = {col, row, 1};
1123             size_t localThreads[3]  = {ltx, lty, 1};
1124
1125             //set args
1126             vector<pair<size_t , const void *> > args;
1127             args.push_back( make_pair( sizeof(cl_mem) , (void *)&src.data ));
1128             args.push_back( make_pair( sizeof(cl_mem) , (void *)&dstr.data ));
1129             args.push_back( make_pair( sizeof(cl_mem) , (void *)&dstsp.data ));
1130             args.push_back( make_pair( sizeof(cl_int) , (void *)&src.step ));
1131             args.push_back( make_pair( sizeof(cl_int) , (void *)&dstr.step ));
1132             args.push_back( make_pair( sizeof(cl_int) , (void *)&dstsp.step ));
1133             args.push_back( make_pair( sizeof(cl_int) , (void *)&src.offset ));
1134             args.push_back( make_pair( sizeof(cl_int) , (void *)&dstr.offset ));
1135             args.push_back( make_pair( sizeof(cl_int) , (void *)&dstsp.offset ));
1136             args.push_back( make_pair( sizeof(cl_int) , (void *)&dstr.cols ));
1137             args.push_back( make_pair( sizeof(cl_int) , (void *)&dstr.rows ));
1138             args.push_back( make_pair( sizeof(cl_int) , (void *)&sp ));
1139             args.push_back( make_pair( sizeof(cl_int) , (void *)&sr ));
1140             args.push_back( make_pair( sizeof(cl_int) , (void *)&maxIter ));
1141             args.push_back( make_pair( sizeof(cl_float) , (void *)&eps ));
1142
1143             openCLExecuteKernel(src.clCxt, &meanShift, "meanshiftproc_kernel", globalThreads, localThreads, args, -1, -1);
1144         }
1145
1146         void meanShiftProc(const oclMat &src, oclMat &dstr, oclMat &dstsp, int sp, int sr, TermCriteria criteria)
1147         {
1148             if ( src.empty() )
1149                 CV_Error( CV_StsBadArg, "The input image is empty" );
1150
1151             if ( src.depth() != CV_8U || src.oclchannels() != 4 )
1152                 CV_Error( CV_StsUnsupportedFormat, "Only 8-bit, 4-channel images are supported" );
1153
1154 //            if (!src.clCxt->supportsFeature(FEATURE_CL_DOUBLE))
1155 //            {
1156 //                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");
1157 //                return;
1158 //            }
1159
1160             dstr.create( src.size(), CV_8UC4 );
1161             dstsp.create( src.size(), CV_16SC2 );
1162
1163             if ( !(criteria.type & TermCriteria::MAX_ITER) )
1164                 criteria.maxCount = 5;
1165
1166             int maxIter = std::min(std::max(criteria.maxCount, 1), 100);
1167
1168             float eps;
1169             if ( !(criteria.type & TermCriteria::EPS) )
1170                 eps = 1.f;
1171             eps = (float)std::max(criteria.epsilon, 0.0);
1172
1173             meanShiftProc_gpu(src, dstr, dstsp, sp, sr, maxIter, eps);
1174         }
1175
1176         ///////////////////////////////////////////////////////////////////////////////////////////////////
1177         ////////////////////////////////////////////////////hist///////////////////////////////////////////////
1178         /////////////////////////////////////////////////////////////////////////////////////////////////////
1179
1180         namespace histograms
1181         {
1182             const int PARTIAL_HISTOGRAM256_COUNT = 256;
1183             const int HISTOGRAM256_BIN_COUNT = 256;
1184         }
1185         ///////////////////////////////calcHist/////////////////////////////////////////////////////////////////
1186         static void calc_sub_hist(const oclMat &mat_src, const oclMat &mat_sub_hist)
1187         {
1188             using namespace histograms;
1189
1190             int depth = mat_src.depth();
1191
1192             size_t localThreads[3]  = { HISTOGRAM256_BIN_COUNT, 1, 1 };
1193             size_t globalThreads[3] = { PARTIAL_HISTOGRAM256_COUNT *localThreads[0], 1, 1};
1194
1195             int dataWidth = 16;
1196             int dataWidth_bits = 4;
1197             int mask = dataWidth - 1;
1198
1199             int cols = mat_src.cols * mat_src.oclchannels();
1200             int src_offset = mat_src.offset;
1201             int hist_step = mat_sub_hist.step >> 2;
1202             int left_col = 0, right_col = 0;
1203
1204             if (cols >= dataWidth * 2 - 1)
1205             {
1206                 left_col = dataWidth - (src_offset & mask);
1207                 left_col &= mask;
1208                 src_offset += left_col;
1209                 cols -= left_col;
1210                 right_col = cols & mask;
1211                 cols -= right_col;
1212             }
1213             else
1214             {
1215                 left_col = cols;
1216                 right_col = 0;
1217                 cols = 0;
1218                 globalThreads[0] = 0;
1219             }
1220
1221             vector<pair<size_t , const void *> > args;
1222             if (globalThreads[0] != 0)
1223             {
1224                 int tempcols = cols >> dataWidth_bits;
1225                 int inc_x = globalThreads[0] % tempcols;
1226                 int inc_y = globalThreads[0] / tempcols;
1227                 src_offset >>= dataWidth_bits;
1228                 int src_step = mat_src.step >> dataWidth_bits;
1229                 int datacount = tempcols * mat_src.rows;
1230
1231                 args.push_back( make_pair( sizeof(cl_mem), (void *)&mat_src.data));
1232                 args.push_back( make_pair( sizeof(cl_int), (void *)&src_step));
1233                 args.push_back( make_pair( sizeof(cl_int), (void *)&src_offset));
1234                 args.push_back( make_pair( sizeof(cl_mem), (void *)&mat_sub_hist.data));
1235                 args.push_back( make_pair( sizeof(cl_int), (void *)&datacount));
1236                 args.push_back( make_pair( sizeof(cl_int), (void *)&tempcols));
1237                 args.push_back( make_pair( sizeof(cl_int), (void *)&inc_x));
1238                 args.push_back( make_pair( sizeof(cl_int), (void *)&inc_y));
1239                 args.push_back( make_pair( sizeof(cl_int), (void *)&hist_step));
1240
1241                 openCLExecuteKernel(mat_src.clCxt, &imgproc_histogram, "calc_sub_hist", globalThreads, localThreads, args, -1, depth);
1242             }
1243
1244             if (left_col != 0 || right_col != 0)
1245             {
1246                 src_offset = mat_src.offset;
1247                 localThreads[0] = 1;
1248                 localThreads[1] = 256;
1249                 globalThreads[0] = left_col + right_col;
1250                 globalThreads[1] = mat_src.rows;
1251
1252                 args.clear();
1253                 args.push_back( make_pair( sizeof(cl_mem), (void *)&mat_src.data));
1254                 args.push_back( make_pair( sizeof(cl_int), (void *)&mat_src.step));
1255                 args.push_back( make_pair( sizeof(cl_int), (void *)&src_offset));
1256                 args.push_back( make_pair( sizeof(cl_mem), (void *)&mat_sub_hist.data));
1257                 args.push_back( make_pair( sizeof(cl_int), (void *)&left_col));
1258                 args.push_back( make_pair( sizeof(cl_int), (void *)&cols));
1259                 args.push_back( make_pair( sizeof(cl_int), (void *)&mat_src.rows));
1260                 args.push_back( make_pair( sizeof(cl_int), (void *)&hist_step));
1261
1262                 openCLExecuteKernel(mat_src.clCxt, &imgproc_histogram, "calc_sub_hist_border", globalThreads, localThreads, args, -1, depth);
1263             }
1264         }
1265
1266         static void merge_sub_hist(const oclMat &sub_hist, oclMat &mat_hist)
1267         {
1268             using namespace histograms;
1269
1270             size_t localThreads[3]  = { 256, 1, 1 };
1271             size_t globalThreads[3] = { HISTOGRAM256_BIN_COUNT *localThreads[0], 1, 1};
1272             int src_step = sub_hist.step >> 2;
1273
1274             vector<pair<size_t , const void *> > args;
1275             args.push_back( make_pair( sizeof(cl_mem), (void *)&sub_hist.data));
1276             args.push_back( make_pair( sizeof(cl_mem), (void *)&mat_hist.data));
1277             args.push_back( make_pair( sizeof(cl_int), (void *)&src_step));
1278
1279             openCLExecuteKernel(sub_hist.clCxt, &imgproc_histogram, "merge_hist", globalThreads, localThreads, args, -1, -1);
1280         }
1281
1282         void calcHist(const oclMat &mat_src, oclMat &mat_hist)
1283         {
1284             using namespace histograms;
1285             CV_Assert(mat_src.type() == CV_8UC1);
1286             mat_hist.create(1, 256, CV_32SC1);
1287
1288             oclMat buf(PARTIAL_HISTOGRAM256_COUNT, HISTOGRAM256_BIN_COUNT, CV_32SC1);
1289             buf.setTo(0);
1290
1291             calc_sub_hist(mat_src, buf);
1292             merge_sub_hist(buf, mat_hist);
1293         }
1294
1295         ///////////////////////////////////equalizeHist/////////////////////////////////////////////////////
1296         void equalizeHist(const oclMat &mat_src, oclMat &mat_dst)
1297         {
1298             mat_dst.create(mat_src.rows, mat_src.cols, CV_8UC1);
1299
1300             oclMat mat_hist(1, 256, CV_32SC1);
1301
1302             calcHist(mat_src, mat_hist);
1303
1304             size_t localThreads[3] = { 256, 1, 1};
1305             size_t globalThreads[3] = { 256, 1, 1};
1306             oclMat lut(1, 256, CV_8UC1);
1307             int total = mat_src.rows * mat_src.cols;
1308
1309             vector<pair<size_t , const void *> > args;
1310             args.push_back( make_pair( sizeof(cl_mem), (void *)&lut.data));
1311             args.push_back( make_pair( sizeof(cl_mem), (void *)&mat_hist.data));
1312             args.push_back( make_pair( sizeof(int), (void *)&total));
1313
1314             openCLExecuteKernel(mat_src.clCxt, &imgproc_histogram, "calLUT", globalThreads, localThreads, args, -1, -1);
1315             LUT(mat_src, lut, mat_dst);
1316         }
1317
1318         ////////////////////////////////////////////////////////////////////////
1319         // CLAHE
1320         namespace clahe
1321         {
1322             static void calcLut(const oclMat &src, oclMat &dst,
1323                 const int tilesX, const int tilesY, const cv::Size tileSize,
1324                 const int clipLimit, const float lutScale)
1325             {
1326                 cl_int2 tile_size;
1327                 tile_size.s[0] = tileSize.width;
1328                 tile_size.s[1] = tileSize.height;
1329
1330                 std::vector<pair<size_t , const void *> > args;
1331                 args.push_back( std::make_pair( sizeof(cl_mem), (void *)&src.data ));
1332                 args.push_back( std::make_pair( sizeof(cl_mem), (void *)&dst.data ));
1333                 args.push_back( std::make_pair( sizeof(cl_int), (void *)&src.step ));
1334                 args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst.step ));
1335                 args.push_back( std::make_pair( sizeof(cl_int2), (void *)&tile_size ));
1336                 args.push_back( std::make_pair( sizeof(cl_int), (void *)&tilesX ));
1337                 args.push_back( std::make_pair( sizeof(cl_int), (void *)&clipLimit ));
1338                 args.push_back( std::make_pair( sizeof(cl_float), (void *)&lutScale ));
1339                 args.push_back( std::make_pair( sizeof(cl_int), (void *)&src.offset ));
1340                 args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst.offset ));
1341
1342                 String kernelName = "calcLut";
1343                 size_t localThreads[3]  = { 32, 8, 1 };
1344                 size_t globalThreads[3] = { tilesX * localThreads[0], tilesY * localThreads[1], 1 };
1345                 bool is_cpu = isCpuDevice();
1346                 if (is_cpu)
1347                     openCLExecuteKernel(Context::getContext(), &imgproc_clahe, kernelName, globalThreads, localThreads, args, -1, -1, (char*)"-D CPU");
1348                 else
1349                 {
1350                     cl_kernel kernel = openCLGetKernelFromSource(Context::getContext(), &imgproc_clahe, kernelName);
1351                     int wave_size = (int)queryWaveFrontSize(kernel);
1352                     openCLSafeCall(clReleaseKernel(kernel));
1353
1354                     std::string opt = format("-D WAVE_SIZE=%d", wave_size);
1355                     openCLExecuteKernel(Context::getContext(), &imgproc_clahe, kernelName, globalThreads, localThreads, args, -1, -1, opt.c_str());
1356                 }
1357             }
1358
1359             static void transform(const oclMat &src, oclMat &dst, const oclMat &lut,
1360                 const int tilesX, const int tilesY, const Size & tileSize)
1361             {
1362                 cl_int2 tile_size;
1363                 tile_size.s[0] = tileSize.width;
1364                 tile_size.s[1] = tileSize.height;
1365
1366                 std::vector<pair<size_t , const void *> > args;
1367                 args.push_back( std::make_pair( sizeof(cl_mem), (void *)&src.data ));
1368                 args.push_back( std::make_pair( sizeof(cl_mem), (void *)&dst.data ));
1369                 args.push_back( std::make_pair( sizeof(cl_mem), (void *)&lut.data ));
1370                 args.push_back( std::make_pair( sizeof(cl_int), (void *)&src.step ));
1371                 args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst.step ));
1372                 args.push_back( std::make_pair( sizeof(cl_int), (void *)&lut.step ));
1373                 args.push_back( std::make_pair( sizeof(cl_int), (void *)&src.cols ));
1374                 args.push_back( std::make_pair( sizeof(cl_int), (void *)&src.rows ));
1375                 args.push_back( std::make_pair( sizeof(cl_int2), (void *)&tile_size ));
1376                 args.push_back( std::make_pair( sizeof(cl_int), (void *)&tilesX ));
1377                 args.push_back( std::make_pair( sizeof(cl_int), (void *)&tilesY ));
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                 args.push_back( std::make_pair( sizeof(cl_int), (void *)&lut.offset ));
1381
1382                 size_t localThreads[3]  = { 32, 8, 1 };
1383                 size_t globalThreads[3] = { src.cols, src.rows, 1 };
1384
1385                 openCLExecuteKernel(Context::getContext(), &imgproc_clahe, "transform", globalThreads, localThreads, args, -1, -1);
1386             }
1387         }
1388
1389         namespace
1390         {
1391             class CLAHE_Impl : public cv::CLAHE
1392             {
1393             public:
1394                 CLAHE_Impl(double clipLimit = 40.0, int tilesX = 8, int tilesY = 8);
1395
1396                 cv::AlgorithmInfo* info() const;
1397
1398                 void apply(cv::InputArray src, cv::OutputArray dst);
1399
1400                 void setClipLimit(double clipLimit);
1401                 double getClipLimit() const;
1402
1403                 void setTilesGridSize(cv::Size tileGridSize);
1404                 cv::Size getTilesGridSize() const;
1405
1406                 void collectGarbage();
1407
1408             private:
1409                 double clipLimit_;
1410                 int tilesX_;
1411                 int tilesY_;
1412
1413                 oclMat srcExt_;
1414                 oclMat lut_;
1415             };
1416
1417             CLAHE_Impl::CLAHE_Impl(double clipLimit, int tilesX, int tilesY) :
1418                 clipLimit_(clipLimit), tilesX_(tilesX), tilesY_(tilesY)
1419             {
1420             }
1421
1422             CV_INIT_ALGORITHM(CLAHE_Impl, "CLAHE_OCL",
1423                 obj.info()->addParam(obj, "clipLimit", obj.clipLimit_);
1424                 obj.info()->addParam(obj, "tilesX", obj.tilesX_);
1425                 obj.info()->addParam(obj, "tilesY", obj.tilesY_))
1426
1427             void CLAHE_Impl::apply(cv::InputArray src_raw, cv::OutputArray dst_raw)
1428             {
1429                 oclMat& src = getOclMatRef(src_raw);
1430                 oclMat& dst = getOclMatRef(dst_raw);
1431                 CV_Assert( src.type() == CV_8UC1 );
1432
1433                 dst.create( src.size(), src.type() );
1434
1435                 const int histSize = 256;
1436
1437                 ensureSizeIsEnough(tilesX_ * tilesY_, histSize, CV_8UC1, lut_);
1438
1439                 cv::Size tileSize;
1440                 oclMat srcForLut;
1441
1442                 if (src.cols % tilesX_ == 0 && src.rows % tilesY_ == 0)
1443                 {
1444                     tileSize = cv::Size(src.cols / tilesX_, src.rows / tilesY_);
1445                     srcForLut = src;
1446                 }
1447                 else
1448                 {
1449                     ocl::copyMakeBorder(src, srcExt_, 0, tilesY_ - (src.rows % tilesY_), 0,
1450                                             tilesX_ - (src.cols % tilesX_), BORDER_REFLECT_101, Scalar::all(0));
1451
1452                     tileSize = Size(srcExt_.cols / tilesX_, srcExt_.rows / tilesY_);
1453                     srcForLut = srcExt_;
1454                 }
1455
1456                 const int tileSizeTotal = tileSize.area();
1457                 const float lutScale = static_cast<float>(histSize - 1) / tileSizeTotal;
1458
1459                 int clipLimit = 0;
1460                 if (clipLimit_ > 0.0)
1461                 {
1462                     clipLimit = static_cast<int>(clipLimit_ * tileSizeTotal / histSize);
1463                     clipLimit = std::max(clipLimit, 1);
1464                 }
1465
1466                 clahe::calcLut(srcForLut, lut_, tilesX_, tilesY_, tileSize, clipLimit, lutScale);
1467                 clahe::transform(src, dst, lut_, tilesX_, tilesY_, tileSize);
1468             }
1469
1470             void CLAHE_Impl::setClipLimit(double clipLimit)
1471             {
1472                 clipLimit_ = clipLimit;
1473             }
1474
1475             double CLAHE_Impl::getClipLimit() const
1476             {
1477                 return clipLimit_;
1478             }
1479
1480             void CLAHE_Impl::setTilesGridSize(cv::Size tileGridSize)
1481             {
1482                 tilesX_ = tileGridSize.width;
1483                 tilesY_ = tileGridSize.height;
1484             }
1485
1486             cv::Size CLAHE_Impl::getTilesGridSize() const
1487             {
1488                 return cv::Size(tilesX_, tilesY_);
1489             }
1490
1491             void CLAHE_Impl::collectGarbage()
1492             {
1493                 srcExt_.release();
1494                 lut_.release();
1495             }
1496         }
1497
1498         cv::Ptr<cv::CLAHE> createCLAHE(double clipLimit, cv::Size tileGridSize)
1499         {
1500             return new CLAHE_Impl(clipLimit, tileGridSize.width, tileGridSize.height);
1501         }
1502
1503         //////////////////////////////////bilateralFilter////////////////////////////////////////////////////
1504
1505         static void oclbilateralFilter_8u( const oclMat &src, oclMat &dst, int d,
1506                                double sigma_color, double sigma_space,
1507                                int borderType )
1508         {
1509             int cn = src.channels();
1510             int i, j, maxk, radius;
1511
1512             CV_Assert( (src.channels() == 1 || src.channels() == 3) &&
1513                        src.type() == dst.type() && src.size() == dst.size() &&
1514                        src.data != dst.data );
1515
1516             if ( sigma_color <= 0 )
1517                 sigma_color = 1;
1518             if ( sigma_space <= 0 )
1519                 sigma_space = 1;
1520
1521             double gauss_color_coeff = -0.5 / (sigma_color * sigma_color);
1522             double gauss_space_coeff = -0.5 / (sigma_space * sigma_space);
1523
1524             if ( d <= 0 )
1525                 radius = cvRound(sigma_space * 1.5);
1526             else
1527                 radius = d / 2;
1528             radius = MAX(radius, 1);
1529             d = radius * 2 + 1;
1530
1531             oclMat temp;
1532             copyMakeBorder( src, temp, radius, radius, radius, radius, borderType );
1533
1534             vector<float> _color_weight(cn * 256);
1535             vector<float> _space_weight(d * d);
1536             vector<int> _space_ofs(d * d);
1537             float *color_weight = &_color_weight[0];
1538             float *space_weight = &_space_weight[0];
1539             int *space_ofs = &_space_ofs[0];
1540
1541             int dst_step_in_pixel = dst.step / dst.elemSize();
1542             int dst_offset_in_pixel = dst.offset / dst.elemSize();
1543             int temp_step_in_pixel = temp.step / temp.elemSize();
1544
1545             // initialize color-related bilateral filter coefficients
1546             for( i = 0; i < 256 * cn; i++ )
1547                 color_weight[i] = (float)std::exp(i * i * gauss_color_coeff);
1548
1549             // initialize space-related bilateral filter coefficients
1550             for( i = -radius, maxk = 0; i <= radius; i++ )
1551                 for( j = -radius; j <= radius; j++ )
1552                 {
1553                     double r = std::sqrt((double)i * i + (double)j * j);
1554                     if ( r > radius )
1555                         continue;
1556                     space_weight[maxk] = (float)std::exp(r * r * gauss_space_coeff);
1557                     space_ofs[maxk++] = (int)(i * temp_step_in_pixel + j);
1558                 }
1559
1560             oclMat oclcolor_weight(1, cn * 256, CV_32FC1, color_weight);
1561             oclMat oclspace_weight(1, d * d, CV_32FC1, space_weight);
1562             oclMat oclspace_ofs(1, d * d, CV_32SC1, space_ofs);
1563
1564             string kernelName = "bilateral";
1565             size_t localThreads[3]  = { 16, 16, 1 };
1566             size_t globalThreads[3] = { dst.cols, dst.rows, 1 };
1567
1568             if ((dst.type() == CV_8UC1) && ((dst.offset & 3) == 0) && ((dst.cols & 3) == 0))
1569             {
1570                 kernelName = "bilateral2";
1571                 globalThreads[0] = dst.cols >> 2;
1572             }
1573
1574             vector<pair<size_t , const void *> > args;
1575             args.push_back( make_pair( sizeof(cl_mem), (void *)&dst.data ));
1576             args.push_back( make_pair( sizeof(cl_mem), (void *)&temp.data ));
1577             args.push_back( make_pair( sizeof(cl_int), (void *)&dst.rows ));
1578             args.push_back( make_pair( sizeof(cl_int), (void *)&dst.cols ));
1579             args.push_back( make_pair( sizeof(cl_int), (void *)&maxk ));
1580             args.push_back( make_pair( sizeof(cl_int), (void *)&radius ));
1581             args.push_back( make_pair( sizeof(cl_int), (void *)&dst_step_in_pixel ));
1582             args.push_back( make_pair( sizeof(cl_int), (void *)&dst_offset_in_pixel ));
1583             args.push_back( make_pair( sizeof(cl_int), (void *)&temp_step_in_pixel ));
1584             args.push_back( make_pair( sizeof(cl_int), (void *)&temp.rows ));
1585             args.push_back( make_pair( sizeof(cl_int), (void *)&temp.cols ));
1586             args.push_back( make_pair( sizeof(cl_mem), (void *)&oclcolor_weight.data ));
1587             args.push_back( make_pair( sizeof(cl_mem), (void *)&oclspace_weight.data ));
1588             args.push_back( make_pair( sizeof(cl_mem), (void *)&oclspace_ofs.data ));
1589
1590             openCLExecuteKernel(src.clCxt, &imgproc_bilateral, kernelName, globalThreads, localThreads, args, dst.oclchannels(), dst.depth());
1591         }
1592
1593         void bilateralFilter(const oclMat &src, oclMat &dst, int radius, double sigmaclr, double sigmaspc, int borderType)
1594         {
1595             dst.create( src.size(), src.type() );
1596             if ( src.depth() == CV_8U )
1597                 oclbilateralFilter_8u( src, dst, radius, sigmaclr, sigmaspc, borderType );
1598             else
1599                 CV_Error( CV_StsUnsupportedFormat, "Bilateral filtering is only implemented for CV_8U images" );
1600         }
1601
1602     }
1603 }
1604 //////////////////////////////////convolve////////////////////////////////////////////////////
1605
1606 static void convolve_run(const oclMat &src, const oclMat &temp1, oclMat &dst, string kernelName, const cv::ocl::ProgramEntry* source)
1607 {
1608     dst.create(src.size(), src.type());
1609
1610     size_t localThreads[3]  = { 16, 16, 1 };
1611     size_t globalThreads[3] = { dst.cols, dst.rows, 1 };
1612
1613     int src_step = src.step / src.elemSize(), src_offset = src.offset / src.elemSize();
1614     int dst_step = dst.step / dst.elemSize(), dst_offset = dst.offset / dst.elemSize();
1615     int temp1_step = temp1.step / temp1.elemSize(), temp1_offset = temp1.offset / temp1.elemSize();
1616
1617     vector<pair<size_t , const void *> > args;
1618     args.push_back( make_pair( sizeof(cl_mem), (void *)&src.data ));
1619     args.push_back( make_pair( sizeof(cl_mem), (void *)&temp1.data ));
1620     args.push_back( make_pair( sizeof(cl_mem), (void *)&dst.data ));
1621     args.push_back( make_pair( sizeof(cl_int), (void *)&src.rows ));
1622     args.push_back( make_pair( sizeof(cl_int), (void *)&src.cols ));
1623     args.push_back( make_pair( sizeof(cl_int), (void *)&src_step ));
1624     args.push_back( make_pair( sizeof(cl_int), (void *)&dst_step ));
1625     args.push_back( make_pair( sizeof(cl_int), (void *)&temp1_step ));
1626     args.push_back( make_pair( sizeof(cl_int), (void *)&temp1.rows ));
1627     args.push_back( make_pair( sizeof(cl_int), (void *)&temp1.cols ));
1628     args.push_back( make_pair( sizeof(cl_int), (void *)&src_offset ));
1629     args.push_back( make_pair( sizeof(cl_int), (void *)&dst_offset ));
1630     args.push_back( make_pair( sizeof(cl_int), (void *)&temp1_offset ));
1631
1632     openCLExecuteKernel(src.clCxt, source, kernelName, globalThreads, localThreads, args, -1, dst.depth());
1633 }
1634
1635 void cv::ocl::convolve(const oclMat &x, const oclMat &t, oclMat &y)
1636 {
1637     CV_Assert(x.depth() == CV_32F && t.depth() == CV_32F);
1638     CV_Assert(t.cols <= 17 && t.rows <= 17);
1639
1640     y.create(x.size(), x.type());
1641
1642     convolve_run(x, t, y, "convolve", &imgproc_convolve);
1643 }