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