1
0
mirror of https://github.com/opencv/opencv.git synced 2026-07-31 00:03:03 +04:00

reference manuals merge is complete!

This commit is contained in:
Vadim Pisarevsky
2011-06-29 17:21:43 +00:00
parent 7f38aa60a2
commit 9638448c81
147 changed files with 5790 additions and 52736 deletions
@@ -152,8 +152,7 @@ Finds the camera intrinsic and extrinsic parameters from several views of a cali
* **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,
@@ -179,13 +178,7 @@ The function returns the final re-projection error.
.. note::
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
: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
:ocv:func:`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` .
.. seealso::
:ocv:func:`FindChessboardCorners`,
@@ -483,6 +476,8 @@ 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() )
.. 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.
:param patternSize: Number of circles per a grid row and column ``( patternSize = Size(points_per_row, points_per_colum) )`` .
@@ -757,7 +752,24 @@ Computes an optimal affine transformation between two 3D point sets.
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
-----------------------------
@@ -786,8 +798,8 @@ Returns the new camera matrix based on the free scaling parameter.
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
:ocv:func:`InitUndistortRectifyMap` to produce the maps for
:ocv:func:`Remap` .
:ocv:func:`initUndistortRectifyMap` to produce the maps for
:ocv:func:`remap` .
@@ -1047,6 +1059,8 @@ The constructors.
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()
-----------------------
Computes disparity using the BM algorithm for a rectified stereo pair.
@@ -1299,7 +1313,7 @@ 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).
@@ -1338,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
:ocv:func:`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.
@@ -1369,12 +1383,14 @@ stereoRectifyUncalibrated
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
: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
.
[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` .
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/
.. [Hartley99] Hartley, R.I., “Theory and Practice of Projective Rectification”. IJCV 35 2, pp 115-127 (1999)
.. [Zhang2000] Z. Zhang. A Flexible New Technique for Camera Calibration. IEEE Transactions on Pattern Analysis and Machine Intelligence, 22(11):1330-1334, 2000.
+2 -1
View File
@@ -29,7 +29,7 @@ Finds centers of clusters and groups input samples around the clusters.
* **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.
@@ -76,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
+3
View 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
+54 -1
View File
@@ -91,6 +91,9 @@ Draws a simple or thick elliptic arc or fills an ellipse sector.
.. 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.
:param center: Center of the ellipse.
@@ -103,7 +106,7 @@ Draws a simple or thick elliptic arc or fills an ellipse sector.
: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.
@@ -264,6 +267,54 @@ That is, the following code renders some text, the tight box surrounding it, and
Scalar::all(255), thickness, 8);
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
--------
@@ -428,6 +479,8 @@ Draws a text string.
: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.
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -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.
+70 -83
View File
@@ -488,9 +488,9 @@ Performs the per-element comparison of two arrays or an array and scalar value.
.. 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)
: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)
: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`` .
@@ -647,24 +647,6 @@ The function returns the number of non-zero elements in ``mtx`` :
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.
cvarrToMat
----------
Converts ``CvMat``, ``IplImage`` , or ``CvMatND`` to ``Mat``.
@@ -1135,25 +1117,6 @@ To extract a channel from a new-style matrix, use
fastAtan2
---------
Calculates the angle of a 2D vector in degrees.
.. ocv:function:: float fastAtan2(float y, float x)
.. ocv:pyfunction:: cv2.fastAtan2(y, x) -> retval
.. ocv:cfunction:: float cvFastArctan(float y, float x)
.. ocv:pyoldfunction:: cv.FastArctan(y, x)-> float
: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.
flip
--------
Flips a 2D array around vertical, horizontal, or both axes.
@@ -1553,7 +1516,9 @@ 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* mat)
.. 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.
@@ -1561,7 +1526,7 @@ Calculates the Mahalanobis distance between two vectors.
: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::
@@ -2217,6 +2182,8 @@ Performs Principal Component Analysis of the supplied dataset.
.. ocv:function:: PCA& PCA::operator()(InputArray data, InputArray mean, int flags, int maxComponents=0)
.. ocv:pyfunction:: cv2.PCACompute(data[, mean[, eigenvectors[, maxComponents]]]) -> mean, eigenvectors
:param data: Input samples stored as the matrix rows or as the matrix columns.
:param mean: Optional mean value. If the matrix is empty ( ``Mat()`` ), the mean is computed from the data.
@@ -2243,6 +2210,8 @@ Projects vector(s) to the principal component subspace.
.. ocv:function:: void PCA::project(InputArray vec, OutputArray result) const
.. 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.
:param result: Output vectors. In case of ``CV_PCA_DATA_AS_COLS`` , the output matrix has as many columns as the number of input vectors. This means that ``result.cols==vec.cols`` and the number of rows match the number of principal components (for example, ``maxComponents`` parameter passed to the constructor).
@@ -2259,6 +2228,8 @@ Reconstructs vectors from their PC projections.
.. ocv:function:: void PCA::backProject(InputArray vec, OutputArray result) const
.. 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.
:param result: Reconstructed vectors. The layout and size are the same as of ``PCA::project`` input vectors.
@@ -2719,35 +2690,6 @@ The second variant of the function is more convenient to use with
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`
scaleAdd
--------
Calculates the sum of a scaled array and another array.
@@ -3161,7 +3103,7 @@ The constructors.
.. ocv:function:: SVD::SVD( InputArray A, int flags=0 )
:param A: Decomposed matrix.
:param src: Decomposed matrix.
:param flags: Operation flags.
@@ -3175,14 +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 )
.. ocv:function:: SVD& SVD::operator()( InputArray src, int flags=0 )
:param A: Decomposed matrix.
:param src: Decomposed matrix.
:param flags: Operation flags.
@@ -3196,35 +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 )
:param A: Left-hand-side matrix.
:param src: 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 x ) const
.. ocv:function:: void SVD::backSubst( InputArray rhs, OutputArray dst ) const
: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 ()` .
.. 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:cfunction:: void cvSVBkSb( const CvArr* w, const CvArr* u, const CvArr* v, const CvArr* rhs, CvArr* dst, int flags)
.. ocv:pyoldfunction:: cv.SVBkSb(w, u, v, rhs, dst, flags)-> None
: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:
@@ -3234,7 +3221,7 @@ 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.
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

