added Generalized Hough implementation
[profile/ivi/opencv.git] / modules / gpu / include / opencv2 / gpu / gpu.hpp
1 /*M///////////////////////////////////////////////////////////////////////////////////////\r
2 //\r
3 //  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.\r
4 //\r
5 //  By downloading, copying, installing or using the software you agree to this license.\r
6 //  If you do not agree to this license, do not download, install,\r
7 //  copy or use the software.\r
8 //\r
9 //\r
10 //                           License Agreement\r
11 //                For Open Source Computer Vision Library\r
12 //\r
13 // Copyright (C) 2000-2008, Intel Corporation, all rights reserved.\r
14 // Copyright (C) 2009, Willow Garage Inc., all rights reserved.\r
15 // Third party copyrights are property of their respective owners.\r
16 //\r
17 // Redistribution and use in source and binary forms, with or without modification,\r
18 // are permitted provided that the following conditions are met:\r
19 //\r
20 //   * Redistribution's of source code must retain the above copyright notice,\r
21 //     this list of conditions and the following disclaimer.\r
22 //\r
23 //   * Redistribution's in binary form must reproduce the above copyright notice,\r
24 //     this list of conditions and the following disclaimer in the documentation\r
25 //     and/or other GpuMaterials provided with the distribution.\r
26 //\r
27 //   * The name of the copyright holders may not be used to endorse or promote products\r
28 //     derived from this software without specific prior written permission.\r
29 //\r
30 // This software is provided by the copyright holders and contributors "as is" and\r
31 // any express or implied warranties, including, but not limited to, the implied\r
32 // warranties of merchantability and fitness for a particular purpose are disclaimed.\r
33 // In no event shall the Intel Corporation or contributors be liable for any direct,\r
34 // indirect, incidental, special, exemplary, or consequential damages\r
35 // (including, but not limited to, procurement of substitute goods or services;\r
36 // loss of use, data, or profits; or business interruption) however caused\r
37 // and on any theory of liability, whether in contract, strict liability,\r
38 // or tort (including negligence or otherwise) arising in any way out of\r
39 // the use of this software, even if advised of the possibility of such damage.\r
40 //\r
41 //M*/\r
42 \r
43 #ifndef __OPENCV_GPU_HPP__\r
44 #define __OPENCV_GPU_HPP__\r
45 \r
46 #ifndef SKIP_INCLUDES\r
47 #include <vector>\r
48 #include <memory>\r
49 #include <iosfwd>\r
50 #endif\r
51 \r
52 #include "opencv2/core/gpumat.hpp"\r
53 #include "opencv2/imgproc/imgproc.hpp"\r
54 #include "opencv2/objdetect/objdetect.hpp"\r
55 #include "opencv2/features2d/features2d.hpp"\r
56 \r
57 namespace cv { namespace gpu {\r
58 \r
59 //////////////////////////////// CudaMem ////////////////////////////////\r
60 // CudaMem is limited cv::Mat with page locked memory allocation.\r
61 // Page locked memory is only needed for async and faster coping to GPU.\r
62 // It is convertable to cv::Mat header without reference counting\r
63 // so you can use it with other opencv functions.\r
64 \r
65 // Page-locks the matrix m memory and maps it for the device(s)\r
66 CV_EXPORTS void registerPageLocked(Mat& m);\r
67 // Unmaps the memory of matrix m, and makes it pageable again.\r
68 CV_EXPORTS void unregisterPageLocked(Mat& m);\r
69 \r
70 class CV_EXPORTS CudaMem\r
71 {\r
72 public:\r
73     enum  { ALLOC_PAGE_LOCKED = 1, ALLOC_ZEROCOPY = 2, ALLOC_WRITE_COMBINED = 4 };\r
74 \r
75     CudaMem();\r
76     CudaMem(const CudaMem& m);\r
77 \r
78     CudaMem(int rows, int cols, int type, int _alloc_type = ALLOC_PAGE_LOCKED);\r
79     CudaMem(Size size, int type, int alloc_type = ALLOC_PAGE_LOCKED);\r
80 \r
81 \r
82     //! creates from cv::Mat with coping data\r
83     explicit CudaMem(const Mat& m, int alloc_type = ALLOC_PAGE_LOCKED);\r
84 \r
85     ~CudaMem();\r
86 \r
87     CudaMem& operator = (const CudaMem& m);\r
88 \r
89     //! returns deep copy of the matrix, i.e. the data is copied\r
90     CudaMem clone() const;\r
91 \r
92     //! allocates new matrix data unless the matrix already has specified size and type.\r
93     void create(int rows, int cols, int type, int alloc_type = ALLOC_PAGE_LOCKED);\r
94     void create(Size size, int type, int alloc_type = ALLOC_PAGE_LOCKED);\r
95 \r
96     //! decrements reference counter and released memory if needed.\r
97     void release();\r
98 \r
99     //! returns matrix header with disabled reference counting for CudaMem data.\r
100     Mat createMatHeader() const;\r
101     operator Mat() const;\r
102 \r
103     //! maps host memory into device address space and returns GpuMat header for it. Throws exception if not supported by hardware.\r
104     GpuMat createGpuMatHeader() const;\r
105     operator GpuMat() const;\r
106 \r
107     //returns if host memory can be mapperd to gpu address space;\r
108     static bool canMapHostMemory();\r
109 \r
110     // Please see cv::Mat for descriptions\r
111     bool isContinuous() const;\r
112     size_t elemSize() const;\r
113     size_t elemSize1() const;\r
114     int type() const;\r
115     int depth() const;\r
116     int channels() const;\r
117     size_t step1() const;\r
118     Size size() const;\r
119     bool empty() const;\r
120 \r
121 \r
122     // Please see cv::Mat for descriptions\r
123     int flags;\r
124     int rows, cols;\r
125     size_t step;\r
126 \r
127     uchar* data;\r
128     int* refcount;\r
129 \r
130     uchar* datastart;\r
131     uchar* dataend;\r
132 \r
133     int alloc_type;\r
134 };\r
135 \r
136 //////////////////////////////// CudaStream ////////////////////////////////\r
137 // Encapculates Cuda Stream. Provides interface for async coping.\r
138 // Passed to each function that supports async kernel execution.\r
139 // Reference counting is enabled\r
140 \r
141 class CV_EXPORTS Stream\r
142 {\r
143 public:\r
144     Stream();\r
145     ~Stream();\r
146 \r
147     Stream(const Stream&);\r
148     Stream& operator=(const Stream&);\r
149 \r
150     bool queryIfComplete();\r
151     void waitForCompletion();\r
152 \r
153     //! downloads asynchronously.\r
154     // Warning! cv::Mat must point to page locked memory (i.e. to CudaMem data or to its subMat)\r
155     void enqueueDownload(const GpuMat& src, CudaMem& dst);\r
156     void enqueueDownload(const GpuMat& src, Mat& dst);\r
157 \r
158     //! uploads asynchronously.\r
159     // Warning! cv::Mat must point to page locked memory (i.e. to CudaMem data or to its ROI)\r
160     void enqueueUpload(const CudaMem& src, GpuMat& dst);\r
161     void enqueueUpload(const Mat& src, GpuMat& dst);\r
162 \r
163     void enqueueCopy(const GpuMat& src, GpuMat& dst);\r
164 \r
165     void enqueueMemSet(GpuMat& src, Scalar val);\r
166     void enqueueMemSet(GpuMat& src, Scalar val, const GpuMat& mask);\r
167 \r
168     // converts matrix type, ex from float to uchar depending on type\r
169     void enqueueConvert(const GpuMat& src, GpuMat& dst, int type, double a = 1, double b = 0);\r
170 \r
171     static Stream& Null();\r
172 \r
173     operator bool() const;\r
174 \r
175 private:\r
176     void create();\r
177     void release();\r
178 \r
179     struct Impl;\r
180     Impl *impl;\r
181 \r
182     friend struct StreamAccessor;\r
183 \r
184     explicit Stream(Impl* impl);\r
185 };\r
186 \r
187 \r
188 //////////////////////////////// Filter Engine ////////////////////////////////\r
189 \r
190 /*!\r
191 The Base Class for 1D or Row-wise Filters\r
192 \r
193 This is the base class for linear or non-linear filters that process 1D data.\r
194 In particular, such filters are used for the "horizontal" filtering parts in separable filters.\r
195 */\r
196 class CV_EXPORTS BaseRowFilter_GPU\r
197 {\r
198 public:\r
199     BaseRowFilter_GPU(int ksize_, int anchor_) : ksize(ksize_), anchor(anchor_) {}\r
200     virtual ~BaseRowFilter_GPU() {}\r
201     virtual void operator()(const GpuMat& src, GpuMat& dst, Stream& stream = Stream::Null()) = 0;\r
202     int ksize, anchor;\r
203 };\r
204 \r
205 /*!\r
206 The Base Class for Column-wise Filters\r
207 \r
208 This is the base class for linear or non-linear filters that process columns of 2D arrays.\r
209 Such filters are used for the "vertical" filtering parts in separable filters.\r
210 */\r
211 class CV_EXPORTS BaseColumnFilter_GPU\r
212 {\r
213 public:\r
214     BaseColumnFilter_GPU(int ksize_, int anchor_) : ksize(ksize_), anchor(anchor_) {}\r
215     virtual ~BaseColumnFilter_GPU() {}\r
216     virtual void operator()(const GpuMat& src, GpuMat& dst, Stream& stream = Stream::Null()) = 0;\r
217     int ksize, anchor;\r
218 };\r
219 \r
220 /*!\r
221 The Base Class for Non-Separable 2D Filters.\r
222 \r
223 This is the base class for linear or non-linear 2D filters.\r
224 */\r
225 class CV_EXPORTS BaseFilter_GPU\r
226 {\r
227 public:\r
228     BaseFilter_GPU(const Size& ksize_, const Point& anchor_) : ksize(ksize_), anchor(anchor_) {}\r
229     virtual ~BaseFilter_GPU() {}\r
230     virtual void operator()(const GpuMat& src, GpuMat& dst, Stream& stream = Stream::Null()) = 0;\r
231     Size ksize;\r
232     Point anchor;\r
233 };\r
234 \r
235 /*!\r
236 The Base Class for Filter Engine.\r
237 \r
238 The class can be used to apply an arbitrary filtering operation to an image.\r
239 It contains all the necessary intermediate buffers.\r
240 */\r
241 class CV_EXPORTS FilterEngine_GPU\r
242 {\r
243 public:\r
244     virtual ~FilterEngine_GPU() {}\r
245 \r
246     virtual void apply(const GpuMat& src, GpuMat& dst, Rect roi = Rect(0,0,-1,-1), Stream& stream = Stream::Null()) = 0;\r
247 };\r
248 \r
249 //! returns the non-separable filter engine with the specified filter\r
250 CV_EXPORTS Ptr<FilterEngine_GPU> createFilter2D_GPU(const Ptr<BaseFilter_GPU>& filter2D, int srcType, int dstType);\r
251 \r
252 //! returns the separable filter engine with the specified filters\r
253 CV_EXPORTS Ptr<FilterEngine_GPU> createSeparableFilter_GPU(const Ptr<BaseRowFilter_GPU>& rowFilter,\r
254     const Ptr<BaseColumnFilter_GPU>& columnFilter, int srcType, int bufType, int dstType);\r
255 CV_EXPORTS Ptr<FilterEngine_GPU> createSeparableFilter_GPU(const Ptr<BaseRowFilter_GPU>& rowFilter,\r
256     const Ptr<BaseColumnFilter_GPU>& columnFilter, int srcType, int bufType, int dstType, GpuMat& buf);\r
257 \r
258 //! returns horizontal 1D box filter\r
259 //! supports only CV_8UC1 source type and CV_32FC1 sum type\r
260 CV_EXPORTS Ptr<BaseRowFilter_GPU> getRowSumFilter_GPU(int srcType, int sumType, int ksize, int anchor = -1);\r
261 \r
262 //! returns vertical 1D box filter\r
263 //! supports only CV_8UC1 sum type and CV_32FC1 dst type\r
264 CV_EXPORTS Ptr<BaseColumnFilter_GPU> getColumnSumFilter_GPU(int sumType, int dstType, int ksize, int anchor = -1);\r
265 \r
266 //! returns 2D box filter\r
267 //! supports CV_8UC1 and CV_8UC4 source type, dst type must be the same as source type\r
268 CV_EXPORTS Ptr<BaseFilter_GPU> getBoxFilter_GPU(int srcType, int dstType, const Size& ksize, Point anchor = Point(-1, -1));\r
269 \r
270 //! returns box filter engine\r
271 CV_EXPORTS Ptr<FilterEngine_GPU> createBoxFilter_GPU(int srcType, int dstType, const Size& ksize,\r
272     const Point& anchor = Point(-1,-1));\r
273 \r
274 //! returns 2D morphological filter\r
275 //! only MORPH_ERODE and MORPH_DILATE are supported\r
276 //! supports CV_8UC1 and CV_8UC4 types\r
277 //! kernel must have CV_8UC1 type, one rows and cols == ksize.width * ksize.height\r
278 CV_EXPORTS Ptr<BaseFilter_GPU> getMorphologyFilter_GPU(int op, int type, const Mat& kernel, const Size& ksize,\r
279     Point anchor=Point(-1,-1));\r
280 \r
281 //! returns morphological filter engine. Only MORPH_ERODE and MORPH_DILATE are supported.\r
282 CV_EXPORTS Ptr<FilterEngine_GPU> createMorphologyFilter_GPU(int op, int type, const Mat& kernel,\r
283     const Point& anchor = Point(-1,-1), int iterations = 1);\r
284 CV_EXPORTS Ptr<FilterEngine_GPU> createMorphologyFilter_GPU(int op, int type, const Mat& kernel, GpuMat& buf,\r
285     const Point& anchor = Point(-1,-1), int iterations = 1);\r
286 \r
287 //! returns 2D filter with the specified kernel\r
288 //! supports CV_8U, CV_16U and CV_32F one and four channel image\r
289 CV_EXPORTS Ptr<BaseFilter_GPU> getLinearFilter_GPU(int srcType, int dstType, const Mat& kernel, Point anchor = Point(-1, -1), int borderType = BORDER_DEFAULT);\r
290 \r
291 //! returns the non-separable linear filter engine\r
292 CV_EXPORTS Ptr<FilterEngine_GPU> createLinearFilter_GPU(int srcType, int dstType, const Mat& kernel,\r
293     Point anchor = Point(-1,-1), int borderType = BORDER_DEFAULT);\r
294 \r
295 //! returns the primitive row filter with the specified kernel.\r
296 //! supports only CV_8UC1, CV_8UC4, CV_16SC1, CV_16SC2, CV_32SC1, CV_32FC1 source type.\r
297 //! there are two version of algorithm: NPP and OpenCV.\r
298 //! NPP calls when srcType == CV_8UC1 or srcType == CV_8UC4 and bufType == srcType,\r
299 //! otherwise calls OpenCV version.\r
300 //! NPP supports only BORDER_CONSTANT border type.\r
301 //! OpenCV version supports only CV_32F as buffer depth and\r
302 //! BORDER_REFLECT101, BORDER_REPLICATE and BORDER_CONSTANT border types.\r
303 CV_EXPORTS Ptr<BaseRowFilter_GPU> getLinearRowFilter_GPU(int srcType, int bufType, const Mat& rowKernel,\r
304     int anchor = -1, int borderType = BORDER_DEFAULT);\r
305 \r
306 //! returns the primitive column filter with the specified kernel.\r
307 //! supports only CV_8UC1, CV_8UC4, CV_16SC1, CV_16SC2, CV_32SC1, CV_32FC1 dst type.\r
308 //! there are two version of algorithm: NPP and OpenCV.\r
309 //! NPP calls when dstType == CV_8UC1 or dstType == CV_8UC4 and bufType == dstType,\r
310 //! otherwise calls OpenCV version.\r
311 //! NPP supports only BORDER_CONSTANT border type.\r
312 //! OpenCV version supports only CV_32F as buffer depth and\r
313 //! BORDER_REFLECT101, BORDER_REPLICATE and BORDER_CONSTANT border types.\r
314 CV_EXPORTS Ptr<BaseColumnFilter_GPU> getLinearColumnFilter_GPU(int bufType, int dstType, const Mat& columnKernel,\r
315     int anchor = -1, int borderType = BORDER_DEFAULT);\r
316 \r
317 //! returns the separable linear filter engine\r
318 CV_EXPORTS Ptr<FilterEngine_GPU> createSeparableLinearFilter_GPU(int srcType, int dstType, const Mat& rowKernel,\r
319     const Mat& columnKernel, const Point& anchor = Point(-1,-1), int rowBorderType = BORDER_DEFAULT,\r
320     int columnBorderType = -1);\r
321 CV_EXPORTS Ptr<FilterEngine_GPU> createSeparableLinearFilter_GPU(int srcType, int dstType, const Mat& rowKernel,\r
322     const Mat& columnKernel, GpuMat& buf, const Point& anchor = Point(-1,-1), int rowBorderType = BORDER_DEFAULT,\r
323     int columnBorderType = -1);\r
324 \r
325 //! returns filter engine for the generalized Sobel operator\r
326 CV_EXPORTS Ptr<FilterEngine_GPU> createDerivFilter_GPU(int srcType, int dstType, int dx, int dy, int ksize,\r
327                                                        int rowBorderType = BORDER_DEFAULT, int columnBorderType = -1);\r
328 CV_EXPORTS Ptr<FilterEngine_GPU> createDerivFilter_GPU(int srcType, int dstType, int dx, int dy, int ksize, GpuMat& buf,\r
329                                                        int rowBorderType = BORDER_DEFAULT, int columnBorderType = -1);\r
330 \r
331 //! returns the Gaussian filter engine\r
332 CV_EXPORTS Ptr<FilterEngine_GPU> createGaussianFilter_GPU(int type, Size ksize, double sigma1, double sigma2 = 0,\r
333                                                           int rowBorderType = BORDER_DEFAULT, int columnBorderType = -1);\r
334 CV_EXPORTS Ptr<FilterEngine_GPU> createGaussianFilter_GPU(int type, Size ksize, GpuMat& buf, double sigma1, double sigma2 = 0,\r
335                                                           int rowBorderType = BORDER_DEFAULT, int columnBorderType = -1);\r
336 \r
337 //! returns maximum filter\r
338 CV_EXPORTS Ptr<BaseFilter_GPU> getMaxFilter_GPU(int srcType, int dstType, const Size& ksize, Point anchor = Point(-1,-1));\r
339 \r
340 //! returns minimum filter\r
341 CV_EXPORTS Ptr<BaseFilter_GPU> getMinFilter_GPU(int srcType, int dstType, const Size& ksize, Point anchor = Point(-1,-1));\r
342 \r
343 //! smooths the image using the normalized box filter\r
344 //! supports CV_8UC1, CV_8UC4 types\r
345 CV_EXPORTS void boxFilter(const GpuMat& src, GpuMat& dst, int ddepth, Size ksize, Point anchor = Point(-1,-1), Stream& stream = Stream::Null());\r
346 \r
347 //! a synonym for normalized box filter\r
348 static inline void blur(const GpuMat& src, GpuMat& dst, Size ksize, Point anchor = Point(-1,-1), Stream& stream = Stream::Null())\r
349 {\r
350     boxFilter(src, dst, -1, ksize, anchor, stream);\r
351 }\r
352 \r
353 //! erodes the image (applies the local minimum operator)\r
354 CV_EXPORTS void erode(const GpuMat& src, GpuMat& dst, const Mat& kernel, Point anchor = Point(-1, -1), int iterations = 1);\r
355 CV_EXPORTS void erode(const GpuMat& src, GpuMat& dst, const Mat& kernel, GpuMat& buf,\r
356                       Point anchor = Point(-1, -1), int iterations = 1,\r
357                       Stream& stream = Stream::Null());\r
358 \r
359 //! dilates the image (applies the local maximum operator)\r
360 CV_EXPORTS void dilate(const GpuMat& src, GpuMat& dst, const Mat& kernel, Point anchor = Point(-1, -1), int iterations = 1);\r
361 CV_EXPORTS void dilate(const GpuMat& src, GpuMat& dst, const Mat& kernel, GpuMat& buf,\r
362                        Point anchor = Point(-1, -1), int iterations = 1,\r
363                        Stream& stream = Stream::Null());\r
364 \r
365 //! applies an advanced morphological operation to the image\r
366 CV_EXPORTS void morphologyEx(const GpuMat& src, GpuMat& dst, int op, const Mat& kernel, Point anchor = Point(-1, -1), int iterations = 1);\r
367 CV_EXPORTS void morphologyEx(const GpuMat& src, GpuMat& dst, int op, const Mat& kernel, GpuMat& buf1, GpuMat& buf2,\r
368                              Point anchor = Point(-1, -1), int iterations = 1, Stream& stream = Stream::Null());\r
369 \r
370 //! applies non-separable 2D linear filter to the image\r
371 CV_EXPORTS void filter2D(const GpuMat& src, GpuMat& dst, int ddepth, const Mat& kernel, Point anchor=Point(-1,-1), int borderType = BORDER_DEFAULT, Stream& stream = Stream::Null());\r
372 \r
373 //! applies separable 2D linear filter to the image\r
374 CV_EXPORTS void sepFilter2D(const GpuMat& src, GpuMat& dst, int ddepth, const Mat& kernelX, const Mat& kernelY,\r
375                             Point anchor = Point(-1,-1), int rowBorderType = BORDER_DEFAULT, int columnBorderType = -1);\r
376 CV_EXPORTS void sepFilter2D(const GpuMat& src, GpuMat& dst, int ddepth, const Mat& kernelX, const Mat& kernelY, GpuMat& buf,\r
377                             Point anchor = Point(-1,-1), int rowBorderType = BORDER_DEFAULT, int columnBorderType = -1,\r
378                             Stream& stream = Stream::Null());\r
379 \r
380 //! applies generalized Sobel operator to the image\r
381 CV_EXPORTS void Sobel(const GpuMat& src, GpuMat& dst, int ddepth, int dx, int dy, int ksize = 3, double scale = 1,\r
382                       int rowBorderType = BORDER_DEFAULT, int columnBorderType = -1);\r
383 CV_EXPORTS void Sobel(const GpuMat& src, GpuMat& dst, int ddepth, int dx, int dy, GpuMat& buf, int ksize = 3, double scale = 1,\r
384                       int rowBorderType = BORDER_DEFAULT, int columnBorderType = -1, Stream& stream = Stream::Null());\r
385 \r
386 //! applies the vertical or horizontal Scharr operator to the image\r
387 CV_EXPORTS void Scharr(const GpuMat& src, GpuMat& dst, int ddepth, int dx, int dy, double scale = 1,\r
388                        int rowBorderType = BORDER_DEFAULT, int columnBorderType = -1);\r
389 CV_EXPORTS void Scharr(const GpuMat& src, GpuMat& dst, int ddepth, int dx, int dy, GpuMat& buf, double scale = 1,\r
390                        int rowBorderType = BORDER_DEFAULT, int columnBorderType = -1, Stream& stream = Stream::Null());\r
391 \r
392 //! smooths the image using Gaussian filter.\r
393 CV_EXPORTS void GaussianBlur(const GpuMat& src, GpuMat& dst, Size ksize, double sigma1, double sigma2 = 0,\r
394                              int rowBorderType = BORDER_DEFAULT, int columnBorderType = -1);\r
395 CV_EXPORTS void GaussianBlur(const GpuMat& src, GpuMat& dst, Size ksize, GpuMat& buf, double sigma1, double sigma2 = 0,\r
396                              int rowBorderType = BORDER_DEFAULT, int columnBorderType = -1, Stream& stream = Stream::Null());\r
397 \r
398 //! applies Laplacian operator to the image\r
399 //! supports only ksize = 1 and ksize = 3\r
400 CV_EXPORTS void Laplacian(const GpuMat& src, GpuMat& dst, int ddepth, int ksize = 1, double scale = 1, int borderType = BORDER_DEFAULT, Stream& stream = Stream::Null());\r
401 \r
402 \r
403 ////////////////////////////// Arithmetics ///////////////////////////////////\r
404 \r
405 //! implements generalized matrix product algorithm GEMM from BLAS\r
406 CV_EXPORTS void gemm(const GpuMat& src1, const GpuMat& src2, double alpha,\r
407     const GpuMat& src3, double beta, GpuMat& dst, int flags = 0, Stream& stream = Stream::Null());\r
408 \r
409 //! transposes the matrix\r
410 //! supports matrix with element size = 1, 4 and 8 bytes (CV_8UC1, CV_8UC4, CV_16UC2, CV_32FC1, etc)\r
411 CV_EXPORTS void transpose(const GpuMat& src1, GpuMat& dst, Stream& stream = Stream::Null());\r
412 \r
413 //! reverses the order of the rows, columns or both in a matrix\r
414 //! supports 1, 3 and 4 channels images with CV_8U, CV_16U, CV_32S or CV_32F depth\r
415 CV_EXPORTS void flip(const GpuMat& a, GpuMat& b, int flipCode, Stream& stream = Stream::Null());\r
416 \r
417 //! transforms 8-bit unsigned integers using lookup table: dst(i)=lut(src(i))\r
418 //! destination array will have the depth type as lut and the same channels number as source\r
419 //! supports CV_8UC1, CV_8UC3 types\r
420 CV_EXPORTS void LUT(const GpuMat& src, const Mat& lut, GpuMat& dst, Stream& stream = Stream::Null());\r
421 \r
422 //! makes multi-channel array out of several single-channel arrays\r
423 CV_EXPORTS void merge(const GpuMat* src, size_t n, GpuMat& dst, Stream& stream = Stream::Null());\r
424 \r
425 //! makes multi-channel array out of several single-channel arrays\r
426 CV_EXPORTS void merge(const vector<GpuMat>& src, GpuMat& dst, Stream& stream = Stream::Null());\r
427 \r
428 //! copies each plane of a multi-channel array to a dedicated array\r
429 CV_EXPORTS void split(const GpuMat& src, GpuMat* dst, Stream& stream = Stream::Null());\r
430 \r
431 //! copies each plane of a multi-channel array to a dedicated array\r
432 CV_EXPORTS void split(const GpuMat& src, vector<GpuMat>& dst, Stream& stream = Stream::Null());\r
433 \r
434 //! computes magnitude of complex (x(i).re, x(i).im) vector\r
435 //! supports only CV_32FC2 type\r
436 CV_EXPORTS void magnitude(const GpuMat& xy, GpuMat& magnitude, Stream& stream = Stream::Null());\r
437 \r
438 //! computes squared magnitude of complex (x(i).re, x(i).im) vector\r
439 //! supports only CV_32FC2 type\r
440 CV_EXPORTS void magnitudeSqr(const GpuMat& xy, GpuMat& magnitude, Stream& stream = Stream::Null());\r
441 \r
442 //! computes magnitude of each (x(i), y(i)) vector\r
443 //! supports only floating-point source\r
444 CV_EXPORTS void magnitude(const GpuMat& x, const GpuMat& y, GpuMat& magnitude, Stream& stream = Stream::Null());\r
445 \r
446 //! computes squared magnitude of each (x(i), y(i)) vector\r
447 //! supports only floating-point source\r
448 CV_EXPORTS void magnitudeSqr(const GpuMat& x, const GpuMat& y, GpuMat& magnitude, Stream& stream = Stream::Null());\r
449 \r
450 //! computes angle (angle(i)) of each (x(i), y(i)) vector\r
451 //! supports only floating-point source\r
452 CV_EXPORTS void phase(const GpuMat& x, const GpuMat& y, GpuMat& angle, bool angleInDegrees = false, Stream& stream = Stream::Null());\r
453 \r
454 //! converts Cartesian coordinates to polar\r
455 //! supports only floating-point source\r
456 CV_EXPORTS void cartToPolar(const GpuMat& x, const GpuMat& y, GpuMat& magnitude, GpuMat& angle, bool angleInDegrees = false, Stream& stream = Stream::Null());\r
457 \r
458 //! converts polar coordinates to Cartesian\r
459 //! supports only floating-point source\r
460 CV_EXPORTS void polarToCart(const GpuMat& magnitude, const GpuMat& angle, GpuMat& x, GpuMat& y, bool angleInDegrees = false, Stream& stream = Stream::Null());\r
461 \r
462 \r
463 //////////////////////////// Per-element operations ////////////////////////////////////\r
464 \r
465 //! adds one matrix to another (c = a + b)\r
466 CV_EXPORTS void add(const GpuMat& a, const GpuMat& b, GpuMat& c, const GpuMat& mask = GpuMat(), int dtype = -1, Stream& stream = Stream::Null());\r
467 //! adds scalar to a matrix (c = a + s)\r
468 CV_EXPORTS void add(const GpuMat& a, const Scalar& sc, GpuMat& c, const GpuMat& mask = GpuMat(), int dtype = -1, Stream& stream = Stream::Null());\r
469 \r
470 //! subtracts one matrix from another (c = a - b)\r
471 CV_EXPORTS void subtract(const GpuMat& a, const GpuMat& b, GpuMat& c, const GpuMat& mask = GpuMat(), int dtype = -1, Stream& stream = Stream::Null());\r
472 //! subtracts scalar from a matrix (c = a - s)\r
473 CV_EXPORTS void subtract(const GpuMat& a, const Scalar& sc, GpuMat& c, const GpuMat& mask = GpuMat(), int dtype = -1, Stream& stream = Stream::Null());\r
474 \r
475 //! computes element-wise weighted product of the two arrays (c = scale * a * b)\r
476 CV_EXPORTS void multiply(const GpuMat& a, const GpuMat& b, GpuMat& c, double scale = 1, int dtype = -1, Stream& stream = Stream::Null());\r
477 //! weighted multiplies matrix to a scalar (c = scale * a * s)\r
478 CV_EXPORTS void multiply(const GpuMat& a, const Scalar& sc, GpuMat& c, double scale = 1, int dtype = -1, Stream& stream = Stream::Null());\r
479 \r
480 //! computes element-wise weighted quotient of the two arrays (c = a / b)\r
481 CV_EXPORTS void divide(const GpuMat& a, const GpuMat& b, GpuMat& c, double scale = 1, int dtype = -1, Stream& stream = Stream::Null());\r
482 //! computes element-wise weighted quotient of matrix and scalar (c = a / s)\r
483 CV_EXPORTS void divide(const GpuMat& a, const Scalar& sc, GpuMat& c, double scale = 1, int dtype = -1, Stream& stream = Stream::Null());\r
484 //! computes element-wise weighted reciprocal of an array (dst = scale/src2)\r
485 CV_EXPORTS void divide(double scale, const GpuMat& b, GpuMat& c, int dtype = -1, Stream& stream = Stream::Null());\r
486 \r
487 //! computes the weighted sum of two arrays (dst = alpha*src1 + beta*src2 + gamma)\r
488 CV_EXPORTS void addWeighted(const GpuMat& src1, double alpha, const GpuMat& src2, double beta, double gamma, GpuMat& dst,\r
489                             int dtype = -1, Stream& stream = Stream::Null());\r
490 \r
491 //! adds scaled array to another one (dst = alpha*src1 + src2)\r
492 static inline void scaleAdd(const GpuMat& src1, double alpha, const GpuMat& src2, GpuMat& dst, Stream& stream = Stream::Null())\r
493 {\r
494     addWeighted(src1, alpha, src2, 1.0, 0.0, dst, -1, stream);\r
495 }\r
496 \r
497 //! computes element-wise absolute difference of two arrays (c = abs(a - b))\r
498 CV_EXPORTS void absdiff(const GpuMat& a, const GpuMat& b, GpuMat& c, Stream& stream = Stream::Null());\r
499 //! computes element-wise absolute difference of array and scalar (c = abs(a - s))\r
500 CV_EXPORTS void absdiff(const GpuMat& a, const Scalar& s, GpuMat& c, Stream& stream = Stream::Null());\r
501 \r
502 //! computes absolute value of each matrix element\r
503 //! supports CV_16S and CV_32F depth\r
504 CV_EXPORTS void abs(const GpuMat& src, GpuMat& dst, Stream& stream = Stream::Null());\r
505 \r
506 //! computes square of each pixel in an image\r
507 //! supports CV_8U, CV_16U, CV_16S and CV_32F depth\r
508 CV_EXPORTS void sqr(const GpuMat& src, GpuMat& dst, Stream& stream = Stream::Null());\r
509 \r
510 //! computes square root of each pixel in an image\r
511 //! supports CV_8U, CV_16U, CV_16S and CV_32F depth\r
512 CV_EXPORTS void sqrt(const GpuMat& src, GpuMat& dst, Stream& stream = Stream::Null());\r
513 \r
514 //! computes exponent of each matrix element (b = e**a)\r
515 //! supports CV_8U, CV_16U, CV_16S and CV_32F depth\r
516 CV_EXPORTS void exp(const GpuMat& a, GpuMat& b, Stream& stream = Stream::Null());\r
517 \r
518 //! computes natural logarithm of absolute value of each matrix element: b = log(abs(a))\r
519 //! supports CV_8U, CV_16U, CV_16S and CV_32F depth\r
520 CV_EXPORTS void log(const GpuMat& a, GpuMat& b, Stream& stream = Stream::Null());\r
521 \r
522 //! computes power of each matrix element:\r
523 //    (dst(i,j) = pow(     src(i,j) , power), if src.type() is integer\r
524 //    (dst(i,j) = pow(fabs(src(i,j)), power), otherwise\r
525 //! supports all, except depth == CV_64F\r
526 CV_EXPORTS void pow(const GpuMat& src, double power, GpuMat& dst, Stream& stream = Stream::Null());\r
527 \r
528 //! compares elements of two arrays (c = a <cmpop> b)\r
529 CV_EXPORTS void compare(const GpuMat& a, const GpuMat& b, GpuMat& c, int cmpop, Stream& stream = Stream::Null());\r
530 CV_EXPORTS void compare(const GpuMat& a, Scalar sc, GpuMat& c, int cmpop, Stream& stream = Stream::Null());\r
531 \r
532 //! performs per-elements bit-wise inversion\r
533 CV_EXPORTS void bitwise_not(const GpuMat& src, GpuMat& dst, const GpuMat& mask=GpuMat(), Stream& stream = Stream::Null());\r
534 \r
535 //! calculates per-element bit-wise disjunction of two arrays\r
536 CV_EXPORTS void bitwise_or(const GpuMat& src1, const GpuMat& src2, GpuMat& dst, const GpuMat& mask=GpuMat(), Stream& stream = Stream::Null());\r
537 //! calculates per-element bit-wise disjunction of array and scalar\r
538 //! supports 1, 3 and 4 channels images with CV_8U, CV_16U or CV_32S depth\r
539 CV_EXPORTS void bitwise_or(const GpuMat& src1, const Scalar& sc, GpuMat& dst, Stream& stream = Stream::Null());\r
540 \r
541 //! calculates per-element bit-wise conjunction of two arrays\r
542 CV_EXPORTS void bitwise_and(const GpuMat& src1, const GpuMat& src2, GpuMat& dst, const GpuMat& mask=GpuMat(), Stream& stream = Stream::Null());\r
543 //! calculates per-element bit-wise conjunction of array and scalar\r
544 //! supports 1, 3 and 4 channels images with CV_8U, CV_16U or CV_32S depth\r
545 CV_EXPORTS void bitwise_and(const GpuMat& src1, const Scalar& sc, GpuMat& dst, Stream& stream = Stream::Null());\r
546 \r
547 //! calculates per-element bit-wise "exclusive or" operation\r
548 CV_EXPORTS void bitwise_xor(const GpuMat& src1, const GpuMat& src2, GpuMat& dst, const GpuMat& mask=GpuMat(), Stream& stream = Stream::Null());\r
549 //! calculates per-element bit-wise "exclusive or" of array and scalar\r
550 //! supports 1, 3 and 4 channels images with CV_8U, CV_16U or CV_32S depth\r
551 CV_EXPORTS void bitwise_xor(const GpuMat& src1, const Scalar& sc, GpuMat& dst, Stream& stream = Stream::Null());\r
552 \r
553 //! pixel by pixel right shift of an image by a constant value\r
554 //! supports 1, 3 and 4 channels images with integers elements\r
555 CV_EXPORTS void rshift(const GpuMat& src, Scalar_<int> sc, GpuMat& dst, Stream& stream = Stream::Null());\r
556 \r
557 //! pixel by pixel left shift of an image by a constant value\r
558 //! supports 1, 3 and 4 channels images with CV_8U, CV_16U or CV_32S depth\r
559 CV_EXPORTS void lshift(const GpuMat& src, Scalar_<int> sc, GpuMat& dst, Stream& stream = Stream::Null());\r
560 \r
561 //! computes per-element minimum of two arrays (dst = min(src1, src2))\r
562 CV_EXPORTS void min(const GpuMat& src1, const GpuMat& src2, GpuMat& dst, Stream& stream = Stream::Null());\r
563 \r
564 //! computes per-element minimum of array and scalar (dst = min(src1, src2))\r
565 CV_EXPORTS void min(const GpuMat& src1, double src2, GpuMat& dst, Stream& stream = Stream::Null());\r
566 \r
567 //! computes per-element maximum of two arrays (dst = max(src1, src2))\r
568 CV_EXPORTS void max(const GpuMat& src1, const GpuMat& src2, GpuMat& dst, Stream& stream = Stream::Null());\r
569 \r
570 //! computes per-element maximum of array and scalar (dst = max(src1, src2))\r
571 CV_EXPORTS void max(const GpuMat& src1, double src2, GpuMat& dst, Stream& stream = Stream::Null());\r
572 \r
573 enum { ALPHA_OVER, ALPHA_IN, ALPHA_OUT, ALPHA_ATOP, ALPHA_XOR, ALPHA_PLUS, ALPHA_OVER_PREMUL, ALPHA_IN_PREMUL, ALPHA_OUT_PREMUL,\r
574        ALPHA_ATOP_PREMUL, ALPHA_XOR_PREMUL, ALPHA_PLUS_PREMUL, ALPHA_PREMUL};\r
575 \r
576 //! Composite two images using alpha opacity values contained in each image\r
577 //! Supports CV_8UC4, CV_16UC4, CV_32SC4 and CV_32FC4 types\r
578 CV_EXPORTS void alphaComp(const GpuMat& img1, const GpuMat& img2, GpuMat& dst, int alpha_op, Stream& stream = Stream::Null());\r
579 \r
580 \r
581 ////////////////////////////// Image processing //////////////////////////////\r
582 \r
583 //! DST[x,y] = SRC[xmap[x,y],ymap[x,y]]\r
584 //! supports only CV_32FC1 map type\r
585 CV_EXPORTS void remap(const GpuMat& src, GpuMat& dst, const GpuMat& xmap, const GpuMat& ymap,\r
586                       int interpolation, int borderMode = BORDER_CONSTANT, Scalar borderValue = Scalar(),\r
587                       Stream& stream = Stream::Null());\r
588 \r
589 //! Does mean shift filtering on GPU.\r
590 CV_EXPORTS void meanShiftFiltering(const GpuMat& src, GpuMat& dst, int sp, int sr,\r
591                                    TermCriteria criteria = TermCriteria(TermCriteria::MAX_ITER + TermCriteria::EPS, 5, 1),\r
592                                    Stream& stream = Stream::Null());\r
593 \r
594 //! Does mean shift procedure on GPU.\r
595 CV_EXPORTS void meanShiftProc(const GpuMat& src, GpuMat& dstr, GpuMat& dstsp, int sp, int sr,\r
596                               TermCriteria criteria = TermCriteria(TermCriteria::MAX_ITER + TermCriteria::EPS, 5, 1),\r
597                               Stream& stream = Stream::Null());\r
598 \r
599 //! Does mean shift segmentation with elimination of small regions.\r
600 CV_EXPORTS void meanShiftSegmentation(const GpuMat& src, Mat& dst, int sp, int sr, int minsize,\r
601                                       TermCriteria criteria = TermCriteria(TermCriteria::MAX_ITER + TermCriteria::EPS, 5, 1));\r
602 \r
603 //! Does coloring of disparity image: [0..ndisp) -> [0..240, 1, 1] in HSV.\r
604 //! Supported types of input disparity: CV_8U, CV_16S.\r
605 //! Output disparity has CV_8UC4 type in BGRA format (alpha = 255).\r
606 CV_EXPORTS void drawColorDisp(const GpuMat& src_disp, GpuMat& dst_disp, int ndisp, Stream& stream = Stream::Null());\r
607 \r
608 //! Reprojects disparity image to 3D space.\r
609 //! Supports CV_8U and CV_16S types of input disparity.\r
610 //! The output is a 3- or 4-channel floating-point matrix.\r
611 //! Each element of this matrix will contain the 3D coordinates of the point (x,y,z,1), computed from the disparity map.\r
612 //! Q is the 4x4 perspective transformation matrix that can be obtained with cvStereoRectify.\r
613 CV_EXPORTS void reprojectImageTo3D(const GpuMat& disp, GpuMat& xyzw, const Mat& Q, int dst_cn = 4, Stream& stream = Stream::Null());\r
614 \r
615 //! converts image from one color space to another\r
616 CV_EXPORTS void cvtColor(const GpuMat& src, GpuMat& dst, int code, int dcn = 0, Stream& stream = Stream::Null());\r
617 \r
618 //! swap channels\r
619 //! dstOrder - Integer array describing how channel values are permutated. The n-th entry\r
620 //!            of the array contains the number of the channel that is stored in the n-th channel of\r
621 //!            the output image. E.g. Given an RGBA image, aDstOrder = [3,2,1,0] converts this to ABGR\r
622 //!            channel order.\r
623 CV_EXPORTS void swapChannels(GpuMat& image, const int dstOrder[4], Stream& stream = Stream::Null());\r
624 \r
625 //! Routines for correcting image color gamma\r
626 CV_EXPORTS void gammaCorrection(const GpuMat& src, GpuMat& dst, bool forward = true, Stream& stream = Stream::Null());\r
627 \r
628 //! applies fixed threshold to the image\r
629 CV_EXPORTS double threshold(const GpuMat& src, GpuMat& dst, double thresh, double maxval, int type, Stream& stream = Stream::Null());\r
630 \r
631 //! resizes the image\r
632 //! Supports INTER_NEAREST, INTER_LINEAR, INTER_CUBIC, INTER_AREA\r
633 CV_EXPORTS void resize(const GpuMat& src, GpuMat& dst, Size dsize, double fx=0, double fy=0, int interpolation = INTER_LINEAR, Stream& stream = Stream::Null());\r
634 \r
635 //! warps the image using affine transformation\r
636 //! Supports INTER_NEAREST, INTER_LINEAR, INTER_CUBIC\r
637 CV_EXPORTS void warpAffine(const GpuMat& src, GpuMat& dst, const Mat& M, Size dsize, int flags = INTER_LINEAR,\r
638     int borderMode = BORDER_CONSTANT, Scalar borderValue = Scalar(), Stream& stream = Stream::Null());\r
639 \r
640 CV_EXPORTS void buildWarpAffineMaps(const Mat& M, bool inverse, Size dsize, GpuMat& xmap, GpuMat& ymap, Stream& stream = Stream::Null());\r
641 \r
642 //! warps the image using perspective transformation\r
643 //! Supports INTER_NEAREST, INTER_LINEAR, INTER_CUBIC\r
644 CV_EXPORTS void warpPerspective(const GpuMat& src, GpuMat& dst, const Mat& M, Size dsize, int flags = INTER_LINEAR,\r
645     int borderMode = BORDER_CONSTANT, Scalar borderValue = Scalar(), Stream& stream = Stream::Null());\r
646 \r
647 CV_EXPORTS void buildWarpPerspectiveMaps(const Mat& M, bool inverse, Size dsize, GpuMat& xmap, GpuMat& ymap, Stream& stream = Stream::Null());\r
648 \r
649 //! builds plane warping maps\r
650 CV_EXPORTS void buildWarpPlaneMaps(Size src_size, Rect dst_roi, const Mat &K, const Mat& R, const Mat &T, float scale,\r
651                                    GpuMat& map_x, GpuMat& map_y, Stream& stream = Stream::Null());\r
652 \r
653 //! builds cylindrical warping maps\r
654 CV_EXPORTS void buildWarpCylindricalMaps(Size src_size, Rect dst_roi, const Mat &K, const Mat& R, float scale,\r
655                                          GpuMat& map_x, GpuMat& map_y, Stream& stream = Stream::Null());\r
656 \r
657 //! builds spherical warping maps\r
658 CV_EXPORTS void buildWarpSphericalMaps(Size src_size, Rect dst_roi, const Mat &K, const Mat& R, float scale,\r
659                                        GpuMat& map_x, GpuMat& map_y, Stream& stream = Stream::Null());\r
660 \r
661 //! rotates an image around the origin (0,0) and then shifts it\r
662 //! supports INTER_NEAREST, INTER_LINEAR, INTER_CUBIC\r
663 //! supports 1, 3 or 4 channels images with CV_8U, CV_16U or CV_32F depth\r
664 CV_EXPORTS void rotate(const GpuMat& src, GpuMat& dst, Size dsize, double angle, double xShift = 0, double yShift = 0,\r
665                        int interpolation = INTER_LINEAR, Stream& stream = Stream::Null());\r
666 \r
667 //! copies 2D array to a larger destination array and pads borders with user-specifiable constant\r
668 CV_EXPORTS void copyMakeBorder(const GpuMat& src, GpuMat& dst, int top, int bottom, int left, int right, int borderType,\r
669                                const Scalar& value = Scalar(), Stream& stream = Stream::Null());\r
670 \r
671 //! computes the integral image\r
672 //! sum will have CV_32S type, but will contain unsigned int values\r
673 //! supports only CV_8UC1 source type\r
674 CV_EXPORTS void integral(const GpuMat& src, GpuMat& sum, Stream& stream = Stream::Null());\r
675 //! buffered version\r
676 CV_EXPORTS void integralBuffered(const GpuMat& src, GpuMat& sum, GpuMat& buffer, Stream& stream = Stream::Null());\r
677 \r
678 //! computes squared integral image\r
679 //! result matrix will have 64F type, but will contain 64U values\r
680 //! supports source images of 8UC1 type only\r
681 CV_EXPORTS void sqrIntegral(const GpuMat& src, GpuMat& sqsum, Stream& stream = Stream::Null());\r
682 \r
683 //! computes vertical sum, supports only CV_32FC1 images\r
684 CV_EXPORTS void columnSum(const GpuMat& src, GpuMat& sum);\r
685 \r
686 //! computes the standard deviation of integral images\r
687 //! supports only CV_32SC1 source type and CV_32FC1 sqr type\r
688 //! output will have CV_32FC1 type\r
689 CV_EXPORTS void rectStdDev(const GpuMat& src, const GpuMat& sqr, GpuMat& dst, const Rect& rect, Stream& stream = Stream::Null());\r
690 \r
691 //! computes Harris cornerness criteria at each image pixel\r
692 CV_EXPORTS void cornerHarris(const GpuMat& src, GpuMat& dst, int blockSize, int ksize, double k, int borderType = BORDER_REFLECT101);\r
693 CV_EXPORTS void cornerHarris(const GpuMat& src, GpuMat& dst, GpuMat& Dx, GpuMat& Dy, int blockSize, int ksize, double k, int borderType = BORDER_REFLECT101);\r
694 CV_EXPORTS void cornerHarris(const GpuMat& src, GpuMat& dst, GpuMat& Dx, GpuMat& Dy, GpuMat& buf, int blockSize, int ksize, double k,\r
695                              int borderType = BORDER_REFLECT101, Stream& stream = Stream::Null());\r
696 \r
697 //! computes minimum eigen value of 2x2 derivative covariation matrix at each pixel - the cornerness criteria\r
698 CV_EXPORTS void cornerMinEigenVal(const GpuMat& src, GpuMat& dst, int blockSize, int ksize, int borderType=BORDER_REFLECT101);\r
699 CV_EXPORTS void cornerMinEigenVal(const GpuMat& src, GpuMat& dst, GpuMat& Dx, GpuMat& Dy, int blockSize, int ksize, int borderType=BORDER_REFLECT101);\r
700 CV_EXPORTS void cornerMinEigenVal(const GpuMat& src, GpuMat& dst, GpuMat& Dx, GpuMat& Dy, GpuMat& buf, int blockSize, int ksize,\r
701     int borderType=BORDER_REFLECT101, Stream& stream = Stream::Null());\r
702 \r
703 //! performs per-element multiplication of two full (not packed) Fourier spectrums\r
704 //! supports 32FC2 matrixes only (interleaved format)\r
705 CV_EXPORTS void mulSpectrums(const GpuMat& a, const GpuMat& b, GpuMat& c, int flags, bool conjB=false, Stream& stream = Stream::Null());\r
706 \r
707 //! performs per-element multiplication of two full (not packed) Fourier spectrums\r
708 //! supports 32FC2 matrixes only (interleaved format)\r
709 CV_EXPORTS void mulAndScaleSpectrums(const GpuMat& a, const GpuMat& b, GpuMat& c, int flags, float scale, bool conjB=false, Stream& stream = Stream::Null());\r
710 \r
711 //! Performs a forward or inverse discrete Fourier transform (1D or 2D) of floating point matrix.\r
712 //! Param dft_size is the size of DFT transform.\r
713 //!\r
714 //! If the source matrix is not continous, then additional copy will be done,\r
715 //! so to avoid copying ensure the source matrix is continous one. If you want to use\r
716 //! preallocated output ensure it is continuous too, otherwise it will be reallocated.\r
717 //!\r
718 //! Being implemented via CUFFT real-to-complex transform result contains only non-redundant values\r
719 //! in CUFFT's format. Result as full complex matrix for such kind of transform cannot be retrieved.\r
720 //!\r
721 //! For complex-to-real transform it is assumed that the source matrix is packed in CUFFT's format.\r
722 CV_EXPORTS void dft(const GpuMat& src, GpuMat& dst, Size dft_size, int flags=0, Stream& stream = Stream::Null());\r
723 \r
724 struct CV_EXPORTS ConvolveBuf\r
725 {\r
726     Size result_size;\r
727     Size block_size;\r
728     Size user_block_size;\r
729     Size dft_size;\r
730     int spect_len;\r
731 \r
732     GpuMat image_spect, templ_spect, result_spect;\r
733     GpuMat image_block, templ_block, result_data;\r
734 \r
735     void create(Size image_size, Size templ_size);\r
736     static Size estimateBlockSize(Size result_size, Size templ_size);\r
737 };\r
738 \r
739 \r
740 //! computes convolution (or cross-correlation) of two images using discrete Fourier transform\r
741 //! supports source images of 32FC1 type only\r
742 //! result matrix will have 32FC1 type\r
743 CV_EXPORTS void convolve(const GpuMat& image, const GpuMat& templ, GpuMat& result, bool ccorr = false);\r
744 CV_EXPORTS void convolve(const GpuMat& image, const GpuMat& templ, GpuMat& result, bool ccorr, ConvolveBuf& buf, Stream& stream = Stream::Null());\r
745 \r
746 struct CV_EXPORTS MatchTemplateBuf\r
747 {\r
748     Size user_block_size;\r
749     GpuMat imagef, templf;\r
750     std::vector<GpuMat> images;\r
751     std::vector<GpuMat> image_sums;\r
752     std::vector<GpuMat> image_sqsums;\r
753 };\r
754 \r
755 //! computes the proximity map for the raster template and the image where the template is searched for\r
756 CV_EXPORTS void matchTemplate(const GpuMat& image, const GpuMat& templ, GpuMat& result, int method, Stream &stream = Stream::Null());\r
757 \r
758 //! computes the proximity map for the raster template and the image where the template is searched for\r
759 CV_EXPORTS void matchTemplate(const GpuMat& image, const GpuMat& templ, GpuMat& result, int method, MatchTemplateBuf &buf, Stream& stream = Stream::Null());\r
760 \r
761 //! smoothes the source image and downsamples it\r
762 CV_EXPORTS void pyrDown(const GpuMat& src, GpuMat& dst, Stream& stream = Stream::Null());\r
763 \r
764 //! upsamples the source image and then smoothes it\r
765 CV_EXPORTS void pyrUp(const GpuMat& src, GpuMat& dst, Stream& stream = Stream::Null());\r
766 \r
767 //! performs linear blending of two images\r
768 //! to avoid accuracy errors sum of weigths shouldn't be very close to zero\r
769 CV_EXPORTS void blendLinear(const GpuMat& img1, const GpuMat& img2, const GpuMat& weights1, const GpuMat& weights2,\r
770                             GpuMat& result, Stream& stream = Stream::Null());\r
771 \r
772 //! Performa bilateral filtering of passsed image\r
773 CV_EXPORTS void bilateralFilter(const GpuMat& src, GpuMat& dst, int kernel_size, float sigma_color, float sigma_spatial,\r
774                                 int borderMode = BORDER_DEFAULT, Stream& stream = Stream::Null());\r
775 \r
776 //! Brute force non-local means algorith (slow but universal)\r
777 CV_EXPORTS void nonLocalMeans(const GpuMat& src, GpuMat& dst, float h,\r
778                               int search_widow_size = 11, int block_size = 7, int borderMode = BORDER_DEFAULT, Stream& s = Stream::Null());\r
779 \r
780 \r
781 struct CV_EXPORTS CannyBuf;\r
782 \r
783 CV_EXPORTS void Canny(const GpuMat& image, GpuMat& edges, double low_thresh, double high_thresh, int apperture_size = 3, bool L2gradient = false);\r
784 CV_EXPORTS void Canny(const GpuMat& image, CannyBuf& buf, GpuMat& edges, double low_thresh, double high_thresh, int apperture_size = 3, bool L2gradient = false);\r
785 CV_EXPORTS void Canny(const GpuMat& dx, const GpuMat& dy, GpuMat& edges, double low_thresh, double high_thresh, bool L2gradient = false);\r
786 CV_EXPORTS void Canny(const GpuMat& dx, const GpuMat& dy, CannyBuf& buf, GpuMat& edges, double low_thresh, double high_thresh, bool L2gradient = false);\r
787 \r
788 struct CV_EXPORTS CannyBuf\r
789 {\r
790     CannyBuf() {}\r
791     explicit CannyBuf(const Size& image_size, int apperture_size = 3) {create(image_size, apperture_size);}\r
792     CannyBuf(const GpuMat& dx_, const GpuMat& dy_);\r
793 \r
794     void create(const Size& image_size, int apperture_size = 3);\r
795 \r
796     void release();\r
797 \r
798     GpuMat dx, dy;\r
799     GpuMat dx_buf, dy_buf;\r
800     GpuMat edgeBuf;\r
801     GpuMat trackBuf1, trackBuf2;\r
802     Ptr<FilterEngine_GPU> filterDX, filterDY;\r
803 };\r
804 \r
805 class CV_EXPORTS ImagePyramid\r
806 {\r
807 public:\r
808     inline ImagePyramid() : nLayers_(0) {}\r
809     inline ImagePyramid(const GpuMat& img, int nLayers, Stream& stream = Stream::Null())\r
810     {\r
811         build(img, nLayers, stream);\r
812     }\r
813 \r
814     void build(const GpuMat& img, int nLayers, Stream& stream = Stream::Null());\r
815 \r
816     void getLayer(GpuMat& outImg, Size outRoi, Stream& stream = Stream::Null()) const;\r
817 \r
818     inline void release()\r
819     {\r
820         layer0_.release();\r
821         pyramid_.clear();\r
822         nLayers_ = 0;\r
823     }\r
824 \r
825 private:\r
826     GpuMat layer0_;\r
827     std::vector<GpuMat> pyramid_;\r
828     int nLayers_;\r
829 };\r
830 \r
831 //! HoughLines\r
832 \r
833 struct HoughLinesBuf\r
834 {\r
835     GpuMat accum;\r
836     GpuMat list;\r
837 };\r
838 \r
839 CV_EXPORTS void HoughLines(const GpuMat& src, GpuMat& lines, float rho, float theta, int threshold, bool doSort = false, int maxLines = 4096);\r
840 CV_EXPORTS void HoughLines(const GpuMat& src, GpuMat& lines, HoughLinesBuf& buf, float rho, float theta, int threshold, bool doSort = false, int maxLines = 4096);\r
841 CV_EXPORTS void HoughLinesDownload(const GpuMat& d_lines, OutputArray h_lines, OutputArray h_votes = noArray());\r
842 \r
843 //! HoughCircles\r
844 \r
845 struct HoughCirclesBuf\r
846 {\r
847     GpuMat edges;\r
848     GpuMat accum;\r
849     GpuMat list;\r
850     CannyBuf cannyBuf;\r
851 };\r
852 \r
853 CV_EXPORTS void HoughCircles(const GpuMat& src, GpuMat& circles, int method, float dp, float minDist, int cannyThreshold, int votesThreshold, int minRadius, int maxRadius, int maxCircles = 4096);\r
854 CV_EXPORTS void HoughCircles(const GpuMat& src, GpuMat& circles, HoughCirclesBuf& buf, int method, float dp, float minDist, int cannyThreshold, int votesThreshold, int minRadius, int maxRadius, int maxCircles = 4096);\r
855 CV_EXPORTS void HoughCirclesDownload(const GpuMat& d_circles, OutputArray h_circles);\r
856 \r
857 //! finds arbitrary template in the grayscale image using Generalized Hough Transform\r
858 //! Ballard, D.H. (1981). Generalizing the Hough transform to detect arbitrary shapes. Pattern Recognition 13 (2): 111-122.\r
859 //! Guil, N., González-Linares, J.M. and Zapata, E.L. (1999). Bidimensional shape detection using an invariant approach. Pattern Recognition 32 (6): 1025-1038.\r
860 class CV_EXPORTS GeneralizedHough_GPU : public Algorithm\r
861 {\r
862 public:\r
863     static Ptr<GeneralizedHough_GPU> create(int method);\r
864 \r
865     virtual ~GeneralizedHough_GPU();\r
866 \r
867     //! set template to search\r
868     void setTemplate(const GpuMat& templ, int cannyThreshold = 100, Point templCenter = Point(-1, -1));\r
869     void setTemplate(const GpuMat& edges, const GpuMat& dx, const GpuMat& dy, Point templCenter = Point(-1, -1));\r
870 \r
871     //! find template on image\r
872     void detect(const GpuMat& image, GpuMat& positions, int cannyThreshold = 100);\r
873     void detect(const GpuMat& edges, const GpuMat& dx, const GpuMat& dy, GpuMat& positions);\r
874 \r
875     void download(const GpuMat& d_positions, OutputArray h_positions, OutputArray h_votes = noArray());\r
876 \r
877     void release();\r
878 \r
879 protected:\r
880     virtual void setTemplateImpl(const GpuMat& edges, const GpuMat& dx, const GpuMat& dy, Point templCenter) = 0;\r
881     virtual void detectImpl(const GpuMat& edges, const GpuMat& dx, const GpuMat& dy, GpuMat& positions) = 0;\r
882     virtual void releaseImpl() = 0;\r
883 \r
884 private:\r
885     GpuMat edges_;\r
886     CannyBuf cannyBuf_;\r
887 };\r
888 \r
889 ////////////////////////////// Matrix reductions //////////////////////////////\r
890 \r
891 //! computes mean value and standard deviation of all or selected array elements\r
892 //! supports only CV_8UC1 type\r
893 CV_EXPORTS void meanStdDev(const GpuMat& mtx, Scalar& mean, Scalar& stddev);\r
894 //! buffered version\r
895 CV_EXPORTS void meanStdDev(const GpuMat& mtx, Scalar& mean, Scalar& stddev, GpuMat& buf);\r
896 \r
897 //! computes norm of array\r
898 //! supports NORM_INF, NORM_L1, NORM_L2\r
899 //! supports all matrices except 64F\r
900 CV_EXPORTS double norm(const GpuMat& src1, int normType=NORM_L2);\r
901 \r
902 //! computes norm of array\r
903 //! supports NORM_INF, NORM_L1, NORM_L2\r
904 //! supports all matrices except 64F\r
905 CV_EXPORTS double norm(const GpuMat& src1, int normType, GpuMat& buf);\r
906 \r
907 //! computes norm of the difference between two arrays\r
908 //! supports NORM_INF, NORM_L1, NORM_L2\r
909 //! supports only CV_8UC1 type\r
910 CV_EXPORTS double norm(const GpuMat& src1, const GpuMat& src2, int normType=NORM_L2);\r
911 \r
912 //! computes sum of array elements\r
913 //! supports only single channel images\r
914 CV_EXPORTS Scalar sum(const GpuMat& src);\r
915 \r
916 //! computes sum of array elements\r
917 //! supports only single channel images\r
918 CV_EXPORTS Scalar sum(const GpuMat& src, GpuMat& buf);\r
919 \r
920 //! computes sum of array elements absolute values\r
921 //! supports only single channel images\r
922 CV_EXPORTS Scalar absSum(const GpuMat& src);\r
923 \r
924 //! computes sum of array elements absolute values\r
925 //! supports only single channel images\r
926 CV_EXPORTS Scalar absSum(const GpuMat& src, GpuMat& buf);\r
927 \r
928 //! computes squared sum of array elements\r
929 //! supports only single channel images\r
930 CV_EXPORTS Scalar sqrSum(const GpuMat& src);\r
931 \r
932 //! computes squared sum of array elements\r
933 //! supports only single channel images\r
934 CV_EXPORTS Scalar sqrSum(const GpuMat& src, GpuMat& buf);\r
935 \r
936 //! finds global minimum and maximum array elements and returns their values\r
937 CV_EXPORTS void minMax(const GpuMat& src, double* minVal, double* maxVal=0, const GpuMat& mask=GpuMat());\r
938 \r
939 //! finds global minimum and maximum array elements and returns their values\r
940 CV_EXPORTS void minMax(const GpuMat& src, double* minVal, double* maxVal, const GpuMat& mask, GpuMat& buf);\r
941 \r
942 //! finds global minimum and maximum array elements and returns their values with locations\r
943 CV_EXPORTS void minMaxLoc(const GpuMat& src, double* minVal, double* maxVal=0, Point* minLoc=0, Point* maxLoc=0,\r
944                           const GpuMat& mask=GpuMat());\r
945 \r
946 //! finds global minimum and maximum array elements and returns their values with locations\r
947 CV_EXPORTS void minMaxLoc(const GpuMat& src, double* minVal, double* maxVal, Point* minLoc, Point* maxLoc,\r
948                           const GpuMat& mask, GpuMat& valbuf, GpuMat& locbuf);\r
949 \r
950 //! counts non-zero array elements\r
951 CV_EXPORTS int countNonZero(const GpuMat& src);\r
952 \r
953 //! counts non-zero array elements\r
954 CV_EXPORTS int countNonZero(const GpuMat& src, GpuMat& buf);\r
955 \r
956 //! reduces a matrix to a vector\r
957 CV_EXPORTS void reduce(const GpuMat& mtx, GpuMat& vec, int dim, int reduceOp, int dtype = -1, Stream& stream = Stream::Null());\r
958 \r
959 \r
960 ///////////////////////////// Calibration 3D //////////////////////////////////\r
961 \r
962 CV_EXPORTS void transformPoints(const GpuMat& src, const Mat& rvec, const Mat& tvec,\r
963                                 GpuMat& dst, Stream& stream = Stream::Null());\r
964 \r
965 CV_EXPORTS void projectPoints(const GpuMat& src, const Mat& rvec, const Mat& tvec,\r
966                               const Mat& camera_mat, const Mat& dist_coef, GpuMat& dst,\r
967                               Stream& stream = Stream::Null());\r
968 \r
969 CV_EXPORTS void solvePnPRansac(const Mat& object, const Mat& image, const Mat& camera_mat,\r
970                                const Mat& dist_coef, Mat& rvec, Mat& tvec, bool use_extrinsic_guess=false,\r
971                                int num_iters=100, float max_dist=8.0, int min_inlier_count=100,\r
972                                std::vector<int>* inliers=NULL);\r
973 \r
974 //////////////////////////////// Image Labeling ////////////////////////////////\r
975 \r
976 //!performs labeling via graph cuts of a 2D regular 4-connected graph.\r
977 CV_EXPORTS void graphcut(GpuMat& terminals, GpuMat& leftTransp, GpuMat& rightTransp, GpuMat& top, GpuMat& bottom, GpuMat& labels,\r
978                          GpuMat& buf, Stream& stream = Stream::Null());\r
979 \r
980 //!performs labeling via graph cuts of a 2D regular 8-connected graph.\r
981 CV_EXPORTS void graphcut(GpuMat& terminals, GpuMat& leftTransp, GpuMat& rightTransp, GpuMat& top, GpuMat& topLeft, GpuMat& topRight,\r
982                          GpuMat& bottom, GpuMat& bottomLeft, GpuMat& bottomRight,\r
983                          GpuMat& labels,\r
984                          GpuMat& buf, Stream& stream = Stream::Null());\r
985 \r
986 //! compute mask for Generalized Flood fill componetns labeling.\r
987 CV_EXPORTS void connectivityMask(const GpuMat& image, GpuMat& mask, const cv::Scalar& lo, const cv::Scalar& hi, Stream& stream = Stream::Null());\r
988 \r
989 //! performs connected componnents labeling.\r
990 CV_EXPORTS void labelComponents(const GpuMat& mask, GpuMat& components, int flags = 0, Stream& stream = Stream::Null());\r
991 \r
992 ////////////////////////////////// Histograms //////////////////////////////////\r
993 \r
994 //! Compute levels with even distribution. levels will have 1 row and nLevels cols and CV_32SC1 type.\r
995 CV_EXPORTS void evenLevels(GpuMat& levels, int nLevels, int lowerLevel, int upperLevel);\r
996 //! Calculates histogram with evenly distributed bins for signle channel source.\r
997 //! Supports CV_8UC1, CV_16UC1 and CV_16SC1 source types.\r
998 //! Output hist will have one row and histSize cols and CV_32SC1 type.\r
999 CV_EXPORTS void histEven(const GpuMat& src, GpuMat& hist, int histSize, int lowerLevel, int upperLevel, Stream& stream = Stream::Null());\r
1000 CV_EXPORTS void histEven(const GpuMat& src, GpuMat& hist, GpuMat& buf, int histSize, int lowerLevel, int upperLevel, Stream& stream = Stream::Null());\r
1001 //! Calculates histogram with evenly distributed bins for four-channel source.\r
1002 //! All channels of source are processed separately.\r
1003 //! Supports CV_8UC4, CV_16UC4 and CV_16SC4 source types.\r
1004 //! Output hist[i] will have one row and histSize[i] cols and CV_32SC1 type.\r
1005 CV_EXPORTS void histEven(const GpuMat& src, GpuMat hist[4], int histSize[4], int lowerLevel[4], int upperLevel[4], Stream& stream = Stream::Null());\r
1006 CV_EXPORTS void histEven(const GpuMat& src, GpuMat hist[4], GpuMat& buf, int histSize[4], int lowerLevel[4], int upperLevel[4], Stream& stream = Stream::Null());\r
1007 //! Calculates histogram with bins determined by levels array.\r
1008 //! levels must have one row and CV_32SC1 type if source has integer type or CV_32FC1 otherwise.\r
1009 //! Supports CV_8UC1, CV_16UC1, CV_16SC1 and CV_32FC1 source types.\r
1010 //! Output hist will have one row and (levels.cols-1) cols and CV_32SC1 type.\r
1011 CV_EXPORTS void histRange(const GpuMat& src, GpuMat& hist, const GpuMat& levels, Stream& stream = Stream::Null());\r
1012 CV_EXPORTS void histRange(const GpuMat& src, GpuMat& hist, const GpuMat& levels, GpuMat& buf, Stream& stream = Stream::Null());\r
1013 //! Calculates histogram with bins determined by levels array.\r
1014 //! All levels must have one row and CV_32SC1 type if source has integer type or CV_32FC1 otherwise.\r
1015 //! All channels of source are processed separately.\r
1016 //! Supports CV_8UC4, CV_16UC4, CV_16SC4 and CV_32FC4 source types.\r
1017 //! Output hist[i] will have one row and (levels[i].cols-1) cols and CV_32SC1 type.\r
1018 CV_EXPORTS void histRange(const GpuMat& src, GpuMat hist[4], const GpuMat levels[4], Stream& stream = Stream::Null());\r
1019 CV_EXPORTS void histRange(const GpuMat& src, GpuMat hist[4], const GpuMat levels[4], GpuMat& buf, Stream& stream = Stream::Null());\r
1020 \r
1021 //! Calculates histogram for 8u one channel image\r
1022 //! Output hist will have one row, 256 cols and CV32SC1 type.\r
1023 CV_EXPORTS void calcHist(const GpuMat& src, GpuMat& hist, Stream& stream = Stream::Null());\r
1024 CV_EXPORTS void calcHist(const GpuMat& src, GpuMat& hist, GpuMat& buf, Stream& stream = Stream::Null());\r
1025 \r
1026 //! normalizes the grayscale image brightness and contrast by normalizing its histogram\r
1027 CV_EXPORTS void equalizeHist(const GpuMat& src, GpuMat& dst, Stream& stream = Stream::Null());\r
1028 CV_EXPORTS void equalizeHist(const GpuMat& src, GpuMat& dst, GpuMat& hist, Stream& stream = Stream::Null());\r
1029 CV_EXPORTS void equalizeHist(const GpuMat& src, GpuMat& dst, GpuMat& hist, GpuMat& buf, Stream& stream = Stream::Null());\r
1030 \r
1031 //////////////////////////////// StereoBM_GPU ////////////////////////////////\r
1032 \r
1033 class CV_EXPORTS StereoBM_GPU\r
1034 {\r
1035 public:\r
1036     enum { BASIC_PRESET = 0, PREFILTER_XSOBEL = 1 };\r
1037 \r
1038     enum { DEFAULT_NDISP = 64, DEFAULT_WINSZ = 19 };\r
1039 \r
1040     //! the default constructor\r
1041     StereoBM_GPU();\r
1042     //! the full constructor taking the camera-specific preset, number of disparities and the SAD window size. ndisparities must be multiple of 8.\r
1043     StereoBM_GPU(int preset, int ndisparities = DEFAULT_NDISP, int winSize = DEFAULT_WINSZ);\r
1044 \r
1045     //! the stereo correspondence operator. Finds the disparity for the specified rectified stereo pair\r
1046     //! Output disparity has CV_8U type.\r
1047     void operator()(const GpuMat& left, const GpuMat& right, GpuMat& disparity, Stream& stream = Stream::Null());\r
1048 \r
1049     //! Some heuristics that tries to estmate\r
1050     // if current GPU will be faster than CPU in this algorithm.\r
1051     // It queries current active device.\r
1052     static bool checkIfGpuCallReasonable();\r
1053 \r
1054     int preset;\r
1055     int ndisp;\r
1056     int winSize;\r
1057 \r
1058     // If avergeTexThreshold  == 0 => post procesing is disabled\r
1059     // If avergeTexThreshold != 0 then disparity is set 0 in each point (x,y) where for left image\r
1060     // SumOfHorizontalGradiensInWindow(x, y, winSize) < (winSize * winSize) * avergeTexThreshold\r
1061     // i.e. input left image is low textured.\r
1062     float avergeTexThreshold;\r
1063 \r
1064 private:\r
1065     GpuMat minSSD, leBuf, riBuf;\r
1066 };\r
1067 \r
1068 ////////////////////////// StereoBeliefPropagation ///////////////////////////\r
1069 // "Efficient Belief Propagation for Early Vision"\r
1070 // P.Felzenszwalb\r
1071 \r
1072 class CV_EXPORTS StereoBeliefPropagation\r
1073 {\r
1074 public:\r
1075     enum { DEFAULT_NDISP  = 64 };\r
1076     enum { DEFAULT_ITERS  = 5  };\r
1077     enum { DEFAULT_LEVELS = 5  };\r
1078 \r
1079     static void estimateRecommendedParams(int width, int height, int& ndisp, int& iters, int& levels);\r
1080 \r
1081     //! the default constructor\r
1082     explicit StereoBeliefPropagation(int ndisp  = DEFAULT_NDISP,\r
1083                                      int iters  = DEFAULT_ITERS,\r
1084                                      int levels = DEFAULT_LEVELS,\r
1085                                      int msg_type = CV_32F);\r
1086 \r
1087     //! the full constructor taking the number of disparities, number of BP iterations on each level,\r
1088     //! number of levels, truncation of data cost, data weight,\r
1089     //! truncation of discontinuity cost and discontinuity single jump\r
1090     //! DataTerm = data_weight * min(fabs(I2-I1), max_data_term)\r
1091     //! DiscTerm = min(disc_single_jump * fabs(f1-f2), max_disc_term)\r
1092     //! please see paper for more details\r
1093     StereoBeliefPropagation(int ndisp, int iters, int levels,\r
1094         float max_data_term, float data_weight,\r
1095         float max_disc_term, float disc_single_jump,\r
1096         int msg_type = CV_32F);\r
1097 \r
1098     //! the stereo correspondence operator. Finds the disparity for the specified rectified stereo pair,\r
1099     //! if disparity is empty output type will be CV_16S else output type will be disparity.type().\r
1100     void operator()(const GpuMat& left, const GpuMat& right, GpuMat& disparity, Stream& stream = Stream::Null());\r
1101 \r
1102 \r
1103     //! version for user specified data term\r
1104     void operator()(const GpuMat& data, GpuMat& disparity, Stream& stream = Stream::Null());\r
1105 \r
1106     int ndisp;\r
1107 \r
1108     int iters;\r
1109     int levels;\r
1110 \r
1111     float max_data_term;\r
1112     float data_weight;\r
1113     float max_disc_term;\r
1114     float disc_single_jump;\r
1115 \r
1116     int msg_type;\r
1117 private:\r
1118     GpuMat u, d, l, r, u2, d2, l2, r2;\r
1119     std::vector<GpuMat> datas;\r
1120     GpuMat out;\r
1121 };\r
1122 \r
1123 /////////////////////////// StereoConstantSpaceBP ///////////////////////////\r
1124 // "A Constant-Space Belief Propagation Algorithm for Stereo Matching"\r
1125 // Qingxiong Yang, Liang Wang, Narendra Ahuja\r
1126 // http://vision.ai.uiuc.edu/~qyang6/\r
1127 \r
1128 class CV_EXPORTS StereoConstantSpaceBP\r
1129 {\r
1130 public:\r
1131     enum { DEFAULT_NDISP    = 128 };\r
1132     enum { DEFAULT_ITERS    = 8   };\r
1133     enum { DEFAULT_LEVELS   = 4   };\r
1134     enum { DEFAULT_NR_PLANE = 4   };\r
1135 \r
1136     static void estimateRecommendedParams(int width, int height, int& ndisp, int& iters, int& levels, int& nr_plane);\r
1137 \r
1138     //! the default constructor\r
1139     explicit StereoConstantSpaceBP(int ndisp    = DEFAULT_NDISP,\r
1140                                    int iters    = DEFAULT_ITERS,\r
1141                                    int levels   = DEFAULT_LEVELS,\r
1142                                    int nr_plane = DEFAULT_NR_PLANE,\r
1143                                    int msg_type = CV_32F);\r
1144 \r
1145     //! the full constructor taking the number of disparities, number of BP iterations on each level,\r
1146     //! number of levels, number of active disparity on the first level, truncation of data cost, data weight,\r
1147     //! truncation of discontinuity cost, discontinuity single jump and minimum disparity threshold\r
1148     StereoConstantSpaceBP(int ndisp, int iters, int levels, int nr_plane,\r
1149         float max_data_term, float data_weight, float max_disc_term, float disc_single_jump,\r
1150         int min_disp_th = 0,\r
1151         int msg_type = CV_32F);\r
1152 \r
1153     //! the stereo correspondence operator. Finds the disparity for the specified rectified stereo pair,\r
1154     //! if disparity is empty output type will be CV_16S else output type will be disparity.type().\r
1155     void operator()(const GpuMat& left, const GpuMat& right, GpuMat& disparity, Stream& stream = Stream::Null());\r
1156 \r
1157     int ndisp;\r
1158 \r
1159     int iters;\r
1160     int levels;\r
1161 \r
1162     int nr_plane;\r
1163 \r
1164     float max_data_term;\r
1165     float data_weight;\r
1166     float max_disc_term;\r
1167     float disc_single_jump;\r
1168 \r
1169     int min_disp_th;\r
1170 \r
1171     int msg_type;\r
1172 \r
1173     bool use_local_init_data_cost;\r
1174 private:\r
1175     GpuMat messages_buffers;\r
1176 \r
1177     GpuMat temp;\r
1178     GpuMat out;\r
1179 };\r
1180 \r
1181 /////////////////////////// DisparityBilateralFilter ///////////////////////////\r
1182 // Disparity map refinement using joint bilateral filtering given a single color image.\r
1183 // Qingxiong Yang, Liang Wang, Narendra Ahuja\r
1184 // http://vision.ai.uiuc.edu/~qyang6/\r
1185 \r
1186 class CV_EXPORTS DisparityBilateralFilter\r
1187 {\r
1188 public:\r
1189     enum { DEFAULT_NDISP  = 64 };\r
1190     enum { DEFAULT_RADIUS = 3 };\r
1191     enum { DEFAULT_ITERS  = 1 };\r
1192 \r
1193     //! the default constructor\r
1194     explicit DisparityBilateralFilter(int ndisp = DEFAULT_NDISP, int radius = DEFAULT_RADIUS, int iters = DEFAULT_ITERS);\r
1195 \r
1196     //! the full constructor taking the number of disparities, filter radius,\r
1197     //! number of iterations, truncation of data continuity, truncation of disparity continuity\r
1198     //! and filter range sigma\r
1199     DisparityBilateralFilter(int ndisp, int radius, int iters, float edge_threshold, float max_disc_threshold, float sigma_range);\r
1200 \r
1201     //! the disparity map refinement operator. Refine disparity map using joint bilateral filtering given a single color image.\r
1202     //! disparity must have CV_8U or CV_16S type, image must have CV_8UC1 or CV_8UC3 type.\r
1203     void operator()(const GpuMat& disparity, const GpuMat& image, GpuMat& dst, Stream& stream = Stream::Null());\r
1204 \r
1205 private:\r
1206     int ndisp;\r
1207     int radius;\r
1208     int iters;\r
1209 \r
1210     float edge_threshold;\r
1211     float max_disc_threshold;\r
1212     float sigma_range;\r
1213 \r
1214     GpuMat table_color;\r
1215     GpuMat table_space;\r
1216 };\r
1217 \r
1218 \r
1219 //////////////// HOG (Histogram-of-Oriented-Gradients) Descriptor and Object Detector //////////////\r
1220 struct CV_EXPORTS HOGConfidence\r
1221 {\r
1222    double scale;\r
1223    vector<Point> locations;\r
1224    vector<double> confidences;\r
1225    vector<double> part_scores[4];\r
1226 };\r
1227 \r
1228 struct CV_EXPORTS HOGDescriptor\r
1229 {\r
1230     enum { DEFAULT_WIN_SIGMA = -1 };\r
1231     enum { DEFAULT_NLEVELS = 64 };\r
1232     enum { DESCR_FORMAT_ROW_BY_ROW, DESCR_FORMAT_COL_BY_COL };\r
1233 \r
1234     HOGDescriptor(Size win_size=Size(64, 128), Size block_size=Size(16, 16),\r
1235                   Size block_stride=Size(8, 8), Size cell_size=Size(8, 8),\r
1236                   int nbins=9, double win_sigma=DEFAULT_WIN_SIGMA,\r
1237                   double threshold_L2hys=0.2, bool gamma_correction=true,\r
1238                   int nlevels=DEFAULT_NLEVELS);\r
1239 \r
1240     size_t getDescriptorSize() const;\r
1241     size_t getBlockHistogramSize() const;\r
1242 \r
1243     void setSVMDetector(const vector<float>& detector);\r
1244 \r
1245     static vector<float> getDefaultPeopleDetector();\r
1246     static vector<float> getPeopleDetector48x96();\r
1247     static vector<float> getPeopleDetector64x128();\r
1248 \r
1249     void detect(const GpuMat& img, vector<Point>& found_locations,\r
1250                 double hit_threshold=0, Size win_stride=Size(),\r
1251                 Size padding=Size());\r
1252 \r
1253     void detectMultiScale(const GpuMat& img, vector<Rect>& found_locations,\r
1254                           double hit_threshold=0, Size win_stride=Size(),\r
1255                           Size padding=Size(), double scale0=1.05,\r
1256                           int group_threshold=2);\r
1257 \r
1258     void computeConfidence(const GpuMat& img, vector<Point>& hits, double hit_threshold,\r
1259                                                 Size win_stride, Size padding, vector<Point>& locations, vector<double>& confidences);\r
1260 \r
1261     void computeConfidenceMultiScale(const GpuMat& img, vector<Rect>& found_locations,\r
1262                                                                     double hit_threshold, Size win_stride, Size padding,\r
1263                                                                     vector<HOGConfidence> &conf_out, int group_threshold);\r
1264 \r
1265     void getDescriptors(const GpuMat& img, Size win_stride,\r
1266                         GpuMat& descriptors,\r
1267                         int descr_format=DESCR_FORMAT_COL_BY_COL);\r
1268 \r
1269     Size win_size;\r
1270     Size block_size;\r
1271     Size block_stride;\r
1272     Size cell_size;\r
1273     int nbins;\r
1274     double win_sigma;\r
1275     double threshold_L2hys;\r
1276     bool gamma_correction;\r
1277     int nlevels;\r
1278 \r
1279 protected:\r
1280     void computeBlockHistograms(const GpuMat& img);\r
1281     void computeGradient(const GpuMat& img, GpuMat& grad, GpuMat& qangle);\r
1282 \r
1283     double getWinSigma() const;\r
1284     bool checkDetectorSize() const;\r
1285 \r
1286     static int numPartsWithin(int size, int part_size, int stride);\r
1287     static Size numPartsWithin(Size size, Size part_size, Size stride);\r
1288 \r
1289     // Coefficients of the separating plane\r
1290     float free_coef;\r
1291     GpuMat detector;\r
1292 \r
1293     // Results of the last classification step\r
1294     GpuMat labels, labels_buf;\r
1295     Mat labels_host;\r
1296 \r
1297     // Results of the last histogram evaluation step\r
1298     GpuMat block_hists, block_hists_buf;\r
1299 \r
1300     // Gradients conputation results\r
1301     GpuMat grad, qangle, grad_buf, qangle_buf;\r
1302 \r
1303     // returns subbuffer with required size, reallocates buffer if nessesary.\r
1304     static GpuMat getBuffer(const Size& sz, int type, GpuMat& buf);\r
1305     static GpuMat getBuffer(int rows, int cols, int type, GpuMat& buf);\r
1306 \r
1307     std::vector<GpuMat> image_scales;\r
1308 };\r
1309 \r
1310 \r
1311 ////////////////////////////////// BruteForceMatcher //////////////////////////////////\r
1312 \r
1313 class CV_EXPORTS BFMatcher_GPU\r
1314 {\r
1315 public:\r
1316     explicit BFMatcher_GPU(int norm = cv::NORM_L2);\r
1317 \r
1318     // Add descriptors to train descriptor collection\r
1319     void add(const std::vector<GpuMat>& descCollection);\r
1320 \r
1321     // Get train descriptors collection\r
1322     const std::vector<GpuMat>& getTrainDescriptors() const;\r
1323 \r
1324     // Clear train descriptors collection\r
1325     void clear();\r
1326 \r
1327     // Return true if there are not train descriptors in collection\r
1328     bool empty() const;\r
1329 \r
1330     // Return true if the matcher supports mask in match methods\r
1331     bool isMaskSupported() const;\r
1332 \r
1333     // Find one best match for each query descriptor\r
1334     void matchSingle(const GpuMat& query, const GpuMat& train,\r
1335         GpuMat& trainIdx, GpuMat& distance,\r
1336         const GpuMat& mask = GpuMat(), Stream& stream = Stream::Null());\r
1337 \r
1338     // Download trainIdx and distance and convert it to CPU vector with DMatch\r
1339     static void matchDownload(const GpuMat& trainIdx, const GpuMat& distance, std::vector<DMatch>& matches);\r
1340     // Convert trainIdx and distance to vector with DMatch\r
1341     static void matchConvert(const Mat& trainIdx, const Mat& distance, std::vector<DMatch>& matches);\r
1342 \r
1343     // Find one best match for each query descriptor\r
1344     void match(const GpuMat& query, const GpuMat& train, std::vector<DMatch>& matches, const GpuMat& mask = GpuMat());\r
1345 \r
1346     // Make gpu collection of trains and masks in suitable format for matchCollection function\r
1347     void makeGpuCollection(GpuMat& trainCollection, GpuMat& maskCollection, const std::vector<GpuMat>& masks = std::vector<GpuMat>());\r
1348 \r
1349     // Find one best match from train collection for each query descriptor\r
1350     void matchCollection(const GpuMat& query, const GpuMat& trainCollection,\r
1351         GpuMat& trainIdx, GpuMat& imgIdx, GpuMat& distance,\r
1352         const GpuMat& masks = GpuMat(), Stream& stream = Stream::Null());\r
1353 \r
1354     // Download trainIdx, imgIdx and distance and convert it to vector with DMatch\r
1355     static void matchDownload(const GpuMat& trainIdx, const GpuMat& imgIdx, const GpuMat& distance, std::vector<DMatch>& matches);\r
1356     // Convert trainIdx, imgIdx and distance to vector with DMatch\r
1357     static void matchConvert(const Mat& trainIdx, const Mat& imgIdx, const Mat& distance, std::vector<DMatch>& matches);\r
1358 \r
1359     // Find one best match from train collection for each query descriptor.\r
1360     void match(const GpuMat& query, std::vector<DMatch>& matches, const std::vector<GpuMat>& masks = std::vector<GpuMat>());\r
1361 \r
1362     // Find k best matches for each query descriptor (in increasing order of distances)\r
1363     void knnMatchSingle(const GpuMat& query, const GpuMat& train,\r
1364         GpuMat& trainIdx, GpuMat& distance, GpuMat& allDist, int k,\r
1365         const GpuMat& mask = GpuMat(), Stream& stream = Stream::Null());\r
1366 \r
1367     // Download trainIdx and distance and convert it to vector with DMatch\r
1368     // compactResult is used when mask is not empty. If compactResult is false matches\r
1369     // vector will have the same size as queryDescriptors rows. If compactResult is true\r
1370     // matches vector will not contain matches for fully masked out query descriptors.\r
1371     static void knnMatchDownload(const GpuMat& trainIdx, const GpuMat& distance,\r
1372         std::vector< std::vector<DMatch> >& matches, bool compactResult = false);\r
1373     // Convert trainIdx and distance to vector with DMatch\r
1374     static void knnMatchConvert(const Mat& trainIdx, const Mat& distance,\r
1375         std::vector< std::vector<DMatch> >& matches, bool compactResult = false);\r
1376 \r
1377     // Find k best matches for each query descriptor (in increasing order of distances).\r
1378     // compactResult is used when mask is not empty. If compactResult is false matches\r
1379     // vector will have the same size as queryDescriptors rows. If compactResult is true\r
1380     // matches vector will not contain matches for fully masked out query descriptors.\r
1381     void knnMatch(const GpuMat& query, const GpuMat& train,\r
1382         std::vector< std::vector<DMatch> >& matches, int k, const GpuMat& mask = GpuMat(),\r
1383         bool compactResult = false);\r
1384 \r
1385     // Find k best matches from train collection for each query descriptor (in increasing order of distances)\r
1386     void knnMatch2Collection(const GpuMat& query, const GpuMat& trainCollection,\r
1387         GpuMat& trainIdx, GpuMat& imgIdx, GpuMat& distance,\r
1388         const GpuMat& maskCollection = GpuMat(), Stream& stream = Stream::Null());\r
1389 \r
1390     // Download trainIdx and distance and convert it to vector with DMatch\r
1391     // compactResult is used when mask is not empty. If compactResult is false matches\r
1392     // vector will have the same size as queryDescriptors rows. If compactResult is true\r
1393     // matches vector will not contain matches for fully masked out query descriptors.\r
1394     static void knnMatch2Download(const GpuMat& trainIdx, const GpuMat& imgIdx, const GpuMat& distance,\r
1395         std::vector< std::vector<DMatch> >& matches, bool compactResult = false);\r
1396     // Convert trainIdx and distance to vector with DMatch\r
1397     static void knnMatch2Convert(const Mat& trainIdx, const Mat& imgIdx, const Mat& distance,\r
1398         std::vector< std::vector<DMatch> >& matches, bool compactResult = false);\r
1399 \r
1400     // Find k best matches  for each query descriptor (in increasing order of distances).\r
1401     // compactResult is used when mask is not empty. If compactResult is false matches\r
1402     // vector will have the same size as queryDescriptors rows. If compactResult is true\r
1403     // matches vector will not contain matches for fully masked out query descriptors.\r
1404     void knnMatch(const GpuMat& query, std::vector< std::vector<DMatch> >& matches, int k,\r
1405         const std::vector<GpuMat>& masks = std::vector<GpuMat>(), bool compactResult = false);\r
1406 \r
1407     // Find best matches for each query descriptor which have distance less than maxDistance.\r
1408     // nMatches.at<int>(0, queryIdx) will contain matches count for queryIdx.\r
1409     // carefully nMatches can be greater than trainIdx.cols - it means that matcher didn't find all matches,\r
1410     // because it didn't have enough memory.\r
1411     // If trainIdx is empty, then trainIdx and distance will be created with size nQuery x max((nTrain / 100), 10),\r
1412     // otherwize user can pass own allocated trainIdx and distance with size nQuery x nMaxMatches\r
1413     // Matches doesn't sorted.\r
1414     void radiusMatchSingle(const GpuMat& query, const GpuMat& train,\r
1415         GpuMat& trainIdx, GpuMat& distance, GpuMat& nMatches, float maxDistance,\r
1416         const GpuMat& mask = GpuMat(), Stream& stream = Stream::Null());\r
1417 \r
1418     // Download trainIdx, nMatches and distance and convert it to vector with DMatch.\r
1419     // matches will be sorted in increasing order of distances.\r
1420     // compactResult is used when mask is not empty. If compactResult is false matches\r
1421     // vector will have the same size as queryDescriptors rows. If compactResult is true\r
1422     // matches vector will not contain matches for fully masked out query descriptors.\r
1423     static void radiusMatchDownload(const GpuMat& trainIdx, const GpuMat& distance, const GpuMat& nMatches,\r
1424         std::vector< std::vector<DMatch> >& matches, bool compactResult = false);\r
1425     // Convert trainIdx, nMatches and distance to vector with DMatch.\r
1426     static void radiusMatchConvert(const Mat& trainIdx, const Mat& distance, const Mat& nMatches,\r
1427         std::vector< std::vector<DMatch> >& matches, bool compactResult = false);\r
1428 \r
1429     // Find best matches for each query descriptor which have distance less than maxDistance\r
1430     // in increasing order of distances).\r
1431     void radiusMatch(const GpuMat& query, const GpuMat& train,\r
1432         std::vector< std::vector<DMatch> >& matches, float maxDistance,\r
1433         const GpuMat& mask = GpuMat(), bool compactResult = false);\r
1434 \r
1435     // Find best matches for each query descriptor which have distance less than maxDistance.\r
1436     // If trainIdx is empty, then trainIdx and distance will be created with size nQuery x max((nQuery / 100), 10),\r
1437     // otherwize user can pass own allocated trainIdx and distance with size nQuery x nMaxMatches\r
1438     // Matches doesn't sorted.\r
1439     void radiusMatchCollection(const GpuMat& query, GpuMat& trainIdx, GpuMat& imgIdx, GpuMat& distance, GpuMat& nMatches, float maxDistance,\r
1440         const std::vector<GpuMat>& masks = std::vector<GpuMat>(), Stream& stream = Stream::Null());\r
1441 \r
1442     // Download trainIdx, imgIdx, nMatches and distance and convert it to vector with DMatch.\r
1443     // matches will be sorted in increasing order of distances.\r
1444     // compactResult is used when mask is not empty. If compactResult is false matches\r
1445     // vector will have the same size as queryDescriptors rows. If compactResult is true\r
1446     // matches vector will not contain matches for fully masked out query descriptors.\r
1447     static void radiusMatchDownload(const GpuMat& trainIdx, const GpuMat& imgIdx, const GpuMat& distance, const GpuMat& nMatches,\r
1448         std::vector< std::vector<DMatch> >& matches, bool compactResult = false);\r
1449     // Convert trainIdx, nMatches and distance to vector with DMatch.\r
1450     static void radiusMatchConvert(const Mat& trainIdx, const Mat& imgIdx, const Mat& distance, const Mat& nMatches,\r
1451         std::vector< std::vector<DMatch> >& matches, bool compactResult = false);\r
1452 \r
1453     // Find best matches from train collection for each query descriptor which have distance less than\r
1454     // maxDistance (in increasing order of distances).\r
1455     void radiusMatch(const GpuMat& query, std::vector< std::vector<DMatch> >& matches, float maxDistance,\r
1456         const std::vector<GpuMat>& masks = std::vector<GpuMat>(), bool compactResult = false);\r
1457 \r
1458     int norm;\r
1459 \r
1460 private:\r
1461     std::vector<GpuMat> trainDescCollection;\r
1462 };\r
1463 \r
1464 template <class Distance>\r
1465 class CV_EXPORTS BruteForceMatcher_GPU;\r
1466 \r
1467 template <typename T>\r
1468 class CV_EXPORTS BruteForceMatcher_GPU< L1<T> > : public BFMatcher_GPU\r
1469 {\r
1470 public:\r
1471     explicit BruteForceMatcher_GPU() : BFMatcher_GPU(NORM_L1) {}\r
1472     explicit BruteForceMatcher_GPU(L1<T> /*d*/) : BFMatcher_GPU(NORM_L1) {}\r
1473 };\r
1474 template <typename T>\r
1475 class CV_EXPORTS BruteForceMatcher_GPU< L2<T> > : public BFMatcher_GPU\r
1476 {\r
1477 public:\r
1478     explicit BruteForceMatcher_GPU() : BFMatcher_GPU(NORM_L2) {}\r
1479     explicit BruteForceMatcher_GPU(L2<T> /*d*/) : BFMatcher_GPU(NORM_L2) {}\r
1480 };\r
1481 template <> class CV_EXPORTS BruteForceMatcher_GPU< Hamming > : public BFMatcher_GPU\r
1482 {\r
1483 public:\r
1484     explicit BruteForceMatcher_GPU() : BFMatcher_GPU(NORM_HAMMING) {}\r
1485     explicit BruteForceMatcher_GPU(Hamming /*d*/) : BFMatcher_GPU(NORM_HAMMING) {}\r
1486 };\r
1487 \r
1488 ////////////////////////////////// CascadeClassifier_GPU //////////////////////////////////////////\r
1489 // The cascade classifier class for object detection: supports old haar and new lbp xlm formats and nvbin for haar cascades olny.\r
1490 class CV_EXPORTS CascadeClassifier_GPU\r
1491 {\r
1492 public:\r
1493     CascadeClassifier_GPU();\r
1494     CascadeClassifier_GPU(const std::string& filename);\r
1495     ~CascadeClassifier_GPU();\r
1496 \r
1497     bool empty() const;\r
1498     bool load(const std::string& filename);\r
1499     void release();\r
1500 \r
1501     /* returns number of detected objects */\r
1502     int detectMultiScale(const GpuMat& image, GpuMat& objectsBuf, double scaleFactor = 1.2, int minNeighbors = 4, Size minSize = Size());\r
1503 \r
1504     bool findLargestObject;\r
1505     bool visualizeInPlace;\r
1506 \r
1507     Size getClassifierSize() const;\r
1508 \r
1509 private:\r
1510     struct CascadeClassifierImpl;\r
1511     CascadeClassifierImpl* impl;\r
1512     struct HaarCascade;\r
1513     struct LbpCascade;\r
1514     friend class CascadeClassifier_GPU_LBP;\r
1515 \r
1516 public:\r
1517     int detectMultiScale(const GpuMat& image, GpuMat& objectsBuf, Size maxObjectSize, Size minSize = Size(), double scaleFactor = 1.1, int minNeighbors = 4);\r
1518 };\r
1519 \r
1520 ////////////////////////////////// SURF //////////////////////////////////////////\r
1521 \r
1522 class CV_EXPORTS SURF_GPU\r
1523 {\r
1524 public:\r
1525     enum KeypointLayout\r
1526     {\r
1527         X_ROW = 0,\r
1528         Y_ROW,\r
1529         LAPLACIAN_ROW,\r
1530         OCTAVE_ROW,\r
1531         SIZE_ROW,\r
1532         ANGLE_ROW,\r
1533         HESSIAN_ROW,\r
1534         ROWS_COUNT\r
1535     };\r
1536 \r
1537     //! the default constructor\r
1538     SURF_GPU();\r
1539     //! the full constructor taking all the necessary parameters\r
1540     explicit SURF_GPU(double _hessianThreshold, int _nOctaves=4,\r
1541          int _nOctaveLayers=2, bool _extended=false, float _keypointsRatio=0.01f, bool _upright = false);\r
1542 \r
1543     //! returns the descriptor size in float's (64 or 128)\r
1544     int descriptorSize() const;\r
1545 \r
1546     //! upload host keypoints to device memory\r
1547     static void uploadKeypoints(const vector<KeyPoint>& keypoints, GpuMat& keypointsGPU);\r
1548     //! download keypoints from device to host memory\r
1549     static void downloadKeypoints(const GpuMat& keypointsGPU, vector<KeyPoint>& keypoints);\r
1550 \r
1551     //! download descriptors from device to host memory\r
1552     static void downloadDescriptors(const GpuMat& descriptorsGPU, vector<float>& descriptors);\r
1553 \r
1554     //! finds the keypoints using fast hessian detector used in SURF\r
1555     //! supports CV_8UC1 images\r
1556     //! keypoints will have nFeature cols and 6 rows\r
1557     //! keypoints.ptr<float>(X_ROW)[i] will contain x coordinate of i'th feature\r
1558     //! keypoints.ptr<float>(Y_ROW)[i] will contain y coordinate of i'th feature\r
1559     //! keypoints.ptr<float>(LAPLACIAN_ROW)[i] will contain laplacian sign of i'th feature\r
1560     //! keypoints.ptr<float>(OCTAVE_ROW)[i] will contain octave of i'th feature\r
1561     //! keypoints.ptr<float>(SIZE_ROW)[i] will contain size of i'th feature\r
1562     //! keypoints.ptr<float>(ANGLE_ROW)[i] will contain orientation of i'th feature\r
1563     //! keypoints.ptr<float>(HESSIAN_ROW)[i] will contain response of i'th feature\r
1564     void operator()(const GpuMat& img, const GpuMat& mask, GpuMat& keypoints);\r
1565     //! finds the keypoints and computes their descriptors.\r
1566     //! Optionally it can compute descriptors for the user-provided keypoints and recompute keypoints direction\r
1567     void operator()(const GpuMat& img, const GpuMat& mask, GpuMat& keypoints, GpuMat& descriptors,\r
1568         bool useProvidedKeypoints = false);\r
1569 \r
1570     void operator()(const GpuMat& img, const GpuMat& mask, std::vector<KeyPoint>& keypoints);\r
1571     void operator()(const GpuMat& img, const GpuMat& mask, std::vector<KeyPoint>& keypoints, GpuMat& descriptors,\r
1572         bool useProvidedKeypoints = false);\r
1573 \r
1574     void operator()(const GpuMat& img, const GpuMat& mask, std::vector<KeyPoint>& keypoints, std::vector<float>& descriptors,\r
1575         bool useProvidedKeypoints = false);\r
1576 \r
1577     void releaseMemory();\r
1578 \r
1579     // SURF parameters\r
1580     double hessianThreshold;\r
1581     int nOctaves;\r
1582     int nOctaveLayers;\r
1583     bool extended;\r
1584     bool upright;\r
1585 \r
1586     //! max keypoints = min(keypointsRatio * img.size().area(), 65535)\r
1587     float keypointsRatio;\r
1588 \r
1589     GpuMat sum, mask1, maskSum, intBuffer;\r
1590 \r
1591     GpuMat det, trace;\r
1592 \r
1593     GpuMat maxPosBuffer;\r
1594 };\r
1595 \r
1596 ////////////////////////////////// FAST //////////////////////////////////////////\r
1597 \r
1598 class CV_EXPORTS FAST_GPU\r
1599 {\r
1600 public:\r
1601     enum\r
1602     {\r
1603         LOCATION_ROW = 0,\r
1604         RESPONSE_ROW,\r
1605         ROWS_COUNT\r
1606     };\r
1607 \r
1608     // all features have same size\r
1609     static const int FEATURE_SIZE = 7;\r
1610 \r
1611     explicit FAST_GPU(int threshold, bool nonmaxSupression = true, double keypointsRatio = 0.05);\r
1612 \r
1613     //! finds the keypoints using FAST detector\r
1614     //! supports only CV_8UC1 images\r
1615     void operator ()(const GpuMat& image, const GpuMat& mask, GpuMat& keypoints);\r
1616     void operator ()(const GpuMat& image, const GpuMat& mask, std::vector<KeyPoint>& keypoints);\r
1617 \r
1618     //! download keypoints from device to host memory\r
1619     static void downloadKeypoints(const GpuMat& d_keypoints, std::vector<KeyPoint>& keypoints);\r
1620 \r
1621     //! convert keypoints to KeyPoint vector\r
1622     static void convertKeypoints(const Mat& h_keypoints, std::vector<KeyPoint>& keypoints);\r
1623 \r
1624     //! release temporary buffer's memory\r
1625     void release();\r
1626 \r
1627     bool nonmaxSupression;\r
1628 \r
1629     int threshold;\r
1630 \r
1631     //! max keypoints = keypointsRatio * img.size().area()\r
1632     double keypointsRatio;\r
1633 \r
1634     //! find keypoints and compute it's response if nonmaxSupression is true\r
1635     //! return count of detected keypoints\r
1636     int calcKeyPointsLocation(const GpuMat& image, const GpuMat& mask);\r
1637 \r
1638     //! get final array of keypoints\r
1639     //! performs nonmax supression if needed\r
1640     //! return final count of keypoints\r
1641     int getKeyPoints(GpuMat& keypoints);\r
1642 \r
1643 private:\r
1644     GpuMat kpLoc_;\r
1645     int count_;\r
1646 \r
1647     GpuMat score_;\r
1648 \r
1649     GpuMat d_keypoints_;\r
1650 };\r
1651 \r
1652 ////////////////////////////////// ORB //////////////////////////////////////////\r
1653 \r
1654 class CV_EXPORTS ORB_GPU\r
1655 {\r
1656 public:\r
1657     enum\r
1658     {\r
1659         X_ROW = 0,\r
1660         Y_ROW,\r
1661         RESPONSE_ROW,\r
1662         ANGLE_ROW,\r
1663         OCTAVE_ROW,\r
1664         SIZE_ROW,\r
1665         ROWS_COUNT\r
1666     };\r
1667 \r
1668     enum\r
1669     {\r
1670         DEFAULT_FAST_THRESHOLD = 20\r
1671     };\r
1672 \r
1673     //! Constructor\r
1674     explicit ORB_GPU(int nFeatures = 500, float scaleFactor = 1.2f, int nLevels = 8, int edgeThreshold = 31,\r
1675                      int firstLevel = 0, int WTA_K = 2, int scoreType = 0, int patchSize = 31);\r
1676 \r
1677     //! Compute the ORB features on an image\r
1678     //! image - the image to compute the features (supports only CV_8UC1 images)\r
1679     //! mask - the mask to apply\r
1680     //! keypoints - the resulting keypoints\r
1681     void operator()(const GpuMat& image, const GpuMat& mask, std::vector<KeyPoint>& keypoints);\r
1682     void operator()(const GpuMat& image, const GpuMat& mask, GpuMat& keypoints);\r
1683 \r
1684     //! Compute the ORB features and descriptors on an image\r
1685     //! image - the image to compute the features (supports only CV_8UC1 images)\r
1686     //! mask - the mask to apply\r
1687     //! keypoints - the resulting keypoints\r
1688     //! descriptors - descriptors array\r
1689     void operator()(const GpuMat& image, const GpuMat& mask, std::vector<KeyPoint>& keypoints, GpuMat& descriptors);\r
1690     void operator()(const GpuMat& image, const GpuMat& mask, GpuMat& keypoints, GpuMat& descriptors);\r
1691 \r
1692     //! download keypoints from device to host memory\r
1693     static void downloadKeyPoints(GpuMat& d_keypoints, std::vector<KeyPoint>& keypoints);\r
1694     //! convert keypoints to KeyPoint vector\r
1695     static void convertKeyPoints(Mat& d_keypoints, std::vector<KeyPoint>& keypoints);\r
1696 \r
1697     //! returns the descriptor size in bytes\r
1698     inline int descriptorSize() const { return kBytes; }\r
1699 \r
1700     inline void setFastParams(int threshold, bool nonmaxSupression = true)\r
1701     {\r
1702         fastDetector_.threshold = threshold;\r
1703         fastDetector_.nonmaxSupression = nonmaxSupression;\r
1704     }\r
1705 \r
1706     //! release temporary buffer's memory\r
1707     void release();\r
1708 \r
1709     //! if true, image will be blurred before descriptors calculation\r
1710     bool blurForDescriptor;\r
1711 \r
1712 private:\r
1713     enum { kBytes = 32 };\r
1714 \r
1715     void buildScalePyramids(const GpuMat& image, const GpuMat& mask);\r
1716 \r
1717     void computeKeyPointsPyramid();\r
1718 \r
1719     void computeDescriptors(GpuMat& descriptors);\r
1720 \r
1721     void mergeKeyPoints(GpuMat& keypoints);\r
1722 \r
1723     int nFeatures_;\r
1724     float scaleFactor_;\r
1725     int nLevels_;\r
1726     int edgeThreshold_;\r
1727     int firstLevel_;\r
1728     int WTA_K_;\r
1729     int scoreType_;\r
1730     int patchSize_;\r
1731 \r
1732     // The number of desired features per scale\r
1733     std::vector<size_t> n_features_per_level_;\r
1734 \r
1735     // Points to compute BRIEF descriptors from\r
1736     GpuMat pattern_;\r
1737 \r
1738     std::vector<GpuMat> imagePyr_;\r
1739     std::vector<GpuMat> maskPyr_;\r
1740 \r
1741     GpuMat buf_;\r
1742 \r
1743     std::vector<GpuMat> keyPointsPyr_;\r
1744     std::vector<int> keyPointsCount_;\r
1745 \r
1746     FAST_GPU fastDetector_;\r
1747 \r
1748     Ptr<FilterEngine_GPU> blurFilter;\r
1749 \r
1750     GpuMat d_keypoints_;\r
1751 };\r
1752 \r
1753 ////////////////////////////////// Optical Flow //////////////////////////////////////////\r
1754 \r
1755 class CV_EXPORTS BroxOpticalFlow\r
1756 {\r
1757 public:\r
1758     BroxOpticalFlow(float alpha_, float gamma_, float scale_factor_, int inner_iterations_, int outer_iterations_, int solver_iterations_) :\r
1759         alpha(alpha_), gamma(gamma_), scale_factor(scale_factor_),\r
1760         inner_iterations(inner_iterations_), outer_iterations(outer_iterations_), solver_iterations(solver_iterations_)\r
1761     {\r
1762     }\r
1763 \r
1764     //! Compute optical flow\r
1765     //! frame0 - source frame (supports only CV_32FC1 type)\r
1766     //! frame1 - frame to track (with the same size and type as frame0)\r
1767     //! u      - flow horizontal component (along x axis)\r
1768     //! v      - flow vertical component (along y axis)\r
1769     void operator ()(const GpuMat& frame0, const GpuMat& frame1, GpuMat& u, GpuMat& v, Stream& stream = Stream::Null());\r
1770 \r
1771     //! flow smoothness\r
1772     float alpha;\r
1773 \r
1774     //! gradient constancy importance\r
1775     float gamma;\r
1776 \r
1777     //! pyramid scale factor\r
1778     float scale_factor;\r
1779 \r
1780     //! number of lagged non-linearity iterations (inner loop)\r
1781     int inner_iterations;\r
1782 \r
1783     //! number of warping iterations (number of pyramid levels)\r
1784     int outer_iterations;\r
1785 \r
1786     //! number of linear system solver iterations\r
1787     int solver_iterations;\r
1788 \r
1789     GpuMat buf;\r
1790 };\r
1791 \r
1792 class CV_EXPORTS GoodFeaturesToTrackDetector_GPU\r
1793 {\r
1794 public:\r
1795     explicit GoodFeaturesToTrackDetector_GPU(int maxCorners = 1000, double qualityLevel = 0.01, double minDistance = 0.0,\r
1796         int blockSize = 3, bool useHarrisDetector = false, double harrisK = 0.04);\r
1797 \r
1798     //! return 1 rows matrix with CV_32FC2 type\r
1799     void operator ()(const GpuMat& image, GpuMat& corners, const GpuMat& mask = GpuMat());\r
1800 \r
1801     int maxCorners;\r
1802     double qualityLevel;\r
1803     double minDistance;\r
1804 \r
1805     int blockSize;\r
1806     bool useHarrisDetector;\r
1807     double harrisK;\r
1808 \r
1809     void releaseMemory()\r
1810     {\r
1811         Dx_.release();\r
1812         Dy_.release();\r
1813         buf_.release();\r
1814         eig_.release();\r
1815         minMaxbuf_.release();\r
1816         tmpCorners_.release();\r
1817     }\r
1818 \r
1819 private:\r
1820     GpuMat Dx_;\r
1821     GpuMat Dy_;\r
1822     GpuMat buf_;\r
1823     GpuMat eig_;\r
1824     GpuMat minMaxbuf_;\r
1825     GpuMat tmpCorners_;\r
1826 };\r
1827 \r
1828 inline GoodFeaturesToTrackDetector_GPU::GoodFeaturesToTrackDetector_GPU(int maxCorners_, double qualityLevel_, double minDistance_,\r
1829         int blockSize_, bool useHarrisDetector_, double harrisK_)\r
1830 {\r
1831     maxCorners = maxCorners_;\r
1832     qualityLevel = qualityLevel_;\r
1833     minDistance = minDistance_;\r
1834     blockSize = blockSize_;\r
1835     useHarrisDetector = useHarrisDetector_;\r
1836     harrisK = harrisK_;\r
1837 }\r
1838 \r
1839 \r
1840 class CV_EXPORTS PyrLKOpticalFlow\r
1841 {\r
1842 public:\r
1843     PyrLKOpticalFlow();\r
1844 \r
1845     void sparse(const GpuMat& prevImg, const GpuMat& nextImg, const GpuMat& prevPts, GpuMat& nextPts,\r
1846         GpuMat& status, GpuMat* err = 0);\r
1847 \r
1848     void dense(const GpuMat& prevImg, const GpuMat& nextImg, GpuMat& u, GpuMat& v, GpuMat* err = 0);\r
1849 \r
1850     void releaseMemory();\r
1851 \r
1852     Size winSize;\r
1853     int maxLevel;\r
1854     int iters;\r
1855     bool useInitialFlow;\r
1856 \r
1857 private:\r
1858     vector<GpuMat> prevPyr_;\r
1859     vector<GpuMat> nextPyr_;\r
1860 \r
1861     GpuMat buf_;\r
1862 \r
1863     GpuMat uPyr_[2];\r
1864     GpuMat vPyr_[2];\r
1865 \r
1866     bool isDeviceArch11_;\r
1867 };\r
1868 \r
1869 \r
1870 class CV_EXPORTS FarnebackOpticalFlow\r
1871 {\r
1872 public:\r
1873     FarnebackOpticalFlow()\r
1874     {\r
1875         numLevels = 5;\r
1876         pyrScale = 0.5;\r
1877         fastPyramids = false;\r
1878         winSize = 13;\r
1879         numIters = 10;\r
1880         polyN = 5;\r
1881         polySigma = 1.1;\r
1882         flags = 0;\r
1883         isDeviceArch11_ = !DeviceInfo().supports(FEATURE_SET_COMPUTE_12);\r
1884     }\r
1885 \r
1886     int numLevels;\r
1887     double pyrScale;\r
1888     bool fastPyramids;\r
1889     int winSize;\r
1890     int numIters;\r
1891     int polyN;\r
1892     double polySigma;\r
1893     int flags;\r
1894 \r
1895     void operator ()(const GpuMat &frame0, const GpuMat &frame1, GpuMat &flowx, GpuMat &flowy, Stream &s = Stream::Null());\r
1896 \r
1897     void releaseMemory()\r
1898     {\r
1899         frames_[0].release();\r
1900         frames_[1].release();\r
1901         pyrLevel_[0].release();\r
1902         pyrLevel_[1].release();\r
1903         M_.release();\r
1904         bufM_.release();\r
1905         R_[0].release();\r
1906         R_[1].release();\r
1907         blurredFrame_[0].release();\r
1908         blurredFrame_[1].release();\r
1909         pyramid0_.clear();\r
1910         pyramid1_.clear();\r
1911     }\r
1912 \r
1913 private:\r
1914     void prepareGaussian(\r
1915             int n, double sigma, float *g, float *xg, float *xxg,\r
1916             double &ig11, double &ig03, double &ig33, double &ig55);\r
1917 \r
1918     void setPolynomialExpansionConsts(int n, double sigma);\r
1919 \r
1920     void updateFlow_boxFilter(\r
1921             const GpuMat& R0, const GpuMat& R1, GpuMat& flowx, GpuMat &flowy,\r
1922             GpuMat& M, GpuMat &bufM, int blockSize, bool updateMatrices, Stream streams[]);\r
1923 \r
1924     void updateFlow_gaussianBlur(\r
1925             const GpuMat& R0, const GpuMat& R1, GpuMat& flowx, GpuMat& flowy,\r
1926             GpuMat& M, GpuMat &bufM, int blockSize, bool updateMatrices, Stream streams[]);\r
1927 \r
1928     GpuMat frames_[2];\r
1929     GpuMat pyrLevel_[2], M_, bufM_, R_[2], blurredFrame_[2];\r
1930     std::vector<GpuMat> pyramid0_, pyramid1_;\r
1931 \r
1932     bool isDeviceArch11_;\r
1933 };\r
1934 \r
1935 \r
1936 //! Interpolate frames (images) using provided optical flow (displacement field).\r
1937 //! frame0   - frame 0 (32-bit floating point images, single channel)\r
1938 //! frame1   - frame 1 (the same type and size)\r
1939 //! fu       - forward horizontal displacement\r
1940 //! fv       - forward vertical displacement\r
1941 //! bu       - backward horizontal displacement\r
1942 //! bv       - backward vertical displacement\r
1943 //! pos      - new frame position\r
1944 //! newFrame - new frame\r
1945 //! buf      - temporary buffer, will have width x 6*height size, CV_32FC1 type and contain 6 GpuMat;\r
1946 //!            occlusion masks            0, occlusion masks            1,\r
1947 //!            interpolated forward flow  0, interpolated forward flow  1,\r
1948 //!            interpolated backward flow 0, interpolated backward flow 1\r
1949 //!\r
1950 CV_EXPORTS void interpolateFrames(const GpuMat& frame0, const GpuMat& frame1,\r
1951                                   const GpuMat& fu, const GpuMat& fv,\r
1952                                   const GpuMat& bu, const GpuMat& bv,\r
1953                                   float pos, GpuMat& newFrame, GpuMat& buf,\r
1954                                   Stream& stream = Stream::Null());\r
1955 \r
1956 CV_EXPORTS void createOpticalFlowNeedleMap(const GpuMat& u, const GpuMat& v, GpuMat& vertex, GpuMat& colors);\r
1957 \r
1958 \r
1959 //////////////////////// Background/foreground segmentation ////////////////////////\r
1960 \r
1961 // Foreground Object Detection from Videos Containing Complex Background.\r
1962 // Liyuan Li, Weimin Huang, Irene Y.H. Gu, and Qi Tian.\r
1963 // ACM MM2003 9p\r
1964 class CV_EXPORTS FGDStatModel\r
1965 {\r
1966 public:\r
1967     struct CV_EXPORTS Params\r
1968     {\r
1969         int Lc;  // Quantized levels per 'color' component. Power of two, typically 32, 64 or 128.\r
1970         int N1c; // Number of color vectors used to model normal background color variation at a given pixel.\r
1971         int N2c; // Number of color vectors retained at given pixel.  Must be > N1c, typically ~ 5/3 of N1c.\r
1972         // Used to allow the first N1c vectors to adapt over time to changing background.\r
1973 \r
1974         int Lcc;  // Quantized levels per 'color co-occurrence' component.  Power of two, typically 16, 32 or 64.\r
1975         int N1cc; // Number of color co-occurrence vectors used to model normal background color variation at a given pixel.\r
1976         int N2cc; // Number of color co-occurrence vectors retained at given pixel.  Must be > N1cc, typically ~ 5/3 of N1cc.\r
1977         // Used to allow the first N1cc vectors to adapt over time to changing background.\r
1978 \r
1979         bool is_obj_without_holes; // If TRUE we ignore holes within foreground blobs. Defaults to TRUE.\r
1980         int perform_morphing;     // Number of erode-dilate-erode foreground-blob cleanup iterations.\r
1981         // These erase one-pixel junk blobs and merge almost-touching blobs. Default value is 1.\r
1982 \r
1983         float alpha1; // How quickly we forget old background pixel values seen. Typically set to 0.1.\r
1984         float alpha2; // "Controls speed of feature learning". Depends on T. Typical value circa 0.005.\r
1985         float alpha3; // Alternate to alpha2, used (e.g.) for quicker initial convergence. Typical value 0.1.\r
1986 \r
1987         float delta;   // Affects color and color co-occurrence quantization, typically set to 2.\r
1988         float T;       // A percentage value which determines when new features can be recognized as new background. (Typically 0.9).\r
1989         float minArea; // Discard foreground blobs whose bounding box is smaller than this threshold.\r
1990 \r
1991         // default Params\r
1992         Params();\r
1993     };\r
1994 \r
1995     // out_cn - channels count in output result (can be 3 or 4)\r
1996     // 4-channels require more memory, but a bit faster\r
1997     explicit FGDStatModel(int out_cn = 3);\r
1998     explicit FGDStatModel(const cv::gpu::GpuMat& firstFrame, const Params& params = Params(), int out_cn = 3);\r
1999 \r
2000     ~FGDStatModel();\r
2001 \r
2002     void create(const cv::gpu::GpuMat& firstFrame, const Params& params = Params());\r
2003     void release();\r
2004 \r
2005     int update(const cv::gpu::GpuMat& curFrame);\r
2006 \r
2007     //8UC3 or 8UC4 reference background image\r
2008     cv::gpu::GpuMat background;\r
2009 \r
2010     //8UC1 foreground image\r
2011     cv::gpu::GpuMat foreground;\r
2012 \r
2013     std::vector< std::vector<cv::Point> > foreground_regions;\r
2014 \r
2015 private:\r
2016     FGDStatModel(const FGDStatModel&);\r
2017     FGDStatModel& operator=(const FGDStatModel&);\r
2018 \r
2019     class Impl;\r
2020     std::auto_ptr<Impl> impl_;\r
2021 };\r
2022 \r
2023 /*!\r
2024  Gaussian Mixture-based Backbround/Foreground Segmentation Algorithm\r
2025 \r
2026  The class implements the following algorithm:\r
2027  "An improved adaptive background mixture model for real-time tracking with shadow detection"\r
2028  P. KadewTraKuPong and R. Bowden,\r
2029  Proc. 2nd European Workshp on Advanced Video-Based Surveillance Systems, 2001."\r
2030  http://personal.ee.surrey.ac.uk/Personal/R.Bowden/publications/avbs01/avbs01.pdf\r
2031 */\r
2032 class CV_EXPORTS MOG_GPU\r
2033 {\r
2034 public:\r
2035     //! the default constructor\r
2036     MOG_GPU(int nmixtures = -1);\r
2037 \r
2038     //! re-initiaization method\r
2039     void initialize(Size frameSize, int frameType);\r
2040 \r
2041     //! the update operator\r
2042     void operator()(const GpuMat& frame, GpuMat& fgmask, float learningRate = 0.0f, Stream& stream = Stream::Null());\r
2043 \r
2044     //! computes a background image which are the mean of all background gaussians\r
2045     void getBackgroundImage(GpuMat& backgroundImage, Stream& stream = Stream::Null()) const;\r
2046 \r
2047     //! releases all inner buffers\r
2048     void release();\r
2049 \r
2050     int history;\r
2051     float varThreshold;\r
2052     float backgroundRatio;\r
2053     float noiseSigma;\r
2054 \r
2055 private:\r
2056     int nmixtures_;\r
2057 \r
2058     Size frameSize_;\r
2059     int frameType_;\r
2060     int nframes_;\r
2061 \r
2062     GpuMat weight_;\r
2063     GpuMat sortKey_;\r
2064     GpuMat mean_;\r
2065     GpuMat var_;\r
2066 };\r
2067 \r
2068 /*!\r
2069  The class implements the following algorithm:\r
2070  "Improved adaptive Gausian mixture model for background subtraction"\r
2071  Z.Zivkovic\r
2072  International Conference Pattern Recognition, UK, August, 2004.\r
2073  http://www.zoranz.net/Publications/zivkovic2004ICPR.pdf\r
2074 */\r
2075 class CV_EXPORTS MOG2_GPU\r
2076 {\r
2077 public:\r
2078     //! the default constructor\r
2079     MOG2_GPU(int nmixtures = -1);\r
2080 \r
2081     //! re-initiaization method\r
2082     void initialize(Size frameSize, int frameType);\r
2083 \r
2084     //! the update operator\r
2085     void operator()(const GpuMat& frame, GpuMat& fgmask, float learningRate = -1.0f, Stream& stream = Stream::Null());\r
2086 \r
2087     //! computes a background image which are the mean of all background gaussians\r
2088     void getBackgroundImage(GpuMat& backgroundImage, Stream& stream = Stream::Null()) const;\r
2089 \r
2090     //! releases all inner buffers\r
2091     void release();\r
2092 \r
2093     // parameters\r
2094     // you should call initialize after parameters changes\r
2095 \r
2096     int history;\r
2097 \r
2098     //! here it is the maximum allowed number of mixture components.\r
2099     //! Actual number is determined dynamically per pixel\r
2100     float varThreshold;\r
2101     // threshold on the squared Mahalanobis distance to decide if it is well described\r
2102     // by the background model or not. Related to Cthr from the paper.\r
2103     // This does not influence the update of the background. A typical value could be 4 sigma\r
2104     // and that is varThreshold=4*4=16; Corresponds to Tb in the paper.\r
2105 \r
2106     /////////////////////////\r
2107     // less important parameters - things you might change but be carefull\r
2108     ////////////////////////\r
2109 \r
2110     float backgroundRatio;\r
2111     // corresponds to fTB=1-cf from the paper\r
2112     // TB - threshold when the component becomes significant enough to be included into\r
2113     // the background model. It is the TB=1-cf from the paper. So I use cf=0.1 => TB=0.\r
2114     // For alpha=0.001 it means that the mode should exist for approximately 105 frames before\r
2115     // it is considered foreground\r
2116     // float noiseSigma;\r
2117     float varThresholdGen;\r
2118 \r
2119     //correspondts to Tg - threshold on the squared Mahalan. dist. to decide\r
2120     //when a sample is close to the existing components. If it is not close\r
2121     //to any a new component will be generated. I use 3 sigma => Tg=3*3=9.\r
2122     //Smaller Tg leads to more generated components and higher Tg might make\r
2123     //lead to small number of components but they can grow too large\r
2124     float fVarInit;\r
2125     float fVarMin;\r
2126     float fVarMax;\r
2127 \r
2128     //initial variance  for the newly generated components.\r
2129     //It will will influence the speed of adaptation. A good guess should be made.\r
2130     //A simple way is to estimate the typical standard deviation from the images.\r
2131     //I used here 10 as a reasonable value\r
2132     // min and max can be used to further control the variance\r
2133     float fCT; //CT - complexity reduction prior\r
2134     //this is related to the number of samples needed to accept that a component\r
2135     //actually exists. We use CT=0.05 of all the samples. By setting CT=0 you get\r
2136     //the standard Stauffer&Grimson algorithm (maybe not exact but very similar)\r
2137 \r
2138     //shadow detection parameters\r
2139     bool bShadowDetection; //default 1 - do shadow detection\r
2140     unsigned char nShadowDetection; //do shadow detection - insert this value as the detection result - 127 default value\r
2141     float fTau;\r
2142     // Tau - shadow threshold. The shadow is detected if the pixel is darker\r
2143     //version of the background. Tau is a threshold on how much darker the shadow can be.\r
2144     //Tau= 0.5 means that if pixel is more than 2 times darker then it is not shadow\r
2145     //See: Prati,Mikic,Trivedi,Cucchiarra,"Detecting Moving Shadows...",IEEE PAMI,2003.\r
2146 \r
2147 private:\r
2148     int nmixtures_;\r
2149 \r
2150     Size frameSize_;\r
2151     int frameType_;\r
2152     int nframes_;\r
2153 \r
2154     GpuMat weight_;\r
2155     GpuMat variance_;\r
2156     GpuMat mean_;\r
2157 \r
2158     GpuMat bgmodelUsedModes_; //keep track of number of modes per pixel\r
2159 };\r
2160 \r
2161 /*!\r
2162  * The class implements the following algorithm:\r
2163  * "ViBe: A universal background subtraction algorithm for video sequences"\r
2164  * O. Barnich and M. Van D Roogenbroeck\r
2165  * IEEE Transactions on Image Processing, 20(6) :1709-1724, June 2011\r
2166  */\r
2167 class CV_EXPORTS VIBE_GPU\r
2168 {\r
2169 public:\r
2170     //! the default constructor\r
2171     explicit VIBE_GPU(unsigned long rngSeed = 1234567);\r
2172 \r
2173     //! re-initiaization method\r
2174     void initialize(const GpuMat& firstFrame, Stream& stream = Stream::Null());\r
2175 \r
2176     //! the update operator\r
2177     void operator()(const GpuMat& frame, GpuMat& fgmask, Stream& stream = Stream::Null());\r
2178 \r
2179     //! releases all inner buffers\r
2180     void release();\r
2181 \r
2182     int nbSamples;         // number of samples per pixel\r
2183     int reqMatches;        // #_min\r
2184     int radius;            // R\r
2185     int subsamplingFactor; // amount of random subsampling\r
2186 \r
2187 private:\r
2188     Size frameSize_;\r
2189 \r
2190     unsigned long rngSeed_;\r
2191     GpuMat randStates_;\r
2192 \r
2193     GpuMat samples_;\r
2194 };\r
2195 \r
2196 /**\r
2197  * Background Subtractor module. Takes a series of images and returns a sequence of mask (8UC1)\r
2198  * images of the same size, where 255 indicates Foreground and 0 represents Background.\r
2199  * This class implements an algorithm described in "Visual Tracking of Human Visitors under\r
2200  * Variable-Lighting Conditions for a Responsive Audio Art Installation," A. Godbehere,\r
2201  * A. Matsukawa, K. Goldberg, American Control Conference, Montreal, June 2012.\r
2202  */\r
2203 class CV_EXPORTS GMG_GPU\r
2204 {\r
2205 public:\r
2206     GMG_GPU();\r
2207 \r
2208     /**\r
2209      * Validate parameters and set up data structures for appropriate frame size.\r
2210      * @param frameSize Input frame size\r
2211      * @param min       Minimum value taken on by pixels in image sequence. Usually 0\r
2212      * @param max       Maximum value taken on by pixels in image sequence. e.g. 1.0 or 255\r
2213      */\r
2214     void initialize(Size frameSize, float min = 0.0f, float max = 255.0f);\r
2215 \r
2216     /**\r
2217      * Performs single-frame background subtraction and builds up a statistical background image\r
2218      * model.\r
2219      * @param frame        Input frame\r
2220      * @param fgmask       Output mask image representing foreground and background pixels\r
2221      * @param stream       Stream for the asynchronous version\r
2222      */\r
2223     void operator ()(const GpuMat& frame, GpuMat& fgmask, float learningRate = -1.0f, Stream& stream = Stream::Null());\r
2224 \r
2225     //! Releases all inner buffers\r
2226     void release();\r
2227 \r
2228     //! Total number of distinct colors to maintain in histogram.\r
2229     int maxFeatures;\r
2230 \r
2231     //! Set between 0.0 and 1.0, determines how quickly features are "forgotten" from histograms.\r
2232     float learningRate;\r
2233 \r
2234     //! Number of frames of video to use to initialize histograms.\r
2235     int numInitializationFrames;\r
2236 \r
2237     //! Number of discrete levels in each channel to be used in histograms.\r
2238     int quantizationLevels;\r
2239 \r
2240     //! Prior probability that any given pixel is a background pixel. A sensitivity parameter.\r
2241     float backgroundPrior;\r
2242 \r
2243     //! Value above which pixel is determined to be FG.\r
2244     float decisionThreshold;\r
2245 \r
2246     //! Smoothing radius, in pixels, for cleaning up FG image.\r
2247     int smoothingRadius;\r
2248 \r
2249     //! Perform background model update.\r
2250     bool updateBackgroundModel;\r
2251 \r
2252 private:\r
2253     float maxVal_, minVal_;\r
2254 \r
2255     Size frameSize_;\r
2256 \r
2257     int frameNum_;\r
2258 \r
2259     GpuMat nfeatures_;\r
2260     GpuMat colors_;\r
2261     GpuMat weights_;\r
2262 \r
2263     Ptr<FilterEngine_GPU> boxFilter_;\r
2264     GpuMat buf_;\r
2265 };\r
2266 \r
2267 ////////////////////////////////// Video Encoding //////////////////////////////////\r
2268 \r
2269 // Works only under Windows\r
2270 // Supports olny H264 video codec and AVI files\r
2271 class CV_EXPORTS VideoWriter_GPU\r
2272 {\r
2273 public:\r
2274     struct EncoderParams;\r
2275 \r
2276     // Callbacks for video encoder, use it if you want to work with raw video stream\r
2277     class EncoderCallBack;\r
2278 \r
2279     enum SurfaceFormat\r
2280     {\r
2281         SF_UYVY = 0,\r
2282         SF_YUY2,\r
2283         SF_YV12,\r
2284         SF_NV12,\r
2285         SF_IYUV,\r
2286         SF_BGR,\r
2287         SF_GRAY = SF_BGR\r
2288     };\r
2289 \r
2290     VideoWriter_GPU();\r
2291     VideoWriter_GPU(const std::string& fileName, cv::Size frameSize, double fps, SurfaceFormat format = SF_BGR);\r
2292     VideoWriter_GPU(const std::string& fileName, cv::Size frameSize, double fps, const EncoderParams& params, SurfaceFormat format = SF_BGR);\r
2293     VideoWriter_GPU(const cv::Ptr<EncoderCallBack>& encoderCallback, cv::Size frameSize, double fps, SurfaceFormat format = SF_BGR);\r
2294     VideoWriter_GPU(const cv::Ptr<EncoderCallBack>& encoderCallback, cv::Size frameSize, double fps, const EncoderParams& params, SurfaceFormat format = SF_BGR);\r
2295     ~VideoWriter_GPU();\r
2296 \r
2297     // all methods throws cv::Exception if error occurs\r
2298     void open(const std::string& fileName, cv::Size frameSize, double fps, SurfaceFormat format = SF_BGR);\r
2299     void open(const std::string& fileName, cv::Size frameSize, double fps, const EncoderParams& params, SurfaceFormat format = SF_BGR);\r
2300     void open(const cv::Ptr<EncoderCallBack>& encoderCallback, cv::Size frameSize, double fps, SurfaceFormat format = SF_BGR);\r
2301     void open(const cv::Ptr<EncoderCallBack>& encoderCallback, cv::Size frameSize, double fps, const EncoderParams& params, SurfaceFormat format = SF_BGR);\r
2302 \r
2303     bool isOpened() const;\r
2304     void close();\r
2305 \r
2306     void write(const cv::gpu::GpuMat& image, bool lastFrame = false);\r
2307 \r
2308     struct CV_EXPORTS EncoderParams\r
2309     {\r
2310         int       P_Interval;      //    NVVE_P_INTERVAL,\r
2311         int       IDR_Period;      //    NVVE_IDR_PERIOD,\r
2312         int       DynamicGOP;      //    NVVE_DYNAMIC_GOP,\r
2313         int       RCType;          //    NVVE_RC_TYPE,\r
2314         int       AvgBitrate;      //    NVVE_AVG_BITRATE,\r
2315         int       PeakBitrate;     //    NVVE_PEAK_BITRATE,\r
2316         int       QP_Level_Intra;  //    NVVE_QP_LEVEL_INTRA,\r
2317         int       QP_Level_InterP; //    NVVE_QP_LEVEL_INTER_P,\r
2318         int       QP_Level_InterB; //    NVVE_QP_LEVEL_INTER_B,\r
2319         int       DeblockMode;     //    NVVE_DEBLOCK_MODE,\r
2320         int       ProfileLevel;    //    NVVE_PROFILE_LEVEL,\r
2321         int       ForceIntra;      //    NVVE_FORCE_INTRA,\r
2322         int       ForceIDR;        //    NVVE_FORCE_IDR,\r
2323         int       ClearStat;       //    NVVE_CLEAR_STAT,\r
2324         int       DIMode;          //    NVVE_SET_DEINTERLACE,\r
2325         int       Presets;         //    NVVE_PRESETS,\r
2326         int       DisableCabac;    //    NVVE_DISABLE_CABAC,\r
2327         int       NaluFramingType; //    NVVE_CONFIGURE_NALU_FRAMING_TYPE\r
2328         int       DisableSPSPPS;   //    NVVE_DISABLE_SPS_PPS\r
2329 \r
2330         EncoderParams();\r
2331         explicit EncoderParams(const std::string& configFile);\r
2332 \r
2333         void load(const std::string& configFile);\r
2334         void save(const std::string& configFile) const;\r
2335     };\r
2336 \r
2337     EncoderParams getParams() const;\r
2338 \r
2339     class CV_EXPORTS EncoderCallBack\r
2340     {\r
2341     public:\r
2342         enum PicType\r
2343         {\r
2344             IFRAME = 1,\r
2345             PFRAME = 2,\r
2346             BFRAME = 3\r
2347         };\r
2348 \r
2349         virtual ~EncoderCallBack() {}\r
2350 \r
2351         // callback function to signal the start of bitstream that is to be encoded\r
2352         // must return pointer to buffer\r
2353         virtual uchar* acquireBitStream(int* bufferSize) = 0;\r
2354 \r
2355         // callback function to signal that the encoded bitstream is ready to be written to file\r
2356         virtual void releaseBitStream(unsigned char* data, int size) = 0;\r
2357 \r
2358         // callback function to signal that the encoding operation on the frame has started\r
2359         virtual void onBeginFrame(int frameNumber, PicType picType) = 0;\r
2360 \r
2361         // callback function signals that the encoding operation on the frame has finished\r
2362         virtual void onEndFrame(int frameNumber, PicType picType) = 0;\r
2363     };\r
2364 \r
2365 private:\r
2366     VideoWriter_GPU(const VideoWriter_GPU&);\r
2367     VideoWriter_GPU& operator=(const VideoWriter_GPU&);\r
2368 \r
2369     class Impl;\r
2370     std::auto_ptr<Impl> impl_;\r
2371 };\r
2372 \r
2373 \r
2374 ////////////////////////////////// Video Decoding //////////////////////////////////////////\r
2375 \r
2376 namespace detail\r
2377 {\r
2378     class FrameQueue;\r
2379     class VideoParser;\r
2380 }\r
2381 \r
2382 class CV_EXPORTS VideoReader_GPU\r
2383 {\r
2384 public:\r
2385     enum Codec\r
2386     {\r
2387         MPEG1 = 0,\r
2388         MPEG2,\r
2389         MPEG4,\r
2390         VC1,\r
2391         H264,\r
2392         JPEG,\r
2393         H264_SVC,\r
2394         H264_MVC,\r
2395 \r
2396         Uncompressed_YUV420 = (('I'<<24)|('Y'<<16)|('U'<<8)|('V')),   // Y,U,V (4:2:0)\r
2397         Uncompressed_YV12   = (('Y'<<24)|('V'<<16)|('1'<<8)|('2')),   // Y,V,U (4:2:0)\r
2398         Uncompressed_NV12   = (('N'<<24)|('V'<<16)|('1'<<8)|('2')),   // Y,UV  (4:2:0)\r
2399         Uncompressed_YUYV   = (('Y'<<24)|('U'<<16)|('Y'<<8)|('V')),   // YUYV/YUY2 (4:2:2)\r
2400         Uncompressed_UYVY   = (('U'<<24)|('Y'<<16)|('V'<<8)|('Y')),   // UYVY (4:2:2)\r
2401     };\r
2402 \r
2403     enum ChromaFormat\r
2404     {\r
2405         Monochrome=0,\r
2406         YUV420,\r
2407         YUV422,\r
2408         YUV444,\r
2409     };\r
2410 \r
2411     struct FormatInfo\r
2412     {\r
2413         Codec codec;\r
2414         ChromaFormat chromaFormat;\r
2415         int width;\r
2416         int height;\r
2417     };\r
2418 \r
2419     class VideoSource;\r
2420 \r
2421     VideoReader_GPU();\r
2422     explicit VideoReader_GPU(const std::string& filename);\r
2423     explicit VideoReader_GPU(const cv::Ptr<VideoSource>& source);\r
2424 \r
2425     ~VideoReader_GPU();\r
2426 \r
2427     void open(const std::string& filename);\r
2428     void open(const cv::Ptr<VideoSource>& source);\r
2429     bool isOpened() const;\r
2430 \r
2431     void close();\r
2432 \r
2433     bool read(GpuMat& image);\r
2434 \r
2435     FormatInfo format() const;\r
2436     void dumpFormat(std::ostream& st);\r
2437 \r
2438     class CV_EXPORTS VideoSource\r
2439     {\r
2440     public:\r
2441         VideoSource() : frameQueue_(0), videoParser_(0) {}\r
2442         virtual ~VideoSource() {}\r
2443 \r
2444         virtual FormatInfo format() const = 0;\r
2445         virtual void start() = 0;\r
2446         virtual void stop() = 0;\r
2447         virtual bool isStarted() const = 0;\r
2448         virtual bool hasError() const = 0;\r
2449 \r
2450         void setFrameQueue(detail::FrameQueue* frameQueue) { frameQueue_ = frameQueue; }\r
2451         void setVideoParser(detail::VideoParser* videoParser) { videoParser_ = videoParser; }\r
2452 \r
2453     protected:\r
2454         bool parseVideoData(const uchar* data, size_t size, bool endOfStream = false);\r
2455 \r
2456     private:\r
2457         VideoSource(const VideoSource&);\r
2458         VideoSource& operator =(const VideoSource&);\r
2459 \r
2460         detail::FrameQueue* frameQueue_;\r
2461         detail::VideoParser* videoParser_;\r
2462     };\r
2463 \r
2464 private:\r
2465     VideoReader_GPU(const VideoReader_GPU&);\r
2466     VideoReader_GPU& operator =(const VideoReader_GPU&);\r
2467 \r
2468     class Impl;\r
2469     std::auto_ptr<Impl> impl_;\r
2470 };\r
2471 \r
2472 //! removes points (CV_32FC2, single row matrix) with zero mask value\r
2473 CV_EXPORTS void compactPoints(GpuMat &points0, GpuMat &points1, const GpuMat &mask);\r
2474 \r
2475 CV_EXPORTS void calcWobbleSuppressionMaps(\r
2476         int left, int idx, int right, Size size, const Mat &ml, const Mat &mr,\r
2477         GpuMat &mapx, GpuMat &mapy);\r
2478 \r
2479 } // namespace gpu\r
2480 \r
2481 } // namespace cv\r
2482 \r
2483 #endif /* __OPENCV_GPU_HPP__ */\r