utility.hpp 42 KB

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