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