Merge pull request #1748 from SpecLad:merge-2.4
[profile/ivi/opencv.git] / modules / ocl / include / opencv2 / ocl.hpp
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 // Redistribution and use in source and binary forms, with or without modification,
19 // are permitted provided that the following conditions are met:
20 //
21 //   * Redistribution's of source code must retain the above copyright notice,
22 //     this list of conditions and the following disclaimer.
23 //
24 //   * Redistribution's in binary form must reproduce the above copyright notice,
25 //     this list of conditions and the following disclaimer in the documentation
26 //     and/or other materials provided with the distribution.
27 //
28 //   * The name of the copyright holders may not be used to endorse or promote products
29 //     derived from this software without specific prior written permission.
30 //
31 // This software is provided by the copyright holders and contributors "as is" and
32 // any express or implied warranties, including, but not limited to, the implied
33 // warranties of merchantability and fitness for a particular purpose are disclaimed.
34 // In no event shall the Intel Corporation or contributors be liable for any direct,
35 // indirect, incidental, special, exemplary, or consequential damages
36 // (including, but not limited to, procurement of substitute goods or services;
37 // loss of use, data, or profits; or business interruption) however caused
38 // and on any theory of liability, whether in contract, strict liability,
39 // or tort (including negligence or otherwise) arising in any way out of
40 // the use of this software, even if advised of the possibility of such damage.
41 //
42 //M*/
43
44 #ifndef __OPENCV_OCL_HPP__
45 #define __OPENCV_OCL_HPP__
46
47 #include <memory>
48 #include <vector>
49
50 #include "opencv2/core.hpp"
51 #include "opencv2/imgproc.hpp"
52 #include "opencv2/objdetect.hpp"
53 #include "opencv2/ml.hpp"
54
55 namespace cv
56 {
57     namespace ocl
58     {
59         enum DeviceType
60         {
61             CVCL_DEVICE_TYPE_DEFAULT     = (1 << 0),
62             CVCL_DEVICE_TYPE_CPU         = (1 << 1),
63             CVCL_DEVICE_TYPE_GPU         = (1 << 2),
64             CVCL_DEVICE_TYPE_ACCELERATOR = (1 << 3),
65             //CVCL_DEVICE_TYPE_CUSTOM      = (1 << 4)
66             CVCL_DEVICE_TYPE_ALL         = 0xFFFFFFFF
67         };
68
69         enum DevMemRW
70         {
71             DEVICE_MEM_R_W = 0,
72             DEVICE_MEM_R_ONLY,
73             DEVICE_MEM_W_ONLY
74         };
75
76         enum DevMemType
77         {
78             DEVICE_MEM_DEFAULT = 0,
79             DEVICE_MEM_AHP,         //alloc host pointer
80             DEVICE_MEM_UHP,         //use host pointer
81             DEVICE_MEM_CHP,         //copy host pointer
82             DEVICE_MEM_PM           //persistent memory
83         };
84
85         // these classes contain OpenCL runtime information
86
87         struct PlatformInfo;
88
89         struct DeviceInfo
90         {
91         public:
92             int _id; // reserved, don't use it
93
94             DeviceType deviceType;
95             std::string deviceProfile;
96             std::string deviceVersion;
97             std::string deviceName;
98             std::string deviceVendor;
99             int deviceVendorId;
100             std::string deviceDriverVersion;
101             std::string deviceExtensions;
102
103             size_t maxWorkGroupSize;
104             std::vector<size_t> maxWorkItemSizes;
105             int maxComputeUnits;
106             size_t localMemorySize;
107             size_t maxMemAllocSize;
108
109             int deviceVersionMajor;
110             int deviceVersionMinor;
111
112             bool haveDoubleSupport;
113             bool isUnifiedMemory; // 1 means integrated GPU, otherwise this value is 0
114             bool isIntelDevice;
115
116             std::string compilationExtraOptions;
117
118             const PlatformInfo* platform;
119
120             DeviceInfo();
121         };
122
123         struct PlatformInfo
124         {
125             int _id; // reserved, don't use it
126
127             std::string platformProfile;
128             std::string platformVersion;
129             std::string platformName;
130             std::string platformVendor;
131             std::string platformExtensons;
132
133             int platformVersionMajor;
134             int platformVersionMinor;
135
136             std::vector<const DeviceInfo*> devices;
137
138             PlatformInfo();
139         };
140
141         //////////////////////////////// Initialization & Info ////////////////////////
142         typedef std::vector<const PlatformInfo*> PlatformsInfo;
143
144         CV_EXPORTS int getOpenCLPlatforms(PlatformsInfo& platforms);
145
146         typedef std::vector<const DeviceInfo*> DevicesInfo;
147
148         CV_EXPORTS int getOpenCLDevices(DevicesInfo& devices, int deviceType = CVCL_DEVICE_TYPE_GPU,
149                 const PlatformInfo* platform = NULL);
150
151         // set device you want to use
152         CV_EXPORTS void setDevice(const DeviceInfo* info);
153
154         enum FEATURE_TYPE
155         {
156             FEATURE_CL_DOUBLE = 1,
157             FEATURE_CL_UNIFIED_MEM,
158             FEATURE_CL_VER_1_2,
159             FEATURE_CL_INTEL_DEVICE
160         };
161
162         // Represents OpenCL context, interface
163         class CV_EXPORTS Context
164         {
165         protected:
166             Context() { }
167             ~Context() { }
168         public:
169             static Context *getContext();
170
171             bool supportsFeature(FEATURE_TYPE featureType) const;
172             const DeviceInfo& getDeviceInfo() const;
173
174             const void* getOpenCLContextPtr() const;
175             const void* getOpenCLCommandQueuePtr() const;
176             const void* getOpenCLDeviceIDPtr() const;
177         };
178
179         inline const void *getClContextPtr()
180         {
181             return Context::getContext()->getOpenCLContextPtr();
182         }
183
184         inline const void *getClCommandQueuePtr()
185         {
186             return Context::getContext()->getOpenCLCommandQueuePtr();
187         }
188
189         CV_EXPORTS bool supportsFeature(FEATURE_TYPE featureType);
190
191         CV_EXPORTS void finish();
192
193         enum BINARY_CACHE_MODE
194         {
195             CACHE_NONE    = 0,        // do not cache OpenCL binary
196             CACHE_DEBUG   = 0x1 << 0, // cache OpenCL binary when built in debug mode
197             CACHE_RELEASE = 0x1 << 1, // default behavior, only cache when built in release mode
198             CACHE_ALL     = CACHE_DEBUG | CACHE_RELEASE, // cache opencl binary
199         };
200         //! Enable or disable OpenCL program binary caching onto local disk
201         // After a program (*.cl files in opencl/ folder) is built at runtime, we allow the
202         // compiled OpenCL program to be cached to the path automatically as "path/*.clb"
203         // binary file, which will be reused when the OpenCV executable is started again.
204         //
205         // This feature is enabled by default.
206         CV_EXPORTS void setBinaryDiskCache(int mode = CACHE_RELEASE, cv::String path = "./");
207
208         //! set where binary cache to be saved to
209         CV_EXPORTS void setBinaryPath(const char *path);
210
211         struct ProgramSource
212         {
213             const char* name;
214             const char* programStr;
215             const char* programHash;
216
217             // Cache in memory by name (should be unique). Caching on disk disabled.
218             inline ProgramSource(const char* _name, const char* _programStr)
219                 : name(_name), programStr(_programStr), programHash(NULL)
220             {
221             }
222
223             // Cache in memory by name (should be unique). Caching on disk uses programHash mark.
224             inline ProgramSource(const char* _name, const char* _programStr, const char* _programHash)
225                 : name(_name), programStr(_programStr), programHash(_programHash)
226             {
227             }
228         };
229
230         //! Calls OpenCL kernel. Pass globalThreads = NULL, and cleanUp = true, to finally clean-up without executing.
231         //! Deprecated, will be replaced
232         CV_EXPORTS void openCLExecuteKernelInterop(Context *clCxt,
233                 const cv::ocl::ProgramSource& source, String kernelName,
234                 size_t globalThreads[3], size_t localThreads[3],
235                 std::vector< std::pair<size_t, const void *> > &args,
236                 int channels, int depth, const char *build_options);
237
238         class CV_EXPORTS oclMatExpr;
239         //////////////////////////////// oclMat ////////////////////////////////
240         class CV_EXPORTS oclMat
241         {
242         public:
243             //! default constructor
244             oclMat();
245             //! constructs oclMatrix of the specified size and type (_type is CV_8UC1, CV_64FC3, CV_32SC(12) etc.)
246             oclMat(int rows, int cols, int type);
247             oclMat(Size size, int type);
248             //! constucts oclMatrix and fills it with the specified value _s.
249             oclMat(int rows, int cols, int type, const Scalar &s);
250             oclMat(Size size, int type, const Scalar &s);
251             //! copy constructor
252             oclMat(const oclMat &m);
253
254             //! constructor for oclMatrix headers pointing to user-allocated data
255             oclMat(int rows, int cols, int type, void *data, size_t step = Mat::AUTO_STEP);
256             oclMat(Size size, int type, void *data, size_t step = Mat::AUTO_STEP);
257
258             //! creates a matrix header for a part of the bigger matrix
259             oclMat(const oclMat &m, const Range &rowRange, const Range &colRange);
260             oclMat(const oclMat &m, const Rect &roi);
261
262             //! builds oclMat from Mat. Perfom blocking upload to device.
263             explicit oclMat (const Mat &m);
264
265             //! destructor - calls release()
266             ~oclMat();
267
268             //! assignment operators
269             oclMat &operator = (const oclMat &m);
270             //! assignment operator. Perfom blocking upload to device.
271             oclMat &operator = (const Mat &m);
272             oclMat &operator = (const oclMatExpr& expr);
273
274             //! pefroms blocking upload data to oclMat.
275             void upload(const cv::Mat &m);
276
277
278             //! downloads data from device to host memory. Blocking calls.
279             operator Mat() const;
280             void download(cv::Mat &m) const;
281
282             //! convert to _InputArray
283             operator _InputArray();
284
285             //! convert to _OutputArray
286             operator _OutputArray();
287
288             //! returns a new oclMatrix header for the specified row
289             oclMat row(int y) const;
290             //! returns a new oclMatrix header for the specified column
291             oclMat col(int x) const;
292             //! ... for the specified row span
293             oclMat rowRange(int startrow, int endrow) const;
294             oclMat rowRange(const Range &r) const;
295             //! ... for the specified column span
296             oclMat colRange(int startcol, int endcol) const;
297             oclMat colRange(const Range &r) const;
298
299             //! returns deep copy of the oclMatrix, i.e. the data is copied
300             oclMat clone() const;
301
302             //! copies those oclMatrix elements to "m" that are marked with non-zero mask elements.
303             // It calls m.create(this->size(), this->type()).
304             // It supports any data type
305             void copyTo( oclMat &m, const oclMat &mask = oclMat()) const;
306
307             //! converts oclMatrix to another datatype with optional scalng. See cvConvertScale.
308             //It supports 8UC1 8UC4 32SC1 32SC4 32FC1 32FC4
309             void convertTo( oclMat &m, int rtype, double alpha = 1, double beta = 0 ) const;
310
311             void assignTo( oclMat &m, int type = -1 ) const;
312
313             //! sets every oclMatrix element to s
314             //It supports 8UC1 8UC4 32SC1 32SC4 32FC1 32FC4
315             oclMat& operator = (const Scalar &s);
316             //! sets some of the oclMatrix elements to s, according to the mask
317             //It supports 8UC1 8UC4 32SC1 32SC4 32FC1 32FC4
318             oclMat& setTo(const Scalar &s, const oclMat &mask = oclMat());
319             //! creates alternative oclMatrix header for the same data, with different
320             // number of channels and/or different number of rows. see cvReshape.
321             oclMat reshape(int cn, int rows = 0) const;
322
323             //! allocates new oclMatrix data unless the oclMatrix already has specified size and type.
324             // previous data is unreferenced if needed.
325             void create(int rows, int cols, int type);
326             void create(Size size, int type);
327
328             //! allocates new oclMatrix with specified device memory type.
329             void createEx(int rows, int cols, int type,
330                           DevMemRW rw_type, DevMemType mem_type);
331             void createEx(Size size, int type, DevMemRW rw_type,
332                           DevMemType mem_type);
333
334             //! decreases reference counter;
335             // deallocate the data when reference counter reaches 0.
336             void release();
337
338             //! swaps with other smart pointer
339             void swap(oclMat &mat);
340
341             //! locates oclMatrix header within a parent oclMatrix. See below
342             void locateROI( Size &wholeSize, Point &ofs ) const;
343             //! moves/resizes the current oclMatrix ROI inside the parent oclMatrix.
344             oclMat& adjustROI( int dtop, int dbottom, int dleft, int dright );
345             //! extracts a rectangular sub-oclMatrix
346             // (this is a generalized form of row, rowRange etc.)
347             oclMat operator()( Range rowRange, Range colRange ) const;
348             oclMat operator()( const Rect &roi ) const;
349
350             oclMat& operator+=( const oclMat& m );
351             oclMat& operator-=( const oclMat& m );
352             oclMat& operator*=( const oclMat& m );
353             oclMat& operator/=( const oclMat& m );
354
355             //! returns true if the oclMatrix data is continuous
356             // (i.e. when there are no gaps between successive rows).
357             // similar to CV_IS_oclMat_CONT(cvoclMat->type)
358             bool isContinuous() const;
359             //! returns element size in bytes,
360             // similar to CV_ELEM_SIZE(cvMat->type)
361             size_t elemSize() const;
362             //! returns the size of element channel in bytes.
363             size_t elemSize1() const;
364             //! returns element type, similar to CV_MAT_TYPE(cvMat->type)
365             int type() const;
366             //! returns element type, i.e. 8UC3 returns 8UC4 because in ocl
367             //! 3 channels element actually use 4 channel space
368             int ocltype() const;
369             //! returns element type, similar to CV_MAT_DEPTH(cvMat->type)
370             int depth() const;
371             //! returns element type, similar to CV_MAT_CN(cvMat->type)
372             int channels() const;
373             //! returns element type, return 4 for 3 channels element,
374             //!becuase 3 channels element actually use 4 channel space
375             int oclchannels() const;
376             //! returns step/elemSize1()
377             size_t step1() const;
378             //! returns oclMatrix size:
379             // width == number of columns, height == number of rows
380             Size size() const;
381             //! returns true if oclMatrix data is NULL
382             bool empty() const;
383
384             //! returns pointer to y-th row
385             uchar* ptr(int y = 0);
386             const uchar *ptr(int y = 0) const;
387
388             //! template version of the above method
389             template<typename _Tp> _Tp *ptr(int y = 0);
390             template<typename _Tp> const _Tp *ptr(int y = 0) const;
391
392             //! matrix transposition
393             oclMat t() const;
394
395             /*! includes several bit-fields:
396               - the magic signature
397               - continuity flag
398               - depth
399               - number of channels
400               */
401             int flags;
402             //! the number of rows and columns
403             int rows, cols;
404             //! a distance between successive rows in bytes; includes the gap if any
405             size_t step;
406             //! pointer to the data(OCL memory object)
407             uchar *data;
408
409             //! pointer to the reference counter;
410             // when oclMatrix points to user-allocated data, the pointer is NULL
411             int *refcount;
412
413             //! helper fields used in locateROI and adjustROI
414             //datastart and dataend are not used in current version
415             uchar *datastart;
416             uchar *dataend;
417
418             //! OpenCL context associated with the oclMat object.
419             Context *clCxt; // TODO clCtx
420             //add offset for handle ROI, calculated in byte
421             int offset;
422             //add wholerows and wholecols for the whole matrix, datastart and dataend are no longer used
423             int wholerows;
424             int wholecols;
425         };
426
427         // convert InputArray/OutputArray to oclMat references
428         CV_EXPORTS oclMat& getOclMatRef(InputArray src);
429         CV_EXPORTS oclMat& getOclMatRef(OutputArray src);
430
431         ///////////////////// mat split and merge /////////////////////////////////
432         //! Compose a multi-channel array from several single-channel arrays
433         // Support all types
434         CV_EXPORTS void merge(const oclMat *src, size_t n, oclMat &dst);
435         CV_EXPORTS void merge(const std::vector<oclMat> &src, oclMat &dst);
436
437         //! Divides multi-channel array into several single-channel arrays
438         // Support all types
439         CV_EXPORTS void split(const oclMat &src, oclMat *dst);
440         CV_EXPORTS void split(const oclMat &src, std::vector<oclMat> &dst);
441
442         ////////////////////////////// Arithmetics ///////////////////////////////////
443
444         //! adds one matrix to another with scale (dst = src1 * alpha + src2 * beta + gama)
445         // supports all data types
446         CV_EXPORTS void addWeighted(const oclMat &src1, double  alpha, const oclMat &src2, double beta, double gama, oclMat &dst);
447
448         //! adds one matrix to another (dst = src1 + src2)
449         // supports all data types
450         CV_EXPORTS void add(const oclMat &src1, const oclMat &src2, oclMat &dst, const oclMat &mask = oclMat());
451         //! adds scalar to a matrix (dst = src1 + s)
452         // supports all data types
453         CV_EXPORTS void add(const oclMat &src1, const Scalar &s, oclMat &dst, const oclMat &mask = oclMat());
454
455         //! subtracts one matrix from another (dst = src1 - src2)
456         // supports all data types
457         CV_EXPORTS void subtract(const oclMat &src1, const oclMat &src2, oclMat &dst, const oclMat &mask = oclMat());
458         //! subtracts scalar from a matrix (dst = src1 - s)
459         // supports all data types
460         CV_EXPORTS void subtract(const oclMat &src1, const Scalar &s, oclMat &dst, const oclMat &mask = oclMat());
461
462         //! computes element-wise product of the two arrays (dst = src1 * scale * src2)
463         // supports all data types
464         CV_EXPORTS void multiply(const oclMat &src1, const oclMat &src2, oclMat &dst, double scale = 1);
465         //! multiplies matrix to a number (dst = scalar * src)
466         // supports all data types
467         CV_EXPORTS void multiply(double scalar, const oclMat &src, oclMat &dst);
468
469         //! computes element-wise quotient of the two arrays (dst = src1 * scale / src2)
470         // supports all data types
471         CV_EXPORTS void divide(const oclMat &src1, const oclMat &src2, oclMat &dst, double scale = 1);
472         //! computes element-wise quotient of the two arrays (dst = scale / src)
473         // supports all data types
474         CV_EXPORTS void divide(double scale, const oclMat &src1, oclMat &dst);
475
476         //! computes element-wise minimum of the two arrays (dst = min(src1, src2))
477         // supports all data types
478         CV_EXPORTS void min(const oclMat &src1, const oclMat &src2, oclMat &dst);
479
480         //! computes element-wise maximum of the two arrays (dst = max(src1, src2))
481         // supports all data types
482         CV_EXPORTS void max(const oclMat &src1, const oclMat &src2, oclMat &dst);
483
484         //! compares elements of two arrays (dst = src1 <cmpop> src2)
485         // supports all data types
486         CV_EXPORTS void compare(const oclMat &src1, const oclMat &src2, oclMat &dst, int cmpop);
487
488         //! transposes the matrix
489         // supports all data types
490         CV_EXPORTS void transpose(const oclMat &src, oclMat &dst);
491
492         //! computes element-wise absolute values of an array (dst = abs(src))
493         // supports all data types
494         CV_EXPORTS void abs(const oclMat &src, oclMat &dst);
495
496         //! computes element-wise absolute difference of two arrays (dst = abs(src1 - src2))
497         // supports all data types
498         CV_EXPORTS void absdiff(const oclMat &src1, const oclMat &src2, oclMat &dst);
499         //! computes element-wise absolute difference of array and scalar (dst = abs(src1 - s))
500         // supports all data types
501         CV_EXPORTS void absdiff(const oclMat &src1, const Scalar &s, oclMat &dst);
502
503         //! computes mean value and standard deviation of all or selected array elements
504         // supports all data types
505         CV_EXPORTS void meanStdDev(const oclMat &mtx, Scalar &mean, Scalar &stddev);
506
507         //! computes norm of array
508         // supports NORM_INF, NORM_L1, NORM_L2
509         // supports all data types
510         CV_EXPORTS double norm(const oclMat &src1, int normType = NORM_L2);
511
512         //! computes norm of the difference between two arrays
513         // supports NORM_INF, NORM_L1, NORM_L2
514         // supports all data types
515         CV_EXPORTS double norm(const oclMat &src1, const oclMat &src2, int normType = NORM_L2);
516
517         //! reverses the order of the rows, columns or both in a matrix
518         // supports all types
519         CV_EXPORTS void flip(const oclMat &src, oclMat &dst, int flipCode);
520
521         //! computes sum of array elements
522         // support all types
523         CV_EXPORTS Scalar sum(const oclMat &m);
524         CV_EXPORTS Scalar absSum(const oclMat &m);
525         CV_EXPORTS Scalar sqrSum(const oclMat &m);
526
527         //! finds global minimum and maximum array elements and returns their values
528         // support all C1 types
529         CV_EXPORTS void minMax(const oclMat &src, double *minVal, double *maxVal = 0, const oclMat &mask = oclMat());
530
531         //! finds global minimum and maximum array elements and returns their values with locations
532         // support all C1 types
533         CV_EXPORTS void minMaxLoc(const oclMat &src, double *minVal, double *maxVal = 0, Point *minLoc = 0, Point *maxLoc = 0,
534                                   const oclMat &mask = oclMat());
535
536         //! counts non-zero array elements
537         // support all types
538         CV_EXPORTS int countNonZero(const oclMat &src);
539
540         //! transforms 8-bit unsigned integers using lookup table: dst(i)=lut(src(i))
541         // destination array will have the depth type as lut and the same channels number as source
542         //It supports 8UC1 8UC4 only
543         CV_EXPORTS void LUT(const oclMat &src, const oclMat &lut, oclMat &dst);
544
545         //! only 8UC1 and 256 bins is supported now
546         CV_EXPORTS void calcHist(const oclMat &mat_src, oclMat &mat_hist);
547         //! only 8UC1 and 256 bins is supported now
548         CV_EXPORTS void equalizeHist(const oclMat &mat_src, oclMat &mat_dst);
549
550         //! only 8UC1 is supported now
551         CV_EXPORTS Ptr<cv::CLAHE> createCLAHE(double clipLimit = 40.0, Size tileGridSize = Size(8, 8));
552
553         //! bilateralFilter
554         // supports 8UC1 8UC4
555         CV_EXPORTS void bilateralFilter(const oclMat& src, oclMat& dst, int d, double sigmaColor, double sigmaSpace, int borderType=BORDER_DEFAULT);
556
557         //! Applies an adaptive bilateral filter to the input image
558         //  This is not truly a bilateral filter. Instead of using user provided fixed parameters,
559         //  the function calculates a constant at each window based on local standard deviation,
560         //  and use this constant to do filtering.
561         //  supports 8UC1, 8UC3
562         CV_EXPORTS void adaptiveBilateralFilter(const oclMat& src, oclMat& dst, Size ksize, double sigmaSpace, Point anchor = Point(-1, -1), int borderType=BORDER_DEFAULT);
563
564         //! computes exponent of each matrix element (dst = e**src)
565         // supports only CV_32FC1, CV_64FC1 type
566         CV_EXPORTS void exp(const oclMat &src, oclMat &dst);
567
568         //! computes natural logarithm of absolute value of each matrix element: dst = log(abs(src))
569         // supports only CV_32FC1, CV_64FC1 type
570         CV_EXPORTS void log(const oclMat &src, oclMat &dst);
571
572         //! computes magnitude of each (x(i), y(i)) vector
573         // supports only CV_32F, CV_64F type
574         CV_EXPORTS void magnitude(const oclMat &x, const oclMat &y, oclMat &magnitude);
575
576         //! computes angle (angle(i)) of each (x(i), y(i)) vector
577         // supports only CV_32F, CV_64F type
578         CV_EXPORTS void phase(const oclMat &x, const oclMat &y, oclMat &angle, bool angleInDegrees = false);
579
580         //! the function raises every element of tne input array to p
581         // support only CV_32F, CV_64F type
582         CV_EXPORTS void pow(const oclMat &x, double p, oclMat &y);
583
584         //! converts Cartesian coordinates to polar
585         // supports only CV_32F CV_64F type
586         CV_EXPORTS void cartToPolar(const oclMat &x, const oclMat &y, oclMat &magnitude, oclMat &angle, bool angleInDegrees = false);
587
588         //! converts polar coordinates to Cartesian
589         // supports only CV_32F CV_64F type
590         CV_EXPORTS void polarToCart(const oclMat &magnitude, const oclMat &angle, oclMat &x, oclMat &y, bool angleInDegrees = false);
591
592         //! perfroms per-elements bit-wise inversion
593         // supports all types
594         CV_EXPORTS void bitwise_not(const oclMat &src, oclMat &dst);
595
596         //! calculates per-element bit-wise disjunction of two arrays
597         // supports all types
598         CV_EXPORTS void bitwise_or(const oclMat &src1, const oclMat &src2, oclMat &dst, const oclMat &mask = oclMat());
599         CV_EXPORTS void bitwise_or(const oclMat &src1, const Scalar &s, oclMat &dst, const oclMat &mask = oclMat());
600
601         //! calculates per-element bit-wise conjunction of two arrays
602         // supports all types
603         CV_EXPORTS void bitwise_and(const oclMat &src1, const oclMat &src2, oclMat &dst, const oclMat &mask = oclMat());
604         CV_EXPORTS void bitwise_and(const oclMat &src1, const Scalar &s, oclMat &dst, const oclMat &mask = oclMat());
605
606         //! calculates per-element bit-wise "exclusive or" operation
607         // supports all types
608         CV_EXPORTS void bitwise_xor(const oclMat &src1, const oclMat &src2, oclMat &dst, const oclMat &mask = oclMat());
609         CV_EXPORTS void bitwise_xor(const oclMat &src1, const Scalar &s, oclMat &dst, const oclMat &mask = oclMat());
610
611         //! Logical operators
612         CV_EXPORTS oclMat operator ~ (const oclMat &);
613         CV_EXPORTS oclMat operator | (const oclMat &, const oclMat &);
614         CV_EXPORTS oclMat operator & (const oclMat &, const oclMat &);
615         CV_EXPORTS oclMat operator ^ (const oclMat &, const oclMat &);
616
617
618         //! Mathematics operators
619         CV_EXPORTS oclMatExpr operator + (const oclMat &src1, const oclMat &src2);
620         CV_EXPORTS oclMatExpr operator - (const oclMat &src1, const oclMat &src2);
621         CV_EXPORTS oclMatExpr operator * (const oclMat &src1, const oclMat &src2);
622         CV_EXPORTS oclMatExpr operator / (const oclMat &src1, const oclMat &src2);
623
624         struct CV_EXPORTS ConvolveBuf
625         {
626             Size result_size;
627             Size block_size;
628             Size user_block_size;
629             Size dft_size;
630
631             oclMat image_spect, templ_spect, result_spect;
632             oclMat image_block, templ_block, result_data;
633
634             void create(Size image_size, Size templ_size);
635             static Size estimateBlockSize(Size result_size, Size templ_size);
636         };
637
638         //! computes convolution of two images, may use discrete Fourier transform
639         // support only CV_32FC1 type
640         CV_EXPORTS void convolve(const oclMat &image, const oclMat &temp1, oclMat &result, bool ccorr = false);
641         CV_EXPORTS void convolve(const oclMat &image, const oclMat &temp1, oclMat &result, bool ccorr, ConvolveBuf& buf);
642
643         //! Performs a per-element multiplication of two Fourier spectrums.
644         //! Only full (not packed) CV_32FC2 complex spectrums in the interleaved format are supported for now.
645         //! support only CV_32FC2 type
646         CV_EXPORTS void mulSpectrums(const oclMat &a, const oclMat &b, oclMat &c, int flags, float scale, bool conjB = false);
647
648         CV_EXPORTS void cvtColor(const oclMat &src, oclMat &dst, int code, int dcn = 0);
649
650         //! initializes a scaled identity matrix
651         CV_EXPORTS void setIdentity(oclMat& src, const Scalar & val = Scalar(1));
652
653         //////////////////////////////// Filter Engine ////////////////////////////////
654
655         /*!
656           The Base Class for 1D or Row-wise Filters
657
658           This is the base class for linear or non-linear filters that process 1D data.
659           In particular, such filters are used for the "horizontal" filtering parts in separable filters.
660           */
661         class CV_EXPORTS BaseRowFilter_GPU
662         {
663         public:
664             BaseRowFilter_GPU(int ksize_, int anchor_, int bordertype_) : ksize(ksize_), anchor(anchor_), bordertype(bordertype_) {}
665             virtual ~BaseRowFilter_GPU() {}
666             virtual void operator()(const oclMat &src, oclMat &dst) = 0;
667             int ksize, anchor, bordertype;
668         };
669
670         /*!
671           The Base Class for Column-wise Filters
672
673           This is the base class for linear or non-linear filters that process columns of 2D arrays.
674           Such filters are used for the "vertical" filtering parts in separable filters.
675           */
676         class CV_EXPORTS BaseColumnFilter_GPU
677         {
678         public:
679             BaseColumnFilter_GPU(int ksize_, int anchor_, int bordertype_) : ksize(ksize_), anchor(anchor_), bordertype(bordertype_) {}
680             virtual ~BaseColumnFilter_GPU() {}
681             virtual void operator()(const oclMat &src, oclMat &dst) = 0;
682             int ksize, anchor, bordertype;
683         };
684
685         /*!
686           The Base Class for Non-Separable 2D Filters.
687
688           This is the base class for linear or non-linear 2D filters.
689           */
690         class CV_EXPORTS BaseFilter_GPU
691         {
692         public:
693             BaseFilter_GPU(const Size &ksize_, const Point &anchor_, const int &borderType_)
694                 : ksize(ksize_), anchor(anchor_), borderType(borderType_) {}
695             virtual ~BaseFilter_GPU() {}
696             virtual void operator()(const oclMat &src, oclMat &dst) = 0;
697             Size ksize;
698             Point anchor;
699             int borderType;
700         };
701
702         /*!
703           The Base Class for Filter Engine.
704
705           The class can be used to apply an arbitrary filtering operation to an image.
706           It contains all the necessary intermediate buffers.
707           */
708         class CV_EXPORTS FilterEngine_GPU
709         {
710         public:
711             virtual ~FilterEngine_GPU() {}
712
713             virtual void apply(const oclMat &src, oclMat &dst, Rect roi = Rect(0, 0, -1, -1)) = 0;
714         };
715
716         //! returns the non-separable filter engine with the specified filter
717         CV_EXPORTS Ptr<FilterEngine_GPU> createFilter2D_GPU(const Ptr<BaseFilter_GPU> filter2D);
718
719         //! returns the primitive row filter with the specified kernel
720         CV_EXPORTS Ptr<BaseRowFilter_GPU> getLinearRowFilter_GPU(int srcType, int bufType, const Mat &rowKernel,
721                 int anchor = -1, int bordertype = BORDER_DEFAULT);
722
723         //! returns the primitive column filter with the specified kernel
724         CV_EXPORTS Ptr<BaseColumnFilter_GPU> getLinearColumnFilter_GPU(int bufType, int dstType, const Mat &columnKernel,
725                 int anchor = -1, int bordertype = BORDER_DEFAULT, double delta = 0.0);
726
727         //! returns the separable linear filter engine
728         CV_EXPORTS Ptr<FilterEngine_GPU> createSeparableLinearFilter_GPU(int srcType, int dstType, const Mat &rowKernel,
729                 const Mat &columnKernel, const Point &anchor = Point(-1, -1), double delta = 0.0, int bordertype = BORDER_DEFAULT);
730
731         //! returns the separable filter engine with the specified filters
732         CV_EXPORTS Ptr<FilterEngine_GPU> createSeparableFilter_GPU(const Ptr<BaseRowFilter_GPU> &rowFilter,
733                 const Ptr<BaseColumnFilter_GPU> &columnFilter);
734
735         //! returns the Gaussian filter engine
736         CV_EXPORTS Ptr<FilterEngine_GPU> createGaussianFilter_GPU(int type, Size ksize, double sigma1, double sigma2 = 0, int bordertype = BORDER_DEFAULT);
737
738         //! returns filter engine for the generalized Sobel operator
739         CV_EXPORTS Ptr<FilterEngine_GPU> createDerivFilter_GPU( int srcType, int dstType, int dx, int dy, int ksize, int borderType = BORDER_DEFAULT );
740
741         //! applies Laplacian operator to the image
742         // supports only ksize = 1 and ksize = 3
743         CV_EXPORTS void Laplacian(const oclMat &src, oclMat &dst, int ddepth, int ksize = 1, double scale = 1,
744                 double delta=0, int borderType=BORDER_DEFAULT);
745
746         //! returns 2D box filter
747         // dst type must be the same as source type
748         CV_EXPORTS Ptr<BaseFilter_GPU> getBoxFilter_GPU(int srcType, int dstType,
749                 const Size &ksize, Point anchor = Point(-1, -1), int borderType = BORDER_DEFAULT);
750
751         //! returns box filter engine
752         CV_EXPORTS Ptr<FilterEngine_GPU> createBoxFilter_GPU(int srcType, int dstType, const Size &ksize,
753                 const Point &anchor = Point(-1, -1), int borderType = BORDER_DEFAULT);
754
755         //! returns 2D filter with the specified kernel
756         // supports: dst type must be the same as source type
757         CV_EXPORTS Ptr<BaseFilter_GPU> getLinearFilter_GPU(int srcType, int dstType, const Mat &kernel, const Size &ksize,
758                 const Point &anchor = Point(-1, -1), int borderType = BORDER_DEFAULT);
759
760         //! returns the non-separable linear filter engine
761         // supports: dst type must be the same as source type
762         CV_EXPORTS Ptr<FilterEngine_GPU> createLinearFilter_GPU(int srcType, int dstType, const Mat &kernel,
763                 const Point &anchor = Point(-1, -1), int borderType = BORDER_DEFAULT);
764
765         //! smooths the image using the normalized box filter
766         CV_EXPORTS void boxFilter(const oclMat &src, oclMat &dst, int ddepth, Size ksize,
767                                   Point anchor = Point(-1, -1), int borderType = BORDER_DEFAULT);
768
769         //! returns 2D morphological filter
770         //! only MORPH_ERODE and MORPH_DILATE are supported
771         // supports CV_8UC1, CV_8UC4, CV_32FC1 and CV_32FC4 types
772         // kernel must have CV_8UC1 type, one rows and cols == ksize.width * ksize.height
773         CV_EXPORTS Ptr<BaseFilter_GPU> getMorphologyFilter_GPU(int op, int type, const Mat &kernel, const Size &ksize,
774                 Point anchor = Point(-1, -1));
775
776         //! returns morphological filter engine. Only MORPH_ERODE and MORPH_DILATE are supported.
777         CV_EXPORTS Ptr<FilterEngine_GPU> createMorphologyFilter_GPU(int op, int type, const Mat &kernel,
778                 const Point &anchor = Point(-1, -1), int iterations = 1);
779
780         //! a synonym for normalized box filter
781         static inline void blur(const oclMat &src, oclMat &dst, Size ksize, Point anchor = Point(-1, -1),
782                                 int borderType = BORDER_CONSTANT)
783         {
784             boxFilter(src, dst, -1, ksize, anchor, borderType);
785         }
786
787         //! applies non-separable 2D linear filter to the image
788         CV_EXPORTS void filter2D(const oclMat &src, oclMat &dst, int ddepth, const Mat &kernel,
789                                  Point anchor = Point(-1, -1), double delta = 0.0, int borderType = BORDER_DEFAULT);
790
791         //! applies separable 2D linear filter to the image
792         CV_EXPORTS void sepFilter2D(const oclMat &src, oclMat &dst, int ddepth, const Mat &kernelX, const Mat &kernelY,
793                                     Point anchor = Point(-1, -1), double delta = 0.0, int bordertype = BORDER_DEFAULT);
794
795         //! applies generalized Sobel operator to the image
796         // dst.type must equalize src.type
797         // supports data type: CV_8UC1, CV_8UC4, CV_32FC1 and CV_32FC4
798         // supports border type: BORDER_CONSTANT, BORDER_REPLICATE, BORDER_REFLECT,BORDER_REFLECT_101
799         CV_EXPORTS void Sobel(const oclMat &src, oclMat &dst, int ddepth, int dx, int dy, int ksize = 3, double scale = 1, double delta = 0.0, int bordertype = BORDER_DEFAULT);
800
801         //! applies the vertical or horizontal Scharr operator to the image
802         // dst.type must equalize src.type
803         // supports data type: CV_8UC1, CV_8UC4, CV_32FC1 and CV_32FC4
804         // supports border type: BORDER_CONSTANT, BORDER_REPLICATE, BORDER_REFLECT,BORDER_REFLECT_101
805         CV_EXPORTS void Scharr(const oclMat &src, oclMat &dst, int ddepth, int dx, int dy, double scale = 1, double delta = 0.0, int bordertype = BORDER_DEFAULT);
806
807         //! smooths the image using Gaussian filter.
808         // dst.type must equalize src.type
809         // supports data type: CV_8UC1, CV_8UC4, CV_32FC1 and CV_32FC4
810         // supports border type: BORDER_CONSTANT, BORDER_REPLICATE, BORDER_REFLECT,BORDER_REFLECT_101
811         CV_EXPORTS void GaussianBlur(const oclMat &src, oclMat &dst, Size ksize, double sigma1, double sigma2 = 0, int bordertype = BORDER_DEFAULT);
812
813         //! erodes the image (applies the local minimum operator)
814         // supports data type: CV_8UC1, CV_8UC4, CV_32FC1 and CV_32FC4
815         CV_EXPORTS void erode( const oclMat &src, oclMat &dst, const Mat &kernel, Point anchor = Point(-1, -1), int iterations = 1,
816
817                                int borderType = BORDER_CONSTANT, const Scalar &borderValue = morphologyDefaultBorderValue());
818
819
820         //! dilates the image (applies the local maximum operator)
821         // supports data type: CV_8UC1, CV_8UC4, CV_32FC1 and CV_32FC4
822         CV_EXPORTS void dilate( const oclMat &src, oclMat &dst, const Mat &kernel, Point anchor = Point(-1, -1), int iterations = 1,
823
824                                 int borderType = BORDER_CONSTANT, const Scalar &borderValue = morphologyDefaultBorderValue());
825
826
827         //! applies an advanced morphological operation to the image
828         CV_EXPORTS void morphologyEx( const oclMat &src, oclMat &dst, int op, const Mat &kernel, Point anchor = Point(-1, -1), int iterations = 1,
829
830                                       int borderType = BORDER_CONSTANT, const Scalar &borderValue = morphologyDefaultBorderValue());
831
832
833         ////////////////////////////// Image processing //////////////////////////////
834         //! Does mean shift filtering on GPU.
835         CV_EXPORTS void meanShiftFiltering(const oclMat &src, oclMat &dst, int sp, int sr,
836                                            TermCriteria criteria = TermCriteria(TermCriteria::MAX_ITER + TermCriteria::EPS, 5, 1));
837
838         //! Does mean shift procedure on GPU.
839         CV_EXPORTS void meanShiftProc(const oclMat &src, oclMat &dstr, oclMat &dstsp, int sp, int sr,
840                                       TermCriteria criteria = TermCriteria(TermCriteria::MAX_ITER + TermCriteria::EPS, 5, 1));
841
842         //! Does mean shift segmentation with elimiation of small regions.
843         CV_EXPORTS void meanShiftSegmentation(const oclMat &src, Mat &dst, int sp, int sr, int minsize,
844                                               TermCriteria criteria = TermCriteria(TermCriteria::MAX_ITER + TermCriteria::EPS, 5, 1));
845
846         //! applies fixed threshold to the image.
847         // supports CV_8UC1 and CV_32FC1 data type
848         // supports threshold type: THRESH_BINARY, THRESH_BINARY_INV, THRESH_TRUNC, THRESH_TOZERO, THRESH_TOZERO_INV
849         CV_EXPORTS double threshold(const oclMat &src, oclMat &dst, double thresh, double maxVal, int type = THRESH_TRUNC);
850
851         //! resizes the image
852         // Supports INTER_NEAREST, INTER_LINEAR
853         // supports CV_8UC1, CV_8UC4, CV_32FC1 and CV_32FC4 types
854         CV_EXPORTS void resize(const oclMat &src, oclMat &dst, Size dsize, double fx = 0, double fy = 0, int interpolation = INTER_LINEAR);
855
856         //! Applies a generic geometrical transformation to an image.
857
858         // Supports INTER_NEAREST, INTER_LINEAR.
859         // Map1 supports CV_16SC2, CV_32FC2  types.
860         // Src supports CV_8UC1, CV_8UC2, CV_8UC4.
861         CV_EXPORTS void remap(const oclMat &src, oclMat &dst, oclMat &map1, oclMat &map2, int interpolation, int bordertype, const Scalar &value = Scalar());
862
863         //! copies 2D array to a larger destination array and pads borders with user-specifiable constant
864         // supports CV_8UC1, CV_8UC4, CV_32SC1 types
865         CV_EXPORTS void copyMakeBorder(const oclMat &src, oclMat &dst, int top, int bottom, int left, int right, int boardtype, const Scalar &value = Scalar());
866
867         //! Smoothes image using median filter
868         // The source 1- or 4-channel image. m should be 3 or 5, the image depth should be CV_8U or CV_32F.
869         CV_EXPORTS void medianFilter(const oclMat &src, oclMat &dst, int m);
870
871         //! warps the image using affine transformation
872         // Supports INTER_NEAREST, INTER_LINEAR, INTER_CUBIC
873         // supports CV_8UC1, CV_8UC4, CV_32FC1 and CV_32FC4 types
874         CV_EXPORTS void warpAffine(const oclMat &src, oclMat &dst, const Mat &M, Size dsize, int flags = INTER_LINEAR);
875
876         //! warps the image using perspective transformation
877         // Supports INTER_NEAREST, INTER_LINEAR, INTER_CUBIC
878         // supports CV_8UC1, CV_8UC4, CV_32FC1 and CV_32FC4 types
879         CV_EXPORTS void warpPerspective(const oclMat &src, oclMat &dst, const Mat &M, Size dsize, int flags = INTER_LINEAR);
880
881         //! computes the integral image and integral for the squared image
882         // sum will have CV_32S type, sqsum - CV32F type
883         // supports only CV_8UC1 source type
884         CV_EXPORTS void integral(const oclMat &src, oclMat &sum, oclMat &sqsum);
885         CV_EXPORTS void integral(const oclMat &src, oclMat &sum);
886         CV_EXPORTS void cornerHarris(const oclMat &src, oclMat &dst, int blockSize, int ksize, double k, int bordertype = cv::BORDER_DEFAULT);
887         CV_EXPORTS void cornerHarris_dxdy(const oclMat &src, oclMat &dst, oclMat &Dx, oclMat &Dy,
888             int blockSize, int ksize, double k, int bordertype = cv::BORDER_DEFAULT);
889         CV_EXPORTS void cornerMinEigenVal(const oclMat &src, oclMat &dst, int blockSize, int ksize, int bordertype = cv::BORDER_DEFAULT);
890         CV_EXPORTS void cornerMinEigenVal_dxdy(const oclMat &src, oclMat &dst, oclMat &Dx, oclMat &Dy,
891             int blockSize, int ksize, int bordertype = cv::BORDER_DEFAULT);
892
893
894         /////////////////////////////////// ML ///////////////////////////////////////////
895
896         //! Compute closest centers for each lines in source and lable it after center's index
897         // supports CV_32FC1/CV_32FC2/CV_32FC4 data type
898         // supports NORM_L1 and NORM_L2 distType
899         // if indices is provided, only the indexed rows will be calculated and their results are in the same
900         // order of indices
901         CV_EXPORTS void distanceToCenters(oclMat &dists, oclMat &labels, const oclMat &src, const oclMat &centers, int distType = NORM_L2SQR, const oclMat &indices = oclMat());
902
903         //!Does k-means procedure on GPU
904         // supports CV_32FC1/CV_32FC2/CV_32FC4 data type
905         CV_EXPORTS double kmeans(const oclMat &src, int K, oclMat &bestLabels,
906                                      TermCriteria criteria, int attemps, int flags, oclMat &centers);
907
908
909         ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
910         ///////////////////////////////////////////CascadeClassifier//////////////////////////////////////////////////////////////////
911         ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
912         class CV_EXPORTS OclCascadeClassifier : public  cv::CascadeClassifier
913         {
914         public:
915             void detectMultiScale(oclMat &image, CV_OUT std::vector<cv::Rect>& faces,
916                                   double scaleFactor = 1.1, int minNeighbors = 3, int flags = 0,
917                                   Size minSize = Size(), Size maxSize = Size());
918         };
919
920         /////////////////////////////// Pyramid /////////////////////////////////////
921         CV_EXPORTS void pyrDown(const oclMat &src, oclMat &dst);
922
923         //! upsamples the source image and then smoothes it
924         CV_EXPORTS void pyrUp(const oclMat &src, oclMat &dst);
925
926         //! performs linear blending of two images
927         //! to avoid accuracy errors sum of weigths shouldn't be very close to zero
928         // supports only CV_8UC1 source type
929         CV_EXPORTS void blendLinear(const oclMat &img1, const oclMat &img2, const oclMat &weights1, const oclMat &weights2, oclMat &result);
930
931         //! computes vertical sum, supports only CV_32FC1 images
932         CV_EXPORTS void columnSum(const oclMat &src, oclMat &sum);
933
934         ///////////////////////////////////////// match_template /////////////////////////////////////////////////////////////
935         struct CV_EXPORTS MatchTemplateBuf
936         {
937             Size user_block_size;
938             oclMat imagef, templf;
939             std::vector<oclMat> images;
940             std::vector<oclMat> image_sums;
941             std::vector<oclMat> image_sqsums;
942         };
943
944         //! computes the proximity map for the raster template and the image where the template is searched for
945         // Supports TM_SQDIFF, TM_SQDIFF_NORMED, TM_CCORR, TM_CCORR_NORMED, TM_CCOEFF, TM_CCOEFF_NORMED for type 8UC1 and 8UC4
946         // Supports TM_SQDIFF, TM_CCORR for type 32FC1 and 32FC4
947         CV_EXPORTS void matchTemplate(const oclMat &image, const oclMat &templ, oclMat &result, int method);
948
949         //! computes the proximity map for the raster template and the image where the template is searched for
950         // Supports TM_SQDIFF, TM_SQDIFF_NORMED, TM_CCORR, TM_CCORR_NORMED, TM_CCOEFF, TM_CCOEFF_NORMED for type 8UC1 and 8UC4
951         // Supports TM_SQDIFF, TM_CCORR for type 32FC1 and 32FC4
952         CV_EXPORTS void matchTemplate(const oclMat &image, const oclMat &templ, oclMat &result, int method, MatchTemplateBuf &buf);
953
954
955
956         ///////////////////////////////////////////// Canny /////////////////////////////////////////////
957         struct CV_EXPORTS CannyBuf;
958
959         //! compute edges of the input image using Canny operator
960         // Support CV_8UC1 only
961         CV_EXPORTS void Canny(const oclMat &image, oclMat &edges, double low_thresh, double high_thresh, int apperture_size = 3, bool L2gradient = false);
962         CV_EXPORTS void Canny(const oclMat &image, CannyBuf &buf, oclMat &edges, double low_thresh, double high_thresh, int apperture_size = 3, bool L2gradient = false);
963         CV_EXPORTS void Canny(const oclMat &dx, const oclMat &dy, oclMat &edges, double low_thresh, double high_thresh, bool L2gradient = false);
964         CV_EXPORTS void Canny(const oclMat &dx, const oclMat &dy, CannyBuf &buf, oclMat &edges, double low_thresh, double high_thresh, bool L2gradient = false);
965
966         struct CV_EXPORTS CannyBuf
967         {
968             CannyBuf() : counter(1, 1, CV_32S) { }
969             ~CannyBuf()
970             {
971                 release();
972             }
973             explicit CannyBuf(const Size &image_size, int apperture_size = 3) : counter(1, 1, CV_32S)
974             {
975                 create(image_size, apperture_size);
976             }
977             CannyBuf(const oclMat &dx_, const oclMat &dy_);
978             void create(const Size &image_size, int apperture_size = 3);
979             void release();
980
981             oclMat dx, dy;
982             oclMat dx_buf, dy_buf;
983             oclMat magBuf, mapBuf;
984             oclMat trackBuf1, trackBuf2;
985             oclMat counter;
986             Ptr<FilterEngine_GPU> filterDX, filterDY;
987         };
988
989         ///////////////////////////////////////// Hough Transform /////////////////////////////////////////
990         //! HoughCircles
991         struct HoughCirclesBuf
992         {
993             oclMat edges;
994             oclMat accum;
995             oclMat srcPoints;
996             oclMat centers;
997             CannyBuf cannyBuf;
998         };
999
1000         CV_EXPORTS void HoughCircles(const oclMat& src, oclMat& circles, int method, float dp, float minDist, int cannyThreshold, int votesThreshold, int minRadius, int maxRadius, int maxCircles = 4096);
1001         CV_EXPORTS void HoughCircles(const oclMat& src, oclMat& circles, HoughCirclesBuf& buf, int method, float dp, float minDist, int cannyThreshold, int votesThreshold, int minRadius, int maxRadius, int maxCircles = 4096);
1002         CV_EXPORTS void HoughCirclesDownload(const oclMat& d_circles, OutputArray h_circles);
1003
1004
1005         ///////////////////////////////////////// clAmdFft related /////////////////////////////////////////
1006         //! Performs a forward or inverse discrete Fourier transform (1D or 2D) of floating point matrix.
1007         //! Param dft_size is the size of DFT transform.
1008         //!
1009         //! For complex-to-real transform it is assumed that the source matrix is packed in CLFFT's format.
1010         // support src type of CV32FC1, CV32FC2
1011         // support flags: DFT_INVERSE, DFT_REAL_OUTPUT, DFT_COMPLEX_OUTPUT, DFT_ROWS
1012         // dft_size is the size of original input, which is used for transformation from complex to real.
1013         // dft_size must be powers of 2, 3 and 5
1014         // real to complex dft requires at least v1.8 clAmdFft
1015         // real to complex dft output is not the same with cpu version
1016         // real to complex and complex to real does not support DFT_ROWS
1017         CV_EXPORTS void dft(const oclMat &src, oclMat &dst, Size dft_size = Size(), int flags = 0);
1018
1019         //! implements generalized matrix product algorithm GEMM from BLAS
1020         // The functionality requires clAmdBlas library
1021         // only support type CV_32FC1
1022         // flag GEMM_3_T is not supported
1023         CV_EXPORTS void gemm(const oclMat &src1, const oclMat &src2, double alpha,
1024                              const oclMat &src3, double beta, oclMat &dst, int flags = 0);
1025
1026         //////////////// HOG (Histogram-of-Oriented-Gradients) Descriptor and Object Detector //////////////
1027
1028         struct CV_EXPORTS HOGDescriptor
1029
1030         {
1031
1032             enum { DEFAULT_WIN_SIGMA = -1 };
1033
1034             enum { DEFAULT_NLEVELS = 64 };
1035
1036             enum { DESCR_FORMAT_ROW_BY_ROW, DESCR_FORMAT_COL_BY_COL };
1037
1038
1039
1040             HOGDescriptor(Size win_size = Size(64, 128), Size block_size = Size(16, 16),
1041
1042                           Size block_stride = Size(8, 8), Size cell_size = Size(8, 8),
1043
1044                           int nbins = 9, double win_sigma = DEFAULT_WIN_SIGMA,
1045
1046                           double threshold_L2hys = 0.2, bool gamma_correction = true,
1047
1048                           int nlevels = DEFAULT_NLEVELS);
1049
1050
1051
1052             size_t getDescriptorSize() const;
1053
1054             size_t getBlockHistogramSize() const;
1055
1056
1057
1058             void setSVMDetector(const std::vector<float> &detector);
1059
1060
1061
1062             static std::vector<float> getDefaultPeopleDetector();
1063
1064             static std::vector<float> getPeopleDetector48x96();
1065
1066             static std::vector<float> getPeopleDetector64x128();
1067
1068
1069
1070             void detect(const oclMat &img, std::vector<Point> &found_locations,
1071
1072                         double hit_threshold = 0, Size win_stride = Size(),
1073
1074                         Size padding = Size());
1075
1076
1077
1078             void detectMultiScale(const oclMat &img, std::vector<Rect> &found_locations,
1079
1080                                   double hit_threshold = 0, Size win_stride = Size(),
1081
1082                                   Size padding = Size(), double scale0 = 1.05,
1083
1084                                   int group_threshold = 2);
1085
1086
1087
1088             void getDescriptors(const oclMat &img, Size win_stride,
1089
1090                                 oclMat &descriptors,
1091
1092                                 int descr_format = DESCR_FORMAT_COL_BY_COL);
1093
1094
1095
1096             Size win_size;
1097
1098             Size block_size;
1099
1100             Size block_stride;
1101
1102             Size cell_size;
1103
1104             int nbins;
1105
1106             double win_sigma;
1107
1108             double threshold_L2hys;
1109
1110             bool gamma_correction;
1111
1112             int nlevels;
1113
1114
1115
1116         protected:
1117
1118             // initialize buffers; only need to do once in case of multiscale detection
1119
1120             void init_buffer(const oclMat &img, Size win_stride);
1121
1122
1123
1124             void computeBlockHistograms(const oclMat &img);
1125
1126             void computeGradient(const oclMat &img, oclMat &grad, oclMat &qangle);
1127
1128
1129
1130             double getWinSigma() const;
1131
1132             bool checkDetectorSize() const;
1133
1134
1135
1136             static int numPartsWithin(int size, int part_size, int stride);
1137
1138             static Size numPartsWithin(Size size, Size part_size, Size stride);
1139
1140
1141
1142             // Coefficients of the separating plane
1143
1144             float free_coef;
1145
1146             oclMat detector;
1147
1148
1149
1150             // Results of the last classification step
1151
1152             oclMat labels;
1153
1154             Mat labels_host;
1155
1156
1157
1158             // Results of the last histogram evaluation step
1159
1160             oclMat block_hists;
1161
1162
1163
1164             // Gradients conputation results
1165
1166             oclMat grad, qangle;
1167
1168
1169
1170             // scaled image
1171
1172             oclMat image_scale;
1173
1174
1175
1176             // effect size of input image (might be different from original size after scaling)
1177
1178             Size effect_size;
1179
1180         };
1181
1182
1183         ////////////////////////feature2d_ocl/////////////////
1184         /****************************************************************************************\
1185         *                                      Distance                                          *
1186         \****************************************************************************************/
1187         template<typename T>
1188         struct CV_EXPORTS Accumulator
1189         {
1190             typedef T Type;
1191         };
1192         template<> struct Accumulator<unsigned char>
1193         {
1194             typedef float Type;
1195         };
1196         template<> struct Accumulator<unsigned short>
1197         {
1198             typedef float Type;
1199         };
1200         template<> struct Accumulator<char>
1201         {
1202             typedef float Type;
1203         };
1204         template<> struct Accumulator<short>
1205         {
1206             typedef float Type;
1207         };
1208
1209         /*
1210          * Manhattan distance (city block distance) functor
1211          */
1212         template<class T>
1213         struct CV_EXPORTS L1
1214         {
1215             enum { normType = NORM_L1 };
1216             typedef T ValueType;
1217             typedef typename Accumulator<T>::Type ResultType;
1218
1219             ResultType operator()( const T *a, const T *b, int size ) const
1220             {
1221                 return normL1<ValueType, ResultType>(a, b, size);
1222             }
1223         };
1224
1225         /*
1226          * Euclidean distance functor
1227          */
1228         template<class T>
1229         struct CV_EXPORTS L2
1230         {
1231             enum { normType = NORM_L2 };
1232             typedef T ValueType;
1233             typedef typename Accumulator<T>::Type ResultType;
1234
1235             ResultType operator()( const T *a, const T *b, int size ) const
1236             {
1237                 return (ResultType)std::sqrt((double)normL2Sqr<ValueType, ResultType>(a, b, size));
1238             }
1239         };
1240
1241         /*
1242          * Hamming distance functor - counts the bit differences between two strings - useful for the Brief descriptor
1243          * bit count of A exclusive XOR'ed with B
1244          */
1245         struct CV_EXPORTS Hamming
1246         {
1247             enum { normType = NORM_HAMMING };
1248             typedef unsigned char ValueType;
1249             typedef int ResultType;
1250
1251             /** this will count the bits in a ^ b
1252              */
1253             ResultType operator()( const unsigned char *a, const unsigned char *b, int size ) const
1254             {
1255                 return normHamming(a, b, size);
1256             }
1257         };
1258
1259         ////////////////////////////////// BruteForceMatcher //////////////////////////////////
1260
1261         class CV_EXPORTS BruteForceMatcher_OCL_base
1262         {
1263         public:
1264             enum DistType {L1Dist = 0, L2Dist, HammingDist};
1265             explicit BruteForceMatcher_OCL_base(DistType distType = L2Dist);
1266
1267             // Add descriptors to train descriptor collection
1268             void add(const std::vector<oclMat> &descCollection);
1269
1270             // Get train descriptors collection
1271             const std::vector<oclMat> &getTrainDescriptors() const;
1272
1273             // Clear train descriptors collection
1274             void clear();
1275
1276             // Return true if there are not train descriptors in collection
1277             bool empty() const;
1278
1279             // Return true if the matcher supports mask in match methods
1280             bool isMaskSupported() const;
1281
1282             // Find one best match for each query descriptor
1283             void matchSingle(const oclMat &query, const oclMat &train,
1284                              oclMat &trainIdx, oclMat &distance,
1285                              const oclMat &mask = oclMat());
1286
1287             // Download trainIdx and distance and convert it to CPU vector with DMatch
1288             static void matchDownload(const oclMat &trainIdx, const oclMat &distance, std::vector<DMatch> &matches);
1289             // Convert trainIdx and distance to vector with DMatch
1290             static void matchConvert(const Mat &trainIdx, const Mat &distance, std::vector<DMatch> &matches);
1291
1292             // Find one best match for each query descriptor
1293             void match(const oclMat &query, const oclMat &train, std::vector<DMatch> &matches, const oclMat &mask = oclMat());
1294
1295             // Make gpu collection of trains and masks in suitable format for matchCollection function
1296             void makeGpuCollection(oclMat &trainCollection, oclMat &maskCollection, const std::vector<oclMat> &masks = std::vector<oclMat>());
1297
1298             // Find one best match from train collection for each query descriptor
1299             void matchCollection(const oclMat &query, const oclMat &trainCollection,
1300                                  oclMat &trainIdx, oclMat &imgIdx, oclMat &distance,
1301                                  const oclMat &masks = oclMat());
1302
1303             // Download trainIdx, imgIdx and distance and convert it to vector with DMatch
1304             static void matchDownload(const oclMat &trainIdx, const oclMat &imgIdx, const oclMat &distance, std::vector<DMatch> &matches);
1305             // Convert trainIdx, imgIdx and distance to vector with DMatch
1306             static void matchConvert(const Mat &trainIdx, const Mat &imgIdx, const Mat &distance, std::vector<DMatch> &matches);
1307
1308             // Find one best match from train collection for each query descriptor.
1309             void match(const oclMat &query, std::vector<DMatch> &matches, const std::vector<oclMat> &masks = std::vector<oclMat>());
1310
1311             // Find k best matches for each query descriptor (in increasing order of distances)
1312             void knnMatchSingle(const oclMat &query, const oclMat &train,
1313                                 oclMat &trainIdx, oclMat &distance, oclMat &allDist, int k,
1314                                 const oclMat &mask = oclMat());
1315
1316             // Download trainIdx and distance and convert it to vector with DMatch
1317             // compactResult is used when mask is not empty. If compactResult is false matches
1318             // vector will have the same size as queryDescriptors rows. If compactResult is true
1319             // matches vector will not contain matches for fully masked out query descriptors.
1320             static void knnMatchDownload(const oclMat &trainIdx, const oclMat &distance,
1321                                          std::vector< std::vector<DMatch> > &matches, bool compactResult = false);
1322             // Convert trainIdx and distance to vector with DMatch
1323             static void knnMatchConvert(const Mat &trainIdx, const Mat &distance,
1324                                         std::vector< std::vector<DMatch> > &matches, bool compactResult = false);
1325
1326             // Find k best matches for each query descriptor (in increasing order of distances).
1327             // compactResult is used when mask is not empty. If compactResult is false matches
1328             // vector will have the same size as queryDescriptors rows. If compactResult is true
1329             // matches vector will not contain matches for fully masked out query descriptors.
1330             void knnMatch(const oclMat &query, const oclMat &train,
1331                           std::vector< std::vector<DMatch> > &matches, int k, const oclMat &mask = oclMat(),
1332                           bool compactResult = false);
1333
1334             // Find k best matches from train collection for each query descriptor (in increasing order of distances)
1335             void knnMatch2Collection(const oclMat &query, const oclMat &trainCollection,
1336                                      oclMat &trainIdx, oclMat &imgIdx, oclMat &distance,
1337                                      const oclMat &maskCollection = oclMat());
1338
1339             // Download trainIdx and distance and convert it to vector with DMatch
1340             // compactResult is used when mask is not empty. If compactResult is false matches
1341             // vector will have the same size as queryDescriptors rows. If compactResult is true
1342             // matches vector will not contain matches for fully masked out query descriptors.
1343             static void knnMatch2Download(const oclMat &trainIdx, const oclMat &imgIdx, const oclMat &distance,
1344                                           std::vector< std::vector<DMatch> > &matches, bool compactResult = false);
1345             // Convert trainIdx and distance to vector with DMatch
1346             static void knnMatch2Convert(const Mat &trainIdx, const Mat &imgIdx, const Mat &distance,
1347                                          std::vector< std::vector<DMatch> > &matches, bool compactResult = false);
1348
1349             // Find k best matches  for each query descriptor (in increasing order of distances).
1350             // compactResult is used when mask is not empty. If compactResult is false matches
1351             // vector will have the same size as queryDescriptors rows. If compactResult is true
1352             // matches vector will not contain matches for fully masked out query descriptors.
1353             void knnMatch(const oclMat &query, std::vector< std::vector<DMatch> > &matches, int k,
1354                           const std::vector<oclMat> &masks = std::vector<oclMat>(), bool compactResult = false);
1355
1356             // Find best matches for each query descriptor which have distance less than maxDistance.
1357             // nMatches.at<int>(0, queryIdx) will contain matches count for queryIdx.
1358             // carefully nMatches can be greater than trainIdx.cols - it means that matcher didn't find all matches,
1359             // because it didn't have enough memory.
1360             // If trainIdx is empty, then trainIdx and distance will be created with size nQuery x max((nTrain / 100), 10),
1361             // otherwize user can pass own allocated trainIdx and distance with size nQuery x nMaxMatches
1362             // Matches doesn't sorted.
1363             void radiusMatchSingle(const oclMat &query, const oclMat &train,
1364                                    oclMat &trainIdx, oclMat &distance, oclMat &nMatches, float maxDistance,
1365                                    const oclMat &mask = oclMat());
1366
1367             // Download trainIdx, nMatches and distance and convert it to vector with DMatch.
1368             // matches will be sorted in increasing order of distances.
1369             // compactResult is used when mask is not empty. If compactResult is false matches
1370             // vector will have the same size as queryDescriptors rows. If compactResult is true
1371             // matches vector will not contain matches for fully masked out query descriptors.
1372             static void radiusMatchDownload(const oclMat &trainIdx, const oclMat &distance, const oclMat &nMatches,
1373                                             std::vector< std::vector<DMatch> > &matches, bool compactResult = false);
1374             // Convert trainIdx, nMatches and distance to vector with DMatch.
1375             static void radiusMatchConvert(const Mat &trainIdx, const Mat &distance, const Mat &nMatches,
1376                                            std::vector< std::vector<DMatch> > &matches, bool compactResult = false);
1377
1378             // Find best matches for each query descriptor which have distance less than maxDistance
1379             // in increasing order of distances).
1380             void radiusMatch(const oclMat &query, const oclMat &train,
1381                              std::vector< std::vector<DMatch> > &matches, float maxDistance,
1382                              const oclMat &mask = oclMat(), bool compactResult = false);
1383
1384             // Find best matches for each query descriptor which have distance less than maxDistance.
1385             // If trainIdx is empty, then trainIdx and distance will be created with size nQuery x max((nQuery / 100), 10),
1386             // otherwize user can pass own allocated trainIdx and distance with size nQuery x nMaxMatches
1387             // Matches doesn't sorted.
1388             void radiusMatchCollection(const oclMat &query, oclMat &trainIdx, oclMat &imgIdx, oclMat &distance, oclMat &nMatches, float maxDistance,
1389                                        const std::vector<oclMat> &masks = std::vector<oclMat>());
1390
1391             // Download trainIdx, imgIdx, nMatches and distance and convert it to vector with DMatch.
1392             // matches will be sorted in increasing order of distances.
1393             // compactResult is used when mask is not empty. If compactResult is false matches
1394             // vector will have the same size as queryDescriptors rows. If compactResult is true
1395             // matches vector will not contain matches for fully masked out query descriptors.
1396             static void radiusMatchDownload(const oclMat &trainIdx, const oclMat &imgIdx, const oclMat &distance, const oclMat &nMatches,
1397                                             std::vector< std::vector<DMatch> > &matches, bool compactResult = false);
1398             // Convert trainIdx, nMatches and distance to vector with DMatch.
1399             static void radiusMatchConvert(const Mat &trainIdx, const Mat &imgIdx, const Mat &distance, const Mat &nMatches,
1400                                            std::vector< std::vector<DMatch> > &matches, bool compactResult = false);
1401
1402             // Find best matches from train collection for each query descriptor which have distance less than
1403             // maxDistance (in increasing order of distances).
1404             void radiusMatch(const oclMat &query, std::vector< std::vector<DMatch> > &matches, float maxDistance,
1405                              const std::vector<oclMat> &masks = std::vector<oclMat>(), bool compactResult = false);
1406
1407             DistType distType;
1408
1409         private:
1410             std::vector<oclMat> trainDescCollection;
1411         };
1412
1413         template <class Distance>
1414         class CV_EXPORTS BruteForceMatcher_OCL;
1415
1416         template <typename T>
1417         class CV_EXPORTS BruteForceMatcher_OCL< L1<T> > : public BruteForceMatcher_OCL_base
1418         {
1419         public:
1420             explicit BruteForceMatcher_OCL() : BruteForceMatcher_OCL_base(L1Dist) {}
1421             explicit BruteForceMatcher_OCL(L1<T> /*d*/) : BruteForceMatcher_OCL_base(L1Dist) {}
1422         };
1423         template <typename T>
1424         class CV_EXPORTS BruteForceMatcher_OCL< L2<T> > : public BruteForceMatcher_OCL_base
1425         {
1426         public:
1427             explicit BruteForceMatcher_OCL() : BruteForceMatcher_OCL_base(L2Dist) {}
1428             explicit BruteForceMatcher_OCL(L2<T> /*d*/) : BruteForceMatcher_OCL_base(L2Dist) {}
1429         };
1430         template <> class CV_EXPORTS BruteForceMatcher_OCL< Hamming > : public BruteForceMatcher_OCL_base
1431         {
1432         public:
1433             explicit BruteForceMatcher_OCL() : BruteForceMatcher_OCL_base(HammingDist) {}
1434             explicit BruteForceMatcher_OCL(Hamming /*d*/) : BruteForceMatcher_OCL_base(HammingDist) {}
1435         };
1436
1437         class CV_EXPORTS BFMatcher_OCL : public BruteForceMatcher_OCL_base
1438         {
1439         public:
1440             explicit BFMatcher_OCL(int norm = NORM_L2) : BruteForceMatcher_OCL_base(norm == NORM_L1 ? L1Dist : norm == NORM_L2 ? L2Dist : HammingDist) {}
1441         };
1442
1443         class CV_EXPORTS GoodFeaturesToTrackDetector_OCL
1444         {
1445         public:
1446             explicit GoodFeaturesToTrackDetector_OCL(int maxCorners = 1000, double qualityLevel = 0.01, double minDistance = 0.0,
1447                 int blockSize = 3, bool useHarrisDetector = false, double harrisK = 0.04);
1448
1449             //! return 1 rows matrix with CV_32FC2 type
1450             void operator ()(const oclMat& image, oclMat& corners, const oclMat& mask = oclMat());
1451             //! download points of type Point2f to a vector. the vector's content will be erased
1452             void downloadPoints(const oclMat &points, std::vector<Point2f> &points_v);
1453
1454             int maxCorners;
1455             double qualityLevel;
1456             double minDistance;
1457
1458             int blockSize;
1459             bool useHarrisDetector;
1460             double harrisK;
1461             void releaseMemory()
1462             {
1463                 Dx_.release();
1464                 Dy_.release();
1465                 eig_.release();
1466                 minMaxbuf_.release();
1467                 tmpCorners_.release();
1468             }
1469         private:
1470             oclMat Dx_;
1471             oclMat Dy_;
1472             oclMat eig_;
1473             oclMat minMaxbuf_;
1474             oclMat tmpCorners_;
1475         };
1476
1477         inline GoodFeaturesToTrackDetector_OCL::GoodFeaturesToTrackDetector_OCL(int maxCorners_, double qualityLevel_, double minDistance_,
1478             int blockSize_, bool useHarrisDetector_, double harrisK_)
1479         {
1480             maxCorners = maxCorners_;
1481             qualityLevel = qualityLevel_;
1482             minDistance = minDistance_;
1483             blockSize = blockSize_;
1484             useHarrisDetector = useHarrisDetector_;
1485             harrisK = harrisK_;
1486         }
1487
1488         /////////////////////////////// PyrLKOpticalFlow /////////////////////////////////////
1489
1490         class CV_EXPORTS PyrLKOpticalFlow
1491         {
1492         public:
1493             PyrLKOpticalFlow()
1494             {
1495                 winSize = Size(21, 21);
1496                 maxLevel = 3;
1497                 iters = 30;
1498                 derivLambda = 0.5;
1499                 useInitialFlow = false;
1500                 minEigThreshold = 1e-4f;
1501                 getMinEigenVals = false;
1502                 isDeviceArch11_ = false;
1503             }
1504
1505             void sparse(const oclMat &prevImg, const oclMat &nextImg, const oclMat &prevPts, oclMat &nextPts,
1506                         oclMat &status, oclMat *err = 0);
1507
1508             void dense(const oclMat &prevImg, const oclMat &nextImg, oclMat &u, oclMat &v, oclMat *err = 0);
1509
1510             Size winSize;
1511             int maxLevel;
1512             int iters;
1513             double derivLambda;
1514             bool useInitialFlow;
1515             float minEigThreshold;
1516             bool getMinEigenVals;
1517
1518             void releaseMemory()
1519             {
1520                 dx_calcBuf_.release();
1521                 dy_calcBuf_.release();
1522
1523                 prevPyr_.clear();
1524                 nextPyr_.clear();
1525
1526                 dx_buf_.release();
1527                 dy_buf_.release();
1528             }
1529
1530         private:
1531             void calcSharrDeriv(const oclMat &src, oclMat &dx, oclMat &dy);
1532
1533             void buildImagePyramid(const oclMat &img0, std::vector<oclMat> &pyr, bool withBorder);
1534
1535             oclMat dx_calcBuf_;
1536             oclMat dy_calcBuf_;
1537
1538             std::vector<oclMat> prevPyr_;
1539             std::vector<oclMat> nextPyr_;
1540
1541             oclMat dx_buf_;
1542             oclMat dy_buf_;
1543
1544             oclMat uPyr_[2];
1545             oclMat vPyr_[2];
1546
1547             bool isDeviceArch11_;
1548         };
1549
1550         class CV_EXPORTS FarnebackOpticalFlow
1551         {
1552         public:
1553             FarnebackOpticalFlow();
1554
1555             int numLevels;
1556             double pyrScale;
1557             bool fastPyramids;
1558             int winSize;
1559             int numIters;
1560             int polyN;
1561             double polySigma;
1562             int flags;
1563
1564             void operator ()(const oclMat &frame0, const oclMat &frame1, oclMat &flowx, oclMat &flowy);
1565
1566             void releaseMemory();
1567
1568         private:
1569             void prepareGaussian(
1570                 int n, double sigma, float *g, float *xg, float *xxg,
1571                 double &ig11, double &ig03, double &ig33, double &ig55);
1572
1573             void setPolynomialExpansionConsts(int n, double sigma);
1574
1575             void updateFlow_boxFilter(
1576                 const oclMat& R0, const oclMat& R1, oclMat& flowx, oclMat &flowy,
1577                 oclMat& M, oclMat &bufM, int blockSize, bool updateMatrices);
1578
1579             void updateFlow_gaussianBlur(
1580                 const oclMat& R0, const oclMat& R1, oclMat& flowx, oclMat& flowy,
1581                 oclMat& M, oclMat &bufM, int blockSize, bool updateMatrices);
1582
1583             oclMat frames_[2];
1584             oclMat pyrLevel_[2], M_, bufM_, R_[2], blurredFrame_[2];
1585             std::vector<oclMat> pyramid0_, pyramid1_;
1586         };
1587
1588         //////////////// build warping maps ////////////////////
1589         //! builds plane warping maps
1590         CV_EXPORTS void buildWarpPlaneMaps(Size src_size, Rect dst_roi, const Mat &K, const Mat &R, const Mat &T, float scale, oclMat &map_x, oclMat &map_y);
1591         //! builds cylindrical warping maps
1592         CV_EXPORTS void buildWarpCylindricalMaps(Size src_size, Rect dst_roi, const Mat &K, const Mat &R, float scale, oclMat &map_x, oclMat &map_y);
1593         //! builds spherical warping maps
1594         CV_EXPORTS void buildWarpSphericalMaps(Size src_size, Rect dst_roi, const Mat &K, const Mat &R, float scale, oclMat &map_x, oclMat &map_y);
1595         //! builds Affine warping maps
1596         CV_EXPORTS void buildWarpAffineMaps(const Mat &M, bool inverse, Size dsize, oclMat &xmap, oclMat &ymap);
1597
1598         //! builds Perspective warping maps
1599         CV_EXPORTS void buildWarpPerspectiveMaps(const Mat &M, bool inverse, Size dsize, oclMat &xmap, oclMat &ymap);
1600
1601         ///////////////////////////////////// interpolate frames //////////////////////////////////////////////
1602         //! Interpolate frames (images) using provided optical flow (displacement field).
1603         //! frame0   - frame 0 (32-bit floating point images, single channel)
1604         //! frame1   - frame 1 (the same type and size)
1605         //! fu       - forward horizontal displacement
1606         //! fv       - forward vertical displacement
1607         //! bu       - backward horizontal displacement
1608         //! bv       - backward vertical displacement
1609         //! pos      - new frame position
1610         //! newFrame - new frame
1611         //! buf      - temporary buffer, will have width x 6*height size, CV_32FC1 type and contain 6 oclMat;
1612         //!            occlusion masks            0, occlusion masks            1,
1613         //!            interpolated forward flow  0, interpolated forward flow  1,
1614         //!            interpolated backward flow 0, interpolated backward flow 1
1615         //!
1616         CV_EXPORTS void interpolateFrames(const oclMat &frame0, const oclMat &frame1,
1617                                           const oclMat &fu, const oclMat &fv,
1618                                           const oclMat &bu, const oclMat &bv,
1619                                           float pos, oclMat &newFrame, oclMat &buf);
1620
1621         //! computes moments of the rasterized shape or a vector of points
1622         //! _array should be a vector a points standing for the contour
1623         CV_EXPORTS Moments ocl_moments(InputArray contour);
1624         //! src should be a general image uploaded to the GPU.
1625         //! the supported oclMat type are CV_8UC1, CV_16UC1, CV_16SC1, CV_32FC1 and CV_64FC1
1626         //! to use type of CV_64FC1, the GPU should support CV_64FC1
1627         CV_EXPORTS Moments ocl_moments(oclMat& src, bool binary);
1628
1629         class CV_EXPORTS StereoBM_OCL
1630         {
1631         public:
1632             enum { BASIC_PRESET = 0, PREFILTER_XSOBEL = 1 };
1633
1634             enum { DEFAULT_NDISP = 64, DEFAULT_WINSZ = 19 };
1635
1636             //! the default constructor
1637             StereoBM_OCL();
1638             //! the full constructor taking the camera-specific preset, number of disparities and the SAD window size. ndisparities must be multiple of 8.
1639             StereoBM_OCL(int preset, int ndisparities = DEFAULT_NDISP, int winSize = DEFAULT_WINSZ);
1640
1641             //! the stereo correspondence operator. Finds the disparity for the specified rectified stereo pair
1642             //! Output disparity has CV_8U type.
1643             void operator() ( const oclMat &left, const oclMat &right, oclMat &disparity);
1644
1645             //! Some heuristics that tries to estmate
1646             // if current GPU will be faster then CPU in this algorithm.
1647             // It queries current active device.
1648             static bool checkIfGpuCallReasonable();
1649
1650             int preset;
1651             int ndisp;
1652             int winSize;
1653
1654             // If avergeTexThreshold  == 0 => post procesing is disabled
1655             // If avergeTexThreshold != 0 then disparity is set 0 in each point (x,y) where for left image
1656             // SumOfHorizontalGradiensInWindow(x, y, winSize) < (winSize * winSize) * avergeTexThreshold
1657             // i.e. input left image is low textured.
1658             float avergeTexThreshold;
1659         private:
1660             oclMat minSSD, leBuf, riBuf;
1661         };
1662
1663         class CV_EXPORTS StereoBeliefPropagation
1664         {
1665         public:
1666             enum { DEFAULT_NDISP  = 64 };
1667             enum { DEFAULT_ITERS  = 5  };
1668             enum { DEFAULT_LEVELS = 5  };
1669             static void estimateRecommendedParams(int width, int height, int &ndisp, int &iters, int &levels);
1670             explicit StereoBeliefPropagation(int ndisp  = DEFAULT_NDISP,
1671                                              int iters  = DEFAULT_ITERS,
1672                                              int levels = DEFAULT_LEVELS,
1673                                              int msg_type = CV_16S);
1674             StereoBeliefPropagation(int ndisp, int iters, int levels,
1675                                     float max_data_term, float data_weight,
1676                                     float max_disc_term, float disc_single_jump,
1677                                     int msg_type = CV_32F);
1678             void operator()(const oclMat &left, const oclMat &right, oclMat &disparity);
1679             void operator()(const oclMat &data, oclMat &disparity);
1680             int ndisp;
1681             int iters;
1682             int levels;
1683             float max_data_term;
1684             float data_weight;
1685             float max_disc_term;
1686             float disc_single_jump;
1687             int msg_type;
1688         private:
1689             oclMat u, d, l, r, u2, d2, l2, r2;
1690             std::vector<oclMat> datas;
1691             oclMat out;
1692         };
1693
1694         class CV_EXPORTS StereoConstantSpaceBP
1695         {
1696         public:
1697             enum { DEFAULT_NDISP    = 128 };
1698             enum { DEFAULT_ITERS    = 8   };
1699             enum { DEFAULT_LEVELS   = 4   };
1700             enum { DEFAULT_NR_PLANE = 4   };
1701             static void estimateRecommendedParams(int width, int height, int &ndisp, int &iters, int &levels, int &nr_plane);
1702             explicit StereoConstantSpaceBP(
1703                 int ndisp    = DEFAULT_NDISP,
1704                 int iters    = DEFAULT_ITERS,
1705                 int levels   = DEFAULT_LEVELS,
1706                 int nr_plane = DEFAULT_NR_PLANE,
1707                 int msg_type = CV_32F);
1708             StereoConstantSpaceBP(int ndisp, int iters, int levels, int nr_plane,
1709                 float max_data_term, float data_weight, float max_disc_term, float disc_single_jump,
1710                 int min_disp_th = 0,
1711                 int msg_type = CV_32F);
1712             void operator()(const oclMat &left, const oclMat &right, oclMat &disparity);
1713             int ndisp;
1714             int iters;
1715             int levels;
1716             int nr_plane;
1717             float max_data_term;
1718             float data_weight;
1719             float max_disc_term;
1720             float disc_single_jump;
1721             int min_disp_th;
1722             int msg_type;
1723             bool use_local_init_data_cost;
1724         private:
1725             oclMat u[2], d[2], l[2], r[2];
1726             oclMat disp_selected_pyr[2];
1727             oclMat data_cost;
1728             oclMat data_cost_selected;
1729             oclMat temp;
1730             oclMat out;
1731         };
1732
1733         // Implementation of the Zach, Pock and Bischof Dual TV-L1 Optical Flow method
1734         //
1735         // see reference:
1736         //   [1] C. Zach, T. Pock and H. Bischof, "A Duality Based Approach for Realtime TV-L1 Optical Flow".
1737         //   [2] Javier Sanchez, Enric Meinhardt-Llopis and Gabriele Facciolo. "TV-L1 Optical Flow Estimation".
1738         class CV_EXPORTS OpticalFlowDual_TVL1_OCL
1739         {
1740         public:
1741             OpticalFlowDual_TVL1_OCL();
1742
1743             void operator ()(const oclMat& I0, const oclMat& I1, oclMat& flowx, oclMat& flowy);
1744
1745             void collectGarbage();
1746
1747             /**
1748             * Time step of the numerical scheme.
1749             */
1750             double tau;
1751
1752             /**
1753             * Weight parameter for the data term, attachment parameter.
1754             * This is the most relevant parameter, which determines the smoothness of the output.
1755             * The smaller this parameter is, the smoother the solutions we obtain.
1756             * It depends on the range of motions of the images, so its value should be adapted to each image sequence.
1757             */
1758             double lambda;
1759
1760             /**
1761             * Weight parameter for (u - v)^2, tightness parameter.
1762             * It serves as a link between the attachment and the regularization terms.
1763             * In theory, it should have a small value in order to maintain both parts in correspondence.
1764             * The method is stable for a large range of values of this parameter.
1765             */
1766             double theta;
1767
1768             /**
1769             * Number of scales used to create the pyramid of images.
1770             */
1771             int nscales;
1772
1773             /**
1774             * Number of warpings per scale.
1775             * Represents the number of times that I1(x+u0) and grad( I1(x+u0) ) are computed per scale.
1776             * This is a parameter that assures the stability of the method.
1777             * It also affects the running time, so it is a compromise between speed and accuracy.
1778             */
1779             int warps;
1780
1781             /**
1782             * Stopping criterion threshold used in the numerical scheme, which is a trade-off between precision and running time.
1783             * A small value will yield more accurate solutions at the expense of a slower convergence.
1784             */
1785             double epsilon;
1786
1787             /**
1788             * Stopping criterion iterations number used in the numerical scheme.
1789             */
1790             int iterations;
1791
1792             bool useInitialFlow;
1793
1794         private:
1795             void procOneScale(const oclMat& I0, const oclMat& I1, oclMat& u1, oclMat& u2);
1796
1797             std::vector<oclMat> I0s;
1798             std::vector<oclMat> I1s;
1799             std::vector<oclMat> u1s;
1800             std::vector<oclMat> u2s;
1801
1802             oclMat I1x_buf;
1803             oclMat I1y_buf;
1804
1805             oclMat I1w_buf;
1806             oclMat I1wx_buf;
1807             oclMat I1wy_buf;
1808
1809             oclMat grad_buf;
1810             oclMat rho_c_buf;
1811
1812             oclMat p11_buf;
1813             oclMat p12_buf;
1814             oclMat p21_buf;
1815             oclMat p22_buf;
1816
1817             oclMat diff_buf;
1818             oclMat norm_buf;
1819         };
1820         // current supported sorting methods
1821         enum
1822         {
1823             SORT_BITONIC,   // only support power-of-2 buffer size
1824             SORT_SELECTION, // cannot sort duplicate keys
1825             SORT_MERGE,
1826             SORT_RADIX      // only support signed int/float keys(CV_32S/CV_32F)
1827         };
1828         //! Returns the sorted result of all the elements in input based on equivalent keys.
1829         //
1830         //  The element unit in the values to be sorted is determined from the data type,
1831         //  i.e., a CV_32FC2 input {a1a2, b1b2} will be considered as two elements, regardless its
1832         //  matrix dimension.
1833         //  both keys and values will be sorted inplace
1834         //  Key needs to be single channel oclMat.
1835         //
1836         //  Example:
1837         //  input -
1838         //    keys   = {2,    3,   1}   (CV_8UC1)
1839         //    values = {10,5, 4,3, 6,2} (CV_8UC2)
1840         //  sortByKey(keys, values, SORT_SELECTION, false);
1841         //  output -
1842         //    keys   = {1,    2,   3}   (CV_8UC1)
1843         //    values = {6,2, 10,5, 4,3} (CV_8UC2)
1844         CV_EXPORTS void sortByKey(oclMat& keys, oclMat& values, int method, bool isGreaterThan = false);
1845         /*!Base class for MOG and MOG2!*/
1846         class CV_EXPORTS BackgroundSubtractor
1847         {
1848         public:
1849             //! the virtual destructor
1850             virtual ~BackgroundSubtractor();
1851             //! the update operator that takes the next video frame and returns the current foreground mask as 8-bit binary image.
1852             virtual void operator()(const oclMat& image, oclMat& fgmask, float learningRate);
1853
1854             //! computes a background image
1855             virtual void getBackgroundImage(oclMat& backgroundImage) const = 0;
1856         };
1857                 /*!
1858         Gaussian Mixture-based Backbround/Foreground Segmentation Algorithm
1859
1860         The class implements the following algorithm:
1861         "An improved adaptive background mixture model for real-time tracking with shadow detection"
1862         P. KadewTraKuPong and R. Bowden,
1863         Proc. 2nd European Workshp on Advanced Video-Based Surveillance Systems, 2001."
1864         http://personal.ee.surrey.ac.uk/Personal/R.Bowden/publications/avbs01/avbs01.pdf
1865         */
1866         class CV_EXPORTS MOG: public cv::ocl::BackgroundSubtractor
1867         {
1868         public:
1869             //! the default constructor
1870             MOG(int nmixtures = -1);
1871
1872             //! re-initiaization method
1873             void initialize(Size frameSize, int frameType);
1874
1875             //! the update operator
1876             void operator()(const oclMat& frame, oclMat& fgmask, float learningRate = 0.f);
1877
1878             //! computes a background image which are the mean of all background gaussians
1879             void getBackgroundImage(oclMat& backgroundImage) const;
1880
1881             //! releases all inner buffers
1882             void release();
1883
1884             int history;
1885             float varThreshold;
1886             float backgroundRatio;
1887             float noiseSigma;
1888
1889         private:
1890             int nmixtures_;
1891
1892             Size frameSize_;
1893             int frameType_;
1894             int nframes_;
1895
1896             oclMat weight_;
1897             oclMat sortKey_;
1898             oclMat mean_;
1899             oclMat var_;
1900         };
1901
1902         /*!
1903         The class implements the following algorithm:
1904         "Improved adaptive Gausian mixture model for background subtraction"
1905         Z.Zivkovic
1906         International Conference Pattern Recognition, UK, August, 2004.
1907         http://www.zoranz.net/Publications/zivkovic2004ICPR.pdf
1908         */
1909         class CV_EXPORTS MOG2: public cv::ocl::BackgroundSubtractor
1910         {
1911         public:
1912             //! the default constructor
1913             MOG2(int nmixtures = -1);
1914
1915             //! re-initiaization method
1916             void initialize(Size frameSize, int frameType);
1917
1918             //! the update operator
1919             void operator()(const oclMat& frame, oclMat& fgmask, float learningRate = -1.0f);
1920
1921             //! computes a background image which are the mean of all background gaussians
1922             void getBackgroundImage(oclMat& backgroundImage) const;
1923
1924             //! releases all inner buffers
1925             void release();
1926
1927             // parameters
1928             // you should call initialize after parameters changes
1929
1930             int history;
1931
1932             //! here it is the maximum allowed number of mixture components.
1933             //! Actual number is determined dynamically per pixel
1934             float varThreshold;
1935             // threshold on the squared Mahalanobis distance to decide if it is well described
1936             // by the background model or not. Related to Cthr from the paper.
1937             // This does not influence the update of the background. A typical value could be 4 sigma
1938             // and that is varThreshold=4*4=16; Corresponds to Tb in the paper.
1939
1940             /////////////////////////
1941             // less important parameters - things you might change but be carefull
1942             ////////////////////////
1943
1944             float backgroundRatio;
1945             // corresponds to fTB=1-cf from the paper
1946             // TB - threshold when the component becomes significant enough to be included into
1947             // the background model. It is the TB=1-cf from the paper. So I use cf=0.1 => TB=0.
1948             // For alpha=0.001 it means that the mode should exist for approximately 105 frames before
1949             // it is considered foreground
1950             // float noiseSigma;
1951             float varThresholdGen;
1952
1953             //correspondts to Tg - threshold on the squared Mahalan. dist. to decide
1954             //when a sample is close to the existing components. If it is not close
1955             //to any a new component will be generated. I use 3 sigma => Tg=3*3=9.
1956             //Smaller Tg leads to more generated components and higher Tg might make
1957             //lead to small number of components but they can grow too large
1958             float fVarInit;
1959             float fVarMin;
1960             float fVarMax;
1961
1962             //initial variance  for the newly generated components.
1963             //It will will influence the speed of adaptation. A good guess should be made.
1964             //A simple way is to estimate the typical standard deviation from the images.
1965             //I used here 10 as a reasonable value
1966             // min and max can be used to further control the variance
1967             float fCT; //CT - complexity reduction prior
1968             //this is related to the number of samples needed to accept that a component
1969             //actually exists. We use CT=0.05 of all the samples. By setting CT=0 you get
1970             //the standard Stauffer&Grimson algorithm (maybe not exact but very similar)
1971
1972             //shadow detection parameters
1973             bool bShadowDetection; //default 1 - do shadow detection
1974             unsigned char nShadowDetection; //do shadow detection - insert this value as the detection result - 127 default value
1975             float fTau;
1976             // Tau - shadow threshold. The shadow is detected if the pixel is darker
1977             //version of the background. Tau is a threshold on how much darker the shadow can be.
1978             //Tau= 0.5 means that if pixel is more than 2 times darker then it is not shadow
1979             //See: Prati,Mikic,Trivedi,Cucchiarra,"Detecting Moving Shadows...",IEEE PAMI,2003.
1980
1981         private:
1982             int nmixtures_;
1983
1984             Size frameSize_;
1985             int frameType_;
1986             int nframes_;
1987
1988             oclMat weight_;
1989             oclMat variance_;
1990             oclMat mean_;
1991
1992             oclMat bgmodelUsedModes_; //keep track of number of modes per pixel
1993         };
1994
1995         /*!***************Kalman Filter*************!*/
1996         class CV_EXPORTS KalmanFilter
1997         {
1998         public:
1999             KalmanFilter();
2000             //! the full constructor taking the dimensionality of the state, of the measurement and of the control vector
2001             KalmanFilter(int dynamParams, int measureParams, int controlParams=0, int type=CV_32F);
2002             //! re-initializes Kalman filter. The previous content is destroyed.
2003             void init(int dynamParams, int measureParams, int controlParams=0, int type=CV_32F);
2004
2005             const oclMat& predict(const oclMat& control=oclMat());
2006             const oclMat& correct(const oclMat& measurement);
2007
2008             oclMat statePre;           //!< predicted state (x'(k)): x(k)=A*x(k-1)+B*u(k)
2009             oclMat statePost;          //!< corrected state (x(k)): x(k)=x'(k)+K(k)*(z(k)-H*x'(k))
2010             oclMat transitionMatrix;   //!< state transition matrix (A)
2011             oclMat controlMatrix;      //!< control matrix (B) (not used if there is no control)
2012             oclMat measurementMatrix;  //!< measurement matrix (H)
2013             oclMat processNoiseCov;    //!< process noise covariance matrix (Q)
2014             oclMat measurementNoiseCov;//!< measurement noise covariance matrix (R)
2015             oclMat errorCovPre;        //!< priori error estimate covariance matrix (P'(k)): P'(k)=A*P(k-1)*At + Q)*/
2016             oclMat gain;               //!< Kalman gain matrix (K(k)): K(k)=P'(k)*Ht*inv(H*P'(k)*Ht+R)
2017             oclMat errorCovPost;       //!< posteriori error estimate covariance matrix (P(k)): P(k)=(I-K(k)*H)*P'(k)
2018         private:
2019             oclMat temp1;
2020             oclMat temp2;
2021             oclMat temp3;
2022             oclMat temp4;
2023             oclMat temp5;
2024         };
2025
2026         /*!***************K Nearest Neighbour*************!*/
2027         class CV_EXPORTS KNearestNeighbour: public CvKNearest
2028         {
2029         public:
2030             KNearestNeighbour();
2031             ~KNearestNeighbour();
2032
2033             bool train(const Mat& trainData, Mat& labels, Mat& sampleIdx = Mat().setTo(Scalar::all(0)),
2034                 bool isRegression = false, int max_k = 32, bool updateBase = false);
2035
2036             void clear();
2037
2038             void find_nearest(const oclMat& samples, int k, oclMat& lables);
2039
2040         private:
2041             oclMat samples_ocl;
2042         };
2043
2044         /*!***************  SVM  *************!*/
2045         class CV_EXPORTS CvSVM_OCL : public CvSVM
2046         {
2047         public:
2048             CvSVM_OCL();
2049
2050             CvSVM_OCL(const cv::Mat& trainData, const cv::Mat& responses,
2051                       const cv::Mat& varIdx=cv::Mat(), const cv::Mat& sampleIdx=cv::Mat(),
2052                       CvSVMParams params=CvSVMParams());
2053             CV_WRAP float predict( const int row_index, Mat& src, bool returnDFVal=false ) const;
2054             CV_WRAP void predict( cv::InputArray samples, cv::OutputArray results ) const;
2055             CV_WRAP float predict( const cv::Mat& sample, bool returnDFVal=false ) const;
2056             float predict( const CvMat* samples, CV_OUT CvMat* results ) const;
2057
2058         protected:
2059             float predict( const int row_index, int row_len, Mat& src, bool returnDFVal=false ) const;
2060             void create_kernel();
2061             void create_solver();
2062         };
2063
2064         /*!***************  END  *************!*/
2065     }
2066 }
2067 #if defined _MSC_VER && _MSC_VER >= 1200
2068 #  pragma warning( push)
2069 #  pragma warning( disable: 4267)
2070 #endif
2071 #include "opencv2/ocl/matrix_operations.hpp"
2072 #if defined _MSC_VER && _MSC_VER >= 1200
2073 #  pragma warning( pop)
2074 #endif
2075
2076 #endif /* __OPENCV_OCL_HPP__ */