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