..cfunction:: double kmeans( const Mat\& samples, int clusterCount, Mat\& labels, TermCriteria termcrit, int attempts, int flags, Mat* centers )
`id=0.0672046481842 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/core/kmeans>`__
Finds the centers of clusters and groups the input samples around the clusters.
:param samples:Floating-point matrix of input samples, one row per sample
:param clusterCount:The number of clusters to split the set by
:param labels:The input/output integer array that will store the cluster indices for every sample
..cfunction:: double kmeans( const Mat\& samples, int clusterCount, Mat\& labels, TermCriteria termcrit, int attempts, int flags, Mat* centers )
:param termcrit:Specifies maximum number of iterations and/or accuracy (distance the centers can move by between subsequent iterations)
Finds the centers of clusters and groups the input samples around the clusters.
:param attempts:How many times the algorithm is executed using different initial labelings. The algorithm returns the labels that yield the best compactness (see the last function parameter)
:param flags:It can take the following values:
* **KMEANS_RANDOM_CENTERS** Random initial centers are selected in each attempt
* **KMEANS_PP_CENTERS** Use kmeans++ center initialization by Arthur and Vassilvitskii
:param samples:Floating-point matrix of input samples, one row per sample
:param clusterCount:The number of clusters to split the set by
:param labels:The input/output integer array that will store the cluster indices for every sample
:param termcrit:Specifies maximum number of iterations and/or accuracy (distance the centers can move by between subsequent iterations)
:param attempts:How many times the algorithm is executed using different initial labelings. The algorithm returns the labels that yield the best compactness (see the last function parameter)
:param flags:It can take the following values:
* **KMEANS_RANDOM_CENTERS** Random initial centers are selected in each attempt
* **KMEANS_PP_CENTERS** Use kmeans++ center initialization by Arthur and Vassilvitskii
* **KMEANS_USE_INITIAL_LABELS** During the first (and possibly the only) attempt, the
function uses the user-supplied labels instaed of computing them from the initial centers. For the second and further attempts, the function will use the random or semi-random centers (use one of ``KMEANS_*_CENTERS`` flag to specify the exact method)
:param centers:The output matrix of the cluster centers, one row per each cluster center
The function
``kmeans``
implements a k-means algorithm that finds the
centers of
``clusterCount``
clusters and groups the input samples
around the clusters. On output,
:math:`\texttt{labels}_i`
contains a 0-based cluster index for
the sample stored in the
:math:`i^{th}`
row of the
``samples``
matrix.
function uses the user-supplied labels instaed of computing them from the initial centers. For the second and further attempts, the function will use the random or semi-random centers (use one of ``KMEANS_*_CENTERS`` flag to specify the exact method)
The function returns the compactness measure, which is computed as
:param centers:The output matrix of the cluster centers, one row per each cluster center
The function ``kmeans`` implements a k-means algorithm that finds the
centers of ``clusterCount`` clusters and groups the input samples
around the clusters. On output,
:math:`\texttt{labels}_i` contains a 0-based cluster index for
the sample stored in the
:math:`i^{th}` row of the ``samples`` matrix.
..math::
The function returns the compactness measure, which is computed as
:param labels:The output vector of labels; will contain as many elements as ``vec`` . Each label ``labels[i]`` is 0-based cluster index of ``vec[i]`` :param predicate: The equivalence predicate (i.e. pointer to a boolean function of two arguments or an instance of the class that has the method ``bool operator()(const _Tp& a, const _Tp& b)`` . The predicate returns true when the elements are certainly if the same class, and false if they may or may not be in the same class
:param vec:The set of elements stored as a vector
:param labels:The output vector of labels; will contain as many elements as ``vec`` . Each label ``labels[i]`` is 0-based cluster index of ``vec[i]``
:param predicate:The equivalence predicate (i.e. pointer to a boolean function of two arguments or an instance of the class that has the method ``bool operator()(const _Tp& a, const _Tp& b)`` . The predicate returns true when the elements are certainly if the same class, and false if they may or may not be in the same class
The generic function
``partition``
implements an
:math:`O(N^2)`
algorithm for
splitting a set of
:math:`N`
elements into one or more equivalency classes, as described in
The generic function ``partition`` implements an
:math:`O(N^2)` algorithm for
splitting a set of
:math:`N` elements into one or more equivalency classes, as described in
Drawing functions work with matrices/images of arbitrary depth.
The boundaries of the shapes can be rendered with antialiasing (implemented only for 8-bit images for now).
All the functions include the parameter color that uses a rgb value (that may be constructed
with
``CV_RGB``
or the :ref:`Scalar` constructor
with ``CV_RGB`` or the :ref:`Scalar` constructor
) for color
images and brightness for grayscale images. For color images the order channel
is normally
is normally
*Blue, Green, Red*
, this is what
:func:`imshow`
,
:func:`imread`
and
:func:`imwrite`
expect
, so if you form a color using
:ref:`Scalar`
constructor, it should look like:
, this is what
:func:`imshow`,:func:`imread` and
:func:`imwrite` expect
, so if you form a color using
:ref:`Scalar` constructor, it should look like:
..math::
\texttt{Scalar} (blue \_ component, green \_ component, red \_ component[, alpha \_ component])
If you are using your own image rendering and I/O functions, you can use any channel ordering, the drawing functions process each channel independently and do not depend on the channel order or even on the color space used. The whole image can be converted from BGR to RGB or to a different color space using
:func:`cvtColor`
.
\texttt{Scalar} (blue \_ component, green \_ component, red \_ component[, alpha \_ component])
If a drawn figure is partially or completely outside the image, the drawing functions clip it. Also, many drawing functions can handle pixel coordinates specified with sub-pixel accuracy, that is, the coordinates can be passed as fixed-point numbers, encoded as integers. The number of fractional bits is specified by the
``shift``
parameter and the real point coordinates are calculated as
. This feature is especially effective wehn rendering antialiased shapes.
If you are using your own image rendering and I/O functions, you can use any channel ordering, the drawing functions process each channel independently and do not depend on the channel order or even on the color space used. The whole image can be converted from BGR to RGB or to a different color space using
:func:`cvtColor` .
Also, note that the functions do not support alpha-transparency - when the target image is 4-channnel, then the
``color[3]``
is simply copied to the repainted pixels. Thus, if you want to paint semi-transparent shapes, you can paint them in a separate buffer and then blend it with the main image.
If a drawn figure is partially or completely outside the image, the drawing functions clip it. Also, many drawing functions can handle pixel coordinates specified with sub-pixel accuracy, that is, the coordinates can be passed as fixed-point numbers, encoded as integers. The number of fractional bits is specified by the ``shift`` parameter and the real point coordinates are calculated as
:math:`\texttt{Point}(x,y)\rightarrow\texttt{Point2f}(x*2^{-shift},y*2^{-shift})` . This feature is especially effective wehn rendering antialiased shapes.
Also, note that the functions do not support alpha-transparency - when the target image is 4-channnel, then the ``color[3]`` is simply copied to the repainted pixels. Thus, if you want to paint semi-transparent shapes, you can paint them in a separate buffer and then blend it with the main image.
..index:: circle
cv::circle
----------
..cfunction:: void circle(Mat\& img, Point center, int radius, const Scalar\& color, int thickness=1, int lineType=8, int shift=0)
`id=0.143685141364 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/core/circle>`__
Draws a circle
:param img:Image where the circle is drawn
..cfunction:: void circle(Mat\& img, Point center, int radius, const Scalar\& color, int thickness=1, int lineType=8, int shift=0)
:param center:Center of the circle
Draws a circle
:param radius:Radius of the circle
:param color:Circle color
:param thickness:Thickness of the circle outline if positive; negative thickness means that a filled circle is to be drawn
:param lineType:Type of the circle boundary, see :func:`line` description
:param shift:Number of fractional bits in the center coordinates and radius value
:param img:Image where the circle is drawn
:param center:Center of the circle
:param radius:Radius of the circle
:param color:Circle color
:param thickness:Thickness of the circle outline if positive; negative thickness means that a filled circle is to be drawn
:param lineType:Type of the circle boundary, see :func:`line` description
:param shift:Number of fractional bits in the center coordinates and radius value
The function
``circle``
draws a simple or filled circle with a
The function ``circle`` draws a simple or filled circle with a
given center and radius.
..index:: clipLine
cv::clipLine
------------
`id=0.715949286846 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/core/clipLine>`__
:param imgSize:The image size; the image rectangle will be ``Rect(0, 0, imgSize.width, imgSize.height)`` :param imgSize: The image rectangle
:param pt1:The first line point
:param pt2:The second line point
:param imgSize:The image size; the image rectangle will be ``Rect(0, 0, imgSize.width, imgSize.height)``
:param imgSize:The image rectangle
:param pt1:The first line point
:param pt2:The second line point
The functions
``clipLine``
calculate a part of the line
The functions ``clipLine`` calculate a part of the line
segment which is entirely within the specified rectangle.
They return
``false``
if the line segment is completely outside the rectangle and
``true``
otherwise.
They return ``false`` if the line segment is completely outside the rectangle and ``true`` otherwise.
..index:: ellipse
cv::ellipse
-----------
..cfunction:: void ellipse(Mat\& img, Point center, Size axes, double angle, double startAngle, double endAngle, const Scalar\& color, int thickness=1, int lineType=8, int shift=0)
`id=0.0631091216884 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/core/ellipse>`__
..cfunction:: void ellipse(Mat\& img, const RotatedRect\& box, const Scalar\& color, int thickness=1, int lineType=8)
Draws a simple or thick elliptic arc or an fills ellipse sector.
:param img:The image
:param center:Center of the ellipse
..cfunction:: void ellipse(Mat\& img, Point center, Size axes, double angle, double startAngle, double endAngle, const Scalar\& color, int thickness=1, int lineType=8, int shift=0)
:param axes:Length of the ellipse axes
:param angle:The ellipse rotation angle in degrees
:param startAngle:Starting angle of the elliptic arc in degrees
..cfunction:: void ellipse(Mat\& img, const RotatedRect\& box, const Scalar\& color, int thickness=1, int lineType=8)
:param endAngle:Ending angle of the elliptic arc in degrees
Draws a simple or thick elliptic arc or an fills ellipse sector.
:param box:Alternative ellipse representation via a :ref:`RotatedRect` , i.e. the function draws an ellipse inscribed in the rotated rectangle
:param color:Ellipse color
:param thickness:Thickness of the ellipse arc outline if positive, otherwise this indicates that a filled ellipse sector is to be drawn
:param lineType:Type of the ellipse boundary, see :func:`line` description
:param shift:Number of fractional bits in the center coordinates and axes' values
:param img:The image
:param center:Center of the ellipse
:param axes:Length of the ellipse axes
:param angle:The ellipse rotation angle in degrees
:param startAngle:Starting angle of the elliptic arc in degrees
:param endAngle:Ending angle of the elliptic arc in degrees
:param box:Alternative ellipse representation via a :ref:`RotatedRect` , i.e. the function draws an ellipse inscribed in the rotated rectangle
:param color:Ellipse color
:param thickness:Thickness of the ellipse arc outline if positive, otherwise this indicates that a filled ellipse sector is to be drawn
:param lineType:Type of the ellipse boundary, see :func:`line` description
:param shift:Number of fractional bits in the center coordinates and axes' values
The functions
``ellipse``
with less parameters draw an ellipse outline, a filled ellipse, an elliptic
arc or a filled ellipse sector.
A piecewise-linear curve is used to approximate the elliptic arc boundary. If you need more control of the ellipse rendering, you can retrieve the curve using
:func:`ellipse2Poly`
and then render it with
:func:`polylines`
or fill it with
:func:`fillPoly`
. If you use the first variant of the function and want to draw the whole ellipse, not an arc, pass
``startAngle=0``
and
``endAngle=360``
. The picture below
The functions ``ellipse`` with less parameters draw an ellipse outline, a filled ellipse, an elliptic
arc or a filled ellipse sector.
A piecewise-linear curve is used to approximate the elliptic arc boundary. If you need more control of the ellipse rendering, you can retrieve the curve using
:func:`ellipse2Poly` and then render it with
:func:`polylines` or fill it with
:func:`fillPoly` . If you use the first variant of the function and want to draw the whole ellipse, not an arc, pass ``startAngle=0`` and ``endAngle=360`` . The picture below
explains the meaning of the parameters.
Parameters of Elliptic Arc
..image:: ../../pics/ellipse.png
..index:: ellipse2Poly
cv::ellipse2Poly
----------------
`id=0.644340648167 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/core/ellipse2Poly>`__
..cfunction:: void ellipse2Poly( Point center, Size axes, int angle, int startAngle, int endAngle, int delta, vector<Point>\& pts )
Approximates an elliptic arc with a polyline
:param center:Center of the arc
:param axes:Half-sizes of the arc. See :func:`ellipse` :param angle: Rotation angle of the ellipse in degrees. See :func:`ellipse` :param startAngle: Starting angle of the elliptic arc in degrees
:param endAngle:Ending angle of the elliptic arc in degrees
:param delta:Angle between the subsequent polyline vertices. It defines the approximation accuracy.
:param center:Center of the arc
:param axes:Half-sizes of the arc. See :func:`ellipse`
:param angle:Rotation angle of the ellipse in degrees. See :func:`ellipse`
:param startAngle:Starting angle of the elliptic arc in degrees
:param endAngle:Ending angle of the elliptic arc in degrees
:param delta:Angle between the subsequent polyline vertices. It defines the approximation accuracy.
:param pts:The output vector of polyline vertices
The function
``ellipse2Poly``
computes the vertices of a polyline that approximates the specified elliptic arc. It is used by
:func:`ellipse`
.
:param pts:The output vector of polyline vertices
The function ``ellipse2Poly`` computes the vertices of a polyline that approximates the specified elliptic arc. It is used by
:func:`ellipse` .
..index:: fillConvexPoly
cv::fillConvexPoly
------------------
`id=0.345453533071 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/core/fillConvexPoly>`__
..cfunction:: void fillConvexPoly(Mat\& img, const Point* pts, int npts, const Scalar\& color, int lineType=8, int shift=0)
Fills a convex polygon.
:param img:Image
:param pts:The polygon vertices
:param npts:The number of polygon vertices
:param color:Polygon color
:param lineType:Type of the polygon boundaries, see :func:`line` description
:param img:Image
:param pts:The polygon vertices
:param npts:The number of polygon vertices
:param color:Polygon color
:param lineType:Type of the polygon boundaries, see :func:`line` description
:param shift:The number of fractional bits in the vertex coordinates
The function
``fillConvexPoly``
draws a filled convex polygon.
This function is much faster than the function
``fillPoly``
and can fill not only convex polygons but any monotonic polygon without self-intersections,
:param shift:The number of fractional bits in the vertex coordinates
The function ``fillConvexPoly`` draws a filled convex polygon.
This function is much faster than the function ``fillPoly`` and can fill not only convex polygons but any monotonic polygon without self-intersections,
i.e., a polygon whose contour intersects every horizontal line (scan
line) twice at the most (though, its top-most and/or the bottom edge could be horizontal).
..index:: fillPoly
cv::fillPoly
------------
..cfunction:: void fillPoly(Mat\& img, const Point** pts, const int* npts, int ncontours, const Scalar\& color, int lineType=8, int shift=0, Point offset=Point() )
`id=0.00272984452496 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/core/fillPoly>`__
Fills the area bounded by one or more polygons
:param img:Image
:param pts:Array of polygons, each represented as an array of points
..cfunction:: void fillPoly(Mat\& img, const Point** pts, const int* npts, int ncontours, const Scalar\& color, int lineType=8, int shift=0, Point offset=Point() )
:param npts:The array of polygon vertex counters
Fills the area bounded by one or more polygons
:param ncontours:The number of contours that bind the filled region
:param color:Polygon color
:param lineType:Type of the polygon boundaries, see :func:`line` description
:param shift:The number of fractional bits in the vertex coordinates
:param img:Image
:param pts:Array of polygons, each represented as an array of points
:param npts:The array of polygon vertex counters
:param ncontours:The number of contours that bind the filled region
:param color:Polygon color
:param lineType:Type of the polygon boundaries, see :func:`line` description
:param shift:The number of fractional bits in the vertex coordinates
The function
``fillPoly``
fills an area bounded by several
The function ``fillPoly`` fills an area bounded by several
polygonal contours. The function can fills complex areas, for example,
areas with holes, contours with self-intersections (some of thier parts), and so forth.
..index:: getTextSize
cv::getTextSize
---------------
`id=0.364618843078 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/core/getTextSize>`__
..cfunction:: Size getTextSize(const string\& text, int fontFace, double fontScale, int thickness, int* baseLine)
Calculates the width and height of a text string.
:param text:The input text string
:param fontFace:The font to use; see :func:`putText` :param fontScale: The font scale; see :func:`putText` :param thickness: The thickness of lines used to render the text; see :func:`putText` :param baseLine: The output parameter - y-coordinate of the baseline relative to the bottom-most text point
The function ``getTextSize`` calculates and returns size of the box that contain the specified text.
That is, the following code will render some text, the tight box surrounding it and the baseline: ::
:param text:The input text string
:param fontFace:The font to use; see :func:`putText`
:param fontScale:The font scale; see :func:`putText`
:param thickness:The thickness of lines used to render the text; see :func:`putText`
:param baseLine:The output parameter - y-coordinate of the baseline relative to the bottom-most text point
The function
``getTextSize``
calculates and returns size of the box that contain the specified text.
That is, the following code will render some text, the tight box surrounding it and the baseline:
@ -447,86 +230,46 @@ That is, the following code will render some text, the tight box surrounding it
line(img, textOrg + Point(0, thickness),
textOrg + Point(textSize.width, thickness),
Scalar(0, 0, 255));
// then put the text itself
putText(img, text, textOrg, fontFace, fontScale,
Scalar::all(255), thickness, 8);
..
..index:: line
cv::line
--------
..cfunction:: void line(Mat\& img, Point pt1, Point pt2, const Scalar\& color, int thickness=1, int lineType=8, int shift=0)
`id=0.645160739861 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/core/line>`__
Draws a line segment connecting two points
:param img:The image
:param pt1:First point of the line segment
:param pt2:Second point of the line segment
..cfunction:: void line(Mat\& img, Point pt1, Point pt2, const Scalar\& color, int thickness=1, int lineType=8, int shift=0)
:param color:Line color
Draws a line segment connecting two points
:param thickness:Line thickness
:param lineType:Type of the line:
* **8** (or omitted) 8-connected line.
* **4** 4-connected line.
* **CV_AA** antialiased line.
:param img:The image
:param pt1:First point of the line segment
:param pt2:Second point of the line segment
:param color:Line color
:param thickness:Line thickness
:param lineType:Type of the line:
* **8** (or omitted) 8-connected line.
* **4** 4-connected line.
* **CV_AA** antialiased line.
:param shift:Number of fractional bits in the point coordinates
The function
``line``
draws the line segment between
``pt1``
and
``pt2``
points in the image. The line is
:param shift:Number of fractional bits in the point coordinates
The function ``line`` draws the line segment between ``pt1`` and ``pt2`` points in the image. The line is
clipped by the image boundaries. For non-antialiased lines
with integer coordinates the 8-connected or 4-connected Bresenham
algorithm is used. Thick lines are drawn with rounding endings.
Antialiased lines are drawn using Gaussian filtering. To specify
the line color, the user may use the macro
``CV_RGB(r, g, b)``
.
the line color, the user may use the macro ``CV_RGB(r, g, b)`` .
..index:: LineIterator
@ -534,22 +277,10 @@ the line color, the user may use the macro
LineIterator
------------
`id=0.913176469223 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/core/LineIterator>`__
..ctype:: LineIterator
Class for iterating pixels on a raster line ::
Class for iterating pixels on a raster line
::
class LineIterator
{
public:
@ -566,205 +297,109 @@ Class for iterating pixels on a raster line
// move the iterator to the next pixel
LineIterator& operator ++();
LineIterator operator ++(int);
// internal state of the iterator
uchar* ptr;
int err, count;
int minusDelta, plusDelta;
int minusStep, plusStep;
};
..
The class
``LineIterator``
is used to get each pixel of a raster line. It can be treated as versatile implementation of the Bresenham algorithm, where you can stop at each pixel and do some extra processing, for example, grab pixel values along the line, or draw a line with some effect (e.g. with XOR operation).
The number of pixels along the line is store in
``LineIterator::count``
.
The class ``LineIterator`` is used to get each pixel of a raster line. It can be treated as versatile implementation of the Bresenham algorithm, where you can stop at each pixel and do some extra processing, for example, grab pixel values along the line, or draw a line with some effect (e.g. with XOR operation).
::
The number of pixels along the line is store in ``LineIterator::count`` . ::
// grabs pixels along the line (pt1, pt2)
// from 8-bit 3-channel image to the buffer
LineIterator it(img, pt1, pt2, 8);
vector<Vec3b> buf(it.count);
for(int i = 0; i < it.count; i++, ++it)
buf[i] = *(const Vec3b)*it;
..
..index:: rectangle
cv::rectangle
-------------
`id=0.494030339931 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/core/rectangle>`__
..cfunction:: void rectangle(Mat\& img, Point pt1, Point pt2, const Scalar\& color, int thickness=1, int lineType=8, int shift=0)
Draws a simple, thick, or filled up-right rectangle.
:param img:Image
:param pt1:One of the rectangle's vertices
:param pt2:Opposite to ``pt1`` rectangle vertex
:param color:Rectangle color or brightness (grayscale image)
:param img:Image
:param pt1:One of the rectangle's vertices
:param pt2:Opposite to ``pt1`` rectangle vertex
:param color:Rectangle color or brightness (grayscale image)
:param thickness:Thickness of lines that make up the rectangle. Negative values, e.g. ``CV_FILLED`` , mean that the function has to draw a filled rectangle.
:param lineType:Type of the line, see :func:`line` description
:param shift:Number of fractional bits in the point coordinates
The function
``rectangle``
draws a rectangle outline or a filled rectangle, which two opposite corners are
``pt1``
and
``pt2``
.
:param thickness:Thickness of lines that make up the rectangle. Negative values, e.g. ``CV_FILLED`` , mean that the function has to draw a filled rectangle.
:param lineType:Type of the line, see :func:`line` description
..index:: polylines
:param shift:Number of fractional bits in the point coordinates
The function ``rectangle`` draws a rectangle outline or a filled rectangle, which two opposite corners are ``pt1`` and ``pt2`` .
..index:: polylines
cv::polylines
-------------
..cfunction:: void polylines(Mat\& img, const Point** pts, const int* npts, int ncontours, bool isClosed, const Scalar\& color, int thickness=1, int lineType=8, int shift=0 )
`id=0.550422277453 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/core/polylines>`__
Draws several polygonal curves
:param img:The image
:param pts:Array of polygonal curves
:param npts:Array of polygon vertex counters
..cfunction:: void polylines(Mat\& img, const Point** pts, const int* npts, int ncontours, bool isClosed, const Scalar\& color, int thickness=1, int lineType=8, int shift=0 )
Draws several polygonal curves
:param ncontours:The number of curves
:param isClosed:Indicates whether the drawn polylines are closed or not. If they are closed, the function draws the line from the last vertex of each curve to its first vertex
:param color:Polyline color
:param thickness:Thickness of the polyline edges
:param lineType:Type of the line segments, see :func:`line` description
:param img:The image
:param pts:Array of polygonal curves
:param npts:Array of polygon vertex counters
:param ncontours:The number of curves
:param isClosed:Indicates whether the drawn polylines are closed or not. If they are closed, the function draws the line from the last vertex of each curve to its first vertex
:param color:Polyline color
:param thickness:Thickness of the polyline edges
:param lineType:Type of the line segments, see :func:`line` description
:param shift:The number of fractional bits in the vertex coordinates
The function
``polylines``
draws one or more polygonal curves.
:param shift:The number of fractional bits in the vertex coordinates
The function ``polylines`` draws one or more polygonal curves.
..index:: putText
cv::putText
-----------
..cfunction:: void putText( Mat\& img, const string\& text, Point org, int fontFace, double fontScale, Scalar color, int thickness=1, int lineType=8, bool bottomLeftOrigin=false )
`id=0.164290316532 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/core/putText>`__
Draws a text string
:param img:The image
:param text:The text string to be drawn
:param org:The bottom-left corner of the text string in the image
..cfunction:: void putText( Mat\& img, const string\& text, Point org, int fontFace, double fontScale, Scalar color, int thickness=1, int lineType=8, bool bottomLeftOrigin=false )
:param fontFace:The 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.
Draws a text string
:param fontScale:The font scale factor that is multiplied by the font-specific base size
:param color:The text color
:param thickness:Thickness of the lines used to draw the text
:param lineType:The line type; see ``line`` for details
:param bottomLeftOrigin:When true, the image data origin is at the bottom-left corner, otherwise it's at the top-left corner
:param img:The image
:param text:The text string to be drawn
:param org:The bottom-left corner of the text string in the image
:param fontFace:The font type, one of ``FONT_HERSHEY_SIMPLEX`` , ``FONT_HERSHEY_PLAIN`` ,
All the OpenCV classes and functions are placed into *"cv"* namespace. Therefore, to access this functionality from your code, use
``cv::`` specifier or ``using namespace cv;`` directive:
All the OpenCV classes and functions are placed into *"cv"* namespace. Therefore, to access this functionality from your code, use ``cv::`` specifier or ``using namespace cv;`` directive:
..code-block:: c
#include "opencv2/core/core.hpp"
...
cv::Mat H = cv::findHomography(points1, points2, CV_RANSAC, 5);
...
or
or ::
::
#include "opencv2/core/core.hpp"
using namespace cv;
...
@ -51,16 +48,13 @@ or
...
It is probable that some of the current or future OpenCV external names conflict with STL
or other libraries, in this case use explicit namespace specifiers to resolve the name conflicts:
or other libraries, in this case use explicit namespace specifiers to resolve the name conflicts: ::
@ -68,13 +62,11 @@ OpenCV handles all the memory automatically.
First of all, ``std::vector``, ``Mat`` and other data structures used by the functions and methods have destructors that deallocate the underlying memory buffers when needed.
Secondly, in the case of ``Mat`` this *when needed* means that the destructors do not always deallocate the buffers, they take into account possible data sharing. That is, destructor decrements the reference counter, associated with the matrix data buffer, and the buffer is deallocated if and only if the reference counter reaches zero, that is, when no other structures refer to the same buffer. Similarly, when ``Mat`` instance is copied, not actual data is really copied; instead, the associated with it reference counter is incremented to memorize that there is another owner of the same data. There is also ``Mat::clone`` method that creates a full copy of the matrix data. Here is the example
Secondly, in the case of ``Mat`` this *when needed* means that the destructors do not always deallocate the buffers, they take into account possible data sharing. That is, destructor decrements the reference counter, associated with the matrix data buffer, and the buffer is deallocated if and only if the reference counter reaches zero, that is, when no other structures refer to the same buffer. Similarly, when ``Mat`` instance is copied, not actual data is really copied; instead, the associated with it reference counter is incremented to memorize that there is another owner of the same data. There is also ``Mat::clone`` method that creates a full copy of the matrix data. Here is the example ::
::
// create a big 8Mb matrix
Mat A(1000, 1000, CV_64F);
// create another header for the same matrix;
// this is instant operation, regardless of the matrix size.
Mat B = A;
@ -82,7 +74,7 @@ Secondly, in the case of ``Mat`` this *when needed* means that the destructors d
Mat C = B.row(3);
// now create a separate copy of the matrix
Mat D = B.clone();
// copy the 5-th row of B to C, that is, copy the 5-th row of A
// copy the 5-th row of B to C, that is, copy the 5-th row of A
// to the 3-rd row of A.
B.row(5).copyTo(C);
// now let A and D share the data; after that the modified version
@ -91,8 +83,8 @@ Secondly, in the case of ``Mat`` this *when needed* means that the destructors d
// now make B an empty matrix (which references no memory buffers),
// but the modified version of A will still be referenced by C,
// despite that C is just a single row of the original A
B.release();
B.release();
// finally, make a full copy of C. In result, the big modified
// matrix will be deallocated, since it's not referenced by anyone
C = C.clone();
@ -107,7 +99,6 @@ one can use::
That is, ``Ptr<T> ptr`` incapsulates a pointer to ``T`` instance and a reference counter associated with the pointer. See ``Ptr`` description for details.
..todo::
Should we replace Ptr<> with the semi-standard shared_ptr<>?
@ -118,17 +109,17 @@ Automatic Allocation of the Output Data
OpenCV does not only deallocate the memory automatically, it can also allocate memory for the output function parameters automatically most of the time. That is, if a function has one or more input arrays (``cv::Mat`` instances) and some output arrays, the output arrays automatically allocated or reallocated. The size and type of the output arrays are determined from the input arrays' size and type. If needed, the functions take extra parameters that help to figure out the output array properties.
Here is the example: ::
#include "cv.h"
#include "highgui.h"
using namespace cv;
int main(int, char**)
{
VideoCapture cap(0);
if(!cap.isOpened()) return -1;
Mat frame, edges;
namedWindow("edges",1);
for(;;)
@ -150,15 +141,14 @@ The key component of this technology is the method ``Mat::create``. It takes the
Some notable exceptions from this scheme are ``cv::mixChannels``, ``cv::RNG::fill`` and a few others functions and methods. They are not able to allocate the output array, so the user has to do that in advance.
Saturation Arithmetics
----------------------
As computer vision library, OpenCV deals a lot with image pixels that are often encoded in a compact 8- or 16-bit per channel form and thus have a limited value range. Furthermore, certain operations on images, like color space conversions, brightness/contrast adjustments, sharpening, complex interpolation (bi-cubic, Lanczos) can produce values out of the available range. If we just store the lowest 8 (16) bit of the result, that will result in some visual artifacts and may affect the further image analysis. To solve this problem, we use so-called *saturation* arithmetics, e.g. to store ``r``, a result of some operation, to 8-bit image, we find the nearest value within 0..255 range:
As computer vision library, OpenCV deals a lot with image pixels that are often encoded in a compact 8- or 16-bit per channel form and thus have a limited value range. Furthermore, certain operations on images, like color space conversions, brightness/contrast adjustments, sharpening, complex interpolation (bi-cubic, Lanczos) can produce values out of the available range. If we just store the lowest 8 (16) bit of the result, that will result in some visual artifacts and may affect the further image analysis. To solve this problem, we use so-called *saturation* arithmetics, e.g. to store ``r``, a result of some operation, to 8-bit image, we find the nearest value within 0..255 range:
..math::
I(x,y)= \min ( \max (\textrm{round}(r), 0), 255)
I(x,y)= \min ( \max (\textrm{round}(r), 0), 255)
The similar rules are applied to 8-bit signed and 16-bit signed and unsigned types. This semantics is used everywhere in the library. In C++ code it is done using ``saturate_cast<>`` functions that resembler the standard C++ cast operations. Here is the implementation of the above formula::
@ -166,7 +156,6 @@ The similar rules are applied to 8-bit signed and 16-bit signed and unsigned typ
where ``cv::uchar`` is OpenCV's 8-bit unsigned integer type. In optimized SIMD code we use specialized instructions, like SSE2' ``paddusb``, ``packuswb`` etc. to achieve exactly the same behavior as in C++ code.
Fixed Pixel Types. Limited Use of Templates
-------------------------------------------
@ -182,18 +171,17 @@ Because of this, there is a limited fixed set of primitive data types that the l
* 32-bit floating-point number (float)
* 64-bit floating-point number (double)
* a tuple of several elements, where all elements have the same type (one of the above). Array, which elements are such tuples, are called multi-channel arrays, as opposite to the single-channel arrays, which elements are scalar values. The maximum possible number of channels is defined by ``CV_CN_MAX`` constant (which is not smaller than 32).
..todo::
Need we extend the above list? Shouldn't we throw away 8-bit signed (schar)?
Multi-channel (``n``-channel) types can be specified using ``CV_8UC1`` ... ``CV_64FC4`` constants (for number of channels from 1 to 4), or using ``CV_8UC(n)`` ... ``CV_64FC(n)`` or ``CV_MAKETYPE(CV_8U, n)`` ... ``CV_MAKETYPE(CV_64F, n)`` macros when the number of channels is more than 4 or unknown at compile time.
..note::
``CV_32FC1 == CV_32F``, ``CV_32FC2 == CV_32FC(2) == CV_MAKETYPE(CV_32F, 2)`` and ``CV_MAKETYPE(depth, n) == ((x&7)<<3) + (n-1)``, that is, the type constant is formed from the ``depth``, taking the lowest 3 bits, and the number of channels minus 1, taking the next ``log2(CV_CN_MAX)`` bits.
..note::``CV_32FC1 == CV_32F``, ``CV_32FC2 == CV_32FC(2) == CV_MAKETYPE(CV_32F, 2)`` and ``CV_MAKETYPE(depth, n) == ((x&7)<<3) + (n-1)``, that is, the type constant is formed from the ``depth``, taking the lowest 3 bits, and the number of channels minus 1, taking the next ``log2(CV_CN_MAX)`` bits.
Here are some examples::
@ -219,7 +207,6 @@ The subset of supported types for each functions has been defined from practical
Should we include such a table into the standard?
Should we specify minimum "must-have" set of supported formats for each functions?
Error handling
--------------
@ -227,10 +214,8 @@ OpenCV uses exceptions to signal about the critical errors. When the input data
The exceptions can be instances of ``cv::Exception`` class or its derivatives. In its turn, ``cv::Exception`` is a derivative of std::exception, so it can be gracefully handled in the code using other standard C++ library components.
The exception is typically thrown using ``CV_Error(errcode, description)`` macro, or its printf-like ``CV_Error_(errcode, printf-spec, (printf-args))`` variant, or using ``CV_Assert(condition)`` macro that checks the condition and throws exception when it is not satisfied. For performance-critical code there is ``CV_DbgAssert(condition)`` that is only retained in Debug configuration. Thanks to the automatic memory management, all the intermediate buffers are automatically deallocated in the case of sudden error; user only needs to put a try statement to catch the exceptions, if needed:
The exception is typically thrown using ``CV_Error(errcode, description)`` macro, or its printf-like ``CV_Error_(errcode, printf-spec, (printf-args))`` variant, or using ``CV_Assert(condition)`` macro that checks the condition and throws exception when it is not satisfied. For performance-critical code there is ``CV_DbgAssert(condition)`` that is only retained in Debug configuration. Thanks to the automatic memory management, all the intermediate buffers are automatically deallocated in the case of sudden error; user only needs to put a try statement to catch the exceptions, if needed: ::
::
try
{
... // call OpenCV
@ -241,7 +226,6 @@ The exception is typically thrown using ``CV_Error(errcode, description)`` macro
. The number of elements must match the number passed to
:func:`allocate`
.
The generic function ``deallocate`` deallocates the buffer allocated with
:func:`allocate` . The number of elements must match the number passed to
:func:`allocate` .
..index:: CV_Assert
@ -153,152 +73,57 @@ deallocates the buffer allocated with
CV_Assert
---------
`id=0.132247699783 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/core/CV_Assert>`__
..cfunction:: CV_Assert(expr)
Checks a condition at runtime.
Checks a condition at runtime. ::
::
#define CV_Assert( expr ) ...
#define CV_DbgAssert(expr) ...
..
:param expr:The checked expression
:param expr:The checked expression
The macros
``CV_Assert``
and
``CV_DbgAssert``
evaluate the specified expression and if it is 0, the macros raise an error (see
:func:`error`
). The macro
``CV_Assert``
checks the condition in both Debug and Release configurations, while
``CV_DbgAssert``
is only retained in the Debug configuration.
The macros ``CV_Assert`` and ``CV_DbgAssert`` evaluate the specified expression and if it is 0, the macros raise an error (see
:func:`error` ). The macro ``CV_Assert`` checks the condition in both Debug and Release configurations, while ``CV_DbgAssert`` is only retained in the Debug configuration.
..index:: error
cv::error
---------
`id=0.274198769781 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/core/error>`__
:param code:The error code, normally, a negative value. The list of pre-defined error codes can be found in ``cxerror.h`` :param msg: Text of the error message
:param args:printf-like formatted error message in parantheses
The function and the helper macros ``CV_Error`` and ``CV_Error_`` call the error handler. Currently, the error handler prints the error code ( ``exc.code`` ), the context ( ``exc.file``,``exc.line`` and the error message ``exc.err`` to the standard error stream ``stderr`` . In Debug configuration it then provokes memory access violation, so that the execution stack and all the parameters can be analyzed in debugger. In Release configuration the exception ``exc`` is thrown.
:param exc:The exception to throw
:param code:The error code, normally, a negative value. The list of pre-defined error codes can be found in ``cxerror.h``
:param msg:Text of the error message
:param args:printf-like formatted error message in parantheses
The function and the helper macros
``CV_Error``
and
``CV_Error_``
call the error handler. Currently, the error handler prints the error code (
``exc.code``
), the context (
``exc.file``
,
``exc.line``
and the error message
``exc.err``
to the standard error stream
``stderr``
. In Debug configuration it then provokes memory access violation, so that the execution stack and all the parameters can be analyzed in debugger. In Release configuration the exception
``exc``
is thrown.
The macro
``CV_Error_``
can be used to construct the error message on-fly to include some dynamic information, for example:
The macro ``CV_Error_`` can be used to construct the error message on-fly to include some dynamic information, for example: ::
::
// note the extra parentheses around the formatted text message
CV_Error_(CV_StsOutOfRange,
("the matrix element (
i, j, mtx.at<float>(i,j)))
..
..index:: Exception
.._Exception:
Exception
---------
`id=0.792198322059 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/core/Exception>`__
..ctype:: Exception
The exception class passed to error ::
The exception class passed to error
::
class Exception
{
public:
@ -308,7 +133,7 @@ The exception class passed to error
const string& _func, const string& _file, int _line);
Exception(const Exception& exc);
Exception& operator = (const Exception& exc);
// the error code
int code;
// the error text message
@ -320,249 +145,115 @@ The exception class passed to error
// the source file line where the error happened
int line;
};
..
The class
``Exception``
encapsulates all or almost all the necessary information about the error happened in the program. The exception is usually constructed and thrown implicitly, via
``CV_Error``
and
``CV_Error_``
macros, see
:func:`error`
.
The class ``Exception`` encapsulates all or almost all the necessary information about the error happened in the program. The exception is usually constructed and thrown implicitly, via ``CV_Error`` and ``CV_Error_`` macros, see
:func:`error` .
..index:: fastMalloc
cv::fastMalloc
--------------
`id=0.913748026438 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/core/fastMalloc>`__
..cfunction:: void* fastMalloc(size_t size)
Allocates aligned memory buffer
:param size:The allocated buffer size
:param size:The allocated buffer size
The function allocates buffer of the specified size and returns it. When the buffer size is 16 bytes or more, the returned buffer is aligned on 16 bytes.
..index:: fastFree
cv::fastFree
------------
`id=0.486348253472 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/core/fastFree>`__
..cfunction:: void fastFree(void* ptr)
Deallocates memory buffer
:param ptr:Pointer to the allocated buffer
:param ptr:Pointer to the allocated buffer
The function deallocates the buffer, allocated with
:func:`fastMalloc`
.
The function deallocates the buffer, allocated with
:func:`fastMalloc` .
If NULL pointer is passed, the function does nothing.
..index:: format
cv::format
----------
`id=0.359045522761 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/core/format>`__
, but forms and returns STL string. It can be used for form the error message in
:func:`Exception`
constructor.
The function acts like ``sprintf`` , but forms and returns STL string. It can be used for form the error message in
:func:`Exception` constructor.
..index:: getNumThreads
cv::getNumThreads
-----------------
`id=0.665594834701 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/core/getNumThreads>`__
..cfunction:: int getNumThreads()
Returns the number of threads used by OpenCV
The function returns the number of threads that is used by OpenCV.
See also:
:func:`setNumThreads`
,
:func:`getThreadNum`
.
See also:
:func:`setNumThreads`,:func:`getThreadNum` .
..index:: getThreadNum
cv::getThreadNum
----------------
`id=0.835208450402 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/core/getThreadNum>`__
..cfunction:: int getThreadNum()
Returns index of the currently executed thread
The function returns 0-based index of the currently executed thread. The function is only valid inside a parallel OpenMP region. When OpenCV is built without OpenMP support, the function always returns 0.
See also:
:func:`setNumThreads`
,
:func:`getNumThreads`
.
See also:
:func:`setNumThreads`,:func:`getNumThreads` .
..index:: getTickCount
cv::getTickCount
----------------
`id=0.682548115061 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/core/getTickCount>`__
..cfunction:: int64 getTickCount()
Returns the number of ticks
The function returns the number of ticks since the certain event (e.g. when the machine was turned on).
It can be used to initialize
:func:`RNG`
or to measure a function execution time by reading the tick count before and after the function call. See also the tick frequency.
It can be used to initialize
:func:`RNG` or to measure a function execution time by reading the tick count before and after the function call. See also the tick frequency.
..index:: getTickFrequency
cv::getTickFrequency
--------------------
`id=0.85013360741 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/core/getTickFrequency>`__
..cfunction:: double getTickFrequency()
Returns the number of ticks per second
The function returns the number of ticks per second.
That is, the following code computes the execution time in seconds.
That is, the following code computes the execution time in seconds. ::
::
double t = (double)getTickCount();
// do something ...
t = ((double)getTickCount() - t)/getTickFrequency();
..
..index:: setNumThreads
cv::setNumThreads
-----------------
`id=0.215563071229 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/core/setNumThreads>`__
..cfunction:: void setNumThreads(int nthreads)
Sets the number of threads used by OpenCV
:param nthreads:The number of threads used by OpenCV
The function sets the number of threads used by OpenCV in parallel OpenMP regions. If ``nthreads=0`` , the function will use the default number of threads, which is usually equal to the number of the processing cores.
:param nthreads:The number of threads used by OpenCV
The function sets the number of threads used by OpenCV in parallel OpenMP regions. If
``nthreads=0``
, the function will use the default number of threads, which is usually equal to the number of the processing cores.
Add descriptors to train descriptor collection. If collection trainDescCollectionis not empty
the new descriptors are added to existing train descriptors.
:param descriptors:Descriptors to add. Each ``descriptors[i]`` is a set of descriptors
from the same (one) train image.
:param descriptors:Descriptors to add. Each ``descriptors[i]`` is a set of descriptors
from the same (one) train image.
..index:: DescriptorMatcher::getTrainDescriptors
cv::DescriptorMatcher::getTrainDescriptors
------------------------------------------
`id=0.354691082433 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/features2d/DescriptorMatcher%3A%3AgetTrainDescriptors>`__
Find the best match for each descriptor from a query set with train descriptors.
Supposed that the query descriptors are of keypoints detected on the same query image.
In first variant of this method train descriptors are set as input argument and
supposed that they are of keypoints detected on the same train image. In second variant
Supposed that the query descriptors are of keypoints detected on the same query image.
In first variant of this method train descriptors are set as input argument and
supposed that they are of keypoints detected on the same train image. In second variant
of the method train descriptors collection that was set using addmethod is used.
Optional mask (or masks) can be set to describe which descriptors can be matched. queryDescriptors[i]can be matched with trainDescriptors[j]only if mask.at<uchar>(i,j)is non-zero.
:param queryDescriptors, trainDescriptors, mask, masks:See in :func:`DescriptorMatcher::match` .
:param matches:Mathes. Each ``matches[i]`` is k or less matches for the same query descriptor.
:param k:Count of best matches will be found per each query descriptor (or less if it's not possible).
:param queryDescriptors, trainDescriptors, mask, masks:See in :func:`DescriptorMatcher::match` .
:param matches:Mathes. Each ``matches[i]`` is k or less matches for the same query descriptor.
:param k:Count of best matches will be found per each query descriptor (or less if it's not possible).
:param compactResult:It's used when mask (or masks) is not empty. If ``compactResult`` is false ``matches`` vector will have the same size as ``queryDescriptors`` rows. If ``compactResult``
is true ``matches`` vector will not contain matches for fully masked out query descriptors.
:param compactResult:It's used when mask (or masks) is not empty. If ``compactResult`` is false ``matches`` vector will have the same size as ``queryDescriptors`` rows. If ``compactResult`` is true ``matches`` vector will not contain matches for fully masked out query descriptors.
..index:: DescriptorMatcher::radiusMatch
cv::DescriptorMatcher::radiusMatch
----------------------------------
`id=0.763278154174 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/features2d/DescriptorMatcher%3A%3AradiusMatch>`__
Now the following matcher types are supported: ``"BruteForce"`` (it uses ``L2`` ), ``"BruteForce-L1"``,``"BruteForce-Hamming"``,``"BruteForce-HammingLUT"``,``"FlannBased"`` .
..index:: BruteForceMatcher
@ -472,63 +259,40 @@ Now the following matcher types are supported:
BruteForceMatcher
-----------------
`id=0.47821275438 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/features2d/BruteForceMatcher>`__
..ctype:: BruteForceMatcher
Brute-force descriptor matcher. For each descriptor in the first set, this matcher finds the closest
descriptor in the second set by trying each one. This descriptor matcher supports masking
permissible matches between descriptor sets.
descriptor in the second set by trying each one. This descriptor matcher supports masking
permissible matches between descriptor sets. ::
::
template<class Distance>
class BruteForceMatcher : public DescriptorMatcher
@ -3,25 +3,14 @@ Common Interfaces of Generic Descriptor Matchers
..highlight:: cpp
Matchers of keypoint descriptors in OpenCV have wrappers with common interface that enables to switch easily
between different algorithms solving the same problem. This section is devoted to matching descriptors
that can not be represented as vectors in a multidimensional space.
``GenericDescriptorMatcher``
is a more generic interface for descriptors. It does not make any assumptions about descriptor representation.
Every descriptor with
:func:`DescriptorExtractor`
interface has a wrapper with
``GenericDescriptorMatcher``
interface (see
:func:`VectorDescriptorMatcher`
).
There are descriptors such as One way descriptor and Ferns that have
``GenericDescriptorMatcher``
interface implemented, but do not support
:func:`DescriptorExtractor`
.
Matchers of keypoint descriptors in OpenCV have wrappers with common interface that enables to switch easily
between different algorithms solving the same problem. This section is devoted to matching descriptors
that can not be represented as vectors in a multidimensional space. ``GenericDescriptorMatcher`` is a more generic interface for descriptors. It does not make any assumptions about descriptor representation.
Every descriptor with
:func:`DescriptorExtractor` interface has a wrapper with ``GenericDescriptorMatcher`` interface (see
:func:`VectorDescriptorMatcher` ).
There are descriptors such as One way descriptor and Ferns that have ``GenericDescriptorMatcher`` interface implemented, but do not support
:func:`DescriptorExtractor` .
..index:: GenericDescriptorMatcher
@ -29,61 +18,42 @@ interface implemented, but do not support
GenericDescriptorMatcher
------------------------
`id=0.973387347242 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/features2d/GenericDescriptorMatcher>`__
..ctype:: GenericDescriptorMatcher
Abstract interface for a keypoint descriptor extracting and matching.
There is
:func:`DescriptorExtractor`
and
:func:`DescriptorMatcher`
for these purposes too, but their interfaces are intended for descriptors
represented as vectors in a multidimensional space.
``GenericDescriptorMatcher``
is a more generic interface for descriptors.
As
:func:`DescriptorMatcher`
,
``GenericDescriptorMatcher``
has two groups
Abstract interface for a keypoint descriptor extracting and matching.
There is
:func:`DescriptorExtractor` and
:func:`DescriptorMatcher` for these purposes too, but their interfaces are intended for descriptors
represented as vectors in a multidimensional space. ``GenericDescriptorMatcher`` is a more generic interface for descriptors.
As
:func:`DescriptorMatcher`,``GenericDescriptorMatcher`` has two groups
of match methods: for matching keypoints of one image with other image or
`id=0.520364236881 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/features2d/GenericDescriptorMatcher%3A%3AgetTrainImages>`__
`id=0.179197628979 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/features2d/GenericDescriptorMatcher%3A%3AgetTrainKeypoints>`__
`id=0.208711469863 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/features2d/GenericDescriptorMatcher%3A%3AisMaskSupported>`__
`id=0.732845229707 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/features2d/GenericDescriptorMatcher%3A%3AradiusMatch>`__
`id=0.355574799377 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/features2d/BOWImgDescriptorExtractor%3A%3ABOWImgDescriptorExtractor>`__
`id=0.592484692408 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/features2d/BOWImgDescriptorExtractor%3A%3AsetVocabulary>`__
`id=0.0185667539631 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/features2d/BOWImgDescriptorExtractor%3A%3AgetVocabulary>`__
`id=0.758326749957 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/features2d/BOWImgDescriptorExtractor%3A%3AdescriptorSize>`__
..cfunction:: int BOWImgDescriptorExtractor::descriptorSize() const
Returns image discriptor size, if vocabulary was set, and 0 otherwise.
`id=0.940227909801 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/features2d/BOWImgDescriptorExtractor%3A%3AdescriptorType>`__
..cfunction:: int BOWImgDescriptorExtractor::descriptorType() const
`id=0.542572017346 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/gpu/gpu%3A%3ADevMem2D_>`__
..ctype:: gpu::DevMem2D_
This is a simple lightweight class that encapsulate pitched memory on GPU. It is intended to pass to nvcc-compiled code, i.e. CUDA kernels. So it is used internally by OpenCV and by users writes own device code. Its members can be called both from host and from device code. ::
template <typename T> struct DevMem2D_
{
int cols;
int rows;
T* data;
size_t step;
This is a simple lightweight class that encapsulate pitched memory on GPU. It is intended to pass to nvcc-compiled code, i.e. CUDA kernels. So it is used internally by OpenCV and by users writes own device code. Its members can be called both from host and from device code.
DevMem2D_(int rows_, int cols_, T *data_, size_t step_);
template <typename U>
explicit DevMem2D_(const DevMem2D_<U>& d);
typedef T elem_type;
enum { elem_size = sizeof(elem_type) };
__CV_GPU_HOST_DEVICE__ size_t elemSize() const;
/* returns pointer to the beggining of given image row */
__CV_GPU_HOST_DEVICE__ T* ptr(int y = 0);
__CV_GPU_HOST_DEVICE__ const T* ptr(int y = 0) const;
};
__CV_GPU_HOST_DEVICE__ size_t elemSize() const;
/* returns pointer to the beggining of given image row */
__CV_GPU_HOST_DEVICE__ T* ptr(int y = 0);
__CV_GPU_HOST_DEVICE__ const T* ptr(int y = 0) const;
};
..
..index:: gpu::PtrStep_
.._gpu::PtrStep_:
gpu::PtrStep_
-------------
`id=0.130599760293 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/gpu/gpu%3A%3APtrStep_>`__
..ctype:: gpu::PtrStep_
This is structure is similar to DevMem2D_but contains only pointer and row step. Width and height fields are excluded due to performance reasons. The structure is for internal use or for users who write own device code. ::
template<typename T> struct PtrStep_
{
T* data;
size_t step;
This is structure is similar to DevMem2D
_
but contains only pointer and row step. Width and height fields are excluded due to performance reasons. The structure is for internal use or for users who write own device code.
::
PtrStep_();
PtrStep_(const DevMem2D_<T>& mem);
typedef T elem_type;
enum { elem_size = sizeof(elem_type) };
template<typename T> struct PtrStep_
{
T* data;
size_t step;
PtrStep_();
PtrStep_(const DevMem2D_<T>& mem);
typedef T elem_type;
enum { elem_size = sizeof(elem_type) };
__CV_GPU_HOST_DEVICE__ size_t elemSize() const;
__CV_GPU_HOST_DEVICE__ T* ptr(int y = 0);
__CV_GPU_HOST_DEVICE__ const T* ptr(int y = 0) const;
};
__CV_GPU_HOST_DEVICE__ size_t elemSize() const;
__CV_GPU_HOST_DEVICE__ T* ptr(int y = 0);
__CV_GPU_HOST_DEVICE__ const T* ptr(int y = 0) const;
};
..
..index:: gpu::PtrElemStrp_
.._gpu::PtrElemStrp_:
gpu::PtrElemStrp_
-----------------
`id=0.837109179392 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/gpu/gpu%3A%3APtrElemStrp_>`__
..ctype:: gpu::PtrElemStrp_
This is structure is similar to DevMem2D_but contains only pointer and row step in elements. Width and height fields are excluded due to performance reasons. This class is can only be constructed if sizeof(T) is a multiple of 256. The structure is for internal use or for users who write own device code. ::
This is structure is similar to DevMem2D
_
but contains only pointer and row step in elements. Width and height fields are excluded due to performance reasons. This class is can only be constructed if sizeof(T) is a multiple of 256. The structure is for internal use or for users who write own device code.
::
template<typename T> struct PtrElemStep_ : public PtrStep_<T>
{
PtrElemStep_(const DevMem2D_<T>& mem);
__CV_GPU_HOST_DEVICE__ T* ptr(int y = 0);
__CV_GPU_HOST_DEVICE__ const T* ptr(int y = 0) const;
};
template<typename T> struct PtrElemStep_ : public PtrStep_<T>
{
PtrElemStep_(const DevMem2D_<T>& mem);
__CV_GPU_HOST_DEVICE__ T* ptr(int y = 0);
__CV_GPU_HOST_DEVICE__ const T* ptr(int y = 0) const;
};
..
..index:: gpu::GpuMat
.._gpu::GpuMat:
gpu::GpuMat
-----------
..ctype:: gpu::GpuMat
`id=0.816128758115 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/gpu/gpu%3A%3AGpuMat>`__
The base storage class for GPU memory with reference counting. Its interface is almost
:func:`Mat` interface with some limitations, so using it won't be a problem. The limitations are no arbitrary dimensions support (only 2D), no functions that returns references to its data (because references on GPU are not valid for CPU), no expression templates technique support. Because of last limitation please take care with overloaded matrix operators - they cause memory allocations. The GpuMat class is convertible to
and
so it can be passed to directly to kernel.
..ctype:: gpu::GpuMat
**Please note:**
In contrast with
:func:`Mat` , In most cases ``GpuMat::isContinuous() == false`` , i.e. rows are aligned to size depending on hardware. Also single row GpuMat is always a continuous matrix. ::
class CV_EXPORTS GpuMat
{
public:
//! default constructor
GpuMat();
GpuMat(int rows, int cols, int type);
GpuMat(Size size, int type);
The base storage class for GPU memory with reference counting. Its interface is almost
:func:`Mat`
interface with some limitations, so using it won't be a problem. The limitations are no arbitrary dimensions support (only 2D), no functions that returns references to its data (because references on GPU are not valid for CPU), no expression templates technique support. Because of last limitation please take care with overloaded matrix operators - they cause memory allocations. The GpuMat class is convertible to
and
so it can be passed to directly to kernel.
**Please note:**
In contrast with
:func:`Mat`
, In most cases
``GpuMat::isContinuous() == false``
, i.e. rows are aligned to size depending on hardware. Also single row GpuMat is always a continuous matrix.
::
class CV_EXPORTS GpuMat
{
public:
//! default constructor
GpuMat();
GpuMat(int rows, int cols, int type);
GpuMat(Size size, int type);
.....
//! builds GpuMat from Mat. Perfom blocking upload to device.
explicit GpuMat (const Mat& m);
//! returns lightweight DevMem2D_ structure for passing
//to nvcc-compiled code. Contains size, data ptr and step.
template <class T> operator DevMem2D_<T>() const;
template <class T> operator PtrStep_<T>() const;
//! pefroms blocking upload data to GpuMat.
void upload(const cv::Mat& m);
void upload(const CudaMem& m, Stream& stream);
//! downloads data from device to host memory. Blocking calls.
operator Mat() const;
void download(cv::Mat& m) const;
//! download async
void download(CudaMem& m, Stream& stream) const;
};
.....
//! builds GpuMat from Mat. Perfom blocking upload to device.
explicit GpuMat (const Mat& m);
//! returns lightweight DevMem2D_ structure for passing
//to nvcc-compiled code. Contains size, data ptr and step.
template <class T> operator DevMem2D_<T>() const;
template <class T> operator PtrStep_<T>() const;
//! pefroms blocking upload data to GpuMat.
void upload(const cv::Mat& m);
void upload(const CudaMem& m, Stream& stream);
//! downloads data from device to host memory. Blocking calls.
operator Mat() const;
void download(cv::Mat& m) const;
//! download async
void download(CudaMem& m, Stream& stream) const;
};
..
**Please note:**
Is it a bad practice to leave static or global GpuMat variables allocated, i.e. to rely on its destructor. That is because destruction order of such variables and CUDA context is undefined and GPU memory release function returns error if CUDA context has been destroyed before.
See also:
:func:`Mat`
Is it a bad practice to leave static or global GpuMat variables allocated, i.e. to rely on its destructor. That is because destruction order of such variables and CUDA context is undefined and GPU memory release function returns error if CUDA context has been destroyed before.
See also:
:func:`Mat`
..index:: gpu::CudaMem
.._gpu::CudaMem:
gpu::CudaMem
------------
`id=0.762477139905 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/gpu/gpu%3A%3ACudaMem>`__
..ctype:: gpu::CudaMem
This is a class with reference counting that wraps special memory type allocation functions from CUDA. Its interface is also
:func:`Mat` -like but with additional memory type parameter:
* ``ALLOC_PAGE_LOCKED`` Set page locked memory type, used commonly for fast and asynchronous upload/download data from/to GPU.
This is a class with reference counting that wraps special memory type allocation functions from CUDA. Its interface is also
:func:`Mat`
-like but with additional memory type parameter:
*
``ALLOC_PAGE_LOCKED``
Set page locked memory type, used commonly for fast and asynchronous upload/download data from/to GPU.
*
``ALLOC_ZEROCOPY``
Specifies zero copy memory allocation, i.e. with possibility to map host memory to GPU address space if supported.
*
``ALLOC_WRITE_COMBINED``
Sets write combined buffer which is not cached by CPU. Such buffers are used to supply GPU with data when GPU only reads it. The advantage is better CPU cache utilization.
Please note that allocation size of such memory types is usually limited. For more details please see "CUDA 2.2 Pinned Memory APIs" document or "CUDA
_
C Programming Guide".
::
class CV_EXPORTS CudaMem
{
public:
enum { ALLOC_PAGE_LOCKED = 1, ALLOC_ZEROCOPY = 2,
ALLOC_WRITE_COMBINED = 4 };
CudaMem(Size size, int type, int alloc_type = ALLOC_PAGE_LOCKED);
//! creates from cv::Mat with coping data
explicit CudaMem(const Mat& m, int alloc_type = ALLOC_PAGE_LOCKED);
......
void create(Size size, int type, int alloc_type = ALLOC_PAGE_LOCKED);
//! returns matrix header with disabled ref. counting for CudaMem data.
Mat createMatHeader() const;
operator Mat() const;
//! maps host memory into device address space
GpuMat createGpuMatHeader() const;
operator GpuMat() const;
//if host memory can be mapperd to gpu address space;
static bool canMapHostMemory();
int alloc_type;
};
..
* ``ALLOC_ZEROCOPY`` Specifies zero copy memory allocation, i.e. with possibility to map host memory to GPU address space if supported.
* ``ALLOC_WRITE_COMBINED`` Sets write combined buffer which is not cached by CPU. Such buffers are used to supply GPU with data when GPU only reads it. The advantage is better CPU cache utilization.
..index:: gpu::CudaMem::createMatHeader
Please note that allocation size of such memory types is usually limited. For more details please see "CUDA 2.2 Pinned Memory APIs" document or "CUDA_C Programming Guide". ::
class CV_EXPORTS CudaMem
{
public:
enum { ALLOC_PAGE_LOCKED = 1, ALLOC_ZEROCOPY = 2,
ALLOC_WRITE_COMBINED = 4 };
cv::gpu::CudaMem::createMatHeader
---------------------------------
CudaMem(Size size, int type, int alloc_type = ALLOC_PAGE_LOCKED);
`id=0.772787893445 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/gpu/gpu%3A%3ACudaMem%3A%3AcreateMatHeader>`__
//! creates from cv::Mat with coping data
explicit CudaMem(const Mat& m, int alloc_type = ALLOC_PAGE_LOCKED);
......
:func:`Mat`
void create(Size size, int type, int alloc_type = ALLOC_PAGE_LOCKED);
//! returns matrix header with disabled ref. counting for CudaMem data.
Mat createMatHeader() const;
operator Mat() const;
..cfunction:: Mat CudaMem::createMatHeader() const
//! maps host memory into device address space
GpuMat createGpuMatHeader() const;
operator GpuMat() const;
//if host memory can be mapperd to gpu address space;
static bool canMapHostMemory();
int alloc_type;
};
..
..cfunction:: CudaMem::operator Mat() const
..index:: gpu::CudaMem::createMatHeader
Creates header without reference counting to CudaMem data.
cv::gpu::CudaMem::createMatHeader
---------------------------------
:func:`Mat`
..cfunction:: Mat CudaMem::createMatHeader() const
..cfunction:: CudaMem::operator Mat() const
Creates header without reference counting to CudaMem data.
..index:: gpu::CudaMem::createGpuMatHeader
cv::gpu::CudaMem::createGpuMatHeader
------------------------------------
`id=0.759677323147 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/gpu/gpu%3A%3ACudaMem%3A%3AcreateGpuMatHeader>`__
Maps CPU memory to GPU address space and creates header without reference counting for it. This can be done only if memory was allocated with ALLOCZEROCOPYflag and if it is supported by hardware (laptops often share video and CPU memory, so address spaces can be mapped, and that eliminates extra copy).
Maps CPU memory to GPU address space and creates header without reference counting for it. This can be done only if memory was allocated with ALLOCZEROCOPYflag and if it is supported by hardware (laptops often share video and CPU memory, so address spaces can be mapped, and that eliminates extra copy).
..index:: gpu::CudaMem::canMapHostMemory
cv::gpu::CudaMem::canMapHostMemory
----------------------------------
`id=0.317724503486 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/gpu/gpu%3A%3ACudaMem%3A%3AcanMapHostMemory>`__
`id=0.153849663278 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/gpu/gpu%3A%3AStream>`__
..ctype:: gpu::Stream
This class encapsulated queue of the asynchronous calls. Some functions have overloads with additional
:func:`gpu::Stream` parameter. The overloads do initialization work (allocate output buffers, upload constants, etc.), start GPU kernel and return before results are ready. A check if all operation are complete can be performed via
:func:`gpu::Stream::queryIfComplete()` . Asynchronous upload/download have to be performed from/to page-locked buffers, i.e. using
:func:`gpu::CudaMem` or
:func:`Mat` header that points to a region of
:func:`gpu::CudaMem` .
This class encapsulated queue of the asynchronous calls. Some functions have overloads with additional
:func:`gpu::Stream`
parameter. The overloads do initialization work (allocate output buffers, upload constants, etc.), start GPU kernel and return before results are ready. A check if all operation are complete can be performed via
:func:`gpu::Stream::queryIfComplete()`
. Asynchronous upload/download have to be performed from/to page-locked buffers, i.e. using
:func:`gpu::CudaMem`
or
:func:`Mat`
header that points to a region of
:func:`gpu::CudaMem`
.
**Please note the limitation**
: currently it is not guaranteed that all will work properly if one operation will be enqueued twice with different data. Some functions use constant GPU memory and next call may update the memory before previous has been finished. But calling asynchronously different operations is safe because each operation has own constant buffer. Memory copy/upload/download/set operations to buffers hold by user are also safe.
::
class CV_EXPORTS Stream
{
public:
Stream();
~Stream();
Stream(const Stream&);
Stream& operator=(const Stream&);
bool queryIfComplete();
void waitForCompletion();
//! downloads asynchronously.
// Warning! cv::Mat must point to page locked memory
// converts matrix type, ex from float to uchar depending on type
void enqueueConvert(const GpuMat& src, GpuMat& dst, int type,
double a = 1, double b = 0);
};
: currently it is not guaranteed that all will work properly if one operation will be enqueued twice with different data. Some functions use constant GPU memory and next call may update the memory before previous has been finished. But calling asynchronously different operations is safe because each operation has own constant buffer. Memory copy/upload/download/set operations to buffers hold by user are also safe. ::
..
class CV_EXPORTS Stream
{
public:
Stream();
~Stream();
Stream(const Stream&);
Stream& operator=(const Stream&);
..index:: gpu::Stream::queryIfComplete
bool queryIfComplete();
void waitForCompletion();
//! downloads asynchronously.
// Warning! cv::Mat must point to page locked memory
`id=0.312772323299 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/gpu/gpu%3A%3AStreamAccessor>`__
..ctype:: gpu::StreamAccessor
This class provides possibility to get ``cudaStream_t`` from
:func:`gpu::Stream` . This class is declared in ``stream_accessor.hpp`` because that is only public header that depend on Cuda Runtime API. Including it will bring the dependency to your code. ::
This class provides possibility to get
``cudaStream_t``
from
:func:`gpu::Stream`
. This class is declared in
``stream_accessor.hpp``
because that is only public header that depend on Cuda Runtime API. Including it will bring the dependency to your code.
`id=0.638242088099 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/gpu/gpu%3A%3AcreateContinuous>`__
..cfunction:: void createContinuous(int rows, int cols, int type, GpuMat\& m)
Creates continuous matrix in GPU memory.
Creates continuous matrix in GPU memory.
:param rows:Row count.
:param cols:Column count.
:param type:Type of the matrix.
:param rows:Row count.
:param cols:Column count.
:param type:Type of the matrix.
:param m:Destination matrix. Will be only reshaped if it has proper type and area ( ``rows`` :math:`\times` ``cols`` ).
Also the following wrappers are available:
:param m:Destination matrix. Will be only reshaped if it has proper type and area ( ``rows`` :math:`\times` ``cols`` ).
Also the following wrappers are available:
..cfunction:: GpuMat createContinuous(int rows, int cols, int type)
..cfunction:: void createContinuous(Size size, int type, GpuMat\& m)
..cfunction:: GpuMat createContinuous(Size size, int type)
Matrix is called continuous if its elements are stored continuously, i.e. wuthout gaps in the end of each row.
Matrix is called continuous if its elements are stored continuously, i.e. wuthout gaps in the end of each row.
..index:: gpu::ensureSizeIsEnough
cv::gpu::ensureSizeIsEnough
---------------------------
`id=0.0969536734629 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/gpu/gpu%3A%3AensureSizeIsEnough>`__
..cfunction:: void ensureSizeIsEnough(int rows, int cols, int type, GpuMat\& m)
Ensures that size of matrix is big enough and matrix has proper type. The function doesn't reallocate memory if the matrix has proper attributes already.
Ensures that size of matrix is big enough and matrix has proper type. The function doesn't reallocate memory if the matrix has proper attributes already.
:param rows:Minimum desired number of rows.
:param cols:Minimum desired number of cols.
:param type:Desired matrix type.
:param rows:Minimum desired number of rows.
:param cols:Minimum desired number of cols.
:param type:Desired matrix type.
:param m:Destination matrix.
Also the following wrapper is available:
:param m:Destination matrix.
Also the following wrapper is available:
..cfunction:: void ensureSizeIsEnough(Size size, int type, GpuMat\& m)
The class ``SURF_GPU`` implements Speeded Up Robust Features descriptor. There is fast multi-scale Hessian keypoint detector that can be used to find the keypoints (which is the default option), but the descriptors can be also computed for the user-specified keypoints. Supports only 8 bit grayscale images.
..
The class ``SURF_GPU`` can store results to GPU and CPU memory and provides static functions to convert results between CPU and GPU version ( ``uploadKeypoints``,``downloadKeypoints``,``downloadDescriptors`` ). CPU results has the same format as
results. GPU results are stored to ``GpuMat`` . ``keypoints`` matrix is one row matrix with ``CV_32FC6`` type. It contains 6 float values per feature: ``x, y, size, response, angle, octave`` . ``descriptors`` matrix is
:math:`\texttt{nFeatures} \times \texttt{descriptorSize}` matrix with ``CV_32FC1`` type.
The class
``SURF_GPU``
implements Speeded Up Robust Features descriptor. There is fast multi-scale Hessian keypoint detector that can be used to find the keypoints (which is the default option), but the descriptors can be also computed for the user-specified keypoints. Supports only 8 bit grayscale images.
The class
``SURF_GPU``
can store results to GPU and CPU memory and provides static functions to convert results between CPU and GPU version (
uses some buffers and provides access to it. All buffers can be safely released between function calls.
See also:
.
The class ``SURF_GPU`` uses some buffers and provides access to it. All buffers can be safely released between function calls.
See also:
.
..index:: gpu::BruteForceMatcher_GPU
@ -124,194 +81,130 @@ See also:
gpu::BruteForceMatcher_GPU
--------------------------
..ctype:: gpu::BruteForceMatcher_GPU
`id=0.776429775465 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/gpu/gpu%3A%3ABruteForceMatcher_GPU>`__
Brute-force descriptor matcher. For each descriptor in the first set, this matcher finds the closest descriptor in the second set by trying each one. This descriptor matcher supports masking permissible matches between descriptor sets. ::
..ctype:: gpu::BruteForceMatcher_GPU
template<class Distance>
class BruteForceMatcher_GPU
{
public:
// Add descriptors to train descriptor collection.
Brute-force descriptor matcher. For each descriptor in the first set, this matcher finds the closest descriptor in the second set by trying each one. This descriptor matcher supports masking permissible matches between descriptor sets.
::
template<class Distance>
class BruteForceMatcher_GPU
{
public:
// Add descriptors to train descriptor collection.
// Return true if there are not train descriptors in collection.
bool empty() const;
..
// Return true if the matcher supports mask in match methods.
bool isMaskSupported() const;
The class
``BruteForceMatcher_GPU``
has the similar interface to class
. It has two groups of match methods: for matching descriptors of one image with other image or with image set. Also all functions have alternative: save results to GPU memory or to CPU memory.
``Distance``
template parameter is kept for CPU/GPU interfaces similarity.
`id=0.164151048457 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/gpu/cv%3A%3Agpu%3A%3ABruteForceMatcher_GPU%3A%3Amatch>`__
The class ``BruteForceMatcher_GPU`` has the similar interface to class
. It has two groups of match methods: for matching descriptors of one image with other image or with image set. Also all functions have alternative: save results to GPU memory or to CPU memory.
``Distance`` template parameter is kept for CPU/GPU interfaces similarity. ``BruteForceMatcher_GPU`` supports only ``L1<float>`` and ``L2<float>`` distance types.
cv::gpu::BruteForceMatcher_GPU::matchSingle
-------------------------------------------
See also:,.
`id=0.230978706047 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/gpu/cv%3A%3Agpu%3A%3ABruteForceMatcher_GPU%3A%3AmatchSingle>`__
Finds the best match for each query descriptor. Results will be stored to GPU memory.
{Query set of descriptors.}
{Train set of descriptors. This will not be added to train descriptors collection stored in class object.}
{One row ``CV_32SC1`` matrix. Will contain the best train index for each query. If some query descriptors are masked out in ``mask`` it will contain -1.}
{One row ``CV_32FC1`` matrix. Will contain the best distance for each query. If some query descriptors are masked out in ``mask`` it will contain ``FLT_MAX`` .}
{Query set of descriptors.}
{Train set of descriptors. This will not be added to train descriptors collection stored in class object.}
{One row
``CV_32SC1``
matrix. Will contain the best train index for each query. If some query descriptors are masked out in
``mask``
it will contain -1.}
{One row
``CV_32FC1``
matrix. Will contain the best distance for each query. If some query descriptors are masked out in
``mask``
it will contain
``FLT_MAX``
.}
:param mask:Mask specifying permissible matches between input query and train matrices of descriptors.
:param mask:Mask specifying permissible matches between input query and train matrices of descriptors.
`id=0.934341769456 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/gpu/cv%3A%3Agpu%3A%3ABruteForceMatcher_GPU%3A%3AmatchCollection>`__
Find the best match for each query descriptor from train collection. Results will be stored to GPU memory.
Find the best match for each query descriptor from train collection. Results will be stored to GPU memory.
{Query set of descriptors.}
{ ``GpuMat`` containing train collection. It can be obtained from train descriptors collection that was set using ``add`` method by
. Or it can contain user defined collection. It must be one row matrix, each element is a ``DevMem2D`` that points to one train descriptors matrix.}
{One row ``CV_32SC1`` matrix. Will contain the best train index for each query. If some query descriptors are masked out in ``maskCollection`` it will contain -1.}
{One row ``CV_32SC1`` matrix. Will contain image train index for each query. If some query descriptors are masked out in ``maskCollection`` it will contain -1.}
{One row ``CV_32FC1`` matrix. Will contain the best distance for each query. If some query descriptors are masked out in ``maskCollection`` it will contain ``FLT_MAX`` .}
{Query set of descriptors.}
{
``GpuMat``
containing train collection. It can be obtained from train descriptors collection that was set using
``add``
method by
. Or it can contain user defined collection. It must be one row matrix, each element is a
``DevMem2D``
that points to one train descriptors matrix.}
{One row
``CV_32SC1``
matrix. Will contain the best train index for each query. If some query descriptors are masked out in
``maskCollection``
it will contain -1.}
{One row
``CV_32SC1``
matrix. Will contain image train index for each query. If some query descriptors are masked out in
``maskCollection``
it will contain -1.}
{One row
``CV_32FC1``
matrix. Will contain the best distance for each query. If some query descriptors are masked out in
``maskCollection``
it will contain
``FLT_MAX``
.}
:param maskCollection:``GpuMat`` containing set of masks. It can be obtained from ``std::vector<GpuMat>`` by . Or it can contain user defined mask set. It must be empty matrix or one row matrix, each element is a ``PtrStep`` that points to one mask.
:param maskCollection:``GpuMat`` containing set of masks. It can be obtained from ``std::vector<GpuMat>`` by . Or it can contain user defined mask set. It must be empty matrix or one row matrix, each element is a ``PtrStep`` that points to one mask.
`id=0.285830043662 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/gpu/cv%3A%3Agpu%3A%3ABruteForceMatcher_GPU%3A%3AmakeGpuCollection>`__
`id=0.171611509706 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/gpu/cv%3A%3Agpu%3A%3ABruteForceMatcher_GPU%3A%3AmatchDownload>`__
`id=0.619005099272 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/gpu/cv%3A%3Agpu%3A%3ABruteForceMatcher_GPU%3A%3AknnMatch>`__
Finds the k best matches for each descriptor from a query set with train descriptors. Found k (or less if not possible) matches are returned in distance increasing order.
Finds the k best matches for each descriptor from a query set with train descriptors. Found k (or less if not possible) matches are returned in distance increasing order.
`id=0.852761934257 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/gpu/cv%3A%3Agpu%3A%3ABruteForceMatcher_GPU%3A%3AknnMatch>`__
Finds the k best matches for each descriptor from a query set with train descriptors. Found k (or less if not possible) matches are returned in distance increasing order. Results will be stored to GPU memory.
{Query set of descriptors.}
{Train set of descriptors. This will not be added to train descriptors collection stored in class object.}
{Matrix with
:math:`\texttt{nQueries} \times \texttt{k}` size and ``CV_32SC1`` type. ``trainIdx.at<int>(queryIdx, i)`` will contain index of the i'th best trains. If some query descriptors are masked out in ``mask`` it will contain -1.}
{Matrix with
:math:`\texttt{nQuery} \times \texttt{k}` and ``CV_32FC1`` type. Will contain distance for each query and the i'th best trains. If some query descriptors are masked out in ``mask`` it will contain ``FLT_MAX`` .}
{Buffer to store all distances between query descriptors and train descriptors. It will have
:math:`\texttt{nQuery} \times \texttt{nTrain}` size and ``CV_32FC1`` type. ``allDist.at<float>(queryIdx, trainIdx)`` will contain ``FLT_MAX`` , if ``trainIdx`` is one from k best, otherwise it will contain distance between ``queryIdx`` and ``trainIdx`` descriptors.}
:param k:Number of the best matches will be found per each query descriptor (or less if it's not possible).
Finds the k best matches for each descriptor from a query set with train descriptors. Found k (or less if not possible) matches are returned in distance increasing order. Results will be stored to GPU memory.
{Query set of descriptors.}
{Train set of descriptors. This will not be added to train descriptors collection stored in class object.}
{Matrix with
:math:`\texttt{nQueries} \times \texttt{k}`
size and
``CV_32SC1``
type.
``trainIdx.at<int>(queryIdx, i)``
will contain index of the i'th best trains. If some query descriptors are masked out in
``mask``
it will contain -1.}
{Matrix with
:math:`\texttt{nQuery} \times \texttt{k}`
and
``CV_32FC1``
type. Will contain distance for each query and the i'th best trains. If some query descriptors are masked out in
``mask``
it will contain
``FLT_MAX``
.}
{Buffer to store all distances between query descriptors and train descriptors. It will have
:math:`\texttt{nQuery} \times \texttt{nTrain}`
size and
``CV_32FC1``
type.
``allDist.at<float>(queryIdx, trainIdx)``
will contain
``FLT_MAX``
, if
``trainIdx``
is one from k best, otherwise it will contain distance between
``queryIdx``
and
``trainIdx``
descriptors.}
:param k:Number of the best matches will be found per each query descriptor (or less if it's not possible).
:param mask:Mask specifying permissible matches between input query and train matrices of descriptors.
:param mask:Mask specifying permissible matches between input query and train matrices of descriptors.
`id=0.735745722087 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/gpu/cv%3A%3Agpu%3A%3ABruteForceMatcher_GPU%3A%3AknnMatchDownload>`__
Downloads trainIdxand distancematrices obtained via to CPU vector with . If compactResultis true matchesvector will not contain matches for fully masked out query descriptors.
Downloads trainIdxand distancematrices obtained via to CPU vector with . If compactResultis true matchesvector will not contain matches for fully masked out query descriptors.
`id=0.964758287221 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/gpu/cv%3A%3Agpu%3A%3ABruteForceMatcher_GPU%3A%3AradiusMatch>`__
Finds the best matches for each query descriptor which have distance less than given threshold. Found matches are returned in distance increasing order.
Finds the best matches for each query descriptor which have distance less than given threshold. Found matches are returned in distance increasing order.
`id=0.499772925784 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/gpu/cv%3A%3Agpu%3A%3ABruteForceMatcher_GPU%3A%3AradiusMatch>`__
Finds the best matches for each query descriptor which have distance less than given threshold. Results will be stored to GPU memory.
Finds the best matches for each query descriptor which have distance less than given threshold. Results will be stored to GPU memory.
{Query set of descriptors.}
{Train set of descriptors. This will not be added to train descriptors collection stored in class object.}
{ ``trainIdx.at<int>(queryIdx, i)`` will contain i'th train index ``(i < min(nMatches.at<unsigned int>(0, queryIdx), trainIdx.cols)`` . If ``trainIdx`` is empty, it will be created with size
:math:`\texttt{nQuery} \times \texttt{nTrain}` . Or it can be allocated by user (it must have ``nQuery`` rows and ``CV_32SC1`` type). Cols can be less than ``nTrain`` , but it can be that matcher won't find all matches, because it haven't enough memory to store results.}
{ ``nMatches.at<unsigned int>(0, queryIdx)`` will contain matches count for ``queryIdx`` . Carefully, ``nMatches`` can be greater than ``trainIdx.cols`` - it means that matcher didn't find all matches, because it didn't have enough memory.}
{ ``distance.at<int>(queryIdx, i)`` will contain i'th distance ``(i < min(nMatches.at<unsigned int>(0, queryIdx), trainIdx.cols)`` . If ``trainIdx`` is empty, it will be created with size
:math:`\texttt{nQuery} \times \texttt{nTrain}` . Otherwise it must be also allocated by user (it must have the same size as ``trainIdx`` and ``CV_32FC1`` type).}
:param maxDistance:Distance threshold.
:param mask:Mask specifying permissible matches between input query and train matrices of descriptors.
{Query set of descriptors.}
{Train set of descriptors. This will not be added to train descriptors collection stored in class object.}
`id=0.627360663551 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/gpu/cv%3A%3Agpu%3A%3ABruteForceMatcher_GPU%3A%3AradiusMatchDownload>`__
Downloads trainIdx, nMatchesand distancematrices obtained via to CPU vector with . If compactResultis true matchesvector will not contain matches for fully masked out query descriptors.
Downloads trainIdx, nMatchesand distancematrices obtained via to CPU vector with . If compactResultis true matchesvector will not contain matches for fully masked out query descriptors.
`id=0.541856697999 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/gpu/gpu%3A%3AgetCudaEnabledDeviceCount>`__
..cfunction:: int getCudaEnabledDeviceCount()
Returns number of CUDA-enabled devices installed. It is to be used before any other GPU functions calls. If OpenCV is compiled without GPU support this function returns 0.
Returns number of CUDA-enabled devices installed. It is to be used before any other GPU functions calls. If OpenCV is compiled without GPU support this function returns 0.
..index:: gpu::setDevice
cv::gpu::setDevice
------------------
`id=0.817295536445 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/gpu/gpu%3A%3AsetDevice>`__
..cfunction:: void setDevice(int device)
Sets device and initializes it for the current thread. Call of this function can be omitted, but in this case a default device will be initialized on fist GPU usage.
:param device:index of GPU device in system starting with 0.
:param device:index of GPU device in system starting with 0.
..index:: gpu::getDevice
cv::gpu::getDevice
------------------
`id=0.908782607162 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/gpu/gpu%3A%3AgetDevice>`__
..cfunction:: int getDevice()
Returns the current device index, which was set by {gpu::getDevice} or initialized by default.
..index:: gpu::GpuFeature
.._gpu::GpuFeature:
gpu::GpuFeature
---------------
`id=0.185426029041 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/gpu/gpu%3A%3AGpuFeature>`__
..ctype:: gpu::GpuFeature
GPU compute features. ::
GPU compute features.
::
enum GpuFeature
{
COMPUTE_10, COMPUTE_11,
@ -95,308 +46,153 @@ GPU compute features.
COMPUTE_20, COMPUTE_21,
ATOMICS, NATIVE_DOUBLE
};
..
..index:: gpu::DeviceInfo
.._gpu::DeviceInfo:
gpu::DeviceInfo
---------------
`id=0.91098225386 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/gpu/gpu%3A%3ADeviceInfo>`__
..ctype:: gpu::DeviceInfo
This class provides functionality for querying the specified GPU properties. ::
This class provides functionality for querying the specified GPU properties.
::
class CV_EXPORTS DeviceInfo
{
public:
DeviceInfo();
DeviceInfo(int device_id);
string name() const;
int majorVersion() const;
int minorVersion() const;
int multiProcessorCount() const;
size_t freeMemory() const;
size_t totalMemory() const;
bool supports(GpuFeature feature) const;
bool isCompatible() const;
};
..
..index:: gpu::DeviceInfo::DeviceInfo
cv::gpu::DeviceInfo::DeviceInfo
-------------------------------
`id=0.971366637207 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/gpu/gpu%3A%3ADeviceInfo%3A%3ADeviceInfo>`__
There are a set of methods for checking whether the module contains intermediate (PTX) or binary GPU code for the given architecture(s):
..cfunction:: static bool has(int major, int minor)
..cfunction:: static bool hasPtx(int major, int minor)
..cfunction:: static bool hasBin(int major, int minor)
..cfunction:: static bool hasEqualOrLessPtx(int major, int minor)
..cfunction:: static bool hasEqualOrGreater(int major, int minor)
..cfunction:: static bool hasEqualOrGreaterPtx(int major, int minor)
..cfunction:: static bool hasEqualOrGreaterBin(int major, int minor)
* **major** Major compute capability version.
* **minor** Minor compute capability version.
* **major** Major compute capability version.
* **minor** Minor compute capability version.
According to the CUDA C Programming Guide Version 3.2: "PTX code produced for some specific compute capability can always be compiled to binary code of greater or equal compute capability".
According to the CUDA C Programming Guide Version 3.2: "PTX code produced for some specific compute capability can always be compiled to binary code of greater or equal compute capability".
The OpenCV GPU module is a set of classes and functions to utilize GPU computational capabilities. It is implemented using NVidia CUDA Runtime API, so only the NVidia GPUs are supported. It includes utility functions, low-level vision primitives as well as high-level algorithms. The utility functions and low-level primitives provide a powerful infrastructure for developing fast vision algorithms taking advantage of GPU. Whereas the high-level functionality includes some state-of-the-art algorithms (such as stereo correspondence, face and people detectors etc.), ready to be used by the application developers.
The GPU module is designed as host-level API, i.e. if a user has pre-compiled OpenCV GPU binaries, it is not necessary to have Cuda Toolkit installed or write any extra code to make use of the GPU.
The GPU module depends on the Cuda Toolkit and NVidia Performance Primitives library (NPP). Make sure you have the latest versions of those. The two libraries can be downloaded from NVidia site for all supported platforms. To compile OpenCV GPU module you will need a compiler compatible with Cuda Runtime Toolkit.
The OpenCV GPU module is a set of classes and functions to utilize GPU computational capabilities. It is implemented using NVidia CUDA Runtime API, so only the NVidia GPUs are supported. It includes utility functions, low-level vision primitives as well as high-level algorithms. The utility functions and low-level primitives provide a powerful infrastructure for developing fast vision algorithms taking advantage of GPU. Whereas the high-level functionality includes some state-of-the-art algorithms (such as stereo correspondence, face and people detectors etc.), ready to be used by the application developers.
The GPU module is designed as host-level API, i.e. if a user has pre-compiled OpenCV GPU binaries, it is not necessary to have Cuda Toolkit installed or write any extra code to make use of the GPU.
The GPU module depends on the Cuda Toolkit and NVidia Performance Primitives library (NPP). Make sure you have the latest versions of those. The two libraries can be downloaded from NVidia site for all supported platforms. To compile OpenCV GPU module you will need a compiler compatible with Cuda Runtime Toolkit.
OpenCV GPU module is designed for ease of use and does not require any knowledge of Cuda. Though, such a knowledge will certainly be useful in non-trivial cases, or when you want to get the highest performance. It is helpful to have understanding of the costs of various operations, what the GPU does, what are the preferred data formats etc. The GPU module is an effective instrument for quick implementation of GPU-accelerated computer vision algorithms. However, if you algorithm involves many simple operations, then for the best possible performance you may still need to write your own kernels, to avoid extra write and read operations on the intermediate results.
To enable CUDA support, configure OpenCV using CMake with
``WITH_CUDA=ON``
. When the flag is set and if CUDA is installed, the full-featured OpenCV GPU module will be built. Otherwise, the module will still be built, but at runtime all functions from the module will throw
:func:`Exception`
with
``CV_GpuNotSupported``
error code, except for
:func:`gpu::getCudaEnabledDeviceCount()`
. The latter function will return zero GPU count in this case. Building OpenCV without CUDA support does not perform device code compilation, so it does not require Cuda Toolkit installed. Therefore, using
:func:`gpu::getCudaEnabledDeviceCount()`
function it is possible to implement a high-level algorithm that will detect GPU presence at runtime and choose the appropriate implementation (CPU or GPU) accordingly.
OpenCV GPU module is designed for ease of use and does not require any knowledge of Cuda. Though, such a knowledge will certainly be useful in non-trivial cases, or when you want to get the highest performance. It is helpful to have understanding of the costs of various operations, what the GPU does, what are the preferred data formats etc. The GPU module is an effective instrument for quick implementation of GPU-accelerated computer vision algorithms. However, if you algorithm involves many simple operations, then for the best possible performance you may still need to write your own kernels, to avoid extra write and read operations on the intermediate results.
To enable CUDA support, configure OpenCV using CMake with ``WITH_CUDA=ON`` . When the flag is set and if CUDA is installed, the full-featured OpenCV GPU module will be built. Otherwise, the module will still be built, but at runtime all functions from the module will throw
:func:`Exception` with ``CV_GpuNotSupported`` error code, except for
:func:`gpu::getCudaEnabledDeviceCount()` . The latter function will return zero GPU count in this case. Building OpenCV without CUDA support does not perform device code compilation, so it does not require Cuda Toolkit installed. Therefore, using
:func:`gpu::getCudaEnabledDeviceCount()` function it is possible to implement a high-level algorithm that will detect GPU presence at runtime and choose the appropriate implementation (CPU or GPU) accordingly.
Compilation for different NVidia platforms.
-------------------------------------------
NVidia compiler allows generating binary code (cubin and fatbin) and intermediate code (PTX). Binary code often implies a specific GPU architecture and generation, so the compatibility with other GPUs is not guaranteed. PTX is targeted for a virtual platform, which is defined entirely by the set of capabilities, or features. Depending on the virtual platform chosen, some of the instructions will be emulated or disabled, even if the real hardware supports all the features.
NVidia compiler allows generating binary code (cubin and fatbin) and intermediate code (PTX). Binary code often implies a specific GPU architecture and generation, so the compatibility with other GPUs is not guaranteed. PTX is targeted for a virtual platform, which is defined entirely by the set of capabilities, or features. Depending on the virtual platform chosen, some of the instructions will be emulated or disabled, even if the real hardware supports all the features.
On first call, the PTX code is compiled to binary code for the particular GPU using JIT compiler. When the target GPU has lower "compute capability" (CC) than the PTX code, JIT fails.
By default, the OpenCV GPU module includes:
On first call, the PTX code is compiled to binary code for the particular GPU using JIT compiler. When the target GPU has lower "compute capability" (CC) than the PTX code, JIT fails.
By default, the OpenCV GPU module includes:
*
Binaries for compute capabilities 1.3 and 2.0 (controlled by
``CUDA_ARCH_BIN``
in CMake)
Binaries for compute capabilities 1.3 and 2.0 (controlled by ``CUDA_ARCH_BIN`` in CMake)
*
PTX code for compute capabilities 1.1 and 1.3 (controlled by
``CUDA_ARCH_PTX``
in CMake)
That means for devices with CC 1.3 and 2.0 binary images are ready to run. For all newer platforms the PTX code for 1.3 is JIT'ed to a binary image. For devices with 1.1 and 1.2 the PTX for 1.1 is JIT'ed. For devices with CC 1.0 no code is available and the functions will throw
:func:`Exception`
. For platforms where JIT compilation is performed first run will be slow.
If you happen to have GPU with CC 1.0, the GPU module can still be compiled on it and most of the functions will run just fine on such card. Simply add "1.0" to the list of binaries, for example,
``CUDA_ARCH_BIN="1.0 1.3 2.0"``
. The functions that can not be run on CC 1.0 GPUs will throw an exception.
You can always determine at runtime whether OpenCV GPU built binaries (or PTX code) are compatible with your GPU. The function
:func:`gpu::DeviceInfo::isCompatible`
return the compatibility status (true/false).
PTX code for compute capabilities 1.1 and 1.3 (controlled by ``CUDA_ARCH_PTX`` in CMake)
That means for devices with CC 1.3 and 2.0 binary images are ready to run. For all newer platforms the PTX code for 1.3 is JIT'ed to a binary image. For devices with 1.1 and 1.2 the PTX for 1.1 is JIT'ed. For devices with CC 1.0 no code is available and the functions will throw
:func:`Exception` . For platforms where JIT compilation is performed first run will be slow.
If you happen to have GPU with CC 1.0, the GPU module can still be compiled on it and most of the functions will run just fine on such card. Simply add "1.0" to the list of binaries, for example, ``CUDA_ARCH_BIN="1.0 1.3 2.0"`` . The functions that can not be run on CC 1.0 GPUs will throw an exception.
You can always determine at runtime whether OpenCV GPU built binaries (or PTX code) are compatible with your GPU. The function
:func:`gpu::DeviceInfo::isCompatible` return the compatibility status (true/false).
Threading and multi-threading.
------------------------------
OpenCV GPU module follows Cuda Runtime API conventions regarding the multi-threaded programming. That is, on first the API call a Cuda context is created implicitly, attached to the current CPU thread and then is used as the thread's "current" context. All further operations, such as memory allocation, GPU code compilation, will be associated with the context and the thread. Because any other thread is not attached to the context, memory (and other resources) allocated in the first thread can not be accessed by the other thread. Instead, for this other thread Cuda will create another context associated with it. In short, by default different threads do not share resources.
But such limitation can be removed using Cuda Driver API (version 3.1 or later). User can retrieve context reference for one thread, attach it to another thread and make it "current" for that thread. Then the threads can share memory and other resources. It is also possible to create a context explicitly before calling any GPU code and attach it to all the threads that you want to share the resources.
OpenCV GPU module follows Cuda Runtime API conventions regarding the multi-threaded programming. That is, on first the API call a Cuda context is created implicitly, attached to the current CPU thread and then is used as the thread's "current" context. All further operations, such as memory allocation, GPU code compilation, will be associated with the context and the thread. Because any other thread is not attached to the context, memory (and other resources) allocated in the first thread can not be accessed by the other thread. Instead, for this other thread Cuda will create another context associated with it. In short, by default different threads do not share resources.
But such limitation can be removed using Cuda Driver API (version 3.1 or later). User can retrieve context reference for one thread, attach it to another thread and make it "current" for that thread. Then the threads can share memory and other resources. It is also possible to create a context explicitly before calling any GPU code and attach it to all the threads that you want to share the resources.
Also it is possible to create context explicitly using Cuda Driver API, attach and make "current" for all necessary threads. Cuda Runtime API (and OpenCV functions respectively) will pick up it.
Also it is possible to create context explicitly using Cuda Driver API, attach and make "current" for all necessary threads. Cuda Runtime API (and OpenCV functions respectively) will pick up it.
Multi-GPU
---------
In the current version each of the OpenCV GPU algorithms can use only a single GPU. So, to utilize multiple GPUs, user has to manually distribute the work between the GPUs. Here are the two ways of utilizing multiple GPUs:
In the current version each of the OpenCV GPU algorithms can use only a single GPU. So, to utilize multiple GPUs, user has to manually distribute the work between the GPUs. Here are the two ways of utilizing multiple GPUs:
*
If you only use synchronous functions, first, create several CPU threads (one per each GPU) and from within each thread create CUDA context for the corresponding GPU using
:func:`gpu::setDevice()`
or Driver API. That's it. Now each of the threads will use the associated GPU.
If you only use synchronous functions, first, create several CPU threads (one per each GPU) and from within each thread create CUDA context for the corresponding GPU using
:func:`gpu::setDevice()` or Driver API. That's it. Now each of the threads will use the associated GPU.
*
In case of asynchronous functions, it is possible to create several Cuda contexts associated with different GPUs but attached to one CPU thread. This can be done only by Driver API. Within the thread you can switch from one GPU to another by making the corresponding context "current". With non-blocking GPU calls managing algorithm is clear.
While developing algorithms for multiple GPUs a data passing overhead have to be taken into consideration. For primitive functions and for small images it can be significant and eliminate all the advantages of having multiple GPUs. But for high level algorithms Multi-GPU acceleration may be suitable. For example, Stereo Block Matching algorithm has been successfully parallelized using the following algorithm:
In case of asynchronous functions, it is possible to create several Cuda contexts associated with different GPUs but attached to one CPU thread. This can be done only by Driver API. Within the thread you can switch from one GPU to another by making the corresponding context "current". With non-blocking GPU calls managing algorithm is clear.
While developing algorithms for multiple GPUs a data passing overhead have to be taken into consideration. For primitive functions and for small images it can be significant and eliminate all the advantages of having multiple GPUs. But for high level algorithms Multi-GPU acceleration may be suitable. For example, Stereo Block Matching algorithm has been successfully parallelized using the following algorithm:
*
Each image of the stereo pair is split into two horizontal overlapping stripes.
Each image of the stereo pair is split into two horizontal overlapping stripes.
*
Each pair of stripes (from the left and the right images) has been processed on a separate Fermi GPU
Each pair of stripes (from the left and the right images) has been processed on a separate Fermi GPU
*
The results are merged into the single disparity map.
The results are merged into the single disparity map.
With this scheme dual GPU gave 180
%
performance increase comparing to the single Fermi GPU. The source code of the example is available at
performance increase comparing to the single Fermi GPU. The source code of the example is available at
`id=0.91431196569 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/gpu/gpu%3A%3AHOGDescriptor%3A%3AgetBlockHistogramSize>`__
`id=0.941470897866 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/gpu/gpu%3A%3AHOGDescriptor%3A%3AgetDefaultPeopleDetector>`__
`id=0.600273723778 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/gpu/gpu%3A%3AHOGDescriptor%3A%3AgetPeopleDetector48x96>`__
`id=0.583356812364 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/gpu/gpu%3A%3AHOGDescriptor%3A%3AgetPeopleDetector64x128>`__
Perfroms object detection without multiscale window.
Perfroms object detection without multiscale window.
:param img:Source image. ``CV_8UC1`` and ``CV_8UC4`` types are supported for now.
:param found_locations:Will contain left-top corner points of detected objects boundaries.
:param hit_threshold:Threshold for the distance between features and SVM classifying plane. Usually it's 0 and should be specfied in the detector coefficients (as the last free coefficient), but if the free coefficient is omitted (it's allowed) you can specify it manually here.
:param img:Source image. ``CV_8UC1`` and ``CV_8UC4`` types are supported for now.
:param found_locations:Will contain left-top corner points of detected objects boundaries.
:param hit_threshold:Threshold for the distance between features and SVM classifying plane. Usually it's 0 and should be specfied in the detector coefficients (as the last free coefficient), but if the free coefficient is omitted (it's allowed) you can specify it manually here.
:param win_stride:Window stride. Must be a multiple of block stride.
:param padding:Mock parameter to keep CPU interface compatibility. Must be (0,0).
:param win_stride:Window stride. Must be a multiple of block stride.
..index:: gpu::HOGDescriptor::detectMultiScale
:param padding:Mock parameter to keep CPU interface compatibility. Must be (0,0).
:param hit_threshold:The threshold for the distance between features and SVM classifying plane. See :func:`gpu::HOGDescriptor::detect` for details.
:param win_stride:Window stride. Must be a multiple of block stride.
:param padding:Mock parameter to keep CPU interface compatibility. Must be (0,0).
:param scale0:Coefficient of the detection window increase.
:param group_threshold:After detection some objects could be covered by many rectangles. This coefficient regulates similarity threshold. 0 means don't perform grouping.
See :func:`groupRectangles` .
:param padding:Mock parameter to keep CPU interface compatibility. Must be (0,0).
..index:: gpu::HOGDescriptor::getDescriptors
:param scale0:Coefficient of the detection window increase.
:param group_threshold:After detection some objects could be covered by many rectangles. This coefficient regulates similarity threshold. 0 means don't perform grouping.
`id=0.502164537388 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/gpu/cv%3A%3Agpu%3A%3ACascadeClassifier_GPU%3A%3ACascadeClassifier_GPU>`__
:param filename:Name of file from which classifier will be load. Only old haar classifier (trained by haartraining application) and NVidia's nvbin are supported.
:param filename:Name of file from which classifier will be load. Only old haar classifier (trained by haartraining application) and NVidia's nvbin are supported.
`id=0.00879679914574 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/gpu/cv%3A%3Agpu%3A%3ACascadeClassifier_GPU%3A%3Aempty>`__
`id=0.831994730738 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/gpu/cv%3A%3Agpu%3A%3ACascadeClassifier_GPU%3A%3Aload>`__
Loads the classifier from file. The previous content is destroyed.
Loads the classifier from file. The previous content is destroyed.
:param filename:Name of file from which classifier will be load. Only old haar classifier (trained by haartraining application) and NVidia's nvbin are supported.
:param filename:Name of file from which classifier will be load. Only old haar classifier (trained by haartraining application) and NVidia's nvbin are supported.
`id=0.524456582811 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/gpu/cv%3A%3Agpu%3A%3ACascadeClassifier_GPU%3A%3Arelease>`__
..cfunction:: int CascadeClassifier_GPU::detectMultiScale(const GpuMat\& image, GpuMat\& objectsBuf, double scaleFactor=1.2, int minNeighbors=4, Size minSize=Size())
Destroys loaded classifier.
Detects objects of different sizes in the input image. The detected objects are returned as a list of rectangles.
:param image:Matrix of type ``CV_8U`` containing the image in which to detect objects.
:param objects:Buffer to store detected objects (rectangles). If it is empty, it will be allocated with default size. If not empty, function will search not more than N objects, where N = sizeof(objectsBufer's data)/sizeof(cv::Rect).
:param minNeighbors:Specifies how many neighbors should each candidate rectangle have to retain it.
cv::gpu::CascadeClassifier_GPU::detectMultiScale
------------------------------------------------
:param minSize:The minimum possible object size. Objects smaller than that are ignored.
`id=0.0605957110589 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/gpu/cv%3A%3Agpu%3A%3ACascadeClassifier_GPU%3A%3AdetectMultiScale>`__
The function returns number of detected objects, so you can retrieve them as in following example: ::
cv::gpu::CascadeClassifier_GPU cascade_gpu(...);
Mat image_cpu = imread(...)
GpuMat image_gpu(image_cpu);
GpuMat objbuf;
int detections_number = cascade_gpu.detectMultiScale( image_gpu,
objbuf, 1.2, minNeighbors);
..cfunction:: int CascadeClassifier_GPU::detectMultiScale(const GpuMat\& image, GpuMat\& objectsBuf, double scaleFactor=1.2, int minNeighbors=4, Size minSize=Size())
Detects objects of different sizes in the input image. The detected objects are returned as a list of rectangles.
:param image:Matrix of type ``CV_8U`` containing the image in which to detect objects.
:param objects:Buffer to store detected objects (rectangles). If it is empty, it will be allocated with default size. If not empty, function will search not more than N objects, where N = sizeof(objectsBufer's data)/sizeof(cv::Rect).
:param scaleFactor:Specifies how much the image size is reduced at each image scale.
:param minNeighbors:Specifies how many neighbors should each candidate rectangle have to retain it.
:param minSize:The minimum possible object size. Objects smaller than that are ignored.
The function returns number of detected objects, so you can retrieve them as in following example:
::
cv::gpu::CascadeClassifier_GPU cascade_gpu(...);
Mat image_cpu = imread(...)
GpuMat image_gpu(image_cpu);
GpuMat objbuf;
int detections_number = cascade_gpu.detectMultiScale( image_gpu,
Transforms the source matrix into the destination matrix using given look-up table:
Transforms the source matrix into the destination matrix using given look-up table:
:param src:Source matrix. ``CV_8UC1`` and ``CV_8UC3`` matrixes are supported for now.
:param lut:Look-up table. Must be continuous, ``CV_8U`` depth matrix. Its area must satisfy to ``lut.rows`` :math:`\times` ``lut.cols`` = 256 condition.
:param dst:Destination matrix. Will have the same depth as ``lut`` and the same number of channels as ``src`` .
:param src:Source matrix. ``CV_8UC1`` and ``CV_8UC3`` matrixes are supported for now.
:param lut:Look-up table. Must be continuous, ``CV_8U`` depth matrix. Its area must satisfy to ``lut.rows`` :math:`\times` ``lut.cols`` = 256 condition.
:param dst:Destination matrix. Will have the same depth as ``lut`` and the same number of channels as ``src`` .
See also:
:func:`LUT`
.
See also:
:func:`LUT` .
..index:: gpu::merge
cv::gpu::merge
--------------
`id=0.568969773318 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/gpu/gpu%3A%3Amerge>`__
..cfunction:: void merge(const GpuMat* src, size_t n, GpuMat\& dst)
applications and can be used within functionally rich UI frameworks (such as Qt, WinForms or Cocoa) or without any UI at all, sometimes there is a need to try some functionality quickly and visualize the results. This is what the HighGUI module has been designed for.
@ -12,7 +11,6 @@ It provides easy interface to:
* add trackbars to the windows, handle simple mouse events as well as keyboard commmands
* read and write images to/from disk or memory.
* read video from camera or file and write video to a file.
applications and can be used within functionally rich UI frameworks (such as Qt, WinForms or Cocoa) or without any UI at all, sometimes there is a need to try some functionality quickly and visualize the results. This is what the HighGUI module has been designed for.
It provides easy interface to:
*
create and manipulate windows that can display images and "remember" their content (no need to handle repaint events from OS)
*
add trackbars to the windows, handle simple mouse events as well as keyboard commmands
*
read and write images to/from disk or memory.
*
read video from camera or file and write video to a file.
This figure explains the new functionalities implemented with Qt GUI. As we can see, the new GUI provides a statusbar, a toolbar, and a control panel. The control panel can have trackbars and buttonbars attached to it.
This figure explains the new functionalities implemented with Qt GUI. As we can see, the new GUI provides a statusbar, a toolbar, and a control panel. The control panel can have trackbars and buttonbars attached to it.
*
To attach a trackbar, the window
_
name parameter must be NULL.
To attach a trackbar, the window_ name parameter must be NULL.
*
To attach a buttonbar, a button must be created.
If the last bar attached to the control panel is a buttonbar, the new button is added on the right of the last button.
If the last bar attached to the control panel is a trackbar, or the control panel is empty, a new buttonbar is created. Then a new button is attached to it.
The following code is an example used to generate the figure.
If the last bar attached to the control panel is a buttonbar, the new button is added on the right of the last button.
If the last bar attached to the control panel is a trackbar, or the control panel is empty, a new buttonbar is created. Then a new button is attached to it.
The following code is an example used to generate the figure. ::
..cfunction:: void setWindowProperty(const string\& name, int prop_id, double prop_value)
`id=0.202216555435 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/highgui/setWindowProperty>`__
Change the parameters of the window dynamically.
:param name:Name of the window.
..cfunction:: void setWindowProperty(const string\& name, int prop_id, double prop_value)
:param prop_id:Window's property to edit. The operation flags:
* **CV_WND_PROP_FULLSCREEN** Change if the window is fullscreen ( ``CV_WINDOW_NORMAL`` or ``CV_WINDOW_FULLSCREEN`` ).
* **CV_WND_PROP_AUTOSIZE** Change if the user can resize the window (texttt {CV\_WINDOW\_NORMAL} or ``CV_WINDOW_AUTOSIZE`` ).
* **CV_WND_PROP_ASPECTRATIO** Change if the image's aspect ratio is preserved (texttt {CV\_WINDOW\_FREERATIO} or ``CV_WINDOW_KEEPRATIO`` ).
Change the parameters of the window dynamically.
:param name:Name of the window.
:param prop_id:Window's property to edit. The operation flags:
* **CV_WND_PROP_FULLSCREEN** Change if the window is fullscreen ( ``CV_WINDOW_NORMAL`` or ``CV_WINDOW_FULLSCREEN`` ).
* **CV_WND_PROP_AUTOSIZE** Change if the user can resize the window (texttt {CV\_WINDOW\_NORMAL} or ``CV_WINDOW_AUTOSIZE`` ).
* **CV_WND_PROP_ASPECTRATIO** Change if the image's aspect ratio is preserved (texttt {CV\_WINDOW\_FREERATIO} or ``CV_WINDOW_KEEPRATIO`` ).
:param prop_value:New value of the Window's property. The operation flags:
* **CV_WINDOW_NORMAL** Change the window in normal size, or allows the user to resize the window.
* **CV_WINDOW_AUTOSIZE** The user cannot resize the window, the size is constrainted by the image displayed.
* **CV_WINDOW_FULLSCREEN** Change the window to fullscreen.
* **CV_WINDOW_FREERATIO** The image expends as much as it can (no ratio constraint)
* **CV_WINDOW_KEEPRATIO** The ration image is respected.
The function
`` setWindowProperty``
allows to change the window's properties.
:param prop_value:New value of the Window's property. The operation flags:
* **CV_WINDOW_NORMAL** Change the window in normal size, or allows the user to resize the window.
* **CV_WINDOW_AUTOSIZE** The user cannot resize the window, the size is constrainted by the image displayed.
* **CV_WINDOW_FULLSCREEN** Change the window to fullscreen.
* **CV_WINDOW_FREERATIO** The image expends as much as it can (no ratio constraint)
* **CV_WINDOW_KEEPRATIO** The ration image is respected.
The function `` setWindowProperty`` allows to change the window's properties.
..index:: getWindowProperty
cv::getWindowProperty
---------------------
..cfunction:: void getWindowProperty(const char* name, int prop_id)
`id=0.467280795493 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/highgui/getWindowProperty>`__
Get the parameters of the window.
:param name:Name of the window.
:param prop_id:Window's property to retrive. The operation flags:
* **CV_WND_PROP_FULLSCREEN** Change if the window is fullscreen ( ``CV_WINDOW_NORMAL`` or ``CV_WINDOW_FULLSCREEN`` ).
* **CV_WND_PROP_AUTOSIZE** Change if the user can resize the window (texttt {CV\_WINDOW\_NORMAL} or ``CV_WINDOW_AUTOSIZE`` ).
* **CV_WND_PROP_ASPECTRATIO** Change if the image's aspect ratio is preserved (texttt {CV\_WINDOW\_FREERATIO} or ``CV_WINDOW_KEEPRATIO`` ).
..cfunction:: void getWindowProperty(const char* name, int prop_id)
See
:ref:`setWindowProperty` to know the meaning of the returned values.
Get the parameters of the window.
:param name:Name of the window.
:param prop_id:Window's property to retrive. The operation flags:
* **CV_WND_PROP_FULLSCREEN** Change if the window is fullscreen ( ``CV_WINDOW_NORMAL`` or ``CV_WINDOW_FULLSCREEN`` ).
* **CV_WND_PROP_AUTOSIZE** Change if the user can resize the window (texttt {CV\_WINDOW\_NORMAL} or ``CV_WINDOW_AUTOSIZE`` ).
* **CV_WND_PROP_ASPECTRATIO** Change if the image's aspect ratio is preserved (texttt {CV\_WINDOW\_FREERATIO} or ``CV_WINDOW_KEEPRATIO`` ).
See
:ref:`setWindowProperty`
to know the meaning of the returned values.
The function
`` getWindowProperty``
return window's properties.
The function `` getWindowProperty`` return window's properties.
..index:: fontQt
cv::fontQt
----------
..cfunction:: CvFont fontQt(const string\& nameFont, int pointSize = -1, Scalar color = Scalar::all(0), int weight = CV_FONT_NORMAL, int style = CV_STYLE_NORMAL, int spacing = 0)
`id=0.680350496921 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/highgui/fontQt>`__
Create the font to be used to draw text on an image.
:param nameFont:Name of the font. The name should match the name of a system font (such as ``Times''). If the font is not found, a default one will be used.
:param pointSize:Size of the font. If not specified, equal zero or negative, the point size of the font is set to a system-dependent default value. Generally, this is 12 points.
..cfunction:: CvFont fontQt(const string\& nameFont, int pointSize = -1, Scalar color = Scalar::all(0), int weight = CV_FONT_NORMAL, int style = CV_STYLE_NORMAL, int spacing = 0)
:param color:Color of the font in BGRA -- A = 255 is fully transparent. Use the macro CV _ RGB for simplicity.
Create the font to be used to draw text on an image.
:param nameFont:Name of the font. The name should match the name of a system font (such as ``Times''). If the font is not found, a default one will be used.
:param pointSize:Size of the font. If not specified, equal zero or negative, the point size of the font is set to a system-dependent default value. Generally, this is 12 points.
:param color:Color of the font in BGRA -- A = 255 is fully transparent. Use the macro CV _ RGB for simplicity.
:param weight:The operation flags:
* **CV_FONT_LIGHT** Weight of 25
* **CV_FONT_NORMAL** Weight of 50
* **CV_FONT_DEMIBOLD** Weight of 63
* **CV_FONT_BOLD** Weight of 75
* **CV_FONT_BLACK** Weight of 87
:param weight:The operation flags:
* **CV_FONT_LIGHT** Weight of 25
You can also specify a positive integer for more control.
:param style:The operation flags:
* **CV_STYLE_NORMAL** Font is normal
* **CV_STYLE_ITALIC** Font is in italic
* **CV_STYLE_OBLIQUE** Font is oblique
:param spacing:Spacing between characters. Can be negative or positive
The function
``fontQt``
creates a CvFont object. This CvFont is not compatible with putText.
A basic usage of this function is:
::
CvFont font = fontQt(''Times'');
addText( img1, ``Hello World !'', Point(50,50), font);
..
* **CV_FONT_NORMAL** Weight of 50
* **CV_FONT_DEMIBOLD** Weight of 63
* **CV_FONT_BOLD** Weight of 75
* **CV_FONT_BLACK** Weight of 87
..index:: addText
You can also specify a positive integer for more control.
:param style:The operation flags:
* **CV_STYLE_NORMAL** Font is normal
* **CV_STYLE_ITALIC** Font is in italic
* **CV_STYLE_OBLIQUE** Font is oblique
cv::addText
-----------
:param spacing:Spacing between characters. Can be negative or positive
`id=0.0425492674947 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/highgui/addText>`__
The function ``fontQt`` creates a CvFont object. This CvFont is not compatible with putText.
A basic usage of this function is: ::
CvFont font = fontQt(''Times'');
addText( img1, ``Hello World !'', Point(50,50), font);
Create the font to be used to draw text on an image
Create the font to be used to draw text on an image
:param img:Image where the text should be drawn
:param text:Text to write on the image
:param location:Point(x,y) where the text should start on the image
:param font:Font to use to draw the text
:param img:Image where the text should be drawn
:param text:Text to write on the image
:param location:Point(x,y) where the text should start on the image
:param font:Font to use to draw the text
The function
``addText``
draw
The function ``addText`` draw
*text*
on the image
on the image
*img*
using a specific font
using a specific font
*font*
(see example
:ref:`fontQt`
)
(see example
:ref:`fontQt` )
..index:: displayOverlay
cv::displayOverlay
------------------
`id=0.969508597197 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/highgui/displayOverlay>`__
..cfunction:: void displayOverlay(const string\& name, const string\& text, int delay)
Display text on the window's image as an overlay for delay milliseconds. This is not editing the image's data. The text is display on the top of the image.
Display text on the window's image as an overlay for delay milliseconds. This is not editing the image's data. The text is display on the top of the image.
:param name:Name of the window
:param text:Overlay text to write on the window's image
:param delay:Delay to display the overlay text. If this function is called before the previous overlay text time out, the timer is restarted and the text updated. . If this value is zero, the text never disapers.
:param name:Name of the window
:param text:Overlay text to write on the window's image
:param delay:Delay to display the overlay text. If this function is called before the previous overlay text time out, the timer is restarted and the text updated. . If this value is zero, the text never disapers.
The function
``displayOverlay``
aims at displaying useful information/tips on the window for a certain amount of time
The function ``displayOverlay`` aims at displaying useful information/tips on the window for a certain amount of time
*delay*
. This information is display on the top of the window.
. This information is display on the top of the window.
..index:: displayStatusBar
cv::displayStatusBar
--------------------
..cfunction:: void displayStatusBar(const string\& name, const string\& text, int delayms)
`id=0.132014751496 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/highgui/displayStatusBar>`__
Display text on the window's statusbar as for delay milliseconds.
:param name:Name of the window
:param text:Text to write on the window's statusbar
:param delay:Delay to display the text. If this function is called before the previous text time out, the timer is restarted and the text updated. If this value is zero, the text never disapers.
..cfunction:: void displayStatusBar(const string\& name, const string\& text, int delayms)
The function ``displayOverlay`` aims at displaying useful information/tips on the window for a certain amount of time
*delay*
. This information is displayed on the window's statubar (the window must be created with ``CV_GUI_EXPANDED`` flags).
Display text on the window's statusbar as for delay milliseconds.
Create a callback function called to draw OpenGL on top the the image display by windowname.
:param name:Name of the window
:param text:Text to write on the window's statusbar
:param delay:Delay to display the text. If this function is called before the previous text time out, the timer is restarted and the text updated. If this value is zero, the text never disapers.
The function
``displayOverlay``
aims at displaying useful information/tips on the window for a certain amount of time
*delay*
. This information is displayed on the window's statubar (the window must be created with
``CV_GUI_EXPANDED``
flags).
:param window_name:Name of the window
:param callbackOpenGL:
Pointer to the function to be called every frame.
This function should be prototyped as ``void Foo(*void);`` .
..index:: createOpenGLCallback
:param userdata:pointer passed to the callback function. *(Optional)*
:param angle:Specifies the field of view angle, in degrees, in the y direction.. *(Optional - Default 45 degree)*
cv::createOpenGLCallback
------------------------
:param zmin:Specifies the distance from the viewer to the near clipping plane (always positive). *(Optional - Default 0.01)*
`id=0.0486773148219 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/highgui/createOpenGLCallback>`__
:param zmax:Specifies the distance from the viewer to the far clipping plane (always positive). *(Optional - Default 1000)*
The function ``createOpenGLCallback`` can be used to draw 3D data on the window. An example of callback could be: ::
load size, location, flags, trackbars' value, zoom and panning location of the window
The function ``loadWindowParameters`` load size, location, flags, trackbars' value, zoom and panning location of the window
*window_name*
..index:: createButton
cv::createButton
----------------
*_*
`id=0.367650849719 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/highgui/createButton>`__
..cfunction:: createButton( const string\& button_name CV_DEFAULT(NULL),ButtonCallback on_change CV_DEFAULT(NULL), void* userdata CV_DEFAULT(NULL) , int button_type CV_DEFAULT(CV_PUSH_BUTTON), int initial_button_state CV_DEFAULT(0)
Create a callback function called to draw OpenGL on top the the image display by windowname.
*_*
:param button_name:Name of the button *( if NULL, the name will be "button <number of boutton>")*
:param on_change:
Pointer to the function to be called every time the button changed its state.
This function should be prototyped as ``void Foo(int state,*void);`` . *state* is the current state of the button. It could be -1 for a push button, 0 or 1 for a check/radio box button.
..cfunction:: createButton( const string\& button_name CV_DEFAULT(NULL),ButtonCallback on_change CV_DEFAULT(NULL), void* userdata CV_DEFAULT(NULL) , int button_type CV_DEFAULT(CV_PUSH_BUTTON), int initial_button_state CV_DEFAULT(0)
:param userdata:pointer passed to the callback function. *(Optional)*
Create a callback function called to draw OpenGL on top the the image display by windowname.
:param button_name:Name of the button *( if NULL, the name will be "button <number of boutton>")*
:param on_change:
Pointer to the function to be called every time the button changed its state.
This function should be prototyped as ``void Foo(int state,*void);`` . *state* is the current state of the button. It could be -1 for a push button, 0 or 1 for a check/radio box button.
:param userdata:pointer passed to the callback function. *(Optional)*
The
``button_type``
parameter can be :
*(Optional -- Will be a push button by default.)
* **CV_PUSH_BUTTON** The button will be a push button.
* **CV_CHECKBOX** The button will be a checkbox button.
* **CV_RADIOBOX** The button will be a radiobox button. The radiobox on the same buttonbar (same line) are exclusive; one on can be select at the time.
*
The ``button_type`` parameter can be :
*(Optional -- Will be a push button by default.)
* **CV_PUSH_BUTTON** The button will be a push button.
* **initial_button_state** Default state of the button. Use for checkbox and radiobox, its value could be 0 or 1. *(Optional)*
The function
``createButton``
attach a button to the control panel. Each button is added to a buttonbar on the right of the last button.
A new buttonbar is create if nothing was attached to the control panel before, or if the last element attached to the control panel was a trackbar.
Here are various example of
``createButton``
function call:
* **CV_CHECKBOX** The button will be a checkbox button.
* **CV_RADIOBOX** The button will be a radiobox button. The radiobox on the same buttonbar (same line) are exclusive; one on can be select at the time.
*
::
* **initial_button_state** Default state of the button. Use for checkbox and radiobox, its value could be 0 or 1. *(Optional)*
The function ``createButton`` attach a button to the control panel. Each button is added to a buttonbar on the right of the last button.
A new buttonbar is create if nothing was attached to the control panel before, or if the last element attached to the control panel was a trackbar.
createButton(NULL,callbackButton);//create a push button "button 0", that will call callbackButton.
:param ext:The file extension that defines the output format
:param img:The image to be written
:param buf:The output buffer; resized to fit the compressed image
:param ext:The file extension that defines the output format
:param img:The image to be written
:param buf:The output buffer; resized to fit the compressed image
:param params:The format-specific parameters; see :ref:`imwrite`
:param params:The format-specific parameters; see :ref:`imwrite`
The function compresses the image and stores it in the memory buffer, which is resized to fit the result.
See
:ref:`imwrite`
for the list of supported formats and the flags description.
See
:ref:`imwrite` for the list of supported formats and the flags description.
..index:: imread
cv::imread
----------
`id=0.16110153292 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/highgui/imread>`__
..cfunction:: Mat imread( const string\& filename, int flags=1 )
Loads an image from a file.
:param filename:Name of file to be loaded.
:param flags:Specifies color type of the loaded image:
* **>0** the loaded image is forced to be a 3-channel color image
* **=0** the loaded image is forced to be grayscale
:param filename:Name of file to be loaded.
:param flags:Specifies color type of the loaded image:
* **>0** the loaded image is forced to be a 3-channel color image
* **=0** the loaded image is forced to be grayscale
* **<0** the loaded image will be loaded as-is (note that in the current implementation the alpha channel, if any, is stripped from the output image, e.g. 4-channel RGBA image will be loaded as RGB if :math:`flags\ge0` ).
The function
``imread``
loads an image from the specified file and returns it. If the image can not be read (because of missing file, improper permissions, unsupported or invalid format), the function returns empty matrix (
``Mat::data==NULL``
).Currently, the following file formats are supported:
* **<0** the loaded image will be loaded as-is (note that in the current implementation the alpha channel, if any, is stripped from the output image, e.g. 4-channel RGBA image will be loaded as RGB if :math:`flags\ge0` ).
The function ``imread`` loads an image from the specified file and returns it. If the image can not be read (because of missing file, improper permissions, unsupported or invalid format), the function returns empty matrix ( ``Mat::data==NULL`` ).Currently, the following file formats are supported:
*
Windows bitmaps -
``*.bmp, *.dib``
(always supported)
Windows bitmaps - ``*.bmp, *.dib`` (always supported)
*
JPEG files -
``*.jpeg, *.jpg, *.jpe``
(see
JPEG files - ``*.jpeg, *.jpg, *.jpe`` (see
**Note2**
)
*
JPEG 2000 files -
``*.jp2``
(see
JPEG 2000 files - ``*.jp2`` (see
**Note2**
)
*
Portable Network Graphics -
``*.png``
(see
Portable Network Graphics - ``*.png`` (see
**Note2**
)
*
Portable image format -
``*.pbm, *.pgm, *.ppm``
(always supported)
Portable image format - ``*.pbm, *.pgm, *.ppm`` (always supported)
*
Sun rasters -
``*.sr, *.ras``
(always supported)
Sun rasters - ``*.sr, *.ras`` (always supported)
*
TIFF files -
``*.tiff, *.tif``
(see
TIFF files - ``*.tiff, *.tif`` (see
**Note2**
)
**Note1**
: The function determines type of the image by the content, not by the file extension.
**Note2**
: On Windows and MacOSX the shipped with OpenCV image codecs (libjpeg, libpng, libtiff and libjasper) are used by default; so OpenCV can always read JPEGs, PNGs and TIFFs. On MacOSX there is also the option to use native MacOSX image readers. But beware that currently these native image loaders give images with somewhat different pixel values, because of the embedded into MacOSX color management.
On Linux, BSD flavors and other Unix-like open-source operating systems OpenCV looks for the supplied with OS image codecs. Please, install the relevant packages (do not forget the development files, e.g. "libjpeg-dev" etc. in Debian and Ubuntu) in order to get the codec support, or turn on
``OPENCV_BUILD_3RDPARTY_LIBS``
flag in CMake.
On Linux, BSD flavors and other Unix-like open-source operating systems OpenCV looks for the supplied with OS image codecs. Please, install the relevant packages (do not forget the development files, e.g. "libjpeg-dev" etc. in Debian and Ubuntu) in order to get the codec support, or turn on ``OPENCV_BUILD_3RDPARTY_LIBS`` flag in CMake.
..index:: imwrite
cv::imwrite
-----------
`id=0.00846497387051 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/highgui/imwrite>`__
:param params:The format-specific save parameters, encoded as pairs ``paramId_1, paramValue_1, paramId_2, paramValue_2, ...`` . The following parameters are currently supported:
:param filename:Name of the file.
:param img:The image to be saved.
:param params:The format-specific save parameters, encoded as pairs ``paramId_1, paramValue_1, paramId_2, paramValue_2, ...`` . The following parameters are currently supported:
* In the case of JPEG it can be a quality ( ``CV_IMWRITE_JPEG_QUALITY`` ), from 0 to 100 (the higher is the better), 95 by default.
* In the case of PNG it can be the compression level ( ``CV_IMWRITE_PNG_COMPRESSION`` ), from 0 to 9 (the higher value means smaller size and longer compression time), 3 by default.
* In the case of PPM, PGM or PBM it can a binary format flag ( ``CV_IMWRITE_PXM_BINARY`` ), 0 or 1, 1 by default.
The function
``imwrite``
saves the image to the specified file. The image format is chosen based on the
``filename``
extension, see
:ref:`imread`
for the list of extensions. Only 8-bit (or 16-bit in the case of PNG, JPEG 2000 and TIFF) single-channel or 3-channel (with 'BGR' channel order) images can be saved using this function. If the format, depth or channel order is different, use
:ref:`Mat::convertTo`
, and
:ref:`cvtColor`
to convert it before saving, or use the universal XML I/O functions to save the image to XML or YAML format.
* In the case of PPM, PGM or PBM it can a binary format flag ( ``CV_IMWRITE_PXM_BINARY`` ), 0 or 1, 1 by default.
The function ``imwrite`` saves the image to the specified file. The image format is chosen based on the ``filename`` extension, see
:ref:`imread` for the list of extensions. Only 8-bit (or 16-bit in the case of PNG, JPEG 2000 and TIFF) single-channel or 3-channel (with 'BGR' channel order) images can be saved using this function. If the format, depth or channel order is different, use
:ref:`Mat::convertTo` , and
:ref:`cvtColor` to convert it before saving, or use the universal XML I/O functions to save the image to XML or YAML format.
..index:: VideoCapture
@ -250,22 +127,10 @@ to convert it before saving, or use the universal XML I/O functions to save the
VideoCapture
------------
`id=0.267295181599 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/highgui/VideoCapture>`__
..ctype:: VideoCapture
Class for video capturing from video files or cameras ::
Class for video capturing from video files or cameras
::
class VideoCapture
{
public:
@ -275,24 +140,24 @@ Class for video capturing from video files or cameras
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();
@ -301,39 +166,30 @@ Class for video capturing from video files or cameras
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
// 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:
The class provides C++ video capturing API. Here is how the class can be used: ::
::
#include "cv.h"
#include "highgui.h"
using namespace cv;
int main(int, char**)
{
VideoCapture cap(0); // open the default camera
if(!cap.isOpened()) // check if we succeeded
return -1;
Mat edges;
namedWindow("edges",1);
for(;;)
@ -349,276 +205,161 @@ The class provides C++ video capturing API. Here is how the class can be used:
// the camera will be deinitialized automatically in VideoCapture destructor
return 0;
}
..
..index:: VideoCapture::VideoCapture
cv::VideoCapture::VideoCapture
------------------------------
..cfunction:: VideoCapture::VideoCapture()
`id=0.788880569149 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/highgui/VideoCapture%3A%3AVideoCapture>`__
`id=0.122963695249 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/highgui/createTrackbar>`__
..cfunction:: int createTrackbar( const string\& trackbarname, const string\& winname, int* value, int count, TrackbarCallback onChange CV_DEFAULT(0), void* userdata CV_DEFAULT(0))
Creates a trackbar and attaches it to the specified window
:param trackbarname:Name of the created trackbar.
:param winname:Name of the window which will be used as a parent of the created trackbar.
:param value:The optional pointer to an integer variable, whose value will reflect the position of the slider. Upon creation, the slider position is defined by this variable.
:param count:The maximal position of the slider. The minimal position is always 0.
:param trackbarname:Name of the created trackbar.
:param winname:Name of the window which will be used as a parent of the created trackbar.
:param value:The optional pointer to an integer variable, whose value will reflect the position of the slider. Upon creation, the slider position is defined by this variable.
:param count:The maximal position of the slider. The minimal position is always 0.
:param onChange:Pointer to the function to be called every time the slider changes position. This function should be prototyped as ``void Foo(int,void*);`` , where the first parameter is the trackbar position and the second parameter is the user data (see the next parameter). If the callback is NULL pointer, then no callbacks is called, but only ``value`` is updated
:param userdata:The user data that is passed as-is to the callback; it can be used to handle trackbar events without using global variables
The function
``createTrackbar``
creates a trackbar (a.k.a. slider or range control) with the specified name and range, assigns a variable
``value``
to be syncronized with trackbar position and specifies a callback function
``onChange``
to be called on the trackbar position change. The created trackbar is displayed on the top of the given window.
:param onChange:Pointer to the function to be called every time the slider changes position. This function should be prototyped as ``void Foo(int,void*);`` , where the first parameter is the trackbar position and the second parameter is the user data (see the next parameter). If the callback is NULL pointer, then no callbacks is called, but only ``value`` is updated
:param userdata:The user data that is passed as-is to the callback; it can be used to handle trackbar events without using global variables
The function ``createTrackbar`` creates a trackbar (a.k.a. slider or range control) with the specified name and range, assigns a variable ``value`` to be syncronized with trackbar position and specifies a callback function ``onChange`` to be called on the trackbar position change. The created trackbar is displayed on the top of the given window.
\
\
**[Qt Backend Only]**
qt-specific details:
* **winname** Name of the window which will be used as a parent for created trackbar. Can be NULL if the trackbar should be attached to the control panel.
* **winname** Name of the window which will be used as a parent for created trackbar. Can be NULL if the trackbar should be attached to the control panel.
The created trackbar is displayed at the bottom of the given window if
The created trackbar is displayed at the bottom of the given window if
*winname*
is correctly provided, or displayed on the control panel if
is correctly provided, or displayed on the control panel if
*winname*
is NULL.
By clicking on the label of each trackbar, it is possible to edit the trackbar's value manually for a more accurate control of it.
..index:: getTrackbarPos
cv::getTrackbarPos
------------------
`id=0.51821188779 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/highgui/getTrackbarPos>`__
..cfunction:: int getTrackbarPos( const string\& trackbarname, const string\& winname )
Returns the trackbar position.
:param trackbarname:Name of the trackbar.
:param winname:Name of the window which is the parent of the trackbar.
:param trackbarname:Name of the trackbar.
:param winname:Name of the window which is the parent of the trackbar.
The function returns the current position of the specified trackbar.
\
\
**[Qt Backend Only]**
qt-specific details:
* **winname** Name of the window which is the parent of the trackbar. Can be NULL if the trackbar is attached to the control panel.
* **winname** Name of the window which is the parent of the trackbar. Can be NULL if the trackbar is attached to the control panel.
..index:: imshow
cv::imshow
----------
`id=0.765508098436 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/highgui/imshow>`__
displays the image in the specified window. If the window was created with the
``CV_WINDOW_AUTOSIZE``
flag then the image is shown with its original size, otherwise the image is scaled to fit in the window. The function may scale the image, depending on its depth:
The function ``imshow`` displays the image in the specified window. If the window was created with the ``CV_WINDOW_AUTOSIZE`` flag then the image is shown with its original size, otherwise the image is scaled to fit in the window. The function may scale the image, depending on its depth:
*
If the image is 8-bit unsigned, it is displayed as is.
*
If the image is 16-bit unsigned or 32-bit integer, the pixels are divided by 256. That is, the value range [0,255*256] is mapped to [0,255].
*
If the image is 32-bit floating-point, the pixel values are multiplied by 255. That is, the value range [0,1] is mapped to [0,255].
..index:: namedWindow
cv::namedWindow
---------------
`id=0.618574996458 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/highgui/namedWindow>`__
..cfunction:: void namedWindow( const string\& winname, int flags )
Creates a window.
:param name:Name of the window in the window caption that may be used as a window identifier.
:param flags:Flags of the window. Currently the only supported flag is ``CV_WINDOW_AUTOSIZE`` . If this is set, the window size is automatically adjusted to fit the displayed image (see :ref:`imshow` ), and the user can not change the window size manually.
:param name:Name of the window in the window caption that may be used as a window identifier.
:param flags:Flags of the window. Currently the only supported flag is ``CV_WINDOW_AUTOSIZE`` . If this is set, the window size is automatically adjusted to fit the displayed image (see :ref:`imshow` ), and the user can not change the window size manually.
The function
``namedWindow``
creates a window which can be used as a placeholder for images and trackbars. Created windows are referred to by their names.
The function ``namedWindow`` creates a window which can be used as a placeholder for images and trackbars. Created windows are referred to by their names.
If a window with the same name already exists, the function does nothing.
\
@ -199,113 +102,58 @@ If a window with the same name already exists, the function does nothing.
**[Qt Backend Only]**
qt-specific details:
* **flags** Flags of the window. Currently the supported flags are:
* **flags** Flags of the window. Currently the supported flags are:
* **CV_WINDOW_NORMAL or CV_WINDOW_AUTOSIZE:** ``CV_WINDOW_NORMAL`` let the user resize the window, whereas ``CV_WINDOW_AUTOSIZE`` adjusts automatically the window's size to fit the displayed image (see :ref:`ShowImage` ), and the user can not change the window size manually.
* **CV_WINDOW_FREERATIO or CV_WINDOW_KEEPRATIO:** ``CV_WINDOW_FREERATIO`` adjust the image without respect the its ration, whereas ``CV_WINDOW_KEEPRATIO`` keep the image's ratio.
* **CV_GUI_NORMAL or CV_GUI_EXPANDED:** ``CV_GUI_NORMAL`` is the old way to draw the window without statusbar and toolbar, whereas ``CV_GUI_EXPANDED`` is the new enhance GUI.
This parameter is optional. The default flags set for a new window are ``CV_WINDOW_AUTOSIZE`` , ``CV_WINDOW_KEEPRATIO`` , and ``CV_GUI_EXPANDED`` .
However, if you want to modify the flags, you can combine them using OR operator, ie:
* **CV_WINDOW_NORMAL or CV_WINDOW_AUTOSIZE:** ``CV_WINDOW_NORMAL`` let the user resize the window, whereas ``CV_WINDOW_AUTOSIZE`` adjusts automatically the window's size to fit the displayed image (see :ref:`ShowImage` ), and the user can not change the window size manually.
* **CV_WINDOW_FREERATIO or CV_WINDOW_KEEPRATIO:** ``CV_WINDOW_FREERATIO`` adjust the image without respect the its ration, whereas ``CV_WINDOW_KEEPRATIO`` keep the image's ratio.
cv::setTrackbarPos
------------------
* **CV_GUI_NORMAL or CV_GUI_EXPANDED:** ``CV_GUI_NORMAL`` is the old way to draw the window without statusbar and toolbar, whereas ``CV_GUI_EXPANDED`` is the new enhance GUI.
`id=0.247665233354 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/highgui/setTrackbarPos>`__
This parameter is optional. The default flags set for a new window are ``CV_WINDOW_AUTOSIZE`` , ``CV_WINDOW_KEEPRATIO`` , and ``CV_GUI_EXPANDED`` .
However, if you want to modify the flags, you can combine them using OR operator, ie:
:param winname:Name of the window which is the parent of trackbar.
:param pos:The new position.
:param trackbarname:Name of the trackbar.
:param winname:Name of the window which is the parent of trackbar.
:param pos:The new position.
The function sets the position of the specified trackbar in the specified window.
\
\
**[Qt Backend Only]**
qt-specific details:
* **winname** Name of the window which is the parent of trackbar. Can be NULL if the trackbar is attached to the control panel.
* **winname** Name of the window which is the parent of trackbar. Can be NULL if the trackbar is attached to the control panel.
..index:: waitKey
cv::waitKey
-----------
`id=0.777845991089 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/highgui/waitKey>`__
..cfunction:: int waitKey(int delay=0)
Waits for a pressed key.
:param delay:Delay in milliseconds. 0 is the special value that means "forever"
:param delay:Delay in milliseconds. 0 is the special value that means "forever"
The function
``waitKey``
waits for key event infinitely (when
:math:`\texttt{delay}\leq 0`
) or for
``delay``
milliseconds, when it's positive. Returns the code of the pressed key or -1 if no key was pressed before the specified time had elapsed.
The function ``waitKey`` waits for key event infinitely (when
:math:`\texttt{delay}\leq 0` ) or for ``delay`` milliseconds, when it's positive. Returns the code of the pressed key or -1 if no key was pressed before the specified time had elapsed.
**Note:**
This function is the only method in HighGUI that can fetch and handle events, so it needs to be called periodically for normal event processing, unless HighGUI is used within some environment that takes care of event processing.
:param edges:The output edge map. It will have the same size and the same type as ``image``
:param threshold1:The first threshold for the hysteresis procedure
:param threshold2:The second threshold for the hysteresis procedure
:param apertureSize:Aperture size for the :func:`Sobel` operator
:param L2gradient:Indicates, whether the more accurate :math:`L_2` norm :math:`=\sqrt{(dI/dx)^2 + (dI/dy)^2}` should be used to compute the image gradient magnitude ( ``L2gradient=true`` ), or a faster default :math:`L_1` norm :math:`=|dI/dx|+|dI/dy|` is enough ( ``L2gradient=false`` )
:param image:Single-channel 8-bit input image
:param edges:The output edge map. It will have the same size and the same type as ``image``
:param threshold1:The first threshold for the hysteresis procedure
:param threshold2:The second threshold for the hysteresis procedure
:param apertureSize:Aperture size for the :func:`Sobel` operator
:param L2gradient:Indicates, whether the more accurate :math:`L_2` norm :math:`=\sqrt{(dI/dx)^2 + (dI/dy)^2}` should be used to compute the image gradient magnitude ( ``L2gradient=true`` ), or a faster default :math:`L_1` norm :math:`=|dI/dx|+|dI/dy|` is enough ( ``L2gradient=false`` )
The function finds edges in the input image
``image``
and marks them in the output map
``edges``
using the Canny algorithm. The smallest value between
``threshold1``
and
``threshold2``
is used for edge linking, the largest value is used to find the initial segments of strong edges, see
The function finds edges in the input image ``image`` and marks them in the output map ``edges`` using the Canny algorithm. The smallest value between ``threshold1`` and ``threshold2`` is used for edge linking, the largest value is used to find the initial segments of strong edges, see
http://en.wikipedia.org/wiki/Canny_edge_detector
..index:: cornerEigenValsAndVecs
cv::cornerEigenValsAndVecs
--------------------------
`id=0.211221916008 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/imgproc/cornerEigenValsAndVecs>`__
..cfunction:: void cornerEigenValsAndVecs( const Mat\& src, Mat\& dst, int blockSize, int apertureSize, int borderType=BORDER_DEFAULT )
Calculates eigenvalues and eigenvectors of image blocks for corner detection.
:param src:Input single-channel 8-bit or floating-point image
:param dst:Image to store the results. It will have the same size as ``src`` and the type ``CV_32FC(6)``
:param blockSize:Neighborhood size (see discussion)
:param apertureSize:Aperture parameter for the :func:`Sobel` operator
:param src:Input single-channel 8-bit or floating-point image
:param dst:Image to store the results. It will have the same size as ``src`` and the type ``CV_32FC(6)``
:param blockSize:Neighborhood size (see discussion)
:param apertureSize:Aperture parameter for the :func:`Sobel` operator
:param boderType:Pixel extrapolation method; see :func:`borderInterpolate`
For every pixel
:math:`p`
, the function
``cornerEigenValsAndVecs``
considers a
``blockSize``
:math:`\times`
``blockSize``
neigborhood
:math:`S(p)`
. It calculates the covariation matrix of derivatives over the neighborhood as:
:param boderType:Pixel extrapolation method; see :func:`borderInterpolate`
For every pixel
:math:`p` , the function ``cornerEigenValsAndVecs`` considers a ``blockSize``:math:`\times```blockSize`` neigborhood
:math:`S(p)` . It calculates the covariation matrix of derivatives over the neighborhood as:
:param corners:Initial coordinates of the input corners; refined coordinates on output
:param winSize:Half of the side length of the search window. For example, if ``winSize=Size(5,5)`` , then a :math:`5*2+1 \times 5*2+1 = 11 \times 11` search window would be used
:param zeroZone:Half of the size of the dead region in the middle of the search zone over which the summation in the formula below is not done. It is used sometimes to avoid possible singularities of the autocorrelation matrix. The value of (-1,-1) indicates that there is no such size
:param image:Input image
:param corners:Initial coordinates of the input corners; refined coordinates on output
:param winSize:Half of the side length of the search window. For example, if ``winSize=Size(5,5)`` , then a :math:`5*2+1 \times 5*2+1 = 11 \times 11` search window would be used
:param zeroZone:Half of the size of the dead region in the middle of the search zone over which the summation in the formula below is not done. It is used sometimes to avoid possible singularities of the autocorrelation matrix. The value of (-1,-1) indicates that there is no such size
:param criteria:Criteria for termination of the iterative process of corner refinement. That is, the process of corner position refinement stops either after a certain number of iterations or when a required accuracy is achieved. The ``criteria`` may specify either of or both the maximum number of iteration and the required accuracy
The function iterates to find the sub-pixel accurate location of corners, or radial saddle points, as shown in on the picture below.
:param criteria:Criteria for termination of the iterative process of corner refinement. That is, the process of corner position refinement stops either after a certain number of iterations or when a required accuracy is achieved. The ``criteria`` may specify either of or both the maximum number of iteration and the required accuracy
The function iterates to find the sub-pixel accurate location of corners, or radial saddle points, as shown in on the picture below.
..image:: ../../pics/cornersubpix.png
Sub-pixel accurate corner locator is based on the observation that every vector from the center
:math:`q`
to a point
:math:`p`
located within a neighborhood of
:math:`q`
is orthogonal to the image gradient at
:math:`p`
subject to image and measurement noise. Consider the expression:
Sub-pixel accurate corner locator is based on the observation that every vector from the center
:math:`q` to a point
:math:`p` located within a neighborhood of
:math:`q` is orthogonal to the image gradient at
:math:`p` subject to image and measurement noise. Consider the expression:
..math::
\epsilon _i = {DI_{p_i}}^T \cdot (q - p_i)
where
:math:`{DI_{p_i}}`
is the image gradient at the one of the points
:math:`p_i`
in a neighborhood of
:math:`q`
. The value of
:math:`q`
is to be found such that
:math:`\epsilon_i`
is minimized. A system of equations may be set up with
:math:`\epsilon_i`
set to zero:
\epsilon _i = {DI_{p_i}}^T \cdot (q - p_i)
where
:math:`{DI_{p_i}}` is the image gradient at the one of the points
:math:`p_i` in a neighborhood of
:math:`q` . The value of
:math:`q` is to be found such that
:math:`\epsilon_i` is minimized. A system of equations may be set up with
:param corners:The output vector of detected corners
Determines strong corners on an image.
:param maxCorners:The maximum number of corners to return. If there are more corners than that will be found, the strongest of them will be returned
:param qualityLevel:Characterizes the minimal accepted quality of image corners; the value of the parameter is multiplied by the by the best corner quality measure (which is the min eigenvalue, see :func:`cornerMinEigenVal` , or the Harris function response, see :func:`cornerHarris` ). The corners, which quality measure is less than the product, will be rejected. For example, if the best corner has the quality measure = 1500, and the ``qualityLevel=0.01`` , then all the corners which quality measure is less than 15 will be rejected.
:param minDistance:The minimum possible Euclidean distance between the returned corners
:param mask:The optional region of interest. If the image is not empty (then it needs to have the type ``CV_8UC1`` and the same size as ``image`` ), it will specify the region in which the corners are detected
:param blockSize:Size of the averaging block for computing derivative covariation matrix over each pixel neighborhood, see :func:`cornerEigenValsAndVecs`
:param useHarrisDetector:Indicates, whether to use operator or :func:`cornerMinEigenVal`
:param k:Free parameter of Harris detector
:param image:The input 8-bit or floating-point 32-bit, single-channel image
:param corners:The output vector of detected corners
:param maxCorners:The maximum number of corners to return. If there are more corners than that will be found, the strongest of them will be returned
:param qualityLevel:Characterizes the minimal accepted quality of image corners; the value of the parameter is multiplied by the by the best corner quality measure (which is the min eigenvalue, see :func:`cornerMinEigenVal` , or the Harris function response, see :func:`cornerHarris` ). The corners, which quality measure is less than the product, will be rejected. For example, if the best corner has the quality measure = 1500, and the ``qualityLevel=0.01`` , then all the corners which quality measure is less than 15 will be rejected.
:param minDistance:The minimum possible Euclidean distance between the returned corners
:param mask:The optional region of interest. If the image is not empty (then it needs to have the type ``CV_8UC1`` and the same size as ``image`` ), it will specify the region in which the corners are detected
:param blockSize:Size of the averaging block for computing derivative covariation matrix over each pixel neighborhood, see :func:`cornerEigenValsAndVecs`
:param useHarrisDetector:Indicates, whether to use operator or :func:`cornerMinEigenVal`
:param k:Free parameter of Harris detector
The function finds the most prominent corners in the image or in the specified image region, as described
in
in
Shi94
:
#.
the function first calculates the corner quality measure at every source image pixel using the
:func:`cornerMinEigenVal`
or
the function first calculates the corner quality measure at every source image pixel using the
:func:`cornerMinEigenVal` or
:func:`cornerHarris`
#.
then it performs non-maxima suppression (the local maxima in
:math:`3\times 3`
neighborhood
then it performs non-maxima suppression (the local maxima in
:math:`3\times 3` neighborhood
are retained).
#.
the next step rejects the corners with the minimal eigenvalue less than
the remaining corners are then sorted by the quality measure in the descending order.
#.
finally, the function throws away each corner
:math:`pt_j`
if there is a stronger corner
:math:`pt_i`
(
:math:`i < j`
) such that the distance between them is less than
``minDistance``
finally, the function throws away each corner
:math:`pt_j` if there is a stronger corner
:math:`pt_i` (
:math:`i < j` ) such that the distance between them is less than ``minDistance``
The function can be used to initialize a point-based tracker of an object.
Note that the if the function is called with different values
``A``
and
``B``
of the parameter
``qualityLevel``
, and
``A``
> {B}, the vector of returned corners with
``qualityLevel=A``
will be the prefix of the output vector with
``qualityLevel=B``
.
See also:
:func:`cornerMinEigenVal`
,
:func:`cornerHarris`
,
:func:`calcOpticalFlowPyrLK`
,
:func:`estimateRigidMotion`
,
:func:`PlanarObjectDetector`
,
:func:`OneWayDescriptor`
Note that the if the function is called with different values ``A`` and ``B`` of the parameter ``qualityLevel`` , and ``A`` > {B}, the vector of returned corners with ``qualityLevel=A`` will be the prefix of the output vector with ``qualityLevel=B`` .
:param circles:The output vector of found circles. Each vector is encoded as 3-element floating-point vector :math:`(x, y, radius)`
:param method:Currently, the only implemented method is ``CV_HOUGH_GRADIENT`` , which is basically *21HT* , described in Yuen90 .
:param dp:The inverse ratio of the accumulator resolution to the image resolution. For example, if ``dp=1`` , the accumulator will have the same resolution as the input image, if ``dp=2`` - accumulator will have half as big width and height, etc
:param minDist:Minimum distance between the centers of the detected circles. If the parameter is too small, multiple neighbor circles may be falsely detected in addition to a true one. If it is too large, some circles may be missed
:param circles:The output vector of found circles. Each vector is encoded as 3-element floating-point vector :math:`(x, y, radius)`
:param method:Currently, the only implemented method is ``CV_HOUGH_GRADIENT`` , which is basically *21HT* , described in Yuen90 .
:param dp:The inverse ratio of the accumulator resolution to the image resolution. For example, if ``dp=1`` , the accumulator will have the same resolution as the input image, if ``dp=2`` - accumulator will have half as big width and height, etc
:param minDist:Minimum distance between the centers of the detected circles. If the parameter is too small, multiple neighbor circles may be falsely detected in addition to a true one. If it is too large, some circles may be missed
:param param1:The first method-specific parameter. in the case of ``CV_HOUGH_GRADIENT`` it is the higher threshold of the two passed to :func:`Canny` edge detector (the lower one will be twice smaller)
:param param2:The second method-specific parameter. in the case of ``CV_HOUGH_GRADIENT`` it is the accumulator threshold at the center detection stage. The smaller it is, the more false circles may be detected. Circles, corresponding to the larger accumulator values, will be returned first
:param minRadius:Minimum circle radius
:param maxRadius:Maximum circle radius
The function finds circles in a grayscale image using some modification of Hough transform. Here is a short usage example:
:param param1:The first method-specific parameter. in the case of ``CV_HOUGH_GRADIENT`` it is the higher threshold of the two passed to :func:`Canny` edge detector (the lower one will be twice smaller)
:param param2:The second method-specific parameter. in the case of ``CV_HOUGH_GRADIENT`` it is the accumulator threshold at the center detection stage. The smaller it is, the more false circles may be detected. Circles, corresponding to the larger accumulator values, will be returned first
:param minRadius:Minimum circle radius
:param maxRadius:Maximum circle radius
::
The function finds circles in a grayscale image using some modification of Hough transform. Here is a short usage example: ::
#include <cv.h>
#include <highgui.h>
#include <math.h>
using namespace cv;
int main(int argc, char** argv)
{
Mat img, gray;
@ -566,144 +289,84 @@ The function finds circles in a grayscale image using some modification of Hough
imshow( "circles", img );
return 0;
}
..
Note that usually the function detects the circles' centers well, however it may fail to find the correct radii. You can assist the function by specifying the radius range (
``minRadius``
and
``maxRadius``
) if you know it, or you may ignore the returned radius, use only the center and find the correct radius using some additional procedure.
See also:
:func:`fitEllipse`
,
:func:`minEnclosingCircle`
Note that usually the function detects the circles' centers well, however it may fail to find the correct radii. You can assist the function by specifying the radius range ( ``minRadius`` and ``maxRadius`` ) if you know it, or you may ignore the returned radius, use only the center and find the correct radius using some additional procedure.
See also:
:func:`fitEllipse`,:func:`minEnclosingCircle`
..index:: HoughLines
cv::HoughLines
--------------
`id=0.877791227007 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/imgproc/HoughLines>`__
Finds lines in a binary image using standard Hough transform.
:param image:The 8-bit, single-channel, binary source image. The image may be modified by the function
:param lines:The output vector of lines. Each line is represented by a two-element vector :math:`(\rho, \theta)` . :math:`\rho` is the distance from the coordinate origin :math:`(0,0)` (top-left corner of the image) and :math:`\theta` is the line rotation angle in radians ( :math:`0 \sim \textrm{vertical line}, \pi/2 \sim \textrm{horizontal line}` )
:param rho:Distance resolution of the accumulator in pixels
:param theta:Angle resolution of the accumulator in radians
:param image:The 8-bit, single-channel, binary source image. The image may be modified by the function
:param lines:The output vector of lines. Each line is represented by a two-element vector :math:`(\rho, \theta)` . :math:`\rho` is the distance from the coordinate origin :math:`(0,0)` (top-left corner of the image) and :math:`\theta` is the line rotation angle in radians ( :math:`0 \sim \textrm{vertical line}, \pi/2 \sim \textrm{horizontal line}` )
:param rho:Distance resolution of the accumulator in pixels
:param theta:Angle resolution of the accumulator in radians
:param threshold:The accumulator threshold parameter. Only those lines are returned that get enough votes ( :math:`>\texttt{threshold}` )
:param srn:For the multi-scale Hough transform it is the divisor for the distance resolution ``rho`` . The coarse accumulator distance resolution will be ``rho`` and the accurate accumulator resolution will be ``rho/srn`` . If both ``srn=0`` and ``stn=0`` then the classical Hough transform is used, otherwise both these parameters should be positive.
:param stn:For the multi-scale Hough transform it is the divisor for the distance resolution ``theta``
The function implements standard or standard multi-scale Hough transform algorithm for line detection. See
:func:`HoughLinesP`
for the code example.
:param threshold:The accumulator threshold parameter. Only those lines are returned that get enough votes ( :math:`>\texttt{threshold}` )
:param srn:For the multi-scale Hough transform it is the divisor for the distance resolution ``rho`` . The coarse accumulator distance resolution will be ``rho`` and the accurate accumulator resolution will be ``rho/srn`` . If both ``srn=0`` and ``stn=0`` then the classical Hough transform is used, otherwise both these parameters should be positive.
:param stn:For the multi-scale Hough transform it is the divisor for the distance resolution ``theta``
The function implements standard or standard multi-scale Hough transform algorithm for line detection. See
:func:`HoughLinesP` for the code example.
..index:: HoughLinesP
cv::HoughLinesP
---------------
`id=0.855533341526 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/imgproc/HoughLinesP>`__
Finds lines segments in a binary image using probabilistic Hough transform.
:param image:The 8-bit, single-channel, binary source image. The image may be modified by the function
:param lines:The output vector of lines. Each line is represented by a 4-element vector :math:`(x_1, y_1, x_2, y_2)` , where :math:`(x_1,y_1)` and :math:`(x_2, y_2)` are the ending points of each line segment detected.
:param rho:Distance resolution of the accumulator in pixels
:param theta:Angle resolution of the accumulator in radians
:param image:The 8-bit, single-channel, binary source image. The image may be modified by the function
:param lines:The output vector of lines. Each line is represented by a 4-element vector :math:`(x_1, y_1, x_2, y_2)` , where :math:`(x_1,y_1)` and :math:`(x_2, y_2)` are the ending points of each line segment detected.
:param rho:Distance resolution of the accumulator in pixels
:param theta:Angle resolution of the accumulator in radians
:param threshold:The accumulator threshold parameter. Only those lines are returned that get enough votes ( :math:`>\texttt{threshold}` )
:param minLineLength:The minimum line length. Line segments shorter than that will be rejected
:param maxLineGap:The maximum allowed gap between points on the same line to link them.
The function implements probabilistic Hough transform algorithm for line detection, described in
Matas00
. Below is line detection example:
:param threshold:The accumulator threshold parameter. Only those lines are returned that get enough votes ( :math:`>\texttt{threshold}` )
:param minLineLength:The minimum line length. Line segments shorter than that will be rejected
::
:param maxLineGap:The maximum allowed gap between points on the same line to link them.
The function implements probabilistic Hough transform algorithm for line detection, described in
Matas00
. Below is line detection example: ::
/* This is a standalone program. Pass an image name as a first parameter
of the program. Switch between standard and probabilistic Hough transform
by changing "#if 1" to "#if 0" and back */
#include <cv.h>
#include <highgui.h>
#include <math.h>
using namespace cv;
int main(int argc, char** argv)
{
Mat src, dst, color_dst;
if( argc != 2 || !(src=imread(argv[1], 0)).data)
return -1;
Canny( src, dst, 50, 200, 3 );
cvtColor( dst, color_dst, CV_GRAY2BGR );
cvtColor( dst, color_dst, CV_GRAY2BGR );
#if 0
vector<Vec2f> lines;
HoughLines( dst, lines, 1, CV_PI/180, 100 );
for( size_t i = 0; i < lines.size(); i++ )
{
float rho = lines[i][0];
@ -727,103 +390,53 @@ Matas00
#endif
namedWindow( "Source", 1 );
imshow( "Source", src );
namedWindow( "Detected Lines", 1 );
imshow( "Detected Lines", color_dst );
waitKey(0);
return 0;
}
..
This is the sample picture the function parameters have been tuned for:
..image:: ../../pics/building.jpg
And this is the output of the above program in the case of probabilistic Hough transform
..image:: ../../pics/houghp.png
..index:: preCornerDetect
cv::preCornerDetect
-------------------
`id=0.828630230352 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/imgproc/preCornerDetect>`__
..cfunction:: void preCornerDetect( const Mat\& src, Mat\& dst, int apertureSize, int borderType=BORDER_DEFAULT )
Calculates the feature map for corner detection
:param src:The source single-channel 8-bit of floating-point image
:param src:The source single-channel 8-bit of floating-point image
:param dst:The output image; will have type ``CV_32F`` and the same size as ``src``
:param apertureSize:Aperture size of :func:`Sobel`
:param borderType:The pixel extrapolation method; see :func:`borderInterpolate`
:param dst:The output image; will have type ``CV_32F`` and the same size as ``src``
:param apertureSize:Aperture size of :func:`Sobel`
:param borderType:The pixel extrapolation method; see :func:`borderInterpolate`
The function calculates the complex spatial derivative-based function of the source image
The functions in this section perform various geometrical transformations of 2D images. That is, they do not change the image content, but deform the pixel grid, and map this deformed grid to the destination image. In fact, to avoid sampling artifacts, the mapping is done in the reverse order, from destination to the source. That is, for each pixel
:math:`(x, y)`
of the destination image, the functions compute coordinates of the corresponding "donor" pixel in the source image and copy the pixel value, that is:
The functions in this section perform various geometrical transformations of 2D images. That is, they do not change the image content, but deform the pixel grid, and map this deformed grid to the destination image. In fact, to avoid sampling artifacts, the mapping is done in the reverse order, from destination to the source. That is, for each pixel
:math:`(x, y)` of the destination image, the functions compute coordinates of the corresponding "donor" pixel in the source image and copy the pixel value, that is:
In the case when the user specifies the forward mapping:
:math:`\left<g_x, g_y\right>:\texttt{src} \rightarrow \texttt{dst}` , the OpenCV functions first compute the corresponding inverse mapping:
:math:`\left<f_x, f_y\right>:\texttt{dst} \rightarrow \texttt{src}` and then use the above formula.
The actual implementations of the geometrical transformations, from the most generic
:ref:`Remap`
and to the simplest and the fastest
:ref:`Resize`
, need to solve the 2 main problems with the above formula:
The actual implementations of the geometrical transformations, from the most generic
:ref:`Remap` and to the simplest and the fastest
:ref:`Resize` , need to solve the 2 main problems with the above formula:
#.
extrapolation of non-existing pixels. Similarly to the filtering functions, described in the previous section, for some
:math:`(x,y)`
one of
:math:`f_x(x,y)`
or
:math:`f_y(x,y)`
, or they both, may fall outside of the image, in which case some extrapolation method needs to be used. OpenCV provides the same selection of the extrapolation methods as in the filtering functions, but also an additional method
``BORDER_TRANSPARENT``
, which means that the corresponding pixels in the destination image will not be modified at all.
extrapolation of non-existing pixels. Similarly to the filtering functions, described in the previous section, for some
:math:`(x,y)` one of
:math:`f_x(x,y)` or
:math:`f_y(x,y)` , or they both, may fall outside of the image, in which case some extrapolation method needs to be used. OpenCV provides the same selection of the extrapolation methods as in the filtering functions, but also an additional method ``BORDER_TRANSPARENT`` , which means that the corresponding pixels in the destination image will not be modified at all.
#.
interpolation of pixel values. Usually
:math:`f_x(x,y)`
and
:math:`f_y(x,y)`
are floating-point numbers (i.e.
:math:`\left<f_x, f_y\right>`
can be an affine or perspective transformation, or radial lens distortion correction etc.), so a pixel values at fractional coordinates needs to be retrieved. In the simplest case the coordinates can be just rounded to the nearest integer coordinates and the corresponding pixel used, which is called nearest-neighbor interpolation. However, a better result can be achieved by using more sophisticated
, where a polynomial function is fit into some neighborhood of the computed pixel
:math:`(f_x(x,y), f_y(x,y))`
and then the value of the polynomial at
:math:`(f_x(x,y), f_y(x,y))`
is taken as the interpolated pixel value. In OpenCV you can choose between several interpolation methods, see
:ref:`Resize`
.
interpolation of pixel values. Usually
:math:`f_x(x,y)` and
:math:`f_y(x,y)` are floating-point numbers (i.e.
:math:`\left<f_x, f_y\right>` can be an affine or perspective transformation, or radial lens distortion correction etc.), so a pixel values at fractional coordinates needs to be retrieved. In the simplest case the coordinates can be just rounded to the nearest integer coordinates and the corresponding pixel used, which is called nearest-neighbor interpolation. However, a better result can be achieved by using more sophisticated `interpolation methods <http://en.wikipedia.org/wiki/Multivariate_interpolation>`_
, where a polynomial function is fit into some neighborhood of the computed pixel
:math:`(f_x(x,y), f_y(x,y))` and then the value of the polynomial at
:math:`(f_x(x,y), f_y(x,y))` is taken as the interpolated pixel value. In OpenCV you can choose between several interpolation methods, see
:ref:`Resize` .
..index:: convertMaps
cv::convertMaps
---------------
`id=0.830076060616 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/imgproc/convertMaps>`__
Converts image transformation maps from one representation to another
:param map1:The first input map of type ``CV_16SC2`` or ``CV_32FC1`` or ``CV_32FC2``
:param map2:The second input map of type ``CV_16UC1`` or ``CV_32FC1`` or none (empty matrix), respectively
:param dstmap1:The first output map; will have type ``dstmap1type`` and the same size as ``src``
:param dstmap2:The second output map
:param dstmap1type:The type of the first output map; should be ``CV_16SC2`` , ``CV_32FC1`` or ``CV_32FC2``
:param nninterpolation:Indicates whether the fixed-point maps will be used for nearest-neighbor or for more complex interpolation
:param map1:The first input map of type ``CV_16SC2`` or ``CV_32FC1`` or ``CV_32FC2``
:param map2:The second input map of type ``CV_16UC1`` or ``CV_32FC1`` or none (empty matrix), respectively
:param dstmap1:The first output map; will have type ``dstmap1type`` and the same size as ``src``
:param dstmap2:The second output map
:param dstmap1type:The type of the first output map; should be ``CV_16SC2`` , ``CV_32FC1`` or ``CV_32FC2``
:param nninterpolation:Indicates whether the fixed-point maps will be used for nearest-neighbor or for more complex interpolation
The function converts a pair of maps for
:func:`remap`
from one representation to another. The following options (
``(map1.type(), map2.type())``
:math:`\rightarrow`
``(dstmap1.type(), dstmap2.type())``
) are supported:
The function converts a pair of maps for
:func:`remap` from one representation to another. The following options ( ``(map1.type(), map2.type())``:math:`\rightarrow```(dstmap1.type(), dstmap2.type())`` ) are supported:
. This is the most frequently used conversion operation, in which the original floating-point maps (see
:func:`remap`
) are converted to more compact and much faster fixed-point representation. The first output array will contain the rounded coordinates and the second array (created only when
``nninterpolation=false``
) will contain indices in the interpolation tables.
:math:`\texttt{(CV\_32FC1, CV\_32FC1)} \rightarrow \texttt{(CV\_16SC2, CV\_16UC1)}` . This is the most frequently used conversion operation, in which the original floating-point maps (see
:func:`remap` ) are converted to more compact and much faster fixed-point representation. The first output array will contain the rounded coordinates and the second array (created only when ``nninterpolation=false`` ) will contain indices in the interpolation tables.
. The same as above, but the original maps are stored in one 2-channel matrix.
:math:`\texttt{(CV\_32FC2)} \rightarrow \texttt{(CV\_16SC2, CV\_16UC1)}` . The same as above, but the original maps are stored in one 2-channel matrix.
#.
the reverse conversion. Obviously, the reconstructed floating-point maps will not be exactly the same as the originals.
where the values of the pixels at non-integer coordinates are retrieved
using bilinear interpolation. Every channel of multiple-channel
images is processed independently. While the rectangle center
must be inside the image, parts of the rectangle may be
outside. In this case, the replication border mode (see
:func:`borderInterpolate`
) is used to extrapolate
outside. In this case, the replication border mode (see
:func:`borderInterpolate` ) is used to extrapolate
the pixel values outside of the image.
See also:
:func:`warpAffine`
,
:func:`warpPerspective`
See also:
:func:`warpAffine`,:func:`warpPerspective`
..index:: getRotationMatrix2D
cv::getRotationMatrix2D
-----------------------
`id=0.641646199188 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/imgproc/getRotationMatrix2D>`__
..cfunction:: Mat getRotationMatrix2D( Point2f center, double angle, double scale )
Calculates the affine matrix of 2d rotation.
:param center:Center of the rotation in the source image
:param angle:The rotation angle in degrees. Positive values mean counter-clockwise rotation (the coordinate origin is assumed to be the top-left corner)
:param scale:Isotropic scale factor
:param center:Center of the rotation in the source image
:param angle:The rotation angle in degrees. Positive values mean counter-clockwise rotation (the coordinate origin is assumed to be the top-left corner)
Applies a generic geometrical transformation to an image.
:param src:Source image
:param dst:Destination image. It will have the same size as ``map1`` and the same type as ``src``
:param map1:The first map of either ``(x,y)`` points or just ``x`` values having type ``CV_16SC2`` , ``CV_32FC1`` or ``CV_32FC2`` . See :func:`convertMaps` for converting floating point representation to fixed-point for speed.
:param map2:The second map of ``y`` values having type ``CV_16UC1`` , ``CV_32FC1`` or none (empty map if map1 is ``(x,y)`` points), respectively
:param interpolation:The interpolation method, see :func:`resize` . The method ``INTER_AREA`` is not supported by this function
:param src:Source image
:param dst:Destination image. It will have the same size as ``map1`` and the same type as ``src``
:param map1:The first map of either ``(x,y)`` points or just ``x`` values having type ``CV_16SC2`` , ``CV_32FC1`` or ``CV_32FC2`` . See :func:`convertMaps` for converting floating point representation to fixed-point for speed.
:param map2:The second map of ``y`` values having type ``CV_16UC1`` , ``CV_32FC1`` or none (empty map if map1 is ``(x,y)`` points), respectively
:param interpolation:The interpolation method, see :func:`resize` . The method ``INTER_AREA`` is not supported by this function
:param borderMode:The pixel extrapolation method, see :func:`borderInterpolate` . When the \ ``borderMode=BORDER_TRANSPARENT`` , it means that the pixels in the destination image that corresponds to the "outliers" in the source image are not modified by the function
:param borderValue:A value used in the case of a constant border. By default it is 0
The function
``remap``
transforms the source image using the specified map:
:param borderMode:The pixel extrapolation method, see :func:`borderInterpolate` . When the \ ``borderMode=BORDER_TRANSPARENT`` , it means that the pixels in the destination image that corresponds to the "outliers" in the source image are not modified by the function
:param borderValue:A value used in the case of a constant border. By default it is 0
The function ``remap`` transforms the source image using the specified map:
`id=0.927768028114 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/imgproc/resize>`__
Resizes an image
:param src:Source image
:param dst:Destination image. It will have size ``dsize`` (when it is non-zero) or the size computed from ``src.size()`` and ``fx`` and ``fy`` . The type of ``dst`` will be the same as of ``src`` .
:param dsize:The destination image size. If it is zero, then it is computed as:
* **INTER_LINEAR** bilinear interpolation (used by default)
* **INTER_AREA** resampling using pixel area relation. It may be the preferred method for image decimation, as it gives moire-free results. But when the image is zoomed, it is similar to the ``INTER_NEAREST`` method
* **INTER_CUBIC** bicubic interpolation over 4x4 pixel neighborhood
* **INTER_LANCZOS4** Lanczos interpolation over 8x8 pixel neighborhood
The function
``resize``
resizes an image
``src``
down to or up to the specified size.
Note that the initial
``dst``
type or size are not taken into account. Instead the size and type are derived from the
``src``
,
``dsize``
,
``fx``
and
``fy``
. If you want to resize
``src``
so that it fits the pre-created
``dst``
, you may call the function as:
::
// explicitly specify dsize=dst.size(); fx and fy will be computed from that.
* **INTER_LINEAR** bilinear interpolation (used by default)
* **INTER_AREA** resampling using pixel area relation. It may be the preferred method for image decimation, as it gives moire-free results. But when the image is zoomed, it is similar to the ``INTER_NEAREST`` method
::
* **INTER_CUBIC** bicubic interpolation over 4x4 pixel neighborhood
* **INTER_LANCZOS4** Lanczos interpolation over 8x8 pixel neighborhood
// specify fx and fy and let the function to compute the destination image size.
The function ``resize`` resizes an image ``src`` down to or up to the specified size.
Note that the initial ``dst`` type or size are not taken into account. Instead the size and type are derived from the ``src``,``dsize``,``fx`` and ``fy`` . If you want to resize ``src`` so that it fits the pre-created ``dst`` , you may call the function as: ::
// explicitly specify dsize=dst.size(); fx and fy will be computed from that.
`id=0.796627178227 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/imgproc/warpAffine>`__
..cfunction:: void warpAffine( const Mat\& src, Mat\& dst, const Mat\& M, Size dsize, int flags=INTER_LINEAR, int borderMode=BORDER_CONSTANT, const Scalar\& borderValue=Scalar())
Applies an affine transformation to an image.
:param src:Source image
:param dst:Destination image; will have size ``dsize`` and the same type as ``src``
:param M::math:`2\times 3` transformation matrix
:param dsize:Size of the destination image
:param flags:A combination of interpolation methods, see :func:`resize` , and the optional flag ``WARP_INVERSE_MAP`` that means that ``M`` is the inverse transformation ( :math:`\texttt{dst}\rightarrow\texttt{src}` )
:param src:Source image
:param dst:Destination image; will have size ``dsize`` and the same type as ``src``
:param M::math:`2\times 3` transformation matrix
:param dsize:Size of the destination image
:param flags:A combination of interpolation methods, see :func:`resize` , and the optional flag ``WARP_INVERSE_MAP`` that means that ``M`` is the inverse transformation ( :math:`\texttt{dst}\rightarrow\texttt{src}` )
:param borderMode:The pixel extrapolation method, see :func:`borderInterpolate` . When the \ ``borderMode=BORDER_TRANSPARENT`` , it means that the pixels in the destination image that corresponds to the "outliers" in the source image are not modified by the function
:param borderValue:A value used in case of a constant border. By default it is 0
The function
``warpAffine``
transforms the source image using the specified matrix:
:param borderMode:The pixel extrapolation method, see :func:`borderInterpolate` . When the \ ``borderMode=BORDER_TRANSPARENT`` , it means that the pixels in the destination image that corresponds to the "outliers" in the source image are not modified by the function
:param borderValue:A value used in case of a constant border. By default it is 0
The function ``warpAffine`` transforms the source image using the specified matrix:
..math::
\texttt{dst} (x,y) = \texttt{src} ( \texttt{M} _{11} x + \texttt{M} _{12} y + \texttt{M} _{13}, \texttt{M} _{21} x + \texttt{M} _{22} y + \texttt{M} _{23})
\texttt{dst} (x,y) = \texttt{src} ( \texttt{M} _{11} x + \texttt{M} _{12} y + \texttt{M} _{13}, \texttt{M} _{21} x + \texttt{M} _{22} y + \texttt{M} _{23})
when the flag
``WARP_INVERSE_MAP``
is set. Otherwise, the transformation is first inverted with
:func:`invertAffineTransform`
and then put in the formula above instead of
``M``
.
when the flag ``WARP_INVERSE_MAP`` is set. Otherwise, the transformation is first inverted with
:func:`invertAffineTransform` and then put in the formula above instead of ``M`` .
`id=0.733510667556 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/imgproc/warpPerspective>`__
..cfunction:: void warpPerspective( const Mat\& src, Mat\& dst, const Mat\& M, Size dsize, int flags=INTER_LINEAR, int borderMode=BORDER_CONSTANT, const Scalar\& borderValue=Scalar())
Applies a perspective transformation to an image.
:param src:Source image
:param dst:Destination image; will have size ``dsize`` and the same type as ``src``
:param M::math:`3\times 3` transformation matrix
:param dsize:Size of the destination image
:param flags:A combination of interpolation methods, see :func:`resize` , and the optional flag ``WARP_INVERSE_MAP`` that means that ``M`` is the inverse transformation ( :math:`\texttt{dst}\rightarrow\texttt{src}` )
:param src:Source image
:param dst:Destination image; will have size ``dsize`` and the same type as ``src``
:param M::math:`3\times 3` transformation matrix
:param dsize:Size of the destination image
:param flags:A combination of interpolation methods, see :func:`resize` , and the optional flag ``WARP_INVERSE_MAP`` that means that ``M`` is the inverse transformation ( :math:`\texttt{dst}\rightarrow\texttt{src}` )
:param borderMode:The pixel extrapolation method, see :func:`borderInterpolate` . When the \ ``borderMode=BORDER_TRANSPARENT`` , it means that the pixels in the destination image that corresponds to the "outliers" in the source image are not modified by the function
:param borderValue:A value used in case of a constant border. By default it is 0
The function
``warpPerspective``
transforms the source image using the specified matrix:
:param borderMode:The pixel extrapolation method, see :func:`borderInterpolate` . When the \ ``borderMode=BORDER_TRANSPARENT`` , it means that the pixels in the destination image that corresponds to the "outliers" in the source image are not modified by the function
:param borderValue:A value used in case of a constant border. By default it is 0
The function ``warpPerspective`` transforms the source image using the specified matrix:
..math::
\texttt{dst} (x,y) = \texttt{src} \left ( \frac{M_{11} x + M_{12} y + M_{13}}{M_{31} x + M_{32} y + M_{33}} ,
\frac{M_{21} x + M_{22} y + M_{23}}{M_{31} x + M_{32} y + M_{33}} \right )
\frac{M_{21} x + M_{22} y + M_{23}}{M_{31} x + M_{32} y + M_{33}} \right )
when the flag
``WARP_INVERSE_MAP``
is set. Otherwise, the transformation is first inverted with
:func:`invert`
and then put in the formula above instead of
``M``
.
when the flag ``WARP_INVERSE_MAP`` is set. Otherwise, the transformation is first inverted with
:func:`invert` and then put in the formula above instead of ``M`` .
:param arrays:Source arrays. They all should have the same depth, ``CV_8U`` or ``CV_32F`` , and the same size. Each of them can have an arbitrary number of channels
:param narrays:The number of source arrays
:param channels:The list of ``dims`` channels that are used to compute the histogram. The first array channels are numerated from 0 to ``arrays[0].channels()-1`` , the second array channels are counted from ``arrays[0].channels()`` to ``arrays[0].channels() + arrays[1].channels()-1`` etc.
:param mask:The optional mask. If the matrix is not empty, it must be 8-bit array of the same size as ``arrays[i]`` . The non-zero mask elements mark the array elements that are counted in the histogram
:param arrays:Source arrays. They all should have the same depth, ``CV_8U`` or ``CV_32F`` , and the same size. Each of them can have an arbitrary number of channels
:param narrays:The number of source arrays
:param channels:The list of ``dims`` channels that are used to compute the histogram. The first array channels are numerated from 0 to ``arrays[0].channels()-1`` , the second array channels are counted from ``arrays[0].channels()`` to ``arrays[0].channels() + arrays[1].channels()-1`` etc.
:param mask:The optional mask. If the matrix is not empty, it must be 8-bit array of the same size as ``arrays[i]`` . The non-zero mask elements mark the array elements that are counted in the histogram
:param hist:The output histogram, a dense or sparse ``dims`` -dimensional array
:param dims:The histogram dimensionality; must be positive and not greater than ``CV_MAX_DIMS`` (=32 in the current OpenCV version)
:param histSize:The array of histogram sizes in each dimension
:param ranges:The array of ``dims`` arrays of the histogram bin boundaries in each dimension. When the histogram is uniform ( ``uniform`` =true), then for each dimension ``i`` it's enough to specify the lower (inclusive) boundary :math:`L_0` of the 0-th histogram bin and the upper (exclusive) boundary :math:`U_{\texttt{histSize}[i]-1}` for the last histogram bin ``histSize[i]-1`` . That is, in the case of uniform histogram each of ``ranges[i]`` is an array of 2 elements. When the histogram is not uniform ( ``uniform=false`` ), then each of ``ranges[i]`` contains ``histSize[i]+1`` elements: :math:`L_0, U_0=L_1, U_1=L_2, ..., U_{\texttt{histSize[i]}-2}=L_{\texttt{histSize[i]}-1}, U_{\texttt{histSize[i]}-1}` . The array elements, which are not between :math:`L_0` and :math:`U_{\texttt{histSize[i]}-1}` , are not counted in the histogram
:param uniform:Indicates whether the histogram is uniform or not, see above
:param accumulate:Accumulation flag. If it is set, the histogram is not cleared in the beginning (when it is allocated). This feature allows user to compute a single histogram from several sets of arrays, or to update the histogram in time
The functions
``calcHist``
calculate the histogram of one or more
arrays. The elements of a tuple that is used to increment
a histogram bin are taken at the same location from the corresponding
input arrays. The sample below shows how to compute 2D Hue-Saturation histogram for a color imag
:param hist:The output histogram, a dense or sparse ``dims`` -dimensional array
:param dims:The histogram dimensionality; must be positive and not greater than ``CV_MAX_DIMS`` (=32 in the current OpenCV version)
:param histSize:The array of histogram sizes in each dimension
:param ranges:The array of ``dims`` arrays of the histogram bin boundaries in each dimension. When the histogram is uniform ( ``uniform`` =true), then for each dimension ``i`` it's enough to specify the lower (inclusive) boundary :math:`L_0` of the 0-th histogram bin and the upper (exclusive) boundary :math:`U_{\texttt{histSize}[i]-1}` for the last histogram bin ``histSize[i]-1`` . That is, in the case of uniform histogram each of ``ranges[i]`` is an array of 2 elements. When the histogram is not uniform ( ``uniform=false`` ), then each of ``ranges[i]`` contains ``histSize[i]+1`` elements: :math:`L_0, U_0=L_1, U_1=L_2, ..., U_{\texttt{histSize[i]}-2}=L_{\texttt{histSize[i]}-1}, U_{\texttt{histSize[i]}-1}` . The array elements, which are not between :math:`L_0` and :math:`U_{\texttt{histSize[i]}-1}` , are not counted in the histogram
:param uniform:Indicates whether the histogram is uniform or not, see above
::
:param accumulate:Accumulation flag. If it is set, the histogram is not cleared in the beginning (when it is allocated). This feature allows user to compute a single histogram from several sets of arrays, or to update the histogram in time
The functions ``calcHist`` calculate the histogram of one or more
arrays. The elements of a tuple that is used to increment
a histogram bin are taken at the same location from the corresponding
input arrays. The sample below shows how to compute 2D Hue-Saturation histogram for a color imag ::
#include <cv.h>
#include <highgui.h>
using namespace cv;
int main( int argc, char** argv )
{
Mat src, hsv;
if( argc != 2 || !(src=imread(argv[1], 1)).data )
return -1;
cvtColor(src, hsv, CV_BGR2HSV);
// let's quantize the hue to 30 levels
// and the saturation to 32 levels
int hbins = 30, sbins = 32;
@ -100,17 +64,17 @@ input arrays. The sample below shows how to compute 2D Hue-Saturation histogram
MatND hist;
// we compute the histogram from the 0-th and 1-st channels
int channels[] = {0, 1};
calcHist( &hsv, 1, channels, Mat(), // do not use mask
hist, 2, histSize, ranges,
true, // the histogram is uniform
false );
double maxVal=0;
minMaxLoc(hist, 0, &maxVal, 0, 0);
int scale = 10;
Mat histImg = Mat::zeros(sbins*scale, hbins*10, CV_8UC3);
for( int h = 0; h < hbins; h++ )
for( int s = 0; s < sbins; s++ )
{
@ -121,284 +85,150 @@ input arrays. The sample below shows how to compute 2D Hue-Saturation histogram
Scalar::all(intensity),
CV_FILLED );
}
namedWindow( "Source", 1 );
imshow( "Source", src );
namedWindow( "H-S Histogram", 1 );
imshow( "H-S Histogram", histImg );
waitKey();
}
..
..index:: calcBackProject
cv::calcBackProject
-------------------
`id=0.307675677402 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/imgproc/calcBackProject>`__
:param arrays:Source arrays. They all should have the same depth, ``CV_8U`` or ``CV_32F`` , and the same size. Each of them can have an arbitrary number of channels
:param narrays:The number of source arrays
:param channels:The list of channels that are used to compute the back projection. The number of channels must match the histogram dimensionality. The first array channels are numerated from 0 to ``arrays[0].channels()-1`` , the second array channels are counted from ``arrays[0].channels()`` to ``arrays[0].channels() + arrays[1].channels()-1`` etc.
:param hist:The input histogram, a dense or sparse
:param backProject:Destination back projection aray; will be a single-channel array of the same size and the same depth as ``arrays[0]``
:param ranges:The array of arrays of the histogram bin boundaries in each dimension. See :func:`calcHist`
:param scale:The optional scale factor for the output back projection
:param arrays:Source arrays. They all should have the same depth, ``CV_8U`` or ``CV_32F`` , and the same size. Each of them can have an arbitrary number of channels
:param narrays:The number of source arrays
:param channels:The list of channels that are used to compute the back projection. The number of channels must match the histogram dimensionality. The first array channels are numerated from 0 to ``arrays[0].channels()-1`` , the second array channels are counted from ``arrays[0].channels()`` to ``arrays[0].channels() + arrays[1].channels()-1`` etc.
:param hist:The input histogram, a dense or sparse
:param backProject:Destination back projection aray; will be a single-channel array of the same size and the same depth as ``arrays[0]``
:param ranges:The array of arrays of the histogram bin boundaries in each dimension. See :func:`calcHist`
:param scale:The optional scale factor for the output back projection
:param uniform:Indicates whether the histogram is uniform or not, see above
The functions
``calcBackProject``
calculate the back project of the histogram. That is, similarly to
``calcHist``
, at each location
``(x, y)``
the function collects the values from the selected channels in the input images and finds the corresponding histogram bin. But instead of incrementing it, the function reads the bin value, scales it by
``scale``
and stores in
``backProject(x,y)``
. In terms of statistics, the function computes probability of each element value in respect with the empirical probability distribution represented by the histogram. Here is how, for example, you can find and track a bright-colored object in a scene:
:param uniform:Indicates whether the histogram is uniform or not, see above
The functions ``calcBackProject`` calculate the back project of the histogram. That is, similarly to ``calcHist`` , at each location ``(x, y)`` the function collects the values from the selected channels in the input images and finds the corresponding histogram bin. But instead of incrementing it, the function reads the bin value, scales it by ``scale`` and stores in ``backProject(x,y)`` . In terms of statistics, the function computes probability of each element value in respect with the empirical probability distribution represented by the histogram. Here is how, for example, you can find and track a bright-colored object in a scene:
#.
Before the tracking, show the object to the camera such that covers almost the whole frame. Calculate a hue histogram. The histogram will likely have a strong maximums, corresponding to the dominant colors in the object.
#.
During the tracking, calculate back projection of a hue plane of each input video frame using that pre-computed histogram. Threshold the back projection to suppress weak colors. It may also have sense to suppress pixels with non sufficient color saturation and too dark or too bright pixels.
#.
Find connected components in the resulting picture and choose, for example, the largest component.
That is the approximate algorithm of
:func:`CAMShift`
color object tracker.
See also:
:func:`calcHist`
That is the approximate algorithm of
:func:`CAMShift` color object tracker.
See also:
:func:`calcHist`
..index:: compareHist
cv::compareHist
---------------
`id=0.679842058679 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/imgproc/compareHist>`__
While the function works well with 1-, 2-, 3-dimensional dense histograms, it may not be suitable for high-dimensional sparse histograms, where, because of aliasing and sampling problems the coordinates of non-zero histogram bins can slightly shift. To compare such histograms or more general sparse configurations of weighted points, consider using the
While the function works well with 1-, 2-, 3-dimensional dense histograms, it may not be suitable for high-dimensional sparse histograms, where, because of aliasing and sampling problems the coordinates of non-zero histogram bins can slightly shift. To compare such histograms or more general sparse configurations of weighted points, consider using the
:func:`calcEMD` function.
..index:: equalizeHist
cv::equalizeHist
----------------
`id=0.125539341699 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/imgproc/equalizeHist>`__
The function supports multi-channel images; each channel is processed independently.
The functions
``accumulate*``
can be used, for example, to collect statistic of background of a scene, viewed by a still camera, for the further foreground-background segmentation.
See also:
:func:`accumulateSquare`
,
:func:`accumulateProduct`
,
:func:`accumulateWeighted`
The functions ``accumulate*`` can be used, for example, to collect statistic of background of a scene, viewed by a still camera, for the further foreground-background segmentation.
:param src:The input image, 1- or 3-channel, 8-bit or 32-bit floating point
:param dst:The accumulator image with the same number of channels as input image, 32-bit or 64-bit floating-point
:param alpha:Weight of the input image
:param mask:Optional operation mask
:param src:The input image, 1- or 3-channel, 8-bit or 32-bit floating point
:param dst:The accumulator image with the same number of channels as input image, 32-bit or 64-bit floating-point
:param alpha:Weight of the input image
:param mask:Optional operation mask
The function calculates the weighted sum of the input image
``src``
and the accumulator
``dst``
so that
``dst``
becomes a running average of frame sequence:
The function calculates the weighted sum of the input image ``src`` and the accumulator ``dst`` so that ``dst`` becomes a running average of frame sequence:
Compares a template against overlapped image regions.
:param image:Image where the search is running; should be 8-bit or 32-bit floating-point
:param templ:Searched template; must be not greater than the source image and have the same data type
:param image:Image where the search is running; should be 8-bit or 32-bit floating-point
:param templ:Searched template; must be not greater than the source image and have the same data type
:param result:A map of comparison results; will be single-channel 32-bit floating-point.
If ``image`` is :math:`W \times H` and ``templ`` is :math:`w \times h` then ``result`` will be :math:`(W-w+1) \times (H-h+1)`
:param method:Specifies the comparison method (see below)
The function slides through
``image``
, compares the
overlapped patches of size
:math:`w \times h`
against
``templ``
using the specified method and stores the comparison results to
``result``
. Here are the formulas for the available comparison
If ``image`` is :math:`W \times H` and ``templ`` is :math:`w \times h` then ``result`` will be :math:`(W-w+1) \times (H-h+1)`
:param method:Specifies the comparison method (see below)
The function slides through ``image`` , compares the
overlapped patches of size
:math:`w \times h` against ``templ`` using the specified method and stores the comparison results to ``result`` . Here are the formulas for the available comparison
methods (
:math:`I`
denotes
``image``
,
:math:`T`
``template``
,
:math:`R`
``result``
). The summation is done over template and/or the
image patch:
:math:`I` denotes ``image``,:math:`T```template``,:math:`R```result`` ). The summation is done over template and/or the
After the function finishes the comparison, the best matches can be found as global minimums (when
``CV_TM_SQDIFF``
was used) or maximums (when
``CV_TM_CCORR``
or
``CV_TM_CCOEFF``
was used) using the
:func:`minMaxLoc`
function. In the case of a color image, template summation in the numerator and each sum in the denominator is done over all of the channels (and separate mean values are used for each channel). That is, the function can take a color template and a color image; the result will still be a single-channel image, which is easier to analyze.
After the function finishes the comparison, the best matches can be found as global minimums (when ``CV_TM_SQDIFF`` was used) or maximums (when ``CV_TM_CCORR`` or ``CV_TM_CCOEFF`` was used) using the
:func:`minMaxLoc` function. In the case of a color image, template summation in the numerator and each sum in the denominator is done over all of the channels (and separate mean values are used for each channel). That is, the function can take a color template and a color image; the result will still be a single-channel image, which is easier to analyze.
A common machine learning task is supervised learning. In supervised learning, the goal is to learn the functional relationship
:math:`F:y = F(x)` between the input
:math:`x` and the output
:math:`y` . Predicting the qualitative output is called classification, while predicting the quantitative output is called regression.
A common machine learning task is supervised learning. In supervised learning, the goal is to learn the functional relationship
:math:`F:y = F(x)`
between the input
:math:`x`
and the output
:math:`y`
. Predicting the qualitative output is called classification, while predicting the quantitative output is called regression.
Boosting is a powerful learning concept, which provide a solution to the supervised classification learning task. It combines the performance of many "weak" classifiers to produce a powerful 'committee'
:ref:`HTF01`
. A weak classifier is only required to be better than chance, and thus can be very simple and computationally inexpensive. Many of them smartly combined, however, results in a strong classifier, which often outperforms most 'monolithic' strong classifiers such as SVMs and Neural Networks.
Boosting is a powerful learning concept, which provide a solution to the supervised classification learning task. It combines the performance of many "weak" classifiers to produce a powerful 'committee'
:ref:`HTF01` . A weak classifier is only required to be better than chance, and thus can be very simple and computationally inexpensive. Many of them smartly combined, however, results in a strong classifier, which 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.
The boosted model is based on
:math:`N`
training examples
:math:`{(x_i,y_i)}1N`
with
:math:`x_i \in{R^K}`
and
:math:`y_i \in{-1, +1}`
.
:math:`x_i`
is a
:math:`K`
-component vector. Each component encodes a feature relevant for the learning task at hand. The desired two-class output is encoded as -1 and +1.
Different variants of boosting are known such as Discrete Adaboost, Real AdaBoost, LogitBoost, and Gentle AdaBoost
:ref:`FHT98`
. All of them are very similar in their overall structure. Therefore, we will look only at the standard two-class Discrete AdaBoost algorithm as shown in the box below. Each sample is initially assigned the same weight (step 2). Next 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, which have been misclassified (step 3c). All weights are then normalized, and the process of finding the next weak classifier continues for another
:math:`M`
-1 times. The final classifier
:math:`F(x)`
is the sign of the weighted sum over the individual weak classifiers (step 4).
The boosted model is based on
:math:`N` training examples
:math:`{(x_i,y_i)}1N` with
:math:`x_i \in{R^K}` and
:math:`y_i \in{-1, +1}` .
:math:`x_i` is a
:math:`K` -component vector. Each component encodes a feature relevant for the learning task at hand. The desired two-class output is encoded as -1 and +1.
Different variants of boosting are known such as Discrete Adaboost, Real AdaBoost, LogitBoost, and Gentle AdaBoost
:ref:`FHT98` . All of them are very similar in their overall structure. Therefore, we will look only at the standard two-class Discrete AdaBoost algorithm as shown in the box below. Each sample is initially assigned the same weight (step 2). Next 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, which have been misclassified (step 3c). All weights are then normalized, and the process of finding the next weak classifier continues for another
:math:`M` -1 times. The final classifier
:math:`F(x)` is the sign of the weighted sum over the individual weak classifiers (step 4).
:math:`w_i \Leftarrow w_i exp[c_m 1_{(y_i \neq f_m(x_i))}], i = 1,2,...,N,`
and renormalize so that
:math:`\Sigma i w_i = 1`
.
Set
:math:`w_i \Leftarrow w_i exp[c_m 1_{(y_i \neq f_m(x_i))}], i = 1,2,...,N,` and renormalize so that
:math:`\Sigma i w_i = 1` .
*
Output the classifier sign
:math:`[\Sigma m = 1M c_m f_m(x)]`
.
:math:`[\Sigma m = 1M c_m f_m(x)]` .
Two-class Discrete AdaBoost Algorithm: Training (steps 1 to 3) and Evaluation (step 4)
**NOTE:**
As well as the classical boosting methods, the current implementation supports 2-class classifiers only. For M
:math:`>`
2 classes there is the
:math:`>` 2 classes there is the
**AdaBoost.MH**
algorithm, described in
:ref:`FHT98`
, that reduces the problem to the 2-class problem, yet with a much larger training set.
In order to reduce computation time for boosted models without substantially losing accuracy, the influence trimming technique may be employed. As the training algorithm proceeds and the number of trees in the ensemble is increased, a larger number of the training samples are classified correctly and with increasing confidence, thereby those samples receive smaller weights on the subsequent iterations. Examples with very low relative weight have small impact on training of the weak classifier. 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
algorithm, described in
:ref:`FHT98` , that reduces the problem to the 2-class problem, yet with a much larger training set.
In order to reduce computation time for boosted models without substantially losing accuracy, the influence trimming technique may be employed. As the training algorithm proceeds and the number of trees in the ensemble is increased, a larger number of the training samples are classified correctly and with increasing confidence, thereby those samples receive smaller weights on the subsequent iterations. Examples with very low relative weight have small impact on training of the weak classifier. 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`
.
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` .
**[HTF01] Hastie, T., Tibshirani, R., Friedman, J. H. The Elements of Statistical Learning: Data Mining, Inference, and Prediction. Springer Series in Statistics. 2001.**
**[FHT98] Friedman, J. H., Hastie, T. and Tibshirani, R. Additive Logistic Regression: a Statistical View of Boosting. Technical Report, Dept. of Statistics, Stanford University, 1998.**
@ -137,42 +83,25 @@ training examples are recomputed at each training iteration. Examples deleted at
CvBoostParams
-------------
`id=0.227680975216 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/ml/CvBoostParams>`__
..ctype:: CvBoostParams
Boosting training parameters. ::
Boosting training parameters.
::
struct CvBoostParams : public CvDTreeParams
{
int boost_type;
int weak_count;
int split_criteria;
double weight_trim_rate;
CvBoostParams();
CvBoostParams( int boost_type, int weak_count, double weight_trim_rate,
int max_depth, bool use_surrogates, const float* priors );
};
..
The structure is derived from
:ref:`CvDTreeParams`
, but not all of the decision tree parameters are supported. In particular, cross-validation is not supported.
The structure is derived from
:ref:`CvDTreeParams` , but not all of the decision tree parameters are supported. In particular, cross-validation is not supported.
..index:: CvBoostTree
@ -180,66 +109,38 @@ The structure is derived from
CvBoostTree
-----------
`id=0.166418635075 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/ml/CvBoostTree>`__
The weak classifier, a component of the boosted tree classifier
:ref:`CvBoost`
, is a derivative of
:ref:`CvDTree`
. Normally, there is no need to use the weak classifiers directly, however they can be accessed as elements of the sequence
``CvBoost::weak``
, retrieved by
``CvBoost::get_weak_predictors``
.
Note, that in the case of LogitBoost and Gentle AdaBoost each weak predictor is a regression tree, rather than a classification tree. Even in the case of Discrete AdaBoost and Real AdaBoost the
``CvBoostTree::predict``
return value (
``CvDTreeNode::value``
) is not the output class label; a negative value "votes" for class
The weak classifier, a component of the boosted tree classifier
:ref:`CvBoost` , is a derivative of
:ref:`CvDTree` . Normally, there is no need to use the weak classifiers directly, however they can be accessed as elements of the sequence ``CvBoost::weak`` , retrieved by ``CvBoost::get_weak_predictors`` .
Note, that in the case of LogitBoost and Gentle AdaBoost each weak predictor is a regression tree, rather than a classification tree. Even in the case of Discrete AdaBoost and Real AdaBoost the ``CvBoostTree::predict`` return value ( ``CvDTreeNode::value`` ) is not the output class label; a negative value "votes" for class
#
0, a positive - for class
0, a positive - for class
#
1. And the votes are weighted. The weight of each individual tree may be increased or decreased using the method
``CvBoostTree::scale``
.
1. And the votes are weighted. The weight of each individual tree may be increased or decreased using the method ``CvBoostTree::scale`` .
..index:: CvBoost
@ -247,102 +148,75 @@ return value (
CvBoost
-------
`id=0.0263891264552 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/ml/CvBoost>`__
The train method follows the common template; the last parameter
``update``
specifies whether the classifier needs to be updated (i.e. the new weak tree classifiers added to the existing ensemble), or the classifier needs to be rebuilt from scratch. The responses must be categorical, i.e. boosted trees can not be built for regression, and there should be 2 classes.
The train method follows the common template; the last parameter ``update`` specifies whether the classifier needs to be updated (i.e. the new weak tree classifiers added to the existing ensemble), or the classifier needs to be rebuilt from scratch. The responses must be categorical, i.e. boosted trees can not be built for regression, and there should be 2 classes.
..index:: CvBoost::predict
@ -350,23 +224,11 @@ specifies whether the classifier needs to be updated (i.e. the new weak tree cla
CvBoost::predict
----------------
`id=0.275883150474 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/ml/CvBoost%3A%3Apredict>`__
The method removes the specified weak classifiers from the sequence. Note that this method should not be confused with the pruning of individual decision trees, which is currently not supported.
..index:: CvBoost::get_weak_predictors
.._CvBoost::get_weak_predictors:
CvBoost::get_weak_predictors
----------------------------
`id=0.670781607621 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/ml/CvBoost%3A%3Aget_weak_predictors>`__
The method returns the sequence of weak classifiers. Each element of the sequence is a pointer to a
``CvBoostTree``
class (or, probably, to some of its derivatives).
The method returns the sequence of weak classifiers. Each element of the sequence is a pointer to a ``CvBoostTree`` class (or, probably, to some of its derivatives).
The ML classes discussed in this section implement Classification And Regression Tree algorithms, which are described in
`[Breiman84] <#paper_Breiman84>`_
The ML classes discussed in this section implement Classification And Regression Tree algorithms, which are described in `[Breiman84] <#paper_Breiman84>`_
.
The class
:ref:`CvDTree`
represents a single decision tree that may be used alone, or as a base class in tree ensembles (see
:ref:`Boosting`
and
:ref:`Random Trees`
).
The class
:ref:`CvDTree` represents a single decision tree that may be used alone, or as a base class in tree ensembles (see
:ref:`Boosting` and
:ref:`Random Trees` ).
A decision tree is a binary tree (i.e. tree where each non-leaf node has exactly 2 child nodes). It can be used either for classification, when each tree leaf is marked with some class label (multiple leafs may have the same label), or for regression, when each tree leaf is also assigned a constant (so the approximation function is piecewise constant).
Predicting with Decision Trees
------------------------------
To reach a leaf node, and to obtain a response for the input feature
vector, the prediction procedure starts with the root node. From each
non-leaf node the procedure goes to the left (i.e. selects the left
@ -38,50 +31,31 @@ tested to see if it belongs to a certain subset of values (also stored
in the node) from a limited set of values the variable could take; if
yes, the procedure goes to the left, else - to the right (for example,
if the color is green or red, go to the left, else to the right). That
is, in each node, a pair of entities (variable
_
index, decision
_
rule
is, in each node, a pair of entities (variable_index, decision_rule
(threshold/subset)) is used. This pair is called a split (split on
the variable variable
_
index). Once a leaf node is reached, the value
the variable variable_index). Once a leaf node is reached, the value
assigned to this node is used as the output of prediction procedure.
Sometimes, certain features of the input vector are missed (for example, in the darkness it is difficult to determine the object color), and the prediction procedure may get stuck in the certain node (in the mentioned example if the node is split by color). To avoid such situations, decision trees use so-called surrogate splits. That is, in addition to the best "primary" split, every tree node may also be split on one or more other variables with nearly the same results.
Training Decision Trees
-----------------------
The tree is built recursively, starting from the root node. All of the training data (feature vectors and the responses) is used to split the root node. In each node the optimum decision rule (i.e. the best "primary" split) is found based on some criteria (in ML
``gini``
"purity" criteria is used for classification, and sum of squared errors is used for regression). Then, if necessary, the surrogate splits are found that resemble the results of the primary split on the training data; all of the data is divided using the primary and the surrogate splits (just like it is done in the prediction procedure) between the left and the right child node. Then the procedure recursively splits both left and right nodes. At each node the recursive procedure may stop (i.e. stop splitting the node further) in one of the following cases:
The tree is built recursively, starting from the root node. All of the training data (feature vectors and the responses) is used to split the root node. In each node the optimum decision rule (i.e. the best "primary" split) is found based on some criteria (in ML ``gini`` "purity" criteria is used for classification, and sum of squared errors is used for regression). Then, if necessary, the surrogate splits are found that resemble the results of the primary split on the training data; all of the data is divided using the primary and the surrogate splits (just like it is done in the prediction procedure) between the left and the right child node. Then the procedure recursively splits both left and right nodes. At each node the recursive procedure may stop (i.e. stop splitting the node further) in one of the following cases:
* depth of the tree branch being constructed has reached the specified maximum value.
* number of training samples in the node is less than the specified threshold, when it is not statistically representative to split the node further.
* all the samples in the node belong to the same class (or, in the case of regression, the variation is too small).
* the best split found does not give any noticeable improvement compared to a random choice.
When the tree is built, it may be pruned using a cross-validation procedure, if necessary. That is, some branches of the tree that may lead to the model overfitting are cut off. Normally this procedure is only applied to standalone decision trees, while tree ensembles usually build small enough trees and use their own protection schemes against overfitting.
When the tree is built, it may be pruned using a cross-validation procedure, if necessary. That is, some branches of the tree that may lead to the model overfitting are cut off. Normally this procedure is only applied to standalone decision trees, while tree ensembles usually build small enough trees and use their own protection schemes against overfitting.
Variable importance
-------------------
Besides the obvious use of decision trees - prediction, the tree can be also used for various data analysis. One of the key properties of the constructed decision tree algorithms is that it is possible to compute importance (relative decisive power) of each variable. For example, in a spam filter that uses a set of words occurred in the message as a feature vector, the variable importance rating can be used to determine the most "spam-indicating" words and thus help to keep the dictionary size reasonable.
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.
@ -94,22 +68,10 @@ Importance of each variable is computed over all the splits on this variable in
CvDTreeSplit
------------
`id=0.286654154683 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/ml/CvDTreeSplit>`__
..ctype:: CvDTreeSplit
Decision tree node split. ::
Decision tree node split.
::
struct CvDTreeSplit
{
int var_idx;
@ -127,58 +89,37 @@ Decision tree node split.
ord;
};
};
..
..index:: CvDTreeNode
.._CvDTreeNode:
CvDTreeNode
-----------
`id=0.948528874157 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/ml/CvDTreeNode>`__
..ctype:: CvDTreeNode
Decision tree node. ::
Decision tree node.
::
struct CvDTreeNode
{
int class_idx;
int Tn;
double value;
CvDTreeNode* parent;
CvDTreeNode* left;
CvDTreeNode* right;
CvDTreeSplit* split;
int sample_count;
int depth;
...
};
..
Other numerous fields of
``CvDTreeNode``
are used internally at the training stage.
Other numerous fields of ``CvDTreeNode`` are used internally at the training stage.
..index:: CvDTreeParams
@ -186,22 +127,10 @@ are used internally at the training stage.
CvDTreeParams
-------------
`id=0.924935526415 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/ml/CvDTreeParams>`__
..ctype:: CvDTreeParams
Decision tree training parameters. ::
Decision tree training parameters.
::
struct CvDTreeParams
{
int max_categories;
@ -213,48 +142,32 @@ Decision tree training parameters.
CvDTreeParams( int _max_depth, int _min_sample_count,
float _regression_accuracy, bool _use_surrogates,
int _max_categories, int _cv_folds,
bool _use_1se_rule, bool _truncate_pruned_tree,
const float* _priors );
};
..
The structure contains all the decision tree training parameters. There is a default constructor that initializes all the parameters with the default values tuned for standalone classification tree. Any of the parameters can be overridden then, or the structure may be fully initialized using the advanced variant of the constructor.
..index:: CvDTreeTrainData
.._CvDTreeTrainData:
CvDTreeTrainData
----------------
`id=0.0482986639469 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/ml/CvDTreeTrainData>`__
..ctype:: CvDTreeTrainData
Decision tree training data and shared data for tree ensembles. ::
Decision tree training data and shared data for tree ensembles.
::
struct CvDTreeTrainData
{
CvDTreeTrainData();
@ -265,7 +178,7 @@ Decision tree training data and shared data for tree ensembles.
const CvDTreeParams& _params=CvDTreeParams(),
bool _shared=false, bool _add_labels=false );
virtual ~CvDTreeTrainData();
virtual void set_data( const CvMat* _train_data, int _tflag,
virtual CvDTreeNode* new_node( CvDTreeNode* parent, int count,
int storage_idx, int offset );
virtual CvDTreeSplit* new_split_ord( int vi, float cmp_val,
int split_point, int inversed, float quality );
virtual CvDTreeSplit* new_split_cat( int vi, float quality );
virtual void free_node_data( CvDTreeNode* node );
virtual void free_train_data();
virtual void free_node( CvDTreeNode* node );
int sample_count, var_all, var_count, max_c_count;
int ord_var_count, cat_var_count;
bool have_labels, have_priors;
bool is_classifier;
int buf_count, buf_size;
bool shared;
CvMat* cat_count;
CvMat* cat_ofs;
CvMat* cat_map;
CvMat* counts;
CvMat* buf;
CvMat* direction;
CvMat* split_buf;
CvMat* var_idx;
CvMat* var_type; // i-th element =
// k<0 - ordered
// k>=0 - categorical, see k-th element of cat_* arrays
CvMat* priors;
CvDTreeParams params;
CvMemStorage* tree_storage;
CvMemStorage* temp_storage;
CvDTreeNode* data_root;
CvSet* node_heap;
CvSet* split_heap;
CvSet* cv_heap;
CvSet* nv_heap;
CvRNG rng;
};
..
This structure is mostly used internally for storing both standalone trees and tree ensembles efficiently. Basically, it contains 3 types of information:
#. The training parameters, an instance of :ref:`CvDTreeParams`.
#. The training data, preprocessed in order to find the best splits more efficiently. For tree ensembles this preprocessed data is reused by all the trees. Additionally, the training data characteristics that are shared by all trees in the ensemble are stored here: variable types, the number of classes, class label compression map etc.
#. Buffers, memory storages for tree nodes, splits and other elements of the trees constructed.
There are 2 ways of using this structure. In simple cases (e.g. a standalone tree, or the ready-to-use "black box" tree ensemble from ML, like
:ref:`Random Trees`
or
:ref:`Boosting`
) there is no need to care or even to know about the structure - just construct the needed statistical model, train it and use it. The
``CvDTreeTrainData``
structure will be constructed and used internally. However, for custom tree algorithms, or another sophisticated cases, the structure may be constructed and used explicitly. The scheme is the following:
There are 2 ways of using this structure. In simple cases (e.g. a standalone tree, or the ready-to-use "black box" tree ensemble from ML, like
:ref:`Random Trees` or
:ref:`Boosting` ) there is no need to care or even to know about the structure - just construct the needed statistical model, train it and use it. The ``CvDTreeTrainData`` structure will be constructed and used internally. However, for custom tree algorithms, or another sophisticated cases, the structure may be constructed and used explicitly. The scheme is the following:
*
The structure is initialized using the default constructor, followed by
``set_data``
(or it is built using the full form of constructor). The parameter
``_shared``
must be set to
``true``
.
The structure is initialized using the default constructor, followed by ``set_data`` (or it is built using the full form of constructor). The parameter ``_shared`` must be set to ``true`` .
*
One or more trees are trained using this data, see the special form of the method
``CvDTree::train``
.
One or more trees are trained using this data, see the special form of the method ``CvDTree::train`` .
*
Finally, the structure can be released only after all the trees using it are released.
..index:: CvDTree
@ -403,59 +289,47 @@ structure will be constructed and used internally. However, for custom tree algo
CvDTree
-------
`id=0.802824162542 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/ml/CvDTree>`__
..ctype:: CvDTree
Decision tree. ::
Decision tree.
::
class CvDTree : public CvStatModel
{
public:
CvDTree();
virtual ~CvDTree();
virtual bool train( const CvMat* _train_data, int _tflag,
The first method follows the generic ``CvStatModel::train`` conventions, it is the most complete form. Both data layouts ( ``_tflag=CV_ROW_SAMPLE`` and ``_tflag=CV_COL_SAMPLE`` ) are supported, as well as sample and variable subsets, missing measurements, arbitrary combinations of input and output variable types etc. The last parameter contains all of the necessary training parameters, see the
:ref:`CvDTreeParams` description.
There are 2
``train``
methods in
``CvDTree``
.
The first method follows the generic
``CvStatModel::train``
conventions, it is the most complete form. Both data layouts (
``_tflag=CV_ROW_SAMPLE``
and
``_tflag=CV_COL_SAMPLE``
) are supported, as well as sample and variable subsets, missing measurements, arbitrary combinations of input and output variable types etc. The last parameter contains all of the necessary training parameters, see the
:ref:`CvDTreeParams`
description.
The second method
``train``
is mostly used for building tree ensembles. It takes the pre-constructed
:ref:`CvDTreeTrainData`
instance and the optional subset of training set. The indices in
``_subsample_idx``
are counted relatively to the
``_sample_idx``
, passed to
``CvDTreeTrainData``
constructor. For example, if
``_sample_idx=[1, 5, 7, 100]``
, then
``_subsample_idx=[0,3]``
means that the samples
``[1, 100]``
of the original training set are used.
The second method ``train`` is mostly used for building tree ensembles. It takes the pre-constructed
:ref:`CvDTreeTrainData` instance and the optional subset of training set. The indices in ``_subsample_idx`` are counted relatively to the ``_sample_idx`` , passed to ``CvDTreeTrainData`` constructor. For example, if ``_sample_idx=[1, 5, 7, 100]`` , then ``_subsample_idx=[0,3]`` means that the samples ``[1, 100]`` of the original training set are used.
..index:: CvDTree::predict
@ -563,44 +396,23 @@ of the original training set are used.
CvDTree::predict
----------------
`id=0.366805937359 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/ml/CvDTree%3A%3Apredict>`__
Returns the leaf node of the decision tree corresponding to the input vector.
The method takes the feature vector and the optional missing measurement mask on input, traverses the decision tree and returns the reached leaf node on output. The prediction result, either the class label or the estimated function value, may be retrieved as the ``value`` field of the
:ref:`CvDTreeNode` structure, for example:dtree-
:math:`>` predict(sample,mask)-
:math:`>` value.
The method takes the feature vector and the optional missing measurement mask on input, traverses the decision tree and returns the reached leaf node on output. The prediction result, either the class label or the estimated function value, may be retrieved as the
``value``
field of the
:ref:`CvDTreeNode`
structure, for example: dtree-
:math:`>`
predict(sample,mask)-
:math:`>`
value.
The last parameter is normally set to
``false``
, implying a regular
input. If it is
``true``
, the method assumes that all the values of
the discrete input variables have been already normalized to
:math:`0`
to
:math:`num\_of\_categories_i-1`
ranges. (as the decision tree uses such
The last parameter is normally set to ``false`` , implying a regular
input. If it is ``true`` , the method assumes that all the values of
the discrete input variables have been already normalized to
:math:`0` to
:math:`num\_of\_categories_i-1` ranges. (as the decision tree uses such
normalized representation internally). It is useful for faster prediction
with tree ensembles. For ordered input variables the flag is not used.
Example: Building A Tree for Classifying Mushrooms. See the
``mushroom.cpp``
sample that demonstrates how to build and use the
Example: Building A Tree for Classifying Mushrooms. See the ``mushroom.cpp`` sample that demonstrates how to build and use the
The EM (Expectation-Maximization) algorithm estimates the parameters of the multivariate probability density function in the form of a Gaussian mixture distribution with a specified number of mixtures.
Consider the set of the feature vectors
:math:`x_1, x_2,...,x_{N}`
: N vectors from a d-dimensional Euclidean space drawn from a Gaussian mixture:
Consider the set of the feature vectors
:math:`x_1, x_2,...,x_{N}` :N vectors from a d-dimensional Euclidean space drawn from a Gaussian mixture:
Alternatively, the algorithm may start with the M-step when the initial values for
:math:`p_{i,k}`
can be provided. Another alternative when
:math:`p_{i,k}`
are unknown, is to use a simpler clustering algorithm to pre-cluster the input samples and thus obtain initial
:math:`p_{i,k}`
. Often (and in ML) the
:ref:`KMeans2`
algorithm is used for that purpose.
Alternatively, the algorithm may start with the M-step when the initial values for
:math:`p_{i,k}` can be provided. Another alternative when
:math:`p_{i,k}` are unknown, is to use a simpler clustering algorithm to pre-cluster the input samples and thus obtain initial
:math:`p_{i,k}` . Often (and in ML) the
:ref:`KMeans2` algorithm is used for that purpose.
One of the main that EM algorithm should deal with is the large number
of parameters to estimate. The majority of the parameters sits in
covariance matrices, which are
:math:`d \times d`
elements each
(where
:math:`d`
is the feature space dimensionality). However, in
covariance matrices, which are
:math:`d \times d` elements each
(where
:math:`d` is the feature space dimensionality). However, in
many practical problems the covariance matrices are close to diagonal,
or even to
:math:`\mu_k*I`
, where
:math:`I`
is identity matrix and
:math:`\mu_k`
is mixture-dependent "scale" parameter. So a robust computation
or even to
:math:`\mu_k*I` , where
:math:`I` is identity matrix and
:math:`\mu_k` is mixture-dependent "scale" parameter. So a robust computation
scheme could be to start with the harder constraints on the covariance
matrices and then use the estimated parameters as an input for a less
constrained optimization problem (often a diagonal covariance matrix is
@ -128,13 +79,8 @@ already a good enough approximation).
**References:**
*
Bilmes98 J. A. Bilmes. A Gentle Tutorial of the EM Algorithm and its Application to Parameter Estimation for Gaussian Mixture and Hidden Markov Models. Technical Report TR-97-021, International Computer Science Institute and Computer Science Division, University of California at Berkeley, April 1998.
..index:: CvEMParams
@ -142,45 +88,33 @@ already a good enough approximation).
CvEMParams
----------
`id=0.432576013672 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/ml/CvEMParams>`__
@ -190,64 +124,48 @@ Parameters of the EM algorithm.
const CvMat** covs;
CvTermCriteria term_crit;
};
..
The structure has 2 constructors, the default one represents a rough rule-of-thumb, with another one it is possible to override a variety of parameters, from a single number of mixtures (the only essential problem-dependent parameter), to the initial values for the mixture parameters.
..index:: CvEM
.._CvEM:
CvEM
----
`id=0.808344863567 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/ml/CvEM>`__
Estimates the Gaussian mixture parameters from the sample set.
Unlike many of the ML models, EM is an unsupervised learning algorithm and it does not take responses (class labels or the function values) on input. Instead, it computes the
:ref:`MLE` of the Gaussian mixture parameters from the input sample set, stores all the parameters inside the structure:
:math:`p_{i,k}` in ``probs``,:math:`a_k` in ``means``:math:`S_k` in ``covs[k]``,:math:`\pi_k` in ``weights`` and optionally computes the output "class label" for each sample:
:math:`\texttt{labels}_i=\texttt{arg max}_k(p_{i,k}), i=1..N` (i.e. indices of the most-probable mixture for each sample).
The trained model can be used further for prediction, just like any other classifier. The model trained is similar to the
:ref:`Bayes classifier` .
Unlike many of the ML models, EM is an unsupervised learning algorithm and it does not take responses (class labels or the function values) on input. Instead, it computes the
:ref:`MLE`
of the Gaussian mixture parameters from the input sample set, stores all the parameters inside the structure:
:math:`p_{i,k}`
in
``probs``
,
:math:`a_k`
in
``means``
:math:`S_k`
in
``covs[k]``
,
:math:`\pi_k`
in
``weights``
and optionally computes the output "class label" for each sample:
The algorithm caches all of the training samples, and predicts the response for a new sample by analyzing a certain number (
**K**
) of the nearest neighbors of the sample (using voting, calculating weighted sum etc.) The method is sometimes referred to as "learning by example", because for prediction it looks for the feature vector with a known response that is closest to the given vector.
..index:: CvKNearest
.._CvKNearest:
CvKNearest
----------
`id=0.969498355265 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/ml/CvKNearest>`__
The method trains the K-Nearest model. It follows the conventions of generic ``train`` "method" with the following limitations: only CV_ROW_SAMPLE data layout is supported, the input variables are all ordered, the output variables can be either categorical ( ``is_regression=false`` ) or ordered ( ``is_regression=true`` ), variable subsets ( ``var_idx`` ) and missing measurements are not supported.
The parameter ``_max_k`` specifies the number of maximum neighbors that may be passed to the method ``find_nearest`` .
The method trains the K-Nearest model. It follows the conventions of generic
``train``
"method" with the following limitations: only CV
_
ROW
_
SAMPLE data layout is supported, the input variables are all ordered, the output variables can be either categorical (
``is_regression=false``
) or ordered (
``is_regression=true``
), variable subsets (
``var_idx``
) and missing measurements are not supported.
The parameter
``_max_k``
specifies the number of maximum neighbors that may be passed to the method
``find_nearest``
.
The parameter
``_update_base``
specifies whether the model is trained from scratch
(
``_update_base=false``
), or it is updated using the new training data (
``_update_base=true``
). In the latter case the parameter
``_max_k``
must not be larger than the original value.
The parameter ``_update_base`` specifies whether the model is trained from scratch
( ``_update_base=false`` ), or it is updated using the new training data ( ``_update_base=true`` ). In the latter case the parameter ``_max_k`` must not be larger than the original value.
..index:: CvKNearest::find_nearest
@ -120,58 +68,26 @@ must not be larger than the original value.
CvKNearest::find_nearest
------------------------
`id=0.654974872601 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/ml/CvKNearest%3A%3Afind_nearest>`__
For each input vector (which are the rows of the matrix
``_samples``
) the method finds the
For each input vector (which are the rows of the matrix ``_samples`` ) the method finds the
:math:`\texttt{k} \le
\texttt{get\_max\_k()}`
nearest neighbor. In the case of regression,
\texttt{get\_max\_k()}` nearest neighbor. In the case of regression,
the predicted result will be a mean value of the particular vector's
neighbor responses. In the case of classification the class is determined
by voting.
For custom classification/regression prediction, the method can optionally return pointers to the neighbor vectors themselves (
``neighbors``
, an array of
``k*_samples->rows``
pointers), their corresponding output values (
``neighbor_responses``
, a vector of
``k*_samples->rows``
elements) and the distances from the input vectors to the neighbors (
``dist``
, also a vector of
``k*_samples->rows``
elements).
For custom classification/regression prediction, the method can optionally return pointers to the neighbor vectors themselves ( ``neighbors`` , an array of ``k*_samples->rows`` pointers), their corresponding output values ( ``neighbor_responses`` , a vector of ``k*_samples->rows`` elements) and the distances from the input vectors to the neighbors ( ``dist`` , also a vector of ``k*_samples->rows`` elements).
For each input vector the neighbors are sorted by their distances to the vector.
If only a single input vector is passed, all output matrices are optional and the predicted value is returned by the method.
If only a single input vector is passed, all output matrices are optional and the predicted value is returned by the method. ::
::
#include "ml.h"
#include "highgui.h"
int main( int argc, char** argv )
{
const int K = 10;
@ -185,36 +101,36 @@ If only a single input vector is passed, all output matrices are optional and th
The Machine Learning Library (MLL) is a set of classes and functions for statistical classification, regression and clustering of data.
Most of the classification and regression algorithms are implemented as C++ classes. As the algorithms have different seta of features (like the ability to handle missing measurements, or categorical input variables etc.), there is a little common ground between the classes. This common ground is defined by the class `CvStatModel` that all the other ML classes are derived from.
ML implements feed-forward artificial neural networks, more particularly, multi-layer perceptrons (MLP), the most commonly used type of neural networks. MLP consists of the input layer, output layer and one or more hidden layers. Each layer of MLP includes one or more neurons that are directionally linked with the neurons from the previous and the next layer. Here is an example of a 3-layer perceptron with 3 inputs, 2 outputs and the hidden layer including 5 neurons:
..image:: ../../pics/mlp_.png
All the neurons in MLP are similar. Each of them has several input links (i.e. it takes the output values from several neurons in the previous layer on input) and several output links (i.e. it passes the response to several neurons in the next layer). The values retrieved from the previous layer are summed with certain weights, individual for each neuron, plus the bias term, and the sum is transformed using the activation function
:math:`f`
that may be also different for different neurons. Here is the picture:
All the neurons in MLP are similar. Each of them has several input links (i.e. it takes the output values from several neurons in the previous layer on input) and several output links (i.e. it passes the response to several neurons in the next layer). The values retrieved from the previous layer are summed with certain weights, individual for each neuron, plus the bias term, and the sum is transformed using the activation function
:math:`f` that may be also different for different neurons. Here is the picture:
:math:`f(x)=\beta*(1-e^{-\alpha x})/(1+e^{-\alpha x}` ), the default choice for MLP; the standard sigmoid with
:math:`\beta =1, \alpha =1` is shown below:
..image:: ../../pics/sigmoid_bipolar.png
*
Gaussian function (
``CvANN_MLP::GAUSSIAN``
):
:math:`f(x)=\beta e^{-\alpha x*x}`
, not completely supported by the moment.
Gaussian function ( ``CvANN_MLP::GAUSSIAN`` ):
:math:`f(x)=\beta e^{-\alpha x*x}` , not completely supported by the moment.
In ML all the neurons have the same activation functions, with the same free parameters (
:math:`\alpha, \beta`
) that are specified by user and are not altered by the training algorithms.
:math:`\alpha, \beta` ) that are specified by user and are not altered by the training algorithms.
So the whole trained network works as follows: It takes the feature vector on input, the vector size is equal to the size of the input layer, when the values are passed as input to the first hidden layer, the outputs of the hidden layer are computed using the weights and the activation functions and passed further downstream, until we compute the output layer.
So, in order to compute the network one needs to know all the
weights
:math:`w^{n+1)}_{i,j}`
. The weights are computed by the training
weights
:math:`w^{n+1)}_{i,j}` . The weights are computed by the training
algorithm. The algorithm takes a training set: multiple input vectors
with the corresponding output vectors, and iteratively adjusts the
weights to try to make the network give the desired response on the
@ -105,29 +62,16 @@ learned network will also "learn" the noise present in the training set,
so the error on the test set usually starts increasing after the network
size reaches some limit. Besides, the larger networks are train much
longer than the smaller ones, so it is reasonable to preprocess the data
(using
:ref:`CalcPCA`
or similar technique) and train a smaller network
(using
:ref:`CalcPCA` or similar technique) and train a smaller network
on only the essential features.
Another feature of the MLP's is their inability to handle categorical
data as is, however there is a workaround. If a certain feature in the
input or output (i.e. in the case of
``n``
-class classifier for
:math:`n>2`
) layer is categorical and can take
:math:`M>2`
different values, it makes sense to represent it as binary tuple of
``M``
elements, where
``i``
-th element is 1 if and only if the
feature is equal to the
``i``
-th value out of
``M``
possible. It
input or output (i.e. in the case of ``n`` -class classifier for
:math:`n>2` ) layer is categorical and can take
:math:`M>2` different values, it makes sense to represent it as binary tuple of ``M`` elements, where ``i`` -th element is 1 if and only if the
feature is equal to the ``i`` -th value out of ``M`` possible. It
will increase the size of the input/output layer, but will speedup the
training algorithm convergence and at the same time enable "fuzzy" values
of such variables, i.e. a tuple of probabilities instead of a fixed value.
@ -138,22 +82,15 @@ and the second (default one) is batch RPROP algorithm.
References:
*
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.
*
M. Riedmiller and H. Braun, "A Direct Adaptive Method for Faster Backpropagation Learning: The RPROP Algorithm", Proc. ICNN, San Francisco (1993).
..index:: CvANN_MLP_TrainParams
@ -161,49 +98,31 @@ References:
CvANN_MLP_TrainParams
---------------------
`id=0.637270235159 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/ml/CvANN_MLP_TrainParams>`__
..ctype:: CvANN_MLP_TrainParams
Parameters of the MLP training algorithm. ::
Parameters of the MLP training algorithm.
::
struct CvANN_MLP_TrainParams
{
CvANN_MLP_TrainParams();
CvANN_MLP_TrainParams( CvTermCriteria term_crit, int train_method,
The structure has default constructor that initializes parameters for
``RPROP``
algorithm. There is also more advanced constructor to customize the parameters and/or choose backpropagation algorithm. Finally, the individual parameters can be adjusted after the structure is created.
The structure has default constructor that initializes parameters for ``RPROP`` algorithm. There is also more advanced constructor to customize the parameters and/or choose backpropagation algorithm. Finally, the individual parameters can be adjusted after the structure is created.
..index:: CvANN_MLP
@ -211,22 +130,10 @@ algorithm. There is also more advanced constructor to customize the parameters a
CvANN_MLP
---------
`id=0.404391979594 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/ml/CvANN_MLP>`__
..ctype:: CvANN_MLP
MLP model. ::
MLP model.
::
class CvANN_MLP : public CvStatModel
{
public:
@ -234,52 +141,52 @@ MLP model.
CvANN_MLP( const CvMat* _layer_sizes,
int _activ_func=SIGMOID_SYM,
double _f_param1=0, double _f_param2=0 );
virtual ~CvANN_MLP();
virtual void create( const CvMat* _layer_sizes,
int _activ_func=SIGMOID_SYM,
double _f_param1=0, double _f_param2=0 );
virtual int train( const CvMat* _inputs, const CvMat* _outputs,
Unlike many other models in ML that are constructed and trained at once, in the MLP model these steps are separated. First, a network with the specified topology is created using the non-default constructor or the method
``create``
. All the weights are set to zeros. Then the network is trained using the set of input and output vectors. The training procedure can be repeated more than once, i.e. the weights can be adjusted based on the new training data.
Unlike many other models in ML that are constructed and trained at once, in the MLP model these steps are separated. First, a network with the specified topology is created using the non-default constructor or the method ``create`` . All the weights are set to zeros. Then the network is trained using the set of input and output vectors. The training procedure can be repeated more than once, i.e. the weights can be adjusted based on the new training data.
..index:: CvANN_MLP::create
@ -319,81 +220,45 @@ Unlike many other models in ML that are constructed and trained at once, in the
CvANN_MLP::create
-----------------
`id=0.505267168137 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/ml/CvANN_MLP%3A%3Acreate>`__
:param _layer_sizes:The integer vector specifies the number of neurons in each layer including the input and output layers.
:param _activ_func:Specifies the activation function for each neuron; one of ``CvANN_MLP::IDENTITY`` , ``CvANN_MLP::SIGMOID_SYM`` and ``CvANN_MLP::GAUSSIAN`` .
:param _f_param1,_f_param2:Free parameters of the activation function, :math:`\alpha` and :math:`\beta` , respectively. See the formulas in the introduction section.
:param _layer_sizes:The integer vector specifies the number of neurons in each layer including the input and output layers.
:param _activ_func:Specifies the activation function for each neuron; one of ``CvANN_MLP::IDENTITY`` , ``CvANN_MLP::SIGMOID_SYM`` and ``CvANN_MLP::GAUSSIAN`` .
:param _f_param1,_f_param2:Free parameters of the activation function, :math:`\alpha` and :math:`\beta` , respectively. See the formulas in the introduction section.
The method creates a MLP network with the specified topology and assigns the same activation function to all the neurons.
`id=0.561890021588 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/ml/CvANN_MLP%3A%3Atrain>`__
Trains/updates MLP.
:param _inputs:A floating-point matrix of input vectors, one vector per row.
:param _outputs:A floating-point matrix of the corresponding output vectors, one vector per row.
:param _sample_weights:(RPROP only) The optional floating-point vector of weights for each sample. Some samples may be more important than others for training, and the user may want to raise the weight of certain classes to find the right balance between hit-rate and false-alarm rate etc.
:param _sample_idx:The optional integer vector indicating the samples (i.e. rows of ``_inputs`` and ``_outputs`` ) that are taken into account.
Trains/updates MLP.
:param _params:The training params. See ``CvANN_MLP_TrainParams`` description.
:param _flags:The various parameters to control the training algorithm. May be a combination of the following:
* **UPDATE_WEIGHTS = 1** algorithm updates the network weights, rather than computes them from scratch (in the latter case the weights are initialized using *Nguyen-Widrow* algorithm).
* **NO_INPUT_SCALE** algorithm does not normalize the input vectors. If this flag is not set, the training algorithm normalizes each input feature independently, shifting its mean value to 0 and making the standard deviation =1. If the network is assumed to be updated frequently, the new training data could be much different from original one. In this case user should take care of proper normalization.
* **NO_OUTPUT_SCALE** algorithm does not normalize the output vectors. If the flag is not set, the training algorithm normalizes each output features independently, by transforming it to the certain range depending on the activation function used.
:param _inputs:A floating-point matrix of input vectors, one vector per row.
:param _outputs:A floating-point matrix of the corresponding output vectors, one vector per row.
:param _sample_weights:(RPROP only) The optional floating-point vector of weights for each sample. Some samples may be more important than others for training, and the user may want to raise the weight of certain classes to find the right balance between hit-rate and false-alarm rate etc.
:param _sample_idx:The optional integer vector indicating the samples (i.e. rows of ``_inputs`` and ``_outputs`` ) that are taken into account.
:param _params:The training params. See ``CvANN_MLP_TrainParams`` description.
:param _flags:The various parameters to control the training algorithm. May be a combination of the following:
* **UPDATE_WEIGHTS = 1** algorithm updates the network weights, rather than computes them from scratch (in the latter case the weights are initialized using *Nguyen-Widrow* algorithm).
* **NO_INPUT_SCALE** algorithm does not normalize the input vectors. If this flag is not set, the training algorithm normalizes each input feature independently, shifting its mean value to 0 and making the standard deviation =1. If the network is assumed to be updated frequently, the new training data could be much different from original one. In this case user should take care of proper normalization.
* **NO_OUTPUT_SCALE** algorithm does not normalize the output vectors. If the flag is not set, the training algorithm normalizes each output features independently, by transforming it to the certain range depending on the activation function used.
This method applies the specified training algorithm to compute/adjust the network weights. It returns the number of done iterations.
This is a simple classification model assuming that feature vectors from each class are normally distributed (though, not necessarily independently distributed), so the whole data distribution function is assumed to be a Gaussian mixture, one component per class. Using the training data the algorithm estimates mean vectors and covariance matrices for every class, and then it uses them for prediction.
**[Fukunaga90] K. Fukunaga. Introduction to Statistical Pattern Recognition. second ed., New York: Academic Press, 1990.**
@ -14,88 +13,48 @@ This is a simple classification model assuming that feature vectors from each cl
CvNormalBayesClassifier
-----------------------
`id=0.110421013491 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/ml/CvNormalBayesClassifier>`__
..ctype:: CvNormalBayesClassifier
Bayes classifier for normally distributed data. ::
Bayes classifier for normally distributed data.
::
class CvNormalBayesClassifier : public CvStatModel
The method trains the Normal Bayes classifier. It follows the conventions of the generic ``train`` "method" with the following limitations: only CV_ROW_SAMPLE data layout is supported; the input variables are all ordered; the output variable is categorical (i.e. elements of ``_responses`` must be integer numbers, though the vector may have ``CV_32FC1`` type), and missing measurements are not supported.
The method trains the Normal Bayes classifier. It follows the conventions of the generic
``train``
"method" with the following limitations: only CV
_
ROW
_
SAMPLE data layout is supported; the input variables are all ordered; the output variable is categorical (i.e. elements of
``_responses``
must be integer numbers, though the vector may have
``CV_32FC1``
type), and missing measurements are not supported.
In addition, there is an
``update``
flag that identifies whether the model should be trained from scratch (
``update=false``
) or should be updated using the new training data (
``update=true``
).
In addition, there is an ``update`` flag that identifies whether the model should be trained from scratch ( ``update=false`` ) or should be updated using the new training data ( ``update=true`` ).
..index:: CvNormalBayesClassifier::predict
@ -103,23 +62,9 @@ flag that identifies whether the model should be trained from scratch (
CvNormalBayesClassifier::predict
--------------------------------
`id=0.821415185096 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/ml/CvNormalBayesClassifier%3A%3Apredict>`__
estimates the most probable classes for the input vectors. The input vectors (one or more) are stored as rows of the matrix
``samples``
. In the case of multiple input vectors, there should be one output vector
``results``
. The predicted class for a single input vector is returned by the method.
The method ``predict`` estimates the most probable classes for the input vectors. The input vectors (one or more) are stored as rows of the matrix ``samples`` . In the case of multiple input vectors, there should be one output vector ``results`` . The predicted class for a single input vector is returned by the method.
. The algorithm can deal with both classification and regression problems. Random trees is a collection (ensemble) of tree predictors that is called
. The algorithm can deal with both classification and regression problems. Random trees is a collection (ensemble) of tree predictors that is called
**forest**
further in this section (the term has been also introduced by L. Breiman). The classification works as follows: the random trees classifier takes the input feature vector, classifies it with every tree in the forest, and outputs the class label that recieved the majority of "votes". In the case of regression the classifier response is the average of the responses over all the trees in the forest.
All the trees are trained with the same parameters, but on the different training sets, which are generated from the original training set using the bootstrap procedure: for each training set we randomly select the same number of vectors as in the original set (
``=N``
). The vectors are chosen with replacement. That is, some vectors will occur more than once and some will be absent. At each node of each tree trained not all the variables are used to find the best split, rather than a random subset of them. With each node a new subset is generated, however its size is fixed for all the nodes and all the trees. It is a training parameter, set to
:math:`\sqrt{number\_of\_variables}`
by default. None of the trees that are built are pruned.
All the trees are trained with the same parameters, but on the different training sets, which are generated from the original training set using the bootstrap procedure: for each training set we randomly select the same number of vectors as in the original set ( ``=N`` ). The vectors are chosen with replacement. That is, some vectors will occur more than once and some will be absent. At each node of each tree trained not all the variables are used to find the best split, rather than a random subset of them. With each node a new subset is generated, however its size is fixed for all the nodes and all the trees. It is a training parameter, set to
:math:`\sqrt{number\_of\_variables}` by default. None of the trees that are built are pruned.
In random trees there is no need for any accuracy estimation procedures, such as cross-validation or bootstrap, or a separate test set to get an estimate of the training error. The error is estimated internally during the training. When the training set for the current tree is drawn by sampling with replacement, some vectors are left out (so-called
In random trees there is no need for any accuracy estimation procedures, such as cross-validation or bootstrap, or a separate test set to get an estimate of the training error. The error is estimated internally during the training. When the training set for the current tree is drawn by sampling with replacement, some vectors are left out (so-called
*oob (out-of-bag) data*
). The size of oob data is about
``N/3``
. The classification error is estimated by using this oob-data as following:
). The size of oob data is about ``N/3`` . The classification error is estimated by using this oob-data as following:
*
Get a prediction for each vector, which is oob relatively to the i-th tree, using the very i-th tree.
*
After all the trees have been trained, for each vector that has ever been oob, find the class-"winner" for it (i.e. the class that has got the majority of votes in the trees, where the vector was oob) and compare it to the ground-truth response.
*
Then the classification error estimate is computed as ratio of number of misclassified oob vectors to all the vectors in the original data. In the case of regression the oob-error is computed as the squared error for oob vectors difference divided by the total number of vectors.
CvRTParams( int _max_depth, int _min_sample_count,
float _regression_accuracy, bool _use_surrogates,
int _max_categories, const float* _priors,
@ -108,36 +76,20 @@ Training Parameters of Random Trees.
int _nactive_vars, int max_tree_count,
float forest_accuracy, int termcrit_type );
};
..
The set of training parameters for the forest is the superset of the training parameters for a single tree. However, Random trees do not need all the functionality/features of decision trees, most noticeably, the trees are not pruned, so the cross-validation parameters are not used.
..index:: CvRTrees
.._CvRTrees:
CvRTrees
--------
`id=0.485875932457 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/ml/CvRTrees>`__
conventions. All of the specific to the algorithm training parameters are passed as a
:ref:`CvRTParams`
instance. The estimate of the training error (
``oob-error``
) is stored in the protected class member
``oob_error``
.
The method ``CvRTrees::train`` is very similar to the first form of ``CvDTree::train`` () and follows the generic method ``CvStatModel::train`` conventions. All of the specific to the algorithm training parameters are passed as a
:ref:`CvRTParams` instance. The estimate of the training error ( ``oob-error`` ) is stored in the protected class member ``oob_error`` .
..index:: CvRTrees::predict
@ -221,23 +149,11 @@ instance. The estimate of the training error (
CvRTrees::predict
-----------------
`id=0.175799484956 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/ml/CvRTrees%3A%3Apredict>`__
The input parameters of the prediction method are the same as in
``CvDTree::predict``
, but the return value type is different. This method returns the cumulative result from all the trees in the forest (the class that receives the majority of voices, or the mean of the regression function estimates).
The input parameters of the prediction method are the same as in ``CvDTree::predict`` , but the return value type is different. This method returns the cumulative result from all the trees in the forest (the class that receives the majority of voices, or the mean of the regression function estimates).
..index:: CvRTrees::get_var_importance
@ -245,25 +161,11 @@ The input parameters of the prediction method are the same as in
CvRTrees::get_var_importance
----------------------------
`id=0.336660771362 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/ml/CvRTrees%3A%3Aget_var_importance>`__
The method returns the variable importance vector, computed at the training stage when
``:ref:`CvRTParams`::calc_var_importance``
is set. If the training flag is not set, then the
``NULL``
pointer is returned. This is unlike decision trees, where variable importance can be computed anytime after the training.
The method returns the variable importance vector, computed at the training stage when ``:ref:`CvRTParams`::calc_var_importance`` is set. If the training flag is not set, then the ``NULL`` pointer is returned. This is unlike decision trees, where variable importance can be computed anytime after the training.
..index:: CvRTrees::get_proximity
@ -271,39 +173,23 @@ pointer is returned. This is unlike decision trees, where variable importance ca
CvRTrees::get_proximity
-----------------------
`id=0.2120965436 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/ml/CvRTrees%3A%3Aget_proximity>`__
Retrieves the proximity measure between two training samples.
The method returns proximity measure between any two samples (the ratio of the those trees in the ensemble, in which the samples fall into the same leaf node, to the total number of the trees).
Example: Prediction of mushroom goodness using random trees classifier ::
Example: Prediction of mushroom goodness using random trees classifier
In this declaration some methods are commented off. Actually, these are methods for which there is no unified API (with the exception of the default constructor), however, there are many similarities in the syntax and semantics that are briefly described below in this section, as if they are a part of the base class.
..index:: CvStatModel::CvStatModel
.._CvStatModel::CvStatModel:
CvStatModel::CvStatModel
------------------------
`id=0.362486770202 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/ml/CvStatModel%3A%3ACvStatModel>`__
..cfunction:: CvStatModel::CvStatModel()
Default constructor.
Each statistical model class in ML has a default constructor without parameters. This constructor is useful for 2-stage model construction, when the default constructor is followed by
``train()``
or
``load()``
.
Each statistical model class in ML has a default constructor without parameters. This constructor is useful for 2-stage model construction, when the default constructor is followed by ``train()`` or ``load()`` .
..index:: CvStatModel::CvStatModel(...)
@ -92,23 +60,11 @@ or
CvStatModel::CvStatModel(...)
-----------------------------
`id=0.672522046035 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/ml/CvStatModel%3A%3ACvStatModel%28...%29>`__
Most ML classes provide single-step construct and train constructors. This constructor is equivalent to the default constructor, followed by the
``train()``
method with the parameters that are passed to the constructor.
Most ML classes provide single-step construct and train constructors. This constructor is equivalent to the default constructor, followed by the ``train()`` method with the parameters that are passed to the constructor.
..index:: CvStatModel::~CvStatModel
@ -116,27 +72,12 @@ method with the parameters that are passed to the constructor.
CvStatModel::~CvStatModel
-------------------------
`id=0.264685391089 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/ml/CvStatModel%3A%3A%7ECvStatModel>`__
..cfunction:: CvStatModel::~CvStatModel()
Virtual destructor.
The destructor of the base class is declared as virtual, so it is safe to write the following code: ::
The destructor of the base class is declared as virtual, so it is safe to write the following code:
::
CvStatModel* model;
if( use_svm )
model = new CvSVM(... /* SVM params */);
@ -144,15 +85,9 @@ The destructor of the base class is declared as virtual, so it is safe to write
model = new CvDTree(... /* Decision tree params */);
...
delete model;
..
Normally, the destructor of each derived class does nothing, but in this instance it calls the overridden method
``clear()``
that deallocates all the memory.
Normally, the destructor of each derived class does nothing, but in this instance it calls the overridden method ``clear()`` that deallocates all the memory.
..index:: CvStatModel::clear
@ -160,29 +95,11 @@ that deallocates all the memory.
CvStatModel::clear
------------------
`id=0.0232469661173 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/ml/CvStatModel%3A%3Aclear>`__
..cfunction:: void CvStatModel::clear()
Deallocates memory and resets the model state.
The method
``clear``
does the same job as the destructor; it deallocates all the memory occupied by the class members. But the object itself is not destructed, and can be reused further. This method is called from the destructor, from the
``train``
methods of the derived classes, from the methods
``load()``
,
``read()``
or even explicitly by the user.
The method ``clear`` does the same job as the destructor; it deallocates all the memory occupied by the class members. But the object itself is not destructed, and can be reused further. This method is called from the destructor, from the ``train`` methods of the derived classes, from the methods ``load()``,``read()`` or even explicitly by the user.
..index:: CvStatModel::save
@ -190,25 +107,11 @@ or even explicitly by the user.
CvStatModel::save
-----------------
`id=0.852967404887 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/ml/CvStatModel%3A%3Asave>`__
stores the complete model state to the specified XML or YAML file with the specified name or default name (that depends on the particular class).
``Data persistence``
functionality from CxCore is used.
The method ``save`` stores the complete model state to the specified XML or YAML file with the specified name or default name (that depends on the particular class). ``Data persistence`` functionality from CxCore is used.
..index:: CvStatModel::load
@ -216,55 +119,27 @@ functionality from CxCore is used.
CvStatModel::load
-----------------
`id=0.957875843108 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/ml/CvStatModel%3A%3Aload>`__
The method ``load`` loads the complete model state with the specified name (or default model-dependent name) from the specified XML or YAML file. The previous model state is cleared by ``clear()`` .
The method
``load``
loads the complete model state with the specified name (or default model-dependent name) from the specified XML or YAML file. The previous model state is cleared by
``clear()``
.
Note that the method is virtual, so any model can be loaded using this virtual method. However, unlike the C types of OpenCV that can be loaded using the generic
Note that the method is virtual, so any model can be loaded using this virtual method. However, unlike the C types of OpenCV that can be loaded using the generic
\
cross{cvLoad}, here the model type must be known, because an empty model must be constructed beforehand. This limitation will be removed in the later ML versions.
..index:: CvStatModel::write
.._CvStatModel::write:
CvStatModel::write
------------------
`id=0.167242991674 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/ml/CvStatModel%3A%3Awrite>`__
..cfunction:: void CvStatModel::write( CvFileStorage* storage, const char* name )
Writes the model to file storage.
The method
``write``
stores the complete model state to the file storage with the specified name or default name (that depends on the particular class). The method is called by
``save()``
.
The method ``write`` stores the complete model state to the file storage with the specified name or default name (that depends on the particular class). The method is called by ``save()`` .
..index:: CvStatModel::read
@ -272,29 +147,14 @@ stores the complete model state to the file storage with the specified name or d
CvStatModel::read
-----------------
`id=0.959831015705 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/ml/CvStatModel%3A%3Aread>`__
The method ``read`` restores the complete model state from the specified node of the file storage. The node must be located by the user using the function
:ref:`GetFileNodeByName` .
The method
``read``
restores the complete model state from the specified node of the file storage. The node must be located by the user using the function
:ref:`GetFileNodeByName`
.
The previous model state is cleared by
``clear()``
.
The previous model state is cleared by ``clear()`` .
..index:: CvStatModel::train
@ -302,95 +162,31 @@ The previous model state is cleared by
`id=0.616920786727 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/ml/CvStatModel%3A%3Atrain>`__
Trains the model.
The method trains the statistical model using a set of input feature vectors and the corresponding output values (responses). Both input and output vectors/values are passed as matrices. By default the input feature vectors are stored as ``train_data`` rows, i.e. all the components (features) of a training vector are stored continuously. However, some algorithms can handle the transposed representation, when all values of each particular feature (component/input variable) over the whole input set are stored continuously. If both layouts are supported, the method includes ``tflag`` parameter that specifies the orientation:
* ``tflag=CV_ROW_SAMPLE`` means that the feature vectors are stored as rows,
* ``tflag=CV_COL_SAMPLE`` means that the feature vectors are stored as columns.
The ``train_data`` must have a ``CV_32FC1`` (32-bit floating-point, single-channel) format. Responses are usually stored in the 1d vector (a row or a column) of ``CV_32SC1`` (only in the classification problem) or ``CV_32FC1`` format, one value per input vector (although some algorithms, like various flavors of neural nets, take vector responses).
Trains the model.
For classification problems the responses are discrete class labels; for regression problems the responses are values of the function to be approximated. Some algorithms can deal only with classification problems, some - only with regression problems, and some can deal with both problems. In the latter case the type of output variable is either passed as separate parameter, or as a last element of ``var_type`` vector:
* ``CV_VAR_CATEGORICAL`` means that the output values are discrete class labels,
* ``CV_VAR_ORDERED(=CV_VAR_NUMERICAL)`` means that the output values are ordered, i.e. 2 different values can be compared as numbers, and this is a regression problem
The types of input variables can be also specified using ``var_type`` . Most algorithms can handle only ordered input variables.
The method trains the statistical model using a set of input feature vectors and the corresponding output values (responses). Both input and output vectors/values are passed as matrices. By default the input feature vectors are stored as
``train_data``
rows, i.e. all the components (features) of a training vector are stored continuously. However, some algorithms can handle the transposed representation, when all values of each particular feature (component/input variable) over the whole input set are stored continuously. If both layouts are supported, the method includes
``tflag``
parameter that specifies the orientation:
*
``tflag=CV_ROW_SAMPLE``
means that the feature vectors are stored as rows,
*
``tflag=CV_COL_SAMPLE``
means that the feature vectors are stored as columns.
The
``train_data``
must have a
``CV_32FC1``
(32-bit floating-point, single-channel) format. Responses are usually stored in the 1d vector (a row or a column) of
``CV_32SC1``
(only in the classification problem) or
``CV_32FC1``
format, one value per input vector (although some algorithms, like various flavors of neural nets, take vector responses).
For classification problems the responses are discrete class labels; for regression problems the responses are values of the function to be approximated. Some algorithms can deal only with classification problems, some - only with regression problems, and some can deal with both problems. In the latter case the type of output variable is either passed as separate parameter, or as a last element of
``var_type``
vector:
*
``CV_VAR_CATEGORICAL``
means that the output values are discrete class labels,
*
``CV_VAR_ORDERED(=CV_VAR_NUMERICAL)``
means that the output values are ordered, i.e. 2 different values can be compared as numbers, and this is a regression problem
The types of input variables can be also specified using
``var_type``
. Most algorithms can handle only ordered input variables.
Many models in the ML may be trained on a selected feature subset, and/or on a selected sample subset of the training set. To make it easier for the user, the method
``train``
usually includes
``var_idx``
and
``sample_idx``
parameters. The former identifies variables (features) of interest, and the latter identifies samples of interest. Both vectors are either integer (
``CV_32SC1``
) vectors, i.e. lists of 0-based indices, or 8-bit (
``CV_8UC1``
) masks of active variables/samples. The user may pass
``NULL``
pointers instead of either of the arguments, meaning that all of the variables/samples are used for training.
Additionally some algorithms can handle missing measurements, that is when certain features of certain training samples have unknown values (for example, they forgot to measure a temperature of patient A on Monday). The parameter
``missing_mask``
, an 8-bit matrix the same size as
``train_data``
, is used to mark the missed values (non-zero elements of the mask).
Usually, the previous model state is cleared by
``clear()``
before running the training procedure. However, some algorithms may optionally update the model state with the new training data, instead of resetting it.
Many models in the ML may be trained on a selected feature subset, and/or on a selected sample subset of the training set. To make it easier for the user, the method ``train`` usually includes ``var_idx`` and ``sample_idx`` parameters. The former identifies variables (features) of interest, and the latter identifies samples of interest. Both vectors are either integer ( ``CV_32SC1`` ) vectors, i.e. lists of 0-based indices, or 8-bit ( ``CV_8UC1`` ) masks of active variables/samples. The user may pass ``NULL`` pointers instead of either of the arguments, meaning that all of the variables/samples are used for training.
Additionally some algorithms can handle missing measurements, that is when certain features of certain training samples have unknown values (for example, they forgot to measure a temperature of patient A on Monday). The parameter ``missing_mask`` , an 8-bit matrix the same size as ``train_data`` , is used to mark the missed values (non-zero elements of the mask).
Usually, the previous model state is cleared by ``clear()`` before running the training procedure. However, some algorithms may optionally update the model state with the new training data, instead of resetting it.
..index:: CvStatModel::predict
@ -398,29 +194,11 @@ before running the training procedure. However, some algorithms may optionally u
CvStatModel::predict
--------------------
`id=0.404351209628 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/ml/CvStatModel%3A%3Apredict>`__
The method is used to predict the response for a new sample. In the case of classification the method returns the class label, in the case of regression - the output function value. The input sample must have as many components as the
``train_data``
passed to
``train``
contains. If the
``var_idx``
parameter is passed to
``train``
, it is remembered and then is used to extract only the necessary components from the input sample in the method
``predict``
.
The method is used to predict the response for a new sample. In the case of classification the method returns the class label, in the case of regression - the output function value. The input sample must have as many components as the ``train_data`` passed to ``train`` contains. If the ``var_idx`` parameter is passed to ``train`` , it is remembered and then is used to extract only the necessary components from the input sample in the method ``predict`` .
The suffix "const" means that prediction does not affect the internal model state, so the method can be safely called from within different threads.
Originally, support vector machines (SVM) was a technique for building an optimal (in some sense) binary (2-class) classifier. Then the technique has been extended to regression and clustering problems. SVM is a partial case of kernel-based methods, it maps feature vectors into higher-dimensional space using some kernel function, and then it builds an optimal linear discriminating function in this space (or an optimal hyper-plane that fits into the training data, ...). in the case of SVM the kernel is not defined explicitly. Instead, a distance between any 2 points in the hyper-space needs to be defined.
The solution is optimal in a sense that the margin between the separating hyper-plane and the nearest feature vectors from the both classes (in the case of 2-class classifier) is maximal. The feature vectors that are the closest to the hyper-plane are called "support vectors", meaning that the position of other vectors does not affect the hyper-plane (the decision function).
There are a lot of good references on SVM. Here are only a few ones to start with.
*
**[Burges98] C. Burges. "A tutorial on support vector machines for pattern recognition", Knowledge Discovery and Data Mining 2(2), 1998.**
(available online at
(available online at
http://citeseer.ist.psu.edu/burges98tutorial.html
).
*
**LIBSVM - A Library for Support Vector Machines. By Chih-Chung Chang and Chih-Jen Lin**
(
http://www.csie.ntu.edu.tw/~cjlin/libsvm/
)
..index:: CvSVM
@ -34,45 +27,33 @@ There are a lot of good references on SVM. Here are only a few ones to start wit
CvSVM
-----
`id=0.838668945864 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/ml/CvSVM>`__
The method trains the SVM model. It follows the conventions of the generic ``train`` "method" with the following limitations: only the CV_ROW_SAMPLE data layout is supported, the input variables are all ordered, the output variables can be either categorical ( ``_params.svm_type=CvSVM::C_SVC`` or ``_params.svm_type=CvSVM::NU_SVC`` ), or ordered ( ``_params.svm_type=CvSVM::EPS_SVR`` or ``_params.svm_type=CvSVM::NU_SVR`` ), or not required at all ( ``_params.svm_type=CvSVM::ONE_CLASS`` ), missing measurements are not supported.
The method trains the SVM model. It follows the conventions of the generic
``train``
"method" with the following limitations: only the CV
_
ROW
_
SAMPLE data layout is supported, the input variables are all ordered, the output variables can be either categorical (
``_params.svm_type=CvSVM::C_SVC``
or
``_params.svm_type=CvSVM::NU_SVC``
), or ordered (
``_params.svm_type=CvSVM::EPS_SVR``
or
``_params.svm_type=CvSVM::NU_SVR``
), or not required at all (
``_params.svm_type=CvSVM::ONE_CLASS``
), missing measurements are not supported.
All the other parameters are gathered in
:ref:`CvSVMParams`
structure.
All the other parameters are gathered in
:ref:`CvSVMParams` structure.
..index:: CvSVM::train_auto
@ -207,119 +140,41 @@ structure.
CvSVM::train_auto
-----------------
`id=0.63289997524 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/ml/CvSVM%3A%3Atrain_auto>`__
:param k_fold:Cross-validation parameter. The training set is divided into ``k_fold`` subsets, one subset being used to train the model, the others forming the test set. So, the SVM algorithm is executed ``k_fold`` times.
:param k_fold:Cross-validation parameter. The training set is divided into ``k_fold`` subsets, one subset being used to train the model, the others forming the test set. So, the SVM algorithm is executed ``k_fold`` times.
The method trains the SVM model automatically by choosing the optimal
parameters
``C``
,
``gamma``
,
``p``
,
``nu``
,
``coef0``
,
``degree``
from
:ref:`CvSVMParams`
. By optimal
parameters ``C``,``gamma``,``p``,``nu``,``coef0``,``degree`` from
:ref:`CvSVMParams` . By optimal
one means that the cross-validation estimate of the test set error
is minimal. The parameters are iterated by a logarithmic grid, for
example, the parameter
``gamma``
takes the values in the set
(
:math:`min`
,
:math:`min*step`
,
:math:`min*{step}^2`
, ...
:math:`min*{step}^n`
)
where
:math:`min`
is
``gamma_grid.min_val``
,
:math:`step`
is
``gamma_grid.step``
, and
:math:`n`
is the maximal index such, that
example, the parameter ``gamma`` takes the values in the set
If there is no need in optimization in some parameter, the according grid step should be set to any value less or equal to 1. For example, to avoid optimization in
``gamma``
one should set
``gamma_grid.step = 0``
,
``gamma_grid.min_val``
,
``gamma_grid.max_val``
being arbitrary numbers. In this case, the value
``params.gamma``
will be taken for
``gamma``
.
If there is no need in optimization in some parameter, the according grid step should be set to any value less or equal to 1. For example, to avoid optimization in ``gamma`` one should set ``gamma_grid.step = 0``,``gamma_grid.min_val``,``gamma_grid.max_val`` being arbitrary numbers. In this case, the value ``params.gamma`` will be taken for ``gamma`` .
And, finally, if the optimization in some parameter is required, but
there is no idea of the corresponding grid, one may call the function
``CvSVM::get_default_grid``
. In
order to generate a grid, say, for
``gamma``
, call
``CvSVM::get_default_grid(CvSVM::GAMMA)``
.
This function works for the case of classification
(
``params.svm_type=CvSVM::C_SVC``
or
``params.svm_type=CvSVM::NU_SVC``
)
as well as for the regression
(
``params.svm_type=CvSVM::EPS_SVR``
or
``params.svm_type=CvSVM::NU_SVR``
). If
``params.svm_type=CvSVM::ONE_CLASS``
, no optimization is made and the usual SVM with specified in
``params``
parameters is executed.
there is no idea of the corresponding grid, one may call the function ``CvSVM::get_default_grid`` . In
order to generate a grid, say, for ``gamma`` , call ``CvSVM::get_default_grid(CvSVM::GAMMA)`` .
This function works for the case of classification
( ``params.svm_type=CvSVM::C_SVC`` or ``params.svm_type=CvSVM::NU_SVC`` )
as well as for the regression
( ``params.svm_type=CvSVM::EPS_SVR`` or ``params.svm_type=CvSVM::NU_SVR`` ). If ``params.svm_type=CvSVM::ONE_CLASS`` , no optimization is made and the usual SVM with specified in ``params`` parameters is executed.
..index:: CvSVM::get_default_grid
@ -327,45 +182,28 @@ parameters is executed.
CvSVM::get_default_grid
-----------------------
`id=0.647625940741 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/ml/CvSVM%3A%3Aget_default_grid>`__
..cfunction:: CvParamGrid CvSVM::get_default_grid( int param_id )
Generates a grid for the SVM parameters.
:param param_id:Must be one of the following:
* **CvSVM::C**
* **CvSVM::GAMMA**
* **CvSVM::P**
* **CvSVM::NU**
* **CvSVM::COEF**
:param param_id:Must be one of the following:
* **CvSVM::C**
* **CvSVM::GAMMA**
* **CvSVM::P**
* **CvSVM::NU**
* **CvSVM::COEF**
* **CvSVM::DEGREE**
.
The grid will be generated for the parameter with this ID.
The function generates a grid for the specified parameter of the SVM algorithm. The grid may be passed to the function
``CvSVM::train_auto``
.
* **CvSVM::DEGREE**
.
The grid will be generated for the parameter with this ID.
The function generates a grid for the specified parameter of the SVM algorithm. The grid may be passed to the function ``CvSVM::train_auto`` .
..index:: CvSVM::get_params
@ -373,23 +211,11 @@ The function generates a grid for the specified parameter of the SVM algorithm.
CvSVM::get_params
-----------------
`id=0.179013680104 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/ml/CvSVM%3A%3Aget_params>`__
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)
int ncategories; // number of categories (for categorical features only)
Size origWinSize; // size of training images
vector<Stage> stages; // vector of stages (BOOST for now)
vector<DTree> classifiers; // vector of decision trees
vector<DTreeNode> nodes; // vector of tree nodes
vector<float> leaves; // vector of leaf values
vector<int> subsets; // subsets of split by categorical feature
Ptr<FeatureEvaluator> feval; // pointer to feature evaluator
Ptr<CvHaarClassifierCascade> oldCascade; // pointer to old cascade
};
..
..index:: CascadeClassifier::CascadeClassifier
cv::CascadeClassifier::CascadeClassifier
----------------------------------------
`id=0.751407128029 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/objdetect/CascadeClassifier%3A%3ACascadeClassifier>`__
Loads the classifier from file. The previous content is destroyed.
:param filename:Name of file from which classifier will be load. File may contain as old haar classifier (trained by haartraining application) or new cascade classifier (trained traincascade application).
:param filename:Name of file from which classifier will be load. File may contain as old haar classifier (trained by haartraining application) or new cascade classifier (trained traincascade application).
..index:: CascadeClassifier::read
cv::CascadeClassifier::read
---------------------------
`id=0.21698114693 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/objdetect/CascadeClassifier%3A%3Aread>`__
Reads the classifier from a FileStorage node. File may contain a new cascade classifier (trained traincascade application) only.
..index:: CascadeClassifier::detectMultiScale
cv::CascadeClassifier::detectMultiScale
---------------------------------------
`id=0.0317051017457 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/objdetect/CascadeClassifier%3A%3AdetectMultiScale>`__
..cfunction:: void CascadeClassifier::detectMultiScale( const Mat\& image, vector<Rect>\& objects, double scaleFactor=1.1, int minNeighbors=3, int flags=0, Size minSize=Size())
Detects objects of different sizes in the input image. The detected objects are returned as a list of rectangles.
:param image:Matrix of type ``CV_8U`` containing the image in which to detect objects.
:param objects:Vector of rectangles such that each rectangle contains the detected object.
:param scaleFactor:Specifies how much the image size is reduced at each image scale.
:param minNeighbors:Speficifes how many neighbors should each candiate rectangle have to retain it.
:param image:Matrix of type ``CV_8U`` containing the image in which to detect objects.
:param objects:Vector of rectangles such that each rectangle contains the detected object.
:param scaleFactor:Specifies how much the image size is reduced at each image scale.
:param minNeighbors:Speficifes how many neighbors should each candiate rectangle have to retain it.
:param flags:This parameter is not used for new cascade and have the same meaning for old cascade as in function cvHaarDetectObjects.
:param minSize:The minimum possible object size. Objects smaller than that are ignored.
:param flags:This parameter is not used for new cascade and have the same meaning for old cascade as in function cvHaarDetectObjects.
..index:: CascadeClassifier::setImage
:param minSize:The minimum possible object size. Objects smaller than that are ignored.
..index:: CascadeClassifier::setImage
cv::CascadeClassifier::setImage
-------------------------------
`id=0.632605719384 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/objdetect/CascadeClassifier%3A%3AsetImage>`__
Sets the image for detection (called by detectMultiScale at each image level).
:param feval:Pointer to feature evaluator which is used for computing features.
:param feval:Pointer to feature evaluator which is used for computing features.
:param image:Matrix of type ``CV_8UC1`` containing the image in which to compute the features.
:param image:Matrix of type ``CV_8UC1`` containing the image in which to compute the features.
..index:: CascadeClassifier::runAt
cv::CascadeClassifier::runAt
----------------------------
`id=0.159942031477 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/objdetect/CascadeClassifier%3A%3ArunAt>`__
..cfunction:: int CascadeClassifier::runAt( Ptr<FeatureEvaluator>\& feval, Point pt )
Runs the detector at the specified point (the image that the detector is working with should be set by setImage).
:param feval:Feature evaluator which is used for computing features.
:param pt:The upper left point of window in which the features will be computed. Size of the window is equal to size of training images.
:param feval:Feature evaluator which is used for computing features.
:param pt:The upper left point of window in which the features will be computed. Size of the window is equal to size of training images.
Returns:
1 - if cascade classifier detects object in the given location.
-si - otherwise. si is an index of stage which first predicted that given window is a background image.
..index:: groupRectangles
cv::groupRectangles
-------------------
`id=0.226659440065 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/objdetect/groupRectangles>`__
..cfunction:: void groupRectangles(vector<Rect>\& rectList, int groupThreshold, double eps=0.2)
Groups the object candidate rectangles
:param rectList:The input/output vector of rectangles. On output there will be retained and grouped rectangles
:param groupThreshold:The minimum possible number of rectangles, minus 1, in a group of rectangles to retain it.
:param eps:The relative difference between sides of the rectangles to merge them into a group
:param rectList:The input/output vector of rectangles. On output there will be retained and grouped rectangles
:param groupThreshold:The minimum possible number of rectangles, minus 1, in a group of rectangles to retain it.
:param eps:The relative difference between sides of the rectangles to merge them into a group
The function is a wrapper for a generic function
:func:`partition`
. It clusters all the input rectangles using the rectangle equivalence criteria, that combines rectangles that have similar sizes and similar locations (the similarity is defined by
``eps``
). When
``eps=0``
, no clustering is done at all. If
:math:`\texttt{eps}\rightarrow +\inf`
, all the rectangles will be put in one cluster. Then, the small clusters, containing less than or equal to
``groupThreshold``
rectangles, will be rejected. In each other cluster the average rectangle will be computed and put into the output rectangle list.
The function is a wrapper for a generic function
:func:`partition` . It clusters all the input rectangles using the rectangle equivalence criteria, that combines rectangles that have similar sizes and similar locations (the similarity is defined by ``eps`` ). When ``eps=0`` , no clustering is done at all. If
:math:`\texttt{eps}\rightarrow +\inf` , all the rectangles will be put in one cluster. Then, the small clusters, containing less than or equal to ``groupThreshold`` rectangles, will be rejected. In each other cluster the average rectangle will be computed and put into the output rectangle list.
:param status:The output status vector. Each element of the vector is set to 1 if the flow for the corresponding features has been found, 0 otherwise
Calculates the optical flow for a sparse feature set using the iterative Lucas-Kanade method with pyramids
:param err:The output vector that will contain the difference between patches around the original and moved points
:param winSize:Size of the search window at each pyramid level
:param maxLevel:0-based maximal pyramid level number. If 0, pyramids are not used (single level), if 1, two levels are used etc.
:param criteria:Specifies the termination criteria of the iterative search algorithm (after the specified maximum number of iterations ``criteria.maxCount`` or when the search window moves by less than ``criteria.epsilon``
:param derivLambda:The relative weight of the spatial image derivatives impact to the optical flow estimation. If ``derivLambda=0`` , only the image intensity is used, if ``derivLambda=1`` , only derivatives are used. Any other values between 0 and 1 means that both derivatives and the image intensity are used (in the corresponding proportions).
:param flags:The operation flags:
:param prevImg:The first 8-bit single-channel or 3-channel input image
:param nextImg:The second input image of the same size and the same type as ``prevImg``
:param prevPts:Vector of points for which the flow needs to be found
:param nextPts:The output vector of points containing the calculated new positions of the input features in the second image
:param status:The output status vector. Each element of the vector is set to 1 if the flow for the corresponding features has been found, 0 otherwise
:param err:The output vector that will contain the difference between patches around the original and moved points
:param winSize:Size of the search window at each pyramid level
:param maxLevel:0-based maximal pyramid level number. If 0, pyramids are not used (single level), if 1, two levels are used etc.
:param criteria:Specifies the termination criteria of the iterative search algorithm (after the specified maximum number of iterations ``criteria.maxCount`` or when the search window moves by less than ``criteria.epsilon``
:param derivLambda:The relative weight of the spatial image derivatives impact to the optical flow estimation. If ``derivLambda=0`` , only the image intensity is used, if ``derivLambda=1`` , only derivatives are used. Any other values between 0 and 1 means that both derivatives and the image intensity are used (in the corresponding proportions).
:param flags:The operation flags:
* **OPTFLOW_USE_INITIAL_FLOW** use initial estimations stored in ``nextPts`` . If the flag is not set, then initially :math:`\texttt{nextPts}\leftarrow\texttt{prevPts}`
The function implements the sparse iterative version of the Lucas-Kanade optical flow in pyramids, see
* **OPTFLOW_USE_INITIAL_FLOW** use initial estimations stored in ``nextPts`` . If the flag is not set, then initially :math:`\texttt{nextPts}\leftarrow\texttt{prevPts}`
The function implements the sparse iterative version of the Lucas-Kanade optical flow in pyramids, see
Bouguet00
.
..index:: calcOpticalFlowFarneback
cv::calcOpticalFlowFarneback
----------------------------
`id=0.147581673853 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/video/calcOpticalFlowFarneback>`__
..cfunction:: void calcOpticalFlowFarneback( const Mat\& prevImg, const Mat\& nextImg, Mat\& flow, double pyrScale, int levels, int winsize, int iterations, int polyN, double polySigma, int flags )
Computes dense optical flow using Gunnar Farneback's algorithm
:param prevImg:The first 8-bit single-channel input image
:param nextImg:The second input image of the same size and the same type as ``prevImg``
:param flow:The computed flow image; will have the same size as ``prevImg`` and type ``CV_32FC2``
:param pyrScale:Specifies the image scale (<1) to build the pyramids for each image. ``pyrScale=0.5`` means the classical pyramid, where each next layer is twice smaller than the previous
:param levels:The number of pyramid layers, including the initial image. ``levels=1`` means that no extra layers are created and only the original images are used
:param winsize:The averaging window size; The larger values increase the algorithm robustness to image noise and give more chances for fast motion detection, but yield more blurred motion field
:param prevImg:The first 8-bit single-channel input image
:param nextImg:The second input image of the same size and the same type as ``prevImg``
:param flow:The computed flow image; will have the same size as ``prevImg`` and type ``CV_32FC2``
:param pyrScale:Specifies the image scale (<1) to build the pyramids for each image. ``pyrScale=0.5`` means the classical pyramid, where each next layer is twice smaller than the previous
:param levels:The number of pyramid layers, including the initial image. ``levels=1`` means that no extra layers are created and only the original images are used
:param winsize:The averaging window size; The larger values increase the algorithm robustness to image noise and give more chances for fast motion detection, but yield more blurred motion field
:param iterations:The number of iterations the algorithm does at each pyramid level
:param polyN:Size of the pixel neighborhood used to find polynomial expansion in each pixel. The larger values mean that the image will be approximated with smoother surfaces, yielding more robust algorithm and more blurred motion field. Typically, ``polyN`` =5 or 7
:param polySigma:Standard deviation of the Gaussian that is used to smooth derivatives that are used as a basis for the polynomial expansion. For ``polyN=5`` you can set ``polySigma=1.1`` , for ``polyN=7`` a good value would be ``polySigma=1.5``
:param flags:The operation flags; can be a combination of the following:
* **OPTFLOW_USE_INITIAL_FLOW** Use the input ``flow`` as the initial flow approximation
* **OPTFLOW_FARNEBACK_GAUSSIAN** Use a Gaussian :math:`\texttt{winsize}\times\texttt{winsize}` filter instead of box filter of the same size for optical flow estimation. Usually, this option gives more accurate flow than with a box filter, at the cost of lower speed (and normally ``winsize`` for a Gaussian window should be set to a larger value to achieve the same level of robustness)
The function finds optical flow for each
``prevImg``
pixel using the alorithm so that
:param iterations:The number of iterations the algorithm does at each pyramid level
:param polyN:Size of the pixel neighborhood used to find polynomial expansion in each pixel. The larger values mean that the image will be approximated with smoother surfaces, yielding more robust algorithm and more blurred motion field. Typically, ``polyN`` =5 or 7
:param polySigma:Standard deviation of the Gaussian that is used to smooth derivatives that are used as a basis for the polynomial expansion. For ``polyN=5`` you can set ``polySigma=1.1`` , for ``polyN=7`` a good value would be ``polySigma=1.5``
:param flags:The operation flags; can be a combination of the following:
..math::
* **OPTFLOW_USE_INITIAL_FLOW** Use the input ``flow`` as the initial flow approximation
* **OPTFLOW_FARNEBACK_GAUSSIAN** Use a Gaussian :math:`\texttt{winsize}\times\texttt{winsize}` filter instead of box filter of the same size for optical flow estimation. Usually, this option gives more accurate flow than with a box filter, at the cost of lower speed (and normally ``winsize`` for a Gaussian window should be set to a larger value to achieve the same level of robustness)
The function finds optical flow for each ``prevImg`` pixel using the alorithm so that
That is, MHI pixels where motion occurs are set to the current
``timestamp``
, while the pixels where motion happened last time a long time ago are cleared.
That is, MHI pixels where motion occurs are set to the current ``timestamp`` , while the pixels where motion happened last time a long time ago are cleared.
The function, together with
:func:`calcMotionGradient`
and
:func:`calcGlobalOrientation`
, implements the motion templates technique, described in
The function, together with
:func:`calcMotionGradient` and
:func:`calcGlobalOrientation` , implements the motion templates technique, described in
Davis97
and
and
Bradski00
.
See also the OpenCV sample
``motempl.c``
that demonstrates the use of all the motion template functions.
See also the OpenCV sample ``motempl.c`` that demonstrates the use of all the motion template functions.
..index:: calcMotionGradient
cv::calcMotionGradient
----------------------
`id=0.911487015982 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/video/calcMotionGradient>`__
Calculates the gradient orientation of a motion history image.
:param mhi:Motion history single-channel floating-point image
:param mask:The output mask image; will have the type ``CV_8UC1`` and the same size as ``mhi`` . Its non-zero elements will mark pixels where the motion gradient data is correct
:param orientation:The output motion gradient orientation image; will have the same type and the same size as ``mhi`` . Each pixel of it will the motion orientation in degrees, from 0 to 360.
:param delta1, delta2:The minimal and maximal allowed difference between ``mhi`` values within a pixel neighorhood. That is, the function finds the minimum ( :math:`m(x,y)` ) and maximum ( :math:`M(x,y)` ) ``mhi`` values over :math:`3 \times 3` neighborhood of each pixel and marks the motion orientation at :math:`(x, y)` as valid only if
:param mhi:Motion history single-channel floating-point image
:param mask:The output mask image; will have the type ``CV_8UC1`` and the same size as ``mhi`` . Its non-zero elements will mark pixels where the motion gradient data is correct
:param orientation:The output motion gradient orientation image; will have the same type and the same size as ``mhi`` . Each pixel of it will the motion orientation in degrees, from 0 to 360.
:param delta1, delta2:The minimal and maximal allowed difference between ``mhi`` values within a pixel neighorhood. That is, the function finds the minimum ( :math:`m(x,y)` ) and maximum ( :math:`M(x,y)` ) ``mhi`` values over :math:`3 \times 3` neighborhood of each pixel and marks the motion orientation at :math:`(x, y)` as valid only if
:func:`phase` are used, so that the computed angle is measured in degrees and covers the full range 0..360). Also, the ``mask`` is filled to indicate pixels where the computed angle is valid.
..index:: calcGlobalOrientation
cv::calcGlobalOrientation
-------------------------
`id=0.785441857219 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/video/calcGlobalOrientation>`__
Calculates the global motion orientation in some selected region.
:param orientation:Motion gradient orientation image, calculated by the function :func:`calcMotionGradient`
:param mask:Mask image. It may be a conjunction of a valid gradient mask, also calculated by :func:`calcMotionGradient` , and the mask of the region, whose direction needs to be calculated
:param orientation:Motion gradient orientation image, calculated by the function :func:`calcMotionGradient`
:param mask:Mask image. It may be a conjunction of a valid gradient mask, also calculated by :func:`calcMotionGradient` , and the mask of the region, whose direction needs to be calculated
:param mhi:The motion history image, calculated by :func:`updateMotionHistory`
:param timestamp:The timestamp passed to :func:`updateMotionHistory`
:param duration:Maximal duration of motion track in milliseconds, passed to :func:`updateMotionHistory`
:param mhi:The motion history image, calculated by :func:`updateMotionHistory`
:param timestamp:The timestamp passed to :func:`updateMotionHistory`
:param duration:Maximal duration of motion track in milliseconds, passed to :func:`updateMotionHistory`
The function calculates the average
motion direction in the selected region and returns the angle between
0 degrees and 360 degrees. The average direction is computed from
the weighted orientation histogram, where a recent motion has larger
weight and the motion occurred in the past has smaller weight, as recorded in
``mhi``
.
weight and the motion occurred in the past has smaller weight, as recorded in ``mhi`` .
..index:: CamShift
cv::CamShift
------------
`id=0.364212510583 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/video/CamShift>`__
:param probImage:Back projection of the object histogram; see :func:`calcBackProject`
:param window:Initial search window
:param probImage:Back projection of the object histogram; see :func:`calcBackProject`
:param window:Initial search window
:param criteria:Stop criteria for the underlying :func:`meanShift`
:param criteria:Stop criteria for the underlying :func:`meanShift`
The function implements the CAMSHIFT object tracking algrorithm
Bradski98
.
First, it finds an object center using
:func:`meanShift`
and then adjust the window size and finds the optimal rotation. The function returns the rotated rectangle structure that includes the object position, size and the orientation. The next position of the search window can be obtained with
``RotatedRect::boundingRect()``
.
See the OpenCV sample
``camshiftdemo.c``
that tracks colored objects.
First, it finds an object center using
:func:`meanShift` and then adjust the window size and finds the optimal rotation. The function returns the rotated rectangle structure that includes the object position, size and the orientation. The next position of the search window can be obtained with ``RotatedRect::boundingRect()`` .
See the OpenCV sample ``camshiftdemo.c`` that tracks colored objects.
..index:: meanShift
cv::meanShift
-------------
`id=0.437046716762 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/video/meanShift>`__
:param probImage:Back projection of the object histogram; see :func:`calcBackProject`
:param window:Initial search window
:param criteria:The stop criteria for the iterative search algorithm
:param probImage:Back projection of the object histogram; see :func:`calcBackProject`
:param window:Initial search window
:param criteria:The stop criteria for the iterative search algorithm
The function implements iterative object search algorithm. It takes the object back projection on input and the initial position. The mass center in
``window``
of the back projection image is computed and the search window center shifts to the mass center. The procedure is repeated until the specified number of iterations
``criteria.maxCount``
is done or until the window center shifts by less than
``criteria.epsilon``
. The algorithm is used inside
:func:`CamShift`
and, unlike
:func:`CamShift`
, the search window size or orientation do not change during the search. You can simply pass the output of
:func:`calcBackProject`
to this function, but better results can be obtained if you pre-filter the back projection and remove the noise (e.g. by retrieving connected components with
:func:`findContours`
, throwing away contours with small area (
:func:`contourArea`
) and rendering the remaining contours with
:func:`drawContours`
)
The function implements iterative object search algorithm. It takes the object back projection on input and the initial position. The mass center in ``window`` of the back projection image is computed and the search window center shifts to the mass center. The procedure is repeated until the specified number of iterations ``criteria.maxCount`` is done or until the window center shifts by less than ``criteria.epsilon`` . The algorithm is used inside
:func:`CamShift` and, unlike
:func:`CamShift` , the search window size or orientation do not change during the search. You can simply pass the output of
:func:`calcBackProject` to this function, but better results can be obtained if you pre-filter the back projection and remove the noise (e.g. by retrieving connected components with
:func:`findContours` , throwing away contours with small area (
:func:`contourArea` ) and rendering the remaining contours with
:func:`drawContours` )
..index:: KalmanFilter
@ -409,22 +203,10 @@ to this function, but better results can be obtained if you pre-filter the back
KalmanFilter
------------
`id=0.4483617174 Comments from the Wiki <http://opencv.willowgarage.com/wiki/documentation/cpp/video/KalmanFilter>`__
..ctype:: KalmanFilter
Kalman filter class ::
Kalman filter class
::
class KalmanFilter
{
public:
@ -434,9 +216,9 @@ Kalman filter class
// predicts statePre from statePost
const Mat& predict(const Mat& control=Mat());
// corrects statePre based on the input measurement vector
// and stores the result to statePost.
// and stores the result to statePost.
const Mat& correct(const Mat& measurement);
Mat statePre; // predicted state (x'(k)):
// x(k)=A*x(k-1)+B*u(k)
Mat statePost; // corrected state (x(k)):
@ -455,17 +237,8 @@ Kalman filter class
// P(k)=(I-K(k)*H)*P'(k)
...
};
..
The class implements standard Kalman filter
The class implements standard Kalman filter
http://en.wikipedia.org/wiki/Kalman_filter
. However, you can modify
``transitionMatrix``
,
``controlMatrix``
and
``measurementMatrix``
to get the extended Kalman filter functionality. See the OpenCV sample
``kalman.c``
. However, you can modify ``transitionMatrix``,``controlMatrix`` and ``measurementMatrix`` to get the extended Kalman filter functionality. See the OpenCV sample ``kalman.c``