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