@@ -67,6 +67,106 @@ The generic function ``deallocate`` deallocates the buffer allocated with
fastAtan2
---------
Calculates the angle of a 2D vector in degrees.
.. ocv:function:: float fastAtan2(float y, float x)
.. ocv:pyfunction:: cv2.fastAtan2(y, x) -> retval
.. ocv:cfunction:: float cvFastArctan(float y, float x)
.. ocv:pyoldfunction:: cv.FastArctan(y, x)-> float
: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.
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
---------
Checks a condition at runtime and throws exception if it fails
@@ -145,6 +245,7 @@ fastMalloc
Allocates an aligned memory buffer.
.. ocv:function:: void* fastMalloc(size_t size)
.. ocv:cfunction:: void* cvAlloc( size_t size )
:param size: Allocated buffer size.
@@ -157,13 +258,13 @@ fastFree
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.
format
@@ -249,6 +350,32 @@ Returns the number of CPU ticks.
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.
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
-----------------
@@ -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.
@@ -12,57 +12,60 @@ KeyPoint
--------
.. ocv:class:: KeyPoint
Data structure for salient point detectors. ::
Data structure for salient point detectors.
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);
.. 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
// 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);
KeyPoint::KeyPoint
------------------
The keypoint constructors
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)
};
.. ocv:function:: KeyPoint::KeyPoint()
// 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);
.. 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
..
FeatureDetector
---------------
@@ -3,8 +3,6 @@ Feature Detection and Description
.. highlight:: cpp
FAST
--------
Detects corners using the FAST algorithm
@@ -52,37 +50,47 @@ 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);
.. [Agrawal08] Agrawal, M. and Konolige, K. and Blas, M.R. "CenSurE: Center Surround Extremas for Realtime Feature Detection and Matching", ECCV08, 2008
// finds keypoints in an image
void operator()(const Mat& image, vector<KeyPoint>& keypoints) const;
};
StarDetector::StarDetector
--------------------------
The Star Detector constructor
The class implements a modified version of the ``CenSurE`` keypoint detector described in
[Agrawal08].
.. 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>
: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)
SIFT
@@ -177,38 +185,82 @@ 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;
};
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.
.. 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>
: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.
ORB
+3 -1
View 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"
@@ -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`.
.. [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.
+2 -1
View 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.
@@ -124,58 +124,10 @@ VideoCapture
------------
.. ocv:class:: VideoCapture
Class for video capturing from video files or cameras ::
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: ::
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);
// starts streaming from the specified camera by its id
virtual bool open(int device);
// 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,6 +154,9 @@ The class provides C++ video capturing API. Here is how the class can be used: :
}
.. note:: In C API the black-box structure ``CvCapture`` is used instead of ``VideoCapture``.
VideoCapture::VideoCapture
------------------------------
VideoCapture constructors.
@@ -212,20 +167,131 @@ VideoCapture constructors.
.. ocv:function:: VideoCapture::VideoCapture(int device)
.. 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).
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
---------------------
Returns the specified ``VideoCapture`` property
.. ocv:function:: double VideoCapture::get(int property_id)
.. ocv:function:: double VideoCapture::get(int propId)
.. ocv:pyfunction:: cv2.VideoCapture.get(propId) -> retval
:param property_id: Property identifier. It can be one of the following:
.. ocv:cfunction:: double cvGetCaptureProperty( CvCapture* capture, int propId )
.. ocv:pyoldfunction:: cv.GetCaptureProperty(capture, propId)->double
: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.
@@ -272,11 +338,14 @@ VideoCapture::set
---------------------
Sets a property in the ``VideoCapture``.
.. ocv:function:: bool VideoCapture::set(int property_id, double value)
.. ocv:function:: bool VideoCapture::set(int propertyId, double value)
.. ocv:pyfunction:: cv2.VideoCapture.set(propId, value) -> retval
:param property_id: Property identifier. It can be one of the following:
.. 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.
@@ -318,43 +387,90 @@ Sets a property in the ``VideoCapture``.
:param value: Value of the property.
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);
VideoWriter::VideoWriter
------------------------
VideoWriter constructors
// returns true if the writer has been initialized successfully
virtual bool isOpened() const;
.. ocv:function:: VideoWriter::VideoWriter()
.. ocv:function:: VideoWriter::VideoWriter(const string& filename, int fourcc, double fps, Size frameSize, bool isColor=true)
// writes the next video frame to the stream
virtual VideoWriter& operator << (const Mat& image);
.. ocv:pyfunction:: cv2.VideoWriter([filename, fourcc, fps, frameSize[, isColor]]) -> <VideoWriter object>
protected:
...
};
.. 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
For more detailed description see http://opencv.willowgarage.com/wiki/documentation/cpp/highgui/VideoWriter
..
.. 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.
+52
View File
@@ -110,6 +110,7 @@ You can call :ocv:func:`destroyWindow` or :ocv:func:`destroyAllWindows` to close
By default, ``flags == CV_WINDOW_AUTOSIZE | CV_WINDOW_KEEPRATIO | CV_GUI_EXPANDED``
destroyWindow
-------------
Destroys a window.
@@ -134,9 +135,60 @@ 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.
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
------------------
Sets the trackbar position.
+10 -5
View File
@@ -7,7 +7,7 @@ Feature Detection
Canny
---------
Finds edges in an image using the Canny algorithm.
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 )
@@ -242,7 +242,7 @@ Determines strong corners on an image.
: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
@@ -287,7 +287,7 @@ Finds circles in a grayscale image using the Hough transform.
: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.
@@ -420,8 +420,7 @@ Finds line segments in a binary image using the probabilistic Hough transform.
: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
@@ -524,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 7177 (1990)
+118 -2
View File
@@ -1044,10 +1044,14 @@ getStructuringElement
-------------------------
Returns a structuring element of the specified size and shape for morphological operations.
.. ocv:function:: Mat getStructuringElement(int shape, Size esize, Point anchor=Point(-1,-1))
.. 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 )
.. ocv:pyoldfunction:: cv.CreateStructuringElementEx(cols, rows, anchorX, anchorY, shape, values=None)-> kernel
:param shape: Element shape that could be one of the following:
* **MORPH_RECT** - a rectangular structuring element:
@@ -1063,10 +1067,22 @@ Returns a structuring element of the specified size and shape for morphological
.. 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 further passed to
:ocv:func:`createMorphologyFilter`,
@@ -1074,6 +1090,7 @@ The function constructs and returns the structuring element that can be further
:ocv:func:`dilate` or
:ocv:func:`morphologyEx` . But you can also construct an arbitrary binary mask yourself and use it as the structuring element.
.. note:: When using OpenCV 1.x C API, the created structuring element ``IplConvKernel* element`` must be released in the end using ``cvReleaseStructuringElement(&element)``.
medianBlur
@@ -1277,6 +1294,54 @@ The function performs the upsampling step of the Gaussian pyramid construction
:ocv:func:`pyrDown` multiplied by 4.
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
---------------
@@ -1313,6 +1378,57 @@ The function applies a separable linear filter to the image. That is, first, eve
:ocv:func:`blur`
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
---------
@@ -191,6 +191,8 @@ 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.
@@ -199,6 +201,8 @@ Calculates an affine matrix of 2D rotation.
:param scale: Isotropic scale factor.
:param mapMatrix: The output affine transformation, 2x3 floating-point matrix.
The function calculates the following matrix:
.. math::
@@ -246,6 +250,53 @@ The result is also a
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
@@ -376,6 +427,9 @@ Applies an affine transformation to an image.
.. 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.
:param dst: Destination image that has the size ``dsize`` and the same type as ``src`` .
@@ -408,6 +462,7 @@ See Also:
:ocv:func:`transform`
.. note:: ``cvGetQuadrangleSubPix`` is similar to ``cvWarpAffine``, but the outliers are extrapolated using replication border mode.
warpPerspective
-------------------
@@ -464,13 +519,16 @@ 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}` .
@@ -574,8 +632,8 @@ Transforms an image to compensate for lens distortion.
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).
+296 -3
View File
@@ -250,9 +250,7 @@ Computes the "minimal work" distance between two weighted point configurations.
: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.
equalizeHist
@@ -263,6 +261,8 @@ 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.
:param dst: Destination image of the same size and type as ``src`` .
@@ -289,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 Movers 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
@@ -421,7 +421,9 @@ Calculates the distance to the closest zero pixel for each pixel of the source i
: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.
@@ -430,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,
@@ -608,7 +609,7 @@ Restores the selected region in an image using the region neighborhood.
* **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
@@ -765,7 +766,7 @@ Performs a marker-based image segmentation using the watershed algrorithm.
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
@@ -827,3 +828,11 @@ Runs the GrabCut algorithm.
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 344371 (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)
+331
View File
@@ -0,0 +1,331 @@
Planar Subdivisions (C API)
============================
.. highlight:: c
CvSubdiv2D
----------
.. ocv:struct:: CvSubdiv2D
Planar subdivision.
::
#define CV_SUBDIV2D_FIELDS() \
CV_GRAPH_FIELDS() \
int quad_edges; \
int is_geometry_valid; \
CvSubdiv2DEdge recent_edge; \
CvPoint2D32f topleft; \
CvPoint2D32f bottomright;
typedef struct CvSubdiv2D
{
CV_SUBDIV2D_FIELDS()
}
CvSubdiv2D;
..
Planar subdivision is the subdivision of a plane into a set of
non-overlapped regions (facets) that cover the whole plane. The above
structure describes a subdivision built on a 2d point set, where the points
are linked together and form a planar graph, which, together with a few
edges connecting the exterior subdivision points (namely, convex hull points)
with infinity, subdivides a plane into facets by its edges.
For every subdivision there exists a dual subdivision in which facets and
points (subdivision vertices) swap their roles, that is, a facet is
treated as a vertex (called a virtual point below) of the dual subdivision and
the original subdivision vertices become facets. On the picture below
original subdivision is marked with solid lines and dual subdivision
with dotted lines.
.. image:: pics/subdiv.png
OpenCV subdivides a plane into triangles using Delaunay's
algorithm. Subdivision is built iteratively starting from a dummy
triangle that includes all the subdivision points for sure. In this
case the dual subdivision is a Voronoi diagram of the input 2d point set. The
subdivisions can be used for the 3d piece-wise transformation of a plane,
morphing, fast location of points on the plane, building special graphs
(such as NNG,RNG) and so forth.
CvQuadEdge2D
------------
.. ocv:struct:: CvQuadEdge2D
Quad-edge of planar subdivision.
::
/* one of edges within quad-edge, lower 2 bits is index (0..3)
and upper bits are quad-edge pointer */
typedef long CvSubdiv2DEdge;
/* quad-edge structure fields */
#define CV_QUADEDGE2D_FIELDS() \
int flags; \
struct CvSubdiv2DPoint* pt[4]; \
CvSubdiv2DEdge next[4];
typedef struct CvQuadEdge2D
{
CV_QUADEDGE2D_FIELDS()
}
CvQuadEdge2D;
..
Quad-edge is a basic element of subdivision containing four edges (e, eRot, reversed e and reversed eRot):
.. image:: pics/quadedge.png
CvSubdiv2DPoint
---------------
.. ocv:struct:: CvSubdiv2DPoint
Point of original or dual subdivision.
::
#define CV_SUBDIV2D_POINT_FIELDS()\
int flags; \
CvSubdiv2DEdge first; \
CvPoint2D32f pt; \
int id;
#define CV_SUBDIV2D_VIRTUAL_POINT_FLAG (1 << 30)
typedef struct CvSubdiv2DPoint
{
CV_SUBDIV2D_POINT_FIELDS()
}
CvSubdiv2DPoint;
..
* id
This integer can be used to index auxillary data associated with each vertex of the planar subdivision
CalcSubdivVoronoi2D
-------------------
Calculates the coordinates of Voronoi diagram cells.
.. ocv:cfunction:: void cvCalcSubdivVoronoi2D( CvSubdiv2D* subdiv )
.. ocv:pyoldfunction:: cv.CalcSubdivVoronoi2D(subdiv)-> None
:param subdiv: Delaunay subdivision, in which all the points are already added
The function calculates the coordinates
of virtual points. All virtual points corresponding to some vertex of the
original subdivision form (when connected together) a boundary of the Voronoi
cell at that point.
ClearSubdivVoronoi2D
--------------------
.. ocv:cfunction:: void cvClearSubdivVoronoi2D( CvSubdiv2D* subdiv )
.. ocv:pyoldfunction:: cv.ClearSubdivVoronoi2D(subdiv)-> None
Removes all virtual points.
:param subdiv: Delaunay subdivision
The function removes all of the virtual points. It
is called internally in
:ref:`CalcSubdivVoronoi2D`
if the subdivision
was modified after previous call to the function.
CreateSubdivDelaunay2D
----------------------
Creates an empty Delaunay triangulation.
.. ocv:cfunction:: CvSubdiv2D* cvCreateSubdivDelaunay2D( CvRect rect, CvMemStorage* storage )
.. ocv:pyoldfunction:: cv.CreateSubdivDelaunay2D(rect, storage)-> emptyDelaunayTriangulation
:param rect: Rectangle that includes all of the 2d points that are to be added to the subdivision
:param storage: Container for subdivision
The function creates an empty Delaunay
subdivision, where 2d points can be added using the function
:ref:`SubdivDelaunay2DInsert`
. All of the points to be added must be within
the specified rectangle, otherwise a runtime error will be raised.
Note that the triangulation is a single large triangle that covers the given rectangle. Hence the three vertices of this triangle are outside the rectangle
``rect``
.
FindNearestPoint2D
------------------
Finds the closest subdivision vertex to the given point.
.. ocv:cfunction:: CvSubdiv2DPoint* cvFindNearestPoint2D( CvSubdiv2D* subdiv, CvPoint2D32f pt )
.. ocv:pyoldfunction:: cv.FindNearestPoint2D(subdiv, pt)-> point
:param subdiv: Delaunay or another subdivision
:param pt: Input point
The function is another function that
locates the input point within the subdivision. It finds the subdivision vertex that
is the closest to the input point. It is not necessarily one of vertices
of the facet containing the input point, though the facet (located using
:ref:`Subdiv2DLocate`
) is used as a starting
point. The function returns a pointer to the found subdivision vertex.
Subdiv2DEdgeDst
---------------
Returns the edge destination.
.. ocv:cfunction:: CvSubdiv2DPoint* cvSubdiv2DEdgeDst( CvSubdiv2DEdge edge )
.. ocv:pyoldfunction:: cv.Subdiv2DEdgeDst(edge)-> point
:param edge: Subdivision edge (not a quad-edge)
The function returns the edge destination. The
returned pointer may be NULL if the edge is from dual subdivision and
the virtual point coordinates are not calculated yet. The virtual points
can be calculated using the function
:ref:`CalcSubdivVoronoi2D`
.
Subdiv2DGetEdge
---------------
Returns one of the edges related to the given edge.
.. ocv:cfunction:: CvSubdiv2DEdge cvSubdiv2DGetEdge( CvSubdiv2DEdge edge, CvNextEdgeType type )
.. ocv:pyoldfunction:: cv.Subdiv2DGetEdge(edge, type)-> CvSubdiv2DEdge
:param edge: Subdivision edge (not a quad-edge)
:param type: Specifies which of the related edges to return, one of the following:
* **CV_NEXT_AROUND_ORG** next around the edge origin ( ``eOnext`` on the picture below if ``e`` is the input edge)
* **CV_NEXT_AROUND_DST** next around the edge vertex ( ``eDnext`` )
* **CV_PREV_AROUND_ORG** previous around the edge origin (reversed ``eRnext`` )
* **CV_PREV_AROUND_DST** previous around the edge destination (reversed ``eLnext`` )
* **CV_NEXT_AROUND_LEFT** next around the left facet ( ``eLnext`` )
* **CV_NEXT_AROUND_RIGHT** next around the right facet ( ``eRnext`` )
* **CV_PREV_AROUND_LEFT** previous around the left facet (reversed ``eOnext`` )
* **CV_PREV_AROUND_RIGHT** previous around the right facet (reversed ``eDnext`` )
.. image:: ../pics/quadedge.png
The function returns one of the edges related to the input edge.
Subdiv2DNextEdge
----------------
Returns next edge around the edge origin
.. ocv:cfunction:: CvSubdiv2DEdge cvSubdiv2DNextEdge( CvSubdiv2DEdge edge )
.. ocv:pyoldfunction:: cv.Subdiv2DNextEdge(edge)-> CvSubdiv2DEdge
:param edge: Subdivision edge (not a quad-edge)
.. image:: ../pics/quadedge.png
The function returns the next edge around the edge origin:
``eOnext``
on the picture above if
``e``
is the input edge)
Subdiv2DLocate
--------------
Returns the location of a point within a Delaunay triangulation.
.. ocv:cfunction:: CvSubdiv2DPointLocation cvSubdiv2DLocate( CvSubdiv2D* subdiv, CvPoint2D32f pt, CvSubdiv2DEdge* edge, CvSubdiv2DPoint** vertex=NULL )
.. ocv:pyoldfunction:: cv.Subdiv2DLocate(subdiv, pt) -> (loc, where)
:param subdiv: Delaunay or another subdivision
:param pt: The point to locate
:param edge: The output edge the point falls onto or right to
:param vertex: Optional output vertex double pointer the input point coinsides with
The function locates the input point within the subdivision. There are 5 cases:
*
The point falls into some facet. The function returns
``CV_PTLOC_INSIDE``
and
``*edge``
will contain one of edges of the facet.
*
The point falls onto the edge. The function returns
``CV_PTLOC_ON_EDGE``
and
``*edge``
will contain this edge.
*
The point coincides with one of the subdivision vertices. The function returns
``CV_PTLOC_VERTEX``
and
``*vertex``
will contain a pointer to the vertex.
*
The point is outside the subdivsion reference rectangle. The function returns
``CV_PTLOC_OUTSIDE_RECT``
and no pointers are filled.
*
One of input arguments is invalid. A runtime error is raised or, if silent or "parent" error processing mode is selected,
``CV_PTLOC_ERROR``
is returnd.
Subdiv2DRotateEdge
------------------
Returns another edge of the same quad-edge.
.. ocv:cfunction:: CvSubdiv2DEdge cvSubdiv2DRotateEdge( CvSubdiv2DEdge edge, int rotate )
.. ocv:pyoldfunction:: cv.Subdiv2DRotateEdge(edge, rotate)-> CvSubdiv2DEdge
:param edge: Subdivision edge (not a quad-edge)
:param rotate: Specifies which of the edges of the same quad-edge as the input one to return, one of the following:
* **0** the input edge ( ``e`` on the picture below if ``e`` is the input edge)
* **1** the rotated edge ( ``eRot`` )
* **2** the reversed edge (reversed ``e`` (in green))
* **3** the reversed rotated edge (reversed ``eRot`` (in green))
.. image:: ../pics/quadedge.png
The function returns one of the edges of the same quad-edge as the input edge.
SubdivDelaunay2DInsert
----------------------
Inserts a single point into a Delaunay triangulation.
.. ocv:cfunction:: CvSubdiv2DPoint* cvSubdivDelaunay2DInsert( CvSubdiv2D* subdiv, CvPoint2D32f pt)
.. ocv:pyoldfunction:: cv.SubdivDelaunay2DInsert(subdiv, pt)-> point
:param subdiv: Delaunay subdivision created by the function :ref:`CreateSubdivDelaunay2D`
:param pt: Inserted point
The function inserts a single point into a subdivision and modifies the subdivision topology appropriately. If a point with the same coordinates exists already, no new point is added. The function returns a pointer to the allocated point. No virtual point coordinates are calculated at this stage.
@@ -98,9 +98,8 @@ Calculates the seven Hu invariants.
: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::
@@ -149,13 +148,12 @@ Finds contours in a binary image.
* **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.
@@ -381,20 +379,55 @@ 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.
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
--------------
@@ -404,11 +437,18 @@ Fits an ellipse around a set of 2D points.
.. ocv:pyfunction:: cv2.fitEllipse(points) -> retval
:param points: Input vector of 2D points, stored in ``std::vector<>`` or ``Mat``.
.. ocv:cfunction:: CvBox2D cvFitEllipse2( const CvArr* points )
.. ocv:pyoldfunction:: cv.FitEllipse2(points)-> Box2D
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.
:param points: The input 2D point set, stored in:
* ``std::vector<>`` or ``Mat`` (C++ interface).
* ``CvSeq*`` or ``CvMat*`` (C interface)
* Nx2 numpy array (Python 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. The algorithm [Fitzgibbon95]_ is used.
fitLine
-----------
@@ -489,7 +529,16 @@ 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.
@@ -631,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 Buyers 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)
+12 -16
View File
@@ -10,8 +10,7 @@ A common machine learning task is supervised learning. In supervised learning, t
:math:`x` and the output
: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.
@@ -23,8 +22,7 @@ The boosted model is based on
:math:`x_i` is a
: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, outlined below. Initially the same weight is assigned to each sample (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
@@ -55,20 +53,15 @@ Different variants of boosting are known as Discrete Adaboost, Real AdaBoost, Lo
#. 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 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:
.. [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:
[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] Friedman, J. H., Hastie, T. and Tibshirani, R. *Additive Logistic Regression: a Statistical View of Boosting*. Technical Report, Dept. of Statistics, Stanford University, 1998.
CvBoostParams
-------------
@@ -151,6 +144,9 @@ Default and training constructors.
.. ocv:cfunction:: 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() )
.. 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
@@ -159,7 +155,7 @@ 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 )
.. ocv:pyfunction:: cv2.CvBoost.train(trainData, tflag, responses[, varIdx[, sampleIdx[, varType[, missingDataMask[, params[, update]]]]]]) -> retval
.. ocv:pyfunction:: cv2.Boost.train(trainData, tflag, responses[, varIdx[, sampleIdx[, varType[, missingDataMask[, params[, update]]]]]]) -> retval
.. ocv:cfunction:: 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 )
@@ -177,7 +173,7 @@ Predicts a response for an input sample.
.. ocv:cfunction:: 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.CvBoost.predict(sample[, missing[, slice[, rawMode[, returnSum]]]]) -> retval
.. ocv:pyfunction:: cv2.Boost.predict(sample[, missing[, slice[, rawMode[, returnSum]]]]) -> retval
:param sample: Input sample.
@@ -199,7 +195,7 @@ Removes the specified weak classifiers.
.. ocv:cfunction:: void CvBoost::prune( CvSlice slice )
.. ocv:pyfunction:: cv2.CvBoost.prune(slice) -> None
.. ocv:pyfunction:: cv2.Boost.prune(slice) -> None
:param slice: Continuous subset of the sequence of weak classifiers to be removed.
+7 -5
View File
@@ -1,8 +1,7 @@
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
:ocv:class:`CvDTree` represents a single decision tree that may be used alone or as a base class in tree ensembles (see
@@ -55,7 +54,6 @@ 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.
CvDTreeSplit
------------
@@ -235,7 +233,7 @@ Trains a decision tree.
.. ocv:cfunction:: bool CvDTree::train( CvDTreeTrainData* trainData, const CvMat* subsampleIdx )
.. ocv:pyfunction:: cv2.CvDTree.train(trainData, tflag, responses[, varIdx[, sampleIdx[, varType[, missingDataMask[, params]]]]]) -> retval
.. ocv:pyfunction:: cv2.DTree.train(trainData, tflag, responses[, varIdx[, sampleIdx[, varType[, missingDataMask[, params]]]]]) -> retval
There are four ``train`` methods in :ocv:class:`CvDTree`:
@@ -255,7 +253,7 @@ Returns the leaf node of a decision tree corresponding to the input vector.
.. ocv:cfunction:: CvDTreeNode* CvDTree::predict( const CvMat* sample, const CvMat* missingDataMask=0, bool preprocessedInput=false ) const
.. ocv:pyfunction:: cv2.CvDTree.predict(sample[, missingDataMask[, preprocessedInput]]) -> retval
.. ocv:pyfunction:: cv2.DTree.predict(sample[, missingDataMask[, preprocessedInput]]) -> retval
:param sample: Sample for prediction.
@@ -294,6 +292,7 @@ Returns the variable importance array.
.. ocv:cfunction:: const CvMat* CvDTree::get_var_importance()
.. ocv:pyfunction:: cv2.DTree.getVarImportance() -> importanceVector
CvDTree::get_root
-----------------
@@ -319,3 +318,6 @@ Returns used train data of the decision tree.
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.
+16 -3
View File
@@ -157,7 +157,7 @@ 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.CvEM.train(samples[, sampleIdx[, params]]) -> retval, labels
.. ocv:pyfunction:: cv2.EM.train(samples[, sampleIdx[, params]]) -> retval, labels
:param samples: Samples from which the Gaussian mixture model will be estimated.
@@ -189,7 +189,7 @@ Returns a mixture component index of a sample.
.. ocv:function:: float CvEM::predict( const CvMat* sample, CvMat* probs ) const
.. ocv:pyfunction:: cv2.CvEM.predict(sample) -> retval, probs
.. ocv:pyfunction:: cv2.EM.predict(sample) -> retval, probs
:param sample: A sample for classification.
@@ -204,8 +204,10 @@ Returns the number of mixture components :math:`M` in the gaussian mixture model
.. ocv:function:: int CvEM::get_nclusters() const
.. ocv:pyfunction:: cv2.EM.getNClusters() -> retval
CvEM::getNClusters
CvEM::getMeans
------------------
Returns mixture means :math:`a_k`.
@@ -213,6 +215,8 @@ Returns mixture means :math:`a_k`.
.. ocv:function:: const CvMat* CvEM::get_means() const
.. ocv:pyfunction:: cv2.EM.getMeans() -> means
CvEM::getCovs
-------------
@@ -222,6 +226,8 @@ Returns mixture covariance matrices :math:`S_k`.
.. ocv:function:: const CvMat** CvEM::get_covs() const
.. ocv:pyfunction:: cv2.EM.getCovs([covs]) -> covs
CvEM::getWeights
----------------
@@ -231,6 +237,8 @@ Returns mixture weights :math:`\pi_k`.
.. ocv:function:: const CvMat* CvEM::get_weights() const
.. ocv:pyfunction:: cv2.EM.getWeights() -> weights
CvEM::getProbs
--------------
@@ -240,6 +248,8 @@ Returns vectors of probabilities for each training sample.
.. 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`.
@@ -251,6 +261,8 @@ Returns logarithm of likelihood.
.. ocv:function:: double CvEM::get_log_likelihood() const
.. ocv:pyfunction:: cv2.EM.getLikelihood() -> likelihood
CvEM::getLikelihoodDelta
------------------------
@@ -260,6 +272,7 @@ Returns difference between logarithm of likelihood on the last iteration and log
.. ocv:function:: double CvEM::get_log_likelihood_delta() const
.. ocv:pyfunction:: cv2.EM.getLikelihoodDelta() -> likelihood delta
CvEM::write_params
------------------
+8 -6
View File
@@ -161,6 +161,8 @@ Default and training constructors.
.. ocv:cfunction:: 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() )
.. ocv:pyfunction:: cv2.GBTrees([trainData, tflag, responses[, varIdx[, sampleIdx[, varType[, missingDataMask[, params]]]]]]) -> <GBTrees object>
The constructors follow conventions of :ocv:func:`CvStatModel::CvStatModel`. See :ocv:func:`CvStatModel::train` for parameters descriptions.
CvGBTrees::train
@@ -169,8 +171,8 @@ Trains a Gradient boosted tree model.
.. 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)
.. ocv:pyfunction:: cv2.CvGBTrees.train(trainData, tflag, responses[, varIdx[, sampleIdx[, varType[, missingDataMask[, params[, update]]]]]]) -> retval
.. ocv:pyfunction:: cv2.GBTrees.train(trainData, tflag, responses[, varIdx[, sampleIdx[, varType[, missingDataMask[, params[, update]]]]]]) -> retval
.. ocv:cfunction:: 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 )
.. ocv:cfunction:: bool CvGBTrees::train(CvMLData* data, CvGBTreesParams params=CvGBTreesParams(), bool update=false)
@@ -196,8 +198,8 @@ Predicts a response for an input sample.
.. ocv:function:: float CvGBTrees::predict(const Mat& sample, const Mat& missing=Mat(), const Range& slice = Range::all(), int k=-1) const
.. ocv:pyfunction:: cv2.CvGBTrees.predict(sample[, missing[, slice[, k]]]) -> retval
.. ocv:pyfunction:: cv2.GBTrees.predict(sample[, missing[, slice[, k]]]) -> retval
.. ocv:cfunction:: float CvGBTrees::predict( const CvMat* sample, const CvMat* missing=0, CvMat* weakResponses=0, CvSlice slice = CV_WHOLE_SEQ, int k=-1 ) const
:param sample: Input feature vector that has the same format as every training set
@@ -239,8 +241,8 @@ Clears the model.
.. ocv:function:: void CvGBTrees::clear()
.. ocv:pyfunction:: cv2.CvGBTrees.clear() -> None
.. ocv:pyfunction:: cv2.GBTrees.clear() -> None
The function deletes the data set information and all the weak models and sets all internal
variables to the initial state. The function is called in :ocv:func:`CvGBTrees::train` and in the
destructor.
+2 -2
View File
@@ -29,7 +29,7 @@ Trains the model.
.. 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:pyfunction:: cv2.CvKNearest.train(trainData, responses[, sampleIdx[, isRegression[, maxK[, updateBase]]]]) -> retval
.. ocv:pyfunction:: cv2.KNearest.train(trainData, responses[, sampleIdx[, isRegression[, maxK[, updateBase]]]]) -> retval
.. ocv:cfunction:: bool CvKNearest::train( const CvMat* trainData, const CvMat* responses, const CvMat* sampleIdx=0, bool is_regression=false, int maxK=32, bool updateBase=false )
@@ -54,7 +54,7 @@ Finds the neighbors and predicts responses for input vectors.
.. ocv:function:: float CvKNearest::find_nearest( const Mat& samples, int k, Mat& results, Mat& neighborResponses, Mat& dists) const
.. ocv:pyfunction:: cv2.CvKNearest.find_nearest(samples, k[, results[, neighborResponses[, dists]]]) -> retval, results, neighborResponses, dists
.. ocv:pyfunction:: cv2.KNearest.find_nearest(samples, k[, results[, neighborResponses[, dists]]]) -> retval, results, neighborResponses, dists
.. ocv:cfunction:: float CvKNearest::find_nearest( const CvMat* samples, int k, CvMat* results=0, const float** neighbors=0, CvMat* neighborResponses=0, CvMat* dist=0 ) const
+14 -13
View File
@@ -88,20 +88,12 @@ 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.
*
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:
*
[RPROP93] M. Riedmiller and H. Braun, *A Direct Adaptive Method for Faster Backpropagation Learning: The RPROP Algorithm*, Proc. ICNN, San Francisco (1993).
.. [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.
.. [RPROP93] M. Riedmiller and H. Braun, *A Direct Adaptive Method for Faster Backpropagation Learning: The RPROP Algorithm*, Proc. ICNN, San Francisco (1993).
CvANN_MLP_TrainParams
---------------------
@@ -119,7 +111,7 @@ The back-propagation algorithm parameters:
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 :ref:`[RPROP93] <RPROP93>` for details):
The RPROP algorithm parameters (see [RPROP93]_ for details):
.. ocv:member:: double rp_dw0
@@ -192,6 +184,8 @@ The constructors.
.. ocv:cfunction:: CvANN_MLP::CvANN_MLP( const CvMat* layerSizes, int activateFunc=CvANN_MLP::SIGMOID_SYM, double fparam1=0, double fparam2=0 )
.. 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
@@ -202,6 +196,8 @@ Constructs MLP with the specified topology.
.. ocv:cfunction:: void CvANN_MLP::create( const CvMat* layerSizes, int activateFunc=CvANN_MLP::SIGMOID_SYM, double fparam1=0, double fparam2=0 )
.. ocv:pyfunction:: cv2.ANN_MLP.create(layerSizes[, activateFunc[, fparam1[, fparam2]]]) -> None
:param layerSizes: Integer vector specifying the number of neurons in each layer including the input and output layers.
:param activateFunc: Parameter specifying the activation function for each neuron: one of ``CvANN_MLP::IDENTITY``, ``CvANN_MLP::SIGMOID_SYM``, and ``CvANN_MLP::GAUSSIAN``.
@@ -218,6 +214,8 @@ Trains/updates MLP.
.. ocv:cfunction:: 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 )
.. ocv:pyfunction:: cv2.ANN_MLP.train(inputs, outputs, sampleWeights[, sampleIdx[, params[, flags]]]) -> niterations
:param inputs: Floating-point matrix of input vectors, one vector per row.
:param outputs: Floating-point matrix of the corresponding output vectors, one vector per row.
@@ -246,6 +244,8 @@ Predicts responses for input samples.
.. ocv:cfunction:: 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.
@@ -273,3 +273,4 @@ Returns neurons weights of the particular layer.
.. ocv:function:: double* CvANN_MLP::get_weights(int layer)
:param layer: Index of the particular layer.
+5 -3
View File
@@ -7,7 +7,7 @@ Normal Bayes Classifier
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.
[Fukunaga90] K. Fukunaga. *Introduction to Statistical Pattern Recognition*. second ed., New York: Academic Press, 1990.
.. [Fukunaga90] K. Fukunaga. *Introduction to Statistical Pattern Recognition*. second ed., New York: Academic Press, 1990.
CvNormalBayesClassifier
-----------------------
@@ -25,6 +25,8 @@ Default and training constructors.
.. ocv:cfunction:: CvNormalBayesClassifier::CvNormalBayesClassifier( const CvMat* trainData, const CvMat* responses, const CvMat* varIdx=0, const CvMat* sampleIdx=0 )
.. ocv:pyfunction:: cv2.NormalBayesClassifier(trainData, responses[, varIdx[, sampleIdx]]) -> <NormalBayesClassifier object>
The constructors follow conventions of :ocv:func:`CvStatModel::CvStatModel`. See :ocv:func:`CvStatModel::train` for parameters descriptions.
CvNormalBayesClassifier::train
@@ -33,7 +35,7 @@ Trains the model.
.. ocv:function:: bool CvNormalBayesClassifier::train( const Mat& trainData, const Mat& responses, const Mat& varIdx = Mat(), const Mat& sampleIdx=Mat(), bool update=false )
.. ocv:pyfunction:: cv2.CvNormalBayesClassifier.train(trainData, responses[, varIdx[, sampleIdx[, update]]]) -> retval
.. ocv:pyfunction:: cv2.NormalBayesClassifier.train(trainData, responses[, varIdx[, sampleIdx[, update]]]) -> retval
.. ocv:cfunction:: bool CvNormalBayesClassifier::train( const CvMat* trainData, const CvMat* responses, const CvMat* varIdx = 0, const CvMat* sampleIdx=0, bool update=false )
@@ -52,7 +54,7 @@ Predicts the response for sample(s).
.. ocv:function:: float CvNormalBayesClassifier::predict( const Mat& samples, Mat* results=0 ) const
.. ocv:pyfunction:: cv2.CvNormalBayesClassifier.predict(samples) -> retval, results
.. ocv:pyfunction:: cv2.NormalBayesClassifier.predict(samples) -> retval, results
.. ocv:cfunction:: float CvNormalBayesClassifier::predict( const CvMat* samples, CvMat* results=0 ) const
+5 -3
View File
@@ -114,7 +114,7 @@ Trains the Random Trees model.
.. ocv:cfunction:: bool CvRTrees::train( CvMLData* data, CvRTParams params=CvRTParams() )
.. ocv:pyfunction:: cv2.CvRTrees.train(trainData, tflag, responses[, varIdx[, sampleIdx[, varType[, missingDataMask[, params]]]]]) -> retval
.. 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``.
@@ -126,7 +126,7 @@ Predicts the output for an input sample.
.. ocv:cfunction:: float CvRTrees::predict( const CvMat* sample, const CvMat* missing = 0 ) const
.. ocv:pyfunction:: cv2.CvRTrees.predict(sample[, missing]) -> retval
.. ocv:pyfunction:: cv2.RTrees.predict(sample[, missing]) -> retval
:param sample: Sample for classification.
@@ -143,7 +143,7 @@ Returns a fuzzy-predicted class label.
.. ocv:cfunction:: float CvRTrees::predict_prob( const CvMat* sample, const CvMat* missing = 0 ) const
.. ocv:pyfunction:: cv2.CvRTrees.predict_prob(sample[, missing]) -> retval
.. ocv:pyfunction:: cv2.RTrees.predict_prob(sample[, missing]) -> retval
:param sample: Sample for classification.
@@ -158,6 +158,8 @@ Returns the variable importance array.
.. ocv:function:: Mat CvRTrees::getVarImportance()
.. ocv:pyfunction:: cv2.RTrees.getVarImportance() -> importanceVector
.. ocv:cfunction:: const CvMat* CvRTrees::get_var_importance()
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.
+2 -2
View File
@@ -89,7 +89,7 @@ Saves the model to a file.
.. ocv:function:: void CvStatModel::save( const char* filename, const char* name=0 )
.. ocv:pyfunction:: cv2.CvStatModel.save(filename[, name]) -> None
.. 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.
@@ -99,7 +99,7 @@ Loads the model from a file.
.. ocv:function:: void CvStatModel::load( const char* filename, const char* name=0 )
.. ocv:pyfunction:: cv2.CvStatModel.load(filename[, name]) -> None
.. ocv:pyfunction:: cv2.StatModel.load(filename[, name]) -> None
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`.
+15 -23
View File
@@ -7,29 +7,11 @@ Originally, support vector machines (SVM) was a technique for building an optima
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/
)
For details of implementation and various SVM formulations see:
.. _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
)
.. [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)
CvParamGrid
@@ -121,7 +103,7 @@ The constructors.
* **CvSVM::NU_SVR** :math:`\nu`-Support Vector Regression. :math:`\nu` is used instead of ``p``.
See :ref:`[LibSVM] <LibSVM>` for details.
See [LibSVM]_ for details.
:param kernel_type: Type of a SVM kernel. Possible values are:
@@ -178,6 +160,8 @@ Default and training constructors.
.. ocv:cfunction:: CvSVM::CvSVM( const CvMat* trainData, const CvMat* responses, const CvMat* varIdx=0, const CvMat* sampleIdx=0, CvSVMParams params=CvSVMParams() )
.. ocv:pyfunction:: cv2.SVM(trainData, responses[, varIdx[, sampleIdx[, params]]]) -> <SVM object>
The constructors follow conventions of :ocv:func:`CvStatModel::CvStatModel`. See :ocv:func:`CvStatModel::train` for parameters descriptions.
CvSVM::train
@@ -188,7 +172,7 @@ Trains an SVM.
.. ocv:cfunction:: bool CvSVM::train( const CvMat* trainData, const CvMat* responses, const CvMat* varIdx=0, const CvMat* sampleIdx=0, CvSVMParams params=CvSVMParams() )
.. ocv:pyfunction:: cv2.CvSVM.train(trainData, responses[, varIdx[, sampleIdx[, params]]]) -> retval
.. ocv:pyfunction:: cv2.SVM.train(trainData, responses[, varIdx[, sampleIdx[, params]]]) -> retval
The method trains the SVM model. It follows the conventions of the generic :ocv:func:`CvStatModel::train` approach with the following limitations:
@@ -212,6 +196,8 @@ Trains an SVM with optimal parameters.
.. ocv:cfunction:: 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 )
.. ocv:pyfunction:: cv2.SVM.train_auto(trainData, responses, varIdx, sampleIdx, params[, k_fold[, Cgrid[, gammaGrid[, pGrid[, nuGrid[, coeffGrid[, degreeGrid[, balanced]]]]]]]]) -> retval
: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.
@@ -244,6 +230,8 @@ Predicts the response for input sample(s).
.. ocv:cfunction:: 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).
@@ -292,6 +280,8 @@ Retrieves a number of support vectors and the particular vector.
.. ocv:function:: const float* CvSVM::get_support_vector(int i) const
.. 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.
@@ -301,3 +291,5 @@ 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
@@ -3,6 +3,35 @@ Cascade Classification
.. highlight:: cpp
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
----------------
.. ocv:class:: FeatureEvaluator
@@ -111,76 +140,7 @@ CascadeClassifier
-----------------
.. ocv:class:: CascadeClassifier
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
};
Cascade classifier class for object detection.
CascadeClassifier::CascadeClassifier
----------------------------------------
@@ -188,6 +148,8 @@ Loads a classifier from a file.
.. ocv:function:: CascadeClassifier::CascadeClassifier(const string& filename)
.. ocv:pyfunction:: cv2.CascadeClassifier(filename) -> <CascadeClassifier object>
:param filename: Name of the file from which the classifier is loaded.
@@ -231,6 +193,12 @@ Detects objects of different sizes in the input image. The detected objects are
.. 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.
:param objects: Vector of rectangles where each rectangle contains the detected object.
@@ -247,22 +215,33 @@ Detects objects of different sizes in the input image. The detected objects are
CascadeClassifier::setImage
-------------------------------
Sets an image for detection that is called by ``detectMultiScale`` at each image level.
Sets an image for detection.
.. ocv:function:: bool CascadeClassifier::setImage( Ptr<FeatureEvaluator>& feval, const Mat& image )
.. 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 used for computing features.
:param image: Matrix of the type ``CV_8UC1`` containing an image where the features are computed.
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. Use ``setImage`` to set the image for the detector to work with.
Runs the detector at the specified point.
.. ocv:function:: int CascadeClassifier::runAt( Ptr<FeatureEvaluator>& feval, Point pt )
.. 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 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.
@@ -270,13 +249,13 @@ Runs the detector at the specified point. Use ``setImage`` to set the image for
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.
Use :ocv:func:`CascadeClassifier::setImage` to set the image for the detector to work with.
groupRectangles
-------------------
Groups the object candidate rectangles.
.. ocv:function:: void groupRectangles(vector<Rect>& rectList, int groupThreshold, double eps=0.2)
.. ocv:function:: void groupRectangles(vector<Rect>& rectList, int groupThreshold, double eps=0.2)
.. ocv:pyfunction:: cv2.groupRectangles(rectList, groupThreshold[, eps]) -> None
.. ocv:pyfunction:: cv2.groupRectangles(rectList, groupThreshold[, eps]) -> weights
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.9 KiB

