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
45 #ifndef __OPENCV_CORE_UTILITY_H__
46 #define __OPENCV_CORE_UTILITY_H__
47
48 #ifndef __cplusplus
49 # error utility.hpp header must be compiled as C++
50 #endif
51
52 #include "opencv2/core.hpp"
53
54 namespace cv
55 {
56
57 #ifdef CV_COLLECT_IMPL_DATA
58 CV_EXPORTS void setImpl(int flags); // set implementation flags and reset storage arrays
59 CV_EXPORTS void addImpl(int flag, const char* func = 0); // add implementation and function name to storage arrays
60 // Get stored implementation flags and fucntions names arrays
61 // Each implementation entry correspond to function name entry, so you can find which implementation was executed in which fucntion
62 CV_EXPORTS int getImpl(std::vector<int> &impl, std::vector<String> &funName);
63
64 CV_EXPORTS bool useCollection(); // return implementation collection state
65 CV_EXPORTS void setUseCollection(bool flag); // set implementation collection state
66
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
72 #define CV_IMPL_ADD(impl) \
73 if(cv::useCollection()) \
74 { \
75 cv::addImpl(impl, CV_Func); \
76 }
77 #else
78 #define CV_IMPL_ADD(impl)
79 #endif
80
81 //! @addtogroup core_utils
82 //! @{
83
84 /** @brief Automatically Allocated Buffer Class
85
86 The class is used for temporary buffers in functions and methods.
87 If a temporary buffer is usually small (a few K's of memory),
88 but its size depends on the parameters, it makes sense to create a small
89 fixed-size array on stack and use it if it's large enough. If the required buffer size
90 is larger than the fixed size, another buffer of sufficient size is allocated dynamically
91 and released after the processing. Therefore, in typical cases, when the buffer size is small,
92 there is no overhead associated with malloc()/free().
93 At the same time, there is no limit on the size of processed data.
94
95 This is what AutoBuffer does. The template takes 2 parameters - type of the buffer elements and
96 the number of stack-allocated elements. Here is how the class is used:
97
98 \code
99 void my_func(const cv::Mat& m)
100 {
101 cv::AutoBuffer<float> buf; // create automatic buffer containing 1000 floats
102
103 buf.allocate(m.rows); // if m.rows <= 1000, the pre-allocated buffer is used,
104 // otherwise the buffer of "m.rows" floats will be allocated
105 // dynamically and deallocated in cv::AutoBuffer destructor
106 ...
107 }
108 \endcode
109 */
110 template<typename _Tp, size_t fixed_size = 1024/sizeof(_Tp)+8> class AutoBuffer
111 {
112 public:
113 typedef _Tp value_type;
114
115 //! the default constructor
116 AutoBuffer();
117 //! constructor taking the real buffer size
118 AutoBuffer(size_t _size);
119
120 //! the copy constructor
121 AutoBuffer(const AutoBuffer<_Tp, fixed_size>& buf);
122 //! the assignment operator
123 AutoBuffer<_Tp, fixed_size>& operator = (const AutoBuffer<_Tp, fixed_size>& buf);
124
125 //! destructor. calls deallocate()
126 ~AutoBuffer();
127
128 //! allocates the new buffer of size _size. if the _size is small enough, stack-allocated buffer is used
129 void allocate(size_t _size);
130 //! deallocates the buffer if it was dynamically allocated
131 void deallocate();
132 //! resizes the buffer and preserves the content
133 void resize(size_t _size);
134 //! returns the current buffer size
135 size_t size() const;
136 //! returns pointer to the real buffer, stack-allocated or head-allocated
137 operator _Tp* ();
138 //! returns read-only pointer to the real buffer, stack-allocated or head-allocated
139 operator const _Tp* () const;
140
141 protected:
142 //! pointer to the real buffer, can point to buf if the buffer is small enough
143 _Tp* ptr;
144 //! size of the real buffer
145 size_t sz;
146 //! pre-allocated buffer. At least 1 element to confirm C++ standard reqirements
147 _Tp buf[(fixed_size > 0) ? fixed_size : 1];
148 };
149
150 /** @brief Sets/resets the break-on-error mode.
151
152 When the break-on-error mode is set, the default error handler issues a hardware exception, which
153 can make debugging more convenient.
154
155 \return the previous state
156 */
157 CV_EXPORTS bool setBreakOnError(bool flag);
158
159 extern "C" typedef int (*ErrorCallback)( int status, const char* func_name,
160 const char* err_msg, const char* file_name,
161 int line, void* userdata );
162
163
164 /** @brief Sets the new error handler and the optional user data.
165
166 The function sets the new error handler, called from cv::error().
167
168 \param errCallback the new error handler. If NULL, the default error handler is used.
169 \param userdata the optional user data pointer, passed to the callback.
170 \param prevUserdata the optional output parameter where the previous user data pointer is stored
171
172 \return the previous error handler
173 */
174 CV_EXPORTS ErrorCallback redirectError( ErrorCallback errCallback, void* userdata=0, void** prevUserdata=0);
175
176 /** @brief Returns a text string formatted using the printf-like expression.
177
178 The function acts like sprintf but forms and returns an STL string. It can be used to form an error
179 message in the Exception constructor.
180 @param fmt printf-compatible formatting specifiers.
181 */
182 CV_EXPORTS String format( const char* fmt, ... );
183 CV_EXPORTS String tempfile( const char* suffix = 0);
184 CV_EXPORTS void glob(String pattern, std::vector<String>& result, bool recursive = false);
185
186 /** @brief OpenCV will try to set the number of threads for the next parallel region.
187
188 If threads == 0, OpenCV will disable threading optimizations and run all it's functions
189 sequentially. Passing threads \< 0 will reset threads number to system default. This function must
190 be called outside of parallel region.
191
192 OpenCV will try to run it's functions with specified threads number, but some behaviour differs from
193 framework:
194 - `TBB` – User-defined parallel constructions will run with the same threads number, if
195 another does not specified. If late on user creates own scheduler, OpenCV will be use it.
196 - `OpenMP` – No special defined behaviour.
197 - `Concurrency` – If threads == 1, OpenCV will disable threading optimizations and run it's
198 functions sequentially.
199 - `GCD` – Supports only values \<= 0.
200 - `C=` – No special defined behaviour.
201 @param nthreads Number of threads used by OpenCV.
202 @sa getNumThreads, getThreadNum
203 */
204 CV_EXPORTS void setNumThreads(int nthreads);
205
206 /** @brief Returns the number of threads used by OpenCV for parallel regions.
207
208 Always returns 1 if OpenCV is built without threading support.
209
210 The exact meaning of return value depends on the threading framework used by OpenCV library:
211 - `TBB` – The number of threads, that OpenCV will try to use for parallel regions. If there is
212 any tbb::thread_scheduler_init in user code conflicting with OpenCV, then function returns
213 default number of threads used by TBB library.
214 - `OpenMP` – An upper bound on the number of threads that could be used to form a new team.
215 - `Concurrency` – The number of threads, that OpenCV will try to use for parallel regions.
216 - `GCD` – Unsupported; returns the GCD thread pool limit (512) for compatibility.
217 - `C=` – The number of threads, that OpenCV will try to use for parallel regions, if before
218 called setNumThreads with threads \> 0, otherwise returns the number of logical CPUs,
219 available for the process.
220 @sa setNumThreads, getThreadNum
221 */
222 CV_EXPORTS int getNumThreads();
223
224 /** @brief Returns the index of the currently executed thread within the current parallel region. Always
225 returns 0 if called outside of parallel region.
226
227 The exact meaning of return value depends on the threading framework used by OpenCV library:
228 - `TBB` – Unsupported with current 4.1 TBB release. May be will be supported in future.
229 - `OpenMP` – The thread number, within the current team, of the calling thread.
230 - `Concurrency` – An ID for the virtual processor that the current context is executing on (0
231 for master thread and unique number for others, but not necessary 1,2,3,...).
232 - `GCD` – System calling thread's ID. Never returns 0 inside parallel region.
233 - `C=` – The index of the current parallel task.
234 @sa setNumThreads, getNumThreads
235 */
236 CV_EXPORTS int getThreadNum();
237
238 /** @brief Returns full configuration time cmake output.
239
240 Returned value is raw cmake output including version control system revision, compiler version,
241 compiler flags, enabled modules and third party libraries, etc. Output format depends on target
242 architecture.
243 */
244 CV_EXPORTS_W const String& getBuildInformation();
245
246 /** @brief Returns the number of ticks.
247
248 The function returns the number of ticks after the certain event (for example, when the machine was
249 turned on). It can be used to initialize RNG or to measure a function execution time by reading the
250 tick count before and after the function call. See also the tick frequency.
251 */
252 CV_EXPORTS_W int64 getTickCount();
253
254 /** @brief Returns the number of ticks per second.
255
256 The function returns the number of ticks per second. That is, the following code computes the
257 execution time in seconds:
258 @code
259 double t = (double)getTickCount();
260 // do something ...
261 t = ((double)getTickCount() - t)/getTickFrequency();
262 @endcode
263 */
264 CV_EXPORTS_W double getTickFrequency();
265
266 /** @brief Returns the number of CPU ticks.
267
268 The function returns the current number of CPU ticks on some architectures (such as x86, x64,
269 PowerPC). On other platforms the function is equivalent to getTickCount. It can also be used for
270 very accurate time measurements, as well as for RNG initialization. Note that in case of multi-CPU
271 systems a thread, from which getCPUTickCount is called, can be suspended and resumed at another CPU
272 with its own counter. So, theoretically (and practically) the subsequent calls to the function do
273 not necessary return the monotonously increasing values. Also, since a modern CPU varies the CPU
274 frequency depending on the load, the number of CPU clocks spent in some code cannot be directly
275 converted to time units. Therefore, getTickCount is generally a preferable solution for measuring
276 execution time.
277 */
278 CV_EXPORTS_W int64 getCPUTickCount();
279
280 /** @brief Available CPU features.
281
282 remember to keep this list identical to the one in cvdef.h
283 */
284 enum CpuFeatures {
285 CPU_MMX = 1,
286 CPU_SSE = 2,
287 CPU_SSE2 = 3,
288 CPU_SSE3 = 4,
289 CPU_SSSE3 = 5,
290 CPU_SSE4_1 = 6,
291 CPU_SSE4_2 = 7,
292 CPU_POPCNT = 8,
293
294 CPU_AVX = 10,
295 CPU_AVX2 = 11,
296 CPU_FMA3 = 12,
297
298 CPU_AVX_512F = 13,
299 CPU_AVX_512BW = 14,
300 CPU_AVX_512CD = 15,
301 CPU_AVX_512DQ = 16,
302 CPU_AVX_512ER = 17,
303 CPU_AVX_512IFMA512 = 18,
304 CPU_AVX_512PF = 19,
305 CPU_AVX_512VBMI = 20,
306 CPU_AVX_512VL = 21,
307
308 CPU_NEON = 100
309 };
310
311 /** @brief Returns true if the specified feature is supported by the host hardware.
312
313 The function returns true if the host hardware supports the specified feature. When user calls
314 setUseOptimized(false), the subsequent calls to checkHardwareSupport() will return false until
315 setUseOptimized(true) is called. This way user can dynamically switch on and off the optimized code
316 in OpenCV.
317 @param feature The feature of interest, one of cv::CpuFeatures
318 */
319 CV_EXPORTS_W bool checkHardwareSupport(int feature);
320
321 /** @brief Returns the number of logical CPUs available for the process.
322 */
323 CV_EXPORTS_W int getNumberOfCPUs();
324
325
326 /** @brief Aligns a pointer to the specified number of bytes.
327
328 The function returns the aligned pointer of the same type as the input pointer:
329 \f[\texttt{(\_Tp*)(((size\_t)ptr + n-1) \& -n)}\f]
330 @param ptr Aligned pointer.
331 @param n Alignment size that must be a power of two.
332 */
alignPtr(_Tp * ptr,int n=(int)sizeof (_Tp))333 template<typename _Tp> static inline _Tp* alignPtr(_Tp* ptr, int n=(int)sizeof(_Tp))
334 {
335 return (_Tp*)(((size_t)ptr + n-1) & -n);
336 }
337
338 /** @brief Aligns a buffer size to the specified number of bytes.
339
340 The function returns the minimum number that is greater or equal to sz and is divisible by n :
341 \f[\texttt{(sz + n-1) \& -n}\f]
342 @param sz Buffer size to align.
343 @param n Alignment size that must be a power of two.
344 */
alignSize(size_t sz,int n)345 static inline size_t alignSize(size_t sz, int n)
346 {
347 CV_DbgAssert((n & (n - 1)) == 0); // n is a power of 2
348 return (sz + n-1) & -n;
349 }
350
351 /** @brief Enables or disables the optimized code.
352
353 The function can be used to dynamically turn on and off optimized code (code that uses SSE2, AVX,
354 and other instructions on the platforms that support it). It sets a global flag that is further
355 checked by OpenCV functions. Since the flag is not checked in the inner OpenCV loops, it is only
356 safe to call the function on the very top level in your application where you can be sure that no
357 other OpenCV function is currently executed.
358
359 By default, the optimized code is enabled unless you disable it in CMake. The current status can be
360 retrieved using useOptimized.
361 @param onoff The boolean flag specifying whether the optimized code should be used (onoff=true)
362 or not (onoff=false).
363 */
364 CV_EXPORTS_W void setUseOptimized(bool onoff);
365
366 /** @brief Returns the status of optimized code usage.
367
368 The function returns true if the optimized code is enabled. Otherwise, it returns false.
369 */
370 CV_EXPORTS_W bool useOptimized();
371
getElemSize(int type)372 static inline size_t getElemSize(int type) { return CV_ELEM_SIZE(type); }
373
374 /////////////////////////////// Parallel Primitives //////////////////////////////////
375
376 /** @brief Base class for parallel data processors
377 */
378 class CV_EXPORTS ParallelLoopBody
379 {
380 public:
381 virtual ~ParallelLoopBody();
382 virtual void operator() (const Range& range) const = 0;
383 };
384
385 /** @brief Parallel data processor
386 */
387 CV_EXPORTS void parallel_for_(const Range& range, const ParallelLoopBody& body, double nstripes=-1.);
388
389 /////////////////////////////// forEach method of cv::Mat ////////////////////////////
390 template<typename _Tp, typename Functor> inline
forEach_impl(const Functor & operation)391 void Mat::forEach_impl(const Functor& operation) {
392 if (false) {
393 operation(*reinterpret_cast<_Tp*>(0), reinterpret_cast<int*>(NULL));
394 // If your compiler fail in this line.
395 // Please check that your functor signature is
396 // (_Tp&, const int*) <- multidimential
397 // or (_Tp&, void*) <- in case of you don't need current idx.
398 }
399
400 CV_Assert(this->total() / this->size[this->dims - 1] <= INT_MAX);
401 const int LINES = static_cast<int>(this->total() / this->size[this->dims - 1]);
402
403 class PixelOperationWrapper :public ParallelLoopBody
404 {
405 public:
406 PixelOperationWrapper(Mat_<_Tp>* const frame, const Functor& _operation)
407 : mat(frame), op(_operation) {};
408 virtual ~PixelOperationWrapper(){};
409 // ! Overloaded virtual operator
410 // convert range call to row call.
411 virtual void operator()(const Range &range) const {
412 const int DIMS = mat->dims;
413 const int COLS = mat->size[DIMS - 1];
414 if (DIMS <= 2) {
415 for (int row = range.start; row < range.end; ++row) {
416 this->rowCall2(row, COLS);
417 }
418 } else {
419 std::vector<int> idx(COLS); /// idx is modified in this->rowCall
420 idx[DIMS - 2] = range.start - 1;
421
422 for (int line_num = range.start; line_num < range.end; ++line_num) {
423 idx[DIMS - 2]++;
424 for (int i = DIMS - 2; i >= 0; --i) {
425 if (idx[i] >= mat->size[i]) {
426 idx[i - 1] += idx[i] / mat->size[i];
427 idx[i] %= mat->size[i];
428 continue; // carry-over;
429 }
430 else {
431 break;
432 }
433 }
434 this->rowCall(&idx[0], COLS, DIMS);
435 }
436 }
437 };
438 private:
439 Mat_<_Tp>* const mat;
440 const Functor op;
441 // ! Call operator for each elements in this row.
442 inline void rowCall(int* const idx, const int COLS, const int DIMS) const {
443 int &col = idx[DIMS - 1];
444 col = 0;
445 _Tp* pixel = &(mat->template at<_Tp>(idx));
446
447 while (col < COLS) {
448 op(*pixel, const_cast<const int*>(idx));
449 pixel++; col++;
450 }
451 col = 0;
452 }
453 // ! Call operator for each elements in this row. 2d mat special version.
454 inline void rowCall2(const int row, const int COLS) const {
455 union Index{
456 int body[2];
457 operator const int*() const {
458 return reinterpret_cast<const int*>(this);
459 }
460 int& operator[](const int i) {
461 return body[i];
462 }
463 } idx = {{row, 0}};
464 // Special union is needed to avoid
465 // "error: array subscript is above array bounds [-Werror=array-bounds]"
466 // when call the functor `op` such that access idx[3].
467
468 _Tp* pixel = &(mat->template at<_Tp>(idx));
469 const _Tp* const pixel_end = pixel + COLS;
470 while(pixel < pixel_end) {
471 op(*pixel++, static_cast<const int*>(idx));
472 idx[1]++;
473 }
474 };
475 PixelOperationWrapper& operator=(const PixelOperationWrapper &) {
476 CV_Assert(false);
477 // We can not remove this implementation because Visual Studio warning C4822.
478 return *this;
479 };
480 };
481
482 parallel_for_(cv::Range(0, LINES), PixelOperationWrapper(reinterpret_cast<Mat_<_Tp>*>(this), operation));
483 }
484
485 /////////////////////////// Synchronization Primitives ///////////////////////////////
486
487 class CV_EXPORTS Mutex
488 {
489 public:
490 Mutex();
491 ~Mutex();
492 Mutex(const Mutex& m);
493 Mutex& operator = (const Mutex& m);
494
495 void lock();
496 bool trylock();
497 void unlock();
498
499 struct Impl;
500 protected:
501 Impl* impl;
502 };
503
504 class CV_EXPORTS AutoLock
505 {
506 public:
AutoLock(Mutex & m)507 AutoLock(Mutex& m) : mutex(&m) { mutex->lock(); }
~AutoLock()508 ~AutoLock() { mutex->unlock(); }
509 protected:
510 Mutex* mutex;
511 private:
512 AutoLock(const AutoLock&);
513 AutoLock& operator = (const AutoLock&);
514 };
515
516 class CV_EXPORTS TLSDataContainer
517 {
518 private:
519 int key_;
520 protected:
521 TLSDataContainer();
522 virtual ~TLSDataContainer();
523 public:
524 virtual void* createDataInstance() const = 0;
525 virtual void deleteDataInstance(void* data) const = 0;
526
527 void* getData() const;
528 };
529
530 template <typename T>
531 class TLSData : protected TLSDataContainer
532 {
533 public:
TLSData()534 inline TLSData() {}
~TLSData()535 inline ~TLSData() {}
get() const536 inline T* get() const { return (T*)getData(); }
537 private:
createDataInstance() const538 virtual void* createDataInstance() const { return new T; }
deleteDataInstance(void * data) const539 virtual void deleteDataInstance(void* data) const { delete (T*)data; }
540 };
541
542 /** @brief Designed for command line parsing
543
544 The sample below demonstrates how to use CommandLineParser:
545 @code
546 CommandLineParser parser(argc, argv, keys);
547 parser.about("Application name v1.0.0");
548
549 if (parser.has("help"))
550 {
551 parser.printMessage();
552 return 0;
553 }
554
555 int N = parser.get<int>("N");
556 double fps = parser.get<double>("fps");
557 String path = parser.get<String>("path");
558
559 use_time_stamp = parser.has("timestamp");
560
561 String img1 = parser.get<String>(0);
562 String img2 = parser.get<String>(1);
563
564 int repeat = parser.get<int>(2);
565
566 if (!parser.check())
567 {
568 parser.printErrors();
569 return 0;
570 }
571 @endcode
572
573 ### Keys syntax
574
575 The keys parameter is a string containing several blocks, each one is enclosed in curley braces and
576 describes one argument. Each argument contains three parts separated by the `|` symbol:
577
578 -# argument names is a space-separated list of option synonyms (to mark argument as positional, prefix it with the `@` symbol)
579 -# default value will be used if the argument was not provided (can be empty)
580 -# help message (can be empty)
581
582 For example:
583
584 @code{.cpp}
585 const String keys =
586 "{help h usage ? | | print this message }"
587 "{@image1 | | image1 for compare }"
588 "{@image2 | | image2 for compare }"
589 "{@repeat |1 | number }"
590 "{path |. | path to file }"
591 "{fps | -1.0 | fps for output video }"
592 "{N count |100 | count of objects }"
593 "{ts timestamp | | use time stamp }"
594 ;
595 }
596 @endcode
597
598 ### Usage
599
600 For the described keys:
601
602 @code{.sh}
603 # Good call (3 positional parameters: image1, image2 and repeat; N is 200, ts is true)
604 $ ./app -N=200 1.png 2.jpg 19 -ts
605
606 # Bad call
607 $ ./app -fps=aaa
608 ERRORS:
609 Exception: can not convert: [aaa] to [double]
610 @endcode
611 */
612 class CV_EXPORTS CommandLineParser
613 {
614 public:
615
616 /** @brief Constructor
617
618 Initializes command line parser object
619
620 @param argc number of command line arguments (from main())
621 @param argv array of command line arguments (from main())
622 @param keys string describing acceptable command line parameters (see class description for syntax)
623 */
624 CommandLineParser(int argc, const char* const argv[], const String& keys);
625
626 /** @brief Copy constructor */
627 CommandLineParser(const CommandLineParser& parser);
628
629 /** @brief Assignment operator */
630 CommandLineParser& operator = (const CommandLineParser& parser);
631
632 /** @brief Destructor */
633 ~CommandLineParser();
634
635 /** @brief Returns application path
636
637 This method returns the path to the executable from the command line (`argv[0]`).
638
639 For example, if the application has been started with such command:
640 @code{.sh}
641 $ ./bin/my-executable
642 @endcode
643 this method will return `./bin`.
644 */
645 String getPathToApplication() const;
646
647 /** @brief Access arguments by name
648
649 Returns argument converted to selected type. If the argument is not known or can not be
650 converted to selected type, the error flag is set (can be checked with @ref check).
651
652 For example, define:
653 @code{.cpp}
654 String keys = "{N count||}";
655 @endcode
656
657 Call:
658 @code{.sh}
659 $ ./my-app -N=20
660 # or
661 $ ./my-app --count=20
662 @endcode
663
664 Access:
665 @code{.cpp}
666 int N = parser.get<int>("N");
667 @endcode
668
669 @param name name of the argument
670 @param space_delete remove spaces from the left and right of the string
671 @tparam T the argument will be converted to this type if possible
672
673 @note You can access positional arguments by their `@`-prefixed name:
674 @code{.cpp}
675 parser.get<String>("@image");
676 @endcode
677 */
678 template <typename T>
get(const String & name,bool space_delete=true) const679 T get(const String& name, bool space_delete = true) const
680 {
681 T val = T();
682 getByName(name, space_delete, ParamType<T>::type, (void*)&val);
683 return val;
684 }
685
686 /** @brief Access positional arguments by index
687
688 Returns argument converted to selected type. Indexes are counted from zero.
689
690 For example, define:
691 @code{.cpp}
692 String keys = "{@arg1||}{@arg2||}"
693 @endcode
694
695 Call:
696 @code{.sh}
697 ./my-app abc qwe
698 @endcode
699
700 Access arguments:
701 @code{.cpp}
702 String val_1 = parser.get<String>(0); // returns "abc", arg1
703 String val_2 = parser.get<String>(1); // returns "qwe", arg2
704 @endcode
705
706 @param index index of the argument
707 @param space_delete remove spaces from the left and right of the string
708 @tparam T the argument will be converted to this type if possible
709 */
710 template <typename T>
get(int index,bool space_delete=true) const711 T get(int index, bool space_delete = true) const
712 {
713 T val = T();
714 getByIndex(index, space_delete, ParamType<T>::type, (void*)&val);
715 return val;
716 }
717
718 /** @brief Check if field was provided in the command line
719
720 @param name argument name to check
721 */
722 bool has(const String& name) const;
723
724 /** @brief Check for parsing errors
725
726 Returns true if error occured while accessing the parameters (bad conversion, missing arguments,
727 etc.). Call @ref printErrors to print error messages list.
728 */
729 bool check() const;
730
731 /** @brief Set the about message
732
733 The about message will be shown when @ref printMessage is called, right before arguments table.
734 */
735 void about(const String& message);
736
737 /** @brief Print help message
738
739 This method will print standard help message containing the about message and arguments description.
740
741 @sa about
742 */
743 void printMessage() const;
744
745 /** @brief Print list of errors occured
746
747 @sa check
748 */
749 void printErrors() const;
750
751 protected:
752 void getByName(const String& name, bool space_delete, int type, void* dst) const;
753 void getByIndex(int index, bool space_delete, int type, void* dst) const;
754
755 struct Impl;
756 Impl* impl;
757 };
758
759 //! @} core_utils
760
761 //! @cond IGNORED
762
763 /////////////////////////////// AutoBuffer implementation ////////////////////////////////////////
764
765 template<typename _Tp, size_t fixed_size> inline
AutoBuffer()766 AutoBuffer<_Tp, fixed_size>::AutoBuffer()
767 {
768 ptr = buf;
769 sz = fixed_size;
770 }
771
772 template<typename _Tp, size_t fixed_size> inline
AutoBuffer(size_t _size)773 AutoBuffer<_Tp, fixed_size>::AutoBuffer(size_t _size)
774 {
775 ptr = buf;
776 sz = fixed_size;
777 allocate(_size);
778 }
779
780 template<typename _Tp, size_t fixed_size> inline
AutoBuffer(const AutoBuffer<_Tp,fixed_size> & abuf)781 AutoBuffer<_Tp, fixed_size>::AutoBuffer(const AutoBuffer<_Tp, fixed_size>& abuf )
782 {
783 ptr = buf;
784 sz = fixed_size;
785 allocate(abuf.size());
786 for( size_t i = 0; i < sz; i++ )
787 ptr[i] = abuf.ptr[i];
788 }
789
790 template<typename _Tp, size_t fixed_size> inline AutoBuffer<_Tp, fixed_size>&
operator =(const AutoBuffer<_Tp,fixed_size> & abuf)791 AutoBuffer<_Tp, fixed_size>::operator = (const AutoBuffer<_Tp, fixed_size>& abuf)
792 {
793 if( this != &abuf )
794 {
795 deallocate();
796 allocate(abuf.size());
797 for( size_t i = 0; i < sz; i++ )
798 ptr[i] = abuf.ptr[i];
799 }
800 return *this;
801 }
802
803 template<typename _Tp, size_t fixed_size> inline
~AutoBuffer()804 AutoBuffer<_Tp, fixed_size>::~AutoBuffer()
805 { deallocate(); }
806
807 template<typename _Tp, size_t fixed_size> inline void
allocate(size_t _size)808 AutoBuffer<_Tp, fixed_size>::allocate(size_t _size)
809 {
810 if(_size <= sz)
811 {
812 sz = _size;
813 return;
814 }
815 deallocate();
816 if(_size > fixed_size)
817 {
818 ptr = new _Tp[_size];
819 sz = _size;
820 }
821 }
822
823 template<typename _Tp, size_t fixed_size> inline void
deallocate()824 AutoBuffer<_Tp, fixed_size>::deallocate()
825 {
826 if( ptr != buf )
827 {
828 delete[] ptr;
829 ptr = buf;
830 sz = fixed_size;
831 }
832 }
833
834 template<typename _Tp, size_t fixed_size> inline void
resize(size_t _size)835 AutoBuffer<_Tp, fixed_size>::resize(size_t _size)
836 {
837 if(_size <= sz)
838 {
839 sz = _size;
840 return;
841 }
842 size_t i, prevsize = sz, minsize = MIN(prevsize, _size);
843 _Tp* prevptr = ptr;
844
845 ptr = _size > fixed_size ? new _Tp[_size] : buf;
846 sz = _size;
847
848 if( ptr != prevptr )
849 for( i = 0; i < minsize; i++ )
850 ptr[i] = prevptr[i];
851 for( i = prevsize; i < _size; i++ )
852 ptr[i] = _Tp();
853
854 if( prevptr != buf )
855 delete[] prevptr;
856 }
857
858 template<typename _Tp, size_t fixed_size> inline size_t
size() const859 AutoBuffer<_Tp, fixed_size>::size() const
860 { return sz; }
861
862 template<typename _Tp, size_t fixed_size> inline
operator _Tp*()863 AutoBuffer<_Tp, fixed_size>::operator _Tp* ()
864 { return ptr; }
865
866 template<typename _Tp, size_t fixed_size> inline
operator const _Tp*() const867 AutoBuffer<_Tp, fixed_size>::operator const _Tp* () const
868 { return ptr; }
869
870 #ifndef OPENCV_NOSTL
get(int index,bool space_delete) const871 template<> inline std::string CommandLineParser::get<std::string>(int index, bool space_delete) const
872 {
873 return get<String>(index, space_delete);
874 }
get(const String & name,bool space_delete) const875 template<> inline std::string CommandLineParser::get<std::string>(const String& name, bool space_delete) const
876 {
877 return get<String>(name, space_delete);
878 }
879 #endif // OPENCV_NOSTL
880
881 //! @endcond
882
883 } //namespace cv
884
885 #ifndef DISABLE_OPENCV_24_COMPATIBILITY
886 #include "opencv2/core/core_c.h"
887 #endif
888
889 #endif //__OPENCV_CORE_UTILITY_H__
890