opencv on mbed

Dependencies:   mbed

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers utility.hpp Source File

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 #include "opencv2/core.hpp"
00053 
00054 namespace cv
00055 {
00056 
00057 #ifdef CV_COLLECT_IMPL_DATA
00058 CV_EXPORTS void setImpl(int flags); // set implementation flags and reset storage arrays
00059 CV_EXPORTS void addImpl(int flag, const char* func = 0); // add implementation and function name to storage arrays
00060 // Get stored implementation flags and fucntions names arrays
00061 // Each implementation entry correspond to function name entry, so you can find which implementation was executed in which fucntion
00062 CV_EXPORTS int getImpl(std::vector<int> &impl, std::vector<String> &funName);
00063 
00064 CV_EXPORTS bool useCollection(); // return implementation collection state
00065 CV_EXPORTS void setUseCollection(bool flag); // set implementation collection state
00066 
00067 #define CV_IMPL_PLAIN  0x01 // native CPU OpenCV implementation
00068 #define CV_IMPL_OCL    0x02 // OpenCL implementation
00069 #define CV_IMPL_IPP    0x04 // IPP implementation
00070 #define CV_IMPL_MT     0x10 // multithreaded implementation
00071 
00072 #define CV_IMPL_ADD(impl)                                                   \
00073     if(cv::useCollection())                                                 \
00074     {                                                                       \
00075         cv::addImpl(impl, CV_Func);                                         \
00076     }
00077 #else
00078 #define CV_IMPL_ADD(impl)
00079 #endif
00080 
00081 //! @addtogroup core_utils
00082 //! @{
00083 
00084 /** @brief  Automatically Allocated Buffer Class
00085 
00086  The class is used for temporary buffers in functions and methods.
00087  If a temporary buffer is usually small (a few K's of memory),
00088  but its size depends on the parameters, it makes sense to create a small
00089  fixed-size array on stack and use it if it's large enough. If the required buffer size
00090  is larger than the fixed size, another buffer of sufficient size is allocated dynamically
00091  and released after the processing. Therefore, in typical cases, when the buffer size is small,
00092  there is no overhead associated with malloc()/free().
00093  At the same time, there is no limit on the size of processed data.
00094 
00095  This is what AutoBuffer does. The template takes 2 parameters - type of the buffer elements and
00096  the number of stack-allocated elements. Here is how the class is used:
00097 
00098  \code
00099  void my_func(const cv::Mat& m)
00100  {
00101     cv::AutoBuffer<float> buf; // create automatic buffer containing 1000 floats
00102 
00103     buf.allocate(m.rows); // if m.rows <= 1000, the pre-allocated buffer is used,
00104                           // otherwise the buffer of "m.rows" floats will be allocated
00105                           // dynamically and deallocated in cv::AutoBuffer destructor
00106     ...
00107  }
00108  \endcode
00109 */
00110 template<typename _Tp, size_t fixed_size = 1024/sizeof(_Tp)+8> class AutoBuffer
00111 {
00112 public:
00113     typedef _Tp value_type;
00114 
00115     //! the default constructor
00116     AutoBuffer();
00117     //! constructor taking the real buffer size
00118     AutoBuffer(size_t _size);
00119 
00120     //! the copy constructor
00121     AutoBuffer(const AutoBuffer<_Tp, fixed_size>& buf);
00122     //! the assignment operator
00123     AutoBuffer<_Tp, fixed_size>& operator = (const AutoBuffer<_Tp, fixed_size>& buf);
00124 
00125     //! destructor. calls deallocate()
00126     ~AutoBuffer();
00127 
00128     //! allocates the new buffer of size _size. if the _size is small enough, stack-allocated buffer is used
00129     void allocate(size_t _size);
00130     //! deallocates the buffer if it was dynamically allocated
00131     void deallocate();
00132     //! resizes the buffer and preserves the content
00133     void resize(size_t _size);
00134     //! returns the current buffer size
00135     size_t size() const;
00136     //! returns pointer to the real buffer, stack-allocated or head-allocated
00137     operator _Tp* ();
00138     //! returns read-only pointer to the real buffer, stack-allocated or head-allocated
00139     operator const _Tp* () const;
00140 
00141 protected:
00142     //! pointer to the real buffer, can point to buf if the buffer is small enough
00143     _Tp* ptr;
00144     //! size of the real buffer
00145     size_t sz;
00146     //! pre-allocated buffer. At least 1 element to confirm C++ standard reqirements
00147     _Tp buf[(fixed_size > 0) ? fixed_size : 1];
00148 };
00149 
00150 /**  @brief Sets/resets the break-on-error mode.
00151 
00152 When the break-on-error mode is set, the default error handler issues a hardware exception, which
00153 can make debugging more convenient.
00154 
00155 \return the previous state
00156  */
00157 CV_EXPORTS bool setBreakOnError(bool flag);
00158 
00159 extern "C" typedef int (*ErrorCallback)( int status, const char* func_name,
00160                                        const char* err_msg, const char* file_name,
00161                                        int line, void* userdata );
00162 
00163 
00164 /** @brief Sets the new error handler and the optional user data.
00165 
00166   The function sets the new error handler, called from cv::error().
00167 
00168   \param errCallback the new error handler. If NULL, the default error handler is used.
00169   \param userdata the optional user data pointer, passed to the callback.
00170   \param prevUserdata the optional output parameter where the previous user data pointer is stored
00171 
00172   \return the previous error handler
00173 */
00174 CV_EXPORTS ErrorCallback redirectError( ErrorCallback errCallback, void* userdata=0, void** prevUserdata=0);
00175 
00176 /** @brief Returns a text string formatted using the printf-like expression.
00177 
00178 The function acts like sprintf but forms and returns an STL string. It can be used to form an error
00179 message in the Exception constructor.
00180 @param fmt printf-compatible formatting specifiers.
00181  */
00182 CV_EXPORTS String format( const char* fmt, ... );
00183 CV_EXPORTS String tempfile( const char* suffix = 0);
00184 CV_EXPORTS void glob(String pattern, std::vector<String>& result, bool recursive = false);
00185 
00186 /** @brief OpenCV will try to set the number of threads for the next parallel region.
00187 
00188 If threads == 0, OpenCV will disable threading optimizations and run all it's functions
00189 sequentially. Passing threads < 0 will reset threads number to system default. This function must
00190 be called outside of parallel region.
00191 
00192 OpenCV will try to run it's functions with specified threads number, but some behaviour differs from
00193 framework:
00194 -   `TBB` – User-defined parallel constructions will run with the same threads number, if
00195     another does not specified. If late on user creates own scheduler, OpenCV will be use it.
00196 -   `OpenMP` – No special defined behaviour.
00197 -   `Concurrency` – If threads == 1, OpenCV will disable threading optimizations and run it's
00198     functions sequentially.
00199 -   `GCD` – Supports only values <= 0.
00200 -   `C=` – No special defined behaviour.
00201 @param nthreads Number of threads used by OpenCV.
00202 @sa getNumThreads, getThreadNum
00203  */
00204 CV_EXPORTS_W void setNumThreads(int nthreads);
00205 
00206 /** @brief Returns the number of threads used by OpenCV for parallel regions.
00207 
00208 Always returns 1 if OpenCV is built without threading support.
00209 
00210 The exact meaning of return value depends on the threading framework used by OpenCV library:
00211 - `TBB` – The number of threads, that OpenCV will try to use for parallel regions. If there is
00212   any tbb::thread_scheduler_init in user code conflicting with OpenCV, then function returns
00213   default number of threads used by TBB library.
00214 - `OpenMP` – An upper bound on the number of threads that could be used to form a new team.
00215 - `Concurrency` – The number of threads, that OpenCV will try to use for parallel regions.
00216 - `GCD` – Unsupported; returns the GCD thread pool limit (512) for compatibility.
00217 - `C=` – The number of threads, that OpenCV will try to use for parallel regions, if before
00218   called setNumThreads with threads > 0, otherwise returns the number of logical CPUs,
00219   available for the process.
00220 @sa setNumThreads, getThreadNum
00221  */
00222 CV_EXPORTS_W int getNumThreads();
00223 
00224 /** @brief Returns the index of the currently executed thread within the current parallel region. Always
00225 returns 0 if called outside of parallel region.
00226 
00227 The exact meaning of return value depends on the threading framework used by OpenCV library:
00228 - `TBB` – Unsupported with current 4.1 TBB release. May be will be supported in future.
00229 - `OpenMP` – The thread number, within the current team, of the calling thread.
00230 - `Concurrency` – An ID for the virtual processor that the current context is executing on (0
00231   for master thread and unique number for others, but not necessary 1,2,3,...).
00232 - `GCD` – System calling thread's ID. Never returns 0 inside parallel region.
00233 - `C=` – The index of the current parallel task.
00234 @sa setNumThreads, getNumThreads
00235  */
00236 CV_EXPORTS_W int getThreadNum();
00237 
00238 /** @brief Returns full configuration time cmake output.
00239 
00240 Returned value is raw cmake output including version control system revision, compiler version,
00241 compiler flags, enabled modules and third party libraries, etc. Output format depends on target
00242 architecture.
00243  */
00244 CV_EXPORTS_W const String& getBuildInformation();
00245 
00246 /** @brief Returns the number of ticks.
00247 
00248 The function returns the number of ticks after the certain event (for example, when the machine was
00249 turned on). It can be used to initialize RNG or to measure a function execution time by reading the
00250 tick count before and after the function call. See also the tick frequency.
00251  */
00252 CV_EXPORTS_W int64 getTickCount();
00253 
00254 /** @brief Returns the number of ticks per second.
00255 
00256 The function returns the number of ticks per second. That is, the following code computes the
00257 execution time in seconds:
00258 @code
00259     double t = (double)getTickCount();
00260     // do something ...
00261     t = ((double)getTickCount() - t)/getTickFrequency();
00262 @endcode
00263  */
00264 CV_EXPORTS_W double getTickFrequency();
00265 
00266 /** @brief Returns the number of CPU ticks.
00267 
00268 The function returns the current number of CPU ticks on some architectures (such as x86, x64,
00269 PowerPC). On other platforms the function is equivalent to getTickCount. It can also be used for
00270 very accurate time measurements, as well as for RNG initialization. Note that in case of multi-CPU
00271 systems a thread, from which getCPUTickCount is called, can be suspended and resumed at another CPU
00272 with its own counter. So, theoretically (and practically) the subsequent calls to the function do
00273 not necessary return the monotonously increasing values. Also, since a modern CPU varies the CPU
00274 frequency depending on the load, the number of CPU clocks spent in some code cannot be directly
00275 converted to time units. Therefore, getTickCount is generally a preferable solution for measuring
00276 execution time.
00277  */
00278 CV_EXPORTS_W int64 getCPUTickCount();
00279 
00280 /** @brief Returns true if the specified feature is supported by the host hardware.
00281 
00282 The function returns true if the host hardware supports the specified feature. When user calls
00283 setUseOptimized(false), the subsequent calls to checkHardwareSupport() will return false until
00284 setUseOptimized(true) is called. This way user can dynamically switch on and off the optimized code
00285 in OpenCV.
00286 @param feature The feature of interest, one of cv::CpuFeatures
00287  */
00288 CV_EXPORTS_W bool checkHardwareSupport(int feature);
00289 
00290 /** @brief Returns the number of logical CPUs available for the process.
00291  */
00292 CV_EXPORTS_W int getNumberOfCPUs();
00293 
00294 
00295 /** @brief Aligns a pointer to the specified number of bytes.
00296 
00297 The function returns the aligned pointer of the same type as the input pointer:
00298 \f[\texttt{(_Tp*)(((size_t)ptr + n-1) & -n)}\f]
00299 @param ptr Aligned pointer.
00300 @param n Alignment size that must be a power of two.
00301  */
00302 template<typename _Tp> static inline _Tp* alignPtr(_Tp* ptr, int n=(int)sizeof(_Tp))
00303 {
00304     return (_Tp*)(((size_t)ptr + n-1) & -n);
00305 }
00306 
00307 /** @brief Aligns a buffer size to the specified number of bytes.
00308 
00309 The function returns the minimum number that is greater or equal to sz and is divisible by n :
00310 \f[\texttt{(sz + n-1) & -n}\f]
00311 @param sz Buffer size to align.
00312 @param n Alignment size that must be a power of two.
00313  */
00314 static inline size_t alignSize(size_t sz, int n)
00315 {
00316     CV_DbgAssert((n & (n - 1)) == 0); // n is a power of 2
00317     return (sz + n-1) & -n;
00318 }
00319 
00320 /** @brief Enables or disables the optimized code.
00321 
00322 The function can be used to dynamically turn on and off optimized code (code that uses SSE2, AVX,
00323 and other instructions on the platforms that support it). It sets a global flag that is further
00324 checked by OpenCV functions. Since the flag is not checked in the inner OpenCV loops, it is only
00325 safe to call the function on the very top level in your application where you can be sure that no
00326 other OpenCV function is currently executed.
00327 
00328 By default, the optimized code is enabled unless you disable it in CMake. The current status can be
00329 retrieved using useOptimized.
00330 @param onoff The boolean flag specifying whether the optimized code should be used (onoff=true)
00331 or not (onoff=false).
00332  */
00333 CV_EXPORTS_W void setUseOptimized(bool onoff);
00334 
00335 /** @brief Returns the status of optimized code usage.
00336 
00337 The function returns true if the optimized code is enabled. Otherwise, it returns false.
00338  */
00339 CV_EXPORTS_W bool useOptimized();
00340 
00341 static inline size_t getElemSize(int type) { return CV_ELEM_SIZE(type); }
00342 
00343 /////////////////////////////// Parallel Primitives //////////////////////////////////
00344 
00345 /** @brief Base class for parallel data processors
00346 */
00347 class CV_EXPORTS ParallelLoopBody
00348 {
00349 public:
00350     virtual ~ParallelLoopBody();
00351     virtual void operator() (const Range& range) const = 0;
00352 };
00353 
00354 /** @brief Parallel data processor
00355 */
00356 CV_EXPORTS void parallel_for_(const Range& range, const ParallelLoopBody& body, double nstripes=-1.);
00357 
00358 /////////////////////////////// forEach method of cv::Mat ////////////////////////////
00359 template<typename _Tp, typename Functor> inline
00360 void Mat::forEach_impl (const Functor& operation) {
00361     if (false) {
00362         operation(*reinterpret_cast<_Tp*>(0), reinterpret_cast<int*>(NULL));
00363         // If your compiler fail in this line.
00364         // Please check that your functor signature is
00365         //     (_Tp&, const int*)   <- multidimential
00366         //  or (_Tp&, void*)        <- in case of you don't need current idx.
00367     }
00368 
00369     CV_Assert(this->total() / this->size[this->dims - 1] <= INT_MAX);
00370     const int LINES = static_cast<int>(this->total() / this->size[this->dims - 1]);
00371 
00372     class PixelOperationWrapper :public ParallelLoopBody
00373     {
00374     public:
00375         PixelOperationWrapper(Mat_<_Tp>* const frame, const Functor& _operation)
00376             : mat(frame), op(_operation) {};
00377         virtual ~PixelOperationWrapper(){};
00378         // ! Overloaded virtual operator
00379         // convert range call to row call.
00380         virtual void operator()(const Range &range) const {
00381             const int DIMS = mat->dims;
00382             const int COLS = mat->size[DIMS - 1];
00383             if (DIMS <= 2) {
00384                 for (int row = range.start; row < range.end; ++row) {
00385                     this->rowCall2(row, COLS);
00386                 }
00387             } else {
00388                 std::vector<int> idx(COLS); /// idx is modified in this->rowCall
00389                 idx[DIMS - 2] = range.start - 1;
00390 
00391                 for (int line_num = range.start; line_num < range.end; ++line_num) {
00392                     idx[DIMS - 2]++;
00393                     for (int i = DIMS - 2; i >= 0; --i) {
00394                         if (idx[i] >= mat->size[i]) {
00395                             idx[i - 1] += idx[i] / mat->size[i];
00396                             idx[i] %= mat->size[i];
00397                             continue; // carry-over;
00398                         }
00399                         else {
00400                             break;
00401                         }
00402                     }
00403                     this->rowCall(&idx[0], COLS, DIMS);
00404                 }
00405             }
00406         };
00407     private:
00408         Mat_<_Tp>* const mat;
00409         const Functor op;
00410         // ! Call operator for each elements in this row.
00411         inline void rowCall(int* const idx, const int COLS, const int DIMS) const {
00412             int &col = idx[DIMS - 1];
00413             col = 0;
00414             _Tp* pixel = &(mat->template at<_Tp>(idx));
00415 
00416             while (col < COLS) {
00417                 op(*pixel, const_cast<const int*>(idx));
00418                 pixel++; col++;
00419             }
00420             col = 0;
00421         }
00422         // ! Call operator for each elements in this row. 2d mat special version.
00423         inline void rowCall2(const int row, const int COLS) const {
00424             union Index{
00425                 int body[2];
00426                 operator const int*() const {
00427                     return reinterpret_cast<const int*>(this);
00428                 }
00429                 int& operator[](const int i) {
00430                     return body[i];
00431                 }
00432             } idx = {{row, 0}};
00433             // Special union is needed to avoid
00434             // "error: array subscript is above array bounds [-Werror=array-bounds]"
00435             // when call the functor `op` such that access idx[3].
00436 
00437             _Tp* pixel = &(mat->template at<_Tp>(idx));
00438             const _Tp* const pixel_end = pixel + COLS;
00439             while(pixel < pixel_end) {
00440                 op(*pixel++, static_cast<const int*>(idx));
00441                 idx[1]++;
00442             }
00443         };
00444         PixelOperationWrapper& operator=(const PixelOperationWrapper &) {
00445             CV_Assert(false);
00446             // We can not remove this implementation because Visual Studio warning C4822.
00447             return *this;
00448         };
00449     };
00450 
00451     parallel_for_(cv::Range(0, LINES), PixelOperationWrapper(reinterpret_cast<Mat_<_Tp>*>(this), operation));
00452 }
00453 
00454 /////////////////////////// Synchronization Primitives ///////////////////////////////
00455 
00456 class CV_EXPORTS Mutex
00457 {
00458 public:
00459     Mutex();
00460     ~Mutex();
00461     Mutex(const Mutex& m);
00462     Mutex& operator = (const Mutex& m);
00463 
00464     void lock();
00465     bool trylock();
00466     void unlock();
00467 
00468     struct Impl;
00469 protected:
00470     Impl* impl;
00471 };
00472 
00473 class CV_EXPORTS AutoLock
00474 {
00475 public:
00476     AutoLock(Mutex& m) : mutex(&m) { mutex->lock(); }
00477     ~AutoLock() { mutex->unlock(); }
00478 protected:
00479     Mutex* mutex;
00480 private:
00481     AutoLock(const AutoLock&);
00482     AutoLock& operator = (const AutoLock&);
00483 };
00484 
00485 // TLS interface
00486 class CV_EXPORTS TLSDataContainer
00487 {
00488 protected:
00489     TLSDataContainer();
00490     virtual ~TLSDataContainer();
00491 
00492     void  gatherData(std::vector<void*> &data) const;
00493 #if OPENCV_ABI_COMPATIBILITY > 300
00494     void* getData() const;
00495     void  release();
00496 
00497 private:
00498 #else
00499     void  release();
00500 
00501 public:
00502     void* getData() const;
00503 #endif
00504     virtual void* createDataInstance() const = 0;
00505     virtual void  deleteDataInstance(void* pData) const = 0;
00506 
00507     int key_;
00508 };
00509 
00510 // Main TLS data class
00511 template <typename T>
00512 class TLSData : protected TLSDataContainer
00513 {
00514 public:
00515     inline TLSData()        {}
00516     inline ~TLSData()       { release();            } // Release key and delete associated data
00517     inline T* get() const   { return (T*)getData(); } // Get data assosiated with key
00518 
00519      // Get data from all threads
00520     inline void gather(std::vector<T*> &data) const
00521     {
00522         std::vector<void*> &dataVoid = reinterpret_cast<std::vector<void*>&>(data);
00523         gatherData(dataVoid);
00524     }
00525 
00526 private:
00527     virtual void* createDataInstance() const {return new T;}                // Wrapper to allocate data by template
00528     virtual void  deleteDataInstance(void* pData) const {delete (T*)pData;} // Wrapper to release data by template
00529 
00530     // Disable TLS copy operations
00531     TLSData(TLSData &) {};
00532     TLSData& operator =(const TLSData &) {return *this;};
00533 };
00534 
00535 /** @brief Designed for command line parsing
00536 
00537 The sample below demonstrates how to use CommandLineParser:
00538 @code
00539     CommandLineParser parser(argc, argv, keys);
00540     parser.about("Application name v1.0.0");
00541 
00542     if (parser.has("help"))
00543     {
00544         parser.printMessage();
00545         return 0;
00546     }
00547 
00548     int N = parser.get<int>("N");
00549     double fps = parser.get<double>("fps");
00550     String path = parser.get<String>("path");
00551 
00552     use_time_stamp = parser.has("timestamp");
00553 
00554     String img1 = parser.get<String>(0);
00555     String img2 = parser.get<String>(1);
00556 
00557     int repeat = parser.get<int>(2);
00558 
00559     if (!parser.check())
00560     {
00561         parser.printErrors();
00562         return 0;
00563     }
00564 @endcode
00565 
00566 ### Keys syntax
00567 
00568 The keys parameter is a string containing several blocks, each one is enclosed in curley braces and
00569 describes one argument. Each argument contains three parts separated by the `|` symbol:
00570 
00571 -# argument names is a space-separated list of option synonyms (to mark argument as positional, prefix it with the `@` symbol)
00572 -# default value will be used if the argument was not provided (can be empty)
00573 -# help message (can be empty)
00574 
00575 For example:
00576 
00577 @code{.cpp}
00578     const String keys =
00579         "{help h usage ? |      | print this message   }"
00580         "{@image1        |      | image1 for compare   }"
00581         "{@image2        |<none>| image2 for compare   }"
00582         "{@repeat        |1     | number               }"
00583         "{path           |.     | path to file         }"
00584         "{fps            | -1.0 | fps for output video }"
00585         "{N count        |100   | count of objects     }"
00586         "{ts timestamp   |      | use time stamp       }"
00587         ;
00588 }
00589 @endcode
00590 
00591 Note that there are no default values for `help` and `timestamp` so we can check their presence using the `has()` method.
00592 Arguments with default values are considered to be always present. Use the `get()` method in these cases to check their
00593 actual value instead.
00594 
00595 String keys like `get<String>("@image1")` return the empty string `""` by default - even with an empty default value.
00596 Use the special `<none>` default value to enforce that the returned string must not be empty. (like in `get<String>("@image2")`)
00597 
00598 ### Usage
00599 
00600 For the described keys:
00601 
00602 @code{.sh}
00603     # Good call (3 positional parameters: image1, image2 and repeat; N is 200, ts is true)
00604     $ ./app -N=200 1.png 2.jpg 19 -ts
00605 
00606     # Bad call
00607     $ ./app -fps=aaa
00608     ERRORS:
00609     Parameter 'fps': can not convert: [aaa] to [double]
00610 @endcode
00611  */
00612 class CV_EXPORTS CommandLineParser
00613 {
00614 public:
00615 
00616     /** @brief Constructor
00617 
00618     Initializes command line parser object
00619 
00620     @param argc number of command line arguments (from main())
00621     @param argv array of command line arguments (from main())
00622     @param keys string describing acceptable command line parameters (see class description for syntax)
00623     */
00624     CommandLineParser(int argc, const char* const argv[], const String& keys);
00625 
00626     /** @brief Copy constructor */
00627     CommandLineParser(const CommandLineParser& parser);
00628 
00629     /** @brief Assignment operator */
00630     CommandLineParser& operator = (const CommandLineParser& parser);
00631 
00632     /** @brief Destructor */
00633     ~CommandLineParser();
00634 
00635     /** @brief Returns application path
00636 
00637     This method returns the path to the executable from the command line (`argv[0]`).
00638 
00639     For example, if the application has been started with such command:
00640     @code{.sh}
00641     $ ./bin/my-executable
00642     @endcode
00643     this method will return `./bin`.
00644     */
00645     String getPathToApplication() const;
00646 
00647     /** @brief Access arguments by name
00648 
00649     Returns argument converted to selected type. If the argument is not known or can not be
00650     converted to selected type, the error flag is set (can be checked with @ref check).
00651 
00652     For example, define:
00653     @code{.cpp}
00654     String keys = "{N count||}";
00655     @endcode
00656 
00657     Call:
00658     @code{.sh}
00659     $ ./my-app -N=20
00660     # or
00661     $ ./my-app --count=20
00662     @endcode
00663 
00664     Access:
00665     @code{.cpp}
00666     int N = parser.get<int>("N");
00667     @endcode
00668 
00669     @param name name of the argument
00670     @param space_delete remove spaces from the left and right of the string
00671     @tparam T the argument will be converted to this type if possible
00672 
00673     @note You can access positional arguments by their `@`-prefixed name:
00674     @code{.cpp}
00675     parser.get<String>("@image");
00676     @endcode
00677      */
00678     template <typename T>
00679     T get(const String& name, bool space_delete = true) const
00680     {
00681         T val = T();
00682         getByName(name, space_delete, ParamType<T>::type, (void*)&val);
00683         return val;
00684     }
00685 
00686     /** @brief Access positional arguments by index
00687 
00688     Returns argument converted to selected type. Indexes are counted from zero.
00689 
00690     For example, define:
00691     @code{.cpp}
00692     String keys = "{@arg1||}{@arg2||}"
00693     @endcode
00694 
00695     Call:
00696     @code{.sh}
00697     ./my-app abc qwe
00698     @endcode
00699 
00700     Access arguments:
00701     @code{.cpp}
00702     String val_1 = parser.get<String>(0); // returns "abc", arg1
00703     String val_2 = parser.get<String>(1); // returns "qwe", arg2
00704     @endcode
00705 
00706     @param index index of the argument
00707     @param space_delete remove spaces from the left and right of the string
00708     @tparam T the argument will be converted to this type if possible
00709      */
00710     template <typename T>
00711     T get(int index, bool space_delete = true) const
00712     {
00713         T val = T();
00714         getByIndex(index, space_delete, ParamType<T>::type, (void*)&val);
00715         return val;
00716     }
00717 
00718     /** @brief Check if field was provided in the command line
00719 
00720     @param name argument name to check
00721     */
00722     bool has(const String& name) const;
00723 
00724     /** @brief Check for parsing errors
00725 
00726     Returns true if error occured while accessing the parameters (bad conversion, missing arguments,
00727     etc.). Call @ref printErrors to print error messages list.
00728      */
00729     bool check() const;
00730 
00731     /** @brief Set the about message
00732 
00733     The about message will be shown when @ref printMessage is called, right before arguments table.
00734      */
00735     void about(const String& message);
00736 
00737     /** @brief Print help message
00738 
00739     This method will print standard help message containing the about message and arguments description.
00740 
00741     @sa about
00742     */
00743     void printMessage() const;
00744 
00745     /** @brief Print list of errors occured
00746 
00747     @sa check
00748     */
00749     void printErrors() const;
00750 
00751 protected:
00752     void getByName(const String& name, bool space_delete, int type, void* dst) const;
00753     void getByIndex(int index, bool space_delete, int type, void* dst) const;
00754 
00755     struct Impl;
00756     Impl* impl;
00757 };
00758 
00759 //! @} core_utils
00760 
00761 //! @cond IGNORED
00762 
00763 /////////////////////////////// AutoBuffer implementation ////////////////////////////////////////
00764 
00765 template<typename _Tp, size_t fixed_size> inline
00766 AutoBuffer<_Tp, fixed_size>::AutoBuffer()
00767 {
00768     ptr = buf;
00769     sz = fixed_size;
00770 }
00771 
00772 template<typename _Tp, size_t fixed_size> inline
00773 AutoBuffer<_Tp, fixed_size>::AutoBuffer(size_t _size)
00774 {
00775     ptr = buf;
00776     sz = fixed_size;
00777     allocate(_size);
00778 }
00779 
00780 template<typename _Tp, size_t fixed_size> inline
00781 AutoBuffer<_Tp, fixed_size>::AutoBuffer(const AutoBuffer<_Tp, fixed_size>& abuf )
00782 {
00783     ptr = buf;
00784     sz = fixed_size;
00785     allocate(abuf.size());
00786     for( size_t i = 0; i < sz; i++ )
00787         ptr[i] = abuf.ptr[i];
00788 }
00789 
00790 template<typename _Tp, size_t fixed_size> inline AutoBuffer<_Tp, fixed_size>&
00791 AutoBuffer<_Tp, fixed_size>::operator = (const AutoBuffer<_Tp, fixed_size>& abuf)
00792 {
00793     if( this != &abuf )
00794     {
00795         deallocate();
00796         allocate(abuf.size());
00797         for( size_t i = 0; i < sz; i++ )
00798             ptr[i] = abuf.ptr[i];
00799     }
00800     return *this;
00801 }
00802 
00803 template<typename _Tp, size_t fixed_size> inline
00804 AutoBuffer<_Tp, fixed_size>::~AutoBuffer()
00805 { deallocate(); }
00806 
00807 template<typename _Tp, size_t fixed_size> inline void
00808 AutoBuffer<_Tp, fixed_size>::allocate(size_t _size)
00809 {
00810     if(_size <= sz)
00811     {
00812         sz = _size;
00813         return;
00814     }
00815     deallocate();
00816     if(_size > fixed_size)
00817     {
00818         ptr = new _Tp[_size];
00819         sz = _size;
00820     }
00821 }
00822 
00823 template<typename _Tp, size_t fixed_size> inline void
00824 AutoBuffer<_Tp, fixed_size>::deallocate()
00825 {
00826     if( ptr != buf )
00827     {
00828         delete[] ptr;
00829         ptr = buf;
00830         sz = fixed_size;
00831     }
00832 }
00833 
00834 template<typename _Tp, size_t fixed_size> inline void
00835 AutoBuffer<_Tp, fixed_size>::resize(size_t _size)
00836 {
00837     if(_size <= sz)
00838     {
00839         sz = _size;
00840         return;
00841     }
00842     size_t i, prevsize = sz, minsize = MIN(prevsize, _size);
00843     _Tp* prevptr = ptr;
00844 
00845     ptr = _size > fixed_size ? new _Tp[_size] : buf;
00846     sz = _size;
00847 
00848     if( ptr != prevptr )
00849         for( i = 0; i < minsize; i++ )
00850             ptr[i] = prevptr[i];
00851     for( i = prevsize; i < _size; i++ )
00852         ptr[i] = _Tp();
00853 
00854     if( prevptr != buf )
00855         delete[] prevptr;
00856 }
00857 
00858 template<typename _Tp, size_t fixed_size> inline size_t
00859 AutoBuffer<_Tp, fixed_size>::size() const
00860 { return sz; }
00861 
00862 template<typename _Tp, size_t fixed_size> inline
00863 AutoBuffer<_Tp, fixed_size>::operator _Tp* ()
00864 { return ptr; }
00865 
00866 template<typename _Tp, size_t fixed_size> inline
00867 AutoBuffer<_Tp, fixed_size>::operator const _Tp* () const
00868 { return ptr; }
00869 
00870 #ifndef OPENCV_NOSTL
00871 template<> inline std::string CommandLineParser::get<std::string>(int index, bool space_delete) const
00872 {
00873     return get<String>(index, space_delete);
00874 }
00875 template<> inline std::string CommandLineParser::get<std::string>(const String& name, bool space_delete) const
00876 {
00877     return get<String>(name, space_delete);
00878 }
00879 #endif // OPENCV_NOSTL
00880 
00881 //! @endcond
00882 
00883 } //namespace cv
00884 
00885 #ifndef DISABLE_OPENCV_24_COMPATIBILITY
00886 #include "opencv2/core/core_c.h"
00887 #endif
00888 
00889 #endif //__OPENCV_CORE_UTILITY_H__
00890