diff --git a/CMakeLists.txt b/CMakeLists.txt index d84aac593dd80393edb5374aa69682d47b7a9b71..60098dca8814e9338bd6a887442011954a4d45c3 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -663,6 +663,14 @@ endif() ################## LATEX ################## set(BUILD_LATEX_DOCS OFF CACHE BOOL "Build LaTeX OpenCV Documentation") +################### DOXYGEN ############### + +find_package(Doxygen) + +if(DOXYGEN_FOUND) + set(BUILD_DOXYGEN_DOCS ON CACHE BOOL "Generate HTML docs using Doxygen") +endif() + # ---------------------------------------------------------------------------- # UPDATE CONFIG FILES & SCRIPTS: # @@ -1190,10 +1198,17 @@ message(STATUS " Use TBB: NO") endif() if(BUILD_LATEX_DOCS AND PDFLATEX_COMPILER) -message(STATUS " Build Documentation 1") +message(STATUS " Build PDF YES") else() -message(STATUS " Build Documentation 0") +message(STATUS " Build PDF NO") endif() + +if(BUILD_DOXYGEN_DOCS AND DOXYGEN_FOUND) +message(STATUS " Doxygen HTMLs YES") +else() +message(STATUS " Doxygen HTMLs NO") +endif() + message(STATUS "") message(STATUS " Install path: ${CMAKE_INSTALL_PREFIX}") message(STATUS "") diff --git a/doc/CMakeLists.txt b/doc/CMakeLists.txt index 6a2a046f38c81a8165ffe32592807722bbbe2ee8..c1dcc94e3d47a263b218bc14ff01affbff983e6e 100644 --- a/doc/CMakeLists.txt +++ b/doc/CMakeLists.txt @@ -126,3 +126,38 @@ endif() # BUILD_LATEX_DOCS AND PDFLATEX_COMPILER install(FILES ${FILES_DOC} DESTINATION "${OPENCV_DOC_INSTALL_PATH}" COMPONENT main) install(FILES ${FILES_DOC_PAPERS} DESTINATION "${OPENCV_DOC_INSTALL_PATH}/papers" COMPONENT main) install(FILES ${FILES_DOC_VS} DESTINATION "${OPENCV_DOC_INSTALL_PATH}/vidsurv" COMPONENT main) + +########################################### Doxygen Docs ######################################### + +if(BUILD_DOXYGEN_DOCS AND DOXYGEN_FOUND) + +set(DOXYGEN_LANGUAGE "English" CACHE STRING "Language used by doxygen") +mark_as_advanced(DOXYGEN_LANGUAGE) + +set(CMAKE_DOXYGEN_IMAGE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/pics") + +set(module_names core) # imgproc calib3d features2d objdetect video highgui ml legacy contrib) +set(DOXYGEN_SOURCE_DIR) +set(doxy_html_dep_list) + +foreach(m ${module_names}) + set(module_hdr_path "${CMAKE_SOURCE_DIR}/modules/${m}/include/opencv2/${m}") + set(DOXYGEN_SOURCE_DIR ${DOXYGEN_SOURCE_DIR} ${module_hdr_path}) + file(GLOB module_hdrs "${module_hdr_path}/*.h*") + set(doxy_html_dep_list ${doxy_html_dep_list} ${module_hdrs}) +endforeach() + +set(DOXYGEN_OUTPUT_DIR html) +string(REGEX REPLACE ";" " " CMAKE_DOXYGEN_INPUT_LIST "${DOXYGEN_SOURCE_DIR}") + +configure_file(Doxyfile.in ${CMAKE_CURRENT_BINARY_DIR}/Doxyfile) +set(HTML_TARGET "DOXY_HTML" ) + +add_custom_target(${HTML_TARGET} ALL + ${DOXYGEN_EXECUTABLE} ${CMAKE_CURRENT_BINARY_DIR}/Doxyfile + DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/Doxyfile ${doxy_html_dep_list}) + +install(DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/html/" DESTINATION "${OPENCV_DOC_INSTALL_PATH}/html/" COMPONENT main) + +endif() + diff --git a/doc/Doxyfile.in b/doc/Doxyfile.in new file mode 100755 index 0000000000000000000000000000000000000000..332ca77542933d8744b278507625d96bdfd8968f --- /dev/null +++ b/doc/Doxyfile.in @@ -0,0 +1,123 @@ +# Doxyfile 1.3.9.1 + +#--------------------------------------------------------------------------- +# Project related configuration options +#--------------------------------------------------------------------------- +PROJECT_NAME = opencv +PROJECT_NUMBER = @OPENCV_VERSION@ +OUTPUT_DIRECTORY = . +CREATE_SUBDIRS = NO +OUTPUT_LANGUAGE = English +BRIEF_MEMBER_DESC = YES +#--------------------------------------------------------------------------- +# Build related configuration options +#--------------------------------------------------------------------------- +EXTRACT_ALL = YES +#--------------------------------------------------------------------------- +# configuration options related to warning and progress messages +#--------------------------------------------------------------------------- +QUIET = NO +WARNINGS = YES +WARN_IF_UNDOCUMENTED = YES +WARN_IF_DOC_ERROR = YES +WARN_FORMAT = "$file:$line: $text" +WARN_LOGFILE = +#--------------------------------------------------------------------------- +# configuration options related to the input files +#--------------------------------------------------------------------------- +INPUT = @CMAKE_DOXYGEN_INPUT_LIST@ +FILE_PATTERNS = *.cpp *.h* +RECURSIVE = NO +EXCLUDE = +EXCLUDE_SYMLINKS = NO +EXCLUDE_PATTERNS = +EXAMPLE_PATH = +EXAMPLE_PATTERNS = +EXAMPLE_RECURSIVE = NO +IMAGE_PATH = @CMAKE_DOXYGEN_IMAGE_PATH@ +INPUT_FILTER = +FILTER_PATTERNS = +FILTER_SOURCE_FILES = NO +#--------------------------------------------------------------------------- +# configuration options related to the alphabetical class index +#--------------------------------------------------------------------------- +ALPHABETICAL_INDEX = YES +COLS_IN_ALPHA_INDEX = 5 +IGNORE_PREFIX = +#--------------------------------------------------------------------------- +# configuration options related to the HTML output +#--------------------------------------------------------------------------- +GENERATE_HTML = YES +HTML_OUTPUT = html +HTML_FILE_EXTENSION = .html + +#--------------------------------------------------------------------------- +# configuration options related to the LaTeX output +#--------------------------------------------------------------------------- +GENERATE_LATEX = NO +#--------------------------------------------------------------------------- +# configuration options related to the RTF output +#--------------------------------------------------------------------------- +GENERATE_RTF = NO +#--------------------------------------------------------------------------- +# configuration options related to the man page output +#--------------------------------------------------------------------------- +GENERATE_MAN = NO +#--------------------------------------------------------------------------- +# configuration options related to the XML output +#--------------------------------------------------------------------------- +GENERATE_XML = NO +#--------------------------------------------------------------------------- +# configuration options for the AutoGen Definitions output +#--------------------------------------------------------------------------- +GENERATE_AUTOGEN_DEF = NO +#--------------------------------------------------------------------------- +# configuration options related to the Perl module output +#--------------------------------------------------------------------------- +GENERATE_PERLMOD = NO +#--------------------------------------------------------------------------- +# Configuration options related to the preprocessor +#--------------------------------------------------------------------------- +ENABLE_PREPROCESSING = YES +MACRO_EXPANSION = YES +EXPAND_ONLY_PREDEF = YES +PREDEFINED = CV_EXPORTS= CVAPI(x)=x __cplusplus=1 +SEARCH_INCLUDES = NO +INCLUDE_PATH = +INCLUDE_FILE_PATTERNS = +EXPAND_AS_DEFINED = +SKIP_FUNCTION_MACROS = YES +#--------------------------------------------------------------------------- +# Configuration::additions related to external references +#--------------------------------------------------------------------------- +TAGFILES = +GENERATE_TAGFILE = +ALLEXTERNALS = NO +EXTERNAL_GROUPS = YES +PERL_PATH = /usr/bin/perl +#--------------------------------------------------------------------------- +# Configuration options related to the dot tool +#--------------------------------------------------------------------------- +CLASS_DIAGRAMS = YES +HIDE_UNDOC_RELATIONS = YES +HAVE_DOT = NO +CLASS_GRAPH = YES +COLLABORATION_GRAPH = YES +UML_LOOK = NO +TEMPLATE_RELATIONS = YES +INCLUDE_GRAPH = YES +INCLUDED_BY_GRAPH = YES +CALL_GRAPH = NO +GRAPHICAL_HIERARCHY = YES +DOT_IMAGE_FORMAT = png +DOT_PATH = +DOTFILE_DIRS = +MAX_DOT_GRAPH_WIDTH = 1024 +MAX_DOT_GRAPH_HEIGHT = 1024 +MAX_DOT_GRAPH_DEPTH = 0 +GENERATE_LEGEND = YES +DOT_CLEANUP = YES +#--------------------------------------------------------------------------- +# Configuration::additions related to the search engine +#--------------------------------------------------------------------------- +SEARCHENGINE = YES diff --git a/doc/cxcore_utilities_system_functions.tex b/doc/cxcore_utilities_system_functions.tex index 0dafda10b6fb7c52785143657190d37e91466971..9d912baf99aea0f1f28f0d1bbaf52c4d04a8639f 100644 --- a/doc/cxcore_utilities_system_functions.tex +++ b/doc/cxcore_utilities_system_functions.tex @@ -730,7 +730,7 @@ Returns the number of ticks per second \cvdefCpp{double getTickFrequency();} The function returns the number of ticks per second. -That is, the following code computes the executing time in seconds. +That is, the following code computes the execution time in seconds. \begin{lstlisting} double t = (double)getTickCount(); // do something ... diff --git a/modules/core/include/opencv2/core/core.hpp b/modules/core/include/opencv2/core/core.hpp index 27ec611bb746b628c102e3552f33c8a97e344d7f..0a8f1877b9d573f0fa2fcb21746cbbcb5e0ae727 100644 --- a/modules/core/include/opencv2/core/core.hpp +++ b/modules/core/include/opencv2/core/core.hpp @@ -1,3 +1,6 @@ +/*! \file core.hpp + \brief The Core Functionality + */ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. @@ -59,6 +62,9 @@ #include #endif // SKIP_INCLUDES +/*! \namespace cv + Namespace where all the C++ OpenCV functionality resides +*/ namespace cv { #undef abs @@ -81,16 +87,30 @@ CV_EXPORTS WString toUtf16(const string& str); CV_EXPORTS string format( const char* fmt, ... ); +/*! + The standard OpenCV exception class. + Instances of the class are thrown by various functions and methods in the case of critical errors. + */ class CV_EXPORTS Exception : public std::exception { public: - Exception() { code = 0; line = 0; } + /*! + Default constructor + */ + Exception() { code = 0; line = 0; } + /*! + Full constructor. Normally the constuctor is not called explicitly. + Instead, the macros CV_Error(), CV_Error_() and CV_Assert() are used. + */ Exception(int _code, const string& _err, const string& _func, const string& _file, int _line) : code(_code), err(_err), func(_func), file(_file), line(_line) { formatMessage(); } virtual ~Exception() throw() {} + /*! + \return the error description and the context as a text string. + */ virtual const char *what() const throw() { return msg.c_str(); } void formatMessage() @@ -101,23 +121,56 @@ public: msg = format("%s:%d: error: (%d) %s\n", file.c_str(), line, code, err.c_str()); } - string msg; + string msg; ///< the formatted error message - int code; - string err; - string func; - string file; - int line; + int code; ///< error code @see CVStatus + string err; ///< error description + string func; ///< function name. Available only when the compiler supports __func__ macro + string file; ///< source file name where the error has occured + int line; ///< line number in the source file where the error has occured }; - + +/*! + \fn void error(const Exception& exc); + \brief Signals an error and raises the exception. + + By default the function prints information about the error to stderr, + then it either stops if setBreakOnError() had been called before or raises the exception. + It is possible to alternate error processing by using redirectError(). + + \param exc the exception raisen. + */ CV_EXPORTS void error( const Exception& exc ); -CV_EXPORTS bool setBreakOnError(bool value); + +/*! + \fn bool setBreakOnError(bool flag); + \brief Sets/resets the break-on-error mode. + + When the break-on-error mode is set, the default error handler + issues a hardware exception, which can make debugging more convenient. + + \return the previous state + */ +CV_EXPORTS bool setBreakOnError(bool flag); typedef int (CV_CDECL *ErrorCallback)( int status, const char* func_name, const char* err_msg, const char* file_name, int line, void* userdata ); - + +/*! + \fn ErrorCallback redirectError( ErrorCallback errCallback, + void* userdata=0, void** prevUserdata=0); + \brief Sets the new error handler and the optional user data. + + The function sets the new error handler, called from cv::error(). + + \param errCallback the new error handler. If NULL, the default error handler is used. + \param userdata the optional user data pointer, passed to the callback. + \param prevUserdata the optional output parameter where the previous user data pointer is stored + + \return the previous error handler +*/ CV_EXPORTS ErrorCallback redirectError( ErrorCallback errCallback, void* userdata=0, void** prevUserdata=0); @@ -141,13 +194,84 @@ CV_EXPORTS void setNumThreads(int); CV_EXPORTS int getNumThreads(); CV_EXPORTS int getThreadNum(); +/*! + \fn int64 getTickCount(); + \brief Returns the number of ticks. + + The function returns the number of ticks since the certain event (e.g. when the machine was turned on). + It can be used to initialize cv::RNG or to measure a function execution time by reading the tick count + before and after the function call. The granularity of ticks depends on the hardware and OS used. Use + cv::getTickFrequency() to convert ticks to seconds. +*/ CV_EXPORTS int64 getTickCount(); + +/*! + \fn int64 getTickCount(); + \brief Returns the number of ticks per seconds. + + The function returns the number of ticks (as returned by cv::getTickCount()) per second. + The following code computes the execution time in milliseconds: + + \code + double exec_time = (double)getTickCount(); + // do something ... + exec_time = ((double)getTickCount() - exec_time)*1000./getTickFrequency(); + \endcode +*/ CV_EXPORTS double getTickFrequency(); + +/*! + \fn int64 getCPUTickCount(); + \brief Returns the number of CPU ticks. + + On platforms where the feature is available, the function returns the number of CPU ticks + since the certain event (normally, the system power-on moment). Using this function + one can accurately measure the execution time of very small code fragments, + for which cv::getTickCount() granularity is not enough. +*/ CV_EXPORTS int64 getCPUTickCount(); +/*! + \fn bool checkHardwareSupport(int feature); + \brief Returns SSE etc. support status + + The function returns true if certain hardware features are available. + Currently, the following features are recognized: + - CV_CPU_MMX - MMX + - CV_CPU_SSE - SSE + - CV_CPU_SSE2 - SSE 2 + - CV_CPU_SSE3 - SSE 3 + - CV_CPU_SSSE3 - SSSE 3 + - CV_CPU_SSE4_1 - SSE 4.1 + - CV_CPU_SSE4_2 - SSE 4.2 + - CV_CPU_AVX - AVX + + \note {Note that the function output is not static. Once you called cv::useOptimized(false), + most of the hardware acceleration is disabled and thus the function will returns false, + until you call cv::useOptimized(true)} +*/ CV_EXPORTS bool checkHardwareSupport(int feature); -CV_EXPORTS void* fastMalloc(size_t); +/*! + \fn void* fastMalloc(size_t bufSize); + \brief allocates memory buffer + + This is specialized OpenCV memory allocation function that returns properly aligned memory buffers. + The usage is identical to malloc(). The allocated buffers must be freed with cv::fastFree(). + If there is not enough memory, the function calls cv::error(), which raises an exception. + + \param bufSize buffer size in bytes + \return the allocated memory buffer. +*/ +CV_EXPORTS void* fastMalloc(size_t bufSize); + +/*! + \fn void fastFree(void* ptr); + \brief frees the memory allocated with cv::fastMalloc + + This is the corresponding deallocation function for cv::fastMalloc(). + When ptr==NULL, the function has no effect. +*/ CV_EXPORTS void fastFree(void* ptr); template static inline _Tp* allocate(size_t n) @@ -160,19 +284,52 @@ template static inline void deallocate(_Tp* ptr, size_t) delete[] ptr; } +/*! + \fn template inline _Tp* alignPtr(_Tp* ptr, int n=(int)sizeof(_Tp)); + \brief aligns pointer by the certain number of bytes + + This small inline function aligns the pointer by the certian number of bytes by shifting + it forward by 0 or a positive offset. +*/ template static inline _Tp* alignPtr(_Tp* ptr, int n=(int)sizeof(_Tp)) { return (_Tp*)(((size_t)ptr + n-1) & -n); } +/*! + \fn inline size_t alignSize(size_t sz, int n); + \brief aligns buffer size by the certain number of bytes + + This small inline function aligns a buffer size by the certian number of bytes by enlarging it. +*/ static inline size_t alignSize(size_t sz, int n) { return (sz + n-1) & -n; } +/*! + \fn void setUseOptimized(bool flag); + \brief Turns on/off available optimization + + The function turns on or off the optimized code in OpenCV. Some optimization can not be enabled + or disabled, but, for example, most of SSE code in OpenCV can be temporarily turned on or off this way. + + \note{Since optimization may imply using special data structures, it may be unsafe + to call this function anywhere in the code. Instead, call it somewhere at the top level.} +*/ CV_EXPORTS void setUseOptimized(bool); + +/*! + \fn bool useOptimized(); + \brief Returns the current optimization status + + The function returns the current optimization status, which is controlled by cv::setUseOptimized(). +*/ CV_EXPORTS bool useOptimized(); +/*! + The STL-compilant memory Allocator based on cv::fastMalloc() and cv::fastFree() +*/ template class CV_EXPORTS Allocator { public: @@ -209,6 +366,12 @@ public: /////////////////////// Vec (used as element of multi-channel images ///////////////////// +/*! + A helper class for cv::DataType + + The class is specialized for each fundamental numerical data type supported by OpenCV. + It provides DataDepth::value constant. +*/ template class CV_EXPORTS DataDepth { public: enum { value = -1, fmt=(int)'\0' }; }; template<> class DataDepth { public: enum { value = CV_8U, fmt=(int)'u' }; }; @@ -221,36 +384,70 @@ template<> class DataDepth { public: enum { value = CV_32F, fmt=(int)'f' template<> class DataDepth { public: enum { value = CV_64F, fmt=(int)'d' }; }; template class DataDepth<_Tp*> { public: enum { value = CV_USRTYPE1, fmt=(int)'r' }; }; +/*! + A short numerical vector. + + This template class represents short numerical vectors (of 1, 2, 3, 4 ... elements) + on which you can perform basic arithmetical operations, access individual elements using [] operator etc. + The vectors are allocated on stack, as opposite to std::valarray, std::vector, cv::Mat etc., + which elements are dynamically allocated in the heap. + + The template takes 2 parameters: + -# _Tp element type + -# cn the number of elements + + In addition to the universal notation like Vec, you can use shorter aliases + for the most popular specialized variants of Vec, e.g. Vec3f ~ Vec. +*/ template class CV_EXPORTS Vec { public: typedef _Tp value_type; enum { depth = DataDepth<_Tp>::value, channels = cn, type = CV_MAKETYPE(depth, channels) }; + //! default constructor Vec(); - Vec(_Tp v0); - Vec(_Tp v0, _Tp v1); - Vec(_Tp v0, _Tp v1, _Tp v2); - Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3); - Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4); - Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5); - Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6); - Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7); - Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7, _Tp v8); - Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7, _Tp v8, _Tp v9); + + Vec(_Tp v0); //!< 1-element vector constructor + Vec(_Tp v0, _Tp v1); //!< 2-element vector constructor + Vec(_Tp v0, _Tp v1, _Tp v2); //!< 3-element vector constructor + Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3); //!< 4-element vector constructor + Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4); //!< 5-element vector constructor + Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5); //!< 6-element vector constructor + Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6); //!< 7-element vector constructor + Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7); //!< 8-element vector constructor + Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7, _Tp v8); //!< 9-element vector constructor + Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7, _Tp v8, _Tp v9); //!< 10-element vector constructor + Vec(const Vec<_Tp, cn>& v); static Vec all(_Tp alpha); + //! dot product _Tp dot(const Vec& v) const; + //! dot product computed in double-precision arithmetics double ddot(const Vec& v) const; + /*! + cross product of the two 3D vectors. + + For other dimensionalities the exception is raised + */ Vec cross(const Vec& v) const; + //! convertion to another data type template operator Vec() const; + //! conversion to 4-element CvScalar. operator CvScalar() const; + + /*! element access */ const _Tp& operator [](int i) const; _Tp& operator[](int i); - _Tp val[cn]; + _Tp val[cn]; //< vector elements }; + +/* \typedef + + Shorter aliases for the most popular specializations of Vec +*/ typedef Vec Vec2b; typedef Vec Vec3b; typedef Vec Vec4b; @@ -277,31 +474,58 @@ typedef Vec Vec3d; typedef Vec Vec4d; typedef Vec Vec6d; + //////////////////////////////// Complex ////////////////////////////// +/*! + A complex number class. + + The template class is similar and compatible with std::complex, however it provides slightly + more convenient access to the real and imaginary parts using through the simple field access, as opposite + to std::complex::real() and std::complex::imag(). +*/ template class CV_EXPORTS Complex { public: + + //! constructors Complex(); Complex( _Tp _re, _Tp _im=0 ); Complex( const std::complex<_Tp>& c ); + + //! conversion to another data type template operator Complex() const; + //! conjugation Complex conj() const; + //! conversion to std::complex operator std::complex<_Tp>() const; - _Tp re, im; + _Tp re, im; //< the real and the imaginary parts }; + +/*! + \typedef +*/ typedef Complex Complexf; typedef Complex Complexd; + //////////////////////////////// Point_ //////////////////////////////// +/*! + template 2D point class. + + The class defines a point in 2D space. Data type of the point coordinates is specified + as a template parameter. There are a few shorter aliases available for user convenience. + See cv::Point, cv::Point2i, cv::Point2f and cv::Point2d. +*/ template class CV_EXPORTS Point_ { public: typedef _Tp value_type; + // various constructors Point_(); Point_(_Tp _x, _Tp _y); Point_(const Point_& pt); @@ -309,93 +533,149 @@ public: Point_(const CvPoint2D32f& pt); Point_(const Size_<_Tp>& sz); Point_(const Vec<_Tp, 2>& v); + Point_& operator = (const Point_& pt); + //! conversion to another data type template operator Point_<_Tp2>() const; + + //! conversion to the old-style C structures operator CvPoint() const; operator CvPoint2D32f() const; operator Vec<_Tp, 2>() const; + //! dot product _Tp dot(const Point_& pt) const; + //! dot product computed in double-precision arithmetics double ddot(const Point_& pt) const; + //! checks whether the point is inside the specified rectangle bool inside(const Rect_<_Tp>& r) const; - _Tp x, y; + _Tp x, y; //< the point coordinates }; +/*! + template 3D point class. + + The class defines a point in 3D space. Data type of the point coordinates is specified + as a template parameter. + + \see cv::Point3i, cv::Point3f and cv::Point3d +*/ template class CV_EXPORTS Point3_ { public: typedef _Tp value_type; + // various constructors Point3_(); Point3_(_Tp _x, _Tp _y, _Tp _z); Point3_(const Point3_& pt); explicit Point3_(const Point_<_Tp>& pt); Point3_(const CvPoint3D32f& pt); Point3_(const Vec<_Tp, 3>& v); + Point3_& operator = (const Point3_& pt); + //! conversion to another data type template operator Point3_<_Tp2>() const; + //! conversion to the old-style CvPoint... operator CvPoint3D32f() const; + //! conversion to cv::Vec<> operator Vec<_Tp, 3>() const; + //! dot product _Tp dot(const Point3_& pt) const; + //! dot product computed in double-precision arithmetics double ddot(const Point3_& pt) const; + //! cross product of the 2 3D points Point3_ cross(const Point3_& pt) const; - _Tp x, y, z; + _Tp x, y, z; //< the point coordinates }; //////////////////////////////// Size_ //////////////////////////////// +/*! + The 2D size class + + The class represents the size of a 2D rectangle, image size, matrix size etc. + Normally, cv::Size ~ cv::Size_ is used. +*/ template class CV_EXPORTS Size_ { public: typedef _Tp value_type; + //! various constructors Size_(); Size_(_Tp _width, _Tp _height); Size_(const Size_& sz); Size_(const CvSize& sz); Size_(const CvSize2D32f& sz); Size_(const Point_<_Tp>& pt); + Size_& operator = (const Size_& sz); + //! the area (width*height) _Tp area() const; + //! conversion of another data type. template operator Size_<_Tp2>() const; + + //! conversion to the old-style OpenCV types operator CvSize() const; operator CvSize2D32f() const; - _Tp width, height; + _Tp width, height; // the width and the height }; //////////////////////////////// Rect_ //////////////////////////////// +/*! + The 2D up-right rectangle class + + The class represents a 2D rectangle with coordinates of the specified data type. + Normally, cv::Rect ~ cv::Rect_ is used. +*/ template class CV_EXPORTS Rect_ { public: typedef _Tp value_type; + //! various constructors Rect_(); Rect_(_Tp _x, _Tp _y, _Tp _width, _Tp _height); Rect_(const Rect_& r); Rect_(const CvRect& r); Rect_(const Point_<_Tp>& org, const Size_<_Tp>& sz); Rect_(const Point_<_Tp>& pt1, const Point_<_Tp>& pt2); + Rect_& operator = ( const Rect_& r ); + //! the top-left corner Point_<_Tp> tl() const; + //! the bottom-right corner Point_<_Tp> br() const; + //! size (width, height) of the rectangle Size_<_Tp> size() const; + //! area (width*height) of the rectangle _Tp area() const; + //! conversion to another data type template operator Rect_<_Tp2>() const; + //! conversion to the old-style CvRect operator CvRect() const; + //! checks whether the rectangle contains the point bool contains(const Point_<_Tp>& pt) const; - _Tp x, y, width, height; + _Tp x, y, width, height; //< the top-left corner, as well as width and height of the rectangle }; + +/*! + \typedef + + shorter aliases for the most popular cv::Point_<>, cv::Size_<> and cv::Rect_<> specializations +*/ typedef Point_ Point2i; typedef Point2i Point; typedef Size_ Size2i; @@ -408,35 +688,62 @@ typedef Point3_ Point3i; typedef Point3_ Point3f; typedef Point3_ Point3d; + +/*! + The rotated 2D rectangle. + + The class represents rotated (i.e. not up-right) rectangles on a plane. + Each rectangle is described by the center point (mass center), length of each side + (represented by cv::Size2f structure) and the rotation angle in degrees. +*/ class CV_EXPORTS RotatedRect { public: + //! various constructors RotatedRect(); RotatedRect(const Point2f& _center, const Size2f& _size, float _angle); RotatedRect(const CvBox2D& box); + + //! returns 4 vertices of the rectangle void points(Point2f pts[]) const; + //! returns the minimal up-right rectangle containing the rotated rectangle Rect boundingRect() const; + //! conversion to the old-style CvBox2D structure operator CvBox2D() const; - Point2f center; - Size2f size; - float angle; + + Point2f center; //< the rectangle mass center + Size2f size; //< width and height of the rectangle + float angle; //< the rotation angle. When the angle is 0, 90, 180, 270 etc., the rectangle becomes an up-right rectangle. }; //////////////////////////////// Scalar_ /////////////////////////////// +/*! + The template scalar class. + + This is partially specialized cv::Vec class with the number of elements = 4, i.e. a short vector of four elements. + Normally, cv::Scalar ~ cv::Scalar_ is used. +*/ template class CV_EXPORTS Scalar_ : public Vec<_Tp, 4> { public: + //! various constructors Scalar_(); Scalar_(_Tp v0, _Tp v1, _Tp v2=0, _Tp v3=0); Scalar_(const CvScalar& s); Scalar_(_Tp v0); + + //! returns a scalar with all elements set to v0 static Scalar_<_Tp> all(_Tp v0); + //! conversion to the old-style CvScalar operator CvScalar() const; + //! conversion to another data type template operator Scalar_() const; + //! per-element product Scalar_<_Tp> mul(const Scalar_<_Tp>& t, double scale=1 ) const; + //! another helper conversion method. \see cvScalarToRawData template void convertTo(T2* buf, int channels, int unroll_to=0) const; }; @@ -444,6 +751,11 @@ typedef Scalar_ Scalar; //////////////////////////////// Range ///////////////////////////////// +/*! + The 2D range class + + This is the class used to specify a continuous subsequence, i.e. part of a contour, or a column span in a matrix. +*/ class CV_EXPORTS Range { public: @@ -460,6 +772,17 @@ public: /////////////////////////////// DataType //////////////////////////////// +/*! + Informative template class for OpenCV "scalars". + + The class is specialized for each primitive numerical type supported by OpenCV (such as unsigned char or float), + as well as for more complex types, like cv::Complex<>, std::complex<>, cv::Vec<> etc. + The common property of all such types (called "scalars", do not confuse it with cv::Scalar_) + is that each of them is basically a tuple of numbers of the same type. Each "scalar" can be represented + by the depth id (CV_8U ... CV_64F) and the number of channels. + OpenCV matrices, 2D or nD, dense or sparse, can store "scalars", + as long as the number of channels does not exceed CV_MAX_CN (currently set to 32). +*/ template class DataType { public: @@ -679,27 +1002,60 @@ public: //////////////////// Generic ref-counting pointer class for C/C++ objects //////////////////////// +/*! + Smart pointer to dynamically allocated objects. + + This is template pointer-wrapping class that stores the associated reference counter along with the + object pointer. The class is similar to std::smart_ptr<> from the recent addons to the C++ standard, + but is shorter to write :) and self-contained (i.e. does add any dependency on the compiler or an external library). + + Basically, you can use "Ptr ptr" (or faster "const Ptr& ptr" for read-only access) + everywhere instead of "MyObjectType* ptr", where MyObjectType is some C structure or a C++ class. + To make it all work, you need to specialize Ptr<>::delete_obj(), like: + + \code + template<> void Ptr::delete_obj() { call_destructor_func(obj); } + \endcode + + \note{if MyObjectType is a C++ class with a destructor, you do not need to specialize delete_obj(), + since the default implementation calls "delete obj;"} + + \note{Another good property of the class is that the operations on the reference counter are atomic, + i.e. it is safe to use the class in multi-threaded applications} +*/ template class CV_EXPORTS Ptr { public: + //! empty constructor Ptr(); + //! take ownership of the pointer. The associated reference counter is allocated and set to 1 Ptr(_Tp* _obj); + //! calls release() ~Ptr(); + //! copy constructor. Copies the members and calls addref() Ptr(const Ptr& ptr); + //! copy operator. Calls ptr.addref() and release() before copying the members Ptr& operator = (const Ptr& ptr); + //! increments the reference counter void addref(); + //! decrements the reference counter. If it reaches 0, delete_obj() is called void release(); + //! deletes the object. Override if needed void delete_obj(); + //! returns true iff obj==NULL bool empty() const; + + //! helper operators making "Ptr ptr" use very similar to "T* ptr". _Tp* operator -> (); const _Tp* operator -> () const; operator _Tp* (); operator const _Tp*() const; + protected: - _Tp* obj; - int* refcount; + _Tp* obj; //< the object pointer. + int* refcount; //< the associated reference counter }; //////////////////////////////// Mat //////////////////////////////// @@ -742,106 +1098,315 @@ enum { GEMM_1_T=1, GEMM_2_T=2, GEMM_3_T=4 }; enum { DFT_INVERSE=1, DFT_SCALE=2, DFT_ROWS=4, DFT_COMPLEX_OUTPUT=16, DFT_REAL_OUTPUT=32, DCT_INVERSE = DFT_INVERSE, DCT_ROWS=DFT_ROWS }; +/*! + The matrix class. + + The class represents a 2D numerical array that can act as a matrix, image, optical flow map etc. + It is very similar to CvMat type from earlier versions of OpenCV, and similarly to CvMat, + the matrix can be multi-channel. It also fully supports ROI mechanism. + + There are many different ways to create cv::Mat object. Here are the some popular ones: +
    +
  • using cv::Mat::create(nrows, ncols, type) method or + the similar constructor cv::Mat::Mat(nrows, ncols, type[, fill_value]) constructor. + A new matrix of the specified size and specifed type will be allocated. + "type" has the same meaning as in cvCreateMat function, + e.g. CV_8UC1 means 8-bit single-channel matrix, CV_32FC2 means 2-channel (i.e. complex) + floating-point matrix etc: + + \code + // make 7x7 complex matrix filled with 1+3j. + cv::Mat M(7,7,CV_32FC2,Scalar(1,3)); + // and now turn M to 100x60 15-channel 8-bit matrix. + // The old content will be deallocated + M.create(100,60,CV_8UC(15)); + \endcode + + As noted in the introduction of this chapter, \texttt{create()} + will only allocate a new matrix when the current matrix dimensionality + or type are different from the specified. + +
  • by using a copy constructor or assignment operator, where on the right side it can + be a matrix or expression, see below. Again, as noted in the introduction, + matrix assignment is O(1) operation because it only copies the header + and increases the reference counter. cv::Mat::clone() method can be used to get a full + (a.k.a. deep) copy of the matrix when you need it. + +
  • by constructing a header for a part of another matrix. It can be a single row, single column, + several rows, several columns, rectangular region in the matrix (called a minor in algebra) or + a diagonal. Such operations are also O(1), because the new header will reference the same data. + You can actually modify a part of the matrix using this feature, e.g. + + \code + // add 5-th row, multiplied by 3 to the 3rd row + M.row(3) = M.row(3) + M.row(5)*3; + + // now copy 7-th column to the 1-st column + // M.col(1) = M.col(7); // this will not work + Mat M1 = M.col(1); + M.col(7).copyTo(M1); + + // create new 320x240 image + cv::Mat img(Size(320,240),CV_8UC3); + // select a roi + cv::Mat roi(img, Rect(10,10,100,100)); + // fill the ROI with (0,255,0) (which is green in RGB space); + // the original 320x240 image will be modified + roi = Scalar(0,255,0); + \endcode + + Thanks to the additional cv::Mat::datastart and cv::Mat::dataend members, it is possible to + compute the relative sub-matrix position in the main "container" matrix using cv::Mat::locateROI(): + + \code + Mat A = Mat::eye(10, 10, CV_32S); + // extracts A columns, 1 (inclusive) to 3 (exclusive). + Mat B = A(Range::all(), Range(1, 3)); + // extracts B rows, 5 (inclusive) to 9 (exclusive). + // that is, C ~ A(Range(5, 9), Range(1, 3)) + Mat C = B(Range(5, 9), Range::all()); + Size size; Point ofs; + C.locateROI(size, ofs); + // size will be (width=10,height=10) and the ofs will be (x=1, y=5) + \endcode + + As in the case of whole matrices, if you need a deep copy, use cv::Mat::clone() method + of the extracted sub-matrices. + +
  • by making a header for user-allocated-data. It can be useful for +
      +
    1. processing "foreign" data using OpenCV (e.g. when you implement + a DirectShow filter or a processing module for gstreamer etc.), e.g. + + \code + void process_video_frame(const unsigned char* pixels, + int width, int height, int step) + { + cv::Mat img(height, width, CV_8UC3, pixels, step); + cv::GaussianBlur(img, img, cv::Size(7,7), 1.5, 1.5); + } + \endcode + +
    2. for quick initialization of small matrices and/or super-fast element access + + \code + double m[3][3] = {{a, b, c}, {d, e, f}, {g, h, i}}; + cv::Mat M = cv::Mat(3, 3, CV_64F, m).inv(); + \endcode +
    + + partial yet very common cases of this "user-allocated data" case are conversions + from CvMat and IplImage to cv::Mat. For this purpose there are special constructors + taking pointers to CvMat or IplImage and the optional + flag indicating whether to copy the data or not. + + Backward conversion from cv::Mat to CvMat or IplImage is provided via cast operators + cv::Mat::operator CvMat() an cv::Mat::operator IplImage(). + The operators do not copy the data. + + + \code + IplImage* img = cvLoadImage("greatwave.jpg", 1); + Mat mtx(img); // convert IplImage* -> cv::Mat + CvMat oldmat = mtx; // convert cv::Mat -> CvMat + CV_Assert(oldmat.cols == img->width && oldmat.rows == img->height && + oldmat.data.ptr == (uchar*)img->imageData && oldmat.step == img->widthStep); + \endcode + +
  • by using MATLAB-style matrix initializers, cv::Mat::zeros(), cv::Mat::ones(), cv::Mat::eye(), e.g.: + + \code + // create a double-precision identity martix and add it to M. + M += Mat::eye(M.rows, M.cols, CV_64F); + \endcode + +
  • by using comma-separated initializer: + + \code + // create 3x3 double-precision identity matrix + Mat M = (Mat_(3,3) << 1, 0, 0, 0, 1, 0, 0, 0, 1); + \endcode + + here we first call constructor of cv::Mat_ class (that we describe further) with the proper matrix, + and then we just put "<<" operator followed by comma-separated values that can be constants, + variables, expressions etc. Also, note the extra parentheses that are needed to avoid compiler errors. + +
