utility.hpp 38 KB

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