utility.hpp 38 KB

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