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

propagated some more fixes from 2.3 branch to the trunk

This commit is contained in:
Vadim Pisarevsky
2011-06-29 22:06:42 +00:00
parent dacd265424
commit b204e73d9a
54 changed files with 9120 additions and 3049 deletions
+1 -1
View File
@@ -645,7 +645,7 @@ Finally, there are STL-style iterators that are smart enough to skip gaps betwee
The matrix iterators are random-access iterators, so they can be passed to any STL algorithm, including ``std::sort()`` .
.. _MatrixExpressions:
Matrix Expressions
------------------
+13 -13
View File
@@ -3,16 +3,17 @@ Clustering
.. highlight:: cpp
.. index:: kmeans
.. _kmeans:
kmeans
------
Finds centers of clusters and groups input samples around the clusters.
.. ocv:function:: double kmeans( InputArray samples, int clusterCount, InputOutputArray labels, TermCriteria termcrit, int attempts, int flags, OutputArray centers=noArray() )
.. ocv:function:: double kmeans( InputArray samples, int clusterCount, InputOutputArray labels, TermCriteria criteria, int attempts, int flags, OutputArray centers=noArray() )
Finds centers of clusters and groups input samples around the clusters.
.. ocv:pyfunction:: cv2.kmeans(data, K, criteria, attempts, flags[, bestLabels[, centers]]) -> retval, bestLabels, centers
.. ocv:cfunction:: int cvKMeans2(const CvArr* samples, int nclusters, CvArr* labels, CvTermCriteria criteria, int attempts=1, CvRNG* rng=0, int flags=0, CvArr* centers=0, double* compactness=0)
.. ocv:pyoldfunction:: cv.KMeans2(samples, nclusters, labels, criteria)-> None
:param samples: Floating-point matrix of input samples, one row per sample.
@@ -20,7 +21,7 @@ kmeans
:param labels: Input/output integer array that stores the cluster indices for every sample.
:param termcrit: Flag to specify the maximum number of iterations and/or the desired accuracy. The accuracy is specified as ``termcrit.epsilon``. As soon as each of the cluster centers moves by less than ``termcrit.epsilon`` on some iteration, the algorithm stops.
:param criteria: The algorithm termination criteria, that is, the maximum number of iterations and/or the desired accuracy. The accuracy is specified as ``criteria.epsilon``. As soon as each of the cluster centers moves by less than ``criteria.epsilon`` on some iteration, the algorithm stops.
:param attempts: Flag to specify the number of times the algorithm is executed using different initial labelings. The algorithm returns the labels that yield the best compactness (see the last function parameter).
@@ -28,7 +29,7 @@ kmeans
* **KMEANS_RANDOM_CENTERS** Select random initial centers in each attempt.
* **KMEANS_PP_CENTERS** Use ``kmeans++`` center initialization by Arthur and Vassilvitskii.
* **KMEANS_PP_CENTERS** Use ``kmeans++`` center initialization by Arthur and Vassilvitskii [Arthur2007].
* **KMEANS_USE_INITIAL_LABELS** During the first (and possibly the only) attempt, use the user-supplied labels instead of computing them from the initial centers. For the second and further attempts, use the random or semi-random centers. Use one of ``KMEANS_*_CENTERS`` flag to specify the exact method.
@@ -53,15 +54,13 @@ Basically, you can use only the core of the function, set the number of
attempts to 1, initialize labels each time using a custom algorithm, pass them with the
( ``flags`` = ``KMEANS_USE_INITIAL_LABELS`` ) flag, and then choose the best (most-compact) clustering.
.. index:: partition
partition
-------------
Splits an element set into equivalency classes.
.. ocv:function:: template<typename _Tp, class _EqPredicate> int
.. ocv:function:: partition( const vector<_Tp>& vec, vector<int>& labels, _EqPredicate predicate=_EqPredicate())
Splits an element set into equivalency classes.
.. ocv:function:: partition( const vector<_Tp>& vec, vector<int>& labels, _EqPredicate predicate=_EqPredicate())
:param vec: Set of elements stored as a vector.
@@ -77,3 +76,4 @@ http://en.wikipedia.org/wiki/Disjoint-set_data_structure
. The function
returns the number of equivalency classes.
.. [Arthur2007] Arthur and S. Vassilvitskii “k-means++: the advantages of careful seeding”, Proceedings of the eighteenth annual ACM-SIAM symposium on Discrete algorithms, 2007
+3
View File
@@ -6,9 +6,12 @@ core. The Core Functionality
:maxdepth: 2
basic_structures
old_basic_structures
dynamic_structures
operations_on_arrays
drawing_functions
xml_yaml_persistence
old_xml_yaml_persistence
clustering
utility_and_system_functions_and_macros
+132 -36
View File
@@ -26,13 +26,16 @@ If a drawn figure is partially or completely outside the image, the drawing func
.. note:: The functions do not support alpha-transparency when the target image is 4-channel. In this case, the ``color[3]`` is simply copied to the repainted pixels. Thus, if you want to paint semi-transparent shapes, you can paint them in a separate buffer and then blend it with the main image.
.. index:: circle
circle
----------
Draws a circle.
.. ocv:function:: void circle(Mat& img, Point center, int radius, const Scalar& color, int thickness=1, int lineType=8, int shift=0)
Draws a circle.
.. ocv:pyfunction:: cv2.circle(img, center, radius, color[, thickness[, lineType[, shift]]]) -> None
.. ocv:cfunction:: void cvCircle( CvArr* img, CvPoint center, int radius, CvScalar color, int thickness=1, int lineType=8, int shift=0 )
.. ocv:pyoldfunction:: cv.Circle(img, center, radius, color, thickness=1, lineType=8, shift=0)-> None
:param img: Image where the circle is drawn.
@@ -50,18 +53,21 @@ circle
The function ``circle`` draws a simple or filled circle with a given center and radius.
.. index:: clipLine
clipLine
------------
Clips the line against the image rectangle.
.. ocv:function:: bool clipLine(Size imgSize, Point& pt1, Point& pt2)
.. ocv:function:: bool clipLine(Rect imgRect, Point& pt1, Point& pt2)
Clips the line against the image rectangle.
.. ocv:pyfunction:: cv2.clipLine(imgRect, pt1, pt2) -> retval, pt1, pt2
.. ocv:cfunction:: int cvClipLine( CvSize imgSize, CvPoint* pt1, CvPoint* pt2 )
.. ocv:pyoldfunction:: cv.ClipLine(imgSize, pt1, pt2) -> (clippedPt1, clippedPt2)
:param imgSize: Image size. The image rectangle is ``Rect(0, 0, imgSize.width, imgSize.height)`` .
:param imgSize: Image rectangle.?? why do you list the same para twice??
:param pt1: First line point.
@@ -71,15 +77,22 @@ clipLine
The functions ``clipLine`` calculate a part of the line segment that is entirely within the specified rectangle.
They return ``false`` if the line segment is completely outside the rectangle. Otherwise, they return ``true`` .
.. index:: ellipse
ellipse
-----------
Draws a simple or thick elliptic arc or fills an ellipse sector.
.. ocv:function:: void ellipse(Mat& img, Point center, Size axes, double angle, double startAngle, double endAngle, const Scalar& color, int thickness=1, int lineType=8, int shift=0)
.. ocv:function:: void ellipse(Mat& img, const RotatedRect& box, const Scalar& color, int thickness=1, int lineType=8)
Draws a simple or thick elliptic arc or fills an ellipse sector.
.. ocv:pyfunction:: cv2.ellipse(img, center, axes, angle, startAngle, endAngle, color[, thickness[, lineType[, shift]]]) -> None
.. ocv:pyfunction:: cv2.ellipse(img, box, color[, thickness[, lineType]]) -> None
.. ocv:cfunction:: void cvEllipse( CvArr* img, CvPoint center, CvSize axes, double angle, double startAngle, double endAngle, CvScalar color, int thickness=1, int lineType=8, int shift=0 )
.. ocv:pyoldfunction:: cv.Ellipse(img, center, axes, angle, startAngle, endAngle, color, thickness=1, lineType=8, shift=0)-> None
.. ocv:cfunction:: void cvEllipseBox( CvArr* img, CvBox2D box, CvScalar color, int thickness=1, int lineType=8, int shift=0 )
.. ocv:pyoldfunction:: cv.EllipseBox(img, box, color, thickness=1, lineType=8, shift=0)-> None
:param img: Image.
@@ -93,7 +106,7 @@ ellipse
:param endAngle: Ending angle of the elliptic arc in degrees.
:param box: Alternative ellipse representation via :ocv:class:`RotatedRect`. This means that the function draws an ellipse inscribed in the rotated rectangle.
:param box: Alternative ellipse representation via :ocv:class:`RotatedRect` or ``CvBox2D``. This means that the function draws an ellipse inscribed in the rotated rectangle.
:param color: Ellipse color.
@@ -113,13 +126,13 @@ A piecewise-linear curve is used to approximate the elliptic arc boundary. If yo
.. image:: pics/ellipse.png
.. index:: ellipse2Poly
ellipse2Poly
----------------
Approximates an elliptic arc with a polyline.
.. ocv:function:: void ellipse2Poly( Point center, Size axes, int angle, int startAngle, int endAngle, int delta, vector<Point>& pts )
Approximates an elliptic arc with a polyline.
.. ocv:pyfunction:: cv2.ellipse2Poly(center, axes, angle, arcStart, arcEnd, delta) -> pts
:param center: Center of the arc.
@@ -138,13 +151,18 @@ ellipse2Poly
The function ``ellipse2Poly`` computes the vertices of a polyline that approximates the specified elliptic arc. It is used by
:ocv:func:`ellipse` .
.. index:: fillConvexPoly
fillConvexPoly
------------------
Fills a convex polygon.
.. ocv:function:: void fillConvexPoly(Mat& img, const Point* pts, int npts, const Scalar& color, int lineType=8, int shift=0)
Fills a convex polygon.
.. ocv:pyfunction:: cv2.fillConvexPoly(img, points, color[, lineType[, shift]]) -> None
.. ocv:cfunction:: void cvFillConvexPoly( CvArr* img, CvPoint* pts, int npts, CvScalar color, int lineType=8, int shift=0 )
.. ocv:pyoldfunction:: cv.FillConvexPoly(img, pn, color, lineType=8, shift=0)-> None
:param img: Image.
@@ -162,13 +180,18 @@ The function ``fillConvexPoly`` draws a filled convex polygon.
This function is much faster than the function ``fillPoly`` . It can fill not only convex polygons but any monotonic polygon without self-intersections,
that is, a polygon whose contour intersects every horizontal line (scan line) twice at the most (though, its top-most and/or the bottom edge could be horizontal).
.. index:: fillPoly
fillPoly
------------
Fills the area bounded by one or more polygons.
.. ocv:function:: void fillPoly(Mat& img, const Point** pts, const int* npts, int ncontours, const Scalar& color, int lineType=8, int shift=0, Point offset=Point() )
Fills the area bounded by one or more polygons.
.. ocv:pyfunction:: cv2.fillPoly(img, pts, color[, lineType[, shift[, offset]]]) -> None
.. ocv:cfunction:: void cvFillPoly( CvArr* img, CvPoint** pts, int* npts, int contours, CvScalar color, int lineType=8, int shift=0 )
.. ocv:pyoldfunction:: cv.FillPoly(img, polys, color, lineType=8, shift=0)-> None
:param img: Image.
@@ -187,22 +210,27 @@ fillPoly
The function ``fillPoly`` fills an area bounded by several polygonal contours. The function can fill complex areas, for example,
areas with holes, contours with self-intersections (some of thier parts), and so forth.
.. index:: getTextSize
getTextSize
---------------
Calculates the width and height of a text string.
.. ocv:function:: Size getTextSize(const string& text, int fontFace, double fontScale, int thickness, int* baseLine)
Calculates the width and height of a text string.
.. ocv:pyfunction:: cv2.getTextSize(text, fontFace, fontScale, thickness) -> retval, baseLine
.. ocv:cfunction:: void cvGetTextSize( const char* textString, const CvFont* font, CvSize* textSize, int* baseline )
.. ocv:pyoldfunction:: cv.GetTextSize(textString, font)-> (textSize, baseline)
:param text: Input text string.
:param fontFace: Font to use. See the :ocv:func:`putText` for details.
:param fontScale: Font scale. See the :ocv:func:`putText` for details.
:param thickness: Thickness of lines used to render the text. See :ocv:func:`putText` for details.
:param baseLine: Output parameter - y-coordinate of the baseline relative to the bottom-most text point.
The function ``getTextSize`` calculates and returns the size of a box that contains the specified text.
@@ -238,13 +266,66 @@ That is, the following code renders some text, the tight box surrounding it, and
putText(img, text, textOrg, fontFace, fontScale,
Scalar::all(255), thickness, 8);
.. index:: line
InitFont
--------
Initializes font structure (OpenCV 1.x API).
.. cfunction:: void cvInitFont( CvFont* font, int fontFace, double hscale, double vscale, double shear=0, int thickness=1, int lineType=8 )
:param font: Pointer to the font structure initialized by the function
:param fontFace: Font name identifier. Only a subset of Hershey fonts http://sources.isc.org/utils/misc/hershey-font.txt are supported now:
* **CV_FONT_HERSHEY_SIMPLEX** normal size sans-serif font
* **CV_FONT_HERSHEY_PLAIN** small size sans-serif font
* **CV_FONT_HERSHEY_DUPLEX** normal size sans-serif font (more complex than ``CV_FONT_HERSHEY_SIMPLEX`` )
* **CV_FONT_HERSHEY_COMPLEX** normal size serif font
* **CV_FONT_HERSHEY_TRIPLEX** normal size serif font (more complex than ``CV_FONT_HERSHEY_COMPLEX`` )
* **CV_FONT_HERSHEY_COMPLEX_SMALL** smaller version of ``CV_FONT_HERSHEY_COMPLEX``
* **CV_FONT_HERSHEY_SCRIPT_SIMPLEX** hand-writing style font
* **CV_FONT_HERSHEY_SCRIPT_COMPLEX** more complex variant of ``CV_FONT_HERSHEY_SCRIPT_SIMPLEX``
The parameter can be composited from one of the values above and an optional ``CV_FONT_ITALIC`` flag, which indicates italic or oblique font.
:param hscale: Horizontal scale. If equal to ``1.0f`` , the characters have the original width depending on the font type. If equal to ``0.5f`` , the characters are of half the original width.
:param vscale: Vertical scale. If equal to ``1.0f`` , the characters have the original height depending on the font type. If equal to ``0.5f`` , the characters are of half the original height.
:param shear: Approximate tangent of the character slope relative to the vertical line. A zero value means a non-italic font, ``1.0f`` means about a 45 degree slope, etc.
:param thickness: Thickness of the text strokes
:param lineType: Type of the strokes, see :ref:`Line` description
The function initializes the font structure that can be passed to text rendering functions.
.. seealso:: :ocv:cfunc:`PutText`
line
--------
Draws a line segment connecting two points.
.. ocv:function:: void line(Mat& img, Point pt1, Point pt2, const Scalar& color, int thickness=1, int lineType=8, int shift=0)
Draws a line segment connecting two points.
.. ocv:pyfunction:: cv2.line(img, pt1, pt2, color[, thickness[, lineType[, shift]]]) -> None
.. ocv:cfunction:: void cvLine( CvArr* img, CvPoint pt1, CvPoint pt2, CvScalar color, int thickness=1, int lineType=8, int shift=0 )
.. ocv:pyoldfunction:: cv.Line(img, pt1, pt2, color, thickness=1, lineType=8, shift=0)-> None
:param img: Image.
@@ -269,13 +350,10 @@ line
The function ``line`` draws the line segment between ``pt1`` and ``pt2`` points in the image. The line is clipped by the image boundaries. For non-antialiased lines with integer coordinates, the 8-connected or 4-connected Bresenham algorithm is used. Thick lines are drawn with rounding endings.
Antialiased lines are drawn using Gaussian filtering. To specify the line color, you may use the macro ``CV_RGB(r, g, b)`` .
.. index:: LineIterator
.. _LineIterator:
LineIterator
------------
.. c:type:: LineIterator
.. ocv:class:: LineIterator
Class for iterating pixels on a raster line. ::
@@ -315,15 +393,20 @@ The number of pixels along the line is stored in ``LineIterator::count`` . ::
for(int i = 0; i < it.count; i++, ++it)
buf[i] = *(const Vec3b)*it;
.. index:: rectangle
rectangle
-------------
Draws a simple, thick, or filled up-right rectangle.
.. ocv:function:: void rectangle(Mat& img, Point pt1, Point pt2, const Scalar& color, int thickness=1, int lineType=8, int shift=0)
.. ocv:function:: void rectangle(Mat& img, Rect r, const Scalar& color, int thickness=1, int lineType=8, int shift=0)
Draws a simple, thick, or filled up-right rectangle.
.. ocv:pyfunction:: cv2.rectangle(img, pt1, pt2, color[, thickness[, lineType[, shift]]]) -> None
.. ocv:cfunction:: void cvRectangle( CvArr* img, CvPoint pt1, CvPoint pt2, CvScalar color, int thickness=1, int lineType=8, int shift=0 )
.. ocv:pyoldfunction:: cv.Rectangle(img, pt1, pt2, color, thickness=1, lineType=8, shift=0)-> None
:param img: Image.
@@ -343,13 +426,19 @@ rectangle
The function ``rectangle`` draws a rectangle outline or a filled rectangle whose two opposite corners are ``pt1`` and ``pt2``, or ``r.tl()`` and ``r.br()-Point(1,1)``.
.. index:: polylines
polylines
-------------
.. ocv:function:: void polylines(Mat& img, const Point** pts, const int* npts, int ncontours, bool isClosed, const Scalar& color, int thickness=1, int lineType=8, int shift=0 )
Draws several polygonal curves.
Draws several polygonal curves.
.. ocv:function:: void polylines(Mat& img, const Point** pts, const int* npts, int ncontours, bool isClosed, const Scalar& color, int thickness=1, int lineType=8, int shift=0 )
.. ocv:pyfunction:: cv2.polylines(img, pts, isClosed, color[, thickness[, lineType[, shift]]]) -> None
.. ocv:cfunction:: void cvPolyLine( CvArr* img, CvPoint** pts, int* npts, int contours, int isClosed, CvScalar color, int thickness=1, int lineType=8, int shift=0 )
.. ocv:pyoldfunction:: cv.PolyLine(img, polys, isClosed, color, thickness=1, lineType=8, shift=0)-> None
:param img: Image.
@@ -371,13 +460,18 @@ polylines
The function ``polylines`` draws one or more polygonal curves.
.. index:: putText
putText
-----------
Draws a text string.
.. ocv:function:: void putText( Mat& img, const string& text, Point org, int fontFace, double fontScale, Scalar color, int thickness=1, int lineType=8, bool bottomLeftOrigin=false )
Draws a text string.
.. ocv:pyfunction:: cv2.putText(img, text, org, fontFace, fontScale, color[, thickness[, linetype[, bottomLeftOrigin]]]) -> None
.. ocv:cfunction:: void cvPutText( CvArr* img, const char* text, CvPoint org, const CvFont* font, CvScalar color )
.. ocv:pyoldfunction:: cv.PutText(img, text, org, font, color)-> None
:param img: Image.
@@ -385,6 +479,8 @@ putText
:param org: Bottom-left corner of the text string in the image.
:param font: ``CvFont`` structure initialized using :ocv:cfunc:`InitFont`.
:param fontFace: Font type. One of ``FONT_HERSHEY_SIMPLEX``, ``FONT_HERSHEY_PLAIN``, ``FONT_HERSHEY_DUPLEX``, ``FONT_HERSHEY_COMPLEX``, ``FONT_HERSHEY_TRIPLEX``, ``FONT_HERSHEY_COMPLEX_SMALL``, ``FONT_HERSHEY_SCRIPT_SIMPLEX``, or ``FONT_HERSHEY_SCRIPT_COMPLEX``,
where each of the font ID's can be combined with ``FONT_HERSHEY_ITALIC`` to get the slanted letters.
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,909 @@
XML/YAML Persistence (C API)
==============================
The section describes the OpenCV 1.x API for reading and writing data structures to/from XML or YAML files. It is now recommended to use the new C++ interface for reading and writing data.
.. highlight:: c
CvFileStorage
-------------
.. ocv:struct:: CvFileStorage
The structure ``CvFileStorage`` is a "black box" representation of the file storage associated with a file on disk. Several functions that are described below take ``CvFileStorage*`` as inputs and allow the user to save or to load hierarchical collections that consist of scalar values, standard CXCore objects (such as matrices, sequences, graphs), and user-defined objects.
OpenCV can read and write data in XML (http://www.w3c.org/XML) or YAML
(http://www.yaml.org) formats. Below is an example of 3x3 floating-point identity matrix ``A``, stored in XML and YAML files using CXCore functions:
XML: ::
<?xml version="1.0">
<opencv_storage>
<A type_id="opencv-matrix">
<rows>3</rows>
<cols>3</cols>
<dt>f</dt>
<data>1. 0. 0. 0. 1. 0. 0. 0. 1.</data>
</A>
</opencv_storage>
YAML: ::
%YAML:1.0
A: !!opencv-matrix
rows: 3
cols: 3
dt: f
data: [ 1., 0., 0., 0., 1., 0., 0., 0., 1.]
As it can be seen from the examples, XML uses nested tags to represent
hierarchy, while YAML uses indentation for that purpose (similar
to the Python programming language).
The same functions can read and write data in both formats;
the particular format is determined by the extension of the opened file, ".xml" for XML files and ".yml" or ".yaml" for YAML.
CvFileNode
----------
.. ocv:struct:: CvFileNode
File storage node. When XML/YAML file is read, it is first parsed and stored in the memory as a hierarchical collection of nodes. Each node can be a "leaf", that is, contain a single number or a string, or be a collection of other nodes. Collections are also referenced to as "structures" in the data writing functions. There can be named collections (mappings), where each element has a name and is accessed by a name, and ordered collections (sequences), where elements do not have names, but rather accessed by index.
.. ocv:member:: int tag
type of the file node:
* CV_NODE_NONE - empty node
* CV_NODE_INT - an integer
* CV_NODE_REAL - a floating-point number
* CV_NODE_STR - text string
* CV_NODE_SEQ - a sequence
* CV_NODE_MAP - a mapping
type of the node can be retrieved using ``CV_NODE_TYPE(node->tag)`` macro.
.. ocv:member:: CvTypeInfo* info
optional pointer to the user type information. If you look at the matrix representation in XML and YAML, shown above, you may notice ``type_id="opencv-matrix"`` or ``!!opencv-matrix`` strings. They are used to specify that the certain element of a file is a representation of a data structure of certain type ("opencv-matrix" corresponds to :ocv:struct:`CvMat`). When a file is parsed, such type identifiers are passed to :ocv:cfunc:`FindType` to find type information and the pointer to it is stored in the file node. See :ocv:struct:`CvTypeInfo` for more details.
.. ocv:member:: union data
the node data, declared as: ::
union
{
double f; /* scalar floating-point number */
int i; /* scalar integer number */
CvString str; /* text string */
CvSeq* seq; /* sequence (ordered collection of file nodes) */
struct CvMap* map; /* map (collection of named file nodes) */
} data;
..
Primitive nodes are read using :ocv:cfunc:`ReadInt`, :ocv:cfunc:`ReadReal` and :ocv:cfunc:`ReadString`. Sequences are read by iterating through ``node->data.seq`` (see "Dynamic Data Structures" section). Mappings are read using :ocv:cfunc:`GetFileNodeByName`. Nodes with the specified type (so that ``node->info != NULL``) can be read using :ocv:cfunc:`Read`.
CvAttrList
----------
.. ocv:struct:: CvAttrList
List of attributes. ::
typedef struct CvAttrList
{
const char** attr; /* NULL-terminated array of (attribute_name,attribute_value) pairs */
struct CvAttrList* next; /* pointer to next chunk of the attributes list */
}
CvAttrList;
/* initializes CvAttrList structure */
inline CvAttrList cvAttrList( const char** attr=NULL, CvAttrList* next=NULL );
/* returns attribute value or 0 (NULL) if there is no such attribute */
const char* cvAttrValue( const CvAttrList* attr, const char* attr_name );
..
In the current implementation, attributes are used to pass extra parameters when writing user objects (see
:ocv:cfunc:`Write`). XML attributes inside tags are not supported, aside from the object type specification (``type_id`` attribute).
CvTypeInfo
----------
.. ocv:struct:: CvTypeInfo
Type information. ::
typedef int (CV_CDECL *CvIsInstanceFunc)( const void* structPtr );
typedef void (CV_CDECL *CvReleaseFunc)( void** structDblPtr );
typedef void* (CV_CDECL *CvReadFunc)( CvFileStorage* storage, CvFileNode* node );
typedef void (CV_CDECL *CvWriteFunc)( CvFileStorage* storage,
const char* name,
const void* structPtr,
CvAttrList attributes );
typedef void* (CV_CDECL *CvCloneFunc)( const void* structPtr );
typedef struct CvTypeInfo
{
int flags; /* not used */
int header_size; /* sizeof(CvTypeInfo) */
struct CvTypeInfo* prev; /* previous registered type in the list */
struct CvTypeInfo* next; /* next registered type in the list */
const char* type_name; /* type name, written to file storage */
/* methods */
CvIsInstanceFunc is_instance; /* checks if the passed object belongs to the type */
CvReleaseFunc release; /* releases object (memory etc.) */
CvReadFunc read; /* reads object from file storage */
CvWriteFunc write; /* writes object to file storage */
CvCloneFunc clone; /* creates a copy of the object */
}
CvTypeInfo;
..
The structure contains information about one of the standard or user-defined types. Instances of the type may or may not contain a pointer to the corresponding :ocv:struct:`CvTypeInfo` structure. In any case, there is a way to find the type info structure for a given object using the :ocv:cfunc:`TypeOf` function. Aternatively, type info can be found by type name using :ocv:cfunc:`FindType`, which is used when an object is read from file storage. The user can register a new type with :ocv:cfunc:`RegisterType`
that adds the type information structure into the beginning of the type list. Thus, it is possible to create specialized types from generic standard types and override the basic methods.
Clone
-----
Makes a clone of an object.
.. ocv:cfunction:: void* cvClone( const void* structPtr )
:param structPtr: The object to clone
The function finds the type of a given object and calls ``clone`` with the passed object. Of course, if you know the object type, for example, ``structPtr`` is ``CvMat*``, it is faster to call the specific function, like :ocv:cfunc:`CloneMat`.
EndWriteStruct
--------------
Finishes writing to a file node collection.
.. ocv:cfunction:: void cvEndWriteStruct(CvFileStorage* fs)
:param fs: File storage
.. seealso:: :ocv:cfunc:`StartWriteStruct`.
FindType
--------
Finds a type by its name.
.. ocv:cfunction:: CvTypeInfo* cvFindType(const char* typeName)
:param typeName: Type name
The function finds a registered type by its name. It returns NULL if there is no type with the specified name.
FirstType
---------
Returns the beginning of a type list.
.. ocv:cfunction:: CvTypeInfo* cvFirstType(void)
The function returns the first type in the list of registered types. Navigation through the list can be done via the ``prev`` and ``next`` fields of the :ocv:struct:`CvTypeInfo` structure.
GetFileNode
-----------
Finds a node in a map or file storage.
.. ocv:cfunction:: CvFileNode* cvGetFileNode( CvFileStorage* fs, CvFileNode* map, const CvStringHashNode* key, int createMissing=0 )
:param fs: File storage
:param map: The parent map. If it is NULL, the function searches a top-level node. If both ``map`` and ``key`` are NULLs, the function returns the root file node - a map that contains top-level nodes.
:param key: Unique pointer to the node name, retrieved with :ocv:cfunc:`GetHashedKey`
:param createMissing: Flag that specifies whether an absent node should be added to the map
The function finds a file node. It is a faster version of :ocv:cfunc:`GetFileNodeByName`
(see :ocv:cfunc:`GetHashedKey` discussion). Also, the function can insert a new node, if it is not in the map yet.
GetFileNodeByName
-----------------
Finds a node in a map or file storage.
.. ocv:cfunction:: CvFileNode* cvGetFileNodeByName( const CvFileStorage* fs, const CvFileNode* map, const char* name)
:param fs: File storage
:param map: The parent map. If it is NULL, the function searches in all the top-level nodes (streams), starting with the first one.
:param name: The file node name
The function finds a file node by ``name``. The node is searched either in ``map`` or, if the pointer is NULL, among the top-level file storage nodes. Using this function for maps and :ocv:cfunc:`GetSeqElem`
(or sequence reader) for sequences, it is possible to nagivate through the file storage. To speed up multiple queries for a certain key (e.g., in the case of an array of structures) one may use a combination of :ocv:cfunc:`GetHashedKey` and :ocv:cfunc:`GetFileNode`.
GetFileNodeName
---------------
Returns the name of a file node.
.. ocv:cfunction:: const char* cvGetFileNodeName( const CvFileNode* node )
:param node: File node
The function returns the name of a file node or NULL, if the file node does not have a name or if ``node`` is ``NULL``.
GetHashedKey
------------
Returns a unique pointer for a given name.
.. ocv:cfunction:: CvStringHashNode* cvGetHashedKey( CvFileStorage* fs, const char* name, int len=-1, int createMissing=0 )
:param fs: File storage
:param name: Literal node name
:param len: Length of the name (if it is known apriori), or -1 if it needs to be calculated
:param createMissing: Flag that specifies, whether an absent key should be added into the hash table
The function returns a unique pointer for each particular file node name. This pointer can be then passed to the :ocv:cfunc:`GetFileNode` function that is faster than :ocv:cfunc:`GetFileNodeByName`
because it compares text strings by comparing pointers rather than the strings' content.
Consider the following example where an array of points is encoded as a sequence of 2-entry maps: ::
points:
- { x: 10, y: 10 }
- { x: 20, y: 20 }
- { x: 30, y: 30 }
# ...
..
Then, it is possible to get hashed "x" and "y" pointers to speed up decoding of the points. ::
#include "cxcore.h"
int main( int argc, char** argv )
{
CvFileStorage* fs = cvOpenFileStorage( "points.yml", 0, CV_STORAGE_READ );
CvStringHashNode* x_key = cvGetHashedNode( fs, "x", -1, 1 );
CvStringHashNode* y_key = cvGetHashedNode( fs, "y", -1, 1 );
CvFileNode* points = cvGetFileNodeByName( fs, 0, "points" );
if( CV_NODE_IS_SEQ(points->tag) )
{
CvSeq* seq = points->data.seq;
int i, total = seq->total;
CvSeqReader reader;
cvStartReadSeq( seq, &reader, 0 );
for( i = 0; i < total; i++ )
{
CvFileNode* pt = (CvFileNode*)reader.ptr;
#if 1 /* faster variant */
CvFileNode* xnode = cvGetFileNode( fs, pt, x_key, 0 );
CvFileNode* ynode = cvGetFileNode( fs, pt, y_key, 0 );
assert( xnode && CV_NODE_IS_INT(xnode->tag) &&
ynode && CV_NODE_IS_INT(ynode->tag));
int x = xnode->data.i; // or x = cvReadInt( xnode, 0 );
int y = ynode->data.i; // or y = cvReadInt( ynode, 0 );
#elif 1 /* slower variant; does not use x_key & y_key */
CvFileNode* xnode = cvGetFileNodeByName( fs, pt, "x" );
CvFileNode* ynode = cvGetFileNodeByName( fs, pt, "y" );
assert( xnode && CV_NODE_IS_INT(xnode->tag) &&
ynode && CV_NODE_IS_INT(ynode->tag));
int x = xnode->data.i; // or x = cvReadInt( xnode, 0 );
int y = ynode->data.i; // or y = cvReadInt( ynode, 0 );
#else /* the slowest yet the easiest to use variant */
int x = cvReadIntByName( fs, pt, "x", 0 /* default value */ );
int y = cvReadIntByName( fs, pt, "y", 0 /* default value */ );
#endif
CV_NEXT_SEQ_ELEM( seq->elem_size, reader );
printf("
}
}
cvReleaseFileStorage( &fs );
return 0;
}
..
Please note that whatever method of accessing a map you are using, it is
still much slower than using plain sequences; for example, in the above
example, it is more efficient to encode the points as pairs of integers
in a single numeric sequence.
GetRootFileNode
---------------
Retrieves one of the top-level nodes of the file storage.
.. ocv:cfunction:: CvFileNode* cvGetRootFileNode( const CvFileStorage* fs, int stream_index=0 )
:param fs: File storage
:param stream_index: Zero-based index of the stream. See :ocv:cfunc:`StartNextStream` . In most cases, there is only one stream in the file; however, there can be several.
The function returns one of the top-level file nodes. The top-level nodes do not have a name, they correspond to the streams that are stored one after another in the file storage. If the index is out of range, the function returns a NULL pointer, so all the top-level nodes can be iterated by subsequent calls to the function with ``stream_index=0,1,...``, until the NULL pointer is returned. This function
can be used as a base for recursive traversal of the file storage.
Load
----
Loads an object from a file.
.. ocv:cfunction:: void* cvLoad( const char* filename, CvMemStorage* storage=NULL, const char* name=NULL, const char** realName=NULL )
.. ocv:pyoldfunction:: cv.Load(filename, storage=None, name=None)-> generic
:param filename: File name
:param storage: Memory storage for dynamic structures, such as :ocv:struct:`CvSeq` or :ocv:struct:`CvGraph` . It is not used for matrices or images.
:param name: Optional object name. If it is NULL, the first top-level object in the storage will be loaded.
:param realName: Optional output parameter that will contain the name of the loaded object (useful if ``name=NULL`` )
The function loads an object from a file. It basically reads the specified file, find the first top-level node and calls :ocv:cfunc:`Read` for that node. If the file node does not have type information or the type information can not be found by the type name, the function returns NULL. After the object is loaded, the file storage is closed and all the temporary buffers are deleted. Thus, to load a dynamic structure, such as a sequence, contour, or graph, one should pass a valid memory storage destination to the function.
OpenFileStorage
---------------
Opens file storage for reading or writing data.
.. ocv:cfunction:: CvFileStorage* cvOpenFileStorage( const char* filename, CvMemStorage* memstorage, int flags)
:param filename: Name of the file associated with the storage
:param memstorage: Memory storage used for temporary data and for
storing dynamic structures, such as :ocv:struct:`CvSeq` or :ocv:struct:`CvGraph` .
If it is NULL, a temporary memory storage is created and used.
:param flags: Can be one of the following:
* **CV_STORAGE_READ** the storage is open for reading
* **CV_STORAGE_WRITE** the storage is open for writing
The function opens file storage for reading or writing data. In the latter case, a new file is created or an existing file is rewritten. The type of the read or written file is determined by the filename extension: ``.xml`` for ``XML`` and ``.yml`` or ``.yaml`` for ``YAML``. The function returns a pointer to the :ocv:struct:`CvFileStorage` structure.
Read
----
Decodes an object and returns a pointer to it.
.. ocv:cfunction:: void* cvRead( CvFileStorage* fs, CvFileNode* node, CvAttrList* attributes=NULL )
:param fs: File storage
:param node: The root object node
:param attributes: Unused parameter
The function decodes a user object (creates an object in a native representation from the file storage subtree) and returns it. The object to be decoded must be an instance of a registered type that supports the ``read`` method (see :ocv:struct:`CvTypeInfo`). The type of the object is determined by the type name that is encoded in the file. If the object is a dynamic structure, it is created either in memory storage and passed to :ocv:cfunc:`OpenFileStorage` or, if a NULL pointer was passed, in temporary
memory storage, which is released when :ocv:cfunc:`ReleaseFileStorage` is called. Otherwise, if the object is not a dynamic structure, it is created in a heap and should be released with a specialized function or by using the generic :ocv:cfunc:`Release`.
ReadByName
----------
Finds an object by name and decodes it.
.. ocv:cfunction:: void* cvReadByName( CvFileStorage* fs, const CvFileNode* map, const char* name, CvAttrList* attributes=NULL )
:param fs: File storage
:param map: The parent map. If it is NULL, the function searches a top-level node.
:param name: The node name
:param attributes: Unused parameter
The function is a simple superposition of :ocv:cfunc:`GetFileNodeByName` and :ocv:cfunc:`Read`.
ReadInt
-------
Retrieves an integer value from a file node.
.. ocv:cfunction:: int cvReadInt( const CvFileNode* node, int defaultValue=0 )
:param node: File node
:param defaultValue: The value that is returned if ``node`` is NULL
The function returns an integer that is represented by the file node. If the file node is NULL, the
``defaultValue`` is returned (thus, it is convenient to call the function right after :ocv:cfunc:`GetFileNode` without checking for a NULL pointer). If the file node has type ``CV_NODE_INT``, then ``node->data.i`` is returned. If the file node has type ``CV_NODE_REAL``, then ``node->data.f``
is converted to an integer and returned. Otherwise the error is reported.
ReadIntByName
-------------
Finds a file node and returns its value.
.. ocv:cfunction:: int cvReadIntByName( const CvFileStorage* fs, const CvFileNode* map, const char* name, int defaultValue=0 )
:param fs: File storage
:param map: The parent map. If it is NULL, the function searches a top-level node.
:param name: The node name
:param defaultValue: The value that is returned if the file node is not found
The function is a simple superposition of :ocv:cfunc:`GetFileNodeByName` and :ocv:cfunc:`ReadInt`.
ReadRawData
-----------
Reads multiple numbers.
.. ocv:cfunction:: void cvReadRawData( const CvFileStorage* fs, const CvFileNode* src, void* dst, const char* dt)
:param fs: File storage
:param src: The file node (a sequence) to read numbers from
:param dst: Pointer to the destination array
:param dt: Specification of each array element. It has the same format as in :ocv:cfunc:`WriteRawData` .
The function reads elements from a file node that represents a sequence of scalars.
ReadRawDataSlice
----------------
Initializes file node sequence reader.
.. ocv:cfunction:: void cvReadRawDataSlice( const CvFileStorage* fs, CvSeqReader* reader, int count, void* dst, const char* dt )
:param fs: File storage
:param reader: The sequence reader. Initialize it with :ocv:cfunc:`StartReadRawData` .
:param count: The number of elements to read
:param dst: Pointer to the destination array
:param dt: Specification of each array element. It has the same format as in :ocv:cfunc:`WriteRawData` .
The function reads one or more elements from the file node, representing a sequence, to a user-specified array. The total number of read sequence elements is a product of ``total``
and the number of components in each array element. For example, if ``dt=2if``, the function will read ``total*3`` sequence elements. As with any sequence, some parts of the file node sequence can be skipped or read repeatedly by repositioning the reader using :ocv:cfunc:`SetSeqReaderPos`.
ReadReal
--------
Retrieves a floating-point value from a file node.
.. ocv:cfunction:: double cvReadReal( const CvFileNode* node, double defaultValue=0. )
:param node: File node
:param defaultValue: The value that is returned if ``node`` is NULL
The function returns a floating-point value
that is represented by the file node. If the file node is NULL, the
``defaultValue``
is returned (thus, it is convenient to call
the function right after
:ocv:cfunc:`GetFileNode`
without checking for a NULL
pointer). If the file node has type
``CV_NODE_REAL``
,
then
``node->data.f``
is returned. If the file node has type
``CV_NODE_INT``
, then
``node-:math:`>`data.f``
is converted to floating-point
and returned. Otherwise the result is not determined.
ReadRealByName
--------------
Finds a file node and returns its value.
.. ocv:cfunction:: double cvReadRealByName( const CvFileStorage* fs, const CvFileNode* map, const char* name, double defaultValue=0.)
:param fs: File storage
:param map: The parent map. If it is NULL, the function searches a top-level node.
:param name: The node name
:param defaultValue: The value that is returned if the file node is not found
The function is a simple superposition of
:ocv:cfunc:`GetFileNodeByName`
and
:ocv:cfunc:`ReadReal`
.
ReadString
----------
Retrieves a text string from a file node.
.. ocv:cfunction:: const char* cvReadString( const CvFileNode* node, const char* defaultValue=NULL )
:param node: File node
:param defaultValue: The value that is returned if ``node`` is NULL
The function returns a text string that is represented
by the file node. If the file node is NULL, the
``defaultValue``
is returned (thus, it is convenient to call the function right after
:ocv:cfunc:`GetFileNode`
without checking for a NULL pointer). If
the file node has type
``CV_NODE_STR``
, then
``node-:math:`>`data.str.ptr``
is returned. Otherwise the result is not determined.
ReadStringByName
----------------
Finds a file node by its name and returns its value.
.. ocv:cfunction:: const char* cvReadStringByName( const CvFileStorage* fs, const CvFileNode* map, const char* name, const char* defaultValue=NULL )
:param fs: File storage
:param map: The parent map. If it is NULL, the function searches a top-level node.
:param name: The node name
:param defaultValue: The value that is returned if the file node is not found
The function is a simple superposition of
:ocv:cfunc:`GetFileNodeByName`
and
:ocv:cfunc:`ReadString`
.
RegisterType
------------
Registers a new type.
.. ocv:cfunction:: void cvRegisterType(const CvTypeInfo* info)
:param info: Type info structure
The function registers a new type, which is
described by
``info``
. The function creates a copy of the structure,
so the user should delete it after calling the function.
Release
-------
Releases an object.
.. ocv:cfunction:: void cvRelease( void** structPtr )
:param structPtr: Double pointer to the object
The function finds the type of a given object and calls
``release``
with the double pointer.
ReleaseFileStorage
------------------
Releases file storage.
.. ocv:cfunction:: void cvReleaseFileStorage(CvFileStorage** fs)
:param fs: Double pointer to the released file storage
The function closes the file associated with the storage and releases all the temporary structures. It must be called after all I/O operations with the storage are finished.
Save
----
Saves an object to a file.
.. ocv:cfunction:: void cvSave( const char* filename, const void* structPtr, const char* name=NULL, const char* comment=NULL, CvAttrList attributes=cvAttrList())
.. ocv:pyoldfunction:: cv.Save(filename, structPtr, name=None, comment=None)-> None
:param filename: File name
:param structPtr: Object to save
:param name: Optional object name. If it is NULL, the name will be formed from ``filename`` .
:param comment: Optional comment to put in the beginning of the file
:param attributes: Optional attributes passed to :ocv:cfunc:`Write`
The function saves an object to a file. It provides a simple interface to
:ocv:cfunc:`Write`
.
StartNextStream
---------------
Starts the next stream.
.. ocv:cfunction:: void cvStartNextStream(CvFileStorage* fs)
:param fs: File storage
The function finishes the currently written stream and starts the next stream. In the case of XML the file with multiple streams looks like this: ::
<opencv_storage>
<!-- stream #1 data -->
</opencv_storage>
<opencv_storage>
<!-- stream #2 data -->
</opencv_storage>
...
The a YAML file will look like this:
%YAML:1.0
# stream #1 data
...
---
# stream #2 data
This is useful for concatenating files or for resuming the writing process.
StartReadRawData
----------------
Initializes the file node sequence reader.
.. ocv:cfunction:: void cvStartReadRawData( const CvFileStorage* fs, const CvFileNode* src, CvSeqReader* reader)
:param fs: File storage
:param src: The file node (a sequence) to read numbers from
:param reader: Pointer to the sequence reader
The function initializes the sequence reader to read data from a file node. The initialized reader can be then passed to :ocv:cfunc:`ReadRawDataSlice`.
StartWriteStruct
----------------
Starts writing a new structure.
.. ocv:cfunction:: void cvStartWriteStruct( CvFileStorage* fs, const char* name, int struct_flags, const char* typeName=NULL, CvAttrList attributes=cvAttrList())
:param fs: File storage
:param name: Name of the written structure. The structure can be accessed by this name when the storage is read.
:param struct_flags: A combination one of the following values:
* **CV_NODE_SEQ** the written structure is a sequence (see discussion of :ocv:struct:`CvFileStorage` ), that is, its elements do not have a name.
* **CV_NODE_MAP** the written structure is a map (see discussion of :ocv:struct:`CvFileStorage` ), that is, all its elements have names.
One and only one of the two above flags must be specified
:param CV_NODE_FLOW: the optional flag that makes sense only for YAML streams. It means that the structure is written as a flow (not as a block), which is more compact. It is recommended to use this flag for structures or arrays whose elements are all scalars.
:param typeName: Optional parameter - the object type name. In
case of XML it is written as a ``type_id`` attribute of the
structure opening tag. In the case of YAML it is written after a colon
following the structure name (see the example in :ocv:struct:`CvFileStorage`
description). Mainly it is used with user objects. When the storage
is read, the encoded type name is used to determine the object type
(see :ocv:struct:`CvTypeInfo` and :ocv:cfunc:`FindTypeInfo` ).
:param attributes: This parameter is not used in the current implementation
The function starts writing a compound structure (collection) that can be a sequence or a map. After all the structure fields, which can be scalars or structures, are written, :ocv:cfunc:`EndWriteStruct` should be called. The function can be used to group some objects or to implement the ``write`` function for a some user object (see :ocv:struct:`CvTypeInfo`).
TypeOf
------
Returns the type of an object.
.. ocv:cfunction:: CvTypeInfo* cvTypeOf( const void* structPtr )
:param structPtr: The object pointer
The function finds the type of a given object. It iterates through the list of registered types and calls the ``is_instance`` function/method for every type info structure with that object until one of them returns non-zero or until the whole list has been traversed. In the latter case, the function returns NULL.
UnregisterType
--------------
Unregisters the type.
.. ocv:cfunction:: void cvUnregisterType( const char* typeName )
:param typeName: Name of an unregistered type
The function unregisters a type with a specified name. If the name is unknown, it is possible to locate the type info by an instance of the type using :ocv:cfunc:`TypeOf` or by iterating the type list, starting from :ocv:cfunc:`FirstType`, and then calling ``cvUnregisterType(info->typeName)``.
Write
-----
Writes an object to file storage.
.. ocv:cfunction:: void cvWrite( CvFileStorage* fs, const char* name, const void* ptr, CvAttrList attributes=cvAttrList() )
:param fs: File storage
:param name: Name of the written object. Should be NULL if and only if the parent structure is a sequence.
:param ptr: Pointer to the object
:param attributes: The attributes of the object. They are specific for each particular type (see the dicsussion below).
The function writes an object to file storage. First, the appropriate type info is found using :ocv:cfunc:`TypeOf`. Then, the ``write`` method associated with the type info is called.
Attributes are used to customize the writing procedure. The standard types support the following attributes (all the ``dt`` attributes have the same format as in :ocv:cfunc:`WriteRawData`):
#.
CvSeq
* **header_dt** description of user fields of the sequence header that follow CvSeq, or CvChain (if the sequence is a Freeman chain) or CvContour (if the sequence is a contour or point sequence)
* **dt** description of the sequence elements.
* **recursive** if the attribute is present and is not equal to "0" or "false", the whole tree of sequences (contours) is stored.
#.
CvGraph
* **header_dt** description of user fields of the graph header that follows CvGraph;
* **vertex_dt** description of user fields of graph vertices
* **edge_dt** description of user fields of graph edges (note that the edge weight is always written, so there is no need to specify it explicitly)
Below is the code that creates the YAML file shown in the
``CvFileStorage``
description:
::
#include "cxcore.h"
int main( int argc, char** argv )
{
CvMat* mat = cvCreateMat( 3, 3, CV_32F );
CvFileStorage* fs = cvOpenFileStorage( "example.yml", 0, CV_STORAGE_WRITE );
cvSetIdentity( mat );
cvWrite( fs, "A", mat, cvAttrList(0,0) );
cvReleaseFileStorage( &fs );
cvReleaseMat( &mat );
return 0;
}
..
WriteComment
------------
Writes a comment.
.. ocv:cfunction:: void cvWriteComment( CvFileStorage* fs, const char* comment, int eolComment)
:param fs: File storage
:param comment: The written comment, single-line or multi-line
:param eolComment: If non-zero, the function tries to put the comment at the end of current line. If the flag is zero, if the comment is multi-line, or if it does not fit at the end of the current line, the comment starts a new line.
The function writes a comment into file storage. The comments are skipped when the storage is read.
WriteFileNode
-------------
Writes a file node to another file storage.
.. ocv:cfunction:: void cvWriteFileNode( CvFileStorage* fs, const char* new_node_name, const CvFileNode* node, int embed )
:param fs: Destination file storage
:param new_file_node: New name of the file node in the destination file storage. To keep the existing name, use :ocv:cfunc:`cvGetFileNodeName`
:param node: The written node
:param embed: If the written node is a collection and this parameter is not zero, no extra level of hiararchy is created. Instead, all the elements of ``node`` are written into the currently written structure. Of course, map elements can only be embedded into another map, and sequence elements can only be embedded into another sequence.
The function writes a copy of a file node to file storage. Possible applications of the function are merging several file storages into one and conversion between XML and YAML formats.
WriteInt
--------
Writes an integer value.
.. ocv:cfunction:: void cvWriteInt( CvFileStorage* fs, const char* name, int value)
:param fs: File storage
:param name: Name of the written value. Should be NULL if and only if the parent structure is a sequence.
:param value: The written value
The function writes a single integer value (with or without a name) to the file storage.
WriteRawData
------------
Writes multiple numbers.
.. ocv:cfunction:: void cvWriteRawData( CvFileStorage* fs, const void* src, int len, const char* dt )
:param fs: File storage
:param src: Pointer to the written array
:param len: Number of the array elements to write
:param dt: Specification of each array element that has the following format ``([count]{'u'|'c'|'w'|'s'|'i'|'f'|'d'})...``
where the characters correspond to fundamental C types:
* **u** 8-bit unsigned number
* **c** 8-bit signed number
* **w** 16-bit unsigned number
* **s** 16-bit signed number
* **i** 32-bit signed number
* **f** single precision floating-point number
* **d** double precision floating-point number
* **r** pointer, 32 lower bits of which are written as a signed integer. The type can be used to store structures with links between the elements. ``count`` is the optional counter of values of a given type. For
example, ``2if`` means that each array element is a structure
of 2 integers, followed by a single-precision floating-point number. The
equivalent notations of the above specification are ' ``iif`` ',
' ``2i1f`` ' and so forth. Other examples: ``u`` means that the
array consists of bytes, and ``2d`` means the array consists of pairs
of doubles.
The function writes an array, whose elements consist
of single or multiple numbers. The function call can be replaced with
a loop containing a few
:ocv:cfunc:`WriteInt`
and
:ocv:cfunc:`WriteReal`
calls, but
a single call is more efficient. Note that because none of the elements
have a name, they should be written to a sequence rather than a map.
WriteReal
---------
Writes a floating-point value.
.. ocv:cfunction:: void cvWriteReal( CvFileStorage* fs, const char* name, double value )
:param fs: File storage
:param name: Name of the written value. Should be NULL if and only if the parent structure is a sequence.
:param value: The written value
The function writes a single floating-point value (with or without a name) to file storage. Special values are encoded as follows: NaN (Not A Number) as .NaN, infinity as +.Inf or -.Inf.
The following example shows how to use the low-level writing functions to store custom structures, such as termination criteria, without registering a new type. ::
void write_termcriteria( CvFileStorage* fs, const char* struct_name,
CvTermCriteria* termcrit )
{
cvStartWriteStruct( fs, struct_name, CV_NODE_MAP, NULL, cvAttrList(0,0));
cvWriteComment( fs, "termination criteria", 1 ); // just a description
if( termcrit->type & CV_TERMCRIT_ITER )
cvWriteInteger( fs, "max_iterations", termcrit->max_iter );
if( termcrit->type & CV_TERMCRIT_EPS )
cvWriteReal( fs, "accuracy", termcrit->epsilon );
cvEndWriteStruct( fs );
}
..
WriteString
-----------
Writes a text string.
.. ocv:cfunction:: void cvWriteString( CvFileStorage* fs, const char* name, const char* str, int quote=0 )
:param fs: File storage
:param name: Name of the written string . Should be NULL if and only if the parent structure is a sequence.
:param str: The written text string
:param quote: If non-zero, the written string is put in quotes, regardless of whether they are required. Otherwise, if the flag is zero, quotes are used only when they are required (e.g. when the string starts with a digit or contains spaces).
The function writes a text string to file storage.
File diff suppressed because it is too large Load Diff
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

@@ -3,13 +3,11 @@ Utility and System Functions and Macros
.. highlight:: cpp
.. index:: alignPtr
alignPtr
------------
.. ocv:function:: template<typename _Tp> _Tp* alignPtr(_Tp* ptr, int n=sizeof(_Tp))
Aligns a pointer to the specified number of bytes.
Aligns a pointer to the specified number of bytes.
.. ocv:function:: template<typename _Tp> _Tp* alignPtr(_Tp* ptr, int n=sizeof(_Tp))
:param ptr: Aligned pointer.
@@ -21,13 +19,13 @@ The function returns the aligned pointer of the same type as the input pointer:
\texttt{(\_Tp*)(((size\_t)ptr + n-1) \& -n)}
.. index:: alignSize
alignSize
-------------
.. ocv:function:: size_t alignSize(size_t sz, int n)
Aligns a buffer size to the specified number of bytes.
Aligns a buffer size to the specified number of bytes.
.. ocv:function:: size_t alignSize(size_t sz, int n)
:param sz: Buffer size to align.
@@ -39,25 +37,25 @@ The function returns the minimum number that is greater or equal to ``sz`` and i
\texttt{(sz + n-1) \& -n}
.. index:: allocate
allocate
------------
.. ocv:function:: template<typename _Tp> _Tp* allocate(size_t n)
Allocates an array of elements.
Allocates an array of elements.
.. ocv:function:: template<typename _Tp> _Tp* allocate(size_t n)
:param n: Number of elements to allocate.
The generic function ``allocate`` allocates a buffer for the specified number of elements. For each element, the default constructor is called.
.. index:: deallocate
deallocate
--------------
.. ocv:function:: template<typename _Tp> void deallocate(_Tp* ptr, size_t n)
Deallocates an array of elements.
Deallocates an array of elements.
.. ocv:function:: template<typename _Tp> void deallocate(_Tp* ptr, size_t n)
:param ptr: Pointer to the deallocated buffer.
@@ -67,34 +65,124 @@ The generic function ``deallocate`` deallocates the buffer allocated with
:ocv:func:`allocate` . The number of elements must match the number passed to
:ocv:func:`allocate` .
.. index:: CV_Assert
fastAtan2
---------
Calculates the angle of a 2D vector in degrees.
.. ocv:function:: float fastAtan2(float y, float x)
.. ocv:pyfunction:: cv2.fastAtan2(y, x) -> retval
.. ocv:cfunction:: float cvFastArctan(float y, float x)
.. ocv:pyoldfunction:: cv.FastArctan(y, x)-> float
:param x: x-coordinate of the vector.
:param y: y-coordinate of the vector.
The function ``fastAtan2`` calculates the full-range angle of an input 2D vector. The angle is measured in degrees and varies from 0 to 360 degrees. The accuracy is about 0.3 degrees.
cubeRoot
--------
Computes the cube root of an argument.
.. ocv:function:: float cubeRoot(float val)
.. ocv:pyfunction:: cv2.cubeRoot(val) -> retval
.. ocv:cfunction:: float cvCbrt(float val)
.. ocv:pyoldfunction:: cv.Cbrt(val)-> float
:param val: A function argument.
The function ``cubeRoot`` computes :math:`\sqrt[3]{\texttt{val}}`. Negative arguments are handled correctly. NaN and Inf are not handled. The accuracy approaches the maximum possible accuracy for single-precision data.
Ceil
-----
Rounds floating-point number to the nearest integer not smaller than the original.
.. ocv:cfunction:: int cvCeil(double value)
.. ocv:pyoldfunction:: cv.Ceil(value) -> int
:param value: floating-point number. If the value is outside of ``INT_MIN`` ... ``INT_MAX`` range, the result is not defined.
The function computes an integer ``i`` such that:
.. math::
i-1 < \texttt{value} \le i
Floor
-----
Rounds floating-point number to the nearest integer not larger than the original.
.. ocv:cfunction:: int cvFloor(double value)
.. ocv:pyoldfunction:: cv.Floor(value) -> int
:param value: floating-point number. If the value is outside of ``INT_MIN`` ... ``INT_MAX`` range, the result is not defined.
The function computes an integer ``i`` such that:
.. math::
i \le \texttt{value} < i+1
Round
-----
Rounds floating-point number to the nearest integer
.. ocv:cfunction:: int cvRound(double value)
.. ocv:pyoldfunction:: cv.Round(value) -> int
:param value: floating-point number. If the value is outside of ``INT_MIN`` ... ``INT_MAX`` range, the result is not defined.
IsInf
-----
Determines if the argument is Infinity.
.. ocv:cfunction:: int cvIsInf(double value)
.. ocv:pyoldfunction:: cv.IsInf(value)-> int
:param value: The input floating-point value
The function returns 1 if the argument is a plus or minus infinity (as defined by IEEE754 standard) and 0 otherwise.
IsNaN
-----
Determines if the argument is Not A Number.
.. ocv:cfunction:: int cvIsNaN(double value)
.. ocv:pyoldfunction:: cv.IsNaN(value)-> int
:param value: The input floating-point value
The function returns 1 if the argument is Not A Number (as defined by IEEE754 standard), 0 otherwise.
CV_Assert
---------
Checks a condition at runtime and throws exception if it fails
.. ocv:function:: CV_Assert(expr)
Checks a condition at runtime. ::
The macros ``CV_Assert`` (and ``CV_DbgAssert``) evaluate the specified expression. If it is 0, the macros raise an error (see :ocv:func:`error` ). The macro ``CV_Assert`` checks the condition in both Debug and Release configurations while ``CV_DbgAssert`` is only retained in the Debug configuration.
#define CV_Assert( expr ) ...
#define CV_DbgAssert(expr) ...
..
:param expr: Expression to check.
The macros ``CV_Assert`` and ``CV_DbgAssert`` evaluate the specified expression. If it is 0, the macros raise an error (see
:ocv:func:`error` ). The macro ``CV_Assert`` checks the condition in both Debug and Release configurations while ``CV_DbgAssert`` is only retained in the Debug configuration.
.. index:: error
error
---------
Signals an error and raises an exception.
.. ocv:function:: void error( const Exception& exc )
.. ocv:function:: #define CV_Error( code, msg ) <...>
.. ocv:function:: #define CV_Error_( code, args ) <...>
Signals an error and raises an exception.
.. ocv:cfunction:: int cvError( int status, const char* funcName, const char* errMsg, const char* filename, int line )
:param exc: Exception to throw.
@@ -104,7 +192,12 @@ error
:param args: ``printf`` -like formatted error message in parentheses.
The function and the helper macros ``CV_Error`` and ``CV_Error_`` call the error handler. Currently, the error handler prints the error code ( ``exc.code`` ), the context ( ``exc.file``,``exc.line`` ), and the error message ``exc.err`` to the standard error stream ``stderr`` . In the Debug configuration, it then provokes memory access violation, so that the execution stack and all the parameters can be analyzed by the debugger. In the Release configuration, the exception ``exc`` is thrown.
The function and the helper macros ``CV_Error`` and ``CV_Error_``: ::
#define CV_Error( code, msg ) error(...)
#define CV_Error_( code, args ) error(...)
call the error handler. Currently, the error handler prints the error code ( ``exc.code`` ), the context ( ``exc.file``,``exc.line`` ), and the error message ``exc.err`` to the standard error stream ``stderr`` . In the Debug configuration, it then provokes memory access violation, so that the execution stack and all the parameters can be analyzed by the debugger. In the Release configuration, the exception ``exc`` is thrown.
The macro ``CV_Error_`` can be used to construct an error message on-fly to include some dynamic information, for example: ::
@@ -113,8 +206,6 @@ The macro ``CV_Error_`` can be used to construct an error message on-fly to incl
("the matrix element (
i, j, mtx.at<float>(i,j)))
.. index:: Exception
Exception
---------
@@ -147,52 +238,53 @@ Exception class passed to an error. ::
The class ``Exception`` encapsulates all or almost all necessary information about the error happened in the program. The exception is usually constructed and thrown implicitly via ``CV_Error`` and ``CV_Error_`` macros. See
:ocv:func:`error` .
.. index:: fastMalloc
fastMalloc
--------------
.. ocv:function:: void* fastMalloc(size_t size)
Allocates an aligned memory buffer.
Allocates an aligned memory buffer.
.. ocv:function:: void* fastMalloc(size_t size)
.. ocv:cfunction:: void* cvAlloc( size_t size )
:param size: Allocated buffer size.
The function allocates the buffer of the specified size and returns it. When the buffer size is 16 bytes or more, the returned buffer is aligned to 16 bytes.
.. index:: fastFree
fastFree
------------
.. ocv:function:: void fastFree(void* ptr)
Deallocates a memory buffer.
Deallocates a memory buffer.
.. ocv:function:: void fastFree(void* ptr)
.. ocv:cfunction:: void cvFree( void** pptr )
:param ptr: Pointer to the allocated buffer.
:param pptr: Double pointer to the allocated buffer
The function deallocates the buffer allocated with
:ocv:func:`fastMalloc` .
If NULL pointer is passed, the function does nothing.
The function deallocates the buffer allocated with :ocv:func:`fastMalloc` . If NULL pointer is passed, the function does nothing. C version of the function clears the pointer *pptr to avoid problems with double memory deallocation.
.. index:: format
format
----------
.. ocv:function:: string format( const char* fmt, ... )
Returns a text string formatted using the ``printf`` -like expression.
Returns a text string formatted using the ``printf`` -like expression.
.. ocv:function:: string format( const char* fmt, ... )
:param fmt: ``printf`` -compatible formatting specifiers.
The function acts like ``sprintf`` but forms and returns an STL string. It can be used to form an error message in the
:ocv:func:`Exception` constructor.
.. index:: getNumThreads
getNumThreads
-----------------
.. ocv:function:: int getNumThreads()
Returns the number of threads used by OpenCV.
Returns the number of threads used by OpenCV.
.. ocv:function:: int getNumThreads()
The function returns the number of threads that is used by OpenCV.
@@ -200,13 +292,13 @@ The function returns the number of threads that is used by OpenCV.
:ocv:func:`setNumThreads`,
:ocv:func:`getThreadNum`
.. index:: getThreadNum
getThreadNum
----------------
.. ocv:function:: int getThreadNum()
Returns the index of the currently executed thread.
Returns the index of the currently executed thread.
.. ocv:function:: int getThreadNum()
The function returns a 0-based index of the currently executed thread. The function is only valid inside a parallel OpenMP region. When OpenCV is built without OpenMP support, the function always returns 0.
@@ -214,25 +306,29 @@ The function returns a 0-based index of the currently executed thread. The funct
:ocv:func:`setNumThreads`,
:ocv:func:`getNumThreads` .
.. index:: getTickCount
getTickCount
----------------
Returns the number of ticks.
.. ocv:function:: int64 getTickCount()
Returns the number of ticks.
.. ocv:pyfunction:: cv2.getTickCount() -> retval
The function returns the number of ticks after the certain event (for example, when the machine was turned on).
It can be used to initialize
:ocv:func:`RNG` or to measure a function execution time by reading the tick count before and after the function call. See also the tick frequency.
.. index:: getTickFrequency
getTickFrequency
--------------------
Returns the number of ticks per second.
.. ocv:function:: double getTickFrequency()
Returns the number of ticks per second.
.. ocv:pyfunction:: cv2.getTickFrequency() -> retval
The function returns the number of ticks per second.
That is, the following code computes the execution time in seconds: ::
@@ -241,23 +337,51 @@ That is, the following code computes the execution time in seconds: ::
// do something ...
t = ((double)getTickCount() - t)/getTickFrequency();
.. index:: getCPUTickCount
getCPUTickCount
----------------
Returns the number of CPU ticks.
.. ocv:function:: int64 getCPUTickCount()
Returns the number of CPU ticks.
.. ocv:pyfunction:: cv2.getCPUTickCount() -> retval
The function returns the current number of CPU ticks on some architectures (such as x86, x64, PowerPC). On other platforms the function is equivalent to ``getTickCount``. It can also be used for very accurate time measurements, as well as for RNG initialization. Note that in case of multi-CPU systems a thread, from which ``getCPUTickCount`` is called, can be suspended and resumed at another CPU with its own counter. So, theoretically (and practically) the subsequent calls to the function do not necessary return the monotonously increasing values. Also, since a modern CPU varies the CPU frequency depending on the load, the number of CPU clocks spent in some code cannot be directly converted to time units. Therefore, ``getTickCount`` is generally a preferable solution for measuring execution time.
.. index:: setNumThreads
saturate_cast
-------------
Template function for accurate conversion from one primitive type to another.
.. ocv:function:: template<...> _Tp saturate_cast(_Tp2 v)
:param v: Function parameter.
The functions ``saturate_cast`` resemble the standard C++ cast operations, such as ``static_cast<T>()`` and others. They perform an efficient and accurate conversion from one primitive type to another (see the introduction chapter). ``saturate`` in the name means that when the input value ``v`` is out of the range of the target type, the result is not formed just by taking low bits of the input, but instead the value is clipped. For example: ::
uchar a = saturate_cast<uchar>(-100); // a = 0 (UCHAR_MIN)
short b = saturate_cast<short>(33333.33333); // b = 32767 (SHRT_MAX)
Such clipping is done when the target type is ``unsigned char`` , ``signed char`` , ``unsigned short`` or ``signed short`` . For 32-bit integers, no clipping is done.
When the parameter is a floating-point value and the target type is an integer (8-, 16- or 32-bit), the floating-point value is first rounded to the nearest integer and then clipped if needed (when the target type is 8- or 16-bit).
This operation is used in the simplest or most complex image processing functions in OpenCV.
.. seealso::
:ocv:func:`add`,
:ocv:func:`subtract`,
:ocv:func:`multiply`,
:ocv:func:`divide`,
:ocv:func:`Mat::convertTo`
setNumThreads
-----------------
.. ocv:function:: void setNumThreads(int nthreads)
Sets the number of threads used by OpenCV.
Sets the number of threads used by OpenCV.
.. ocv:function:: void setNumThreads(int nthreads)
:param nthreads: Number of threads used by OpenCV.
@@ -267,13 +391,17 @@ The function sets the number of threads used by OpenCV in parallel OpenMP region
:ocv:func:`getNumThreads`,
:ocv:func:`getThreadNum`
.. index:: setUseOptimized
setUseOptimized
-----------------
Enables or disables the optimized code.
.. ocv:function:: void setUseOptimized(bool onoff)
Enables or disables the optimized code.
.. ocv:pyfunction:: cv2.setUseOptimized(onoff) -> None
.. ocv:cfunction:: int cvUseOptimized( int onoff )
:param onoff: The boolean flag specifying whether the optimized code should be used (``onoff=true``) or not (``onoff=false``).
@@ -281,12 +409,12 @@ The function can be used to dynamically turn on and off optimized code (code tha
By default, the optimized code is enabled unless you disable it in CMake. The current status can be retrieved using ``useOptimized``.
.. index:: useOptimized
useOptimized
-----------------
Returns the status of optimized code usage.
.. ocv:function:: bool useOptimized()
Returns the status of optimized code usage.
.. ocv:pyfunction:: cv2.useOptimized() -> retval
The function returns ``true`` if the optimized code is enabled. Otherwise, it returns ``false``.
@@ -162,5 +162,3 @@ FileNodeIterator
.. ocv:class:: FileNodeIterator
The class ``FileNodeIterator`` is used to iterate through sequences and mappings. A standard STL notation, with ``node.begin()``, ``node.end()`` denoting the beginning and the end of a sequence, stored in ``node``. See the data reading sample in the beginning of the section.
+1
View File
@@ -2075,6 +2075,7 @@ void cv::compare(InputArray _src1, InputArray _src2, OutputArray _dst, int op)
if( kind1 == kind2 && src1.dims <= 2 && src2.dims <= 2 && src1.size() == src2.size() && src1.type() == src2.type() )
{
CV_Assert(src1.channels() == 1);
_dst.create(src1.size(), CV_8UC1);
Mat dst = _dst.getMat();
Size sz = getContinuousSize(src1, src2, dst, src1.channels());
+1 -1
View File
@@ -148,7 +148,7 @@ static void updateContinuityFlag(Mat& m)
break;
}
int64 t = (int64)(m.step[0]/CV_ELEM_SIZE(m.flags))*m.size[0];
int64 t = (int64)m.step[0]*m.size[0];
if( j <= i && t == (int)t )
m.flags |= Mat::CONTINUOUS_FLAG;
else