Removed Sphinx documentation files

This commit is contained in:
Maksim Shabunin
2014-12-24 18:37:57 +03:00
parent 61991a3330
commit d01bedbc61
338 changed files with 0 additions and 73040 deletions

File diff suppressed because it is too large Load Diff

View File

@@ -1,101 +0,0 @@
Clustering
==========
.. highlight:: cpp
kmeans
------
Finds centers of clusters and groups input samples around the clusters.
.. ocv:function:: double kmeans( InputArray data, int K, InputOutputArray bestLabels, TermCriteria criteria, int attempts, int flags, OutputArray centers=noArray() )
.. ocv:pyfunction:: cv2.kmeans(data, K, bestLabels, criteria, attempts, flags[, centers]) -> retval, bestLabels, centers
.. ocv:cfunction:: int cvKMeans2( const CvArr* samples, int cluster_count, CvArr* labels, CvTermCriteria termcrit, int attempts=1, CvRNG* rng=0, int flags=0, CvArr* _centers=0, double* compactness=0 )
:param samples: Floating-point matrix of input samples, one row per sample.
:param data: Data for clustering. An array of N-Dimensional points with float coordinates is needed. Examples of this array can be:
* ``Mat points(count, 2, CV_32F);``
* ``Mat points(count, 1, CV_32FC2);``
* ``Mat points(1, count, CV_32FC2);``
* ``std::vector<cv::Point2f> points(sampleCount);``
:param cluster_count: Number of clusters to split the set by.
:param K: Number of clusters to split the set by.
:param labels: Input/output integer array that stores the cluster indices for every sample.
: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 termcrit: The algorithm termination criteria, that is, the maximum number of iterations and/or the desired accuracy.
:param attempts: Flag to specify the number of times the algorithm is executed using different initial labellings. The algorithm returns the labels that yield the best compactness (see the last function parameter).
:param rng: CvRNG state initialized by RNG().
:param flags: Flag that can take the following values:
* **KMEANS_RANDOM_CENTERS** Select random initial centers in each attempt.
* **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.
:param centers: Output matrix of the cluster centers, one row per each cluster center.
:param _centers: Output matrix of the cluster centers, one row per each cluster center.
:param compactness: The returned value that is described below.
The function ``kmeans`` implements a k-means algorithm that finds the
centers of ``cluster_count`` clusters and groups the input samples
around the clusters. As an 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.
The function returns the compactness measure that is computed as
.. math::
\sum _i \| \texttt{samples} _i - \texttt{centers} _{ \texttt{labels} _i} \| ^2
after every attempt. The best (minimum) value is chosen and the
corresponding labels and the compactness value are returned by the function.
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.
.. note::
* An example on K-means clustering can be found at opencv_source_code/samples/cpp/kmeans.cpp
* (Python) An example on K-means clustering can be found at opencv_source_code/samples/python2/kmeans.py
partition
-------------
Splits an element set into equivalency classes.
.. ocv:function:: template<typename _Tp, class _EqPredicate> int partition( const vector<_Tp>& vec, vector<int>& labels, _EqPredicate predicate=_EqPredicate())
:param vec: Set of elements stored as a vector.
:param labels: Output vector of labels. It contains as many elements as ``vec``. Each label ``labels[i]`` is a 0-based cluster index of ``vec[i]`` .
:param predicate: Equivalence predicate (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 in the same class, and returns ``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
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

View File

@@ -1,100 +0,0 @@
Command Line Parser
===================
.. highlight:: cpp
CommandLineParser
-----------------
.. ocv:class:: CommandLineParser
The CommandLineParser class is designed for command line arguments parsing
.. ocv:function:: CommandLineParser::CommandLineParser( int argc, const char* const argv[], const String& keys )
:param argc:
:param argv:
:param keys:
.. ocv:function:: template<typename T> T CommandLineParser::get<T>(const String& name, bool space_delete = true)
:param name:
:param space_delete:
.. ocv:function:: template<typename T> T CommandLineParser::get<T>(int index, bool space_delete = true)
:param index:
:param space_delete:
.. ocv:function:: bool CommandLineParser::has(const String& name)
:param name:
.. ocv:function:: bool CommandLineParser::check()
.. ocv:function:: void CommandLineParser::about( const String& message )
:param message:
.. ocv:function:: void CommandLineParser::printMessage()
.. ocv:function:: void CommandLineParser::printErrors()
.. ocv:function:: String CommandLineParser::getPathToApplication()
The sample below demonstrates how to use CommandLineParser:
::
CommandLineParser parser(argc, argv, keys);
parser.about("Application name v1.0.0");
if (parser.has("help"))
{
parser.printMessage();
return 0;
}
int N = parser.get<int>("N");
double fps = parser.get<double>("fps");
String path = parser.get<String>("path");
use_time_stamp = parser.has("timestamp");
String img1 = parser.get<String>(0);
String img2 = parser.get<String>(1);
int repeat = parser.get<int>(2);
if (!parser.check())
{
parser.printErrors();
return 0;
}
Syntax:
::
const String keys =
"{help h usage ? | | print this message }"
"{@image1 | | image1 for compare }"
"{@image2 | | image2 for compare }"
"{@repeat |1 | number }"
"{path |. | path to file }"
"{fps | -1.0 | fps for output video }"
"{N count |100 | count of objects }"
"{ts timestamp | | use time stamp }"
;
Use:
::
# ./app -N=200 1.png 2.jpg 19 -ts
# ./app -fps=aaa
ERRORS:
Exception: can not convert: [aaa] to [double]

View File

@@ -1,19 +0,0 @@
****************************
core. The Core Functionality
****************************
.. toctree::
:maxdepth: 2
basic_structures
command_line_parser
old_basic_structures
dynamic_structures
operations_on_arrays
xml_yaml_persistence
old_xml_yaml_persistence
clustering
utility_and_system_functions_and_macros
opengl_interop
ipp_async_converters
optim

File diff suppressed because it is too large Load Diff

View File

@@ -1,235 +0,0 @@
************
Introduction
************
.. highlight:: cpp
OpenCV (Open Source Computer Vision Library: http://opencv.org) is an open-source BSD-licensed library that includes several hundreds of computer vision algorithms. The document describes the so-called OpenCV 2.x API, which is essentially a C++ API, as opposite to the C-based OpenCV 1.x API. The latter is described in opencv1x.pdf.
OpenCV has a modular structure, which means that the package includes several shared or static libraries. The following modules are available:
* **core** - a compact module defining basic data structures, including the dense multi-dimensional array ``Mat`` and basic functions used by all other modules.
* **imgproc** - an image processing module that includes linear and non-linear image filtering, geometrical image transformations (resize, affine and perspective warping, generic table-based remapping), color space conversion, histograms, and so on.
* **video** - a video analysis module that includes motion estimation, background subtraction, and object tracking algorithms.
* **calib3d** - basic multiple-view geometry algorithms, single and stereo camera calibration, object pose estimation, stereo correspondence algorithms, and elements of 3D reconstruction.
* **features2d** - salient feature detectors, descriptors, and descriptor matchers.
* **objdetect** - detection of objects and instances of the predefined classes (for example, faces, eyes, mugs, people, cars, and so on).
* **highgui** - an easy-to-use interface to simple UI capabilities.
* **videoio** - an easy-to-use interface to video capturing and video codecs.
* **gpu** - GPU-accelerated algorithms from different OpenCV modules.
* ... some other helper modules, such as FLANN and Google test wrappers, Python bindings, and others.
The further chapters of the document describe functionality of each module. But first, make sure to get familiar with the common API concepts used thoroughly in the library.
API Concepts
================
``cv`` Namespace
------------------
All the OpenCV classes and functions are placed into the ``cv`` namespace. Therefore, to access this functionality from your code, use the ``cv::`` specifier or ``using namespace cv;`` directive:
.. code-block:: c
#include "opencv2/core.hpp"
...
cv::Mat H = cv::findHomography(points1, points2, CV_RANSAC, 5);
...
or ::
#include "opencv2/core.hpp"
using namespace cv;
...
Mat H = findHomography(points1, points2, CV_RANSAC, 5 );
...
Some of the current or future OpenCV external names may conflict with STL
or other libraries. In this case, use explicit namespace specifiers to resolve the name conflicts: ::
Mat a(100, 100, CV_32F);
randu(a, Scalar::all(1), Scalar::all(std::rand()));
cv::log(a, a);
a /= std::log(2.);
Automatic Memory Management
---------------------------
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. This means that the destructors do not always deallocate the buffers as in case of ``Mat``. They take into account possible data sharing. A destructor decrements the reference counter associated with the matrix data buffer. 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 a ``Mat`` instance is copied, no actual data is really copied. Instead, the reference counter is incremented to memorize that there is another owner of the same data. There is also the ``Mat::clone`` method that creates a full copy of the matrix data. See the example below: ::
// create a big 8Mb matrix
Mat A(1000, 1000, CV_64F);
// create another header for the same matrix;
// this is an instant operation, regardless of the matrix size.
Mat B = A;
// create another header for the 3-rd row of A; no data is copied either
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
// 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
// of A is still referenced by B and C.
A = 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();
// finally, make a full copy of C. As a result, the big modified
// matrix will be deallocated, since it is not referenced by anyone
C = C.clone();
You see that the use of ``Mat`` and other basic structures is simple. But what about high-level classes or even user
data types created without taking automatic memory management into account? For them, OpenCV offers the :ocv:class:`Ptr`
template class that is similar to ``std::shared_ptr`` from C++11. So, instead of using plain pointers::
T* ptr = new T(...);
you can use::
Ptr<T> ptr(new T(...));
or::
Ptr<T> ptr = makePtr<T>(...);
``Ptr<T>`` encapsulates a pointer to a ``T`` instance and a reference counter associated with the pointer. See the
:ocv:class:`Ptr` description for details.
.. _AutomaticAllocation:
Automatic Allocation of the Output Data
---------------------------------------
OpenCV deallocates the memory automatically, as well as automatically allocates the memory for output function parameters most of the time. So, if a function has one or more input arrays (``cv::Mat`` instances) and some output arrays, the output arrays are automatically allocated or reallocated. The size and type of the output arrays are determined from the size and type of input arrays. If needed, the functions take extra parameters that help to figure out the output array properties.
Example: ::
#include "opencv2/imgproc.hpp"
#include "opencv2/highgui.hpp"
using namespace cv;
int main(int, char**)
{
VideoCapture cap(0);
if(!cap.isOpened()) return -1;
Mat frame, edges;
namedWindow("edges",1);
for(;;)
{
cap >> frame;
cvtColor(frame, edges, COLOR_BGR2GRAY);
GaussianBlur(edges, edges, Size(7,7), 1.5, 1.5);
Canny(edges, edges, 0, 30, 3);
imshow("edges", edges);
if(waitKey(30) >= 0) break;
}
return 0;
}
The array ``frame`` is automatically allocated by the ``>>`` operator since the video frame resolution and the bit-depth is known to the video capturing module. The array ``edges`` is automatically allocated by the ``cvtColor`` function. It has the same size and the bit-depth as the input array. The number of channels is 1 because the color conversion code ``COLOR_BGR2GRAY`` is passed, which means a color to grayscale conversion. Note that ``frame`` and ``edges`` are allocated only once during the first execution of the loop body since all the next video frames have the same resolution. If you somehow change the video resolution, the arrays are automatically reallocated.
The key component of this technology is the ``Mat::create`` method. It takes the desired array size and type. If the array already has the specified size and type, the method does nothing. Otherwise, it releases the previously allocated data, if any (this part involves decrementing the reference counter and comparing it with zero), and then allocates a new buffer of the required size. Most functions call the ``Mat::create`` method for each output array, and so the automatic output data allocation is implemented.
Some notable exceptions from this scheme are ``cv::mixChannels``, ``cv::RNG::fill``, and a few other functions and methods. They are not able to allocate the output array, so you have to do this in advance.
Saturation Arithmetics
----------------------
As a 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 you just store the lowest 8 (16) bits of the result, this results in visual artifacts and may affect a further image analysis. To solve this problem, the so-called *saturation* arithmetics is used. For example, to store ``r``, the result of an operation, to an 8-bit image, you find the nearest value within the 0..255 range:
.. math::
I(x,y)= \min ( \max (\textrm{round}(r), 0), 255)
Similar rules are applied to 8-bit signed, 16-bit signed and unsigned types. This semantics is used everywhere in the library. In C++ code, it is done using the ``saturate_cast<>`` functions that resemble standard C++ cast operations. See below the implementation of the formula provided above::
I.at<uchar>(y, x) = saturate_cast<uchar>(r);
where ``cv::uchar`` is an OpenCV 8-bit unsigned integer type. In the optimized SIMD code, such SSE2 instructions as ``paddusb``, ``packuswb``, and so on are used. They help achieve exactly the same behavior as in C++ code.
.. note:: Saturation is not applied when the result is 32-bit integer.
Fixed Pixel Types. Limited Use of Templates
-------------------------------------------
Templates is a great feature of C++ that enables implementation of very powerful, efficient and yet safe data structures and algorithms. However, the extensive use of templates may dramatically increase compilation time and code size. Besides, it is difficult to separate an interface and implementation when templates are used exclusively. This could be fine for basic algorithms but not good for computer vision libraries where a single algorithm may span thousands lines of code. Because of this and also to simplify development of bindings for other languages, like Python, Java, Matlab that do not have templates at all or have limited template capabilities, the current OpenCV implementation is based on polymorphism and runtime dispatching over templates. In those places where runtime dispatching would be too slow (like pixel access operators), impossible (generic ``Ptr<>`` implementation), or just very inconvenient (``saturate_cast<>()``) the current implementation introduces small template classes, methods, and functions. Anywhere else in the current OpenCV version the use of templates is limited.
Consequently, there is a limited fixed set of primitive data types the library can operate on. That is, array elements should have one of the following types:
* 8-bit unsigned integer (uchar)
* 8-bit signed integer (schar)
* 16-bit unsigned integer (ushort)
* 16-bit signed integer (short)
* 32-bit signed integer (int)
* 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). An array whose elements are such tuples, are called multi-channel arrays, as opposite to the single-channel arrays, whose elements are scalar values. The maximum possible number of channels is defined by the ``CV_CN_MAX`` constant, which is currently set to 512.
For these basic types, the following enumeration is applied::
enum { CV_8U=0, CV_8S=1, CV_16U=2, CV_16S=3, CV_32S=4, CV_32F=5, CV_64F=6 };
Multi-channel (``n``-channel) types can be specified using the following options:
* ``CV_8UC1`` ... ``CV_64FC4`` constants (for a number of channels from 1 to 4)
* ``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 the compilation 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)``. This means that the constant type 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.
Examples: ::
Mat mtx(3, 3, CV_32F); // make a 3x3 floating-point matrix
Mat cmtx(10, 1, CV_64FC2); // make a 10x1 2-channel floating-point
// matrix (10-element complex vector)
Mat img(Size(1920, 1080), CV_8UC3); // make a 3-channel (color) image
// of 1920 columns and 1080 rows.
Mat grayscale(image.size(), CV_MAKETYPE(image.depth(), 1)); // make a 1-channel image of
// the same size and same
// channel type as img
Arrays with more complex elements cannot be constructed or processed using OpenCV. Furthermore, each function or method can handle only a subset of all possible array types. Usually, the more complex the algorithm is, the smaller the supported subset of formats is. See below typical examples of such limitations:
* The face detection algorithm only works with 8-bit grayscale or color images.
* Linear algebra functions and most of the machine learning algorithms work with floating-point arrays only.
* Basic functions, such as ``cv::add``, support all types.
* Color space conversion functions support 8-bit unsigned, 16-bit unsigned, and 32-bit floating-point types.
The subset of supported types for each function has been defined from practical needs and could be extended in future based on user requests.
InputArray and OutputArray
--------------------------
Many OpenCV functions process dense 2-dimensional or multi-dimensional numerical arrays. Usually, such functions take cpp:class:`Mat` as parameters, but in some cases it's more convenient to use ``std::vector<>`` (for a point set, for example) or ``Matx<>`` (for 3x3 homography matrix and such). To avoid many duplicates in the API, special "proxy" classes have been introduced. The base "proxy" class is ``InputArray``. It is used for passing read-only arrays on a function input. The derived from ``InputArray`` class ``OutputArray`` is used to specify an output array for a function. Normally, you should not care of those intermediate types (and you should not declare variables of those types explicitly) - it will all just work automatically. You can assume that instead of ``InputArray``/``OutputArray`` you can always use ``Mat``, ``std::vector<>``, ``Matx<>``, ``Vec<>`` or ``Scalar``. When a function has an optional input or output array, and you do not have or do not want one, pass ``cv::noArray()``.
Error Handling
--------------
OpenCV uses exceptions to signal critical errors. When the input data has a correct format and belongs to the specified value range, but the algorithm cannot succeed for some reason (for example, the optimization algorithm did not converge), it returns a special error code (typically, just a boolean variable).
The exceptions can be instances of the ``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 either using the ``CV_Error(errcode, description)`` macro, or its printf-like ``CV_Error_(errcode, printf-spec, (printf-args))`` variant, or using the ``CV_Assert(condition)`` macro that checks the condition and throws an exception when it is not satisfied. For performance-critical code, there is ``CV_DbgAssert(condition)`` that is only retained in the Debug configuration. Due to the automatic memory management, all the intermediate buffers are automatically deallocated in case of a sudden error. You only need to add a try statement to catch exceptions, if needed: ::
try
{
... // call OpenCV
}
catch( cv::Exception& e )
{
const char* err_msg = e.what();
std::cout << "exception caught: " << err_msg << std::endl;
}
Multi-threading and Re-enterability
-----------------------------------
The current OpenCV implementation is fully re-enterable. That is, the same function, the same *constant* method of a class instance, or the same *non-constant* method of different class instances can be called from different threads. Also, the same ``cv::Mat`` can be used in different threads because the reference-counting operations use the architecture-specific atomic instructions.

