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