cuda.hpp 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309
  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. //! constructs 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. CV_WRAP 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. // returns pointer to cuda memory
  233. CV_WRAP void* cudaPtr() const;
  234. //! internal use method: updates the continuity flag
  235. CV_WRAP void updateContinuityFlag();
  236. /*! includes several bit-fields:
  237. - the magic signature
  238. - continuity flag
  239. - depth
  240. - number of channels
  241. */
  242. int flags;
  243. //! the number of rows and columns
  244. int rows, cols;
  245. //! a distance between successive rows in bytes; includes the gap if any
  246. CV_PROP size_t step;
  247. //! pointer to the data
  248. uchar* data;
  249. //! pointer to the reference counter;
  250. //! when GpuMat points to user-allocated data, the pointer is NULL
  251. int* refcount;
  252. //! helper fields used in locateROI and adjustROI
  253. uchar* datastart;
  254. const uchar* dataend;
  255. //! allocator
  256. Allocator* allocator;
  257. };
  258. struct CV_EXPORTS_W GpuData
  259. {
  260. explicit GpuData(size_t _size);
  261. ~GpuData();
  262. GpuData(const GpuData&) = delete;
  263. GpuData& operator=(const GpuData&) = delete;
  264. GpuData(GpuData&&) = delete;
  265. GpuData& operator=(GpuData&&) = delete;
  266. uchar* data;
  267. size_t size;
  268. };
  269. class CV_EXPORTS_W GpuMatND
  270. {
  271. public:
  272. using SizeArray = std::vector<int>;
  273. using StepArray = std::vector<size_t>;
  274. using IndexArray = std::vector<int>;
  275. //! destructor
  276. ~GpuMatND();
  277. //! default constructor
  278. GpuMatND();
  279. /** @overload
  280. @param size Array of integers specifying an n-dimensional array shape.
  281. @param type Array type. Use CV_8UC1, ..., CV_16FC4 to create 1-4 channel matrices, or
  282. CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices.
  283. */
  284. GpuMatND(SizeArray size, int type);
  285. /** @overload
  286. @param size Array of integers specifying an n-dimensional array shape.
  287. @param type Array type. Use CV_8UC1, ..., CV_16FC4 to create 1-4 channel matrices, or
  288. CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices.
  289. @param data Pointer to the user data. Matrix constructors that take data and step parameters do not
  290. allocate matrix data. Instead, they just initialize the matrix header that points to the specified
  291. data, which means that no data is copied. This operation is very efficient and can be used to
  292. process external data using OpenCV functions. The external data is not automatically deallocated, so
  293. you should take care of it.
  294. @param step Array of _size.size()-1 steps in case of a multi-dimensional array (the last step is always
  295. set to the element size). If not specified, the matrix is assumed to be continuous.
  296. */
  297. GpuMatND(SizeArray size, int type, void* data, StepArray step = StepArray());
  298. /** @brief Allocates GPU memory.
  299. Suppose there is some GPU memory already allocated. In that case, this method may choose to reuse that
  300. GPU memory under the specific condition: it must be of the same size and type, not externally allocated,
  301. the GPU memory is continuous(i.e., isContinuous() is true), and is not a sub-matrix of another GpuMatND
  302. (i.e., isSubmatrix() is false). In other words, this method guarantees that the GPU memory allocated by
  303. this method is always continuous and is not a sub-region of another GpuMatND.
  304. */
  305. void create(SizeArray size, int type);
  306. void release();
  307. void swap(GpuMatND& m) noexcept;
  308. /** @brief Creates a full copy of the array and the underlying data.
  309. The method creates a full copy of the array. It mimics the behavior of Mat::clone(), i.e.
  310. the original step is not taken into account. So, the array copy is a continuous array
  311. occupying total()\*elemSize() bytes.
  312. */
  313. GpuMatND clone() const;
  314. /** @overload
  315. This overload is non-blocking, so it may return even if the copy operation is not finished.
  316. */
  317. GpuMatND clone(Stream& stream) const;
  318. /** @brief Extracts a sub-matrix.
  319. The operator makes a new header for the specified sub-array of \*this.
  320. The operator is an O(1) operation, that is, no matrix data is copied.
  321. @param ranges Array of selected ranges along each dimension.
  322. */
  323. GpuMatND operator()(const std::vector<Range>& ranges) const;
  324. /** @brief Creates a GpuMat header for a 2D plane part of an n-dim matrix.
  325. @note The returned GpuMat is constructed with the constructor for user-allocated data.
  326. That is, It does not perform reference counting.
  327. @note This function does not increment this GpuMatND's reference counter.
  328. */
  329. GpuMat createGpuMatHeader(IndexArray idx, Range rowRange, Range colRange) const;
  330. /** @overload
  331. Creates a GpuMat header if this GpuMatND is effectively 2D.
  332. @note The returned GpuMat is constructed with the constructor for user-allocated data.
  333. That is, It does not perform reference counting.
  334. @note This function does not increment this GpuMatND's reference counter.
  335. */
  336. GpuMat createGpuMatHeader() const;
  337. /** @brief Extracts a 2D plane part of an n-dim matrix.
  338. It differs from createGpuMatHeader(IndexArray, Range, Range) in that it clones a part of this
  339. GpuMatND to the returned GpuMat.
  340. @note This operator does not increment this GpuMatND's reference counter;
  341. */
  342. GpuMat operator()(IndexArray idx, Range rowRange, Range colRange) const;
  343. /** @brief Extracts a 2D plane part of an n-dim matrix if this GpuMatND is effectively 2D.
  344. It differs from createGpuMatHeader() in that it clones a part of this GpuMatND.
  345. @note This operator does not increment this GpuMatND's reference counter;
  346. */
  347. operator GpuMat() const;
  348. GpuMatND(const GpuMatND&) = default;
  349. GpuMatND& operator=(const GpuMatND&) = default;
  350. #if defined(__GNUC__) && __GNUC__ < 5
  351. // error: function '...' defaulted on its first declaration with an exception-specification
  352. // that differs from the implicit declaration '...'
  353. GpuMatND(GpuMatND&&) = default;
  354. GpuMatND& operator=(GpuMatND&&) = default;
  355. #else
  356. GpuMatND(GpuMatND&&) noexcept = default;
  357. GpuMatND& operator=(GpuMatND&&) noexcept = default;
  358. #endif
  359. void upload(InputArray src);
  360. void upload(InputArray src, Stream& stream);
  361. void download(OutputArray dst) const;
  362. void download(OutputArray dst, Stream& stream) const;
  363. //! returns true iff the GpuMatND data is continuous
  364. //! (i.e. when there are no gaps between successive rows)
  365. bool isContinuous() const;
  366. //! returns true if the matrix is a sub-matrix of another matrix
  367. bool isSubmatrix() const;
  368. //! returns element size in bytes
  369. size_t elemSize() const;
  370. //! returns the size of element channel in bytes
  371. size_t elemSize1() const;
  372. //! returns true if data is null
  373. bool empty() const;
  374. //! returns true if not empty and points to external(user-allocated) gpu memory
  375. bool external() const;
  376. //! returns pointer to the first byte of the GPU memory
  377. uchar* getDevicePtr() const;
  378. //! returns the total number of array elements
  379. size_t total() const;
  380. //! returns the size of underlying memory in bytes
  381. size_t totalMemSize() const;
  382. //! returns element type
  383. int type() const;
  384. private:
  385. //! internal use
  386. void setFields(SizeArray size, int type, StepArray step = StepArray());
  387. public:
  388. /*! includes several bit-fields:
  389. - the magic signature
  390. - continuity flag
  391. - depth
  392. - number of channels
  393. */
  394. int flags;
  395. //! matrix dimensionality
  396. int dims;
  397. //! shape of this array
  398. SizeArray size;
  399. /*! step values
  400. Their semantics is identical to the semantics of step for Mat.
  401. */
  402. StepArray step;
  403. private:
  404. /*! internal use
  405. If this GpuMatND holds external memory, this is empty.
  406. */
  407. std::shared_ptr<GpuData> data_;
  408. /*! internal use
  409. If this GpuMatND manages memory with reference counting, this value is
  410. always equal to data_->data. If this GpuMatND holds external memory,
  411. data_ is empty and data points to the external memory.
  412. */
  413. uchar* data;
  414. /*! internal use
  415. If this GpuMatND is a sub-matrix of a larger matrix, this value is the
  416. difference of the first byte between the sub-matrix and the whole matrix.
  417. */
  418. size_t offset;
  419. };
  420. /** @brief Creates a continuous matrix.
  421. @param rows Row count.
  422. @param cols Column count.
  423. @param type Type of the matrix.
  424. @param arr Destination matrix. This parameter changes only if it has a proper type and area (
  425. \f$\texttt{rows} \times \texttt{cols}\f$ ).
  426. Matrix is called continuous if its elements are stored continuously, that is, without gaps at the
  427. end of each row.
  428. */
  429. CV_EXPORTS_W void createContinuous(int rows, int cols, int type, OutputArray arr);
  430. /** @brief Ensures that the size of a matrix is big enough and the matrix has a proper type.
  431. @param rows Minimum desired number of rows.
  432. @param cols Minimum desired number of columns.
  433. @param type Desired matrix type.
  434. @param arr Destination matrix.
  435. The function does not reallocate memory if the matrix has proper attributes already.
  436. */
  437. CV_EXPORTS_W void ensureSizeIsEnough(int rows, int cols, int type, OutputArray arr);
  438. /** @brief Bindings overload to create a GpuMat from existing GPU memory.
  439. @param rows Row count.
  440. @param cols Column count.
  441. @param type Type of the matrix.
  442. @param cudaMemoryAddress Address of the allocated GPU memory on the device. This does not allocate matrix data. Instead, it just initializes the matrix header that points to the specified \a cudaMemoryAddress, which means that no data is copied. This operation is very efficient and can be used to process external data using OpenCV functions. The external data is not automatically deallocated, so you should take care of it.
  443. @param step Number of bytes each matrix row occupies. The value should include the padding bytes at the end of each row, if any. If the parameter is missing (set to Mat::AUTO_STEP ), no padding is assumed and the actual step is calculated as cols*elemSize(). See GpuMat::elemSize.
  444. @note Overload for generation of bindings only, not exported or intended for use internally from C++.
  445. */
  446. CV_EXPORTS_W GpuMat inline createGpuMatFromCudaMemory(int rows, int cols, int type, size_t cudaMemoryAddress, size_t step = Mat::AUTO_STEP) {
  447. return GpuMat(rows, cols, type, reinterpret_cast<void*>(cudaMemoryAddress), step);
  448. };
  449. /** @overload
  450. @param size 2D array size: Size(cols, rows). In the Size() constructor, the number of rows and the number of columns go in the reverse order.
  451. @param type Type of the matrix.
  452. @param cudaMemoryAddress Address of the allocated GPU memory on the device. This does not allocate matrix data. Instead, it just initializes the matrix header that points to the specified \a cudaMemoryAddress, which means that no data is copied. This operation is very efficient and can be used to process external data using OpenCV functions. The external data is not automatically deallocated, so you should take care of it.
  453. @param step Number of bytes each matrix row occupies. The value should include the padding bytes at the end of each row, if any. If the parameter is missing (set to Mat::AUTO_STEP ), no padding is assumed and the actual step is calculated as cols*elemSize(). See GpuMat::elemSize.
  454. @note Overload for generation of bindings only, not exported or intended for use internally from C++.
  455. */
  456. CV_EXPORTS_W inline GpuMat createGpuMatFromCudaMemory(Size size, int type, size_t cudaMemoryAddress, size_t step = Mat::AUTO_STEP) {
  457. return GpuMat(size, type, reinterpret_cast<void*>(cudaMemoryAddress), step);
  458. };
  459. /** @brief BufferPool for use with CUDA streams
  460. BufferPool utilizes Stream's allocator to create new buffers for GpuMat's. It is
  461. only useful when enabled with #setBufferPoolUsage.
  462. @code
  463. setBufferPoolUsage(true);
  464. @endcode
  465. @note #setBufferPoolUsage must be called \em before any Stream declaration.
  466. Users may specify custom allocator for Stream and may implement their own stream based
  467. functions utilizing the same underlying GPU memory management.
  468. If custom allocator is not specified, BufferPool utilizes StackAllocator by
  469. default. StackAllocator allocates a chunk of GPU device memory beforehand,
  470. and when GpuMat is declared later on, it is given the pre-allocated memory.
  471. This kind of strategy reduces the number of calls for memory allocating APIs
  472. such as cudaMalloc or cudaMallocPitch.
  473. Below is an example that utilizes BufferPool with StackAllocator:
  474. @code
  475. #include <opencv2/opencv.hpp>
  476. using namespace cv;
  477. using namespace cv::cuda
  478. int main()
  479. {
  480. setBufferPoolUsage(true); // Tell OpenCV that we are going to utilize BufferPool
  481. setBufferPoolConfig(getDevice(), 1024 * 1024 * 64, 2); // Allocate 64 MB, 2 stacks (default is 10 MB, 5 stacks)
  482. Stream stream1, stream2; // Each stream uses 1 stack
  483. BufferPool pool1(stream1), pool2(stream2);
  484. GpuMat d_src1 = pool1.getBuffer(4096, 4096, CV_8UC1); // 16MB
  485. GpuMat d_dst1 = pool1.getBuffer(4096, 4096, CV_8UC3); // 48MB, pool1 is now full
  486. GpuMat d_src2 = pool2.getBuffer(1024, 1024, CV_8UC1); // 1MB
  487. GpuMat d_dst2 = pool2.getBuffer(1024, 1024, CV_8UC3); // 3MB
  488. cvtColor(d_src1, d_dst1, cv::COLOR_GRAY2BGR, 0, stream1);
  489. cvtColor(d_src2, d_dst2, cv::COLOR_GRAY2BGR, 0, stream2);
  490. }
  491. @endcode
  492. If we allocate another GpuMat on pool1 in the above example, it will be carried out by
  493. the DefaultAllocator since the stack for pool1 is full.
  494. @code
  495. GpuMat d_add1 = pool1.getBuffer(1024, 1024, CV_8UC1); // Stack for pool1 is full, memory is allocated with DefaultAllocator
  496. @endcode
  497. If a third stream is declared in the above example, allocating with #getBuffer
  498. within that stream will also be carried out by the DefaultAllocator because we've run out of
  499. stacks.
  500. @code
  501. Stream stream3; // Only 2 stacks were allocated, we've run out of stacks
  502. BufferPool pool3(stream3);
  503. GpuMat d_src3 = pool3.getBuffer(1024, 1024, CV_8UC1); // Memory is allocated with DefaultAllocator
  504. @endcode
  505. @warning When utilizing StackAllocator, deallocation order is important.
  506. Just like a stack, deallocation must be done in LIFO order. Below is an example of
  507. erroneous usage that violates LIFO rule. If OpenCV is compiled in Debug mode, this
  508. sample code will emit CV_Assert error.
  509. @code
  510. int main()
  511. {
  512. setBufferPoolUsage(true); // Tell OpenCV that we are going to utilize BufferPool
  513. Stream stream; // A default size (10 MB) stack is allocated to this stream
  514. BufferPool pool(stream);
  515. GpuMat mat1 = pool.getBuffer(1024, 1024, CV_8UC1); // Allocate mat1 (1MB)
  516. GpuMat mat2 = pool.getBuffer(1024, 1024, CV_8UC1); // Allocate mat2 (1MB)
  517. mat1.release(); // erroneous usage : mat2 must be deallocated before mat1
  518. }
  519. @endcode
  520. Since C++ local variables are destroyed in the reverse order of construction,
  521. the code sample below satisfies the LIFO rule. Local GpuMat's are deallocated
  522. and the corresponding memory is automatically returned to the pool for later usage.
  523. @code
  524. int main()
  525. {
  526. setBufferPoolUsage(true); // Tell OpenCV that we are going to utilize BufferPool
  527. setBufferPoolConfig(getDevice(), 1024 * 1024 * 64, 2); // Allocate 64 MB, 2 stacks (default is 10 MB, 5 stacks)
  528. Stream stream1, stream2; // Each stream uses 1 stack
  529. BufferPool pool1(stream1), pool2(stream2);
  530. for (int i = 0; i < 10; i++)
  531. {
  532. GpuMat d_src1 = pool1.getBuffer(4096, 4096, CV_8UC1); // 16MB
  533. GpuMat d_dst1 = pool1.getBuffer(4096, 4096, CV_8UC3); // 48MB, pool1 is now full
  534. GpuMat d_src2 = pool2.getBuffer(1024, 1024, CV_8UC1); // 1MB
  535. GpuMat d_dst2 = pool2.getBuffer(1024, 1024, CV_8UC3); // 3MB
  536. d_src1.setTo(Scalar(i), stream1);
  537. d_src2.setTo(Scalar(i), stream2);
  538. cvtColor(d_src1, d_dst1, cv::COLOR_GRAY2BGR, 0, stream1);
  539. cvtColor(d_src2, d_dst2, cv::COLOR_GRAY2BGR, 0, stream2);
  540. // The order of destruction of the local variables is:
  541. // d_dst2 => d_src2 => d_dst1 => d_src1
  542. // LIFO rule is satisfied, this code runs without error
  543. }
  544. }
  545. @endcode
  546. */
  547. class CV_EXPORTS_W BufferPool
  548. {
  549. public:
  550. //! Gets the BufferPool for the given stream.
  551. CV_WRAP explicit BufferPool(Stream& stream);
  552. //! Allocates a new GpuMat of given size and type.
  553. CV_WRAP GpuMat getBuffer(int rows, int cols, int type);
  554. // WARNING: unreachable code using Ninja
  555. #if defined _MSC_VER && _MSC_VER >= 1920
  556. #pragma warning(push)
  557. #pragma warning(disable: 4702)
  558. #endif
  559. //! Allocates a new GpuMat of given size and type.
  560. CV_WRAP GpuMat getBuffer(Size size, int type) { return getBuffer(size.height, size.width, type); }
  561. #if defined _MSC_VER && _MSC_VER >= 1920
  562. #pragma warning(pop)
  563. #endif
  564. //! Returns the allocator associated with the stream.
  565. CV_WRAP Ptr<GpuMat::Allocator> getAllocator() const { return allocator_; }
  566. private:
  567. Ptr<GpuMat::Allocator> allocator_;
  568. };
  569. //! BufferPool management (must be called before Stream creation)
  570. CV_EXPORTS_W void setBufferPoolUsage(bool on);
  571. CV_EXPORTS_W void setBufferPoolConfig(int deviceId, size_t stackSize, int stackCount);
  572. //===================================================================================
  573. // HostMem
  574. //===================================================================================
  575. /** @brief Class with reference counting wrapping special memory type allocation functions from CUDA.
  576. Its interface is also Mat-like but with additional memory type parameters.
  577. - **PAGE_LOCKED** sets a page locked memory type used commonly for fast and asynchronous
  578. uploading/downloading data from/to GPU.
  579. - **SHARED** specifies a zero copy memory allocation that enables mapping the host memory to GPU
  580. address space, if supported.
  581. - **WRITE_COMBINED** sets the write combined buffer that is not cached by CPU. Such buffers are
  582. used to supply GPU with data when GPU only reads it. The advantage is a better CPU cache
  583. utilization.
  584. @note Allocation size of such memory types is usually limited. For more details, see *CUDA 2.2
  585. Pinned Memory APIs* document or *CUDA C Programming Guide*.
  586. */
  587. class CV_EXPORTS_W HostMem
  588. {
  589. public:
  590. enum AllocType { PAGE_LOCKED = 1, SHARED = 2, WRITE_COMBINED = 4 };
  591. static MatAllocator* getAllocator(HostMem::AllocType alloc_type = HostMem::AllocType::PAGE_LOCKED);
  592. CV_WRAP explicit HostMem(HostMem::AllocType alloc_type = HostMem::AllocType::PAGE_LOCKED);
  593. HostMem(const HostMem& m);
  594. CV_WRAP HostMem(int rows, int cols, int type, HostMem::AllocType alloc_type = HostMem::AllocType::PAGE_LOCKED);
  595. CV_WRAP HostMem(Size size, int type, HostMem::AllocType alloc_type = HostMem::AllocType::PAGE_LOCKED);
  596. //! creates from host memory with coping data
  597. CV_WRAP explicit HostMem(InputArray arr, HostMem::AllocType alloc_type = HostMem::AllocType::PAGE_LOCKED);
  598. ~HostMem();
  599. HostMem& operator =(const HostMem& m);
  600. //! swaps with other smart pointer
  601. CV_WRAP void swap(HostMem& b);
  602. //! returns deep copy of the matrix, i.e. the data is copied
  603. CV_WRAP HostMem clone() const;
  604. //! allocates new matrix data unless the matrix already has specified size and type.
  605. CV_WRAP void create(int rows, int cols, int type);
  606. void create(Size size, int type);
  607. //! creates alternative HostMem header for the same data, with different
  608. //! number of channels and/or different number of rows
  609. CV_WRAP HostMem reshape(int cn, int rows = 0) const;
  610. //! decrements reference counter and released memory if needed.
  611. void release();
  612. //! returns matrix header with disabled reference counting for HostMem data.
  613. CV_WRAP Mat createMatHeader() const;
  614. /** @brief Maps CPU memory to GPU address space and creates the cuda::GpuMat header without reference counting
  615. for it.
  616. This can be done only if memory was allocated with the SHARED flag and if it is supported by the
  617. hardware. Laptops often share video and CPU memory, so address spaces can be mapped, which
  618. eliminates an extra copy.
  619. */
  620. GpuMat createGpuMatHeader() const;
  621. // Please see cv::Mat for descriptions
  622. CV_WRAP bool isContinuous() const;
  623. CV_WRAP size_t elemSize() const;
  624. CV_WRAP size_t elemSize1() const;
  625. CV_WRAP int type() const;
  626. CV_WRAP int depth() const;
  627. CV_WRAP int channels() const;
  628. CV_WRAP size_t step1() const;
  629. CV_WRAP Size size() const;
  630. CV_WRAP bool empty() const;
  631. // Please see cv::Mat for descriptions
  632. int flags;
  633. int rows, cols;
  634. CV_PROP size_t step;
  635. uchar* data;
  636. int* refcount;
  637. uchar* datastart;
  638. const uchar* dataend;
  639. AllocType alloc_type;
  640. };
  641. /** @brief Page-locks the memory of matrix and maps it for the device(s).
  642. @param m Input matrix.
  643. */
  644. CV_EXPORTS_W void registerPageLocked(Mat& m);
  645. /** @brief Unmaps the memory of matrix and makes it pageable again.
  646. @param m Input matrix.
  647. */
  648. CV_EXPORTS_W void unregisterPageLocked(Mat& m);
  649. //===================================================================================
  650. // Stream
  651. //===================================================================================
  652. /** @brief This class encapsulates a queue of asynchronous calls.
  653. @note Currently, you may face problems if an operation is enqueued twice with different data. Some
  654. functions use the constant GPU memory, and next call may update the memory before the previous one
  655. has been finished. But calling different operations asynchronously is safe because each operation
  656. has its own constant buffer. Memory copy/upload/download/set operations to the buffers you hold are
  657. also safe.
  658. @note The Stream class is not thread-safe. Please use different Stream objects for different CPU threads.
  659. @code
  660. void thread1()
  661. {
  662. cv::cuda::Stream stream1;
  663. cv::cuda::func1(..., stream1);
  664. }
  665. void thread2()
  666. {
  667. cv::cuda::Stream stream2;
  668. cv::cuda::func2(..., stream2);
  669. }
  670. @endcode
  671. @note By default all CUDA routines are launched in Stream::Null() object, if the stream is not specified by user.
  672. In multi-threading environment the stream objects must be passed explicitly (see previous note).
  673. */
  674. class CV_EXPORTS_W Stream
  675. {
  676. typedef void (Stream::*bool_type)() const;
  677. void this_type_does_not_support_comparisons() const {}
  678. public:
  679. typedef void (*StreamCallback)(int status, void* userData);
  680. //! creates a new asynchronous stream
  681. CV_WRAP Stream();
  682. //! creates a new asynchronous stream with custom allocator
  683. CV_WRAP Stream(const Ptr<GpuMat::Allocator>& allocator);
  684. /** @brief creates a new Stream using the cudaFlags argument to determine the behaviors of the stream
  685. @note The cudaFlags parameter is passed to the underlying api cudaStreamCreateWithFlags() and
  686. supports the same parameter values.
  687. @code
  688. // creates an OpenCV cuda::Stream that manages an asynchronous, non-blocking,
  689. // non-default CUDA stream
  690. cv::cuda::Stream cvStream(cudaStreamNonBlocking);
  691. @endcode
  692. */
  693. CV_WRAP Stream(const size_t cudaFlags);
  694. /** @brief Returns true if the current stream queue is finished. Otherwise, it returns false.
  695. */
  696. CV_WRAP bool queryIfComplete() const;
  697. /** @brief Blocks the current CPU thread until all operations in the stream are complete.
  698. */
  699. CV_WRAP void waitForCompletion();
  700. /** @brief Makes a compute stream wait on an event.
  701. */
  702. CV_WRAP void waitEvent(const Event& event);
  703. /** @brief Adds a callback to be called on the host after all currently enqueued items in the stream have
  704. completed.
  705. @note Callbacks must not make any CUDA API calls. Callbacks must not perform any synchronization
  706. that may depend on outstanding device work or other callbacks that are not mandated to run earlier.
  707. Callbacks without a mandated order (in independent streams) execute in undefined order and may be
  708. serialized.
  709. */
  710. void enqueueHostCallback(StreamCallback callback, void* userData);
  711. //! return Stream object for default CUDA stream
  712. CV_WRAP static Stream& Null();
  713. //! returns true if stream object is not default (!= 0)
  714. operator bool_type() const;
  715. //! return Pointer to CUDA stream
  716. CV_WRAP void* cudaPtr() const;
  717. class Impl;
  718. private:
  719. Ptr<Impl> impl_;
  720. Stream(const Ptr<Impl>& impl);
  721. friend struct StreamAccessor;
  722. friend class BufferPool;
  723. friend class DefaultDeviceInitializer;
  724. };
  725. /** @brief Bindings overload to create a Stream object from the address stored in an existing CUDA Runtime API stream pointer (cudaStream_t).
  726. @param cudaStreamMemoryAddress Memory address stored in a CUDA Runtime API stream pointer (cudaStream_t). The created Stream object does not perform any allocation or deallocation and simply wraps existing raw CUDA Runtime API stream pointer.
  727. @note Overload for generation of bindings only, not exported or intended for use internally from C++.
  728. */
  729. CV_EXPORTS_W Stream wrapStream(size_t cudaStreamMemoryAddress);
  730. class CV_EXPORTS_W Event
  731. {
  732. public:
  733. enum CreateFlags
  734. {
  735. DEFAULT = 0x00, /**< Default event flag */
  736. BLOCKING_SYNC = 0x01, /**< Event uses blocking synchronization */
  737. DISABLE_TIMING = 0x02, /**< Event will not record timing data */
  738. INTERPROCESS = 0x04 /**< Event is suitable for interprocess use. DisableTiming must be set */
  739. };
  740. CV_WRAP explicit Event(const Event::CreateFlags flags = Event::CreateFlags::DEFAULT);
  741. //! records an event
  742. CV_WRAP void record(Stream& stream = Stream::Null());
  743. //! queries an event's status
  744. CV_WRAP bool queryIfComplete() const;
  745. //! waits for an event to complete
  746. CV_WRAP void waitForCompletion();
  747. //! computes the elapsed time between events
  748. CV_WRAP static float elapsedTime(const Event& start, const Event& end);
  749. class Impl;
  750. private:
  751. Ptr<Impl> impl_;
  752. Event(const Ptr<Impl>& impl);
  753. friend struct EventAccessor;
  754. };
  755. CV_ENUM_FLAGS(Event::CreateFlags)
  756. //! @} cudacore_struct
  757. //===================================================================================
  758. // Initialization & Info
  759. //===================================================================================
  760. //! @addtogroup cudacore_init
  761. //! @{
  762. /** @brief Returns the number of installed CUDA-enabled devices.
  763. Use this function before any other CUDA functions calls. If OpenCV is compiled without CUDA support,
  764. this function returns 0. If the CUDA driver is not installed, or is incompatible, this function
  765. returns -1.
  766. */
  767. CV_EXPORTS_W int getCudaEnabledDeviceCount();
  768. /** @brief Sets a device and initializes it for the current thread.
  769. @param device System index of a CUDA device starting with 0.
  770. If the call of this function is omitted, a default device is initialized at the fist CUDA usage.
  771. */
  772. CV_EXPORTS_W void setDevice(int device);
  773. /** @brief Returns the current device index set by cuda::setDevice or initialized by default.
  774. */
  775. CV_EXPORTS_W int getDevice();
  776. /** @brief Explicitly destroys and cleans up all resources associated with the current device in the current
  777. process.
  778. Any subsequent API call to this device will reinitialize the device.
  779. */
  780. CV_EXPORTS_W void resetDevice();
  781. /** @brief Enumeration providing CUDA computing features.
  782. */
  783. enum FeatureSet
  784. {
  785. FEATURE_SET_COMPUTE_10 = 10,
  786. FEATURE_SET_COMPUTE_11 = 11,
  787. FEATURE_SET_COMPUTE_12 = 12,
  788. FEATURE_SET_COMPUTE_13 = 13,
  789. FEATURE_SET_COMPUTE_20 = 20,
  790. FEATURE_SET_COMPUTE_21 = 21,
  791. FEATURE_SET_COMPUTE_30 = 30,
  792. FEATURE_SET_COMPUTE_32 = 32,
  793. FEATURE_SET_COMPUTE_35 = 35,
  794. FEATURE_SET_COMPUTE_50 = 50,
  795. GLOBAL_ATOMICS = FEATURE_SET_COMPUTE_11,
  796. SHARED_ATOMICS = FEATURE_SET_COMPUTE_12,
  797. NATIVE_DOUBLE = FEATURE_SET_COMPUTE_13,
  798. WARP_SHUFFLE_FUNCTIONS = FEATURE_SET_COMPUTE_30,
  799. DYNAMIC_PARALLELISM = FEATURE_SET_COMPUTE_35
  800. };
  801. //! checks whether current device supports the given feature
  802. CV_EXPORTS bool deviceSupports(FeatureSet feature_set);
  803. /** @brief Class providing a set of static methods to check what NVIDIA\* card architecture the CUDA module was
  804. built for.
  805. According to the CUDA C Programming Guide Version 3.2: "PTX code produced for some specific compute
  806. capability can always be compiled to binary code of greater or equal compute capability".
  807. */
  808. class CV_EXPORTS_W TargetArchs
  809. {
  810. public:
  811. /** @brief The following method checks whether the module was built with the support of the given feature:
  812. @param feature_set Features to be checked. See :ocvcuda::FeatureSet.
  813. */
  814. static bool builtWith(FeatureSet feature_set);
  815. /** @brief There is a set of methods to check whether the module contains intermediate (PTX) or binary CUDA
  816. code for the given architecture(s):
  817. @param major Major compute capability version.
  818. @param minor Minor compute capability version.
  819. */
  820. CV_WRAP static bool has(int major, int minor);
  821. CV_WRAP static bool hasPtx(int major, int minor);
  822. CV_WRAP static bool hasBin(int major, int minor);
  823. CV_WRAP static bool hasEqualOrLessPtx(int major, int minor);
  824. CV_WRAP static bool hasEqualOrGreater(int major, int minor);
  825. CV_WRAP static bool hasEqualOrGreaterPtx(int major, int minor);
  826. CV_WRAP static bool hasEqualOrGreaterBin(int major, int minor);
  827. };
  828. /** @brief Class providing functionality for querying the specified GPU properties.
  829. */
  830. class CV_EXPORTS_W DeviceInfo
  831. {
  832. public:
  833. //! creates DeviceInfo object for the current GPU
  834. CV_WRAP DeviceInfo();
  835. /** @brief The constructors.
  836. @param device_id System index of the CUDA device starting with 0.
  837. Constructs the DeviceInfo object for the specified device. If device_id parameter is missed, it
  838. constructs an object for the current device.
  839. */
  840. CV_WRAP DeviceInfo(int device_id);
  841. /** @brief Returns system index of the CUDA device starting with 0.
  842. */
  843. CV_WRAP int deviceID() const;
  844. //! ASCII string identifying device
  845. const char* name() const;
  846. //! global memory available on device in bytes
  847. CV_WRAP size_t totalGlobalMem() const;
  848. //! shared memory available per block in bytes
  849. CV_WRAP size_t sharedMemPerBlock() const;
  850. //! 32-bit registers available per block
  851. CV_WRAP int regsPerBlock() const;
  852. //! warp size in threads
  853. CV_WRAP int warpSize() const;
  854. //! maximum pitch in bytes allowed by memory copies
  855. CV_WRAP size_t memPitch() const;
  856. //! maximum number of threads per block
  857. CV_WRAP int maxThreadsPerBlock() const;
  858. //! maximum size of each dimension of a block
  859. CV_WRAP Vec3i maxThreadsDim() const;
  860. //! maximum size of each dimension of a grid
  861. CV_WRAP Vec3i maxGridSize() const;
  862. //! clock frequency in kilohertz
  863. CV_WRAP int clockRate() const;
  864. //! constant memory available on device in bytes
  865. CV_WRAP size_t totalConstMem() const;
  866. //! major compute capability
  867. CV_WRAP int majorVersion() const;
  868. //! minor compute capability
  869. CV_WRAP int minorVersion() const;
  870. //! alignment requirement for textures
  871. CV_WRAP size_t textureAlignment() const;
  872. //! pitch alignment requirement for texture references bound to pitched memory
  873. CV_WRAP size_t texturePitchAlignment() const;
  874. //! number of multiprocessors on device
  875. CV_WRAP int multiProcessorCount() const;
  876. //! specified whether there is a run time limit on kernels
  877. CV_WRAP bool kernelExecTimeoutEnabled() const;
  878. //! device is integrated as opposed to discrete
  879. CV_WRAP bool integrated() const;
  880. //! device can map host memory with cudaHostAlloc/cudaHostGetDevicePointer
  881. CV_WRAP bool canMapHostMemory() const;
  882. enum ComputeMode
  883. {
  884. ComputeModeDefault, /**< default compute mode (Multiple threads can use cudaSetDevice with this device) */
  885. ComputeModeExclusive, /**< compute-exclusive-thread mode (Only one thread in one process will be able to use cudaSetDevice with this device) */
  886. ComputeModeProhibited, /**< compute-prohibited mode (No threads can use cudaSetDevice with this device) */
  887. ComputeModeExclusiveProcess /**< compute-exclusive-process mode (Many threads in one process will be able to use cudaSetDevice with this device) */
  888. };
  889. //! compute mode
  890. CV_WRAP DeviceInfo::ComputeMode computeMode() const;
  891. //! maximum 1D texture size
  892. CV_WRAP int maxTexture1D() const;
  893. //! maximum 1D mipmapped texture size
  894. CV_WRAP int maxTexture1DMipmap() const;
  895. //! maximum size for 1D textures bound to linear memory
  896. CV_WRAP int maxTexture1DLinear() const;
  897. //! maximum 2D texture dimensions
  898. CV_WRAP Vec2i maxTexture2D() const;
  899. //! maximum 2D mipmapped texture dimensions
  900. CV_WRAP Vec2i maxTexture2DMipmap() const;
  901. //! maximum dimensions (width, height, pitch) for 2D textures bound to pitched memory
  902. CV_WRAP Vec3i maxTexture2DLinear() const;
  903. //! maximum 2D texture dimensions if texture gather operations have to be performed
  904. CV_WRAP Vec2i maxTexture2DGather() const;
  905. //! maximum 3D texture dimensions
  906. CV_WRAP Vec3i maxTexture3D() const;
  907. //! maximum Cubemap texture dimensions
  908. CV_WRAP int maxTextureCubemap() const;
  909. //! maximum 1D layered texture dimensions
  910. CV_WRAP Vec2i maxTexture1DLayered() const;
  911. //! maximum 2D layered texture dimensions
  912. CV_WRAP Vec3i maxTexture2DLayered() const;
  913. //! maximum Cubemap layered texture dimensions
  914. CV_WRAP Vec2i maxTextureCubemapLayered() const;
  915. //! maximum 1D surface size
  916. CV_WRAP int maxSurface1D() const;
  917. //! maximum 2D surface dimensions
  918. CV_WRAP Vec2i maxSurface2D() const;
  919. //! maximum 3D surface dimensions
  920. CV_WRAP Vec3i maxSurface3D() const;
  921. //! maximum 1D layered surface dimensions
  922. CV_WRAP Vec2i maxSurface1DLayered() const;
  923. //! maximum 2D layered surface dimensions
  924. CV_WRAP Vec3i maxSurface2DLayered() const;
  925. //! maximum Cubemap surface dimensions
  926. CV_WRAP int maxSurfaceCubemap() const;
  927. //! maximum Cubemap layered surface dimensions
  928. CV_WRAP Vec2i maxSurfaceCubemapLayered() const;
  929. //! alignment requirements for surfaces
  930. CV_WRAP size_t surfaceAlignment() const;
  931. //! device can possibly execute multiple kernels concurrently
  932. CV_WRAP bool concurrentKernels() const;
  933. //! device has ECC support enabled
  934. CV_WRAP bool ECCEnabled() const;
  935. //! PCI bus ID of the device
  936. CV_WRAP int pciBusID() const;
  937. //! PCI device ID of the device
  938. CV_WRAP int pciDeviceID() const;
  939. //! PCI domain ID of the device
  940. CV_WRAP int pciDomainID() const;
  941. //! true if device is a Tesla device using TCC driver, false otherwise
  942. CV_WRAP bool tccDriver() const;
  943. //! number of asynchronous engines
  944. CV_WRAP int asyncEngineCount() const;
  945. //! device shares a unified address space with the host
  946. CV_WRAP bool unifiedAddressing() const;
  947. //! peak memory clock frequency in kilohertz
  948. CV_WRAP int memoryClockRate() const;
  949. //! global memory bus width in bits
  950. CV_WRAP int memoryBusWidth() const;
  951. //! size of L2 cache in bytes
  952. CV_WRAP int l2CacheSize() const;
  953. //! maximum resident threads per multiprocessor
  954. CV_WRAP int maxThreadsPerMultiProcessor() const;
  955. //! gets free and total device memory
  956. CV_WRAP void queryMemory(size_t& totalMemory, size_t& freeMemory) const;
  957. CV_WRAP size_t freeMemory() const;
  958. CV_WRAP size_t totalMemory() const;
  959. /** @brief Provides information on CUDA feature support.
  960. @param feature_set Features to be checked. See cuda::FeatureSet.
  961. This function returns true if the device has the specified CUDA feature. Otherwise, it returns false
  962. */
  963. bool supports(FeatureSet feature_set) const;
  964. /** @brief Checks the CUDA module and device compatibility.
  965. This function returns true if the CUDA module can be run on the specified device. Otherwise, it
  966. returns false .
  967. */
  968. CV_WRAP bool isCompatible() const;
  969. private:
  970. int device_id_;
  971. };
  972. CV_EXPORTS_W void printCudaDeviceInfo(int device);
  973. CV_EXPORTS_W void printShortCudaDeviceInfo(int device);
  974. /** @brief Converts an array to half precision floating number.
  975. @param _src input array.
  976. @param _dst output array.
  977. @param stream Stream for the asynchronous version.
  978. @sa convertFp16
  979. */
  980. CV_EXPORTS void convertFp16(InputArray _src, OutputArray _dst, Stream& stream = Stream::Null());
  981. //! @} cudacore_init
  982. }} // namespace cv { namespace cuda {
  983. #include "opencv2/core/cuda.inl.hpp"
  984. #endif /* OPENCV_CORE_CUDA_HPP */