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