View File

@@ -1,72 +0,0 @@
Intel® IPP Asynchronous C/C++ Converters
========================================
.. highlight:: cpp
General Information
-------------------
This section describes conversion between OpenCV and `Intel® IPP Asynchronous C/C++ <http://software.intel.com/en-us/intel-ipp-preview>`_ library.
`Getting Started Guide <http://registrationcenter.intel.com/irc_nas/3727/ipp_async_get_started.htm>`_ help you to install the library, configure header and library build paths.
hpp::getHpp
-----------
Create ``hppiMatrix`` from ``Mat``.
.. ocv:function:: hppiMatrix* hpp::getHpp(const Mat& src, hppAccel accel)
:param src: input matrix.
:param accel: accelerator instance. Supports type:
* **HPP_ACCEL_TYPE_CPU** - accelerated by optimized CPU instructions.
* **HPP_ACCEL_TYPE_GPU** - accelerated by GPU programmable units or fixed-function accelerators.
* **HPP_ACCEL_TYPE_ANY** - any acceleration or no acceleration available.
This function allocates and initializes the ``hppiMatrix`` that has the same size and type as input matrix, returns the ``hppiMatrix*``.
If you want to use zero-copy for GPU you should to have 4KB aligned matrix data. See details `hppiCreateSharedMatrix <http://software.intel.com/ru-ru/node/501697>`_.
Supports ``CV_8U``, ``CV_16U``, ``CV_16S``, ``CV_32S``, ``CV_32F``, ``CV_64F``.
.. note:: The ``hppiMatrix`` pointer to the image buffer in system memory refers to the ``src.data``. Control the lifetime of the matrix and don't change its data, if there is no special need.
.. seealso:: :ref:`howToUseIPPAconversion`, :ocv:func:`hpp::getMat`
hpp::getMat
-----------
Create ``Mat`` from ``hppiMatrix``.
.. ocv:function:: Mat hpp::getMat(hppiMatrix* src, hppAccel accel, int cn)
:param src: input hppiMatrix.
:param accel: accelerator instance (see :ocv:func:`hpp::getHpp` for the list of acceleration framework types).
:param cn: number of channels.
This function allocates and initializes the ``Mat`` that has the same size and type as input matrix.
Supports ``CV_8U``, ``CV_16U``, ``CV_16S``, ``CV_32S``, ``CV_32F``, ``CV_64F``.
.. seealso:: :ref:`howToUseIPPAconversion`, :ocv:func:`hpp::copyHppToMat`, :ocv:func:`hpp::getHpp`.
hpp::copyHppToMat
-----------------
Convert ``hppiMatrix`` to ``Mat``.
.. ocv:function:: void hpp::copyHppToMat(hppiMatrix* src, Mat& dst, hppAccel accel, int cn)
:param src: input hppiMatrix.
:param dst: output matrix.
:param accel: accelerator instance (see :ocv:func:`hpp::getHpp` for the list of acceleration framework types).
:param cn: number of channels.
This function allocates and initializes new matrix (if needed) that has the same size and type as input matrix.
Supports ``CV_8U``, ``CV_16U``, ``CV_16S``, ``CV_32S``, ``CV_32F``, ``CV_64F``.
.. seealso:: :ref:`howToUseIPPAconversion`, :ocv:func:`hpp::getMat`, :ocv:func:`hpp::getHpp`.

File diff suppressed because it is too large Load Diff

View File

