1 /*M///////////////////////////////////////////////////////////////////////////////////////
3 // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
5 // By downloading, copying, installing or using the software you agree to this license.
6 // If you do not agree to this license, do not download, install,
7 // copy or use the software.
11 // For Open Source Computer Vision Library
13 // Copyright (C) 2010-2012, Institute Of Software Chinese Academy Of Science, all rights reserved.
14 // Copyright (C) 2010-2012, Advanced Micro Devices, Inc., all rights reserved.
15 // Copyright (C) 2010-2012, Multicoreware, Inc., all rights reserved.
16 // Third party copyrights are property of their respective owners.
18 // Redistribution and use in source and binary forms, with or without modification,
19 // are permitted provided that the following conditions are met:
21 // * Redistribution's of source code must retain the above copyright notice,
22 // this list of conditions and the following disclaimer.
24 // * Redistribution's in binary form must reproduce the above copyright notice,
25 // this list of conditions and the following disclaimer in the documentation
26 // and/or other materials provided with the distribution.
28 // * The name of the copyright holders may not be used to endorse or promote products
29 // derived from this software without specific prior written permission.
31 // This software is provided by the copyright holders and contributors "as is" and
32 // any express or implied warranties, including, but not limited to, the implied
33 // warranties of merchantability and fitness for a particular purpose are disclaimed.
34 // In no event shall the Intel Corporation or contributors be liable for any direct,
35 // indirect, incidental, special, exemplary, or consequential damages
36 // (including, but not limited to, procurement of substitute goods or services;
37 // loss of use, data, or profits; or business interruption) however caused
38 // and on any theory of liability, whether in contract, strict liability,
39 // or tort (including negligence or otherwise) arising in any way out of
40 // the use of this software, even if advised of the possibility of such damage.
44 #ifndef __OPENCV_OCL_HPP__
45 #define __OPENCV_OCL_HPP__
50 #include "opencv2/core.hpp"
51 #include "opencv2/imgproc.hpp"
52 #include "opencv2/objdetect.hpp"
53 #include "opencv2/ml.hpp"
61 CVCL_DEVICE_TYPE_DEFAULT = (1 << 0),
62 CVCL_DEVICE_TYPE_CPU = (1 << 1),
63 CVCL_DEVICE_TYPE_GPU = (1 << 2),
64 CVCL_DEVICE_TYPE_ACCELERATOR = (1 << 3),
65 //CVCL_DEVICE_TYPE_CUSTOM = (1 << 4)
66 CVCL_DEVICE_TYPE_ALL = 0xFFFFFFFF
78 DEVICE_MEM_DEFAULT = 0,
79 DEVICE_MEM_AHP, //alloc host pointer
80 DEVICE_MEM_UHP, //use host pointer
81 DEVICE_MEM_CHP, //copy host pointer
82 DEVICE_MEM_PM //persistent memory
85 // these classes contain OpenCL runtime information
92 int _id; // reserved, don't use it
94 DeviceType deviceType;
95 std::string deviceProfile;
96 std::string deviceVersion;
97 std::string deviceName;
98 std::string deviceVendor;
100 std::string deviceDriverVersion;
101 std::string deviceExtensions;
103 size_t maxWorkGroupSize;
104 std::vector<size_t> maxWorkItemSizes;
106 size_t localMemorySize;
107 size_t maxMemAllocSize;
109 int deviceVersionMajor;
110 int deviceVersionMinor;
112 bool haveDoubleSupport;
113 bool isUnifiedMemory; // 1 means integrated GPU, otherwise this value is 0
116 std::string compilationExtraOptions;
118 const PlatformInfo* platform;
125 int _id; // reserved, don't use it
127 std::string platformProfile;
128 std::string platformVersion;
129 std::string platformName;
130 std::string platformVendor;
131 std::string platformExtensons;
133 int platformVersionMajor;
134 int platformVersionMinor;
136 std::vector<const DeviceInfo*> devices;
141 //////////////////////////////// Initialization & Info ////////////////////////
142 typedef std::vector<const PlatformInfo*> PlatformsInfo;
144 CV_EXPORTS int getOpenCLPlatforms(PlatformsInfo& platforms);
146 typedef std::vector<const DeviceInfo*> DevicesInfo;
148 CV_EXPORTS int getOpenCLDevices(DevicesInfo& devices, int deviceType = CVCL_DEVICE_TYPE_GPU,
149 const PlatformInfo* platform = NULL);
151 // set device you want to use
152 CV_EXPORTS void setDevice(const DeviceInfo* info);
156 FEATURE_CL_DOUBLE = 1,
157 FEATURE_CL_UNIFIED_MEM,
159 FEATURE_CL_INTEL_DEVICE
162 // Represents OpenCL context, interface
163 class CV_EXPORTS Context
169 static Context *getContext();
171 bool supportsFeature(FEATURE_TYPE featureType) const;
172 const DeviceInfo& getDeviceInfo() const;
174 const void* getOpenCLContextPtr() const;
175 const void* getOpenCLCommandQueuePtr() const;
176 const void* getOpenCLDeviceIDPtr() const;
179 inline const void *getClContextPtr()
181 return Context::getContext()->getOpenCLContextPtr();
184 inline const void *getClCommandQueuePtr()
186 return Context::getContext()->getOpenCLCommandQueuePtr();
189 CV_EXPORTS bool supportsFeature(FEATURE_TYPE featureType);
191 CV_EXPORTS void finish();
193 enum BINARY_CACHE_MODE
195 CACHE_NONE = 0, // do not cache OpenCL binary
196 CACHE_DEBUG = 0x1 << 0, // cache OpenCL binary when built in debug mode
197 CACHE_RELEASE = 0x1 << 1, // default behavior, only cache when built in release mode
198 CACHE_ALL = CACHE_DEBUG | CACHE_RELEASE, // cache opencl binary
200 //! Enable or disable OpenCL program binary caching onto local disk
201 // After a program (*.cl files in opencl/ folder) is built at runtime, we allow the
202 // compiled OpenCL program to be cached to the path automatically as "path/*.clb"
203 // binary file, which will be reused when the OpenCV executable is started again.
205 // This feature is enabled by default.
206 CV_EXPORTS void setBinaryDiskCache(int mode = CACHE_RELEASE, cv::String path = "./");
208 //! set where binary cache to be saved to
209 CV_EXPORTS void setBinaryPath(const char *path);
214 const char* programStr;
215 const char* programHash;
217 // Cache in memory by name (should be unique). Caching on disk disabled.
218 inline ProgramSource(const char* _name, const char* _programStr)
219 : name(_name), programStr(_programStr), programHash(NULL)
223 // Cache in memory by name (should be unique). Caching on disk uses programHash mark.
224 inline ProgramSource(const char* _name, const char* _programStr, const char* _programHash)
225 : name(_name), programStr(_programStr), programHash(_programHash)
230 //! Calls OpenCL kernel. Pass globalThreads = NULL, and cleanUp = true, to finally clean-up without executing.
231 //! Deprecated, will be replaced
232 CV_EXPORTS void openCLExecuteKernelInterop(Context *clCxt,
233 const cv::ocl::ProgramSource& source, String kernelName,
234 size_t globalThreads[3], size_t localThreads[3],
235 std::vector< std::pair<size_t, const void *> > &args,
236 int channels, int depth, const char *build_options);
238 class CV_EXPORTS oclMatExpr;
239 //////////////////////////////// oclMat ////////////////////////////////
240 class CV_EXPORTS oclMat
243 //! default constructor
245 //! constructs oclMatrix of the specified size and type (_type is CV_8UC1, CV_64FC3, CV_32SC(12) etc.)
246 oclMat(int rows, int cols, int type);
247 oclMat(Size size, int type);
248 //! constucts oclMatrix and fills it with the specified value _s.
249 oclMat(int rows, int cols, int type, const Scalar &s);
250 oclMat(Size size, int type, const Scalar &s);
252 oclMat(const oclMat &m);
254 //! constructor for oclMatrix headers pointing to user-allocated data
255 oclMat(int rows, int cols, int type, void *data, size_t step = Mat::AUTO_STEP);
256 oclMat(Size size, int type, void *data, size_t step = Mat::AUTO_STEP);
258 //! creates a matrix header for a part of the bigger matrix
259 oclMat(const oclMat &m, const Range &rowRange, const Range &colRange);
260 oclMat(const oclMat &m, const Rect &roi);
262 //! builds oclMat from Mat. Perfom blocking upload to device.
263 explicit oclMat (const Mat &m);
265 //! destructor - calls release()
268 //! assignment operators
269 oclMat &operator = (const oclMat &m);
270 //! assignment operator. Perfom blocking upload to device.
271 oclMat &operator = (const Mat &m);
272 oclMat &operator = (const oclMatExpr& expr);
274 //! pefroms blocking upload data to oclMat.
275 void upload(const cv::Mat &m);
278 //! downloads data from device to host memory. Blocking calls.
279 operator Mat() const;
280 void download(cv::Mat &m) const;
282 //! convert to _InputArray
283 operator _InputArray();
285 //! convert to _OutputArray
286 operator _OutputArray();
288 //! returns a new oclMatrix header for the specified row
289 oclMat row(int y) const;
290 //! returns a new oclMatrix header for the specified column
291 oclMat col(int x) const;
292 //! ... for the specified row span
293 oclMat rowRange(int startrow, int endrow) const;
294 oclMat rowRange(const Range &r) const;
295 //! ... for the specified column span
296 oclMat colRange(int startcol, int endcol) const;
297 oclMat colRange(const Range &r) const;
299 //! returns deep copy of the oclMatrix, i.e. the data is copied
300 oclMat clone() const;
302 //! copies those oclMatrix elements to "m" that are marked with non-zero mask elements.
303 // It calls m.create(this->size(), this->type()).
304 // It supports any data type
305 void copyTo( oclMat &m, const oclMat &mask = oclMat()) const;
307 //! converts oclMatrix to another datatype with optional scalng. See cvConvertScale.
308 void convertTo( oclMat &m, int rtype, double alpha = 1, double beta = 0 ) const;
310 void assignTo( oclMat &m, int type = -1 ) const;
312 //! sets every oclMatrix element to s
313 oclMat& operator = (const Scalar &s);
314 //! sets some of the oclMatrix elements to s, according to the mask
315 oclMat& setTo(const Scalar &s, const oclMat &mask = oclMat());
316 //! creates alternative oclMatrix header for the same data, with different
317 // number of channels and/or different number of rows. see cvReshape.
318 oclMat reshape(int cn, int rows = 0) const;
320 //! allocates new oclMatrix data unless the oclMatrix already has specified size and type.
321 // previous data is unreferenced if needed.
322 void create(int rows, int cols, int type);
323 void create(Size size, int type);
325 //! allocates new oclMatrix with specified device memory type.
326 void createEx(int rows, int cols, int type,
327 DevMemRW rw_type, DevMemType mem_type);
328 void createEx(Size size, int type, DevMemRW rw_type,
329 DevMemType mem_type);
331 //! decreases reference counter;
332 // deallocate the data when reference counter reaches 0.
335 //! swaps with other smart pointer
336 void swap(oclMat &mat);
338 //! locates oclMatrix header within a parent oclMatrix. See below
339 void locateROI( Size &wholeSize, Point &ofs ) const;
340 //! moves/resizes the current oclMatrix ROI inside the parent oclMatrix.
341 oclMat& adjustROI( int dtop, int dbottom, int dleft, int dright );
342 //! extracts a rectangular sub-oclMatrix
343 // (this is a generalized form of row, rowRange etc.)
344 oclMat operator()( Range rowRange, Range colRange ) const;
345 oclMat operator()( const Rect &roi ) const;
347 oclMat& operator+=( const oclMat& m );
348 oclMat& operator-=( const oclMat& m );
349 oclMat& operator*=( const oclMat& m );
350 oclMat& operator/=( const oclMat& m );
352 //! returns true if the oclMatrix data is continuous
353 // (i.e. when there are no gaps between successive rows).
354 // similar to CV_IS_oclMat_CONT(cvoclMat->type)
355 bool isContinuous() const;
356 //! returns element size in bytes,
357 // similar to CV_ELEM_SIZE(cvMat->type)
358 size_t elemSize() const;
359 //! returns the size of element channel in bytes.
360 size_t elemSize1() const;
361 //! returns element type, similar to CV_MAT_TYPE(cvMat->type)
363 //! returns element type, i.e. 8UC3 returns 8UC4 because in ocl
364 //! 3 channels element actually use 4 channel space
366 //! returns element type, similar to CV_MAT_DEPTH(cvMat->type)
368 //! returns element type, similar to CV_MAT_CN(cvMat->type)
369 int channels() const;
370 //! returns element type, return 4 for 3 channels element,
371 //!becuase 3 channels element actually use 4 channel space
372 int oclchannels() const;
373 //! returns step/elemSize1()
374 size_t step1() const;
375 //! returns oclMatrix size:
376 // width == number of columns, height == number of rows
378 //! returns true if oclMatrix data is NULL
381 //! matrix transposition
384 /*! includes several bit-fields:
385 - the magic signature
391 //! the number of rows and columns
393 //! a distance between successive rows in bytes; includes the gap if any
395 //! pointer to the data(OCL memory object)
398 //! pointer to the reference counter;
399 // when oclMatrix points to user-allocated data, the pointer is NULL
402 //! helper fields used in locateROI and adjustROI
403 //datastart and dataend are not used in current version
407 //! OpenCL context associated with the oclMat object.
408 Context *clCxt; // TODO clCtx
409 //add offset for handle ROI, calculated in byte
411 //add wholerows and wholecols for the whole matrix, datastart and dataend are no longer used
416 // convert InputArray/OutputArray to oclMat references
417 CV_EXPORTS oclMat& getOclMatRef(InputArray src);
418 CV_EXPORTS oclMat& getOclMatRef(OutputArray src);
420 ///////////////////// mat split and merge /////////////////////////////////
421 //! Compose a multi-channel array from several single-channel arrays
423 CV_EXPORTS void merge(const oclMat *src, size_t n, oclMat &dst);
424 CV_EXPORTS void merge(const std::vector<oclMat> &src, oclMat &dst);
426 //! Divides multi-channel array into several single-channel arrays
428 CV_EXPORTS void split(const oclMat &src, oclMat *dst);
429 CV_EXPORTS void split(const oclMat &src, std::vector<oclMat> &dst);
431 ////////////////////////////// Arithmetics ///////////////////////////////////
433 //! adds one matrix to another with scale (dst = src1 * alpha + src2 * beta + gama)
434 // supports all data types
435 CV_EXPORTS void addWeighted(const oclMat &src1, double alpha, const oclMat &src2, double beta, double gama, oclMat &dst);
437 //! adds one matrix to another (dst = src1 + src2)
438 // supports all data types
439 CV_EXPORTS void add(const oclMat &src1, const oclMat &src2, oclMat &dst, const oclMat &mask = oclMat());
440 //! adds scalar to a matrix (dst = src1 + s)
441 // supports all data types
442 CV_EXPORTS void add(const oclMat &src1, const Scalar &s, oclMat &dst, const oclMat &mask = oclMat());
444 //! subtracts one matrix from another (dst = src1 - src2)
445 // supports all data types
446 CV_EXPORTS void subtract(const oclMat &src1, const oclMat &src2, oclMat &dst, const oclMat &mask = oclMat());
447 //! subtracts scalar from a matrix (dst = src1 - s)
448 // supports all data types
449 CV_EXPORTS void subtract(const oclMat &src1, const Scalar &s, oclMat &dst, const oclMat &mask = oclMat());
451 //! computes element-wise product of the two arrays (dst = src1 * scale * src2)
452 // supports all data types
453 CV_EXPORTS void multiply(const oclMat &src1, const oclMat &src2, oclMat &dst, double scale = 1);
454 //! multiplies matrix to a number (dst = scalar * src)
455 // supports all data types
456 CV_EXPORTS void multiply(double scalar, const oclMat &src, oclMat &dst);
458 //! computes element-wise quotient of the two arrays (dst = src1 * scale / src2)
459 // supports all data types
460 CV_EXPORTS void divide(const oclMat &src1, const oclMat &src2, oclMat &dst, double scale = 1);
461 //! computes element-wise quotient of the two arrays (dst = scale / src)
462 // supports all data types
463 CV_EXPORTS void divide(double scale, const oclMat &src1, oclMat &dst);
465 //! computes element-wise minimum of the two arrays (dst = min(src1, src2))
466 // supports all data types
467 CV_EXPORTS void min(const oclMat &src1, const oclMat &src2, oclMat &dst);
469 //! computes element-wise maximum of the two arrays (dst = max(src1, src2))
470 // supports all data types
471 CV_EXPORTS void max(const oclMat &src1, const oclMat &src2, oclMat &dst);
473 //! compares elements of two arrays (dst = src1 <cmpop> src2)
474 // supports all data types
475 CV_EXPORTS void compare(const oclMat &src1, const oclMat &src2, oclMat &dst, int cmpop);
477 //! transposes the matrix
478 // supports all data types
479 CV_EXPORTS void transpose(const oclMat &src, oclMat &dst);
481 //! computes element-wise absolute values of an array (dst = abs(src))
482 // supports all data types
483 CV_EXPORTS void abs(const oclMat &src, oclMat &dst);
485 //! computes element-wise absolute difference of two arrays (dst = abs(src1 - src2))
486 // supports all data types
487 CV_EXPORTS void absdiff(const oclMat &src1, const oclMat &src2, oclMat &dst);
488 //! computes element-wise absolute difference of array and scalar (dst = abs(src1 - s))
489 // supports all data types
490 CV_EXPORTS void absdiff(const oclMat &src1, const Scalar &s, oclMat &dst);
492 //! computes mean value and standard deviation of all or selected array elements
493 // supports all data types
494 CV_EXPORTS void meanStdDev(const oclMat &mtx, Scalar &mean, Scalar &stddev);
496 //! computes norm of array
497 // supports NORM_INF, NORM_L1, NORM_L2
498 // supports all data types
499 CV_EXPORTS double norm(const oclMat &src1, int normType = NORM_L2);
501 //! computes norm of the difference between two arrays
502 // supports NORM_INF, NORM_L1, NORM_L2
503 // supports all data types
504 CV_EXPORTS double norm(const oclMat &src1, const oclMat &src2, int normType = NORM_L2);
506 //! reverses the order of the rows, columns or both in a matrix
507 // supports all types
508 CV_EXPORTS void flip(const oclMat &src, oclMat &dst, int flipCode);
510 //! computes sum of array elements
512 CV_EXPORTS Scalar sum(const oclMat &m);
513 CV_EXPORTS Scalar absSum(const oclMat &m);
514 CV_EXPORTS Scalar sqrSum(const oclMat &m);
516 //! finds global minimum and maximum array elements and returns their values
517 // support all C1 types
518 CV_EXPORTS void minMax(const oclMat &src, double *minVal, double *maxVal = 0, const oclMat &mask = oclMat());
520 //! finds global minimum and maximum array elements and returns their values with locations
521 // support all C1 types
522 CV_EXPORTS void minMaxLoc(const oclMat &src, double *minVal, double *maxVal = 0, Point *minLoc = 0, Point *maxLoc = 0,
523 const oclMat &mask = oclMat());
525 //! counts non-zero array elements
527 CV_EXPORTS int countNonZero(const oclMat &src);
529 //! transforms 8-bit unsigned integers using lookup table: dst(i)=lut(src(i))
530 // destination array will have the depth type as lut and the same channels number as source
531 //It supports 8UC1 8UC4 only
532 CV_EXPORTS void LUT(const oclMat &src, const oclMat &lut, oclMat &dst);
534 //! only 8UC1 and 256 bins is supported now
535 CV_EXPORTS void calcHist(const oclMat &mat_src, oclMat &mat_hist);
536 //! only 8UC1 and 256 bins is supported now
537 CV_EXPORTS void equalizeHist(const oclMat &mat_src, oclMat &mat_dst);
539 //! only 8UC1 is supported now
540 CV_EXPORTS Ptr<cv::CLAHE> createCLAHE(double clipLimit = 40.0, Size tileGridSize = Size(8, 8));
543 // supports 8UC1 8UC4
544 CV_EXPORTS void bilateralFilter(const oclMat& src, oclMat& dst, int d, double sigmaColor, double sigmaSpace, int borderType=BORDER_DEFAULT);
546 //! Applies an adaptive bilateral filter to the input image
547 // Unlike the usual bilateral filter that uses fixed value for sigmaColor,
548 // the adaptive version calculates the local variance in he ksize neighborhood
549 // and use this as sigmaColor, for the value filtering. However, the local standard deviation is
550 // clamped to the maxSigmaColor.
551 // supports 8UC1, 8UC3
552 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);
554 //! computes exponent of each matrix element (dst = e**src)
555 // supports only CV_32FC1, CV_64FC1 type
556 CV_EXPORTS void exp(const oclMat &src, oclMat &dst);
558 //! computes natural logarithm of absolute value of each matrix element: dst = log(abs(src))
559 // supports only CV_32FC1, CV_64FC1 type
560 CV_EXPORTS void log(const oclMat &src, oclMat &dst);
562 //! computes square root of each matrix element
563 // supports only CV_32FC1, CV_64FC1 type
564 CV_EXPORTS void sqrt(const oclMat &src, oclMat &dst);
566 //! computes magnitude of each (x(i), y(i)) vector
567 // supports only CV_32F, CV_64F type
568 CV_EXPORTS void magnitude(const oclMat &x, const oclMat &y, oclMat &magnitude);
570 //! computes angle (angle(i)) of each (x(i), y(i)) vector
571 // supports only CV_32F, CV_64F type
572 CV_EXPORTS void phase(const oclMat &x, const oclMat &y, oclMat &angle, bool angleInDegrees = false);
574 //! the function raises every element of tne input array to p
575 // support only CV_32F, CV_64F type
576 CV_EXPORTS void pow(const oclMat &x, double p, oclMat &y);
578 //! converts Cartesian coordinates to polar
579 // supports only CV_32F CV_64F type
580 CV_EXPORTS void cartToPolar(const oclMat &x, const oclMat &y, oclMat &magnitude, oclMat &angle, bool angleInDegrees = false);
582 //! converts polar coordinates to Cartesian
583 // supports only CV_32F CV_64F type
584 CV_EXPORTS void polarToCart(const oclMat &magnitude, const oclMat &angle, oclMat &x, oclMat &y, bool angleInDegrees = false);
586 //! perfroms per-elements bit-wise inversion
587 // supports all types
588 CV_EXPORTS void bitwise_not(const oclMat &src, oclMat &dst);
590 //! calculates per-element bit-wise disjunction of two arrays
591 // supports all types
592 CV_EXPORTS void bitwise_or(const oclMat &src1, const oclMat &src2, oclMat &dst, const oclMat &mask = oclMat());
593 CV_EXPORTS void bitwise_or(const oclMat &src1, const Scalar &s, oclMat &dst, const oclMat &mask = oclMat());
595 //! calculates per-element bit-wise conjunction of two arrays
596 // supports all types
597 CV_EXPORTS void bitwise_and(const oclMat &src1, const oclMat &src2, oclMat &dst, const oclMat &mask = oclMat());
598 CV_EXPORTS void bitwise_and(const oclMat &src1, const Scalar &s, oclMat &dst, const oclMat &mask = oclMat());
600 //! calculates per-element bit-wise "exclusive or" operation
601 // supports all types
602 CV_EXPORTS void bitwise_xor(const oclMat &src1, const oclMat &src2, oclMat &dst, const oclMat &mask = oclMat());
603 CV_EXPORTS void bitwise_xor(const oclMat &src1, const Scalar &s, oclMat &dst, const oclMat &mask = oclMat());
605 //! Logical operators
606 CV_EXPORTS oclMat operator ~ (const oclMat &);
607 CV_EXPORTS oclMat operator | (const oclMat &, const oclMat &);
608 CV_EXPORTS oclMat operator & (const oclMat &, const oclMat &);
609 CV_EXPORTS oclMat operator ^ (const oclMat &, const oclMat &);
612 //! Mathematics operators
613 CV_EXPORTS oclMatExpr operator + (const oclMat &src1, const oclMat &src2);
614 CV_EXPORTS oclMatExpr operator - (const oclMat &src1, const oclMat &src2);
615 CV_EXPORTS oclMatExpr operator * (const oclMat &src1, const oclMat &src2);
616 CV_EXPORTS oclMatExpr operator / (const oclMat &src1, const oclMat &src2);
618 struct CV_EXPORTS ConvolveBuf
622 Size user_block_size;
625 oclMat image_spect, templ_spect, result_spect;
626 oclMat image_block, templ_block, result_data;
628 void create(Size image_size, Size templ_size);
629 static Size estimateBlockSize(Size result_size, Size templ_size);
632 //! computes convolution of two images, may use discrete Fourier transform
633 // support only CV_32FC1 type
634 CV_EXPORTS void convolve(const oclMat &image, const oclMat &temp1, oclMat &result, bool ccorr = false);
635 CV_EXPORTS void convolve(const oclMat &image, const oclMat &temp1, oclMat &result, bool ccorr, ConvolveBuf& buf);
637 //! Performs a per-element multiplication of two Fourier spectrums.
638 //! Only full (not packed) CV_32FC2 complex spectrums in the interleaved format are supported for now.
639 //! support only CV_32FC2 type
640 CV_EXPORTS void mulSpectrums(const oclMat &a, const oclMat &b, oclMat &c, int flags, float scale, bool conjB = false);
642 CV_EXPORTS void cvtColor(const oclMat &src, oclMat &dst, int code, int dcn = 0);
644 //! initializes a scaled identity matrix
645 CV_EXPORTS void setIdentity(oclMat& src, const Scalar & val = Scalar(1));
647 //! fills the output array with repeated copies of the input array
648 CV_EXPORTS void repeat(const oclMat & src, int ny, int nx, oclMat & dst);
650 //////////////////////////////// Filter Engine ////////////////////////////////
653 The Base Class for 1D or Row-wise Filters
655 This is the base class for linear or non-linear filters that process 1D data.
656 In particular, such filters are used for the "horizontal" filtering parts in separable filters.
658 class CV_EXPORTS BaseRowFilter_GPU
661 BaseRowFilter_GPU(int ksize_, int anchor_, int bordertype_) : ksize(ksize_), anchor(anchor_), bordertype(bordertype_) {}
662 virtual ~BaseRowFilter_GPU() {}
663 virtual void operator()(const oclMat &src, oclMat &dst) = 0;
664 int ksize, anchor, bordertype;
668 The Base Class for Column-wise Filters
670 This is the base class for linear or non-linear filters that process columns of 2D arrays.
671 Such filters are used for the "vertical" filtering parts in separable filters.
673 class CV_EXPORTS BaseColumnFilter_GPU
676 BaseColumnFilter_GPU(int ksize_, int anchor_, int bordertype_) : ksize(ksize_), anchor(anchor_), bordertype(bordertype_) {}
677 virtual ~BaseColumnFilter_GPU() {}
678 virtual void operator()(const oclMat &src, oclMat &dst) = 0;
679 int ksize, anchor, bordertype;
683 The Base Class for Non-Separable 2D Filters.
685 This is the base class for linear or non-linear 2D filters.
687 class CV_EXPORTS BaseFilter_GPU
690 BaseFilter_GPU(const Size &ksize_, const Point &anchor_, const int &borderType_)
691 : ksize(ksize_), anchor(anchor_), borderType(borderType_) {}
692 virtual ~BaseFilter_GPU() {}
693 virtual void operator()(const oclMat &src, oclMat &dst) = 0;
700 The Base Class for Filter Engine.
702 The class can be used to apply an arbitrary filtering operation to an image.
703 It contains all the necessary intermediate buffers.
705 class CV_EXPORTS FilterEngine_GPU
708 virtual ~FilterEngine_GPU() {}
710 virtual void apply(const oclMat &src, oclMat &dst, Rect roi = Rect(0, 0, -1, -1)) = 0;
713 //! returns the non-separable filter engine with the specified filter
714 CV_EXPORTS Ptr<FilterEngine_GPU> createFilter2D_GPU(const Ptr<BaseFilter_GPU> filter2D);
716 //! returns the primitive row filter with the specified kernel
717 CV_EXPORTS Ptr<BaseRowFilter_GPU> getLinearRowFilter_GPU(int srcType, int bufType, const Mat &rowKernel,
718 int anchor = -1, int bordertype = BORDER_DEFAULT);
720 //! returns the primitive column filter with the specified kernel
721 CV_EXPORTS Ptr<BaseColumnFilter_GPU> getLinearColumnFilter_GPU(int bufType, int dstType, const Mat &columnKernel,
722 int anchor = -1, int bordertype = BORDER_DEFAULT, double delta = 0.0);
724 //! returns the separable linear filter engine
725 CV_EXPORTS Ptr<FilterEngine_GPU> createSeparableLinearFilter_GPU(int srcType, int dstType, const Mat &rowKernel,
726 const Mat &columnKernel, const Point &anchor = Point(-1, -1), double delta = 0.0, int bordertype = BORDER_DEFAULT);
728 //! returns the separable filter engine with the specified filters
729 CV_EXPORTS Ptr<FilterEngine_GPU> createSeparableFilter_GPU(const Ptr<BaseRowFilter_GPU> &rowFilter,
730 const Ptr<BaseColumnFilter_GPU> &columnFilter);
732 //! returns the Gaussian filter engine
733 CV_EXPORTS Ptr<FilterEngine_GPU> createGaussianFilter_GPU(int type, Size ksize, double sigma1, double sigma2 = 0, int bordertype = BORDER_DEFAULT);
735 //! returns filter engine for the generalized Sobel operator
736 CV_EXPORTS Ptr<FilterEngine_GPU> createDerivFilter_GPU( int srcType, int dstType, int dx, int dy, int ksize, int borderType = BORDER_DEFAULT );
738 //! applies Laplacian operator to the image
739 // supports only ksize = 1 and ksize = 3
740 CV_EXPORTS void Laplacian(const oclMat &src, oclMat &dst, int ddepth, int ksize = 1, double scale = 1,
741 double delta=0, int borderType=BORDER_DEFAULT);
743 //! returns 2D box filter
744 // dst type must be the same as source type
745 CV_EXPORTS Ptr<BaseFilter_GPU> getBoxFilter_GPU(int srcType, int dstType,
746 const Size &ksize, Point anchor = Point(-1, -1), int borderType = BORDER_DEFAULT);
748 //! returns box filter engine
749 CV_EXPORTS Ptr<FilterEngine_GPU> createBoxFilter_GPU(int srcType, int dstType, const Size &ksize,
750 const Point &anchor = Point(-1, -1), int borderType = BORDER_DEFAULT);
752 //! returns 2D filter with the specified kernel
753 // supports: dst type must be the same as source type
754 CV_EXPORTS Ptr<BaseFilter_GPU> getLinearFilter_GPU(int srcType, int dstType, const Mat &kernel, const Size &ksize,
755 const Point &anchor = Point(-1, -1), int borderType = BORDER_DEFAULT);
757 //! returns the non-separable linear filter engine
758 // supports: dst type must be the same as source type
759 CV_EXPORTS Ptr<FilterEngine_GPU> createLinearFilter_GPU(int srcType, int dstType, const Mat &kernel,
760 const Point &anchor = Point(-1, -1), int borderType = BORDER_DEFAULT);
762 //! smooths the image using the normalized box filter
763 CV_EXPORTS void boxFilter(const oclMat &src, oclMat &dst, int ddepth, Size ksize,
764 Point anchor = Point(-1, -1), int borderType = BORDER_DEFAULT);
766 //! returns 2D morphological filter
767 //! only MORPH_ERODE and MORPH_DILATE are supported
768 // supports CV_8UC1, CV_8UC4, CV_32FC1 and CV_32FC4 types
769 // kernel must have CV_8UC1 type, one rows and cols == ksize.width * ksize.height
770 CV_EXPORTS Ptr<BaseFilter_GPU> getMorphologyFilter_GPU(int op, int type, const Mat &kernel, const Size &ksize,
771 Point anchor = Point(-1, -1));
773 //! returns morphological filter engine. Only MORPH_ERODE and MORPH_DILATE are supported.
774 CV_EXPORTS Ptr<FilterEngine_GPU> createMorphologyFilter_GPU(int op, int type, const Mat &kernel,
775 const Point &anchor = Point(-1, -1), int iterations = 1);
777 //! a synonym for normalized box filter
778 static inline void blur(const oclMat &src, oclMat &dst, Size ksize, Point anchor = Point(-1, -1),
779 int borderType = BORDER_CONSTANT)
781 boxFilter(src, dst, -1, ksize, anchor, borderType);
784 //! applies non-separable 2D linear filter to the image
785 CV_EXPORTS void filter2D(const oclMat &src, oclMat &dst, int ddepth, const Mat &kernel,
786 Point anchor = Point(-1, -1), double delta = 0.0, int borderType = BORDER_DEFAULT);
788 //! applies separable 2D linear filter to the image
789 CV_EXPORTS void sepFilter2D(const oclMat &src, oclMat &dst, int ddepth, const Mat &kernelX, const Mat &kernelY,
790 Point anchor = Point(-1, -1), double delta = 0.0, int bordertype = BORDER_DEFAULT);
792 //! applies generalized Sobel operator to the image
793 // dst.type must equalize src.type
794 // supports data type: CV_8UC1, CV_8UC4, CV_32FC1 and CV_32FC4
795 // supports border type: BORDER_CONSTANT, BORDER_REPLICATE, BORDER_REFLECT,BORDER_REFLECT_101
796 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);
798 //! applies the vertical or horizontal Scharr operator to the image
799 // dst.type must equalize src.type
800 // supports data type: CV_8UC1, CV_8UC4, CV_32FC1 and CV_32FC4
801 // supports border type: BORDER_CONSTANT, BORDER_REPLICATE, BORDER_REFLECT,BORDER_REFLECT_101
802 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);
804 //! smooths the image using Gaussian filter.
805 // dst.type must equalize src.type
806 // supports data type: CV_8UC1, CV_8UC4, CV_32FC1 and CV_32FC4
807 // supports border type: BORDER_CONSTANT, BORDER_REPLICATE, BORDER_REFLECT,BORDER_REFLECT_101
808 CV_EXPORTS void GaussianBlur(const oclMat &src, oclMat &dst, Size ksize, double sigma1, double sigma2 = 0, int bordertype = BORDER_DEFAULT);
810 //! erodes the image (applies the local minimum operator)
811 // supports data type: CV_8UC1, CV_8UC4, CV_32FC1 and CV_32FC4
812 CV_EXPORTS void erode( const oclMat &src, oclMat &dst, const Mat &kernel, Point anchor = Point(-1, -1), int iterations = 1,
814 int borderType = BORDER_CONSTANT, const Scalar &borderValue = morphologyDefaultBorderValue());
817 //! dilates the image (applies the local maximum operator)
818 // supports data type: CV_8UC1, CV_8UC4, CV_32FC1 and CV_32FC4
819 CV_EXPORTS void dilate( const oclMat &src, oclMat &dst, const Mat &kernel, Point anchor = Point(-1, -1), int iterations = 1,
821 int borderType = BORDER_CONSTANT, const Scalar &borderValue = morphologyDefaultBorderValue());
824 //! applies an advanced morphological operation to the image
825 CV_EXPORTS void morphologyEx( const oclMat &src, oclMat &dst, int op, const Mat &kernel, Point anchor = Point(-1, -1), int iterations = 1,
827 int borderType = BORDER_CONSTANT, const Scalar &borderValue = morphologyDefaultBorderValue());
830 ////////////////////////////// Image processing //////////////////////////////
831 //! Does mean shift filtering on GPU.
832 CV_EXPORTS void meanShiftFiltering(const oclMat &src, oclMat &dst, int sp, int sr,
833 TermCriteria criteria = TermCriteria(TermCriteria::MAX_ITER + TermCriteria::EPS, 5, 1));
835 //! Does mean shift procedure on GPU.
836 CV_EXPORTS void meanShiftProc(const oclMat &src, oclMat &dstr, oclMat &dstsp, int sp, int sr,
837 TermCriteria criteria = TermCriteria(TermCriteria::MAX_ITER + TermCriteria::EPS, 5, 1));
839 //! Does mean shift segmentation with elimiation of small regions.
840 CV_EXPORTS void meanShiftSegmentation(const oclMat &src, Mat &dst, int sp, int sr, int minsize,
841 TermCriteria criteria = TermCriteria(TermCriteria::MAX_ITER + TermCriteria::EPS, 5, 1));
843 //! applies fixed threshold to the image.
844 // supports CV_8UC1 and CV_32FC1 data type
845 // supports threshold type: THRESH_BINARY, THRESH_BINARY_INV, THRESH_TRUNC, THRESH_TOZERO, THRESH_TOZERO_INV
846 CV_EXPORTS double threshold(const oclMat &src, oclMat &dst, double thresh, double maxVal, int type = THRESH_TRUNC);
848 //! resizes the image
849 // Supports INTER_NEAREST, INTER_LINEAR
850 // supports CV_8UC1, CV_8UC4, CV_32FC1 and CV_32FC4 types
851 CV_EXPORTS void resize(const oclMat &src, oclMat &dst, Size dsize, double fx = 0, double fy = 0, int interpolation = INTER_LINEAR);
853 //! Applies a generic geometrical transformation to an image.
855 // Supports INTER_NEAREST, INTER_LINEAR.
856 // Map1 supports CV_16SC2, CV_32FC2 types.
857 // Src supports CV_8UC1, CV_8UC2, CV_8UC4.
858 CV_EXPORTS void remap(const oclMat &src, oclMat &dst, oclMat &map1, oclMat &map2, int interpolation, int bordertype, const Scalar &value = Scalar());
860 //! copies 2D array to a larger destination array and pads borders with user-specifiable constant
861 // supports CV_8UC1, CV_8UC4, CV_32SC1 types
862 CV_EXPORTS void copyMakeBorder(const oclMat &src, oclMat &dst, int top, int bottom, int left, int right, int boardtype, const Scalar &value = Scalar());
864 //! Smoothes image using median filter
865 // The source 1- or 4-channel image. m should be 3 or 5, the image depth should be CV_8U or CV_32F.
866 CV_EXPORTS void medianFilter(const oclMat &src, oclMat &dst, int m);
868 //! warps the image using affine transformation
869 // Supports INTER_NEAREST, INTER_LINEAR, INTER_CUBIC
870 // supports CV_8UC1, CV_8UC4, CV_32FC1 and CV_32FC4 types
871 CV_EXPORTS void warpAffine(const oclMat &src, oclMat &dst, const Mat &M, Size dsize, int flags = INTER_LINEAR);
873 //! warps the image using perspective transformation
874 // Supports INTER_NEAREST, INTER_LINEAR, INTER_CUBIC
875 // supports CV_8UC1, CV_8UC4, CV_32FC1 and CV_32FC4 types
876 CV_EXPORTS void warpPerspective(const oclMat &src, oclMat &dst, const Mat &M, Size dsize, int flags = INTER_LINEAR);
878 //! computes the integral image and integral for the squared image
879 // sum will support CV_32S, CV_32F, sqsum - support CV32F, CV_64F
880 // supports only CV_8UC1 source type
881 CV_EXPORTS void integral(const oclMat &src, oclMat &sum, oclMat &sqsum, int sdepth=-1 );
882 CV_EXPORTS void integral(const oclMat &src, oclMat &sum, int sdepth=-1 );
883 CV_EXPORTS void cornerHarris(const oclMat &src, oclMat &dst, int blockSize, int ksize, double k, int bordertype = cv::BORDER_DEFAULT);
884 CV_EXPORTS void cornerHarris_dxdy(const oclMat &src, oclMat &dst, oclMat &Dx, oclMat &Dy,
885 int blockSize, int ksize, double k, int bordertype = cv::BORDER_DEFAULT);
886 CV_EXPORTS void cornerMinEigenVal(const oclMat &src, oclMat &dst, int blockSize, int ksize, int bordertype = cv::BORDER_DEFAULT);
887 CV_EXPORTS void cornerMinEigenVal_dxdy(const oclMat &src, oclMat &dst, oclMat &Dx, oclMat &Dy,
888 int blockSize, int ksize, int bordertype = cv::BORDER_DEFAULT);
891 /////////////////////////////////// ML ///////////////////////////////////////////
893 //! Compute closest centers for each lines in source and lable it after center's index
894 // supports CV_32FC1/CV_32FC2/CV_32FC4 data type
895 // supports NORM_L1 and NORM_L2 distType
896 // if indices is provided, only the indexed rows will be calculated and their results are in the same
898 CV_EXPORTS void distanceToCenters(const oclMat &src, const oclMat ¢ers, Mat &dists, Mat &labels, int distType = NORM_L2SQR);
900 //!Does k-means procedure on GPU
901 // supports CV_32FC1/CV_32FC2/CV_32FC4 data type
902 CV_EXPORTS double kmeans(const oclMat &src, int K, oclMat &bestLabels,
903 TermCriteria criteria, int attemps, int flags, oclMat ¢ers);
906 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
907 ///////////////////////////////////////////CascadeClassifier//////////////////////////////////////////////////////////////////
908 ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
909 class CV_EXPORTS OclCascadeClassifier : public cv::CascadeClassifier
912 void detectMultiScale(oclMat &image, CV_OUT std::vector<cv::Rect>& faces,
913 double scaleFactor = 1.1, int minNeighbors = 3, int flags = 0,
914 Size minSize = Size(), Size maxSize = Size());
917 /////////////////////////////// Pyramid /////////////////////////////////////
918 CV_EXPORTS void pyrDown(const oclMat &src, oclMat &dst);
920 //! upsamples the source image and then smoothes it
921 CV_EXPORTS void pyrUp(const oclMat &src, oclMat &dst);
923 //! performs linear blending of two images
924 //! to avoid accuracy errors sum of weigths shouldn't be very close to zero
925 // supports only CV_8UC1 source type
926 CV_EXPORTS void blendLinear(const oclMat &img1, const oclMat &img2, const oclMat &weights1, const oclMat &weights2, oclMat &result);
928 //! computes vertical sum, supports only CV_32FC1 images
929 CV_EXPORTS void columnSum(const oclMat &src, oclMat &sum);
931 ///////////////////////////////////////// match_template /////////////////////////////////////////////////////////////
932 struct CV_EXPORTS MatchTemplateBuf
934 Size user_block_size;
935 oclMat imagef, templf;
936 std::vector<oclMat> images;
937 std::vector<oclMat> image_sums;
938 std::vector<oclMat> image_sqsums;
941 //! computes the proximity map for the raster template and the image where the template is searched for
942 // Supports TM_SQDIFF, TM_SQDIFF_NORMED, TM_CCORR, TM_CCORR_NORMED, TM_CCOEFF, TM_CCOEFF_NORMED for type 8UC1 and 8UC4
943 // Supports TM_SQDIFF, TM_CCORR for type 32FC1 and 32FC4
944 CV_EXPORTS void matchTemplate(const oclMat &image, const oclMat &templ, oclMat &result, int method);
946 //! computes the proximity map for the raster template and the image where the template is searched for
947 // Supports TM_SQDIFF, TM_SQDIFF_NORMED, TM_CCORR, TM_CCORR_NORMED, TM_CCOEFF, TM_CCOEFF_NORMED for type 8UC1 and 8UC4
948 // Supports TM_SQDIFF, TM_CCORR for type 32FC1 and 32FC4
949 CV_EXPORTS void matchTemplate(const oclMat &image, const oclMat &templ, oclMat &result, int method, MatchTemplateBuf &buf);
953 ///////////////////////////////////////////// Canny /////////////////////////////////////////////
954 struct CV_EXPORTS CannyBuf;
956 //! compute edges of the input image using Canny operator
957 // Support CV_8UC1 only
958 CV_EXPORTS void Canny(const oclMat &image, oclMat &edges, double low_thresh, double high_thresh, int apperture_size = 3, bool L2gradient = false);
959 CV_EXPORTS void Canny(const oclMat &image, CannyBuf &buf, oclMat &edges, double low_thresh, double high_thresh, int apperture_size = 3, bool L2gradient = false);
960 CV_EXPORTS void Canny(const oclMat &dx, const oclMat &dy, oclMat &edges, double low_thresh, double high_thresh, bool L2gradient = false);
961 CV_EXPORTS void Canny(const oclMat &dx, const oclMat &dy, CannyBuf &buf, oclMat &edges, double low_thresh, double high_thresh, bool L2gradient = false);
963 struct CV_EXPORTS CannyBuf
965 CannyBuf() : counter(1, 1, CV_32S) { }
970 explicit CannyBuf(const Size &image_size, int apperture_size = 3) : counter(1, 1, CV_32S)
972 create(image_size, apperture_size);
974 CannyBuf(const oclMat &dx_, const oclMat &dy_);
975 void create(const Size &image_size, int apperture_size = 3);
979 oclMat dx_buf, dy_buf;
980 oclMat magBuf, mapBuf;
981 oclMat trackBuf1, trackBuf2;
983 Ptr<FilterEngine_GPU> filterDX, filterDY;
986 ///////////////////////////////////////// Hough Transform /////////////////////////////////////////
988 struct HoughCirclesBuf
997 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);
998 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);
999 CV_EXPORTS void HoughCirclesDownload(const oclMat& d_circles, OutputArray h_circles);
1002 ///////////////////////////////////////// clAmdFft related /////////////////////////////////////////
1003 //! Performs a forward or inverse discrete Fourier transform (1D or 2D) of floating point matrix.
1004 //! Param dft_size is the size of DFT transform.
1006 //! For complex-to-real transform it is assumed that the source matrix is packed in CLFFT's format.
1007 // support src type of CV32FC1, CV32FC2
1008 // support flags: DFT_INVERSE, DFT_REAL_OUTPUT, DFT_COMPLEX_OUTPUT, DFT_ROWS
1009 // dft_size is the size of original input, which is used for transformation from complex to real.
1010 // dft_size must be powers of 2, 3 and 5
1011 // real to complex dft requires at least v1.8 clAmdFft
1012 // real to complex dft output is not the same with cpu version
1013 // real to complex and complex to real does not support DFT_ROWS
1014 CV_EXPORTS void dft(const oclMat &src, oclMat &dst, Size dft_size = Size(), int flags = 0);
1016 //! implements generalized matrix product algorithm GEMM from BLAS
1017 // The functionality requires clAmdBlas library
1018 // only support type CV_32FC1
1019 // flag GEMM_3_T is not supported
1020 CV_EXPORTS void gemm(const oclMat &src1, const oclMat &src2, double alpha,
1021 const oclMat &src3, double beta, oclMat &dst, int flags = 0);
1023 //////////////// HOG (Histogram-of-Oriented-Gradients) Descriptor and Object Detector //////////////
1025 struct CV_EXPORTS HOGDescriptor
1029 enum { DEFAULT_WIN_SIGMA = -1 };
1031 enum { DEFAULT_NLEVELS = 64 };
1033 enum { DESCR_FORMAT_ROW_BY_ROW, DESCR_FORMAT_COL_BY_COL };
1037 HOGDescriptor(Size win_size = Size(64, 128), Size block_size = Size(16, 16),
1039 Size block_stride = Size(8, 8), Size cell_size = Size(8, 8),
1041 int nbins = 9, double win_sigma = DEFAULT_WIN_SIGMA,
1043 double threshold_L2hys = 0.2, bool gamma_correction = true,
1045 int nlevels = DEFAULT_NLEVELS);
1049 size_t getDescriptorSize() const;
1051 size_t getBlockHistogramSize() const;
1055 void setSVMDetector(const std::vector<float> &detector);
1059 static std::vector<float> getDefaultPeopleDetector();
1061 static std::vector<float> getPeopleDetector48x96();
1063 static std::vector<float> getPeopleDetector64x128();
1067 void detect(const oclMat &img, std::vector<Point> &found_locations,
1069 double hit_threshold = 0, Size win_stride = Size(),
1071 Size padding = Size());
1075 void detectMultiScale(const oclMat &img, std::vector<Rect> &found_locations,
1077 double hit_threshold = 0, Size win_stride = Size(),
1079 Size padding = Size(), double scale0 = 1.05,
1081 int group_threshold = 2);
1085 void getDescriptors(const oclMat &img, Size win_stride,
1087 oclMat &descriptors,
1089 int descr_format = DESCR_FORMAT_COL_BY_COL);
1105 double threshold_L2hys;
1107 bool gamma_correction;
1115 // initialize buffers; only need to do once in case of multiscale detection
1117 void init_buffer(const oclMat &img, Size win_stride);
1121 void computeBlockHistograms(const oclMat &img);
1123 void computeGradient(const oclMat &img, oclMat &grad, oclMat &qangle);
1127 double getWinSigma() const;
1129 bool checkDetectorSize() const;
1133 static int numPartsWithin(int size, int part_size, int stride);
1135 static Size numPartsWithin(Size size, Size part_size, Size stride);
1139 // Coefficients of the separating plane
1147 // Results of the last classification step
1155 // Results of the last histogram evaluation step
1161 // Gradients conputation results
1163 oclMat grad, qangle;
1173 // effect size of input image (might be different from original size after scaling)
1180 ////////////////////////feature2d_ocl/////////////////
1181 /****************************************************************************************\
1183 \****************************************************************************************/
1184 template<typename T>
1185 struct CV_EXPORTS Accumulator
1189 template<> struct Accumulator<unsigned char>
1193 template<> struct Accumulator<unsigned short>
1197 template<> struct Accumulator<char>
1201 template<> struct Accumulator<short>
1207 * Manhattan distance (city block distance) functor
1210 struct CV_EXPORTS L1
1212 enum { normType = NORM_L1 };
1213 typedef T ValueType;
1214 typedef typename Accumulator<T>::Type ResultType;
1216 ResultType operator()( const T *a, const T *b, int size ) const
1218 return normL1<ValueType, ResultType>(a, b, size);
1223 * Euclidean distance functor
1226 struct CV_EXPORTS L2
1228 enum { normType = NORM_L2 };
1229 typedef T ValueType;
1230 typedef typename Accumulator<T>::Type ResultType;
1232 ResultType operator()( const T *a, const T *b, int size ) const
1234 return (ResultType)std::sqrt((double)normL2Sqr<ValueType, ResultType>(a, b, size));
1239 * Hamming distance functor - counts the bit differences between two strings - useful for the Brief descriptor
1240 * bit count of A exclusive XOR'ed with B
1242 struct CV_EXPORTS Hamming
1244 enum { normType = NORM_HAMMING };
1245 typedef unsigned char ValueType;
1246 typedef int ResultType;
1248 /** this will count the bits in a ^ b
1250 ResultType operator()( const unsigned char *a, const unsigned char *b, int size ) const
1252 return normHamming(a, b, size);
1256 ////////////////////////////////// BruteForceMatcher //////////////////////////////////
1258 class CV_EXPORTS BruteForceMatcher_OCL_base
1261 enum DistType {L1Dist = 0, L2Dist, HammingDist};
1262 explicit BruteForceMatcher_OCL_base(DistType distType = L2Dist);
1264 // Add descriptors to train descriptor collection
1265 void add(const std::vector<oclMat> &descCollection);
1267 // Get train descriptors collection
1268 const std::vector<oclMat> &getTrainDescriptors() const;
1270 // Clear train descriptors collection
1273 // Return true if there are not train descriptors in collection
1276 // Return true if the matcher supports mask in match methods
1277 bool isMaskSupported() const;
1279 // Find one best match for each query descriptor
1280 void matchSingle(const oclMat &query, const oclMat &train,
1281 oclMat &trainIdx, oclMat &distance,
1282 const oclMat &mask = oclMat());
1284 // Download trainIdx and distance and convert it to CPU vector with DMatch
1285 static void matchDownload(const oclMat &trainIdx, const oclMat &distance, std::vector<DMatch> &matches);
1286 // Convert trainIdx and distance to vector with DMatch
1287 static void matchConvert(const Mat &trainIdx, const Mat &distance, std::vector<DMatch> &matches);
1289 // Find one best match for each query descriptor
1290 void match(const oclMat &query, const oclMat &train, std::vector<DMatch> &matches, const oclMat &mask = oclMat());
1292 // Make gpu collection of trains and masks in suitable format for matchCollection function
1293 void makeGpuCollection(oclMat &trainCollection, oclMat &maskCollection, const std::vector<oclMat> &masks = std::vector<oclMat>());
1295 // Find one best match from train collection for each query descriptor
1296 void matchCollection(const oclMat &query, const oclMat &trainCollection,
1297 oclMat &trainIdx, oclMat &imgIdx, oclMat &distance,
1298 const oclMat &masks = oclMat());
1300 // Download trainIdx, imgIdx and distance and convert it to vector with DMatch
1301 static void matchDownload(const oclMat &trainIdx, const oclMat &imgIdx, const oclMat &distance, std::vector<DMatch> &matches);
1302 // Convert trainIdx, imgIdx and distance to vector with DMatch
1303 static void matchConvert(const Mat &trainIdx, const Mat &imgIdx, const Mat &distance, std::vector<DMatch> &matches);
1305 // Find one best match from train collection for each query descriptor.
1306 void match(const oclMat &query, std::vector<DMatch> &matches, const std::vector<oclMat> &masks = std::vector<oclMat>());
1308 // Find k best matches for each query descriptor (in increasing order of distances)
1309 void knnMatchSingle(const oclMat &query, const oclMat &train,
1310 oclMat &trainIdx, oclMat &distance, oclMat &allDist, int k,
1311 const oclMat &mask = oclMat());
1313 // Download trainIdx and distance and convert it to vector with DMatch
1314 // compactResult is used when mask is not empty. If compactResult is false matches
1315 // vector will have the same size as queryDescriptors rows. If compactResult is true
1316 // matches vector will not contain matches for fully masked out query descriptors.
1317 static void knnMatchDownload(const oclMat &trainIdx, const oclMat &distance,
1318 std::vector< std::vector<DMatch> > &matches, bool compactResult = false);
1319 // Convert trainIdx and distance to vector with DMatch
1320 static void knnMatchConvert(const Mat &trainIdx, const Mat &distance,
1321 std::vector< std::vector<DMatch> > &matches, bool compactResult = false);
1323 // Find k best matches for each query descriptor (in increasing order of distances).
1324 // compactResult is used when mask is not empty. If compactResult is false matches
1325 // vector will have the same size as queryDescriptors rows. If compactResult is true
1326 // matches vector will not contain matches for fully masked out query descriptors.
1327 void knnMatch(const oclMat &query, const oclMat &train,
1328 std::vector< std::vector<DMatch> > &matches, int k, const oclMat &mask = oclMat(),
1329 bool compactResult = false);
1331 // Find k best matches from train collection for each query descriptor (in increasing order of distances)
1332 void knnMatch2Collection(const oclMat &query, const oclMat &trainCollection,
1333 oclMat &trainIdx, oclMat &imgIdx, oclMat &distance,
1334 const oclMat &maskCollection = oclMat());
1336 // Download trainIdx and distance and convert it to vector with DMatch
1337 // compactResult is used when mask is not empty. If compactResult is false matches
1338 // vector will have the same size as queryDescriptors rows. If compactResult is true
1339 // matches vector will not contain matches for fully masked out query descriptors.
1340 static void knnMatch2Download(const oclMat &trainIdx, const oclMat &imgIdx, const oclMat &distance,
1341 std::vector< std::vector<DMatch> > &matches, bool compactResult = false);
1342 // Convert trainIdx and distance to vector with DMatch
1343 static void knnMatch2Convert(const Mat &trainIdx, const Mat &imgIdx, const Mat &distance,
1344 std::vector< std::vector<DMatch> > &matches, bool compactResult = false);
1346 // Find k best matches for each query descriptor (in increasing order of distances).
1347 // compactResult is used when mask is not empty. If compactResult is false matches
1348 // vector will have the same size as queryDescriptors rows. If compactResult is true
1349 // matches vector will not contain matches for fully masked out query descriptors.
1350 void knnMatch(const oclMat &query, std::vector< std::vector<DMatch> > &matches, int k,
1351 const std::vector<oclMat> &masks = std::vector<oclMat>(), bool compactResult = false);
1353 // Find best matches for each query descriptor which have distance less than maxDistance.
1354 // nMatches.at<int>(0, queryIdx) will contain matches count for queryIdx.
1355 // carefully nMatches can be greater than trainIdx.cols - it means that matcher didn't find all matches,
1356 // because it didn't have enough memory.
1357 // If trainIdx is empty, then trainIdx and distance will be created with size nQuery x max((nTrain / 100), 10),
1358 // otherwize user can pass own allocated trainIdx and distance with size nQuery x nMaxMatches
1359 // Matches doesn't sorted.
1360 void radiusMatchSingle(const oclMat &query, const oclMat &train,
1361 oclMat &trainIdx, oclMat &distance, oclMat &nMatches, float maxDistance,
1362 const oclMat &mask = oclMat());
1364 // Download trainIdx, nMatches and distance and convert it to vector with DMatch.
1365 // matches will be sorted in increasing order of distances.
1366 // compactResult is used when mask is not empty. If compactResult is false matches
1367 // vector will have the same size as queryDescriptors rows. If compactResult is true
1368 // matches vector will not contain matches for fully masked out query descriptors.
1369 static void radiusMatchDownload(const oclMat &trainIdx, const oclMat &distance, const oclMat &nMatches,
1370 std::vector< std::vector<DMatch> > &matches, bool compactResult = false);
1371 // Convert trainIdx, nMatches and distance to vector with DMatch.
1372 static void radiusMatchConvert(const Mat &trainIdx, const Mat &distance, const Mat &nMatches,
1373 std::vector< std::vector<DMatch> > &matches, bool compactResult = false);
1375 // Find best matches for each query descriptor which have distance less than maxDistance
1376 // in increasing order of distances).
1377 void radiusMatch(const oclMat &query, const oclMat &train,
1378 std::vector< std::vector<DMatch> > &matches, float maxDistance,
1379 const oclMat &mask = oclMat(), bool compactResult = false);
1381 // Find best matches for each query descriptor which have distance less than maxDistance.
1382 // If trainIdx is empty, then trainIdx and distance will be created with size nQuery x max((nQuery / 100), 10),
1383 // otherwize user can pass own allocated trainIdx and distance with size nQuery x nMaxMatches
1384 // Matches doesn't sorted.
1385 void radiusMatchCollection(const oclMat &query, oclMat &trainIdx, oclMat &imgIdx, oclMat &distance, oclMat &nMatches, float maxDistance,
1386 const std::vector<oclMat> &masks = std::vector<oclMat>());
1388 // Download trainIdx, imgIdx, nMatches and distance and convert it to vector with DMatch.
1389 // matches will be sorted in increasing order of distances.
1390 // compactResult is used when mask is not empty. If compactResult is false matches
1391 // vector will have the same size as queryDescriptors rows. If compactResult is true
1392 // matches vector will not contain matches for fully masked out query descriptors.
1393 static void radiusMatchDownload(const oclMat &trainIdx, const oclMat &imgIdx, const oclMat &distance, const oclMat &nMatches,
1394 std::vector< std::vector<DMatch> > &matches, bool compactResult = false);
1395 // Convert trainIdx, nMatches and distance to vector with DMatch.
1396 static void radiusMatchConvert(const Mat &trainIdx, const Mat &imgIdx, const Mat &distance, const Mat &nMatches,
1397 std::vector< std::vector<DMatch> > &matches, bool compactResult = false);
1399 // Find best matches from train collection for each query descriptor which have distance less than
1400 // maxDistance (in increasing order of distances).
1401 void radiusMatch(const oclMat &query, std::vector< std::vector<DMatch> > &matches, float maxDistance,
1402 const std::vector<oclMat> &masks = std::vector<oclMat>(), bool compactResult = false);
1407 std::vector<oclMat> trainDescCollection;
1410 template <class Distance>
1411 class CV_EXPORTS BruteForceMatcher_OCL;
1413 template <typename T>
1414 class CV_EXPORTS BruteForceMatcher_OCL< L1<T> > : public BruteForceMatcher_OCL_base
1417 explicit BruteForceMatcher_OCL() : BruteForceMatcher_OCL_base(L1Dist) {}
1418 explicit BruteForceMatcher_OCL(L1<T> /*d*/) : BruteForceMatcher_OCL_base(L1Dist) {}
1420 template <typename T>
1421 class CV_EXPORTS BruteForceMatcher_OCL< L2<T> > : public BruteForceMatcher_OCL_base
1424 explicit BruteForceMatcher_OCL() : BruteForceMatcher_OCL_base(L2Dist) {}
1425 explicit BruteForceMatcher_OCL(L2<T> /*d*/) : BruteForceMatcher_OCL_base(L2Dist) {}
1427 template <> class CV_EXPORTS BruteForceMatcher_OCL< Hamming > : public BruteForceMatcher_OCL_base
1430 explicit BruteForceMatcher_OCL() : BruteForceMatcher_OCL_base(HammingDist) {}
1431 explicit BruteForceMatcher_OCL(Hamming /*d*/) : BruteForceMatcher_OCL_base(HammingDist) {}
1434 class CV_EXPORTS BFMatcher_OCL : public BruteForceMatcher_OCL_base
1437 explicit BFMatcher_OCL(int norm = NORM_L2) : BruteForceMatcher_OCL_base(norm == NORM_L1 ? L1Dist : norm == NORM_L2 ? L2Dist : HammingDist) {}
1440 class CV_EXPORTS GoodFeaturesToTrackDetector_OCL
1443 explicit GoodFeaturesToTrackDetector_OCL(int maxCorners = 1000, double qualityLevel = 0.01, double minDistance = 0.0,
1444 int blockSize = 3, bool useHarrisDetector = false, double harrisK = 0.04);
1446 //! return 1 rows matrix with CV_32FC2 type
1447 void operator ()(const oclMat& image, oclMat& corners, const oclMat& mask = oclMat());
1448 //! download points of type Point2f to a vector. the vector's content will be erased
1449 void downloadPoints(const oclMat &points, std::vector<Point2f> &points_v);
1452 double qualityLevel;
1456 bool useHarrisDetector;
1458 void releaseMemory()
1463 minMaxbuf_.release();
1464 tmpCorners_.release();
1474 inline GoodFeaturesToTrackDetector_OCL::GoodFeaturesToTrackDetector_OCL(int maxCorners_, double qualityLevel_, double minDistance_,
1475 int blockSize_, bool useHarrisDetector_, double harrisK_)
1477 maxCorners = maxCorners_;
1478 qualityLevel = qualityLevel_;
1479 minDistance = minDistance_;
1480 blockSize = blockSize_;
1481 useHarrisDetector = useHarrisDetector_;
1485 ////////////////////////////////// FAST Feature Detector //////////////////////////////////
1486 class CV_EXPORTS FAST_OCL
1497 // all features have same size
1498 static const int FEATURE_SIZE = 7;
1500 explicit FAST_OCL(int threshold, bool nonmaxSupression = true, double keypointsRatio = 0.05);
1502 //! finds the keypoints using FAST detector
1503 //! supports only CV_8UC1 images
1504 void operator ()(const oclMat& image, const oclMat& mask, oclMat& keypoints);
1505 void operator ()(const oclMat& image, const oclMat& mask, std::vector<KeyPoint>& keypoints);
1507 //! download keypoints from device to host memory
1508 static void downloadKeypoints(const oclMat& d_keypoints, std::vector<KeyPoint>& keypoints);
1510 //! convert keypoints to KeyPoint vector
1511 static void convertKeypoints(const Mat& h_keypoints, std::vector<KeyPoint>& keypoints);
1513 //! release temporary buffer's memory
1516 bool nonmaxSupression;
1520 //! max keypoints = keypointsRatio * img.size().area()
1521 double keypointsRatio;
1523 //! find keypoints and compute it's response if nonmaxSupression is true
1524 //! return count of detected keypoints
1525 int calcKeyPointsLocation(const oclMat& image, const oclMat& mask);
1527 //! get final array of keypoints
1528 //! performs nonmax supression if needed
1529 //! return final count of keypoints
1530 int getKeyPoints(oclMat& keypoints);
1538 oclMat d_keypoints_;
1540 int calcKeypointsOCL(const oclMat& img, const oclMat& mask, int maxKeypoints);
1541 int nonmaxSupressionOCL(oclMat& keypoints);
1544 /////////////////////////////// PyrLKOpticalFlow /////////////////////////////////////
1546 class CV_EXPORTS PyrLKOpticalFlow
1551 winSize = Size(21, 21);
1555 useInitialFlow = false;
1556 minEigThreshold = 1e-4f;
1557 getMinEigenVals = false;
1558 isDeviceArch11_ = false;
1561 void sparse(const oclMat &prevImg, const oclMat &nextImg, const oclMat &prevPts, oclMat &nextPts,
1562 oclMat &status, oclMat *err = 0);
1564 void dense(const oclMat &prevImg, const oclMat &nextImg, oclMat &u, oclMat &v, oclMat *err = 0);
1570 bool useInitialFlow;
1571 float minEigThreshold;
1572 bool getMinEigenVals;
1574 void releaseMemory()
1576 dx_calcBuf_.release();
1577 dy_calcBuf_.release();
1587 void calcSharrDeriv(const oclMat &src, oclMat &dx, oclMat &dy);
1589 void buildImagePyramid(const oclMat &img0, std::vector<oclMat> &pyr, bool withBorder);
1594 std::vector<oclMat> prevPyr_;
1595 std::vector<oclMat> nextPyr_;
1603 bool isDeviceArch11_;
1606 class CV_EXPORTS FarnebackOpticalFlow
1609 FarnebackOpticalFlow();
1620 void operator ()(const oclMat &frame0, const oclMat &frame1, oclMat &flowx, oclMat &flowy);
1622 void releaseMemory();
1625 void prepareGaussian(
1626 int n, double sigma, float *g, float *xg, float *xxg,
1627 double &ig11, double &ig03, double &ig33, double &ig55);
1629 void setPolynomialExpansionConsts(int n, double sigma);
1631 void updateFlow_boxFilter(
1632 const oclMat& R0, const oclMat& R1, oclMat& flowx, oclMat &flowy,
1633 oclMat& M, oclMat &bufM, int blockSize, bool updateMatrices);
1635 void updateFlow_gaussianBlur(
1636 const oclMat& R0, const oclMat& R1, oclMat& flowx, oclMat& flowy,
1637 oclMat& M, oclMat &bufM, int blockSize, bool updateMatrices);
1640 oclMat pyrLevel_[2], M_, bufM_, R_[2], blurredFrame_[2];
1641 std::vector<oclMat> pyramid0_, pyramid1_;
1644 //////////////// build warping maps ////////////////////
1645 //! builds plane warping maps
1646 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);
1647 //! builds cylindrical warping maps
1648 CV_EXPORTS void buildWarpCylindricalMaps(Size src_size, Rect dst_roi, const Mat &K, const Mat &R, float scale, oclMat &map_x, oclMat &map_y);
1649 //! builds spherical warping maps
1650 CV_EXPORTS void buildWarpSphericalMaps(Size src_size, Rect dst_roi, const Mat &K, const Mat &R, float scale, oclMat &map_x, oclMat &map_y);
1651 //! builds Affine warping maps
1652 CV_EXPORTS void buildWarpAffineMaps(const Mat &M, bool inverse, Size dsize, oclMat &xmap, oclMat &ymap);
1654 //! builds Perspective warping maps
1655 CV_EXPORTS void buildWarpPerspectiveMaps(const Mat &M, bool inverse, Size dsize, oclMat &xmap, oclMat &ymap);
1657 ///////////////////////////////////// interpolate frames //////////////////////////////////////////////
1658 //! Interpolate frames (images) using provided optical flow (displacement field).
1659 //! frame0 - frame 0 (32-bit floating point images, single channel)
1660 //! frame1 - frame 1 (the same type and size)
1661 //! fu - forward horizontal displacement
1662 //! fv - forward vertical displacement
1663 //! bu - backward horizontal displacement
1664 //! bv - backward vertical displacement
1665 //! pos - new frame position
1666 //! newFrame - new frame
1667 //! buf - temporary buffer, will have width x 6*height size, CV_32FC1 type and contain 6 oclMat;
1668 //! occlusion masks 0, occlusion masks 1,
1669 //! interpolated forward flow 0, interpolated forward flow 1,
1670 //! interpolated backward flow 0, interpolated backward flow 1
1672 CV_EXPORTS void interpolateFrames(const oclMat &frame0, const oclMat &frame1,
1673 const oclMat &fu, const oclMat &fv,
1674 const oclMat &bu, const oclMat &bv,
1675 float pos, oclMat &newFrame, oclMat &buf);
1677 //! computes moments of the rasterized shape or a vector of points
1678 //! _array should be a vector a points standing for the contour
1679 CV_EXPORTS Moments ocl_moments(InputArray contour);
1680 //! src should be a general image uploaded to the GPU.
1681 //! the supported oclMat type are CV_8UC1, CV_16UC1, CV_16SC1, CV_32FC1 and CV_64FC1
1682 //! to use type of CV_64FC1, the GPU should support CV_64FC1
1683 CV_EXPORTS Moments ocl_moments(oclMat& src, bool binary);
1685 class CV_EXPORTS StereoBM_OCL
1688 enum { BASIC_PRESET = 0, PREFILTER_XSOBEL = 1 };
1690 enum { DEFAULT_NDISP = 64, DEFAULT_WINSZ = 19 };
1692 //! the default constructor
1694 //! the full constructor taking the camera-specific preset, number of disparities and the SAD window size. ndisparities must be multiple of 8.
1695 StereoBM_OCL(int preset, int ndisparities = DEFAULT_NDISP, int winSize = DEFAULT_WINSZ);
1697 //! the stereo correspondence operator. Finds the disparity for the specified rectified stereo pair
1698 //! Output disparity has CV_8U type.
1699 void operator() ( const oclMat &left, const oclMat &right, oclMat &disparity);
1701 //! Some heuristics that tries to estmate
1702 // if current GPU will be faster then CPU in this algorithm.
1703 // It queries current active device.
1704 static bool checkIfGpuCallReasonable();
1710 // If avergeTexThreshold == 0 => post procesing is disabled
1711 // If avergeTexThreshold != 0 then disparity is set 0 in each point (x,y) where for left image
1712 // SumOfHorizontalGradiensInWindow(x, y, winSize) < (winSize * winSize) * avergeTexThreshold
1713 // i.e. input left image is low textured.
1714 float avergeTexThreshold;
1716 oclMat minSSD, leBuf, riBuf;
1719 class CV_EXPORTS StereoBeliefPropagation
1722 enum { DEFAULT_NDISP = 64 };
1723 enum { DEFAULT_ITERS = 5 };
1724 enum { DEFAULT_LEVELS = 5 };
1725 static void estimateRecommendedParams(int width, int height, int &ndisp, int &iters, int &levels);
1726 explicit StereoBeliefPropagation(int ndisp = DEFAULT_NDISP,
1727 int iters = DEFAULT_ITERS,
1728 int levels = DEFAULT_LEVELS,
1729 int msg_type = CV_16S);
1730 StereoBeliefPropagation(int ndisp, int iters, int levels,
1731 float max_data_term, float data_weight,
1732 float max_disc_term, float disc_single_jump,
1733 int msg_type = CV_32F);
1734 void operator()(const oclMat &left, const oclMat &right, oclMat &disparity);
1735 void operator()(const oclMat &data, oclMat &disparity);
1739 float max_data_term;
1741 float max_disc_term;
1742 float disc_single_jump;
1745 oclMat u, d, l, r, u2, d2, l2, r2;
1746 std::vector<oclMat> datas;
1750 class CV_EXPORTS StereoConstantSpaceBP
1753 enum { DEFAULT_NDISP = 128 };
1754 enum { DEFAULT_ITERS = 8 };
1755 enum { DEFAULT_LEVELS = 4 };
1756 enum { DEFAULT_NR_PLANE = 4 };
1757 static void estimateRecommendedParams(int width, int height, int &ndisp, int &iters, int &levels, int &nr_plane);
1758 explicit StereoConstantSpaceBP(
1759 int ndisp = DEFAULT_NDISP,
1760 int iters = DEFAULT_ITERS,
1761 int levels = DEFAULT_LEVELS,
1762 int nr_plane = DEFAULT_NR_PLANE,
1763 int msg_type = CV_32F);
1764 StereoConstantSpaceBP(int ndisp, int iters, int levels, int nr_plane,
1765 float max_data_term, float data_weight, float max_disc_term, float disc_single_jump,
1766 int min_disp_th = 0,
1767 int msg_type = CV_32F);
1768 void operator()(const oclMat &left, const oclMat &right, oclMat &disparity);
1773 float max_data_term;
1775 float max_disc_term;
1776 float disc_single_jump;
1779 bool use_local_init_data_cost;
1781 oclMat u[2], d[2], l[2], r[2];
1782 oclMat disp_selected_pyr[2];
1784 oclMat data_cost_selected;
1789 // Implementation of the Zach, Pock and Bischof Dual TV-L1 Optical Flow method
1792 // [1] C. Zach, T. Pock and H. Bischof, "A Duality Based Approach for Realtime TV-L1 Optical Flow".
1793 // [2] Javier Sanchez, Enric Meinhardt-Llopis and Gabriele Facciolo. "TV-L1 Optical Flow Estimation".
1794 class CV_EXPORTS OpticalFlowDual_TVL1_OCL
1797 OpticalFlowDual_TVL1_OCL();
1799 void operator ()(const oclMat& I0, const oclMat& I1, oclMat& flowx, oclMat& flowy);
1801 void collectGarbage();
1804 * Time step of the numerical scheme.
1809 * Weight parameter for the data term, attachment parameter.
1810 * This is the most relevant parameter, which determines the smoothness of the output.
1811 * The smaller this parameter is, the smoother the solutions we obtain.
1812 * It depends on the range of motions of the images, so its value should be adapted to each image sequence.
1817 * Weight parameter for (u - v)^2, tightness parameter.
1818 * It serves as a link between the attachment and the regularization terms.
1819 * In theory, it should have a small value in order to maintain both parts in correspondence.
1820 * The method is stable for a large range of values of this parameter.
1825 * Number of scales used to create the pyramid of images.
1830 * Number of warpings per scale.
1831 * Represents the number of times that I1(x+u0) and grad( I1(x+u0) ) are computed per scale.
1832 * This is a parameter that assures the stability of the method.
1833 * It also affects the running time, so it is a compromise between speed and accuracy.
1838 * Stopping criterion threshold used in the numerical scheme, which is a trade-off between precision and running time.
1839 * A small value will yield more accurate solutions at the expense of a slower convergence.
1844 * Stopping criterion iterations number used in the numerical scheme.
1848 bool useInitialFlow;
1851 void procOneScale(const oclMat& I0, const oclMat& I1, oclMat& u1, oclMat& u2);
1853 std::vector<oclMat> I0s;
1854 std::vector<oclMat> I1s;
1855 std::vector<oclMat> u1s;
1856 std::vector<oclMat> u2s;
1876 // current supported sorting methods
1879 SORT_BITONIC, // only support power-of-2 buffer size
1880 SORT_SELECTION, // cannot sort duplicate keys
1882 SORT_RADIX // only support signed int/float keys(CV_32S/CV_32F)
1884 //! Returns the sorted result of all the elements in input based on equivalent keys.
1886 // The element unit in the values to be sorted is determined from the data type,
1887 // i.e., a CV_32FC2 input {a1a2, b1b2} will be considered as two elements, regardless its
1888 // matrix dimension.
1889 // both keys and values will be sorted inplace
1890 // Key needs to be single channel oclMat.
1894 // keys = {2, 3, 1} (CV_8UC1)
1895 // values = {10,5, 4,3, 6,2} (CV_8UC2)
1896 // sortByKey(keys, values, SORT_SELECTION, false);
1898 // keys = {1, 2, 3} (CV_8UC1)
1899 // values = {6,2, 10,5, 4,3} (CV_8UC2)
1900 CV_EXPORTS void sortByKey(oclMat& keys, oclMat& values, int method, bool isGreaterThan = false);
1901 /*!Base class for MOG and MOG2!*/
1902 class CV_EXPORTS BackgroundSubtractor
1905 //! the virtual destructor
1906 virtual ~BackgroundSubtractor();
1907 //! the update operator that takes the next video frame and returns the current foreground mask as 8-bit binary image.
1908 virtual void operator()(const oclMat& image, oclMat& fgmask, float learningRate);
1910 //! computes a background image
1911 virtual void getBackgroundImage(oclMat& backgroundImage) const = 0;
1914 Gaussian Mixture-based Backbround/Foreground Segmentation Algorithm
1916 The class implements the following algorithm:
1917 "An improved adaptive background mixture model for real-time tracking with shadow detection"
1918 P. KadewTraKuPong and R. Bowden,
1919 Proc. 2nd European Workshp on Advanced Video-Based Surveillance Systems, 2001."
1920 http://personal.ee.surrey.ac.uk/Personal/R.Bowden/publications/avbs01/avbs01.pdf
1922 class CV_EXPORTS MOG: public cv::ocl::BackgroundSubtractor
1925 //! the default constructor
1926 MOG(int nmixtures = -1);
1928 //! re-initiaization method
1929 void initialize(Size frameSize, int frameType);
1931 //! the update operator
1932 void operator()(const oclMat& frame, oclMat& fgmask, float learningRate = 0.f);
1934 //! computes a background image which are the mean of all background gaussians
1935 void getBackgroundImage(oclMat& backgroundImage) const;
1937 //! releases all inner buffers
1942 float backgroundRatio;
1959 The class implements the following algorithm:
1960 "Improved adaptive Gausian mixture model for background subtraction"
1962 International Conference Pattern Recognition, UK, August, 2004.
1963 http://www.zoranz.net/Publications/zivkovic2004ICPR.pdf
1965 class CV_EXPORTS MOG2: public cv::ocl::BackgroundSubtractor
1968 //! the default constructor
1969 MOG2(int nmixtures = -1);
1971 //! re-initiaization method
1972 void initialize(Size frameSize, int frameType);
1974 //! the update operator
1975 void operator()(const oclMat& frame, oclMat& fgmask, float learningRate = -1.0f);
1977 //! computes a background image which are the mean of all background gaussians
1978 void getBackgroundImage(oclMat& backgroundImage) const;
1980 //! releases all inner buffers
1984 // you should call initialize after parameters changes
1988 //! here it is the maximum allowed number of mixture components.
1989 //! Actual number is determined dynamically per pixel
1991 // threshold on the squared Mahalanobis distance to decide if it is well described
1992 // by the background model or not. Related to Cthr from the paper.
1993 // This does not influence the update of the background. A typical value could be 4 sigma
1994 // and that is varThreshold=4*4=16; Corresponds to Tb in the paper.
1996 /////////////////////////
1997 // less important parameters - things you might change but be carefull
1998 ////////////////////////
2000 float backgroundRatio;
2001 // corresponds to fTB=1-cf from the paper
2002 // TB - threshold when the component becomes significant enough to be included into
2003 // the background model. It is the TB=1-cf from the paper. So I use cf=0.1 => TB=0.
2004 // For alpha=0.001 it means that the mode should exist for approximately 105 frames before
2005 // it is considered foreground
2006 // float noiseSigma;
2007 float varThresholdGen;
2009 //correspondts to Tg - threshold on the squared Mahalan. dist. to decide
2010 //when a sample is close to the existing components. If it is not close
2011 //to any a new component will be generated. I use 3 sigma => Tg=3*3=9.
2012 //Smaller Tg leads to more generated components and higher Tg might make
2013 //lead to small number of components but they can grow too large
2018 //initial variance for the newly generated components.
2019 //It will will influence the speed of adaptation. A good guess should be made.
2020 //A simple way is to estimate the typical standard deviation from the images.
2021 //I used here 10 as a reasonable value
2022 // min and max can be used to further control the variance
2023 float fCT; //CT - complexity reduction prior
2024 //this is related to the number of samples needed to accept that a component
2025 //actually exists. We use CT=0.05 of all the samples. By setting CT=0 you get
2026 //the standard Stauffer&Grimson algorithm (maybe not exact but very similar)
2028 //shadow detection parameters
2029 bool bShadowDetection; //default 1 - do shadow detection
2030 unsigned char nShadowDetection; //do shadow detection - insert this value as the detection result - 127 default value
2032 // Tau - shadow threshold. The shadow is detected if the pixel is darker
2033 //version of the background. Tau is a threshold on how much darker the shadow can be.
2034 //Tau= 0.5 means that if pixel is more than 2 times darker then it is not shadow
2035 //See: Prati,Mikic,Trivedi,Cucchiarra,"Detecting Moving Shadows...",IEEE PAMI,2003.
2048 oclMat bgmodelUsedModes_; //keep track of number of modes per pixel
2051 /*!***************Kalman Filter*************!*/
2052 class CV_EXPORTS KalmanFilter
2056 //! the full constructor taking the dimensionality of the state, of the measurement and of the control vector
2057 KalmanFilter(int dynamParams, int measureParams, int controlParams=0, int type=CV_32F);
2058 //! re-initializes Kalman filter. The previous content is destroyed.
2059 void init(int dynamParams, int measureParams, int controlParams=0, int type=CV_32F);
2061 const oclMat& predict(const oclMat& control=oclMat());
2062 const oclMat& correct(const oclMat& measurement);
2064 oclMat statePre; //!< predicted state (x'(k)): x(k)=A*x(k-1)+B*u(k)
2065 oclMat statePost; //!< corrected state (x(k)): x(k)=x'(k)+K(k)*(z(k)-H*x'(k))
2066 oclMat transitionMatrix; //!< state transition matrix (A)
2067 oclMat controlMatrix; //!< control matrix (B) (not used if there is no control)
2068 oclMat measurementMatrix; //!< measurement matrix (H)
2069 oclMat processNoiseCov; //!< process noise covariance matrix (Q)
2070 oclMat measurementNoiseCov;//!< measurement noise covariance matrix (R)
2071 oclMat errorCovPre; //!< priori error estimate covariance matrix (P'(k)): P'(k)=A*P(k-1)*At + Q)*/
2072 oclMat gain; //!< Kalman gain matrix (K(k)): K(k)=P'(k)*Ht*inv(H*P'(k)*Ht+R)
2073 oclMat errorCovPost; //!< posteriori error estimate covariance matrix (P(k)): P(k)=(I-K(k)*H)*P'(k)
2082 /*!***************K Nearest Neighbour*************!*/
2083 class CV_EXPORTS KNearestNeighbour: public CvKNearest
2086 KNearestNeighbour();
2087 ~KNearestNeighbour();
2089 bool train(const Mat& trainData, Mat& labels, Mat& sampleIdx = Mat().setTo(Scalar::all(0)),
2090 bool isRegression = false, int max_k = 32, bool updateBase = false);
2094 void find_nearest(const oclMat& samples, int k, oclMat& lables);
2100 /*!*************** SVM *************!*/
2101 class CV_EXPORTS CvSVM_OCL : public CvSVM
2106 CvSVM_OCL(const cv::Mat& trainData, const cv::Mat& responses,
2107 const cv::Mat& varIdx=cv::Mat(), const cv::Mat& sampleIdx=cv::Mat(),
2108 CvSVMParams params=CvSVMParams());
2109 CV_WRAP float predict( const int row_index, Mat& src, bool returnDFVal=false ) const;
2110 CV_WRAP void predict( cv::InputArray samples, cv::OutputArray results ) const;
2111 CV_WRAP float predict( const cv::Mat& sample, bool returnDFVal=false ) const;
2112 float predict( const CvMat* samples, CV_OUT CvMat* results ) const;
2115 float predict( const int row_index, int row_len, Mat& src, bool returnDFVal=false ) const;
2116 void create_kernel();
2117 void create_solver();
2120 /*!*************** END *************!*/
2123 #if defined _MSC_VER && _MSC_VER >= 1200
2124 # pragma warning( push)
2125 # pragma warning( disable: 4267)
2127 #include "opencv2/ocl/matrix_operations.hpp"
2128 #if defined _MSC_VER && _MSC_VER >= 1200
2129 # pragma warning( pop)
2132 #endif /* __OPENCV_OCL_HPP__ */