Merge remote-tracking branch 'origin/2.4' into merge-2.4
[profile/ivi/opencv.git] / modules / ocl / src / arithm.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 //    Jiang Liyuan, jlyuan001.good@163.com
23 //    Rock Li, Rock.Li@amd.com
24 //    Zailong Wu, bullet@yeah.net
25 //    Peng Xiao, pengxiao@outlook.com
26 //
27 // Redistribution and use in source and binary forms, with or without modification,
28 // are permitted provided that the following conditions are met:
29 //
30 //   * Redistribution's of source code must retain the above copyright notice,
31 //     this list of conditions and the following disclaimer.
32 //
33 //   * Redistribution's in binary form must reproduce the above copyright notice,
34 //     this list of conditions and the following disclaimer in the documentation
35 //     and/or other materials provided with the distribution.
36 //
37 //   * The name of the copyright holders may not be used to endorse or promote products
38 //     derived from this software without specific prior written permission.
39 //
40 // This software is provided by the copyright holders and contributors "as is" and
41 // any express or implied warranties, including, but not limited to, the implied
42 // warranties of merchantability and fitness for a particular purpose are disclaimed.
43 // In no event shall the Intel Corporation or contributors be liable for any direct,
44 // indirect, incidental, special, exemplary, or consequential damages
45 // (including, but not limited to, procurement of substitute goods or services;
46 // loss of use, data, or profits; or business interruption) however caused
47 // and on any theory of liability, whether in contract, strict liability,
48 // or tort (including negligence or otherwise) arising in any way out of
49 // the use of this software, even if advised of the possibility of such damage.
50 //
51 //M*/
52
53 #include "precomp.hpp"
54 #include "opencl_kernels.hpp"
55
56 using namespace cv;
57 using namespace cv::ocl;
58
59 static std::vector<uchar> scalarToVector(const cv::Scalar & sc, int depth, int ocn, int cn)
60 {
61     CV_Assert(ocn == cn || (ocn == 4 && cn == 3));
62
63     static const int sizeMap[] = { sizeof(uchar), sizeof(char), sizeof(ushort),
64                                sizeof(short), sizeof(int), sizeof(float), sizeof(double) };
65
66     int elemSize1 = sizeMap[depth];
67     int bufSize = elemSize1 * ocn;
68     std::vector<uchar> _buf(bufSize);
69     uchar * buf = &_buf[0];
70     scalarToRawData(sc, buf, CV_MAKE_TYPE(depth, cn));
71     memset(buf + elemSize1 * cn, 0, (ocn - cn) * elemSize1);
72
73     return _buf;
74 }
75
76 //////////////////////////////////////////////////////////////////////////////
77 /////////////// add subtract multiply divide min max /////////////////////////
78 //////////////////////////////////////////////////////////////////////////////
79
80 enum { ADD = 0, SUB, MUL, DIV, ABS, ABS_DIFF, MIN, MAX };
81
82 static void arithmetic_run_generic(const oclMat &src1, const oclMat &src2, const Scalar & scalar, const oclMat & mask,
83                             oclMat &dst, int op_type, bool use_scalar = false)
84 {
85     Context *clCxt = src1.clCxt;
86     bool hasDouble = clCxt->supportsFeature(FEATURE_CL_DOUBLE);
87     if (!hasDouble && (src1.depth() == CV_64F || src2.depth() == CV_64F || dst.depth() == CV_64F))
88     {
89         CV_Error(Error::OpenCLDoubleNotSupported, "Selected device doesn't support double");
90         return;
91     }
92
93     CV_Assert(src2.empty() || (!src2.empty() && src1.type() == src2.type() && src1.size() == src2.size()));
94     CV_Assert(mask.empty() || (!mask.empty() && mask.type() == CV_8UC1 && mask.size() == src1.size()));
95     CV_Assert(op_type >= ADD && op_type <= MAX);
96
97     dst.create(src1.size(), src1.type());
98
99     int oclChannels = src1.oclchannels(), depth = src1.depth();
100     int src1step1 = src1.step / src1.elemSize(), src1offset1 = src1.offset / src1.elemSize();
101     int src2step1 = src2.step / src2.elemSize(), src2offset1 = src2.offset / src2.elemSize();
102     int maskstep1 = mask.step, maskoffset1 = mask.offset / mask.elemSize();
103     int dststep1 = dst.step / dst.elemSize(), dstoffset1 = dst.offset / dst.elemSize();
104     std::vector<uchar> m;
105
106     size_t localThreads[3]  = { 16, 16, 1 };
107     size_t globalThreads[3] = { dst.cols, dst.rows, 1 };
108
109     std::string kernelName = "arithm_binary_op";
110
111     const char * const typeMap[] = { "uchar", "char", "ushort", "short", "int", "float", "double" };
112     const char * const WTypeMap[] = { "short", "short", "int", "int", "int", "float", "double" };
113     const char * const funcMap[] = { "FUNC_ADD", "FUNC_SUB", "FUNC_MUL", "FUNC_DIV", "FUNC_ABS", "FUNC_ABS_DIFF", "FUNC_MIN", "FUNC_MAX" };
114     const char * const channelMap[] = { "", "", "2", "4", "4" };
115     bool haveScalar = use_scalar || src2.empty();
116
117     int WDepth = depth;
118     if (haveScalar)
119         WDepth = hasDouble && WDepth == CV_64F ? CV_64F : CV_32F;
120     if (op_type == DIV)
121         WDepth = hasDouble ? CV_64F : CV_32F;
122     else if (op_type == MUL)
123         WDepth = hasDouble && (depth == CV_32S || depth == CV_64F) ? CV_64F : CV_32F;
124
125     std::string buildOptions = format("-D T=%s%s -D WT=%s%s -D convertToT=convert_%s%s%s -D %s "
126                                       "-D convertToWT=convert_%s%s",
127                                       typeMap[depth], channelMap[oclChannels],
128                                       WTypeMap[WDepth], channelMap[oclChannels],
129                                       typeMap[depth], channelMap[oclChannels], (depth >= CV_32F ? "" : (depth == CV_32S ? "_rte" : "_sat_rte")),
130                                       funcMap[op_type], WTypeMap[WDepth], channelMap[oclChannels]);
131
132     std::vector<std::pair<size_t , const void *> > args;
133     args.push_back( std::make_pair( sizeof(cl_mem), (void *)&src1.data ));
134     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src1step1 ));
135     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src1offset1 ));
136
137     if (!src2.empty())
138     {
139         args.push_back( std::make_pair( sizeof(cl_mem), (void *)&src2.data ));
140         args.push_back( std::make_pair( sizeof(cl_int), (void *)&src2step1 ));
141         args.push_back( std::make_pair( sizeof(cl_int), (void *)&src2offset1 ));
142
143         kernelName += "_mat";
144
145         if (haveScalar)
146             buildOptions += " -D HAVE_SCALAR";
147     }
148
149     if (haveScalar)
150     {
151         const int WDepthMap[] = { CV_16S, CV_16S, CV_32S, CV_32S, CV_32S, CV_32F, CV_64F };
152         m = scalarToVector(scalar, WDepthMap[WDepth], oclChannels, src1.channels());
153
154         args.push_back( std::make_pair( m.size(), (void *)&m[0]));
155
156         kernelName += "_scalar";
157     }
158
159     if (!mask.empty())
160     {
161         args.push_back( std::make_pair( sizeof(cl_mem), (void *)&mask.data ));
162         args.push_back( std::make_pair( sizeof(cl_int), (void *)&maskstep1 ));
163         args.push_back( std::make_pair( sizeof(cl_int), (void *)&maskoffset1 ));
164
165         kernelName += "_mask";
166     }
167
168     args.push_back( std::make_pair( sizeof(cl_mem), (void *)&dst.data ));
169     args.push_back( std::make_pair( sizeof(cl_int), (void *)&dststep1 ));
170     args.push_back( std::make_pair( sizeof(cl_int), (void *)&dstoffset1 ));
171
172     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src1.cols ));
173     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src1.rows ));
174
175     openCLExecuteKernel(clCxt, mask.empty() ?
176                             (!src2.empty() ? &arithm_add : &arithm_add_scalar) :
177                             (!src2.empty() ? &arithm_add_mask : &arithm_add_scalar_mask),
178                         kernelName, globalThreads, localThreads,
179                         args, -1, -1, buildOptions.c_str());
180 }
181
182 void cv::ocl::add(const oclMat &src1, const oclMat &src2, oclMat &dst, const oclMat &mask)
183 {
184     arithmetic_run_generic(src1, src2, Scalar(), mask, dst, ADD);
185 }
186
187 void cv::ocl::add(const oclMat &src1, const Scalar &src2, oclMat &dst, const oclMat &mask)
188 {
189     arithmetic_run_generic(src1, oclMat(), src2, mask, dst, ADD);
190 }
191
192 void cv::ocl::subtract(const oclMat &src1, const oclMat &src2, oclMat &dst, const oclMat &mask)
193 {
194     arithmetic_run_generic(src1, src2, Scalar(), mask, dst, SUB);
195 }
196
197 void cv::ocl::subtract(const oclMat &src1, const Scalar &src2, oclMat &dst, const oclMat &mask)
198 {
199     arithmetic_run_generic(src1, oclMat(), src2, mask, dst, SUB);
200 }
201
202 void cv::ocl::multiply(const oclMat &src1, const oclMat &src2, oclMat &dst, double scalar)
203 {
204     const bool use_scalar = !(std::abs(scalar - 1.0) < std::numeric_limits<double>::epsilon());
205     arithmetic_run_generic(src1, src2, Scalar::all(scalar), oclMat(), dst, MUL, use_scalar);
206 }
207
208 void cv::ocl::multiply(double scalar, const oclMat &src, oclMat &dst)
209 {
210     arithmetic_run_generic(src, oclMat(), Scalar::all(scalar), oclMat(), dst, MUL);
211 }
212
213 void cv::ocl::divide(const oclMat &src1, const oclMat &src2, oclMat &dst, double scalar)
214 {
215     const bool use_scalar = !(std::abs(scalar - 1.0) < std::numeric_limits<double>::epsilon());
216     arithmetic_run_generic(src1, src2, Scalar::all(scalar), oclMat(), dst, DIV, use_scalar);
217 }
218
219 void cv::ocl::divide(double scalar, const oclMat &src, oclMat &dst)
220 {
221     arithmetic_run_generic(src, oclMat(), Scalar::all(scalar), oclMat(), dst, DIV);
222 }
223
224 void cv::ocl::min(const oclMat &src1, const oclMat &src2, oclMat &dst)
225 {
226     arithmetic_run_generic(src1, src2, Scalar::all(0), oclMat(), dst, MIN);
227 }
228
229 void cv::ocl::max(const oclMat &src1, const oclMat &src2, oclMat &dst)
230 {
231     arithmetic_run_generic(src1, src2, Scalar::all(0), oclMat(), dst, MAX);
232 }
233
234 //////////////////////////////////////////////////////////////////////////////
235 /////////////////////////////Abs, Absdiff ////////////////////////////////////
236 //////////////////////////////////////////////////////////////////////////////
237
238 void cv::ocl::abs(const oclMat &src, oclMat &dst)
239 {
240     // explicitly uses use_scalar (even if zero) so that the correct kernel is used
241     arithmetic_run_generic(src, oclMat(), Scalar(), oclMat(), dst, ABS, true);
242 }
243
244 void cv::ocl::absdiff(const oclMat &src1, const oclMat &src2, oclMat &dst)
245 {
246     arithmetic_run_generic(src1, src2, Scalar(), oclMat(), dst, ABS_DIFF);
247 }
248
249 void cv::ocl::absdiff(const oclMat &src1, const Scalar &src2, oclMat &dst)
250 {
251     arithmetic_run_generic(src1, oclMat(), src2, oclMat(), dst, ABS_DIFF);
252 }
253
254 //////////////////////////////////////////////////////////////////////////////
255 /////////////////////////////////  compare ///////////////////////////////////
256 //////////////////////////////////////////////////////////////////////////////
257
258 static void compare_run(const oclMat &src1, const oclMat &src2, oclMat &dst, int cmpOp,
259                         String kernelName, const cv::ocl::ProgramEntry* source)
260 {
261     dst.create(src1.size(), CV_8UC1);
262
263     int depth = src1.depth();
264     size_t localThreads[3]  = { 64, 4, 1 };
265     size_t globalThreads[3] = { dst.cols, dst.rows, 1 };
266
267     int src1step1 = src1.step1(), src1offset1 = src1.offset / src1.elemSize1();
268     int src2step1 = src2.step1(), src2offset1 = src2.offset / src2.elemSize1();
269     int dststep1 = dst.step1(), dstoffset1 = dst.offset / dst.elemSize1();
270
271     const char * const typeMap[] = { "uchar", "char", "ushort", "short", "int", "float", "double" };
272     const char * operationMap[] = { "==", ">", ">=", "<", "<=", "!=" };
273     std::string buildOptions = format("-D T=%s -D Operation=%s", typeMap[depth], operationMap[cmpOp]);
274
275     std::vector<std::pair<size_t , const void *> > args;
276     args.push_back( std::make_pair( sizeof(cl_mem), (void *)&src1.data ));
277     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src1step1 ));
278     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src1offset1 ));
279     args.push_back( std::make_pair( sizeof(cl_mem), (void *)&src2.data ));
280     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src2step1 ));
281     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src2offset1 ));
282     args.push_back( std::make_pair( sizeof(cl_mem), (void *)&dst.data ));
283     args.push_back( std::make_pair( sizeof(cl_int), (void *)&dststep1 ));
284     args.push_back( std::make_pair( sizeof(cl_int), (void *)&dstoffset1 ));
285     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src1.cols ));
286     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src1.rows ));
287
288     openCLExecuteKernel(src1.clCxt, source, kernelName, globalThreads, localThreads,
289                         args, -1, -1, buildOptions.c_str());
290 }
291
292 void cv::ocl::compare(const oclMat &src1, const oclMat &src2, oclMat &dst , int cmpOp)
293 {
294     if (!src1.clCxt->supportsFeature(FEATURE_CL_DOUBLE) && src1.depth() == CV_64F)
295     {
296         CV_Error(Error::OpenCLDoubleNotSupported, "Selected device doesn't support double");
297         return;
298     }
299
300     CV_Assert(src1.type() == src2.type() && src1.channels() == 1);
301     CV_Assert(cmpOp >= CMP_EQ && cmpOp <= CMP_NE);
302
303     compare_run(src1, src2, dst, cmpOp, "arithm_compare", &arithm_compare);
304 }
305
306 //////////////////////////////////////////////////////////////////////////////
307 ////////////////////////////////// sum  //////////////////////////////////////
308 //////////////////////////////////////////////////////////////////////////////
309
310 enum { SUM = 0, ABS_SUM, SQR_SUM };
311
312 static void arithmetic_sum_buffer_run(const oclMat &src, cl_mem &dst, int groupnum, int type, int ddepth)
313 {
314     int ochannels = src.oclchannels();
315     int all_cols = src.step / src.elemSize();
316     int pre_cols = (src.offset % src.step) / src.elemSize();
317     int sec_cols = all_cols - (src.offset % src.step + src.cols * src.elemSize() - 1) / src.elemSize() - 1;
318     int invalid_cols = pre_cols + sec_cols;
319     int cols = all_cols - invalid_cols , elemnum = cols * src.rows;;
320     int offset = src.offset / src.elemSize();
321
322     const char * const typeMap[] = { "uchar", "char", "ushort", "short", "int", "float", "double" };
323     const char * const funcMap[] = { "FUNC_SUM", "FUNC_ABS_SUM", "FUNC_SQR_SUM" };
324     const char * const channelMap[] = { " ", " ", "2", "4", "4" };
325     String buildOptions = format("-D srcT=%s%s -D dstT=%s%s -D convertToDstT=convert_%s%s -D %s",
326                                  typeMap[src.depth()], channelMap[ochannels],
327                                  typeMap[ddepth], channelMap[ochannels],
328                                  typeMap[ddepth], channelMap[ochannels],
329                                  funcMap[type]);
330
331     std::vector<std::pair<size_t , const void *> > args;
332     args.push_back( std::make_pair( sizeof(cl_int) , (void *)&cols ));
333     args.push_back( std::make_pair( sizeof(cl_int) , (void *)&invalid_cols ));
334     args.push_back( std::make_pair( sizeof(cl_int) , (void *)&offset));
335     args.push_back( std::make_pair( sizeof(cl_int) , (void *)&elemnum));
336     args.push_back( std::make_pair( sizeof(cl_int) , (void *)&groupnum));
337     args.push_back( std::make_pair( sizeof(cl_mem) , (void *)&src.data));
338     args.push_back( std::make_pair( sizeof(cl_mem) , (void *)&dst ));
339     size_t globalThreads[3] = { groupnum * 256, 1, 1 };
340     size_t localThreads[3] = { 256, 1, 1 };
341
342     openCLExecuteKernel(src.clCxt, &arithm_sum, "arithm_op_sum", globalThreads, localThreads,
343                         args, -1, -1, buildOptions.c_str());
344 }
345
346 template <typename T>
347 Scalar arithmetic_sum(const oclMat &src, int type, int ddepth)
348 {
349     CV_Assert(src.step % src.elemSize() == 0);
350
351     size_t groupnum = src.clCxt->getDeviceInfo().maxComputeUnits;
352     CV_Assert(groupnum != 0);
353
354     int dbsize = groupnum * src.oclchannels();
355     Context *clCxt = src.clCxt;
356
357     AutoBuffer<T> _buf(dbsize);
358     T *p = (T*)_buf;
359     memset(p, 0, dbsize * sizeof(T));
360
361     cl_mem dstBuffer = openCLCreateBuffer(clCxt, CL_MEM_WRITE_ONLY, dbsize * sizeof(T));
362     arithmetic_sum_buffer_run(src, dstBuffer, groupnum, type, ddepth);
363     openCLReadBuffer(clCxt, dstBuffer, (void *)p, dbsize * sizeof(T));
364     openCLFree(dstBuffer);
365
366     Scalar s = Scalar::all(0.0);
367     for (int i = 0; i < dbsize;)
368          for (int j = 0; j < src.oclchannels(); j++, i++)
369             s.val[j] += p[i];
370
371     return s;
372 }
373
374 typedef Scalar (*sumFunc)(const oclMat &src, int type, int ddepth);
375
376 Scalar cv::ocl::sum(const oclMat &src)
377 {
378     if (!src.clCxt->supportsFeature(FEATURE_CL_DOUBLE) && src.depth() == CV_64F)
379     {
380         CV_Error(Error::OpenCLDoubleNotSupported, "Selected device doesn't support double");
381         return Scalar::all(0);
382     }
383     static sumFunc functab[3] =
384     {
385         arithmetic_sum<int>,
386         arithmetic_sum<float>,
387         arithmetic_sum<double>
388     };
389
390     int ddepth = std::max(src.depth(), CV_32S);
391     sumFunc func = functab[ddepth - CV_32S];
392     return func(src, SUM, ddepth);
393 }
394
395 Scalar cv::ocl::absSum(const oclMat &src)
396 {
397     if (!src.clCxt->supportsFeature(FEATURE_CL_DOUBLE) && src.depth() == CV_64F)
398     {
399         CV_Error(Error::OpenCLDoubleNotSupported, "Selected device doesn't support double");
400         return cv::Scalar::all(0);
401     }
402
403     static sumFunc functab[3] =
404     {
405         arithmetic_sum<int>,
406         arithmetic_sum<float>,
407         arithmetic_sum<double>
408     };
409
410     int ddepth = std::max(src.depth(), CV_32S);
411     sumFunc func = functab[ddepth - CV_32S];
412     return func(src, ABS_SUM, ddepth);
413 }
414
415 Scalar cv::ocl::sqrSum(const oclMat &src)
416 {
417     if (!src.clCxt->supportsFeature(FEATURE_CL_DOUBLE) && src.depth() == CV_64F)
418     {
419         CV_Error(Error::OpenCLDoubleNotSupported, "Selected device doesn't support double");
420         return cv::Scalar::all(0);
421     }
422     static sumFunc functab[3] =
423     {
424         arithmetic_sum<int>,
425         arithmetic_sum<float>,
426         arithmetic_sum<double>
427     };
428
429     int ddepth = std::max(src.depth(), CV_32S);
430     sumFunc func = functab[ddepth - CV_32S];
431     return func(src, SQR_SUM, ddepth);
432 }
433
434 //////////////////////////////////////////////////////////////////////////////
435 //////////////////////////////// meanStdDev //////////////////////////////////
436 //////////////////////////////////////////////////////////////////////////////
437
438 void cv::ocl::meanStdDev(const oclMat &src, Scalar &mean, Scalar &stddev)
439 {
440     if (src.depth() == CV_64F && !src.clCxt->supportsFeature(FEATURE_CL_DOUBLE))
441     {
442         CV_Error(Error::OpenCLDoubleNotSupported, "Selected device doesn't support double");
443         return;
444     }
445
446     double total = 1.0 / src.size().area();
447
448     mean = sum(src);
449     stddev = sqrSum(src);
450
451     for (int i = 0; i < 4; ++i)
452     {
453         mean[i] *= total;
454         stddev[i] = std::sqrt(std::max(stddev[i] * total - mean.val[i] * mean.val[i] , 0.));
455     }
456 }
457
458 //////////////////////////////////////////////////////////////////////////////
459 //////////////////////////////////// minMax  /////////////////////////////////
460 //////////////////////////////////////////////////////////////////////////////
461
462 template <typename T, typename WT>
463 static void arithmetic_minMax_run(const oclMat &src, const oclMat & mask, cl_mem &dst, int groupnum, String kernelName)
464 {
465     int all_cols = src.step / src.elemSize();
466     int pre_cols = (src.offset % src.step) / src.elemSize();
467     int sec_cols = all_cols - (src.offset % src.step + src.cols * src.elemSize() - 1) / src.elemSize() - 1;
468     int invalid_cols = pre_cols + sec_cols;
469     int cols = all_cols - invalid_cols , elemnum = cols * src.rows;
470     int offset = src.offset / src.elemSize();
471
472     const char * const typeMap[] = { "uchar", "char", "ushort", "short", "int", "float", "double" };
473     const char * const channelMap[] = { " ", " ", "2", "4", "4" };
474
475     std::ostringstream stream;
476     stream << "-D T=" << typeMap[src.depth()] << channelMap[src.channels()];
477     if (std::numeric_limits<T>::is_integer)
478     {
479         stream << " -D MAX_VAL=" << (WT)std::numeric_limits<T>::max();
480         stream << " -D MIN_VAL=" << (WT)std::numeric_limits<T>::min();
481     }
482     else
483         stream << " -D DEPTH_" << src.depth();
484     std::string buildOptions = stream.str();
485
486     std::vector<std::pair<size_t , const void *> > args;
487     args.push_back( std::make_pair( sizeof(cl_mem) , (void *)&src.data));
488     args.push_back( std::make_pair( sizeof(cl_mem) , (void *)&dst ));
489     args.push_back( std::make_pair( sizeof(cl_int) , (void *)&cols ));
490     args.push_back( std::make_pair( sizeof(cl_int) , (void *)&invalid_cols ));
491     args.push_back( std::make_pair( sizeof(cl_int) , (void *)&offset));
492     args.push_back( std::make_pair( sizeof(cl_int) , (void *)&elemnum));
493     args.push_back( std::make_pair( sizeof(cl_int) , (void *)&groupnum));
494
495     int minvalid_cols = 0, moffset = 0;
496     if (!mask.empty())
497     {
498         int mall_cols = mask.step / mask.elemSize();
499         int mpre_cols = (mask.offset % mask.step) / mask.elemSize();
500         int msec_cols = mall_cols - (mask.offset % mask.step + mask.cols * mask.elemSize() - 1) / mask.elemSize() - 1;
501         minvalid_cols = mpre_cols + msec_cols;
502         moffset = mask.offset / mask.elemSize();
503
504         args.push_back( std::make_pair( sizeof(cl_mem) , (void *)&mask.data ));
505         args.push_back( std::make_pair( sizeof(cl_int) , (void *)&minvalid_cols ));
506         args.push_back( std::make_pair( sizeof(cl_int) , (void *)&moffset ));
507
508         kernelName = kernelName + "_mask";
509     }
510
511     size_t globalThreads[3] = {groupnum * 256, 1, 1};
512     size_t localThreads[3] = {256, 1, 1};
513
514     openCLExecuteKernel(src.clCxt, &arithm_minMax, kernelName, globalThreads, localThreads,
515                         args, -1, -1, buildOptions.c_str());
516 }
517
518 template <typename T, typename WT>
519 void arithmetic_minMax(const oclMat &src, double *minVal, double *maxVal, const oclMat &mask)
520 {
521     size_t groupnum = src.clCxt->getDeviceInfo().maxComputeUnits;
522     CV_Assert(groupnum != 0);
523
524     int dbsize = groupnum * 2 * src.elemSize();
525     oclMat buf;
526     ensureSizeIsEnough(1, dbsize, CV_8UC1, buf);
527
528     cl_mem buf_data = reinterpret_cast<cl_mem>(buf.data);
529     arithmetic_minMax_run<T, WT>(src, mask, buf_data, groupnum, "arithm_op_minMax");
530
531     Mat matbuf = Mat(buf);
532     T *p = matbuf.ptr<T>();
533     if (minVal != NULL)
534     {
535         *minVal = std::numeric_limits<double>::max();
536         for (int i = 0, end = src.oclchannels() * (int)groupnum; i < end; i++)
537             *minVal = *minVal < p[i] ? *minVal : p[i];
538     }
539     if (maxVal != NULL)
540     {
541         *maxVal = -std::numeric_limits<double>::max();
542         for (int i = src.oclchannels() * (int)groupnum, end = i << 1; i < end; i++)
543             *maxVal = *maxVal > p[i] ? *maxVal : p[i];
544     }
545 }
546
547 typedef void (*minMaxFunc)(const oclMat &src, double *minVal, double *maxVal, const oclMat &mask);
548
549 void cv::ocl::minMax(const oclMat &src, double *minVal, double *maxVal, const oclMat &mask)
550 {
551     CV_Assert(src.channels() == 1);
552     CV_Assert(src.size() == mask.size() || mask.empty());
553     CV_Assert(src.step % src.elemSize() == 0);
554
555     if (minVal == NULL && maxVal == NULL)
556         return;
557
558     if (!src.clCxt->supportsFeature(FEATURE_CL_DOUBLE) && src.depth() == CV_64F)
559     {
560         CV_Error(Error::OpenCLDoubleNotSupported, "Selected device doesn't support double");
561         return;
562     }
563
564     static minMaxFunc functab[] =
565     {
566         arithmetic_minMax<uchar, int>,
567         arithmetic_minMax<char, int>,
568         arithmetic_minMax<ushort, int>,
569         arithmetic_minMax<short, int>,
570         arithmetic_minMax<int, int>,
571         arithmetic_minMax<float, float>,
572         arithmetic_minMax<double, double>,
573         0
574     };
575
576     minMaxFunc func = functab[src.depth()];
577     CV_Assert(func != 0);
578
579     func(src, minVal, maxVal, mask);
580 }
581
582 //////////////////////////////////////////////////////////////////////////////
583 /////////////////////////////////// norm /////////////////////////////////////
584 //////////////////////////////////////////////////////////////////////////////
585
586 double cv::ocl::norm(const oclMat &src1, int normType)
587 {
588     CV_Assert((normType & NORM_RELATIVE) == 0);
589     return norm(src1, oclMat(), normType);
590 }
591
592 static void arithm_absdiff_nonsaturate_run(const oclMat & src1, const oclMat & src2, oclMat & diff, int ntype)
593 {
594     Context *clCxt = src1.clCxt;
595     if (!clCxt->supportsFeature(FEATURE_CL_DOUBLE) && src1.depth() == CV_64F)
596     {
597         CV_Error(Error::OpenCLDoubleNotSupported, "Selected device doesn't support double");
598         return;
599     }
600     CV_Assert(src1.step % src1.elemSize() == 0 && (src2.empty() || src2.step % src2.elemSize() == 0));
601
602     int ddepth = std::max(src1.depth(), CV_32S);
603     if (ntype == NORM_L2)
604         ddepth = std::max<int>(CV_32F, ddepth);
605
606     diff.create(src1.size(), CV_MAKE_TYPE(ddepth, src1.channels()));
607     CV_Assert(diff.step % diff.elemSize() == 0);
608
609     int oclChannels = src1.oclchannels(), sdepth = src1.depth();
610     int src1step1 = src1.step / src1.elemSize(), src1offset1 = src1.offset / src1.elemSize();
611     int src2step1 = src2.step / src2.elemSize(), src2offset1 = src2.offset / src2.elemSize();
612     int diffstep1 = diff.step / diff.elemSize(), diffoffset1 = diff.offset / diff.elemSize();
613
614     String kernelName = "arithm_absdiff_nonsaturate";
615     size_t localThreads[3]  = { 16, 16, 1 };
616     size_t globalThreads[3] = { diff.cols, diff.rows, 1 };
617
618     const char * const typeMap[] = { "uchar", "char", "ushort", "short", "int", "float", "double" };
619     const char * const channelMap[] = { "", "", "2", "4", "4" };
620
621     std::string buildOptions = format("-D srcT=%s%s -D dstT=%s%s -D convertToDstT=convert_%s%s",
622                                       typeMap[sdepth], channelMap[oclChannels],
623                                       typeMap[ddepth], channelMap[oclChannels],
624                                       typeMap[ddepth], channelMap[oclChannels]);
625
626     std::vector<std::pair<size_t , const void *> > args;
627     args.push_back( std::make_pair( sizeof(cl_mem), (void *)&src1.data ));
628     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src1step1 ));
629     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src1offset1 ));
630
631     if (!src2.empty())
632     {
633         args.push_back( std::make_pair( sizeof(cl_mem), (void *)&src2.data ));
634         args.push_back( std::make_pair( sizeof(cl_int), (void *)&src2step1 ));
635         args.push_back( std::make_pair( sizeof(cl_int), (void *)&src2offset1 ));
636
637         kernelName = kernelName + "_binary";
638     }
639
640     args.push_back( std::make_pair( sizeof(cl_mem), (void *)&diff.data ));
641     args.push_back( std::make_pair( sizeof(cl_int), (void *)&diffstep1 ));
642     args.push_back( std::make_pair( sizeof(cl_int), (void *)&diffoffset1 ));
643
644     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src1.cols ));
645     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src1.rows ));
646
647     openCLExecuteKernel(clCxt, &arithm_absdiff_nonsaturate,
648                         kernelName, globalThreads, localThreads,
649                         args, -1, -1, buildOptions.c_str());
650 }
651
652 double cv::ocl::norm(const oclMat &src1, const oclMat &src2, int normType)
653 {
654     if (!src1.clCxt->supportsFeature(FEATURE_CL_DOUBLE) && src1.depth() == CV_64F)
655     {
656         CV_Error(Error::OpenCLDoubleNotSupported, "Selected device doesn't support double");
657         return -1;
658     }
659     CV_Assert(src2.empty() || (src1.type() == src2.type() && src1.size() == src2.size()));
660
661     bool isRelative = (normType & NORM_RELATIVE) != 0;
662     normType &= NORM_TYPE_MASK;
663     CV_Assert(normType == NORM_INF || normType == NORM_L1 || normType == NORM_L2);
664
665     Scalar s;
666     int cn = src1.channels();
667     double r = 0;
668     oclMat diff;
669
670     arithm_absdiff_nonsaturate_run(src1, src2, diff, normType);
671
672     switch (normType)
673     {
674     case NORM_INF:
675         diff = diff.reshape(1);
676         minMax(diff, NULL, &r);
677         break;
678     case NORM_L1:
679         s = sum(diff);
680         for (int i = 0; i < cn; ++i)
681             r += s[i];
682         break;
683     case NORM_L2:
684         s = sqrSum(diff);
685         for (int i = 0; i < cn; ++i)
686             r += s[i];
687         r = std::sqrt(r);
688         break;
689     }
690     if (isRelative)
691         r = r / (norm(src2, normType) + DBL_EPSILON);
692
693     return r;
694 }
695
696 //////////////////////////////////////////////////////////////////////////////
697 ////////////////////////////////// flip //////////////////////////////////////
698 //////////////////////////////////////////////////////////////////////////////
699
700 enum { FLIP_COLS = 1 << 0, FLIP_ROWS = 1 << 1, FLIP_BOTH = FLIP_ROWS | FLIP_COLS };
701
702 static void arithmetic_flip_run(const oclMat &src, oclMat &dst, String kernelName, int flipType)
703 {
704     int cols = dst.cols, rows = dst.rows;
705     if ((cols == 1 && flipType == FLIP_COLS) ||
706             (rows == 1 && flipType == FLIP_ROWS) ||
707             (rows == 1 && cols == 1 && flipType == FLIP_BOTH))
708     {
709         src.copyTo(dst);
710         return;
711     }
712
713     cols = flipType == FLIP_COLS ? divUp(cols, 2) : cols;
714     rows = flipType & FLIP_ROWS ? divUp(rows, 2) : rows;
715
716     const char * const channelMap[] = { "", "", "2", "4", "4" };
717     const char * const typeMap[] = { "uchar", "char", "ushort", "short", "int", "float", "double" };
718     std::string buildOptions = format("-D T=%s%s", typeMap[dst.depth()], channelMap[dst.oclchannels()]);
719
720     size_t localThreads[3]  = { 64, 4, 1 };
721     size_t globalThreads[3] = { cols, rows, 1 };
722
723     int elemSize = src.elemSize();
724     int src_step = src.step / elemSize, src_offset = src.offset / elemSize;
725     int dst_step = dst.step / elemSize, dst_offset = dst.offset / elemSize;
726
727     std::vector<std::pair<size_t , const void *> > args;
728     args.push_back( std::make_pair( sizeof(cl_mem), (void *)&src.data ));
729     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src_step ));
730     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src_offset ));
731     args.push_back( std::make_pair( sizeof(cl_mem), (void *)&dst.data ));
732     args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst_step ));
733     args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst_offset ));
734     args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst.rows ));
735     args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst.cols ));
736     args.push_back( std::make_pair( sizeof(cl_int), (void *)&rows ));
737     args.push_back( std::make_pair( sizeof(cl_int), (void *)&cols ));
738
739     openCLExecuteKernel(src.clCxt, &arithm_flip, kernelName, globalThreads, localThreads, args,
740                         -1, -1, buildOptions.c_str());
741 }
742
743 void cv::ocl::flip(const oclMat &src, oclMat &dst, int flipCode)
744 {
745     if (!src.clCxt->supportsFeature(FEATURE_CL_DOUBLE) && src.depth() == CV_64F)
746     {
747         CV_Error(Error::OpenCLDoubleNotSupported, "Selected device doesn't support double");
748         return;
749     }
750
751     dst.create(src.size(), src.type());
752
753     if (flipCode == 0)
754         arithmetic_flip_run(src, dst, "arithm_flip_rows", FLIP_ROWS);
755     else if (flipCode > 0)
756         arithmetic_flip_run(src, dst, "arithm_flip_cols", FLIP_COLS);
757     else
758         arithmetic_flip_run(src, dst, "arithm_flip_rows_cols", FLIP_BOTH);
759 }
760
761 //////////////////////////////////////////////////////////////////////////////
762 ////////////////////////////////// LUT  //////////////////////////////////////
763 //////////////////////////////////////////////////////////////////////////////
764
765 static void arithmetic_lut_run(const oclMat &src, const oclMat &lut, oclMat &dst, String kernelName)
766 {
767     int sdepth = src.depth();
768     int src_step1 = src.step1(), dst_step1 = dst.step1();
769     int src_offset1 = src.offset / src.elemSize1(), dst_offset1 = dst.offset / dst.elemSize1();
770     int lut_offset1 = lut.offset / lut.elemSize1() + (sdepth == CV_8U ? 0 : 128) * lut.channels();
771     int cols1 = src.cols * src.oclchannels();
772
773     size_t localSize[] = { 16, 16, 1 };
774     size_t globalSize[] = { lut.channels() == 1 ? cols1 : src.cols, src.rows, 1 };
775
776     const char * const typeMap[] = { "uchar", "char", "ushort", "short", "int", "float", "double" };
777     std::string buildOptions = format("-D srcT=%s -D dstT=%s", typeMap[sdepth], typeMap[dst.depth()]);
778
779     std::vector<std::pair<size_t , const void *> > args;
780     args.push_back( std::make_pair( sizeof(cl_mem), (void *)&src.data ));
781     args.push_back( std::make_pair( sizeof(cl_mem), (void *)&lut.data ));
782     args.push_back( std::make_pair( sizeof(cl_mem), (void *)&dst.data ));
783     args.push_back( std::make_pair( sizeof(cl_int), (void *)&cols1));
784     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src.rows ));
785     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src_offset1 ));
786     args.push_back( std::make_pair( sizeof(cl_int), (void *)&lut_offset1 ));
787     args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst_offset1 ));
788     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src_step1 ));
789     args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst_step1 ));
790
791     openCLExecuteKernel(src.clCxt, &arithm_LUT, kernelName, globalSize, localSize,
792                         args, lut.oclchannels(), -1, buildOptions.c_str());
793 }
794
795 void cv::ocl::LUT(const oclMat &src, const oclMat &lut, oclMat &dst)
796 {
797     if (!lut.clCxt->supportsFeature(FEATURE_CL_DOUBLE) && lut.depth() == CV_64F)
798     {
799         CV_Error(Error::OpenCLDoubleNotSupported, "Selected device doesn't support double");
800         return;
801     }
802
803     int cn = src.channels(), depth = src.depth();
804
805     CV_Assert(depth == CV_8U || depth == CV_8S);
806     CV_Assert(lut.channels() == 1 || lut.channels() == src.channels());
807     CV_Assert(lut.rows == 1 && lut.cols == 256);
808
809     dst.create(src.size(), CV_MAKETYPE(lut.depth(), cn));
810     arithmetic_lut_run(src, lut, dst, "LUT");
811 }
812
813 //////////////////////////////////////////////////////////////////////////////
814 //////////////////////////////// exp log /////////////////////////////////////
815 //////////////////////////////////////////////////////////////////////////////
816
817 static void arithmetic_exp_log_run(const oclMat &src, oclMat &dst, String kernelName, const cv::ocl::ProgramEntry* source)
818 {
819     Context  *clCxt = src.clCxt;
820     if (!clCxt->supportsFeature(FEATURE_CL_DOUBLE) && src.depth() == CV_64F)
821     {
822         CV_Error(Error::OpenCLDoubleNotSupported, "Selected device doesn't support double");
823         return;
824     }
825
826     CV_Assert( src.depth() == CV_32F || src.depth() == CV_64F);
827     dst.create(src.size(), src.type());
828
829     int ddepth = dst.depth();
830     int cols1 = src.cols * src.oclchannels();
831     int srcoffset1 = src.offset / src.elemSize1(), dstoffset1 = dst.offset / dst.elemSize1();
832     int srcstep1 = src.step1(), dststep1 = dst.step1();
833
834     size_t localThreads[3]  = { 64, 4, 1 };
835     size_t globalThreads[3] = { dst.cols, dst.rows, 1 };
836
837     std::string buildOptions = format("-D srcT=%s",
838                                       ddepth == CV_32F ? "float" : "double");
839
840     std::vector<std::pair<size_t , const void *> > args;
841     args.push_back( std::make_pair( sizeof(cl_mem), (void *)&src.data ));
842     args.push_back( std::make_pair( sizeof(cl_mem), (void *)&dst.data ));
843     args.push_back( std::make_pair( sizeof(cl_int), (void *)&cols1 ));
844     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src.rows ));
845     args.push_back( std::make_pair( sizeof(cl_int), (void *)&srcoffset1 ));
846     args.push_back( std::make_pair( sizeof(cl_int), (void *)&dstoffset1 ));
847     args.push_back( std::make_pair( sizeof(cl_int), (void *)&srcstep1 ));
848     args.push_back( std::make_pair( sizeof(cl_int), (void *)&dststep1 ));
849
850     openCLExecuteKernel(clCxt, source, kernelName, globalThreads, localThreads,
851                         args, src.oclchannels(), -1, buildOptions.c_str());
852 }
853
854 void cv::ocl::exp(const oclMat &src, oclMat &dst)
855 {
856     arithmetic_exp_log_run(src, dst, "arithm_exp", &arithm_exp);
857 }
858
859 void cv::ocl::log(const oclMat &src, oclMat &dst)
860 {
861     arithmetic_exp_log_run(src, dst, "arithm_log", &arithm_log);
862 }
863
864 //////////////////////////////////////////////////////////////////////////////
865 ////////////////////////////// magnitude phase ///////////////////////////////
866 //////////////////////////////////////////////////////////////////////////////
867
868 static void arithmetic_magnitude_phase_run(const oclMat &src1, const oclMat &src2, oclMat &dst, String kernelName)
869 {
870     int depth = dst.depth();
871
872     size_t localThreads[3]  = { 64, 4, 1 };
873     size_t globalThreads[3] = { dst.cols, dst.rows, 1 };
874
875     int src1_step = src1.step / src1.elemSize(), src1_offset = src1.offset / src1.elemSize();
876     int src2_step = src2.step / src2.elemSize(), src2_offset = src2.offset / src2.elemSize();
877     int dst_step = dst.step / dst.elemSize(), dst_offset = dst.offset / dst.elemSize();
878
879     std::vector<std::pair<size_t , const void *> > args;
880     args.push_back( std::make_pair( sizeof(cl_mem), (void *)&src1.data ));
881     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src1_step ));
882     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src1_offset ));
883     args.push_back( std::make_pair( sizeof(cl_mem), (void *)&src2.data ));
884     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src2_step ));
885     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src2_offset ));
886     args.push_back( std::make_pair( sizeof(cl_mem), (void *)&dst.data ));
887     args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst_step ));
888     args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst_offset ));
889     args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst.rows ));
890     args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst.cols ));
891
892     const char * const channelMap[] = { "", "", "2", "4", "4" };
893     std::string buildOptions = format("-D T=%s%s", depth == CV_32F ? "float" : "double", channelMap[dst.channels()]);
894
895     openCLExecuteKernel(src1.clCxt, &arithm_magnitude, kernelName, globalThreads, localThreads, args, -1, -1, buildOptions.c_str());
896 }
897
898 void cv::ocl::magnitude(const oclMat &src1, const oclMat &src2, oclMat &dst)
899 {
900     if (!src1.clCxt->supportsFeature(FEATURE_CL_DOUBLE) && src1.depth() == CV_64F)
901     {
902         CV_Error(Error::OpenCLDoubleNotSupported, "Selected device doesn't support double");
903         return;
904     }
905
906     CV_Assert(src1.type() == src2.type() && src1.size() == src2.size() &&
907               (src1.depth() == CV_32F || src1.depth() == CV_64F));
908
909     dst.create(src1.size(), src1.type());
910     arithmetic_magnitude_phase_run(src1, src2, dst, "arithm_magnitude");
911 }
912
913 static void arithmetic_phase_run(const oclMat &src1, const oclMat &src2, oclMat &dst, String kernelName, const cv::ocl::ProgramEntry* source)
914 {
915     int depth = dst.depth(), cols1 = src1.cols * src1.oclchannels();
916     int src1step1 = src1.step / src1.elemSize1(), src1offset1 = src1.offset / src1.elemSize1();
917     int src2step1 = src2.step / src2.elemSize1(), src2offset1 = src2.offset / src2.elemSize1();
918     int dststep1 = dst.step / dst.elemSize1(), dstoffset1 = dst.offset / dst.elemSize1();
919
920     size_t localThreads[3]  = { 64, 4, 1 };
921     size_t globalThreads[3] = { cols1, dst.rows, 1 };
922
923     std::vector<std::pair<size_t , const void *> > args;
924     args.push_back( std::make_pair( sizeof(cl_mem), (void *)&src1.data ));
925     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src1step1 ));
926     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src1offset1 ));
927     args.push_back( std::make_pair( sizeof(cl_mem), (void *)&src2.data ));
928     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src2step1 ));
929     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src2offset1 ));
930     args.push_back( std::make_pair( sizeof(cl_mem), (void *)&dst.data ));
931     args.push_back( std::make_pair( sizeof(cl_int), (void *)&dststep1 ));
932     args.push_back( std::make_pair( sizeof(cl_int), (void *)&dstoffset1 ));
933     args.push_back( std::make_pair( sizeof(cl_int), (void *)&cols1 ));
934     args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst.rows ));
935
936     openCLExecuteKernel(src1.clCxt, source, kernelName, globalThreads, localThreads, args, -1, depth);
937 }
938
939 void cv::ocl::phase(const oclMat &x, const oclMat &y, oclMat &Angle, bool angleInDegrees)
940 {
941     if (!x.clCxt->supportsFeature(FEATURE_CL_DOUBLE) && x.depth() == CV_64F)
942     {
943         CV_Error(Error::OpenCLDoubleNotSupported, "Selected device doesn't support double");
944         return;
945     }
946
947     CV_Assert(x.type() == y.type() && x.size() == y.size() && (x.depth() == CV_32F || x.depth() == CV_64F));
948     CV_Assert(x.step % x.elemSize() == 0 && y.step % y.elemSize() == 0);
949
950     Angle.create(x.size(), x.type());
951     arithmetic_phase_run(x, y, Angle, angleInDegrees ? "arithm_phase_indegrees" : "arithm_phase_inradians", &arithm_phase);
952 }
953
954 //////////////////////////////////////////////////////////////////////////////
955 ////////////////////////////////// cartToPolar ///////////////////////////////
956 //////////////////////////////////////////////////////////////////////////////
957
958 static void arithmetic_cartToPolar_run(const oclMat &src1, const oclMat &src2, oclMat &dst_mag, oclMat &dst_cart,
959                                 String kernelName, bool angleInDegrees)
960 {
961     int channels = src1.oclchannels();
962     int depth = src1.depth();
963
964     int cols = src1.cols * channels;
965
966     size_t localThreads[3]  = { 64, 4, 1 };
967     size_t globalThreads[3] = { cols, src1.rows, 1 };
968
969     int src1_step = src1.step / src1.elemSize1(), src1_offset = src1.offset / src1.elemSize1();
970     int src2_step = src2.step / src2.elemSize1(), src2_offset = src2.offset / src2.elemSize1();
971     int dst_mag_step = dst_mag.step / dst_mag.elemSize1(), dst_mag_offset = dst_mag.offset / dst_mag.elemSize1();
972     int dst_cart_step = dst_cart.step / dst_cart.elemSize1(), dst_cart_offset = dst_cart.offset / dst_cart.elemSize1();
973
974     std::vector<std::pair<size_t , const void *> > args;
975     args.push_back( std::make_pair( sizeof(cl_mem), (void *)&src1.data ));
976     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src1_step ));
977     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src1_offset ));
978     args.push_back( std::make_pair( sizeof(cl_mem), (void *)&src2.data ));
979     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src2_step ));
980     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src2_offset ));
981     args.push_back( std::make_pair( sizeof(cl_mem), (void *)&dst_mag.data ));
982     args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst_mag_step ));
983     args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst_mag_offset ));
984     args.push_back( std::make_pair( sizeof(cl_mem), (void *)&dst_cart.data ));
985     args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst_cart_step ));
986     args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst_cart_offset ));
987     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src1.rows ));
988     args.push_back( std::make_pair( sizeof(cl_int), (void *)&cols ));
989
990     openCLExecuteKernel(src1.clCxt, &arithm_cartToPolar, kernelName, globalThreads, localThreads, args,
991                         -1, depth, angleInDegrees ? "-D DEGREE" : "-D RADIAN");
992 }
993
994 void cv::ocl::cartToPolar(const oclMat &x, const oclMat &y, oclMat &mag, oclMat &angle, bool angleInDegrees)
995 {
996     if (!x.clCxt->supportsFeature(FEATURE_CL_DOUBLE) && x.depth() == CV_64F)
997     {
998         CV_Error(Error::OpenCLDoubleNotSupported, "Selected device doesn't support double");
999         return;
1000     }
1001
1002     CV_Assert(x.type() == y.type() && x.size() == y.size() && (x.depth() == CV_32F || x.depth() == CV_64F));
1003
1004     mag.create(x.size(), x.type());
1005     angle.create(x.size(), x.type());
1006
1007     arithmetic_cartToPolar_run(x, y, mag, angle, "arithm_cartToPolar", angleInDegrees);
1008 }
1009
1010 //////////////////////////////////////////////////////////////////////////////
1011 ////////////////////////////////// polarToCart ///////////////////////////////
1012 //////////////////////////////////////////////////////////////////////////////
1013
1014 static void arithmetic_ptc_run(const oclMat &src1, const oclMat &src2, oclMat &dst1, oclMat &dst2, bool angleInDegrees,
1015                         String kernelName)
1016 {
1017     int channels = src2.oclchannels(), depth = src2.depth();
1018     int cols = src2.cols * channels, rows = src2.rows;
1019
1020     size_t localThreads[3]  = { 64, 4, 1 };
1021     size_t globalThreads[3] = { cols, rows, 1 };
1022
1023     int src1_step = src1.step / src1.elemSize1(), src1_offset = src1.offset / src1.elemSize1();
1024     int src2_step = src2.step / src2.elemSize1(), src2_offset = src2.offset / src2.elemSize1();
1025     int dst1_step = dst1.step / dst1.elemSize1(), dst1_offset = dst1.offset / dst1.elemSize1();
1026     int dst2_step = dst2.step / dst2.elemSize1(), dst2_offset = dst2.offset / dst2.elemSize1();
1027
1028     std::vector<std::pair<size_t , const void *> > args;
1029     if (src1.data)
1030     {
1031         args.push_back( std::make_pair( sizeof(cl_mem), (void *)&src1.data ));
1032         args.push_back( std::make_pair( sizeof(cl_int), (void *)&src1_step ));
1033         args.push_back( std::make_pair( sizeof(cl_int), (void *)&src1_offset ));
1034     }
1035     args.push_back( std::make_pair( sizeof(cl_mem), (void *)&src2.data ));
1036     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src2_step ));
1037     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src2_offset ));
1038     args.push_back( std::make_pair( sizeof(cl_mem), (void *)&dst1.data ));
1039     args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst1_step ));
1040     args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst1_offset ));
1041     args.push_back( std::make_pair( sizeof(cl_mem), (void *)&dst2.data ));
1042     args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst2_step ));
1043     args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst2_offset ));
1044     args.push_back( std::make_pair( sizeof(cl_int), (void *)&rows ));
1045     args.push_back( std::make_pair( sizeof(cl_int), (void *)&cols ));
1046
1047     openCLExecuteKernel(src1.clCxt, &arithm_polarToCart, kernelName, globalThreads, localThreads,
1048                         args, -1, depth, angleInDegrees ? "-D DEGREE" : "-D RADIAN");
1049 }
1050
1051 void cv::ocl::polarToCart(const oclMat &magnitude, const oclMat &angle, oclMat &x, oclMat &y, bool angleInDegrees)
1052 {
1053     if (!magnitude.clCxt->supportsFeature(FEATURE_CL_DOUBLE) && magnitude.depth() == CV_64F)
1054     {
1055         CV_Error(Error::OpenCLDoubleNotSupported, "Selected device doesn't support double");
1056         return;
1057     }
1058
1059     CV_Assert(angle.depth() == CV_32F || angle.depth() == CV_64F);
1060     CV_Assert(magnitude.size() == angle.size() && magnitude.type() == angle.type());
1061
1062     x.create(angle.size(), angle.type());
1063     y.create(angle.size(), angle.type());
1064
1065     if ( magnitude.data )
1066         arithmetic_ptc_run(magnitude, angle, x, y, angleInDegrees, "arithm_polarToCart_mag");
1067     else
1068         arithmetic_ptc_run(magnitude, angle, x, y, angleInDegrees, "arithm_polarToCart");
1069 }
1070
1071 //////////////////////////////////////////////////////////////////////////////
1072 /////////////////////////////////// minMaxLoc ////////////////////////////////
1073 //////////////////////////////////////////////////////////////////////////////
1074
1075 static void arithmetic_minMaxLoc_run(const oclMat &src, cl_mem &dst, int vlen , int groupnum)
1076 {
1077     std::vector<std::pair<size_t , const void *> > args;
1078     int all_cols = src.step / (vlen * src.elemSize1());
1079     int pre_cols = (src.offset % src.step) / (vlen * src.elemSize1());
1080     int sec_cols = all_cols - (src.offset % src.step + src.cols * src.elemSize1() - 1) / (vlen * src.elemSize1()) - 1;
1081     int invalid_cols = pre_cols + sec_cols;
1082     int cols = all_cols - invalid_cols , elemnum = cols * src.rows;;
1083     int offset = src.offset / (vlen * src.elemSize1());
1084     int repeat_s = src.offset / src.elemSize1() - offset * vlen;
1085     int repeat_e = (offset + cols) * vlen - src.offset / src.elemSize1() - src.cols;
1086     args.push_back( std::make_pair( sizeof(cl_int) , (void *)&cols ));
1087     args.push_back( std::make_pair( sizeof(cl_int) , (void *)&invalid_cols ));
1088     args.push_back( std::make_pair( sizeof(cl_int) , (void *)&offset));
1089     args.push_back( std::make_pair( sizeof(cl_int) , (void *)&elemnum));
1090     args.push_back( std::make_pair( sizeof(cl_int) , (void *)&groupnum));
1091     args.push_back( std::make_pair( sizeof(cl_mem) , (void *)&src.data));
1092     args.push_back( std::make_pair( sizeof(cl_mem) , (void *)&dst ));
1093     char build_options[50];
1094     sprintf(build_options, "-D DEPTH_%d -D REPEAT_S%d -D REPEAT_E%d", src.depth(), repeat_s, repeat_e);
1095     size_t gt[3] = {groupnum * 256, 1, 1}, lt[3] = {256, 1, 1};
1096     openCLExecuteKernel(src.clCxt, &arithm_minMaxLoc, "arithm_op_minMaxLoc", gt, lt, args, -1, -1, build_options);
1097 }
1098
1099 static void arithmetic_minMaxLoc_mask_run(const oclMat &src, const oclMat &mask, cl_mem &dst, int vlen, int groupnum)
1100 {
1101     std::vector<std::pair<size_t , const void *> > args;
1102     size_t gt[3] = {groupnum * 256, 1, 1}, lt[3] = {256, 1, 1};
1103     char build_options[50];
1104     if (src.oclchannels() == 1)
1105     {
1106         int cols = (src.cols - 1) / vlen + 1;
1107         int invalid_cols = src.step / (vlen * src.elemSize1()) - cols;
1108         int offset = src.offset / src.elemSize1();
1109         int repeat_me = vlen - (mask.cols % vlen == 0 ? vlen : mask.cols % vlen);
1110         int minvalid_cols = mask.step / (vlen * mask.elemSize1()) - cols;
1111         int moffset = mask.offset / mask.elemSize1();
1112         int elemnum = cols * src.rows;
1113         sprintf(build_options, "-D DEPTH_%d -D REPEAT_E%d", src.depth(), repeat_me);
1114         args.push_back( std::make_pair( sizeof(cl_int) , (void *)&cols ));
1115         args.push_back( std::make_pair( sizeof(cl_int) , (void *)&invalid_cols ));
1116         args.push_back( std::make_pair( sizeof(cl_int) , (void *)&offset));
1117         args.push_back( std::make_pair( sizeof(cl_int) , (void *)&elemnum));
1118         args.push_back( std::make_pair( sizeof(cl_int) , (void *)&groupnum));
1119         args.push_back( std::make_pair( sizeof(cl_mem) , (void *)&src.data));
1120         args.push_back( std::make_pair( sizeof(cl_int) , (void *)&minvalid_cols ));
1121         args.push_back( std::make_pair( sizeof(cl_int) , (void *)&moffset ));
1122         args.push_back( std::make_pair( sizeof(cl_mem) , (void *)&mask.data ));
1123         args.push_back( std::make_pair( sizeof(cl_mem) , (void *)&dst ));
1124
1125         openCLExecuteKernel(src.clCxt, &arithm_minMaxLoc_mask, "arithm_op_minMaxLoc_mask", gt, lt, args, -1, -1, build_options);
1126     }
1127 }
1128
1129 template <typename T>
1130 void arithmetic_minMaxLoc(const oclMat &src, double *minVal, double *maxVal,
1131                           Point *minLoc, Point *maxLoc, const oclMat &mask)
1132 {
1133     CV_Assert(src.oclchannels() == 1);
1134     size_t groupnum = src.clCxt->getDeviceInfo().maxComputeUnits;
1135     CV_Assert(groupnum != 0);
1136     int minloc = -1 , maxloc = -1;
1137     int vlen = 4, dbsize = groupnum * vlen * 4 * sizeof(T) ;
1138     Context *clCxt = src.clCxt;
1139     cl_mem dstBuffer = openCLCreateBuffer(clCxt, CL_MEM_WRITE_ONLY, dbsize);
1140     *minVal = std::numeric_limits<double>::max() , *maxVal = -std::numeric_limits<double>::max();
1141
1142     if (mask.empty())
1143         arithmetic_minMaxLoc_run(src, dstBuffer, vlen, groupnum);
1144     else
1145         arithmetic_minMaxLoc_mask_run(src, mask, dstBuffer, vlen, groupnum);
1146
1147     AutoBuffer<T> _buf(groupnum * vlen * 4);
1148     T *p = (T*)_buf;
1149     memset(p, 0, dbsize);
1150
1151     openCLReadBuffer(clCxt, dstBuffer, (void *)p, dbsize);
1152     for (int i = 0; i < vlen * (int)groupnum; i++)
1153     {
1154         *minVal = (*minVal < p[i] || p[i + 2 * vlen * groupnum] == -1) ? *minVal : p[i];
1155         minloc = (*minVal < p[i] || p[i + 2 * vlen * groupnum] == -1) ? minloc : cvRound(p[i + 2 * vlen * groupnum]);
1156     }
1157     for (int i = vlen * (int)groupnum; i < 2 * vlen * (int)groupnum; i++)
1158     {
1159         *maxVal = (*maxVal > p[i] || p[i + 2 * vlen * groupnum] == -1) ? *maxVal : p[i];
1160         maxloc = (*maxVal > p[i] || p[i + 2 * vlen * groupnum] == -1) ? maxloc : cvRound(p[i + 2 * vlen * groupnum]);
1161     }
1162
1163     int pre_rows = src.offset / src.step;
1164     int pre_cols = (src.offset % src.step) / src.elemSize1();
1165     int wholecols = src.step / src.elemSize1();
1166     if ( minLoc )
1167     {
1168         if ( minloc >= 0 )
1169         {
1170             minLoc->y = minloc / wholecols - pre_rows;
1171             minLoc->x = minloc % wholecols - pre_cols;
1172         }
1173         else
1174             minLoc->x = minLoc->y = -1;
1175     }
1176     if ( maxLoc )
1177     {
1178         if ( maxloc >= 0 )
1179         {
1180             maxLoc->y = maxloc / wholecols - pre_rows;
1181             maxLoc->x = maxloc % wholecols - pre_cols;
1182         }
1183         else
1184             maxLoc->x = maxLoc->y = -1;
1185     }
1186
1187     openCLSafeCall(clReleaseMemObject(dstBuffer));
1188 }
1189
1190 typedef void (*minMaxLocFunc)(const oclMat &src, double *minVal, double *maxVal,
1191                               Point *minLoc, Point *maxLoc, const oclMat &mask);
1192
1193 void cv::ocl::minMaxLoc(const oclMat &src, double *minVal, double *maxVal,
1194                         Point *minLoc, Point *maxLoc, const oclMat &mask)
1195 {
1196     if (!src.clCxt->supportsFeature(FEATURE_CL_DOUBLE) && src.depth() == CV_64F)
1197     {
1198         CV_Error(Error::OpenCLDoubleNotSupported, "Selected device doesn't support double");
1199         return;
1200     }
1201
1202     static minMaxLocFunc functab[2] =
1203     {
1204         arithmetic_minMaxLoc<float>,
1205         arithmetic_minMaxLoc<double>
1206     };
1207
1208     minMaxLocFunc func;
1209     func = functab[(int)src.clCxt->supportsFeature(FEATURE_CL_DOUBLE)];
1210     func(src, minVal, maxVal, minLoc, maxLoc, mask);
1211 }
1212
1213 //////////////////////////////////////////////////////////////////////////////
1214 ///////////////////////////// countNonZero ///////////////////////////////////
1215 //////////////////////////////////////////////////////////////////////////////
1216
1217 static void arithmetic_countNonZero_run(const oclMat &src, cl_mem &dst, int groupnum, String kernelName)
1218 {
1219     int ochannels = src.oclchannels();
1220     int all_cols = src.step / src.elemSize();
1221     int pre_cols = (src.offset % src.step) / src.elemSize();
1222     int sec_cols = all_cols - (src.offset % src.step + src.cols * src.elemSize() - 1) / src.elemSize() - 1;
1223     int invalid_cols = pre_cols + sec_cols;
1224     int cols = all_cols - invalid_cols , elemnum = cols * src.rows;;
1225     int offset = src.offset / src.elemSize();
1226
1227     const char * const typeMap[] = { "uchar", "char", "ushort", "short", "int", "float", "double" };
1228     const char * const channelMap[] = { " ", " ", "2", "4", "4" };
1229     String buildOptions = format("-D srcT=%s%s -D dstT=int%s", typeMap[src.depth()], channelMap[ochannels],
1230                                  channelMap[ochannels]);
1231
1232     std::vector<std::pair<size_t , const void *> > args;
1233     args.push_back( std::make_pair( sizeof(cl_int) , (void *)&cols ));
1234     args.push_back( std::make_pair( sizeof(cl_int) , (void *)&invalid_cols ));
1235     args.push_back( std::make_pair( sizeof(cl_int) , (void *)&offset));
1236     args.push_back( std::make_pair( sizeof(cl_int) , (void *)&elemnum));
1237     args.push_back( std::make_pair( sizeof(cl_int) , (void *)&groupnum));
1238     args.push_back( std::make_pair( sizeof(cl_mem) , (void *)&src.data));
1239     args.push_back( std::make_pair( sizeof(cl_mem) , (void *)&dst ));
1240
1241     size_t globalThreads[3] = { groupnum * 256, 1, 1 };
1242     size_t localThreads[3] = { 256, 1, 1 };
1243
1244     openCLExecuteKernel(src.clCxt, &arithm_nonzero, kernelName, globalThreads, localThreads,
1245                         args, -1, -1, buildOptions.c_str());
1246 }
1247
1248 int cv::ocl::countNonZero(const oclMat &src)
1249 {
1250     CV_Assert(src.step % src.elemSize() == 0);
1251     CV_Assert(src.channels() == 1);
1252
1253     Context *clCxt = src.clCxt;
1254     if (!src.clCxt->supportsFeature(FEATURE_CL_DOUBLE) && src.depth() == CV_64F)
1255     {
1256         CV_Error(Error::OpenCLDoubleNotSupported, "selected device doesn't support double");
1257         return -1;
1258     }
1259
1260     size_t groupnum = src.clCxt->getDeviceInfo().maxComputeUnits;
1261     CV_Assert(groupnum != 0);
1262     int dbsize = groupnum;
1263
1264     String kernelName = "arithm_op_nonzero";
1265
1266     AutoBuffer<int> _buf(dbsize);
1267     int *p = (int*)_buf, nonzero = 0;
1268     memset(p, 0, dbsize * sizeof(int));
1269
1270     cl_mem dstBuffer = openCLCreateBuffer(clCxt, CL_MEM_WRITE_ONLY, dbsize * sizeof(int));
1271     arithmetic_countNonZero_run(src, dstBuffer, groupnum, kernelName);
1272     openCLReadBuffer(clCxt, dstBuffer, (void *)p, dbsize * sizeof(int));
1273
1274     for (int i = 0; i < dbsize; i++)
1275         nonzero += p[i];
1276
1277     openCLSafeCall(clReleaseMemObject(dstBuffer));
1278
1279     return nonzero;
1280 }
1281
1282 //////////////////////////////////////////////////////////////////////////////
1283 ////////////////////////////////bitwise_op////////////////////////////////////
1284 //////////////////////////////////////////////////////////////////////////////
1285
1286 static void bitwise_unary_run(const oclMat &src1, oclMat &dst, String kernelName, const cv::ocl::ProgramEntry* source)
1287 {
1288     dst.create(src1.size(), src1.type());
1289
1290     int channels = dst.oclchannels();
1291     int depth = dst.depth();
1292
1293     int vector_lengths[4][7] = {{4, 4, 4, 4, 1, 1, 1},
1294         {4, 4, 4, 4, 1, 1, 1},
1295         {4, 4, 4, 4, 1, 1, 1},
1296         {4, 4, 4, 4, 1, 1, 1}
1297     };
1298
1299     size_t vector_length = vector_lengths[channels - 1][depth];
1300     int offset_cols = (dst.offset / dst.elemSize1()) & (vector_length - 1);
1301     int cols = divUp(dst.cols * channels + offset_cols, vector_length);
1302
1303     size_t localThreads[3]  = { 64, 4, 1 };
1304     size_t globalThreads[3] = { cols, dst.rows, 1 };
1305
1306     int dst_step1 = dst.cols * dst.elemSize();
1307     std::vector<std::pair<size_t , const void *> > args;
1308     args.push_back( std::make_pair( sizeof(cl_mem), (void *)&src1.data ));
1309     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src1.step ));
1310     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src1.offset ));
1311     args.push_back( std::make_pair( sizeof(cl_mem), (void *)&dst.data ));
1312     args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst.step ));
1313     args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst.offset ));
1314     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src1.rows ));
1315     args.push_back( std::make_pair( sizeof(cl_int), (void *)&cols ));
1316     args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst_step1 ));
1317
1318     openCLExecuteKernel(src1.clCxt, source, kernelName, globalThreads, localThreads, args, -1, depth);
1319 }
1320
1321 enum { AND = 0, OR, XOR };
1322
1323 static void bitwise_binary_run(const oclMat &src1, const oclMat &src2, const Scalar& src3, const oclMat &mask,
1324                                oclMat &dst, int operationType)
1325 {
1326     CV_Assert(operationType >= AND && operationType <= XOR);
1327     CV_Assert(src2.empty() || (!src2.empty() && src1.type() == src2.type() && src1.size() == src2.size()));
1328     CV_Assert(mask.empty() || (!mask.empty() && mask.type() == CV_8UC1 && mask.size() == src1.size()));
1329
1330     dst.create(src1.size(), src1.type());
1331     oclMat m;
1332
1333     const char operationMap[] = { '&', '|', '^' };
1334     std::string kernelName("arithm_bitwise_binary");
1335
1336     int vlen = std::min<int>(8, src1.elemSize1() * src1.oclchannels());
1337     std::string vlenstr = vlen > 1 ? format("%d", vlen) : "";
1338     std::string buildOptions = format("-D Operation=%c -D vloadn=vload%s -D vstoren=vstore%s -D elemSize=%d -D vlen=%d"
1339                                       " -D ucharv=uchar%s",
1340                                       operationMap[operationType], vlenstr.c_str(), vlenstr.c_str(),
1341                                       (int)src1.elemSize(), vlen, vlenstr.c_str());
1342
1343     size_t localThreads[3]  = { 16, 16, 1 };
1344     size_t globalThreads[3] = { dst.cols, dst.rows, 1 };
1345
1346     std::vector<std::pair<size_t , const void *> > args;
1347     args.push_back( std::make_pair( sizeof(cl_mem), (void *)&src1.data ));
1348     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src1.step ));
1349     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src1.offset ));
1350
1351     if (src2.empty())
1352     {
1353         m.create(1, 1, dst.type());
1354         m.setTo(src3);
1355
1356         args.push_back( std::make_pair( sizeof(cl_mem), (void *)&m.data ));
1357
1358         kernelName += "_scalar";
1359     }
1360     else
1361     {
1362         args.push_back( std::make_pair( sizeof(cl_mem), (void *)&src2.data ));
1363         args.push_back( std::make_pair( sizeof(cl_int), (void *)&src2.step ));
1364         args.push_back( std::make_pair( sizeof(cl_int), (void *)&src2.offset ));
1365     }
1366
1367     if (!mask.empty())
1368     {
1369         args.push_back( std::make_pair( sizeof(cl_mem), (void *)&mask.data ));
1370         args.push_back( std::make_pair( sizeof(cl_int), (void *)&mask.step ));
1371         args.push_back( std::make_pair( sizeof(cl_int), (void *)&mask.offset ));
1372
1373         kernelName += "_mask";
1374     }
1375
1376     args.push_back( std::make_pair( sizeof(cl_mem), (void *)&dst.data ));
1377     args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst.step ));
1378     args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst.offset ));
1379
1380     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src1.cols ));
1381     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src1.rows ));
1382
1383     openCLExecuteKernel(src1.clCxt, mask.empty() ? (!src2.empty() ? &arithm_bitwise_binary : &arithm_bitwise_binary_scalar) :
1384                                               (!src2.empty() ? &arithm_bitwise_binary_mask : &arithm_bitwise_binary_scalar_mask),
1385                         kernelName, globalThreads, localThreads,
1386                         args, -1, -1, buildOptions.c_str());
1387 }
1388
1389 void cv::ocl::bitwise_not(const oclMat &src, oclMat &dst)
1390 {
1391     if (!src.clCxt->supportsFeature(FEATURE_CL_DOUBLE) && src.depth() == CV_64F)
1392     {
1393         CV_Error(Error::OpenCLDoubleNotSupported, "Selected device doesn't support double");
1394         return;
1395     }
1396
1397     dst.create(src.size(), src.type());
1398     bitwise_unary_run(src, dst, "arithm_bitwise_not", &arithm_bitwise_not);
1399 }
1400
1401 void cv::ocl::bitwise_or(const oclMat &src1, const oclMat &src2, oclMat &dst, const oclMat &mask)
1402 {
1403     bitwise_binary_run(src1, src2, Scalar(), mask, dst, OR);
1404 }
1405
1406 void cv::ocl::bitwise_or(const oclMat &src1, const Scalar &src2, oclMat &dst, const oclMat &mask)
1407 {
1408     bitwise_binary_run(src1, oclMat(), src2, mask, dst, OR);
1409 }
1410
1411 void cv::ocl::bitwise_and(const oclMat &src1, const oclMat &src2, oclMat &dst, const oclMat &mask)
1412 {
1413     bitwise_binary_run(src1, src2, Scalar(), mask, dst, AND);
1414 }
1415
1416 void cv::ocl::bitwise_and(const oclMat &src1, const Scalar &src2, oclMat &dst, const oclMat &mask)
1417 {
1418     bitwise_binary_run(src1, oclMat(), src2, mask, dst, AND);
1419 }
1420
1421 void cv::ocl::bitwise_xor(const oclMat &src1, const oclMat &src2, oclMat &dst, const oclMat &mask)
1422 {
1423     bitwise_binary_run(src1, src2, Scalar(), mask, dst, XOR);
1424 }
1425
1426 void cv::ocl::bitwise_xor(const oclMat &src1, const Scalar &src2, oclMat &dst, const oclMat &mask)
1427 {
1428     bitwise_binary_run(src1, oclMat(), src2, mask, dst, XOR);
1429 }
1430
1431 oclMat cv::ocl::operator ~ (const oclMat &src)
1432 {
1433     return oclMatExpr(src, oclMat(), MAT_NOT);
1434 }
1435
1436 oclMat cv::ocl::operator | (const oclMat &src1, const oclMat &src2)
1437 {
1438     return oclMatExpr(src1, src2, MAT_OR);
1439 }
1440
1441 oclMat cv::ocl::operator & (const oclMat &src1, const oclMat &src2)
1442 {
1443     return oclMatExpr(src1, src2, MAT_AND);
1444 }
1445
1446 oclMat cv::ocl::operator ^ (const oclMat &src1, const oclMat &src2)
1447 {
1448     return oclMatExpr(src1, src2, MAT_XOR);
1449 }
1450
1451 cv::ocl::oclMatExpr cv::ocl::operator + (const oclMat &src1, const oclMat &src2)
1452 {
1453     return oclMatExpr(src1, src2, cv::ocl::MAT_ADD);
1454 }
1455
1456 cv::ocl::oclMatExpr cv::ocl::operator - (const oclMat &src1, const oclMat &src2)
1457 {
1458     return oclMatExpr(src1, src2, cv::ocl::MAT_SUB);
1459 }
1460
1461 cv::ocl::oclMatExpr cv::ocl::operator * (const oclMat &src1, const oclMat &src2)
1462 {
1463     return oclMatExpr(src1, src2, cv::ocl::MAT_MUL);
1464 }
1465
1466 cv::ocl::oclMatExpr cv::ocl::operator / (const oclMat &src1, const oclMat &src2)
1467 {
1468     return oclMatExpr(src1, src2, cv::ocl::MAT_DIV);
1469 }
1470
1471 void oclMatExpr::assign(oclMat& m) const
1472 {
1473     switch (op)
1474     {
1475         case MAT_ADD:
1476             add(a, b, m);
1477             break;
1478         case MAT_SUB:
1479             subtract(a, b, m);
1480             break;
1481         case MAT_MUL:
1482             multiply(a, b, m);
1483             break;
1484         case MAT_DIV:
1485             divide(a, b, m);
1486             break;
1487         case MAT_NOT:
1488             bitwise_not(a, m);
1489             break;
1490         case MAT_AND:
1491             bitwise_and(a, b, m);
1492             break;
1493         case MAT_OR:
1494             bitwise_or(a, b, m);
1495             break;
1496         case MAT_XOR:
1497             bitwise_xor(a, b, m);
1498             break;
1499     }
1500 }
1501
1502 oclMatExpr::operator oclMat() const
1503 {
1504     oclMat m;
1505     assign(m);
1506     return m;
1507 }
1508
1509 //////////////////////////////////////////////////////////////////////////////
1510 /////////////////////////////// transpose ////////////////////////////////////
1511 //////////////////////////////////////////////////////////////////////////////
1512
1513 #define TILE_DIM   (32)
1514 #define BLOCK_ROWS (256 / TILE_DIM)
1515
1516 static void transpose_run(const oclMat &src, oclMat &dst, String kernelName, bool inplace = false)
1517 {
1518     const char * const typeMap[] = { "uchar", "char", "ushort", "short", "int", "float", "double" };
1519     const char channelsString[] = { ' ', ' ', '2', '4', '4' };
1520     std::string buildOptions = format("-D T=%s%c", typeMap[src.depth()],
1521                                       channelsString[src.channels()]);
1522
1523     size_t localThreads[3]  = { TILE_DIM, BLOCK_ROWS, 1 };
1524     size_t globalThreads[3] = { src.cols, inplace ? src.rows : divUp(src.rows, TILE_DIM) * BLOCK_ROWS, 1 };
1525
1526     int srcstep1 = src.step / src.elemSize(), dststep1 = dst.step / dst.elemSize();
1527     int srcoffset1 = src.offset / src.elemSize(), dstoffset1 = dst.offset / dst.elemSize();
1528
1529     std::vector<std::pair<size_t , const void *> > args;
1530     args.push_back( std::make_pair( sizeof(cl_mem), (void *)&src.data ));
1531     args.push_back( std::make_pair( sizeof(cl_mem), (void *)&dst.data ));
1532     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src.cols ));
1533     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src.rows ));
1534     args.push_back( std::make_pair( sizeof(cl_int), (void *)&srcstep1 ));
1535     args.push_back( std::make_pair( sizeof(cl_int), (void *)&dststep1 ));
1536     args.push_back( std::make_pair( sizeof(cl_int), (void *)&srcoffset1 ));
1537     args.push_back( std::make_pair( sizeof(cl_int), (void *)&dstoffset1 ));
1538
1539     openCLExecuteKernel(src.clCxt, &arithm_transpose, kernelName, globalThreads, localThreads,
1540                         args, -1, -1, buildOptions.c_str());
1541 }
1542
1543 void cv::ocl::transpose(const oclMat &src, oclMat &dst)
1544 {
1545     if (!src.clCxt->supportsFeature(FEATURE_CL_DOUBLE) && src.depth() == CV_64F)
1546     {
1547         CV_Error(Error::OpenCLDoubleNotSupported, "Selected device doesn't support double");
1548         return;
1549     }
1550
1551     if ( src.data == dst.data && src.cols == src.rows && dst.offset == src.offset
1552          && dst.size() == src.size())
1553         transpose_run( src, dst, "transpose_inplace", true);
1554     else
1555     {
1556         dst.create(src.cols, src.rows, src.type());
1557         transpose_run( src, dst, "transpose");
1558     }
1559 }
1560
1561 //////////////////////////////////////////////////////////////////////////////
1562 ////////////////////////////// addWeighted ///////////////////////////////////
1563 //////////////////////////////////////////////////////////////////////////////
1564
1565 void cv::ocl::addWeighted(const oclMat &src1, double alpha, const oclMat &src2, double beta, double gama, oclMat &dst)
1566 {
1567     Context *clCxt = src1.clCxt;
1568     bool hasDouble = clCxt->supportsFeature(FEATURE_CL_DOUBLE);
1569     if (!hasDouble && src1.depth() == CV_64F)
1570     {
1571         CV_Error(Error::OpenCLDoubleNotSupported, "Selected device doesn't support double");
1572         return;
1573     }
1574
1575     CV_Assert(src1.size() ==  src2.size() && src1.type() == src2.type());
1576     dst.create(src1.size(), src1.type());
1577
1578     int channels = dst.oclchannels();
1579     int depth = dst.depth();
1580
1581     int cols1 = src1.cols * channels;
1582     int src1step1 = src1.step1(), src1offset1 = src1.offset / src1.elemSize1();
1583     int src2step1 = src2.step1(), src2offset1 = src2.offset / src1.elemSize1();
1584     int dststep1 = dst.step1(), dstoffset1 = dst.offset / dst.elemSize1();
1585
1586     const char * const typeMap[] = { "uchar", "char", "ushort", "short", "int", "float", "double" };
1587     std::string buildOptions = format("-D T=%s -D WT=%s -D convertToT=convert_%s%s",
1588                                       typeMap[depth], hasDouble ? "double" : "float", typeMap[depth],
1589                                       depth >= CV_32F ? "" : "_sat_rte");
1590
1591     size_t localThreads[3]  = { 256, 1, 1 };
1592     size_t globalThreads[3] = { cols1, dst.rows, 1};
1593
1594     float alpha_f = static_cast<float>(alpha),
1595             beta_f = static_cast<float>(beta),
1596             gama_f = static_cast<float>(gama);
1597
1598     std::vector<std::pair<size_t , const void *> > args;
1599     args.push_back( std::make_pair( sizeof(cl_mem), (void *)&src1.data ));
1600     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src1step1 ));
1601     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src1offset1));
1602     args.push_back( std::make_pair( sizeof(cl_mem), (void *)&src2.data ));
1603     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src2step1 ));
1604     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src2offset1));
1605     args.push_back( std::make_pair( sizeof(cl_mem), (void *)&dst.data ));
1606     args.push_back( std::make_pair( sizeof(cl_int), (void *)&dststep1 ));
1607     args.push_back( std::make_pair( sizeof(cl_int), (void *)&dstoffset1));
1608
1609     if (!hasDouble)
1610     {
1611         args.push_back( std::make_pair( sizeof(cl_float), (void *)&alpha_f ));
1612         args.push_back( std::make_pair( sizeof(cl_float), (void *)&beta_f ));
1613         args.push_back( std::make_pair( sizeof(cl_float), (void *)&gama_f ));
1614     }
1615     else
1616     {
1617         args.push_back( std::make_pair( sizeof(cl_double), (void *)&alpha ));
1618         args.push_back( std::make_pair( sizeof(cl_double), (void *)&beta ));
1619         args.push_back( std::make_pair( sizeof(cl_double), (void *)&gama ));
1620     }
1621
1622     args.push_back( std::make_pair( sizeof(cl_int), (void *)&cols1 ));
1623     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src1.rows ));
1624
1625     openCLExecuteKernel(clCxt, &arithm_addWeighted, "addWeighted", globalThreads, localThreads,
1626                         args, -1, -1, buildOptions.c_str());
1627 }
1628
1629 //////////////////////////////////////////////////////////////////////////////
1630 /////////////////////////////////// Pow //////////////////////////////////////
1631 //////////////////////////////////////////////////////////////////////////////
1632
1633 static void arithmetic_pow_run(const oclMat &src, double p, oclMat &dst, String kernelName, const cv::ocl::ProgramEntry* source)
1634 {
1635     int channels = dst.oclchannels();
1636     int depth = dst.depth();
1637
1638     size_t localThreads[3]  = { 64, 4, 1 };
1639     size_t globalThreads[3] = { dst.cols, dst.rows, 1 };
1640
1641     const char * const typeStr = depth == CV_32F ? "float" : "double";
1642     const char * const channelMap[] = { "", "", "2", "4", "4" };
1643     std::string buildOptions = format("-D VT=%s%s -D T=%s", typeStr, channelMap[channels], typeStr);
1644
1645     int src_step = src.step / src.elemSize(), src_offset = src.offset / src.elemSize();
1646     int dst_step = dst.step / dst.elemSize(), dst_offset = dst.offset / dst.elemSize();
1647
1648     std::vector<std::pair<size_t , const void *> > args;
1649     args.push_back( std::make_pair( sizeof(cl_mem), (void *)&src.data ));
1650     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src_step ));
1651     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src_offset ));
1652     args.push_back( std::make_pair( sizeof(cl_mem), (void *)&dst.data ));
1653     args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst_step ));
1654     args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst_offset ));
1655     args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst.rows ));
1656     args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst.cols ));
1657
1658     float pf = static_cast<float>(p);
1659     if(src.depth() == CV_32F)
1660         args.push_back( std::make_pair( sizeof(cl_float), (void *)&pf ));
1661     else
1662         args.push_back( std::make_pair( sizeof(cl_double), (void *)&p ));
1663
1664     openCLExecuteKernel(src.clCxt, source, kernelName, globalThreads, localThreads, args, -1, -1, buildOptions.c_str());
1665 }
1666
1667 void cv::ocl::pow(const oclMat &x, double p, oclMat &y)
1668 {
1669     if (!x.clCxt->supportsFeature(FEATURE_CL_DOUBLE) && x.depth() == CV_64F)
1670     {
1671         CV_Error(Error::OpenCLDoubleNotSupported, "Selected device doesn't support double");
1672         return;
1673     }
1674
1675     CV_Assert(x.depth() == CV_32F || x.depth() == CV_64F);
1676     y.create(x.size(), x.type());
1677
1678     arithmetic_pow_run(x, p, y, "arithm_pow", &arithm_pow);
1679 }
1680
1681 //////////////////////////////////////////////////////////////////////////////
1682 /////////////////////////////// setIdentity //////////////////////////////////
1683 //////////////////////////////////////////////////////////////////////////////
1684
1685 void cv::ocl::setIdentity(oclMat& src, const Scalar & scalar)
1686 {
1687     if (!src.clCxt->supportsFeature(FEATURE_CL_DOUBLE) && src.depth() == CV_64F)
1688     {
1689         CV_Error(Error::OpenCLDoubleNotSupported, "Selected device doesn't support double");
1690         return;
1691     }
1692
1693     CV_Assert(src.step % src.elemSize() == 0);
1694
1695     int src_step1 = src.step / src.elemSize(), src_offset1 = src.offset / src.elemSize();
1696     size_t local_threads[] = { 16, 16, 1 };
1697     size_t global_threads[] = { src.cols, src.rows, 1 };
1698
1699     const char * const typeMap[] = { "uchar", "char", "ushort", "short", "int", "float", "double" };
1700     const char * const channelMap[] = { "", "", "2", "4", "4" };
1701     String buildOptions = format("-D T=%s%s", typeMap[src.depth()], channelMap[src.oclchannels()]);
1702
1703     std::vector<std::pair<size_t , const void *> > args;
1704     args.push_back( std::make_pair( sizeof(cl_mem), (void *)&src.data ));
1705     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src_step1 ));
1706     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src_offset1 ));
1707     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src.cols));
1708     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src.rows));
1709
1710     oclMat sc(1, 1, src.type(), scalar);
1711     args.push_back( std::make_pair( sizeof(cl_mem), (void *)&sc.data ));
1712
1713     openCLExecuteKernel(src.clCxt, &arithm_setidentity, "setIdentity", global_threads, local_threads,
1714                         args, -1, -1, buildOptions.c_str());
1715 }
1716
1717 //////////////////////////////////////////////////////////////////////////////
1718 ////////////////////////////////// Repeat ////////////////////////////////////
1719 //////////////////////////////////////////////////////////////////////////////
1720
1721 void cv::ocl::repeat(const oclMat & src, int ny, int nx, oclMat & dst)
1722 {
1723     CV_Assert(nx > 0 && ny > 0);
1724     dst.create(src.rows * ny, src.cols * nx, src.type());
1725
1726     for (int y = 0; y < ny; ++y)
1727         for (int x = 0; x < nx; ++x)
1728         {
1729             Rect roi(x * src.cols, y * src.rows, src.cols, src.rows);
1730             oclMat hdr = dst(roi);
1731             src.copyTo(hdr);
1732         }
1733 }