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