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 #if defined(check)
53 # warning Detected Apple 'check' macro definition, it can cause build conflicts. Please, include this header before any Apple headers.
54 #endif
55
56 #include "opencv2/core.hpp"
57 #include <ostream>
58
59 #include <functional>
60
61 #if !defined(_M_CEE)
62 #include <mutex> // std::mutex, std::lock_guard
63 #endif
64
65 namespace cv
66 {
67
68 //! @addtogroup core_utils
69 //! @{
70
71 /** @brief Automatically Allocated Buffer Class
72
73 The class is used for temporary buffers in functions and methods.
74 If a temporary buffer is usually small (a few K's of memory),
75 but its size depends on the parameters, it makes sense to create a small
76 fixed-size array on stack and use it if it's large enough. If the required buffer size
77 is larger than the fixed size, another buffer of sufficient size is allocated dynamically
78 and released after the processing. Therefore, in typical cases, when the buffer size is small,
79 there is no overhead associated with malloc()/free().
80 At the same time, there is no limit on the size of processed data.
81
82 This is what AutoBuffer does. The template takes 2 parameters - type of the buffer elements and
83 the number of stack-allocated elements. Here is how the class is used:
84
85 \code
86 void my_func(const cv::Mat& m)
87 {
88 cv::AutoBuffer<float> buf(1000); // create automatic buffer containing 1000 floats
89
90 buf.allocate(m.rows); // if m.rows <= 1000, the pre-allocated buffer is used,
91 // otherwise the buffer of "m.rows" floats will be allocated
92 // dynamically and deallocated in cv::AutoBuffer destructor
93 ...
94 }
95 \endcode
96 */
97 #ifdef OPENCV_ENABLE_MEMORY_SANITIZER
98 template<typename _Tp, size_t fixed_size = 0> class AutoBuffer
99 #else
100 template<typename _Tp, size_t fixed_size = 1024/sizeof(_Tp)+8> class AutoBuffer
101 #endif
102 {
103 public:
104 typedef _Tp value_type;
105
106 //! the default constructor
107 AutoBuffer();
108 //! constructor taking the real buffer size
109 explicit AutoBuffer(size_t _size);
110
111 //! the copy constructor
112 AutoBuffer(const AutoBuffer<_Tp, fixed_size>& buf);
113 //! the assignment operator
114 AutoBuffer<_Tp, fixed_size>& operator = (const AutoBuffer<_Tp, fixed_size>& buf);
115
116 //! destructor. calls deallocate()
117 ~AutoBuffer();
118
119 //! allocates the new buffer of size _size. if the _size is small enough, stack-allocated buffer is used
120 void allocate(size_t _size);
121 //! deallocates the buffer if it was dynamically allocated
122 void deallocate();
123 //! resizes the buffer and preserves the content
124 void resize(size_t _size);
125 //! returns the current buffer size
126 size_t size() const;
127 //! returns pointer to the real buffer, stack-allocated or heap-allocated
data()128 inline _Tp* data() { return ptr; }
129 //! returns read-only pointer to the real buffer, stack-allocated or heap-allocated
data() const130 inline const _Tp* data() const { return ptr; }
131
132 #if !defined(OPENCV_DISABLE_DEPRECATED_COMPATIBILITY) // use to .data() calls instead
133 //! returns pointer to the real buffer, stack-allocated or heap-allocated
operator _Tp*()134 operator _Tp* () { return ptr; }
135 //! returns read-only pointer to the real buffer, stack-allocated or heap-allocated
operator const _Tp*() const136 operator const _Tp* () const { return ptr; }
137 #else
138 //! returns a reference to the element at specified location. No bounds checking is performed in Release builds.
operator [](size_t i)139 inline _Tp& operator[] (size_t i) { CV_DbgCheckLT(i, sz, "out of range"); return ptr[i]; }
140 //! returns a reference to the element at specified location. No bounds checking is performed in Release builds.
operator [](size_t i) const141 inline const _Tp& operator[] (size_t i) const { CV_DbgCheckLT(i, sz, "out of range"); return ptr[i]; }
142 #endif
143
144 protected:
145 //! pointer to the real buffer, can point to buf if the buffer is small enough
146 _Tp* ptr;
147 //! size of the real buffer
148 size_t sz;
149 //! pre-allocated buffer. At least 1 element to confirm C++ standard requirements
150 _Tp buf[(fixed_size > 0) ? fixed_size : 1];
151 };
152
153 /** @brief Sets/resets the break-on-error mode.
154
155 When the break-on-error mode is set, the default error handler issues a hardware exception, which
156 can make debugging more convenient.
157
158 \return the previous state
159 */
160 CV_EXPORTS bool setBreakOnError(bool flag);
161
162 extern "C" typedef int (*ErrorCallback)( int status, const char* func_name,
163 const char* err_msg, const char* file_name,
164 int line, void* userdata );
165
166
167 /** @brief Sets the new error handler and the optional user data.
168
169 The function sets the new error handler, called from cv::error().
170
171 \param errCallback the new error handler. If NULL, the default error handler is used.
172 \param userdata the optional user data pointer, passed to the callback.
173 \param prevUserdata the optional output parameter where the previous user data pointer is stored
174
175 \return the previous error handler
176 */
177 CV_EXPORTS ErrorCallback redirectError( ErrorCallback errCallback, void* userdata=0, void** prevUserdata=0);
178
179 CV_EXPORTS String tempfile( const char* suffix = 0);
180 CV_EXPORTS void glob(String pattern, std::vector<String>& result, bool recursive = false);
181
182 /** @brief OpenCV will try to set the number of threads for the next parallel region.
183
184 If threads == 0, OpenCV will disable threading optimizations and run all it's functions
185 sequentially. Passing threads \< 0 will reset threads number to system default. This function must
186 be called outside of parallel region.
187
188 OpenCV will try to run its functions with specified threads number, but some behaviour differs from
189 framework:
190 - `TBB` - User-defined parallel constructions will run with the same threads number, if
191 another is not specified. If later on user creates his own scheduler, OpenCV will use it.
192 - `OpenMP` - No special defined behaviour.
193 - `Concurrency` - If threads == 1, OpenCV will disable threading optimizations and run its
194 functions sequentially.
195 - `GCD` - Supports only values \<= 0.
196 - `C=` - No special defined behaviour.
197 @param nthreads Number of threads used by OpenCV.
198 @sa getNumThreads, getThreadNum
199 */
200 CV_EXPORTS_W void setNumThreads(int nthreads);
201
202 /** @brief Returns the number of threads used by OpenCV for parallel regions.
203
204 Always returns 1 if OpenCV is built without threading support.
205
206 The exact meaning of return value depends on the threading framework used by OpenCV library:
207 - `TBB` - The number of threads, that OpenCV will try to use for parallel regions. If there is
208 any tbb::thread_scheduler_init in user code conflicting with OpenCV, then function returns
209 default number of threads used by TBB library.
210 - `OpenMP` - An upper bound on the number of threads that could be used to form a new team.
211 - `Concurrency` - The number of threads, that OpenCV will try to use for parallel regions.
212 - `GCD` - Unsupported; returns the GCD thread pool limit (512) for compatibility.
213 - `C=` - The number of threads, that OpenCV will try to use for parallel regions, if before
214 called setNumThreads with threads \> 0, otherwise returns the number of logical CPUs,
215 available for the process.
216 @sa setNumThreads, getThreadNum
217 */
218 CV_EXPORTS_W int getNumThreads();
219
220 /** @brief Returns the index of the currently executed thread within the current parallel region. Always
221 returns 0 if called outside of parallel region.
222
223 @deprecated Current implementation doesn't corresponding to this documentation.
224
225 The exact meaning of the return value depends on the threading framework used by OpenCV library:
226 - `TBB` - Unsupported with current 4.1 TBB release. Maybe will be supported in future.
227 - `OpenMP` - The thread number, within the current team, of the calling thread.
228 - `Concurrency` - An ID for the virtual processor that the current context is executing on (0
229 for master thread and unique number for others, but not necessary 1,2,3,...).
230 - `GCD` - System calling thread's ID. Never returns 0 inside parallel region.
231 - `C=` - The index of the current parallel task.
232 @sa setNumThreads, getNumThreads
233 */
234 CV_EXPORTS_W int getThreadNum();
235
236 /** @brief Returns full configuration time cmake output.
237
238 Returned value is raw cmake output including version control system revision, compiler version,
239 compiler flags, enabled modules and third party libraries, etc. Output format depends on target
240 architecture.
241 */
242 CV_EXPORTS_W const String& getBuildInformation();
243
244 /** @brief Returns library version string
245
246 For example "3.4.1-dev".
247
248 @sa getMajorVersion, getMinorVersion, getRevisionVersion
249 */
250 CV_EXPORTS_W String getVersionString();
251
252 /** @brief Returns major library version */
253 CV_EXPORTS_W int getVersionMajor();
254
255 /** @brief Returns minor library version */
256 CV_EXPORTS_W int getVersionMinor();
257
258 /** @brief Returns revision field of the library version */
259 CV_EXPORTS_W int getVersionRevision();
260
261 /** @brief Returns the number of ticks.
262
263 The function returns the number of ticks after the certain event (for example, when the machine was
264 turned on). It can be used to initialize RNG or to measure a function execution time by reading the
265 tick count before and after the function call.
266 @sa getTickFrequency, TickMeter
267 */
268 CV_EXPORTS_W int64 getTickCount();
269
270 /** @brief Returns the number of ticks per second.
271
272 The function returns the number of ticks per second. That is, the following code computes the
273 execution time in seconds:
274 @code
275 double t = (double)getTickCount();
276 // do something ...
277 t = ((double)getTickCount() - t)/getTickFrequency();
278 @endcode
279 @sa getTickCount, TickMeter
280 */
281 CV_EXPORTS_W double getTickFrequency();
282
283 /** @brief a Class to measure passing time.
284
285 The class computes passing time by counting the number of ticks per second. That is, the following code computes the
286 execution time in seconds:
287 @snippet snippets/core_various.cpp TickMeter_total
288
289 It is also possible to compute the average time over multiple runs:
290 @snippet snippets/core_various.cpp TickMeter_average
291
292 @sa getTickCount, getTickFrequency
293 */
294 class CV_EXPORTS_W TickMeter
295 {
296 public:
297 //! the default constructor
TickMeter()298 CV_WRAP TickMeter()
299 {
300 reset();
301 }
302
303 //! starts counting ticks.
start()304 CV_WRAP void start()
305 {
306 startTime = cv::getTickCount();
307 }
308
309 //! stops counting ticks.
stop()310 CV_WRAP void stop()
311 {
312 int64 time = cv::getTickCount();
313 if (startTime == 0)
314 return;
315 ++counter;
316 sumTime += (time - startTime);
317 startTime = 0;
318 }
319
320 //! returns counted ticks.
getTimeTicks() const321 CV_WRAP int64 getTimeTicks() const
322 {
323 return sumTime;
324 }
325
326 //! returns passed time in microseconds.
getTimeMicro() const327 CV_WRAP double getTimeMicro() const
328 {
329 return getTimeMilli()*1e3;
330 }
331
332 //! returns passed time in milliseconds.
getTimeMilli() const333 CV_WRAP double getTimeMilli() const
334 {
335 return getTimeSec()*1e3;
336 }
337
338 //! returns passed time in seconds.
getTimeSec() const339 CV_WRAP double getTimeSec() const
340 {
341 return (double)getTimeTicks() / getTickFrequency();
342 }
343
344 //! returns internal counter value.
getCounter() const345 CV_WRAP int64 getCounter() const
346 {
347 return counter;
348 }
349
350 //! returns average FPS (frames per second) value.
getFPS() const351 CV_WRAP double getFPS() const
352 {
353 const double sec = getTimeSec();
354 if (sec < DBL_EPSILON)
355 return 0.;
356 return counter / sec;
357 }
358
359 //! returns average time in seconds
getAvgTimeSec() const360 CV_WRAP double getAvgTimeSec() const
361 {
362 if (counter <= 0)
363 return 0.;
364 return getTimeSec() / counter;
365 }
366
367 //! returns average time in milliseconds
getAvgTimeMilli() const368 CV_WRAP double getAvgTimeMilli() const
369 {
370 return getAvgTimeSec() * 1e3;
371 }
372
373 //! resets internal values.
reset()374 CV_WRAP void reset()
375 {
376 startTime = 0;
377 sumTime = 0;
378 counter = 0;
379 }
380
381 private:
382 int64 counter;
383 int64 sumTime;
384 int64 startTime;
385 };
386
387 /** @brief output operator
388 @code
389 TickMeter tm;
390 tm.start();
391 // do something ...
392 tm.stop();
393 std::cout << tm;
394 @endcode
395 */
396
397 static inline
operator <<(std::ostream & out,const TickMeter & tm)398 std::ostream& operator << (std::ostream& out, const TickMeter& tm)
399 {
400 return out << tm.getTimeSec() << "sec";
401 }
402
403 /** @brief Returns the number of CPU ticks.
404
405 The function returns the current number of CPU ticks on some architectures (such as x86, x64,
406 PowerPC). On other platforms the function is equivalent to getTickCount. It can also be used for
407 very accurate time measurements, as well as for RNG initialization. Note that in case of multi-CPU
408 systems a thread, from which getCPUTickCount is called, can be suspended and resumed at another CPU
409 with its own counter. So, theoretically (and practically) the subsequent calls to the function do
410 not necessary return the monotonously increasing values. Also, since a modern CPU varies the CPU
411 frequency depending on the load, the number of CPU clocks spent in some code cannot be directly
412 converted to time units. Therefore, getTickCount is generally a preferable solution for measuring
413 execution time.
414 */
415 CV_EXPORTS_W int64 getCPUTickCount();
416
417 /** @brief Returns true if the specified feature is supported by the host hardware.
418
419 The function returns true if the host hardware supports the specified feature. When user calls
420 setUseOptimized(false), the subsequent calls to checkHardwareSupport() will return false until
421 setUseOptimized(true) is called. This way user can dynamically switch on and off the optimized code
422 in OpenCV.
423 @param feature The feature of interest, one of cv::CpuFeatures
424 */
425 CV_EXPORTS_W bool checkHardwareSupport(int feature);
426
427 /** @brief Returns feature name by ID
428
429 Returns empty string if feature is not defined
430 */
431 CV_EXPORTS_W String getHardwareFeatureName(int feature);
432
433 /** @brief Returns list of CPU features enabled during compilation.
434
435 Returned value is a string containing space separated list of CPU features with following markers:
436
437 - no markers - baseline features
438 - prefix `*` - features enabled in dispatcher
439 - suffix `?` - features enabled but not available in HW
440
441 Example: `SSE SSE2 SSE3 *SSE4.1 *SSE4.2 *FP16 *AVX *AVX2 *AVX512-SKX?`
442 */
443 CV_EXPORTS_W std::string getCPUFeaturesLine();
444
445 /** @brief Returns the number of logical CPUs available for the process.
446 */
447 CV_EXPORTS_W int getNumberOfCPUs();
448
449
450 /** @brief Aligns a pointer to the specified number of bytes.
451
452 The function returns the aligned pointer of the same type as the input pointer:
453 \f[\texttt{(_Tp*)(((size_t)ptr + n-1) & -n)}\f]
454 @param ptr Aligned pointer.
455 @param n Alignment size that must be a power of two.
456 */
alignPtr(_Tp * ptr,int n=(int)sizeof (_Tp))457 template<typename _Tp> static inline _Tp* alignPtr(_Tp* ptr, int n=(int)sizeof(_Tp))
458 {
459 CV_DbgAssert((n & (n - 1)) == 0); // n is a power of 2
460 return (_Tp*)(((size_t)ptr + n-1) & -n);
461 }
462
463 /** @brief Aligns a buffer size to the specified number of bytes.
464
465 The function returns the minimum number that is greater than or equal to sz and is divisible by n :
466 \f[\texttt{(sz + n-1) & -n}\f]
467 @param sz Buffer size to align.
468 @param n Alignment size that must be a power of two.
469 */
alignSize(size_t sz,int n)470 static inline size_t alignSize(size_t sz, int n)
471 {
472 CV_DbgAssert((n & (n - 1)) == 0); // n is a power of 2
473 return (sz + n-1) & -n;
474 }
475
476 /** @brief Integer division with result round up.
477
478 Use this function instead of `ceil((float)a / b)` expressions.
479
480 @sa alignSize
481 */
divUp(int a,unsigned int b)482 static inline int divUp(int a, unsigned int b)
483 {
484 CV_DbgAssert(a >= 0);
485 return (a + b - 1) / b;
486 }
487 /** @overload */
divUp(size_t a,unsigned int b)488 static inline size_t divUp(size_t a, unsigned int b)
489 {
490 return (a + b - 1) / b;
491 }
492
493 /** @brief Round first value up to the nearest multiple of second value.
494
495 Use this function instead of `ceil((float)a / b) * b` expressions.
496
497 @sa divUp
498 */
roundUp(int a,unsigned int b)499 static inline int roundUp(int a, unsigned int b)
500 {
501 CV_DbgAssert(a >= 0);
502 return a + b - 1 - (a + b -1) % b;
503 }
504 /** @overload */
roundUp(size_t a,unsigned int b)505 static inline size_t roundUp(size_t a, unsigned int b)
506 {
507 return a + b - 1 - (a + b - 1) % b;
508 }
509
510 /** @brief Alignment check of passed values
511
512 Usage: `isAligned<sizeof(int)>(...)`
513
514 @note Alignment(N) must be a power of 2 (2**k, 2^k)
515 */
516 template<int N, typename T> static inline
isAligned(const T & data)517 bool isAligned(const T& data)
518 {
519 CV_StaticAssert((N & (N - 1)) == 0, ""); // power of 2
520 return (((size_t)data) & (N - 1)) == 0;
521 }
522 /** @overload */
523 template<int N> static inline
isAligned(const void * p1)524 bool isAligned(const void* p1)
525 {
526 return isAligned<N>((size_t)p1);
527 }
528 /** @overload */
529 template<int N> static inline
isAligned(const void * p1,const void * p2)530 bool isAligned(const void* p1, const void* p2)
531 {
532 return isAligned<N>(((size_t)p1)|((size_t)p2));
533 }
534 /** @overload */
535 template<int N> static inline
isAligned(const void * p1,const void * p2,const void * p3)536 bool isAligned(const void* p1, const void* p2, const void* p3)
537 {
538 return isAligned<N>(((size_t)p1)|((size_t)p2)|((size_t)p3));
539 }
540 /** @overload */
541 template<int N> static inline
isAligned(const void * p1,const void * p2,const void * p3,const void * p4)542 bool isAligned(const void* p1, const void* p2, const void* p3, const void* p4)
543 {
544 return isAligned<N>(((size_t)p1)|((size_t)p2)|((size_t)p3)|((size_t)p4));
545 }
546
547 /** @brief Enables or disables the optimized code.
548
549 The function can be used to dynamically turn on and off optimized dispatched code (code that uses SSE4.2, AVX/AVX2,
550 and other instructions on the platforms that support it). It sets a global flag that is further
551 checked by OpenCV functions. Since the flag is not checked in the inner OpenCV loops, it is only
552 safe to call the function on the very top level in your application where you can be sure that no
553 other OpenCV function is currently executed.
554
555 By default, the optimized code is enabled unless you disable it in CMake. The current status can be
556 retrieved using useOptimized.
557 @param onoff The boolean flag specifying whether the optimized code should be used (onoff=true)
558 or not (onoff=false).
559 */
560 CV_EXPORTS_W void setUseOptimized(bool onoff);
561
562 /** @brief Returns the status of optimized code usage.
563
564 The function returns true if the optimized code is enabled. Otherwise, it returns false.
565 */
566 CV_EXPORTS_W bool useOptimized();
567
getElemSize(int type)568 static inline size_t getElemSize(int type) { return (size_t)CV_ELEM_SIZE(type); }
569
570 /////////////////////////////// Parallel Primitives //////////////////////////////////
571
572 /** @brief Base class for parallel data processors
573
574 @ingroup core_parallel
575 */
576 class CV_EXPORTS ParallelLoopBody
577 {
578 public:
579 virtual ~ParallelLoopBody();
580 virtual void operator() (const Range& range) const = 0;
581 };
582
583 /** @brief Parallel data processor
584
585 @ingroup core_parallel
586 */
587 CV_EXPORTS void parallel_for_(const Range& range, const ParallelLoopBody& body, double nstripes=-1.);
588
589 //! @ingroup core_parallel
590 class ParallelLoopBodyLambdaWrapper : public ParallelLoopBody
591 {
592 private:
593 std::function<void(const Range&)> m_functor;
594 public:
595 inline
ParallelLoopBodyLambdaWrapper(std::function<void (const Range &)> functor)596 ParallelLoopBodyLambdaWrapper(std::function<void(const Range&)> functor)
597 : m_functor(functor)
598 {
599 // nothing
600 }
601
operator ()(const cv::Range & range) const602 virtual void operator() (const cv::Range& range) const CV_OVERRIDE
603 {
604 m_functor(range);
605 }
606 };
607
608 //! @ingroup core_parallel
609 static inline
parallel_for_(const Range & range,std::function<void (const Range &)> functor,double nstripes=-1.)610 void parallel_for_(const Range& range, std::function<void(const Range&)> functor, double nstripes=-1.)
611 {
612 parallel_for_(range, ParallelLoopBodyLambdaWrapper(functor), nstripes);
613 }
614
615
616 /////////////////////////////// forEach method of cv::Mat ////////////////////////////
617 template<typename _Tp, typename Functor> inline
forEach_impl(const Functor & operation)618 void Mat::forEach_impl(const Functor& operation) {
619 if (false) {
620 operation(*reinterpret_cast<_Tp*>(0), reinterpret_cast<int*>(0));
621 // If your compiler fails in this line.
622 // Please check that your functor signature is
623 // (_Tp&, const int*) <- multi-dimensional
624 // or (_Tp&, void*) <- in case you don't need current idx.
625 }
626
627 CV_Assert(!empty());
628 CV_Assert(this->total() / this->size[this->dims - 1] <= INT_MAX);
629 const int LINES = static_cast<int>(this->total() / this->size[this->dims - 1]);
630
631 class PixelOperationWrapper :public ParallelLoopBody
632 {
633 public:
634 PixelOperationWrapper(Mat_<_Tp>* const frame, const Functor& _operation)
635 : mat(frame), op(_operation) {}
636 virtual ~PixelOperationWrapper(){}
637 // ! Overloaded virtual operator
638 // convert range call to row call.
639 virtual void operator()(const Range &range) const CV_OVERRIDE
640 {
641 const int DIMS = mat->dims;
642 const int COLS = mat->size[DIMS - 1];
643 if (DIMS <= 2) {
644 for (int row = range.start; row < range.end; ++row) {
645 this->rowCall2(row, COLS);
646 }
647 } else {
648 std::vector<int> idx(DIMS); /// idx is modified in this->rowCall
649 idx[DIMS - 2] = range.start - 1;
650
651 for (int line_num = range.start; line_num < range.end; ++line_num) {
652 idx[DIMS - 2]++;
653 for (int i = DIMS - 2; i >= 0; --i) {
654 if (idx[i] >= mat->size[i]) {
655 idx[i - 1] += idx[i] / mat->size[i];
656 idx[i] %= mat->size[i];
657 continue; // carry-over;
658 }
659 else {
660 break;
661 }
662 }
663 this->rowCall(&idx[0], COLS, DIMS);
664 }
665 }
666 }
667 private:
668 Mat_<_Tp>* const mat;
669 const Functor op;
670 // ! Call operator for each elements in this row.
671 inline void rowCall(int* const idx, const int COLS, const int DIMS) const {
672 int &col = idx[DIMS - 1];
673 col = 0;
674 _Tp* pixel = &(mat->template at<_Tp>(idx));
675
676 while (col < COLS) {
677 op(*pixel, const_cast<const int*>(idx));
678 pixel++; col++;
679 }
680 col = 0;
681 }
682 // ! Call operator for each elements in this row. 2d mat special version.
683 inline void rowCall2(const int row, const int COLS) const {
684 union Index{
685 int body[2];
686 operator const int*() const {
687 return reinterpret_cast<const int*>(this);
688 }
689 int& operator[](const int i) {
690 return body[i];
691 }
692 } idx = {{row, 0}};
693 // Special union is needed to avoid
694 // "error: array subscript is above array bounds [-Werror=array-bounds]"
695 // when call the functor `op` such that access idx[3].
696
697 _Tp* pixel = &(mat->template at<_Tp>(idx));
698 const _Tp* const pixel_end = pixel + COLS;
699 while(pixel < pixel_end) {
700 op(*pixel++, static_cast<const int*>(idx));
701 idx[1]++;
702 }
703 }
704 PixelOperationWrapper& operator=(const PixelOperationWrapper &) {
705 CV_Assert(false);
706 // We can not remove this implementation because Visual Studio warning C4822.
707 return *this;
708 }
709 };
710
711 parallel_for_(cv::Range(0, LINES), PixelOperationWrapper(reinterpret_cast<Mat_<_Tp>*>(this), operation));
712 }
713
714 /////////////////////////// Synchronization Primitives ///////////////////////////////
715
716 #if !defined(_M_CEE)
717 typedef std::recursive_mutex Mutex;
718 typedef std::lock_guard<cv::Mutex> AutoLock;
719 #endif
720
721
722 /** @brief Designed for command line parsing
723
724 The sample below demonstrates how to use CommandLineParser:
725 @code
726 CommandLineParser parser(argc, argv, keys);
727 parser.about("Application name v1.0.0");
728
729 if (parser.has("help"))
730 {
731 parser.printMessage();
732 return 0;
733 }
734
735 int N = parser.get<int>("N");
736 double fps = parser.get<double>("fps");
737 String path = parser.get<String>("path");
738
739 use_time_stamp = parser.has("timestamp");
740
741 String img1 = parser.get<String>(0);
742 String img2 = parser.get<String>(1);
743
744 int repeat = parser.get<int>(2);
745
746 if (!parser.check())
747 {
748 parser.printErrors();
749 return 0;
750 }
751 @endcode
752
753 ### Keys syntax
754
755 The keys parameter is a string containing several blocks, each one is enclosed in curly braces and
756 describes one argument. Each argument contains three parts separated by the `|` symbol:
757
758 -# argument names is a space-separated list of option synonyms (to mark argument as positional, prefix it with the `@` symbol)
759 -# default value will be used if the argument was not provided (can be empty)
760 -# help message (can be empty)
761
762 For example:
763
764 @code{.cpp}
765 const String keys =
766 "{help h usage ? | | print this message }"
767 "{@image1 | | image1 for compare }"
768 "{@image2 |<none>| image2 for compare }"
769 "{@repeat |1 | number }"
770 "{path |. | path to file }"
771 "{fps | -1.0 | fps for output video }"
772 "{N count |100 | count of objects }"
773 "{ts timestamp | | use time stamp }"
774 ;
775 }
776 @endcode
777
778 Note that there are no default values for `help` and `timestamp` so we can check their presence using the `has()` method.
779 Arguments with default values are considered to be always present. Use the `get()` method in these cases to check their
780 actual value instead.
781
782 String keys like `get<String>("@image1")` return the empty string `""` by default - even with an empty default value.
783 Use the special `<none>` default value to enforce that the returned string must not be empty. (like in `get<String>("@image2")`)
784
785 ### Usage
786
787 For the described keys:
788
789 @code{.sh}
790 # Good call (3 positional parameters: image1, image2 and repeat; N is 200, ts is true)
791 $ ./app -N=200 1.png 2.jpg 19 -ts
792
793 # Bad call
794 $ ./app -fps=aaa
795 ERRORS:
796 Parameter 'fps': can not convert: [aaa] to [double]
797 @endcode
798 */
799 class CV_EXPORTS CommandLineParser
800 {
801 public:
802
803 /** @brief Constructor
804
805 Initializes command line parser object
806
807 @param argc number of command line arguments (from main())
808 @param argv array of command line arguments (from main())
809 @param keys string describing acceptable command line parameters (see class description for syntax)
810 */
811 CommandLineParser(int argc, const char* const argv[], const String& keys);
812
813 /** @brief Copy constructor */
814 CommandLineParser(const CommandLineParser& parser);
815
816 /** @brief Assignment operator */
817 CommandLineParser& operator = (const CommandLineParser& parser);
818
819 /** @brief Destructor */
820 ~CommandLineParser();
821
822 /** @brief Returns application path
823
824 This method returns the path to the executable from the command line (`argv[0]`).
825
826 For example, if the application has been started with such a command:
827 @code{.sh}
828 $ ./bin/my-executable
829 @endcode
830 this method will return `./bin`.
831 */
832 String getPathToApplication() const;
833
834 /** @brief Access arguments by name
835
836 Returns argument converted to selected type. If the argument is not known or can not be
837 converted to selected type, the error flag is set (can be checked with @ref check).
838
839 For example, define:
840 @code{.cpp}
841 String keys = "{N count||}";
842 @endcode
843
844 Call:
845 @code{.sh}
846 $ ./my-app -N=20
847 # or
848 $ ./my-app --count=20
849 @endcode
850
851 Access:
852 @code{.cpp}
853 int N = parser.get<int>("N");
854 @endcode
855
856 @param name name of the argument
857 @param space_delete remove spaces from the left and right of the string
858 @tparam T the argument will be converted to this type if possible
859
860 @note You can access positional arguments by their `@`-prefixed name:
861 @code{.cpp}
862 parser.get<String>("@image");
863 @endcode
864 */
865 template <typename T>
get(const String & name,bool space_delete=true) const866 T get(const String& name, bool space_delete = true) const
867 {
868 T val = T();
869 getByName(name, space_delete, ParamType<T>::type, (void*)&val);
870 return val;
871 }
872
873 /** @brief Access positional arguments by index
874
875 Returns argument converted to selected type. Indexes are counted from zero.
876
877 For example, define:
878 @code{.cpp}
879 String keys = "{@arg1||}{@arg2||}"
880 @endcode
881
882 Call:
883 @code{.sh}
884 ./my-app abc qwe
885 @endcode
886
887 Access arguments:
888 @code{.cpp}
889 String val_1 = parser.get<String>(0); // returns "abc", arg1
890 String val_2 = parser.get<String>(1); // returns "qwe", arg2
891 @endcode
892
893 @param index index of the argument
894 @param space_delete remove spaces from the left and right of the string
895 @tparam T the argument will be converted to this type if possible
896 */
897 template <typename T>
get(int index,bool space_delete=true) const898 T get(int index, bool space_delete = true) const
899 {
900 T val = T();
901 getByIndex(index, space_delete, ParamType<T>::type, (void*)&val);
902 return val;
903 }
904
905 /** @brief Check if field was provided in the command line
906
907 @param name argument name to check
908 */
909 bool has(const String& name) const;
910
911 /** @brief Check for parsing errors
912
913 Returns false if error occurred while accessing the parameters (bad conversion, missing arguments,
914 etc.). Call @ref printErrors to print error messages list.
915 */
916 bool check() const;
917
918 /** @brief Set the about message
919
920 The about message will be shown when @ref printMessage is called, right before arguments table.
921 */
922 void about(const String& message);
923
924 /** @brief Print help message
925
926 This method will print standard help message containing the about message and arguments description.
927
928 @sa about
929 */
930 void printMessage() const;
931
932 /** @brief Print list of errors occurred
933
934 @sa check
935 */
936 void printErrors() const;
937
938 protected:
939 void getByName(const String& name, bool space_delete, Param type, void* dst) const;
940 void getByIndex(int index, bool space_delete, Param type, void* dst) const;
941
942 struct Impl;
943 Impl* impl;
944 };
945
946 //! @} core_utils
947
948 //! @cond IGNORED
949
950 /////////////////////////////// AutoBuffer implementation ////////////////////////////////////////
951
952 template<typename _Tp, size_t fixed_size> inline
AutoBuffer()953 AutoBuffer<_Tp, fixed_size>::AutoBuffer()
954 {
955 ptr = buf;
956 sz = fixed_size;
957 }
958
959 template<typename _Tp, size_t fixed_size> inline
AutoBuffer(size_t _size)960 AutoBuffer<_Tp, fixed_size>::AutoBuffer(size_t _size)
961 {
962 ptr = buf;
963 sz = fixed_size;
964 allocate(_size);
965 }
966
967 template<typename _Tp, size_t fixed_size> inline
AutoBuffer(const AutoBuffer<_Tp,fixed_size> & abuf)968 AutoBuffer<_Tp, fixed_size>::AutoBuffer(const AutoBuffer<_Tp, fixed_size>& abuf )
969 {
970 ptr = buf;
971 sz = fixed_size;
972 allocate(abuf.size());
973 for( size_t i = 0; i < sz; i++ )
974 ptr[i] = abuf.ptr[i];
975 }
976
977 template<typename _Tp, size_t fixed_size> inline AutoBuffer<_Tp, fixed_size>&
operator =(const AutoBuffer<_Tp,fixed_size> & abuf)978 AutoBuffer<_Tp, fixed_size>::operator = (const AutoBuffer<_Tp, fixed_size>& abuf)
979 {
980 if( this != &abuf )
981 {
982 deallocate();
983 allocate(abuf.size());
984 for( size_t i = 0; i < sz; i++ )
985 ptr[i] = abuf.ptr[i];
986 }
987 return *this;
988 }
989
990 template<typename _Tp, size_t fixed_size> inline
~AutoBuffer()991 AutoBuffer<_Tp, fixed_size>::~AutoBuffer()
992 { deallocate(); }
993
994 template<typename _Tp, size_t fixed_size> inline void
allocate(size_t _size)995 AutoBuffer<_Tp, fixed_size>::allocate(size_t _size)
996 {
997 if(_size <= sz)
998 {
999 sz = _size;
1000 return;
1001 }
1002 deallocate();
1003 sz = _size;
1004 if(_size > fixed_size)
1005 {
1006 ptr = new _Tp[_size];
1007 }
1008 }
1009
1010 template<typename _Tp, size_t fixed_size> inline void
deallocate()1011 AutoBuffer<_Tp, fixed_size>::deallocate()
1012 {
1013 if( ptr != buf )
1014 {
1015 delete[] ptr;
1016 ptr = buf;
1017 sz = fixed_size;
1018 }
1019 }
1020
1021 template<typename _Tp, size_t fixed_size> inline void
resize(size_t _size)1022 AutoBuffer<_Tp, fixed_size>::resize(size_t _size)
1023 {
1024 if(_size <= sz)
1025 {
1026 sz = _size;
1027 return;
1028 }
1029 size_t i, prevsize = sz, minsize = MIN(prevsize, _size);
1030 _Tp* prevptr = ptr;
1031
1032 ptr = _size > fixed_size ? new _Tp[_size] : buf;
1033 sz = _size;
1034
1035 if( ptr != prevptr )
1036 for( i = 0; i < minsize; i++ )
1037 ptr[i] = prevptr[i];
1038 for( i = prevsize; i < _size; i++ )
1039 ptr[i] = _Tp();
1040
1041 if( prevptr != buf )
1042 delete[] prevptr;
1043 }
1044
1045 template<typename _Tp, size_t fixed_size> inline size_t
size() const1046 AutoBuffer<_Tp, fixed_size>::size() const
1047 { return sz; }
1048
1049 //! @endcond
1050
1051
1052 // Basic Node class for tree building
1053 template<class OBJECT>
1054 class CV_EXPORTS Node
1055 {
1056 public:
Node()1057 Node()
1058 {
1059 m_pParent = 0;
1060 }
Node(OBJECT & payload)1061 Node(OBJECT& payload) : m_payload(payload)
1062 {
1063 m_pParent = 0;
1064 }
~Node()1065 ~Node()
1066 {
1067 removeChilds();
1068 if (m_pParent)
1069 {
1070 int idx = m_pParent->findChild(this);
1071 if (idx >= 0)
1072 m_pParent->m_childs.erase(m_pParent->m_childs.begin() + idx);
1073 }
1074 }
1075
findChild(OBJECT & payload) const1076 Node<OBJECT>* findChild(OBJECT& payload) const
1077 {
1078 for(size_t i = 0; i < this->m_childs.size(); i++)
1079 {
1080 if(this->m_childs[i]->m_payload == payload)
1081 return this->m_childs[i];
1082 }
1083 return NULL;
1084 }
1085
findChild(Node<OBJECT> * pNode) const1086 int findChild(Node<OBJECT> *pNode) const
1087 {
1088 for (size_t i = 0; i < this->m_childs.size(); i++)
1089 {
1090 if(this->m_childs[i] == pNode)
1091 return (int)i;
1092 }
1093 return -1;
1094 }
1095
addChild(Node<OBJECT> * pNode)1096 void addChild(Node<OBJECT> *pNode)
1097 {
1098 if(!pNode)
1099 return;
1100
1101 CV_Assert(pNode->m_pParent == 0);
1102 pNode->m_pParent = this;
1103 this->m_childs.push_back(pNode);
1104 }
1105
removeChilds()1106 void removeChilds()
1107 {
1108 for(size_t i = 0; i < m_childs.size(); i++)
1109 {
1110 m_childs[i]->m_pParent = 0; // avoid excessive parent vector trimming
1111 delete m_childs[i];
1112 }
1113 m_childs.clear();
1114 }
1115
getDepth()1116 int getDepth()
1117 {
1118 int count = 0;
1119 Node *pParent = m_pParent;
1120 while(pParent) count++, pParent = pParent->m_pParent;
1121 return count;
1122 }
1123
1124 public:
1125 OBJECT m_payload;
1126 Node<OBJECT>* m_pParent;
1127 std::vector<Node<OBJECT>*> m_childs;
1128 };
1129
1130
1131 namespace samples {
1132
1133 //! @addtogroup core_utils_samples
1134 // This section describes utility functions for OpenCV samples.
1135 //
1136 // @note Implementation of these utilities is not thread-safe.
1137 //
1138 //! @{
1139
1140 /** @brief Try to find requested data file
1141
1142 Search directories:
1143
1144 1. Directories passed via `addSamplesDataSearchPath()`
1145 2. OPENCV_SAMPLES_DATA_PATH_HINT environment variable
1146 3. OPENCV_SAMPLES_DATA_PATH environment variable
1147 If parameter value is not empty and nothing is found then stop searching.
1148 4. Detects build/install path based on:
1149 a. current working directory (CWD)
1150 b. and/or binary module location (opencv_core/opencv_world, doesn't work with static linkage)
1151 5. Scan `<source>/{,data,samples/data}` directories if build directory is detected or the current directory is in source tree.
1152 6. Scan `<install>/share/OpenCV` directory if install directory is detected.
1153
1154 @see cv::utils::findDataFile
1155
1156 @param relative_path Relative path to data file
1157 @param required Specify "file not found" handling.
1158 If true, function prints information message and raises cv::Exception.
1159 If false, function returns empty result
1160 @param silentMode Disables messages
1161 @return Returns path (absolute or relative to the current directory) or empty string if file is not found
1162 */
1163 CV_EXPORTS_W cv::String findFile(const cv::String& relative_path, bool required = true, bool silentMode = false);
1164
1165 CV_EXPORTS_W cv::String findFileOrKeep(const cv::String& relative_path, bool silentMode = false);
1166
findFileOrKeep(const cv::String & relative_path,bool silentMode)1167 inline cv::String findFileOrKeep(const cv::String& relative_path, bool silentMode)
1168 {
1169 cv::String res = findFile(relative_path, false, silentMode);
1170 if (res.empty())
1171 return relative_path;
1172 return res;
1173 }
1174
1175 /** @brief Override search data path by adding new search location
1176
1177 Use this only to override default behavior
1178 Passed paths are used in LIFO order.
1179
1180 @param path Path to used samples data
1181 */
1182 CV_EXPORTS_W void addSamplesDataSearchPath(const cv::String& path);
1183
1184 /** @brief Append samples search data sub directory
1185
1186 General usage is to add OpenCV modules name (`<opencv_contrib>/modules/<name>/samples/data` -> `<name>/samples/data` + `modules/<name>/samples/data`).
1187 Passed subdirectories are used in LIFO order.
1188
1189 @param subdir samples data sub directory
1190 */
1191 CV_EXPORTS_W void addSamplesDataSearchSubDirectory(const cv::String& subdir);
1192
1193 //! @}
1194 } // namespace samples
1195
1196 namespace utils {
1197
1198 CV_EXPORTS int getThreadID();
1199
1200 } // namespace
1201
1202 } //namespace cv
1203
1204 #ifdef CV_COLLECT_IMPL_DATA
1205 #include "opencv2/core/utils/instrumentation.hpp"
1206 #else
1207 /// Collect implementation data on OpenCV function call. Requires ENABLE_IMPL_COLLECTION build option.
1208 #define CV_IMPL_ADD(impl)
1209 #endif
1210
1211 #endif //OPENCV_CORE_UTILITY_H
1212