@@ -1,909 +0,0 @@
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. Alternatively, 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* struct_ptr )
:param struct_ptr: 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, ``struct_ptr`` 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* type_name )
:param type_name: 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 create_missing=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 create_missing: 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 navigate 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 create_missing=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 create_missing: 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* memstorage=NULL, const char* name=NULL, const char** real_name=NULL )
:param filename: File name
:param memstorage: 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 real_name: 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, const char* encoding=NULL )
: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. If the file cannot be opened then the function returns ``NULL``.
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 default_value=0 )
:param node: File node
:param default_value: 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
``default_value`` 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 default_value=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 default_value: 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 default_value=0. )
:param node: File node
:param default_value: 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
``default_value``
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 default_value=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 default_value: 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* default_value=NULL )
:param node: File node
:param default_value: 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
``default_value``
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* default_value=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 default_value: 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** struct_ptr )
:param struct_ptr: 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* struct_ptr, const char* name=NULL, const char* comment=NULL, CvAttrList attributes=cvAttrList() )
:param filename: File name
:param struct_ptr: 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 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* type_name=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
* **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 type_name: 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:`FindType` ).
: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* struct_ptr )
:param struct_ptr: 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* type_name )
:param type_name: 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 discussion 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 eol_comment )
:param fs: File storage
:param comment: The written comment, single-line or multi-line
:param eol_comment: 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_node_name: 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 hierarchy 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.

View File

