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