added GPU bilateral filter + tests
[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 ////////////////////////////// Matrix reductions //////////////////////////////\r
858 \r
859 //! computes mean value and standard deviation of all or selected array elements\r
860 //! supports only CV_8UC1 type\r
861 CV_EXPORTS void meanStdDev(const GpuMat& mtx, Scalar& mean, Scalar& stddev);\r
862 //! buffered version\r
863 CV_EXPORTS void meanStdDev(const GpuMat& mtx, Scalar& mean, Scalar& stddev, GpuMat& buf);\r
864 \r
865 //! computes norm of array\r
866 //! supports NORM_INF, NORM_L1, NORM_L2\r
867 //! supports all matrices except 64F\r
868 CV_EXPORTS double norm(const GpuMat& src1, int normType=NORM_L2);\r
869 \r
870 //! computes norm of array\r
871 //! supports NORM_INF, NORM_L1, NORM_L2\r
872 //! supports all matrices except 64F\r
873 CV_EXPORTS double norm(const GpuMat& src1, int normType, GpuMat& buf);\r
874 \r
875 //! computes norm of the difference between two arrays\r
876 //! supports NORM_INF, NORM_L1, NORM_L2\r
877 //! supports only CV_8UC1 type\r
878 CV_EXPORTS double norm(const GpuMat& src1, const GpuMat& src2, int normType=NORM_L2);\r
879 \r
880 //! computes sum of array elements\r
881 //! supports only single channel images\r
882 CV_EXPORTS Scalar sum(const GpuMat& src);\r
883 \r
884 //! computes sum of array elements\r
885 //! supports only single channel images\r
886 CV_EXPORTS Scalar sum(const GpuMat& src, GpuMat& buf);\r
887 \r
888 //! computes sum of array elements absolute values\r
889 //! supports only single channel images\r
890 CV_EXPORTS Scalar absSum(const GpuMat& src);\r
891 \r
892 //! computes sum of array elements absolute values\r
893 //! supports only single channel images\r
894 CV_EXPORTS Scalar absSum(const GpuMat& src, GpuMat& buf);\r
895 \r
896 //! computes squared sum of array elements\r
897 //! supports only single channel images\r
898 CV_EXPORTS Scalar sqrSum(const GpuMat& src);\r
899 \r
900 //! computes squared sum of array elements\r
901 //! supports only single channel images\r
902 CV_EXPORTS Scalar sqrSum(const GpuMat& src, GpuMat& buf);\r
903 \r
904 //! finds global minimum and maximum array elements and returns their values\r
905 CV_EXPORTS void minMax(const GpuMat& src, double* minVal, double* maxVal=0, const GpuMat& mask=GpuMat());\r
906 \r
907 //! finds global minimum and maximum array elements and returns their values\r
908 CV_EXPORTS void minMax(const GpuMat& src, double* minVal, double* maxVal, const GpuMat& mask, GpuMat& buf);\r
909 \r
910 //! finds global minimum and maximum array elements and returns their values with locations\r
911 CV_EXPORTS void minMaxLoc(const GpuMat& src, double* minVal, double* maxVal=0, Point* minLoc=0, Point* maxLoc=0,\r
912                           const GpuMat& mask=GpuMat());\r
913 \r
914 //! finds global minimum and maximum array elements and returns their values with locations\r
915 CV_EXPORTS void minMaxLoc(const GpuMat& src, double* minVal, double* maxVal, Point* minLoc, Point* maxLoc,\r
916                           const GpuMat& mask, GpuMat& valbuf, GpuMat& locbuf);\r
917 \r
918 //! counts non-zero array elements\r
919 CV_EXPORTS int countNonZero(const GpuMat& src);\r
920 \r
921 //! counts non-zero array elements\r
922 CV_EXPORTS int countNonZero(const GpuMat& src, GpuMat& buf);\r
923 \r
924 //! reduces a matrix to a vector\r
925 CV_EXPORTS void reduce(const GpuMat& mtx, GpuMat& vec, int dim, int reduceOp, int dtype = -1, Stream& stream = Stream::Null());\r
926 \r
927 \r
928 ///////////////////////////// Calibration 3D //////////////////////////////////\r
929 \r
930 CV_EXPORTS void transformPoints(const GpuMat& src, const Mat& rvec, const Mat& tvec,\r
931                                 GpuMat& dst, Stream& stream = Stream::Null());\r
932 \r
933 CV_EXPORTS void projectPoints(const GpuMat& src, const Mat& rvec, const Mat& tvec,\r
934                               const Mat& camera_mat, const Mat& dist_coef, GpuMat& dst,\r
935                               Stream& stream = Stream::Null());\r
936 \r
937 CV_EXPORTS void solvePnPRansac(const Mat& object, const Mat& image, const Mat& camera_mat,\r
938                                const Mat& dist_coef, Mat& rvec, Mat& tvec, bool use_extrinsic_guess=false,\r
939                                int num_iters=100, float max_dist=8.0, int min_inlier_count=100,\r
940                                std::vector<int>* inliers=NULL);\r
941 \r
942 //////////////////////////////// Image Labeling ////////////////////////////////\r
943 \r
944 //!performs labeling via graph cuts of a 2D regular 4-connected graph.\r
945 CV_EXPORTS void graphcut(GpuMat& terminals, GpuMat& leftTransp, GpuMat& rightTransp, GpuMat& top, GpuMat& bottom, GpuMat& labels,\r
946                          GpuMat& buf, Stream& stream = Stream::Null());\r
947 \r
948 //!performs labeling via graph cuts of a 2D regular 8-connected graph.\r
949 CV_EXPORTS void graphcut(GpuMat& terminals, GpuMat& leftTransp, GpuMat& rightTransp, GpuMat& top, GpuMat& topLeft, GpuMat& topRight,\r
950                          GpuMat& bottom, GpuMat& bottomLeft, GpuMat& bottomRight,\r
951                          GpuMat& labels,\r
952                          GpuMat& buf, Stream& stream = Stream::Null());\r
953 \r
954 //! compute mask for Generalized Flood fill componetns labeling.\r
955 CV_EXPORTS void connectivityMask(const GpuMat& image, GpuMat& mask, const cv::Scalar& lo, const cv::Scalar& hi, Stream& stream = Stream::Null());\r
956 \r
957 //! performs connected componnents labeling.\r
958 CV_EXPORTS void labelComponents(const GpuMat& mask, GpuMat& components, int flags = 0, Stream& stream = Stream::Null());\r
959 \r
960 ////////////////////////////////// Histograms //////////////////////////////////\r
961 \r
962 //! Compute levels with even distribution. levels will have 1 row and nLevels cols and CV_32SC1 type.\r
963 CV_EXPORTS void evenLevels(GpuMat& levels, int nLevels, int lowerLevel, int upperLevel);\r
964 //! Calculates histogram with evenly distributed bins for signle channel source.\r
965 //! Supports CV_8UC1, CV_16UC1 and CV_16SC1 source types.\r
966 //! Output hist will have one row and histSize cols and CV_32SC1 type.\r
967 CV_EXPORTS void histEven(const GpuMat& src, GpuMat& hist, int histSize, int lowerLevel, int upperLevel, Stream& stream = Stream::Null());\r
968 CV_EXPORTS void histEven(const GpuMat& src, GpuMat& hist, GpuMat& buf, int histSize, int lowerLevel, int upperLevel, Stream& stream = Stream::Null());\r
969 //! Calculates histogram with evenly distributed bins for four-channel source.\r
970 //! All channels of source are processed separately.\r
971 //! Supports CV_8UC4, CV_16UC4 and CV_16SC4 source types.\r
972 //! Output hist[i] will have one row and histSize[i] cols and CV_32SC1 type.\r
973 CV_EXPORTS void histEven(const GpuMat& src, GpuMat hist[4], int histSize[4], int lowerLevel[4], int upperLevel[4], Stream& stream = Stream::Null());\r
974 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
975 //! Calculates histogram with bins determined by levels array.\r
976 //! levels must have one row and CV_32SC1 type if source has integer type or CV_32FC1 otherwise.\r
977 //! Supports CV_8UC1, CV_16UC1, CV_16SC1 and CV_32FC1 source types.\r
978 //! Output hist will have one row and (levels.cols-1) cols and CV_32SC1 type.\r
979 CV_EXPORTS void histRange(const GpuMat& src, GpuMat& hist, const GpuMat& levels, Stream& stream = Stream::Null());\r
980 CV_EXPORTS void histRange(const GpuMat& src, GpuMat& hist, const GpuMat& levels, GpuMat& buf, Stream& stream = Stream::Null());\r
981 //! Calculates histogram with bins determined by levels array.\r
982 //! All levels must have one row and CV_32SC1 type if source has integer type or CV_32FC1 otherwise.\r
983 //! All channels of source are processed separately.\r
984 //! Supports CV_8UC4, CV_16UC4, CV_16SC4 and CV_32FC4 source types.\r
985 //! Output hist[i] will have one row and (levels[i].cols-1) cols and CV_32SC1 type.\r
986 CV_EXPORTS void histRange(const GpuMat& src, GpuMat hist[4], const GpuMat levels[4], Stream& stream = Stream::Null());\r
987 CV_EXPORTS void histRange(const GpuMat& src, GpuMat hist[4], const GpuMat levels[4], GpuMat& buf, Stream& stream = Stream::Null());\r
988 \r
989 //! Calculates histogram for 8u one channel image\r
990 //! Output hist will have one row, 256 cols and CV32SC1 type.\r
991 CV_EXPORTS void calcHist(const GpuMat& src, GpuMat& hist, Stream& stream = Stream::Null());\r
992 CV_EXPORTS void calcHist(const GpuMat& src, GpuMat& hist, GpuMat& buf, Stream& stream = Stream::Null());\r
993 \r
994 //! normalizes the grayscale image brightness and contrast by normalizing its histogram\r
995 CV_EXPORTS void equalizeHist(const GpuMat& src, GpuMat& dst, Stream& stream = Stream::Null());\r
996 CV_EXPORTS void equalizeHist(const GpuMat& src, GpuMat& dst, GpuMat& hist, Stream& stream = Stream::Null());\r
997 CV_EXPORTS void equalizeHist(const GpuMat& src, GpuMat& dst, GpuMat& hist, GpuMat& buf, Stream& stream = Stream::Null());\r
998 \r
999 //////////////////////////////// StereoBM_GPU ////////////////////////////////\r
1000 \r
1001 class CV_EXPORTS StereoBM_GPU\r
1002 {\r
1003 public:\r
1004     enum { BASIC_PRESET = 0, PREFILTER_XSOBEL = 1 };\r
1005 \r
1006     enum { DEFAULT_NDISP = 64, DEFAULT_WINSZ = 19 };\r
1007 \r
1008     //! the default constructor\r
1009     StereoBM_GPU();\r
1010     //! the full constructor taking the camera-specific preset, number of disparities and the SAD window size. ndisparities must be multiple of 8.\r
1011     StereoBM_GPU(int preset, int ndisparities = DEFAULT_NDISP, int winSize = DEFAULT_WINSZ);\r
1012 \r
1013     //! the stereo correspondence operator. Finds the disparity for the specified rectified stereo pair\r
1014     //! Output disparity has CV_8U type.\r
1015     void operator()(const GpuMat& left, const GpuMat& right, GpuMat& disparity, Stream& stream = Stream::Null());\r
1016 \r
1017     //! Some heuristics that tries to estmate\r
1018     // if current GPU will be faster than CPU in this algorithm.\r
1019     // It queries current active device.\r
1020     static bool checkIfGpuCallReasonable();\r
1021 \r
1022     int preset;\r
1023     int ndisp;\r
1024     int winSize;\r
1025 \r
1026     // If avergeTexThreshold  == 0 => post procesing is disabled\r
1027     // If avergeTexThreshold != 0 then disparity is set 0 in each point (x,y) where for left image\r
1028     // SumOfHorizontalGradiensInWindow(x, y, winSize) < (winSize * winSize) * avergeTexThreshold\r
1029     // i.e. input left image is low textured.\r
1030     float avergeTexThreshold;\r
1031 \r
1032 private:\r
1033     GpuMat minSSD, leBuf, riBuf;\r
1034 };\r
1035 \r
1036 ////////////////////////// StereoBeliefPropagation ///////////////////////////\r
1037 // "Efficient Belief Propagation for Early Vision"\r
1038 // P.Felzenszwalb\r
1039 \r
1040 class CV_EXPORTS StereoBeliefPropagation\r
1041 {\r
1042 public:\r
1043     enum { DEFAULT_NDISP  = 64 };\r
1044     enum { DEFAULT_ITERS  = 5  };\r
1045     enum { DEFAULT_LEVELS = 5  };\r
1046 \r
1047     static void estimateRecommendedParams(int width, int height, int& ndisp, int& iters, int& levels);\r
1048 \r
1049     //! the default constructor\r
1050     explicit StereoBeliefPropagation(int ndisp  = DEFAULT_NDISP,\r
1051                                      int iters  = DEFAULT_ITERS,\r
1052                                      int levels = DEFAULT_LEVELS,\r
1053                                      int msg_type = CV_32F);\r
1054 \r
1055     //! the full constructor taking the number of disparities, number of BP iterations on each level,\r
1056     //! number of levels, truncation of data cost, data weight,\r
1057     //! truncation of discontinuity cost and discontinuity single jump\r
1058     //! DataTerm = data_weight * min(fabs(I2-I1), max_data_term)\r
1059     //! DiscTerm = min(disc_single_jump * fabs(f1-f2), max_disc_term)\r
1060     //! please see paper for more details\r
1061     StereoBeliefPropagation(int ndisp, int iters, int levels,\r
1062         float max_data_term, float data_weight,\r
1063         float max_disc_term, float disc_single_jump,\r
1064         int msg_type = CV_32F);\r
1065 \r
1066     //! the stereo correspondence operator. Finds the disparity for the specified rectified stereo pair,\r
1067     //! if disparity is empty output type will be CV_16S else output type will be disparity.type().\r
1068     void operator()(const GpuMat& left, const GpuMat& right, GpuMat& disparity, Stream& stream = Stream::Null());\r
1069 \r
1070 \r
1071     //! version for user specified data term\r
1072     void operator()(const GpuMat& data, GpuMat& disparity, Stream& stream = Stream::Null());\r
1073 \r
1074     int ndisp;\r
1075 \r
1076     int iters;\r
1077     int levels;\r
1078 \r
1079     float max_data_term;\r
1080     float data_weight;\r
1081     float max_disc_term;\r
1082     float disc_single_jump;\r
1083 \r
1084     int msg_type;\r
1085 private:\r
1086     GpuMat u, d, l, r, u2, d2, l2, r2;\r
1087     std::vector<GpuMat> datas;\r
1088     GpuMat out;\r
1089 };\r
1090 \r
1091 /////////////////////////// StereoConstantSpaceBP ///////////////////////////\r
1092 // "A Constant-Space Belief Propagation Algorithm for Stereo Matching"\r
1093 // Qingxiong Yang, Liang Wang, Narendra Ahuja\r
1094 // http://vision.ai.uiuc.edu/~qyang6/\r
1095 \r
1096 class CV_EXPORTS StereoConstantSpaceBP\r
1097 {\r
1098 public:\r
1099     enum { DEFAULT_NDISP    = 128 };\r
1100     enum { DEFAULT_ITERS    = 8   };\r
1101     enum { DEFAULT_LEVELS   = 4   };\r
1102     enum { DEFAULT_NR_PLANE = 4   };\r
1103 \r
1104     static void estimateRecommendedParams(int width, int height, int& ndisp, int& iters, int& levels, int& nr_plane);\r
1105 \r
1106     //! the default constructor\r
1107     explicit StereoConstantSpaceBP(int ndisp    = DEFAULT_NDISP,\r
1108                                    int iters    = DEFAULT_ITERS,\r
1109                                    int levels   = DEFAULT_LEVELS,\r
1110                                    int nr_plane = DEFAULT_NR_PLANE,\r
1111                                    int msg_type = CV_32F);\r
1112 \r
1113     //! the full constructor taking the number of disparities, number of BP iterations on each level,\r
1114     //! number of levels, number of active disparity on the first level, truncation of data cost, data weight,\r
1115     //! truncation of discontinuity cost, discontinuity single jump and minimum disparity threshold\r
1116     StereoConstantSpaceBP(int ndisp, int iters, int levels, int nr_plane,\r
1117         float max_data_term, float data_weight, float max_disc_term, float disc_single_jump,\r
1118         int min_disp_th = 0,\r
1119         int msg_type = CV_32F);\r
1120 \r
1121     //! the stereo correspondence operator. Finds the disparity for the specified rectified stereo pair,\r
1122     //! if disparity is empty output type will be CV_16S else output type will be disparity.type().\r
1123     void operator()(const GpuMat& left, const GpuMat& right, GpuMat& disparity, Stream& stream = Stream::Null());\r
1124 \r
1125     int ndisp;\r
1126 \r
1127     int iters;\r
1128     int levels;\r
1129 \r
1130     int nr_plane;\r
1131 \r
1132     float max_data_term;\r
1133     float data_weight;\r
1134     float max_disc_term;\r
1135     float disc_single_jump;\r
1136 \r
1137     int min_disp_th;\r
1138 \r
1139     int msg_type;\r
1140 \r
1141     bool use_local_init_data_cost;\r
1142 private:\r
1143     GpuMat messages_buffers;\r
1144 \r
1145     GpuMat temp;\r
1146     GpuMat out;\r
1147 };\r
1148 \r
1149 /////////////////////////// DisparityBilateralFilter ///////////////////////////\r
1150 // Disparity map refinement using joint bilateral filtering given a single color image.\r
1151 // Qingxiong Yang, Liang Wang, Narendra Ahuja\r
1152 // http://vision.ai.uiuc.edu/~qyang6/\r
1153 \r
1154 class CV_EXPORTS DisparityBilateralFilter\r
1155 {\r
1156 public:\r
1157     enum { DEFAULT_NDISP  = 64 };\r
1158     enum { DEFAULT_RADIUS = 3 };\r
1159     enum { DEFAULT_ITERS  = 1 };\r
1160 \r
1161     //! the default constructor\r
1162     explicit DisparityBilateralFilter(int ndisp = DEFAULT_NDISP, int radius = DEFAULT_RADIUS, int iters = DEFAULT_ITERS);\r
1163 \r
1164     //! the full constructor taking the number of disparities, filter radius,\r
1165     //! number of iterations, truncation of data continuity, truncation of disparity continuity\r
1166     //! and filter range sigma\r
1167     DisparityBilateralFilter(int ndisp, int radius, int iters, float edge_threshold, float max_disc_threshold, float sigma_range);\r
1168 \r
1169     //! the disparity map refinement operator. Refine disparity map using joint bilateral filtering given a single color image.\r
1170     //! disparity must have CV_8U or CV_16S type, image must have CV_8UC1 or CV_8UC3 type.\r
1171     void operator()(const GpuMat& disparity, const GpuMat& image, GpuMat& dst, Stream& stream = Stream::Null());\r
1172 \r
1173 private:\r
1174     int ndisp;\r
1175     int radius;\r
1176     int iters;\r
1177 \r
1178     float edge_threshold;\r
1179     float max_disc_threshold;\r
1180     float sigma_range;\r
1181 \r
1182     GpuMat table_color;\r
1183     GpuMat table_space;\r
1184 };\r
1185 \r
1186 \r
1187 //////////////// HOG (Histogram-of-Oriented-Gradients) Descriptor and Object Detector //////////////\r
1188 struct CV_EXPORTS HOGConfidence\r
1189 {\r
1190    double scale;\r
1191    vector<Point> locations;\r
1192    vector<double> confidences;\r
1193    vector<double> part_scores[4];\r
1194 };\r
1195 \r
1196 struct CV_EXPORTS HOGDescriptor\r
1197 {\r
1198     enum { DEFAULT_WIN_SIGMA = -1 };\r
1199     enum { DEFAULT_NLEVELS = 64 };\r
1200     enum { DESCR_FORMAT_ROW_BY_ROW, DESCR_FORMAT_COL_BY_COL };\r
1201 \r
1202     HOGDescriptor(Size win_size=Size(64, 128), Size block_size=Size(16, 16),\r
1203                   Size block_stride=Size(8, 8), Size cell_size=Size(8, 8),\r
1204                   int nbins=9, double win_sigma=DEFAULT_WIN_SIGMA,\r
1205                   double threshold_L2hys=0.2, bool gamma_correction=true,\r
1206                   int nlevels=DEFAULT_NLEVELS);\r
1207 \r
1208     size_t getDescriptorSize() const;\r
1209     size_t getBlockHistogramSize() const;\r
1210 \r
1211     void setSVMDetector(const vector<float>& detector);\r
1212 \r
1213     static vector<float> getDefaultPeopleDetector();\r
1214     static vector<float> getPeopleDetector48x96();\r
1215     static vector<float> getPeopleDetector64x128();\r
1216 \r
1217     void detect(const GpuMat& img, vector<Point>& found_locations,\r
1218                 double hit_threshold=0, Size win_stride=Size(),\r
1219                 Size padding=Size());\r
1220 \r
1221     void detectMultiScale(const GpuMat& img, vector<Rect>& found_locations,\r
1222                           double hit_threshold=0, Size win_stride=Size(),\r
1223                           Size padding=Size(), double scale0=1.05,\r
1224                           int group_threshold=2);\r
1225 \r
1226     void computeConfidence(const GpuMat& img, vector<Point>& hits, double hit_threshold,\r
1227                                                 Size win_stride, Size padding, vector<Point>& locations, vector<double>& confidences);\r
1228 \r
1229     void computeConfidenceMultiScale(const GpuMat& img, vector<Rect>& found_locations,\r
1230                                                                     double hit_threshold, Size win_stride, Size padding,\r
1231                                                                     vector<HOGConfidence> &conf_out, int group_threshold);\r
1232 \r
1233     void getDescriptors(const GpuMat& img, Size win_stride,\r
1234                         GpuMat& descriptors,\r
1235                         int descr_format=DESCR_FORMAT_COL_BY_COL);\r
1236 \r
1237     Size win_size;\r
1238     Size block_size;\r
1239     Size block_stride;\r
1240     Size cell_size;\r
1241     int nbins;\r
1242     double win_sigma;\r
1243     double threshold_L2hys;\r
1244     bool gamma_correction;\r
1245     int nlevels;\r
1246 \r
1247 protected:\r
1248     void computeBlockHistograms(const GpuMat& img);\r
1249     void computeGradient(const GpuMat& img, GpuMat& grad, GpuMat& qangle);\r
1250 \r
1251     double getWinSigma() const;\r
1252     bool checkDetectorSize() const;\r
1253 \r
1254     static int numPartsWithin(int size, int part_size, int stride);\r
1255     static Size numPartsWithin(Size size, Size part_size, Size stride);\r
1256 \r
1257     // Coefficients of the separating plane\r
1258     float free_coef;\r
1259     GpuMat detector;\r
1260 \r
1261     // Results of the last classification step\r
1262     GpuMat labels, labels_buf;\r
1263     Mat labels_host;\r
1264 \r
1265     // Results of the last histogram evaluation step\r
1266     GpuMat block_hists, block_hists_buf;\r
1267 \r
1268     // Gradients conputation results\r
1269     GpuMat grad, qangle, grad_buf, qangle_buf;\r
1270 \r
1271     // returns subbuffer with required size, reallocates buffer if nessesary.\r
1272     static GpuMat getBuffer(const Size& sz, int type, GpuMat& buf);\r
1273     static GpuMat getBuffer(int rows, int cols, int type, GpuMat& buf);\r
1274 \r
1275     std::vector<GpuMat> image_scales;\r
1276 };\r
1277 \r
1278 \r
1279 ////////////////////////////////// BruteForceMatcher //////////////////////////////////\r
1280 \r
1281 class CV_EXPORTS BFMatcher_GPU\r
1282 {\r
1283 public:\r
1284     explicit BFMatcher_GPU(int norm = cv::NORM_L2);\r
1285 \r
1286     // Add descriptors to train descriptor collection\r
1287     void add(const std::vector<GpuMat>& descCollection);\r
1288 \r
1289     // Get train descriptors collection\r
1290     const std::vector<GpuMat>& getTrainDescriptors() const;\r
1291 \r
1292     // Clear train descriptors collection\r
1293     void clear();\r
1294 \r
1295     // Return true if there are not train descriptors in collection\r
1296     bool empty() const;\r
1297 \r
1298     // Return true if the matcher supports mask in match methods\r
1299     bool isMaskSupported() const;\r
1300 \r
1301     // Find one best match for each query descriptor\r
1302     void matchSingle(const GpuMat& query, const GpuMat& train,\r
1303         GpuMat& trainIdx, GpuMat& distance,\r
1304         const GpuMat& mask = GpuMat(), Stream& stream = Stream::Null());\r
1305 \r
1306     // Download trainIdx and distance and convert it to CPU vector with DMatch\r
1307     static void matchDownload(const GpuMat& trainIdx, const GpuMat& distance, std::vector<DMatch>& matches);\r
1308     // Convert trainIdx and distance to vector with DMatch\r
1309     static void matchConvert(const Mat& trainIdx, const Mat& distance, std::vector<DMatch>& matches);\r
1310 \r
1311     // Find one best match for each query descriptor\r
1312     void match(const GpuMat& query, const GpuMat& train, std::vector<DMatch>& matches, const GpuMat& mask = GpuMat());\r
1313 \r
1314     // Make gpu collection of trains and masks in suitable format for matchCollection function\r
1315     void makeGpuCollection(GpuMat& trainCollection, GpuMat& maskCollection, const std::vector<GpuMat>& masks = std::vector<GpuMat>());\r
1316 \r
1317     // Find one best match from train collection for each query descriptor\r
1318     void matchCollection(const GpuMat& query, const GpuMat& trainCollection,\r
1319         GpuMat& trainIdx, GpuMat& imgIdx, GpuMat& distance,\r
1320         const GpuMat& masks = GpuMat(), Stream& stream = Stream::Null());\r
1321 \r
1322     // Download trainIdx, imgIdx and distance and convert it to vector with DMatch\r
1323     static void matchDownload(const GpuMat& trainIdx, const GpuMat& imgIdx, const GpuMat& distance, std::vector<DMatch>& matches);\r
1324     // Convert trainIdx, imgIdx and distance to vector with DMatch\r
1325     static void matchConvert(const Mat& trainIdx, const Mat& imgIdx, const Mat& distance, std::vector<DMatch>& matches);\r
1326 \r
1327     // Find one best match from train collection for each query descriptor.\r
1328     void match(const GpuMat& query, std::vector<DMatch>& matches, const std::vector<GpuMat>& masks = std::vector<GpuMat>());\r
1329 \r
1330     // Find k best matches for each query descriptor (in increasing order of distances)\r
1331     void knnMatchSingle(const GpuMat& query, const GpuMat& train,\r
1332         GpuMat& trainIdx, GpuMat& distance, GpuMat& allDist, int k,\r
1333         const GpuMat& mask = GpuMat(), Stream& stream = Stream::Null());\r
1334 \r
1335     // Download trainIdx and distance and convert it to vector with DMatch\r
1336     // compactResult is used when mask is not empty. If compactResult is false matches\r
1337     // vector will have the same size as queryDescriptors rows. If compactResult is true\r
1338     // matches vector will not contain matches for fully masked out query descriptors.\r
1339     static void knnMatchDownload(const GpuMat& trainIdx, const GpuMat& distance,\r
1340         std::vector< std::vector<DMatch> >& matches, bool compactResult = false);\r
1341     // Convert trainIdx and distance to vector with DMatch\r
1342     static void knnMatchConvert(const Mat& trainIdx, const Mat& distance,\r
1343         std::vector< std::vector<DMatch> >& matches, bool compactResult = false);\r
1344 \r
1345     // Find k best matches for each query descriptor (in increasing order of distances).\r
1346     // compactResult is used when mask is not empty. If compactResult is false matches\r
1347     // vector will have the same size as queryDescriptors rows. If compactResult is true\r
1348     // matches vector will not contain matches for fully masked out query descriptors.\r
1349     void knnMatch(const GpuMat& query, const GpuMat& train,\r
1350         std::vector< std::vector<DMatch> >& matches, int k, const GpuMat& mask = GpuMat(),\r
1351         bool compactResult = false);\r
1352 \r
1353     // Find k best matches from train collection for each query descriptor (in increasing order of distances)\r
1354     void knnMatch2Collection(const GpuMat& query, const GpuMat& trainCollection,\r
1355         GpuMat& trainIdx, GpuMat& imgIdx, GpuMat& distance,\r
1356         const GpuMat& maskCollection = GpuMat(), Stream& stream = Stream::Null());\r
1357 \r
1358     // Download trainIdx and distance and convert it to vector with DMatch\r
1359     // compactResult is used when mask is not empty. If compactResult is false matches\r
1360     // vector will have the same size as queryDescriptors rows. If compactResult is true\r
1361     // matches vector will not contain matches for fully masked out query descriptors.\r
1362     static void knnMatch2Download(const GpuMat& trainIdx, const GpuMat& imgIdx, const GpuMat& distance,\r
1363         std::vector< std::vector<DMatch> >& matches, bool compactResult = false);\r
1364     // Convert trainIdx and distance to vector with DMatch\r
1365     static void knnMatch2Convert(const Mat& trainIdx, const Mat& imgIdx, const Mat& distance,\r
1366         std::vector< std::vector<DMatch> >& matches, bool compactResult = false);\r
1367 \r
1368     // Find k best matches  for each query descriptor (in increasing order of distances).\r
1369     // compactResult is used when mask is not empty. If compactResult is false matches\r
1370     // vector will have the same size as queryDescriptors rows. If compactResult is true\r
1371     // matches vector will not contain matches for fully masked out query descriptors.\r
1372     void knnMatch(const GpuMat& query, std::vector< std::vector<DMatch> >& matches, int k,\r
1373         const std::vector<GpuMat>& masks = std::vector<GpuMat>(), bool compactResult = false);\r
1374 \r
1375     // Find best matches for each query descriptor which have distance less than maxDistance.\r
1376     // nMatches.at<int>(0, queryIdx) will contain matches count for queryIdx.\r
1377     // carefully nMatches can be greater than trainIdx.cols - it means that matcher didn't find all matches,\r
1378     // because it didn't have enough memory.\r
1379     // If trainIdx is empty, then trainIdx and distance will be created with size nQuery x max((nTrain / 100), 10),\r
1380     // otherwize user can pass own allocated trainIdx and distance with size nQuery x nMaxMatches\r
1381     // Matches doesn't sorted.\r
1382     void radiusMatchSingle(const GpuMat& query, const GpuMat& train,\r
1383         GpuMat& trainIdx, GpuMat& distance, GpuMat& nMatches, float maxDistance,\r
1384         const GpuMat& mask = GpuMat(), Stream& stream = Stream::Null());\r
1385 \r
1386     // Download trainIdx, nMatches and distance and convert it to vector with DMatch.\r
1387     // matches will be sorted in increasing order of distances.\r
1388     // compactResult is used when mask is not empty. If compactResult is false matches\r
1389     // vector will have the same size as queryDescriptors rows. If compactResult is true\r
1390     // matches vector will not contain matches for fully masked out query descriptors.\r
1391     static void radiusMatchDownload(const GpuMat& trainIdx, const GpuMat& distance, const GpuMat& nMatches,\r
1392         std::vector< std::vector<DMatch> >& matches, bool compactResult = false);\r
1393     // Convert trainIdx, nMatches and distance to vector with DMatch.\r
1394     static void radiusMatchConvert(const Mat& trainIdx, const Mat& distance, const Mat& nMatches,\r
1395         std::vector< std::vector<DMatch> >& matches, bool compactResult = false);\r
1396 \r
1397     // Find best matches for each query descriptor which have distance less than maxDistance\r
1398     // in increasing order of distances).\r
1399     void radiusMatch(const GpuMat& query, const GpuMat& train,\r
1400         std::vector< std::vector<DMatch> >& matches, float maxDistance,\r
1401         const GpuMat& mask = GpuMat(), bool compactResult = false);\r
1402 \r
1403     // Find best matches for each query descriptor which have distance less than maxDistance.\r
1404     // If trainIdx is empty, then trainIdx and distance will be created with size nQuery x max((nQuery / 100), 10),\r
1405     // otherwize user can pass own allocated trainIdx and distance with size nQuery x nMaxMatches\r
1406     // Matches doesn't sorted.\r
1407     void radiusMatchCollection(const GpuMat& query, GpuMat& trainIdx, GpuMat& imgIdx, GpuMat& distance, GpuMat& nMatches, float maxDistance,\r
1408         const std::vector<GpuMat>& masks = std::vector<GpuMat>(), Stream& stream = Stream::Null());\r
1409 \r
1410     // Download trainIdx, imgIdx, nMatches and distance and convert it to vector with DMatch.\r
1411     // matches will be sorted in increasing order of distances.\r
1412     // compactResult is used when mask is not empty. If compactResult is false matches\r
1413     // vector will have the same size as queryDescriptors rows. If compactResult is true\r
1414     // matches vector will not contain matches for fully masked out query descriptors.\r
1415     static void radiusMatchDownload(const GpuMat& trainIdx, const GpuMat& imgIdx, const GpuMat& distance, const GpuMat& nMatches,\r
1416         std::vector< std::vector<DMatch> >& matches, bool compactResult = false);\r
1417     // Convert trainIdx, nMatches and distance to vector with DMatch.\r
1418     static void radiusMatchConvert(const Mat& trainIdx, const Mat& imgIdx, const Mat& distance, const Mat& nMatches,\r
1419         std::vector< std::vector<DMatch> >& matches, bool compactResult = false);\r
1420 \r
1421     // Find best matches from train collection for each query descriptor which have distance less than\r
1422     // maxDistance (in increasing order of distances).\r
1423     void radiusMatch(const GpuMat& query, std::vector< std::vector<DMatch> >& matches, float maxDistance,\r
1424         const std::vector<GpuMat>& masks = std::vector<GpuMat>(), bool compactResult = false);\r
1425 \r
1426     int norm;\r
1427 \r
1428 private:\r
1429     std::vector<GpuMat> trainDescCollection;\r
1430 };\r
1431 \r
1432 template <class Distance>\r
1433 class CV_EXPORTS BruteForceMatcher_GPU;\r
1434 \r
1435 template <typename T>\r
1436 class CV_EXPORTS BruteForceMatcher_GPU< L1<T> > : public BFMatcher_GPU\r
1437 {\r
1438 public:\r
1439     explicit BruteForceMatcher_GPU() : BFMatcher_GPU(NORM_L1) {}\r
1440     explicit BruteForceMatcher_GPU(L1<T> /*d*/) : BFMatcher_GPU(NORM_L1) {}\r
1441 };\r
1442 template <typename T>\r
1443 class CV_EXPORTS BruteForceMatcher_GPU< L2<T> > : public BFMatcher_GPU\r
1444 {\r
1445 public:\r
1446     explicit BruteForceMatcher_GPU() : BFMatcher_GPU(NORM_L2) {}\r
1447     explicit BruteForceMatcher_GPU(L2<T> /*d*/) : BFMatcher_GPU(NORM_L2) {}\r
1448 };\r
1449 template <> class CV_EXPORTS BruteForceMatcher_GPU< Hamming > : public BFMatcher_GPU\r
1450 {\r
1451 public:\r
1452     explicit BruteForceMatcher_GPU() : BFMatcher_GPU(NORM_HAMMING) {}\r
1453     explicit BruteForceMatcher_GPU(Hamming /*d*/) : BFMatcher_GPU(NORM_HAMMING) {}\r
1454 };\r
1455 \r
1456 ////////////////////////////////// CascadeClassifier_GPU //////////////////////////////////////////\r
1457 // The cascade classifier class for object detection: supports old haar and new lbp xlm formats and nvbin for haar cascades olny.\r
1458 class CV_EXPORTS CascadeClassifier_GPU\r
1459 {\r
1460 public:\r
1461     CascadeClassifier_GPU();\r
1462     CascadeClassifier_GPU(const std::string& filename);\r
1463     ~CascadeClassifier_GPU();\r
1464 \r
1465     bool empty() const;\r
1466     bool load(const std::string& filename);\r
1467     void release();\r
1468 \r
1469     /* returns number of detected objects */\r
1470     int detectMultiScale(const GpuMat& image, GpuMat& objectsBuf, double scaleFactor = 1.2, int minNeighbors = 4, Size minSize = Size());\r
1471 \r
1472     bool findLargestObject;\r
1473     bool visualizeInPlace;\r
1474 \r
1475     Size getClassifierSize() const;\r
1476 \r
1477 private:\r
1478     struct CascadeClassifierImpl;\r
1479     CascadeClassifierImpl* impl;\r
1480     struct HaarCascade;\r
1481     struct LbpCascade;\r
1482     friend class CascadeClassifier_GPU_LBP;\r
1483 \r
1484 public:\r
1485     int detectMultiScale(const GpuMat& image, GpuMat& objectsBuf, Size maxObjectSize, Size minSize = Size(), double scaleFactor = 1.1, int minNeighbors = 4);\r
1486 };\r
1487 \r
1488 ////////////////////////////////// SURF //////////////////////////////////////////\r
1489 \r
1490 class CV_EXPORTS SURF_GPU\r
1491 {\r
1492 public:\r
1493     enum KeypointLayout\r
1494     {\r
1495         X_ROW = 0,\r
1496         Y_ROW,\r
1497         LAPLACIAN_ROW,\r
1498         OCTAVE_ROW,\r
1499         SIZE_ROW,\r
1500         ANGLE_ROW,\r
1501         HESSIAN_ROW,\r
1502         ROWS_COUNT\r
1503     };\r
1504 \r
1505     //! the default constructor\r
1506     SURF_GPU();\r
1507     //! the full constructor taking all the necessary parameters\r
1508     explicit SURF_GPU(double _hessianThreshold, int _nOctaves=4,\r
1509          int _nOctaveLayers=2, bool _extended=false, float _keypointsRatio=0.01f, bool _upright = false);\r
1510 \r
1511     //! returns the descriptor size in float's (64 or 128)\r
1512     int descriptorSize() const;\r
1513 \r
1514     //! upload host keypoints to device memory\r
1515     static void uploadKeypoints(const vector<KeyPoint>& keypoints, GpuMat& keypointsGPU);\r
1516     //! download keypoints from device to host memory\r
1517     static void downloadKeypoints(const GpuMat& keypointsGPU, vector<KeyPoint>& keypoints);\r
1518 \r
1519     //! download descriptors from device to host memory\r
1520     static void downloadDescriptors(const GpuMat& descriptorsGPU, vector<float>& descriptors);\r
1521 \r
1522     //! finds the keypoints using fast hessian detector used in SURF\r
1523     //! supports CV_8UC1 images\r
1524     //! keypoints will have nFeature cols and 6 rows\r
1525     //! keypoints.ptr<float>(X_ROW)[i] will contain x coordinate of i'th feature\r
1526     //! keypoints.ptr<float>(Y_ROW)[i] will contain y coordinate of i'th feature\r
1527     //! keypoints.ptr<float>(LAPLACIAN_ROW)[i] will contain laplacian sign of i'th feature\r
1528     //! keypoints.ptr<float>(OCTAVE_ROW)[i] will contain octave of i'th feature\r
1529     //! keypoints.ptr<float>(SIZE_ROW)[i] will contain size of i'th feature\r
1530     //! keypoints.ptr<float>(ANGLE_ROW)[i] will contain orientation of i'th feature\r
1531     //! keypoints.ptr<float>(HESSIAN_ROW)[i] will contain response of i'th feature\r
1532     void operator()(const GpuMat& img, const GpuMat& mask, GpuMat& keypoints);\r
1533     //! finds the keypoints and computes their descriptors.\r
1534     //! Optionally it can compute descriptors for the user-provided keypoints and recompute keypoints direction\r
1535     void operator()(const GpuMat& img, const GpuMat& mask, GpuMat& keypoints, GpuMat& descriptors,\r
1536         bool useProvidedKeypoints = false);\r
1537 \r
1538     void operator()(const GpuMat& img, const GpuMat& mask, std::vector<KeyPoint>& keypoints);\r
1539     void operator()(const GpuMat& img, const GpuMat& mask, std::vector<KeyPoint>& keypoints, GpuMat& descriptors,\r
1540         bool useProvidedKeypoints = false);\r
1541 \r
1542     void operator()(const GpuMat& img, const GpuMat& mask, std::vector<KeyPoint>& keypoints, std::vector<float>& descriptors,\r
1543         bool useProvidedKeypoints = false);\r
1544 \r
1545     void releaseMemory();\r
1546 \r
1547     // SURF parameters\r
1548     double hessianThreshold;\r
1549     int nOctaves;\r
1550     int nOctaveLayers;\r
1551     bool extended;\r
1552     bool upright;\r
1553 \r
1554     //! max keypoints = min(keypointsRatio * img.size().area(), 65535)\r
1555     float keypointsRatio;\r
1556 \r
1557     GpuMat sum, mask1, maskSum, intBuffer;\r
1558 \r
1559     GpuMat det, trace;\r
1560 \r
1561     GpuMat maxPosBuffer;\r
1562 };\r
1563 \r
1564 ////////////////////////////////// FAST //////////////////////////////////////////\r
1565 \r
1566 class CV_EXPORTS FAST_GPU\r
1567 {\r
1568 public:\r
1569     enum\r
1570     {\r
1571         LOCATION_ROW = 0,\r
1572         RESPONSE_ROW,\r
1573         ROWS_COUNT\r
1574     };\r
1575 \r
1576     // all features have same size\r
1577     static const int FEATURE_SIZE = 7;\r
1578 \r
1579     explicit FAST_GPU(int threshold, bool nonmaxSupression = true, double keypointsRatio = 0.05);\r
1580 \r
1581     //! finds the keypoints using FAST detector\r
1582     //! supports only CV_8UC1 images\r
1583     void operator ()(const GpuMat& image, const GpuMat& mask, GpuMat& keypoints);\r
1584     void operator ()(const GpuMat& image, const GpuMat& mask, std::vector<KeyPoint>& keypoints);\r
1585 \r
1586     //! download keypoints from device to host memory\r
1587     static void downloadKeypoints(const GpuMat& d_keypoints, std::vector<KeyPoint>& keypoints);\r
1588 \r
1589     //! convert keypoints to KeyPoint vector\r
1590     static void convertKeypoints(const Mat& h_keypoints, std::vector<KeyPoint>& keypoints);\r
1591 \r
1592     //! release temporary buffer's memory\r
1593     void release();\r
1594 \r
1595     bool nonmaxSupression;\r
1596 \r
1597     int threshold;\r
1598 \r
1599     //! max keypoints = keypointsRatio * img.size().area()\r
1600     double keypointsRatio;\r
1601 \r
1602     //! find keypoints and compute it's response if nonmaxSupression is true\r
1603     //! return count of detected keypoints\r
1604     int calcKeyPointsLocation(const GpuMat& image, const GpuMat& mask);\r
1605 \r
1606     //! get final array of keypoints\r
1607     //! performs nonmax supression if needed\r
1608     //! return final count of keypoints\r
1609     int getKeyPoints(GpuMat& keypoints);\r
1610 \r
1611 private:\r
1612     GpuMat kpLoc_;\r
1613     int count_;\r
1614 \r
1615     GpuMat score_;\r
1616 \r
1617     GpuMat d_keypoints_;\r
1618 };\r
1619 \r
1620 ////////////////////////////////// ORB //////////////////////////////////////////\r
1621 \r
1622 class CV_EXPORTS ORB_GPU\r
1623 {\r
1624 public:\r
1625     enum\r
1626     {\r
1627         X_ROW = 0,\r
1628         Y_ROW,\r
1629         RESPONSE_ROW,\r
1630         ANGLE_ROW,\r
1631         OCTAVE_ROW,\r
1632         SIZE_ROW,\r
1633         ROWS_COUNT\r
1634     };\r
1635 \r
1636     enum\r
1637     {\r
1638         DEFAULT_FAST_THRESHOLD = 20\r
1639     };\r
1640 \r
1641     //! Constructor\r
1642     explicit ORB_GPU(int nFeatures = 500, float scaleFactor = 1.2f, int nLevels = 8, int edgeThreshold = 31,\r
1643                      int firstLevel = 0, int WTA_K = 2, int scoreType = 0, int patchSize = 31);\r
1644 \r
1645     //! Compute the ORB features on an image\r
1646     //! image - the image to compute the features (supports only CV_8UC1 images)\r
1647     //! mask - the mask to apply\r
1648     //! keypoints - the resulting keypoints\r
1649     void operator()(const GpuMat& image, const GpuMat& mask, std::vector<KeyPoint>& keypoints);\r
1650     void operator()(const GpuMat& image, const GpuMat& mask, GpuMat& keypoints);\r
1651 \r
1652     //! Compute the ORB features and descriptors on an image\r
1653     //! image - the image to compute the features (supports only CV_8UC1 images)\r
1654     //! mask - the mask to apply\r
1655     //! keypoints - the resulting keypoints\r
1656     //! descriptors - descriptors array\r
1657     void operator()(const GpuMat& image, const GpuMat& mask, std::vector<KeyPoint>& keypoints, GpuMat& descriptors);\r
1658     void operator()(const GpuMat& image, const GpuMat& mask, GpuMat& keypoints, GpuMat& descriptors);\r
1659 \r
1660     //! download keypoints from device to host memory\r
1661     static void downloadKeyPoints(GpuMat& d_keypoints, std::vector<KeyPoint>& keypoints);\r
1662     //! convert keypoints to KeyPoint vector\r
1663     static void convertKeyPoints(Mat& d_keypoints, std::vector<KeyPoint>& keypoints);\r
1664 \r
1665     //! returns the descriptor size in bytes\r
1666     inline int descriptorSize() const { return kBytes; }\r
1667 \r
1668     inline void setFastParams(int threshold, bool nonmaxSupression = true)\r
1669     {\r
1670         fastDetector_.threshold = threshold;\r
1671         fastDetector_.nonmaxSupression = nonmaxSupression;\r
1672     }\r
1673 \r
1674     //! release temporary buffer's memory\r
1675     void release();\r
1676 \r
1677     //! if true, image will be blurred before descriptors calculation\r
1678     bool blurForDescriptor;\r
1679 \r
1680 private:\r
1681     enum { kBytes = 32 };\r
1682 \r
1683     void buildScalePyramids(const GpuMat& image, const GpuMat& mask);\r
1684 \r
1685     void computeKeyPointsPyramid();\r
1686 \r
1687     void computeDescriptors(GpuMat& descriptors);\r
1688 \r
1689     void mergeKeyPoints(GpuMat& keypoints);\r
1690 \r
1691     int nFeatures_;\r
1692     float scaleFactor_;\r
1693     int nLevels_;\r
1694     int edgeThreshold_;\r
1695     int firstLevel_;\r
1696     int WTA_K_;\r
1697     int scoreType_;\r
1698     int patchSize_;\r
1699 \r
1700     // The number of desired features per scale\r
1701     std::vector<size_t> n_features_per_level_;\r
1702 \r
1703     // Points to compute BRIEF descriptors from\r
1704     GpuMat pattern_;\r
1705 \r
1706     std::vector<GpuMat> imagePyr_;\r
1707     std::vector<GpuMat> maskPyr_;\r
1708 \r
1709     GpuMat buf_;\r
1710 \r
1711     std::vector<GpuMat> keyPointsPyr_;\r
1712     std::vector<int> keyPointsCount_;\r
1713 \r
1714     FAST_GPU fastDetector_;\r
1715 \r
1716     Ptr<FilterEngine_GPU> blurFilter;\r
1717 \r
1718     GpuMat d_keypoints_;\r
1719 };\r
1720 \r
1721 ////////////////////////////////// Optical Flow //////////////////////////////////////////\r
1722 \r
1723 class CV_EXPORTS BroxOpticalFlow\r
1724 {\r
1725 public:\r
1726     BroxOpticalFlow(float alpha_, float gamma_, float scale_factor_, int inner_iterations_, int outer_iterations_, int solver_iterations_) :\r
1727         alpha(alpha_), gamma(gamma_), scale_factor(scale_factor_),\r
1728         inner_iterations(inner_iterations_), outer_iterations(outer_iterations_), solver_iterations(solver_iterations_)\r
1729     {\r
1730     }\r
1731 \r
1732     //! Compute optical flow\r
1733     //! frame0 - source frame (supports only CV_32FC1 type)\r
1734     //! frame1 - frame to track (with the same size and type as frame0)\r
1735     //! u      - flow horizontal component (along x axis)\r
1736     //! v      - flow vertical component (along y axis)\r
1737     void operator ()(const GpuMat& frame0, const GpuMat& frame1, GpuMat& u, GpuMat& v, Stream& stream = Stream::Null());\r
1738 \r
1739     //! flow smoothness\r
1740     float alpha;\r
1741 \r
1742     //! gradient constancy importance\r
1743     float gamma;\r
1744 \r
1745     //! pyramid scale factor\r
1746     float scale_factor;\r
1747 \r
1748     //! number of lagged non-linearity iterations (inner loop)\r
1749     int inner_iterations;\r
1750 \r
1751     //! number of warping iterations (number of pyramid levels)\r
1752     int outer_iterations;\r
1753 \r
1754     //! number of linear system solver iterations\r
1755     int solver_iterations;\r
1756 \r
1757     GpuMat buf;\r
1758 };\r
1759 \r
1760 class CV_EXPORTS GoodFeaturesToTrackDetector_GPU\r
1761 {\r
1762 public:\r
1763     explicit GoodFeaturesToTrackDetector_GPU(int maxCorners = 1000, double qualityLevel = 0.01, double minDistance = 0.0,\r
1764         int blockSize = 3, bool useHarrisDetector = false, double harrisK = 0.04);\r
1765 \r
1766     //! return 1 rows matrix with CV_32FC2 type\r
1767     void operator ()(const GpuMat& image, GpuMat& corners, const GpuMat& mask = GpuMat());\r
1768 \r
1769     int maxCorners;\r
1770     double qualityLevel;\r
1771     double minDistance;\r
1772 \r
1773     int blockSize;\r
1774     bool useHarrisDetector;\r
1775     double harrisK;\r
1776 \r
1777     void releaseMemory()\r
1778     {\r
1779         Dx_.release();\r
1780         Dy_.release();\r
1781         buf_.release();\r
1782         eig_.release();\r
1783         minMaxbuf_.release();\r
1784         tmpCorners_.release();\r
1785     }\r
1786 \r
1787 private:\r
1788     GpuMat Dx_;\r
1789     GpuMat Dy_;\r
1790     GpuMat buf_;\r
1791     GpuMat eig_;\r
1792     GpuMat minMaxbuf_;\r
1793     GpuMat tmpCorners_;\r
1794 };\r
1795 \r
1796 inline GoodFeaturesToTrackDetector_GPU::GoodFeaturesToTrackDetector_GPU(int maxCorners_, double qualityLevel_, double minDistance_,\r
1797         int blockSize_, bool useHarrisDetector_, double harrisK_)\r
1798 {\r
1799     maxCorners = maxCorners_;\r
1800     qualityLevel = qualityLevel_;\r
1801     minDistance = minDistance_;\r
1802     blockSize = blockSize_;\r
1803     useHarrisDetector = useHarrisDetector_;\r
1804     harrisK = harrisK_;\r
1805 }\r
1806 \r
1807 \r
1808 class CV_EXPORTS PyrLKOpticalFlow\r
1809 {\r
1810 public:\r
1811     PyrLKOpticalFlow();\r
1812 \r
1813     void sparse(const GpuMat& prevImg, const GpuMat& nextImg, const GpuMat& prevPts, GpuMat& nextPts,\r
1814         GpuMat& status, GpuMat* err = 0);\r
1815 \r
1816     void dense(const GpuMat& prevImg, const GpuMat& nextImg, GpuMat& u, GpuMat& v, GpuMat* err = 0);\r
1817 \r
1818     void releaseMemory();\r
1819 \r
1820     Size winSize;\r
1821     int maxLevel;\r
1822     int iters;\r
1823     bool useInitialFlow;\r
1824 \r
1825 private:\r
1826     vector<GpuMat> prevPyr_;\r
1827     vector<GpuMat> nextPyr_;\r
1828 \r
1829     GpuMat buf_;\r
1830 \r
1831     GpuMat uPyr_[2];\r
1832     GpuMat vPyr_[2];\r
1833 \r
1834     bool isDeviceArch11_;\r
1835 };\r
1836 \r
1837 \r
1838 class CV_EXPORTS FarnebackOpticalFlow\r
1839 {\r
1840 public:\r
1841     FarnebackOpticalFlow()\r
1842     {\r
1843         numLevels = 5;\r
1844         pyrScale = 0.5;\r
1845         fastPyramids = false;\r
1846         winSize = 13;\r
1847         numIters = 10;\r
1848         polyN = 5;\r
1849         polySigma = 1.1;\r
1850         flags = 0;\r
1851         isDeviceArch11_ = !DeviceInfo().supports(FEATURE_SET_COMPUTE_12);\r
1852     }\r
1853 \r
1854     int numLevels;\r
1855     double pyrScale;\r
1856     bool fastPyramids;\r
1857     int winSize;\r
1858     int numIters;\r
1859     int polyN;\r
1860     double polySigma;\r
1861     int flags;\r
1862 \r
1863     void operator ()(const GpuMat &frame0, const GpuMat &frame1, GpuMat &flowx, GpuMat &flowy, Stream &s = Stream::Null());\r
1864 \r
1865     void releaseMemory()\r
1866     {\r
1867         frames_[0].release();\r
1868         frames_[1].release();\r
1869         pyrLevel_[0].release();\r
1870         pyrLevel_[1].release();\r
1871         M_.release();\r
1872         bufM_.release();\r
1873         R_[0].release();\r
1874         R_[1].release();\r
1875         blurredFrame_[0].release();\r
1876         blurredFrame_[1].release();\r
1877         pyramid0_.clear();\r
1878         pyramid1_.clear();\r
1879     }\r
1880 \r
1881 private:\r
1882     void prepareGaussian(\r
1883             int n, double sigma, float *g, float *xg, float *xxg,\r
1884             double &ig11, double &ig03, double &ig33, double &ig55);\r
1885 \r
1886     void setPolynomialExpansionConsts(int n, double sigma);\r
1887 \r
1888     void updateFlow_boxFilter(\r
1889             const GpuMat& R0, const GpuMat& R1, GpuMat& flowx, GpuMat &flowy,\r
1890             GpuMat& M, GpuMat &bufM, int blockSize, bool updateMatrices, Stream streams[]);\r
1891 \r
1892     void updateFlow_gaussianBlur(\r
1893             const GpuMat& R0, const GpuMat& R1, GpuMat& flowx, GpuMat& flowy,\r
1894             GpuMat& M, GpuMat &bufM, int blockSize, bool updateMatrices, Stream streams[]);\r
1895 \r
1896     GpuMat frames_[2];\r
1897     GpuMat pyrLevel_[2], M_, bufM_, R_[2], blurredFrame_[2];\r
1898     std::vector<GpuMat> pyramid0_, pyramid1_;\r
1899 \r
1900     bool isDeviceArch11_;\r
1901 };\r
1902 \r
1903 \r
1904 //! Interpolate frames (images) using provided optical flow (displacement field).\r
1905 //! frame0   - frame 0 (32-bit floating point images, single channel)\r
1906 //! frame1   - frame 1 (the same type and size)\r
1907 //! fu       - forward horizontal displacement\r
1908 //! fv       - forward vertical displacement\r
1909 //! bu       - backward horizontal displacement\r
1910 //! bv       - backward vertical displacement\r
1911 //! pos      - new frame position\r
1912 //! newFrame - new frame\r
1913 //! buf      - temporary buffer, will have width x 6*height size, CV_32FC1 type and contain 6 GpuMat;\r
1914 //!            occlusion masks            0, occlusion masks            1,\r
1915 //!            interpolated forward flow  0, interpolated forward flow  1,\r
1916 //!            interpolated backward flow 0, interpolated backward flow 1\r
1917 //!\r
1918 CV_EXPORTS void interpolateFrames(const GpuMat& frame0, const GpuMat& frame1,\r
1919                                   const GpuMat& fu, const GpuMat& fv,\r
1920                                   const GpuMat& bu, const GpuMat& bv,\r
1921                                   float pos, GpuMat& newFrame, GpuMat& buf,\r
1922                                   Stream& stream = Stream::Null());\r
1923 \r
1924 CV_EXPORTS void createOpticalFlowNeedleMap(const GpuMat& u, const GpuMat& v, GpuMat& vertex, GpuMat& colors);\r
1925 \r
1926 \r
1927 //////////////////////// Background/foreground segmentation ////////////////////////\r
1928 \r
1929 // Foreground Object Detection from Videos Containing Complex Background.\r
1930 // Liyuan Li, Weimin Huang, Irene Y.H. Gu, and Qi Tian.\r
1931 // ACM MM2003 9p\r
1932 class CV_EXPORTS FGDStatModel\r
1933 {\r
1934 public:\r
1935     struct CV_EXPORTS Params\r
1936     {\r
1937         int Lc;  // Quantized levels per 'color' component. Power of two, typically 32, 64 or 128.\r
1938         int N1c; // Number of color vectors used to model normal background color variation at a given pixel.\r
1939         int N2c; // Number of color vectors retained at given pixel.  Must be > N1c, typically ~ 5/3 of N1c.\r
1940         // Used to allow the first N1c vectors to adapt over time to changing background.\r
1941 \r
1942         int Lcc;  // Quantized levels per 'color co-occurrence' component.  Power of two, typically 16, 32 or 64.\r
1943         int N1cc; // Number of color co-occurrence vectors used to model normal background color variation at a given pixel.\r
1944         int N2cc; // Number of color co-occurrence vectors retained at given pixel.  Must be > N1cc, typically ~ 5/3 of N1cc.\r
1945         // Used to allow the first N1cc vectors to adapt over time to changing background.\r
1946 \r
1947         bool is_obj_without_holes; // If TRUE we ignore holes within foreground blobs. Defaults to TRUE.\r
1948         int perform_morphing;     // Number of erode-dilate-erode foreground-blob cleanup iterations.\r
1949         // These erase one-pixel junk blobs and merge almost-touching blobs. Default value is 1.\r
1950 \r
1951         float alpha1; // How quickly we forget old background pixel values seen. Typically set to 0.1.\r
1952         float alpha2; // "Controls speed of feature learning". Depends on T. Typical value circa 0.005.\r
1953         float alpha3; // Alternate to alpha2, used (e.g.) for quicker initial convergence. Typical value 0.1.\r
1954 \r
1955         float delta;   // Affects color and color co-occurrence quantization, typically set to 2.\r
1956         float T;       // A percentage value which determines when new features can be recognized as new background. (Typically 0.9).\r
1957         float minArea; // Discard foreground blobs whose bounding box is smaller than this threshold.\r
1958 \r
1959         // default Params\r
1960         Params();\r
1961     };\r
1962 \r
1963     // out_cn - channels count in output result (can be 3 or 4)\r
1964     // 4-channels require more memory, but a bit faster\r
1965     explicit FGDStatModel(int out_cn = 3);\r
1966     explicit FGDStatModel(const cv::gpu::GpuMat& firstFrame, const Params& params = Params(), int out_cn = 3);\r
1967 \r
1968     ~FGDStatModel();\r
1969 \r
1970     void create(const cv::gpu::GpuMat& firstFrame, const Params& params = Params());\r
1971     void release();\r
1972 \r
1973     int update(const cv::gpu::GpuMat& curFrame);\r
1974 \r
1975     //8UC3 or 8UC4 reference background image\r
1976     cv::gpu::GpuMat background;\r
1977 \r
1978     //8UC1 foreground image\r
1979     cv::gpu::GpuMat foreground;\r
1980 \r
1981     std::vector< std::vector<cv::Point> > foreground_regions;\r
1982 \r
1983 private:\r
1984     FGDStatModel(const FGDStatModel&);\r
1985     FGDStatModel& operator=(const FGDStatModel&);\r
1986 \r
1987     class Impl;\r
1988     std::auto_ptr<Impl> impl_;\r
1989 };\r
1990 \r
1991 /*!\r
1992  Gaussian Mixture-based Backbround/Foreground Segmentation Algorithm\r
1993 \r
1994  The class implements the following algorithm:\r
1995  "An improved adaptive background mixture model for real-time tracking with shadow detection"\r
1996  P. KadewTraKuPong and R. Bowden,\r
1997  Proc. 2nd European Workshp on Advanced Video-Based Surveillance Systems, 2001."\r
1998  http://personal.ee.surrey.ac.uk/Personal/R.Bowden/publications/avbs01/avbs01.pdf\r
1999 */\r
2000 class CV_EXPORTS MOG_GPU\r
2001 {\r
2002 public:\r
2003     //! the default constructor\r
2004     MOG_GPU(int nmixtures = -1);\r
2005 \r
2006     //! re-initiaization method\r
2007     void initialize(Size frameSize, int frameType);\r
2008 \r
2009     //! the update operator\r
2010     void operator()(const GpuMat& frame, GpuMat& fgmask, float learningRate = 0.0f, Stream& stream = Stream::Null());\r
2011 \r
2012     //! computes a background image which are the mean of all background gaussians\r
2013     void getBackgroundImage(GpuMat& backgroundImage, Stream& stream = Stream::Null()) const;\r
2014 \r
2015     //! releases all inner buffers\r
2016     void release();\r
2017 \r
2018     int history;\r
2019     float varThreshold;\r
2020     float backgroundRatio;\r
2021     float noiseSigma;\r
2022 \r
2023 private:\r
2024     int nmixtures_;\r
2025 \r
2026     Size frameSize_;\r
2027     int frameType_;\r
2028     int nframes_;\r
2029 \r
2030     GpuMat weight_;\r
2031     GpuMat sortKey_;\r
2032     GpuMat mean_;\r
2033     GpuMat var_;\r
2034 };\r
2035 \r
2036 /*!\r
2037  The class implements the following algorithm:\r
2038  "Improved adaptive Gausian mixture model for background subtraction"\r
2039  Z.Zivkovic\r
2040  International Conference Pattern Recognition, UK, August, 2004.\r
2041  http://www.zoranz.net/Publications/zivkovic2004ICPR.pdf\r
2042 */\r
2043 class CV_EXPORTS MOG2_GPU\r
2044 {\r
2045 public:\r
2046     //! the default constructor\r
2047     MOG2_GPU(int nmixtures = -1);\r
2048 \r
2049     //! re-initiaization method\r
2050     void initialize(Size frameSize, int frameType);\r
2051 \r
2052     //! the update operator\r
2053     void operator()(const GpuMat& frame, GpuMat& fgmask, float learningRate = -1.0f, Stream& stream = Stream::Null());\r
2054 \r
2055     //! computes a background image which are the mean of all background gaussians\r
2056     void getBackgroundImage(GpuMat& backgroundImage, Stream& stream = Stream::Null()) const;\r
2057 \r
2058     //! releases all inner buffers\r
2059     void release();\r
2060 \r
2061     // parameters\r
2062     // you should call initialize after parameters changes\r
2063 \r
2064     int history;\r
2065 \r
2066     //! here it is the maximum allowed number of mixture components.\r
2067     //! Actual number is determined dynamically per pixel\r
2068     float varThreshold;\r
2069     // threshold on the squared Mahalanobis distance to decide if it is well described\r
2070     // by the background model or not. Related to Cthr from the paper.\r
2071     // This does not influence the update of the background. A typical value could be 4 sigma\r
2072     // and that is varThreshold=4*4=16; Corresponds to Tb in the paper.\r
2073 \r
2074     /////////////////////////\r
2075     // less important parameters - things you might change but be carefull\r
2076     ////////////////////////\r
2077 \r
2078     float backgroundRatio;\r
2079     // corresponds to fTB=1-cf from the paper\r
2080     // TB - threshold when the component becomes significant enough to be included into\r
2081     // the background model. It is the TB=1-cf from the paper. So I use cf=0.1 => TB=0.\r
2082     // For alpha=0.001 it means that the mode should exist for approximately 105 frames before\r
2083     // it is considered foreground\r
2084     // float noiseSigma;\r
2085     float varThresholdGen;\r
2086 \r
2087     //correspondts to Tg - threshold on the squared Mahalan. dist. to decide\r
2088     //when a sample is close to the existing components. If it is not close\r
2089     //to any a new component will be generated. I use 3 sigma => Tg=3*3=9.\r
2090     //Smaller Tg leads to more generated components and higher Tg might make\r
2091     //lead to small number of components but they can grow too large\r
2092     float fVarInit;\r
2093     float fVarMin;\r
2094     float fVarMax;\r
2095 \r
2096     //initial variance  for the newly generated components.\r
2097     //It will will influence the speed of adaptation. A good guess should be made.\r
2098     //A simple way is to estimate the typical standard deviation from the images.\r
2099     //I used here 10 as a reasonable value\r
2100     // min and max can be used to further control the variance\r
2101     float fCT; //CT - complexity reduction prior\r
2102     //this is related to the number of samples needed to accept that a component\r
2103     //actually exists. We use CT=0.05 of all the samples. By setting CT=0 you get\r
2104     //the standard Stauffer&Grimson algorithm (maybe not exact but very similar)\r
2105 \r
2106     //shadow detection parameters\r
2107     bool bShadowDetection; //default 1 - do shadow detection\r
2108     unsigned char nShadowDetection; //do shadow detection - insert this value as the detection result - 127 default value\r
2109     float fTau;\r
2110     // Tau - shadow threshold. The shadow is detected if the pixel is darker\r
2111     //version of the background. Tau is a threshold on how much darker the shadow can be.\r
2112     //Tau= 0.5 means that if pixel is more than 2 times darker then it is not shadow\r
2113     //See: Prati,Mikic,Trivedi,Cucchiarra,"Detecting Moving Shadows...",IEEE PAMI,2003.\r
2114 \r
2115 private:\r
2116     int nmixtures_;\r
2117 \r
2118     Size frameSize_;\r
2119     int frameType_;\r
2120     int nframes_;\r
2121 \r
2122     GpuMat weight_;\r
2123     GpuMat variance_;\r
2124     GpuMat mean_;\r
2125 \r
2126     GpuMat bgmodelUsedModes_; //keep track of number of modes per pixel\r
2127 };\r
2128 \r
2129 /*!\r
2130  * The class implements the following algorithm:\r
2131  * "ViBe: A universal background subtraction algorithm for video sequences"\r
2132  * O. Barnich and M. Van D Roogenbroeck\r
2133  * IEEE Transactions on Image Processing, 20(6) :1709-1724, June 2011\r
2134  */\r
2135 class CV_EXPORTS VIBE_GPU\r
2136 {\r
2137 public:\r
2138     //! the default constructor\r
2139     explicit VIBE_GPU(unsigned long rngSeed = 1234567);\r
2140 \r
2141     //! re-initiaization method\r
2142     void initialize(const GpuMat& firstFrame, Stream& stream = Stream::Null());\r
2143 \r
2144     //! the update operator\r
2145     void operator()(const GpuMat& frame, GpuMat& fgmask, Stream& stream = Stream::Null());\r
2146 \r
2147     //! releases all inner buffers\r
2148     void release();\r
2149 \r
2150     int nbSamples;         // number of samples per pixel\r
2151     int reqMatches;        // #_min\r
2152     int radius;            // R\r
2153     int subsamplingFactor; // amount of random subsampling\r
2154 \r
2155 private:\r
2156     Size frameSize_;\r
2157 \r
2158     unsigned long rngSeed_;\r
2159     GpuMat randStates_;\r
2160 \r
2161     GpuMat samples_;\r
2162 };\r
2163 \r
2164 /**\r
2165  * Background Subtractor module. Takes a series of images and returns a sequence of mask (8UC1)\r
2166  * images of the same size, where 255 indicates Foreground and 0 represents Background.\r
2167  * This class implements an algorithm described in "Visual Tracking of Human Visitors under\r
2168  * Variable-Lighting Conditions for a Responsive Audio Art Installation," A. Godbehere,\r
2169  * A. Matsukawa, K. Goldberg, American Control Conference, Montreal, June 2012.\r
2170  */\r
2171 class CV_EXPORTS GMG_GPU\r
2172 {\r
2173 public:\r
2174     GMG_GPU();\r
2175 \r
2176     /**\r
2177      * Validate parameters and set up data structures for appropriate frame size.\r
2178      * @param frameSize Input frame size\r
2179      * @param min       Minimum value taken on by pixels in image sequence. Usually 0\r
2180      * @param max       Maximum value taken on by pixels in image sequence. e.g. 1.0 or 255\r
2181      */\r
2182     void initialize(Size frameSize, float min = 0.0f, float max = 255.0f);\r
2183 \r
2184     /**\r
2185      * Performs single-frame background subtraction and builds up a statistical background image\r
2186      * model.\r
2187      * @param frame        Input frame\r
2188      * @param fgmask       Output mask image representing foreground and background pixels\r
2189      * @param stream       Stream for the asynchronous version\r
2190      */\r
2191     void operator ()(const GpuMat& frame, GpuMat& fgmask, float learningRate = -1.0f, Stream& stream = Stream::Null());\r
2192 \r
2193     //! Releases all inner buffers\r
2194     void release();\r
2195 \r
2196     //! Total number of distinct colors to maintain in histogram.\r
2197     int maxFeatures;\r
2198 \r
2199     //! Set between 0.0 and 1.0, determines how quickly features are "forgotten" from histograms.\r
2200     float learningRate;\r
2201 \r
2202     //! Number of frames of video to use to initialize histograms.\r
2203     int numInitializationFrames;\r
2204 \r
2205     //! Number of discrete levels in each channel to be used in histograms.\r
2206     int quantizationLevels;\r
2207 \r
2208     //! Prior probability that any given pixel is a background pixel. A sensitivity parameter.\r
2209     float backgroundPrior;\r
2210 \r
2211     //! Value above which pixel is determined to be FG.\r
2212     float decisionThreshold;\r
2213 \r
2214     //! Smoothing radius, in pixels, for cleaning up FG image.\r
2215     int smoothingRadius;\r
2216 \r
2217     //! Perform background model update.\r
2218     bool updateBackgroundModel;\r
2219 \r
2220 private:\r
2221     float maxVal_, minVal_;\r
2222 \r
2223     Size frameSize_;\r
2224 \r
2225     int frameNum_;\r
2226 \r
2227     GpuMat nfeatures_;\r
2228     GpuMat colors_;\r
2229     GpuMat weights_;\r
2230 \r
2231     Ptr<FilterEngine_GPU> boxFilter_;\r
2232     GpuMat buf_;\r
2233 };\r
2234 \r
2235 ////////////////////////////////// Video Encoding //////////////////////////////////\r
2236 \r
2237 // Works only under Windows\r
2238 // Supports olny H264 video codec and AVI files\r
2239 class CV_EXPORTS VideoWriter_GPU\r
2240 {\r
2241 public:\r
2242     struct EncoderParams;\r
2243 \r
2244     // Callbacks for video encoder, use it if you want to work with raw video stream\r
2245     class EncoderCallBack;\r
2246 \r
2247     enum SurfaceFormat\r
2248     {\r
2249         SF_UYVY = 0,\r
2250         SF_YUY2,\r
2251         SF_YV12,\r
2252         SF_NV12,\r
2253         SF_IYUV,\r
2254         SF_BGR,\r
2255         SF_GRAY = SF_BGR\r
2256     };\r
2257 \r
2258     VideoWriter_GPU();\r
2259     VideoWriter_GPU(const std::string& fileName, cv::Size frameSize, double fps, SurfaceFormat format = SF_BGR);\r
2260     VideoWriter_GPU(const std::string& fileName, cv::Size frameSize, double fps, const EncoderParams& params, SurfaceFormat format = SF_BGR);\r
2261     VideoWriter_GPU(const cv::Ptr<EncoderCallBack>& encoderCallback, cv::Size frameSize, double fps, SurfaceFormat format = SF_BGR);\r
2262     VideoWriter_GPU(const cv::Ptr<EncoderCallBack>& encoderCallback, cv::Size frameSize, double fps, const EncoderParams& params, SurfaceFormat format = SF_BGR);\r
2263     ~VideoWriter_GPU();\r
2264 \r
2265     // all methods throws cv::Exception if error occurs\r
2266     void open(const std::string& fileName, cv::Size frameSize, double fps, SurfaceFormat format = SF_BGR);\r
2267     void open(const std::string& fileName, cv::Size frameSize, double fps, const EncoderParams& params, SurfaceFormat format = SF_BGR);\r
2268     void open(const cv::Ptr<EncoderCallBack>& encoderCallback, cv::Size frameSize, double fps, SurfaceFormat format = SF_BGR);\r
2269     void open(const cv::Ptr<EncoderCallBack>& encoderCallback, cv::Size frameSize, double fps, const EncoderParams& params, SurfaceFormat format = SF_BGR);\r
2270 \r
2271     bool isOpened() const;\r
2272     void close();\r
2273 \r
2274     void write(const cv::gpu::GpuMat& image, bool lastFrame = false);\r
2275 \r
2276     struct CV_EXPORTS EncoderParams\r
2277     {\r
2278         int       P_Interval;      //    NVVE_P_INTERVAL,\r
2279         int       IDR_Period;      //    NVVE_IDR_PERIOD,\r
2280         int       DynamicGOP;      //    NVVE_DYNAMIC_GOP,\r
2281         int       RCType;          //    NVVE_RC_TYPE,\r
2282         int       AvgBitrate;      //    NVVE_AVG_BITRATE,\r
2283         int       PeakBitrate;     //    NVVE_PEAK_BITRATE,\r
2284         int       QP_Level_Intra;  //    NVVE_QP_LEVEL_INTRA,\r
2285         int       QP_Level_InterP; //    NVVE_QP_LEVEL_INTER_P,\r
2286         int       QP_Level_InterB; //    NVVE_QP_LEVEL_INTER_B,\r
2287         int       DeblockMode;     //    NVVE_DEBLOCK_MODE,\r
2288         int       ProfileLevel;    //    NVVE_PROFILE_LEVEL,\r
2289         int       ForceIntra;      //    NVVE_FORCE_INTRA,\r
2290         int       ForceIDR;        //    NVVE_FORCE_IDR,\r
2291         int       ClearStat;       //    NVVE_CLEAR_STAT,\r
2292         int       DIMode;          //    NVVE_SET_DEINTERLACE,\r
2293         int       Presets;         //    NVVE_PRESETS,\r
2294         int       DisableCabac;    //    NVVE_DISABLE_CABAC,\r
2295         int       NaluFramingType; //    NVVE_CONFIGURE_NALU_FRAMING_TYPE\r
2296         int       DisableSPSPPS;   //    NVVE_DISABLE_SPS_PPS\r
2297 \r
2298         EncoderParams();\r
2299         explicit EncoderParams(const std::string& configFile);\r
2300 \r
2301         void load(const std::string& configFile);\r
2302         void save(const std::string& configFile) const;\r
2303     };\r
2304 \r
2305     EncoderParams getParams() const;\r
2306 \r
2307     class CV_EXPORTS EncoderCallBack\r
2308     {\r
2309     public:\r
2310         enum PicType\r
2311         {\r
2312             IFRAME = 1,\r
2313             PFRAME = 2,\r
2314             BFRAME = 3\r
2315         };\r
2316 \r
2317         virtual ~EncoderCallBack() {}\r
2318 \r
2319         // callback function to signal the start of bitstream that is to be encoded\r
2320         // must return pointer to buffer\r
2321         virtual uchar* acquireBitStream(int* bufferSize) = 0;\r
2322 \r
2323         // callback function to signal that the encoded bitstream is ready to be written to file\r
2324         virtual void releaseBitStream(unsigned char* data, int size) = 0;\r
2325 \r
2326         // callback function to signal that the encoding operation on the frame has started\r
2327         virtual void onBeginFrame(int frameNumber, PicType picType) = 0;\r
2328 \r
2329         // callback function signals that the encoding operation on the frame has finished\r
2330         virtual void onEndFrame(int frameNumber, PicType picType) = 0;\r
2331     };\r
2332 \r
2333 private:\r
2334     VideoWriter_GPU(const VideoWriter_GPU&);\r
2335     VideoWriter_GPU& operator=(const VideoWriter_GPU&);\r
2336 \r
2337     class Impl;\r
2338     std::auto_ptr<Impl> impl_;\r
2339 };\r
2340 \r
2341 \r
2342 ////////////////////////////////// Video Decoding //////////////////////////////////////////\r
2343 \r
2344 namespace detail\r
2345 {\r
2346     class FrameQueue;\r
2347     class VideoParser;\r
2348 }\r
2349 \r
2350 class CV_EXPORTS VideoReader_GPU\r
2351 {\r
2352 public:\r
2353     enum Codec\r
2354     {\r
2355         MPEG1 = 0,\r
2356         MPEG2,\r
2357         MPEG4,\r
2358         VC1,\r
2359         H264,\r
2360         JPEG,\r
2361         H264_SVC,\r
2362         H264_MVC,\r
2363 \r
2364         Uncompressed_YUV420 = (('I'<<24)|('Y'<<16)|('U'<<8)|('V')),   // Y,U,V (4:2:0)\r
2365         Uncompressed_YV12   = (('Y'<<24)|('V'<<16)|('1'<<8)|('2')),   // Y,V,U (4:2:0)\r
2366         Uncompressed_NV12   = (('N'<<24)|('V'<<16)|('1'<<8)|('2')),   // Y,UV  (4:2:0)\r
2367         Uncompressed_YUYV   = (('Y'<<24)|('U'<<16)|('Y'<<8)|('V')),   // YUYV/YUY2 (4:2:2)\r
2368         Uncompressed_UYVY   = (('U'<<24)|('Y'<<16)|('V'<<8)|('Y')),   // UYVY (4:2:2)\r
2369     };\r
2370 \r
2371     enum ChromaFormat\r
2372     {\r
2373         Monochrome=0,\r
2374         YUV420,\r
2375         YUV422,\r
2376         YUV444,\r
2377     };\r
2378 \r
2379     struct FormatInfo\r
2380     {\r
2381         Codec codec;\r
2382         ChromaFormat chromaFormat;\r
2383         int width;\r
2384         int height;\r
2385     };\r
2386 \r
2387     class VideoSource;\r
2388 \r
2389     VideoReader_GPU();\r
2390     explicit VideoReader_GPU(const std::string& filename);\r
2391     explicit VideoReader_GPU(const cv::Ptr<VideoSource>& source);\r
2392 \r
2393     ~VideoReader_GPU();\r
2394 \r
2395     void open(const std::string& filename);\r
2396     void open(const cv::Ptr<VideoSource>& source);\r
2397     bool isOpened() const;\r
2398 \r
2399     void close();\r
2400 \r
2401     bool read(GpuMat& image);\r
2402 \r
2403     FormatInfo format() const;\r
2404     void dumpFormat(std::ostream& st);\r
2405 \r
2406     class CV_EXPORTS VideoSource\r
2407     {\r
2408     public:\r
2409         VideoSource() : frameQueue_(0), videoParser_(0) {}\r
2410         virtual ~VideoSource() {}\r
2411 \r
2412         virtual FormatInfo format() const = 0;\r
2413         virtual void start() = 0;\r
2414         virtual void stop() = 0;\r
2415         virtual bool isStarted() const = 0;\r
2416         virtual bool hasError() const = 0;\r
2417 \r
2418         void setFrameQueue(detail::FrameQueue* frameQueue) { frameQueue_ = frameQueue; }\r
2419         void setVideoParser(detail::VideoParser* videoParser) { videoParser_ = videoParser; }\r
2420 \r
2421     protected:\r
2422         bool parseVideoData(const uchar* data, size_t size, bool endOfStream = false);\r
2423 \r
2424     private:\r
2425         VideoSource(const VideoSource&);\r
2426         VideoSource& operator =(const VideoSource&);\r
2427 \r
2428         detail::FrameQueue* frameQueue_;\r
2429         detail::VideoParser* videoParser_;\r
2430     };\r
2431 \r
2432 private:\r
2433     VideoReader_GPU(const VideoReader_GPU&);\r
2434     VideoReader_GPU& operator =(const VideoReader_GPU&);\r
2435 \r
2436     class Impl;\r
2437     std::auto_ptr<Impl> impl_;\r
2438 };\r
2439 \r
2440 //! removes points (CV_32FC2, single row matrix) with zero mask value\r
2441 CV_EXPORTS void compactPoints(GpuMat &points0, GpuMat &points1, const GpuMat &mask);\r
2442 \r
2443 CV_EXPORTS void calcWobbleSuppressionMaps(\r
2444         int left, int idx, int right, Size size, const Mat &ml, const Mat &mr,\r
2445         GpuMat &mapx, GpuMat &mapy);\r
2446 \r
2447 } // namespace gpu\r
2448 \r
2449 } // namespace cv\r
2450 \r
2451 #endif /* __OPENCV_GPU_HPP__ */\r