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.
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.
10 #ifndef __OPENCV_OCL_HPP__
11 #define __OPENCV_OCL_HPP__
16 #include "opencv2/core.hpp"
17 #include "opencv2/imgproc.hpp"
18 #include "opencv2/objdetect.hpp"
19 #include "opencv2/ml.hpp"
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
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
51 // these classes contain OpenCL runtime information
58 int _id; // reserved, don't use it
60 DeviceType deviceType;
61 std::string deviceProfile;
62 std::string deviceVersion;
63 std::string deviceName;
64 std::string deviceVendor;
66 std::string deviceDriverVersion;
67 std::string deviceExtensions;
69 size_t maxWorkGroupSize;
70 std::vector<size_t> maxWorkItemSizes;
72 size_t localMemorySize;
73 size_t maxMemAllocSize;
75 int deviceVersionMajor;
76 int deviceVersionMinor;
78 bool haveDoubleSupport;
79 bool isUnifiedMemory; // 1 means integrated GPU, otherwise this value is 0
82 std::string compilationExtraOptions;
84 const PlatformInfo* platform;
92 int _id; // reserved, don't use it
94 std::string platformProfile;
95 std::string platformVersion;
96 std::string platformName;
97 std::string platformVendor;
98 std::string platformExtensons;
100 int platformVersionMajor;
101 int platformVersionMinor;
103 std::vector<const DeviceInfo*> devices;
109 //////////////////////////////// Initialization & Info ////////////////////////
110 typedef std::vector<const PlatformInfo*> PlatformsInfo;
112 CV_EXPORTS int getOpenCLPlatforms(PlatformsInfo& platforms);
114 typedef std::vector<const DeviceInfo*> DevicesInfo;
116 CV_EXPORTS int getOpenCLDevices(DevicesInfo& devices, int deviceType = CVCL_DEVICE_TYPE_GPU,
117 const PlatformInfo* platform = NULL);
119 // set device you want to use
120 CV_EXPORTS void setDevice(const DeviceInfo* info);
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);
128 FEATURE_CL_DOUBLE = 1,
129 FEATURE_CL_UNIFIED_MEM,
131 FEATURE_CL_INTEL_DEVICE
134 // Represents OpenCL context, interface
135 class CV_EXPORTS Context
141 static Context *getContext();
143 bool supportsFeature(FEATURE_TYPE featureType) const;
144 const DeviceInfo& getDeviceInfo() const;
146 const void* getOpenCLContextPtr() const;
147 const void* getOpenCLCommandQueuePtr() const;
148 const void* getOpenCLDeviceIDPtr() const;
151 inline const void *getClContextPtr()
153 return Context::getContext()->getOpenCLContextPtr();
156 inline const void *getClCommandQueuePtr()
158 return Context::getContext()->getOpenCLCommandQueuePtr();
161 CV_EXPORTS bool supportsFeature(FEATURE_TYPE featureType);
163 CV_EXPORTS void finish();
165 enum BINARY_CACHE_MODE
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
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.
177 // This feature is enabled by default.
178 CV_EXPORTS void setBinaryDiskCache(int mode = CACHE_RELEASE, cv::String path = "./");
180 //! set where binary cache to be saved to
181 CV_EXPORTS void setBinaryPath(const char *path);
186 const char* programStr;
187 const char* programHash;
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)
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)
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);
210 class CV_EXPORTS oclMatExpr;
211 //////////////////////////////// oclMat ////////////////////////////////
212 class CV_EXPORTS oclMat
215 //! default constructor
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);
224 oclMat(const oclMat &m);
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);
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);
234 //! builds oclMat from Mat. Perfom blocking upload to device.
235 explicit oclMat (const Mat &m);
237 //! destructor - calls release()
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);
246 //! pefroms blocking upload data to oclMat.
247 void upload(const cv::Mat &m);
250 //! downloads data from device to host memory. Blocking calls.
251 operator Mat() const;
252 void download(cv::Mat &m) const;
254 //! convert to _InputArray
255 operator _InputArray();
257 //! convert to _OutputArray
258 operator _OutputArray();
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;
271 //! returns deep copy of the oclMatrix, i.e. the data is copied
272 oclMat clone() const;
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;
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;
282 void assignTo( oclMat &m, int type = -1 ) const;
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;
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);
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);
303 //! decreases reference counter;
304 // deallocate the data when reference counter reaches 0.
307 //! swaps with other smart pointer
308 void swap(oclMat &mat);
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;
319 oclMat& operator+=( const oclMat& m );
320 oclMat& operator-=( const oclMat& m );
321 oclMat& operator*=( const oclMat& m );
322 oclMat& operator/=( const oclMat& m );
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)
335 //! returns element type, i.e. 8UC3 returns 8UC4 because in ocl
336 //! 3 channels element actually use 4 channel space
338 //! returns element type, similar to CV_MAT_DEPTH(cvMat->type)
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
350 //! returns true if oclMatrix data is NULL
353 //! matrix transposition
356 /*! includes several bit-fields:
357 - the magic signature
363 //! the number of rows and columns
365 //! a distance between successive rows in bytes; includes the gap if any
367 //! pointer to the data(OCL memory object)
370 //! pointer to the reference counter;
371 // when oclMatrix points to user-allocated data, the pointer is NULL
374 //! helper fields used in locateROI and adjustROI
375 //datastart and dataend are not used in current version
379 //! OpenCL context associated with the oclMat object.
380 Context *clCxt; // TODO clCtx
381 //add offset for handle ROI, calculated in byte
383 //add wholerows and wholecols for the whole matrix, datastart and dataend are no longer used
388 // convert InputArray/OutputArray to oclMat references
389 CV_EXPORTS oclMat& getOclMatRef(InputArray src);
390 CV_EXPORTS oclMat& getOclMatRef(OutputArray src);
392 ///////////////////// mat split and merge /////////////////////////////////
393 //! Compose a multi-channel array from several single-channel arrays
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);
398 //! Divides multi-channel array into several single-channel arrays
400 CV_EXPORTS void split(const oclMat &src, oclMat *dst);
401 CV_EXPORTS void split(const oclMat &src, std::vector<oclMat> &dst);
403 ////////////////////////////// Arithmetics ///////////////////////////////////
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);
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());
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());
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);
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);
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);
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);
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);
449 //! transposes the matrix
450 // supports all data types
451 CV_EXPORTS void transpose(const oclMat &src, oclMat &dst);
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);
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);
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);
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);
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);
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);
482 //! computes sum of array elements
484 CV_EXPORTS Scalar sum(const oclMat &m);
485 CV_EXPORTS Scalar absSum(const oclMat &m);
486 CV_EXPORTS Scalar sqrSum(const oclMat &m);
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());
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());
497 //! counts non-zero array elements
499 CV_EXPORTS int countNonZero(const oclMat &src);
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);
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);
511 //! only 8UC1 is supported now
512 CV_EXPORTS Ptr<cv::CLAHE> createCLAHE(double clipLimit = 40.0, Size tileGridSize = Size(8, 8));
515 // supports 8UC1 8UC4
516 CV_EXPORTS void bilateralFilter(const oclMat& src, oclMat& dst, int d, double sigmaColor, double sigmaSpace, int borderType=BORDER_DEFAULT);
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);
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);
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);
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);
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);
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);
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);
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);
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);
558 //! perfroms per-elements bit-wise inversion
559 // supports all types
560 CV_EXPORTS void bitwise_not(const oclMat &src, oclMat &dst);
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());
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());
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());
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 &);
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);
590 struct CV_EXPORTS ConvolveBuf
594 Size user_block_size;
597 oclMat image_spect, templ_spect, result_spect;
598 oclMat image_block, templ_block, result_data;
600 void create(Size image_size, Size templ_size);
601 static Size estimateBlockSize(Size result_size, Size templ_size);
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);
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);
614 CV_EXPORTS void cvtColor(const oclMat &src, oclMat &dst, int code, int dcn = 0);
616 //! initializes a scaled identity matrix
617 CV_EXPORTS void setIdentity(oclMat& src, const Scalar & val = Scalar(1));
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);
622 //////////////////////////////// Filter Engine ////////////////////////////////
625 The Base Class for 1D or Row-wise Filters
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.
630 class CV_EXPORTS BaseRowFilter_GPU
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;
640 The Base Class for Column-wise Filters
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.
645 class CV_EXPORTS BaseColumnFilter_GPU
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;
655 The Base Class for Non-Separable 2D Filters.
657 This is the base class for linear or non-linear 2D filters.
659 class CV_EXPORTS BaseFilter_GPU
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;
672 The Base Class for Filter Engine.
674 The class can be used to apply an arbitrary filtering operation to an image.
675 It contains all the necessary intermediate buffers.
677 class CV_EXPORTS FilterEngine_GPU
680 virtual ~FilterEngine_GPU() {}
682 virtual void apply(const oclMat &src, oclMat &dst, Rect roi = Rect(0, 0, -1, -1)) = 0;
685 //! returns the non-separable filter engine with the specified filter
686 CV_EXPORTS Ptr<FilterEngine_GPU> createFilter2D_GPU(const Ptr<BaseFilter_GPU> filter2D);
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);
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);
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);
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);
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);
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 );
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);
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);
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);
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);
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);
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);
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));
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);
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)
753 boxFilter(src, dst, -1, ksize, anchor, borderType);
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);
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);
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);
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);
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);
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,
786 int borderType = BORDER_CONSTANT, const Scalar &borderValue = morphologyDefaultBorderValue());
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,
793 int borderType = BORDER_CONSTANT, const Scalar &borderValue = morphologyDefaultBorderValue());
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,
799 int borderType = BORDER_CONSTANT, const Scalar &borderValue = morphologyDefaultBorderValue());
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));
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));
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));
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);
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);
825 //! Applies a generic geometrical transformation to an image.
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());
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());
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);
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);
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);
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);
863 /////////////////////////////////// ML ///////////////////////////////////////////
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
870 CV_EXPORTS void distanceToCenters(const oclMat &src, const oclMat ¢ers, Mat &dists, Mat &labels, int distType = NORM_L2SQR);
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 ¢ers);
878 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
879 ///////////////////////////////////////////CascadeClassifier//////////////////////////////////////////////////////////////////
880 ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
881 class CV_EXPORTS OclCascadeClassifier : public cv::CascadeClassifier
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());
889 /////////////////////////////// Pyramid /////////////////////////////////////
890 CV_EXPORTS void pyrDown(const oclMat &src, oclMat &dst);
892 //! upsamples the source image and then smoothes it
893 CV_EXPORTS void pyrUp(const oclMat &src, oclMat &dst);
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);
900 //! computes vertical sum, supports only CV_32FC1 images
901 CV_EXPORTS void columnSum(const oclMat &src, oclMat &sum);
903 ///////////////////////////////////////// match_template /////////////////////////////////////////////////////////////
904 struct CV_EXPORTS MatchTemplateBuf
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;
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);
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);
925 ///////////////////////////////////////////// Canny /////////////////////////////////////////////
926 struct CV_EXPORTS CannyBuf;
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);
935 struct CV_EXPORTS CannyBuf
937 CannyBuf() : counter(1, 1, CV_32S) { }
942 explicit CannyBuf(const Size &image_size, int apperture_size = 3) : counter(1, 1, CV_32S)
944 create(image_size, apperture_size);
946 CannyBuf(const oclMat &dx_, const oclMat &dy_);
947 void create(const Size &image_size, int apperture_size = 3);
951 oclMat dx_buf, dy_buf;
952 oclMat magBuf, mapBuf;
953 oclMat trackBuf1, trackBuf2;
955 Ptr<FilterEngine_GPU> filterDX, filterDY;
958 ///////////////////////////////////////// Hough Transform /////////////////////////////////////////
960 struct HoughCirclesBuf
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);
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.
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);
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);
995 //////////////// HOG (Histogram-of-Oriented-Gradients) Descriptor and Object Detector //////////////
997 struct CV_EXPORTS HOGDescriptor
1001 enum { DEFAULT_WIN_SIGMA = -1 };
1003 enum { DEFAULT_NLEVELS = 64 };
1005 enum { DESCR_FORMAT_ROW_BY_ROW, DESCR_FORMAT_COL_BY_COL };
1009 HOGDescriptor(Size win_size = Size(64, 128), Size block_size = Size(16, 16),
1011 Size block_stride = Size(8, 8), Size cell_size = Size(8, 8),
1013 int nbins = 9, double win_sigma = DEFAULT_WIN_SIGMA,
1015 double threshold_L2hys = 0.2, bool gamma_correction = true,
1017 int nlevels = DEFAULT_NLEVELS);
1021 size_t getDescriptorSize() const;
1023 size_t getBlockHistogramSize() const;
1027 void setSVMDetector(const std::vector<float> &detector);
1031 static std::vector<float> getDefaultPeopleDetector();
1033 static std::vector<float> getPeopleDetector48x96();
1035 static std::vector<float> getPeopleDetector64x128();
1039 void detect(const oclMat &img, std::vector<Point> &found_locations,
1041 double hit_threshold = 0, Size win_stride = Size(),
1043 Size padding = Size());
1047 void detectMultiScale(const oclMat &img, std::vector<Rect> &found_locations,
1049 double hit_threshold = 0, Size win_stride = Size(),
1051 Size padding = Size(), double scale0 = 1.05,
1053 int group_threshold = 2);
1057 void getDescriptors(const oclMat &img, Size win_stride,
1059 oclMat &descriptors,
1061 int descr_format = DESCR_FORMAT_COL_BY_COL);
1077 double threshold_L2hys;
1079 bool gamma_correction;
1087 // initialize buffers; only need to do once in case of multiscale detection
1089 void init_buffer(const oclMat &img, Size win_stride);
1093 void computeBlockHistograms(const oclMat &img);
1095 void computeGradient(const oclMat &img, oclMat &grad, oclMat &qangle);
1099 double getWinSigma() const;
1101 bool checkDetectorSize() const;
1105 static int numPartsWithin(int size, int part_size, int stride);
1107 static Size numPartsWithin(Size size, Size part_size, Size stride);
1111 // Coefficients of the separating plane
1119 // Results of the last classification step
1127 // Results of the last histogram evaluation step
1133 // Gradients conputation results
1135 oclMat grad, qangle;
1145 // effect size of input image (might be different from original size after scaling)
1152 ////////////////////////feature2d_ocl/////////////////
1153 /****************************************************************************************\
1155 \****************************************************************************************/
1156 template<typename T>
1157 struct CV_EXPORTS Accumulator
1161 template<> struct Accumulator<unsigned char>
1165 template<> struct Accumulator<unsigned short>
1169 template<> struct Accumulator<char>
1173 template<> struct Accumulator<short>
1179 * Manhattan distance (city block distance) functor
1182 struct CV_EXPORTS L1
1184 enum { normType = NORM_L1 };
1185 typedef T ValueType;
1186 typedef typename Accumulator<T>::Type ResultType;
1188 ResultType operator()( const T *a, const T *b, int size ) const
1190 return normL1<ValueType, ResultType>(a, b, size);
1195 * Euclidean distance functor
1198 struct CV_EXPORTS L2
1200 enum { normType = NORM_L2 };
1201 typedef T ValueType;
1202 typedef typename Accumulator<T>::Type ResultType;
1204 ResultType operator()( const T *a, const T *b, int size ) const
1206 return (ResultType)std::sqrt((double)normL2Sqr<ValueType, ResultType>(a, b, size));
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
1214 struct CV_EXPORTS Hamming
1216 enum { normType = NORM_HAMMING };
1217 typedef unsigned char ValueType;
1218 typedef int ResultType;
1220 /** this will count the bits in a ^ b
1222 ResultType operator()( const unsigned char *a, const unsigned char *b, int size ) const
1224 return normHamming(a, b, size);
1228 ////////////////////////////////// BruteForceMatcher //////////////////////////////////
1230 class CV_EXPORTS BruteForceMatcher_OCL_base
1233 enum DistType {L1Dist = 0, L2Dist, HammingDist};
1234 explicit BruteForceMatcher_OCL_base(DistType distType = L2Dist);
1236 // Add descriptors to train descriptor collection
1237 void add(const std::vector<oclMat> &descCollection);
1239 // Get train descriptors collection
1240 const std::vector<oclMat> &getTrainDescriptors() const;
1242 // Clear train descriptors collection
1245 // Return true if there are not train descriptors in collection
1248 // Return true if the matcher supports mask in match methods
1249 bool isMaskSupported() const;
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());
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);
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());
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>());
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());
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);
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>());
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());
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);
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);
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());
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);
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);
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());
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);
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);
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>());
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);
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);
1379 std::vector<oclMat> trainDescCollection;
1382 template <class Distance>
1383 class CV_EXPORTS BruteForceMatcher_OCL;
1385 template <typename T>
1386 class CV_EXPORTS BruteForceMatcher_OCL< L1<T> > : public BruteForceMatcher_OCL_base
1389 explicit BruteForceMatcher_OCL() : BruteForceMatcher_OCL_base(L1Dist) {}
1390 explicit BruteForceMatcher_OCL(L1<T> /*d*/) : BruteForceMatcher_OCL_base(L1Dist) {}
1392 template <typename T>
1393 class CV_EXPORTS BruteForceMatcher_OCL< L2<T> > : public BruteForceMatcher_OCL_base
1396 explicit BruteForceMatcher_OCL() : BruteForceMatcher_OCL_base(L2Dist) {}
1397 explicit BruteForceMatcher_OCL(L2<T> /*d*/) : BruteForceMatcher_OCL_base(L2Dist) {}
1399 template <> class CV_EXPORTS BruteForceMatcher_OCL< Hamming > : public BruteForceMatcher_OCL_base
1402 explicit BruteForceMatcher_OCL() : BruteForceMatcher_OCL_base(HammingDist) {}
1403 explicit BruteForceMatcher_OCL(Hamming /*d*/) : BruteForceMatcher_OCL_base(HammingDist) {}
1406 class CV_EXPORTS BFMatcher_OCL : public BruteForceMatcher_OCL_base
1409 explicit BFMatcher_OCL(int norm = NORM_L2) : BruteForceMatcher_OCL_base(norm == NORM_L1 ? L1Dist : norm == NORM_L2 ? L2Dist : HammingDist) {}
1412 class CV_EXPORTS GoodFeaturesToTrackDetector_OCL
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);
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);
1424 double qualityLevel;
1428 bool useHarrisDetector;
1430 void releaseMemory()
1435 minMaxbuf_.release();
1436 tmpCorners_.release();
1446 inline GoodFeaturesToTrackDetector_OCL::GoodFeaturesToTrackDetector_OCL(int maxCorners_, double qualityLevel_, double minDistance_,
1447 int blockSize_, bool useHarrisDetector_, double harrisK_)
1449 maxCorners = maxCorners_;
1450 qualityLevel = qualityLevel_;
1451 minDistance = minDistance_;
1452 blockSize = blockSize_;
1453 useHarrisDetector = useHarrisDetector_;
1457 ////////////////////////////////// FAST Feature Detector //////////////////////////////////
1458 class CV_EXPORTS FAST_OCL
1469 // all features have same size
1470 static const int FEATURE_SIZE = 7;
1472 explicit FAST_OCL(int threshold, bool nonmaxSupression = true, double keypointsRatio = 0.05);
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);
1479 //! download keypoints from device to host memory
1480 static void downloadKeypoints(const oclMat& d_keypoints, std::vector<KeyPoint>& keypoints);
1482 //! convert keypoints to KeyPoint vector
1483 static void convertKeypoints(const Mat& h_keypoints, std::vector<KeyPoint>& keypoints);
1485 //! release temporary buffer's memory
1488 bool nonmaxSupression;
1492 //! max keypoints = keypointsRatio * img.size().area()
1493 double keypointsRatio;
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);
1499 //! get final array of keypoints
1500 //! performs nonmax supression if needed
1501 //! return final count of keypoints
1502 int getKeyPoints(oclMat& keypoints);
1510 oclMat d_keypoints_;
1512 int calcKeypointsOCL(const oclMat& img, const oclMat& mask, int maxKeypoints);
1513 int nonmaxSupressionOCL(oclMat& keypoints);
1516 /////////////////////////////// PyrLKOpticalFlow /////////////////////////////////////
1518 class CV_EXPORTS PyrLKOpticalFlow
1523 winSize = Size(21, 21);
1527 useInitialFlow = false;
1528 minEigThreshold = 1e-4f;
1529 getMinEigenVals = false;
1530 isDeviceArch11_ = false;
1533 void sparse(const oclMat &prevImg, const oclMat &nextImg, const oclMat &prevPts, oclMat &nextPts,
1534 oclMat &status, oclMat *err = 0);
1536 void dense(const oclMat &prevImg, const oclMat &nextImg, oclMat &u, oclMat &v, oclMat *err = 0);
1542 bool useInitialFlow;
1543 float minEigThreshold;
1544 bool getMinEigenVals;
1546 void releaseMemory()
1548 dx_calcBuf_.release();
1549 dy_calcBuf_.release();
1559 void calcSharrDeriv(const oclMat &src, oclMat &dx, oclMat &dy);
1561 void buildImagePyramid(const oclMat &img0, std::vector<oclMat> &pyr, bool withBorder);
1566 std::vector<oclMat> prevPyr_;
1567 std::vector<oclMat> nextPyr_;
1575 bool isDeviceArch11_;
1578 class CV_EXPORTS FarnebackOpticalFlow
1581 FarnebackOpticalFlow();
1592 void operator ()(const oclMat &frame0, const oclMat &frame1, oclMat &flowx, oclMat &flowy);
1594 void releaseMemory();
1597 void prepareGaussian(
1598 int n, double sigma, float *g, float *xg, float *xxg,
1599 double &ig11, double &ig03, double &ig33, double &ig55);
1601 void setPolynomialExpansionConsts(int n, double sigma);
1603 void updateFlow_boxFilter(
1604 const oclMat& R0, const oclMat& R1, oclMat& flowx, oclMat &flowy,
1605 oclMat& M, oclMat &bufM, int blockSize, bool updateMatrices);
1607 void updateFlow_gaussianBlur(
1608 const oclMat& R0, const oclMat& R1, oclMat& flowx, oclMat& flowy,
1609 oclMat& M, oclMat &bufM, int blockSize, bool updateMatrices);
1612 oclMat pyrLevel_[2], M_, bufM_, R_[2], blurredFrame_[2];
1613 std::vector<oclMat> pyramid0_, pyramid1_;
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);
1626 //! builds Perspective warping maps
1627 CV_EXPORTS void buildWarpPerspectiveMaps(const Mat &M, bool inverse, Size dsize, oclMat &xmap, oclMat &ymap);
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
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);
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);
1657 class CV_EXPORTS StereoBM_OCL
1660 enum { BASIC_PRESET = 0, PREFILTER_XSOBEL = 1 };
1662 enum { DEFAULT_NDISP = 64, DEFAULT_WINSZ = 19 };
1664 //! the default constructor
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);
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);
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();
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;
1688 oclMat minSSD, leBuf, riBuf;
1691 class CV_EXPORTS StereoBeliefPropagation
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);
1711 float max_data_term;
1713 float max_disc_term;
1714 float disc_single_jump;
1717 oclMat u, d, l, r, u2, d2, l2, r2;
1718 std::vector<oclMat> datas;
1722 class CV_EXPORTS StereoConstantSpaceBP
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);
1745 float max_data_term;
1747 float max_disc_term;
1748 float disc_single_jump;
1751 bool use_local_init_data_cost;
1753 oclMat u[2], d[2], l[2], r[2];
1754 oclMat disp_selected_pyr[2];
1756 oclMat data_cost_selected;
1761 // Implementation of the Zach, Pock and Bischof Dual TV-L1 Optical Flow method
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
1769 OpticalFlowDual_TVL1_OCL();
1771 void operator ()(const oclMat& I0, const oclMat& I1, oclMat& flowx, oclMat& flowy);
1773 void collectGarbage();
1776 * Time step of the numerical scheme.
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.
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.
1797 * Number of scales used to create the pyramid of images.
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.
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.
1816 * Stopping criterion iterations number used in the numerical scheme.
1820 bool useInitialFlow;
1823 void procOneScale(const oclMat& I0, const oclMat& I1, oclMat& u1, oclMat& u2);
1825 std::vector<oclMat> I0s;
1826 std::vector<oclMat> I1s;
1827 std::vector<oclMat> u1s;
1828 std::vector<oclMat> u2s;
1848 // current supported sorting methods
1851 SORT_BITONIC, // only support power-of-2 buffer size
1852 SORT_SELECTION, // cannot sort duplicate keys
1854 SORT_RADIX // only support signed int/float keys(CV_32S/CV_32F)
1856 //! Returns the sorted result of all the elements in input based on equivalent keys.
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.
1866 // keys = {2, 3, 1} (CV_8UC1)
1867 // values = {10,5, 4,3, 6,2} (CV_8UC2)
1868 // sortByKey(keys, values, SORT_SELECTION, false);
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
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);
1882 //! computes a background image
1883 virtual void getBackgroundImage(oclMat& backgroundImage) const = 0;
1886 Gaussian Mixture-based Backbround/Foreground Segmentation Algorithm
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
1894 class CV_EXPORTS MOG: public cv::ocl::BackgroundSubtractor
1897 //! the default constructor
1898 MOG(int nmixtures = -1);
1900 //! re-initiaization method
1901 void initialize(Size frameSize, int frameType);
1903 //! the update operator
1904 void operator()(const oclMat& frame, oclMat& fgmask, float learningRate = 0.f);
1906 //! computes a background image which are the mean of all background gaussians
1907 void getBackgroundImage(oclMat& backgroundImage) const;
1909 //! releases all inner buffers
1914 float backgroundRatio;
1931 The class implements the following algorithm:
1932 "Improved adaptive Gausian mixture model for background subtraction"
1934 International Conference Pattern Recognition, UK, August, 2004.
1935 http://www.zoranz.net/Publications/zivkovic2004ICPR.pdf
1937 class CV_EXPORTS MOG2: public cv::ocl::BackgroundSubtractor
1940 //! the default constructor
1941 MOG2(int nmixtures = -1);
1943 //! re-initiaization method
1944 void initialize(Size frameSize, int frameType);
1946 //! the update operator
1947 void operator()(const oclMat& frame, oclMat& fgmask, float learningRate = -1.0f);
1949 //! computes a background image which are the mean of all background gaussians
1950 void getBackgroundImage(oclMat& backgroundImage) const;
1952 //! releases all inner buffers
1956 // you should call initialize after parameters changes
1960 //! here it is the maximum allowed number of mixture components.
1961 //! Actual number is determined dynamically per pixel
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.
1968 /////////////////////////
1969 // less important parameters - things you might change but be carefull
1970 ////////////////////////
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;
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
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)
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
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.
2020 oclMat bgmodelUsedModes_; //keep track of number of modes per pixel
2023 /*!***************Kalman Filter*************!*/
2024 class CV_EXPORTS 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);
2033 const oclMat& predict(const oclMat& control=oclMat());
2034 const oclMat& correct(const oclMat& measurement);
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)
2054 /*!***************K Nearest Neighbour*************!*/
2055 class CV_EXPORTS KNearestNeighbour: public CvKNearest
2058 KNearestNeighbour();
2059 ~KNearestNeighbour();
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);
2066 void find_nearest(const oclMat& samples, int k, oclMat& lables);
2072 /*!*************** SVM *************!*/
2073 class CV_EXPORTS CvSVM_OCL : public CvSVM
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;
2087 float predict( const int row_index, int row_len, Mat& src, bool returnDFVal=false ) const;
2088 void create_kernel();
2089 void create_solver();
2092 /*!*************** END *************!*/
2095 #if defined _MSC_VER && _MSC_VER >= 1200
2096 # pragma warning( push)
2097 # pragma warning( disable: 4267)
2099 #include "opencv2/ocl/matrix_operations.hpp"
2100 #if defined _MSC_VER && _MSC_VER >= 1200
2101 # pragma warning( pop)
2104 #endif /* __OPENCV_OCL_HPP__ */