+ + Once matrix is created, it will be automatically managed by using reference-counting mechanism + (unless the matrix header is built on top of user-allocated data, + in which case you should handle the data by yourself). + The matrix data will be deallocated when no one points to it; + if you want to release the data pointed by a matrix header before the matrix destructor is called, + use cv::Mat::release(). + + The next important thing to learn about the matrix class is element access. Here is how the matrix is stored. + The elements are stored in row-major order (row by row). The cv::Mat::data member points to the first element of the first row, + cv::Mat::rows contains the number of matrix rows and cv::Mat::cols - the number of matrix columns. There is yet another member, + cv::Mat::step that is used to actually compute address of a matrix element. cv::Mat::step is needed because the matrix can be + a part of another matrix or because there can some padding space in the end of each row for a proper alignment. + + \image html roi.png + + Given these parameters, address of the matrix element M_{ij} is computed as following: + + addr(M_{ij})=M.data + M.step*i + j*M.elemSize() + + if you know the matrix element type, e.g. it is float, then you can use cv::Mat::at() method: + + addr(M_{ij})=&M.at(i,j) + + (where & is used to convert the reference returned by cv::Mat::at() to a pointer). + if you need to process a whole row of matrix, the most efficient way is to get the pointer to the row first, and then just use plain C operator \texttt{[]}: + + \code + // compute sum of positive matrix elements + // (assuming that M is double-precision matrix) + double sum=0; + for(int i = 0; i < M.rows; i++) + { + const double* Mi = M.ptr(i); + for(int j = 0; j < M.cols; j++) + sum += std::max(Mi[j], 0.); + } + \endcode + + Some operations, like the above one, do not actually depend on the matrix shape, + they just process elements of a matrix one by one (or elements from multiple matrices + that are sitting in the same place, e.g. matrix addition). Such operations are called + element-wise and it makes sense to check whether all the input/output matrices are continuous, + i.e. have no gaps in the end of each row, and if yes, process them as a single long row: + + \code + // compute sum of positive matrix elements, optimized variant + double sum=0; + int cols = M.cols, rows = M.rows; + if(M.isContinuous()) + { + cols *= rows; + rows = 1; + } + for(int i = 0; i < rows; i++) + { + const double* Mi = M.ptr(i); + for(int j = 0; j < cols; j++) + sum += std::max(Mi[j], 0.); + } + \endcode + in the case of continuous matrix the outer loop body will be executed just once, + so the overhead will be smaller, which will be especially noticeable in the case of small matrices. + + Finally, there are STL-style iterators that are smart enough to skip gaps between successive rows: + \code + // compute sum of positive matrix elements, iterator-based variant + double sum=0; + MatConstIterator_ it = M.begin(), it_end = M.end(); + for(; it != it_end; ++it) + sum += std::max(*it, 0.); + \endcode + + The matrix iterators are random-access iterators, so they can be passed to any STL algorithm, including \texttt{std::sort()}. +*/ class CV_EXPORTS Mat { public: - // constructors + //! default constructor Mat(); - // constructs matrix of the specified size and type + //! constructs matrix of the specified size and type // (_type is CV_8UC1, CV_64FC3, CV_32SC(12) etc.) Mat(int _rows, int _cols, int _type); Mat(Size _size, int _type); - // constucts matrix and fills it with the specified value _s. + //! constucts matrix and fills it with the specified value _s. Mat(int _rows, int _cols, int _type, const Scalar& _s); Mat(Size _size, int _type, const Scalar& _s); - // copy constructor + //! copy constructor Mat(const Mat& m); - // constructor for matrix headers pointing to user-allocated data + //! constructor for matrix headers pointing to user-allocated data Mat(int _rows, int _cols, int _type, void* _data, size_t _step=AUTO_STEP); Mat(Size _size, int _type, void* _data, size_t _step=AUTO_STEP); - // creates a matrix header for a part of the bigger matrix + //! creates a matrix header for a part of the bigger matrix Mat(const Mat& m, const Range& rowRange, const Range& colRange); Mat(const Mat& m, const Rect& roi); - // converts old-style CvMat to the new matrix; the data is not copied by default + //! converts old-style CvMat to the new matrix; the data is not copied by default Mat(const CvMat* m, bool copyData=false); - // converts old-style IplImage to the new matrix; the data is not copied by default + //! converts old-style IplImage to the new matrix; the data is not copied by default Mat(const IplImage* img, bool copyData=false); - // builds matrix from std::vector with or without copying the data + //! builds matrix from std::vector with or without copying the data template explicit Mat(const vector<_Tp>& vec, bool copyData=false); - // builds matrix from cv::Vec; the data is copied + //! builds matrix from cv::Vec; the data is copied template explicit Mat(const Vec<_Tp, n>& vec); - // builds matrix from a 2D point + //! builds matrix from a 2D point template explicit Mat(const Point_<_Tp>& pt); - // builds matrix from a 3D point + //! builds matrix from a 3D point template explicit Mat(const Point3_<_Tp>& pt); - // helper constructor to compile matrix expressions + //! helper constructor to compile matrix expressions Mat(const MatExpr_Base& expr); - // destructor - calls release() + //! destructor - calls release() ~Mat(); - // assignment operators + //! assignment operators Mat& operator = (const Mat& m); Mat& operator = (const MatExpr_Base& expr); operator MatExpr_() const; - // returns a new matrix header for the specified row + //! returns a new matrix header for the specified row Mat row(int y) const; - // returns a new matrix header for the specified column + //! returns a new matrix header for the specified column Mat col(int x) const; - // ... for the specified row span + //! ... for the specified row span Mat rowRange(int startrow, int endrow) const; Mat rowRange(const Range& r) const; - // ... for the specified column span + //! ... for the specified column span Mat colRange(int startcol, int endcol) const; Mat colRange(const Range& r) const; - // ... for the specified diagonal + //! ... for the specified diagonal // (d=0 - the main diagonal, // >0 - a diagonal from the lower half, // <0 - a diagonal from the upper half) Mat diag(int d=0) const; - // constructs a square diagonal matrix which main diagonal is vector "d" + //! constructs a square diagonal matrix which main diagonal is vector "d" static Mat diag(const Mat& d); - // returns deep copy of the matrix, i.e. the data is copied + //! returns deep copy of the matrix, i.e. the data is copied Mat clone() const; - // copies the matrix content to "m". + //! copies the matrix content to "m". // It calls m.create(this->size(), this->type()). void copyTo( Mat& m ) const; - // copies those matrix elements to "m" that are marked with non-zero mask elements. + //! copies those matrix elements to "m" that are marked with non-zero mask elements. void copyTo( Mat& m, const Mat& mask ) const; - // converts matrix to another datatype with optional scalng. See cvConvertScale. + //! converts matrix to another datatype with optional scalng. See cvConvertScale. void convertTo( Mat& m, int rtype, double alpha=1, double beta=0 ) const; void assignTo( Mat& m, int type=-1 ) const; - // sets every matrix element to s + //! sets every matrix element to s Mat& operator = (const Scalar& s); - // sets some of the matrix elements to s, according to the mask + //! sets some of the matrix elements to s, according to the mask Mat& setTo(const Scalar& s, const Mat& mask=Mat()); - // creates alternative matrix header for the same data, with different + //! creates alternative matrix header for the same data, with different // number of channels and/or different number of rows. see cvReshape. Mat reshape(int _cn, int _rows=0) const; - // matrix transposition by means of matrix expressions + //! matrix transposition by means of matrix expressions MatExpr_ >, Mat> t() const; - // matrix inversion by means of matrix expressions + //! matrix inversion by means of matrix expressions MatExpr_ >, Mat> inv(int method=DECOMP_LU) const; MatExpr_ >, Mat> - // per-element matrix multiplication by means of matrix expressions + //! per-element matrix multiplication by means of matrix expressions mul(const Mat& m, double scale=1) const; MatExpr_ >, Mat> mul(const MatExpr_ >, Mat>& m, double scale=1) const; MatExpr_ >, Mat> mul(const MatExpr_ >, Mat>& m, double scale=1) const; - // computes cross-product of 2 3D vectors + //! computes cross-product of 2 3D vectors Mat cross(const Mat& m) const; - // computes dot-product + //! computes dot-product double dot(const Mat& m) const; - // Matlab-style matrix initialization + //! Matlab-style matrix initialization static MatExpr_Initializer zeros(int rows, int cols, int type); static MatExpr_Initializer zeros(Size size, int type); static MatExpr_Initializer ones(int rows, int cols, int type); @@ -849,62 +1414,62 @@ public: static MatExpr_Initializer eye(int rows, int cols, int type); static MatExpr_Initializer eye(Size size, int type); - // allocates new matrix data unless the matrix already has specified size and type. + //! allocates new matrix data unless the matrix already has specified size and type. // previous data is unreferenced if needed. void create(int _rows, int _cols, int _type); void create(Size _size, int _type); - // increases the reference counter; use with care to avoid memleaks + //! increases the reference counter; use with care to avoid memleaks void addref(); - // decreases reference counter; + //! decreases reference counter; // deallocate the data when reference counter reaches 0. void release(); - // locates matrix header within a parent matrix. See below + //! locates matrix header within a parent matrix. See below void locateROI( Size& wholeSize, Point& ofs ) const; - // moves/resizes the current matrix ROI inside the parent matrix. + //! moves/resizes the current matrix ROI inside the parent matrix. Mat& adjustROI( int dtop, int dbottom, int dleft, int dright ); - // extracts a rectangular sub-matrix + //! extracts a rectangular sub-matrix // (this is a generalized form of row, rowRange etc.) Mat operator()( Range rowRange, Range colRange ) const; Mat operator()( const Rect& roi ) const; - // converts header to CvMat; no data is copied + //! converts header to CvMat; no data is copied operator CvMat() const; - // converts header to IplImage; no data is copied + //! converts header to IplImage; no data is copied operator IplImage() const; - // returns true iff the matrix data is continuous + //! returns true iff the matrix data is continuous // (i.e. when there are no gaps between successive rows). // similar to CV_IS_MAT_CONT(cvmat->type) bool isContinuous() const; - // returns element size in bytes, + //! returns element size in bytes, // similar to CV_ELEM_SIZE(cvmat->type) size_t elemSize() const; - // returns the size of element channel in bytes. + //! returns the size of element channel in bytes. size_t elemSize1() const; - // returns element type, similar to CV_MAT_TYPE(cvmat->type) + //! returns element type, similar to CV_MAT_TYPE(cvmat->type) int type() const; - // returns element type, similar to CV_MAT_DEPTH(cvmat->type) + //! returns element type, similar to CV_MAT_DEPTH(cvmat->type) int depth() const; - // returns element type, similar to CV_MAT_CN(cvmat->type) + //! returns element type, similar to CV_MAT_CN(cvmat->type) int channels() const; - // returns step/elemSize1() + //! returns step/elemSize1() size_t step1() const; - // returns matrix size: + //! returns matrix size: // width == number of columns, height == number of rows Size size() const; - // returns true if matrix data is NULL + //! returns true if matrix data is NULL bool empty() const; - // returns pointer to y-th row + //! returns pointer to y-th row uchar* ptr(int y=0); const uchar* ptr(int y=0) const; - // template version of the above method + //! template version of the above method template _Tp* ptr(int y=0); template const _Tp* ptr(int y=0) const; - // template methods for read-write or read-only element access. + //! template methods for read-write or read-only element access. // note that _Tp must match the actual matrix type - // the functions do not do any on-fly type conversion template _Tp& at(int y, int x); @@ -914,7 +1479,7 @@ public: template _Tp& at(int i); template const _Tp& at(int i) const; - // template methods for iteration over matrix elements. + //! template methods for iteration over matrix elements. // the iterators take care of skipping gaps in the end of rows (if any) template MatIterator_<_Tp> begin(); template MatIterator_<_Tp> end(); @@ -923,30 +1488,35 @@ public: enum { MAGIC_VAL=0x42FF0000, AUTO_STEP=0, CONTINUOUS_FLAG=CV_MAT_CONT_FLAG }; - // includes several bit-fields: - // * the magic signature - // * continuity flag - // * depth - // * number of channels + /*! includes several bit-fields: + - the magic signature + - continuity flag + - depth + - number of channels + */ int flags; - // the number of rows and columns + //! the number of rows and columns int rows, cols; - // a distance between successive rows in bytes; includes the gap if any + //! a distance between successive rows in bytes; includes the gap if any size_t step; - // pointer to the data + //! pointer to the data uchar* data; - // pointer to the reference counter; + //! pointer to the reference counter; // when matrix points to user-allocated data, the pointer is NULL int* refcount; - // helper fields used in locateROI and adjustROI + //! helper fields used in locateROI and adjustROI uchar* datastart; uchar* dataend; }; -// Multiply-with-Carry RNG +/*! + Random Number Generator + + The class implements RNG using Multiply-with-Carry algorithm +*/ class CV_EXPORTS RNG { public: @@ -954,6 +1524,7 @@ public: RNG(); RNG(uint64 _state); + //! updates the state and returns the next 32-bit unsigned integer random number unsigned next(); operator uchar(); @@ -961,18 +1532,21 @@ public: operator ushort(); operator short(); operator unsigned(); - //! Returns a random integer sampled uniformly from [0, N). + //! returns a random integer sampled uniformly from [0, N). unsigned operator()(unsigned N); unsigned operator ()(); operator int(); operator float(); operator double(); + //! returns uniformly distributed integer random number from [a,b) range int uniform(int a, int b); + //! returns uniformly distributed floating-point random number from [a,b) range float uniform(float a, float b); + //! returns uniformly distributed double-precision floating-point random number from [a,b) range double uniform(double a, double b); void fill( Mat& mat, int distType, const Scalar& a, const Scalar& b ); void fill( MatND& mat, int distType, const Scalar& a, const Scalar& b ); - //! Returns Gaussian random variate with mean zero. + //! returns Gaussian random variate with mean zero. double gaussian(double sigma); uint64 state; @@ -993,54 +1567,88 @@ public: double epsilon; }; +//! converts array (CvMat or IplImage) to cv::Mat CV_EXPORTS Mat cvarrToMat(const CvArr* arr, bool copyData, bool allowND, int coiMode); +//! extracts Channel of Interest from CvMat or IplImage and makes cv::Mat out of it. CV_EXPORTS void extractImageCOI(const CvArr* arr, Mat& coiimg, int coi=-1); +//! inserts single-channel cv::Mat into a multi-channel CvMat or IplImage CV_EXPORTS void insertImageCOI(const Mat& coiimg, CvArr* arr, int coi=-1); +//! adds one matrix to another (c = a + b) CV_EXPORTS void add(const Mat& a, const Mat& b, Mat& c, const Mat& mask); +//! subtracts one matrix from another (c = a - b) CV_EXPORTS void subtract(const Mat& a, const Mat& b, Mat& c, const Mat& mask); +//! adds one matrix to another (c = a + b) CV_EXPORTS void add(const Mat& a, const Mat& b, Mat& c); +//! subtracts one matrix from another (c = a - b) CV_EXPORTS void subtract(const Mat& a, const Mat& b, Mat& c); +//! adds scalar to a matrix (c = a + s) CV_EXPORTS void add(const Mat& a, const Scalar& s, Mat& c, const Mat& mask=Mat()); +//! subtracts scalar from a matrix (c = a - s) CV_EXPORTS void subtract(const Mat& a, const Scalar& s, Mat& c, const Mat& mask=Mat()); +//! subtracts matrix from a scalar matrix (c = s - a) +CV_EXPORTS void subtract(const Scalar& s, const Mat& a, Mat& c, const Mat& mask=Mat()); +//! computes element-wise weighted product of the two arrays (c = scale*a*b) CV_EXPORTS void multiply(const Mat& a, const Mat& b, Mat& c, double scale=1); +//! computes element-wise weighted quotient of the two arrays (c = scale*a/b) CV_EXPORTS void divide(const Mat& a, const Mat& b, Mat& c, double scale=1); +//! computes element-wise weighted reciprocal of an array (c = scale/b) CV_EXPORTS void divide(double scale, const Mat& b, Mat& c); -CV_EXPORTS void subtract(const Scalar& s, const Mat& a, Mat& c, const Mat& mask=Mat()); +//! adds scaled array to another one (c = a*alpha + b) CV_EXPORTS void scaleAdd(const Mat& a, double alpha, const Mat& b, Mat& c); +//! computes weighted sum of two arrays (c=alpha*a + beta*b + gamma) CV_EXPORTS void addWeighted(const Mat& a, double alpha, const Mat& b, double beta, double gamma, Mat& c); +//! scales array elements, computes absolute values and converts the results to 8-bit unsigned integers: c(i)=saturate_castabs(a(i)*alpha+beta) CV_EXPORTS void convertScaleAbs(const Mat& a, Mat& c, double alpha=1, double beta=0); +//! transforms 8-bit unsigned integers using lookup table: b(i)=lut(a(i)) CV_EXPORTS void LUT(const Mat& a, const Mat& lut, Mat& b); +//! computes sum of array elements CV_EXPORTS Scalar sum(const Mat& m); +//! computes the number of nonzero array elements CV_EXPORTS int countNonZero( const Mat& m ); +//! computes mean value of array elements CV_EXPORTS Scalar mean(const Mat& m); +//! computes mean value of selected array elements CV_EXPORTS Scalar mean(const Mat& m, const Mat& mask); +//! computes mean value and standard deviation of all or selected array elements CV_EXPORTS void meanStdDev(const Mat& m, Scalar& mean, Scalar& stddev, const Mat& mask=Mat()); +//! computes norm of array elements CV_EXPORTS double norm(const Mat& a, int normType=NORM_L2); +//! computes norm of the difference between two arrays CV_EXPORTS double norm(const Mat& a, const Mat& b, int normType=NORM_L2); +//! computes norm of selected array elements CV_EXPORTS double norm(const Mat& a, int normType, const Mat& mask); +//! computes norm of selected part of the difference between two arrays CV_EXPORTS double norm(const Mat& a, const Mat& b, int normType, const Mat& mask); +//! scales and shifts array elements so that either the specified norm (alpha) or the minimum (alpha) and maximum (beta) array values get the specified values CV_EXPORTS void normalize( const Mat& a, Mat& b, double alpha=1, double beta=0, int norm_type=NORM_L2, int rtype=-1, const Mat& mask=Mat()); +//! computes global minimum and maximum array elements and their locations CV_EXPORTS void minMaxLoc(const Mat& a, double* minVal, double* maxVal=0, Point* minLoc=0, Point* maxLoc=0, const Mat& mask=Mat()); +//! transforms 2D matrix to 1D row or column vector by taking sum, minimum, maximum or mean value over all the rows CV_EXPORTS void reduce(const Mat& m, Mat& dst, int dim, int rtype, int dtype=-1); +//! makes multi-channel array out of several single channel arrays CV_EXPORTS void merge(const Mat* mv, size_t count, Mat& dst); +//! copies each plane of a multi-channel array to a dedicated array CV_EXPORTS void split(const Mat& m, Mat* mvbegin); +//! copies selected channels from the input arrays to the selected channels of the output arrays CV_EXPORTS void mixChannels(const Mat* src, int nsrcs, Mat* dst, int ndsts, const int* fromTo, size_t npairs); +//! reverses the order of the rows, columns or both in a matrix CV_EXPORTS void flip(const Mat& a, Mat& b, int flipCode); +//! replicates the input matrix the specified number of times in the horizontal and/or vertical direction CV_EXPORTS void repeat(const Mat& a, int ny, int nx, Mat& b); static inline Mat repeat(const Mat& src, int ny, int nx) { @@ -1048,26 +1656,44 @@ static inline Mat repeat(const Mat& src, int ny, int nx) Mat dst; repeat(src, ny, nx, dst); return dst; } +//! computes bitwise conjunction of the two arrays (c = a & b) CV_EXPORTS void bitwise_and(const Mat& a, const Mat& b, Mat& c, const Mat& mask=Mat()); +//! computes bitwise disjunction of the two arrays (c = a | b) CV_EXPORTS void bitwise_or(const Mat& a, const Mat& b, Mat& c, const Mat& mask=Mat()); +//! computes bitwise exclusive-or of the two arrays (c = a ^ b) CV_EXPORTS void bitwise_xor(const Mat& a, const Mat& b, Mat& c, const Mat& mask=Mat()); +//! computes bitwise conjunction of an array and scalar (c = a & s) CV_EXPORTS void bitwise_and(const Mat& a, const Scalar& s, Mat& c, const Mat& mask=Mat()); +//! computes bitwise disjunction of an array and scalar (c = a | s) CV_EXPORTS void bitwise_or(const Mat& a, const Scalar& s, Mat& c, const Mat& mask=Mat()); +//! computes bitwise exclusive-or of an array and scalar (c = a ^ s) CV_EXPORTS void bitwise_xor(const Mat& a, const Scalar& s, Mat& c, const Mat& mask=Mat()); +//! inverts each bit of a (c = ~a) CV_EXPORTS void bitwise_not(const Mat& a, Mat& c); +//! computes element-wise absolute difference of two arrays (c = abs(a - b)) CV_EXPORTS void absdiff(const Mat& a, const Mat& b, Mat& c); +//! computes element-wise absolute difference of array and a scalar (c = abs(a - s)) CV_EXPORTS void absdiff(const Mat& a, const Scalar& s, Mat& c); +//! set mask elements for those array elements which are within the element-specific bounding box (dst = lowerb <= src && src < upperb) CV_EXPORTS void inRange(const Mat& src, const Mat& lowerb, const Mat& upperb, Mat& dst); +//! set mask elements for those array elements which are within the fixed bounding box (dst = lowerb <= src && src < upperb) CV_EXPORTS void inRange(const Mat& src, const Scalar& lowerb, const Scalar& upperb, Mat& dst); +//! compares elements of two arrays (c = a b) CV_EXPORTS void compare(const Mat& a, const Mat& b, Mat& c, int cmpop); +//! compares elements of array with a scalar (c = a s) CV_EXPORTS void compare(const Mat& a, double s, Mat& c, int cmpop); +//! computes per-element minimum of two arrays (c = min(a, b)) CV_EXPORTS void min(const Mat& a, const Mat& b, Mat& c); +//! computes per-element minimum of array and a scalar (c = min(a, alpha)) CV_EXPORTS void min(const Mat& a, double alpha, Mat& c); +//! computes per-element maximum of two arrays (c = max(a, b)) CV_EXPORTS void max(const Mat& a, const Mat& b, Mat& c); +//! computes per-element maximum of array and a scalar (c = max(a, alpha)) CV_EXPORTS void max(const Mat& a, double alpha, Mat& c); + CV_EXPORTS void sqrt(const Mat& a, Mat& b); CV_EXPORTS void pow(const Mat& a, double power, Mat& b); CV_EXPORTS void exp(const Mat& a, Mat& b); @@ -1260,25 +1886,25 @@ public: typedef MatConstIterator_<_Tp> const_iterator; Mat_(); - // equivalent to Mat(_rows, _cols, DataType<_Tp>::type) + //! equivalent to Mat(_rows, _cols, DataType<_Tp>::type) Mat_(int _rows, int _cols); - // other forms of the above constructor + //! other forms of the above constructor Mat_(int _rows, int _cols, const _Tp& value); explicit Mat_(Size _size); Mat_(Size _size, const _Tp& value); - // copy/conversion contructor. If m is of different type, it's converted + //! copy/conversion contructor. If m is of different type, it's converted Mat_(const Mat& m); - // copy constructor + //! copy constructor Mat_(const Mat_& m); - // construct a matrix on top of user-allocated data. + //! construct a matrix on top of user-allocated data. // step is in bytes(!!!), regardless of the type Mat_(int _rows, int _cols, _Tp* _data, size_t _step=AUTO_STEP); // minor selection Mat_(const Mat_& m, const Range& rowRange, const Range& colRange); Mat_(const Mat_& m, const Rect& roi); - // to support complex matrix expressions + //! to support complex matrix expressions Mat_(const MatExpr_Base& expr); - // makes a matrix out of Vec, std::vector, Point_ or Point3_. The matrix will have a single column + //! makes a matrix out of Vec, std::vector, Point_ or Point3_. The matrix will have a single column explicit Mat_(const vector<_Tp>& vec, bool copyData=false); template explicit Mat_(const Vec<_Tp, n>& vec); explicit Mat_(const Point_<_Tp>& pt); @@ -1286,31 +1912,31 @@ public: Mat_& operator = (const Mat& m); Mat_& operator = (const Mat_& m); - // set all the elements to s. + //! set all the elements to s. Mat_& operator = (const _Tp& s); - // iterators; they are smart enough to skip gaps in the end of rows + //! iterators; they are smart enough to skip gaps in the end of rows iterator begin(); iterator end(); const_iterator begin() const; const_iterator end() const; - // equivalent to Mat::create(_rows, _cols, DataType<_Tp>::type) + //! equivalent to Mat::create(_rows, _cols, DataType<_Tp>::type) void create(int _rows, int _cols); void create(Size _size); - // cross-product + //! cross-product Mat_ cross(const Mat_& m) const; - // to support complex matrix expressions + //! to support complex matrix expressions Mat_& operator = (const MatExpr_Base& expr); - // data type conversion + //! data type conversion template operator Mat_() const; - // overridden forms of Mat::row() etc. + //! overridden forms of Mat::row() etc. Mat_ row(int y) const; Mat_ col(int x) const; Mat_ diag(int d=0) const; Mat_ clone() const; - // transposition, inversion, per-element multiplication + //! transposition, inversion, per-element multiplication MatExpr_ >, Mat> t() const; MatExpr_ >, Mat> inv(int method=DECOMP_LU) const;