+4 -1
View 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(),
+1 -1
View File
@@ -1,5 +1,5 @@
############################
OpenCV 2.x C++ API Reference
OpenCV API Reference
############################
.. toctree::
@@ -41,8 +41,7 @@ Calculates an optical flow for a sparse feature set using the iterative Lucas-Ka
* **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]_.
@@ -78,7 +77,7 @@ Computes a dense optical flow using the Gunnar Farneback's algorithm.
* **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 z 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::
@@ -143,7 +142,7 @@ Calculates the optical flow for two images using Horn-Schunck algorithm.
: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`.
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
@@ -165,7 +164,7 @@ Calculates the optical flow for two images using Lucas-Kanade algorithm.
: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`.
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`.
estimateRigidTransform
@@ -243,9 +242,9 @@ 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.
@@ -364,8 +363,7 @@ Finds an object center, size, and orientation.
: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()`` .
@@ -407,8 +405,7 @@ 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`` .
@@ -421,6 +418,11 @@ The constructors.
.. 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: Dimensionality of the state.
@@ -431,6 +433,7 @@ The constructors.
:param type: Type of the created matrices that should be ``CV_32F`` or ``CV_64F``.
.. note:: In C API when ``CvKalman* kalmanFilter`` structure is not needed anymore, it should be released with ``cvReleaseKalman(&kalmanFilter)``
KalmanFilter::init
------------------
@@ -447,7 +450,6 @@ Re-initializes Kalman filter. The previous content is destroyed.
:param type: Type of the created matrices that should be ``CV_32F`` or ``CV_64F``.
KalmanFilter::predict
---------------------
Computes a predicted state.
@@ -456,6 +458,9 @@ Computes a 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
@@ -467,6 +472,9 @@ 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
@@ -489,19 +497,17 @@ 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.
BackgroundSubtractor::operator()
-------------------------------
Computes a foreground mask.
.. ocv:function:: virtual void BackgroundSubtractor::operator()(InputArray image, OutputArray fgmask, double learningRate=0)
.. ocv:pyfunction:: cv2.BackgroundSubtractor.apply(image[, fgmask[, learningRate]]) -> fgmask
:param image: Next video frame.
:param fgmask: Foreground mask as an 8-bit binary image.
:param fgmask: The output foreground mask as an 8-bit binary image.
BackgroundSubtractor::getBackgroundImage
@@ -534,6 +540,8 @@ The contructors
.. ocv:function:: BackgroundSubtractorMOG::BackgroundSubtractorMOG(int history, int nmixtures, double backgroundRatio, double noiseSigma=0)
.. ocv:pyfunction:: cv2.BackgroundSubtractorMOG(history, nmixtures, backgroundRatio[, noiseSigma]) -> <BackgroundSubtractorMOG object>
:param history: Length of the history.
:param nmixtures: Number of Gaussian mixtures.
@@ -638,6 +646,23 @@ BackgroundSubtractorMOG2::getBackgroundImage
--------------------------------------------
Returns background image
.. ocv:function:: virtual void BackgroundSubtractorMOG2::getBackgroundImage(OutputArray backgroundImage) const
.. ocv:function:: virtual void BackgroundSubtractorMOG2::getBackgroundImage(OutputArray backgroundImage)
See :ocv:func:`BackgroundSubtractor::getBackgroundImage`.
See :ocv:func:`BackgroundSubtractor::getBackgroundImage`.
.. [Bouguet00] Jean-Yves Bouguet. Pyramidal Implementation of the Lucas Kanade Feature Tracker.
.. [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
.. [Farneback2003] Gunnar Farneback, Two-frame motion estimation based on polynomial expansion, Lecture Notes in Computer Science, 2003, (2749), , 363-370.
.. [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