utility.hpp 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231
  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. // Copyright (C) 2015, Itseez Inc., all rights reserved.
  17. // Third party copyrights are property of their respective owners.
  18. //
  19. // Redistribution and use in source and binary forms, with or without modification,
  20. // are permitted provided that the following conditions are met:
  21. //
  22. // * Redistribution's of source code must retain the above copyright notice,
  23. // this list of conditions and the following disclaimer.
  24. //
  25. // * Redistribution's in binary form must reproduce the above copyright notice,
  26. // this list of conditions and the following disclaimer in the documentation
  27. // and/or other materials provided with the distribution.
  28. //
  29. // * The name of the copyright holders may not be used to endorse or promote products
  30. // derived from this software without specific prior written permission.
  31. //
  32. // This software is provided by the copyright holders and contributors "as is" and
  33. // any express or implied warranties, including, but not limited to, the implied
  34. // warranties of merchantability and fitness for a particular purpose are disclaimed.
  35. // In no event shall the Intel Corporation or contributors be liable for any direct,
  36. // indirect, incidental, special, exemplary, or consequential damages
  37. // (including, but not limited to, procurement of substitute goods or services;
  38. // loss of use, data, or profits; or business interruption) however caused
  39. // and on any theory of liability, whether in contract, strict liability,
  40. // or tort (including negligence or otherwise) arising in any way out of
  41. // the use of this software, even if advised of the possibility of such damage.
  42. //
  43. //M*/
  44. #ifndef OPENCV_CORE_UTILITY_H
  45. #define OPENCV_CORE_UTILITY_H
  46. #ifndef __cplusplus
  47. # error utility.hpp header must be compiled as C++
  48. #endif
  49. #if defined(check)
  50. # warning Detected Apple 'check' macro definition, it can cause build conflicts. Please, include this header before any Apple headers.
  51. #endif
  52. #include "opencv2/core.hpp"
  53. #include <ostream>
  54. #include <functional>
  55. #if !defined(_M_CEE)
  56. #include <mutex> // std::mutex, std::lock_guard
  57. #endif
  58. namespace cv
  59. {
  60. //! @addtogroup core_utils
  61. //! @{
  62. /** @brief Automatically Allocated Buffer Class
  63. The class is used for temporary buffers in functions and methods.
  64. If a temporary buffer is usually small (a few K's of memory),
  65. but its size depends on the parameters, it makes sense to create a small
  66. fixed-size array on stack and use it if it's large enough. If the required buffer size
  67. is larger than the fixed size, another buffer of sufficient size is allocated dynamically
  68. and released after the processing. Therefore, in typical cases, when the buffer size is small,
  69. there is no overhead associated with malloc()/free().
  70. At the same time, there is no limit on the size of processed data.
  71. This is what AutoBuffer does. The template takes 2 parameters - type of the buffer elements and
  72. the number of stack-allocated elements. Here is how the class is used:
  73. \code
  74. void my_func(const cv::Mat& m)
  75. {
  76. cv::AutoBuffer<float> buf(1000); // create automatic buffer containing 1000 floats
  77. buf.allocate(m.rows); // if m.rows <= 1000, the pre-allocated buffer is used,
  78. // otherwise the buffer of "m.rows" floats will be allocated
  79. // dynamically and deallocated in cv::AutoBuffer destructor
  80. ...
  81. }
  82. \endcode
  83. */
  84. #ifdef OPENCV_ENABLE_MEMORY_SANITIZER
  85. template<typename _Tp, size_t fixed_size = 0> class AutoBuffer
  86. #else
  87. template<typename _Tp, size_t fixed_size = 1024/sizeof(_Tp)+8> class AutoBuffer
  88. #endif
  89. {
  90. public:
  91. typedef _Tp value_type;
  92. //! the default constructor
  93. AutoBuffer();
  94. //! constructor taking the real buffer size
  95. explicit AutoBuffer(size_t _size);
  96. //! the copy constructor
  97. AutoBuffer(const AutoBuffer<_Tp, fixed_size>& buf);
  98. //! the assignment operator
  99. AutoBuffer<_Tp, fixed_size>& operator = (const AutoBuffer<_Tp, fixed_size>& buf);
  100. //! destructor. calls deallocate()
  101. ~AutoBuffer();
  102. //! allocates the new buffer of size _size. if the _size is small enough, stack-allocated buffer is used
  103. void allocate(size_t _size);
  104. //! deallocates the buffer if it was dynamically allocated
  105. void deallocate();
  106. //! resizes the buffer and preserves the content
  107. void resize(size_t _size);
  108. //! returns the current buffer size
  109. size_t size() const;
  110. //! returns pointer to the real buffer, stack-allocated or heap-allocated
  111. inline _Tp* data() { return ptr; }
  112. //! returns read-only pointer to the real buffer, stack-allocated or heap-allocated
  113. inline const _Tp* data() const { return ptr; }
  114. #if !defined(OPENCV_DISABLE_DEPRECATED_COMPATIBILITY) // use to .data() calls instead
  115. //! returns pointer to the real buffer, stack-allocated or heap-allocated
  116. operator _Tp* () { return ptr; }
  117. //! returns read-only pointer to the real buffer, stack-allocated or heap-allocated
  118. operator const _Tp* () const { return ptr; }
  119. #else
  120. //! returns a reference to the element at specified location. No bounds checking is performed in Release builds.
  121. inline _Tp& operator[] (size_t i) { CV_DbgCheckLT(i, sz, "out of range"); return ptr[i]; }
  122. //! returns a reference to the element at specified location. No bounds checking is performed in Release builds.
  123. inline const _Tp& operator[] (size_t i) const { CV_DbgCheckLT(i, sz, "out of range"); return ptr[i]; }
  124. #endif
  125. protected:
  126. //! pointer to the real buffer, can point to buf if the buffer is small enough
  127. _Tp* ptr;
  128. //! size of the real buffer
  129. size_t sz;
  130. //! pre-allocated buffer. At least 1 element to confirm C++ standard requirements
  131. _Tp buf[(fixed_size > 0) ? fixed_size : 1];
  132. };
  133. /** @brief Sets/resets the break-on-error mode.
  134. When the break-on-error mode is set, the default error handler issues a hardware exception, which
  135. can make debugging more convenient.
  136. \return the previous state
  137. */
  138. CV_EXPORTS bool setBreakOnError(bool flag);
  139. extern "C" typedef int (*ErrorCallback)( int status, const char* func_name,
  140. const char* err_msg, const char* file_name,
  141. int line, void* userdata );
  142. /** @brief Sets the new error handler and the optional user data.
  143. The function sets the new error handler, called from cv::error().
  144. \param errCallback the new error handler. If NULL, the default error handler is used.
  145. \param userdata the optional user data pointer, passed to the callback.
  146. \param prevUserdata the optional output parameter where the previous user data pointer is stored
  147. \return the previous error handler
  148. */
  149. CV_EXPORTS ErrorCallback redirectError( ErrorCallback errCallback, void* userdata=0, void** prevUserdata=0);
  150. CV_EXPORTS String tempfile( const char* suffix = 0);
  151. CV_EXPORTS void glob(String pattern, std::vector<String>& result, bool recursive = false);
  152. /** @brief OpenCV will try to set the number of threads for subsequent parallel regions.
  153. If threads == 1, OpenCV will disable threading optimizations and run all it's functions
  154. sequentially. Passing threads \< 0 will reset threads number to system default.
  155. The function is not thread-safe. It must not be called in parallel region or concurrent threads.
  156. OpenCV will try to run its functions with specified threads number, but some behaviour differs from
  157. framework:
  158. - `TBB` - User-defined parallel constructions will run with the same threads number, if
  159. another is not specified. If later on user creates his own scheduler, OpenCV will use it.
  160. - `OpenMP` - No special defined behaviour.
  161. - `Concurrency` - If threads == 1, OpenCV will disable threading optimizations and run its
  162. functions sequentially.
  163. - `GCD` - Supports only values \<= 0.
  164. - `C=` - No special defined behaviour.
  165. @param nthreads Number of threads used by OpenCV.
  166. @sa getNumThreads, getThreadNum
  167. */
  168. CV_EXPORTS_W void setNumThreads(int nthreads);
  169. /** @brief Returns the number of threads used by OpenCV for parallel regions.
  170. Always returns 1 if OpenCV is built without threading support.
  171. The exact meaning of return value depends on the threading framework used by OpenCV library:
  172. - `TBB` - The number of threads, that OpenCV will try to use for parallel regions. If there is
  173. any tbb::thread_scheduler_init in user code conflicting with OpenCV, then function returns
  174. default number of threads used by TBB library.
  175. - `OpenMP` - An upper bound on the number of threads that could be used to form a new team.
  176. - `Concurrency` - The number of threads, that OpenCV will try to use for parallel regions.
  177. - `GCD` - Unsupported; returns the GCD thread pool limit (512) for compatibility.
  178. - `C=` - The number of threads, that OpenCV will try to use for parallel regions, if before
  179. called setNumThreads with threads \> 0, otherwise returns the number of logical CPUs,
  180. available for the process.
  181. @sa setNumThreads, getThreadNum
  182. */
  183. CV_EXPORTS_W int getNumThreads();
  184. /** @brief Returns the index of the currently executed thread within the current parallel region. Always
  185. returns 0 if called outside of parallel region.
  186. @deprecated Current implementation doesn't corresponding to this documentation.
  187. The exact meaning of the return value depends on the threading framework used by OpenCV library:
  188. - `TBB` - Unsupported with current 4.1 TBB release. Maybe will be supported in future.
  189. - `OpenMP` - The thread number, within the current team, of the calling thread.
  190. - `Concurrency` - An ID for the virtual processor that the current context is executing on (0
  191. for master thread and unique number for others, but not necessary 1,2,3,...).
  192. - `GCD` - System calling thread's ID. Never returns 0 inside parallel region.
  193. - `C=` - The index of the current parallel task.
  194. @sa setNumThreads, getNumThreads
  195. */
  196. CV_EXPORTS_W int getThreadNum();
  197. /** @brief Returns full configuration time cmake output.
  198. Returned value is raw cmake output including version control system revision, compiler version,
  199. compiler flags, enabled modules and third party libraries, etc. Output format depends on target
  200. architecture.
  201. */
  202. CV_EXPORTS_W const String& getBuildInformation();
  203. /** @brief Returns library version string
  204. For example "3.4.1-dev".
  205. @sa getMajorVersion, getMinorVersion, getRevisionVersion
  206. */
  207. CV_EXPORTS_W String getVersionString();
  208. /** @brief Returns major library version */
  209. CV_EXPORTS_W int getVersionMajor();
  210. /** @brief Returns minor library version */
  211. CV_EXPORTS_W int getVersionMinor();
  212. /** @brief Returns revision field of the library version */
  213. CV_EXPORTS_W int getVersionRevision();
  214. /** @brief Returns the number of ticks.
  215. The function returns the number of ticks after the certain event (for example, when the machine was
  216. turned on). It can be used to initialize RNG or to measure a function execution time by reading the
  217. tick count before and after the function call.
  218. @sa getTickFrequency, TickMeter
  219. */
  220. CV_EXPORTS_W int64 getTickCount();
  221. /** @brief Returns the number of ticks per second.
  222. The function returns the number of ticks per second. That is, the following code computes the
  223. execution time in seconds:
  224. @code
  225. double t = (double)getTickCount();
  226. // do something ...
  227. t = ((double)getTickCount() - t)/getTickFrequency();
  228. @endcode
  229. @sa getTickCount, TickMeter
  230. */
  231. CV_EXPORTS_W double getTickFrequency();
  232. /** @brief a Class to measure passing time.
  233. The class computes passing time by counting the number of ticks per second. That is, the following code computes the
  234. execution time in seconds:
  235. @snippet snippets/core_various.cpp TickMeter_total
  236. It is also possible to compute the average time over multiple runs:
  237. @snippet snippets/core_various.cpp TickMeter_average
  238. @sa getTickCount, getTickFrequency
  239. */
  240. class CV_EXPORTS_W TickMeter
  241. {
  242. public:
  243. //! the default constructor
  244. CV_WRAP TickMeter()
  245. {
  246. reset();
  247. }
  248. //! starts counting ticks.
  249. CV_WRAP void start()
  250. {
  251. startTime = cv::getTickCount();
  252. }
  253. //! stops counting ticks.
  254. CV_WRAP void stop()
  255. {
  256. int64 time = cv::getTickCount();
  257. if (startTime == 0)
  258. return;
  259. ++counter;
  260. sumTime += (time - startTime);
  261. startTime = 0;
  262. }
  263. //! returns counted ticks.
  264. CV_WRAP int64 getTimeTicks() const
  265. {
  266. return sumTime;
  267. }
  268. //! returns passed time in microseconds.
  269. CV_WRAP double getTimeMicro() const
  270. {
  271. return getTimeMilli()*1e3;
  272. }
  273. //! returns passed time in milliseconds.
  274. CV_WRAP double getTimeMilli() const
  275. {
  276. return getTimeSec()*1e3;
  277. }
  278. //! returns passed time in seconds.
  279. CV_WRAP double getTimeSec() const
  280. {
  281. return (double)getTimeTicks() / getTickFrequency();
  282. }
  283. //! returns internal counter value.
  284. CV_WRAP int64 getCounter() const
  285. {
  286. return counter;
  287. }
  288. //! returns average FPS (frames per second) value.
  289. CV_WRAP double getFPS() const
  290. {
  291. const double sec = getTimeSec();
  292. if (sec < DBL_EPSILON)
  293. return 0.;
  294. return counter / sec;
  295. }
  296. //! returns average time in seconds
  297. CV_WRAP double getAvgTimeSec() const
  298. {
  299. if (counter <= 0)
  300. return 0.;
  301. return getTimeSec() / counter;
  302. }
  303. //! returns average time in milliseconds
  304. CV_WRAP double getAvgTimeMilli() const
  305. {
  306. return getAvgTimeSec() * 1e3;
  307. }
  308. //! resets internal values.
  309. CV_WRAP void reset()
  310. {
  311. startTime = 0;
  312. sumTime = 0;
  313. counter = 0;
  314. }
  315. private:
  316. int64 counter;
  317. int64 sumTime;
  318. int64 startTime;
  319. };
  320. /** @brief output operator
  321. @code
  322. TickMeter tm;
  323. tm.start();
  324. // do something ...
  325. tm.stop();
  326. std::cout << tm;
  327. @endcode
  328. */
  329. static inline
  330. std::ostream& operator << (std::ostream& out, const TickMeter& tm)
  331. {
  332. return out << tm.getTimeSec() << "sec";
  333. }
  334. /** @brief Returns the number of CPU ticks.
  335. The function returns the current number of CPU ticks on some architectures (such as x86, x64,
  336. PowerPC). On other platforms the function is equivalent to getTickCount. It can also be used for
  337. very accurate time measurements, as well as for RNG initialization. Note that in case of multi-CPU
  338. systems a thread, from which getCPUTickCount is called, can be suspended and resumed at another CPU
  339. with its own counter. So, theoretically (and practically) the subsequent calls to the function do
  340. not necessary return the monotonously increasing values. Also, since a modern CPU varies the CPU
  341. frequency depending on the load, the number of CPU clocks spent in some code cannot be directly
  342. converted to time units. Therefore, getTickCount is generally a preferable solution for measuring
  343. execution time.
  344. */
  345. CV_EXPORTS_W int64 getCPUTickCount();
  346. /** @brief Returns true if the specified feature is supported by the host hardware.
  347. The function returns true if the host hardware supports the specified feature. When user calls
  348. setUseOptimized(false), the subsequent calls to checkHardwareSupport() will return false until
  349. setUseOptimized(true) is called. This way user can dynamically switch on and off the optimized code
  350. in OpenCV.
  351. @param feature The feature of interest, one of cv::CpuFeatures
  352. */
  353. CV_EXPORTS_W bool checkHardwareSupport(int feature);
  354. /** @brief Returns feature name by ID
  355. Returns empty string if feature is not defined
  356. */
  357. CV_EXPORTS_W String getHardwareFeatureName(int feature);
  358. /** @brief Returns list of CPU features enabled during compilation.
  359. Returned value is a string containing space separated list of CPU features with following markers:
  360. - no markers - baseline features
  361. - prefix `*` - features enabled in dispatcher
  362. - suffix `?` - features enabled but not available in HW
  363. Example: `SSE SSE2 SSE3 *SSE4.1 *SSE4.2 *FP16 *AVX *AVX2 *AVX512-SKX?`
  364. */
  365. CV_EXPORTS_W std::string getCPUFeaturesLine();
  366. /** @brief Returns the number of logical CPUs available for the process.
  367. */
  368. CV_EXPORTS_W int getNumberOfCPUs();
  369. /** @brief Aligns a pointer to the specified number of bytes.
  370. The function returns the aligned pointer of the same type as the input pointer:
  371. \f[\texttt{(_Tp*)(((size_t)ptr + n-1) & -n)}\f]
  372. @param ptr Aligned pointer.
  373. @param n Alignment size that must be a power of two.
  374. */
  375. template<typename _Tp> static inline _Tp* alignPtr(_Tp* ptr, int n=(int)sizeof(_Tp))
  376. {
  377. CV_DbgAssert((n & (n - 1)) == 0); // n is a power of 2
  378. return (_Tp*)(((size_t)ptr + n-1) & -n);
  379. }
  380. /** @brief Aligns a buffer size to the specified number of bytes.
  381. The function returns the minimum number that is greater than or equal to sz and is divisible by n :
  382. \f[\texttt{(sz + n-1) & -n}\f]
  383. @param sz Buffer size to align.
  384. @param n Alignment size that must be a power of two.
  385. */
  386. static inline size_t alignSize(size_t sz, int n)
  387. {
  388. CV_DbgAssert((n & (n - 1)) == 0); // n is a power of 2
  389. return (sz + n-1) & -n;
  390. }
  391. /** @brief Integer division with result round up.
  392. Use this function instead of `ceil((float)a / b)` expressions.
  393. @sa alignSize
  394. */
  395. static inline int divUp(int a, unsigned int b)
  396. {
  397. CV_DbgAssert(a >= 0);
  398. return (a + b - 1) / b;
  399. }
  400. /** @overload */
  401. static inline size_t divUp(size_t a, unsigned int b)
  402. {
  403. return (a + b - 1) / b;
  404. }
  405. /** @brief Round first value up to the nearest multiple of second value.
  406. Use this function instead of `ceil((float)a / b) * b` expressions.
  407. @sa divUp
  408. */
  409. static inline int roundUp(int a, unsigned int b)
  410. {
  411. CV_DbgAssert(a >= 0);
  412. return a + b - 1 - (a + b -1) % b;
  413. }
  414. /** @overload */
  415. static inline size_t roundUp(size_t a, unsigned int b)
  416. {
  417. return a + b - 1 - (a + b - 1) % b;
  418. }
  419. /** @brief Alignment check of passed values
  420. Usage: `isAligned<sizeof(int)>(...)`
  421. @note Alignment(N) must be a power of 2 (2**k, 2^k)
  422. */
  423. template<int N, typename T> static inline
  424. bool isAligned(const T& data)
  425. {
  426. CV_StaticAssert((N & (N - 1)) == 0, ""); // power of 2
  427. return (((size_t)data) & (N - 1)) == 0;
  428. }
  429. /** @overload */
  430. template<int N> static inline
  431. bool isAligned(const void* p1)
  432. {
  433. return isAligned<N>((size_t)p1);
  434. }
  435. /** @overload */
  436. template<int N> static inline
  437. bool isAligned(const void* p1, const void* p2)
  438. {
  439. return isAligned<N>(((size_t)p1)|((size_t)p2));
  440. }
  441. /** @overload */
  442. template<int N> static inline
  443. bool isAligned(const void* p1, const void* p2, const void* p3)
  444. {
  445. return isAligned<N>(((size_t)p1)|((size_t)p2)|((size_t)p3));
  446. }
  447. /** @overload */
  448. template<int N> static inline
  449. bool isAligned(const void* p1, const void* p2, const void* p3, const void* p4)
  450. {
  451. return isAligned<N>(((size_t)p1)|((size_t)p2)|((size_t)p3)|((size_t)p4));
  452. }
  453. /** @brief Enables or disables the optimized code.
  454. The function can be used to dynamically turn on and off optimized dispatched code (code that uses SSE4.2, AVX/AVX2,
  455. and other instructions on the platforms that support it). It sets a global flag that is further
  456. checked by OpenCV functions. Since the flag is not checked in the inner OpenCV loops, it is only
  457. safe to call the function on the very top level in your application where you can be sure that no
  458. other OpenCV function is currently executed.
  459. By default, the optimized code is enabled unless you disable it in CMake. The current status can be
  460. retrieved using useOptimized.
  461. @param onoff The boolean flag specifying whether the optimized code should be used (onoff=true)
  462. or not (onoff=false).
  463. */
  464. CV_EXPORTS_W void setUseOptimized(bool onoff);
  465. /** @brief Returns the status of optimized code usage.
  466. The function returns true if the optimized code is enabled. Otherwise, it returns false.
  467. */
  468. CV_EXPORTS_W bool useOptimized();
  469. static inline size_t getElemSize(int type) { return (size_t)CV_ELEM_SIZE(type); }
  470. /////////////////////////////// Parallel Primitives //////////////////////////////////
  471. /** @brief Base class for parallel data processors
  472. @ingroup core_parallel
  473. */
  474. class CV_EXPORTS ParallelLoopBody
  475. {
  476. public:
  477. virtual ~ParallelLoopBody();
  478. virtual void operator() (const Range& range) const = 0;
  479. };
  480. /** @brief Parallel data processor
  481. @ingroup core_parallel
  482. */
  483. CV_EXPORTS void parallel_for_(const Range& range, const ParallelLoopBody& body, double nstripes=-1.);
  484. //! @ingroup core_parallel
  485. class ParallelLoopBodyLambdaWrapper : public ParallelLoopBody
  486. {
  487. private:
  488. std::function<void(const Range&)> m_functor;
  489. public:
  490. inline
  491. ParallelLoopBodyLambdaWrapper(std::function<void(const Range&)> functor)
  492. : m_functor(functor)
  493. {
  494. // nothing
  495. }
  496. virtual void operator() (const cv::Range& range) const CV_OVERRIDE
  497. {
  498. m_functor(range);
  499. }
  500. };
  501. //! @ingroup core_parallel
  502. static inline
  503. void parallel_for_(const Range& range, std::function<void(const Range&)> functor, double nstripes=-1.)
  504. {
  505. parallel_for_(range, ParallelLoopBodyLambdaWrapper(functor), nstripes);
  506. }
  507. /////////////////////////////// forEach method of cv::Mat ////////////////////////////
  508. template<typename _Tp, typename Functor> inline
  509. void Mat::forEach_impl(const Functor& operation) {
  510. if (false) {
  511. operation(*reinterpret_cast<_Tp*>(0), reinterpret_cast<int*>(0));
  512. // If your compiler fails in this line.
  513. // Please check that your functor signature is
  514. // (_Tp&, const int*) <- multi-dimensional
  515. // or (_Tp&, void*) <- in case you don't need current idx.
  516. }
  517. CV_Assert(!empty());
  518. CV_Assert(this->total() / this->size[this->dims - 1] <= INT_MAX);
  519. const int LINES = static_cast<int>(this->total() / this->size[this->dims - 1]);
  520. class PixelOperationWrapper :public ParallelLoopBody
  521. {
  522. public:
  523. PixelOperationWrapper(Mat_<_Tp>* const frame, const Functor& _operation)
  524. : mat(frame), op(_operation) {}
  525. virtual ~PixelOperationWrapper(){}
  526. // ! Overloaded virtual operator
  527. // convert range call to row call.
  528. virtual void operator()(const Range &range) const CV_OVERRIDE
  529. {
  530. const int DIMS = mat->dims;
  531. const int COLS = mat->size[DIMS - 1];
  532. if (DIMS <= 2) {
  533. for (int row = range.start; row < range.end; ++row) {
  534. this->rowCall2(row, COLS);
  535. }
  536. } else {
  537. std::vector<int> idx(DIMS); /// idx is modified in this->rowCall
  538. idx[DIMS - 2] = range.start - 1;
  539. for (int line_num = range.start; line_num < range.end; ++line_num) {
  540. idx[DIMS - 2]++;
  541. for (int i = DIMS - 2; i >= 0; --i) {
  542. if (idx[i] >= mat->size[i]) {
  543. idx[i - 1] += idx[i] / mat->size[i];
  544. idx[i] %= mat->size[i];
  545. continue; // carry-over;
  546. }
  547. else {
  548. break;
  549. }
  550. }
  551. this->rowCall(&idx[0], COLS, DIMS);
  552. }
  553. }
  554. }
  555. private:
  556. Mat_<_Tp>* const mat;
  557. const Functor op;
  558. // ! Call operator for each elements in this row.
  559. inline void rowCall(int* const idx, const int COLS, const int DIMS) const {
  560. int &col = idx[DIMS - 1];
  561. col = 0;
  562. _Tp* pixel = &(mat->template at<_Tp>(idx));
  563. while (col < COLS) {
  564. op(*pixel, const_cast<const int*>(idx));
  565. pixel++; col++;
  566. }
  567. col = 0;
  568. }
  569. // ! Call operator for each elements in this row. 2d mat special version.
  570. inline void rowCall2(const int row, const int COLS) const {
  571. union Index{
  572. int body[2];
  573. operator const int*() const {
  574. return reinterpret_cast<const int*>(this);
  575. }
  576. int& operator[](const int i) {
  577. return body[i];
  578. }
  579. } idx = {{row, 0}};
  580. // Special union is needed to avoid
  581. // "error: array subscript is above array bounds [-Werror=array-bounds]"
  582. // when call the functor `op` such that access idx[3].
  583. _Tp* pixel = &(mat->template at<_Tp>(idx));
  584. const _Tp* const pixel_end = pixel + COLS;
  585. while(pixel < pixel_end) {
  586. op(*pixel++, static_cast<const int*>(idx));
  587. idx[1]++;
  588. }
  589. }
  590. PixelOperationWrapper& operator=(const PixelOperationWrapper &) {
  591. CV_Assert(false);
  592. // We can not remove this implementation because Visual Studio warning C4822.
  593. return *this;
  594. }
  595. };
  596. parallel_for_(cv::Range(0, LINES), PixelOperationWrapper(reinterpret_cast<Mat_<_Tp>*>(this), operation));
  597. }
  598. /////////////////////////// Synchronization Primitives ///////////////////////////////
  599. #if !defined(_M_CEE)
  600. #ifndef OPENCV_DISABLE_THREAD_SUPPORT
  601. typedef std::recursive_mutex Mutex;
  602. typedef std::lock_guard<cv::Mutex> AutoLock;
  603. #else // OPENCV_DISABLE_THREAD_SUPPORT
  604. // Custom (failing) implementation of `std::recursive_mutex`.
  605. struct Mutex {
  606. void lock(){
  607. CV_Error(cv::Error::StsNotImplemented,
  608. "cv::Mutex is disabled by OPENCV_DISABLE_THREAD_SUPPORT=ON");
  609. }
  610. void unlock(){
  611. CV_Error(cv::Error::StsNotImplemented,
  612. "cv::Mutex is disabled by OPENCV_DISABLE_THREAD_SUPPORT=ON");
  613. }
  614. };
  615. // Stub for cv::AutoLock when threads are disabled.
  616. struct AutoLock {
  617. AutoLock(Mutex &) { }
  618. };
  619. #endif // OPENCV_DISABLE_THREAD_SUPPORT
  620. #endif // !defined(_M_CEE)
  621. /** @brief Designed for command line parsing
  622. The sample below demonstrates how to use CommandLineParser:
  623. @code
  624. CommandLineParser parser(argc, argv, keys);
  625. parser.about("Application name v1.0.0");
  626. if (parser.has("help"))
  627. {
  628. parser.printMessage();
  629. return 0;
  630. }
  631. int N = parser.get<int>("N");
  632. double fps = parser.get<double>("fps");
  633. String path = parser.get<String>("path");
  634. use_time_stamp = parser.has("timestamp");
  635. String img1 = parser.get<String>(0);
  636. String img2 = parser.get<String>(1);
  637. int repeat = parser.get<int>(2);
  638. if (!parser.check())
  639. {
  640. parser.printErrors();
  641. return 0;
  642. }
  643. @endcode
  644. ### Keys syntax
  645. The keys parameter is a string containing several blocks, each one is enclosed in curly braces and
  646. describes one argument. Each argument contains three parts separated by the `|` symbol:
  647. -# argument names is a list of option synonyms separated by standard space characters ' ' (to mark argument as positional, prefix it with the `@` symbol)
  648. -# default value will be used if the argument was not provided (can be empty)
  649. -# help message (can be empty)
  650. For example:
  651. @code{.cpp}
  652. const String keys =
  653. "{help h usage ? | | print this message }"
  654. "{@image1 | | image1 for compare }"
  655. "{@image2 |<none>| image2 for compare }"
  656. "{@repeat |1 | number }"
  657. "{path |. | path to file }"
  658. "{fps | -1.0 | fps for output video }"
  659. "{N count |100 | count of objects }"
  660. "{ts timestamp | | use time stamp }"
  661. ;
  662. }
  663. @endcode
  664. Note that there are no default values for `help` and `timestamp` so we can check their presence using the `has()` method.
  665. Arguments with default values are considered to be always present. Use the `get()` method in these cases to check their
  666. actual value instead.
  667. Note that whitespace characters other than standard spaces are considered part of the string.
  668. Additionally, leading and trailing standard spaces around the help messages are ignored.
  669. String keys like `get<String>("@image1")` return the empty string `""` by default - even with an empty default value.
  670. Use the special `<none>` default value to enforce that the returned string must not be empty. (like in `get<String>("@image2")`)
  671. ### Usage
  672. For the described keys:
  673. @code{.sh}
  674. # Good call (3 positional parameters: image1, image2 and repeat; N is 200, ts is true)
  675. $ ./app -N=200 1.png 2.jpg 19 -ts
  676. # Bad call
  677. $ ./app -fps=aaa
  678. ERRORS:
  679. Parameter 'fps': can not convert: [aaa] to [double]
  680. @endcode
  681. */
  682. class CV_EXPORTS CommandLineParser
  683. {
  684. public:
  685. /** @brief Constructor
  686. Initializes command line parser object
  687. @param argc number of command line arguments (from main())
  688. @param argv array of command line arguments (from main())
  689. @param keys string describing acceptable command line parameters (see class description for syntax)
  690. */
  691. CommandLineParser(int argc, const char* const argv[], const String& keys);
  692. /** @brief Copy constructor */
  693. CommandLineParser(const CommandLineParser& parser);
  694. /** @brief Assignment operator */
  695. CommandLineParser& operator = (const CommandLineParser& parser);
  696. /** @brief Destructor */
  697. ~CommandLineParser();
  698. /** @brief Returns application path
  699. This method returns the path to the executable from the command line (`argv[0]`).
  700. For example, if the application has been started with such a command:
  701. @code{.sh}
  702. $ ./bin/my-executable
  703. @endcode
  704. this method will return `./bin`.
  705. */
  706. String getPathToApplication() const;
  707. /** @brief Access arguments by name
  708. Returns argument converted to selected type. If the argument is not known or can not be
  709. converted to selected type, the error flag is set (can be checked with @ref check).
  710. For example, define:
  711. @code{.cpp}
  712. String keys = "{N count||}";
  713. @endcode
  714. Call:
  715. @code{.sh}
  716. $ ./my-app -N=20
  717. # or
  718. $ ./my-app --count=20
  719. @endcode
  720. Access:
  721. @code{.cpp}
  722. int N = parser.get<int>("N");
  723. @endcode
  724. @param name name of the argument
  725. @param space_delete remove spaces from the left and right of the string
  726. @tparam T the argument will be converted to this type if possible
  727. @note You can access positional arguments by their `@`-prefixed name:
  728. @code{.cpp}
  729. parser.get<String>("@image");
  730. @endcode
  731. */
  732. template <typename T>
  733. T get(const String& name, bool space_delete = true) const
  734. {
  735. T val = T();
  736. getByName(name, space_delete, ParamType<T>::type, (void*)&val);
  737. return val;
  738. }
  739. /** @brief Access positional arguments by index
  740. Returns argument converted to selected type. Indexes are counted from zero.
  741. For example, define:
  742. @code{.cpp}
  743. String keys = "{@arg1||}{@arg2||}"
  744. @endcode
  745. Call:
  746. @code{.sh}
  747. ./my-app abc qwe
  748. @endcode
  749. Access arguments:
  750. @code{.cpp}
  751. String val_1 = parser.get<String>(0); // returns "abc", arg1
  752. String val_2 = parser.get<String>(1); // returns "qwe", arg2
  753. @endcode
  754. @param index index of the argument
  755. @param space_delete remove spaces from the left and right of the string
  756. @tparam T the argument will be converted to this type if possible
  757. */
  758. template <typename T>
  759. T get(int index, bool space_delete = true) const
  760. {
  761. T val = T();
  762. getByIndex(index, space_delete, ParamType<T>::type, (void*)&val);
  763. return val;
  764. }
  765. /** @brief Check if field was provided in the command line
  766. @param name argument name to check
  767. */
  768. bool has(const String& name) const;
  769. /** @brief Check for parsing errors
  770. Returns false if error occurred while accessing the parameters (bad conversion, missing arguments,
  771. etc.). Call @ref printErrors to print error messages list.
  772. */
  773. bool check() const;
  774. /** @brief Set the about message
  775. The about message will be shown when @ref printMessage is called, right before arguments table.
  776. */
  777. void about(const String& message);
  778. /** @brief Print help message
  779. This method will print standard help message containing the about message and arguments description.
  780. @sa about
  781. */
  782. void printMessage() const;
  783. /** @brief Print list of errors occurred
  784. @sa check
  785. */
  786. void printErrors() const;
  787. protected:
  788. void getByName(const String& name, bool space_delete, Param type, void* dst) const;
  789. void getByIndex(int index, bool space_delete, Param type, void* dst) const;
  790. struct Impl;
  791. Impl* impl;
  792. };
  793. //! @} core_utils
  794. //! @cond IGNORED
  795. /////////////////////////////// AutoBuffer implementation ////////////////////////////////////////
  796. template<typename _Tp, size_t fixed_size> inline
  797. AutoBuffer<_Tp, fixed_size>::AutoBuffer()
  798. {
  799. ptr = buf;
  800. sz = fixed_size;
  801. }
  802. template<typename _Tp, size_t fixed_size> inline
  803. AutoBuffer<_Tp, fixed_size>::AutoBuffer(size_t _size)
  804. {
  805. ptr = buf;
  806. sz = fixed_size;
  807. allocate(_size);
  808. }
  809. template<typename _Tp, size_t fixed_size> inline
  810. AutoBuffer<_Tp, fixed_size>::AutoBuffer(const AutoBuffer<_Tp, fixed_size>& abuf )
  811. {
  812. ptr = buf;
  813. sz = fixed_size;
  814. allocate(abuf.size());
  815. for( size_t i = 0; i < sz; i++ )
  816. ptr[i] = abuf.ptr[i];
  817. }
  818. template<typename _Tp, size_t fixed_size> inline AutoBuffer<_Tp, fixed_size>&
  819. AutoBuffer<_Tp, fixed_size>::operator = (const AutoBuffer<_Tp, fixed_size>& abuf)
  820. {
  821. if( this != &abuf )
  822. {
  823. deallocate();
  824. allocate(abuf.size());
  825. for( size_t i = 0; i < sz; i++ )
  826. ptr[i] = abuf.ptr[i];
  827. }
  828. return *this;
  829. }
  830. template<typename _Tp, size_t fixed_size> inline
  831. AutoBuffer<_Tp, fixed_size>::~AutoBuffer()
  832. { deallocate(); }
  833. template<typename _Tp, size_t fixed_size> inline void
  834. AutoBuffer<_Tp, fixed_size>::allocate(size_t _size)
  835. {
  836. if(_size <= sz)
  837. {
  838. sz = _size;
  839. return;
  840. }
  841. deallocate();
  842. sz = _size;
  843. if(_size > fixed_size)
  844. {
  845. ptr = new _Tp[_size];
  846. }
  847. }
  848. template<typename _Tp, size_t fixed_size> inline void
  849. AutoBuffer<_Tp, fixed_size>::deallocate()
  850. {
  851. if( ptr != buf )
  852. {
  853. delete[] ptr;
  854. ptr = buf;
  855. sz = fixed_size;
  856. }
  857. }
  858. template<typename _Tp, size_t fixed_size> inline void
  859. AutoBuffer<_Tp, fixed_size>::resize(size_t _size)
  860. {
  861. if(_size <= sz)
  862. {
  863. sz = _size;
  864. return;
  865. }
  866. size_t i, prevsize = sz, minsize = MIN(prevsize, _size);
  867. _Tp* prevptr = ptr;
  868. ptr = _size > fixed_size ? new _Tp[_size] : buf;
  869. sz = _size;
  870. if( ptr != prevptr )
  871. for( i = 0; i < minsize; i++ )
  872. ptr[i] = prevptr[i];
  873. for( i = prevsize; i < _size; i++ )
  874. ptr[i] = _Tp();
  875. if( prevptr != buf )
  876. delete[] prevptr;
  877. }
  878. template<typename _Tp, size_t fixed_size> inline size_t
  879. AutoBuffer<_Tp, fixed_size>::size() const
  880. { return sz; }
  881. //! @endcond
  882. // Basic Node class for tree building
  883. template<class OBJECT>
  884. class CV_EXPORTS Node
  885. {
  886. public:
  887. Node()
  888. {
  889. m_pParent = 0;
  890. }
  891. Node(OBJECT& payload) : m_payload(payload)
  892. {
  893. m_pParent = 0;
  894. }
  895. ~Node()
  896. {
  897. removeChilds();
  898. if (m_pParent)
  899. {
  900. int idx = m_pParent->findChild(this);
  901. if (idx >= 0)
  902. m_pParent->m_childs.erase(m_pParent->m_childs.begin() + idx);
  903. }
  904. }
  905. Node<OBJECT>* findChild(OBJECT& payload) const
  906. {
  907. for(size_t i = 0; i < this->m_childs.size(); i++)
  908. {
  909. if(this->m_childs[i]->m_payload == payload)
  910. return this->m_childs[i];
  911. }
  912. return NULL;
  913. }
  914. int findChild(Node<OBJECT> *pNode) const
  915. {
  916. for (size_t i = 0; i < this->m_childs.size(); i++)
  917. {
  918. if(this->m_childs[i] == pNode)
  919. return (int)i;
  920. }
  921. return -1;
  922. }
  923. void addChild(Node<OBJECT> *pNode)
  924. {
  925. if(!pNode)
  926. return;
  927. CV_Assert(pNode->m_pParent == 0);
  928. pNode->m_pParent = this;
  929. this->m_childs.push_back(pNode);
  930. }
  931. void removeChilds()
  932. {
  933. for(size_t i = 0; i < m_childs.size(); i++)
  934. {
  935. m_childs[i]->m_pParent = 0; // avoid excessive parent vector trimming
  936. delete m_childs[i];
  937. }
  938. m_childs.clear();
  939. }
  940. int getDepth()
  941. {
  942. int count = 0;
  943. Node *pParent = m_pParent;
  944. while(pParent) count++, pParent = pParent->m_pParent;
  945. return count;
  946. }
  947. public:
  948. OBJECT m_payload;
  949. Node<OBJECT>* m_pParent;
  950. std::vector<Node<OBJECT>*> m_childs;
  951. };
  952. namespace samples {
  953. //! @addtogroup core_utils_samples
  954. // This section describes utility functions for OpenCV samples.
  955. //
  956. // @note Implementation of these utilities is not thread-safe.
  957. //
  958. //! @{
  959. /** @brief Try to find requested data file
  960. Search directories:
  961. 1. Directories passed via `addSamplesDataSearchPath()`
  962. 2. OPENCV_SAMPLES_DATA_PATH_HINT environment variable
  963. 3. OPENCV_SAMPLES_DATA_PATH environment variable
  964. If parameter value is not empty and nothing is found then stop searching.
  965. 4. Detects build/install path based on:
  966. a. current working directory (CWD)
  967. b. and/or binary module location (opencv_core/opencv_world, doesn't work with static linkage)
  968. 5. Scan `<source>/{,data,samples/data}` directories if build directory is detected or the current directory is in source tree.
  969. 6. Scan `<install>/share/OpenCV` directory if install directory is detected.
  970. @see cv::utils::findDataFile
  971. @param relative_path Relative path to data file
  972. @param required Specify "file not found" handling.
  973. If true, function prints information message and raises cv::Exception.
  974. If false, function returns empty result
  975. @param silentMode Disables messages
  976. @return Returns path (absolute or relative to the current directory) or empty string if file is not found
  977. */
  978. CV_EXPORTS_W cv::String findFile(const cv::String& relative_path, bool required = true, bool silentMode = false);
  979. CV_EXPORTS_W cv::String findFileOrKeep(const cv::String& relative_path, bool silentMode = false);
  980. inline cv::String findFileOrKeep(const cv::String& relative_path, bool silentMode)
  981. {
  982. cv::String res = findFile(relative_path, false, silentMode);
  983. if (res.empty())
  984. return relative_path;
  985. return res;
  986. }
  987. /** @brief Override search data path by adding new search location
  988. Use this only to override default behavior
  989. Passed paths are used in LIFO order.
  990. @param path Path to used samples data
  991. */
  992. CV_EXPORTS_W void addSamplesDataSearchPath(const cv::String& path);
  993. /** @brief Append samples search data sub directory
  994. General usage is to add OpenCV modules name (`<opencv_contrib>/modules/<name>/samples/data` -> `<name>/samples/data` + `modules/<name>/samples/data`).
  995. Passed subdirectories are used in LIFO order.
  996. @param subdir samples data sub directory
  997. */
  998. CV_EXPORTS_W void addSamplesDataSearchSubDirectory(const cv::String& subdir);
  999. //! @}
  1000. } // namespace samples
  1001. namespace utils {
  1002. CV_EXPORTS int getThreadID();
  1003. } // namespace
  1004. } //namespace cv
  1005. #ifdef CV_COLLECT_IMPL_DATA
  1006. #include "opencv2/core/utils/instrumentation.hpp"
  1007. #else
  1008. /// Collect implementation data on OpenCV function call. Requires ENABLE_IMPL_COLLECTION build option.
  1009. #define CV_IMPL_ADD(impl)
  1010. #endif
  1011. #endif //OPENCV_CORE_UTILITY_H