propagated some more fixes from 2.3 branch to the trunk
authorVadim Pisarevsky <no@email>
Wed, 29 Jun 2011 22:06:42 +0000 (22:06 +0000)
committerVadim Pisarevsky <no@email>
Wed, 29 Jun 2011 22:06:42 +0000 (22:06 +0000)
54 files changed:
modules/calib3d/doc/camera_calibration_and_3d_reconstruction.rst
modules/core/doc/basic_structures.rst
modules/core/doc/clustering.rst
modules/core/doc/core.rst
modules/core/doc/drawing_functions.rst
modules/core/doc/dynamic_structures.rst [new file with mode: 0644]
modules/core/doc/old_basic_structures.rst [new file with mode: 0644]
modules/core/doc/old_xml_yaml_persistence.rst [new file with mode: 0644]
modules/core/doc/operations_on_arrays.rst
modules/core/doc/pics/memstorage1.png [new file with mode: 0644]
modules/core/doc/pics/memstorage2.png [new file with mode: 0644]
modules/core/doc/utility_and_system_functions_and_macros.rst
modules/core/doc/xml_yaml_persistence.rst
modules/core/src/arithm.cpp
modules/core/src/matrix.cpp
modules/features2d/doc/common_interfaces_of_descriptor_extractors.rst
modules/features2d/doc/common_interfaces_of_descriptor_matchers.rst
modules/features2d/doc/common_interfaces_of_feature_detectors.rst
modules/features2d/doc/common_interfaces_of_generic_descriptor_matchers.rst
modules/features2d/doc/drawing_function_of_keypoints_and_matches.rst
modules/features2d/doc/feature_detection_and_description.rst
modules/features2d/doc/object_categorization.rst
modules/features2d/src/orb.cpp
modules/gpu/doc/camera_calibration_and_3d_reconstruction.rst
modules/gpu/doc/object_detection.rst
modules/highgui/doc/qt_new_functions.rst
modules/highgui/doc/reading_and_writing_images_and_video.rst
modules/highgui/doc/user_interface.rst
modules/imgproc/doc/feature_detection.rst
modules/imgproc/doc/filtering.rst
modules/imgproc/doc/geometric_transformations.rst
modules/imgproc/doc/histograms.rst
modules/imgproc/doc/imgproc.rst
modules/imgproc/doc/miscellaneous_transformations.rst
modules/imgproc/doc/motion_analysis_and_object_tracking.rst
modules/imgproc/doc/object_detection.rst
modules/imgproc/doc/structural_analysis_and_shape_descriptors.rst
modules/ml/doc/boosting.rst
modules/ml/doc/decision_trees.rst
modules/ml/doc/expectation_maximization.rst
modules/ml/doc/gradient_boosted_trees.rst
modules/ml/doc/k_nearest_neighbors.rst
modules/ml/doc/mldata.rst
modules/ml/doc/neural_networks.rst
modules/ml/doc/normal_bayes_classifier.rst
modules/ml/doc/random_trees.rst
modules/ml/doc/statistical_models.rst
modules/ml/doc/support_vector_machines.rst
modules/objdetect/doc/cascade_classification.rst
modules/objdetect/doc/pics/haarfeatures.png [new file with mode: 0644]
modules/python/src2/gen2.py
modules/refman.rst
modules/video/doc/motion_analysis_and_object_tracking.rst
modules/video/src/lkpyramid.cpp

index a0667ae..5b67ec6 100644 (file)
@@ -1,6 +1,8 @@
 Camera Calibration and 3D Reconstruction
 ========================================
 
+.. highlight:: cpp
+
 The functions in this section use a so-called pinhole camera model. In this model, a scene view is formed by projecting 3D points into the image plane
 using a perspective transformation.
 
@@ -105,14 +107,25 @@ The functions below use the above model to do the following:
 
 calibrateCamera
 ---------------
+Finds the camera intrinsic and extrinsic parameters from several views of a calibration pattern.
 
 .. ocv:function:: double calibrateCamera( InputArrayOfArrays objectPoints, InputArrayOfArrays imagePoints, Size imageSize, InputOutputArray cameraMatrix, InputOutputArray distCoeffs, OutputArrayOfArrays rvecs, OutputArrayOfArrays tvecs, int flags=0 )
 
-    Finds the camera intrinsic and extrinsic parameters from several views of a calibration pattern.
+.. ocv:pyfunction:: cv2.calibrateCamera(objectPoints, imagePoints, imageSize, cameraMatrix, distCoeffs[, rvecs[, tvecs[, flags]]]) -> retval, cameraMatrix, distCoeffs, rvecs, tvecs
+
+.. ocv:cfunction:: double cvCalibrateCamera2( const CvMat* objectPoints, const CvMat* imagePoints, const CvMat* pointCounts, CvSize imageSize, CvMat* cameraMatrix, CvMat* distCoeffs, CvMat* rvecs=NULL, CvMat* tvecs=NULL, int flags=0 )
 
-    :param objectPoints: Vector of vectors of calibration pattern points in the calibration pattern coordinate space. The outer vector contains as many elements as the number of the pattern views. If the same calibration pattern is shown in each view and it is fully visible, all the vectors will be the same. Although, it is possible to use partially occluded patterns, or even different patterns in different views. Then, the vectors will be different. The points are 3D, but since they are in a pattern coordinate system, then, if the rig is planar, it may make sense to put the model to a XY coordinate plane so that Z-coordinate of each input object point is 0.
+.. ocv:pyoldfunction:: cv.CalibrateCamera2(objectPoints, imagePoints, pointCounts, imageSize, cameraMatrix, distCoeffs, rvecs, tvecs, flags=0)-> None
 
-    :param imagePoints: Vector of vectors of the projections of calibration pattern points. ``imagePoints.size()`` and ``objectPoints.size()`` and ``imagePoints[i].size()`` must be equal to ``objectPoints[i].size()`` for each ``i``.
+    :param objectPoints: In the new interface it is a vector of vectors of calibration pattern points in the calibration pattern coordinate space. The outer vector contains as many elements as the number of the pattern views. If the same calibration pattern is shown in each view and it is fully visible, all the vectors will be the same. Although, it is possible to use partially occluded patterns, or even different patterns in different views. Then, the vectors will be different. The points are 3D, but since they are in a pattern coordinate system, then, if the rig is planar, it may make sense to put the model to a XY coordinate plane so that Z-coordinate of each input object point is 0.
+    
+        In the old interface all the vectors of object points from different views are concatenated together.
+
+    :param imagePoints: In the new interface it is a vector of vectors of the projections of calibration pattern points. ``imagePoints.size()`` and ``objectPoints.size()`` and ``imagePoints[i].size()`` must be equal to ``objectPoints[i].size()`` for each ``i``.
+    
+        In the old interface all the vectors of object points from different views are concatenated together.
+        
+    :param pointCounts: In the old interface this is a vector of integers, containing as many elements, as the number of views of the calibration pattern. Each element is the number of points in each view. Usually, all the elements are the same and equal to the number of feature points on the calibration pattern.
 
     :param imageSize: Size of the image used only to initialize the intrinsic camera matrix.
 
@@ -120,7 +133,7 @@ calibrateCamera
 
     :param distCoeffs: Output vector of distortion coefficients  :math:`(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6]])`  of 4, 5, or 8 elements.
 
-    :param rvecs: Output  vector of rotation vectors (see  :ref:`Rodrigues` ) estimated for each pattern view. That is, each k-th rotation vector together with the corresponding k-th translation vector (see the next output parameter description) brings the calibration pattern from the model coordinate space (in which object points are specified) to the world coordinate space, that is, a real position of the calibration pattern in the k-th pattern view (k=0.. *M* -1).
+    :param rvecs: Output  vector  of rotation vectors (see  :ocv:func:`Rodrigues` ) estimated for each pattern view. That is, each k-th rotation vector together with the corresponding k-th translation vector (see the next output parameter description) brings the calibration pattern from the model coordinate space (in which object points are specified) to the world coordinate space, that is, a real position of the calibration pattern in the k-th pattern view (k=0.. *M* -1).
 
     :param tvecs: Output vector of translation vectors estimated for each pattern view.
 
@@ -139,8 +152,7 @@ calibrateCamera
         * **CV_CALIB_RATIONAL_MODEL** Coefficients k4, k5, and k6 are enabled. To provide the backward compatibility, this extra flag should be explicitly specified to make the calibration function use the rational model and return 8 coefficients. If the flag is not set, the function computes  and returns  only 5 distortion coefficients.
 
 The function estimates the intrinsic camera
-parameters and extrinsic parameters for each of the views. The
-coordinates of 3D object points and their corresponding 2D projections
+parameters and extrinsic parameters for each of the views. The algorithm is based on [Zhang2000] and [BoughuetMCT]. The coordinates of 3D object points and their corresponding 2D projections
 in each view must be specified. That may be achieved by using an
 object with a known geometry and easily detectable feature points.
 Such an object is called a calibration rig or calibration pattern,
@@ -158,37 +170,32 @@ The algorithm performs the following steps:
 
 #.
     Estimate the initial camera pose as if the intrinsic parameters have been already known. This is done using
-    :ref:`solvePnP` .
+    :ocv:func:`solvePnP` .
 #.
     Run the global Levenberg-Marquardt optimization algorithm to minimize the reprojection error, that is, the total sum of squared distances between the observed feature points ``imagePoints``     and the projected (using the current estimates for camera parameters and the poses) object points ``objectPoints``. See :ref:`projectPoints` for details.
 
 The function returns the final re-projection error.
 
-**Note:**
+.. note::
 
-If you use a non-square (=non-NxN) grid and
-:ref:`findChessboardCorners` for calibration, and ``calibrateCamera`` returns
-bad values (zero distortion coefficients, an image center very far from
-:math:`(w/2-0.5,h/2-0.5)` , and/or large differences between
-:math:`f_x` and
-:math:`f_y` (ratios of
-10:1 or more)), then you have probably used ``patternSize=cvSize(rows,cols)`` instead of using ``patternSize=cvSize(cols,rows)`` in
-:ref:`FindChessboardCorners` .
+    If you use a non-square (=non-NxN) grid and        :ocv:func:`findChessboardCorners` for calibration, and ``calibrateCamera`` returns bad values (zero distortion coefficients, an image center very far from ``(w/2-0.5,h/2-0.5)``, and/or large differences between :math:`f_x` and :math:`f_y` (ratios of 10:1 or more)), then you have probably used ``patternSize=cvSize(rows,cols)`` instead of using ``patternSize=cvSize(cols,rows)`` in :ocv:func:`findChessboardCorners` .
 
-See Also:
-:ref:`FindChessboardCorners`,
-:ref:`solvePnP`,
-:ref:`initCameraMatrix2D`, 
-:ref:`stereoCalibrate`,
-:ref:`undistort`
+.. seealso::
+:ocv:func:`FindChessboardCorners`,
+:ocv:func:`solvePnP`,
+:ocv:func:`initCameraMatrix2D`, 
+:ocv:func:`stereoCalibrate`,
+:ocv:func:`undistort`
 
 
 
 calibrationMatrixValues
 -----------------------
+Computes useful camera characteristics from the camera matrix.
+
 .. ocv:function:: void calibrationMatrixValues( InputArray cameraMatrix, Size imageSize, double apertureWidth, double apertureHeight, double& fovx, double& fovy, double& focalLength, Point2d& principalPoint, double& aspectRatio )
 
-    Computes useful camera characteristics from the camera matrix.
+.. ocv:pyfunction:: cv2.calibrationMatrixValues(cameraMatrix, imageSize, apertureWidth, apertureHeight) -> fovx, fovy, focalLength, principalPoint, aspectRatio
 
     :param cameraMatrix: Input camera matrix that can be estimated by  :ref:`calibrateCamera`  or  :ref:`stereoCalibrate` .
     
@@ -214,18 +221,19 @@ The function computes various useful camera characteristics from the previously
 
 composeRT
 -------------
+Combines two rotation-and-shift transformations.
 
 .. ocv:function:: void composeRT( InputArray rvec1, InputArray tvec1, InputArray rvec2, InputArray tvec2, OutputArray rvec3, OutputArray tvec3, OutputArray dr3dr1=noArray(), OutputArray dr3dt1=noArray(), OutputArray dr3dr2=noArray(), OutputArray dr3dt2=noArray(), OutputArray dt3dr1=noArray(), OutputArray dt3dt1=noArray(), OutputArray dt3dr2=noArray(), OutputArray dt3dt2=noArray() )
 
-    Combines two rotation-and-shift transformations.
+.. ocv:pyfunction:: cv2.composeRT(rvec1, tvec1, rvec2, tvec2[, rvec3[, tvec3[, dr3dr1[, dr3dt1[, dr3dr2[, dr3dt2[, dt3dr1[, dt3dt1[, dt3dr2[, dt3dt2]]]]]]]]]]) -> rvec3, tvec3, dr3dr1, dr3dt1, dr3dr2, dr3dt2, dt3dr1, dt3dt1, dt3dr2, dt3dt2
 
-    :param rvec1: The first rotation vector.
+    :param rvec1: First rotation vector.
 
-    :param tvec1: The first translation vector.
+    :param tvec1: First translation vector.
 
-    :param rvec2: The second rotation vector.
+    :param rvec2: Second rotation vector.
 
-    :param tvec2: The second translation vector.
+    :param tvec2: Second translation vector.
 
     :param rvec3: Output rotation vector of the superposition.
 
@@ -242,22 +250,26 @@ The functions compute:
 where :math:`\mathrm{rodrigues}` denotes a rotation vector to a rotation matrix transformation, and
 :math:`\mathrm{rodrigues}^{-1}` denotes the inverse transformation. See :ref:`Rodrigues` for details.
 
-Also, the functions can compute the derivatives of the output vectors with regards to the input vectors (see :ref:`matMulDeriv` ).
-The functions are used inside :ref:`stereoCalibrate` but can also be used in your own code where Levenberg-Marquardt or another gradient-based solver is used to optimize a function that contains a matrix multiplication.
+Also, the functions can compute the derivatives of the output vectors with regards to the input vectors (see :ocv:func:`matMulDeriv` ).
+The functions are used inside :ocv:func:`stereoCalibrate` but can also be used in your own code where Levenberg-Marquardt or another gradient-based solver is used to optimize a function that contains a matrix multiplication.
 
 
 
 computeCorrespondEpilines
 -----------------------------
+For points in an image of a stereo pair, computes the corresponding epilines in the other image.
+
 .. ocv:function:: void computeCorrespondEpilines( InputArray points, int whichImage, InputArray F, OutputArray lines )
 
-    For points in an image of a stereo pair, computes the corresponding epilines in the other image.
+.. ocv:cfunction:: void cvComputeCorrespondEpilines( const CvMat* points, int whichImage, const CvMat* F, CvMat* lines)
+
+.. ocv:pyoldfunction:: cv.ComputeCorrespondEpilines(points, whichImage, F, lines) -> None
 
     :param points: Input points.  :math:`N \times 1`  or  :math:`1 \times N`  matrix of type  ``CV_32FC2``  or  ``vector<Point2f>`` .
     
     :param whichImage: Index of the image (1 or 2) that contains the  ``points`` .
     
-    :param F: Fundamental matrix that can be estimated using  :ref:`findFundamentalMat`         or  :ref:`StereoRectify` .
+    :param F: Fundamental matrix that can be estimated using  :ocv:func:`findFundamentalMat`         or  :ocv:func:`StereoRectify` .
 
     :param lines: Output vector of the epipolar lines corresponding to the points in the other image. Each line :math:`ax + by + c=0`  is encoded by 3 numbers  :math:`(a, b, c)` .
     
@@ -265,7 +277,7 @@ For every point in one of the two images of a stereo pair, the function finds th
 corresponding epipolar line in the other image.
 
 From the fundamental matrix definition (see
-:ref:`findFundamentalMat` ),
+:ocv:func:`findFundamentalMat` ),
 line
 :math:`l^{(2)}_i` in the second image for the point
 :math:`p^{(1)}_i` in the first image (when ``whichImage=1`` ) is computed as:
@@ -287,13 +299,13 @@ Line coefficients are defined up to a scale. They are normalized so that
 
 
 
-
 convertPointsToHomogeneous
-------------------------
+--------------------------
+Converts points from Euclidean to homogeneous space.
 
 .. ocv:function:: void convertPointsToHomogeneous( InputArray src, OutputArray dst )
 
-    Converts points from Euclidean to homogeneous space.
+.. ocv:pyfunction:: cv2.convertPointsToHomogeneous(src[, dst]) -> dst
 
     :param src: Input vector of ``N``-dimensional points.
 
@@ -304,11 +316,12 @@ The function converts points from Euclidean to homogeneous space by appending 1'
 
 
 convertPointsFromHomogeneous
-------------------------
+----------------------------
+Converts points from homogeneous to Euclidean space.
 
 .. ocv:function:: void convertPointsFromHomogeneous( InputArray src, OutputArray dst )
 
-    Converts points from homogeneous to Euclidean space.
+.. ocv:pyfunction:: cv2.convertPointsFromHomogeneous(src[, dst]) -> dst
 
     :param src: Input vector of ``N``-dimensional points.
 
@@ -320,30 +333,39 @@ The function converts points homogeneous to Euclidean space using perspective pr
 
 convertPointsHomogeneous
 ------------------------
+Converts points to/from homogeneous coordinates.
 
 .. ocv:function:: void convertPointsHomogeneous( InputArray src, OutputArray dst )
 
-    Converts points to/from homogeneous coordinates.
+.. ocv:pyfunction:: cv2.convertPointsHomogeneous(src[, dst]) -> dst
 
-    :param src: Input array or vector of 2D, 3D, or 4D points.
+.. ocv:cfunction:: void cvConvertPointsHomogeneous( const CvMat* src, CvMat* dst )
+.. ocv:pyoldfunction:: cv.ConvertPointsHomogeneous( src, dst ) -> None
 
-    :param dst: Output vector of 2D, 3D or 4D points.
+    :param src: Input array or vector of 2D, 3D, or 4D points.
 
-The function converts 2D or 3D points from/to homogeneous coordinates by calling either :ocv:func:`convertPointsToHomogeneous` or :ocv:func:`convertPointsFromHomogeneous`. The function is obsolete; use one of the previous two instead.
+    :param dst: Output vector of 2D, 3D, or 4D points.
 
+The function converts 2D or 3D points from/to homogeneous coordinates by calling either :ocv:func:`convertPointsToHomogeneous` or :ocv:func:`convertPointsFromHomogeneous`. 
 
+.. note:: The function is obsolete. Use one of the previous two functions instead.
 
-.. _decomposeProjectionMatrix:
 
 decomposeProjectionMatrix
------------------------------
+--------------------------
+Decomposes a projection matrix into a rotation matrix and a camera matrix.
+
 .. ocv:function:: void decomposeProjectionMatrix( InputArray projMatrix, OutputArray cameraMatrix, OutputArray rotMatrix, OutputArray transVect, OutputArray rotMatrixX=noArray(), OutputArray rotMatrixY=noArray(), OutputArray rotMatrixZ=noArray(), OutputArray eulerAngles=noArray() )
 
-    Decomposes a projection matrix into a rotation matrix and a camera matrix.
+.. ocv:pyfunction:: cv2.decomposeProjectionMatrix(projMatrix[, cameraMatrix[, rotMatrix[, transVect[, rotMatrixX[, rotMatrixY[, rotMatrixZ[, eulerAngles]]]]]]]) -> cameraMatrix, rotMatrix, transVect, rotMatrixX, rotMatrixY, rotMatrixZ, eulerAngles
+
+.. ocv:cfunction:: void cvDecomposeProjectionMatrix( const CvMat *projMatrix, CvMat *cameraMatrix, CvMat *rotMatrix, CvMat *transVect, CvMat *rotMatrX=NULL, CvMat *rotMatrY=NULL, CvMat *rotMatrZ=NULL, CvPoint3D64f *eulerAngles=NULL)
+
+.. ocv:pyoldfunction:: cv.DecomposeProjectionMatrix(projMatrix, cameraMatrix, rotMatrix, transVect, rotMatrX=None, rotMatrY=None, rotMatrZ=None) -> eulerAngles
 
     :param projMatrix: 3x4 input projection matrix P.
 
-    :param cameraMatrix: The output 3x3 camera matrix K
+    :param cameraMatrix: Output 3x3 camera matrix K.
 
     :param rotMatrix: Output 3x3 external rotation matrix R.
 
@@ -355,26 +377,31 @@ decomposeProjectionMatrix
 
     :param rotMatrZ: Optional 3x3 rotation matrix around z-axis.
 
-    :param eulerAngles: Optional 3-element vector containing the three Euler angles of rotation.
+    :param eulerAngles: Optional three-element vector containing three Euler angles of rotation.
 
 The function computes a decomposition of a projection matrix into a calibration and a rotation matrix and the position of a camera.
 
-It optionally returns three rotation matrices, one for each axis, and the three Euler angles that could be used in OpenGL.
+It optionally returns three rotation matrices, one for each axis, and three Euler angles that could be used in OpenGL.
 
 The function is based on
-:ref:`RQDecomp3x3` .
+:ocv:func:`RQDecomp3x3` .
 
 
 
 drawChessboardCorners
 -------------------------
+Renders the detected chessboard corners.
+
 .. ocv:function:: void drawChessboardCorners( InputOutputArray image, Size patternSize, InputArray corners, bool patternWasFound )
 
-    Renders the detected chessboard corners.
+.. ocv:pyfunction:: cv2.drawChessboardCorners(image, patternSize, corners, patternWasFound) -> None
+
+.. ocv:cfunction:: void cvDrawChessboardCorners( CvArr* image, CvSize patternSize, CvPoint2D32f* corners, int count, int patternWasFound )
+.. ocv:pyoldfunction:: cv.DrawChessboardCorners(image, patternSize, corners, patternWasFound)-> None
 
     :param image: Destination image. It must be an 8-bit color image.
 
-    :param patternSize: Number of inner corners per a chessboard row and column ``(patternSize = cv::Size(points_per_row,points_per_column))``
+    :param patternSize: Number of inner corners per a chessboard row and column ``(patternSize = cv::Size(points_per_row,points_per_column))``.
 
     :param corners: Array of detected corners, the output of ``findChessboardCorners``.
 
@@ -386,13 +413,18 @@ The function draws individual chessboard corners detected either as red circles
 
 findChessboardCorners
 -------------------------
+Finds the positions of internal corners of the chessboard.
+
 .. ocv:function:: bool findChessboardCorners( InputArray image, Size patternSize, OutputArray corners, int flags=CV_CALIB_CB_ADAPTIVE_THRESH+CV_CALIB_CB_NORMALIZE_IMAGE )
 
-    Finds the positions of internal corners of the chessboard.
+.. ocv:pyfunction:: cv2.findChessboardCorners(image, patternSize[, corners[, flags]]) -> retval, corners
+
+.. ocv:cfunction:: int cvFindChessboardCorners( const void* image, CvSize patternSize, CvPoint2D32f* corners, int* cornerCount=NULL, int flags=CV_CALIB_CB_ADAPTIVE_THRESH )
+.. ocv:pyoldfunction:: cv.FindChessboardCorners(image, patternSize, flags=CV_CALIB_CB_ADAPTIVE_THRESH) -> corners
 
     :param image: Source chessboard view. It must be an 8-bit grayscale or color image.
 
-    :param patternSize: Number of inner corners per a chessboard row and column. ``( patternSize = cvSize(points_per_row,points_per_colum) = cvSize(columns,rows) )``
+    :param patternSize: Number of inner corners per a chessboard row and column ``( patternSize = cvSize(points_per_row,points_per_colum) = cvSize(columns,rows) )``.
 
     :param corners: Output array of detected corners. 
 
@@ -400,9 +432,9 @@ findChessboardCorners
 
             * **CV_CALIB_CB_ADAPTIVE_THRESH** Use adaptive thresholding to convert the image to black and white, rather than a fixed threshold level (computed from the average image brightness).
 
-            * **CV_CALIB_CB_NORMALIZE_IMAGE** Normalize the image gamma with  :ref:`EqualizeHist`  before applying fixed or adaptive thresholding.
+            * **CV_CALIB_CB_NORMALIZE_IMAGE** Normalize the image gamma with  :ocv:func:`EqualizeHist`  before applying fixed or adaptive thresholding.
 
-            * **CV_CALIB_CB_FILTER_QUADS** Use additional criteria (like contour area, perimeter, square-like shape) to filter out false quads that are extracted at the contour retrieval stage.
+            * **CV_CALIB_CB_FILTER_QUADS** Use additional criteria (like contour area, perimeter, square-like shape) to filter out false quads extracted at the contour retrieval stage.
 
             * **CALIB_CB_FAST_CHECK** Run a fast check on the image that looks for chessboard corners, and shortcut the call if none is found. This can drastically speed up the call in the degenerate condition when no chessboard is observed.
 
@@ -412,8 +444,8 @@ locate the internal chessboard corners. The function returns a non-zero
 value if all of the corners are found and they are placed
 in a certain order (row by row, left to right in every row). Otherwise, if the function fails to find all the corners or reorder
 them, it returns 0. For example, a regular chessboard has 8 x 8
-squares and 7 x 7 internal corners, that is, points where the black
-squares touch each other. The detected coordinates are approximate so the function calls :ref:`cornerSubPix` internally to determine their position more accurately.
+squares and 7 x 7 internal corners, that is, points where the black squares touch each other.
+The detected coordinates are approximate, and to determine their positions more accurately, the function calls :ocv:func:`cornerSubPix`.
 You also may use the function :ref:`cornerSubPix` with different parameters if returned coordinates are not accurate enough.
 
 Sample usage of detecting and drawing chessboard corners: ::
@@ -434,17 +466,17 @@ Sample usage of detecting and drawing chessboard corners: ::
 
     drawChessboardCorners(img, patternsize, Mat(corners), patternfound);
 
-**Note:**
-
-The function requires white space (like a square-thick border, the wider the better) around the board to make the detection more robust in various environments. Otherwise, if there is no border and the background is dark, the outer black squares cannot be segmented properly and so the square grouping and ordering algorithm fails.
+.. note:: The function requires white space (like a square-thick border, the wider the better) around the board to make the detection more robust in various environments. Otherwise, if there is no border and the background is dark, the outer black squares cannot be segmented properly and so the square grouping and ordering algorithm fails.
 
 
 
 findCirclesGrid
 -------------------
+Finds the centers in the grid of circles.
+
 .. ocv:function:: bool findCirclesGrid( InputArray image, Size patternSize, OutputArray centers, int flags=CALIB_CB_SYMMETRIC_GRID, const Ptr<FeatureDetector> &blobDetector = new SimpleBlobDetector() )
 
-    Finds the centers in the grid of circles.
+.. ocv:pyfunction:: cv2.findCirclesGridDefault(image, patternSize[, centers[, flags]]) -> centers
 
     :param image: Grid view of source circles. It must be an 8-bit grayscale or color image.
 
@@ -479,17 +511,21 @@ Sample usage of detecting and drawing the centers of circles: ::
 
     drawChessboardCorners(img, patternsize, Mat(centers), patternfound);
 
-**Note:**
-
-The function requires white space (like a square-thick border, the wider the better) around the board to make the detection more robust in various environments.
+.. note:: The function requires white space (like a square-thick border, the wider the better) around the board to make the detection more robust in various environments.
 
 
 
 solvePnP
 ------------
+Finds an object pose from 3D-2D point correspondences.
+
 .. ocv:function:: void solvePnP( InputArray objectPoints, InputArray imagePoints, InputArray cameraMatrix, InputArray distCoeffs, OutputArray rvec, OutputArray tvec, bool useExtrinsicGuess=false )
 
-    Finds an object pose from 3D-2D point correspondences.
+.. ocv:pyfunction:: cv2.solvePnP(objectPoints, imagePoints, cameraMatrix, distCoeffs[, rvec[, tvec[, useExtrinsicGuess]]]) -> rvec, tvec
+
+.. ocv:cfunction:: void cvFindExtrinsicCameraParams2( const CvMat* objectPoints, const CvMat* imagePoints, const CvMat* cameraMatrix, const CvMat* distCoeffs, CvMat* rvec, CvMat* tvec, int useExtrinsicGuess=0)
+
+.. ocv:pyoldfunction:: cv.FindExtrinsicCameraParams2(objectPoints, imagePoints, cameraMatrix, distCoeffs, rvec, tvec, useExtrinsicGuess=0)-> None
 
     :param objectPoints: Array of object points in the object coordinate space, 3xN/Nx3 1-channel or 1xN/Nx1 3-channel, where N is the number of points.  ``vector<Point3f>``  can be also passed here.
 
@@ -499,23 +535,24 @@ solvePnP
        
     :param distCoeffs: Input vector of distortion coefficients  :math:`(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6]])`  of 4, 5, or 8 elements. If the vector is NULL/empty, the zero distortion coefficients are assumed.
 
-    :param rvec: Output rotation vector (see  :ref:`Rodrigues` ) that, together with  ``tvec`` , brings points from the model coordinate system to the camera coordinate system.
+    :param rvec: Output rotation vector (see  :ocv:func:`Rodrigues` ) that, together with  ``tvec`` , brings points from the model coordinate system to the camera coordinate system.
 
     :param tvec: Output translation vector.
 
     :param useExtrinsicGuess: If true (1), the function uses the provided  ``rvec``  and  ``tvec``  values as initial approximations of the rotation and translation vectors, respectively, and further optimizes them.
 
 The function estimates the object pose given a set of object points, their corresponding image projections, as well as the camera matrix and the distortion coefficients. This function finds such a pose that minimizes reprojection error, that is, the sum of squared distances between the observed projections ``imagePoints`` and the projected (using
-:ref:`projectPoints` ) ``objectPoints`` .
+:ocv:func:`projectPoints` ) ``objectPoints`` .
 
 
 
 solvePnPRansac
 ------------------
+Finds an object pose from 3D-2D point correspondences using the RANSAC scheme.
 
 .. ocv:function:: void solvePnPRansac( InputArray objectPoints, InputArray imagePoints, InputArray cameraMatrix, InputArray distCoeffs, OutputArray rvec, OutputArray tvec, bool useExtrinsicGuess=false, int iterationsCount = 100, float reprojectionError = 8.0, int minInliersCount = 100, OutputArray inliers = noArray()  )
 
-    Finds an object pose from 3D-2D point correspondences using the RANSAC scheme.
+.. ocv:pyfunction:: cv2.solvePnPRansac(objectPoints, imagePoints, cameraMatrix, distCoeffs[, rvec[, tvec[, useExtrinsicGuess[, iterationsCount[, reprojectionError[, minInliersCount[, inliers]]]]]]]) -> rvec, tvec, inliers
 
     :param objectPoints: Array of object points in the object coordinate space, 3xN/Nx3 1-channel or 1xN/Nx1 3-channel, where N is the number of points.   ``vector<Point3f>``  can be also passed here.
 
@@ -525,7 +562,7 @@ solvePnPRansac
     
     :param distCoeffs: Input vector of distortion coefficients  :math:`(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6]])`  of 4, 5, or 8 elements. If the vector is NULL/empty, the zero distortion coefficients are assumed.
 
-    :param rvec: Output rotation vector (see  :ref:`Rodrigues` ) that, together with  ``tvec`` , brings points from the model coordinate system to the camera coordinate system.
+    :param rvec: Output rotation vector (see  :ocv:func:`Rodrigues` ) that, together with  ``tvec`` , brings points from the model coordinate system to the camera coordinate system.
 
     :param tvec: Output translation vector.
 
@@ -533,22 +570,27 @@ solvePnPRansac
 
     :param iterationsCount: Number of iterations. 
     
-    :param reprojectionError: The inlier threshold value used by the RANSAC procedure. That is, the parameter value is the maximum allowed distance between the observed and computed point projections to consider it an inlier.
+    :param reprojectionError: Inlier threshold value used by the RANSAC procedure. The parameter value is the maximum allowed distance between the observed and computed point projections to consider it an inlier.
    
-    :param minInliersCount: If the algorithm at some stage finds more inliers than ``minInliersCount`` , it finishs.
+    :param minInliersCount: Number of inliers. If the algorithm at some stage finds more inliers than ``minInliersCount`` , it finishes.
     
     :param inliers: Output vector that contains indices of inliers in ``objectPoints`` and ``imagePoints`` .
 
 The function estimates an object pose given a set of object points, their corresponding image projections, as well as the camera matrix and the distortion coefficients. This function finds such a pose that minimizes reprojection error, that is, the sum of squared distances between the observed projections ``imagePoints`` and the projected (using
-:ref:`projectPoints` ) ``objectPoints``. The use of RANSAC makes the function resistant to outliers.
+:ocv:func:`projectPoints` ) ``objectPoints``. The use of RANSAC makes the function resistant to outliers.
 
 
 
 findFundamentalMat
 ----------------------
+Calculates a fundamental matrix from the corresponding points in two images.
+
 .. ocv:function:: Mat findFundamentalMat( InputArray points1, InputArray points2, int method=FM_RANSAC, double param1=3., double param2=0.99, OutputArray mask=noArray() )
 
-    Calculates a fundamental matrix from the corresponding points in two images.
+.. ocv:pyfunction:: cv2.findFundamentalMat(points1, points2[, method[, param1[, param2[, mask]]]]) -> retval, mask
+
+.. ocv:cfunction:: int cvFindFundamentalMat( const CvMat* points1, const CvMat* points2, CvMat* fundamentalMatrix, int method=CV_FM_RANSAC, double param1=1., double param2=0.99, CvMat* status=NULL)
+.. ocv:pyoldfunction:: cv.FindFundamentalMat(points1, points2, fundamentalMatrix, method=CV_FM_RANSAC, param1=1., param2=0.99, status=None) -> None
 
     :param points1: Array of  ``N``  points from the first image. The point coordinates should be floating-point (single or double precision).
 
@@ -583,9 +625,9 @@ the found fundamental matrix. Normally just one matrix is found. But in case of
 :math:`9 \times 3` matrix that stores all 3 matrices sequentially).
 
 The calculated fundamental matrix may be passed further to
-:ref:`ComputeCorrespondEpilines` that finds the epipolar lines
+:ocv:func:`ComputeCorrespondEpilines` that finds the epipolar lines
 corresponding to the specified points. It can also be passed to
-:ref:`StereoRectifyUncalibrated` to compute the rectification transformation. ::
+:ocv:func:`StereoRectifyUncalibrated` to compute the rectification transformation. ::
 
     // Example. Estimation of fundamental matrix using the RANSAC algorithm
     int point_count = 100;
@@ -606,9 +648,14 @@ corresponding to the specified points. It can also be passed to
 
 findHomography
 ------------------
+Finds a perspective transformation between two planes.
+
 .. ocv:function:: Mat findHomography( InputArray srcPoints, InputArray dstPoints, int method=0, double ransacReprojThreshold=3, OutputArray mask=noArray() )
 
-    Finds a perspective transformation between two planes.
+.. ocv:pyfunction:: cv2.findHomography(srcPoints, dstPoints[, method[, ransacReprojThreshold[, mask]]]) -> retval, mask
+
+.. ocv:cfunction:: void cvFindHomography( const CvMat* srcPoints, const CvMat* dstPoints, CvMat* H int method=0, double ransacReprojThreshold=3, CvMat* status=NULL)
+.. ocv:pyoldfunction:: cv.FindHomography(srcPoints, dstPoints, H, method, ransacReprojThreshold=3.0, status=None)-> None
 
     :param srcPoints: Coordinates of the points in the original plane, a matrix of the type  ``CV_32FC2``  or ``vector<Point2f>`` .
 
@@ -673,23 +720,26 @@ The function is used to find initial intrinsic and extrinsic matrices.
 Homography matrix is determined up to a scale. Thus, it is normalized so that
 :math:`h_{33}=1` .
 
-See Also:
-:ref:`GetAffineTransform`,
-:ref:`GetPerspectiveTransform`,
-:ref:`EstimateRigidMotion`,
-:ref:`WarpPerspective`,
-:ref:`PerspectiveTransform`
+.. seealso::
+:ocv:func:`GetAffineTransform`,
+:ocv:func:`GetPerspectiveTransform`,
+:ocv:func:`EstimateRigidMotion`,
+:ocv:func:`WarpPerspective`,
+:ocv:func:`PerspectiveTransform`
 
 
 estimateAffine3D
 --------------------
+Computes an optimal affine transformation between two 3D point sets.
+
 .. ocv:function:: int estimateAffine3D(InputArray srcpt, InputArray dstpt, OutputArray out,                     OutputArray inliers, double ransacThreshold = 3.0, double confidence = 0.99)
 
-    Computes an optimal affine transformation between two 3D point sets.
+.. ocv:pyfunction:: cv2.estimateAffine3D(_from, _to[, _out[, _inliers[, param1[, param2]]]]) -> retval, _out, _inliers
+.. ocv:pyfunction:: cv2.estimateAffine3D(from, to[, dst[, outliers[, param1[, param2]]]]) -> retval, dst, outliers
 
-    :param srcpt: The first input 3D point set.
+    :param srcpt: First input 3D point set.
 
-    :param dstpt: The second input 3D point set.
+    :param dstpt: Second input 3D point set.
 
     :param out: Output 3D affine transformation matrix  :math:`3 \times 4` .
 
@@ -697,18 +747,40 @@ estimateAffine3D
 
     :param ransacThreshold: Maximum reprojection error in the RANSAC algorithm to consider a point as an inlier.
 
-    :param confidence: The confidence level, between 0 and 1, that the estimated transformation will have. Anything between 0.95 and 0.99 is usually good enough. Too close to 1 values can slow down the estimation too much, lower than 0.8-0.9 confidence values can result in an incorrectly estimated transformation.
+    :param confidence: Confidence level, between 0 and 1, for the estimated transformation. Anything between 0.95 and 0.99 is usually good enough. Values too close to 1 can slow down the estimation significantly. Values lower than 0.8-0.9 can result in an incorrectly estimated transformation.
 
 The function estimates an optimal 3D affine transformation between two 3D point sets using the RANSAC algorithm.
 
 
+filterSpeckles
+--------------
+Filters off small noise blobs (speckles) in the disparity map
+
+.. ocv:function:: void filterSpeckles( InputOutputArray img, double newVal, int maxSpeckleSize, double maxDiff, InputOutputArray buf=noArray() );
 
+.. ocv:pyfunction:: cv2.filterSpeckles(img, newVal, maxSpeckleSize, maxDiff[, buf]) -> None
+
+    :param img: The input 16-bit signed disparity image
+    
+    :param newVal: The disparity value used to paint-off the speckles
+    
+    :param maxSpeckleSize: The maximum speckle size to consider it a speckle. Larger blobs are not affected by the algorithm
+    
+    :param maxDiff: Maximum difference between neighbor disparity pixels to put them into the same blob. Note that since StereoBM, StereoSGBM and may be other algorithms return a fixed-point disparity map, where disparity values are multiplied by 16, this scale factor should be taken into account when specifying this parameter value.
+    
+    :param buf: The optional temporary buffer to avoid memory allocation within the function.
+    
 
 getOptimalNewCameraMatrix
 -----------------------------
+Returns the new camera matrix based on the free scaling parameter.
+
 .. ocv:function:: Mat getOptimalNewCameraMatrix( InputArray cameraMatrix, InputArray distCoeffs, Size imageSize, double alpha, Size newImageSize=Size(), Rect* validPixROI=0)
 
-    Returns the new camera matrix based on the free scaling parameter.
+.. ocv:pyfunction:: cv2.getOptimalNewCameraMatrix(cameraMatrix, distCoeffs, imageSize, alpha[, newImgSize]) -> retval, validPixROI
+
+.. ocv:cfunction:: void cvGetOptimalNewCameraMatrix( const CvMat* cameraMatrix, const CvMat* distCoeffs, CvSize imageSize, double alpha, CvMat* newCameraMatrix, CvSize newImageSize=cvSize(0, 0), CvRect* validPixROI=0 )
+.. ocv:pyoldfunction:: cv.GetOptimalNewCameraMatrix(cameraMatrix, distCoeffs, imageSize, alpha, newCameraMatrix, newImageSize=(0, 0), validPixROI=0) -> None
 
     :param cameraMatrix: Input camera matrix.
 
@@ -722,24 +794,32 @@ getOptimalNewCameraMatrix
 
     :param newImageSize: Image size after rectification. By default,it is set to  ``imageSize`` .
 
-    :param validPixROI: Optional output rectangle that outlines all-good-pixels region in the undistorted image. See  ``roi1, roi2``  description in  :ref:`StereoRectify` .
+    :param validPixROI: Optional output rectangle that outlines all-good-pixels region in the undistorted image. See  ``roi1, roi2``  description in  :ocv:func:`StereoRectify` .
     
 The function computes and returns
 the optimal new camera matrix based on the free scaling parameter. By varying  this parameter, you may retrieve only sensible pixels ``alpha=0`` , keep all the original image pixels if there is valuable information in the corners ``alpha=1`` , or get something in between. When ``alpha>0`` , the undistortion result is likely to have some black pixels corresponding to "virtual" pixels outside of the captured distorted image. The original camera matrix, distortion coefficients, the computed new camera matrix, and ``newImageSize`` should be passed to
-:ref:`InitUndistortRectifyMap` to produce the maps for
-:ref:`Remap` .
+:ocv:func:`initUndistortRectifyMap` to produce the maps for
+:ocv:func:`remap` .
 
 
 
 initCameraMatrix2D
 ----------------------
+Finds an initial camera matrix from 3D-2D point correspondences.
+
 .. ocv:function:: Mat initCameraMatrix2D( InputArrayOfArrays objectPoints, InputArrayOfArrays imagePoints, Size imageSize, double aspectRatio=1.)
 
-    Finds an initial camera matrix from 3D-2D point correspondences.
+.. ocv:pyfunction:: cv2.initCameraMatrix2D(objectPoints, imagePoints, imageSize[, aspectRatio]) -> retval
 
-    :param objectPoints: Vector of vectors of the calibration pattern points in the calibration pattern coordinate space. See  :ref:`calibrateCamera` for details.
+.. ocv:cfunction:: void cvInitIntrinsicParams2D( const CvMat* objectPoints, const CvMat* imagePoints, const CvMat* pointCounts, CvSize imageSize, CvMat* cameraMatrix, double aspectRatio=1.)
+
+.. ocv:pyoldfunction:: cv.InitIntrinsicParams2D(objectPoints, imagePoints, pointCounts, imageSize, cameraMatrix, aspectRatio=1.) -> None
+
+    :param objectPoints: Vector of vectors of the calibration pattern points in the calibration pattern coordinate space. In the old interface all the per-view vectors are concatenated. See :ocv:func:`calibrateCamera` for details.
+    
+    :param imagePoints: Vector of vectors of the projections of the calibration pattern points. In the old interface all the per-view vectors are concatenated. 
     
-    :param imagePoints: Vector of vectors of the projections of the calibration pattern points.
+    :param npoints: The integer vector of point counters for each view.
     
     :param imageSize: Image size in pixels used to initialize the principal point.
 
@@ -752,35 +832,40 @@ Currently, the function only supports planar calibration patterns, which are pat
 
 matMulDeriv
 ---------------
+Computes partial derivatives of the matrix product for each multiplied matrix.
 
 .. ocv:function:: void matMulDeriv( InputArray A, InputArray B, OutputArray dABdA, OutputArray dABdB )
 
-    Computes partial derivatives of the matrix product for each multiplied matrix.
+.. ocv:pyfunction:: cv2.matMulDeriv(A, B[, dABdA[, dABdB]]) -> dABdA, dABdB
 
-    :param A: The first multiplied matrix.
+    :param A: First multiplied matrix.
 
-    :param B: The second multiplied matrix.
+    :param B: Second multiplied matrix.
 
-    :param dABdA: The first output derivative matrix  ``d(A*B)/dA``  of size  :math:`\texttt{A.rows*B.cols} \times {A.rows*A.cols}` .
+    :param dABdA: First output derivative matrix  ``d(A*B)/dA``  of size  :math:`\texttt{A.rows*B.cols} \times {A.rows*A.cols}` .
     
-    :param dABdA: The second output derivative matrix  ``d(A*B)/dB``  of size  :math:`\texttt{A.rows*B.cols} \times {B.rows*B.cols}` .
+    :param dABdA: Second output derivative matrix  ``d(A*B)/dB``  of size  :math:`\texttt{A.rows*B.cols} \times {B.rows*B.cols}` .
 
 The function computes partial derivatives of the elements of the matrix product
 :math:`A*B` with regard to the elements of each of the two input matrices. The function is used to compute the Jacobian matrices in
-:ref:`stereoCalibrate`  but can also be used in any other similar optimization function.
+:ocv:func:`stereoCalibrate`  but can also be used in any other similar optimization function.
 
 
 
 projectPoints
 -----------------
+Projects 3D points to an image plane.
 
 .. ocv:function:: void projectPoints( InputArray objectPoints, InputArray rvec, InputArray tvec, InputArray cameraMatrix, InputArray distCoeffs, OutputArray imagePoints, OutputArray jacobian=noArray(), double aspectRatio=0 )
 
-    Projects 3D points to an image plane.
+.. ocv:pyfunction:: cv2.projectPoints(objectPoints, rvec, tvec, cameraMatrix, distCoeffs[, imagePoints[, jacobian[, aspectRatio]]]) -> imagePoints, jacobian
+
+.. ocv:cfunction:: void cvProjectPoints2( const CvMat* objectPoints, const CvMat* rvec, const CvMat* tvec, const CvMat* cameraMatrix, const CvMat* distCoeffs, CvMat* imagePoints, CvMat* dpdrot=NULL, CvMat* dpdt=NULL, CvMat* dpdf=NULL, CvMat* dpdc=NULL, CvMat* dpddist=NULL )
+.. ocv:pyoldfunction:: cv.ProjectPoints2(objectPoints, rvec, tvec, cameraMatrix, distCoeffs, imagePoints, dpdrot=None, dpdt=None, dpdf=None, dpdc=None, dpddist=None)-> None
 
     :param objectPoints: Array of object points, 3xN/Nx3 1-channel or 1xN/Nx1 3-channel  (or  ``vector<Point3f>`` ), where N is the number of points in the view.
 
-    :param rvec: Rotation vector. See  :ref:`Rodrigues` for details.
+    :param rvec: Rotation vector. See  :ocv:func:`Rodrigues` for details.
     
     :param tvec: Translation vector.
 
@@ -790,7 +875,7 @@ projectPoints
 
     :param imagePoints: Output array of image points, 2xN/Nx2 1-channel or 1xN/Nx1 2-channel, or  ``vector<Point2f>`` .
 
-    :param jacobian: Optional output 2Nx(10+<numDistCoeffs>) jacobian matrix of derivatives of image points with respect to components of the rotation vector, translation vector, focal lengths, coordinates of the principal point and the distortion coefficients.
+    :param jacobian: Optional output 2Nx(10+<numDistCoeffs>) jacobian matrix of derivatives of image points with respect to components of the rotation vector, translation vector, focal lengths, coordinates of the principal point and the distortion coefficients. In the old interface different components of the jacobian are returned via different output parameters.
 
     :param aspectRatio: Optional "fixed aspect ratio" parameter. If the parameter is not 0, the function assumes that the aspect ratio (*fx/fy*) is fixed and correspondingly adjusts the jacobian matrix.
 
@@ -801,32 +886,34 @@ of partial derivatives of image points coordinates (as functions of all the
 input parameters) with respect to the particular parameters, intrinsic and/or
 extrinsic. The Jacobians are used during the global optimization
 in
-:ref:`calibrateCamera`, 
-:ref:`solvePnP`, and 
-:ref:`stereoCalibrate` . The
+:ocv:func:`calibrateCamera`, 
+:ocv:func:`solvePnP`, and 
+:ocv:func:`stereoCalibrate` . The
 function itself can also be used to compute a re-projection error given the
 current intrinsic and extrinsic parameters.
 
-**Note:**
-
-By setting ``rvec=tvec=(0,0,0)``  or by setting ``cameraMatrix`` to a 3x3 identity matrix, or by passing zero distortion coefficients, you can get various useful partial cases of the function. This means that you can compute the distorted coordinates for a sparse set of points or apply a perspective transformation (and also compute the derivatives) in the ideal zero-distortion setup.
+.. note:: By setting ``rvec=tvec=(0,0,0)``  or by setting ``cameraMatrix`` to a 3x3 identity matrix, or by passing zero distortion coefficients, you can get various useful partial cases of the function. This means that you can compute the distorted coordinates for a sparse set of points or apply a perspective transformation (and also compute the derivatives) in the ideal zero-distortion setup.
 
 
 
 reprojectImageTo3D
 ----------------------
+Reprojects a disparity image to 3D space.
 
 .. ocv:function:: void reprojectImageTo3D( InputArray disparity, OutputArray _3dImage, InputArray Q, bool handleMissingValues=false, int depth=-1 )
 
-    Reprojects a disparity image to 3D space.
+.. ocv:pyfunction:: cv2.reprojectImageTo3D(disparity, Q[, _3dImage[, handleMissingValues[, ddepth]]]) -> _3dImage
+
+.. ocv:cfunction:: void cvReprojectImageTo3D( const CvArr* disparity, CvArr* _3dImage, const CvMat* Q, int handleMissingValues=0)
+.. ocv:pyoldfunction:: cv.ReprojectImageTo3D(disparity, _3dImage, Q, handleMissingValues=0) -> None
 
     :param disparity: Input single-channel 16-bit signed or 32-bit floating-point disparity image.
 
     :param _3dImage: Output 3-channel floating-point image of the same size as  ``disparity`` . Each element of  ``_3dImage(x,y)``  contains 3D coordinates of the point  ``(x,y)``  computed from the disparity map.
 
-    :param Q: :math:`4 \times 4`  perspective transformation matrix that can be obtained with  :ref:`StereoRectify` .
+    :param Q: :math:`4 \times 4`  perspective transformation matrix that can be obtained with  :ocv:func:`StereoRectify` .
     
-    :param handleMissingValues: Indicates, whether the function should handle missing values (i.e. points where the disparity was not computed). If ``handleMissingValues=true``, then pixels with the minimal disparity that corresponds to the outliers (see  :ref:`StereoBM::operator ()` ) are transformed to 3D points with a very large Z value (currently set to 10000).
+    :param handleMissingValues: Indicates, whether the function should handle missing values (i.e. points where the disparity was not computed). If ``handleMissingValues=true``, then pixels with the minimal disparity that corresponds to the outliers (see  :ocv:func:`StereoBM::operator()` ) are transformed to 3D points with a very large Z value (currently set to 10000).
 
     :param ddepth: The optional output array depth. If it is ``-1``, the output image will have ``CV_32F`` depth. ``ddepth`` can also be set to ``CV_16S``, ``CV_32S`` or ``CV_32F``.
     
@@ -838,17 +925,21 @@ The function transforms a single-channel disparity map to a 3-channel image repr
 
 The matrix ``Q`` can be an arbitrary
 :math:`4 \times 4` matrix (for example, the one computed by
-:ref:`StereoRectify`). To reproject a sparse set of points {(x,y,d),...} to 3D space, use
-:ref:`PerspectiveTransform` .
+:ocv:func:`StereoRectify`). To reproject a sparse set of points {(x,y,d),...} to 3D space, use
+:ocv:func:`PerspectiveTransform` .
 
 
 
 RQDecomp3x3
 ---------------
+Computes an RQ decomposition of 3x3 matrices.
 
 .. ocv:function:: Vec3d RQDecomp3x3( InputArray M, OutputArray R, OutputArray Q, OutputArray Qx=noArray(), OutputArray Qy=noArray(), OutputArray Qz=noArray() )
 
-    Computes an RQ decomposition of 3x3 matrices.
+.. ocv:pyfunction:: cv2.RQDecomp3x3(src[, mtxR[, mtxQ[, Qx[, Qy[, Qz]]]]]) -> retval, mtxR, mtxQ, Qx, Qy, Qz
+
+.. ocv:cfunction:: void cvRQDecomp3x3( const CvMat *M, CvMat *R, CvMat *Q, CvMat *Qx=NULL, CvMat *Qy=NULL, CvMat *Qz=NULL, CvPoint3D64f *eulerAngles=NULL)
+.. ocv:pyoldfunction:: cv.RQDecomp3x3(M, R, Q, Qx=None, Qy=None, Qz=None) -> eulerAngles
 
     :param M: 3x3 input matrix.
 
@@ -863,7 +954,7 @@ RQDecomp3x3
     :param Qz: Optional output 3x3 rotation matrix around z-axis.
 
 The function computes a RQ decomposition using the given rotations. This function is used in
-:ref:`DecomposeProjectionMatrix` to decompose the left 3x3 submatrix of a projection matrix into a camera and a rotation matrix.
+:ocv:func:`DecomposeProjectionMatrix` to decompose the left 3x3 submatrix of a projection matrix into a camera and a rotation matrix.
 
 It optionally returns three rotation matrices, one for each axis, and the three Euler angles
 (as the return value)
@@ -873,9 +964,15 @@ that could be used in OpenGL.
 
 Rodrigues
 -------------
+Converts a rotation matrix to a rotation vector or vice versa.
+
 .. ocv:function:: void Rodrigues(InputArray src, OutputArray dst, OutputArray jacobian=noArray())
 
-    Converts a rotation matrix to a rotation vector or vice versa.
+.. ocv:pyfunction:: cv2.Rodrigues(src[, dst[, jacobian]]) -> dst, jacobian
+
+.. ocv:cfunction:: int cvRodrigues2( const CvMat* src, CvMat* dst, CvMat* jacobian=0 )
+
+.. ocv:pyoldfunction:: cv.Rodrigues2(src, dst, jacobian=0)-> None
 
     :param src: Input rotation vector (3x1 or 1x3) or rotation matrix (3x3).
 
@@ -896,17 +993,17 @@ Inverse transformation can be also done easily, since
 A rotation vector is a convenient and most compact representation of a rotation matrix
 (since any rotation matrix has just 3 degrees of freedom). The representation is
 used in the global 3D geometry optimization procedures like
-:ref:`calibrateCamera`,
-:ref:`stereoCalibrate`, or
-:ref:`solvePnP` .
+:ocv:func:`calibrateCamera`,
+:ocv:func:`stereoCalibrate`, or
+:ocv:func:`solvePnP` .
 
 
 
 StereoBM
 --------
-.. c:type:: StereoBM
+.. ocv:class:: StereoBM
 
-Class for computing stereo correspondence using the block matching algorithm ::
+Class for computing stereo correspondence using the block matching algorithm. ::
 
     // Block matching stereo correspondence algorithm class StereoBM
     {
@@ -931,18 +1028,50 @@ Class for computing stereo correspondence using the block matching algorithm ::
         Ptr<CvStereoBMState> state;
     };
 
-The class is a C++ wrapper for the associated functions. In particular, ``StereoBM::operator ()`` is the wrapper for
-:ref:`StereoBM::operator ()`. 
+The class is a C++ wrapper for the associated functions. In particular, ``StereoBM::operator()`` is the wrapper for
+:ocv:func:`StereoBM::operator()`. 
+
+
+StereoBM::StereoBM
+---------------------
+The constructors.
+
+.. ocv:function:: StereoBM::StereoBM()
+.. ocv:function:: StereoBM::StereoBM(int preset, int ndisparities=0, int SADWindowSize=21)
+
+.. ocv:pyfunction:: cv2.StereoBM.StereoBM(preset[, ndisparities[, SADWindowSize]]) -> <StereoBM object>
 
+.. ocv:cfunction:: CvStereoBMState* cvCreateStereoBMState( int preset=CV_STEREO_BM_BASIC, int ndisparities=0 )
 
+.. ocv:pyoldfunction:: cv.CreateStereoBMState(preset=CV_STEREO_BM_BASIC, ndisparities=0)-> StereoBMState
 
+    :param preset: specifies the whole set of algorithm parameters, one of:
+    
+            * BASIC_PRESET - parameters suitable for general cameras 
+            * FISH_EYE_PRESET - parameters suitable for wide-angle cameras 
+            * NARROW_PRESET - parameters suitable for narrow-angle cameras
+        
+        After constructing the class, you can override any parameters set by the preset.
+    
+    :param ndisparities: the disparity search range. For each pixel algorithm will find the best disparity from 0 (default minimum disparity) to ``ndisparities``. The search range can then be shifted by changing the minimum disparity.
+    
+    :param SADWindowSize: the linear size of the blocks compared by the algorithm. The size should be odd (as the block is centered at the current pixel). Larger block size implies smoother, though less accurate disparity map. Smaller block size gives more detailed disparity map, but there is higher chance for algorithm to find a wrong correspondence.
+    
+The constructors initialize ``StereoBM`` state. You can then call ``StereoBM::operator()`` to compute disparity for a specific stereo pair.
+
+.. note:: In the C API you need to deallocate ``CvStereoBM`` state when it is not needed anymore using ``cvReleaseStereoBMState(&stereobm)``.
 
-StereoBM::operator ()
+StereoBM::operator()
 -----------------------
+Computes disparity using the BM algorithm for a rectified stereo pair.
 
 .. ocv:function:: void StereoBM::operator()(InputArray left, InputArray right, OutputArray disp, int disptype=CV_16S )
 
-    Computes disparity using the BM algorithm for a rectified stereo pair.
+.. ocv:pyfunction:: cv2.StereoBM.compute(left, right[, disparity[, disptype]]) -> disparity
+
+.. ocv:cfunction:: void cvFindStereoCorrespondenceBM( const CvArr* left, const CvArr* right, CvArr* disparity, CvStereoBMState* state )
+
+.. ocv:pyoldfunction:: cv.FindStereoCorrespondenceBM(left, right, disparity, state)-> None
 
     :param left: Left 8-bit single-channel or 3-channel image.
 
@@ -951,6 +1080,8 @@ StereoBM::operator ()
     :param disp: Output disparity map. It has the same size as the input images. When ``disptype==CV_16S``, the map is a 16-bit signed single-channel image, containing disparity values scaled by 16. To get the true disparity values from such fixed-point representation, you will need to divide each  ``disp`` element by 16. If ``disptype==CV_32F``, the disparity map will already contain the real disparity values on output.
     
     :param disptype: Type of the output disparity map, ``CV_16S`` (default) or ``CV_32F``.
+    
+    :param state: The pre-initialized ``CvStereoBMState`` structure in the case of the old API.
 
 The method executes the BM algorithm on a rectified stereo pair. See the ``stereo_match.cpp`` OpenCV sample on how to prepare images and call the method. Note that the method is not constant, thus you should not use the same ``StereoBM`` instance from within different threads simultaneously.
 
@@ -960,9 +1091,9 @@ The method executes the BM algorithm on a rectified stereo pair. See the ``stere
 StereoSGBM
 ----------
 
-.. c:type:: StereoSGBM
+.. ocv:class:: StereoSGBM
 
-Class for computing stereo correspondence using the semi-global block matching algorithm ::
+Class for computing stereo correspondence using the semi-global block matching algorithm. ::
 
     class StereoSGBM
     {
@@ -998,7 +1129,7 @@ The class implements the modified H. Hirschmuller algorithm HH08 that differs fr
 
  * Mutual information cost function is not implemented. Instead, a simpler Birchfield-Tomasi sub-pixel metric from BT96 is used. Though, the color images are supported as well.
 
- * Some pre- and post- processing steps from K. Konolige algorithm :ref:`StereoBM::operator ()`  are included, for example: pre-filtering (``CV_STEREO_BM_XSOBEL`` type) and post-filtering (uniqueness check, quadratic interpolation and speckle filtering).
+ * Some pre- and post- processing steps from K. Konolige algorithm :ocv:func:`StereoBM::operator ()`  are included, for example: pre-filtering (``CV_STEREO_BM_XSOBEL`` type) and post-filtering (uniqueness check, quadratic interpolation and speckle filtering).
 
 
 
@@ -1008,7 +1139,9 @@ StereoSGBM::StereoSGBM
 
 .. ocv:function:: StereoSGBM::StereoSGBM( int minDisparity, int numDisparities, int SADWindowSize, int P1=0, int P2=0, int disp12MaxDiff=0, int preFilterCap=0, int uniquenessRatio=0, int speckleWindowSize=0, int speckleRange=0, bool fullDP=false)
 
-    The constructor.
+.. ocv:pyfunction:: cv2.StereoSGBM.StereoSGBM(minDisparity, numDisparities, SADWindowSize[, P1[, P2[, disp12MaxDiff[, preFilterCap[, uniquenessRatio[, speckleWindowSize[, speckleRange[, fullDP]]]]]]]]) -> <StereoSGBM object>
+
+    Initializes ``StereoSGBM`` and sets parameters to custom values.??
 
     :param minDisparity: Minimum possible disparity value. Normally, it is zero but sometimes rectification algorithms can shift images, so this parameter needs to be adjusted accordingly.
 
@@ -1039,6 +1172,8 @@ StereoSGBM::operator ()
 
 .. ocv:function:: void StereoSGBM::operator()(InputArray left, InputArray right, OutputArray disp)
 
+.. ocv:pyfunction:: cv2.StereoSGBM.compute(left, right[, disp]) -> disp
+
     Computes disparity using the SGBM algorithm for a rectified stereo pair.
 
     :param left: Left 8-bit single-channel or 3-channel image.
@@ -1049,9 +1184,7 @@ StereoSGBM::operator ()
 
 The method executes the SGBM algorithm on a rectified stereo pair. See ``stereo_match.cpp`` OpenCV sample on how to prepare images and call the method. 
 
-**Note**:
-
-The method is not constant, so you should not use the same ``StereoSGBM`` instance from different threads simultaneously.
+.. note:: The method is not constant, so you should not use the same ``StereoSGBM`` instance from different threads simultaneously.
 
 
 
@@ -1061,6 +1194,11 @@ stereoCalibrate
 
     Calibrates the stereo camera.
 
+.. ocv:pyfunction:: cv2.stereoCalibrate(objectPoints, imagePoints1, imagePoints2, cameraMatrix1, distCoeffs1, cameraMatrix2, distCoeffs2, imageSize[, R[, T[, E[, F[, criteria[, flags]]]]]]) -> retval, cameraMatrix1, distCoeffs1, cameraMatrix2, distCoeffs2, R, T, E, F
+
+.. ocv:cfunction:: double cvStereoCalibrate( const CvMat* objectPoints, const CvMat* imagePoints1, const CvMat* imagePoints2, const CvMat* pointCounts, CvMat* cameraMatrix1, CvMat* distCoeffs1, CvMat* cameraMatrix2, CvMat* distCoeffs2, CvSize imageSize, CvMat* R, CvMat* T, CvMat* E=0, CvMat* F=0, CvTermCriteria termCrit=cvTermCriteria( CV_TERMCRIT_ITER+CV_TERMCRIT_EPS, 30, 1e-6), int flags=CV_CALIB_FIX_INTRINSIC )
+.. ocv:pyoldfunction:: cv.StereoCalibrate( objectPoints, imagePoints1, imagePoints2, pointCounts, cameraMatrix1, distCoeffs1, cameraMatrix2, distCoeffs2, imageSize, R, T, E=None, F=None, termCrit=(CV_TERMCRIT_ITER+CV_TERMCRIT_EPS, 30, 1e-6), flags=CV_CALIB_FIX_INTRINSIC)-> None
+
     :param objectPoints: Vector of vectors of the calibration pattern points.
 
     :param imagePoints1: Vector of vectors of the projections of the calibration pattern points, observed by the first camera.
@@ -1135,9 +1273,9 @@ where
     F = cameraMatrix2^{-T} E cameraMatrix1^{-1}
 
 Besides the stereo-related information, the function can also perform a full calibration of each of two cameras. However, due to the high dimensionality of the parameter space and noise in the input data, the function can diverge from the correct solution. If the intrinsic parameters can be estimated with high accuracy for each of the cameras individually (for example, using
-:ref:`calibrateCamera` ), you are recommended to do so and then pass ``CV_CALIB_FIX_INTRINSIC`` flag to the function along with the computed intrinsic parameters. Otherwise, if all the parameters are estimated at once, it makes sense to restrict some parameters, for example, pass ``CV_CALIB_SAME_FOCAL_LENGTH`` and ``CV_CALIB_ZERO_TANGENT_DIST`` flags, which is usually a reasonable assumption.
+:ocv:func:`calibrateCamera` ), you are recommended to do so and then pass ``CV_CALIB_FIX_INTRINSIC`` flag to the function along with the computed intrinsic parameters. Otherwise, if all the parameters are estimated at once, it makes sense to restrict some parameters, for example, pass ``CV_CALIB_SAME_FOCAL_LENGTH`` and ``CV_CALIB_ZERO_TANGENT_DIST`` flags, which is usually a reasonable assumption.
 
-Similarly to :ref:`calibrateCamera` , the function minimizes the total re-projection error for all the points in all the available views from both cameras. The function returns the final value of the re-projection error.
+Similarly to :ocv:func:`calibrateCamera` , the function minimizes the total re-projection error for all the points in all the available views from both cameras. The function returns the final value of the re-projection error.
 
 
 
@@ -1148,13 +1286,16 @@ stereoRectify
 
     Computes rectification transforms for each head of a calibrated stereo camera.
 
-    :param cameraMatrix1: The first camera matrix.
+.. ocv:cfunction:: void cvStereoRectify( const CvMat* cameraMatrix1, const CvMat* cameraMatrix2, const CvMat* distCoeffs1, const CvMat* distCoeffs2, CvSize imageSize, const CvMat* R, const CvMat* T, CvMat* R1, CvMat* R2, CvMat* P1, CvMat* P2, CvMat* Q=0, int flags=CV_CALIB_ZERO_DISPARITY, double alpha=-1, CvSize newImageSize=cvSize(0, 0), CvRect* roi1=0, CvRect* roi2=0)
+.. ocv:pyoldfunction:: cv.StereoRectify( cameraMatrix1, cameraMatrix2, distCoeffs1, distCoeffs2, imageSize, R, T, R1, R2, P1, P2, Q=None, flags=CV_CALIB_ZERO_DISPARITY, alpha=-1, newImageSize=(0, 0))-> (roi1, roi2)
+
+    :param cameraMatrix1: First camera matrix.
     
-    :param cameraMatrix2: The second camera matrix.
+    :param cameraMatrix2: Second camera matrix.
 
-    :param distCoeffs1: The first camera distortion parameters.
+    :param distCoeffs1: First camera distortion parameters.
     
-    :param distCoeffs2: The second camera distortion parameters.
+    :param distCoeffs2: Second camera distortion parameters.
 
     :param imageSize: Size of the image used for stereo calibration.
 
@@ -1172,12 +1313,12 @@ stereoRectify
 
     :param alpha: Free scaling parameter. If it is -1  or absent, the function performs the default scaling. Otherwise, the parameter should be between 0 and 1.  ``alpha=0``  means that the rectified images are zoomed and shifted so that only valid pixels are visible (no black areas after rectification).  ``alpha=1``  means that the rectified image is decimated and shifted so that all the pixels from the original images from the cameras are retained in the rectified images (no source image pixels are lost). Obviously, any intermediate value yields an intermediate result between those two extreme cases.
 
-    :param newImageSize: New image resolution after rectification. The same size should be passed to  :ref:`InitUndistortRectifyMap` (see the  ``stereo_calib.cpp``  sample in OpenCV samples directory). When (0,0) is passed (default), it is set to the original  ``imageSize`` . Setting it to larger value can help you preserve details in the original image, especially when there is a big radial distortion.
+    :param newImageSize: New image resolution after rectification. The same size should be passed to  :ocv:func:`initUndistortRectifyMap` (see the  ``stereo_calib.cpp``  sample in OpenCV samples directory). When (0,0) is passed (default), it is set to the original  ``imageSize`` . Setting it to larger value can help you preserve details in the original image, especially when there is a big radial distortion.
 
     :param roi1, roi2: Optional output rectangles inside the rectified images where all the pixels are valid. If  ``alpha=0`` , the ROIs cover the whole images. Otherwise, they are likely to be smaller (see the picture below).
 
 The function computes the rotation matrices for each camera that (virtually) make both camera image planes the same plane. Consequently, this makes all the epipolar lines parallel and thus simplifies the dense stereo correspondence problem. The function takes the matrices computed by
-:ref:`stereoCalibrate` as input. As output, it provides two rotation matrices and also two projection matrices in the new coordinates. The function distinguishes the following two cases:
+:ocv:func:`stereoCalibrate` as input. As output, it provides two rotation matrices and also two projection matrices in the new coordinates. The function distinguishes the following two cases:
 
 #.
     **Horizontal stereo**: the first and the second camera views are shifted relative to each other mainly along the x axis (with possible small vertical shift). In the rectified images, the corresponding epipolar lines in the left and right cameras are horizontal and have the same y-coordinate. P1 and P2 look like:
@@ -1211,7 +1352,7 @@ The function computes the rotation matrices for each camera that (virtually) mak
 
 As you can see, the first three columns of ``P1`` and ``P2`` will effectively be the new "rectified" camera matrices.
 The matrices, together with ``R1`` and ``R2`` , can then be passed to
-:ref:`InitUndistortRectifyMap` to initialize the rectification map for each camera.
+:ocv:func:`initUndistortRectifyMap` to initialize the rectification map for each camera.
 
 See below the screenshot from the ``stereo_calib.cpp`` sample. Some red horizontal lines pass through the corresponding image regions. This means that the images are well rectified, which is what most stereo correspondence algorithms rely on. The green rectangles are ``roi1`` and ``roi2`` . You see that their interiors are all valid pixels.
 
@@ -1225,6 +1366,11 @@ stereoRectifyUncalibrated
 
     Computes a rectification transform for an uncalibrated stereo camera.
 
+.. ocv:pyfunction:: cv2.stereoRectifyUncalibrated(points1, points2, F, imgSize[, H1[, H2[, threshold]]]) -> retval, H1, H2
+
+.. ocv:cfunction:: void cvStereoRectifyUncalibrated( const CvMat* points1, const CvMat* points2, const CvMat* F, CvSize imageSize, CvMat* H1, CvMat* H2, double threshold=5 )
+.. ocv:pyoldfunction:: cv.StereoRectifyUncalibrated(points1, points2, F, imageSize, H1, H2, threshold=5)-> None
+
     :param points1, points2: Two arrays of corresponding 2D points. The same formats as in  :ref:`findFundamentalMat`  are supported.
 
     :param F: Input fundamental matrix. It can be computed from the same set of point pairs using  :ref:`findFundamentalMat` .
@@ -1236,13 +1382,15 @@ stereoRectifyUncalibrated
     :param threshold: Optional threshold used to filter out the outliers. If the parameter is greater than zero, all the point pairs that do not comply with the epipolar geometry (that is, the points for which  :math:`|\texttt{points2[i]}^T*\texttt{F}*\texttt{points1[i]}|>\texttt{threshold}` ) are rejected prior to computing the homographies. Otherwise,all the points are considered inliers.
 
 The function computes the rectification transformations without knowing intrinsic parameters of the cameras and their relative position in the space, which explains the suffix "uncalibrated". Another related difference from
-:ref:`StereoRectify` is that the function outputs not the rectification transformations in the object (3D) space, but the planar perspective transformations encoded by the homography matrices ``H1`` and ``H2`` . The function implements the algorithm
-Hartley99
-.
+:ocv:func:`StereoRectify` is that the function outputs not the rectification transformations in the object (3D) space, but the planar perspective transformations encoded by the homography matrices ``H1`` and ``H2`` . The function implements the algorithm
+[Hartley99]_.
+
+.. note::
+
+    While the algorithm does not need to know the intrinsic parameters of the cameras, it heavily depends on the epipolar geometry. Therefore, if the camera lenses have a significant distortion, it would be better to correct it before computing the fundamental matrix and calling this function. For example, distortion coefficients can be estimated for each head of stereo camera separately by using :ocv:func:`calibrateCamera` . Then, the images can be corrected using :ocv:func:`undistort` , or just the point coordinates can be corrected with :ocv:func:`undistortPoints` .
+
+.. [BouguetMCT] J.Y.Bouguet. MATLAB calibration tool. http://www.vision.caltech.edu/bouguetj/calib_doc/
 
-**Note**:
+.. [Hartley99] Hartley, R.I., “Theory and Practice of Projective Rectification”. IJCV 35 2, pp 115-127 (1999)
 
-While the algorithm does not need to know the intrinsic parameters of the cameras, it heavily depends on the epipolar geometry. Therefore, if the camera lenses have a significant distortion, it would be better to correct it before computing the fundamental matrix and calling this function. For example, distortion coefficients can be estimated for each head of stereo camera separately by using
-:ref:`calibrateCamera` . Then, the images can be corrected using
-:ref:`undistort` , or just the point coordinates can be corrected with
-:ref:`undistortPoints` .
+.. [Zhang2000] Z. Zhang. A Flexible New Technique for Camera Calibration. IEEE Transactions on Pattern Analysis and Machine Intelligence, 22(11):1330-1334, 2000.
\ No newline at end of file
index d99ad58..ce04268 100644 (file)
@@ -645,7 +645,7 @@ Finally, there are STL-style iterators that are smart enough to skip gaps betwee
 
 The matrix iterators are random-access iterators, so they can be passed to any STL algorithm, including ``std::sort()`` .
 
-.. _MatrixExpressions:
+
 
 Matrix Expressions
 ------------------
index d1b734b..e37036a 100644 (file)
@@ -3,16 +3,17 @@ Clustering
 
 .. highlight:: cpp
 
-.. index:: kmeans
-
-.. _kmeans:
-
 kmeans
 ------
+Finds centers of clusters and groups input samples around the clusters.
+
+.. ocv:function:: double kmeans( InputArray samples, int clusterCount, InputOutputArray labels, TermCriteria criteria, int attempts, int flags, OutputArray centers=noArray() )
+
+.. ocv:pyfunction:: cv2.kmeans(data, K, criteria, attempts, flags[, bestLabels[, centers]]) -> retval, bestLabels, centers
 
-.. ocv:function:: double kmeans( InputArray samples, int clusterCount, InputOutputArray labels, TermCriteria termcrit, int attempts, int flags, OutputArray centers=noArray() )
+.. ocv:cfunction:: int cvKMeans2(const CvArr* samples, int nclusters, CvArr* labels, CvTermCriteria criteria, int attempts=1, CvRNG* rng=0, int flags=0, CvArr* centers=0, double* compactness=0)
 
-    Finds centers of clusters and groups input samples around the clusters.
+.. ocv:pyoldfunction:: cv.KMeans2(samples, nclusters, labels, criteria)-> None
 
     :param samples: Floating-point matrix of input samples, one row per sample.
 
@@ -20,7 +21,7 @@ kmeans
 
     :param labels: Input/output integer array that stores the cluster indices for every sample.
 
-    :param termcrit: Flag to specify the maximum number of iterations and/or the desired accuracy. The accuracy is specified as ``termcrit.epsilon``. As soon as each of the cluster centers moves by less than ``termcrit.epsilon`` on some iteration, the algorithm stops.
+    :param criteria: The algorithm termination criteria, that is, the maximum number of iterations and/or the desired accuracy. The accuracy is specified as ``criteria.epsilon``. As soon as each of the cluster centers moves by less than ``criteria.epsilon`` on some iteration, the algorithm stops.
 
     :param attempts: Flag to specify the number of times the algorithm is executed using different initial labelings. The algorithm returns the labels that yield the best compactness (see the last function parameter).
 
@@ -28,7 +29,7 @@ kmeans
 
             * **KMEANS_RANDOM_CENTERS** Select random initial centers in each attempt.
 
-            * **KMEANS_PP_CENTERS** Use ``kmeans++`` center initialization by Arthur and Vassilvitskii.
+            * **KMEANS_PP_CENTERS** Use ``kmeans++`` center initialization by Arthur and Vassilvitskii [Arthur2007].
 
             * **KMEANS_USE_INITIAL_LABELS** During the first (and possibly the only) attempt, use the user-supplied labels instead of computing them from the initial centers. For the second and further attempts, use the random or semi-random centers. Use one of  ``KMEANS_*_CENTERS``  flag to specify the exact method.
 
@@ -53,15 +54,13 @@ Basically, you can use only the core of the function, set the number of
 attempts to 1, initialize labels each time using a custom algorithm, pass them with the
 ( ``flags`` = ``KMEANS_USE_INITIAL_LABELS`` ) flag, and then choose the best (most-compact) clustering.
 
-.. index:: partition
-
 partition
 -------------
-.. ocv:function:: template<typename _Tp, class _EqPredicate> int
+Splits an element set into equivalency classes.
 
-.. ocv:function:: partition( const vector<_Tp>& vec, vector<int>& labels,               _EqPredicate predicate=_EqPredicate())
+.. ocv:function:: template<typename _Tp, class _EqPredicate> int
 
-    Splits an element set into equivalency classes.
+.. ocv:function:: partition( const vector<_Tp>& vec, vector<int>& labels, _EqPredicate predicate=_EqPredicate())
 
     :param vec: Set of elements stored as a vector.
 
@@ -77,3 +76,4 @@ http://en.wikipedia.org/wiki/Disjoint-set_data_structure
 . The function
 returns the number of equivalency classes.
 
+.. [Arthur2007] Arthur and S. Vassilvitskii “k-means++: the advantages of careful seeding”, Proceedings of the eighteenth annual ACM-SIAM symposium on Discrete algorithms, 2007
index b510e45..7eb4e3e 100644 (file)
@@ -6,9 +6,12 @@ core. The Core Functionality
     :maxdepth: 2
 
     basic_structures
+    old_basic_structures
+    dynamic_structures
     operations_on_arrays
     drawing_functions
     xml_yaml_persistence
+    old_xml_yaml_persistence
     clustering
     utility_and_system_functions_and_macros
 
index bb33191..29f5527 100644 (file)
@@ -26,13 +26,16 @@ If a drawn figure is partially or completely outside the image, the drawing func
 
 .. note:: The functions do not support alpha-transparency when the target image is 4-channel. In this case, the ``color[3]`` is simply copied to the repainted pixels. Thus, if you want to paint semi-transparent shapes, you can paint them in a separate buffer and then blend it with the main image.
 
-.. index:: circle
-
 circle
 ----------
+Draws a circle.
+
 .. ocv:function:: void circle(Mat& img, Point center, int radius,            const Scalar& color, int thickness=1,            int lineType=8, int shift=0)
 
-    Draws a circle.
+.. ocv:pyfunction:: cv2.circle(img, center, radius, color[, thickness[, lineType[, shift]]]) -> None
+
+.. ocv:cfunction:: void cvCircle( CvArr* img, CvPoint center, int radius, CvScalar color, int thickness=1, int lineType=8, int shift=0 )
+.. ocv:pyoldfunction:: cv.Circle(img, center, radius, color, thickness=1, lineType=8, shift=0)-> None
 
     :param img: Image where the circle is drawn.
 
@@ -50,18 +53,21 @@ circle
 
 The function ``circle`` draws a simple or filled circle with a given center and radius.
 
-.. index:: clipLine
-
 clipLine
 ------------
+Clips the line against the image rectangle.
+
 .. ocv:function:: bool clipLine(Size imgSize, Point& pt1, Point& pt2)
 
 .. ocv:function:: bool clipLine(Rect imgRect, Point& pt1, Point& pt2)
 
-    Clips the line against the image rectangle.
+.. ocv:pyfunction:: cv2.clipLine(imgRect, pt1, pt2) -> retval, pt1, pt2
+
+.. ocv:cfunction:: int cvClipLine( CvSize imgSize, CvPoint* pt1, CvPoint* pt2 )
+.. ocv:pyoldfunction:: cv.ClipLine(imgSize, pt1, pt2) -> (clippedPt1, clippedPt2)
 
     :param imgSize: Image size. The image rectangle is  ``Rect(0, 0, imgSize.width, imgSize.height)`` .     
-       
+
     :param imgSize: Image rectangle.?? why do you list the same para twice??
 
     :param pt1: First line point.
@@ -71,15 +77,22 @@ clipLine
 The functions ``clipLine`` calculate a part of the line segment that is entirely within the specified rectangle.
 They return ``false`` if the line segment is completely outside the rectangle. Otherwise, they return ``true`` .
 
-.. index:: ellipse
-
 ellipse
 -----------
+Draws a simple or thick elliptic arc or fills an ellipse sector.
+
 .. ocv:function:: void ellipse(Mat& img, Point center, Size axes,             double angle, double startAngle, double endAngle,             const Scalar& color, int thickness=1,             int lineType=8, int shift=0)
 
 .. ocv:function:: void ellipse(Mat& img, const RotatedRect& box, const Scalar& color,             int thickness=1, int lineType=8)
 
-    Draws a simple or thick elliptic arc or fills an ellipse sector.
+.. ocv:pyfunction:: cv2.ellipse(img, center, axes, angle, startAngle, endAngle, color[, thickness[, lineType[, shift]]]) -> None
+.. ocv:pyfunction:: cv2.ellipse(img, box, color[, thickness[, lineType]]) -> None
+
+.. ocv:cfunction:: void cvEllipse( CvArr* img, CvPoint center, CvSize axes, double angle, double startAngle, double endAngle, CvScalar color, int thickness=1, int lineType=8, int shift=0 )
+.. ocv:pyoldfunction:: cv.Ellipse(img, center, axes, angle, startAngle, endAngle, color, thickness=1, lineType=8, shift=0)-> None
+
+.. ocv:cfunction:: void cvEllipseBox( CvArr* img, CvBox2D box, CvScalar color, int thickness=1, int lineType=8, int shift=0 )
+.. ocv:pyoldfunction:: cv.EllipseBox(img, box, color, thickness=1, lineType=8, shift=0)-> None
 
     :param img: Image.
 
@@ -93,7 +106,7 @@ ellipse
 
     :param endAngle: Ending angle of the elliptic arc in degrees.
 
-    :param box: Alternative ellipse representation via  :ocv:class:`RotatedRect`. This means that the function draws an ellipse inscribed in the rotated rectangle.
+    :param box: Alternative ellipse representation via  :ocv:class:`RotatedRect` or ``CvBox2D``. This means that the function draws an ellipse inscribed in the rotated rectangle.
 
     :param color: Ellipse color.
 
@@ -113,13 +126,13 @@ A piecewise-linear curve is used to approximate the elliptic arc boundary. If yo
 
 .. image:: pics/ellipse.png
 
-.. index:: ellipse2Poly
-
 ellipse2Poly
 ----------------
+Approximates an elliptic arc with a polyline.
+
 .. ocv:function:: void ellipse2Poly( Point center, Size axes, int angle,                   int startAngle, int endAngle, int delta,                   vector<Point>& pts )
 
-    Approximates an elliptic arc with a polyline.
+.. ocv:pyfunction:: cv2.ellipse2Poly(center, axes, angle, arcStart, arcEnd, delta) -> pts
 
     :param center: Center of the arc.
 
@@ -138,13 +151,18 @@ ellipse2Poly
 The function ``ellipse2Poly`` computes the vertices of a polyline that approximates the specified elliptic arc. It is used by
 :ocv:func:`ellipse` .
 
-.. index:: fillConvexPoly
+
 
 fillConvexPoly
 ------------------
+Fills a convex polygon.
+
 .. ocv:function:: void fillConvexPoly(Mat& img, const Point* pts, int npts,                    const Scalar& color, int lineType=8,                    int shift=0)
 
-    Fills a convex polygon.
+.. ocv:pyfunction:: cv2.fillConvexPoly(img, points, color[, lineType[, shift]]) -> None
+
+.. ocv:cfunction:: void cvFillConvexPoly( CvArr* img, CvPoint* pts, int npts, CvScalar color, int lineType=8, int shift=0 )
+.. ocv:pyoldfunction:: cv.FillConvexPoly(img, pn, color, lineType=8, shift=0)-> None
 
     :param img: Image.
 
@@ -162,13 +180,18 @@ The function ``fillConvexPoly`` draws a filled convex polygon.
 This function is much faster than the function ``fillPoly`` . It can fill not only convex polygons but any monotonic polygon without self-intersections,
 that is, a polygon whose contour intersects every horizontal line (scan line) twice at the most (though, its top-most and/or the bottom edge could be horizontal).
 
-.. index:: fillPoly
+
 
 fillPoly
 ------------
+Fills the area bounded by one or more polygons.
+
 .. ocv:function:: void fillPoly(Mat& img, const Point** pts,               const int* npts, int ncontours,              const Scalar& color, int lineType=8,              int shift=0, Point offset=Point() )
 
-    Fills the area bounded by one or more polygons.
+.. ocv:pyfunction:: cv2.fillPoly(img, pts, color[, lineType[, shift[, offset]]]) -> None
+
+.. ocv:cfunction:: void cvFillPoly( CvArr* img, CvPoint** pts, int* npts, int contours, CvScalar color, int lineType=8, int shift=0 )
+.. ocv:pyoldfunction:: cv.FillPoly(img, polys, color, lineType=8, shift=0)-> None
 
     :param img: Image.
 
@@ -187,22 +210,27 @@ fillPoly
 The function ``fillPoly`` fills an area bounded by several polygonal contours. The function can fill complex areas, for example,
 areas with holes, contours with self-intersections (some of thier parts), and so forth.
 
-.. index:: getTextSize
+
 
 getTextSize
 ---------------
+Calculates the width and height of a text string.
+
 .. ocv:function:: Size getTextSize(const string& text, int fontFace,                 double fontScale, int thickness,                 int* baseLine)
 
-    Calculates the width and height of a text string.
+.. ocv:pyfunction:: cv2.getTextSize(text, fontFace, fontScale, thickness) -> retval, baseLine
+
+.. ocv:cfunction:: void cvGetTextSize( const char* textString, const CvFont* font, CvSize* textSize, int* baseline )
+.. ocv:pyoldfunction:: cv.GetTextSize(textString, font)-> (textSize, baseline)
 
     :param text: Input text string.
 
     :param fontFace: Font to use. See the  :ocv:func:`putText` for details.    
-       
+
     :param fontScale: Font scale. See the  :ocv:func:`putText`  for details.   
-       
+
     :param thickness: Thickness of lines used to render the text. See  :ocv:func:`putText`  for details.   
-       
+
     :param baseLine: Output parameter - y-coordinate of the baseline relative to the bottom-most text point.
 
 The function ``getTextSize`` calculates and returns the size of a box that contains the specified text.
@@ -238,13 +266,66 @@ That is, the following code renders some text, the tight box surrounding it, and
     putText(img, text, textOrg, fontFace, fontScale,
             Scalar::all(255), thickness, 8);
 
-.. index:: line
+
+InitFont
+--------
+Initializes font structure (OpenCV 1.x API).
+
+.. cfunction:: void cvInitFont(  CvFont* font, int fontFace, double hscale, double vscale, double shear=0, int thickness=1, int lineType=8 )
+
+    :param font: Pointer to the font structure initialized by the function 
+
+    :param fontFace: Font name identifier. Only a subset of Hershey fonts  http://sources.isc.org/utils/misc/hershey-font.txt  are supported now:
+
+            * **CV_FONT_HERSHEY_SIMPLEX** normal size sans-serif font 
+
+            * **CV_FONT_HERSHEY_PLAIN** small size sans-serif font 
+
+            * **CV_FONT_HERSHEY_DUPLEX** normal size sans-serif font (more complex than    ``CV_FONT_HERSHEY_SIMPLEX`` ) 
+
+            * **CV_FONT_HERSHEY_COMPLEX** normal size serif font 
+
+            * **CV_FONT_HERSHEY_TRIPLEX** normal size serif font (more complex than  ``CV_FONT_HERSHEY_COMPLEX`` ) 
+
+            * **CV_FONT_HERSHEY_COMPLEX_SMALL** smaller version of  ``CV_FONT_HERSHEY_COMPLEX`` 
+
+            * **CV_FONT_HERSHEY_SCRIPT_SIMPLEX** hand-writing style font 
+
+            * **CV_FONT_HERSHEY_SCRIPT_COMPLEX** more complex variant of  ``CV_FONT_HERSHEY_SCRIPT_SIMPLEX`` 
+
+         The parameter can be composited from one of the values above and an optional  ``CV_FONT_ITALIC``  flag, which indicates italic or oblique font. 
+
+
+    :param hscale: Horizontal scale.  If equal to  ``1.0f`` , the characters have the original width depending on the font type. If equal to  ``0.5f`` , the characters are of half the original width. 
+
+
+    :param vscale: Vertical scale. If equal to  ``1.0f`` , the characters have the original height depending on the font type. If equal to  ``0.5f`` , the characters are of half the original height. 
+
+
+    :param shear: Approximate tangent of the character slope relative to the vertical line.  A zero value means a non-italic font,  ``1.0f``  means about a 45 degree slope, etc. 
+
+
+    :param thickness: Thickness of the text strokes 
+
+
+    :param lineType: Type of the strokes, see  :ref:`Line`  description 
+
+
+The function initializes the font structure that can be passed to text rendering functions.
+
+.. seealso:: :ocv:cfunc:`PutText`
+
 
 line
 --------
+Draws a line segment connecting two points.
+
 .. ocv:function:: void line(Mat& img, Point pt1, Point pt2, const Scalar& color,          int thickness=1, int lineType=8, int shift=0)
 
-    Draws a line segment connecting two points.
+.. ocv:pyfunction:: cv2.line(img, pt1, pt2, color[, thickness[, lineType[, shift]]]) -> None
+
+.. ocv:cfunction:: void cvLine( CvArr* img, CvPoint pt1, CvPoint pt2, CvScalar color, int thickness=1, int lineType=8, int shift=0 )
+.. ocv:pyoldfunction:: cv.Line(img, pt1, pt2, color, thickness=1, lineType=8, shift=0)-> None
 
     :param img: Image.
 
@@ -269,13 +350,10 @@ line
 The function ``line`` draws the line segment between ``pt1`` and ``pt2`` points in the image. The line is clipped by the image boundaries. For non-antialiased lines with integer coordinates, the 8-connected or 4-connected Bresenham algorithm is used. Thick lines are drawn with rounding endings.
 Antialiased lines are drawn using Gaussian filtering. To specify the line color, you may use the macro ``CV_RGB(r, g, b)`` .
 
-.. index:: LineIterator
-
-.. _LineIterator:
 
 LineIterator
 ------------
-.. c:type:: LineIterator
+.. ocv:class:: LineIterator
 
 Class for iterating pixels on a raster line. ::
 
@@ -315,15 +393,20 @@ The number of pixels along the line is stored in ``LineIterator::count`` . ::
     for(int i = 0; i < it.count; i++, ++it)
         buf[i] = *(const Vec3b)*it;
 
-.. index:: rectangle
+
 
 rectangle
 -------------
+Draws a simple, thick, or filled up-right rectangle.
+
 .. ocv:function:: void rectangle(Mat& img, Point pt1, Point pt2, const Scalar& color, int thickness=1,               int lineType=8, int shift=0)
 
 .. ocv:function:: void rectangle(Mat& img, Rect r, const Scalar& color, int thickness=1,               int lineType=8, int shift=0)
 
-    Draws a simple, thick, or filled up-right rectangle.
+.. ocv:pyfunction:: cv2.rectangle(img, pt1, pt2, color[, thickness[, lineType[, shift]]]) -> None
+
+.. ocv:cfunction:: void cvRectangle( CvArr* img, CvPoint pt1, CvPoint pt2, CvScalar color, int thickness=1, int lineType=8, int shift=0 )
+.. ocv:pyoldfunction:: cv.Rectangle(img, pt1, pt2, color, thickness=1, lineType=8, shift=0)-> None
 
     :param img: Image.
 
@@ -343,13 +426,19 @@ rectangle
 
 The function ``rectangle`` draws a rectangle outline or a filled rectangle whose two opposite corners are ``pt1`` and ``pt2``, or ``r.tl()`` and ``r.br()-Point(1,1)``.
 
-.. index:: polylines
+
 
 polylines
 -------------
-.. ocv:function:: void polylines(Mat& img, const Point** pts, const int* npts,               int ncontours, bool isClosed, const Scalar& color,               int thickness=1, int lineType=8, int shift=0 )
+Draws several polygonal curves.
+
+.. ocv:function:: void polylines(Mat& img, const Point** pts, const int* npts, int ncontours, bool isClosed, const Scalar& color, int thickness=1, int lineType=8, int shift=0 )
+
+.. ocv:pyfunction:: cv2.polylines(img, pts, isClosed, color[, thickness[, lineType[, shift]]]) -> None
+
+.. ocv:cfunction:: void cvPolyLine( CvArr* img, CvPoint** pts, int* npts, int contours, int isClosed, CvScalar color, int thickness=1, int lineType=8, int shift=0 )
 
-    Draws several polygonal curves.
+.. ocv:pyoldfunction:: cv.PolyLine(img, polys, isClosed, color, thickness=1, lineType=8, shift=0)-> None
 
     :param img: Image.
 
@@ -371,13 +460,18 @@ polylines
 
 The function ``polylines`` draws one or more polygonal curves.
 
-.. index:: putText
+
 
 putText
 -----------
+Draws a text string.
+
 .. ocv:function:: void putText( Mat& img, const string& text, Point org,              int fontFace, double fontScale, Scalar color,              int thickness=1, int lineType=8,              bool bottomLeftOrigin=false )
 
-    Draws a text string.
+.. ocv:pyfunction:: cv2.putText(img, text, org, fontFace, fontScale, color[, thickness[, linetype[, bottomLeftOrigin]]]) -> None
+
+.. ocv:cfunction:: void cvPutText( CvArr* img, const char* text, CvPoint org, const CvFont* font, CvScalar color )
+.. ocv:pyoldfunction:: cv.PutText(img, text, org, font, color)-> None
 
     :param img: Image.
 
@@ -385,6 +479,8 @@ putText
 
     :param org: Bottom-left corner of the text string in the image.
 
+    :param font: ``CvFont`` structure initialized using :ocv:cfunc:`InitFont`.
+
     :param fontFace: Font type. One of  ``FONT_HERSHEY_SIMPLEX``,  ``FONT_HERSHEY_PLAIN``, ``FONT_HERSHEY_DUPLEX``,  ``FONT_HERSHEY_COMPLEX``,  ``FONT_HERSHEY_TRIPLEX``, ``FONT_HERSHEY_COMPLEX_SMALL``,  ``FONT_HERSHEY_SCRIPT_SIMPLEX``, or  ``FONT_HERSHEY_SCRIPT_COMPLEX``,
            where each of the font ID's can be combined with  ``FONT_HERSHEY_ITALIC``  to get the slanted letters.
 
diff --git a/modules/core/doc/dynamic_structures.rst b/modules/core/doc/dynamic_structures.rst
new file mode 100644 (file)
index 0000000..a92f95e
--- /dev/null
@@ -0,0 +1,1549 @@
+Dynamic Structures
+==================
+
+.. highlight:: c
+
+The section describes OpenCV 1.x API for creating growable sequences and other dynamic data structures allocated in ``CvMemStorage``. If you use the new C++, Python, Java etc interface, you will unlikely need this functionality. Use ``std::vector`` or other high-level data structures.
+
+CvMemStorage
+------------
+
+.. ocv:struct:: CvMemStorage
+
+A storage for various OpenCV dynamic data structures, such as ``CvSeq``, ``CvSet`` etc.
+
+    .. ocv:member:: CvMemBlock* bottom
+    
+        the first memory block in the double-linked list of blocks
+    
+    .. ocv:member:: CvMemBlock* top
+        
+        the current partially allocated memory block in the list of blocks
+    
+    .. ocv:member:: CvMemStorage* parent
+    
+        the parent storage (if any) from which the new memory blocks are borrowed.
+        
+    .. ocv:member:: int free_space
+    
+        number of free bytes in the ``top`` block
+        
+    .. ocv:member:: int block_size
+    
+        the total size of the memory blocks
+
+Memory storage is a low-level structure used to store dynamically growing data structures such as sequences, contours, graphs, subdivisions, etc. It is organized as a list of memory blocks of equal size - 
+``bottom`` field is the beginning of the list of blocks and ``top`` is the currently used block, but not necessarily the last block of the list. All blocks between ``bottom`` and ``top``, not including the
+latter, are considered fully occupied; all blocks between ``top`` and the last block, not including  ``top``, are considered free and ``top`` itself is partly ocupied - ``free_space`` contains the number of free bytes left in the end of ``top``.
+
+A new memory buffer that may be allocated explicitly by :ocv:cfunc:`MemStorageAlloc` function or implicitly by higher-level functions, such as :ocv:cfunc:`SeqPush`,  :ocv:cfunc:`GraphAddEdge` etc. 
+
+The buffer is put in the end of already allocated space in the ``top`` memory block, if there is enough free space. After allocation, ``free_space`` is decreased by the size of the allocated buffer plus some padding to keep the proper alignment. When the allocated buffer does not fit into the available portion of 
+``top``, the next storage block from the list is taken as ``top`` and  ``free_space`` is reset to the whole block size prior to the allocation.
+
+If there are no more free blocks, a new block is allocated (or borrowed from the parent, see :ocv:cfunc:`CreateChildMemStorage`) and added to the end of list. Thus, the storage behaves as a stack with ``bottom`` indicating bottom of the stack and the pair (``top``, ``free_space``)
+indicating top of the stack. The stack top may be saved via :ocv:cfunc:`SaveMemStoragePos`, restored via 
+:ocv:cfunc:`RestoreMemStoragePos`, or reset via :ocv:cfunc:`ClearStorage`.
+
+CvMemBlock
+----------
+
+.. ocv:struct:: CvMemBlock
+
+The structure :ocv:struct:`CvMemBlock` represents a single block of memory storage. The actual data in the memory blocks follows the header.
+
+CvMemStoragePos
+---------------
+
+.. ocv:struct:: CvMemStoragePos
+
+The structure stores the position in the memory storage. It is used by :ocv:cfunc:`SaveMemStoragePos` and  :ocv:cfunc:`RestoreMemStoragePos`.
+
+CvSeq
+-----
+
+.. ocv:struct:: CvSeq
+
+Dynamically growing sequence.
+
+    .. ocv:member:: int flags
+    
+        sequence flags, including the sequence signature (CV_SEQ_MAGIC_VAL or CV_SET_MAGIC_VAL), type of the elements and some other information about the sequence.
+        
+    .. ocv:member:: int header_size
+    
+        size of the sequence header. It should be sizeof(CvSeq) at minimum. See :ocv:cfunc:`CreateSeq`.
+        
+    .. ocv:member:: CvSeq* h_prev
+    .. ocv:member:: CvSeq* h_next
+    .. ocv:member:: CvSeq* v_prev
+    .. ocv:member:: CvSeq* v_next
+    
+        pointers to another sequences in a sequence tree. Sequence trees are used to store hierarchical contour structures, retrieved by :ocv:cfunc:`FindContours`
+
+    .. ocv:member:: int total
+    
+        the number of sequence elements
+        
+    .. ocv:member:: int elem_size
+    
+        size of each sequence element in bytes
+        
+    .. ocv:member:: CvMemStorage* storage
+    
+        memory storage where the sequence resides. It can be a NULL pointer.
+        
+    .. ocv:member:: CvSeqBlock* first
+    
+        pointer to the first data block
+
+The structure ``CvSeq`` is a base for all of OpenCV dynamic data structures.        
+There are two types of sequences - dense and sparse. The base type for dense
+sequences is  :ocv:struct:`CvSeq` and such sequences are used to represent
+growable 1d arrays - vectors, stacks, queues, and deques. They have no gaps
+in the middle - if an element is removed from the middle or inserted
+into the middle of the sequence, the elements from the closer end are
+shifted. Sparse sequences have  :ocv:struct:`CvSet` as a base class and they are
+discussed later in more detail. They are sequences of nodes; each may be either occupied or free as indicated by the node flag. Such sequences are used for unordered data structures such as sets of elements, graphs, hash tables and so forth.
+
+
+CvSlice
+-------
+
+.. ocv:struct:: CvSlice
+
+A sequence slice. In C++ interface the class :ocv:class:`Range` should be used instead.
+
+    .. ocv:member: int start_index
+    
+        inclusive start index of the sequence slice
+        
+    .. ocv:member: int end_index
+    
+        exclusive end index of the sequence slice
+
+There are helper functions to construct the slice and to compute its length: ::
+    
+    inline CvSlice cvSlice( int start, int end );
+    #define CV_WHOLE_SEQ_END_INDEX 0x3fffffff
+    #define CV_WHOLE_SEQ  cvSlice(0, CV_WHOLE_SEQ_END_INDEX)
+    
+    /* calculates the sequence slice length */
+    int cvSliceLength( CvSlice slice, const CvSeq* seq );
+
+..
+
+Some of functions that operate on sequences take a ``CvSlice slice`` parameter that is often set to the whole sequence (CV_WHOLE_SEQ) by default. Either of the ``start_index`` and  ``end_index`` may be negative or exceed the sequence length. If they are equal, the slice is considered empty (i.e., contains no elements). Because sequences are treated as circular structures, the slice may select a
+few elements in the end of a sequence followed by a few elements at the beginning of the sequence. For example,  ``cvSlice(-2, 3)`` in the case of a 10-element sequence will select a 5-element slice, containing the pre-last (8th), last (9th), the very first (0th), second (1th) and third (2nd)
+elements. The functions normalize the slice argument in the following way:
+
+  #. :ocv:cfunc:`SliceLength` is called to determine the length of the slice,
+  #. ``start_index`` of the slice is normalized similarly to the argument of :ocv:cfunc:`GetSeqElem` (i.e., negative indices are allowed). The actual slice to process starts at the normalized  ``start_index`` and lasts :ocv:cfunc:`SliceLength` elements (again, assuming the sequence is a circular structure).
+
+If a function does not accept a slice argument, but you want to process only a part of the sequence, the sub-sequence may be extracted using the :ocv:cfunc:`SeqSlice` function, or stored into a continuous
+buffer with :ocv:cfunc:`CvtSeqToArray` (optionally, followed by :ocv:cfunc:`MakeSeqHeaderForArray`).
+
+CvSet
+-----
+
+.. ocv:struct:: CvSet
+
+The structure ``CvSet`` is a base for OpenCV 1.x sparse data structures. It is derived from  :ocv:struct:`CvSeq` and includes an additional member ``free_elems`` - a list of free nodes. Every node of the set, whether free or not, is an element of the underlying sequence. While there are no restrictions on elements of dense sequences, the set (and derived structures) elements must start with an integer field and be able to fit CvSetElem structure, because these two fields (an integer followed by a pointer) are required for the organization of a node set with the list of free nodes. If a node is free, the ``flags``
+field is negative (the most-significant bit, or MSB, of the field is set), and the ``next_free`` points to the next free node (the first free node is referenced by the ``free_elems`` field of :ocv:struct:`CvSet`). And if a node is occupied, the ``flags`` field is positive and contains the node index that may be retrieved using the (``set_elem->flags & CV_SET_ELEM_IDX_MASK``) expressions, the rest of the node content is determined by the user. In particular, the occupied nodes are not linked as the free nodes are, so the second field can be used for such a link as well as for some different purpose. The macro ``CV_IS_SET_ELEM(set_elem_ptr)`` can be used to determined whether the specified node is occupied or not.
+
+Initially the set and the free node list are empty. When a new node is requested from the set, it is taken from the list of free nodes, which is then updated. If the list appears to be empty, a new sequence block is allocated and all the nodes within the block are joined in the list of free nodes. Thus, the ``total``
+field of the set is the total number of nodes both occupied and free. When an occupied node is released, it is added to the list of free nodes. The node released last will be occupied first.
+
+``CvSet`` is used to represent graphs (:ocv:struct:`CvGraph`), sparse multi-dimensional arrays (:ocv:struct:`CvSparseMat`), and planar subdivisions (:ocv:struct:`CvSubdiv2D`).
+
+
+CvGraph
+-------
+.. ocv:struct:: CvGraph
+
+The structure ``CvGraph`` is a base for graphs used in OpenCV 1.x. It inherits from 
+:ocv:struct:`CvSet`, that is, it is considered as a set of vertices. Besides, it contains another set as a member, a set of graph edges. Graphs in OpenCV are represented using adjacency lists format.
+
+
+CvGraphScanner
+--------------
+
+.. ocv:struct:: CvGraphScanner
+
+The structure ``CvGraphScanner`` is used for depth-first graph traversal. See discussion of the functions below.
+
+
+CvTreeNodeIterator
+------------------
+
+The structure ``CvTreeNodeIterator`` is used to traverse trees of sequences.
+
+ClearGraph
+----------
+Clears a graph.
+
+.. ocv:cfunction:: void cvClearGraph( CvGraph* graph )
+
+    :param graph: Graph
+
+The function removes all vertices and edges from a graph. The function has O(1) time complexity.
+
+ClearMemStorage
+---------------
+Clears memory storage.
+
+.. ocv:cfunction:: void cvClearMemStorage( CvMemStorage* storage )
+
+    :param storage: Memory storage
+
+The function resets the top (free space boundary) of the storage to the very beginning. This function does not deallocate any memory. If the storage has a parent, the function returns
+all blocks to the parent.
+
+ClearSeq
+--------
+Clears a sequence.
+
+.. ocv:cfunction:: void cvClearSeq( CvSeq* seq )
+
+    :param seq: Sequence
+
+The function removes all elements from a sequence. The function does not return the memory to the storage block, but this memory is reused later when new elements are added to the sequence. The function has
+'O(1)' time complexity.
+
+.. note:: It is impossible to deallocate a sequence, i.e. free space in the memory storage occupied by the sequence. Instead, call :ocv:cfunc:`ClearMemStorage` or :ocv:cfunc:`ReleaseMemStorage` from time to time somewhere in a top-level processing loop.
+
+ClearSet
+--------
+Clears a set.
+
+.. ocv:cfunction:: void cvClearSet( CvSet* setHeader )
+
+    :param setHeader: Cleared set
+
+The function removes all elements from set. It has O(1) time complexity.
+
+CloneGraph
+----------
+Clones a graph.
+
+.. ocv:cfunction:: CvGraph* cvCloneGraph(  const CvGraph* graph, CvMemStorage* storage )
+
+    :param graph: The graph to copy
+
+    :param storage: Container for the copy
+
+The function creates a full copy of the specified graph. If the
+graph vertices or edges have pointers to some external data, it can still be
+shared between the copies. The vertex and edge indices in the new graph
+may be different from the original because the function defragments
+the vertex and edge sets.
+
+CloneSeq
+--------
+Creates a copy of a sequence.
+
+.. ocv:cfunction:: CvSeq* cvCloneSeq(  const CvSeq* seq, CvMemStorage* storage=NULL )
+.. ocv:pyoldfunction:: cv.CloneSeq(seq, storage)-> None
+
+    :param seq: Sequence
+
+    :param storage: The destination storage block to hold the new sequence header and the copied data, if any. If it is NULL, the function uses the storage block containing the input sequence.
+
+The function makes a complete copy of the input sequence and returns it.
+
+The call ``cvCloneSeq( seq, storage )`` is equivalent to ``cvSeqSlice( seq, CV_WHOLE_SEQ, storage, 1 )``.
+
+
+CreateChildMemStorage
+---------------------
+Creates child memory storage.
+
+.. ocv:cfunction:: CvMemStorage* cvCreateChildMemStorage(CvMemStorage* parent)
+
+    :param parent: Parent memory storage
+
+The function creates a child memory
+storage that is similar to simple memory storage except for the
+differences in the memory allocation/deallocation mechanism. When a
+child storage needs a new block to add to the block list, it tries
+to get this block from the parent. The first unoccupied parent block
+available is taken and excluded from the parent block list. If no blocks
+are available, the parent either allocates a block or borrows one from
+its own parent, if any. In other words, the chain, or a more complex
+structure, of memory storages where every storage is a child/parent of
+another is possible. When a child storage is released or even cleared,
+it returns all blocks to the parent. In other aspects, child storage
+is the same as simple storage.
+
+Child storage is useful in the following situation. Imagine
+that the user needs to process dynamic data residing in a given storage area and
+put the result back to that same storage area. With the simplest approach,
+when temporary data is resided in the same storage area as the input and
+output data, the storage area will look as follows after processing:
+
+Dynamic data processing without using child storage
+
+.. image:: pics/memstorage1.png
+
+That is, garbage appears in the middle of the storage. However, if
+one creates a child memory storage at the beginning of processing,
+writes temporary data there, and releases the child storage at the end,
+no garbage will appear in the source/destination storage:
+
+Dynamic data processing using a child storage
+
+.. image:: pics/memstorage2.png
+
+CreateGraph
+-----------
+Creates an empty graph.
+
+.. ocv:cfunction:: CvGraph* cvCreateGraph(  int graph_flags, int header_size, int vtx_size, int edge_size, CvMemStorage* storage )
+
+
+    :param graph_flags: Type of the created graph. Usually, it is either  ``CV_SEQ_KIND_GRAPH``  for generic unoriented graphs and ``CV_SEQ_KIND_GRAPH | CV_GRAPH_FLAG_ORIENTED``  for generic oriented graphs.
+
+    :param header_size: Graph header size; may not be less than  ``sizeof(CvGraph)``
+
+    :param vtx_size: Graph vertex size; the custom vertex structure must start with  :ocv:struct:`CvGraphVtx`  (use  ``CV_GRAPH_VERTEX_FIELDS()`` )
+
+    :param edge_size: Graph edge size; the custom edge structure must start with  :ocv:struct:`CvGraphEdge`  (use  ``CV_GRAPH_EDGE_FIELDS()`` )
+
+    :param storage: The graph container
+
+The function creates an empty graph and returns a pointer to it.
+
+CreateGraphScanner
+------------------
+Creates structure for depth-first graph traversal.
+
+.. ocv:cfunction:: CvGraphScanner*  cvCreateGraphScanner(  CvGraph* graph, CvGraphVtx* vtx=NULL, int mask=CV_GRAPH_ALL_ITEMS )
+    
+
+    :param graph: Graph
+
+    :param vtx: Initial vertex to start from. If NULL, the traversal starts from the first vertex (a vertex with the minimal index in the sequence of vertices).
+
+    :param mask: Event mask indicating which events are of interest to the user (where  :ocv:cfunc:`NextGraphItem`  function returns control to the user) It can be  ``CV_GRAPH_ALL_ITEMS``  (all events are of interest) or a combination of the following flags:
+
+            * **CV_GRAPH_VERTEX** stop at the graph vertices visited for the first time 
+            
+            * **CV_GRAPH_TREE_EDGE** stop at tree edges ( ``tree edge``  is the edge connecting the last visited vertex and the vertex to be visited next) 
+            
+            * **CV_GRAPH_BACK_EDGE** stop at back edges ( ``back edge``  is an edge connecting the last visited vertex with some of its ancestors in the search tree) 
+            
+            * **CV_GRAPH_FORWARD_EDGE** stop at forward edges ( ``forward edge``  is an edge conecting the last visited vertex with some of its descendants in the search tree. The forward edges are only possible during oriented graph traversal) 
+            
+            * **CV_GRAPH_CROSS_EDGE** stop at cross edges ( ``cross edge``  is an edge connecting different search trees or branches of the same tree. The  ``cross edges``  are only possible during oriented graph traversal) 
+            
+            * **CV_GRAPH_ANY_EDGE** stop at any edge ( ``tree, back, forward`` , and  ``cross edges`` ) 
+            
+            * **CV_GRAPH_NEW_TREE** stop in the beginning of every new search tree. When the traversal procedure visits all vertices and edges reachable from the initial vertex (the visited vertices together with tree edges make up a tree), it searches for some unvisited vertex in the graph and resumes the traversal process from that vertex. Before starting a new tree (including the very first tree when  ``cvNextGraphItem``  is called for the first time) it generates a  ``CV_GRAPH_NEW_TREE``  event. For unoriented graphs, each search tree corresponds to a connected component of the graph. 
+            
+            * **CV_GRAPH_BACKTRACKING** stop at every already visited vertex during backtracking - returning to already visited vertexes of the traversal tree.
+
+The function creates a structure for depth-first graph traversal/search. The initialized structure is used in the 
+:ocv:cfunc:`NextGraphItem`
+function - the incremental traversal procedure.
+
+CreateMemStorage
+----------------
+Creates memory storage.
+
+.. ocv:cfunction:: CvMemStorage* cvCreateMemStorage( int blockSize=0 )
+.. ocv:pyoldfunction:: cv.CreateMemStorage(blockSize=0) -> memstorage
+    
+
+    :param blockSize: Size of the storage blocks in bytes. If it is 0, the block size is set to a default value - currently it is  about 64K.
+
+The function creates an empty memory storage. See 
+:ocv:struct:`CvMemStorage`
+description.
+
+CreateSeq
+---------
+Creates a sequence.
+
+.. ocv:cfunction:: CvSeq* cvCreateSeq(  int seqFlags, int headerSize, int elemSize, CvMemStorage* storage)
+    
+
+    :param seqFlags: Flags of the created sequence. If the sequence is not passed to any function working with a specific type of sequences, the sequence value may be set to 0, otherwise the appropriate type must be selected from the list of predefined sequence types.
+
+    :param headerSize: Size of the sequence header; must be greater than or equal to  ``sizeof(CvSeq)`` . If a specific type or its extension is indicated, this type must fit the base type header.
+
+    :param elemSize: Size of the sequence elements in bytes. The size must be consistent with the sequence type. For example, for a sequence of points to be created, the element type    ``CV_SEQ_ELTYPE_POINT``  should be specified and the parameter  ``elemSize``  must be equal to  ``sizeof(CvPoint)`` .
+
+    :param storage: Sequence location
+
+The function creates a sequence and returns
+the pointer to it. The function allocates the sequence header in
+the storage block as one continuous chunk and sets the structure
+fields 
+``flags``
+, 
+``elemSize``
+, 
+``headerSize``
+, and
+``storage``
+to passed values, sets 
+``delta_elems``
+to the
+default value (that may be reassigned using the 
+:ocv:cfunc:`SetSeqBlockSize`
+function), and clears other header fields, including the space following
+the first 
+``sizeof(CvSeq)``
+bytes.
+
+CreateSet
+---------
+Creates an empty set.
+
+.. ocv:cfunction:: CvSet* cvCreateSet(  int set_flags, int header_size, int elem_size, CvMemStorage* storage )
+
+    :param set_flags: Type of the created set
+
+    :param header_size: Set header size; may not be less than  ``sizeof(CvSet)``
+
+    :param elem_size: Set element size; may not be less than  :ocv:struct:`CvSetElem`
+
+    :param storage: Container for the set
+
+The function creates an empty set with a specified header size and element size, and returns the pointer to the set. This function is just a thin layer on top of 
+:ocv:cfunc:`CreateSeq`.
+
+CvtSeqToArray
+-------------
+Copies a sequence to one continuous block of memory.
+
+.. ocv:cfunction:: void* cvCvtSeqToArray(  const CvSeq* seq, void* elements, CvSlice slice=CV_WHOLE_SEQ )
+
+    :param seq: Sequence
+
+    :param elements: Pointer to the destination array that must be large enough. It should be a pointer to data, not a matrix header.
+
+    :param slice: The sequence portion to copy to the array
+
+The function copies the entire sequence or subsequence to the specified buffer and returns the pointer to the buffer.
+
+EndWriteSeq
+-----------
+Finishes the process of writing a sequence.
+
+.. ocv:cfunction:: CvSeq* cvEndWriteSeq( CvSeqWriter* writer )
+
+    :param writer: Writer state
+
+The function finishes the writing process and
+returns the pointer to the written sequence. The function also truncates
+the last incomplete sequence block to return the remaining part of the
+block to memory storage. After that, the sequence can be read and
+modified safely. See 
+:ocv:cfunc:`StartWriteSeq`
+and 
+:ocv:cfunc:`StartAppendToSeq`
+
+FindGraphEdge
+-------------
+Finds an edge in a graph.
+
+.. ocv:cfunction:: CvGraphEdge* cvFindGraphEdge( const CvGraph* graph, int start_idx, int end_idx )
+
+::
+
+    #define cvGraphFindEdge cvFindGraphEdge
+
+..
+
+    :param graph: Graph
+
+    :param start_idx: Index of the starting vertex of the edge
+
+    :param end_idx: Index of the ending vertex of the edge. For an unoriented graph, the order of the vertex parameters does not matter.
+
+The function finds the graph edge connecting two specified vertices and returns a pointer to it or NULL if the edge does not exist.
+
+FindGraphEdgeByPtr
+------------------
+Finds an edge in a graph by using its pointer.
+
+.. ocv:cfunction:: CvGraphEdge* cvFindGraphEdgeByPtr(  const CvGraph* graph, const CvGraphVtx* startVtx, const CvGraphVtx* endVtx )
+
+::
+
+    #define cvGraphFindEdgeByPtr cvFindGraphEdgeByPtr
+
+..
+
+    :param graph: Graph
+
+    :param startVtx: Pointer to the starting vertex of the edge
+
+    :param endVtx: Pointer to the ending vertex of the edge. For an unoriented graph, the order of the vertex parameters does not matter.
+
+The function finds the graph edge connecting two specified vertices and returns pointer to it or NULL if the edge does not exists.
+
+FlushSeqWriter
+--------------
+Updates sequence headers from the writer.
+
+.. ocv:cfunction:: void cvFlushSeqWriter( CvSeqWriter* writer )
+
+    :param writer: Writer state
+
+The function is intended to enable the user to
+read sequence elements, whenever required, during the writing process,
+e.g., in order to check specific conditions. The function updates the
+sequence headers to make reading from the sequence possible. The writer
+is not closed, however, so that the writing process can be continued at
+any time. If an algorithm requires frequent flushes, consider using
+:ocv:cfunc:`SeqPush`
+instead.
+
+GetGraphVtx
+-----------
+Finds a graph vertex by using its index.
+
+.. ocv:cfunction:: CvGraphVtx* cvGetGraphVtx(  CvGraph* graph, int vtx_idx )
+
+    :param graph: Graph
+
+    :param vtx_idx: Index of the vertex
+
+The function finds the graph vertex by using its index and returns the pointer to it or NULL if the vertex does not belong to the graph.
+
+GetSeqElem
+----------
+Returns a pointer to a sequence element according to its index.
+
+.. ocv:cfunction:: char* cvGetSeqElem( const CvSeq* seq, int index )
+
+::
+
+    #define CV_GET_SEQ_ELEM( TYPE, seq, index )  (TYPE*)cvGetSeqElem( (CvSeq*)(seq), (index) )
+
+..
+
+    :param seq: Sequence
+
+    :param index: Index of element
+
+The function finds the element with the given
+index in the sequence and returns the pointer to it. If the element
+is not found, the function returns 0. The function supports negative
+indices, where -1 stands for the last sequence element, -2 stands for
+the one before last, etc. If the sequence is most likely to consist of
+a single sequence block or the desired element is likely to be located
+in the first block, then the macro
+``CV_GET_SEQ_ELEM( elemType, seq, index )``
+should be used, where the parameter 
+``elemType``
+is the
+type of sequence elements ( 
+:ocv:struct:`CvPoint`
+for example), the parameter
+``seq``
+is a sequence, and the parameter 
+``index``
+is the index
+of the desired element. The macro checks first whether the desired element
+belongs to the first block of the sequence and returns it if it does;
+otherwise the macro calls the main function 
+``GetSeqElem``
+. Negative
+indices always cause the 
+:ocv:cfunc:`GetSeqElem`
+call. The function has O(1)
+time complexity assuming that the number of blocks is much smaller than the
+number of elements.
+
+GetSeqReaderPos
+---------------
+Returns the current reader position.
+
+.. ocv:cfunction:: int cvGetSeqReaderPos( CvSeqReader* reader )
+
+    :param reader: Reader state
+
+The function returns the current reader position (within 0 ... 
+``reader->seq->total``
+- 1).
+
+GetSetElem
+----------
+Finds a set element by its index.
+
+.. ocv:cfunction:: CvSetElem* cvGetSetElem(  const CvSet* setHeader, int index )
+
+    :param setHeader: Set
+
+    :param index: Index of the set element within a sequence
+
+The function finds a set element by its index. The function returns the pointer to it or 0 if the index is invalid or the corresponding node is free. The function supports negative indices as it uses 
+:ocv:cfunc:`GetSeqElem`
+to locate the node.
+
+GraphAddEdge
+------------
+Adds an edge to a graph.
+
+.. ocv:cfunction:: int cvGraphAddEdge(  CvGraph* graph, int start_idx, int end_idx, const CvGraphEdge* edge=NULL, CvGraphEdge** inserted_edge=NULL )
+
+    :param graph: Graph
+
+    :param start_idx: Index of the starting vertex of the edge
+
+    :param end_idx: Index of the ending vertex of the edge. For an unoriented graph, the order of the vertex parameters does not matter.
+
+    :param edge: Optional input parameter, initialization data for the edge
+
+    :param inserted_edge: Optional output parameter to contain the address of the inserted edge
+
+The function connects two specified vertices. The function returns 1 if the edge has been added successfully, 0 if the edge connecting the two vertices exists already and -1 if either of the vertices was not found, the starting and the ending vertex are the same, or there is some other critical situation. In the latter case (i.e., when the result is negative), the function also reports an error by default.
+
+GraphAddEdgeByPtr
+-----------------
+Adds an edge to a graph by using its pointer.
+
+.. ocv:cfunction:: int cvGraphAddEdgeByPtr(  CvGraph* graph, CvGraphVtx* start_vtx, CvGraphVtx* end_vtx, const CvGraphEdge* edge=NULL, CvGraphEdge** inserted_edge=NULL )
+
+    :param graph: Graph
+
+    :param start_vtx: Pointer to the starting vertex of the edge
+
+    :param end_vtx: Pointer to the ending vertex of the edge. For an unoriented graph, the order of the vertex parameters does not matter.
+
+    :param edge: Optional input parameter, initialization data for the edge
+
+    :param inserted_edge: Optional output parameter to contain the address of the inserted edge within the edge set
+
+The function connects two specified vertices. The
+function returns 1 if the edge has been added successfully, 0 if the
+edge connecting the two vertices exists already, and -1 if either of the
+vertices was not found, the starting and the ending vertex are the same
+or there is some other critical situation. In the latter case (i.e., when
+the result is negative), the function also reports an error by default.
+
+GraphAddVtx
+-----------
+Adds a vertex to a graph.
+
+.. ocv:cfunction:: int cvGraphAddVtx(  CvGraph* graph, const CvGraphVtx* vtx=NULL, CvGraphVtx** inserted_vtx=NULL )
+
+    :param graph: Graph
+
+    :param vtx: Optional input argument used to initialize the added vertex (only user-defined fields beyond  ``sizeof(CvGraphVtx)``  are copied)
+
+    :param inserted_vertex: Optional output argument. If not  ``NULL`` , the address of the new vertex is written here.
+
+The function adds a vertex to the graph and returns the vertex index.
+
+GraphEdgeIdx
+------------
+Returns the index of a graph edge.
+
+.. ocv:cfunction:: int cvGraphEdgeIdx(  CvGraph* graph, CvGraphEdge* edge )
+
+    :param graph: Graph
+
+    :param edge: Pointer to the graph edge
+
+The function returns the index of a graph edge.
+
+GraphRemoveEdge
+---------------
+Removes an edge from a graph.
+
+.. ocv:cfunction:: void cvGraphRemoveEdge(  CvGraph* graph, int start_idx, int end_idx )
+
+    :param graph: Graph
+
+    :param start_idx: Index of the starting vertex of the edge
+
+    :param end_idx: Index of the ending vertex of the edge. For an unoriented graph, the order of the vertex parameters does not matter.
+
+The function removes the edge connecting two specified vertices. If the vertices are not connected [in that order], the function does nothing.
+
+GraphRemoveEdgeByPtr
+--------------------
+Removes an edge from a graph by using its pointer.
+
+.. ocv:cfunction:: void cvGraphRemoveEdgeByPtr(  CvGraph* graph, CvGraphVtx* start_vtx, CvGraphVtx* end_vtx )
+
+    :param graph: Graph
+
+    :param start_vtx: Pointer to the starting vertex of the edge
+
+    :param end_vtx: Pointer to the ending vertex of the edge. For an unoriented graph, the order of the vertex parameters does not matter.
+
+The function removes the edge connecting two specified vertices. If the vertices are not connected [in that order], the function does nothing.
+
+GraphRemoveVtx
+--------------
+Removes a vertex from a graph.
+
+.. ocv:cfunction:: int cvGraphRemoveVtx(  CvGraph* graph, int index )
+
+    :param graph: Graph
+
+    :param vtx_idx: Index of the removed vertex
+
+The function removes a vertex from a graph
+together with all the edges incident to it. The function reports an error
+if the input vertex does not belong to the graph. The return value is the
+number of edges deleted, or -1 if the vertex does not belong to the graph.
+
+GraphRemoveVtxByPtr
+-------------------
+Removes a vertex from a graph by using its pointer.
+
+.. ocv:cfunction:: int cvGraphRemoveVtxByPtr(  CvGraph* graph, CvGraphVtx* vtx )
+
+    :param graph: Graph
+
+    :param vtx: Pointer to the removed vertex
+
+The function removes a vertex from the graph by using its pointer together with all the edges incident to it. The function reports an error if the vertex does not belong to the graph. The return value is the number of edges deleted, or -1 if the vertex does not belong to the graph.
+
+GraphVtxDegree
+--------------
+Counts the number of edges indicent to the vertex.
+
+.. ocv:cfunction:: int cvGraphVtxDegree( const CvGraph* graph, int vtxIdx )
+
+    :param graph: Graph
+
+    :param vtxIdx: Index of the graph vertex
+
+The function returns the number of edges incident to the specified vertex, both incoming and outgoing. To count the edges, the following code is used:
+
+::
+
+    CvGraphEdge* edge = vertex->first; int count = 0;
+    while( edge )
+    {
+        edge = CV_NEXT_GRAPH_EDGE( edge, vertex );
+        count++;
+    }
+
+..
+
+The macro 
+``CV_NEXT_GRAPH_EDGE( edge, vertex )``
+returns the edge incident to 
+``vertex``
+that follows after 
+``edge``
+.
+
+GraphVtxDegreeByPtr
+-------------------
+Finds an edge in a graph.
+
+.. ocv:cfunction:: int cvGraphVtxDegreeByPtr(  const CvGraph* graph, const CvGraphVtx* vtx )
+
+    :param graph: Graph
+
+    :param vtx: Pointer to the graph vertex
+
+The function returns the number of edges incident to the specified vertex, both incoming and outcoming.
+
+GraphVtxIdx
+-----------
+Returns the index of a graph vertex.
+
+.. ocv:cfunction:: int cvGraphVtxIdx(  CvGraph* graph, CvGraphVtx* vtx )
+
+    :param graph: Graph
+
+    :param vtx: Pointer to the graph vertex
+
+The function returns the index of a graph vertex.
+
+InitTreeNodeIterator
+--------------------
+Initializes the tree node iterator.
+
+.. ocv:cfunction:: void cvInitTreeNodeIterator(  CvTreeNodeIterator* tree_iterator, const void* first, int max_level )
+
+    :param tree_iterator: Tree iterator initialized by the function
+
+    :param first: The initial node to start traversing from
+
+    :param max_level: The maximal level of the tree ( ``first``  node assumed to be at the first level) to traverse up to. For example, 1 means that only nodes at the same level as  ``first``  should be visited, 2 means that the nodes on the same level as  ``first``  and their direct children should be visited, and so forth.
+
+The function initializes the tree iterator. The tree is traversed in depth-first order.
+
+InsertNodeIntoTree
+------------------
+Adds a new node to a tree.
+
+.. ocv:cfunction:: void cvInsertNodeIntoTree(  void* node, void* parent, void* frame )
+
+    :param node: The inserted node
+
+    :param parent: The parent node that is already in the tree
+
+    :param frame: The top level node. If  ``parent``  and  ``frame``  are the same, the  ``v_prev``  field of  ``node``  is set to NULL rather than  ``parent`` .
+
+The function adds another node into tree. The function does not allocate any memory, it can only modify links of the tree nodes.
+
+MakeSeqHeaderForArray
+---------------------
+Constructs a sequence header for an array.
+
+.. ocv:cfunction:: CvSeq* cvMakeSeqHeaderForArray(  int seq_type, int header_size, int elem_size, void* elements, int total, CvSeq* seq, CvSeqBlock* block )
+
+    :param seq_type: Type of the created sequence
+
+    :param header_size: Size of the header of the sequence. Parameter sequence must point to the structure of that size or greater
+
+    :param elem_size: Size of the sequence elements
+
+    :param elements: Elements that will form a sequence
+
+    :param total: Total number of elements in the sequence. The number of array elements must be equal to the value of this parameter.
+
+    :param seq: Pointer to the local variable that is used as the sequence header
+
+    :param block: Pointer to the local variable that is the header of the single sequence block
+
+The function initializes a sequence
+header for an array. The sequence header as well as the sequence block are
+allocated by the user (for example, on stack). No data is copied by the
+function. The resultant sequence will consists of a single block and
+have NULL storage pointer; thus, it is possible to read its elements,
+but the attempts to add elements to the sequence will raise an error in
+most cases.
+
+MemStorageAlloc
+---------------
+Allocates a memory buffer in a storage block.
+
+.. ocv:cfunction:: void* cvMemStorageAlloc(  CvMemStorage* storage, size_t size )
+
+    :param storage: Memory storage
+
+    :param size: Buffer size
+
+The function allocates a memory buffer in
+a storage block. The buffer size must not exceed the storage block size,
+otherwise a runtime error is raised. The buffer address is aligned by
+``CV_STRUCT_ALIGN=sizeof(double)``
+(for the moment) bytes.
+
+MemStorageAllocString
+---------------------
+Allocates a text string in a storage block.
+
+.. ocv:cfunction:: CvString cvMemStorageAllocString(CvMemStorage* storage, const char* ptr, int len=-1)
+
+::
+
+    typedef struct CvString
+    {
+        int len;
+        char* ptr;
+    }
+    CvString;
+
+..
+
+    :param storage: Memory storage
+
+    :param ptr: The string
+
+    :param len: Length of the string (not counting the ending  ``NUL`` ) . If the parameter is negative, the function computes the length.
+
+The function creates copy of the string
+in memory storage. It returns the structure that contains user-passed
+or computed length of the string and pointer to the copied string.
+
+NextGraphItem
+-------------
+Executes one or more steps of the graph traversal procedure.
+
+.. ocv:cfunction:: int cvNextGraphItem( CvGraphScanner* scanner )
+
+    :param scanner: Graph traversal state. It is updated by this function.
+
+The function traverses through the graph
+until an event of interest to the user (that is, an event, specified
+in the 
+``mask``
+in the 
+:ocv:cfunc:`CreateGraphScanner`
+call) is met or the
+traversal is completed. In the first case, it returns one of the events
+listed in the description of the 
+``mask``
+parameter above and with
+the next call it resumes the traversal. In the latter case, it returns
+``CV_GRAPH_OVER``
+(-1). When the event is 
+``CV_GRAPH_VERTEX``
+,
+``CV_GRAPH_BACKTRACKING``
+, or 
+``CV_GRAPH_NEW_TREE``
+,
+the currently observed vertex is stored in 
+``scanner-:math:`>`vtx``
+. And if the
+event is edge-related, the edge itself is stored at 
+``scanner-:math:`>`edge``
+,
+the previously visited vertex - at 
+``scanner-:math:`>`vtx``
+and the other ending
+vertex of the edge - at 
+``scanner-:math:`>`dst``
+.
+
+NextTreeNode
+------------
+Returns the currently observed node and moves the iterator toward the next node.
+
+.. ocv:cfunction:: void* cvNextTreeNode( CvTreeNodeIterator* tree_iterator )
+
+    :param tree_iterator: Tree iterator initialized by the function
+
+The function returns the currently observed node and then updates the
+iterator - moving it toward the next node. In other words, the function
+behavior is similar to the 
+``*p++``
+expression on a typical C
+pointer or C++ collection iterator. The function returns NULL if there
+are no more nodes.
+
+PrevTreeNode
+------------
+Returns the currently observed node and moves the iterator toward the previous node.
+
+.. ocv:cfunction:: void* cvPrevTreeNode( CvTreeNodeIterator* tree_iterator )
+
+    :param tree_iterator: Tree iterator initialized by the function
+
+The function returns the currently observed node and then updates
+the iterator - moving it toward the previous node. In other words,
+the function behavior is similar to the 
+``*p--``
+expression on a
+typical C pointer or C++ collection iterator. The function returns NULL
+if there are no more nodes.
+
+ReleaseGraphScanner
+-------------------
+Completes the graph traversal procedure.
+
+.. ocv:cfunction:: void cvReleaseGraphScanner( CvGraphScanner** scanner )
+
+    :param scanner: Double pointer to graph traverser
+
+The function completes the graph traversal procedure and releases the traverser state.
+
+ReleaseMemStorage
+-----------------
+Releases memory storage.
+
+.. ocv:cfunction:: void cvReleaseMemStorage( CvMemStorage** storage )
+
+    :param storage: Pointer to the released storage
+
+The function deallocates all storage memory
+blocks or returns them to the parent, if any. Then it deallocates the
+storage header and clears the pointer to the storage. All child storage 
+associated with a given parent storage block must be released before the 
+parent storage block is released.
+
+RestoreMemStoragePos
+--------------------
+Restores memory storage position.
+
+.. ocv:cfunction:: void cvRestoreMemStoragePos( CvMemStorage* storage, CvMemStoragePos* pos)
+
+    :param storage: Memory storage
+
+    :param pos: New storage top position
+
+The function restores the position of the storage top from the parameter 
+``pos``
+. This function and the function 
+``cvClearMemStorage``
+are the only methods to release memory occupied in memory blocks. Note again that there is no way to free memory in the middle of an occupied portion of a storage block.
+
+SaveMemStoragePos
+-----------------
+Saves memory storage position.
+
+.. ocv:cfunction:: void cvSaveMemStoragePos( const CvMemStorage* storage, CvMemStoragePos* pos)
+
+    :param storage: Memory storage
+
+    :param pos: The output position of the storage top
+
+The function saves the current position
+of the storage top to the parameter 
+``pos``
+. The function
+``cvRestoreMemStoragePos``
+can further retrieve this position.
+
+SeqElemIdx
+----------
+Returns the index of a specific sequence element.
+
+.. ocv:cfunction:: int cvSeqElemIdx(  const CvSeq* seq, const void* element, CvSeqBlock** block=NULL )
+
+    :param seq: Sequence
+
+    :param element: Pointer to the element within the sequence
+
+    :param block: Optional argument. If the pointer is not  ``NULL`` , the address of the sequence block that contains the element is stored in this location.
+
+The function returns the index of a sequence element or a negative number if the element is not found.
+
+SeqInsert
+---------
+Inserts an element in the middle of a sequence.
+
+.. ocv:cfunction:: char* cvSeqInsert(  CvSeq* seq, int beforeIndex, void* element=NULL )
+
+    :param seq: Sequence
+
+    :param beforeIndex: Index before which the element is inserted. Inserting before 0 (the minimal allowed value of the parameter) is equal to  :ocv:cfunc:`SeqPushFront`  and inserting before  ``seq->total``  (the maximal allowed value of the parameter) is equal to  :ocv:cfunc:`SeqPush` .
+
+    :param element: Inserted element
+
+The function shifts the sequence elements from the inserted position to the nearest end of the sequence and copies the 
+``element``
+content there if the pointer is not NULL. The function returns a pointer to the inserted element.
+
+SeqInsertSlice
+--------------
+Inserts an array in the middle of a sequence.
+
+.. ocv:cfunction:: void cvSeqInsertSlice(  CvSeq* seq, int beforeIndex, const CvArr* fromArr )
+
+    :param seq: Sequence 
+    
+    :param beforeIndex: Index before which the array is inserted
+    
+    :param fromArr: The array to take elements from
+
+The function inserts all 
+``fromArr``
+array elements at the specified position of the sequence. The array
+``fromArr``
+can be a matrix or another sequence.
+
+SeqInvert
+---------
+Reverses the order of sequence elements.
+
+.. ocv:cfunction:: void cvSeqInvert( CvSeq* seq )
+    
+    :param seq: Sequence 
+    
+The function reverses the sequence in-place - the first element becomes the last one, the last element becomes the first one and so forth.
+
+SeqPop
+------
+Removes an element from the end of a sequence.
+
+.. ocv:cfunction:: void cvSeqPop(  CvSeq* seq, void* element=NULL )
+    
+    :param seq: Sequence 
+    
+    :param element: Optional parameter . If the pointer is not zero, the function copies the removed element to this location. 
+    
+The function removes an element from a sequence. The function reports an error if the sequence is already empty. The function has O(1) complexity.
+
+SeqPopFront
+-----------
+Removes an element from the beginning of a sequence.
+
+.. ocv:cfunction:: void cvSeqPopFront(   CvSeq* seq, void* element=NULL )
+
+    :param seq: Sequence
+
+    :param element: Optional parameter. If the pointer is not zero, the function copies the removed element to this location.
+
+The function removes an element from the beginning of a sequence. The function reports an error if the sequence is already empty. The function has O(1) complexity.
+
+SeqPopMulti
+-----------
+Removes several elements from either end of a sequence.
+
+.. ocv:cfunction:: void cvSeqPopMulti(  CvSeq* seq, void* elements, int count, int in_front=0 )
+
+    :param seq: Sequence
+
+    :param elements: Removed elements
+
+    :param count: Number of elements to pop
+
+    :param in_front: The flags specifying which end of the modified sequence. 
+         
+            * **CV_BACK** the elements are added to the end of the sequence 
+            
+            * **CV_FRONT** the elements are added to the beginning of the sequence
+
+The function removes several elements from either end of the sequence. If the number of the elements to be removed exceeds the total number of elements in the sequence, the function removes as many elements as possible.
+
+SeqPush
+-------
+Adds an element to the end of a sequence.
+
+.. ocv:cfunction:: char* cvSeqPush(  CvSeq* seq, void* element=NULL )
+
+    :param seq: Sequence
+
+    :param element: Added element
+
+The function adds an element to the end of a sequence and returns a pointer to the allocated element. If the input 
+``element``
+is NULL, the function simply allocates a space for one more element.
+
+The following code demonstrates how to create a new sequence using this function:
+
+::
+
+    CvMemStorage* storage = cvCreateMemStorage(0);
+    CvSeq* seq = cvCreateSeq( CV_32SC1, /* sequence of integer elements */
+                              sizeof(CvSeq), /* header size - no extra fields */
+                              sizeof(int), /* element size */
+                              storage /* the container storage */ );
+    int i;
+    for( i = 0; i < 100; i++ )
+    {
+        int* added = (int*)cvSeqPush( seq, &i );
+        printf( "
+    }
+    
+    ...
+    /* release memory storage in the end */
+    cvReleaseMemStorage( &storage );
+
+..
+
+The function has O(1) complexity, but there is a faster method for writing large sequences (see 
+:ocv:cfunc:`StartWriteSeq`
+and related functions).
+
+SeqPushFront
+------------
+Adds an element to the beginning of a sequence.
+
+.. ocv:cfunction:: char* cvSeqPushFront( CvSeq* seq, void* element=NULL )
+
+    :param seq: Sequence
+
+    :param element: Added element
+
+The function is similar to 
+:ocv:cfunc:`SeqPush`
+but it adds the new element to the beginning of the sequence. The function has O(1) complexity.
+
+SeqPushMulti
+------------
+Pushes several elements to either end of a sequence.
+
+.. ocv:cfunction:: void cvSeqPushMulti(  CvSeq* seq, void* elements, int count, int in_front=0 )
+
+    :param seq: Sequence
+
+    :param elements: Added elements
+
+    :param count: Number of elements to push
+
+    :param in_front: The flags specifying which end of the modified sequence. 
+         
+            * **CV_BACK** the elements are added to the end of the sequence 
+            
+            * **CV_FRONT** the elements are added to the beginning of the sequence
+
+The function adds several elements to either
+end of a sequence. The elements are added to the sequence in the same
+order as they are arranged in the input array but they can fall into
+different sequence blocks.
+
+SeqRemove
+---------
+Removes an element from the middle of a sequence.
+
+.. ocv:cfunction:: void cvSeqRemove(  CvSeq* seq, int index )
+
+    :param seq: Sequence
+
+    :param index: Index of removed element
+
+The function removes elements with the given
+index. If the index is out of range the function reports an error. An
+attempt to remove an element from an empty sequence is a special
+case of this situation. The function removes an element by shifting
+the sequence elements between the nearest end of the sequence and the
+``index``
+-th position, not counting the latter.
+
+SeqRemoveSlice
+--------------
+Removes a sequence slice.
+
+.. ocv:cfunction:: void cvSeqRemoveSlice( CvSeq* seq, CvSlice slice )
+
+    :param seq: Sequence
+
+    :param slice: The part of the sequence to remove
+
+The function removes a slice from the sequence.
+
+SeqSearch
+---------
+Searches for an element in a sequence.
+
+.. ocv:cfunction:: char* cvSeqSearch( CvSeq* seq, const void* elem, CvCmpFunc func,                    int is_sorted, int* elem_idx, void* userdata=NULL )
+
+    :param seq: The sequence
+
+    :param elem: The element to look for
+
+    :param func: The comparison function that returns negative, zero or positive value depending on the relationships among the elements (see also  :ocv:cfunc:`SeqSort` )
+
+    :param is_sorted: Whether the sequence is sorted or not
+
+    :param elem_idx: Output parameter; index of the found element
+
+    :param userdata: The user parameter passed to the compasion function; helps to avoid global variables in some cases
+
+::
+
+    /* a < b ? -1 : a > b ? 1 : 0 */
+    typedef int (CV_CDECL* CvCmpFunc)(const void* a, const void* b, void* userdata);
+
+..
+
+The function searches for the element in the sequence. If
+the sequence is sorted, a binary O(log(N)) search is used; otherwise, a
+simple linear search is used. If the element is not found, the function
+returns a NULL pointer and the index is set to the number of sequence
+elements if a linear search is used, or to the smallest index
+``i, seq(i)>elem``
+.
+
+SeqSlice
+--------
+Makes a separate header for a sequence slice.
+
+.. ocv:cfunction:: CvSeq* cvSeqSlice(  const CvSeq* seq, CvSlice slice, CvMemStorage* storage=NULL, int copy_data=0 )
+
+    :param seq: Sequence
+
+    :param slice: The part of the sequence to be extracted
+
+    :param storage: The destination storage block to hold the new sequence header and the copied data, if any. If it is NULL, the function uses the storage block containing the input sequence.
+
+    :param copy_data: The flag that indicates whether to copy the elements of the extracted slice ( ``copy_data!=0`` ) or not ( ``copy_data=0`` )
+
+The function creates a sequence that represents the specified slice of the input sequence. The new sequence either shares the elements with the original sequence or has its own copy of the elements. So if one needs to process a part of sequence but the processing function does not have a slice parameter, the required sub-sequence may be extracted using this function.
+
+SeqSort
+-------
+Sorts sequence element using the specified comparison function.
+
+.. ocv:cfunction:: void cvSeqSort( CvSeq* seq, CvCmpFunc func, void* userdata=NULL )
+
+::
+
+    /* a < b ? -1 : a > b ? 1 : 0 */
+    typedef int (CV_CDECL* CvCmpFunc)(const void* a, const void* b, void* userdata);
+
+..
+
+    :param seq: The sequence to sort
+
+    :param func: The comparison function that returns a negative, zero, or positive value depending on the relationships among the elements (see the above declaration and the example below) - a similar function is used by  ``qsort``  from C runline except that in the latter,  ``userdata``  is not used
+
+    :param userdata: The user parameter passed to the compasion function; helps to avoid global variables in some cases
+
+The function sorts the sequence in-place using the specified criteria. Below is an example of using this function:
+
+::
+
+    /* Sort 2d points in top-to-bottom left-to-right order */
+    static int cmp_func( const void* _a, const void* _b, void* userdata )
+    {
+        CvPoint* a = (CvPoint*)_a;
+        CvPoint* b = (CvPoint*)_b;
+        int y_diff = a->y - b->y;
+        int x_diff = a->x - b->x;
+        return y_diff ? y_diff : x_diff;
+    }
+    
+    ...
+    
+    CvMemStorage* storage = cvCreateMemStorage(0);
+    CvSeq* seq = cvCreateSeq( CV_32SC2, sizeof(CvSeq), sizeof(CvPoint), storage );
+    int i;
+    
+    for( i = 0; i < 10; i++ )
+    {
+        CvPoint pt;
+        pt.x = rand() 
+        pt.y = rand() 
+        cvSeqPush( seq, &pt );
+    }
+    
+    cvSeqSort( seq, cmp_func, 0 /* userdata is not used here */ );
+    
+    /* print out the sorted sequence */
+    for( i = 0; i < seq->total; i++ )
+    {
+        CvPoint* pt = (CvPoint*)cvSeqElem( seq, i );
+        printf( "(
+    }
+    
+    cvReleaseMemStorage( &storage );
+
+..
+
+SetAdd
+------
+Occupies a node in the set.
+
+.. ocv:cfunction:: int cvSetAdd(  CvSet* setHeader, CvSetElem* elem=NULL, CvSetElem** inserted_elem=NULL )
+
+    :param setHeader: Set
+
+    :param elem: Optional input argument, an inserted element. If not NULL, the function copies the data to the allocated node (the MSB of the first integer field is cleared after copying).
+
+    :param inserted_elem: Optional output argument; the pointer to the allocated cell
+
+The function allocates a new node, optionally copies
+input element data to it, and returns the pointer and the index to the
+node. The index value is taken from the lower bits of the 
+``flags``
+field of the node. The function has O(1) complexity; however, there exists
+a faster function for allocating set nodes (see 
+:ocv:cfunc:`SetNew`
+).
+
+SetNew
+------
+Adds an element to a set (fast variant).
+
+.. ocv:cfunction:: CvSetElem* cvSetNew( CvSet* setHeader )
+
+    :param setHeader: Set
+
+The function is an inline lightweight variant of 
+:ocv:cfunc:`SetAdd`
+. It occupies a new node and returns a pointer to it rather than an index.
+
+SetRemove
+---------
+Removes an element from a set.
+
+.. ocv:cfunction:: void cvSetRemove(  CvSet* setHeader, int index )
+
+    :param setHeader: Set
+
+    :param index: Index of the removed element
+
+The function removes an element with a specified
+index from the set. If the node at the specified location is not occupied,
+the function does nothing. The function has O(1) complexity; however,
+:ocv:cfunc:`SetRemoveByPtr`
+provides a quicker way to remove a set element
+if it is located already.
+
+SetRemoveByPtr
+--------------
+Removes a set element based on its pointer.
+
+.. ocv:cfunction:: void cvSetRemoveByPtr(  CvSet* setHeader, void* elem )
+
+    :param setHeader: Set
+
+    :param elem: Removed element
+
+The function is an inline lightweight variant of 
+:ocv:cfunc:`SetRemove`
+that requires an element pointer. The function does not check whether the node is occupied or not - the user should take care of that.
+
+SetSeqBlockSize
+---------------
+Sets up sequence block size.
+
+.. ocv:cfunction:: void cvSetSeqBlockSize(  CvSeq* seq, int deltaElems )
+
+    :param seq: Sequence
+
+    :param deltaElems: Desirable sequence block size for elements
+
+The function affects memory allocation
+granularity. When the free space in the sequence buffers has run out,
+the function allocates the space for 
+``deltaElems``
+sequence
+elements. If this block immediately follows the one previously allocated,
+the two blocks are concatenated; otherwise, a new sequence block is
+created. Therefore, the bigger the parameter is, the lower the possible
+sequence fragmentation, but the more space in the storage block is wasted. When
+the sequence is created, the parameter 
+``deltaElems``
+is set to
+the default value of about 1K. The function can be called any time after
+the sequence is created and affects future allocations. The function
+can modify the passed value of the parameter to meet memory storage
+constraints.
+
+SetSeqReaderPos
+---------------
+Moves the reader to the specified position.
+
+.. ocv:cfunction:: void cvSetSeqReaderPos(  CvSeqReader* reader, int index, int is_relative=0 )
+
+    :param reader: Reader state
+
+    :param index: The destination position. If the positioning mode is used (see the next parameter), the actual position will be  ``index``  mod  ``reader->seq->total`` .
+
+    :param is_relative: If it is not zero, then  ``index``  is a relative to the current position
+
+The function moves the read position to an absolute position or relative to the current position.
+
+StartAppendToSeq
+----------------
+Initializes the process of writing data to a sequence.
+
+.. ocv:cfunction:: void cvStartAppendToSeq(  CvSeq* seq, CvSeqWriter* writer )
+
+    :param seq: Pointer to the sequence
+
+    :param writer: Writer state; initialized by the function
+
+The function initializes the process of
+writing data to a sequence. Written elements are added to the end of the
+sequence by using the
+``CV_WRITE_SEQ_ELEM( written_elem, writer )``
+macro. Note
+that during the writing process, other operations on the sequence may
+yield an incorrect result or even corrupt the sequence (see description of
+:ocv:cfunc:`FlushSeqWriter`
+, which helps to avoid some of these problems).
+
+StartReadSeq
+------------
+Initializes the process of sequential reading from a sequence.
+
+.. ocv:cfunction:: void cvStartReadSeq(  const CvSeq* seq, CvSeqReader* reader, int reverse=0 )
+
+    :param seq: Sequence
+
+    :param reader: Reader state; initialized by the function
+
+    :param reverse: Determines the direction of the sequence traversal. If  ``reverse``  is 0, the reader is positioned at the first sequence element; otherwise it is positioned at the last element.
+
+The function initializes the reader state. After
+that, all the sequence elements from the first one down to the last one
+can be read by subsequent calls of the macro
+``CV_READ_SEQ_ELEM( read_elem, reader )``
+in the case of forward reading and by using
+``CV_REV_READ_SEQ_ELEM( read_elem, reader )``
+in the case of reverse
+reading. Both macros put the sequence element to 
+``read_elem``
+and
+move the reading pointer toward the next element. A circular structure
+of sequence blocks is used for the reading process, that is, after the
+last element has been read by the macro 
+``CV_READ_SEQ_ELEM``
+, the
+first element is read when the macro is called again. The same applies to
+``CV_REV_READ_SEQ_ELEM``
+. There is no function to finish the reading
+process, since it neither changes the sequence nor creates any temporary
+buffers. The reader field 
+``ptr``
+points to the current element of
+the sequence that is to be read next. The code below demonstrates how
+to use the sequence writer and reader.
+
+::
+
+    CvMemStorage* storage = cvCreateMemStorage(0);
+    CvSeq* seq = cvCreateSeq( CV_32SC1, sizeof(CvSeq), sizeof(int), storage );
+    CvSeqWriter writer;
+    CvSeqReader reader;
+    int i;
+    
+    cvStartAppendToSeq( seq, &writer );
+    for( i = 0; i < 10; i++ )
+    {
+        int val = rand()
+        CV_WRITE_SEQ_ELEM( val, writer );
+        printf("
+    }
+    cvEndWriteSeq( &writer );
+    
+    cvStartReadSeq( seq, &reader, 0 );
+    for( i = 0; i < seq->total; i++ )
+    {
+        int val;
+    #if 1
+        CV_READ_SEQ_ELEM( val, reader );
+        printf("
+    #else /* alternative way, that is prefferable if sequence elements are large,
+             or their size/type is unknown at compile time */
+        printf("
+        CV_NEXT_SEQ_ELEM( seq->elem_size, reader );
+    #endif
+    }
+    ...
+    
+    cvReleaseStorage( &storage );
+
+..
+
+StartWriteSeq
+-------------
+Creates a new sequence and initializes a writer for it.
+
+.. ocv:cfunction:: void cvStartWriteSeq(  int seq_flags, int header_size, int elem_size, CvMemStorage* storage, CvSeqWriter* writer )
+
+    :param seq_flags: Flags of the created sequence. If the sequence is not passed to any function working with a specific type of sequences, the sequence value may be equal to 0; otherwise the appropriate type must be selected from the list of predefined sequence types.
+
+    :param header_size: Size of the sequence header. The parameter value may not be less than  ``sizeof(CvSeq)`` . If a certain type or extension is specified, it must fit within the base type header.
+
+    :param elem_size: Size of the sequence elements in bytes; must be consistent with the sequence type. For example, if a sequence of points is created (element type  ``CV_SEQ_ELTYPE_POINT``  ), then the parameter  ``elem_size``  must be equal to  ``sizeof(CvPoint)`` .
+
+    :param storage: Sequence location
+
+    :param writer: Writer state; initialized by the function
+
+The function is a combination of
+:ocv:cfunc:`CreateSeq`
+and 
+:ocv:cfunc:`StartAppendToSeq`
+. The pointer to the
+created sequence is stored at
+``writer->seq``
+and is also returned by the
+:ocv:cfunc:`EndWriteSeq`
+function that should be called at the end.
+
+TreeToNodeSeq
+-------------
+Gathers all node pointers to a single sequence.
+
+.. ocv:cfunction:: CvSeq* cvTreeToNodeSeq(  const void* first, int header_size, CvMemStorage* storage )
+
+    :param first: The initial tree node
+
+    :param header_size: Header size of the created sequence (sizeof(CvSeq) is the most frequently used value)
+
+    :param storage: Container for the sequence
+
+The function puts pointers of all nodes reacheable from  ``first`` into a single sequence. The pointers are written sequentially in the depth-first order.
+
diff --git a/modules/core/doc/old_basic_structures.rst b/modules/core/doc/old_basic_structures.rst
new file mode 100644 (file)
index 0000000..dbc5068
--- /dev/null
@@ -0,0 +1,1747 @@
+Basic C Structures and Operations
+=================================
+
+.. highlight:: c
+
+The section describes the main data structures, used by the OpenCV 1.x API, and the basic functions to create and process the data structures.
+
+CvPoint
+-------
+
+.. ocv:struct:: CvPoint
+
+2D point with integer coordinates (usually zero-based).
+
+    .. ocv:member:: int x
+    
+        x-coordinate 
+    
+    .. ocv:member:: int y
+
+        y-coordinate 
+
+.. ocv:cfunction:: CvPoint cvPoint( int x, int y )
+
+    constructs ``CvPoint`` structure.
+
+.. ocv:cfunction:: CvPoint cvPointFrom32f( CvPoint32f pt );
+
+    converts ``CvPoint2D32f`` to ``CvPoint``.
+
+.. seealso:: :ocv:class:`Point\_`
+
+CvPoint2D32f
+------------
+
+.. ocv:struct:: CvPoint2D32f
+
+2D point with floating-point coordinates.
+
+    .. ocv:member:: float x
+
+        x-coordinate 
+
+    .. ocv:member:: float y
+
+        y-coordinate 
+
+.. ocv:cfunction:: CvPoint2D32f cvPoint2D32f( float x, float y )
+
+    constructs ``CvPoint2D32f`` structure.
+
+.. ocv:cfunction:: CvPoint2D32f cvPointTo32f( CvPoint pt )
+
+    converts ``CvPoint`` to ``CvPoint2D32f``.
+
+.. seealso:: :ocv:class:`Point\_`
+
+CvPoint3D32f
+------------
+
+.. ocv:struct:: CvPoint3D32f
+
+3D point with floating-point coordinates
+
+    .. ocv:member:: float x
+
+        x-coordinate 
+
+    .. ocv:member:: float y
+
+        y-coordinate 
+
+    .. ocv:member:: float z
+
+        z-coordinate
+
+.. ocv:cfunction:: CvPoint3D32f cvPoint3D32f( float x, float y, float z )
+
+    constructs ``CvPoint3D32f`` structure.
+
+.. seealso:: :ocv:class:`Point3\_`
+
+CvPoint2D64f
+------------
+
+.. ocv:struct:: CvPoint2D64f
+
+2D point with double-precision floating-point coordinates.
+
+    .. ocv:member:: double x
+
+        x-coordinate 
+
+    .. ocv:member:: double y
+
+        y-coordinate 
+
+.. ocv:cfunction:: CvPoint2D64f cvPoint2D64f( double x, double y )
+
+    constructs ``CvPoint2D64f`` structure.
+
+.. seealso:: :ocv:class:`Point\_`
+
+CvPoint3D64f
+------------
+
+.. ocv:struct:: CvPoint3D64f
+
+3D point with double-precision floating-point coordinates.
+
+    .. ocv:member:: double x
+
+        x-coordinate 
+
+    .. ocv:member:: double y
+
+        y-coordinate
+        
+    .. ocv:member:: double z 
+
+.. ocv:cfunction:: CvPoint3D64f cvPoint3D64f( double x, double y, double z )
+
+    constructs ``CvPoint3D64f`` structure.
+
+.. seealso:: :ocv:class:`Point3\_`
+
+CvSize
+------
+
+.. ocv:struct:: CvSize
+
+Size of a rectangle or an image.
+    
+    .. ocv:member:: int width
+    
+        Width of the rectangle 
+    
+    .. ocv:member:: int height
+    
+        Height of the rectangle
+
+.. ocv:cfunction:: CvSize cvSize( int width, int height )
+
+    constructs ``CvSize`` structure.
+
+.. seealso:: :ocv:class:`Size\_`
+
+CvSize2D32f
+-----------
+
+.. ocv:struct:: CvSize2D32f
+
+Sub-pixel accurate size of a rectangle.
+
+    .. ocv:member:: float width
+    
+        Width of the rectangle 
+    
+    .. ocv:member:: float height
+    
+        Height of the rectangle
+
+.. ocv:cfunction:: CvSize2D32f cvSize2D23f( float width, float height )
+
+    constructs ``CvSize2D32f`` structure.
+
+.. seealso:: :ocv:class:`Size\_`    
+
+CvRect
+------
+
+.. ocv:struct:: CvRect
+
+Stores coordinates of a rectangle.
+
+    .. ocv:member:: int x
+    
+        x-coordinate of the top-left corner 
+    
+    .. ocv:member:: int y
+    
+        y-coordinate of the top-left corner (sometimes bottom-left corner)
+    
+    .. ocv:member:: int width
+    
+        Width of the rectangle 
+    
+    .. ocv:member:: int height
+    
+        Height of the rectangle 
+    
+.. ocv:cfunction:: CvRect cvRect( int x, int y, int width, int height )
+
+    constructs ``CvRect`` structure.
+    
+.. seealso:: :ocv:class:`Rect\_`
+
+CvScalar
+--------
+
+.. ocv:struct:: CvScalar
+
+A container for 1-,2-,3- or 4-tuples of doubles.
+
+    .. ocv:member:: double[4] val
+
+.. ocv::cfunction:: CvScalar cvScalar( double val0, double val1=0, double val2=0, double val3=0 )
+
+    initializes val[0] with val0, val[1] with val1, val[2] with val2 and val[3] with val3.
+    
+.. ocv::cfunction:: CvScalar cvScalarAll( double val0123 )
+
+    initializes all of val[0]...val[3] with val0123 
+
+.. ocv::cfunction:: CvScalar cvRealScalar( double val0 )
+
+    initializes val[0] with val0, val[1], val[2] and val[3] with 0.
+
+.. seealso:: :ocv:class:`Scalar\_`
+
+CvTermCriteria
+--------------
+
+.. ocv:struct:: CvTermCriteria
+
+Termination criteria for iterative algorithms.
+
+    .. ocv:member:: int type
+    
+        type of the termination criteria, one of:
+        
+            * ``CV_TERMCRIT_ITER`` - stop the algorithm after ``max_iter`` iterations at maximum.
+            
+            * ``CV_TERMCRIT_EPS`` - stop the algorithm after the achieved algorithm-dependent accuracy becomes lower than ``epsilon``.
+            
+            * ``CV_TERMCRIT_ITER+CV_TERMCRIT_EPS`` - stop the algorithm after ``max_iter`` iterations or when the achieved accuracy is lower than ``epsilon``, whichever comes the earliest.
+
+    .. ocv:member:: int max_iter    
+
+        Maximum number of iterations 
+    
+    .. ocv:member:: double epsilon
+    
+        Required accuracy
+
+.. seealso:: :ocv:class:`TermCriteria`
+
+CvMat
+-----
+
+.. ocv:struct:: CvMat
+
+A multi-channel dense matrix.
+
+    .. ocv:member:: int type
+    
+        ``CvMat`` signature (``CV_MAT_MAGIC_VAL``) plus type of the elements. Type of the matrix elements can be retrieved using ``CV_MAT_TYPE`` macro: ::
+            
+                int type = CV_MAT_TYPE(matrix->type);
+                
+        For description of possible matrix elements, see :ocv:class:`Mat`.
+    
+    .. ocv:member:: int step
+    
+        Full row length in bytes 
+    
+    .. ocv:member:: int* refcount
+    
+        Underlying data reference counter 
+    
+    .. ocv:member:: union data
+    
+        Pointers to the actual matrix data:
+           
+           * ptr - pointer to 8-bit unsigned elements
+           * s - pointer to 16-bit signed elements
+           * i - pointer to 32-bit signed elements
+           * fl - pointer to 32-bit floating-point elements
+           * db - pointer to 64-bit floating-point elements
+    
+    .. ocv:member:: int rows
+    
+        Number of rows 
+    
+    .. ocv:member:: int cols
+    
+        Number of columns 
+
+Matrix elements are stored row by row. Element (i, j) (i - 0-based row index, j - 0-based column index) of a matrix can be retrieved or modified using ``CV_MAT_ELEM`` macro: ::
+
+    uchar pixval = CV_MAT_ELEM(grayimg, uchar, i, j)
+    CV_MAT_ELEM(cameraMatrix, float, 0, 2) = image.width*0.5f;
+    
+To access multiple-channel matrices, you can use ``CV_MAT_ELEM(matrix, type, i, j*nchannels + channel_idx)``.
+
+``CvMat`` is now obsolete; consider using :ocv:class:`Mat` instead.
+
+CvMatND
+-------
+
+.. ocv:struct:: CvMatND
+
+Multi-dimensional dense multi-channel array.
+
+    .. ocv:member:: int type
+    
+        A ``CvMatND`` signature (``CV_MATND_MAGIC_VAL``) plus the type of elements. Type of the matrix elements can be retrieved using ``CV_MAT_TYPE`` macro: ::
+            
+                int type = CV_MAT_TYPE(ndmatrix->type);
+    
+    .. ocv:member:: int dims
+    
+        The number of array dimensions 
+    
+    .. ocv:member:: int* refcount
+    
+        Underlying data reference counter 
+    
+    .. ocv:member:: union data
+    
+        Pointers to the actual matrix data 
+    
+           * ptr - pointer to 8-bit unsigned elements
+           * s - pointer to 16-bit signed elements
+           * i - pointer to 32-bit signed elements
+           * fl - pointer to 32-bit floating-point elements
+           * db - pointer to 64-bit floating-point elements
+    
+    .. ocv:member:: array dim
+    
+        Arrays of pairs (array size along the i-th dimension, distance between neighbor elements along i-th dimension): ::
+            
+            for(int i = 0; i < ndmatrix->dims; i++)
+                printf("size[i] = %d, step[i] = %d\n", ndmatrix->dim[i].size, ndmatrix->dim[i].step);
+        
+``CvMatND`` is now obsolete; consider using :ocv:class:`Mat` instead.
+
+CvSparseMat
+-----------
+
+.. ocv:struct:: CvSparseMat
+
+Multi-dimensional sparse multi-channel array.
+    
+    .. ocv:member:: int type
+    
+        A ``CvSparseMat`` signature (CV_SPARSE_MAT_MAGIC_VAL) plus the type of sparse matrix elements. Similarly to ``CvMat`` and ``CvMatND``, use ``CV_MAT_TYPE()`` to retrieve type of the elements.
+    
+    .. ocv:member:: int dims
+    
+        Number of dimensions 
+    
+    .. ocv:member:: int* refcount
+    
+        Underlying reference counter. Not used. 
+    
+    .. ocv:member:: CvSet* heap
+    
+        A pool of hash table nodes
+    
+    .. ocv:member:: void** hashtable
+    
+        The hash table. Each entry is a list of nodes. 
+    
+    .. ocv:member:: int hashsize
+    
+        Size of the hash table 
+    
+    .. ocv:member:: int[] size
+    
+        Array of dimension sizes
+
+IplImage
+--------
+
+.. ocv:struct:: IplImage
+
+IPL image header
+    
+    .. ocv:member:: int nSize
+    
+        ``sizeof(IplImage)`` 
+    
+    .. ocv:member:: int ID
+    
+        Version, always equals 0 
+    
+    .. ocv:member:: int nChannels
+    
+        Number of channels. Most OpenCV functions support 1-4 channels. 
+    
+    .. ocv:member:: int alphaChannel
+    
+        Ignored by OpenCV 
+    
+    .. ocv:member:: int depth
+    
+        Channel depth in bits + the optional sign bit ( ``IPL_DEPTH_SIGN`` ). The supported depths are: 
+            
+            * ``IPL_DEPTH_8U`` - unsigned 8-bit integer. Equivalent to ``CV_8U`` in matrix types.
+            * ``IPL_DEPTH_8S`` - signed 8-bit integer. Equivalent to ``CV_8S`` in matrix types.
+            * ``IPL_DEPTH_16U`` - unsigned 16-bit integer. Equivalent to ``CV_16U`` in matrix types.
+            * ``IPL_DEPTH_16S`` - signed 8-bit integer. Equivalent to ``CV_16S`` in matrix types.
+            * ``IPL_DEPTH_32S`` - signed 32-bit integer. Equivalent to ``CV_32S`` in matrix types.
+            * ``IPL_DEPTH_32F`` - single-precision floating-point number. Equivalent to ``CV_32F`` in matrix types.
+            * ``IPL_DEPTH_64F`` - double-precision floating-point number. Equivalent to ``CV_64F`` in matrix types.
+    
+    .. ocv:member:: char[] colorModel
+    
+        Ignored by OpenCV. 
+    
+    .. ocv:member:: char[] channelSeq
+    
+        Ignored by OpenCV 
+    
+    .. ocv:member:: int dataOrder
+    
+        0 =  ``IPL_DATA_ORDER_PIXEL``  - interleaved color channels, 1 - separate color channels.  :ocv:cfunc:`CreateImage`  only creates images with interleaved channels. For example, the usual layout of a color image is:  :math:`b_{00} g_{00} r_{00} b_{10} g_{10} r_{10} ...` 
+    
+    .. ocv:member:: int origin
+    
+        0 - top-left origin, 1 - bottom-left origin (Windows bitmap style) 
+    
+    .. ocv:member:: int align
+    
+        Alignment of image rows (4 or 8). OpenCV ignores this and uses widthStep instead. 
+    
+    .. ocv:member:: int width
+    
+        Image width in pixels 
+        
+    .. ocv:member:: int height
+    
+        Image height in pixels 
+    
+    .. ocv:member:: IplROI* roi
+    
+        Region Of Interest (ROI). If not NULL, only this image region will be processed. 
+    
+    .. ocv:member:: IplImage* maskROI
+    
+        Must be NULL in OpenCV 
+    
+    .. ocv:member:: void* imageId
+    
+        Must be NULL in OpenCV 
+    
+    .. ocv:member:: void* tileInfo
+    
+        Must be NULL in OpenCV 
+    
+    .. ocv:member:: int imageSize
+    
+        Image data size in bytes. For interleaved data, this equals  :math:`\texttt{image->height} \cdot \texttt{image->widthStep}`   
+    
+    .. ocv:member:: char* imageData
+    
+        A pointer to the aligned image data. Do not assign imageData directly. Use :ocv:cfunc:`SetData`.
+    
+    .. ocv:member:: int widthStep
+    
+        The size of an aligned image row, in bytes.  
+    
+    .. ocv:member:: int[] BorderMode
+    
+        Border completion mode, ignored by OpenCV 
+    
+    .. ocv:member:: int[] BorderConst
+    
+        Constant border value, ignored by OpenCV 
+    
+    .. ocv:member:: char* imageDataOrigin
+    
+        A pointer to the origin of the image data (not necessarily aligned). This is used for image deallocation. 
+    
+The ``IplImage`` is taken from the Intel Image Processing Library, in which the format is native. OpenCV only supports a subset of possible ``IplImage`` formats, as outlined in the parameter list above.
+
+In addition to the above restrictions, OpenCV handles ROIs differently. OpenCV functions require that the image size or ROI size of all source and destination images match exactly. On the other hand, the Intel Image Processing Library processes the area of intersection between the source and destination images (or ROIs), allowing them to vary independently.
+
+CvArr
+-----
+
+.. ocv:struct:: CvArr
+
+This is the "metatype" used *only* as a function parameter. It denotes that the function accepts arrays of multiple types, such as IplImage*, CvMat* or even CvSeq* sometimes. The particular array type is determined at runtime by analyzing the first 4 bytes of the header. In C++ interface the role of ``CvArr`` is played by ``InputArray`` and ``OutputArray``.
+
+ClearND
+-------
+Clears a specific array element.
+
+.. ocv:cfunction:: void cvClearND(CvArr* arr, int* idx)
+.. ocv:pyoldfunction:: cv.ClearND(arr, idx)-> None
+
+    :param arr: Input array 
+    :param idx: Array of the element indices 
+    
+The function clears (sets to zero) a specific element of a dense array or deletes the element of a sparse array. If the sparse array element does not exists, the function does nothing.
+
+CloneImage
+----------
+Makes a full copy of an image, including the header, data, and ROI.
+
+.. ocv:cfunction:: IplImage* cvCloneImage(const IplImage* image)
+.. ocv:pyoldfunction:: cv.CloneImage(image)-> copy
+    
+    :param image: The original image
+
+CloneMat
+--------
+Creates a full matrix copy.
+
+.. ocv:cfunction:: CvMat* cvCloneMat(const CvMat* mat)
+.. ocv:pyoldfunction:: cv.CloneMat(mat)-> copy
+    
+    :param mat: Matrix to be copied 
+    
+Creates a full copy of a matrix and returns a pointer to the copy. Note that the matrix copy is compacted, that is, it will not have gaps between rows.
+
+CloneMatND
+----------
+Creates full copy of a multi-dimensional array and returns a pointer to the copy.
+
+.. ocv:cfunction:: CvMatND* cvCloneMatND(const CvMatND* mat)
+.. ocv:pyoldfunction:: cv.CloneMatND(mat)-> copy
+    
+    :param mat: Input array
+
+CloneSparseMat
+--------------
+Creates full copy of sparse array.
+
+.. ocv:cfunction:: CvSparseMat* cvCloneSparseMat(const CvSparseMat* mat)
+    
+    :param mat: Input array 
+    
+The function creates a copy of the input array and returns pointer to the copy.
+
+
+ConvertScale
+------------
+Converts one array to another with optional linear transformation.
+
+.. ocv:cfunction:: void cvConvertScale(const CvArr* src, CvArr* dst, double scale=1, double shift=0)
+.. ocv:pyoldfunction:: cv.ConvertScale(src, dst, scale=1.0, shift=0.0)-> None
+.. ocv:pyoldfunction:: cv.Convert(src, dst)-> None
+
+::
+    
+    #define cvCvtScale cvConvertScale
+    #define cvScale  cvConvertScale
+    #define cvConvert(src, dst )  cvConvertScale((src), (dst), 1, 0 )
+
+..
+    
+    :param src: Source array 
+    
+    :param dst: Destination array 
+    
+    :param scale: Scale factor 
+    
+    :param shift: Value added to the scaled source array elements 
+    
+The function has several different purposes, and thus has several different names. It copies one array to another with optional scaling, which is performed first, and/or optional type conversion, performed after:
+
+.. math::
+
+    \texttt{dst} (I) =  \texttt{scale} \texttt{src} (I) + ( \texttt{shift} _0, \texttt{shift} _1,...) 
+
+
+All the channels of multi-channel arrays are processed independently.
+
+The type of conversion is done with rounding and saturation, that is if the
+result of scaling + conversion can not be represented exactly by a value
+of the destination array element type, it is set to the nearest representable
+value on the real axis.
+
+
+Copy
+----
+Copies one array to another.
+
+.. cfunction:: void cvCopy(const CvArr* src, CvArr* dst, const CvArr* mask=NULL)
+.. ocv:pyoldfunction:: cv.Copy(src, dst, mask=None)-> None
+
+    :param src: The source array 
+    
+    :param dst: The destination array 
+    
+    :param mask: Operation mask, 8-bit single channel array; specifies elements of the destination array to be changed 
+    
+The function copies selected elements from an input array to an output array:
+
+.. math::
+
+    \texttt{dst} (I)= \texttt{src} (I)  \quad \text{if} \quad \texttt{mask} (I)  \ne 0. 
+
+If any of the passed arrays is of ``IplImage`` type, then its ROI and COI fields are used. Both arrays must have the same type, the same number of dimensions, and the same size. The function can also copy sparse arrays (mask is not supported in this case).
+
+
+CreateData
+----------
+Allocates array data
+
+.. ocv:cfunction:: void cvCreateData(CvArr* arr)
+.. ocv:pyoldfunction:: cv.CreateData(arr) -> None    
+
+    :param arr: Array header 
+    
+The function allocates image, matrix or multi-dimensional dense array data. Note that in the case of matrix types OpenCV allocation functions are used. In the case of IplImage they are used
+unless ``CV_TURN_ON_IPL_COMPATIBILITY()`` has been called before. In the latter case IPL functions are used to allocate the data.
+
+CreateImage
+-----------
+Creates an image header and allocates the image data.
+
+.. ocv:cfunction:: IplImage* cvCreateImage(CvSize size, int depth, int channels)
+.. ocv:pyoldfunction:: cv.CreateImage(size, depth, channels)->image
+    
+    :param size: Image width and height 
+    
+    :param depth: Bit depth of image elements. See  :ocv:struct:`IplImage`  for valid depths. 
+    
+    :param channels: Number of channels per pixel. See  :ocv:struct:`IplImage`  for details. This function only creates images with interleaved channels. 
+    
+This function call is equivalent to the following code: ::
+
+    header = cvCreateImageHeader(size, depth, channels);
+    cvCreateData(header);
+
+CreateImageHeader
+-----------------
+Creates an image header but does not allocate the image data.
+
+.. ocv:cfunction:: IplImage* cvCreateImageHeader(CvSize size, int depth, int channels)
+.. ocv:pyoldfunction:: cv.CreateImageHeader(size, depth, channels) -> image
+
+    :param size: Image width and height 
+    
+    :param depth: Image depth (see  :ocv:cfunc:`CreateImage` ) 
+    
+    :param channels: Number of channels (see  :ocv:cfunc:`CreateImage` )
+
+CreateMat
+---------
+Creates a matrix header and allocates the matrix data. 
+
+.. ocv:cfunction:: CvMat* cvCreateMat( int rows, int cols, int type)
+.. ocv:pyoldfunction:: cv.CreateMat(rows, cols, type) -> mat
+    
+    :param rows: Number of rows in the matrix 
+    
+    :param cols: Number of columns in the matrix 
+    
+    :param type: The type of the matrix elements in the form  ``CV_<bit depth><S|U|F>C<number of channels>`` , where S=signed, U=unsigned, F=float. For example, CV _ 8UC1 means the elements are 8-bit unsigned and the there is 1 channel, and CV _ 32SC2 means the elements are 32-bit signed and there are 2 channels.
+
+The function call is equivalent to the following code: ::
+
+    CvMat* mat = cvCreateMatHeader(rows, cols, type);
+    cvCreateData(mat);
+
+CreateMatHeader
+---------------
+Creates a matrix header but does not allocate the matrix data.
+
+.. ocv:cfunction:: CvMat* cvCreateMatHeader( int rows, int cols, int type)
+.. ocv:pyoldfunction:: cv.CreateMatHeader(rows, cols, type) -> mat
+    
+    :param rows: Number of rows in the matrix 
+    
+    :param cols: Number of columns in the matrix 
+    
+    :param type: Type of the matrix elements, see  :ocv:cfunc:`CreateMat` 
+    
+The function allocates a new matrix header and returns a pointer to it. The matrix data can then be allocated using :ocv:cfunc:`CreateData` or set explicitly to user-allocated data via :ocv:func:`SetData`.
+
+CreateMatND
+-----------
+Creates the header and allocates the data for a multi-dimensional dense array.
+
+.. ocv:cfunction:: CvMatND* cvCreateMatND( int dims, const int* sizes, int type)
+.. ocv:pyoldfunction:: cv.CreateMatND(dims, type) -> None
+
+    :param dims: Number of array dimensions. This must not exceed CV_MAX_DIM (32 by default, but can be changed at build time). 
+    
+    :param sizes: Array of dimension sizes. 
+    
+    :param type: Type of array elements, see  :ocv:cfunc:`CreateMat` . 
+    
+This function call is equivalent to the following code: ::
+    
+    CvMatND* mat = cvCreateMatNDHeader(dims, sizes, type);
+    cvCreateData(mat);
+
+CreateMatNDHeader
+-----------------
+Creates a new matrix header but does not allocate the matrix data.
+
+.. ocv:cfunction:: CvMatND* cvCreateMatNDHeader( int dims, const int* sizes, int type)
+.. ocv:pyoldfunction:: cv.CreateMatNDHeader(dims, type) -> None
+    
+    :param dims: Number of array dimensions 
+    
+    :param sizes: Array of dimension sizes 
+    
+    :param type: Type of array elements, see  :ocv:cfunc:`CreateMat`
+
+The function allocates a header for a multi-dimensional dense array. The array data can further be allocated using  :ocv:cfunc:`CreateData` or set explicitly to user-allocated data via  :ocv:cfunc:`SetData`.
+
+CreateSparseMat
+---------------
+Creates sparse array.
+
+.. ocv:cfunction:: CvSparseMat* cvCreateSparseMat(int dims, const int* sizes, int type)
+    
+    :param dims: Number of array dimensions. In contrast to the dense matrix, the number of dimensions is practically unlimited (up to  :math:`2^{16}` ). 
+    
+    :param sizes: Array of dimension sizes 
+    
+    :param type: Type of array elements. The same as for CvMat
+
+The function allocates a multi-dimensional sparse array. Initially the array contain no elements, that is 
+:ocv:cfunc:`GetPtrND` and other related functions will return 0 for every index.
+
+
+CrossProduct
+------------
+Calculates the cross product of two 3D vectors.
+
+.. ocv:cfunction:: void cvCrossProduct(const CvArr* src1, const CvArr* src2, CvArr* dst)
+.. ocv:pyoldfunction:: cv.CrossProduct(src1, src2, dst)-> None
+    
+    :param src1: The first source vector 
+    
+    :param src2: The second source vector 
+    
+    :param dst: The destination vector 
+    
+The function calculates the cross product of two 3D vectors:
+
+.. math::
+
+    \texttt{dst} =  \texttt{src1} \times \texttt{src2} 
+
+or:
+
+.. math::
+
+    \begin{array}{l} \texttt{dst} _1 =  \texttt{src1} _2  \texttt{src2} _3 -  \texttt{src1} _3  \texttt{src2} _2 \\ \texttt{dst} _2 =  \texttt{src1} _3  \texttt{src2} _1 -  \texttt{src1} _1  \texttt{src2} _3 \\ \texttt{dst} _3 =  \texttt{src1} _1  \texttt{src2} _2 -  \texttt{src1} _2  \texttt{src2} _1 \end{array} 
+
+
+DotProduct
+----------
+Calculates the dot product of two arrays in Euclidian metrics.
+
+.. ocv:cfunction:: double cvDotProduct(const CvArr* src1, const CvArr* src2)
+.. ocv:pyoldfunction:: cv.DotProduct(src1, src2)-> double
+
+    :param src1: The first source array 
+
+    :param src2: The second source array 
+
+The function calculates and returns the Euclidean dot product of two arrays.
+
+.. math::
+
+    src1  \bullet src2 =  \sum _I ( \texttt{src1} (I)  \texttt{src2} (I)) 
+
+In the case of multiple channel arrays, the results for all channels are accumulated. In particular, 
+``cvDotProduct(a,a)`` where  ``a`` is a complex vector, will return  :math:`||\texttt{a}||^2`.
+The function can process multi-dimensional arrays, row by row, layer by layer, and so on.
+
+
+Get?D
+-----
+
+.. ocv:cfunction:: CvScalar cvGet1D(const CvArr* arr, int idx0)
+.. ocv:cfunction:: CvScalar cvGet2D(const CvArr* arr, int idx0, int idx1)
+.. ocv:cfunction:: CvScalar cvGet3D(const CvArr* arr, int idx0, int idx1, int idx2)
+.. ocv:cfunction:: CvScalar cvGetND(const CvArr* arr, int* idx)
+
+.. ocv:pyoldfunction:: cv.Get1D(arr, idx) -> scalar
+.. ocv:pyoldfunction:: cv.Get2D(arr, idx0, idx1) -> scalar
+.. ocv:pyoldfunction:: cv.Get3D(arr, idx0, idx1, idx2) -> scalar
+.. ocv:pyoldfunction:: cv.GetND(arr, indices) -> scalar
+
+    Return a specific array element.
+    
+    :param arr: Input array 
+    
+    :param idx0: The first zero-based component of the element index 
+    
+    :param idx1: The second zero-based component of the element index 
+    
+    :param idx2: The third zero-based component of the element index 
+    
+    :param idx: Array of the element indices
+
+The functions return a specific array element. In the case of a sparse array the functions return 0 if the requested node does not exist (no new node is created by the functions).
+
+GetCol(s)
+---------
+Returns one of more array columns.
+
+.. ocv:cfunction:: CvMat* cvGetCol(const CvArr* arr, CvMat* submat, int col)
+.. ocv:cfunction:: CvMat* cvGetCols(const CvArr* arr, CvMat* submat, int startCol, int endCol)
+    
+.. ocv:pyoldfunction:: cv.GetCol(arr, col)-> submat
+.. ocv:pyoldfunction:: cv.GetCols(arr, startCol, endCol)-> submat
+    
+    :param arr: Input array 
+    
+    :param submat: Pointer to the resulting sub-array header 
+    
+    :param col: Zero-based index of the selected column 
+    
+    :param startCol: Zero-based index of the starting column (inclusive) of the span 
+    
+    :param endCol: Zero-based index of the ending column (exclusive) of the span
+
+The functions return the header, corresponding to a specified column span of the input array. That is, no data is copied. Therefore, any modifications of the submatrix will affect the original array. If you need to copy the columns, use :ocv:cfunc:`CloneMat`. ``cvGetCol(arr, submat, col)`` is a shortcut for ``cvGetCols(arr, submat, col, col+1)``.
+
+GetDiag
+-------
+Returns one of array diagonals.
+
+.. ocv:cfunction:: CvMat* cvGetDiag(const CvArr* arr, CvMat* submat, int diag=0)
+.. ocv:pyoldfunction:: cv.GetDiag(arr, diag=0)-> submat
+    
+    :param arr: Input array 
+    
+    :param submat: Pointer to the resulting sub-array header 
+    
+    :param diag: Index of the array diagonal. Zero value corresponds to the main diagonal, -1 corresponds to the diagonal above the main, 1 corresponds to the diagonal below the main, and so forth. 
+    
+The function returns the header, corresponding to a specified diagonal of the input array.
+
+GetDims
+---------
+Return number of array dimensions
+
+.. ocv:cfunction:: int cvGetDims(const CvArr* arr, int* sizes=NULL)
+.. ocv:pyoldfunction:: cv.GetDims(arr)-> list
+
+    :param arr: Input array 
+    
+    :param sizes: Optional output vector of the array dimension sizes. For
+        2d arrays the number of rows (height) goes first, number of columns
+        (width) next.     
+    
+The function returns the array dimensionality and the array of dimension sizes. In the case of  ``IplImage`` or `CvMat` it always returns 2 regardless of number of image/matrix rows. For example, the following code calculates total number of array elements: ::
+    
+    int sizes[CV_MAX_DIM];
+    int i, total = 1;
+    int dims = cvGetDims(arr, size);
+    for(i = 0; i < dims; i++ )
+        total *= sizes[i];
+
+GetDimSize
+------------
+Returns array size along the specified dimension.
+
+.. ocv:cfunction:: int cvGetDimSize(const CvArr* arr, int index)
+
+    :param arr: Input array 
+
+    :param index: Zero-based dimension index (for matrices 0 means number of rows, 1 means number of columns; for images 0 means height, 1 means width)
+
+GetElemType
+-----------
+Returns type of array elements.
+
+.. ocv:cfunction:: int cvGetElemType(const CvArr* arr)
+.. ocv:pyoldfunction:: cv.GetElemType(arr)-> int    
+    
+    :param arr: Input array 
+    
+The function returns type of the array elements. In the case of ``IplImage`` the type is converted to ``CvMat``-like representation. For example, if the image has been created as: ::
+
+    IplImage* img = cvCreateImage(cvSize(640, 480), IPL_DEPTH_8U, 3);
+    
+The code ``cvGetElemType(img)`` will return ``CV_8UC3``.
+
+GetImage
+--------
+Returns image header for arbitrary array.
+
+.. ocv:cfunction:: IplImage* cvGetImage(const CvArr* arr, IplImage* imageHeader)
+.. ocv:pyoldfunction:: cv.GetImage(arr) -> iplimage
+    
+    :param arr: Input array 
+    
+    :param imageHeader: Pointer to  ``IplImage``  structure used as a temporary buffer 
+    
+The function returns the image header for the input array that can be a matrix (:ocv:struct:`CvMat`) or image (:ocv:struct:`IplImage`). In the case of an image the function simply returns the input pointer. In the case of ``CvMat`` it initializes an ``imageHeader`` structure with the parameters of the input matrix. Note that if we transform ``IplImage`` to ``CvMat`` using :ocv:cfunc:`GetMat` and then transform ``CvMat`` back to IplImage using this function, we will get different headers if the ROI is set in the original image.
+
+GetImageCOI
+-----------
+Returns the index of the channel of interest. 
+
+.. ocv:cfunction:: int cvGetImageCOI(const IplImage* image)
+.. ocv:pyoldfunction:: cv.GetImageCOI(image)-> channel
+    
+    :param image: A pointer to the image header 
+    
+Returns the channel of interest of in an IplImage. Returned values correspond to the ``coi`` in 
+:ocv:cfunc:`SetImageCOI`.
+
+GetImageROI
+-----------
+Returns the image ROI.
+
+.. ocv:cfunction:: CvRect cvGetImageROI(const IplImage* image)
+.. ocv:pyoldfunction:: cv.GetImageROI(image)-> CvRect
+
+    :param image: A pointer to the image header 
+    
+If there is no ROI set, ``cvRect(0,0,image->width,image->height)`` is returned.
+
+GetMat
+------
+Returns matrix header for arbitrary array.
+
+.. ocv:cfunction:: CvMat* cvGetMat(const CvArr* arr, CvMat* header, int* coi=NULL, int allowND=0)
+.. ocv:pyoldfunction:: cv.GetMat(arr, allowND=0) -> cvmat
+
+    :param arr: Input array 
+    
+    :param header: Pointer to  :ocv:struct:`CvMat`  structure used as a temporary buffer 
+    
+    :param coi: Optional output parameter for storing COI 
+    
+    :param allowND: If non-zero, the function accepts multi-dimensional dense arrays (CvMatND*) and returns 2D matrix (if CvMatND has two dimensions) or 1D matrix (when CvMatND has 1 dimension or more than 2 dimensions). The ``CvMatND`` array must be continuous. 
+    
+The function returns a matrix header for the input array that can be a matrix - :ocv:struct:`CvMat`, an image - :ocv:struct:`IplImage`, or a multi-dimensional dense array - :ocv:struct:`CvMatND` (the third option is allowed only if ``allowND != 0``) . In the case of matrix the function simply returns the input pointer. In the case of ``IplImage*`` or ``CvMatND`` it initializes the ``header`` structure with parameters of the current image ROI and returns ``&header``. Because COI is not supported by ``CvMat``, it is returned separately.
+
+The function provides an easy way to handle both types of arrays - ``IplImage`` and  ``CvMat`` using the same code. Input array must have non-zero data pointer, otherwise the function will report an error.
+
+.. seealso:: :ocv:cfunc:`GetImage`, :ocv:cfunc:`GetMatND`, :ocv:func:`cvarrToMat`.
+
+.. note:: If the input array is ``IplImage`` with planar data layout and COI set, the function returns the pointer to the selected plane and ``COI == 0``. This feature allows user to process ``IplImage`` strctures with planar data layout, even though OpenCV does not support such images.
+
+GetNextSparseNode
+-----------------
+Returns the next sparse matrix element
+
+.. ocv:cfunction:: CvSparseNode* cvGetNextSparseNode(CvSparseMatIterator* matIterator)
+
+    :param matIterator: Sparse array iterator
+
+The function moves iterator to the next sparse matrix element and returns pointer to it. In the current version there is no any particular order of the elements, because they are stored in the hash table. The sample below demonstrates how to iterate through the sparse matrix: ::
+
+    // print all the non-zero sparse matrix elements and compute their sum
+    double sum = 0;
+    int i, dims = cvGetDims(sparsemat);
+    CvSparseMatIterator it;
+    CvSparseNode* node = cvInitSparseMatIterator(sparsemat, &it);
+    
+    for(; node != 0; node = cvGetNextSparseNode(&it))
+    {
+        /* get pointer to the element indices */
+        int* idx = CV_NODE_IDX(array, node);
+        /* get value of the element (assume that the type is CV_32FC1) */
+        float val = *(float*)CV_NODE_VAL(array, node);
+        printf("M");
+        for(i = 0; i < dims; i++ )
+            printf("[%d]", idx[i]);
+        printf("=%g\n", val);
+    
+        sum += val;
+    }
+    
+    printf("nTotal sum = %g\n", sum);
+
+
+GetRawData
+----------
+Retrieves low-level information about the array.
+
+.. ocv:cfunction:: void cvGetRawData(const CvArr* arr, uchar** data, int* step=NULL, CvSize* roiSize=NULL)
+
+    :param arr: Array header
+
+    :param data: Output pointer to the whole image origin or ROI origin if ROI is set
+
+    :param step: Output full row length in bytes
+
+    :param roiSize: Output ROI size
+
+The function fills output variables with low-level information about the array data. All output parameters are optional, so some of the pointers may be set to ``NULL``. If the array is ``IplImage`` with ROI set, the parameters of ROI are returned.
+
+The following example shows how to get access to array elements. It computes absolute values of the array elements ::
+
+    float* data;
+    int step;
+    CvSize size;
+    
+    cvGetRawData(array, (uchar**)&data, &step, &size);
+    step /= sizeof(data[0]);
+    
+    for(int y = 0; y < size.height; y++, data += step )
+        for(int x = 0; x < size.width; x++ )
+            data[x] = (float)fabs(data[x]);
+
+GetReal?D
+---------
+Return a specific element of single-channel 1D, 2D, 3D or nD array.
+
+.. ocv:cfunction:: double cvGetReal1D(const CvArr* arr, int idx0)
+.. ocv:cfunction:: double cvGetReal2D(const CvArr* arr, int idx0, int idx1)
+.. ocv:cfunction:: double cvGetReal3D(const CvArr* arr, int idx0, int idx1, int idx2)
+.. ocv:cfunction:: double cvGetRealND(const CvArr* arr, int* idx)
+
+.. ocv:pyoldfunction:: cv.GetReal1D(arr, idx0)->float
+.. ocv:pyoldfunction:: cv.GetReal2D(arr, idx0, idx1)->float
+.. ocv:pyoldfunction:: cv.GetReal3D(arr, idx0, idx1, idx2)->float
+.. ocv:pyoldfunction:: cv.GetRealND(arr, idx)->float
+
+    :param arr: Input array. Must have a single channel.
+
+    :param idx0: The first zero-based component of the element index
+
+    :param idx1: The second zero-based component of the element index
+
+    :param idx2: The third zero-based component of the element index
+
+    :param idx: Array of the element indices
+
+Returns a specific element of a single-channel array. If the array has multiple channels, a runtime error is raised. Note that ``Get?D`` functions can be used safely for both single-channel and multiple-channel arrays though they are a bit slower.
+
+In the case of a sparse array the functions return 0 if the requested node does not exist (no new node is created by the functions).
+
+
+GetRow(s)
+---------
+Returns array row or row span.
+
+.. ocv:cfunction:: CvMat* cvGetRow(const CvArr* arr, CvMat* submat, int row)
+
+.. ocv:cfunction:: CvMat* cvGetRows(const CvArr* arr, CvMat* submat, int startRow, int endRow, int deltaRow=1)
+
+.. ocv:pyoldfunction:: cv.GetRow(arr, row)-> submat
+.. ocv:pyoldfunction:: cv.GetRows(arr, startRow, endRow, deltaRow=1)-> submat
+
+    :param arr: Input array
+
+    :param submat: Pointer to the resulting sub-array header
+
+    :param row: Zero-based index of the selected row
+
+    :param startRow: Zero-based index of the starting row (inclusive) of the span
+
+    :param endRow: Zero-based index of the ending row (exclusive) of the span
+
+    :param deltaRow: Index step in the row span. That is, the function extracts every  ``deltaRow`` -th row from  ``startRow``  and up to (but not including)  ``endRow`` .
+
+The functions return the header, corresponding to a specified row/row span of the input array. ``cvGetRow(arr, submat, row)`` is a shortcut for ``cvGetRows(arr, submat, row, row+1)``.
+
+
+GetSize
+-------
+Returns size of matrix or image ROI.
+
+.. ocv:cfunction:: CvSize cvGetSize(const CvArr* arr)
+.. ocv:pyoldfunction:: cv.GetSize(arr)-> (width, height)
+
+    :param arr: array header
+
+The function returns number of rows (CvSize::height) and number of columns (CvSize::width) of the input matrix or image. In the case of image the size of ROI is returned.
+
+GetSubRect
+----------
+Returns matrix header corresponding to the rectangular sub-array of input image or matrix.
+
+.. ocv:cfunction:: CvMat* cvGetSubRect(const CvArr* arr, CvMat* submat, CvRect rect)
+.. ocv:pyoldfunction:: cv.GetSubRect(arr, rect) -> submat
+
+    :param arr: Input array
+
+    :param submat: Pointer to the resultant sub-array header
+
+    :param rect: Zero-based coordinates of the rectangle of interest
+
+The function returns header, corresponding to a specified rectangle of the input array. In other words, it allows the user to treat a rectangular part of input array as a stand-alone array. ROI is taken into account by the function so the sub-array of ROI is actually extracted.
+
+DecRefData
+----------
+Decrements an array data reference counter.
+
+.. ocv:cfunction:: void cvDecRefData(CvArr* arr)
+
+    :param arr: Pointer to an array header
+
+The function decrements the data reference counter in a :ocv:struct:`CvMat` or :ocv:struct:`CvMatND` if the reference counter pointer is not NULL. If the counter reaches zero, the data is deallocated. In the current implementation the reference counter is not NULL only if the data was allocated using the  :ocv:cfunc:`CreateData` function. The counter will be NULL in other cases such as: external data was assigned to the header using :ocv:cfunc:`SetData`, header is part of a larger matrix or image, or the header was converted from an image or n-dimensional matrix header.
+
+
+IncRefData
+----------
+Increments array data reference counter.
+
+.. ocv:cfunction:: int cvIncRefData(CvArr* arr)
+
+    :param arr: Array header
+
+The function increments :ocv:struct:`CvMat` or :ocv:struct:`CvMatND` data reference counter and returns the new counter value if the reference counter pointer is not NULL, otherwise it returns zero.
+
+
+InitImageHeader
+---------------
+Initializes an image header that was previously allocated.
+
+.. ocv:cfunction:: IplImage* cvInitImageHeader( IplImage* image, CvSize size, int depth, int channels, int origin=0, int align=4)
+
+    :param image: Image header to initialize
+
+    :param size: Image width and height
+
+    :param depth: Image depth (see  :ocv:cfunc:`CreateImage` )
+
+    :param channels: Number of channels (see  :ocv:cfunc:`CreateImage` )
+
+    :param origin: Top-left  ``IPL_ORIGIN_TL``  or bottom-left  ``IPL_ORIGIN_BL``
+
+    :param align: Alignment for image rows, typically 4 or 8 bytes
+
+The returned ``IplImage*`` points to the initialized header.
+
+
+InitMatHeader
+-------------
+Initializes a pre-allocated matrix header.
+
+.. ocv:cfunction:: CvMat* cvInitMatHeader( CvMat* mat, int rows, int cols, int type,  void* data=NULL, int step=CV_AUTOSTEP)
+
+    :param mat: A pointer to the matrix header to be initialized
+
+    :param rows: Number of rows in the matrix
+
+    :param cols: Number of columns in the matrix
+
+    :param type: Type of the matrix elements, see  :ocv:cfunc:`CreateMat` .
+
+    :param data: Optional: data pointer assigned to the matrix header
+
+    :param step: Optional: full row width in bytes of the assigned data. By default, the minimal possible step is used which assumes there are no gaps between subsequent rows of the matrix.
+
+This function is often used to process raw data with OpenCV matrix functions. For example, the following code computes the matrix product of two matrices, stored as ordinary arrays: ::
+
+    double a[] = { 1, 2, 3, 4,
+                   5, 6, 7, 8,
+                   9, 10, 11, 12 };
+    
+    double b[] = { 1, 5, 9,
+                   2, 6, 10,
+                   3, 7, 11,
+                   4, 8, 12 };
+    
+    double c[9];
+    CvMat Ma, Mb, Mc ;
+    
+    cvInitMatHeader(&Ma, 3, 4, CV_64FC1, a);
+    cvInitMatHeader(&Mb, 4, 3, CV_64FC1, b);
+    cvInitMatHeader(&Mc, 3, 3, CV_64FC1, c);
+    
+    cvMatMulAdd(&Ma, &Mb, 0, &Mc);
+    // the c array now contains the product of a (3x4) and b (4x3)
+
+
+InitMatNDHeader
+---------------
+Initializes a pre-allocated multi-dimensional array header.
+
+.. ocv:cfunction:: CvMatND* cvInitMatNDHeader( CvMatND* mat, int dims, const int* sizes, int type, void* data=NULL)
+
+    :param mat: A pointer to the array header to be initialized
+
+    :param dims: The number of array dimensions
+
+    :param sizes: An array of dimension sizes
+
+    :param type: Type of array elements, see  :ocv:cfunc:`CreateMat`
+
+    :param data: Optional data pointer assigned to the matrix header
+
+
+InitSparseMatIterator
+---------------------
+Initializes sparse array elements iterator.
+
+.. ocv:cfunction:: CvSparseNode* cvInitSparseMatIterator(const CvSparseMat* mat,                                        CvSparseMatIterator* matIterator)
+
+    :param mat: Input array
+
+    :param matIterator: Initialized iterator
+
+The function initializes iterator of sparse array elements and returns pointer to the first element, or NULL if the array is empty.
+
+
+Mat
+---
+Initializes matrix header (lightweight variant).
+
+.. ocv:cfunction:: CvMat cvMat( int rows, int cols, int type, void* data=NULL)
+
+    :param rows: Number of rows in the matrix
+
+    :param cols: Number of columns in the matrix
+
+    :param type: Type of the matrix elements - see  :ocv:cfunc:`CreateMat`
+
+    :param data: Optional data pointer assigned to the matrix header
+
+Initializes a matrix header and assigns data to it. The matrix is filled *row*-wise (the first ``cols`` elements of data form the first row of the matrix, etc.)
+
+This function is a fast inline substitution for :ocv:cfunc:`InitMatHeader`. Namely, it is equivalent to: ::
+
+    CvMat mat;
+    cvInitMatHeader(&mat, rows, cols, type, data, CV_AUTOSTEP);
+
+
+Ptr?D
+-----
+Return pointer to a particular array element.
+
+.. ocv:cfunction:: uchar* cvPtr1D(const CvArr* arr, int idx0, int* type=NULL)
+
+.. ocv:cfunction:: uchar* cvPtr2D(const CvArr* arr, int idx0, int idx1, int* type=NULL)
+
+.. ocv:cfunction:: uchar* cvPtr3D(const CvArr* arr, int idx0, int idx1, int idx2, int* type=NULL)
+
+.. ocv:cfunction:: uchar* cvPtrND(const CvArr* arr, int* idx, int* type=NULL, int createNode=1, unsigned* precalcHashval=NULL)
+
+    :param arr: Input array
+
+    :param idx0: The first zero-based component of the element index
+
+    :param idx1: The second zero-based component of the element index
+
+    :param idx2: The third zero-based component of the element index
+
+    :param idx: Array of the element indices
+
+    :param type: Optional output parameter: type of matrix elements
+
+    :param createNode: Optional input parameter for sparse matrices. Non-zero value of the parameter means that the requested element is created if it does not exist already.
+
+    :param precalcHashval: Optional input parameter for sparse matrices. If the pointer is not NULL, the function does not recalculate the node hash value, but takes it from the specified location. It is useful for speeding up pair-wise operations (TODO: provide an example)
+
+The functions return a pointer to a specific array element. Number of array dimension should match to the number of indices passed to the function except for ``cvPtr1D`` function that can be used for sequential access to 1D, 2D or nD dense arrays.
+
+The functions can be used for sparse arrays as well - if the requested node does not exist they create it and set it to zero.
+
+All these as well as other functions accessing array elements (
+:ocv:cfunc:`Get`
+, 
+:ocv:cfunc:`GetReal`
+, 
+:ocv:cfunc:`Set`
+, 
+:ocv:cfunc:`SetReal`
+) raise an error in case if the element index is out of range.
+
+
+ReleaseData
+-----------
+Releases array data.
+
+.. ocv:cfunction:: void cvReleaseData(CvArr* arr)
+
+    :param arr: Array header
+
+The function releases the array data. In the case of 
+:ocv:struct:`CvMat`
+or 
+:ocv:struct:`CvMatND`
+it simply calls cvDecRefData(), that is the function can not deallocate external data. See also the note to 
+:ocv:cfunc:`CreateData`
+.
+
+
+ReleaseImage
+------------
+Deallocates the image header and the image data.
+
+.. ocv:cfunction:: void cvReleaseImage(IplImage** image)
+
+    :param image: Double pointer to the image header
+
+This call is a shortened form of ::
+
+    if(*image )
+    {
+        cvReleaseData(*image);
+        cvReleaseImageHeader(image);
+    }
+
+..
+
+ReleaseImageHeader
+------------------
+Deallocates an image header.
+
+.. ocv:cfunction:: void cvReleaseImageHeader(IplImage** image)
+
+    :param image: Double pointer to the image header
+
+This call is an analogue of ::
+
+    if(image )
+    {
+        iplDeallocate(*image, IPL_IMAGE_HEADER | IPL_IMAGE_ROI);
+        *image = 0;
+    }
+
+..
+
+but it does not use IPL functions by default (see the ``CV_TURN_ON_IPL_COMPATIBILITY`` macro).
+
+
+ReleaseMat
+----------
+Deallocates a matrix.
+
+.. ocv:cfunction:: void cvReleaseMat(CvMat** mat)
+
+    :param mat: Double pointer to the matrix
+
+The function decrements the matrix data reference counter and deallocates matrix header. If the data reference counter is 0, it also deallocates the data. ::
+
+    if(*mat )
+        cvDecRefData(*mat);
+    cvFree((void**)mat);
+
+..
+
+ReleaseMatND
+------------
+Deallocates a multi-dimensional array.
+
+.. ocv:cfunction:: void cvReleaseMatND(CvMatND** mat)
+
+    :param mat: Double pointer to the array
+
+The function decrements the array data reference counter and releases the array header. If the reference counter reaches 0, it also deallocates the data. ::
+
+    if(*mat )
+        cvDecRefData(*mat);
+    cvFree((void**)mat);
+
+..
+
+ReleaseSparseMat
+----------------
+Deallocates sparse array.
+
+.. ocv:cfunction:: void cvReleaseSparseMat(CvSparseMat** mat)
+
+    :param mat: Double pointer to the array
+
+The function releases the sparse array and clears the array pointer upon exit.
+
+ResetImageROI
+-------------
+Resets the image ROI to include the entire image and releases the ROI structure.
+
+.. ocv:cfunction:: void cvResetImageROI(IplImage* image)
+.. ocv:pyoldfunction:: cv.ResetImageROI(image)-> None
+
+    :param image: A pointer to the image header
+
+This produces a similar result to the following, but in addition it releases the ROI structure. ::
+
+    cvSetImageROI(image, cvRect(0, 0, image->width, image->height ));
+    cvSetImageCOI(image, 0);
+
+..
+
+Reshape
+-------
+Changes shape of matrix/image without copying data.
+
+.. ocv:cfunction:: CvMat* cvReshape(const CvArr* arr, CvMat* header, int newCn, int newRows=0)
+.. ocv:pyoldfunction:: cv.Reshape(arr, newCn, newRows=0) -> cvmat
+
+    :param arr: Input array
+
+    :param header: Output header to be filled
+
+    :param newCn: New number of channels. 'newCn = 0' means that the number of channels remains unchanged.
+
+    :param newRows: New number of rows. 'newRows = 0' means that the number of rows remains unchanged unless it needs to be changed according to  ``newCn``  value.
+
+The function initializes the CvMat header so that it points to the same data as the original array but has a different shape - different number of channels, different number of rows, or both.
+
+The following example code creates one image buffer and two image headers, the first is for a 320x240x3 image and the second is for a 960x240x1 image: ::
+
+    IplImage* color_img = cvCreateImage(cvSize(320,240), IPL_DEPTH_8U, 3);
+    CvMat gray_mat_hdr;
+    IplImage gray_img_hdr, *gray_img;
+    cvReshape(color_img, &gray_mat_hdr, 1);
+    gray_img = cvGetImage(&gray_mat_hdr, &gray_img_hdr);
+
+..
+
+And the next example converts a 3x3 matrix to a single 1x9 vector:
+
+::
+
+    CvMat* mat = cvCreateMat(3, 3, CV_32F);
+    CvMat row_header, *row;
+    row = cvReshape(mat, &row_header, 0, 1);
+
+..
+
+ReshapeMatND
+------------
+Changes the shape of a multi-dimensional array without copying the data.
+
+.. ocv:cfunction:: CvArr* cvReshapeMatND(const CvArr* arr, int sizeofHeader, CvArr* header,                        int newCn, int newDims, int* newSizes)
+.. ocv:pyoldfunction:: cv.ReshapeMatND(arr, newCn, newDims) -> cvmat
+
+    :param arr: Input array
+
+    :param sizeofHeader: Size of output header to distinguish between IplImage, CvMat and CvMatND output headers
+
+    :param header: Output header to be filled
+
+    :param newCn: New number of channels. ``newCn = 0``  means that the number of channels remains unchanged.
+
+    :param newDims: New number of dimensions. ``newDims = 0`` means that the number of dimensions remains the same.
+
+    :param newSizes: Array of new dimension sizes. Only  ``newDims-1``  values are used, because the total number of elements must remain the same. Thus, if  ``newDims = 1``,  ``newSizes``  array is not used.
+
+The function is an advanced version of :ocv:cfunc:`Reshape` that can work with multi-dimensional arrays as well (though it can work with ordinary images and matrices) and change the number of dimensions.
+
+Below are the two samples from the 
+:ocv:cfunc:`Reshape`
+description rewritten using 
+:ocv:cfunc:`ReshapeMatND`
+: ::
+
+    IplImage* color_img = cvCreateImage(cvSize(320,240), IPL_DEPTH_8U, 3);
+    IplImage gray_img_hdr, *gray_img;
+    gray_img = (IplImage*)cvReshapeND(color_img, &gray_img_hdr, 1, 0, 0);
+    
+    ...
+    
+    /* second example is modified to convert 2x2x2 array to 8x1 vector */
+    int size[] = { 2, 2, 2 };
+    CvMatND* mat = cvCreateMatND(3, size, CV_32F);
+    CvMat row_header, *row;
+    row = (CvMat*)cvReshapeND(mat, &row_header, 0, 1, 0);
+
+..
+
+Set
+---
+Sets every element of an array to a given value.
+
+.. ocv:cfunction:: void cvSet(CvArr* arr, CvScalar value, const CvArr* mask=NULL)
+.. ocv:pyoldfunction:: cv.Set(arr, value, mask=None)-> None
+
+    :param arr: The destination array
+
+    :param value: Fill value
+
+    :param mask: Operation mask, 8-bit single channel array; specifies elements of the destination array to be changed
+
+The function copies the scalar ``value`` to every selected element of the destination array:
+
+.. math::
+
+    \texttt{arr} (I)= \texttt{value} \quad \text{if} \quad \texttt{mask} (I)  \ne 0
+
+If array ``arr`` is of ``IplImage`` type, then is ROI used, but COI must not be set.
+
+Set?D
+-----
+Change the particular array element.
+
+.. ocv:cfunction:: void cvSet1D(CvArr* arr, int idx0, CvScalar value)
+
+.. ocv:cfunction:: void cvSet2D(CvArr* arr, int idx0, int idx1, CvScalar value)
+
+.. ocv:cfunction:: void cvSet3D(CvArr* arr, int idx0, int idx1, int idx2, CvScalar value)
+
+.. ocv:cfunction:: void cvSetND(CvArr* arr, int* idx, CvScalar value)
+
+.. ocv:pyoldfunction:: cv.Set1D(arr, idx, value) -> None
+.. ocv:pyoldfunction:: cv.Set2D(arr, idx0, idx1, value) -> None
+.. ocv:pyoldfunction:: cv.Set3D(arr, idx0, idx1, idx2, value) -> None
+.. ocv:pyoldfunction:: cv.SetND(arr, indices, value) -> None
+
+
+    :param arr: Input array
+
+    :param idx0: The first zero-based component of the element index
+
+    :param idx1: The second zero-based component of the element index
+
+    :param idx2: The third zero-based component of the element index
+
+    :param idx: Array of the element indices
+
+    :param value: The assigned value
+
+The functions assign the new value to a particular array element. In the case of a sparse array the functions create the node if it does not exist yet.
+
+SetData
+-------
+Assigns user data to the array header.
+
+.. ocv:cfunction:: void cvSetData(CvArr* arr, void* data, int step)
+.. ocv:pyoldfunction:: cv.SetData(arr, data, step)-> None
+
+    :param arr: Array header
+
+    :param data: User data
+
+    :param step: Full row length in bytes
+
+The function assigns user data to the array header. Header should be initialized before using 
+:ocv:cfunc:`cvCreateMatHeader`, :ocv:cfunc:`cvCreateImageHeader`, :ocv:cfunc:`cvCreateMatNDHeader`,
+:ocv:cfunc:`cvInitMatHeader`, :ocv:cfunc:`cvInitImageHeader` or :ocv:cfunc:`cvInitMatNDHeader`.
+
+
+
+SetImageCOI
+-----------
+Sets the channel of interest in an IplImage.
+
+.. ocv:cfunction:: void cvSetImageCOI( IplImage* image, int coi)
+.. ocv:pyoldfunction:: cv.SetImageCOI(image, coi)-> None
+
+    :param image: A pointer to the image header
+
+    :param coi: The channel of interest. 0 - all channels are selected, 1 - first channel is selected, etc. Note that the channel indices become 1-based.
+
+If the ROI is set to ``NULL`` and the coi is *not* 0, the ROI is allocated. Most OpenCV functions do  *not* support the COI setting, so to process an individual image/matrix channel one may copy (via :ocv:cfunc:`Copy` or :ocv:cfunc:`Split`) the channel to a separate image/matrix, process it and then copy the result back (via :ocv:cfunc:`Copy` or :ocv:cfunc:`Merge`) if needed.
+
+
+SetImageROI
+-----------
+Sets an image Region Of Interest (ROI) for a given rectangle.
+
+.. ocv:cfunction:: void cvSetImageROI( IplImage* image, CvRect rect)
+.. ocv:pyoldfunction:: cv.SetImageROI(image, rect)-> None
+
+    :param image: A pointer to the image header
+
+    :param rect: The ROI rectangle
+
+If the original image ROI was ``NULL`` and the ``rect`` is not the whole image, the ROI structure is allocated.
+
+Most OpenCV functions support the use of ROI and treat the image rectangle as a separate image. For example, all of the pixel coordinates are counted from the top-left (or bottom-left) corner of the ROI, not the original image.
+
+
+SetReal?D
+---------
+Change a specific array element.
+
+.. ocv:cfunction:: void cvSetReal1D(CvArr* arr, int idx0, double value)
+
+.. ocv:cfunction:: void cvSetReal2D(CvArr* arr, int idx0, int idx1, double value)
+
+.. ocv:cfunction:: void cvSetReal3D(CvArr* arr, int idx0, int idx1, int idx2, double value)
+
+.. ocv:cfunction:: void cvSetRealND(CvArr* arr, int* idx, double value)
+
+.. ocv:pyoldfunction:: cv.SetReal1D(arr, idx, value) -> None
+.. ocv:pyoldfunction:: cv.SetReal2D(arr, idx0, idx1, value) -> None
+.. ocv:pyoldfunction:: cv.SetReal3D(arr, idx0, idx1, idx2, value) -> None
+.. ocv:pyoldfunction:: cv.SetRealND(arr, indices, value) -> None
+
+    :param arr: Input array
+
+    :param idx0: The first zero-based component of the element index
+
+    :param idx1: The second zero-based component of the element index
+
+    :param idx2: The third zero-based component of the element index
+
+    :param idx: Array of the element indices
+
+    :param value: The assigned value
+
+The functions assign a new value to a specific element of a single-channel array. If the array has multiple channels, a runtime error is raised. Note that the ``Set*D`` function can be used safely for both single-channel and multiple-channel arrays, though they are a bit slower.
+
+In the case of a sparse array the functions create the node if it does not yet exist.
+
+SetZero
+-------
+Clears the array.
+
+.. ocv:cfunction:: void cvSetZero(CvArr* arr)
+.. ocv:pyoldfunction:: cv.SetZero(arr)-> None
+
+    :param arr: Array to be cleared
+
+The function clears the array. In the case of dense arrays (CvMat, CvMatND or IplImage), cvZero(array) is equivalent to cvSet(array,cvScalarAll(0),0). In the case of sparse arrays all the elements are removed.
+
+mGet
+----
+Returns the particular element of single-channel floating-point matrix.
+
+.. ocv:cfunction:: double cvmGet(const CvMat* mat, int row, int col)
+.. ocv:pyoldfunction:: cv.mGet(mat, row, col)-> double
+
+    :param mat: Input matrix
+
+    :param row: The zero-based index of row
+
+    :param col: The zero-based index of column
+
+The function is a fast replacement for :ocv:cfunc:`GetReal2D` in the case of single-channel floating-point matrices. It is faster because it is inline, it does fewer checks for array type and array element type, and it checks for the row and column ranges only in debug mode.
+
+mSet
+----
+Sets a specific element of a single-channel floating-point matrix.
+
+.. ocv:cfunction:: void cvmSet(CvMat* mat, int row, int col, double value)
+.. ocv:pyoldfunction:: cv.mSet(mat, row, col, value)-> None
+
+    :param mat: The matrix
+
+    :param row: The zero-based index of row
+
+    :param col: The zero-based index of column
+
+    :param value: The new value of the matrix element
+
+The function is a fast replacement for :ocv:cfunc:`SetReal2D` in the case of single-channel floating-point matrices. It is faster because it is inline, it does fewer checks for array type and array element type,  and it checks for the row and column ranges only in debug mode.
+
+
+SetIPLAllocators
+----------------
+Makes OpenCV use IPL functions for allocating IplImage and IplROI structures.
+
+.. cfunction:: void cvSetIPLAllocators( Cv_iplCreateImageHeader create_header,                          Cv_iplAllocateImageData allocate_data, Cv_iplDeallocate deallocate,                          Cv_iplCreateROI create_roi, Cv_iplCloneImage clone_image )
+
+Normally, the function is not called directly. Instead, a simple macro ``CV_TURN_ON_IPL_COMPATIBILITY()`` is used that calls ``cvSetIPLAllocators`` and passes there pointers to IPL allocation functions. ::
+
+    ...
+    CV_TURN_ON_IPL_COMPATIBILITY()
+    ...
+    
+
+RNG
+---
+Initializes a random number generator state.
+
+.. ocv:cfunction:: CvRNG cvRNG(int64 seed=-1)
+.. ocv:pyoldfunction:: cv.RNG(seed=-1LL)-> CvRNG
+
+    :param seed: 64-bit value used to initiate a random sequence 
+    
+The function initializes a random number generator and returns the state. The pointer to the state can be then passed to the :ocv:cfunc:`RandInt`, :ocv:cfunc:`RandReal` and :ocv:cfunc:`RandArr` functions. In the current implementation a multiply-with-carry generator is used.
+
+.. sealso:: the C++ class :ocv:class:`RNG` replaced ``CvRNG``.
+
+
+RandArr
+-------
+Fills an array with random numbers and updates the RNG state.
+
+.. ocv:cfunction:: void cvRandArr( CvRNG* rng, CvArr* arr, int distType, CvScalar param1, CvScalar param2)
+.. ocv:pyoldfunction:: cv.RandArr(rng, arr, distType, param1, param2)-> None    
+    
+    :param rng: CvRNG state initialized by :ocv:cfunc:`RNG` 
+    
+    :param arr: The destination array 
+    
+    :param distType: Distribution type 
+         
+            * **CV_RAND_UNI** uniform distribution 
+            
+            * **CV_RAND_NORMAL** normal or Gaussian distribution 
+    
+    :param param1: The first parameter of the distribution. In the case of a uniform distribution it is the inclusive lower boundary of the random numbers range. In the case of a normal distribution it is the mean value of the random numbers. 
+    
+    :param param2: The second parameter of the distribution. In the case of a uniform distribution it is the exclusive upper boundary of the random numbers range. In the case of a normal distribution it is the standard deviation of the random numbers. 
+    
+The function fills the destination array with uniformly or normally distributed random numbers.
+
+.. seealso:: :ocv:func:`randu`, :ocv:func:`randn`, :ocv:func:`RNG::fill`.
+
+RandInt
+-------
+Returns a 32-bit unsigned integer and updates RNG.
+
+.. ocv:cfunction:: unsigned cvRandInt(CvRNG* rng)
+.. ocv:pyoldfunction:: cv.RandInt(rng)-> unsigned
+    
+    :param rng: CvRNG state initialized by  :ocv:cfunc:`RNG`.
+    
+The function returns a uniformly-distributed random 32-bit unsigned integer and updates the RNG state. It is similar to the rand() function from the C runtime library, except that OpenCV functions always generates a 32-bit random number, regardless of the platform.
+
+
+RandReal
+--------
+Returns a floating-point random number and updates RNG.
+
+.. ocv:cfunction:: double cvRandReal(CvRNG* rng)
+.. ocv:pyoldfunction:: cv.RandReal(rng)-> double
+
+    :param rng: RNG state initialized by  :ocv:cfunc:`RNG` 
+    
+The function returns a uniformly-distributed random floating-point number between 0 and 1 (1 is not included).
+
+
+fromarray
+---------
+Create a CvMat from an object that supports the array interface.
+
+.. ocv:pyoldfunction:: cv.fromarray(object, allowND=False) -> CvMat
+    
+    :param object: Any object that supports the array interface 
+    
+    :param allowND: If true, will return a CvMatND 
+    
+If the object supports the `array interface <http://docs.scipy.org/doc/numpy/reference/arrays.interface.html>`_
+,
+return a :ocv:struct:`CvMat` or :ocv:struct:`CvMatND`, depending on ``allowND`` flag:
+
+  * If ``allowND = False``, then the object's array must be either 2D or 3D. If it is 2D, then the returned CvMat has a single channel.  If it is 3D, then the returned CvMat will have N channels, where N is the last dimension of the array. In this case, N cannot be greater than OpenCV's channel limit, ``CV_CN_MAX``.
+
+  * If``allowND = True``, then ``fromarray`` returns a single-channel :ocv:struct:`CvMatND` with the same shape as the original array.
+
+For example, `NumPy <http://numpy.scipy.org/>`_ arrays support the array interface, so can be converted to OpenCV objects:
+
+.. code-block::python
+    
+    >>> import cv, numpy
+    >>> a = numpy.ones((480, 640))
+    >>> mat = cv.fromarray(a)
+    >>> print cv.GetDims(mat), cv.CV_MAT_CN(cv.GetElemType(mat))
+    (480, 640) 1
+    >>> a = numpy.ones((480, 640, 3))
+    >>> mat = cv.fromarray(a)
+    >>> print cv.GetDims(mat), cv.CV_MAT_CN(cv.GetElemType(mat))
+    (480, 640) 3
+    >>> a = numpy.ones((480, 640, 3))
+    >>> mat = cv.fromarray(a, allowND = True)
+    >>> print cv.GetDims(mat), cv.CV_MAT_CN(cv.GetElemType(mat))
+    (480, 640, 3) 1
+
+.. note:: In the new Python wrappers (**cv2** module) the function is not needed, since cv2 can process  Numpy arrays (and this is the only supported array type).
+
diff --git a/modules/core/doc/old_xml_yaml_persistence.rst b/modules/core/doc/old_xml_yaml_persistence.rst
new file mode 100644 (file)
index 0000000..4c5f024
--- /dev/null
@@ -0,0 +1,909 @@
+XML/YAML Persistence (C API)
+==============================
+
+The section describes the OpenCV 1.x API for reading and writing data structures to/from XML or YAML files. It is now recommended to use the new C++ interface for reading and writing data.
+
+.. highlight:: c
+
+CvFileStorage
+-------------
+
+.. ocv:struct:: CvFileStorage
+
+The structure ``CvFileStorage`` is a "black box" representation of the file storage associated with a file on disk. Several functions that are described below take ``CvFileStorage*`` as inputs and allow the user to save or to load hierarchical collections that consist of scalar values, standard CXCore objects (such as matrices, sequences, graphs), and user-defined objects.
+
+OpenCV can read and write data in XML (http://www.w3c.org/XML) or YAML
+(http://www.yaml.org) formats. Below is an example of 3x3 floating-point identity matrix ``A``, stored in XML and YAML files using CXCore functions:
+
+XML: ::
+
+  <?xml version="1.0">
+  <opencv_storage>
+  <A type_id="opencv-matrix">
+    <rows>3</rows>
+    <cols>3</cols>
+    <dt>f</dt>
+    <data>1. 0. 0. 0. 1. 0. 0. 0. 1.</data>
+  </A>
+  </opencv_storage>
+
+YAML: ::
+
+  %YAML:1.0
+  A: !!opencv-matrix
+    rows: 3
+    cols: 3
+    dt: f
+    data: [ 1., 0., 0., 0., 1., 0., 0., 0., 1.]
+
+As it can be seen from the examples, XML uses nested tags to represent
+hierarchy, while YAML uses indentation for that purpose (similar
+to the Python programming language).
+
+The same functions can read and write data in both formats;
+the particular format is determined by the extension of the opened file, ".xml" for XML files and ".yml" or ".yaml" for YAML.
+
+CvFileNode
+----------
+
+.. ocv:struct:: CvFileNode
+
+File storage node. When XML/YAML file is read, it is first parsed and stored in the memory as a hierarchical collection of nodes. Each node can be a "leaf", that is, contain a single number or a string, or be a collection of other nodes. Collections are also referenced to as "structures" in the data writing functions. There can be named collections (mappings), where each element has a name and is accessed by a name, and ordered collections (sequences), where elements do not have names, but rather accessed by index.
+
+    .. ocv:member:: int tag
+    
+        type of the file node:
+        
+            * CV_NODE_NONE - empty node
+            * CV_NODE_INT - an integer
+            * CV_NODE_REAL - a floating-point number
+            * CV_NODE_STR - text string
+            * CV_NODE_SEQ - a sequence
+            * CV_NODE_MAP - a mapping
+
+        type of the node can be retrieved using ``CV_NODE_TYPE(node->tag)`` macro.
+
+    .. ocv:member:: CvTypeInfo* info
+    
+        optional pointer to the user type information. If you look at the matrix representation in XML and YAML, shown above, you may notice ``type_id="opencv-matrix"`` or ``!!opencv-matrix`` strings. They are used to specify that the certain element of a file is a representation of a data structure of certain type  ("opencv-matrix" corresponds to :ocv:struct:`CvMat`). When a file is parsed, such type identifiers are passed to :ocv:cfunc:`FindType` to find type information and the pointer to it is stored in the file node. See :ocv:struct:`CvTypeInfo` for more details.
+        
+    .. ocv:member:: union data
+    
+        the node data, declared as: ::
+        
+            union
+            {
+                double f; /* scalar floating-point number */
+                int i;    /* scalar integer number */
+                CvString str; /* text string */
+                CvSeq* seq; /* sequence (ordered collection of file nodes) */
+                struct CvMap* map; /* map (collection of named file nodes) */
+            } data;
+
+        ..
+        
+        Primitive nodes are read using :ocv:cfunc:`ReadInt`, :ocv:cfunc:`ReadReal` and :ocv:cfunc:`ReadString`. Sequences are read by iterating through ``node->data.seq`` (see "Dynamic Data Structures" section). Mappings are read using :ocv:cfunc:`GetFileNodeByName`. Nodes with the specified type (so that ``node->info != NULL``) can be read using :ocv:cfunc:`Read`.
+
+CvAttrList
+----------
+
+.. ocv:struct:: CvAttrList
+
+List of attributes. ::
+
+    typedef struct CvAttrList
+    {
+        const char** attr; /* NULL-terminated array of (attribute_name,attribute_value) pairs */
+        struct CvAttrList* next; /* pointer to next chunk of the attributes list */
+    }
+    CvAttrList;
+    
+    /* initializes CvAttrList structure */
+    inline CvAttrList cvAttrList( const char** attr=NULL, CvAttrList* next=NULL );
+    
+    /* returns attribute value or 0 (NULL) if there is no such attribute */
+    const char* cvAttrValue( const CvAttrList* attr, const char* attr_name );
+
+..
+
+In the current implementation, attributes are used to pass extra parameters when writing user objects (see 
+:ocv:cfunc:`Write`). XML attributes inside tags are not supported, aside from the object type specification (``type_id`` attribute).
+
+CvTypeInfo
+----------
+
+.. ocv:struct:: CvTypeInfo
+
+Type information. ::
+
+    typedef int (CV_CDECL *CvIsInstanceFunc)( const void* structPtr );
+    typedef void (CV_CDECL *CvReleaseFunc)( void** structDblPtr );
+    typedef void* (CV_CDECL *CvReadFunc)( CvFileStorage* storage, CvFileNode* node );
+    typedef void (CV_CDECL *CvWriteFunc)( CvFileStorage* storage,
+                                          const char* name,
+                                          const void* structPtr,
+                                          CvAttrList attributes );
+    typedef void* (CV_CDECL *CvCloneFunc)( const void* structPtr );
+    
+    typedef struct CvTypeInfo
+    {
+        int flags; /* not used */
+        int header_size; /* sizeof(CvTypeInfo) */
+        struct CvTypeInfo* prev; /* previous registered type in the list */
+        struct CvTypeInfo* next; /* next registered type in the list */
+        const char* type_name; /* type name, written to file storage */
+    
+        /* methods */
+        CvIsInstanceFunc is_instance; /* checks if the passed object belongs to the type */
+        CvReleaseFunc release; /* releases object (memory etc.) */
+        CvReadFunc read; /* reads object from file storage */
+        CvWriteFunc write; /* writes object to file storage */
+        CvCloneFunc clone; /* creates a copy of the object */
+    }
+    CvTypeInfo;
+
+..
+
+The structure contains information about one of the standard or user-defined types. Instances of the type may or may not contain a pointer to the corresponding  :ocv:struct:`CvTypeInfo` structure. In any case, there is a way to find the type info structure for a given object using the  :ocv:cfunc:`TypeOf` function. Aternatively, type info can be found by type name using :ocv:cfunc:`FindType`, which is used when an object is read from file storage. The user can register a new type with :ocv:cfunc:`RegisterType`
+that adds the type information structure into the beginning of the type list. Thus, it is possible to create specialized types from generic standard types and override the basic methods.
+
+Clone
+-----
+Makes a clone of an object.
+
+.. ocv:cfunction:: void* cvClone( const void* structPtr )
+    
+    :param structPtr: The object to clone 
+
+The function finds the type of a given object and calls ``clone`` with the passed object. Of course, if you know the object type, for example, ``structPtr`` is ``CvMat*``, it is faster to call the specific function, like :ocv:cfunc:`CloneMat`.
+
+EndWriteStruct
+--------------
+Finishes writing to a file node collection.
+
+.. ocv:cfunction:: void  cvEndWriteStruct(CvFileStorage* fs)
+
+    :param fs: File storage 
+
+.. seealso:: :ocv:cfunc:`StartWriteStruct`.
+
+FindType
+--------
+Finds a type by its name.
+
+.. ocv:cfunction:: CvTypeInfo* cvFindType(const char* typeName)
+    
+    :param typeName: Type name 
+
+The function finds a registered type by its name. It returns NULL if there is no type with the specified name.
+
+FirstType
+---------
+Returns the beginning of a type list.
+
+.. ocv:cfunction:: CvTypeInfo* cvFirstType(void)
+
+The function returns the first type in the list of registered types. Navigation through the list can be done via the ``prev`` and  ``next`` fields of the  :ocv:struct:`CvTypeInfo` structure.
+
+GetFileNode
+-----------
+Finds a node in a map or file storage.
+
+.. ocv:cfunction:: CvFileNode* cvGetFileNode( CvFileStorage* fs, CvFileNode* map, const CvStringHashNode* key, int createMissing=0 )
+    
+    :param fs: File storage 
+
+    :param map: The parent map. If it is NULL, the function searches a top-level node. If both  ``map``  and  ``key``  are NULLs, the function returns the root file node - a map that contains top-level nodes. 
+
+    :param key: Unique pointer to the node name, retrieved with  :ocv:cfunc:`GetHashedKey` 
+
+    :param createMissing: Flag that specifies whether an absent node should be added to the map 
+
+The function finds a file node. It is a faster version of  :ocv:cfunc:`GetFileNodeByName`
+(see :ocv:cfunc:`GetHashedKey` discussion). Also, the function can insert a new node, if it is not in the map yet.
+
+GetFileNodeByName
+-----------------
+Finds a node in a map or file storage.
+
+.. ocv:cfunction:: CvFileNode* cvGetFileNodeByName( const CvFileStorage* fs, const CvFileNode* map, const char* name)
+    
+    :param fs: File storage 
+
+    :param map: The parent map. If it is NULL, the function searches in all the top-level nodes (streams), starting with the first one. 
+
+    :param name: The file node name 
+
+The function finds a file node by ``name``. The node is searched either in ``map`` or, if the pointer is NULL, among the top-level file storage nodes. Using this function for maps and  :ocv:cfunc:`GetSeqElem`
+(or sequence reader) for sequences, it is possible to nagivate through the file storage. To speed up multiple queries for a certain key (e.g., in the case of an array of structures) one may use a combination of  :ocv:cfunc:`GetHashedKey` and :ocv:cfunc:`GetFileNode`.
+
+GetFileNodeName
+---------------
+Returns the name of a file node.
+
+.. ocv:cfunction:: const char* cvGetFileNodeName( const CvFileNode* node )
+
+    :param node: File node 
+
+The function returns the name of a file node or NULL, if the file node does not have a name or if  ``node`` is  ``NULL``.
+
+GetHashedKey
+------------
+Returns a unique pointer for a given name.
+
+.. ocv:cfunction:: CvStringHashNode* cvGetHashedKey( CvFileStorage* fs, const char* name, int len=-1, int createMissing=0 )
+
+    :param fs: File storage 
+
+    :param name: Literal node name 
+
+    :param len: Length of the name (if it is known apriori), or -1 if it needs to be calculated 
+
+    :param createMissing: Flag that specifies, whether an absent key should be added into the hash table 
+
+The function returns a unique pointer for each particular file node name. This pointer can be then passed to the :ocv:cfunc:`GetFileNode` function that is faster than  :ocv:cfunc:`GetFileNodeByName`
+because it compares text strings by comparing pointers rather than the strings' content.
+
+Consider the following example where an array of points is encoded as a sequence of 2-entry maps: ::
+    
+    points:
+      - { x: 10, y: 10 }
+      - { x: 20, y: 20 }
+      - { x: 30, y: 30 }
+      # ...
+
+..
+
+Then, it is possible to get hashed "x" and "y" pointers to speed up decoding of the points. ::
+
+    #include "cxcore.h"
+    
+    int main( int argc, char** argv )
+    {
+        CvFileStorage* fs = cvOpenFileStorage( "points.yml", 0, CV_STORAGE_READ );
+        CvStringHashNode* x_key = cvGetHashedNode( fs, "x", -1, 1 );
+        CvStringHashNode* y_key = cvGetHashedNode( fs, "y", -1, 1 );
+        CvFileNode* points = cvGetFileNodeByName( fs, 0, "points" );
+    
+        if( CV_NODE_IS_SEQ(points->tag) )
+        {
+            CvSeq* seq = points->data.seq;
+            int i, total = seq->total;
+            CvSeqReader reader;
+            cvStartReadSeq( seq, &reader, 0 );
+            for( i = 0; i < total; i++ )
+            {
+                CvFileNode* pt = (CvFileNode*)reader.ptr;
+    #if 1 /* faster variant */
+                CvFileNode* xnode = cvGetFileNode( fs, pt, x_key, 0 );
+                CvFileNode* ynode = cvGetFileNode( fs, pt, y_key, 0 );
+                assert( xnode && CV_NODE_IS_INT(xnode->tag) &&
+                        ynode && CV_NODE_IS_INT(ynode->tag));
+                int x = xnode->data.i; // or x = cvReadInt( xnode, 0 );
+                int y = ynode->data.i; // or y = cvReadInt( ynode, 0 );
+    #elif 1 /* slower variant; does not use x_key & y_key */
+                CvFileNode* xnode = cvGetFileNodeByName( fs, pt, "x" );
+                CvFileNode* ynode = cvGetFileNodeByName( fs, pt, "y" );
+                assert( xnode && CV_NODE_IS_INT(xnode->tag) &&
+                        ynode && CV_NODE_IS_INT(ynode->tag));
+                int x = xnode->data.i; // or x = cvReadInt( xnode, 0 );
+                int y = ynode->data.i; // or y = cvReadInt( ynode, 0 );
+    #else /* the slowest yet the easiest to use variant */
+                int x = cvReadIntByName( fs, pt, "x", 0 /* default value */ );
+                int y = cvReadIntByName( fs, pt, "y", 0 /* default value */ );
+    #endif
+                CV_NEXT_SEQ_ELEM( seq->elem_size, reader );
+                printf("
+            }
+        }
+        cvReleaseFileStorage( &fs );
+        return 0;
+    }
+..
+
+Please note that whatever method of accessing a map you are using, it is
+still much slower than using plain sequences; for example, in the above
+example, it is more efficient to encode the points as pairs of integers
+in a single numeric sequence.
+
+GetRootFileNode
+---------------
+Retrieves one of the top-level nodes of the file storage.
+
+.. ocv:cfunction:: CvFileNode* cvGetRootFileNode( const CvFileStorage* fs, int stream_index=0 )
+    
+    :param fs: File storage 
+
+    :param stream_index: Zero-based index of the stream. See  :ocv:cfunc:`StartNextStream` . In most cases, there is only one stream in the file; however, there can be several. 
+
+The function returns one of the top-level file nodes. The top-level nodes do not have a name, they correspond to the streams that are stored one after another in the file storage. If the index is out of range, the function returns a NULL pointer, so all the top-level nodes can be iterated by subsequent calls to the function with ``stream_index=0,1,...``, until the NULL pointer is returned. This function
+can be used as a base for recursive traversal of the file storage.
+
+
+Load
+----
+Loads an object from a file.
+
+.. ocv:cfunction:: void* cvLoad( const char* filename, CvMemStorage* storage=NULL, const char* name=NULL, const char** realName=NULL )
+.. ocv:pyoldfunction:: cv.Load(filename, storage=None, name=None)-> generic
+    
+    :param filename: File name 
+
+    :param storage: Memory storage for dynamic structures, such as  :ocv:struct:`CvSeq`  or  :ocv:struct:`CvGraph`  . It is not used for matrices or images. 
+
+    :param name: Optional object name. If it is NULL, the first top-level object in the storage will be loaded. 
+
+    :param realName: Optional output parameter that will contain the name of the loaded object (useful if  ``name=NULL`` ) 
+
+The function loads an object from a file. It basically reads the specified file, find the first top-level node and calls :ocv:cfunc:`Read` for that node. If the file node does not have type information or the type information can not be found by the type name, the function returns NULL. After the object is loaded, the file storage is closed and all the temporary buffers are deleted. Thus, to load a dynamic structure, such as a sequence, contour, or graph, one should pass a valid memory storage destination to the function.
+
+OpenFileStorage
+---------------
+Opens file storage for reading or writing data.
+
+.. ocv:cfunction:: CvFileStorage* cvOpenFileStorage( const char* filename, CvMemStorage* memstorage, int flags)
+
+    :param filename: Name of the file associated with the storage 
+
+    :param memstorage: Memory storage used for temporary data and for
+        storing dynamic structures, such as  :ocv:struct:`CvSeq`  or  :ocv:struct:`CvGraph` .
+        If it is NULL, a temporary memory storage is created and used. 
+
+    :param flags: Can be one of the following:
+
+            * **CV_STORAGE_READ** the storage is open for reading 
+
+            * **CV_STORAGE_WRITE** the storage is open for writing 
+
+The function opens file storage for reading or writing data. In the latter case, a new file is created or an existing file is rewritten. The type of the read or written file is determined by the filename extension:  ``.xml`` for  ``XML`` and  ``.yml`` or  ``.yaml`` for  ``YAML``. The function returns a pointer to the :ocv:struct:`CvFileStorage` structure.
+
+Read
+----
+Decodes an object and returns a pointer to it.
+
+.. ocv:cfunction:: void* cvRead( CvFileStorage* fs, CvFileNode* node, CvAttrList* attributes=NULL )
+    
+    :param fs: File storage 
+
+    :param node: The root object node 
+
+    :param attributes: Unused parameter 
+
+The function decodes a user object (creates an object in a native representation from the file storage subtree) and returns it. The object to be decoded must be an instance of a registered type that supports the ``read`` method (see :ocv:struct:`CvTypeInfo`). The type of the object is determined by the type name that is encoded in the file. If the object is a dynamic structure, it is created either in memory storage and passed to :ocv:cfunc:`OpenFileStorage` or, if a NULL pointer was passed, in temporary
+memory storage, which is released when :ocv:cfunc:`ReleaseFileStorage` is called. Otherwise, if the object is not a dynamic structure, it is created in a heap and should be released with a specialized function or by using the generic :ocv:cfunc:`Release`.
+
+ReadByName
+----------
+Finds an object by name and decodes it.
+
+.. ocv:cfunction:: void* cvReadByName( CvFileStorage* fs, const CvFileNode* map, const char* name, CvAttrList* attributes=NULL )
+    
+    :param fs: File storage 
+
+    :param map: The parent map. If it is NULL, the function searches a top-level node. 
+
+    :param name: The node name 
+
+    :param attributes: Unused parameter 
+
+The function is a simple superposition of :ocv:cfunc:`GetFileNodeByName` and  :ocv:cfunc:`Read`.
+
+ReadInt
+-------
+Retrieves an integer value from a file node.
+
+.. ocv:cfunction:: int cvReadInt( const CvFileNode* node, int defaultValue=0 )
+
+    :param node: File node 
+
+    :param defaultValue: The value that is returned if  ``node``  is NULL 
+
+The function returns an integer that is represented by the file node. If the file node is NULL, the 
+``defaultValue`` is returned (thus, it is convenient to call the function right after :ocv:cfunc:`GetFileNode` without checking for a NULL pointer). If the file node has type  ``CV_NODE_INT``, then  ``node->data.i`` is returned. If the file node has type  ``CV_NODE_REAL``, then  ``node->data.f``
+is converted to an integer and returned. Otherwise the error is reported.
+
+ReadIntByName
+-------------
+Finds a file node and returns its value.
+
+.. ocv:cfunction:: int cvReadIntByName( const CvFileStorage* fs, const CvFileNode* map, const char* name, int defaultValue=0 )
+
+    :param fs: File storage 
+
+    :param map: The parent map. If it is NULL, the function searches a top-level node. 
+
+    :param name: The node name 
+
+    :param defaultValue: The value that is returned if the file node is not found 
+
+The function is a simple superposition of  :ocv:cfunc:`GetFileNodeByName` and  :ocv:cfunc:`ReadInt`.
+
+ReadRawData
+-----------
+Reads multiple numbers.
+
+.. ocv:cfunction:: void cvReadRawData( const CvFileStorage* fs, const CvFileNode* src, void* dst, const char* dt)
+
+    :param fs: File storage 
+
+    :param src: The file node (a sequence) to read numbers from 
+
+    :param dst: Pointer to the destination array 
+
+    :param dt: Specification of each array element. It has the same format as in  :ocv:cfunc:`WriteRawData` . 
+
+The function reads elements from a file node that represents a sequence of scalars.
+
+
+ReadRawDataSlice
+----------------
+Initializes file node sequence reader.
+
+.. ocv:cfunction:: void cvReadRawDataSlice( const CvFileStorage* fs, CvSeqReader* reader, int count, void* dst, const char* dt )
+    
+    :param fs: File storage 
+
+    :param reader: The sequence reader. Initialize it with  :ocv:cfunc:`StartReadRawData` . 
+
+    :param count: The number of elements to read 
+
+    :param dst: Pointer to the destination array 
+
+    :param dt: Specification of each array element. It has the same format as in  :ocv:cfunc:`WriteRawData` . 
+
+The function reads one or more elements from the file node, representing a sequence, to a user-specified array. The total number of read sequence elements is a product of ``total``
+and the number of components in each array element. For example, if ``dt=2if``, the function will read ``total*3`` sequence elements. As with any sequence, some parts of the file node sequence can be skipped or read repeatedly by repositioning the reader using :ocv:cfunc:`SetSeqReaderPos`.
+
+ReadReal
+--------
+Retrieves a floating-point value from a file node.
+
+.. ocv:cfunction:: double cvReadReal( const CvFileNode* node, double defaultValue=0. )
+    
+    :param node: File node 
+
+    :param defaultValue: The value that is returned if  ``node``  is NULL 
+
+The function returns a floating-point value
+that is represented by the file node. If the file node is NULL, the
+``defaultValue``
+is returned (thus, it is convenient to call
+the function right after 
+:ocv:cfunc:`GetFileNode`
+without checking for a NULL
+pointer). If the file node has type 
+``CV_NODE_REAL``
+,
+then 
+``node->data.f``
+is returned. If the file node has type
+``CV_NODE_INT``
+, then 
+``node-:math:`>`data.f``
+is converted to floating-point
+and returned. Otherwise the result is not determined.
+
+
+ReadRealByName
+--------------
+Finds a file node and returns its value.
+
+.. ocv:cfunction:: double  cvReadRealByName( const CvFileStorage* fs, const CvFileNode* map, const char* name, double defaultValue=0.)
+    
+    :param fs: File storage 
+
+    :param map: The parent map. If it is NULL, the function searches a top-level node. 
+
+    :param name: The node name 
+
+    :param defaultValue: The value that is returned if the file node is not found 
+
+The function is a simple superposition of 
+:ocv:cfunc:`GetFileNodeByName`
+and 
+:ocv:cfunc:`ReadReal`
+.
+
+
+ReadString
+----------
+Retrieves a text string from a file node.
+
+.. ocv:cfunction:: const char* cvReadString( const CvFileNode* node, const char* defaultValue=NULL )
+    
+    :param node: File node 
+
+    :param defaultValue: The value that is returned if  ``node``  is NULL 
+
+The function returns a text string that is represented
+by the file node. If the file node is NULL, the 
+``defaultValue``
+is returned (thus, it is convenient to call the function right after
+:ocv:cfunc:`GetFileNode`
+without checking for a NULL pointer). If
+the file node has type 
+``CV_NODE_STR``
+, then 
+``node-:math:`>`data.str.ptr``
+is returned. Otherwise the result is not determined.
+
+
+ReadStringByName
+----------------
+Finds a file node by its name and returns its value.
+
+.. ocv:cfunction:: const char* cvReadStringByName( const CvFileStorage* fs, const CvFileNode* map, const char* name, const char* defaultValue=NULL )
+    
+    :param fs: File storage 
+
+    :param map: The parent map. If it is NULL, the function searches a top-level node. 
+
+    :param name: The node name 
+
+    :param defaultValue: The value that is returned if the file node is not found 
+
+The function is a simple superposition of 
+:ocv:cfunc:`GetFileNodeByName`
+and 
+:ocv:cfunc:`ReadString`
+.
+
+
+RegisterType
+------------
+Registers a new type.
+
+.. ocv:cfunction:: void cvRegisterType(const CvTypeInfo* info)
+
+    :param info: Type info structure 
+
+The function registers a new type, which is
+described by 
+``info``
+. The function creates a copy of the structure,
+so the user should delete it after calling the function.
+
+
+Release
+-------
+Releases an object.
+
+.. ocv:cfunction:: void cvRelease( void** structPtr )
+
+    :param structPtr: Double pointer to the object 
+
+The function finds the type of a given object and calls 
+``release``
+with the double pointer.
+
+
+ReleaseFileStorage
+------------------
+Releases file storage.
+
+.. ocv:cfunction:: void  cvReleaseFileStorage(CvFileStorage** fs)
+    
+    :param fs: Double pointer to the released file storage 
+
+The function closes the file associated with the storage and releases all the temporary structures. It must be called after all I/O operations with the storage are finished.
+
+
+Save
+----
+Saves an object to a file.
+
+.. ocv:cfunction:: void cvSave( const char* filename, const void* structPtr, const char* name=NULL, const char* comment=NULL, CvAttrList attributes=cvAttrList())
+.. ocv:pyoldfunction:: cv.Save(filename, structPtr, name=None, comment=None)-> None
+    
+    :param filename: File name 
+
+    :param structPtr: Object to save 
+
+    :param name: Optional object name. If it is NULL, the name will be formed from  ``filename`` . 
+
+    :param comment: Optional comment to put in the beginning of the file 
+
+    :param attributes: Optional attributes passed to  :ocv:cfunc:`Write` 
+
+The function saves an object to a file. It provides a simple interface to 
+:ocv:cfunc:`Write`
+.
+
+
+StartNextStream
+---------------
+Starts the next stream.
+
+.. ocv:cfunction:: void cvStartNextStream(CvFileStorage* fs)
+
+    :param fs: File storage 
+
+The function finishes the currently written stream and starts the next stream. In the case of XML the file with multiple streams looks like this: ::
+
+<opencv_storage>
+<!-- stream #1 data -->
+</opencv_storage>
+<opencv_storage>
+<!-- stream #2 data -->
+</opencv_storage>
+...
+
+The a YAML file will look like this:
+%YAML:1.0
+# stream #1 data
+...
+---
+# stream #2 data
+
+This is useful for concatenating files or for resuming the writing process.
+
+
+StartReadRawData
+----------------
+Initializes the file node sequence reader.
+
+.. ocv:cfunction:: void cvStartReadRawData( const CvFileStorage* fs, const CvFileNode* src, CvSeqReader* reader)
+
+    :param fs: File storage 
+
+    :param src: The file node (a sequence) to read numbers from 
+
+    :param reader: Pointer to the sequence reader 
+
+The function initializes the sequence reader to read data from a file node. The initialized reader can be then passed to :ocv:cfunc:`ReadRawDataSlice`.
+
+
+StartWriteStruct
+----------------
+Starts writing a new structure.
+
+.. ocv:cfunction:: void  cvStartWriteStruct( CvFileStorage* fs, const char* name, int struct_flags, const char* typeName=NULL, CvAttrList attributes=cvAttrList())
+    
+    :param fs: File storage 
+
+    :param name: Name of the written structure. The structure can be accessed by this name when the storage is read. 
+
+    :param struct_flags: A combination one of the following values: 
+         
+            * **CV_NODE_SEQ** the written structure is a sequence (see discussion of  :ocv:struct:`CvFileStorage` ), that is, its elements do not have a name. 
+            
+            * **CV_NODE_MAP** the written structure is a map (see discussion of  :ocv:struct:`CvFileStorage` ), that is, all its elements have names. 
+
+         One and only one of the two above flags must be specified 
+
+    :param CV_NODE_FLOW: the optional flag that makes sense only for YAML streams. It means that the structure is written as a flow (not as a block), which is more compact. It is recommended to use this flag for structures or arrays whose elements are all scalars. 
+
+    :param typeName: Optional parameter - the object type name. In
+        case of XML it is written as a  ``type_id``  attribute of the
+        structure opening tag. In the case of YAML it is written after a colon
+        following the structure name (see the example in  :ocv:struct:`CvFileStorage` 
+        description). Mainly it is used with user objects. When the storage
+        is read, the encoded type name is used to determine the object type
+        (see  :ocv:struct:`CvTypeInfo`  and  :ocv:cfunc:`FindTypeInfo` ). 
+
+    :param attributes: This parameter is not used in the current implementation 
+
+The function starts writing a compound structure (collection) that can be a sequence or a map. After all the structure fields, which can be scalars or structures, are written, :ocv:cfunc:`EndWriteStruct` should be called. The function can be used to group some objects or to implement the ``write`` function for a some user object (see :ocv:struct:`CvTypeInfo`).
+
+
+TypeOf
+------
+Returns the type of an object.
+
+.. ocv:cfunction:: CvTypeInfo* cvTypeOf( const void* structPtr )
+
+    :param structPtr: The object pointer 
+
+The function finds the type of a given object. It iterates through the list of registered types and calls the  ``is_instance`` function/method for every type info structure with that object until one of them returns non-zero or until the whole list has been traversed. In the latter case, the function returns NULL.
+
+
+UnregisterType
+--------------
+Unregisters the type.
+
+.. ocv:cfunction:: void cvUnregisterType( const char* typeName )
+    
+    :param typeName: Name of an unregistered type 
+
+The function unregisters a type with a specified name. If the name is unknown, it is possible to locate the type info by an instance of the type using :ocv:cfunc:`TypeOf` or by iterating the type list, starting from  :ocv:cfunc:`FirstType`, and then calling ``cvUnregisterType(info->typeName)``.
+
+
+Write
+-----
+Writes an object to file storage.
+
+.. ocv:cfunction:: void  cvWrite( CvFileStorage* fs, const char* name, const void* ptr, CvAttrList attributes=cvAttrList() )
+    
+    :param fs: File storage 
+
+    :param name: Name of the written object. Should be NULL if and only if the parent structure is a sequence. 
+
+    :param ptr: Pointer to the object 
+
+    :param attributes: The attributes of the object. They are specific for each particular type (see the dicsussion below).
+
+The function writes an object to file storage. First, the appropriate type info is found using :ocv:cfunc:`TypeOf`. Then, the ``write`` method associated with the type info is called.
+
+Attributes are used to customize the writing procedure. The standard types support the following attributes (all the ``dt`` attributes have the same format as in :ocv:cfunc:`WriteRawData`):
+
+#.
+    CvSeq
+
+        * **header_dt** description of user fields of the sequence header that follow CvSeq, or CvChain (if the sequence is a Freeman chain) or CvContour (if the sequence is a contour or point sequence) 
+
+        * **dt** description of the sequence elements. 
+
+        * **recursive** if the attribute is present and is not equal to "0" or "false", the whole tree of sequences (contours) is stored.
+
+#.
+    CvGraph
+
+        * **header_dt** description of user fields of the graph header that follows CvGraph; 
+
+        * **vertex_dt** description of user fields of graph vertices 
+
+        * **edge_dt** description of user fields of graph edges (note that the edge weight is always written, so there is no need to specify it explicitly)
+
+Below is the code that creates the YAML file shown in the 
+``CvFileStorage``
+description:
+
+::
+
+    #include "cxcore.h"
+    
+    int main( int argc, char** argv )
+    {
+        CvMat* mat = cvCreateMat( 3, 3, CV_32F );
+        CvFileStorage* fs = cvOpenFileStorage( "example.yml", 0, CV_STORAGE_WRITE );
+    
+        cvSetIdentity( mat );
+        cvWrite( fs, "A", mat, cvAttrList(0,0) );
+    
+        cvReleaseFileStorage( &fs );
+        cvReleaseMat( &mat );
+        return 0;
+    }
+
+..
+
+
+WriteComment
+------------
+Writes a comment.
+
+.. ocv:cfunction:: void  cvWriteComment( CvFileStorage* fs, const char* comment, int eolComment)
+
+    :param fs: File storage 
+
+    :param comment: The written comment, single-line or multi-line 
+
+    :param eolComment: If non-zero, the function tries to put the comment at the end of current line. If the flag is zero, if the comment is multi-line, or if it does not fit at the end of the current line, the comment starts  a new line. 
+
+The function writes a comment into file storage. The comments are skipped when the storage is read.
+
+WriteFileNode
+-------------
+Writes a file node to another file storage.
+
+.. ocv:cfunction:: void cvWriteFileNode( CvFileStorage* fs, const char* new_node_name, const CvFileNode* node, int embed )
+    
+    :param fs: Destination file storage 
+
+    :param new_file_node: New name of the file node in the destination file storage. To keep the existing name, use  :ocv:cfunc:`cvGetFileNodeName` 
+
+    :param node: The written node 
+
+    :param embed: If the written node is a collection and this parameter is not zero, no extra level of hiararchy is created. Instead, all the elements of  ``node``  are written into the currently written structure. Of course, map elements can only be embedded into another map, and sequence elements can only be embedded into another sequence. 
+
+The function writes a copy of a file node to file storage. Possible applications of the function are merging several file storages into one and conversion between XML and YAML formats.
+
+WriteInt
+--------
+Writes an integer value.
+
+.. ocv:cfunction:: void  cvWriteInt( CvFileStorage* fs, const char* name, int value)
+
+    :param fs: File storage 
+
+    :param name: Name of the written value. Should be NULL if and only if the parent structure is a sequence. 
+
+    :param value: The written value 
+
+The function writes a single integer value (with or without a name) to the file storage.
+
+
+WriteRawData
+------------
+Writes multiple numbers.
+
+.. ocv:cfunction:: void  cvWriteRawData( CvFileStorage* fs, const void* src, int len, const char* dt )
+    
+    :param fs: File storage 
+
+    :param src: Pointer to the written array 
+
+    :param len: Number of the array elements to write 
+
+    :param dt: Specification of each array element that has the following format  ``([count]{'u'|'c'|'w'|'s'|'i'|'f'|'d'})...`` 
+        where the characters correspond to fundamental C types: 
+
+            * **u** 8-bit unsigned number 
+
+            * **c** 8-bit signed number 
+
+            * **w** 16-bit unsigned number 
+
+            * **s** 16-bit signed number 
+
+            * **i** 32-bit signed number 
+
+            * **f** single precision floating-point number 
+
+            * **d** double precision floating-point number 
+
+            * **r** pointer, 32 lower bits of which are written as a signed integer. The type can be used to store structures with links between the elements. ``count``  is the optional counter of values of a given type. For
+                example,  ``2if``  means that each array element is a structure
+                of 2 integers, followed by a single-precision floating-point number. The
+                equivalent notations of the above specification are ' ``iif`` ',
+                ' ``2i1f`` ' and so forth. Other examples:  ``u``  means that the
+                array consists of bytes, and  ``2d``  means the array consists of pairs
+                of doubles.
+
+The function writes an array, whose elements consist
+of single or multiple numbers. The function call can be replaced with
+a loop containing a few 
+:ocv:cfunc:`WriteInt`
+and 
+:ocv:cfunc:`WriteReal`
+calls, but
+a single call is more efficient. Note that because none of the elements
+have a name, they should be written to a sequence rather than a map.
+
+
+WriteReal
+---------
+Writes a floating-point value.
+
+.. ocv:cfunction:: void  cvWriteReal( CvFileStorage* fs, const char* name, double value )
+    
+    :param fs: File storage 
+
+    :param name: Name of the written value. Should be NULL if and only if the parent structure is a sequence. 
+
+    :param value: The written value 
+
+The function writes a single floating-point value (with or without a name) to file storage. Special values are encoded as follows: NaN (Not A Number) as .NaN, infinity as +.Inf or -.Inf.
+
+The following example shows how to use the low-level writing functions to store custom structures, such as termination criteria, without registering a new type. ::
+
+    void write_termcriteria( CvFileStorage* fs, const char* struct_name,
+                             CvTermCriteria* termcrit )
+    {
+        cvStartWriteStruct( fs, struct_name, CV_NODE_MAP, NULL, cvAttrList(0,0));
+        cvWriteComment( fs, "termination criteria", 1 ); // just a description
+        if( termcrit->type & CV_TERMCRIT_ITER )
+            cvWriteInteger( fs, "max_iterations", termcrit->max_iter );
+        if( termcrit->type & CV_TERMCRIT_EPS )
+            cvWriteReal( fs, "accuracy", termcrit->epsilon );
+        cvEndWriteStruct( fs );
+    }
+
+..
+
+
+WriteString
+-----------
+Writes a text string.
+
+.. ocv:cfunction:: void  cvWriteString( CvFileStorage* fs, const char* name, const char* str, int quote=0 )
+
+    :param fs: File storage 
+
+    :param name: Name of the written string . Should be NULL if and only if the parent structure is a sequence. 
+
+    :param str: The written text string 
+
+    :param quote: If non-zero, the written string is put in quotes, regardless of whether they are required. Otherwise, if the flag is zero, quotes are used only when they are required (e.g. when the string starts with a digit or contains spaces). 
+
+The function writes a text string to file storage.
index 317d56d..1d5f937 100644 (file)
@@ -5,11 +5,11 @@ Operations on Arrays
 
 abs
 ---
+Computes an absolute value of each matrix element.
+
 .. ocv:function:: MatExpr abs(const Mat& src)
 .. ocv:function:: MatExpr abs(const MatExpr& src)
 
-    Computes an absolute value of each matrix element.
-
     :param src: Matrix or matrix expression.
     
 ``abs`` is a meta-function that is expanded to one of :ocv:func:`absdiff` forms:
@@ -18,18 +18,25 @@ abs
 
     * ``C = abs(A)``     is equivalent to ``absdiff(A, Scalar::all(0), C)``     
 
-    * ``C = Mat_<Vec<uchar,n> >(abs(A*alpha + beta))``     is equivalent to ``convertScaleAbs(A, C, alpha, beta)``
+    * ``C = Mat_<Vec<uchar,n> >(abs(A*alpha + beta))``     is equivalent to :ocv:funcx:`convertScaleAbs`(A, C, alpha, beta)`
     
-    The output matrix has the same size and the same type as the input one except for the last case, where ``C`` is ``depth=CV_8U`` .
+The output matrix has the same size and the same type as the input one except for the last case, where ``C`` is ``depth=CV_8U`` .
 
     .. seealso:: :ref:`MatrixExpressions`, :ocv:func:`absdiff`
 
 
 absdiff
 -----------
+Computes the per-element absolute difference between two arrays or between an array and a scalar.
+
 .. ocv:function:: void absdiff(InputArray src1, InputArray src2, OutputArray dst)
 
-    Computes the per-element absolute difference between two arrays or between an array and a scalar.
+.. ocv:pyfunction:: cv2.absdiff(src1, src2[, dst]) -> dst
+
+.. ocv:cfunction:: void cvAbsDiff(const CvArr* src1, const CvArr* src2, CvArr* dst)
+.. ocv:cfunction:: void cvAbsDiffS(const CvArr* src, CvArr* dst, CvScalar value)
+.. ocv:pyoldfunction:: cv.AbsDiff(src1, src2, dst)-> None
+.. ocv:pyoldfunction:: cv.AbsDiffS(src, dst, value)-> None
 
     :param src1: First input array or a scalar.
     
@@ -63,7 +70,7 @@ The function ``absdiff`` computes:
     where  ``I`` is a multi-dimensional index of array elements. In case of multi-channel arrays, each channel is processed independently.
 
 
-    .. seealso:: :ocv:func:`abs`
+.. seealso:: :ocv:func:`abs`
 
 
 add
@@ -72,7 +79,13 @@ add
 Computes the per-element sum of two arrays or an array and a scalar.
 
 .. ocv:function:: void add(InputArray src1, InputArray src2, OutputArray dst, InputArray mask=noArray(), int dtype=-1)
-.. ocv:pyfunction:: cv2.add(src1, src2 [, dst=None [, mask=None [, dtype=-1]]]) -> dst
+
+.. ocv:pyfunction:: cv2.add(src1, src2[, dst[, mask[, dtype]]]) -> dst
+
+.. ocv:cfunction:: void cvAdd(const CvArr* src1, const CvArr* src2, CvArr* dst, const CvArr* mask=NULL)
+.. ocv:cfunction:: void cvAddS(const CvArr* src, CvScalar value, CvArr* dst, const CvArr* mask=NULL)
+.. ocv:pyoldfunction:: cv.Add(src1, src2, dst, mask=None)-> None
+.. ocv:pyoldfunction:: cv.AddS(src, value, dst, mask=None)-> None
 
     :param src1: First source array or a scalar.
 
@@ -121,16 +134,21 @@ The input arrays and the destination array can all have the same or different de
     :ocv:func:`subtract`,
     :ocv:func:`addWeighted`,
     :ocv:func:`scaleAdd`,
-    :ocv:func:`convertScale`,
+    :ocv:func:`Mat::convertTo`,
     :ref:`MatrixExpressions`
 
 
 
 addWeighted
 ---------------
+Computes the weighted sum of two arrays.
+
 .. ocv:function:: void addWeighted(InputArray src1, double alpha, InputArray src2, double beta, double gamma, OutputArray dst, int dtype=-1)
 
-    Computes the weighted sum of two arrays.
+.. ocv:pyfunction:: cv2.addWeighted(src1, alpha, src2, beta, gamma[, dst[, dtype]]) -> dst
+
+.. ocv:cfunction:: void cvAddWeighted(const CvArr* src1, double alpha, const CvArr* src2, double beta, double gamma, CvArr* dst)
+.. ocv:pyoldfunction:: cv.AddWeighted(src1, alpha, src2, beta, gamma, dst)-> None
 
     :param src1: First source array.
 
@@ -164,16 +182,23 @@ The function can be replaced with a matrix expression: ::
     :ocv:func:`add`,
     :ocv:func:`subtract`,
     :ocv:func:`scaleAdd`,
-    :ocv:func:`convertScale`,
+    :ocv:func:`Mat::convertTo`,
     :ref:`MatrixExpressions`
 
 
 
 bitwise_and
 -----------
+Calculates the per-element bit-wise conjunction of two arrays or an array and a scalar.
+
 .. ocv:function:: void bitwise_and(InputArray src1, InputArray src2, OutputArray dst, InputArray mask=noArray())
 
-    Calculates the per-element bit-wise conjunction of two arrays or an array and a scalar.
+.. ocv:pyfunction:: cv2.bitwise_and(src1, src2[, dst[, mask]]) -> dst
+
+.. ocv:cfunction:: void cvAnd(const CvArr* src1, const CvArr* src2, CvArr* dst, const CvArr* mask=NULL)
+.. ocv:cfunction:: void cvAndS(const CvArr* src, CvScalar value, CvArr* dst, const CvArr* mask=NULL)
+.. ocv:pyoldfunction:: cv.And(src1, src2, dst, mask=None)-> None
+.. ocv:pyoldfunction:: cv.AndS(src, value, dst, mask=None)-> None
 
     :param src1: First source array or a scalar.
 
@@ -213,9 +238,14 @@ In case of floating-point arrays, their machine-specific bit representations (us
 
 bitwise_not
 -----------
+Inverts every bit of an array.
+
 .. ocv:function:: void bitwise_not(InputArray src, OutputArray dst, InputArray mask=noArray())
 
-    Inverts every bit of an array.
+.. ocv:pyfunction:: cv2.bitwise_not(src[, dst[, mask]]) -> dst
+
+.. ocv:cfunction:: void cvNot(const CvArr* src, CvArr* dst)
+.. ocv:pyoldfunction:: cv.Not(src, dst)-> None
 
     :param src: Source array.
 
@@ -235,9 +265,16 @@ In case of a floating-point source array, its machine-specific bit representatio
 
 bitwise_or
 ----------
+Calculates the per-element bit-wise disjunction of two arrays or an array and a scalar.
+
 .. ocv:function:: void bitwise_or(InputArray src1, InputArray src2, OutputArray dst, InputArray mask=noArray())
 
-    Calculates the per-element bit-wise disjunction of two arrays or an array and a scalar.
+.. ocv:pyfunction:: cv2.bitwise_or(src1, src2[, dst[, mask]]) -> dst
+
+.. ocv:cfunction:: void cvOr(const CvArr* src1, const CvArr* src2, CvArr* dst, const CvArr* mask=NULL)
+.. ocv:cfunction:: void cvOrS(const CvArr* src, CvScalar value, CvArr* dst, const CvArr* mask=NULL)
+.. ocv:pyoldfunction:: cv.Or(src1, src2, dst, mask=None)-> None
+.. ocv:pyoldfunction:: cv.OrS(src, value, dst, mask=None)-> None
 
     :param src1: First source array or a scalar.
 
@@ -274,13 +311,18 @@ The function computes the per-element bit-wise logical disjunction for:
 In case of floating-point arrays, their machine-specific bit representations (usually IEEE754-compliant) are used for the operation. In case of multi-channel arrays, each channel is processed independently. In the second and third cases above, the scalar is first converted to the array type.
     
 
-
-
 bitwise_xor
 -----------
+Calculates the per-element bit-wise "exclusive or" operation on two arrays or an array and a scalar.
+
 .. ocv:function:: void bitwise_xor(InputArray src1, InputArray src2, OutputArray dst, InputArray mask=noArray())
 
-    Calculates the per-element bit-wise "exclusive or" operation on two arrays or an array and a scalar.
+.. ocv:pyfunction:: cv2.bitwise_xor(src1, src2[, dst[, mask]]) -> dst
+
+.. ocv:cfunction:: void cvXor(const CvArr* src1, const CvArr* src2, CvArr* dst, const CvArr* mask=NULL)
+.. ocv:cfunction:: void cvXorS(const CvArr* src, CvScalar value, CvArr* dst, const CvArr* mask=NULL)
+.. ocv:pyoldfunction:: cv.Xor(src1, src2, dst, mask=None)-> None
+.. ocv:pyoldfunction:: cv.XorS(src, value, dst, mask=None)-> None
 
     :param src1: First source array or a scalar.
 
@@ -319,12 +361,16 @@ In case of floating-point arrays, their machine-specific bit representations (us
 
 calcCovarMatrix
 ---------------
+Calculates the covariance matrix of a set of vectors.
 
 .. ocv:function:: void calcCovarMatrix( const Mat* samples, int nsamples, Mat& covar, Mat& mean, int flags, int ctype=CV_64F)
 
 .. ocv:function:: void calcCovarMatrix( InputArray samples, OutputArray covar, OutputArray mean, int flags, int ctype=CV_64F)
 
-    Calculates the covariance matrix of a set of vectors.
+.. ocv:pyfunction:: cv2.calcCovarMatrix(samples, flags[, covar[, mean[, ctype]]]) -> covar, mean
+
+.. ocv:cfunction:: void cvCalcCovarMatrix( const CvArr** vects, int count, CvArr* covMat, CvArr* avg, int flags)
+.. ocv:pyoldfunction:: cv.CalcCovarMatrix(vects, covMat, avg, flags)-> None
 
     :param samples: Samples stored either as separate matrices or as rows/columns of a single matrix.
 
@@ -372,10 +418,14 @@ The functions ``calcCovarMatrix`` calculate the covariance matrix and, optionall
 
 cartToPolar
 -----------
+Calculates the magnitude and angle of 2D vectors.
 
 .. ocv:function:: void cartToPolar(InputArray x, InputArray y, OutputArray magnitude, OutputArray angle, bool angleInDegrees=false)
 
-    Calculates the magnitude and angle of 2D vectors.
+.. ocv:pyfunction:: cv2.cartToPolar(x, y[, magnitude[, angle[, angleInDegrees]]]) -> magnitude, angle
+
+.. ocv:cfunction:: void cvCartToPolar( const CvArr* x, const CvArr* y, CvArr* magnitude, CvArr* angle=NULL, int angleInDegrees=0)
+.. ocv:pyoldfunction:: cv.CartToPolar(x, y, magnitude, angle=None, angleInDegrees=0)-> None
 
     :param x: Array of x-coordinates. This must be a single-precision or double-precision floating-point array.
 
@@ -399,10 +449,11 @@ The angles are calculated with accuracy about 0.3 degrees. For the point (0,0),
 
 checkRange
 ----------
+Checks every element of an input array for invalid values.
 
 .. ocv:function:: bool checkRange(InputArray src, bool quiet=true, Point* pos=0, double minVal=-DBL_MAX, double maxVal=DBL_MAX)
 
-    Checks every element of an input array for invalid values.
+.. ocv:pyfunction:: cv2.checkRange(a[, quiet[, minVal[, maxVal]]]) -> retval, pt
 
     :param src: Array to check.
 
@@ -423,14 +474,23 @@ If some values are out of range, position of the first outlier is stored in ``po
 
 compare
 -------
+Performs the per-element comparison of two arrays or an array and scalar value.
 
 .. ocv:function:: void compare(InputArray src1, InputArray src2, OutputArray dst, int cmpop)
 
-    Performs the per-element comparison of two arrays or an array and scalar value.
+.. ocv:pyfunction:: cv2.compare(src1, src2, cmpop[, dst]) -> dst
 
-    :param src1: First source array or a scalar.
+.. ocv:cfunction:: void cvCmp(const CvArr* src1, const CvArr* src2, CvArr* dst, int cmpOp)
 
-    :param src2: Second source array or a scalar.
+.. ocv:pyoldfunction:: cv.Cmp(src1, src2, dst, cmpOp)-> None
+
+.. ocv:cfunction:: void cvCmpS(const CvArr* src1, double src2, CvArr* dst, int cmpOp)
+
+.. ocv:pyoldfunction:: cv.CmpS(src1, src2, dst, cmpOp)-> None
+
+    :param src1: First source array or a scalar (in the case of ``cvCmp``, ``cv.Cmp``, ``cvCmpS``, ``cv.CmpS`` it is always an array). When it is array, it must have a single channel.
+
+    :param src2: Second source array or a scalar (in the case of ``cvCmp`` and ``cv.Cmp`` it is always an array; in the case of ``cvCmpS``, ``cv.CmpS`` it is always a scalar). When it is array, it must have a single channel.
     
     :param dst: Destination array that has the same size as the input array(s) and type= ``CV_8UC1`` .
     
@@ -451,21 +511,21 @@ The function compares:
 
    .. math::
 
-       \texttt{dst} (I) =  \texttt{src1} (I)  \,cmpop\, \texttt{src2} (I)
+       \texttt{dst} (I) =  \texttt{src1} (I)  \,\texttt{cmpop}\, \texttt{src2} (I)
 
  *
    Elements of ``src1`` with a scalar ``src2` when ``src2`` is constructed from ``Scalar`` or has a single element:
 
    .. math::
 
-       \texttt{dst} (I) =  \texttt{src1}(I) \,cmpop\,  \texttt{src2}
+       \texttt{dst} (I) =  \texttt{src1}(I) \,\texttt{cmpop}\,  \texttt{src2}
 
  *
    ``src1`` with elements of ``src2`` when ``src1`` is constructed from ``Scalar`` or has a single element:
 
    .. math::
 
-       \texttt{dst} (I) =  \texttt{src1}  \,cmpop\, \texttt{src2} (I)
+       \texttt{dst} (I) =  \texttt{src1}  \,\texttt{cmpop}\, \texttt{src2} (I)
 
 
 When the comparison result is true, the corresponding element of destination array is set to 255.    
@@ -488,10 +548,11 @@ The comparison operations can be replaced with the equivalent matrix expressions
 
 completeSymm
 ------------
+Copies the lower or the upper half of a square matrix to another half.
 
 .. ocv:function:: void completeSymm(InputOutputArray mtx, bool lowerToUpper=false)
 
-    Copies the lower or the upper half of a square matrix to another half.
+.. ocv:pyfunction:: cv2.completeSymm(mtx[, lowerToUpper]) -> None
 
     :param mtx: Input-output floating-point square matrix.
 
@@ -516,10 +577,14 @@ The function ``completeSymm`` copies the lower half of a square matrix to its an
 
 convertScaleAbs
 ---------------
+Scales, computes absolute values, and converts the result to 8-bit.
 
 .. ocv:function:: void convertScaleAbs(InputArray src, OutputArray dst, double alpha=1, double beta=0)
 
-    Scales, computes absolute values, and converts the result to 8-bit.
+.. ocv:pyfunction:: cv2.convertScaleAbs(src[, dst[, alpha[, beta]]]) -> dst
+
+.. ocv:cfunction:: void cvConvertScaleAbs(const CvArr* src, CvArr* dst, double scale=1, double shift=0)
+.. ocv:pyoldfunction:: cv.ConvertScaleAbs(src, dst, scale=1.0, shift=0.0)-> None
 
     :param src: Source array.
 
@@ -555,10 +620,14 @@ In case of multi-channel arrays, the function processes each channel independent
 
 countNonZero
 ------------
+Counts non-zero array elements.
 
 .. ocv:function:: int countNonZero( InputArray mtx )
 
-    Counts non-zero array elements.
+.. ocv:pyfunction:: cv2.countNonZero(src) -> retval
+
+.. ocv:cfunction:: int cvCountNonZero(const CvArr* arr)
+.. ocv:pyoldfunction:: cv.CountNonZero(arr)-> int
 
     :param mtx: Single-channel array.
 
@@ -578,26 +647,12 @@ The function returns the number of non-zero elements in ``mtx`` :
 
 
 
-cubeRoot
---------
-
-.. ocv:function:: float cubeRoot(float val)
-
-    Computes the cube root of an argument.
-
-    :param val: A function argument.
-
-The function ``cubeRoot`` computes :math:`\sqrt[3]{\texttt{val}}`. Negative arguments are handled correctly. NaN and Inf are not handled. The accuracy approaches the maximum possible accuracy for single-precision data.
-
-
-
 cvarrToMat
 ----------
+Converts ``CvMat``, ``IplImage`` , or ``CvMatND`` to ``Mat``.
 
 .. ocv:function:: Mat cvarrToMat(const CvArr* src, bool copyData=false, bool allowND=true, int coiMode=0)
 
-    Converts ``CvMat``, ``IplImage`` , or ``CvMatND`` to ``Mat``.
-
     :param src: Source ``CvMat``, ``IplImage`` , or  ``CvMatND`` .
     
     :param copyData: When it is false (default value), no data is copied and only the new header is created. In this case, the original array should not be deallocated while the new matrix header is used. If the parameter is true, all the data is copied and you may deallocate the original array right after the conversion.
@@ -658,9 +713,14 @@ The last parameter, ``coiMode`` , specifies how to deal with an image with COI s
 
 dct
 -------
+Performs a forward or inverse discrete Cosine transform of 1D or 2D array.
+
 .. ocv:function:: void dct(InputArray src, OutputArray dst, int flags=0)
 
-    Performs a forward or inverse discrete Cosine transform of 1D or 2D array.
+.. ocv:pyfunction:: cv2.dct(src[, dst[, flags]]) -> dst
+
+.. ocv:cfunction:: void cvDCT(const CvArr* src, CvArr* dst, int flags)
+.. ocv:pyoldfunction:: cv.DCT(src, dst, flags)-> None
 
     :param src: Source floating-point array.
 
@@ -747,10 +807,14 @@ The function chooses the mode of operation by looking at the flags and size of t
 
 dft
 ---
+Performs a forward or inverse Discrete Fourier transform of a 1D or 2D floating-point array.
 
 .. ocv:function:: void dft(InputArray src, OutputArray dst, int flags=0, int nonzeroRows=0)
 
-    Performs a forward or inverse Discrete Fourier transform of a 1D or 2D floating-point array.
+.. ocv:pyfunction:: cv2.dft(src[, dst[, flags[, nonzeroRows]]]) -> dst
+
+.. ocv:cfunction:: void cvDFT(const CvArr* src, CvArr* dst, int flags, int nonzeroRows=0)
+.. ocv:pyoldfunction:: cv.DFT(src, dst, flags, nonzeroRows=0)-> None
 
     :param src: Source array that could be real or complex.
 
@@ -896,11 +960,17 @@ All of the above improvements have been implemented in :ocv:func:`matchTemplate`
 
 divide
 ----------
+Performs per-element division of two arrays or a scalar by an array.
+
 .. ocv:function:: void divide(InputArray src1, InputArray src2, OutputArray dst, double scale=1, int dtype=-1)
 
 .. ocv:function:: void divide(double scale, InputArray src2, OutputArray dst, int dtype=-1)
 
-    Performs per-element division of two arrays or a scalar by an array.
+.. ocv:pyfunction:: cv2.divide(src1, src2[, dst[, scale[, dtype]]]) -> dst
+.. ocv:pyfunction:: cv2.divide(scale, src2[, dst[, dtype]]) -> dst
+
+.. ocv:cfunction:: void cvDiv(const CvArr* src1, const CvArr* src2, CvArr* dst, double scale=1)
+.. ocv:pyoldfunction:: cv.Div(src1, src2, dst, scale)-> None
 
     :param src1: First source array.
 
@@ -937,10 +1007,14 @@ When ``src2(I)`` is zero, ``dst(I)`` will also be zero. Different channels of mu
 
 determinant
 -----------
+Returns the determinant of a square floating-point matrix.
 
 .. ocv:function:: double determinant(InputArray mtx)
 
-    Returns the determinant of a square floating-point matrix.
+.. ocv:pyfunction:: cv2.determinant(mtx) -> retval
+
+.. ocv:cfunction:: double cvDet(const CvArr* mtx)
+.. ocv:pyoldfunction:: cv.Det(mtx)-> double
 
     :param mtx: Input matrix that must have  ``CV_32FC1``  or  ``CV_64FC1``  type and square size.
 
@@ -966,8 +1040,14 @@ eigen
 
 .. ocv:function:: bool eigen(InputArray src, OutputArray eigenvalues, OutputArray eigenvectors, int lowindex=-1,int highindex=-1)
 
+.. ocv:cfunction:: void cvEigenVV( CvArr* src, CvArr* eigenvectors, CvArr* eigenvalues, double eps=0, int lowindex=-1, int highindex=-1)
+
+.. ocv:pyoldfunction:: cv.EigenVV(src, eigenvectors, eigenvalues, eps, lowindex=-1, highindex=-1)-> None
+
     Computes eigenvalues and eigenvectors of a symmetric matrix.
 
+.. ocv:pyfunction:: cv2.eigen(src, computeEigenvectors[, eigenvalues[, eigenvectors[, lowindex[, highindex]]]]) -> retval, eigenvalues, eigenvectors
+
     :param src: Input matrix that must have  ``CV_32FC1``  or  ``CV_64FC1``  type, square size and be symmetrical (``src`` :sup:`T` == ``src``).
     
     :param eigenvalues: Output vector of eigenvalues of the same type as  ``src`` . The eigenvalues are stored in the descending order.
@@ -982,16 +1062,22 @@ The functions ``eigen`` compute just eigenvalues, or eigenvalues and eigenvector
 
     src*eigenvectors.row(i).t() = eigenvalues.at<srcType>(i)*eigenvectors.row(i).t()
 
+.. note:: in the new and the old interfaces different ordering of eigenvalues and eigenvectors parameters is used.
+
 .. seealso:: :ocv:func:`completeSymm` , :ocv:class:`PCA`
 
 
 
 exp
 ---
+Calculates the exponent of every array element.
 
 .. ocv:function:: void exp(InputArray src, OutputArray dst)
 
-    Calculates the exponent of every array element.
+.. ocv:pyfunction:: cv2.exp(src[, dst]) -> dst
+
+.. ocv:cfunction:: void cvExp(const CvArr* src, CvArr* dst)
+.. ocv:pyoldfunction:: cv.Exp(src, dst)-> None
 
     :param src: Source array.
 
@@ -1001,7 +1087,7 @@ The function ``exp`` calculates the exponent of every element of the input array
 
 .. math::
 
-    \texttt{dst} [I] = e^{ \texttt{src} }(I)
+    \texttt{dst} [I] = e^{ src(I) }
 
 The maximum relative error is about ``7e-6`` for single-precision input and less than ``1e-10`` for double-precision input. Currently, the function converts denormalized values to zeros on output. Special values (NaN, Inf) are not handled.
 
@@ -1011,11 +1097,10 @@ The maximum relative error is about ``7e-6`` for single-precision input and less
 
 extractImageCOI
 ---------------
+Extracts the selected image channel.
 
 .. ocv:function:: void extractImageCOI(const CvArr* src, OutputArray dst, int coi=-1)
 
-    Extracts the selected image channel.
-
     :param src: Source array. It should be a pointer to  ``CvMat``  or  ``IplImage`` .
     
     :param dst: Destination array with a single channel and the same size and depth as  ``src`` .
@@ -1028,30 +1113,20 @@ To extract a channel from a new-style matrix, use
 :ocv:func:`mixChannels` or
 :ocv:func:`split` .
 
-.. seealso::  :ocv:func:`mixChannels` , :ocv:func:`split` , :ocv:func:`merge` , :ocv:func:`cvarrToMat` , :ocv:func:`cvSetImageCOI` , :ocv:func:`cvGetImageCOI`
-
-
-
-fastAtan2
----------
-
-.. ocv:function:: float fastAtan2(float y, float x)
-
-    Calculates the angle of a 2D vector in degrees.
-
-    :param x: x-coordinate of the vector.
-
-    :param y: y-coordinate of the vector.
-
-The function ``fastAtan2`` calculates the full-range angle of an input 2D vector. The angle is measured in degrees and varies from 0 to 360 degrees. The accuracy is about 0.3 degrees.
+.. seealso::  :ocv:func:`mixChannels` , :ocv:func:`split` , :ocv:func:`merge` , :ocv:func:`cvarrToMat` , :ocv:cfunc:`cvSetImageCOI` , :ocv:cfunc:`cvGetImageCOI`
 
 
 
 flip
 --------
+Flips a 2D array around vertical, horizontal, or both axes.
+
 .. ocv:function:: void flip(InputArray src, OutputArray dst, int flipCode)
 
-    Flips a 2D array around vertical, horizontal, or both axes.
+.. ocv:pyfunction:: cv2.flip(src, flipCode[, dst]) -> dst
+
+.. ocv:cfunction:: void cvFlip(const CvArr* src, CvArr* dst=NULL, int flipMode=0)
+.. ocv:pyoldfunction:: cv.Flip(src, dst=None, flipMode=0)-> None
 
     :param src: Source array.
 
@@ -1063,9 +1138,14 @@ The function ``flip`` flips the array in one of three different ways (row and co
 
 .. math::
 
-    \texttt{dst} _{ij} =  \forkthree{\texttt{src}_{\texttt{src.rows}-i-1,j} }{if  \texttt{flipCode} = 0}
-    { \texttt{src} _{i, \texttt{src.cols} -j-1}}{if  \texttt{flipCode} > 0}
-    { \texttt{src} _{ \texttt{src.rows} -i-1, \texttt{src.cols} -j-1}}{if  \texttt{flipCode} < 0}
+    \texttt{dst} _{ij} =
+    \left\{
+    \begin{array}{l l}
+    \texttt{src} _{\texttt{src.rows}-i-1,j} & if\;  \texttt{flipCode} = 0 \\
+    \texttt{src} _{i, \texttt{src.cols} -j-1} & if\;  \texttt{flipCode} > 0 \\
+    \texttt{src} _{ \texttt{src.rows} -i-1, \texttt{src.cols} -j-1} & if\; \texttt{flipCode} < 0 \\
+    \end{array}
+    \right.
 
 The example scenarios of using the function are the following:
 
@@ -1087,10 +1167,14 @@ The example scenarios of using the function are the following:
 
 gemm
 ----
+Performs generalized matrix multiplication.
 
 .. ocv:function:: void gemm(InputArray src1, InputArray src2, double alpha, InputArray src3, double beta, OutputArray dst, int flags=0)
 
-    Performs generalized matrix multiplication.
+.. ocv:pyfunction:: cv2.gemm(src1, src2, alpha, src3, gamma[, dst[, flags]]) -> dst
+
+.. ocv:cfunction:: void cvGEMM( const CvArr* src1, const CvArr* src2, double alpha, const CvArr* src3, double beta, CvArr* dst, int tABC=0)
+.. ocv:pyoldfunction:: cv.GEMM(src1, src2, alphs, src3, beta, dst, tABC=0)-> None
 
     :param src1: First multiplied input matrix that should have  ``CV_32FC1`` , ``CV_64FC1`` , ``CV_32FC2`` , or  ``CV_64FC2``  type.
 
@@ -1127,13 +1211,12 @@ The function can be replaced with a matrix expression. For example, the above ca
 
 getConvertElem
 --------------
+Returns a conversion function for a single pixel.
 
 .. ocv:function:: ConvertData getConvertElem(int fromType, int toType)
 
 .. ocv:function:: ConvertScaleData getConvertScaleElem(int fromType, int toType)
 
-    Returns a conversion function for a single pixel.
-
     :param fromType: Source pixel type.
 
     :param toType: Destination pixel type.
@@ -1162,10 +1245,14 @@ The functions ``getConvertElem`` and ``getConvertScaleElem`` return pointers to
 
 getOptimalDFTSize
 -----------------
+Returns the optimal DFT size for a given vector size.
 
 .. ocv:function:: int getOptimalDFTSize(int vecsize)
 
-    Returns the optimal DFT size for a given vector size.
+.. ocv:pyfunction:: cv2.getOptimalDFTSize(vecsize) -> retval
+
+.. ocv:cfunction:: int cvGetOptimalDFTSize(int size0)
+.. ocv:pyoldfunction:: cv.GetOptimalDFTSize(size0)-> int
 
     :param vecsize: Vector size.
 
@@ -1184,10 +1271,11 @@ While the function cannot be used directly to estimate the optimal vector size f
 
 idct
 ----
+Computes the inverse Discrete Cosine Transform of a 1D or 2D array.
 
 .. ocv:function:: void idct(InputArray src, OutputArray dst, int flags=0)
 
-    Computes the inverse Discrete Cosine Transform of a 1D or 2D array.
+.. ocv:pyfunction:: cv2.idct(src[, dst[, flags]]) -> dst
 
     :param src: Source floating-point single-channel array.
 
@@ -1208,10 +1296,11 @@ idct
 
 idft
 ----
+Computes the inverse Discrete Fourier Transform of a 1D or 2D array.
 
 .. ocv:function:: void idft(InputArray src, OutputArray dst, int flags=0, int outputRows=0)
 
-    Computes the inverse Discrete Fourier Transform of a 1D or 2D array.
+.. ocv:pyfunction:: cv2.idft(src[, dst[, flags[, nonzeroRows]]]) -> dst
 
     :param src: Source floating-point real or complex array.
 
@@ -1239,10 +1328,16 @@ See :ocv:func:`dft` for details.
 
 inRange
 -------
+Checks if array elements lie between the elements of two other arrays.
 
 .. ocv:function:: void inRange(InputArray src, InputArray lowerb, InputArray upperb, OutputArray dst)
 
-    Checks if array elements lie between the elements of two other arrays.
+.. ocv:pyfunction:: cv2.inRange(src, lowerb, upperb[, dst]) -> dst
+
+.. ocv:cfunction:: void cvInRange(const CvArr* src, const CvArr* lower, const CvArr* upper, CvArr* dst)
+.. ocv:cfunction:: void cvInRangeS(const CvArr* src, CvScalar lower, CvScalar upper, CvArr* dst)
+.. ocv:pyoldfunction:: cv.InRange(src, lower, upper, dst)-> None
+.. ocv:pyoldfunction:: cv.InRangeS(src, lower, upper, dst)-> None
 
     :param src: First source array.
 
@@ -1254,32 +1349,35 @@ inRange
 
 The function checks the range as follows:
 
- * For every element of the input array:
+ * For every element of a single-channel input array:
 
    .. math::
 
       \texttt{dst} (I)= \texttt{lowerb} (I)_0  \leq \texttt{src} (I)_0 <  \texttt{upperb} (I)_0
 
- * For single-channel arrays:
+ * For two-channel arrays:
 
    .. math::
 
       \texttt{dst} (I)= \texttt{lowerb} (I)_0  \leq \texttt{src} (I)_0 <  \texttt{upperb} (I)_0  \land \texttt{lowerb} (I)_1  \leq \texttt{src} (I)_1 <  \texttt{upperb} (I)_1
 
- * For two-channel arrays and so forth. 
+ * and so forth.
 
-``dst`` (I) is set to 255 (all ``1`` -bits) if ``src`` (I) is within the specified range and 0 otherwise.
+That is, ``dst`` (I) is set to 255 (all ``1`` -bits) if ``src`` (I) is within the specified 1D, 2D, 3D, ... box and 0 otherwise.
 
 When the lower and/or upper bounary parameters are scalars, the indexes ``(I)`` at ``lowerb`` and ``upperb`` in the above formulas should be omitted.
 
 
-
 invert
 ------
+Finds the inverse or pseudo-inverse of a matrix.
 
 .. ocv:function:: double invert(InputArray src, OutputArray dst, int method=DECOMP_LU)
 
-    Finds the inverse or pseudo-inverse of a matrix.
+.. ocv:pyfunction:: cv2.invert(src[, dst[, flags]]) -> retval, dst
+
+.. ocv:cfunction:: double cvInvert(const CvArr* src, CvArr* dst, int method=CV_LU)
+.. ocv:pyoldfunction:: cv.Invert(src, dst, method=CV_LU)-> double
 
     :param src: Source floating-point  ``M x N``  matrix.
 
@@ -1311,10 +1409,14 @@ Similarly to ``DECOMP_LU`` , the method ``DECOMP_CHOLESKY`` works only with non-
 
 log
 ---
+Calculates the natural logarithm of every array element.
 
 .. ocv:function:: void log(InputArray src, OutputArray dst)
 
-    Calculates the natural logarithm of every array element.
+.. ocv:pyfunction:: cv2.log(src[, dst]) -> dst
+
+.. ocv:cfunction:: void cvLog(const CvArr* src, CvArr* dst)
+.. ocv:pyoldfunction:: cv.Log(src, dst)-> None
 
     :param src: Source array.
 
@@ -1343,10 +1445,14 @@ The maximum relative error is about ``7e-6`` for single-precision input and less
 
 LUT
 ---
+Performs a look-up table transform of an array.
 
 .. ocv:function:: void LUT(InputArray src, InputArray lut, OutputArray dst)
 
-    Performs a look-up table transform of an array.
+.. ocv:pyfunction:: cv2.LUT(src, lut[, dst[, interpolation]]) -> dst
+
+.. ocv:cfunction:: void cvLUT(const CvArr* src, CvArr* dst, const CvArr* lut)
+.. ocv:pyoldfunction:: cv.LUT(src, dst, lut)-> None
 
     :param src: Source array of 8-bit elements.
 
@@ -1375,10 +1481,11 @@ where
 
 magnitude
 ---------
+Calculates the magnitude of 2D vectors.
 
 .. ocv:function:: void magnitude(InputArray x, InputArray y, OutputArray magnitude)
 
-    Calculates the magnitude of 2D vectors.
+.. ocv:pyfunction:: cv2.magnitude(x, y[, magnitude]) -> magnitude
 
     :param x: Floating-point array of x-coordinates of the vectors.
 
@@ -1403,10 +1510,15 @@ The function ``magnitude`` calculates the magnitude of 2D vectors formed from th
 
 Mahalanobis
 -----------
+Calculates the Mahalanobis distance between two vectors.
 
 .. ocv:function:: double Mahalanobis(InputArray vec1, InputArray vec2, InputArray icovar)
 
-    Calculates the Mahalanobis distance between two vectors.
+.. ocv:pyfunction:: cv2.Mahalanobis(v1, v2, icovar) -> retval
+
+.. ocv:cfunction:: double cvMahalanobis( const CvArr* vec1, const CvArr* vec2, CvArr* icovar)
+
+.. ocv:pyoldfunction:: cv.Mahalanobis(vec1, vec2, icovar)-> None
 
     :param vec1: First 1D source vector.
 
@@ -1414,7 +1526,7 @@ Mahalanobis
 
     :param icovar: Inverse covariance matrix.
 
-The function ``Mahalonobis`` calculates and returns the weighted distance between two vectors:
+The function ``Mahalanobis`` calculates and returns the weighted distance between two vectors:
 
 .. math::
 
@@ -1428,6 +1540,7 @@ The covariance matrix may be calculated using the
 
 max
 ---
+Calculates per-element maximum of two arrays or an array and a scalar.
 
 .. ocv:function:: MatExpr max(const Mat& src1, const Mat& src2)
 
@@ -1441,7 +1554,12 @@ max
 
 .. ocv:function:: void max(const Mat& src1, double value, Mat& dst)
 
-    Calculates per-element maximum of two arrays or an array and a scalar.
+.. ocv:pyfunction:: cv2.max(src1, src2[, dst]) -> dst
+
+.. ocv:cfunction:: void cvMax(const CvArr* src1, const CvArr* src2, CvArr* dst)
+.. ocv:cfunction:: void cvMaxS(const CvArr* src, double value, CvArr* dst)
+.. ocv:pyoldfunction:: cv.Max(src1, src2, dst)-> None
+.. ocv:pyoldfunction:: cv.MaxS(src, value, dst)-> None
 
     :param src1: First source array.
 
@@ -1479,12 +1597,16 @@ The first 3 variants of the function listed above are actually a part of
 
 mean
 ----
+Calculates an average (mean) of array elements.
+
+.. ocv:function:: Scalar mean(InputArray src, InputArray mask=noArray())
 
-.. ocv:function:: Scalar mean(InputArray mtx, InputArray mask=noArray())
+.. ocv:pyfunction:: cv2.mean(src[, mask]) -> retval
 
-    Calculates an average (mean) of array elements.
+.. ocv:cfunction:: CvScalar cvAvg(const CvArr* src, const CvArr* mask=NULL)
+.. ocv:pyoldfunction:: cv.Avg(src, mask=None)-> CvScalar
 
-    :param mtx: Source array that should have from 1 to 4 channels so that the result can be stored in  :ocv:func:`Scalar` .
+    :param src: Source array that should have from 1 to 4 channels so that the result can be stored in  :ocv:func:`Scalar` .
 
     :param mask: Optional operation mask.
 
@@ -1507,12 +1629,16 @@ When all the mask elements are 0's, the functions return ``Scalar::all(0)`` .
 
 meanStdDev
 ----------
+Calculates a mean and standard deviation of array elements.
 
-.. ocv:function:: void meanStdDev(InputArray mtx, OutputArray mean, OutputArray stddev, InputArray mask=noArray())
+.. ocv:function:: void meanStdDev(InputArray src, OutputArray mean, OutputArray stddev, InputArray mask=noArray())
 
-    Calculates a mean and standard deviation of array elements.
+.. ocv:pyfunction:: cv2.meanStdDev(src[, mean[, stddev[, mask]]]) -> mean, stddev
 
-    :param mtx: Source array that should have from 1 to 4 channels so that the results can be stored in  :ocv:func:`Scalar` 's.
+.. ocv:cfunction:: void cvAvgSdv(const CvArr* src, CvScalar* mean, CvScalar* stdDev, const CvArr* mask=NULL)
+.. ocv:pyoldfunction:: cv.AvgSdv(src, mask=None)-> (mean, stdDev)
+
+    :param src: Source array that should have from 1 to 4 channels so that the results can be stored in  :ocv:func:`Scalar` 's.
 
     :param mean: Output parameter: computed mean value.
 
@@ -1542,12 +1668,16 @@ When all the mask elements are 0's, the functions return ``mean=stddev=Scalar::a
 
 merge
 -----
+Composes a multi-channel array from several single-channel arrays.
 
 .. ocv:function:: void merge(const Mat* mv, size_t count, OutputArray dst)
 
 .. ocv:function:: void merge(const vector<Mat>& mv, OutputArray dst)
 
-    Composes a multi-channel array from several single-channel arrays.
+.. ocv:pyfunction:: cv2.merge(mv[, dst]) -> dst
+
+.. ocv:cfunction:: void cvMerge(const CvArr* src0, const CvArr* src1, const CvArr* src2, const CvArr* src3, CvArr* dst)
+.. ocv:pyoldfunction:: cv.Merge(src0, src1, src2, src3, dst)-> None
 
     :param mv: Source array or vector of matrices to be merged. All the matrices in ``mv``  must have the same size and the same depth.
 
@@ -1565,12 +1695,13 @@ The function
 
     :ocv:func:`mixChannels`,
     :ocv:func:`split`,
-    :ocv:func:`reshape`
+    :ocv:func:`Mat::reshape`
 
 
 
 min
 ---
+Calculates per-element minimum of two arrays or array and a scalar.
 
 .. ocv:function:: MatExpr min(const Mat& src1, const Mat& src2)
 
@@ -1584,7 +1715,12 @@ min
 
 .. ocv:function:: void min(const Mat& src1, double value, Mat& dst)
 
-    Calculates per-element minimum of two arrays or array and a scalar.
+.. ocv:pyfunction:: cv2.min(src1, src2[, dst]) -> dst
+
+.. ocv:cfunction:: void cvMin(const CvArr* src1, const CvArr* src2, CvArr* dst)
+.. ocv:cfunction:: void cvMinS(const CvArr* src, double value, CvArr* dst)
+.. ocv:pyoldfunction:: cv.Min(src1, src2, dst)-> None
+.. ocv:pyoldfunction:: cv.MinS(src, value, dst)-> None
 
     :param src1: First source array.
 
@@ -1623,12 +1759,16 @@ The first three variants of the function listed above are actually a part of
 
 minMaxLoc
 ---------
+Finds the global minimum and maximum in a whole array or sub-array.
 
 .. ocv:function:: void minMaxLoc(InputArray src, double* minVal, double* maxVal=0, Point* minLoc=0, Point* maxLoc=0, InputArray mask=noArray())
 
 .. ocv:function:: void minMaxLoc(const SparseMat& src, double* minVal, double* maxVal, int* minIdx=0, int* maxIdx=0)
 
-    Finds the global minimum and maximum in a whole array or sub-array.
+.. ocv:pyfunction:: cv2.minMaxLoc(src[, mask]) -> minVal, maxVal, minLoc, maxLoc
+
+.. ocv:cfunction:: void cvMinMaxLoc(const CvArr* arr, double* minVal, double* maxVal, CvPoint* minLoc=NULL, CvPoint* maxLoc=NULL, const CvArr* mask=NULL)
+.. ocv:pyoldfunction:: cv.MinMaxLoc(arr, mask=None)-> (minVal, maxVal, minLoc, maxLoc)
 
     :param src: Source single-channel array.
 
@@ -1672,12 +1812,16 @@ In case of a sparse matrix, the minimum is found among non-zero elements only.
 
 mixChannels
 -----------
+Copies specified channels from input arrays to the specified channels of output arrays.
 
 .. ocv:function:: void mixChannels(const Mat* srcv, int nsrc, Mat* dstv, int ndst, const int* fromTo, size_t npairs)
 
 .. ocv:function:: void mixChannels(const vector<Mat>& srcv, vector<Mat>& dstv, const int* fromTo, int npairs)
 
-    Copies specified channels from input arrays to the specified channels of output arrays.
+.. ocv:pyfunction:: cv2.mixChannels(src, dst, fromTo) -> None
+
+.. ocv:cfunction:: void cvMixChannels(const CvArr** src, int srcCount, CvArr** dst, int dstCount, const int* fromTo, int pairCount)
+.. ocv:pyoldfunction:: cv.MixChannels(src, dst, fromTo) -> None
 
     :param srcv: Input array or vector of matrices. All the matrices must have the same size and the same depth.
 
@@ -1722,10 +1866,14 @@ In the example below, the code splits a 4-channel RGBA image into a 3-channel BG
 
 mulSpectrums
 ------------
+Performs the per-element multiplication of two Fourier spectrums.
 
 .. ocv:function:: void mulSpectrums(InputArray src1, InputArray src2, OutputArray dst, int flags, bool conj=false)
 
-    Performs the per-element multiplication of two Fourier spectrums.
+.. ocv:pyfunction:: cv2.mulSpectrums(a, b, flags[, c[, conjB]]) -> c
+
+.. ocv:cfunction:: void cvMulSpectrums( const CvArr* src1, const CvArr* src2, CvArr* dst, int flags)
+.. ocv:pyoldfunction:: cv.MulSpectrums(src1, src2, dst, flags)-> None
 
     :param src1: First source array.
 
@@ -1748,10 +1896,14 @@ The function, together with
 
 multiply
 --------
+Calculates the per-element scaled product of two arrays.
 
 .. ocv:function:: void multiply(InputArray src1, InputArray src2, OutputArray dst, double scale=1)
 
-    Calculates the per-element scaled product of two arrays.
+.. ocv:pyfunction:: cv2.multiply(src1, src2[, dst[, scale[, dtype]]]) -> dst
+
+.. ocv:cfunction:: void cvMul(const CvArr* src1, const CvArr* src2, CvArr* dst, double scale=1)
+.. ocv:pyoldfunction:: cv.Mul(src1, src2, dst, scale)-> None
 
     :param src1: First source array.
 
@@ -1791,10 +1943,14 @@ For a not-per-element matrix product, see
 
 mulTransposed
 -------------
+Calculates the product of a matrix and its transposition.
 
 .. ocv:function:: void mulTransposed(InputArray src, OutputArray dst, bool aTa, InputArray delta=noArray(), double scale=1, int rtype=-1)
 
-    Calculates the product of a matrix and its transposition.
+.. ocv:pyfunction:: cv2.mulTransposed(src, aTa[, dst[, delta[, scale[, dtype]]]]) -> dst
+
+.. ocv:cfunction:: void cvMulTransposed(const CvArr* src, CvArr* dst, int order, const CvArr* delta=NULL, double scale=1.0)
+.. ocv:pyoldfunction:: cv.MulTransposed(src, dst, order, delta=None, scale)-> None
 
     :param src: Source single-channel matrix. Note that unlike :ocv:func:`gemm`, the function can multiply not only floating-point matrices.
 
@@ -1833,6 +1989,7 @@ otherwise. The function is used to compute the covariance matrix. With zero delt
 
 norm
 ----
+Calculates an absolute array norm, an absolute difference norm, or a relative difference norm.
 
 .. ocv:function:: double norm(InputArray src1, int normType=NORM_L2, InputArray mask=noArray())
 
@@ -1840,7 +1997,11 @@ norm
 
 .. ocv:function:: double norm( const SparseMat& src, int normType )
 
-    Calculates an absolute array norm, an absolute difference norm, or a relative difference norm.
+.. ocv:pyfunction:: cv2.norm(src1[, normType[, mask]]) -> retval
+.. ocv:pyfunction:: cv2.norm(src1, src2[, normType[, mask]]) -> retval
+
+.. ocv:cfunction:: double cvNorm(const CvArr* arr1, const CvArr* arr2=NULL, int normType=CV_L2, const CvArr* mask=NULL)
+.. ocv:pyoldfunction:: cv.Norm(arr1, arr2, normType=CV_L2, mask=None)-> double
 
     :param src1: First source array.
 
@@ -1884,12 +2045,13 @@ A multi-channel source arrays are treated as a single-channel, that is, the resu
 
 normalize
 ---------
+Normalizes the norm or value range of an array.
 
 .. ocv:function:: void normalize(const InputArray src, OutputArray dst, double alpha=1, double beta=0, int normType=NORM_L2, int rtype=-1, InputArray mask=noArray())
 
 .. ocv:function:: void normalize(const SparseMat& src, SparseMat& dst, double alpha, int normType)
 
-    Normalizes the norm or value range of an array.
+.. ocv:pyfunction:: cv2.normalize(src[, dst[, alpha[, beta[, norm_type[, dtype[, mask]]]]]]) -> dst
 
     :param src: Source array.
 
@@ -1991,12 +2153,12 @@ The sample below is the function that takes two matrices. The first function sto
 
 PCA::PCA
 ------------
+PCA constructors
+
 .. ocv:function:: PCA::PCA()
 
 .. ocv:function:: PCA::PCA(InputArray data, InputArray mean, int flags, int maxComponents=0)
 
-    PCA constructors
-
     :param data: Input samples stored as matrix rows or matrix columns.
 
     :param mean: Optional mean value. If the matrix is empty ( ``Mat()`` ), the mean is computed from the data.
@@ -2016,10 +2178,11 @@ The default constructor initializes an empty PCA structure. The second construct
 
 PCA::operator ()
 ----------------
+Performs Principal Component Analysis of the supplied dataset.
 
 .. ocv:function:: PCA& PCA::operator()(InputArray data, InputArray mean, int flags, int maxComponents=0)
 
-    Performs Principal Component Analysis of the supplied dataset.
+.. ocv:pyfunction:: cv2.PCACompute(data[, mean[, eigenvectors[, maxComponents]]]) -> mean, eigenvectors
 
     :param data: Input samples stored as the matrix rows or as the matrix columns.
 
@@ -2041,12 +2204,13 @@ The computed eigenvalues are sorted from the largest to the smallest and the cor
 
 PCA::project
 ------------
+Projects vector(s) to the principal component subspace.
 
 .. ocv:function:: Mat PCA::project(InputArray vec) const
 
 .. ocv:function:: void PCA::project(InputArray vec, OutputArray result) const
 
-    Projects vector(s) to the principal component subspace.
+.. ocv:pyfunction:: cv2.PCAProject(vec, mean, eigenvectors[, result]) -> result
 
     :param vec: Input vector(s). They must have the same dimensionality and the same layout as the input data used at PCA phase. That is, if  ``CV_PCA_DATA_AS_ROWS``  are specified, then  ``vec.cols==data.cols``  (vector dimensionality) and  ``vec.rows``  is the number of vectors to project. The same is true for the  ``CV_PCA_DATA_AS_COLS``  case.
 
@@ -2058,12 +2222,13 @@ The methods project one or more vectors to the principal component subspace, whe
 
 PCA::backProject
 ----------------
+Reconstructs vectors from their PC projections.
 
 .. ocv:function:: Mat PCA::backProject(InputArray vec) const
 
 .. ocv:function:: void PCA::backProject(InputArray vec, OutputArray result) const
 
-    Reconstructs vectors from their PC projections.
+.. ocv:pyfunction:: cv2.PCABackProject(vec, mean, eigenvectors[, result]) -> result
 
     :param vec: Coordinates of the vectors in the principal component subspace. The layout and size are the same as of  ``PCA::project``  output vectors.
 
@@ -2076,9 +2241,14 @@ The methods are inverse operations to
 
 perspectiveTransform
 --------------------
+Performs the perspective matrix transformation of vectors.
+
 .. ocv:function:: void perspectiveTransform(InputArray src, OutputArray dst, InputArray mtx)
 
-    Performs the perspective matrix transformation of vectors.
+.. ocv:pyfunction:: cv2.perspectiveTransform(src, m[, dst]) -> dst
+
+.. ocv:cfunction:: void cvPerspectiveTransform(const CvArr* src, CvArr* dst, const CvMat* mat)
+.. ocv:pyoldfunction:: cv.PerspectiveTransform(src, dst, mat)-> None
 
     :param src: Source two-channel or three-channel floating-point array. Each element is a 2D/3D vector to be transformed.
 
@@ -2119,10 +2289,11 @@ Here a 3D vector transformation is shown. In case of a 2D vector transformation,
 
 phase
 -----
+Calculates the rotation angle of 2D vectors.
 
 .. ocv:function:: void phase(InputArray x, InputArray y, OutputArray angle, bool angleInDegrees=false)
 
-    Calculates the rotation angle of 2D vectors.
+.. ocv:pyfunction:: cv2.phase(x, y[, angle[, angleInDegrees]]) -> angle
 
     :param x: Source floating-point array of x-coordinates of 2D vectors.
 
@@ -2143,10 +2314,14 @@ The angle estimation accuracy is about 0.3 degrees. When ``x(I)=y(I)=0`` , the c
 
 polarToCart
 -----------
+Computes x and y coordinates of 2D vectors from their magnitude and angle.
 
 .. ocv:function:: void polarToCart(InputArray magnitude, InputArray angle, OutputArray x, OutputArray y, bool angleInDegrees=false)
 
-    Computes x and y coordinates of 2D vectors from their magnitude and angle.
+.. ocv:pyfunction:: cv2.polarToCart(magnitude, angle[, x[, y[, angleInDegrees]]]) -> x, y
+
+.. ocv:cfunction:: void cvPolarToCart( const CvArr* magnitude, const CvArr* angle, CvArr* x, CvArr* y, int angleInDegrees=0)
+.. ocv:pyoldfunction:: cv.PolarToCart(magnitude, angle, x, y, angleInDegrees=0)-> None
 
     :param magnitude: Source floating-point array of magnitudes of 2D vectors. It can be an empty matrix ( ``=Mat()`` ). In this case, the function assumes that all the magnitudes are =1. If it is not empty, it must have the same size and type as  ``angle`` .
     
@@ -2180,10 +2355,14 @@ The relative accuracy of the estimated coordinates is about ``1e-6``.
 
 pow
 ---
+Raises every array element to a power.
 
 .. ocv:function:: void pow(InputArray src, double p, OutputArray dst)
 
-    Raises every array element to a power.
+.. ocv:pyfunction:: cv2.pow(src, power[, dst]) -> dst
+
+.. ocv:cfunction:: void cvPow( const CvArr* src, CvArr* dst, double power)
+.. ocv:pyoldfunction:: cv.Pow(src, dst, power)-> None
 
     :param src: Source array.
 
@@ -2231,12 +2410,12 @@ http://en.wikipedia.org/wiki/Ziggurat_algorithm
 
 RNG::RNG
 ------------
+The constructors
+
 .. ocv:function:: RNG::RNG()
 
 .. ocv:function:: RNG::RNG(uint64 state)
 
-    Introduces RNG constructors.
-
     :param state: 64-bit value used to initialize the RNG.
 
 These are the RNG constructors. The first form sets the state to some pre-defined value, equal to ``2**32-1`` in the current implementation. The second form sets the state to the specified value. If you passed ``state=0`` , the constructor uses the above default value instead to avoid the singular random number sequence, consisting of all zeros.
@@ -2245,9 +2424,9 @@ These are the RNG constructors. The first form sets the state to some pre-define
 
 RNG::next
 -------------
-.. ocv:function:: unsigned RNG::next()
+Returns the next random number.
 
-    Returns the next random number.
+.. ocv:function:: unsigned RNG::next()
 
 The method updates the state using the MWC algorithm and returns the next 32-bit random number.
 
@@ -2255,6 +2434,7 @@ The method updates the state using the MWC algorithm and returns the next 32-bit
 
 RNG::operator T
 ---------------
+Returns the next random number of the specified type.
 
 .. ocv:function:: RNG::operator uchar()
 
@@ -2272,20 +2452,18 @@ RNG::operator T
 
 .. ocv:function:: RNG::operator double()
 
-    Returns the next random number of the specified type.
-
 Each of the methods updates the state using the MWC algorithm and returns the next random number of the specified type. In case of integer types, the returned number is from the available value range for the specified type. In case of floating-point types, the returned value is from ``[0,1)`` range.
 
 
 
 RNG::operator ()
 --------------------
+Returns the next random number.
+
 .. ocv:function:: unsigned RNG::operator ()()
 
 .. ocv:function:: unsigned RNG::operator ()(unsigned N)
 
-    Returns the next random number.
-
     :param N: Upper non-inclusive boundary of the returned random number.
 
 The methods transform the state using the MWC algorithm and return the next random number. The first form is equivalent to
@@ -2295,14 +2473,14 @@ The methods transform the state using the MWC algorithm and return the next rand
 
 RNG::uniform
 ----------------
+Returns the next random number sampled from the uniform distribution.
+
 .. ocv:function:: int RNG::uniform(int a, int b)
 
 .. ocv:function:: float RNG::uniform(float a, float b)
 
 .. ocv:function:: double RNG::uniform(double a, double b)
 
-    Returns the next random number sampled from the uniform distribution.
-
     :param a: Lower inclusive boundary of the returned random numbers.
 
     :param b: Upper non-inclusive boundary of the returned random numbers.
@@ -2334,9 +2512,9 @@ The compiler does not take into account the type of the variable to which you as
 
 RNG::gaussian
 -----------------
-.. ocv:function:: double RNG::gaussian(double sigma)
+Returns the next random number sampled from the Gaussian distribution.
 
-    Returns the next random number sampled from the Gaussian distribution.
+.. ocv:function:: double RNG::gaussian(double sigma)
 
     :param sigma: Standard deviation of the distribution.
 
@@ -2346,9 +2524,9 @@ The method transforms the state using the MWC algorithm and returns the next ran
 
 RNG::fill
 -------------
-.. ocv:function:: void RNG::fill( InputOutputArray mat, int distType, InputArray a, InputArray b )
+Fills arrays with random numbers.
 
-    Fills arrays with random numbers.
+.. ocv:function:: void RNG::fill( InputOutputArray mat, int distType, InputArray a, InputArray b )
 
     :param mat: 2D or N-dimensional matrix. Currently matrices with more than 4 channels are not supported by the methods. Use  :ocv:func:`reshape`  as a possible workaround.
 
@@ -2362,12 +2540,13 @@ Each of the methods fills the matrix with the random values from the specified d
 
 randu
 -----
+Generates a single uniformly-distributed random number or an array of random numbers.
 
 .. ocv:function:: template<typename _Tp> _Tp randu()
 
 .. ocv:function:: void randu(InputOutputArray mtx, InputArray low, InputArray high)
 
-    Generates a single uniformly-distributed random number or an array of random numbers.
+.. ocv:pyfunction:: cv2.randu(dst, low, high) -> None
 
     :param mtx: Output array of random numbers. The array must be pre-allocated.
 
@@ -2394,10 +2573,11 @@ The second non-template variant of the function fills the matrix ``mtx`` with un
 
 randn
 -----
+Fills the array with normally distributed random numbers.
 
 .. ocv:function:: void randn(InputOutputArray mtx, InputArray mean, InputArray stddev)
 
-    Fills the array with normally distributed random numbers.
+.. ocv:pyfunction:: cv2.randn(dst, mean, stddev) -> None
 
     :param mtx: Output array of random numbers. The array must be pre-allocated and have 1 to 4 channels.
 
@@ -2416,10 +2596,11 @@ The function ``randn`` fills the matrix ``mtx`` with normally distributed random
 
 randShuffle
 -----------
+Shuffles the array elements randomly.
 
 .. ocv:function:: void randShuffle(InputOutputArray mtx, double iterFactor=1., RNG* rng=0)
 
-    Shuffles the array elements randomly.
+.. ocv:pyfunction:: cv2.randShuffle(src[, dst[, iterFactor]]) -> dst
 
     :param mtx: Input/output numerical 1D array.
 
@@ -2438,10 +2619,14 @@ The function ``randShuffle`` shuffles the specified 1D array by randomly choosin
 
 reduce
 ------
+Reduces a matrix to a vector.
 
 .. ocv:function:: void reduce(InputArray mtx, OutputArray vec, int dim, int reduceOp, int dtype=-1)
 
-    Reduces a matrix to a vector.
+.. ocv:pyfunction:: cv2.reduce(src, dim, rtype[, dst[, dtype]]) -> dst
+
+.. ocv:cfunction:: void cvReduce(const CvArr* src, CvArr* dst, int dim=-1, int op=CV_REDUCE_SUM)
+.. ocv:pyoldfunction:: cv.Reduce(src, dst, dim=-1, op=CV_REDUCE_SUM)-> None
 
     :param mtx: Source 2D matrix.
 
@@ -2469,12 +2654,16 @@ The function ``reduce`` reduces the matrix to a vector by treating the matrix ro
 
 repeat
 ------
+Fills the destination array with repeated copies of the source array.
 
 .. ocv:function:: void repeat(InputArray src, int ny, int nx, OutputArray dst)
 
 .. ocv:function:: Mat repeat(InputArray src, int ny, int nx)
 
-    Fills the destination array with repeated copies of the source array.
+.. ocv:pyfunction:: cv2.repeat(src, ny, nx[, dst]) -> dst
+
+.. ocv:cfunction:: void cvRepeat(const CvArr* src, CvArr* dst)
+.. ocv:pyoldfunction:: cv.Repeat(src, dst)-> None
 
     :param src: Source array to replicate.
 
@@ -2489,7 +2678,7 @@ The functions
 
 .. math::
 
-    \texttt{dst} _{ij}= \texttt{src} _{i \mod \texttt{src.rows} , \; j \mod \texttt{src.cols} }
+    \texttt{dst} _{ij}= \texttt{src} _{i\mod src.rows, \; j\mod src.cols }
 
 The second variant of the function is more convenient to use with
 :ref:`MatrixExpressions` . 
@@ -2501,42 +2690,16 @@ The second variant of the function is more convenient to use with
 
 
 
-saturate_cast
--------------
-
-.. ocv:function:: template<...> _Tp saturate_cast(_Tp2 v)
-
-    Template function for accurate conversion from one primitive type to another.
-
-    :param v: Function parameter.
-
-The functions ``saturate_cast`` resemble the standard C++ cast operations, such as ``static_cast<T>()`` and others. They perform an efficient and accurate conversion from one primitive type to another (see the introduction chapter). ``saturate`` in the name means that when the input value ``v`` is out of the range of the target type, the result is not formed just by taking low bits of the input, but instead the value is clipped. For example: ::
-
-    uchar a = saturate_cast<uchar>(-100); // a = 0 (UCHAR_MIN)
-    short b = saturate_cast<short>(33333.33333); // b = 32767 (SHRT_MAX)
-
-Such clipping is done when the target type is ``unsigned char`` , ``signed char`` , ``unsigned short`` or ``signed short`` . For 32-bit integers, no clipping is done.
-
-When the parameter is a floating-point value and the target type is an integer (8-, 16- or 32-bit), the floating-point value is first rounded to the nearest integer and then clipped if needed (when the target type is 8- or 16-bit).
-
-This operation is used in the simplest or most complex image processing functions in OpenCV.
-
-.. seealso::
-
-    :ocv:func:`add`,
-    :ocv:func:`subtract`,
-    :ocv:func:`multiply`,
-    :ocv:func:`divide`,
-    :ocv:func:`Mat::convertTo`
-
-
-
 scaleAdd
 --------
+Calculates the sum of a scaled array and another array.
 
 .. ocv:function:: void scaleAdd(InputArray src1, double scale, InputArray src2, OutputArray dst)
 
-    Calculates the sum of a scaled array and another array.
+.. ocv:pyfunction:: cv2.scaleAdd(src1, alpha, src2[, dst]) -> dst
+
+.. ocv:cfunction:: void cvScaleAdd(const CvArr* src1, CvScalar scale, const CvArr* src2, CvArr* dst)
+.. ocv:pyoldfunction:: cv.ScaleAdd(src1, scale, src2, dst)-> None
 
     :param src1: First source array.
 
@@ -2572,10 +2735,14 @@ The function can also be emulated with a matrix expression, for example: ::
 
 setIdentity
 -----------
+Initializes a scaled identity matrix.
 
 .. ocv:function:: void setIdentity(InputOutputArray dst, const Scalar& value=Scalar(1))
 
-    Initializes a scaled identity matrix.
+.. ocv:pyfunction:: cv2.setIdentity(mtx[, s]) -> None
+
+.. ocv:cfunction:: void cvSetIdentity(CvArr* mat, CvScalar value=cvRealScalar(1))
+.. ocv:pyoldfunction:: cv.SetIdentity(mat, value=1)-> None
 
     :param dst: Matrix to initialize (not necessarily square).
 
@@ -2606,10 +2773,14 @@ The function can also be emulated using the matrix initializers and the matrix e
 
 solve
 -----
+Solves one or more linear systems or least-squares problems.
 
 .. ocv:function:: bool solve(InputArray src1, InputArray src2, OutputArray dst, int flags=DECOMP_LU)
 
-    Solves one or more linear systems or least-squares problems.
+.. ocv:pyfunction:: cv2.solve(src1, src2[, dst[, flags]]) -> retval, dst
+
+.. ocv:cfunction:: int cvSolve(const CvArr* src1, const CvArr* src2, CvArr* dst, int method=CV_LU)
+.. ocv:pyoldfunction:: cv.Solve(A, B, X, method=CV_LU)-> None
 
     :param src1: Input matrix on the left-hand side of the system.
 
@@ -2652,9 +2823,14 @@ If ``DECOMP_LU`` or ``DECOMP_CHOLESKY`` method is used, the function returns 1 i
 
 solveCubic
 --------------
+Finds the real roots of a cubic equation.
+
 .. ocv:function:: void solveCubic(InputArray coeffs, OutputArray roots)
 
-    Finds the real roots of a cubic equation.
+.. ocv:pyfunction:: cv2.solveCubic(coeffs[, roots]) -> retval, roots
+
+.. ocv:cfunction:: void cvSolveCubic(const CvArr* coeffs, CvArr* roots)
+.. ocv:pyoldfunction:: cv.SolveCubic(coeffs, roots)-> None
 
     :param coeffs: Equation coefficients, an array of 3 or 4 elements.
 
@@ -2680,10 +2856,11 @@ The roots are stored in the ``roots`` array.
 
 solvePoly
 ---------
+Finds the real or complex roots of a polynomial equation.
 
 .. ocv:function:: void solvePoly(InputArray coeffs, OutputArray roots, int maxIters=300)
 
-    Finds the real or complex roots of a polynomial equation.
+.. ocv:pyfunction:: cv2.solvePoly(coeffs[, roots[, maxIters]]) -> retval, roots
 
     :param coeffs: Array of polynomial coefficients.
 
@@ -2701,10 +2878,11 @@ The function ``solvePoly`` finds real and complex roots of a polynomial equation
 
 sort
 ----
+Sorts each row or each column of a matrix.
 
 .. ocv:function:: void sort(InputArray src, OutputArray dst, int flags)
 
-    Sorts each row or each column of a matrix.
+.. ocv:pyfunction:: cv2.sort(src, flags[, dst]) -> dst
 
     :param src: Source single-channel array.
 
@@ -2731,10 +2909,11 @@ The function ``sort`` sorts each matrix row or each matrix column in ascending o
 
 sortIdx
 -------
+Sorts each row or each column of a matrix.
 
 .. ocv:function:: void sortIdx(InputArray src, OutputArray dst, int flags)
 
-    Sorts each row or each column of a matrix.
+.. ocv:pyfunction:: cv2.sortIdx(src, flags[, dst]) -> dst
 
     :param src: Source single-channel array.
 
@@ -2768,12 +2947,16 @@ The function ``sortIdx`` sorts each matrix row or each matrix column in the asce
 
 split
 -----
+Divides a multi-channel array into several single-channel arrays.
 
 .. ocv:function:: void split(const Mat& mtx, Mat* mv)
 
 .. ocv:function:: void split(const Mat& mtx, vector<Mat>& mv)
 
-    Divides a multi-channel array into several single-channel arrays.
+.. ocv:pyfunction:: cv2.split(m, mv) -> None
+
+.. ocv:cfunction:: void cvSplit(const CvArr* src, CvArr* dst0, CvArr* dst1, CvArr* dst2, CvArr* dst3)
+.. ocv:pyoldfunction:: cv.Split(src, dst0, dst1, dst2, dst3)-> None
 
     :param mtx: Source multi-channel array.
 
@@ -2798,10 +2981,14 @@ If you need to extract a single channel or do some other sophisticated channel p
 
 sqrt
 ----
+Calculates a quare root of array elements.
 
 .. ocv:function:: void sqrt(InputArray src, OutputArray dst)
 
-    Calculates a quare root of array elements.
+.. ocv:pyfunction:: cv2.sqrt(src[, dst]) -> dst
+
+.. ocv:cfunction:: float cvSqrt(float value)
+.. ocv:pyoldfunction:: cv.Sqrt(value)-> float
 
     :param src: Source floating-point array.
 
@@ -2818,10 +3005,19 @@ The functions ``sqrt`` calculate a square root of each source array element. In
 
 subtract
 --------
+Calculates the per-element difference between two arrays or array and a scalar.
 
 .. ocv:function:: void subtract(InputArray src1, InputArray src2, OutputArray dst, InputArray mask=noArray(), int dtype=-1)
 
-    Calculates the per-element difference between two arrays or array and a scalar.
+.. ocv:pyfunction:: cv2.subtract(src1, src2[, dst[, mask[, dtype]]]) -> dst
+
+.. ocv:cfunction:: void cvSub(const CvArr* src1, const CvArr* src2, CvArr* dst, const CvArr* mask=NULL)
+.. ocv:cfunction:: void cvSubRS(const CvArr* src1, CvScalar src2, CvArr* dst, const CvArr* mask=NULL)
+.. ocv:cfunction:: void cvSubS(const CvArr* src1, CvScalar src2, CvArr* dst, const CvArr* mask=NULL)
+
+.. ocv:pyoldfunction:: cv.Sub(src1, src2, dst, mask=None)-> None
+.. ocv:pyoldfunction:: cv.SubRS(src1, src2, dst, mask=None)-> None
+.. ocv:pyoldfunction:: cv.SubS(src1, src2, dst, mask=None)-> None
 
     :param src1: First source array or a scalar.
 
@@ -2855,6 +3051,13 @@ The function ``subtract`` computes:
     .. math::
 
         \texttt{dst}(I) =  \texttt{saturate} ( \texttt{src1} -  \texttt{src2}(I) ) \quad \texttt{if mask}(I) \ne0
+        
+ *
+    The reverse difference between a scalar and an array in the case of ``SubRS``:
+    
+    .. math::
+
+        \texttt{dst}(I) =  \texttt{saturate} ( \texttt{src2} -  \texttt{src1}(I) ) \quad \texttt{if mask}(I) \ne0
 
 where ``I`` is a multi-dimensional index of array elements. In case of multi-channel arrays, each channel is processed independently.
 
@@ -2870,7 +3073,7 @@ The input arrays and the destination array can all have the same or different de
     :ocv:func:`add`,
     :ocv:func:`addWeighted`,
     :ocv:func:`scaleAdd`,
-    :ocv:func:`convertScale`,
+    :ocv:func:`Mat::convertTo`,
     :ref:`MatrixExpressions`
 
 
@@ -2894,14 +3097,13 @@ For a faster operation, you can pass ``flags=SVD::MODIFY_A|...`` to modify the d
 
 SVD::SVD
 --------
+The constructors.
 
 .. ocv:function:: SVD::SVD()
 
 .. ocv:function:: SVD::SVD( InputArray A, int flags=0 )
 
-    Introduces SVD constructors.
-
-    :param A: Decomposed matrix.
+    :param src: Decomposed matrix.
 
     :param flags: Operation flags.
 
@@ -2915,15 +3117,13 @@ The first constructor initializes an empty ``SVD`` structure. The second constru
 :ocv:func:`SVD::operator ()` .
 
 
-
 SVD::operator ()
 ----------------
+Performs SVD of a matrix.
 
-.. ocv:function:: SVD& SVD::operator ()( InputArray A, int flags=0 )
-
-    Performs SVD of a matrix.
+.. ocv:function:: SVD& SVD::operator()( InputArray src, int flags=0 )
 
-    :param A: Decomposed matrix.
+    :param src: Decomposed matrix.
 
     :param flags: Operation flags.
 
@@ -2937,37 +3137,81 @@ The operator performs the singular value decomposition of the supplied matrix. T
 :ocv:func:`Mat::create` .
 
 
+SVD::compute
+------------
+Performs SVD of a matrix
+
+.. ocv:function:: static void SVD::compute( InputArray src, OutputArray w, OutputArray u, OutputArray vt, int flags=0 )
+
+.. ocv:function:: static void SVD::compute( InputArray src, OutputArray w, int flags=0 )
+
+.. ocv:pyfunction:: cv2.SVDecomp(src[, w[, u[, vt[, flags]]]]) -> w, u, vt
+
+.. ocv:cfunction:: void cvSVD( CvArr* src, CvArr* w, CvArr* u=NULL, CvArr* v=NULL, int flags=0)
+
+.. ocv:pyoldfunction:: cv.SVD(src, w, u=None, v=None, flags=0)-> None
+
+    :param src: Decomposed matrix
+    
+    :param w: Computed singular values
+    
+    :param u: Computed left singular vectors
+    
+    :param v: Computed right singular vectors
+    
+    :param vt: Transposed matrix of right singular values
+    
+    :param flags: Opertion flags - see :ocv:func:`SVD::SVD`.
+
+The methods/functions perform SVD of matrix. Unlike ``SVD::SVD`` constructor and ``SVD::operator ()``, they store the results to the user-provided matrices. ::
+
+    Mat A, w, u, vt;
+    SVD::compute(A, w, u, vt);
+    
 
 SVD::solveZ
 -----------
+Solves an under-determined singular linear system.
 
-.. ocv:function:: static void SVD::solveZ( InputArray A, OutputArray x )
+.. ocv:function:: static void SVD::solveZ( InputArray src, OutputArray dst )
 
-    Solves an under-determined singular linear system.
+    :param src: Left-hand-side matrix.
 
-    :param A: Left-hand-side matrix.
-
-    :param x: Found solution.
+    :param dst: Found solution.
 
 The method finds a unit-length solution ``x`` of a singular linear system 
 ``A*x = 0``. Depending on the rank of ``A``, there can be no solutions, a single solution or an infinite number of solutions. In general, the algorithm solves the following problem:
 
 .. math::
 
-    x^* =  \arg \min _{x:  \| x \| =1}  \| A  \cdot x  \|
-
+    dst =  \arg \min _{x:  \| x \| =1}  \| src  \cdot x  \|
 
 
 SVD::backSubst
 --------------
+Performs a singular value back substitution.
+
+.. ocv:function:: void SVD::backSubst( InputArray rhs, OutputArray dst ) const
+
+.. ocv:function:: static void SVD::backSubst( InputArray w, InputArray u, InputArray vt, InputArray rhs, OutputArray dst )
+
+.. ocv:pyfunction:: cv2.SVBackSubst(w, u, vt, rhs[, dst]) -> dst
 
-.. ocv:function:: void SVD::backSubst( InputArray rhs, OutputArray x ) const
+.. ocv:cfunction:: void cvSVBkSb( const CvArr* w, const CvArr* u, const CvArr* v, const CvArr* rhs, CvArr* dst, int flags)
 
-    Performs a singular value back substitution.
+.. ocv:pyoldfunction:: cv.SVBkSb(w, u, v, rhs, dst, flags)-> None
 
-    :param rhs: Right-hand side of a linear system  ``A*x = rhs`` to be solved, where ``A`` has been previously decomposed using :ocv:func:`SVD::SVD`  or  :ocv:func:`SVD::operator ()` .
+    :param w: Singular values
     
-    :param x: Found solution of the system.
+    :param u: Left singular vectors
+    
+    :param v: Right singular vectors
+    
+    :param vt: Transposed matrix of right singular vectors.
+
+    :param rhs: Right-hand side of a linear system ``(u*w*v')*dst = rhs`` to be solved, where ``A`` has been previously decomposed.
+    
+    :param dst: Found solution of the system.
 
 The method computes a back substitution for the specified right-hand side:
 
@@ -2977,18 +3221,22 @@ The method computes a back substitution for the specified right-hand side:
 
 Using this technique you can either get a very accurate solution of the convenient linear system, or the best (in the least-squares terms) pseudo-solution of an overdetermined linear system. 
 
-.. note:: Explicit SVD with the further back substitution only makes sense if you need to solve many linear systems with the same left-hand side (for example, ``A`` ). If all you need is to solve a single system (possibly with multiple ``rhs`` immediately available), simply call :ocv:func:`solve` add pass ``DECOMP_SVD`` there. It does absolutely the same thing.
+.. note:: Explicit SVD with the further back substitution only makes sense if you need to solve many linear systems with the same left-hand side (for example, ``src`` ). If all you need is to solve a single system (possibly with multiple ``rhs`` immediately available), simply call :ocv:func:`solve` add pass ``DECOMP_SVD`` there. It does absolutely the same thing.
 
 
 
 sum
 ---
+Calculates the sum of array elements.
+
+.. ocv:function:: Scalar sum(InputArray arr)
 
-.. ocv:function:: Scalar sum(InputArray mtx)
+.. ocv:function:: cv2.sumElems(arr) -> retval
 
-    Calculates the sum of array elements.
+.. ocv:cfunction:: CvScalar cvSum(const CvArr* arr)
+.. ocv:pyoldfunction:: cv.Sum(arr)-> CvScalar
 
-    :param mtx: Source array that must have from 1 to 4 channels.
+    :param arr: Source array that must have from 1 to 4 channels.
 
 The functions ``sum`` calculate and return the sum of array elements, independently for each channel.
 
@@ -3005,11 +3253,10 @@ The functions ``sum`` calculate and return the sum of array elements, independen
 
 theRNG
 ------
+Returns the default random number generator.
 
 .. ocv:function:: RNG& theRNG()
 
-    Returns the default random number generator.
-
 The function ``theRNG`` returns the default random number generator. For each thread, there is a separate random number generator, so you can use the function safely in multi-thread environments. If you just need to get a single random number using this generator or initialize an array, you can use
 :ocv:func:`randu` or
 :ocv:func:`randn` instead. But if you are going to generate many random numbers inside a loop, it is much faster to use this function to retrieve the generator and then use ``RNG::operator _Tp()`` .
@@ -3024,10 +3271,14 @@ The function ``theRNG`` returns the default random number generator. For each th
 
 trace
 -----
+Returns the trace of a matrix.
+
+.. ocv:function:: Scalar trace(InputArray mat)
 
-.. ocv:function:: Scalar trace(InputArray mtx)
+.. ocv:pyfunction:: cv2.trace(mat) -> retval
 
-    Returns the trace of a matrix.
+.. ocv:cfunction:: CvScalar cvTrace(const CvArr* mat)
+.. ocv:pyoldfunction:: cv.Trace(mat)-> CvScalar
 
     :param mtx: Source matrix.
 
@@ -3041,16 +3292,22 @@ The function ``trace`` returns the sum of the diagonal elements of the matrix ``
 
 transform
 ---------
+Performs the matrix transformation of every array element.
 
 .. ocv:function:: void transform(InputArray src, OutputArray dst, InputArray mtx )
 
-    Performs the matrix transformation of every array element.
+.. ocv:pyfunction:: cv2.transform(src, mtx [, dst]) -> dst
+
+.. ocv:cfunction:: void cvTransform(const CvArr* src, CvArr* dst, const CvMat* mtx, const CvMat* shiftvec=NULL)
+.. ocv:pyoldfunction:: cv.Transform(src, dst, mtx, shiftvec=None)-> None
 
     :param src: Source array that must have as many channels (1 to 4) as  ``mtx.cols``  or  ``mtx.cols-1``.
     
     :param dst: Destination array of the same size and depth as  ``src`` . It has as many channels as  ``mtx.rows``  .   
     
-    :param mtx: Transformation matrix.
+    :param mtx: Transformation ``2x2`` or ``2x3`` floating-point matrix.
+    
+    :param shiftvec: Optional translation vector (when ``mtx`` is ``2x2``)
 
 The function ``transform`` performs the matrix transformation of every element of the array ``src`` and stores the results in ``dst`` :
 
@@ -3086,10 +3343,14 @@ points, arbitrary linear color space transformation (such as various kinds of RG
 
 transpose
 ---------
+Transposes a matrix.
 
 .. ocv:function:: void transpose(InputArray src, OutputArray dst)
 
-    Transposes a matrix.
+.. ocv:pyfunction:: cv2.transpose(src[, dst]) -> dst
+
+.. ocv:cfunction:: void cvTranspose(const CvArr* src, CvArr* dst)
+.. ocv:pyoldfunction:: cv.Transpose(src, dst)-> None
 
     :param src: Source array.
 
diff --git a/modules/core/doc/pics/memstorage1.png b/modules/core/doc/pics/memstorage1.png
new file mode 100644 (file)
index 0000000..d4a477c
Binary files /dev/null and b/modules/core/doc/pics/memstorage1.png differ
diff --git a/modules/core/doc/pics/memstorage2.png b/modules/core/doc/pics/memstorage2.png
new file mode 100644 (file)
index 0000000..7af0e95
Binary files /dev/null and b/modules/core/doc/pics/memstorage2.png differ
index 7199b97..6fa86cf 100644 (file)
@@ -3,13 +3,11 @@ Utility and System Functions and Macros
 
 .. highlight:: cpp
 
-.. index:: alignPtr
-
 alignPtr
 ------------
-.. ocv:function:: template<typename _Tp> _Tp* alignPtr(_Tp* ptr, int n=sizeof(_Tp))
+Aligns a pointer to the specified number of bytes.
 
-    Aligns a pointer to the specified number of bytes.
+.. ocv:function:: template<typename _Tp> _Tp* alignPtr(_Tp* ptr, int n=sizeof(_Tp))
 
     :param ptr: Aligned pointer.
 
@@ -21,13 +19,13 @@ The function returns the aligned pointer of the same type as the input pointer:
 
     \texttt{(\_Tp*)(((size\_t)ptr + n-1) \& -n)}
 
-.. index:: alignSize
+
 
 alignSize
 -------------
-.. ocv:function:: size_t alignSize(size_t sz, int n)
+Aligns a buffer size to the specified number of bytes.
 
-    Aligns a buffer size to the specified number of bytes.
+.. ocv:function:: size_t alignSize(size_t sz, int n)
 
     :param sz: Buffer size to align.
 
@@ -39,25 +37,25 @@ The function returns the minimum number that is greater or equal to ``sz`` and i
 
     \texttt{(sz + n-1) \& -n}
 
-.. index:: allocate
+
 
 allocate
 ------------
-.. ocv:function:: template<typename _Tp> _Tp* allocate(size_t n)
+Allocates an array of elements.
 
-    Allocates an array of elements.
+.. ocv:function:: template<typename _Tp> _Tp* allocate(size_t n)
 
     :param n: Number of elements to allocate.
 
 The generic function ``allocate`` allocates a buffer for the specified number of elements. For each element, the default constructor is called.
 
-.. index:: deallocate
+
 
 deallocate
 --------------
-.. ocv:function:: template<typename _Tp> void deallocate(_Tp* ptr, size_t n)
+Deallocates an array of elements.
 
-    Deallocates an array of elements.
+.. ocv:function:: template<typename _Tp> void deallocate(_Tp* ptr, size_t n)
 
     :param ptr: Pointer to the deallocated buffer.
 
@@ -67,34 +65,124 @@ The generic function ``deallocate`` deallocates the buffer allocated with
 :ocv:func:`allocate` . The number of elements must match the number passed to
 :ocv:func:`allocate` .
 
-.. index:: CV_Assert
 
-CV_Assert
+
+fastAtan2
 ---------
-.. ocv:function:: CV_Assert(expr)
+Calculates the angle of a 2D vector in degrees.
 
-    Checks a condition at runtime. ::
+.. ocv:function:: float fastAtan2(float y, float x)
 
-    #define CV_Assert( expr ) ...
-    #define CV_DbgAssert(expr) ...
-..
+.. ocv:pyfunction:: cv2.fastAtan2(y, x) -> retval
 
-   :param expr: Expression to check.
+.. ocv:cfunction:: float cvFastArctan(float y, float x)
+.. ocv:pyoldfunction:: cv.FastArctan(y, x)-> float
 
-The macros ``CV_Assert`` and ``CV_DbgAssert`` evaluate the specified expression. If it is 0, the macros raise an error (see
-:ocv:func:`error` ). The macro ``CV_Assert`` checks the condition in both Debug and Release configurations while ``CV_DbgAssert`` is only retained in the Debug configuration.
+    :param x: x-coordinate of the vector.
 
-.. index:: error
+    :param y: y-coordinate of the vector.
 
-error
+The function ``fastAtan2`` calculates the full-range angle of an input 2D vector. The angle is measured in degrees and varies from 0 to 360 degrees. The accuracy is about 0.3 degrees.
+
+
+cubeRoot
+--------
+Computes the cube root of an argument.
+
+.. ocv:function:: float cubeRoot(float val)
+
+.. ocv:pyfunction:: cv2.cubeRoot(val) -> retval
+
+.. ocv:cfunction:: float cvCbrt(float val)
+
+.. ocv:pyoldfunction:: cv.Cbrt(val)-> float
+
+    :param val: A function argument.
+
+The function ``cubeRoot`` computes :math:`\sqrt[3]{\texttt{val}}`. Negative arguments are handled correctly. NaN and Inf are not handled. The accuracy approaches the maximum possible accuracy for single-precision data.
+
+
+Ceil
+-----
+Rounds floating-point number to the nearest integer not smaller than the original.
+
+.. ocv:cfunction:: int cvCeil(double value)
+.. ocv:pyoldfunction:: cv.Ceil(value) -> int
+
+    :param value: floating-point number. If the value is outside of ``INT_MIN`` ... ``INT_MAX`` range, the result is not defined.
+
+The function computes an integer ``i`` such that:
+
+.. math::
+
+    i-1 < \texttt{value} \le i
+
+
+Floor
+-----
+Rounds floating-point number to the nearest integer not larger than the original.
+
+.. ocv:cfunction:: int cvFloor(double value)
+.. ocv:pyoldfunction:: cv.Floor(value) -> int
+
+    :param value: floating-point number. If the value is outside of ``INT_MIN`` ... ``INT_MAX`` range, the result is not defined.
+
+The function computes an integer ``i`` such that:
+
+.. math::
+
+    i \le \texttt{value} < i+1
+
+
+Round
+-----
+Rounds floating-point number to the nearest integer
+
+.. ocv:cfunction:: int cvRound(double value)
+.. ocv:pyoldfunction:: cv.Round(value) -> int
+
+    :param value: floating-point number. If the value is outside of ``INT_MIN`` ... ``INT_MAX`` range, the result is not defined.
+
+
+IsInf
+-----
+Determines if the argument is Infinity.
+
+.. ocv:cfunction:: int cvIsInf(double value)
+.. ocv:pyoldfunction:: cv.IsInf(value)-> int
+
+        :param value: The input floating-point value 
+
+The function returns 1 if the argument is a plus or minus infinity (as defined by IEEE754 standard) and 0 otherwise.
+
+IsNaN
+-----
+Determines if the argument is Not A Number.
+
+.. ocv:cfunction:: int cvIsNaN(double value)
+.. ocv:pyoldfunction:: cv.IsNaN(value)-> int
+
+        :param value: The input floating-point value 
+
+The function returns 1 if the argument is Not A Number (as defined by IEEE754 standard), 0 otherwise.
+
+
+CV_Assert
 ---------
-.. ocv:function:: void error( const Exception& exc )
+Checks a condition at runtime and throws exception if it fails
+
+.. ocv:function:: CV_Assert(expr)
+
+The macros ``CV_Assert`` (and ``CV_DbgAssert``) evaluate the specified expression. If it is 0, the macros raise an error (see :ocv:func:`error` ). The macro ``CV_Assert`` checks the condition in both Debug and Release configurations while ``CV_DbgAssert`` is only retained in the Debug configuration.
 
-.. ocv:function:: #define CV_Error( code, msg ) <...>
 
-.. ocv:function:: #define CV_Error_( code, args ) <...>
+error
+---------
+Signals an error and raises an exception.
+
+.. ocv:function:: void error( const Exception& exc )
 
-    Signals an error and raises an exception.
+.. ocv:cfunction:: int cvError( int status, const char* funcName, const char* errMsg, const char* filename, int line )
 
     :param exc: Exception to throw.
 
@@ -104,7 +192,12 @@ error
 
     :param args: ``printf`` -like formatted error message in parentheses.
 
-The function and the helper macros ``CV_Error`` and ``CV_Error_`` call the error handler. Currently, the error handler prints the error code ( ``exc.code`` ), the context ( ``exc.file``,``exc.line`` ), and the error message ``exc.err`` to the standard error stream ``stderr`` . In the Debug configuration, it then provokes memory access violation, so that the execution stack and all the parameters can be analyzed by the debugger. In the Release configuration, the exception ``exc`` is thrown.
+The function and the helper macros ``CV_Error`` and ``CV_Error_``: ::
+
+    #define CV_Error( code, msg ) error(...)
+    #define CV_Error_( code, args ) error(...)
+
+call the error handler. Currently, the error handler prints the error code ( ``exc.code`` ), the context ( ``exc.file``,``exc.line`` ), and the error message ``exc.err`` to the standard error stream ``stderr`` . In the Debug configuration, it then provokes memory access violation, so that the execution stack and all the parameters can be analyzed by the debugger. In the Release configuration, the exception ``exc`` is thrown.
 
 The macro ``CV_Error_`` can be used to construct an error message on-fly to include some dynamic information, for example: ::
 
@@ -113,8 +206,6 @@ The macro ``CV_Error_`` can be used to construct an error message on-fly to incl
         ("the matrix element (
         i, j, mtx.at<float>(i,j)))
 
-.. index:: Exception
-
 
 Exception
 ---------
@@ -147,52 +238,53 @@ Exception class passed to an error. ::
 The class ``Exception`` encapsulates all or almost all necessary information about the error happened in the program. The exception is usually constructed and thrown implicitly via ``CV_Error`` and ``CV_Error_`` macros. See
 :ocv:func:`error` .
 
-.. index:: fastMalloc
+
 
 fastMalloc
 --------------
-.. ocv:function:: void* fastMalloc(size_t size)
+Allocates an aligned memory buffer.
 
-    Allocates an aligned memory buffer.
+.. ocv:function:: void* fastMalloc(size_t size)
+.. ocv:cfunction:: void* cvAlloc( size_t size )
 
     :param size: Allocated buffer size.
 
 The function allocates the buffer of the specified size and returns it. When the buffer size is 16 bytes or more, the returned buffer is aligned to 16 bytes.
 
-.. index:: fastFree
+
 
 fastFree
 ------------
-.. ocv:function:: void fastFree(void* ptr)
+Deallocates a memory buffer.
 
-    Deallocates a memory buffer.
+.. ocv:function:: void fastFree(void* ptr)
+.. ocv:cfunction:: void cvFree( void** pptr )
 
     :param ptr: Pointer to the allocated buffer.
+    
+    :param pptr: Double pointer to the allocated buffer
 
-The function deallocates the buffer allocated with
-:ocv:func:`fastMalloc` .
-If NULL pointer is passed, the function does nothing.
+The function deallocates the buffer allocated with :ocv:func:`fastMalloc` . If NULL pointer is passed, the function does nothing. C version of the function clears the pointer *pptr to avoid problems with double memory deallocation.
 
-.. index:: format
 
 format
 ----------
-.. ocv:function:: string format( const char* fmt, ... )
+Returns a text string formatted using the ``printf`` -like expression.
 
-    Returns a text string formatted using the ``printf`` -like expression.
+.. ocv:function:: string format( const char* fmt, ... )
 
     :param fmt: ``printf`` -compatible formatting specifiers.
 
 The function acts like ``sprintf``  but forms and returns an STL string. It can be used to form an error message in the
 :ocv:func:`Exception` constructor.
 
-.. index:: getNumThreads
+
 
 getNumThreads
 -----------------
-.. ocv:function:: int getNumThreads()
+Returns the number of threads used by OpenCV.
 
-    Returns the number of threads used by OpenCV.
+.. ocv:function:: int getNumThreads()
 
 The function returns the number of threads that is used by OpenCV.
 
@@ -200,13 +292,13 @@ The function returns the number of threads that is used by OpenCV.
 :ocv:func:`setNumThreads`,
 :ocv:func:`getThreadNum` 
 
-.. index:: getThreadNum
+
 
 getThreadNum
 ----------------
-.. ocv:function:: int getThreadNum()
+Returns the index of the currently executed thread.
 
-    Returns the index of the currently executed thread.
+.. ocv:function:: int getThreadNum()
 
 The function returns a 0-based index of the currently executed thread. The function is only valid inside a parallel OpenMP region. When OpenCV is built without OpenMP support, the function always returns 0.
 
@@ -214,25 +306,29 @@ The function returns a 0-based index of the currently executed thread. The funct
 :ocv:func:`setNumThreads`,
 :ocv:func:`getNumThreads` .
 
-.. index:: getTickCount
+
 
 getTickCount
 ----------------
+Returns the number of ticks.
+
 .. ocv:function:: int64 getTickCount()
 
-    Returns the number of ticks.
+.. ocv:pyfunction:: cv2.getTickCount() -> retval
 
 The function returns the number of ticks after the certain event (for example, when the machine was turned on).
 It can be used to initialize
 :ocv:func:`RNG` or to measure a function execution time by reading the tick count before and after the function call. See also the tick frequency.
 
-.. index:: getTickFrequency
+
 
 getTickFrequency
 --------------------
+Returns the number of ticks per second.
+
 .. ocv:function:: double getTickFrequency()
 
-    Returns the number of ticks per second.
+.. ocv:pyfunction:: cv2.getTickFrequency() -> retval
 
 The function returns the number of ticks per second.
 That is, the following code computes the execution time in seconds: ::
@@ -241,23 +337,51 @@ That is, the following code computes the execution time in seconds: ::
     // do something ...
     t = ((double)getTickCount() - t)/getTickFrequency();
 
-.. index:: getCPUTickCount
+
 
 getCPUTickCount
 ----------------
+Returns the number of CPU ticks.
+
 .. ocv:function:: int64 getCPUTickCount()
 
-    Returns the number of CPU ticks.
+.. ocv:pyfunction:: cv2.getCPUTickCount() -> retval
 
 The function returns the current number of CPU ticks on some architectures (such as x86, x64, PowerPC). On other platforms the function is equivalent to ``getTickCount``. It can also be used for very accurate time measurements, as well as for RNG initialization. Note that in case of multi-CPU systems a thread, from which ``getCPUTickCount`` is called, can be suspended and resumed at another CPU with its own counter. So, theoretically (and practically) the subsequent calls to the function do not necessary return the monotonously increasing values. Also, since a modern CPU varies the CPU frequency depending on the load, the number of CPU clocks spent in some code cannot be directly converted to time units. Therefore, ``getTickCount`` is generally a preferable solution for measuring execution time.
 
-.. index:: setNumThreads
+
+saturate_cast
+-------------
+Template function for accurate conversion from one primitive type to another.
+
+.. ocv:function:: template<...> _Tp saturate_cast(_Tp2 v)
+
+    :param v: Function parameter.
+
+The functions ``saturate_cast`` resemble the standard C++ cast operations, such as ``static_cast<T>()`` and others. They perform an efficient and accurate conversion from one primitive type to another (see the introduction chapter). ``saturate`` in the name means that when the input value ``v`` is out of the range of the target type, the result is not formed just by taking low bits of the input, but instead the value is clipped. For example: ::
+
+    uchar a = saturate_cast<uchar>(-100); // a = 0 (UCHAR_MIN)
+    short b = saturate_cast<short>(33333.33333); // b = 32767 (SHRT_MAX)
+
+Such clipping is done when the target type is ``unsigned char`` , ``signed char`` , ``unsigned short`` or ``signed short`` . For 32-bit integers, no clipping is done.
+
+When the parameter is a floating-point value and the target type is an integer (8-, 16- or 32-bit), the floating-point value is first rounded to the nearest integer and then clipped if needed (when the target type is 8- or 16-bit).
+
+This operation is used in the simplest or most complex image processing functions in OpenCV.
+
+.. seealso::
+
+    :ocv:func:`add`,
+    :ocv:func:`subtract`,
+    :ocv:func:`multiply`,
+    :ocv:func:`divide`,
+    :ocv:func:`Mat::convertTo`
 
 setNumThreads
 -----------------
-.. ocv:function:: void setNumThreads(int nthreads)
+Sets the number of threads used by OpenCV.
 
-    Sets the number of threads used by OpenCV.
+.. ocv:function:: void setNumThreads(int nthreads)
 
     :param nthreads: Number of threads used by OpenCV.
 
@@ -267,13 +391,17 @@ The function sets the number of threads used by OpenCV in parallel OpenMP region
 :ocv:func:`getNumThreads`,
 :ocv:func:`getThreadNum` 
 
-.. index:: setUseOptimized
+
 
 setUseOptimized
 -----------------
+Enables or disables the optimized code.
+
 .. ocv:function:: void setUseOptimized(bool onoff)
 
-    Enables or disables the optimized code.
+.. ocv:pyfunction:: cv2.setUseOptimized(onoff) -> None
+
+.. ocv:cfunction:: int cvUseOptimized( int onoff )
 
     :param onoff: The boolean flag specifying whether the optimized code should be used (``onoff=true``) or not (``onoff=false``).
 
@@ -281,12 +409,12 @@ The function can be used to dynamically turn on and off optimized code (code tha
 
 By default, the optimized code is enabled unless you disable it in CMake. The current status can be retrieved using ``useOptimized``.
 
-.. index:: useOptimized
-
 useOptimized
 -----------------
+Returns the status of optimized code usage.
+
 .. ocv:function:: bool useOptimized()
 
-    Returns the status of optimized code usage.
+.. ocv:pyfunction:: cv2.useOptimized() -> retval
 
 The function returns ``true`` if the optimized code is enabled. Otherwise, it returns ``false``.
index e08a027..93532e4 100644 (file)
@@ -162,5 +162,3 @@ FileNodeIterator
 .. ocv:class:: FileNodeIterator
 
 The class ``FileNodeIterator`` is used to iterate through sequences and mappings. A standard STL notation, with ``node.begin()``, ``node.end()`` denoting the beginning and the end of a sequence, stored in ``node``.  See the data reading sample in the beginning of the section.
-
-
index fdb2707..07a1894 100644 (file)
@@ -2075,6 +2075,7 @@ void cv::compare(InputArray _src1, InputArray _src2, OutputArray _dst, int op)
 
     if( kind1 == kind2 && src1.dims <= 2 && src2.dims <= 2 && src1.size() == src2.size() && src1.type() == src2.type() )
     {
+        CV_Assert(src1.channels() == 1);
         _dst.create(src1.size(), CV_8UC1);
         Mat dst = _dst.getMat();
         Size sz = getContinuousSize(src1, src2, dst, src1.channels());
index 987b57a..f0905a1 100644 (file)
@@ -148,7 +148,7 @@ static void updateContinuityFlag(Mat& m)
             break;
     }
     
-    int64 t = (int64)(m.step[0]/CV_ELEM_SIZE(m.flags))*m.size[0];
+    int64 t = (int64)m.step[0]*m.size[0];
     if( j <= i && t == (int)t )
         m.flags |= Mat::CONTINUOUS_FLAG;
     else
index 56685dd..5983c46 100644 (file)
@@ -9,7 +9,7 @@ represented as vectors in a multidimensional space. All objects that implement t
 descriptor extractors inherit the
 :ocv:class:`DescriptorExtractor` interface.
 
-.. index:: DescriptorExtractor
+
 
 DescriptorExtractor
 -------------------
@@ -47,13 +47,13 @@ distances between descriptors. Therefore, a collection of
 descriptors is represented as
 :ocv:class:`Mat` , where each row is a keypoint descriptor.
 
-.. index:: DescriptorExtractor::compute
+
 
 DescriptorExtractor::compute
 --------------------------------
-.. ocv:function:: void DescriptorExtractor::compute( const Mat& image, vector<KeyPoint>& keypoints, Mat& descriptors ) const
+Computes the descriptors for a set of keypoints detected in an image (first variant) or image set (second variant).
 
-    Computes the descriptors for a set of keypoints detected in an image (first variant) or image set (second variant).
+.. ocv:function:: void DescriptorExtractor::compute( const Mat& image, vector<KeyPoint>& keypoints, Mat& descriptors ) const
 
     :param image: Image.
 
@@ -71,33 +71,33 @@ DescriptorExtractor::compute
 
     :param descriptors: Descriptor collection. ``descriptors[i]`` are descriptors computed for a ``keypoints[i]`` set.
 
-.. index:: DescriptorExtractor::read
+
 
 DescriptorExtractor::read
 -----------------------------
-.. ocv:function:: void DescriptorExtractor::read( const FileNode& fn )
+Reads the object of a descriptor extractor from a file node.
 
-    Reads the object of a descriptor extractor from a file node.
+.. ocv:function:: void DescriptorExtractor::read( const FileNode& fn )
 
     :param fn: File node from which the detector is read.
 
-.. index:: DescriptorExtractor::write
+
 
 DescriptorExtractor::write
 ------------------------------
-.. ocv:function:: void DescriptorExtractor::write( FileStorage& fs ) const
+Writes the object of a descriptor extractor to a file storage.
 
-    Writes the object of a descriptor extractor to a file storage.
+.. ocv:function:: void DescriptorExtractor::write( FileStorage& fs ) const
 
     :param fs: File storage where the detector is written.
 
-.. index:: DescriptorExtractor::create
+
 
 DescriptorExtractor::create
 -------------------------------
-.. ocv:function:: Ptr<DescriptorExtractor>  DescriptorExtractor::create( const string& descriptorExtractorType )
+Creates a descriptor extractor by name.
 
-    Creates a descriptor extractor by name.
+.. ocv:function:: Ptr<DescriptorExtractor>  DescriptorExtractor::create( const string& descriptorExtractorType )
 
     :param descriptorExtractorType: Descriptor extractor type.
 
@@ -112,9 +112,7 @@ A combined format is also supported: descriptor extractor adapter name ( ``"Oppo
 :ocv:class:`OpponentColorDescriptorExtractor` ) + descriptor extractor name (see above),
 for example: ``"OpponentSIFT"`` .
 
-.. index:: SiftDescriptorExtractor
 
-.. _SiftDescriptorExtractor:
 
 SiftDescriptorExtractor
 -----------------------
@@ -144,9 +142,7 @@ Wrapping class for computing descriptors by using the
     }
 
 
-.. index:: SurfDescriptorExtractor
 
-.. _SurfDescriptorExtractor:
 
 SurfDescriptorExtractor
 -----------------------
@@ -170,9 +166,7 @@ Wrapping class for computing descriptors by using the
     }
 
 
-.. index:: OrbDescriptorExtractor
 
-.. _OrbDescriptorExtractor:
 
 OrbDescriptorExtractor
 ---------------------------
@@ -196,7 +190,7 @@ Wrapping class for computing descriptors by using the
     }
 
 
-.. index:: CalonderDescriptorExtractor
+
 
 CalonderDescriptorExtractor
 ---------------------------
@@ -220,10 +214,6 @@ Wrapping class for computing descriptors by using the
     }
 
 
-.. index:: OpponentColorDescriptorExtractor
-
-.. _OpponentColorDescriptorExtractor:
-
 OpponentColorDescriptorExtractor
 --------------------------------
 .. ocv:class:: OpponentColorDescriptorExtractor
@@ -248,9 +238,6 @@ them into a single color descriptor. ::
     };
 
 
-.. index:: BriefDescriptorExtractor
-
-.. _BriefDescriptorExtractor:
 
 BriefDescriptorExtractor
 ------------------------
index 6ed69f9..31ac5a1 100644 (file)
@@ -9,10 +9,6 @@ that are represented as vectors in a multidimensional space. All objects that im
 descriptor matchers inherit the
 :ocv:class:`DescriptorMatcher` interface.
 
-.. index:: DMatch
-
-.. _DMatch:
-
 DMatch
 ------
 .. ocv:class:: DMatch
@@ -42,10 +38,6 @@ train descriptor index, train image index, and distance between descriptors. ::
     };
 
 
-.. index:: DescriptorMatcher
-
-.. _DescriptorMatcher:
-
 DescriptorMatcher
 -----------------
 .. ocv:class:: DescriptorMatcher
@@ -104,66 +96,67 @@ with an image set. ::
     };
 
 
-.. index:: DescriptorMatcher::add
-
 DescriptorMatcher::add
 --------------------------
-.. ocv:function:: void add( const vector<Mat>& descriptors )
+Adds descriptors to train a descriptor collection. If the collection ``trainDescCollectionis`` is not empty, the new descriptors are added to existing train descriptors.
 
-    Adds descriptors to train a descriptor collection. If the collection ``trainDescCollectionis`` is not empty, the new descriptors are added to existing train descriptors.
+.. ocv:function:: void DescriptorMatcher::add( const vector<Mat>& descriptors )
 
     :param descriptors: Descriptors to add. Each  ``descriptors[i]``  is a set of descriptors from the same train image.
 
-.. index:: DescriptorMatcher::getTrainDescriptors
 
 DescriptorMatcher::getTrainDescriptors
 ------------------------------------------
-.. ocv:function:: const vector<Mat>& getTrainDescriptors() const
+Returns a constant link to the train descriptor collection ``trainDescCollection`` .
+
+.. ocv:function:: const vector<Mat>& DescriptorMatcher::getTrainDescriptors() const
+
+    
 
-    Returns a constant link to the train descriptor collection ``trainDescCollection`` .
 
-.. index:: DescriptorMatcher::clear
 
 DescriptorMatcher::clear
 ----------------------------
+Clears the train descriptor collection.
+
 .. ocv:function:: void DescriptorMatcher::clear()
 
-    Clears the train descriptor collection.
 
-.. index:: DescriptorMatcher::empty
 
 DescriptorMatcher::empty
 ----------------------------
+Returns true if there are no train descriptors in the collection.
+
 .. ocv:function:: bool DescriptorMatcher::empty() const
 
-    Returns true if there are no train descriptors in the collection.
 
-.. index:: DescriptorMatcher::isMaskSupported
 
 DescriptorMatcher::isMaskSupported
 --------------------------------------
+Returns true if the descriptor matcher supports masking permissible matches.
+
 .. ocv:function:: bool DescriptorMatcher::isMaskSupported()
 
-    Returns true if the descriptor matcher supports masking permissible matches.
 
-.. index:: DescriptorMatcher::train
 
 DescriptorMatcher::train
 ----------------------------
+Trains a descriptor matcher
+
 .. ocv:function:: void DescriptorMatcher::train()
 
-    Trains a descriptor matcher (for example, the flann index). In all methods to match, the method ``train()`` is run every time before matching. Some descriptor matchers (for example, ``BruteForceMatcher``) have an empty implementation of this method. Other matchers really train their inner structures (for example, ``FlannBasedMatcher`` trains ``flann::Index`` ).
+Trains a descriptor matcher (for example, the flann index). In all methods to match, the method ``train()`` is run every time before matching. Some descriptor matchers (for example, ``BruteForceMatcher``) have an empty implementation of this method. Other matchers really train their inner structures (for example, ``FlannBasedMatcher`` trains ``flann::Index`` ).
+
 
-.. index:: DescriptorMatcher::match
 
 DescriptorMatcher::match
 ----------------------------
+Finds the best match for each descriptor from a query set.
+
 .. ocv:function:: void DescriptorMatcher::match( const Mat& queryDescriptors, const Mat& trainDescriptors, vector<DMatch>& matches, const Mat& mask=Mat() ) const
 
 .. ocv:function:: void DescriptorMatcher::match( const Mat& queryDescriptors, vector<DMatch>& matches, const vector<Mat>& masks=vector<Mat>() )
 
-    Finds the best match for each descriptor from a query set.
-
     :param queryDescriptors: Query set of descriptors.
 
     :param trainDescriptors: Train set of descriptors. This set is not added to the train descriptors collection stored in the class object.
@@ -176,16 +169,16 @@ DescriptorMatcher::match
 
 In the first variant of this method, the train descriptors are passed as an input argument. In the second variant of the method, train descriptors collection that was set by ``DescriptorMatcher::add`` is used. Optional mask (or masks) can be passed to specify which query and training descriptors can be matched. Namely, ``queryDescriptors[i]`` can be matched with ``trainDescriptors[j]`` only if ``mask.at<uchar>(i,j)`` is non-zero. 
 
-.. index:: DescriptorMatcher::knnMatch
+
 
 DescriptorMatcher::knnMatch
 -------------------------------
+Finds the k best matches for each descriptor from a query set.
+
 .. ocv:function:: void DescriptorMatcher::knnMatch( const Mat& queryDescriptors,       const Mat& trainDescriptors,       vector<vector<DMatch> >& matches,       int k, const Mat& mask=Mat(),       bool compactResult=false ) const
 
 .. ocv:function:: void DescriptorMatcher::knnMatch( const Mat& queryDescriptors,           vector<vector<DMatch> >& matches, int k,      const vector<Mat>& masks=vector<Mat>(),       bool compactResult=false )
 
-    Finds the k best matches for each descriptor from a query set.
-
     :param queryDescriptors: Query set of descriptors.
 
     :param trainDescriptors: Train set of descriptors. This set is not added to the train descriptors collection stored in the class object.
@@ -202,16 +195,16 @@ DescriptorMatcher::knnMatch
 
 These extended variants of :ocv:func:`DescriptorMatcher::match` methods find several best matches for each query descriptor. The matches are returned in the distance increasing order. See :ocv:func:`DescriptorMatcher::match` for the details about query and train descriptors. 
 
-.. index:: DescriptorMatcher::radiusMatch
+
 
 DescriptorMatcher::radiusMatch
 ----------------------------------
+For each query descriptor, finds the training descriptors not farther than the specified distance.
+
 .. ocv:function:: void DescriptorMatcher::radiusMatch( const Mat& queryDescriptors,           const Mat& trainDescriptors,           vector<vector<DMatch> >& matches,           float maxDistance, const Mat& mask=Mat(),           bool compactResult=false ) const
 
 .. ocv:function:: void DescriptorMatcher::radiusMatch( const Mat& queryDescriptors,           vector<vector<DMatch> >& matches,           float maxDistance,      const vector<Mat>& masks=vector<Mat>(),       bool compactResult=false )
 
-    For each query descriptor, finds the training descriptors not farther than the specified distance.
-
     :param queryDescriptors: Query set of descriptors.
 
     :param trainDescriptors: Train set of descriptors. This set is not added to the train descriptors collection stored in the class object.
@@ -228,23 +221,23 @@ DescriptorMatcher::radiusMatch
     
 For each query descriptor, the methods find such training descriptors that the distance between the query descriptor and the training descriptor is equal or smaller than ``maxDistance``. Found matches are returned in the distance increasing order.
 
-.. index:: DescriptorMatcher::clone
+
 
 DescriptorMatcher::clone
 ----------------------------
-.. ocv:function:: Ptr<DescriptorMatcher> DescriptorMatcher::clone( bool emptyTrainData ) const
+Clones the matcher.
 
-    Clones the matcher.
+.. ocv:function:: Ptr<DescriptorMatcher> DescriptorMatcher::clone( bool emptyTrainData ) const
 
     :param emptyTrainData: If ``emptyTrainData`` is false, the method creates a deep copy of the object, that is, copies both parameters and train data. If ``emptyTrainData`` is true, the method creates an object copy with the current parameters but with empty train data.
 
-.. index:: DescriptorMatcher::create
+
 
 DescriptorMatcher::create
 -----------------------------
-.. ocv:function:: Ptr<DescriptorMatcher> DescriptorMatcher::create( const string& descriptorMatcherType )
+Creates a descriptor matcher of a given type with the default parameters (using default constructor).
 
-    Creates a descriptor matcher of a given type with the default parameters (using default constructor).
+.. ocv:function:: Ptr<DescriptorMatcher> DescriptorMatcher::create( const string& descriptorMatcherType )
 
     :param descriptorMatcherType: Descriptor matcher type. Now the following matcher types are supported:
 
@@ -259,9 +252,9 @@ DescriptorMatcher::create
         * 
             ``FlannBased``
 
-.. index:: BruteForceMatcher
 
-.. _BruteForceMatcher:
+
+
 
 BruteForceMatcher
 -----------------
@@ -345,9 +338,9 @@ For efficiency, ``BruteForceMatcher`` is used as a template parameterized with t
     };
 
 
-.. index:: FlannBasedMatcher
 
-.. _FlannBasedMatcher:
+
+
 
 FlannBasedMatcher
 -----------------
index 6ab3acb..bc0984a 100644 (file)
@@ -12,57 +12,60 @@ KeyPoint
 --------
 .. ocv:class:: KeyPoint
 
-Data structure for salient point detectors. ::
+Data structure for salient point detectors.
+
+    .. ocv:member:: Point2f pt
+    
+        coordinates of the keypoint
+        
+    .. ocv:member:: float size
+    
+         diameter of the meaningful keypoint neighborhood
+         
+    .. ocv:member:: float angle
+    
+        computed orientation of the keypoint (-1 if not applicable)
+        
+    .. ocv:member:: float response
+    
+        the response by which the most strong keypoints have been selected. Can be used for further sorting or subsampling
+        
+    .. ocv:member:: int octave
+    
+        octave (pyramid layer) from which the keypoint has been extracted
+        
+    .. ocv:member:: int class_id
+    
+        object id that can be used to clustered keypoints by an object they belong to
+
+KeyPoint::KeyPoint
+------------------
+The keypoint constructors
+
+.. ocv:function:: KeyPoint::KeyPoint()
+
+.. ocv:function:: KeyPoint::KeyPoint(Point2f _pt, float _size, float _angle=-1, float _response=0, int _octave=0, int _class_id=-1)
+
+.. ocv:function:: KeyPoint::KeyPoint(float x, float y, float _size, float _angle=-1, float _response=0, int _octave=0, int _class_id=-1)
+
+.. ocv:pyfunction:: cv2.KeyPoint(x, y, _size[, _angle[, _response[, _octave[, _class_id]]]]) -> <KeyPoint object>
+
+    :param x: x-coordinate of the keypoint
+    
+    :param y: y-coordinate of the keypoint
+    
+    :param _pt: x & y coordinates of the keypoint
+    
+    :param _size: keypoint diameter
+    
+    :param _angle: keypoint orientation
+    
+    :param _response: keypoint detector response on the keypoint (that is, strength of the keypoint)
+    
+    :param _octave: pyramid octave in which the keypoint has been detected
+    
+    :param _class_id: object id
 
-    class KeyPoint
-    {
-    public:
-        // the default constructor
-        KeyPoint() : pt(0,0), size(0), angle(-1), response(0), octave(0),
-                     class_id(-1) {}
-        // the full constructor
-        KeyPoint(Point2f _pt, float _size, float _angle=-1,
-                float _response=0, int _octave=0, int _class_id=-1)
-                : pt(_pt), size(_size), angle(_angle), response(_response),
-                  octave(_octave), class_id(_class_id) {}
-        // another form of the full constructor
-        KeyPoint(float x, float y, float _size, float _angle=-1,
-                float _response=0, int _octave=0, int _class_id=-1)
-                : pt(x, y), size(_size), angle(_angle), response(_response),
-                  octave(_octave), class_id(_class_id) {}
-        // converts vector of keypoints to vector of points
-        static void convert(const std::vector<KeyPoint>& keypoints,
-                            std::vector<Point2f>& points2f,
-                            const std::vector<int>& keypointIndexes=std::vector<int>());
-        // converts vector of points to the vector of keypoints, where each
-        // keypoint is assigned to the same size and the same orientation
-        static void convert(const std::vector<Point2f>& points2f,
-                            std::vector<KeyPoint>& keypoints,
-                            float size=1, float response=1, int octave=0,
-                            int class_id=-1);
-
-        // computes overlap for pair of keypoints;
-        // overlap is a ratio between area of keypoint regions intersection and
-        // area of keypoint regions union (now keypoint region is a circle)
-        static float overlap(const KeyPoint& kp1, const KeyPoint& kp2);
-
-        Point2f pt; // coordinates of the keypoints
-        float size; // diameter of the meaningful keypoint neighborhood
-        float angle; // computed orientation of the keypoint (-1 if not applicable)
-        float response; // the response by which the most strong keypoints
-                        // have been selected. Can be used for further sorting
-                        // or subsampling
-        int octave; // octave (pyramid layer) from which the keypoint has been extracted
-        int class_id; // object class (if the keypoints need to be clustered by
-                      // an object they belong to)
-    };
-
-    // writes vector of keypoints to the file storage
-    void write(FileStorage& fs, const string& name, const vector<KeyPoint>& keypoints);
-    // reads vector of keypoints from the specified file storage node
-    void read(const FileNode& node, CV_OUT vector<KeyPoint>& keypoints);
-
-..
 
 FeatureDetector
 ---------------
@@ -93,9 +96,9 @@ Abstract base class for 2D image feature detectors. ::
 
 FeatureDetector::detect
 ---------------------------
-.. ocv:function:: void FeatureDetector::detect( const Mat& image,                                vector<KeyPoint>& keypoints,                                 const Mat& mask=Mat() ) const
+Detects keypoints in an image (first variant) or image set (second variant).
 
-    Detects keypoints in an image (first variant) or image set (second variant).
+.. ocv:function:: void FeatureDetector::detect( const Mat& image, vector<KeyPoint>& keypoints, const Mat& mask=Mat() ) const
 
     :param image: Image.
 
@@ -113,25 +116,25 @@ FeatureDetector::detect
 
 FeatureDetector::read
 -------------------------
-.. ocv:function:: void FeatureDetector::read( const FileNode& fn )
+Reads a feature detector object from a file node.
 
-    Reads a feature detector object from a file node.
+.. ocv:function:: void FeatureDetector::read( const FileNode& fn )
 
     :param fn: File node from which the detector is read.
 
 FeatureDetector::write
 --------------------------
-.. ocv:function:: void FeatureDetector::write( FileStorage& fs ) const
+Writes a feature detector object to a file storage.
 
-    Writes a feature detector object to a file storage.
+.. ocv:function:: void FeatureDetector::write( FileStorage& fs ) const
 
     :param fs: File storage where the detector is written.
 
 FeatureDetector::create
 ---------------------------
-.. ocv:function:: Ptr<FeatureDetector> FeatureDetector::create( const string& detectorType )
+Creates a feature detector by its name.
 
-    Creates a feature detector by its name.
+.. ocv:function:: Ptr<FeatureDetector> FeatureDetector::create( const string& detectorType )
 
     :param detectorType: Feature detector type.
 
@@ -457,12 +460,11 @@ Example of creating ``DynamicAdaptedFeatureDetector`` : ::
                                   new FastAdjuster(20,true)));
 
 
-                                                                 
 DynamicAdaptedFeatureDetector::DynamicAdaptedFeatureDetector
 ----------------------------------------------------------------
-.. ocv:function:: DynamicAdaptedFeatureDetector::DynamicAdaptedFeatureDetector(       const Ptr<AdjusterAdapter>& adjuster,       int min_features,   int max_features,   int max_iters )
+The constructor
 
-    Constructs the class.
+.. ocv:function:: DynamicAdaptedFeatureDetector::DynamicAdaptedFeatureDetector(       const Ptr<AdjusterAdapter>& adjuster,       int min_features,   int max_features,   int max_iters )
 
     :param adjuster:  :ocv:class:`AdjusterAdapter`  that detects features and adjusts parameters.
 
@@ -497,9 +499,9 @@ See
 
 AdjusterAdapter::tooFew
 ---------------------------
-.. ocv:function:: void AdjusterAdapter::tooFew(int min, int n_detected)
+Adjusts the detector parameters to detect more features.
 
-    Adjusts the detector parameters to detect more features.
+.. ocv:function:: void AdjusterAdapter::tooFew(int min, int n_detected)
 
     :param min: Minimum desired number of features.
 
@@ -514,9 +516,9 @@ Example: ::
 
 AdjusterAdapter::tooMany
 ----------------------------
-.. ocv:function:: void AdjusterAdapter::tooMany(int max, int n_detected)
+Adjusts the detector parameters to detect less features.
 
-    Adjusts the detector parameters to detect less features.
+.. ocv:function:: void AdjusterAdapter::tooMany(int max, int n_detected)
 
     :param max: Maximum desired number of features.
 
@@ -532,9 +534,9 @@ Example: ::
 
 AdjusterAdapter::good
 -------------------------
-.. ocv:function:: bool AdjusterAdapter::good() const
+Returns false if the detector parameters cannot be adjusted any more. 
 
-    Returns false if the detector parameters cannot be adjusted any more. 
+.. ocv:function:: bool AdjusterAdapter::good() const
 
 Example: ::
 
@@ -545,6 +547,8 @@ Example: ::
 
 AdjusterAdapter::create
 -------------------------
+Creates an adjuster adapter by name
+
 .. ocv:function:: Ptr<AdjusterAdapter> AdjusterAdapter::create( const string& detectorType )
 
     Creates an adjuster adapter by name ``detectorType``. The detector name is the same as in :ocv:func:`FeatureDetector::create`, but now supports ``"FAST"``, ``"STAR"``, and ``"SURF"`` only.
index ce50d1d..7289b53 100644 (file)
@@ -11,7 +11,7 @@ Every descriptor with the
 :ocv:class:`VectorDescriptorMatcher` ).
 There are descriptors such as the One-way descriptor and Ferns that have the ``GenericDescriptorMatcher`` interface implemented but do not support ``DescriptorExtractor``.
 
-.. index:: GenericDescriptorMatcher
+
 
 GenericDescriptorMatcher
 ------------------------
@@ -79,68 +79,69 @@ Abstract interface for extracting and matching a keypoint descriptor. There are
     };
 
 
-.. index:: GenericDescriptorMatcher::add
+
 
 GenericDescriptorMatcher::add
 ---------------------------------
-.. ocv:function:: void GenericDescriptorMatcher::add( const vector<Mat>& images,                        vector<vector<KeyPoint> >& keypoints )
+Adds images and their keypoints to the training collection stored in the class instance.
 
-    Adds images and their keypoints to the training collection stored in the class instance.
+.. ocv:function:: void GenericDescriptorMatcher::add( const vector<Mat>& images,                        vector<vector<KeyPoint> >& keypoints )
 
     :param images: Image collection.
 
     :param keypoints: Point collection. It is assumed that ``keypoints[i]``  are keypoints detected in the image  ``images[i]`` .
 
-.. index:: GenericDescriptorMatcher::getTrainImages
+
 
 GenericDescriptorMatcher::getTrainImages
 --------------------------------------------
+Returns a train image collection.
+
 .. ocv:function:: const vector<Mat>& GenericDescriptorMatcher::getTrainImages() const
 
-    Returns a train image collection.
 
-.. index:: GenericDescriptorMatcher::getTrainKeypoints
 
 GenericDescriptorMatcher::getTrainKeypoints
 -----------------------------------------------
+Returns a train keypoints collection.
+
 .. ocv:function:: const vector<vector<KeyPoint> >&  GenericDescriptorMatcher::getTrainKeypoints() const
 
-    Returns a train keypoints collection.
 
-.. index:: GenericDescriptorMatcher::clear
 
 GenericDescriptorMatcher::clear
 -----------------------------------
+Clears a train collection (images and keypoints).
+
 .. ocv:function:: void GenericDescriptorMatcher::clear()
 
-    Clears a train collection (images and keypoints).
 
-.. index:: GenericDescriptorMatcher::train
 
 GenericDescriptorMatcher::train
 -----------------------------------
+Trains descriptor matcher
+
 .. ocv:function:: void GenericDescriptorMatcher::train()
 
-    Trains an object, for example, a tree-based structure, to extract descriptors or to optimize descriptors matching.
+Prepares descriptor matcher, for example, creates a tree-based structure, to extract descriptors or to optimize descriptors matching.
 
-.. index:: GenericDescriptorMatcher::isMaskSupported
 
 GenericDescriptorMatcher::isMaskSupported
 ---------------------------------------------
+Returns ``true`` if a generic descriptor matcher supports masking permissible matches.
+
 .. ocv:function:: void GenericDescriptorMatcher::isMaskSupported()
 
-    Returns ``true`` if a generic descriptor matcher supports masking permissible matches.
 
-.. index:: GenericDescriptorMatcher::classify
 
 GenericDescriptorMatcher::classify
 --------------------------------------
+Classifies keypoints from a query set.
+
 .. ocv:function:: void GenericDescriptorMatcher::classify(  const Mat& queryImage,           vector<KeyPoint>& queryKeypoints,           const Mat& trainImage,           vector<KeyPoint>& trainKeypoints ) const
 
 .. ocv:function:: void GenericDescriptorMatcher::classify( const Mat& queryImage,           vector<KeyPoint>& queryKeypoints )
 
-    Classifies keypoints from a query set.
-
     :param queryImage: Query image.
 
     :param queryKeypoints: Keypoints from a query image.
@@ -159,15 +160,15 @@ The methods do the following:
 #.
     Set the ``class_id`` field of each keypoint from the query set to ``class_id`` of the corresponding keypoint from the training set.
 
-.. index:: GenericDescriptorMatcher::match
+
 
 GenericDescriptorMatcher::match
 -----------------------------------
-.. ocv:function:: void GenericDescriptorMatcher::match(           const Mat& queryImage, vector<KeyPoint>& queryKeypoints,      const Mat& trainImage, vector<KeyPoint>& trainKeypoints,      vector<DMatch>& matches, const Mat& mask=Mat() ) const
+Finds the best match in the training set for each keypoint from the query set.
 
-.. ocv:function:: void GenericDescriptorMatcher::match(           const Mat& queryImage, vector<KeyPoint>& queryKeypoints,          vector<DMatch>& matches,           const vector<Mat>& masks=vector<Mat>() )
+.. ocv:function:: void GenericDescriptorMatcher::match( const Mat& queryImage, vector<KeyPoint>& queryKeypoints, const Mat& trainImage, vector<KeyPoint>& trainKeypoints, vector<DMatch>& matches, const Mat& mask=Mat() ) const
 
-    Finds the best match in the training set for each keypoint from the query set.
+.. ocv:function:: void GenericDescriptorMatcher::match( const Mat& queryImage, vector<KeyPoint>& queryKeypoints, vector<DMatch>& matches, const vector<Mat>& masks=vector<Mat>() )
 
     :param queryImage: Query image.
 
@@ -185,61 +186,57 @@ GenericDescriptorMatcher::match
 
 The methods find the best match for each query keypoint. In the first variant of the method, a train image and its keypoints are the input arguments. In the second variant, query keypoints are matched to the internally stored training collection that can be built using the ``GenericDescriptorMatcher::add`` method.     Optional mask (or masks) can be passed to specify which query and training descriptors can be matched. Namely, ``queryKeypoints[i]`` can be matched with ``trainKeypoints[j]`` only if ``mask.at<uchar>(i,j)`` is non-zero.
 
-.. index:: GenericDescriptorMatcher::knnMatch
+
 
 GenericDescriptorMatcher::knnMatch
 --------------------------------------
+Finds the ``k`` best matches for each query keypoint.
+
 .. ocv:function:: void GenericDescriptorMatcher::knnMatch(           const Mat& queryImage, vector<KeyPoint>& queryKeypoints,      const Mat& trainImage, vector<KeyPoint>& trainKeypoints,      vector<vector<DMatch> >& matches, int k,       const Mat& mask=Mat(), bool compactResult=false ) const
 
 .. ocv:function:: void GenericDescriptorMatcher::knnMatch(           const Mat& queryImage, vector<KeyPoint>& queryKeypoints,      vector<vector<DMatch> >& matches, int k,       const vector<Mat>& masks=vector<Mat>(),       bool compactResult=false )
-
-    Finds the ``k`` best matches for each query keypoint.
     
 The methods are extended variants of ``GenericDescriptorMatch::match``. The parameters are similar, and the  the semantics is similar to ``DescriptorMatcher::knnMatch``. But this class does not require explicitly computed keypoint descriptors.
 
-.. index:: GenericDescriptorMatcher::radiusMatch
+
 
 GenericDescriptorMatcher::radiusMatch
 -----------------------------------------
+For each query keypoint, finds the training keypoints not farther than the specified distance.
+
 .. ocv:function:: void GenericDescriptorMatcher::radiusMatch(           const Mat& queryImage, vector<KeyPoint>& queryKeypoints,      const Mat& trainImage, vector<KeyPoint>& trainKeypoints,      vector<vector<DMatch> >& matches, float maxDistance,       const Mat& mask=Mat(), bool compactResult=false ) const
 
 .. ocv:function:: void GenericDescriptorMatcher::radiusMatch(           const Mat& queryImage, vector<KeyPoint>& queryKeypoints,      vector<vector<DMatch> >& matches, float maxDistance,       const vector<Mat>& masks=vector<Mat>(),       bool compactResult=false )
 
-    For each query keypoint, finds the training keypoints not farther than the specified distance.
-
 The methods are similar to ``DescriptorMatcher::radius``. But this class does not require explicitly computed keypoint descriptors.
 
-.. index:: GenericDescriptorMatcher::read
+
 
 GenericDescriptorMatcher::read
 ----------------------------------
+Reads a matcher object from a file node.
+
 .. ocv:function:: void GenericDescriptorMatcher::read( const FileNode& fn )
 
-    Reads a matcher object from a file node.
 
-.. index:: GenericDescriptorMatcher::write
 
 GenericDescriptorMatcher::write
 -----------------------------------
-.. ocv:function:: void GenericDescriptorMatcher::write( FileStorage& fs ) const
+Writes a match object to a file storage.
 
-    Writes a match object to a file storage.
+.. ocv:function:: void GenericDescriptorMatcher::write( FileStorage& fs ) const
 
-.. index:: GenericDescriptorMatcher::clone
 
 GenericDescriptorMatcher::clone
 -----------------------------------
-.. ocv:function:: Ptr<GenericDescriptorMatcher> GenericDescriptorMatcher::clone( bool emptyTrainData ) const
+Clones the matcher.
 
-    Clones the matcher.
+.. ocv:function:: Ptr<GenericDescriptorMatcher> GenericDescriptorMatcher::clone( bool emptyTrainData ) const
 
     :param emptyTrainData: If ``emptyTrainData`` is false, the method creates a deep copy of the object, that is, copies
             both parameters and train data. If ``emptyTrainData`` is true, the method creates an object copy with the current parameters
             but with empty train data.
 
-.. index:: OneWayDescriptorMatcher
-
-.. _OneWayDescriptorMatcher:
 
 OneWayDescriptorMatcher
 -----------------------
@@ -298,7 +295,7 @@ Wrapping class for computing, matching, and classifying descriptors using the
     };
 
 
-.. index:: FernDescriptorMatcher
+
 
 FernDescriptorMatcher
 ---------------------
@@ -355,9 +352,7 @@ Wrapping class for computing, matching, and classifying descriptors using the
     };
 
 
-.. index:: VectorDescriptorMatcher
 
-.. _VectorDescriptorMatcher:
 
 VectorDescriptorMatcher
 -----------------------
index beed4da..82450b6 100644 (file)
@@ -1,16 +1,16 @@
 Drawing Function of Keypoints and Matches
 =========================================
 
-.. index:: drawMatches
+
 
 drawMatches
 ---------------
+Draws the found matches of keypoints from two images.
 
 .. ocv:function:: void drawMatches( const Mat& img1, const vector<KeyPoint>& keypoints1,          const Mat& img2, const vector<KeyPoint>& keypoints2,          const vector<DMatch>& matches1to2, Mat& outImg,          const Scalar& matchColor=Scalar::all(-1),           const Scalar& singlePointColor=Scalar::all(-1),          const vector<char>& matchesMask=vector<char>(),          int flags=DrawMatchesFlags::DEFAULT )
 
 .. ocv:function:: void drawMatches( const Mat& img1, const vector<KeyPoint>& keypoints1,           const Mat& img2, const vector<KeyPoint>& keypoints2,           const vector<vector<DMatch> >& matches1to2, Mat& outImg,           const Scalar& matchColor=Scalar::all(-1),            const Scalar& singlePointColor=Scalar::all(-1),           const vector<vector<char>>& matchesMask=           vector<vector<char> >(),           int flags=DrawMatchesFlags::DEFAULT )
-    
-    Draws the found matches of keypoints from two images.
+
 
     :param img1: First source image.
 
@@ -59,13 +59,13 @@ This function draws matches of keypoints from two images in the output image. Ma
 
 ..
 
-.. index:: drawKeypoints
+
 
 drawKeypoints
 -----------------
-.. ocv:function:: void drawKeypoints( const Mat& image,           const vector<KeyPoint>& keypoints,           Mat& outImg, const Scalar& color=Scalar::all(-1),           int flags=DrawMatchesFlags::DEFAULT )
+Draws keypoints.
 
-    Draws keypoints.
+.. ocv:function:: void drawKeypoints( const Mat& image,           const vector<KeyPoint>& keypoints,           Mat& outImg, const Scalar& color=Scalar::all(-1),           int flags=DrawMatchesFlags::DEFAULT )
 
     :param image: Source image.
 
index 2f84894..fd83387 100644 (file)
@@ -3,13 +3,11 @@ Feature Detection and Description
 
 .. highlight:: cpp
 
-.. index:: FAST
-
 FAST
 --------
-.. ocv:function:: void FAST( const Mat& image, vector<KeyPoint>& keypoints,            int threshold, bool nonmaxSupression=true )
+Detects corners using the FAST algorithm
 
-    Detects corners using the FAST algorithm by E. Rosten (*Machine Learning for High-speed Corner Detection*, 2006).
+.. ocv:function:: void FAST( const Mat& image, vector<KeyPoint>& keypoints,            int threshold, bool nonmaxSupression=true )
 
     :param image: Image where keypoints (corners) are detected.
 
@@ -19,9 +17,8 @@ FAST
 
     :param nonmaxSupression: If it is true, non-maximum supression is applied to detected corners (keypoints).
 
-.. index:: MSER
+Detects corners using the FAST algorithm by E. Rosten (*Machine Learning for High-speed Corner Detection*, 2006).
 
-.. _MSER:
 
 MSER
 ----
@@ -48,46 +45,53 @@ Maximally stable extremal region extractor. ::
 The class encapsulates all the parameters of the MSER extraction algorithm (see
 http://en.wikipedia.org/wiki/Maximally_stable_extremal_regions). Also see http://opencv.willowgarage.com/wiki/documentation/cpp/features2d/MSER for usefull comments and parameters description.
 
-.. index:: StarDetector
-
-.. _StarDetector:
 
 StarDetector
 ------------
 .. ocv:class:: StarDetector
 
-Class implementing the ``Star`` keypoint detector. ::
+Class implementing the ``Star`` keypoint detector, a modified version of the ``CenSurE`` keypoint detector described in [Agrawal08]_.
 
-    class StarDetector : CvStarDetectorParams
-    {
-    public:
-        // default constructor
-        StarDetector();
-        // the full constructor that initializes all the algorithm parameters:
-        // maxSize - maximum size of the features. The following
-        //      values of the parameter are supported:
-        //      4, 6, 8, 11, 12, 16, 22, 23, 32, 45, 46, 64, 90, 128
-        // responseThreshold - threshold for the approximated laplacian,
-        //      used to eliminate weak features. The larger it is,
-        //      the less features will be retrieved
-        // lineThresholdProjected - another threshold for the laplacian to
-        //      eliminate edges
-        // lineThresholdBinarized - another threshold for the feature
-        //      size to eliminate edges.
-        // The larger the 2nd threshold, the more points you get.
-        StarDetector(int maxSize, int responseThreshold,
-                     int lineThresholdProjected,
-                     int lineThresholdBinarized,
-                     int suppressNonmaxSize);
-
-        // finds keypoints in an image
-        void operator()(const Mat& image, vector<KeyPoint>& keypoints) const;
-    };
+.. [Agrawal08] Agrawal, M. and Konolige, K. and Blas, M.R. "CenSurE: Center Surround Extremas for Realtime Feature Detection and Matching", ECCV08, 2008
+
+StarDetector::StarDetector
+--------------------------
+The Star Detector constructor
+
+.. ocv:function:: StarDetector::StarDetector()
+
+.. ocv:function:: StarDetector::StarDetector(int maxSize, int responseThreshold, int lineThresholdProjected, int lineThresholdBinarized, int suppressNonmaxSize)
+
+.. ocv:pyfunction:: cv2.StarDetector(maxSize, responseThreshold, lineThresholdProjected, lineThresholdBinarized, suppressNonmaxSize) -> <StarDetector object>
 
-The class implements a modified version of the ``CenSurE`` keypoint detector described in
-[Agrawal08].
+    :param maxSize: maximum size of the features. The following values are supported: 4, 6, 8, 11, 12, 16, 22, 23, 32, 45, 46, 64, 90, 128. In the case of a different value the result is undefined.
+    
+    :param responseThreshold: threshold for the approximated laplacian, used to eliminate weak features. The larger it is, the less features will be retrieved
+    
+    :param lineThresholdProjected: another threshold for the laplacian to eliminate edges    
+
+    :param lineThresholdBinarized: yet another threshold for the feature size to eliminate edges. The larger the 2nd threshold, the more points you get.
+
+StarDetector::operator()
+------------------------
+Finds keypoints in an image
+        
+.. ocv:function:: void StarDetector::operator()(const Mat& image, vector<KeyPoint>& keypoints)
+
+.. ocv:pyfunction:: cv2.StarDetector.detect(image) -> keypoints
+
+.. ocv:cfunction:: CvSeq* cvGetStarKeypoints( const CvArr* image, CvMemStorage* storage, CvStarDetectorParams params=cvStarDetectorParams() )
+
+.. ocv:pyoldfunction:: cv.GetStarKeypoints(image, storage, params)-> keypoints
+
+    :param image: The input 8-bit grayscale image
+    
+    :param keypoints: The output vector of keypoints
+    
+    :param storage: The memory storage used to store the keypoints (OpenCV 1.x API only)
+    
+    :param params: The algorithm parameters stored in ``CvStarDetectorParams`` (OpenCV 1.x API only)
 
-.. index:: SIFT
 
 SIFT
 ----
@@ -175,45 +179,89 @@ Class for extracting keypoints and computing descriptors using the Scale Invaria
     };
 
 
-.. index:: SURF
+
 
 SURF
 ----
 .. ocv:class:: SURF
 
-Class for extracting Speeded Up Robust Features from an image. ::
+Class for extracting Speeded Up Robust Features from an image [Bay06]_. The class is derived from ``CvSURFParams`` structure, which specifies the algorithm parameters:
 
-    class SURF : public CvSURFParams
-    {
-    public:
-        // c:function::default constructor
-        SURF();
-        // constructor that initializes all the algorithm parameters
-        SURF(double _hessianThreshold, int _nOctaves=4,
-             int _nOctaveLayers=2, bool _extended=false);
-        // returns the number of elements in each descriptor (64 or 128)
-        int descriptorSize() const;
-        // detects keypoints using fast multi-scale Hessian detector
-        void operator()(const Mat& img, const Mat& mask,
-                        vector<KeyPoint>& keypoints) const;
-        // detects keypoints and computes the SURF descriptors for them;
-        // output vector "descriptors" stores elements of descriptors and has size
-        // equal descriptorSize()*keypoints.size() as each descriptor is
-        // descriptorSize() elements of this vector.
-        void operator()(const Mat& img, const Mat& mask,
-                        vector<KeyPoint>& keypoints,
-                        vector<float>& descriptors,
-                        bool useProvidedKeypoints=false) const;
-    };
+    .. ocv:member:: int extended
+    
+        * 0 means that the basic descriptors (64 elements each) shall be computed
+        * 1 means that the extended descriptors (128 elements each) shall be computed
+       
+    .. ocv:member:: int upright
+    
+        * 0 means that detector computes orientation of each feature.
+        * 1 means that the orientation is not computed (which is much, much faster). For example, if you match images from a stereo pair, or do image stitching, the matched features likely have very similar angles, and you can speed up feature extraction by setting ``upright=1``.
+        
+    .. ocv:member:: double hessianThreshold
+    
+        Threshold for the keypoint detector. Only features, whose hessian is larger than ``hessianThreshold`` are retained by the detector. Therefore, the larger the value, the less keypoints you will get. A good default value could be from 300 to 500, depending from the image contrast.
+        
+    .. ocv:member:: int nOctaves
+    
+        The number of a gaussian pyramid octaves that the detector uses. It is set to 4 by default. If you want to get very large features, use the larger value. If you want just small features, decrease it.
+        
+    .. ocv:member:: int nOctaveLayers
+    
+        The number of images within each octave of a gaussian pyramid. It is set to 2 by default.
+
+
+.. [Bay06] Bay, H. and Tuytelaars, T. and Van Gool, L. "SURF: Speeded Up Robust Features", 9th European Conference on Computer Vision, 2006
+
+
+SURF::SURF
+----------
+The SURF extractor constructors.
+
+.. ocv:function:: SURF::SURF()
+
+.. ocv:function:: SURF::SURF(double hessianThreshold, int nOctaves=4, int nOctaveLayers=2, bool extended=false, bool upright=false)
+
+.. ocv:pyfunction:: cv2.SURF(_hessianThreshold[, _nOctaves[, _nOctaveLayers[, _extended[, _upright]]]]) -> <SURF object>
 
-The class implements the Speeded Up Robust Features descriptor 
-[Bay06].
-There is a fast multi-scale Hessian keypoint detector that can be used to find keypoints
-(default option). But the descriptors can be also computed for the user-specified keypoints.
-The algorithm can be used for object tracking and localization, image stitching, and so on. See the ``find_obj.cpp`` demo in the OpenCV samples directory.
+    :param hessianThreshold: Threshold for hessian keypoint detector used in SURF.
+    
+    :param nOctaves: Number of pyramid octaves the keypoint detector will use.
+    
+    :param nOctaveLayers: Number of octave layers within each octave.
+    
+    :param extended: Extended descriptor flag (true - use extended 128-element descriptors; false - use 64-element descriptors).
+    
+    :param upright: Up-right or rotated features flag (true - do not compute orientation of features; false - compute orientation).
+
+
+SURF::operator()
+----------------
+Detects keypoints and computes SURF descriptors for them.
+
+.. ocv:function:: void SURF::operator()(const Mat& image, const Mat& mask, vector<KeyPoint>& keypoints)
+.. ocv:function:: void SURF::operator()(const Mat& image, const Mat& mask, vector<KeyPoint>& keypoints, vector<float>& descriptors, bool useProvidedKeypoints=false)
 
+.. ocv:pyfunction:: cv2.SURF.detect(img, mask) -> keypoints
+.. ocv:pyfunction:: cv2.SURF.detect(img, mask[, useProvidedKeypoints]) -> keypoints, descriptors
+
+.. ocv:cfunction:: void cvExtractSURF( const CvArr* image, const CvArr* mask, CvSeq** keypoints, CvSeq** descriptors, CvMemStorage* storage, CvSURFParams params )
+
+.. ocv:pyoldfunction:: cv.ExtractSURF(image, mask, storage, params)-> (keypoints, descriptors)
+
+    :param image: Input 8-bit grayscale image
+    
+    :param mask: Optional input mask that marks the regions where we should detect features.
+    
+    :param keypoints: The input/output vector of keypoints
+    
+    :param descriptors: The output concatenated vectors of descriptors. Each descriptor is 64- or 128-element vector, as returned by ``SURF::descriptorSize()``. So the total size of ``descriptors`` will be ``keypoints.size()*descriptorSize()``.
+    
+    :param useProvidedKeypoints: Boolean flag. If it is true, the keypoint detector is not run. Instead, the provided vector of keypoints is used and the algorithm just computes their descriptors.
+    
+    :param storage: Memory storage for the output keypoints and descriptors in OpenCV 1.x API.
+    
+    :param params: SURF algorithm parameters in OpenCV 1.x API.
 
-.. index:: ORB
 
 ORB
 ----
@@ -269,7 +317,7 @@ Class for extracting ORB features and descriptors from an image. ::
 The class implements ORB.
 
 
-.. index:: RandomizedTree
+
 
 
 RandomizedTree
@@ -344,13 +392,13 @@ Class containing a base structure for ``RTreeClassifier``. ::
             void estimateQuantPercForPosteriors(float perc[2]);
     };
 
-.. index:: RandomizedTree::train
+
 
 RandomizedTree::train
 -------------------------
-.. ocv:function:: void train(std::vector<BaseKeypoint> const& base_set, RNG& rng, PatchGenerator& make_patch, int depth, int views, size_t reduced_num_dim, int num_quant_bits)
+Trains a randomized tree using an input set of keypoints.
 
-    Trains a randomized tree using an input set of keypoints.
+.. ocv:function:: void train(std::vector<BaseKeypoint> const& base_set, RNG& rng, PatchGenerator& make_patch, int depth, int views, size_t reduced_num_dim, int num_quant_bits)
 
 .. ocv:function:: void train(std::vector<BaseKeypoint> const& base_set, RNG& rng, PatchGenerator& make_patch, int depth, int views, size_t reduced_num_dim, int num_quant_bits)
 
@@ -368,37 +416,37 @@ RandomizedTree::train
     
     :param num_quant_bits: Number of bits used for quantization.
 
-.. index:: RandomizedTree::read
+
 
 RandomizedTree::read
 ------------------------
+Reads a pre-saved randomized tree from a file or stream.
+
 .. ocv:function:: read(const char* file_name, int num_quant_bits)
 
 .. ocv:function:: read(std::istream &is, int num_quant_bits)
 
-    Reads a pre-saved randomized tree from a file or stream.
-
     :param file_name: Name of the file that contains randomized tree data.
 
     :param is: Input stream associated with the file that contains randomized tree data.
 
     :param num_quant_bits: Number of bits used for quantization.
 
-.. index:: RandomizedTree::write
+
 
 RandomizedTree::write
 -------------------------
-.. ocv:function:: void write(const char* file_name) const
+Writes the current randomized tree to a file or stream.
 
-    Writes the current randomized tree to a file or stream.
+.. ocv:function:: void write(const char* file_name) const
 
-.. ocv:function:: void write(std::ostream \&os) const
+.. ocv:function:: void write(std::ostream &os) const
 
     :param file_name: Name of the file where randomized tree data is stored.
 
     :param is: Output stream associated with the file where randomized tree data is stored.
 
-.. index:: RandomizedTree::applyQuantization
+
 
 RandomizedTree::applyQuantization
 -------------------------------------
@@ -408,9 +456,6 @@ RandomizedTree::applyQuantization
 
     :param num_quant_bits: Number of bits used for quantization.
 
-.. index:: RTreeNode
-
-.. _RTreeNode:
 
 RTreeNode
 ---------
@@ -436,9 +481,7 @@ Class containing a base structure for ``RandomizedTree``. ::
             }
     };
 
-.. index:: RTreeClassifier
 
-.. _RTreeClassifier:
 
 RTreeClassifier
 ---------------
@@ -508,13 +551,13 @@ Class containing ``RTreeClassifier``. It represents the Calonder descriptor orig
             bool keep_floats_;
     };
 
-.. index:: RTreeClassifier::train
+
 
 RTreeClassifier::train
 --------------------------
-.. ocv:function:: void train(vector<BaseKeypoint> const& base_set, RNG& rng, int num_trees = RTreeClassifier::DEFAULT_TREES,                         int depth = DEFAULT_DEPTH, int views = DEFAULT_VIEWS, size_t reduced_num_dim = DEFAULT_REDUCED_NUM_DIM, int num_quant_bits = DEFAULT_NUM_QUANT_BITS, bool print_status = true)
+Trains a randomized tree classifier using an input set of keypoints.
 
-    Trains a randomized tree classifier using an input set of keypoints.
+.. ocv:function:: void train(vector<BaseKeypoint> const& base_set, RNG& rng, int num_trees = RTreeClassifier::DEFAULT_TREES,                         int depth = DEFAULT_DEPTH, int views = DEFAULT_VIEWS, size_t reduced_num_dim = DEFAULT_REDUCED_NUM_DIM, int num_quant_bits = DEFAULT_NUM_QUANT_BITS, bool print_status = true)
 
 .. ocv:function:: void train(vector<BaseKeypoint> const& base_set, RNG& rng, PatchGenerator& make_patch, int num_trees = RTreeClassifier::DEFAULT_TREES, int depth = DEFAULT_DEPTH, int views = DEFAULT_VIEWS, size_t reduced_num_dim = DEFAULT_REDUCED_NUM_DIM,                         int num_quant_bits = DEFAULT_NUM_QUANT_BITS, bool print_status = true)
 
@@ -536,41 +579,41 @@ RTreeClassifier::train
     
     :param print_status: Current status of training printed on the console.
 
-.. index:: RTreeClassifier::getSignature
+
 
 RTreeClassifier::getSignature
 ---------------------------------
-.. ocv:function:: void getSignature(IplImage *patch, uchar *sig)
+Returns a signature for an image patch.
 
-    Returns a signature for an image patch.
+.. ocv:function:: void getSignature(IplImage *patch, uchar *sig)
 
 .. ocv:function:: void getSignature(IplImage *patch, float *sig)
 
     :param patch: Image patch to calculate the signature for.
     :param sig: Output signature (array dimension is ``reduced_num_dim)`` .
 
-.. index:: RTreeClassifier::getSparseSignature
+
 
 RTreeClassifier::getSparseSignature
 --------------------------------------- 
+Returns a sparse signature for an image patch
 
 .. ocv:function:: void getSparseSignature(IplImage *patch, float *sig, float thresh)
 
-    Returns a signature for an image patch similarly to ``getSignature``  but uses a threshold for removing all signature elements below the threshold so that the signature is compressed.
-
     :param patch: Image patch to calculate the signature for.
     
     :param sig: Output signature (array dimension is ``reduced_num_dim)`` .
     
     :param thresh: Threshold used for compressing the signature.
 
-.. index:: RTreeClassifier::countNonZeroElements
+    Returns a signature for an image patch similarly to ``getSignature``  but uses a threshold for removing all signature elements below the threshold so that the signature is compressed.
+
 
 RTreeClassifier::countNonZeroElements
 -----------------------------------------
-.. ocv:function:: static int countNonZeroElements(float *vec, int n, double tol=1e-10)
+Returns the number of non-zero elements in an input array.
 
-    Returns the number of non-zero elements in an input array.
+.. ocv:function:: static int countNonZeroElements(float *vec, int n, double tol=1e-10)
 
     :param vec: Input vector containing float elements.
 
@@ -578,13 +621,13 @@ RTreeClassifier::countNonZeroElements
 
     :param tol: Threshold used for counting elements. All elements less than ``tol``  are considered as zero elements.
 
-.. index:: RTreeClassifier::read
+
 
 RTreeClassifier::read
 -------------------------
-.. ocv:function:: read(const char* file_name)
+Reads a pre-saved ``RTreeClassifier`` from a file or stream.
 
-    Reads a pre-saved ``RTreeClassifier`` from a file or stream.
+.. ocv:function:: read(const char* file_name)
 
 .. ocv:function:: read(std::istream& is)
 
@@ -592,13 +635,13 @@ RTreeClassifier::read
 
     :param is: Input stream associated with the file that contains randomized tree data.
 
-.. index:: RTreeClassifier::write
+
 
 RTreeClassifier::write
 --------------------------
-.. ocv:function:: void write(const char* file_name) const
+Writes the current ``RTreeClassifier`` to a file or stream.
 
-    Writes the current ``RTreeClassifier`` to a file or stream.
+.. ocv:function:: void write(const char* file_name) const
 
 .. ocv:function:: void write(std::ostream &os) const
 
@@ -606,13 +649,13 @@ RTreeClassifier::write
 
     :param os: Output stream associated with the file where randomized tree data is stored.
 
-.. index:: RTreeClassifier::setQuantization
+
 
 RTreeClassifier::setQuantization
 ------------------------------------
-.. ocv:function:: void setQuantization(int num_quant_bits)
+Applies quantization to the current randomized tree.
 
-    Applies quantization to the current randomized tree.
+.. ocv:function:: void setQuantization(int num_quant_bits)
 
     :param num_quant_bits: Number of bits used for quantization.
 
index 3a816ed..b3bf351 100644 (file)
@@ -34,42 +34,41 @@ Lixin Fan, Jutta Willamowski, Cedric Bray, 2004. ::
 
 BOWTrainer::add
 -------------------
-.. ocv:function:: void BOWTrainer::add( const Mat& descriptors )
+Adds descriptors to a training set. 
 
-    Adds descriptors to a training set. The training set is clustered using ``clustermethod`` to construct the vocabulary.
+.. ocv:function:: void BOWTrainer::add( const Mat& descriptors )
 
     :param descriptors: Descriptors to add to a training set. Each row of  the ``descriptors``  matrix is a descriptor.
 
+The training set is clustered using ``clustermethod`` to construct the vocabulary.
 
 BOWTrainer::getDescriptors
 ------------------------------
+Returns a training set of descriptors.
+
 .. ocv:function:: const vector<Mat>& BOWTrainer::getDescriptors() const
 
-    Returns a training set of descriptors.
 
-.. index:: BOWTrainer::descripotorsCount
 
 BOWTrainer::descripotorsCount
 ---------------------------------
+Returns the count of all descriptors stored in the training set.
+
 .. ocv:function:: const vector<Mat>& BOWTrainer::descripotorsCount() const
 
-    Returns the count of all descriptors stored in the training set.
 
-.. index:: BOWTrainer::cluster
 
 BOWTrainer::cluster
 -----------------------
-.. ocv:function:: Mat BOWTrainer::cluster() const
+Clusters train descriptors. 
 
-    Clusters train descriptors. The vocabulary consists of cluster centers. So, this method returns the vocabulary. In the first variant of the method, train descriptors stored in the object are clustered. In the second variant, input descriptors are clustered.
+.. ocv:function:: Mat BOWTrainer::cluster() const
 
 .. ocv:function:: Mat BOWTrainer::cluster( const Mat& descriptors ) const
 
     :param descriptors: Descriptors to cluster. Each row of  the ``descriptors``  matrix is a descriptor. Descriptors are not added to the inner train descriptor set.
 
-.. index:: BOWKMeansTrainer
-
-.. _BOWKMeansTrainer:
+The vocabulary consists of cluster centers. So, this method returns the vocabulary. In the first variant of the method, train descriptors stored in the object are clustered. In the second variant, input descriptors are clustered.
 
 BOWKMeansTrainer
 ----------------
@@ -94,7 +93,9 @@ BOWKMeansTrainer
     };
 
 BOWKMeansTrainer::BOWKMeansTrainer
-----------------
+----------------------------------
+The constructor.
+
 .. ocv:function:: BOWKMeansTrainer::BOWKMeansTrainer( int clusterCount, const TermCriteria& termcrit=TermCriteria(), int attempts=3, int flags=KMEANS_PP_CENTERS );
 
     See :ocv:func:`kmeans` function parameters.
@@ -132,43 +133,43 @@ The class declaration is the following: ::
         };
 
 
-.. index:: BOWImgDescriptorExtractor::BOWImgDescriptorExtractor
+
 
 BOWImgDescriptorExtractor::BOWImgDescriptorExtractor
 --------------------------------------------------------
-.. ocv:function:: BOWImgDescriptorExtractor::BOWImgDescriptorExtractor(           const Ptr<DescriptorExtractor>& dextractor,          const Ptr<DescriptorMatcher>& dmatcher )
+The constructor.
 
-    Constructs a class.
+.. ocv:function:: BOWImgDescriptorExtractor::BOWImgDescriptorExtractor(           const Ptr<DescriptorExtractor>& dextractor,          const Ptr<DescriptorMatcher>& dmatcher )
 
     :param dextractor: Descriptor extractor that is used to compute descriptors for an input image and its keypoints.
 
     :param dmatcher: Descriptor matcher that is used to find the nearest word of the trained vocabulary for each keypoint descriptor of the image.
 
-.. index:: BOWImgDescriptorExtractor::setVocabulary
+
 
 BOWImgDescriptorExtractor::setVocabulary
 --------------------------------------------
-.. ocv:function:: void BOWImgDescriptorExtractor::setVocabulary( const Mat& vocabulary )
+Sets a visual vocabulary.
 
-    Sets a visual vocabulary.
+.. ocv:function:: void BOWImgDescriptorExtractor::setVocabulary( const Mat& vocabulary )
 
     :param vocabulary: Vocabulary (can be trained using the inheritor of  :ocv:class:`BOWTrainer` ). Each row of the vocabulary is a visual word (cluster center).
 
-.. index:: BOWImgDescriptorExtractor::getVocabulary
+
 
 BOWImgDescriptorExtractor::getVocabulary
 --------------------------------------------
+Returns the set vocabulary.
+
 .. ocv:function:: const Mat& BOWImgDescriptorExtractor::getVocabulary() const
 
-    Returns the set vocabulary.
 
-.. index:: BOWImgDescriptorExtractor::compute
 
 BOWImgDescriptorExtractor::compute
 --------------------------------------
-.. ocv:function:: void BOWImgDescriptorExtractor::compute( const Mat& image,           vector<KeyPoint>& keypoints, Mat& imgDescriptor,           vector<vector<int> >* pointIdxsOfClusters=0,           Mat* descriptors=0 )
+Computes an image descriptor using the set visual vocabulary.
 
-    Computes an image descriptor using the set visual vocabulary.
+.. ocv:function:: void BOWImgDescriptorExtractor::compute( const Mat& image, vector<KeyPoint>& keypoints, Mat& imgDescriptor, vector<vector<int> >* pointIdxsOfClusters=0, Mat* descriptors=0 )
 
     :param image: Image, for which the descriptor is computed.
 
@@ -180,19 +181,19 @@ BOWImgDescriptorExtractor::compute
 
     :param descriptors: Descriptors of the image keypoints  that are returned if they are non-zero.
 
-.. index:: BOWImgDescriptorExtractor::descriptorSize
+
 
 BOWImgDescriptorExtractor::descriptorSize
 ---------------------------------------------
+Returns an image discriptor size if the vocabulary is set. Otherwise, it returns 0.
+
 .. ocv:function:: int BOWImgDescriptorExtractor::descriptorSize() const
 
-    Returns an image discriptor size if the vocabulary is set. Otherwise, it returns 0.
 
-.. index:: BOWImgDescriptorExtractor::descriptorType
 
 BOWImgDescriptorExtractor::descriptorType
 ---------------------------------------------
-.. ocv:function:: int BOWImgDescriptorExtractor::descriptorType() const
+Returns an image descriptor type.
 
-    Returns an image descriptor type.
+.. ocv:function:: int BOWImgDescriptorExtractor::descriptorType() const
 
index b3d13b9..d28b20c 100644 (file)
@@ -398,6 +398,8 @@ private:
     //switch (sz)
     {
       //default:
+      if( rotated_patterns_.empty() )
+          rotated_patterns_ = OrbPatterns::generateRotatedPatterns();
       pattern_data = reinterpret_cast<int*> (rotated_patterns_[angle_idx].data);
       //break;
     }
@@ -437,7 +439,7 @@ private:
 
 };
 
-std::vector<cv::Mat> ORB::OrbPatterns::rotated_patterns_ = OrbPatterns::generateRotatedPatterns();
+std::vector<cv::Mat> ORB::OrbPatterns::rotated_patterns_;
 
 //this is the definition for BIT_PATTERN
 #include "orb_pattern.hpp"
index eea023b..5007e2c 100644 (file)
@@ -144,23 +144,24 @@ Class computing stereo correspondence using the belief propagation algorithm. ::
         ...
     };
 
-The class implements Pedro F. Felzenszwalb algorithm [Pedro F. Felzenszwalb and Daniel P. Huttenlocher. *Efficient belief propagation for early vision*. International Journal of Computer Vision, 70(1), October 2006]. It can compute own data cost (using a truncated linear model) or use a user-provided data cost.
+The class implements algorithm described in [Felzenszwalb2006]_ . It can compute own data cost (using a truncated linear model) or use a user-provided data cost.
 
 .. note::
 
-       ``StereoBeliefPropagation`` requires a lot of memory for message storage:
+    ``StereoBeliefPropagation`` requires a lot of memory for message storage:
 
-       .. math::
+    .. math::
 
-               width \_ step  \cdot height  \cdot ndisp  \cdot 4  \cdot (1 + 0.25)
+        width \_ step  \cdot height  \cdot ndisp  \cdot 4  \cdot (1 + 0.25)
 
-       and for data cost storage:
+    and for data cost storage:
 
-       .. math::
+    .. math::
 
-               width\_step \cdot height \cdot ndisp \cdot (1 + 0.25 + 0.0625 +  \dotsm + \frac{1}{4^{levels}})
+        width\_step \cdot height \cdot ndisp \cdot (1 + 0.25 + 0.0625 +  \dotsm + \frac{1}{4^{levels}})
+
+    ``width_step`` is the number of bytes in a line including padding.
 
-       ``width_step`` is the number of bytes in a line including padding.
 
 .. index:: gpu::StereoBeliefPropagation::StereoBeliefPropagation
 
@@ -198,7 +199,7 @@ gpu::StereoBeliefPropagation::StereoBeliefPropagation
 
     DiscTerm =  \min (disc \_ single \_ jump  \cdot \lvert f_1-f_2  \rvert , max \_ disc \_ term)
 
-For more details, see [Pedro F. Felzenszwalb and Daniel P. Huttenlocher. *Efficient belief propagation for early vision*. International Journal of Computer Vision, 70(1), October 2006].
+For more details, see [Felzenszwalb2006]_.
 
 By default, :ocv:class:`StereoBeliefPropagation` uses floating-point arithmetics and the ``CV_32FC1`` type for messages. But it can also use fixed-point arithmetics and the ``CV_16SC1`` message type for better performance. To avoid an overflow in this case, the parameters must satisfy the following requirement:
 
@@ -300,7 +301,7 @@ Class computing stereo correspondence using the constant space belief propagatio
     };
 
 
-The class implements Q. Yang algorithm [Q. Yang, L. Wang, and N. Ahuja. *A constant-space belief propagation algorithm for stereo matching*. In CVPR, 2010]. ``StereoConstantSpaceBP`` supports both local minimum and global minimum data cost initialization algortihms. For more details, see the paper mentioned above. By default, a local algorithm is used. To enable a global algorithm, set ``use_local_init_data_cost`` to ``false``.
+The class implements algorithm described in [Yang2010]_. ``StereoConstantSpaceBP`` supports both local minimum and global minimum data cost initialization algortihms. For more details, see the paper mentioned above. By default, a local algorithm is used. To enable a global algorithm, set ``use_local_init_data_cost`` to ``false``.
 
 .. index:: gpu::StereoConstantSpaceBP::StereoConstantSpaceBP
 
@@ -342,7 +343,7 @@ gpu::StereoConstantSpaceBP::StereoConstantSpaceBP
 
     DiscTerm =  \min (disc \_ single \_ jump  \cdot \lvert f_1-f_2  \rvert , max \_ disc \_ term)
 
-For more details, see [Q. Yang, L. Wang, and N. Ahuja. *A constant-space belief propagation algorithm for stereo matching*. In CVPR, 2010].
+For more details, see [Yang2010]_.
 
 By default, ``StereoConstantSpaceBP`` uses floating-point arithmetics and the ``CV_32FC1`` type for messages. But it can also use fixed-point arithmetics and the ``CV_16SC1`` message type for better perfomance. To avoid an overflow in this case, the parameters must satisfy the following requirement:
 
@@ -410,7 +411,7 @@ Class refinining a disparity map using joint bilateral filtering. ::
     };
 
 
-The class implements Q. Yang algorithm [Q. Yang, L. Wang, and N. Ahuja. *A constant-space belief propagation algorithm for stereo matching*. In CVPR, 2010].
+The class implements [Yang2010]_ algorithm.
 
 .. index:: gpu::DisparityBilateralFilter::DisparityBilateralFilter
 
@@ -524,4 +525,8 @@ gpu::solvePnPRansac
     :param inliers: Output vector of inlier indices.   
 
 See Also :ocv:func:`solvePnPRansac`.
-  
\ No newline at end of file
+
+
+.. [Felzenszwalb2006] Pedro F. Felzenszwalb algorithm [Pedro F. Felzenszwalb and Daniel P. Huttenlocher. *Efficient belief propagation for early vision*. International Journal of Computer Vision, 70(1), October 2006
+
+.. [Yang2010] Q. Yang, L. Wang, and N. Ahuja. *A constant-space belief propagation algorithm for stereo matching*. In CVPR, 2010.
index 69ee39f..e935bea 100644 (file)
@@ -9,7 +9,7 @@ gpu::HOGDescriptor
 ------------------
 .. ocv:class:: gpu::HOGDescriptor
 
-Class providing a histogram of Oriented Gradients [Navneet Dalal and Bill Triggs. *Histogram of oriented gradients for human detection*. 2005.] descriptor and detector.
+The class implements Histogram of Oriented Gradients ([Dalal2005]_) object detector.
 ::
 
     struct CV_EXPORTS HOGDescriptor
@@ -326,3 +326,4 @@ gpu::CascadeClassifier_GPU::detectMultiScale
 
 .. seealso:: :ocv:func:`CascadeClassifier::detectMultiScale` 
 
+.. [Dalal2005] Navneet Dalal and Bill Triggs. *Histogram of oriented gradients for human detection*. 2005.
index bb85ec4..534b9bf 100644 (file)
@@ -4,7 +4,7 @@ Qt New Functions
 
 .. image:: pics/qtgui.png
 
-This figure explains new functionality implemented with Qt* GUI. The new GUI provides a statusbar, a toolbar, and a control panel. The control panel can have trackbars and buttonbars attached to it. If you can't see the control panel then press Ctrl+P or right-click on any Qt-window and select "Display properties window".
+This figure explains new functionality implemented with Qt* GUI. The new GUI provides a statusbar, a toolbar, and a control panel. The control panel can have trackbars and buttonbars attached to it. If you cannot see the control panel, press Ctrl+P or right-click any Qt window and select **Display properties window**.
 
 *
     To attach a trackbar, the window name parameter must be NULL.
@@ -14,7 +14,7 @@ This figure explains new functionality implemented with Qt* GUI. The new GUI pro
     If the last bar attached to the control panel is a buttonbar, the new button is added to the right of the last button.
     If the last bar attached to the control panel is a trackbar, or the control panel is empty, a new buttonbar is created. Then, a new button is attached to it.
 
-The following code is an example used to generate the figure. ::
+See below the example used to generate the figure: ::
 
     int main(int argc, char *argv[])
         int value = 50;
@@ -56,103 +56,104 @@ The following code is an example used to generate the figure. ::
         return 0;
     }
 
-.. index:: setWindowProperty
-
-.. _setWindowProperty:
 
 setWindowProperty
 ---------------------
+Changes parameters of a window dynamically.
+
 .. ocv:function:: void setWindowProperty(const string& name, int prop_id, double prop_value)
 
-    Changes parameters of a window dynamically.
+.. ocv:pyfunction:: cv2.setWindowProperty(winname, prop_id, prop_value) -> None
+
+.. ocv:cfunction:: void cvSetWindowProperty(const char* name, int propId, double propValue)
 
     :param name: Name of the window.
 
     :param prop_id: Window property to edit. The following operation flags are available:
         
-            * **CV_WND_PROP_FULLSCREEN** Change if the window is fullscreen ( ``CV_WINDOW_NORMAL``  or  ``CV_WINDOW_FULLSCREEN`` ).
+            * **CV_WND_PROP_FULLSCREEN**  Change if the window is fullscreen ( ``CV_WINDOW_NORMAL``  or  ``CV_WINDOW_FULLSCREEN`` ).
             
-            * **CV_WND_PROP_AUTOSIZE** Change if the window is resizable (texttt {CV\_WINDOW\_NORMAL}  or   ``CV_WINDOW_AUTOSIZE`` ).
+            * **CV_WND_PROP_AUTOSIZE**  Change if the window is resizable (``CV_WINDOW_NORMAL``  or   ``CV_WINDOW_AUTOSIZE`` ).
             
-            * **CV_WND_PROP_ASPECTRATIO** Change if the aspect ratio of the image is preserved  (texttt {CV\_WINDOW\_FREERATIO}  or  ``CV_WINDOW_KEEPRATIO`` ).
+            * **CV_WND_PROP_ASPECTRATIO**  Change if the aspect ratio of the image is preserved  ( ``CV_WINDOW_FREERATIO``  or  ``CV_WINDOW_KEEPRATIO`` ).
             
 
     :param prop_value: New value of the window property. The following operation flags are available:
         
-            * **CV_WINDOW_NORMAL** Change the window to normal size or make the window resizable.
+            * **CV_WINDOW_NORMAL**  Change the window to normal size or make the window resizable.
             
-            * **CV_WINDOW_AUTOSIZE** Constrain the size by the displayed image. The window is not resizable.
+            * **CV_WINDOW_AUTOSIZE**  Constrain the size by the displayed image. The window is not resizable.
             
-            * **CV_WINDOW_FULLSCREEN** Change the window to fullscreen.
+            * **CV_WINDOW_FULLSCREEN**  Change the window to fullscreen.
             
-            * **CV_WINDOW_FREERATIO** Make the window resizable without any ratio constraints.
+            * **CV_WINDOW_FREERATIO**  Make the window resizable without any ratio constraints.
             
-            * **CV_WINDOW_KEEPRATIO** Make the window resizable, but preserve the proportions of the displayed image.
+            * **CV_WINDOW_KEEPRATIO**  Make the window resizable, but preserve the proportions of the displayed image.
             
 
 The function ``setWindowProperty``  enables changing properties of a window.
 
-.. index:: getWindowProperty
-
 getWindowProperty
 ---------------------
+Provides parameters of a window.
+
 .. ocv:function:: void  getWindowProperty(const string& name, int prop_id)
 
-    Provides parameters of a window.
+.. ocv:pyfunction:: cv2.getWindowProperty(winname, prop_id) -> retval
+
+.. ocv:cfunction:: void cvGetWindowProperty(const char* name, int propId)
 
     :param name: Name of the window.
 
     :param prop_id: Window property to retrive. The following operation flags are available:
         
-            * **CV_WND_PROP_FULLSCREEN** Change if the window is fullscreen ( ``CV_WINDOW_NORMAL``  or  ``CV_WINDOW_FULLSCREEN`` ).
+            * **CV_WND_PROP_FULLSCREEN**  Change if the window is fullscreen ( ``CV_WINDOW_NORMAL``  or  ``CV_WINDOW_FULLSCREEN`` ).
             
-            * **CV_WND_PROP_AUTOSIZE** Change if the window is resizable (texttt {CV\_WINDOW\_NORMAL}  or   ``CV_WINDOW_AUTOSIZE`` ).
+            * **CV_WND_PROP_AUTOSIZE**  Change if the window is resizable (``CV_WINDOW_NORMAL``  or   ``CV_WINDOW_AUTOSIZE`` ).
             
-            * **CV_WND_PROP_ASPECTRATIO** Change if the aspect ratio of the image is preserved  (texttt {CV\_WINDOW\_FREERATIO}  or  ``CV_WINDOW_KEEPRATIO`` ).
+            * **CV_WND_PROP_ASPECTRATIO**  Change if the aspect ratio of the image is preserved  (``CV_WINDOW_FREERATIO``  or  ``CV_WINDOW_KEEPRATIO`` ).
             
 
 See
-:ref:`setWindowProperty` to know the meaning of the returned values.
+:ocv:func:`setWindowProperty` to know the meaning of the returned values.
 
 The function ``getWindowProperty``  returns properties of a window.
 
-.. index:: fontQt
-
-.. _fontQt:
-
 fontQt
 ----------
+Creates the font to draw a text on an image.
+
 .. ocv:function:: CvFont fontQt(const string& nameFont, int pointSize  = -1, Scalar color = Scalar::all(0), int weight = CV_FONT_NORMAL,  int style = CV_STYLE_NORMAL, int spacing = 0)
 
-    Creates the font to draw a text on an image.
+.. ocv:cfunction:: CvFont cvFontQt(const char* nameFont, int pointSize=-1, CvScalar color=cvScalarAll(0), int weight=CV_FONT_NORMAL, int style=CV_STYLE_NORMAL, int spacing=0)
 
     :param nameFont: Name of the font. The name should match the name of a system font (such as *Times*). If the font is not found, a default one is used.
 
     :param pointSize: Size of the font. If not specified, equal zero or negative, the point size of the font is set to a system-dependent default value. Generally, this is 12 points.
 
-    :param color: Color of the font in BGRA --  A = 255 is fully transparent. Use the macro ``CV _ RGB`` for simplicity.
+    :param color: Color of the font in BGRA where A = 255 is fully transparent. Use the macro ``CV _ RGB`` for simplicity.
 
     :param weight: Font weight. The following operation flags are available:
         
-            * **CV_FONT_LIGHT** Weight of 25
+            * **CV_FONT_LIGHT**  Weight of 25
             
-            * **CV_FONT_NORMAL** Weight of 50
+            * **CV_FONT_NORMAL**  Weight of 50
             
-            * **CV_FONT_DEMIBOLD** Weight of 63
+            * **CV_FONT_DEMIBOLD**  Weight of 63
             
-            * **CV_FONT_BOLD** Weight of 75
+            * **CV_FONT_BOLD**  Weight of 75
             
-            * **CV_FONT_BLACK** Weight of 87
+            * **CV_FONT_BLACK**  Weight of 87
 
             You can also specify a positive integer for better control.
 
     :param style: Font style. The following operation flags are available:
         
-            * **CV_STYLE_NORMAL** Normal font
+            * **CV_STYLE_NORMAL**  Normal font
             
-            * **CV_STYLE_ITALIC** Italic font
+            * **CV_STYLE_ITALIC**  Italic font
             
-            * **CV_STYLE_OBLIQUE** Oblique font
+            * **CV_STYLE_OBLIQUE**  Oblique font
             
     :param spacing: Spacing between characters. It can be negative or positive.
 
@@ -163,13 +164,14 @@ A basic usage of this function is the following: ::
     CvFont font = fontQt(''Times'');
     addText( img1, ``Hello World !'', Point(50,50), font);
 
-.. index:: addText
 
 addText
 -----------
+Creates the font to draw a text on an image.
+
 .. ocv:function:: void addText(const Mat& img, const string& text, Point location, CvFont *font)
 
-    Creates the font to draw a text on an image.
+.. ocv:cfunction:: void cvAddText(const CvArr* img, const char* text, CvPoint location, CvFont *font)
 
     :param img: 8-bit 3-channel image where the text should be drawn.
 
@@ -185,16 +187,17 @@ on an image
 *img*
 using a specific font
 *font*
-(see example
-:ref:`fontQt` )
+(see example :ocv:func:`fontQt` )
 
 .. index:: displayOverlay
 
 displayOverlay
 ------------------
+Displays a  text on a window image as an overlay for a specified duration.  
+
 .. ocv:function:: void displayOverlay(const string& name, const string& text, int delay)
 
-    Displays a  text on a window image as an overlay for a specified duration.  
+.. ocv:cfunction:: void cvDisplayOverlay(const char* name, const char* text, int delay)
 
     :param name: Name of the window.
 
@@ -204,13 +207,14 @@ displayOverlay
 
 The function ``displayOverlay`` displays useful information/tips on top of the window for a certain amount of time *delay*. The function does not modify the image, displayed in the window, that is, after the specified delay the original content of the window is restored.
 
-.. index:: displayStatusBar
 
 displayStatusBar
 --------------------
+Displays a text on the window statusbar during the specified period of time.
+
 .. ocv:function:: void displayStatusBar(const string& name, const string& text, int delay)
 
-    Displays a text on the window statusbar during the specified period of time.
+.. ocv:cfunction:: void cvDisplayStatusBar(const char* name, const char* text, int delayms)
 
     :param name: Name of the window.
 
@@ -222,14 +226,13 @@ The function ``displayOverlay`` displays useful information/tips on top of the w
 *delay*
 . This information is displayed on the window statubar (the window must be created with the ``CV_GUI_EXPANDED`` flags).
 
-.. index:: createOpenGLCallback
-
 createOpenGLCallback
 ------------------------
+Creates a callback function called to draw OpenGL on top the the image display by ``windowname``.
 
 .. ocv:function:: void createOpenGLCallback( const string& window_name, OpenGLCallback callbackOpenGL, void* userdata CV_DEFAULT(NULL), double angle CV_DEFAULT(-1), double zmin CV_DEFAULT(-1), double zmax CV_DEFAULT(-1)
 
-    Creates a callback function called to draw OpenGL on top the the image display by ``windowname``.
+.. ocv:cfunction:: void cvCreateOpenGLCallback( const char* windowName, CvOpenGLCallback callbackOpenGL, void* userdata=NULL, double angle=-1, double zmin=-1, double zmax=-1
 
     :param window_name: Name of the window.
 
@@ -237,13 +240,13 @@ createOpenGLCallback
 
     :param userdata: Pointer passed to the callback function.  *(Optional)*
 
-    :param angle: Parameter specifying the field of view angle, in degrees, in the y direction. Default value is 45 degrees. *(Optional)*
+    :param angle: Parameter specifying the field of view angle, in degrees, in the y direction. Default value is 45 degrees. *(Optional)*
 
     :param zmin: Parameter specifying the distance from the viewer to the near clipping plane (always positive). Default value is 0.01. *(Optional)*
 
     :param zmax: Parameter specifying the distance from the viewer to the far clipping plane (always positive). Default value is 1000. *(Optional)*
 
-The function ``createOpenGLCallback`` can be used to draw 3D data on the window.  An example of callback could be: ::
+The function ``createOpenGLCallback`` can be used to draw 3D data on the window. See the example of callback use below: ::
 
     void on_opengl(void* param)
     {
@@ -274,42 +277,40 @@ The function ``createOpenGLCallback`` can be used to draw 3D data on the window.
         }
     }
 
-.. index:: saveWindowParameters
 
 saveWindowParameters
 ------------------------
+Saves parameters of the specified window.
 
 .. ocv:function:: void saveWindowParameters(const string& name)
 
-    Saves parameters of the window ``windowname`` .
+.. ocv:cfunction:: void cvSaveWindowParameters(const char* name)
 
     :param name: Name of the window.
 
 The function ``saveWindowParameters`` saves size, location, flags,  trackbars value, zoom and panning location of the window
 ``window_name`` .
 
-.. index:: loadWindowParameters
-
 loadWindowParameters
 ------------------------
+Loads parameters of the specified window.
 
 .. ocv:function:: void loadWindowParameters(const string& name)
 
-    Loads parameters of the window ``windowname`` .
+.. ocv:cfunction:: void cvLoadWindowParameters(const char* name)
 
     :param name: Name of the window.
 
 The function ``loadWindowParameters`` loads size, location, flags, trackbars value, zoom and panning location of the window
 ``window_name`` .
 
-.. index:: createButton
-
 createButton
 ----------------
+Attaches a button to the control panel.
 
 .. ocv:function:: createButton( const string& button_name CV_DEFAULT(NULL),ButtonCallback on_change CV_DEFAULT(NULL), void* userdata CV_DEFAULT(NULL), int button_type CV_DEFAULT(CV_PUSH_BUTTON), int initial_button_state CV_DEFAULT(0))
 
-    Attaches a button to the control panel.
+.. ocv:cfunction:: cvCreateButton( const char* buttonName=NULL, CvButtonCallback onChange=NULL, void* userdata=NULL, int buttonType=CV_PUSH_BUTTON, int initialButtonState=0
 
     :param  button_name: Name of the button.
 
@@ -317,20 +318,20 @@ createButton
 
     :param userdata: Pointer passed to the callback function.
 
-    :param button_type: The optional type of the button.
+    :param button_type: Optional type of the button.
 
-        * **CV_PUSH_BUTTON** Push button
+        * **CV_PUSH_BUTTON**  Push button
 
-        * **CV_CHECKBOX** Checkbox button
+        * **CV_CHECKBOX**  Checkbox button
 
-        * **CV_RADIOBOX** Radiobox button. The radiobox on the same buttonbar (same line) are exclusive, that is only one can be selected at a time.
+        * **CV_RADIOBOX**  Radiobox button. The radiobox on the same buttonbar (same line) are exclusive, that is only one can be selected at a time.
 
     :param initial_button_state: Default state of the button. Use for checkbox and radiobox. Its value could be 0 or 1.  *(Optional)*
 
 The function ``createButton`` attaches a button to the control panel. Each button is added to a buttonbar to the right of the last button.
 A new buttonbar is created if nothing was attached to the control panel before, or if the last element attached to the control panel was a trackbar.
 
-Here are various examples of the ``createButton`` function call: ::
+See below various examples of the ``createButton`` function call: ::
 
     createButton(NULL,callbackButton);//create a push button "button 0", that will call callbackButton.
     createButton("button2",callbackButton,NULL,CV_CHECKBOX,0);
index 390ecbb..1af534a 100644 (file)
@@ -3,35 +3,31 @@ Reading and Writing Images and Video
 
 .. highlight:: cpp
 
-.. index:: imdecode
-
-.. _imdecode:
-
 imdecode
 ------------
+Reads an image from a buffer in memory.
+
 .. ocv:function:: Mat imdecode( InputArray buf,  int flags )
 
-    Reads an image from a buffer in memory.
+.. ocv:pyfunction:: cv2.imdecode(buf, flags) -> retval
 
     :param buf: Input array of vector of bytes.
 
-    :param flags: The same flags as in  :ref:`imread` .
+    :param flags: The same flags as in  :ocv:func:`imread` .
     
-The function reads an image from the specified buffer in memory.
+The function reads an image from the specified buffer in the memory.
 If the buffer is too short or contains invalid data, the empty matrix is returned.
 
 See
-:ref:`imread` for the list of supported formats and flags description.
-
-.. index:: imencode
-
-.. _imencode:
+:ocv:func:`imread` for the list of supported formats and flags description.
 
 imencode
 ------------
+Encodes an image into a memory buffer.
+
 .. ocv:function:: bool imencode( const string& ext, InputArray img, vector<uchar>& buf, const vector<int>& params=vector<int>())
 
-    Encode an image into a memory buffer.
+.. ocv:pyfunction:: cv2.imencode(ext, img, buf[, params]) -> retval
 
     :param ext: File extension that defines the output format.
 
@@ -39,31 +35,37 @@ imencode
 
     :param buf: Output buffer resized to fit the compressed image.
 
-    :param params: Format-specific parameters. See  :ref:`imwrite` .
+    :param params: Format-specific parameters. See  :ocv:func:`imwrite` .
 
 The function compresses the image and stores it in the memory buffer that is resized to fit the result.
 See
-:ref:`imwrite` for the list of supported formats and flags description.
-
-.. index:: imread
-
-.. _imread:
+:ocv:func:`imwrite` for the list of supported formats and flags description.
 
 imread
 ----------
+Loads an image from a file.
+
 .. ocv:function:: Mat imread( const string& filename, int flags=1 )
 
-    Loads an image from a file.
+.. ocv:pyfunction:: cv2.imread(filename[, flags]) -> retval
+
+.. ocv:cfunction:: IplImage* cvLoadImage( const char* filename, int flags=CV_LOAD_IMAGE_COLOR )
+
+.. ocv:cfunction:: CvMat* cvLoadImageM( const char* filename, int flags=CV_LOAD_IMAGE_COLOR )
+
+.. ocv:pyoldfunction:: cv.LoadImage(filename, flags=CV_LOAD_IMAGE_COLOR)->None
+
+.. ocv:pyoldfunction:: cv.LoadImageM(filename, flags=CV_LOAD_IMAGE_COLOR)->None
 
     :param filename: Name of file to be loaded.
 
     :param flags: Flags specifying the color type of a loaded image:
 
-        * **>0**  a 3-channel color image
+        * **>0**  Return a 3-channel color image
 
-        * **=0** a grayscale image
+        * **=0**  Return a grayscale image
 
-        * **<0** The image is loaded as is. Note that in the current implementation the alpha channel, if any, is stripped from the output image. For example, a 4-channel RGBA image is loaded as RGB if  :math:`flags\ge0` .
+        * **<0**  Return the loaded image as is. Note that in the current implementation the alpha channel, if any, is stripped from the output image. For example, a 4-channel RGBA image is loaded as RGB if  :math:`flags\ge0` .
 
 The function ``imread`` loads an image from the specified file and returns it. If the image cannot be read (because of missing file, improper permissions, unsupported or invalid format), the function returns an empty matrix ( ``Mat::data==NULL`` ). Currently, the following file formats are supported:
 
@@ -81,27 +83,29 @@ The function ``imread`` loads an image from the specified file and returns it. I
 
  * TIFF files - ``*.tiff, *.tif`` (see the *Notes* section)
 
-**Notes**:
+.. note::
 
-* The function determines the type of an image by the content, not by the file extension.
+    * The function determines the type of an image by the content, not by the file extension.
 
-* On Microsoft Windows* OS and MacOSX*, the codecs shipped with an OpenCV image (libjpeg, libpng, libtiff, and libjasper) are used by default. So, OpenCV can always read JPEGs, PNGs, and TIFFs. On MacOSX, there is also an option to use native MacOSX image readers. But beware that currently these native image loaders give images with different pixel values because of the color management embedded into MacOSX.
+    * On Microsoft Windows* OS and MacOSX*, the codecs shipped with an OpenCV image (libjpeg, libpng, libtiff, and libjasper) are used by default. So, OpenCV can always read JPEGs, PNGs, and TIFFs. On MacOSX, there is also an option to use native MacOSX image readers. But beware that currently these native image loaders give images with different pixel values because of the color management embedded into MacOSX.
 
-* On Linux*, BSD flavors and other Unix-like open-source operating systems, OpenCV looks for codecs supplied with an OS image. Install the relevant packages (do not forget the development files, for example, "libjpeg-dev", in Debian* and Ubuntu*) to get the codec support or turn on the ``OPENCV_BUILD_3RDPARTY_LIBS`` flag in CMake.
-
-.. index:: imwrite
-
-.. _imwrite:
+    * On Linux*, BSD flavors and other Unix-like open-source operating systems, OpenCV looks for codecs supplied with an OS image. Install the relevant packages (do not forget the development files, for example, "libjpeg-dev", in Debian* and Ubuntu*) to get the codec support or turn on the ``OPENCV_BUILD_3RDPARTY_LIBS`` flag in CMake.
 
 imwrite
 -----------
-.. ocv:function:: bool imwrite( const string& filename, InputArray img, const vector<int>& params=vector<int>())
+Saves an image to a specified file.
+
+.. ocv:function:: bool imwrite( const string& filename, InputArray image, const vector<int>& params=vector<int>())
+
+.. ocv:pyfunction:: cv2.imwrite(filename, image[, params]) -> retval
 
-    Saves an image to a specified file.
+.. ocv:cfunction:: int cvSaveImage( const char* filename, const CvArr* image )
+
+.. ocv:pyoldfunction:: cv.SaveImage(filename, image)-> None
 
     :param filename: Name of the file.
 
-    :param img: Image to be saved.
+    :param image: Image to be saved.
 
     :param params: Format-specific save parameters encoded as pairs  ``paramId_1, paramValue_1, paramId_2, paramValue_2, ...`` . The following parameters are currently supported:
 
@@ -112,70 +116,18 @@ imwrite
         *  For PPM, PGM, or PBM, it can be a binary format flag ( ``CV_IMWRITE_PXM_BINARY`` ), 0 or 1. Default value is 1.
 
 The function ``imwrite`` saves the image to the specified file. The image format is chosen based on the ``filename`` extension (see
-:ref:`imread` for the list of extensions). Only 8-bit (or 16-bit in case of PNG, JPEG 2000, and TIFF) single-channel or 3-channel (with 'BGR' channel order) images can be saved using this function. If the format, depth or channel order is different, use
-:ref:`Mat::convertTo` , and
-:ref:`cvtColor` to convert it before saving. Or, use the universal XML I/O functions to save the image to XML or YAML format.
-
-.. index:: VideoCapture
-
-.. _VideoCapture:
+:ocv:func:`imread` for the list of extensions). Only 8-bit (or 16-bit in case of PNG, JPEG 2000, and TIFF) single-channel or 3-channel (with 'BGR' channel order) images can be saved using this function. If the format, depth or channel order is different, use
+:ocv:func:`Mat::convertTo` , and
+:ocv:func:`cvtColor` to convert it before saving. Or, use the universal XML I/O functions to save the image to XML or YAML format.
 
 VideoCapture
 ------------
-.. c:type:: VideoCapture
-
-Class for video capturing from video files or cameras ::
-
-    class VideoCapture
-    {
-    public:
-        // the default constructor
-        VideoCapture();
-        // the constructor that opens video file
-        VideoCapture(const string& filename);
-        // the constructor that starts streaming from the camera
-        VideoCapture(int device);
-
-        // the destructor
-        virtual ~VideoCapture();
-
-        // opens the specified video file
-        virtual bool open(const string& filename);
+.. ocv:class:: VideoCapture
 
-        // starts streaming from the specified camera by its id
-        virtual bool open(int device);
+Class for video capturing from video files or cameras.
+The class provides C++ API for capturing video from cameras or for reading video files. Here is how the class can be used: ::
 
-        // returns true if the file was open successfully or if the camera
-        // has been initialized succesfully
-        virtual bool isOpened() const;
-
-        // closes the camera stream or the video file
-        // (automatically called by the destructor)
-        virtual void release();
-
-        // grab the next frame or a set of frames from a multi-head camera;
-        // returns false if there are no more frames
-        virtual bool grab();
-        // reads the frame from the specified video stream
-        // (non-zero channel is only valid for multi-head camera live streams)
-        virtual bool retrieve(Mat& image, int channel=0);
-        // equivalent to grab() + retrieve(image, 0);
-        virtual VideoCapture& operator >> (Mat& image);
-
-        // sets the specified property propId to the specified value
-        virtual bool set(int propId, double value);
-        // retrieves value of the specified property
-        virtual double get(int propId);
-
-    protected:
-        ...
-    };
-
-
-The class provides C++ video capturing API. Here is how the class can be used: ::
-
-    #include "cv.h"
-    #include "highgui.h"
+    #include "opencv2/opencv.hpp"
 
     using namespace cv;
 
@@ -202,35 +154,146 @@ The class provides C++ video capturing API. Here is how the class can be used: :
     }
 
 
-.. index:: VideoCapture::VideoCapture
+.. note:: In C API the black-box structure ``CvCapture`` is used instead of ``VideoCapture``.
 
-.. _VideoCapture::VideoCapture:
 
 VideoCapture::VideoCapture
 ------------------------------
+VideoCapture constructors.
+
 .. ocv:function:: VideoCapture::VideoCapture()
 
 .. ocv:function:: VideoCapture::VideoCapture(const string& filename)
 
 .. ocv:function:: VideoCapture::VideoCapture(int device)
 
-VideoCapture constructors.
+.. ocv:pyfunction:: cv2.VideoCapture() -> <VideoCapture object>
+.. ocv:pyfunction:: cv2.VideoCapture(filename) -> <VideoCapture object>
+.. ocv:pyfunction:: cv2.VideoCapture(device) -> <VideoCapture object>
+
+.. ocv:cfunction:: CvCapture* cvCaptureFromCAM( int device )
+.. ocv:pyoldfunction:: cv.CaptureFromCAM(device) -> CvCapture
+.. ocv:cfunction:: CvCapture* cvCaptureFromFile( const char* filename )
+.. ocv:pyoldfunction:: cv.CaptureFromFile(filename) -> CvCapture
+
+    :param filename: name of the opened video file
+
+    :param device: id of the opened video capturing device (i.e. a camera index). If there is a single camera connected, just pass 0.
+
+.. note:: In C API, when you finished working with video, release ``CvCapture`` structure with ``cvReleaseCapture()``, or use ``Ptr<CvCapture>`` that calls ``cvReleaseCapture()`` automatically in the destructor.
+
+
+VideoCapture::open
+---------------------
+Open video file or a capturing device for video capturing
+
+.. ocv:function:: bool VideoCapture::open(const string& filename)
+.. ocv:function:: bool VideoCapture::open(int device)
+
+.. ocv:pyfunction:: cv2.VideoCapture.open(filename) -> successFlag
+.. ocv:pyfunction:: cv2.VideoCapture.open(device) -> successFlag
 
     :param filename: name of the opened video file
 
     :param device: id of the opened video capturing device (i.e. a camera index).
 
-.. index:: VideoCapture::get
+The methods first call :ocv:cfunc:`VideoCapture::release` to close the already opened file or camera. 
+
+
+VideoCapture::isOpened
+----------------------
+Returns true if video capturing has been initialized already.
+
+.. ocv:function:: bool VideoCapture::isOpened()
+
+.. ocv:pyfunction:: cv2.VideoCapture.isOpened() -> flag
+
+If the previous call to ``VideoCapture`` constructor or ``VideoCapture::open`` succeeded, the method returns true.
+
+VideoCapture::release
+---------------------
+Closes video file or capturing device.
+
+.. ocv:function:: void VideoCapture::release()
+
+.. ocv:pyfunction:: cv2.VideoCapture.release()
+
+.. ocv:cfunction: void cvReleaseCapture(CvCapture** capture)
+
+The methods are automatically called by subsequent :ocv:func:`VideoCapture::open` and by ``VideoCapture`` destructor.
+
+The C function also deallocates memory and clears ``*capture`` pointer.
+
+
+VideoCapture::grab
+---------------------
+Grabs the next frame from video file or capturing device.
+
+.. ocv:function:: bool VideoCapture::grab()
+
+.. ocv:pyfunction:: cv2.VideoCapture.grab() -> successFlag
+
+.. ocv:cfunction: int cvGrabFrame(CvCapture* capture)
+
+.. ocv:pyoldfunction:: cv.GrabFrame(capture) -> int
+
+The methods/functions grab the next frame from video file or camera and return true (non-zero) in the case of success.
+
+The primary use of the function is in multi-camera environments, especially when the cameras do not have hardware synchronization. That is, you call ``VideoCapture::grab()`` for each camera and after that call the slower method ``VideoCapture::retrieve()`` to decode and get frame from each camera. This way the overhead on demosaicing or motion jpeg decompression etc. is eliminated and the retrieved frames from different cameras will be closer in time.
+
+Also, when a connected camera is multi-head (for example, a stereo camera or a Kinect device), the correct way of retrieving data from it is to call `VideoCapture::grab` first and then call :ocv:func:`VideoCapture::retrieve` one or more times with different values of the ``channel`` parameter. See https://code.ros.org/svn/opencv/trunk/opencv/samples/cpp/kinect_maps.cpp
+
+
+VideoCapture::retrieve
+----------------------
+Decodes and returns the grabbed video frame.
+
+.. ocv:function:: bool VideoCapture::retrieve(Mat& image, int channel=0)
+
+.. ocv:pyfunction:: cv2.VideoCapture.retrieve([image[, channel]]) -> successFlag, image
+
+.. ocv:cfunction: IplImage* cvRetrieveFrame(CvCapture* capture)
+
+.. ocv:pyoldfunction:: cv.RetrieveFrame(capture) -> iplimage
+
+The methods/functions decode and retruen the just grabbed frame. If no frames has been grabbed (camera has been disconnected, or there are no more frames in video file), the methods return false and the functions return NULL pointer.
+
+.. note:: OpenCV 1.x functions ``cvRetrieveFrame`` and ``cv.RetrieveFrame`` return image stored inside the video capturing structure. It is not allowed to modify or release the image! You can copy the frame using :ocv:cfunc:`cvCloneImage` and then do whatever you want with the copy.
+
+
+VideoCapture::read
+----------------------
+Grabs, decodes and returns the next video frame.
+
+.. ocv:function:: VideoCapture& VideoCapture::operator >> (Mat& image)
+.. ocv:function:: bool VideoCapture::read(Mat& image)
+
+.. ocv:pyfunction:: cv2.VideoCapture.read([image]) -> successFlag, image
+
+.. ocv:cfunction: IplImage* cvQueryFrame(CvCapture* capture)
+
+.. ocv:pyoldfunction:: cv.QueryFrame(capture) -> iplimage
+
+The methods/functions combine :ocv:func:`VideoCapture::grab` and :ocv:func:`VideoCapture::retrieve` in one call. This is the most convenient method for reading video files or capturing data from decode and retruen the just grabbed frame. If no frames has been grabbed (camera has been disconnected, or there are no more frames in video file), the methods return false and the functions return NULL pointer.
+
+.. note:: OpenCV 1.x functions ``cvRetrieveFrame`` and ``cv.RetrieveFrame`` return image stored inside the video capturing structure. It is not allowed to modify or release the image! You can copy the frame using :ocv:cfunc:`cvCloneImage` and then do whatever you want with the copy.
 
-.. _VideoCapture::get:
 
 VideoCapture::get
 ---------------------
-.. ocv:function:: double VideoCapture::get(int property_id)
+Returns the specified ``VideoCapture`` property 
+
+.. ocv:function:: double VideoCapture::get(int propId)
+
+.. ocv:pyfunction:: cv2.VideoCapture.get(propId) -> retval
+
+.. ocv:cfunction:: double cvGetCaptureProperty( CvCapture* capture, int propId )
+.. ocv:pyoldfunction:: cv.GetCaptureProperty(capture, propId)->double
 
-    :param property_id: Property identifier. It can be one of the following:
 
-        * **CV_CAP_PROP_POS_MSEC** Film current position in milliseconds or video capture timestamp.
+    :param propId: Property identifier. It can be one of the following:
+
+        * **CV_CAP_PROP_POS_MSEC** Current position of the video file in milliseconds or video capture timestamp.
 
         * **CV_CAP_PROP_POS_FRAMES** 0-based index of the frame to be decoded/captured next.
 
@@ -264,26 +327,27 @@ VideoCapture::get
 
         * **CV_CAP_PROP_CONVERT_RGB** Boolean flags indicating whether images should be converted to RGB.
 
-        * **CV_CAP_PROP_WHITE_BALANCE** Currently unsupported
+        * **CV_CAP_PROP_WHITE_BALANCE** Currently not supported
 
-        * **CV_CAP_PROP_RECTIFICATION** TOWRITE (note: only supported by DC1394 v 2.x backend currently)
+        * **CV_CAP_PROP_RECTIFICATION** Rectification flag for stereo cameras (note: only supported by DC1394 v 2.x backend currently)
 
 
 **Note**: When querying a property that is not supported by the backend used by the ``VideoCapture`` class, value 0 is returned.
 
-.. index:: VideoCapture::set
-
-.. _VideoCapture::set:
-
 VideoCapture::set
 ---------------------
-.. ocv:function:: bool VideoCapture::set(int property_id, double value)
+Sets a property in the ``VideoCapture``.
 
-    Sets a property in the VideoCapture backend.
+.. ocv:function:: bool VideoCapture::set(int propertyId, double value)
 
-    :param property_id: Property identifier. It can be one of the following:
+.. ocv:pyfunction:: cv2.VideoCapture.set(propId, value) -> retval
 
-        * **CV_CAP_PROP_POS_MSEC** Film current position in milliseconds or video capture timestamp.
+.. ocv:cfunction:: int cvSetCaptureProperty( CvCapture* capture, int propId, double value )
+.. ocv:pyoldfunction:: cv.SetCaptureProperty(capture, propId, value)->None
+
+    :param propId: Property identifier. It can be one of the following:
+
+        * **CV_CAP_PROP_POS_MSEC** Current position of the video file in milliseconds.
 
         * **CV_CAP_PROP_POS_FRAMES** 0-based index of the frame to be decoded/captured next.
 
@@ -319,53 +383,94 @@ VideoCapture::set
 
         * **CV_CAP_PROP_WHITE_BALANCE** Currently unsupported
 
-        * **CV_CAP_PROP_RECTIFICATION** TOWRITE (note: only supported by DC1394 v 2.x backend currently)
+        * **CV_CAP_PROP_RECTIFICATION** Rectification flag for stereo cameras (note: only supported by DC1394 v 2.x backend currently)
 
     :param value: Value of the property.
 
 
 
-.. index:: VideoWriter
-
-.. _VideoWriter:
-
 VideoWriter
 -----------
-.. c:type:: VideoWriter
+.. ocv:class:: VideoWriter
 
-Video writer class ::
+Video writer class.
 
-    class VideoWriter
-    {
-    public:
-        // default constructor
-        VideoWriter();
-        // constructor that calls open
-        VideoWriter(const string& filename, int fourcc,
-                    double fps, Size frameSize, bool isColor=true);
-
-        // the destructor
-        virtual ~VideoWriter();
-
-        // opens the file and initializes the video writer.
-        // filename - the output file name.
-        // fourcc - the codec
-        // fps - the number of frames per second
-        // frameSize - the video frame size
-        // isColor - specifies whether the video stream is color or grayscale
-        virtual bool open(const string& filename, int fourcc,
-                          double fps, Size frameSize, bool isColor=true);
-
-        // returns true if the writer has been initialized successfully
-        virtual bool isOpened() const;
-
-        // writes the next video frame to the stream
-        virtual VideoWriter& operator << (const Mat& image);
-
-    protected:
-        ...
-    };
-
-For more detailed description see http://opencv.willowgarage.com/wiki/documentation/cpp/highgui/VideoWriter
-..
+
+
+VideoWriter::VideoWriter
+------------------------
+VideoWriter constructors
+
+.. ocv:function:: VideoWriter::VideoWriter()
+.. ocv:function:: VideoWriter::VideoWriter(const string& filename, int fourcc, double fps, Size frameSize, bool isColor=true)
+
+.. ocv:pyfunction:: cv2.VideoWriter([filename, fourcc, fps, frameSize[, isColor]]) -> <VideoWriter object>
+
+.. ocv:cfunction:: CvVideoWriter* cvCreateVideoWriter( const char* filename, int fourcc, double fps, CvSize frameSize, int isColor=1 )
+.. ocv:pyoldfunction:: cv.CreateVideoWriter(filename, fourcc, fps, frameSize, isColor) -> CvVideoWriter
+
+.. ocv:pyfunction:: cv2.VideoWriter.isOpened() -> retval
+.. ocv:pyfunction:: cv2.VideoWriter.open(filename, fourcc, fps, frameSize[, isColor]) -> retval
+.. ocv:pyfunction:: cv2.VideoWriter.write(image) -> None
+
+    :param filename: Name of the output video file. 
+
+    :param fourcc: 4-character code of codec used to compress the frames. For example, ``CV_FOURCC('P','I','M,'1')``  is a MPEG-1 codec, ``CV_FOURCC('M','J','P','G')``  is a motion-jpeg codec etc.
+
+    :param fps: Framerate of the created video stream. 
+
+    :param frameSize: Size of the  video frames. 
+
+    :param isColor: If it is not zero, the encoder will expect and encode color frames, otherwise it will work with grayscale frames (the flag is currently supported on Windows only). 
+
+The constructors/functions initialize video writers. On Linux FFMPEG is used to write videos; on Windows FFMPEG or VFW is used; on MacOSX QTKit is used.
+
+
+
+ReleaseVideoWriter
+------------------
+Releases the AVI writer.
+
+.. ocv:cfunction:: void cvReleaseVideoWriter( CvVideoWriter** writer )
+
+The function should be called after you finished using ``CvVideoWriter`` opened with :ocv:cfunc:`CreateVideoWriter`.
+
+
+VideoWriter::open
+-----------------
+Initializes or reinitializes video writer.
+
+.. ocv:function: bool VideoWriter::open(const string& filename, int fourcc, double fps, Size frameSize, bool isColor=true)
+
+.. ocv:pyfunction:: cv2.VideoWriter.open(filename, fourcc, fps, frameSize[, isColor]) -> retval
+
+The method opens video writer. Parameters are the same as in the constructor :ocv:func:`VideoWriter::VideoWriter`.
+
+
+VideoWriter::isOpened
+---------------------
+Returns true if video writer has been successfully initialized.
+
+.. ocv:function: bool VideoWriter::isOpened()
+
+.. ocv:pyfunction:: cv2.VideoWriter.isOpened() -> retval
+
+
+VideoWriter::write
+------------------
+Writes the next video frame
+
+.. ocv:function:: VideoWriter& VideoWriter::operator << (const Mat& image)
+.. ocv:function:: void VideoWriter::write(const Mat& image)
+
+.. ocv:pyfunction:: cv2.VideoWriter.write(image) -> None
+
+.. ocv:cfunction:: int cvWriteFrame( CvVideoWriter* writer, const IplImage* image )
+.. ocv:pyoldfunction:: cv.WriteFrame(writer, image)->int
+
+    :param writer: Video writer structure (OpenCV 1.x API) 
+    
+    :param image: The written frame 
+    
+The functions/methods write the specified image to video file. It must have the same size as has been specified when opening the video writer.
 
index 257226a..1fc919f 100644 (file)
@@ -3,15 +3,14 @@ User Interface
 
 .. highlight:: cpp
 
-.. index:: createTrackbar
-
-.. _createTrackbar:
-
 createTrackbar
 ------------------
+Creates a trackbar and attaches it to the specified window.
+
 .. ocv:function:: int createTrackbar( const string& trackbarname, const string& winname, int* value, int count, TrackbarCallback onChange=0, void* userdata=0)
 
-    Creates a trackbar and attaches it to the specified window.
+.. ocv:cfunction:: int cvCreateTrackbar( const char* trackbarName, const char* windowName, int* value, int count, CvTrackbarCallback onChange )
+.. ocv:pyoldfunction:: cv.CreateTrackbar(trackbarName, windowName, value, count, onChange) -> None
 
     :param trackbarname: Name of the created trackbar.
 
@@ -25,29 +24,24 @@ createTrackbar
 
     :param userdata: User data that is passed as is to the callback. It can be used to handle trackbar events without using global variables.
 
-The function ``createTrackbar`` creates a trackbar (a.k.a. slider or range control) with the specified name and range, assigns a variable ``value`` to be syncronized with the trackbar position and specifies the callback function ``onChange`` to be called on the trackbar position change. The created trackbar is displayed on top of the given window.
-
+The function ``createTrackbar`` creates a trackbar (a slider or range control) with the specified name and range, assigns a variable ``value`` to be a position syncronized with the trackbar and specifies the callback function ``onChange`` to be called on the trackbar position change. The created trackbar is displayed in the specified window ``winname``.
 
-**[Qt Backend Only]**
-Qt-specific details:
+.. note::
+    
+    **[Qt Backend Only]** ``winname`` can be empty (or NULL) if the trackbar should be attached to the control panel.
 
-    * **winname** Name of the window that will be used as a parent for created trackbar. It can be NULL if the trackbar should be attached to the control panel.
-
-The created trackbar is displayed at the bottom of the given window if
-*winname*
-is correctly provided, or displayed on the control panel if
-*winname*
-is NULL.
-
-Clicking the label of each trackbar enables editing the trackbar values manually for a more accurate control of it.
-
-.. index:: getTrackbarPos
+Clicking the label of each trackbar enables editing the trackbar values manually.
 
 getTrackbarPos
 ------------------
+Returns the trackbar position.
+
 .. ocv:function:: int getTrackbarPos( const string& trackbarname, const string& winname )
 
-    Returns the trackbar position.
+.. ocv:pyfunction:: cv2.getTrackbarPos(trackbarname, winname) -> retval
+
+.. ocv:cfunction:: int cvGetTrackbarPos( const char* trackbarName, const char* windowName )
+.. ocv:pyoldfunction:: cv.GetTrackbarPos(trackbarName, windowName)-> None
 
     :param trackbarname: Name of the trackbar.
 
@@ -55,21 +49,20 @@ getTrackbarPos
 
 The function returns the current position of the specified trackbar.
 
+.. note::
 
-**[Qt Backend Only]**
-Qt-specific details:
-
-    * **winname** Name of the window that is the parent of the trackbar. It can be NULL if the trackbar is attached to the control panel.
-
-.. index:: imshow
-
-.. _imshow:
+    **[Qt Backend Only]** ``winname`` can be empty (or NULL) if the trackbar is attached to the control panel.
 
 imshow
 ----------
+Displays an image in the specified window.
+
 .. ocv:function:: void imshow( const string& winname, InputArray image )
 
-    Displays an image in the specified window.
+.. ocv:pyfunction:: cv2.imshow(winname, image) -> None
+
+.. ocv:cfunction:: void cvShowImage( const char* winname, const CvArr* image )
+.. ocv:pyoldfunction:: cv.ShowImage(winname, image)-> None
 
     :param winname: Name of the window.
 
@@ -77,95 +70,135 @@ imshow
 
 The function ``imshow`` displays an image in the specified window. If the window was created with the ``CV_WINDOW_AUTOSIZE`` flag, the image is shown with its original size. Otherwise, the image is scaled to fit the window. The function may scale the image, depending on its depth:
 
-*
-    If the image is 8-bit unsigned, it is displayed as is.
-
-*
-    If the image is 16-bit unsigned or 32-bit integer, the pixels are divided by 256. That is, the value range [0,255*256] is mapped to [0,255].
+    * If the image is 8-bit unsigned, it is displayed as is.
 
-*
-    If the image is 32-bit floating-point, the pixel values are multiplied by 255. That is, the value range [0,1] is mapped to [0,255].
+    * If the image is 16-bit unsigned or 32-bit integer, the pixels are divided by 256. That is, the value range [0,255*256] is mapped to [0,255].
 
-.. index:: namedWindow
+    * If the image is 32-bit floating-point, the pixel values are multiplied by 255. That is, the value range [0,1] is mapped to [0,255].
 
-.. _namedWindow:
 
 namedWindow
 ---------------
+Creates a window.
+
 .. ocv:function:: void namedWindow( const string& winname, int flags )
 
-    Creates a window.
+.. ocv:pyfunction:: cv2.namedWindow(winname[, flags]) -> None
+
+.. ocv:cfunction:: int cvNamedWindow( const char* name, int flags )
+.. ocv:pyoldfunction:: cv.NamedWindow(name, flags=CV_WINDOW_AUTOSIZE)-> None
 
     :param name: Name of the window in the window caption that may be used as a window identifier.
 
-    :param flags: Flags of the window. Currently the only supported flag is  ``CV_WINDOW_AUTOSIZE`` . If this is set, the window size is automatically adjusted to fit the displayed image (see  :ref:`imshow` ), and you cannot change the window size manually.
+    :param flags: Flags of the window. Currently the only supported flag is  ``CV_WINDOW_AUTOSIZE`` . If this is set, the window size is automatically adjusted to fit the displayed image (see  :ocv:func:`imshow` ), and you cannot change the window size manually.
 
 The function ``namedWindow`` creates a window that can be used as a placeholder for images and trackbars. Created windows are referred to by their names.
 
 If a window with the same name already exists, the function does nothing.
 
-You can call :cpp:func:`destroyWindow` or :cpp:func:`destroyAllWindows` to close the window and de-allocate any associated memory usage. For a simple program, you do not really have to call these functions because all the resources and windows of the application are closed automatically by the operating system upon exit.
-
-
-**[Qt Backend Only]**
-Qt-specific details:
-
-    * **flags** Flags of the window. Currently the supported flags are:
-
-            * **CV_WINDOW_NORMAL or CV_WINDOW_AUTOSIZE:**   ``CV_WINDOW_NORMAL``  enables you to resize the window, whereas   ``CV_WINDOW_AUTOSIZE``  adjusts automatically the window size to fit the displayed image (see  :ref:`imshow` ), and you cannot change the window size manually.
-
-            * **CV_WINDOW_FREERATIO or CV_WINDOW_KEEPRATIO:** ``CV_WINDOW_FREERATIO``  adjusts the image with no respect to its ratio, whereas  ``CV_WINDOW_KEEPRATIO``  keeps the image ratio.
+You can call :ocv:func:`destroyWindow` or :ocv:func:`destroyAllWindows` to close the window and de-allocate any associated memory usage. For a simple program, you do not really have to call these functions because all the resources and windows of the application are closed automatically by the operating system upon exit.
 
-            * **CV_GUI_NORMAL or CV_GUI_EXPANDED:**   ``CV_GUI_NORMAL``  is the old way to draw the window without statusbar and toolbar, whereas  ``CV_GUI_EXPANDED``  is a new enhanced GUI.
+.. note::
 
-        This parameter is optional. The default flags set for a new window are  ``CV_WINDOW_AUTOSIZE`` , ``CV_WINDOW_KEEPRATIO`` , and  ``CV_GUI_EXPANDED`` .
+    Qt backend supports additional flags:
 
-        However, if you want to modify the flags, you can combine them using the OR operator, that is:
+        * **CV_WINDOW_NORMAL or CV_WINDOW_AUTOSIZE:**   ``CV_WINDOW_NORMAL``  enables you to resize the window, whereas   ``CV_WINDOW_AUTOSIZE``  adjusts automatically the window size to fit the displayed image (see  :ocv:func:`imshow` ), and you cannot change the window size manually.
 
-        ::
+        * **CV_WINDOW_FREERATIO or CV_WINDOW_KEEPRATIO:** ``CV_WINDOW_FREERATIO``  adjusts the image with no respect to its ratio, whereas  ``CV_WINDOW_KEEPRATIO``  keeps the image ratio.
 
-            namedWindow( "myWindow", CV_WINDOW_NORMAL | CV_GUI_NORMAL );
+        * **CV_GUI_NORMAL or CV_GUI_EXPANDED:**   ``CV_GUI_NORMAL``  is the old way to draw the window without statusbar and toolbar, whereas  ``CV_GUI_EXPANDED``  is a new enhanced GUI.
 
-        ..
+    By default, ``flags == CV_WINDOW_AUTOSIZE | CV_WINDOW_KEEPRATIO | CV_GUI_EXPANDED``
 
 
-.. index:: destroyWindow
-
-.. _destroyWindow:
-
 destroyWindow
 -------------
-.. ocv:function:: void destroyWindow( const string &winname )
+Destroys a window.
 
-    Destroys a window.
+.. ocv:function:: void destroyWindow( const string &winname )
             
+.. ocv:pyfunction:: cv2.destroyWindow(winname) -> None
+
+.. ocv:cfunction:: void cvDestroyWindow( const char* name )
+.. ocv:pyoldfunction:: cv.DestroyWindow(name)-> None
+
     :param winname: Name of the window to be destroyed. 
                                            
 The function ``destroyWindow`` destroys the window with the given name.
 
 
-.. index:: destroyAllWindows
-
-.. _destroyAllWindows:
-
 destroyAllWindows
 -----------------
+Destroys all of the HighGUI windows.
+
 .. ocv:function:: void destroyAllWindows()
 
-    Destroys all of the HighGUI windows.
+.. ocv:pyfunction:: cv2.destroyAllWindows() -> None
+
+.. ocv:cfunction:: void cvDestroyAllWindows()
+.. ocv:pyoldfunction:: cv.DestroyAllWindows()-> None
 
 The function ``destroyAllWindows`` destroys all of the opened HighGUI windows.
 
 
-.. index:: setTrackbarPos
+MoveWindow
+----------
+Moves window to the specified position
+
+.. ocv:cfunction:: void cvMoveWindow( const char* name, int x, int y )
+.. ocv:pyoldfunction:: cv.MoveWindow(name, x, y)-> None
+
+    :param name: Window name
+    
+    :param x: The new x-coordinate of the window
+    
+    :param y: The new y-coordinate of the window
+
+
+ResizeWindow
+----------
+Resizes window to the specified size
+
+.. ocv:cfunction:: void cvResizeWindow( const char* name, int width, int height )
+.. ocv:pyoldfunction:: cv.ResizeWindow(name, width, height)-> None
+
+    :param name: Window name
+
+    :param width: The new window width
+
+    :param height: The new window height
+
+.. note::
+
+   * The specified window size is for the image area. Toolbars are not counted.
+   
+   * Only windows created without CV_WINDOW_AUTOSIZE flag can be resized.
+
+
+SetMouseCallback
+----------------
+Sets mouse handler for the specified window
+
+.. ocv:cfunction:: void cvSetMouseCallback( const char* name, CvMouseCallback onMouse, void* param=NULL )
+.. ocv:pyoldfunction:: cv.SetMouseCallback(name, onMouse, param) -> None
+
+    :param name: Window name
+    
+    :param onMouse: Mouse callback. See OpenCV samples, such as  https://code.ros.org/svn/opencv/trunk/opencv/samples/cpp/ffilldemo.cpp, on how to specify and use the callback.
+    
+    :param param: The optional parameter passed to the callback.
 
-.. _setTrackbarPos:
 
 setTrackbarPos
 ------------------
+Sets the trackbar position.
+
 .. ocv:function:: void setTrackbarPos( const string& trackbarname, const string& winname, int pos )
 
-    Sets the trackbar position.
+.. ocv:pyfunction:: cv2.setTrackbarPos(trackbarname, winname, pos) -> None
+
+.. ocv:cfunction:: void cvSetTrackbarPos( const char* trackbarName, const char* windowName, int pos )
+.. ocv:pyoldfunction:: cv.SetTrackbarPos(trackbarName, windowName, pos)-> None
 
     :param trackbarname: Name of the trackbar.
 
@@ -175,30 +208,30 @@ setTrackbarPos
 
 The function sets the position of the specified trackbar in the specified window.
 
-
-**[Qt Backend Only]**
-Qt-specific details:
-
-    * **winname** Name of the window that is the parent of the trackbar. It can be NULL if the trackbar is attached to the control panel.
-
-.. index:: waitKey
-
-.. _waitKey:
+.. note::
+    
+    **[Qt Backend Only]** ``winname`` can be empty (or NULL) if the trackbar is attached to the control panel.
 
 waitKey
 -----------
+Waits for a pressed key.
+
 .. ocv:function:: int waitKey(int delay=0)
 
-    Waits for a pressed key.
+.. ocv:pyfunction:: cv2.waitKey([, delay]) -> retval
+
+.. ocv:cfunction:: int cvWaitKey( int delay=0 )
+.. ocv:pyoldfunction:: cv.WaitKey(delay=0)-> int
 
     :param delay: Delay in milliseconds. 0 is the special value that means "forever".
 
 The function ``waitKey`` waits for a key event infinitely (when
 :math:`\texttt{delay}\leq 0` ) or for ``delay`` milliseconds, when it is positive. Since the OS has a minimum time between switching threads, the function will not wait exactly ``delay`` ms, it will wait at least ``delay`` ms, depending on what else is running on your computer at that time. It returns the code of the pressed key or -1 if no key was pressed before the specified time had elapsed.
 
-**Notes:**
-
-* This function is the only method in HighGUI that can fetch and handle events, so it needs to be called periodically for normal event processing unless HighGUI is used within an environment that takes care of event processing.
+.. note::
 
-* The function only works if there is at least one HighGUI window created and the window is active. If there are several HighGUI windows, any of them can be active.
+    This function is the only method in HighGUI that can fetch and handle events, so it needs to be called periodically for normal event processing unless HighGUI is used within an environment that takes care of event processing.
 
+.. note::
+    
+    The function only works if there is at least one HighGUI window created and the window is active. If there are several HighGUI windows, any of them can be active.
index c010b5e..d1ef5b9 100644 (file)
@@ -3,13 +3,18 @@ Feature Detection
 
 .. highlight:: cpp
 
-.. index:: Canny
+
 
 Canny
 ---------
+Finds edges in an image using the [Canny86]_ algorithm.
+
 .. ocv:function:: void Canny( InputArray image, OutputArray edges, double threshold1, double threshold2, int apertureSize=3, bool L2gradient=false )
 
-    Finds edges in an image using the Canny algorithm.
+.. ocv:pyfunction:: cv2.Canny(image, threshold1, threshold2[, edges[, apertureSize[, L2gradient]]]) -> edges
+
+.. ocv:cfunction:: void cvCanny( const CvArr* image, CvArr* edges, double threshold1, double threshold2, int apertureSize=3 )
+.. ocv:pyoldfunction:: cv.Canny(image, edges, threshold1, threshold2, apertureSize=3)-> None
 
     :param image: Single-channel 8-bit input image.
 
@@ -26,14 +31,18 @@ Canny
 The function finds edges in the input image ``image`` and marks them in the output map ``edges`` using the Canny algorithm. The smallest value between ``threshold1`` and ``threshold2`` is used for edge linking. The largest value is used to find initial segments of strong edges. See
 http://en.wikipedia.org/wiki/Canny_edge_detector
 
-.. index:: cornerEigenValsAndVecs
+
 
 cornerEigenValsAndVecs
 ----------------------
+Calculates eigenvalues and eigenvectors of image blocks for corner detection.
 
 .. ocv:function:: void cornerEigenValsAndVecs( InputArray src, OutputArray dst, int blockSize, int apertureSize, int borderType=BORDER_DEFAULT )
 
-    Calculates eigenvalues and eigenvectors of image blocks for corner detection.
+.. ocv:pyfunction:: cv2.cornerEigenValsAndVecs(src, blockSize, ksize[, dst[, borderType]]) -> dst
+
+.. ocv:cfunction:: void cvCornerEigenValsAndVecs( const CvArr* image, CvArr* eigenvv, int blockSize, int apertureSize=3 )
+.. ocv:pyoldfunction:: cv.CornerEigenValsAndVecs(image, eigenvv, blockSize, apertureSize=3)-> None
 
     :param src: Input single-channel 8-bit or floating-point image.
 
@@ -73,14 +82,18 @@ See Also:
 :ocv:func:`cornerHarris`,
 :ocv:func:`preCornerDetect`
 
-.. index:: cornerHarris
+
 
 cornerHarris
 ------------
+Harris edge detector.
 
 .. ocv:function:: void cornerHarris( InputArray src, OutputArray dst, int blockSize, int apertureSize, double k, int borderType=BORDER_DEFAULT )
 
-    Harris edge detector.
+.. ocv:pyfunction:: cv2.cornerHarris(src, blockSize, ksize, k[, dst[, borderType]]) -> dst
+
+.. ocv:cfunction:: void cvCornerHarris( const CvArr* image, CvArr* harrisDst, int blockSize, int apertureSize=3, double k=0.04 )
+.. ocv:pyoldfunction:: cv.CornerHarris(image, harrisDst, blockSize, apertureSize=3, k=0.04)-> None
 
     :param src: Input single-channel 8-bit or floating-point image.
 
@@ -108,14 +121,18 @@ The function runs the Harris edge detector on the image. Similarly to
 
 Corners in the image can be found as the local maxima of this response map.
 
-.. index:: cornerMinEigenVal
+
 
 cornerMinEigenVal
 -----------------
+Calculates the minimal eigenvalue of gradient matrices for corner detection.
 
 .. ocv:function:: void cornerMinEigenVal( InputArray src, OutputArray dst, int blockSize, int apertureSize=3, int borderType=BORDER_DEFAULT )
 
-    Calculates the minimal eigenvalue of gradient matrices for corner detection.
+.. ocv:pyfunction:: cv2.cornerMinEigenVal(src, blockSize[, dst[, ksize[, borderType]]]) -> dst
+
+.. ocv:cfunction:: void cvCornerMinEigenVal( const CvArr* image, CvArr* eigenval, int blockSize, int apertureSize=3 )
+.. ocv:pyoldfunction:: cv.CornerMinEigenVal(image, eigenval, blockSize, apertureSize=3)-> None
 
     :param src: Input single-channel 8-bit or floating-point image.
 
@@ -132,13 +149,19 @@ The function is similar to
 :math:`\min(\lambda_1, \lambda_2)` in terms of the formulae in the
 :ocv:func:`cornerEigenValsAndVecs` description.
 
-.. index:: cornerSubPix
+
 
 cornerSubPix
 ----------------
+Refines the corner locations.
+
 .. ocv:function:: void cornerSubPix( InputArray image, InputOutputArray corners, Size winSize, Size zeroZone, TermCriteria criteria )
 
-    Refines the corner locations.
+.. ocv:pyfunction:: cv2.cornerSubPix(image, corners, winSize, zeroZone, criteria) -> None
+
+.. ocv:cfunction:: void cvFindCornerSubPix( const CvArr* image, CvPoint2D32f* corners, int count, CvSize winSize, CvSize zeroZone, CvTermCriteria criteria )
+
+.. ocv:pyoldfunction:: cv.FindCornerSubPix(image, corners, winSize, zeroZone, criteria)-> corners
 
     :param image: Input image.
 
@@ -188,14 +211,18 @@ where the gradients are summed within a neighborhood ("search window") of
 The algorithm sets the center of the neighborhood window at this new center
 :math:`q` and then iterates until the center stays within a set threshold.
 
-.. index:: goodFeaturesToTrack
+
 
 goodFeaturesToTrack
 -------------------
+Determines strong corners on an image.
 
 .. ocv:function:: void goodFeaturesToTrack( InputArray image, OutputArray corners, int maxCorners, double qualityLevel, double minDistance, InputArray mask=noArray(), int blockSize=3, bool useHarrisDetector=false, double k=0.04 )
 
-    Determines strong corners on an image.
+.. ocv:pyfunction:: cv2.goodFeaturesToTrack(image, maxCorners, qualityLevel, minDistance[, corners[, mask[, blockSize[, useHarrisDetector[, k]]]]]) -> corners
+
+.. ocv:cfunction:: void cvGoodFeaturesToTrack( const CvArr* image CvArr* eigImage, CvArr* tempImage CvPoint2D32f* corners int* cornerCount double qualityLevel double minDistance const CvArr* mask=NULL int blockSize=3 int useHarris=0 double k=0.04 )
+.. ocv:pyoldfunction:: cv.GoodFeaturesToTrack(image, eigImage, tempImage, cornerCount, qualityLevel, minDistance, mask=None, blockSize=3, useHarris=0, k=0.04)-> corners
 
     :param image: Input 8-bit or floating-point 32-bit, single-channel image.
 
@@ -215,7 +242,7 @@ goodFeaturesToTrack
     
     :param k: Free parameter of the Harris detector.
 
-The function finds the most prominent corners in the image or in the specified image region, as described in [Shi94]:
+The function finds the most prominent corners in the image or in the specified image region, as described in [Shi94]_:
 
 #.
     Function calculates the corner quality measure at every source image pixel using the
@@ -246,20 +273,21 @@ See Also: :ocv:func:`cornerMinEigenVal`,
 :ocv:func:`PlanarObjectDetector`, 
 :ocv:func:`OneWayDescriptor`
 
-.. index:: HoughCircles
+
 
 HoughCircles
 ------------
+Finds circles in a grayscale image using the Hough transform.
 
 .. ocv:function:: void HoughCircles( InputArray image, OutputArray circles, int method, double dp, double minDist, double param1=100, double param2=100, int minRadius=0, int maxRadius=0 )
 
-    Finds circles in a grayscale image using the Hough transform.
+.. ocv:pyfunction:: cv2.HoughCircles(image, method, dp, minDist[, circles[, param1[, param2[, minRadius[, maxRadius]]]]]) -> circles
 
     :param image: 8-bit, single-channel, grayscale input image.
 
     :param circles: Output vector of found circles. Each vector is encoded as a 3-element floating-point vector  :math:`(x, y, radius)` .
     
-    :param method: The detection method to use. Currently, the only implemented method is  ``CV_HOUGH_GRADIENT`` , which is basically  *21HT* , described in  [Yuen90].
+    :param method: The detection method to use. Currently, the only implemented method is  ``CV_HOUGH_GRADIENT`` , which is basically  *21HT* , described in  [Yuen90]_.
 
     :param dp: Inverse ratio of the accumulator resolution to the image resolution. For example, if  ``dp=1`` , the accumulator has the same resolution as the input image. If  ``dp=2`` , the accumulator has half as big width and height.
 
@@ -312,14 +340,19 @@ See Also:
 :ocv:func:`fitEllipse`,
 :ocv:func:`minEnclosingCircle`
 
-.. index:: HoughLines
+
 
 HoughLines
 ----------
+Finds lines in a binary image using the standard Hough transform.
 
 .. ocv:function:: void HoughLines( InputArray image, OutputArray lines, double rho, double theta, int threshold, double srn=0, double stn=0 )
 
-    Finds lines in a binary image using the standard Hough transform.
+.. ocv:pyfunction:: cv2.HoughLines(image, rho, theta, threshold[, lines[, srn[, stn]]]) -> lines
+
+.. ocv:cfunction:: CvSeq* cvHoughLines2( CvArr* image, void* storage, int method, double rho, double theta, int threshold, double param1=0, double param2=0 )
+
+.. ocv:pyoldfunction:: cv.HoughLines2(image, storage, method, rho, theta, threshold, param1=0, param2=0)-> lines
 
     :param image: 8-bit, single-channel binary source image. The image may be modified by the function.
 
@@ -333,20 +366,44 @@ HoughLines
 
     :param srn: For the multi-scale Hough transform, it is a divisor for the distance resolution  ``rho`` . The coarse accumulator distance resolution is  ``rho``  and the accurate accumulator resolution is  ``rho/srn`` . If both  ``srn=0``  and  ``stn=0`` , the classical Hough transform is used. Otherwise, both these parameters should be positive.
 
-    :param stn: For the multi-scale Hough transform, it is a divisor for the distance resolution  ``theta`` .
+    :param stn: For the multi-scale Hough transform, it is a divisor for the distance resolution  ``theta``.
+    
+    :param method: The Hough transform variant, one of the following: 
+         
+            * **CV_HOUGH_STANDARD** classical or standard Hough transform. Every line is represented by two floating-point numbers  :math:`(\rho, \theta)` , where  :math:`\rho`  is a distance between (0,0) point and the line, and  :math:`\theta`  is the angle between x-axis and the normal to the line. Thus, the matrix must be (the created sequence will be) of  ``CV_32FC2``  type 
+            
+               
+            * **CV_HOUGH_PROBABILISTIC** probabilistic Hough transform (more efficient in case if picture contains a few long linear segments). It returns line segments rather than the whole line. Each segment is represented by starting and ending points, and the matrix must be (the created sequence will be) of  ``CV_32SC4``  type 
+             
+            * **CV_HOUGH_MULTI_SCALE** multi-scale variant of the classical Hough transform. The lines are encoded the same way as  ``CV_HOUGH_STANDARD``
     
-The function implements the standard or standard multi-scale Hough transform algorithm for line detection. See
-:ocv:func:`HoughLinesP` for the code example. Also see http://homepages.inf.ed.ac.uk/rbf/HIPR2/hough.htm for a good explanation of Hough transform.
 
+    :param param1: The first method-dependent parameter:
+    
+        *  For the classical Hough transform it is not used (0).
+    
+        *  For the probabilistic Hough transform it is the minimum line length.
+    
+        *  For the multi-scale Hough transform it is ``srn``. 
 
-.. index:: HoughLinesP
+    :param param2: The second method-dependent parameter: 
+    
+        *  For the classical Hough transform it is not used (0).
+    
+        *  For the probabilistic Hough transform it is the maximum gap between line segments lying on the same line to treat them as a single line segment (that is, to join them).
+    
+        *  For the multi-scale Hough transform it is ``stn``.
+
+The function implements the standard or standard multi-scale Hough transform algorithm for line detection.  See http://homepages.inf.ed.ac.uk/rbf/HIPR2/hough.htm for a good explanation of Hough transform.
+See also the example in :ocv:func:`HoughLinesP` description.
 
 HoughLinesP
 -----------
+Finds line segments in a binary image using the probabilistic Hough transform.
 
 .. ocv:function:: void HoughLinesP( InputArray image, OutputArray lines, double rho, double theta, int threshold, double minLineLength=0, double maxLineGap=0 )
 
-    Finds line segments in a binary image using the probabilistic Hough transform.
+.. ocv:pyfunction:: cv2.HoughLinesP(image, rho, theta, threshold[, lines[, minLineLength[, maxLineGap]]]) -> lines
 
     :param image: 8-bit, single-channel binary source image. The image may be modified by the function.
 
@@ -363,8 +420,7 @@ HoughLinesP
     :param maxLineGap: Maximum allowed gap between points on the same line to link them.
 
 The function implements the probabilistic Hough transform algorithm for line detection, described in
-Matas00
-. See the line detection example below: ::
+[Matas00]_. See the line detection example below: ::
 
     /* This is a standalone program. Pass an image name as a first parameter
     of the program.  Switch between standard and probabilistic Hough transform
@@ -427,14 +483,18 @@ And this is the output of the above program in case of the probabilistic Hough t
 
 .. image:: pics/houghp.png
 
-.. index:: preCornerDetect
+
 
 preCornerDetect
 ---------------
+Calculates a feature map for corner detection.
 
 .. ocv:function:: void preCornerDetect( InputArray src, OutputArray dst, int apertureSize, int borderType=BORDER_DEFAULT )
 
-    Calculates a feature map for corner detection.
+.. ocv:pyfunction:: cv2.preCornerDetect(src, ksize[, dst[, borderType]]) -> dst
+
+.. ocv:cfunction:: void cvPreCornerDetect( const CvArr* image, CvArr* corners, int apertureSize=3 )
+.. ocv:pyoldfunction:: cv.PreCornerDetect(image, corners, apertureSize=3)-> None
 
     :param src: Source single-channel 8-bit of floating-point image.
 
@@ -463,4 +523,10 @@ The corners can be found as local maximums of the functions, as shown below: ::
     dilate(corners, dilated_corners, Mat(), 1);
     Mat corner_mask = corners == dilated_corners;
 
+.. [Canny86] J. Canny. A Computational Approach to Edge Detection, IEEE Trans. on Pattern Analysis and Machine Intelligence, 8(6), pp. 679-698 (1986).
+
+.. [Matas00] Matas, J. and Galambos, C. and Kittler, J.V., “Robust Detection of Lines Using the Progressive Probabilistic Hough Transform”. CVIU 78 1, pp 119-137 (2000)
+
+.. [Shi94] J. Shi and C. Tomasi. Good features to track. Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition, pages 593-600, June 1994.
 
+.. [Yuen90] Yuen, H. K. and Princen, J. and Illingworth, J. and Kittler, J., “Comparative study of Hough transform methods for circle finding”. Image Vision Comput. 8 1, pp 71–77 (1990)
\ No newline at end of file
index 1b83917..6f0e69a 100644 (file)
@@ -1,10 +1,8 @@
-.. _ImageFiltering:
-
-.. highlight:: cpp
-
 Image Filtering
 ===============
 
+.. highlight:: cpp
+
 Functions and classes described in this section are used to perform various linear or non-linear filtering operations on 2D images (represented as
 :ocv:func:`Mat`'s). It means that for each pixel location
 :math:`(x,y)` in the source image (normally, rectangular), its neighborhood is considered and used to compute the response. In case of a linear filter, it is a weighted sum of pixel values. In case of morphological operations, it is the minimum or maximum values, and so on. The computed response is stored in the destination image at the same location
@@ -14,13 +12,13 @@ Another common feature of the functions and classes described in this section is
 :math:`3 \times 3` filter, then, when processing the left-most pixels in each row, you need pixels to the left of them, that is, outside of the image. You can let these pixels be the same as the left-most image pixels ("replicated border" extrapolation method), or assume that all the non-existing pixels are zeros ("contant border" extrapolation method), and so on.
 OpenCV enables you to specify the extrapolation method. For details, see the function  :ocv:func:`borderInterpolate`  and discussion of the  ``borderType``  parameter in various functions below.
 
-.. index:: BaseColumnFilter
+
 
 BaseColumnFilter
 ----------------
 .. ocv:class:: BaseColumnFilter
 
-Base class for filters with single-column kernels ::
+Base class for filters with single-column kernels. ::
 
     class BaseColumnFilter
     {
@@ -55,7 +53,7 @@ where
 :math:`F` is a filtering function but, as it is represented as a class, it can produce any side effects, memorize previously processed data, and so on. The class only defines an interface and is not used directly. Instead, there are several functions in OpenCV (and you can add more) that return pointers to the derived classes that implement specific filtering operations. Those pointers are then passed to the
 :ocv:func:`FilterEngine` constructor. While the filtering operation interface uses the ``uchar`` type, a particular implementation is not limited to 8-bit data.
 
-See Also:
+.. seealso::
 :ocv:func:`BaseRowFilter`,
 :ocv:func:`BaseFilter`,
 :ocv:func:`FilterEngine`,
@@ -63,13 +61,13 @@ See Also:
 :ocv:func:`getLinearColumnFilter`,
 :ocv:func:`getMorphologyColumnFilter`
 
-.. index:: BaseFilter
+
 
 BaseFilter
 ----------
 .. ocv:class:: BaseFilter
 
-Base class for 2D image filters ::
+Base class for 2D image filters. ::
 
     class BaseFilter
     {
@@ -105,20 +103,20 @@ where
 :math:`F` is a filtering function. The class only defines an interface and is not used directly. Instead, there are several functions in OpenCV (and you can add more) that return pointers to the derived classes that implement specific filtering operations. Those pointers are then passed to the
 :ocv:func:`FilterEngine` constructor. While the filtering operation interface uses the ``uchar`` type, a particular implementation is not limited to 8-bit data.
 
-See Also:
+.. seealso::
 :ocv:func:`BaseColumnFilter`,
 :ocv:func:`BaseRowFilter`,
 :ocv:func:`FilterEngine`,
 :ocv:func:`getLinearFilter`,
 :ocv:func:`getMorphologyFilter`
 
-.. index:: BaseRowFilter
+
 
 BaseRowFilter
 -------------
 .. ocv:class:: BaseRowFilter
 
-Base class for filters with single-row kernels ::
+Base class for filters with single-row kernels. ::
 
     class BaseRowFilter
     {
@@ -146,7 +144,7 @@ where
 :math:`F` is a filtering function. The class only defines an interface and is not used directly. Instead, there are several functions in OpenCV (and you can add more) that return pointers to the derived classes that implement specific filtering operations. Those pointers are then passed to the
 :ocv:func:`FilterEngine` constructor. While the filtering operation interface uses the ``uchar`` type, a particular implementation is not limited to 8-bit data.
 
-See Also:
+.. seealso::
 :ocv:func:`BaseColumnFilter`,
 :ocv:func:`Filter`,
 :ocv:func:`FilterEngine`,
@@ -154,13 +152,13 @@ See Also:
 :ocv:func:`getMorphologyRowFilter`,
 :ocv:func:`getRowSumFilter`
 
-.. index:: FilterEngine
+
 
 FilterEngine
 ------------
 .. ocv:class:: FilterEngine
 
-Generic image filtering class ::
+Generic image filtering class. ::
 
     class FilterEngine
     {
@@ -290,7 +288,7 @@ This class makes it easier to combine filtering operations with other operations
     }
 
 
-If you do not need that much control of the filtering process, you can simply use the ``FilterEngine::apply`` method. Here is how the method is actually implemented: ::
+If you do not need that much control of the filtering process, you can simply use the ``FilterEngine::apply`` method. The method is implemented as follows: ::
 
     void FilterEngine::apply(const Mat& src, Mat& dst,
         const Rect& srcRoi, Point dstOfs, bool isolated)
@@ -322,7 +320,7 @@ If you do not need that much control of the filtering process, you can simply us
     }
 
 
-Unlike the earlier versions of OpenCV, now the filtering operations fully support the notion of image ROI, that is, pixels outside of the ROI but inside the image can be used in the filtering operations. For example, you can take a ROI of a single pixel and filter it. This will be a filter response at that particular pixel. However, it is possible to emulate the old behavior by passing ``isolated=false`` to ``FilterEngine::start`` or ``FilterEngine::apply`` . You can pass the ROI explicitly to ``FilterEngine::apply``  or construct new matrix headers: ::
+Unlike the earlier versions of OpenCV, now the filtering operations fully support the notion of image ROI, that is, pixels outside of the ROI but inside the image can be used in the filtering operations. For example, you can take a ROI of a single pixel and filter it. This will be a filter response at that particular pixel. However, it is possible to emulate the old behavior by passing ``isolated=false`` to ``FilterEngine::start`` or ``FilterEngine::apply`` . You can pass the ROI explicitly to ``FilterEngine::apply``  or construct new matrix headers: ::
 
     // compute dI/dx derivative at src(x,y)
 
@@ -357,7 +355,7 @@ Explore the data types. As it was mentioned in the
 *
     In case of non-separable filtering, ``bufType``     must be the same as ``srcType``     . The source data is copied to the temporary buffer, if needed, and then just passed to ``FilterEngine::filter2D``     . That is, the input type for ``filter2D``     is ``srcType``     (= ``bufType``     ) and the output type is ``dstType``     .
 
-See Also:
+.. seealso::
 :ocv:func:`BaseColumnFilter`,
 :ocv:func:`BaseFilter`,
 :ocv:func:`BaseRowFilter`,
@@ -368,13 +366,15 @@ See Also:
 :ocv:func:`createMorphologyFilter`,
 :ocv:func:`createSeparableLinearFilter`
 
-.. index:: bilateralFilter
+
 
 bilateralFilter
 -------------------
+Applies the bilateral filter to an image.
+
 .. ocv:function:: void bilateralFilter( InputArray src, OutputArray dst, int d, double sigmaColor, double sigmaSpace, int borderType=BORDER_DEFAULT )
 
-    Applies the bilateral filter to an image.
+.. ocv:pyfunction:: cv2.bilateralFilter(src, d, sigmaColor, sigmaSpace[, dst[, borderType]]) -> dst
 
     :param src: Source 8-bit or floating-point, 1-channel or 3-channel image.
 
@@ -388,22 +388,24 @@ bilateralFilter
 
 The function applies bilateral filtering to the input image, as described in
 http://www.dai.ed.ac.uk/CVonline/LOCAL\_COPIES/MANDUCHI1/Bilateral\_Filtering.html
-``bilateralFilter`` can do a very good job of reducing unwanted noise while keep edges fairly sharp. However it is very slow compared to most filters.
+``bilateralFilter`` can reduce unwanted noise very well while keeping edges fairly sharp. However, it is very slow compared to most filters.
 
-*Sigma values*: For simplicity, you can set the 2 sigma values to be the same. If they are small (< 10) then the filter will not have much effect, whereas if they are large (> 150) then they will have a very strong effect, making the image look "cartoonish".
+*Sigma values*: For simplicity, you can set the 2 sigma values to be the same. If they are small (< 10), the filter will not have much effect, whereas if they are large (> 150), they will have a very strong effect, making the image look "cartoonish".
 
 *Filter size*: Large filters (d > 5) are very slow, so it is recommended to use d=5 for real-time applications, and perhaps d=9 for offline applications that need heavy noise filtering.
 
-This filter doesn't work inplace.
+This filter does not work inplace.
+
 
 
-.. index:: blur
 
 blur
 --------
+Smoothes an image using the normalized box filter.
+
 .. ocv:function:: void blur( InputArray src, OutputArray dst, Size ksize, Point anchor=Point(-1,-1),           int borderType=BORDER_DEFAULT )
 
-    Smoothes an image using the normalized box filter.
+.. ocv:pyfunction:: cv2.blur(src, ksize[, dst[, anchor[, borderType]]]) -> dst
 
     :param src: Source image.
 
@@ -423,19 +425,21 @@ The function smoothes an image using the kernel:
 
 The call ``blur(src, dst, ksize, anchor, borderType)`` is equivalent to ``boxFilter(src, dst, src.type(), anchor, true, borderType)`` .
 
-See Also:
+.. seealso::
 :ocv:func:`boxFilter`,
 :ocv:func:`bilateralFilter`,
 :ocv:func:`GaussianBlur`,
 :ocv:func:`medianBlur` 
 
-.. index:: borderInterpolate
+
 
 borderInterpolate
 ---------------------
+Computes the source location of an extrapolated pixel.
+
 .. ocv:function:: int borderInterpolate( int p, int len, int borderType )
 
-    Computes the source location of an extrapolated pixel.
+.. ocv:pyfunction:: cv2.borderInterpolate(p, len, borderType) -> retval
 
     :param p: 0-based coordinate of the extrapolated pixel along one of the axes, likely <0 or >= ``len`` .
     
@@ -443,7 +447,7 @@ borderInterpolate
 
     :param borderType: Border type, one of the  ``BORDER_*`` , except for  ``BORDER_TRANSPARENT``  and  ``BORDER_ISOLATED`` . When  ``borderType==BORDER_CONSTANT`` , the function always returns -1, regardless of  ``p``  and  ``len`` .
 
-The function computes and returns the coordinate of the donor pixel, corresponding to the specified extrapolated pixel when using the specified extrapolation border mode. For example, if we use ``BORDER_WRAP`` mode in the horizontal direction, ``BORDER_REFLECT_101`` in the vertical direction and want to compute value of the "virtual" pixel ``Point(-5, 100)`` in a floating-point image ``img`` , it will be ::
+The function computes and returns the coordinate of a donor pixel corresponding to the specified extrapolated pixel when using the specified extrapolation border mode. For example, if you use ``BORDER_WRAP`` mode in the horizontal direction, ``BORDER_REFLECT_101`` in the vertical direction and want to compute value of the "virtual" pixel ``Point(-5, 100)`` in a floating-point image ``img`` , it looks like: ::
 
     float val = img.at<float>(borderInterpolate(100, img.rows, BORDER_REFLECT_101),
                               borderInterpolate(-5, img.cols, BORDER_WRAP));
@@ -453,17 +457,19 @@ Normally, the function is not called directly. It is used inside
 :ocv:func:`FilterEngine` and
 :ocv:func:`copyMakeBorder` to compute tables for quick extrapolation.
 
-See Also:
+.. seealso::
 :ocv:func:`FilterEngine`,
 :ocv:func:`copyMakeBorder`
 
-.. index:: boxFilter
+
 
 boxFilter
 -------------
+Smoothes an image using the box filter.
+
 .. ocv:function:: void boxFilter( InputArray src, OutputArray dst, int ddepth, Size ksize, Point anchor=Point(-1,-1), bool normalize=true, int borderType=BORDER_DEFAULT )
 
-    Smoothes an image using the box filter.
+.. ocv:pyfunction:: cv2.boxFilter(src, ddepth, ksize[, dst[, anchor[, normalize[, borderType]]]]) -> dst
 
     :param src: Source image.
 
@@ -493,38 +499,42 @@ Unnormalized box filter is useful for computing various integral characteristics
 and so on). If you need to compute pixel sums over variable-size windows, use
 :ocv:func:`integral` .
 
-See Also:
+.. seealso::
 :ocv:func:`boxFilter`,
 :ocv:func:`bilateralFilter`,
 :ocv:func:`GaussianBlur`,
 :ocv:func:`medianBlur`,
 :ocv:func:`integral` 
 
-.. index:: buildPyramid
+
 
 buildPyramid
 ----------------
-.. ocv:function:: void buildPyramid( InputArray src, OutputArrayOfArrays dst, int maxlevel )
+Constructs the Gaussian pyramid for an image.
 
-    Constructs the Gaussian pyramid for an image.
+.. ocv:function:: void buildPyramid( InputArray src, OutputArrayOfArrays dst, int maxlevel )
 
     :param src: Source image. Check  :ocv:func:`pyrDown`  for the list of supported types.
 
-    :param dst: Destination vector of  ``maxlevel+1``  images of the same type as  ``src`` . ``dst[0]``  will be the same as  ``src`` .  ``dst[1]``  is the next pyramid layer,
-        a smoothed and down-sized  ``src``  , and so on.
+    :param dst: Destination vector of  ``maxlevel+1``  images of the same type as  ``src`` . ``dst[0]``  will be the same as  ``src`` .  ``dst[1]``  is the next pyramid layer, a smoothed and down-sized  ``src``  , and so on.
 
     :param maxlevel: 0-based index of the last (the smallest) pyramid layer. It must be non-negative.
 
 The function constructs a vector of images and builds the Gaussian pyramid by recursively applying
 :ocv:func:`pyrDown` to the previously built pyramid layers, starting from ``dst[0]==src`` .
 
-.. index:: copyMakeBorder
+
 
 copyMakeBorder
 ------------------
+Forms a border around an image.
+
 .. ocv:function:: void copyMakeBorder( InputArray src, OutputArray dst, int top, int bottom, int left, int right, int borderType, const Scalar& value=Scalar() )
 
-    Forms a border around an image.
+.. ocv:pyfunction:: cv2.copyMakeBorder(src, top, bottom, left, right, borderType[, dst[, value]]) -> dst
+
+.. ocv:cfunction:: void cvCopyMakeBorder( const CvArr* src, CvArr* dst, CvPoint offset, int bordertype, CvScalar value=cvScalarAll(0) )
+.. ocv:pyoldfunction:: cv.CopyMakeBorder(src, dst, offset, bordertype, value=(0, 0, 0, 0))-> None
 
     :param src: Source image.
 
@@ -556,20 +566,20 @@ The function supports the mode when ``src`` is already in the middle of ``dst``
     ...
 
 
-See Also:
+.. seealso::
 :ocv:func:`borderInterpolate`
-.. index:: createBoxFilter
+
 
 createBoxFilter
 -------------------
+Returns a box filter engine.
+
 .. ocv:function:: Ptr<FilterEngine> createBoxFilter( int srcType, int dstType,                                 Size ksize, Point anchor=Point(-1,-1), bool normalize=true, int borderType=BORDER_DEFAULT)
 
 .. ocv:function:: Ptr<BaseRowFilter> getRowSumFilter(int srcType, int sumType,                                   int ksize, int anchor=-1)
 
 .. ocv:function:: Ptr<BaseColumnFilter> getColumnSumFilter(int sumType, int dstType,                                   int ksize, int anchor=-1, double scale=1)
 
-    Returns a box filter engine.
-
     :param srcType: Source image type.
 
     :param sumType: Intermediate horizontal sum type that must have as many channels as  ``srcType`` .
@@ -595,18 +605,18 @@ The function itself is used by
 :ocv:func:`blur` and
 :ocv:func:`boxFilter` .
 
-See Also:
+.. seealso::
 :ocv:func:`FilterEngine`,
 :ocv:func:`blur`,
 :ocv:func:`boxFilter` 
 
-.. index:: createDerivFilter
+
 
 createDerivFilter
 ---------------------
-.. ocv:function:: Ptr<FilterEngine> createDerivFilter( int srcType, int dstType,                                     int dx, int dy, int ksize, int borderType=BORDER_DEFAULT )
+Returns an engine for computing image derivatives.
 
-    Returns an engine for computing image derivatives.
+.. ocv:function:: Ptr<FilterEngine> createDerivFilter( int srcType, int dstType,                                     int dx, int dy, int ksize, int borderType=BORDER_DEFAULT )
 
     :param srcType: Source image type.
 
@@ -626,19 +636,19 @@ The function :ocv:func:`createDerivFilter` is a small convenience function that
 :ocv:func:`Sobel` and
 :ocv:func:`Scharr` .
 
-See Also:
+.. seealso::
 :ocv:func:`createSeparableLinearFilter`,
 :ocv:func:`getDerivKernels`,
 :ocv:func:`Scharr`,
 :ocv:func:`Sobel` 
 
-.. index:: createGaussianFilter
+
 
 createGaussianFilter
 ------------------------
-.. ocv:function:: Ptr<FilterEngine> createGaussianFilter( int type, Size ksize,                                   double sigmaX, double sigmaY=0, int borderType=BORDER_DEFAULT)
+Returns an engine for smoothing images with the Gaussian filter.
 
-    Returns an engine for smoothing images with the Gaussian filter.
+.. ocv:function:: Ptr<FilterEngine> createGaussianFilter( int type, Size ksize,                                   double sigmaX, double sigmaY=0, int borderType=BORDER_DEFAULT)
 
     :param type: Source and destination image type.
 
@@ -655,21 +665,21 @@ The function :ocv:func:`createGaussianFilter` computes Gaussian kernel coefficie
 :ocv:func:`getGaussianKernel` and then
 :ocv:func:`createSeparableFilter` directly.
 
-See Also:
+.. seealso::
 :ocv:func:`createSeparableLinearFilter`,
 :ocv:func:`getGaussianKernel`,
 :ocv:func:`GaussianBlur` 
 
-.. index:: createLinearFilter
+
 
 createLinearFilter
 ----------------------
+Creates a non-separable linear filter engine.
+
 .. ocv:function:: Ptr<FilterEngine> createLinearFilter(int srcType, int dstType, InputArray kernel, Point _anchor=Point(-1,-1), double delta=0, int rowBorderType=BORDER_DEFAULT, int columnBorderType=-1, const Scalar& borderValue=Scalar())
 
 .. ocv:function:: Ptr<BaseFilter> getLinearFilter(int srcType, int dstType,                               InputArray kernel, Point anchor=Point(-1,-1), double delta=0, int bits=0)
 
-    Creates a non-separable linear filter engine.
-
     :param srcType: Source image type.
 
     :param dstType: Destination image type that must have as many channels as  ``srcType`` .
@@ -689,14 +699,16 @@ createLinearFilter
 The function returns a pointer to a 2D linear filter for the specified kernel, the source array type, and the destination array type. The function is a higher-level function that calls ``getLinearFilter`` and passes the retrieved 2D filter to the
 :ocv:func:`FilterEngine` constructor.
 
-See Also:
+.. seealso::
 :ocv:func:`createSeparableLinearFilter`,
 :ocv:func:`FilterEngine`,
 :ocv:func:`filter2D`
-.. index:: createMorphologyFilter
+
 
 createMorphologyFilter
 --------------------------
+Creates an engine for non-separable morphological operations.
+
 .. ocv:function:: Ptr<FilterEngine> createMorphologyFilter(int op, int type,    InputArray element, Point anchor=Point(-1,-1), int rowBorderType=BORDER_CONSTANT, int columnBorderType=-1, const Scalar& borderValue=morphologyDefaultBorderValue())
 
 .. ocv:function:: Ptr<BaseFilter> getMorphologyFilter(int op, int type, InputArray element,                                    Point anchor=Point(-1,-1))
@@ -707,9 +719,7 @@ createMorphologyFilter
 
 .. ocv:function:: Scalar morphologyDefaultBorderValue()
 
-    Creates an engine for non-separable morphological operations.
-
-    :param op: Morphology operation id,  ``MORPH_ERODE``  or  ``MORPH_DILATE`` .
+    :param op: Morphology operation ID,  ``MORPH_ERODE``  or  ``MORPH_DILATE`` .
     
     :param type: Input/output image type.
 
@@ -731,23 +741,23 @@ The functions construct primitive morphological filtering operations or a filter
 Note that
 :ocv:func:`createMorphologyFilter` analyzes the structuring element shape and builds a separable morphological filter engine when the structuring element is square.
 
-See Also:
+.. seealso::
 :ocv:func:`erode`,
 :ocv:func:`dilate`,
 :ocv:func:`morphologyEx`,
 :ocv:func:`FilterEngine`
-.. index:: createSeparableLinearFilter
+
 
 createSeparableLinearFilter
 -------------------------------
+Creates an engine for a separable linear filter.
+
 .. ocv:function:: Ptr<FilterEngine> createSeparableLinearFilter(int srcType, int dstType,                         InputArray rowKernel, InputArray columnKernel, Point anchor=Point(-1,-1), double delta=0,                         int rowBorderType=BORDER_DEFAULT, int columnBorderType=-1, const Scalar& borderValue=Scalar())
 
 .. ocv:function:: Ptr<BaseColumnFilter> getLinearColumnFilter(int bufType, int dstType,                         InputArray columnKernel, int anchor, int symmetryType, double delta=0, int bits=0)
 
 .. ocv:function:: Ptr<BaseRowFilter> getLinearRowFilter(int srcType, int bufType,                         InputArray rowKernel, int anchor, int symmetryType)
 
-    Creates an engine for a separable linear filter.
-
     :param srcType: Source array type.
 
     :param dstType: Destination image type that must have as many channels as  ``srcType`` .
@@ -776,18 +786,23 @@ The functions construct primitive separable linear filtering operations or a fil
 :ocv:func:`createMorphologyFilter` is smart enough to figure out the ``symmetryType`` for each of the two kernels, the intermediate ``bufType``  and, if filtering can be done in integer arithmetics, the number of ``bits`` to encode the filter coefficients. If it does not work for you, it is possible to call ``getLinearColumnFilter``,``getLinearRowFilter`` directly and then pass them to the
 :ocv:func:`FilterEngine` constructor.
 
-See Also:
+.. seealso::
 :ocv:func:`sepFilter2D`,
 :ocv:func:`createLinearFilter`,
 :ocv:func:`FilterEngine`,
 :ocv:func:`getKernelType`
-.. index:: dilate
+
 
 dilate
 ----------
+Dilates an image by using a specific structuring element.
+
 .. ocv:function:: void dilate( InputArray src, OutputArray dst, InputArray element, Point anchor=Point(-1,-1), int iterations=1, int borderType=BORDER_CONSTANT, const Scalar& borderValue=morphologyDefaultBorderValue() )
 
-    Dilates an image by using a specific structuring element.
+.. ocv:pyfunction:: cv2.dilate(src, kernel[, dst[, anchor[, iterations[, borderType[, borderValue]]]]]) -> dst
+
+.. ocv:cfunction:: void cvDilate( const CvArr* src, CvArr* dst, IplConvKernel* element=NULL, int iterations=1 )
+.. ocv:pyoldfunction:: cv.Dilate(src, dst, element=None, iterations=1)-> None
 
     :param src: Source image.
 
@@ -811,17 +826,22 @@ The function dilates the source image using the specified structuring element th
 
 The function supports the in-place mode. Dilation can be applied several ( ``iterations`` ) times. In case of multi-channel images, each channel is processed independently.
 
-See Also:
+.. seealso::
 :ocv:func:`erode`,
 :ocv:func:`morphologyEx`,
 :ocv:func:`createMorphologyFilter`
-.. index:: erode
+
 
 erode
 ---------
+Erodes an image by using a specific structuring element.
+
 .. ocv:function:: void erode( InputArray src, OutputArray dst, InputArray element, Point anchor=Point(-1,-1), int iterations=1, int borderType=BORDER_CONSTANT, const Scalar& borderValue=morphologyDefaultBorderValue() )
 
-    Erodes an image by using a specific structuring element.
+.. ocv:pyfunction:: cv2.erode(src, kernel[, dst[, anchor[, iterations[, borderType[, borderValue]]]]]) -> dst
+
+.. ocv:cfunction:: void cvErode( const CvArr* src, CvArr* dst, IplConvKernel* element=NULL, int iterations=1)
+.. ocv:pyoldfunction:: cv.Erode(src, dst, element=None, iterations=1)-> None
 
     :param src: Source image.
 
@@ -845,18 +865,23 @@ The function erodes the source image using the specified structuring element tha
 
 The function supports the in-place mode. Erosion can be applied several ( ``iterations`` ) times. In case of multi-channel images, each channel is processed independently.
 
-See Also:
+.. seealso::
 :ocv:func:`dilate`,
 :ocv:func:`morphologyEx`,
 :ocv:func:`createMorphologyFilter`
 
-.. index:: filter2D
+
 
 filter2D
 ------------
+Convolves an image with the kernel.
+
 .. ocv:function:: void filter2D( InputArray src, OutputArray dst, int ddepth, InputArray kernel, Point anchor=Point(-1,-1), double delta=0, int borderType=BORDER_DEFAULT )
 
-    Convolves an image with the kernel.
+.. ocv:pyfunction:: cv2.filter2D(src, ddepth, kernel[, dst[, anchor[, delta[, borderType]]]]) -> dst
+
+.. ocv:cfunction:: void cvFilter2D( const CvArr* src, CvArr* dst, const CvMat* kernel, CvPoint anchor=cvPoint(-1, -1))
+.. ocv:pyoldfunction:: cv.Filter2D(src, dst, kernel, anchor=(-1, -1))-> None
 
     :param src: Source image.
 
@@ -885,19 +910,21 @@ That is, the kernel is not mirrored around the anchor point. If you need a real
 
 The function uses the DFT-based algorithm in case of sufficiently large kernels (~``11 x 11`` or larger) and the direct algorithm (that uses the engine retrieved by :ocv:func:`createLinearFilter` ) for small kernels.
 
-See Also:
+.. seealso::
 :ocv:func:`sepFilter2D`,
 :ocv:func:`createLinearFilter`,
 :ocv:func:`dft`,
 :ocv:func:`matchTemplate`
 
-.. index:: GaussianBlur
+
 
 GaussianBlur
 ----------------
+Smoothes an image using a Gaussian filter.
+
 .. ocv:function:: void GaussianBlur( InputArray src, OutputArray dst, Size ksize, double sigmaX, double sigmaY=0, int borderType=BORDER_DEFAULT )
 
-    Smoothes an image using a Gaussian filter.
+.. ocv:pyfunction:: cv2.GaussianBlur(src, ksize, sigma1[, dst[, sigma2[, borderType]]]) -> dst
 
     :param src: Source image.
 
@@ -911,20 +938,22 @@ GaussianBlur
 
 The function convolves the source image with the specified Gaussian kernel. In-place filtering is supported.
 
-See Also:
+.. seealso::
 :ocv:func:`sepFilter2D`,
 :ocv:func:`filter2D`,
 :ocv:func:`blur`,
 :ocv:func:`boxFilter`,
 :ocv:func:`bilateralFilter`,
 :ocv:func:`medianBlur`
-.. index:: getDerivKernels
+
 
 getDerivKernels
 -------------------
+Returns filter coefficients for computing spatial image derivatives.
+
 .. ocv:function:: void getDerivKernels( OutputArray kx, OutputArray ky, int dx, int dy, int ksize,                      bool normalize=false, int ktype=CV_32F )
 
-    Returns filter coefficients for computing spatial image derivatives.
+.. ocv:pyfunction:: cv2.getDerivKernels(dx, dy, ksize[, kx[, ky[, normalize[, ktype]]]]) -> kx, ky
 
     :param kx: Output matrix of row filter coefficients. It has the type  ``ktype`` .
     
@@ -947,13 +976,15 @@ The function computes and returns the filter coefficients for spatial image deri
 :ocv:func:`sepFilter2D` or to
 :ocv:func:`createSeparableLinearFilter` .
 
-.. index:: getGaussianKernel
+
 
 getGaussianKernel
 ---------------------
+Returns Gaussian filter coefficients.
+
 .. ocv:function:: Mat getGaussianKernel( int ksize, double sigma, int ktype=CV_64F )
 
-    Returns Gaussian filter coefficients.
+.. ocv:pyfunction:: cv2.getGaussianKernel(ksize, sigma[, ktype]) -> retval
 
     :param ksize: Aperture size. It should be odd ( :math:`\texttt{ksize} \mod 2 = 1` ) and positive.
 
@@ -974,23 +1005,23 @@ where
 
 Two of such generated kernels can be passed to
 :ocv:func:`sepFilter2D` or to
-:ocv:func:`createSeparableLinearFilter`. Those functions automatically recognize smoothing kernels (i.e. symmetrical kernel with sum of weights = 1) and handle them accordingly. You may also use the higher-level
+:ocv:func:`createSeparableLinearFilter`. Those functions automatically recognize smoothing kernels (a symmetrical kernel with sum of weights equal to 1) and handle them accordingly. You may also use the higher-level
 :ocv:func:`GaussianBlur`.
 
-See Also:
+.. seealso::
 :ocv:func:`sepFilter2D`,
 :ocv:func:`createSeparableLinearFilter`,
 :ocv:func:`getDerivKernels`,
 :ocv:func:`getStructuringElement`,
 :ocv:func:`GaussianBlur` 
 
-.. index:: getKernelType
+
 
 getKernelType
 -----------------
-.. ocv:function:: int getKernelType(InputArray kernel, Point anchor)
+Returns the kernel type.
 
-    Returns the kernel type.
+.. ocv:function:: int getKernelType(InputArray kernel, Point anchor)
 
     :param kernel: 1D array of the kernel coefficients to analyze.
 
@@ -1007,13 +1038,19 @@ The function analyzes the kernel coefficients and returns the corresponding kern
     * **KERNEL_SMOOTH** All the kernel elements are non-negative and summed to 1. For example, the Gaussian kernel is both smooth kernel and symmetrical, so the function returns  ``KERNEL_SMOOTH | KERNEL_SYMMETRICAL`` .
     * **KERNEL_INTEGER** All the kernel coefficients are integer numbers. This flag can be combined with  ``KERNEL_SYMMETRICAL``  or  ``KERNEL_ASYMMETRICAL`` .
     
-.. index:: getStructuringElement
+
 
 getStructuringElement
 -------------------------
-.. ocv:function:: Mat getStructuringElement(int shape, Size esize, Point anchor=Point(-1,-1))
+Returns a structuring element of the specified size and shape for morphological operations.
+
+.. ocv:function:: Mat getStructuringElement(int shape, Size ksize, Point anchor=Point(-1,-1))
+
+.. ocv:pyfunction:: cv2.getStructuringElement(shape, ksize[, anchor]) -> retval
+
+.. ocv:cfunction:: IplConvKernel* cvCreateStructuringElementEx( int cols, int rows, int anchorX, int anchorY, int shape, int* values=NULL )
 
-    Returns a structuring element of the specified size and shape for morphological operations.
+.. ocv:pyoldfunction:: cv.CreateStructuringElementEx(cols, rows, anchorX, anchorY, shape, values=None)-> kernel
 
     :param shape: Element shape that could be one of the following:
 
@@ -1030,24 +1067,39 @@ getStructuringElement
         .. math::
 
             E_{ij} =  \fork{1}{if i=\texttt{anchor.y} or j=\texttt{anchor.x}}{0}{otherwise}
+            
+      * **CV_SHAPE_CUSTOM**     - custom structuring element (OpenCV 1.x API)
 
-    :param esize: Size of the structuring element.
+    :param ksize: Size of the structuring element.
+
+    :param cols: Width of the structuring element
+    
+    :param rows: Height of the structuring element
 
     :param anchor: Anchor position within the element. The default value  :math:`(-1, -1)`  means that the anchor is at the center. Note that only the shape of a cross-shaped element depends on the anchor position. In other cases the anchor just regulates how much the result of the morphological operation is shifted.
+    
+    :param anchorX: x-coordinate of the anchor
+    
+    :param anchorY: y-coordinate of the anchor
+    
+    :param values: integer array of ``cols``*``rows`` elements that specifies the custom shape of the structuring element, when ``shape=CV_SHAPE_CUSTOM``.
 
-The function constructs and returns the structuring element that can be then passed to
+The function constructs and returns the structuring element that can be further passed to
 :ocv:func:`createMorphologyFilter`,
 :ocv:func:`erode`,
 :ocv:func:`dilate` or
 :ocv:func:`morphologyEx` . But you can also construct an arbitrary binary mask yourself and use it as the structuring element.
 
-.. index:: medianBlur
+.. note:: When using OpenCV 1.x C API, the created structuring element ``IplConvKernel* element`` must be released in the end using ``cvReleaseStructuringElement(&element)``.
+
 
 medianBlur
 --------------
+Smoothes an image using the median filter.
+
 .. ocv:function:: void medianBlur( InputArray src, OutputArray dst, int ksize )
 
-    Smoothes an image using the median filter.
+.. ocv:pyfunction:: cv2.medianBlur(src, ksize[, dst]) -> dst
 
     :param src: Source 1-, 3-, or 4-channel image. When  ``ksize``  is 3 or 5, the image depth should be  ``CV_8U`` ,  ``CV_16U`` ,  or  ``CV_32F`` . For larger aperture sizes, it can only be  ``CV_8U`` .
     
@@ -1058,19 +1110,24 @@ medianBlur
 The function smoothes an image using the median filter with the
 :math:`\texttt{ksize} \times \texttt{ksize}` aperture. Each channel of a multi-channel image is processed independently. In-place operation is supported.
 
-See Also:
+.. seealso::
 :ocv:func:`bilateralFilter`,
 :ocv:func:`blur`,
 :ocv:func:`boxFilter`,
 :ocv:func:`GaussianBlur`
 
-.. index:: morphologyEx
+
 
 morphologyEx
 ----------------
+Performs advanced morphological transformations.
+
 .. ocv:function:: void morphologyEx( InputArray src, OutputArray dst, int op, InputArray element,                   Point anchor=Point(-1,-1), int iterations=1, int borderType=BORDER_CONSTANT, const Scalar& borderValue=morphologyDefaultBorderValue() )
 
-    Performs advanced morphological transformations.
+.. ocv:pyfunction:: cv2.morphologyEx(src, op, kernel[, dst[, anchor[, iterations[, borderType[, borderValue]]]]]) -> dst
+
+.. ocv:cfunction:: void cvMorphologyEx( const CvArr* src, CvArr* dst, CvArr* temp, IplConvKernel* element, int operation, int iterations=1 )
+.. ocv:pyoldfunction:: cv.MorphologyEx(src, dst, temp, element, operation, iterations=1)-> None
 
     :param src: Source image.
 
@@ -1130,18 +1187,24 @@ Morphological gradient:
 
 Any of the operations can be done in-place.
 
-See Also:
+.. seealso::
 :ocv:func:`dilate`,
 :ocv:func:`erode`,
 :ocv:func:`createMorphologyFilter`
 
-.. index:: Laplacian
+
 
 Laplacian
 -------------
+Calculates the Laplacian of an image.
+
 .. ocv:function:: void Laplacian( InputArray src, OutputArray dst, int ddepth, int ksize=1, double scale=1, double delta=0, int borderType=BORDER_DEFAULT )
 
-    Calculates the Laplacian of an image.
+.. ocv:pyfunction:: cv2.Laplacian(src, ddepth[, dst[, ksize[, scale[, delta[, borderType]]]]]) -> dst
+
+.. ocv:cfunction:: void cvLaplace( const CvArr* src, CvArr* dst, int ksize=3)
+
+.. ocv:pyoldfunction:: cv.Laplace(src, dst, ksize=3)-> None
 
     :param src: Source image.
 
@@ -1170,17 +1233,22 @@ This is done when ``ksize > 1`` . When ``ksize == 1`` , the Laplacian is compute
 
     \vecthreethree {0}{1}{0}{1}{-4}{1}{0}{1}{0}
 
-See Also:
+.. seealso::
 :ocv:func:`Sobel`,
 :ocv:func:`Scharr`
 
-.. index:: pyrDown
+
 
 pyrDown
 -----------
+Smoothes an image and downsamples it.
+
 .. ocv:function:: void pyrDown( InputArray src, OutputArray dst, const Size& dstsize=Size())
 
-    Smoothes an image and downsamples it.
+.. ocv:pyfunction:: cv2.pyrDown(src[, dst[, dstsize]]) -> dst
+
+.. ocv:cfunction:: void cvPyrDown( const CvArr* src, CvArr* dst, int filter=CV_GAUSSIAN_5x5 )
+.. ocv:pyoldfunction:: cv.PyrDown(src, dst, filter=CV_GAUSSIAN_5X5)-> None
 
     :param src: Source image.
 
@@ -1201,13 +1269,15 @@ The function performs the downsampling step of the Gaussian pyramid construction
 
 Then, it downsamples the image by rejecting even rows and columns.
 
-.. index:: pyrUp
+
 
 pyrUp
 ---------
+Upsamples an image and then smoothes it.
+
 .. ocv:function:: void pyrUp( InputArray src, OutputArray dst, const Size& dstsize=Size())
 
-    Upsamples an image and then smoothes it.
+.. ocv:pyfunction:: cv2.pyrUp(src[, dst[, dstsize]]) -> dst
 
     :param src: Source image.
 
@@ -1223,13 +1293,63 @@ pyrUp
 The function performs the upsampling step of the Gaussian pyramid construction  though it can actually be used to construct the Laplacian pyramid. First, it upsamples the source image by injecting even zero rows and columns and then convolves the result with the same kernel as in
 :ocv:func:`pyrDown`  multiplied by 4.
 
-.. index:: sepFilter2D
+
+pyrMeanShiftFiltering
+---------------------
+Performs initial step of meanshift segmentation of an image.
+
+.. ocv:function: void pyrMeanShiftFiltering( InputArray src, OutputArray dst, double sp, double sr, int maxLevel=1, TermCriteria termcrit=TermCriteria(TermCriteria::MAX_ITER+TermCriteria::EPS,5,1) )
+
+.. ocv:pyfunction:: cv2.pyrMeanShiftFiltering(src, sp, sr[, dst[, maxLevel[, termcrit]]]) -> dst
+
+.. ocv:cfunction:: void cvPyrMeanShiftFiltering( const CvArr* src, CvArr* dst, double sp,  double sr,  int max_level=1, CvTermCriteria termcrit= cvTermCriteria(CV_TERMCRIT_ITER+CV_TERMCRIT_EPS,5,1))
+
+.. ocv:pyoldfunction:: cv.PyrMeanShiftFiltering(src, dst, sp, sr, maxLevel=1, termcrit=(CV_TERMCRIT_ITER+CV_TERMCRIT_EPS, 5, 1))-> None
+    
+    :param src: The source 8-bit, 3-channel image. 
+    
+    :param dst: The destination image of the same format and the same size as the source. 
+    
+    :param sp: The spatial window radius. 
+    
+    :param sr: The color window radius. 
+    
+    :param maxLevel: Maximum level of the pyramid for the segmentation. 
+    
+    :param termcrit: Termination criteria: when to stop meanshift iterations. 
+    
+       
+The function implements the filtering stage of meanshift segmentation, that is, the output of the function is the filtered "posterized" image with color gradients and fine-grain texture flattened. At every pixel 
+``(X,Y)`` of the input image (or down-sized input image, see below) the function executes meanshift
+iterations, that is, the pixel ``(X,Y)`` neighborhood in the joint space-color hyperspace is considered:
+
+    .. math::
+
+        (x,y): X- \texttt{sp} \le x  \le X+ \texttt{sp} , Y- \texttt{sp} \le y  \le Y+ \texttt{sp} , ||(R,G,B)-(r,g,b)||   \le \texttt{sr} 
+
+
+where  ``(R,G,B)`` and  ``(r,g,b)`` are the vectors of color components at ``(X,Y)`` and  ``(x,y)``, respectively (though, the algorithm does not depend on the color space used, so any 3-component color space can be used instead). Over the neighborhood the average spatial value  ``(X',Y')`` and average color vector  ``(R',G',B')`` are found and they act as the neighborhood center on the next iteration: 
+
+    .. math::
+
+        (X,Y)~(X',Y'), (R,G,B)~(R',G',B').
+    
+After the iterations over, the color components of the initial pixel (that is, the pixel from where the iterations started) are set to the final value (average color at the last iteration): 
+
+    .. math::
+        
+        I(X,Y) <- (R*,G*,B*)
+
+When ``maxLevel > 0``, the gaussian pyramid of ``maxLevel+1`` levels is built, and the above procedure is run on the smallest layer first. After that, the results are propagated to the larger layer and the iterations are run again only on those pixels where the layer colors differ by more than ``sr`` from the lower-resolution layer of the pyramid. That makes boundaries of color regions sharper. Note that the results will be actually different from the ones obtained by running the meanshift procedure on the whole original image (i.e. when ``maxLevel==0``).
+
 
 sepFilter2D
 ---------------
+Applies a separable linear filter to an image.
+
 .. ocv:function:: void sepFilter2D( InputArray src, OutputArray dst, int ddepth, InputArray rowKernel, InputArray columnKernel, Point anchor=Point(-1,-1), double delta=0, int borderType=BORDER_DEFAULT )
 
-    Applies a separable linear filter to an image.
+.. ocv:pyfunction:: cv2.sepFilter2D(src, ddepth, kernelX, kernelY[, dst[, anchor[, delta[, borderType]]]]) -> dst
 
     :param src: Source image.
 
@@ -1249,7 +1369,7 @@ sepFilter2D
 
 The function applies a separable linear filter to the image. That is, first, every row of ``src`` is filtered with the 1D kernel ``rowKernel`` . Then, every column of the result is filtered with the 1D kernel ``columnKernel`` . The final result shifted by ``delta`` is stored in ``dst`` .
 
-See Also:
+.. seealso::
 :ocv:func:`createSeparableLinearFilter`,
 :ocv:func:`filter2D`,
 :ocv:func:`Sobel`,
@@ -1257,13 +1377,69 @@ See Also:
 :ocv:func:`boxFilter`,
 :ocv:func:`blur` 
 
-.. index:: Sobel
+
+Smooth
+------
+Smooths the image in one of several ways.
+
+.. ocv:cfunction:: void cvSmooth( const CvArr* src,  CvArr* dst,  int smoothtype=CV_GAUSSIAN,  int param1=3,  int param2=0,  double param3=0,  double param4=0)
+
+.. ocv:pyoldfunction:: cv.Smooth(src, dst, smoothtype=CV_GAUSSIAN, param1=3, param2=0, param3=0, param4=0)-> None
+
+    :param src: The source image 
+    
+    :param dst: The destination image 
+    
+    :param smoothtype: Type of the smoothing: 
+                
+            * **CV_BLUR_NO_SCALE** linear convolution with  :math:`\texttt{param1}\times\texttt{param2}`  box kernel (all 1's). If you want to smooth different pixels with different-size box kernels, you can use the integral image that is computed using  :ref:`Integral` 
+            
+               
+            * **CV_BLUR** linear convolution with  :math:`\texttt{param1}\times\texttt{param2}`  box kernel (all 1's) with subsequent scaling by  :math:`1/(\texttt{param1}\cdot\texttt{param2})` 
+            
+               
+            * **CV_GAUSSIAN** linear convolution with a  :math:`\texttt{param1}\times\texttt{param2}`  Gaussian kernel 
+            
+               
+            * **CV_MEDIAN** median filter with a  :math:`\texttt{param1}\times\texttt{param1}`  square aperture 
+            
+               
+            * **CV_BILATERAL** bilateral filter with a  :math:`\texttt{param1}\times\texttt{param1}`  square aperture, color sigma= ``param3``  and spatial sigma= ``param4`` . If  ``param1=0`` , the aperture square side is set to  ``cvRound(param4*1.5)*2+1`` . Information about bilateral filtering can be found at  http://www.dai.ed.ac.uk/CVonline/LOCAL\_COPIES/MANDUCHI1/Bilateral\_Filtering.html 
+            
+            
+    :param param1: The first parameter of the smoothing operation, the aperture width. Must be a positive odd number (1, 3, 5, ...) 
+    
+    :param param2: The second parameter of the smoothing operation, the aperture height. Ignored by  ``CV_MEDIAN``  and  ``CV_BILATERAL``  methods. In the case of simple scaled/non-scaled and Gaussian blur if  ``param2``  is zero, it is set to  ``param1`` . Otherwise it must be a positive odd number. 
+    
+    :param param3: In the case of a Gaussian parameter this parameter may specify Gaussian  :math:`\sigma`  (standard deviation). If it is zero, it is calculated from the kernel size:  
+        
+        .. math::
+        
+            \sigma  = 0.3 (n/2 - 1) + 0.8  \quad   \text{where}   \quad  n= \begin{array}{l l} \mbox{\texttt{param1} for horizontal kernel} \\ \mbox{\texttt{param2} for vertical kernel} \end{array} 
+        
+        Using standard sigma for small kernels ( :math:`3\times 3`  to  :math:`7\times 7` ) gives better speed. If  ``param3``  is not zero, while  ``param1``  and  ``param2``  are zeros, the kernel size is calculated from the sigma (to provide accurate enough operation). 
+    
+The function smooths an image using one of several methods. Every of the methods has some features and restrictions listed below:
+
+ * Blur with no scaling works with single-channel images only and supports accumulation of 8-bit to 16-bit format (similar to :ocv:func:`Sobel` and :ocv:func:`Laplace`) and 32-bit floating point to 32-bit floating-point format.
+
+ * Simple blur and Gaussian blur support 1- or 3-channel, 8-bit and 32-bit floating point images. These two methods can process images in-place.
+
+ * Median and bilateral filters work with 1- or 3-channel 8-bit images and can not process images in-place.
+
+.. note:: The function is now obsolete. Use :ocv:func:`GaussianBlur`, :ocv:func:`blur`, :ocv:func:`medianBlur` or :ocv:func:`bilateralFilter`.
+
 
 Sobel
 ---------
+Calculates the first, second, third, or mixed image derivatives using an extended Sobel operator.
+
 .. ocv:function:: void Sobel( InputArray src, OutputArray dst, int ddepth, int xorder, int yorder, int ksize=3, double scale=1, double delta=0, int borderType=BORDER_DEFAULT )
 
-    Calculates the first, second, third, or mixed image derivatives using an extended Sobel operator.
+.. ocv:pyfunction:: cv2.Sobel(src, ddepth, dx, dy[, dst[, ksize[, scale[, delta[, borderType]]]]]) -> dst
+
+.. ocv:cfunction:: void cvSobel( const CvArr* src, CvArr* dst, int xorder, int yorder, int apertureSize=3 )
+.. ocv:pyoldfunction:: cv.Sobel(src, dst, xorder, yorder, apertureSize=3)-> None
 
     :param src: Source image.
 
@@ -1323,20 +1499,22 @@ The second case corresponds to a kernel of:
 
     \vecthreethree{-1}{-2}{-1}{0}{0}{0}{1}{2}{1}
 
-See Also:
+.. seealso::
 :ocv:func:`Scharr`,
 :ocv:func:`Lapacian`,
 :ocv:func:`sepFilter2D`,
 :ocv:func:`filter2D`,
 :ocv:func:`GaussianBlur`
 
-.. index:: Scharr
+
 
 Scharr
 ----------
+Calculates the first x- or y- image derivative using Scharr operator.
+
 .. ocv:function:: void Scharr( InputArray src, OutputArray dst, int ddepth, int xorder, int yorder,            double scale=1, double delta=0, int borderType=BORDER_DEFAULT )
 
-    Calculates the first x- or y- image derivative using Scharr operator.
+.. ocv:pyfunction:: cv2.Scharr(src, ddepth, dx, dy[, dst[, scale[, delta[, borderType]]]]) -> dst
 
     :param src: Source image.
 
index 4f116b0..0572689 100644 (file)
@@ -1,6 +1,7 @@
 Geometric Image Transformations
 ===============================
 .. highlight:: cpp
+
 The functions in this section perform various geometrical transformations of 2D images. They do not change the image content but deform the pixel grid and map this deformed grid to the destination image. In fact, to avoid sampling artifacts, the mapping is done in the reverse order, from destination to the source. That is, for each pixel
 :math:`(x, y)` of the destination image, the functions compute coordinates of the corresponding "donor" pixel in the source image and copy the pixel value:
 
@@ -32,16 +33,13 @@ The actual implementations of the geometrical transformations, from the most gen
     :math:`(f_x(x,y), f_y(x,y))`     is taken as the interpolated pixel value. In OpenCV, you can choose between several interpolation methods. See
     :ref:`Resize`   for details.
 
-.. index:: convertMaps
-
-.. _convertMaps:
-
 convertMaps
 -----------
+Converts image transformation maps from one representation to another.
 
 .. ocv:function:: void convertMaps( InputArray map1, InputArray map2, OutputArray dstmap1, OutputArray dstmap2, int dstmap1type, bool nninterpolation=false )
 
-    Converts image transformation maps from one representation to another.
+.. ocv:pyfunction:: cv2.convertMaps(map1, map2, dstmap1type[, dstmap1[, dstmap2[, nninterpolation]]]) -> dstmap1, dstmap2
 
     :param map1: The first input map of type  ``CV_16SC2``  ,  ``CV_32FC1`` , or  ``CV_32FC2`` .
     
@@ -73,13 +71,18 @@ See Also:
 :ocv:func:`undisort`,
 :ocv:func:`initUndistortRectifyMap`
 
-.. index:: getAffineTransform
+
 
 getAffineTransform
 ----------------------
+Calculates an affine transform from three pairs of the corresponding points.
+
 .. ocv:function:: Mat getAffineTransform( const Point2f src[], const Point2f dst[] )
 
-    Calculates an affine transform from three pairs of the corresponding points.
+.. ocv:pyfunction:: cv2.getAffineTransform(src, dst) -> retval
+
+.. ocv:cfunction:: CvMat* cvGetAffineTransform( const CvPoint2D32f* src, const CvPoint2D32f* dst, CvMat* mapMatrix )
+.. ocv:pyoldfunction:: cv.GetAffineTransform(src, dst, mapMatrix)-> None
 
     :param src: Coordinates of triangle vertices in the source image.
 
@@ -104,15 +107,17 @@ See Also:
 :ocv:func:`transform`
 
 
-.. index:: getPerspectiveTransform
-
-.. _getPerspectiveTransform:
 
 getPerspectiveTransform
 ---------------------------
+Calculates a perspective transform from four pairs of the corresponding points.
+
 .. ocv:function:: Mat getPerspectiveTransform( const Point2f src[], const Point2f dst[] )
 
-    Calculates a perspective transform from four pairs of the corresponding points.
+.. ocv:pyfunction:: cv2.getPerspectiveTransform(src, dst) -> retval
+
+.. ocv:cfunction:: CvMat* cvGetPerspectiveTransform( const CvPoint2D32f* src, const CvPoint2D32f* dst, CvMat* mapMatrix )
+.. ocv:pyoldfunction:: cv.GetPerspectiveTransform(src, dst, mapMatrix)-> None
 
     :param src: Coordinates of quadrangle vertices in the source image.
 
@@ -137,15 +142,17 @@ See Also:
 :ocv:func:`warpPerspective`,
 :ocv:func:`perspectiveTransform`
 
-.. index:: getRectSubPix
-
-.. getRectSubPix:
 
 getRectSubPix
 -----------------
+Retrieves a pixel rectangle from an image with sub-pixel accuracy.
+
 .. ocv:function:: void getRectSubPix( InputArray image, Size patchSize, Point2f center, OutputArray dst, int patchType=-1 )
 
-    Retrieves a pixel rectangle from an image with sub-pixel accuracy.
+.. ocv:pyfunction:: cv2.getRectSubPix(image, patchSize, center[, patch[, patchType]]) -> patch
+
+.. ocv:cfunction:: void cvGetRectSubPix( const CvArr* src, CvArr* dst, CvPoint2D32f center )
+.. ocv:pyoldfunction:: cv.GetRectSubPix(src, dst, center)-> None
 
     :param src: Source image.
 
@@ -175,15 +182,18 @@ See Also:
 :ocv:func:`warpAffine`,
 :ocv:func:`warpPerspective`
 
-.. index:: getRotationMatrix2D
-
-.. _getRotationMatrix2D:
 
 getRotationMatrix2D
 -----------------------
+Calculates an affine matrix of 2D rotation.
+
 .. ocv:function:: Mat getRotationMatrix2D( Point2f center, double angle, double scale )
 
-    Calculates an affine matrix of 2D rotation.
+.. ocv:pyfunction:: cv2.getRotationMatrix2D(center, angle, scale) -> retval
+
+.. ocv:cfunction:: CvMat* cv2DRotationMatrix( CvPoint2D32f center, double angle, double scale, CvMat* mapMatrix )
+
+.. ocv:pyoldfunction:: cv.GetRotationMatrix2D(center, angle, scale, mapMatrix)-> None
 
     :param center: Center of the rotation in the source image.
 
@@ -191,6 +201,8 @@ getRotationMatrix2D
 
     :param scale: Isotropic scale factor.
 
+    :param mapMatrix: The output affine transformation, 2x3 floating-point matrix.
+
 The function calculates the following matrix:
 
 .. math::
@@ -210,15 +222,17 @@ See Also:
 :ocv:func:`warpAffine`,
 :ocv:func:`transform`
 
-.. index:: invertAffineTransform
 
-.. _invertAffineTransform:
+
+
 
 invertAffineTransform
 -------------------------
+Inverts an affine transformation.
+
 .. ocv:function:: void invertAffineTransform(InputArray M, OutputArray iM)
 
-    Inverts an affine transformation.
+.. ocv:pyfunction:: cv2.invertAffineTransform(M[, iM]) -> iM
 
     :param M: Original affine transformation.
 
@@ -234,16 +248,67 @@ The function computes an inverse affine transformation represented by
 The result is also a
 :math:`2 \times 3` matrix of the same type as ``M`` .
 
-.. index:: remap
 
-.. _remap:
+
+LogPolar
+--------
+Remaps an image to log-polar space.
+
+.. ocv:cfunction:: void cvLogPolar( const CvArr* src, CvArr* dst, CvPoint2D32f center, double M, int flags=CV_INTER_LINEAR+CV_WARP_FILL_OUTLIERS )
+
+.. ocv:pyoldfunction:: cv.LogPolar(src, dst, center, M, flags=CV_INNER_LINEAR+CV_WARP_FILL_OUTLIERS)-> None
+
+    :param src: Source image 
+
+    :param dst: Destination image 
+
+    :param center: The transformation center; where the output precision is maximal 
+
+    :param M: Magnitude scale parameter. See below 
+
+    :param flags: A combination of interpolation methods and the following optional flags: 
+            
+            * **CV_WARP_FILL_OUTLIERS** fills all of the destination image pixels. If some of them correspond to outliers in the source image, they are set to zero 
+        
+           
+            * **CV_WARP_INVERSE_MAP** See below 
+
+The function ``cvLogPolar`` transforms the source image using the following transformation:
+
+  * Forward transformation (``CV_WARP_INVERSE_MAP``is not set):
+
+        .. math::
+
+            dst( \phi , \rho ) = src(x,y) 
+
+
+  * Inverse transformation (``CV_WARP_INVERSE_MAP`` is set):
+
+        .. math::
+
+            dst(x,y) = src( \phi , \rho ) 
+
+
+where
+
+    .. math::
+
+        \rho = M  \cdot \log{\sqrt{x^2 + y^2}} , \phi =atan(y/x) 
+
+
+The function emulates the human "foveal" vision and can be used for fast scale and rotation-invariant template matching, for object tracking and so forth. The function can not operate in-place.
+
 
 remap
 -----
+Applies a generic geometrical transformation to an image.
 
 .. ocv:function:: void remap( InputArray src, OutputArray dst, InputArray map1, InputArray map2, int interpolation, int borderMode=BORDER_CONSTANT, const Scalar& borderValue=Scalar())
 
-    Applies a generic geometrical transformation to an image.
+.. ocv:pyfunction:: cv2.remap(src, map1, map2, interpolation[, dst[, borderMode[, borderValue]]]) -> dst
+
+.. ocv:cfunction:: void cvRemap( const CvArr* src, CvArr* dst, const CvArr* mapx, const CvArr* mapy, int flags=CV_INTER_LINEAR+CV_WARP_FILL_OUTLIERS, CvScalar fillval=cvScalarAll(0) )
+.. ocv:pyoldfunction:: cv.Remap(src, dst, mapx, mapy, flags=CV_INNER_LINEAR+CV_WARP_FILL_OUTLIERS, fillval=(0, 0, 0, 0))-> None
 
     :param src: Source image.
 
@@ -279,16 +344,18 @@ representations of a map is that they can yield much faster (~2x) remapping oper
 
 This function cannot operate in-place.
 
-.. index:: resize
 
-.. _resize:
 
 resize
 ----------
+Resizes an image.
 
 .. ocv:function:: void resize( InputArray src, OutputArray dst, Size dsize, double fx=0, double fy=0, int interpolation=INTER_LINEAR )
 
-    Resizes an image.
+.. ocv:pyfunction:: cv2.resize(src, dsize[, dst[, fx[, fy[, interpolation]]]]) -> dst
+
+.. ocv:cfunction:: void cvResize( const CvArr* src, CvArr* dst, int interpolation=CV_INTER_LINEAR )
+.. ocv:pyoldfunction:: cv.Resize(src, dst, interpolation=CV_INTER_LINEAR)-> None
 
     :param src: Source image.
 
@@ -301,7 +368,7 @@ resize
             \texttt{dsize = Size(round(fx*src.cols), round(fy*src.rows))}
 
         
-    Either  ``dsize``  or both  ``fx``  and  ``fy``  must be non-zero.
+        Either  ``dsize``  or both  ``fx``  and  ``fy``  must be non-zero.
 
     :param fx: Scale factor along the horizontal axis. When it is 0, it is computed as
 
@@ -346,15 +413,22 @@ See Also:
 :ocv:func:`warpPerspective`,
 :ocv:func:`remap` 
 
-.. index:: warpAffine
 
-.. _warpAffine:
+
 
 warpAffine
 --------------
+Applies an affine transformation to an image.
+
 .. ocv:function:: void warpAffine( InputArray src, OutputArray dst, InputArray M, Size dsize, int flags=INTER_LINEAR, int borderMode=BORDER_CONSTANT, const Scalar& borderValue=Scalar())
 
-    Applies an affine transformation to an image.
+.. ocv:pyfunction:: cv2.warpAffine(src, M, dsize[, dst[, flags[, borderMode[, borderValue]]]]) -> dst
+
+.. ocv:cfunction:: void cvWarpAffine( const CvArr* src, CvArr* dst, const CvMat* mapMatrix, int flags=CV_INTER_LINEAR+CV_WARP_FILL_OUTLIERS, CvScalar fillval=cvScalarAll(0) )
+.. ocv:pyoldfunction:: cv.WarpAffine(src, dst, mapMatrix, flags=CV_INTER_LINEAR+CV_WARP_FILL_OUTLIERS, fillval=(0, 0, 0, 0))-> None
+
+.. ocv:cfunction:: void cvGetQuadrangleSubPix( const CvArr* src, CvArr* dst, const CvMat* mapMatrix )
+.. ocv:pyoldfunction:: cv.GetQuadrangleSubPix(src, dst, mapMatrix)-> None
 
     :param src: Source image.
 
@@ -387,13 +461,19 @@ See Also:
 :ocv:func:`getRectSubPix`,
 :ocv:func:`transform`
 
-.. index:: warpPerspective
+
+.. note:: ``cvGetQuadrangleSubPix`` is similar to ``cvWarpAffine``, but the outliers are extrapolated using replication border mode.
 
 warpPerspective
 -------------------
+Applies a perspective transformation to an image.
+
 .. ocv:function:: void warpPerspective( InputArray src, OutputArray dst, InputArray M, Size dsize, int flags=INTER_LINEAR, int borderMode=BORDER_CONSTANT, const Scalar& borderValue=Scalar())
 
-    Applies a perspective transformation to an image.
+.. ocv:pyfunction:: cv2.warpPerspective(src, M, dsize[, dst[, flags[, borderMode[, borderValue]]]]) -> dst
+
+.. ocv:cfunction:: void cvWarpPerspective( const CvArr* src, CvArr* dst, const CvMat* mapMatrix, int flags=CV_INTER_LINEAR+CV_WARP_FILL_OUTLIERS, CvScalar fillval=cvScalarAll(0) )
+.. ocv:pyoldfunction:: cv.WarpPerspective(src, dst, mapMatrix, flags=CV_INNER_LINEAR+CV_WARP_FILL_OUTLIERS, fillval=(0, 0, 0, 0))-> None
 
     :param src: Source image.
 
@@ -428,20 +508,27 @@ See Also:
 :ocv:func:`perspectiveTransform`
 
 
-.. index:: initUndistortRectifyMap
+
 
 initUndistortRectifyMap
 ---------------------------
+Computes the undistortion and rectification transformation map.
 
 .. ocv:function:: void initUndistortRectifyMap( InputArray cameraMatrix, InputArray distCoeffs, InputArray R, InputArray newCameraMatrix, Size size, int m1type, OutputArray map1, OutputArray map2 )
 
-    Computes the undistortion and rectification transformation map.
+.. ocv:pyfunction:: cv2.initUndistortRectifyMap(cameraMatrix, distCoeffs, R, newCameraMatrix, size, m1type[, map1[, map2]]) -> map1, map2
+
+.. ocv:cfunction:: void cvInitUndistortRectifyMap( const CvMat* cameraMatrix, const CvMat* distCoeffs, const CvMat* R, const CvMat* newCameraMatrix, CvArr* map1, CvArr* map2 )
+.. ocv:cfunction:: void cvInitUndistortMap( const CvMat* cameraMatrix, const CvMat* distCoeffs, CvArr* map1, CvArr* map2 )
+
+.. ocv:pyoldfunction:: cv.InitUndistortRectifyMap(cameraMatrix, distCoeffs, R, newCameraMatrix, map1, map2)-> None
+.. ocv:pyoldfunction:: cv.InitUndistortMap(cameraMatrix, distCoeffs, map1, map2)-> None
 
     :param cameraMatrix: Input camera matrix  :math:`A=\vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}` .
     
     :param distCoeffs: Input vector of distortion coefficients  :math:`(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6]])`  of 4, 5, or 8 elements. If the vector is NULL/empty, the zero distortion coefficients are assumed.
 
-    :param R: Optional rectification transformation in the object space (3x3 matrix).  ``R1``  or  ``R2`` , computed by  :ref:`StereoRectify`  can be passed here. If the matrix is empty, the identity transformation is assumed.
+    :param R: Optional rectification transformation in the object space (3x3 matrix).  ``R1``  or  ``R2`` , computed by  :ref:`StereoRectify`  can be passed here. If the matrix is empty, the identity transformation is assumed. In ``cvInitUndistortMap`` R assumed to be an identity matrix.
 
     :param newCameraMatrix: New camera matrix  :math:`A'=\vecthreethree{f_x'}{0}{c_x'}{0}{f_y'}{c_y'}{0}{0}{1}` .
     
@@ -483,13 +570,15 @@ In case of a stereo camera, this function is called twice: once for each camera
 where ``cameraMatrix`` can be chosen arbitrarily.
 
 
-.. index:: getDefaultNewCameraMatrix
+
 
 getDefaultNewCameraMatrix
 -----------------------------
+Returns the default new camera matrix.
+
 .. ocv:function:: Mat getDefaultNewCameraMatrix(InputArray cameraMatrix, Size imgSize=Size(), bool centerPrincipalPoint=false )
 
-    Returns the default new camera matrix.
+.. ocv:pyfunction:: cv2.getDefaultNewCameraMatrix(cameraMatrix[, imgsize[, centerPrincipalPoint]]) -> retval
 
     :param cameraMatrix: Input camera matrix.
 
@@ -516,13 +605,19 @@ By default, the undistortion functions in OpenCV (see
 :ref:`undistort`) do not move the principal point. However, when you work with stereo, it is important to move the principal points in both views to the same y-coordinate (which is required by most of stereo correspondence algorithms), and may be to the same x-coordinate too. So, you can form the new camera matrix for each view where the principal points are located at the center.
 
 
-.. index:: undistort
+
 
 undistort
 -------------
+Transforms an image to compensate for lens distortion.
+
 .. ocv:function:: void undistort( InputArray src, OutputArray dst, InputArray cameraMatrix, InputArray distCoeffs, InputArray newCameraMatrix=noArray() )
 
-    Transforms an image to compensate for lens distortion.
+.. ocv:pyfunction:: cv2.undistort(src, cameraMatrix, distCoeffs[, dst[, newCameraMatrix]]) -> dst
+
+.. ocv:cfunction:: void cvUndistort2( const CvArr* src, CvArr* dst, const CvMat* cameraMatrix, const CvMat* distCoeffs, const CvMat* newCameraMatrix=NULL )
+
+.. ocv:pyoldfunction:: cv.Undistort2(src, dst, cameraMatrix, distCoeffs)-> None
 
     :param src: Input (distorted) image.
 
@@ -537,8 +632,8 @@ undistort
 The function transforms an image to compensate radial and tangential lens distortion.
 
 The function is simply a combination of
-:ref:`InitUndistortRectifyMap` (with unity ``R`` ) and
-:ref:`Remap` (with bilinear interpolation). See the former function for details of the transformation being performed.
+:ocv:func:`initUndistortRectifyMap` (with unity ``R`` ) and
+:ocv:func:`remap` (with bilinear interpolation). See the former function for details of the transformation being performed.
 
 Those pixels in the destination image, for which there is no correspondent pixels in the source image, are filled with zeros (black color).
 
@@ -551,13 +646,16 @@ The camera matrix and the distortion parameters can be determined using
 :math:`c_y` need to be scaled accordingly, while the distortion coefficients remain the same.
 
 
-.. index:: undistortPoints
+
 
 undistortPoints
 -------------------
+Computes the ideal point coordinates from the observed point coordinates.
+
 .. ocv:function:: void undistortPoints( InputArray src, OutputArray dst, InputArray cameraMatrix, InputArray distCoeffs, InputArray R=noArray(), InputArray P=noArray())
 
-    Computes the ideal point coordinates from the observed point coordinates.
+.. ocv:cfunction:: void cvUndistortPoints( const CvMat* src, CvMat* dst, const CvMat* cameraMatrix, const CvMat* distCoeffs, const CvMat* R=NULL, const CvMat* P=NULL)
+.. ocv:pyoldfunction:: cv.UndistortPoints(src, dst, cameraMatrix, distCoeffs, R=None, P=None)-> None
 
     :param src: Observed point coordinates, 1xN or Nx1 2-channel (CV_32FC2 or CV_64FC2).
 
index b6e7585..c1fe52f 100644 (file)
@@ -3,15 +3,20 @@ Histograms
 
 .. highlight:: cpp
 
-.. index:: calcHist
+
 
 calcHist
 ------------
+Calculates a histogram of a set of arrays.
+
 .. ocv:function:: void calcHist( const Mat* arrays, int narrays, const int* channels, InputArray mask,               OutputArray hist, int dims, const int* histSize, const float** ranges, bool uniform=true,               bool accumulate=false )
 
 .. ocv:function:: void calcHist( const Mat* arrays, int narrays, const int* channels, InputArray mask,               SparseMat& hist, int dims, const int* histSize, const float** ranges, bool uniform=true, bool accumulate=false )
 
-    Calculates a histogram of a set of arrays.
+.. ocv:pyfunction:: cv2.calcHist(images, channels, mask, histSize, ranges[, hist[, accumulate]]) -> hist
+
+.. ocv:cfunction:: void cvCalcHist( IplImage** image, CvHistogram* hist, int accumulate=0, const CvArr* mask=NULL )
+.. ocv:pyoldfunction:: cv.CalcHist(image, hist, accumulate=0, mask=None)-> None
 
     :param arrays: Source arrays. They all should have the same depth,  ``CV_8U``  or  ``CV_32F`` , and the same size. Each of them can have an arbitrary number of channels.
 
@@ -95,15 +100,20 @@ input arrays at the same location. The sample below shows how to compute a 2D Hu
     }
 
 
-.. index:: calcBackProject
+
 
 calcBackProject
 -------------------
+Calculates the back projection of a histogram.
+
 .. ocv:function:: void calcBackProject( const Mat* arrays, int narrays, const int* channels, InputArray hist, OutputArray backProject, const float** ranges, double scale=1, bool uniform=true )
 
 .. ocv:function:: void calcBackProject( const Mat* arrays, int narrays, const int* channels, const SparseMat& hist, OutputArray backProject, const float** ranges, double scale=1, bool uniform=true )
 
-    Calculates the back projection of a histogram.
+.. ocv:pyfunction:: cv2.calcBackProject(images, channels, hist, ranges[, dst[, scale]]) -> dst
+
+.. ocv:cfunction:: void cvCalcBackProject( IplImage** image, CvArr* backProject, const CvHistogram* hist )
+.. ocv:pyoldfunction:: cv.CalcBackProject(image, backProject, hist)-> None
 
     :param arrays: Source arrays. They all should have the same depth,  ``CV_8U``  or  ``CV_32F`` , and the same size. Each of them can have an arbitrary number of channels.
 
@@ -138,16 +148,20 @@ This is an approximate algorithm of the
 See Also:
 :ocv:func:`calcHist`
 
-.. index:: compareHist
+
 
 compareHist
 -----------
+Compares two histograms.
 
 .. ocv:function:: double compareHist( InputArray H1, InputArray H2, int method )
 
 .. ocv:function:: double compareHist( const SparseMat& H1,  const SparseMat& H2, int method )
 
-    Compares two histograms.
+.. ocv:pyfunction:: cv2.compareHist(H1, H2, method) -> retval
+
+.. ocv:cfunction:: double cvCompareHist( const CvHistogram* hist1, const CvHistogram* hist2, int method )
+.. ocv:pyoldfunction:: cv.CompareHist(hist1, hist2, method)->float
 
     :param H1: The first compared histogram.
 
@@ -204,14 +218,16 @@ While the function works well with 1-, 2-, 3-dimensional dense histograms, it ma
 :ocv:func:`EMD` function.
 
 
-.. index:: EMD
+
 
 EMD
 ------
-.. ocv:function:: float EMD( InputArray signature1, InputArray signature2, int distType, InputArray cost=noArray(), float* lowerBound=0, OutputArray flow=noArray() )
+Computes the "minimal work" distance between two weighted point configurations.
 
-    Computes the "minimal work" distance between two weighted point configurations.
+.. ocv:function:: float EMD( InputArray signature1, InputArray signature2, int distType, InputArray cost=noArray(), float* lowerBound=0, OutputArray flow=noArray() )
 
+.. ocv:cfunction:: float cvCalcEMD2( const CvArr* signature1, const CvArr* signature2, int distType, CvDistanceFunction distFunc=NULL, const CvArr* cost=NULL, CvArr* flow=NULL, float* lowerBound=NULL, void* userdata=NULL )
+.. ocv:pyoldfunction:: cv.CalcEMD2(signature1, signature2, distType, distFunc=None, cost=None, flow=None, lowerBound=None, userdata=None) -> float
 
     :param signature1: The first signature, a  :math:`\texttt{size1}\times \texttt{dims}+1`  floating-point matrix. Each row stores the point weight followed by the point coordinates. The matrix is allowed to have a single column (weights only) if the user-defined cost matrix is used.
 
@@ -219,22 +235,33 @@ EMD
 
     :param distType: Used metric.  ``CV_DIST_L1, CV_DIST_L2`` , and  ``CV_DIST_C``  stand for one of the standard metrics;  ``CV_DIST_USER``  means that a pre-calculated cost matrix ``cost``  is used.
 
+    :param distFunc: custom distance function, supported by the old interface. ``CvDistanceFunction`` is defined as: ::
+        
+            typedef float (CV_CDECL * CvDistanceFunction)( const float* a,
+                                const float* b, void* userdata );
+        
+        where ``a`` and ``b`` are point coordinates and ``userdata`` is the same as the last parameter.
+        
     :param cost: The user-defined  :math:`\texttt{size1}\times \texttt{size2}`  cost matrix. Also, if a cost matrix is used, lower boundary  ``lowerBound``  can not be calculated, because it needs a metric function.
 
     :param lowerBound: Optional input/output parameter: lower boundary of distance between the two signatures that is a distance between mass centers. The lower boundary may not be calculated if the user-defined cost matrix is used, the total weights of point configurations are not equal, or if the signatures consist of weights only (i.e. the signature matrices have a single column). The user  **must**  initialize  ``*lowerBound`` . If the calculated distance between mass centers is greater or equal to  ``*lowerBound``  (it means that the signatures are far enough) the function does not calculate EMD. In any case  ``*lowerBound``  is set to the calculated distance between mass centers on return. Thus, if user wants to calculate both distance between mass centers and EMD,  ``*lowerBound``  should be set to 0.
 
     :param flow: The resultant  :math:`\texttt{size1} \times \texttt{size2}`  flow matrix:  :math:`\texttt{flow}_{i,j}`  is a flow from  :math:`i`  th point of  ``signature1``  to  :math:`j`  th point of  ``signature2``  .
+    
+    :param userdata: Optional pointer directly passed to the custom distance function.
 
-The function computes the earth mover distance and/or a lower boundary of the distance between the two weighted point configurations. One of the applications described in :ref:`RubnerSept98` is multi-dimensional histogram comparison for image retrieval. EMD is a transportation problem that is solved using some modification of a simplex algorithm, thus the complexity is exponential in the worst case, though, on average it is much faster. In the case of a real metric the lower boundary can be calculated even faster (using linear-time algorithm) and it can be used to determine roughly whether the two signatures are far enough so that they cannot relate to the same object.
-
+The function computes the earth mover distance and/or a lower boundary of the distance between the two weighted point configurations. One of the applications described in [RubnerSept98]_ is multi-dimensional histogram comparison for image retrieval. EMD is a transportation problem that is solved using some modification of a simplex algorithm, thus the complexity is exponential in the worst case, though, on average it is much faster. In the case of a real metric the lower boundary can be calculated even faster (using linear-time algorithm) and it can be used to determine roughly whether the two signatures are far enough so that they cannot relate to the same object.
 
-.. index:: equalizeHist
 
 equalizeHist
 ----------------
+Equalizes the histogram of a grayscale image.
+
 .. ocv:function:: void equalizeHist( InputArray src, OutputArray dst )
 
-    Equalizes the histogram of a grayscale image.
+.. ocv:pyfunction:: cv2.equalizeHist(src[, dst]) -> dst
+
+.. ocv:cfunction:: void cvEqualizeHist( const CvArr* src, CvArr* dst )
 
     :param src: Source 8-bit single channel image.
 
@@ -262,3 +289,296 @@ The function equalizes the histogram of the input image using the following algo
     :math:`\texttt{dst}(x,y) = H'(\texttt{src}(x,y))`
 
 The algorithm normalizes the brightness and increases the contrast of the image.
+
+
+Extra Histogram Functions (C API)
+---------------------------------
+
+In the rest of the section additional C functions operating on ``CvHistogram`` are described.
+
+CalcBackProjectPatch
+--------------------
+Locates a template within an image by using a histogram comparison.
+
+.. ocv:cfunction:: void cvCalcBackProjectPatch( IplImage** images, CvArr* dst, CvSize patch_size, CvHistogram* hist, int method, double factor )
+
+.. ocv:pyoldfunction:: cv.CalcBackProjectPatch(images, dst, patchSize, hist, method, factor)-> None
+    
+    :param images: Source images (though, you may pass CvMat** as well)     
+    
+    :param dst: Destination image 
+    
+    :param patch_size: Size of the patch slid though the source image 
+    
+    :param hist: Histogram 
+    
+    :param method: Comparison method, passed to  :ref:`CompareHist`  (see description of that function) 
+    
+    :param factor: Normalization factor for histograms, will affect the normalization scale of the destination image, pass 1 if unsure 
+    
+The function calculates the back projection by comparing histograms of the source image patches with the given histogram. The function is similar to :ocv:func:`MatchTemplate`, but instead of comparing raster patch with all its possible positions within the search window, the function ``CalcBackProjectPatch`` compares histograms. Below is the diagram of the algorithm: ::
+
+.. image:: pics/backprojectpatch.png
+
+
+CalcProbDensity
+---------------
+Divides one histogram by another.
+
+.. ocv:cfunction:: void  cvCalcProbDensity(  const CvHistogram* hist1, const CvHistogram* hist2, CvHistogram* dsthist, double scale=255 )
+
+.. ocv:pyoldfunction:: cv.CalcProbDensity(hist1, hist2, dsthist, scale=255)-> None
+    
+    :param hist1: first histogram (the divisor) 
+    
+    :param hist2: second histogram 
+    
+    :param dsthist: destination histogram 
+    
+    :param scale: scale factor for the destination histogram 
+    
+The function calculates the object probability density from the two histograms as:
+
+.. math::
+
+    \texttt{disthist} (I)= \forkthree{0}{if $\texttt{hist1}(I)=0$}{\texttt{scale}}{if $\texttt{hist1}(I) \ne 0$ and $\texttt{hist2}(I) > \texttt{hist1}(I)$}{\frac{\texttt{hist2}(I) \cdot \texttt{scale}}{\texttt{hist1}(I)}}{if $\texttt{hist1}(I) \ne 0$ and $\texttt{hist2}(I) \le \texttt{hist1}(I)$} 
+
+
+ClearHist
+---------
+Clears the histogram.
+
+.. ocv:cfunction:: void cvClearHist( CvHistogram* hist )
+.. ocv:pyoldfunction:: cv.ClearHist(hist)-> None
+
+    :param hist: Histogram 
+
+The function sets all of the histogram bins to 0 in the case of a dense histogram and removes all histogram bins in the case of a sparse array.
+
+
+CopyHist
+--------
+Copies a histogram.
+
+.. ocv:cfunction:: void cvCopyHist( const CvHistogram* src, CvHistogram** dst )
+
+    :param src: Source histogram 
+    
+    :param dst: Pointer to destination histogram 
+    
+The function makes a copy of the histogram. If the second histogram pointer ``*dst`` is NULL, a new histogram of the same size as  ``src`` is created. Otherwise, both histograms must have equal types and sizes. Then the function copies the source histogram's bin values to the destination histogram and sets the same bin value ranges as in ``src``.
+
+
+CreateHist
+----------
+Creates a histogram.
+
+.. ocv:cfunction:: CvHistogram* cvCreateHist( int dims, int* sizes, int type, float** ranges=NULL, int uniform=1 )
+
+.. ocv:pyoldfunction:: cv.CreateHist(dims, type, ranges, uniform=1) -> hist
+
+    :param dims: Number of histogram dimensions 
+    
+    :param sizes: Array of the histogram dimension sizes 
+    
+    :param type: Histogram representation format:  ``CV_HIST_ARRAY``  means that the histogram data is represented as a multi-dimensional dense array CvMatND;  ``CV_HIST_SPARSE``  means that histogram data is represented as a multi-dimensional sparse array CvSparseMat 
+    
+    :param ranges: Array of ranges for the histogram bins. Its meaning depends on the  ``uniform``  parameter value. The ranges are used for when the histogram is calculated or backprojected to determine which histogram bin corresponds to which value/tuple of values from the input image(s) 
+    
+    :param uniform: Uniformity flag; if not 0, the histogram has evenly
+        spaced bins and for every  :math:`0<=i<cDims`   ``ranges[i]`` 
+        is an array of two numbers: lower and upper boundaries for the i-th
+        histogram dimension.
+        The whole range [lower,upper] is then split
+        into  ``dims[i]``  equal parts to determine the  ``i-th``  input
+        tuple value ranges for every histogram bin. And if  ``uniform=0`` ,
+        then  ``i-th``  element of  ``ranges``  array contains ``dims[i]+1``  elements: :math:`\texttt{lower}_0, \texttt{upper}_0, 
+        \texttt{lower}_1, \texttt{upper}_1 = \texttt{lower}_2,
+        ...
+        \texttt{upper}_{dims[i]-1}` 
+        where :math:`\texttt{lower}_j`  and  :math:`\texttt{upper}_j` 
+        are lower and upper
+        boundaries of  ``i-th``  input tuple value for  ``j-th`` 
+        bin, respectively. In either case, the input values that are beyond
+        the specified range for a histogram bin are not counted by :ocv:cfunc:`CalcHist`  and filled with 0 by :ocv:cfunc:`CalcBackProject` 
+    
+The function creates a histogram of the specified size and returns a pointer to the created histogram. If the array ``ranges`` is 0, the histogram bin ranges must be specified later via the function  :ocv:cfunc:`SetHistBinRanges`. Though :ocv:cfunc:`CalcHist` and :ocv:cfunc:`CalcBackProject` may process 8-bit images without setting bin ranges, they assume thy are equally spaced in 0 to 255 bins.
+
+
+GetHistValue*D
+--------------
+Returns a pointer to the histogram bin.
+
+.. ocv:cfunction:: float cvGetHistValue_1D(hist, idx0)
+
+.. ocv:cfunction:: float cvGetHistValue_2D(hist, idx0, idx1)
+
+.. ocv:cfunction:: float cvGetHistValue_3D(hist, idx0, idx1, idx2)
+
+.. ocv:cfunction:: float cvGetHistValue_nD(hist, idx)
+    
+    :param hist: Histogram 
+    
+    :param idx0, idx1, idx2, idx3: Indices of the bin 
+    
+    :param idx: Array of indices 
+
+::
+
+    #define cvGetHistValue_1D( hist, idx0 ) 
+        ((float*)(cvPtr1D( (hist)->bins, (idx0), 0 ))
+    #define cvGetHistValue_2D( hist, idx0, idx1 ) 
+        ((float*)(cvPtr2D( (hist)->bins, (idx0), (idx1), 0 )))
+    #define cvGetHistValue_3D( hist, idx0, idx1, idx2 ) 
+        ((float*)(cvPtr3D( (hist)->bins, (idx0), (idx1), (idx2), 0 )))
+    #define cvGetHistValue_nD( hist, idx ) 
+        ((float*)(cvPtrND( (hist)->bins, (idx), 0 )))    
+
+..
+
+The macros ``GetHistValue`` return a pointer to the specified bin of the 1D, 2D, 3D or N-D histogram. In the case of a sparse histogram the function creates a new bin and sets it to 0, unless it exists already.
+
+
+GetMinMaxHistValue
+------------------
+Finds the minimum and maximum histogram bins.
+
+.. ocv:cfunction:: void cvGetMinMaxHistValue(  const CvHistogram* hist, float* min_value, float* max_value, int* min_idx=NULL, int* max_idx=NULL )
+    
+.. ocv:pyoldfunction:: cv.GetMinMaxHistValue(hist)-> (minValue, maxValue, minIdx, maxIdx)
+
+    :param hist: Histogram 
+    
+    :param min_value: Pointer to the minimum value of the histogram 
+    
+    :param max_value: Pointer to the maximum value of the histogram 
+    
+    :param min_idx: Pointer to the array of coordinates for the minimum 
+    
+    :param max_idx: Pointer to the array of coordinates for the maximum 
+    
+The function finds the minimum and maximum histogram bins and their positions. All of output arguments are optional. Among several extremas with the same value the ones with the minimum index (in lexicographical order) are returned. In the case of several maximums or minimums, the earliest in lexicographical order (extrema locations) is returned.
+
+
+MakeHistHeaderForArray
+----------------------
+Makes a histogram out of an array.
+
+.. ocv:cfunction:: CvHistogram*  cvMakeHistHeaderForArray(  int dims, int* sizes, CvHistogram* hist, float* data, float** ranges=NULL, int uniform=1 )
+    
+    :param dims: Number of histogram dimensions 
+    
+    :param sizes: Array of the histogram dimension sizes 
+    
+    :param hist: The histogram header initialized by the function 
+    
+    :param data: Array that will be used to store histogram bins 
+    
+    :param ranges: Histogram bin ranges, see  :ref:`CreateHist` 
+    
+    :param uniform: Uniformity flag, see  :ref:`CreateHist` 
+    
+The function initializes the histogram, whose header and bins are allocated by the user. :ocv:cfunc:`ReleaseHist` does not need to be called afterwards. Only dense histograms can be initialized this way. The function returns ``hist``.
+
+NormalizeHist
+-------------
+Normalizes the histogram.
+
+.. ocv:cfunction:: void cvNormalizeHist( CvHistogram* hist, double factor )
+.. ocv:pyoldfunction:: cv.NormalizeHist(hist, factor)-> None
+    
+    :param hist: Pointer to the histogram 
+    
+    :param factor: Normalization factor 
+    
+The function normalizes the histogram bins by scaling them, such that the sum of the bins becomes equal to  ``factor``.
+
+
+QueryHistValue*D
+----------------
+Queries the value of the histogram bin.
+
+.. ocv:cfunction:: float QueryHistValue_1D(CvHistogram hist, int idx0)
+.. ocv:cfunction:: float QueryHistValue_2D(CvHistogram hist, int idx0, int idx1)
+.. ocv:cfunction:: float QueryHistValue_3D(CvHistogram hist, int idx0, int idx1, int idx2)
+.. ocv:cfunction:: float QueryHistValue_nD(CvHistogram hist, const int* idx)
+
+.. ocv:pyoldfunction:: cv.QueryHistValue_1D(hist, idx0) -> float
+.. ocv:pyoldfunction:: cv.QueryHistValue_2D(hist, idx0, idx1) -> float
+.. ocv:pyoldfunction:: cv.QueryHistValue_3D(hist, idx0, idx1, idx2) -> float
+.. ocv:pyoldfunction:: cv.QueryHistValueND(hist, idx) -> float
+
+    :param hist: Histogram 
+    
+    :param idx0, idx1, idx2, idx3: Indices of the bin 
+    
+    :param idx: Array of indices 
+
+The macros return the value of the specified bin of the 1D, 2D, 3D or N-D histogram. In the case of a sparse histogram the function returns 0, if the bin is not present in the histogram no new bin is created.
+
+ReleaseHist
+-----------
+Releases the histogram.
+
+.. ocv:cfunction:: void cvReleaseHist( CvHistogram** hist )
+    
+    :param hist: Double pointer to the released histogram 
+    
+The function releases the histogram (header and the data). The pointer to the histogram is cleared by the function. If ``*hist`` pointer is already ``NULL``, the function does nothing.
+
+
+SetHistBinRanges
+----------------
+Sets the bounds of the histogram bins.
+
+.. ocv:cfunction:: void cvSetHistBinRanges(  CvHistogram* hist, float** ranges, int uniform=1 )
+
+    :param hist: Histogram 
+    
+    :param ranges: Array of bin ranges arrays, see  :ref:`CreateHist` 
+    
+    :param uniform: Uniformity flag, see  :ref:`CreateHist` 
+    
+The function is a stand-alone function for setting bin ranges in the histogram. For a more detailed description of the parameters ``ranges`` and ``uniform`` see the :ocv:cfunc:`CalcHist` function, that can initialize the ranges as well. Ranges for the histogram bins must be set before the histogram is calculated or the backproject of the histogram is calculated.
+
+
+ThreshHist
+----------
+Thresholds the histogram.
+
+.. ocv:cfunction:: void cvThreshHist( CvHistogram* hist, double threshold )
+.. ocv:pyoldfunction:: cv.ThreshHist(hist, threshold)-> None
+    
+    :param hist: Pointer to the histogram 
+    
+    :param threshold: Threshold level 
+    
+The function clears histogram bins that are below the specified threshold.
+
+
+CalcPGH
+-------
+Calculates a pair-wise geometrical histogram for a contour.
+
+.. ocv:cfunction:: void cvCalcPGH( const CvSeq* contour, CvHistogram* hist )
+.. ocv:pyoldfunction:: cv.CalcPGH(contour, hist)-> None
+    
+    :param contour: Input contour. Currently, only integer point coordinates are allowed 
+    
+    :param hist: Calculated histogram; must be two-dimensional 
+    
+The function calculates a 2D pair-wise geometrical histogram (PGH), described in [Iivarinen97]_ for the contour. The algorithm considers every pair of contour
+edges. The angle between the edges and the minimum/maximum distances
+are determined for every pair. To do this each of the edges in turn
+is taken as the base, while the function loops through all the other
+edges. When the base edge and any other edge are considered, the minimum
+and maximum distances from the points on the non-base edge and line of
+the base edge are selected. The angle between the edges defines the row
+of the histogram in which all the bins that correspond to the distance
+between the calculated minimum and maximum distances are incremented
+(that is, the histogram is transposed relatively to the definition in the original paper). The histogram can be used for contour matching.
+
+.. [RubnerSept98] Y. Rubner. C. Tomasi, L.J. Guibas. The Earth Mover’s Distance as a Metric for Image Retrieval. Technical Report STAN-CS-TN-98-86, Department of Computer Science, Stanford University, September 1998.
+
+.. [Iivarinen97] Jukka Iivarinen, Markus Peura, Jaakko Srel, and Ari Visa. Comparison of Combined Shape Descriptors for Irregular Objects, 8th British Machine Vision Conference, BMVC'97.
+http://www.cis.hut.fi/research/IA/paper/publications/bmvc97/bmvc97.html
\ No newline at end of file
index acaebc4..319fb22 100644 (file)
@@ -12,6 +12,7 @@ imgproc. Image Processing
     miscellaneous_transformations
     histograms
     structural_analysis_and_shape_descriptors
+    planar_subdivisions
     motion_analysis_and_object_tracking
     feature_detection
     object_detection
index 520ff2d..fdf0fc0 100644 (file)
@@ -3,15 +3,17 @@ Miscellaneous Image Transformations
 
 .. highlight:: cpp
 
-.. index:: adaptiveThreshold
-
-.. _adaptiveThreshold:
 
 adaptiveThreshold
 ---------------------
+Applies an adaptive threshold to an array.
+
 .. ocv:function:: void adaptiveThreshold( InputArray src, OutputArray dst, double maxValue,                        int adaptiveMethod, int thresholdType,                        int blockSize, double C )
 
-    Applies an adaptive threshold to an array.
+.. ocv:pyfunction:: cv2.adaptiveThreshold(src, maxValue, adaptiveMethod, thresholdType, blockSize, C[, dst]) -> dst
+
+.. ocv:cfunction:: void cvAdaptiveThreshold( const CvArr* src, CvArr* dst, double maxValue, int adaptiveMethod=CV_ADAPTIVE_THRESH_MEAN_C, int thresholdType=CV_THRESH_BINARY, int blockSize=3, double param1=5 )
+.. ocv:pyoldfunction:: cv.AdaptiveThreshold(src, dst, maxValue, adaptiveMethod=CV_ADAPTIVE_THRESH_MEAN_C, thresholdType=CV_THRESH_BINARY, blockSize=3, param1=5)-> None
 
     :param src: Source 8-bit single-channel image.
 
@@ -64,15 +66,17 @@ See Also:
 :ocv:func:`GaussianBlur`
 
 
-.. index:: cvtColor
-
-.. _cvtColor:
 
 cvtColor
 ------------
+Converts an image from one color space to another.
+
 .. ocv:function:: void cvtColor( InputArray src, OutputArray dst, int code, int dstCn=0 )
 
-    Converts an image from one color space to another.
+.. ocv:pyfunction:: cv2.cvtColor(src, code[, dst[, dstCn]]) -> dst
+
+.. ocv:cfunction:: void cvCvtColor( const CvArr* src, CvArr* dst, int code )
+.. ocv:pyoldfunction:: cv.CvtColor(src, dst, code)-> None
 
     :param src: Source image: 8-bit unsigned, 16-bit unsigned ( ``CV_16UC...`` ), or single-precision floating-point.
 
@@ -399,22 +403,27 @@ The function can do the following transformations:
     columns, respectively. For example, the above pattern has a very
     popular "BG" type.
 
-.. index:: distanceTransform
-
-.. _distanceTransform:
 
 distanceTransform
 ---------------------
+Calculates the distance to the closest zero pixel for each pixel of the source image.
+
 .. ocv:function:: void distanceTransform( InputArray src, OutputArray dst, int distanceType, int maskSize )
 
 .. ocv:function:: void distanceTransform( InputArray src, OutputArray dst, OutputArray labels, int distanceType, int maskSize )
 
-    Calculates the distance to the closest zero pixel for each pixel of the source image.
+.. ocv:pyfunction:: cv2.distanceTransform(src, distanceType, maskSize[, dst[, labels]]) -> dst, labels
+
+.. ocv:cfunction:: void cvDistTransform( const CvArr* src, CvArr* dst, int distanceType=CV_DIST_L2, int maskSize=3, const float* mask=NULL, CvArr* labels=NULL )
+
+.. ocv:pyoldfunction:: cv.DistTransform(src, dst, distanceType=CV_DIST_L2, maskSize=3, mask=None, labels=None)-> None
 
     :param src: 8-bit, single-channel (binary) source image.
 
     :param dst: Output image with calculated distances. It is a 32-bit floating-point, single-channel image of the same size as  ``src`` .
+    
     :param distanceType: Type of distance. It can be  ``CV_DIST_L1, CV_DIST_L2`` , or  ``CV_DIST_C`` .
+    
     :param maskSize: Size of the distance transform mask. It can be 3, 5, or  ``CV_DIST_MASK_PRECISE``  (the latter option is only supported by the first function). In case of the ``CV_DIST_L1``  or  ``CV_DIST_C``  distance type, the parameter is forced to 3 because a  :math:`3\times 3`  mask gives the same result as  :math:`5\times 5`  or any larger aperture.
 
     :param labels: Optional output 2D array of labels (the discrete Voronoi diagram). It has the type  ``CV_32SC1``  and the same size as  ``src`` . See the details below.
@@ -423,11 +432,10 @@ The functions ``distanceTransform`` calculate the approximate or precise
 distance from every binary image pixel to the nearest zero pixel.
 For zero image pixels, the distance will obviously be zero.
 
-When ``maskSize == CV_DIST_MASK_PRECISE`` and ``distanceType == CV_DIST_L2`` , the function runs the algorithm described in
-Felzenszwalb04.
+When ``maskSize == CV_DIST_MASK_PRECISE`` and ``distanceType == CV_DIST_L2`` , the function runs the algorithm described in [Felzenszwalb04]_.
 
 In other cases, the algorithm
-Borgefors86
+[Borgefors86]_
 is used. This means that
 for a pixel the function finds the shortest path to the nearest zero pixel
 consisting of basic shifts: horizontal,
@@ -467,17 +475,22 @@ In this mode, the complexity is still linear.
 That is, the function provides a very fast way to compute the Voronoi diagram for a binary image.
 Currently, the second variant can use only the approximate distance transform algorithm.
 
-.. index:: floodFill
 
-.. _floodFill:
+
+
 
 floodFill
 -------------
+Fills a connected component with the given color.
+
 .. ocv:function:: int floodFill( InputOutputArray image, Point seed, Scalar newVal, Rect* rect=0, Scalar loDiff=Scalar(), Scalar upDiff=Scalar(),               int flags=4 )
 
 .. ocv:function:: int floodFill( InputOutputArray image, InputOutputArray mask, Point seed, Scalar newVal, Rect* rect=0, Scalar loDiff=Scalar(), Scalar upDiff=Scalar(), int flags=4 )
 
-    Fills a connected component with the given color.
+.. ocv:pyfunction:: cv2.floodFill(image, mask, seedPoint, newVal[, loDiff[, upDiff[, flags]]]) -> retval, rect
+
+.. ocv:cfunction:: void cvFloodFill( CvArr* image, CvPoint seedPoint, CvScalar newVal, CvScalar loDiff=cvScalarAll(0), CvScalar upDiff=cvScalarAll(0), CvConnectedComp* comp=NULL, int flags=4, CvArr* mask=NULL )
+.. ocv:pyoldfunction:: cv.FloodFill(image, seedPoint, newVal, loDiff=(0, 0, 0, 0), upDiff=(0, 0, 0, 0), flags=4, mask=None)-> comp
 
     :param image: Input/output 1- or 3-channel, 8-bit, or floating-point image. It is modified by the function unless the  ``FLOODFILL_MASK_ONLY``  flag is set in the second variant of the function. See the details below.
 
@@ -569,15 +582,20 @@ Use these functions to either mark a connected component with the specified colo
 See Also:
 :ocv:func:`findContours`
 
-.. index:: inpaint
 
-.. _inpaint:
+
+
 
 inpaint
 -----------
+Restores the selected region in an image using the region neighborhood.
+
 .. ocv:function:: void inpaint( InputArray src, InputArray inpaintMask, OutputArray dst, double inpaintRadius, int flags )
 
-    Restores the selected region in an image using the region neighborhood.
+.. ocv:pyfunction:: cv2.inpaint(src, inpaintMask, inpaintRange, flags[, dst]) -> dst
+
+.. ocv:cfunction:: void cvInpaint( const CvArr* src, const CvArr* mask, CvArr* dst, double inpaintRadius, int flags)
+.. ocv:pyoldfunction:: cv.Inpaint(src, mask, dst, inpaintRadius, flags) -> None
 
     :param src: Input 8-bit 1-channel or 3-channel image.
 
@@ -591,23 +609,32 @@ inpaint
 
             * **INPAINT_NS**   Navier-Stokes based method.
 
-            * **INPAINT_TELEA**        Method by Alexandru Telea  Telea04.
+            * **INPAINT_TELEA**        Method by Alexandru Telea  [Telea04]_.
 
 The function reconstructs the selected image area from the pixel near the area boundary. The function may be used to remove dust and scratches from a scanned photo, or to remove undesirable objects from still images or video. See
 http://en.wikipedia.org/wiki/Inpainting
 for more details.
 
-.. index:: integral
+
 
 integral
 ------------
+Calculates the integral of an image.
+
 .. ocv:function:: void integral( InputArray image, OutputArray sum, int sdepth=-1 )
 
 .. ocv:function:: void integral( InputArray image, OutputArray sum, OutputArray sqsum, int sdepth=-1 )
 
 .. ocv:function:: void integral( InputArray image, OutputArray sum,  OutputArray sqsum, OutputArray tilted, int sdepth=-1 )
 
-    Calculates the integral of an image.
+.. ocv:pyfunction:: cv2.integral(src[, sum[, sdepth]]) -> sum
+
+.. ocv:pyfunction:: cv2.integral2(src[, sum[, sqsum[, sdepth]]]) -> sum, sqsum
+
+.. ocv:pyfunction:: cv2.integral3(src[, sum[, sqsum[, tilted[, sdepth]]]]) -> sum, sqsum, tilted
+
+.. ocv:cfunction:: void cvIntegral( const CvArr* image, CvArr* sum, CvArr* sqsum=NULL, CvArr* tiltedSum=NULL )
+.. ocv:pyoldfunction:: cv.Integral(image, sum, sqsum=None, tiltedSum=None)-> None
 
     :param image: Source image as :math:`W \times H` , 8-bit or floating-point (32f or 64f).
 
@@ -645,15 +672,20 @@ As a practical example, the next figure shows the calculation of the integral of
 
 .. image:: pics/integral.png
 
-.. index:: threshold
 
-.. _threshold:
+
+
 
 threshold
 -------------
+Applies a fixed-level threshold to each array element.
+
 .. ocv:function:: double threshold( InputArray src, OutputArray dst, double thresh, double maxVal, int thresholdType )
 
-    Applies a fixed-level threshold to each array element.
+.. ocv:pyfunction:: cv2.threshold(src, thresh, maxval, type[, dst]) -> retval, dst
+
+.. ocv:cfunction:: double cvThreshold( const CvArr* src, CvArr* dst, double threshold, double maxValue, int thresholdType )
+.. ocv:pyoldfunction:: cv.Threshold(src, dst, threshold, maxValue, thresholdType)-> None
 
     :param src: Source array (single-channel, 8-bit of 32-bit floating point)
 
@@ -718,13 +750,15 @@ See Also:
 :ocv:func:`min`,
 :ocv:func:`max`
 
-.. index:: watershed
+
 
 watershed
 -------------
+Performs a marker-based image segmentation using the watershed algrorithm.
+
 .. ocv:function:: void watershed( InputArray image, InputOutputArray markers )
 
-    Performs a marker-based image segmentation using the watershed algrorithm.
+.. ocv:pyfunction:: cv2.watershed(image, markers) -> None
 
     :param image: Input 8-bit 3-channel image.
 
@@ -732,7 +766,7 @@ watershed
 
 The function implements one of the variants
 of watershed, non-parametric marker-based segmentation algorithm,
-described in [Meyer92]. Before passing the image to the
+described in [Meyer92]_. Before passing the image to the
 function, you have to roughly outline the desired regions in the image ``markers`` with positive (
 :math:`>0` ) indices. So, every region is
 represented as one or more connected components with the pixel values
@@ -756,14 +790,15 @@ can be found in the OpenCV samples directory (see the ``watershed.cpp`` demo).
 See Also:
 :ocv:func:`findContours`
 
-.. index:: grabCut
+
 
 grabCut
 -------
+Runs the GrabCut algorithm.
 
 .. ocv:function:: void grabCut(InputArray image, InputOutputArray mask, Rect rect, InputOutputArray bgdModel, InputOutputArray fgdModel, int iterCount, int mode )
 
-    Runs the GrabCut algorithm.
+.. ocv:pyfunction:: cv2.grabCut(img, mask, rect, bgdModel, fgdModel, iterCount[, mode]) -> None
 
     :param image: Input 8-bit 3-channel image.
 
@@ -793,3 +828,11 @@ grabCut
 
 The function implements the `GrabCut image segmentation algorithm <http://en.wikipedia.org/wiki/GrabCut>`_.
 See the sample grabcut.cpp to learn how to use the function.
+
+.. [Borgefors86] Borgefors, Gunilla, “Distance transformations in digital images”. Comput. Vision Graph. Image Process. 34 3, pp 344–371 (1986)
+
+.. [Felzenszwalb04] Felzenszwalb, Pedro F. and Huttenlocher, Daniel P. “Distance Transforms of Sampled Functions”, TR2004-1963, TR2004-1963 (2004)
+
+.. [Meyer92] Meyer, F. “Color image segmentation”, ICIP92, 1992
+
+.. [Telea04] Alexandru Telea, “An Image Inpainting Technique Based on the Fast Marching Method”. Journal of Graphics, GPU, and Game Tools 9 1, pp 23-34 (2004)
index 43b72eb..4c65082 100644 (file)
@@ -3,13 +3,16 @@ Motion Analysis and Object Tracking
 
 .. highlight:: cpp
 
-.. index:: accumulate
-
 accumulate
 --------------
+Adds an image to the accumulator.
+
 .. ocv:function:: void accumulate( InputArray src, InputOutputArray dst, InputArray mask=noArray() )
 
-    Adds an image to the accumulator.
+.. ocv:pyfunction:: cv2.accumulate(src, dst[, mask]) -> dst
+
+.. ocv:cfunction:: void cvAcc( const CvArr* src, CvArr* dst, const CvArr* mask=NULL )
+.. ocv:pyoldfunction:: cv.Acc(src, dst, mask=None)-> None
 
     :param src: Input image as 1- or 3-channel, 8-bit or 32-bit floating point.
 
@@ -27,18 +30,23 @@ The function supports multi-channel images. Each channel is processed independen
 
 The functions ``accumulate*`` can be used, for example, to collect statistics of a scene background viewed by a still camera and for the further foreground-background segmentation.
 
-See Also:
+.. seealso::
 :ocv:func:`accumulateSquare`,
 :ocv:func:`accumulateProduct`,
 :ocv:func:`accumulateWeighted`
 
-.. index:: accumulateSquare
+
 
 accumulateSquare
 --------------------
+Adds the square of a source image to the accumulator.
+
 .. ocv:function:: void accumulateSquare( InputArray src, InputOutputArray dst,  InputArray mask=noArray() )
 
-    Adds the square of a source image to the accumulator.
+.. ocv:pyfunction:: cv2.accumulateSquare(src, dst[, mask]) -> dst
+
+.. ocv:cfunction:: void cvSquareAcc( const CvArr* src, CvArr* dst, const CvArr* mask=NULL )
+.. ocv:pyoldfunction:: cv.SquareAcc(src, dst, mask=None)-> None
 
     :param src: Input image as 1- or 3-channel, 8-bit or 32-bit floating point.
 
@@ -46,36 +54,41 @@ accumulateSquare
 
     :param mask: Optional operation mask.
 
-The function adds the input image ``src`` or its selected region, raised to power 2, to the accumulator ``dst`` :
+The function adds the input image ``src`` or its selected region, raised to a power of 2, to the accumulator ``dst`` :
 
 .. math::
 
     \texttt{dst} (x,y)  \leftarrow \texttt{dst} (x,y) +  \texttt{src} (x,y)^2  \quad \text{if} \quad \texttt{mask} (x,y)  \ne 0
 
-The function supports multi-channel images Each channel is processed independently.
+The function supports multi-channel images. Each channel is processed independently.
 
-See Also:
+.. seealso::
 :ocv:func:`accumulateSquare`,
 :ocv:func:`accumulateProduct`,
 :ocv:func:`accumulateWeighted`
 
-.. index:: accumulateProduct
+
 
 accumulateProduct
 ---------------------
+Adds the per-element product of two input images to the accumulator.
+
 .. ocv:function:: void accumulateProduct( InputArray src1, InputArray src2, InputOutputArray dst, InputArray mask=noArray() )
 
-    Adds the per-element product of two input images to the accumulator.
+.. ocv:pyfunction:: cv2.accumulateProduct(src1, src2, dst[, mask]) -> dst
+
+.. ocv:cfunction:: void cvMultiplyAcc( const CvArr* src1, const CvArr* src2, CvArr* dst, const CvArr* mask=NULL )
+.. ocv:pyoldfunction:: cv.MultiplyAcc(src1, src2, dst, mask=None)-> None
 
-    :param src1: The first input image, 1- or 3-channel, 8-bit or 32-bit floating point.
+    :param src1: First input image, 1- or 3-channel, 8-bit or 32-bit floating point.
 
-    :param src2: The second input image of the same type and the same size as  ``src1`` .
+    :param src2: Second input image of the same type and the same size as  ``src1`` .
        
     :param dst: Accumulator with the same number of channels as input images, 32-bit or 64-bit floating-point.
 
     :param mask: Optional operation mask.
 
-The function adds the product of 2 images or their selected regions to the accumulator ``dst`` :
+The function adds the product of two images or their selected regions to the accumulator ``dst`` :
 
 .. math::
 
@@ -83,18 +96,23 @@ The function adds the product of 2 images or their selected regions to the accum
 
 The function supports multi-channel images. Each channel is processed independently.
 
-See Also:
+.. seealso::
 :ocv:func:`accumulate`,
 :ocv:func:`accumulateSquare`,
 :ocv:func:`accumulateWeighted`
 
-.. index:: accumulateWeighted
+
 
 accumulateWeighted
 ----------------------
+Updates a running average.
+
 .. ocv:function:: void accumulateWeighted( InputArray src, InputOutputArray dst, double alpha, InputArray mask=noArray() )
 
-    Updates a running average.
+.. ocv:pyfunction:: cv2.accumulateWeighted(src, dst, alpha[, mask]) -> dst
+
+.. ocv:cfunction:: void cvRunningAvg( const CvArr* src, CvArr* dst, double alpha, const CvArr* mask=NULL )
+.. ocv:pyoldfunction:: cv.RunningAvg(src, dst, alpha, mask=None)-> None
 
     :param src: Input image as 1- or 3-channel, 8-bit or 32-bit floating point.
 
@@ -113,7 +131,7 @@ The function calculates the weighted sum of the input image ``src`` and the accu
 That is, ``alpha`` regulates the update speed (how fast the accumulator "forgets" about earlier images).
 The function supports multi-channel images. Each channel is processed independently.
 
-See Also:
+.. seealso::
 :ocv:func:`accumulate`,
 :ocv:func:`accumulateSquare`,
 :ocv:func:`accumulateProduct` 
\ No newline at end of file
index 5c60a14..4faec8c 100644 (file)
@@ -3,13 +3,16 @@ Object Detection
 
 .. highlight:: cpp
 
-.. index:: matchTemplate
-
 matchTemplate
 -----------------
+Compares a template against overlapped image regions.
+
 .. ocv:function:: void matchTemplate( InputArray image, InputArray temp, OutputArray result, int method )
 
-    Compares a template against overlapped image regions.
+.. ocv:pyfunction:: cv2.matchTemplate(image, templ, method[, result]) -> result
+
+.. ocv:cfunction:: void cvMatchTemplate( const CvArr* image, const CvArr* templ, CvArr* result, int method )
+.. ocv:pyoldfunction:: cv.MatchTemplate(image, templ, result, method)-> None
 
     :param image: Image where the search is running. It must be 8-bit or 32-bit floating-point.
 
index 8445d5a..a3218a6 100644 (file)
@@ -3,13 +3,24 @@ Structural Analysis and Shape Descriptors
 
 .. highlight:: cpp
 
-.. index:: moments
-
 moments
 -----------
+Calculates all of the moments up to the third order of a polygon or rasterized shape
+
 .. ocv:function:: Moments moments( InputArray array, bool binaryImage=false )
 
-    Calculates all of the moments up to the third order of a polygon or rasterized shape where the class ``Moments`` is defined as: ::
+.. ocv:pyfunction:: cv2.moments(array[, binaryImage]) -> retval
+
+.. ocv:cfunction:: void cvMoments( const CvArr* array, CvMoments* moments, int binary=0 )
+.. ocv:pyoldfunction:: cv.Moments(array, binary=0) -> moments
+
+    :param array: A raster image (single-channel, 8-bit or floating-point 2D array) or an array ( :math:`1 \times N`  or  :math:`N \times 1` ) of 2D points (``Point``  or  ``Point2f`` ).
+
+    :param binaryImage: If it is true, all non-zero image pixels are treated as 1's. The parameter is used for images only.
+    
+    :param moments: The output moments
+
+The function computes moments, up to the 3rd order, of a vector shape or a rasterized shape. The results are returned in a structure ``Moments``, defined as: ::
 
     class Moments
     {
@@ -28,13 +39,8 @@ moments
         double  nu20, nu11, nu02, nu30, nu21, nu12, nu03;
     };
 
-    :param array: A raster image (single-channel, 8-bit or floating-point 2D array) or an array ( :math:`1 \times N`  or  :math:`N \times 1` ) of 2D points (``Point``  or  ``Point2f`` ).
-
-    :param binaryImage: If it is true, all non-zero image pixels are treated as 1's. The parameter is used for images only.
 
-The function computes moments, up to the 3rd order, of a vector shape or a rasterized shape.
-In case of a raster image, the spatial moments
-:math:`\texttt{Moments::m}_{ji}` are computed as:
+In case of a raster image, the spatial moments :math:`\texttt{Moments::m}_{ji}` are computed as:
 
 .. math::
 
@@ -75,20 +81,25 @@ See Also:
 :ocv:func:`contourArea`,
 :ocv:func:`arcLength`
 
-.. index:: HuMoments
+
 
 HuMoments
 -------------
+Calculates the seven Hu invariants.
+
 .. ocv:function:: void HuMoments( const Moments& moments, double h[7] )
 
-    Calculates the seven Hu invariants.
+.. ocv:pyfunction:: cv2.HuMoments(m) -> hu
+
+.. ocv:cfunction:: void cvGetHuMoments( const CvMoments* moments, CvHuMoments* hu )
+
+.. ocv:pyoldfunction:: cv.GetHuMoments(moments) -> hu
 
     :param moments: Input moments computed with  :ocv:func:`moments` .
     :param h: Output Hu invariants.
 
-The function calculates the seven Hu invariants (see
-http://en.wikipedia.org/wiki/Image_moment
-) defined as:
+The function calculates the seven Hu invariants (introduced in [Hu62]_; see also
+http://en.wikipedia.org/wiki/Image_moment) defined as:
 
 .. math::
 
@@ -103,15 +114,17 @@ These values are proved to be invariants to the image scale, rotation, and refle
 See Also:
 :ocv:func:`matchShapes`
 
-.. index:: findContours
 
 findContours
 ----------------
+Finds contours in a binary image.
+
 .. ocv:function:: void findContours( InputOutputArray image, OutputArrayOfArrays contours,                   OutputArray hierarchy, int mode, int method, Point offset=Point())
 
 .. ocv:function:: void findContours( InputOutputArray image, OutputArrayOfArrays contours, int mode, int method, Point offset=Point())
 
-    Finds contours in a binary image.
+.. ocv:cfunction:: int cvFindContours( CvArr* image, CvMemStorage* storage, CvSeq** firstContour, int headerSize=sizeof(CvContour), int mode=CV_RETR_LIST, int method=CV_CHAIN_APPROX_SIMPLE, CvPoint offset=cvPoint(0, 0) )
+.. ocv:pyoldfunction:: cv.FindContours(image, storage, mode=CV_RETR_LIST, method=CV_CHAIN_APPROX_SIMPLE, offset=(0, 0)) -> cvseq
 
     :param image: Source, an 8-bit single-channel image. Non-zero pixels are treated as 1's. Zero pixels remain 0's, so the image is treated as  ``binary`` . You can use  :ocv:func:`compare` ,  :ocv:func:`inRange` ,  :ocv:func:`threshold` ,  :ocv:func:`adaptiveThreshold` ,  :ocv:func:`Canny` , and others to create a binary image out of a grayscale or color one. The function modifies the  ``image``  while extracting the contours.
 
@@ -135,24 +148,28 @@ findContours
 
             * **CV_CHAIN_APPROX_SIMPLE** compresses horizontal, vertical, and diagonal segments and leaves only their end points. For example, an up-right rectangular contour is encoded with 4 points.
 
-            * **CV_CHAIN_APPROX_TC89_L1,CV_CHAIN_APPROX_TC89_KCOS** applies one of the flavors of the Teh-Chin chain approximation algorithm. See  TehChin89 for details.
+            * **CV_CHAIN_APPROX_TC89_L1,CV_CHAIN_APPROX_TC89_KCOS** applies one of the flavors of the Teh-Chin chain approximation algorithm. See  [TehChin89]_ for details.
 
     :param offset: Optional offset by which every contour point is shifted. This is useful if the contours are extracted from the image ROI and then they should be analyzed in the whole image context.
 
 The function retrieves contours from the binary image using the algorithm
-Suzuki85
-. The contours are a useful tool for shape analysis and object detection and recognition. See ``squares.c`` in the OpenCV sample directory.
+[Suzuki85]_. The contours are a useful tool for shape analysis and object detection and recognition. See ``squares.c`` in the OpenCV sample directory.
 
 **Note**:
 Source ``image`` is modified by this function.
 
-.. index:: drawContours
+
 
 drawContours
 ----------------
+Draws contours outlines or filled contours.
+
 .. ocv:function:: void drawContours( InputOutputArray image, InputArrayOfArrays contours,                   int contourIdx, const Scalar& color, int thickness=1, int lineType=8, InputArray hierarchy=noArray(), int maxLevel=INT_MAX, Point offset=Point() )
 
-    Draws contours outlines or filled contours.
+.. ocv:pyfunction:: cv2.drawContours(image, contours, contourIdx, color[, thickness[, lineType[, hierarchy[, maxLevel[, offset]]]]]) -> None
+
+.. ocv:cfunction:: void cvDrawContours( CvArr *img, CvSeq* contour, CvScalar externalColor, CvScalar holeColor, int maxLevel, int thickness=1, int lineType=8 )
+.. ocv:pyoldfunction:: cv.DrawContours(img, contour, externalColor, holeColor, maxLevel, thickness=1, lineType=8, offset=(0, 0))-> None
 
     :param image: Destination image.
 
@@ -217,34 +234,79 @@ The function draws contour outlines in the image if
         waitKey(0);
     }
 
-.. index:: approxPolyDP
+
 
 approxPolyDP
 ----------------
+Approximates a polygonal curve(s) with the specified precision.
+
 .. ocv:function:: void approxPolyDP( InputArray curve, OutputArray approxCurve, double epsilon, bool closed )
 
-    Approximates a polygonal curve(s) with the specified precision.
+.. ocv:pyfunction:: cv2.approxPolyDP(curve, epsilon, closed[, approxCurve]) -> approxCurve
+
+.. ocv:cfunction:: CvSeq* cvApproxPoly( const void* curve, int headerSize, CvMemStorage* storage, int method, double epsilon, int recursive=0 )
 
-    :param curve: Input vector of 2d point, stored in ``std::vector`` or ``Mat``.
+    :param curve: Input vector of 2d point, stored in:
+        
+        * ``std::vector`` or ``Mat`` (C++ interface)
+        
+        * ``Nx2`` numpy array (Python interface).
+        
+        * ``CvSeq`` or `` ``CvMat`` (C interface) 
 
-    :param approxCurve: Result of the approximation. The type should match the type of the input curve.
+    :param approxCurve: Result of the approximation. The type should match the type of the input curve. In the case of C interface the approximated curve is stored in the memory storage and pointer to it is returned.
 
     :param epsilon: Parameter specifying the approximation accuracy. This is the maximum distance between the original curve and its approximation.
 
     :param closed: If true, the approximated curve is closed (its first and last vertices are connected). Otherwise, it is not closed.
+    
+    :param headerSize: Header size of the approximated curve. Normally, ``sizeof(CvContour)`` is used.
+    
+    :param storage: Memory storage where the approximated curve will be stored.
+    
+    :param method: The contour approximation algorithm. Only ``CV_POLY_APPROX_DP`` is supported.
+    
+    :param recursive: The recursion flag. If it is non-zero and ``curve`` is ``CvSeq*``, the function ``cvApproxPoly`` will approximate all the contours accessible from ``curve`` by ``h_next`` and ``v_next`` links.
 
 The functions ``approxPolyDP`` approximate a curve or a polygon with another curve/polygon with less vertices, so that the distance between them is less or equal to the specified precision. It uses the Douglas-Peucker algorithm
 http://en.wikipedia.org/wiki/Ramer-Douglas-Peucker_algorithm
 
 See http://code.ros.org/svn/opencv/trunk/opencv/samples/cpp/contours.cpp on how to use the function.
 
-.. index:: arcLength
+
+ApproxChains
+-------------
+Approximates Freeman chain(s) with a polygonal curve.
+
+.. ocv:cfunction:: CvSeq* cvApproxChains( CvSeq* chain, CvMemStorage* storage, int method=CV_CHAIN_APPROX_SIMPLE, double parameter=0, int minimalPerimeter=0, int recursive=0 )
+
+.. ocv:pyoldfunction:: cv.ApproxChains(chain, storage, method=CV_CHAIN_APPROX_SIMPLE, parameter=0, minimalPerimeter=0, recursive=0)-> contours
+    
+    :param chain: Pointer to the approximated Freeman chain that can refer to other chains     
+    
+    :param storage: Storage location for the resulting polylines 
+    
+    :param method: Approximation method (see the description of the function  :ref:`FindContours` ) 
+    
+    :param parameter: Method parameter (not used now) 
+    
+    :param minimalPerimeter: Approximates only those contours whose perimeters are not less than  ``minimal_perimeter`` . Other chains are removed from the resulting structure   
+    
+    :param recursive: Recursion flag. If it is non-zero, the function approximates all chains that can be obtained to from  ``chain``  by using the  ``h_next``  or  ``v_next`` links. Otherwise, the single input chain is approximated.
+    
+This is a stand-alone contour approximation routine, not represented in the new interface. When :ocv:cfunc:`FindContours` retrieves contours as Freeman chains, it calls to the function to get approximated contours, represented as polygons.
+
 
 arcLength
 -------------
+Calculates a contour perimeter or a curve length.
+
 .. ocv:function:: double arcLength( InputArray curve, bool closed )
 
-    Calculates a contour perimeter or a curve length.
+.. ocv:pyfunction:: cv2.arcLength(curve, closed) -> retval
+
+.. ocv:cfunction:: double cvArcLength( const void* curve, CvSlice slice=CV_WHOLE_SEQ, int isClosed=-1 )
+.. ocv:pyoldfunction:: cv.ArcLength(curve, slice=CV_WHOLE_SEQ, isClosed=-1)-> double
 
     :param curve: Input vector of 2D points, stored in ``std::vector`` or ``Mat``.
 
@@ -252,26 +314,36 @@ arcLength
 
 The function computes a curve length or a closed contour perimeter.
 
-.. index:: boundingRect
+
 
 boundingRect
 ----------------
+Calculates the up-right bounding rectangle of a point set.
+
 .. ocv:function:: Rect boundingRect( InputArray points )
 
-    Calculates the up-right bounding rectangle of a point set.
+.. ocv:pyfunction:: cv2.boundingRect(points) -> retval
+
+.. ocv:cfunction:: CvRect cvBoundingRect( CvArr* points, int update=0 )
+.. ocv:pyoldfunction:: cv.BoundingRect(points, update=0)-> CvRect
 
     :param points: Input 2D point set, stored in ``std::vector`` or ``Mat``.
 
 The function calculates and returns the minimal up-right bounding rectangle for the specified point set.
 
 
-.. index:: contourArea
+
 
 contourArea
 ---------------
+Calculates a contour area.
+
 .. ocv:function:: double contourArea( InputArray contour, bool oriented=false )
 
-    Calculates a contour area.
+.. ocv:pyfunction:: cv2.contourArea(contour[, oriented]) -> retval
+
+.. ocv:cfunction:: double cvContourArea( const CvArr* contour, CvSlice slice=CV_WHOLE_SEQ )
+.. ocv:pyoldfunction:: cv.ContourArea(contour, slice=CV_WHOLE_SEQ)-> double
 
     :param contour: Input vector of 2d points (contour vertices), stored in ``std::vector`` or ``Mat``.
     :param orientation: Oriented area flag. If it is true, the function returns a signed area value, depending on the contour orientation (clockwise or counter-clockwise). Using this feature you can determine orientation of a contour by taking sign of the area. By default the parameter is ``false``, which means that the absolute value is returned.
@@ -297,46 +369,97 @@ Here is a short example: ::
             "area1 =" << area1 << endl <<
             "approx poly vertices" << approx.size() << endl;
 
-.. index:: convexHull
+
 
 convexHull
 --------------
+Finds the convex hull of a point set.
+
 .. ocv:function:: void convexHull( InputArray points, OutputArray hull, bool clockwise=false, bool returnPoints=true )
 
-    Finds the convex hull of a point set.
+.. ocv:pyfunction:: cv2.convexHull(points[, hull[, returnPoints[, clockwise]]]) -> hull
+
+.. ocv:cfunction:: CvSeq* cvConvexHull2( const CvArr* input, void* storage=NULL, int orientation=CV_CLOCKWISE, int returnPoints=0 )
+
+.. ocv:pyoldfunction:: cv.ConvexHull2(points, storage, orientation=CV_CLOCKWISE, returnPoints=0)-> convexHull
 
     :param points: Input 2D point set, stored in ``std::vector`` or ``Mat``.
 
     :param hull: Output convex hull. It is either an integer vector of indices or vector of points. In the first case the ``hull`` elements are 0-based indices of the convex hull points in the original array (since the set of convex hull points is a subset of the original point set). In the second case ``hull`` elements will be the convex hull points themselves.
+    
+    :param storage: The output memory storage in the old API (``cvConvexHull2`` returns a sequence containing the convex hull points or their indices).
 
     :param clockwise: Orientation flag. If true, the output convex hull will be oriented clockwise. Otherwise, it will be oriented counter-clockwise. The usual screen coordinate system is assumed where the origin is at the top-left corner, x axis is oriented to the right, and y axis is oriented downwards.
     
+    :param orientation: Convex hull orientation parameter in the old API, ``CV_CLOCKWISE`` or ``CV_COUNTERCLOCKWISE``.
+    
     :param returnPoints: Operation flag. In the case of matrix, when the flag is true, the function will return convex hull points, otherwise it will return indices of the convex hull points. When the output array is ``std::vector``, the flag is ignored, and the output depends on the type of the vector - ``std::vector<int>`` implies ``returnPoints=true``, ``std::vector<Point>`` implies ``returnPoints=false``.
 
 The functions find the convex hull of a 2D point set using the Sklansky's algorithm
-Sklansky82
+[Sklansky82]_
 that has
 *O(N logN)* complexity in the current implementation. See the OpenCV sample ``convexhull.cpp`` that demonstrates the usage of different function variants.
 
-.. index:: fitEllipse
+
+ConvexityDefects
+----------------
+Finds the convexity defects of a contour.
+
+.. ocv:cfunction:: CvSeq* cvConvexityDefects(  const CvArr* contour, const CvArr* convexhull, CvMemStorage* storage=NULL )
+
+.. ocv:pyoldfunction:: cv.ConvexityDefects(contour, convexhull, storage)-> convexityDefects
+
+    :param contour: Input contour 
+    
+    :param convexhull: Convex hull obtained using  :ocv:cfunc:`ConvexHull2`  that should contain pointers or indices to the contour points, not the hull points themselves (the  ``returnPoints``  parameter in  :ocv:cfunc:`ConvexHull2`  should be 0) 
+    
+    :param storage: Container for the output sequence of convexity defects. If it is NULL, the contour or hull (in that order) storage is used 
+    
+The function finds all convexity defects of the input contour and returns a sequence of the ``CvConvexityDefect`` structures, where ``CvConvexityDetect`` is defined as: ::
+
+     struct CvConvexityDefect
+     {
+        CvPoint* start; // point of the contour where the defect begins
+        CvPoint* end; // point of the contour where the defect ends
+        CvPoint* depth_point; // the farthest from the convex hull point within the defect
+        float depth; // distance between the farthest point and the convex hull
+     };
+
+Here is the picture displaying convexity defects of a hand contour:
+
+.. image:: pics/defects.png
 
 fitEllipse
 --------------
+Fits an ellipse around a set of 2D points.
+
 .. ocv:function:: RotatedRect fitEllipse( InputArray points )
 
-    Fits an ellipse around a set of 2D points.
+.. ocv:pyfunction:: cv2.fitEllipse(points) -> retval
+
+.. ocv:cfunction:: CvBox2D cvFitEllipse2( const CvArr* points )
+.. ocv:pyoldfunction:: cv.FitEllipse2(points)-> Box2D
 
-    :param points: Input vector of 2D points, stored in ``std::vector<>`` or ``Mat``.
+    :param points: The input 2D point set, stored in:
+    
+        * ``std::vector<>`` or ``Mat`` (C++ interface).
+
+        * ``CvSeq*`` or ``CvMat*`` (C interface)
 
-The function calculates the ellipse that fits (in least-squares sense) a set of 2D points best of all. It returns the rotated rectangle in which the ellipse is inscribed.
+        * Nx2 numpy array (Python interface)
 
-.. index:: fitLine
+The function calculates the ellipse that fits (in least-squares sense) a set of 2D points best of all. It returns the rotated rectangle in which the ellipse is inscribed. The algorithm [Fitzgibbon95]_ is used.
 
 fitLine
 -----------
+Fits a line to a 2D or 3D point set.
+
 .. ocv:function:: void fitLine( InputArray points, OutputArray line, int distType, double param, double reps, double aeps )
 
-    Fits a line to a 2D or 3D point set.
+.. ocv:pyfunction:: cv2.fitLine(points, distType, param, reps, aeps) -> line
+
+.. ocv:cfunction:: void cvFitLine( const CvArr* points, int distType, double param, double reps, double aeps, float* line )
+.. ocv:pyoldfunction:: cv.FitLine(points, distType, param, reps, aeps) -> line
 
     :param points: Input vector of 2D or 3D points, stored in ``std::vector<>`` or ``Mat``.
 
@@ -396,39 +519,74 @@ http://en.wikipedia.org/wiki/M-estimator
 :math:`w_i` are adjusted to be inversely proportional to
 :math:`\rho(r_i)` .
 
-.. index:: isContourConvex
+
 
 isContourConvex
 -------------------
+Tests a contour convexity.
+
 .. ocv:function:: bool isContourConvex( InputArray contour )
 
-    Tests a contour convexity.
+.. ocv:pyfunction:: cv2.isContourConvex(contour) -> retval
 
-    :param contour: The input vector of 2D points, stored in ``std::vector<>`` or ``Mat``.
+.. ocv:cfunction:: int cvCheckContourConvexity( const CvArr* contour )
+.. ocv:pyoldfunction:: cv.CheckContourConvexity(contour)-> int
+
+    :param contour: The input vector of 2D points, stored in:
+    
+            * ``std::vector<>`` or ``Mat`` (C++ interface).
+
+            * ``CvSeq*`` or ``CvMat*`` (C interface)
+
+            * Nx2 numpy array (Python interface)
 
 The function tests whether the input contour is convex or not. The contour must be simple, that is, without self-intersections. Otherwise, the function output is undefined.
 
-.. index:: minAreaRect
+
 
 minAreaRect
 ---------------
+Finds a rotated rectangle of the minimum area enclosing the input 2D point set.
+
 .. ocv:function:: RotatedRect minAreaRect( InputArray points )
 
-    Finds a rotated rectangle of the minimum area enclosing the input 2D point set.
+.. ocv:pyfunction:: cv2.minAreaRect(points) -> retval
 
-    :param points: The input vector of 2D points, stored in ``std::vector<>`` or ``Mat``.
+.. ocv:cfunction:: CvBox2D cvMinAreaRect2( const CvArr* points, CvMemStorage* storage=NULL )
+
+.. ocv:pyoldfunction:: cv.MinAreaRect2(points, storage=None)-> CvBox2D
+
+    :param points: The input vector of 2D points, stored in:
+    
+        * ``std::vector<>`` or ``Mat`` (C++ interface).
+        
+        * ``CvSeq*`` or ``CvMat*`` (C interface)
+        
+        * Nx2 numpy array (Python interface)
 
 The function calculates and returns the minimum-area bounding rectangle (possibly rotated) for a specified point set. See the OpenCV sample ``minarea.cpp`` .
 
-.. index:: minEnclosingCircle
+
 
 minEnclosingCircle
 ----------------------
+Finds a circle of the minimum area enclosing a 2D point set.
+
 .. ocv:function:: void minEnclosingCircle( InputArray points, Point2f& center, float& radius )
 
-    Finds a circle of the minimum area enclosing a 2D point set.
+.. ocv:pyfunction:: cv2.minEnclosingCircle(points, center, radius) -> None
+
+.. ocv:cfunction:: int cvMinEnclosingCircle( const CvArr* points, CvPoint2D32f* center, float* radius )
 
-    :param points: The input vector of 2D points, stored in ``std::vector<>`` or ``Mat``.
+.. ocv:pyoldfunction:: cv.MinEnclosingCircle(points)-> (int, center, radius)
+
+    :param points: The input vector of 2D points, stored in:
+    
+        * ``std::vector<>`` or ``Mat`` (C++ interface).
+        
+        * ``CvSeq*`` or ``CvMat*`` (C interface)
+        
+        * Nx2 numpy array (Python interface)
 
     :param center: Output center of the circle.
 
@@ -436,13 +594,18 @@ minEnclosingCircle
 
 The function finds the minimal enclosing circle of a 2D point set using an iterative algorithm. See the OpenCV sample ``minarea.cpp`` .
 
-.. index:: matchShapes
+
 
 matchShapes
 ---------------
+Compares two shapes.
+
 .. ocv:function:: double matchShapes( InputArray object1, InputArray object2, int method, double parameter=0 )
 
-    Compares two shapes.
+.. ocv:pyfunction:: cv2.matchShapes(contour1, contour2, method, parameter) -> retval
+
+.. ocv:cfunction:: double cvMatchShapes( const void* object1, const void* object2, int method, double parameter=0 )
+.. ocv:pyoldfunction:: cv.MatchShapes(object1, object2, method, parameter=0)-> None
 
     :param object1: The first contour or grayscale image.
 
@@ -486,13 +649,18 @@ and
 :math:`A` and
 :math:`B` , respectively.
 
-.. index:: pointPolygonTest
+
 
 pointPolygonTest
 --------------------
+Performs a point-in-contour test.
+
 .. ocv:function:: double pointPolygonTest( InputArray contour, Point2f pt, bool measureDist )
 
-    Performs a point-in-contour test.
+.. ocv:pyfunction:: cv2.pointPolygonTest(contour, pt, measureDist) -> retval
+
+.. ocv:cfunction:: double cvPointPolygonTest( const CvArr* contour, CvPoint2D32f pt, int measureDist )
+.. ocv:pyoldfunction:: cv.PointPolygonTest(contour, pt, measureDist)-> double
 
     :param contour: Input contour.
 
@@ -512,3 +680,12 @@ Here is a sample output of the function where each image pixel is tested against
 
 .. image:: pics/pointpolygon.png
 
+.. [Fitzgibbon95] Andrew W. Fitzgibbon, R.B.Fisher. A Buyer’s Guide to Conic Fitting. Proc.5th British Machine Vision Conference, Birmingham, pp. 513-522, 1995.
+
+.. [Hu62] M. Hu. Visual Pattern Recognition by Moment Invariants, IRE Transactions on Information Theory, 8:2, pp. 179-187, 1962.
+
+.. [Sklansky82] Sklansky, J., “Finding the Convex Hull of a Simple Polygon”. PRL 1 $number, pp 79-83 (1982)
+
+.. [Suzuki85] Suzuki, S. and Abe, K., “Topological Structural Analysis of Digitized Binary Images by Border Following”. CVGIP 30 1, pp 32-46 (1985)
+
+.. [TehChin89] Teh, C.H. and Chin, R.T., “On the Detection of Dominant Points on Digital Curve”. PAMI 11 8, pp 859-872 (1989)
index 2238ad8..430b713 100644 (file)
@@ -3,13 +3,14 @@
 Boosting
 ========
 
+.. highlight:: cpp
+
 A common machine learning task is supervised learning. In supervised learning, the goal is to learn the functional relationship
 :math:`F: y = F(x)` between the input
 :math:`x` and the output
-:math:`y` . Predicting the qualitative output is called classification, while predicting the quantitative output is called regression.
+:math:`y` . Predicting the qualitative output is called *classification*, while predicting the quantitative output is called *regression*.
 
-Boosting is a powerful learning concept that provides a solution to the supervised classification learning task. It combines the performance of many "weak" classifiers to produce a powerful 'committee'
-:ref:`[HTF01] <HTF01>` . A weak classifier is only required to be better than chance, and thus can be very simple and computationally inexpensive. However, many of them smartly combine results to a strong classifier that often outperforms most "monolithic" strong classifiers such as SVMs and Neural Networks.??
+Boosting is a powerful learning concept that provides a solution to the supervised classification learning task. It combines the performance of many "weak" classifiers to produce a powerful committee [HTF01]_. A weak classifier is only required to be better than chance, and thus can be very simple and computationally inexpensive. However, many of them smartly combine results to a strong classifier that often outperforms most "monolithic" strong classifiers such as SVMs and Neural Networks.
 
 Decision trees are the most popular weak classifiers used in boosting schemes. Often the simplest decision trees with only a single split node per tree (called ``stumps`` ) are sufficient.
 
@@ -19,15 +20,16 @@ The boosted model is based on
 :math:`x_i \in{R^K}` and
 :math:`y_i \in{-1, +1}` .
 :math:`x_i` is a
-:math:`K` -component vector. Each component encodes a feature relevant for the learning task at hand. The desired two-class output is encoded as -1 and +1.
+:math:`K` -component vector. Each component encodes a feature relevant to the learning task at hand. The desired two-class output is encoded as -1 and +1.
 
-Different variants of boosting are known as Discrete Adaboost, Real AdaBoost, LogitBoost, and Gentle AdaBoost
-:ref:`[FHT98] <FHT98>` . All of them are very similar in their overall structure. Therefore, this chapter focuses only on the standard two-class Discrete AdaBoost algorithm as shown in the box below??. Each sample is initially assigned the same weight (step 2). Then, a weak classifier
+Different variants of boosting are known as Discrete Adaboost, Real AdaBoost, LogitBoost, and Gentle AdaBoost [FHT98]_. All of them are very similar in their overall structure. Therefore, this chapter focuses only on the standard two-class Discrete AdaBoost algorithm, outlined below. Initially the same weight is assigned to each sample (step 2). Then, a weak classifier
 :math:`f_{m(x)}` is trained on the weighted training data (step 3a). Its weighted training error and scaling factor
 :math:`c_m` is computed (step 3b). The weights are increased for training samples that have been misclassified (step 3c). All weights are then normalized, and the process of finding the next weak classifier continues for another
 :math:`M` -1 times. The final classifier
 :math:`F(x)` is the sign of the weighted sum over the individual weak classifiers (step 4).
 
+**Two-class Discrete AdaBoost Algorithm**
+
 #.
     Set
     :math:`N`     examples
@@ -39,175 +41,196 @@ Different variants of boosting are known as Discrete Adaboost, Real AdaBoost, Lo
     :math:`w_i = 1/N, i = 1,...,N`     .
 
 #.
-    Repeat for
-    :math:`m`     =
-    :math:`1,2,...,M`     :
+    Repeat for :math:`m = 1,2,...,M` :
 
-    #.
-        Fit the classifier
-        :math:`f_m(x) \in{-1,1}`         , using weights
-        :math:`w_i`         on the training data.
+    3.1. Fit the classifier :math:`f_m(x) \in{-1,1}`, using weights :math:`w_i` on the training data.
 
-    #.
-        Compute
-        :math:`err_m = E_w [1_{(y =\neq f_m(x))}], c_m = log((1 - err_m)/err_m)`         .
+    3.2. Compute :math:`err_m = E_w [1_{(y \neq f_m(x))}], c_m = log((1 - err_m)/err_m)`         .
 
-    #.
-        Set
-        :math:`w_i \Leftarrow w_i exp[c_m 1_{(y_i \neq f_m(x_i))}], i = 1,2,...,N,`         and renormalize so that
-        :math:`\Sigma i w_i = 1`         .
+    3.3. Set :math:`w_i \Leftarrow w_i exp[c_m 1_{(y_i \neq f_m(x_i))}], i = 1,2,...,N,` and renormalize so that :math:`\Sigma i w_i = 1`         .
 
-    #.
-        Output the classifier sign
-        :math:`[\Sigma m = 1M c_m f_m(x)]`         .
 
-Two-class Discrete AdaBoost Algorithm: Training (steps 1 to 3) and Evaluation (step 4)??you need to revise this section. what is this? a title for the image that is missing?
+#. Classify new samples *x* using the formula: :math:`\textrm{sign} (\Sigma m = 1M c_m f_m(x))`         .
 
-**NOTE:**
 
-Similar to the classical boosting methods, the current implementation supports two-class classifiers only. For M
-:math:`>` two classes, there is the
-**AdaBoost.MH**
-algorithm (described in
-:ref:`[FHT98] <FHT98>` ) that reduces the problem to the two-class problem, yet with a much larger training set.
+.. note:: Similar to the classical boosting methods, the current implementation supports two-class classifiers only. For ``M > 2`` classes, there is the **AdaBoost.MH** algorithm (described in [FHT98]_) that reduces the problem to the two-class problem, yet with a much larger training set.
 
-To reduce computation time for boosted models without substantially losing accuracy, the influence trimming technique may be employed. As the training algorithm proceeds and the number of trees in the ensemble is increased, a larger number of the training samples are classified correctly and with increasing confidence, thereby those samples receive smaller weights on the subsequent iterations. Examples with a very low relative weight have a small impact on the weak classifier training. Thus, such examples may be excluded during the weak classifier training without having much effect on the induced classifier. This process is controlled with the ``weight_trim_rate`` parameter. Only examples with the summary fraction ``weight_trim_rate`` of the total weight mass are used in the weak classifier training. Note that the weights for
+To reduce computation time for boosted models without substantially losing accuracy, the influence trimming technique can be employed. As the training algorithm proceeds and the number of trees in the ensemble is increased, a larger number of the training samples are classified correctly and with increasing confidence, thereby those samples receive smaller weights on the subsequent iterations. Examples with a very low relative weight have a small impact on the weak classifier training. Thus, such examples may be excluded during the weak classifier training without having much effect on the induced classifier. This process is controlled with the ``weight_trim_rate`` parameter. Only examples with the summary fraction ``weight_trim_rate`` of the total weight mass are used in the weak classifier training. Note that the weights for
 **all**
-training examples are recomputed at each training iteration. Examples deleted at a particular iteration may be used again for learning some of the weak classifiers further
-:ref:`[FHT98] <FHT98>` .
+training examples are recomputed at each training iteration. Examples deleted at a particular iteration may be used again for learning some of the weak classifiers further [FHT98]_.
 
-.. _HTF01:??what is this meant to be? it doesn't work
+.. [HTF01] Hastie, T., Tibshirani, R., Friedman, J. H. *The Elements of Statistical Learning: Data Mining, Inference, and Prediction*. Springer Series in Statistics. 2001.
 
-[HTF01] Hastie, T., Tibshirani, R., Friedman, J. H. *The Elements of Statistical Learning: Data Mining, Inference, and Prediction. Springer Series in Statistics*. 2001.
+.. [FHT98] Friedman, J. H., Hastie, T. and Tibshirani, R. *Additive Logistic Regression: a Statistical View of Boosting*. Technical Report, Dept. of Statistics, Stanford University, 1998.
 
-.. _FHT98:??the same comment
+CvBoostParams
+-------------
+.. ocv:class:: CvBoostParams
 
-[FHT98] Friedman, J. H., Hastie, T. and Tibshirani, R. Additive Logistic Regression: a Statistical View of Boosting. Technical Report, Dept. of Statistics*, Stanford University, 1998.
+    Boosting training parameters.
 
-.. index:: CvBoostParams
+The structure is derived from :ocv:class:`CvDTreeParams` but not all of the decision tree parameters are supported. In particular, cross-validation is not supported.
 
-.. _CvBoostParams:
+All parameters are public. You can initialize them by a constructor and then override some of them directly if you want.
 
-CvBoostParams
--------------
-.. c:type:: CvBoostParams
+CvBoostParams::CvBoostParams
+----------------------------
+The constructors.
 
-Boosting training parameters ::
+.. ocv:function:: CvBoostParams::CvBoostParams()
 
-    struct CvBoostParams : public CvDTreeParams
-    {
-        int boost_type;
-        int weak_count;
-        int split_criteria;
-        double weight_trim_rate;
+.. ocv:function:: CvBoostParams::CvBoostParams( int boost_type, int weak_count, double weight_trim_rate, int max_depth, bool use_surrogates, const float* priors )
 
-        CvBoostParams();
-        CvBoostParams( int boost_type, int weak_count, double weight_trim_rate,
-                       int max_depth, bool use_surrogates, const float* priors );
-    };
+    :param boost_type: Type of the boosting algorithm. Possible values are:
+        
+        * **CvBoost::DISCRETE** Discrete AbaBoost.
+        * **CvBoost::REAL** Real AdaBoost. It is a technique that utilizes confidence-rated predictions and works well with categorical data.
+        * **CvBoost::LOGIT** LogitBoost. It can produce good regression fits.
+        * **CvBoost::GENTLE** Gentle AdaBoost. It puts less weight on outlier data points and for that reason is often good with regression data. 
 
+        Gentle AdaBoost and Real AdaBoost are often the preferable choices. 
 
-The structure is derived from
-:ref:`CvDTreeParams`  but not all of the decision tree parameters are supported. In particular, cross-validation is not supported.
+    :param weak_count: The number of weak classifiers.
 
-.. index:: CvBoostTree
+    :param weight_trim_rate: A threshold between 0 and 1 used to save computational time. Samples with summary weight :math:`\leq 1 - weight\_trim\_rate` do not participate in the *next* iteration of training. Set this parameter to 0 to turn off this functionality.
 
-.. _CvBoostTree:
+See :ocv:func:`CvDTreeParams::CvDTreeParams` for description of other parameters.
 
-CvBoostTree
------------
-.. c:type:: CvBoostTree
+Also there is one structure member that you can set directly:
 
-Weak tree classifier ::
+.. ocv:member:: int split_criteria
 
-    class CvBoostTree: public CvDTree
-    {
-    public:
-        CvBoostTree();
-        virtual ~CvBoostTree();
+    Splitting criteria used to choose optimal splits during a weak tree construction. Possible values are:
 
-        virtual bool train( CvDTreeTrainData* _train_data,
-                            const Mat& subsample_idx, CvBoost* ensemble );
-        virtual void scale( double s );
-        virtual void read( CvFileStorage* fs, CvFileNode* node,
-                           CvBoost* ensemble, CvDTreeTrainData* _data );
-        virtual void clear();
+        * **CvBoost::DEFAULT** Use the default for the particular boosting method, see below.
+        * **CvBoost::GINI** Use Gini index. This is default option for Real AdaBoost; may be also used for Discrete AdaBoost.
+        * **CvBoost::MISCLASS** Use misclassification rate. This is default option for Discrete AdaBoost; may be also used for Real AdaBoost.
+        * **CvBoost::SQERR** Use least squares criteria. This is default and the only option for LogitBoost and Gentle AdaBoost.
 
-    protected:
-        ...
-        CvBoost* ensemble;
-    };
+Default parameters are:
 
+::
 
-The weak classifier, a component of the boosted tree classifier
-:ref:`CvBoost` , is a derivative of
-:ref:`CvDTree` . Normally, there is no need to use the weak classifiers directly. However, they can be accessed as elements of the sequence ``CvBoost::weak`` , retrieved by ``CvBoost::get_weak_predictors`` .
+    CvBoostParams::CvBoostParams()
+    {
+        boost_type = CvBoost::REAL;
+        weak_count = 100;
+        weight_trim_rate = 0.95;
+        cv_folds = 0;
+        max_depth = 1;
+    }
 
-**Note:**
+CvBoostTree
+-----------
+.. ocv:class:: CvBoostTree
 
-In case of LogitBoost and Gentle AdaBoost, each weak predictor is a regression tree, rather than a classification tree. Even in case of Discrete AdaBoost and Real AdaBoost, the ``CvBoostTree::predict`` return value ( ``CvDTreeNode::value`` ) is not an output class label. A negative value "votes" for class
-#
-0, a positive - for class
-#
-1. The votes are weighted. The weight of each individual tree may be increased or decreased using the method ``CvBoostTree::scale`` .
+The weak tree classifier, a component of the boosted tree classifier :ocv:class:`CvBoost`, is a derivative of :ocv:class:`CvDTree`. Normally, there is no need to use the weak classifiers directly. However, they can be accessed as elements of the sequence :ocv:member:`CvBoost::weak`, retrieved by :ocv:func:`CvBoost::get_weak_predictors`.
 
-.. index:: CvBoost
+.. note:: In case of LogitBoost and Gentle AdaBoost, each weak predictor is a regression tree, rather than a classification tree. Even in case of Discrete AdaBoost and Real AdaBoost, the ``CvBoostTree::predict`` return value (:ocv:member:`CvDTreeNode::value`) is not an output class label. A negative value "votes" for class #0, a positive value - for class #1. The votes are weighted. The weight of each individual tree may be increased or decreased using the method ``CvBoostTree::scale``.
 
 CvBoost
 -------
 .. ocv:class:: CvBoost
 
-Boosted tree classifier, derived from :ocv:class:`CvStatModel`
+Boosted tree classifier derived from :ocv:class:`CvStatModel`.
+
+CvBoost::CvBoost
+----------------
+Default and training constructors.
+
+.. ocv:function:: CvBoost::CvBoost()
+
+.. ocv:function:: CvBoost::CvBoost( const Mat& trainData, int tflag, const Mat& responses, const Mat& varIdx=Mat(), const Mat& sampleIdx=Mat(), const Mat& varType=Mat(), const Mat& missingDataMask=Mat(), CvBoostParams params=CvBoostParams() )
 
-.. index:: CvBoost::train
+.. ocv:function::CvBoost::CvBoost( const CvMat* trainData, int tflag, const CvMat* responses, const CvMat* varIdx=0, const CvMat* sampleIdx=0, const CvMat* varType=0, const CvMat* missingDataMask=0, CvBoostParams params=CvBoostParams() )
 
-.. _CvBoost::train:
+.. ocv:pyfunction:: cv2.Boost(trainData, tflag, responses[, varIdx[, sampleIdx[, varType[, missingDataMask[, params]]]]]) -> <Boost object>
+
+
+The constructors follow conventions of :ocv:func:`CvStatModel::CvStatModel`. See :ocv:func:`CvStatModel::train` for parameters descriptions.
 
 CvBoost::train
 --------------
-.. ocv:function:: bool CvBoost::train(  const Mat& _train_data, int _tflag, const Mat& _responses,  const Mat& _var_idx=Mat(), const Mat& _sample_idx=Mat(), const Mat& _var_type=Mat(), const Mat& _missing_mask=Mat(), CvBoostParams params=CvBoostParams(), bool update=false )
+Trains a boosted tree classifier.
+
+.. ocv:function:: bool CvBoost::train( const Mat& trainData, int tflag, const Mat& responses, const Mat& varIdx=Mat(), const Mat& sampleIdx=Mat(), const Mat& varType=Mat(), const Mat& missingDataMask=Mat(), CvBoostParams params=CvBoostParams(), bool update=false )
 
-    Trains a boosted tree classifier.
+.. ocv:function::bool CvBoost::train( const CvMat* trainData, int tflag, const CvMat* responses, const CvMat* varIdx=0, const CvMat* sampleIdx=0, const CvMat* varType=0, const CvMat* missingDataMask=0, CvBoostParams params=CvBoostParams(), bool update=false )
 
-The train method follows the common template. The last parameter ``update`` specifies whether the classifier needs to be updated (the new weak tree classifiers added to the existing ensemble) or the classifier needs to be rebuilt from scratch. The responses must be categorical, which means that boosted trees cannot be built for regression, and there should be two classes.
+.. ocv:function::bool CvBoost::train( CvMLData* data, CvBoostParams params=CvBoostParams(), bool update=false )
 
-.. index:: CvBoost::predict
+.. ocv:pyfunction:: cv2.Boost.train(trainData, tflag, responses[, varIdx[, sampleIdx[, varType[, missingDataMask[, params[, update]]]]]]) -> retval
 
-.. _CvBoost::predict:
+    :param update: Specifies whether the classifier needs to be updated (``true``, the new weak tree classifiers added to the existing ensemble) or the classifier needs to be rebuilt from scratch (``false``).
+
+The train method follows the common template of :ocv:func:`CvStatModel::train`. The responses must be categorical, which means that boosted trees cannot be built for regression, and there should be two classes.
 
 CvBoost::predict
 ----------------
-.. ocv:function:: float CvBoost::predict(  const Mat& sample, const Mat& missing=Mat(),                          const Range& slice=Range::all(), bool rawMode=false, bool returnSum=false ) const
+Predicts a response for an input sample.
+
+.. ocv:function:: float CvBoost::predict(  const Mat& sample, const Mat& missing=Mat(), const Range& slice=Range::all(), bool rawMode=false, bool returnSum=false ) const
+
+.. ocv:function::float CvBoost::predict( const CvMat* sample, const CvMat* missing=0, CvMat* weak_responses=0, CvSlice slice=CV_WHOLE_SEQ, bool raw_mode=false, bool return_sum=false ) const
+
+.. ocv:pyfunction:: cv2.Boost.predict(sample[, missing[, slice[, rawMode[, returnSum]]]]) -> retval
+
+    :param sample: Input sample.
+
+    :param missing: Optional mask of missing measurements. To handle missing measurements, the weak classifiers must include surrogate splits (see ``CvDTreeParams::use_surrogates``).
 
-    Predicts a response for an input sample.
+    :param weak_responses: Optional output parameter, a floating-point vector with responses of each individual weak classifier. The number of elements in the vector must be equal to the slice length.
 
-The method ``CvBoost::predict`` runs the sample through the trees in the ensemble and returns the output class label based on the weighted voting.
+    :param slice: Continuous subset of the sequence of weak classifiers to be used for prediction. By default, all the weak classifiers are used. 
 
-.. index:: CvBoost::prune
+    :param raw_mode: Normally, it should be set to ``false``.
+    
+    :param return_sum: If ``true`` then return sum of votes instead of the class label.
 
-.. _CvBoost::prune:
+The method runs the sample through the trees in the ensemble and returns the output class label based on the weighted voting.
 
 CvBoost::prune
 --------------
-.. ocv:function:: void CvBoost::prune( CvSlice slice )
+Removes the specified weak classifiers.
 
-    Removes the specified weak classifiers.
+.. ocv:function::void CvBoost::prune( CvSlice slice )
+
+.. ocv:pyfunction:: cv2.Boost.prune(slice) -> None
+
+    :param slice: Continuous subset of the sequence of weak classifiers to be removed.
 
 The method removes the specified weak classifiers from the sequence. 
 
-**Note:**
+.. note:: Do not confuse this method with the pruning of individual decision trees, which is currently not supported.
+
 
-Do not confuse this method with the pruning of individual decision trees, which is currently not supported.
+CvBoost::calc_error
+-------------------
+Returns error of the boosted tree classifier.
 
-.. index:: CvBoost::get_weak_predictors
+.. ocv:function::float CvBoost::calc_error( CvMLData* _data, int type , std::vector<float> *resp = 0 )
+
+The method is identical to :ocv:func:`CvDTree::calc_error` but uses the boosted tree classifier as predictor.
 
-.. _CvBoost::get_weak_predictors:
 
 CvBoost::get_weak_predictors
 ----------------------------
-.. ocv:function:: CvSeq* CvBoost::get_weak_predictors()
+Returns the sequence of weak tree classifiers.
+
+.. ocv:function::CvSeq* CvBoost::get_weak_predictors()
+
+The method returns the sequence of weak classifiers. Each element of the sequence is a pointer to the :ocv:class:`CvBoostTree` class or to some of its derivatives.
+
+CvBoost::get_params
+-------------------
+Returns current parameters of the boosted tree classifier.
+
+.. ocv:function:: const CvBoostParams& CvBoost::get_params() const
+
 
-    Returns the sequence of weak tree classifiers.
+CvBoost::get_data
+-----------------
+Returns used train data of the boosted tree classifier.
 
-The method returns the sequence of weak classifiers. Each element of the sequence is a pointer to the ``CvBoostTree`` class or, probably, to some of its derivatives.
+.. ocv:function::const CvDTreeTrainData* CvBoost::get_data() const
 
index 8324905..88427b7 100644 (file)
@@ -1,15 +1,14 @@
 Decision Trees
 ==============
 
-The ML classes discussed in this section implement Classification and Regression Tree algorithms described in `[Breiman84] <#paper_Breiman84>`_
-.
+The ML classes discussed in this section implement Classification and Regression Tree algorithms described in [Breiman84]_.
 
 The class
-:ref:`CvDTree` represents a single decision tree that may be used alone, or as a base class in tree ensembles (see
+:ocv:class:`CvDTree` represents a single decision tree that may be used alone or as a base class in tree ensembles (see
 :ref:`Boosting` and
 :ref:`Random Trees` ).
 
-A decision tree is a binary tree (tree where each non-leaf node has exactly two child nodes). It can be used either for classification or for regression. For classification, each tree leaf is marked with a class label; multiple leafs may have the same label. For regression, a constant is also assigned to each tree leaf, so the approximation function is piecewise constant.
+A decision tree is a binary tree (tree where each non-leaf node has two child nodes). It can be used either for classification or for regression. For classification, each tree leaf is marked with a class label; multiple leaves may have the same label. For regression, a constant is also assigned to each tree leaf, so the approximation function is piecewise constant.
 
 Predicting with Decision Trees
 ------------------------------
@@ -22,7 +21,7 @@ value of a certain variable whose index is stored in the observed
 node. The following variables are possible:
 
 * 
-  **Ordered variables.** The variable value is compared with a threshold that is also stored in the node). If the value is less than the threshold, the procedure goes to the left. Otherwise, it goes to the right. For example, if the weight is less than 1 kilogram, the procedure goes to the left, else to the right.
+  **Ordered variables.** The variable value is compared with a threshold that is also stored in the node. If the value is less than the threshold, the procedure goes to the left. Otherwise, it goes to the right. For example, if the weight is less than 1 kilogram, the procedure goes to the left, else to the right.
 * 
   **Categorical variables.**  A discrete variable value is tested to see whether it belongs to a certain subset of values (also stored in the node) from a limited set of values the variable could take. If it does, the procedure goes to the left. Otherwise, it goes to the right. For example, if the color is green or red, go to the left, else to the right.
 
@@ -36,7 +35,7 @@ Sometimes, certain features of the input vector are missed (for example, in the
 Training Decision Trees
 -----------------------
 
-The tree is built recursively, starting from the root node. All training data (feature vectors and responses) is used to split the root node. In each node the optimum decision rule (the best "primary" split) is found based on some criteria. In ML, ``gini`` "purity" criteria are used for classification, and sum of squared errors is used for regression. Then, if necessary, the surrogate splits are found. They resemble the results of the primary split on the training data. All the data is divided using the primary and the surrogate splits (like it is done in the prediction procedure) between the left and the right child node. Then, the procedure recursively splits both left and right nodes. At each node the recursive procedure may stop (that is, stop splitting the node further) in one of the following cases:
+The tree is built recursively, starting from the root node. All training data (feature vectors and responses) is used to split the root node. In each node the optimum decision rule (the best "primary" split) is found based on some criteria. In machine learning, ``gini`` "purity" criteria are used for classification, and sum of squared errors is used for regression. Then, if necessary, the surrogate splits are found. They resemble the results of the primary split on the training data. All the data is divided using the primary and the surrogate splits (like it is done in the prediction procedure) between the left and the right child node. Then, the procedure recursively splits both left and right nodes. At each node the recursive procedure may stop (that is, stop splitting the node further) in one of the following cases:
 
 * Depth of the constructed tree branch has reached the specified maximum value.
 
@@ -46,7 +45,7 @@ The tree is built recursively, starting from the root node. All training data (f
 
 * The best found split does not give any noticeable improvement compared to a random choice.
 
-When the tree is built, it may be pruned using a cross-validation procedure, if necessary. That is, some branches of the tree that may lead to the model overfitting are cut off. Normally, this procedure is only applied to standalone decision trees. Tree ensembles usually build trees that are small enough and use their own protection schemes against overfitting.
+When the tree is built, it may be pruned using a cross-validation procedure, if necessary. That is, some branches of the tree that may lead to the model overfitting are cut off. Normally, this procedure is only applied to standalone decision trees. Usually tree ensembles build trees that are small enough and use their own protection schemes against overfitting.
 
 Variable Importance
 -------------------
@@ -55,372 +54,270 @@ Besides the prediction that is an obvious use of decision trees, the tree can be
 
 Importance of each variable is computed over all the splits on this variable in the tree, primary and surrogate ones. Thus, to compute variable importance correctly, the surrogate splits must be enabled in the training parameters, even if there is no missing data.
 
-[Breiman84] Breiman, L., Friedman, J. Olshen, R. and Stone, C. (1984), *Classification and Regression Trees*, Wadsworth.
-
-.. index:: CvDTreeSplit
-
-.. _CvDTreeSplit:
 
 CvDTreeSplit
 ------------
-.. c:type:: CvDTreeSplit
+.. ocv:class:: CvDTreeSplit
 
-Decision tree node split ::
 
-    struct CvDTreeSplit
-    {
-        int var_idx;
-        int inversed;
-        float quality;
-        CvDTreeSplit* next;
-        union
-        {
-            int subset[2];
-            struct
-            {
-                float c;
-                int split_point;
-            }
-            ord;
-        };
-    };
+The structure represents a possible decision tree node split. It has public members:
 
+.. ocv:member:: int var_idx
 
-.. index:: CvDTreeNode
+    Index of variable on which the split is created.
 
-.. _CvDTreeNode:
+.. ocv:member:: int inversed
 
-CvDTreeNode
------------
-.. c:type:: CvDTreeNode
+    If it is not null then inverse split rule is used that is left and right branches are exchanged in the rule expressions below. 
 
-Decision tree node ::
+.. ocv:member:: float quality
 
-    struct CvDTreeNode
-    {
-        int class_idx;
-        int Tn;
-        double value;
+    The split quality, a positive number. It is used to choose the best primary split, then to choose and sort the surrogate splits. After the tree is constructed, it is also used to compute variable importance. 
 
-        CvDTreeNode* parent;
-        CvDTreeNode* left;
-        CvDTreeNode* right;
+.. ocv:member:: CvDTreeSplit* next
 
-        CvDTreeSplit* split;
+    Pointer to the next split in the node list of splits.
 
-        int sample_count;
-        int depth;
-        ...
-    };
+.. ocv:member:: int subset[2]
 
+    Bit array indicating the value subset in case of split on a categorical variable. The rule is:
 
-Other numerous fields of ``CvDTreeNode`` are used internally at the training stage.
+::
 
-.. index:: CvDTreeParams
+    if var_value in subset 
+      then next_node <- left 
+      else next_node <- right
 
-.. _CvDTreeParams:
+.. ocv:member:: float ord.c 
 
-CvDTreeParams
--------------
-.. c:type:: CvDTreeParams
+    The threshold value in case of split on an ordered variable. The rule is: 
 
-    Decision tree training parameters.
+::
 
-The structure contains all the decision tree training parameters. You can initialize it by default constructor and then override any parameters directly before training, or the structure may be fully initialized using the advanced variant of the constructor.
+    if var_value < c 
+      then next_node<-left 
+      else next_node<-right
 
-.. index:: CvDTreeParams::CvDTreeParams
+.. ocv:member:: int ord.split_point
 
-.. _CvDTreeParams::CvDTreeParams
+    Used internally by the training algorithm.
 
-CvDTreeParams::CvDTreeParams
-----------------------------
-.. ocv:function:: CvDTreeParams::CvDTreeParams()  
+CvDTreeNode
+-----------
+.. ocv:class:: CvDTreeNode
 
-.. ocv:function:: CvDTreeParams( int max_depth, int min_sample_count, float regression_accuracy, bool use_surrogates, int max_categories, int cv_folds, bool use_1se_rule, bool truncate_pruned_tree, const float* priors )
 
-    :param max_depth: The maximum number of levels in a tree. The depth of a constructed tree may be smaller due to other termination criterias or pruning of the tree.
+The structure represents a node in a decision tree. It has public members:    
 
-    :param min_sample_count: If the number of samples in a node is less than this parameter then the node will not be splitted.
+.. ocv:member:: int class_idx 
 
-    :param regression_accuracy: Termination criteria for regression trees. If all absolute differences between an estimated value in a node and values of train samples in this node are less than this parameter then the node will not be splitted.
-    :param use_surrogates: If true then surrogate splits will be built. These splits allow to work with missing data.
+    Class index normalized to 0..class_count-1 range and assigned to the node. It is used internally in classification trees and tree ensembles.
 
-    :param max_categories: Cluster possible values of a categorical variable into ``K`` :math:`\leq` ``max_categories`` clusters to find a suboptimal split. The clustering is applied only in n>2-class classification problems for categorical variables with ``N > max_categories`` possible values. See the Learning OpenCV book (page 489) for more detailed explanation.
+.. ocv:member:: int Tn
 
-    :param cv_folds: If ``cv_folds > 1`` then prune a tree with ``K``-fold cross-validation where ``K`` is equal to ``cv_folds``.
+    Tree index in a ordered sequence of pruned trees. The indices are used during and after the pruning procedure. The root node has the maximum value ``Tn`` of the whole tree, child nodes have ``Tn`` less than or equal to the parent's ``Tn``, and nodes with :math:`Tn \leq CvDTree::pruned\_tree\_idx` are not used at prediction stage (the corresponding branches are considered as cut-off), even if they have not been physically deleted from the tree at the pruning stage.
 
-    :param use_1se_rule: If true then a pruning will be harsher. This will make a tree more compact but a bit less accurate.
+.. ocv:member:: double value
 
-    :param truncate_pruned_tree: If true then pruned branches are removed completely from the tree. Otherwise they are retained and it is possible to get the unpruned tree or prune the tree differently by changing ``CvDTree::pruned_tree_idx`` parameter.
+    Value at the node: a class label in case of classification or estimated function value in case of regression.
 
-    :param priors: Weights of prediction categories which determine relative weights that you give to misclassification. That is, if the weight of the first category is 1 and the weight of the second category is 10, then each mistake in predicting the second category is equivalent to making 10 mistakes in predicting the first category.
+.. ocv:member:: CvDTreeNode* parent
 
-The default constructor initializes all the parameters with the default values tuned for the standalone classification tree:
+    Pointer to the parent node.
 
-::
+.. ocv:mebmer:: CvDTreeNode* left
 
-    CvDTreeParams() : max_categories(10), max_depth(INT_MAX), min_sample_count(10),
-        cv_folds(10), use_surrogates(true), use_1se_rule(true),
-        truncate_pruned_tree(true), regression_accuracy(0.01f), priors(0)
-    {}
-
-.. index:: CvDTreeTrainData
+    Pointer to the left child node.
 
-.. _CvDTreeTrainData:
+.. ocv:member:: CvDTreeNode* right
 
-CvDTreeTrainData
-----------------
-.. c:type:: CvDTreeTrainData
+    Pointer to the right child node.
 
-Decision tree training data and shared data for tree ensembles ::
+.. ocv:member:: CvDTreeSplit* split
 
-    struct CvDTreeTrainData
-    {
-        CvDTreeTrainData();
-        CvDTreeTrainData( const Mat& _train_data, int _tflag,
-                          const Mat& _responses, const Mat& _var_idx=Mat(),
-                          const Mat& _sample_idx=Mat(), const Mat& _var_type=Mat(),
-                          const Mat& _missing_mask=Mat(),
-                          const CvDTreeParams& _params=CvDTreeParams(),
-                          bool _shared=false, bool _add_labels=false );
-        virtual ~CvDTreeTrainData();
+    Pointer to the first (primary) split in the node list of splits.
 
-        virtual void set_data( const Mat& _train_data, int _tflag,
-                              const Mat& _responses, const Mat& _var_idx=Mat(),
-                              const Mat& _sample_idx=Mat(), const Mat& _var_type=Mat(),
-                              const Mat& _missing_mask=Mat(),
-                              const CvDTreeParams& _params=CvDTreeParams(),
-                              bool _shared=false, bool _add_labels=false,
-                              bool _update_data=false );
+.. ocv:mebmer:: int sample_count
 
-        virtual void get_vectors( const Mat& _subsample_idx,
-             float* values, uchar* missing, float* responses,
-             bool get_class_idx=false );
+    The number of samples that fall into the node at the training stage. It is used to resolve the difficult cases - when the variable for the primary split is missing and all the variables for other surrogate splits are missing too. In this case the sample is directed to the left if ``left->sample_count > right->sample_count`` and to the right otherwise. 
 
-        virtual CvDTreeNode* subsample_data( const Mat& _subsample_idx );
+.. ocv:member:: int depth
 
-        virtual void write_params( CvFileStorage* fs );
-        virtual void read_params( CvFileStorage* fs, CvFileNode* node );
+    Depth of the node. The root node depth is 0, the child nodes depth is the parent's depth + 1. 
 
-        // release all the data
-        virtual void clear();
+Other numerous fields of ``CvDTreeNode`` are used internally at the training stage.
 
-        int get_num_classes() const;
-        int get_var_type(int vi) const;
-        int get_work_var_count() const;
+CvDTreeParams
+-------------
+.. ocv:class:: CvDTreeParams
 
-        virtual int* get_class_labels( CvDTreeNode* n );
-        virtual float* get_ord_responses( CvDTreeNode* n );
-        virtual int* get_labels( CvDTreeNode* n );
-        virtual int* get_cat_var_data( CvDTreeNode* n, int vi );
-        virtual CvPair32s32f* get_ord_var_data( CvDTreeNode* n, int vi );
-        virtual int get_child_buf_idx( CvDTreeNode* n );
+The structure contains all the decision tree training parameters. You can initialize it by default constructor and then override any parameters directly before training, or the structure may be fully initialized using the advanced variant of the constructor.
 
-        ////////////////////////////////////
+CvDTreeParams::CvDTreeParams
+----------------------------
+The constructors.
 
-        virtual bool set_params( const CvDTreeParams& params );
-        virtual CvDTreeNode* new_node( CvDTreeNode* parent, int count,
-                                       int storage_idx, int offset );
+.. ocv:function:: CvDTreeParams::CvDTreeParams()  
 
-        virtual CvDTreeSplit* new_split_ord( int vi, float cmp_val,
-                    int split_point, int inversed, float quality );
-        virtual CvDTreeSplit* new_split_cat( int vi, float quality );
-        virtual void free_node_data( CvDTreeNode* node );
-        virtual void free_train_data();
-        virtual void free_node( CvDTreeNode* node );
+.. ocv:function:: CvDTreeParams::CvDTreeParams( int max_depth, int min_sample_count, float regression_accuracy, bool use_surrogates, int max_categories, int cv_folds, bool use_1se_rule, bool truncate_pruned_tree, const float* priors )
 
-        int sample_count, var_all, var_count, max_c_count;
-        int ord_var_count, cat_var_count;
-        bool have_labels, have_priors;
-        bool is_classifier;
+    :param max_depth: The maximum possible depth of the tree. That is the training algorithms attempts to split a node while its depth is less than ``max_depth``. The actual depth may be smaller if the other termination criteria are met (see the outline of the training procedure in the beginning of the section), and/or if the tree is pruned. 
+    
+    :param min_sample_count: If the number of samples in a node is less than this parameter then the node will not be splitted.
 
-        int buf_count, buf_size;
-        bool shared;
+    :param regression_accuracy: Termination criteria for regression trees. If all absolute differences between an estimated value in a node and values of train samples in this node are less than this parameter then the node will not be splitted.
+    :param use_surrogates: If true then surrogate splits will be built. These splits allow to work with missing data and compute variable importance correctly.
 
-        Mat& cat_count;
-        Mat& cat_ofs;
-        Mat& cat_map;
+    :param max_categories: Cluster possible values of a categorical variable into ``K`` :math:`\leq` ``max_categories`` clusters to find a suboptimal split. If a discrete variable, on which the training procedure tries to make a split, takes more than ``max_categories`` values, the precise best subset estimation may take a very long time because the algorithm is exponential. Instead, many decision trees engines (including ML) try to find sub-optimal split in this case by clustering all the samples into ``max_categories`` clusters that is some categories are merged together. The clustering is applied only in ``n``>2-class classification problems for categorical variables with ``N > max_categories`` possible values. In case of regression and 2-class classification the optimal split can be found efficiently without employing clustering, thus the parameter is not used in these cases. 
 
-        Mat& counts;
-        Mat& buf;
-        Mat& direction;
-        Mat& split_buf;
+    :param cv_folds: If ``cv_folds > 1`` then prune a tree with ``K``-fold cross-validation where ``K`` is equal to ``cv_folds``.
 
-        Mat& var_idx;
-        Mat& var_type; // i-th element =
-                         //   k<0  - ordered
-                         //   k>=0 - categorical, see k-th element of cat_* arrays
-        Mat& priors;
+    :param use_1se_rule: If true then a pruning will be harsher. This will make a tree more compact and more resistant to the training data noise but a bit less accurate.
 
-        CvDTreeParams params;
+    :param truncate_pruned_tree: If true then pruned branches are physically removed from the tree. Otherwise they are retained and it is possible to get results from the original unpruned (or pruned less aggressively) tree by decreasing ``CvDTree::pruned_tree_idx`` parameter.
 
-        CvMemStorage* tree_storage;
-        CvMemStorage* temp_storage;
+    :param priors: The array of a priori class probabilities, sorted by the class label value. The parameter can be used to tune the decision tree preferences toward a certain class. For example, if you want to detect some rare anomaly occurrence, the training base will likely contain much more normal cases than anomalies, so a very good classification performance will be achieved just by considering every case as normal. To avoid this, the priors can be specified, where the anomaly probability is artificially increased (up to 0.5 or even greater), so the weight of the misclassified anomalies becomes much bigger, and the tree is adjusted properly. You can also think about this parameter as weights of prediction categories which determine relative weights that you give to misclassification. That is, if the weight of the first category is 1 and the weight of the second category is 10, then each mistake in predicting the second category is equivalent to making 10 mistakes in predicting the first category.
 
-        CvDTreeNode* data_root;
+The default constructor initializes all the parameters with the default values tuned for the standalone classification tree:
 
-        CvSet* node_heap;
-        CvSet* split_heap;
-        CvSet* cv_heap;
-        CvSet* nv_heap;
+::
 
-        CvRNG rng;
-    };
+    CvDTreeParams() : max_categories(10), max_depth(INT_MAX), min_sample_count(10),
+        cv_folds(10), use_surrogates(true), use_1se_rule(true),
+        truncate_pruned_tree(true), regression_accuracy(0.01f), priors(0)
+    {}
 
+CvDTreeTrainData
+----------------
+.. ocv:class:: CvDTreeTrainData
 
-This structure is mostly used internally for storing both standalone trees and tree ensembles efficiently. Basically, it contains the following types of information:
+Decision tree training data and shared data for tree ensembles. The structure is mostly used internally for storing both standalone trees and tree ensembles efficiently. Basically, it contains the following types of information:
 
-#. Training parameters, an instance of :ref:`CvDTreeParams`.
+#. Training parameters, an instance of :ocv:class:`CvDTreeParams`.
 
-#. Training data, preprocessed to find the best splits more efficiently. For tree ensembles, this preprocessed data is reused by all trees. Additionally, the training data characteristics shared by all trees in the ensemble are stored here: variable types, the number of classes, class label compression map, and so on.
+#. Training data preprocessed to find the best splits more efficiently. For tree ensembles, this preprocessed data is reused by all trees. Additionally, the training data characteristics shared by all trees in the ensemble are stored here: variable types, the number of classes, a class label compression map, and so on.
 
 #. Buffers, memory storages for tree nodes, splits, and other elements of the constructed trees.
 
-There are two ways of using this structure. In simple cases (for example, a standalone tree or the ready-to-use "black box" tree ensemble from ML, like
+There are two ways of using this structure. In simple cases (for example, a standalone tree or the ready-to-use "black box" tree ensemble from machine learning, like
 :ref:`Random Trees` or
 :ref:`Boosting` ), there is no need to care or even to know about the structure. You just construct the needed statistical model, train it, and use it. The ``CvDTreeTrainData`` structure is constructed and used internally. However, for custom tree algorithms or another sophisticated cases, the structure may be constructed and used explicitly. The scheme is the following:
 
 #.
-    The structure is initialized using the default constructor, followed by ``set_data`` , or it is built using the full form of constructor. The parameter ``_shared``  must be set to ``true`` .
+    The structure is initialized using the default constructor, followed by ``set_data``, or it is built using the full form of constructor. The parameter ``_shared`` must be set to ``true``.
 
 #.
-    One or more trees are trained using this data (see the special form of the method ``CvDTree::train``  ).
+    One or more trees are trained using this data (see the special form of the method :ocv:func:`CvDTree::train`).
 
 #.
     The structure is released as soon as all the trees using it are released.
 
-.. index:: CvDTree
-
-.. _CvDTree:
-
 CvDTree
 -------
-.. c:type:: CvDTree
+.. ocv:class:: CvDTree
 
-Decision tree ::
+The class implements a decision tree as described in the beginning of this section.
 
-    class CvDTree : public CvStatModel
-    {
-    public:
-        CvDTree();
-        virtual ~CvDTree();
 
-        virtual bool train( const Mat& _train_data, int _tflag,
-                            const Mat& _responses, const Mat& _var_idx=Mat(),
-                            const Mat& _sample_idx=Mat(), const Mat& _var_type=Mat(),
-                            const Mat& _missing_mask=Mat(),
-                            CvDTreeParams params=CvDTreeParams() );
+CvDTree::train
+--------------
+Trains a decision tree.
 
-        virtual bool train( CvDTreeTrainData* _train_data,
-                            const Mat& _subsample_idx );
+.. ocv:function:: bool CvDTree::train( const Mat& train_data,  int tflag, const Mat& responses,  const Mat& var_idx=Mat(), const Mat& sample_idx=Mat(), const Mat& var_type=Mat(), const Mat& missing_mask=Mat(), CvDTreeParams params=CvDTreeParams() )
 
-        virtual CvDTreeNode* predict( const Mat& _sample,
-                                      const Mat& _missing_data_mask=Mat(),
-                                      bool raw_mode=false ) const;
-        virtual const Mat& get_var_importance();
-        virtual void clear();
+.. ocv:function::bool CvDTree::train( const CvMat* trainData, int tflag, const CvMat* responses, const CvMat* varIdx=0, const CvMat* sampleIdx=0, const CvMat* varType=0, const CvMat* missingDataMask=0, CvDTreeParams params=CvDTreeParams() )
 
-        virtual void read( CvFileStorage* fs, CvFileNode* node );
-        virtual void write( CvFileStorage* fs, const char* name );
+.. ocv:function::bool CvDTree::train( CvMLData* trainData, CvDTreeParams params=CvDTreeParams() )
 
-        // special read & write methods for trees in the tree ensembles
-        virtual void read( CvFileStorage* fs, CvFileNode* node,
-                           CvDTreeTrainData* data );
-        virtual void write( CvFileStorage* fs );
+.. ocv:function::bool CvDTree::train( CvDTreeTrainData* trainData, const CvMat* subsampleIdx )
 
-        const CvDTreeNode* get_root() const;
-        int get_pruned_tree_idx() const;
-        CvDTreeTrainData* get_data();
+.. ocv:pyfunction:: cv2.DTree.train(trainData, tflag, responses[, varIdx[, sampleIdx[, varType[, missingDataMask[, params]]]]]) -> retval
 
-    protected:
+There are four ``train`` methods in :ocv:class:`CvDTree`:
 
-        virtual bool do_train( const Mat& _subsample_idx );
+* The **first two** methods follow the generic :ocv:func:`CvStatModel::train` conventions. It is the most complete form. Both data layouts (``tflag=CV_ROW_SAMPLE`` and ``tflag=CV_COL_SAMPLE``) are supported, as well as sample and variable subsets, missing measurements, arbitrary combinations of input and output variable types, and so on. The last parameter contains all of the necessary training parameters (see the :ocv:class:`CvDTreeParams` description).
 
-        virtual void try_split_node( CvDTreeNode* n );
-        virtual void split_node_data( CvDTreeNode* n );
-        virtual CvDTreeSplit* find_best_split( CvDTreeNode* n );
-        virtual CvDTreeSplit* find_split_ord_class( CvDTreeNode* n, int vi );
-        virtual CvDTreeSplit* find_split_cat_class( CvDTreeNode* n, int vi );
-        virtual CvDTreeSplit* find_split_ord_reg( CvDTreeNode* n, int vi );
-        virtual CvDTreeSplit* find_split_cat_reg( CvDTreeNode* n, int vi );
-        virtual CvDTreeSplit* find_surrogate_split_ord( CvDTreeNode* n, int vi );
-        virtual CvDTreeSplit* find_surrogate_split_cat( CvDTreeNode* n, int vi );
-        virtual double calc_node_dir( CvDTreeNode* node );
-        virtual void complete_node_dir( CvDTreeNode* node );
-        virtual void cluster_categories( const int* vectors, int vector_count,
-            int var_count, int* sums, int k, int* cluster_labels );
+* The **third** method uses :ocv:class:`CvMLData` to pass training data to a decision tree.
 
-        virtual void calc_node_value( CvDTreeNode* node );
+* The **last** method ``train`` is mostly used for building tree ensembles. It takes the pre-constructed :ocv:class:`CvDTreeTrainData` instance and an optional subset of the training set. The indices in ``subsampleIdx`` are counted relatively to the ``_sample_idx`` , passed to the ``CvDTreeTrainData`` constructor. For example, if ``_sample_idx=[1, 5, 7, 100]`` , then ``subsampleIdx=[0,3]`` means that the samples ``[1, 100]`` of the original training set are used.
 
-        virtual void prune_cv();
-        virtual double update_tree_rnc( int T, int fold );
-        virtual int cut_tree( int T, int fold, double min_alpha );
-        virtual void free_prune_data(bool cut_tree);
-        virtual void free_tree();
 
-        virtual void write_node( CvFileStorage* fs, CvDTreeNode* node );
-        virtual void write_split( CvFileStorage* fs, CvDTreeSplit* split );
-        virtual CvDTreeNode* read_node( CvFileStorage* fs,
-                                        CvFileNode* node,
-                                        CvDTreeNode* parent );
-        virtual CvDTreeSplit* read_split( CvFileStorage* fs, CvFileNode* node );
-        virtual void write_tree_nodes( CvFileStorage* fs );
-        virtual void read_tree_nodes( CvFileStorage* fs, CvFileNode* node );
 
-        CvDTreeNode* root;
+CvDTree::predict
+----------------
+Returns the leaf node of a decision tree corresponding to the input vector.
 
-        int pruned_tree_idx;
-        Mat& var_importance;
+.. ocv:function:: CvDTreeNode* CvDTree::predict( const Mat& sample, const Mat& missingDataMask=Mat(), bool preprocessedInput=false ) const
 
-        CvDTreeTrainData* data;
-    };
+.. ocv:function::CvDTreeNode* CvDTree::predict( const CvMat* sample, const CvMat* missingDataMask=0, bool preprocessedInput=false ) const
 
+.. ocv:pyfunction:: cv2.DTree.predict(sample[, missingDataMask[, preprocessedInput]]) -> retval
 
-.. index:: CvDTree::train
+    :param sample: Sample for prediction.
 
-.. _CvDTree::train:
+    :param missingDataMask: Optional input missing measurement mask.
 
-CvDTree::train
---------------
-.. ocv:function:: bool CvDTree::train(  const Mat& _train_data,  int _tflag, const Mat& _responses,  const Mat& _var_idx=Mat(), const Mat& _sample_idx=Mat(),  const Mat& _var_type=Mat(), const Mat& _missing_mask=Mat(), CvDTreeParams params=CvDTreeParams() )
+    :param preprocessedInput: This parameter is normally set to ``false``, implying a regular input. If it is ``true``, the method assumes that all the values of the discrete input variables have been already normalized to :math:`0` to :math:`num\_of\_categories_i-1` ranges since the decision tree uses such normalized representation internally. It is useful for faster prediction with tree ensembles. For ordered input variables, the flag is not used.
+       
+The method traverses the decision tree and returns the reached leaf node as output. The prediction result, either the class label or the estimated function value, may be retrieved as the ``value`` field of the :ocv:class:`CvDTreeNode` structure, for example: ``dtree->predict(sample,mask)->value``.
 
-.. ocv:function:: bool CvDTree::train( CvDTreeTrainData* _train_data, const Mat& _subsample_idx )
 
-    Trains a decision tree.
 
-There are two ``train`` methods in ``CvDTree`` :
+CvDTree::calc_error
+-------------------
+Returns error of the decision tree.
 
-* The first method follows the generic ``CvStatModel::train`` conventions. It is the most complete form. Both data layouts ( ``_tflag=CV_ROW_SAMPLE`` and ``_tflag=CV_COL_SAMPLE`` ) are supported, as well as sample and variable subsets, missing measurements, arbitrary combinations of input and output variable types, and so on. The last parameter contains all of the necessary training parameters (see the
-:ref:`CvDTreeParams` description).
+.. ocv:function::float CvDTree::calc_error( CvMLData* trainData, int type, std::vector<float> *resp = 0 )
 
-* The second method ``train`` is mostly used for building tree ensembles. It takes the pre-constructed
-:ref:`CvDTreeTrainData` instance and an optional subset of the training set. The indices in ``_subsample_idx`` are counted relatively to the ``_sample_idx`` , passed to the ``CvDTreeTrainData`` constructor. For example, if ``_sample_idx=[1, 5, 7, 100]`` , then ``_subsample_idx=[0,3]`` means that the samples ``[1, 100]`` of the original training set are used.
+    :param data: Data for the decision tree.
+    
+    :param type: Type of error. Possible values are:
 
-.. index:: CvDTree::predict
+        * **CV_TRAIN_ERROR** Error on train samples.
 
-.. _CvDTree::predict:
+        * **CV_TEST_ERROR** Erron on test samples.
 
-CvDTree::predict
-----------------
-.. ocv:function:: CvDTreeNode* CvDTree::predict(  const Mat& _sample,  const Mat& _missing_data_mask=Mat(),                                 bool raw_mode=false ) const
+    :param resp: If it is not null then size of this vector will be set to the number of samples and each element will be set to result of prediction on the corresponding sample.
+
+The method calculates error of the decision tree. In case of classification it is the percentage of incorrectly classified samples and in case of regression it is the mean of squared errors on samples.
+
+
+CvDTree::getVarImportance
+-------------------------
+Returns the variable importance array.
+
+.. ocv:function:: Mat CvDTree::getVarImportance()
+
+.. ocv:function::const CvMat* CvDTree::get_var_importance()
 
-    Returns the leaf node of a decision tree corresponding to the input vector.
+.. ocv:pyfunction:: cv2.DTree.getVarImportance() -> importanceVector
 
-The method takes the feature vector and an optional missing measurement mask as input, traverses the decision tree, and returns the reached leaf node as output. The prediction result, either the class label or the estimated function value, may be retrieved as the ``value`` field of the
-:ref:`CvDTreeNode` structure, for example: dtree-
-:math:`>` predict(sample,mask)-
-:math:`>` value.
+CvDTree::get_root
+-----------------
+Returns the root of the decision tree.
 
-The last parameter is normally set to ``false`` , implying a regular
-input. If it is ``true`` , the method assumes that all the values of
-the discrete input variables have been already normalized to
-:math:`0` to
-:math:`num\_of\_categories_i-1` ranges since the decision tree uses such
-normalized representation internally. It is useful for faster prediction
-with tree ensembles. For ordered input variables, the flag is not used.
+.. ocv:function:: const CvDTreeNode* CvDTree::get_root() const
+
+
+CvDTree::get_pruned_tree_idx
+----------------------------
+Returns the ``CvDTree::pruned_tree_idx`` parameter.
+
+.. ocv:function:: int CvDTree::get_pruned_tree_idx() const
+
+The parameter ``DTree::pruned_tree_idx`` is used to prune a decision tree. See the ``CvDTreeNode::Tn`` parameter.
+
+CvDTree::get_data
+-----------------
+Returns used train data of the decision tree.
+
+.. ocv:function::const CvDTreeTrainData* CvDTree::get_data() const
 
 Example: building a tree for classifying mushrooms.  See the ``mushroom.cpp`` sample that demonstrates how to build and use the
 decision tree.
 
+
+.. [Breiman84] Breiman, L., Friedman, J. Olshen, R. and Stone, C. (1984), *Classification and Regression Trees*, Wadsworth.
+
index 5ffa3bb..c7e6982 100644 (file)
@@ -1,7 +1,9 @@
 Expectation Maximization
 ========================
 
-The EM (Expectation Maximization) algorithm estimates the parameters of the multivariate probability density function in the form of a Gaussian mixture distribution with a specified number of mixtures.
+.. highlight:: cpp
+
+The Expectation Maximization(EM) algorithm estimates the parameters of the multivariate probability density function in the form of a Gaussian mixture distribution with a specified number of mixtures.
 
 Consider the set of the N feature vectors
 { :math:`x_1, x_2,...,x_{N}` } from a d-dimensional Euclidean space drawn from a Gaussian mixture:
@@ -59,7 +61,7 @@ At the second step (Maximization step or M-step), the mixture parameter estimate
 Alternatively, the algorithm may start with the M-step when the initial values for
 :math:`p_{i,k}` can be provided. Another alternative when
 :math:`p_{i,k}` are unknown is to use a simpler clustering algorithm to pre-cluster the input samples and thus obtain initial
-:math:`p_{i,k}` . Often (including ML) the
+:math:`p_{i,k}` . Often (including macnine learning) the
 :ref:`kmeans` algorithm is used for that purpose.
 
 One of the main problems of the EM algorithm is a large number
@@ -83,121 +85,87 @@ already a good enough approximation).
 *
     Bilmes98 J. A. Bilmes. *A Gentle Tutorial of the EM Algorithm and its Application to Parameter Estimation for Gaussian Mixture and Hidden Markov Models*. Technical Report TR-97-021, International Computer Science Institute and Computer Science Division, University of California at Berkeley, April 1998.
 
-.. index:: CvEMParams
-
-.. _CvEMParams:
 
 CvEMParams
 ----------
-.. c:type:: CvEMParams
+.. ocv:class:: CvEMParams
 
-Parameters of the EM algorithm ::
+Parameters of the EM algorithm. All parameters are public. You can initialize them by a constructor and then override some of them directly if you want.
 
-    struct CvEMParams
-    {
-        CvEMParams() : nclusters(10), cov_mat_type(CvEM::COV_MAT_DIAGONAL),
-            start_step(CvEM::START_AUTO_STEP), probs(0), weights(0), means(0),
-                                                         covs(0)
-        {
-            term_crit=cvTermCriteria( CV_TERMCRIT_ITER+CV_TERMCRIT_EPS,
-                                                    100, FLT_EPSILON );
-        }
-
-        CvEMParams( int _nclusters, int _cov_mat_type=1/*CvEM::COV_MAT_DIAGONAL*/,
-                    int _start_step=0/*CvEM::START_AUTO_STEP*/,
-                    CvTermCriteria _term_crit=cvTermCriteria(
-                                            CV_TERMCRIT_ITER+CV_TERMCRIT_EPS,
-                                            100, FLT_EPSILON),
-                    const CvMat* _probs=0, const CvMat* _weights=0,
-                    const CvMat* _means=0, const CvMat** _covs=0 ) :
-                    nclusters(_nclusters), cov_mat_type(_cov_mat_type),
-                    start_step(_start_step),
-                    probs(_probs), weights(_weights), means(_means), covs(_covs),
-                    term_crit(_term_crit)
-        {}
-
-        int nclusters;
-        int cov_mat_type;
-        int start_step;
-        const CvMat* probs;
-        const CvMat* weights;
-        const CvMat* means;
-        const CvMat** covs;
-        CvTermCriteria term_crit;
-    };
-
-
-The structure has two constructors. The default one represents a rough rule-of-the-thumb. With another one it is possible to override a variety of parameters from a single number of mixtures (the only essential problem-dependent parameter) to initial values for the mixture parameters.
-
-.. index:: CvEM
-
-.. _CvEM:
 
-CvEM
-----
-.. c:type:: CvEM
 
-EM model ::
+CvEMParams::CvEMParams
+----------------------
+The constructors
 
-    class CV_EXPORTS CvEM : public CvStatModel
-    {
-    public:
-        // Type of covariance matrices
-        enum { COV_MAT_SPHERICAL=0, COV_MAT_DIAGONAL=1, COV_MAT_GENERIC=2 };
+.. ocv:function:: CvEMParams::CvEMParams()
+
+.. ocv:function:: CvEMParams::CvEMParams( int nclusters, int cov_mat_type=CvEM::COV_MAT_DIAGONAL, int start_step=CvEM::START_AUTO_STEP, CvTermCriteria term_crit=cvTermCriteria(CV_TERMCRIT_ITER+CV_TERMCRIT_EPS, 100, FLT_EPSILON), const CvMat* probs=0, const CvMat* weights=0, const CvMat* means=0, const CvMat** covs=0 ) 
+
+    :param nclusters: The number of mixture components in the gaussian mixture model. Some of EM implementation could determine the optimal number of mixtures within a specified value range, but that is not the case in ML yet.
+    
+    :param cov_mat_type: Constraint on covariance matrices which defines type of matrices. Possible values are:
 
-        // Initial step
-        enum { START_E_STEP=1, START_M_STEP=2, START_AUTO_STEP=0 };
+        * **CvEM::COV_MAT_SPHERICAL** A scaled identity matrix :math:`\mu_k * I`. There is the only parameter :math:`\mu_k` to be estimated for earch matrix. The option may be used in special cases, when the constraint is relevant, or as a first step in the optimization (for example in case when the data is preprocessed with PCA). The results of such preliminary estimation may be passed again to the optimization procedure, this time with ``cov_mat_type=CvEM::COV_MAT_DIAGONAL``.
 
-        CvEM();
-        CvEM( const Mat& samples, const Mat& sample_idx=Mat(),
-              CvEMParams params=CvEMParams(), Mat* labels=0 );
-        virtual ~CvEM();
+        * **CvEM::COV_MAT_DIAGONAL** A diagonal matrix with positive diagonal elements. The number of free parameters is ``d`` for each matrix. This is most commonly used option yielding good estimation results.
 
-        virtual bool train( const Mat& samples, const Mat& sample_idx=Mat(),
-                            CvEMParams params=CvEMParams(), Mat* labels=0 );
+        * **CvEM::COV_MAT_GENERIC** A symmetric positively defined matrix. The number of free parameters in each matrix is about :math:`d^2/2`. It is not recommended to use this option, unless there is pretty accurate initial estimation of the parameters and/or a huge number of training samples.
 
-        virtual float predict( const Mat& sample, Mat& probs ) const;
-        virtual void clear();
+    :param start_step: The start step of the EM algorithm: 
 
-        int get_nclusters() const { return params.nclusters; }
-        const Mat& get_means() const { return means; }
-        const Mat&* get_covs() const { return covs; }
-        const Mat& get_weights() const { return weights; }
-        const Mat& get_probs() const { return probs; }
+        * **CvEM::START_E_STEP** Start with Expectation step. You need to provide means :math:`a_k` of mixture components to use this option. Optionally you can pass weights :math:`\pi_k` and covariance matrices :math:`S_k` of mixture components.
+        * **CvEM::START_M_STEP** Start with Maximization step. You need to provide initial probabilites :math:`p_{i,k}` to use this option.
+        * **CvEM::START_AUTO_STEP** Start with Expectation step. You need not provide any parameters because they will be estimated by the k-means algorithm.
 
-    protected:
+    :param term_crit: The termination criteria of the EM algorithm. The EM algorithm can be terminated by the number of iterations ``term_crit.max_iter`` (number of M-steps) or when relative change of likelihood logarithm is less than ``term_crit.epsilon``.
 
-        virtual void set_params( const CvEMParams& params,
-                                 const CvVectors& train_data );
-        virtual void init_em( const CvVectors& train_data );
-        virtual double run_em( const CvVectors& train_data );
-        virtual void init_auto( const CvVectors& samples );
-        virtual void kmeans( const CvVectors& train_data, int nclusters,
-                             Mat& labels, CvTermCriteria criteria,
-                             const Mat& means );
-        CvEMParams params;
-        double log_likelihood;
+    :param probs: Initial probabilities :math:`p_{i,k}` of sample :math:`i` to belong to mixture component :math:`k`. It is a floating-point matrix of :math:`nsamples \times nclusters` size. It is used and must be not NULL only when ``start_step=CvEM::START_M_STEP``.
 
-        Mat& means;
-        Mat&* covs;
-        Mat& weights;
-        Mat& probs;
+    :param weights: Initial weights :math:`\pi_k` of mixture components. It is a floating-point vector with :math:`nclusters` elements. It is used (if not NULL) only when ``start_step=CvEM::START_E_STEP``. 
 
-        Mat& log_weight_div_det;
-        Mat& inv_eigen_values;
-        Mat&* cov_rotate_mats;
-    };
+    :param means: Initial means :math:`a_k` of mixture components. It is a floating-point matrix of :math:`nclusters \times dims` size. It is used used and must be not NULL only when ``start_step=CvEM::START_E_STEP``.
 
+    :param covs: Initial covariance matrices :math:`S_k` of mixture components. Each of covariance matrices is a valid square floating-point matrix of :math:`dims \times dims` size. It is used (if not NULL) only when ``start_step=CvEM::START_E_STEP``.
 
-.. index:: CvEM::train
+The default constructor represents a rough rule-of-the-thumb:
+
+::
+
+    CvEMParams() : nclusters(10), cov_mat_type(1/*CvEM::COV_MAT_DIAGONAL*/),
+        start_step(0/*CvEM::START_AUTO_STEP*/), probs(0), weights(0), means(0), covs(0)
+    {
+        term_crit=cvTermCriteria( CV_TERMCRIT_ITER+CV_TERMCRIT_EPS, 100, FLT_EPSILON );
+    }
+
+
+With another contstructor it is possible to override a variety of parameters from a single number of mixtures (the only essential problem-dependent parameter) to initial values for the mixture parameters.
+
+
+CvEM
+----
+.. ocv:class:: CvEM
+
+    The class implements the EM algorithm as described in the beginning of this section.
 
-.. _CvEM::train:
 
 CvEM::train
 -----------
+Estimates the Gaussian mixture parameters from a sample set.
+
 .. ocv:function:: void CvEM::train(  const Mat& samples,  const Mat&  sample_idx=Mat(),                    CvEMParams params=CvEMParams(),  Mat* labels=0 )
 
-    Estimates the Gaussian mixture parameters from a sample set.
+.. ocv:function:: bool CvEM::train( const CvMat* samples, const CvMat* sampleIdx=0, CvEMParams params=CvEMParams(), CvMat* labels=0 )
+
+.. ocv:pyfunction:: cv2.EM.train(samples[, sampleIdx[, params]]) -> retval, labels
+
+    :param samples: Samples from which the Gaussian mixture model will be estimated.
+
+    :param sample_idx: Mask of samples to use. All samples are used by default.
+
+    :param params: Parameters of the EM algorithm.
+
+    :param labels: The optional output "class label" for each sample: :math:`\texttt{labels}_i=\texttt{arg max}_k(p_{i,k}), i=1..N` (indices of the most probable mixture component for each sample).
 
 Unlike many of the ML models, EM is an unsupervised learning algorithm and it does not take responses (class labels or function values) as input. Instead, it computes the
 *Maximum Likelihood Estimate* of the Gaussian mixture parameters from an input sample set, stores all the parameters inside the structure:
@@ -205,12 +173,126 @@ Unlike many of the ML models, EM is an unsupervised learning algorithm and it do
 :math:`a_k` in ``means`` ,
 :math:`S_k` in ``covs[k]``,
 :math:`\pi_k` in ``weights`` , and optionally computes the output "class label" for each sample:
-:math:`\texttt{labels}_i=\texttt{arg max}_k(p_{i,k}), i=1..N` (indices of the most probable mixture for each sample).
+:math:`\texttt{labels}_i=\texttt{arg max}_k(p_{i,k}), i=1..N` (indices of the most probable mixture component for each sample).
 
 The trained model can be used further for prediction, just like any other classifier. The trained model is similar to the
 :ref:`Bayes classifier`.
 
-For example of clustering random samples of multi-Gaussian distribution using EM see em.cpp sample in OpenCV distribution.
+For an example of clustering random samples of the multi-Gaussian distribution using EM, see ``em.cpp`` sample in the OpenCV distribution.
+
+
+CvEM::predict
+-------------
+Returns a mixture component index of a sample.
+
+.. ocv:function:: float CvEM::predict( const Mat& sample, Mat* probs=0 ) const
+
+.. ocv:function:: float CvEM::predict( const CvMat* sample, CvMat* probs ) const
+
+.. ocv:pyfunction:: cv2.EM.predict(sample) -> retval, probs
+
+    :param sample: A sample for classification.
+
+    :param probs: If it is not null then the method will write posterior probabilities of each component given the sample data to this parameter.
+
+
+CvEM::getNClusters
+------------------
+Returns the number of mixture components :math:`M` in the gaussian mixture model.
+
+.. ocv:function:: int CvEM::getNClusters() const
+
+.. ocv:function:: int CvEM::get_nclusters() const
+
+.. ocv:pyfunction:: cv2.EM.getNClusters() -> retval
+
+
+CvEM::getMeans
+------------------
+Returns mixture means :math:`a_k`.
+
+.. ocv:function:: Mat CvEM::getMeans() const
+
+.. ocv:function:: const CvMat* CvEM::get_means() const
+
+.. ocv:pyfunction:: cv2.EM.getMeans() -> means
+
+
+CvEM::getCovs
+-------------
+Returns mixture covariance matrices :math:`S_k`.
+
+.. ocv:function:: void CvEM::getCovs(std::vector<cv::Mat>& covs) const
+
+.. ocv:function:: const CvMat** CvEM::get_covs() const
+
+.. ocv:pyfunction:: cv2.EM.getCovs([covs]) -> covs
+
+
+CvEM::getWeights
+----------------
+Returns mixture weights :math:`\pi_k`.
+
+.. ocv:function:: Mat CvEM::getWeights() const
+
+.. ocv:function:: const CvMat* CvEM::get_weights() const
+
+.. ocv:pyfunction:: cv2.EM.getWeights() -> weights
+
+
+CvEM::getProbs
+--------------
+Returns vectors of probabilities for each training sample.
+
+.. ocv:function:: Mat CvEM::getProbs() const
+
+.. ocv:function:: const CvMat* CvEM::get_probs() const
+
+.. ocv:pyfunction:: cv2.EM.getProbs() -> probs
+
+For each training sample :math:`i` (that have been passed to the constructor or to :ocv:func:`CvEM::train`) returns probabilites :math:`p_{i,k}` to belong to a mixture component :math:`k`.
+
+
+CvEM::getLikelihood
+-------------------
+Returns logarithm of likelihood.
+
+.. ocv:function:: double CvEM::getLikelihood() const
+
+.. ocv:function:: double CvEM::get_log_likelihood() const
+
+.. ocv:pyfunction:: cv2.EM.getLikelihood() -> likelihood
+
+
+CvEM::getLikelihoodDelta
+------------------------
+Returns difference between logarithm of likelihood on the last iteration and logarithm of likelihood on the previous iteration.
+
+.. ocv:function:: double CvEM::getLikelihoodDelta() const
+
+.. ocv:function:: double CvEM::get_log_likelihood_delta() const 
+
+.. ocv:pyfunction:: cv2.EM.getLikelihoodDelta() -> likelihood delta
+
+CvEM::write_params
+------------------
+Writes used parameters of the EM algorithm to a file storage.
+
+.. ocv:function:: void CvEM::write_params( CvFileStorage* fs ) const
+
+    :param fs: A file storage where parameters will be written.
+
+
+CvEM::read_params
+-----------------
+Reads parameters of the EM algorithm.
+
+.. ocv:function:: void CvEM::read_params( CvFileStorage* fs, CvFileNode* node )
+
+    :param fs: A file storage with parameters of the EM algorithm.
+
+    :param node: The parent map. If it is NULL, the function searches a node with parameters in all the top-level nodes (streams), starting with the first one.
 
+The function reads EM parameters from the specified file storage node. For example of clustering random samples of multi-Gaussian distribution using EM see em.cpp sample in OpenCV distribution.
 
 
index 8cef701..67ad301 100644 (file)
@@ -3,24 +3,24 @@
 Gradient Boosted Trees\r
 ======================\r
 \r
-Gradient Boosted Trees (GBT) is a generalized boosting algorithm, introduced by\r
+.. highlight:: cpp\r
+\r
+Gradient Boosted Trees (GBT) is a generalized boosting algorithm introduced by\r
 Jerome Friedman: http://www.salfordsystems.com/doc/GreedyFuncApproxSS.pdf .\r
-In contrast to AdaBoost.M1 algorithm GBT can deal with both multiclass\r
-classification and regression problems. More than that it can use any\r
+In contrast to the AdaBoost.M1 algorithm, GBT can deal with both multiclass\r
+classification and regression problems. Moreover, it can use any\r
 differential loss function, some popular ones are implemented.\r
-Decision trees (:ref:`CvDTree`) usage as base learners allows to process ordered\r
+Decision trees (:ocv:class:`CvDTree`) usage as base learners allows to process ordered\r
 and categorical variables.\r
 \r
 \r
-.. _Training the GBT model:\r
-\r
 Training the GBT model\r
 ----------------------\r
 \r
-Gradient Boosted Trees model represents an ensemble of single regression trees,\r
-that are built in a greedy fashion. Training procedure is an iterative proccess\r
-similar to the numerical optimazation via gradient descent method. Summary loss\r
-on the training set depends only from the current model predictions on the\r
+Gradient Boosted Trees model represents an ensemble of single regression trees\r
+built in a greedy fashion. Training procedure is an iterative proccess\r
+similar to the numerical optimization via the gradient descent method. Summary loss\r
+on the training set depends only on the current model predictions for the\r
 thaining samples,  in other words\r
 :math:`\sum^N_{i=1}L(y_i, F(x_i)) \equiv \mathcal{L}(F(x_1), F(x_2), ... , F(x_N))\r
 \equiv \mathcal{L}(F)`. And the :math:`\mathcal{L}(F)`\r
@@ -30,12 +30,13 @@ gradient can be computed as follows:
     grad(\mathcal{L}(F)) = \left( \dfrac{\partial{L(y_1, F(x_1))}}{\partial{F(x_1)}},\r
     \dfrac{\partial{L(y_2, F(x_2))}}{\partial{F(x_2)}}, ... ,\r
     \dfrac{\partial{L(y_N, F(x_N))}}{\partial{F(x_N)}} \right) .\r
-On every training step a single regression tree is built to predict an\r
+\r
+At every training step, a single regression tree is built to predict an\r
 antigradient vector components. Step length is computed corresponding to the\r
-loss function and separately for every region determined by the tree leaf, and\r
-can be eliminated by changing leaves' values directly.\r
+loss function and separately for every region determined by the tree leaf. It\r
+can be eliminated by changing values of the leaves  directly.\r
 \r
-The main scheme of the training proccess is shown below.\r
+See below the main scheme of the training proccess:\r
 \r
 #.\r
     Find the best constant model.\r
@@ -52,114 +53,90 @@ The main scheme of the training proccess is shown below.
         Add the tree to the model.\r
 \r
 \r
-The following loss functions are implemented:\r
+The following loss functions are implemented for regression problems:\r
 \r
-*for regression problems:*\r
-\r
-#.\r
+*\r
     Squared loss (``CvGBTrees::SQUARED_LOSS``):\r
     :math:`L(y,f(x))=\dfrac{1}{2}(y-f(x))^2`\r
-#.\r
+*\r
     Absolute loss (``CvGBTrees::ABSOLUTE_LOSS``):\r
     :math:`L(y,f(x))=|y-f(x)|`\r
-#.\r
+*\r
     Huber loss (``CvGBTrees::HUBER_LOSS``):\r
     :math:`L(y,f(x)) = \left\{ \begin{array}{lr}\r
     \delta\cdot\left(|y-f(x)|-\dfrac{\delta}{2}\right) & : |y-f(x)|>\delta\\\r
     \dfrac{1}{2}\cdot(y-f(x))^2 & : |y-f(x)|\leq\delta \end{array} \right.`,\r
-    where :math:`\delta` is the :math:`\alpha`-quantile estimation of the\r
+    \r
+       where :math:`\delta` is the :math:`\alpha`-quantile estimation of the\r
     :math:`|y-f(x)|`. In the current implementation :math:`\alpha=0.2`.\r
 \r
-*for classification problems:*\r
 \r
-4.\r
+The following loss functions are implemented for classification problems:\r
+\r
+*\r
     Deviance or cross-entropy loss (``CvGBTrees::DEVIANCE_LOSS``):\r
     :math:`K` functions are built, one function for each output class, and\r
     :math:`L(y,f_1(x),...,f_K(x)) = -\sum^K_{k=0}1(y=k)\ln{p_k(x)}`,\r
     where :math:`p_k(x)=\dfrac{\exp{f_k(x)}}{\sum^K_{i=1}\exp{f_i(x)}}`\r
-    is the estimation of the probability that :math:`y=k`.\r
+    is the estimation of the probability of :math:`y=k`.\r
 \r
-In the end we get the model in the following form:\r
+As a result, you get the following model:\r
 \r
 .. math:: f(x) = f_0 + \nu\cdot\sum^M_{i=1}T_i(x) ,\r
-where :math:`f_0` is the initial guess (the best constant model) and :math:`\nu`\r
+\r
+where :math:`f_0` is an initial guess (the best constant model) and :math:`\nu`\r
 is a regularization parameter from the interval :math:`(0,1]`, futher called\r
 *shrinkage*.\r
 \r
 \r
-.. _Predicting with GBT model:\r
-\r
-Predicting with GBT model\r
+Predicting with the GBT Model\r
 -------------------------\r
 \r
-To get the GBT model prediciton it is needed to compute the sum of responses of\r
-all the trees in the ensemble. For regression problems it is the answer, and\r
-for classification problems the result is :math:`\arg\max_{i=1..K}(f_i(x))`.\r
+To get the GBT model prediciton, you need to compute the sum of responses of\r
+all the trees in the ensemble. For regression problems, it is the answer.\r
+For classification problems, the result is :math:`\arg\max_{i=1..K}(f_i(x))`.\r
 \r
 \r
 .. highlight:: cpp\r
 \r
 \r
-.. index:: CvGBTreesParams\r
-.. _CvGBTreesParams:\r
-\r
 CvGBTreesParams\r
 ---------------\r
-.. c:type:: CvGBTreesParams\r
-\r
-GBT training parameters ::\r
+.. ocv:class:: CvGBTreesParams\r
 \r
-    struct CvGBTreesParams : public CvDTreeParams\r
-    {\r
-        int weak_count;\r
-        int loss_function_type;\r
-        float subsample_portion;\r
-        float shrinkage;\r
-\r
-        CvGBTreesParams();\r
-        CvGBTreesParams( int loss_function_type, int weak_count, float shrinkage,\r
-            float subsample_portion, int max_depth, bool use_surrogates );\r
-    };\r
+GBT training parameters.\r
 \r
 The structure contains parameters for each sigle decision tree in the ensemble,\r
 as well as the whole model characteristics. The structure is derived from\r
-:ref:`CvDTreeParams` but not all of the decision tree parameters are supported:\r
-cross-validation, pruning and class priorities are not used. The whole\r
-parameters list is shown below:\r
+:ocv:class:`CvDTreeParams` but not all of the decision tree parameters are supported:\r
+cross-validation, pruning, and class priorities are not used.\r
 \r
-``weak_count``\r
+CvGBTreesParams::CvGBTreesParams\r
+--------------------------------\r
+.. ocv:function:: CvGBTreesParams::CvGBTreesParams()\r
 \r
-    The count of boosting algorithm iterations. ``weak_count*K`` -- is the total\r
-    count of trees in the GBT model, where ``K`` is the output classes count\r
-    (equal to one in the case of regression).\r
-    \r
-``loss_function_type``\r
+.. ocv:function:: CvGBTreesParams::CvGBTreesParams( int loss_function_type, int weak_count, float shrinkage, float subsample_portion, int max_depth, bool use_surrogates )\r
 \r
-    The type of the loss function used for training\r
+   :param loss_function_type: Type of the loss function used for training\r
     (see :ref:`Training the GBT model`). It must be one of the\r
-    following: ``CvGBTrees::SQUARED_LOSS``, ``CvGBTrees::ABSOLUTE_LOSS``,\r
+    following types: ``CvGBTrees::SQUARED_LOSS``, ``CvGBTrees::ABSOLUTE_LOSS``,\r
     ``CvGBTrees::HUBER_LOSS``, ``CvGBTrees::DEVIANCE_LOSS``. The first three\r
-    ones are used for the case of regression problems, and the last one for\r
+    types are used for regression problems, and the last one for\r
     classification.\r
-    \r
-``shrinkage``\r
 \r
-    Regularization parameter (see :ref:`Training the GBT model`).\r
+   :param weak_count: Count of boosting algorithm iterations. ``weak_count*K`` is the total\r
+    count of trees in the GBT model, where ``K`` is the output classes count\r
+    (equal to one in case of a regression).\r
+  \r
+   :param shrinkage: Regularization parameter (see :ref:`Training the GBT model`).\r
     \r
-``subsample_portion``\r
-\r
-    The portion of the whole training set used on each algorithm iteration.\r
-    Subset is generated randomly\r
-    (For more information see\r
-    http://www.salfordsystems.com/doc/StochasticBoostingSS.pdf).\r
-\r
-``max_depth``\r
+   :param subsample_portion: Portion of the whole training set used for each algorithm iteration.\r
+    Subset is generated randomly. For more information see\r
+    http://www.salfordsystems.com/doc/StochasticBoostingSS.pdf.\r
 \r
-    The maximal depth of each decision tree in the ensemble (see :ref:`CvDTree`).\r
+   :param max_depth: Maximal depth of each decision tree in the ensemble (see :ocv:class:`CvDTree`).\r
 \r
-``use_surrogates``\r
-\r
-    If ``true`` surrogate splits are built (see :ref:`CvDTree`).\r
+   :param use_surrogates: If ``true``, surrogate splits are built (see :ocv:class:`CvDTree`).\r
     \r
 By default the following constructor is used:\r
 \r
@@ -168,204 +145,126 @@ By default the following constructor is used:
     CvGBTreesParams(CvGBTrees::SQUARED_LOSS, 200, 0.8f, 0.01f, 3, false)\r
         : CvDTreeParams( 3, 10, 0, false, 10, 0, false, false, 0 )\r
 \r
+CvGBTrees\r
+---------\r
+.. ocv:class:: CvGBTrees\r
+\r
+The class implements the Gradient boosted tree model as described in the beginning of this section.\r
 \r
+CvGBTrees::CvGBTrees\r
+--------------------\r
+Default and training constructors.\r
 \r
-.. index:: CvGBTrees\r
-.. _CvGBTrees:\r
+.. ocv:function:: CvGBTrees::CvGBTrees()\r
 \r
-CvGBTrees\r
----------\r
-.. c:type:: CvGBTrees\r
-\r
-GBT model ::\r
-\r
-       class CvGBTrees : public CvStatModel\r
-       {\r
-       public:\r
-\r
-               enum {SQUARED_LOSS=0, ABSOLUTE_LOSS, HUBER_LOSS=3, DEVIANCE_LOSS};\r
-\r
-               CvGBTrees();\r
-               CvGBTrees( const cv::Mat& trainData, int tflag,\r
-                        const Mat& responses, const Mat& varIdx=Mat(),\r
-                        const Mat& sampleIdx=Mat(), const cv::Mat& varType=Mat(),\r
-                        const Mat& missingDataMask=Mat(),\r
-                        CvGBTreesParams params=CvGBTreesParams() );\r
-\r
-               virtual ~CvGBTrees();\r
-               virtual bool train( const Mat& trainData, int tflag,\r
-                        const Mat& responses, const Mat& varIdx=Mat(),\r
-                        const Mat& sampleIdx=Mat(), const Mat& varType=Mat(),\r
-                        const Mat& missingDataMask=Mat(),\r
-                        CvGBTreesParams params=CvGBTreesParams(),\r
-                        bool update=false );\r
-               \r
-               virtual bool train( CvMLData* data,\r
-                        CvGBTreesParams params=CvGBTreesParams(),\r
-                        bool update=false );\r
-\r
-               virtual float predict( const Mat& sample, const Mat& missing=Mat(),\r
-                        const Range& slice = Range::all(),\r
-                        int k=-1 ) const;\r
-\r
-               virtual void clear();\r
-\r
-               virtual float calc_error( CvMLData* _data, int type,\r
-                        std::vector<float> *resp = 0 );\r
-\r
-               virtual void write( CvFileStorage* fs, const char* name ) const;\r
-\r
-               virtual void read( CvFileStorage* fs, CvFileNode* node );\r
-\r
-       protected:\r
-               \r
-               CvDTreeTrainData* data;\r
-               CvGBTreesParams params;\r
-               CvSeq** weak;\r
-               Mat& orig_response;\r
-               Mat& sum_response;\r
-               Mat& sum_response_tmp;\r
-               Mat& weak_eval;\r
-               Mat& sample_idx;\r
-               Mat& subsample_train;\r
-               Mat& subsample_test;\r
-               Mat& missing;\r
-               Mat& class_labels;\r
-               RNG* rng;\r
-               int class_count;\r
-               float delta;\r
-               float base_value;\r
-               \r
-               ...\r
-\r
-       };\r
-\r
-\r
-       \r
-.. index:: CvGBTrees::train\r
-\r
-.. _CvGBTrees::train:\r
+.. ocv:function:: CvGBTrees::CvGBTrees( const Mat& trainData, int tflag, const Mat& responses, const Mat& varIdx=Mat(), const Mat& sampleIdx=Mat(), const Mat& varType=Mat(), const Mat& missingDataMask=Mat(), CvGBTreesParams params=CvGBTreesParams() )\r
+\r
+.. ocv:function::CvGBTrees::CvGBTrees( const CvMat* trainData, int tflag, const CvMat* responses, const CvMat* varIdx=0, const CvMat* sampleIdx=0, const CvMat* varType=0, const CvMat* missingDataMask=0, CvGBTreesParams params=CvGBTreesParams() )\r
+\r
+.. ocv:pyfunction:: cv2.GBTrees([trainData, tflag, responses[, varIdx[, sampleIdx[, varType[, missingDataMask[, params]]]]]]) -> <GBTrees object>\r
+\r
+The constructors follow conventions of :ocv:func:`CvStatModel::CvStatModel`. See :ocv:func:`CvStatModel::train` for parameters descriptions.\r
 \r
 CvGBTrees::train\r
 ----------------\r
-.. c:function:: bool train(const Mat & trainData, int tflag, const Mat & responses, const Mat & varIdx=Mat(), const Mat & sampleIdx=Mat(), const Mat & varType=Mat(), const Mat & missingDataMask=Mat(), CvGBTreesParams params=CvGBTreesParams(), bool update=false)\r
+Trains a Gradient boosted tree model.\r
+\r
+.. ocv:function:: bool CvGBTrees::train(const Mat& trainData, int tflag, const Mat& responses, const Mat& varIdx=Mat(), const Mat& sampleIdx=Mat(), const Mat& varType=Mat(), const Mat& missingDataMask=Mat(), CvGBTreesParams params=CvGBTreesParams(), bool update=false)\r
 \r
-.. c:function:: bool train(CvMLData* data, CvGBTreesParams params=CvGBTreesParams(), bool update=false)\r
+.. ocv:function::bool CvGBTrees::train( const CvMat* trainData, int tflag, const CvMat* responses, const CvMat* varIdx=0, const CvMat* sampleIdx=0, const CvMat* varType=0, const CvMat* missingDataMask=0, CvGBTreesParams params=CvGBTreesParams(), bool update=false )\r
+\r
+.. ocv:function::bool CvGBTrees::train(CvMLData* data, CvGBTreesParams params=CvGBTreesParams(), bool update=false)\r
+\r
+.. ocv:pyfunction:: cv2.GBTrees.train(trainData, tflag, responses[, varIdx[, sampleIdx[, varType[, missingDataMask[, params[, update]]]]]]) -> retval\r
     \r
-       Trains a Gradient boosted tree model.\r
-       \r
-The first train method follows the common template (see :ref:`CvStatModel::train`).\r
+The first train method follows the common template (see :ocv:func:`CvStatModel::train`).\r
 Both ``tflag`` values (``CV_ROW_SAMPLE``, ``CV_COL_SAMPLE``) are supported.\r
-``trainData`` must be of ``CV_32F`` type. ``responses`` must be a matrix of type\r
-``CV_32S`` or ``CV_32F``, in both cases it is converted into the ``CV_32F``\r
+``trainData`` must be of the ``CV_32F`` type. ``responses`` must be a matrix of type\r
+``CV_32S`` or ``CV_32F``. In both cases it is converted into the ``CV_32F``\r
 matrix inside the training procedure. ``varIdx`` and ``sampleIdx`` must be a\r
-list of indices (``CV_32S``), or a mask (``CV_8U`` or ``CV_8S``). ``update`` is\r
+list of indices (``CV_32S``) or a mask (``CV_8U`` or ``CV_8S``). ``update`` is\r
 a dummy parameter.\r
 \r
-The second form of :ref:`CvGBTrees::train` function uses :ref:`CvMLData` as a\r
+The second form of :ocv:func:`CvGBTrees::train` function uses :ocv:class:`CvMLData` as a\r
 data set container. ``update`` is still a dummy parameter. \r
 \r
 All parameters specific to the GBT model are passed into the training function\r
-as a :ref:`CvGBTreesParams` structure.\r
-\r
+as a :ocv:class:`CvGBTreesParams` structure.\r
 \r
-.. index:: CvGBTrees::predict\r
-\r
-.. _CvGBTrees::predict:\r
 \r
 CvGBTrees::predict\r
 ------------------\r
-.. c:function:: float predict(const Mat & sample, const Mat & missing=Mat(), const Range & slice = Range::all(), int k=-1) const\r
+Predicts a response for an input sample.\r
 \r
-    Predicts a response for an input sample.\r
\r
-The method predicts the response, corresponding to the given sample\r
-(see :ref:`Predicting with GBT model`).\r
-The result is either the class label or the estimated function value.\r
-:c:func:`predict` method allows to use the parallel version of the GBT model\r
-prediction if the OpenCV is built with the TBB library. In this case predicitons\r
-of single trees are computed in a parallel fashion.\r
-\r
-``sample``\r
-\r
-    An input feature vector, that has the same format as every training set\r
-    element. Hence, if not all the variables were actualy used while training,\r
-    ``sample`` have to contain fictive values on the appropriate places.\r
-    \r
-``missing``\r
+.. ocv:function:: float CvGBTrees::predict(const Mat& sample, const Mat& missing=Mat(), const Range& slice = Range::all(), int k=-1) const\r
 \r
-    The missing values mask. The one dimentional matrix of the same size as\r
-    ``sample`` having a ``CV_8U`` type. ``1`` corresponds to the missing value\r
-    in the same position in the ``sample`` vector. If there are no missing values\r
-    in the feature vector empty matrix can be passed instead of the missing mask.\r
-    \r
-``weak_responses``\r
+.. ocv:function::float CvGBTrees::predict( const CvMat* sample, const CvMat* missing=0, CvMat* weakResponses=0, CvSlice slice = CV_WHOLE_SEQ, int k=-1 ) const\r
 \r
-    In addition to the prediciton of the whole model all the trees' predcitions\r
-    can be obtained by passing a ``weak_responses`` matrix with :math:`K` rows,\r
-    where :math:`K` is the output classes count (1 for the case of regression)\r
-    and having as many columns as the ``slice`` length.\r
-    \r
-``slice``\r
+.. ocv:pyfunction:: cv2.GBTrees.predict(sample[, missing[, slice[, k]]]) -> retval\r
+\r
+   :param sample: Input feature vector that has the same format as every training set\r
+    element. If not all the variables were actualy used during training,\r
+    ``sample`` contains forged values at the appropriate places.\r
     \r
-    Defines the part of the ensemble used for prediction.\r
-    All trees are used when ``slice = Range::all()``. This parameter is useful to\r
-    get predictions of the GBT models with different ensemble sizes learning\r
-    only the one model actually.\r
+   :param missing: Missing values mask, which is a dimentional matrix of the same size as\r
+    ``sample`` having the ``CV_8U`` type. ``1`` corresponds to the missing value\r
+    in the same position in the ``sample`` vector. If there are no missing values\r
+    in the feature vector, an empty matrix can be passed instead of the missing mask.\r
     \r
-``k``\r
+   :param weak_responses: Matrix used to obtain predictions of all the trees.\r
+    The matrix has :math:`K` rows,\r
+    where :math:`K` is the count of output classes (1 for the regression case).\r
+    The matrix has as many columns as the ``slice`` length.\r
     \r
-    In the case of the classification problem not the one, but :math:`K` tree\r
-    ensembles are built (see :ref:`Training the GBT model`). By passing this\r
-    parameter the ouput can be changed to sum of the trees' predictions in the\r
-    ``k``'th ensemble only. To get the total GBT model prediction ``k`` value\r
-    must be -1. For regression problems ``k`` have to be equal to -1 also.\r
+   :param slice: Parameter defining the part of the ensemble used for prediction.\r
+    If ``slice = Range::all()``, all trees are used. Use this parameter to\r
+    get predictions of the GBT models with different ensemble sizes learning\r
+    only one model.\r
     \r
+   :param k: Number of tree ensembles built in case of the classification problem\r
+    (see :ref:`Training the GBT model`). Use this\r
+    parameter to change the ouput to sum of the trees' predictions in the\r
+    ``k``-th ensemble only. To get the total GBT model prediction, ``k`` value\r
+    must be -1. For regression problems, ``k`` is also equal to -1.\r
\r
+The method predicts the response corresponding to the given sample\r
+(see :ref:`Predicting with the GBT model`).\r
+The result is either the class label or the estimated function value. The\r
+:ocv:func:`predict` method enables using the parallel version of the GBT model\r
+prediction if the OpenCV is built with the TBB library. In this case, predictions\r
+of single trees are computed in a parallel fashion. \r
 \r
     \r
-.. index:: CvGBTrees::clear\r
-\r
-.. _CvGBTrees::clear:\r
-\r
 CvGBTrees::clear\r
 ----------------\r
-.. c:function:: void clear()\r
+Clears the model.\r
 \r
-    Clears the model.\r
+.. ocv:function:: void CvGBTrees::clear()\r
     \r
-Deletes the data set information, all the weak models and sets all internal\r
-variables to the initial state. Is called in :ref:`CvGBTrees::train` and in the\r
-destructor.\r
+.. ocv:pyfunction:: cv2.GBTrees.clear() -> None\r
 \r
+The function deletes the data set information and all the weak models and sets all internal\r
+variables to the initial state. The function is called in :ocv:func:`CvGBTrees::train` and in the\r
+destructor.\r
 \r
-.. index:: CvGBTrees::calc_error\r
-\r
-.. _CvGBTrees::calc_error:\r
 \r
 CvGBTrees::calc_error\r
 ---------------------\r
-.. c:function:: float calc_error( CvMLData* _data, int type, std::vector<float> *resp = 0 )\r
-\r
-    Calculates training or testing error.\r
-    \r
-If the :ref:`CvMLData` data is used to store the data set :c:func:`calc_error` can be\r
-used to get the training or testing error easily and (optionally) all predictions\r
-on the training/testing set. If TBB library is used, the error is computed in a\r
-parallel way: predictions for different samples are computed at the same time.\r
-In the case of regression problem mean squared error is returned. For\r
-classifications the result is the misclassification error in percent.\r
+Calculates a training or testing error.\r
 \r
-``_data``\r
+.. ocv:function:: float CvGBTrees::calc_error( CvMLData* _data, int type, std::vector<float> *resp = 0 )\r
 \r
-    Data set.\r
-    \r
-``type``\r
+   :param _data: Data set.\r
     \r
-    Defines what error should be computed: train (``CV_TRAIN_ERROR``) or test\r
+   :param type: Parameter defining the error that should be computed: train (``CV_TRAIN_ERROR``) or test\r
     (``CV_TEST_ERROR``).\r
 \r
-``resp``\r
-    \r
-    If not ``0`` a vector of predictions on the corresponding data set is\r
+   :param resp: If non-zero, a vector of predictions on the corresponding data set is\r
     returned.\r
 \r
+If the :ocv:class:`CvMLData` data is used to store the data set, :ocv:func:`calc_error` can be\r
+used to get a training/testing error easily and (optionally) all predictions\r
+on the training/testing set. If the Intel* TBB* library is used, the error is computed in a\r
+parallel way, namely, predictions for different samples are computed at the same time.\r
+In case of a regression problem, a mean squared error is returned. For\r
+classifications, the result is a misclassification error in percent.\r
index b611d79..d4f225f 100644 (file)
-K Nearest Neighbors
+K-Nearest Neighbors
 ===================
 
-The algorithm caches all training samples and predicts the response for a new sample by analyzing a certain number (
-**K**
-) of the nearest neighbors of the sample (using voting, calculating weighted sum, and so on). The method is sometimes referred to as "learning by example" because for prediction it looks for the feature vector with a known response that is closest to the given vector.
+.. highlight:: cpp
 
-.. index:: CvKNearest
-
-.. _CvKNearest:
+The algorithm caches all training samples and predicts the response for a new sample by analyzing a certain number (**K**) of the nearest neighbors of the sample using voting, calculating weighted sum, and so on. The method is sometimes referred to as "learning by example" because for prediction it looks for the feature vector with a known response that is closest to the given vector.
 
 CvKNearest
 ----------
-.. c:type:: CvKNearest
+.. ocv:class:: CvKNearest
 
-K-Nearest Neighbors model ::
+The class implements K-Nearest Neighbors model as described in the beginning of this section. 
 
-    class CvKNearest : public CvStatModel
-    {
-    public:
+CvKNearest::CvKNearest
+----------------------
+Default and training constructors.
 
-        CvKNearest();
-        virtual ~CvKNearest();
+.. ocv:function:: CvKNearest::CvKNearest()
 
-        CvKNearest( const Mat& _train_data, const Mat& _responses,
-                    const Mat& _sample_idx=Mat(), bool _is_regression=false, int max_k=32 );
+.. ocv:function:: CvKNearest::CvKNearest( const Mat& trainData, const Mat& responses, const Mat& sampleIdx=Mat(), bool isRegression=false, int max_k=32 )
 
-        virtual bool train( const Mat& _train_data, const Mat& _responses,
-                            const Mat& _sample_idx=Mat(), bool is_regression=false,
-                            int _max_k=32, bool _update_base=false );
+.. ocv:function::CvKNearest::CvKNearest( const CvMat* trainData, const CvMat* responses, const CvMat* sampleIdx=0, bool isRegression=false, int max_k=32 )
 
-        virtual float find_nearest( const Mat& _samples, int k, Mat* results=0,
-            const float** neighbors=0, Mat* neighbor_responses=0, Mat* dist=0 ) const;
+See :ocv:func:`CvKNearest::train` for additional parameters descriptions.
 
-        virtual void clear();
-        int get_max_k() const;
-        int get_var_count() const;
-        int get_sample_count() const;
-        bool is_regression() const;
+CvKNearest::train
+-----------------
+Trains the model.
 
-    protected:
-        ...
-    };
+.. ocv:function:: bool CvKNearest::train( const Mat& trainData, const Mat& responses, const Mat& sampleIdx=Mat(), bool isRegression=false, int maxK=32, bool updateBase=false )
 
+.. ocv:function::bool CvKNearest::train( const CvMat* trainData, const CvMat* responses, const CvMat* sampleIdx=0, bool is_regression=false, int maxK=32, bool updateBase=false )
 
-.. index:: CvKNearest::train
+.. ocv:pyfunction:: cv2.KNearest.train(trainData, responses[, sampleIdx[, isRegression[, maxK[, updateBase]]]]) -> retval
 
-.. _CvKNearest::train:
+    :param isRegression: Type of the problem: ``true`` for regression and ``false`` for classification.
 
-CvKNearest::train
------------------
-.. ocv:function:: bool CvKNearest::train(  const Mat& _train_data,  const Mat& _responses,                          const Mat& _sample_idx=Mat(),  bool is_regression=false, int _max_k=32,  bool _update_base=false )
+    :param maxK: Number of maximum neighbors that may be passed to the method :ocv:func:`CvKNearest::find_nearest`.
+
+    :param updateBase: Specifies whether the model is trained from scratch (``update_base=false``), or it is updated using the new training data (``update_base=true``). In the latter case, the parameter ``maxK`` must not be larger than the original value.
 
-    Trains the model.
+The method trains the K-Nearest model. It follows the conventions of the generic :ocv:func:`CvStataModel::train` approach with the following limitations: 
 
-The method trains the K-Nearest model. It follows the conventions of the generic ``train`` "method" with the following limitations: 
 * Only ``CV_ROW_SAMPLE`` data layout is supported.
 * Input variables are all ordered.
 * Output variables can be either categorical ( ``is_regression=false`` ) or ordered ( ``is_regression=true`` ).
-* Variable subsets ( ``var_idx`` ) and missing measurements are not supported.
+* Variable subsets (``var_idx``) and missing measurements are not supported.
 
-The parameter ``_max_k`` specifies the number of maximum neighbors that may be passed to the method ``find_nearest`` .
+CvKNearest::find_nearest
+------------------------
+Finds the neighbors and predicts responses for input vectors.
 
-The parameter ``_update_base`` specifies whether the model is trained from scratch
-( ``_update_base=false`` ), or it is updated using the new training data ( ``_update_base=true`` ). In the latter case, the parameter ``_max_k`` must not be larger than the original value.
+.. ocv:function:: float CvKNearest::find_nearest( const Mat& samples, int k, Mat* results=0, const float** neighbors=0, Mat* neighborResponses=0, Mat* dist=0 ) const
 
-.. index:: CvKNearest::find_nearest
+.. ocv:function:: float CvKNearest::find_nearest( const Mat& samples, int k, Mat& results, Mat& neighborResponses, Mat& dists) const
 
-.. _CvKNearest::find_nearest:
+.. ocv:function::float CvKNearest::find_nearest( const CvMat* samples, int k, CvMat* results=0, const float** neighbors=0, CvMat* neighborResponses=0, CvMat* dist=0 ) const
 
-CvKNearest::find_nearest
-------------------------
-.. ocv:function:: float CvKNearest::find_nearest(  const Mat& _samples,  int k, Mat* results=0,          const float** neighbors=0,  Mat* neighbor_responses=0,  Mat* dist=0 ) const
+.. ocv:pyfunction:: cv2.KNearest.find_nearest(samples, k[, results[, neighborResponses[, dists]]]) -> retval, results, neighborResponses, dists
+
+
+    :param samples: Input samples stored by rows. It is a single-precision floating-point matrix of :math:`number\_of\_samples \times number\_of\_features` size.
+
+    :param k: Number of used nearest neighbors. It must satisfy constraint: :math:`k \le` :ocv:func:`CvKNearest::get_max_k`.
 
-    Finds the neighbors for input vectors.
+    :param results: Vector with results of prediction (regression or classification) for each input sample. It is a single-precision floating-point vector with ``number_of_samples`` elements.
 
-For each input vector (a row of the matrix ``_samples`` ), the method finds the
-:math:`\texttt{k} \le
-\texttt{get\_max\_k()}` nearest neighbor.  In case of regression,
-the predicted result is a mean value of the particular vector's
-neighbor responses. In case of classification, the class is determined
-by voting.
+    :param neighbors: Optional output pointers to the neighbor vectors themselves. It is an array of ``k*samples->rows`` pointers.
 
-For a custom classification/regression prediction, the method can optionally return pointers to the neighbor vectors themselves ( ``neighbors`` , an array of ``k*_samples->rows`` pointers), their corresponding output values ( ``neighbor_responses`` , a vector of ``k*_samples->rows`` elements), and the distances from the input vectors to the neighbors ( ``dist`` , also a vector of ``k*_samples->rows`` elements).
+    :param neighborResponses: Optional output values for corresponding ``neighbors``. It is a single-precision floating-point matrix of :math:`number\_of\_samples \times k` size.
+
+    :param dist: Optional output distances from the input vectors to the corresponding ``neighbors``. It is a single-precision floating-point matrix of :math:`number\_of\_samples \times k` size.
+
+For each input vector (a row of the matrix ``samples``), the method finds the ``k`` nearest neighbors.  In case of regression, the predicted result is a mean value of the particular vector's neighbor responses. In case of classification, the class is determined by voting.
 
 For each input vector, the neighbors are sorted by their distances to the vector.
 
+In case of C++ interface you can use output pointers to empty matrices and the function will allocate memory itself.
+
 If only a single input vector is passed, all output matrices are optional and the predicted value is returned by the method.
 
-The sample below (currently using the obsolete ``CvMat`` structures) demonstrates the use of the k-nearest classifier for 2D point classification ::
+CvKNearest::get_max_k
+---------------------
+Returns the number of maximum neighbors that may be passed to the method :ocv:func:`CvKNearest::find_nearest`.
+
+.. ocv:function:: int CvKNearest::get_max_k() const
+
+CvKNearest::get_var_count
+-------------------------
+Returns the number of used features (variables count).
+
+.. ocv:function:: int CvKNearest::get_var_count() const
+
+CvKNearest::get_sample_count
+----------------------------
+Returns the total number of train samples.
+
+.. ocv:function:: int CvKNearest::get_sample_count() const
+
+CvKNearest::is_regression
+-------------------------
+Returns type of the problem: ``true`` for regression and ``false`` for classification.
+
+.. ocv:function:: bool CvKNearest::is_regression() const
+
+
+
+The sample below (currently using the obsolete ``CvMat`` structures) demonstrates the use of the k-nearest classifier for 2D point classification: ::
 
     #include "ml.h"
     #include "highgui.h"
index 338f73e..f360b3d 100644 (file)
@@ -3,13 +3,13 @@ MLData
 
 .. highlight:: cpp
 
-For the machine learning algorithms usage it is often that data set is saved in file of format like .csv. The supported format file must contains the table of predictors and responses values, each row of the table must correspond to one sample. Missing values are supported. Famous UC Irvine Machine Learning Repository (http://archive.ics.uci.edu/ml/) provides many stored in such format data sets to the machine learning community. The class MLData has been implemented to ease the loading data for the training one of the existing in OpenCV machine learning algorithm. For float values only separator ``'.'`` is supported.
+For the machine learning algorithms, the data set is often stored in a file of the ``.csv``-like format. The file contains a table of predictor and response values where each row of the table corresponds to a sample. Missing values are supported. The UC Irvine Machine Learning Repository (http://archive.ics.uci.edu/ml/) provides many data sets stored in such a format to the machine learning community. The class ``MLData`` is implemented to easily load the data for training one of the OpenCV machine learning algorithms. For float values, only the  ``'.'`` separator is supported.
 
 CvMLData
 --------
 .. ocv:class:: CvMLData
 
-The class to load the data from .csv file. 
+Class for loading the data from a ``.csv`` file. 
 ::
 
     class CV_EXPORTS CvMLData
@@ -56,135 +56,190 @@ The class to load the data from .csv file.
 
 CvMLData::read_csv
 ------------------
+Reads the data set from a ``.csv``-like ``filename`` file and stores all read values in a matrix. 
+
 .. ocv:function:: int CvMLData::read_csv(const char* filename);
 
-    This method reads the data set from .csv-like file named ``filename`` and store all read values in one matrix. While reading the method tries to define variables (predictors and response) type: ordered or categorical. If some value of the variable is not a number (e.g. contains the letters) exept a label for missing value, then the type of the variable is set to ``CV_VAR_CATEGORICAL``. If all unmissing values of the variable are the numbers, then the type of the variable is set to ``CV_VAR_ORDERED``. So default definition of variables types works correctly for all cases except the case of categorical variable that has numerical class labeles. In such case the type ``CV_VAR_ORDERED`` will be set and user should change the type to ``CV_VAR_CATEGORICAL`` using method :ocv:func:`CvMLData::change_var_type`. For categorical variables the common map is built to convert string class label to the numerical class label and this map can be got by :ocv:func:`CvMLData::get_class_labels_map`. Also while reading the data the method constructs the mask of missing values (e.g. values are egual to `'?'`).
+    :param filename: The input file name
+
+While reading the data, the method tries to define the type of variables (predictors and responses): ordered or categorical. If a value of the variable is not numerical (except for the label for a missing value), the type of the variable is set to ``CV_VAR_CATEGORICAL``. If all existing values of the variable are numerical, the type of the variable is set to ``CV_VAR_ORDERED``. So, the default definition of variables types works correctly for all cases except the case of a categorical variable with numerical class labeles. In this case, the type ``CV_VAR_ORDERED`` is set. You should change the type to ``CV_VAR_CATEGORICAL`` using the method :ocv:func:`CvMLData::change_var_type`. For categorical variables, a common map is built to convert a string class label to the numerical class label. Use :ocv:func:`CvMLData::get_class_labels_map` to obtain this map. 
+
+Also, when reading the data, the method constructs the mask of missing values. For example, values are egual to `'?'`.
 
 CvMLData::get_values
 --------------------
+Returns a pointer to the matrix of predictors and response values
+
 .. ocv:function:: const CvMat* CvMLData::get_values() const;
 
-    Returns the pointer to the predictors and responses ``values`` matrix or ``0`` if data has not been loaded from file yet. This matrix has rows count equal to samples count, columns count equal to predictors ``+ 1`` for response (if exist) count (i.e. each row of matrix is values of one sample predictors and response) and type ``CV_32FC1``.
+The method returns a pointer to the matrix of predictor and response ``values``  or ``0`` if the data has not been loaded from the file yet. 
+
+The row count of this matrix equals the sample count. The column count equals predictors ``+ 1`` for the response (if exists) count. This means that each row of the matrix contains values of one sample predictor and response. The matrix type is ``CV_32FC1``.
 
 CvMLData::get_responses
 -----------------------
+Returns a pointer to the matrix of response values
+
 .. ocv:function:: const CvMat* CvMLData::get_responses();
 
-    Returns the pointer to the responses values matrix or throw exception if data has not been loaded from file yet. This matrix has rows count equal to samples count, one column and type ``CV_32FC1``.
+The method returns a pointer to the matrix of response values or throws an exception if the data has not been loaded from the file yet. 
+
+This is a single-column matrix of the type ``CV_32FC1``. Its row count is equal to the sample count, one column and .
 
 CvMLData::get_missing
 ---------------------
+Returns a pointer to the mask matrix of missing values
+
 .. ocv:function:: const CvMat* CvMLData::get_missing() const;
 
-    Returns the pointer to the missing values mask matrix or throw exception if data has not been loaded from file yet. This matrix has the same size as ``values`` matrix (see :ocv:func:`CvMLData::get_values`) and type ``CV_8UC1``.
+The method returns a pointer to the mask matrix of missing values or throws an exception if the data has not been loaded from the file yet. 
+
+This matrix has the same size as the  ``values`` matrix (see :ocv:func:`CvMLData::get_values`) and the type ``CV_8UC1``.
 
 CvMLData::set_response_idx
 --------------------------
+Specifies index of response column in the data matrix
+
 .. ocv:function:: void CvMLData::set_response_idx( int idx );
 
-    Sets index of response column in ``values`` matrix (see :ocv:func:`CvMLData::get_values`) or throw exception if data has not been loaded from file yet. The old response column become pridictors. If ``idx < 0`` there will be no response.
+The method sets the index of a response column in the ``values`` matrix (see :ocv:func:`CvMLData::get_values`) or throws an exception if the data has not been loaded from the file yet. 
+
+The old response columns become predictors. If ``idx < 0``, there is no response.
 
 CvMLData::get_response_idx
-----------
+--------------------------
+Returns index of the response column in the loaded data matrix
+
 .. ocv:function:: int CvMLData::get_response_idx() const;
 
-    Gets response column index in ``values`` matrix (see :ocv:func:`CvMLData::get_values`), negative value there is no response or throw exception if data has not been loaded from file yet.
+The method returns the index of a response column in the ``values`` matrix (see :ocv:func:`CvMLData::get_values`) or throws an exception if the data has not been loaded from the file yet.
+
+If ``idx < 0``, there is no response.
     
 
 CvMLData::set_train_test_split
 ------------------------------
+Divides the read data set into two disjoint training and test subsets. 
+
 .. ocv:function:: void CvMLData::set_train_test_split( const CvTrainTestSplit * spl );
-    
-    For different purposes it can be useful to devide the read data set into two disjoint subsets: training and test ones. This method sets parametes for such split (using ``spl``, see :ocv:class:`CvTrainTestSplit`) and make the data split or throw exception if data has not been loaded from file yet. 
+
+This method sets parameters for such a split using ``spl`` (see :ocv:class:`CvTrainTestSplit`) or throws an exception if the data has not been loaded from the file yet. 
 
 CvMLData::get_train_sample_idx
 ------------------------------
+Returns the matrix of sample indices for a training subset
+
 .. ocv:function:: const CvMat* CvMLData::get_train_sample_idx() const;
 
-    The read data set can be devided on training and test data subsets by setting split (see :ocv:func:`CvMLData::set_train_test_split`). Current method returns the matrix of samples indices for training subset (this matrix has one row and type ``CV_32SC1``). If data split is not set then the method returns ``0``. If data has not been loaded from file yet an exception is thrown.
+The method returns the matrix of sample indices for a training subset. This is a single-row  matrix of the type ``CV_32SC1``. If data split is not set, the method returns ``0``. If the data has not been loaded from the file yet, an exception is thrown.
 
 CvMLData::get_test_sample_idx
 -----------------------------
+Returns the matrix of sample indices for a testing subset
+
 .. ocv:function:: const CvMat* CvMLData::get_test_sample_idx() const;
-    
-    Analogically with :ocv:func:`CvMLData::get_train_sample_idx`, but for test subset.
+
     
 CvMLData::mix_train_and_test_idx
 --------------------------------
+Mixes the indices of training and test samples
+
 .. ocv:function:: void CvMLData::mix_train_and_test_idx();
     
-    Mixes the indices of training and test samples preserving sizes of training and test subsets (if data split is set by :ocv:func:`CvMLData::get_values`). If data has not been loaded from file yet an exception is thrown.
+The method shuffles the indices of training and test samples preserving sizes of training and test subsets if the data split is set by :ocv:func:`CvMLData::get_values`. If the data has not been loaded from the file yet, an exception is thrown.
 
 CvMLData::get_var_idx
 ---------------------
+Returns the indices of the active variables in the data matrix
+
 .. ocv:function:: const CvMat* CvMLData::get_var_idx();
     
-    Returns used variables (columns) indices in the ``values`` matrix (see :ocv:func:`CvMLData::get_values`), ``0`` if used subset is not set or throw exception if data has not been loaded from file yet. Returned matrix has one row, columns count equel to used variable subset size and type ``CV_32SC1``.
+The method returns the indices of variables (columns) used in the ``values`` matrix (see :ocv:func:`CvMLData::get_values`). 
+
+It returns ``0`` if the used subset is not set. It throws an exception if the data has not been loaded from the file yet. Returned matrix is a single-row matrix of the type ``CV_32SC1``. Its column count is equal to the size of the used variable subset.
 
 CvMLData::chahge_var_idx
 ------------------------
+Enables or disables particular variable in the loaded data
+
 .. ocv:function:: void CvMLData::chahge_var_idx( int vi, bool state );
 
-    By default after reading the data set all variables in ``values`` matrix (see :ocv:func:`CvMLData::get_values`) are used. But the user may want to use only subset of variables and can include on/off (depends on ``state`` value) a variable with ``vi`` index from used subset. If data has not been loaded from file yet an exception is thrown.
+By default, after reading the data set all variables in the ``values`` matrix (see :ocv:func:`CvMLData::get_values`) are used. But you may want to use only a subset of variables and include/exclude (depending on ``state`` value) a variable with the ``vi`` index from the used subset. If the data has not been loaded from the file yet, an exception is thrown.
     
 CvMLData::get_var_types
 -----------------------
+Returns a matrix of the variable types. 
+
 .. ocv:function:: const CvMat* CvMLData::get_var_types();
-    Returns matrix of used variable types. The matrix has one row, column count equel to used variables count and type ``CV_8UC1``. If data has not been loaded from file yet an exception is thrown.
+    
+The function returns a single-row matrix of the type ``CV_8UC1``, where each element is set to either ``CV_VAR_ORDERED`` or ``CV_VAR_CATEGORICAL``. The number of columns is equal to the number of variables. If data has not been loaded from file yet an exception is thrown.
     
 CvMLData::set_var_types
 -----------------------
+Sets the variables types in the loaded data.
+
 .. ocv:function:: void CvMLData::set_var_types( const char* str );
 
-    Sets variables types according to given string ``str``. The better description of the supporting string format is several examples of it: ``"ord[0-17],cat[18]"``, ``"ord[0,2,4,10-12], cat[1,3,5-9,13,14]"``, ``"cat"`` (all variables are categorical), ``"ord"`` (all variables are ordered). That is after the variable type a list of such type variables indices is followed.
+In the string, a variable type is followed by a list of variables indices. For example: ``"ord[0-17],cat[18]"``, ``"ord[0,2,4,10-12], cat[1,3,5-9,13,14]"``, ``"cat"`` (all variables are categorical), ``"ord"`` (all variables are ordered). 
 
 CvMLData::get_var_type
 ----------------------
+Returns type of the specified variable
+
 .. ocv:function:: int CvMLData::get_var_type( int var_idx ) const;
 
-    Returns type of variable by index ``var_idx`` ( ``CV_VAR_ORDERED`` or ``CV_VAR_CATEGORICAL``).
+The method returns the type of a variable by the index ``var_idx`` ( ``CV_VAR_ORDERED`` or ``CV_VAR_CATEGORICAL``).
     
 CvMLData::change_var_type
 -------------------------
+Changes type of the specified variable
+
 .. ocv:function:: void CvMLData::change_var_type( int var_idx, int type);
     
-    Changes type of variable with index ``var_idx`` from existing type to ``type`` ( ``CV_VAR_ORDERED`` or ``CV_VAR_CATEGORICAL``).
+The method changes type of variable with index ``var_idx`` from existing type to ``type`` ( ``CV_VAR_ORDERED`` or ``CV_VAR_CATEGORICAL``).
      
 CvMLData::set_delimiter
 -----------------------
+Sets the delimiter in the file used to separate input numbers
+
 .. ocv:function:: void CvMLData::set_delimiter( char ch );
 
-    Sets the delimiter for the variable values in file. E.g. ``','`` (default), ``';'``, ``' '`` (space) or other character (exapt float separator ``'.'``).
+The method sets the delimiter for variables in a file. For example: ``','`` (default), ``';'``, ``' '`` (space), or other characters. The floating-point separator ``'.'`` is not allowed.
 
 CvMLData::get_delimiter
 -----------------------
+Returns the currently used delimiter character.
+
 .. ocv:function:: char CvMLData::get_delimiter() const;
 
-    Gets the set delimiter charecter.
 
 CvMLData::set_miss_ch
 ---------------------
+Sets the character used to specify missing values
+
 .. ocv:function:: void CvMLData::set_miss_ch( char ch );
 
-    Sets the character denoting the missing of value. E.g. ``'?'`` (default), ``'-'``, etc (exapt float separator ``'.'``).
+The method sets the character used to specify missing values. For example: ``'?'`` (default), ``'-'``. The floating-point separator ``'.'`` is not allowed.
 
 CvMLData::get_miss_ch
 ---------------------
-.. ocv:function:: char CvMLData::get_miss_ch() const;
+Returns the currently used missing value character.
 
-    Gets the character denoting the missing value.
+.. ocv:function:: char CvMLData::get_miss_ch() const;
 
 CvMLData::get_class_labels_map
 -------------------------------
+Returns a map that converts strings to labels.
+
 .. ocv:function:: const std::map<std::string, int>& CvMLData::get_class_labels_map() const;
 
-    Returns map that converts string class labels to the numerical class labels. It can be used to get original class label (as in file).
+The method returns a map that converts string class labels to the numerical class labels. It can be used to get an original class label as in a file.
 
 CvTrainTestSplit
 ----------------
 .. ocv:class:: CvTrainTestSplit
 
-The structure to set split of data set read by :ocv:class:`CvMLData`.
+Structure setting the split of a data set read by :ocv:class:`CvMLData`.
 ::
 
     struct CvTrainTestSplit
@@ -203,4 +258,8 @@ The structure to set split of data set read by :ocv:class:`CvMLData`.
         bool mix;
     };
 
-There are two ways to construct split. The first is by setting training sample count (subset size) ``train_sample_count``; other existing samples will be in test subset. The second is by setting training sample portion in ``[0,..1]``. The flag ``mix`` is used to mix training and test samples indices when split will be set, otherwise the data set will be devided in the storing order (first part of samples of given size is the training subset, other part is the test one).
+There are two ways to construct a split:
+
+* Set the training sample count (subset size) ``train_sample_count``. Other existing samples are located in a test subset. 
+
+* Set a training sample portion in ``[0,..1]``. The flag ``mix`` is used to mix training and test samples indices when the split is set. Otherwise, the data set is split in the storing order: the first part of samples of a given size is a training subset, the second part is a test subset.
index e38c1cc..89b11f1 100644 (file)
@@ -1,7 +1,9 @@
 Neural Networks
 ===============
 
-ML implements feed-forward artificial neural networks, more particularly, multi-layer perceptrons (MLP), the most commonly used type of neural networks. MLP consists of the input layer, output layer, and one or more hidden layers. Each layer of MLP includes one or more neurons that are directionally linked with the neurons from the previous and the next layer. The example below represents a 3-layer perceptron with three inputs, two outputs, and the hidden layer including five neurons:
+.. highlight:: cpp
+
+ML implements feed-forward artificial neural networks or, more particularly, multi-layer perceptrons (MLP), the most commonly used type of neural networks. MLP consists of the input layer, output layer, and one or more hidden layers. Each layer of MLP includes one or more neurons directionally linked with the neurons from the previous and the next layer. The example below represents a 3-layer perceptron with three inputs, two outputs, and the hidden layer including five neurons:
 
 .. image:: pics/mlp.png
 
@@ -45,10 +47,13 @@ In ML, all the neurons have the same activation functions, with the same free pa
 
 So, the whole trained network works as follows: 
 
-#. It takes the feature vector as input. The vector size is equal to the size of the input layer.
-#. Values are passed as input to the first hidden layer.
-#. Outputs of the hidden layer are computed using the weights and the activation functions.
-#. Outputs are passed further downstream until you compute the output layer.
+#. Take the feature vector as input. The vector size is equal to the size of the input layer.
+
+#. Pass values as input to the first hidden layer.
+
+#. Compute outputs of the hidden layer using the weights and the activation functions.
+
+#. Pass outputs further downstream until you compute the output layer.
 
 So, to compute the network, you need to know all the
 weights
@@ -66,10 +71,10 @@ so the error on the test set usually starts increasing after the network
 size reaches a limit. Besides, the larger networks are trained much
 longer than the smaller ones, so it is reasonable to pre-process the data,
 using
-:ref:`PCA::operator ()` or similar technique, and train a smaller network
+:ocv:func:`PCA::operator ()` or similar technique, and train a smaller network
 on only essential features.
 
-Another feature of MLP's is their inability to handle categorical
+Another MPL feature is an inability to handle categorical
 data as is. However, there is a workaround. If a certain feature in the
 input or output (in case of ``n`` -class classifier for
 :math:`n>2` ) layer is categorical and can take
@@ -83,187 +88,189 @@ ML implements two algorithms for training MLP's. The first algorithm is a classi
 random sequential back-propagation algorithm.
 The second (default) one is a batch RPROP algorithm.
 
-References:
+.. [BackPropWikipedia] http://en.wikipedia.org/wiki/Backpropagation. Wikipedia article about the back-propagation algorithm.
 
-*
-    http://en.wikipedia.org/wiki/Backpropagation
-    . Wikipedia article about the back-propagation algorithm.
+.. [LeCun98] Y. LeCun, L. Bottou, G.B. Orr and K.-R. Muller, *Efficient backprop*, in Neural Networks---Tricks of the Trade, Springer Lecture Notes in Computer Sciences 1524, pp.5-50, 1998.
 
-*
-    Y. LeCun, L. Bottou, G.B. Orr and K.-R. Muller, *Efficient backprop*, in Neural Networks---Tricks of the Trade, Springer Lecture Notes in Computer Sciences 1524, pp.5-50, 1998.
+.. [RPROP93] M. Riedmiller and H. Braun, *A Direct Adaptive Method for Faster Backpropagation Learning: The RPROP Algorithm*, Proc. ICNN, San Francisco (1993).
+    
 
-*
-    M. Riedmiller and H. Braun, *A Direct Adaptive Method for Faster Backpropagation Learning: The RPROP Algorithm*, Proc. ICNN, San Francisco (1993).
+CvANN_MLP_TrainParams
+---------------------
+.. ocv:class:: CvANN_MLP_TrainParams
 
-.. index:: CvANN_MLP_TrainParams
+Parameters of the MLP training algorithm. You can initialize the structure by a constructor or the individual parameters can be adjusted after the structure is created.
 
-.. _CvANN_MLP_TrainParams:
+The back-propagation algorithm parameters:
 
-CvANN_MLP_TrainParams
----------------------
-.. c:type:: CvANN_MLP_TrainParams
+.. ocv:member:: double bp_dw_scale
 
-Parameters of the MLP training algorithm ::
+    Strength of the weight gradient term. The recommended value is about 0.1.
+
+.. ocv:member:: double bp_moment_scale
+
+    Strength of the momentum term (the difference between weights on the 2 previous iterations). This parameter provides some inertia to smooth the random fluctuations of the weights. It can vary from 0 (the feature is disabled) to 1 and beyond. The value 0.1 or so is good enough
+
+The RPROP algorithm parameters (see [RPROP93]_ for details):
+
+.. ocv:member:: double rp_dw0
+
+    Initial value :math:`\Delta_0` of update-values :math:`\Delta_{ij}`.
+
+.. ocv:member:: double rp_dw_plus
+
+    Increase factor :math:`\eta^+`. It must be >1.
+
+.. ocv:member:: double rp_dw_minus
+
+    Decrease factor :math:`\eta^-`. It must be <1.
+
+.. ocv:member:: double rp_dw_min
+
+    Update-values lower limit :math:`\Delta_{min}`. It must be positive.
+
+.. ocv:member:: double rp_dw_max
+
+    Update-values upper limit :math:`\Delta_{max}`. It must be >1.
 
-    struct CvANN_MLP_TrainParams
-    {
-        CvANN_MLP_TrainParams();
-        CvANN_MLP_TrainParams( CvTermCriteria term_crit, int train_method,
-                               double param1, double param2=0 );
-        ~CvANN_MLP_TrainParams();
 
-        enum { BACKPROP=0, RPROP=1 };
+CvANN_MLP_TrainParams::CvANN_MLP_TrainParams
+--------------------------------------------
+The constructors.
 
-        CvTermCriteria term_crit;
-        int train_method;
+.. ocv:function:: CvANN_MLP_TrainParams::CvANN_MLP_TrainParams()
 
-        // back-propagation parameters
-        double bp_dw_scale, bp_moment_scale;
+.. ocv:function:: CvANN_MLP_TrainParams::CvANN_MLP_TrainParams( CvTermCriteria term_crit, int train_method, double param1, double param2=0 )
 
-        // rprop parameters
-        double rp_dw0, rp_dw_plus, rp_dw_minus, rp_dw_min, rp_dw_max;
-    };
+    :param term_crit: Termination criteria of the training algorithm. You can specify the maximum number of iterations (``max_iter``) and/or how much the error could change between the iterations to make the algorithm continue (``epsilon``).
 
+    :param train_method: Training method of the MLP. Possible values are:
 
+        * **CvANN_MLP_TrainParams::BACKPROP** The back-propagation algorithm.
 
-The structure has a default constructor that initializes parameters for the ``RPROP`` algorithm. There is also a more advanced constructor to customize the parameters and/or choose the back-propagation algorithm. Finally, the individual parameters can be adjusted after the structure is created.
+        * **CvANN_MLP_TrainParams::RPROP** The RPROP algorithm.
 
-.. index:: CvANN_MLP
+    :param param1: Parameter of the training method. It is ``rp_dw0`` for ``RPROP`` and ``bp_dw_scale`` for ``BACKPROP``.
 
-.. _CvANN_MLP:
+    :param param2: Parameter of the training method. It is ``rp_dw_min`` for ``RPROP`` and ``bp_moment_scale`` for ``BACKPROP``.
+
+By default the RPROP algorithm is used:
+
+::
+
+    CvANN_MLP_TrainParams::CvANN_MLP_TrainParams()
+    {
+        term_crit = cvTermCriteria( CV_TERMCRIT_ITER + CV_TERMCRIT_EPS, 1000, 0.01 );
+        train_method = RPROP;
+        bp_dw_scale = bp_moment_scale = 0.1;
+        rp_dw0 = 0.1; rp_dw_plus = 1.2; rp_dw_minus = 0.5;
+        rp_dw_min = FLT_EPSILON; rp_dw_max = 50.;
+    }
 
 CvANN_MLP
 ---------
-.. c:type:: CvANN_MLP
+.. ocv:class:: CvANN_MLP
 
-MLP model ::
+MLP model.   
+
+Unlike many other models in ML that are constructed and trained at once, in the MLP model these steps are separated. First, a network with the specified topology is created using the non-default constructor or the method :ocv:func:`CvANN_MLP::create`. All the weights are set to zeros. Then, the network is trained using a set of input and output vectors. The training procedure can be repeated more than once, that is, the weights can be adjusted based on the new training data.
 
-    class CvANN_MLP : public CvStatModel
-    {
-    public:
-        CvANN_MLP();
-        CvANN_MLP( const Mat& _layer_sizes,
-                   int _activ_func=SIGMOID_SYM,
-                   double _f_param1=0, double _f_param2=0 );
-
-        virtual ~CvANN_MLP();
-
-        virtual void create( const Mat& _layer_sizes,
-                             int _activ_func=SIGMOID_SYM,
-                             double _f_param1=0, double _f_param2=0 );
-
-        virtual int train( const Mat& _inputs, const Mat& _outputs,
-                           const Mat& _sample_weights,
-                           const Mat& _sample_idx=Mat(),
-                           CvANN_MLP_TrainParams _params = CvANN_MLP_TrainParams(),
-                           int flags=0 );
-        virtual float predict( const Mat& _inputs,
-                               Mat& _outputs ) const;
-
-        virtual void clear();
-
-        // possible activation functions
-        enum { IDENTITY = 0, SIGMOID_SYM = 1, GAUSSIAN = 2 };
-
-        // available training flags
-        enum { UPDATE_WEIGHTS = 1, NO_INPUT_SCALE = 2, NO_OUTPUT_SCALE = 4 };
-
-        virtual void read( CvFileStorage* fs, CvFileNode* node );
-        virtual void write( CvFileStorage* storage, const char* name );
-
-        int get_layer_count() { return layer_sizes ? layer_sizes->cols : 0; }
-        const Mat& get_layer_sizes() { return layer_sizes; }
-
-    protected:
-
-        virtual bool prepare_to_train( const Mat& _inputs, const Mat& _outputs,
-                const Mat& _sample_weights, const Mat& _sample_idx,
-                CvANN_MLP_TrainParams _params,
-                CvVectors* _ivecs, CvVectors* _ovecs, double** _sw, int _flags );
-
-        // sequential random backpropagation
-        virtual int train_backprop( CvVectors _ivecs, CvVectors _ovecs,
-                                                    const double* _sw );
-
-        // RPROP algorithm
-        virtual int train_rprop( CvVectors _ivecs, CvVectors _ovecs,
-                                                 const double* _sw );
-
-        virtual void calc_activ_func( Mat& xf, const double* bias ) const;
-        virtual void calc_activ_func_deriv( Mat& xf, Mat& deriv,
-                                                 const double* bias ) const;
-        virtual void set_activ_func( int _activ_func=SIGMOID_SYM,
-                                     double _f_param1=0, double _f_param2=0 );
-        virtual void init_weights();
-        virtual void scale_input( const Mat& _src, Mat& _dst ) const;
-        virtual void scale_output( const Mat& _src, Mat& _dst ) const;
-        virtual void calc_input_scale( const CvVectors* vecs, int flags );
-        virtual void calc_output_scale( const CvVectors* vecs, int flags );
-
-        virtual void write_params( CvFileStorage* fs );
-        virtual void read_params( CvFileStorage* fs, CvFileNode* node );
-
-        Mat& layer_sizes;
-        Mat& wbuf;
-        Mat& sample_weights;
-        double** weights;
-        double f_param1, f_param2;
-        double min_val, max_val, min_val1, max_val1;
-        int activ_func;
-        int max_count, max_buf_sz;
-        CvANN_MLP_TrainParams params;
-        CvRNG rng;
-    };
-    
 
+CvANN_MLP::CvANN_MLP
+--------------------
+The constructors.
 
-Unlike many other models in ML that are constructed and trained at once, in the MLP model these steps are separated. First, a network with the specified topology is created using the non-default constructor or the method ``create`` . All the weights are set to zeros. Then, the network is trained using a set of input and output vectors. The training procedure can be repeated more than once, that is, the weights can be adjusted based on the new training data.
+.. ocv:function:: CvANN_MLP::CvANN_MLP()
 
-.. index:: CvANN_MLP::create
+.. ocv:function::CvANN_MLP::CvANN_MLP( const CvMat* layerSizes, int activateFunc=CvANN_MLP::SIGMOID_SYM, double fparam1=0, double fparam2=0 )
 
-.. _CvANN_MLP::create:
+.. ocv:pyfunction:: cv2.ANN_MLP(layerSizes[, activateFunc[, fparam1[, fparam2]]]) -> <ANN_MLP object>
+
+The advanced constructor allows to create MLP with the specified topology. See :ocv:func:`CvANN_MLP::create` for details.
 
 CvANN_MLP::create
 -----------------
-.. ocv:function:: void CvANN_MLP::create(  const Mat& _layer_sizes,                          int _activ_func=SIGMOID_SYM,                          double _f_param1=0,  double _f_param2=0 )
+Constructs MLP with the specified topology.
 
-    Constructs MLP with the specified topology.
+.. ocv:function:: void CvANN_MLP::create( const Mat& layerSizes, int activateFunc=CvANN_MLP::SIGMOID_SYM, double fparam1=0, double fparam2=0 )
 
-    :param _layer_sizes: Integer vector specifying the number of neurons in each layer including the input and output layers.
+.. ocv:function::void CvANN_MLP::create( const CvMat* layerSizes, int activateFunc=CvANN_MLP::SIGMOID_SYM, double fparam1=0, double fparam2=0 )
 
-    :param _activ_func: Parameter specifying the activation function for each neuron: one of  ``CvANN_MLP::IDENTITY`` ,  ``CvANN_MLP::SIGMOID_SYM`` , and  ``CvANN_MLP::GAUSSIAN`` .
+.. ocv:pyfunction:: cv2.ANN_MLP.create(layerSizes[, activateFunc[, fparam1[, fparam2]]]) -> None
 
-    :param _f_param1,_f_param2: Free parameters of the activation function,  :math:`\alpha`  and  :math:`\beta` , respectively. See the formulas in the introduction section.
+    :param layerSizes: Integer vector specifying the number of neurons in each layer including the input and output layers.
 
-The method creates an MLP network with the specified topology and assigns the same activation function to all the neurons.
+    :param activateFunc: Parameter specifying the activation function for each neuron: one of  ``CvANN_MLP::IDENTITY``, ``CvANN_MLP::SIGMOID_SYM``, and ``CvANN_MLP::GAUSSIAN``.
 
-.. index:: CvANN_MLP::train
+    :param fparam1/fparam2: Free parameters of the activation function, :math:`\alpha` and :math:`\beta`, respectively. See the formulas in the introduction section.
 
-.. _CvANN_MLP::train:
+The method creates an MLP network with the specified topology and assigns the same activation function to all the neurons.
 
 CvANN_MLP::train
 ----------------
-.. ocv:function:: int CvANN_MLP::train(  const Mat& _inputs,  const Mat& _outputs,                        const Mat& _sample_weights,  const Mat& _sample_idx=Mat(),                        CvANN_MLP_TrainParams _params = CvANN_MLP_TrainParams(),                        int flags=0 )
+Trains/updates MLP.
 
-    Trains/updates MLP.
+.. ocv:function:: int CvANN_MLP::train( const Mat& inputs, const Mat& outputs, const Mat& sampleWeights, const Mat& sampleIdx=Mat(), CvANN_MLP_TrainParams params = CvANN_MLP_TrainParams(), int flags=0 )
 
-    :param _inputs: Floating-point matrix of input vectors, one vector per row.
+.. ocv:function::int CvANN_MLP::train( const CvMat* inputs, const CvMat* outputs, const CvMat* sampleWeights, const CvMat* sampleIdx=0, CvANN_MLP_TrainParams params = CvANN_MLP_TrainParams(), int flags=0 )
 
-    :param _outputs: Floating-point matrix of the corresponding output vectors, one vector per row.
+.. ocv:pyfunction:: cv2.ANN_MLP.train(inputs, outputs, sampleWeights[, sampleIdx[, params[, flags]]]) -> niterations
 
-    :param _sample_weights: (RPROP only) Optional floating-point vector of weights for each sample. Some samples may be more important than others for training. You may want to raise the weight of certain classes to find the right balance between hit-rate and false-alarm rate, and so on.
+    :param inputs: Floating-point matrix of input vectors, one vector per row.
 
-    :param _sample_idx: Optional integer vector indicating the samples (rows of  ``_inputs``  and  ``_outputs`` ) that are taken into account.
+    :param outputs: Floating-point matrix of the corresponding output vectors, one vector per row.
 
-    :param _params: Training parameters. See the ``CvANN_MLP_TrainParams``  description.
+    :param sampleWeights: (RPROP only) Optional floating-point vector of weights for each sample. Some samples may be more important than others for training. You may want to raise the weight of certain classes to find the right balance between hit-rate and false-alarm rate, and so on.
 
-    :param _flags: Various parameters to control the training algorithm. A combination of the following parameters is possible:
+    :param sampleIdx: Optional integer vector indicating the samples (rows of ``inputs`` and ``outputs``) that are taken into account.
 
-            * **UPDATE_WEIGHTS = 1** Algorithm updates the network weights, rather than computes them from scratch (in the latter case the weights are initialized using the  Nguyen-Widrow  algorithm).
+    :param params: Training parameters. See the :ocv:class:`CvANN_MLP_TrainParams` description.
 
-            * **NO_INPUT_SCALE** Algorithm does not normalize the input vectors. If this flag is not set, the training algorithm normalizes each input feature independently, shifting its mean value to 0 and making the standard deviation =1. If the network is assumed to be updated frequently, the new training data could be much different from original one. In this case, you should take care of proper normalization.
+    :param flags: Various parameters to control the training algorithm. A combination of the following parameters is possible:
+
+            * **UPDATE_WEIGHTS** Algorithm updates the network weights, rather than computes them from scratch. In the latter case the weights are initialized using the Nguyen-Widrow algorithm.
+
+            * **NO_INPUT_SCALE** Algorithm does not normalize the input vectors. If this flag is not set, the training algorithm normalizes each input feature independently, shifting its mean value to 0 and making the standard deviation equal to 1. If the network is assumed to be updated frequently, the new training data could be much different from original one. In this case, you should take care of proper normalization.
 
             * **NO_OUTPUT_SCALE** Algorithm does not normalize the output vectors. If the flag is not set, the training algorithm normalizes each output feature independently, by transforming it to the certain range depending on the used activation function.
 
 This method applies the specified training algorithm to computing/adjusting the network weights. It returns the number of done iterations.
 
+CvANN_MLP::predict
+------------------
+Predicts responses for input samples.
+
+.. ocv:function:: float CvANN_MLP::predict( const Mat& inputs, Mat& outputs ) const
+
+.. ocv:function::float CvANN_MLP::predict( const CvMat* inputs, CvMat* outputs ) const
+
+.. ocv:pyfunction:: cv2.ANN_MLP.predict(inputs, outputs) -> retval
+
+    :param inputs: Input samples.
+
+    :param outputs: Predicted responses for corresponding samples.
+
+The method returns a dummy value which should be ignored.
+
+CvANN_MLP::get_layer_count
+--------------------------
+Returns the number of layers in the MLP.
+
+.. ocv:function:: int CvANN_MLP::get_layer_count()
+
+CvANN_MLP::get_layer_sizes
+--------------------------
+Returns numbers of neurons in each layer of the MLP.
+
+.. ocv:function::const CvMat* CvANN_MLP::get_layer_sizes()
+
+The method returns the integer vector specifying the number of neurons in each layer including the input and output layers of the MLP.
+
+CvANN_MLP::get_weights
+----------------------
+Returns neurons weights of the particular layer.
+
+.. ocv:function:: double* CvANN_MLP::get_weights(int layer)
+
+    :param layer: Index of the particular layer.
+    
\ No newline at end of file
index 1107bd1..42af24d 100644 (file)
@@ -3,71 +3,60 @@
 Normal Bayes Classifier
 =======================
 
-This is a simple classification model assuming that feature vectors from each class are normally distributed (though, not necessarily independently distributed). So, the whole data distribution function is assumed to be a Gaussian mixture, one component per  class. Using the training data the algorithm estimates mean vectors and covariance matrices for every class, and then it uses them for prediction.
+.. highlight:: cpp
 
-[Fukunaga90] K. Fukunaga. *Introduction to Statistical Pattern Recognition*. second ed., New York: Academic Press, 1990.
+This simple classification model assumes that feature vectors from each class are normally distributed (though, not necessarily independently distributed). So, the whole data distribution function is assumed to be a Gaussian mixture, one component per  class. Using the training data the algorithm estimates mean vectors and covariance matrices for every class, and then it uses them for prediction.
 
-.. index:: CvNormalBayesClassifier
+.. [Fukunaga90] K. Fukunaga. *Introduction to Statistical Pattern Recognition*. second ed., New York: Academic Press, 1990.
 
 CvNormalBayesClassifier
 -----------------------
-.. c:type:: CvNormalBayesClassifier
+.. ocv:class:: CvNormalBayesClassifier
 
-Bayes classifier for normally distributed data ::
+Bayes classifier for normally distributed data.
 
-    class CvNormalBayesClassifier : public CvStatModel
-    {
-    public:
-        CvNormalBayesClassifier();
-        virtual ~CvNormalBayesClassifier();
+CvNormalBayesClassifier::CvNormalBayesClassifier
+------------------------------------------------
+Default and training constructors.
 
-        CvNormalBayesClassifier( const Mat& _train_data, const Mat& _responses,
-            const Mat& _var_idx=Mat(), const Mat& _sample_idx=Mat() );
+.. ocv:function:: CvNormalBayesClassifier::CvNormalBayesClassifier()
 
-        virtual bool train( const Mat& _train_data, const Mat& _responses,
-            const Mat& _var_idx=Mat(), const Mat& _sample_idx=Mat(), bool update=false );
+.. ocv:function:: CvNormalBayesClassifier::CvNormalBayesClassifier( const Mat& trainData, const Mat& responses, const Mat& varIdx=Mat(), const Mat& sampleIdx=Mat() )
 
-        virtual float predict( const Mat& _samples, Mat* results=0 ) const;
-        virtual void clear();
+.. ocv:function::CvNormalBayesClassifier::CvNormalBayesClassifier( const CvMat* trainData, const CvMat* responses, const CvMat* varIdx=0, const CvMat* sampleIdx=0 )
 
-        virtual void save( const char* filename, const char* name=0 );
-        virtual void load( const char* filename, const char* name=0 );
+.. ocv:pyfunction:: cv2.NormalBayesClassifier(trainData, responses[, varIdx[, sampleIdx]]) -> <NormalBayesClassifier object>
 
-        virtual void write( CvFileStorage* storage, const char* name );
-        virtual void read( CvFileStorage* storage, CvFileNode* node );
-    protected:
-        ...
-    };
+The constructors follow conventions of :ocv:func:`CvStatModel::CvStatModel`. See :ocv:func:`CvStatModel::train` for parameters descriptions.
 
+CvNormalBayesClassifier::train
+------------------------------
+Trains the model.
 
-.. index:: CvNormalBayesClassifier::train
+.. ocv:function:: bool CvNormalBayesClassifier::train( const Mat& trainData, const Mat& responses, const Mat& varIdx = Mat(), const Mat& sampleIdx=Mat(), bool update=false )
 
-.. _CvNormalBayesClassifier::train:
+.. ocv:function::bool CvNormalBayesClassifier::train( const CvMat* trainData, const CvMat* responses, const CvMat* varIdx = 0, const CvMat* sampleIdx=0, bool update=false )
 
-CvNormalBayesClassifier::train
-------------------------------
-.. ocv:function:: bool CvNormalBayesClassifier::train(  const Mat& _train_data,  const Mat& _responses,                 const Mat& _var_idx =Mat(),  const Mat& _sample_idx=Mat(),  bool update=false )
+.. ocv:pyfunction:: cv2.NormalBayesClassifier.train(trainData, responses[, varIdx[, sampleIdx[, update]]]) -> retval
 
-    Trains the model.
+    :param update: Identifies whether the model should be trained from scratch (``update=false``) or should be updated using the new training data (``update=true``).
 
-The method trains the Normal Bayes classifier. It follows the conventions of the generic ``train`` "method" with the following limitations: 
+The method trains the Normal Bayes classifier. It follows the conventions of the generic :ocv:func:`CvStatModel::train` approach with the following limitations: 
 
 * Only ``CV_ROW_SAMPLE`` data layout is supported.
 * Input variables are all ordered.
-* Output variable is categorical , which means that elements of ``_responses`` must be integer numbers, though the vector may have the ``CV_32FC1`` type.
+* Output variable is categorical , which means that elements of ``responses`` must be integer numbers, though the vector may have the ``CV_32FC1`` type.
 * Missing measurements are not supported.
 
-In addition, there is an ``update`` flag that identifies whether the model should be trained from scratch ( ``update=false`` ) or should be updated using the new training data ( ``update=true`` ).
-
-.. index:: CvNormalBayesClassifier::predict
-
-.. _CvNormalBayesClassifier::predict:
-
 CvNormalBayesClassifier::predict
 --------------------------------
+Predicts the response for sample(s).
+
 .. ocv:function:: float CvNormalBayesClassifier::predict(  const Mat& samples,  Mat* results=0 ) const
 
-    Predicts the response for sample(s).
+.. ocv:function::float CvNormalBayesClassifier::predict( const CvMat* samples, CvMat* results=0 ) const
+
+.. ocv:pyfunction:: cv2.NormalBayesClassifier.predict(samples) -> retval, results
 
-The method ``predict`` estimates the most probable classes for input vectors. Input vectors (one or more) are stored as rows of the matrix ``samples`` . In case of multiple input vectors, there should be one output vector ``results`` . The predicted class for a single input vector is returned by the method.
+The method estimates the most probable classes for input vectors. Input vectors (one or more) are stored as rows of the matrix ``samples``. In case of multiple input vectors, there should be one output vector ``results``. The predicted class for a single input vector is returned by the method.
 
index 1449280..a1f3577 100644 (file)
@@ -3,13 +3,15 @@
 Random Trees
 ============
 
+.. highlight:: cpp
+
 Random trees have been introduced by Leo Breiman and Adele Cutler:
 http://www.stat.berkeley.edu/users/breiman/RandomForests/
 . The algorithm can deal with both classification and regression problems. Random trees is a collection (ensemble) of tree predictors that is called
 *forest*
-further in this section (the term has been also introduced by L. Breiman). The classification works as follows: the random trees classifier takes the input feature vector, classifies it with every tree in the forest, and outputs the class label that recieved the majority of "votes". In case of regression, the classifier response is the average of the responses over all the trees in the forest.
+further in this section (the term has been also introduced by L. Breiman). The classification works as follows: the random trees classifier takes the input feature vector, classifies it with every tree in the forest, and outputs the class label that recieved the majority of "votes". In case of regression, the classifier response is the average of the responses over all the trees in the forest.
 
-All the trees are trained with the same parameters but on different training sets that are generated from the original training set using the bootstrap procedure: for each training set, you randomly select the same number of vectors as in the original set ( ``=N`` ). The vectors are chosen with replacement. That is, some vectors will occur more than once and some will be absent. At each node of each trained tree,  not all the variables are used to find the best split, rather than a random subset of them. With each node a new subset is generated. However, its size is fixed for all the nodes and all the trees. It is a training parameter set to
+All the trees are trained with the same parameters but on different training sets. These sets are generated from the original training set using the bootstrap procedure: for each training set, you randomly select the same number of vectors as in the original set ( ``=N`` ). The vectors are chosen with replacement. That is, some vectors will occur more than once and some will be absent. At each node of each trained tree,  not all the variables are used to find the best split, but a random subset of them. With each node a new subset is generated. However, its size is fixed for all the nodes and all the trees. It is a training parameter set to
 :math:`\sqrt{number\_of\_variables}` by default. None of the built trees are pruned.
 
 In random trees there is no need for any accuracy estimation procedures, such as cross-validation or bootstrap, or a separate test set to get an estimate of the training error. The error is estimated internally during the training. When the training set for the current tree is drawn by sampling with replacement, some vectors are left out (so-called
@@ -20,25 +22,28 @@ In random trees there is no need for any accuracy estimation procedures, such as
     Get a prediction for each vector, which is oob relative to the i-th tree, using the very i-th tree.
 
 #.
-    After all the trees have been trained, for each vector that has ever been oob, find the class-"winner" for it (the class that has got the majority of votes in the trees where the vector was oob) and compare it to the ground-truth response.
+    After all the trees have been trained, for each vector that has ever been oob, find the class-*winner* for it (the class that has got the majority of votes in the trees where the vector was oob) and compare it to the ground-truth response.
 
 #.
-    Compute the classification error estimate as ratio of the number of misclassified oob vectors to all the vectors in the original data. In case of regression, the oob-error is computed as the squared error for oob vectors difference divided by the total number of vectors.
+    Compute the classification error estimate as a ratio of the number of misclassified oob vectors to all the vectors in the original data. In case of regression, the oob-error is computed as the squared error for oob vectors difference divided by the total number of vectors.
+
+
+For the random trees usage example, please, see letter_recog.cpp sample in OpenCV distribution.
 
 **References:**
 
 *
-    Machine Learning, Wald I, July 2002.
+    *Machine Learning*, Wald I, July 2002.
 
     http://stat-www.berkeley.edu/users/breiman/wald2002-1.pdf
 
 *
-    Looking Inside the Black Box, Wald II, July 2002.
+    *Looking Inside the Black Box*, Wald II, July 2002.
 
     http://stat-www.berkeley.edu/users/breiman/wald2002-2.pdf
 
 *
-    Software for the Masses, Wald III, July 2002.
+    *Software for the Masses*, Wald III, July 2002.
 
     http://stat-www.berkeley.edu/users/breiman/wald2002-3.pdf
 
@@ -47,136 +52,171 @@ In random trees there is no need for any accuracy estimation procedures, such as
     http://www.stat.berkeley.edu/users/breiman/RandomForests/cc_home.htm
     .
 
-.. index:: CvRTParams
-
-.. _CvRTParams:
-
 CvRTParams
 ----------
-.. c:type:: CvRTParams
-
-Training parameters of random trees ::
+.. ocv:class:: CvRTParams
 
-    struct CvRTParams : public CvDTreeParams
-    {
-        bool calc_var_importance;
-        int nactive_vars;
-        CvTermCriteria term_crit;
+    Training parameters of random trees.
 
-        CvRTParams() : CvDTreeParams( 5, 10, 0, false, 10, 0, false, false, 0 ),
-            calc_var_importance(false), nactive_vars(0)
-        {
-            term_crit = cvTermCriteria( CV_TERMCRIT_ITER+CV_TERMCRIT_EPS, 50, 0.1 );
-        }
+The set of training parameters for the forest is a superset of the training parameters for a single tree. However, random trees do not need all the functionality/features of decision trees. Most noticeably, the trees are not pruned, so the cross-validation parameters are not used.
 
-        CvRTParams( int _max_depth, int _min_sample_count,
-                    float _regression_accuracy, bool _use_surrogates,
-                    int _max_categories, const float* _priors,
-                    bool _calc_var_importance,
-                    int _nactive_vars, int max_tree_count,
-                    float forest_accuracy, int termcrit_type );
-    };
 
+CvRTParams::CvRTParams:
+-----------------------
+The constructors.
 
-The set of training parameters for the forest is a superset of the training parameters for a single tree. However, random trees do not need all the functionality/features of decision trees. Most noticeably, the trees are not pruned, so the cross-validation parameters are not used.
+.. ocv:function:: CvRTParams::CvRTParams()  
 
-.. index:: CvRTrees
+.. ocv:function:: CvRTParams::CvRTParams( int max_depth, int min_sample_count, float regression_accuracy, bool use_surrogates, int max_categories, const float* priors, bool calc_var_importance, int nactive_vars, int max_num_of_trees_in_the_forest, float forest_accuracy, int termcrit_type )
 
-.. _CvRTrees:
+    :param calc_var_importance: If true then variable importance will be calculated and then it can be retrieved by :ocv:func:`CvRTrees::get_var_importance`.
 
-CvRTrees
---------
-.. c:type:: CvRTrees
+    :param nactive_vars: The size of the randomly selected subset of features at each tree node and that are used to find the best split(s). If you set it to 0 then the size will be set to the square root of the total number of features.
 
-Random trees ::
+    :param max_num_of_trees_in_the_forest: The maximum number of trees in the forest (suprise, suprise).
 
-    class CvRTrees : public CvStatModel
-    {
-    public:
-        CvRTrees();
-        virtual ~CvRTrees();
-        virtual bool train( const Mat& _train_data, int _tflag,
-                            const Mat& _responses, const Mat& _var_idx=Mat(),
-                            const Mat& _sample_idx=Mat(), const Mat& _var_type=Mat(),
-                            const Mat& _missing_mask=Mat(),
-                            CvRTParams params=CvRTParams() );
-        virtual float predict( const Mat& sample, const Mat& missing = 0 )
-                                                                    const;
-        virtual void clear();
+    :param forest_accuracy: Sufficient accuracy (OOB error).
 
-        virtual const Mat& get_var_importance();
-        virtual float get_proximity( const Mat& sample_1, const Mat& sample_2 )
-                                                                            const;
+    :param termcrit_type: The type of the termination criteria:
+     
+        * **CV_TERMCRIT_ITER** Terminate learning by the ``max_num_of_trees_in_the_forest``;
+        
+        * **CV_TERMCRIT_EPS** Terminate learning by the ``forest_accuracy``;
 
-        virtual void read( CvFileStorage* fs, CvFileNode* node );
-        virtual void write( CvFileStorage* fs, const char* name );
+        * **CV_TERMCRIT_ITER | CV_TERMCRIT_EPS** Use both termination criterias.
 
-        Mat& get_active_var_mask();
-        CvRNG* get_rng();
+For meaning of other parameters see :ocv:func:`CvDTreeParams::CvDTreeParams`.
 
-        int get_tree_count() const;
-        CvForestTree* get_tree(int i) const;
+The default constructor sets all parameters to default values which are different from default values of :ocv:class:`CvDTreeParams`:
 
-    protected:
+::
 
-        bool grow_forest( const CvTermCriteria term_crit );
-
-        // array of the trees of the forest
-        CvForestTree** trees;
-        CvDTreeTrainData* data;
-        int ntrees;
-        int nclasses;
-        ...
-    };
+    CvRTParams::CvRTParams() : CvDTreeParams( 5, 10, 0, false, 10, 0, false, false, 0 ),
+        calc_var_importance(false), nactive_vars(0)
+    {
+        term_crit = cvTermCriteria( CV_TERMCRIT_ITER+CV_TERMCRIT_EPS, 50, 0.1 );
+    }
 
 
-.. index:: CvRTrees::train
+CvRTrees
+--------
+.. ocv:class:: CvRTrees
 
-.. _CvRTrees::train:
+    The class implements the random forest predictor as described in the beginning of this section.
 
 CvRTrees::train
 ---------------
-.. ocv:function:: bool CvRTrees::train(  const Mat& train_data,  int tflag,                      const Mat& responses,  const Mat& comp_idx=Mat(),                      const Mat& sample_idx=Mat(),  const Mat& var_type=Mat(),                      const Mat& missing_mask=Mat(),                      CvRTParams params=CvRTParams() )
+Trains the Random Trees model.
 
-    Trains the Random Tree model.
+.. ocv:function:: bool CvRTrees::train( const Mat& trainData, int tflag, const Mat& responses, const Mat& varIdx=Mat(), const Mat& sampleIdx=Mat(), const Mat& varType=Mat(), const Mat& missingDataMask=Mat(), CvRTParams params=CvRTParams() )
 
-The method ``CvRTrees::train`` is very similar to the first form of ``CvDTree::train`` () and follows the generic method ``CvStatModel::train`` conventions. All the parameters specific to the algorithm training are passed as a
-:ref:`CvRTParams` instance. The estimate of the training error ( ``oob-error`` ) is stored in the protected class member ``oob_error`` .
+.. ocv:function::bool CvRTrees::train( const CvMat* trainData, int tflag, const CvMat* responses, const CvMat* varIdx=0, const CvMat* sampleIdx=0, const CvMat* varType=0, const CvMat* missingDataMask=0, CvRTParams params=CvRTParams() )
 
-.. index:: CvRTrees::predict
+.. ocv:function::bool CvRTrees::train( CvMLData* data, CvRTParams params=CvRTParams() )
 
-.. _CvRTrees::predict:
+.. ocv:pyfunction:: cv2.RTrees.train(trainData, tflag, responses[, varIdx[, sampleIdx[, varType[, missingDataMask[, params]]]]]) -> retval
+
+The method :ocv:func:`CvRTrees::train` is very similar to the method :ocv:func:`CvDTree::train` and follows the generic method :ocv:func:`CvStatModel::train` conventions. All the parameters specific to the algorithm training are passed as a :ocv:class:`CvRTParams` instance. The estimate of the training error (``oob-error``) is stored in the protected class member ``oob_error``.
 
 CvRTrees::predict
 -----------------
+Predicts the output for an input sample.
+
 .. ocv:function:: double CvRTrees::predict(  const Mat& sample,  const Mat& missing=Mat() ) const
 
-    Predicts the output for an input sample.
+.. ocv:function::float CvRTrees::predict( const CvMat* sample, const CvMat* missing = 0 ) const
+
+.. ocv:pyfunction:: cv2.RTrees.predict(sample[, missing]) -> retval
+
+    :param sample: Sample for classification.
+
+    :param missing: Optional missing measurement mask of the sample.
+
+The input parameters of the prediction method are the same as in :ocv:func:`CvDTree::predict`  but the return value type is different. This method returns the cumulative result from all the trees in the forest (the class that receives the majority of voices, or the mean of the regression function estimates).
+
+
+CvRTrees::predict_prob
+----------------------
+Returns a fuzzy-predicted class label.
+
+.. ocv:function:: float CvRTrees::predict_prob( const cv::Mat& sample, const cv::Mat& missing = cv::Mat() ) const
 
-The input parameters of the prediction method are the same as in ``CvDTree::predict``  but the return value type is different. This method returns the cumulative result from all the trees in the forest (the class that receives the majority of voices, or the mean of the regression function estimates).
+.. ocv:function::float CvRTrees::predict_prob( const CvMat* sample, const CvMat* missing = 0 ) const
 
-.. index:: CvRTrees::get_var_importance
+.. ocv:pyfunction:: cv2.RTrees.predict_prob(sample[, missing]) -> retval
 
-.. _CvRTrees::get_var_importance:
+    :param sample: Sample for classification.
 
-CvRTrees::get_var_importance
+    :param missing: Optional missing measurement mask of the sample.
+
+The function works for binary classification problems only. It returns the number between 0 and 1. This number represents probability or confidence of the sample belonging to the second class. It is calculated as the proportion of decision trees that classified the sample to the second class.
+
+
+CvRTrees::getVarImportance
 ----------------------------
-.. ocv:function:: const Mat& CvRTrees::get_var_importance() const
+Returns the variable importance array.
+
+.. ocv:function:: Mat CvRTrees::getVarImportance()
 
-    Retrieves the variable importance array.
+.. ocv:function::const CvMat* CvRTrees::get_var_importance()
 
-The method returns the variable importance vector, computed at the training stage when ``:ref:`CvRTParams`::calc_var_importance`` is set. If the training flag is not set, the ``NULL`` pointer is returned. This differs from the decision trees where variable importance can be computed anytime after the training.
+.. ocv:pyfunction:: cv2.RTrees.getVarImportance() -> importanceVector
 
-.. index:: CvRTrees::get_proximity
+The method returns the variable importance vector, computed at the training stage when ``CvRTParams::calc_var_importance`` is set to true. If this flag was set to false, the ``NULL`` pointer is returned. This differs from the decision trees where variable importance can be computed anytime after the training.
 
-.. _CvRTrees::get_proximity:
 
 CvRTrees::get_proximity
 -----------------------
-.. ocv:function:: float CvRTrees::get_proximity(  const Mat& sample_1,  const Mat& sample_2 ) const
+Retrieves the proximity measure between two training samples.
 
-    Retrieves the proximity measure between two training samples.
+.. ocv:function::float CvRTrees::get_proximity( const CvMat* sample1, const CvMat* sample2, const CvMat* missing1 = 0, const CvMat* missing2 = 0 ) const
 
-The method returns proximity measure between any two samples, which is the ratio of those trees in the ensemble, in which the samples fall into the same leaf node, to the total number of the trees.
+    :param sample_1: The first sample.
 
-For the random trees usage example, please, see letter_recog.cpp sample in OpenCV distribution.
+    :param sample_2: The second sample.
+
+    :param missing1: Optional missing measurement mask of the first sample.
+
+    :param missing2:  Optional missing measurement mask of the second sample.
+
+The method returns proximity measure between any two samples. This is a ratio of those trees in the ensemble, in which the samples fall into the same leaf node, to the total number of the trees.
+
+CvRTrees::calc_error
+--------------------
+Returns error of the random forest.
+
+.. ocv:function::float CvRTrees::calc_error( CvMLData* data, int type, std::vector<float> *resp = 0 )
+
+The method is identical to :ocv:func:`CvDTree::calc_error` but uses the random forest as predictor.
+
+
+CvRTrees::get_train_error
+-------------------------
+Returns the train error.
+
+.. ocv:function:: float CvRTrees::get_train_error()
+
+The method works for classification problems only. It returns the proportion of incorrectly classified train samples.
+
+
+CvRTrees::get_rng
+-----------------
+Returns the state of the used random number generator.
+
+.. ocv:function::CvRNG* CvRTrees::get_rng()
+
+
+CvRTrees::get_tree_count
+------------------------
+Returns the number of trees in the constructed random forest.
+
+.. ocv:function:: int CvRTrees::get_tree_count() const
+
+
+CvRTrees::get_tree
+------------------
+Returns the specific decision tree in the constructed random forest.
+
+.. ocv:function:: CvForestTree* CvRTrees::get_tree(int i) const
+
+    :param i: Index of the decision tree.
index 21fac34..8e2bb01 100644 (file)
@@ -7,9 +7,9 @@ Statistical Models
 
 CvStatModel
 -----------
-.. c:type:: CvStatModel
+.. ocv:class:: CvStatModel
 
-Base class for statistical models in ML ::
+Base class for statistical models in ML. ::
 
     class CvStatModel
     {
@@ -40,39 +40,27 @@ Base class for statistical models in ML ::
 
 In this declaration, some methods are commented off. These are methods for which there is no unified API (with the exception of the default constructor). However, there are many similarities in the syntax and semantics that are briefly described below in this section, as if they are part of the base class.
 
-.. index:: CvStatModel::CvStatModel
-
-.. _CvStatModel::CvStatModel:
-
 CvStatModel::CvStatModel
 ------------------------
-.. ocv:function:: CvStatModel::CvStatModel()
-
-    Serves as a default constructor.
+The default constuctor.
 
-Each statistical model class in ML has a default constructor without parameters. This constructor is useful for a 2-stage model construction, when the default constructor is followed by ``train()`` or ``load()`` .
-
-.. index:: CvStatModel::CvStatModel(...)
+.. ocv:function:: CvStatModel::CvStatModel()
 
-.. _CvStatModel::CvStatModel(...):
+Each statistical model class in ML has a default constructor without parameters. This constructor is useful for a two-stage model construction, when the default constructor is followed by :ocv:func:`CvStatModel::train` or :ocv:func:`CvStatModel::load`.
 
 CvStatModel::CvStatModel(...)
 -----------------------------
-.. ocv:function:: CvStatModel::CvStatModel( const Mat& train_data ... )
-
-    Serves as a training constructor.
+The training constructor.
 
-Most ML classes provide a single-step constructor and train constructors. This constructor is equivalent to the default constructor, followed by the ``train()`` method with the parameters that are passed to the constructor.
-
-.. index:: CvStatModel::~CvStatModel
+.. ocv:function:: CvStatModel::CvStatModel( const Mat& train_data ... )
 
-.. _CvStatModel::~CvStatModel:
+Most ML classes provide a single-step constructor and train constructors. This constructor is equivalent to the default constructor, followed by the :ocv:func:`CvStatModel::train` method with the parameters that are passed to the constructor.
 
 CvStatModel::~CvStatModel
 -------------------------
-.. ocv:function:: CvStatModel::~CvStatModel()
+The virtual destructor.
 
-    Serves as a virtual destructor.
+.. ocv:function:: CvStatModel::~CvStatModel()
 
 The destructor of the base class is declared as virtual. So, it is safe to write the following code: ::
 
@@ -85,81 +73,62 @@ The destructor of the base class is declared as virtual. So, it is safe to write
     delete model;
 
 
-Normally, the destructor of each derived class does nothing. But in this instance, it calls the overridden method ``clear()`` that deallocates all the memory.
-
-.. index:: CvStatModel::clear
-
-.. _CvStatModel::clear:
+Normally, the destructor of each derived class does nothing. But in this instance, it calls the overridden method :ocv:func:`CvStatModel::clear` that deallocates all the memory.
 
 CvStatModel::clear
 ------------------
-.. ocv:function:: void CvStatModel::clear()
-
-    Deallocates memory and resets the model state.
+Deallocates memory and resets the model state.
 
-The method ``clear`` does the same job as the destructor: it deallocates all the memory occupied by the class members. But the object itself is not destructed and can be reused further. This method is called from the destructor, from the ``train`` methods of the derived classes, from the methods ``load()``,``read()`` , or even explicitly by the user.
-
-.. index:: CvStatModel::save
+.. ocv:function:: void CvStatModel::clear()
 
-.. _CvStatModel::save:
+The method ``clear`` does the same job as the destructor: it deallocates all the memory occupied by the class members. But the object itself is not destructed and can be reused further. This method is called from the destructor, from the :ocv:func:`CvStatModel::train` methods of the derived classes, from the methods :ocv:func:`CvStatModel::load`, :ocv:func:`CvStatModel::read()`, or even explicitly by the user.
 
 CvStatModel::save
 -----------------
+Saves the model to a file.
+
 .. ocv:function:: void CvStatModel::save( const char* filename, const char* name=0 )
 
-    Saves the model to a file.
+.. ocv:pyfunction:: cv2.StatModel.save(filename[, name]) -> None
 
 The method ``save`` saves the complete model state to the specified XML or YAML file with the specified name or default name (which depends on a particular class). *Data persistence* functionality from ``CxCore`` is used.
 
-.. index:: CvStatModel::load
-
-.. _CvStatModel::load:
-
 CvStatModel::load
 -----------------
-.. ocv:function:: void CvStatModel::load( const char* filename, const char* name=0 )
+Loads the model from a file.
 
-    Loads the model from a file.
-
-The method ``load`` loads the complete model state with the specified name (or default model-dependent name) from the specified XML or YAML file. The previous model state is cleared by ``clear()`` .
+.. ocv:function:: void CvStatModel::load( const char* filename, const char* name=0 )
 
+.. ocv:pyfunction:: cv2.StatModel.load(filename[, name]) -> None
 
-.. index:: CvStatModel::write
+The method ``load`` loads the complete model state with the specified name (or default model-dependent name) from the specified XML or YAML file. The previous model state is cleared by :ocv:func:`CvStatModel::clear`.
 
-.. _CvStatModel::write:
 
 CvStatModel::write
 ------------------
-.. ocv:function:: void CvStatModel::write( CvFileStorage* storage, const char* name )
-
-    Writes the model to the file storage.
+Writes the model to the file storage.
 
-The method ``write`` stores the complete model state in the file storage with the specified name or default name (which depends on the particular class). The method is called by ``save()`` .
+.. ocv:function:: void CvStatModel::write( CvFileStorage* storage, const char* name )
 
-.. index:: CvStatModel::read
+The method ``write`` stores the complete model state in the file storage with the specified name or default name (which depends on the particular class). The method is called by :ocv:func:`CvStatModel::save`.
 
-.. _CvStatModel::read:
 
 CvStatModel::read
 -----------------
-.. ocv:function:: void CvStatMode::read( CvFileStorage* storage, CvFileNode* node )
+Reads the model from the file storage.
 
-    Reads the model from the file storage.
+.. ocv:function:: void CvStatModel::read( CvFileStorage* storage, CvFileNode* node )
 
 The method ``read`` restores the complete model state from the specified node of the file storage. Use the function
-:ref:`GetFileNodeByName` to locate the node.
-
-The previous model state is cleared by ``clear()`` .
+:ocv:func:`GetFileNodeByName` to locate the node.
 
-.. index:: CvStatModel::train
-
-.. _CvStatModel::train:
+The previous model state is cleared by :ocv:func:`CvStatModel::clear`.
 
 CvStatModel::train
 ------------------
-.. ocv:function:: bool CvStatMode::train( const Mat& train_data, [int tflag,] ..., const Mat& responses, ...,     [const Mat& var_idx,] ..., [const Mat& sample_idx,] ...     [const Mat& var_type,] ..., [const Mat& missing_mask,] <misc_training_alg_params> ... )
+Trains the model.
 
-    Trains the model.
+.. ocv:function:: bool CvStatModel::train( const Mat& train_data, [int tflag,] ..., const Mat& responses, ...,     [const Mat& var_idx,] ..., [const Mat& sample_idx,] ...     [const Mat& var_type,] ..., [const Mat& missing_mask,] <misc_training_alg_params> ... )
 
 The method trains the statistical model using a set of input feature vectors and the corresponding output values (responses). Both input and output vectors/values are passed as matrices. By default, the input feature vectors are stored as ``train_data`` rows, that is, all the components (features) of a training vector are stored continuously. However, some algorithms can handle the transposed representation when all values of each particular feature (component/input variable) over the whole input set are stored continuously. If both layouts are supported, the method includes the ``tflag`` parameter that specifies the orientation as follows:
 
@@ -167,7 +136,7 @@ The method trains the statistical model using a set of input feature vectors and
 
 * ``tflag=CV_COL_SAMPLE``     The feature vectors are stored as columns.
 
-The ``train_data`` must have the ``CV_32FC1`` (32-bit floating-point, single-channel) format. Responses are usually stored in the 1D vector (a row or a column) of ``CV_32SC1`` (only in the classification problem) or ``CV_32FC1`` format, one value per input vector. Although, some algorithms, like various flavors of neural nets, take vector responses.
+The ``train_data`` must have the ``CV_32FC1`` (32-bit floating-point, single-channel) format. Responses are usually stored in a 1D vector (a row or a column) of ``CV_32SC1`` (only in the classification problem) or ``CV_32FC1`` format, one value per input vector. Although, some algorithms, like various flavors of neural nets, take vector responses.
 
 For classification problems, the responses are discrete class labels. For regression problems, the responses are values of the function to be approximated. Some algorithms can deal only with classification problems, some - only with regression problems, and some can deal with both problems. In the latter case, the type of output variable is either passed as a separate parameter or as the last element of the ``var_type`` vector:
 
@@ -175,25 +144,21 @@ For classification problems, the responses are discrete class labels. For regres
 
 * ``CV_VAR_ORDERED(=CV_VAR_NUMERICAL)``     The output values are ordered. This means that two different values can be compared as numbers, and this is a regression problem.
 
-Types of input variables can be also specified using ``var_type`` . Most algorithms can handle only ordered input variables.
-
-Many models in the ML may be trained on a selected feature subset, and/or on a selected sample subset of the training set. To make it easier for you, the method ``train`` usually includes the ``var_idx`` and ``sample_idx`` parameters. The former parameter identifies variables (features) of interest, and the latter one identifies samples of interest. Both vectors are either integer ( ``CV_32SC1`` ) vectors (lists of 0-based indices) or 8-bit ( ``CV_8UC1`` ) masks of active variables/samples. You may pass ``NULL`` pointers instead of either of the arguments, meaning that all of the variables/samples are used for training.
-
-Additionally, some algorithms can handle missing measurements, that is, when certain features of certain training samples have unknown values (for example, they forgot to measure a temperature of patient A on Monday). The parameter ``missing_mask`` , an 8-bit matrix of the same size as ``train_data`` , is used to mark the missed values (non-zero elements of the mask).
+Types of input variables can be also specified using ``var_type``. Most algorithms can handle only ordered input variables.
 
-Usually, the previous model state is cleared by ``clear()`` before running the training procedure. However, some algorithms may optionally update the model state with the new training data, instead of resetting it.
+Many ML models may be trained on a selected feature subset, and/or on a selected sample subset of the training set. To make it easier for you, the method ``train`` usually includes the ``var_idx`` and ``sample_idx`` parameters. The former parameter identifies variables (features) of interest, and the latter one identifies samples of interest. Both vectors are either integer (``CV_32SC1``) vectors (lists of 0-based indices) or 8-bit (``CV_8UC1``) masks of active variables/samples. You may pass ``NULL`` pointers instead of either of the arguments, meaning that all of the variables/samples are used for training.
 
-.. index:: CvStatModel::predict
+Additionally, some algorithms can handle missing measurements, that is, when certain features of certain training samples have unknown values (for example, they forgot to measure a temperature of patient A on Monday). The parameter ``missing_mask``, an 8-bit matrix of the same size as ``train_data``, is used to mark the missed values (non-zero elements of the mask).
 
-.. _CvStatModel::predict:
+Usually, the previous model state is cleared by :ocv:func:`CvStatModel::clear` before running the training procedure. However, some algorithms may optionally update the model state with the new training data, instead of resetting it.
 
 CvStatModel::predict
 --------------------
-.. ocv:function:: float CvStatMode::predict( const Mat& sample[, <prediction_params>] ) const
+Predicts the response for a sample.
 
-    Predicts the response for a sample.
+.. ocv:function:: float CvStatModel::predict( const Mat& sample[, <prediction_params>] ) const
 
-The method is used to predict the response for a new sample. In case of a classification, the method returns the class label. In case of a regression, the method returns the output function value. The input sample must have as many components as the ``train_data`` passed to ``train`` contains. If the ``var_idx`` parameter is passed to ``train`` , it is remembered and then is used to extract only the necessary components from the input sample in the method ``predict`` .
+The method is used to predict the response for a new sample. In case of a classification, the method returns the class label. In case of a regression, the method returns the output function value. The input sample must have as many components as the ``train_data`` passed to ``train`` contains. If the ``var_idx`` parameter is passed to ``train``, it is remembered and then is used to extract only the necessary components from the input sample in the method ``predict``.
 
 The suffix ``const`` means that prediction does not affect the internal model state, so the method can be safely called from within different threads.
 
index 431ed25..e0a5414 100644 (file)
@@ -3,197 +3,250 @@ Support Vector Machines
 
 .. highlight:: cpp
 
-Originally, support vector machines (SVM) was a technique for building an optimal binary (2-class) classifier. Later the technique has been extended to regression and clustering problems. SVM is a partial case of kernel-based methods. It maps feature vectors into a higher-dimensional space using a kernel function and builds an optimal linear discriminating function in this space or an optimal hyper-plane that fits into the training data. In case of SVM, the kernel is not defined explicitly. Instead, a distance between any 2 points in the hyper-space needs to be defined.
+Originally, support vector machines (SVM) was a technique for building an optimal binary (2-class) classifier. Later the technique was extended to regression and clustering problems. SVM is a partial case of kernel-based methods. It maps feature vectors into a higher-dimensional space using a kernel function and builds an optimal linear discriminating function in this space or an optimal hyper-plane that fits into the training data. In case of SVM, the kernel is not defined explicitly. Instead, a distance between any 2 points in the hyper-space needs to be defined.
 
-The solution is optimal, which means that the margin between the separating hyper-plane and the nearest feature vectors from both classes (in case of 2-class classifier) is maximal. The feature vectors that are the closest to the hyper-plane are called "support vectors", which means that the position of other vectors does not affect the hyper-plane (the decision function).
+The solution is optimal, which means that the margin between the separating hyper-plane and the nearest feature vectors from both classes (in case of 2-class classifier) is maximal. The feature vectors that are the closest to the hyper-plane are called *support vectors*, which means that the position of other vectors does not affect the hyper-plane (the decision function).
 
-There are a lot of good references on SVM. You may consider starting with the following:
+SVM implementation in OpenCV is based on [LibSVM]_.
 
-*
-    [Burges98] C. Burges. *A tutorial on support vector machines for pattern recognition*, Knowledge Discovery and Data Mining 2(2), 1998.
-    (available online at
-    http://citeseer.ist.psu.edu/burges98tutorial.html
-    ).
+.. [Burges98] C. Burges. *A tutorial on support vector machines for pattern recognition*, Knowledge Discovery and Data Mining 2(2), 1998 (available online at http://citeseer.ist.psu.edu/burges98tutorial.html)
 
-*
-    Chih-Chung Chang and Chih-Jen Lin. *LIBSVM - A Library for Support Vector Machines* 
-    (
-    http://www.csie.ntu.edu.tw/~cjlin/libsvm/
-    )
+.. [LibSVM] C.-C. Chang and C.-J. Lin. *LIBSVM: a library for support vector machines*, ACM Transactions on Intelligent Systems and Technology, 2:27:1--27:27, 2011. (http://www.csie.ntu.edu.tw/~cjlin/papers/libsvm.pdf)
 
-.. index:: CvSVM
 
-.. _CvSVM:
+CvParamGrid
+-----------
+.. ocv:class:: CvParamGrid
 
-CvSVM
------
-.. c:type:: CvSVM
+The structure represents the logarithmic grid range of statmodel parameters. It is used for optimizing statmodel accuracy by varying model parameters, the accuracy estimate being computed by cross-validation. 
 
-Support Vector Machines ::
+.. ocv:member:: double CvParamGrid::min_val
 
-    class CvSVM : public CvStatModel
-    {
-    public:
-        // SVM type
-        enum { C_SVC=100, NU_SVC=101, ONE_CLASS=102, EPS_SVR=103, NU_SVR=104 };
+    Minimum value of the statmodel parameter.
+
+.. ocv:member:: double CvParamGrid::max_val
 
-        // SVM kernel type
-        enum { LINEAR=0, POLY=1, RBF=2, SIGMOID=3 };
+    Maximum value of the statmodel parameter.
 
-        // SVM params type
-        enum { C=0, GAMMA=1, P=2, NU=3, COEF=4, DEGREE=5 };
+.. ocv:member:: double CvParamGrid::step
 
-        CvSVM();
-        virtual ~CvSVM();
+    Logarithmic step for iterating the statmodel parameter.
 
-        CvSVM( const Mat& _train_data, const Mat& _responses,
-               const Mat& _var_idx=Mat(), const Mat& _sample_idx=Mat(),
-               CvSVMParams _params=CvSVMParams() );
+The grid determines the following iteration sequence of the statmodel parameter values:
 
-        virtual bool train( const Mat& _train_data, const Mat& _responses,
-                            const Mat& _var_idx=Mat(), const Mat& _sample_idx=Mat(),
-                            CvSVMParams _params=CvSVMParams() );
+.. math::
+
+    (min\_val, min\_val*step, min\_val*{step}^2, \dots,  min\_val*{step}^n),
 
-        virtual bool train_auto( const Mat& _train_data, const Mat& _responses,
-            const Mat& _var_idx, const Mat& _sample_idx, CvSVMParams _params,
-            int k_fold = 10,
-            CvParamGrid C_grid      = get_default_grid(CvSVM::C),
-            CvParamGrid gamma_grid  = get_default_grid(CvSVM::GAMMA),
-            CvParamGrid p_grid      = get_default_grid(CvSVM::P),
-            CvParamGrid nu_grid     = get_default_grid(CvSVM::NU),
-            CvParamGrid coef_grid   = get_default_grid(CvSVM::COEF),
-            CvParamGrid degree_grid = get_default_grid(CvSVM::DEGREE) );
+where :math:`n` is the maximal index satisfying
 
-        virtual float predict( const Mat& _sample ) const;
-        virtual int get_support_vector_count() const;
-        virtual const float* get_support_vector(int i) const;
-        virtual CvSVMParams get_params() const { return params; };
-        virtual void clear();
+.. math::
 
-        static CvParamGrid get_default_grid( int param_id );
+    \texttt{min\_val} * \texttt{step} ^n <  \texttt{max\_val}
 
-        virtual void save( const char* filename, const char* name=0 );
-        virtual void load( const char* filename, const char* name=0 );
+The grid is logarithmic, so ``step`` must always be greater then 1.
 
-        virtual void write( CvFileStorage* storage, const char* name );
-        virtual void read( CvFileStorage* storage, CvFileNode* node );
-        int get_var_count() const { return var_idx ? var_idx->cols : var_all; }
+CvParamGrid::CvParamGrid
+------------------------
+The constructors.
 
-    protected:
-        ...
-    };
+.. ocv:function:: CvParamGrid::CvParamGrid()
 
+.. ocv:function:: CvParamGrid::CvParamGrid( double min_val, double max_val, double log_step )
 
-.. index:: CvSVMParams
+The full constructor initializes corresponding members. The default constructor creates a dummy grid:
 
-.. _CvSVMParams:
+::
+
+    CvParamGrid::CvParamGrid()
+    {
+        min_val = max_val = step = 0;
+    }
+
+CvParamGrid::check
+------------------
+Checks validness of the grid.
+
+.. ocv:function:: bool CvParamGrid::check()
+
+Returns ``true`` if the grid is valid and ``false`` otherwise. The grid is valid if and only if:
+
+* Lower bound of the grid is less then the upper one.
+* Lower bound of the grid is positive.
+* Grid step is greater then 1.
 
 CvSVMParams
 -----------
-.. c:type:: CvSVMParams
+.. ocv:class:: CvSVMParams
+
+SVM training parameters.
+
+The structure must be initialized and passed to the training method of :ocv:class:`CvSVM`.
+
+CvSVMParams::CvSVMParams
+------------------------
+The constructors.
+
+.. ocv:function:: CvSVMParams::CvSVMParams()
+
+.. ocv:function:: CvSVMParams::CvSVMParams( int svm_type, int kernel_type, double degree, double gamma, double coef0, double Cvalue, double nu, double p, CvMat* class_weights, CvTermCriteria term_crit )
+
+    :param svm_type: Type of a SVM formulation. Possible values are:
+
+        * **CvSVM::C_SVC** C-Support Vector Classification. ``n``-class classification (``n`` :math:`\geq` 2), allows imperfect separation of classes with penalty multiplier ``C`` for outliers.
+
+        * **CvSVM::NU_SVC** :math:`\nu`-Support Vector Classification. ``n``-class classification with possible imperfect separation. Parameter :math:`\nu`  (in the range 0..1, the larger the value, the smoother the decision boundary) is used instead of ``C``.
+
+        * **CvSVM::ONE_CLASS** Distribution Estimation (One-class SVM). All the training data are from the same class, SVM builds a boundary that separates the class from the rest of the feature space.
+
+        * **CvSVM::EPS_SVR** :math:`\epsilon`-Support Vector Regression. The distance between feature vectors from the training set and the fitting hyper-plane must be less than ``p``. For outliers the penalty multiplier ``C`` is used.
+
+        * **CvSVM::NU_SVR** :math:`\nu`-Support Vector Regression. :math:`\nu` is used instead of ``p``.
+
+        See [LibSVM]_ for details.
+
+    :param kernel_type: Type of a SVM kernel. Possible values are:
+
+        * **CvSVM::LINEAR** Linear kernel. No mapping is done, linear discrimination (or regression) is done in the original feature space. It is the fastest option. :math:`K(x_i, x_j) = x_i^T x_j`.
+
+        * **CvSVM::POLY** Polynomial kernel: :math:`K(x_i, x_j) = (\gamma x_i^T x_j + coef0)^{degree}, \gamma > 0`.
+
+        * **CvSVM::RBF** Radial basis function (RBF), a good choice in most cases. :math:`K(x_i, x_j) = e^{-\gamma ||x_i - x_j||^2}, \gamma > 0`.
+
+        * **CvSVM::SIGMOID** Sigmoid kernel: :math:`K(x_i, x_j) = \tanh(\gamma x_i^T x_j + coef0)`.
+    :param degree: Parameter ``degree`` of a kernel function (POLY).
+
+    :param gamma: Parameter :math:`\gamma` of a kernel function (POLY / RBF / SIGMOID).
+
+    :param coef0: Parameter ``coef0`` of a kernel function (POLY / SIGMOID).
+
+    :param Cvalue: Parameter ``C`` of a SVM optimiazation problem (C_SVC / EPS_SVR / NU_SVR).
+
+    :param nu: Parameter :math:`\nu` of a SVM optimization problem (NU_SVC / ONE_CLASS / NU_SVR).
+
+    :param p: Parameter :math:`\epsilon` of a SVM optimization problem (EPS_SVR).
+
+    :param class_weights: Optional weights in the C_SVC problem , assigned to particular classes. They are multiplied by ``C`` so the parameter ``C`` of class ``#i`` becomes :math:`class\_weights_i * C`. Thus these weights affect the misclassification penalty for different classes. The larger weight, the larger penalty on misclassification of data from the corresponding class.
+
+    :param term_crit: Termination criteria of the iterative SVM training procedure which solves a partial case of constrained quadratic optimization problem. You can specify tolerance and/or the maximum number of iterations.
 
-SVM training parameters ::
+The default constructor initialize the structure with following values:
 
-    struct CvSVMParams
+::
+
+    CvSVMParams::CvSVMParams() :
+        svm_type(CvSVM::C_SVC), kernel_type(CvSVM::RBF), degree(0),
+        gamma(1), coef0(0), C(1), nu(0), p(0), class_weights(0)
     {
-        CvSVMParams();
-        CvSVMParams( int _svm_type, int _kernel_type,
-                     double _degree, double _gamma, double _coef0,
-                     double _C, double _nu, double _p,
-                     const CvMat* _class_weights, CvTermCriteria _term_crit );
+        term_crit = cvTermCriteria( CV_TERMCRIT_ITER+CV_TERMCRIT_EPS, 1000, FLT_EPSILON );
+    }
+
+
+
+CvSVM
+-----
+.. ocv:class:: CvSVM
+
+Support Vector Machines.
 
-        int         svm_type;
-        int         kernel_type;
-        double      degree; // for poly
-        double      gamma;  // for poly/rbf/sigmoid
-        double      coef0;  // for poly/sigmoid
+CvSVM::CvSVM
+------------
+Default and training constructors.
 
-        double      C;  // for CV_SVM_C_SVC, CV_SVM_EPS_SVR and CV_SVM_NU_SVR
-        double      nu; // for CV_SVM_NU_SVC, CV_SVM_ONE_CLASS, and CV_SVM_NU_SVR
-        double      p; // for CV_SVM_EPS_SVR
-        CvMat*      class_weights; // for CV_SVM_C_SVC
-        CvTermCriteria term_crit; // termination criteria
-    };
+.. ocv:function:: CvSVM::CvSVM()
 
+.. ocv:function:: CvSVM::CvSVM( const Mat& trainData, const Mat& responses, const Mat& varIdx=Mat(), const Mat& sampleIdx=Mat(), CvSVMParams params=CvSVMParams() )
 
-The structure must be initialized and passed to the training method of
-:ref:`CvSVM` .
+.. ocv:function::CvSVM::CvSVM( const CvMat* trainData, const CvMat* responses, const CvMat* varIdx=0, const CvMat* sampleIdx=0, CvSVMParams params=CvSVMParams() )
 
-.. index:: CvSVM::train
+.. ocv:pyfunction:: cv2.SVM(trainData, responses[, varIdx[, sampleIdx[, params]]]) -> <SVM object>
 
-.. _CvSVM::train:
+The constructors follow conventions of :ocv:func:`CvStatModel::CvStatModel`. See :ocv:func:`CvStatModel::train` for parameters descriptions.
 
 CvSVM::train
 ------------
-.. ocv:function:: bool CvSVM::train(  const Mat& _train_data,  const Mat& _responses,                     const Mat& _var_idx=Mat(),  const Mat& _sample_idx=Mat(),                     CvSVMParams _params=CvSVMParams() )
+Trains an SVM.
+
+.. ocv:function:: bool CvSVM::train( const Mat& trainData, const Mat& responses, const Mat& varIdx=Mat(), const Mat& sampleIdx=Mat(), CvSVMParams params=CvSVMParams() )
+
+.. ocv:function::bool CvSVM::train( const CvMat* trainData, const CvMat* responses, const CvMat* varIdx=0, const CvMat* sampleIdx=0, CvSVMParams params=CvSVMParams() )
 
-    Trains SVM.
+.. ocv:pyfunction:: cv2.SVM.train(trainData, responses[, varIdx[, sampleIdx[, params]]]) -> retval
 
-The method trains the SVM model. It follows the conventions of the generic ``train`` "method" with the following limitations: 
+The method trains the SVM model. It follows the conventions of the generic :ocv:func:`CvStatModel::train` approach with the following limitations: 
 
 * Only the ``CV_ROW_SAMPLE`` data layout is supported.
+
 * Input variables are all ordered.
-* Output variables can be either categorical ( ``_params.svm_type=CvSVM::C_SVC`` or ``_params.svm_type=CvSVM::NU_SVC`` ), or ordered ( ``_params.svm_type=CvSVM::EPS_SVR`` or ``_params.svm_type=CvSVM::NU_SVR`` ), or not required at all ( ``_params.svm_type=CvSVM::ONE_CLASS`` ).
+
+* Output variables can be either categorical (``params.svm_type=CvSVM::C_SVC`` or ``params.svm_type=CvSVM::NU_SVC``), or ordered (``params.svm_type=CvSVM::EPS_SVR`` or ``params.svm_type=CvSVM::NU_SVR``), or not required at all (``params.svm_type=CvSVM::ONE_CLASS``).
+
 * Missing measurements are not supported.
 
 All the other parameters are gathered in the
-:ref:`CvSVMParams` structure.
+:ocv:class:`CvSVMParams` structure.
 
-.. index:: CvSVM::train_auto
-
-.. _CvSVM::train_auto:
 
 CvSVM::train_auto
 -----------------
-.. ocv:function:: train_auto(  const Mat& _train_data,  const Mat& _responses,          const Mat& _var_idx,  const Mat& _sample_idx,          CvSVMParams params,  int k_fold = 10,          CvParamGrid C_grid      = get_default_grid(CvSVM::C),          CvParamGrid gamma_grid  = get_default_grid(CvSVM::GAMMA),          CvParamGrid p_grid      = get_default_grid(CvSVM::P),          CvParamGrid nu_grid     = get_default_grid(CvSVM::NU),          CvParamGrid coef_grid   = get_default_grid(CvSVM::COEF),          CvParamGrid degree_grid = get_default_grid(CvSVM::DEGREE) )
+Trains an SVM with optimal parameters.
 
-    Trains SVM with optimal parameters.
+.. ocv:function:: bool CvSVM::train_auto( const Mat& trainData, const Mat& responses, const Mat& varIdx, const Mat& sampleIdx, CvSVMParams params, int k_fold = 10, CvParamGrid Cgrid = CvSVM::get_default_grid(CvSVM::C), CvParamGrid gammaGrid = CvSVM::get_default_grid(CvSVM::GAMMA), CvParamGrid pGrid = CvSVM::get_default_grid(CvSVM::P), CvParamGrid nuGrid  = CvSVM::get_default_grid(CvSVM::NU), CvParamGrid coeffGrid = CvSVM::get_default_grid(CvSVM::COEF), CvParamGrid degreeGrid = CvSVM::get_default_grid(CvSVM::DEGREE), bool balanced=false)
 
-    :param k_fold: Cross-validation parameter. The training set is divided into  ``k_fold``  subsets. One subset is used to train the model, the others form the test set. So, the SVM algorithm is executed  ``k_fold``  times.
+.. ocv:function::bool CvSVM::train_auto( const CvMat* trainData, const CvMat* responses, const CvMat* varIdx, const CvMat* sampleIdx, CvSVMParams params, int kfold = 10, CvParamGrid Cgrid = get_default_grid(CvSVM::C), CvParamGrid gammaGrid = get_default_grid(CvSVM::GAMMA), CvParamGrid pGrid = get_default_grid(CvSVM::P), CvParamGrid nuGrid = get_default_grid(CvSVM::NU), CvParamGrid coeffGrid = get_default_grid(CvSVM::COEF), CvParamGrid degreeGrid = get_default_grid(CvSVM::DEGREE), bool balanced=false )
 
-The method trains the SVM model automatically by choosing the optimal
-parameters ``C`` , ``gamma`` , ``p`` , ``nu`` , ``coef0`` , ``degree`` from
-:ref:`CvSVMParams`. Parameters are considered optimal
-when the cross-validation estimate of the test set error
-is minimal. The parameters are iterated by a logarithmic grid, for
-example, the parameter ``gamma`` takes the values in the set
-(
-:math:`min`,
-:math:`min*step`,
-:math:`min*{step}^2` , ...
-:math:`min*{step}^n` )
-where
-:math:`min` is ``gamma_grid.min_val`` ,
-:math:`step` is ``gamma_grid.step`` , and
-:math:`n` is the maximal index such that
+.. ocv:pyfunction:: cv2.SVM.train_auto(trainData, responses, varIdx, sampleIdx, params[, k_fold[, Cgrid[, gammaGrid[, pGrid[, nuGrid[, coeffGrid[, degreeGrid[, balanced]]]]]]]]) -> retval
 
-.. math::
+    :param k_fold: Cross-validation parameter. The training set is divided into ``k_fold`` subsets. One subset is used to train the model, the others form the test set. So, the SVM algorithm is executed ``k_fold`` times.
+    :param \*Grid: Iteration grid for the corresponding SVM parameter.
 
-    \texttt{gamma\_grid.min\_val} * \texttt{gamma\_grid.step} ^n <  \texttt{gamma\_grid.max\_val}
+    :param balanced: If ``true`` and the problem is 2-class classification then the method creates more balanced cross-validation subsets that is proportions between classes in subsets are close to such proportion in the whole train dataset.
 
-So ``step`` must always be greater than 1.
+The method trains the SVM model automatically by choosing the optimal
+parameters ``C``, ``gamma``, ``p``, ``nu``, ``coef0``, ``degree`` from
+:ocv:class:`CvSVMParams`. Parameters are considered optimal
+when the cross-validation estimate of the test set error
+is minimal.
 
-If there is no need to optimize a parameter, the corresponding grid step should be set to any value less or equal to 1. For example, to avoid optimization in ``gamma`` , set ``gamma_grid.step = 0`` , ``gamma_grid.min_val`` , ``gamma_grid.max_val`` as arbitrary numbers. In this case, the value ``params.gamma`` is taken for ``gamma`` .
+If there is no need to optimize a parameter, the corresponding grid step should be set to any value less than or equal to 1. For example, to avoid optimization in ``gamma``, set ``gamma_grid.step = 0``, ``gamma_grid.min_val``, ``gamma_grid.max_val`` as arbitrary numbers. In this case, the value ``params.gamma`` is taken for ``gamma``.
 
 And, finally, if the optimization in a parameter is required but
-the corresponding grid is unknown, you may call the function ``CvSVM::get_default_grid`` . To generate a grid, for example, for ``gamma`` , call ``CvSVM::get_default_grid(CvSVM::GAMMA)`` .
+the corresponding grid is unknown, you may call the function :ocv:func:`CvSVM::get_default_grid`. To generate a grid, for example, for ``gamma``, call ``CvSVM::get_default_grid(CvSVM::GAMMA)``.
 
-This function works for the case of classification
-( ``params.svm_type=CvSVM::C_SVC`` or ``params.svm_type=CvSVM::NU_SVC`` )
+This function works for the classification
+(``params.svm_type=CvSVM::C_SVC`` or ``params.svm_type=CvSVM::NU_SVC``)
 as well as for the regression
-( ``params.svm_type=CvSVM::EPS_SVR`` or ``params.svm_type=CvSVM::NU_SVR`` ). If ``params.svm_type=CvSVM::ONE_CLASS`` , no optimization is made and the usual SVM with parameters specified in ``params``  is executed.
+(``params.svm_type=CvSVM::EPS_SVR`` or ``params.svm_type=CvSVM::NU_SVR``). If ``params.svm_type=CvSVM::ONE_CLASS``, no optimization is made and the usual SVM with parameters specified in ``params`` is executed.
 
-.. index:: CvSVM::get_default_grid
+CvSVM::predict
+--------------
+Predicts the response for input sample(s).
 
-.. _CvSVM::get_default_grid:
+.. ocv:function:: float CvSVM::predict( const Mat& sample, bool returnDFVal=false ) const
+
+.. ocv:function::float CvSVM::predict( const CvMat* sample, bool returnDFVal=false ) const
+
+.. ocv:function::float CvSVM::predict( const CvMat* samples, CvMat* results ) const
+
+.. ocv:pyfunction:: cv2.SVM.predict(sample[, returnDFVal]) -> retval
+
+    :param sample(s): Input sample(s) for prediction.
+
+    :param returnDFVal: Specifies a type of the return value. If ``true`` and the problem is 2-class classification then the method returns the decision function value that is signed distance to the margin, else the function returns a class label (classification) or estimated function value (regression).
+
+    :param results: Output prediction responses for corresponding samples.
+
+If you pass one sample then prediction result is returned. If you want to get responses for several samples then you should pass the ``results`` matrix where prediction results will be stored.
 
 CvSVM::get_default_grid
 -----------------------
-.. ocv:function:: CvParamGrid CvSVM::get_default_grid( int param_id )
+Generates a grid for SVM parameters.
 
-    Generates a grid for SVM parameters.
+.. ocv:function:: CvParamGrid CvSVM::get_default_grid( int param_id )
 
-    :param param_id: SVN parameters IDs that must be one of the following:
+    :param param_id: SVM parameters IDs that must be one of the following:
 
             * **CvSVM::C**
 
@@ -207,33 +260,36 @@ CvSVM::get_default_grid
 
             * **CvSVM::DEGREE**
 
-        The grid will be generated for the parameter with this ID.
-
-The function generates a grid for the specified parameter of the SVM algorithm. The grid may be passed to the function ``CvSVM::train_auto`` .
+        The grid is generated for the parameter with this ID.
 
-.. index:: CvSVM::get_params
-
-.. _CvSVM::get_params:
+The function generates a grid for the specified parameter of the SVM algorithm. The grid may be passed to the function :ocv:func:`CvSVM::train_auto`.
 
 CvSVM::get_params
 -----------------
-.. ocv:function:: CvSVMParams CvSVM::get_params() const
-
-    Returns the current SVM parameters.
+Returns the current SVM parameters.
 
-This function may be used to get the optimal parameters obtained while automatically training ``CvSVM::train_auto`` .
-
-.. index:: CvSVM::get_support_vector*
+.. ocv:function:: CvSVMParams CvSVM::get_params() const
 
-.. _CvSVM::get_support_vector*:
+This function may be used to get the optimal parameters obtained while automatically training :ocv:func:`CvSVM::train_auto`.
 
-CvSVM::get_support_vector*
+CvSVM::get_support_vector
 --------------------------
+Retrieves a number of support vectors and the particular vector.
+
 .. ocv:function:: int CvSVM::get_support_vector_count() const
 
 .. ocv:function:: const float* CvSVM::get_support_vector(int i) const
 
-    Retrieves a number of support vectors and the particular vector.
+.. ocv:pyfunction:: cv2.SVM.get_support_vector_count() -> nsupportVectors
+
+    :param i: Index of the particular support vector.
 
 The methods can be used to retrieve a set of support vectors.
 
+CvSVM::get_var_count
+--------------------
+Returns the number of used features (variables count).
+
+.. ocv:function:: int CvSVM::get_var_count() const
+
+.. ocv:pyfunction:: cv2.SVM.get_var_count() -> nvars
index be800af..9db8e89 100644 (file)
@@ -3,13 +3,40 @@ Cascade Classification
 
 .. highlight:: cpp
 
-.. index:: FeatureEvaluator
+Haar Feature-based Cascade Classifier for Object Detection
+----------------------------------------------------------
+
+The object detector described below has been initially proposed by Paul Viola [Viola01]_ and improved by Rainer Lienhart [Lienhart02]_.
+
+First, a classifier (namely a *cascade of boosted classifiers working with haar-like features*) is trained with a few hundred sample views of a particular object (i.e., a face or a car), called positive examples, that are scaled to the same size (say, 20x20), and negative examples - arbitrary images of the same size.
+
+After a classifier is trained, it can be applied to a region of interest (of the same size as used during the training) in an input image. The classifier outputs a "1" if the region is likely to show the object (i.e., face/car), and "0" otherwise. To search for the object in the whole image one can move the search window across the image and check every location using the classifier. The classifier is designed so that it can be easily "resized" in order to be able to find the objects of interest at different sizes, which is more efficient than resizing the image itself. So, to find an object of an unknown size in the image the scan procedure should be done several times at different scales.
+
+The word "cascade" in the classifier name means that the resultant classifier consists of several simpler classifiers (*stages*) that are applied subsequently to a region of interest until at some stage the candidate is rejected or all the stages are passed. The word "boosted" means that the classifiers at every stage of the cascade are complex themselves and they are built out of basic classifiers using one of four different ``boosting`` techniques (weighted voting). Currently Discrete Adaboost, Real Adaboost, Gentle Adaboost and Logitboost are supported. The basic classifiers are decision-tree classifiers with at least 2 leaves. Haar-like features are the input to the basic classifers, and are calculated as described below. The current algorithm uses the following Haar-like features:
+
+
+.. image:: pics/haarfeatures.png
+
+
+The feature used in a particular classifier is specified by its shape (1a, 2b etc.), position within the region of interest and the scale (this scale is not the same as the scale used at the detection stage, though these two scales are multiplied). For example, in the case of the third line feature (2c) the response is calculated as the difference between the sum of image pixels under the rectangle covering the whole feature (including the two white stripes and the black stripe in the middle) and the sum of the image pixels under the black stripe multiplied by 3 in order to compensate for the differences in the size of areas. The sums of pixel values over a rectangular regions are calculated rapidly using integral images (see below and the :ocv:func:`integral` description).
+
+To see the object detector at work, have a look at the facedetect demo:
+https://code.ros.org/svn/opencv/trunk/opencv/samples/cpp/facedetect.cpp
+
+The following reference is for the detection part only. There is a separate application called  ``opencv_traincascade`` that can train a cascade of boosted classifiers from a set of samples.
+
+.. note:: In the new C++ interface it is also possible to use LBP (local binary pattern) features in addition to Haar-like features.
+
+.. [Viola01] Paul Viola and Michael J. Jones. Rapid Object Detection using a Boosted Cascade of Simple Features. IEEE CVPR, 2001. The paper is available online at http://www.ai.mit.edu/people/viola/
+
+.. [Lienhart02] Rainer Lienhart and Jochen Maydt. An Extended Set of Haar-like Features for Rapid Object Detection. IEEE ICIP 2002, Vol. 1, pp. 900-903, Sep. 2002. This paper, as well as the extended technical report, can be retrieved at http://www.lienhart.de/Publications/publications.html
+
 
 FeatureEvaluator
 ----------------
-.. c:type:: FeatureEvaluator
+.. ocv:class:: FeatureEvaluator
 
-Base class for computing feature values in cascade classifiers ::
+Base class for computing feature values in cascade classifiers. ::
 
     class CV_EXPORTS FeatureEvaluator
     {
@@ -30,39 +57,36 @@ Base class for computing feature values in cascade classifiers ::
     };
 
 
-.. index:: FeatureEvaluator::read
-
 FeatureEvaluator::read
 --------------------------
-.. ocv:function:: bool FeatureEvaluator::read(const FileNode& node)
+Reads parameters of features from the ``FileStorage`` node.
 
-    Reads parameters of features from the ``FileStorage`` node.
+.. ocv:function:: bool FeatureEvaluator::read(const FileNode& node)
 
     :param node: File node from which the feature parameters are read.
 
-.. index:: FeatureEvaluator::clone
+
 
 FeatureEvaluator::clone
 ---------------------------
+Returns a full copy of the feature evaluator.
+
 .. ocv:function:: Ptr<FeatureEvaluator> FeatureEvaluator::clone() const
 
-    Returns a full copy of the feature evaluator.
 
-.. index:: FeatureEvaluator::getFeatureType
 
 FeatureEvaluator::getFeatureType
 ------------------------------------
-.. ocv:function:: int FeatureEvaluator::getFeatureType() const
+Returns the feature type (``HAAR`` or ``LBP`` for now).
 
-    Returns the feature type (``HAAR`` or ``LBP`` for now).
+.. ocv:function:: int FeatureEvaluator::getFeatureType() const
 
-.. index:: FeatureEvaluator::setImage
 
 FeatureEvaluator::setImage
 ------------------------------
-.. ocv:function:: bool FeatureEvaluator::setImage(const Mat& img, Size origWinSize)
+Assigns an image to feature evaluator.
 
-    Assigns an image to feature evaluator.
+.. ocv:function:: bool FeatureEvaluator::setImage(const Mat& img, Size origWinSize)
 
     :param img: Matrix of the type   ``CV_8UC1``  containing an image where the features are computed.
 
@@ -70,170 +94,110 @@ FeatureEvaluator::setImage
 
 The method assigns an image, where the features will be computed, to the feature evaluator.
 
-.. index:: FeatureEvaluator::setWindow
+
 
 FeatureEvaluator::setWindow
 -------------------------------
-.. ocv:function:: bool FeatureEvaluator::setWindow(Point p)
+Assigns a window in the current image where the features will be computed.
 
-    Assigns a window in the current image where the features will be computed.
+.. ocv:function:: bool FeatureEvaluator::setWindow(Point p)
 
     :param p: Upper left point of the window where the features are computed. Size of the window is equal to the size of training images.
 
-.. index:: FeatureEvaluator::calcOrd
-
 FeatureEvaluator::calcOrd
 -----------------------------
-.. ocv:function:: double FeatureEvaluator::calcOrd(int featureIdx) const
+Computes the value of an ordered (numerical) feature.
 
-    Computes the value of an ordered (numerical) feature.
+.. ocv:function:: double FeatureEvaluator::calcOrd(int featureIdx) const
 
     :param featureIdx: Index of the feature whose value is computed.
 
 The function returns the computed value of an ordered feature.
 
-.. index:: FeatureEvaluator::calcCat
+
 
 FeatureEvaluator::calcCat
 -----------------------------
-.. ocv:function:: int FeatureEvaluator::calcCat(int featureIdx) const
+Computes the value of a categorical feature.
 
-    Computes the value of a categorical feature.
+.. ocv:function:: int FeatureEvaluator::calcCat(int featureIdx) const
 
     :param featureIdx: Index of the feature whose value is computed.
 
-The function returns the computed label of a categorical feature, that is, the value from [0,... (number of categories - 1)].
+The function returns the computed label of a categorical feature, which is the value from [0,... (number of categories - 1)].
 
-.. index:: FeatureEvaluator::create
 
 FeatureEvaluator::create
 ----------------------------
-.. ocv:function:: static Ptr<FeatureEvaluator> FeatureEvaluator::create(int type)
+Constructs the feature evaluator.
 
-    Constructs the feature evaluator.
+.. ocv:function:: static Ptr<FeatureEvaluator> FeatureEvaluator::create(int type)
 
     :param type: Type of features evaluated by cascade (``HAAR`` or ``LBP`` for now).
 
-.. index:: CascadeClassifier
-
-.. _CascadeClassifier:
 
 CascadeClassifier
 -----------------
-.. c:type:: CascadeClassifier
+.. ocv:class:: CascadeClassifier
 
-The cascade classifier class for object detection ::
-
-    class CascadeClassifier
-    {
-    public:
-            // structure for storing a tree node
-        struct CV_EXPORTS DTreeNode
-        {
-            int featureIdx; // index of the feature on which we perform the split
-            float threshold; // split threshold of ordered features only
-            int left; // left child index in the tree nodes array
-            int right; // right child index in the tree nodes array
-        };
-
-        // structure for storing a decision tree
-        struct CV_EXPORTS DTree
-        {
-            int nodeCount; // nodes count
-        };
-
-        // structure for storing a cascade stage (BOOST only for now)
-        struct CV_EXPORTS Stage
-        {
-            int first; // first tree index in tree array
-            int ntrees; // number of trees
-            float threshold; // threshold of stage sum
-        };
-
-        enum { BOOST = 0 }; // supported stage types
-
-        // mode of detection (see parameter flags in function HaarDetectObjects)
-        enum { DO_CANNY_PRUNING = CV_HAAR_DO_CANNY_PRUNING,
-               SCALE_IMAGE = CV_HAAR_SCALE_IMAGE,
-               FIND_BIGGEST_OBJECT = CV_HAAR_FIND_BIGGEST_OBJECT,
-               DO_ROUGH_SEARCH = CV_HAAR_DO_ROUGH_SEARCH };
-
-        CascadeClassifier(); // default constructor
-        CascadeClassifier(const string& filename);
-        ~CascadeClassifier(); // destructor
-
-        bool empty() const;
-        bool load(const string& filename);
-        bool read(const FileNode& node);
-
-        void detectMultiScale( const Mat& image, vector<Rect>& objects,
-                               double scaleFactor=1.1, int minNeighbors=3,
-                                                       int flags=0, Size minSize=Size());
-
-        bool setImage( Ptr<FeatureEvaluator>&, const Mat& );
-        int runAt( Ptr<FeatureEvaluator>&, Point );
-
-        bool is_stump_based; // true, if the trees are stumps
-
-        int stageType; // stage type (BOOST only for now)
-        int featureType; // feature type (HAAR or LBP for now)
-        int ncategories; // number of categories (for categorical features only)
-        Size origWinSize; // size of training images
-
-        vector<Stage> stages; // vector of stages (BOOST for now)
-        vector<DTree> classifiers; // vector of decision trees
-        vector<DTreeNode> nodes; // vector of tree nodes
-        vector<float> leaves; // vector of leaf values
-        vector<int> subsets; // subsets of split by categorical feature
-
-        Ptr<FeatureEvaluator> feval; // pointer to feature evaluator
-        Ptr<CvHaarClassifierCascade> oldCascade; // pointer to old cascade
-    };
-
-
-.. index:: CascadeClassifier::CascadeClassifier
+Cascade classifier class for object detection.
 
 CascadeClassifier::CascadeClassifier
 ----------------------------------------
+Loads a classifier from a file.
+
 .. ocv:function:: CascadeClassifier::CascadeClassifier(const string& filename)
 
-    Loads a classifier from a file.
+.. ocv:pyfunction:: cv2.CascadeClassifier(filename) -> <CascadeClassifier object>
 
     :param filename: Name of the file from which the classifier is loaded.
 
-.. index:: CascadeClassifier::empty
+
 
 CascadeClassifier::empty
 ----------------------------
+Checks whether the classifier has been loaded.
+
 .. ocv:function:: bool CascadeClassifier::empty() const
 
-    Checks if the classifier has been loaded or not.
 
-.. index:: CascadeClassifier::load
+.. ocv:pyfunction:: cv2.CascadeClassifier.empty() -> retval
 
 CascadeClassifier::load
 ---------------------------
+Loads a classifier from a file.
+
 .. ocv:function:: bool CascadeClassifier::load(const string& filename)
 
-    Loads a classifier from a file. The previous content is destroyed.
+.. ocv:pyfunction:: cv2.CascadeClassifier.load(filename) -> retval
+
+    :param filename: Name of the file from which the classifier is loaded. The file may contain an old HAAR classifier trained by the haartraining application or a new cascade classifier trained by the traincascade application.
 
-    :param filename: Name of the file from which the classifier is loaded. The file may contain an old HAAR classifier (trained by the haartraining application) or new cascade classifier trained traincascade application.
 
-.. index:: CascadeClassifier::read
 
 CascadeClassifier::read
 ---------------------------
+Reads a classifier from a FileStorage node. 
+
 .. ocv:function:: bool CascadeClassifier::read(const FileNode& node)
 
-    Reads a classifier from a FileStorage node. The file may contain a new cascade classifier (trained traincascade application) only.
+.. note:: The file may contain a new cascade classifier (trained traincascade application) only.
 
-.. index:: CascadeClassifier::detectMultiScale
 
 CascadeClassifier::detectMultiScale
 ---------------------------------------
+Detects objects of different sizes in the input image. The detected objects are returned as a list of rectangles.
+
 .. ocv:function:: void CascadeClassifier::detectMultiScale( const Mat& image,                            vector<Rect>& objects,                            double scaleFactor=1.1,                            int minNeighbors=3, int flags=0,                            Size minSize=Size())
 
-    Detects objects of different sizes in the input image. The detected objects are returned as a list of rectangles.
+.. ocv:pyfunction:: cv2.CascadeClassifier.detectMultiScale(image[, scaleFactor[, minNeighbors[, flags[, minSize[, maxSize]]]]]) -> objects
+.. ocv:pyfunction:: cv2.CascadeClassifier.detectMultiScale(image, rejectLevels, levelWeights[, scaleFactor[, minNeighbors[, flags[, minSize[, maxSize[, outputRejectLevels]]]]]]) -> objects
+
+.. ocv:cfunction:: CvSeq* cvHaarDetectObjects( const CvArr* image, CvHaarClassifierCascade* cascade, CvMemStorage* storage, double scaleFactor=1.1, int minNeighbors=3, int flags=0, CvSize minSize=cvSize(0, 0), CvSize maxSize=cvSize(0, 0) )
+
+.. ocv:pyoldfunction:: cv.HaarDetectObjects(image, cascade, storage, scaleFactor=1.1, minNeighbors=3, flags=0, minSize=(0, 0))-> detectedObjects
+
+    :param cascade: Haar classifier cascade (OpenCV 1.x API only). It can be loaded from XML or YAML file using :ocv:cfunc:`Load`. When the cascade is not needed anymore, release it using ``cvReleaseHaarClassifierCascade(&cascade)``.
 
     :param image: Matrix of the type   ``CV_8U``  containing an image where objects are detected.
 
@@ -247,47 +211,62 @@ CascadeClassifier::detectMultiScale
 
     :param minSize: Minimum possible object size. Objects smaller than that are ignored.
 
-.. index:: CascadeClassifier::setImage
+
 
 CascadeClassifier::setImage
 -------------------------------
+Sets an image for detection.
+
 .. ocv:function:: bool CascadeClassifier::setImage( Ptr<FeatureEvaluator>& feval, const Mat& image )
 
-    Sets an image for detection, which is called by ``detectMultiScale`` at each image level.
+.. ocv:cfunction:: void cvSetImagesForHaarClassifierCascade( CvHaarClassifierCascade* cascade, const CvArr* sum, const CvArr* sqsum, const CvArr* tiltedSum, double scale )
+
+    :param cascade: Haar classifier cascade (OpenCV 1.x API only). See :ocv:func:`CascadeClassifier::detectMultiScale` for more information.
 
-    :param feval: Pointer to the feature evaluator that is used for computing features.
+    :param feval: Pointer to the feature evaluator used for computing features.
 
     :param image: Matrix of the type   ``CV_8UC1``  containing an image where the features are computed.
 
-.. index:: CascadeClassifier::runAt
+The function is automatically called by :ocv:func:`CascadeClassifier::detectMultiScale` at every image scale. But if you want to test various locations manually using :ocv:func:`CascadeClassifier::runAt`, you need to call the function before, so that the integral images are computed.
+
+.. note:: in the old API you need to supply integral images (that can be obtained using :ocv:cfunc:`Integral`) instead of the original image.
+
 
 CascadeClassifier::runAt
 ----------------------------
+Runs the detector at the specified point.
+
 .. ocv:function:: int CascadeClassifier::runAt( Ptr<FeatureEvaluator>& feval, Point pt )
 
-    Runs the detector at the specified point. Use ``setImage`` to set the image that the detector is working with.
+.. ocv:cfunction:: int cvRunHaarClassifierCascade( CvHaarClassifierCascade* cascade, CvPoint pt, int startStage=0 )
+
+    :param cascade: Haar classifier cascade (OpenCV 1.x API only). See :ocv:func:`CascadeClassifier::detectMultiScale` for more information.
 
-    :param feval: Feature evaluator that is used for computing features.
+    :param feval: Feature evaluator used for computing features.
 
     :param pt: Upper left point of the window where the features are computed. Size of the window is equal to the size of training images.
 
 The function returns 1 if the cascade classifier detects an object in the given location.
 Otherwise, it returns negated index of the stage at which the candidate has been rejected.
 
-.. index:: groupRectangles
+Use :ocv:func:`CascadeClassifier::setImage` to set the image for the detector to work with.
 
 groupRectangles
 -------------------
-.. ocv:function:: void groupRectangles(vector<Rect>& rectList,                     int groupThreshold, double eps=0.2)
+Groups the object candidate rectangles.
+
+.. ocv:function:: void groupRectangles(vector<Rect>& rectList, int groupThreshold, double eps=0.2)
 
-    Groups the object candidate rectangles.
+.. ocv:pyfunction:: cv2.groupRectangles(rectList, groupThreshold[, eps]) -> None
+.. ocv:pyfunction:: cv2.groupRectangles(rectList, groupThreshold[, eps]) -> weights
+.. ocv:pyfunction:: cv2.groupRectangles(rectList, groupThreshold, eps, weights, levelWeights) -> None
 
-    :param rectList: Input/output vector of rectangles. Output vector includes retained and grouped rectangles.??
+    :param rectList: Input/output vector of rectangles. Output vector includes retained and grouped rectangles.
 
-    :param groupThreshold: Minimum possible number of rectangles minus 1. The threshold is used in a group of rectangles to retain it.??
+    :param groupThreshold: Minimum possible number of rectangles minus 1. The threshold is used in a group of rectangles to retain it.
 
     :param eps: Relative difference between sides of the rectangles to merge them into a group.
 
 The function is a wrapper for the generic function
-:ref:`partition` . It clusters all the input rectangles using the rectangle equivalence criteria that combines rectangles with similar sizes and similar locations (the similarity is defined by ``eps`` ). When ``eps=0`` , no clustering is done at all. If
+:ocv:func:`partition` . It clusters all the input rectangles using the rectangle equivalence criteria that combines rectangles with similar sizes and similar locations. The similarity is defined by ``eps``. When ``eps=0`` , no clustering is done at all. If
 :math:`\texttt{eps}\rightarrow +\inf` , all the rectangles are put in one cluster. Then, the small clusters containing less than or equal to ``groupThreshold`` rectangles are rejected. In each other cluster, the average rectangle is computed and put into the output rectangle list.
diff --git a/modules/objdetect/doc/pics/haarfeatures.png b/modules/objdetect/doc/pics/haarfeatures.png
new file mode 100644 (file)
index 0000000..ff2eabe
Binary files /dev/null and b/modules/objdetect/doc/pics/haarfeatures.png differ
index dde0ee5..65be794 100644 (file)
@@ -443,7 +443,10 @@ class FuncInfo(object):
         # we write ClassName([args ...]) -> object
         if have_empty_constructor and len(self.variants) == 2:
             idx = self.variants[1].py_arglist != []
-            docstring_list = ["[" + self.variants[idx].py_docstring + "]"]
+            s = self.variants[idx].py_docstring
+            p1 = s.find("(")
+            p2 = s.rfind(")")
+            docstring_list = [s[:p1+1] + "[" + s[p1+2:p2] + "]" + s[p2:]]
             
         return Template('    {"$py_funcname", (PyCFunction)$wrap_funcname, METH_KEYWORDS, "$py_docstring"},\n'
                         ).substitute(py_funcname = self.variants[0].wname, wrap_funcname=self.get_wrapper_name(),
index d25d3c1..6ed01a4 100644 (file)
@@ -1,5 +1,5 @@
 ############################
-OpenCV 2.x C++ API Reference
+OpenCV API Reference
 ############################
 
 .. toctree::
index 2644bdd..f70d876 100644 (file)
@@ -3,21 +3,26 @@ Motion Analysis and Object Tracking
 
 .. highlight:: cpp
 
-.. index:: calcOpticalFlowPyrLK
+
 
 calcOpticalFlowPyrLK
 ------------------------
+Calculates an optical flow for a sparse feature set using the iterative Lucas-Kanade method with pyramids.
+
 .. ocv:function:: void calcOpticalFlowPyrLK( InputArray prevImg, InputArray nextImg, InputArray prevPts, InputOutputArray nextPts, OutputArray status, OutputArray err, Size winSize=Size(15,15), int maxLevel=3,        TermCriteria criteria=TermCriteria(TermCriteria::COUNT+TermCriteria::EPS, 30, 0.01), double derivLambda=0.5, int flags=0 )
 
-    Calculates an optical flow for a sparse feature set using the iterative Lucas-Kanade method with pyramids.
+.. ocv:pyfunction:: cv2.calcOpticalFlowPyrLK(prevImg, nextImg, prevPts[, nextPts[, status[, err[, winSize[, maxLevel[, criteria[, derivLambda[, flags]]]]]]]]) -> nextPts, status, err
 
-    :param prevImg: The first 8-bit single-channel or 3-channel input image.
+.. ocv:cfunction:: void cvCalcOpticalFlowPyrLK( const CvArr* prev, const CvArr* curr, CvArr* prevPyr, CvArr* currPyr, const CvPoint2D32f* prevFeatures, CvPoint2D32f* currFeatures, int count, CvSize winSize, int level, char* status, float* trackError, CvTermCriteria criteria, int flags )
+.. ocv:pyoldfunction:: cv.CalcOpticalFlowPyrLK( prev, curr, prevPyr, currPyr, prevFeatures, winSize, level, criteria, flags, guesses=None) -> (currFeatures, status, trackError)
 
-    :param nextImg: The second input image of the same size and the same type as  ``prevImg`` .
+    :param prevImg: First 8-bit single-channel or 3-channel input image.
 
-    :param prevPts: Vector of points for which the flow needs to be found.
+    :param nextImg: Second input image of the same size and the same type as  ``prevImg`` .
 
-    :param nextPts: Output vector of points containing the calculated new positions of input features in the second image.
+    :param prevPts: Vector of 2D points for which the flow needs to be found. The point coordinates must be single-precision floating-point numbers.
+
+    :param nextPts: Output vector of 2D points (with single-precision floating-point coordinates) containing the calculated new positions of input features in the second image. When ``OPTFLOW_USE_INITIAL_FLOW`` flag is passed, the vector must have the same size as in the input.
 
     :param status: Output status vector. Each element of the vector is set to 1 if the flow for the corresponding features has been found. Otherwise, it is set to 0.
 
@@ -36,20 +41,21 @@ calcOpticalFlowPyrLK
             * **OPTFLOW_USE_INITIAL_FLOW** Use initial estimations stored in  ``nextPts`` . If the flag is not set, then ``prevPts`` is copied to ``nextPts`` and is considered as the initial estimate.
             
 The function implements a sparse iterative version of the Lucas-Kanade optical flow in pyramids. See
-Bouguet00
-.
+[Bouguet00]_.
+
 
-.. index:: calcOpticalFlowFarneback
 
 calcOpticalFlowFarneback
 ----------------------------
+Computes a dense optical flow using the Gunnar Farneback's algorithm.
+
 .. ocv:function:: void calcOpticalFlowFarneback( InputArray prevImg, InputArray nextImg,                               InputOutputArray flow, double pyrScale, int levels, int winsize, int iterations, int polyN, double polySigma, int flags )
 
-    Computes a dense optical flow using the Gunnar Farneback's algorithm.
+.. ocv:pyfunction:: cv2.calcOpticalFlowFarneback(prev, next, pyr_scale, levels, winsize, iterations, poly_n, poly_sigma, flags[, flow]) -> flow
 
-    :param prevImg: The first 8-bit single-channel input image.
+    :param prevImg: First 8-bit single-channel input image.
 
-    :param nextImg: The second input image of the same size and the same type as  ``prevImg`` .
+    :param nextImg: Second input image of the same size and the same type as  ``prevImg`` .
 
     :param flow: Computed flow image that has the same size as  ``prevImg``  and type  ``CV_32FC2`` .
 
@@ -69,37 +75,120 @@ calcOpticalFlowFarneback
 
             * **OPTFLOW_USE_INITIAL_FLOW** Use the input  ``flow``  as an initial flow approximation.
 
-            * **OPTFLOW_FARNEBACK_GAUSSIAN** Use the Gaussian  :math:`\texttt{winsize}\times\texttt{winsize}`  filter instead of a box filter of the same size for optical flow estimation. Usually, this option gives more accurate flow than with a box filter, at the cost of lower speed. Normally,  ``winsize``  for a Gaussian window should be set to a larger value to achieve the same level of robustness.
+            * **OPTFLOW_FARNEBACK_GAUSSIAN** Use the Gaussian  :math:`\texttt{winsize}\times\texttt{winsize}`  filter instead of a box filter of the same size for optical flow estimation. Usually, this option gives more accurate flow than with a box filter, at the cost of lower speed. Normally,  ``winsize``  for a Gaussian window should be set to a larger value to achieve the same level of robustness.
 
-The function finds an optical flow for each ``prevImg`` pixel using the alorithm so that
+The function finds an optical flow for each ``prevImg`` pixel using the [Farneback2003]_ alorithm so that
 
 .. math::
 
-    \texttt{prevImg} (x,y)  \sim \texttt{nextImg} ( \texttt{flow} (x,y)[0],  \texttt{flow} (x,y)[1])
+    \texttt{prevImg} (y,x)  \sim \texttt{nextImg} ( y + \texttt{flow} (y,x)[1],  x + \texttt{flow} (y,x)[0])
+
+
+
+CalcOpticalFlowBM
+-----------------
+Calculates the optical flow for two images by using the block matching method.
+
+.. ocv::cfunction:: void cvCalcOpticalFlowBM( const CvArr* prev, const CvArr* curr, CvSize blockSize, CvSize shiftSize, CvSize maxRange, int usePrevious, CvArr* velx, CvArr* vely )
+
+.. ocv:pyoldfunction:: cv.CalcOpticalFlowBM(prev, curr, blockSize, shiftSize, maxRange, usePrevious, velx, vely)-> None
+
+        :param prev: First image, 8-bit, single-channel 
+
+        :param curr: Second image, 8-bit, single-channel 
+
+        :param blockSize: Size of basic blocks that are compared 
+
+        :param shiftSize: Block coordinate increments 
+
+        :param maxRange: Size of the scanned neighborhood in pixels around the block 
+
+        :param usePrevious: Flag that specifies whether to use the input velocity as initial approximations or not.
+
+        :param velx: Horizontal component of the optical flow of
+
+            .. math::
+
+                \left \lfloor   \frac{\texttt{prev->width} - \texttt{blockSize.width}}{\texttt{shiftSize.width}}   \right \rfloor \times \left \lfloor   \frac{\texttt{prev->height} - \texttt{blockSize.height}}{\texttt{shiftSize.height}}   \right \rfloor 
+
+            size, 32-bit floating-point, single-channel 
+
+        :param vely: Vertical component of the optical flow of the same size  ``velx`` , 32-bit floating-point, single-channel 
+
+
+The function calculates the optical flow for overlapped blocks ``blockSize.width x blockSize.height`` pixels each, thus the velocity fields are smaller than the original images. For every block in  ``prev``
+the functions tries to find a similar block in ``curr`` in some neighborhood of the original block or shifted by ``(velx(x0,y0), vely(x0,y0))`` block as has been calculated by previous function call (if ``usePrevious=1``)
+
+
+CalcOpticalFlowHS
+-----------------
+Calculates the optical flow for two images using Horn-Schunck algorithm.
+
+.. ocv::cfunction:: void cvCalcOpticalFlowHS(  const CvArr* prev, const CvArr* curr, int usePrevious, CvArr* velx, CvArr* vely, double lambda, CvTermCriteria criteria )
+
+.. ocv:pyoldfunction:: cv.CalcOpticalFlowHS(prev, curr, usePrevious, velx, vely, lambda, criteria)-> None
 
+    :param prev: First image, 8-bit, single-channel 
+
+    :param curr: Second image, 8-bit, single-channel 
+
+    :param usePrevious: Flag that specifies whether to use the input velocity as initial approximations or not.
+
+    :param velx: Horizontal component of the optical flow of the same size as input images, 32-bit floating-point, single-channel 
+
+    :param vely: Vertical component of the optical flow of the same size as input images, 32-bit floating-point, single-channel 
+
+    :param lambda: Smoothness weight. The larger it is, the smoother optical flow map you get.
+
+    :param criteria: Criteria of termination of velocity computing 
+
+The function computes the flow for every pixel of the first input image using the Horn and Schunck algorithm [Horn81]_. The function is obsolete. To track sparse features, use :ocv:func:`calcOpticalFlowPyrLK`. To track all the pixels, use :ocv:func:`calcOpticalFlowFarneback`.
+
+
+CalcOpticalFlowLK
+-----------------
+
+Calculates the optical flow for two images using Lucas-Kanade algorithm.
+
+.. ocv:cfunction:: void cvCalcOpticalFlowLK( const CvArr* prev, const CvArr* curr, CvSize winSize, CvArr* velx, CvArr* vely )
+
+.. ocv:pyoldfunction:: cv.CalcOpticalFlowLK(prev, curr, winSize, velx, vely)-> None
+
+    :param prev: First image, 8-bit, single-channel 
+
+    :param curr: Second image, 8-bit, single-channel 
+
+    :param winSize: Size of the averaging window used for grouping pixels 
+
+    :param velx: Horizontal component of the optical flow of the same size as input images, 32-bit floating-point, single-channel 
+
+    :param vely: Vertical component of the optical flow of the same size as input images, 32-bit floating-point, single-channel 
+
+The function computes the flow for every pixel of the first input image using the Lucas and Kanade algorithm [Lucas81]_. The function is obsolete. To track sparse features, use :ocv:func:`calcOpticalFlowPyrLK`. To track all the pixels, use :ocv:func:`calcOpticalFlowFarneback`.
 
-.. index:: estimateRigidTransform
 
 estimateRigidTransform
 --------------------------
+Computes an optimal affine transformation between two 2D point sets.
+
 .. ocv:function:: Mat estimateRigidTransform( InputArray src, InputArray dst, bool fullAffine )
 
-    Computes an optimal affine transformation between two 2D point sets.
+.. ocv:pyfunction:: cv2.estimateRigidTransform(src, dst, fullAffine) -> retval
 
-    :param src: The first input 2D point set, stored in ``std::vector`` or ``Mat``, or an image, stored in ``Mat``
+    :param src: First input 2D point set stored in ``std::vector`` or ``Mat``, or an image stored in ``Mat``.
 
-    :param dst: The second input 2D point set of the same size and the same type as ``A``, or another image.
+    :param dst: Second input 2D point set of the same size and the same type as ``A``, or another image.
 
     :param fullAffine: If true, the function finds an optimal affine transformation with no additional resrictions (6 degrees of freedom). Otherwise, the class of transformations to choose from is limited to combinations of translation, rotation, and uniform scaling (5 degrees of freedom).
 
 The function finds an optimal affine transform *[A|b]* (a ``2 x 3`` floating-point matrix) that approximates best the affine transformation between:
 
-  #.
-      two point sets
-  #.
-      or between 2 raster images. In this case, the function first finds some features in the ``src`` image and finds the corresponding features in ``dst`` image, after which the problem is reduced to the first case.
+  *
+      Two point sets
+  *
+      Two raster images. In this case, the function first finds some features in the ``src`` image and finds the corresponding features in ``dst`` image. After that, the problem is reduced to the first case.
       
-In the case of point sets, the problem is formulated in the following way. We need to find such 2x2 matrix *A* and 2x1 vector *b*, such that:
+In case of point sets, the problem is formulated as follows: you need to find a 2x2 matrix *A* and 2x1 vector *b* so that:
 
     .. math::
 
@@ -107,7 +196,7 @@ In the case of point sets, the problem is formulated in the following way. We ne
 
     where ``src[i]`` and ``dst[i]`` are the i-th points in ``src`` and ``dst``, respectively
     
-    :math:`[A|b]` can be either arbitrary (when ``fullAffine=true`` ) or have form
+    :math:`[A|b]` can be either arbitrary (when ``fullAffine=true`` ) or have a form of
 
     .. math::
 
@@ -115,19 +204,24 @@ In the case of point sets, the problem is formulated in the following way. We ne
 
     when ``fullAffine=false`` .
 
-    See Also:
-    :ocv:func:`getAffineTransform`,
-    :ocv:func:`getPerspectiveTransform`,
-    :ocv:func:`findHomography`
+.. seealso::
+:ocv:func:`getAffineTransform`,
+:ocv:func:`getPerspectiveTransform`,
+:ocv:func:`findHomography`
+
 
 
-.. index:: updateMotionHistory
 
 updateMotionHistory
 -----------------------
+Updates the motion history image by a moving silhouette.
+
 .. ocv:function:: void updateMotionHistory( InputArray silhouette, InputOutputArray mhi, double timestamp, double duration )
 
-    Updates the motion history image by a moving silhouette.
+.. ocv:pyfunction:: cv2.updateMotionHistory(silhouette, mhi, timestamp, duration) -> None
+
+.. ocv:cfunction:: void cvUpdateMotionHistory( const CvArr* silhouette, CvArr* mhi, double timestamp, double duration )
+.. ocv:pyoldfunction:: cv.UpdateMotionHistory(silhouette, mhi, timestamp, duration)-> None
 
     :param silhouette: Silhouette mask that has non-zero pixels where the motion occurs.
 
@@ -148,19 +242,24 @@ That is, MHI pixels where the motion occurs are set to the current ``timestamp``
 The function, together with
 :ocv:func:`calcMotionGradient` and
 :ocv:func:`calcGlobalOrientation` , implements a motion templates technique described in
-Davis97
+[Davis97]_
 and
-Bradski00
+[Bradski00]_
 .
 See also the OpenCV sample ``motempl.c`` that demonstrates the use of all the motion template functions.
 
-.. index:: calcMotionGradient
+
 
 calcMotionGradient
 ----------------------
+Calculates a gradient orientation of a motion history image.
+
 .. ocv:function:: void calcMotionGradient( InputArray mhi, OutputArray mask, OutputArray orientation,                         double delta1, double delta2, int apertureSize=3 )
 
-    Calculates a gradient orientation of a motion history image.
+.. ocv:pyfunction:: cv2.calcMotionGradient(mhi, delta1, delta2[, mask[, orientation[, apertureSize]]]) -> mask, orientation
+
+.. ocv:cfunction:: void cvCalcMotionGradient( const CvArr* mhi, CvArr* mask, CvArr* orientation, double delta1, double delta2, int apertureSize=3 )
+.. ocv:pyoldfunction:: cv.CalcMotionGradient(mhi, mask, orientation, delta1, delta2, apertureSize=3)-> None
 
     :param mhi: Motion history single-channel floating-point image.
 
@@ -187,13 +286,18 @@ In fact,
 :ocv:func:`fastArctan` and
 :ocv:func:`phase` are used so that the computed angle is measured in degrees and covers the full range 0..360. Also, the ``mask`` is filled to indicate pixels where the computed angle is valid.
 
-.. index:: calcGlobalOrientation
+
 
 calcGlobalOrientation
 -------------------------
+Calculates a global motion orientation in a selected region.
+
 .. ocv:function:: double calcGlobalOrientation( InputArray orientation, InputArray mask, InputArray mhi, double timestamp, double duration )
 
-    Calculates a global motion orientation in a selected region.
+.. ocv:pyfunction:: cv2.calcGlobalOrientation(orientation, mask, mhi, timestamp, duration) -> retval
+
+.. ocv:cfunction:: double cvCalcGlobalOrientation( const CvArr* orientation, const CvArr* mask, const CvArr* mhi, double timestamp, double duration )
+.. ocv:pyoldfunction:: cv.CalcGlobalOrientation(orientation, mask, mhi, timestamp, duration)-> float
 
     :param orientation: Motion gradient orientation image calculated by the function  :ocv:func:`calcMotionGradient` .
     
@@ -212,36 +316,45 @@ the weighted orientation histogram, where a recent motion has a larger
 weight and the motion occurred in the past has a smaller weight, as recorded in ``mhi`` .
 
 
-.. index:: segmentMotion
+
 
 segmentMotion
 -------------
+Splits a motion history image into a few parts corresponding to separate independent motions (for example, left hand, right hand).
 
 .. ocv:function:: void segmentMotion(InputArray mhi, OutputArray segmask, vector<Rect>& boundingRects, double timestamp, double segThresh)
 
-    Splits a motion history image into a few parts corresponding to separate independent motions (e.g. left hand, right hand).
+.. ocv:pyfunction:: cv2.segmentMotion(mhi, boundingRects, timestamp, segThresh[, segmask]) -> segmask
+
+.. ocv:cfunction:: CvSeq* cvSegmentMotion( const CvArr* mhi, CvArr* segMask, CvMemStorage* storage, double timestamp, double segThresh )
+.. ocv:pyoldfunction:: cv.SegmentMotion(mhi, segMask, storage, timestamp, segThresh)-> None
 
     :param mhi: Motion history image.
 
-    :param segmask: Image where the mask found should be stored, single-channel, 32-bit floating-point.
+    :param segmask: Image where the found mask should be stored, single-channel, 32-bit floating-point.
 
-    :param boundingRects: Vector that will contain ROIs of motion connected components.
+    :param boundingRects: Vector containing ROIs of motion connected components.
 
     :param timestamp: Current time in milliseconds or other units.
 
-    :param segThresh: Segmentation threshold; recommended to be equal to the interval between motion history "steps" or greater.
+    :param segThresh: Segmentation threshold that is recommended to be equal to the interval between motion history "steps" or greater.
  
 
 The function finds all of the motion segments and marks them in ``segmask`` with individual values (1,2,...). It also computes a vector with ROIs of motion connected components. After that the motion direction for every component can be calculated with :ocv:func:`calcGlobalOrientation` using the extracted mask of the particular component.
 
 
-.. index:: CamShift
+
 
 CamShift
 ------------
+Finds an object center, size, and orientation.
+
 .. ocv:function:: RotatedRect CamShift( InputArray probImage, Rect& window, TermCriteria criteria )
 
-    Finds an object center, size, and orientation.
+.. ocv:pyfunction:: cv2.CamShift(probImage, window, criteria) -> retval, window
+
+.. ocv:cfunction:: int cvCamShift( const CvArr* probImage, CvRect window, CvTermCriteria criteria, CvConnectedComp* comp, CvBox2D* box=NULL )
+.. ocv:pyoldfunction:: cv.CamShift(probImage, window, criteria)-> (int, comp, box)
 
     :param probImage: Back projection of the object histogram. See  :ocv:func:`calcBackProject` .
     
@@ -250,20 +363,24 @@ CamShift
     :param criteria: Stop criteria for the underlying  :ocv:func:`meanShift` .
 
 The function implements the CAMSHIFT object tracking algrorithm
-Bradski98
-.
+[Bradski98]_.
 First, it finds an object center using
 :ocv:func:`meanShift` and then adjusts the window size and finds the optimal rotation. The function returns the rotated rectangle structure that includes the object position, size, and orientation. The next position of the search window can be obtained with ``RotatedRect::boundingRect()`` .
 
 See the OpenCV sample ``camshiftdemo.c`` that tracks colored objects.
 
-.. index:: meanShift
+
 
 meanShift
 -------------
+Finds an object on a back projection image.
+
 .. ocv:function:: int meanShift( InputArray probImage, Rect& window, TermCriteria criteria )
 
-    Finds an object on a back projection image.
+.. ocv:pyfunction:: cv2.meanShift(probImage, window, criteria) -> retval, window
+
+.. ocv:cfunction:: int cvMeanShift( const CvArr* probImage, CvRect window, CvTermCriteria criteria, CvConnectedComp* comp )
+.. ocv:pyoldfunction:: cv.MeanShift(probImage, window, criteria)-> comp
 
     :param probImage: Back projection of the object histogram. See  :ocv:func:`calcBackProject` for details.
        
@@ -274,94 +391,99 @@ meanShift
 The function implements the iterative object search algorithm. It takes the input back projection of an object and the initial position. The mass center in ``window`` of the back projection image is computed and the search window center shifts to the mass center. The procedure is repeated until the specified number of iterations ``criteria.maxCount`` is done or until the window center shifts by less than ``criteria.epsilon`` . The algorithm is used inside
 :ocv:func:`CamShift` and, unlike
 :ocv:func:`CamShift` , the search window size or orientation do not change during the search. You can simply pass the output of
-:ocv:func:`calcBackProject` to this function. But better results can be obtained if you pre-filter the back projection and remove the noise (for example, by retrieving connected components with
+:ocv:func:`calcBackProject` to this function. But better results can be obtained if you pre-filter the back projection and remove the noise. For example, you can do this by retrieving connected components with
 :ocv:func:`findContours` , throwing away contours with small area (
 :ocv:func:`contourArea` ), and rendering the  remaining contours with
-:ocv:func:`drawContours` ).
+:ocv:func:`drawContours` .
 
-.. index:: KalmanFilter
 
-.. _KalmanFilter:
 
 KalmanFilter
 ------------
-.. c:type:: KalmanFilter
+.. ocv:class:: KalmanFilter
 
     Kalman filter class.
 
 The class implements a standard Kalman filter
-http://en.wikipedia.org/wiki/Kalman_filter
-. However, you can modify ``transitionMatrix``, ``controlMatrix``, and ``measurementMatrix`` to get an extended Kalman filter functionality. See the OpenCV sample ``kalman.cpp`` .
+http://en.wikipedia.org/wiki/Kalman_filter, [Welch95]_. However, you can modify ``transitionMatrix``, ``controlMatrix``, and ``measurementMatrix`` to get an extended Kalman filter functionality. See the OpenCV sample ``kalman.cpp`` .
+
 
 
-.. index:: KalmanFilter::KalmanFilter
 
 KalmanFilter::KalmanFilter
 --------------------------
+The constructors.
 
 .. ocv:function:: KalmanFilter::KalmanFilter()
 
-    Creates an empty object that can be initialized later by the function :ocv:func:`KalmanFilter::init`.
-
 .. ocv:function:: KalmanFilter::KalmanFilter(int dynamParams, int measureParams, int controlParams=0, int type=CV_32F)
 
+.. ocv:pyfunction:: cv2.KalmanFilter(dynamParams, measureParams[, controlParams[, type]]) -> <KalmanFilter object>
+
+.. ocv:cfunction:: CvKalman* cvCreateKalman( int dynamParams, int measureParams, int controlParams=0 )
+.. ocv:pyoldfunction:: cv.CreateKalman(dynamParams, measureParams, controlParams=0) -> CvKalman
+
     The full constructor.
     
-    :param dynamParams: The dimensionality of the state.
+    :param dynamParams: Dimensionality of the state.
     
-    :param measureParams: The dimensionality of the measurement.
+    :param measureParams: Dimensionality of the measurement.
     
-    :param controlParams: The dimensionality of the control vector.
+    :param controlParams: Dimensionality of the control vector.
 
-    :param type: Type of the created matrices. Should be ``CV_32F`` or ``CV_64F``.
+    :param type: Type of the created matrices that should be ``CV_32F`` or ``CV_64F``.
 
-.. index:: KalmanFilter::init
+.. note:: In C API when ``CvKalman* kalmanFilter`` structure is not needed anymore, it should be released with ``cvReleaseKalman(&kalmanFilter)``
 
 KalmanFilter::init
 ------------------
+Re-initializes Kalman filter. The previous content is destroyed.
 
 .. ocv:function:: void KalmanFilter::init(int dynamParams, int measureParams, int controlParams=0, int type=CV_32F)
 
-    Re-initializes Kalman filter. The previous content is destroyed.
-
-    :param dynamParams: The dimensionality of the state.
+    :param dynamParams: Dimensionalityensionality of the state.
     
-    :param measureParams: The dimensionality of the measurement.
+    :param measureParams: Dimensionality of the measurement.
     
-    :param controlParams: The dimensionality of the control vector.
-
-    :param type: Type of the created matrices. Should be ``CV_32F`` or ``CV_64F``.
+    :param controlParams: Dimensionality of the control vector.
 
+    :param type: Type of the created matrices that should be ``CV_32F`` or ``CV_64F``.
 
-.. index:: KalmanFilter::predict
 
 KalmanFilter::predict
 ---------------------
+Computes a predicted state.
 
 .. ocv:function:: const Mat& KalmanFilter::predict(const Mat& control=Mat())
 
-    Computes predicted state
+.. ocv:pyfunction:: cv2.KalmanFilter.predict([, control]) -> retval
 
+.. ocv:cfunction:: const CvMat* cvKalmanPredict( CvKalman* kalman, const CvMat* control=NULL)
+.. ocv:pyoldfunction:: cv.KalmanPredict(kalman, control=None) -> cvmat
+
+    :param control: The optional input control
 
-.. index:: KalmanFilter::correct
 
 KalmanFilter::correct
 ---------------------
+Updates the predicted state from the measurement.
 
 .. ocv:function:: const Mat& KalmanFilter::correct(const Mat& measurement)
 
-    Updates the predicted state from the measurement
+.. ocv:pyfunction:: cv2.KalmanFilter.correct(measurement) -> retval
+
+.. ocv:cfunction:: const CvMat* cvKalmanCorrect( CvKalman* kalman, const CvMat* measurement )
+.. ocv:pyoldfunction:: cv.KalmanCorrect(kalman, measurement) -> cvmat
 
+    :param control: The measured system parameters
 
-.. index:: BackgroundSubtractor
 
 BackgroundSubtractor
 --------------------
 
 .. ocv:class: BackgroundSubtractor
 
-The base class for background/foreground segmentation. ::
+Base class for background/foreground segmentation. ::
 
     class BackgroundSubtractor
     {
@@ -375,164 +497,172 @@ The base class for background/foreground segmentation. ::
 The class is only used to define the common interface for the whole family of background/foreground segmentation algorithms.
 
 
-.. index:: BackgroundSubtractor::operator()
-
 BackgroundSubtractor::operator()
 -------------------------------
+Computes a foreground mask.
 
 .. ocv:function:: virtual void BackgroundSubtractor::operator()(InputArray image, OutputArray fgmask, double learningRate=0)
 
-    Computes foreground mask.
-
-    :param image: The next video frame.
+.. ocv:pyfunction:: cv2.BackgroundSubtractor.apply(image[, fgmask[, learningRate]]) -> fgmask
 
-    :param fgmask: The foreground mask as 8-bit binary image.
+    :param image: Next video frame.
 
+    :param fgmask: The output foreground mask as an 8-bit binary image.
 
-.. index:: BackgroundSubtractor::getBackgroundImage
 
 BackgroundSubtractor::getBackgroundImage
 ----------------------------------------
+Computes a background image.
 
 .. ocv:function:: virtual void BackgroundSubtractor::getBackgroundImage(OutputArray backgroundImage) const
 
-This method computes a background image.
-
-
-.. index:: BackgroundSubtractorMOG
+    :param backgroundImage: The output background image.
+    
+.. note:: Sometimes the background image can be very blurry, as it contain the average background statistics.
 
 BackgroundSubtractorMOG
 -----------------------
 
 .. ocv:class: BackgroundSubtractorMOG : public BackgroundSubtractor
 
-    Gaussian Mixture-based Backbround/Foreground Segmentation Algorithm.
+Gaussian Mixture-based Backbround/Foreground Segmentation Algorithm.
+
+The class implements the algorithm described in P. KadewTraKuPong and R. Bowden, *An improved adaptive background mixture model for real-time tracking with shadow detection*, Proc. 2nd European Workshp on Advanced Video-Based Surveillance Systems, 2001: http://personal.ee.surrey.ac.uk/Personal/R.Bowden/publications/avbs01/avbs01.pdf
 
-The class implements the following algorithm: P. KadewTraKuPong and R. Bowden, An improved adaptive background mixture model for real-time tracking with shadow detection, Proc. 2nd European Workshp on Advanced Video-Based Surveillance Systems, 2001: http://personal.ee.surrey.ac.uk/Personal/R.Bowden/publications/avbs01/avbs01.pdf
 
 
-.. index:: BackgroundSubtractorMOG::BackgroundSubtractorMOG
 
 BackgroundSubtractorMOG::BackgroundSubtractorMOG
 ------------------------------------------------
+The contructors
 
 .. ocv:function:: BackgroundSubtractorMOG::BackgroundSubtractorMOG()
 
 .. ocv:function:: BackgroundSubtractorMOG::BackgroundSubtractorMOG(int history, int nmixtures, double backgroundRatio, double noiseSigma=0)
 
-    :param history: The length of the history.
+.. ocv:pyfunction:: cv2.BackgroundSubtractorMOG(history, nmixtures, backgroundRatio[, noiseSigma]) -> <BackgroundSubtractorMOG object>
+
+    :param history: Length of the history.
 
-    :param nmixtures: The number of gaussian mixtures.
+    :param nmixtures: Number of Gaussian mixtures.
 
     :param backgroundRatio: Background ratio.
 
-    :param noiseSigma: The noise strength.
+    :param noiseSigma: Noise strength.
+
+Default constructor sets all parameters to default values.
 
-Default constructor sets all parameters to some default values.
 
 
-.. index:: BackgroundSubtractorMOG::operator()
 
 BackgroundSubtractorMOG::operator()
 -----------------------------------
+Updates the background model and returns the foreground mask
 
 .. ocv:function:: virtual void BackgroundSubtractorMOG::operator()(InputArray image, OutputArray fgmask, double learningRate=0)
 
-    The update operator.
-
-
-.. index:: BackgroundSubtractorMOG::initialize
-
-BackgroundSubtractorMOG::initialize
------------------------------------
-
-.. ocv:function:: virtual void BackgroundSubtractorMOG::initialize(Size frameSize, int frameType) 
-
-    Re-initiaization method.
+Parameters are the same as in ``BackgroundSubtractor::operator()``
 
 
-.. index:: BackgroundSubtractorMOG2
-
 BackgroundSubtractorMOG2
 ------------------------
+Gaussian Mixture-based Backbround/Foreground Segmentation Algorithm.
 
 .. ocv:class: BackgroundSubtractorMOG2 : public BackgroundSubtractor
 
-    Gaussian Mixture-based Backbround/Foreground Segmentation Algorithm.
-
-The class implements the Gaussian mixture model background subtraction from: 
-
-  * Z.Zivkovic, Improved adaptive Gausian mixture model for background subtraction, International Conference Pattern Recognition, UK, August, 2004, http://www.zoranz.net/Publications/zivkovic2004ICPR.pdf. The code is very fast and performs also shadow detection. Number of Gausssian components is adapted per pixel.
+    Here are important members of the class that control the algorithm, which you can set after constructing the class instance:
 
-  * Z.Zivkovic, F. van der Heijden, Efficient Adaptive Density Estimapion per Image Pixel for the Task of Background Subtraction, Pattern Recognition Letters, vol. 27, no. 7, pages 773-780, 2006. The algorithm similar to the standard Stauffer&Grimson algorithm with additional selection of the number of the Gaussian components based on: Z.Zivkovic, F.van der Heijden, Recursive unsupervised learning of finite mixture models, IEEE Trans. on Pattern Analysis and Machine Intelligence, vol.26, no.5, pages 651-656, 2004.
+    :ocv:member:: nmixtures
+    
+        Maximum allowed number of mixture comonents. Actual number is determined dynamically per pixel.
 
+    :ocv:member:: backgroundRatio
+    
+        Threshold defining whether the component is significant enough to be included into the background model ( corresponds to ``TB=1-cf`` from the paper??which paper??). ``cf=0.1 => TB=0.9`` is default. For ``alpha=0.001``, it means that the mode should exist for approximately 105 frames before it is considered foreground.
 
-.. index:: BackgroundSubtractorMOG2::BackgroundSubtractorMOG2
+    :ocv:member:: varThresholdGen
+    
+        Threshold for the squared Mahalanobis distance that helps decide when a sample is close to the existing components (corresponds to ``Tg``). If it is not close to any component, a new component is generated. ``3 sigma => Tg=3*3=9`` is default. A smaller ``Tg`` value generates more components. A higher ``Tg`` value may result in a small number of components but they can grow too large.
 
-BackgroundSubtractorMOG2::BackgroundSubtractorMOG2
---------------------------------------------------
+    :ocv:member:: fVarInit
+    
+        Initial variance for the newly generated components. It affects the speed of adaptation. The parameter value is based on your estimate of the typical standard deviation from the images. OpenCV uses 15 as a reasonable value.
 
-.. ocv:function:: BackgroundSubtractorMOG2::BackgroundSubtractorMOG2()
+    :ocv:member::
+    
+        fVarMin Parameter used to further control the variance.
 
-.. ocv:function:: BackgroundSubtractorMOG2::BackgroundSubtractorMOG2(int history, float varThreshold, bool bShadowDetection=1)
+    :ocv:member::
+    
+        fVarMax Parameter used to further control the variance.
 
-    :param history: The length of the history.
+    :ocv:member:: fCT
+        
+        Complexity reduction parameter. This parameter defines the number of samples needed to accept to prove the component exists. ``CT=0.05`` is a default value for all the samples. By setting ``CT=0`` you get an algorithm very similar to the standard Stauffer&Grimson algorithm.
 
-    :param varThreshold: Threshold on the squared Mahalanobis distance to decide if it is well described by the background model or not. Related to Cthr from the paper. This does not influence the update of the background. A typical value could be 4 sigma and that is varThreshold=4*4=16; Corresponds to Tb in the paper.
+    :param nShadowDetection
+    
+        The value for marking shadow pixels in the output foreground mask. Default value is 127.
 
-    :param bShadowDetection: Do shadow detection (true) or not (false).
+    :param fTau
+        
+        Shadow threshold. The shadow is detected if the pixel is a darker version of the background. ``Tau`` is a threshold defining how much darker the shadow can be. ``Tau= 0.5`` means that if a pixel is more than twice darker then it is not shadow. See Prati,Mikic,Trivedi,Cucchiarra, *Detecting Moving Shadows...*, IEEE PAMI,2003.
 
 
-The class has an important public parameter:
+The class implements the Gaussian mixture model background subtraction described in:
 
-    :param nmixtures: The maximum allowed number of mixture comonents. Actual number is determined dynamically per pixel.
+  * Z.Zivkovic, *Improved adaptive Gausian mixture model for background subtraction*, International Conference Pattern Recognition, UK, August, 2004, http://www.zoranz.net/Publications/zivkovic2004ICPR.pdf. The code is very fast and performs also shadow detection. Number of Gausssian components is adapted per pixel.
 
-Also the class has several less important parameters - things you might change but be carefull:
+  * Z.Zivkovic, F. van der Heijden, *Efficient Adaptive Density Estimapion per Image Pixel for the Task of Background Subtraction*, Pattern Recognition Letters, vol. 27, no. 7, pages 773-780, 2006. The algorithm similar to the standard Stauffer&Grimson algorithm with additional selection of the number of the Gaussian components based on: Z.Zivkovic, F.van der Heijden, Recursive unsupervised learning of finite mixture models, IEEE Trans. on Pattern Analysis and Machine Intelligence, vol.26, no.5, pages 651-656, 2004.
 
-    :param backgroundRatio: Corresponds to fTB=1-cf from the paper. TB - threshold when the component becomes significant enough to be included into the background model. It is the TB=1-cf from the paper. Default is cf=0.1 => TB=0.9. For alpha=0.001 it means that the mode should exist for approximately 105 frames before it is considered foreground.
 
-    :param varThresholdGen: Correspondts to Tg - threshold on the squared Mahalanobis distance to decide when a sample is close to the existing components. If it is not close to any a new component will be generated. Default is 3 sigma => Tg=3*3=9. Smaller Tg leads to more generated components and higher Tg might make lead to small number of components but they can grow too large.
+BackgroundSubtractorMOG2::BackgroundSubtractorMOG2
+--------------------------------------------------
+The constructors.
 
-    :param fVarInit: Initial variance for the newly generated components. It will will influence the speed of adaptation. A good guess should be made. A simple way is to estimate the typical standard deviation from the images. OpenCV uses here 15 as a reasonable value.
+.. ocv:function:: BackgroundSubtractorMOG2::BackgroundSubtractorMOG2()
 
-    :param fVarMin: Used to further control the variance.
+.. ocv:function:: BackgroundSubtractorMOG2::BackgroundSubtractorMOG2(int history, float varThreshold, bool bShadowDetection=1)
 
-    :param fVarMax: Used to further control the variance.
+    :param history: Length of the history.
 
-    :param fCT: Complexity reduction prior. This is related to the number of samples needed to accept that a component actually exists. Default is CT=0.05 of all the samples. By setting CT=0 you get the standard Stauffer&Grimson algorithm (maybe not exact but very similar).
+    :param varThreshold: Threshold on the squared Mahalanobis distance to decide whether it is well described by the background model (see Cthr??). This parameter does not affect the background update. A typical value could be 4 sigma, that is, ``varThreshold=4*4=16;`` (see Tb??).
 
-    :param nShadowDetection: This value is inserted as the shadow detection result. Default value is 127.
+    :param bShadowDetection: Parameter defining whether shadow detection should be enabled (``true`` or ``false``).
 
-    :param fTau: Shadow threshold. The shadow is detected if the pixel is darker version of the background. Tau is a threshold on how much darker the shadow can be. Tau= 0.5 means that if pixel is more than 2 times darker then it is not shadow. See: Prati,Mikic,Trivedi,Cucchiarra,"Detecting Moving Shadows...",IEEE PAMI,2003.
-                 
 
-.. index:: BackgroundSubtractorMOG2::operator()
 
 BackgroundSubtractorMOG2::operator()
 -----------------------------------
+Updates the background model and computes the foreground mask
 
 .. ocv:function:: virtual void BackgroundSubtractorMOG2::operator()(InputArray image, OutputArray fgmask, double learningRate=-1)
 
-    The update operator.
+    See ``BackgroundSubtractor::operator ()``.
 
 
-.. index:: BackgroundSubtractorMOG2::initialize
 
-BackgroundSubtractorMOG2::initialize
-------------------------------------
+BackgroundSubtractorMOG2::getBackgroundImage
+--------------------------------------------
+Returns background image
 
-.. ocv:function:: virtual void BackgroundSubtractorMOG2::initialize(Size frameSize, int frameType)
+.. ocv:function:: virtual void BackgroundSubtractorMOG2::getBackgroundImage(OutputArray backgroundImage)
 
-    Re-initiaization method.
+See :ocv:func:`BackgroundSubtractor::getBackgroundImage`.
 
 
-.. index:: BackgroundSubtractorMOG2::getBackgroundImage
+.. [Bouguet00] Jean-Yves Bouguet. Pyramidal Implementation of the Lucas Kanade Feature Tracker.
 
-BackgroundSubtractorMOG2::getBackgroundImage
---------------------------------------------
+.. [Bradski98] Bradski, G.R. "Computer Vision Face Tracking for Use in a Perceptual User Interface", Intel, 1998
+
+.. [Bradski00] Davis, J.W. and Bradski, G.R. “Motion Segmentation and Pose Recognition with Motion History Gradients”, WACV00, 2000
+
+.. [Davis97] Davis, J.W. and Bobick, A.F. “The Representation and Recognition of Action Using Temporal Templates”, CVPR97, 1997
 
-.. ocv:function:: virtual void BackgroundSubtractorMOG2::getBackgroundImage(OutputArray backgroundImage) const
+.. [Farneback2003] Gunnar Farneback, Two-frame motion estimation based on polynomial expansion, Lecture Notes in Computer Science, 2003, (2749), , 363-370. 
 
-    Computes a background image which are the mean of all background gaussians.
+.. [Horn81] Berthold K.P. Horn and Brian G. Schunck. Determining Optical Flow. Artificial Intelligence, 17, pp. 185-203, 1981.
 
+.. [Lucas81] Lucas, B., and Kanade, T. An Iterative Image Registration Technique with an Application to Stereo Vision, Proc. of 7th International Joint Conference on Artificial Intelligence (IJCAI), pp. 674-679.
 
+.. [Welch95] Greg Welch and Gary Bishop “An Introduction to the Kalman Filter”, 1995
index 9762a7d..b1a5101 100644 (file)
@@ -67,7 +67,9 @@ void cv::calcOpticalFlowPyrLK( InputArray _prevImg, InputArray _nextImg,
     CV_Assert( prevImg.size() == nextImg.size() &&
         prevImg.type() == nextImg.type() );
 
-    size_t npoints = prevPtsMat.total();
+    int npoints;
+    CV_Assert( (npoints = prevPtsMat.checkVector(2, CV_32F, true)) >= 0 );
+    
     if( npoints == 0 )
     {
         _nextPts.release();
@@ -76,24 +78,31 @@ void cv::calcOpticalFlowPyrLK( InputArray _prevImg, InputArray _nextImg,
         return;
     }
     
-    CV_Assert( prevPtsMat.isContinuous() );
-    const Point2f* prevPts = (const Point2f*)prevPtsMat.data;
+    if( !(flags & OPTFLOW_USE_INITIAL_FLOW) )
+        _nextPts.create(prevPtsMat.size(), prevPtsMat.type(), -1, true);
     
-    _nextPts.create((int)npoints, 1, prevPtsMat.type(), -1, true);
     Mat nextPtsMat = _nextPts.getMat();
-    CV_Assert( nextPtsMat.isContinuous() );
+    CV_Assert( nextPtsMat.checkVector(2, CV_32F, true) == npoints );
+    
+    const Point2f* prevPts = (const Point2f*)prevPtsMat.data;
     Point2f* nextPts = (Point2f*)nextPtsMat.data;
     
     _status.create((int)npoints, 1, CV_8U, -1, true);
-    Mat statusMat = _status.getMat();
+    Mat statusMat = _status.getMat(), errMat;
     CV_Assert( statusMat.isContinuous() );
     uchar* status = statusMat.data;
-    for( size_t i = 0; i < npoints; i++ )
+    float* err = 0;
+    
+    for( int i = 0; i < npoints; i++ )
         status[i] = true;
-    _err.create((int)npoints, 1, CV_32F, -1, true);
-    Mat errMat = _err.getMat();
-    CV_Assert( errMat.isContinuous() );
-    float* err = (float*)errMat.data;
+    
+    if( _err.needed() )
+    {
+        _err.create((int)npoints, 1, CV_32F, -1, true);
+        errMat = _err.getMat();
+        CV_Assert( errMat.isContinuous() );
+        err = (float*)errMat.data;
+    }
 
     vector<Mat> prevPyr, nextPyr;
 
@@ -194,7 +203,7 @@ void cv::calcOpticalFlowPyrLK( InputArray _prevImg, InputArray _nextImg,
         copyMakeBorder( derivJ, _derivJ, winSize.height, winSize.height,
             winSize.width, winSize.width, BORDER_CONSTANT );*/
 
-        for( size_t ptidx = 0; ptidx < npoints; ptidx++ )
+        for( int ptidx = 0; ptidx < npoints; ptidx++ )
         {
             Point2f prevPt = prevPts[ptidx]*(float)(1./(1 << level));
             Point2f nextPt;
@@ -274,7 +283,8 @@ void cv::calcOpticalFlowPyrLK( InputArray _prevImg, InputArray _nextImg,
             double D = A11*A22 - A12*A12;
             double minEig = (A22 + A11 - std::sqrt((A11-A22)*(A11-A22) +
                 4.*A12*A12))/(2*winSize.width*winSize.height);
-            err[ptidx] = (float)minEig;
+            if( err )
+                err[ptidx] = (float)minEig;
 
             if( D < DBL_EPSILON )
             {