Important changes to repositories hosted on mbed.com
Mbed hosted mercurial repositories are deprecated and are due to be permanently deleted in July 2026.
To keep a copy of this software download the repository Zip archive or clone locally using Mercurial.
It is also possible to export all your personal repositories from the account settings page.
Dependents: RZ_A2M_Mbed_samples
utility.hpp
00001 /*M/////////////////////////////////////////////////////////////////////////////////////// 00002 // 00003 // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. 00004 // 00005 // By downloading, copying, installing or using the software you agree to this license. 00006 // If you do not agree to this license, do not download, install, 00007 // copy or use the software. 00008 // 00009 // 00010 // License Agreement 00011 // For Open Source Computer Vision Library 00012 // 00013 // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. 00014 // Copyright (C) 2009, Willow Garage Inc., all rights reserved. 00015 // Copyright (C) 2013, OpenCV Foundation, all rights reserved. 00016 // Copyright (C) 2015, Itseez Inc., all rights reserved. 00017 // Third party copyrights are property of their respective owners. 00018 // 00019 // Redistribution and use in source and binary forms, with or without modification, 00020 // are permitted provided that the following conditions are met: 00021 // 00022 // * Redistribution's of source code must retain the above copyright notice, 00023 // this list of conditions and the following disclaimer. 00024 // 00025 // * Redistribution's in binary form must reproduce the above copyright notice, 00026 // this list of conditions and the following disclaimer in the documentation 00027 // and/or other materials provided with the distribution. 00028 // 00029 // * The name of the copyright holders may not be used to endorse or promote products 00030 // derived from this software without specific prior written permission. 00031 // 00032 // This software is provided by the copyright holders and contributors "as is" and 00033 // any express or implied warranties, including, but not limited to, the implied 00034 // warranties of merchantability and fitness for a particular purpose are disclaimed. 00035 // In no event shall the Intel Corporation or contributors be liable for any direct, 00036 // indirect, incidental, special, exemplary, or consequential damages 00037 // (including, but not limited to, procurement of substitute goods or services; 00038 // loss of use, data, or profits; or business interruption) however caused 00039 // and on any theory of liability, whether in contract, strict liability, 00040 // or tort (including negligence or otherwise) arising in any way out of 00041 // the use of this software, even if advised of the possibility of such damage. 00042 // 00043 //M*/ 00044 00045 #ifndef OPENCV_CORE_UTILITY_H 00046 #define OPENCV_CORE_UTILITY_H 00047 00048 #ifndef __cplusplus 00049 # error utility.hpp header must be compiled as C++ 00050 #endif 00051 00052 #if defined(check) 00053 # warning Detected Apple 'check' macro definition, it can cause build conflicts. Please, include this header before any Apple headers. 00054 #endif 00055 00056 #include "opencv2/core.hpp" 00057 00058 namespace cv 00059 { 00060 00061 #ifdef CV_COLLECT_IMPL_DATA 00062 CV_EXPORTS void setImpl(int flags); // set implementation flags and reset storage arrays 00063 CV_EXPORTS void addImpl(int flag, const char* func = 0); // add implementation and function name to storage arrays 00064 // Get stored implementation flags and fucntions names arrays 00065 // Each implementation entry correspond to function name entry, so you can find which implementation was executed in which fucntion 00066 CV_EXPORTS int getImpl(std::vector<int> &impl, std::vector<String> &funName); 00067 00068 CV_EXPORTS bool useCollection(); // return implementation collection state 00069 CV_EXPORTS void setUseCollection(bool flag); // set implementation collection state 00070 00071 #define CV_IMPL_PLAIN 0x01 // native CPU OpenCV implementation 00072 #define CV_IMPL_OCL 0x02 // OpenCL implementation 00073 #define CV_IMPL_IPP 0x04 // IPP implementation 00074 #define CV_IMPL_MT 0x10 // multithreaded implementation 00075 00076 #define CV_IMPL_ADD(impl) \ 00077 if(cv::useCollection()) \ 00078 { \ 00079 cv::addImpl(impl, CV_Func); \ 00080 } 00081 #else 00082 #define CV_IMPL_ADD(impl) 00083 #endif 00084 00085 //! @addtogroup core_utils 00086 //! @{ 00087 00088 /** @brief Automatically Allocated Buffer Class 00089 00090 The class is used for temporary buffers in functions and methods. 00091 If a temporary buffer is usually small (a few K's of memory), 00092 but its size depends on the parameters, it makes sense to create a small 00093 fixed-size array on stack and use it if it's large enough. If the required buffer size 00094 is larger than the fixed size, another buffer of sufficient size is allocated dynamically 00095 and released after the processing. Therefore, in typical cases, when the buffer size is small, 00096 there is no overhead associated with malloc()/free(). 00097 At the same time, there is no limit on the size of processed data. 00098 00099 This is what AutoBuffer does. The template takes 2 parameters - type of the buffer elements and 00100 the number of stack-allocated elements. Here is how the class is used: 00101 00102 \code 00103 void my_func(const cv::Mat& m) 00104 { 00105 cv::AutoBuffer<float> buf; // create automatic buffer containing 1000 floats 00106 00107 buf.allocate(m.rows); // if m.rows <= 1000, the pre-allocated buffer is used, 00108 // otherwise the buffer of "m.rows" floats will be allocated 00109 // dynamically and deallocated in cv::AutoBuffer destructor 00110 ... 00111 } 00112 \endcode 00113 */ 00114 template<typename _Tp, size_t fixed_size = 1024/sizeof(_Tp)+8> class AutoBuffer 00115 { 00116 public: 00117 typedef _Tp value_type; 00118 00119 //! the default constructor 00120 AutoBuffer(); 00121 //! constructor taking the real buffer size 00122 AutoBuffer(size_t _size); 00123 00124 //! the copy constructor 00125 AutoBuffer(const AutoBuffer<_Tp, fixed_size>& buf); 00126 //! the assignment operator 00127 AutoBuffer<_Tp, fixed_size>& operator = (const AutoBuffer<_Tp, fixed_size>& buf); 00128 00129 //! destructor. calls deallocate() 00130 ~AutoBuffer(); 00131 00132 //! allocates the new buffer of size _size. if the _size is small enough, stack-allocated buffer is used 00133 void allocate(size_t _size); 00134 //! deallocates the buffer if it was dynamically allocated 00135 void deallocate(); 00136 //! resizes the buffer and preserves the content 00137 void resize(size_t _size); 00138 //! returns the current buffer size 00139 size_t size() const; 00140 //! returns pointer to the real buffer, stack-allocated or head-allocated 00141 operator _Tp* (); 00142 //! returns read-only pointer to the real buffer, stack-allocated or head-allocated 00143 operator const _Tp* () const; 00144 00145 protected: 00146 //! pointer to the real buffer, can point to buf if the buffer is small enough 00147 _Tp* ptr; 00148 //! size of the real buffer 00149 size_t sz; 00150 //! pre-allocated buffer. At least 1 element to confirm C++ standard reqirements 00151 _Tp buf[(fixed_size > 0) ? fixed_size : 1]; 00152 }; 00153 00154 /** @brief Sets/resets the break-on-error mode. 00155 00156 When the break-on-error mode is set, the default error handler issues a hardware exception, which 00157 can make debugging more convenient. 00158 00159 \return the previous state 00160 */ 00161 CV_EXPORTS bool setBreakOnError(bool flag); 00162 00163 extern "C" typedef int (*ErrorCallback)( int status, const char* func_name, 00164 const char* err_msg, const char* file_name, 00165 int line, void* userdata ); 00166 00167 00168 /** @brief Sets the new error handler and the optional user data. 00169 00170 The function sets the new error handler, called from cv::error(). 00171 00172 \param errCallback the new error handler. If NULL, the default error handler is used. 00173 \param userdata the optional user data pointer, passed to the callback. 00174 \param prevUserdata the optional output parameter where the previous user data pointer is stored 00175 00176 \return the previous error handler 00177 */ 00178 CV_EXPORTS ErrorCallback redirectError( ErrorCallback errCallback, void* userdata=0, void** prevUserdata=0); 00179 00180 /** @brief Returns a text string formatted using the printf-like expression. 00181 00182 The function acts like sprintf but forms and returns an STL string. It can be used to form an error 00183 message in the Exception constructor. 00184 @param fmt printf-compatible formatting specifiers. 00185 */ 00186 CV_EXPORTS String format( const char* fmt, ... ); 00187 CV_EXPORTS String tempfile( const char* suffix = 0); 00188 CV_EXPORTS void glob(String pattern, std::vector<String>& result, bool recursive = false); 00189 00190 /** @brief OpenCV will try to set the number of threads for the next parallel region. 00191 00192 If threads == 0, OpenCV will disable threading optimizations and run all it's functions 00193 sequentially. Passing threads < 0 will reset threads number to system default. This function must 00194 be called outside of parallel region. 00195 00196 OpenCV will try to run it's functions with specified threads number, but some behaviour differs from 00197 framework: 00198 - `TBB` – User-defined parallel constructions will run with the same threads number, if 00199 another does not specified. If late on user creates own scheduler, OpenCV will be use it. 00200 - `OpenMP` – No special defined behaviour. 00201 - `Concurrency` – If threads == 1, OpenCV will disable threading optimizations and run it's 00202 functions sequentially. 00203 - `GCD` – Supports only values <= 0. 00204 - `C=` – No special defined behaviour. 00205 @param nthreads Number of threads used by OpenCV. 00206 @sa getNumThreads, getThreadNum 00207 */ 00208 CV_EXPORTS_W void setNumThreads(int nthreads); 00209 00210 /** @brief Returns the number of threads used by OpenCV for parallel regions. 00211 00212 Always returns 1 if OpenCV is built without threading support. 00213 00214 The exact meaning of return value depends on the threading framework used by OpenCV library: 00215 - `TBB` – The number of threads, that OpenCV will try to use for parallel regions. If there is 00216 any tbb::thread_scheduler_init in user code conflicting with OpenCV, then function returns 00217 default number of threads used by TBB library. 00218 - `OpenMP` – An upper bound on the number of threads that could be used to form a new team. 00219 - `Concurrency` – The number of threads, that OpenCV will try to use for parallel regions. 00220 - `GCD` – Unsupported; returns the GCD thread pool limit (512) for compatibility. 00221 - `C=` – The number of threads, that OpenCV will try to use for parallel regions, if before 00222 called setNumThreads with threads > 0, otherwise returns the number of logical CPUs, 00223 available for the process. 00224 @sa setNumThreads, getThreadNum 00225 */ 00226 CV_EXPORTS_W int getNumThreads(); 00227 00228 /** @brief Returns the index of the currently executed thread within the current parallel region. Always 00229 returns 0 if called outside of parallel region. 00230 00231 The exact meaning of return value depends on the threading framework used by OpenCV library: 00232 - `TBB` – Unsupported with current 4.1 TBB release. May be will be supported in future. 00233 - `OpenMP` – The thread number, within the current team, of the calling thread. 00234 - `Concurrency` – An ID for the virtual processor that the current context is executing on (0 00235 for master thread and unique number for others, but not necessary 1,2,3,...). 00236 - `GCD` – System calling thread's ID. Never returns 0 inside parallel region. 00237 - `C=` – The index of the current parallel task. 00238 @sa setNumThreads, getNumThreads 00239 */ 00240 CV_EXPORTS_W int getThreadNum(); 00241 00242 /** @brief Returns full configuration time cmake output. 00243 00244 Returned value is raw cmake output including version control system revision, compiler version, 00245 compiler flags, enabled modules and third party libraries, etc. Output format depends on target 00246 architecture. 00247 */ 00248 CV_EXPORTS_W const String& getBuildInformation(); 00249 00250 /** @brief Returns the number of ticks. 00251 00252 The function returns the number of ticks after the certain event (for example, when the machine was 00253 turned on). It can be used to initialize RNG or to measure a function execution time by reading the 00254 tick count before and after the function call. 00255 @sa getTickFrequency, TickMeter 00256 */ 00257 CV_EXPORTS_W int64 getTickCount(); 00258 00259 /** @brief Returns the number of ticks per second. 00260 00261 The function returns the number of ticks per second. That is, the following code computes the 00262 execution time in seconds: 00263 @code 00264 double t = (double)getTickCount(); 00265 // do something ... 00266 t = ((double)getTickCount() - t)/getTickFrequency(); 00267 @endcode 00268 @sa getTickCount, TickMeter 00269 */ 00270 CV_EXPORTS_W double getTickFrequency(); 00271 00272 /** @brief a Class to measure passing time. 00273 00274 The class computes passing time by counting the number of ticks per second. That is, the following code computes the 00275 execution time in seconds: 00276 @code 00277 TickMeter tm; 00278 tm.start(); 00279 // do something ... 00280 tm.stop(); 00281 std::cout << tm.getTimeSec(); 00282 @endcode 00283 @sa getTickCount, getTickFrequency 00284 */ 00285 00286 class CV_EXPORTS_W TickMeter 00287 { 00288 public: 00289 //! the default constructor 00290 CV_WRAP TickMeter() 00291 { 00292 reset(); 00293 } 00294 00295 /** 00296 starts counting ticks. 00297 */ 00298 CV_WRAP void start() 00299 { 00300 startTime = cv::getTickCount(); 00301 } 00302 00303 /** 00304 stops counting ticks. 00305 */ 00306 CV_WRAP void stop() 00307 { 00308 int64 time = cv::getTickCount(); 00309 if (startTime == 0) 00310 return; 00311 ++counter; 00312 sumTime += (time - startTime); 00313 startTime = 0; 00314 } 00315 00316 /** 00317 returns counted ticks. 00318 */ 00319 CV_WRAP int64 getTimeTicks() const 00320 { 00321 return sumTime; 00322 } 00323 00324 /** 00325 returns passed time in microseconds. 00326 */ 00327 CV_WRAP double getTimeMicro() const 00328 { 00329 return getTimeMilli()*1e3; 00330 } 00331 00332 /** 00333 returns passed time in milliseconds. 00334 */ 00335 CV_WRAP double getTimeMilli() const 00336 { 00337 return getTimeSec()*1e3; 00338 } 00339 00340 /** 00341 returns passed time in seconds. 00342 */ 00343 CV_WRAP double getTimeSec() const 00344 { 00345 return (double)getTimeTicks() / getTickFrequency(); 00346 } 00347 00348 /** 00349 returns internal counter value. 00350 */ 00351 CV_WRAP int64 getCounter() const 00352 { 00353 return counter; 00354 } 00355 00356 /** 00357 resets internal values. 00358 */ 00359 CV_WRAP void reset() 00360 { 00361 startTime = 0; 00362 sumTime = 0; 00363 counter = 0; 00364 } 00365 00366 private: 00367 int64 counter; 00368 int64 sumTime; 00369 int64 startTime; 00370 }; 00371 00372 /** @brief output operator 00373 @code 00374 TickMeter tm; 00375 tm.start(); 00376 // do something ... 00377 tm.stop(); 00378 std::cout << tm; 00379 @endcode 00380 */ 00381 00382 static inline 00383 std::ostream& operator << (std::ostream& out, const TickMeter& tm) 00384 { 00385 return out << tm.getTimeSec() << "sec"; 00386 } 00387 00388 /** @brief Returns the number of CPU ticks. 00389 00390 The function returns the current number of CPU ticks on some architectures (such as x86, x64, 00391 PowerPC). On other platforms the function is equivalent to getTickCount. It can also be used for 00392 very accurate time measurements, as well as for RNG initialization. Note that in case of multi-CPU 00393 systems a thread, from which getCPUTickCount is called, can be suspended and resumed at another CPU 00394 with its own counter. So, theoretically (and practically) the subsequent calls to the function do 00395 not necessary return the monotonously increasing values. Also, since a modern CPU varies the CPU 00396 frequency depending on the load, the number of CPU clocks spent in some code cannot be directly 00397 converted to time units. Therefore, getTickCount is generally a preferable solution for measuring 00398 execution time. 00399 */ 00400 CV_EXPORTS_W int64 getCPUTickCount(); 00401 00402 /** @brief Returns true if the specified feature is supported by the host hardware. 00403 00404 The function returns true if the host hardware supports the specified feature. When user calls 00405 setUseOptimized(false), the subsequent calls to checkHardwareSupport() will return false until 00406 setUseOptimized(true) is called. This way user can dynamically switch on and off the optimized code 00407 in OpenCV. 00408 @param feature The feature of interest, one of cv::CpuFeatures 00409 */ 00410 CV_EXPORTS_W bool checkHardwareSupport(int feature); 00411 00412 /** @brief Returns the number of logical CPUs available for the process. 00413 */ 00414 CV_EXPORTS_W int getNumberOfCPUs(); 00415 00416 00417 /** @brief Aligns a pointer to the specified number of bytes. 00418 00419 The function returns the aligned pointer of the same type as the input pointer: 00420 \f[\texttt{(_Tp*)(((size_t)ptr + n-1) & -n)}\f] 00421 @param ptr Aligned pointer. 00422 @param n Alignment size that must be a power of two. 00423 */ 00424 template<typename _Tp> static inline _Tp* alignPtr(_Tp* ptr, int n=(int)sizeof(_Tp)) 00425 { 00426 return (_Tp*)(((size_t)ptr + n-1) & -n); 00427 } 00428 00429 /** @brief Aligns a buffer size to the specified number of bytes. 00430 00431 The function returns the minimum number that is greater or equal to sz and is divisible by n : 00432 \f[\texttt{(sz + n-1) & -n}\f] 00433 @param sz Buffer size to align. 00434 @param n Alignment size that must be a power of two. 00435 */ 00436 static inline size_t alignSize(size_t sz, int n) 00437 { 00438 CV_DbgAssert((n & (n - 1)) == 0); // n is a power of 2 00439 return (sz + n-1) & -n; 00440 } 00441 00442 /** @brief Enables or disables the optimized code. 00443 00444 The function can be used to dynamically turn on and off optimized code (code that uses SSE2, AVX, 00445 and other instructions on the platforms that support it). It sets a global flag that is further 00446 checked by OpenCV functions. Since the flag is not checked in the inner OpenCV loops, it is only 00447 safe to call the function on the very top level in your application where you can be sure that no 00448 other OpenCV function is currently executed. 00449 00450 By default, the optimized code is enabled unless you disable it in CMake. The current status can be 00451 retrieved using useOptimized. 00452 @param onoff The boolean flag specifying whether the optimized code should be used (onoff=true) 00453 or not (onoff=false). 00454 */ 00455 CV_EXPORTS_W void setUseOptimized(bool onoff); 00456 00457 /** @brief Returns the status of optimized code usage. 00458 00459 The function returns true if the optimized code is enabled. Otherwise, it returns false. 00460 */ 00461 CV_EXPORTS_W bool useOptimized(); 00462 00463 static inline size_t getElemSize(int type) { return CV_ELEM_SIZE(type); } 00464 00465 /////////////////////////////// Parallel Primitives ////////////////////////////////// 00466 00467 /** @brief Base class for parallel data processors 00468 */ 00469 class CV_EXPORTS ParallelLoopBody 00470 { 00471 public: 00472 virtual ~ParallelLoopBody(); 00473 virtual void operator() (const Range& range) const = 0; 00474 }; 00475 00476 /** @brief Parallel data processor 00477 */ 00478 CV_EXPORTS void parallel_for_(const Range& range, const ParallelLoopBody& body, double nstripes=-1.); 00479 00480 /////////////////////////////// forEach method of cv::Mat //////////////////////////// 00481 template<typename _Tp, typename Functor> inline 00482 void Mat::forEach_impl (const Functor& operation) { 00483 if (false) { 00484 operation(*reinterpret_cast<_Tp*>(0), reinterpret_cast<int*>(0)); 00485 // If your compiler fail in this line. 00486 // Please check that your functor signature is 00487 // (_Tp&, const int*) <- multidimential 00488 // or (_Tp&, void*) <- in case of you don't need current idx. 00489 } 00490 00491 CV_Assert(this->total() / this->size[this->dims - 1] <= INT_MAX); 00492 const int LINES = static_cast<int>(this->total() / this->size[this->dims - 1]); 00493 00494 class PixelOperationWrapper :public ParallelLoopBody 00495 { 00496 public: 00497 PixelOperationWrapper(Mat_<_Tp>* const frame, const Functor& _operation) 00498 : mat(frame), op(_operation) {} 00499 virtual ~PixelOperationWrapper(){} 00500 // ! Overloaded virtual operator 00501 // convert range call to row call. 00502 virtual void operator()(const Range &range) const { 00503 const int DIMS = mat->dims; 00504 const int COLS = mat->size[DIMS - 1]; 00505 if (DIMS <= 2) { 00506 for (int row = range.start; row < range.end; ++row) { 00507 this->rowCall2(row, COLS); 00508 } 00509 } else { 00510 std::vector<int> idx(COLS); /// idx is modified in this->rowCall 00511 idx[DIMS - 2] = range.start - 1; 00512 00513 for (int line_num = range.start; line_num < range.end; ++line_num) { 00514 idx[DIMS - 2]++; 00515 for (int i = DIMS - 2; i >= 0; --i) { 00516 if (idx[i] >= mat->size[i]) { 00517 idx[i - 1] += idx[i] / mat->size[i]; 00518 idx[i] %= mat->size[i]; 00519 continue; // carry-over; 00520 } 00521 else { 00522 break; 00523 } 00524 } 00525 this->rowCall(&idx[0], COLS, DIMS); 00526 } 00527 } 00528 } 00529 private: 00530 Mat_<_Tp>* const mat; 00531 const Functor op; 00532 // ! Call operator for each elements in this row. 00533 inline void rowCall(int* const idx, const int COLS, const int DIMS) const { 00534 int &col = idx[DIMS - 1]; 00535 col = 0; 00536 _Tp* pixel = &(mat->template at<_Tp>(idx)); 00537 00538 while (col < COLS) { 00539 op(*pixel, const_cast<const int*>(idx)); 00540 pixel++; col++; 00541 } 00542 col = 0; 00543 } 00544 // ! Call operator for each elements in this row. 2d mat special version. 00545 inline void rowCall2(const int row, const int COLS) const { 00546 union Index{ 00547 int body[2]; 00548 operator const int*() const { 00549 return reinterpret_cast<const int*>(this); 00550 } 00551 int& operator[](const int i) { 00552 return body[i]; 00553 } 00554 } idx = {{row, 0}}; 00555 // Special union is needed to avoid 00556 // "error: array subscript is above array bounds [-Werror=array-bounds]" 00557 // when call the functor `op` such that access idx[3]. 00558 00559 _Tp* pixel = &(mat->template at<_Tp>(idx)); 00560 const _Tp* const pixel_end = pixel + COLS; 00561 while(pixel < pixel_end) { 00562 op(*pixel++, static_cast<const int*>(idx)); 00563 idx[1]++; 00564 } 00565 } 00566 PixelOperationWrapper& operator=(const PixelOperationWrapper &) { 00567 CV_Assert(false); 00568 // We can not remove this implementation because Visual Studio warning C4822. 00569 return *this; 00570 } 00571 }; 00572 00573 parallel_for_(cv::Range(0, LINES), PixelOperationWrapper(reinterpret_cast<Mat_<_Tp>*>(this), operation)); 00574 } 00575 00576 /////////////////////////// Synchronization Primitives /////////////////////////////// 00577 00578 class CV_EXPORTS Mutex 00579 { 00580 public: 00581 Mutex(); 00582 ~Mutex(); 00583 Mutex(const Mutex& m); 00584 Mutex& operator = (const Mutex& m); 00585 00586 void lock(); 00587 bool trylock(); 00588 void unlock(); 00589 00590 struct Impl; 00591 protected: 00592 Impl* impl; 00593 }; 00594 00595 class CV_EXPORTS AutoLock 00596 { 00597 public: 00598 AutoLock(Mutex& m) : mutex(&m) { mutex->lock(); } 00599 ~AutoLock() { mutex->unlock(); } 00600 protected: 00601 Mutex* mutex; 00602 private: 00603 AutoLock(const AutoLock&); 00604 AutoLock& operator = (const AutoLock&); 00605 }; 00606 00607 // TLS interface 00608 class CV_EXPORTS TLSDataContainer 00609 { 00610 protected: 00611 TLSDataContainer(); 00612 virtual ~TLSDataContainer(); 00613 00614 void gatherData(std::vector<void*> &data) const; 00615 #if OPENCV_ABI_COMPATIBILITY > 300 00616 void* getData() const; 00617 void release(); 00618 00619 private: 00620 #else 00621 void release(); 00622 00623 public: 00624 void* getData() const; 00625 #endif 00626 virtual void* createDataInstance() const = 0; 00627 virtual void deleteDataInstance(void* pData) const = 0; 00628 00629 int key_; 00630 }; 00631 00632 // Main TLS data class 00633 template <typename T> 00634 class TLSData : protected TLSDataContainer 00635 { 00636 public: 00637 inline TLSData() {} 00638 inline ~TLSData() { release(); } // Release key and delete associated data 00639 inline T* get() const { return (T*)getData(); } // Get data assosiated with key 00640 00641 // Get data from all threads 00642 inline void gather(std::vector<T*> &data) const 00643 { 00644 std::vector<void*> &dataVoid = reinterpret_cast<std::vector<void*>&>(data); 00645 gatherData(dataVoid); 00646 } 00647 00648 private: 00649 virtual void* createDataInstance() const {return new T;} // Wrapper to allocate data by template 00650 virtual void deleteDataInstance(void* pData) const {delete (T*)pData;} // Wrapper to release data by template 00651 00652 // Disable TLS copy operations 00653 TLSData(TLSData &) {} 00654 TLSData& operator =(const TLSData &) {return *this;} 00655 }; 00656 00657 /** @brief Designed for command line parsing 00658 00659 The sample below demonstrates how to use CommandLineParser: 00660 @code 00661 CommandLineParser parser(argc, argv, keys); 00662 parser.about("Application name v1.0.0"); 00663 00664 if (parser.has("help")) 00665 { 00666 parser.printMessage(); 00667 return 0; 00668 } 00669 00670 int N = parser.get<int>("N"); 00671 double fps = parser.get<double>("fps"); 00672 String path = parser.get<String>("path"); 00673 00674 use_time_stamp = parser.has("timestamp"); 00675 00676 String img1 = parser.get<String>(0); 00677 String img2 = parser.get<String>(1); 00678 00679 int repeat = parser.get<int>(2); 00680 00681 if (!parser.check()) 00682 { 00683 parser.printErrors(); 00684 return 0; 00685 } 00686 @endcode 00687 00688 ### Keys syntax 00689 00690 The keys parameter is a string containing several blocks, each one is enclosed in curley braces and 00691 describes one argument. Each argument contains three parts separated by the `|` symbol: 00692 00693 -# argument names is a space-separated list of option synonyms (to mark argument as positional, prefix it with the `@` symbol) 00694 -# default value will be used if the argument was not provided (can be empty) 00695 -# help message (can be empty) 00696 00697 For example: 00698 00699 @code{.cpp} 00700 const String keys = 00701 "{help h usage ? | | print this message }" 00702 "{@image1 | | image1 for compare }" 00703 "{@image2 |<none>| image2 for compare }" 00704 "{@repeat |1 | number }" 00705 "{path |. | path to file }" 00706 "{fps | -1.0 | fps for output video }" 00707 "{N count |100 | count of objects }" 00708 "{ts timestamp | | use time stamp }" 00709 ; 00710 } 00711 @endcode 00712 00713 Note that there are no default values for `help` and `timestamp` so we can check their presence using the `has()` method. 00714 Arguments with default values are considered to be always present. Use the `get()` method in these cases to check their 00715 actual value instead. 00716 00717 String keys like `get<String>("@image1")` return the empty string `""` by default - even with an empty default value. 00718 Use the special `<none>` default value to enforce that the returned string must not be empty. (like in `get<String>("@image2")`) 00719 00720 ### Usage 00721 00722 For the described keys: 00723 00724 @code{.sh} 00725 # Good call (3 positional parameters: image1, image2 and repeat; N is 200, ts is true) 00726 $ ./app -N=200 1.png 2.jpg 19 -ts 00727 00728 # Bad call 00729 $ ./app -fps=aaa 00730 ERRORS: 00731 Parameter 'fps': can not convert: [aaa] to [double] 00732 @endcode 00733 */ 00734 class CV_EXPORTS CommandLineParser 00735 { 00736 public: 00737 00738 /** @brief Constructor 00739 00740 Initializes command line parser object 00741 00742 @param argc number of command line arguments (from main()) 00743 @param argv array of command line arguments (from main()) 00744 @param keys string describing acceptable command line parameters (see class description for syntax) 00745 */ 00746 CommandLineParser(int argc, const char* const argv[], const String& keys); 00747 00748 /** @brief Copy constructor */ 00749 CommandLineParser(const CommandLineParser& parser); 00750 00751 /** @brief Assignment operator */ 00752 CommandLineParser& operator = (const CommandLineParser& parser); 00753 00754 /** @brief Destructor */ 00755 ~CommandLineParser(); 00756 00757 /** @brief Returns application path 00758 00759 This method returns the path to the executable from the command line (`argv[0]`). 00760 00761 For example, if the application has been started with such command: 00762 @code{.sh} 00763 $ ./bin/my-executable 00764 @endcode 00765 this method will return `./bin`. 00766 */ 00767 String getPathToApplication() const; 00768 00769 /** @brief Access arguments by name 00770 00771 Returns argument converted to selected type. If the argument is not known or can not be 00772 converted to selected type, the error flag is set (can be checked with @ref check). 00773 00774 For example, define: 00775 @code{.cpp} 00776 String keys = "{N count||}"; 00777 @endcode 00778 00779 Call: 00780 @code{.sh} 00781 $ ./my-app -N=20 00782 # or 00783 $ ./my-app --count=20 00784 @endcode 00785 00786 Access: 00787 @code{.cpp} 00788 int N = parser.get<int>("N"); 00789 @endcode 00790 00791 @param name name of the argument 00792 @param space_delete remove spaces from the left and right of the string 00793 @tparam T the argument will be converted to this type if possible 00794 00795 @note You can access positional arguments by their `@`-prefixed name: 00796 @code{.cpp} 00797 parser.get<String>("@image"); 00798 @endcode 00799 */ 00800 template <typename T> 00801 T get(const String& name, bool space_delete = true) const 00802 { 00803 T val = T(); 00804 getByName(name, space_delete, ParamType<T>::type, (void*)&val); 00805 return val; 00806 } 00807 00808 /** @brief Access positional arguments by index 00809 00810 Returns argument converted to selected type. Indexes are counted from zero. 00811 00812 For example, define: 00813 @code{.cpp} 00814 String keys = "{@arg1||}{@arg2||}" 00815 @endcode 00816 00817 Call: 00818 @code{.sh} 00819 ./my-app abc qwe 00820 @endcode 00821 00822 Access arguments: 00823 @code{.cpp} 00824 String val_1 = parser.get<String>(0); // returns "abc", arg1 00825 String val_2 = parser.get<String>(1); // returns "qwe", arg2 00826 @endcode 00827 00828 @param index index of the argument 00829 @param space_delete remove spaces from the left and right of the string 00830 @tparam T the argument will be converted to this type if possible 00831 */ 00832 template <typename T> 00833 T get(int index, bool space_delete = true) const 00834 { 00835 T val = T(); 00836 getByIndex(index, space_delete, ParamType<T>::type, (void*)&val); 00837 return val; 00838 } 00839 00840 /** @brief Check if field was provided in the command line 00841 00842 @param name argument name to check 00843 */ 00844 bool has(const String& name) const; 00845 00846 /** @brief Check for parsing errors 00847 00848 Returns true if error occured while accessing the parameters (bad conversion, missing arguments, 00849 etc.). Call @ref printErrors to print error messages list. 00850 */ 00851 bool check() const; 00852 00853 /** @brief Set the about message 00854 00855 The about message will be shown when @ref printMessage is called, right before arguments table. 00856 */ 00857 void about(const String& message); 00858 00859 /** @brief Print help message 00860 00861 This method will print standard help message containing the about message and arguments description. 00862 00863 @sa about 00864 */ 00865 void printMessage() const; 00866 00867 /** @brief Print list of errors occured 00868 00869 @sa check 00870 */ 00871 void printErrors() const; 00872 00873 protected: 00874 void getByName(const String& name, bool space_delete, int type, void* dst) const; 00875 void getByIndex(int index, bool space_delete, int type, void* dst) const; 00876 00877 struct Impl; 00878 Impl* impl; 00879 }; 00880 00881 //! @} core_utils 00882 00883 //! @cond IGNORED 00884 00885 /////////////////////////////// AutoBuffer implementation //////////////////////////////////////// 00886 00887 template<typename _Tp, size_t fixed_size> inline 00888 AutoBuffer<_Tp, fixed_size>::AutoBuffer() 00889 { 00890 ptr = buf; 00891 sz = fixed_size; 00892 } 00893 00894 template<typename _Tp, size_t fixed_size> inline 00895 AutoBuffer<_Tp, fixed_size>::AutoBuffer(size_t _size) 00896 { 00897 ptr = buf; 00898 sz = fixed_size; 00899 allocate(_size); 00900 } 00901 00902 template<typename _Tp, size_t fixed_size> inline 00903 AutoBuffer<_Tp, fixed_size>::AutoBuffer(const AutoBuffer<_Tp, fixed_size>& abuf ) 00904 { 00905 ptr = buf; 00906 sz = fixed_size; 00907 allocate(abuf.size()); 00908 for( size_t i = 0; i < sz; i++ ) 00909 ptr[i] = abuf.ptr[i]; 00910 } 00911 00912 template<typename _Tp, size_t fixed_size> inline AutoBuffer<_Tp, fixed_size>& 00913 AutoBuffer<_Tp, fixed_size>::operator = (const AutoBuffer<_Tp, fixed_size>& abuf) 00914 { 00915 if( this != &abuf ) 00916 { 00917 deallocate(); 00918 allocate(abuf.size()); 00919 for( size_t i = 0; i < sz; i++ ) 00920 ptr[i] = abuf.ptr[i]; 00921 } 00922 return *this; 00923 } 00924 00925 template<typename _Tp, size_t fixed_size> inline 00926 AutoBuffer<_Tp, fixed_size>::~AutoBuffer() 00927 { deallocate(); } 00928 00929 template<typename _Tp, size_t fixed_size> inline void 00930 AutoBuffer<_Tp, fixed_size>::allocate(size_t _size) 00931 { 00932 if(_size <= sz) 00933 { 00934 sz = _size; 00935 return; 00936 } 00937 deallocate(); 00938 sz = _size; 00939 if(_size > fixed_size) 00940 { 00941 ptr = new _Tp[_size]; 00942 } 00943 } 00944 00945 template<typename _Tp, size_t fixed_size> inline void 00946 AutoBuffer<_Tp, fixed_size>::deallocate() 00947 { 00948 if( ptr != buf ) 00949 { 00950 delete[] ptr; 00951 ptr = buf; 00952 sz = fixed_size; 00953 } 00954 } 00955 00956 template<typename _Tp, size_t fixed_size> inline void 00957 AutoBuffer<_Tp, fixed_size>::resize(size_t _size) 00958 { 00959 if(_size <= sz) 00960 { 00961 sz = _size; 00962 return; 00963 } 00964 size_t i, prevsize = sz, minsize = MIN(prevsize, _size); 00965 _Tp* prevptr = ptr; 00966 00967 ptr = _size > fixed_size ? new _Tp[_size] : buf; 00968 sz = _size; 00969 00970 if( ptr != prevptr ) 00971 for( i = 0; i < minsize; i++ ) 00972 ptr[i] = prevptr[i]; 00973 for( i = prevsize; i < _size; i++ ) 00974 ptr[i] = _Tp(); 00975 00976 if( prevptr != buf ) 00977 delete[] prevptr; 00978 } 00979 00980 template<typename _Tp, size_t fixed_size> inline size_t 00981 AutoBuffer<_Tp, fixed_size>::size() const 00982 { return sz; } 00983 00984 template<typename _Tp, size_t fixed_size> inline 00985 AutoBuffer<_Tp, fixed_size>::operator _Tp* () 00986 { return ptr; } 00987 00988 template<typename _Tp, size_t fixed_size> inline 00989 AutoBuffer<_Tp, fixed_size>::operator const _Tp* () const 00990 { return ptr; } 00991 00992 #ifndef OPENCV_NOSTL 00993 template<> inline std::string CommandLineParser::get<std::string>(int index, bool space_delete) const 00994 { 00995 return get<String>(index, space_delete); 00996 } 00997 template<> inline std::string CommandLineParser::get<std::string>(const String& name, bool space_delete) const 00998 { 00999 return get<String>(name, space_delete); 01000 } 01001 #endif // OPENCV_NOSTL 01002 01003 //! @endcond 01004 01005 01006 // Basic Node class for tree building 01007 template<class OBJECT> 01008 class CV_EXPORTS Node 01009 { 01010 public: 01011 Node() 01012 { 01013 m_pParent = 0; 01014 } 01015 Node(OBJECT& payload) : m_payload(payload) 01016 { 01017 m_pParent = 0; 01018 } 01019 ~Node() 01020 { 01021 removeChilds(); 01022 if (m_pParent) 01023 { 01024 int idx = m_pParent->findChild(this); 01025 if (idx >= 0) 01026 m_pParent->m_childs.erase(m_pParent->m_childs.begin() + idx); 01027 } 01028 } 01029 01030 Node<OBJECT>* findChild(OBJECT& payload) const 01031 { 01032 for(size_t i = 0; i < this->m_childs.size(); i++) 01033 { 01034 if(this->m_childs[i]->m_payload == payload) 01035 return this->m_childs[i]; 01036 } 01037 return NULL; 01038 } 01039 01040 int findChild(Node<OBJECT> *pNode) const 01041 { 01042 for (size_t i = 0; i < this->m_childs.size(); i++) 01043 { 01044 if(this->m_childs[i] == pNode) 01045 return (int)i; 01046 } 01047 return -1; 01048 } 01049 01050 void addChild(Node<OBJECT> *pNode) 01051 { 01052 if(!pNode) 01053 return; 01054 01055 CV_Assert(pNode->m_pParent == 0); 01056 pNode->m_pParent = this; 01057 this->m_childs.push_back(pNode); 01058 } 01059 01060 void removeChilds() 01061 { 01062 for(size_t i = 0; i < m_childs.size(); i++) 01063 { 01064 m_childs[i]->m_pParent = 0; // avoid excessive parent vector trimming 01065 delete m_childs[i]; 01066 } 01067 m_childs.clear(); 01068 } 01069 01070 int getDepth() 01071 { 01072 int count = 0; 01073 Node *pParent = m_pParent; 01074 while(pParent) count++, pParent = pParent->m_pParent; 01075 return count; 01076 } 01077 01078 public: 01079 OBJECT m_payload; 01080 Node<OBJECT>* m_pParent; 01081 std::vector<Node<OBJECT>*> m_childs; 01082 }; 01083 01084 // Instrumentation external interface 01085 namespace instr 01086 { 01087 01088 #if !defined OPENCV_ABI_CHECK 01089 01090 enum TYPE 01091 { 01092 TYPE_GENERAL = 0, // OpenCV API function, e.g. exported function 01093 TYPE_MARKER, // Information marker 01094 TYPE_WRAPPER, // Wrapper function for implementation 01095 TYPE_FUN, // Simple function call 01096 }; 01097 01098 enum IMPL 01099 { 01100 IMPL_PLAIN = 0, 01101 IMPL_IPP, 01102 IMPL_OPENCL, 01103 }; 01104 01105 struct NodeDataTls 01106 { 01107 NodeDataTls() 01108 { 01109 m_ticksTotal = 0; 01110 } 01111 uint64 m_ticksTotal; 01112 }; 01113 01114 class CV_EXPORTS NodeData 01115 { 01116 public: 01117 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); 01118 NodeData(NodeData &ref); 01119 ~NodeData(); 01120 NodeData& operator=(const NodeData&); 01121 01122 cv::String m_funName; 01123 cv::instr::TYPE m_instrType; 01124 cv::instr::IMPL m_implType; 01125 const char* m_fileName; 01126 int m_lineNum; 01127 void* m_retAddress; 01128 bool m_alwaysExpand; 01129 bool m_funError; 01130 01131 volatile int m_counter; 01132 volatile uint64 m_ticksTotal; 01133 TLSData<NodeDataTls> m_tls; 01134 int m_threads; 01135 01136 // No synchronization 01137 double getTotalMs() const { return ((double)m_ticksTotal / cv::getTickFrequency()) * 1000; } 01138 double getMeanMs() const { return (((double)m_ticksTotal/m_counter) / cv::getTickFrequency()) * 1000; } 01139 }; 01140 bool operator==(const NodeData& lhs, const NodeData& rhs); 01141 01142 typedef Node<NodeData> InstrNode; 01143 01144 CV_EXPORTS InstrNode* getTrace(); 01145 01146 #endif // !defined OPENCV_ABI_CHECK 01147 01148 01149 CV_EXPORTS bool useInstrumentation(); 01150 CV_EXPORTS void setUseInstrumentation(bool flag); 01151 CV_EXPORTS void resetTrace(); 01152 01153 enum FLAGS 01154 { 01155 FLAGS_NONE = 0, 01156 FLAGS_MAPPING = 0x01, 01157 FLAGS_EXPAND_SAME_NAMES = 0x02, 01158 }; 01159 01160 CV_EXPORTS void setFlags(FLAGS modeFlags); 01161 static inline void setFlags(int modeFlags) { setFlags((FLAGS)modeFlags); } 01162 CV_EXPORTS FLAGS getFlags(); 01163 } 01164 01165 } //namespace cv 01166 01167 #ifndef DISABLE_OPENCV_24_COMPATIBILITY 01168 #include "opencv2/core/core_c.h" 01169 #endif 01170 01171 #endif //OPENCV_CORE_UTILITY_H
Generated on Tue Jul 12 2022 18:20:20 by