@@ -1,543 +0,0 @@
OpenGL interoperability
=======================
.. highlight:: cpp
General Information
-------------------
This section describes OpenGL interoperability.
To enable OpenGL support, configure OpenCV using ``CMake`` with ``WITH_OPENGL=ON`` .
Currently OpenGL is supported only with WIN32, GTK and Qt backends on Windows and Linux (MacOS and Android are not supported).
For GTK backend ``gtkglext-1.0`` library is required.
To use OpenGL functionality you should first create OpenGL context (window or frame buffer).
You can do this with :ocv:func:`namedWindow` function or with other OpenGL toolkit (GLUT, for example).
ogl::Buffer
-----------
Smart pointer for OpenGL buffer object with reference counting.
.. ocv:class:: ogl::Buffer
Buffer Objects are OpenGL objects that store an array of unformatted memory allocated by the OpenGL context.
These can be used to store vertex data, pixel data retrieved from images or the framebuffer, and a variety of other things.
``ogl::Buffer`` has interface similar with :ocv:class:`Mat` interface and represents 2D array memory.
``ogl::Buffer`` supports memory transfers between host and device and also can be mapped to CUDA memory.
ogl::Buffer::Target
-------------------
The target defines how you intend to use the buffer object.
.. ocv:enum:: ogl::Buffer::Target
.. ocv:emember:: ARRAY_BUFFER
The buffer will be used as a source for vertex data.
.. ocv:emember:: ELEMENT_ARRAY_BUFFER
The buffer will be used for indices (in ``glDrawElements`` or :ocv:func:`ogl::render`, for example).
.. ocv:emember:: PIXEL_PACK_BUFFER
The buffer will be used for reading from OpenGL textures.
.. ocv:emember:: PIXEL_UNPACK_BUFFER
The buffer will be used for writing to OpenGL textures.
ogl::Buffer::Buffer
-------------------
The constructors.
.. ocv:function:: ogl::Buffer::Buffer()
.. ocv:function:: ogl::Buffer::Buffer(int arows, int acols, int atype, unsigned int abufId, bool autoRelease = false)
.. ocv:function:: ogl::Buffer::Buffer(Size asize, int atype, unsigned int abufId, bool autoRelease = false)
.. ocv:function:: ogl::Buffer::Buffer(int arows, int acols, int atype, Target target = ARRAY_BUFFER, bool autoRelease = false)
.. ocv:function:: ogl::Buffer::Buffer(Size asize, int atype, Target target = ARRAY_BUFFER, bool autoRelease = false)
.. ocv:function:: ogl::Buffer::Buffer(InputArray arr, Target target = ARRAY_BUFFER, bool autoRelease = false)
:param arows: Number of rows in a 2D array.
:param acols: Number of columns in a 2D array.
:param asize: 2D array size.
:param atype: Array type ( ``CV_8UC1, ..., CV_64FC4`` ). See :ocv:class:`Mat` for details.
:param abufId: Buffer object name.
:param arr: Input array (host or device memory, it can be :ocv:class:`Mat` , :ocv:class:`cuda::GpuMat` or ``std::vector`` ).
:param target: Buffer usage. See :ocv:enum:`ogl::Buffer::Target` .
:param autoRelease: Auto release mode (if true, release will be called in object's destructor).
Creates empty ``ogl::Buffer`` object, creates ``ogl::Buffer`` object from existed buffer ( ``abufId`` parameter),
allocates memory for ``ogl::Buffer`` object or copies from host/device memory.
ogl::Buffer::create
-------------------
Allocates memory for ``ogl::Buffer`` object.
.. ocv:function:: void ogl::Buffer::create(int arows, int acols, int atype, Target target = ARRAY_BUFFER, bool autoRelease = false)
.. ocv:function:: void ogl::Buffer::create(Size asize, int atype, Target target = ARRAY_BUFFER, bool autoRelease = false)
:param arows: Number of rows in a 2D array.
:param acols: Number of columns in a 2D array.
:param asize: 2D array size.
:param atype: Array type ( ``CV_8UC1, ..., CV_64FC4`` ). See :ocv:class:`Mat` for details.
:param target: Buffer usage. See :ocv:enum:`ogl::Buffer::Target` .
:param autoRelease: Auto release mode (if true, release will be called in object's destructor).
ogl::Buffer::release
--------------------
Decrements the reference counter and destroys the buffer object if needed.
.. ocv:function:: void ogl::Buffer::release()
The function will call `setAutoRelease(true)` .
ogl::Buffer::setAutoRelease
---------------------------
Sets auto release mode.
.. ocv:function:: void ogl::Buffer::setAutoRelease(bool flag)
:param flag: Auto release mode (if true, release will be called in object's destructor).
The lifetime of the OpenGL object is tied to the lifetime of the context.
If OpenGL context was bound to a window it could be released at any time (user can close a window).
If object's destructor is called after destruction of the context it will cause an error.
Thus ``ogl::Buffer`` doesn't destroy OpenGL object in destructor by default (all OpenGL resources will be released with OpenGL context).
This function can force ``ogl::Buffer`` destructor to destroy OpenGL object.
ogl::Buffer::copyFrom
---------------------
Copies from host/device memory to OpenGL buffer.
.. ocv:function:: void ogl::Buffer::copyFrom(InputArray arr, Target target = ARRAY_BUFFER, bool autoRelease = false)
:param arr: Input array (host or device memory, it can be :ocv:class:`Mat` , :ocv:class:`cuda::GpuMat` or ``std::vector`` ).
:param target: Buffer usage. See :ocv:enum:`ogl::Buffer::Target` .
:param autoRelease: Auto release mode (if true, release will be called in object's destructor).
ogl::Buffer::copyTo
-------------------
Copies from OpenGL buffer to host/device memory or another OpenGL buffer object.
.. ocv:function:: void ogl::Buffer::copyTo(OutputArray arr) const
:param arr: Destination array (host or device memory, can be :ocv:class:`Mat` , :ocv:class:`cuda::GpuMat` , ``std::vector`` or ``ogl::Buffer`` ).
ogl::Buffer::clone
------------------
Creates a full copy of the buffer object and the underlying data.
.. ocv:function:: Buffer ogl::Buffer::clone(Target target = ARRAY_BUFFER, bool autoRelease = false) const
:param target: Buffer usage for destination buffer.
:param autoRelease: Auto release mode for destination buffer.
ogl::Buffer::bind
-----------------
Binds OpenGL buffer to the specified buffer binding point.
.. ocv:function:: void ogl::Buffer::bind(Target target) const
:param target: Binding point. See :ocv:enum:`ogl::Buffer::Target` .
ogl::Buffer::unbind
-------------------
Unbind any buffers from the specified binding point.
.. ocv:function:: static void ogl::Buffer::unbind(Target target)
:param target: Binding point. See :ocv:enum:`ogl::Buffer::Target` .
ogl::Buffer::mapHost
--------------------
Maps OpenGL buffer to host memory.
.. ocv:function:: Mat ogl::Buffer::mapHost(Access access)
:param access: Access policy, indicating whether it will be possible to read from, write to, or both read from and write to the buffer object's mapped data store. The symbolic constant must be ``ogl::Buffer::READ_ONLY`` , ``ogl::Buffer::WRITE_ONLY`` or ``ogl::Buffer::READ_WRITE`` .
``mapHost`` maps to the client's address space the entire data store of the buffer object.
The data can then be directly read and/or written relative to the returned pointer, depending on the specified ``access`` policy.
A mapped data store must be unmapped with :ocv:func:`ogl::Buffer::unmapHost` before its buffer object is used.
This operation can lead to memory transfers between host and device.
Only one buffer object can be mapped at a time.
ogl::Buffer::unmapHost
----------------------
Unmaps OpenGL buffer.
.. ocv:function:: void ogl::Buffer::unmapHost()
ogl::Buffer::mapDevice
----------------------
Maps OpenGL buffer to CUDA device memory.
.. ocv:function:: cuda::GpuMat ogl::Buffer::mapDevice()
This operatation doesn't copy data.
Several buffer objects can be mapped to CUDA memory at a time.
A mapped data store must be unmapped with :ocv:func:`ogl::Buffer::unmapDevice` before its buffer object is used.
ogl::Buffer::unmapDevice
------------------------
Unmaps OpenGL buffer.
.. ocv:function:: void ogl::Buffer::unmapDevice()
ogl::Texture2D
--------------
Smart pointer for OpenGL 2D texture memory with reference counting.
.. ocv:class:: ogl::Texture2D
ogl::Texture2D::Format
----------------------
An Image Format describes the way that the images in Textures store their data.
.. ocv:enum:: ogl::Texture2D::Format
.. ocv:emember:: NONE
.. ocv:emember:: DEPTH_COMPONENT
.. ocv:emember:: RGB
.. ocv:emember:: RGBA
ogl::Texture2D::Texture2D
-------------------------
The constructors.
.. ocv:function:: ogl::Texture2D::Texture2D()
.. ocv:function:: ogl::Texture2D::Texture2D(int arows, int acols, Format aformat, unsigned int atexId, bool autoRelease = false)
.. ocv:function:: ogl::Texture2D::Texture2D(Size asize, Format aformat, unsigned int atexId, bool autoRelease = false)
.. ocv:function:: ogl::Texture2D::Texture2D(int arows, int acols, Format aformat, bool autoRelease = false)
.. ocv:function:: ogl::Texture2D::Texture2D(Size asize, Format aformat, bool autoRelease = false)
.. ocv:function:: ogl::Texture2D::Texture2D(InputArray arr, bool autoRelease = false)
:param arows: Number of rows.
:param acols: Number of columns.
:param asize: 2D array size.
:param aformat: Image format. See :ocv:enum:`ogl::Texture2D::Format` .
:param arr: Input array (host or device memory, it can be :ocv:class:`Mat` , :ocv:class:`cuda::GpuMat` or :ocv:class:`ogl::Buffer` ).
:param autoRelease: Auto release mode (if true, release will be called in object's destructor).
Creates empty ``ogl::Texture2D`` object, allocates memory for ``ogl::Texture2D`` object or copies from host/device memory.
ogl::Texture2D::create
----------------------
Allocates memory for ``ogl::Texture2D`` object.
.. ocv:function:: void ogl::Texture2D::create(int arows, int acols, Format aformat, bool autoRelease = false)
.. ocv:function:: void ogl::Texture2D::create(Size asize, Format aformat, bool autoRelease = false)
:param arows: Number of rows.
:param acols: Number of columns.
:param asize: 2D array size.
:param aformat: Image format. See :ocv:enum:`ogl::Texture2D::Format` .
:param autoRelease: Auto release mode (if true, release will be called in object's destructor).
ogl::Texture2D::release
-----------------------
Decrements the reference counter and destroys the texture object if needed.
.. ocv:function:: void ogl::Texture2D::release()
The function will call `setAutoRelease(true)` .
ogl::Texture2D::setAutoRelease
------------------------------
Sets auto release mode.
.. ocv:function:: void ogl::Texture2D::setAutoRelease(bool flag)
:param flag: Auto release mode (if true, release will be called in object's destructor).
The lifetime of the OpenGL object is tied to the lifetime of the context.
If OpenGL context was bound to a window it could be released at any time (user can close a window).
If object's destructor is called after destruction of the context it will cause an error.
Thus ``ogl::Texture2D`` doesn't destroy OpenGL object in destructor by default (all OpenGL resources will be released with OpenGL context).
This function can force ``ogl::Texture2D`` destructor to destroy OpenGL object.
ogl::Texture2D::copyFrom
------------------------
Copies from host/device memory to OpenGL texture.
.. ocv:function:: void ogl::Texture2D::copyFrom(InputArray arr, bool autoRelease = false)
:param arr: Input array (host or device memory, it can be :ocv:class:`Mat` , :ocv:class:`cuda::GpuMat` or :ocv:class:`ogl::Buffer` ).
:param autoRelease: Auto release mode (if true, release will be called in object's destructor).
ogl::Texture2D::copyTo
----------------------
Copies from OpenGL texture to host/device memory or another OpenGL texture object.
.. ocv:function:: void ogl::Texture2D::copyTo(OutputArray arr, int ddepth = CV_32F, bool autoRelease = false) const
:param arr: Destination array (host or device memory, can be :ocv:class:`Mat` , :ocv:class:`cuda::GpuMat` , :ocv:class:`ogl::Buffer` or ``ogl::Texture2D`` ).
:param ddepth: Destination depth.
:param autoRelease: Auto release mode for destination buffer (if ``arr`` is OpenGL buffer or texture).
ogl::Texture2D::bind
--------------------
Binds texture to current active texture unit for ``GL_TEXTURE_2D`` target.
.. ocv:function:: void ogl::Texture2D::bind() const
ogl::Arrays
-----------
Wrapper for OpenGL Client-Side Vertex arrays.
.. ocv:class:: ogl::Arrays
``ogl::Arrays`` stores vertex data in :ocv:class:`ogl::Buffer` objects.
ogl::Arrays::setVertexArray
---------------------------
Sets an array of vertex coordinates.
.. ocv:function:: void ogl::Arrays::setVertexArray(InputArray vertex)
:param vertex: array with vertex coordinates, can be both host and device memory.
ogl::Arrays::resetVertexArray
-----------------------------
Resets vertex coordinates.
.. ocv:function:: void ogl::Arrays::resetVertexArray()
ogl::Arrays::setColorArray
--------------------------
Sets an array of vertex colors.
.. ocv:function:: void ogl::Arrays::setColorArray(InputArray color)
:param color: array with vertex colors, can be both host and device memory.
ogl::Arrays::resetColorArray
----------------------------
Resets vertex colors.
.. ocv:function:: void ogl::Arrays::resetColorArray()
ogl::Arrays::setNormalArray
---------------------------
Sets an array of vertex normals.
.. ocv:function:: void ogl::Arrays::setNormalArray(InputArray normal)
:param normal: array with vertex normals, can be both host and device memory.
ogl::Arrays::resetNormalArray
-----------------------------
Resets vertex normals.
.. ocv:function:: void ogl::Arrays::resetNormalArray()
ogl::Arrays::setTexCoordArray
-----------------------------
Sets an array of vertex texture coordinates.
.. ocv:function:: void ogl::Arrays::setTexCoordArray(InputArray texCoord)
:param texCoord: array with vertex texture coordinates, can be both host and device memory.
ogl::Arrays::resetTexCoordArray
-------------------------------
Resets vertex texture coordinates.
.. ocv:function:: void ogl::Arrays::resetTexCoordArray()
ogl::Arrays::release
--------------------
Releases all inner buffers.
.. ocv:function:: void ogl::Arrays::release()
ogl::Arrays::setAutoRelease
---------------------------
Sets auto release mode all inner buffers.
.. ocv:function:: void ogl::Arrays::setAutoRelease(bool flag)
:param flag: Auto release mode.
ogl::Arrays::bind
-----------------
Binds all vertex arrays.
.. ocv:function:: void ogl::Arrays::bind() const
ogl::Arrays::size
-----------------
Returns the vertex count.
.. ocv:function:: int ogl::Arrays::size() const
ogl::render
-----------
Render OpenGL texture or primitives.
.. ocv:function:: void ogl::render(const Texture2D& tex, Rect_<double> wndRect = Rect_<double>(0.0, 0.0, 1.0, 1.0), Rect_<double> texRect = Rect_<double>(0.0, 0.0, 1.0, 1.0))
.. ocv:function:: void ogl::render(const Arrays& arr, int mode = POINTS, Scalar color = Scalar::all(255))
.. ocv:function:: void ogl::render(const Arrays& arr, InputArray indices, int mode = POINTS, Scalar color = Scalar::all(255))
:param tex: Texture to draw.
:param wndRect: Region of window, where to draw a texture (normalized coordinates).
:param texRect: Region of texture to draw (normalized coordinates).
:param arr: Array of privitives vertices.
:param indices: Array of vertices indices (host or device memory).
:param mode: Render mode. Available options:
* **POINTS**
* **LINES**
* **LINE_LOOP**
* **LINE_STRIP**
* **TRIANGLES**
* **TRIANGLE_STRIP**
* **TRIANGLE_FAN**
* **QUADS**
* **QUAD_STRIP**
* **POLYGON**
:param color: Color for all vertices. Will be used if ``arr`` doesn't contain color array.
cuda::setGlDevice
-----------------
Sets a CUDA device and initializes it for the current thread with OpenGL interoperability.
.. ocv:function:: void cuda::setGlDevice( int device = 0 )
:param device: System index of a CUDA device starting with 0.
This function should be explicitly called after OpenGL context creation and before any CUDA calls.

File diff suppressed because it is too large Load Diff

View File

@@ -1,341 +0,0 @@
Optimization Algorithms
=======================
.. highlight:: cpp
The algorithms in this section minimize or maximize function value within specified constraints or without any constraints.
solveLP
--------------------
Solve given (non-integer) linear programming problem using the Simplex Algorithm (Simplex Method).
What we mean here by "linear programming problem" (or LP problem, for short) can be
formulated as:
.. math::
\mbox{Maximize } c\cdot x\\
\mbox{Subject to:}\\
Ax\leq b\\
x\geq 0
Where :math:`c` is fixed *1*-by-*n* row-vector, :math:`A` is fixed *m*-by-*n* matrix, :math:`b` is fixed *m*-by-*1* column vector and
:math:`x` is an arbitrary *n*-by-*1* column vector, which satisfies the constraints.
Simplex algorithm is one of many algorithms that are designed to handle this sort of problems efficiently. Although it is not optimal in theoretical
sense (there exist algorithms that can solve any problem written as above in polynomial type, while simplex method degenerates to exponential time
for some special cases), it is well-studied, easy to implement and is shown to work well for real-life purposes.
The particular implementation is taken almost verbatim from **Introduction to Algorithms, third edition**
by T. H. Cormen, C. E. Leiserson, R. L. Rivest and Clifford Stein. In particular, the Bland's rule
(`http://en.wikipedia.org/wiki/Bland%27s\_rule <http://en.wikipedia.org/wiki/Bland%27s_rule>`_) is used to prevent cycling.
.. ocv:function:: int solveLP(const Mat& Func, const Mat& Constr, Mat& z)
:param Func: This row-vector corresponds to :math:`c` in the LP problem formulation (see above). It should contain 32- or 64-bit floating point numbers. As a convenience, column-vector may be also submitted, in the latter case it is understood to correspond to :math:`c^T`.
:param Constr: *m*-by-*n\+1* matrix, whose rightmost column corresponds to :math:`b` in formulation above and the remaining to :math:`A`. It should containt 32- or 64-bit floating point numbers.
:param z: The solution will be returned here as a column-vector - it corresponds to :math:`c` in the formulation above. It will contain 64-bit floating point numbers.
:return: One of the return codes:
::
//!the return codes for solveLP() function
enum
{
SOLVELP_UNBOUNDED = -2, //problem is unbounded (target function can achieve arbitrary high values)
SOLVELP_UNFEASIBLE = -1, //problem is unfeasible (there are no points that satisfy all the constraints imposed)
SOLVELP_SINGLE = 0, //there is only one maximum for target function
SOLVELP_MULTI = 1 //there are multiple maxima for target function - the arbitrary one is returned
};
DownhillSolver
---------------------------------
.. ocv:class:: DownhillSolver
This class is used to perform the non-linear non-constrained *minimization* of a function, defined on an *n*-dimensional Euclidean space,
using the **Nelder-Mead method**, also known as **downhill simplex method**. The basic idea about the method can be obtained from
(`http://en.wikipedia.org/wiki/Nelder-Mead\_method <http://en.wikipedia.org/wiki/Nelder-Mead_method>`_). It should be noted, that
this method, although deterministic, is rather a heuristic and therefore may converge to a local minima, not necessary a global one.
It is iterative optimization technique, which at each step uses an information about the values of a function evaluated only at
*n+1* points, arranged as a *simplex* in *n*-dimensional space (hence the second name of the method). At each step new point is
chosen to evaluate function at, obtained value is compared with previous ones and based on this information simplex changes it's shape
, slowly moving to the local minimum. Thus this method is using *only* function values to make decision, on contrary to, say, Nonlinear
Conjugate Gradient method (which is also implemented in ``optim``).
Algorithm stops when the number of function evaluations done exceeds ``termcrit.maxCount``, when the function values at the
vertices of simplex are within ``termcrit.epsilon`` range or simplex becomes so small that it
can enclosed in a box with ``termcrit.epsilon`` sides, whatever comes first, for some defined by user
positive integer ``termcrit.maxCount`` and positive non-integer ``termcrit.epsilon``.
::
class CV_EXPORTS Solver : public Algorithm
{
public:
class CV_EXPORTS Function
{
public:
virtual ~Function() {}
virtual double calc(const double* x) const = 0;
virtual void getGradient(const double* /*x*/,double* /*grad*/) {}
};
virtual Ptr<Function> getFunction() const = 0;
virtual void setFunction(const Ptr<Function>& f) = 0;
virtual TermCriteria getTermCriteria() const = 0;
virtual void setTermCriteria(const TermCriteria& termcrit) = 0;
// x contain the initial point before the call and the minima position (if algorithm converged) after. x is assumed to be (something that
// after getMat() will return) row-vector or column-vector. *It's size and should
// be consisted with previous dimensionality data given, if any (otherwise, it determines dimensionality)*
virtual double minimize(InputOutputArray x) = 0;
};
class CV_EXPORTS DownhillSolver : public Solver
{
public:
//! returns row-vector, even if the column-vector was given
virtual void getInitStep(OutputArray step) const=0;
//!This should be called at least once before the first call to minimize() and step is assumed to be (something that
//! after getMat() will return) row-vector or column-vector. *It's dimensionality determines the dimensionality of a problem.*
virtual void setInitStep(InputArray step)=0;
};
It should be noted, that ``DownhillSolver`` is a derivative of the abstract interface ``Solver``, which in
turn is derived from the ``Algorithm`` interface and is used to encapsulate the functionality, common to all non-linear optimization
algorithms in the ``optim`` module.
DownhillSolver::getFunction
--------------------------------------------
Getter for the optimized function. The optimized function is represented by ``Solver::Function`` interface, which requires
derivatives to implement the sole method ``calc(double*)`` to evaluate the function.
.. ocv:function:: Ptr<Solver::Function> DownhillSolver::getFunction()
:return: Smart-pointer to an object that implements ``Solver::Function`` interface - it represents the function that is being optimized. It can be empty, if no function was given so far.
DownhillSolver::setFunction
-----------------------------------------------
Setter for the optimized function. *It should be called at least once before the call to* ``DownhillSolver::minimize()``, as
default value is not usable.
.. ocv:function:: void DownhillSolver::setFunction(const Ptr<Solver::Function>& f)
:param f: The new function to optimize.
DownhillSolver::getTermCriteria
----------------------------------------------------
Getter for the previously set terminal criteria for this algorithm.
.. ocv:function:: TermCriteria DownhillSolver::getTermCriteria()
:return: Deep copy of the terminal criteria used at the moment.
DownhillSolver::setTermCriteria
------------------------------------------
Set terminal criteria for downhill simplex method. Two things should be noted. First, this method *is not necessary* to be called
before the first call to ``DownhillSolver::minimize()``, as the default value is sensible. Second, the method will raise an error
if ``termcrit.type!=(TermCriteria::MAX_ITER+TermCriteria::EPS)``, ``termcrit.epsilon<=0`` or ``termcrit.maxCount<=0``. That is,
both ``epsilon`` and ``maxCount`` should be set to positive values (non-integer and integer respectively) and they represent
tolerance and maximal number of function evaluations that is allowed.
Algorithm stops when the number of function evaluations done exceeds ``termcrit.maxCount``, when the function values at the
vertices of simplex are within ``termcrit.epsilon`` range or simplex becomes so small that it
can enclosed in a box with ``termcrit.epsilon`` sides, whatever comes first.
.. ocv:function:: void DownhillSolver::setTermCriteria(const TermCriteria& termcrit)
:param termcrit: Terminal criteria to be used, represented as ``TermCriteria`` structure (defined elsewhere in openCV). Mind you, that it should meet ``(termcrit.type==(TermCriteria::MAX_ITER+TermCriteria::EPS) && termcrit.epsilon>0 && termcrit.maxCount>0)``, otherwise the error will be raised.
DownhillSolver::getInitStep
-----------------------------------
Returns the initial step that will be used in downhill simplex algorithm. See the description
of corresponding setter (follows next) for the meaning of this parameter.
.. ocv:function:: void getInitStep(OutputArray step)
:param step: Initial step that will be used in algorithm. Note, that although corresponding setter accepts column-vectors as well as row-vectors, this method will return a row-vector.
DownhillSolver::setInitStep
----------------------------------
Sets the initial step that will be used in downhill simplex algorithm. Step, together with initial point (givin in ``DownhillSolver::minimize``)
are two *n*-dimensional vectors that are used to determine the shape of initial simplex. Roughly said, initial point determines the position
of a simplex (it will become simplex's centroid), while step determines the spread (size in each dimension) of a simplex. To be more precise,
if :math:`s,x_0\in\mathbb{R}^n` are the initial step and initial point respectively, the vertices of a simplex will be: :math:`v_0:=x_0-\frac{1}{2}
s` and :math:`v_i:=x_0+s_i` for :math:`i=1,2,\dots,n` where :math:`s_i` denotes projections of the initial step of *n*-th coordinate (the result
of projection is treated to be vector given by :math:`s_i:=e_i\cdot\left<e_i\cdot s\right>`, where :math:`e_i` form canonical basis)
.. ocv:function:: void setInitStep(InputArray step)
:param step: Initial step that will be used in algorithm. Roughly said, it determines the spread (size in each dimension) of an initial simplex.
DownhillSolver::minimize
-----------------------------------
The main method of the ``DownhillSolver``. It actually runs the algorithm and performs the minimization. The sole input parameter determines the
centroid of the starting simplex (roughly, it tells where to start), all the others (terminal criteria, initial step, function to be minimized)
are supposed to be set via the setters before the call to this method or the default values (not always sensible) will be used.
.. ocv:function:: double DownhillSolver::minimize(InputOutputArray x)
:param x: The initial point, that will become a centroid of an initial simplex. After the algorithm will terminate, it will be setted to the point where the algorithm stops, the point of possible minimum.
:return: The value of a function at the point found.
createDownhillSolver
------------------------------------
This function returns the reference to the ready-to-use ``DownhillSolver`` object. All the parameters are optional, so this procedure can be called
even without parameters at all. In this case, the default values will be used. As default value for terminal criteria are the only sensible ones,
``DownhillSolver::setFunction()`` and ``DownhillSolver::setInitStep()`` should be called upon the obtained object, if the respective parameters
were not given to ``createDownhillSolver()``. Otherwise, the two ways (give parameters to ``createDownhillSolver()`` or miss them out and call the
``DownhillSolver::setFunction()`` and ``DownhillSolver::setInitStep()``) are absolutely equivalent (and will drop the same errors in the same way,
should invalid input be detected).
.. ocv:function:: Ptr<DownhillSolver> createDownhillSolver(const Ptr<Solver::Function>& f,InputArray initStep, TermCriteria termcrit)
:param f: Pointer to the function that will be minimized, similarly to the one you submit via ``DownhillSolver::setFunction``.
:param step: Initial step, that will be used to construct the initial simplex, similarly to the one you submit via ``DownhillSolver::setInitStep``.
:param termcrit: Terminal criteria to the algorithm, similarly to the one you submit via ``DownhillSolver::setTermCriteria``.
ConjGradSolver
---------------------------------
.. ocv:class:: ConjGradSolver
This class is used to perform the non-linear non-constrained *minimization* of a function with *known gradient*
, defined on an *n*-dimensional Euclidean space,
using the **Nonlinear Conjugate Gradient method**. The implementation was done based on the beautifully clear explanatory article `An Introduction to the Conjugate Gradient Method Without the Agonizing Pain <http://www.cs.cmu.edu/~quake-papers/painless-conjugate-gradient.pdf>`_
by Jonathan Richard Shewchuk. The method can be seen as an adaptation of a standard Conjugate Gradient method (see, for example
`http://en.wikipedia.org/wiki/Conjugate_gradient_method <http://en.wikipedia.org/wiki/Conjugate_gradient_method>`_) for numerically solving the
systems of linear equations.
It should be noted, that
this method, although deterministic, is rather a heuristic method and therefore may converge to a local minima, not necessary a global one. What
is even more disastrous, most of its behaviour is ruled by gradient, therefore it essentially cannot distinguish between local minima and maxima.
Therefore, if it starts sufficiently near to the local maximum, it may converge to it. Another obvious restriction is that it should be possible
to compute the gradient of a function at any point, thus it is preferable to have analytic expression for gradient and computational burden
should be born by the user.
The latter responsibility is accompilished via the ``getGradient(const double* x,double* grad)`` method of a
``Solver::Function`` interface (which represents function that is being optimized). This method takes point a point in *n*-dimensional space
(first argument represents the array of coordinates of that point) and comput its gradient (it should be stored in the second argument as an array).
::
class CV_EXPORTS Solver : public Algorithm
{
public:
class CV_EXPORTS Function
{
public:
virtual ~Function() {}
virtual double calc(const double* x) const = 0;
virtual void getGradient(const double* /*x*/,double* /*grad*/) {}
};
virtual Ptr<Function> getFunction() const = 0;
virtual void setFunction(const Ptr<Function>& f) = 0;
virtual TermCriteria getTermCriteria() const = 0;
virtual void setTermCriteria(const TermCriteria& termcrit) = 0;
// x contain the initial point before the call and the minima position (if algorithm converged) after. x is assumed to be (something that
// after getMat() will return) row-vector or column-vector. *It's size and should
// be consisted with previous dimensionality data given, if any (otherwise, it determines dimensionality)*
virtual double minimize(InputOutputArray x) = 0;
};
class CV_EXPORTS ConjGradSolver : public Solver{
};
Note, that class ``ConjGradSolver`` thus does not add any new methods to the basic ``Solver`` interface.
ConjGradSolver::getFunction
--------------------------------------------
Getter for the optimized function. The optimized function is represented by ``Solver::Function`` interface, which requires
derivatives to implement the method ``calc(double*)`` to evaluate the function. It should be emphasized once more, that since Nonlinear
Conjugate Gradient method requires gradient to be computable in addition to the function values,
``getGradient(const double* x,double* grad)`` method of a ``Solver::Function`` interface should be also implemented meaningfully.
.. ocv:function:: Ptr<Solver::Function> ConjGradSolver::getFunction()
:return: Smart-pointer to an object that implements ``Solver::Function`` interface - it represents the function that is being optimized. It can be empty, if no function was given so far.
ConjGradSolver::setFunction
-----------------------------------------------
Setter for the optimized function. *It should be called at least once before the call to* ``ConjGradSolver::minimize()``, as
default value is not usable.
.. ocv:function:: void ConjGradSolver::setFunction(const Ptr<Solver::Function>& f)
:param f: The new function to optimize.
ConjGradSolver::getTermCriteria
----------------------------------------------------
Getter for the previously set terminal criteria for this algorithm.
.. ocv:function:: TermCriteria ConjGradSolver::getTermCriteria()
:return: Deep copy of the terminal criteria used at the moment.
ConjGradSolver::setTermCriteria
------------------------------------------
Set terminal criteria for downhill simplex method. Two things should be noted. First, this method *is not necessary* to be called
before the first call to ``ConjGradSolver::minimize()``, as the default value is sensible. Second, the method will raise an error
if ``termcrit.type!=(TermCriteria::MAX_ITER+TermCriteria::EPS)`` and ``termcrit.type!=TermCriteria::MAX_ITER``. This means that termination criteria
has to restrict maximum number of iterations to be done and may optionally allow algorithm to stop earlier if certain tolerance
is achieved (what we mean by "tolerance is achieved" will be clarified below). If ``termcrit`` restricts both tolerance and maximum iteration
number, both ``termcrit.epsilon`` and ``termcrit.maxCount`` should be positive. In case, if ``termcrit.type==TermCriteria::MAX_ITER``,
only member ``termcrit.maxCount`` is required to be positive and in this case algorithm will just work for required number of iterations.
In current implementation, "tolerance is achieved" means that we have arrived at the point where the :math:`L_2`-norm of the gradient is less
than the tolerance value.
.. ocv:function:: void ConjGradSolver::setTermCriteria(const TermCriteria& termcrit)
:param termcrit: Terminal criteria to be used, represented as ``TermCriteria`` structure (defined elsewhere in openCV). Mind you, that it should meet ``termcrit.type==(TermCriteria::MAX_ITER+TermCriteria::EPS) && termcrit.epsilon>0 && termcrit.maxCount>0`` or ``termcrit.type==TermCriteria::MAX_ITER) && termcrit.maxCount>0``, otherwise the error will be raised.
ConjGradSolver::minimize
-----------------------------------
The main method of the ``ConjGradSolver``. It actually runs the algorithm and performs the minimization. The sole input parameter determines the
centroid of the starting simplex (roughly, it tells where to start), all the others (terminal criteria and function to be minimized)
are supposed to be set via the setters before the call to this method or the default values (not always sensible) will be used. Sometimes it may
throw an error, if these default values cannot be used (say, you forgot to set the function to minimize and default value, that is, empty function,
cannot be used).
.. ocv:function:: double ConjGradSolver::minimize(InputOutputArray x)
:param x: The initial point. It is hard to overemphasize how important the choise of initial point is when you are using the heuristic algorithm like this one. Badly chosen initial point can make algorithm converge to (local) maximum instead of minimum, do not converge at all, converge to local minimum instead of global one.
:return: The value of a function at the point found.
createConjGradSolver
------------------------------------
This function returns the reference to the ready-to-use ``ConjGradSolver`` object. All the parameters are optional, so this procedure can be called
even without parameters at all. In this case, the default values will be used. As default value for terminal criteria are the only sensible ones,
``ConjGradSolver::setFunction()`` should be called upon the obtained object, if the function
was not given to ``createConjGradSolver()``. Otherwise, the two ways (submit it to ``createConjGradSolver()`` or miss it out and call the
``ConjGradSolver::setFunction()``) are absolutely equivalent (and will drop the same errors in the same way,
should invalid input be detected).
.. ocv:function:: Ptr<ConjGradSolver> createConjGradSolver(const Ptr<Solver::Function>& f, TermCriteria termcrit)
:param f: Pointer to the function that will be minimized, similarly to the one you submit via ``ConjGradSolver::setFunction``.
:param termcrit: Terminal criteria to the algorithm, similarly to the one you submit via ``ConjGradSolver::setTermCriteria``.

View File

@@ -1,493 +0,0 @@
Utility and System Functions and Macros
=======================================
.. highlight:: cpp
alignPtr
------------
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.
:param n: Alignment size that must be a power of two.
The function returns the aligned pointer of the same type as the input pointer:
.. math::
\texttt{(\_Tp*)(((size\_t)ptr + n-1) \& -n)}
alignSize
-------------
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.
:param n: Alignment size that must be a power of two.
The function returns the minimum number that is greater or equal to ``sz`` and is divisible by ``n`` :
.. math::
\texttt{(sz + n-1) \& -n}
allocate
------------
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.
deallocate
--------------
Deallocates an array of elements.
.. ocv:function:: template<typename _Tp> void deallocate(_Tp* ptr, size_t n)
:param ptr: Pointer to the deallocated buffer.
:param n: Number of elements in the buffer.
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` .
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)
: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 value )
: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)
: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)
: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)
: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)
: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)
: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)
:param expr: Expression for 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.
error
-----
Signals an error and raises an exception.
.. ocv:function:: void error( const Exception& exc )
.. ocv:cfunction:: void cvError( int status, const char* func_name, const char* err_msg, const char* file_name, int line )
:param exc: Exception to throw.
:param status: Error code. Normally, it is a negative value. The list of pre-defined error codes can be found in ``cxerror.h`` .
:param func_name: The function name where error occurs.
:param err_msg: Text of the error message.
:param file_name: The file name where error occurs.
:param line: The line number where error occurs.
:param args: ``printf`` -like formatted error message in parentheses.
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: ::
// note the extra parentheses around the formatted text message
CV_Error_(CV_StsOutOfRange,
("the matrix element (
i, j, mtx.at<float>(i,j)))
Exception
---------
.. ocv:class:: Exception : public std::exception
Exception class passed to an error. ::
class Exception
{
public:
// various constructors and the copy operation
Exception() { code = 0; line = 0; }
Exception(int _code, const String& _err,
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
String err;
// function name where the error happened
String func;
// the source file name where the error happened
String file;
// the source file line where the error happened
int line;
};
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` .
fastMalloc
--------------
Allocates an aligned memory buffer.
.. ocv:function:: void* fastMalloc( size_t bufSize )
.. ocv:cfunction:: void* cvAlloc( size_t size )
:param size: Allocated buffer size.
:param bufSize: 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.
fastFree
--------
Deallocates a memory buffer.
.. ocv:function:: void fastFree(void* ptr)
.. ocv:cfunction:: void cvFree( void** pptr )
:param ptr: Pointer to the allocated buffer.
:param pptr: Double pointer to the allocated buffer
The function deallocates the buffer allocated with :ocv:func:`fastMalloc` . If NULL pointer is passed, the function does nothing. C version of the function clears the pointer ``*pptr`` to avoid problems with double memory deallocation.
format
------
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:class:`Exception` constructor.
getBuildInformation
-------------------
Returns full configuration time cmake output.
.. ocv:function:: const String& getBuildInformation()
Returned value is raw cmake output including version control system revision, compiler version, compiler flags, enabled modules and third party libraries, etc. Output format depends on target architecture.
checkHardwareSupport
--------------------
Returns true if the specified feature is supported by the host hardware.
.. ocv:function:: bool checkHardwareSupport(int feature)
.. ocv:cfunction:: int cvCheckHardwareSupport(int feature)
.. ocv:pyfunction:: cv2.checkHardwareSupport(feature) -> retval
:param feature: The feature of interest, one of:
* ``CV_CPU_MMX`` - MMX
* ``CV_CPU_SSE`` - SSE
* ``CV_CPU_SSE2`` - SSE 2
* ``CV_CPU_SSE3`` - SSE 3
* ``CV_CPU_SSSE3`` - SSSE 3
* ``CV_CPU_SSE4_1`` - SSE 4.1
* ``CV_CPU_SSE4_2`` - SSE 4.2
* ``CV_CPU_POPCNT`` - POPCOUNT
* ``CV_CPU_AVX`` - AVX
The function returns true if the host hardware supports the specified feature. When user calls ``setUseOptimized(false)``, the subsequent calls to ``checkHardwareSupport()`` will return false until ``setUseOptimized(true)`` is called. This way user can dynamically switch on and off the optimized code in OpenCV.
getNumberOfCPUs
-----------------
Returns the number of logical CPUs available for the process.
.. ocv:function:: int getNumberOfCPUs()
getNumThreads
-----------------
Returns the number of threads used by OpenCV for parallel regions.
Always returns 1 if OpenCV is built without threading support.
.. ocv:function:: int getNumThreads()
The exact meaning of return value depends on the threading framework used by OpenCV library:
* **TBB** The number of threads, that OpenCV will try to use for parallel regions.
If there is any ``tbb::thread_scheduler_init`` in user code conflicting with OpenCV, then
function returns default number of threads used by TBB library.
* **OpenMP** An upper bound on the number of threads that could be used to form a new team.
* **Concurrency** The number of threads, that OpenCV will try to use for parallel regions.
* **GCD** Unsupported; returns the GCD thread pool limit (512) for compatibility.
* **C=** The number of threads, that OpenCV will try to use for parallel regions,
if before called ``setNumThreads`` with ``threads > 0``,
otherwise returns the number of logical CPUs, available for the process.
.. seealso::
:ocv:func:`setNumThreads`,
:ocv:func:`getThreadNum`
getThreadNum
----------------
Returns the index of the currently executed thread within the current parallel region.
Always returns 0 if called outside of parallel region.
.. ocv:function:: int getThreadNum()
The exact meaning of return value depends on the threading framework used by OpenCV library:
* **TBB** Unsupported with current 4.1 TBB release. May be will be supported in future.
* **OpenMP** The thread number, within the current team, of the calling thread.
* **Concurrency** An ID for the virtual processor that the current context is executing
on (0 for master thread and unique number for others, but not necessary 1,2,3,...).
* **GCD** System calling thread's ID. Never returns 0 inside parallel region.
* **C=** The index of the current parallel task.
.. seealso::
:ocv:func:`setNumThreads`,
:ocv:func:`getNumThreads`
getTickCount
------------
Returns the number of ticks.
.. ocv:function:: int64 getTickCount()
.. 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.
getTickFrequency
----------------
Returns the number of ticks per second.
.. ocv:function:: double getTickFrequency()
.. 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: ::
double t = (double)getTickCount();
// do something ...
t = ((double)getTickCount() - t)/getTickFrequency();
getCPUTickCount
---------------
Returns the number of CPU ticks.
.. ocv:function:: int64 getCPUTickCount()
.. 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.
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
-----------------
OpenCV will try to set the number of threads for the next parallel region.
If ``threads == 0``, OpenCV will disable threading optimizations and run all it's
functions sequentially. Passing ``threads < 0`` will reset threads number to system default.
This function must be called outside of parallel region.
.. ocv:function:: void setNumThreads(int nthreads)
:param nthreads: Number of threads used by OpenCV.
OpenCV will try to run it's functions with specified threads number, but
some behaviour differs from framework:
* **TBB** User-defined parallel constructions will run with the same threads number,
if another does not specified. If late on user creates own scheduler, OpenCV will be use it.
* **OpenMP** No special defined behaviour.
* **Concurrency** If ``threads == 1``, OpenCV will disable threading optimizations
and run it's functions sequentially.
* **GCD** Supports only values <= 0.
* **C=** No special defined behaviour.
.. seealso::
:ocv:func:`getNumThreads`,
:ocv:func:`getThreadNum`
setUseOptimized
---------------
Enables or disables the optimized code.
.. ocv:function:: int cvUseOptimized( int on_off )
.. ocv:pyfunction:: cv2.setUseOptimized(onoff) -> None
.. ocv:cfunction:: int cvUseOptimized( int on_off )
:param on_off: The boolean flag specifying whether the optimized code should be used (``on_off=true``) or not (``on_off=false``).
The function can be used to dynamically turn on and off optimized code (code that uses SSE2, AVX, and other instructions on the platforms that support it). It sets a global flag that is further checked by OpenCV functions. Since the flag is not checked in the inner OpenCV loops, it is only safe to call the function on the very top level in your application where you can be sure that no other OpenCV function is currently executed.
By default, the optimized code is enabled unless you disable it in CMake. The current status can be retrieved using ``useOptimized``.
useOptimized
------------
Returns the status of optimized code usage.
.. ocv:function:: bool useOptimized()
.. ocv:pyfunction:: cv2.useOptimized() -> retval
The function returns ``true`` if the optimized code is enabled. Otherwise, it returns ``false``.

View File

@@ -1,718 +0,0 @@
XML/YAML Persistence
====================
.. highlight:: cpp
XML/YAML file storages. Writing to a file storage.
--------------------------------------------------
You can store and then restore various OpenCV data structures to/from XML (http://www.w3c.org/XML) or YAML
(http://www.yaml.org) formats. Also, it is possible store and load arbitrarily complex data structures, which include OpenCV data structures, as well as primitive data types (integer and floating-point numbers and text strings) as their elements.
Use the following procedure to write something to XML or YAML:
#. Create new :ocv:class:`FileStorage` and open it for writing. It can be done with a single call to :ocv:func:`FileStorage::FileStorage` constructor that takes a filename, or you can use the default constructor and then call :ocv:func:`FileStorage::open`. Format of the file (XML or YAML) is determined from the filename extension (".xml" and ".yml"/".yaml", respectively)
#. Write all the data you want using the streaming operator ``<<``, just like in the case of STL streams.
#. Close the file using :ocv:func:`FileStorage::release`. ``FileStorage`` destructor also closes the file.
Here is an example: ::
#include "opencv2/opencv.hpp"
#include <time.h>
using namespace cv;
int main(int, char** argv)
{
FileStorage fs("test.yml", FileStorage::WRITE);
fs << "frameCount" << 5;
time_t rawtime; time(&rawtime);
fs << "calibrationDate" << asctime(localtime(&rawtime));
Mat cameraMatrix = (Mat_<double>(3,3) << 1000, 0, 320, 0, 1000, 240, 0, 0, 1);
Mat distCoeffs = (Mat_<double>(5,1) << 0.1, 0.01, -0.001, 0, 0);
fs << "cameraMatrix" << cameraMatrix << "distCoeffs" << distCoeffs;
fs << "features" << "[";
for( int i = 0; i < 3; i++ )
{
int x = rand() % 640;
int y = rand() % 480;
uchar lbp = rand() % 256;
fs << "{:" << "x" << x << "y" << y << "lbp" << "[:";
for( int j = 0; j < 8; j++ )
fs << ((lbp >> j) & 1);
fs << "]" << "}";
}
fs << "]";
fs.release();
return 0;
}
The sample above stores to XML and integer, text string (calibration date), 2 matrices, and a custom structure "feature", which includes feature coordinates and LBP (local binary pattern) value. Here is output of the sample:
.. code-block:: yaml
%YAML:1.0
frameCount: 5
calibrationDate: "Fri Jun 17 14:09:29 2011\n"
cameraMatrix: !!opencv-matrix
rows: 3
cols: 3
dt: d
data: [ 1000., 0., 320., 0., 1000., 240., 0., 0., 1. ]
distCoeffs: !!opencv-matrix
rows: 5
cols: 1
dt: d
data: [ 1.0000000000000001e-01, 1.0000000000000000e-02,
-1.0000000000000000e-03, 0., 0. ]
features:
- { x:167, y:49, lbp:[ 1, 0, 0, 1, 1, 0, 1, 1 ] }
- { x:298, y:130, lbp:[ 0, 0, 0, 1, 0, 0, 1, 1 ] }
- { x:344, y:158, lbp:[ 1, 1, 0, 0, 0, 0, 1, 0 ] }
As an exercise, you can replace ".yml" with ".xml" in the sample above and see, how the corresponding XML file will look like.
Several things can be noted by looking at the sample code and the output:
*
The produced YAML (and XML) consists of heterogeneous collections that can be nested. There are 2 types of collections: named collections (mappings) and unnamed collections (sequences). In mappings each element has a name and is accessed by name. This is similar to structures and ``std::map`` in C/C++ and dictionaries in Python. In sequences elements do not have names, they are accessed by indices. This is similar to arrays and ``std::vector`` in C/C++ and lists, tuples in Python. "Heterogeneous" means that elements of each single collection can have different types.
Top-level collection in YAML/XML is a mapping. Each matrix is stored as a mapping, and the matrix elements are stored as a sequence. Then, there is a sequence of features, where each feature is represented a mapping, and lbp value in a nested sequence.
*
When you write to a mapping (a structure), you write element name followed by its value. When you write to a sequence, you simply write the elements one by one. OpenCV data structures (such as cv::Mat) are written in absolutely the same way as simple C data structures - using **``<<``** operator.
*
To write a mapping, you first write the special string **"{"** to the storage, then write the elements as pairs (``fs << <element_name> << <element_value>``) and then write the closing **"}"**.
*
To write a sequence, you first write the special string **"["**, then write the elements, then write the closing **"]"**.
*
In YAML (but not XML), mappings and sequences can be written in a compact Python-like inline form. In the sample above matrix elements, as well as each feature, including its lbp value, is stored in such inline form. To store a mapping/sequence in a compact form, put ":" after the opening character, e.g. use **"{:"** instead of **"{"** and **"[:"** instead of **"["**. When the data is written to XML, those extra ":" are ignored.
.. note::
* A complete example using the FileStorage interface can be found at opencv_source_code/samples/cpp/filestorage.cpp
Reading data from a file storage.
---------------------------------
To read the previously written XML or YAML file, do the following:
#.
Open the file storage using :ocv:func:`FileStorage::FileStorage` constructor or :ocv:func:`FileStorage::open` method. In the current implementation the whole file is parsed and the whole representation of file storage is built in memory as a hierarchy of file nodes (see :ocv:class:`FileNode`)
#.
Read the data you are interested in. Use :ocv:func:`FileStorage::operator []`, :ocv:func:`FileNode::operator []` and/or :ocv:class:`FileNodeIterator`.
#.
Close the storage using :ocv:func:`FileStorage::release`.
Here is how to read the file created by the code sample above: ::
FileStorage fs2("test.yml", FileStorage::READ);
// first method: use (type) operator on FileNode.
int frameCount = (int)fs2["frameCount"];
String date;
// second method: use FileNode::operator >>
fs2["calibrationDate"] >> date;
Mat cameraMatrix2, distCoeffs2;
fs2["cameraMatrix"] >> cameraMatrix2;
fs2["distCoeffs"] >> distCoeffs2;
cout << "frameCount: " << frameCount << endl
<< "calibration date: " << date << endl
<< "camera matrix: " << cameraMatrix2 << endl
<< "distortion coeffs: " << distCoeffs2 << endl;
FileNode features = fs2["features"];
FileNodeIterator it = features.begin(), it_end = features.end();
int idx = 0;
std::vector<uchar> lbpval;
// iterate through a sequence using FileNodeIterator
for( ; it != it_end; ++it, idx++ )
{
cout << "feature #" << idx << ": ";
cout << "x=" << (int)(*it)["x"] << ", y=" << (int)(*it)["y"] << ", lbp: (";
// you can also easily read numerical arrays using FileNode >> std::vector operator.
(*it)["lbp"] >> lbpval;
for( int i = 0; i < (int)lbpval.size(); i++ )
cout << " " << (int)lbpval[i];
cout << ")" << endl;
}
fs.release();
FileStorage
-----------
.. ocv:class:: FileStorage
XML/YAML file storage class that encapsulates all the information necessary for writing or reading data to/from a file.
FileStorage::FileStorage
------------------------
The constructors.
.. ocv:function:: FileStorage::FileStorage()
.. ocv:function:: FileStorage::FileStorage(const String& source, int flags, const String& encoding=String())
:param source: Name of the file to open or the text string to read the data from. Extension of the file (``.xml`` or ``.yml``/``.yaml``) determines its format (XML or YAML respectively). Also you can append ``.gz`` to work with compressed files, for example ``myHugeMatrix.xml.gz``. If both ``FileStorage::WRITE`` and ``FileStorage::MEMORY`` flags are specified, ``source`` is used just to specify the output file format (e.g. ``mydata.xml``, ``.yml`` etc.).
:param flags: Mode of operation. Possible values are:
* **FileStorage::READ** Open the file for reading.
* **FileStorage::WRITE** Open the file for writing.
* **FileStorage::APPEND** Open the file for appending.
* **FileStorage::MEMORY** Read data from ``source`` or write data to the internal buffer (which is returned by ``FileStorage::release``)
:param encoding: Encoding of the file. Note that UTF-16 XML encoding is not supported currently and you should use 8-bit encoding instead of it.
The full constructor opens the file. Alternatively you can use the default constructor and then call :ocv:func:`FileStorage::open`.
FileStorage::open
-----------------
Opens a file.
.. ocv:function:: bool FileStorage::open(const String& filename, int flags, const String& encoding=String())
:param filename: Name of the file to open or the text string to read the data from.
Extension of the file (``.xml`` or ``.yml``/``.yaml``) determines its format (XML or YAML respectively).
Also you can append ``.gz`` to work with compressed files, for example ``myHugeMatrix.xml.gz``.
If both ``FileStorage::WRITE`` and ``FileStorage::MEMORY`` flags are specified, ``source``
is used just to specify the output file format (e.g. ``mydata.xml``, ``.yml`` etc.).
:param flags: Mode of operation. See FileStorage constructor for more details.
:param encoding: Encoding of the file. Note that UTF-16 XML encoding is not supported currently and you should use 8-bit encoding instead of it.
See description of parameters in :ocv:func:`FileStorage::FileStorage`. The method calls :ocv:func:`FileStorage::release` before opening the file.
FileStorage::isOpened
---------------------
Checks whether the file is opened.
.. ocv:function:: bool FileStorage::isOpened() const
:returns: ``true`` if the object is associated with the current file and ``false`` otherwise.
It is a good practice to call this method after you tried to open a file.
FileStorage::release
--------------------
Closes the file and releases all the memory buffers.
.. ocv:function:: void FileStorage::release()
Call this method after all I/O operations with the storage are finished.
FileStorage::releaseAndGetString
--------------------------------
Closes the file and releases all the memory buffers.
.. ocv:function:: String FileStorage::releaseAndGetString()
Call this method after all I/O operations with the storage are finished. If the storage was opened for writing data and ``FileStorage::WRITE`` was specified
FileStorage::getFirstTopLevelNode
---------------------------------
Returns the first element of the top-level mapping.
.. ocv:function:: FileNode FileStorage::getFirstTopLevelNode() const
:returns: The first element of the top-level mapping.
FileStorage::root
-----------------
Returns the top-level mapping
.. ocv:function:: FileNode FileStorage::root(int streamidx=0) const
:param streamidx: Zero-based index of the stream. In most cases there is only one stream in the file. However, YAML supports multiple streams and so there can be several.
:returns: The top-level mapping.
FileStorage::operator[]
-----------------------
Returns the specified element of the top-level mapping.
.. ocv:function:: FileNode FileStorage::operator[](const String& nodename) const
.. ocv:function:: FileNode FileStorage::operator[](const char* nodename) const
:param nodename: Name of the file node.
:returns: Node with the given name.
FileStorage::operator*
----------------------
Returns the obsolete C FileStorage structure.
.. ocv:function:: CvFileStorage* FileStorage::operator *()
.. ocv:function:: const CvFileStorage* FileStorage::operator *() const
:returns: Pointer to the underlying C FileStorage structure
FileStorage::writeRaw
---------------------
Writes multiple numbers.
.. ocv:function:: void FileStorage::writeRaw( const String& fmt, const uchar* vec, size_t len )
:param fmt: 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.
:param vec: Pointer to the written array.
:param len: Number of the ``uchar`` elements to write.
Writes one or more numbers of the specified format to the currently written structure. Usually it is more convenient to use :ocv:func:`operator <<` instead of this method.
FileStorage::writeObj
---------------------
Writes the registered C structure (CvMat, CvMatND, CvSeq).
.. ocv:function:: void FileStorage::writeObj( const String& name, const void* obj )
:param name: Name of the written object.
:param obj: Pointer to the object.
See :ocv:cfunc:`Write` for details.
FileStorage::getDefaultObjectName
---------------------------------
Returns the normalized object name for the specified name of a file.
.. ocv:function:: static String FileStorage::getDefaultObjectName(const String& filename)
:param filename: Name of a file
:returns: The normalized object name.
operator <<
-----------
Writes data to a file storage.
.. ocv:function:: template<typename _Tp> FileStorage& operator << (FileStorage& fs, const _Tp& value)
.. ocv:function:: template<typename _Tp> FileStorage& operator << ( FileStorage& fs, const vector<_Tp>& vec )
:param fs: Opened file storage to write data.
:param value: Value to be written to the file storage.
:param vec: Vector of values to be written to the file storage.
It is the main function to write data to a file storage. See an example of its usage at the beginning of the section.
operator >>
-----------
Reads data from a file storage.
.. ocv:function:: template<typename _Tp> void operator >> (const FileNode& n, _Tp& value)
.. ocv:function:: template<typename _Tp> void operator >> (const FileNode& n, vector<_Tp>& vec)
.. ocv:function:: template<typename _Tp> FileNodeIterator& operator >> (FileNodeIterator& it, _Tp& value)
.. ocv:function:: template<typename _Tp> FileNodeIterator& operator >> (FileNodeIterator& it, vector<_Tp>& vec)
:param n: Node from which data will be read.
:param it: Iterator from which data will be read.
:param value: Value to be read from the file storage.
:param vec: Vector of values to be read from the file storage.
It is the main function to read data from a file storage. See an example of its usage at the beginning of the section.
FileNode
--------
.. ocv:class:: FileNode
File Storage Node class. The node is used to store each and every element of the file storage opened for reading. 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. There can be named collections (mappings) where each element has a name and it is accessed by a name, and ordered collections (sequences) where elements do not have names but rather accessed by index. Type of the file node can be determined using :ocv:func:`FileNode::type` method.
Note that file nodes are only used for navigating file storages opened for reading. When a file storage is opened for writing, no data is stored in memory after it is written.
FileNode::FileNode
------------------
The constructors.
.. ocv:function:: FileNode::FileNode()
.. ocv:function:: FileNode::FileNode(const CvFileStorage* fs, const CvFileNode* node)
.. ocv:function:: FileNode::FileNode(const FileNode& node)
:param fs: Pointer to the obsolete file storage structure.
:param node: File node to be used as initialization for the created file node.
These constructors are used to create a default file node, construct it from obsolete structures or from the another file node.
FileNode::operator[]
--------------------
Returns element of a mapping node or a sequence node.
.. ocv:function:: FileNode FileNode::operator[](const String& nodename) const
.. ocv:function:: FileNode FileNode::operator[](const char* nodename) const
.. ocv:function:: FileNode FileNode::operator[](int i) const
:param nodename: Name of an element in the mapping node.
:param i: Index of an element in the sequence node.
:returns: Returns the element with the given identifier.
FileNode::type
--------------
Returns type of the node.
.. ocv:function:: int FileNode::type() const
:returns: Type of the node. Possible values are:
* **FileNode::NONE** Empty node.
* **FileNode::INT** Integer.
* **FileNode::REAL** Floating-point number.
* **FileNode::FLOAT** Synonym or ``REAL``.
* **FileNode::STR** Text string in UTF-8 encoding.
* **FileNode::STRING** Synonym for ``STR``.
* **FileNode::REF** Integer of type ``size_t``. Typically used for storing complex dynamic structures where some elements reference the others.
* **FileNode::SEQ** Sequence.
* **FileNode::MAP** Mapping.
* **FileNode::FLOW** Compact representation of a sequence or mapping. Used only by the YAML writer.
* **FileNode::USER** Registered object (e.g. a matrix).
* **FileNode::EMPTY** Empty structure (sequence or mapping).
* **FileNode::NAMED** The node has a name (i.e. it is an element of a mapping).
FileNode::empty
---------------
Checks whether the node is empty.
.. ocv:function:: bool FileNode::empty() const
:returns: ``true`` if the node is empty.
FileNode::isNone
----------------
Checks whether the node is a "none" object
.. ocv:function:: bool FileNode::isNone() const
:returns: ``true`` if the node is a "none" object.
FileNode::isSeq
---------------
Checks whether the node is a sequence.
.. ocv:function:: bool FileNode::isSeq() const
:returns: ``true`` if the node is a sequence.
FileNode::isMap
---------------
Checks whether the node is a mapping.
.. ocv:function:: bool FileNode::isMap() const
:returns: ``true`` if the node is a mapping.
FileNode::isInt
---------------
Checks whether the node is an integer.
.. ocv:function:: bool FileNode::isInt() const
:returns: ``true`` if the node is an integer.
FileNode::isReal
----------------
Checks whether the node is a floating-point number.
.. ocv:function:: bool FileNode::isReal() const
:returns: ``true`` if the node is a floating-point number.
FileNode::isString
------------------
Checks whether the node is a text string.
.. ocv:function:: bool FileNode::isString() const
:returns: ``true`` if the node is a text string.
FileNode::isNamed
-----------------
Checks whether the node has a name.
.. ocv:function:: bool FileNode::isNamed() const
:returns: ``true`` if the node has a name.
FileNode::name
--------------
Returns the node name.
.. ocv:function:: String FileNode::name() const
:returns: The node name or an empty string if the node is nameless.
FileNode::size
--------------
Returns the number of elements in the node.
.. ocv:function:: size_t FileNode::size() const
:returns: The number of elements in the node, if it is a sequence or mapping, or 1 otherwise.
FileNode::operator int
----------------------
Returns the node content as an integer.
.. ocv:function:: FileNode::operator int() const
:returns: The node content as an integer. If the node stores a floating-point number, it is rounded.
FileNode::operator float
------------------------
Returns the node content as float.
.. ocv:function:: FileNode::operator float() const
:returns: The node content as float.
FileNode::operator double
-------------------------
Returns the node content as double.
.. ocv:function:: FileNode::operator double() const
:returns: The node content as double.
FileNode::operator String
------------------------------
Returns the node content as text string.
.. ocv:function:: FileNode::operator String() const
:returns: The node content as a text string.
FileNode::operator*
-------------------
Returns pointer to the underlying obsolete file node structure.
.. ocv:function:: CvFileNode* FileNode::operator *()
:returns: Pointer to the underlying obsolete file node structure.
FileNode::begin
---------------
Returns the iterator pointing to the first node element.
.. ocv:function:: FileNodeIterator FileNode::begin() const
:returns: Iterator pointing to the first node element.
FileNode::end
-------------
Returns the iterator pointing to the element following the last node element.
.. ocv:function:: FileNodeIterator FileNode::end() const
:returns: Iterator pointing to the element following the last node element.
FileNode::readRaw
-----------------
Reads node elements to the buffer with the specified format.
.. ocv:function:: void FileNode::readRaw( const String& fmt, uchar* vec, size_t len ) const
:param fmt: Specification of each array element. It has the same format as in :ocv:func:`FileStorage::writeRaw`.
:param vec: Pointer to the destination array.
:param len: Number of elements to read. If it is greater than number of remaining elements then all of them will be read.
Usually it is more convenient to use :ocv:func:`operator >>` instead of this method.
FileNode::readObj
-----------------
Reads the registered object.
.. ocv:function:: void* FileNode::readObj() const
:returns: Pointer to the read object.
See :ocv:cfunc:`Read` for details.
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.
FileNodeIterator::FileNodeIterator
----------------------------------
The constructors.
.. ocv:function:: FileNodeIterator::FileNodeIterator()
.. ocv:function:: FileNodeIterator::FileNodeIterator(const CvFileStorage* fs, const CvFileNode* node, size_t ofs=0)
.. ocv:function:: FileNodeIterator::FileNodeIterator(const FileNodeIterator& it)
:param fs: File storage for the iterator.
:param node: File node for the iterator.
:param ofs: Index of the element in the node. The created iterator will point to this element.
:param it: Iterator to be used as initialization for the created iterator.
These constructors are used to create a default iterator, set it to specific element in a file node or construct it from another iterator.
FileNodeIterator::operator*
---------------------------
Returns the currently observed element.
.. ocv:function:: FileNode FileNodeIterator::operator *() const
:returns: Currently observed element.
FileNodeIterator::operator->
----------------------------
Accesses methods of the currently observed element.
.. ocv:function:: FileNode FileNodeIterator::operator ->() const
FileNodeIterator::operator ++
-----------------------------
Moves iterator to the next node.
.. ocv:function:: FileNodeIterator& FileNodeIterator::operator ++ ()
.. ocv:function:: FileNodeIterator FileNodeIterator::operator ++ (int)
FileNodeIterator::operator --
-----------------------------
Moves iterator to the previous node.
.. ocv:function:: FileNodeIterator& FileNodeIterator::operator -- ()
.. ocv:function:: FileNodeIterator FileNodeIterator::operator -- (int)
FileNodeIterator::operator +=
-----------------------------
Moves iterator forward by the specified offset.
.. ocv:function:: FileNodeIterator& FileNodeIterator::operator +=( int ofs )
:param ofs: Offset (possibly negative) to move the iterator.
FileNodeIterator::operator -=
-----------------------------
Moves iterator backward by the specified offset (possibly negative).
.. ocv:function:: FileNodeIterator& FileNodeIterator::operator -=( int ofs )
:param ofs: Offset (possibly negative) to move the iterator.
FileNodeIterator::readRaw
-------------------------
Reads node elements to the buffer with the specified format.
.. ocv:function:: FileNodeIterator& FileNodeIterator::readRaw( const String& fmt, uchar* vec, size_t maxCount=(size_t)INT_MAX )
:param fmt: Specification of each array element. It has the same format as in :ocv:func:`FileStorage::writeRaw`.
:param vec: Pointer to the destination array.
:param maxCount: Number of elements to read. If it is greater than number of remaining elements then all of them will be read.
Usually it is more convenient to use :ocv:func:`operator >>` instead of this method.