utility.hpp 38 KB

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