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