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