utility.hpp 41 KB

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