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