cuda.hpp 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049
  1. /*M///////////////////////////////////////////////////////////////////////////////////////
  2. //
  3. // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
  4. //
  5. // By downloading, copying, installing or using the software you agree to this license.
  6. // If you do not agree to this license, do not download, install,
  7. // copy or use the software.
  8. //
  9. //
  10. // License Agreement
  11. // For Open Source Computer Vision Library
  12. //
  13. // Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
  14. // Copyright (C) 2009, Willow Garage Inc., all rights reserved.
  15. // Copyright (C) 2013, OpenCV Foundation, all rights reserved.
  16. // Third party copyrights are property of their respective owners.
  17. //
  18. // Redistribution and use in source and binary forms, with or without modification,
  19. // are permitted provided that the following conditions are met:
  20. //
  21. // * Redistribution's of source code must retain the above copyright notice,
  22. // this list of conditions and the following disclaimer.
  23. //
  24. // * Redistribution's in binary form must reproduce the above copyright notice,
  25. // this list of conditions and the following disclaimer in the documentation
  26. // and/or other materials provided with the distribution.
  27. //
  28. // * The name of the copyright holders may not be used to endorse or promote products
  29. // derived from this software without specific prior written permission.
  30. //
  31. // This software is provided by the copyright holders and contributors "as is" and
  32. // any express or implied warranties, including, but not limited to, the implied
  33. // warranties of merchantability and fitness for a particular purpose are disclaimed.
  34. // In no event shall the Intel Corporation or contributors be liable for any direct,
  35. // indirect, incidental, special, exemplary, or consequential damages
  36. // (including, but not limited to, procurement of substitute goods or services;
  37. // loss of use, data, or profits; or business interruption) however caused
  38. // and on any theory of liability, whether in contract, strict liability,
  39. // or tort (including negligence or otherwise) arising in any way out of
  40. // the use of this software, even if advised of the possibility of such damage.
  41. //
  42. //M*/
  43. #ifndef OPENCV_CORE_CUDA_HPP
  44. #define OPENCV_CORE_CUDA_HPP
  45. #ifndef __cplusplus
  46. # error cuda.hpp header must be compiled as C++
  47. #endif
  48. #include "opencv2/core.hpp"
  49. #include "opencv2/core/cuda_types.hpp"
  50. /**
  51. @defgroup cuda CUDA-accelerated Computer Vision
  52. @{
  53. @defgroup cudacore Core part
  54. @{
  55. @defgroup cudacore_init Initialization and Information
  56. @defgroup cudacore_struct Data Structures
  57. @}
  58. @}
  59. */
  60. namespace cv { namespace cuda {
  61. //! @addtogroup cudacore_struct
  62. //! @{
  63. //===================================================================================
  64. // GpuMat
  65. //===================================================================================
  66. /** @brief Base storage class for GPU memory with reference counting.
  67. Its interface matches the Mat interface with the following limitations:
  68. - no arbitrary dimensions support (only 2D)
  69. - no functions that return references to their data (because references on GPU are not valid for
  70. CPU)
  71. - no expression templates technique support
  72. Beware that the latter limitation may lead to overloaded matrix operators that cause memory
  73. allocations. The GpuMat class is convertible to cuda::PtrStepSz and cuda::PtrStep so it can be
  74. passed directly to the kernel.
  75. @note In contrast with Mat, in most cases GpuMat::isContinuous() == false . This means that rows are
  76. aligned to a size depending on the hardware. Single-row GpuMat is always a continuous matrix.
  77. @note You are not recommended to leave static or global GpuMat variables allocated, that is, to rely
  78. on its destructor. The destruction order of such variables and CUDA context is undefined. GPU memory
  79. release function returns error if the CUDA context has been destroyed before.
  80. Some member functions are described as a "Blocking Call" while some are described as a
  81. "Non-Blocking Call". Blocking functions are synchronous to host. It is guaranteed that the GPU
  82. operation is finished when the function returns. However, non-blocking functions are asynchronous to
  83. host. Those functions may return even if the GPU operation is not finished.
  84. Compared to their blocking counterpart, non-blocking functions accept Stream as an additional
  85. argument. If a non-default stream is passed, the GPU operation may overlap with operations in other
  86. streams.
  87. @sa Mat
  88. */
  89. class CV_EXPORTS_W GpuMat
  90. {
  91. public:
  92. class CV_EXPORTS_W Allocator
  93. {
  94. public:
  95. virtual ~Allocator() {}
  96. // allocator must fill data, step and refcount fields
  97. virtual bool allocate(GpuMat* mat, int rows, int cols, size_t elemSize) = 0;
  98. virtual void free(GpuMat* mat) = 0;
  99. };
  100. //! default allocator
  101. CV_WRAP static GpuMat::Allocator* defaultAllocator();
  102. CV_WRAP static void setDefaultAllocator(GpuMat::Allocator* allocator);
  103. //! default constructor
  104. CV_WRAP explicit GpuMat(GpuMat::Allocator* allocator = GpuMat::defaultAllocator());
  105. //! constructs GpuMat of the specified size and type
  106. CV_WRAP GpuMat(int rows, int cols, int type, GpuMat::Allocator* allocator = GpuMat::defaultAllocator());
  107. CV_WRAP GpuMat(Size size, int type, GpuMat::Allocator* allocator = GpuMat::defaultAllocator());
  108. //! constucts GpuMat and fills it with the specified value _s
  109. CV_WRAP GpuMat(int rows, int cols, int type, Scalar s, GpuMat::Allocator* allocator = GpuMat::defaultAllocator());
  110. CV_WRAP GpuMat(Size size, int type, Scalar s, GpuMat::Allocator* allocator = GpuMat::defaultAllocator());
  111. //! copy constructor
  112. CV_WRAP GpuMat(const GpuMat& m);
  113. //! constructor for GpuMat headers pointing to user-allocated data
  114. GpuMat(int rows, int cols, int type, void* data, size_t step = Mat::AUTO_STEP);
  115. GpuMat(Size size, int type, void* data, size_t step = Mat::AUTO_STEP);
  116. //! creates a GpuMat header for a part of the bigger matrix
  117. CV_WRAP GpuMat(const GpuMat& m, Range rowRange, Range colRange);
  118. CV_WRAP GpuMat(const GpuMat& m, Rect roi);
  119. //! builds GpuMat from host memory (Blocking call)
  120. CV_WRAP explicit GpuMat(InputArray arr, GpuMat::Allocator* allocator = GpuMat::defaultAllocator());
  121. //! destructor - calls release()
  122. ~GpuMat();
  123. //! assignment operators
  124. GpuMat& operator =(const GpuMat& m);
  125. //! allocates new GpuMat data unless the GpuMat already has specified size and type
  126. CV_WRAP void create(int rows, int cols, int type);
  127. CV_WRAP void create(Size size, int type);
  128. //! decreases reference counter, deallocate the data when reference counter reaches 0
  129. void release();
  130. //! swaps with other smart pointer
  131. CV_WRAP void swap(GpuMat& mat);
  132. /** @brief Performs data upload to GpuMat (Blocking call)
  133. This function copies data from host memory to device memory. As being a blocking call, it is
  134. guaranteed that the copy operation is finished when this function returns.
  135. */
  136. CV_WRAP void upload(InputArray arr);
  137. /** @brief Performs data upload to GpuMat (Non-Blocking call)
  138. This function copies data from host memory to device memory. As being a non-blocking call, this
  139. function may return even if the copy operation is not finished.
  140. The copy operation may be overlapped with operations in other non-default streams if \p stream is
  141. not the default stream and \p dst is HostMem allocated with HostMem::PAGE_LOCKED option.
  142. */
  143. CV_WRAP void upload(InputArray arr, Stream& stream);
  144. /** @brief Performs data download from GpuMat (Blocking call)
  145. This function copies data from device memory to host memory. As being a blocking call, it is
  146. guaranteed that the copy operation is finished when this function returns.
  147. */
  148. CV_WRAP void download(OutputArray dst) const;
  149. /** @brief Performs data download from GpuMat (Non-Blocking call)
  150. This function copies data from device memory to host memory. As being a non-blocking call, this
  151. function may return even if the copy operation is not finished.
  152. The copy operation may be overlapped with operations in other non-default streams if \p stream is
  153. not the default stream and \p dst is HostMem allocated with HostMem::PAGE_LOCKED option.
  154. */
  155. CV_WRAP void download(OutputArray dst, Stream& stream) const;
  156. //! returns deep copy of the GpuMat, i.e. the data is copied
  157. CV_WRAP GpuMat clone() const;
  158. //! copies the GpuMat content to device memory (Blocking call)
  159. CV_WRAP void copyTo(OutputArray dst) const;
  160. //! copies the GpuMat content to device memory (Non-Blocking call)
  161. CV_WRAP void copyTo(OutputArray dst, Stream& stream) const;
  162. //! copies those GpuMat elements to "m" that are marked with non-zero mask elements (Blocking call)
  163. CV_WRAP void copyTo(OutputArray dst, InputArray mask) const;
  164. //! copies those GpuMat elements to "m" that are marked with non-zero mask elements (Non-Blocking call)
  165. CV_WRAP void copyTo(OutputArray dst, InputArray mask, Stream& stream) const;
  166. //! sets some of the GpuMat elements to s (Blocking call)
  167. CV_WRAP GpuMat& setTo(Scalar s);
  168. //! sets some of the GpuMat elements to s (Non-Blocking call)
  169. CV_WRAP GpuMat& setTo(Scalar s, Stream& stream);
  170. //! sets some of the GpuMat elements to s, according to the mask (Blocking call)
  171. CV_WRAP GpuMat& setTo(Scalar s, InputArray mask);
  172. //! sets some of the GpuMat elements to s, according to the mask (Non-Blocking call)
  173. CV_WRAP GpuMat& setTo(Scalar s, InputArray mask, Stream& stream);
  174. //! converts GpuMat to another datatype (Blocking call)
  175. CV_WRAP void convertTo(OutputArray dst, int rtype) const;
  176. //! converts GpuMat to another datatype (Non-Blocking call)
  177. CV_WRAP void convertTo(OutputArray dst, int rtype, Stream& stream) const;
  178. //! converts GpuMat to another datatype with scaling (Blocking call)
  179. CV_WRAP void convertTo(OutputArray dst, int rtype, double alpha, double beta = 0.0) const;
  180. //! converts GpuMat to another datatype with scaling (Non-Blocking call)
  181. CV_WRAP void convertTo(OutputArray dst, int rtype, double alpha, Stream& stream) const;
  182. //! converts GpuMat to another datatype with scaling (Non-Blocking call)
  183. CV_WRAP void convertTo(OutputArray dst, int rtype, double alpha, double beta, Stream& stream) const;
  184. CV_WRAP void assignTo(GpuMat& m, int type = -1) const;
  185. //! returns pointer to y-th row
  186. uchar* ptr(int y = 0);
  187. const uchar* ptr(int y = 0) const;
  188. //! template version of the above method
  189. template<typename _Tp> _Tp* ptr(int y = 0);
  190. template<typename _Tp> const _Tp* ptr(int y = 0) const;
  191. template <typename _Tp> operator PtrStepSz<_Tp>() const;
  192. template <typename _Tp> operator PtrStep<_Tp>() const;
  193. //! returns a new GpuMat header for the specified row
  194. CV_WRAP GpuMat row(int y) const;
  195. //! returns a new GpuMat header for the specified column
  196. CV_WRAP GpuMat col(int x) const;
  197. //! ... for the specified row span
  198. CV_WRAP GpuMat rowRange(int startrow, int endrow) const;
  199. CV_WRAP GpuMat rowRange(Range r) const;
  200. //! ... for the specified column span
  201. CV_WRAP GpuMat colRange(int startcol, int endcol) const;
  202. CV_WRAP GpuMat colRange(Range r) const;
  203. //! extracts a rectangular sub-GpuMat (this is a generalized form of row, rowRange etc.)
  204. GpuMat operator ()(Range rowRange, Range colRange) const;
  205. GpuMat operator ()(Rect roi) const;
  206. //! creates alternative GpuMat header for the same data, with different
  207. //! number of channels and/or different number of rows
  208. CV_WRAP GpuMat reshape(int cn, int rows = 0) const;
  209. //! locates GpuMat header within a parent GpuMat
  210. CV_WRAP void locateROI(Size& wholeSize, Point& ofs) const;
  211. //! moves/resizes the current GpuMat ROI inside the parent GpuMat
  212. CV_WRAP GpuMat& adjustROI(int dtop, int dbottom, int dleft, int dright);
  213. //! returns true iff the GpuMat data is continuous
  214. //! (i.e. when there are no gaps between successive rows)
  215. CV_WRAP bool isContinuous() const;
  216. //! returns element size in bytes
  217. CV_WRAP size_t elemSize() const;
  218. //! returns the size of element channel in bytes
  219. CV_WRAP size_t elemSize1() const;
  220. //! returns element type
  221. CV_WRAP int type() const;
  222. //! returns element type
  223. CV_WRAP int depth() const;
  224. //! returns number of channels
  225. CV_WRAP int channels() const;
  226. //! returns step/elemSize1()
  227. CV_WRAP size_t step1() const;
  228. //! returns GpuMat size : width == number of columns, height == number of rows
  229. CV_WRAP Size size() const;
  230. //! returns true if GpuMat data is NULL
  231. CV_WRAP bool empty() const;
  232. //! internal use method: updates the continuity flag
  233. CV_WRAP void updateContinuityFlag();
  234. /*! includes several bit-fields:
  235. - the magic signature
  236. - continuity flag
  237. - depth
  238. - number of channels
  239. */
  240. int flags;
  241. //! the number of rows and columns
  242. int rows, cols;
  243. //! a distance between successive rows in bytes; includes the gap if any
  244. CV_PROP size_t step;
  245. //! pointer to the data
  246. uchar* data;
  247. //! pointer to the reference counter;
  248. //! when GpuMat points to user-allocated data, the pointer is NULL
  249. int* refcount;
  250. //! helper fields used in locateROI and adjustROI
  251. uchar* datastart;
  252. const uchar* dataend;
  253. //! allocator
  254. Allocator* allocator;
  255. };
  256. /** @brief Creates a continuous matrix.
  257. @param rows Row count.
  258. @param cols Column count.
  259. @param type Type of the matrix.
  260. @param arr Destination matrix. This parameter changes only if it has a proper type and area (
  261. \f$\texttt{rows} \times \texttt{cols}\f$ ).
  262. Matrix is called continuous if its elements are stored continuously, that is, without gaps at the
  263. end of each row.
  264. */
  265. CV_EXPORTS_W void createContinuous(int rows, int cols, int type, OutputArray arr);
  266. /** @brief Ensures that the size of a matrix is big enough and the matrix has a proper type.
  267. @param rows Minimum desired number of rows.
  268. @param cols Minimum desired number of columns.
  269. @param type Desired matrix type.
  270. @param arr Destination matrix.
  271. The function does not reallocate memory if the matrix has proper attributes already.
  272. */
  273. CV_EXPORTS_W void ensureSizeIsEnough(int rows, int cols, int type, OutputArray arr);
  274. /** @brief BufferPool for use with CUDA streams
  275. BufferPool utilizes Stream's allocator to create new buffers for GpuMat's. It is
  276. only useful when enabled with #setBufferPoolUsage.
  277. @code
  278. setBufferPoolUsage(true);
  279. @endcode
  280. @note #setBufferPoolUsage must be called \em before any Stream declaration.
  281. Users may specify custom allocator for Stream and may implement their own stream based
  282. functions utilizing the same underlying GPU memory management.
  283. If custom allocator is not specified, BufferPool utilizes StackAllocator by
  284. default. StackAllocator allocates a chunk of GPU device memory beforehand,
  285. and when GpuMat is declared later on, it is given the pre-allocated memory.
  286. This kind of strategy reduces the number of calls for memory allocating APIs
  287. such as cudaMalloc or cudaMallocPitch.
  288. Below is an example that utilizes BufferPool with StackAllocator:
  289. @code
  290. #include <opencv2/opencv.hpp>
  291. using namespace cv;
  292. using namespace cv::cuda
  293. int main()
  294. {
  295. setBufferPoolUsage(true); // Tell OpenCV that we are going to utilize BufferPool
  296. setBufferPoolConfig(getDevice(), 1024 * 1024 * 64, 2); // Allocate 64 MB, 2 stacks (default is 10 MB, 5 stacks)
  297. Stream stream1, stream2; // Each stream uses 1 stack
  298. BufferPool pool1(stream1), pool2(stream2);
  299. GpuMat d_src1 = pool1.getBuffer(4096, 4096, CV_8UC1); // 16MB
  300. GpuMat d_dst1 = pool1.getBuffer(4096, 4096, CV_8UC3); // 48MB, pool1 is now full
  301. GpuMat d_src2 = pool2.getBuffer(1024, 1024, CV_8UC1); // 1MB
  302. GpuMat d_dst2 = pool2.getBuffer(1024, 1024, CV_8UC3); // 3MB
  303. cvtColor(d_src1, d_dst1, CV_GRAY2BGR, 0, stream1);
  304. cvtColor(d_src2, d_dst2, CV_GRAY2BGR, 0, stream2);
  305. }
  306. @endcode
  307. If we allocate another GpuMat on pool1 in the above example, it will be carried out by
  308. the DefaultAllocator since the stack for pool1 is full.
  309. @code
  310. GpuMat d_add1 = pool1.getBuffer(1024, 1024, CV_8UC1); // Stack for pool1 is full, memory is allocated with DefaultAllocator
  311. @endcode
  312. If a third stream is declared in the above example, allocating with #getBuffer
  313. within that stream will also be carried out by the DefaultAllocator because we've run out of
  314. stacks.
  315. @code
  316. Stream stream3; // Only 2 stacks were allocated, we've run out of stacks
  317. BufferPool pool3(stream3);
  318. GpuMat d_src3 = pool3.getBuffer(1024, 1024, CV_8UC1); // Memory is allocated with DefaultAllocator
  319. @endcode
  320. @warning When utilizing StackAllocator, deallocation order is important.
  321. Just like a stack, deallocation must be done in LIFO order. Below is an example of
  322. erroneous usage that violates LIFO rule. If OpenCV is compiled in Debug mode, this
  323. sample code will emit CV_Assert error.
  324. @code
  325. int main()
  326. {
  327. setBufferPoolUsage(true); // Tell OpenCV that we are going to utilize BufferPool
  328. Stream stream; // A default size (10 MB) stack is allocated to this stream
  329. BufferPool pool(stream);
  330. GpuMat mat1 = pool.getBuffer(1024, 1024, CV_8UC1); // Allocate mat1 (1MB)
  331. GpuMat mat2 = pool.getBuffer(1024, 1024, CV_8UC1); // Allocate mat2 (1MB)
  332. mat1.release(); // erroneous usage : mat2 must be deallocated before mat1
  333. }
  334. @endcode
  335. Since C++ local variables are destroyed in the reverse order of construction,
  336. the code sample below satisfies the LIFO rule. Local GpuMat's are deallocated
  337. and the corresponding memory is automatically returned to the pool for later usage.
  338. @code
  339. int main()
  340. {
  341. setBufferPoolUsage(true); // Tell OpenCV that we are going to utilize BufferPool
  342. setBufferPoolConfig(getDevice(), 1024 * 1024 * 64, 2); // Allocate 64 MB, 2 stacks (default is 10 MB, 5 stacks)
  343. Stream stream1, stream2; // Each stream uses 1 stack
  344. BufferPool pool1(stream1), pool2(stream2);
  345. for (int i = 0; i < 10; i++)
  346. {
  347. GpuMat d_src1 = pool1.getBuffer(4096, 4096, CV_8UC1); // 16MB
  348. GpuMat d_dst1 = pool1.getBuffer(4096, 4096, CV_8UC3); // 48MB, pool1 is now full
  349. GpuMat d_src2 = pool2.getBuffer(1024, 1024, CV_8UC1); // 1MB
  350. GpuMat d_dst2 = pool2.getBuffer(1024, 1024, CV_8UC3); // 3MB
  351. d_src1.setTo(Scalar(i), stream1);
  352. d_src2.setTo(Scalar(i), stream2);
  353. cvtColor(d_src1, d_dst1, CV_GRAY2BGR, 0, stream1);
  354. cvtColor(d_src2, d_dst2, CV_GRAY2BGR, 0, stream2);
  355. // The order of destruction of the local variables is:
  356. // d_dst2 => d_src2 => d_dst1 => d_src1
  357. // LIFO rule is satisfied, this code runs without error
  358. }
  359. }
  360. @endcode
  361. */
  362. class CV_EXPORTS_W BufferPool
  363. {
  364. public:
  365. //! Gets the BufferPool for the given stream.
  366. explicit BufferPool(Stream& stream);
  367. //! Allocates a new GpuMat of given size and type.
  368. CV_WRAP GpuMat getBuffer(int rows, int cols, int type);
  369. //! Allocates a new GpuMat of given size and type.
  370. CV_WRAP GpuMat getBuffer(Size size, int type) { return getBuffer(size.height, size.width, type); }
  371. //! Returns the allocator associated with the stream.
  372. CV_WRAP Ptr<GpuMat::Allocator> getAllocator() const { return allocator_; }
  373. private:
  374. Ptr<GpuMat::Allocator> allocator_;
  375. };
  376. //! BufferPool management (must be called before Stream creation)
  377. CV_EXPORTS_W void setBufferPoolUsage(bool on);
  378. CV_EXPORTS_W void setBufferPoolConfig(int deviceId, size_t stackSize, int stackCount);
  379. //===================================================================================
  380. // HostMem
  381. //===================================================================================
  382. /** @brief Class with reference counting wrapping special memory type allocation functions from CUDA.
  383. Its interface is also Mat-like but with additional memory type parameters.
  384. - **PAGE_LOCKED** sets a page locked memory type used commonly for fast and asynchronous
  385. uploading/downloading data from/to GPU.
  386. - **SHARED** specifies a zero copy memory allocation that enables mapping the host memory to GPU
  387. address space, if supported.
  388. - **WRITE_COMBINED** sets the write combined buffer that is not cached by CPU. Such buffers are
  389. used to supply GPU with data when GPU only reads it. The advantage is a better CPU cache
  390. utilization.
  391. @note Allocation size of such memory types is usually limited. For more details, see *CUDA 2.2
  392. Pinned Memory APIs* document or *CUDA C Programming Guide*.
  393. */
  394. class CV_EXPORTS_W HostMem
  395. {
  396. public:
  397. enum AllocType { PAGE_LOCKED = 1, SHARED = 2, WRITE_COMBINED = 4 };
  398. static MatAllocator* getAllocator(HostMem::AllocType alloc_type = HostMem::AllocType::PAGE_LOCKED);
  399. CV_WRAP explicit HostMem(HostMem::AllocType alloc_type = HostMem::AllocType::PAGE_LOCKED);
  400. HostMem(const HostMem& m);
  401. CV_WRAP HostMem(int rows, int cols, int type, HostMem::AllocType alloc_type = HostMem::AllocType::PAGE_LOCKED);
  402. CV_WRAP HostMem(Size size, int type, HostMem::AllocType alloc_type = HostMem::AllocType::PAGE_LOCKED);
  403. //! creates from host memory with coping data
  404. CV_WRAP explicit HostMem(InputArray arr, HostMem::AllocType alloc_type = HostMem::AllocType::PAGE_LOCKED);
  405. ~HostMem();
  406. HostMem& operator =(const HostMem& m);
  407. //! swaps with other smart pointer
  408. CV_WRAP void swap(HostMem& b);
  409. //! returns deep copy of the matrix, i.e. the data is copied
  410. CV_WRAP HostMem clone() const;
  411. //! allocates new matrix data unless the matrix already has specified size and type.
  412. CV_WRAP void create(int rows, int cols, int type);
  413. void create(Size size, int type);
  414. //! creates alternative HostMem header for the same data, with different
  415. //! number of channels and/or different number of rows
  416. CV_WRAP HostMem reshape(int cn, int rows = 0) const;
  417. //! decrements reference counter and released memory if needed.
  418. void release();
  419. //! returns matrix header with disabled reference counting for HostMem data.
  420. CV_WRAP Mat createMatHeader() const;
  421. /** @brief Maps CPU memory to GPU address space and creates the cuda::GpuMat header without reference counting
  422. for it.
  423. This can be done only if memory was allocated with the SHARED flag and if it is supported by the
  424. hardware. Laptops often share video and CPU memory, so address spaces can be mapped, which
  425. eliminates an extra copy.
  426. */
  427. GpuMat createGpuMatHeader() const;
  428. // Please see cv::Mat for descriptions
  429. CV_WRAP bool isContinuous() const;
  430. CV_WRAP size_t elemSize() const;
  431. CV_WRAP size_t elemSize1() const;
  432. CV_WRAP int type() const;
  433. CV_WRAP int depth() const;
  434. CV_WRAP int channels() const;
  435. CV_WRAP size_t step1() const;
  436. CV_WRAP Size size() const;
  437. CV_WRAP bool empty() const;
  438. // Please see cv::Mat for descriptions
  439. int flags;
  440. int rows, cols;
  441. CV_PROP size_t step;
  442. uchar* data;
  443. int* refcount;
  444. uchar* datastart;
  445. const uchar* dataend;
  446. AllocType alloc_type;
  447. };
  448. /** @brief Page-locks the memory of matrix and maps it for the device(s).
  449. @param m Input matrix.
  450. */
  451. CV_EXPORTS_W void registerPageLocked(Mat& m);
  452. /** @brief Unmaps the memory of matrix and makes it pageable again.
  453. @param m Input matrix.
  454. */
  455. CV_EXPORTS_W void unregisterPageLocked(Mat& m);
  456. //===================================================================================
  457. // Stream
  458. //===================================================================================
  459. /** @brief This class encapsulates a queue of asynchronous calls.
  460. @note Currently, you may face problems if an operation is enqueued twice with different data. Some
  461. functions use the constant GPU memory, and next call may update the memory before the previous one
  462. has been finished. But calling different operations asynchronously is safe because each operation
  463. has its own constant buffer. Memory copy/upload/download/set operations to the buffers you hold are
  464. also safe.
  465. @note The Stream class is not thread-safe. Please use different Stream objects for different CPU threads.
  466. @code
  467. void thread1()
  468. {
  469. cv::cuda::Stream stream1;
  470. cv::cuda::func1(..., stream1);
  471. }
  472. void thread2()
  473. {
  474. cv::cuda::Stream stream2;
  475. cv::cuda::func2(..., stream2);
  476. }
  477. @endcode
  478. @note By default all CUDA routines are launched in Stream::Null() object, if the stream is not specified by user.
  479. In multi-threading environment the stream objects must be passed explicitly (see previous note).
  480. */
  481. class CV_EXPORTS_W Stream
  482. {
  483. typedef void (Stream::*bool_type)() const;
  484. void this_type_does_not_support_comparisons() const {}
  485. public:
  486. typedef void (*StreamCallback)(int status, void* userData);
  487. //! creates a new asynchronous stream
  488. CV_WRAP Stream();
  489. //! creates a new asynchronous stream with custom allocator
  490. CV_WRAP Stream(const Ptr<GpuMat::Allocator>& allocator);
  491. /** @brief Returns true if the current stream queue is finished. Otherwise, it returns false.
  492. */
  493. CV_WRAP bool queryIfComplete() const;
  494. /** @brief Blocks the current CPU thread until all operations in the stream are complete.
  495. */
  496. CV_WRAP void waitForCompletion();
  497. /** @brief Makes a compute stream wait on an event.
  498. */
  499. CV_WRAP void waitEvent(const Event& event);
  500. /** @brief Adds a callback to be called on the host after all currently enqueued items in the stream have
  501. completed.
  502. @note Callbacks must not make any CUDA API calls. Callbacks must not perform any synchronization
  503. that may depend on outstanding device work or other callbacks that are not mandated to run earlier.
  504. Callbacks without a mandated order (in independent streams) execute in undefined order and may be
  505. serialized.
  506. */
  507. void enqueueHostCallback(StreamCallback callback, void* userData);
  508. //! return Stream object for default CUDA stream
  509. CV_WRAP static Stream& Null();
  510. //! returns true if stream object is not default (!= 0)
  511. operator bool_type() const;
  512. class Impl;
  513. private:
  514. Ptr<Impl> impl_;
  515. Stream(const Ptr<Impl>& impl);
  516. friend struct StreamAccessor;
  517. friend class BufferPool;
  518. friend class DefaultDeviceInitializer;
  519. };
  520. class CV_EXPORTS_W Event
  521. {
  522. public:
  523. enum CreateFlags
  524. {
  525. DEFAULT = 0x00, /**< Default event flag */
  526. BLOCKING_SYNC = 0x01, /**< Event uses blocking synchronization */
  527. DISABLE_TIMING = 0x02, /**< Event will not record timing data */
  528. INTERPROCESS = 0x04 /**< Event is suitable for interprocess use. DisableTiming must be set */
  529. };
  530. CV_WRAP explicit Event(Event::CreateFlags flags = Event::CreateFlags::DEFAULT);
  531. //! records an event
  532. CV_WRAP void record(Stream& stream = Stream::Null());
  533. //! queries an event's status
  534. CV_WRAP bool queryIfComplete() const;
  535. //! waits for an event to complete
  536. CV_WRAP void waitForCompletion();
  537. //! computes the elapsed time between events
  538. CV_WRAP static float elapsedTime(const Event& start, const Event& end);
  539. class Impl;
  540. private:
  541. Ptr<Impl> impl_;
  542. Event(const Ptr<Impl>& impl);
  543. friend struct EventAccessor;
  544. };
  545. //! @} cudacore_struct
  546. //===================================================================================
  547. // Initialization & Info
  548. //===================================================================================
  549. //! @addtogroup cudacore_init
  550. //! @{
  551. /** @brief Returns the number of installed CUDA-enabled devices.
  552. Use this function before any other CUDA functions calls. If OpenCV is compiled without CUDA support,
  553. this function returns 0. If the CUDA driver is not installed, or is incompatible, this function
  554. returns -1.
  555. */
  556. CV_EXPORTS_W int getCudaEnabledDeviceCount();
  557. /** @brief Sets a device and initializes it for the current thread.
  558. @param device System index of a CUDA device starting with 0.
  559. If the call of this function is omitted, a default device is initialized at the fist CUDA usage.
  560. */
  561. CV_EXPORTS_W void setDevice(int device);
  562. /** @brief Returns the current device index set by cuda::setDevice or initialized by default.
  563. */
  564. CV_EXPORTS_W int getDevice();
  565. /** @brief Explicitly destroys and cleans up all resources associated with the current device in the current
  566. process.
  567. Any subsequent API call to this device will reinitialize the device.
  568. */
  569. CV_EXPORTS_W void resetDevice();
  570. /** @brief Enumeration providing CUDA computing features.
  571. */
  572. enum FeatureSet
  573. {
  574. FEATURE_SET_COMPUTE_10 = 10,
  575. FEATURE_SET_COMPUTE_11 = 11,
  576. FEATURE_SET_COMPUTE_12 = 12,
  577. FEATURE_SET_COMPUTE_13 = 13,
  578. FEATURE_SET_COMPUTE_20 = 20,
  579. FEATURE_SET_COMPUTE_21 = 21,
  580. FEATURE_SET_COMPUTE_30 = 30,
  581. FEATURE_SET_COMPUTE_32 = 32,
  582. FEATURE_SET_COMPUTE_35 = 35,
  583. FEATURE_SET_COMPUTE_50 = 50,
  584. GLOBAL_ATOMICS = FEATURE_SET_COMPUTE_11,
  585. SHARED_ATOMICS = FEATURE_SET_COMPUTE_12,
  586. NATIVE_DOUBLE = FEATURE_SET_COMPUTE_13,
  587. WARP_SHUFFLE_FUNCTIONS = FEATURE_SET_COMPUTE_30,
  588. DYNAMIC_PARALLELISM = FEATURE_SET_COMPUTE_35
  589. };
  590. //! checks whether current device supports the given feature
  591. CV_EXPORTS bool deviceSupports(FeatureSet feature_set);
  592. /** @brief Class providing a set of static methods to check what NVIDIA\* card architecture the CUDA module was
  593. built for.
  594. According to the CUDA C Programming Guide Version 3.2: "PTX code produced for some specific compute
  595. capability can always be compiled to binary code of greater or equal compute capability".
  596. */
  597. class CV_EXPORTS_W TargetArchs
  598. {
  599. public:
  600. /** @brief The following method checks whether the module was built with the support of the given feature:
  601. @param feature_set Features to be checked. See :ocvcuda::FeatureSet.
  602. */
  603. static bool builtWith(FeatureSet feature_set);
  604. /** @brief There is a set of methods to check whether the module contains intermediate (PTX) or binary CUDA
  605. code for the given architecture(s):
  606. @param major Major compute capability version.
  607. @param minor Minor compute capability version.
  608. */
  609. CV_WRAP static bool has(int major, int minor);
  610. CV_WRAP static bool hasPtx(int major, int minor);
  611. CV_WRAP static bool hasBin(int major, int minor);
  612. CV_WRAP static bool hasEqualOrLessPtx(int major, int minor);
  613. CV_WRAP static bool hasEqualOrGreater(int major, int minor);
  614. CV_WRAP static bool hasEqualOrGreaterPtx(int major, int minor);
  615. CV_WRAP static bool hasEqualOrGreaterBin(int major, int minor);
  616. };
  617. /** @brief Class providing functionality for querying the specified GPU properties.
  618. */
  619. class CV_EXPORTS_W DeviceInfo
  620. {
  621. public:
  622. //! creates DeviceInfo object for the current GPU
  623. CV_WRAP DeviceInfo();
  624. /** @brief The constructors.
  625. @param device_id System index of the CUDA device starting with 0.
  626. Constructs the DeviceInfo object for the specified device. If device_id parameter is missed, it
  627. constructs an object for the current device.
  628. */
  629. CV_WRAP DeviceInfo(int device_id);
  630. /** @brief Returns system index of the CUDA device starting with 0.
  631. */
  632. CV_WRAP int deviceID() const;
  633. //! ASCII string identifying device
  634. const char* name() const;
  635. //! global memory available on device in bytes
  636. CV_WRAP size_t totalGlobalMem() const;
  637. //! shared memory available per block in bytes
  638. CV_WRAP size_t sharedMemPerBlock() const;
  639. //! 32-bit registers available per block
  640. CV_WRAP int regsPerBlock() const;
  641. //! warp size in threads
  642. CV_WRAP int warpSize() const;
  643. //! maximum pitch in bytes allowed by memory copies
  644. CV_WRAP size_t memPitch() const;
  645. //! maximum number of threads per block
  646. CV_WRAP int maxThreadsPerBlock() const;
  647. //! maximum size of each dimension of a block
  648. CV_WRAP Vec3i maxThreadsDim() const;
  649. //! maximum size of each dimension of a grid
  650. CV_WRAP Vec3i maxGridSize() const;
  651. //! clock frequency in kilohertz
  652. CV_WRAP int clockRate() const;
  653. //! constant memory available on device in bytes
  654. CV_WRAP size_t totalConstMem() const;
  655. //! major compute capability
  656. CV_WRAP int majorVersion() const;
  657. //! minor compute capability
  658. CV_WRAP int minorVersion() const;
  659. //! alignment requirement for textures
  660. CV_WRAP size_t textureAlignment() const;
  661. //! pitch alignment requirement for texture references bound to pitched memory
  662. CV_WRAP size_t texturePitchAlignment() const;
  663. //! number of multiprocessors on device
  664. CV_WRAP int multiProcessorCount() const;
  665. //! specified whether there is a run time limit on kernels
  666. CV_WRAP bool kernelExecTimeoutEnabled() const;
  667. //! device is integrated as opposed to discrete
  668. CV_WRAP bool integrated() const;
  669. //! device can map host memory with cudaHostAlloc/cudaHostGetDevicePointer
  670. CV_WRAP bool canMapHostMemory() const;
  671. enum ComputeMode
  672. {
  673. ComputeModeDefault, /**< default compute mode (Multiple threads can use cudaSetDevice with this device) */
  674. ComputeModeExclusive, /**< compute-exclusive-thread mode (Only one thread in one process will be able to use cudaSetDevice with this device) */
  675. ComputeModeProhibited, /**< compute-prohibited mode (No threads can use cudaSetDevice with this device) */
  676. ComputeModeExclusiveProcess /**< compute-exclusive-process mode (Many threads in one process will be able to use cudaSetDevice with this device) */
  677. };
  678. //! compute mode
  679. CV_WRAP DeviceInfo::ComputeMode computeMode() const;
  680. //! maximum 1D texture size
  681. CV_WRAP int maxTexture1D() const;
  682. //! maximum 1D mipmapped texture size
  683. CV_WRAP int maxTexture1DMipmap() const;
  684. //! maximum size for 1D textures bound to linear memory
  685. CV_WRAP int maxTexture1DLinear() const;
  686. //! maximum 2D texture dimensions
  687. CV_WRAP Vec2i maxTexture2D() const;
  688. //! maximum 2D mipmapped texture dimensions
  689. CV_WRAP Vec2i maxTexture2DMipmap() const;
  690. //! maximum dimensions (width, height, pitch) for 2D textures bound to pitched memory
  691. CV_WRAP Vec3i maxTexture2DLinear() const;
  692. //! maximum 2D texture dimensions if texture gather operations have to be performed
  693. CV_WRAP Vec2i maxTexture2DGather() const;
  694. //! maximum 3D texture dimensions
  695. CV_WRAP Vec3i maxTexture3D() const;
  696. //! maximum Cubemap texture dimensions
  697. CV_WRAP int maxTextureCubemap() const;
  698. //! maximum 1D layered texture dimensions
  699. CV_WRAP Vec2i maxTexture1DLayered() const;
  700. //! maximum 2D layered texture dimensions
  701. CV_WRAP Vec3i maxTexture2DLayered() const;
  702. //! maximum Cubemap layered texture dimensions
  703. CV_WRAP Vec2i maxTextureCubemapLayered() const;
  704. //! maximum 1D surface size
  705. CV_WRAP int maxSurface1D() const;
  706. //! maximum 2D surface dimensions
  707. CV_WRAP Vec2i maxSurface2D() const;
  708. //! maximum 3D surface dimensions
  709. CV_WRAP Vec3i maxSurface3D() const;
  710. //! maximum 1D layered surface dimensions
  711. CV_WRAP Vec2i maxSurface1DLayered() const;
  712. //! maximum 2D layered surface dimensions
  713. CV_WRAP Vec3i maxSurface2DLayered() const;
  714. //! maximum Cubemap surface dimensions
  715. CV_WRAP int maxSurfaceCubemap() const;
  716. //! maximum Cubemap layered surface dimensions
  717. CV_WRAP Vec2i maxSurfaceCubemapLayered() const;
  718. //! alignment requirements for surfaces
  719. CV_WRAP size_t surfaceAlignment() const;
  720. //! device can possibly execute multiple kernels concurrently
  721. CV_WRAP bool concurrentKernels() const;
  722. //! device has ECC support enabled
  723. CV_WRAP bool ECCEnabled() const;
  724. //! PCI bus ID of the device
  725. CV_WRAP int pciBusID() const;
  726. //! PCI device ID of the device
  727. CV_WRAP int pciDeviceID() const;
  728. //! PCI domain ID of the device
  729. CV_WRAP int pciDomainID() const;
  730. //! true if device is a Tesla device using TCC driver, false otherwise
  731. CV_WRAP bool tccDriver() const;
  732. //! number of asynchronous engines
  733. CV_WRAP int asyncEngineCount() const;
  734. //! device shares a unified address space with the host
  735. CV_WRAP bool unifiedAddressing() const;
  736. //! peak memory clock frequency in kilohertz
  737. CV_WRAP int memoryClockRate() const;
  738. //! global memory bus width in bits
  739. CV_WRAP int memoryBusWidth() const;
  740. //! size of L2 cache in bytes
  741. CV_WRAP int l2CacheSize() const;
  742. //! maximum resident threads per multiprocessor
  743. CV_WRAP int maxThreadsPerMultiProcessor() const;
  744. //! gets free and total device memory
  745. CV_WRAP void queryMemory(size_t& totalMemory, size_t& freeMemory) const;
  746. CV_WRAP size_t freeMemory() const;
  747. CV_WRAP size_t totalMemory() const;
  748. /** @brief Provides information on CUDA feature support.
  749. @param feature_set Features to be checked. See cuda::FeatureSet.
  750. This function returns true if the device has the specified CUDA feature. Otherwise, it returns false
  751. */
  752. bool supports(FeatureSet feature_set) const;
  753. /** @brief Checks the CUDA module and device compatibility.
  754. This function returns true if the CUDA module can be run on the specified device. Otherwise, it
  755. returns false .
  756. */
  757. CV_WRAP bool isCompatible() const;
  758. private:
  759. int device_id_;
  760. };
  761. CV_EXPORTS_W void printCudaDeviceInfo(int device);
  762. CV_EXPORTS_W void printShortCudaDeviceInfo(int device);
  763. /** @brief Converts an array to half precision floating number.
  764. @param _src input array.
  765. @param _dst output array.
  766. @param stream Stream for the asynchronous version.
  767. @sa convertFp16
  768. */
  769. CV_EXPORTS void convertFp16(InputArray _src, OutputArray _dst, Stream& stream = Stream::Null());
  770. //! @} cudacore_init
  771. }} // namespace cv { namespace cuda {
  772. #include "opencv2/core/cuda.inl.hpp"
  773. #endif /* OPENCV_CORE_CUDA_HPP */