Merge pull request #1521 from nailbiter:optimCG
[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 materials 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.wholecols != _src.cols || _src.wholerows != _src.rows) && (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             dst.create(_src.rows + top + bottom, _src.cols + left + right, _src.type());
458             int srcStep = _src.step / _src.elemSize(),  dstStep = dst.step / dst.elemSize();
459             int srcOffset = _src.offset / _src.elemSize(), dstOffset = dst.offset / dst.elemSize();
460             int depth = _src.depth(), ochannels = _src.oclchannels();
461
462             int __bordertype[] = { BORDER_CONSTANT, BORDER_REPLICATE, BORDER_REFLECT, BORDER_WRAP, BORDER_REFLECT_101 };
463             const char *borderstr[] = { "BORDER_CONSTANT", "BORDER_REPLICATE", "BORDER_REFLECT", "BORDER_WRAP", "BORDER_REFLECT_101" };
464
465             int bordertype_index = -1;
466             for (int i = 0, end = sizeof(__bordertype) / sizeof(int); i < end; i++)
467                 if (__bordertype[i] == bordertype)
468                 {
469                     bordertype_index = i;
470                     break;
471                 }
472             if (bordertype_index < 0)
473                 CV_Error(Error::StsBadArg, "Unsupported border type");
474
475             size_t localThreads[3] = { 16, 16, 1 };
476             size_t globalThreads[3] = { dst.cols, dst.rows, 1 };
477
478             std::vector< std::pair<size_t, const void *> > args;
479             args.push_back( std::make_pair( sizeof(cl_mem), (void *)&_src.data));
480             args.push_back( std::make_pair( sizeof(cl_mem), (void *)&dst.data));
481             args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst.cols));
482             args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst.rows));
483             args.push_back( std::make_pair( sizeof(cl_int), (void *)&_src.cols));
484             args.push_back( std::make_pair( sizeof(cl_int), (void *)&_src.rows));
485             args.push_back( std::make_pair( sizeof(cl_int), (void *)&srcStep));
486             args.push_back( std::make_pair( sizeof(cl_int), (void *)&srcOffset));
487             args.push_back( std::make_pair( sizeof(cl_int), (void *)&dstStep));
488             args.push_back( std::make_pair( sizeof(cl_int), (void *)&dstOffset));
489             args.push_back( std::make_pair( sizeof(cl_int), (void *)&top));
490             args.push_back( std::make_pair( sizeof(cl_int), (void *)&left));
491
492             const char * const typeMap[] = { "uchar", "char", "ushort", "short", "int", "float", "double" };
493             const char * const channelMap[] = { "", "", "2", "4", "4" };
494             std::string buildOptions = format("-D GENTYPE=%s%s -D %s",
495                                               typeMap[depth], channelMap[ochannels],
496                                               borderstr[bordertype_index]);
497
498             int cn = src.channels(), ocn = src.oclchannels();
499             int bufSize = src.elemSize1() * ocn;
500             AutoBuffer<uchar> _buf(bufSize);
501             uchar * buf = (uchar *)_buf;
502             scalarToRawData(scalar, buf, dst.type());
503             memset(buf + src.elemSize1() * cn, 0, (ocn - cn) * src.elemSize1());
504
505             args.push_back( std::make_pair( bufSize , (void *)buf ));
506
507             openCLExecuteKernel(src.clCxt, &imgproc_copymakeboder, "copymakeborder", globalThreads,
508                                 localThreads, args, -1, -1, buildOptions.c_str());
509         }
510
511         ////////////////////////////////////////////////////////////////////////
512         // warp
513
514         namespace
515         {
516 #define F double
517
518             void convert_coeffs(F *M)
519             {
520                 double D = M[0] * M[4] - M[1] * M[3];
521                 D = D != 0 ? 1. / D : 0;
522                 double A11 = M[4] * D, A22 = M[0] * D;
523                 M[0] = A11;
524                 M[1] *= -D;
525                 M[3] *= -D;
526                 M[4] = A22;
527                 double b1 = -M[0] * M[2] - M[1] * M[5];
528                 double b2 = -M[3] * M[2] - M[4] * M[5];
529                 M[2] = b1;
530                 M[5] = b2;
531             }
532
533             double invert(double *M)
534             {
535 #define Sd(y,x) (Sd[y*3+x])
536 #define Dd(y,x) (Dd[y*3+x])
537 #define det3(m)    (m(0,0)*(m(1,1)*m(2,2) - m(1,2)*m(2,1)) -  \
538                     m(0,1)*(m(1,0)*m(2,2) - m(1,2)*m(2,0)) +  \
539                     m(0,2)*(m(1,0)*m(2,1) - m(1,1)*m(2,0)))
540                 double *Sd = M;
541                 double *Dd = M;
542                 double d = det3(Sd);
543                 double result = 0;
544                 if ( d != 0)
545                 {
546                     double t[9];
547                     result = d;
548                     d = 1. / d;
549
550                     t[0] = (Sd(1, 1) * Sd(2, 2) - Sd(1, 2) * Sd(2, 1)) * d;
551                     t[1] = (Sd(0, 2) * Sd(2, 1) - Sd(0, 1) * Sd(2, 2)) * d;
552                     t[2] = (Sd(0, 1) * Sd(1, 2) - Sd(0, 2) * Sd(1, 1)) * d;
553
554                     t[3] = (Sd(1, 2) * Sd(2, 0) - Sd(1, 0) * Sd(2, 2)) * d;
555                     t[4] = (Sd(0, 0) * Sd(2, 2) - Sd(0, 2) * Sd(2, 0)) * d;
556                     t[5] = (Sd(0, 2) * Sd(1, 0) - Sd(0, 0) * Sd(1, 2)) * d;
557
558                     t[6] = (Sd(1, 0) * Sd(2, 1) - Sd(1, 1) * Sd(2, 0)) * d;
559                     t[7] = (Sd(0, 1) * Sd(2, 0) - Sd(0, 0) * Sd(2, 1)) * d;
560                     t[8] = (Sd(0, 0) * Sd(1, 1) - Sd(0, 1) * Sd(1, 0)) * d;
561
562                     Dd(0, 0) = t[0];
563                     Dd(0, 1) = t[1];
564                     Dd(0, 2) = t[2];
565                     Dd(1, 0) = t[3];
566                     Dd(1, 1) = t[4];
567                     Dd(1, 2) = t[5];
568                     Dd(2, 0) = t[6];
569                     Dd(2, 1) = t[7];
570                     Dd(2, 2) = t[8];
571                 }
572                 return result;
573             }
574
575             void warpAffine_gpu(const oclMat &src, oclMat &dst, F coeffs[2][3], int interpolation)
576             {
577                 CV_Assert( (src.oclchannels() == dst.oclchannels()) );
578                 int srcStep = src.step1();
579                 int dstStep = dst.step1();
580                 float float_coeffs[2][3];
581                 cl_mem coeffs_cm;
582
583                 Context *clCxt = src.clCxt;
584                 String s[3] = {"NN", "Linear", "Cubic"};
585                 String kernelName = "warpAffine" + s[interpolation];
586
587                 if (src.clCxt->supportsFeature(FEATURE_CL_DOUBLE))
588                 {
589                     cl_int st;
590                     coeffs_cm = clCreateBuffer(*(cl_context*)clCxt->getOpenCLContextPtr(), CL_MEM_READ_WRITE, sizeof(F) * 2 * 3, NULL, &st );
591                     openCLVerifyCall(st);
592                     openCLSafeCall(clEnqueueWriteBuffer(*(cl_command_queue*)clCxt->getOpenCLCommandQueuePtr(), (cl_mem)coeffs_cm, 1, 0,
593                                                         sizeof(F) * 2 * 3, coeffs, 0, 0, 0));
594                 }
595                 else
596                 {
597                     cl_int st;
598                     for(int m = 0; m < 2; m++)
599                         for(int n = 0; n < 3; n++)
600                             float_coeffs[m][n] = coeffs[m][n];
601
602                     coeffs_cm = clCreateBuffer(*(cl_context*)clCxt->getOpenCLContextPtr(), CL_MEM_READ_WRITE, sizeof(float) * 2 * 3, NULL, &st );
603                     openCLSafeCall(clEnqueueWriteBuffer(*(cl_command_queue*)clCxt->getOpenCLCommandQueuePtr(), (cl_mem)coeffs_cm,
604                                                         1, 0, sizeof(float) * 2 * 3, float_coeffs, 0, 0, 0));
605
606                 }
607                 //TODO: improve this kernel
608                 size_t blkSizeX = 16, blkSizeY = 16;
609                 size_t glbSizeX;
610                 size_t cols;
611
612                 if (src.type() == CV_8UC1 && interpolation != 2)
613                 {
614                     cols = (dst.cols + dst.offset % 4 + 3) / 4;
615                     glbSizeX = cols % blkSizeX == 0 ? cols : (cols / blkSizeX + 1) * blkSizeX;
616                 }
617                 else
618                 {
619                     cols = dst.cols;
620                     glbSizeX = dst.cols % blkSizeX == 0 ? dst.cols : (dst.cols / blkSizeX + 1) * blkSizeX;
621                 }
622
623                 size_t glbSizeY = dst.rows % blkSizeY == 0 ? dst.rows : (dst.rows / blkSizeY + 1) * blkSizeY;
624                 size_t globalThreads[3] = {glbSizeX, glbSizeY, 1};
625                 size_t localThreads[3] = {blkSizeX, blkSizeY, 1};
626
627                 std::vector< std::pair<size_t, const void *> > args;
628
629                 args.push_back(std::make_pair(sizeof(cl_mem), (void *)&src.data));
630                 args.push_back(std::make_pair(sizeof(cl_mem), (void *)&dst.data));
631                 args.push_back(std::make_pair(sizeof(cl_int), (void *)&src.cols));
632                 args.push_back(std::make_pair(sizeof(cl_int), (void *)&src.rows));
633                 args.push_back(std::make_pair(sizeof(cl_int), (void *)&dst.cols));
634                 args.push_back(std::make_pair(sizeof(cl_int), (void *)&dst.rows));
635                 args.push_back(std::make_pair(sizeof(cl_int), (void *)&srcStep));
636                 args.push_back(std::make_pair(sizeof(cl_int), (void *)&dstStep));
637                 args.push_back(std::make_pair(sizeof(cl_int), (void *)&src.offset));
638                 args.push_back(std::make_pair(sizeof(cl_int), (void *)&dst.offset));
639                 args.push_back(std::make_pair(sizeof(cl_mem), (void *)&coeffs_cm));
640                 args.push_back(std::make_pair(sizeof(cl_int), (void *)&cols));
641
642                 openCLExecuteKernel(clCxt, &imgproc_warpAffine, kernelName, globalThreads, localThreads, args, src.oclchannels(), src.depth());
643                 openCLSafeCall(clReleaseMemObject(coeffs_cm));
644             }
645
646             void warpPerspective_gpu(const oclMat &src, oclMat &dst, double coeffs[3][3], int interpolation)
647             {
648                 CV_Assert( (src.oclchannels() == dst.oclchannels()) );
649                 int srcStep = src.step1();
650                 int dstStep = dst.step1();
651                 float float_coeffs[3][3];
652                 cl_mem coeffs_cm;
653
654                 Context *clCxt = src.clCxt;
655                 String s[3] = {"NN", "Linear", "Cubic"};
656                 String kernelName = "warpPerspective" + s[interpolation];
657
658                 if (src.clCxt->supportsFeature(FEATURE_CL_DOUBLE))
659                 {
660                     cl_int st;
661                     coeffs_cm = clCreateBuffer(*(cl_context*)clCxt->getOpenCLContextPtr(), CL_MEM_READ_WRITE, sizeof(double) * 3 * 3, NULL, &st );
662                     openCLVerifyCall(st);
663                     openCLSafeCall(clEnqueueWriteBuffer(*(cl_command_queue*)clCxt->getOpenCLCommandQueuePtr(), (cl_mem)coeffs_cm, 1, 0,
664                                                         sizeof(double) * 3 * 3, coeffs, 0, 0, 0));
665                 }
666                 else
667                 {
668                     cl_int st;
669                     for(int m = 0; m < 3; m++)
670                         for(int n = 0; n < 3; n++)
671                             float_coeffs[m][n] = coeffs[m][n];
672
673                     coeffs_cm = clCreateBuffer(*(cl_context*)clCxt->getOpenCLContextPtr(), CL_MEM_READ_WRITE, sizeof(float) * 3 * 3, NULL, &st );
674                     openCLVerifyCall(st);
675                     openCLSafeCall(clEnqueueWriteBuffer(*(cl_command_queue*)clCxt->getOpenCLCommandQueuePtr(), (cl_mem)coeffs_cm, 1, 0,
676                                                         sizeof(float) * 3 * 3, float_coeffs, 0, 0, 0));
677                 }
678
679                 //TODO: improve this kernel
680                 size_t blkSizeX = 16, blkSizeY = 16;
681                 size_t glbSizeX;
682                 size_t cols;
683                 if (src.type() == CV_8UC1 && interpolation == 0)
684                 {
685                     cols = (dst.cols + dst.offset % 4 + 3) / 4;
686                     glbSizeX = cols % blkSizeX == 0 ? cols : (cols / blkSizeX + 1) * blkSizeX;
687                 }
688                 else
689                 {
690                     cols = dst.cols;
691                     glbSizeX = dst.cols % blkSizeX == 0 ? dst.cols : (dst.cols / blkSizeX + 1) * blkSizeX;
692                 }
693
694                 size_t glbSizeY = dst.rows % blkSizeY == 0 ? dst.rows : (dst.rows / blkSizeY + 1) * blkSizeY;
695                 size_t globalThreads[3] = {glbSizeX, glbSizeY, 1};
696                 size_t localThreads[3] = {blkSizeX, blkSizeY, 1};
697
698                 std::vector< std::pair<size_t, const void *> > args;
699
700                 args.push_back(std::make_pair(sizeof(cl_mem), (void *)&src.data));
701                 args.push_back(std::make_pair(sizeof(cl_mem), (void *)&dst.data));
702                 args.push_back(std::make_pair(sizeof(cl_int), (void *)&src.cols));
703                 args.push_back(std::make_pair(sizeof(cl_int), (void *)&src.rows));
704                 args.push_back(std::make_pair(sizeof(cl_int), (void *)&dst.cols));
705                 args.push_back(std::make_pair(sizeof(cl_int), (void *)&dst.rows));
706                 args.push_back(std::make_pair(sizeof(cl_int), (void *)&srcStep));
707                 args.push_back(std::make_pair(sizeof(cl_int), (void *)&dstStep));
708                 args.push_back(std::make_pair(sizeof(cl_int), (void *)&src.offset));
709                 args.push_back(std::make_pair(sizeof(cl_int), (void *)&dst.offset));
710                 args.push_back(std::make_pair(sizeof(cl_mem), (void *)&coeffs_cm));
711                 args.push_back(std::make_pair(sizeof(cl_int), (void *)&cols));
712
713                 openCLExecuteKernel(clCxt, &imgproc_warpPerspective, kernelName, globalThreads, localThreads, args, src.oclchannels(), src.depth());
714                 openCLSafeCall(clReleaseMemObject(coeffs_cm));
715             }
716         }
717
718         void warpAffine(const oclMat &src, oclMat &dst, const Mat &M, Size dsize, int flags)
719         {
720             int interpolation = flags & INTER_MAX;
721
722             CV_Assert((src.depth() == CV_8U  || src.depth() == CV_32F) && src.oclchannels() != 2 && src.oclchannels() != 3);
723             CV_Assert(interpolation == INTER_NEAREST || interpolation == INTER_LINEAR || interpolation == INTER_CUBIC);
724
725             dst.create(dsize, src.type());
726
727             CV_Assert(M.rows == 2 && M.cols == 3);
728
729             int warpInd = (flags & WARP_INVERSE_MAP) >> 4;
730             F coeffs[2][3];
731
732             double coeffsM[2*3];
733             Mat coeffsMat(2, 3, CV_64F, (void *)coeffsM);
734             M.convertTo(coeffsMat, coeffsMat.type());
735             if (!warpInd)
736                 convert_coeffs(coeffsM);
737
738             for(int i = 0; i < 2; ++i)
739                 for(int j = 0; j < 3; ++j)
740                     coeffs[i][j] = coeffsM[i*3+j];
741
742             warpAffine_gpu(src, dst, coeffs, interpolation);
743         }
744
745         void warpPerspective(const oclMat &src, oclMat &dst, const Mat &M, Size dsize, int flags)
746         {
747             int interpolation = flags & INTER_MAX;
748
749             CV_Assert((src.depth() == CV_8U  || src.depth() == CV_32F) && src.oclchannels() != 2 && src.oclchannels() != 3);
750             CV_Assert(interpolation == INTER_NEAREST || interpolation == INTER_LINEAR || interpolation == INTER_CUBIC);
751
752             dst.create(dsize, src.type());
753
754
755             CV_Assert(M.rows == 3 && M.cols == 3);
756
757             int warpInd = (flags & WARP_INVERSE_MAP) >> 4;
758             double coeffs[3][3];
759
760             double coeffsM[3*3];
761             Mat coeffsMat(3, 3, CV_64F, (void *)coeffsM);
762             M.convertTo(coeffsMat, coeffsMat.type());
763             if (!warpInd)
764                 invert(coeffsM);
765
766             for(int i = 0; i < 3; ++i)
767                 for(int j = 0; j < 3; ++j)
768                     coeffs[i][j] = coeffsM[i*3+j];
769
770             warpPerspective_gpu(src, dst, coeffs, interpolation);
771         }
772
773         ////////////////////////////////////////////////////////////////////////
774         // integral
775
776         void integral(const oclMat &src, oclMat &sum, oclMat &sqsum)
777         {
778             CV_Assert(src.type() == CV_8UC1);
779             if (!src.clCxt->supportsFeature(ocl::FEATURE_CL_DOUBLE) && src.depth() == CV_64F)
780             {
781                 CV_Error(Error::OpenCLDoubleNotSupported, "Select device doesn't support double");
782                 return;
783             }
784
785             int vlen = 4;
786             int offset = src.offset / vlen;
787             int pre_invalid = src.offset % vlen;
788             int vcols = (pre_invalid + src.cols + vlen - 1) / vlen;
789
790             oclMat t_sum , t_sqsum;
791             int w = src.cols + 1, h = src.rows + 1;
792             int depth = src.depth() == CV_8U ? CV_32S : CV_64F;
793             int type = CV_MAKE_TYPE(depth, 1);
794
795             t_sum.create(src.cols, src.rows, type);
796             sum.create(h, w, type);
797
798             t_sqsum.create(src.cols, src.rows, CV_32FC1);
799             sqsum.create(h, w, CV_32FC1);
800
801             int sum_offset = sum.offset / vlen;
802             int sqsum_offset = sqsum.offset / vlen;
803
804             std::vector<std::pair<size_t , const void *> > args;
805             args.push_back( std::make_pair( sizeof(cl_mem) , (void *)&src.data ));
806             args.push_back( std::make_pair( sizeof(cl_mem) , (void *)&t_sum.data ));
807             args.push_back( std::make_pair( sizeof(cl_mem) , (void *)&t_sqsum.data ));
808             args.push_back( std::make_pair( sizeof(cl_int) , (void *)&offset ));
809             args.push_back( std::make_pair( sizeof(cl_int) , (void *)&pre_invalid ));
810             args.push_back( std::make_pair( sizeof(cl_int) , (void *)&src.rows ));
811             args.push_back( std::make_pair( sizeof(cl_int) , (void *)&src.cols ));
812             args.push_back( std::make_pair( sizeof(cl_int) , (void *)&src.step ));
813             args.push_back( std::make_pair( sizeof(cl_int) , (void *)&t_sum.step));
814             size_t gt[3] = {((vcols + 1) / 2) * 256, 1, 1}, lt[3] = {256, 1, 1};
815             openCLExecuteKernel(src.clCxt, &imgproc_integral, "integral_cols", gt, lt, args, -1, depth);
816
817             args.clear();
818             args.push_back( std::make_pair( sizeof(cl_mem) , (void *)&t_sum.data ));
819             args.push_back( std::make_pair( sizeof(cl_mem) , (void *)&t_sqsum.data ));
820             args.push_back( std::make_pair( sizeof(cl_mem) , (void *)&sum.data ));
821             args.push_back( std::make_pair( sizeof(cl_mem) , (void *)&sqsum.data ));
822             args.push_back( std::make_pair( sizeof(cl_int) , (void *)&t_sum.rows ));
823             args.push_back( std::make_pair( sizeof(cl_int) , (void *)&t_sum.cols ));
824             args.push_back( std::make_pair( sizeof(cl_int) , (void *)&t_sum.step ));
825             args.push_back( std::make_pair( sizeof(cl_int) , (void *)&sum.step));
826             args.push_back( std::make_pair( sizeof(cl_int) , (void *)&sqsum.step));
827             args.push_back( std::make_pair( sizeof(cl_int) , (void *)&sum_offset));
828             args.push_back( std::make_pair( sizeof(cl_int) , (void *)&sqsum_offset));
829             size_t gt2[3] = {t_sum.cols  * 32, 1, 1}, lt2[3] = {256, 1, 1};
830             openCLExecuteKernel(src.clCxt, &imgproc_integral, "integral_rows", gt2, lt2, args, -1, depth);
831         }
832
833         void integral(const oclMat &src, oclMat &sum)
834         {
835             CV_Assert(src.type() == CV_8UC1);
836             int vlen = 4;
837             int offset = src.offset / vlen;
838             int pre_invalid = src.offset % vlen;
839             int vcols = (pre_invalid + src.cols + vlen - 1) / vlen;
840
841             oclMat t_sum;
842             int w = src.cols + 1, h = src.rows + 1;
843             int depth = src.depth() == CV_8U ? CV_32S : CV_32F;
844             int type = CV_MAKE_TYPE(depth, 1);
845
846             t_sum.create(src.cols, src.rows, type);
847             sum.create(h, w, type);
848
849             int sum_offset = sum.offset / vlen;
850             std::vector<std::pair<size_t , const void *> > args;
851             args.push_back( std::make_pair( sizeof(cl_mem) , (void *)&src.data ));
852             args.push_back( std::make_pair( sizeof(cl_mem) , (void *)&t_sum.data ));
853             args.push_back( std::make_pair( sizeof(cl_int) , (void *)&offset ));
854             args.push_back( std::make_pair( sizeof(cl_int) , (void *)&pre_invalid ));
855             args.push_back( std::make_pair( sizeof(cl_int) , (void *)&src.rows ));
856             args.push_back( std::make_pair( sizeof(cl_int) , (void *)&src.cols ));
857             args.push_back( std::make_pair( sizeof(cl_int) , (void *)&src.step ));
858             args.push_back( std::make_pair( sizeof(cl_int) , (void *)&t_sum.step));
859             size_t gt[3] = {((vcols + 1) / 2) * 256, 1, 1}, lt[3] = {256, 1, 1};
860             openCLExecuteKernel(src.clCxt, &imgproc_integral_sum, "integral_sum_cols", gt, lt, args, -1, depth);
861
862             args.clear();
863             args.push_back( std::make_pair( sizeof(cl_mem) , (void *)&t_sum.data ));
864             args.push_back( std::make_pair( sizeof(cl_mem) , (void *)&sum.data ));
865             args.push_back( std::make_pair( sizeof(cl_int) , (void *)&t_sum.rows ));
866             args.push_back( std::make_pair( sizeof(cl_int) , (void *)&t_sum.cols ));
867             args.push_back( std::make_pair( sizeof(cl_int) , (void *)&t_sum.step ));
868             args.push_back( std::make_pair( sizeof(cl_int) , (void *)&sum.step));
869             args.push_back( std::make_pair( sizeof(cl_int) , (void *)&sum_offset));
870             size_t gt2[3] = {t_sum.cols  * 32, 1, 1}, lt2[3] = {256, 1, 1};
871             openCLExecuteKernel(src.clCxt, &imgproc_integral_sum, "integral_sum_rows", gt2, lt2, args, -1, depth);
872         }
873
874         /////////////////////// corner //////////////////////////////
875
876         static void extractCovData(const oclMat &src, oclMat &Dx, oclMat &Dy,
877                             int blockSize, int ksize, int borderType)
878         {
879             CV_Assert(src.type() == CV_8UC1 || src.type() == CV_32FC1);
880             double scale = static_cast<double>(1 << ((ksize > 0 ? ksize : 3) - 1)) * blockSize;
881             if (ksize < 0)
882                 scale *= 2.;
883
884             if (src.depth() == CV_8U)
885             {
886                 scale *= 255.;
887                 scale = 1. / scale;
888             }
889             else
890                 scale = 1. / scale;
891
892             if (ksize > 0)
893             {
894                 Sobel(src, Dx, CV_32F, 1, 0, ksize, scale, 0, borderType);
895                 Sobel(src, Dy, CV_32F, 0, 1, ksize, scale, 0, borderType);
896             }
897             else
898             {
899                 Scharr(src, Dx, CV_32F, 1, 0, scale, 0, borderType);
900                 Scharr(src, Dy, CV_32F, 0, 1, scale, 0, borderType);
901             }
902             CV_Assert(Dx.offset == 0 && Dy.offset == 0);
903         }
904
905         static void corner_ocl(const cv::ocl::ProgramEntry* source, String kernelName, int block_size, float k, oclMat &Dx, oclMat &Dy,
906                         oclMat &dst, int border_type)
907         {
908             char borderType[30];
909             switch (border_type)
910             {
911             case cv::BORDER_CONSTANT:
912                 sprintf(borderType, "BORDER_CONSTANT");
913                 break;
914             case cv::BORDER_REFLECT101:
915                 sprintf(borderType, "BORDER_REFLECT101");
916                 break;
917             case cv::BORDER_REFLECT:
918                 sprintf(borderType, "BORDER_REFLECT");
919                 break;
920             case cv::BORDER_REPLICATE:
921                 sprintf(borderType, "BORDER_REPLICATE");
922                 break;
923             default:
924                 CV_Error(Error::StsBadFlag, "BORDER type is not supported!");
925             }
926
927             std::string buildOptions = format("-D anX=%d -D anY=%d -D ksX=%d -D ksY=%d -D %s",
928                     block_size / 2, block_size / 2, block_size, block_size, borderType);
929
930             size_t blockSizeX = 256, blockSizeY = 1;
931             size_t gSize = blockSizeX - block_size / 2 * 2;
932             size_t globalSizeX = (Dx.cols) % gSize == 0 ? Dx.cols / gSize * blockSizeX : (Dx.cols / gSize + 1) * blockSizeX;
933             size_t rows_per_thread = 2;
934             size_t globalSizeY = ((Dx.rows + rows_per_thread - 1) / rows_per_thread) % blockSizeY == 0 ?
935                                  ((Dx.rows + rows_per_thread - 1) / rows_per_thread) :
936                                  (((Dx.rows + rows_per_thread - 1) / rows_per_thread) / blockSizeY + 1) * blockSizeY;
937
938             size_t gt[3] = { globalSizeX, globalSizeY, 1 };
939             size_t lt[3]  = { blockSizeX, blockSizeY, 1 };
940             std::vector<std::pair<size_t , const void *> > args;
941             args.push_back( std::make_pair( sizeof(cl_mem) , (void *)&Dx.data ));
942             args.push_back( std::make_pair( sizeof(cl_mem) , (void *)&Dy.data));
943             args.push_back( std::make_pair( sizeof(cl_mem) , (void *)&dst.data));
944             args.push_back( std::make_pair( sizeof(cl_int) , (void *)&Dx.offset ));
945             args.push_back( std::make_pair( sizeof(cl_int) , (void *)&Dx.wholerows ));
946             args.push_back( std::make_pair( sizeof(cl_int) , (void *)&Dx.wholecols ));
947             args.push_back( std::make_pair(sizeof(cl_int), (void *)&Dx.step));
948             args.push_back( std::make_pair( sizeof(cl_int) , (void *)&Dy.offset ));
949             args.push_back( std::make_pair( sizeof(cl_int) , (void *)&Dy.wholerows ));
950             args.push_back( std::make_pair( sizeof(cl_int) , (void *)&Dy.wholecols ));
951             args.push_back( std::make_pair(sizeof(cl_int), (void *)&Dy.step));
952             args.push_back( std::make_pair(sizeof(cl_int), (void *)&dst.offset));
953             args.push_back( std::make_pair(sizeof(cl_int), (void *)&dst.rows));
954             args.push_back( std::make_pair(sizeof(cl_int), (void *)&dst.cols));
955             args.push_back( std::make_pair(sizeof(cl_int), (void *)&dst.step));
956             args.push_back( std::make_pair( sizeof(cl_float) , (void *)&k));
957             openCLExecuteKernel(dst.clCxt, source, kernelName, gt, lt, args, -1, -1, buildOptions.c_str());
958         }
959
960         void cornerHarris(const oclMat &src, oclMat &dst, int blockSize, int ksize,
961                           double k, int borderType)
962         {
963             oclMat dx, dy;
964             cornerHarris_dxdy(src, dst, dx, dy, blockSize, ksize, k, borderType);
965         }
966
967         void cornerHarris_dxdy(const oclMat &src, oclMat &dst, oclMat &dx, oclMat &dy, int blockSize, int ksize,
968                           double k, int borderType)
969         {
970             if (!src.clCxt->supportsFeature(FEATURE_CL_DOUBLE) && src.depth() == CV_64F)
971             {
972                 CV_Error(Error::OpenCLDoubleNotSupported, "Select device doesn't support double");
973                 return;
974             }
975
976             CV_Assert(src.cols >= blockSize / 2 && src.rows >= blockSize / 2);
977             CV_Assert(borderType == cv::BORDER_CONSTANT || borderType == cv::BORDER_REFLECT101 || borderType == cv::BORDER_REPLICATE
978                       || borderType == cv::BORDER_REFLECT);
979             extractCovData(src, dx, dy, blockSize, ksize, borderType);
980             dst.create(src.size(), CV_32F);
981             corner_ocl(&imgproc_calcHarris, "calcHarris", blockSize, static_cast<float>(k), dx, dy, dst, borderType);
982         }
983
984         void cornerMinEigenVal(const oclMat &src, oclMat &dst, int blockSize, int ksize, int borderType)
985         {
986             oclMat dx, dy;
987             cornerMinEigenVal_dxdy(src, dst, dx, dy, blockSize, ksize, borderType);
988         }
989
990         void cornerMinEigenVal_dxdy(const oclMat &src, oclMat &dst, oclMat &dx, oclMat &dy, int blockSize, int ksize, int borderType)
991         {
992             if (!src.clCxt->supportsFeature(FEATURE_CL_DOUBLE) && src.depth() == CV_64F)
993             {
994                 CV_Error(Error::OpenCLDoubleNotSupported, "select device don't support double");
995                 return;
996             }
997
998             CV_Assert(src.cols >= blockSize / 2 && src.rows >= blockSize / 2);
999             CV_Assert(borderType == cv::BORDER_CONSTANT || borderType == cv::BORDER_REFLECT101 || borderType == cv::BORDER_REPLICATE || borderType == cv::BORDER_REFLECT);
1000             extractCovData(src, dx, dy, blockSize, ksize, borderType);
1001             dst.create(src.size(), CV_32F);
1002
1003             corner_ocl(&imgproc_calcMinEigenVal, "calcMinEigenVal", blockSize, 0, dx, dy, dst, borderType);
1004         }
1005
1006         /////////////////////////////////// MeanShiftfiltering ///////////////////////////////////////////////
1007
1008         static void meanShiftFiltering_gpu(const oclMat &src, oclMat dst, int sp, int sr, int maxIter, float eps)
1009         {
1010             CV_Assert( (src.cols == dst.cols) && (src.rows == dst.rows) );
1011             CV_Assert( !(dst.step & 0x3) );
1012
1013             //Arrange the NDRange
1014             int col = src.cols, row = src.rows;
1015             int ltx = 16, lty = 8;
1016             if (src.cols % ltx != 0)
1017                 col = (col / ltx + 1) * ltx;
1018             if (src.rows % lty != 0)
1019                 row = (row / lty + 1) * lty;
1020
1021             size_t globalThreads[3] = {col, row, 1};
1022             size_t localThreads[3]  = {ltx, lty, 1};
1023
1024             //set args
1025             std::vector<std::pair<size_t , const void *> > args;
1026             args.push_back( std::make_pair( sizeof(cl_mem) , (void *)&dst.data ));
1027             args.push_back( std::make_pair( sizeof(cl_int) , (void *)&dst.step ));
1028             args.push_back( std::make_pair( sizeof(cl_mem) , (void *)&src.data ));
1029             args.push_back( std::make_pair( sizeof(cl_int) , (void *)&src.step ));
1030             args.push_back( std::make_pair( sizeof(cl_int) , (void *)&dst.offset ));
1031             args.push_back( std::make_pair( sizeof(cl_int) , (void *)&src.offset ));
1032             args.push_back( std::make_pair( sizeof(cl_int) , (void *)&dst.cols ));
1033             args.push_back( std::make_pair( sizeof(cl_int) , (void *)&dst.rows ));
1034             args.push_back( std::make_pair( sizeof(cl_int) , (void *)&sp ));
1035             args.push_back( std::make_pair( sizeof(cl_int) , (void *)&sr ));
1036             args.push_back( std::make_pair( sizeof(cl_int) , (void *)&maxIter ));
1037             args.push_back( std::make_pair( sizeof(cl_float) , (void *)&eps ));
1038
1039             openCLExecuteKernel(src.clCxt, &meanShift, "meanshift_kernel", globalThreads, localThreads, args, -1, -1);
1040         }
1041
1042         void meanShiftFiltering(const oclMat &src, oclMat &dst, int sp, int sr, TermCriteria criteria)
1043         {
1044             if (src.empty())
1045                 CV_Error(Error::StsBadArg, "The input image is empty");
1046
1047             if ( src.depth() != CV_8U || src.oclchannels() != 4 )
1048                 CV_Error(Error::StsUnsupportedFormat, "Only 8-bit, 4-channel images are supported");
1049
1050             dst.create( src.size(), CV_8UC4 );
1051
1052             if ( !(criteria.type & TermCriteria::MAX_ITER) )
1053                 criteria.maxCount = 5;
1054
1055             int maxIter = std::min(std::max(criteria.maxCount, 1), 100);
1056
1057             float eps;
1058             if ( !(criteria.type & TermCriteria::EPS) )
1059                 eps = 1.f;
1060             eps = (float)std::max(criteria.epsilon, 0.0);
1061
1062             meanShiftFiltering_gpu(src, dst, sp, sr, maxIter, eps);
1063         }
1064
1065         static void meanShiftProc_gpu(const oclMat &src, oclMat dstr, oclMat dstsp, int sp, int sr, int maxIter, float eps)
1066         {
1067             //sanity checks
1068             CV_Assert( (src.cols == dstr.cols) && (src.rows == dstr.rows) &&
1069                        (src.rows == dstsp.rows) && (src.cols == dstsp.cols));
1070             CV_Assert( !(dstsp.step & 0x3) );
1071
1072             //Arrange the NDRange
1073             int col = src.cols, row = src.rows;
1074             int ltx = 16, lty = 8;
1075             if (src.cols % ltx != 0)
1076                 col = (col / ltx + 1) * ltx;
1077             if (src.rows % lty != 0)
1078                 row = (row / lty + 1) * lty;
1079
1080             size_t globalThreads[3] = {col, row, 1};
1081             size_t localThreads[3]  = {ltx, lty, 1};
1082
1083             //set args
1084             std::vector<std::pair<size_t , const void *> > args;
1085             args.push_back( std::make_pair( sizeof(cl_mem) , (void *)&src.data ));
1086             args.push_back( std::make_pair( sizeof(cl_mem) , (void *)&dstr.data ));
1087             args.push_back( std::make_pair( sizeof(cl_mem) , (void *)&dstsp.data ));
1088             args.push_back( std::make_pair( sizeof(cl_int) , (void *)&src.step ));
1089             args.push_back( std::make_pair( sizeof(cl_int) , (void *)&dstr.step ));
1090             args.push_back( std::make_pair( sizeof(cl_int) , (void *)&dstsp.step ));
1091             args.push_back( std::make_pair( sizeof(cl_int) , (void *)&src.offset ));
1092             args.push_back( std::make_pair( sizeof(cl_int) , (void *)&dstr.offset ));
1093             args.push_back( std::make_pair( sizeof(cl_int) , (void *)&dstsp.offset ));
1094             args.push_back( std::make_pair( sizeof(cl_int) , (void *)&dstr.cols ));
1095             args.push_back( std::make_pair( sizeof(cl_int) , (void *)&dstr.rows ));
1096             args.push_back( std::make_pair( sizeof(cl_int) , (void *)&sp ));
1097             args.push_back( std::make_pair( sizeof(cl_int) , (void *)&sr ));
1098             args.push_back( std::make_pair( sizeof(cl_int) , (void *)&maxIter ));
1099             args.push_back( std::make_pair( sizeof(cl_float) , (void *)&eps ));
1100
1101             openCLExecuteKernel(src.clCxt, &meanShift, "meanshiftproc_kernel", globalThreads, localThreads, args, -1, -1);
1102         }
1103
1104         void meanShiftProc(const oclMat &src, oclMat &dstr, oclMat &dstsp, int sp, int sr, TermCriteria criteria)
1105         {
1106             if (src.empty())
1107                 CV_Error(Error::StsBadArg, "The input image is empty");
1108
1109             if ( src.depth() != CV_8U || src.oclchannels() != 4 )
1110                 CV_Error(Error::StsUnsupportedFormat, "Only 8-bit, 4-channel images are supported");
1111
1112 //            if (!src.clCxt->supportsFeature(FEATURE_CL_DOUBLE))
1113 //            {
1114 //                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");
1115 //                return;
1116 //            }
1117
1118             dstr.create( src.size(), CV_8UC4 );
1119             dstsp.create( src.size(), CV_16SC2 );
1120
1121             if ( !(criteria.type & TermCriteria::MAX_ITER) )
1122                 criteria.maxCount = 5;
1123
1124             int maxIter = std::min(std::max(criteria.maxCount, 1), 100);
1125
1126             float eps;
1127             if ( !(criteria.type & TermCriteria::EPS) )
1128                 eps = 1.f;
1129             eps = (float)std::max(criteria.epsilon, 0.0);
1130
1131             meanShiftProc_gpu(src, dstr, dstsp, sp, sr, maxIter, eps);
1132         }
1133
1134         ///////////////////////////////////////////////////////////////////////////////////////////////////
1135         ////////////////////////////////////////////////////hist///////////////////////////////////////////////
1136         /////////////////////////////////////////////////////////////////////////////////////////////////////
1137
1138         namespace histograms
1139         {
1140             const int PARTIAL_HISTOGRAM256_COUNT = 256;
1141             const int HISTOGRAM256_BIN_COUNT = 256;
1142         }
1143         ///////////////////////////////calcHist/////////////////////////////////////////////////////////////////
1144         static void calc_sub_hist(const oclMat &mat_src, const oclMat &mat_sub_hist)
1145         {
1146             using namespace histograms;
1147
1148             int depth = mat_src.depth();
1149
1150             size_t localThreads[3]  = { HISTOGRAM256_BIN_COUNT, 1, 1 };
1151             size_t globalThreads[3] = { PARTIAL_HISTOGRAM256_COUNT *localThreads[0], 1, 1};
1152
1153             int dataWidth = 16;
1154             int dataWidth_bits = 4;
1155             int mask = dataWidth - 1;
1156
1157             int cols = mat_src.cols * mat_src.oclchannels();
1158             int src_offset = mat_src.offset;
1159             int hist_step = mat_sub_hist.step >> 2;
1160             int left_col = 0, right_col = 0;
1161
1162             if (cols >= dataWidth * 2 - 1)
1163             {
1164                 left_col = dataWidth - (src_offset & mask);
1165                 left_col &= mask;
1166                 src_offset += left_col;
1167                 cols -= left_col;
1168                 right_col = cols & mask;
1169                 cols -= right_col;
1170             }
1171             else
1172             {
1173                 left_col = cols;
1174                 right_col = 0;
1175                 cols = 0;
1176                 globalThreads[0] = 0;
1177             }
1178
1179             std::vector<std::pair<size_t , const void *> > args;
1180             if (globalThreads[0] != 0)
1181             {
1182                 int tempcols = cols >> dataWidth_bits;
1183                 int inc_x = globalThreads[0] % tempcols;
1184                 int inc_y = globalThreads[0] / tempcols;
1185                 src_offset >>= dataWidth_bits;
1186                 int src_step = mat_src.step >> dataWidth_bits;
1187                 int datacount = tempcols * mat_src.rows;
1188
1189                 args.push_back( std::make_pair( sizeof(cl_mem), (void *)&mat_src.data));
1190                 args.push_back( std::make_pair( sizeof(cl_int), (void *)&src_step));
1191                 args.push_back( std::make_pair( sizeof(cl_int), (void *)&src_offset));
1192                 args.push_back( std::make_pair( sizeof(cl_mem), (void *)&mat_sub_hist.data));
1193                 args.push_back( std::make_pair( sizeof(cl_int), (void *)&datacount));
1194                 args.push_back( std::make_pair( sizeof(cl_int), (void *)&tempcols));
1195                 args.push_back( std::make_pair( sizeof(cl_int), (void *)&inc_x));
1196                 args.push_back( std::make_pair( sizeof(cl_int), (void *)&inc_y));
1197                 args.push_back( std::make_pair( sizeof(cl_int), (void *)&hist_step));
1198
1199                 openCLExecuteKernel(mat_src.clCxt, &imgproc_histogram, "calc_sub_hist", globalThreads, localThreads, args, -1, depth);
1200             }
1201
1202             if (left_col != 0 || right_col != 0)
1203             {
1204                 src_offset = mat_src.offset;
1205                 localThreads[0] = 1;
1206                 localThreads[1] = 256;
1207                 globalThreads[0] = left_col + right_col;
1208                 globalThreads[1] = mat_src.rows;
1209
1210                 args.clear();
1211                 args.push_back( std::make_pair( sizeof(cl_mem), (void *)&mat_src.data));
1212                 args.push_back( std::make_pair( sizeof(cl_int), (void *)&mat_src.step));
1213                 args.push_back( std::make_pair( sizeof(cl_int), (void *)&src_offset));
1214                 args.push_back( std::make_pair( sizeof(cl_mem), (void *)&mat_sub_hist.data));
1215                 args.push_back( std::make_pair( sizeof(cl_int), (void *)&left_col));
1216                 args.push_back( std::make_pair( sizeof(cl_int), (void *)&cols));
1217                 args.push_back( std::make_pair( sizeof(cl_int), (void *)&mat_src.rows));
1218                 args.push_back( std::make_pair( sizeof(cl_int), (void *)&hist_step));
1219
1220                 openCLExecuteKernel(mat_src.clCxt, &imgproc_histogram, "calc_sub_hist_border", globalThreads, localThreads, args, -1, depth);
1221             }
1222         }
1223
1224         static void merge_sub_hist(const oclMat &sub_hist, oclMat &mat_hist)
1225         {
1226             using namespace histograms;
1227
1228             size_t localThreads[3]  = { 256, 1, 1 };
1229             size_t globalThreads[3] = { HISTOGRAM256_BIN_COUNT *localThreads[0], 1, 1};
1230             int src_step = sub_hist.step >> 2;
1231
1232             std::vector<std::pair<size_t , const void *> > args;
1233             args.push_back( std::make_pair( sizeof(cl_mem), (void *)&sub_hist.data));
1234             args.push_back( std::make_pair( sizeof(cl_mem), (void *)&mat_hist.data));
1235             args.push_back( std::make_pair( sizeof(cl_int), (void *)&src_step));
1236
1237             openCLExecuteKernel(sub_hist.clCxt, &imgproc_histogram, "merge_hist", globalThreads, localThreads, args, -1, -1);
1238         }
1239
1240         void calcHist(const oclMat &mat_src, oclMat &mat_hist)
1241         {
1242             using namespace histograms;
1243             CV_Assert(mat_src.type() == CV_8UC1);
1244             mat_hist.create(1, 256, CV_32SC1);
1245
1246             oclMat buf(PARTIAL_HISTOGRAM256_COUNT, HISTOGRAM256_BIN_COUNT, CV_32SC1);
1247             buf.setTo(0);
1248
1249             calc_sub_hist(mat_src, buf);
1250             merge_sub_hist(buf, mat_hist);
1251         }
1252
1253         ///////////////////////////////////equalizeHist/////////////////////////////////////////////////////
1254         void equalizeHist(const oclMat &mat_src, oclMat &mat_dst)
1255         {
1256             mat_dst.create(mat_src.rows, mat_src.cols, CV_8UC1);
1257
1258             oclMat mat_hist(1, 256, CV_32SC1);
1259
1260             calcHist(mat_src, mat_hist);
1261
1262             size_t localThreads[3] = { 256, 1, 1};
1263             size_t globalThreads[3] = { 256, 1, 1};
1264             oclMat lut(1, 256, CV_8UC1);
1265             int total = mat_src.rows * mat_src.cols;
1266
1267             std::vector<std::pair<size_t , const void *> > args;
1268             args.push_back( std::make_pair( sizeof(cl_mem), (void *)&lut.data));
1269             args.push_back( std::make_pair( sizeof(cl_mem), (void *)&mat_hist.data));
1270             args.push_back( std::make_pair( sizeof(int), (void *)&total));
1271
1272             openCLExecuteKernel(mat_src.clCxt, &imgproc_histogram, "calLUT", globalThreads, localThreads, args, -1, -1);
1273             LUT(mat_src, lut, mat_dst);
1274         }
1275
1276         ////////////////////////////////////////////////////////////////////////
1277         // CLAHE
1278         namespace clahe
1279         {
1280             static void calcLut(const oclMat &src, oclMat &dst,
1281                 const int tilesX, const int tilesY, const cv::Size tileSize,
1282                 const int clipLimit, const float lutScale)
1283             {
1284                 cl_int2 tile_size;
1285                 tile_size.s[0] = tileSize.width;
1286                 tile_size.s[1] = tileSize.height;
1287
1288                 std::vector<std::pair<size_t , const void *> > args;
1289                 args.push_back( std::make_pair( sizeof(cl_mem), (void *)&src.data ));
1290                 args.push_back( std::make_pair( sizeof(cl_mem), (void *)&dst.data ));
1291                 args.push_back( std::make_pair( sizeof(cl_int), (void *)&src.step ));
1292                 args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst.step ));
1293                 args.push_back( std::make_pair( sizeof(cl_int2), (void *)&tile_size ));
1294                 args.push_back( std::make_pair( sizeof(cl_int), (void *)&tilesX ));
1295                 args.push_back( std::make_pair( sizeof(cl_int), (void *)&clipLimit ));
1296                 args.push_back( std::make_pair( sizeof(cl_float), (void *)&lutScale ));
1297                 args.push_back( std::make_pair( sizeof(cl_int), (void *)&src.offset ));
1298                 args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst.offset ));
1299
1300                 String kernelName = "calcLut";
1301                 size_t localThreads[3]  = { 32, 8, 1 };
1302                 size_t globalThreads[3] = { tilesX * localThreads[0], tilesY * localThreads[1], 1 };
1303                 bool is_cpu = isCpuDevice();
1304                 if (is_cpu)
1305                     openCLExecuteKernel(Context::getContext(), &imgproc_clahe, kernelName, globalThreads, localThreads, args, -1, -1, (char*)"-D CPU");
1306                 else
1307                 {
1308                     cl_kernel kernel = openCLGetKernelFromSource(Context::getContext(), &imgproc_clahe, kernelName);
1309                     int wave_size = (int)queryWaveFrontSize(kernel);
1310                     openCLSafeCall(clReleaseKernel(kernel));
1311
1312                     std::string opt = format("-D WAVE_SIZE=%d", wave_size);
1313                     openCLExecuteKernel(Context::getContext(), &imgproc_clahe, kernelName, globalThreads, localThreads, args, -1, -1, opt.c_str());
1314                 }
1315             }
1316
1317             static void transform(const oclMat &src, oclMat &dst, const oclMat &lut,
1318                 const int tilesX, const int tilesY, const Size & tileSize)
1319             {
1320                 cl_int2 tile_size;
1321                 tile_size.s[0] = tileSize.width;
1322                 tile_size.s[1] = tileSize.height;
1323
1324                 std::vector<std::pair<size_t , const void *> > args;
1325                 args.push_back( std::make_pair( sizeof(cl_mem), (void *)&src.data ));
1326                 args.push_back( std::make_pair( sizeof(cl_mem), (void *)&dst.data ));
1327                 args.push_back( std::make_pair( sizeof(cl_mem), (void *)&lut.data ));
1328                 args.push_back( std::make_pair( sizeof(cl_int), (void *)&src.step ));
1329                 args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst.step ));
1330                 args.push_back( std::make_pair( sizeof(cl_int), (void *)&lut.step ));
1331                 args.push_back( std::make_pair( sizeof(cl_int), (void *)&src.cols ));
1332                 args.push_back( std::make_pair( sizeof(cl_int), (void *)&src.rows ));
1333                 args.push_back( std::make_pair( sizeof(cl_int2), (void *)&tile_size ));
1334                 args.push_back( std::make_pair( sizeof(cl_int), (void *)&tilesX ));
1335                 args.push_back( std::make_pair( sizeof(cl_int), (void *)&tilesY ));
1336                 args.push_back( std::make_pair( sizeof(cl_int), (void *)&src.offset ));
1337                 args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst.offset ));
1338                 args.push_back( std::make_pair( sizeof(cl_int), (void *)&lut.offset ));
1339
1340                 size_t localThreads[3]  = { 32, 8, 1 };
1341                 size_t globalThreads[3] = { src.cols, src.rows, 1 };
1342
1343                 openCLExecuteKernel(Context::getContext(), &imgproc_clahe, "transform", globalThreads, localThreads, args, -1, -1);
1344             }
1345         }
1346
1347         namespace
1348         {
1349             class CLAHE_Impl : public cv::CLAHE
1350             {
1351             public:
1352                 CLAHE_Impl(double clipLimit = 40.0, int tilesX = 8, int tilesY = 8);
1353
1354                 cv::AlgorithmInfo* info() const;
1355
1356                 void apply(cv::InputArray src, cv::OutputArray dst);
1357
1358                 void setClipLimit(double clipLimit);
1359                 double getClipLimit() const;
1360
1361                 void setTilesGridSize(cv::Size tileGridSize);
1362                 cv::Size getTilesGridSize() const;
1363
1364                 void collectGarbage();
1365
1366             private:
1367                 double clipLimit_;
1368                 int tilesX_;
1369                 int tilesY_;
1370
1371                 oclMat srcExt_;
1372                 oclMat lut_;
1373             };
1374
1375             CLAHE_Impl::CLAHE_Impl(double clipLimit, int tilesX, int tilesY) :
1376                 clipLimit_(clipLimit), tilesX_(tilesX), tilesY_(tilesY)
1377             {
1378             }
1379
1380             CV_INIT_ALGORITHM(CLAHE_Impl, "CLAHE_OCL",
1381                 obj.info()->addParam(obj, "clipLimit", obj.clipLimit_);
1382                 obj.info()->addParam(obj, "tilesX", obj.tilesX_);
1383                 obj.info()->addParam(obj, "tilesY", obj.tilesY_))
1384
1385             void CLAHE_Impl::apply(cv::InputArray src_raw, cv::OutputArray dst_raw)
1386             {
1387                 oclMat& src = getOclMatRef(src_raw);
1388                 oclMat& dst = getOclMatRef(dst_raw);
1389                 CV_Assert( src.type() == CV_8UC1 );
1390
1391                 dst.create( src.size(), src.type() );
1392
1393                 const int histSize = 256;
1394
1395                 ensureSizeIsEnough(tilesX_ * tilesY_, histSize, CV_8UC1, lut_);
1396
1397                 cv::Size tileSize;
1398                 oclMat srcForLut;
1399
1400                 if (src.cols % tilesX_ == 0 && src.rows % tilesY_ == 0)
1401                 {
1402                     tileSize = cv::Size(src.cols / tilesX_, src.rows / tilesY_);
1403                     srcForLut = src;
1404                 }
1405                 else
1406                 {
1407                     ocl::copyMakeBorder(src, srcExt_, 0, tilesY_ - (src.rows % tilesY_), 0,
1408                                             tilesX_ - (src.cols % tilesX_), BORDER_REFLECT_101, Scalar::all(0));
1409
1410                     tileSize = Size(srcExt_.cols / tilesX_, srcExt_.rows / tilesY_);
1411                     srcForLut = srcExt_;
1412                 }
1413
1414                 const int tileSizeTotal = tileSize.area();
1415                 const float lutScale = static_cast<float>(histSize - 1) / tileSizeTotal;
1416
1417                 int clipLimit = 0;
1418                 if (clipLimit_ > 0.0)
1419                 {
1420                     clipLimit = static_cast<int>(clipLimit_ * tileSizeTotal / histSize);
1421                     clipLimit = std::max(clipLimit, 1);
1422                 }
1423
1424                 clahe::calcLut(srcForLut, lut_, tilesX_, tilesY_, tileSize, clipLimit, lutScale);
1425                 clahe::transform(src, dst, lut_, tilesX_, tilesY_, tileSize);
1426             }
1427
1428             void CLAHE_Impl::setClipLimit(double clipLimit)
1429             {
1430                 clipLimit_ = clipLimit;
1431             }
1432
1433             double CLAHE_Impl::getClipLimit() const
1434             {
1435                 return clipLimit_;
1436             }
1437
1438             void CLAHE_Impl::setTilesGridSize(cv::Size tileGridSize)
1439             {
1440                 tilesX_ = tileGridSize.width;
1441                 tilesY_ = tileGridSize.height;
1442             }
1443
1444             cv::Size CLAHE_Impl::getTilesGridSize() const
1445             {
1446                 return cv::Size(tilesX_, tilesY_);
1447             }
1448
1449             void CLAHE_Impl::collectGarbage()
1450             {
1451                 srcExt_.release();
1452                 lut_.release();
1453             }
1454         }
1455
1456         cv::Ptr<cv::CLAHE> createCLAHE(double clipLimit, cv::Size tileGridSize)
1457         {
1458             return makePtr<CLAHE_Impl>(clipLimit, tileGridSize.width, tileGridSize.height);
1459         }
1460
1461         //////////////////////////////////bilateralFilter////////////////////////////////////////////////////
1462
1463         static void oclbilateralFilter_8u( const oclMat &src, oclMat &dst, int d,
1464                                double sigma_color, double sigma_space,
1465                                int borderType )
1466         {
1467             int cn = src.channels();
1468             int i, j, maxk, radius;
1469
1470             CV_Assert( (src.channels() == 1 || src.channels() == 3) &&
1471                        src.type() == dst.type() && src.size() == dst.size() &&
1472                        src.data != dst.data );
1473
1474             if ( sigma_color <= 0 )
1475                 sigma_color = 1;
1476             if ( sigma_space <= 0 )
1477                 sigma_space = 1;
1478
1479             double gauss_color_coeff = -0.5 / (sigma_color * sigma_color);
1480             double gauss_space_coeff = -0.5 / (sigma_space * sigma_space);
1481
1482             if ( d <= 0 )
1483                 radius = cvRound(sigma_space * 1.5);
1484             else
1485                 radius = d / 2;
1486             radius = MAX(radius, 1);
1487             d = radius * 2 + 1;
1488
1489             oclMat temp;
1490             copyMakeBorder( src, temp, radius, radius, radius, radius, borderType );
1491
1492             std::vector<float> _color_weight(cn * 256);
1493             std::vector<float> _space_weight(d * d);
1494             std::vector<int> _space_ofs(d * d);
1495             float *color_weight = &_color_weight[0];
1496             float *space_weight = &_space_weight[0];
1497             int *space_ofs = &_space_ofs[0];
1498
1499             int dst_step_in_pixel = dst.step / dst.elemSize();
1500             int dst_offset_in_pixel = dst.offset / dst.elemSize();
1501             int temp_step_in_pixel = temp.step / temp.elemSize();
1502
1503             // initialize color-related bilateral filter coefficients
1504             for( i = 0; i < 256 * cn; i++ )
1505                 color_weight[i] = (float)std::exp(i * i * gauss_color_coeff);
1506
1507             // initialize space-related bilateral filter coefficients
1508             for( i = -radius, maxk = 0; i <= radius; i++ )
1509                 for( j = -radius; j <= radius; j++ )
1510                 {
1511                     double r = std::sqrt((double)i * i + (double)j * j);
1512                     if ( r > radius )
1513                         continue;
1514                     space_weight[maxk] = (float)std::exp(r * r * gauss_space_coeff);
1515                     space_ofs[maxk++] = (int)(i * temp_step_in_pixel + j);
1516                 }
1517
1518             oclMat oclcolor_weight(1, cn * 256, CV_32FC1, color_weight);
1519             oclMat oclspace_weight(1, d * d, CV_32FC1, space_weight);
1520             oclMat oclspace_ofs(1, d * d, CV_32SC1, space_ofs);
1521
1522             String kernelName = "bilateral";
1523             size_t localThreads[3]  = { 16, 16, 1 };
1524             size_t globalThreads[3] = { dst.cols, dst.rows, 1 };
1525
1526             if ((dst.type() == CV_8UC1) && ((dst.offset & 3) == 0) && ((dst.cols & 3) == 0))
1527             {
1528                 kernelName = "bilateral2";
1529                 globalThreads[0] = dst.cols >> 2;
1530             }
1531
1532             std::vector<std::pair<size_t , const void *> > args;
1533             args.push_back( std::make_pair( sizeof(cl_mem), (void *)&dst.data ));
1534             args.push_back( std::make_pair( sizeof(cl_mem), (void *)&temp.data ));
1535             args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst.rows ));
1536             args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst.cols ));
1537             args.push_back( std::make_pair( sizeof(cl_int), (void *)&maxk ));
1538             args.push_back( std::make_pair( sizeof(cl_int), (void *)&radius ));
1539             args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst_step_in_pixel ));
1540             args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst_offset_in_pixel ));
1541             args.push_back( std::make_pair( sizeof(cl_int), (void *)&temp_step_in_pixel ));
1542             args.push_back( std::make_pair( sizeof(cl_int), (void *)&temp.rows ));
1543             args.push_back( std::make_pair( sizeof(cl_int), (void *)&temp.cols ));
1544             args.push_back( std::make_pair( sizeof(cl_mem), (void *)&oclcolor_weight.data ));
1545             args.push_back( std::make_pair( sizeof(cl_mem), (void *)&oclspace_weight.data ));
1546             args.push_back( std::make_pair( sizeof(cl_mem), (void *)&oclspace_ofs.data ));
1547
1548             openCLExecuteKernel(src.clCxt, &imgproc_bilateral, kernelName, globalThreads, localThreads, args, dst.oclchannels(), dst.depth());
1549         }
1550
1551         void bilateralFilter(const oclMat &src, oclMat &dst, int radius, double sigmaclr, double sigmaspc, int borderType)
1552         {
1553             dst.create( src.size(), src.type() );
1554             if ( src.depth() == CV_8U )
1555                 oclbilateralFilter_8u( src, dst, radius, sigmaclr, sigmaspc, borderType );
1556             else
1557                 CV_Error(Error::StsUnsupportedFormat, "Bilateral filtering is only implemented for CV_8U images");
1558         }
1559
1560     }
1561 }
1562 //////////////////////////////////mulSpectrums////////////////////////////////////////////////////
1563 void cv::ocl::mulSpectrums(const oclMat &a, const oclMat &b, oclMat &c, int /*flags*/, float scale, bool conjB)
1564 {
1565     CV_Assert(a.type() == CV_32FC2);
1566     CV_Assert(b.type() == CV_32FC2);
1567
1568     c.create(a.size(), CV_32FC2);
1569
1570     size_t lt[3]  = { 16, 16, 1 };
1571     size_t gt[3]  = { a.cols, a.rows, 1 };
1572
1573     String kernelName = conjB ? "mulAndScaleSpectrumsKernel_CONJ":"mulAndScaleSpectrumsKernel";
1574
1575     std::vector<std::pair<size_t , const void *> > args;
1576     args.push_back( std::make_pair( sizeof(cl_mem), (void *)&a.data ));
1577     args.push_back( std::make_pair( sizeof(cl_mem), (void *)&b.data ));
1578     args.push_back( std::make_pair( sizeof(cl_float), (void *)&scale));
1579     args.push_back( std::make_pair( sizeof(cl_mem), (void *)&c.data ));
1580     args.push_back( std::make_pair( sizeof(cl_int), (void *)&a.cols ));
1581     args.push_back( std::make_pair( sizeof(cl_int), (void *)&a.rows));
1582     args.push_back( std::make_pair( sizeof(cl_int), (void *)&a.step ));
1583
1584     Context *clCxt = Context::getContext();
1585     openCLExecuteKernel(clCxt, &imgproc_mulAndScaleSpectrums, kernelName, gt, lt, args, -1, -1);
1586 }
1587 //////////////////////////////////convolve////////////////////////////////////////////////////
1588 // ported from CUDA module
1589 void cv::ocl::ConvolveBuf::create(Size image_size, Size templ_size)
1590 {
1591     result_size = Size(image_size.width - templ_size.width + 1,
1592                        image_size.height - templ_size.height + 1);
1593
1594     block_size = user_block_size;
1595     if (user_block_size.width == 0 || user_block_size.height == 0)
1596         block_size = estimateBlockSize(result_size, templ_size);
1597
1598     dft_size.width  = 1 << int(ceil(std::log(block_size.width + templ_size.width - 1.) / std::log(2.)));
1599     dft_size.height = 1 << int(ceil(std::log(block_size.height + templ_size.height - 1.) / std::log(2.)));
1600
1601     // CUFFT has hard-coded kernels for power-of-2 sizes (up to 8192),
1602     // see CUDA Toolkit 4.1 CUFFT Library Programming Guide
1603     //if (dft_size.width > 8192)
1604     dft_size.width = getOptimalDFTSize(block_size.width + templ_size.width - 1.);
1605     //if (dft_size.height > 8192)
1606     dft_size.height = getOptimalDFTSize(block_size.height + templ_size.height - 1.);
1607
1608     // To avoid wasting time doing small DFTs
1609     dft_size.width = std::max(dft_size.width, 512);
1610     dft_size.height = std::max(dft_size.height, 512);
1611
1612     image_block.create(dft_size, CV_32F);
1613     templ_block.create(dft_size, CV_32F);
1614     result_data.create(dft_size, CV_32F);
1615
1616     //spect_len = dft_size.height * (dft_size.width / 2 + 1);
1617     image_spect.create(dft_size.height, dft_size.width / 2 + 1, CV_32FC2);
1618     templ_spect.create(dft_size.height, dft_size.width / 2 + 1, CV_32FC2);
1619     result_spect.create(dft_size.height, dft_size.width / 2 + 1, CV_32FC2);
1620
1621     // Use maximum result matrix block size for the estimated DFT block size
1622     block_size.width = std::min(dft_size.width - templ_size.width + 1, result_size.width);
1623     block_size.height = std::min(dft_size.height - templ_size.height + 1, result_size.height);
1624 }
1625
1626 Size cv::ocl::ConvolveBuf::estimateBlockSize(Size result_size, Size /*templ_size*/)
1627 {
1628     int width = (result_size.width + 2) / 3;
1629     int height = (result_size.height + 2) / 3;
1630     width = std::min(width, result_size.width);
1631     height = std::min(height, result_size.height);
1632     return Size(width, height);
1633 }
1634
1635 static void convolve_run_fft(const oclMat &image, const oclMat &templ, oclMat &result, bool ccorr, ConvolveBuf& buf)
1636 {
1637 #if defined HAVE_CLAMDFFT
1638     CV_Assert(image.type() == CV_32F);
1639     CV_Assert(templ.type() == CV_32F);
1640
1641     buf.create(image.size(), templ.size());
1642     result.create(buf.result_size, CV_32F);
1643
1644     Size& block_size = buf.block_size;
1645     Size& dft_size = buf.dft_size;
1646
1647     oclMat& image_block = buf.image_block;
1648     oclMat& templ_block = buf.templ_block;
1649     oclMat& result_data = buf.result_data;
1650
1651     oclMat& image_spect = buf.image_spect;
1652     oclMat& templ_spect = buf.templ_spect;
1653     oclMat& result_spect = buf.result_spect;
1654
1655     oclMat templ_roi = templ;
1656     copyMakeBorder(templ_roi, templ_block, 0, templ_block.rows - templ_roi.rows, 0,
1657                    templ_block.cols - templ_roi.cols, 0, Scalar());
1658
1659     cv::ocl::dft(templ_block, templ_spect, dft_size);
1660
1661     // Process all blocks of the result matrix
1662     for (int y = 0; y < result.rows; y += block_size.height)
1663     {
1664         for (int x = 0; x < result.cols; x += block_size.width)
1665         {
1666             Size image_roi_size(std::min(x + dft_size.width, image.cols) - x,
1667                                 std::min(y + dft_size.height, image.rows) - y);
1668             Rect roi0(x, y, image_roi_size.width, image_roi_size.height);
1669
1670             oclMat image_roi(image, roi0);
1671
1672             copyMakeBorder(image_roi, image_block, 0, image_block.rows - image_roi.rows,
1673                            0, image_block.cols - image_roi.cols, 0, Scalar());
1674
1675             cv::ocl::dft(image_block, image_spect, dft_size);
1676
1677             mulSpectrums(image_spect, templ_spect, result_spect, 0,
1678                                  1.f / dft_size.area(), ccorr);
1679
1680             cv::ocl::dft(result_spect, result_data, dft_size, cv::DFT_INVERSE | cv::DFT_REAL_OUTPUT);
1681
1682             Size result_roi_size(std::min(x + block_size.width, result.cols) - x,
1683                                  std::min(y + block_size.height, result.rows) - y);
1684
1685             Rect roi1(x, y, result_roi_size.width, result_roi_size.height);
1686             Rect roi2(0, 0, result_roi_size.width, result_roi_size.height);
1687
1688             oclMat result_roi(result, roi1);
1689             oclMat result_block(result_data, roi2);
1690
1691             result_block.copyTo(result_roi);
1692         }
1693     }
1694
1695 #else
1696     CV_Error(Error::OpenCLNoAMDBlasFft, "OpenCL DFT is not implemented");
1697 #define UNUSED(x) (void)(x);
1698     UNUSED(image) UNUSED(templ) UNUSED(result) UNUSED(ccorr) UNUSED(buf)
1699 #undef UNUSED
1700 #endif
1701 }
1702
1703 static void convolve_run(const oclMat &src, const oclMat &temp1, oclMat &dst, String kernelName, const cv::ocl::ProgramEntry* source)
1704 {
1705     CV_Assert(src.depth() == CV_32FC1);
1706     CV_Assert(temp1.depth() == CV_32F);
1707     CV_Assert(temp1.cols <= 17 && temp1.rows <= 17);
1708
1709     dst.create(src.size(), src.type());
1710
1711     CV_Assert(src.cols == dst.cols && src.rows == dst.rows);
1712     CV_Assert(src.type() == dst.type());
1713
1714     size_t localThreads[3]  = { 16, 16, 1 };
1715     size_t globalThreads[3] = { dst.cols, dst.rows, 1 };
1716
1717     int src_step = src.step / src.elemSize(), src_offset = src.offset / src.elemSize();
1718     int dst_step = dst.step / dst.elemSize(), dst_offset = dst.offset / dst.elemSize();
1719     int temp1_step = temp1.step / temp1.elemSize(), temp1_offset = temp1.offset / temp1.elemSize();
1720
1721     std::vector<std::pair<size_t , const void *> > args;
1722     args.push_back( std::make_pair( sizeof(cl_mem), (void *)&src.data ));
1723     args.push_back( std::make_pair( sizeof(cl_mem), (void *)&temp1.data ));
1724     args.push_back( std::make_pair( sizeof(cl_mem), (void *)&dst.data ));
1725     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src.rows ));
1726     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src.cols ));
1727     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src_step ));
1728     args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst_step ));
1729     args.push_back( std::make_pair( sizeof(cl_int), (void *)&temp1_step ));
1730     args.push_back( std::make_pair( sizeof(cl_int), (void *)&temp1.rows ));
1731     args.push_back( std::make_pair( sizeof(cl_int), (void *)&temp1.cols ));
1732     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src_offset ));
1733     args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst_offset ));
1734     args.push_back( std::make_pair( sizeof(cl_int), (void *)&temp1_offset ));
1735
1736     openCLExecuteKernel(src.clCxt, source, kernelName, globalThreads, localThreads, args, -1, dst.depth());
1737 }
1738
1739 void cv::ocl::convolve(const oclMat &x, const oclMat &t, oclMat &y, bool ccorr)
1740 {
1741     CV_Assert(x.depth() == CV_32F);
1742     CV_Assert(t.depth() == CV_32F);
1743     y.create(x.size(), x.type());
1744     String kernelName = "convolve";
1745     if(t.cols > 17 || t.rows > 17)
1746     {
1747         ConvolveBuf buf;
1748         convolve_run_fft(x, t, y, ccorr, buf);
1749     }
1750     else
1751     {
1752         CV_Assert(ccorr == false);
1753         convolve_run(x, t, y, kernelName, &imgproc_convolve);
1754     }
1755 }
1756 void cv::ocl::convolve(const oclMat &image, const oclMat &templ, oclMat &result, bool ccorr, ConvolveBuf& buf)
1757 {
1758     result.create(image.size(), image.type());
1759     convolve_run_fft(image, templ, result, ccorr, buf);
1760 }