fixed extrapolation for ocl::cornerMinEigenVal and ocl::cornerHarris; enabled CV_32FC...
[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                 Sobel(src, Dx, CV_32F, 1, 0, ksize, scale, 0, borderType);
880                 Sobel(src, Dy, CV_32F, 0, 1, ksize, scale, 0, borderType);
881             }
882             else
883             {
884                 Scharr(src, Dx, CV_32F, 1, 0, scale, 0, borderType);
885                 Scharr(src, Dy, CV_32F, 0, 1, scale, 0, borderType);
886             }
887             CV_Assert(Dx.offset == 0 && Dy.offset == 0);
888         }
889
890         static void corner_ocl(const cv::ocl::ProgramEntry* source, string kernelName, int block_size, float k, oclMat &Dx, oclMat &Dy,
891                         oclMat &dst, int border_type)
892         {
893             char borderType[30];
894             switch (border_type)
895             {
896             case cv::BORDER_CONSTANT:
897                 sprintf(borderType, "BORDER_CONSTANT");
898                 break;
899             case cv::BORDER_REFLECT101:
900                 sprintf(borderType, "BORDER_REFLECT101");
901                 break;
902             case cv::BORDER_REFLECT:
903                 sprintf(borderType, "BORDER_REFLECT");
904                 break;
905             case cv::BORDER_REPLICATE:
906                 sprintf(borderType, "BORDER_REPLICATE");
907                 break;
908             default:
909                 CV_Error(CV_StsBadFlag, "BORDER type is not supported!");
910             }
911
912             std::string buildOptions = format("-D anX=%d -D anY=%d -D ksX=%d -D ksY=%d -D %s",
913                     block_size / 2, block_size / 2, block_size, block_size, borderType);
914
915             size_t blockSizeX = 256, blockSizeY = 1;
916             size_t gSize = blockSizeX - block_size / 2 * 2;
917             size_t globalSizeX = (Dx.cols) % gSize == 0 ? Dx.cols / gSize * blockSizeX : (Dx.cols / gSize + 1) * blockSizeX;
918             size_t rows_per_thread = 2;
919             size_t globalSizeY = ((Dx.rows + rows_per_thread - 1) / rows_per_thread) % blockSizeY == 0 ?
920                                  ((Dx.rows + rows_per_thread - 1) / rows_per_thread) :
921                                  (((Dx.rows + rows_per_thread - 1) / rows_per_thread) / blockSizeY + 1) * blockSizeY;
922
923             size_t gt[3] = { globalSizeX, globalSizeY, 1 };
924             size_t lt[3]  = { blockSizeX, blockSizeY, 1 };
925             vector<pair<size_t , const void *> > args;
926             args.push_back( make_pair( sizeof(cl_mem) , (void *)&Dx.data ));
927             args.push_back( make_pair( sizeof(cl_mem) , (void *)&Dy.data));
928             args.push_back( make_pair( sizeof(cl_mem) , (void *)&dst.data));
929             args.push_back( make_pair( sizeof(cl_int) , (void *)&Dx.offset ));
930             args.push_back( make_pair( sizeof(cl_int) , (void *)&Dx.wholerows ));
931             args.push_back( make_pair( sizeof(cl_int) , (void *)&Dx.wholecols ));
932             args.push_back( make_pair(sizeof(cl_int), (void *)&Dx.step));
933             args.push_back( make_pair( sizeof(cl_int) , (void *)&Dy.offset ));
934             args.push_back( make_pair( sizeof(cl_int) , (void *)&Dy.wholerows ));
935             args.push_back( make_pair( sizeof(cl_int) , (void *)&Dy.wholecols ));
936             args.push_back( make_pair(sizeof(cl_int), (void *)&Dy.step));
937             args.push_back( make_pair(sizeof(cl_int), (void *)&dst.offset));
938             args.push_back( make_pair(sizeof(cl_int), (void *)&dst.rows));
939             args.push_back( make_pair(sizeof(cl_int), (void *)&dst.cols));
940             args.push_back( make_pair(sizeof(cl_int), (void *)&dst.step));
941             args.push_back( make_pair( sizeof(cl_float) , (void *)&k));
942
943             openCLExecuteKernel(dst.clCxt, source, kernelName, gt, lt, args, -1, -1, buildOptions.c_str());
944         }
945
946         void cornerHarris(const oclMat &src, oclMat &dst, int blockSize, int ksize,
947                           double k, int borderType)
948         {
949             oclMat dx, dy;
950             cornerHarris_dxdy(src, dst, dx, dy, blockSize, ksize, k, borderType);
951         }
952
953         void cornerHarris_dxdy(const oclMat &src, oclMat &dst, oclMat &dx, oclMat &dy, int blockSize, int ksize,
954                           double k, int borderType)
955         {
956             if (!src.clCxt->supportsFeature(FEATURE_CL_DOUBLE) && src.depth() == CV_64F)
957             {
958                 CV_Error(CV_OpenCLDoubleNotSupported, "Selected device doesn't support double");
959                 return;
960             }
961
962             CV_Assert(borderType == cv::BORDER_CONSTANT || borderType == cv::BORDER_REFLECT101 || borderType == cv::BORDER_REPLICATE
963                       || borderType == cv::BORDER_REFLECT);
964
965             extractCovData(src, dx, dy, blockSize, ksize, borderType);
966             dst.create(src.size(), CV_32FC1);
967             corner_ocl(&imgproc_calcHarris, "calcHarris", blockSize, static_cast<float>(k), dx, dy, dst, borderType);
968         }
969
970         void cornerMinEigenVal(const oclMat &src, oclMat &dst, int blockSize, int ksize, int borderType)
971         {
972             oclMat dx, dy;
973             cornerMinEigenVal_dxdy(src, dst, dx, dy, blockSize, ksize, borderType);
974         }
975
976         void cornerMinEigenVal_dxdy(const oclMat &src, oclMat &dst, oclMat &dx, oclMat &dy, int blockSize, int ksize, int borderType)
977         {
978             if (!src.clCxt->supportsFeature(FEATURE_CL_DOUBLE) && src.depth() == CV_64F)
979             {
980                 CV_Error(CV_OpenCLDoubleNotSupported, "Selected device doesn't support double");
981                 return;
982             }
983
984             CV_Assert(borderType == cv::BORDER_CONSTANT || borderType == cv::BORDER_REFLECT101 ||
985                       borderType == cv::BORDER_REPLICATE || borderType == cv::BORDER_REFLECT);
986
987             extractCovData(src, dx, dy, blockSize, ksize, borderType);
988             dst.create(src.size(), CV_32F);
989
990             corner_ocl(&imgproc_calcMinEigenVal, "calcMinEigenVal", blockSize, 0, dx, dy, dst, borderType);
991         }
992
993         /////////////////////////////////// MeanShiftfiltering ///////////////////////////////////////////////
994
995         static void meanShiftFiltering_gpu(const oclMat &src, oclMat dst, int sp, int sr, int maxIter, float eps)
996         {
997             CV_Assert( (src.cols == dst.cols) && (src.rows == dst.rows) );
998             CV_Assert( !(dst.step & 0x3) );
999
1000             //Arrange the NDRange
1001             int col = src.cols, row = src.rows;
1002             int ltx = 16, lty = 8;
1003             if (src.cols % ltx != 0)
1004                 col = (col / ltx + 1) * ltx;
1005             if (src.rows % lty != 0)
1006                 row = (row / lty + 1) * lty;
1007
1008             size_t globalThreads[3] = {col, row, 1};
1009             size_t localThreads[3]  = {ltx, lty, 1};
1010
1011             //set args
1012             vector<pair<size_t , const void *> > args;
1013             args.push_back( make_pair( sizeof(cl_mem) , (void *)&dst.data ));
1014             args.push_back( make_pair( sizeof(cl_int) , (void *)&dst.step ));
1015             args.push_back( make_pair( sizeof(cl_mem) , (void *)&src.data ));
1016             args.push_back( make_pair( sizeof(cl_int) , (void *)&src.step ));
1017             args.push_back( make_pair( sizeof(cl_int) , (void *)&dst.offset ));
1018             args.push_back( make_pair( sizeof(cl_int) , (void *)&src.offset ));
1019             args.push_back( make_pair( sizeof(cl_int) , (void *)&dst.cols ));
1020             args.push_back( make_pair( sizeof(cl_int) , (void *)&dst.rows ));
1021             args.push_back( make_pair( sizeof(cl_int) , (void *)&sp ));
1022             args.push_back( make_pair( sizeof(cl_int) , (void *)&sr ));
1023             args.push_back( make_pair( sizeof(cl_int) , (void *)&maxIter ));
1024             args.push_back( make_pair( sizeof(cl_float) , (void *)&eps ));
1025
1026             openCLExecuteKernel(src.clCxt, &meanShift, "meanshift_kernel", globalThreads, localThreads, args, -1, -1);
1027         }
1028
1029         void meanShiftFiltering(const oclMat &src, oclMat &dst, int sp, int sr, TermCriteria criteria)
1030         {
1031             if ( src.empty() )
1032                 CV_Error( CV_StsBadArg, "The input image is empty" );
1033
1034             if ( src.depth() != CV_8U || src.oclchannels() != 4 )
1035                 CV_Error( CV_StsUnsupportedFormat, "Only 8-bit, 4-channel images are supported" );
1036
1037             dst.create( src.size(), CV_8UC4 );
1038
1039             if ( !(criteria.type & TermCriteria::MAX_ITER) )
1040                 criteria.maxCount = 5;
1041
1042             int maxIter = std::min(std::max(criteria.maxCount, 1), 100);
1043
1044             float eps;
1045             if ( !(criteria.type & TermCriteria::EPS) )
1046                 eps = 1.f;
1047             eps = (float)std::max(criteria.epsilon, 0.0);
1048
1049             meanShiftFiltering_gpu(src, dst, sp, sr, maxIter, eps);
1050         }
1051
1052         static void meanShiftProc_gpu(const oclMat &src, oclMat dstr, oclMat dstsp, int sp, int sr, int maxIter, float eps)
1053         {
1054             //sanity checks
1055             CV_Assert( (src.cols == dstr.cols) && (src.rows == dstr.rows) &&
1056                        (src.rows == dstsp.rows) && (src.cols == dstsp.cols));
1057             CV_Assert( !(dstsp.step & 0x3) );
1058
1059             //Arrange the NDRange
1060             int col = src.cols, row = src.rows;
1061             int ltx = 16, lty = 8;
1062             if (src.cols % ltx != 0)
1063                 col = (col / ltx + 1) * ltx;
1064             if (src.rows % lty != 0)
1065                 row = (row / lty + 1) * lty;
1066
1067             size_t globalThreads[3] = {col, row, 1};
1068             size_t localThreads[3]  = {ltx, lty, 1};
1069
1070             //set args
1071             vector<pair<size_t , const void *> > args;
1072             args.push_back( make_pair( sizeof(cl_mem) , (void *)&src.data ));
1073             args.push_back( make_pair( sizeof(cl_mem) , (void *)&dstr.data ));
1074             args.push_back( make_pair( sizeof(cl_mem) , (void *)&dstsp.data ));
1075             args.push_back( make_pair( sizeof(cl_int) , (void *)&src.step ));
1076             args.push_back( make_pair( sizeof(cl_int) , (void *)&dstr.step ));
1077             args.push_back( make_pair( sizeof(cl_int) , (void *)&dstsp.step ));
1078             args.push_back( make_pair( sizeof(cl_int) , (void *)&src.offset ));
1079             args.push_back( make_pair( sizeof(cl_int) , (void *)&dstr.offset ));
1080             args.push_back( make_pair( sizeof(cl_int) , (void *)&dstsp.offset ));
1081             args.push_back( make_pair( sizeof(cl_int) , (void *)&dstr.cols ));
1082             args.push_back( make_pair( sizeof(cl_int) , (void *)&dstr.rows ));
1083             args.push_back( make_pair( sizeof(cl_int) , (void *)&sp ));
1084             args.push_back( make_pair( sizeof(cl_int) , (void *)&sr ));
1085             args.push_back( make_pair( sizeof(cl_int) , (void *)&maxIter ));
1086             args.push_back( make_pair( sizeof(cl_float) , (void *)&eps ));
1087
1088             openCLExecuteKernel(src.clCxt, &meanShift, "meanshiftproc_kernel", globalThreads, localThreads, args, -1, -1);
1089         }
1090
1091         void meanShiftProc(const oclMat &src, oclMat &dstr, oclMat &dstsp, int sp, int sr, TermCriteria criteria)
1092         {
1093             if ( src.empty() )
1094                 CV_Error( CV_StsBadArg, "The input image is empty" );
1095
1096             if ( src.depth() != CV_8U || src.oclchannels() != 4 )
1097                 CV_Error( CV_StsUnsupportedFormat, "Only 8-bit, 4-channel images are supported" );
1098
1099 //            if (!src.clCxt->supportsFeature(FEATURE_CL_DOUBLE))
1100 //            {
1101 //                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");
1102 //                return;
1103 //            }
1104
1105             dstr.create( src.size(), CV_8UC4 );
1106             dstsp.create( src.size(), CV_16SC2 );
1107
1108             if ( !(criteria.type & TermCriteria::MAX_ITER) )
1109                 criteria.maxCount = 5;
1110
1111             int maxIter = std::min(std::max(criteria.maxCount, 1), 100);
1112
1113             float eps;
1114             if ( !(criteria.type & TermCriteria::EPS) )
1115                 eps = 1.f;
1116             eps = (float)std::max(criteria.epsilon, 0.0);
1117
1118             meanShiftProc_gpu(src, dstr, dstsp, sp, sr, maxIter, eps);
1119         }
1120
1121         ///////////////////////////////////////////////////////////////////////////////////////////////////
1122         ////////////////////////////////////////////////////hist///////////////////////////////////////////////
1123         /////////////////////////////////////////////////////////////////////////////////////////////////////
1124
1125         namespace histograms
1126         {
1127             const int PARTIAL_HISTOGRAM256_COUNT = 256;
1128             const int HISTOGRAM256_BIN_COUNT = 256;
1129         }
1130         ///////////////////////////////calcHist/////////////////////////////////////////////////////////////////
1131         static void calc_sub_hist(const oclMat &mat_src, const oclMat &mat_sub_hist)
1132         {
1133             using namespace histograms;
1134
1135             int depth = mat_src.depth();
1136
1137             size_t localThreads[3]  = { HISTOGRAM256_BIN_COUNT, 1, 1 };
1138             size_t globalThreads[3] = { PARTIAL_HISTOGRAM256_COUNT *localThreads[0], 1, 1};
1139
1140             int dataWidth = 16;
1141             int dataWidth_bits = 4;
1142             int mask = dataWidth - 1;
1143
1144             int cols = mat_src.cols * mat_src.oclchannels();
1145             int src_offset = mat_src.offset;
1146             int hist_step = mat_sub_hist.step >> 2;
1147             int left_col = 0, right_col = 0;
1148
1149             if (cols >= dataWidth * 2 - 1)
1150             {
1151                 left_col = dataWidth - (src_offset & mask);
1152                 left_col &= mask;
1153                 src_offset += left_col;
1154                 cols -= left_col;
1155                 right_col = cols & mask;
1156                 cols -= right_col;
1157             }
1158             else
1159             {
1160                 left_col = cols;
1161                 right_col = 0;
1162                 cols = 0;
1163                 globalThreads[0] = 0;
1164             }
1165
1166             vector<pair<size_t , const void *> > args;
1167             if (globalThreads[0] != 0)
1168             {
1169                 int tempcols = cols >> dataWidth_bits;
1170                 int inc_x = globalThreads[0] % tempcols;
1171                 int inc_y = globalThreads[0] / tempcols;
1172                 src_offset >>= dataWidth_bits;
1173                 int src_step = mat_src.step >> dataWidth_bits;
1174                 int datacount = tempcols * mat_src.rows;
1175
1176                 args.push_back( make_pair( sizeof(cl_mem), (void *)&mat_src.data));
1177                 args.push_back( make_pair( sizeof(cl_int), (void *)&src_step));
1178                 args.push_back( make_pair( sizeof(cl_int), (void *)&src_offset));
1179                 args.push_back( make_pair( sizeof(cl_mem), (void *)&mat_sub_hist.data));
1180                 args.push_back( make_pair( sizeof(cl_int), (void *)&datacount));
1181                 args.push_back( make_pair( sizeof(cl_int), (void *)&tempcols));
1182                 args.push_back( make_pair( sizeof(cl_int), (void *)&inc_x));
1183                 args.push_back( make_pair( sizeof(cl_int), (void *)&inc_y));
1184                 args.push_back( make_pair( sizeof(cl_int), (void *)&hist_step));
1185
1186                 openCLExecuteKernel(mat_src.clCxt, &imgproc_histogram, "calc_sub_hist", globalThreads, localThreads, args, -1, depth);
1187             }
1188
1189             if (left_col != 0 || right_col != 0)
1190             {
1191                 src_offset = mat_src.offset;
1192                 localThreads[0] = 1;
1193                 localThreads[1] = 256;
1194                 globalThreads[0] = left_col + right_col;
1195                 globalThreads[1] = mat_src.rows;
1196
1197                 args.clear();
1198                 args.push_back( make_pair( sizeof(cl_mem), (void *)&mat_src.data));
1199                 args.push_back( make_pair( sizeof(cl_int), (void *)&mat_src.step));
1200                 args.push_back( make_pair( sizeof(cl_int), (void *)&src_offset));
1201                 args.push_back( make_pair( sizeof(cl_mem), (void *)&mat_sub_hist.data));
1202                 args.push_back( make_pair( sizeof(cl_int), (void *)&left_col));
1203                 args.push_back( make_pair( sizeof(cl_int), (void *)&cols));
1204                 args.push_back( make_pair( sizeof(cl_int), (void *)&mat_src.rows));
1205                 args.push_back( make_pair( sizeof(cl_int), (void *)&hist_step));
1206
1207                 openCLExecuteKernel(mat_src.clCxt, &imgproc_histogram, "calc_sub_hist_border", globalThreads, localThreads, args, -1, depth);
1208             }
1209         }
1210
1211         static void merge_sub_hist(const oclMat &sub_hist, oclMat &mat_hist)
1212         {
1213             using namespace histograms;
1214
1215             size_t localThreads[3]  = { 256, 1, 1 };
1216             size_t globalThreads[3] = { HISTOGRAM256_BIN_COUNT *localThreads[0], 1, 1};
1217             int src_step = sub_hist.step >> 2;
1218
1219             vector<pair<size_t , const void *> > args;
1220             args.push_back( make_pair( sizeof(cl_mem), (void *)&sub_hist.data));
1221             args.push_back( make_pair( sizeof(cl_mem), (void *)&mat_hist.data));
1222             args.push_back( make_pair( sizeof(cl_int), (void *)&src_step));
1223
1224             openCLExecuteKernel(sub_hist.clCxt, &imgproc_histogram, "merge_hist", globalThreads, localThreads, args, -1, -1);
1225         }
1226
1227         void calcHist(const oclMat &mat_src, oclMat &mat_hist)
1228         {
1229             using namespace histograms;
1230             CV_Assert(mat_src.type() == CV_8UC1);
1231             mat_hist.create(1, 256, CV_32SC1);
1232
1233             oclMat buf(PARTIAL_HISTOGRAM256_COUNT, HISTOGRAM256_BIN_COUNT, CV_32SC1);
1234             buf.setTo(0);
1235
1236             calc_sub_hist(mat_src, buf);
1237             merge_sub_hist(buf, mat_hist);
1238         }
1239
1240         ///////////////////////////////////equalizeHist/////////////////////////////////////////////////////
1241         void equalizeHist(const oclMat &mat_src, oclMat &mat_dst)
1242         {
1243             mat_dst.create(mat_src.rows, mat_src.cols, CV_8UC1);
1244
1245             oclMat mat_hist(1, 256, CV_32SC1);
1246
1247             calcHist(mat_src, mat_hist);
1248
1249             size_t localThreads[3] = { 256, 1, 1};
1250             size_t globalThreads[3] = { 256, 1, 1};
1251             oclMat lut(1, 256, CV_8UC1);
1252             int total = mat_src.rows * mat_src.cols;
1253
1254             vector<pair<size_t , const void *> > args;
1255             args.push_back( make_pair( sizeof(cl_mem), (void *)&lut.data));
1256             args.push_back( make_pair( sizeof(cl_mem), (void *)&mat_hist.data));
1257             args.push_back( make_pair( sizeof(int), (void *)&total));
1258
1259             openCLExecuteKernel(mat_src.clCxt, &imgproc_histogram, "calLUT", globalThreads, localThreads, args, -1, -1);
1260             LUT(mat_src, lut, mat_dst);
1261         }
1262
1263         ////////////////////////////////////////////////////////////////////////
1264         // CLAHE
1265         namespace clahe
1266         {
1267             static void calcLut(const oclMat &src, oclMat &dst,
1268                 const int tilesX, const int tilesY, const cv::Size tileSize,
1269                 const int clipLimit, const float lutScale)
1270             {
1271                 cl_int2 tile_size;
1272                 tile_size.s[0] = tileSize.width;
1273                 tile_size.s[1] = tileSize.height;
1274
1275                 std::vector<pair<size_t , const void *> > args;
1276                 args.push_back( std::make_pair( sizeof(cl_mem), (void *)&src.data ));
1277                 args.push_back( std::make_pair( sizeof(cl_mem), (void *)&dst.data ));
1278                 args.push_back( std::make_pair( sizeof(cl_int), (void *)&src.step ));
1279                 args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst.step ));
1280                 args.push_back( std::make_pair( sizeof(cl_int2), (void *)&tile_size ));
1281                 args.push_back( std::make_pair( sizeof(cl_int), (void *)&tilesX ));
1282                 args.push_back( std::make_pair( sizeof(cl_int), (void *)&clipLimit ));
1283                 args.push_back( std::make_pair( sizeof(cl_float), (void *)&lutScale ));
1284                 args.push_back( std::make_pair( sizeof(cl_int), (void *)&src.offset ));
1285                 args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst.offset ));
1286
1287                 String kernelName = "calcLut";
1288                 size_t localThreads[3]  = { 32, 8, 1 };
1289                 size_t globalThreads[3] = { tilesX * localThreads[0], tilesY * localThreads[1], 1 };
1290                 bool is_cpu = isCpuDevice();
1291                 if (is_cpu)
1292                     openCLExecuteKernel(Context::getContext(), &imgproc_clahe, kernelName, globalThreads, localThreads, args, -1, -1, (char*)"-D CPU");
1293                 else
1294                 {
1295                     cl_kernel kernel = openCLGetKernelFromSource(Context::getContext(), &imgproc_clahe, kernelName);
1296                     int wave_size = (int)queryWaveFrontSize(kernel);
1297                     openCLSafeCall(clReleaseKernel(kernel));
1298
1299                     std::string opt = format("-D WAVE_SIZE=%d", wave_size);
1300                     openCLExecuteKernel(Context::getContext(), &imgproc_clahe, kernelName, globalThreads, localThreads, args, -1, -1, opt.c_str());
1301                 }
1302             }
1303
1304             static void transform(const oclMat &src, oclMat &dst, const oclMat &lut,
1305                 const int tilesX, const int tilesY, const Size & tileSize)
1306             {
1307                 cl_int2 tile_size;
1308                 tile_size.s[0] = tileSize.width;
1309                 tile_size.s[1] = tileSize.height;
1310
1311                 std::vector<pair<size_t , const void *> > args;
1312                 args.push_back( std::make_pair( sizeof(cl_mem), (void *)&src.data ));
1313                 args.push_back( std::make_pair( sizeof(cl_mem), (void *)&dst.data ));
1314                 args.push_back( std::make_pair( sizeof(cl_mem), (void *)&lut.data ));
1315                 args.push_back( std::make_pair( sizeof(cl_int), (void *)&src.step ));
1316                 args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst.step ));
1317                 args.push_back( std::make_pair( sizeof(cl_int), (void *)&lut.step ));
1318                 args.push_back( std::make_pair( sizeof(cl_int), (void *)&src.cols ));
1319                 args.push_back( std::make_pair( sizeof(cl_int), (void *)&src.rows ));
1320                 args.push_back( std::make_pair( sizeof(cl_int2), (void *)&tile_size ));
1321                 args.push_back( std::make_pair( sizeof(cl_int), (void *)&tilesX ));
1322                 args.push_back( std::make_pair( sizeof(cl_int), (void *)&tilesY ));
1323                 args.push_back( std::make_pair( sizeof(cl_int), (void *)&src.offset ));
1324                 args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst.offset ));
1325                 args.push_back( std::make_pair( sizeof(cl_int), (void *)&lut.offset ));
1326
1327                 size_t localThreads[3]  = { 32, 8, 1 };
1328                 size_t globalThreads[3] = { src.cols, src.rows, 1 };
1329
1330                 openCLExecuteKernel(Context::getContext(), &imgproc_clahe, "transform", globalThreads, localThreads, args, -1, -1);
1331             }
1332         }
1333
1334         namespace
1335         {
1336             class CLAHE_Impl : public cv::CLAHE
1337             {
1338             public:
1339                 CLAHE_Impl(double clipLimit = 40.0, int tilesX = 8, int tilesY = 8);
1340
1341                 cv::AlgorithmInfo* info() const;
1342
1343                 void apply(cv::InputArray src, cv::OutputArray dst);
1344
1345                 void setClipLimit(double clipLimit);
1346                 double getClipLimit() const;
1347
1348                 void setTilesGridSize(cv::Size tileGridSize);
1349                 cv::Size getTilesGridSize() const;
1350
1351                 void collectGarbage();
1352
1353             private:
1354                 double clipLimit_;
1355                 int tilesX_;
1356                 int tilesY_;
1357
1358                 oclMat srcExt_;
1359                 oclMat lut_;
1360             };
1361
1362             CLAHE_Impl::CLAHE_Impl(double clipLimit, int tilesX, int tilesY) :
1363                 clipLimit_(clipLimit), tilesX_(tilesX), tilesY_(tilesY)
1364             {
1365             }
1366
1367             CV_INIT_ALGORITHM(CLAHE_Impl, "CLAHE_OCL",
1368                 obj.info()->addParam(obj, "clipLimit", obj.clipLimit_);
1369                 obj.info()->addParam(obj, "tilesX", obj.tilesX_);
1370                 obj.info()->addParam(obj, "tilesY", obj.tilesY_))
1371
1372             void CLAHE_Impl::apply(cv::InputArray src_raw, cv::OutputArray dst_raw)
1373             {
1374                 oclMat& src = getOclMatRef(src_raw);
1375                 oclMat& dst = getOclMatRef(dst_raw);
1376                 CV_Assert( src.type() == CV_8UC1 );
1377
1378                 dst.create( src.size(), src.type() );
1379
1380                 const int histSize = 256;
1381
1382                 ensureSizeIsEnough(tilesX_ * tilesY_, histSize, CV_8UC1, lut_);
1383
1384                 cv::Size tileSize;
1385                 oclMat srcForLut;
1386
1387                 if (src.cols % tilesX_ == 0 && src.rows % tilesY_ == 0)
1388                 {
1389                     tileSize = cv::Size(src.cols / tilesX_, src.rows / tilesY_);
1390                     srcForLut = src;
1391                 }
1392                 else
1393                 {
1394                     ocl::copyMakeBorder(src, srcExt_, 0, tilesY_ - (src.rows % tilesY_), 0,
1395                                             tilesX_ - (src.cols % tilesX_), BORDER_REFLECT_101, Scalar::all(0));
1396
1397                     tileSize = Size(srcExt_.cols / tilesX_, srcExt_.rows / tilesY_);
1398                     srcForLut = srcExt_;
1399                 }
1400
1401                 const int tileSizeTotal = tileSize.area();
1402                 const float lutScale = static_cast<float>(histSize - 1) / tileSizeTotal;
1403
1404                 int clipLimit = 0;
1405                 if (clipLimit_ > 0.0)
1406                 {
1407                     clipLimit = static_cast<int>(clipLimit_ * tileSizeTotal / histSize);
1408                     clipLimit = std::max(clipLimit, 1);
1409                 }
1410
1411                 clahe::calcLut(srcForLut, lut_, tilesX_, tilesY_, tileSize, clipLimit, lutScale);
1412                 clahe::transform(src, dst, lut_, tilesX_, tilesY_, tileSize);
1413             }
1414
1415             void CLAHE_Impl::setClipLimit(double clipLimit)
1416             {
1417                 clipLimit_ = clipLimit;
1418             }
1419
1420             double CLAHE_Impl::getClipLimit() const
1421             {
1422                 return clipLimit_;
1423             }
1424
1425             void CLAHE_Impl::setTilesGridSize(cv::Size tileGridSize)
1426             {
1427                 tilesX_ = tileGridSize.width;
1428                 tilesY_ = tileGridSize.height;
1429             }
1430
1431             cv::Size CLAHE_Impl::getTilesGridSize() const
1432             {
1433                 return cv::Size(tilesX_, tilesY_);
1434             }
1435
1436             void CLAHE_Impl::collectGarbage()
1437             {
1438                 srcExt_.release();
1439                 lut_.release();
1440             }
1441         }
1442
1443         cv::Ptr<cv::CLAHE> createCLAHE(double clipLimit, cv::Size tileGridSize)
1444         {
1445             return new CLAHE_Impl(clipLimit, tileGridSize.width, tileGridSize.height);
1446         }
1447
1448         //////////////////////////////////bilateralFilter////////////////////////////////////////////////////
1449
1450         static void oclbilateralFilter_8u( const oclMat &src, oclMat &dst, int d,
1451                                double sigma_color, double sigma_space,
1452                                int borderType )
1453         {
1454             int cn = src.channels();
1455             int i, j, maxk, radius;
1456
1457             CV_Assert( (src.channels() == 1 || src.channels() == 3) &&
1458                        src.type() == dst.type() && src.size() == dst.size() &&
1459                        src.data != dst.data );
1460
1461             if ( sigma_color <= 0 )
1462                 sigma_color = 1;
1463             if ( sigma_space <= 0 )
1464                 sigma_space = 1;
1465
1466             double gauss_color_coeff = -0.5 / (sigma_color * sigma_color);
1467             double gauss_space_coeff = -0.5 / (sigma_space * sigma_space);
1468
1469             if ( d <= 0 )
1470                 radius = cvRound(sigma_space * 1.5);
1471             else
1472                 radius = d / 2;
1473             radius = MAX(radius, 1);
1474             d = radius * 2 + 1;
1475
1476             oclMat temp;
1477             copyMakeBorder( src, temp, radius, radius, radius, radius, borderType );
1478
1479             vector<float> _color_weight(cn * 256);
1480             vector<float> _space_weight(d * d);
1481             vector<int> _space_ofs(d * d);
1482             float *color_weight = &_color_weight[0];
1483             float *space_weight = &_space_weight[0];
1484             int *space_ofs = &_space_ofs[0];
1485
1486             int dst_step_in_pixel = dst.step / dst.elemSize();
1487             int dst_offset_in_pixel = dst.offset / dst.elemSize();
1488             int temp_step_in_pixel = temp.step / temp.elemSize();
1489
1490             // initialize color-related bilateral filter coefficients
1491             for( i = 0; i < 256 * cn; i++ )
1492                 color_weight[i] = (float)std::exp(i * i * gauss_color_coeff);
1493
1494             // initialize space-related bilateral filter coefficients
1495             for( i = -radius, maxk = 0; i <= radius; i++ )
1496                 for( j = -radius; j <= radius; j++ )
1497                 {
1498                     double r = std::sqrt((double)i * i + (double)j * j);
1499                     if ( r > radius )
1500                         continue;
1501                     space_weight[maxk] = (float)std::exp(r * r * gauss_space_coeff);
1502                     space_ofs[maxk++] = (int)(i * temp_step_in_pixel + j);
1503                 }
1504
1505             oclMat oclcolor_weight(1, cn * 256, CV_32FC1, color_weight);
1506             oclMat oclspace_weight(1, d * d, CV_32FC1, space_weight);
1507             oclMat oclspace_ofs(1, d * d, CV_32SC1, space_ofs);
1508
1509             string kernelName = "bilateral";
1510             size_t localThreads[3]  = { 16, 16, 1 };
1511             size_t globalThreads[3] = { dst.cols, dst.rows, 1 };
1512
1513             if ((dst.type() == CV_8UC1) && ((dst.offset & 3) == 0) && ((dst.cols & 3) == 0))
1514             {
1515                 kernelName = "bilateral2";
1516                 globalThreads[0] = dst.cols >> 2;
1517             }
1518
1519             vector<pair<size_t , const void *> > args;
1520             args.push_back( make_pair( sizeof(cl_mem), (void *)&dst.data ));
1521             args.push_back( make_pair( sizeof(cl_mem), (void *)&temp.data ));
1522             args.push_back( make_pair( sizeof(cl_int), (void *)&dst.rows ));
1523             args.push_back( make_pair( sizeof(cl_int), (void *)&dst.cols ));
1524             args.push_back( make_pair( sizeof(cl_int), (void *)&maxk ));
1525             args.push_back( make_pair( sizeof(cl_int), (void *)&radius ));
1526             args.push_back( make_pair( sizeof(cl_int), (void *)&dst_step_in_pixel ));
1527             args.push_back( make_pair( sizeof(cl_int), (void *)&dst_offset_in_pixel ));
1528             args.push_back( make_pair( sizeof(cl_int), (void *)&temp_step_in_pixel ));
1529             args.push_back( make_pair( sizeof(cl_int), (void *)&temp.rows ));
1530             args.push_back( make_pair( sizeof(cl_int), (void *)&temp.cols ));
1531             args.push_back( make_pair( sizeof(cl_mem), (void *)&oclcolor_weight.data ));
1532             args.push_back( make_pair( sizeof(cl_mem), (void *)&oclspace_weight.data ));
1533             args.push_back( make_pair( sizeof(cl_mem), (void *)&oclspace_ofs.data ));
1534
1535             openCLExecuteKernel(src.clCxt, &imgproc_bilateral, kernelName, globalThreads, localThreads, args, dst.oclchannels(), dst.depth());
1536         }
1537
1538         void bilateralFilter(const oclMat &src, oclMat &dst, int radius, double sigmaclr, double sigmaspc, int borderType)
1539         {
1540             dst.create( src.size(), src.type() );
1541             if ( src.depth() == CV_8U )
1542                 oclbilateralFilter_8u( src, dst, radius, sigmaclr, sigmaspc, borderType );
1543             else
1544                 CV_Error( CV_StsUnsupportedFormat, "Bilateral filtering is only implemented for CV_8U images" );
1545         }
1546
1547     }
1548 }
1549 //////////////////////////////////convolve////////////////////////////////////////////////////
1550
1551 static void convolve_run(const oclMat &src, const oclMat &temp1, oclMat &dst, string kernelName, const cv::ocl::ProgramEntry* source)
1552 {
1553     dst.create(src.size(), src.type());
1554
1555     size_t localThreads[3]  = { 16, 16, 1 };
1556     size_t globalThreads[3] = { dst.cols, dst.rows, 1 };
1557
1558     int src_step = src.step / src.elemSize(), src_offset = src.offset / src.elemSize();
1559     int dst_step = dst.step / dst.elemSize(), dst_offset = dst.offset / dst.elemSize();
1560     int temp1_step = temp1.step / temp1.elemSize(), temp1_offset = temp1.offset / temp1.elemSize();
1561
1562     vector<pair<size_t , const void *> > args;
1563     args.push_back( make_pair( sizeof(cl_mem), (void *)&src.data ));
1564     args.push_back( make_pair( sizeof(cl_mem), (void *)&temp1.data ));
1565     args.push_back( make_pair( sizeof(cl_mem), (void *)&dst.data ));
1566     args.push_back( make_pair( sizeof(cl_int), (void *)&src.rows ));
1567     args.push_back( make_pair( sizeof(cl_int), (void *)&src.cols ));
1568     args.push_back( make_pair( sizeof(cl_int), (void *)&src_step ));
1569     args.push_back( make_pair( sizeof(cl_int), (void *)&dst_step ));
1570     args.push_back( make_pair( sizeof(cl_int), (void *)&temp1_step ));
1571     args.push_back( make_pair( sizeof(cl_int), (void *)&temp1.rows ));
1572     args.push_back( make_pair( sizeof(cl_int), (void *)&temp1.cols ));
1573     args.push_back( make_pair( sizeof(cl_int), (void *)&src_offset ));
1574     args.push_back( make_pair( sizeof(cl_int), (void *)&dst_offset ));
1575     args.push_back( make_pair( sizeof(cl_int), (void *)&temp1_offset ));
1576
1577     openCLExecuteKernel(src.clCxt, source, kernelName, globalThreads, localThreads, args, -1, dst.depth());
1578 }
1579
1580 void cv::ocl::convolve(const oclMat &x, const oclMat &t, oclMat &y)
1581 {
1582     CV_Assert(x.depth() == CV_32F && t.depth() == CV_32F);
1583     CV_Assert(t.cols <= 17 && t.rows <= 17);
1584
1585     y.create(x.size(), x.type());
1586
1587     convolve_run(x, t, y, "convolve", &imgproc_convolve);
1588 }