utility.hpp 38 KB

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